branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import itertools
#入力値
input_num = input()
t = 1
counter = 0
result = 0
while (counter < int(input_num)):
head_num = []
tail_num = []
#基の値は2つに分ける
original_t = ((t - 1) / 2)
head_num.append(original_t)
tail_num.append(original_t + 1)
#奇数のみ計算
for num in range(1, int(t) + 1, 2):
#奇数の約数を求める
if t%num == 0:
middle_pos = ((num - 1) / 2) + 1
middle_num = t / num
head_num.append(middle_num - (num - middle_pos))
if head_num[-1] < 0:
#最小がマイナス値の場合は相殺
head_num[-1] = (-1 * head_num[-1]) + 1
#最大値を追加
tail_num.append(middle_num + (num - middle_pos))
#総当りで連続する和の連続の有無を検証
for head, tail in itertools.product(head_num, tail_num):
if head== (tail + 1):
counter+=1
break
t+=1
head_num.clear()
tail_num.clear()
#inputされた値、n番目の連続する整数の和が連続する表現が可能な数
print(t - 1) | 86c89a9176662767117ee04d25a19e660602997a | [
"Python"
] | 1 | Python | k191k/sum_consecutive_integers | e29d280609a6e08d6c377347952f64390d212583 | e85194e31b75112b5e1d4f92246676c6b3b7271d |
refs/heads/master | <file_sep>package com.employee.controller;
import com.employee.model.Admin;
import com.employee.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.persistence.Access;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
private AdminService adminService;
@Autowired
public LoginController(AdminService adminService) {
this.adminService = adminService;
}
// Login form
@GetMapping("/")
public String login(Model model) {
model.addAttribute("admin", new Admin());
return "login";
}
@PostMapping("/login")
public String processLogin(@ModelAttribute Admin admin, HttpSession session) {
if(adminService.verifyLogin(admin)){
session.setAttribute("admin", admin);
return "redirect:/employee";
}
return "redirect:/";
}
}
<file_sep>package com.employee.service.serviceImpl;
import com.employee.model.Attendance;
import com.employee.model.Employee;
import com.employee.repository.AttendanceRepository;
import com.employee.service.AttendanceService;
import com.employee.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AttendanceServiceImpl implements AttendanceService {
private AttendanceRepository attendanceRepository;
private EmployeeService employeeService;
@Autowired
public AttendanceServiceImpl(AttendanceRepository attendanceRepository, EmployeeService employeeService) {
this.attendanceRepository = attendanceRepository;
this.employeeService = employeeService;
}
@Override
public Attendance addEmployeeAttendance(Attendance attendance, Employee employee) {
attendance.setEmployee(employee);
return attendanceRepository.save(attendance);
}
@Override
public List<Attendance> getAttendanceByEmployee(Employee employee) {
return attendanceRepository.findAttendanceByEmployee(employee);
}
}
<file_sep>package com.employee.service;
import com.employee.model.Attendance;
import com.employee.model.Employee;
import java.util.List;
public interface AttendanceService {
Attendance addEmployeeAttendance(Attendance attendance, Employee employee);
List<Attendance> getAttendanceByEmployee(Employee employee);
}
<file_sep>package com.employee.model;
import lombok.*;
import javax.persistence.*;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Employee extends BaseModel {
private String firstName;
private String lastName;
// @Column(unique = true) //two users cannot have the same email
private String email;
private String age;
private String position;
private String salary;
private String leaveStatus;
private String address;
private String phoneNumber;
private String stateOfOrigin;
private String maritalStatus;
private String religion;
private String qualification;
private String yearsOfExperience;
}
<file_sep>package com.employee.service.serviceImpl;
import com.employee.model.Admin;
import com.employee.service.AdminService;
import org.springframework.stereotype.Service;
@Service
public class AdminServiceImpl implements AdminService {
@Override
public Boolean verifyLogin(Admin admin) {
return admin.getUsername().equals("admin") && admin.getPassword().equals("<PASSWORD>");
}
}
| 41ceda272ab2cef9f8aa76033db4f314d2b9c10e | [
"Java"
] | 5 | Java | Etiena821/Employee-Trial1 | 1b48adcd5508bf052949feca6b1dafc03f2edfdb | 863e285ee782d4eb912ffe55c1c6955bb24a1402 |
refs/heads/main | <repo_name>brad0s/react-native-hiit-timer<file_sep>/App/components/Countdown.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import colors from '../constants/colors';
import CircleTimer from './CircleTimer';
export default function Countdown({
countdown,
rounds,
roundCountdown,
roundsCounter,
workoutTime,
restTime,
isWorkoutTime,
cyclesCounter,
cycles,
}) {
const formatTime = (time) => {
const seconds = `0${Math.floor(time % 60)}`.slice(-2);
const minutes = `0${Math.floor((time / 60) % 60)}`.slice(-2);
const timeString = `${minutes}:${seconds}`;
return timeString;
};
return (
<View style={styles.container}>
<View style={styles.metaContainer}>
<Text style={styles.metaTime}>{formatTime(countdown)}</Text>
<Text style={styles.metaTime}>
Cycle {cyclesCounter}/{cycles}
</Text>
<Text style={styles.metaTime}>
Round {roundsCounter % rounds === 0 ? rounds : roundsCounter % rounds}
/{rounds}
</Text>
</View>
<CircleTimer
roundCountdown={roundCountdown}
countdown={countdown}
rounds={rounds}
roundsCounter={roundsCounter}
workoutTime={workoutTime}
restTime={restTime}
isWorkoutTime={isWorkoutTime}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
// marginHorizontal: 50,
// marginTop: 40,
},
metaContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: colors.buttonBackground.gray,
padding: 5,
paddingVertical: 5,
paddingHorizontal: 8,
borderRadius: 5,
},
metaTime: {
fontSize: 18,
color: colors.white,
fontWeight: 'bold',
},
});
<file_sep>/App/screens/Home.js
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, StyleSheet } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import Countdown from '../components/Countdown';
import CountdownButton from '../components/CountdownButton';
import colors from '../constants/colors';
export default function Home() {
const INIT_WORKOUT_TIME = 5;
const INIT_REST_TIME = 5;
const INIT_ROUNDS = 3;
const INIT_CYCLES = 3;
const [workoutTime, setWorkoutTime] = useState(INIT_WORKOUT_TIME);
const [restTime, setRestTime] = useState(INIT_REST_TIME);
const [rounds, setRounds] = useState(INIT_ROUNDS);
const [cycles, setCycles] = useState(INIT_CYCLES);
const [countdown, setCountdown] = useState(
(INIT_WORKOUT_TIME + INIT_REST_TIME) * INIT_ROUNDS * INIT_CYCLES
);
const [roundCountdown, setRoundCountdown] = useState(INIT_WORKOUT_TIME);
const [roundsCounter, setRoundsCounter] = useState(1);
const [cyclesCounter, setCyclesCounter] = useState(1);
const [isWorkoutTime, setIsWorkoutTime] = useState(true);
const [isCountingDown, setIsCountingDown] = useState(false);
useEffect(() => {
if (!countdown) {
return;
}
if (!isCountingDown) {
return;
}
const intervalId = setInterval(() => {
setCountdown(countdown - 1);
setRoundCountdown(roundCountdown - 1);
if (roundCountdown === 0) {
if (isWorkoutTime) {
setIsWorkoutTime(!isWorkoutTime);
setRoundCountdown(restTime - 1);
} else {
setIsWorkoutTime(!isWorkoutTime);
setRoundCountdown(workoutTime - 1);
setRoundsCounter(roundsCounter + 1);
if (roundsCounter % rounds === 0) {
setCyclesCounter(cyclesCounter + 1);
}
}
}
}, 1000);
return () => clearInterval(intervalId);
}, [
countdown,
isCountingDown,
roundCountdown,
roundsCounter,
isWorkoutTime,
workoutTime,
restTime,
rounds,
cyclesCounter,
]);
return (
<SafeAreaView style={styles.container}>
<StatusBar style="light" />
<Countdown
countdown={countdown}
rounds={rounds}
roundCountdown={roundCountdown}
roundsCounter={roundsCounter}
workoutTime={workoutTime}
restTime={restTime}
isWorkoutTime={isWorkoutTime}
cycles={cycles}
cyclesCounter={cyclesCounter}
/>
<View style={styles.buttonsContainer}>
{/* {!isCountingDown && countdown !== (workoutTime + restTime) * rounds && ( */}
<CountdownButton
text="Cancel"
color={colors.white}
backgroundColor={colors.buttonBackground.gray}
disabled={
countdown !== (workoutTime + restTime) * rounds * cycles
? false
: true
}
onPress={() => {
setCountdown((workoutTime + restTime) * rounds * cycles);
setRoundCountdown(workoutTime);
setRoundsCounter(1);
setIsCountingDown(false);
setIsWorkoutTime(true);
setCyclesCounter(1);
}}
/>
{/* )} */}
{!isCountingDown &&
countdown === (workoutTime + restTime) * rounds * cycles && (
<CountdownButton
text="Start"
color={colors.text.green}
backgroundColor={colors.buttonBackground.green}
onPress={() => {
setIsCountingDown(true);
}}
/>
)}
{isCountingDown && (
<CountdownButton
text="Pause"
color={colors.text.yellow}
backgroundColor={colors.buttonBackground.yellow}
onPress={() => {
setIsCountingDown(false);
}}
/>
)}
{!isCountingDown &&
countdown !== (workoutTime + restTime) * rounds * cycles && (
<CountdownButton
text="Resume"
color={colors.text.green}
backgroundColor={colors.buttonBackground.green}
onPress={() => {
setIsCountingDown(true);
}}
/>
)}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.black,
},
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
flex: 1,
},
});
<file_sep>/README.md
# react-native-hiit-timer
<file_sep>/App/constants/colors.js
export default {
text: {
green: 'rgb(100, 199, 99)',
yellow: 'rgb(228, 154, 56)',
red: 'rgb(236, 85, 69)',
gray: 'rgb(153,153,159)',
},
buttonBackground: {
green: 'rgb(19, 41, 20)',
yellow: 'rgb(49,33,7)',
red: 'rgb(47,16,13)',
gray: 'rgb(51,51,51)',
},
black: '#000',
white: '#fff',
gray: 'rgb(117, 117, 117)',
graybg: 'rgb(28, 28, 30)',
};
<file_sep>/App/components/CountdownButton.js
import React from 'react';
import { Pressable, Text, StyleSheet } from 'react-native';
import colors from '../constants/colors';
export default function CountdownButton({
text,
onPress,
color,
backgroundColor,
disabled,
}) {
let textStyle = null;
if (disabled) {
textStyle = [styles.buttonText, { color: colors.text.gray }];
} else {
textStyle = [styles.buttonText, { color }];
}
return (
<Pressable
onPress={onPress}
style={[styles.button, { backgroundColor }]}
disabled={disabled}
>
<Text style={textStyle}>{text}</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
borderWidth: 1,
borderRadius: 100,
margin: 10,
width: 90,
height: 90,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
fontSize: 18,
color: colors.white,
},
});
<file_sep>/App/components/CircleTimer.js
import React from 'react';
import { View, StyleSheet } from 'react-native';
import Svg, { Circle, G, Path, Text } from 'react-native-svg';
import colors from '../constants/colors';
export default function CircleTimer({
roundCountdown,
workoutTime,
restTime,
isWorkoutTime,
}) {
let circleColor = isWorkoutTime
? colors.buttonBackground.green
: colors.buttonBackground.red;
let textColor = isWorkoutTime ? colors.text.green : colors.text.red;
const animateCircle = () => {
let full = null;
if (isWorkoutTime) {
full = workoutTime;
} else {
full = restTime;
}
const rawFraction = roundCountdown / full;
const gradualFraction = rawFraction - (1 / full) * (1 - rawFraction);
const fraction = (gradualFraction * 283).toFixed(0);
return fraction;
};
return (
<View style={styles.container}>
<View style={styles.circleTimer}>
<Svg height="100%" width="100%" viewBox="0 0 100 100">
<G
fill="none"
stroke="none"
style={{ display: 'flex', alignItems: 'center' }}
>
<Text
strokeWidth="0"
fill={textColor}
fontSize="40"
textAnchor="middle"
alignmentBaseline="middle"
x="50"
y="50"
>
{roundCountdown}
</Text>
<Circle
cx="50"
cy="50"
r="45"
strokeWidth="3"
stroke={colors.buttonBackground.gray}
/>
<Path
strokeDasharray={`${animateCircle()} 283`}
d="
M 50, 50
m -45, 0
a 45,45 0 1,0 90,0
a 45,45 0 1,0 -90,0"
strokeWidth="3"
strokeLinecap="round"
// transform="rotate(90deg)"
stroke={circleColor}
style={{ transform: [{ rotateX: '90deg' }] }}
/>
</G>
</Svg>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
circleTimer: {
flex: 1,
// alignItems: 'center',
// justifyContent: 'center',
},
});
| 7bf5a1121630e0bafdf9d52a82254fb0cc28e3bc | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | brad0s/react-native-hiit-timer | 50d38317f0b49936bf4f62ec6a0b4018ca047ebf | ea404540e3d1344c333919e31f0365051dca0f3b |
refs/heads/master | <file_sep><?php
require 'includes/functions.php';
$connection = dbConnect();
// TODO Roep de juiste function aan om de feed op te halen, wat geef je aan deze function?
$feed =getFeedFotos($connection);
// TODO: Gebruik json_encode functie om alles om te zetten naar een json formaat
$json = json_encode($feed);
// Juiste Content-type header sturen naar de client
header( 'Content-type: application/json;charset=utf-8' );
// TODO: Hier de json echo-en
echo $json;
?>
<file_sep>CREATE DATABASE IF NOT EXISTS `fotofeed`;
USE `fotofeed`;
DROP TABLE IF EXISTS `fotos`;
CREATE TABLE `fotos` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`titel` varchar(255) DEFAULT NULL,
`filename` varchar(255) DEFAULT NULL,
`datum` datetime DEFAULT NULL,
`gebruiker_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `fotos` (`id`, `titel`, `filename`, `datum`, `gebruiker_id`)
VALUES
(1,'Covid 19','covid19.jpg','2020-04-12 11:12:00',1),
(2,'Ibizaaaa','ibiza.jpg','2020-02-05 09:45:00',2),
(3,'Ik moet nodig','toilet-paper.jpg','2019-11-23 11:34:00',3),
(4,'Fishy fishy','jellyfish.jpg','2016-04-22 11:57:00',2),
(5,'Summer time','summer-holiday.jpg','2019-08-01 15:29:00',1);
DROP TABLE IF EXISTS `gebruikers`;
CREATE TABLE `gebruikers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`voornaam` varchar(255) DEFAULT NULL,
`achternaam` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`wachtwoord` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `gebruikers` (`id`, `voornaam`, `achternaam`, `username`, `wachtwoord`)
VALUES
(1,'Karel','Klaproos','kareltje111','$2y$10$NSSsEML.vZNnBWhgQvEpm.1.g4cYayeQa5IQvVFuPV5nI/oDOAzl2'),
(2,'Roos','Willemse','r00s','$2y$10$NSSsEML.vZNnBWhgQvEpm.1.g4cYayeQa5IQvVFuPV5nI/oDOAzl2'),
(3,'Vladimir','Poetin','CommandR','$2y$10$NSSsEML.vZNnBWhgQvEpm.1.g4cYayeQa5IQvVFuPV5nI/oDOAzl2');
<file_sep><?php
/**
* Verbinding met de database maken
*
* @return bool|PDO
*/
function dbConnect() {
// Lees het config bestand in en sla de array uit config op in een variabele
$config = require( __DIR__ . '/config.php' );
try {
// Verbinding maken met gebruik van de database instellingen die in de config array zijn opgeslagen
$connection = new PDO( 'mysql:host=' . $config['hostname'] . ';dbname=' . $config['database'], $config['username'], $config['password'] );
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$connection->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
return $connection;
} catch ( PDOException $e ) {
echo $e->getMessage();
}
return false;
}
/**
* Geeft het pad op naar de huidige website
* Daar kun je dan een pad achter plakken zodat je altijd een volledige url krijgt
*/
function getWebsiteBaseUrl() {
/*
$full_path_website = dirname( __DIR__ );
$document_root = $_SERVER['DOCUMENT_ROOT'];
*/
$full_path_website = str_replace( '\\', '/', dirname( __DIR__ ) );
$document_root = $_SERVER['DOCUMENT_ROOT'];
// Pak alleen het pad
$relative_server_path = str_replace( $document_root, '', $full_path_website );
$protocol = 'http://';
if ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ) {
$protocol = 'https://';
}
$host = $_SERVER['HTTP_HOST'];
return $protocol . $host . $relative_server_path;
}
/**
* Haal alle foto's met gebruikers informatie op uit de database
*
* @param PDO $connection
*
* @return array
*/
function getFeedFotos( PDO $connection ) {
try {
// TODO: Maak hier de query die alle foto's ophaalt en gebruik een LEFT JOIN om ook de gebruikers informatie meteen op te halen
// $sql = 'SELECT * FROM fotos';
$sql = 'SELECT fotos.gebruiker_id,fotos.filename, fotos.titel, fotos.datum, gebruikers.username
FROM fotos LEFT JOIN gebruikers
on gebruikers.id = fotos.gebruiker_id LIMIT 4';
$statement = $connection->query( $sql );
//leeg array
$feed = [];
//Haal SQL data op
foreach ( $statement as $foto ) {
// TODO: Probeer de function getBaseUrl() te gebruiken om ook de volledige url naar het plaatje te berekenen
$url = getWebsiteBaseUrl() . '/images/' . $foto['filename'];//filename is de db() tabel
//sla website url bijv: localhost/images/zomervakantie&Leren.jpg
//Maak in de foto array een apparte
$foto['url']=$url;
// TODO: Voeg hier alle rijen toe aan de $feed array
//Sla opgehaalde data op in een array als object!
// TODO Voeg dat toe aan de gegevens van elke foto
$feed[] = $foto;
/*
$rep=" ";
echo
$foto['id'] . $rep.
$foto['titel'] . $rep.
$foto['filename'] . $rep.
$foto['datum'] . $rep.
$foto['gebruiker_id'] . "\n";
*/
}
// De feed array teruggeven
return $feed;
} catch ( PDOException $e ) {
echo 'Fout bij database verbinding:<br>' . $e->getMessage() . ' op regel ' . $e->getLine() . ' in ' . $e->getFile();
exit;
}
}
?><file_sep>#
+ live url: http://30168.hosts2.ma-cloud.nl/bewijzenmap/periode4.4/bap/handOnJson11/
# BAP: Hands-On JSON
Voorbeeldcode aanlsuitend op de lessen van Simon over JSON.
JSON kun je ook genereren in de backend met de PHP function `json_encode`
Je roept dan een PHP script aan wat de JSON genereert en teruggeeft. Ook kun je gegevens in JSON formaat naar de server sturen en met `json_decode` omzetten naar een `array`.
Zo kun je die gegevens weer in een handig formaat omzetten en gebruiken.
## Opdracht: Maak de code werkend zodat de feed wordt ingeladen uit de database (via feed.php)
**Importeer eerst het `fotofeed.sql` bestand**
In de code zitten op een aantal plekken comments met een **TODO**
Dat zijn plekken waar jouw developer skills nodig zijn. Maak de code werkend.
### In de backend
1. Maak de query werkend zodat de juiste gegevens van fotos opgehaald worden
2. Bonus: Gebruik een JOIN SQL statement om ook de gebruikers informatie meteen te koppelen en op te halen
3. Test de feed door feed.php op te vragen in je browser, bekijk de structuur goed
4. Zorg dat wachtwoord NIET wordt opgehaald (tip: SELECT alleen de kolommen die je wilt)
5. In de database staat wel de filename, maar hoe maak je hier een goed werkende url van?
6. Zorg dat in de feed ook de volledige url naar de afbeelding komt (zo kan de afbeelding altijd worden ingeladen)
### In de frontend:
- Zorg dat met de XMLHTTPRequest de juiste url (met de JSON data) wordt ingeladen
- Pas de javascript code aan zodat voor elke foto een DIV met een IMG wordt gemaakt, en dat IMG de juiste src inlaadt uit de feed
- Lees ook andere gegevens uit de JSON en toon deze in de HTML
## Tips
- Bekijk goed wat de feed allemaal voor informatie bevat door `feed.php` op te vragen als je deze werkend hebt
- Gebruik de web inspector om te kijken welke XMLHTTPRequests er verstuurd worden (tabje XHR in web inspector)
- Kijk of de plaatjes goed worden opgevraagd
- Om javascript fouten op te sporen (Console tabje in web inspector)
<file_sep>function handleRequest() {
let jsonData = JSON.parse(this.responseText);
console.log(jsonData);
}
function makeRequest() {
let request = new XMLHttpRequest();
request.addEventListener("load", handleRequest);
request.open("GET", 'data.json', true);
request.send();
}
let button = document.getElementById('jsonbutton');
button.addEventListener('click', makeRequest);<file_sep><?php
// Voorbeeld hoe je een array uit PHP in json kunt omzetten (encoden)
$data = [
'id' => 1,
'naam' => '<NAME>',
'filename' => 'myphoto.jpg'
];
header( 'Content-type: application/json;charset=utf-8' );
echo json_encode($data);
<file_sep>// Ophalen output div om alle foto items aan toe te voegen
let feedOutput = document.getElementById('feed');
// TODO: Haal de json button op met getElementById
let jsonButton=document.getElementById("json-btn");
function createFeedHTML(feed){
// Door elke rij in de feed loopen
for (let i = 0; i < feed.length; i++) {
// De huidige rij ophalen
let fotoInfo = feed[i];
let feedItem = document.createElement('div');
feedItem.className = 'item';
let fotoTitel = document.createElement('h1');
fotoTitel.innerHTML = fotoInfo.titel;
//Op volgorde laat zien: Titel
feedItem.append(fotoTitel);
let fotogebruiker_id = document.createElement('h2');
fotogebruiker_id.innerHTML = fotoInfo.gebruiker_id;
//Op volgorde laat zien: gebruiker_id
feedItem.append(fotogebruiker_id);
let fotoUser = document.createElement('h3');
fotoUser.innerHTML = fotoInfo.username;
//Op volgorde laat zien: gebruikersnaam
feedItem.append(fotoUser);
let fotoDatum = document.createElement('h4');
fotoDatum.innerHTML = fotoInfo.datum;
// TODO: Voeg hier andere informatie van de foto (gebruikersnaam, datum...?)
let fotoImage = document.createElement('img');
// fotoImage.src = "images/"+fotoInfo.filename; // Hier moet natuurlijk de juiste url komen uit de feed
fotoImage.src = fotoInfo.url; // Hier moet natuurlijk de juiste url komen uit de feed
fotoImage.title = fotoInfo.titel;
//Op volgorde laat zien: Foto
feedItem.append(fotoImage);
//Op volgorde laat zien: Datum
feedItem.append(fotoDatum);
//Voeg alles samen
feedOutput.append(feedItem);
}
}
function requestListener() {
//Parse geeft een gestructureerd object terug
let feed = JSON.parse(this.responseText);
// TODO: Roep hier de functie aan die de feed verwerkt
createFeedHTML(feed);
}
function loadFeed() {
let request = new XMLHttpRequest();
// TODO: Zet de juiste url voor de feed hier
//let jsonUrl = fotoImage.src;
//let my_var = <?php echo json_encode($url2);?>
let jsonUrl = "feed.php";
// request.addEventListener("load", handleRequest);
//wanner JSON is geladen, zal het requestListenaar opvragen en die zal wat met JSON doen
request.addEventListener("load", requestListener);
//dit is de url die je gaat opvragen: jsonUrl
request.open("GET", jsonUrl, true);
//en stuur maar op
request.send();
}
// TODO: Zorg dat als je op de jsonButton klikt dat de functie load loadFeed wordt aangeroepen
jsonButton.addEventListener('click', loadFeed);
function handleRequest(){
let jsonData=json.parse(this.responseText);
console.log(jsonData);
} | b8018965ca340ac54ca296930607b6ce5f8bbd32 | [
"Markdown",
"SQL",
"JavaScript",
"PHP"
] | 7 | PHP | LeroyAndrade/L1-p4-11-JSON-JS | 54bbfa527c2714f3bcda182ed6b077488dd53f53 | 38c9abdfb3b1f902d6b7ad82e0211feb8750f743 |
refs/heads/master | <repo_name>KashanMehmood/restraunt-crud<file_sep>/src/App.js
import React from 'react';
import './App.css';
import Home from "./component/Home";
import RestaurantList from "./component/RestaurantList";
import RestaurantMake from "./component/RestaurantMake";
import RestaurantSearch from "./component/RestaurantSearch";
import RestaurantDetail from "./component/RestaurantDetail";
import RestaurantUpdate from "./component/RestaurantUpdate";
import Login from "./component/Login";
import { Navbar, Nav } from 'react-bootstrap';
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faList, faHome, faPlus, faSearch, faSignInAlt } from '@fortawesome/free-solid-svg-icons';
import Logout from './component/Logout';
import Protected from './component/Protected';
function App() {
return (
<div className="App">
<Router>
<div>
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Resto</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
{/* you can also write this */}
{/* <Nav.Link href="/">Home</Nav.Link> */}
<Nav.Link href="/"><FontAwesomeIcon icon={faHome} /> Home</Nav.Link>
<Nav.Link href="/list"><FontAwesomeIcon icon={faList} /> List</Nav.Link>
<Nav.Link href="/create"><FontAwesomeIcon icon={faPlus} /> Add</Nav.Link>
<Nav.Link href="/search"><FontAwesomeIcon icon={faSearch} /> Search</Nav.Link>
{/* <Nav.Link href="/detail"><FontAwesomeIcon icon={faInfoCircle} /> Detail</Nav.Link> */}
{/* <Nav.Link href="/update"><FontAwesomeIcon icon={faPencilAlt} /> Update</Nav.Link> */}
{
localStorage.getItem('login') ?
<Nav.Link href="/logout"><FontAwesomeIcon icon={faSignInAlt} /> Logout</Nav.Link>
:
<Nav.Link href="/login"><FontAwesomeIcon icon={faSignInAlt} /> Login</Nav.Link>
}
</Nav>
</Navbar.Collapse>
</Navbar>
{/* <nav>
<ul>
<li>
<Link to="/" >Home</Link>
</li>
<li>
<Link to="/list">List</Link>
</li>
<li>
<Link to="/create">Create</Link>
</li>
<li>
<Link to="/search">Search</Link>
</li>
<li>
<Link to="/detail">Details</Link>
</li>
<li>
<Link to="/update">Update</Link>
</li>
</ul>
</nav> */}
<Switch>
{/* <Route exact path="/">
<Home />
</Route> */}
<Protected exact path="/" component={Home} />
<Route path="/list">
<RestaurantList />
</Route>
<Route path="/create">
<RestaurantMake />
</Route>
<Route path="/search">
<RestaurantSearch />
</Route>
<Route path="/detail">
<RestaurantDetail />
</Route>
<Route path="/update/:id"
render={(props) => <RestaurantUpdate {...props} />}
>
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/logout">
<Logout />
</Route>
</Switch>
</div>
</Router>
</div>
);
}
export default App;
<file_sep>/src/component/Login.js
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import { Form, Button } from 'react-bootstrap';
class Login extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
};
this.submit = this.submit.bind(this);
}
submit() {
console.log(this.state.email);
console.log(this.state.password);
fetch("http://localhost:3000/login/?email=" + this.state.email + "&password=" + this.state.password)
.then(response => response.json())
.then((responseJson) => {
if (responseJson.length === 1) {
localStorage.setItem('login', JSON.stringify(responseJson));
this.props.history.push('/list');
} else {
alert("Your email or passwor is incorrect");
}
})
.catch(error => console.log(error)) //to catch the errors if any
}
render() {
return (
<div className="container">
<div className="row">
<div className="offset-md-3 col-md-6">
<Form>
<Form.Group align="left" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control onChange={(e) => { this.setState({ email: e.target.value }) }} type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group align="left" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control onChange={(e) => { this.setState({ password: e.target.value }) }} type="password" placeholder="<PASSWORD>" />
</Form.Group>
<Form.Group align="left" controlId="formBasicCheckbox">
<Button variant="primary" type="button" onClick={this.submit}>Submit</Button>
</Form.Group>
</Form>
</div>
</div>
</div>
);
}
}
export default withRouter(Login);
// export default Login;<file_sep>/src/component/RestaurantUpdate.js
import React, { Component } from 'react';
class RestaurantUpdate extends Component {
constructor() {
super();
this.state = {
id: "",
name: "",
address: "",
rating: "",
email: ""
};
this.submit = this.submit.bind(this);
}
componentDidMount() {
fetch("http://localhost:3000/restaurant/" + this.props.match.params.id)
.then(response => response.json())
.then((responseJson) => {
this.setState({
id: responseJson.id,
name: responseJson.name,
address: responseJson.address,
rating: responseJson.rating,
email: responseJson.email
})
console.log(responseJson)
})
.catch(error => console.log(error)) //to catch the errors if any
}
submit() {
console.log(this.state);
fetch("http://localhost:3000/restaurant/"+this.state.id, {
method: "PUT",
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(this.state)
})
.then(response => response.json())
.then((responseJson) => {
alert("Restaurant Updated");
})
.catch(error => console.log(error)) //to catch the errors if any
}
render() {
// console.log(this.state.name);
return (
<div>
RestaurantUpdate Component
<br />
<input type="text" value={this.state.name} onChange={(e) => { this.setState({ name: e.target.value }) }}
placeholder="Name"
/> <br />
<input type="text" value={this.state.address} onChange={(e) => { this.setState({ address: e.target.value }) }}
placeholder="Address"
/><br />
<input type="text" value={this.state.rating} onChange={(e) => { this.setState({ rating: e.target.value }) }}
placeholder="Rating"
/><br />
<input type="text" value={this.state.email} onChange={(e) => { this.setState({ email: e.target.value }) }}
placeholder="Email"
/><br />
{/* <br />
<input type="text" value={this.state.name} onChange={(e) => { this.setState({ name: e.target.value }) }}
placeholder="Name"
/> <br />
<input type="text" value={this.state.address} onChange={(e) => { this.setState({ address: e.target.value }) }}
placeholder="Address"
/><br />
<input type="text" value={this.state.rating} onChange={(e) => { this.setState({ rating: e.target.value }) }}
placeholder="Rating"
/><br />
<input type="text" value={this.state.email} onChange={(e) => { this.setState({ email: e.target.value }) }}
placeholder="Email"
/><br /> */}
<button type="button" onClick={this.submit}>Submit</button>
</div>
);
}
}
export default RestaurantUpdate;<file_sep>/README.md
Tutorial Play list
https://www.youtube.com/playlist?list=PL8p2I9GklV46FX2Uik_rVlbN_nSx0Wc43
1. npm install -g json-server.(https://github.com/typicode/json-server)
1. mkdir db (create a db folder).
2. create a file db.json and create api object.
3. run command
json-server --watch db/db.json
2. Install Bootstrap
1. npm install react-bootstrap bootstrap
2. add line in index.js
import 'bootstrap/dist/css/bootstrap.min.css
3. Add Font Awsome Icon
1. npm i --save @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome
4. Protected Route
https://codedaily.io/tutorials/49/Create-a-ProtectedRoute-for-Logged-In-Users-with-Route-Redirect-and-a-Render-Prop-in-React-Router <file_sep>/src/component/RestaurantMake.js
import React, { Component } from 'react';
import { Form, Button, InputGroup, FormControl } from 'react-bootstrap';
class RestaurantMake extends Component {
constructor() {
super();
this.state = {
id: "",
name: "",
address: "",
rating: "",
email: ""
};
this.submit = this.submit.bind(this);
}
submit() {
fetch("http://localhost:3000/restaurant", {
method: "POST",
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(this.state)
})
.then(response => response.json())
.then((responseJson) => {
this.setState({
name: "",
address: "",
rating: "",
email: ""
})
alert("Restaurant added");
})
.catch(error => console.log(error)) //to catch the errors if any
}
render() {
return (
<div className="container">
<div className="row">
<div className="offset-md-3 col-md-6">
<Form>
<Form.Group align="left" controlId="formBasicEmail">
<Form.Label>Name</Form.Label>
<Form.Control value={this.state.name} onChange={(e) => { this.setState({ name: e.target.value }) }} type="text" placeholder="Enter Name" />
</Form.Group>
<Form.Group align="left" controlId="formBasicEmail">
<Form.Label>Email</Form.Label>
<Form.Control value={this.state.email} onChange={(e) => { this.setState({ email: e.target.value }) }} type="email" placeholder="Enter Email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group align="left" controlId="formBasicEmail">
<Form.Label>Address</Form.Label>
<InputGroup>
<FormControl value={this.state.address} onChange={(e) => { this.setState({ address: e.target.value }) }} as="textarea" placeholder="Enter Address" aria-label="With textarea" />
</InputGroup>
</Form.Group>
<Form.Group align="left" controlId="formBasicPassword">
<Form.Label>Rating</Form.Label>
<Form.Control value={this.state.rating} onChange={(e) => { this.setState({ rating: e.target.value }) }} type="text" placeholder="Enter Rating" />
</Form.Group>
<Form.Group align="left" controlId="formBasicCheckbox">
<Button variant="primary" type="button" onClick={this.submit}>Add</Button>
</Form.Group>
</Form>
</div>
</div>
</div>
);
}
}
export default RestaurantMake; | aa04a37ad50cd8fd89f872ae745c55f5e8892ff7 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | KashanMehmood/restraunt-crud | ee5b56960abbadf62fe802c22323a9c523146189 | 795f02d2d156f7d07bfa1d02c958b349ed5cac08 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn trường</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_2.php");
?>
<div class="main1">
<h2>
Lưu ý: <a href="index.php">HoTroTuyenSinh.com</a> chỉ đưa ra được gợi ý chọn trường khi thí sinh đã chọn ngành!
</h2>
<p style="font-size: 11px;">
<i>Thí sinh có thể yêu cầu <a href="index.php">HoTroTuyenSinh.com</a> đưa ra gợi ý chọn trường ngay cả khi thí sinh không yêu cầu <a href="index.php">HoTroTuyenSinh.com</a> đưa ra gợi ý chọn ngành.<br>Nhưng khi đó, thí sinh phải chuẩn bị sẵn 1 mã Ngành, Nhóm ngành từ trước.</i>
</p>
<br>
<p>
Gợi ý chọn trường được đưa ra dựa trên 7 tiêu chí sau:
</p>
<ol>
<li><b>Ranking của trường:</b> là thứ hạng của trường trong bảng xếp hạng các trường.</li>
<li><b>Số chỉ tiêu:</b> là số chỉ tiêu tuyển sinh nhóm ngành đã được gợi ý tại trường.</li>
<li><b>Chênh lệch điểm chuẩn:</b> là mức độ chênh lệch điểm mà thí sinh đạt được so với điểm ngưỡng của trường.</li>
<li><b>Khả năng tìm việc:</b> là khả năng tốt nghiệp xong có việc làm luôn khi theo học tại trường.</li>
<li><b>Khoảng cách:</b> là khoảng cách về địa lý giữa nơi thường trú của thí sinh đến trường học.</li>
<li><b>Học phí:</b> là khoản phí trung bình mỗi thí sinh phải bỏ ra nếu theo học tại trường.</li>
<li><b>Môi trường học tập:</b> là đánh giá của các sinh viên hiện đang theo học tại trường về môi trường học tập của trường đó.</li>
</ol>
<br>
<p>
Để có thể đưa ra gợi ý chọn trường, <a href="index.php">HoTroTuyenSinh.com</a> muốn biết:
</p>
<form name="suggest2"
action="suggest2_result.php"
method="POST"
>
<br>
<hr>
<h2>
Bước 1: Đánh giá mức độ quan trọng của các tiêu chí chọn trường.
</h2>
<?php
include("weight_2.php");
?>
<br>
<hr>
<h2>
Bước 2: Cung cấp Tên Ngành đã chọn.
</h2>
Tên Ngành:
<input type="text" name="ten_nganh_da_chon" placeholder="Nhập Tên Ngành đã chọn" style="width: 400px;" required><br><br>
<br>
<hr>
<h2>
Bước 3: Cung cấp kết quả thi.
</h2>
Kết quả thi môn 1:
<input type="number" step="0.01" name="mon_1" min="0" max="10" required><br><br>
Kết quả thi môn 2:
<input type="number" step="0.01" id="ToanHoc" name="mon_2" min="0" max="10" required><br><br>
Kết quả thi môn 3:
<input type="number" step="0.01" id="ToanHoc" name="mon_3" min="0" max="10" required><br><br>
Tổng điểm cộng:
<input type="number" step="0.01" id="ToanHoc" name="mon_4" min="0" max="10" required><br><br>
<br>
<hr>
<h2>
Bước 4: Cung cấp địa chỉ thường trú.
</h2>
Địa chỉ thường trú:
<input type="text" name="address" placeholder="Nhập địa chỉ thường trú của thí sinh" style="width: 400px;" required><br><br>
<br>
<hr>
<h2>
Bước 5: Xem kết quả gợi ý chọn trường.
</h2>
<input type="submit" name="view_result" value="Xem kết quả gợi ý" onclick="locdau()">
</form>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn Ngành</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_1.php");
?>
<div class="main1">
<p>
Các gợi ý được đưa ra dựa trên 3 tiêu chí sau:
</p>
<ol>
<li>Mức độ yêu thích cúa thí sinh đối với từng Khối ngành, Lĩnh vực đào tạo, Nhóm ngành, Ngành.</li>
<li>Năng lực bản thân của thí sinh.</li>
<li>Số chỉ tiêu đã quy định của từng Khối ngành, Lĩnh vực đào tạo, Nhóm ngành, Ngành. (Số chỉ tiêu này đã bao gồm cả số chỉ tiêu tuyển thằng).</li>
</ol>
<br>
<h2>Bước 4: Gợi ý chọn Ngành</h2>
<p>
<a href="index.php">HoTroTuyenSinh.com</a> muốn biết:<br><br>
</p>
<?php
include("atribute_1_4_1.php");
include("view_result.php");
?>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Máy chủ: 127.0.0.1
-- Thời gian đã tạo: Th6 04, 2018 lúc 11:15 AM
-- Phiên bản máy phục vụ: 10.1.31-MariaDB
-- Phiên bản PHP: 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Cơ sở dữ liệu: `recommendation`
--
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `admin`
--
CREATE TABLE `admin` (
`ID` int(1) NOT NULL,
`admin_name` varchar(10) NOT NULL,
`admin_password` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `admin`
--
INSERT INTO `admin` (`ID`, `admin_name`, `admin_password`) VALUES
(1, 'admin', <PASSWORD>);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `fuzzy_set`
--
CREATE TABLE `fuzzy_set` (
`ID` int(10) NOT NULL,
`Bien_Ngon_Ngu` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`a1` float NOT NULL,
`b1` float NOT NULL,
`c1` float NOT NULL,
`d1` float NOT NULL,
`h11` float NOT NULL,
`h12` float NOT NULL,
`a2` float NOT NULL,
`b2` float NOT NULL,
`c2` float NOT NULL,
`d2` float NOT NULL,
`h21` float NOT NULL,
`h22` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `fuzzy_set`
--
INSERT INTO `fuzzy_set` (`ID`, `Bien_Ngon_Ngu`, `a1`, `b1`, `c1`, `d1`, `h11`, `h12`, `a2`, `b2`, `c2`, `d2`, `h21`, `h22`) VALUES
(1, 'cuc_ky_thich', 0.8, 0.9, 1, 1, 1, 1, 0.85, 0.93, 1, 1, 0.8, 0.8),
(2, 'rat_thich', 0.6, 0.7, 0.9, 1, 1, 1, 0.65, 0.73, 0.87, 0.95, 0.8, 0.8),
(3, 'yeu_thich', 0.4, 0.5, 0.7, 0.8, 1, 1, 0.45, 0.53, 0.67, 0.75, 0.8, 0.8),
(4, 'binh_thuong', 0.2, 0.3, 0.5, 0.6, 1, 1, 0.25, 0.33, 0.47, 0.55, 0.8, 0.8),
(5, 'khong_thich', 0, 0.1, 0.3, 0.4, 1, 1, 0.05, 0.13, 0.27, 0.35, 0.8, 0.8),
(6, 'rat_khong_thich', 0, 0, 0.1, 0.2, 1, 1, 0, 0, 0.05, 0.15, 0.8, 0.8);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `khoi_nganh`
--
CREATE TABLE `khoi_nganh` (
`Khoi_Nganh_ID` int(11) NOT NULL,
`Ten_Khoi_Nganh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`So_Chi_Tieu` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `khoi_nganh`
--
INSERT INTO `khoi_nganh` (`Khoi_Nganh_ID`, `Ten_Khoi_Nganh`, `So_Chi_Tieu`) VALUES
(1, 'Khối ngành I', 0),
(2, 'Khối ngành II', 0),
(3, 'Khối ngành III', 0),
(4, 'Khối ngành IV', 0),
(5, 'Khối ngành V', 0),
(6, 'Khối ngành VI', 0),
(7, 'Khối ngành VII', 0);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `khoi_thi`
--
CREATE TABLE `khoi_thi` (
`Khoi_Thi_ID` int(11) NOT NULL,
`Ma_Khoi_Thi_BGD` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Mon_Thi_1` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Mon_Thi_2` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Mon_Thi_3` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `khoi_thi`
--
INSERT INTO `khoi_thi` (`Khoi_Thi_ID`, `Ma_Khoi_Thi_BGD`, `Mon_Thi_1`, `Mon_Thi_2`, `Mon_Thi_3`) VALUES
(1, 'A00', 'Toán Học', 'Vật Lí', 'Hóa Học'),
(2, 'A01', 'Toán Học', 'Vật Lí', 'Tiếng Anh'),
(3, 'B00', 'Toán Học', 'Hóa Học', 'Sinh Học'),
(4, 'C00', 'Ngữ Văn', 'Lịch Sử', 'Địa Lý'),
(5, 'D01', 'Ngữ Văn', 'Toán Học', 'Tiếng Anh'),
(6, 'D02', 'Ngữ Văn', 'Toán Học', 'Tiếng Nga'),
(7, 'D03', 'Ngữ Văn', 'Toán Học', 'Tiếng Pháp'),
(8, 'D04', 'Ngữ Văn', 'Toán Học', 'Tiếng Trung'),
(9, 'D05', 'Ngữ Văn', 'Toán Học', 'Tiếng Đức'),
(10, 'D06', 'Ngữ Văn', 'Toán Học', 'Lịch Sử'),
(11, 'A02', 'Toán Học', 'Vật Lí', 'Sinh Học'),
(12, 'A03', 'Toán Học', 'Vật Lí', 'Lịch Sử'),
(13, 'A04', 'Toán Học', 'Vật Lí', 'Địa Lý'),
(14, 'A05', 'Toán Học', 'Hóa Học', 'Lịch Sử'),
(15, 'A06', 'Toán Học', 'Hóa Học', 'Địa Lý'),
(16, 'A07', 'Toán Học', 'Lịch Sử', 'Địa Lý'),
(17, 'A08', 'Toán Học', 'Lịch Sử', 'Giáo Dục Công Dân'),
(18, 'A09', 'Toán Học', 'Địa Lý', 'Giáo Dục Công Dân'),
(19, 'A10', 'Toán Học', 'Vật Lí', 'Giáo Dục Công Dân'),
(20, 'A11', 'Toán Học', 'Hóa Học', 'Giáo Dục Công Dân'),
(21, 'A12', 'Toán Học', 'Khoa Học Tự Nhiên', 'Khoa Học Xã Hội'),
(22, 'A14', 'Toán Học', 'Khoa Học Tự Nhiên', 'Địa Lý'),
(23, 'A15', 'Toán Học', 'Khoa Học Tự Nhiên', 'Lịch Sử'),
(24, 'A16', 'Toán Học', 'Khoa Học Tự Nhiên', 'Ngữ Văn'),
(25, 'A17', 'Toán Học', 'Vật Lí', 'Khoa Học Xã Hội'),
(26, 'A18', 'Toán Học', 'Hóa Học', 'Khoa Học Xã Hội'),
(27, 'B01', 'Toán Học', 'Sinh Học', 'Lịch Sử'),
(28, 'B02', 'Toán Học', 'Sinh Học', 'Địa Lý'),
(29, 'B03', 'Toán Học', 'Sinh Học', 'Ngữ Văn'),
(30, 'B04', 'Toán Học', 'Sinh Học', 'Giáo Dục Công Dân'),
(31, 'B05', 'Toán Học', 'Sinh Học', 'Khoa Học Xã Hội'),
(32, 'B08', 'Toán Học', 'Sinh Học', 'Tiếng Anh'),
(33, 'C01', 'Ngữ Văn', 'Toán Học', 'Vật Lí'),
(34, 'C02', 'Ngữ Văn', 'Toán Học', 'Hóa Học'),
(35, 'C03', 'Ngữ Văn', 'Toán Học', 'Lịch Sử'),
(36, 'C04', 'Ngữ Văn', 'Toán Học', 'Địa Lý'),
(37, 'C05', 'Ngữ Văn', 'Vật Lí', 'Hóa Học'),
(38, 'C06', 'Ngữ Văn', 'Vật Lí', 'Sinh Học'),
(39, 'C07', 'Ngữ Văn', 'Vật Lí', 'Lịch Sử'),
(40, 'C08', 'Ngữ Văn', 'Hóa Học', 'Sinh Học'),
(41, 'C09', 'Ngữ Văn', 'Vật Lí', 'Địa Lý'),
(42, 'C10', 'Ngữ Văn', 'Hóa Học', 'Lịch Sử'),
(43, 'C12', 'Ngữ Văn', 'Sinh Học', 'Lịch Sử'),
(44, 'C13', 'Ngữ Văn', 'Sinh Học', 'Địa Lý'),
(45, 'C14', 'Ngữ Văn', 'Toán Học', 'Giáo Dục Công Dân'),
(46, 'C16', 'Ngữ Văn', 'Vật Lí', 'Giáo Dục Công Dân'),
(47, 'C17', 'Ngữ Văn', 'Hóa Học', 'Giáo Dục Công Dân'),
(48, 'C19', 'Ngữ Văn', 'Lịch Sử', 'Giáo Dục Công Dân'),
(49, 'C20', 'Ngữ Văn', 'Địa Lý', 'Giáo Dục Công Dân'),
(50, 'D07', 'Toán Học', 'Hóa Học', 'Tiếng Anh'),
(51, 'D08', 'Toán Học', 'Sinh Học', 'Tiếng Anh'),
(52, 'D09', 'Toán Học', 'Lịch Sử', 'Tiếng Anh'),
(53, 'D10', 'Toán Học', 'Địa Lý', 'Tiếng Anh'),
(54, 'D11', 'Ngữ Văn', 'Vật Lí', 'Tiếng Anh'),
(55, 'D12', 'Ngữ Văn', 'Hóa Học', 'Tiếng Anh'),
(56, 'D13', 'Ngữ Văn', 'Sinh Học', 'Tiếng Anh'),
(57, 'D14', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Anh'),
(58, 'D15', 'Ngữ Văn', 'Địa Lý', 'Tiếng Anh'),
(59, 'D16', 'Toán Học', 'Địa Lý', 'Tiếng Đức'),
(60, 'D17', 'Toán Học', 'Địa Lý', 'Tiếng Nga'),
(61, 'D18', 'Toán Học', 'Địa Lý', 'Tiếng Nhật'),
(62, 'D19', 'Toán Học', 'Địa Lý', 'Tiếng Pháp'),
(63, 'D20', 'Toán Học', 'Địa Lý', 'Tiếng Trung'),
(64, 'D21', 'Toán Học', 'Hóa Học', 'Tiếng Đức'),
(65, 'D22', 'Toán Học', 'Hóa Học', 'Tiếng Nga'),
(66, 'D23', 'Toán Học', 'Hóa Học', 'Tiếng Nhật'),
(67, 'D24', 'Toán Học', 'Hóa Học', 'Tiếng Pháp'),
(68, 'D25', 'Toán Học', 'Hóa Học', 'Tiếng Trung'),
(69, 'D26', 'Toán Học', 'Vật Lí', 'Tiếng Đức'),
(70, 'D27', 'Toán Học', 'Vật Lí', 'Tiếng Nga'),
(71, 'D28', 'Toán Học', 'Vật Lí', 'Tiếng Nhật'),
(72, 'D29', 'Toán Học', 'Vật Lí', 'Tiếng Pháp'),
(73, 'D30', 'Toán Học', 'Vật Lí', 'Tiếng Trung'),
(74, 'D31', 'Toán Học', 'Sinh Học', 'Tiếng Đức'),
(75, 'D32', 'Toán Học', 'Sinh Học', 'Tiếng Nga'),
(76, 'D33', 'Toán Học', 'Sinh Học', 'Tiếng Nhật'),
(77, 'D34', 'Toán Học', 'Sinh Học', 'Tiếng Pháp'),
(78, 'D35', 'Toán Học', 'Sinh Học', 'Tiếng Trung'),
(79, 'D41', 'Ngữ Văn', 'Địa Lý', 'Tiếng Đức'),
(80, 'D42', 'Ngữ Văn', 'Địa Lý', 'Tiếng Nga'),
(81, 'D43', 'Ngữ Văn', 'Địa Lý', 'Tiếng Nhật'),
(82, 'D44', 'Ngữ Văn', 'Địa Lý', 'Tiếng Pháp'),
(83, 'D45', 'Ngữ Văn', 'Địa Lý', 'Tiếng Trung'),
(84, 'D52', 'Ngữ Văn', 'Vật Lí', 'Tiếng Nga'),
(85, 'D54', 'Ngữ Văn', 'Vật Lí', 'Tiếng Pháp'),
(86, 'D55', 'Ngữ Văn', 'Vật Lí', 'Tiếng Trung'),
(87, 'D61', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Đức'),
(88, 'D62', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Nga'),
(89, 'D63', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Nhật'),
(90, 'D64', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Pháp'),
(91, 'D65', 'Ngữ Văn', 'Lịch Sử', 'Tiếng Trung'),
(92, 'D66', 'Ngữ Văn', 'Giáo Dục Công Dân', 'Tiếng Anh'),
(93, 'D68', 'Ngữ Văn', 'Giáo Dục Công Dân', 'Tiếng Nga'),
(94, 'D69', 'Ngữ Văn', 'Giáo Dục Công Dân', 'Tiếng Nhật'),
(95, 'D70', 'Ngữ Văn', 'Giáo Dục Công Dân', 'Tiếng Pháp'),
(96, 'D72', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Anh'),
(97, 'D73', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Đức'),
(98, 'D74', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Nga'),
(99, 'D75', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Nhật'),
(100, 'D76', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Pháp'),
(101, 'D77', 'Ngữ Văn', 'Khoa Học Tự Nhiên', 'Tiếng Trung'),
(102, 'D78', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Anh'),
(103, 'D79', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Đức'),
(104, 'D80', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Nga'),
(105, 'D81', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Nhật'),
(106, 'D82', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Pháp'),
(107, 'D83', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Tiếng Trung'),
(108, 'D84', 'Toán Học', 'Giáo Dục Công Dân', 'Tiếng Anh'),
(109, 'D85', 'Toán Học', 'Giáo Dục Công Dân', 'Tiếng Đức'),
(110, 'D86', 'Toán Học', 'Giáo Dục Công Dân', 'Tiếng Nga'),
(111, 'D87', 'Toán Học', 'Giáo Dục Công Dân', 'Tiếng Pháp'),
(112, 'D88', 'Toán Học', 'Giáo Dục Công Dân', 'Tiếng Nhật'),
(113, 'D90', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Anh'),
(114, 'D91', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Pháp'),
(115, 'D92', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Đức'),
(116, 'D93', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Nga'),
(117, 'D94', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Nhật'),
(118, 'D95', 'Toán Học', 'Khoa Học Tự Nhiên', 'Tiếng Trung'),
(119, 'D96', 'Toán Học', 'Khoa Học Xã Hội', 'Tiếng Anh'),
(120, 'D97', 'Toán Học', 'Khoa Học Xã Hội', 'Tiếng Pháp'),
(121, 'D98', 'Toán Học', 'Khoa Học Xã Hội', 'Tiếng Đức'),
(122, 'D99', 'Toán Học', 'Khoa Học Xã Hội', 'Tiếng Nga'),
(123, 'H00', 'Ngữ Văn', 'Năng Khiếu Vẽ Nghệ Thuật 1', 'Năng Khiếu Vẽ Nghệ Thuật 2'),
(124, 'H01', 'Toán Học', 'Ngữ Văn', 'Vữ'),
(125, 'H02', 'Toán học', 'Vẽ Hình Họa Mỹ Thuật', 'Vẽ Trang Trí Màu'),
(126, 'H03', 'Toán Học', 'Khoa Học Tự Nhiên', 'Vẽ Năng Khiếu'),
(127, 'H04', 'Toán Học', 'Tiếng Anh', 'Vẽ Năng Khiếu'),
(128, 'H05', 'Ngữ Văn', 'Khoa Học Xã Hội', 'Vẽ Năng Khiếu'),
(129, 'H06', 'Ngữ Văn', 'Tiếng Anh', 'Vẽ Mỹ Thuật'),
(130, 'H07', 'Toán Học', 'Hình Họa', 'Trang Trí'),
(131, 'H08', 'Ngữ Văn', 'Lịch Sử', 'Vẽ Mỹ Thuật'),
(132, 'K01', 'Toán Học', 'Tiếng Anh', 'Tin Học'),
(133, 'M00', 'Ngữ Văn', 'Toán Học', 'Đọc Diễn Cảm - Hát'),
(134, 'M01', 'Ngữ Văn', 'Lịch Sử', 'Năng Khiếu'),
(135, 'M02', 'Toán Học', 'Năng Khiếu 1', 'Năng Khiếu 2'),
(136, 'M03', 'Ngữ Văn', 'Năng Khiếu 1', 'Năng Khiếu 2'),
(137, 'M04', 'Toán Học', 'Đọc Diễn Cảm', 'Hát - Múa'),
(138, 'M09', 'Toán Học', 'Năng Khiếu Mầm Non 1', 'Năng Khiếu Mầm Non 2'),
(139, 'M10', 'Toán Học', 'Tiếng Anh', 'Năng Khiếu 1'),
(140, 'M11', 'Ngữ Văn', 'Năng Khiếu Báo Chí', 'Tiếng Anh'),
(141, 'M13', 'Toán Học', 'Sinh Học', 'Năng Khiếu'),
(142, 'M14', 'Ngữ Văn', 'Năng Khiếu Báo Chí', 'Toán Học'),
(143, 'M15', 'Ngữ Văn', 'Năng Khiếu Báo Chí', 'Tiếng Anh'),
(144, 'M16', 'Ngữ Văn', 'Năng Khiếu Báo Chí', 'Vật Lí'),
(145, 'M17', 'Ngữ Văn', 'Năng Khiếu Báo Chí', 'Lích Sử'),
(146, 'M18', 'Ngữ Văn', 'Năng Khiếu Ảnh Báo Chí', 'Toán Học'),
(147, 'M19', 'Ngữ Văn', 'Năng Khiếu Ảnh Báo Chí', 'Tiếng Anh'),
(148, 'M20', 'Ngữ Văn', 'Năng Khiếu Ảnh Báo Chí', 'Vật Lí'),
(149, 'M21', 'Ngữ Văn', 'Năng Khiếu Ảnh Báo Chí', 'Lịch Sử'),
(150, 'M22', 'Ngữ Văn', 'Năng Khiếu Quay Phim Truyền Hình', 'Toán Học'),
(151, 'M23', 'Ngữ Văn', 'Năng Khiếu Quay Phim Truyền Hình', 'Tiếng Anh'),
(152, 'M24', 'Ngữ Văn', 'Năng Khiếu Quay Phim Truyền Hình', 'Vật Lí'),
(153, 'M25', 'Ngữ Văn', 'Năng Khiếu Quay Phim Truyền Hình', 'Lích Sử'),
(154, 'N00', 'Ngữ Văn', 'Năng Khiếu Âm Nhạc 1', 'Năng Khiếu Âm Nhạc 2'),
(155, 'N01', 'Ngữ Văn', 'Xướng Âm', 'Biểu Diễn Nghệ Thuật'),
(156, 'N02', 'Ngữ Văn', 'Ký Xướng Âm', 'Hát Hoặc Biểu Diễn Nhạc Cụ'),
(157, 'N03', 'Ngữ Văn', 'Ghi Âm - Xướng Âm', 'Chuyên Môn'),
(158, 'N04', 'Ngữ Văn', 'Năng Khiếu Thuyết Trình', 'Năng Khiếu'),
(159, 'N05', 'Ngữ Văn', 'Xây Dựng Kích Bản Sự Kiện', 'Năng Khiếu'),
(160, 'N08', 'Ngữ Văn', 'Hòa Thanh', 'Phát Triển Chủ Đề Và Pgổ Thơ'),
(161, 'N09', 'Ngữ Văn', 'Hòa Thanh', 'Chỉ Huy Tại Chỗ'),
(162, 'R00', 'Ngữ Văn', 'Lích Sử', 'Năng Khiếu Báo Chí'),
(163, 'R01', 'Ngữ Văn', 'Địa Lý', 'Năng Khiếu Biểu Diễn Nghệ Thuật'),
(164, 'R02', 'Ngữ Văn', 'Toán Học', 'Năng Khiếu Biểu Diễn Nghệ Thuật'),
(165, 'R04', 'Ngữ Văn', 'Năng Khiếu Biểu Diễn Nghệ Thuật', 'Năng khiếu Kiến thức Văn Hóa - Xã Hội - Nghệ Thuật'),
(166, 'R05', 'Ngữ Văn', 'Tiếng Anh', 'Năng Khiếu Kiến Thức Truyền Thông'),
(167, 'S00', 'Ngữ Văn', 'Năng Khiếu Sân Khấu Điện Ảnh 1', 'Năng Khiếu Sân Khấu Điện Ảnh 2'),
(168, 'S01', 'Toán Học', 'Năng Khiếu 1', 'Năng Khiếu 2'),
(169, 'T00', 'Toán Học', 'Sinh Học', 'Năng Khiếu Thể Dục Thể Thao'),
(170, 'T01', 'Toán Học', 'Ngữ Văn', 'Năng Khiếu Thể Dục Thể Thao'),
(171, 'T02', 'Ngữ Văn', 'Sinh Học', 'Năng Khiếu Thể Dục Thể Thao'),
(172, 'T03', 'Ngữ Văn', 'Địa Lý', 'Năng Khiếu Thể Dục Thể Thao'),
(173, 'T04', 'Toán Học', 'Vật Lí', 'Năng Khiếu Thể Dục Thể Thao'),
(174, 'T05', 'Ngữ Văn', 'Giáo Dục Công Dân', 'Năng Khiếu'),
(175, 'V00', 'Toán Học', 'Vật Lí', 'Vẽ Hình Họa Mỹ Thuật'),
(176, 'V01', 'Toán Học', 'Ngữ Văn', 'Vẽ Hình Họa Mỹ Thuật'),
(177, 'V02', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Anh'),
(178, 'V03', 'Vẽ Mỹ Thuật', 'Toán Học', 'Hóa Học'),
(179, 'V04', 'Vẽ Mỹ Thuật', 'Ngữ Văn', 'Vật Lí'),
(180, 'V06', 'Vẽ Mỹ Thuật', 'Toán Học', 'Địa Lý'),
(181, 'V07', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Đức'),
(182, 'V08', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Nga'),
(183, 'V09', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Nhật'),
(184, 'V10', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Pháp'),
(185, 'V11', 'Vẽ Mỹ Thuật', 'Toán Học', 'Tiếng Trung');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `linh_vuc_dao_tao`
--
CREATE TABLE `linh_vuc_dao_tao` (
`Linh_Vuc_Dao_Tao_ID` int(11) NOT NULL,
`Ma_Linh_Vuc_Dao_Tao` int(11) NOT NULL,
`Ten_Linh_Vuc_Dao_Tao` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`So_Chi_Tieu_Linh_Vuc_Dao_Tao` int(11) NOT NULL,
`Khoi_Nganh_ID` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `linh_vuc_dao_tao`
--
INSERT INTO `linh_vuc_dao_tao` (`Linh_Vuc_Dao_Tao_ID`, `Ma_Linh_Vuc_Dao_Tao`, `Ten_Linh_Vuc_Dao_Tao`, `So_Chi_Tieu_Linh_Vuc_Dao_Tao`, `Khoi_Nganh_ID`) VALUES
(1, 714, 'Khoa học giáo dục và đào tạo giáo viên', 0, 1),
(2, 721, 'Nghệ thuật', 0, 2),
(3, 722, 'Nhân văn', 0, 7),
(4, 731, 'Khoa học xã hội và hành vi', 0, 7),
(5, 732, 'Báo chí và thông tin', 0, 7),
(6, 734, 'Kinh doanh và quản lý', 0, 3),
(7, 742, 'Khoa học sự sống', 0, 4),
(8, 744, 'Khoa học tự nhiên', 0, 4),
(9, 746, 'Toán và thống kê', 0, 5),
(10, 748, 'Máy tính và công nghệ thông tin', 0, 5),
(11, 751, 'công nghệ kỹ thuật', 0, 5),
(12, 752, 'Kỹ thuật', 0, 5),
(13, 754, 'Sản xuất và chế biến', 0, 5),
(14, 758, 'Kiến trúc và xây dựng', 0, 5),
(15, 762, 'Nông, lâm nghiệp và thủy sản', 0, 5),
(16, 764, 'Thú y', 0, 5),
(17, 772, 'Sức khỏe', 0, 6),
(18, 776, 'Dịch vụ xã hội', 0, 7),
(19, 781, 'Du lịch, khách sạn, thể thao và dịch vụ cá nhân', 0, 7),
(20, 784, 'Dịch vụ vận tải', 0, 7),
(21, 785, 'Môi trường và bảo vệ môi trường', 0, 7),
(22, 786, 'An ninh, Quốc phòng', 0, 7);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `nganh`
--
CREATE TABLE `nganh` (
`Nganh_ID` int(11) NOT NULL,
`Ma_Nganh_BGD` int(11) NOT NULL,
`Ten_Nganh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Nhom_Nganh_ID` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `nganh`
--
INSERT INTO `nganh` (`Nganh_ID`, `Ma_Nganh_BGD`, `Ten_Nganh`, `Nhom_Nganh_ID`) VALUES
(1, 7140101, 'Giáo dục học', 1),
(2, 7140114, 'Quản lý giáo dục', 1),
(3, 7140201, 'Giáo dục Mầm non', 2),
(4, 7140202, 'Giáo dục Tiểu học', 2),
(5, 7140203, 'Giáo dục Đặc biệt', 2),
(6, 7140204, 'Giáo dục Công dân', 2),
(7, 7140205, 'Giáo dục Chính trị', 2),
(8, 7140206, 'Giáo dục Thể chất', 2),
(9, 7140207, 'Huấn luyện thể thao', 2),
(10, 7140208, 'Giáo dục Quốc phòng - An ninh', 2),
(11, 7140209, 'Sư phạm Toán học', 2),
(12, 7140210, 'Sư phạm Tin học', 2),
(13, 7140211, 'Sư phạm Vật Lý', 2),
(14, 7140212, 'Sư phạm Hóa học', 2),
(15, 7140213, 'Sư phạm Sinh học', 2),
(16, 7140214, '<NAME>m Kỹ thuật công nghiệp', 2),
(17, 7140215, 'S<NAME>ạm Kỹ thuật nông nghiệp', 2),
(18, 7140217, '<NAME> Ng<NAME>', 2),
(19, 7140218, '<NAME> Lịch sử', 2),
(20, 7140219, '<NAME> Địa lý', 2),
(21, 7140221, '<NAME>', 2),
(22, 7140222, '<NAME>', 2),
(23, 7140223, '<NAME>', 2),
(24, 7140224, '<NAME>', 2),
(25, 7140225, '<NAME>', 2),
(26, 7140226, '<NAME>', 2),
(27, 7140227, '<NAME>', 2),
(28, 7140228, '<NAME>', 2),
(29, 7140229, '<NAME>', 2),
(30, 7140230, '<NAME>', 2),
(31, 7140231, '<NAME>', 2),
(32, 7140232, '<NAME>', 2),
(33, 7140233, 'Sư phạm Tiếng Pháp', 2),
(34, 7140234, 'Sư phạm Tiếng Trung Quốc', 2),
(35, 7140235, 'Sư phạm Tiếng Đức', 2),
(36, 7140236, 'Sư phạm Tiếng Nhật', 2),
(37, 7140237, 'Sư phạm Tiếng Hàn Quốc', 2),
(38, 7140245, 'Sư phạm Nghệ thuật', 2),
(39, 7140246, 'Sư phạm Công nghệ', 2),
(40, 7140247, 'Sư phạm Khoa học tự nhiên', 2),
(41, 7140248, '<NAME> luật', 2),
(42, 7210101, 'Lý luận, lịch sử và phê bình mỹ thuật', 4),
(43, 7210103, 'Hội họa', 4),
(44, 7210104, 'Đồ họa', 4),
(45, 7210105, 'Điêu khắc', 4),
(46, 7210107, 'Gốm', 4),
(47, 7210110, 'Mỹ thuật đô thị', 4),
(48, 7210201, 'Âm nhạc học', 5),
(49, 7210203, 'Sáng tác âm nhạc', 5),
(50, 7210204, '<NAME>', 5),
(51, 7210205, '<NAME>', 5),
(52, 7210207, 'Biểu diễn nhạc cụ phương Tây', 5),
(53, 7210208, 'Piano', 5),
(54, 7210209, 'Nhạc Jazz', 5),
(55, 7210210, 'Biểu diễn nhạc cụ truyền thống', 5),
(56, 7210221, 'Lý luận, lịch sử và phê bình sân khấu', 5),
(57, 7210225, 'Biên kịch sân khấu', 5),
(58, 7210226, 'Diễn viên sân khấu kịch hát', 5),
(59, 7210227, 'Đạo diễn sân khấu', 5),
(60, 7210231, 'Lý luận, lịch sử và phê bình điện ảnh, truyền hình', 5),
(61, 7210233, 'Biên kịch điện ảnh, truyền hình', 5),
(62, 7210234, 'Diễn viên kịch, điện ảnh, truyền hình', 5),
(63, 7210235, 'Đạo diễn điện ảnh, truyền hình', 5),
(64, 7210236, 'Quay phim', 5),
(65, 7210241, 'Lý luận, lịch sử và phê bình múa', 5),
(66, 7210242, 'Diễn viên múa', 5),
(67, 7210243, 'Biên đạo múa', 5),
(68, 7210244, 'Huấn luyện múa', 5),
(69, 7210301, 'Nhiếp ảnh', 6),
(70, 7210302, 'Công nghệ điện ảnh, truyền hình', 6),
(71, 7210303, 'Thiết kế âm thanh, ash sáng', 6),
(72, 7210402, 'Thiết kế công nghiệp', 7),
(73, 7210403, 'Thiết kế đồ họa', 7),
(74, 7210404, 'Thiết kế thời trang', 7),
(75, 7210406, 'Thiết kế mỹ thuật sân khấu điện ảnh', 7),
(76, 7220101, 'Tiếng Việt và văn hóa Việt Nam', 9),
(77, 7220104, '<NAME>', 9),
(78, 7220105, 'Ngôn ngữ Jrai', 9),
(79, 7220106, 'Ngôn ngữ Khmer', 9),
(80, 7220107, 'Ngôn ngữ Hmông', 9),
(81, 7220108, 'Ngôn ngữ Chăm', 9),
(82, 7220110, 'Sáng tác văn học', 9),
(83, 7220112, 'Văn hóa các dân tọc thiểu số Việt Nam', 9),
(84, 7220201, 'Ngôn ngữ Anh', 10),
(85, 7220202, 'Ngôn ngữ Nga', 10),
(86, 7220203, 'Ngôn ngữ Pháp', 10),
(87, 7220204, 'Ngôn ngữ Trung Quốc', 10),
(88, 7220205, 'Ngôn ngữ Đức', 10),
(89, 7220206, 'Ngôn ngữ Tây Ban Nha', 10),
(90, 7220207, 'Ngôn ngữ Bồ Đào Nha', 10),
(91, 7220208, 'Ngôn ngữ Italia', 10),
(92, 7220209, 'Ngôn ngữ Nhật', 10),
(93, 7220210, 'Ngôn ngữ Hàn Quốc', 10),
(94, 7220211, 'Ngôn ngữ Ả Rập', 10),
(95, 7229001, 'Triết học', 11),
(96, 7229008, 'Chủ nghĩa xã hội khoa học', 11),
(97, 7229009, 'Tôn giáo học', 11),
(98, 7229010, 'Lịch sử', 11),
(99, 7229020, 'Ngôn ngữ học', 11),
(100, 7229030, 'Văn học', 11),
(101, 7229040, 'Văn hóa học', 11),
(102, 7229042, 'Quản lý văn hóa', 11),
(103, 7229045, 'Gia đình học', 11),
(104, 7310101, 'Kinh tế', 12),
(105, 7310102, 'Kinh tế chính trị', 12),
(106, 7310104, 'Kinh tế đầu tư', 12),
(107, 7310105, 'Kinh tế phát triển', 12),
(108, 7310106, 'Kinh tế quốc tế', 12),
(109, 7310107, 'Thống kê kinh tế', 12),
(110, 7310108, 'Toán kinh tế', 12),
(111, 7310201, 'Chính trị học', 13),
(112, 7310202, 'X<NAME> và chính quyền Nhà nước', 13),
(113, 7310205, 'Quản lý nhà nước', 13),
(114, 7310206, 'Quan hệ quốc tế', 13),
(115, 7310301, 'Xã hội học', 14),
(116, 7310302, 'Nhân học', 14),
(117, 7310401, 'Tâm lý học', 15),
(118, 7310402, 'Tâm lý học giáo dục', 15),
(119, 7310501, 'Địa lý học', 16),
(120, 7310601, 'Quốc tế học', 17),
(121, 7310602, 'Châu Á học', 17),
(122, 7310607, 'Thái Bình Dương học', 17),
(123, 7310608, 'Đông phương học', 17),
(124, 7310612, 'Trung Quốc học', 17),
(125, 7310613, 'Nhật Bản học', 17),
(126, 7310614, 'Hàn Quốc học', 17),
(127, 7310620, 'Đông Nam Á học', 17),
(128, 7310630, 'Việt Nam học', 17),
(129, 7320101, 'Báo chí', 19),
(130, 7320104, 'Truyền thông đa phương tiện', 19),
(131, 7320105, 'Truyền thông đại chúng', 19),
(132, 7320106, 'Công nghệ truyền thông', 19),
(133, 7320107, 'Truyền thông quốc tế', 19),
(134, 7320108, 'Quan hệ công chúng', 19),
(135, 7320201, 'Thông tin - Thư viện', 20),
(136, 7320205, 'Quản lý thông tin', 20),
(137, 7320303, 'Lưu trữ học', 21),
(138, 7320305, 'Bảo tàng học', 21),
(139, 7320401, 'Xuất bản', 22),
(140, 7320402, 'Kinh doanh xuất bản phẩm', 22),
(141, 7340101, 'Quản trị kinh doanh', 24),
(142, 7340115, 'Marketing', 24),
(143, 7340116, '<NAME>', 24),
(144, 7340120, 'Kinh doanh quốc tế', 24),
(145, 7340121, 'Kinh doanh thương mại', 24),
(146, 7340122, 'Thương mại điện tử', 24),
(147, 7340123, 'Kinh doanh thời trang và dệt may', 24),
(148, 7340201, '<NAME> - <NAME>', 25),
(149, 7340204, 'Bảo hiểm', 25),
(150, 7340301, 'Kế toán', 26),
(151, 7340302, '<NAME>', 26),
(152, 7340401, 'Khoa học quản lý', 27),
(153, 7340403, 'Quản lý công', 27),
(154, 7340404, 'Quản trị nhân lực', 27),
(155, 7340405, 'Hệ thống thông tin quản lý', 27),
(156, 7340406, 'Quản trị văn phòng', 27),
(157, 7340408, 'Quan hệ lao động', 27),
(158, 7340409, 'Quản lý dự án', 27),
(159, 7380101, 'Luật', 29),
(160, 7380102, 'Luật Hiến pháp và luật Hành chính', 29),
(161, 7380103, 'Luật dân sự và tố tụng dân sự', 29),
(162, 7380104, 'Luật hình sự và tố tụng hình sự', 29),
(163, 7380107, '<NAME>', 29),
(164, 7380108, '<NAME>ốc tế', 29),
(165, 7420101, 'Sinh học', 31),
(166, 7420201, 'Công nghệ sinh học', 32),
(167, 7420202, 'Kỹ thuật sinh học', 32),
(168, 7420203, 'Sinh học ứng dụng', 32),
(169, 7440101, 'Thiên văn học', 34),
(170, 7440102, 'Vật lý học', 34),
(171, 7440106, 'Vật lý nguyên tử và hạt nhân', 34),
(172, 7440110, 'Cơ học', 34),
(173, 7440112, 'Hóa học', 34),
(174, 7440122, 'Khoa học vật liệu', 34),
(175, 7440201, 'Địa chất học', 35),
(176, 7440212, 'Bản đồ học', 35),
(177, 7440217, 'Địa lý tự nhiên', 35),
(178, 7440221, 'Khí tượng và khí hậu học', 35),
(179, 7440224, 'Thủy văn học', 35),
(180, 7440228, 'Hải dương học', 35),
(181, 7440301, 'Khoa học môi trường', 36),
(182, 7460101, 'Toán học', 38),
(183, 7460107, 'Khoa học tính toán', 38),
(184, 7460112, 'Toán ứng dụng', 38),
(185, 7460115, 'Toán cơ', 38),
(186, 7460117, 'Toán tin', 38),
(187, 7460201, 'Thống kê', 39),
(188, 7480101, 'Khoa học máy tính', 41),
(189, 7480102, 'Mạng máy tính và truyền thông dữ liệu', 41),
(190, 7480103, 'Kỹ thuật phần mềm', 41),
(191, 7480104, 'Hệ thống thông tin', 41),
(192, 7480106, 'Kỹ thuật máy tính', 41),
(193, 7480108, 'Công nghệ kỹ thuật máy tính', 41),
(194, 7480201, 'Công nghệ thông tin', 42),
(195, 7480202, 'An toàn thông tin', 42),
(196, 7510101, 'Công nghệ kỹ thuật kiến trúc', 44),
(197, 7510102, 'Công nghệ kỹ thuật công trình xây dựng', 44),
(198, 7510103, 'Công nghệ kỹ thuật xây dựng', 44),
(199, 7510104, 'Công nghệ kỹ thuật giao thông', 44),
(200, 7510105, 'Công nghệ kỹ thuật vật liệu xây dựng', 44),
(201, 7510201, 'Công nghệ kỹ thuật cơ khí', 45),
(202, 7510202, 'Công nghệ chế tạo máy', 45),
(203, 7510203, 'Công nghệ kỹ thuật cơ điện tử', 45),
(204, 7510205, 'Công nghệ kỹ thuật ô tô', 45),
(205, 7510206, 'Công nghệ kỹ thuật nhiệt', 45),
(206, 7510207, 'Công nghệ kỹ thuật tàu thủy', 45),
(207, 7510211, 'Bảo dưỡng công nghiệp', 45),
(208, 7510301, 'Công nghệ kỹ thuật điện, điện tử', 46),
(209, 7510302, 'Công nghệ kỹ thuật điện tử - viễn thông', 46),
(210, 7510303, 'Công nghệ kỹ thuật điều khiển và tự động hóa', 46),
(211, 7510401, 'Công nghệ kỹ thuật hóa học', 47),
(212, 7510402, 'Công nghệ vật liệu', 47),
(213, 7510406, 'Công nghệ kỹ thuật môi trường', 47),
(214, 7510407, 'Công nghệ kỹ thuật hạt nhân', 47),
(215, 7510601, 'Quản lý công nghiệp', 48),
(216, 7510604, 'Kinh tế công nghiệp', 48),
(217, 7510605, 'Logistics và Quản lý chuỗi cung ứng', 48),
(218, 7510701, 'Công nghệ dầu khí và khai thác dầu', 49),
(219, 7510801, 'Công nghệ kỹ thuật in', 50),
(220, 7520101, 'Cơ kỹ thuật', 52),
(221, 7520103, 'Kỹ thuật cơ khí', 52),
(222, 7520114, 'Kỹ thuật cơ điện tử', 52),
(223, 7520115, 'Kỹ thuật nhiệt', 52),
(224, 7520116, 'Kỹ thuật cơ khí động lực', 52),
(225, 7520117, 'Kỹ thuật công nghiệp', 52),
(226, 7520118, 'Kỹ thuật hệ thống công nghiệp', 52),
(227, 7520120, 'Kỹ thuật hàng không', 52),
(228, 7520121, 'Kỹ thuật không gian', 52),
(229, 7520122, 'Kỹ thuật tàu thủy', 52),
(230, 7520130, 'Kỹ thuật ô tô', 52),
(231, 7520137, 'Kỹ thuật in', 52),
(232, 7520201, 'Kỹ thuật điện', 53),
(233, 7520204, 'Kỹ thuật ra-đa dẫn đường', 53),
(234, 7520205, 'Kỹ thuật thủy âm', 53),
(235, 7520206, 'Kỹ thuật biển', 53),
(236, 7520207, 'Kỹ thuật điện tử - viễn thông', 53),
(237, 7520212, 'Kỹ thuật y sinh', 53),
(238, 7520216, 'Kỹ thuật điều khiển và tự động hóa', 53),
(239, 7520301, 'Kỹ thuật hóa học', 54),
(240, 7520309, 'Kỹ thuật vật liệu', 54),
(241, 7520310, 'Kỹ thuật vật liệu kim loại', 54),
(242, 7520312, 'Kỹ thuật dệt', 54),
(243, 7520320, 'Kỹ thuật môi trường', 54),
(244, 7520401, 'Vật lý kỹ thuật', 55),
(245, 7520402, 'Kỹ thuật hạt nhân', 55),
(246, 7520501, 'Kỹ thuật địa chất', 56),
(247, 7520502, 'Kỹ thuật địa vật lý', 56),
(248, 7520503, 'Kỹ thuật trắc địa - bản đồ', 56),
(249, 7520601, 'Kỹ thuật mỏ', 57),
(250, 7520602, 'Kỹ thuật thăm dò và khảo sát', 57),
(251, 7520604, 'Kỹ thuật dầu khí', 57),
(252, 7520607, 'Kỹ thuật tuyển khoáng', 57),
(253, 7540101, 'Công nghệ thực phẩm', 59),
(254, 7540102, 'Kỹ thuật thực phẩm', 59),
(255, 7540104, 'Công nghệ sau thu hoạch', 59),
(256, 7540105, 'Công nghệ chế biến thủy sản', 59),
(257, 7540106, 'Đảm bảo chất lượng và an toàn thực phẩm', 59),
(258, 7540202, 'Công nghệ sợi, dệt', 60),
(259, 7540203, 'Công nghệ vật liệu dệt, may', 60),
(260, 7540204, 'Công nghệ dệt, may', 60),
(261, 7540206, 'Công nghệ da giày', 60),
(262, 7549001, 'Công nghệ chế biến lâm sản', 61),
(263, 7580101, 'Kiến trúc', 62),
(264, 7580102, 'Kiến trúc cảnh quan', 62),
(265, 7580103, 'Kiến trúc nội thất', 62),
(266, 7580104, 'Kiến trúc đô thị', 62),
(267, 7580105, 'Quy hoạch vùng và đô thị', 62),
(268, 7580106, 'Quản lý đô thị và cong trình', 62),
(269, 7580108, 'Thiết kế nội thất', 62),
(270, 7580111, 'Bảo tồn di sản kiến trúc đô thị', 62),
(271, 7580112, 'Đô thị học', 62),
(272, 7580201, 'Kỹ thuật xây dựng', 63),
(273, 7580202, 'Kỹ thuật xây dựng công trình thủy', 63),
(274, 7580203, 'Kỹ thuật xây dựng công trình biển', 63),
(275, 7580205, 'Kỹ thuật xây dựng công trình giao thông', 63),
(276, 7580210, 'Kỹ thuật cơ sở hạ tầng', 63),
(277, 7580211, 'Địa kỹ thuật xây dựng', 63),
(278, 7580212, 'Kỹ thuật tài nguyên nước', 63),
(279, 7580213, 'Kỹ thuật cấp thoát nước', 63),
(280, 7580301, 'Kinh tế xây dựng', 64),
(281, 7580302, 'Quản lý xây dựng', 64),
(282, 7620101, 'Nông nghiệp', 66),
(283, 7620102, 'Khuyến nông', 66),
(284, 7620103, 'Khoa học đất', 66),
(285, 7620105, 'Chăn nuôi', 66),
(286, 7620109, 'Nông học', 66),
(287, 7620110, 'Khoa học cây trồng', 66),
(288, 7620112, 'Bảo vệ thực vật', 66),
(289, 7620113, 'Công nghệ rau hoa quả và cảnh quan', 66),
(290, 7620114, 'Kinh doanh nông nghiệp', 66),
(291, 7620115, 'Kinh tế nông nghiệp', 66),
(292, 7620116, 'Phát triển nông thôn', 66),
(293, 7620201, 'Lâm học', 67),
(294, 7620202, 'Lâm nghiệp đô thị', 67),
(295, 7620205, 'Lâm sinh', 67),
(296, 7620211, 'Quản lý tài nguyên rừng', 67),
(297, 7620301, 'Nuôi trồng thủy sản', 68),
(298, 7620302, 'Bệnh học thủy sản', 68),
(299, 7620303, 'Khoa học thủy sản', 68),
(300, 7620304, 'Khai thác thủy sản', 68),
(301, 7620305, 'Quản lý thủy sản', 68),
(302, 7640404, 'Thú y', 70),
(303, 7720101, 'Y khoa', 71),
(304, 7720110, 'Y học dự phòng', 71),
(305, 7720115, 'Y học cổ truyền', 71),
(306, 7720201, 'Dược học', 72),
(307, 7720203, 'Hóa dược', 72),
(308, 7720301, 'Điều dưỡng', 73),
(309, 7720302, 'Hộ sinh', 73),
(310, 7720401, 'Dinh dưỡng', 74),
(311, 7720501, 'Răng - Hàm - Mặt', 75),
(312, 7720502, 'Kỹ thuật phục hình răng', 75),
(313, 7720601, 'Kỹ thuật xét nghiệm Y học', 76),
(314, 7720602, 'Kỹ thuật hình ảnh Y học', 76),
(315, 7720603, 'Kỹ thuật hồi phục chức năng', 76),
(316, 7720701, 'Y tế công cộng', 77),
(317, 7720801, 'Tổ chức và quản lý y tế', 78),
(318, 7720802, 'Quản lý bệnh viện', 78),
(319, 7729001, 'Y học thể dục thể thao', 79),
(321, 7760101, 'Công tác xã hội', 80),
(322, 7760102, 'Công tác thanh thiếu niên', 80),
(323, 7760103, 'Hỗ trợ giáo dục người khuyết tật', 80),
(324, 7810101, 'Du lịch', 82),
(325, 7810103, 'Quản trị dịch vụ du lịch và lữ hành', 82),
(326, 7810201, 'Quản trị khách sạn', 83),
(327, 7810202, 'Quản trị nhà hàng và dịch vụ ăn uống', 83),
(328, 7810301, 'Quản lỹ thể dục thể thao', 84),
(329, 7810501, 'Kinh tế gia đình', 85),
(330, 7840101, '<NAME>', 87),
(331, 7840102, 'Quản lý hoạt động bay', 87),
(332, 7840104, 'Kinh tế vậ<NAME>', 87),
(333, 7840106, 'Khoa h<NAME>', 87),
(334, 7850101, 'Quản lý tài nguyên và môi trường', 89),
(335, 7850102, 'Kinh tế tài nguyên thiên nhiên', 89),
(336, 7850103, 'Quản lý đất đai', 89),
(337, 7850201, 'Bảo hộ lao động', 90),
(338, 7860101, 'Trinh sát an ninh', 92),
(339, 7860102, 'Trinh sát cảnh sát', 92),
(340, 7860104, 'Điều tra hình sự', 92),
(341, 7860108, '<NAME>', 92),
(342, 7860109, 'Quản lý nhà nước về an ninh trật tự', 92),
(343, 7860110, 'Quản lý trật tự an toàn giao thông', 92),
(344, 7860111, 'Thi hành án hình sự và hỗ trợ tư pháp', 92),
(345, 7860112, 'Tham mưu, chỉ huy công an nhân dân', 92),
(346, 7860113, 'Phòng cháy chữa cháy và cứu nạn cứu hộ', 92),
(347, 7860116, 'Hậu cần công an nhân dân', 92),
(348, 7860117, 'Tình báo an ninh', 92),
(349, 7860201, 'Chỉ huy tham mưu Lục quân', 93),
(350, 7860202, 'Chỉ huy tham mưu Hải quân', 93),
(351, 7860203, 'Chỉ huy tham mưu Không quân', 93),
(352, 7860204, 'Chỉ huy tham mưu Phòng không', 93),
(353, 7860205, 'Chỉ huy tham mưu Pháo binh', 93),
(354, 7860206, 'Chỉ huy tham mưu Thăng - Thiết giáp', 93),
(355, 7860207, 'Chỉ huy tham mưu Đặc công', 93),
(356, 7860214, 'Biên phòng', 93),
(357, 7860217, 'Tình báo quân sự', 93),
(358, 7860218, 'Hậu cần quân sự', 93),
(359, 7860220, 'Chỉ huy tham mưu thông tin', 93),
(360, 7860222, 'Quân sự cơ sở', 93),
(361, 7860224, 'Chỉ huy quản lý kỹ thuật', 93),
(362, 7860226, 'Chỉ huy Kỹ thuật phòng không', 93),
(363, 7860227, 'Chỉ huy kỹ thuật Tăng thiết giáp', 93),
(364, 7860228, 'Chỉ huy kỹ thuật Công binh', 93),
(365, 7860229, 'Chỉ huy kỹ thuật Hóa học', 93),
(366, 7860231, 'Trinh sát kỹ thuật', 93),
(367, 7860232, 'Chỉ huy kỹ thuật Hải quân', 93),
(368, 7860233, 'Chỉ huy kỹ thuật tác chiến điện tử', 93);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `nhom_nganh`
--
CREATE TABLE `nhom_nganh` (
`Nhom_Nganh_ID` int(11) NOT NULL,
`Ma_Nhom_Nganh_BGD` int(11) NOT NULL,
`Ten_Nhom_Nganh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`So_Chi_Tieu_Nhom_Nganh` int(11) NOT NULL,
`Linh_Vuc_Dao_Tao_ID` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `nhom_nganh`
--
INSERT INTO `nhom_nganh` (`Nhom_Nganh_ID`, `Ma_Nhom_Nganh_BGD`, `Ten_Nhom_Nganh`, `So_Chi_Tieu_Nhom_Nganh`, `Linh_Vuc_Dao_Tao_ID`) VALUES
(1, 71401, 'Khoa học giáo dục', 0, 1),
(2, 71402, 'Đào tạo giáo viên', 0, 1),
(3, 71490, 'Khác', 0, 1),
(4, 72101, 'Mỹ thuật', 0, 2),
(5, 72102, 'Nghệ thuật trình diễn', 0, 2),
(6, 72103, 'Nghệ thuật nghe nhìn', 0, 2),
(7, 72104, 'Mỹ thuật ứng dụng', 0, 2),
(8, 72190, 'Khác', 0, 2),
(9, 72201, 'Ngôn ngữ, văn học và văn hóa Việt Nam', 0, 3),
(10, 72202, 'Ngôn ngữ, văn học và văn hóa nước ngoài', 0, 3),
(11, 72290, 'Khác', 0, 3),
(12, 73101, 'Kinh tế học', 0, 4),
(13, 73102, 'Khoa học chính trị', 0, 4),
(14, 73103, 'Xã hội học và Nhân học', 0, 4),
(15, 73104, 'Tâm lý học', 0, 4),
(16, 73105, 'Địa lý học', 0, 4),
(17, 73106, 'Khu vực học', 0, 4),
(18, 73190, 'Khác', 0, 4),
(19, 73201, 'Báo chí và truyền thông', 0, 5),
(20, 73202, 'Thông tin - Thư viện', 0, 5),
(21, 73203, 'Văn thư - Lưu trữ - Bảo tàng', 0, 5),
(22, 73204, 'Xuất bản - Phát hành', 0, 5),
(23, 73290, 'Khác', 0, 5),
(24, 73401, '<NAME>', 0, 6),
(25, 73402, 'Tài chính - Ngân hàng - Bảo hiểm', 0, 6),
(26, 73403, 'Kế toán - Kiểm toán', 0, 6),
(27, 73404, 'Quản trị - Quản lý', 0, 6),
(28, 73490, 'Khác', 0, 6),
(29, 73801, 'Luật', 0, 7),
(30, 73890, 'Khác', 0, 7),
(31, 74201, 'Sinh học', 0, 8),
(32, 74202, 'Sinh học ứng dụng', 0, 8),
(33, 74290, 'Khác', 0, 8),
(34, 74401, 'Khoa học vật chất', 0, 9),
(35, 74402, 'Khoa học trái đất', 0, 9),
(36, 74403, 'Khoa học môi trường', 0, 9),
(37, 74490, 'Khác', 0, 9),
(38, 74601, 'Toán học', 0, 10),
(39, 74602, 'Thống kê', 0, 10),
(40, 74690, 'Khác', 0, 10),
(41, 74801, 'Máy tính', 0, 11),
(42, 74802, 'Công nghệ thông tin', 0, 11),
(43, 74890, 'Khác', 0, 11),
(44, 75101, 'Công nghệ kỹ thuật kiến trúc và công trình xây dựng', 0, 11),
(45, 75102, 'Công nghệ kỹ thuật cơ khí', 0, 11),
(46, 75103, 'Công nghệ kỹ thuật điện, điện tử và viễn thông', 0, 11),
(47, 75104, 'Công nghệ hóa học, vật liệu, luyện kim và môi trường', 0, 11),
(48, 75106, 'Quản lý công nghiệp', 0, 11),
(49, 75107, 'Công nghệ dầu khí và khai thác', 0, 11),
(50, 75108, 'Công nghệ kỹ thuật in', 0, 11),
(51, 75190, 'Khác', 0, 11),
(52, 75201, 'Kỹ thuật cơ khí và cơ kỹ thuật', 0, 12),
(53, 75202, 'Kỹ thuật điện, điện tử và viễn thông', 0, 12),
(54, 75203, 'Kỹ thuật hóa học, vật liệu, luyện kim và môi trường', 0, 12),
(55, 75204, 'Vật lý kỹ thuật', 0, 12),
(56, 75205, 'Kỹ thuật địa chất, địa vật lý và trắc địa', 0, 12),
(57, 75206, 'Kỹ thuật mỏ', 0, 12),
(58, 75290, 'Khác', 0, 12),
(59, 75401, 'Chế biến lương thực, thực phẩm và đồ uống', 0, 13),
(60, 75402, 'Sản xuất, chế biến sợi, vải, giày, da', 0, 13),
(61, 75490, 'Khác', 0, 13),
(62, 75801, 'Kiến trúc và quy hoạch', 0, 14),
(63, 75802, 'Xây dựng', 0, 14),
(64, 75803, 'Quản lý xây dựng', 0, 14),
(65, 75890, 'Khác', 0, 14),
(66, 76201, 'Nông nghiệp', 0, 15),
(67, 76202, 'Lâm nghiệp', 0, 15),
(68, 76203, 'Thủy sản', 0, 15),
(69, 76290, 'Khác', 0, 15),
(70, 76401, 'Thú y', 0, 16),
(71, 77201, 'Y học', 0, 17),
(72, 77202, 'Dược học', 0, 17),
(73, 77203, 'Điều dưỡng - Hộ sinh', 0, 17),
(74, 77204, 'Dinh dưỡng', 0, 17),
(75, 77205, 'Răng - Hàm - Mặt (Nha khoa)', 0, 17),
(76, 77206, 'Kỹ thuật Y học', 0, 17),
(77, 77207, 'Y tế công cộng', 0, 17),
(78, 77208, 'Quản lý Y tế', 0, 17),
(79, 77290, 'Khác', 0, 17),
(80, 77601, 'Công tác xã hội', 0, 18),
(81, 77690, 'Khác', 0, 18),
(82, 78101, 'Du lịch', 0, 19),
(83, 78102, 'Khách sạn, nhà hàng', 0, 19),
(84, 78103, 'Thể dục thể thao', 0, 19),
(85, 78105, 'Kinh tế gia đình', 0, 19),
(86, 78190, 'Khác', 0, 19),
(87, 78401, '<NAME>', 0, 20),
(88, 78490, 'Khác', 0, 20),
(89, 78501, 'Quản lý tài nguyên môi trường', 0, 21),
(90, 78502, 'Dịch vụ an toàn lao động và vệ sinh công nghiệp', 0, 21),
(91, 78590, 'Khác', 0, 21),
(92, 78601, 'An ninh và trật tự xã hội', 0, 22),
(93, 78602, '<NAME>', 0, 22),
(94, 78690, 'Khác', 0, 22);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `thuoc_tinh_bai_toan_1`
--
CREATE TABLE `thuoc_tinh_bai_toan_1` (
`ID` int(5) NOT NULL,
`Ten_Thuoc_Tinh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `thuoc_tinh_bai_toan_1`
--
INSERT INTO `thuoc_tinh_bai_toan_1` (`ID`, `Ten_Thuoc_Tinh`) VALUES
(1, 'Năng lực bản thân'),
(2, 'Mức độ yêu thích'),
(3, 'Số chỉ tiêu');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `thuoc_tinh_bai_toan_2`
--
CREATE TABLE `thuoc_tinh_bai_toan_2` (
`ID` int(11) NOT NULL,
`Ten_Thuoc_Tinh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `thuoc_tinh_bai_toan_2`
--
INSERT INTO `thuoc_tinh_bai_toan_2` (`ID`, `Ten_Thuoc_Tinh`) VALUES
(1, 'Ranking của trường'),
(2, 'Số chỉ tiêu'),
(3, 'Điểm chuẩn'),
(4, 'Khả năng tìm việc'),
(5, 'Khoảng cách'),
(6, 'Học phí'),
(7, 'Môi trường học tập');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `to_chuc_dao_tao`
--
CREATE TABLE `to_chuc_dao_tao` (
`To_Chuc_Dao_Tao_ID` int(11) NOT NULL,
`Ma_To_Chuc_Dao_Tao` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Ten_To_Chuc_Dao_Tao` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Logo` varchar(255) NOT NULL,
`Website` varchar(255) NOT NULL,
`Thong_Tin_Tuyen_Sinh` varchar(255) NOT NULL,
`Rankiing` int(11) NOT NULL,
`Vi_Tri` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `to_chuc_dao_tao`
--
INSERT INTO `to_chuc_dao_tao` (`To_Chuc_Dao_Tao_ID`, `Ma_To_Chuc_Dao_Tao`, `Ten_To_Chuc_Dao_Tao`, `Logo`, `Website`, `Thong_Tin_Tuyen_Sinh`, `Rankiing`, `Vi_Tri`) VALUES
(1, 'BKA', 'Đại học Bách Khoa Hà Nội', 'img/bkhnlogo.jpg', 'https://www.hust.edu.vn/', 'http://tuyensinhdaihoc.hust.edu.vn/', 1, 'Số 1 Đại Cồ Việt, Hai Bà Trưng, Hà Nội'),
(2, 'QH', 'Đại học Quốc gia Hà Nội', 'img/dhqghnlogo.jpg', 'http://www.vnu.edu.vn/home/', 'http://tuyensinh.vnu.edu.vn/', 2, ''),
(3, 'SPH', 'Đại học Sư phạm Hà Nội', 'img/dhsphnlogo.jpg', 'http://hnue.edu.vn/', 'http://hnue.edu.vn/Tintuc-Sukien/Trangtintonghop/tabid/260/category/61/Default.aspx', 3, ''),
(4, 'TCT', 'Đại học Cần Thơ', 'img/dhctlogo.jpg', 'https://www.ctu.edu.vn/', 'https://tuyensinh.ctu.edu.vn/', 4, 'Khu II, đường 3/2, <NAME>, <NAME>, TP. Cần Thơ.'),
(5, 'QS', 'Đại học Quốc Gia Thành Phố Hồ Chí Minh', 'img/dhqgtphcmlogo.jpg', 'http://www.vnuhcm.edu.vn/', 'http://tuyensinh.vnuhcm.edu.vn/', 5, ''),
(6, 'HVN', 'Học viện Nông Nghiệp Việt Nam', 'img/hvnnvnlogo.jpg', 'http://www.vnua.edu.vn/', 'http://tuyensinh.vnua.edu.vn/', 6, ''),
(7, 'MDA', 'Đại học Mỏ - Địa Chất', 'img/dhmdclogo.jpg', 'http://humg.edu.vn/Pages/home.aspx', 'http://ts.humg.edu.vn/Pages/home.aspx', 7, ''),
(8, 'DT', 'Đại học Thái Nguyên', 'img/dhtnlogo.jpg', 'http://www.tnu.edu.vn/Pages/home.aspx', 'http://tuyensinh.tnu.edu.vn/', 8, ''),
(9, 'DD', 'Đại học Đà Nẵng', 'img/dhdnlogo.jpg', 'http://www.udn.vn/', 'http://ts.udn.vn/', 9, ''),
(10, 'YHB', 'Đại học Y Hà Nội', 'img/dhyhnlogo.jpg', 'http://www.hmu.edu.vn/news/default.aspx', 'http://www.hmu.edu.vn/news/xc66_Tuyen-sinh-.html', 10, ''),
(11, 'NLS', 'Đại học Nông Lâm Thành Phố Hồ Chí Minh', 'img/dhnltphcmlogo.jpg', 'http://www.hcmuaf.edu.vn/', 'http://ts.hcmuaf.edu.vn/contents.php?ur=ts&ids=32054', 11, ''),
(12, 'BVH', 'Học viện Công nghệ Bưu chính Viễn thông', 'img/dhcnbcvtlogo.jpg', 'http://portal.ptit.edu.vn/', 'http://portal.ptit.edu.vn/tuyensinh/dh-chinh-quy/', 12, ''),
(13, 'DH', 'Đại học Huế', 'img/dhhlogo.jpg', 'http://hueuni.edu.vn/', 'http://hueuni.edu.vn/portal/vi/index.php/Category/tin-tuyen-sinh.html', 13, ''),
(14, 'KHA', 'Đại học Kinh tế Quốc dân', 'img/dhktqdlogo.jpg', 'https://www.neu.edu.vn/', 'https://tuyensinh.neu.edu.vn/', 14, ''),
(15, 'GHA', 'Đại học Giao Thông Vận tải', 'img/dhgtvtlogo.jpg', 'https://www.utc.edu.vn/', 'http://ts.utc.edu.vn/', 15, ''),
(16, 'TDV', 'Đại học Vinh', 'img/dhvlogo.jpg', 'http://www.vinhuni.edu.vn/', 'http://www.vinhuni.edu.vn/tuyen-sinh/dai-hoc-chinh-quy', 16, ''),
(17, 'KQH', 'Học viện Kỹ thuật Quân sự', 'img/hvktqslogo.jpg', 'http://mta.edu.vn/', 'http://mta.edu.vn/TUY%E1%BB%82N-SINH/Tuy%E1%BB%83n-sinh-%C4%91%E1%BA%A1i-h%E1%BB%8Dc', 17, ''),
(18, 'DQN', 'Đại học Quy Nhơn', 'img/dhqnlogo.jpg', 'http://www.qnu.edu.vn/', 'http://tuyensinh.qnu.edu.vn/', 18, ''),
(19, 'DVT', 'Đại học Trà Vinh', 'img/dhtvlogo.jpg', 'http://www.tvu.edu.vn/', 'https://tuyensinh.tvu.edu.vn/', 19, ''),
(20, 'XDA', 'Đại học Xây Dựng', 'img/dhxdlogo.jpg', 'http://nuce.edu.vn/', 'http://tuyensinh.nuce.edu.vn/', 20, ''),
(21, 'TSN', 'Đại học Nha Trang', 'img/dhntlogo.jpg', 'http://www.ntu.edu.vn/', 'http://tuyensinh.ntu.edu.vn/', 21, ''),
(22, 'KSA', 'Đại học Kinh tế Thành phố Hồ Chí Minh', 'img/dhkttphcmlogo.jpg', 'http://www.ueh.edu.vn/', 'http://tuyensinh.ueh.edu.vn/', 22, ''),
(23, 'QSQ', 'Đại học Quốc tế - Đại học Quốc gia Thp. Hồ Chí Minh', 'img/dhqtdhqgtphcmlogo.jpg', 'https://www.hcmiu.edu.vn/', 'https://tuyensinh.hcmiu.edu.vn/', 23, ''),
(24, 'DDT', 'Đại học Duy Tân', 'img/dhdtlogo.jpg', 'http://duytan.edu.vn/', 'http://duytan.edu.vn/tuyen-sinh/Page/Home.aspx', 24, ''),
(25, 'QST', 'Đại học Khoa Học Tự Nhiên - Đại học Quốc Gia Thp. Hồ Chí Minh', 'img/dhkhtndhqgtphcmlogo.jpg', 'https://www.hcmus.edu.vn/', 'https://tuyensinh.hcmus.edu.vn/', 25, ''),
(26, 'DVL', 'Đại học Văn Lang', 'img/dhvllogo.jpg', 'http://www.vanlanguni.edu.vn/', 'http://tuyensinh.vanlanguni.edu.vn/', 26, ''),
(27, 'RMU', 'Đại học Quốc tế RMIT Việt Nam', 'img/dhqtrmitvnlogo.jpg', 'https://www.rmit.edu.vn/vi', 'http://diemthi.tuyensinh247.com/thong-tin-dai-hoc-quoc-te-rmit-viet-nam-RMU.html', 27, ''),
(28, 'FPT', 'Đại học FPT', 'img/dhfptlogo.jpg', 'http://fpt.edu.vn/don-vi/dai-hoc-fpt', 'http://fpt.edu.vn/don-vi/dai-hoc-fpt', 28, ''),
(29, 'QSC', 'Đại học Công nghệ Thông tin - Đại học Quốc gia Thành phố Hồ Chí Minh', 'img/dhcnttdhqgtphcmlogo.jpg', 'https://www.uit.edu.vn/', 'https://tuyensinh.uit.edu.vn/', 29, ''),
(30, 'YDS', 'Đại học Y dược Thành phố Hồ Chí Minh', 'img/dhydtphcmlogo.jpg', 'http://www.yds.edu.vn/yds2/', 'http://www.yds.edu.vn/yds2/?Content=tuyensinh', 30, ''),
(31, 'DKC', 'Đại học Công nghệ Thp. Hồ Chí Minh', 'img/dhcntphcmlogo.jpg', 'https://www.hutech.edu.vn/', 'http://www.hutech.edu.vn/xet-tuyen-dai-hoc', 31, ''),
(32, 'SPK', 'Đại học Sư phạm Kỹ thuật TP. Hồ Chí Minh', 'img/dhspkttphcmlogo.jpg', 'http://hcmute.edu.vn/', 'http://hcmute.edu.vn/ArticleId/9333f78d-088e-49e5-9a65-1e93a6404c9d/tuyen-sinh-dai-hoc-he-chinh-quy-nam-2018-cua-truong-dh-spkt-tp-hcm', 32, ''),
(33, 'TAG', 'Đại học An Giang', 'img/dhaglogo.jpg', 'http://www.agu.edu.vn/', 'http://www.agu.edu.vn/tuyensinh/', 33, ''),
(34, 'SKH', 'Đại học Sư phạm Kỹ thuật Hưng Yên', 'img/dhspkthylogo.jpg', 'http://www.utehy.edu.vn/', 'http://tuyensinh.utehy.edu.vn/', 34, ''),
(35, 'SPS', 'Đại học Sư phạm TP. HỒ CHÍ MINH', 'img/dhsptphcmlogo.jpg', 'http://www.hcmup.edu.vn/', 'http://www.thongtintuyensinh.vn/Truong_Dai_hoc_Su_pham_TPHCM_C51_D705.htm', 35, ''),
(36, 'NTH', 'Đại học Ngoại thương', 'img/dhngoaithuonglogo.jpg', 'http://ftu.edu.vn/', 'http://www.tuyensinhtoanquoc24h.com/2017/11/truong-dai-hoc-ngoai-thuong-tuyen-sinh.html', 36, ''),
(37, 'NHH', 'Học viện Ngân hàng', 'img/hvnhlogo.jpg', 'http://hvnh.edu.vn/hvnh/vi/home.html', 'http://hvnh.edu.vn/hvnh/vi/thong-tin-tuyen-sinh', 37, ''),
(38, 'DTH', 'Đại học Hoa Sen', 'img/dhhslogo.jpg', 'https://www.hoasen.edu.vn/vi', 'https://tuyensinh.hoasen.edu.vn/', 38, ''),
(39, 'HHA', 'Đại học Hàng hải Việt Nam', 'img/dhhhvnlogo.jpg', 'http://www.vimaru.edu.vn/', 'http://tuyensinh.vimaru.edu.vn/', 39, ''),
(40, 'VGU', 'Đại học Việt - Đức', 'img/dhvdlogo.jpg', 'http://www.vgu.edu.vn/vi/', 'http://www.vgu.edu.vn/vi/web/cms/admission', 40, ''),
(41, 'NTT', 'Đại học Nguyễn Tất Thành', 'img/dhnttlogo.jpg', 'http://ntt.edu.vn/web/', 'http://ntt.edu.vn/web/tuyen-sinh/', 41, ''),
(42, 'HDT', 'Đại học Hồng Đức', 'img/dhhdlogo.jpg', 'http://www.hdu.edu.vn/default.aspx', 'http://www.hdu.edu.vn/default.aspx', 42, ''),
(43, 'MBS', 'Đại học Mở Thành phố Hồ Chí Minh', 'img/dhmtphcmlogo.jpg', 'http://ou.edu.vn/', 'http://tuyensinh.ou.edu.vn/', 43, ''),
(44, 'DLH', 'Đại học Lạc Hồng', 'img/dhlhlogo.jpg', 'https://lhu.edu.vn/', 'https://tuyensinh.lhu.edu.vn/', 44, ''),
(45, '', 'Cao đẳng Nghề B<NAME>', 'img/bkhnlogo.jpg', 'http://www.hactech.edu.vn/', 'http://www.hactech.edu.vn/vn/Thong-tin-tuyen-sinh-517.html', 45, ''),
(46, 'YTC', 'Đại học Y tế Công cộng', 'img/dhytcclogo.jpg', 'http://www.huph.edu.vn/', 'http://tuyensinh.huph.edu.vn/', 46, ''),
(47, 'DHP', 'Đại học Dân lập Hải Phòng', 'img/dhdlhplogo.jpg', 'http://www.hpu.edu.vn/home/trangchu.html', 'http://www.hpu.edu.vn/tuyensinh/HPUTS-tuyensinh.html', 47, ''),
(48, 'DDL', 'Đại học Điện lực', 'img/dhdllogo.jpg', 'http://epu.edu.vn/', 'http://tuyensinh.epu.edu.vn/', 48, ''),
(49, 'DTN', 'Đại học Nông Lâm Thái Nguyên', 'img/dhnltnlogo.jpg', 'http://tuaf.edu.vn/', 'http://tuyensinh.tuaf.edu.vn/', 49, ''),
(50, 'SP2', 'Đại học Sư phạm Hà Nội 2', 'img/dhsphn2logo.jpg', 'http://www.hpu2.edu.vn/', 'http://tuyensinh.hpu2.edu.vn/', 50, ''),
(51, 'DTK', 'Đại học Kỹ thuật Công nghiệp - Đại học Thái Nguyên', 'img/dhktcntnlogo.jpg', 'http://www.tnut.edu.vn/', 'http://ts.tnut.edu.vn/', 51, ''),
(52, 'QSX', 'Đại học Khoa học Xã hội và Nhân văn - Đại học Quốc gia Thành phố Hồ Chí Minh', 'img/dhkhxhvnvdhqgtphcmlogo.jpg', 'http://hcmussh.edu.vn/', 'http://tuyensinh.hcmussh.edu.vn/', 52, ''),
(53, 'DCN', 'Đại học Công nghiệp Hà Nội', 'img/dhcnhnlogo.jpg', 'https://www.haui.edu.vn/vn', 'https://tuyensinh.haui.edu.vn/', 53, ''),
(54, 'SGD', 'Đại học Sài Gòn', 'img/dhsglogo.jpg', 'https://sgu.edu.vn/', 'http://www.thongtintuyensinh.vn/Truong-Dai-hoc-Sai-Gon_C51_D707.htm', 54, ''),
(55, 'TLA', 'Đại học Thủy lợi', 'img/dhtllogo.jpg', 'http://www.tlu.edu.vn/', 'http://www.tlu.edu.vn/tuyen-sinh', 55, ''),
(56, 'GTA', 'Đại học Công nghệ Giao thông Vận tải', 'img/dhcngtvtlogo.jpg', 'http://utt.edu.vn/', 'http://tuyensinh.utt.edu.vn/', 56, ''),
(57, 'SPD', 'Đại học Đồng Tháp', 'img/dhdongthaplogo.jpg', 'http://www.dthu.edu.vn/', 'http://www.dthu.edu.vn/', 57, ''),
(58, 'LNS', 'Đại học Lâm nghiệp', 'img/dhlnlogo.jpg', 'http://vnuf.edu.vn/', 'http://tuyensinh.vfu.edu.vn/', 58, ''),
(59, 'VHH', 'Đại học Văn hóa Hà Nội', 'img/dhvhhnlogo.jpg', 'http://huc.edu.vn/', 'http://huc.edu.vn/thong-tin-tuyen-sinh-dai-hoc-chinh-quy-nam-2018-5311-vi.htm', 59, ''),
(60, 'LPS', 'Đại học Luật TP.HCM', 'img/dhltphcmlogo.jpg', 'http://www.hcmulaw.edu.vn/', 'http://ts.hcmulaw.edu.vn/', 60, ''),
(61, 'NHS', 'Đại học Ngân hàng Thành phố Hồ Chí Minh', 'img/dhnhtphcmlogo.jpg', 'http://buh.edu.vn/', 'http://tuyensinh.buh.edu.vn/', 61, ''),
(62, 'DTT', 'Đại học Tôn Đức Thắng', 'img/dhtdtlogo.jpg', 'http://www.tdtu.edu.vn/', 'http://tuyensinh.tdtu.edu.vn/', 62, ''),
(63, 'TTB', 'Đại học Tây Bắc', 'img/dhtblogo.jpg', 'http://www.utb.edu.vn/', 'http://www.utb.edu.vn/index.php/tuyen-sinh', 63, ''),
(64, 'HUI', 'Đại học Công nghiệp TP.HCM', 'img/dhcongnghieptphcmlogo.jpg', 'http://www.hui.edu.vn/', 'http://www.utb.edu.vn/index.php/tuyen-sinh', 64, ''),
(65, 'DKH', 'Đại học Dược Hà Nội', 'img/dhdhnlogo.jpg', 'http://www.hup.edu.vn/Pages/default.aspx#section=generalw', 'http://www.hup.edu.vn/Pages/tuyen-sinh.aspx', 65, ''),
(66, 'TYS', 'Đại học Y khoa Phạm Ngọc Thạch', 'img/dhykpntlogo.jpg', 'https://www.pnt.edu.vn/', 'https://pqldt.pnt.edu.vn/vi/tuyen-sinh-dai-hoc-chinh-quy', 66, ''),
(67, 'NHF', 'Đại học Hà Nội', 'img/dhhnlogo.jpg', 'http://www.hanu.edu.vn/vn/', 'http://hanu.vn/vn/chinh-quy.html', 67, ''),
(68, 'KTS', 'Đại học Kiến trúc TP. Hồ Chí Minh', 'img/dhkientructphcmlogo.jpg', 'http://www.uah.edu.vn/', 'http://www.uah.edu.vn/router/dai-hoc-353.html', 68, ''),
(69, 'HTC', 'Học viện Tài chính', 'img/hvtclogo.jpg', 'https://hvtc.edu.vn/', 'https://hvtc.edu.vn/tabid/109/Default.aspx', 69, ''),
(70, 'TDL', 'Đại học Đà Lạt', 'img/dhdalatlogo.jpg', 'http://www.dlu.edu.vn/', 'http://pqldt.dlu.edu.vn/', 70, ''),
(71, 'QSK', 'Đại học Kinh tế Luật - Đại học Quốc gia Thành phố Hồ Chí Minh', 'img/dhktldhqgtphcmlogo.jpg', 'http://www.uel.edu.vn/', 'http://tuyensinh.uel.edu.vn/', 71, ''),
(72, 'QHT', 'Đại học Khoa học Tự nhiên - Đại học Quốc gia Hà Nội', 'img/dhkhtndhqghnlogo.jpg', 'http://hus.vnu.edu.vn/', 'http://hus.vnu.edu.vn/vi/main/tuyensinh', 72, ''),
(73, 'LPH', 'Đại học Luật Hà Nội', 'img/dhlhnlogo.jpg', 'http://hlu.edu.vn/', 'http://tuyensinh.hlu.edu.vn/', 73, ''),
(74, 'MHN', 'Viện đại học Mở Hà Nội', 'img/dhmhnlogo.jpg', 'https://hou.edu.vn/', 'https://tuyensinh.hou.edu.vn/', 74, ''),
(75, 'QHE', 'Đại học Kinh tế - Đại học Quốc gia Hà Nội', 'img/dhktdhqghnlogo.jpg', 'http://ueb.edu.vn/', 'http://tuyensinhdaihoc.ueb.edu.vn/', 75, ''),
(76, 'TDM', 'Đại học Thủ Dầu Một', 'img/dhtdmlogo.jpg', 'https://tdmu.edu.vn/', 'https://tuyensinh.tdmu.edu.vn/', 76, ''),
(77, 'DNT', 'Đại học Ngoại ngữ - Tin học TP.HCM', 'img/dhnnthtphcmlogo.jpg', 'http://www.huflit.edu.vn/', 'http://www.huflit.edu.vn/tuyen-sinh-39/', 77, ''),
(78, 'KTA', 'Đại học Kiến trúc Hà Nội', 'img/dhkthnlogo.jpg', 'http://www.hau.edu.vn/', 'http://www.hau.edu.vn/thong-tin-tuyen-sinh-dai-hoc_c08/', 78, ''),
(79, '', 'Trung tâm Nghiên cứu và Đào tạo Thiết kế Vi mạch', 'img/icdreclogo.jpg', 'http://icdrec.edu.vn/', '', 79, ''),
(80, 'TMA', 'Đại học Thương mại', 'img/dhtmlogo.jpg', 'http://tmu.edu.vn/', 'https://tmu.edu.vn/vi/news/TUYEN-SINH/', 80, ''),
(81, 'THP', 'Đại học Hải Phòng', 'img/dhhplogo.jpg', 'http://dhhp.edu.vn/vi/trang-chu/', 'http://tuyensinh.dhhp.edu.vn/', 81, ''),
(82, '', 'Viện đào tạo Quốc tế về Khoa học Vật liệu Đại học Bách Khoa Hà Nội', 'img/itimslogo.jpg', 'http://www.itims.edu.vn/', '', 82, ''),
(83, 'DTL', 'Đại học Thăng Long', 'img/dhthanglonglogo.jpg', 'http://www.thanglong.edu.vn/', 'http://www.thanglong.edu.vn/tuyen-sinh/tuyen-sinh-dai-hoc-chinh-quy', 83, ''),
(84, 'YPB', 'Đại học Y Dược Hải Phòng', 'img/dhydhplogo.jpg', 'http://hpmu.edu.vn/hpmu/', 'http://hpmu.edu.vn/hpmu/news/THONG-TIN-TUYEN-SINH/', 84, ''),
(85, 'DQK', 'Đại học Kinh doanh và Công nghệ Hà Nội', 'img/dhkdvcnhnlogo.jpg', 'http://hubt.edu.vn/', 'http://hubt.edu.vn/tin-tuc-khoa-1/dai-hoc-chinh-quy/20', 85, ''),
(86, 'GTS', 'Đại học Giao thông Vận tải Thành phố Hồ Chí Minh', 'img/dhgtvttphcmlogo.jpg', 'https://ut.edu.vn/', 'http://tuyensinh.ut.edu.vn/chuyenmuc/thong-bao-tuyen-sinh/dai-hoc-cao-dang-chinh-quy/', 86, ''),
(87, 'DSG', 'Đại học Công nghệ Sài Gòn', 'img/dhcnsglogo.jpg', 'http://www.stu.edu.vn/', 'http://www.stu.edu.vn/vi/1/14112/thong-bao-tuyen-sinh-dai-hoc-chinh-quy-nam-2018.html', 87, ''),
(88, 'DBD', 'Đại học Bình Dương', 'img/dhbdlogo.jpg', 'http://www.bdu.edu.vn/', 'http://tuyensinh.bdu.edu.vn/', 88, ''),
(89, 'HQT', 'Học viện Ngoại giao Việt Nam', 'img/hvnglogo.jpg', 'http://www.dav.edu.vn/', 'https://www.dav.edu.vn/vi/tuyen-sinh', 89, ''),
(90, '', 'Học viện Kỹ thuật Lê Qúy Đôn', 'img/dhktlqdlogo.jpg', 'http://www.lqdtu.edu.vn/', '', 90, ''),
(91, 'DHL', 'Đại học Nông Lâm - Đại học Huế', 'img/dhnlhlogo.jpg', 'http://www.huaf.edu.vn/', 'http://tuyensinh.huaf.edu.vn/', 91, ''),
(92, 'BVU', 'Đại học Bà Rịa - Vũng Tàu', 'img/dhbrvtlogo.jpg', 'http://bvu.edu.vn/', 'http://bvu.edu.vn/tuyen-sinh1', 92, ''),
(93, 'DQB', 'Đại học Quảng Bình', 'img/dhqblogo.jpg', 'http://quangbinhuni.edu.vn/', 'http://quangbinhuni.edu.vn/Dai-Hoc-Quang-Binh/PortalNews/Tuyen_sinh/0/36/0', 94, ''),
(94, 'HIU', 'Đại học Quốc tế Hồng Bàng', 'img/dhqthblogo.jpg', 'http://hiu.vn/', 'http://admissions.hiu.vn/', 95, ''),
(95, 'DCD', 'Đại học Công nghệ Đồng Nai', 'img/dhcndnlogo.jpg', 'http://dntu.edu.vn/', 'http://ts.dntu.edu.vn/', 96, ''),
(96, 'TTN', 'Đại học Tây Nguyên', 'img/dhtaynguyenlogo.jpg', 'http://www.ttn.edu.vn/', 'https://www.ttn.edu.vn/index.php/tuyensinh/tuyensinhdhcd', 97, ''),
(97, '', 'Saigon Tech', 'img/saigontechlogo.jpg', 'http://www.saigontech.edu.vn/', 'http://www.saigontech.edu.vn/thong-tin-tuyen-sinh-va-nhap-hoc.html', 98, ''),
(98, 'DBG', 'Đại học Nông Lâm Bắc Giang', 'img/dhnlbglogo.jpg', 'http://bafu.edu.vn/home/', 'http://bafu.edu.vn/tuyensinh/', 99, ''),
(99, 'DBH', 'Đại học Quốc tế Bắc Hà', 'img/dhqtbhlogo.jpg', 'http://www.bhiu.edu.vn/', 'http://www.bhiu.edu.vn/danh-muc-tin/313_tuyen-sinh', 100, ''),
(100, 'MTS', 'Đại học Mỹ thuật Thành phố Hồ Chí Minh', 'img/dhmythuattphcmlogo.jpg', 'http://hcmufa.edu.vn/', 'http://hcmufa.edu.vn/tuyen-sinh', 101, ''),
(101, 'D50', 'Cao đẳng Cộng đồng Đồng Tháp', 'img/cdcddtlogo.jpg', 'http://www.dtcc.edu.vn/', 'http://www.dtcc.edu.vn/tuyen_sinh/ch%C3%ADnh-quy/th%C3%B4ng-tin-tuy%E1%BB%83n-sinh-2018.html', 102, ''),
(102, 'HCH', 'Học viện Hành chính Quốc gia', 'img/hvhcqglogo.jpg', 'http://www1.napa.vn/', 'http://www1.napa.vn/bandaotao/category/tuyen-sinh', 103, ''),
(103, 'GSA', 'Đại học Giao thông Vận tải cơ sở 2 phía Nam', 'img/dhgtvtcs2logo.jpg', 'http://utc2.edu.vn/', 'http://tuyensinh.utc2.edu.vn/', 107, ''),
(104, 'DLA', 'Đại học Kinh tế Công nghiệp Long An', 'img/dhktcnlalogo.jpg', 'http://daihoclongan.edu.vn/', 'https://daihoclongan.edu.vn/tin-tuc-su-kien/tin-tuyen-sinh/1349-thong-tin-tuyen-sinh-dai-hoc-chinh-quy-nam-2018.html', 108, ''),
(105, 'DCL', 'Đại học Cửu Long', 'img/dhcllogo.jpg', 'http://www.mku.edu.vn/', 'http://mku.edu.vn/tuyensinh/', 109, ''),
(106, 'NVH', 'Học viện Âm nhạc Quốc gia Việt Nam', 'img/hvanqgvnlogo.jpg', 'http://www.vnam.edu.vn/', 'http://www.vnam.edu.vn/Categories.aspx?lang=&CatID=9', 110, ''),
(107, 'NVS', 'Nhạc viện Thành phố Hồ Chí Minh', 'img/nvtphcmlogo.jpg', 'http://www.hcmcons.vn/', 'http://www.hcmcons.vn/dao-tao/trung-cap-dai-hoc/thong-bao/tuyen-sinh', 111, ''),
(108, '', 'Cao đẳng Kinh tế Tài chính Vĩnh Long', 'img/cdkttcvllogo.jpg', 'http://www.vcef.edu.vn/', 'http://www.vcef.edu.vn/', 112, ''),
(109, 'DQT', 'Đại học Quang Trung', 'img/dhqtlogo.jpg', 'http://www.quangtrung.edu.vn/page/dhqt.php', 'http://www.quangtrung.edu.vn/page/dhqt.php', 114, ''),
(110, 'MTC', 'Đại học Mỹ thuật Công nghiệp Hà Nội', 'img/dhmtcnhnlogo.jpg', 'http://mythuatcongnghiep.edu.vn/', 'http://mythuatcongnghiep.edu.vn/tin-tuc/tuyen-sinh.html', 115, ''),
(111, 'QSB', 'Đại học Bách Khoa Tp. Hồ Chí Minh', 'img/dhbktphcmlogo.jpg', 'http://www.bku.edu.vn/', 'https://kenhtuyensinh.vn/dai-hoc-bach-khoa-tphcm', 116, ''),
(112, 'DVX', 'Đại học Công nghệ Vạn Xuân', 'img/dhcnvxlogo.jpg', 'https://www.vxut.edu.vn/', 'https://www.vxut.edu.vn/home/v1/category/79/', 123, ''),
(113, '', 'Cao đẳng S<NAME>', 'img/cdspntlogo.jpg', 'http://www.cdspninhthuan.edu.vn/', 'http://www.cdspninhthuan.edu.vn/', 124, ''),
(114, 'DPD', 'Đại học Dân lập Phương Đông', 'img/dhpdlogo.jpg', 'http://phuongdong.edu.vn/', 'http://phuongdong.edu.vn/tuyensinh.html', 125, ''),
(115, 'DPX', 'Đại học Dân lập Phú Xuân', 'img/dhdlpxlogo.jpg', 'http://www.phuxuanuni.edu.vn/', 'https://drive.google.com/file/d/1pfy_AMtAeODAm2QclQZFLpARmI86yMK-/view', 126, ''),
(116, '0218', '<NAME>', 'img/tcpnlogo.jpg', 'http://www.phuongnam-et.edu.vn/index.php?lang=vi', 'http://tuyensinh.phuongnam-et.edu.vn/', 127, ''),
(117, 'HKC', 'Học viện Khoa học và Công nghệ', 'img/hvkhvcnlogo.jpg', 'http://gust.edu.vn/vn', 'http://gust.edu.vn/vn', 128, ''),
(118, 'D54', '<NAME>', 'img/cdkglogo.jpg', 'http://www.kgtec.edu.vn/', 'http://www.kgc.edu.vn/tuyen-sinh.html', 129, '');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `trong_so`
--
CREATE TABLE `trong_so` (
`ID` int(2) NOT NULL,
`Trong_So_Bien_Ngon_Ngu` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `trong_so`
--
INSERT INTO `trong_so` (`ID`, `Trong_So_Bien_Ngon_Ngu`) VALUES
(1, 'khong_anh_huong'),
(2, 'anh_huong_it'),
(3, 'anh_huong_kha_lon'),
(4, 'anh_huong_rat_lon');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `tuyen_sinh`
--
CREATE TABLE `tuyen_sinh` (
`Tuyen_Sinh_ID` int(11) NOT NULL,
`Ma_To_Chuc_Dao_Tao` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Ten_Nganh` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Ma_Khoi_Thi` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`So_Chi_Tieu` int(11) NOT NULL,
`Ma_Nganh_TCDT` varchar(255) CHARACTER SET utf8 COLLATE utf8_vietnamese_ci NOT NULL,
`Diem_Nguong` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Đang đổ dữ liệu cho bảng `tuyen_sinh`
--
INSERT INTO `tuyen_sinh` (`Tuyen_Sinh_ID`, `Ma_To_Chuc_Dao_Tao`, `Ten_Nganh`, `Ma_Khoi_Thi`, `So_Chi_Tieu`, `Ma_Nganh_TCDT`, `Diem_Nguong`) VALUES
(1, 'BKA', 'Kỹ thuật cơ điện tử', 'A00', 160, 'ME1', 27),
(2, 'BKA', 'Kỹ thuật cơ điện tử', 'A01', 160, 'ME1', 27),
(3, 'BKA', 'Kỹ thuật Cơ khí', 'A00', 250, 'ME2', 25.75),
(4, 'BKA', 'Kỹ thuật Cơ khí', 'A01', 250, 'ME2', 25.75),
(5, 'BKA', 'Chương trình tiên tiến Cơ điện tử', 'A00', 40, 'ME-E1', 25.5),
(6, 'BKA', 'Chương trình tiên tiến Cơ điện tử', 'A01', 40, 'ME-E1', 25.5),
(7, 'BKA', 'Kỹ thuật Ô tô', 'A00', 110, 'TE1', 25.75),
(8, 'BKA', 'Kỹ thuật Ô tô', 'A01', 110, 'TE1', 25.75),
(9, 'BKA', 'Kỹ thuật Cơ khi Động lực', 'A00', 25, 'TE2', 25.75),
(10, 'BKA', 'Kỹ thuật Cơ khi Động lực', 'A01', 25, 'TE2', 25.75),
(11, 'BKA', 'Kỹ thuật Hàng không', 'A00', 20, 'TE3', 25.75),
(12, 'BKA', 'Kỹ thuật Hàng không', 'A01', 20, 'TE3', 25.75),
(13, 'BKA', 'Kỹ thuật Tàu thủy', 'A00', 20, 'TE4', 25.75),
(14, 'BKA', 'Kỹ thuật Tàu thủy', 'A01', 20, 'TE4', 25.75),
(15, 'BKA', 'Chương trình tiên tiến Kỹ thuật Ô tô', 'A00', 15, 'TE-E2', 0),
(16, 'BKA', 'Chương trình tiên tiến Kỹ thuật Ô tô', 'A01', 15, 'TE-E2', 0),
(17, 'BKA', 'Kỹ thuật Nhiệt', 'A00', 125, 'HE1', 24.75),
(18, 'BKA', 'Kỹ thuật Nhiệt', 'A01', 125, 'HE1', 24.75),
(19, 'BKA', 'Kỹ thuật Vật liệu', 'A00', 110, 'MS1', 23.75),
(20, 'BKA', 'Kỹ thuật Vật liệu', 'A01', 110, 'MS1', 23.75),
(21, 'BKA', 'Chương trình Tiên tiến Khoa học Kỹ thuật Vật liệu', 'A00', 15, 'MS-E3', 23.37),
(22, 'BKA', 'Chương trình Tiên tiến Khoa học Kỹ thuật Vật liệu', 'A01', 15, 'MS-E3', 23.37),
(23, 'BKA', 'Kỹ thuật Điện tử Viễn thông', 'A00', 270, 'ET1', 26.25),
(24, 'BKA', 'Kỹ thuật Điện tử Viễn thông', 'A01', 270, 'ET1', 26.25),
(25, 'BKA', 'Chương trình Tiên tiến Điện tử Viễn thông', 'A00', 20, 'ET-E4', 25.5),
(26, 'BKA', 'Chương trình Tiên tiến Điện tử Viễn thông', 'A01', 20, 'ET-E4', 25.5),
(27, 'BKA', 'Chương trình Tiên tiến Kỹ thuật Y sinh', 'A00', 20, 'ET-E5', 25.25),
(28, 'BKA', 'Chương trình Tiên tiến Kỹ thuật Y sinh', 'A01', 20, 'ET-E5', 25.25),
(29, 'BKA', 'Khoa học Máy tính', 'A00', 100, 'IT1', 28.25),
(30, 'BKA', 'Khoa học Máy tính', 'A01', 100, 'IT1', 28.25),
(31, 'BKA', 'Kỹ thuật Máy tính', 'A00', 80, 'IT2', 28.25),
(32, 'BKA', 'Kỹ thuật Máy tính', 'A01', 80, 'IT2', 28.25),
(33, 'BKA', 'Công nghệ Thông tin', 'A00', 800, 'IT3', 28.25),
(34, 'BKA', 'Công nghệ Thông tin', 'A01', 800, 'IT3', 28.25),
(35, 'BKA', 'Công nghệ Thông tin Việt -Nhật', 'A00', 100, 'IT-E6', 26.75),
(36, 'BKA', 'Công nghệ Thông tin Việt -Nhật', 'A01', 100, 'IT-E6', 26.75),
(37, 'BKA', 'Công nghệ Thồng tin ICT', 'A00', 40, 'IT-E7', 26.75),
(38, 'BKA', 'Công nghệ Thồng tin ICT', 'A01', 40, 'IT-E7', 26.75),
(39, 'BKA', 'Toán Tin', 'A00', 50, 'MI1', 25.75),
(40, 'BKA', 'Toán Tin', 'A01', 50, 'MI1', 25.75),
(41, 'BKA', 'Hệ thống Thông tin Quản lý', 'A00', 30, 'MI2', 25.75),
(42, 'BKA', 'Hệ thống Thông tin Quản lý', 'A01', 30, 'MI2', 25.75),
(43, 'BKA', 'Kỹ thuật Điện', 'A00', 110, 'EE1', 27.25),
(44, 'BKA', 'Kỹ thuật Điện', 'A01', 110, 'EE1', 27.25),
(45, 'BKA', 'Kỹ thuật Điều khiển - Tự động hóa', 'A00', 250, 'EE2', 27.25),
(46, 'BKA', 'Kỹ thuật Điều khiển - Tự động hóa', 'A01', 250, 'EE2', 27.25),
(47, 'BKA', 'Chương trình Tiên tiến Điều khiển Tự động hóa và Hệ thống điện', 'A00', 40, 'EE-E8', 26.25),
(48, 'BKA', 'Chương trình Tiên tiến Điều khiển Tự động hóa và Hệ thống điện', 'A01', 40, 'EE-E8', 26.25),
(49, 'BKA', 'Kỹ thuật Hóa học', 'A00', 160, 'CH1', 25),
(50, 'BKA', 'Kỹ thuật Hóa học', 'B00', 160, 'CH1', 25),
(51, 'BKA', 'Kỹ thuật Hóa học', 'D07', 160, 'CH1', 25),
(52, 'BKA', 'Hóa học', 'A00', 27, 'CH2', 25),
(53, 'BKA', 'Hóa học', 'B00', 26, 'CH2', 25),
(54, 'BKA', 'Hóa học', 'D07', 26, 'CH2', 25),
(55, 'BKA', 'Kỹ thuật in', 'A00', 14, 'CH3', 21.25),
(56, 'BKA', 'Kỹ thuật in', 'B00', 13, 'CH3', 21.25),
(57, 'BKA', 'Kỹ thuật in', 'D07', 13, 'CH3', 21.25),
(58, 'BKA', 'Kỹ thuật Sinh học', 'A00', 27, 'BF1', 25),
(59, 'BKA', 'Kỹ thuật Sinh học', 'B00', 27, 'BF1', 25),
(60, 'BKA', 'Kỹ thuật Sinh học', 'D07', 26, 'BF1', 25),
(61, 'BKA', 'Kỹ thuật Thực phẩm', 'A00', 67, 'BF2', 25),
(62, 'BKA', 'Kỹ thuật Thực phẩm', 'B00', 67, 'BF2', 25),
(63, 'BKA', 'Kỹ thuật Thực phẩm', 'D07', 66, 'BF2', 25),
(64, 'BKA', 'Kỹ thuật Môi trường', 'A00', 40, 'EV1', 25),
(65, 'BKA', 'Kỹ thuật Môi trường', 'B00', 40, 'EV1', 25),
(66, 'BKA', 'Kỹ thuật Môi trường', 'D07', 40, 'EV1', 25),
(67, 'BKA', 'Kỹ thuật Dệt', 'A00', 55, 'TX1', 24.5),
(68, 'BKA', 'Kỹ thuật Dệt', 'A01', 55, 'TX1', 24.5),
(69, 'BKA', 'Công nghệ May', 'A00', 45, 'TX2', 24.5),
(70, 'BKA', 'Công nghệ May', 'A01', 45, 'TX2', 24.5),
(71, 'BKA', 'Sư phạm Kỹ thuật Công nghiệp', 'A00', 20, 'ED1', 22.5),
(72, 'BKA', 'Sư phạm Kỹ thuật Công nghiệp', 'A01', 20, 'ED1', 22.5),
(73, 'BKA', 'Vật lý Kỹ thuật', 'A00', 75, 'PH1', 23.25),
(74, 'BKA', 'Vật lý Kỹ thuật', 'A01', 75, 'PH1', 23.25),
(75, 'BKA', 'Kỹ thuật Hạt nhân', 'A00', 15, 'NE1', 23.25),
(76, 'BKA', 'Kỹ thuật Hạt nhân', 'A01', 15, 'NE1', 23.25),
(77, 'BKA', 'Kinh tế Công nghiệp', 'A00', 17, 'EM1', 23),
(78, 'BKA', 'Kinh tế Công nghiệp', 'A01', 17, 'EM1', 23),
(79, 'BKA', 'Kinh tế Công nghiệp', 'D01', 16, 'EM1', 23),
(80, 'BKA', 'Quản lý Công nghiệp', 'A00', 30, 'EM2', 23),
(81, 'BKA', 'Quản lý Công nghiệp', 'A01', 30, 'EM2', 23),
(82, 'BKA', 'Quản lý Công nghiệp', 'D01', 30, 'EM2', 23),
(83, 'BKA', 'Quản trị kinh doanh', 'A00', 27, 'EM3', 24.25),
(84, 'BKA', 'Quản trị kinh doanh', 'A01', 27, 'EM3', 24.25),
(85, 'BKA', 'Quản trị kinh doanh', 'D01', 26, 'EM3', 24.25),
(86, 'BKA', 'Kế toán', 'A00', 20, 'EM4', 23.75),
(87, 'BKA', 'Kế toán', 'A01', 20, 'EM4', 23.75),
(88, 'BKA', 'Kế toán', 'D01', 20, 'EM4', 23.75),
(89, 'BKA', 'Tài chính Ngân hàng', 'A00', 14, 'EM5', 23.75),
(90, 'BKA', 'Tài chính Ngân hàng', 'A01', 13, 'EM5', 23.75),
(91, 'BKA', 'Tài chính Ngân hàng', 'D01', 13, 'EM5', 23.75),
(92, 'BKA', 'Tiếng Anh Khoa học Kỹ thuật và Công nghệ', 'D01', 140, 'FL1', 24.5),
(93, 'BKA', 'Tiếng Anh chuyên nghiệp Quốc tế', 'D01', 60, 'FL2', 24.5),
(94, 'BKA', 'Cơ điện tử', 'A00', 34, 'ME-NUT', 23.25),
(95, 'BKA', 'Cơ điện tử', 'A01', 33, 'ME-NUT', 23.25),
(96, 'BKA', 'Cơ điện tử', 'D07', 33, 'ME-NUT', 23.25),
(97, 'BKA', 'Cơ khí Chế tạo máy', 'A00', 10, 'ME-GU', 0),
(98, 'BKA', 'Cơ khí Chế tạo máy', 'A01', 10, 'ME-GU', 0),
(99, 'BKA', 'Cơ khí Chế tạo máy', 'D07', 10, 'ME-GU', 0),
(100, 'BKA', 'Điện tử Viễn thông', 'A00', 14, 'ET-LUH', 22),
(101, 'BKA', 'Điện tử Viễn thông', 'A01', 13, 'ET-LUH', 22),
(102, 'BKA', 'Điện tử Viễn thông', 'D07', 13, 'ET-LUH', 22),
(103, 'BKA', 'Công nghệ thông tin', 'A00', 24, 'IT-LTU', 23.5),
(104, 'BKA', 'Công nghệ thông tin', 'A01', 23, 'IT-LTU', 23.5),
(105, 'BKA', 'Công nghệ thông tin', 'D07', 23, 'IT-LTU', 23.5),
(106, 'BKA', 'Công nghệ thông tin', 'A00', 20, 'IT-VUW', 22),
(107, 'BKA', 'Công nghệ thông tin', 'A01', 20, 'IT-VUW', 22),
(108, 'BKA', 'Công nghệ thông tin', 'D07', 20, 'IT-VUW', 22),
(109, 'BKA', 'Hệ thống thông tin', 'A00', 10, 'IT-GINP', 20),
(110, 'BKA', 'Hệ thống thông tin', 'A01', 10, 'IT-GINP', 20),
(111, 'BKA', 'Hệ thống thông tin', 'D07', 10, 'IT-GINP', 20),
(112, 'BKA', 'Hệ thống thông tin', 'D29', 10, 'IT-GINP', 20),
(113, 'BKA', 'Quản trị kinh doanh', 'A00', 13, 'EM-VUW', 21.25),
(114, 'BKA', 'Quản trị kinh doanh', 'D07', 13, 'EM-VUW', 21.25),
(115, 'BKA', 'Quản trị kinh doanh', 'A01', 12, 'EM-VUW', 21.25),
(116, 'BKA', 'Quản trị kinh doanh', 'D01', 12, 'EM-VUW', 21.25),
(117, 'BKA', 'Quản lý công nghiệp Logistics và quản lý chuỗi cung ứng', 'A00', 10, 'EM-NU', 20),
(118, 'BKA', 'Quản lý công nghiệp Logistics và quản lý chuỗi cung ứng', 'D07', 10, 'EM-NU', 20),
(119, 'BKA', 'Quản lý công nghiệp Logistics và quản lý chuỗi cung ứng', 'A01', 10, 'EM-NU', 20),
(120, 'BKA', 'Quản lý công nghiệp Logistics và quản lý chuỗi cung ứng', 'D01', 10, 'EM-NU', 20),
(121, 'BKA', 'Quản trị kinh doanh', 'A00', 10, 'TROY-BA', 21),
(122, 'BKA', 'Quản trị kinh doanh', 'D07', 10, 'TROY-BA', 21),
(123, 'BKA', 'Quản trị kinh doanh', 'A01', 10, 'TROY-BA', 21),
(124, 'BKA', 'Quản trị kinh doanh', 'D01', 10, 'TROY-BA', 21),
(125, 'BKA', 'Khoa học máy tính', 'A00', 10, 'TROY-IT', 21.25),
(126, 'BKA', 'Khoa học máy tính', 'D07', 10, 'TROY-IT', 21.25),
(127, 'BKA', 'Khoa học máy tính', 'A01', 10, 'TROY-IT', 21.25),
(128, 'BKA', 'Khoa học máy tính', 'D01', 10, 'TROY-IT', 21.25),
(135, 'SPH', 'Sư phạm Toán học', 'A00', 120, '7140209A', 26),
(136, 'SPH', 'Sư phạm Toán học (dạy Toán bằng tiếng Anh)', 'A00', 10, '7140209B', 26),
(137, 'SPH', 'Sư phạm Toán học (dạy Toán bằng tiếng Anh)', 'A01', 9, '7140209C', 27.75),
(138, 'SPH', 'Sư phạm Toán học (dạy Toán bằng tiếng Anh)', 'D01', 6, '7140209D', 27),
(139, 'SPH', 'Sư phạm Tin học', 'A00', 30, '7140210A', 19),
(140, 'SPH', 'Sư phạm Tin học', 'A01', 5, '7140210B', 17.75),
(141, 'SPH', 'Sư phạm Tin học(dạy Tin bằng tiếng Anh)', 'A00', 13, '7140210C', 23.5),
(142, 'SPH', 'Sư phạm Tin học(dạy Tin bằng tiếng Anh)', 'A01', 12, '7140210D', 20),
(143, 'SPH', 'Sư phạm Vật lí', 'A00', 55, '7140211A', 23),
(144, 'SPH', 'Sư phạm Vật lí', 'A01', 15, '7140211B', 22.75),
(145, 'SPH', 'Sư phạm Vật lí', 'C01', 10, '7140211C', 22.75),
(146, 'SPH', 'Sư phạm Vật Lí (dạy Lý bằng tiếng Anh)', 'A00', 5, '7140211D', 22.5),
(147, 'SPH', 'Sư phạm Vật Lí (dạy Lý bằng tiếng Anh)', 'A01', 15, '7140211E', 22.75),
(148, 'SPH', 'Sư phạm Vật Lí (dạy Lý bằng tiếng Anh)', 'C01', 5, '7140211G', 19),
(149, 'SPH', 'Sư phạm Hóa học', 'A00', 80, '7140212A', 23.75),
(150, 'SPH', 'Sư phạm Hóa học (dạy Hóa bằng tiếng Anh)', 'D07', 25, '7140212B', 21),
(151, 'SPH', 'Sư phạm Sinh học', 'A00', 10, '7140213A', 19.5),
(152, 'SPH', 'Sư phạm Sinh học', 'B00', 45, '7140213B', 22),
(153, 'SPH', 'Sư phạm Sinh học', 'B03', 5, '7140213C', 0),
(154, 'SPH', 'Sư phạm Sinh học (dạy Sinh bằng tiếng Anh)', 'D01', 3, '7140213D', 0),
(155, 'SPH', 'Sư phạm Sinh học (dạy Sinh bằng tiếng Anh)', 'D08', 18, '7140213F', 19.5),
(156, 'SPH', 'Sư phạm Sinh học (dạy Sinh bằng tiếng Anh)', 'D07', 4, '7140213E', 18),
(157, 'SPH', 'Sư phạm Công nghệ', 'A00', 50, '7140246A', 0),
(158, 'SPH', 'Sư phạm Công nghệ', 'A01', 50, '7140246B', 0),
(159, 'SPH', 'Sư phạm Công nghệ', 'C01', 50, '7140246C', 0),
(160, 'SPH', 'Sư phạm Ngữ Văn', 'C00', 90, '7140217C', 27),
(161, 'SPH', 'Sư phạm Ngữ Văn', 'D01', 19, '7140217D', 23.5),
(162, 'SPH', 'Sư phạm Ngữ Văn', 'D02', 18, '7140217D', 23.5),
(163, 'SPH', 'Sư phạm Ngữ Văn', 'D03', 18, '7140217D', 23.5),
(164, 'SPH', 'Sư phạm Lịch sử', 'C00', 65, '7140218C', 25.5),
(165, 'SPH', 'Sư phạm Lịch sử', 'D14', 2, '7140218D', 22),
(166, 'SPH', 'Sư phạm Lịch sử', 'D62', 2, '7140218D', 22),
(167, 'SPH', 'Sư phạm Lịch sử', 'D64', 1, '7140218D', 22),
(168, 'SPH', 'Sư phạm Địa lý', 'A00', 15, '7140219A', 18),
(169, 'SPH', 'Sư phạm Địa lý', 'C04', 15, '7140219B', 22.5),
(170, 'SPH', 'Sư phạm Địa lý', 'C00', 50, '7140219C', 25.5),
(171, 'SPH', 'Sư phạm Giáo dục công dân', 'C14', 20, '7140204A', 23.5),
(172, 'SPH', 'Sư phạm Giáo dục công dân', 'D66', 9, '7140204B', 21.25),
(173, 'SPH', 'Sư phạm Giáo dục công dân', 'D68', 8, '7140204B', 21.25),
(174, 'SPH', 'Sư phạm Giáo dục công dân', 'D70', 8, '7140204B', 21.25),
(175, 'SPH', 'Sư phạm Giáo dục công dân', 'D01', 12, '7140204D', 17),
(176, 'SPH', 'Sư phạm Giáo dục công dân', 'D02', 12, '7140204D', 17),
(177, 'SPH', 'Sư phạm Giáo dục công dân', 'D03', 11, '7140204D', 17),
(178, 'SPH', 'Sư phạm Giáo dục Chính trị', 'C14', 15, '7140205A', 21),
(179, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D66', 7, '7140205B', 18.75),
(180, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D68', 7, '7140205B', 18.75),
(181, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D70', 6, '7140205B', 18.75),
(182, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D01', 7, '7140205D', 17.5),
(183, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D02', 7, '7140205D', 17.5),
(184, 'SPH', 'Sư phạm Giáo dục Chính trị', 'D03', 6, '7140205D', 17.5),
(185, 'SPH', 'Sư phạm tiếng Anh', 'D01', 60, '7140231', 25.75),
(186, 'SPH', 'Sư phạm tiếng Pháp', 'D01', 9, '7140233D', 19.5),
(187, 'SPH', 'Sư phạm tiếng Pháp', 'D02', 9, '7140233D', 19.5),
(188, 'SPH', 'Sư phạm tiếng Pháp', 'D03', 8, '7140233D', 19.5),
(189, 'SPH', 'Sư phạm tiếng Pháp', 'D15', 2, '7140233C', 21.5),
(190, 'SPH', 'Sư phạm tiếng Pháp', 'D42', 1, '7140233C', 21.5),
(191, 'SPH', 'Sư phạm tiếng Pháp', 'D44', 1, '7140233C', 21.5),
(192, 'SPH', 'Sư phạm Âm nhạc', 'N02', 25, '7140222', 17.5),
(193, 'SPH', 'Sư phạm Mỹ thuật', 'H07', 25, '7140222', 19),
(194, 'SPH', 'Giáo dục thể chất', '', 25, '7140206', 16),
(195, 'SPH', 'Giáo dục mầm non', 'M00', 40, '7140201A', 22.25),
(196, 'SPH', 'Giáo dục mầm non sư phạm tiếng Anh', 'M01', 15, '7140201B', 20.5),
(197, 'SPH', 'Giáo dục mầm non sư phạm tiếng Anh', 'M02', 15, '7140201B', 22),
(198, 'SPH', 'Giáo dục Tiểu học', 'D01', 12, '7140202A', 25.25),
(199, 'SPH', 'Giáo dục Tiểu học', 'D02', 12, '7140202A', 25.25),
(200, 'SPH', 'Giáo dục Tiểu học', 'D03', 12, '7140202A', 25.25),
(201, 'SPH', 'Giáo dục Tiểu học', 'D11', 2, '7140202B', 20.5),
(202, 'SPH', 'Giáo dục Tiểu học', 'D52', 2, '7140202B', 20.5),
(203, 'SPH', 'Giáo dục Tiểu học', 'D54', 1, '7140202B', 20.5),
(204, 'SPH', 'Giáo dục Tiểu học Sư phạm Tiếng Anh', 'D01', 25, '7140202D', 24.75),
(205, 'SPH', 'Giáo dục Tiểu học Sư phạm Tiếng Anh', 'D11', 5, '7140202C', 20.5),
(206, 'SPH', 'Giáo dục đặc biệt', 'B03', 10, '714203B', 19.25),
(207, 'SPH', 'Giáo dục đặc biệt', 'C00', 17, '714203C', 26.755),
(208, 'SPH', 'Giáo dục đặc biệt', 'D01', 3, '714203D', 23),
(209, 'SPH', 'Giáo dục đặc biệt', 'D02', 3, '714203D', 23),
(210, 'SPH', 'Giáo dục đặc biệt', 'D03', 2, '714203D', 23),
(211, 'SPH', 'Quản lý giáo dục', 'A00', 10, '7140114A', 20.25),
(212, 'SPH', 'Quản lý giáo dục', 'C00', 15, '7140114C', 23.75),
(213, 'SPH', 'Quản lý giáo dục', 'D01', 4, '7140114D', 20.5),
(214, 'SPH', 'Quản lý giáo dục', 'D02', 3, '7140114D', 20.5),
(215, 'SPH', 'Quản lý giáo dục', 'D03', 3, '7140114D', 20.5),
(216, 'SPH', 'Hóa học', 'A00', 100, '7440112', 23.75),
(217, 'SPH', 'Sinh học', 'A00', 15, '7420101A', 19),
(218, 'SPH', 'Sinh học', 'B00', 70, '7420101B', 19),
(219, 'SPH', 'Sinh học', 'C04', 15, '7420101C', 0),
(220, 'SPH', 'Toán học', 'A00', 50, '7460101B', 19.5),
(221, 'SPH', 'Toán học', 'A01', 20, '7460101C', 19.5),
(222, 'SPH', 'Toán học', 'D01', 30, '7460101D', 17.75),
(223, 'SPH', 'Công nghệ thông tin', 'A00', 90, '7480201A', 17.25),
(224, 'SPH', 'Công nghệ thông tin', 'A01', 90, '7480201B', 18),
(225, 'SPH', 'Việt Nam học', 'C04', 15, '7310630B', 18.5),
(226, 'SPH', 'Việt Nam học', 'C04', 45, '7310630C', 21.25),
(227, 'SPH', 'Việt Nam học', 'D01', 20, '7310630D', 17.25),
(228, 'SPH', 'Việt Nam học', 'D02', 20, '7310630D', 17.25),
(229, 'SPH', 'Việt Nam học', 'D03', 20, '7310630D', 17.25),
(230, 'SPH', 'Văn học', 'C00', 60, '7229030C', 24.25),
(231, 'SPH', 'Văn học', 'D01', 14, '7229030D', 20.25),
(232, 'SPH', 'Văn học', 'D02', 13, '7229030D', 20.25),
(233, 'SPH', 'Văn học', 'D03', 13, '7229030D', 20.25),
(234, 'SPH', 'Ngôn ngữ Anh', 'D01', 100, '7220201D', 23.25),
(235, 'SPH', 'Triết học', 'C03', 35, '7229001B', 20.5),
(236, 'SPH', 'Triết học', 'C00', 45, '7229001C', 19),
(237, 'SPH', 'Triết học', 'D01', 7, '7229001D', 18.5),
(238, 'SPH', 'Triết học', 'D02', 7, '7229001D', 18.5),
(239, 'SPH', 'Triết học', 'D03', 6, '7229001D', 18.5),
(240, 'SPH', 'Chính trị học', 'C14', 30, '7310201A', 17.25),
(241, 'SPH', 'Chính trị học', 'D84', 10, '7310201B', 21.75),
(242, 'SPH', 'Chính trị học', 'D86', 10, '7310201B', 21.75),
(243, 'SPH', 'Chính trị học', 'D87', 10, '7310201B', 21.75),
(244, 'SPH', 'Chính trị học', 'D01', 14, '7310201D', 18.25),
(245, 'SPH', 'Chính trị học', 'D02', 13, '7310201D', 18.25),
(246, 'SPH', 'Chính trị học', 'D03', 13, '7310201D', 18.25),
(247, 'SPH', 'Tâm lý học', 'C03', 20, '7310401A', 19.25),
(248, 'SPH', 'Tâm lý học', 'C00', 70, '7310401C', 21.75),
(249, 'SPH', 'Tâm lý học', 'D01', 10, '7310401D', 20.25),
(250, 'SPH', 'Tâm lý học', 'D02', 10, '7310401D', 20.25),
(251, 'SPH', 'Tâm lý học', 'D03', 10, '7310401D', 20.25),
(252, 'SPH', 'Tâm lý giáo dục', 'C03', 10, '7310403A', 17.5),
(253, 'SPH', 'Tâm lý giáo dục', 'C00', 20, '7310403C', 24.5),
(254, 'SPH', 'Tâm lý giáo dục', 'D01', 4, '7310403D', 22.75),
(255, 'SPH', 'Tâm lý giáo dục', 'D02', 4, '7310403D', 22.75),
(256, 'SPH', 'Tâm lý giáo dục', 'D03', 4, '7310403D', 22.75),
(257, 'SPH', 'Công tác xã hội', 'D14', 7, '7760101B', 17.25),
(258, 'SPH', 'Công tác xã hội', 'D62', 6, '7760101B', 17.25),
(259, 'SPH', 'Công tác xã hội', 'D64', 6, '7760101B', 17.25),
(260, 'SPH', 'Công tác xã hội', 'C00', 30, '7760101C', 19),
(261, 'SPH', 'Công tác xã hội', 'D01', 24, '7760101D', 17),
(262, 'SPH', 'Công tác xã hội', 'D02', 24, '7760101D', 17),
(263, 'SPH', 'Công tác xã hội', 'D03', 24, '7760101D', 17),
(264, 'TCT', 'Giáo dục tiểu học', 'A00', 9, '7140202', 22),
(265, 'TCT', 'Giáo dục tiểu học', 'D01', 9, '7140202', 22),
(266, 'TCT', 'Giáo dục tiểu học', 'C01', 9, '7140202', 22),
(267, 'TCT', 'Giáo dục tiểu học', 'D03', 8, '7140202', 22),
(268, 'TCT', 'Giáo dục Công dân', 'C00', 5, '7140204', 22.75),
(269, 'TCT', 'Giáo dục Công dân', 'D14', 5, '7140204', 22.75),
(270, 'TCT', 'Giáo dục Công dân', 'D15', 5, '7140204', 22.75),
(271, 'TCT', 'Giáo dục Công dân', 'C19', 5, '7140204', 22.75),
(272, 'TCT', 'Giáo dục Thể chất', 'T00', 10, '7140206', 17.75),
(273, 'TCT', 'Giáo dục Thể chất', 'T01', 10, '7140206', 17.75),
(274, 'TCT', 'Sư phạm Toán học', 'A00', 5, '7140209', 23.5),
(275, 'TCT', 'Sư phạm Toán học', 'A01', 5, '7140209', 23.5),
(276, 'TCT', 'Sư phạm Toán học', 'D07', 5, '7140209', 23.5),
(277, 'TCT', 'Sư phạm Toán học', 'D08', 5, '7140209', 23.5),
(278, 'TCT', 'Sư phạm Tin học', 'A00', 7, '7140210', 16.5),
(279, 'TCT', 'Sư phạm Tin học', 'A01', 6, '7140210', 16.5),
(280, 'TCT', 'Sư phạm Tin học', 'A02', 6, '7140210', 16.5),
(281, 'TCT', 'Sư phạm Tin học', 'D29', 6, '7140210', 16.5),
(282, 'TCT', 'Sư phạm Vật lí', 'A00', 5, '7140211', 21.75),
(283, 'TCT', 'Sư phạm Vật lí', 'A01', 5, '7140211', 21.75),
(284, 'TCT', 'Sư phạm Vật lí', 'A02', 5, '7140211', 21.75),
(285, 'TCT', 'Sư phạm Vật lí', 'D29', 5, '7140211', 21.75),
(286, 'TCT', 'Sư phạm Hóa học', 'A00', 5, '7140212', 23.25),
(287, 'TCT', 'Sư phạm Hóa học', 'B00', 5, '7140212', 23.25),
(288, 'TCT', 'Sư phạm Hóa học', 'D07', 5, '7140212', 23.25),
(289, 'TCT', 'Sư phạm Hóa học', 'D24', 5, '7140212', 23.25),
(290, 'TCT', 'Sư phạm Sinh học', 'B00', 10, '7140213', 21),
(291, 'TCT', 'Sư phạm Sinh học', 'D08', 10, '7140213', 21),
(292, 'TCT', 'Sư phạm Ngữ văn', 'C00', 7, '7140217', 25),
(293, 'TCT', 'Sư phạm Ngữ văn', 'D14', 7, '7140217', 25),
(294, 'TCT', 'Sư phạm Ngữ văn', 'D15', 6, '7140217', 25),
(295, 'TCT', 'Sư phạm Lịch sử', 'C00', 7, '7140218', 23.75),
(296, 'TCT', 'Sư phạm Lịch sử', 'D14', 7, '7140218', 23.75),
(297, 'TCT', 'Sư phạm Lịch sử', 'D64', 7, '7140218', 23.75),
(298, 'TCT', 'Sư phạm Địa lý', 'C00', 5, '7140219', 24),
(299, 'TCT', 'Sư phạm Địa lý', 'C04', 5, '7140219', 24),
(300, 'TCT', 'Sư phạm Địa lý', 'D15', 5, '7140219', 24),
(301, 'TCT', 'Sư phạm Địa lý', 'D44', 5, '7140219', 24),
(302, 'TCT', 'Sư phạm tiếng Anh', 'D01', 7, '7140231', 24.5),
(303, 'TCT', 'Sư phạm tiếng Anh', 'D14', 7, '7140231', 24.5),
(304, 'TCT', 'Sư phạm tiếng Anh', 'D15', 6, '7140231', 24.5),
(305, 'TCT', 'Sư phạm tiếng Pháp', 'D03', 5, '7140233', 16.25),
(306, 'TCT', 'Sư phạm tiếng Pháp', 'D01', 5, '7140233', 16.25),
(307, 'TCT', 'Sư phạm tiếng Pháp', 'D14', 5, '7140233', 16.25),
(308, 'TCT', 'Sư phạm tiếng Pháp', 'D64', 5, '7140233', 16.25),
(309, 'TCT', 'Việt Nam học', 'C00', 33, '7310630', 24.5),
(310, 'TCT', 'Việt Nam học', 'D01', 33, '7310630', 24.5),
(311, 'TCT', 'Việt Nam học', 'D14', 32, '7310630', 24.5),
(312, 'TCT', 'Việt Nam học', 'D15', 32, '7310630', 24.5),
(313, 'TCT', 'Văn học', 'C00', 37, '7229030', 22.75),
(314, 'TCT', 'Văn học', 'D14', 37, '7229030', 22.75),
(315, 'TCT', 'Văn học', 'D15', 36, '7229030', 22.75),
(316, 'TCT', 'Ngôn ngữ Anh', 'D01', 60, '7220201', 23.5),
(317, 'TCT', 'Ngôn ngữ Anh', 'D14', 60, '7220201', 23.5),
(318, 'TCT', 'Ngôn ngữ Anh', 'D15', 60, '7220201', 23.5),
(319, 'TCT', 'Ngôn ngữ Pháp', 'D03', 15, '7220203', 18),
(320, 'TCT', 'Ngôn ngữ Pháp', 'D01', 15, '7220203', 18),
(321, 'TCT', 'Ngôn ngữ Pháp', 'D14', 15, '7220203', 18),
(322, 'TCT', 'Ngôn ngữ Pháp', 'D64', 15, '7220203', 18),
(323, 'TCT', 'Triết học', 'C00', 20, '7229001', 21.5),
(324, 'TCT', 'Triết học', 'D14', 20, '7229001', 21.5),
(325, 'TCT', 'Triết học', 'D15', 20, '7229001', 21.5),
(326, 'TCT', 'Triết học', 'C19', 20, '7229001', 21.5),
(327, 'TCT', 'Chính trị học', 'C00', 20, '7310201', 23.5),
(328, 'TCT', 'Chính trị học', 'D14', 20, '7310201', 23.5),
(329, 'TCT', 'Chính trị học', 'D15', 20, '7310201', 23.5),
(330, 'TCT', 'Chính trị học', 'C19', 20, '7310201', 23.5),
(331, 'TCT', 'Xã hội học', 'A01', 20, '7310301', 22.75),
(332, 'TCT', 'Xã hội học', 'C00', 20, '7310301', 22.75),
(333, 'TCT', 'Xã hội học', 'D01', 20, '7310301', 22.75),
(334, 'TCT', 'Xã hội học', 'C19', 20, '7310301', 22.75),
(335, 'TCT', 'Thông tin thư viện', 'A01', 15, '7320201', 17.75),
(336, 'TCT', 'Thông tin thư viện', 'D01', 15, '7320201', 17.75),
(337, 'TCT', 'Thông tin thư viện', 'D29', 15, '7320201', 17.75),
(338, 'TCT', 'Thông tin thư viện', 'D03', 15, '7320201', 17.75),
(339, 'TCT', 'Quản trị kinh doanh', 'A00', 30, '7340101', 22.5),
(340, 'TCT', 'Quản trị kinh doanh', 'A01', 30, '7340101', 22.5),
(341, 'TCT', 'Quản trị kinh doanh', 'D01', 30, '7340101', 22.5),
(342, 'TCT', 'Quản trị kinh doanh', 'C02', 30, '7340101', 22.5),
(343, 'TCT', 'Kinh tế', 'A00', 30, '7310101', 21.25),
(344, 'TCT', 'Kinh tế', 'A01', 30, '7310101', 21.25),
(345, 'TCT', 'Kinh tế', 'D01', 30, '7310101', 21.25),
(346, 'TCT', 'Kinh tế', 'C02', 30, '7310101', 21.25),
(347, 'TCT', 'Quản trị dịch vụ du lịch và lữ hành', 'A00', 28, '7810103', 22.5),
(348, 'TCT', 'Quản trị dịch vụ du lịch và lữ hành', 'A01', 28, '7810103', 22.5),
(349, 'TCT', 'Quản trị dịch vụ du lịch và lữ hành', 'D01', 27, '7810103', 22.5),
(350, 'TCT', 'Quản trị dịch vụ du lịch và lữ hành', 'C02', 27, '7810103', 22.5),
(351, 'TCT', 'Marketing', 'A00', 20, '7340115', 22.25),
(352, 'TCT', 'Marketing', 'A01', 20, '7340115', 22.25),
(353, 'TCT', 'Marketing', 'D01', 20, '7340115', 22.25),
(354, 'TCT', 'Marketing', 'C02', 20, '7340115', 22.25),
(355, 'TCT', 'Kinh doanh quốc tế', 'A00', 33, '7340120', 22.25),
(356, 'TCT', 'Kinh doanh quốc tế', 'A01', 33, '7340120', 22.25),
(357, 'TCT', 'Kinh doanh quốc tế', 'D01', 32, '7340120', 22.25),
(358, 'TCT', 'Kinh doanh quốc tế', 'C02', 32, '7340120', 22.25),
(359, 'TCT', 'Kinh doanh thương mại', 'A00', 28, '7340121', 21.25),
(360, 'TCT', 'Kinh doanh thương mại', 'A01', 28, '7340121', 21.25),
(361, 'TCT', 'Kinh doanh thương mại', 'D01', 27, '7340121', 21.25),
(362, 'TCT', 'Kinh doanh thương mại', 'C02', 27, '7340121', 21.25),
(363, 'TCT', 'Tài chính - ngân hàng', 'A00', 30, '7340201', 21.75),
(364, 'TCT', 'Tài chính - ngân hàng', 'A01', 30, '7340201', 21.75),
(365, 'TCT', 'Tài chính - ngân hàng', 'D01', 30, '7340201', 21.75),
(366, 'TCT', 'Tài chính - ngân hàng', 'C02', 30, '7340201', 21.75),
(367, 'TCT', 'Kế toán', 'A00', 30, '7340301', 22.75),
(368, 'TCT', 'Kế toán', 'A01', 30, '7340301', 22.75),
(369, 'TCT', 'Kế toán', 'D01', 30, '7340301', 22.75),
(370, 'TCT', 'Kế toán', 'C02', 30, '7340301', 22.75),
(371, 'TCT', 'Kiểm toán', 'A00', 25, '7340302', 21),
(372, 'TCT', 'Kiểm toán', 'A01', 25, '7340302', 21),
(373, 'TCT', 'Kiểm toán', 'D01', 25, '7340302', 21),
(374, 'TCT', 'Kiểm toán', 'C02', 25, '7340302', 21),
(375, 'TCT', 'Luật', 'A00', 70, '7380101', 25.25),
(376, 'TCT', 'Luật', 'C00', 70, '7380101', 25.25),
(377, 'TCT', 'Luật', 'D01', 70, '7380101', 25.25),
(378, 'TCT', 'Luật', 'D03', 70, '7380101', 25.25),
(379, 'TCT', 'Sinh học', 'B00', 55, '7420101', 17.5),
(380, 'TCT', 'Sinh học', 'D08', 55, '7420101', 17.5),
(381, 'TCT', 'Công nghệ sinh học', 'A00', 34, '7420201', 22.75),
(382, 'TCT', 'Công nghệ sinh học', 'B00', 33, '7420201', 22.75),
(383, 'TCT', 'Công nghệ sinh học', 'D07', 33, '7420201', 22.75),
(384, 'TCT', 'Công nghệ sinh học', 'D08', 33, '7420201', 22.75),
(385, 'TCT', 'Sinh học ứng dụng', 'A00', 15, '7420203', 18.75),
(386, 'TCT', 'Sinh học ứng dụng', 'B00', 15, '7420203', 18.75),
(387, 'TCT', 'Sinh học ứng dụng', 'A01', 15, '7420203', 18.75),
(388, 'TCT', 'Sinh học ứng dụng', 'D08', 15, '7420203', 18.75),
(389, 'TCT', 'Hóa học', 'A00', 20, '7440112', 19.75),
(390, 'TCT', 'Hóa học', 'B00', 20, '7440112', 19.75),
(391, 'TCT', 'Hóa học', 'D07', 20, '7440112', 19.75),
(392, 'TCT', 'Hóa dược', 'A00', 20, '7720203', 24),
(393, 'TCT', 'Hóa dược', 'B00', 20, '7720203', 24),
(394, 'TCT', 'Hóa dược', 'D07', 20, '7720203', 24),
(395, 'TCT', 'Khoa học môi trường', 'A00', 37, '7440301', 17),
(396, 'TCT', 'Khoa học môi trường', 'B00', 37, '7440301', 17),
(397, 'TCT', 'Khoa học môi trường', 'D07', 37, '7440301', 17),
(398, 'TCT', 'Khoa học đất', 'B00', 20, '7620103', 15.5),
(399, 'TCT', 'Khoa học đất', 'A00', 20, '7620103', 15.5),
(400, 'TCT', 'Khoa học đất', 'D07', 20, '7620103', 15.5),
(401, 'TCT', 'Khoa học đất', 'D08', 20, '7620103', 15.5),
(402, 'TCT', 'Toán ứng dụng', 'A00', 20, '7460112', 15.5),
(403, 'TCT', 'Toán ứng dụng', 'A01', 20, '7460112', 15.5),
(404, 'TCT', 'Toán ứng dụng', 'B00', 20, '7460112', 15.5),
(405, 'TCT', 'Khoa học máy tính', 'A00', 60, '7480101', 16.5),
(406, 'TCT', 'Khoa học máy tính', 'A01', 60, '7480101', 16.5),
(407, 'TCT', 'Mạng máy tính và truyền thông dữ liệu', 'A00', 60, '7480102', 18.25),
(408, 'TCT', 'Mạng máy tính và truyền thông dữ liệu', 'A01', 60, '7480102', 18.25),
(409, 'TCT', 'Kỹ thuật phần mềm', 'A00', 70, '7480103', 20.5),
(410, 'TCT', 'Kỹ thuật phần mềm', 'A01', 70, '7480103', 20.5),
(411, 'TCT', 'Hệ thống thông tin', 'A00', 50, '7480104', 16.5),
(412, 'TCT', 'Hệ thống thông tin', 'A01', 50, '7480104', 16.5),
(413, 'TCT', 'Công nghệ thông tin', 'A00', 120, '7480201', 20.25),
(414, 'TCT', 'Công nghệ thông tin', 'A01', 120, '7480201', 20.25),
(415, 'TCT', 'Công nghệ hóa học', 'A00', 30, '7510401', 21.25),
(416, 'TCT', 'Công nghệ hóa học', 'B00', 30, '7510401', 21.25),
(417, 'TCT', 'Công nghệ hóa học', 'A01', 30, '7510401', 21.25),
(418, 'TCT', 'Công nghệ hóa học', 'D07', 30, '7510401', 21.25),
(419, 'TCT', 'Kỹ thuật vật liệu', 'A00', 15, '7520309', 15.5),
(420, 'TCT', 'Kỹ thuật vật liệu', 'B00', 15, '7520309', 15.5),
(421, 'TCT', 'Kỹ thuật vật liệu', 'A01', 15, '7520309', 15.5),
(422, 'TCT', 'Kỹ thuật vật liệu', 'D07', 15, '7520309', 15.5),
(423, 'TCT', 'Quản lý công nghiệp', 'A00', 40, '7510601', 18.75),
(424, 'TCT', 'Quản lý công nghiệp', 'A01', 40, '7510601', 18.75),
(425, 'TCT', 'Quản lý công nghiệp', 'D01', 40, '7510601', 18.75),
(426, 'TCT', 'Kỹ thuật cơ khí', 'A00', 125, '7520103', 20.5),
(427, 'TCT', 'Kỹ thuật cơ khí', 'A01', 125, '7520103', 20.5),
(428, 'TCT', 'Kỹ thuật cơ điện tử', 'A00', 55, '7520114', 20.5),
(429, 'TCT', 'Kỹ thuật cơ điện tử', 'A01', 55, '7520114', 20.5),
(430, 'TCT', 'Kỹ thuật điện', 'A00', 50, '7520201', 20),
(431, 'TCT', 'Kỹ thuật điện', 'A01', 50, '7520201', 20),
(432, 'TCT', 'Kỹ thuật điện', 'D07', 50, '7520201', 20),
(433, 'TCT', 'Kỹ thuật điện tử - viễn thông', 'A00', 55, '7520207', 18.25),
(434, 'TCT', 'Kỹ thuật điện tử - viễn thông', 'A01', 55, '7520207', 18.25),
(435, 'TCT', 'Kỹ thuật máy tính', 'A00', 60, '7480106', 16.5),
(436, 'TCT', 'Kỹ thuật máy tính', 'A01', 60, '7480106', 16.5),
(437, 'TCT', 'Kỹ thuật điều khiển và tự động hóa', 'A00', 55, '7520216', 19),
(438, 'TCT', 'Kỹ thuật điều khiển và tự động hóa', 'A01', 55, '7520216', 19),
(439, 'TCT', 'Kỹ thuật môi trường', 'A00', 30, '7520320', 16.5),
(440, 'TCT', 'Kỹ thuật môi trường', 'B00', 30, '7520320', 16.5),
(441, 'TCT', 'Kỹ thuật môi trường', 'D07', 30, '7520320', 16.5),
(442, 'TCT', 'Kỹ thuật môi trường', 'A01', 30, '7520320', 16.5),
(443, 'TCT', 'Vật lí kỹ thuật', 'A00', 17, '7520401', 15.5),
(444, 'TCT', 'Vật lí kỹ thuật', 'A01', 17, '7520401', 15.5),
(445, 'TCT', 'Vật lí kỹ thuật', 'A02', 16, '7520401', 15.5),
(446, 'TCT', 'Công nghệ thực phẩm', 'A00', 40, '7540101', 21.75),
(447, 'TCT', 'Công nghệ thực phẩm', 'B00', 40, '7540101', 21.75),
(448, 'TCT', 'Công nghệ thực phẩm', 'D07', 40, '7540101', 21.75),
(449, 'TCT', 'Công nghệ thực phẩm', 'A01', 40, '7540101', 21.75),
(450, 'TCT', 'Công nghệ sau thu hoạch', 'A00', 18, '7540104', 18),
(451, 'TCT', 'Công nghệ sau thu hoạch', 'B00', 18, '7540104', 18),
(452, 'TCT', 'Công nghệ sau thu hoạch', 'D07', 16, '7540104', 18),
(453, 'TCT', 'Công nghệ sau thu hoạch', 'A01', 16, '7540104', 18),
(454, 'TCT', 'Công nghệ chế biến thủy sản', 'A00', 23, '7540105', 19),
(455, 'TCT', 'Công nghệ chế biến thủy sản', 'B00', 23, '7540105', 19),
(456, 'TCT', 'Công nghệ chế biến thủy sản', 'D07', 22, '7540105', 19),
(457, 'TCT', 'Công nghệ chế biến thủy sản', 'A01', 22, '7540105', 19),
(458, 'TCT', 'Kỹ thuật xây dựng', 'A00', 80, '7580201', 19.25),
(459, 'TCT', 'Kỹ thuật xây dựng', 'A01', 80, '7580201', 19.25),
(460, 'TCT', 'Kỹ thuật xây dựng công trình thủy lợi', 'A00', 30, '7580202', 15.5),
(461, 'TCT', 'Kỹ thuật xây dựng công trình thủy lợi', 'A01', 30, '7580202', 15.5),
(462, 'TCT', 'Kỹ thuật xây dựng công trình giao thông', 'A00', 30, '7580202', 18),
(463, 'TCT', 'Kỹ thuật xây dựng công trình giao thông', 'A01', 30, '7580202', 18),
(464, 'TCT', 'Kỹ thuật tài nguyên nước', 'A00', 20, '7580212', 15.5),
(465, 'TCT', 'Kỹ thuật tài nguyên nước', 'A01', 20, '7580212', 15.5),
(466, 'TCT', 'Kỹ thuật tài nguyên nước', 'D07', 20, '7580212', 15.5),
(467, 'TCT', 'Chăn nuôi', 'A00', 30, '7620105', 16.25),
(468, 'TCT', 'Chăn nuôi', 'B00', 30, '7620105', 16.25),
(469, 'TCT', 'Chăn nuôi', 'A02', 30, '7620105', 16.25),
(470, 'TCT', 'Chăn nuôi', 'D08', 30, '7620105', 16.25),
(471, 'TCT', 'Nông học', 'B00', 20, '7620109', 20.25),
(472, 'TCT', 'Nông học', 'D08', 20, '7620109', 20.25),
(473, 'TCT', 'Nông học', 'D07', 20, '7620109', 20.25),
(474, 'TCT', 'Khoa học cây trồng', 'B00', 38, '7620110', 17.25),
(475, 'TCT', 'Khoa học cây trồng', 'A02', 38, '7620110', 17.25),
(476, 'TCT', 'Khoa học cây trồng', 'D07', 36, '7620110', 17.25),
(477, 'TCT', 'Khoa học cây trồng', 'D08', 36, '7620110', 17.25),
(478, 'TCT', 'Bảo vệ thực vật', 'B00', 47, '7620112', 20.75),
(479, 'TCT', 'Bảo vệ thực vật', 'D07', 47, '7620112', 20.75),
(480, 'TCT', 'Bảo vệ thực vật', 'D08', 46, '7620112', 20.75),
(481, 'TCT', 'Công nghệ rau quả và cảnh quan', 'B00', 15, '7620113', 15.5),
(482, 'TCT', 'Công nghệ rau quả và cảnh quan', 'D07', 15, '7620113', 15.5),
(483, 'TCT', 'Công nghệ rau quả và cảnh quan', 'D08', 15, '7620113', 15.5),
(484, 'TCT', 'Công nghệ rau quả và cảnh quan', 'A00', 15, '7620113', 15.5),
(485, 'TCT', 'Kinh tế nông nghiệp', 'A00', 30, '7620115', 18.5),
(486, 'TCT', 'Kinh tế nông nghiệp', 'A01', 30, '7620115', 18.5),
(487, 'TCT', 'Kinh tế nông nghiệp', 'D01', 30, '7620115', 18.5),
(488, 'TCT', 'Kinh tế nông nghiệp', 'C02', 30, '7620115', 18.5),
(489, 'TCT', 'Phát triển nông thôn', 'A00', 20, '7620116', 15.5),
(490, 'TCT', 'Phát triển nông thôn', 'B00', 20, '7620116', 15.5),
(491, 'TCT', 'Phát triển nông thôn', 'A01', 20, '7620116', 15.5),
(492, 'TCT', 'Phát triển nông thôn', 'D07', 20, '7620116', 15.5),
(493, 'TCT', 'Lâm sinh', 'A00', 15, '7620205', 15.5),
(494, 'TCT', 'Lâm sinh', 'A01', 15, '7620205', 15.5),
(495, 'TCT', 'Lâm sinh', 'B00', 15, '7620205', 15.5),
(496, 'TCT', 'Lâm sinh', 'D08', 15, '7620205', 15.5),
(497, 'TCT', 'Nuôi trồng thủy sản', 'B00', 35, '7620301', 17),
(498, 'TCT', 'Nuôi trồng thủy sản', 'A00', 35, '7620301', 17),
(499, 'TCT', 'Nuôi trồng thủy sản', 'D07', 35, '7620301', 17),
(500, 'TCT', 'Nuôi trồng thủy sản', 'D07', 35, '7620301', 17),
(501, 'TCT', 'Bệnh học thủy sản', 'B00', 15, '7620302', 16.25),
(502, 'TCT', 'Bệnh học thủy sản', 'A00', 15, '7620302', 16.25),
(503, 'TCT', 'Bệnh học thủy sản', 'D07', 15, '7620302', 16.25),
(504, 'TCT', 'Bệnh học thủy sản', 'D08', 15, '7620302', 16.25),
(505, 'TCT', 'Quản lý thủy sản', 'B00', 15, '7620305', 15.5),
(506, 'TCT', 'Quản lý thủy sản', 'A00', 15, '7620305', 15.5),
(507, 'TCT', 'Quản lý thủy sản', 'D07', 15, '7620305', 15.5),
(508, 'TCT', 'Quản lý thủy sản', 'D08', 15, '7620305', 15.5),
(509, 'TCT', 'Thú y', 'B00', 35, '7640101', 21.75),
(510, 'TCT', 'Thú y', 'A02', 35, '7640101', 21.75),
(511, 'TCT', 'Thú y', 'D07', 35, '7640101', 21.75),
(512, 'TCT', 'Thú y', 'D08', 35, '7640101', 21.75),
(513, 'TCT', 'Quản lý tài nguyên và môi trường', 'A00', 15, '7850101', 21),
(514, 'TCT', 'Quản lý tài nguyên và môi trường', 'A01', 15, '7850101', 21),
(515, 'TCT', 'Quản lý tài nguyên và môi trường', 'B00', 15, '7850101', 21),
(516, 'TCT', 'Quản lý tài nguyên và môi trường', 'D07', 15, '7850101', 21),
(517, 'TCT', 'Kinh tế tài nguyên thiên nhiên', 'A00', 15, '7850102', 18.75),
(518, 'TCT', 'Kinh tế tài nguyên thiên nhiên', 'A01', 15, '7850102', 18.75),
(519, 'TCT', 'Kinh tế tài nguyên thiên nhiên', 'D01', 15, '7850102', 18.75),
(520, 'TCT', 'Kinh tế tài nguyên thiên nhiên', 'C02', 15, '7850102', 18.75),
(521, 'TCT', 'Quản lý đất đai', 'A00', 23, '7850103', 19),
(522, 'TCT', 'Quản lý đất đai', 'A01', 23, '7850103', 19),
(523, 'TCT', 'Quản lý đất đai', 'B00', 23, '7850103', 19),
(524, 'TCT', 'Quản lý đất đai', 'D07', 23, '7850103', 19);
--
-- Chỉ mục cho các bảng đã đổ
--
--
-- Chỉ mục cho bảng `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`ID`);
--
-- Chỉ mục cho bảng `fuzzy_set`
--
ALTER TABLE `fuzzy_set`
ADD PRIMARY KEY (`ID`);
--
-- Chỉ mục cho bảng `khoi_nganh`
--
ALTER TABLE `khoi_nganh`
ADD PRIMARY KEY (`Khoi_Nganh_ID`);
--
-- Chỉ mục cho bảng `khoi_thi`
--
ALTER TABLE `khoi_thi`
ADD PRIMARY KEY (`Khoi_Thi_ID`);
--
-- Chỉ mục cho bảng `linh_vuc_dao_tao`
--
ALTER TABLE `linh_vuc_dao_tao`
ADD PRIMARY KEY (`Linh_Vuc_Dao_Tao_ID`),
ADD KEY `Khoi_Nganh_ID` (`Khoi_Nganh_ID`);
--
-- Chỉ mục cho bảng `nganh`
--
ALTER TABLE `nganh`
ADD PRIMARY KEY (`Nganh_ID`),
ADD KEY `Nhom_Nganh_ID` (`Nhom_Nganh_ID`);
--
-- Chỉ mục cho bảng `nhom_nganh`
--
ALTER TABLE `nhom_nganh`
ADD PRIMARY KEY (`Nhom_Nganh_ID`),
ADD KEY `Linh_Vuc_Dao_Tao_ID` (`Linh_Vuc_Dao_Tao_ID`);
--
-- Chỉ mục cho bảng `thuoc_tinh_bai_toan_1`
--
ALTER TABLE `thuoc_tinh_bai_toan_1`
ADD PRIMARY KEY (`ID`);
--
-- Chỉ mục cho bảng `thuoc_tinh_bai_toan_2`
--
ALTER TABLE `thuoc_tinh_bai_toan_2`
ADD PRIMARY KEY (`ID`);
--
-- Chỉ mục cho bảng `to_chuc_dao_tao`
--
ALTER TABLE `to_chuc_dao_tao`
ADD PRIMARY KEY (`To_Chuc_Dao_Tao_ID`);
--
-- Chỉ mục cho bảng `trong_so`
--
ALTER TABLE `trong_so`
ADD PRIMARY KEY (`ID`);
--
-- Chỉ mục cho bảng `tuyen_sinh`
--
ALTER TABLE `tuyen_sinh`
ADD PRIMARY KEY (`Tuyen_Sinh_ID`);
--
-- AUTO_INCREMENT cho các bảng đã đổ
--
--
-- AUTO_INCREMENT cho bảng `khoi_nganh`
--
ALTER TABLE `khoi_nganh`
MODIFY `Khoi_Nganh_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT cho bảng `khoi_thi`
--
ALTER TABLE `khoi_thi`
MODIFY `Khoi_Thi_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=186;
--
-- AUTO_INCREMENT cho bảng `linh_vuc_dao_tao`
--
ALTER TABLE `linh_vuc_dao_tao`
MODIFY `Linh_Vuc_Dao_Tao_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT cho bảng `nganh`
--
ALTER TABLE `nganh`
MODIFY `Nganh_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=369;
--
-- AUTO_INCREMENT cho bảng `nhom_nganh`
--
ALTER TABLE `nhom_nganh`
MODIFY `Nhom_Nganh_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=95;
--
-- AUTO_INCREMENT cho bảng `thuoc_tinh_bai_toan_2`
--
ALTER TABLE `thuoc_tinh_bai_toan_2`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT cho bảng `to_chuc_dao_tao`
--
ALTER TABLE `to_chuc_dao_tao`
MODIFY `To_Chuc_Dao_Tao_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=119;
--
-- AUTO_INCREMENT cho bảng `tuyen_sinh`
--
ALTER TABLE `tuyen_sinh`
MODIFY `Tuyen_Sinh_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=525;
--
-- Các ràng buộc cho các bảng đã đổ
--
--
-- Các ràng buộc cho bảng `linh_vuc_dao_tao`
--
ALTER TABLE `linh_vuc_dao_tao`
ADD CONSTRAINT `linh_vuc_dao_tao_ibfk_1` FOREIGN KEY (`Khoi_Nganh_ID`) REFERENCES `khoi_nganh` (`Khoi_Nganh_ID`);
--
-- Các ràng buộc cho bảng `nganh`
--
ALTER TABLE `nganh`
ADD CONSTRAINT `nganh_ibfk_1` FOREIGN KEY (`Nhom_Nganh_ID`) REFERENCES `nhom_nganh` (`Nhom_Nganh_ID`);
--
-- Các ràng buộc cho bảng `nhom_nganh`
--
ALTER TABLE `nhom_nganh`
ADD CONSTRAINT `nhom_nganh_ibfk_1` FOREIGN KEY (`Linh_Vuc_Dao_Tao_ID`) REFERENCES `linh_vuc_dao_tao` (`Linh_Vuc_Dao_Tao_ID`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn trường</title>
<?php
include("meta.php");
?>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid #52D017;
width: 50%;
}
th {
height: 50px;
}
td {
height: 30px;
text-align: center;
}
</style>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_2.php");
?>
<div class="main1">
<p>Bảng dưới đây xếp hạng mức độ phù hợp của từng Tổ chức Đào tạo đối với thí sinh theo thứ tự giảm dần:</p>
<br>
<table>
<?php
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối với cơ sở dữ liệu");
mysqli_set_charset($connect, "utf8");
$ten_nganh_da_chon = $_POST['ten_nganh_da_chon'];
$query = "SELECT to_chuc_dao_tao.Ten_To_Chuc_Dao_Tao, to_chuc_dao_tao.Ma_To_Chuc_Dao_Tao FROM tuyen_sinh JOIN to_chuc_dao_tao WHERE Ten_Nganh='$ten_nganh_da_chon' AND to_chuc_dao_tao.Ma_To_Chuc_Dao_Tao = tuyen_sinh.Ma_To_Chuc_Dao_Tao";
$query_result = mysqli_query($connect, $query);
$query_result_count = mysqli_num_rows($query_result);
if ($query_result_count == 0) {
header("location:suggest2_none_result.php");
}
else{
$result1 = [];
$result2 = [];
while ($row = mysqli_fetch_assoc($query_result)) {
$result1[] = $row['Ten_To_Chuc_Dao_Tao'];
$result2[] = $row['Ma_To_Chuc_Dao_Tao'];
}
$tap_phuong_an = [];
foreach (array_unique($result1) as $key => $value) {
$tap_phuong_an[] = $value;
}
$tap_ma_phuong_an = [];
foreach (array_unique($result2) as $key => $value) {
$tap_ma_phuong_an[] = $value;
}
$attribute_id = [];
$query = "SELECT ID FROM thuoc_tinh_bai_toan_2;";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$attribute_id[] = "attribute_" . $row['ID'];
}
$weight_id = [];
foreach ($attribute_id as $key => $value) {
$weight_language_value = $_POST[$value];
$query = "SELECT ID FROM trong_so WHERE Trong_So_Bien_Ngon_Ngu='$weight_language_value'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$weight_id[] = (int)$row['ID'];
}
}
$base_sum = array_sum($weight_id);
$weight_base = 1 / $base_sum;
$weight = [];
foreach ($weight_id as $key => $value) {
$weight[] = $value * $weight_base;
}
$ranking = [];
$kha_nang_tim_viec = [];
$hoc_phi = [];
$moi_truong_hoc_tap = [];
foreach ($tap_phuong_an as $key => $value) {
$query = "SELECT * FROM to_chuc_dao_tao WHERE Ten_To_Chuc_Dao_Tao='$value'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$ranking[] = (int)$row['Ranking'];
$kha_nang_tim_viec[] = (float)$row['Kha_Nang_Tim_Viec'];
$hoc_phi[] = (float)$row['Hoc_Phi'];
$moi_truong_hoc_tap[] = $row['Moi_Truong_Hoc_Tap'];
}
}
$so_chi_tieu = [];
$diem_nguong = [];
foreach ($tap_ma_phuong_an as $key => $value) {
$so_chi_tieu[$value] = 0;
$diem_nguong[$value] = 100;
$query = "SELECT So_Chi_Tieu, Diem_Nguong FROM tuyen_sinh WHERE Ma_To_Chuc_Dao_Tao='$value'AND Ten_Nganh='$ten_nganh_da_chon'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$so_chi_tieu[$value] += (int)$row['So_Chi_Tieu'];
if ((float)$row['Diem_Nguong'] < $diem_nguong[$value])
$diem_nguong[$value] = (float)$row['Diem_Nguong'];
}
}
$diem_thi = [];
$diem_thi[] = (float)$_POST['mon_1'];
$diem_thi[] = (float)$_POST['mon_2'];
$diem_thi[] = (float)$_POST['mon_3'];
$diem_thi[] = (float)$_POST['mon_4'];
$tong_diem = array_sum($diem_thi);
$chenh_lech_diem_chuan = [];
foreach ($diem_nguong as $key => $value) {
$chenh_lech_diem_chuan[$key] = abs($value - $tong_diem);
}
// -tính khoảng cách
function get_infor_from_address($address = null) {
$prepAddr = str_replace(' ', '+', stripUnicode($address));
$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output = json_decode($geocode);
return $output;
}
// Loại bỏ dấu tiếng Việt để cho kết quả chính xác hơn
function stripUnicode($str){
if (!$str) return false;
$unicode = array(
'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
'd'=>'đ|Đ',
'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
'i'=>'í|ì|ỉ|ĩ|ị|Í|Ì|Ỉ|Ĩ|Ị',
'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ|Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
'y'=>'ý|ỳ|ỷ|ỹ|ỵ|Ý|Ỳ|Ỷ|Ỹ|Ỵ'
);
foreach($unicode as $nonUnicode=>$uni) $str = preg_replace("/($uni)/i",$nonUnicode,$str);
return $str;
}
$address_1 = $_POST['address'];
$location_1 = get_infor_from_address($address_1);
$latitude_1 = $location_1->results[0]->geometry->location->lat;
$longitude_1 = $location_1->results[0]->geometry->location->lng;
$address_2 = [];
foreach ($tap_ma_phuong_an as $key => $value) {
$query = "SELECT Vi_Tri FROM to_chuc_dao_tao WHERE Ma_To_Chuc_Dao_Tao='$value'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$address_2[] = $row['Vi_Tri'];
}
}
$location_2 = [];
$latitude_2 = [];
$longitude_2 = [];
foreach ($address_2 as $key => $value) {
$location_2[] = get_infor_from_address($value);
$latitude_2[] = $location_2[$key]->results[0]->geometry->location->lat;
$longitude_2[] = $location_2[$key]->results[0]->geometry->location->lng;
}
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$kilometers = $miles * 1.609344;
return $kilometers;
}
$distance = [];
for($i=0; $i<count($address_2); $i++){
$distance[] = getDistanceBetweenPointsNew($latitude_1, $longitude_1, $latitude_2[$i], $longitude_2[$i]);
}
//TOPSIS
//Bước 1: Chuẩn hóa:
// khử mờ biến ngôn ngữ:
foreach ($moi_truong_hoc_tap as $key => $value) {
$query = "SELECT * FROM fuzzy_set WHERE Bien_Ngon_Ngu='$value'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$fuzzy_set_a1[] = $row["a1"];
$fuzzy_set_b1[] = $row["b1"];
$fuzzy_set_c1[] = $row["c1"];
$fuzzy_set_d1[] = $row["d1"];
$fuzzy_set_h11[] = $row["h11"];
$fuzzy_set_h12[] = $row["h12"];
$fuzzy_set_a2[] = $row["a2"];
$fuzzy_set_b2[] = $row["b2"];
$fuzzy_set_c2[] = $row["c2"];
$fuzzy_set_d2[] = $row["d2"];
$fuzzy_set_h21[] = $row["h21"];
$fuzzy_set_h22[] = $row["h22"];
}
}
$fuzzy_set_mount = count($fuzzy_set_a1);
$n = 2;
$he_so_lech = $n / (2 * $n + 1);
for ($i = 0; $i < $fuzzy_set_mount; $i++) {
$tich_hop_trung_binh_can_duoi[$i] = ($fuzzy_set_a1[$i] + $fuzzy_set_d1[$i]) / 2 +
$he_so_lech * ($fuzzy_set_b1[$i] - $fuzzy_set_a1[$i] - $fuzzy_set_d1[$i] + $fuzzy_set_c1[$i]);
$tich_hop_trung_binh_can_tren[$i] = ($fuzzy_set_a2[$i] + $fuzzy_set_d2[$i]) / 2 +
$he_so_lech * ($fuzzy_set_b2[$i] - $fuzzy_set_a2[$i] - $fuzzy_set_d2[$i] + $fuzzy_set_c2[$i]);
$tich_hop_trung_binh[$i] = ($tich_hop_trung_binh_can_tren[$i] + $tich_hop_trung_binh_can_duoi[$i]) / 2;
}
}
//Chuẩn hóa giá trị các thuộc tính theo CHUẨN HÓA TUYẾN TÍNH
$attribute_1 = $ranking; //tiêu chí giá
$attribute_1_chuan_hoa = [];
foreach ($attribute_1 as $key => $value) {
$attribute_1_chuan_hoa[] = 1 / $value;
}
$attribute_2 = $so_chi_tieu;
$attribute_2_chuan_hoa = [];
$attribute_2_max = max($attribute_2);
foreach ($attribute_2 as $key => $value) {
$attribute_2_chuan_hoa[] = $value / $attribute_2_max;
}
$attribute_3 = $chenh_lech_diem_chuan; //tiêu chí giá
$attribute_3_chuan_hoa = [];
foreach ($attribute_3 as $key => $value) {
$attribute_3_chuan_hoa[] = 1 / $value;
}
$attribute_4 = $kha_nang_tim_viec;
$attribute_4_chuan_hoa = [];
$attribute_4_max = max($attribute_4);
foreach ($attribute_4 as $key => $value) {
$attribute_4_chuan_hoa[] = $value / $attribute_4_max;
}
$attribute_5 = $hoc_phi; // tiêu chí giá
$attribute_5_chuan_hoa = [];
foreach ($attribute_5 as $key => $value) {
$attribute_5_chuan_hoa[] = 1 / $value;
}
$attribute_6 = $tich_hop_trung_binh;
$attribute_6_chuan_hoa = [];
$attribute_6_max = max($attribute_6);
foreach ($attribute_6 as $key => $value) {
$attribute_6_chuan_hoa[] = $value / $attribute_6_max;
}
$attribute_7 = $distance; // tiêu chí giá
$attribute_7_chuan_hoa = [];
foreach ($attribute_7 as $key => $value) {
$attribute_7_chuan_hoa[] = 1 / $value;
}
//Bước 2: Tính giá trị theo trọng số:
$trong_so = $weight;
$attribute_1_trong_so = [];
foreach ($attribute_1_chuan_hoa as $key => $value) {
$attribute_1_trong_so[] = $value * $trong_so[0];
}
$attribute_2_trong_so = [];
foreach ($attribute_2_chuan_hoa as $key => $value) {
$attribute_2_trong_so[] = $value * $trong_so[1];
}
$attribute_3_trong_so = [];
foreach ($attribute_3_chuan_hoa as $key => $value) {
$attribute_3_trong_so[] = $value * $trong_so[2];
}
$attribute_4_trong_so = [];
foreach ($attribute_4_chuan_hoa as $key => $value) {
$attribute_4_trong_so[] = $value * $trong_so[3];
}
$attribute_5_trong_so = [];
foreach ($attribute_5_chuan_hoa as $key => $value) {
$attribute_5_trong_so[] = $value * $trong_so[4];
}
$attribute_6_trong_so = [];
foreach ($attribute_6_chuan_hoa as $key => $value) {
$attribute_6_trong_so[] = $value * $trong_so[5];
}
$attribute_7_trong_so = [];
foreach ($attribute_7_chuan_hoa as $key => $value) {
$attribute_7_trong_so[] = $value * $trong_so[6];
}
//Bước 3: Tìm phương án lý tưởng tốt và phương án lý tưởng xấu
$phuong_an_ly_tuong_tot = [];
$phuong_an_ly_tuong_tot[] = max($attribute_1_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_2_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_3_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_4_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_5_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_6_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_7_trong_so);
$phuong_an_ly_tuong_xau = [];
$phuong_an_ly_tuong_xau[] = min($attribute_1_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_2_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_3_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_4_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_5_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_6_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_7_trong_so);
//Bước 4: Tính khoảng cách của từng phương án đến 2 phương án lý tưởng tốt và lý tưởng xấu
$attribute_1_tru_ly_tuong_tot = [];
foreach ($attribute_1_trong_so as $key => $value) {
$attribute_1_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[0] - $value;
}
$attribute_2_tru_ly_tuong_tot = [];
foreach ($attribute_2_trong_so as $key => $value) {
$attribute_2_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[1] - $value;
}
$attribute_3_tru_ly_tuong_tot = [];
foreach ($attribute_3_trong_so as $key => $value) {
$attribute_3_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[2] - $value;
}
$attribute_4_tru_ly_tuong_tot = [];
foreach ($attribute_4_trong_so as $key => $value) {
$attribute_4_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[3] - $value;
}
$attribute_5_tru_ly_tuong_tot = [];
foreach ($attribute_5_trong_so as $key => $value) {
$attribute_5_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[4] - $value;
}
$attribute_6_tru_ly_tuong_tot = [];
foreach ($attribute_6_trong_so as $key => $value) {
$attribute_6_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[5] - $value;
}
$attribute_7_tru_ly_tuong_tot = [];
foreach ($attribute_7_trong_so as $key => $value) {
$attribute_7_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[6] - $value;
}
$khoang_cach_den_phuong_an_ly_tuong_tot = [];
for($i=0; $i<count($attribute_1); $i++){
$khoang_cach_den_phuong_an_ly_tuong_tot[$i] = sqrt(
pow($attribute_1_tru_ly_tuong_tot[$i], 2) +
pow($attribute_2_tru_ly_tuong_tot[$i], 2) +
pow($attribute_3_tru_ly_tuong_tot[$i], 2) +
pow($attribute_4_tru_ly_tuong_tot[$i], 2) +
pow($attribute_5_tru_ly_tuong_tot[$i], 2) +
pow($attribute_6_tru_ly_tuong_tot[$i], 2) +
pow($attribute_7_tru_ly_tuong_tot[$i], 2)
);
}
$attribute_1_tru_ly_tuong_xau = [];
foreach ($attribute_1_trong_so as $key => $value) {
$attribute_1_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[0];
}
$attribute_2_tru_ly_tuong_xau = [];
foreach ($attribute_2_trong_so as $key => $value) {
$attribute_2_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[1];
}
$attribute_3_tru_ly_tuong_xau = [];
foreach ($attribute_3_trong_so as $key => $value) {
$attribute_3_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[2];
}
$attribute_4_tru_ly_tuong_xau = [];
foreach ($attribute_4_trong_so as $key => $value) {
$attribute_4_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[3];
}
$attribute_5_tru_ly_tuong_xau = [];
foreach ($attribute_5_trong_so as $key => $value) {
$attribute_5_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[4];
}
$attribute_6_tru_ly_tuong_xau = [];
foreach ($attribute_6_trong_so as $key => $value) {
$attribute_6_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[5];
}
$attribute_7_tru_ly_tuong_xau = [];
foreach ($attribute_7_trong_so as $key => $value) {
$attribute_7_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[6];
}
$khoang_cach_den_phuong_an_ly_tuong_xau = [];
for($i=0; $i<count($attribute_1); $i++){
$khoang_cach_den_phuong_an_ly_tuong_xau[$i] = sqrt(
pow($attribute_1_tru_ly_tuong_xau[$i], 2) +
pow($attribute_2_tru_ly_tuong_xau[$i], 2) +
pow($attribute_3_tru_ly_tuong_xau[$i], 2) +
pow($attribute_4_tru_ly_tuong_xau[$i], 2) +
pow($attribute_5_tru_ly_tuong_xau[$i], 2) +
pow($attribute_6_tru_ly_tuong_xau[$i], 2) +
pow($attribute_7_tru_ly_tuong_xau[$i], 2)
);
}
//Bước 5: Tính độ tương tự tới phương án lý tưởng tốt
$do_tuong_tu = [];
for($i=0; $i<count($attribute_1); $i++){
$do_tuong_tu[$i] = $khoang_cach_den_phuong_an_ly_tuong_xau[$i] / ($khoang_cach_den_phuong_an_ly_tuong_xau[$i] + $khoang_cach_den_phuong_an_ly_tuong_tot[$i]);
}
//Bước 6: Xếp hạng các phương án và đưa ra gợi ý
$sap_xep = [];
foreach ($do_tuong_tu as $key => $value) {
foreach ($tap_phuong_an as $key1 => $value1) {
if($key == $key1)
$sap_xep[$value1] = $value;
}
}
arsort($sap_xep);
echo '<th>';
echo "Tên Tổ chức Đào tạo";
echo '</th>';
// echo '<th>';
// echo "Ranking";
// echo '</th>';
// echo '<th>';
// echo "Số chỉ tiêu";
// echo '</th>';
// echo '<th>';
// echo "Chênh lệch điểm chuẩn";
// echo '</th>';
// echo '<th>';
// echo "Khả năng tìm việc";
// echo '</th>';
// echo '<th>';
// echo "Học phí";
// echo '</th>';
// echo '<th>';
// echo "Môi trường học tập";
// echo '</th>';
// echo '<th>';
// echo "Khoảng cách";
// echo '</th>';
echo '<th>';
echo "Xếp hạng";
echo '</th>';
$rank = 1;
foreach ($sap_xep as $key => $value) {
echo '<tr>';
echo '<td>';
echo $key;
echo '</td>';
echo '<td>';
echo $rank;
echo '</td>';
echo '</tr>';
$rank++;
}
mysqli_close($connect);
?>
</table>
<br>
<p>
<b><a href="index.php">HoTroTuyenSinh.com</a> gợi ý thí sinh nên chọn Tổ chức Đào tạo có mức độ phù hợp cao nhất.</b>
</p>
<br>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><hr>
<p>
<b>Mức độ yêu thích đối với từng Ngành</b>
</p>
<form id="atribute_1_4_1" action="" method="">
<table>
<tr>
<td>Tên Ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
</table>
<br>
<input type="submit" name="atribute_1_4_1_submit" value="Gửi đánh giá">
</form>
<br>
<br><file_sep><!DOCTYPE html>
<html>
<head>
<title><NAME> | Thông tin truyển sinh</title>
<?php
include("meta.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("sideright.php");
?>
<div class="main">
<form action="search.php"
method="POST"
name="search_form"
onsubmit="return(search_validate())">
<input type="text" name="school_infor" placeholder="Nhập tên trường, mã trường" required>
<input type="submit" name="search_button" value="Tìm kiếm">
</form>
</div>
<div class="main">
<?php
include("school_infor_pass.php");
?>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn trường</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_2.php");
?>
<div class="main1">
<h2>
Rất xin lỗi <a href="index.php">HoTroTuyenSinh.com</a> không tìm thấy mã ngành này...
</h2>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><hr>
<p>
<b>Mức độ yêu thích đối với từng Nhóm ngành</b>
</p>
<form id="atribute_1_3_1" action="" method="">
<table>
<tr>
<td>Tên Nhóm ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Nhóm ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Nhóm ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Nhóm ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên Nhóm ngành:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
</table>
<br>
<input type="submit" name="atribute_1_3_1_submit" value="Gửi đánh giá">
</form>
<br>
<br><file_sep>function search_validate(){
if (document.search_form.school_info.value == "") {
alert("Hãy nhập Tên trường hoặc Mã trường để thực hiện tìm kiếm!");
//document.search_form.Name.focus();
//return false;
}
return (true);
}
function atribute_1_1_2_validate(){
var ToanHoc = document.getElementById('ToanHoc');
if (ToanHoc.value == "") {
alert("Hãy nhập điểm tổng kết môn Toán Học");
//location.reload(true);
}
if (ToanHoc.value < 0 || ToanHoc.value > 10) {
alert("Điểm tổng kết môn Toán Học phải trong khoảng từ 0 đến 10.");
}
if (isNaN(ToanHoc.value) == true) {
alert("Điểm tổng kết môn Toán Học phải là giá trị số!");
}
var NguVan = document.getElementById('NguVan');
if (NguVan.value == "") {
alert("Hãy nhập điểm tổng kết môn Ngữ Văn");
}
if (NguVan.value < 0 || NguVan.value > 10) {
alert("Điểm tổng kết môn Ngữ Văn phải trong khoảng từ 0 đến 10.");
}
if (isNaN(NguVan.value) == true) {
alert("Điểm tổng kết môn Ngữ Văn phải là giá trị số!");
}
var SinhHoc = document.getElementById('SinhHoc');
if (SinhHoc.value == "") {
alert("Hãy nhập điểm tổng kết môn Sinh Học");
}
if (SinhHoc.value < 0 || SinhHoc.value > 10) {
alert("Điểm tổng kết môn Sinh Học phải trong khoảng từ 0 đến 10.");
}
if (isNaN(SinhHoc.value) == true) {
alert("Điểm tổng kết môn Sinh Học phải là giá trị số!");
}
var VatLi = document.getElementById('VatLi');
if (VatLi.value == "") {
alert("Hãy nhập điểm tổng kết môn Vật Lí");
}
if (VatLi.value < 0 || VatLi.value > 10) {
alert("Điểm tổng kết môn Vật Lí phải trong khoảng từ 0 đến 10.");
}
if (isNaN(VatLi.value) == true) {
alert("Điểm tổng kết môn Vật Lí phải là giá trị số!");
}
var HoaHoc = document.getElementById('HoaHoc');
if (HoaHoc.value == "") {
alert("Hãy nhập điểm tổng kết môn Hóa Học");
}
if (HoaHoc.value < 0 || HoaHoc.value > 10) {
alert("Điểm tổng kết môn Hóa Học phải trong khoảng từ 0 đến 10.");
}
if (isNaN(HoaHoc.value) == true) {
alert("Điểm tổng kết môn Hóa Học phải là giá trị số!");
}
var LichSu = document.getElementById('LichSu');
if (LichSu.value == "") {
alert("Hãy nhập điểm tổng kết môn Lịch Sử");
}
if (LichSu.value < 0 || LichSu.value > 10) {
alert("Điểm tổng kết môn Lịch Sử phải trong khoảng từ 0 đến 10.");
}
if (isNaN(LichSu.value) == true) {
alert("Điểm tổng kết môn Lịch Sử phải là giá trị số!");
}
var DiaLy = document.getElementById('DiaLy');
if (DiaLy.value == "") {
alert("Hãy nhập điểm tổng kết môn Địa Lý");
}
if (DiaLy.value < 0 || DiaLy.value > 10) {
alert("Điểm tổng kết môn Địa Lý phải trong khoảng từ 0 đến 10.");
}
if (isNaN(DiaLy.value) == true) {
alert("Điểm tổng kết môn Địa Lý phải là giá trị số!");
}
var NgoaiNgu = document.getElementById('NgoaiNgu');
if (NgoaiNgu.value == "") {
alert("Hãy nhập điểm tổng kết môn Ngoại Ngữ");
}
if (NgoaiNgu.value < 0 || NgoaiNgu.value > 10) {
alert("Điểm tổng kết môn Ngoại Ngữ phải trong khoảng từ 0 đến 10.");
}
if (isNaN(NgoaiNgu.value) == true) {
alert("Điểm tổng kết môn Ngoại Ngữ phải là giá trị số!");
}
var GiaoDucCongDan = document.getElementById('GiaoDucCongDan');
if (GiaoDucCongDan.value == "") {
alert("Hãy nhập điểm tổng kết môn GDCD");
}
if (GiaoDucCongDan.value < 0 || GiaoDucCongDan.value > 10) {
alert("Điểm tổng kết môn GDCD phải trong khoảng từ 0 đến 10.");
}
if (isNaN(GiaoDucCongDan.value) == true) {
alert("Điểm tổng kết môn GDCD phải là giá trị số!");
}
var GiaoDucQuocPhong = document.getElementById('GiaoDucQuocPhong');
if (GiaoDucQuocPhong.value == "") {
alert("Hãy nhập điểm tổng kết môn GDQP");
}
if (GiaoDucQuocPhong.value < 0 || GiaoDucQuocPhong.value > 10) {
alert("Điểm tổng kết môn GDQP phải trong khoảng từ 0 đến 10.");
}
if (isNaN(GiaoDucQuocPhong.value) == true) {
alert("Điểm tổng kết môn GDQP phải là giá trị số!");
}
var TheDuc = document.getElementById('TheDuc');
if (TheDuc.value == "") {
alert("Hãy nhập điểm tổng kết môn Thể Dục");
}
if (TheDuc.value < 0 || TheDuc.value > 10) {
alert("Điểm tổng kết môn Thể Dục phải trong khoảng từ 0 đến 10.");
}
if (isNaN(TheDuc.value) == true) {
alert("Điểm tổng kết môn Thể Dục phải là giá trị số!");
}
var CongNghe = document.getElementById('CongNghe');
if (CongNghe.value == "") {
alert("Hãy nhập điểm tổng kết môn Công Nghệ");
}
if (CongNghe.value < 0 || CongNghe.value > 10) {
alert("Điểm tổng kết môn Công Nghệ phải trong khoảng từ 0 đến 10.");
}
if (isNaN(CongNghe.value) == true) {
alert("Điểm tổng kết môn Công Nghệ phải là giá trị số!");
}
var TinHoc = document.getElementById('TinHoc');
if (TinHoc.value == "") {
alert("Hãy nhập điểm tổng kết môn Tin Học");
}
if (TinHoc.value < 0 || TinHoc.value > 10) {
alert("Điểm tổng kết môn Tin Học phải trong khoảng từ 0 đến 10.");
}
if (isNaN(TinHoc.value) == true) {
alert("Điểm tổng kết môn Tin Học phải là giá trị số!");
}
var MonTuChon = document.getElementById('MonTuChon');
if (MonTuChon.value == "") {
alert("Hãy nhập điểm tổng kết Môn Tự Chọn");
}
if (MonTuChon.value < 0 || MonTuChon.value > 10) {
alert("Điểm tổng kết Môn Tự Chọn phải trong khoảng từ 0 đến 10.");
}
if (isNaN(MonTuChon.value) == true) {
alert("Điểm tổng kết Môn Tự Chọn phải là giá trị số!");
}
var DiemUuTien_1 = document.getElementById('DiemUuTien_1');
if (DiemUuTien_1.value == "") {
alert("Hãy nhập Điểm Ưu Tiên");
}
if (DiemUuTien_1.value < 0) {
alert("Điểm Ưu Tiên nhỏ nhất là 0");
}
if (isNaN(DiemUuTien_1.value) == true) {
alert("Điểm Ưu Tiên phải là giá trị số!");
}
}
function suggest_1_result_validate(){
var Suggest_1_result = document.getElementById('suggest_1_result');
if (Suggest_1_result.value == "") {
alert("Hãy nhập Mã Ngành hoặc Mã Nhóm ngành đã chọn!");
}
}
function test_point_validate(){
var Point_1 = document.getElementById('point_1');
if (Point_1.value == "") {
alert("Hãy nhập điểm thi môn thi 1");
}
if (Point_1.value < 0 || Point_1.value > 10) {
alert("Điểm thi môn thi 1 phải trong khoảng từ 0 đến 10.");
}
if (isNaN(Point_1.value) == true) {
alert("Điểm thi môn thi 1 phải là giá trị số!");
}
var Point_2 = document.getElementById('point_2');
if (Point_2.value == "") {
alert("Hãy nhập điểm thi môn thi 2");
}
if (Point_2.value < 0 || Point_2.value > 10) {
alert("Điểm thi môn thi 2 phải trong khoảng từ 0 đến 10.");
}
if (isNaN(Point_2.value) == true) {
alert("Điểm thi môn thi 2 phải là giá trị số!");
}
var Point_3 = document.getElementById('point_3');
if (Point_3.value == "") {
alert("Hãy nhập điểm thi môn thi 3");
}
if (Point_3.value < 0 || Point_2.value > 10) {
alert("Điểm thi môn thi 3 phải trong khoảng từ 0 đến 10.");
}
if (isNaN(Point_3.value) == true) {
alert("Điểm thi môn thi 3 phải là giá trị số!");
}
var DiemUuTien_2 = document.getElementById('DiemUuTien_2');
if (DiemUuTien_2.value == "") {
alert("Hãy nhập Điểm Ưu Tiên");
}
if (DiemUuTien_2.value < 0) {
alert("Điểm Ưu Tiên nhỏ nhất là 0");
}
if (isNaN(DiemUuTien_2.value) == true) {
alert("Điểm Ưu Tiên phải là giá trị số!");
}
}
function home_address_validate(){
var Home_address = document.getElementById('home_address_box');
if (Home_address.value == "") {
alert("Hãy nhập địa chỉ thường trú!");
}
}
function locdau(){
//code by Minit - www.canthoit.info - 13-05-2009
var str = (document.getElementById("title").value);
str= str.toLowerCase();
str= str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");
str= str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");
str= str.replace(/ì|í|ị|ỉ|ĩ/g,"i");
str= str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");
str= str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");
str= str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");
str= str.replace(/đ/g,"d");
str= str.replace(/!|@|\$|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\'| |\"|\&|\#|\[|\]|~/g,"-");
str= str.replace(/-+-/g,"-"); //thay thế 2- thành 1-
str= str.replace(/^\-+|\-+$/g,"");//cắt bỏ ký tự - ở đầu và cuối chuỗi
return alert("Kết Quả: "+ str);
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Liên hệ hỗ trợ</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("sideright.php");
?>
<div class="main">
<p>
Nếu gặp khó khăn trong quá trình sử dụng website <a href="index.php">HoTroTuyenSinh.com</a>, thí sinh và các bậc phụ huynh vui lòng liên hệ quản trị viên để được hỗ trợ kịp thời.
</p>
<br>
<br>
<table>
<tr>
<td>
<a href="https://www.facebook.com/TranThiNhuHoa14295" target="_blank"><img src="img/admin.jpg" alt="admin image" width="100px" style="border-radius: 5px;"></a>
</td>
<td>
<ul>
<li><b>Quản trị viên:</b> HoaTTN</li>
<li><b>Email:</b> <EMAIL></li>
<li><b>Phone Number:</b> 0129 620 0995</li>
</ul>
</td>
</tr>
</table>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><?php
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối đến cơ sở dữ liệu!");
mysqli_set_charset($connect, "utf8");
$query = "SELECT * FROM to_chuc_dao_tao";
$query_result = mysqli_query($GLOBALS['connect'], $query);
$count = mysqli_num_rows($query_result);
class Pagination {
protected $_config = array(
'current_page' => 1,
'total_record' => 1,
'total_page' => 1,
'limit' => 10,
'start' => 0,
'link_full' => '',
'link_first' => '',
);
function init($config = array()) {
foreach ($config as $key => $val){
if (isset($this->_config[$key])){
$this->_config[$key] = $val;
}
}
if ($this->_config['limit'] < 0){
$this->_config['limit'] = 0;
}
$this->_config['total_page'] = ceil($this->_config['total_record'] / $this->_config['limit']);
if (!$this->_config['total_page']){
$this->_config['total_page'] = 1;
}
if ($this->_config['current_page'] < 1){
$this->_config['current_page'] = 1;
}
if ($this->_config['current_page'] > $this->_config['total_page']){
$this->_config['current_page'] = $this->_config['total_page'];
}
$this->_config['start'] = ($this->_config['current_page'] - 1) * $this->_config['limit'];
}
private function __link($page) {
if ($page <= 1 && $this->_config['link_first']){
return $this->_config['link_first'];
}
return str_replace('{page}', $page, $this->_config['link_full']);
}
function html() {
$p = '';
if ($this->_config['total_record'] > $this->_config['limit']) {
$a = ($this->_config['current_page'] - 1) * $this->_config['limit'];
$b = $this->_config['limit'];
$query = "SELECT * FROM to_chuc_dao_tao LIMIT $a, $b";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo "<table class=" . "table_infor_pass" . ">";
echo "<tr>";
echo "<td class=" . "td_infor_pass" . ">";
echo "<a href='".$row["Website"]."' target='_blank'><img src='".$row["Logo"]."' alt='school logo' width='100px'></a>";
echo "</td>";
echo "<td>";
echo "<ul>";
echo "<li class=" . "infor_pass" . "><b>Tên trường:</b> " . $row["Ten_To_Chuc_Dao_Tao"] ."</li>";
echo "<li class=" . "infor_pass" . "><b>Mã trường:</b> " . $row["Ma_To_Chuc_Dao_Tao"] . "</li>";
echo "<li class=" . "infor_pass" . "><b>Trang chủ:</b> <a href='" . $row["Website"] . "' target='_blank'>" . $row["Website"] . "</a></li>";
echo "<li class=" . "infor_pass" . "><b>Thông tin tuyển sinh:</b> <a href='" . $row["Thong_Tin_Tuyen_Sinh"] . "' target='_blank'>" . $row["Thong_Tin_Tuyen_Sinh"] . "</a></li>";
echo "</ul>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "<br><br>";
}
$p = '<ul>';
if ($this->_config['current_page'] > 1) {
$p .= '<li class="infor"><a href="'.$this->__link('1').'">First</a></li>';
$p .= '<li class="infor"><a href="'.$this->__link($this->_config['current_page']-1).'">Prev</a></li>';
}
for ($i = 1; $i <= $this->_config['total_page']; $i++) {
if ($this->_config['current_page'] == $i){
$p .= '<li class="infor"><span>'.$i.'</span></li>';
}
else{
$p .= '<li class="infor"><a href="'.$this->__link($i).'">'.$i.'</a></li>';
}
}
if ($this->_config['current_page'] < $this->_config['total_page']) {
$p .= '<li class="infor"><a href="'.$this->__link($this->_config['current_page'] + 1).'">Next</a></li>';
$p .= '<li class="infor"><a href="'.$this->__link($this->_config['total_page']).'">Last</a></li>';
}
$p .= '</ul>';
}
return $p;
}
}
$config = array(
'current_page' => isset($_GET['page']) ? $_GET['page'] : 1,
'total_record' => $count,
'limit' => 5,
'link_full' => 'infor.php?page={page}',
'link_first' => 'infor.php',
);
$paging = new Pagination();
$paging->init($config);
echo $paging->html();
echo "<br><br>";
?>
<style>
.infor {
float:left;
margin: 3px;
border: solid 1px #52D017;
display: inline;
}
.infor_pass {
list-style-type: none;
}
.table_infor_pass {
border: 1px solid #52D017;
width: 100%;
border-radius: 5px;
height: 200px;
}
.td_infor_pass {
width: 20%;
}
a {
padding: 5px;
color: black;
}
span {
display:inline-block;
padding: 0px 3px;
background: #52D017;
color:white
}
</style><file_sep><!DOCTYPE html>
<html>
<head>
<title>H<NAME> Tuyển Sinh | Gợi ý chọn Lĩnh vực đào tạo</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_1.php");
?>
<div class="main1">
<p>
Các gợi ý được đưa ra dựa trên 3 tiêu chí sau:
</p>
<ol>
<li>Mức độ yêu thích cúa thí sinh đối với từng Lĩnh vực đào tạo.</li>
<li>Năng lực bản thân của thí sinh.</li>
<li>Số chỉ tiêu đã quy định của từng Lĩnh vực đào tạo.</li>
</ol>
<br>
<h2>Bước 2: Gợi ý chọn Lĩnh vực Đào tạo</h2>
<p>
<a href="index.php">HoTroTuyenSinh.com</a> muốn biết:<br><br>
</p>
<?php
include("atribute_1_2_1.php");
include("view_result.php");
?>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Admin | Quản lý giá trị trọng số</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="school_infor_manage.php">Trang quản trị website HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("admin_navigation_bar.php");
?>
</div>
<div id="footer" style="height: 20px;">
© 2018 manage webpage hotrotuyensinh.com (by HoaTTN)
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn Khối ngành</title>
<?php
include("meta.php");
?>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid #52D017;
width: 50%;
}
th {
height: 50px;
}
td {
height: 30px;
text-align: center;
}
</style>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_1.php");
?>
<div class="main1">
<p>Bảng dưới đây xếp hạng mức độ phù hợp của từng Khối Ngành đối với thí sinh theo thứ tự giảm dần:</p>
<br>
<table>
<?php
$sap_xep = [];
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối với cơ sở dữ liệu");
mysqli_set_charset($connect, "utf8");
// function tinh_trong_so(){
$attribute_id = [];
$query = "SELECT ID FROM thuoc_tinh_bai_toan_1;";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$attribute_id[] = "attribute_" . $row['ID'];
}
$weight_id = [];
foreach ($attribute_id as $key => $value) {
$weight_language_value = $_POST[$value];
$query = "SELECT ID FROM trong_so WHERE Trong_So_Bien_Ngon_Ngu='$weight_language_value'";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$weight_id[] = (int)$row['ID'];
}
}
$base_sum = array_sum($weight_id);
$weight_base = 1 / $base_sum;
$weight = [];
foreach ($weight_id as $key => $value) {
$weight[] = $value * $weight_base;
}
// function tinh_muc_do_yeu_thich_khoi_nganh(){
$khoi_nganh_ID = "SELECT Khoi_Nganh_ID FROM khoi_nganh";
$khoi_nganh_ID_result = mysqli_query($GLOBALS['connect'], $khoi_nganh_ID);
while ($khoi_nganh_ID_row = mysqli_fetch_assoc($khoi_nganh_ID_result)) {
$select_khoi_nganh_name[] = "khoi_nganh_" . $khoi_nganh_ID_row["Khoi_Nganh_ID"];
}
foreach ($select_khoi_nganh_name as $select_khoi_nganh_name_key => $select_khoi_nganh_name_value) {
$attribute_khoi_nganh = $_POST["" . $select_khoi_nganh_name_value];
$attribute_khoi_nganh_sql = "SELECT * FROM fuzzy_set WHERE Bien_Ngon_Ngu='$attribute_khoi_nganh'";
$attribute_khoi_nganh_sql_result = mysqli_query($GLOBALS['connect'], $attribute_khoi_nganh_sql);
while ($fuzzy_set_khoi_nganh_row = mysqli_fetch_assoc($attribute_khoi_nganh_sql_result)) {
$fuzzy_set_a1[] = $fuzzy_set_khoi_nganh_row["a1"];
$fuzzy_set_b1[] = $fuzzy_set_khoi_nganh_row["b1"];
$fuzzy_set_c1[] = $fuzzy_set_khoi_nganh_row["c1"];
$fuzzy_set_d1[] = $fuzzy_set_khoi_nganh_row["d1"];
$fuzzy_set_h11[] = $fuzzy_set_khoi_nganh_row["h11"];
$fuzzy_set_h12[] = $fuzzy_set_khoi_nganh_row["h12"];
$fuzzy_set_a2[] = $fuzzy_set_khoi_nganh_row["a2"];
$fuzzy_set_b2[] = $fuzzy_set_khoi_nganh_row["b2"];
$fuzzy_set_c2[] = $fuzzy_set_khoi_nganh_row["c2"];
$fuzzy_set_d2[] = $fuzzy_set_khoi_nganh_row["d2"];
$fuzzy_set_h21[] = $fuzzy_set_khoi_nganh_row["h21"];
$fuzzy_set_h22[] = $fuzzy_set_khoi_nganh_row["h22"];
}
}
$fuzzy_set_mount = count($fuzzy_set_a1);
$n = 2;
$he_so_lech = $n / (2 * $n + 1);
for ($i = 0; $i < $fuzzy_set_mount; $i++) {
$tich_hop_trung_binh_can_duoi[$i] = ($fuzzy_set_a1[$i] + $fuzzy_set_d1[$i]) / 2 +
$he_so_lech * ($fuzzy_set_b1[$i] - $fuzzy_set_a1[$i] - $fuzzy_set_d1[$i] + $fuzzy_set_c1[$i]);
$tich_hop_trung_binh_can_tren[$i] = ($fuzzy_set_a2[$i] + $fuzzy_set_d2[$i]) / 2 +
$he_so_lech * ($fuzzy_set_b2[$i] - $fuzzy_set_a2[$i] - $fuzzy_set_d2[$i] + $fuzzy_set_c2[$i]);
$tich_hop_trung_binh[$i] = ($tich_hop_trung_binh_can_tren[$i] + $tich_hop_trung_binh_can_duoi[$i]) / 2;
}
// function tinh_nang_luc_ban_than_theo_khoi_nganh(){
$diem_tong_ket = array(
"Toán Học" => (int)$_POST['toan_hoc'],
"Ngữ Văn" => (int)$_POST['ngu_van'],
"Sinh Học" => (int)$_POST['sinh_hoc'],
"Vật Lí" => (int)$_POST['vat_li'],
"Hóa Học" => (int)$_POST['hoa_hoc'],
"Lịch Sử" => (int)$_POST['lich_su'],
"Địa Lý" => (int)$_POST['dia_ly'],
"Ngoại Ngữ" => (int)$_POST['ngoai_ngu'],
"Giáo Dục Công Dân" => (int)$_POST['giao_duc_cong_dan'],
"Giáo Dục Quốc Phòng" => (int)$_POST['giao_duc_quoc_phong'],
"Thể Dục" => (int)$_POST['the_duc'],
"Công Nghệ" => (int)$_POST['cong_nghe'],
"Tin Học" => (int)$_POST['tin_hoc'],
"Môn Tự Chọn" => (int)$_POST['mon_tu_chon'],
"Điểm Ưu Tiên" => (int)$_POST['diem_uu_tien'],
);
mysqli_set_charset($GLOBALS['connect'], "utf8");
$ten_nganh = [];
$ten_nganh_sql = "SELECT Ten_Nganh, Ma_Khoi_Thi FROM tuyen_sinh";
$ten_nganh_sql_result = mysqli_query($GLOBALS['connect'], $ten_nganh_sql);
while ($ten_nganh[] = mysqli_fetch_assoc($ten_nganh_sql_result)) {
}
$result = [];
foreach ($ten_nganh as $key => $value) {
if (array_key_exists($value['Ten_Nganh'], $result)) {
if (in_array($value['Ma_Khoi_Thi'], $result[$value['Ten_Nganh']])) {
continue;
}
}
$result[$value['Ten_Nganh']][] = $value['Ma_Khoi_Thi'];
}
$nhom_nganh = [];
$query = "SELECT Ten_Nganh, Nhom_Nganh_ID FROM nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($nhom_nganh[] = mysqli_fetch_assoc($query_result)) {
}
$result2 = [];
foreach ($nhom_nganh as $value) {
if (array_key_exists($value['Ten_Nganh'], $result))
$result2[$value['Nhom_Nganh_ID']] = array_merge($result[$value['Ten_Nganh']], $result2[$value['Nhom_Nganh_ID']] ?? []);
}
foreach ($result2 as $key => $value) {
$temp = array_unique($value);
$result2[$key] = $temp;
}
$khoi_nganh = [];
$query = "SELECT khoi_nganh.Khoi_Nganh_ID, khoi_nganh.Ten_Khoi_Nganh, nhom_nganh.Nhom_Nganh_ID, nhom_nganh.Ten_Nhom_Nganh
FROM nhom_nganh JOIN khoi_nganh JOIN linh_vuc_dao_tao
WHERE khoi_nganh.Khoi_Nganh_ID = linh_vuc_dao_tao.Khoi_Nganh_ID AND
nhom_nganh.Linh_Vuc_Dao_Tao_ID = linh_vuc_dao_tao.Linh_Vuc_Dao_Tao_ID";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($khoi_nganh[] = mysqli_fetch_assoc($query_result)) {
}
$result3 = [];
foreach ($khoi_nganh as $value) {
if (array_key_exists($value['Nhom_Nganh_ID'], $result2) && $value['Ten_Khoi_Nganh'] != "")
$result3[$value['Ten_Khoi_Nganh']] = array_merge($result2[$value['Nhom_Nganh_ID']], $result3[$value['Ten_Khoi_Nganh']] ?? []);
}
foreach ($result3 as $key => $value) {
$temp = array_unique($value);
$result3[$key] = $temp;
}
$diem_khoi_thi = [];
$query = "SELECT Ma_Khoi_Thi_BGD, Mon_Thi_1, Mon_Thi_2, Mon_Thi_3 FROM khoi_thi";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($diem_khoi_thi[] = mysqli_fetch_assoc($query_result)) {
}
$tong_diem = [];
foreach ($diem_khoi_thi as $value) {
$temp = ($diem_tong_ket[$value['Mon_Thi_1']] ?? $diem_tong_ket["Môn Tự Chọn"])
+ ($diem_tong_ket[$value['Mon_Thi_2']] ?? $diem_tong_ket["Môn Tự Chọn"])
+ ($diem_tong_ket[$value['Mon_Thi_3']] ?? $diem_tong_ket["Môn Tự Chọn"])
+ $diem_tong_ket["Điểm Ưu Tiên"];
$tong_diem[$value['Ma_Khoi_Thi_BGD']] = $temp;
}
$result4 = [];
foreach ($result3 as $key => $value){
$temp = [];
foreach ($value as $sVal ){
$temp[$sVal] = $tong_diem[$sVal];
}
$max = max($temp);
$result4[$key] = $max;
}
$result5 = [];
$query = "SELECT Ten_Khoi_Nganh FROM khoi_nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$result5[$row['Ten_Khoi_Nganh']] = 0;
}
$result6 = [];
$result6 = array_merge($result5, $result4);
// function so_chi_tieu_theo_khoi_nganh(){
$result1 = [];
$query = "SELECT khoi_nganh.Ten_Khoi_Nganh, tuyen_sinh.So_Chi_Tieu
FROM khoi_nganh JOIN linh_vuc_dao_tao JOIN nhom_nganh JOIN nganh JOIN tuyen_sinh
WHERE
khoi_nganh.Khoi_Nganh_ID = linh_vuc_dao_tao.Khoi_Nganh_ID AND
linh_vuc_dao_tao.Linh_Vuc_Dao_Tao_ID = nhom_nganh.Linh_Vuc_Dao_Tao_ID AND
nhom_nganh.Nhom_Nganh_ID = nganh.Nhom_Nganh_ID AND
nganh.Ten_Nganh = tuyen_sinh.Ten_Nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$result1[$row['Ten_Khoi_Nganh']] = (int)$row['So_Chi_Tieu'] + ($result1[$row['Ten_Khoi_Nganh']]??0);
}
$result2 = [];
$query = "SELECT Ten_Khoi_Nganh FROM khoi_nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$result2[$row['Ten_Khoi_Nganh']] = 0;
}
$result3 = [];
$result3 = array_merge($result2, $result1);
// function goi_y_chon_khoi_nganh(){
$trong_so = [];
foreach ($weight as $key => $value) {
$trong_so[] = $value;
}
$attribute_1 = [];
foreach ($tich_hop_trung_binh as $key => $value) {
$attribute_1[$key] = $value;
}
$attribute_2 = [];
foreach ($result6 as $key => $value) {
$attribute_2[] = $value;
}
$attribute_3 = [];
foreach ($result3 as $key => $value) {
$attribute_3[] = $value;
}
//TOPSIS
//Bước 1: Chuẩn hóa giá trị các thuộc tính theo CHUẨN HÓA TUYẾN TÍNH
$attribute_1_chuan_hoa = [];
$attribute_1_max = max($attribute_1);
foreach ($attribute_1 as $key => $value) {
$attribute_1_chuan_hoa[] = $value / $attribute_1_max;
}
$attribute_2_chuan_hoa = [];
$attribute_2_max = max($attribute_2);
foreach ($attribute_2 as $key => $value) {
$attribute_2_chuan_hoa[] = $value / $attribute_2_max;
}
$attribute_3_chuan_hoa = [];
$attribute_3_max = max($attribute_3);
foreach ($attribute_3 as $key => $value) {
$attribute_3_chuan_hoa[] = $value / $attribute_3_max;
}
//Bước 2: Tính giá trị theo trọng số
$attribute_1_trong_so = [];
foreach ($attribute_1_chuan_hoa as $key => $value) {
$attribute_1_trong_so[] = $value * $trong_so[0];
}
$attribute_2_trong_so = [];
foreach ($attribute_2_chuan_hoa as $key => $value) {
$attribute_2_trong_so[] = $value * $trong_so[1];
}
$attribute_3_trong_so = [];
foreach ($attribute_3_chuan_hoa as $key => $value) {
$attribute_3_trong_so[] = $value * $trong_so[2];
}
//Bước 3: Tìm phương án lý tưởng tốt và phương án lý tưởng xấu
$phuong_an_ly_tuong_tot = [];
$phuong_an_ly_tuong_tot[] = max($attribute_1_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_2_trong_so);
$phuong_an_ly_tuong_tot[] = max($attribute_3_trong_so);
$phuong_an_ly_tuong_xau = [];
$phuong_an_ly_tuong_xau[] = min($attribute_1_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_2_trong_so);
$phuong_an_ly_tuong_xau[] = min($attribute_3_trong_so);
//Bước 4: Tính khoảng cách của từng phương án đến 2 phương án lý tưởng tốt và lý tưởng xấu
$attribute_1_tru_ly_tuong_tot = [];
foreach ($attribute_1_trong_so as $key => $value) {
$attribute_1_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[0] - $value;
}
$attribute_2_tru_ly_tuong_tot = [];
foreach ($attribute_2_trong_so as $key => $value) {
$attribute_2_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[1] - $value;
}
$attribute_3_tru_ly_tuong_tot = [];
foreach ($attribute_3_trong_so as $key => $value) {
$attribute_3_tru_ly_tuong_tot[] = $phuong_an_ly_tuong_tot[2] - $value;
}
$khoang_cach_den_phuong_an_ly_tuong_tot = [];
for($i=0; $i<count($attribute_1); $i++){
$khoang_cach_den_phuong_an_ly_tuong_tot[$i] = sqrt(pow($attribute_1_tru_ly_tuong_tot[$i], 2) + pow($attribute_2_tru_ly_tuong_tot[$i], 2) + pow($attribute_3_tru_ly_tuong_tot[$i], 2));
}
$attribute_1_tru_ly_tuong_xau = [];
foreach ($attribute_1_trong_so as $key => $value) {
$attribute_1_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[0];
}
$attribute_2_tru_ly_tuong_xau = [];
foreach ($attribute_2_trong_so as $key => $value) {
$attribute_2_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[1];
}
$attribute_3_tru_ly_tuong_xau = [];
foreach ($attribute_3_trong_so as $key => $value) {
$attribute_3_tru_ly_tuong_xau[] = $value - $phuong_an_ly_tuong_xau[2];
}
$khoang_cach_den_phuong_an_ly_tuong_xau = [];
for($i=0; $i<count($attribute_1); $i++){
$khoang_cach_den_phuong_an_ly_tuong_xau[$i] = sqrt(pow($attribute_1_tru_ly_tuong_xau[$i], 2) + pow($attribute_2_tru_ly_tuong_xau[$i], 2) + pow($attribute_3_tru_ly_tuong_xau[$i], 2));
}
//Bước 5: Tính độ tương tự tới phương án lý tưởng tốt
$do_tuong_tu = [];
for($i=0; $i<count($attribute_1); $i++){
$do_tuong_tu[$i] = $khoang_cach_den_phuong_an_ly_tuong_xau[$i] / ($khoang_cach_den_phuong_an_ly_tuong_xau[$i] + $khoang_cach_den_phuong_an_ly_tuong_tot[$i]);
}
//Bước 6: Xếp hạng các phương án và đưa ra gợi ý
$khoi_nganh_infor = [];
$query = "SELECT Ten_Khoi_Nganh FROM khoi_nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$khoi_nganh_infor[] = $row['Ten_Khoi_Nganh'];
}
// $sap_xep = [];
foreach ($do_tuong_tu as $key => $value) {
foreach ($khoi_nganh_infor as $key1 => $value1) {
if($key == $key1)
$sap_xep[$value1] = $value;
}
}
arsort($sap_xep);
echo '<th>';
echo "Khối ngành";
echo '</th>';
// echo '<th>';
// echo "Khối thi";
// echo '</th>';
echo '<th>';
echo "Xếp hạng";
echo '</th>';
$rank = 1;
foreach ($sap_xep as $key => $value) {
echo '<tr>';
echo '<td>';
echo $key;
echo '</td>';
echo '<td>';
echo $rank;
echo '</td>';
echo '</tr>';
$rank++;
}
mysqli_close($connect);
?>
</table>
<br>
<p>
<b><a href="index.php">HoTroTuyenSinh.com</a> gợi ý thí sinh nên chọn các ngành thuộc khối ngành có mức độ phù hợp cao nhất, <br>và chọn một trong các khối thi:</b>
<?php
foreach ($sap_xep as $key => $value) {
$khoi_nganh_goi_y[] = $key;
}
// include "Properties.php";
$dbhost = 'localhost';
$dbuser = 'homestead';
$dbpass = '<PASSWORD>';
$db = 'recommendation';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối với cơ sở dữ liệu");
mysqli_set_charset($connect, "utf8");
$query = "SELECT tuyen_sinh.Ma_Khoi_Thi FROM khoi_nganh JOIN linh_vuc_dao_tao JOIN nhom_nganh JOIN nganh JOIN tuyen_sinh WHERE khoi_nganh.Ten_Khoi_Nganh = '$khoi_nganh_goi_y[0]' AND khoi_nganh.Khoi_Nganh_ID = linh_vuc_dao_tao.Khoi_Nganh_ID AND linh_vuc_dao_tao.Linh_Vuc_Dao_Tao_ID = nhom_nganh.Linh_Vuc_Dao_Tao_ID AND nhom_nganh.Nhom_Nganh_ID = nganh.Nhom_Nganh_ID AND nganh.Ten_Nganh = tuyen_sinh.Ten_Nganh";
$query_result = mysqli_query($GLOBALS['connect'], $query);
while ($row = mysqli_fetch_assoc($query_result)) {
$khoi_thi_result[] = $row['Ma_Khoi_Thi'];
}
$khoi_thi_unique = array_unique($khoi_thi_result);
foreach ($khoi_thi_unique as $key => $value) {
echo $value ." ";
}
mysqli_close($connect);
?>
</p>
<br>
<a href="suggest1_2.php">Xem gợi ý chọn Lĩnh vực Đào tạo</a>
<p style="font-size: 11px;">
<i>Lưu ý: <a href="index.php">HoTroTuyenSinh.com</a> chỉ gợi ý thí sinh lựa chọn Lĩnh vực Đào tạo trong Khối Ngành có độ phù hợp cao nhất.</i>
</p>
<br>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Giới thiệu website</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("sideright.php");
?>
<div class="main">
<h2>Chào mừng đến với <a href="index.php">HoTroTuyenSinh.com</a>!</h2>
<br>
<p>
<a href="index.php">HoTroTuyenSinh.com</a> sẽ giúp thí sinh và các bậc phụ huynh:
</p>
<ol>
<li>
Tra cứu thông tin tuyển sinh của các trường Cao đẳng, Đại học, các Học viện trên cả nước:
<ul>
<li>Tên trường</li>
<li>Mã trường</li>
<li>Thông tin tuyển sinh</li>
<li>Bảng đánh giá, xếp hạng các trường</li>
<li>...</li>
</ul>
</li>
<br>
<li>
Tra cứu thông tin liên quan đến tuyển sinh:
<ul>
<li>Quy định về tổ hợp môn thi theo từng khối thi</li>
<li>Quy định về ngành, nhóm ngành đào tạo cấp IV (bậc Đại học)</li>
<li>Quy định về điểm ưu tiên, điểm cộng tối đa</li>
<li>...</li>
</ul>
</li>
<br>
<li>
Đưa ra gợi ý chọn ngành, nhóm ngành phù hợp nhất.
<ul>
<li>Gợi ý chọn khối ngành</li>
<li>Gợi ý chọn lĩnh vực đào tạo</li>
<li>Gợi ý chọn nhóm ngành</li>
<li>Gợi ý chọn ngành</li>
<li>...</li>
</ul>
</li>
<br>
<li>
Đưa ra gợi ý chọn trường phù hợp nhất.
<ul>
<li>Gợi ý chọn trường được đưa ra sau khi đã có gợi ý chọn ngành, nhóm ngành.</li>
</ul>
</li>
</ol>
</div>
<div class="main">
<h2>Lưu ý:</h2>
<br>
<ol>
<li>
<p>Những thông tin có trên <a href="index.php">HoTroTuyenSinh.com</a> là do bên thứ 3 cung cấp, <a href="index.php">HoTroTuyenSinh.com</a> không can thiệp vào nội dung những thông tin này. Do đó, nếu những thông tin này có sai sót hoặc nhầm lẫn, thì <a href="index.php">HoTroTuyenSinh.com</a> hoàn toàn không chịu trách nhiệm.</p>
</li>
<li>
<p><a href="index.php">HoTroTuyenSinh.com</a> chỉ đưa ra các gợi ý, hoàn toàn không bắt buộc thí sinh và các bậc phụ huynh phải làm theo gợi ý này.</p>
</li>
<li>
<p>Tính toán và thực tế sẽ có sự sai lệch nhất định, nếu thí sinh và các bậc phụ huynh sử dụng kết quả gợi ý của <a href="index.php">HoTroTuyenSinh.com</a> và gặp tổn thất, <a href="index.php">HoTroTuyenSinh.com</a> hoàn toàn không chịu trách nhiệm.</p>
</li>
</ol>
<br>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: thuyn
* Date: 02-Jun-18
* Time: 12:26 PM
*/
class Properties
{
const DATABASE = [
'name' => 'recommendation',
'host' => 'localhost',
'username' => 'homestead',
'password' => '<PASSWORD>',
];
}<file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Chính sách bảo mật</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("sideright.php");
?>
<div class="main">
<h2>Chính sách bảo mật thông tin của <a href="index.php">HoTroTuyenSinh.com</a></h2>
<br>
<ol>
<li>
<p>
<b>Thông tin cá nhân:</b> Để có thể đưa ra được gợi ý chọn trường, chọn ngành, nhóm ngành, <a href="index.php">HoTroTuyenSinh.com</a> yêu cầu thí sinh và các bậc phụ huynh phải cung cấp rất nhiều thông tin cá nhân, ví dụ như: địa chỉ cư trú, điểm tổng kết từng môn, sở thích bản thân của thí sinh ... Tuy nhiên, <a href="index.php">HoTroTuyenSinh.com</a> chỉ sử dụng những thông tin này vào quá trình tính toán để đưa ra gợi ý, và không lưu trữ các thông tin này, cũng như, không lưu trữ kết quả tính toán thu được.
</p>
</li>
<br>
<li>
<p>
<b>Các trang web bên thứ ba:</b> <a href="index.php">HoTroTuyenSinh.com</a> không chịu trác nhiệm về sự riêng tư, thông tin cá nhân mà thí sinh và các bậc phụ huynh cung cấp cho bất kỳ bên thứ ba nào vận hành bất kỳ trang web nào mà <a href="index.php">HoTroTuyenSinh.com</a> có chứa đường dẫn liên kết.
</p>
</li>
<br>
<li>
<p>
<b>Thời gian giữ lại:</b> <a href="index.php">HoTroTuyenSinh.com</a> chỉ giữ lại thông tin cá nhân mà thí sinh và các bậc phụ huynh cung cấp trong khoảng thời gian cần thiết để thực hiện mục đích đưa ra các gợi ý.
</p>
</li>
<br>
<li>
<p>
<b>Cập nhật đối với chính sách bảo mật thông tin này:</b> <a href="index.php">HoTroTuyenSinh.com</a> có thể thay đổi Chính sách Bảo mật thông tin này bất cứ lúc nào. Tuy nhiên, các sửa đổi chỉ có hiệu lực khi được đăng tải trên trang <a href="privacy_policy.php">Chính sách Bảo mật</a>.
</p>
</li>
<br>
<li>
<p>
<b>Liên hệ với chúng tôi:</b> Nếu có bất kỳ thắc mắc nào về Chính sách Bảo mật này, vui lòng <a href="contact.php">liên hệ với chúng tôi</a> để được giải đáp kịp thời.
</p>
</li>
</ol>
<br>
<p>Trân trọng!</p>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><?php
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
$admin_table = "admin";
$admin_connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối với cơ sở dữ liệu");
$admin_name = $_POST['admin_name'];
$admin_password = $_POST['<PASSWORD>password'];
$sql = "SELECT * FROM admin WHERE admin_name='$admin_name' and admin_password='$<PASSWORD>'";
$result = mysqli_query($admin_connect, $sql);
$count = mysqli_num_rows($result);
if ($count == 1) {
header("location:school_infor_manage.php");
} else {
echo "Sai tên đăng nhập hoặc mật khẩu";
}
mysqli_close($admin_connect);
?><file_sep><table>
<?php
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
// $db_table = "thuoc_tinh_bai_toan_1";
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db)
or die("Không thể kết nối đến cơ sở dữ liệu!");
mysqli_set_charset($connect, "utf8");
$attribute_list = "SELECT * FROM thuoc_tinh_bai_toan_2";
$data = mysqli_query($connect, $attribute_list);
while ($row = mysqli_fetch_assoc($data)) {
# code...
echo '<tr>';
echo '<td>';
echo $row["Ten_Thuoc_Tinh"] . ' :';
echo '</td>';
echo '<td>';
echo '<select name="attribute_' . $row["ID"] . '">';
echo '<option value="anh_huong_rat_lon">-- Ảnh hưởng rất lớn --</option>';
echo '<option value="anh_huong_kha_lon">-- Ảnh hưởng khá lớn --</option>';
echo '<option value="anh_huong_it">-- Ảnh hưởng ít --</option>';
echo '<option value="khong_anh_huong">-- Không ảnh hưởng --</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
}
mysqli_close($connect);
?>
</table><file_sep><table>
<?php
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
// $db_table = "thuoc_tinh_bai_toan_1";
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db)
or die("Không thể kết nối đến cơ sở dữ liệu!");
mysqli_set_charset($connect, "utf8");
$khoi_nganh_list = "SELECT * FROM khoi_nganh";
$data = mysqli_query($connect, $khoi_nganh_list);
while ($row = mysqli_fetch_assoc($data)) {
# code...
echo '<tr>';
echo '<td>';
echo $row["Ten_Khoi_Nganh"] . ' :';
echo '</td>';
echo '<td>';
echo '<select name="khoi_nganh_' . $row["Khoi_Nganh_ID"] . '">';
echo '<option value="cuc_ky_thich">-- Cực kỳ thích --</option>';
echo '<option value="rat_thich">-- Rất thích --</option>';
echo '<option value="yeu_thich">-- Yêu thích --</option>';
echo '<option value="binh_thuong">-- Bình thường --</option>';
echo '<option value="khong_thich">-- Không thích --</option>';
echo '<option value="rat_khong_thich">-- Rất không thích --</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
}
mysqli_close($connect);
?>
</table><file_sep><!DOCTYPE html>
<html>
<head>
<title><NAME> | Gợi ý chọn trường</title>
<?php
include("meta.php");
?>
<style>
.main{
height: 585px;
}
</style>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<div class="main">
<?php
echo "Xin lỗi, chúng tôi không xác định được địa điểm này....";
?>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Gợi ý chọn Khối ngành</title>
<?php
include("meta.php");
?>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("step_bar_1.php");
?>
<div class="main1">
<p>
Các gợi ý được đưa ra dựa trên 3 tiêu chí sau:
</p>
<ol>
<li>Mức độ yêu thích cúa thí sinh đối với từng Khối ngành.</li>
<li>Năng lực bản thân của thí sinh.</li>
<li>Số chỉ tiêu đã quy định của từng Khối ngành.</li>
</ol>
<br>
<h2>Bước 1: Gợi ý chọn Khối ngành</h2>
<p>
<a href="index.php">HoTroTuyenSinh.com</a> muốn biết: <br><br>
</p>
<hr>
<p>
<b>Mức độ ảnh hưởng của các tiêu chí đối với việc ra quyết định</b>
</p>
<form name="suggest1_1"
action="suggest1_1_result.php"
method="POST"
>
<?php
include("weight_1.php");
?>
<br>
<hr>
<p>
<b>Mức độ yêu thích đối với từng Khối ngành</b>
</p>
<?php
include("atribute_1_1_1.php");
?>
<br>
<hr>
<p>
<b>Điểm tổng kết các môn học sau:</b>
</p>
<?php
include("atribute_1_1_2.php");
?>
<br>
<input type="submit" name="suggest1_1_submit" value="Xem kết quả gợi ý">
</form>
<br>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html><file_sep><hr>
<p>
<b>Mức độ yêu thích đối với từng Lĩnh vực Đào tạo</b>
</p>
<form id="atribute_1_2_1" action="" method="">
<table>
<tr>
<td>Tên lĩnh vực đào tạo:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên lĩnh vực đào tạo:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên lĩnh vực đào tạo:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên lĩnh vực đào tạo:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
<tr>
<td>Tên lĩnh vực đào tạo:</td>
<td><?php include("rate_2.php"); ?></td>
</tr>
</table>
<br>
<input type="submit" name="atribute_1_2_1_submit" value="Gửi đánh giá">
</form>
<br>
<br><file_sep><!DOCTYPE html>
<html>
<head>
<title>Hỗ Trợ Tuyển Sinh | Thông tin truyển sinh</title>
<?php
include("meta.php");
?>
<style>
.infor_pass {
list-style-type: none;
}
.table_infor_pass {
border: 1px solid #52D017;
width: 100%;
border-radius: 5px;
height: 200px;
}
</style>
</head>
<body>
<div id="header">
<h3><a href="index.php">HoTroTuyenSinh.com</a></h3>
</div>
<div id="navbar">
<?php
include("navigation_bar.php");
?>
</div>
<?php
include("sideright.php");
?>
<div class="main">
<form action="search.php" method="POST" name="search_form"
onsubmit="return(search_validate())">
<input type="text" name="school_infor"
placeholder="Nhập tên trường, mã trường" required>
<input type="submit" name="search_button" value="Tìm kiếm">
</form>
</div>
<div class="main">
<?php
include "Properties.php";
$dbhost = Properties::DATABASE['host'];
$dbuser = Properties::DATABASE['username'];
$dbpass = Properties::DATABASE['password'];
$db = Properties::DATABASE['name'];
// $db_table = "to_chuc_dao_tao";
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die("Không thể kết nối đến cơ sở dữ liệu!");
mysqli_set_charset($connect, "utf8");
$input = $_POST['school_infor'];
$sql = "SELECT * FROM to_chuc_dao_tao WHERE Ma_To_Chuc_Dao_Tao='$input' OR Ten_To_Chuc_Dao_Tao='$input'";
mysqli_set_charset($connect, "utf8");
$result = mysqli_query($connect, $sql);
$count = mysqli_num_rows($result);
if (mysqli_num_rows($result) == 0) {
echo 'Không có kết quả tìm kiếm!';
} else {
while ($row = mysqli_fetch_assoc($result)) {
echo "<table class=" . "table_infor_pass" . ">";
echo "<tr>";
echo "<td>";
echo "<a href='" . $row["Website"] . "' target='_blank'><img src='" . $row["Logo"] . "' alt='school logo' width='100px'></a>";
echo "</td>";
echo "<td>";
echo "<ul>";
echo "<li class=" . "infor_pass" . "><b>Tên trường:</b> " . $row["Ten_To_Chuc_Dao_Tao"] . "</li>";
echo "<li class=" . "infor_pass" . "><b>Mã trường:</b> " . $row["Ma_To_Chuc_Dao_Tao"] . "</li>";
echo "<li class=" . "infor_pass" . "><b>Trang chủ:</b> <a href='" . $row["Website"] . "' target='_blank'>" . $row["Website"] . "</a></li>";
echo "<li class=" . "infor_pass" . "><b>Thông tin tuyển sinh:</b> <a href='" . $row["Thong_Tin_Tuyen_Sinh"] . "' target='_blank'>" . $row["Thong_Tin_Tuyen_Sinh"] . "</a></li>";
echo "</ul>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($connect);
?>
</div>
<div id="footer">
<?php
include("footer.php");
?>
</div>
</body>
</html> | 2b3a6e78bec9b84df25f52a0c1b0456a2bef93e9 | [
"JavaScript",
"SQL",
"PHP"
] | 24 | PHP | TranThiNhuHoa/DoAnTotNghiep | 4c378665812320b5fe122d2011056373f9d7b18a | 5795e1f356eb6dc5bd4caac93e5d3faada065c59 |
refs/heads/master | <file_sep>class PetsController < ApplicationController
skip_before_action :authenticate_user!, only: [ :index, :show ]
def index
@pets = Pet.where.not(latitude: nil, longitude: nil)
@hash = Gmaps4rails.build_markers(@pets) do |pet, marker|
marker.lat pet.latitude
marker.lng pet.longitude
# marker.infowindow render_to_string(partial: "/flats/map_box", locals: { flat: flat })
end
end
def show
@pet = Pet.find(params[:id])
# @hash = Gmaps4rails.build_markers([ @pet ]) do |pet, marker|
# marker.lat pet.latitude
# marker.lng pet.longitude
# # marker.infowindow render_to_string(partial: "/flats/map_box", locals: { flat: flat })
# end
@hash = [lat: @pet.latitude, lng: @pet.longitude ]
end
def new
@pet = Pet.new
end
def create
@pet = Pet.new(pet_params)
@pet.user = current_user
if @pet.save
redirect_to profile_path(current_user)
else
render :new
end
end
def edit
@pet = Pet.find(params[:id])
end
def update
@pet = Pet.find(params[:id])
@pet.update(pet_params)
redirect_to profile_path(current_user)
end
def destroy
@pet = Pet.find(params[:id])
@pet.destroy
redirect_to profile_path(current_user)
end
private
def pet_params
params.require(:pet).permit(:name, :photo, :photo_cache, :species, :walk, :address, :size, :age, :food)
end
end
<file_sep>class ChangeStartDateColumnName < ActiveRecord::Migration[5.0]
def change
rename_column :bookings, :start_date, :starts_at
rename_column :bookings, :end_date, :ends_at
end
end
<file_sep>class PagesController < ApplicationController
skip_before_action :authenticate_user!
def home
@pets = Pet.all
end
end
<file_sep>class BookingsController < ApplicationController
before_action :authenticate_user!
before_action :set_pet, only: [ :new, :create]
def index
@bookings = Booking.all
end
def show
@booking = Booking.find(params[:id])
end
def new
@booking = Booking.new
end
def create
@booking = @pet.bookings.build
@booking.starts_at = Date.strptime(booking_params[:starts_at], "%m/%d/%Y")
@booking.ends_at = Date.strptime(booking_params[:ends_at], "%m/%d/%Y")
@booking.user = current_user
if @booking.save
redirect_to profile_path(current_user)
else
render :new
end
end
def destroy
@booking = Booking.find(params[:id])
@booking.destroy
redirect_to profile_path(current_user)
end
private
def booking_params
params.require(:booking).permit(:starts_at, :ends_at)
end
def set_pet
@pet = Pet.find(params[:pet_id])
end
end
| 46ac6a34b7d5f099bda3c767b45d78dc25b1f490 | [
"Ruby"
] | 4 | Ruby | KaizokuoJ/pet-my-pet | b5d0cf89cb577e93556827c6a00a02eb1c60b0f7 | 7a5127913cc8e08971efe4a0fc6084e0715aabb7 |
refs/heads/master | <repo_name>LeighCurran/SamsungRemoteLibrary<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Eight.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Eight : INumberButton, IChannelButton
{
public string Code { get { return "KEY_8"; } }
public int Number { get { return 8; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Recording/Play.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Recording
{
public class Play : IRecordingButton
{
public string Code { get { return "KEY_PLAY"; } }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IChannelButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IChannelButton : IButton
{
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IVolumeButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IVolumeButton : IButton
{
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Demo.Console/Program.cs
using SamsungRemoteLibrary.Interfaces;
using SamsungRemoteLibrary.TvConnector;
namespace SamsungRemoteLibrary.Demo.Console
{
public class Program
{
class YourSettings : IRemoteControlIdentification, ITvSettings
{
// Change these properties
public string RemoteControlIp{get{return "192.168.1.35";}}
public string TvIp{get{return "192.168.1.184";}}
public int TvPortNumber{get{return 55000;}}
public string RemoteControlMac{get{return "0C-89-10-CD-43-28";}}
public string AppName{get{return "Anderbakk remote";}}
public override string ToString()
{
return string.Format(
"Application name:{4}\nRemote control IP: {0}\nRemote control mac: {1}\nTv address: {2}:{3}\n",
RemoteControlIp, RemoteControlMac, TvIp, TvPortNumber, AppName);
}
}
static void Main()
{
DisplayLogo();
var yourSettings = new YourSettings();
System.Console.WriteLine(yourSettings);
var remote = new RemoteControl(new SamsungTvConnection(yourSettings, new SamsungBytesBuilder(yourSettings)));
remote.Push("KEY_VOLDOWN");
System.Console.WriteLine("Command sent to TV.");
System.Console.ReadLine();
}
private static void DisplayLogo()
{
System.Console.WriteLine(@"
_ _ _ _ _ _
/ \ _ __ __| | ___ _ __| |__ __ _| | _| | _( )___
/ _ \ | '_ \ / _` |/ _ \ '__| '_ \ / _` | |/ / |/ /// __|
/ ___ \| | | | (_| | __/ | | |_) | (_| | <| < \__ \
/_/__ \_\_| |_|\__,_|\___|_| |_.__/ \__,_|_|\_\_|\_\ |___/
| _ \ ___ _ __ ___ ___ | |_ ___
| |_) / _ \ '_ ` _ \ / _ \| __/ _ \
| _ < __/ | | | | | (_) | || __/
|_| \_\___|_| |_| |_|\___/ \__\___|
");
}
}
}
<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IPowerButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IPowerButton : IButton
{ }
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IRemoteControlSettings.cs
namespace SamsungRemoteLibrary.Interfaces
{
public interface IRemoteControlSettings
{
string RemoteControlIp { get; }
string TvIp { get; }
int TvPortNumber { get; }
string RemoteControlMac { get; }
string AppName { get; }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IButton
{
string Code { get; }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Four.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Four : INumberButton, IChannelButton
{
public string Code { get { return "KEY_4"; } }
public int Number { get { return 4; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/NavigateUp.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
class NavigateUp : INavigationButton
{
public string Code { get { return "KEY_UP"; } }
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/Exit.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
public class Exit : INavigationButton
{
public string Code { get { return "KEY_EXIT"; } }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/RemoteControl.cs
namespace SamsungUniversalRemoteLibrary
{
public class RemoteControl : IRemoteControl
{
private readonly IConnectToTv _tvConnector;
public RemoteControl(IConnectToTv tvConnector)
{
_tvConnector = tvConnector;
}
public void Push(IButton button)
{
_tvConnector.Send(button);
}
public void Push(string button)
{
_tvConnector.Send(button);
}
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Volume/Mute.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Volume
{
public class Mute : IVolumeButton
{
public string Code { get { return "KEY_MUTE"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IButton.cs
namespace SamsungRemoteLibrary.Interfaces
{
public interface IButton
{
string Code { get; }
}
public interface IChannelButton : IButton
{
}
public interface INumberButton : IButton
{
int Number { get; }
}
public interface IRecordingButton : IButton { }
public interface INavigationButton : IButton
{
}
public interface IVolumeButton : IButton
{
}
public interface IPowerButton : IButton
{ }
public interface IMenuButton : IButton
{
}
public interface IMiscButton : IButton
{
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Misc/PowerOff.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Misc
{
public class PowerOff : IPowerButton
{
public string Code { get { return "KEY_POWEROFF"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Recording/Rewind.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Recording
{
public class Rewind : IRecordingButton
{
public string Code { get { return "KEY_REWIND"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/PictureSize.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class PictureSize : IMenuButton
{
public string Code { get { return "KEY_PICTURE_SIZE"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Zero.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Zero : INumberButton, IChannelButton
{
public string Code { get { return "KEY_0"; } }
public int Number { get { return 0; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Volume/VolumeDown.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Volume
{
public class VolumeDown : IVolumeButton
{
public string Code { get { return "KEY_VOLDOWN"; } }
}
}<file_sep>/README.md
Samsung Remote Library for .NET
====================
This project contains a library to control your Samsung TV over TCP.
Supports sending channel keys, navigation, recording, TV-guide, Smart Hub, volume etc.
Only tested on Samsung 55" 3D LED Smart TV UE55F8005.<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/Info.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class Info : IMenuButton
{
public string Code { get { return "KEY_INFO"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/Tools.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class Tools : IMenuButton
{
public string Code { get { return "KEY_TOOLS"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Two.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Two : INumberButton, IChannelButton
{
public string Code { get { return "KEY_2"; } }
public int Number { get { return 2; } }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/INavigationButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface INavigationButton : IButton
{
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/ICreateBytesForSamsung.cs
using System;
namespace SamsungRemoteLibrary.Interfaces
{
public interface ICreateBytesForSamsung
{
byte[] CreateIdentifier();
byte[] CreateSecondParameter();
byte[] CreateCommand(string command);
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Channel/ChannelList.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Channel
{
public class ChannelList : IChannelButton
{
public string Code { get { return "KEY_CH_LIST"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Three.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Three : INumberButton, IChannelButton
{
public string Code { get { return "KEY_3"; } }
public int Number { get { return 3; } }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IRecordingButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IRecordingButton : IButton { }
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Five.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Five : INumberButton, IChannelButton
{
public string Code { get { return "KEY_5"; } }
public int Number { get { return 5; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Misc/Mts.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Misc
{
public class Mts : IMiscButton
{
public string Code { get { return "KEY_MTS #Dual"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Volume/VolumeUp.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Volume
{
public class VolumeUp : IVolumeButton
{
public string Code { get { return "KEY_VOLUP"; } }
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/NavigateLeft.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
public class NavigateLeft : INavigationButton
{
public string Code { get { return "KEY_LEFT"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/Enter.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
public class Enter : INavigationButton
{
public string Code { get { return "KEY_ENTER"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Misc/Ad.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Misc
{
public class Ad : IMiscButton
{
public string Code { get { return "KEY_AD"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.TvConnector/SamsungBytesBuilder.cs
using System;
using System.Text;
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.TvConnector
{
/// <summary>
/// Builds the different byte arrays with app identification and the actual command.
///
/// Ported to .NET from https://github.com/instant-solutions/Java-Samsung-Remote-Library
/// </summary>
public class SamsungBytesBuilder : ICreateBytesForSamsung
{
private readonly IRemoteControlIdentification _settings;
private const string AppString = "samsung.remote";
private readonly string _nullValue = char.ToString((char) 0x00);
public SamsungBytesBuilder(IRemoteControlIdentification settings)
{
_settings = settings;
}
public byte[] CreateIdentifier()
{
var myIpBase64 = Base64Encode(_settings.RemoteControlIp);
var myMacBase64 = Base64Encode(_settings.RemoteControlMac);
var nameBase64 = Base64Encode(_settings.AppName);
var message =
char.ToString((char)0x64) +
_nullValue +
Format(myIpBase64.Length) +
_nullValue +
myIpBase64 +
Format(myMacBase64.Length) +
_nullValue +
myMacBase64 +
Format(nameBase64.Length) +
_nullValue +
nameBase64;
var wrappedMessage =
_nullValue +
Format(AppString.Length) +
_nullValue +
AppString +
Format(message.Length) +
_nullValue +
message;
return ConvertToBytes(wrappedMessage);
}
//Might be used for some TV models...
public byte[] CreateSecondParameter()
{
var message = ((char)0xc8) +
((char)0x00) + string.Empty;
var wrappedMessage =
_nullValue +
Format(AppString.Length) +
_nullValue +
AppString +
Format(message.Length) +
_nullValue +
message;
return ConvertToBytes(wrappedMessage);
}
public byte[] CreateCommand(string command)
{
var encodedCommand = Base64Encode(command);
var message =
_nullValue +
_nullValue +
_nullValue +
char.ToString((char)encodedCommand.Length) +
_nullValue +
encodedCommand;
var wrappedMessage =
_nullValue +
Format(AppString.Length) +
_nullValue +
AppString +
Format(message.Length) +
_nullValue +
message;
return ConvertToBytes(wrappedMessage);
}
private static string Format(int value)
{
return char.ToString((char)value);
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
private static byte[] ConvertToBytes(string value)
{
return Encoding.ASCII.GetBytes(value);
}
}
}
<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/ITvSettings.cs
namespace SamsungUniversalRemoteLibrary
{
public interface ITvSettings
{
string TvIp { get; }
int TvPortNumber { get; }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/SmartHub.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class SmartHub : IMenuButton
{
public string Code { get { return "KEY_CONTENTS"; } }
}
}
<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IMiscButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IMiscButton : IButton
{
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IRemoteControl.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IRemoteControl
{
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IMenuButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IMenuButton : IButton
{
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Misc/Rss.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Misc
{
public class Rss : IMiscButton
{
public string Code { get { return "KEY_RSS #Internet"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Seven.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Seven : INumberButton, IChannelButton
{
public string Code { get { return "KEY_7"; } }
public int Number { get { return 7; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IRemoteControl.cs
namespace SamsungRemoteLibrary.Interfaces
{
public interface IRemoteControl
{
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/Nine.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class Nine : INumberButton, IChannelButton
{
public string Code { get { return "KEY_9"; } }
public int Number { get { return 9; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/Guide.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class Guide : IMenuButton
{
public string Code { get { return "KEY_GUIDE"; } }
}
}<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/IRemoteControlIdentification.cs
namespace SamsungUniversalRemoteLibrary
{
public interface IRemoteControlIdentification
{
string RemoteControlIp { get; }
string RemoteControlMac { get; }
string AppName { get; }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IConnectToTv.cs
namespace SamsungRemoteLibrary.Interfaces
{
public interface IConnectToTv
{
void Send(IButton button);
void Send(string button);
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IRemoteControlIdentification.cs
namespace SamsungRemoteLibrary.Interfaces
{
public interface IRemoteControlIdentification
{
string RemoteControlIp { get; }
string RemoteControlMac { get; }
string AppName { get; }
}
public interface ITvSettings
{
string TvIp { get; }
int TvPortNumber { get; }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Recording/Pause.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Recording
{
public class Pause : IRecordingButton
{
public string Code { get { return "KEY_PAUSE"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.TvConnector/SamsungTvConnection.cs
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.TvConnector
{
public class SamsungTvConnection : IConnectToTv
{
private readonly ITvSettings _settings;
private readonly ICreateBytesForSamsung _createBytesForSamsung;
public SamsungTvConnection(ITvSettings settings, ICreateBytesForSamsung createBytesForSamsung)
{
_settings = settings;
_createBytesForSamsung = createBytesForSamsung;
}
public void Send(IButton button)
{
var identifier = _createBytesForSamsung.CreateIdentifier();
var secondParameter = _createBytesForSamsung.CreateSecondParameter();
var command = _createBytesForSamsung.CreateCommand(button.Code);
Send(_settings.TvIp, _settings.TvPortNumber,
new List<byte[]>
{
identifier,
secondParameter,
command
});
}
public void Send(string button)
{
var identifier = _createBytesForSamsung.CreateIdentifier();
var secondParameter = _createBytesForSamsung.CreateSecondParameter();
var command = _createBytesForSamsung.CreateCommand(button);
Send(_settings.TvIp, _settings.TvPortNumber,
new List<byte[]>
{
identifier,
secondParameter,
command
});
}
private void Send(string ipAddress, int portNumber, IEnumerable<byte[]> messages)
{
var listOfByteArrays = messages as IList<byte[]> ?? messages.ToList();
using (var socket = new Socket(SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(ipAddress, portNumber);
foreach (var message in listOfByteArrays)
{
socket.Send(message);
}
}
}
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/Return.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
public class Return : INavigationButton
{
public string Code { get { return "KEY_RETURN"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Channel/Source.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Channel
{
public class Source : IChannelButton
{
public string Code { get { return "KEY_SOURCE"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.Interfaces/IRequestBuilder.cs
using System;
namespace SamsungRemoteLibrary.Interfaces
{
public interface IRequestBuilder
{
byte[] CreateIdentifier(String callerMacAddress, String applicationName, String callerIpAddress);
byte[] CreateSecondParameter();
byte[] CreateCommand(string command);
byte[] CreateText(String text);
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary.TvConnector/RequestBuilder.cs
using System;
using System.Text;
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.TvConnector
{
public class RequestBuilder : IRequestBuilder
{
private const string AppString = "samsung.remote";
public byte[] CreateIdentifier(String callerMacAddress, String applicationName, String callerIpAddress)
{
var myIpBase64 = Base64Encode(callerIpAddress);
var myMacBase64 = Base64Encode(callerMacAddress);
var nameBase64 = Base64Encode(applicationName);
var message =
char.ToString((char)0x64) +
char.ToString((char)0x00) +
char.ToString((char)myIpBase64.Length) +
char.ToString((char)0x00) +
myIpBase64 +
char.ToString((char)myMacBase64.Length) +
char.ToString((char)0x00) +
myMacBase64 +
char.ToString((char)nameBase64.Length) +
char.ToString((char)0x00) +
nameBase64;
var part =
char.ToString((char)0x00) +
char.ToString((char)AppString.Length) +
char.ToString((char)0x00) +
AppString +
char.ToString((char)message.Length) +
char.ToString((char)0x00) +
message;
return ConvertToBytes(part);
}
//Might be used for some TV models...
public byte[] CreateSecondParameter()
{
var message = ((char)0xc8) +
((char)0x00) + string.Empty;
var part =
char.ToString((char)0x00) +
char.ToString((char)AppString.Length) +
char.ToString((char)0x00) +
AppString +
char.ToString((char)message.Length) +
char.ToString((char)0x00) +
message;
return ConvertToBytes(part);
}
public byte[] CreateCommand(string command)
{
var commandBase64 = Base64Encode(command);
var message =
char.ToString((char)0x00) +
char.ToString((char)0x00) +
char.ToString((char)0x00) +
char.ToString((char)commandBase64.Length) +
char.ToString((char)0x00) +
commandBase64;
var part =
char.ToString((char)0x00) +
char.ToString((char)AppString.Length) +
char.ToString((char)0x00) +
AppString +
char.ToString((char)message.Length) +
char.ToString((char)0x00) +
message;
return ConvertToBytes(part);
}
public byte[] CreateText(String text)
{
var textBase64 = Base64Encode(text);
var message =
char.ToString((char)0x01) +
char.ToString((char)0x00) +
char.ToString((char)textBase64.Length) +
char.ToString((char)0x00) +
textBase64;
var part =
char.ToString((char)0x01) +
char.ToString((char)AppString.Length) +
char.ToString((char)0x00) +
AppString +
char.ToString((char)message.Length) +
char.ToString((char)0x00) +
message;
return ConvertToBytes(part);
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
private static byte[] ConvertToBytes(string value)
{
return Encoding.ASCII.GetBytes(value);
}
}
}
<file_sep>/SamsungRemote/SamsungUniversalRemoteLibrary/INumberButton.cs
namespace SamsungUniversalRemoteLibrary
{
public interface INumberButton : IButton
{
int Number { get; }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Number/One.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Number
{
public class One : INumberButton, IChannelButton
{
public string Code { get { return "KEY_1"; }}
public int Number { get { return 1; } }
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/Menu.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class Menu : IMenuButton
{
public string Code { get { return "KEY_MENU"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Menu/Caption.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Menu
{
public class Caption : IMenuButton
{
public string Code { get { return "KEY_CAPTION #Subt"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Misc/WLink.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Misc
{
public class WLink : IMiscButton
{
public string Code { get { return "KEY_W_LINK #Media P"; } }
}
}
<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Navigation/NavigateRight.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Navigation
{
public class NavigateRight : INavigationButton
{
public string Code { get { return "KEY_RIGHT"; } }
}
}<file_sep>/SamsungRemote/SamsungRemoteLibrary/Buttons/Recording/Forward.cs
using SamsungRemoteLibrary.Interfaces;
namespace SamsungRemoteLibrary.Buttons.Recording
{
public class Forward : IRecordingButton
{
public string Code { get { return "KEY_FF"; } }
}
} | b255b8bfd37a87a8fdc3e80d2e3e20866700cbe5 | [
"Markdown",
"C#"
] | 61 | C# | LeighCurran/SamsungRemoteLibrary | df6ef4070930a651358ca42275dcc0129ab1202a | c9f25e526ea7438f8d6872ea3a65a5ab4ee3f76a |
refs/heads/master | <repo_name>liym0723/simple_form_imitation<file_sep>/lib/simple_form_imitation/wrappers/leaf.rb
module SimpleFormImitation
module Wrappers
class Leaf < Many # 单个组件
attr_reader :namespace
def initialize(namespace, options = {})
@namespace = namespace
@options = options
end
# input -> SimpleForm::Inputs::StringInput 实例
def render(input)
# b.use :placeholder
# #<SimpleForm::Wrappers::Leaf:0x000000000426daa0 @namespace=:placeholder, @options={}>,
# -> @namespace = placeholder
# m = 12.method("+")
# m.call(3) #=> 15
# m.call(20) #=> 32
# method.call(@options)
method = input.method(@namespace)
# #<Method: SimpleFormImitation::Inputs::StringInput#input>
if method.arity.zero?
method.call
else
method.call(@options)
end
# "<h1>Liym Test -> Leaf.#render</h1>"
end
end
end
end
<file_sep>/lib/simple_form_imitation/components/pattern.rb
module SimpleFormImitation
module Components
module Pattern
def pattern( wrapper_options = nil )
nil
end
end
end
end
<file_sep>/lib/simple_form_imitation/inputs/collection_radio_buttons_input.rb
module SimpleFormImitation
module Inputs
class CollectionRadioButtonsInput < CollectionInput
# 单选
def input(wrapper_options = nil)
label_method, value_method = detect_collection_methods
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
# "input_type -> radio_buttons"
# "attribute_name -> name"
# "collection -> [[\"YES\", true], [\"NO\", false]]"
# collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
@builder.send("collection_#{input_type}", attribute_name, collection, value_method, label_method,input_options, merged_input_options )
end
end
end
end<file_sep>/lib/simple_form_imitation/components/label_input.rb
module SimpleFormImitation
module Components
module LabelInput
extend ActiveSupport::Concern # 用来规范 model 代码逻辑。
included do
include SimpleFormImitation::Components::Labels
end
def label_input(wrapper_options = nil)
if options[:label] == false
# deprecated component -> 翻译 启用的组件
deprecated_component(:input, wrapper_options)
else
deprecated_component(:label, wrapper_options) + deprecated_component(:input, wrapper_options)
end
end
def deprecated_component(namespace, wrapper_options = nil)
method = method(namespace)
# "label === #<Method: SimpleForm::Inputs::StringInput(SimpleForm::Components::Labels)#label>"
# "input === #<Method: SimpleForm::Inputs::StringInput#input>"
# 每一个类型都单独写了 input
# label 就用的共同的 base include SimpleFormImitation::Components::LabelInput # label
if method.arity.zero?
method.call
else
method.call(wrapper_options)
end
end
end
end
end
<file_sep>/lib/simple_form_imitation/inputs/date_time_input.rb
module SimpleFormImitation
module Inputs
class DateTimeInput < Base
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
@builder.send(:"#{input_type}_select", attribute_name, options, merged_input_options)
end
end
end
end<file_sep>/lib/simple_form_imitation/components/placeholder.rb
module SimpleFormImitation
module Components
module Placeholder
def placeholder( wrapper_options = nil )
nil
end
end
end
end
<file_sep>/lib/simple_form_imitation.rb
require "simple_form_imitation/version"
require 'action_view'
require 'simple_form_imitation/action_view_extensions/form_helper'
# 仿 simple_form
# TODO 和 simple_form 同时使用时, @@全局变量会被覆盖 必须换掉名称
module SimpleFormImitation
extend ActiveSupport::Autoload # 引入延时加载
autoload :Helpers #
autoload :Wrappers
eager_autoload do
autoload :FormBuilder # -> 表格生成器
autoload :Inputs # -> 输入项
autoload :Components
end
# mattr_reader -> 只可读取
# mattr_accessor -> 可读 可写
# simple_form class
mattr_reader :form_class_imitation
@@form_class_imitation = :simple_form
# simple form default class
mattr_accessor :default_form_class_imitation
@@default_form_class_imitation = nil
mattr_accessor :label_text
@@label_text = ->(label, required, explicit_label) { "#{required} #{label}" }
# 默认包装器
mattr_accessor :default_wrapper
@@default_wrapper = :default
@@wrappers = {}
# You can define which elements should obtain additional classes. -> 那些元素获取其他类
mattr_accessor :generate_additional_classes_for
@@generate_additional_classes_for = %i[wrapper label input]
# input 默认class
mattr_accessor :input_class
@@input_class = nil
# 错误的方法
mattr_accessor :error_method
@@error_method = :first
# Define the way to render check boxes / radio buttons with labels.
# inline: input + label (default)
# nested: label > input
mattr_accessor :boolean_style
@@boolean_style = :inline
mattr_accessor :i18n_scope
@@i18n_scope = 'simple_form'
mattr_accessor :button_class
@@button_class = 'button'
# defaule errorr proc
mattr_accessor :field_error_proc_imitation
@@field_error_proc_imitation = proc do |html_tag, instance_tag|
# proc
# p = proc {|x,y| x = x, y = y}
# p.call(1,2) -> x = 1, y = 2
# p.call([1,2]) -> x = 1, y = 2
# p.call(1) -> x= 1, y =
# p.call(1,2,3) -> x = 1, y = 2
html_tag
end
# 检索给定的包装器
def self.wrapper(name)
@@wrappers[name.to_s] or "Couldn't find wrapper with name #{name}"
end
# 使用SimpleForm::Wrappers::Builder定义一个新的包装器 并给定存储名称
def self.wrappers(*args, &block)
if block_given?
# extract_options! 返回参数中的 hash
options = args.extract_options!
name = args.first || :default
@@wrappers[name.to_s] = build(options, &block)
else
@@wrappers
end
end
# 使用 SimpleForm::Wrappers::Builder 构架新的包装
# 初始化的时候 构建包装器
def self.build(options = {})
options[:tag] = :div if options[:tag].nil?
builder = SimpleFormImitation::Wrappers::Builder.new(options)
yield builder
SimpleFormImitation::Wrappers::Root.new(builder.to_a, options)
end
wrappers class: :input, hint_class: :field_with_hint, error_class: :field_with_errors, valid_class: :field_without_errors do |b|
# b -> SimpleFormImitation::Wrappers::Builder.new(options)
# b.use :html5
#
# b.use :min_max
# b.use :maxlength
# b.use :minlength
# b.use :placeholder
# b.optional :pattern
# b.optional :readonly
b.use :label_input
# b.use :hint, wrap_with: { tag: :span, class: :hint }
# b.use :error, wrap_with: { tag: :span, class: :error }
end
class Error < StandardError; end
# Your code goes here...
def self.setup
@@configured = true
yield self
end
def self.additional_classes_for(component)
generate_additional_classes_for.include?(component) ? yield : []
end
end
<file_sep>/lib/simple_form_imitation/inputs/boolean_input.rb
module SimpleFormImitation
module Inputs
class BooleanInput < Base
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
# nested -> 嵌套包装
# inline -> 不生成包装
if nested_boolean_style?
# 嵌套 TODO 一般不经常用这个属性
else
# 不产生包装
build_check_box(unchecked_value, merged_input_options)
end
end
def nested_boolean_style?
# Hash.fetch(key, default) -> 取出key的值,没有的情况下默认给一个
options.fetch(:boolean_style, SimpleFormImitation.boolean_style) == :nested
end
# 默认值赋予 0
def unchecked_value
options.fetch(:unchecked_value, '0')
end
def check_value
options.fetch(:checked_value, '1')
end
def build_check_box unchecked_value, options
# check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
@builder.check_box(attribute_name, options, check_value, unchecked_value)
end
end
end
end<file_sep>/lib/simple_form_imitation/inputs/base.rb
require 'active_support/core_ext/string/output_safety'
require 'action_view/helpers'
module SimpleFormImitation
module Inputs
class Base
include ERB::Util # html_escape
include ActionView::Helpers::TranslationHelper
include SimpleFormImitation::Components::LabelInput
include SimpleFormImitation::Components::Labels
include SimpleFormImitation::Components::Errors
include SimpleFormImitation::Components::Maxlength
include SimpleFormImitation::Components::Minlength
include SimpleFormImitation::Components::MinMax
include SimpleFormImitation::Components::Pattern
include SimpleFormImitation::Components::Placeholder
include SimpleFormImitation::Helpers::Disabled
include SimpleFormImitation::Helpers::Readonly
include SimpleFormImitation::Helpers::Validators
attr_reader :input_type, :options, :attribute_name, :input_html_options, :input_html_classes, :html_classes, :column
# # @builder -> #<SimpleForm::FormBuilder:0x0000000007bf8f40>
delegate :template, :object, :object_name, :lookup_model_names, :lookup_action, to: :@builder
class_attribute :default_options
self.default_options = {}
# def self.enable(*keys)
# options = self.default_options.dup
# keys.each{|k| options.delete(k)}
# self.default_options = options
# end
#
# def self.disable(*keys)
# options = self.default_options.dup
# keys.each { |key| options[key] = false }
# self.default_options = options
# end
#
# enable :hint
#
# disable :maxlength, :minlength, :placeholder, :pattern, :min_max
def initialize(builder, attribute_name, column, input_type, options = {})
options = options.dup # dup 创建新的实例
@builder = builder
@attribute_name = attribute_name
@column = column
@input_type = input_type
# reverse_merge! 反向合并 前者覆盖后者
@options = options.reverse_merge!(self.class.default_options)
# "@builder -> #<SimpleFormImitation::FormBuilder:0x00000000095c5630>"
# "@attribute_name -> name"
# "@column -> #<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x00000000093f16d8>"
# "@input_type -> string"
# "@options -> {:label=>\"Your username please\", :error=>\"NAME is mandatory\"}"
# "@template -> "
# "input_html_classes -> [:string, :required]"
# "input_html_options -> {:class=>[:string, :required], :required=>true, :\"aria-required\"=>true, :\"aria-invalid\"=>true, :maxlength=>255, :minlength=>nil, :placeholder=>nil}"
@html_classes = SimpleFormImitation.additional_classes_for(:input) {additional_classes}
@input_html_classes = @html_classes.dup
# 默认class
input_html_classes = self.input_html_classes
if SimpleFormImitation.input_class && input_html_classes.any?
input_html_classes << SimpleFormImitation.input_class
end
@input_html_options = html_options_for(:input, input_html_classes)
end
def additional_classes
@additional_classes ||= [input_type]
end
def html_options_for(namespace, css_classes)
html_options = options["#{namespace}_html".to_sym]
html_options = html_options ? html_options.dup : {}
css_classes << html_options[:class] if html_options.key?(:class)
html_options[:class] = css_classes unless css_classes.empty?
html_options
end
# 拼接 自定义 class
def merge_wrapper_options(options, wrapper_options)
if wrapper_options
wrapper_options = set_input_classes(wrapper_options)
wrapper_options.merge(options) do |k, oldval, newval|
case key.to_s
when "class"
Array(oldval) + Array(newval)
when "data","aria"
oldval.merge(newval)
else
newval
end
end
else
options
end
end
def set_input_classes(wrapper_options)
wrapper_options = wrapper_options.dup
error_class = wrapper_options.delete(:error_class)
valid_class = wrapper_options.delete(:valid_class)
if error_class.present? && has_errors?
wrapper_options[:class] = "#{wrapper_options[:class] } #{error_class}"
end
if valid_class.present? && vaild?
wrapper_options[:class] = "#{wrapper_options[:class]} #{valid_class}"
end
wrapper_options
end
def limit
# "column -> #<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x00000000093e1f80>"
# "decimal_limit -> 256"
# "column_limit -> 255"
if column
decimal_or_float? ? decimal_limit : column_limit
end
end
def decimal_or_float?
column.type == :float || column.type == :decimal
end
def decimal_limit
column_limit && (column_limit + 1)
end
def column_limit
column.limit
end
def translate_from_namespace(namespace, default = '')
# 根据 namespace 查找到 translate
# "model_names -> [\"user\"]"
# "lookup_action -> new"
# "reflection_or_attribute_name -> name"
model_names = lookup_model_names.dup
# shift 删除首个 且返回
while !model_names.empty?
end
end
def i18n_scope
SimpleFormImitation.i18n_scope
end
def input_options
options
end
end
end
end<file_sep>/lib/generators/simple_form_imitation/install_generator.rb
# frozen_string_literal: true
module SimpleFormImitation
module Generators
# generate 生成器
class InstallGenerator < Rails::Generators::Base
# 存储并返回定义这个类所在的位置
source_root File.expand_path('../templates', __FILE__)
def copy_config
# 复制 initializers 目录
directory 'config/initializers'
end
end
end
end
<file_sep>/lib/simple_form_imitation/components/hints.rb
module SimpleFormImitation
module Components
module Hints
def hint( wrapper_options = nil )
nil
end
end
end
end
<file_sep>/lib/simple_form_imitation/helpers/validators.rb
# 验证
module SimpleFormImitation
module Helpers
module Validators
def has_validators?
# validators_on 列出用于验证特定属性的所有验证器。
@has_validators ||= attribute_name && object.class.respond_to?(:validators_on)
end
def attribute_validators
object.class.validators_on(attribute_name)
end
def find_validator(kind)
attribute_validators.find{|v| v.kind == kind} if has_validators?
end
end
end
end
<file_sep>/lib/simple_form_imitation/wrappers.rb
module SimpleFormImitation
module Wrappers
autoload :Root, 'simple_form_imitation/wrappers/root'
autoload :Many, 'simple_form_imitation/wrappers/many'
autoload :Builder, 'simple_form_imitation/wrappers/builder'
autoload :Single, 'simple_form_imitation/wrappers/single' # 包含一个组件的包装器优化
autoload :Leaf, 'simple_form_imitation/wrappers/leaf' # 对一个组件的包装器
end
end<file_sep>/lib/simple_form_imitation/form_builder.rb
require 'simple_form_imitation/map_type'
# 表单生成器
module SimpleFormImitation
class FormBuilder < ActionView::Helpers::FormBuilder
extend ActiveSupport::Autoload # 引入延时加载
# attr_reader -> 提供读取方法
# template, object_name 在 ActionView::Helpers::FormBuilder 中初始化了
attr_reader :wrapper, :object, :template, :object_name
extend MapType # 加载映射
include SimpleFormImitation::Inputs # 加载inputs
ACTIONS = {
'create' => 'new',
'update' => 'edit'
}
map_type :string, to: SimpleFormImitation::Inputs::StringInput
map_type :text, to: SimpleFormImitation::Inputs::TextInput
map_type :file, to: SimpleFormImitation::Inputs::FileInput
map_type :password, to: SimpleFormImitation::Inputs::PasswordInput
map_type :hidden, to: SimpleFormImitation::Inputs::HiddenInput
map_type :datetime, to: SimpleFormImitation::Inputs::DateTimeInput
map_type :boolean, to: SimpleFormImitation::Inputs::BooleanInput
map_type :select, to: SimpleFormImitation::Inputs::CollectionSelectInput
map_type :radio_buttons, to: SimpleFormImitation::Inputs::CollectionRadioButtonsInput
def initialize(*)
super
# @object -> 对象
# convert_to_model -> 对象转换成 Model 或 model_name 进行处理
# @object -> User
@object = convert_to_model(@object)
@defaults = options[:defaults]
@wrapper = SimpleFormImitation.wrapper(options[:wrapper] || SimpleFormImitation.default_wrapper)
end
# 根据 字段类型, 渲染出不同的内容
#
# call 调用block. &block 代码块
def input attribute_name, options = {}, &block
# deep_dup -> 拷贝hash
# deep_merge -> 合并hash 并返回
# deep_dup.deep_merge 拷贝hash 并合并hash, 返回一个新的hash
options = @defaults.deep_dup.deep_merge(options) if @defaults # 默认样式存在的话
# 根据 name 获取到 inputs 类型 获取到类型
# #<SimpleFormImitation::Inputs::StringInput:0x0000000009199188>
input = find_input(attribute_name, options, &block)
# 获取到类型 接下来就是需要获取到包装器了(wrapper)
# "wrapper -> #<SimpleFormImitation::Wrappers::Root:0x0000000006f9b5b8>"
wrapper = find_wrapper(input.input_type, options)
wrapper.render input
end
# Find an input based on the attribute name. 根据属性名称查找对应类型
def find_input attribute_name, options = {}, &block
column = find_attribute_column(attribute_name) # -> ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString
input_type = default_input_type(attribute_name, column, options) # :string
# 查询 并创建 inputs 实例对象出来
find_mapping(input_type).new(self, attribute_name, column, input_type, options)
end
def find_attribute_column attribute_name
# has_attribute?(name) -> object 是否存在 name 这个code
return unless @object.has_attribute?(attribute_name)
if @object.respond_to?(:type_for_attribute)
# type_for_attribute -> 返回具有给定名称的属性类型
@object.type_for_attribute(attribute_name.to_s) # -> <ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x00000000094dd880
elsif @object.respond_to?(:column_for_attribute)
# column_for_attribute 返回指定属性的列对象
# person.column_for_attribute(:name) -> #<ActiveRecord::ConnectionAdapters::Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
@object.column_for_attribute(attribute_name)
end
end
def default_input_type attribute_name, column, options = {}
return options[:as].to_sym if options[:as] # 如果提供了类型 就不需要去猜测
return :select if options[:collection]
input_type = column.try(:type) # 通过find_attribute_column 获取到数据库的字段类型
case input_type
when :timestamp
:datetime
when :string, :citext, nil
case attribute_name.to_s
when /(?:\b|\W|_)password(?:\b|\W|_)/ then :password
when /(?:\b|\W|_)time_zone(?:\b|\W|_)/ then :time_zone
when /(?:\b|\W|_)country(?:\b|\W|_)/ then :country
when /(?:\b|\W|_)email(?:\b|\W|_)/ then :email
when /(?:\b|\W|_)phone(?:\b|\W|_)/ then :tel
when /(?:\b|\W|_)url(?:\b|\W|_)/ then :url
else
# 是否是文件类型
file_method?(attribute_name) ? :file : (input_type || :string)
end
else
input_type
end
end
# 判断是否是文件类型
def file_method?(attribute_name)
@object.respond_to?("#{attribute_name}_attachment") ||
@object.respond_to?("remote_#{attribute_name}_url") ||
@object.respond_to?("#{attribute_name}_attacher") ||
@object.respond_to?("#{attribute_name}_file_name")
end
# 尝试查找映射 mapping -> 映射
# 尝试查找映射。 它遵循以下规则:
# 1. 如果成功, 他将尝试查找注册的映射
# 尝试在对象范围内查找具有相同名称的替代品
# 或使用找到的映射
# 2. 如果不是 退回到 input_type input
# 3. 如果不是 退回到 SimpleForm::Inputs::#{input_type}Input
# input_type = string -> return SimpleForm::Inputs::StringInput
def find_mapping(input_type)
# self.class.mappings[input_type] -> SimpleForm::Inputs::StringInput
# 根据 type 找到对应的input
self.class.mappings[input_type]
end
# 查找包装器
def find_wrapper input_type, options
wrapper
end
# 从object_name混乱中提取模型名称
def lookup_model_names
@lookup_model_names ||= begin
# scan 重复将模式与self匹配,并返回匹配的子字符串数组
names = object_name.to_s.scan().flatten
names.each { |name| name.gsub!('_attributes', '') }
names.freeze # freeze 禁止修改, 冻结
end
end
# 查找 使用的操作(controller)。
def lookup_action
@lookup_action ||= begin
action = template.controller template.controller && template.controller.action_name
return unless action
action = action.to_s
ACTIONS[action] || action
end
end
def button(type, *args, &block)
# extract_options! 筛选出hash, 不存在则返回 {}
options = args.extract_options!.dup
options[:class] = [SimpleFormImitation.button_class, options[:class]].compact # 合并class
args << options
# 支持自定义 button
# "self -> #<SimpleForm::FormBuilder:0x00000000097cb808>"
if respond_to?(:"#{type}_button")
send(:"#{type}_button", *args, &block)
# module SimpleForm
# class FormBuilder
# def submit_button(*args, &block)
# ActionController::Base.helpers.content_tag(:div, class: 'form-actions') do
# submit(*args, &block)
# end
# end
# end
# end
else
send(type, *args, &block)
end
end
def full_error(attribute_name, options = {})
options = options.dup
options[:error_prefix] ||= if object.class.respond_to?(:human_attribute_name)
# human_attribute_name I18n 获取对应文言
object.class.human_attribute_name(attribute_name.to_s)
else
# humanize
# 调整属性名称以显示给最终用户
# 1. 删除后缀 _id
# 2. 删除前 _
# 3. 用空格替换下划线
# 4. 除首字母外,所有单词均小写
# 5.大写第一个单词
attribute_name.to_s.humanize
end
error(attribute_name, options)
end
def error attribute_name, options = {}
options = options.dup
options[:error_html] = options.except(:error_tag, :error_prefix, :error_method)
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
wrapper.find(:error).
render(SimpleFormImitation::Inputs::Base.new(self, attribute_name, column, input_type, options))
end
end
end
<file_sep>/lib/simple_form_imitation/inputs/collection_select_input.rb
module SimpleFormImitation
module Inputs
class CollectionSelectInput < CollectionInput
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
label_method,value_method = detect_collection_methods
# collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
@builder.collection_select(attribute_name, collection, value_method, label_method, input_options, merged_input_options)
end
end
end
end<file_sep>/lib/simple_form_imitation/inputs.rb
module SimpleFormImitation
module Inputs
extend ActiveSupport::Autoload
autoload :Base
autoload :StringInput
autoload :TextInput
autoload :FileInput
autoload :PasswordInput
autoload :BooleanInput
autoload :DateTimeInput
autoload :HiddenInput
autoload :CollectionInput
autoload :CollectionSelectInput
autoload :CollectionRadioButtonsInput
end
end
<file_sep>/lib/simple_form_imitation/components/errors.rb
module SimpleFormImitation
module Components
module Errors
def error(wrapper_options = nil)
error_text if has_errors?
end
def has_errors?
# object -> <User:0x0000000009468378
object_with_errors? || object.nil? && has_custom_error?
end
def object_with_errors?
object && object.respond_to?(:errors) && errors.present?
end
def has_custom_error?
# "options[:error] -> NAME is mandatory"
options[:error].is_a?(String)
end
def errors
@errors ||= errors_on_attribute
end
def errors_on_attribute
object.errors[attribute_name] || []
end
def error_text
# 如果是一个错误 就取一个, 否则只取第一个
text = has_custom_error? ? options[:error] : errors.send(error_method)
# lstrip 去掉前置空格
# html_safe html格式
# 错误前缀 错误
"#{html_escape(options[:error_prefix])} #{html_escape(text)}".lstrip.html_safe
end
def error_method
options[:error_method] || SimpleFormImitation.error_method
end
def has_value?
object && object.respond_to?(attribute_name) && object.send(attribute_name).present?
end
def valid?
!has_errors? && has_value?
end
end
end
end
<file_sep>/lib/simple_form_imitation/components/min_max.rb
module SimpleFormImitation
module Components
module MinMax
def min_max( wrapper_options = nil )
nil
end
end
end
end
<file_sep>/lib/simple_form_imitation/wrappers/many.rb
module SimpleFormImitation
module Wrappers
class Many
attr_reader :namespace, :defaults, :components
def initialize(namespace, components, defaults = {})
@namespace = namespace
@components = components
@defaults = defaults
@defaults[:tag] = :div unless @defaults.key?(:tag)
@defaults[:class] = Array(@defaults[:class])
end
def render(input)
# "input -> #<SimpleFormImitation::Inputs::StringInput:0x0000000009144098>"
# "input.options -> {:label=>\"Your username please\", :error=>\"NAME is mandatory\"}"
# "components -> []"
content = "".html_safe
options = input.options
# 拼接 content
components.each do |component|
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6af20>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6ae30>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6a8b8>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6a6d8>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6a4f8>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f6a2c8>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f69fd0>"
# "component -> #<SimpleFormImitation::Wrappers::Leaf:0x0000000007f69f58>" # 一个
# "component -> #<SimpleFormImitation::Wrappers::Single:0x0000000007f69cb0>" # 一组
# "component -> #<SimpleFormImitation::Wrappers::Single:0x0000000007f69a08>" # 一组
# b.xxxx :aaa , aaa -> namespace
next if options[component.namespace] == false
rendered = component.render(input)
# safe_concat 如果 可用则用;否则用 concat
# content.class -> ActiveSupport::SafeBuffer
# # 在 Active Support 里也提供了 safe_concat 方法,如果 可用则用;否则用 concat
# 字符串拼接
content.safe_concat rendered.to_s if rendered
end
wrap(input, options, content)
end
def wrap input, options, content
# "input -> #<SimpleFormImitation::Inputs::StringInput:0x000000000bdee9b8>"
# "options -> {:label=>\"Your username please\", :error=>\"NAME is mandatory\"}"
# "content- > <label for=\"user_name\"><abbr title='required'>*</abbr> Your username please</label><input type=\"text\" name=\"user[name]\" id=\"user_name\" />"
return content if options[namespace] == false
tag = (namespace && options["#{namespace}_tag".to_sym]) || @defaults[:tag]
return content unless tag
klass = html_classes(input, options)
opts = html_options(options)
opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
# 给 class 拼接 class
input.template.content_tag(tag, content, opts) # -> <tag class=opts>content</tag>
end
def html_classes(input, options)
# dup 复制 但不复制拓展
@defaults[:class].dup
end
def html_options(options)
(@defaults[:html] || {}).merge(options["#{namespace}_html".to_sym] || {})
end
def find(name)
return self if namespace == name
@components.try(:each) do |c|
if c.is_a?(Symbol)
return nil if c == namespace
elsif value = c.find(name)
return value
end
end
nil
end
end
end
end
<file_sep>/lib/simple_form_imitation/components/labels.rb
module SimpleFormImitation
module Components
module Labels
extend ActiveSupport::Concern # module ClassMethods
module ClassMethods
def translate_required_html
"<abbr title='#{translate_required_text}'>#{translate_required_mark}</abbr>"
end
def translate_required_text
"required"
end
def translate_required_mark
"*"
end
end
def label(wrapper_options = nil)
label_options = merge_wrapper_options(label_html_options, wrapper_options)
# "@builder -> #<SimpleFormImitation::FormBuilder:0x00000000094cd2c8>"
# "attribute_name ->name"
@builder.label(attribute_name, label_text, label_options)
end
def label_text
# "html_escape(raw_label_text) -> Your username please"
# "required_label_text -> <abbr title=\"required\">*</abbr>"
# "options[:label] -> Your username please"
# html_escape 转义下 避免特殊字符
text = options[:label_text] || SimpleForm.label_text.call(html_escape(raw_label_text), required_label_text, options[:label].present?)
text.to_s.strip.html_safe
end
def raw_label_text
options[:label] || label_translation
end
# 必填 选则不同的 text
def required_label_text
self.class.translate_required_html.dup
end
# First check labels translation and then human attribute name.
# 首先检查标签翻译,然后检查人员属性名称。
def label_translation
"name"
end
# 获取到自定义
#<%= f.input :name,label: 'Your username please', error: 'NAME is mandatory', label_html: { class: 'my_class' } %>
def label_html_options
label_html_classes = SimpleFormImitation.additional_classes_for(:label) {
[input_type]
}
html_options_for(:label, label_html_classes)
end
end
end
end
<file_sep>/lib/simple_form_imitation/wrappers/root.rb
module SimpleFormImitation
module Wrappers
class Root < Many
attr_reader :options
def initialize(*args)
super(:wrapper, *args)
@options = @defaults.except(:tag, :class, :error_class, :hint_class)
end
def render(input)
input.options.reverse_merge!(@options)
super
end
def html_classes(input, options)
# "options -> {:label=>\"Your username please\", :error=>\"NAME is mandatory\"}"
css = options[:wrapper_class] ? Array(options[:wrapper_class]) : @defaults[:class]
# 根据配置 增加
css += SimpleFormImitation.additional_classes_for(:wrapper) do
input.additional_classes
end
# 错误信息
css << html_class(:error_class, options){ input.has_errors?}
css.compact
end
def html_class(key, options)
css = (options["wrapper_#{key}".to_sym] || @defaults[key])
css if css && yield
end
# Provide a fallback if name cannot be found. 找不到名称 提供备用
def find(name)
super || SimpleFormImitation::Wrappers::Many.new(name, [Leaf.new(name)])
end
end
end
end
<file_sep>/lib/simple_form_imitation/inputs/collection_input.rb
module SimpleFormImitation
module Inputs
class CollectionInput < Base
# 确定正确的方法以查找集合的标签和值。
# #如果未定义标签或值方法,将尝试根据以下内容查找它们
# #关于可以通过配置的默认标签和值方法
# #SimpleForm.collection_label_methods和
# #SimpleForm.collection_value_methods。
def detect_collection_methods
label, value = options.delete(:label_method), options.delete(:value_method)
# 如果某一个值不存在的话
unless label && value
# 查询值
common_method_for = detect_common_display_methods
label ||= common_method_for[:label]
value ||= common_method_for[:value]
end
[label, value]
end
# 检测常见的显示方法
def detect_common_display_methods
# TODO 不考虑,没有就给一个默认
{label: :first, value: :second}
end
def collection
@collection ||= begin
collection = options.delete(:collection) || [["YES",true],["NO",false]]
collection.respond_to?(:call) ? collection.call : collection.to_a
end
end
end
end
end<file_sep>/lib/simple_form_imitation/components/maxlength.rb
module SimpleFormImitation
module Components
module Maxlength
def maxlength( wrapper_options = nil )
# maximum_length_from_validation -> 自定义验证 或 长度验证
# limit 数据库长度
# 1. 自定义长度, 2 验证长度, 3 数据库数据长度
input_html_options[:maxlength] ||= maximum_length_from_validation || limit
nil
end
def maximum_length_from_validation
# 自定义长度 或者 长度验证
maxlength = options[:maxlength]
if maxlength.is_a?(String) || maxlength.is_a?(Integer)
# 自定义长度
maxlength
else
# 最大长度
# ,length:{ maximum: 200}
length_validator = find_length_validator
maximum_length_value_from(length_validator)
end
end
def find_length_validator
find_validator(:length)
end
def maximum_length_value_from(length_validator)
if length_validator
length_validator.options[:is] || length_validator.options[:maximum]
end
end
end
end
end
<file_sep>/lib/simple_form_imitation/map_type.rb
# frozen_string_literal: true
require 'active_support/core_ext/class/attribute'
module SimpleFormImitation
module MapType
def self.extended(base)
base.class_attribute :mappings
base.mappings = {}
end
def map_type(*types)
# extract_options! 把可选参数里的 Hash 部分,萃取出来。
map_to = types.extract_options![:to]
raise ArgumentError, "You need to give :to as option to map_type" unless map_to
# (1..10).each_with_object([]) { |i, a| a << i*2 } #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
self.mappings = mappings.merge types.each_with_object({}) { |t, m| m[t] = map_to }
end
end
end<file_sep>/lib/simple_form_imitation/helpers.rb
module SimpleFormImitation
module Helpers
autoload :Disabled, 'simple_form_imitation/helpers/disabled' # 是否禁止输入
autoload :Readonly, 'simple_form_imitation/helpers/readonly' # 是否只读
autoload :Validators, 'simple_form_imitation/helpers/validators'
end
end<file_sep>/lib/simple_form_imitation/helpers/readonly.rb
# 无法编辑
module SimpleFormImitation
module Helpers
module Readonly
end
end
end
<file_sep>/lib/simple_form_imitation/helpers/disabled.rb
# 只读
module SimpleFormImitation
module Helpers
module Disabled
end
end
end
<file_sep>/lib/simple_form_imitation/action_view_extensions/form_helper.rb
module SimpleFormImitation
module ActionViewExtensions
module FormHelper
def test_simple_form_for record, options = {}, &block
# 重写表单构造器 ActionView::Helpers::FormBuilder
options[:builder] ||= SimpleFormImitation::FormBuilder
options[:html] ||= {}
if options[:html].key? :class
# 使用自定义class
options[:html][:class] = [SimpleFormImitation.form_class_imitation,options[:html][:class]].compact # compact -> 去掉 nil
else
# 使用默认 class
options[:html][:class] = [SimpleFormImitation.form_class_imitation, SimpleFormImitation.default_form_class_imitation,].compact
end
# 重写 错误的情况,暂时没实现包裹
with_simple_form_field_error_proc do
form_for record,options,&block
end
end
private
def with_simple_form_field_error_proc
# 从 action view 获取默认的错误代码块
default_field_error_proc = ::ActionView::Base.field_error_proc
begin
# 覆盖 ActionView 的错误代码块
::ActionView::Base.field_error_proc = SimpleFormImitation.field_error_proc_imitation
yield if block_given?
ensure
# 一定会执行的, 还原 ActionView 的错误代码块
::ActionView::Base.field_error_proc = default_field_error_proc
end
end
end
end
end
# 加载 FormHelper
ActiveSupport.on_load :action_view do
::ActionView::Base.send :include, SimpleFormImitation::ActionViewExtensions::FormHelper
end<file_sep>/lib/simple_form_imitation/components/minlength.rb
module SimpleFormImitation
module Components
module Minlength
def minlength( wrapper_options = nil )
nil
end
end
end
end
| ac778cc3f033b292da97fc9da4d9f4396dd6ae39 | [
"Ruby"
] | 29 | Ruby | liym0723/simple_form_imitation | 26ea8d893187b36d9be373118e385183db17a553 | 8465a33506512a85eb825a24b90eea5aefbfe9a8 |
refs/heads/master | <file_sep>server.port=8888
logging.level.root=info
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
logging.file=../AllAppLog/demonegotiator.log<file_sep>package com.exchange.negotiator.demonegotiator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemonegotiatorApplication {
public static void main(String[] args) {
SpringApplication.run(DemonegotiatorApplication.class, args);
}
}
<file_sep>package com.exchange.negotiator.demonegotiator.service;
import com.exchange.negotiator.demonegotiator.model.Stock;
import com.exchange.negotiator.demonegotiator.model.StockResponse;
public interface NegotiatorService {
Stock getStock(String stockId);
StockResponse createStock(Stock stock);
Stock updateStock(Stock stock);
}
<file_sep>package com.exchange.negotiator.demonegotiator.service;
import com.exchange.negotiator.demonegotiator.model.Stock;
import com.exchange.negotiator.demonegotiator.model.StockResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@Component
public class NegotiatorServiceImpl implements NegotiatorService {
public static final Logger logger = LoggerFactory.getLogger(NegotiatorServiceImpl.class);
private String path = "http://localhost:8080/stock/";
@Override
public Stock getStock(String stockId) {
logger.info("Inside NegotiatorServiceImpl getStock method");
Stock stock = new Stock();
try {
ObjectMapper mapper = new ObjectMapper();
StringBuilder baseUrl = new StringBuilder(path);
URL url = new URL(baseUrl.append(stockId).toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userCredentials = "username:<PASSWORD>";
String basicAuth = "Basic " + new String(Base64.encodeBase64(userCredentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
//StringBuilder stockDetails = new StringBuilder("");
while ((output = br.readLine()) != null) {
// stockDetails.append(output);
stock = mapper.readValue(output, Stock.class);
}
conn.disconnect();
logger.info("Exiting NegotiatorServiceImpl getStock method");
return stock;
} catch (MalformedURLException e) {
logger.error("Exiting NegotiatorServiceImpl getStock method URL error " + e);
} catch (IOException e) {
logger.error("Exiting NegotiatorServiceImpl getStock method IO error " + e);
}
return null;
}
@Override
public StockResponse createStock(Stock stock) {
logger.info("Inside NegotiatorServiceImpl createStock method");
StockResponse stockResponse = new StockResponse();
try {
ObjectMapper mapper = new ObjectMapper();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
String userCredentials = "<PASSWORD>:password";
String basicAuth = "Basic " + new String(Base64.encodeBase64(userCredentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
/*String input = "{\"stockId\":\"" + stock.getStockId() + "\",\"price\":\""+ stock.getPrice() +"\",\"companyName\":\""+stock.getCompanyName()+"\"}\n" +
"\n";*/
String input = mapper.writeValueAsString(stock);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); }
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
// StringBuilder status = new StringBuilder("");
while ((output = br.readLine()) != null) {
// status.append(output);
stockResponse = mapper.readValue(output, StockResponse.class);
}
conn.disconnect();
logger.info("Exiting NegotiatorServiceImpl createStock method");
return stockResponse;
} catch (MalformedURLException e) {
logger.error("Exiting NegotiatorServiceImpl createStock method URL error " + e);
} catch (IOException e) {
logger.error("Exiting NegotiatorServiceImpl createStock method IO error " + e);
stockResponse.setStatusMessage(e.getMessage());
}
return stockResponse;
}
@Override
public Stock updateStock(Stock stock) {
logger.info("Exiting NegotiatorServiceImpl updateStock method");
try {
ObjectMapper mapper = new ObjectMapper();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
String userCredentials = "username:<PASSWORD>";
String basicAuth = "Basic " + new String(Base64.encodeBase64(userCredentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
/*String input = "{\"stockId\":\"" + stock.getStockId() + "\",\"price\":\""+ stock.getPrice() +"\",\"companyName\":\""+stock.getCompanyName()+"\"}\n" +
"\n";*/
String input = mapper.writeValueAsString(stock);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); }
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
//StringBuilder stockDetails = new StringBuilder("");
while ((output = br.readLine()) != null) {
//stockDetails.append(output);
stock = mapper.readValue(output, Stock.class);
}
conn.disconnect();
logger.info("Exiting NegotiatorServiceImpl updateStock method");
return stock;
} catch (MalformedURLException e) {
logger.error("Exiting NegotiatorServiceImpl updateStock method URL error " + e);
} catch (IOException e) {
logger.error("Exiting NegotiatorServiceImpl updateStock method IO error " + e);
}
return null;
}
}
| a5b2611fc4a63c47f739843268b7c1fcdc6538cf | [
"Java",
"INI"
] | 4 | INI | XI966-tejpratapkushawaha/demonegotiator | 8ca480dbce3c92b97296a031054f03f40a181df5 | bbc39cbf3c704010aea09591bf6e3fd1ee7a3210 |
refs/heads/master | <repo_name>tangciwei/react-didact<file_sep>/readme.md
# react 原理学习
- fiber 数据结构,将执行过程分层一份一份的,这样就不会阻塞 ui 渲染,所以要在上面记录一些信息,3 个指针;
- Reconciliation,指的是更新时,去 diff。函数执行也在这个阶段,这里也包括 useState 的执行。
- commit 阶段,真正更新 dom。3 种情况的区别
## fiber 数据结构
原因方便找下一个 fiber/上一个
One of the goals of this data structure is to make it easy to find the next unit of work. That’s why each fiber has a link to its first child, its next sibling and its parent.
优先 child/sibling/parent
## Reconciliation 阶段
1. 首次+更新,先构造 fiber 数据结构,顺便得到 diff 数据,每次要做的事情是(当前 dom 生成,首次),diff children 得到数据;
2. 最后 commitRoot, 根据 diff 的数据,进行相应更新。
3. 新增 dom
4. 删除 dom
5. 属性
1. 删除旧属性/事件
2. 新增新属性/事件
6. 再次归零,旧的 currentRoot 和 wipRoot
## 函数和 hooks 机制
- 函数,无非就是让其执行一次;
- 中间有 useState 时,执行就会有闭包,闭包里面放着 hook,当下次 setState 时,会将更新事件放入 hook 的队列里面,然后下次 render 时,就会执行队列里面的函数。
- 这当中,每个函数多个 useState 区分完全是靠 index。
## 其他资料
- toyReact :
https://segmentfault.com/a/1190000023616070
<file_sep>/src/didact.ts
declare var requestIdleCallback: {
(callback: {
(deadline: Deadline): void;
}): void;
}
interface Deadline {
timeRemaining(): number
}
type ElementType = string | "TEXT_ELEMENT" | Function;
interface Props {
[key: string]: any;
children: (VDom | string)[];
}
interface VDom {
type: ElementType;
props: Props;
}
type DOM = Text | Element;
interface Fiber {
props: Props;
type?: ElementType
dom?: DOM | null;
parent?: Fiber
child?: Fiber
sibling?: Fiber
alternate?: Fiber
effectTag?: 'UPDATE' | 'PLACEMENT' | 'DELETION'
hooks?: Hook[]
}
interface Hook {
state: any // todo
queue: Action[]
}
interface Action {
(state: any): any;
}
// ----------------------------
function createElement(type: ElementType, props: Props, ...children: Props['children']): VDom {
return {
type,
props: {
...props,
children: children.map((child) =>
typeof child === "object" ? child : createTextElement(child)
),
},
};
}
function createTextElement(text: string): VDom {
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: [],
},
} as VDom;
}
function createDom(fiber: Fiber): DOM {
const dom =
fiber.type == "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(fiber.type as string) as Element
updateDom(dom, {} as Props, fiber.props)
return dom
}
// ----------------------
// 入口
requestIdleCallback(workLoop)
let nextUnitOfWork: Fiber | undefined | null = null
let wipRoot: Fiber | null = null
let currentRoot: Fiber | null = null
let deletions: Fiber[] = []
function workLoop(deadline: Deadline) {
let shouldYield = false
while (nextUnitOfWork && !shouldYield) {
nextUnitOfWork = performUnitOfWork(
nextUnitOfWork
)
shouldYield = deadline.timeRemaining() < 1
}
if (!nextUnitOfWork && wipRoot) {
commitRoot()
}
requestIdleCallback(workLoop)
}
function performUnitOfWork(fiber: Fiber): Fiber | undefined {
const isFunctionComponent =
fiber.type instanceof Function
if (isFunctionComponent) {
updateFunctionComponent(fiber)
} else {
updateHostComponent(fiber)
}
if (fiber.child) {
return fiber.child
}
let nextFiber = fiber
while (nextFiber) {
if (nextFiber.sibling) {
return nextFiber.sibling
}
nextFiber = nextFiber.parent
}
}
// WIP= Work in Progress
let wipFiber: Fiber = null
let hookIndex: number = null
function updateFunctionComponent(fiber: Fiber) {
wipFiber = fiber
hookIndex = 0
wipFiber.hooks = []
const children = [(fiber.type as Function)(fiber.props)]
reconcileChildren(fiber, children)
}
function useState<T>(initial: T) {
const oldHook =
wipFiber.alternate &&
wipFiber.alternate.hooks &&
wipFiber.alternate.hooks[hookIndex]
const hook = {
state: oldHook ? oldHook.state : initial,
queue: [],
} as Hook;
const actions: Action[] = oldHook ? oldHook.queue : []
actions.forEach(action => {
hook.state = action(hook.state)
})
const setState = (action: Action) => {
hook.queue.push(action)
wipRoot = {
dom: currentRoot.dom,
props: currentRoot.props,
alternate: currentRoot,
}
nextUnitOfWork = wipRoot
deletions = []
}
wipFiber.hooks.push(hook)
hookIndex++
return [hook.state, setState]
}
function updateHostComponent(fiber: Fiber) {
if (!fiber.dom) {
fiber.dom = createDom(fiber)
}
reconcileChildren(fiber, fiber.props.children as VDom[])
}
function reconcileChildren(wipFiber: Fiber, elements: VDom[]) {
let index = 0
let oldFiber: Fiber =
wipFiber.alternate && wipFiber.alternate.child
let prevSibling: Fiber = null
while (
index < elements.length ||
oldFiber != null
) {
const element = elements[index]
let newFiber: Fiber = null
const sameType =
oldFiber &&
element &&
element.type == oldFiber.type
if (sameType) {
newFiber = {
type: oldFiber.type,
props: element.props,
dom: oldFiber.dom,
parent: wipFiber,
alternate: oldFiber,
effectTag: "UPDATE",
}
}
if (element && !sameType) {
newFiber = {
type: element.type,
props: element.props,
dom: null,
parent: wipFiber,
alternate: null,
effectTag: "PLACEMENT",
}
}
if (oldFiber && !sameType) {
oldFiber.effectTag = "DELETION"
deletions.push(oldFiber)
}
if (oldFiber) {
oldFiber = oldFiber.sibling
}
if (index === 0) {
wipFiber.child = newFiber
} else if (element) {
prevSibling.sibling = newFiber
}
prevSibling = newFiber
index++
}
}
function commitRoot() {
deletions.forEach(commitWork)
commitWork(wipRoot.child)
// 恢复
currentRoot = wipRoot
wipRoot = null
}
function commitWork(fiber: Fiber) {
if (!fiber) {
return
}
// const domParent = fiber.parent.dom
let domParentFiber = fiber.parent
while (!domParentFiber.dom) {
domParentFiber = domParentFiber.parent
}
const domParent = domParentFiber.dom
if (
fiber.effectTag === "PLACEMENT" &&
fiber.dom != null
) {
domParent.appendChild(fiber.dom)
}
else if (fiber.effectTag === "DELETION") {
commitDeletion(fiber, domParent)
}
else if (
fiber.effectTag === "UPDATE" &&
fiber.dom != null
) {
updateDom(
fiber.dom,
fiber.alternate.props,
fiber.props
)
}
commitWork(fiber.child)
commitWork(fiber.sibling)
}
function commitDeletion(fiber: Fiber, domParent: DOM) {
if (fiber.dom) {
domParent.removeChild(fiber.dom)
} else {
commitDeletion(fiber.child, domParent)
}
}
const isNew = (prev: Props, next: Props) => (key: string) =>
prev[key] !== next[key]
const isGone = (prev: Props, next: Props) => (key: string) => !(key in next)
const isEvent = (key: string) => key.startsWith("on")
const isProperty = (key: string) =>
key !== "children" && !isEvent(key)
function updateDom(dom: DOM, prevProps: Props, nextProps: Props) {
//Remove old or changed event listeners
Object.keys(prevProps)
.filter(isEvent)
.filter(
key =>
!(key in nextProps) ||
isNew(prevProps, nextProps)(key)
)
.forEach(name => {
const eventType = name
.toLowerCase()
.substring(2)
dom.removeEventListener(
eventType,
prevProps[name]
)
})
// Remove old properties
Object.keys(prevProps)
.filter(isProperty)
.filter(isGone(prevProps, nextProps))
.forEach(name => {
(dom as any)[name] = ""
})
// Set new or changed properties
Object.keys(nextProps)
.filter(isProperty)
.filter(isNew(prevProps, nextProps))
.forEach(name => {
(dom as any)[name] = nextProps[name]
})
// Add event listeners
Object.keys(nextProps)
.filter(isEvent)
.filter(isNew(prevProps, nextProps))
.forEach(name => {
const eventType = name
.toLowerCase()
.substring(2)
dom.addEventListener(
eventType,
nextProps[name]
)
})
}
function render(element: VDom, container: DOM) {
wipRoot = {
dom: container,
props: {
children: [element],
},
alternate: currentRoot
}
deletions = [];
nextUnitOfWork = wipRoot
}
export const Didact = {
createElement,
render,
useState
};
| 134a1c8189814b0f411d678bbfd20426e63465f3 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | tangciwei/react-didact | 4c5bef0b4db7f1ac44138afb9acdba89010c5e60 | 40371f4edad2e6773d4d8c7e95f0524427bcde2f |
refs/heads/master | <file_sep>//Write a program that finds in given array of integers a sequence of given sum S (if present). Example: {4, 3, 1, 4, 2, 5, 8}, S=11 {4, 2, 5}
using System;
class SequenceOfGivenSum
{
static void Main()
{
int s = int.Parse(Console.ReadLine());
string inputArrayOne = Console.ReadLine();
char[] delimiter = new char[] {',',' '};
string[] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[]realArray=new int[inputArrayTwo.Length];
for (int i = 0; i < inputArrayTwo.Length; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
}
int currentSum=0;
int sumOfAll = 0;
for (int i = 0; i < realArray.Length; i++)
{
sumOfAll += realArray[i];
if (i == realArray.Length - 1 && sumOfAll<s)
{
Console.WriteLine("There is no sequence of given sum!");
}
currentSum = 0;
for (int j = i; j < realArray.Length; j++)
{
currentSum += realArray[j];
if (currentSum == s)
{
for (int n = i; n <=j; n++)
{
if (n >= i + 1)
{
Console.Write(", ");
}
Console.Write(realArray[n]);
}
currentSum=0;
Console.WriteLine();
break;
}
if (currentSum > s)
{
currentSum = 0;
break;
}
}
}
}
}
<file_sep>//Write a program that concatenates two text files into another text file.
using System;
using System.IO;
using System.Text;
class ConcatenatesTwoTextFiles
{
static void Main()
{
StreamReader reader = new StreamReader(@"..\..\..\01.ReadTextAndPrintsOddLines\01.ReadTextAndPrintsOddLines.cs");
StreamReader reader2 = new StreamReader(@"..\..\02.ConcatenatesTwoTextFiles.cs");
StringBuilder firstText=new StringBuilder();
using(reader)
{
firstText.Append(reader.ReadToEnd());
}
StringBuilder secondText = new StringBuilder();
using(reader2)
{
secondText.Append(reader2.ReadToEnd());
}
string finalText = "finalText.txt";
StreamWriter writer = new StreamWriter(finalText);
using(writer)
{
writer.WriteLine(firstText);
writer.WriteLine();
writer.WriteLine(new string('-',70));
writer.WriteLine();
writer.WriteLine(secondText);
}
}
}<file_sep>//Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum.
using System;
class MaxSumOfKelements
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
string inputArrayOne = Console.ReadLine();
char [] delimiter = new char[] {' '};
string [] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[] realArray = new int[n];
for (int i = 0; i < n; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
}
Array.Sort(realArray);
for (int i = realArray.Length- 1; i >(realArray.Length-1)-k; i--)
{
if (i < realArray.Length - 1)
{
Console.Write(", ");
}
Console.Write(realArray[i]);
}
Console.WriteLine();
}
}
<file_sep>//You are given a sequence of positive integer values written into a string, separated by spaces. Write a function that reads these values from given string and calculates their sum. Example:
// string = "43 68 9 23 318" result = 461
using System;
using System.Text;
class SumOfStringSequenceOfIntValue
{
static void Main()
{
string input = Console.ReadLine();
input += " ";
int answer=0;
for (int i = 0; i < input.Length; i++)
{
StringBuilder currentNumber = new StringBuilder();
while (input[i] > 47 && input[i] < 58 && i <= input.Length-1)
{
currentNumber.Append(input[i]);
i++;
}
answer += int.Parse(currentNumber.ToString());
}
Console.WriteLine(answer);
}
}<file_sep>//Write a program that reads a rectangular matrix of size N x M and finds in it the square 3 x 3 that has maximal sum of its elements.
using System;
class MaxSumOfRectanMatrix
{
static void Main()
{
int m = int.Parse(Console.ReadLine());
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, m];
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
string inputArrayOne = Console.ReadLine();
string[] inputArrayTwo = inputArrayOne.Split(' ');
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[rows, col] = int.Parse(inputArrayTwo[col]);
}
}
int maxSum = int.MinValue;
int [,] realSmallMatrix = new int [3,3];
for (int rows = 0; rows <=matrix.GetLength(0)-3; rows++)
{
for (int col = 0; col <=matrix.GetLength(1)-3; col++)
{
int currentSum = 0;
int [,]currentSmallMatrix = new int [3,3];
int realRows = 0;
for (int smallRows = rows; smallRows < rows+3; smallRows++)
{
int realCol = 0;
for (int smallCol = col; smallCol < col+3; smallCol++)
{
currentSum += matrix[smallRows, smallCol];
currentSmallMatrix [realRows,realCol]= matrix[smallRows, smallCol];
realCol++;
}
realRows++;
}
if (currentSum > maxSum)
{
realSmallMatrix = (int[,])currentSmallMatrix.Clone();
maxSum = currentSum;
}
}
}
for (int rows = 0; rows < realSmallMatrix.GetLength(0); rows++)
{
for (int col = 0; col < realSmallMatrix.GetLength(1); col++)
{
Console.Write("{0,2}",realSmallMatrix[rows,col]);
}
Console.WriteLine();
}
}
}
<file_sep>//Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file. Example:
// Ivan George
// Peter Ivan
// Maria Maria
// George Peter
using System;
using System.IO;
class SortsListOfString
{
static void Main()
{
int nNames = int.Parse(Console.ReadLine());
string[] array=new string[nNames];
StreamWriter writer = new StreamWriter("inputFile.txt");
using(writer)
{
for (int i = 0; i < nNames; i++)
{
writer.WriteLine(Console.ReadLine());
}
}
StreamReader reader = new StreamReader("inputFile.txt");
using (reader)
{
for (int i = 0; i < nNames; i++)
{
array[i] = reader.ReadLine();
}
Array.Sort(array);
}
StreamWriter writer2 = new StreamWriter("outputFile.txt");
using (writer2)
{
for (int i = 0; i < nNames; i++)
{
writer2.WriteLine(array[i]);
}
}
}
}<file_sep>//Write a method that adds two positive integer numbers represented as arrays of digits (each array element arr[i] contains a digit; the last digit is kept in arr[0]). Each of the numbers that will be added could have up to 10 000 digits.
using System;
public class SumTwoBigIntegers
{
public static int[] SumOfArray(int[] firstArray, int[] secondArray)
{
Array.Reverse(firstArray);
Array.Reverse(secondArray);
int maxLength = Math.Max(firstArray.Length, secondArray.Length);
int[] realArray = new int[maxLength];
int[] finalArray = new int[maxLength + 1];
if (firstArray.Length > secondArray.Length)
{
Array.Copy(secondArray, realArray, secondArray.Length);
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(firstArray[i] + realArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
if (counter == 1)
{
finalArray[finalArray.Length - 1] = 1;
}
return finalArray;
}
else if (firstArray.Length < secondArray.Length)
{
Array.Copy(firstArray, realArray, firstArray.Length);
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(realArray[i] + secondArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
return finalArray;
}
else
{
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(firstArray[i] + secondArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
}
return finalArray;
}
public static int[] ToArray(string number)
{
int[] array = new int[number.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = number[i] - 48;
}
return array;
}
static void Main()
{
string firstNumber = Console.ReadLine();
string secondNumber = Console.ReadLine();
int[] firstArray, secondArray;
firstArray = ToArray(firstNumber);
secondArray = ToArray(secondNumber);
int[] finalArray = SumOfArray(firstArray, secondArray);
if (finalArray[finalArray.Length - 1] == 0)
{
for (int i = finalArray.Length - 2; i >= 0; i--)
{
Console.Write(finalArray[i]);
}
Console.WriteLine();
}
else
{
for (int i = finalArray.Length - 1; i >= 0; i--)
{
Console.Write(finalArray[i]);
}
Console.WriteLine();
}
}
}<file_sep>//We are given a string containing a list of forbidden words and a text containing some of these words. Write a program that replaces the forbidden words with asterisks.
using System;
using System.Text;
class ForbiddenWordsWithAsterisks
{
static void Main()
{
string text = Console.ReadLine();
string words = Console.ReadLine();
char[] split = { ',',' ' };
string[] forbiddenWords = words.Split(split,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < forbiddenWords.Length; i++)
{
StringBuilder asteriks = new StringBuilder();
for (int j = 1; j <=forbiddenWords[i].Length; j++)
{
asteriks.Append('*');
}
text=text.Replace(forbiddenWords[i],asteriks.ToString());
}
Console.WriteLine(text);
}
}<file_sep>//Write a program that extracts from given HTML file its title (if available), and its body text without the HTML tags.
using System;
using System.Text;
class ExtractHTMLTextWithoutTags
{
static void Main()
{
StringBuilder text=new StringBuilder();
string line = string.Empty;
do
{
line = Console.ReadLine();
text.Append(line);
line = line.ToLower();
} while (line != "</html>");
Console.WriteLine();
for (int i = 0; i < text.Length-1; i++)
{
if(text[i]=='>'&&text[i+1]!='<')
{
i++;
while(i<text.Length-1 && text[i]!='<')
{
Console.Write(text[i]);
i++;
}
Console.WriteLine();
}
}
}
}<file_sep>//Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the "selection sort" algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc.
using System;
class SelectionSortAlgorithm
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int [] array=new int [n];
int[] newArray = new int[n];
for (int i = 0; i < n; i++)
{
array[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
int minValue = int.MaxValue;
int maxValue = int.MinValue;
for (int j = i+1; j < n; j++)
{
minValue = Math.Min(array[i], array[j]);
maxValue = Math.Max(array[i], array[j]);
array[i] = minValue;
array[j] = maxValue;
}
}
Console.WriteLine(string.Join(" ",array));
}
}
<file_sep>//Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file.
using System;
using System.IO;
class InsertsLineNumbers
{
static void Main()
{
StreamReader reader = new StreamReader(@"..\..\03.InsertsLineNumbers.cs");
string finalText="finalText.txt";
StreamWriter writer = new StreamWriter(finalText);
using(writer)
{
string currentText=reader.ReadLine();
int line=0;
while(currentText!=null)
{
line++;
writer.WriteLine("{0}. {1}",line,currentText);
currentText = reader.ReadLine();
}
}
}
}<file_sep>//Write a program that compares two char arrays lexicographically (letter by letter).
using System;
class ComparesTwoCharArrays
{
static void Main()
{
string firstArray = Console.ReadLine();
string secondArray = Console.ReadLine();
int length = Math.Min(firstArray.Length,secondArray.Length);
for (int i = 0; i < length; i++)
{
if (firstArray[i] == secondArray[i])
{
continue;
}
if (firstArray[i] > secondArray[i])
{
Console.WriteLine("{0} is first lexicographically!",secondArray);
return;
}
if (firstArray[i] < secondArray[i])
{
Console.WriteLine("{0} is first lexicographically!",firstArray);
return;
}
}
if (firstArray.Length == secondArray.Length)
{
Console.WriteLine("No difference!");
}
if (firstArray.Length > secondArray.Length)
{
Console.WriteLine("{0} is first lexicographically!", secondArray);
}
if(firstArray.Length < secondArray.Length)
{
Console.WriteLine("{0} is first lexicographically!", firstArray);
}
}
}
<file_sep>//Write a program that reads a text file containing a square matrix of numbers and finds in the matrix an area of size 2 x 2 with a maximal sum of its elements. The first line in the input file contains the size of matrix N. Each of the next N lines contain N numbers separated by space. The output should be a single number in a separate text file. Example:
//4
//2 3 3 4
//0 2 3 4 17
//3 7 1 2
//4 3 3 2
using System;
using System.IO;
class MaxSumInMatrix
{
static void Main()
{
int nNumbers = int.Parse(Console.ReadLine());
int[,] finalArray = new int[2, 2];
int maxSum = int.MinValue;
StreamWriter writer = new StreamWriter("matrix.txt");
using(writer)
{
for (int i = 0; i < nNumbers; i++)
{
writer.WriteLine(Console.ReadLine());
}
}
StreamReader reader = new StreamReader("matrix.txt");
using(reader)
{
int [,] inputArray=new int[nNumbers,nNumbers];
for (int rows = 0; rows < inputArray.GetLength(0); rows++)
{
string currentRow = string.Empty;
currentRow = reader.ReadLine();
string[] stringArray;
stringArray = currentRow.Split(' ');
for (int cols = 0; cols < inputArray.GetLength(1); cols++)
{
inputArray[rows, cols] = int.Parse(stringArray[cols]);
}
}
for (int row = 0; row <nNumbers-1; row++)
{
for (int col = 0; col < nNumbers-1; col++)
{
int currentSum =0;
currentSum += inputArray[row, col] + inputArray[row, col+1] + inputArray[row+1, col] + inputArray[row+1, col+1];
if (currentSum > maxSum)
{
maxSum = currentSum;
finalArray[0, 0] = inputArray[row, col];
finalArray[0, 1] = inputArray[row, col + 1];
finalArray[1, 0] = inputArray[row+1, col];
finalArray[1, 1] = inputArray[row+1, col + 1];
}
}
}
Console.WriteLine(maxSum);
}
StreamWriter finalWriter=new StreamWriter("finalAnswer.txt");
using (finalWriter)
{
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 2; col++)
{
finalWriter.Write(finalArray[row,col]);
finalWriter.Write(" ");
}
finalWriter.WriteLine();
}
finalWriter.WriteLine(maxSum);
}
}
}<file_sep>//Write a program to test "PrintName" method.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace _01.SayHello_Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string firstTest = SayHello.PrintName("Peter");
Assert.AreEqual("Hello, Peter!", firstTest);
}
}
}
<file_sep>//Write a program that finds the most frequent number in an array. Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} 4 (5 times).
using System;
class TheMostFrequentNumber
{
static void Main()
{
string inputArrayOne = Console.ReadLine();
char[] delimiter = new char[] {',',' '};
string[] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[]realArray=new int[inputArrayTwo.Length];
for (int i = 0; i < inputArrayTwo.Length; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
}
int frequentNumber = 0;
int maxFrequent = 1;
int counter = 1;
for (int i = 0; i < realArray.Length; i++)
{
for (int j = i+1; j < realArray.Length; j++)
{
if (realArray[i] == realArray[j])
{
counter++;
}
}
if (maxFrequent < counter)
{
frequentNumber = i;
}
maxFrequent = Math.Max(maxFrequent, counter);
counter = 1;
}
Console.WriteLine("{0}({1} times)", realArray[frequentNumber], maxFrequent);
}
}
<file_sep>using System;
using System.Collections.Generic;
class JoroTheRabbit
{
static void Main()
{
char[] separator = { ' ', ',' };
string[] currentInput = Console.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries);
int maxCount = 0;
List<int> input = new List<int>();
foreach (var n in currentInput)
{
input.Add(int.Parse(n));
}
for (int i = 0; i < currentInput.Length; i++)
{
for (int step = 1; step < currentInput.Length; step++)
{
int counter = 1;
int currentElement = i;
int next = currentElement + step;
if (next >= input.Count)
{
next = next - input.Count;
}
while (input[currentElement] < input[next])
{
counter++;
currentElement = next;
next = currentElement + step;
if (next >= input.Count)
{
next = next - input.Count;
}
}
if (counter > maxCount)
{
maxCount = counter;
}
}
}
Console.WriteLine(maxCount);
}
}<file_sep>//Write methods that calculate the surface of a triangle by given:
//Side and an altitude to it; Three sides; Two sides and an angle between them. Use System.Math.
using System;
class CalculateTheSurfaceOfATriangleProgram
{
static double CalculateSurface(double side,double altitude)
{
double result = (side * altitude) / 2d;
return result;
}
static double CalculateSurface(double sideA, double sideB,double sideC)
{
double perimiter = (sideA + sideB + sideC)/2;
double result = Math.Sqrt(perimiter)*((perimiter-sideA)*(perimiter-sideB)*(perimiter-sideC));
return result;
}
static double CalculateSurface(double sideA, double sideB,float angle)
{
double result = (sideA * sideB*Math.Sin(angle)) / 2d;
return result;
}
static void Main()
{
Console.Write("Please, input your choise -a , b or c:");
string input = Console.ReadLine();
switch (input)
{
case"a":
Console.Write("Enter a side:");
double side = double.Parse(Console.ReadLine());
Console.Write("Enter an altitude:");
double altitude = double.Parse(Console.ReadLine());
Console.WriteLine("{0:F2}",CalculateSurface(side,altitude));
return;
case "b":
Console.Write("Enter a side A:");
double sideA = double.Parse(Console.ReadLine());
Console.Write("Enter a side B:");
double sideB = double.Parse(Console.ReadLine());
Console.Write("Enter a side C:");
double sideC = double.Parse(Console.ReadLine());
Console.WriteLine("{0:F2}",CalculateSurface(sideA,sideB,sideC));
return;
case "c":
Console.Write("Enter a first side:");
double firstSide = double.Parse(Console.ReadLine());
Console.Write("Enter a second side:");
double secondSide = double.Parse(Console.ReadLine());
Console.Write("Enter an angle:");
float angle = float.Parse(Console.ReadLine());
Console.WriteLine("{0:F2}",CalculateSurface(firstSide,secondSide,angle));
return;
}
}
}<file_sep>//Write a program that extracts from a given text all sentences containing given word.
using System;
class ExtractSentencesFromTextContainingWord
{
static void Main()
{
string text = Console.ReadLine();
string word=" "+ Console.ReadLine() + " ";
int position = 0;
string sentence = string.Empty;
for (int i = 0; i < text.Length; i=position)
{
position=text.IndexOf('.',i)+1;
sentence = text.Substring(i, position - i);
if(sentence.IndexOf(word)>0)
{
Console.WriteLine(sentence);
}
}
}
}<file_sep>//Write a test program to check if the method "CountNum" is working correctly.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace _04.CountNumInArray_Test
{
[TestClass]
public class UnitTest1
{
int minValue = int.MinValue;
int maxValue = int.MaxValue;
[TestMethod]
public void TestMethod1()
{
int [] testArray = { 1, 3, 1, 5, 1, 3, 2 };
int seekingNumber = 1;
Assert.AreEqual(3, CountNumInArray.CountNum(testArray,seekingNumber));
}
[TestMethod]
public void TestMethod2()
{
int[] testArray = { 1, 3, 1, 5, 1, 3, 2 };
int seekingNumber = 3;
Assert.AreEqual(2, CountNumInArray.CountNum(testArray, seekingNumber));
}
[TestMethod]
public void TestMethod3()
{
int[] testArray = { minValue, 2, 1, 5, minValue, 3, minValue };
int seekingNumber = minValue;
Assert.AreEqual(3, CountNumInArray.CountNum(testArray, seekingNumber));
}
[TestMethod]
public void TestMethod4()
{
int[] testArray = { 1, maxValue, 1, 5, minValue, 3, maxValue };
int seekingNumber = maxValue;
Assert.AreEqual(2, CountNumInArray.CountNum(testArray, seekingNumber));
}
}
}<file_sep>//Write a method that calculates the number of workdays between today and given date, passed as parameter. Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.
using System;
class TheNumberOfWorkdays
{
static int i;
static int TheNumbersOfDays(int a,int b,int c,int difference)
{
DateTime today = new DateTime(a,b,c);
int answer = difference;
DateTime[] holidays = new DateTime[10];
for ( i = 1; i <=difference; i++)
{
holidays[0] = new DateTime(today.Year, 3, 3);
holidays[1] = new DateTime(today.Year, 5, 1);
holidays[2] = new DateTime(today.Year, 5, 6);
holidays[3] = new DateTime(today.Year, 5, 24);
holidays[4] = new DateTime(today.Year, 9, 6);
holidays[5] = new DateTime(today.Year, 9, 22);
holidays[6] = new DateTime(today.Year, 11, 1);
holidays[7] = new DateTime(today.Year, 12, 24);
holidays[8] = new DateTime(today.Year, 12, 26);
holidays[9] = new DateTime(today.Year, 12, 25);
foreach (var n in holidays)
{
if (today.Date == n.Date || today.DayOfWeek == DayOfWeek.Saturday || today.DayOfWeek == DayOfWeek.Sunday)
{
answer--;
break;
}
}
today = today.AddDays(1);
}
return answer;
}
static void Main()
{
int beginingYear = int.Parse(Console.ReadLine());
int beginingMonth = int.Parse(Console.ReadLine());
int beginingDay = int.Parse(Console.ReadLine());
DateTime today = new DateTime(beginingYear, beginingMonth, beginingDay);
int endYear = int.Parse(Console.ReadLine());
int endMonth = int.Parse(Console.ReadLine());
int endDay=int.Parse(Console.ReadLine());
DateTime givenDay = new DateTime(endYear, endMonth, endDay);
int diference = 0;
diference+=-(int)(today-givenDay).TotalDays;
Console.WriteLine(TheNumbersOfDays(beginingYear,beginingMonth,beginingDay,diference));
}
}<file_sep>//Write a program that reads a list of words, separated by spaces and prints the list in an alphabetical order.
using System;
class ListInAnAlphabeticalOrder
{
static void Main()
{
string listOfWords = Console.ReadLine();
char[] separator = { ' ', ',' };
string[] arrayOfWords = listOfWords.Split(separator,StringSplitOptions.RemoveEmptyEntries);
Array.Sort(arrayOfWords);
Console.WriteLine(string.Join("\n",arrayOfWords));
}
}<file_sep>using System;
class TwoGirlsOnePath
{
static void Main()
{
string[] pathCells = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
long [] realPath=new long[pathCells.Length];
for (int i = 0; i < pathCells.Length; i++)
{
realPath[i] = long.Parse(pathCells[i]);
}
long dollyPath = realPath.Length-1;
Console.WriteLine("Dolly");
Console.WriteLine("{0} {1}",0,0);
}
}<file_sep>//Write a method that counts how many times given number appears in given array.
using System;
public class CountNumInArray
{
public static int CountNum(int [] array,int number)
{
int counter = 0;
foreach (var n in array)
{
if (n == number)
{
counter++;
}
}
return counter;
}
static void Main()
{
Console.Write("How many number you want to input:");
int numberOfIntegers = int.Parse(Console.ReadLine());
int [] integerArray=new int [numberOfIntegers];
for (int i = 0; i < numberOfIntegers; i++)
{
Console.Write("Input number {0}:",i+1);
integerArray[i] = int.Parse(Console.ReadLine());
}
Console.Write("Number to search for:");
int seekingNumber = int.Parse(Console.ReadLine());
int result = CountNum(integerArray, seekingNumber);
Console.WriteLine("Found {0} times!",result);
}
}
<file_sep>//Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.
using System;
class FindKElementWithBinSearch
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int k = int.Parse(Console.ReadLine());
string inputArray = Console.ReadLine();
string[] splitArray = inputArray.Split(' ');
int [] realArray=new int[n];
for (int i = 0; i < n; i++)
{
realArray[i] = int.Parse(splitArray[i]);
}
Array.Sort(realArray);
int seekingNumber = Array.BinarySearch(realArray,k);
if (realArray[0] > k)
{
Console.WriteLine("There isn't such a number in the array.");
}
else
{
if (seekingNumber < 0)
{
seekingNumber = -seekingNumber - 2;
Console.WriteLine(realArray[seekingNumber]);
}
else
{
Console.WriteLine(realArray[seekingNumber]);
}
}
}
}
<file_sep>//Write a program that reads a string, reverses it and prints the result at the console.
//Example: "sample" "elpmas".
using System;
class ReverseString
{
static void Main()
{
string input = Console.ReadLine();
char []answer=input.ToCharArray();
Array.Reverse(answer);
Console.WriteLine(answer);
}
}<file_sep>//Write a program that encodes and decodes a string using given encryption key (cipher). The key consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) operation over the first letter of the string with the first of the key, the second – with the second, etc. When the last key character is reached, the next is the first.
using System;
using System.Text;
class XORCharactersEncode
{
static void Main()
{
string cipher = Console.ReadLine();
string text = Console.ReadLine();
StringBuilder answer = new StringBuilder();
//ab ab a
//Na ko v
for (int i = 0; i < text.Length; i++)
{
answer.AppendFormat(@"\u{0:x4}",text[i]^cipher[i%cipher.Length]);
}
Console.WriteLine(answer);
}
}<file_sep>//Write a program that finds the maximal sequence of equal elements in an array.
//Example: {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} -> {2, 2, 2}.
using System;
using System.Collections.Generic;
class MaximalSequenceOfEqualElements
{
static void Main()
{
string inputArrayOne = Console.ReadLine();
char[] delimiter = new char[] {',',' '};
string[] inputOne =inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[] arr = new int[inputOne.Length];
for (int i = 0; i < inputOne.Length; i++)
{
arr[i] = int.Parse(inputOne[i]);
}
int counter = 1;
int maxValue = 0;
int sequenceDigit = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] == arr[i + 1])
{
counter++;
if (counter > maxValue)
{
sequenceDigit = arr[i];
}
maxValue = Math.Max(maxValue, counter);
}
else
{
counter = 1;
}
}
for (int i = 0; i < maxValue; i++)
{
if (i >= 1)
{
Console.Write(", ");
}
Console.Write(sequenceDigit);
}
Console.WriteLine();
}
}
<file_sep>//Write a program that reads a date and time given in the format: day.month.year hour:minute:second and prints the date and time after 6 hours and 30 minutes (in the same format) along with the day of week in Bulgarian.
using System;
using System.Globalization;
class DateAndTimeAfter6HoursAnd30Minutes
{
static void Main()
{
string format = "d.M.yyyy H:mm:ss";
DateTime now = DateTime.ParseExact(Console.ReadLine(), format, CultureInfo.InvariantCulture);
DateTime after=now.AddHours(6.5);
Console.WriteLine("{0:d.M.yyyy HH:mm:ss}",after);
}
}<file_sep>/*
* Write a program that reverses the words in given sentence.
Example: "C# is not C++ and PHP is not Delphi" "Delphi not is PHP and C++ not is C#".
*/
using System;
class ReversesTheWordsInSentence
{
static void Main()
{
string sentence = Console.ReadLine();
char[] separator = { ' ', '\"' };
string[] array = sentence.Split(separator,StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(array);
Console.WriteLine("\"{0}\"",string.Join(" ",array));
}
}<file_sep>//Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} {2, 3, 4}.
using System;
class MaxIncreasingSequence
{
static void Main()
{
string inputArrayOne = Console.ReadLine();
char[] delimiter = new char [] {',',' '};
string [] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[] realArray = new int[inputArrayTwo.Length];
for (int i = 0; i < inputArrayTwo.Length; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
}
int counter = 0;
int sequenceDigit = 0;
int maxValue = 0;
for (int i = 0; i < realArray.Length-1; i++)
{
if (realArray[i] < realArray[i + 1])
{
counter++;
if (maxValue < counter)
{
sequenceDigit = i;
sequenceDigit++;
}
maxValue = Math.Max(maxValue, counter);
}
else
{
counter = 0;
}
}
int[] finalArray = new int[maxValue+1];
int j = 0;
for (int i = sequenceDigit-maxValue; i <=sequenceDigit; i++,j++)
{
finalArray[j] = realArray[i];
}
if (maxValue!=0)
{
Console.WriteLine(string.Join(", ", finalArray));
}
else
{
Console.WriteLine("The array doesn't have an increasing sequence!");
}
}
}
<file_sep>//Write a method ReadNumber(int start, int end) that enters an integer number in given range [start…end]. If an invalid number or non-number text is entered, the method should throw an exception. Using this method write a program that enters 10 numbers:
// a1, a2, … a10, such that 1 < a1 < … < a10 < 100
using System;
class ReadNumberFromStartToEnd
{
static int ReadNumber(int a,int b)
{
int numbers=0;
try
{
numbers= int.Parse(Console.ReadLine());
if((numbers<a) || (numbers>b))
{
throw new ArgumentOutOfRangeException();
}
}
catch(ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
catch(ArgumentNullException ex)
{
Console.WriteLine(ex.Message);
}
catch(OverflowException ex)
{
Console.WriteLine(ex.Message);
}
catch(FormatException ex )
{
Console.WriteLine(ex.Message);
}
catch(OutOfMemoryException ex)
{
Console.WriteLine(ex.Message);
}
return numbers;
}
static void Main()
{
int start = 1;
int end = 100;
int previousNumber=ReadNumber(start, end);
int currentNumber;
for (int i = 0; i < 9; i++)
{
try
{
currentNumber = ReadNumber(start, end);
if (previousNumber >= currentNumber)
{
throw new ArgumentOutOfRangeException();
}
previousNumber = currentNumber;
}
catch(ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}<file_sep>using System;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class RelevanceIndex
{
static void Main()
{
StringBuilder searchWord = new StringBuilder(Console.ReadLine().ToLower());
for (int i = 0; i < searchWord.Length; i++)
{
if (searchWord[i] == ' ')
{
searchWord.Remove(i, 1);
}
}
int l = int.Parse(Console.ReadLine());
string[] allLines = new string[l];
for (int i = 0; i < l; i++)
{
var sb = new StringBuilder();
string[] currentRow = Console.ReadLine().Split(new char[] { ',', '.', '(', ')', ';', '-', '!', '?', ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < currentRow.Length; j++)
{
if (currentRow[j].ToLower() == searchWord.ToString())
{
sb.Append(currentRow[j].ToUpper());
}
else
{
sb.Append(currentRow[j]);
}
sb.Append(" ");
}
allLines[i] = sb.ToString();
}
int[] sortArray = new int[l];
string pattern = searchWord.ToString();
pattern = pattern.ToUpper();
for (int i = 0; i < allLines.Length; i++)
{
sortArray[i] = Regex.Matches(allLines[i], pattern).Count;
}
Array.Sort(sortArray, allLines);
Array.Reverse(allLines);
Console.WriteLine(string.Join("\n", allLines));
}
}<file_sep>//Write a method that returns the index of the first element in array that is bigger than its neighbors, or -1, if there’s no such element.
//Use the method from the previous exercise.
using System;
class FirstElementInArrayBiggerThenNeiboursProgram
{
static int FirstBiggerElement(int[]array)
{
for (int i = 1; i < array.Length-1; i++)
{
if(array[i]>array[i-1] && array[i]>array[i+1])
{
return i;
}
}
return -1;
}
static void Main()
{
Console.Write("How many numbers you want to input:");
int numberOfIntegers = int.Parse(Console.ReadLine());
int[] integerArray = new int[numberOfIntegers];
for (int i = 0; i < integerArray.Length; i++)
{
Console.Write("Input {0} Numbers:", i + 1);
integerArray[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine(FirstBiggerElement(integerArray));
}
}
<file_sep>//Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".
using System;
class PalindromesInTextProgram
{
static void Main()
{
string text = Console.ReadLine();
char[] separator = { ' ',',','.','!','?',':',';'};
string[] allWords = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < allWords.Length; i++)
{
int counter = 0;
char[] word=allWords[i].ToLower().ToCharArray();
for (int j = 0; j < word.Length; j++)
{
if(word[j]==word[word.Length-1-j])
{
counter++;
}
}
if(counter==(allWords[i].Length)&&counter!=1)
{
Console.WriteLine(allWords[i]);
}
}
}
}<file_sep>using System;
class GreedyDwarf
{
static void Main()
{
char[] separator = { ',', ' ' };
string[] realValley = Console.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries);
int m = int.Parse(Console.ReadLine());
int maxSum = int.MinValue;
for (int i = 0; i < m; i++)
{
int valleyIndex = 0;
string[] valley = new string[realValley.Length];
Array.Copy(realValley, valley, realValley.Length);
int currentSum = int.Parse(valley[0]);
int patternCounter = 0;
string[] currentPattern = (Console.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries));
do
{
valleyIndex = int.Parse(currentPattern[patternCounter % currentPattern.Length]) + valleyIndex;
if (valleyIndex > 0 && valleyIndex < valley.Length && valley[valleyIndex] != null)
{
currentSum += int.Parse(valley[valleyIndex]);
valley[valleyIndex] = null;
}
else
{
if (maxSum < currentSum)
{
maxSum = currentSum;
}
break;
}
patternCounter++;
} while (valleyIndex > 0 && valleyIndex < valley.Length);
}
Console.WriteLine(maxSum);
}
}<file_sep>//Write a program that reads a number and prints it as a decimal number, hexadecimal number, percentage and in scientific notation. Format the output aligned right in 15 symbols.
using System;
class FormatOutputNumber
{
static void Main()
{
double number = double.Parse(Console.ReadLine());
Console.Write("{0,15:D}\n" +
"{0,15:X}\n" +
"{1,15:P3}\n" +
"{1,15:E}\n",
(int)number,number);
}
}<file_sep>//Write a program that reads two dates in the format: day.month.year and calculates the number of days between them.
using System;
using System.Globalization;
class NumbersOfDaysBetweenTwoDates
{
static void Main()
{
string format = "d.MM.yyyy";
DateTime firstDate = DateTime.ParseExact(Console.ReadLine(), format, CultureInfo.InvariantCulture);
DateTime secondDate = DateTime.ParseExact(Console.ReadLine(), format, CultureInfo.InvariantCulture);
Console.WriteLine(Math.Abs((secondDate-firstDate).TotalDays));
}
}<file_sep>using System;
using System.Text;
class StrangeLandNumbers
{
static void Main()
{
string[] array = {"f", "bIN", "oBJEC", "mNTRAVL", "lPVKNQ", "pNWE", "hT"};
string input = Console.ReadLine();
StringBuilder currentWord = new StringBuilder();
ulong answer = 0;
for (int i = 0; i < input.Length; i++)
{
currentWord.Append(input[i]);
for (int j = 0; j < array.Length; j++)
{
if (currentWord.ToString() == array[j])
{
answer *= 7;
answer += (ulong)j;
currentWord = new StringBuilder();
break;
}
}
}
Console.WriteLine(answer);
}
}<file_sep>//You are given a text. Write a program that changes the text in all regions surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested.
//We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.
using System;
class ChangeWordsToUppercase
{
static void Main()
{
string input = Console.ReadLine();
int startPosition = 0;
int endPostion = 0;
string upCase = string.Empty;
while (startPosition < input.LastIndexOf("<upcase>"))
{
startPosition = input.IndexOf("<upcase>");
endPostion = input.IndexOf("</upcase>")+9;
upCase = input.Substring(startPosition+8, endPostion-9-(startPosition+8)).ToUpper();
input = input.Replace(input.Substring(startPosition,endPostion-startPosition), upCase);
startPosition ++;
}
Console.WriteLine(input);
}
}<file_sep>using System;
using System.Text;
using System.Collections.Generic;
class DecodeAndDecrypt
{
static void Main()
{
StringBuilder input = new StringBuilder(Console.ReadLine());
StringBuilder cypherLength1 = new StringBuilder();
int start = input.Length - 1;
while (input[start] >= '0' && input[start] <= '9')
{
cypherLength1.Insert(0, (input[start]));
input.Remove(start, 1);
start--;
}
int cypherLength = int.Parse(cypherLength1.ToString());
StringBuilder encryptMessage = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (input[i] >= '0' && input[i] <= '9')
{
StringBuilder currentPosition = new StringBuilder();
while (input[i] >= '0' && input[i] <= '9')
{
currentPosition.Append(input[i]);
i++;
}
encryptMessage.Append(input[i], int.Parse(currentPosition.ToString()));
}
else
{
encryptMessage.Append(input[i]);
}
}
string cypher = encryptMessage.ToString().Substring(encryptMessage.Length - cypherLength);
encryptMessage.Remove(encryptMessage.Length - cypherLength, cypherLength);
List<char> answer = new List<char>(encryptMessage.ToString());
for (int i = 0; i < Math.Max(cypher.Length, encryptMessage.Length); i++)
{
answer[i % answer.Count] = (char)((((cypher[i % cypherLength] - 'A') ^ (answer[i % answer.Count] - 'A')) + 'A'));
}
Console.WriteLine(string.Join("", answer));
}
}<file_sep>//Write a program to convert hexadecimal numbers to their decimal representation.
using System;
class HexadecimalToDecimal
{
static void Main()
{
string input = Console.ReadLine();
int result=0;
for (int i = input.Length - 1; i >= 0; i--)
{
if((input[i]-48)<10)
{
result += (input[i]-48) * (int)Math.Pow(16, input.Length - 1 - i);
}
else
{
switch (input[i])
{
case'A':
result += 10 * (int)Math.Pow(16, input.Length - 1 - i);
break;
case 'B':
result += 11 * (int)Math.Pow(16, input.Length - 1 - i);
break;
case 'C':
result += 12 * (int)Math.Pow(16, input.Length - 1 - i);
break;
case 'D':
result += 13 * (int)Math.Pow(16, input.Length - 1 - i);
break;
case 'E':
result += 14 * (int)Math.Pow(16, input.Length - 1 - i);
break;
case 'F':
result += 15 * (int)Math.Pow(16, input.Length - 1 - i);
break;
}
}
}
Console.WriteLine(result);
}
}<file_sep>//Write a program that fills and prints a matrix of size (n, n) as shown below: (examples for n = 4).
using System;
class FillsAndPrintsAMatrix
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
PrintMatrix(MatrixA(n));
PrintMatrix(MatrixB(n));
PrintMatrix(MatrixC(n));
PrintMatrix(MatrixD(n));
}
static int[,]MatrixA(int n)
{
int[,] matrix = new int[n, n];
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
int counter = rows;
counter++;
for (int col = 0; col < matrix.GetLength(1); col++, counter += n)
{
matrix[rows, col] = counter;
}
}
return matrix;
}
static int[,]MatrixB(int n)
{
int[,] matrix = new int[n, n];
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
int counter = rows;
int counter2 = 0;
counter++;
for (int col = 0; col < matrix.GetLength(1); col++, counter += n)
{
if (col % 2 == 0)
{
matrix[rows, col] = counter;
}
else
{
counter2 = n * (col + 1);
counter2 -= rows;
matrix[rows, col] = counter2;
}
}
}
return matrix;
}
static int[,]MatrixC(int n)
{
int[,] matrix = new int[n, n];
int counter = 1;
for (int rows = matrix.GetLength(0) - 1; rows >= 0; rows--)
{
for (int col = 0; col < n - rows; col++)
{
matrix[(rows + col), col] = counter;
counter++;
}
}
for (int col = 1; col < matrix.GetLength(1); col++)
{
for (int rows = 0; rows < n - col; rows++)
{
matrix[rows, (rows + col)] = counter;
counter++;
}
}
return matrix;
}
static int[,] MatrixD(int dim)
{
int[,] matrix = new int[dim, dim];
int numConcentricSquares = (int)Math.Ceiling((dim) / 2.0);
int j;
int sideLen = dim;
int currNum = 0;
for (int i = 0; i < numConcentricSquares; i++)
{
// do left side
for (j = 0; j < sideLen; j++)
{
matrix[i + j, i] = ++currNum;
}
// do bottom side
for (j = 1; j < sideLen - 1; j++)
{
matrix[dim - 1 - i, i + j] = ++currNum;
}
// do right side
for (j = sideLen - 1; j > 0; j--)
{
matrix[i + j, dim - 1 - i] = ++currNum;
}
// do top side
for (j = sideLen - 1; j > 0; j--)
{
matrix[i, i + j] = ++currNum;
}
sideLen -= 2;
}
return matrix;
}
static void PrintMatrix(int [,] matrix)
{
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write("{0,4}",matrix[rows,col]);
}
Console.WriteLine();
}
Console.WriteLine();
}
} <file_sep>//Write a program that finds the index of given element in a sorted array of integers by using the binary search algorithm (find it in Wikipedia).
using System;
class BinarySearchAlgorithm
{
static void Main()
{
string inputArrayOne = Console.ReadLine();
int findingNumber = int.Parse(Console.ReadLine());
char[] delimiter = new char[] {',',' '};
string[] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int []realArray=new int[inputArrayTwo.Length];
for (int i = 0; i < inputArrayTwo.Length; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
}
Array.Sort(realArray);
int left = 0;
int right = realArray.Length-1;
int middle;
while (left<=right)
{
middle = (left + right) / 2;
if (realArray[middle] == findingNumber)
{
Console.WriteLine(middle);
return;
}
if (realArray[middle]>findingNumber)
{
right = middle - 1;
}
if (realArray[middle] < findingNumber)
{
left=middle+1;
}
}
Console.WriteLine("Not Found!");
}
}
<file_sep>//Write a program that removes from a text file all words listed in given another text file. Handle all possible exceptions in your methods.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class RemoveGivenWordsFromText
{
static void Main()
{
try
{
StreamReader reader = new StreamReader("words.txt");
List<string> list = new List<string>();
using (reader)
{
string currentRow = reader.ReadLine();
while (currentRow != null)
{
list.Add(" " + currentRow + " ");
currentRow = reader.ReadLine();
}
}
StreamReader reader2 = new StreamReader("text.txt");
string text = string.Empty;
using (reader2)
{
text = " " + reader2.ReadToEnd();
}
for (int i = 0; i < list.Count; i++)
{
text = Regex.Replace(text, list[i], " ");
}
StreamWriter writer = new StreamWriter("answer.txt");
using (writer)
{
writer.Write(text);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
catch (FileLoadException ex)
{
Console.WriteLine(ex.Message);
}
catch (FieldAccessException ex)
{
Console.WriteLine(ex.Message);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
catch (OutOfMemoryException ex)
{
Console.WriteLine(ex.Message);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
}<file_sep>//Write a program that parses an URL address given in the format.
using System;
class ParsesAnURLAddressIntTheFormat
{
static void Main()
{
string url = Console.ReadLine();
int startPosition = 0;
int endPosition = 0;
endPosition = url.IndexOf(@"://", startPosition);
string protocol = url.Substring(startPosition,endPosition-startPosition);
startPosition = endPosition + 3;
endPosition = url.IndexOf(@"/",startPosition);
string server = url.Substring(startPosition, endPosition - startPosition);
string resource = url.Substring(endPosition);
Console.WriteLine("\"[protocol] = \"{0}\"",protocol);
Console.WriteLine("\"[protocol] = \"{0}\"",server);
Console.WriteLine("\"[protocol] = \"{0}\"",resource);
}
}<file_sep>using System;
using System.Text;
using System.Collections.Generic;
using System.Numerics;
class BunnyFactory
{
static void Main()
{
List<int> allCages = new List<int>();
while (true)
{
var currentCage = new StringBuilder(Console.ReadLine());
if (currentCage.ToString() != "END")
{
allCages.Add(int.Parse(currentCage.ToString()));
}
else
{
break;
}
}
int ithCyckle = 1;
while (true)
{
int sumOfIcages = 0;
if (ithCyckle > allCages.Count)
{
Console.WriteLine(string.Join(" ", allCages));
break;
}
for (int i = 0; i < ithCyckle; i++)
{
sumOfIcages += allCages[i];
}
if (sumOfIcages <= allCages.Count - ithCyckle)
{
BigInteger currentSum = 0;
BigInteger curremtProduct = 1;
for (int j = ithCyckle; j < ithCyckle + sumOfIcages; j++)
{
currentSum += allCages[j];
curremtProduct *= allCages[j];
}
StringBuilder newCages = new StringBuilder();
newCages.Append(currentSum);
newCages.Append(curremtProduct);
for (int i = ithCyckle + sumOfIcages; i < allCages.Count; i++)
{
newCages.Append(allCages[i]);
}
allCages = new List<int>();
for (int i = 0; i < newCages.Length; i++)
{
if (newCages[i] != '0' && newCages[i] != '1')
{
allCages.Add(newCages[i] - '0');
}
}
}
else if (sumOfIcages > allCages.Count - ithCyckle)
{
Console.WriteLine(string.Join(" ", allCages));
break;
}
ithCyckle++;
}
}
}<file_sep>//Write a method that reverses the digits of given decimal number. Example: 256 652
using System;
class ReverseNumber
{
static string ReverseDecimalNumber(int number)
{
string realNumber = string.Empty;
while (number>0)
{
realNumber += number%10;
number /= 10;
}
return realNumber;
}
static void Main()
{
int inputNumber = int.Parse(Console.ReadLine());
if(inputNumber<0)
{
inputNumber = -inputNumber;
Console.WriteLine("-{0}",int.Parse(ReverseDecimalNumber(inputNumber)));
}
else if(inputNumber>0)
{
Console.WriteLine(int.Parse(ReverseDecimalNumber(inputNumber)));
}
else
{
Console.WriteLine(0);
}
}
}<file_sep>using System;
using System.Text;
class KaspichanNumbers
{
static string KaspichanNumber(ulong number)
{
if (number < 26)
{
return ((char)(number % 26 + 'A')).ToString();
}
else
{
StringBuilder result = new StringBuilder();
result.Append((char)(number / 26 + 96));
result.Append((char)(number % 26 + 'A'));
return result.ToString();
}
}
static void Main()
{
ulong input = ulong.Parse(Console.ReadLine());
StringBuilder answer = new StringBuilder();
do
{
ulong currentNumber = input % 256;
answer.Insert(0, KaspichanNumber(currentNumber));
input = input / 256;
} while (input != 0);
Console.WriteLine(answer);
}
}<file_sep>using System;
using System.Collections.Generic;
class Zerg
{
static void Main()
{
var alphabet = new List<string>(){ "Rawr", "Rrrr", "Hsst", "Ssst", "Grrr", "Rarr", "Mrrr", "Psst", "Uaah", "Uaha", "Zzzz", "Bauu", "Djav", "Myau", "Gruh" };
var input = Console.ReadLine();
long answer=0;
for (int i = 0; i < input.Length; i+=4)
{
var word = input.Substring(i, 4);
var decimalRepresentation = alphabet.IndexOf(word);
answer *= 15;
answer += decimalRepresentation;
}
Console.WriteLine(answer);
}
}<file_sep>//Write a program that creates an array containing all letters from the alphabet (A-Z). Read a word from the console and print the index of each of its letters in the array.
using System;
class ArrayWithAlphabetLetters
{
static void Main()
{
string inputWord = Console.ReadLine();
char [] alphabetLetters=new char[26];
for (int i = 0; i < 26; i++)
{
alphabetLetters[i] = (char)(i+65);
}
for (int i = 0; i < inputWord.Length; i++)
{
for (int j = 0; j < 26; j++)
{
if (inputWord[i] == alphabetLetters[j])
{
Console.Write("{0} ",j);
break;
}
}
}
Console.WriteLine();
}
}
<file_sep>//Write a program to convert decimal numbers to their hexadecimal representation.
using System;
class DecimalToHexadecimal
{
static void Main()
{
uint input = uint.Parse(Console.ReadLine());
string result = string.Empty;
do
{
if (input % 16 < 10)
{
result += input % 16;
}
else
{
switch (input % 16)
{
case 10:
result += "A";
break;
case 11:
result += "B";
break;
case 12:
result += "C";
break;
case 13:
result += "D";
break;
case 14:
result += "E";
break;
case 15:
result += "F";
break;
}
}
input /= 16;
} while (input > 0);
for (int i = result.Length - 1; i >= 0; i--)
{
Console.Write(result[i]);
}
Console.WriteLine();
}
}<file_sep>//Write a program that enters file name along with its full file path (e.g. C:\WINDOWS\win.ini), reads its contents and prints it on the console. Find in MSDN how to use System.IO.File.ReadAllText(…). Be sure to catch all possible exceptions and print user-friendly error messages.
using System;
using System.IO;
using System.Security;
class EnterFilePathInConsoleAndReadProgram
{
static string ReadAllText(string path)
{
string answer = File.ReadAllText(path);
return answer;
}
static void Main()
{
string filePath = Console.ReadLine();
string exceptionMessage = string.Empty;
try
{
Console.WriteLine(ReadAllText(filePath));
}
catch (ArgumentNullException ex)
{
exceptionMessage=ex.Message;
}
catch (ArgumentException ex)
{
exceptionMessage = ex.Message;
}
catch (PathTooLongException ex)
{
exceptionMessage = ex.Message;
}
catch (DirectoryNotFoundException ex)
{
exceptionMessage = ex.Message;
}
catch (FileNotFoundException ex)
{
exceptionMessage = ex.Message;
}
catch (IOException ex)
{
exceptionMessage = ex.Message;
}
catch (UnauthorizedAccessException ex)
{
exceptionMessage = ex.Message;
}
catch (NotSupportedException ex)
{
exceptionMessage = ex.Message;
}
catch (SecurityException ex)
{
exceptionMessage = ex.Message;
}
catch (Exception ex)
{
exceptionMessage = ex.Message;
}
finally
{
if(exceptionMessage!=null)
{
Console.WriteLine(exceptionMessage);
}
}
}
}<file_sep>//Write a method GetMax() with two parameters that returns the bigger of two integers. Write a program that reads 3 integers from the console and prints the biggest of them using the method GetMax().
using System;
class GetMaxValue
{
private static int GetMax(int firstNumber, int secondNumber)
{
if (firstNumber > secondNumber)
{
return firstNumber;
}
return secondNumber;
}
static void Main()
{
Console.Write("Enter first number:");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter second number:");
int b = int.Parse(Console.ReadLine());
Console.Write("Enter third number:");
int c = int.Parse(Console.ReadLine());
Console.WriteLine(GetMax(GetMax(a,b),c));
}
}
<file_sep>//Write a program to check if in a given expression the brackets are put correctly.
//Example of correct expression: ((a+b)/5-d).
//Example of incorrect expression: )(a+b)).
using System;
class AreTheBracketsPutCorrectly
{
static void Main()
{
string input= Console.ReadLine();
int counter = 0;
bool isCorrect = true;
for (int i = 0; i < input.Length; i++)
{
if(input[i]=='(')
{
counter++;
}
else if (input[i]==')')
{
counter--;
}
if(counter<0)
{
isCorrect = false;
break;
}
}
if(counter>0)
{
isCorrect = false;
}
Console.WriteLine(isCorrect);
}
}<file_sep>//Write a program to calculate n! for each n in the range [1..100]. Hint: Implement first a method that multiplies a number represented as array of digits by given integer number.
using System;
class NFactorielFrom1To100
{
static string Multiply(string number,int a)
{
int currentSum = 0;
int currentSum2 = 0;
string finalSum = string.Empty;
//string answer = string.Empty;
for (int i = number.Length - 1; i >= 0; i--)
{
currentSum = 0;
currentSum += int.Parse((a *(number[i]-48)).ToString());
if(currentSum2!=0)
{
finalSum += (currentSum+ currentSum2);
}
currentSum2 = currentSum;
}
//answer = finalSum.ToString();
return finalSum;
}
static string Transformation(int [] array)
{
string result = string.Empty;
for (int i = array.Length - 1; i >= 0; i--)
{
result += array[i];
}
return result;
}
public static int[] ToArray(string number)
{
int[] array = new int[number.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = number[i] - 48;
}
return array;
}
public static string SumOfArray(string number1,string number2)
{
int[] firstArray=new int[number1.Length];
int[] secondArray=new int [number2.Length];
Array.Copy(firstArray, ToArray(number1), number1.Length);
Array.Copy(secondArray, ToArray(number2), number2.Length);
//Array.Reverse(firstArray);
//Array.Reverse(secondArray);
int maxLength = Math.Max(firstArray.Length, secondArray.Length);
int[] realArray = new int[maxLength];
int[] finalArray = new int[maxLength + 1];
if (firstArray.Length > secondArray.Length)
{
Array.Copy(secondArray, realArray, secondArray.Length);
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(firstArray[i] + realArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
if (counter == 1)
{
finalArray[finalArray.Length - 1] = 1;
}
number1 = Transformation(finalArray);
return number1;
}
else if (firstArray.Length < secondArray.Length)
{
Array.Copy(firstArray, realArray, firstArray.Length);
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(realArray[i] + secondArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
number1 = Transformation(finalArray);
return number1;
}
else
{
int currentSum = 0;
int counter = 0;
for (int i = 0; i < maxLength; i++)
{
currentSum = (int)(firstArray[i] + secondArray[i]) + counter;
counter = 0;
if (currentSum <= 9)
{
finalArray[i] = currentSum;
}
else if (currentSum > 9)
{
finalArray[i] = currentSum % 10;
counter++;
}
}
}
number1 = Transformation(finalArray);
return number1;
}
static void Main()
{
int num=int.Parse(Console.ReadLine());
string answer = "1";
for (int i = 2; i < num; i++)
{
answer=Multiply(answer,i);
}
Console.WriteLine(answer);
}
}
<file_sep>using System;
using System.Text;
class TRES4Numbers
{
static void Main()
{
ulong numberInDecimal = ulong.Parse(Console.ReadLine());
string[] allDigitsInTRESNUM4 = {"LON+","VK-","*ACAD","^MIM","ERIK|","SEY&","EMY>>","/TEL","<<DON"};
var answer=new StringBuilder();
while (numberInDecimal!=0)
{
answer.Insert(0,allDigitsInTRESNUM4[numberInDecimal%9]);
numberInDecimal /= 9;
}
Console.WriteLine(answer);
}
}<file_sep>//Write a method that checks if the element at given position in given array of integers is bigger than its two neighbors (when such exist).
using System;
class CheckTheNeiboursInArray
{
static string CheckTheNeibours(int[] array, int position)
{
if (position == 0)
{
return "This is first element!";
}
else if (position == array.Length - 1)
{
return "This is last element!";
}
else if (array[position] > array[position - 1] && array[position] > array[position + 1])
{
return "The element is bigger then neibours!";
}
return "The element isn't bigger then neibours!";
}
static void Main()
{
Console.Write("How many numbers you want to input:");
int numberOfIntegers = int.Parse(Console.ReadLine());
int [] integerArray=new int [numberOfIntegers];
for (int i = 0; i < integerArray.Length; i++)
{
Console.Write("Input {0} Numbers:",i+1);
integerArray[i] = int.Parse(Console.ReadLine());
}
Console.Write("Input the positon to check:");
int position = int.Parse(Console.ReadLine());
if(position<0 || position>integerArray.Length-1)
{
throw new Exception("Wrong position!");
}
Console.WriteLine(CheckTheNeibours(integerArray,position));
}
}<file_sep>using System;
class DurankulakNumbers
{
static long DurankulakNumber(string input)
{
if(input.Length>1)
{
return (input[0] - 96) * 26 + (input[1] - 65);
}
else
{
return (input[0] - 65);
}
}
static void Main()
{
string input = Console.ReadLine();
long answer = 0;
for (int i = 0; i < input.Length; i++)
{
answer *= 168;
if(char.IsLower(input[i]))
{
answer += DurankulakNumber(input.Substring(i,2));
i++;
}
else
{
answer += DurankulakNumber(input[i].ToString());
}
}
Console.WriteLine(answer);
}
}<file_sep>using System;
using System.Text;
class VariableLengthCodes
{
static void Main()
{
string[] allNumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int[] allIntegers = new int[allNumbers.Length];
for (int i = 0; i < allNumbers.Length; i++)
{
allIntegers[i] = int.Parse(allNumbers[i]);
}
var bitSequence = new StringBuilder();
for (int i = 0; i < allNumbers.Length; i++)
{
bitSequence.Append(Convert.ToString(allIntegers[i], 2));
}
int l = int.Parse(Console.ReadLine());
char[]arrayWithLetters=new char[l+1];
arrayWithLetters[0] = ' ';
for (int i = 0; i < l; i++)
{
StringBuilder currentWord = new StringBuilder(Console.ReadLine());
var currentLetter = new StringBuilder(currentWord.ToString());
currentWord.Remove(0, 1);
arrayWithLetters[int.Parse(currentWord.ToString())] = currentLetter[0];
}
for (int i = 0; i < bitSequence.Length; i++)
{
int counter = 0;
while (i<bitSequence.Length-1 && bitSequence[i]!='0')
{
counter++;
i++;
}
Console.Write(arrayWithLetters[counter]);
}
Console.WriteLine();
}
}<file_sep>//You are given an array of strings. Write a method that sorts the array by the length of its elements (the number of characters composing them).
using System;
class SortTheStringArrayByItsLength
{
static void Main()
{
string[] stringArray = {"book","programmer","computer","science","short","integer","byte","sbyte"};
int [] intArray=new int [stringArray.Length];
for (int i = 0; i < stringArray.Length; i++)
{
intArray[i] = stringArray[i].Length;
}
Array.Sort(intArray);
string [] finalArray=new string[stringArray.Length];
for (int i = 0; i < stringArray.Length; i++)
{
for (int j = 0; j < intArray.Length; j++)
{
if (stringArray[j].Length == intArray[i])
{
finalArray[i] = stringArray[j];
stringArray[j] = string.Empty;
break;
}
}
}
Console.WriteLine(string.Join(",",finalArray));
}
}
<file_sep>//Write a program to convert decimal numbers to their binary representation.
using System;
class DecimalToBinary
{
static void Main()
{
int input = int.Parse(Console.ReadLine());
string binaryRepresentation=string.Empty;
do
{
binaryRepresentation += (input % 2).ToString();
input /= 2;
} while (input > 0);
for (int i = binaryRepresentation.Length - 1; i >= 0; i--)
{
Console.Write(binaryRepresentation[i]);
}
Console.WriteLine();
}
}<file_sep>//Write a program that compares two text files line by line and prints the number of lines that are the same and the number of lines that are different. Assume the files have equal number of lines.
using System;
using System.IO;
class ComparesTwoTextFilesLineByLine
{
static void Main()
{
StreamReader reader = new StreamReader("1.txt");
StreamReader reader2 = new StreamReader("2.txt");
using(reader)
{
using(reader2)
{
int counter=0;
int counter2=0;
string readLine = reader.ReadLine();
string readLine2 = reader2.ReadLine();
while (readLine != null && readLine2 != null)
{
if (readLine==readLine2)
{
counter++;
}
else
{
counter2++;
}
readLine = reader.ReadLine();
readLine2 = reader2.ReadLine();
}
Console.WriteLine(counter);
Console.WriteLine(counter2);
}
}
}
}<file_sep>//A dictionary is stored as a sequence of text lines containing words and their explanations. Write a program that enters a word and translates it by using the dictionary.
using System;
class EncyclopedicDictionary
{
static void Main()
{
int nNumbers = int.Parse(Console.ReadLine());
string [] sentences=new string[nNumbers];
for (int i = 0; i < nNumbers; i++)
{
sentences[i] = Console.ReadLine();
}
string seekingWord = Console.ReadLine();
for (int i = 0; i < sentences.Length; i++)
{
if (sentences[i].IndexOf(seekingWord)==0)
{
Console.WriteLine(sentences[i].Substring(sentences[i].IndexOf('-')+2));
}
}
}
}<file_sep>//Write a program to convert from any numeral system of given base s to any other numeral system of base d (2 ≤ s, d ≤ 16).
using System;
class ConvertFromAnyNumeralSystem
{
static void PrintResult(string finalAnswer)
{
for (int i = finalAnswer.Length - 1; i >= 0; i--)
{
Console.Write(finalAnswer[i]);
}
Console.WriteLine();
}
static int ConvertToDecimal(string number,int input)
{
int result = 0;
for (int i = number.Length - 1; i >= 0; i--)
{
if (number[i] < 58)
{
result += (number[i] - 48) * (int)(Math.Pow(input, number.Length - 1 - i));
}
else
{
result += (number[i] - 55) * (int)(Math.Pow(input, number.Length - 1 - i));
}
}
return result;
}
static string ConvertToOutputSystem(int decimalNumber,int outputSystem)
{
string answer = string.Empty;
do
{
if (decimalNumber % outputSystem < 10)
{
answer += (decimalNumber % outputSystem).ToString();
}
else
{
answer += ((char)(decimalNumber % outputSystem+55)).ToString();
}
decimalNumber /= outputSystem;
} while (decimalNumber > 0);
return answer;
}
static void Main()
{
int inputSystem = int.Parse(Console.ReadLine());
int outputSystem = int.Parse(Console.ReadLine());
string inputNumber = Console.ReadLine();
int decimalAnswer = 0;
string finalAnswer = string.Empty;
decimalAnswer = ConvertToDecimal(inputNumber, inputSystem);
finalAnswer=ConvertToOutputSystem(decimalAnswer,outputSystem);
PrintResult(finalAnswer);
}
}<file_sep>using System;
using System.Text;
using System.Linq;
class BasicLanguage
{
static int For(string input)
{
while (true)
{
}
}
static void Main()
{
StringBuilder input = new StringBuilder();
while (input.ToString().IndexOf("EXIT;")<0)
{
input.Append(Console.ReadLine());
}
string allText=input.ToString();
string[] lines = allText.Split(';');
Console.WriteLine(string.Join("\n",lines));
}
}<file_sep>using System;
class SpecialValue
{
static int[][] ConvertToIntArray(int[][] row, int n)
{
int[][] jaggedArray = new int[n][];
for (int i = 0; i < n; i++)
{
string[] currentRow = Console.ReadLine().Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
jaggedArray[i] = new int[currentRow.Length];
for (int j = 0; j < currentRow.Length; j++)
{
jaggedArray[i][j] = int.Parse(currentRow[j]);
}
}
return jaggedArray;
}
static void Main()
{
int n = int.Parse(Console.ReadLine());
int[][] jaggedArray = new int[n][];
int maxLength = 0;
jaggedArray = ConvertToIntArray(jaggedArray, n);
for (int i = 0; i < n; i++)
{
if (maxLength < jaggedArray[i].Length)
{
maxLength = jaggedArray[i].Length;
}
}
int maxSum = 0;
for (int col = 0; col < jaggedArray[0].Length; col++)
{
int currentSum = 0;
int currentRow = 0;
int item = jaggedArray[currentRow][col];
int path = 1;
bool[,] jaggedBoolArray = new bool[n, maxLength];
if (item >= 0)
{
do
{
jaggedBoolArray[currentRow % n, col] = true;
currentRow++;
item = jaggedArray[currentRow % n][item];
path++;
if (item < 0)
{
break;
}
jaggedBoolArray[currentRow % n, item] = true;
} while (jaggedBoolArray[(currentRow + 1) % n, item] != true);
currentSum = path + Math.Abs(item);
}
else
{
currentSum = path + Math.Abs(item);
}
if (maxSum < currentSum)
{
maxSum = currentSum;
}
}
Console.WriteLine(maxSum);
}
}<file_sep>//Write a program to convert binary numbers to hexadecimal numbers (directly).
using System;
class BinaryToHexadecimalDirectly
{
static void Main()
{
string input = Console.ReadLine();
int length = input.Length;
if(input.Length%4!=0)
{
length += (4 - input.Length % 4);
}
input = input.PadLeft(length, '0');
string output = string.Empty;
for (int i = 0; i < input.Length-3; i+=4)
{
string currentValue = string.Empty;
for (int j = i; j < i+4; j++)
{
currentValue+=input[j];
}
switch (currentValue)
{
case"0000":
output += 0;
break;
case "0001":
output += 1;
break;
case "0010":
output += 2;
break;
case "0011":
output += 3;
break;
case "0100":
output += 4;
break;
case "0101":
output += 5;
break;
case "0110":
output += 6;
break;
case "0111":
output += 7;
break;
case "1000":
output += 8;
break;
case "1001":
output += 9;
break;
case "1010":
output += "A";
break;
case "1011":
output += "B";
break;
case "1100":
output += "C";
break;
case "1101":
output += "D";
break;
case "1110":
output += "E";
break;
case "1111":
output += "F";
break;
default:
output = "Error";
break;
}
}
Console.WriteLine(output);
}
}<file_sep>using System;
using System.Text;
class MultiverseCommunication
{
static void Main()
{
string input = Console.ReadLine();
string[] array = { "CHU", "TEL", "OFT", "IVA", "EMY", "VNB", "POQ", "ERI", "CAD", "K-A", "IIA", "YLO", "PLA" };
long answer = 0;
for (int i = 0; i < input.Length; i+=3)
{
for (int j=0;j<array.Length;j++)
{
if(input.Substring(i,3)==array[j])
{
answer *= 13;
answer += j;
break;
}
}
}
Console.WriteLine(answer);
}
}<file_sep>//Write a program that replaces in a HTML document given as string all the tags <a href="…">…</a> with corresponding tags [URL=…]…/URL].
using System;
using System.Text.RegularExpressions;
class ReplacesInAHTMLDocument
{
static void Main()
{
string html = Console.ReadLine();
html = html.Replace("<a href=\"", "[URL=");
html = html.Replace("\">", "]");
html = html.Replace("</a>", "[/URL]");
Console.WriteLine();
Console.WriteLine(html);
}
}<file_sep>//Write a method that return the maximal element in a portion of array of integers starting at given index. Using it write another method that sorts an array in ascending / descending order.
using System;
class FindMaxInArrayAndSort
{
static int FindMaxInArray(int[]array,int startPosition)
{
if(startPosition>array.Length)
{
return -1;
}
int maxElement = array[startPosition];
for (int i = startPosition+1; i < array.Length; i++)
{
if(array[i]>maxElement)
{
maxElement = array[i];
}
}
return maxElement;
}
static int FindMinInArray(int[] array, int startPosition)
{
if (startPosition > array.Length)
{
return -1;
}
int minElement = array[startPosition];
for (int i = startPosition + 1; i < array.Length; i++)
{
if (array[i] < minElement)
{
minElement = array[i];
}
}
return minElement;
}
static void DescendingArray(int []array)
{
int[] descendingArray=new int [array.Length];
for (int i = 0; i < array.Length; i++)
{
descendingArray[i] = FindMaxInArray(array, i);
for (int j = 0; j < array.Length; j++)
{
if(descendingArray[i]==array[j])
{
array[j] = array[i];
array[i] = descendingArray[i];
break;
}
}
}
foreach (var n in descendingArray)
{
Console.Write(n+" ");
}
Console.WriteLine();
}
static void AscendingArray(int []array)
{
int[] ascendingArray = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
ascendingArray[i] = FindMinInArray(array, i);
for (int j = 0; j < array.Length; j++)
{
if(ascendingArray[i]==array[j])
{
array[j] = array[i];
array[i] = ascendingArray[i];
break;
}
}
}
foreach (var n in ascendingArray)
{
Console.Write(n+" ");
}
Console.WriteLine();
}
static void Main()
{
Console.Write("Enter a number of integers:");
int number = int.Parse(Console.ReadLine());
int[] array = new int[number];
for (int i = 0; i < number; i++)
{
Console.Write("Enter {0} integer:",i+1);
array[i] = int.Parse(Console.ReadLine());
}
Console.Write("Enter the start position:");
int startPosition = int.Parse(Console.ReadLine());
Console.WriteLine(FindMaxInArray(array,startPosition));
DescendingArray(array);
AscendingArray(array);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
class MagicWords
{
static void Main()
{
int nNumber = int.Parse(Console.ReadLine());
List<string> allWords = new List<string>(1000);
int maxLength = 0;
for (int i = 0; i < nNumber; i++)
{
allWords.Add(Console.ReadLine());
if (allWords[i].Length > maxLength)
{
maxLength = allWords[i].Length;
}
}
StringBuilder currentWords = new StringBuilder();
for (int i = 0; i < nNumber; i++)
{
currentWords.Append(allWords[i]);
allWords[i] = null;
allWords.Insert(currentWords.Length%(nNumber+1), currentWords.ToString());
allWords.Remove(null);
currentWords.Clear();
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < maxLength; i++)
{
foreach (var n in allWords)
{
if(i<n.Length)
{
result.Append(n[i]);
}
}
}
Console.WriteLine(result.ToString());
}
}<file_sep>using System;
using System.Text;
class MovingLetters
{
static void Main()
{
string input = Console.ReadLine();
string[] arrayWithWords = input.Split(' ');
int maxLength = 0;
foreach (var n in arrayWithWords)
{
if (maxLength < n.Length)
{
maxLength = n.Length;
}
}
StringBuilder finalWord = new StringBuilder();
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < arrayWithWords.Length; j++)
{
if (i < arrayWithWords[j].Length)
{
finalWord.Append(arrayWithWords[j][arrayWithWords[j].Length - i - 1]);
}
}
}
for (int i = 0; i < finalWord.Length; i++)
{
char letter;
letter = finalWord[i];
finalWord.Remove(i, 1);
if (char.IsLower(letter))
{
finalWord.Insert(((int)letter - 96 + i) % (finalWord.Length + 1), letter);
}
else
{
finalWord.Insert(((int)letter - 64 + i) % (finalWord.Length + 1), letter);
}
}
Console.WriteLine(finalWord);
}
}<file_sep>using System;
using System.Text.RegularExpressions;
namespace ExtractEmails
{
class EmailsExtractor
{
static void Main(string[] args)
{
string text = Console.ReadLine();
string[] words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (TestEmailRegex(words[i]))
{
Console.WriteLine(words[i]);
}
}
}
static bool TestEmailRegex(string emailAddress)
{
string patternStrict = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
Regex reStrict = new Regex(patternStrict);
bool isStrictMatch = reStrict.IsMatch(emailAddress);
return isStrictMatch;
}
}
}
<file_sep>//Write a program that reads two arrays from the console and compares them element by element.
using System;
class ComparesTwoIntegerArrays
{
static void Main()
{
//Each array is inserted on one line and every element of the array is created with space between them.
string firstArray = Console.ReadLine();
string secondArray = Console.ReadLine();
if (firstArray.Length != secondArray.Length)
{
Console.WriteLine("false");
return;
}
for (int i = 0; i < firstArray.Length; i+=2)
{
if (firstArray[i] != secondArray[i])
{
Console.WriteLine("false");
return;
}
else
{
continue;
}
}
Console.WriteLine("true");
}
}
<file_sep>//Write a program to convert binary numbers to their decimal representation.
using System;
using System.Linq;
class BinaryToDecimalProgram
{
static void Main()
{
string input =Console.ReadLine();
int result = 0;
for (int i = input.Length - 1; i >= 0; i--)
{
result += (input[i]-48)*(int)(Math.Pow(2,input.Length-1-i));
}
Console.WriteLine(result);
}
}<file_sep>//Write a program that finds the sequence of maximal sum in given array. Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} {2, -1, 6, 4}
using System;
class TheSequenceOfMaxSum
{
static void Main()
{
string inputArrayOne = Console.ReadLine();
char[] delimiter = new char[] {',',' '};
string [] inputArrayTwo = inputArrayOne.Split(delimiter,StringSplitOptions.RemoveEmptyEntries);
int[]realArray=new int[inputArrayTwo.Length];
int currentSum = 0;
int maxSum = 0;
int counter = 1;
int arrayNumber = 0;
for (int i = 0; i < inputArrayTwo.Length; i++)
{
realArray[i] = int.Parse(inputArrayTwo[i]);
currentSum += realArray[i];
if (currentSum > maxSum)
{
maxSum = currentSum;
counter++;
arrayNumber = i;
}
if (currentSum < 0)
{
currentSum = 0;
counter = 1;
}
if (i == inputArrayTwo.Length - 1)
{
for (int j = arrayNumber-counter; j <=arrayNumber; j++)
{
Console.Write(realArray[j]);
if (j < arrayNumber)
{
Console.Write(", ");
}
}
}
}
Console.WriteLine();
}
}
<file_sep>//Write a program that deletes from given text file all odd lines. The result should be in the same file.
using System;
using System.IO;
using System.Collections.Generic;
class DeleteOddLines
{
static void Main()
{
string filePath="inputFile.txt";
StreamReader reader = new StreamReader(filePath);
List<string> array=new List<string>();
using (reader)
{
int number = 0;
string currentLine=reader.ReadLine();
while(currentLine!=null)
{
number++;
if(number%2==0)
{
array.Add(currentLine);
}
currentLine = reader.ReadLine();
}
}
StreamWriter writer = new StreamWriter(filePath);
using (writer)
{
for (int i = 0; i < array.Count; i++)
{
writer.WriteLine(array[i]);
}
}
}
}<file_sep>//Write a program that reads a string from the console and lists all different words in the string along with information how many times each word is found.
using System;
class PrintsAllDifferentWordsInTheString
{
static void Main()
{
string text = Console.ReadLine();
char[] separator = { ' ','.',',','!','?',':',';'};
string[] allWords = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
Array.Sort(allWords);
for (int i = 0; i < allWords.Length; i++)
{
int counter=1;
while(i<allWords.Length-1 && allWords[i]==allWords[i+1])
{
counter++;
i++;
}
Console.WriteLine("{0}->{1}times",allWords[i],counter);
}
}
}<file_sep>//Write a method that asks the user for his name and prints “Hello, <name>” (for example, “Hello, Peter!”).
using System;
public class SayHello
{
public static string PrintName(string name )
{
string greeting = "Hello, " + name+"!";
return greeting;
}
static void Main()
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine(PrintName(name));
}
}<file_sep>using System;
class PatternsProgram
{
static void Main()
{
int n=int.Parse(Console.ReadLine());
int [,]matrix=new int[n,n];
for (int i = 0; i < n; i++)
{
string[] line = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j= 0; j< n; j++)
{
matrix[i, j]=int.Parse(line[j]);
}
}
bool flag = false;
int maxSum = 0;
for (int i = 0; i < n-2; i++)
{
for (int j = 0; j < n-4; j++)
{
int currentSum=0;
if (matrix[i, j] == matrix[i, j + 1] - 1 && matrix[i, j + 1] == matrix[i, j + 2] - 1 && matrix[i, j + 2] == matrix[i + 1, j + 2] - 1 && matrix[i + 1, j + 2] == matrix[i + 2, j + 2] - 1 && matrix[i + 2, j + 2] == matrix[i + 2, j + 3] - 1 && matrix[i + 2, j + 3]==matrix[i+2,j+4]-1)
{
flag = true;
int currentElement=matrix[i,j];
currentSum = currentElement;
for (int k = 0; k < 6; k++)
{
currentElement++;
currentSum += currentElement;
}
}
if(currentSum>maxSum)
{
maxSum = currentSum;
}
}
}
if(flag)
{
Console.WriteLine("YES {0}",maxSum);
}
else
{
for (int i = 0; i < n; i++)
{
maxSum += matrix[i, i];
}
Console.WriteLine("NO {0}",maxSum);
}
}
}<file_sep>using System;
using System.Text;
class GagNumbers
{
static void Main()
{
string input = Console.ReadLine();
string[] digits = { "-!", "**", "!!!", "&&", "&-", "!-", "*!!!", "&*!", "!!**!-" };
StringBuilder currentWord = new StringBuilder();
ulong answer = 0;
for (int i = 0; i < input.Length; i++)
{
currentWord.Append(input[i]);
for (int j = 0; j < digits.Length; j++)
{
if (currentWord.ToString() == digits[j])
{
answer *= 9;
answer += (ulong)j;
currentWord = new StringBuilder();
break;
}
}
}
Console.WriteLine(answer);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
class ConsoleJustification
{
static List<string> ConvertToList(int n, List<string> list)
{
string[] currentRow;
for (int i = 0; i < n; i++)
{
currentRow = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < currentRow.Length; j++)
{
list.Add(currentRow[j]);
}
}
return list;
}
static void Main()
{
int n = int.Parse(Console.ReadLine());
int w = int.Parse(Console.ReadLine());
List<string> allWords = new List<string>();
allWords = ConvertToList(n, allWords);
for (int i = 0; i < allWords.Count - 1; i++)
{
var line = new StringBuilder(allWords[i]);
int wordsOnRow = 1;
while (i < allWords.Count - 1 && line.Length + allWords[i + 1].Length + 1 <= w)
{
wordsOnRow++;
i++;
line.Append(" ");
line.Append(allWords[i]);
}
if (line.Length < w)
{
int index = 0;
while (line.Length != w && wordsOnRow != 1)
{
index++;
if (index == line.Length - 1)
{
index = 0;
}
if (line[index] == ' ' && line[index + 1] != ' ')
{
line.Insert(index, ' ');
index++;
}
}
}
Console.WriteLine(line.ToString());
if (i == allWords.Count - 2)
{
Console.WriteLine(allWords[allWords.Count - 1]);
}
}
}
}<file_sep>//Write a program that extracts from a given text all dates that match the format DD.MM.YYYY. Display them in the standard date format for Canada.
using System;
using System.Text.RegularExpressions;
using System.Globalization;
namespace ExtractDates
{
class DatesExtractor
{
static void Main(string[] args)
{
string text = Console.ReadLine();
string pattern =
"\\b(?<day>[\\d]{1,2})\\.(?<month>[\\d]{2})\\.(?<year>[\\d]{4})\\.";
Regex dates = new Regex(pattern);
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match date in matches)
{
DateTime theDate = new DateTime(int.Parse(date.Groups["year"].ToString()),
int.Parse(date.Groups["month"].ToString()),
int.Parse(date.Groups["day"].ToString()));
CultureInfo culture = new CultureInfo("en-CA");
Console.WriteLine(theDate.ToString("d", culture));
}
}
}
}
<file_sep>//Write a program that extracts from given XML file all the text without the tags.
using System;
using System.IO;
class XMLFileWithoutTheTags
{
static void Main()
{
StreamReader reader = new StreamReader("inputFile.xml");
using (reader)
{
string text = reader.ReadToEnd();
for (int i = 0; i < text.Length-1; i++)
{
if (text[i] == '>'&& text[i+1]!='<')
{
while (text[i] != '<' && i<text.Length-1)
{
i++;
if(text[i]!='<')
{
Console.Write(text[i]);
}
}
if (text[i - 1] != '>')
{
Console.WriteLine();
}
}
}
}
}
}<file_sep>//Write a program that reads a string from the console and replaces all series of consecutive identical letters with a single one. Example: "aaaaabbbbbcdddeeeedssaa" "abcdedsa".
using System;
using System.Text;
class ReplacesAllSeriesOfIdenticalLetters
{
static void Main()
{
string text = Console.ReadLine();
for (int i = 0; i < text.Length; i++)
{
int currentPosition = i;
int counter = 0;
while(currentPosition<text.Length-1 &&text[currentPosition]==text[currentPosition+1])
{
counter++;
currentPosition++;
}
text = text.Remove(i , counter);
}
Console.WriteLine(text);
}
}<file_sep>//Write a program that reads an integer number and calculates and prints its square root. If the number is invalid or negative, print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally.
using System;
class SquareRootOfIntegerNumber
{
static void Main()
{
try
{
uint number = uint.Parse(Console.ReadLine());
double answer;
Console.WriteLine("{0:F2}",answer = Math.Sqrt(number));
}
catch(OverflowException)
{
Console.WriteLine("Invalid Number!");
}
catch(FormatException)
{
Console.WriteLine("Invalid Number!");
}
finally
{
Console.WriteLine("Good bye!");
}
}
}<file_sep>//Write a program that deletes from a text file all words that start with the prefix "test". Words contain only the symbols 0...9, a...z, A…Z, _.
using System;
using System.IO;
using System.Text.RegularExpressions;
class DeletePrefixTest
{
static void Main()
{
StreamReader reader = new StreamReader("input.txt");
string text;
using (reader)
{
text = reader.ReadToEnd();
}
text = Regex.Replace(text, @"\btest\w+", "");
text = Regex.Replace(text, @"\btest\b", "");
StreamWriter writer = new StreamWriter("input.txt");
using (writer)
{
writer.Write(text);
}
}
}<file_sep>//Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file. Ensure it will work with large files (e.g. 100 MB).
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
class ReplaceAllSubstringsStart
{
static void Main()
{
int nRows = int.Parse(Console.ReadLine());
StreamWriter writer = new StreamWriter("inputFile.txt");
using (writer)
{
for (int i = 0; i < nRows; i++)
{
writer.WriteLine(Console.ReadLine());
}
}
StreamReader reader = new StreamReader("inputFile.txt");
StreamWriter writer2 = new StreamWriter("outputFile.txt");
using (reader)
{
string currentLine = reader.ReadLine();
using (writer2)
{
for (int i = 0; i < nRows; i++)
{
writer2.WriteLine(Regex.Replace(currentLine, "start", "finish"));
currentLine = reader.ReadLine();
}
}
}
}
}<file_sep>//Write a program that reads a text file and prints on the console its odd lines.
using System;
using System.IO;
class ReadTextAndPrintsOddLines
{
static void Main()
{
StreamReader reader=new StreamReader(@"..\..\01.ReadTextAndPrintsOddLines.cs");
using(reader)
{
int lineNumber = 0;
string line = reader.ReadLine();
while(line!=null)
{
lineNumber++;
if(lineNumber%2!=0)
{
Console.WriteLine("{0}. {1}",lineNumber,line);
}
line = reader.ReadLine();
}
}
}
}<file_sep>//Write a program that reads a string from the console and prints all different letters in the string along with information how many times each letter is found.
using System;
class PrintsAllDifferentLettersInTheString
{
static void Main()
{
char [] text = Console.ReadLine().ToCharArray();
Array.Sort(text);
for (int i = 0; i < text.Length; i++)
{
int counter=1;
while(i<text.Length-1 && text[i]==text[i+1])
{
counter++;
i++;
}
Console.WriteLine("{0}->{1}times",text[i],counter);
}
}
}<file_sep>using System;
using System.Text;
class EncodeAndEncrypt
{
static void Main()
{
string message = Console.ReadLine();
string cypher = Console.ReadLine();
StringBuilder encryptedMessage=new StringBuilder(message);
for (int i = 0; i < Math.Max(message.Length,cypher.Length); i++)
{
encryptedMessage[i%encryptedMessage.Length] = (char)((((encryptedMessage[i%encryptedMessage.Length] - 'A') ^ (cypher[i % cypher.Length] - 'A')) + 'A'));
}
encryptedMessage.Append(cypher);
StringBuilder encodedMessage = new StringBuilder();
for (int i = 0; i < encryptedMessage.Length; i++)
{
int repeatedLetter = 1;
while (i < encryptedMessage.Length-1 && encryptedMessage[i] == encryptedMessage[i + 1])
{
repeatedLetter++;
i++;
}
if(repeatedLetter>2)
{
encodedMessage.Append(repeatedLetter);
encodedMessage.Append(encryptedMessage[i]);
}
else
{
encodedMessage.Append(encryptedMessage[i],repeatedLetter);
}
}
encodedMessage.Append(cypher.Length);
Console.WriteLine(encodedMessage);
}
} | 09971aad3b0fa78a3d109675f9f21cc5f99784a5 | [
"C#"
] | 91 | C# | Marto89/CSharp-Part2 | 57e930d3a11439ca8711e4dc4b138bdd715d8068 | f97cd3c983573d0f3239d98a9030256635794b69 |
refs/heads/master | <repo_name>laury93/IMCv2<file_sep>/app/src/main/java/com/example/myimc/MainActivity.kt
package com.example.myimc
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.myimcv2.R
import kotlinx.android.synthetic.main.activity_main.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_calcular.setOnClickListener{calculateImc()}
}
private fun calculateImc(){
if(et_altura.text.toString().isEmpty() || et_peso.text.toString().isEmpty()) {
Toast.makeText(
this,
"Los campos Peso y Altura no deben estar vacios para realizar el cálculo.",
Toast.LENGTH_SHORT
).show()
}else{
val altura: Double = et_altura.text.toString().toDouble()/100
val peso: Double = et_peso.text.toString().toDouble()
val alturax2: Double = altura*altura
var imc: Double = peso/alturax2
tv_imc.text = String.format("%.2f",imc)
var hombre: Boolean = false
var mujer: Boolean = false
hombre = rb_hombre.isChecked
mujer = rb_mujer.isChecked
if(hombre == true ){
if(imc < 18.5){
tv_estado.text = "Peso inferior al normal"
}else if(imc in 18.5..24.9){
tv_estado.text = "Normal"
}else if(imc in 25.0..29.9){
tv_estado.text = "Sobrepeso"
}else if(imc > 30.0){
tv_estado.text = "Obesidad"
}
}else if(mujer == true){
if(imc < 18.5){
tv_estado.text = "Peso inferior al normal"
}else if(imc in 18.5..23.9){
tv_estado.text = "Normal"
}else if(imc in 25.0..28.9){
tv_estado.text = "Sobrepeso"
}else if(imc > 29.0){
tv_estado.text = "Obesidad"
}
}
}
if (fileList().contains("notas.txt")) {
try {
val archivo = InputStreamReader(openFileInput("notas.txt"))
val br = BufferedReader(archivo)
var linea = br.readLine()
val todo = StringBuilder()
while (linea != null) {
todo.append(linea + "\n")
linea = br.readLine()
}
br.close()
archivo.close()
et_peso.setText(todo)
} catch (e: IOException) {
}
}
try {
val archivo = OutputStreamWriter(openFileOutput("notas.txt", Activity.MODE_PRIVATE))
archivo.write(et_altura.text.toString())
archivo.flush()
archivo.close()
} catch (e: IOException) {
}
Toast.makeText(this, "Los datos fueron grabados",Toast.LENGTH_SHORT).show()
finish()
}
} | b2a2d8972a532dd7d4a2ba2405f216df2fb4d25d | [
"Kotlin"
] | 1 | Kotlin | laury93/IMCv2 | fe982fff83948a220d6fbf37373871fe37f9ae2c | 4b4e2fb90be32a1fbe292c94c6065c80300ca5a0 |
refs/heads/master | <file_sep><?php
/**
* Скрипт для відправки телефону через e-mail,
* автоматично перевіряє номер телефону на відсутність зайвої інформації та правильність вводу.
* Сприймає всі міжнародні формати:
* (123)456-7890 | (123)456-7890 x123 | +1 (123)456-7890
* 12 3456 789 0 x1234 | (123)456-7890x123 |(123)456-7890ext123
* (123)456-7890 extension123 | 123.456.7890 | 1234567890 | 1234567
* 12 34 56 78 90 | 12 3 4567 890123 x4567 | +12 3456 7890 | +12 34 56 7890
* +12 3456 7890 | +12 34567890
*
* <<EMAIL>>
*/
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// змінна для імені абонента
$abonent_name = strip_tags(substr(trim($_POST['abonent_name']), 0, 30));
// змінна для номеру телефону
$phone_number = strip_tags(substr(trim($_POST['phone_number']), 0, 19));
// змінна для відповіді, формат json
$response = array();
//International & Domestic Phone Numbers with Ext
if (!preg_match('/^([\+][0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)$/', $phone_number)) {
//if (false) {
$response['error'] = "Необхібно ввести коректний номер телефону!\n". $phone_number;
echo json_encode($response);
exit();
}
// Добавляємо дату та час до нашого пповідомлення
$date_time = date('d.m.y, H:i');
// Заголовок e-mail повіломлення
$subject = "Новий зворотний дзвінок";
// $to - кому відправляємо e-mail
$to = "<EMAIL>";
// $from - від кого відправляємо e-mail
$from = "http://site.net.ua <<EMAIL>>";
// IP адреса відправника
$remote_addr=$_SERVER["REMOTE_ADDR"];
// створюємо наше повідомлення
$message = "<b>" . $subject . ":</b>\t" . $date_time . "<br />"
. "<b>Ім’я абонента:</b>\t" . $abonent_name . "<br />"
. "<b>Контактний телефон:</b>\t" . $phone_number . "<br />"
. "<b>IP відправника:</b>\t" . $remote_addr;
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: " . $from . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$result = false;
$result = mail($to, $subject.":\t".$date_time, $message, $headers);
if($result) {
$response['success'] = "Повідомлення надіслано!!!";
} else {
$response['success'] = '<font color="#FF0000">Повідомлення не надіслано!!! Спробуйте пізніше...</font>';
}
echo json_encode($response);
exit();
}
exit();
<file_sep># call_me
Call Me - simple script


<file_sep>//jQuery.noConflict();
jQuery(document).ready(function () {
jQuery("#telNumber").mask("+38 (999) 999-99-99");
var p = jQuery('.window_wrap');
jQuery('.telButton').click(function () {
p.css({'display': 'block'}).hide().fadeIn(1000);
});
p.click(function (event) {
if (event.target == this) {
jQuery(this).css({'display': 'none'});
}
});
jQuery('.window_close').click(function () {
p.css({'display': 'none'});
});
jQuery('#telButton').click(function () {
var abonent_name = jQuery('#abonentName').val();
var phone_number = jQuery('#telNumber').val();
if (abonent_name.length <= 2) {
alert("Введіть, будь ласка, Ваше Ім’я");
return false;
}
if (abonent_name.length > 30) {
alert("В полі Ім’я можна ввести не більше 30-ти символів");
return false;
}
//console.log(phone_number.length);
if (phone_number.length == 0) {
alert("Введіть, будь ласка, номер телефону");
return false;
}
jQuery('#backPhone').fadeOut(500, function () {
jQuery('<p>Надсилання!</p>').appendTo(jQuery('.window')).hide().fadeIn(300, function () {
jQuery.ajax({
type: 'POST',
url: '/call-me.php',
data: {
phone_number: phone_number,
abonent_name: abonent_name
},
dataType: 'json',
success: function (data) {
if (data.error) {
jQuery('.window p').last().remove();
jQuery('#backPhone').fadeIn(300, function () {
alert(data.error);
});
} else {
jQuery('.window p').last().fadeOut(300, function () {
jQuery(this).text(data.success).fadeIn(300, function () {
jQuery('.window_wrap').delay(1500).fadeOut(300);
});
});
}
},
error: function () {
alert('Error send!!!');
}
});
});
});
return false;
});
jQuery('.telButton .telButton_background').hover(
function () {
var v = jQuery('.telButton_hover');
if (!v.hasClass('fHovered')) {
v.stop().css('display', 'block').animate({'opacity': 1}, 1000).addClass('fHovered');
}
},
function () {
var v = jQuery('.telButton_hover');
if (v.hasClass('fHovered')) {
v.stop().animate({'opacity': 0}, 1000, function () {
jQuery(this).css('display', 'none');
}).removeClass('fHovered');
}
}
);
jQuery('.telButton.anim').css({'position': 'absolute', 'top': '-100px', 'right': '50px', 'transition': "top 0.9s cubic-bezier(.65, 1.95, .03, .32) 0.5s"});
telButtonReturn();
jQuery(window).scroll(function () {
telButtonReturn();
});
jQuery(window).resize(function () {
telButtonReturn();
});
function telButtonReturn() {
var wHeight = getWindowHeight();
var sHeight = jQuery(window).scrollTop();
var result = wHeight + sHeight - 100;
jQuery('.telButton.anim').css({'position': 'absolute', 'top': result + 'px', 'right': '50px'});
}
function getWindowHeight() {
var windowHeight;
windowHeight = jQuery(window).height();
return windowHeight;
}
}); | 365f4b01cb101cc565e2654ea5dee5a00ef825ec | [
"Markdown",
"JavaScript",
"PHP"
] | 3 | PHP | YuriiRadio/call_me | 6a4c4a6126cd445cd717e8e76917366dc3d1e00e | e007212dfc9765f17122446a971cc8bfbe436d39 |
refs/heads/master | <repo_name>marcosantonio0307/eletrocellsrn<file_sep>/app/models/product.rb
class Product < ApplicationRecord
validates :name, presence: true
validates :amount, presence: true
validates :cost, presence: true
validates :price, presence: true
end
<file_sep>/app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
@title = 'Meus Produtos'
@products = Product.all
@products.order! :name
end
def new
@product = Product.new
@message = ''
end
def create
@message = ''
values = params.require(:product).permit!
sku_registred = Product.all.map{|p| p.sku}
@product = Product.new values
if sku_registred.include? @product.sku
@message = 'SKU já Cadastrado!'
render :new
else
@product.sku.upcase!
@product.name.upcase!
@product.save
if @product.save
redirect_to products_path, notice: 'Produto Criado com Sucesso!'
else
@message = 'Campos Obrigatórios não Preenchidos!'
render :new
end
end
end
def edit
@product = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
values = params.require(:product).permit!
@product.update values
if @product.save
redirect_to products_path, notice: 'Produto Atualizado com Sucesso!'
else
render :edit
end
end
def add
@product = Product.find(params[:id])
end
def entry
@product = Product.find(params[:id])
entry = params[:entry]
entry = entry.to_i
amount = @product.amount + entry
@product.update(amount: amount)
redirect_to product_path(@product), notice: 'Entrada Realizada com Sucesso!'
end
def report_products
@category = params[:category]
@products = Product.where(category: @category)
@products = @products.order :amount
end
def inventory
@sales = Sale.all
@sales = filter_day(@sales)
@products = []
@sales.each do |sale|
sale.item.each do |item|
if @products.include? item.product
item.product
else
@products << item.product
end
end
end
respond_to do |format|
format.html
format.pdf { render template: 'products/print_inventory', pdf: 'print_inventory'}
end
end
def cost
cells = Product.where(category: 'celular')
resume(cells)
@cells_amount = @products_amount
@cells_cost = @products_cost
@cells_price = @products_price
eletronics = Product.where(category: 'eletronico')
resume(eletronics)
@eletronics_amount = @products_amount
@eletronics_cost = @products_cost
@eletronics_price = @products_price
parts = Product.where(category: 'peca')
resume(parts)
@parts_amount = @products_amount
@parts_cost = @products_cost
@parts_price = @products_price
accessories = Product.where(category: 'acessorio')
resume(accessories)
@accessories_amount = @products_amount
@accessories_cost = @products_cost
@accessories_price = @products_price
all_products = Product.all
resume(all_products)
@all_products_amount = @products_amount
@all_products_cost = @products_cost
@all_products_price = @products_price
end
def destroy
id = params[:id]
Product.destroy id
redirect_to products_path, notice: 'Produto Excluído com Sucesso!'
end
def search
@name = params[:name]
@name.upcase!
@products = Product.where "name like ?", "%#{@name}%"
end
def show
@product = Product.find(params[:id])
end
end
private
def resume(products)
@products_amount = 0
@products_cost = 0
@products_price = 0
products.each do |product|
amount = product.amount
cost = amount * product.cost
price = amount * product.price
@products_amount += amount
@products_cost += cost
@products_price += price
end
@products_amount
@products_cost
@products_price
end<file_sep>/app/models/sale.rb
class Sale < ApplicationRecord
belongs_to :client
belongs_to :user
has_many :item, dependent: :destroy
def update_total
new_total = item.map{|i| i.price}.sum
update(total: new_total)
end
end
<file_sep>/app/controllers/expenses_controller.rb
class ExpensesController < ApplicationController
def expenses
@category = 'gerais'
@expenses = Expense.where(category: @category)
@report = true
@title = 'Despesas'
render :index
end
def advances
@category = 'vale funcionario'
@expenses = Expense.where(category: @category)
@report = true
@title = 'Vales'
render :index
end
def devolutions
@category = 'devolucao'
@expenses = Expense.where(category: @category)
@report = true
@title = 'Devoluções'
render :index
end
def index
@expenses = Expense.all
@expenses = @expenses.order :id
@title = 'Minhas Despesas'
@report = true
end
def new
@expense = Expense.new
@category = 'gerais'
end
def advance
@expense = Expense.new
@category = 'vale funcionario'
end
def devolution
@expense = Expense.new
@category = 'devolucao'
end
def create
values = params.require(:expense).permit!
@expense = Expense.create values
@expense.update(user_id: current_user.id)
if @expense.save
redirect_to expenses_expenses_day_path, notice: 'Despesa Salva com Sucesso!'
end
end
def edit
@expense = Expense.find(params[:id])
@category = @expense.category
end
def update
values = params.require(:expense).permit!
@expense = Expense.find(params[:id])
@expense.update values
redirect_to expenses_expenses_day_path, notice: 'Despesa Alterada com Sucesso!'
end
def filter_date
@category = params[:category]
@report = true
if @category != ""
@expenses = Expense.where(category: @category)
else
@expenses = Expense.all
end
@begin_date = params[:begin_date]
@end_date = params[:end_date]
@filter = []
if @begin_date > @end_date
render :index
else
@expenses.each do |expense|
if expense.created_at.strftime("%Y-%m-%d") == @begin_date
@filter << expense
elsif expense.created_at.strftime("%Y-%m-%d") > @begin_date && expense.created_at.strftime("%Y-%m-%d") < @end_date
@filter << expense
elsif expense.created_at.strftime("%Y-%m-%d") == @end_date
@filter << expense
end
end
@expenses = @filter
end
end
def expenses_day
@title = 'Despesas do Dia'
@expenses = Expense.all
@expenses = filter_day(@expenses)
end
def show
@expense = Expense.find(params[:id])
end
def destroy
id = params[:id]
Expense.destroy id
redirect_to expenses_path, notice: 'Despesa Excluída com Sucesso'
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
resources :clients, only:[:index, :new, :create, :edit, :update, :destroy]
resources :products, only:[:index, :new, :create, :edit, :update, :destroy]
resources :expenses, only:[:index, :new, :create, :edit, :update, :destroy]
resources :cash, only:[:index, :new, :edit, :update]
get 'users/edit_user' => 'users#edit_user'
get 'users/edit_category/:id' => 'users#edit_category', as: :category_user
resources :users, only:[:index, :new, :create, :edit, :update]
get 'cash/report' => 'cash/report'
get 'cash/filter_date' => 'cash#filter_date'
get 'cash/reopen' => 'cash#reopen'
get 'cash/:id' => 'cash#show'
get 'sales/filter_date' => 'sales#filter_date'
get 'sales/sales' => 'sales#sales'
get 'sales/:id/print' => 'sales#print', as: :print_sale
get 'sales/search' => 'sales#search'
get 'sales/salesman' => 'sales#salesman'
get 'sales/report_salesman' => 'sales#report_salesman'
get 'sales/commission' => 'sales#commission'
get 'sales/report_commission' => 'sales#report_commission'
get 'sales/sales_day' => 'sales#sales_day'
get 'sales/services_day' => 'sales#services_day'
get 'sales/new_service' => 'sales#new_service', as: :new_service_sale
get 'sales/services' => 'sales#services'
get 'sales/:id/finish' => 'sales#finish', as: :finish_sale
get 'sales/:id/search_item' => 'sales#search_item', as: :search_item_sale
get 'sales/:sale_id/new_select/:id' => 'items#new_select', as: :new_select_sale_item
get 'sales/:sale_id/select_client/:id' => 'sales#select_client', as: :select_client_sale
get 'sales/:id/cancel' => 'sales#cancel', as: :cancel_sale
get 'sales/opens' => 'sales#opens'
resources :sales do
resources :items
end
get 'clients/:id' => 'clients#show'
get 'products/search' => 'products#search', as: :search_products
get 'products/category' => 'products#category'
get 'products/report_products' => 'products#report_products'
get 'products/inventory' => 'products#inventory'
get 'products/cost' => 'products#cost'
get 'products/:id/add' => 'products#add', as: :add_product
get 'products/:id/entry' => 'products#entry', as: :entry_product
get 'products/:id' => 'products#show'
get 'sales/:id/client' => 'sales#client', as: :client_sale
post 'sales/:sale_id/items/:id' => 'items#add', as: :add_sale_item
get 'expenses/advance' => 'expenses#advance', as: :advance_expense
get 'expenses/devolution' => 'expenses#devolution', as: :devolution_expense
get 'expenses/expenses' => 'expenses#expenses'
get 'expenses/advances' => 'expenses#advances'
get 'expenses/devolutions' => 'expenses#devolutions'
get 'expenses/filter_date' => 'expenses#filter_date'
get 'expenses/expenses_day' => 'expenses#expenses_day'
get 'expenses/:id' => 'expenses#show'
root 'home#index'
end
<file_sep>/db/migrate/20190531131903_add_category_to_sales.rb
class AddCategoryToSales < ActiveRecord::Migration[5.2]
def change
add_column :sales, :category, :string
add_column :sales, :description, :string
add_column :sales, :status, :string
end
end
<file_sep>/app/controllers/clients_controller.rb
class ClientsController < ApplicationController
def index
@clients = Client.all
end
def new
@client = Client.new
@message = ''
end
def create
@message = ''
cpf_registred = Client.all.map{|c| c.cpf}
values = params.require(:client).permit!
@client = Client.new values
if cpf_registred.include?(@client.cpf)
@message = 'CPF ja cadastrado!'
render :new
else
@client.name.upcase!
@client.save
if @client.save
redirect_to client_path(@client), notice: 'Cliente Cadastrado com Sucesso!'
else
@message = 'Campos Obrigatórios não Preenchidos!'
render :new
end
end
end
def edit
@client = Client.find(params[:id])
end
def update
@client = Client.find(params[:id])
values = params.require(:client).permit!
@client.update values
if @client.save
redirect_to client_path, notice: 'Cliente Altualizado com Sucesso!'
else
render :edit
end
end
def destroy
id = params[:id]
Client.destroy id
redirect_to clients_path, notice: 'Cliente Excluído com Sucesso!'
end
def search
@name = params[:name]
@name.upcase!
@clients = Client.where "name like ?", "%#{@name}%"
end
def show
@client = Client.find(params[:id])
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def admin?(user)
if user.category == 'admin'
true
end
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!
def filter_day(base)
today = Time.zone.now
today = today.strftime("%Y-%m-%d")
filter = []
base.each do |b|
if b.created_at.strftime("%Y-%m-%d") == today
filter << b
end
end
base = filter
base.sort!
end
end
<file_sep>/db/migrate/20190603191922_add_nextbegin_to_cash.rb
class AddNextbeginToCash < ActiveRecord::Migration[5.2]
def change
add_column :cashes, :next_begin, :decimal
end
end
<file_sep>/app/controllers/cash_controller.rb
class CashController < ApplicationController
def index
@sales = Sale.where(category: 'sale')
@services = Sale.where(category: 'service')
@expenses = Expense.all
cash_sales = filter_day(@sales)
cash_services = filter_day(@services)
cash_outflows = filter_day(@expenses)
@total_cash_sales = 0
@total_cash_services = 0
@total_cash_outflows = 0
if Cash.last != nil
@begin_value = Cash.last.next_begin
else
@begin_value = 0
end
cash_sales.each do |cash|
@total_cash_sales += cash.total
end
cash_services.each do |cash|
@total_cash_services += cash.total
end
cash_outflows.each do |cash|
@total_cash_outflows += cash.total
end
@current_cash = @total_cash_sales + @total_cash_services + @begin_value - @total_cash_outflows
cashes = Cash.all
@today_cash = filter_day(cashes)
end
def new
total = params[:total]
@cash = Cash.create(total: total, next_begin: 0)
redirect_to edit_cash_path(@cash)
end
def edit
@cash = Cash.find(params[:id])
end
def update
@cash = Cash.find(params[:id])
next_begin = params[:next_begin]
@cash.update(next_begin: next_begin.to_f)
redirect_to root_path, notice: 'Caixa Fechado Com Sucesso!'
end
def report
@cashes = Cash.all
end
def filter_date
@cashes = Cash.all
@begin_date = params[:begin_date]
@end_date = params[:end_date]
filter = []
if @begin_date > @end_date
render :report
else
@cashes.each do |cash|
if cash.created_at.strftime("%Y-%m-%d") == @begin_date
filter << cash
elsif cash.created_at.strftime("%Y-%m-%d") > @begin_date && cash.created_at.strftime("%Y-%m-%d") < @end_date
filter << cash
elsif cash.created_at.strftime("%Y-%m-%d") == @end_date
filter << cash
end
end
@cashes = filter
end
end
def reopen
cashes = Cash.all
cash = filter_day(cashes)
if cash != []
cash.first.destroy
redirect_to cash_index_path, notice: 'Caixa Reaberto!'
else
redirect_to cash_index_path, notice: 'Caixa já esta aberto!'
end
end
end
<file_sep>/app/controllers/sales_controller.rb
class SalesController < ApplicationController
def index
@sales = Sale.where(category: 'sale')
@sales = @sales.order :id
@report = false
@title = 'Vendas'
end
def services
@sales = Sale.where(category: 'service')
@sales = @sales.order :id
@report = false
@title = 'Ordens de Serviço'
render :index
end
def opens
@sales = Sale.where(category: 'service', status: 'aberta')
@report = false
@title = 'O.S Abertas'
render :sales_day
end
def new
@sale = Sale.new
if Sale.last != nil
last_id = Sale.last.id
@sale.id = (last_id + 1)
else
@sale.id = 1
end
@sale.client_id = 1
@sale.user_id = current_user.id
@sale.total = 0
@sale.category = 'sale'
@sale.status = 'fechada'
@sale.description = ''
@sale.save
redirect_to client_sale_path(@sale)
end
def new_service
@sale = Sale.new
if Sale.last != nil
last_id = Sale.last.id
@sale.id = (last_id + 1)
else
@sale.id = 1
end
@sale.client_id = 1
@sale.user_id = current_user.id
@sale.total = 0
@sale.category = 'service'
@sale.status = 'aberta'
@sale.description = ''
@sale.save
redirect_to client_sale_path(@sale)
end
def client
@sale = Sale.find(params[:id])
@clients = Client.all
end
def select_client
@sale = Sale.find(params[:sale_id])
client = Client.find(params[:id])
@sale.update(client_id: client.id)
redirect_to edit_sale_path(@sale)
end
def edit
@sale = Sale.find(params[:id])
@items = Item.where(sale_id: @sale.id)
end
def update
@sale = Sale.find(params[:id])
description = params[:description]
status = params[:status]
imei = params[:imei]
warrenty = params[:warrenty]
if @sale.category == 'service'
@sale.update(description: description, status: status)
else
@sale.update(imei: imei, warrenty: warrenty)
end
redirect_to print_sale_path(@sale), notice: 'Venda Salva com Sucesso!'
end
def print
@sale = Sale.find(params[:id])
if @sale.category == 'service'
respond_to do |format|
format.html
format.pdf { render template: 'sales/print_os', pdf: 'print_os'}
end
else
respond_to do |format|
format.html
format.pdf { render template: 'sales/print_sale', pdf: 'print_sale'}
end
end
end
def finish
@sale = Sale.find(params[:id])
@sale.update(status: 'fechada')
redirect_to sales_services_day_path, notice: 'O.S finalizada com Sucesso!'
end
def filter_date
category = params[:category]
@sales = Sale.where(category: category)
@begin_date = params[:begin_date]
@end_date = params[:end_date]
@sales = filter(@sales, @begin_date, @end_date)
end
def search
@name = params[:client]
client = Client.where "name like ?", "%#{@name}%"
if client.first != nil
@sales = Sale.where "client_id like ?", "%#{client.first.id}%"
else
@sales = []
end
end
def report_salesman
@title = 'Relatório por Vendedor'
@begin_date = params[:begin_date]
@end_date = params[:end_date]
@sellers = User.all
@sales = Sale.where(category: 'sale')
@sales = filter(@sales, @begin_date, @end_date)
end
def report_commission
id = params[:salesman]
salesman = User.where(id: id)
@sales = Sale.where(user_id: id, category: 'sale')
@begin_date = params[:begin_date]
@end_date = params[:end_date]
@percentage = params[:commission]
@percentage = @percentage.to_f
@report = true
@title = "Vendedor: #{salesman.first.email}"
@sales = filter(@sales, @begin_date, @end_date)
@commission = 0
@sales.each do |sale|
sale.item.each do |item|
if item.product.category != 'celular'
if item.price != nil
@commission += item.price
end
end
end
end
@total_sales = @commission
@commission = @commission * (@percentage/100)
end
def sales_day
@title = 'Vendas do Dia'
@report = false
@sales = Sale.where(category: 'sale')
filter = filter_day(@sales)
@sales = filter
end
def services_day
@title = 'O.S do Dia'
@report = false
@sales = Sale.where(category: 'service')
filter = filter_day(@sales)
@sales = filter
render :sales_day
end
def search_item
@sale = Sale.find(params[:id])
@products = Product.all
end
def cancel
@sale = Sale.find(params[:id])
if @sale.item.empty? == true
@sale.destroy
redirect_to sales_sales_day_path, notice: 'Venda Cancelada!'
else
@sale.item.each do |item|
if item.amount != nil
amount = item.amount #retorna a quantidade do produto para o estoque quando remove-o da lista
new_amount = item.product.amount + amount
item.product.update(amount: new_amount)
end
end
@sale.destroy
redirect_to sales_sales_day_path, notice: 'Venda Cancelada!'
end
end
def destroy
id = params[:id]
Sale.destroy id
redirect_to sales_sales_day_path, notice: 'Venda Excluída com Sucesso!'
end
def show
@sale = Sale.find(params[:id])
@items = Item.where(sale_id: @sale.id)
if @sale.category == 'service'
if @sale.status == 'aberta'
respond_to do |format|
format.html
format.pdf { render template: 'sales/print_os', pdf: 'print_os'}
end
else
respond_to do |format|
format.html
format.pdf { render template: 'sales/print_os_finish', pdf: 'print_os_finish'}
end
end
else
respond_to do |format|
format.html
format.pdf { render template: 'sales/print_sale', pdf: 'print_sale'}
end
end
end
end
private
def filter(sales, begin_date, end_date)
filter = []
if begin_date > end_date
render :index
else
sales.each do |sale|
if sale.created_at.strftime("%Y-%m-%d") == begin_date
filter << sale
elsif sale.created_at.strftime("%Y-%m-%d") > begin_date && sale.created_at.strftime("%Y-%m-%d") < end_date
filter << sale
elsif sale.created_at.strftime("%Y-%m-%d") == end_date
filter << sale
end
end
sales = filter
end
end
<file_sep>/app/controllers/items_controller.rb
class ItemsController < ApplicationController
def new
@sale = Sale.find(params[:sale_id])
sku = params[:sku].strip
sku.upcase!
item = Product.where "sku like ?", "%#{sku}%"
if item.first.amount > 0
@item = Item.create
@item.update(sale: @sale, product: item.first)
else
redirect_to edit_sale_path(@sale), notice: 'Produto com Estoque Zerado!'
end
end
def new_select
@sale = Sale.find(params[:sale_id])
product = Product.find(params[:id])
if product.amount > 0
@item = Item.create
@item.update(sale: @sale, product: product)
else
redirect_to edit_sale_path(@sale), notice: 'Produto com Estoque Zerado!'
end
end
def add
@sale = Sale.find(params[:sale_id]) #set
@item = Item.find(params[:id])
amount = params[:amount].to_i
unity = @item.product.price
discount = params[:discount].to_f
price = unity * amount
price = price - discount
@item.update(amount: amount, price: price, discount: discount)
@sale.update_total
new_amount = @item.product.amount - amount
@item.product.update(amount: new_amount)
redirect_to edit_sale_path(@sale), notice: 'Item Incluído com Sucesso!'
end
def destroy
@sale = Sale.find(params[:sale_id])
id = params[:id]
item = Item.find(id)
if item.amount != nil
amount = item.amount #retorna a quantidade do produto para o estoque quando remove-o da lista
new_amount = item.product.amount + amount
item.product.update(amount: new_amount)
end
Item.destroy id
@sale.update_total
redirect_to edit_sale_path(@sale)
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def new
sign_out
redirect_to new_user_registration_path
end
def edit_user
@user = current_user
render :edit
end
def edit
@user = User.find(params[:id])
end
def edit_category
@user = User.find(params[:id])
end
def update
user = User.find(params[:id])
password = params[:password]
category = params[:category]
name = params[:name]
if password != ''
if category != nil
user.update(password: <PASSWORD>, category: category, name: name)
redirect_to root_path, notice: 'Alterado com Sucesso!'
else
user.update(password: <PASSWORD>)
redirect_to root_path, notice: 'Alterado com Sucesso!'
end
else
render :edit
end
end
end
| 7dfa9ab7e3b962d25372cf8f220e8b73487f9c4d | [
"Ruby"
] | 14 | Ruby | marcosantonio0307/eletrocellsrn | a5ef42ec035bab12220ef885500dd91347eed0a8 | bce7ab615e10e2c86d47e28a68e58175e380b551 |
refs/heads/master | <repo_name>dairaga/sqlx<file_sep>/cmd_test.go
package sqlx
import "fmt"
func ExampleCmd_Select() {
cmd := NewCmd()
cmd.Reset()
cmd.Select("1 + 1")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("1 + 1").From("DUAL")
fmt.Println(cmd)
cmd.Reset()
cmd.Select().From("t1").InnerJoinOn("t2", "t1.id=t2.id")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("CONCAT(last_name,', ',first_name) AS full_name").From("mytable").OrderBy("full_name")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("t1.name", "t2.salary").From("employee AS t1").From("info AS t2").Where("t1.name = t2.name")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("a", "COUNT(b)").From("test_table").GroupBy("a").OrderBy("NULL")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("COUNT(col1) AS col2").From("t").GroupBy("col2").Having("col2 = 2")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("REPEAT('a',1)").Union().Select("REPEAT('b',10)")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("college", "region", "seed").From("tournament").OrderBy("region").OrderBy("seed")
fmt.Println(cmd)
cmd.Reset()
cmd.Select("user", "MAX(salary)").From("users").GroupBy("user").Having("MAX(salary) > 10")
fmt.Println(cmd)
cmd.Reset()
cmd.Select().From("tbl").Limit(10, 5)
fmt.Println(cmd)
// Output:
// SELECT 1 + 1
// SELECT 1 + 1 FROM DUAL
// SELECT * FROM t1 INNER JOIN t2 ON t1.id=t2.id
// SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable ORDER BY full_name
// SELECT t1.name,t2.salary FROM employee AS t1,info AS t2 WHERE t1.name = t2.name
// SELECT a,COUNT(b) FROM test_table GROUP BY a ORDER BY NULL
// SELECT COUNT(col1) AS col2 FROM t GROUP BY col2 HAVING col2 = 2
// SELECT REPEAT('a',1) UNION SELECT REPEAT('b',10)
// SELECT college,region,seed FROM tournament ORDER BY region, seed
// SELECT user,MAX(salary) FROM users GROUP BY user HAVING MAX(salary) > 10
// SELECT * FROM tbl LIMIT 5,10
}
func ExampleCmd_Union() {
cmd := NewCmd()
sub := NewCmd()
cmd.Reset()
sub.Reset()
cmd.Select("a").From("t1").WhereAnd("a=10", "B=1").OrderBy("a").Limit(10)
sub.Select("a").From("t2").WhereAnd("a=11", "B=2").OrderBy("a").Limit(10)
cmd.Union(sub)
fmt.Println(cmd)
cmd.Reset()
sub.Reset()
cmd.Select("a").From("t1").WhereAnd("a=10", "B=1")
sub.Select("a").From("t2").WhereAnd("a=11", "B=2")
cmd.Union(sub)
cmd.OrderBy("a").Limit(10)
fmt.Println(cmd)
cmd.Reset()
sub.Reset()
cmd.Select("1 AS sort_col", "col1a", "col1b").From("t1")
sub.Select("2", "col2a", "col2b").From("t2")
cmd.Union(sub)
cmd.OrderBy("sort_col").OrderBy("col1a")
fmt.Println(cmd)
// Output:
// (SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10)
// (SELECT a FROM t1 WHERE a=10 AND B=1) UNION (SELECT a FROM t2 WHERE a=11 AND B=2) ORDER BY a LIMIT 10
// (SELECT 1 AS sort_col,col1a,col1b FROM t1) UNION (SELECT 2,col2a,col2b FROM t2) ORDER BY sort_col, col1a
}
func ExampleCmd_Join() {
cmd := NewCmd()
cmd.Reset()
cmd.Select().From("t1").LeftJoin("t2", "t3", "t4").On("t2.a=t1.a", "t3.b=t1.b", "t4.c=t1.c")
fmt.Println(cmd)
cmd.Reset()
cmd.Select().From("t1").RightJoinOn("t2", "t1.a=t2.a")
fmt.Println(cmd)
cmd.Reset()
cmd.Select().From("table1").LeftJoinOn("table2", "table1.id=table2.id").LeftJoinOn("table3", "table2.id=table3.id")
fmt.Println(cmd)
// Output:
// SELECT * FROM t1 LEFT JOIN (t2,t3,t4) ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)
// SELECT * FROM t1 RIGHT JOIN t2 ON t1.a=t2.a
// SELECT * FROM table1 LEFT JOIN table2 ON table1.id=table2.id LEFT JOIN table3 ON table2.id=table3.id
}
func ExampleCmd_Delete() {
cmd := NewCmd()
cmd.Reset()
cmd.Delete().From("somelog").Where("user='jcole'").OrderBy("timestamp_column", DESC).Limit(1)
fmt.Println(cmd)
cmd.Reset()
cmd.Delete("t1", "t2").From("t1").InnerJoinOn("t2", "t1.id=t2.id").InnerJoinOn("t3", "t2.id=t3.id")
fmt.Println(cmd)
cmd.Reset()
cmd.Delete("t1").From("t1").LeftJoinOn("t2", "t1.id=t2.id").Where("t2.id IS NULL")
fmt.Println(cmd)
cmd.Reset()
cmd.Delete("a1", "a2").From("t1 AS a1").InnerJoin("t2 AS a2").Where("a1.id=a2.id")
fmt.Println(cmd)
// Output:
// DELETE FROM somelog WHERE user='jcole' ORDER BY timestamp_column DESC LIMIT 1
// DELETE t1,t2 FROM t1 INNER JOIN t2 ON t1.id=t2.id INNER JOIN t3 ON t2.id=t3.id
// DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL
// DELETE a1,a2 FROM t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id
}
func ExampleCmd_Insert() {
cmd := NewCmd()
cmd.Reset()
cmd.Insert("tbl_name", "col1", "col2").Values()
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("tbl_name", "a", "b", "c").Values().Values().Values()
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("tbl_temp2", "fld_id").Select("tbl_temp1.fld_order_id").From("tbl_temp1").Where("tbl_temp1.fld_order_id > 100")
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("t1", "a", "b", "c").Values().Duplicate("c=c+1")
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("t1", "a", "b", "c").Values().DuplicateValues("a", "b", "c")
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("t1", "a", "b", "c").Values().Values().Duplicate("c=VALUES(a)+VALUES(b)")
fmt.Println(cmd)
cmd.Reset()
cmd.Insert("t1", "a", "b").Select("c", "d").From("t2").Union().Select("e", "f").From("t3").Duplicate("b=b+c")
fmt.Println(cmd)
sub := NewCmd()
sub.Select("c", "d").From("t2").Union().Select("e", "f").From("t3")
cmd.Reset()
cmd.Insert("t1", "a", "b").Select().SubQuery(sub, "dt").Duplicate("b=b+c")
fmt.Println(cmd)
// Output:
// INSERT INTO tbl_name (col1,col2) VALUES (?,?)
// INSERT INTO tbl_name (a,b,c) VALUES (?,?,?),(?,?,?),(?,?,?)
// INSERT INTO tbl_temp2 (fld_id) SELECT tbl_temp1.fld_order_id FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100
// INSERT INTO t1 (a,b,c) VALUES (?,?,?) ON DUPLICATE KEY UPDATE c=c+1
// INSERT INTO t1 (a,b,c) VALUES (?,?,?) ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c)
// INSERT INTO t1 (a,b,c) VALUES (?,?,?),(?,?,?) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b)
// INSERT INTO t1 (a,b) SELECT c,d FROM t2 UNION SELECT e,f FROM t3 ON DUPLICATE KEY UPDATE b=b+c
// INSERT INTO t1 (a,b) SELECT * FROM (SELECT c,d FROM t2 UNION SELECT e,f FROM t3) AS dt ON DUPLICATE KEY UPDATE b=b+c
}
func ExampleCmd_Replace() {
cmd := NewCmd()
cmd.Reset()
cmd.Replace("test", "a", "b", "c").Values()
fmt.Println(cmd)
// Output:
// REPLACE INTO test(a,b,c) VALUES (?,?,?)
}
func ExampleCmd_Update() {
cmd := NewCmd()
cmd.Reset()
cmd.Update("t1").Set("col1=col1+1")
fmt.Println(cmd)
cmd.Reset()
cmd.Update("t1").SetFields("col1")
fmt.Println(cmd)
cmd.Reset()
cmd.Update("t1").Set("col1=col1+1", "col2=col1")
fmt.Println(cmd)
cmd.Reset()
cmd.Update("t").Set("id=id+1").OrderBy("id", DESC)
fmt.Println(cmd)
cmd.Reset()
cmd.Update("items", "month").Set("items.price=month.price").Where("items.id=month.id")
fmt.Println(cmd)
// Output:
// UPDATE t1 SET col1=col1+1
// UPDATE t1 SET col1=?
// UPDATE t1 SET col1=col1+1,col2=col1
// UPDATE t SET id=id+1 ORDER BY id DESC
// UPDATE items,month SET items.price=month.price WHERE items.id=month.id
}
<file_sep>/convient_test.go
package sqlx
import "testing"
const (
t1 = "a_id_name_age"
t2 = "AIdNameAge"
)
func TestToCamel(t *testing.T) {
test := toCamel(t1)
if test != t2 {
t.Errorf("toCamel %s, %s", test, t2)
}
}
func TestToSnake(t *testing.T) {
test := toSnake(t2)
if test != t1 {
t.Errorf("toSnake %s, %s", test, t1)
}
}
<file_sep>/Makefile
.PHONY: clean
build:
docker build -t sqlx/test:0.0.1 --no-cache .
test:
docker run -d --name sqlxtest -p 3306:3306 sqlx/test:0.0.1
docker logs -f sqlxtest
clean:
- docker rm -f sqlxtest
- docker rmi sqlx/test:0.0.1<file_sep>/go.mod
module github.com/dairaga/sqlx
go 1.13
require (
github.com/go-sql-driver/mysql v1.4.1
github.com/spf13/cast v1.3.0
)
<file_sep>/cmd.go
package sqlx
import (
"fmt"
"strings"
)
func strjoin(a []string, sep string, extra ...string) string {
out := strings.Join(a, sep)
switch len(extra) {
case 1:
return extra[0] + out
case 2:
return extra[0] + out + extra[1]
default:
return out
}
}
// JoinType ...
type JoinType uint8
// Join type
const (
InnerJoin JoinType = 1 + iota
LeftJoin
RightJoin
)
func (t JoinType) String() string {
switch t {
case InnerJoin:
return " INNER JOIN "
case RightJoin:
return " RIGHT JOIN "
case LeftJoin:
return " LEFT JOIN "
default:
return " LEFT JOIN "
}
}
// Direction ...
type Direction uint8
// Sort direction
const (
ASC Direction = 1 + iota
DESC
)
func (d Direction) String() string {
switch d {
case ASC:
return " ASC"
case DESC:
return " DESC"
default:
return ""
}
}
// Cmd ...
type Cmd struct {
orderby bool
from bool
fields int
values bool
sb *strings.Builder
}
// NewCmd returns a mysql command builder.
func NewCmd() *Cmd {
return &Cmd{
orderby: false,
from: false,
fields: 0,
values: false,
sb: new(strings.Builder),
}
}
// Reset ...
func (c *Cmd) Reset() *Cmd {
c.orderby = false
c.from = false
c.fields = 0
c.values = false
c.sb.Reset()
return c
}
// Select build select part sql.
func (c *Cmd) Select(fields ...string) *Cmd {
if c.sb.Len() > 0 {
c.sb.WriteString(" SELECT ")
} else {
c.sb.WriteString("SELECT ")
}
if len(fields) > 0 {
c.sb.WriteString(strjoin(fields, ","))
} else {
c.sb.WriteString("*")
}
c.from = false
c.orderby = false
return c
}
// Into ...
func (c *Cmd) Into(table string) *Cmd {
c.sb.WriteString(" INTO ")
c.sb.WriteString(table)
return c
}
// From ...
func (c *Cmd) From(table ...string) *Cmd {
if len(table) <= 0 {
panic("at least one table")
}
if !c.from {
c.sb.WriteString(" FROM ")
c.from = true
} else {
c.sb.WriteByte(',')
}
c.sb.WriteString(strjoin(table, ","))
return c
}
// SubQuery ...
func (c *Cmd) SubQuery(sub *Cmd, as ...string) *Cmd {
out := "(" + sub.String() + ")"
if len(as) > 0 {
out = out + " AS " + as[0]
}
return c.From(out)
}
// Union ...
func (c *Cmd) Union(other ...*Cmd) *Cmd {
if len(other) > 0 {
out := c.String()
c.Reset()
c.Parentheses(out).sb.WriteString(" UNION ")
c.Parentheses(other[0].String())
} else {
c.sb.WriteString(" UNION")
}
return c
}
// Join ...
func (c *Cmd) Join(t JoinType, table ...string) *Cmd {
size := len(table)
if size < 0 {
panic("at least one table")
}
c.sb.WriteString(t.String())
if size == 1 {
c.sb.WriteString(table[0])
} else {
c.sb.WriteString(strjoin(table, ",", "(", ")"))
}
return c
}
// InnerJoin ...
func (c *Cmd) InnerJoin(table ...string) *Cmd {
return c.Join(InnerJoin, table...)
}
// LeftJoin ...
func (c *Cmd) LeftJoin(table ...string) *Cmd {
return c.Join(LeftJoin, table...)
}
// RightJoin ...
func (c *Cmd) RightJoin(table ...string) *Cmd {
return c.Join(RightJoin, table...)
}
// On ...
func (c *Cmd) On(condition ...string) *Cmd {
size := len(condition)
if size < 0 {
panic("at least one condition")
}
c.sb.WriteString(" ON ")
if size == 1 {
c.sb.WriteString(condition[0])
} else {
c.sb.WriteString(strjoin(condition, " AND ", "(", ")"))
}
return c
}
// JoinOn ...
func (c *Cmd) JoinOn(t JoinType, table string, condition string) *Cmd {
return c.Join(t, table).On(condition)
}
// LeftJoinOn ...
func (c *Cmd) LeftJoinOn(table string, condition string) *Cmd {
return c.JoinOn(LeftJoin, table, condition)
}
// RightJoinOn ...
func (c *Cmd) RightJoinOn(table string, condition string) *Cmd {
return c.JoinOn(RightJoin, table, condition)
}
// InnerJoinOn ...
func (c *Cmd) InnerJoinOn(table string, condition string) *Cmd {
return c.JoinOn(InnerJoin, table, condition)
}
// Where ...
func (c *Cmd) Where(condition string) *Cmd {
c.sb.WriteString(" WHERE ")
c.sb.WriteString(condition)
return c
}
// And ...
func (c *Cmd) And(condition ...string) *Cmd {
if len(condition) <= 0 {
panic("at least one condition")
}
c.sb.WriteString(strjoin(condition, " AND ", " AND "))
return c
}
// Or ...
func (c *Cmd) Or(condition ...string) *Cmd {
if len(condition) <= 0 {
panic("at least one condition")
}
c.sb.WriteString(strjoin(condition, " OR ", " OR "))
return c
}
// WhereAnd ...
func (c *Cmd) WhereAnd(condition string, others ...string) *Cmd {
c.Where(condition)
if len(others) > 0 {
c.And(others...)
}
return c
}
// WhereOr ...
func (c *Cmd) WhereOr(condition string, others ...string) *Cmd {
c.Where(condition)
if len(others) > 0 {
c.Or(others...)
}
return c
}
// Insert ...
func (c *Cmd) Insert(table string, fields ...string) *Cmd {
c.sb.WriteString("INSERT")
c.Into(table)
c.fields = len(fields)
if c.fields > 0 {
c.sb.WriteString(strjoin(fields, ",", " (", ")"))
}
c.values = false
return c
}
// InsertValues ...
func (c *Cmd) InsertValues(table string, fields ...string) *Cmd {
return c.Insert(table, fields...).Values()
}
// Values ...
func (c *Cmd) Values(assignments ...string) *Cmd {
if !c.values {
c.sb.WriteString(" VALUES ")
c.values = true
} else {
c.sb.WriteString(",")
}
if len(assignments) <= 0 {
c.sb.WriteByte('(')
c.sb.WriteString(strings.Repeat("?,", c.fields-1))
c.sb.WriteString("?)")
} else {
c.sb.WriteString(strjoin(assignments, ",", "(", ")"))
}
return c
}
// Duplicate ...
func (c *Cmd) Duplicate(assignments ...string) *Cmd {
c.sb.WriteString(" ON DUPLICATE KEY UPDATE ")
c.sb.WriteString(strjoin(assignments, ","))
return c
}
// DuplicateValues ...
func (c *Cmd) DuplicateValues(values ...string) *Cmd {
out := make([]string, len(values))
for i, x := range values {
out[i] = fmt.Sprintf("%s=VALUES(%s)", x, x)
}
return c.Duplicate(out...)
}
// SetFields ...
func (c *Cmd) SetFields(fields ...string) *Cmd {
out := make([]string, len(fields))
for i, f := range fields {
out[i] = fmt.Sprintf("%s=?", f)
}
return c.Set(out...)
}
// Set ...
func (c *Cmd) Set(assignments ...string) *Cmd {
c.sb.WriteString(" SET")
c.sb.WriteString(strjoin(assignments, ",", " "))
return c
}
// Update ...
func (c *Cmd) Update(table string, others ...string) *Cmd {
c.sb.WriteString("UPDATE ")
c.sb.WriteString(table)
if len(others) > 0 {
c.sb.WriteString(strjoin(others, ",", ","))
}
return c
}
// Delete ...
func (c *Cmd) Delete(as ...string) *Cmd {
c.sb.WriteString("DELETE")
if len(as) > 0 {
c.sb.WriteString(strjoin(as, ",", " "))
}
return c
}
// DeleteFrom ...
func (c *Cmd) DeleteFrom(table ...string) *Cmd {
return c.Delete().From(table...)
}
// Replace ...
func (c *Cmd) Replace(table string, fields ...string) *Cmd {
c.sb.WriteString("REPLACE")
c.Into(table)
c.fields = len(fields)
c.values = false
if c.fields > 0 {
c.sb.WriteString(strjoin(fields, ",", "(", ")"))
}
return c
}
// Parentheses ...
func (c *Cmd) Parentheses(any string) *Cmd {
c.sb.WriteString("(")
c.sb.WriteString(any)
c.sb.WriteString(")")
return c
}
// Limit ...
func (c *Cmd) Limit(count int, offset ...int) *Cmd {
if len(offset) > 0 {
c.sb.WriteString(fmt.Sprintf(" LIMIT %d,%d", offset[0], count))
} else {
c.sb.WriteString(fmt.Sprintf(" LIMIT %d", count))
}
return c
}
// GroupBy ...
func (c *Cmd) GroupBy(fields ...string) *Cmd {
c.sb.WriteString(" GROUP BY ")
c.sb.WriteString(strjoin(fields, ","))
return c
}
// OrderBy ...
func (c *Cmd) OrderBy(field string, direction ...Direction) *Cmd {
dir := Direction(0)
if len(direction) > 0 {
dir = direction[0]
}
if !c.orderby {
c.sb.WriteString(" ORDER BY ")
c.orderby = true
} else {
c.sb.WriteString(", ")
}
c.sb.WriteString(field)
c.sb.WriteString(dir.String())
return c
}
// Having ...
func (c *Cmd) Having(condition string) *Cmd {
c.sb.WriteString(" HAVING ")
c.sb.WriteString(condition)
return c
}
// Raw appends string to command
func (c *Cmd) Raw(any string) *Cmd {
c.sb.WriteString(any)
return c
}
func (c *Cmd) String() string {
return c.sb.String()
}
// SQL ...
func (c *Cmd) SQL(sqlcmds ...string) string {
if len(sqlcmds) > 0 {
c.Reset()
c.Raw(strings.Join(sqlcmds, ";"))
}
return c.String()
}
<file_sep>/db.go
package sqlx
import (
"context"
"database/sql"
"errors"
"os"
)
// DB ...
type DB struct {
*sqlxobj
}
// WrapDB ...
func WrapDB(db *sql.DB, err error) (*DB, error) {
if err != nil {
return nil, err
}
return &DB{&sqlxobj{db, NewCmd(), nil}}, nil
}
var (
_driver string
_dsn string
)
// Close ...
func (db *DB) Close() error {
return db.sqlxobj.x.(*sql.DB).Close()
}
// Begin ...
func (db *DB) Begin() (*Tx, error) {
return WrapTx(db.sqlxobj.x.(*sql.DB).Begin())
}
// BeginTx ...
func (db *DB) BeginTx(ctx context.Context, ops *sql.TxOptions) (*Tx, error) {
return WrapTx(db.sqlxobj.x.(*sql.DB).BeginTx(ctx, ops))
}
// ----------------------------------------------------------------------------
// Open ....
func Open() (*DB, error) {
if _driver == "" || _dsn == "" {
_driver, _ = os.LookupEnv("DB_DRIVER")
if _driver == "" {
return nil, errors.New("can not find Database Driver")
}
_dsn, _ = os.LookupEnv("DB_DSN")
if _dsn == "" {
return nil, errors.New("can not find Database Data Source Name")
}
}
return OpenDB(_driver, _dsn)
}
// OpenDB ...
func OpenDB(driver, dsn string) (*DB, error) {
return WrapDB(sql.Open(driver, dsn))
}
<file_sep>/convert_test.go
package sqlx
import (
"database/sql"
"testing"
"time"
)
var (
now = time.Now()
str = "ABC"
nostr = "1"
cases = []interface{}{
int(1),
uint(1),
int8(1),
uint8(1),
int16(1),
uint16(1),
int32(1),
uint32(1),
int64(1),
uint64(1),
float32(1),
float64(1),
true,
str,
nostr,
now,
sql.RawBytes([]byte(str)),
sql.RawBytes(nil),
sql.NullBool{Valid: true, Bool: false},
sql.NullBool{Valid: false, Bool: false},
sql.NullFloat64{Valid: true, Float64: 1},
sql.NullFloat64{Valid: false, Float64: 0},
sql.NullInt64{Valid: true, Int64: 1},
sql.NullInt64{Valid: false, Int64: 0},
sql.NullString{Valid: true, String: str},
sql.NullString{Valid: true, String: nostr},
sql.NullString{Valid: false, String: ""},
}
)
func TestToInt(t *testing.T) {
ans := []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toInt(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToUint(t *testing.T) {
ans := []uint{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toUint(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToInt8(t *testing.T) {
ans := []int8{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toInt8(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToUint8(t *testing.T) {
ans := []uint8{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toUint8(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToInt16(t *testing.T) {
ans := []int16{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toInt16(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToUint16(t *testing.T) {
ans := []uint16{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toUint16(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToInt32(t *testing.T) {
ans := []int32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toInt32(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToUint32(t *testing.T) {
ans := []uint32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toUint32(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToInt64(t *testing.T) {
ans := []int64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toInt64(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToUint64(t *testing.T) {
ans := []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toUint64(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %d, but %d", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToFloat32(t *testing.T) {
ans := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toFloat32(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %v, but %v", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToFloat64(t *testing.T) {
ans := []float64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1, 100, 100, 100, 0, 100, 1, 100, 1, 100, 100, 1, 100}
for i, x := range cases {
a := toFloat64(x, 100)
if a != ans[i] {
t.Errorf("%v toInt should be %v, but %v", x, ans[i], a)
}
//t.Logf("%d: %v => %d", i, x, a)
//fmt.Printf("%d,", a)
}
}
func TestToString(t *testing.T) {
def := "xyz"
ans := []string{"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "true", str, nostr, now.String(), str, "", "false", def, "1", def, "1", def, str, nostr, def}
for i, x := range cases {
a := toString(x, def)
if a != ans[i] {
t.Errorf("%v toInt should be %v, but %v", x, ans[i], a)
}
//t.Logf("%d: %v => %v", i, x, a)
//fmt.Printf("%q,", a)
}
}
func TestToBool(t *testing.T) {
def := false
ans := []bool{true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, false, false, false, false, true, false, true, false, false, true, false}
for i, x := range cases {
a := toBool(x, def)
if a != ans[i] {
t.Errorf("%v toInt should be %v, but %v", x, ans[i], a)
}
//t.Logf("%d: %v => %v", i, x, a)
//fmt.Printf("%v,", a)
}
}
func TestToTime(t *testing.T) {
def := time.Now()
d1 := time.Unix(1, 0)
ans := []time.Time{
d1, d1, //int, uint,
def, def, def, def, // int8, uint8, int16, uint16
d1, d1, d1, d1, // int32, uint32, int64, uint64
def, def, // float32, float64
def, def, def, // true, string, string
now,
def, def, // sql.RawBytes, sql.RawBytes
def, def, def, def, // sql.NullBool, sql.NullBool, sql.NullFloat64, sql.NullFloat64
d1, def, // sql.NullInt64, sql.NullInt64
def, def, def, // sql.NullString, sql.NullString, sql.NullString
}
for i, x := range cases {
a := toTime(x, def)
if a != ans[i] {
t.Errorf("%v toInt should be %v, but %v", x, ans[i], a)
}
//t.Logf("%d: %v (%T) => %v", i, x, x, a)
//fmt.Printf("%v,", a)
}
}
<file_sep>/sqlx.go
package sqlx
import (
"context"
"database/sql"
"errors"
"reflect"
"strings"
"time"
)
var (
timeType = reflect.TypeOf(time.Time{})
stringType = reflect.TypeOf("")
boolType = reflect.TypeOf(false)
int64Type = reflect.TypeOf(int64(0))
float64Type = reflect.TypeOf(float64(0.0))
rawBytesType = reflect.TypeOf(sql.RawBytes{})
bytesType = reflect.TypeOf([]byte{})
nullStringType = reflect.TypeOf(sql.NullString{})
nullBoolType = reflect.TypeOf(sql.NullBool{})
nullInt64Type = reflect.TypeOf(sql.NullInt64{})
nullFloat64Type = reflect.TypeOf(sql.NullFloat64{})
)
type sqlobj interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
}
type sqlxobj struct {
x sqlobj
cmd *Cmd
args []interface{}
}
func (z *sqlxobj) Args(x ...interface{}) *sqlxobj {
if len(x) > 0 {
z.args = append(z.args, x...)
}
return z
}
// Reset ...
func (z *sqlxobj) Reset() *sqlxobj {
z.args = nil
z.cmd.Reset()
return z
}
// Select build select part sql.
func (z *sqlxobj) Select(fields ...string) *sqlxobj {
z.cmd.Select(fields...)
return z
}
// Into ...
func (z *sqlxobj) Into(table string) *sqlxobj {
z.cmd.Into(table)
return z
}
// From ...
func (z *sqlxobj) From(table ...string) *sqlxobj {
z.cmd.From(table...)
return z
}
// SubQuery ...
func (z *sqlxobj) SubQuery(sub *Cmd, as ...string) *sqlxobj {
z.cmd.SubQuery(sub, as...)
return z
}
// Union ...
func (z *sqlxobj) Union(other ...*Cmd) *sqlxobj {
z.cmd.Union(other...)
return z
}
// Join ...
func (z *sqlxobj) Join(t JoinType, table ...string) *sqlxobj {
z.cmd.Join(t, table...)
return z
}
// InnerJoin ...
func (z *sqlxobj) InnerJoin(table ...string) *sqlxobj {
z.cmd.InnerJoin(table...)
return z
}
// LeftJoin ...
func (z *sqlxobj) LeftJoin(table ...string) *sqlxobj {
z.cmd.LeftJoin(table...)
return z
}
// RightJoin ...
func (z *sqlxobj) RightJoin(table ...string) *sqlxobj {
z.cmd.RightJoin(table...)
return z
}
// On ...
func (z *sqlxobj) On(condition ...string) *sqlxobj {
z.cmd.On(condition...)
return z
}
// JoinOn ...
func (z *sqlxobj) JoinOn(t JoinType, table string, condition string) *sqlxobj {
z.cmd.JoinOn(t, table, condition)
return z
}
// LeftJoinOn ...
func (z *sqlxobj) LeftJoinOn(table string, condition string) *sqlxobj {
z.cmd.LeftJoinOn(table, condition)
return z
}
// RightJoinOn ...
func (z *sqlxobj) RightJoinOn(table string, condition string) *sqlxobj {
z.cmd.RightJoinOn(table, condition)
return z
}
// InnerJoinOn ...
func (z *sqlxobj) InnerJoinOn(table string, condition string) *sqlxobj {
z.cmd.InnerJoinOn(table, condition)
return z
}
// Where ...
func (z *sqlxobj) Where(condition string) *sqlxobj {
z.cmd.Where(condition)
return z
}
// And ...
func (z *sqlxobj) And(condition ...string) *sqlxobj {
z.cmd.And(condition...)
return z
}
// Or ...
func (z *sqlxobj) Or(condition ...string) *sqlxobj {
z.cmd.Or(condition...)
return z
}
// WhereAnd ...
func (z *sqlxobj) WhereAnd(condition string, others ...string) *sqlxobj {
z.cmd.WhereAnd(condition, others...)
return z
}
// WhereOr ...
func (z *sqlxobj) WhereOr(condition string, others ...string) *sqlxobj {
z.cmd.WhereOr(condition, others...)
return z
}
// Insert ...
func (z *sqlxobj) Insert(table string, fields ...string) *sqlxobj {
z.cmd.Insert(table, fields...)
return z
}
func (z *sqlxobj) InsertValues(table string, fields ...string) *sqlxobj {
z.cmd.InsertValues(table, fields...)
return z
}
// Values ...
func (z *sqlxobj) Values(assignments ...string) *sqlxobj {
z.cmd.Values(assignments...)
return z
}
// Duplicate ...
func (z *sqlxobj) Duplicate(assignments ...string) *sqlxobj {
z.cmd.Duplicate(assignments...)
return z
}
// DuplicateValues ...
func (z *sqlxobj) DuplicateValues(values ...string) *sqlxobj {
z.cmd.DuplicateValues(values...)
return z
}
// SetFields ...
func (z *sqlxobj) SetFields(fields ...string) *sqlxobj {
z.cmd.SetFields(fields...)
return z
}
// Set ...
func (z *sqlxobj) Set(assignments ...string) *sqlxobj {
z.cmd.Set(assignments...)
return z
}
// Update ...
func (z *sqlxobj) Update(table string, others ...string) *sqlxobj {
z.cmd.Update(table, others...)
return z
}
// Delete ...
func (z *sqlxobj) Delete(as ...string) *sqlxobj {
z.cmd.Delete(as...)
return z
}
func (z *sqlxobj) DeleteFrom(table ...string) *sqlxobj {
z.cmd.DeleteFrom(table...)
return z
}
// Replace ...
func (z *sqlxobj) Replace(table string, fields ...string) *sqlxobj {
z.cmd.Replace(table, fields...)
return z
}
// Parentheses ...
func (z *sqlxobj) Parentheses(any string) *sqlxobj {
z.cmd.Parentheses(any)
return z
}
// Limit ...
func (z *sqlxobj) Limit(count int, offset ...int) *sqlxobj {
z.cmd.Limit(count, offset...)
return z
}
// GroupBy ...
func (z *sqlxobj) GroupBy(fields ...string) *sqlxobj {
z.cmd.GroupBy(fields...)
return z
}
// OrderBy ...
func (z *sqlxobj) OrderBy(field string, direction ...Direction) *sqlxobj {
z.cmd.OrderBy(field, direction...)
return z
}
// Having ...
func (z *sqlxobj) Having(condition string) *sqlxobj {
z.cmd.Having(condition)
return z
}
// Raw appends string to command
func (z *sqlxobj) Raw(any string) *sqlxobj {
z.cmd.Raw(any)
return z
}
// SQL ...
func (z *sqlxobj) SQL(sqlcmds ...string) string {
return z.cmd.SQL(sqlcmds...)
}
// ExecContext ...
func (z *sqlxobj) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
if len(args) > 0 {
return z.x.ExecContext(ctx, z.SQL(), args...)
}
return z.x.ExecContext(ctx, z.SQL(), z.args...)
}
// Exec ...
func (z *sqlxobj) Exec(args ...interface{}) (sql.Result, error) {
return z.ExecContext(context.Background(), args...)
}
func (z *sqlxobj) CountContext(ctx context.Context, args ...interface{}) (int, error) {
newSQL := z.cmd.SQL()
pos := strings.Index(newSQL, "FROM")
if pos <= 0 {
return 0, errors.New("sql command error")
}
newSQL = "SELECT count(*) as cc " + newSQL[pos:]
oldCmd := z.cmd
defer func() {
z.cmd = oldCmd
}()
newCmd := NewCmd()
newCmd.Raw(newSQL)
z.cmd = newCmd
row := z.QueryRowContext(ctx, args...)
if row.Err() != nil {
return 0, row.Err()
}
return row.GetInt("cc", 0), nil
}
func (z *sqlxobj) Count(args ...interface{}) (int, error) {
return z.CountContext(context.Background(), args...)
}
// QueryContext ...
func (z *sqlxobj) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) {
if len(args) > 0 {
return WrapRows(z.x.QueryContext(ctx, z.SQL(), args...))
}
return WrapRows(z.x.QueryContext(ctx, z.SQL(), z.args...))
}
// Query ...
func (z *sqlxobj) Query(args ...interface{}) (*Rows, error) {
return z.QueryContext(context.Background(), args...)
}
// AllContext ...
func (z *sqlxobj) AllContext(ctx context.Context, args ...interface{}) ([]interface{}, error) {
rows, err := z.QueryContext(ctx, args...)
if err != nil {
return nil, err
}
return rows.All()
}
// All ...
func (z *sqlxobj) All(args ...interface{}) ([]interface{}, error) {
return z.AllContext(context.Background(), args...)
}
// UnmarshalAllContext ...
func (z *sqlxobj) UnmarshalAllContext(ctx context.Context, x interface{}, args ...interface{}) error {
rows, err := z.QueryContext(ctx, args...)
if err != nil {
return err
}
return rows.UnmarshalAll(x)
}
// UnmarshalAll ...
func (z *sqlxobj) UnmarshalAll(x interface{}, args ...interface{}) error {
return z.UnmarshalAllContext(context.Background(), x, args...)
}
// QueryRowContext ...
func (z *sqlxobj) QueryRowContext(ctx context.Context, args ...interface{}) *Row {
return WrapRow(z.QueryContext(ctx, args...))
}
// QueryRow ...
func (z *sqlxobj) QueryRow(args ...interface{}) *Row {
return z.QueryRowContext(context.Background(), args...)
}
// DataContext ...
func (z *sqlxobj) DataContext(ctx context.Context, args ...interface{}) (interface{}, error) {
return z.QueryRowContext(ctx, args...).Data()
}
// Data ...
func (z *sqlxobj) Data(args ...interface{}) (interface{}, error) {
return z.DataContext(context.Background(), args...)
}
// UnmarshalContext ...
func (z *sqlxobj) UnmarshalContext(ctx context.Context, x interface{}, args ...interface{}) error {
return z.QueryRowContext(ctx, args...).Unmarshal(x)
}
// Unmarshal ...
func (z *sqlxobj) Unmarshal(x interface{}, args ...interface{}) error {
return z.UnmarshalContext(context.Background(), x, args...)
}
// PrepareContext ...
func (z *sqlxobj) PrepareContext(ctx context.Context) (*Stmt, error) {
return WrapStmt(z.x.PrepareContext(ctx, z.SQL()))
}
// Prepare ...
func (z *sqlxobj) Prepare() (*Stmt, error) {
return z.PrepareContext(context.Background())
}
<file_sep>/sqlx_test.go
package sqlx_test
import (
"fmt"
"reflect"
"time"
"github.com/dairaga/sqlx"
)
const dsnFmt = "%s:%s@tcp(%s:%d)/%s?%s=%s&%s=%s"
var (
dsn = fmt.Sprintf(dsnFmt, "test", "test", "127.0.0.1", 3306, "mytest", "charset", "utf8mb4,utf8", "parseTime", "true")
)
var (
timeType = reflect.TypeOf(time.Time{})
)
const (
test1Row = `{"c01":"AQ==","c01_1":"AQ==","c02_s":-2,"c02_u":2,"c03":1,"c04_s":-4,"c04_u":4,"c05_s":-5,"c05_u":5,"c06_s":-6,"c06_u":6,"c07_s":-7,"c07_u":7,"c08_s":-8,"c08_u":8,"c09_s":-9,"c09_u":9,"c10_s":-10,"c10_u":10,"c11":"2019-01-01T00:00:00Z","c12":"MTIzOjA0OjA1","c13":2019,"c14":"2014-09-23T10:01:02Z","c15":"2014-09-23T10:01:02Z","c16":"C16","c17":"C17","c18":"QzE4AAAAAAAAAA==","c19":"QzE5","c20":"QzIw","c21":"C21","c22":"QzIy","c23":"C23","c24":"QzI0","c25":"C25","c26":"QzI2","c27":"C27","c28":"a","c29":"b"}`
test1Rows = `[{"c01":"AQ==","c01_1":"AQ==","c02_s":-2,"c02_u":2,"c03":1,"c04_s":-4,"c04_u":4,"c05_s":-5,"c05_u":5,"c06_s":-6,"c06_u":6,"c07_s":-7,"c07_u":7,"c08_s":-8,"c08_u":8,"c09_s":-9,"c09_u":9,"c10_s":-10,"c10_u":10,"c11":"2019-01-01T00:00:00Z","c12":"MTIzOjA0OjA1","c13":2019,"c14":"2014-09-23T10:01:02Z","c15":"2014-09-23T10:01:02Z","c16":"C16","c17":"C17","c18":"QzE4AAAAAAAAAA==","c19":"QzE5","c20":"QzIw","c21":"C21","c22":"QzIy","c23":"C23","c24":"QzI0","c25":"C25","c26":"QzI2","c27":"C27","c28":"a","c29":"b"}]`
test2Row = `{"c01":null,"c01_1":null,"c02_s":0,"c02_u":0,"c03":0,"c04_s":0,"c04_u":0,"c05_s":0,"c05_u":0,"c06_s":0,"c06_u":0,"c07_s":0,"c07_u":0,"c08_s":0,"c08_u":0,"c09_s":0,"c09_u":0,"c10_s":0,"c10_u":0,"c11":"0001-01-01T00:00:00Z","c12":null,"c13":0,"c14":"0001-01-01T00:00:00Z","c15":"2014-09-23T10:01:02Z","c16":"","c17":"","c18":null,"c19":null,"c20":null,"c21":"","c22":null,"c23":"","c24":null,"c25":"","c26":null,"c27":"","c28":"","c29":""}`
test2Rows = `[{"c01":null,"c01_1":null,"c02_s":0,"c02_u":0,"c03":0,"c04_s":0,"c04_u":0,"c05_s":0,"c05_u":0,"c06_s":0,"c06_u":0,"c07_s":0,"c07_u":0,"c08_s":0,"c08_u":0,"c09_s":0,"c09_u":0,"c10_s":0,"c10_u":0,"c11":"0001-01-01T00:00:00Z","c12":null,"c13":0,"c14":"0001-01-01T00:00:00Z","c15":"2014-09-23T10:01:02Z","c16":"","c17":"","c18":null,"c19":null,"c20":null,"c21":"","c22":null,"c23":"","c24":null,"c25":"","c26":null,"c27":"","c28":"","c29":""}]`
s1 = `{"id":6,"name":"C16","birthday":"2014-09-23T10:01:02Z"}`
s1Slice = `[{"id":6,"name":"C16","birthday":"2014-09-23T10:01:02Z"}]`
s2 = `{"id":0,"name":"","birthday":"0001-01-01T00:00:00Z"}`
s2Slice = `[{"id":0,"name":"","birthday":"0001-01-01T00:00:00Z"}]`
)
type TestStruct1 struct {
ID int64 `sqlx:"c06_u" json:"id"`
Name string `sqlx:"c16" json:"name"`
Birthday time.Time `sqlx:"c14" json:"birthday"`
}
func OpenDB(d, dsn string) (*sqlx.DB, error) {
return sqlx.OpenDB("mysql", dsn)
}
<file_sep>/db_test.go
package sqlx_test
import (
"encoding/json"
"testing"
)
func TestDBXData(t *testing.T) {
db, err := OpenDB("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
d1, err := db.Reset().Select().From("test1").Data()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test1Row {
t.Errorf("json string should be \n%s\n but \n%s", test1Row, string(tmp))
}
d2, err := db.Reset().Select().From("test2").Data()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d2)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test2Row {
t.Errorf("json string should be \n%s\n but \n%s", test2Row, string(tmp))
}
}
func TestDBXUnmarshal(t *testing.T) {
db, err := OpenDB("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
d1 := &TestStruct1{}
err = db.Reset().Select().From("test1").Unmarshal(d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s1 {
t.Errorf("json string should be \n%s\n but \n%s", s1, string(tmp))
}
err = db.Reset().Select().From("test2").Unmarshal(d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s2 {
t.Errorf("json string should be \n%s\n but \n%s", s2, string(tmp))
}
}
func TestDBXAll(t *testing.T) {
db, err := OpenDB("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
all, err := db.Reset().Select().From("test1").All()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(all)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test1Rows {
t.Errorf("json string should be \n%s\n but \n%s", test1Rows, string(tmp))
}
all, err = db.Reset().Select().From("test2").All()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(all)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test2Rows {
t.Errorf("json string should be \n%s\n but \n%s", test2Rows, string(tmp))
}
}
func TestDBXUnmarshalAll(t *testing.T) {
db, err := OpenDB("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
d1 := []TestStruct1{}
err = db.Reset().Select().From("test1").UnmarshalAll(&d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s1Slice {
t.Errorf("json string should be \n%s\n but \n%s", s1Slice, string(tmp))
}
err = db.Reset().Select().From("test2").UnmarshalAll(&d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s2Slice {
t.Errorf("json string should be \n%s\n but \n%s", s2Slice, string(tmp))
}
}
<file_sep>/rows.go
package sqlx
import (
"database/sql"
"fmt"
"reflect"
"time"
)
var (
zeroTime = time.Time{}
)
// Rows ...
type Rows struct {
x *sql.Rows
s reflect.Type
names []string
types []reflect.Type
r *Row
}
// WrapRows ...
func WrapRows(rows *sql.Rows, err error) (*Rows, error) {
if err != nil {
return nil, err
}
return toRows(rows)
}
func toRows(rows *sql.Rows) (*Rows, error) {
cols, err := rows.ColumnTypes()
if err != nil {
return nil, err
}
size := len(cols)
rs := &Rows{
x: rows,
names: make([]string, size),
types: make([]reflect.Type, size),
}
fields := make([]reflect.StructField, size)
for i, col := range cols {
rs.names[i] = col.Name()
f := reflect.StructField{
Name: toCamel(rs.names[i]),
Tag: reflect.StructTag(fmt.Sprintf(`json:"%s"`, rs.names[i])),
}
switch col.DatabaseTypeName() {
case "DECIMAL":
if null, _ := col.Nullable(); null {
rs.types[i] = nullFloat64Type
} else {
rs.types[i] = float64Type
}
f.Type = float64Type
case "TEXT", "VARCHAR", "CHAR", "NCHAR", "NVARCHAR":
if null, _ := col.Nullable(); null {
rs.types[i] = nullStringType
} else {
rs.types[i] = stringType
}
f.Type = stringType
case "DATE", "DATETIME", "TIMESTAMP":
rs.types[i] = col.ScanType()
f.Type = timeType
default:
t := col.ScanType()
rs.types[i] = t
if t.AssignableTo(nullBoolType) {
f.Type = boolType
} else if t.AssignableTo(nullFloat64Type) {
f.Type = float64Type
} else if t.AssignableTo(nullInt64Type) {
f.Type = int64Type
} else if t.AssignableTo(nullStringType) {
f.Type = stringType
} else if t.AssignableTo(rawBytesType) {
f.Type = bytesType
} else {
f.Type = t
}
}
fields[i] = f
}
rs.s = reflect.StructOf(fields)
return rs, nil
}
// Names ...
func (rs *Rows) Names() []string {
return rs.names
}
// Data ...
func (rs *Rows) Data() (interface{}, error) {
if rs.x.Err() != nil {
return nil, rs.x.Err()
}
return rs.r.Data()
}
// Unmarshal ...
func (rs *Rows) Unmarshal(x interface{}) error {
if rs.x.Err() != nil {
return rs.x.Err()
}
return rs.r.Unmarshal(x)
}
// Next ...
func (rs *Rows) Next() bool {
//if rs.lastErr != nil {
// return false
//}
if !rs.x.Next() {
return false
}
rs.r = &Row{rows: rs}
if err := rs.r.scan(); err != nil {
return false
}
return true
}
// Close ...
func (rs *Rows) Close() error {
return rs.x.Close()
}
// Err returns error of Rows.
func (rs *Rows) Err() error {
return rs.x.Err()
}
// AllRow ...
func (rs *Rows) AllRow() ([]*Row, error) {
defer rs.Close()
var ret []*Row
for rs.Next() {
ret = append(ret, rs.r)
}
return ret, rs.Err()
}
// All ...
func (rs *Rows) All() ([]interface{}, error) {
tmp, err := rs.AllRow()
if err != nil {
return nil, err
}
var ret []interface{}
for _, r := range tmp {
s, err := r.Data()
if err != nil {
return nil, err
}
ret = append(ret, s)
}
return ret, nil
}
// UnmarshalAll ...
func (rs *Rows) UnmarshalAll(x interface{}) error {
defer rs.Close()
rv := reflect.ValueOf(x)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return fmt.Errorf("x must be Ptr of Slice")
}
rv = rv.Elem()
if rv.Kind() != reflect.Slice {
return fmt.Errorf("x must be Ptr of Slice")
}
newV := reflect.MakeSlice(rv.Type(), 0, 0)
needElm := true
elmType := rv.Type().Elem()
if elmType.Kind() == reflect.Ptr {
elmType = elmType.Elem()
needElm = false
}
for rs.Next() {
d := reflect.New(elmType)
if err := rs.r.Unmarshal(d.Interface()); err != nil {
return err
}
if needElm {
newV = reflect.Append(newV, d.Elem())
} else {
newV = reflect.Append(newV, d)
}
}
rv.Set(newV)
return nil
}
// Get ...
func (rs *Rows) Get(name string) interface{} {
return rs.r.Get(name)
}
// GetInt ...
func (rs *Rows) GetInt(name string, def ...int) int {
return rs.r.GetInt(name, def...)
}
// GetUint ...
func (rs *Rows) GetUint(name string, def ...uint) uint {
return rs.r.GetUint(name, def...)
}
// GetInt8 ...
func (rs *Rows) GetInt8(name string, def ...int8) int8 {
return rs.r.GetInt8(name, def...)
}
// GetUint8 ...
func (rs *Rows) GetUint8(name string, def ...uint8) uint8 {
return rs.r.GetUint8(name, def...)
}
// GetInt16 ...
func (rs *Rows) GetInt16(name string, def ...int16) int16 {
return rs.r.GetInt16(name, def...)
}
// GetUint16 ...
func (rs *Rows) GetUint16(name string, def ...uint16) uint16 {
return rs.r.GetUint16(name, def...)
}
// GetInt32 ...
func (rs *Rows) GetInt32(name string, def ...int32) int32 {
return rs.r.GetInt32(name, def...)
}
// GetUint32 ...
func (rs *Rows) GetUint32(name string, def ...uint32) uint32 {
return rs.r.GetUint32(name, def...)
}
// GetInt64 ...
func (rs *Rows) GetInt64(name string, def ...int64) int64 {
return rs.r.GetInt64(name, def...)
}
// GetUint64 ...
func (rs *Rows) GetUint64(name string, def ...uint64) uint64 {
return rs.r.GetUint64(name, def...)
}
// GetFloat32 ...
func (rs *Rows) GetFloat32(name string, def ...float32) float32 {
return rs.r.GetFloat32(name, def...)
}
// GetFloat64 ...
func (rs *Rows) GetFloat64(name string, def ...float64) float64 {
return rs.r.GetFloat64(name, def...)
}
// GetString ...
func (rs *Rows) GetString(name string, def ...string) string {
return rs.r.GetString(name, def...)
}
// GetTime ...
func (rs *Rows) GetTime(name string, def ...time.Time) time.Time {
return rs.r.GetTime(name, def...)
}
// GetBool ...
func (rs *Rows) GetBool(name string, def ...bool) bool {
return rs.r.GetBool(name, def...)
}
// GetBytes ...
func (rs *Rows) GetBytes(name string, def ...[]byte) []byte {
return rs.r.GetBytes(name, def...)
}
// GetDuration ...
func (rs *Rows) GetDuration(name string, def ...time.Duration) time.Duration {
return rs.r.GetDuration(name, def...)
}
// ----------------------------------------------------------------------------
// Row ...
type Row struct {
rows *Rows
err error
data map[string]interface{}
s interface{}
}
// WrapRow ...
func WrapRow(rs *Rows, err error) *Row {
r := &Row{rows: rs, err: err}
if err == nil {
if rs.Next() {
r.scan()
} else {
r.err = sql.ErrNoRows
}
rs.Close()
}
return r
}
// Err ...
func (r *Row) Err() error {
if r.err != nil {
return r.err
}
return nil
}
func (r *Row) scan() error {
if r.err != nil {
return r.err
}
size := len(r.rows.types)
vals := make([]interface{}, size)
for i, typ := range r.rows.types {
vals[i] = reflect.New(typ).Interface()
}
if err := r.rows.x.Scan(vals...); err != nil {
r.err = err
return err
}
r.data = make(map[string]interface{}, size)
for i, x := range vals {
r.data[r.rows.names[i]] = reflect.ValueOf(x).Elem().Interface()
}
return nil
}
// Get ...
func (r *Row) Get(name string) interface{} {
if r.err != nil {
return nil
}
x, ok := r.data[name]
if !ok {
x, ok = r.data[toSnake(name)]
}
if !ok {
return nil
}
return x
}
// GetInt ...
func (r *Row) GetInt(name string, def ...int) int {
v := int(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toInt(x, v)
}
// GetUint ...
func (r *Row) GetUint(name string, def ...uint) uint {
v := uint(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toUint(x, v)
}
// GetInt8 ...
func (r *Row) GetInt8(name string, def ...int8) int8 {
v := int8(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toInt8(x, v)
}
// GetUint8 ...
func (r *Row) GetUint8(name string, def ...uint8) uint8 {
v := uint8(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toUint8(x, v)
}
// GetInt16 ...
func (r *Row) GetInt16(name string, def ...int16) int16 {
v := int16(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toInt16(x, v)
}
// GetUint16 ...
func (r *Row) GetUint16(name string, def ...uint16) uint16 {
v := uint16(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toUint16(x, v)
}
// GetInt32 ...
func (r *Row) GetInt32(name string, def ...int32) int32 {
v := int32(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toInt32(x, v)
}
// GetUint32 ...
func (r *Row) GetUint32(name string, def ...uint32) uint32 {
v := uint32(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toUint32(x, v)
}
// GetInt64 ...
func (r *Row) GetInt64(name string, def ...int64) int64 {
v := int64(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toInt64(x, v)
}
// GetUint64 ...
func (r *Row) GetUint64(name string, def ...uint64) uint64 {
v := uint64(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toUint64(x, v)
}
// GetFloat32 ...
func (r *Row) GetFloat32(name string, def ...float32) float32 {
v := float32(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toFloat32(x, v)
}
// GetFloat64 ...
func (r *Row) GetFloat64(name string, def ...float64) float64 {
v := float64(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toFloat64(x, v)
}
// GetString ...
func (r *Row) GetString(name string, def ...string) string {
v := ""
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toString(x, v)
}
// GetTime ...
func (r *Row) GetTime(name string, def ...time.Time) time.Time {
v := zeroTime
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toTime(x, v)
}
// GetBool ...
func (r *Row) GetBool(name string, def ...bool) bool {
v := false
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toBool(x, v)
}
// GetBytes ...
func (r *Row) GetBytes(name string, def ...[]byte) []byte {
var v []byte
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toBytes(x, v)
}
// GetDuration ...
func (r *Row) GetDuration(name string, def ...time.Duration) time.Duration {
v := time.Duration(0)
if len(def) > 0 {
v = def[0]
}
x := r.Get(name)
if x == nil {
return v
}
return toDuration(x, v)
}
// Unmarshal ...
func (r *Row) Unmarshal(x interface{}) error {
return r._unmarshal("", x)
}
// Data ...
func (r *Row) Data() (interface{}, error) {
if r.err != nil {
return nil, r.err
}
x := reflect.New(r.rows.s).Interface()
if err := r.Unmarshal(x); err != nil {
return nil, err
}
return x, nil
}
func (r *Row) _unmarshal(prefix string, d interface{}) (err error) {
if r.err != nil {
return r.err
}
defer func() {
if pr := recover(); pr != nil {
err = fmt.Errorf("%v", pr)
}
}()
v := reflect.ValueOf(d)
if v.Kind() != reflect.Ptr {
return fmt.Errorf("d must be pointer")
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return fmt.Errorf("d must be pointer of struct")
}
typ := v.Type()
size := typ.NumField()
for i := 0; i < size; i++ {
f := v.Field(i)
t := typ.Field(i)
if !f.CanSet() {
continue
}
name := ""
if tag := t.Tag.Get("sqlx"); tag != "" && tag != "-" {
name = tag
} else if tag := t.Tag.Get("json"); tag != "" && tag != "-" {
name = tag
} else {
name = toSnake(t.Name)
}
if prefix != "" {
name = fmt.Sprintf("%s.%s", prefix, name)
}
switch f.Interface().(type) {
case []byte:
f.Set(reflect.ValueOf(r.GetBytes(name)))
case time.Time:
f.Set(reflect.ValueOf(r.GetTime(name)))
case time.Duration:
f.Set(reflect.ValueOf(r.GetDuration(name)))
default:
switch f.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f.SetInt(r.GetInt64(name))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
f.SetUint(r.GetUint64(name))
case reflect.String:
f.SetString(r.GetString(name))
case reflect.Float32, reflect.Float64:
f.SetFloat(r.GetFloat64(name))
case reflect.Bool:
f.SetBool(r.GetBool(name))
case reflect.Ptr:
if f.Type().Elem().Kind() == reflect.Struct {
nextV := reflect.New(f.Type().Elem())
if err := r._unmarshal(name, nextV.Interface()); err != nil {
return err
}
f.Set(nextV)
}
case reflect.Struct:
nextV := reflect.New(f.Type())
if err := r._unmarshal(name, nextV.Interface()); err != nil {
return err
}
f.Set(nextV.Elem())
default:
continue
}
}
}
return nil
}
<file_sep>/stmt.go
package sqlx
import (
"context"
"database/sql"
)
// Stmt wraps sql.Stmt
type Stmt struct {
x *sql.Stmt
}
// WrapStmt ...
func WrapStmt(stmt *sql.Stmt, err error) (*Stmt, error) {
if err != nil {
return nil, err
}
return &Stmt{x: stmt}, nil
}
// Close ...
func (stmt *Stmt) Close() error {
return stmt.x.Close()
}
// ExecContext ...
func (stmt *Stmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) {
return stmt.x.ExecContext(ctx, args...)
}
// Exec ...
func (stmt *Stmt) Exec(args ...interface{}) (sql.Result, error) {
return stmt.ExecContext(context.Background(), args...)
}
// QueryContext ...
func (stmt *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) {
return WrapRows(stmt.x.QueryContext(ctx, args...))
}
// Query ...
func (stmt *Stmt) Query(args ...interface{}) (*Rows, error) {
return stmt.QueryContext(context.Background(), args...)
}
// AllContext ...
func (stmt *Stmt) AllContext(ctx context.Context, args ...interface{}) ([]interface{}, error) {
rows, err := stmt.QueryContext(ctx, args...)
if err != nil {
return nil, err
}
return rows.All()
}
// All ...
func (stmt *Stmt) All(args ...interface{}) ([]interface{}, error) {
return stmt.AllContext(context.Background(), args...)
}
// UnmarshalAllContext ...
func (stmt *Stmt) UnmarshalAllContext(ctx context.Context, x interface{}, args ...interface{}) error {
rows, err := stmt.QueryContext(ctx, args...)
if err != nil {
return err
}
return rows.UnmarshalAll(x)
}
// UnmarshalAll ...
func (stmt *Stmt) UnmarshalAll(x interface{}, args ...interface{}) error {
return stmt.UnmarshalAllContext(context.Background(), x, args...)
}
// QueryRowContext ...
func (stmt *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row {
return WrapRow(stmt.QueryContext(ctx, args...))
}
// QueryRow ...
func (stmt *Stmt) QueryRow(args ...interface{}) *Row {
return stmt.QueryRowContext(context.Background(), args...)
}
// DataContext ...
func (stmt *Stmt) DataContext(ctx context.Context, args ...interface{}) (interface{}, error) {
return stmt.QueryRowContext(ctx, args...).Data()
}
// Data ...
func (stmt *Stmt) Data(args ...interface{}) (interface{}, error) {
return stmt.DataContext(context.Background(), args...)
}
// UnmarshalContext ...
func (stmt *Stmt) UnmarshalContext(ctx context.Context, x interface{}, args ...interface{}) error {
return stmt.QueryRowContext(ctx, args...).Unmarshal(x)
}
// Unmarshal ...
func (stmt *Stmt) Unmarshal(x interface{}, args ...interface{}) error {
return stmt.UnmarshalContext(context.Background(), x, args...)
}
<file_sep>/Dockerfile
FROM mysql:5.7.25
ENV MYSQL_ROOT_PASSWORD=<PASSWORD>
ADD test.sql /docker-entrypoint-initdb.d/<file_sep>/test.sql
set names utf8;
drop database if exists mytest;
create database mytest charset utf8;
grant all on mytest.* to 'test'@'%' identified by 'test';
flush privileges;
use mytest;
create table test1 (
c01 bit not null default 0,
c01_1 bit(1) not null default 0,
c02_s tinyint not null default 0,
c02_u tinyint unsigned not null default 0,
c03 bool not null default false,
c04_s smallint not null default 0,
c04_u smallint unsigned not null default 0,
c05_s mediumint not null default 0,
c05_u mediumint unsigned not null default 0,
c06_s int not null default 0,
c06_u int unsigned not null default 0,
c07_s bigint not null default 0,
c07_u bigint unsigned not null default 0,
c08_s decimal not null default 0,
c08_u decimal unsigned not null default 0,
c09_s float not null default 0,
c09_u float unsigned not null default 0,
c10_s double not null default 0,
c10_u double unsigned not null default 0,
c11 date not null,
c12 time not null,
c13 year not null,
c14 datetime not null,
c15 timestamp not null,
c16 char(10) not null,
c17 varchar(10) not null,
c18 binary(10) not null,
c19 varbinary(10) not null,
c20 tinyblob not null,
c21 tinytext not null,
c22 blob not null,
c23 text not null,
c24 mediumblob not null,
c25 mediumtext not null,
c26 longblob not null,
c27 longtext not null,
c28 enum('a', 'b', 'c') not null,
c29 set('a', 'b', 'c') not null
) charset utf8;
insert into test1 values(b'1', b'1', -2, 2, true, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, '2019-01-01', "123:04:05", '2019', '2014-09-23 10:01:02', '2014-09-23 10:01:02', 'C16', 'C17', 'C18', 'C19', 'C20', 'C21', 'C22', 'C23', 'C24', 'C25', 'C26', 'C27', 'a', 'b');
create table test2 (
c01 bit,
c01_1 bit(1),
c02_s tinyint,
c02_u tinyint unsigned,
c03 bool,
c04_s smallint,
c04_u smallint unsigned,
c05_s mediumint,
c05_u mediumint unsigned,
c06_s int,
c06_u int unsigned,
c07_s bigint,
c07_u bigint unsigned,
c08_s decimal,
c08_u decimal unsigned,
c09_s float,
c09_u float unsigned,
c10_s double,
c10_u double unsigned,
c11 date,
c12 time,
c13 year,
c14 datetime,
c15 timestamp,
c16 char(10),
c17 varchar(10),
c18 binary(10),
c19 varbinary(10),
c20 tinyblob,
c21 tinytext,
c22 blob,
c23 text,
c24 mediumblob,
c25 mediumtext,
c26 longblob,
c27 longtext,
c28 enum('a', 'b', 'c'),
c29 set('a', 'b', 'c')
) charset utf8;
insert into test2 values();
update test2 set c15 = '2014-09-23 10:01:02'<file_sep>/rows_test.go
package sqlx_test
import (
"encoding/json"
"reflect"
"testing"
"time"
gsql "database/sql"
"github.com/dairaga/sqlx"
_ "github.com/go-sql-driver/mysql"
)
var (
funcNames = []string{"GetBool", "GetFloat32", "GetFloat64", "GetInt", "GetInt16", "GetInt32", "GetInt64", "GetInt8", "GetString", "GetTime", "GetUint", "GetUint16", "GetUint32", "GetUint64", "GetUint8", "GetBytes"}
funcs = []interface{}{
func(rs *sqlx.Rows, name string, def bool) bool { return rs.GetBool(name, def) },
func(rs *sqlx.Rows, name string, def float32) float32 { return rs.GetFloat32(name, def) },
func(rs *sqlx.Rows, name string, def float64) float64 { return rs.GetFloat64(name, def) },
func(rs *sqlx.Rows, name string, def int) int { return rs.GetInt(name, def) },
func(rs *sqlx.Rows, name string, def int16) int16 { return rs.GetInt16(name, def) },
func(rs *sqlx.Rows, name string, def int32) int32 { return rs.GetInt32(name, def) },
func(rs *sqlx.Rows, name string, def int64) int64 { return rs.GetInt64(name, def) },
func(rs *sqlx.Rows, name string, def int8) int8 { return rs.GetInt8(name, def) },
func(rs *sqlx.Rows, name string, def string) string { return rs.GetString(name, def) },
func(rs *sqlx.Rows, name string, def time.Time) time.Time { return rs.GetTime(name, def) },
func(rs *sqlx.Rows, name string, def uint) uint { return rs.GetUint(name, def) },
func(rs *sqlx.Rows, name string, def uint16) uint16 { return rs.GetUint16(name, def) },
func(rs *sqlx.Rows, name string, def uint32) uint32 { return rs.GetUint32(name, def) },
func(rs *sqlx.Rows, name string, def uint64) uint64 { return rs.GetUint64(name, def) },
func(rs *sqlx.Rows, name string, def uint8) uint8 { return rs.GetUint8(name, def) },
func(rs *sqlx.Rows, name string, def []byte) []byte { return rs.GetBytes(name, def) },
}
defTime = time.Now()
defstr = "xyz"
defbytes = []byte{}
defs = []interface{}{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes}
)
func TestZeroTime(t *testing.T) {
t.Log(reflect.Zero(timeType))
}
func Test1(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rows, err := db.Query("select * from test1")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
cols, err := rows.ColumnTypes()
if err != nil {
t.Fatal(err)
}
for i, col := range cols {
canNull, ok1 := col.Nullable()
len, ok2 := col.Length()
p, s, ok3 := col.DecimalSize()
t.Logf("\n%d: %s\t%s\t%v\n\tnull: %v, %v\n\tlen: %v, %v\n\tdecimal size: %v, %v, %v", i, col.Name(), col.DatabaseTypeName(), col.ScanType(), canNull, ok1, len, ok2, p, s, ok3)
}
rows2, err := db.Query("select * from test2")
if err != nil {
t.Fatal(err)
}
defer rows2.Close()
cols, err = rows2.ColumnTypes()
if err != nil {
t.Fatal(err)
}
for i, col := range cols {
canNull, ok1 := col.Nullable()
len, ok2 := col.Length()
p, s, ok3 := col.DecimalSize()
t.Logf("\n%d: %s\t%s\t%v\n\tnull: %v, %v\n\tlen: %v, %v\n\tdecimal size: %v, %v, %v", i, col.Name(), col.DatabaseTypeName(), col.ScanType(), canNull, ok1, len, ok2, p, s, ok3)
}
}
func TestToRowsAllNotNull(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs, err := sqlx.WrapRows(db.Query("select * from test1"))
if err != nil {
t.Fatal(err)
}
defer rs.Close()
ansTime1 := time.Date(2019, time.January, 1, 0, 0, 0, 0, time.UTC)
ansTime1Bytes, _ := ansTime1.MarshalBinary()
ansTime2 := time.Date(2014, time.September, 23, 10, 01, 02, 0, time.UTC)
ansTime2Bytes, _ := ansTime2.MarshalBinary()
ans := [][][]interface{}{
{
{true, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), string([]byte{1}), defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{1}},
{true, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), string([]byte{1}), defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{1}},
{true, float32(-2), float64(-2), int(-2), int16(-2), int32(-2), int64(-2), int8(-2), "-2", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{254}},
{true, float32(2), float64(2), int(2), int16(2), int32(2), int64(2), int8(2), "2", defTime, uint(2), uint16(2), uint32(2), uint64(2), uint8(2), []byte{2}},
{true, float32(1), float64(1), int(1), int16(1), int32(1), int64(1), int8(1), "1", defTime, uint(1), uint16(1), uint32(1), uint64(1), uint8(1), []byte{1}},
{true, float32(-4), float64(-4), int(-4), int16(-4), int32(-4), int64(-4), int8(-4), "-4", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{252, 255}},
{true, float32(4), float64(4), int(4), int16(4), int32(4), int64(4), int8(4), "4", defTime, uint(4), uint16(4), uint32(4), uint64(4), uint8(4), []byte{4, 0}},
{true, float32(-5), float64(-5), int(-5), int16(-5), int32(-5), int64(-5), int8(-5), "-5", time.Unix(-5, 0), uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{251, 255, 255, 255}},
{true, float32(5), float64(5), int(5), int16(5), int32(5), int64(5), int8(5), "5", time.Unix(5, 0), uint(5), uint16(5), uint32(5), uint64(5), uint8(5), []byte{5, 0, 0, 0}},
{true, float32(-6), float64(-6), int(-6), int16(-6), int32(-6), int64(-6), int8(-6), "-6", time.Unix(-6, 0), uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{250, 255, 255, 255}},
{true, float32(6), float64(6), int(6), int16(6), int32(6), int64(6), int8(6), "6", time.Unix(6, 0), uint(6), uint16(6), uint32(6), uint64(6), uint8(6), []byte{6, 0, 0, 0}},
{true, float32(-7), float64(-7), int(-7), int16(-7), int32(-7), int64(-7), int8(-7), "-7", time.Unix(-7, 0), uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{249, 255, 255, 255, 255, 255, 255, 255}},
{true, float32(7), float64(7), int(7), int16(7), int32(7), int64(7), int8(7), "7", time.Unix(7, 0), uint(7), uint16(7), uint32(7), uint64(7), uint8(7), []byte{7, 0, 0, 0, 0, 0, 0, 0}},
{true, float32(-8), float64(-8), int(-8), int16(-8), int32(-8), int64(-8), int8(-8), "-8", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{true, float32(8), float64(8), int(8), int16(8), int32(8), int64(8), int8(8), "8", defTime, uint(8), uint16(8), uint32(8), uint64(8), uint8(8), defbytes},
{true, float32(-9), float64(-9), int(-9), int16(-9), int32(-9), int64(-9), int8(-9), "-9", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{true, float32(9), float64(9), int(9), int16(9), int32(9), int64(9), int8(9), "9", defTime, uint(9), uint16(9), uint32(9), uint64(9), uint8(9), defbytes},
{true, float32(-10), float64(-10), int(-10), int16(-10), int32(-10), int64(-10), int8(-10), "-10", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{true, float32(10), float64(10), int(10), int16(10), int32(10), int64(10), int8(10), "10", defTime, uint(10), uint16(10), uint32(10), uint64(10), uint8(10), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), ansTime1.String(), ansTime1, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), ansTime1Bytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "123:04:05", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("123:04:05")},
{true, float32(2019), float64(2019), int(2019), int16(2019), int32(2019), int64(2019), int8(-29), "2019", defTime, uint(2019), uint16(2019), uint32(2019), uint64(2019), uint8(227), []byte{227, 7}},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), ansTime2.String(), ansTime2, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), ansTime2Bytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), ansTime2.String(), ansTime2, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), ansTime2Bytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C16", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C16")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C17", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C17")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), string([]byte{'C', '1', '8', 0, 0, 0, 0, 0, 0, 0}), defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte{'C', '1', '8', 0, 0, 0, 0, 0, 0, 0}},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C19", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C19")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C20", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C20")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C21", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C21")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C22", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C22")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C23", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C23")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C24", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C24")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C25", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C25")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C26", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C26")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "C27", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("C27")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "a", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("a")},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "b", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), []byte("b")},
},
}
count := 0
for rs.Next() {
for i, name := range rs.Names() {
if i < len(ans[count]) {
for j, f := range funcs {
a := ans[count][i][j]
b := reflect.ValueOf(f).Call([]reflect.Value{reflect.ValueOf(rs), reflect.ValueOf(name), reflect.ValueOf(defs[j])})[0].Interface()
switch av := a.(type) {
case []byte:
if string(av) != string(b.([]byte)) {
t.Errorf("%d: %s %s should be %v, but %v", i, name, funcNames[j], av, b.([]byte))
}
default:
if a != b {
t.Errorf("%d: %s %s should be %v, but %v", i, name, funcNames[j], a, b)
}
}
}
} else {
t.Logf("%d: %s: bool: %v", i, name, rs.GetBool(name, false))
t.Logf("%d: %s: float32: %v", i, name, rs.GetFloat32(name, 100.0))
t.Logf("%d: %s: float64: %v", i, name, rs.GetFloat64(name, 100.0))
t.Logf("%d: %s: int: %v", i, name, rs.GetInt(name, -100))
t.Logf("%d: %s: int16: %v", i, name, rs.GetInt16(name, -100))
t.Logf("%d: %s: int32: %v", i, name, rs.GetInt32(name, -100))
t.Logf("%d: %s: int64: %v", i, name, rs.GetInt64(name, -100))
t.Logf("%d: %s: int8: %v", i, name, rs.GetInt8(name, -100))
t.Logf("%d: %s: string: %v", i, name, rs.GetString(name, "xyz"))
t.Logf("%d: %s: time: %v", i, name, rs.GetTime(name, defTime))
t.Logf("%d: %s: uint: %v", i, name, rs.GetUint(name, 100))
t.Logf("%d: %s: uint16: %v", i, name, rs.GetUint16(name, 100))
t.Logf("%d: %s: uint32: %v", i, name, rs.GetUint32(name, 100))
t.Logf("%d: %s: uint64: %v", i, name, rs.GetUint64(name, 100))
t.Logf("%d: %s: uint8: %v", i, name, rs.GetUint8(name, 100))
t.Logf("%d: %s: bytes: %v", i, name, rs.GetBytes(name, defbytes))
}
}
count++
}
if err := rs.Err(); err != nil {
t.Errorf("rs err: %v", err)
}
}
func TestToRowsAllNull(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs, err := sqlx.WrapRows(db.Query("select * from test2"))
if err != nil {
t.Fatal(err)
}
defer rs.Close()
timeAns := time.Date(2014, time.September, 23, 10, 01, 02, 0, time.UTC)
timeAnsBytes, _ := timeAns.MarshalBinary()
ans := [][][]interface{}{
{
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), timeAns.String(), timeAns, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), timeAnsBytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), "", defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
{false, float32(100), float64(100), int(-100), int16(-100), int32(-100), int64(-100), int8(-100), defstr, defTime, uint(100), uint16(100), uint32(100), uint64(100), uint8(100), defbytes},
},
}
count := 0
for rs.Next() {
for i, name := range rs.Names() {
if i < len(ans[count]) {
for j, f := range funcs {
a := ans[count][i][j]
b := reflect.ValueOf(f).Call([]reflect.Value{reflect.ValueOf(rs), reflect.ValueOf(name), reflect.ValueOf(defs[j])})[0].Interface()
switch av := a.(type) {
case []byte:
if string(av) != string(b.([]byte)) {
t.Errorf("%d: %s %s should be %v, but %v", i, name, funcNames[j], av, b.([]byte))
}
default:
if a != b {
t.Errorf("%d: %s %s should be %v, but %v", i, name, funcNames[j], a, b)
}
}
}
} else {
t.Logf("%d: %s: bool: %v", i, name, rs.GetBool(name, false))
t.Logf("%d: %s: float32: %v", i, name, rs.GetFloat32(name, 100.0))
t.Logf("%d: %s: float64: %v", i, name, rs.GetFloat64(name, 100.0))
t.Logf("%d: %s: int: %v", i, name, rs.GetInt(name, -100))
t.Logf("%d: %s: int16: %v", i, name, rs.GetInt16(name, -100))
t.Logf("%d: %s: int32: %v", i, name, rs.GetInt32(name, -100))
t.Logf("%d: %s: int64: %v", i, name, rs.GetInt64(name, -100))
t.Logf("%d: %s: int8: %v", i, name, rs.GetInt8(name, -100))
t.Logf("%d: %s: string: %v", i, name, rs.GetString(name, "xyz"))
t.Logf("%d: %s: time: %v", i, name, rs.GetTime(name, defTime))
t.Logf("%d: %s: uint: %v", i, name, rs.GetUint(name, 100))
t.Logf("%d: %s: uint16: %v", i, name, rs.GetUint16(name, 100))
t.Logf("%d: %s: uint32: %v", i, name, rs.GetUint32(name, 100))
t.Logf("%d: %s: uint64: %v", i, name, rs.GetUint64(name, 100))
t.Logf("%d: %s: uint8: %v", i, name, rs.GetUint8(name, 100))
t.Logf("%d: %s: bytes: %v", i, name, rs.GetBytes(name, defbytes))
}
}
count++
}
if err := rs.Err(); err != nil {
t.Errorf("rs err: %v", err)
}
}
func TestData(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs1, err := sqlx.WrapRows(db.Query("select * from test1"))
if err != nil {
t.Fatal(err)
}
defer rs1.Close()
if !rs1.Next() {
t.Errorf("no data")
return
}
d1, err := rs1.Data()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test1Row {
t.Errorf("json string should be \n%s\n but \n%s", test1Row, string(tmp))
}
rs2, err := sqlx.WrapRows(db.Query("select * from test2"))
if err != nil {
t.Fatal(err)
}
defer rs2.Close()
if !rs2.Next() {
t.Errorf("no data")
return
}
d2, err := rs2.Data()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d2)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test2Row {
t.Errorf("json string should be \n%s\n but \n%s", test2Row, string(tmp))
}
}
func TestUnmarshal(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs1, err := sqlx.WrapRows(db.Query("select * from test1"))
if err != nil {
t.Fatal(err)
}
defer rs1.Close()
if !rs1.Next() {
t.Errorf("no data")
return
}
d1 := &TestStruct1{}
err = rs1.Unmarshal(d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s1 {
t.Errorf("json string should be \n%s\n but \n%s", s1, string(tmp))
}
rs2, err := sqlx.WrapRows(db.Query("select * from test2"))
if err != nil {
t.Fatal(err)
}
defer rs2.Close()
if !rs2.Next() {
t.Errorf("no data")
return
}
err = rs2.Unmarshal(d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s2 {
t.Errorf("json string should be \n%s\n but \n%s", s2, string(tmp))
}
}
func TestAll(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs1, err := sqlx.WrapRows(db.Query("select * from test1"))
if err != nil {
t.Fatal(err)
}
defer rs1.Close()
all, err := rs1.All()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(all)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test1Rows {
t.Errorf("json string should be \n%s\n but \n%s", test1Rows, string(tmp))
}
rs2, err := sqlx.WrapRows(db.Query("select * from test2"))
if err != nil {
t.Fatal(err)
}
defer rs2.Close()
all, err = rs2.All()
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(all)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != test2Rows {
t.Errorf("json string should be \n%s\n but \n%s", test2Rows, string(tmp))
}
}
func TestUnmarshalAll(t *testing.T) {
db, err := gsql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
rs1, err := sqlx.WrapRows(db.Query("select * from test1"))
if err != nil {
t.Fatal(err)
}
defer rs1.Close()
d1 := []TestStruct1{}
err = rs1.UnmarshalAll(&d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err := json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s1Slice {
t.Errorf("json string should be \n%s\n but \n%s", s1Slice, string(tmp))
}
rs2, err := sqlx.WrapRows(db.Query("select * from test2"))
if err != nil {
t.Fatal(err)
}
defer rs2.Close()
err = rs2.UnmarshalAll(&d1)
if err != nil {
t.Errorf("to internal data: %v", err)
}
tmp, err = json.Marshal(d1)
if err != nil {
t.Errorf("marshal: %v", err)
}
if string(tmp) != s2Slice {
t.Errorf("json string should be \n%s\n but \n%s", s2Slice, string(tmp))
}
}
<file_sep>/convert.go
package sqlx
import (
"database/sql"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"reflect"
"strconv"
"time"
"github.com/spf13/cast"
)
var errNil = errors.New("input is nil")
func _cast(x, def interface{}, castFunc interface{}) interface{} {
if x == nil {
return def
}
switch v := x.(type) {
case driver.Valuer:
dv, err := v.Value()
if err != nil {
return def
}
if dv == nil {
return def
}
return _cast(dv, def, castFunc)
case sql.RawBytes:
return _cast([]byte(v), def, castFunc)
default:
result := reflect.ValueOf(castFunc).Call([]reflect.Value{reflect.ValueOf(x)})
if result[1].IsNil() {
return result[0].Interface()
}
return def
}
}
func toInt(x interface{}, def int) int {
return _cast(x, def, cast.ToIntE).(int)
}
func toUint(x interface{}, def uint) uint {
return _cast(x, def, cast.ToUintE).(uint)
}
func toInt8(x interface{}, def int8) int8 {
return _cast(x, def, cast.ToInt8E).(int8)
}
func toUint8(x interface{}, def uint8) uint8 {
return _cast(x, def, cast.ToUint8E).(uint8)
}
func toInt16(x interface{}, def int16) int16 {
return _cast(x, def, cast.ToInt16E).(int16)
}
func toUint16(x interface{}, def uint16) uint16 {
return _cast(x, def, cast.ToUint16E).(uint16)
}
func toInt32(x interface{}, def int32) int32 {
return _cast(x, def, cast.ToInt32E).(int32)
}
func toUint32(x interface{}, def uint32) uint32 {
return _cast(x, def, cast.ToUint32E).(uint32)
}
func toInt64(x interface{}, def int64) int64 {
return _cast(x, def, cast.ToInt64E).(int64)
}
func toUint64(x interface{}, def uint64) uint64 {
return _cast(x, def, cast.ToUint64E).(uint64)
}
func toFloat32(x interface{}, def float32) float32 {
return _cast(x, def, cast.ToFloat32E).(float32)
}
func toFloat64(x interface{}, def float64) float64 {
return _cast(x, def, cast.ToFloat64E).(float64)
}
func toString(x interface{}, def string) string {
return _cast(x, def, cast.ToStringE).(string)
}
func toTime(x interface{}, def time.Time) time.Time {
return _cast(x, def, cast.ToTimeE).(time.Time)
}
func toDuration(x interface{}, def time.Duration) time.Duration {
return _cast(x, def, cast.ToDurationE).(time.Duration)
}
func _castToBoolE(x interface{}) (bool, error) {
if x == nil {
return false, errNil
}
switch v := x.(type) {
case bool:
return v, nil
case int:
return !(0 == v), nil
case uint:
return !(0 == v), nil
case int8:
return !(0 == v), nil
case uint8:
return !(0 == v), nil
case int16:
return !(0 == v), nil
case uint16:
return !(0 == v), nil
case int32:
return !(0 == v), nil
case uint32:
return !(0 == v), nil
case int64:
return !(0 == v), nil
case uint64:
return !(0 == v), nil
case float32:
return !(0 == v), nil
case float64:
return !(0 == v), nil
case string:
return strconv.ParseBool(v)
case []byte:
if len(v) == 1 {
return !(0 == v[0]), nil
}
return false, fmt.Errorf("%v can not convert to bool", v)
default:
return false, fmt.Errorf("%v can not convert to bool", v)
}
}
func toBool(x interface{}, def bool) bool {
return _cast(x, def, _castToBoolE).(bool)
}
func _castToBytesE(x interface{}) ([]byte, error) {
if x == nil {
return nil, errNil
}
switch v := x.(type) {
case sql.RawBytes:
return []byte(v), nil
case []byte:
return v, nil
case uint:
ret := make([]byte, 8)
binary.LittleEndian.PutUint64(ret, uint64(v))
return ret, nil
case int:
ret := make([]byte, 8)
binary.LittleEndian.PutUint64(ret, uint64(v))
return ret, nil
case uint8:
return []byte{v}, nil
case int8:
return []byte{uint8(v)}, nil
case uint16:
ret := make([]byte, 2)
binary.LittleEndian.PutUint16(ret, v)
return ret, nil
case int16:
ret := make([]byte, 2)
binary.LittleEndian.PutUint16(ret, uint16(v))
return ret, nil
case uint32:
ret := make([]byte, 4)
binary.LittleEndian.PutUint32(ret, v)
return ret, nil
case int32:
ret := make([]byte, 4)
binary.LittleEndian.PutUint32(ret, uint32(v))
return ret, nil
case uint64:
ret := make([]byte, 8)
binary.LittleEndian.PutUint64(ret, v)
return ret, nil
case int64:
ret := make([]byte, 8)
binary.LittleEndian.PutUint64(ret, uint64(v))
return ret, nil
case string:
return []byte(v), nil
case bool:
if v {
return []byte{1}, nil
}
return []byte{0}, nil
case time.Time:
return v.MarshalBinary()
default:
return nil, fmt.Errorf("%v can convert to bytes", v)
}
}
func toBytes(x interface{}, def []byte) []byte {
return _cast(x, def, _castToBytesE).([]byte)
}
<file_sep>/tx.go
package sqlx
import (
"context"
"database/sql"
)
// Tx wraps sql.Tx
type Tx struct {
*sqlxobj
}
// WrapTx ...
func WrapTx(tx *sql.Tx, err error) (*Tx, error) {
if err != nil {
return nil, err
}
return &Tx{&sqlxobj{tx, NewCmd(), nil}}, nil
}
// Commit ...
func (t *Tx) Commit() error {
return t.sqlxobj.x.(*sql.Tx).Commit()
}
// Rollback ...
func (t *Tx) Rollback() error {
return t.sqlxobj.x.(*sql.Tx).Rollback()
}
// StmtContext ...
func (t *Tx) StmtContext(ctx context.Context, s *Stmt) *Stmt {
return &Stmt{x: t.sqlxobj.x.(*sql.Tx).StmtContext(ctx, s.x)}
}
// Stmt ...
func (t *Tx) Stmt(s *Stmt) *Stmt {
return t.StmtContext(context.Background(), s)
}
<file_sep>/convient.go
package sqlx
import "strings"
func toCamel(v string) string {
ret := &strings.Builder{}
ret.Grow(len(v))
needUpper := true
for _, x := range v {
if needUpper {
if 'a' <= x && x <= 'z' {
x -= 'a' - 'A'
}
}
if x == '_' || x == '.' {
needUpper = true
continue
}
ret.WriteByte(byte(x))
needUpper = false
}
return ret.String()
}
func toSnake(v string) string {
needUnderLine := false
ret := &strings.Builder{}
ret.Grow(len(v))
for _, x := range v {
if 'A' <= x && x <= 'Z' {
if needUnderLine {
ret.WriteByte(byte('_'))
}
needUnderLine = true
x += 'a' - 'A'
}
ret.WriteByte(byte(x))
}
return ret.String()
}
| a6cb8ae39d68eb50170370d3b0d79ee23f924a29 | [
"SQL",
"Makefile",
"Go",
"Go Module",
"Dockerfile"
] | 18 | Go | dairaga/sqlx | 8cd413085957e8349bc8d7cf8dbacb50fcabfaa4 | 2cdddcf8511b198d95f3bedf930b09a679d79317 |
refs/heads/master | <file_sep>$(document).ready(function(){
$('#wall').show();
$("#wall").slideReveal({ trigger: $("#button"), position: "right", width: "100vw", speed: "1000"});
$('#intro').show().textition({map: {x: 100, y: 0, z: 0},autoplay: true});
setTimeout(function() { $('#intro').remove();}, 17000);
$( "#console" ).setAsTerminal("#console", "user", "host", "~", "$", PROGRAMS);
$('#code').click(function(){$('#console').fadeToggle("slide").delay(800);});
$('#contacts').click(function(){
$('#contact').fadeToggle("slide").delay(800);
$('#email').fadeToggle("slide").delay(1200);
});
$('#socials').click(function(){$('#social').fadeToggle("slide").delay(800);});
$('#bhome').click(function () {
$('#pages').attr('src', 'blog.html');
});
$('#stats').click(function () {
$('#pages').attr('src', 'blog2.html');
});
});
| 58ec5b907678e478556ad5684d1cd2b0b3d181ee | [
"JavaScript"
] | 1 | JavaScript | pedrocr83/personal_website | 9dbc66a1ec836575c6a3680894c736a3c4222904 | b03a1a0c15cb969f9e13fc9144d5d7bc4be98728 |
refs/heads/master | <repo_name>iwe7/ims-socket.io-client<file_sep>/dist/index.d.ts
export * from './public_api';
export * from './socket-subject';
<file_sep>/dist/url.d.ts
export interface Url {
port: string;
path: string;
host: string;
protocol: string;
id: string;
href: string;
source: any;
query: string;
}
export declare function url(uri: string, loc?: Location): Url;
<file_sep>/src/url.ts
import parseuri = require('parseuri');
import debug2 = require('debug');
const debug: debug2.IDebugger = debug2('socket.io-client:url');
import { global } from './global';
export interface Url {
port: string;
path: string;
host: string;
protocol: string;
id: string;
href: string;
source: any;
query: string;
}
export function url(uri: string, loc?: Location): Url {
let obj: Url;
loc = loc || global.location as Location;
if (null == uri) uri = loc.protocol + '//' + loc.host;
if ('string' === typeof uri) {
if ('/' === uri.charAt(0)) {
if ('/' === uri.charAt(1)) {
uri = loc.protocol + uri;
} else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
debug('protocol-less url %s', uri);
if ('undefined' !== typeof loc) {
uri = loc.protocol + '//' + uri;
} else {
uri = 'https://' + uri;
}
}
// parse
debug('parse %s', uri);
obj = parseuri(uri);
}
// make sure we treat `localhost:80` and `localhost` equally
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = '80';
} else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = '443';
}
}
obj.path = obj.path || '/socket.io';
var ipv6 = obj.host.indexOf(':') !== -1;
var host = ipv6 ? '[' + obj.host + ']' : obj.host;
// define unique id
obj.id = obj.protocol + '://' + host + ':' + obj.port;
// define href
obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
return obj;
}
<file_sep>/dist/socket.d.ts
import { Manager } from './manager';
import Emitter = require('component-emitter');
/**
* `Socket` constructor.
*
* @api public
*/
export declare class Socket extends Emitter {
nsp?: string;
json: Socket;
id: string;
ids: any;
acks: any;
receiveBuffer: any;
sendBuffer: any;
connected: boolean;
disconnected: boolean;
flags: any;
query: any;
io: Manager;
constructor(io: Manager | string, nsp?: string, opts?: any);
on(event: 'connect', listener: () => void): Emitter;
on(event: 'connect_error', listener: (err: Error) => void): Emitter;
on(event: 'connect_timeout', listener: () => void): Emitter;
on(event: 'connecting', listener: (attempt: number) => void): Emitter;
on(event: 'disconnect', listener: () => void): Emitter;
on(event: 'error', listener: (err: Error) => void): Emitter;
on(event: 'reconnect', listener: (attempt: number) => void): Emitter;
on(event: 'reconnect_attempt', listener: () => void): Emitter;
on(event: 'reconnect_failed', listener: () => void): Emitter;
on(event: 'reconnect_error', listener: (err: Error) => void): Emitter;
on(event: 'reconnecting', listener: (attempt: number) => void): Emitter;
on(event: 'ping', listener: () => void): Emitter;
on(event: 'pong', listener: () => void): Emitter;
on(event: 'message', listener: (data: any) => void): Emitter;
/**
* Subscribe to open, close and packet events
*
* @api private
*/
subs: any;
subEvents(): void;
open(): Socket;
connect(): Socket;
send(...args: any[]): this;
emit(ev: string, ...args: any[]): boolean;
packet(packet: any): void;
onopen(): void;
onclose(reason: any): void;
onpacket(packet: any): void;
onevent(packet: any): void;
ack(id: any): () => void;
private onack;
onconnect(): void;
emitBuffered(): void;
private ondisconnect;
destroy(): void;
close(): Socket;
disconnect(): Socket;
compress(compress: boolean): Socket;
binary(binary: any): this;
}
<file_sep>/dist/public_api.d.ts
import { ManagerOpts } from './manager';
import { Socket } from './socket';
export declare const managers: {};
export interface ConnectOption extends ManagerOpts {
}
export declare type ConnectFunction = (uri: string, opts: ConnectOption) => Socket;
export declare const connect: ConnectFunction;
export declare const protocol: any;
export { Manager } from './manager';
export { Socket } from './socket';
<file_sep>/readme.md
### @types/socket.io-client 版本过低
> 用typescript重写,并增加实用功能
## socket.io-client
```ts
import { connect } from 'ims-socket.io-client';
const socket = connect('http://localhost:3000',{});
socket.onconnect = ()=> {
socket.send('some data');
};
socket.on('message',(data)=>{
console.log(data);
})
```
## rxjs封装
```ts
import { SocketSubject } from 'ims-socket.io-client';
const socket = new SocketSubject('http://localhost:3000',{});
// 订阅时创建连接
socket.subscribe(res=>{
console.log('接受到的消息',res);
});
// 发送消息 等同于 socket.send(data);
socket.next(data);
// 取消订阅时关闭连接 socket.close();
socket.unsubject();
```
<file_sep>/src/manager.ts
import eio = require('engine.io-client');
import parser = require('socket.io-parser');
import { Encoder, Decoder } from 'socket.io-parser';
import bind = require('component-bind');
import debug2 = require('debug');
const debug: debug2.IDebugger = debug2('socket.io-client:manager');
import indexOf = require('indexof');
import Backoff = require('backo2');
import Emitter = require('component-emitter');
import { on } from './on';
import { Socket } from './socket';
const has = Object.prototype.hasOwnProperty;
export interface ManagerOpts extends eio.SocketOptions {
forceNew?: boolean;
multiplex?: boolean;
path?: string;
reconnection?: boolean;
reconnectionAttempts?: number;
reconnectionDelay?: number;
reconnectionDelayMax?: number;
randomizationFactor?: number;
timeout?: number;
autoConnect?: boolean;
host?: string;
hostname?: string;
secure?: boolean;
port?: string;
query?: Object;
upgrade?: boolean;
forceJSONP?: boolean;
jsonp?: boolean;
forceBase64?: boolean;
enablesXDR?: boolean;
timestampParam?: string;
timestampRequests?: boolean;
policyPost?: number;
rememberUpgrade?: boolean;
onlyBinaryUpgrades?: boolean;
pfx?: string;
key?: string;
passphrase?: string
cert?: string;
ca?: string | string[];
ciphers?: string;
rejectUnauthorized?: boolean;
}
export class Manager extends Emitter {
nsps: { [namespace: string]: Socket } = {};
subs: any;
backoff: Backoff;
_reconnectionDelay: any;
_reconnectionDelayMax: any;
_randomizationFactor: any;
readyState: string = 'closed';
connecting: Socket[] = [];
lastPing: number;
encoding: boolean = false;
packetBuffer: any;
encoder: any;
decoder: any;
autoConnect: boolean;
engine: any;
skipReconnect: boolean;
_timeout: any;
_reconnection: boolean;
uri: string;
constructor(uri: string | ManagerOpts, public opts?: ManagerOpts) {
super();
if (typeof uri === 'string') {
this.uri = uri;
} else {
opts = uri;
uri = undefined;
}
this.opts = this.opts || {};
this.opts.path = this.opts.path || '/socket.io';
this.nsps = {};
this.subs = [];
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1000);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
this.randomizationFactor(opts.randomizationFactor || 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay() as any,
max: this.reconnectionDelayMax() as any,
jitter: this.randomizationFactor() as any,
});
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
this.lastPing = null;
this.packetBuffer = [];
this.encoder = new Encoder();
this.decoder = new Decoder();
this.autoConnect = opts.autoConnect !== false;
console.log(this.autoConnect);
if (this.autoConnect) this.open();
}
/**
* Propagate given event to sockets and emit on `this`
*
* @api private
*/
emitAll(...args: any[]) {
this.emit.apply(this, arguments);
for (var nsp in this.nsps) {
if (has.call(this.nsps, nsp)) {
this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
}
}
};
/**
* Update `socket.id` of all sockets
*
* @api private
*/
updateSocketIds() {
for (var nsp in this.nsps) {
if (has.call(this.nsps, nsp)) {
this.nsps[nsp].id = this.generateId(nsp);
}
}
};
generateId(nsp: string) {
return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
}
reconnection(v: boolean): this | boolean {
if (!arguments.length) return this._reconnection;
this._reconnection = !!v;
return this;
}
_reconnectionAttempts: any;
reconnectionAttempts(v: number): this | number {
if (!arguments.length) return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
}
reconnectionDelay(v?: number): number | this {
if (!arguments.length) return this._reconnectionDelay;
this._reconnectionDelay = v;
this.backoff && this.backoff.setMin(v);
this._reconnectionDelay
}
randomizationFactor(v?: number): number | this {
if (!arguments.length) return this._randomizationFactor;
this._randomizationFactor = v;
this.backoff && this.backoff.setJitter(v);
return this;
}
reconnectionDelayMax(v?: number): number | this {
if (!arguments.length) return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
this.backoff && this.backoff.setMax(v);
return this;
};
timeout(v?: number): this | number {
if (!arguments.length) return this._timeout;
this._timeout = v;
return this;
}
reconnecting: any;
private maybeReconnectOnOpen() {
// Only try to reconnect if it's the first time we're connecting
if (!this.reconnecting && this._reconnection && (<any>this.backoff).attempts === 0) {
// keeps reconnection from firing twice for the same reconnection loop
this.reconnect();
}
};
open(fn?: (err?: any) => void): this {
return this.connect(fn);
}
connect(fn?: (err?: any) => void): this {
debug('readyState %s', this.readyState);
if (~this.readyState.indexOf('open')) return this;
debug('opening %s', this.uri);
this.engine = eio(this.uri, this.opts);
var socket = this.engine;
var self = this;
this.readyState = 'opening';
this.skipReconnect = false;
var openSub = on(socket, 'open', function () {
self.onopen();
fn && fn();
});
var errorSub = on(socket, 'error', function (data) {
debug('connect_error');
self.cleanup();
self.readyState = 'closed';
self.emitAll('connect_error', data);
if (fn) {
var err = new Error('Connection error');
err.message = data;
fn(err);
} else {
self.maybeReconnectOnOpen();
}
});
if (false !== this._timeout) {
var timeout = this._timeout;
debug('connect attempt will timeout after %d', timeout);
var timer = setTimeout(function () {
debug('connect attempt timed out after %d', timeout);
openSub.destroy();
socket.close();
socket.emit('error', 'timeout');
self.emitAll('connect_timeout', timeout);
}, timeout);
this.subs.push({
destroy: function () {
clearTimeout(timer);
}
});
}
this.subs.push(openSub);
this.subs.push(errorSub);
return this;
}
/**
* Called upon transport open.
*
* @api private
*/
onopen() {
debug('open');
// clear old subs
this.cleanup();
// mark as open
this.readyState = 'open';
this.emit('open');
// add new subs
var socket = this.engine;
this.subs.push(on(socket, 'data', bind(this, 'ondata')));
this.subs.push(on(socket, 'ping', bind(this, 'onping')));
this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
this.subs.push(on(socket, 'error', bind(this, 'onerror')));
this.subs.push(on(socket, 'close', bind(this, 'onclose')));
this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
};
/**
* Called upon a ping.
*
* @api private
*/
onping() {
this.lastPing = new Date().getTime();
this.emitAll('ping');
};
/**
* Called upon a packet.
*
* @api private
*/
onpong() {
const diff = new Date().getTime() - this.lastPing;
this.emitAll('pong', diff);
};
/**
* Called with data.
*
* @api private
*/
ondata(data) {
this.decoder.add(data);
};
/**
* Called when parser fully decodes a packet.
*
* @api private
*/
ondecoded(packet) {
this.emit('packet', packet);
};
/**
* Called upon socket error.
*
* @api private
*/
onerror(err) {
debug('error', err);
this.emitAll('error', err);
};
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @api public
*/
socket(nsp: string, opts): Socket {
let socket = this.nsps[nsp];
if (!socket) {
socket = new Socket(this, nsp, opts);
this.nsps[nsp] = socket;
socket.on('connecting', () => {
console.log('onConnecting');
if (!~indexOf(this.connecting, socket)) {
this.connecting.push(socket);
console.log(this.connecting);
}
});
socket.on('connect', () => {
socket.id = this.generateId(nsp);
});
}
return socket;
};
/**
* Called upon a socket close.
*
* @param {Socket} socket
*/
destroy(socket) {
var index = indexOf(this.connecting, socket);
if (~index) this.connecting.splice(index, 1);
if (this.connecting.length) return;
this.close();
};
/**
* Writes a packet.
*
* @param {Object} packet
* @api private
*/
packet(packet) {
debug('writing packet %j', packet);
var self = this;
if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
if (!self.encoding) {
// encode, then write to engine with result
self.encoding = true;
this.encoder.encode(packet, function (encodedPackets) {
for (var i = 0; i < encodedPackets.length; i++) {
self.engine.write(encodedPackets[i], packet.options);
}
self.encoding = false;
self.processPacketQueue();
});
} else { // add packet to the queue
self.packetBuffer.push(packet);
}
};
/**
* If packet buffer is non-empty, begins encoding the
* next packet in line.
*
* @api private
*/
processPacketQueue() {
if (this.packetBuffer.length > 0 && !this.encoding) {
var pack = this.packetBuffer.shift();
this.packet(pack);
}
};
/**
* Clean up transport subscriptions and packet buffer.
*
* @api private
*/
cleanup() {
debug('cleanup');
var subsLength = this.subs.length;
for (var i = 0; i < subsLength; i++) {
var sub = this.subs.shift();
sub.destroy();
}
this.packetBuffer = [];
this.encoding = false;
this.lastPing = null;
this.decoder.destroy();
};
/**
* Close the current socket.
*
* @api private
*/
close() {
return this.disconnect()
}
disconnect() {
debug('disconnect');
this.skipReconnect = true;
this.reconnecting = false;
if ('opening' === this.readyState) {
// `onclose` will not fire because
// an open event never happened
this.cleanup();
}
this.backoff.reset();
this.readyState = 'closed';
if (this.engine) this.engine.close();
};
/**
* Called upon engine close.
*
* @api private
*/
onclose(reason) {
debug('onclose');
this.cleanup();
this.backoff.reset();
this.readyState = 'closed';
this.emit('close', reason);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
};
/**
* Attempt a reconnection.
*
* @api private
*/
reconnect() {
if (this.reconnecting || this.skipReconnect) return this;
var self = this;
if ((<any>this.backoff).attempts >= this._reconnectionAttempts) {
debug('reconnect failed');
this.backoff.reset();
this.emitAll('reconnect_failed');
this.reconnecting = false;
} else {
var delay = this.backoff.duration();
debug('will wait %dms before reconnect attempt', delay);
this.reconnecting = true;
var timer = setTimeout(function () {
if (self.skipReconnect) return;
debug('attempting reconnect');
self.emitAll('reconnect_attempt', (<any>self.backoff).attempts);
self.emitAll('reconnecting', (<any>self.backoff).attempts);
// check again for the case socket closed in above events
if (self.skipReconnect) return;
self.open(function (err) {
if (err) {
debug('reconnect attempt error');
self.reconnecting = false;
self.reconnect();
self.emitAll('reconnect_error', err.data);
} else {
debug('reconnect success');
self.onreconnect();
}
});
}, delay);
this.subs.push({
destroy: function () {
clearTimeout(timer);
}
});
}
}
/**
* Called upon successful reconnect.
*
* @api private
*/
onreconnect() {
var attempt = (<any>this.backoff).attempts;
this.reconnecting = false;
this.backoff.reset();
this.updateSocketIds();
this.emitAll('reconnect', attempt);
}
}
<file_sep>/src/public_api.ts
import { url, Url } from './url';
import { Manager, ManagerOpts } from './manager';
import { Socket } from './socket';
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io-client');
export const managers = {};
const cache = managers;
export interface ConnectOption extends ManagerOpts { }
export type ConnectFunction = (uri: string, opts: ConnectOption) => Socket;
export const connect: ConnectFunction = (uri: string, opts: ConnectOption): Socket => {
if (typeof uri === 'object') {
opts = uri;
uri = undefined;
}
opts = opts || {};
const parsed: Url = url(uri);
const source = parsed.source;
const id = parsed.id;
const path = parsed.path;
const sameNamespace = cache[id] && path in cache[id].nsps;
const newConnection = opts.forceNew || opts['force new connection'] ||
false === opts.multiplex || sameNamespace;
let io: Manager;
if (newConnection) {
debug('ignoring socket cache for %s', source);
io = new Manager(source, opts);
} else {
if (!cache[id]) {
debug('new io instance for %s', source);
cache[id] = new Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.query;
}
return io.socket(parsed.path, opts);
}
export const protocol = parser.protocol;
export { Manager } from './manager';
export { Socket } from './socket';
<file_sep>/src/socket-subject.ts
import { Subject, merge, Subscriber, Subscription, fromEvent } from 'rxjs';
import { Socket, connect, ConnectOption } from './public_api';
export class SocketSubject<T> extends Subject<T> {
socket: Socket;
constructor(
public url: string,
public options?: ConnectOption
) {
super();
}
next(value?: T): void {
this.socket.send(value);
}
error(err: any): void {
super.error(err);
}
complete(): void {
this.socket.close();
super.complete();
}
unsubscribe(): void {
this.socket.close();
super.unsubscribe();
}
_subscribe(subscriber: Subscriber<T>): Subscription {
this.socket = connect(this.url, {});
this.socket.onconnect = () => {
this.socket.connected = true;
this.socket.on('message', (data: T) => {
super.next(data);
});
merge(
fromEvent(this.socket, 'error'),
fromEvent(this.socket, 'connect_error'),
fromEvent(this.socket, 'reconnect_error'),
).subscribe(err => this.error(err));
merge(
fromEvent(this.socket, 'disconnect'),
fromEvent(this.socket, 'connect_timeout'),
fromEvent(this.socket, 'reconnect_failed'),
).subscribe(() => {
this.complete();
});
}
return super._subscribe(subscriber);
}
}
<file_sep>/dist/manager.d.ts
import eio = require('engine.io-client');
import Backoff = require('backo2');
import Emitter = require('component-emitter');
import { Socket } from './socket';
export interface ManagerOpts extends eio.SocketOptions {
forceNew?: boolean;
multiplex?: boolean;
path?: string;
reconnection?: boolean;
reconnectionAttempts?: number;
reconnectionDelay?: number;
reconnectionDelayMax?: number;
randomizationFactor?: number;
timeout?: number;
autoConnect?: boolean;
host?: string;
hostname?: string;
secure?: boolean;
port?: string;
query?: Object;
upgrade?: boolean;
forceJSONP?: boolean;
jsonp?: boolean;
forceBase64?: boolean;
enablesXDR?: boolean;
timestampParam?: string;
timestampRequests?: boolean;
policyPost?: number;
rememberUpgrade?: boolean;
onlyBinaryUpgrades?: boolean;
pfx?: string;
key?: string;
passphrase?: string;
cert?: string;
ca?: string | string[];
ciphers?: string;
rejectUnauthorized?: boolean;
}
export declare class Manager extends Emitter {
opts?: ManagerOpts;
nsps: {
[namespace: string]: Socket;
};
subs: any;
backoff: Backoff;
_reconnectionDelay: any;
_reconnectionDelayMax: any;
_randomizationFactor: any;
readyState: string;
connecting: Socket[];
lastPing: number;
encoding: boolean;
packetBuffer: any;
encoder: any;
decoder: any;
autoConnect: boolean;
engine: any;
skipReconnect: boolean;
_timeout: any;
_reconnection: boolean;
uri: string;
constructor(uri: string | ManagerOpts, opts?: ManagerOpts);
/**
* Propagate given event to sockets and emit on `this`
*
* @api private
*/
emitAll(...args: any[]): void;
/**
* Update `socket.id` of all sockets
*
* @api private
*/
updateSocketIds(): void;
generateId(nsp: string): string;
reconnection(v: boolean): this | boolean;
_reconnectionAttempts: any;
reconnectionAttempts(v: number): this | number;
reconnectionDelay(v?: number): number | this;
randomizationFactor(v?: number): number | this;
reconnectionDelayMax(v?: number): number | this;
timeout(v?: number): this | number;
reconnecting: any;
private maybeReconnectOnOpen;
open(fn?: (err?: any) => void): this;
connect(fn?: (err?: any) => void): this;
/**
* Called upon transport open.
*
* @api private
*/
onopen(): void;
/**
* Called upon a ping.
*
* @api private
*/
onping(): void;
/**
* Called upon a packet.
*
* @api private
*/
onpong(): void;
/**
* Called with data.
*
* @api private
*/
ondata(data: any): void;
/**
* Called when parser fully decodes a packet.
*
* @api private
*/
ondecoded(packet: any): void;
/**
* Called upon socket error.
*
* @api private
*/
onerror(err: any): void;
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @api public
*/
socket(nsp: string, opts: any): Socket;
/**
* Called upon a socket close.
*
* @param {Socket} socket
*/
destroy(socket: any): void;
/**
* Writes a packet.
*
* @param {Object} packet
* @api private
*/
packet(packet: any): void;
/**
* If packet buffer is non-empty, begins encoding the
* next packet in line.
*
* @api private
*/
processPacketQueue(): void;
/**
* Clean up transport subscriptions and packet buffer.
*
* @api private
*/
cleanup(): void;
/**
* Close the current socket.
*
* @api private
*/
close(): void;
disconnect(): void;
/**
* Called upon engine close.
*
* @api private
*/
onclose(reason: any): void;
/**
* Attempt a reconnection.
*
* @api private
*/
reconnect(): this;
/**
* Called upon successful reconnect.
*
* @api private
*/
onreconnect(): void;
}
<file_sep>/dist/global.d.ts
declare const _global: {
[name: string]: any;
};
export { _global as global };
<file_sep>/src/socket.ts
import { Manager, ManagerOpts } from './manager';
/**
* Module dependencies.
*/
import parser = require('socket.io-parser');
import Emitter = require('component-emitter');
import toArray = require('to-array');
import { on } from './on';
import bind = require('component-bind');
import debug2 = require('debug');
const debug: debug2.IDebugger = debug2('socket.io-client:socket');
import parseqs = require('parseqs');
import hasBin = require('has-binary2');
/**
* Internal events (blacklisted).
* These events can't be emitted by the user.
*
* @api private
*/
var events = {
connect: 1,
connect_error: 1,
connect_timeout: 1,
connecting: 1,
disconnect: 1,
error: 1,
reconnect: 1,
reconnect_attempt: 1,
reconnect_failed: 1,
reconnect_error: 1,
reconnecting: 1,
ping: 1,
pong: 1
};
/**
* Shortcut to `Emitter#emit`.
*/
var emit = Emitter.prototype.emit;
/**
* `Socket` constructor.
*
* @api public
*/
export class Socket extends Emitter {
json: Socket;
id: string;
ids: any;
acks: any;
receiveBuffer: any;
sendBuffer: any;
connected: boolean = false;
disconnected: boolean = true;
flags: any;
query: any;
io: Manager;
constructor(io: Manager | string, public nsp?: string, opts?: any) {
super();
if (typeof io === 'object') {
this.io = io;
}
this.json = this; // compat
this.ids = 0;
this.acks = {};
this.receiveBuffer = [];
this.sendBuffer = [];
this.flags = {};
if (opts && opts.query) {
this.query = opts.query;
}
if (this.io.autoConnect) this.open();
}
on(event: 'connect', listener: () => void): Emitter;
on(event: 'connect_error', listener: (err: Error) => void): Emitter;
on(event: 'connect_timeout', listener: () => void): Emitter;
on(event: 'connecting', listener: (attempt: number) => void): Emitter;
on(event: 'disconnect', listener: () => void): Emitter;
on(event: 'error', listener: (err: Error) => void): Emitter;
on(event: 'reconnect', listener: (attempt: number) => void): Emitter;
on(event: 'reconnect_attempt', listener: () => void): Emitter;
on(event: 'reconnect_failed', listener: () => void): Emitter;
on(event: 'reconnect_error', listener: (err: Error) => void): Emitter;
on(event: 'reconnecting', listener: (attempt: number) => void): Emitter;
on(event: 'ping', listener: () => void): Emitter;
on(event: 'pong', listener: () => void): Emitter;
on(event: 'message', listener: (data: any) => void): Emitter;
on(event: string, listener: Function): Emitter {
return super.on(event, listener);
}
/**
* Subscribe to open, close and packet events
*
* @api private
*/
subs: any;
subEvents() {
if (this.subs) return;
var io = this.io;
this.subs = [
on(io, 'open', bind(this, 'onopen')),
on(io, 'packet', bind(this, 'onpacket')),
on(io, 'close', bind(this, 'onclose'))
];
}
open(): Socket {
return this.connect();
}
connect(): Socket {
if (this.connected) return this;
this.subEvents();
this.io.open(); // ensure open
if ('open' === this.io.readyState) this.onopen();
this.emit('connecting');
return this;
}
send(...args: any[]) {
args.unshift('message');
this.emit.apply(this, args);
return this;
}
emit(ev: string, ...args: any[]): boolean {
if (events.hasOwnProperty(ev)) {
emit.apply(this, arguments);
return true;
}
let packet: any = {
type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
data: args
};
packet.options = {};
packet.options.compress = !this.flags || false !== this.flags.compress;
if ('function' === typeof args[args.length - 1]) {
debug('emitting packet with ack id %d', this.ids);
this.acks[this.ids] = args.pop();
packet.id = this.ids++;
}
if (this.connected) {
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
this.flags = {};
return true;
}
packet(packet) {
packet.nsp = this.nsp;
this.io.packet(packet);
}
onopen() {
debug('transport is open - connecting');
// write connect packet if necessary
if ('/' !== this.nsp) {
if (this.query) {
var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
debug('sending connect packet with query %s', query);
this.packet({ type: parser.CONNECT, query: query });
} else {
this.packet({ type: parser.CONNECT });
}
}
}
onclose(reason) {
debug('close (%s)', reason);
this.connected = false;
this.disconnected = true;
delete this.id;
this.emit('disconnect', reason);
}
onpacket(packet) {
var sameNamespace = packet.nsp === this.nsp;
var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
if (!sameNamespace && !rootNamespaceError) return;
switch (packet.type) {
case parser.CONNECT:
this.onconnect();
break;
case parser.EVENT:
this.onevent(packet);
break;
case parser.BINARY_EVENT:
this.onevent(packet);
break;
case parser.ACK:
this.onack(packet);
break;
case parser.BINARY_ACK:
this.onack(packet);
break;
case parser.DISCONNECT:
this.ondisconnect();
break;
case parser.ERROR:
this.emit('error', packet.data);
break;
}
}
onevent(packet) {
var args = packet.data || [];
debug('emitting event %j', args);
if (null != packet.id) {
debug('attaching ack callback to event');
args.push(this.ack(packet.id));
}
if (this.connected) {
emit.apply(this, args);
} else {
this.receiveBuffer.push(args);
}
}
ack(id) {
var self = this;
var sent = false;
return function () {
// prevent double callbacks
if (sent) return;
sent = true;
var args = toArray(arguments);
debug('sending ack %j', args);
self.packet({
type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
id: id,
data: args
});
};
}
private onack(packet) {
var ack = this.acks[packet.id];
if ('function' === typeof ack) {
debug('calling ack %s with %j', packet.id, packet.data);
ack.apply(this, packet.data);
delete this.acks[packet.id];
} else {
debug('bad ack %s', packet.id);
}
}
onconnect() {
this.connected = true;
this.disconnected = false;
this.emit('connect');
this.emitBuffered();
}
emitBuffered() {
var i;
for (i = 0; i < this.receiveBuffer.length; i++) {
emit.apply(this, this.receiveBuffer[i]);
}
this.receiveBuffer = [];
for (i = 0; i < this.sendBuffer.length; i++) {
this.packet(this.sendBuffer[i]);
}
this.sendBuffer = [];
}
private ondisconnect() {
debug('server disconnect (%s)', this.nsp);
this.destroy();
this.onclose('io server disconnect');
}
destroy() {
if (this.subs) {
// clean subscriptions to avoid reconnections
for (var i = 0; i < this.subs.length; i++) {
this.subs[i].destroy();
}
this.subs = null;
}
this.io.destroy(this);
}
close(): Socket {
return this.disconnect();
}
disconnect(): Socket {
if (this.connected) {
debug('performing disconnect (%s)', this.nsp);
this.packet({ type: parser.DISCONNECT });
}
// remove socket from pool
this.destroy();
if (this.connected) {
// fire events
this.onclose('io client disconnect');
}
return this;
}
compress(compress: boolean): Socket {
this.flags.compress = compress;
return this;
}
binary(binary) {
this.flags.binary = binary;
return this;
}
}
<file_sep>/dist/socket-subject.d.ts
import { Subject, Subscriber, Subscription } from 'rxjs';
import { Socket, ConnectOption } from './public_api';
export declare class SocketSubject<T> extends Subject<T> {
url: string;
options?: ConnectOption;
socket: Socket;
constructor(url: string, options?: ConnectOption);
next(value?: T): void;
error(err: any): void;
complete(): void;
unsubscribe(): void;
_subscribe(subscriber: Subscriber<T>): Subscription;
}
| b0e29a7488ecb0d1e10e0eb64ae68e975bd0f84a | [
"Markdown",
"TypeScript"
] | 13 | TypeScript | iwe7/ims-socket.io-client | 938dd2d8991f7910a873e9328c029029400961f5 | 690cf261c446bd7dc95578e28d15d364207853de |
refs/heads/master | <file_sep>// 引入mockjs
const Mock = require('mockjs');
// 获取 mock.Random 对象
const Random = Mock.Random;
// mock一组数据
const produceNewsData = function() {
var result = [];
for (let i = 0; i < 5; i++) {
var orderLine = [];
var lineLength = Random.integer(1, 5);
console.log(Random.integer(1, 5));
for (let i = 0; i < lineLength; i++) {
orderLine.push({
image: Random.image('200x100'),
price: Random.float(1, 1000),
num: Random.integer(1, 10),
desc: Random.ctitle(2, 5) + '重约' + Random.integer(1, 5000) + 'g',
title: Random.ctitle(5, 8)
});
}
var province = Random.province();
var city = Random.city(province);
var county = Random.county(city);
var stateList = [
{ name: 'need_pay', title: '待付款' },
{ name: 'need_send', title: '待发货' },
{ name: 'need_pay', title: '完成' }];
var newArticleObject = {
title: Random.csentence(5, 10), // Random.csentence( min, max )
state: stateList[Random.integer(0, 2)], // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码
name: '' + Random.natural(), // Random.cname() 随机生成一个常见的中文姓名
message: '产品共计1 合计 ¥ 20(含运费¥ 1)', // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
otherMessage: '运费保险 等', // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
orderLine: orderLine,
userAddress: county
};
result.push(newArticleObject);
};
return {
result: result
};
};
// Mock.mock( url, post/get , 返回的数据);
Mock.mock('/get/orders', 'post', produceNewsData);
const onProduct = function() {
var orderLine = [];
var lineLength = Random.integer(1, 5);
console.log(Random.integer(1, 5));
for (let i = 0; i < lineLength; i++) {
orderLine.push({
image: Random.image('200x100'),
price: Random.float(1, 1000),
num: Random.integer(1, 10),
desc: Random.ctitle(2, 5) + '重约' + Random.integer(1, 5000) + 'g',
title: Random.ctitle(5, 8)
});
}
var province = Random.province();
var city = Random.city(province);
var county = Random.county(city);
var stateList = [
{ name: 'need_pay', title: '待付款' },
{ name: 'need_send', title: '待发货' },
{ name: 'need_pay', title: '完成' }];
var newArticleObject = {
title: Random.csentence(5, 10), // Random.csentence( min, max )
state: stateList[Random.integer(0, 2)], // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码
name: '' + Random.natural(), // Random.cname() 随机生成一个常见的中文姓名
message: '产品共计1 合计 ¥ 20(含运费¥ 1)', // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
otherMessage: '运费保险 等', // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串
orderLine: orderLine,
userAddress: county,
currentContact: { name: Random.ctitle(2, 4), tel: '' + Random.integer(11), address: county }
};
return {
result: newArticleObject
};
};
Mock.mock('/get/orderDetail', 'post', onProduct);
const homePage = function() {
var allData = { hotCat: '', images: '', competitiveProducts: '' };
var hotRowLine = [];
var hotCatLine = [];
for (let i = 0; i < 2; i++) {
hotCatLine = [];
for (let j = 0; j < 4; j++) {
hotCatLine.push({
image: Random.image('200x200'),
productId: Random.integer(1000, 8000),
name: Random.ctitle(2, 4),
price: Random.integer(2, 100) + '积分'
});
}
hotRowLine.push(hotCatLine);
}
var images = [];
for (let i = 0; i < 4; i++) {
images.push({
image: Random.image('500x500'),
articleId: Random.integer(1000, 8000)
});
}
var competitiveProducts = { name: '精品推荐', product: [] };
for (let i = 0; i < 9; i++) {
competitiveProducts.product.push({
image: Random.image('80x80'),
articleId: Random.integer(1000, 8000),
name: Random.integer(1000, 8000)
});
}
allData.hotCat = hotRowLine;
allData.images = images;
allData.competitiveProducts = competitiveProducts;
return {
result: allData
};
};
Mock.mock('/get/homePageVal', 'post', homePage);
const homeProdcutList = function() {
var products = [];
for (let j = 0; j < 10; j++) {
products.push({
image: Random.image('120x150'),
productId: Random.integer(1000, 8000),
name: Random.ctitle(2, 4),
desc: Random.ctitle(6, 10),
num: Random.integer(2, 100),
price: Random.integer(2, 100) + '积分'
});
}
return {
result: products
};
};
Mock.mock('/get/goodsList', 'post', homeProdcutList);
var getGoodsSku = function() {
var skuJson = [{
'dim': 1, 'saleAttrList': [
{ 'skuIds': [4527256, 4933449, 4512471, 4512467, 4460331, 4047307],
'imagePath': 'jfs/t5698/100/4596147819/145612/2cce3ed1/59521259Ne7404ff7.jpg', 'saleValue': '\u6a31\u82b1\u7c89' },
{ 'skuIds': [4460325, 5114935, 4325123], 'imagePath': 'jfs/t6598/73/190892520/246785/46883a6e/593ba628N8794c6a6.jpg', 'saleValue': '\u6d45\u84dd\u8272' },
{ 'skuIds': [4390096, 4512445, 4460333, 4512465, 4780389, 4791052], 'imagePath': 'jfs/t3076/42/8593902551/206108/fdb1a60f/58c60fc3Nf9faa2fa.jpg', 'saleValue': '\u78e8\u7802\u9ed1' },
{ 'skuIds': [3915537], 'imagePath': 'jfs/t5050/1/1165634167/293759/f54c5ed2/58ed8800N261978fb.jpg', 'saleValue': '\u84dd\u7eff\u8272' },
{ 'skuIds': [4512487, 4390094], 'imagePath': 'jfs/t4621/258/2224761053/195204/fa95be0d/58ed8c2fN2a4c2cc6.jpg', 'saleValue': '\u94c2\u94f6\u7070' },
{ 'skuIds': [3846673, 4512491, 4032215, 4512459, 4780359, 4460347], 'imagePath': 'jfs/t6553/346/1473938601/145939/f7796bfa/59521206N527bb108.jpg', 'saleValue': '\u9999\u69df\u91d1' }], 'saleName': '\u989c\u8272' }, { 'dim': 2, 'saleAttrList': [{ 'skuIds': [4527256, 3846673, 4390096, 4512445, 4512467, 5114935, 4512459, 4512487, 4390094, 3915537], 'imagePath': null, 'saleValue': '3GB 32GB' },
{ 'skuIds': [4460325, 4460333, 4512471, 4512465, 4460331, 4047307, 4512491, 4032215, 4460347, 4791052, 4325123], 'imagePath': null, 'saleValue': '4GB 64GB' },
{ 'skuIds': [4933449, 4780359, 4780389], 'imagePath': null, 'saleValue': '4GB 64GB\uff08\u79fb\u52a8\u5b9a\u5236\u5168\u7f51\u901a\uff09' }], 'saleName': '\u7248\u672c' }, { 'dim': 3, 'saleAttrList': [
{ 'skuIds': [4512445, 4512471, 4512465, 4512467, 4512491, 4512459, 4512487], 'imagePath': null, 'saleValue': '\u4fdd\u9669\u5957\u88c5' },
{ 'skuIds': [4460325, 4460333, 4460331, 4460347], 'imagePath': null, 'saleValue': '\u5b9a\u4f4d\u5957\u88c5' },
{ 'skuIds': [4527256, 3846673, 4933449, 4390096, 5114935, 4047307, 4032215, 4390094, 3915537, 4780359, 4780389, 4791052, 4325123], 'imagePath': null, 'saleValue': '\u88f8\u673a' }], 'saleName': '\u8d2d\u4e70\u540d\u79f0' }];
var skuTree = [];
var skuList = [];
var skus = [];
for (let i = 0; i < skuJson.length; i++) {
skuTree.push({
'k_s': skuJson[i].dim + '',
k: skuJson[i].saleName,
v: []
});
for (let j = 0; j < skuJson[i].saleAttrList.length; j++) {
var attrId = Random.integer(100000, 1000000);
skuTree[skuTree.length - 1].v.push({
id: attrId + '',
name: skuJson[i].saleAttrList[j].saleValue,
imgUrl: 'http://img13.360buyimg.com/n0/' + skuJson[i].saleAttrList[j].imagePath
});
for (let k = 0; k < skuJson[i].saleAttrList[j].skuIds.length; k++) {
if (skus.indexOf(skuJson[i].saleAttrList[j].skuIds[k]) < 0) {
const attr = skuJson[i].dim + '';
skus.push(skuJson[i].saleAttrList[j].skuIds[k]);
skuList.push({
price: Random.integer(10, 1000),
id: skuJson[i].saleAttrList[j].skuIds[k]
});
skuList[skuList.length - 1][attr] = attrId;
} else {
skuList[skus.indexOf(skuJson[i].saleAttrList[j].skuIds[k])][skuJson[i].dim] = attrId;
}
}
}
}
console.log(skuTree);
console.log(skuList);
console.log(skus);
return {
result: { tree: skuTree, list: skuList }
};
};
Mock.mock('/get/getGoodsSku', 'post', getGoodsSku);
var thumbs = [
'jfs/t6520/331/1089001978/81731/75164eb7/594a37a7Nbf238ce7.jpg',
'jfs/t6058/155/969572637/20614/6fd919e4/592e8d89Ncd9821ed.jpg',
'g15/M07/12/0C/rBEhWVJvaNUIAAAAAAFO23_VM5cAAEufgLgwAcAAU7z943.jpg',
' jfs/t5167/246/90241913/148408/27e07fda/58f87327Nb3418960.jpg',
'jfs/t4222/236/3792324942/405127/5e6895a9/58e83dd5Ne06d95d0.jpg',
'jfs/t5230/288/100503114/197424/14915453/58f87322N8a1272d6.jpg',
'jfs/t6079/16/2411000961/295727/16cc1c6e/5940ff2cN4a349a84.jpg',
'jfs/t6079/16/2411000961/295727/16cc1c6e/5940ff2cN4a349a84.jpg',
'g13/M01/05/04/rBEhU1KEekYIAAAAAAHfQlkjaqAAAFd9gGYcpYAAd9a410.jpg',
'jfs/t10852/69/1019216077/418065/f937865f/59db1f8cN93efed0c.jpg',
'jfs/t4639/245/582026275/111556/6aa8606a/58d1fd7fN46d644b0.jpg',
'jfs/t7465/247/4202349615/70427/581818a/5a01a321N41e81840.jpg',
'jfs/t2650/105/1117442102/208760/827e92c4/57335747N0ce77b7c.jpg',
'jfs/t3586/127/1594906486/138769/bb837a48/582be2fdN907f437f.jpg',
'jfs/t7531/21/3621555298/399169/a4b6d34f/59c21c01Nce4d33c0.jpg',
'jfs/t5782/94/951807027/107102/b5d91a5a/59228eecN541c61c1.jpg',
'jfs/t6067/50/5425799928/316261/413a82f1/596c339dN8d107fba.jpg',
'jfs/t4366/71/2045605853/291379/56c87b03/58ca4dc5N1c303706.jpg',
'jfs/t3997/155/920002377/372314/813c1345/586210f1Naf213509.jpg',
'jfs/t6025/297/1199794256/308597/1319a39/59312087N9e907313.jpg',
'jfs/t3316/327/925534159/264012/36d737e4/58185d27Nf11468eb.jpg',
'jfs/t9010/353/1021381481/286573/b6a887b6/59baaca6N33c86fb3.jpg',
'jfs/t5698/100/4596147819/145612/2cce3ed1/59521259Ne7404ff7.jpg',
'jfs/t9916/316/2305170278/62366/3a1447f6/59f2f7d2N38f816bb.jpg',
'jfs/t5656/183/8357361424/250180/594d9590/5978234bNdccfc0ec.jpg',
'jfs/t10300/119/1747598257/168815/372e79cf/59e6b1caNdba1e2b6.jpg',
'jfs/t8287/350/2427159969/142433/430fb21c/59ccd17eNebed7612.jpg',
'jfs/t5653/334/7142475715/216433/adfd20f7/596f05b8Ne3347e62.jpg',
'jfs/t8284/363/1326459580/71585/6d3e8013/59b857f2N6ca75622.jpg',
'jfs/t5845/283/3029282901/139575/97407784/593692c3Neba552ea.jpg',
'jfs/t5014/17/152292429/254365/126d8e97/58db914aNb485f8fa.jpg',
'jfs/t4909/265/281173291/187118/46eff65/58ddfd62Naeaabb3b.jpg',
'jfs/t3667/111/2238224664/230338/88b1271d/584654fcNa07f2c3e.jpg',
'jfs/t12052/327/27615067/123900/a328b3ef/5a01c315Nb0176e3c.jpg',
'jfs/t6313/9/361775681/80331/7a647145/593e4ec1Nf8874945.jpg',
'jfs/t3373/247/1000083455/157057/387db100/581a9bcbN85e5f0a2.jpg',
'jfs/t6295/248/1683884215/269723/b3c43437/5955c6e7N1e18d758.jpg',
'jfs/t13372/101/13325431/70427/581818a/5a01a638N9c082481.jpg',
'jfs/t1846/284/1504859992/95973/28b89716/565ff1b9N85cef595.jpg',
'jfs/t10888/335/1248622203/92633/a0f69a17/59de1802Nacae2eb2.jpg',
'jfs/t7303/35/4452071055/360758/36794399/5a014e30N3b7c1016.jpg',
'jfs/t3301/16/1615084619/137077/bc52150e/57d0c513Nd51ff9a3.jpg',
'jfs/t3106/271/3159789861/182436/8857a9a1/57ecc9d4N5183cfc5.jpg',
'jfs/t10546/119/1007692688/358419/49ab51a9/59db1ed4Nac9024b8.jpg',
'jfs/t7072/70/770659273/224621/51def495/59840c11N8380accc.jpg',
'jfs/t2500/140/2373001479/542205/159c60a2/56cd08ecN866527bb.jpg',
'jfs/t3475/235/594632011/135582/af801e4f/580f12bdN5659471e.jpg',
'jfs/t8740/345/1324626863/267121/b87aaf29/59b79539N5ee8a31f.jpg',
'jfs/t12826/258/453941393/77903/94670e7a/5a0bbc0aN601a57e8.jpg',
'jfs/t10315/227/1754541026/256693/980afae7/59e5bdf4Nb6b9904a.jpg',
'jfs/t4756/276/2202072274/229228/2dabe2e4/58f9e5fdNb6d3484f.jpg',
'jfs/t8215/26/1298631064/94425/febfd44/59b9e23cN3f58cd96.jpg',
'jfs/t5641/365/6763058847/371625/423b9ba5/596c2effN126fb68d.jpg',
'jfs/t9349/45/1532833793/200090/267e3e56/59bb72d9N11feae8b.jpg',
'jfs/t7750/259/1312711713/236360/5938a219/599c1062Nd651d2c1.jpg',
'jfs/t3094/281/4693364807/209161/b3af192b/584fcf74Nfe1748ed.jpg',
'jfs/t8284/363/1326459580/71585/6d3e8013/59b857f2N6ca75622.jpg',
'jfs/t5335/39/1553366100/209772/32105f74/5911bac3N5d51d2aa.jpg',
'jfs/t7519/271/716725745/182136/ba4736cf/59968f76N305fcda0.jpg',
'jfs/t5860/31/1435315325/195398/ba8744bf/59264e07N797a8757.jpg',
'jfs/t5881/279/1484279631/216483/4bbce005/592694e3Nda6f85d6.jpg',
'jfs/t3376/108/2363165851/327545/686107c9/584f577aN18ce3b83.jpg',
'jfs/t6055/105/9785665789/242409/f32688e2/599644b9N40f563da.jpg',
'jfs/t4717/131/225494258/86027/36a57ccf/58dcd0baNd799945e.jpg',
'jfs/t8866/302/1981122529/278885/96ccd6f8/59c23186N32b4fc90.jpg',
'jfs/t5893/358/6006981394/188969/ff80aba/5966e95dNe5248b3d.jpg',
'jfs/t10285/132/1611057220/333194/a05da231/59e45767Na9fa8cd0.jpg',
'jfs/t10438/112/1205662754/210785/bf836347/59ddcd56N848dc34b.jpg',
'jfs/t7201/59/2444944006/242409/f32688e2/599646fbN0329f015.jpg',
'jfs/t6400/251/1498502133/126650/2ade0e70/5951fa4aN6c972662.jpg',
'jfs/t967/1/1478624280/237831/cd2dd740/573001adN435be1da.jpg',
'jfs/t2905/300/3847999660/312900/a9fb3e68/579b201cNed7566f1.jpg',
'jfs/t11248/33/1480957878/70427/581818a/5a01a5b9N32675e8a.jpg',
'jfs/t6055/105/9785665789/242409/f32688e2/599644b9N40f563da.jpg',
'jfs/t5857/57/3540884961/258886/ed4e13c/593e4a8eNc91d6b28.jpg',
'jfs/t4009/231/2184886632/159441/419975d9/58a43cdaN710d8e7e.jpg',
'jfs/t3238/281/6935622958/250180/594d9590/58afdbdbNf0d5dfa7.jpg',
'jfs/t3724/297/70731013/253611/a62cf5f0/57fe0b76N977c8829.jpg',
'jfs/t5941/277/303563741/206302/bee5dd6a/59269427N60666d2c.jpg',
'jfs/t2269/171/2134075275/79011/8c63b3b8/56b1b888N419ccf6c.jpg',
'jfs/t8239/88/1957124504/330499/de78e394/59c1f21fN37a48a9a.jpg',
'jfs/t7645/310/1491077037/143323/424b6c10/599d21b3N75095691.jpg',
'jfs/t9883/249/1396078625/156545/91c4388a/59e08ddaN5a0fd12c.jpg',
'jfs/t3250/72/1629247361/133742/e0c6726d/57d11c72N093250ec.jpg',
'jfs/t6019/205/157969858/195398/ba8744bf/59264e5dN9862a0ac.jpg',
'jfs/t4249/136/395545190/195516/2d25b5dc/58b3e356N4a8f9575.jpg',
'jfs/t5839/335/9832328676/329980/98ecec34/59897c85Ncf1e2cd5.jpg',
'jfs/t7438/195/493717560/185814/559e2ca8/5993e164Nda995521.jpg',
'jfs/t5113/211/143860912/100416/cb06f1da/58f96b45Nda2a07b6.jpg',
'jfs/t6043/305/5636125253/87985/21230f90/596f169aN1246fe10.jpg'
];
var getGoodsCartMessage = function() {
var returnVal = {
title: Random.ctitle(2, 4),
num: Random.integer(1, 10),
thumb: 'http://img13.360buyimg.com/n0/' + thumbs[Random.integer(0, thumbs.length)],
price: Random.integer(100, 100000),
desc: Random.ctitle(6, 8)
};
return {
result: returnVal
};
};
Mock.mock('/get/getGoodsCartMessage', 'post', getGoodsCartMessage);
var getGoodsClassList = function() {
var result = [
{ index: 1, id: 6196, text: '厨具', children: [] },
{ index: 2, id: 9847, text: '家具', children: [] },
{ index: 3, id: 9987, text: '手机', children: [] },
{ index: 4, id: 1319, text: '母婴', children: [] },
{ index: 5, id: 12218, text: '生鲜', children: [] },
{ index: 6, id: 12259, text: '酒类', children: [] },
{ index: 7, id: 5025, text: '钟表', children: [] },
{ index: 8, id: 9192, text: '医药保健', children: [] },
{ index: 9, id: 6994, text: '宠物生活', children: [] },
{ index: 10, id: 652, text: '数码', children: [] }
];
for (var i = 0; i < result.length; i++) {
var secondClass = [];
for (var j = 0; j < Random.integer(10, 20); j++) {
var thirdClass = [];
for (var k = 0; k <= Random.integer(10, 20); k++) {
thirdClass.push({ index: k, id: Random.integer(100000, 3000000), text: Random.ctitle(2, 4) });
}
secondClass.push({ index: j, id: Random.integer(100000, 3000000), text: Random.ctitle(2, 4), children: thirdClass });
}
result[i].children = secondClass;
}
return {
result: result
};
};
console.log(getGoodsClassList);
Mock.mock('/get/classList', 'post', getGoodsClassList);
<file_sep>import Vue from 'vue';
import Router from 'vue-router';
import { Lazyload, Cell, CellGroup } from 'vant';
import vantCss from 'vant-css';
Vue.use(Router);
Vue.use(Lazyload);
Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(vantCss);
const User = r => require.ensure([], () => r(require('./view/user')), 'user');
const Cart = r => require.ensure([], () => r(require('./view/cart')), 'cart');
const Goods = r => require.ensure([], () => r(require('./view/goods')), 'goods');
// const App = r => require.ensure([], () => r(require('./App')), 'App');
const Home = r => require.ensure([], () => r(require('./view/home')), 'home');
const Search = r => require.ensure([], () => r(require('./view/search_goods')), 'search');
const OrderList = r => require.ensure([], () => r(require('./view/order_list')), 'orderList');
const Classify = r => require.ensure([], () => r(require('./view/classify')), 'classify');
const OrderDetail = r => require.ensure([], () => r(require('./view/order')), 'orderDetail');
const goodsList = r => require.ensure([], () => r(require('./view/goods_list')), 'goodsList');
const routes = [
{
path: '*',
component: Home,
meta: {
title: '首页'
}
},
{
name: 'user',
component: User,
meta: {
title: '会员中心'
}
},
{
name: 'classify',
component: Classify,
meta: {
title: '会员中心'
}
},
{
name: 'search',
component: Search,
meta: {
title: '搜索'
}
},
{
name: 'cart',
component: Cart,
meta: {
title: '购物车'
}
},
{
name: 'goods',
component: Goods,
meta: {
title: '商品详情'
}
},
{
name: 'orders',
component: OrderList,
meta: {
title: '订单列表'
}
},
{
name: 'orderDetail',
component: OrderDetail,
meta: {
title: '订单详情'
}
},
{
name: 'goodsList',
component: goodsList,
meta: {
title: '产品列表'
}
}
];
// add route path
routes.forEach(route => {
route.path = route.path || '/' + (route.name || '');
});
const router = new Router({ routes });
router.beforeEach((to, from, next) => {
const title = to.meta && to.meta.title;
if (title) {
document.title = title;
}
next();
});
export {
router
};
<file_sep>import './common/rem';
import Vue from 'vue';
import App from './App.vue';
import { router } from './router';
import Vuex from 'vuex';
require('./mock.js');
Vue.use(Vuex);
Vue.directive('focus', {
// 当绑定元素插入到 DOM 中。
inserted: function(el) {
// 聚焦元素
el.focus();
}
});
const store = new Vuex.Store({}); // 这里你可能已经有其他 module
store.registerModule('vantStore', {
state: {
bottomActive: true,
headTitle: '首页',
goodsCart: []
},
mutations: {
updatebottomActive: function(state, payload) {
state.bottomActive = payload;
},
updateheadTitle: function(state, payload) {
state.headTitle = payload;
}
}
});
new Vue({
router,
store,
el: '#app',
render: h => h(App)
});
<file_sep># Vant-demo
Vant 示例页面汇总。
<img src="https://user-images.githubusercontent.com/13111533/35260626-824ae724-0047-11e8-9397-f1e259f55e74.gif" alt="demos" width="600" />
根据vant 官方demo 进行的进一步的拓展
``` bash
# 安装依赖
npm install
# 本地开发
# 通过 localhost:8080 访问页面
npm run dev
# 生产环境构建
npm run build
```
| 25dc0f40170a9f1df95716f57a3771265bbc3d08 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Judystudy/vant_shop | 8eaea680d4d8ade4a45b6f971a2b8c9b9e46c338 | ab2b993525ecf63f2f7969dd312a8153dd87f31f |
refs/heads/master | <file_sep>import React from 'react';
import './upload_button.css';
class UploadButton extends React.Component {
constructor(props) {
super(props);
this.state = {
filename: undefined,
invalid: undefined,
};
this.fileInput = React.createRef();
}
render() {
let filenameMessage = '';
if (this.state.filename) {
filenameMessage = `File uploaded: ${this.state.filename}`;
}
return (
<div className="upload-button-container">
<button className="upload-button" type="button" onClick={this.openFileDialog}>
Upload
</button>
<div className="upload-button-filename">
{filenameMessage}
</div>
<div className={`upload-button-invalid ${this.state.invalid ? '' : 'noshow'}`}>
Please upload your movie
</div>
<input
ref={this.fileInput}
type="file"
accept="video/*"
name="movie"
onChange={this.handleUpload}
style={{display: "none"}} />
</div>
);
}
openFileDialog = (e) => {
this.fileInput.current.click();
}
handleUpload = (e) => {
const file = this.getFile();
if (file) {
this.setState({
filename: file.name,
invalid: false,
})
}
}
getFile() {
return this.fileInput.current.files[0];
}
validate() {
if (!this.getFile()) {
this.setState({
invalid: true,
})
return false;
}
return true;
}
}
export default UploadButton;<file_sep>import React from 'react';
import './go_button.css';
class GoButton extends React.Component {
render() {
return (
<div>
<input type="submit" value="GO!" className="go-button"/>
</div>
);
}
}
export default GoButton;<file_sep>const express = require('express');
const multer = require('multer');
const path = require('path');
const util = require('util');
const {exec} = require('child_process');
const execAndWait = util.promisify(exec);
const LocationOption = {
TopLeft: 'top-left',
TopMiddle: 'top-middle',
TopRight: 'top-right',
BottomLeft: 'bottom-left',
BottomMiddle: 'bottom-middle',
BottomRight: 'bottom-right',
};
const storage = multer.diskStorage({
filename(req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const extension = file.originalname.split('.').pop();
cb(null, `${file.fieldname}-${uniqueSuffix}.${extension}`);
},
})
const upload = multer({storage});
const app = express();
const static = express.static(path.join(__dirname, 'build'));
app.use(static);
app.use('/timestamp', static);
function getIndex(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
}
app.get('/', getIndex);
app.get('/timestamp', getIndex)
function getTimestampCenter(location) {
switch (location) {
case LocationOption.TopLeft:
return {x: '20', y: '20'};
case LocationOption.TopMiddle:
return {x: '(w-text_w)/2', y: '20'};
case LocationOption.TopRight:
return {x: 'w-text_w-20', y: '20'};
case LocationOption.BottomLeft:
return {x: '20', y: 'h-text_h-20'};
case LocationOption.BottomMiddle:
return {x: '(w-text_w)/2', y: 'h-text_h-20'};
case LocationOption.BottomRight:
return {x: 'w-text_w-20', y:'h-text_h-20'};
default:
return getTimestampCenter(LocationOption.BottomMiddle);
}
}
async function postBurnTimecode(req, res) {
try {
const path = req.file.path;
const extension = req.file.path.split('.').pop();
const outputPath = path.substring(0, path.length - extension.length) + '-output.' + extension;
const location = req.body.location;
const {x, y} = getTimestampCenter(location);
const {stdout, stderr} = await execAndWait(
`ffmpeg -i ${path} -vf "drawtext=text='%{pts\\:hms}':fontsize=48:fontcolor=white:box=1:boxborderw=6:boxcolor=black@0.75:x=${x}:y=${y}" -c:a copy ${outputPath}`);
res.sendFile(outputPath);
} catch (e) {
res.send(`Error while processing file: ${e}`);
}
}
app.post('/burn-timecode', upload.single('movie'), postBurnTimecode);
app.post('//burn-timecode', upload.single('movie'), postBurnTimecode);
app.post('/timestamp/burn-timecode', upload.single('movie'), postBurnTimecode);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});<file_sep># Use the base App Engine Docker image, based on Ubuntu 16.0.4.
FROM gcr.io/google-appengine/nodejs
RUN apt-get update -y && \
apt-get install --no-install-recommends -y -q \
ffmpeg && \
apt-get clean
COPY . /app/
RUN npm install --unsafe-perm
# Set common env vars
ENV NODE_ENV production
ENV PORT 8080
# start
CMD ["npm", "start"]<file_sep>A React frontend and Express Node server to upload and burn timestamps into movies.
## Running locally
In the top-level directory, install all the dependencies:
```
npm install
```
Build the React application for deployment:
```
npm run build
```
Start the node server:
```
node server.js
```
This starts the server listening on port 8080. Go to `localhost:8080` to see the page.
## Requirements
npm, node.
The node server assumes that ffmpeg is installed.
| 3b954571ad157e61a1ba8188123ecd11a5d46f46 | [
"JavaScript",
"Dockerfile",
"Markdown"
] | 5 | JavaScript | tbondwilkinson/video-timestamps | e648894b8aadf754a5a51b0d222bcf93b42a291e | 907353ec43fc9929badfb4db5a2291d12004329a |
refs/heads/master | <repo_name>Oleg-Pashulia/Sequence<file_sep>/main.js
function sequence(startNumber, step) {
function plus() {
let a = startNumber
startNumber += step;
return a;
}
return plus;
}
let generatorOne = sequence(4,5)
console.log(generatorOne())
console.log(generatorOne())
console.log(generatorOne())
console.log('another')
let generatorTwo = sequence(3, 2);
console.log(generatorTwo())
console.log(generatorTwo())
console.log(generatorTwo())
console.log(generatorTwo())
console.log(generatorTwo())
console.log(generatorTwo())
console.log('another')
let generatorThree = sequence(0, 7);
console.log(generatorThree())
console.log(generatorThree())
console.log(generatorThree())
console.log(generatorThree())
| 088b092b9c8c449a978e80ee94f9bcbe962bdb5a | [
"JavaScript"
] | 1 | JavaScript | Oleg-Pashulia/Sequence | a379540f31026708fd138cfca66d8a5504cf9b9a | f8622510c5aa04aedc686e2fb81aa4bc76289eef |
refs/heads/master | <repo_name>rbreaves/NodeJS-simple-REST-API-for-MS-SQL-Server<file_sep>/server.js
var express = require('express');
var app = express();
var sql = require('mssql');
// Connection string parameters.
var sqlConfig = {
user: 'UserName',
password: '<PASSWORD>',
server: 'MS SQL server',
database: 'Database'
}
// Start server and listen on http://localhost:8000/
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Server listening at http://%s:%s", host, port)
})
async function execute(query) {
return new Promise((resolve, reject) => {
new sql.ConnectionPool(sqlConfig).connect().then(pool => {
return pool.request().query(query)
}).then(result => {
resolve(result.recordset);
sql.close();
}).catch(err => {
reject(err)
sql.close();
});
});
}
// Get query that return data from orders table
app.get('/orders', function (req, res) {
execute('SELECT * FROM Orders;')
.then(function(value) {
res.end(JSON.stringify(value)); // Result in JSON format
});
})
// Get query with where
app.get('/orders/:orderId/', function (req, res) {
execute('SELECT * FROM Orders WHERE orderId = ' + req.params.orderId)
.then(function(value) {
res.end(JSON.stringify(value)); // Result in JSON format
});
})
<file_sep>/README.md
# NodeJS simple REST API for MS SQL Server
Here’s how to create a simple NodeJS REST API for a MS SQL database.
Returning results in JSON format.
### Modules
[Express](https://www.npmjs.com/package/express)
[mssql](https://www.npmjs.com/package/mssql)
[async](https://www.npmjs.com/package/async)
# Installation
Requires Node.js Node 7.6 or newer.
npm install
| 19c41c2085f917ea464ab5b835e3f97822f72a39 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | rbreaves/NodeJS-simple-REST-API-for-MS-SQL-Server | 6f6a0c4c7c131a1008e3c9f3874998b48080b354 | c2593db5aea49f6ee1342a72fff746700a79074d |
refs/heads/master | <file_sep>import React from "react";
import "../styles/results.css";
function Results({ persons }, { filteredPersons }, handleSort) {
return (
<div className="container">
{" "}
<div className="results-table">
<table className="table table-striped table-dark table-sortable">
<thead>
<tr>
<th>Image</th>
<th>
<div onClick={() => handleSort(persons)}>Name</div>
</th>
<th>Phone</th>
<th>Email</th>
<th>DOB</th>
</tr>
</thead>
<tbody>
{persons.map((person, index) => (
<tr key={index}>
<td>
<img src={person.picture.medium} alt="thumb" />{" "}
</td>
<td>{person.name.first}</td>
<td>{person.phone}</td>
<td>{person.email}</td>
<td>{person.dob.date.slice(0, 10)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
export default Results;<file_sep># employee-directory
This single page web app was built using react. It's purpose is to display a list of employees that allows you to sort, or search for people. As a manager, I want to be able to quickly scan through my employees, so that I can more expeditiously find information that I am looking for.
## Getting Started
When you load the web app, your list of employees will automatically populate. After your list is brought up, you can search for specific people, by entering their name into the search field. You will also be able to sort the columns, by clicking the table header for each specific column.
### Installing
All dependencies are ready to be installed by the user, using npm i in your terminal.
## Deployment
This page is deployed on github pages at https://flashotfr.github.io/employee-directory/ .
## Built With
* React.JS
## Authors
* **<NAME>**
## Acknowledgments
* Hat tip to the code monster by lady java team
* Max
* Andrea
* Marie
* <NAME> | d50021f6819657bcfd87bf05b14c963ec995338c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | FlashOTFR/employee-directory | 4f9a020410d47d46a270de8c4db65e65010f0a77 | 0e9b4d1831ccc605ec6128591a3c799a7800239a |
refs/heads/master | <file_sep>using CaclClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WFCalcWithButton
{
public class MockCalcClient : ICalcClient
{
public async Task<double> Calculate(double a, double b, char op)
{
double res = 0;
switch (op)
{
case '-': res = a - b; break;
case '+': res = a + b; break;
case '*': res = a * b; break;
case '/': res = a / b; break;
}
return res;
}
}
class RealCalcClient : ICalcClient
{
CalcClient client = null;
public RealCalcClient(string uri)
{
client = new CalcClient(uri);
}
public async Task<double> Calculate(double a, double b, char op)
{
return await client.Calculate(a, b, op);
}
}
}
<file_sep>using System;
using TestStack.White.UIItems.WindowItems;
using TestStack.White;
using TestStack.White.Factory;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
using NUnit.Framework;
namespace AutoTest
{
public class WFWithB
{
Application application;
Window window;
ObjectModel obj;
static string GetApplicationPath(string applicationName)
{
var tmpDirName = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\');
var solutionFolder = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(tmpDirName))) + @"\WFCalcWithButton\";
string result = Path.Combine(solutionFolder, applicationName);
return result;
}
[SetUp]
public void StartApp()
{
//application = Application.Launch(new ProcessStartInfo(@"WFCalcWithButton.exe")
//{
// WorkingDirectory = @"..\..\..\WFCalcWithButton\bin\Debug\",
//});
application = Application.Launch(GetApplicationPath("WFCalcWithButton.exe"));
window = application.GetWindows()[0];
obj = new ObjectModel(window);
}
[TearDown]
public void QuitF()
{
application.Kill();
}
[Test]
[TestCase("but1")]
[TestCase("but2")]
[TestCase("but3")]
[TestCase("but4")]
[TestCase("but5")]
[TestCase("but6")]
[TestCase("but6")]
[TestCase("but8")]
[TestCase("but9")]
[TestCase("but0")]
[TestCase("butMinus")]
[TestCase("butPlus")]
[TestCase("butMult")]
[TestCase("butDiv")]
[TestCase("butEqual")]
public void TestWPFExistingElement(string elId)
{
obj = new ObjectModel(window);
Assert.AreEqual(true, obj.GetButton(elId).Visible);
}
[Test]
[TestCase("but1", "1")]
[TestCase("but2", "2")]
[TestCase("but3", "3")]
[TestCase("but4", "4")]
[TestCase("but5", "5")]
[TestCase("but6", "6")]
[TestCase("but7", "7")]
[TestCase("but8", "8")]
[TestCase("but9", "9")]
[TestCase("but0", "0")]
public void TestWPFSimpleCheck(string elId, string res)
{
obj.GetButton(elId).Click();
string calc = obj.GetTextBox("txtResult").BulkText;
Assert.AreEqual(res, calc);
}
[Test]
[TestCase(new string[] { "but1", "but2", "but3" }, "123")]
[TestCase(new string[] { "but4", "but5", "but6" }, "456")]
[TestCase(new string[] { "but7", "but8", "but9" }, "789")]
[TestCase(new string[] { "but3", "but0", "but6" }, "306")]
public void TestWPFComplexCheck(string[] arr, string res)
{
foreach (string str in arr)
{
obj.GetButton(str).Click();
}
string calc = obj.GetTextBox("txtResult").BulkText;
Assert.AreEqual(res, calc);
}
[Test]
[TestCase("but1", "but2", "butPlus", "3")]
[TestCase("but3", "but4", "butMinus", "-1")]
[TestCase("but5", "but6", "butMult", "30")]
[TestCase("but9", "but3", "butDiv", "3")]
public void TestWPFRealJob(string x, string y, string op, string res)
{
Task.Run(() =>
{
obj.GetButton(x).Click();
obj.GetButton(op).Click();
obj.GetButton(y).Click();
obj.GetButton("butEqual").Click();
string calc = obj.GetTextBox("txtResult").BulkText;
return calc;
}).ContinueWith((e) => { Assert.AreEqual(res, e); });
}
}
}
<file_sep>using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
using NUnit.Framework;
using WFCalcWithButton;
namespace ClaclLogicTest
{
[TestFixture]
public class UnitTestLogic
{
MockCalcClient mock;
[SetUp]
public void Es()
{
mock = new MockCalcClient();
}
[Test]
[TestCase(1, 2, '+', "3")]
[TestCase(12, 2, '-', "10")]
[TestCase(7, 2, '*', "14")]
[TestCase(6, 2, '/', "3")]
public void TestCalcWF(double x, double y, char op, string res)
{
Assert.AreEqual(res, Task.Run(() => mock.Calculate( x, y, op)).Result);
}
}
}
<file_sep>using System;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
using NUnit.Framework;
namespace UnitTestBDD
{
public class UnitTestBDD
{
public void TestMethod1()
{
}
}
}
<file_sep>using CaclClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WFCalcWithButton
{
public partial class Form1 : Form
{
public enum ClientType{ REAL, MOCK };
ICalcClient client;
int x = 0;
int y = 0;
char op = ' ';
public Form1(ClientType clientType)
{
InitializeComponent();
if (clientType == ClientType.REAL)
client = new RealCalcClient("http://localhost:8888");
else
client = new MockCalcClient();
}
private void buttonNumber_Click(object sender, EventArgs e)
{
Button but = (Button)sender;
textResult.Text += but.Text;
}
private async void buttonOperation_Click(object sender, EventArgs e)
{
Button but = (Button)sender;
char oper = Convert.ToChar(but.Text);
if (oper != '=')
{
x = Int32.Parse(textResult.Text);
textResult.Text = "";
op = oper;
}
else
{
y = Int32.Parse(textResult.Text);
textResult.Text = (await client.Calculate(x, y, op)).ToString();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WFCalcWithButton
{
public interface ICalcClient
{
Task<double> Calculate(double x, double y, char op);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LightBDD;
using NUnit.Framework;
using LightBDD.NUnit2;
namespace UnitTest
{
class CalcFeature : FeatureFixture
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestStack.White.UIItems;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;
namespace AutoTest
{
public class ObjectModel
{
string but1 = "button1";
string but2 = "button2";
string but3 = "button3";
string but4 = "button4";
string but5 = "button5";
string but6 = "button6";
string but7 = "button7";
string but8 = "button8";
string but9 = "button9";
string but0 = "button0";
string butPlus = "buttonPlus";
string butMinus = "buttonMinus";
string butMult = "buttonMultiply";
string butDiv = "buttonDivide";
string butEqual = "buttonEqual";
string txtResult = "textResult";
Window window;
public ObjectModel()
{
}
public ObjectModel(Window window)
{
this.window = window;
}
public Button GetButton(string s)
{
Button flag = null;
if (s == nameof(but1))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but1));
else if (s == nameof(but2))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but2));
else if (s == nameof(but3))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but3));
else if (s == nameof(but4))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but4));
else if (s == nameof(but5))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but5));
else if (s == nameof(but6))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but6));
else if (s == nameof(but7))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but7));
else if (s == nameof(but8))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but8));
else if (s == nameof(but9))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but9));
else if (s == nameof(but0))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(but0));
else if (s == nameof(butMinus))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(butMinus));
else if (s == nameof(butPlus))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(butPlus));
else if (s == nameof(butDiv))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(butDiv));
else if (s == nameof(butEqual))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(butEqual));
else if (s == nameof(butMult))
flag = window.Get<Button>(SearchCriteria.ByAutomationId(butMult));
return flag;
}
public TextBox GetTextBox(string s)
{
TextBox flag = null;
if (s == nameof(txtResult))
flag = window.Get<TextBox>(SearchCriteria.ByAutomationId(txtResult));
return flag;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CaclClient
{
public class CalcClient
{
HttpClient client = null;
string url = null;
public CalcClient(string servAddress)
{
client = new HttpClient();
url = servAddress;
}
public async Task<double> Calculate(double a, double b, char op)
{
var param = "a=" + a + "&b=" + b + "&op=" + op;
string response = await client.GetStringAsync(url + "/?" + param);
return Convert.ToDouble(response);
}
}
}
| c62c61a1fdc912dce3c70ae06881db2098b85aea | [
"C#"
] | 9 | C# | EnigmaInTheJungle/DeskCalcWithMock-BDD | e6a546b63580c09cb844907594c118902d491462 | a9ae41a263e1b07818c4078a8c43b6aa1b486cd7 |
refs/heads/master | <repo_name>Gutxaka/spree_variant_options<file_sep>/Gemfile
source "http://rubygems.org"
gem 'spree', github: 'spree/spree', branch: '2-4-stable'
gem 'sass', '~> 3.2.2'
gem 'rails', '~> 4.1.8'
gem 'sass-rails', '~> 4.0.5'
gem 'font-awesome-sass', '~> 4.2.0'
gemspec | 78b66696c669b1b23f063198f6cda658113b8664 | [
"Ruby"
] | 1 | Ruby | Gutxaka/spree_variant_options | 8c1ccb04bd84819e064832943c412afaa678fb2f | f8d3b81f4ad68bc9fd8f6542524cbde02c0cad28 |
refs/heads/master | <file_sep>import java.util.*;
public class string {
public static void main (String[] str) {
//String str1 = " MrSachinPandit ";
String str1 = str[0];
char[] str1_arr = str1.toCharArray ();
char[] result = new char[30];
int space_count = 0;
int length = 0;
int i;
for (i = 0; i < str1.length(); i++) {
if (str1_arr[i] == ' ') {
space_count++;
}
}
length = str1.length() + 2*space_count;
for (i = str1.length() - 1; i >= 0; i--) {
if (str1_arr[i] != ' ') {
result[length - 1] = str1_arr[i];
length--;
} else {
result[length - 1] = '0';
result[length - 2] = '2';
result[length - 3] = '%';
length -= 3;
}
}
System.out.println ("Original = " + str1);
System.out.println ("Result = " + String.valueOf (result));
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
int
find_sum (int num) {
int new_num = 0;
int rem = 0;
while (num > 0) {
rem = num % 10;
new_num += rem * rem;
num = num/10;
}
return new_num;
}
int
check_if_present (int *arr, int count, int new_num) {
int i;
/*
for (i = 0; i <= count; i++)
printf ("%d ", arr[i]);
*/
//printf ("\n");
for (i = 0; i <= count; i++) {
if (arr[i] == new_num)
return 1;
}
return 0;
}
int
find_if_happy (int num, int *happy) {
int new_num;
int count = 0;
int first = 0;
int arr[100];
int i = 0;
int ret = 0;
for (i = 0 ; i < 100; i++)
arr[i] = 0;
arr[count] = num;
count++;
new_num = num;
while (new_num != 1) {
new_num = find_sum (new_num);
//printf ("New Num = %d\n", new_num);
if (check_if_present (arr, count, new_num)) {
*happy = 0;
return count;
}
arr[count] = new_num;
count++;
}
*happy = 1;
return count;
}
int main () {
int i = 0;
int arr[10];
int ret = 0;
int happy = 0;
while (i < 10) {
scanf ("%d", &arr[i]);
i++;
}
i = 0;
while (i < 10) {
ret = 0;
happy = 0;
if (arr[i] == 1) {
printf ("happy 0\n");
} else {
ret = find_if_happy (arr[i], &happy);
if (happy ==0) {
printf ("unhappy %d\n", ret);
} else {
printf ("happy %d\n", ret - 1);
}
}
i++;
}
return 1;
}
<file_sep># coding
Repository that contains all the coding questions
<file_sep>import java.util.*;
public class cycle {
public static void main(String[] args) {
int distance = 8;
int[] radius = { 1, 3, 6, 2, 5 };
int[] cost = { 5, 6, 8, 3, 4 };
int[] ans = Circles(distance, radius, cost);
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
System.out.println();
}
statis int get_start_index ()
static int[] Circles(int distance, int[] radius, int[] cost) {
int j;
int min_cost=-1, min_index=0;
int key1, key2;
int index=0;
int k = 0;
int[] result = new int[radius.length];
int[] sorted_array = new int[radius.length];
sorted_array = Arrays.sort (radius);
for (int i = 0; i < radius.length; i++) {
min_cost=-1;
min_index = 0;
for (j = 0; j < radius.length; j++){
if(radius[i] + radius[j] >= distance) {
if((cost[i]+cost[j])<min_cost || min_cost==-1) {
min_cost = cost[i] + cost[j];
min_index = j;
}
if((cost[i]+cost[j])==min_cost) {
if(radius[j] > radius[min_index]) {
min_index=j;
}
}
}
}
if (min_index == 0)
result[k++] = 0;
else
result[k++] = min_index+1;
}
return result;
}
}
<file_sep>
class Treenode {
int val;
Treenode left;
Treenode right;
Treenode (int num) {
this.val = num;
}
}
public class tree {
static int nextH = 0;
static int print_next_highest (Treenode head, int num) {
if (head == null) {
return nextH;
} else if (head.val == num) {
return head.val;
} else if (head.val > num) {
if (head.val < nextH || nextH == -1)
nextH = head.val;
nextH = print_next_highest (head.left, num);
} else if (head.val < num) {
nextH = print_next_highest (head.right, num);
}
return nextH;
}
static void inorder (Treenode head) {
if (head == null)
return;
inorder (head.left);
System.out.print (head.val + " ");
inorder (head.right);
}
public static void main (String[] str) {
Treenode head = new Treenode(10);
head.left = new Treenode (5);
head.left.left = new Treenode (3);
head.left.right = new Treenode (7);
head.left.right.left = new Treenode (6);
head.left.right.right = new Treenode (8);
head.left.left.left = new Treenode (1);
head.right = new Treenode (12);
head.right.right = new Treenode (13);
inorder (head);
System.out.println();
nextH = -1;
System.out.println (print_next_highest (head, 1000));
}
}
<file_sep>import java.util.*;
public class string_rotate {
public static void main (String[] str) {
String str1 = str[0];
String str2 = str[1];
StringBuffer result = new StringBuffer ("");
result.append (str1);
result.append (str1);
//System.out.println ("result = " + result);
if (result.toString().toLowerCase().contains(str2.toString().toLowerCase())) {
System.out.println ("Yes it is!!");
} else {
System.out.println ("Sorry it is not..");
}
}
}
| cd20d80310d23792a0f53ed1f6870fcb115af2cb | [
"Markdown",
"Java",
"C"
] | 6 | Java | sachin-pandit/coding | 4f43f39fe2bd17d78f65a034038853dd8a29f5df | 71a4ca89316757deaa1fa6626b2503e377ce33d3 |
refs/heads/master | <repo_name>zhangjihu0/myNotebook<file_sep>/mongoDB_study/advance2/数据库常用命令.md
# 常用命令
1. 查看记录数:count
db.person.find().count();
2. 查找不重复的值 distinect
db.runCommand({distinct:'person',key:'home'}).value
3. group 分组
db.runCommand({
group:{
ns:集合名称,
key:分组的键值,
initial:初始值,
$reduce: 分解器,
condition:条件,
finalize:完成时的处理器
}})
db.runCommand({
group:{
ns:'person',
key:{'home':true},//已对象形式的表示得到了分组的结果,已字符串的结果表达得到了所有分组中的最大值;
initial:{'name':0},
$reduce:function(doc,acc){//循环每个分组里的文档
if(doc.name>acc.name){ //返回每组的最大值;
acc.name = doc.name;
acc.home = doc.home;
}
},
condition:{name:{$gt:2}},
finalize:function(acc){//修改输出结果中的表达方式
acc.name = acc.home+"中最大值的名字是"+acc.name
}
}
})
4. 删除集合
db.runCommand({drop:'person'});
5. 查看常用的命令
http://127.0.0:28017/_commands
6. 查看数据的信息
db.runCommand({buildInfo:1})
7. 查看最后一次错误的信息
db.runCommand({getLastError:'person'})
<file_sep>/mongoDB_study/advance3/索引.md
### 索引
#### 什么索引
特殊的数据结构,按顺序保存文档中的一个或多个指定.使用B-Tree索引, 方便范围查询和匹配查询。
### 建立索引(单建索引)
#### 插入数据
for(var i =0;i<300000;i++){db.persons.insert({name:i})}
#### 创建匿名索引 //系统自动生成索引
db.person.ensureIndex({name:1})
#### 创建命名索引
db.person.ensureIndex({name:-1},{name:'nameIndex'})
#### 分析索引执行过程
db.persons().find({name;1}).explain();
#### 指定使用的索引
db.persons.find({name:1}).hint({name:-1}).explain()
#### 创建唯一索引并删除重复记录
name:索引名称;
unique:true 是否唯一值
dropDups:true 删除是
db.person.ensureIndex({"name":1},{"name":"indexname","unique":true,dropDups:true})
#### 删除所有索引
db.runcommand({dropIndexes:'person',index:'*'});
#### 后台创建索引 异步执行后返回
db.person.ensureIndex({"name":1},{"name":"indexname","unique":true,"background":true})
### 建立多键索引
// 可以自动对数组进行索引
db.person.insert({hobby:['basketball','football','pingpang']})
db.ensureIndex({hobby:1})
find({},{})//第一个只是查询值,第二值是返回值,1返回,0不返回;
db.person.find({hobby:'football'},{hobby:1,_id:0})
### 复合索引
db.person.insert({a:1,b:2})
db.person.insert({a:2,b:3})
db.p.ensureIndex({a:1,b:1});
db.p.find({a:1,b:2},{a:1,_id:0}).explain();
查询的条件不止一个,需要用
### 过期索引
在一定时间后会过期,过期后相应的数据被删除
session 日志 缓存 临时文件
db.p2.insert({time:new Date()});
db.p2.insert({time:new date()});
//索引10秒后删除索引以及数据
db.p2.insert({time:1},{expireAfterSeconds:10})
// 索引字段的值必须Date 对象, 不能是其他类型比如时间戳
// 删除时间不是准确,没60秒跑一次。删除也需要时间,所以有误差
### 二维索引
空间索引,可以查询一定范围内的地理位置。
for(var i =1;i<=10;i++){
for(var j=1;j<=10;j++){
db.map.insert({gis:{x:i,y:j}});
}
}
db.map.ensureIndex({gis:'2d'},{min:-1,max:10000});//建立索引,范围索引
## 查询离[1,1]最近的点;
db.map.find({gis:{$near:[1,1]}},{gis:1,_id:0}).limit(3);1:显示。0:不显示;
## 查询[1,1]和[3,3]为对角线的矩形内的所有点;
db.map.find({gis:{$within:{$box:[[1,1],[3,3]]}}},{gis:1,_id:0})
## 查询圆心[1,1],半径为1的圆形之内的所有的点.
db.map.find({gis:{$within:{$center:[[1,1],1]}}},{gis:1,_id:0});
## 多边形
db.map.find({gis:{$within:{$polygon:[[2,1],[1,3],[3,3]]}}},{gis:1,_id:0})
# 索引建立的注释;
1. 1为正序 -1 为倒序
2. 索引虽然可以提升查询性能,但会降低插件的效率
3. 建立合理的索引<file_sep>/mongoDB_study/advance3/主从复制.md
### 主从复制
主从复制就是一个简单的数据库库同步备份的集群技术
1.集群中需要指定主服务器
2.还好从服务器,从服务器需要知道谁是他的主服务器
#### 配置
启动主服务器
mongod ---dbpath=/data/mongodb/master --port=8000 --master
启动从服务器
mongod --dbpath =/data/mongodb/master --port=8000 --source localhost:8000
#### 重要提示 从服务器需要指定的
only 指定复制的数据库
slavedelay 主库向从库同步的延时时间
oplogsize 主节点操作记录存储到local的oplog里,从服务器从主服务器上获取回这个日志文件然后更新自己
autoresync 是否自动同步所有数据
#### 从服务器修改主服务器,
use local
show collection
db.sources.find()
{
'host':'localhost:8000','source':'main','syncedTo':Timestamp(1432215079)
}<file_sep>/mongoDB_study/advance3/分片.md
### 分片
分片类似于表区分<file_sep>/mongoDB_study/advance3/副本集.md
### 副本集
它是一个集群当主服务器宕机后,其它从服务器会根据权重算法选举出来一台从服务器作为主服务器
主服务器恢复后,就会变成从服务器,继续加入当前的集群
与主从的区别
主从需要手动指定,副本集自动根据权重产生
县长
村长
mongod --dbpath=/data/mongodb/master1 --port=8001 --replSet=groups --noprealloc
mongod
--dbpath=/data/mongodb/master2 --port=8002 --replSet=groups --noprealloc
mongod
--dbpath=/data/mongodb/master3 --port=8003
--replSet=groups --noprealloc
use admin
db.runCommand({
replSetInitiate:{
"_id":'groups',
members:[{_id:1,host:'127.0.0.1:8000'}]
}
})
slaveOk = false 不可读从服务器,true下可以;
<file_sep>/mongoDB_study/advance2/gridfs.md
### 概念
是mongodb自带的文件系统,使用二进制存储文件。可以以BSON的格式保存二进制对象。
但是普通的BSON 对象的体积不能超过4M。所以mongodb提供了gridfs.他可以把大文件透明的分割小文件,从而保存大体积的数据。
### 上传一个文件
1. mongofiles -d files -l "E:\test.txt" put 'test.txt'
### 查看文件
1. mongofiles -d files get 'test.txt'
### 查看所有文件
1. mongofiles -d files list
### 删除文件//只能识别双引号不能用单引号;
1. mongofiles -d files delete "test.txt"
### eval 服务器端脚本 当前数据库下使用;
//可执行js语句
db.eval("1+1");
db.eval("return 'hello'");
db.system.js.insert({_id:'x',value:1})//定义全局变量,x=1
db.system.js.insert({_id:'say',value:function(){return 'hello'}})
db.eval("say()");<file_sep>/mongoDB_study/v8/scope.js
// 作用域
// person在每次被调用的时候会创建相应的作用域,执行完之后,作用域销毁
// 内部的局部活动变量也被销毁局部变量存活时间变短
var person = function(){
var name = ""
}
person();
//垃圾回收的基本过程
// 1.标识符查找 就是变量名
function say(){
console.log(name)
}
function first(){
var name ='first';
function second(){
var name ='second';
function third(){
var name = 'third'
}
third();
}
second()
}
first()
//变量如何释放
//全局变量无法销毁
//只能通过delete删除引用或重新赋值
global.name= 'zfpx';
age = {age:6};
console.log(global.name);
delete global.name //不好,会打破v8的属性结构机制;
name=null;//被v8垃圾回收
/**
* 外部不能访问内部定义的变量
* 闭包可以实现外部作用域访问内部作用域的变量或方法
* 一般情况下由于city是局部变量应该销毁但由于返回了一个匿名函数,具备了访问city的能力
* 所以无法回收的情况分为两种,一种全局一种是闭包
*/
function City(name){
this.name =name;
this.age =0;
}
var cityFactory = function(name){
var city = new City(name);
return function(){
return city
}
}
var beijing = cityFactory('北京')
beijing=null;//City的实例会被回收
console.log(beijing())<file_sep>/正则表达式/17_12_01.md
慕课网正则表达式教程:
https://www.imooc.com/learn/706
正则表达式图形展示学习地址:
http://regexper.com
###
\d? //dgt数字 ?0||1个
\d+ //1||多个
\d{3,5} //循环2-4次
\d* //循环任意次,包含0
\b 单词边界
/\bis/\b 职匹配is,不匹配this
. \\表示任意字符
http:\/\/.+\.jpg \\一个以上的任意字符串并已.jpg结尾
\d{4}[/-] 数组中表示或者关系,任意四个数字,后面接着/或-
^\d{4}[/-]\d{2}[/-]\d{2}[/-]$
2017-09-10000 不能匹配
2017-09-10 能匹配
/g 全文匹配
/gi 全局匹配无大小写;
var reg = new RegExp('\\bis\\b','g')
/i 忽略大小写;
### 元字符
. * + ?$ ^ | \ () {} []
### 字符类
[] 符合某些特征的对象,一个泛指,而不是某个
[abc]是把a 或b 或 c 归为一类, 表达式可以匹配这类字符 即 有其中的一个就行
### 字符类取反 ^
[^abc] 任意不等于abc 中任意一个的符合结果;
### 范围类
[a-z] 从a到z的任意字符;
[a-zA-Z]/g
[0-9]/g//不会匹配横线
2017-06-12
[0-9-]/g
//会匹配横线
### 预定义类
. [^\r\n] 除了回车换行之外的所有字符
\d [0-9] 数字字符
\D [^0-9] 非数字字符
\s [\t\n\x0B\f\r] 空白符
\S 非空白符
\w [a-zA-Z_0-9] 单词字符(字母、数字下划线)
\W 非单词字符
^ 开头标记
\b单词边界
\B非单词边界
\gm匹配多行
### 量词
? 最多出现一次;
+ 最少出现一次;
* 出现任意次;可以是0次
{n} 出现固定的n次
{n,m} 出现从n-m 次
{n,} 出现最少n次
### 贪婪模式:
12345678
\d{3,6} //尽可能多的匹配此时即6次;
### 非贪婪模式:
12345678
\d{3,5}? 只匹配3次
### 分组 ()
Byron{3}
{}匹配紧挨着的部分
[a-z]\d{3} 匹配数字连续出现3次的情况;
([a-z]\d){3} 匹配任意小写字符数字连续出现3次的情况;
### 或 |
ByronCasper.replace(/Byron|Casper/g,'X')
XX
### 反向引用
'2016-11-25'.replace(/\d{4}-\d{2}-\d{2}/g,'$1')
$1
'2016-11-25'.replace(/(\d{4})-(\d{4})-(d{2})/g,'$2/$3/$1')
"11/25/2016"
<file_sep>/mongoDB_study/v8/垃圾回收机制js.md
## javascript 垃圾回收器
自动垃圾回收机制管理内存
### 优化
简化开发,节省代码。
### 缺点
无法完整掌握内存
### node的内存管理
服务器端的node有必要管理内存
内存泄漏后果严重,有可能引起文件描述符耗尽和连接占满
### v8内存限制
64位 1.4G 32位 0.7G
无法操作大对象
node.js中的js对象都是通过V8进行分配管理内存的
最大1.4G
console.log(process.memoryUsage())
{
rss:161546624,进程的常驻内存16M 有7M不属于堆内存;
heapTotal:9751808,V8已经申请到的堆内存数量9M
heapUsed:3952576,V8已经使用的堆内存总量3M
}
### 为何
V8 的垃圾收集原理
1.5内存 完全收集一次 需要1 秒以上
这一秒钟 叫stop the world,应用的性能和响应能力都会下降
## 如何打开内存限制
node --max-old-space-size=2000 app.js 单位是M
node --max-new-space-size = 1024 app.js 单位是KB
一旦初始化成功,生效不能再修改
### 的垃圾回收机制
V8 是基于分代的垃圾回收。分为新生代和老生代
按存活时间来划分的。年龄小的新生代,年龄大的老生代
#### 内存分代
- 年龄小的新生代,
由两个区域组成。[][].
默认情况下 64位 新生代 内存是32M
32位 新生代 内存 16M
新生代由两块 from to 区域组成。每块 64位 16M 32位8M
- 年代大的老生代
默认情况下 64位 老生代 内存是1400M
32位 老生代 内存是700M
#### 新生代的垃圾回收算法:
大多数被分配到这里,这里是他们出生的地方
这个区域很小,但垃圾回收非常频繁
当指针到达末尾时,要进行垃圾回收
新生代通过scavenge算法进行回收
scavenge
新生代匹配一分为2, 每个16M
一个使用,一个空闲
开始垃圾回收时,会检测from里的存活对象,如果还活着,拷贝到to 空间里
非存在对象,释放空间;
完成复制后,from 和to 角色互换;
复制的过程采用广度优先的策略,从根对象出现,遍历所有能力直接访问的对象
优点 是速度快 效率高
缺点是浪费空间
但是由于存活对象少,空间小,所有这种方案最合适
当一个对象经历过多次闪复制依然存活时,它就是生存周期比较长的对象 它会被移动到老生代,这个移动过程称之为晋升或升级
有两种情况会晋升
1.经历过5次以上的回收
2.to的空间内存使用占比超过20%,或超大对象
###老生代垃圾回收算法
mark-sweep mark-compact
标记-清理 标记-整理
###mark-sweep
标记活着的对象,随后清理标记阶段没有标记的对象,只清理死亡的对象,活着的对象在新生代比较多,在老生代比较少
问题在于清除后会出现内存不连续的情况,这种内存碎片会对后续的分配造成影响
如果要分配一个大对象,碎片空间无法分配
###mark-compact
标记死亡后进行整理,活着的对象往左移动,移动完成后,直接清理掉外界的内存。
### incremental making 增量标记
以上三种回收时都需要暂停程序运行,收集完成后才进行恢复。stap the world
新生代影响不大,老生代内存空间大,存活对象多,耗时比较长,比较严重
把标记改为了增量标记。将一口气的停顿拆分成了多个小步骤。
做完一步程序运行一会,垃圾回收和应用程序运行交替进行。
停顿时间可以减少到1/6左右
### 查看垃圾回收日志
#### trace_gc
node --trace_gc --trace_gc_verbose traceGc.js>trace.log
知道何时执行GC,每次GC的时间以及每个区域的内存占用情况
### Prof
可以得到V8执行性能分析,包括垃圾回收的占用时间
ngryman/v8-windows-tickprocessor //可视化的工具GC
### 如何让内存高效的工作;
我们让垃圾回收更高效的工作;
#### 如何释放内存
scope closure
内存指标
堆内存总得是小于RSS,NOD中的内存并不全都是由V8进行分配的不通过V8分配的内存称为堆 外内存
<file_sep>/mongoDB_study/advance2/固定集合.md
### 建立集合的时候指定集合的大小和文档的数量,如果满了,就把最后的元素抛弃掉,把新的元素
### 特性
- 没有索引
- 插入和查询数组速度飞快 不需要重新分配空间
- 日志
### 创建固定集合 max文档的数量
//只能保存5条数据,超出后先进先出
db.createCollection('lesson',{size:50,max:5,capped:true})
### 获取所有的集合;
db.getCollectionNames();
### 将现有非固定集合变成固定集合
size 集合的大小
db.runCommand({convertToCapped:'lesson',size:6})
convert//使转换
Capped// 覆盖帽子--加帽子从而产生固定数量<file_sep>/mongoDB_study/readme.md
#### 今天内容 show dbs 显示所用的数据库;
扩展命令、数据库管理、索引、主从和副本以及分片。
#### 命令和配置 mongod --config mong.conf
1. 启动项
--dbpath 指定数据文件的目录
--port 端口 默认是27017 2801
--fork 以后台守候的方式进行启动
--logpath 指定日志文件输出路径
--config 指定一个配置文件
--auth 以安全的方式启动数据库,默认不验证
--rest 会启动一个帮助页面
2. 启动数据库
3. 关闭数据库
3.1 ctrl+c
3.2 在另一个cmd中
mongo localhost:5000
use admin
db.shutdownServer();//cmd
3.3 直接关闭cmd
#### 导入导出cmd
--备注:在保持连接的情况下,mongo localhost:5000 use blog
for(var i=1;i<=100;i++>){
db.persons.insert({name:i,age:i})
}插入数据;
db.persons.find().count();查看数据库条数;
db.persons.find()只会返回20条数据
-导出 mongoexport
Ctrl c
mongoexport -d blog -c person --cvs -o bak.cvs
-d 指定导出的数据库
-c 指定导出的集合
-o 导出的文件存储路径
-q 进行过滤
--cvs 指定文件格式
-文件导入
mongoimport --db blog --collection person --file bak.json;
mongodump -d blog -o bak.dmp//导出整个数据库生成bak.dmp文件;
#### 备份数据库
mongoimport --db blog --collection person --file bak.json
#### 数据恢复
运行时恢复 --directoryperdb一个单独的目录 \blog 对应的文件名称;
mongorestore -db blog --directoryperdb bak.dmp\blog
#### 文件备份
把备份文件放到其他目录,然后修改config更改指向重新连接;
#### 为了数据的完整性和一致性;导出前先锁库即不能再写入了;
导出前添加锁:use admin db.runCommand({fsync:1,lock:1})fsync:同步状态;
db.fsyncUnlock();解除锁定;
#### 用户和权限
##### 安全措施
物理隔离 网络隔离 防火墙 (ip ip段 白名单 黑名单)用户名密码验证;
####用户管理
1. 为数据库添加用户:
use admin
db.addUser('zry','123')// {user:zry,roles:['root']}//已被废弃;
show roles 展示所有角色;
db.createUser({user:'zf',pwd:'123',roles:[role:'userAdmin',db:'admin']})
2. 展示特权:
db.runCommand({userInfo:'zry',showPrivileges:true}) showPrivileges://展示用户信息包含权限;
3. 查询当前的数据库的所有用户
db.system.users.find();//所用用户的列表和定义的权限
4. 在创建的数据上,登录来确认权限
db.auth('zf','123') //
5. 修改用户密码
db.changeUserPassword('<PASSWORD>','456')//修改用户密码;
6. 修改用户信息
db.runCommand({updateUser:'zhangsan',pwd:'789',customData:{title:'manager',age:'30'})
7. 删除用户
db.system.users.remove({user:"java1"});
### 用户的注意事项
1. 用户的操作都需要在admin下面进行use admin
2. 如果在某一个数据库下执行操作,那只对当前数据库生效。
3. addUser 已经废弃,不建议使用。但是创建出来的是默认的有root权限的用户
<file_sep>/mongoDB_study/index.md
advance 3 23分钟处,插入数据
advance 3 50分钟处 二维索引 | ce3a43e1adb2c81e763d6e92c90ee0658d5e25b0 | [
"Markdown",
"JavaScript"
] | 12 | Markdown | zhangjihu0/myNotebook | f1185fec991df703690cbc888c4553cf9db42ac6 | 2ae8c77ee09c87c79cd04ca5caa717efb7206237 |
refs/heads/master | <file_sep># Generated by Django 2.1.7 on 2019-04-20 09:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Company',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('tel_num', models.CharField(max_length=128)),
('address', models.CharField(max_length=128)),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('reg_date', models.DateTimeField(auto_created=True)),
('descriptions', models.CharField(default='비어있음..', max_length=128)),
('order_owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='OrderedProduct',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('product_cnt', models.PositiveIntegerField(default=1)),
('amount_of_credited_mileage', models.PositiveIntegerField()),
('related_order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.Order')),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128)),
('price', models.PositiveIntegerField(default=0)),
('product_owned_company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.Company')),
],
),
migrations.AddField(
model_name='orderedproduct',
name='related_product',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.Product'),
),
migrations.AddField(
model_name='order',
name='product_set_included_order',
field=models.ManyToManyField(related_name='ordered_product_set', through='orm_practice_app.OrderedProduct', to='orm_practice_app.Product'),
),
]
<file_sep>certifi==2019.3.9
chardet==3.0.4
coreapi==2.3.3
coreschema==0.0.4
Django==2.2.1
django-extensions==2.1.6
django-extensions-shell==1.7.4.1
django-query-logger==0.1.2
djangorestframework==3.9.2
idna==2.8
inflection==0.3.1
itypes==1.1.0
Jinja2==2.10
MarkupSafe==1.1.1
psycopg2==2.8.2
pytz==2018.9
requests==2.21.0
ruamel.yaml==0.15.89
six==1.12.0
uritemplate==3.0.0
urllib3==1.24.1
<file_sep># Generated by Django 2.1.7 on 2019-04-20 13:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('orm_practice_app', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='product',
name='product_owned_company',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.Company'),
),
]
<file_sep># Generated by Django 2.1.7 on 2019-05-06 04:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('orm_practice_app', '0003_auto_20190420_1313'),
]
operations = [
migrations.CreateModel(
name='Mileage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.PositiveSmallIntegerField(default=0)),
('descriptions', models.CharField(max_length=128, null=True)),
],
),
migrations.CreateModel(
name='UserAddress',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('city', models.CharField(help_text='서울시,안양시,...', max_length=128)),
('gu', models.CharField(default='', help_text='서초구, 강남구,...,', max_length=128)),
('detail', models.CharField(default='', help_text='104동 101호', max_length=128)),
],
),
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('tel_num', models.CharField(max_length=128, null=True)),
('owned_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='mileage',
name='owned_userinfo',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.UserInfo'),
),
migrations.AddField(
model_name='mileage',
name='related_order',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='orm_practice_app.Order'),
),
]
<file_sep># Generated by Django 2.1.7 on 2019-04-20 13:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orm_practice_app', '0002_auto_20190420_1308'),
]
operations = [
migrations.AlterField(
model_name='company',
name='tel_num',
field=models.CharField(max_length=128, null=True),
),
]
<file_sep>from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Sum, Count, Avg
class Company(models.Model):
name: str = models.CharField(max_length=128, null=False)
tel_num: str = models.CharField(max_length=128, null=True)
address: str = models.CharField(max_length=128, null=False)
class Product(models.Model):
name: str = models.CharField(null=False, max_length=128)
price: int = models.PositiveIntegerField(null=False, default=0)
product_owned_company: Company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=False)
class OrderedProduct(models.Model):
product_cnt: int = models.PositiveIntegerField(null=False, default=1)
amount_of_credited_mileage: int = models.PositiveIntegerField(null=False)
related_product: Product = models.ForeignKey(Product, on_delete=models.CASCADE)
related_order = models.ForeignKey('Order', on_delete=models.CASCADE,null=True)
class Order(models.Model):
descriptions: str = models.CharField(null=False, default='비어있음..', max_length=128)
reg_date: datetime = models.DateTimeField(auto_created=True)
order_owner: User = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=False)
product_set_included_order: set = models.ManyToManyField(to=Product, related_name='ordered_product_set',
through='OrderedProduct',
through_fields=('related_order', 'related_product'),
)
class UserAddress(models.Model):
city = models.CharField(help_text='서울시,안양시,...', max_length=128, null=False)
gu = models.CharField(help_text='서초구, 강남구,...,', max_length=128, null=False, default='')
detail = models.CharField(help_text='104동 101호', max_length=128, null=False, default='')
class Mileage(models.Model):
owned_userinfo = models.ForeignKey(to='UserInfo', on_delete=models.CASCADE, null=True)
related_order = models.OneToOneField(Order, on_delete=models.CASCADE, null=False)
amount = models.PositiveSmallIntegerField(default=0)
descriptions = models.CharField(max_length=128, null=True)
class UserInfo(models.Model):
owned_user = models.ForeignKey(User, on_delete=models.CASCADE, null=False)
tel_num = models.CharField(max_length=128, null=True)
#
# Order.objects.get(id=3).product_set_included_order.annotate(num_name_blabla=Count('name')).aggregate(Avg('num_name_blabla'))
<file_sep>from random import randint
from django.core.management import BaseCommand
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.db import transaction
from django.utils import timezone
from orm_practice_app.models import Company, Product, Order, OrderedProduct
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--user_cnt', nargs=1, type=int)
parser.add_argument('--company_cnt', nargs=1, type=int)
parser.add_argument('--product_cnt', nargs=1, type=int)
parser.add_argument('--order_cnt', nargs=1, type=int)
def handle(self, *args, **options):
user_cnt = options['user_cnt'][0] or 100
company_cnt = options['company_cnt'][0] or 100
product_cnt = options['product_cnt'][0] or 100
order_cnt = options['order_cnt'][0] or 1000
suffix = User.objects.last().id if User.objects.exists() else 0
for i in range(0, user_cnt, 20):
User.objects.bulk_create([
User(
username='username' + str(suffix+idx + i),
email='<EMAIL>' + str(idx + i),
password=make_password('<PASSWORD>'),
is_active=True,
) for idx in range(1, 21)
])
users = User.objects.all()
for i in range(0, company_cnt, 20):
Company.objects.bulk_create([
Company(
name='company_name' + str(i + idx),
tel_num='070-123-4567',
address='서초구 ~~ 마제스타시티',
) for idx in range(1, 21)
])
companies = Company.objects.all()
for i in range(0, product_cnt, 100):
Product.objects.bulk_create([
Product(
name='product_name' + str(i + idx),
price=randint(10000, 100001),
product_owned_company=companies[randint(0, company_cnt - 1)//2],
) for idx in range(1, 101)
])
products = Product.objects.all()
for i in range(0, order_cnt, 100):
orders = Order.objects.bulk_create([
Order(
descriptions='주문의 상세내용입니다...' + str(i + idx),
reg_date=timezone.now(),
order_owner=users[randint(0, user_cnt - 1)//2],
) for idx in range(1, 101)
])
OrderedProduct.objects.bulk_create([
OrderedProduct(
product_cnt=randint(1, 30),
amount_of_credited_mileage=randint(100, 4000),
related_order=orders[idx - 1],
related_product=products[randint(0, product_cnt - 1)//2],
) for idx in range(1, 101)
])
self.stdout.write(self.style.SUCCESS('Successfully Create Bulk!!!!!!'))
| d68490eb60e3db4b2227fb16e7cfb6f09ca9b1cb | [
"Python",
"Text"
] | 7 | Python | heoheon-developer/Django_ORM_pratice_project | 0d0670ff715ff357eb5217240ee41f3531c98590 | cdeb009dcea8094c75737c7f4fa2b7e4f24995fa |
refs/heads/main | <repo_name>eljosephavila123/ReconnaissanceOnMars<file_sep>/recofmars/tools/__init__.py
from ._tools import show_image
<file_sep>/recofmars/__init__.py
r"""
#######
Reconnaissance on Mars with Machine Learning
#######
"""
from . import binarization
from . import pathfinder
from . import tools
<file_sep>/recofmars/pathfinder/__init__.py
from ._funcs import astar
<file_sep>/README.md
<p align="center">
<a href="" rel="noopener">
<img width=300px height=300px src="image/logo.png" alt="Project logo"></a>
</p>
<h1 align="center"> Reconnaissance on Mars with Machine Learning </h1>
<div align="center">
[]()
[]()
</div>
# Process.... 🧑🏼💻
- [ ] Mars aerial image segmentation
- [ ] Image binarization
- [ ] Validation
- [ ] Tests
- [ ] Creation of possible paths through images using A \* start
- [ ] Search training (A \* start)
- [ ] Classification of rocky materials (Tensorflow Lite)
- [ ] Simultaneous Work on Rover and Drone
### Autor
- <NAME>(octajos)
<file_sep>/recofmars/binarization/__funcs.py
import numpy as np
import cv2
import json
from matplotlib import pyplot as plt
def read_this(image_file, gray_scale=False):
image_src = cv2.imread(image_file)
if gray_scale:
image_src = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
else:
image_src = cv2.cvtColor(image_src, cv2.COLOR_BGR2RGB)
return image_src
def convert_binary(image_matrix, thresh_val):
white = 255
black = 0
initial_conv = np.where((image_matrix <= thresh_val), image_matrix, white)
final_conv = np.where((initial_conv > thresh_val), initial_conv, black)
return final_conv
def binarize_this(image_file, thresh_val=127, with_plot=False, gray_scale=False):
image_src = read_this(image_file=image_file, gray_scale=gray_scale)
if not gray_scale:
cmap_val = None
r_img, g_img, b_img = image_src[:, :, 0], image_src[:, :, 1], image_src[:, :, 2]
r_b = convert_binary(image_matrix=r_img, thresh_val=thresh_val)
g_b = convert_binary(image_matrix=g_img, thresh_val=thresh_val)
b_b = convert_binary(image_matrix=b_img, thresh_val=thresh_val)
image_b = np.dstack(tup=(r_b, g_b, b_b))
else:
cmap_val = "gray"
image_b = convert_binary(image_matrix=image_src, thresh_val=thresh_val)
if with_plot:
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(10, 20))
ax1.axis("off")
ax1.title.set_text("Original")
ax2.axis("off")
ax2.title.set_text("Binarized")
ax1.imshow(image_src, cmap=cmap_val)
ax2.imshow(image_b, cmap=cmap_val)
return image_b
return image_b
<file_sep>/recofmars/pathfinder/README.md
A* (pronounced "A-star") is a graph traversal and path search algorithm, which is often used in many fields of computer science due to its completeness, optimality, and optimal efficiency.[1] One major practical drawback is its ${O(b^{d})}O(b^d)$ space complexity, as it stores all generated nodes in memory. Thus, in practical travel-routing systems, it is generally outperformed by algorithms which can pre-process the graph to attain better performance, as well as memory-bounded approaches; however, A* is still the best solution in many cases.
<NAME>, <NAME> and <NAME> of Stanford Research Institute (now SRI International) first published the algorithm in 1968. It can be seen as an extension of Dijkstra's algorithm. A\* achieves better performance by using heuristics to guide its search. [1](https://en.wikipedia.org/wiki/A*_search_algorithm)

## References
[1] [https://en.wikipedia.org/wiki/A\*\_search_algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm)
<file_sep>/recofmars/tools/_tools.py
import matplotlib.pyplot as plt
# GRAPHICS TOOLS
def show_image(grid: list) -> list:
r"Shows the changes generated by the A star algorithm"
ptl.imshow(grid)
return grid
# GENERATE ROADS
<file_sep>/recofmars/binarization/__init__.py
from .__funcs import binarize_this
| a00ecf5bb6bb5b8eb38c6fbd468800fdff23fdf2 | [
"Markdown",
"Python"
] | 8 | Python | eljosephavila123/ReconnaissanceOnMars | 4ddf1f433f9d4f2e3abb272ef45bc27c9fe48af0 | daa168cc2cb3c39f404edb0beddde595ac886c0f |
refs/heads/master | <file_sep>import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns
from binarytree import heapq
heap = heapq
Time = 0
body_heap = []
list_times_lock1 = []
list_times_lock2 = []
list_times_lock3 = []
list_times_lock4 = []
list_times_lock5 = []
def Printlistship(list):
a = []
for x in list:
a.append(x.id)
print('Aqui va la lista')
print(a)
class lock:
def __init__(self, id):
self.id = id
self.name = 'lock' + str(id)
self.free = True
self.capacity = 12
self.list_ship = []
self.open = np.infty
self.ready_ship = np.infty
self.ready_transp = np.infty
self.ready_exit = np.infty
class Channel:
def __init__(self):
self.lockslist = initlocks()
def insert_ship_in_first_locks(self, id, ship):
lockx = self.lockslist[id]
if lockx.free:
if lockx.capacity >= ship.range:
lockx.list_ship.append(ship)
lockx.capacity = lockx.capacity - ship.range
if lockx.capacity == 0:
lockx.free = False
lockx.down = False
# Comenzar flujo de agua
return 0
lockx.free = False
# Comenzar flujo de agua
lockx.down = False
def free_lock(self, id_of_lock):
self.lockslist[id_of_lock].free = True
self.lockslist[id_of_lock].capacity = 12
self.lockslist[id_of_lock].list_ship = []
######Chekear el tiempo que demora en volver a bajar el agua
self.lockslist[id_of_lock].down = True
def move_into_locks(self, id_lock_orgin, id_lock_destiny):
lis = self.lockslist[id_lock_orgin].list_ship
self.free_lock(id_lock_orgin)
# Ver q las compuertas esten abiertas
self.lockslist[id_lock_destiny].free = False
self.lockslist[id_lock_destiny].capacity = self.lockslist[id_lock_orgin].capacity
self.lockslist[id_lock_destiny].list_ship = lis
# comenzar el flujo de agua
def fist_lock(self):
global Time
select_ships = self.select_ship_in()
for x in select_ships:
Time += x.tarrive
time_open = self.disexp(np.random.uniform(), 4)
time_in = self.disexp(np.random.uniform(), 2) * len(select_ships)
time_trans = self.disexp(np.random.uniform(), 7)
time_exit = (self.disexp(np.random.uniform(), 1.5)) * len(select_ships)
Time += time_exit + time_trans + time_in + time_open
return select_ships
def Media(self,*args):
suma = 0
denominador = 0
for x in args:
denominador += len(x)
for y in x:
suma += y
return suma/denominador
def manager(self):
global Time
global body_heap
list_of_ships = self.generate_list_of_ship()
self.build_heap(list_of_ships)
#print(body_heap)
while Time < 111100:
var = Time
list = self.fist_lock()
list_times_lock1.append(Time-var)
var = Time
self.all_steep(list)
list_times_lock2.append(Time - var)
var = Time
self.all_steep(list)
list_times_lock3.append(Time - var)
var = Time
self.all_steep(list)
list_times_lock4.append(Time - var)
var = Time
self.all_steep(list)
list_times_lock5.append(Time - var)
var = Time
print('La media de espera de los barcos es ' + str(
self.Media(list_times_lock2, list_times_lock1, list_times_lock3, list_times_lock4, list_times_lock5)) + ' minutos')
#while Time <= 100:
#flag = self.procces_tails()
#if flag[0]:
#self.next_lock(flag[1], 1)
#else:
#flag = self.all_steep(1,self.lockslist[1].list_ship)
#if flag[0]:
# self.next_lock(flag[1],2)
#else:
# flag = self.all_steep(2, self.lockslist[1].list_ship)
#if flag[0]:
# self.next_lock(flag[1],3)
#else:
# flag = self.all_steep(3, self.lockslist[1].list_ship)
#if flag[0]:
# self.next_lock(flag[1], 4)
#else:
# flag = self.all_steep(4, self.lockslist[1].list_ship)
def generate_list_of_ship(self) -> list:
list = []
id = 0
var = 50
for x in range(1, var):
id += 1
ran = np.random.randint(0, 781)
if ran < 240:
list.append((self.distnorm(ran, 5, 2), 2, id))
continue
if ran < 600:
list.append((self.distnorm(ran, 3, 1), 2, id))
continue
list.append((self.distnorm(ran, 10, 2), 2, id))
for x in range(1, var):
id += 1
ran = np.random.randint(0, 781)
if ran < 240:
list.append((self.distnorm(ran, 15, 3), 4, id))
continue
if ran < 600:
list.append((self.distnorm(ran, 10, 5), 4, id))
continue
list.append((self.distnorm(ran, 20, 5), 4, id))
for x in range(1, var):
id += 1
ran = np.random.randint(0, 781)
if ran < 240:
list.append((self.distnorm(ran, 45, 3), 8, id))
continue
if ran < 600:
list.append((self.distnorm(ran, 35, 7), 8, id))
continue
list.append((self.distnorm(ran, 60, 9), 8, id))
return list
def build_heap(self,lis):
for x in lis:
if x[0] <= 780:
heap.heappush(body_heap, x)
else:
continue
def distnorm(self, x, mu, sigma):
return int(((1 / (sigma * np.sqrt(2 * np.pi))) * (np.e ** (((-1) / 2)) * ((x - mu) / sigma) ** 2)) / 10)
def disexp(self, x, alpha):
return int(((1 / alpha) * np.e ** (-x / alpha)) * 70)
def run_locks(self):
for x in reversed(self.lockslist):
if not x.free:
for y in x.list_ship:
pass
else:
continue
def procces_tails(self ):
if self.lockslist[0].free:
#print('Comienza la primera excluza ')
#if self.lockslist[0].free:
if self.lockslist[0].open == np.infty:
time_open = self.disexp(np.random.uniform(),4)
self.lockslist[0].open = time_open
if self.lockslist[0].free:
if self.lockslist[0].open == 0:
#print('Ya pueden entrar los barcos')
list = self.select_ship_in()
self.lockslist[0].list_ship = list
if self.lockslist[0].ready_ship == np.infty:
time_in = self.disexp(np.random.uniform(),2)* len(list)
self.lockslist[0].ready_ship = time_in
if self.lockslist[0].ready_ship == 0:
self.lockslist[0].free = False
Printlistship(self.lockslist[0].list_ship)
return (True,self.lockslist[0].list_ship)
if self.lockslist[0].ready_ship > 0:
self.lockslist[0].ready_ship -= 1
else:
self.lockslist[0].open -= 1
if not self.lockslist[0].free and self.lockslist[0].open == 0:
if self.lockslist[0].ready_transp == np.infty:
time_trans = self.disexp(np.random.uniform(),7)
self.lockslist[0].ready_transp = time_trans
if self.lockslist[0].ready_transp == 0:
if self.lockslist[0].ready_exit == np.infty:
time_exit = (self.disexp(np.random.uniform(),1.5))* len(self.lockslist[0].list_ship)
self.lockslist[0].ready_exit = time_exit
if self.lockslist[0].ready_transp > 0:
self.lockslist[0].ready_transp -= 1
if self.lockslist[0].ready_exit == 0:
id = self.lockslist[0].id
list_to_ret = self.lockslist[0].list_ship
self.lockslist[0] = lock(id)
return (True,list_to_ret)
if self.lockslist[0].ready_exit > 0:
self.lockslist[0].ready_exit -= 1
return (False,[])
def next_lock(self,list,lock_id):
self.all_steep(lock_id,list)
def all_steep(self, list):
global Time
time_open = self.disexp(np.random.uniform(), 4)
time_in = self.disexp(np.random.uniform(), 2) * len(list)
time_trans = self.disexp(np.random.uniform(), 7)
time_exit = (self.disexp(np.random.uniform(), 1.5)) * len(list)
Time += time_open + time_in +time_trans + time_exit
def select_ship_in(self) -> list:
list_aux = []
while len(body_heap) > 0:
pop = heap.heappop(body_heap)
if self.lockslist[0].capacity >= pop[1]:
self.lockslist[0].list_ship.append(ship(pop[2], pop[1],pop[0]))
self.lockslist[0].capacity -= pop[1]
if self.lockslist[0].capacity == 0:
return self.lockslist[0].list_ship
else:
list_aux.append(pop)
else:
for x in list_aux:
heap.heappush(body_heap,x)
return self.lockslist[0].list_ship
# Empezar el poceso sin estar lleno el dique
class ship:
def __init__(self, id, range ,tarrive):
self.id = id;
self.tarrive = tarrive
self.tbegining = 0
self.texit = 0
self.texcusa1 = 0
self.texcusa2 = 0
self.texcusa3 = 0
self.texcusa4 = 0
self.texcusa5 = 0
self.range = range
def initlocks():
list = []
for x in range(1, 6):
list.append(lock(x))
return list
if __name__ == '__main__':
canal = Channel()
canal.manager()
#normal = distnorm(5,2)
#normal = stats.norm(60, 9)
#x = np.linspace(normal.ppf(0.01),normal.ppf(0.99), 100)
#num = np.random.randint(0,780)
#print(num)
#fp = normal.pdf(num) # Función de Probabil
#print(x)
#print(fp)
#print(np.random.rand(4))
#print(number)
#print(distnorm(1,60,9))
#print(generate_list_of_ship())
#print(stats.norm(60,9).)
<file_sep># <NAME>
## Integrante
<NAME> 411
Requisitos:
python3
***import numpy as np
***from binarytree import heapq
Ejecutar:
python3 Canal.py
| 98af366882243fec41fe1c3ef6f06aa31fd85eff | [
"Markdown",
"Python"
] | 2 | Python | Leandroglez39/CanalMaritimo | 741b51483dde7771997c9b9c2cc01b80286ef579 | 1f433d9d7bbe10359b21e8385256a339e25c316d |
refs/heads/master | <repo_name>joao-parana/ss31<file_sep>/ex-2-2/start-app.sh
#!/bin/bash
set -e
APP_NAME=ss31-ex-2-2
if [ $1 = 'build' ];
then
mvn clean
mvn package && rm -rf tomcat8x/webapps/$APP_NAME*
cp target/$APP_NAME-1.0.war tomcat8x/webapps/$APP_NAME.war
fi
#
rm -rf tomcat8x/logs/*.log
rm -rf tomcat8x/logs/*.txt
cd tomcat8x/bin/
./start-tomcat.sh
<file_sep>/ldap/run-app.sh
#!/bin/bash
set -e
if [ $1 = 'build' ];
then
mvn package && rm -rf tomcat8x/webapps/my-calendar*
cp target/chapter05.01-calendar-1.0.war tomcat8x/webapps/my-calendar.war
fi
#
cd tomcat8x/bin/
./run-tomcat.sh
<file_sep>/ad-ldap/README.md
# my-calendar
## Build & Run
```
./start-app
```
## Config
```
cat WEB-INF/spring/security-ldap-explicitly.xml
```
## Dependências
LDAP Server rodando no **host** corp.jbcpcalendar.com na **porta** 389
```
more /etc/hosts
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
# Add others entries.
##
127.0.0.1 localhost
127.0.0.1 corp.jbcpcalendar.com
. . .
```
A classe **org.springframework.security.ldap.authentication.LdapAuthenticationProvider** será invocada e delega a pesquisa no diretório a classe **org.springframework.security.ldap.search.FilterBasedLdapUserSearch** que usa **searchFilter** '(sAMAccountName={0})' e **searchBase** 'CN=Users'
No caso de ocorrer um erro, como por exemplo: java.net.ConnectException: **Connection refused**, a aplicação é desviada para **/my-calendar/login/form?error** para exibir a mensagem.
O AD LDS (**Active Directory Lightweight Directory Services**) pode ser obtido no site da Microsoft em [https://www.microsoft.com/pt-br/download/details.aspx?id=14683](https://www.microsoft.com/pt-br/download/details.aspx?id=14683) e funciona no **Windows 7**

<file_sep>/ex-2-2/src/main/java/Cripto.java
public class Cripto {
public static void main(String[] args) {
char letraA = 'A';
int valorNumericoDaLetraA = (int) letraA;
System.out.println(valorNumericoDaLetraA);
int[] letras = { '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' };
for (int deslocamento : letras) {
char meuChar = (char) deslocamento;
System.out.println(meuChar + " = " + deslocamento);
}
// Para o exemplo da chave BUGRE temos
int[] deslocamentoBUGRE = { 'B', 'U', 'G', 'R', 'E' };
int[] mensagem = { 'N', 'E', 'G', 'O', 'C', 'I', 'O', 'O', 'K', 'D', 'E', 'Z', 'M', 'I', 'L', 'H', 'O', 'E',
'S' };
int indiceChave = 0;
for (int caracter : mensagem) {
int criptografado = (caracter + (int) deslocamentoBUGRE[indiceChave]) - 65;
if (criptografado > 90) {
criptografado = criptografado - 26;
}
System.out.println((char) deslocamentoBUGRE[indiceChave] + " # " + caracter + " => " + criptografado + " - "
+ (char) criptografado);
// Incrementa o indice da chave
indiceChave++;
// Reseta o indice da chave
if (indiceChave > 4) {
indiceChave = 0;
}
}
}
}
<file_sep>/README.md
#spring-security-3-1
Este Repositório contém exemplos de uso do Spring Security.
O trabalho foi baseado no livro:
**Spring Security 3.1 - Secure your web applications from hackers with this step-by-step guide**
Autores: <NAME> e <NAME>
editado pela PACKT
## Exemplo com LDAP usando AD da Microsoft
> Veja os diretórios **ldap** e **ad-ldap**
## Active Directory Lightweight Directory Services no Windows7 64bits
[https://dzone.com/articles/getting-started-active](https://dzone.com/articles/getting-started-active)
O arquivo **Windows6.1-KB975541-x64.msu** que é o Setup para Windows 7 encontra-se neste repositório.
## O que temos no repositório
* Exemplo básico de uso do Spring Security com adaptações simples.
* Informações de como integrar o LDAP Directory Services com o Spring Security
## Veja o que você precisa para usar estes códigos
* Java Development Kit 1.8 pode ser baixado do site da Oracle
* Spring Tool Suite 3.1.0.RELEASE+ **é opcional** e pode ser baixado de http://www.springsource.org/sts
* Apache Tomcat 8 pode ser baixado de http://tomcat.apache.org/
* Apache Maven 3 pode ser baixado de http://maven.apache.org/
## Para quem se destina este repositório
Desenvolvedores Java com conhecimento básico de criação de aplicação Java e de XML
<file_sep>/ldap/tomcat8x/bin/run-tomcat.sh
#!/bin/bash
set -e
export CATALINA_BASE=../
export CATALINA_HOME=../../../tomcat8x/
$CATALINA_HOME/bin/catalina.sh run
<file_sep>/docs/README.md
Este Diretório armazena os assets usados na documentação
<file_sep>/ex-0-1/README.md
# ss31-ex-0-1
<file_sep>/first/README.md
### Arquivo security.xml

<file_sep>/first/src/main/java/first/web/model/CreateEventForm.java
package first.web.model;
import java.util.Calendar;
import javax.validation.constraints.NotNull;
import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import first.domain.Event;
import first.service.CalendarService;
import first.service.UserContext;
import first.web.EventsController;
/**
* A form object that is used for creating a new {@link Event}. Using a
* different object is one way of preventing malicious users from filling out
* field that they should not (i.e. fill out a different owner field).
*
* @author <NAME>
*
*/
public class CreateEventForm {
private static final Logger logger = Logger.getLogger(CreateEventForm.class);
public CreateEventForm() {
logger.info("••• criando CreateEventForm");
}
@NotEmpty(message = "Attendee Email is required")
@Email(message = "Attendee Email must be a valid email")
private String attendeeEmail;
@NotEmpty(message = "Summary is required")
private String summary;
@NotEmpty(message = "Description is required")
private String description;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
@NotNull(message = "Event Date/Time is required")
private Calendar when;
public String getAttendeeEmail() {
logger.info("••• getAttendeeEmail() running");
return attendeeEmail;
}
public void setAttendeeEmail(String attendeeEmail) {
logger.info("••• setAttendeeEmail() running");
this.attendeeEmail = attendeeEmail;
}
public String getSummary() {
logger.info("••• getSummary() running");
return summary;
}
public void setSummary(String summary) {
logger.info("••• setSummary() running");
this.summary = summary;
}
public String getDescription() {
logger.info("••• getDescription() running");
return description;
}
public void setDescription(String description) {
logger.info("••• setDescription() running");
this.description = description;
}
public Calendar getWhen() {
logger.info("••• getWhen() running");
return when;
}
public void setWhen(Calendar when) {
logger.info("••• setWhen() running");
this.when = when;
}
}<file_sep>/ldap/README.md
#
```
Usuário senha Observação
---------------------+---------+-----------------------------------------
uid=admin,ou=system secret Conta de Administração do Diretório LDAP
<EMAIL> admin1 Conta de usuário no grupo Admin
<EMAIL> user1 Conta de usuário ordinário
<EMAIL> user1 Conta de usuário ordinário
<EMAIL> user2 Conta de usuário ordinário
```
Usuários podem ser vistos em `src/main/resources/ldif/calendar.ldif`
Use os comandos abaixo:
```
mvn package && rm -rf tomcat8x/webapps/my-calendar*
cp target/chapter05.01-calendar-1.0.war tomcat8x/webapps/my-calendar.war
cd tomcat8x/bin/
./run-tomcat.sh
```
Por conveniencia foi criada a shel `run-app.sh` que contém este código. Assim basta executar :
```
./run-app.sh
```
Esta shell tem o seguinte conteúdo
```
#!/bin/bash
set -e
if [ $1 = 'build' ];
then
mvn package && rm -rf tomcat8x/webapps/my-calendar*
cp target/chapter05.01-calendar-1.0.war tomcat8x/webapps/my-calendar.war
fi
#
cd tomcat8x/bin/
./run-tomcat.sh
```
| 418ed42d06ca748052e63a2f0d990852e053cea2 | [
"Markdown",
"Java",
"Shell"
] | 11 | Shell | joao-parana/ss31 | e86c851740bb89ad0be092d5d32f6c0d2ef92a41 | 0c4035afc5a84157dcc8fa282eab4dbd3788e614 |
refs/heads/master | <file_sep>package bitset_test
import (
"testing"
"github.com/tomcraven/bitset"
)
func TestCreate(t *testing.T) {
bitset.Create(10)
}
func createFromStringTest(input string, t *testing.T) {
b := bitset.CreateFromString(input)
if b.Size() != uint(len(input)) {
t.Error("bitset should have size", len(input))
}
for i, character := range input {
shouldBeSet := character == '1'
shouldBeClear := !shouldBeSet
if shouldBeSet && !b.Get(uint(i)) {
t.Error("bitset should have bit at position", i, "set")
} else if shouldBeClear && b.Get(uint(i)) {
t.Error("bitset should not have bit at position", i, "set")
}
}
}
func TestCreateFromString(t *testing.T) {
createFromStringTest("00000000", t)
createFromStringTest("0", t)
createFromStringTest("1", t)
createFromStringTest("0110", t)
}
<file_sep>package bitset_test
import "testing"
import "github.com/tomcraven/bitset"
func shouldBeSet(t *testing.T, b bitset.Bitset, indexes ...uint) {
for _, v := range indexes {
if !b.Get(v) {
t.Error("bitset should have bit set at position", v)
}
}
}
func shouldBeClear(t *testing.T, b bitset.Bitset, indexes ...uint) {
for _, v := range indexes {
if b.Get(v) {
t.Error("bitset should not have bit set at position", v)
}
}
}
func TestSliceGetSetClear(t *testing.T) {
b := bitset.Create(10)
b.Set(0, 1, 2, 3, 4)
slice := b.Slice(0, 5)
if slice.Size() != 5 {
t.Error("sliced bitset should have size", 5)
}
shouldBeSet(t, slice, 0, 1, 2, 3, 4)
// Should set and clear bits in original bitset
slice.Clear(0, 1, 2, 3, 4)
slice.Set(5, 6, 7, 8, 9)
for i := uint(0); i < 5; i++ {
if slice.Get(i) || b.Get(i) {
t.Error("original and sliced bitset should not have bit set at index", i)
}
}
for i := uint(5); i < 10; i++ {
if !(slice.Get(i) && b.Get(i)) {
t.Error("original and sliced btiset should have bit set at index", i)
}
}
}
func TestSliceSetTo(t *testing.T) {
b := bitset.Create(10)
b.Set(5, 6, 7, 8, 9)
slice := b.Slice(0, 5)
slice.SetTo(0, true)
slice.SetTo(5, false)
shouldBeSet(t, b, 0)
shouldBeClear(t, b, 5)
}
func TestSliceSetAll(t *testing.T) {
b := bitset.Create(10)
slice := b.Slice(2, 7)
slice.SetAll()
shouldBeSet(t, b, 2, 3, 4, 5, 6)
shouldBeClear(t, b, 0, 1, 7, 8, 9)
}
func TestSliceClearAll(t *testing.T) {
b := bitset.Create(10)
b.SetAll()
slice := b.Slice(2, 7)
slice.ClearAll()
shouldBeSet(t, b, 0, 1, 7, 8, 9)
shouldBeClear(t, b, 2, 3, 4, 5, 6)
}
func TestSliceInvert(t *testing.T) {
b := bitset.Create(10)
slice := b.Slice(2, 7)
slice.Invert()
shouldBeSet(t, b, 2, 3, 4, 5, 6)
shouldBeClear(t, b, 0, 1, 7, 8, 9)
}
func TestSliceClone(t *testing.T) {
b := bitset.Create(10)
slice := b.Slice(2, 7)
slice.Set(0, 3, 4)
sliceClone := slice.Clone()
sliceClone.Invert()
if sliceClone.Size() != slice.Size() {
t.Error("slice and clone should have the same size")
}
for i := uint(0); i < slice.Size(); i++ {
if slice.Get(i) == sliceClone.Get(i) {
t.Error("slice clone was inverted, it should be opposite to original")
}
}
}
func TestSliceSlice(t *testing.T) {
b := bitset.Create(10)
slice := b.Slice(2, 7)
sliceSlice := slice.Slice(1, 5)
sliceSlice.SetAll()
// sliceSlice == 1111
shouldBeSet(t, sliceSlice, 0, 1, 2, 3)
// slice == 0111100
shouldBeClear(t, slice, 0, 5, 6)
shouldBeSet(t, slice, 1, 2, 3, 4)
// b = 0001111000
shouldBeClear(t, b, 0, 1, 2, 7, 8, 9)
shouldBeSet(t, b, 3, 4, 5, 6)
}
func TestSliceEqualsBitset(t *testing.T) {
b := bitset.Create(10)
slice := b.Slice(0, 10)
newBitset := bitset.Create(10)
b.Set(0, 2)
slice.Set(1, 3)
if !slice.Equals(b) {
t.Error("bitset and slice should be equal")
}
newBitset.Set(0, 1, 2, 3)
if !slice.Equals(newBitset) {
t.Error("slice and new bitset should be equal")
}
newBitset.ClearAll()
if slice.Equals(newBitset) {
t.Error("slice and new bitset should not be equal")
}
}
func TestSliceEqualsSlice(t *testing.T) {
a := bitset.Create(10).Slice(0, 10)
b := bitset.Create(10).Slice(0, 10)
c := b.Slice(0, 2)
if b.Equals(c) {
t.Error("slices with different sizes should not be equal")
}
if !a.Equals(b) {
t.Error("slices a and b should be equal")
}
a.Set(7, 8, 9)
if a.Equals(b) {
t.Error("slices a and b should not be equal")
}
}
func TestSliceBuildUint8(t *testing.T) {
// Bitset too small
buildUint8Test(true, func() bitset.Bitset {
b := bitset.Create(1)
return b.Slice(0, 1)
}, 0, t)
// Bitset big enough but blank
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(8)
b.ClearAll()
return b.Slice(0, 8)
}, 0, t)
// Bitset with all some bits set
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(8)
b.SetAll()
return b.Slice(0, 8)
}, 255, t)
// Bitset with some bits set 00000000 01100001 == 97 == 'a'
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(16)
b.ClearAll()
b.Set(8)
b.Set(13)
b.Set(14)
return b.Slice(8, 16)
}, 97, t)
}
<file_sep>package bitset
import "fmt"
type slice struct {
other Bitset
begin, end uint
}
func (s *slice) Set(indexes ...uint) {
for i := uint(0); i < uint(len(indexes)); i++ {
index := indexes[i]
s.other.Set(s.begin + index)
}
}
func (s *slice) SetTo(index uint, val bool) {
s.other.SetTo(s.begin+index, val)
}
func (s *slice) SetAll() {
for i := s.begin; i < s.end; i++ {
s.other.Set(i)
}
}
func (s *slice) Clear(indexes ...uint) {
for i := uint(0); i < uint(len(indexes)); i++ {
index := indexes[i]
s.other.Clear(s.begin + index)
}
}
func (s *slice) ClearAll() {
for i := s.begin; i < s.end; i++ {
s.other.Clear(i)
}
}
func (s *slice) Invert() {
for i := s.begin; i < s.end; i++ {
s.other.SetTo(i, !s.other.Get(i))
}
}
func (s *slice) Get(index uint) bool {
return s.other.Get(s.begin + index)
}
func (s *slice) Size() uint {
return s.end - s.begin
}
func (s *slice) Clone() Bitset {
return &slice{
begin: s.begin,
end: s.end,
other: s.other.Clone(),
}
}
func (s *slice) Slice(begin, end uint) Bitset {
return &slice{
begin: begin,
end: end,
other: s,
}
}
func (s *slice) Equals(other Bitset) bool {
return other.equalsSlice(s)
}
func (s *slice) equalsBitset(other *bitset) bool {
return equalsBitsetSlice(other, s)
}
func (s *slice) equalsSlice(other *slice) bool {
return equalsSliceSlice(s, other)
}
func (s *slice) Output() {
for i := uint(0); i < s.Size(); i++ {
if s.Get(i) {
fmt.Printf("1")
} else {
fmt.Printf("0")
}
}
fmt.Printf("\n")
}
func (s *slice) BuildUint8(output *uint8) bool {
if s.Size() < 8 {
return false
}
for i := uint(0); i < 8; i++ {
if s.Get(i) {
(*output) |= 1 << i
} else {
(*output) &= ^(1 << i)
}
}
return true
}
<file_sep>package main
import (
"fmt"
"github.com/tomcraven/bitset"
)
func settingAndClearing() {
fmt.Println(" ** Setting and clearing **")
b := bitset.Create(8)
b.Output() // 00000000
b.Set(1, 2, 7)
b.Output() // 01100001
b.Clear(2)
b.Output() // 01000001
b.SetAll()
b.Output() // 11111111
b.Clear(1, 2, 3, 4, 5)
b.Output() // 10000011
b.ClearAll()
b.Output() // 00000000
fmt.Println()
}
func slicing() {
fmt.Println(" ** Slicing **")
b := bitset.Create(8)
b.Output() // 00000000
slice := b.Slice(0, 4)
b.Set(0, 1, 4, 5)
b.Output() // 11001100
slice.Output() // 1100
slice.SetAll()
b.Output() // 11111100
slice.Output() // 1111
slicedSlice := slice.Slice(2, 4)
b.ClearAll()
b.Output() // 00000000
slice.Output() // 0000
slicedSlice.Output() // 00
slicedSlice.Set(0, 1)
slicedSlice.Output() // 11
slice.Output() // 0011
b.Output() // 00110000
fmt.Println()
}
func building() {
fmt.Println(" ** Building **")
b := bitset.Create(16)
var output uint8
b.BuildUint8(&output)
b.Output() // 0000000000000000
fmt.Println(output) // 0
b.Set(0, 1, 2, 3, 4, 5, 6, 7)
b.Output() // 1111111100000000
b.BuildUint8(&output)
fmt.Println(output) // 255
slice := b.Slice(4, 12)
slice.Output() // 11110000
slice.BuildUint8(&output)
fmt.Println(output) // 15
}
func main() {
settingAndClearing()
slicing()
building()
/*
Program output:
** Setting and clearing **
00000000
01100001
01000001
11111111
10000011
00000000
** Slicing **
00000000
11001100
1100
11111100
1111
00000000
0000
00
11
0011
00110000
** Building **
0000000000000000
0
1111111100000000
255
11110000
15
*/
}
<file_sep>package bitset
const bitsPerUint64 = 64
type Bitset interface {
Set(...uint)
SetTo(uint, bool)
SetAll()
Clear(...uint)
ClearAll()
Invert()
Get(uint) bool
Size() uint
Clone() Bitset
Slice(uint, uint) Bitset
Output()
BuildUint8(*uint8) bool
Equals(Bitset) bool
equalsBitset(*bitset) bool
equalsSlice(*slice) bool
}
func bitArraySize(numBits uint) uint {
return (numBits / bitsPerUint64) + 1
}
// Create takes a size and returns a bitset with that size
func Create(size uint) Bitset {
b := bitset{}
b.init(size)
return &b
}
// CreateFromString takes a string of 1s and 0s and returns a bitset
// that matches that
func CreateFromString(str string) Bitset {
b := Create(uint(len(str)))
for i, char := range str {
b.SetTo(uint(i), char == '1')
}
return b
}
func equalsBitsetBitset(a *bitset, b *bitset) bool {
if a.Size() != b.Size() {
return false
}
for i := 0; i < len(a.bits); i++ {
if a.bits[0] != b.bits[0] {
return false
}
}
return true
}
// TODO - can we do better?
func naiveEquality(a Bitset, b Bitset) bool {
if a.Size() != b.Size() {
return false
}
for i := uint(0); i < a.Size(); i++ {
if a.Get(i) != b.Get(i) {
return false
}
}
return true
}
func equalsBitsetSlice(a *bitset, b *slice) bool {
return naiveEquality(a, b)
}
func equalsSliceSlice(a *slice, b *slice) bool {
return naiveEquality(a, b)
}
<file_sep># Bitset
A simple bitset implementation in Go.
## Installation
```
go get github.com/tomcraven/bitset
```
## Example
```go
package main
import (
"fmt"
"github.com/tomcraven/bitset"
)
func settingAndClearing() {
fmt.Println(" ** Setting and clearing **")
b := bitset.Create(8)
b.Output() // 00000000
b.Set(1, 2, 7)
b.Output() // 01100001
b.Clear(2)
b.Output() // 01000001
b.SetAll()
b.Output() // 11111111
b.Clear(1, 2, 3, 4, 5)
b.Output() // 10000011
b.ClearAll()
b.Output() // 00000000
fmt.Println()
}
func slicing() {
fmt.Println(" ** Slicing **")
b := bitset.Create(8)
b.Output() // 00000000
slice := b.Slice(0, 4)
b.Set(0, 1, 4, 5)
b.Output() // 11001100
slice.Output() // 1100
slice.SetAll()
b.Output() // 11111100
slice.Output() // 1111
slicedSlice := slice.Slice(2, 4)
b.ClearAll()
b.Output() // 00000000
slice.Output() // 0000
slicedSlice.Output() // 00
slicedSlice.Set(0, 1)
slicedSlice.Output() // 11
slice.Output() // 0011
b.Output() // 00110000
fmt.Println()
}
func building() {
fmt.Println(" ** Building **")
b := bitset.Create(16)
var output uint8
b.BuildUint8(&output)
b.Output() // 0000000000000000
fmt.Println(output) // 0
b.Set(0, 1, 2, 3, 4, 5, 6, 7)
b.Output() // 1111111100000000
b.BuildUint8(&output)
fmt.Println(output) // 255
slice := b.Slice(4, 12)
slice.Output() // 11110000
slice.BuildUint8(&output)
fmt.Println(output) // 15
}
func main() {
settingAndClearing()
slicing()
building()
/*
Program output:
** Setting and clearing **
00000000
01100001
01000001
11111111
10000011
00000000
** Slicing **
00000000
11001100
1100
11111100
1111
00000000
0000
00
11
0011
00110000
** Building **
0000000000000000
0
1111111100000000
255
11110000
15
*/
}
```
<file_sep>package bitset
import (
"fmt"
"math"
)
type bitset struct {
bits []uint64
size uint
}
func (b *bitset) init(size uint) {
b.size = size
b.bits = make([]uint64, bitArraySize(size))
}
func (b *bitset) Set(indexes ...uint) {
for i := uint(0); i < uint(len(indexes)); i++ {
index := indexes[i]
elementIndex := index / bitsPerUint64
bitIndex := index % bitsPerUint64
b.bits[elementIndex] |= 1 << bitIndex
}
}
func (b *bitset) SetTo(index uint, value bool) {
if value {
b.Set(index)
} else {
b.Clear(index)
}
}
func (b *bitset) setImpl(index uint) {
}
func (b *bitset) Get(index uint) bool {
elementIndex := index / bitsPerUint64
bitIndex := index % bitsPerUint64
return ((b.bits[elementIndex] >> bitIndex) & 1) == 1
}
func (b *bitset) Clear(indexes ...uint) {
for i := uint(0); i < uint(len(indexes)); i++ {
index := indexes[i]
elementIndex := index / bitsPerUint64
bitIndex := index % bitsPerUint64
b.bits[elementIndex] &= ^(1 << bitIndex)
}
}
func (b *bitset) Size() uint {
return b.size
}
func (b *bitset) Clone() Bitset {
new := bitset{}
new.init(b.size)
copy(new.bits, b.bits)
return &new
}
func (b *bitset) SetAll() {
for i := range b.bits {
b.bits[i] = math.MaxUint64
}
}
func (b *bitset) ClearAll() {
for i := range b.bits {
b.bits[i] = 0
}
}
func (b *bitset) Invert() {
for i := range b.bits {
b.bits[i] = ^b.bits[i]
}
}
func (b *bitset) Equals(other Bitset) bool {
return other.equalsBitset(b)
}
func (b *bitset) equalsBitset(other *bitset) bool {
return equalsBitsetBitset(b, other)
}
func (b *bitset) equalsSlice(other *slice) bool {
return equalsBitsetSlice(b, other)
}
func (b *bitset) Output() {
for i := uint(0); i < b.Size(); i++ {
if b.Get(i) {
fmt.Printf("1")
} else {
fmt.Printf("0")
}
}
fmt.Printf("\n")
}
func (b *bitset) BuildUint8(output *uint8) bool {
if b.Size() < 8 {
return false
}
for i := uint(0); i < 8; i++ {
if b.Get(i) {
(*output) |= 1 << i
} else {
(*output) &= ^(1 << i)
}
}
return true
}
func (b *bitset) Slice(begin, end uint) Bitset {
return &slice{
begin: begin,
end: end,
other: b,
}
}
<file_sep>package bitset_test
import "testing"
import "github.com/tomcraven/bitset"
func TestSetGet(t *testing.T) {
bitset := bitset.Create(10)
if bitset.Get(0) {
t.Error("bitset should not have the bit at position 0 set")
}
if bitset.Get(5) {
t.Error("bitset should not have the bit at position 0 set")
}
bitset.Set(0)
bitset.Set(5)
if !bitset.Get(0) {
t.Error("bitset should have the bit at position 0 set")
}
if !bitset.Get(5) {
t.Error("bitset should have the bit at position 0 set")
}
}
func sizeTest(size uint, t *testing.T) {
bitset := bitset.Create(size)
if bitset.Size() != size {
t.Error("bitset should have size", size)
}
}
func TestSize(t *testing.T) {
sizeTest(0, t)
sizeTest(10, t)
}
func TestClear(t *testing.T) {
bitset := bitset.Create(10)
bitset.Set(0)
bitset.Set(5)
bitset.Clear(0)
if bitset.Get(0) {
t.Error("bitset should not have the bit at position 0 set")
}
if !bitset.Get(5) {
t.Error("bitset should have the bit at position 0 set")
}
}
func TestSetTo(t *testing.T) {
bitset := bitset.Create(10)
bitset.SetTo(0, false)
bitset.SetTo(5, true)
if bitset.Get(0) {
t.Error("bitset should not have the bit at position 0 set")
}
if !bitset.Get(5) {
t.Error("bitset should have the bit at position 0 set")
}
}
func TestClone(t *testing.T) {
bitset := bitset.Create(10)
bitset.Set(0)
bitset.Set(3)
bitset.Set(8)
copy := bitset.Clone()
for _, i := range []uint{0, 3, 8} {
if !copy.Get(i) {
t.Error("bitset should not have the bit at position", i, "set")
}
}
for _, i := range []uint{1, 2, 4, 5, 6, 7, 9} {
if copy.Get(i) {
t.Error("bitset should not have the bit at position", i, "set")
}
}
}
func TestSetAll(t *testing.T) {
bitset := bitset.Create(64)
for i := uint(0); i < bitset.Size(); i++ {
if bitset.Get(i) {
t.Error("bitset should not have the bit at position", i, "set")
}
}
bitset.SetAll()
for i := uint(0); i < bitset.Size(); i++ {
if !bitset.Get(i) {
t.Error("bitset should have the bit at position", i, "set")
}
}
}
func TestClearAll(t *testing.T) {
bitset := bitset.Create(10)
bitset.SetAll()
for i := uint(0); i < bitset.Size(); i++ {
if !bitset.Get(i) {
t.Error("bitset should have the bit at position", i, "set")
}
}
bitset.ClearAll()
for i := uint(0); i < bitset.Size(); i++ {
if bitset.Get(i) {
t.Error("bitset should not have the bit at position", i, "set")
}
}
}
func TestInvert(t *testing.T) {
b := bitset.Create(10)
b.Invert()
for i := uint(0); i < b.Size(); i++ {
if !b.Get(i) {
t.Error("bitset should have the bit at position", i, "set")
}
}
}
func TestEqualsBitset(t *testing.T) {
a := bitset.Create(10)
b := bitset.Create(10)
c := bitset.Create(20)
if a.Equals(c) {
t.Error("a should not equal c")
}
a.Set(0, 5, 6, 7)
b.Set(0, 5, 6, 7)
if !a.Equals(b) {
t.Error("a should equal b")
}
b.ClearAll()
if a.Equals(b) {
t.Error("a should now not equal b")
}
}
func TestEqualsSlice(t *testing.T) {
b := bitset.Create(10)
b.Set(0, 2, 4, 6, 8)
slice := b.Slice(0, 10)
if !b.Equals(slice) {
t.Error("bitset and slice should be equal")
}
// Changing these change for both because it's a slice
// b == slice == 1000000001
b.Set(9)
slice.Set(0)
if !b.Equals(slice) {
t.Error("bitset and slice should be equal")
}
// newBitset == 1000000000
newBitset := bitset.Create(10)
newBitset.Set(0)
if newBitset.Equals(slice) {
t.Error("newBitset and the old slice should not be equal")
}
}
func buildUint8Test(shouldFail bool, f func() bitset.Bitset, expected uint8, t *testing.T) {
b := f()
var input uint8
if b.BuildUint8(&input) && shouldFail {
t.Error("should fail to build")
}
if input != expected {
t.Error(input, "does not equal the expected result", expected)
}
}
func TestBuildUint8(t *testing.T) {
// Bitset too small
buildUint8Test(true, func() bitset.Bitset {
b := bitset.Create(1)
return b
}, 0, t)
// Bitset big enough but blank
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(8)
b.ClearAll()
return b
}, 0, t)
// Bitset with all some bits set
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(8)
b.SetAll()
return b
}, 255, t)
// Bitset with some bits set 01100001 == 97 == 'a'
buildUint8Test(false, func() bitset.Bitset {
b := bitset.Create(8)
b.ClearAll()
b.Set(0)
b.Set(5)
b.Set(6)
return b
}, 97, t)
}
func TestSlice(t *testing.T) {
b := bitset.Create(10)
b.Set(0)
b.Set(1)
b.Set(2)
slice := b.Slice(0, 3)
if slice.Size() != 3 {
t.Error("sliced bitset should have size", 3)
}
for i := uint(0); i < slice.Size(); i++ {
if !slice.Get(i) {
t.Error("sliced bitset should have bit set at index", i)
}
}
}
func TestSetVarArgs(t *testing.T) {
b := bitset.Create(10)
b.Set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for i := uint(0); i < b.Size(); i++ {
if !b.Get(i) {
t.Error("bitset should have bit set at index", i)
}
}
}
func TestClearVarArgs(t *testing.T) {
b := bitset.Create(10)
b.SetAll()
b.Clear(0, 1, 2, 3, 4)
for i := uint(0); i < 5; i++ {
if b.Get(i) {
t.Error("bitset should not have bitset at index", i)
}
}
}
| 94d1f7e9c898e98bd24ea42497679c4adba76f08 | [
"Markdown",
"Go"
] | 8 | Go | tomcraven/bitset | 93818f3f232582fd237f081954a2eac988116694 | 80de00a842ed8d3d7db5c39079a73bb97415efe8 |
refs/heads/master | <repo_name>wereHamster/git-bundler-service<file_sep>/bundle.sh
#!/bin/sh
set -e
ROOT="$1/data/bundles/$2"
GIT_DIR="$ROOT/repo"; export GIT_DIR
mkdir -p "$GIT_DIR"
git init --bare
git remote add origin -f --mirror "$3"
git bundle create "$ROOT/bundle" --all
rm -rf $GIT_DIR
<file_sep>/deploy.sh
#!/bin/sh
set -e
git fetch -q origin && git reset -q --hard $1
npm install --mongodb:native
./node_modules/.bin/coffee -c index.coffee app.coffee </dev/null
./node_modules/.bin/stylus -c public/style.styl </dev/null
| 1b34401b3452a458be763a8b2dfc995ef00671a3 | [
"Shell"
] | 2 | Shell | wereHamster/git-bundler-service | 10e71f14e2ca5c9070995bd36b150e95e25f88be | 063658b0c73fb00f9c477cff7c1615265d7e7055 |
refs/heads/master | <file_sep>package model;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
*Klasa ktora wysyla komendy do serwera. Jest skladowa:
*@see model.ConnectedClient#accessor
*@author <NAME>
*@version 1.0
*/
public class CommandSender {
/**
* Buforowany strumien potrzebny do odebrania pliku/listy plikow
*/
private BufferedInputStream input = null;//
/**
* Buforowany strumien potrzebny do zapisu danych otrzymanych z serwera do pliku
*/
private BufferedOutputStream output = null;//
/**
*Klasa bedaca zadaniem wykonywanym raz na okreslony czas.(Wysylanie sygnalu nOOp co 30 sekund w celu
*zapobiegniecia zamkniecia polaczenia przez serwer)
*@author <NAME>
*@version 1.0
*/
protected class SendNoopSignalTask extends TimerTask {
public void run() {
try {
noop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Socket przez ktory przesylamy komendy.
*/
Socket clientSocket = null;
/**
* Socekt przez ktory przesyłaemy dane.
*/
Socket passiveClientSocket = null;
/**
* Obiekt do wysyłania komend w postaci string.
*/
private PrintWriter toServerStream = null;
/**
* Obiekt ktorym odbieramy komendy w postaci string.
*/
private BufferedReader fromServerStream = null;
/**
* Sluzy do ustwaiania zadania wysylania sygnalu noop
* @see SendNoopSignalTask
*/
private Timer NoopTimer = null;
/**
* Metoda laczy z serwerem na zadanym hoscie i porcie
*@exception gdy podczas laczenia wystapi blad
*/
public void connect() throws Exception {
// /startConnectingToServer(host, port);
clientSocket = new Socket("127.0.0.1", 3021);// TODO
toServerStream = new PrintWriter(clientSocket.getOutputStream(), true);
fromServerStream = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String serverAnswer = fromServerStream.readLine();
// ///////tylko jedna linie dostajemy
System.out.println("S:" + serverAnswer);
resetTimeOfNoopTask();
if (serverAnswer == null || (!serverAnswer.startsWith("220"))) {
throw new Exception(
"Zla odpowiedz serwera przy probie polaczenia przed logowaniem");
}
}
/**
* Metoda wysyla login uzytkownika.
* @param login nazwa uzytkownika
* @throws Exception gdy serwer odpowie w nieoczekiwany sposob
*/
public void sendLogin(String login) throws Exception {
resetTimeOfNoopTask();
if (clientSocket == null || clientSocket.isClosed()) {
throw new Exception("Brak polaczenia");
}
toServerStream.println("USER " + login);
System.out.println("U:" + "USER " + login);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("331"))) {
throw new Exception(
"Zla odpowiedz serwera przy probie wyslania loginu");
}
}
/**
* Funkcja wysyla haslo do serwera w celu zalogowania
* @param password <PASSWORD> uzytkownika
* @throws Exception gdy serwer odpowie w niewlasciwy sposob.
*/
public void sendPassword(String password) throws Exception {
resetTimeOfNoopTask();
if (clientSocket == null || clientSocket.isClosed()) {
throw new Exception("Brak polaczenia");
}
toServerStream.println("PASS " + password);
System.out.println("U:" + "PASS " + "*********");
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("230"))) {
throw new Exception(
"Zla odpowiedz serwera przy probie wyslania hasla");
}
}
/**
* Funkcja wysyla komunikat Noop
* @throws Exception gdy serwer odpowie w nieoczekiwny sposob
* @see SendNoopSignalTask
*/
public void noop() throws Exception {
toServerStream.println("NOOP");
System.out.println("U:NOOP");
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("200"))) {
throw new Exception("Zla odpowiedz serwera przy poleceniu noop");
}
}
/**
* Funkcja reetuje czas odliczany do wysylania komuniaktu noop.
*/
private void resetTimeOfNoopTask() {
if (NoopTimer != null)
NoopTimer.cancel();
NoopTimer = new Timer();
NoopTimer.scheduleAtFixedRate(new SendNoopSignalTask(), 30000, 30000);
}
/**
* Funkcja usuwa Timer ktory odlicza czas.
*/
public void deleteTimer() {
if (NoopTimer != null) {
NoopTimer.cancel();
NoopTimer = null;
}
}
// z separatorem na koncu scezka
/**
* Funkcja odpowada za komende pwd
* @return sciezka do aktualnego katalogu na serwerze
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public String pwd() throws Exception {
resetTimeOfNoopTask();
if (clientSocket == null || clientSocket.isClosed()) {
throw new Exception("Brak polaczenia");
}
toServerStream.println("PWD");
System.out.println("U:" + "PWD");
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("257"))) {
throw new Exception("Zla odpowiedz serwera przy komendzie PWD");
}
String result = serverAnswer.substring(serverAnswer.indexOf("\"") + 1,
serverAnswer.lastIndexOf("\""));
return result;
}
// zakladamy ze katalog .. sie nie wyse wiec dodajemy w modelu talicy zawsze
/**
* Metoda odpowiada za komende list() - w trybie pasywnym odbiera liste plikow z katalogu na serwerze
* @return lista plikow z aktualnego katalogu na serwerze
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public ArrayList<FileWrapper> list() throws Exception {//TODO tu moga byc problemy
resetTimeOfNoopTask();
pasv();
// System.out.println("nie wykonue sie");}
toServerStream.println("LIST");
System.out.println("U:LIST");
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("150"))) {
passiveClientSocket.close();
throw new Exception("Zla odpowiedz serwera przy komendzie LIST");
}
BufferedReader readList = new BufferedReader(new InputStreamReader(
passiveClientSocket.getInputStream()));
String file = null;// Nazwa"drwrw"MM/dd/yyyy HH:mm:ss
ArrayList<FileWrapper> files = new ArrayList<FileWrapper>();
while ((file = readList.readLine()) != null) {// tu w petli z portu
// pasywnego
files.add(new FileWrapper(file));
}
serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("226"))) {
passiveClientSocket.close();
throw new Exception("Zla odpowiedz serwera po transferze listy");
}
readList.close();
//isPassive = false;
passiveClientSocket.close();
passiveClientSocket = null;
return files;
// return sendListLine();
}
/**
* Metoda wlacza tryb pasywny do odbioru/wysylania plikow.
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void pasv() throws Exception {
if (passiveClientSocket == null) {
resetTimeOfNoopTask();
toServerStream.println("PASV");
System.out.println("U:PASV");
passiveClientSocket = new Socket("127.0.0.1", 3020);// TODO
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("227"))) {
throw new Exception(
"Zla odpowiedz serwera przy probie wejscia w tryb pasywny");
}
}
}
/**
* Konczy polaczenie z serwerem.
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void disconnect() throws Exception {
try {
if (!clientSocket.isConnected()) {
throw new Exception(
"Brak polaczenia w metodzie closeConnection()");
}
toServerStream.println("QUIT");
System.out.println("U:QUIT");
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("221"))) {
throw new Exception("Zla odpowiedz serwera po quit");
}
} finally {
deleteTimer();
/*
* toServerStream.close(); fromServerStream.close();
* passiveClientSocket.close();
*
* socket.close();
*/
}
}
/**
* Tworzy katalog po stronie serwera.
* @param path
* @return true jesli utworzono katalog else false
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public boolean mkdir(String path) throws Exception {
if (!clientSocket.isConnected()) {
throw new Exception("Brak polaczenia w metodzie makeDirectory()");
}
resetTimeOfNoopTask();
toServerStream.println("MKD " + path);
System.out.println("U:MKD " + path);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer.startsWith("450"))
return false;// 450 gdy nie rzrobil folderu bo juz taki byl
if (serverAnswer == null || (!serverAnswer.startsWith("257"))) {
throw new Exception("Zla odpowiedz serwera przy tworzeniu katalogu");
}
return true;
}
/**
* Usuwa katalog po stronie serwera.
* @param dirname nazwa katalogu do suniecia
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void deleteDir(String dirname) throws Exception {
if (!clientSocket.isConnected()) {
throw new Exception("Brak polaczenia w metodzie removeDirecotery()");
}
resetTimeOfNoopTask();
toServerStream.println("RMD " + dirname);
System.out.println("U:RMD " + dirname);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("250"))) {
throw new Exception("Zla odpowiedz serwera przy usuwaniu katalogu");
}
}
/**
* Zmienia katalog roboczy po stronie serwera.
* @param dir nazwa katalogu do wejscia
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void cwd(String dir) throws Exception {
if (!clientSocket.isConnected()) {
throw new Exception("Brak polaczenia w metodzie cwd()");
}
resetTimeOfNoopTask();
toServerStream.println("CWD " + dir);
System.out.println("U:CWD " + dir);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("250"))) {
throw new Exception("Zla odpowiedz serwera przy zmianie katalogu");
}
}
/**
* Usuwa plik z serwera
* @param filename nazwa pliku do usuniecia
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void deleteFile(String filename) throws Exception {
if (!clientSocket.isConnected()) {
throw new Exception("Brak polaczenia w metodzie removeFile()");
}
resetTimeOfNoopTask();
toServerStream.println("DELE " + filename);
System.out.println("U:DELE " + filename);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("250"))) {
throw new Exception("Zla odpowiedz serwera przy usuwaniu pliku");
}
}
/**
* Wysyła cały folder z wszystkimi plikami rekursywnie. jesli to plik uzywa etody stor.
* @param directoryToSend
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
* @see #stor(File)
*/
public void uploadDir(File directoryToSend) throws Exception {
resetTimeOfNoopTask();
File[] list = directoryToSend.listFiles();
String directoryName = directoryToSend.getName();
mkdir(directoryName);// tworzymy ten katalog
cwd(directoryName); // przechodzimy do niego
for (File f : list) {
if (f.isFile())
stor(f);
if (f.isDirectory())
uploadDir(f);
}
cwd("..");// z powrotem w gore
}
/**
* Metoda komendy stor - wysyla plik na serwer.
* @param fi obiekt reprezentujacy plik do wsylania.
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void stor(File fi) throws Exception {
pasv();
String filename = fi.getName();
resetTimeOfNoopTask();
toServerStream.println("STOR " + filename);
System.out.println("U:STOR " + filename);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("150"))) {
passiveClientSocket.close();
throw new Exception("Zla odpowiedz serwera przy poleceniu stor"
+ filename);
}
input = new BufferedInputStream(new FileInputStream(fi));// zrodlo-plik
output = new BufferedOutputStream(passiveClientSocket.getOutputStream());// output-passive
// System.out.println("klient przed move file");
transfer();
//System.out.println("klient po file");
serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("226"))) {
passiveClientSocket.close();
throw new Exception(
"Zla odpowiedz serwera przy konczeniu polecenia stor"
+ filename);
}
}
/**
* Gdy chcemy pobrac cos z serwera - metoda dodaje koncowke do pliku, zapobiegajac 2 takim samym nazwa
* i tworzy odpowiedznie podfoldery itd.
* @param serverFile plik do sciagniecia
* @param serverPath sciezka na serwerze
* @param clientPath sciezka u kleinta gdzie plik zostanie zapisany
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void downloadFromServer(FileWrapper serverFile, String serverPath,
String clientPath) throws Exception {
// decydujemy jaka koncowke dac
String suffix = "(0)";
String finalName = "";
File newClient;
if (serverFile.isDir()) {
finalName = serverFile.getName() + suffix;
} else {// jesli jest plikiem
String extension = "";
int i = serverFile.getName().lastIndexOf('.');
if (i > 0) {// jesli ma rozszerzenie
extension = serverFile.getName().substring(i + 1);
finalName = serverFile.getName().substring(0,
serverFile.getName().lastIndexOf("."))
+ suffix + "." + extension;
} else {// gdy nie ma rpzszerzenia
finalName = serverFile.getName() + suffix;
}
}
newClient = new File(clientPath + File.separator + finalName);
// tworzymy ten katalog u siebie tam gdzie jest root
if (newClient.exists()) {
boolean ready = false;
Integer tryCounter = 1;
do {
suffix = "(" + tryCounter.toString() + ")";
if (serverFile.isDir()) {
finalName = serverFile.getName() + suffix;
} else {// jesli jest plikiem
String extension = "";
int i = serverFile.getName().lastIndexOf('.');
if (i > 0) {// jesli ma rozszerzenie
extension = serverFile.getName().substring(i + 1);
finalName = serverFile.getName().substring(0,
serverFile.getName().lastIndexOf("."))
+ suffix + "." + extension;
} else {// gdy nie ma rpzszerzenia
finalName = serverFile.getName() + suffix;
}
}
newClient = new File(clientPath + File.separator + finalName);
if (!newClient.exists())
ready = true;
tryCounter++;
} while (!ready);
}
if (!serverFile.isDir()) {// jesli to nie katalog to przesylamy jeden
// plik i koniec
System.out.println("if get not direcotry");
retr(newClient, serverFile.getName());
return;
}
if (!newClient.exists()) {
if (!newClient.mkdirs())
System.out.println("blad!!!!!!!!!!1");
// System.out.println("nazwa z wrapera"+ftpfile.getFilename());
// System.out.println("czy moge pisac"+newClient.canWrite());
// System.out.println("stworzylem w getsthfromsrv taki folder "
// + clientpath + File.separator + ftpfile.getFilename());
}// tworzy folder o nazwie tego elementu z listy
cwd(serverFile.getName());// wchodzimy tam do serwera
ArrayList<FileWrapper> list = list();
if (list.size() == 0) {// jesli jest pusty to wracamy i konczymy
cwd("..");
return;
}
for (FileWrapper f : list) {
downloadFromServer(f, serverPath + File.separator + f.getName(),
clientPath + File.separator + finalName);
}
cwd("..");
}
/**
* Funkcja poberajaca z serwera w trbie pasywnym pliki.
* @param fi obiekt file gdzie zostanie zapisany pobrany plik
* @param filename nazwa obieranego pliku
* @throws Exception gdy serwer odpowie w zly sposob lub nastapi blad polaczenia
*/
public void retr(File fi, String filename) throws Exception {
pasv();
toServerStream.println("RETR " + filename);
resetTimeOfNoopTask();
System.out.println("U:RETR " + filename);
String serverAnswer = fromServerStream.readLine();
System.out.println("S:" + serverAnswer);
if (serverAnswer == null || (!serverAnswer.startsWith("150"))) {
passiveClientSocket.close();
throw new Exception("Zla odpowiedz serwera przy poleceniu retr "
+ filename);
}
input = new BufferedInputStream(passiveClientSocket.getInputStream());
output = new BufferedOutputStream(new FileOutputStream(fi));
//System.out.println("przed move");
transfer();
//System.out.println("po movei zamknieciu ");
serverAnswer = fromServerStream.readLine();
if (serverAnswer == null || (!serverAnswer.startsWith("226"))) {
passiveClientSocket.close();
throw new Exception("Zla odpowiedz serwera po poleceniu retr "
+ filename + serverAnswer);
}
}
/**
* Przerzuca dane mierzy strumieniami
*
* @throws IOException gdy nastapi blad w dzialaniu strumieni.
*/
private void transfer() throws IOException {
byte[] buffer = new byte[10];
int bytesRead = 0;
while ((bytesRead = input.read(buffer)) != -1) {
System.out.println(buffer);
System.out.println(bytesRead);
output.write(buffer, 0, bytesRead);
output.flush();
resetTimeOfNoopTask();
}
output.close();
input.close();
passiveClientSocket.close();
passiveClientSocket = null;
}
}
<file_sep>package model;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
/**
* Klasa reprezentujaca połaczenie klienta.
*
* @author <NAME>
* @version 1.0
*/
public class ConnectedClient {
public String serverPath = null;
public CommandSender accessor = null;
/**
* kontruktor bezargumentowy.
*/
public ConnectedClient() {
}
/**
* Nawiazuje polaczenie z wybranymi parametrami
*
* @param login
* nazwa uzytkownika
* @param pass
* haslo
* @param hostname
* nazwa hosta
* @param port
* @throws UnknownHostException
* @throws IOException
*/
public void connect(String login, String pass, String hostname, int port)
throws UnknownHostException, IOException {
}
/**
* Deleguje wysylanie odpowiednich komend do metod
*
* @param comm
* @param clientPath
* @throws Exception
*/
public void sendMessageToServer(String comm, String clientPath)
throws Exception {//
String com = comm;
if (comm.contains(" "))
com = cutCommand(comm);
String valueAfterCommand = null;
if (comm.length() > 4)
valueAfterCommand = comm.substring(comm.indexOf(" ") + 1);
switch (com) {
case "USER":
accessor.sendLogin(valueAfterCommand);
break;
case "PASS":
accessor.sendPassword(valueAfterCommand);
break;
case "QUIT":
accessor.disconnect();
break;
case "NOOP":
accessor.noop();
break;
case "PASV":
accessor.pasv();
break;
case "STOR":
File storFile = new File(clientPath + File.separator
+ valueAfterCommand);
accessor.stor(storFile);
break;
case "RETR":
File retrFile = new File(clientPath + File.separator
+ valueAfterCommand);
accessor.retr(retrFile, valueAfterCommand);
break;
case "DELE":
accessor.deleteFile(valueAfterCommand);
break;
case "RMD":
accessor.deleteDir(valueAfterCommand);
break;
case "MKD":
accessor.mkdir(valueAfterCommand);
break;
case "PWD":
accessor.pwd();
break;
case "LIST":
accessor.list();
// accessor.sendListLine();
// TODO
break;
case "CWD":
accessor.cwd(valueAfterCommand);
break;
case "mkdir":
accessor.mkdir(valueAfterCommand);
break;
case "pwd":
accessor.pwd();
break;
case "rmdir":
accessor.deleteDir(valueAfterCommand);
break;
case "cd":
accessor.cwd(valueAfterCommand);
accessor.list();
break;
default:
System.out.println("Unsupported command.");
}
}
/**
* Zamyka połaczenie z klientem
*
* @throws Exception
*/
public void closeConnection() throws Exception {
accessor.disconnect();
}
/**
* Przycina odebrana komende zeby uzyskac argument
*
* @param comm
* komenda do przyciecia
* @return argument komendy
*/
private String cutCommand(String comm) {
return comm.substring(0, comm.indexOf(" "));
}
}
<file_sep>package controller;
//!!!!!!!!
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.UnknownHostException;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import model.CommandSender;
import model.FileWrapper;
import view.MainClientWindow;
import model.ConnectedClient;
/**
* Klasa odpowiadajaca za przekierowanie strumienia na wyjscie konsoli.
*
* @author <NAME>
* @version 1.0
*/
class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char) b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
/**
* Klasa bedaca kontrolelrem aplikacji. Znajduja sie w niej wszystkie listenery
* jako klasy wewnetrzne.
*
* @author <NAME>
* @version 1.0
*/
public class ClientControllerClass {
/**
* Klasa odpowiadajaca za to ze gdy uzytkownik 2x kliknie na folder w tabeli
* klienta przejdzie do niego.
*
* @author <NAME>
* @version 1.0
*/
class ClientTableListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable target = (JTable) e.getSource();
int row = target.getSelectedRow();
String dirName = (String) mcw.clientContentTable.getValueAt(
row, 1);
boolean isDir = false;
for (File f : mcw.clientFiles) {// dla wszystkich plikow klienta
if (f.getName().equals(dirName)) {// jesli ktorys z nich ma
// taka
// sama nazwe i jest
// katalogiem
if (f.isDirectory())
isDir = true;
}
}
if (dirName.equals("..")) {// jak idziemy w gore
// System.out.println("tu1 " + mcw.clientPath);
mcw.clientPath = mcw.clientPath.substring(0,
mcw.clientPath.lastIndexOf(File.separator));
// System.out.println("tu2 " + mcw.clientPath);
mcw.currentClientDirectory = new File(mcw.clientPath);
mcw.clientFiles = mcw.currentClientDirectory.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
mcw.clientPathTF.setText(mcw.clientPath);
} else if (isDir) {
mcw.currentClientDirectory = new File(mcw.clientPath
+ File.separator + dirName);
mcw.clientPath = mcw.clientPath + File.separator + dirName;
mcw.clientFiles = mcw.currentClientDirectory.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
mcw.clientPathTF.setText(mcw.clientPath);
}
}
}
}
/**
* Klasa odpowiadajaca za to ze gdy uzytkownik 2x kliknie na folder w tabeli
* serwera przejdzie do niego.
*
* @author <NAME>
* @version 1.0
*/
class ServerTableListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
try {
JTable target = (JTable) e.getSource();
int row = target.getSelectedRow();
String dirName = (String) mcw.serverContentTable
.getValueAt(row, 1);
boolean isDir = false;
for (FileWrapper f : mcw.serverFiles) {// dla wszystkich
// plikow
// klienta
if (f.getName().equals(dirName)) {// jesli ktorys z
// nich ma taka
// sama nazwe i
// jest
// katalogiem
if (f.isDir())
isDir = true;
}
}
if (dirName.equals("..")) {// jak idziemy w gore
System.out.println("tu1 " + mcw.serverPath);
rc.accessor.cwd("..");
mcw.serverPath = rc.accessor.pwd();
mcw.serverPathTF.setText(mcw.serverPath);
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
} else if (isDir) {
rc.accessor.cwd(dirName);
mcw.serverPath = rc.accessor.pwd();
mcw.serverPathTF.setText(mcw.serverPath);
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(mcw,
"PROBLEM przy listenerze tabeli serwera!",
"PROBLEM przy listenerze tabeli serwera!",
JOptionPane.INFORMATION_MESSAGE);
e1.printStackTrace();
return;
}
}
}
}
/**
* Klasa odpowiadajaca za to ze gdy uzytkownik kliknie na przyscik połacz
* zostanie nawiazana proba połaczenia z serwerem.
*
* @author <NAME>
* @version 1.0
*/
class ConnectButtonListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
try {
rc.accessor = new CommandSender();
String user = mcw.loginTF.getText();
String pass = new String(mcw.passwordPF.getPassword());
rc.accessor.connect();
rc.accessor.sendLogin(user);
rc.accessor.sendPassword(pass);
mcw.serverPath = rc.accessor.pwd() + File.separator;
rc.accessor.pwd();
mcw.serverPathTF.setText(mcw.serverPath);
// rc.accessor.pasv();
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
mcw.statusLabel.setText("POLACZONY");
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(mcw, "NumberFormatException!",
"NumberFormatException!",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
return;
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(mcw, "UnknownHostException!",
"UnknownHostException!",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
return;
} catch (IOException e) {
JOptionPane.showMessageDialog(mcw, "IOException!",
"IOException!", JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw, "Exception !",
"Exception !", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* Klasa odpowiadajaca za to ze gdy uzytkownik kliknie na przyscik ROZLACZ
* zostanie zakonczone połączenie.
*
* @author <NAME>
* @version 1.0
*/
class DisconectButtonListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
System.out.println("disco button");
try {
mcw.statusLabel.setText("BRAK POLACZENIA");
rc.accessor.disconnect();
/*
* mcw.ftpFiles = null; mcw.displayFilesInServerTable();
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* Skladowa ktora reprezentuje glowne okno aplikacji
*/
MainClientWindow mcw = null;
/**
* Skladowa ktora jest obiektem -najdanikiem wysylajacym komendy do serwera
* i odbierajacym odpoiwedzi.
*/
ConnectedClient rc = null;
// //////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////
/**
* Konstruktor bezargumentowy przekierowuje standardowe wejscie,oraz tworzy
* obiekty listenerow i je przypisuje do elementow gui.
*/
public ClientControllerClass() {
mcw = new MainClientWindow();
rc = new ConnectedClient();
// TODO to zostaw!!!!!!!!!!!!!1
PrintStream printStream = new PrintStream(new CustomOutputStream(
mcw.consoleTA));
System.setOut(printStream);
System.setErr(printStream);
ConnectButtonListener cdbl = new ConnectButtonListener();
mcw.connectButton.addActionListener(cdbl);
DisconectButtonListener dbl = new DisconectButtonListener();
mcw.disconectButton.addActionListener(dbl);
ClientTableListener ctl = new ClientTableListener();// gdy klikasz 2
// razy
mcw.clientContentTable.addMouseListener(ctl);
ServerTableListener stl = new ServerTableListener();
mcw.serverContentTable.addMouseListener(stl);
CreateDirectoryFTPPML cdftppml = new CreateDirectoryFTPPML();
mcw.serverPM.mkDirMI.addActionListener(cdftppml);
CreateDirectoryPML cdpml = new CreateDirectoryPML();
mcw.clientPM.mkdirMI.addActionListener(cdpml);
ClientPML lpml = new ClientPML();
mcw.clientPM.addPopupMenuListener(lpml);
DeleteClientFile dlf = new DeleteClientFile();
mcw.clientPM.deleteMI.addActionListener(dlf);
DeleteFTPL dftpl = new DeleteFTPL();
mcw.serverPM.deleteMI.addActionListener(dftpl);
GetFileFTPL gfftppl = new GetFileFTPL();
mcw.serverPM.downloadMI.addActionListener(gfftppl);
SendFileLPL sflpl = new SendFileLPL();
mcw.clientPM.sendMI.addActionListener(sflpl);
}
/**
* Funkcja main programu inicjalizuje aplikacje tworzac pojedynczy obiekt
* kontrolera ktory sprawuje władze nad cała oplikacja.
*
* @param tablica
* argumentow String wrzuconych do programu.
*/
public static void main(String[] args) {
@SuppressWarnings("unused")
ClientControllerClass ccc = new ClientControllerClass();
}
/**
* Listener popupmenu opcji "wyslij" odpowiada za wysłanie pliku/całego
* katalogu na ktory kliknał uztykownik na serwer.Moze rekurencyjnie
* wywolywac metode sendToServer(File).
*
* @author <NAME>
* @version 1.0
* @see #sendToServer(File)
*/
class SendFileLPL implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
int row = mcw.getClientTable().getSelectedRow();
String filename = (String) mcw.getClientTable().getValueAt(row, 1);
File fileToSend = new File(mcw.clientPath + File.separator
+ filename);
try {
sendToServer(fileToSend);
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
mcw.clientFiles = mcw.currentClientDirectory.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw, "Exception !",
"Exception !", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* Metoda ułatwa rekurencyjne wywoływanie wysyłania na serwer.
*
* @param obiekt
* file reprezentujacy plik ktory chcemy wysłac
* @exception Gdy
* cos pojdzie nie tak - bedzie zła odpowiedz serwera lub
* problem z polaczeniem
*/
public void sendToServer(File fileToSend) throws Exception {
if (fileToSend.isDirectory()) {// jak jest katalogiem
String s = fileToSend.getName();
boolean done = rc.accessor.mkdir(fileToSend.getName());
while (!done) {
s = (String) JOptionPane.showInputDialog(mcw, "Jeszcze raz", s
+ ":Taki folder juz istnieje",
JOptionPane.PLAIN_MESSAGE);
done = rc.accessor.mkdir(s);
}
if (fileToSend.listFiles().length > 0) {
rc.accessor.cwd(s);
for (File fi : fileToSend.listFiles()) {
sendToServer(fi);
}
rc.accessor.cwd("..");
}
} else {
rc.accessor.stor(fileToSend);
}
}
// //////////////////////////////////////////
// //////////////////////////////////////////
/**
* Klasa bedaca listener opcji pobierz z popupmenu dla tabeli plikow
* serwera.
*
* @author <NAME>
* @version 1.0
* @see #getFile()
*/
class GetFileFTPL implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
try {
getFile();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw,
"Blad pobieraniu pliku z FTP !", "IOException !",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* Metoda umozliwiajaca rekurencyjne pobieranie plikow z serwera. jesli
* uzytkownik kliknal na folder, folder o tej samej naziwe jest stworzony i
* pliki zostaja pobrane. Ponadto dla kazdego ubiektu w folderze jest
* sprawdzone czy nie jest katalogiem - jesli jest, metoda zostanie
* rekurencyjnie wywolana dla tego folderu.
*
* Na koncu uaktualniona jest lista plikow tezby uwzglenic te pobrane
*
* @exception gdy
* nastapi zla odpowiedz serwera
*/
private void getFile() throws Exception {
int row = mcw.getServerTable().getSelectedRow();
// String filename = (String) mcw.getFTPTable().getValueAt(row, 1);
String filename = (String) mcw.serverTableModel.getValueAt(row, 1);
// System.out.println("filename" + filename + "ddddd");
boolean isDirectory = false;
for (FileWrapper f : mcw.getListOfServerFiles()) {
if (f.getName().equals(filename)) {
if (f.isDir())
isDirectory = true;
}
}
FileWrapper fw = new FileWrapper();
fw.name = filename;
fw.isDir = isDirectory;
rc.accessor.downloadFromServer(fw, mcw.serverPath, mcw.clientPath);
File roo = new File(mcw.clientPath);
mcw.clientFiles = roo.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
}
/**
* Listener ktory odpowiada za opcje usun w menu tabeli serwera. Wywyoluje
* funkcje deleteFromServer(String)
*
* @author Michal Wilk
* @version 1.0
* @see #deleteFromServer(String)
*/
class DeleteFTPL implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
int row = mcw.clientContentTable.getSelectedRow();
String filename = (String) mcw.serverTableModel.getValueAt(row, 1);
try {
deleteFromServer(filename);
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw,
"Blad przy usuwaniu na FTP !", "IOException !",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* Funkcja ktora usuwa pliki badz foldery wywyalujac 2 funkcje odpowiednio
* jesli obiekt jest plikiem lub folderem.
*
* @exception gdy
* bedzie zla odpowiedz serwera lub wystapi blad polaczenia.
* @see model.CommandSender#deleteDir(String dirname)
* @see model.CommandSender#deleteFile(String filename)
*/
private void deleteFromServer(String name) throws Exception {
int row = mcw.getServerTable().getSelectedRow();
String filename = (String) mcw.getServerTable().getValueAt(row, 1);
boolean isDirectory = false;
for (FileWrapper f : mcw.getListOfServerFiles()) {
if (f.getName().equals(filename))
if (f.isDir())
isDirectory = true;
}
if (isDirectory)
rc.accessor.deleteDir(filename);
else
rc.accessor.deleteFile(filename);
}
/**
* Klasa odpowiadajaca za widocznosc menu popup tabeli z plikami klienta
*
* @author <NAME>
* @version 1.0
* @see view.ClientPM#onTableClicked()
*/
class ClientPML implements PopupMenuListener {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if (mcw.clientPM.onTableClicked()) {
Point point = mcw.clientContentTable.getMousePosition();
int currentRow = mcw.clientContentTable.rowAtPoint(point);
mcw.clientContentTable.setRowSelectionInterval(currentRow,
currentRow);
}
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
}
/**
* Klasa odpowiadajaca za widocznosc menu popup tabeli z plikami serwera
*
* @author <NAME>
* @version 1.0
* @see view.ServerPM#onTableClicked()
*/
class ServerPopupListener implements PopupMenuListener {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if (mcw.serverPM.onTableClicked()) {
Point point = mcw.serverContentTable.getMousePosition();
int currentRow = mcw.serverContentTable.rowAtPoint(point);
mcw.serverContentTable.setRowSelectionInterval(currentRow,
currentRow);
}
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
}
/**
* LIstener odpowiadajacy za opcje stworz folder gdy uzytkownik kliknie na
* tabele serwera
*
* @author <NAME>
* @version 1.0
* @see model.CommandSender#mkdir(String path)
*/
class CreateDirectoryFTPPML implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
String s = (String) JOptionPane.showInputDialog(mcw,
"Podaj nazwe folderu:", "Podaj nazwe folderu",
JOptionPane.PLAIN_MESSAGE);
// If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
boolean done = false;
try {
done = rc.accessor.mkdir(s);
while (!done) {
s = (String) JOptionPane.showInputDialog(mcw,
"Jeszcze raz", s + ":Taki folder juz istnieje",
JOptionPane.PLAIN_MESSAGE);
done = rc.accessor.mkdir(s);
}
mcw.serverFiles = rc.accessor.list();
mcw.displayFilesInServerTable();
} catch (SQLException e) {
JOptionPane.showMessageDialog(mcw,
"PROBLEM Z BAZA DANYCH!",
"PROBLEM Z BAZA DANYCH!!",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw,
"Blad przy tworzeniu katalogu na FTP !",
"IOException !", JOptionPane.INFORMATION_MESSAGE);
}
return;
}
}
}
/**
* LIstener odpowiadajacy za opcje stworz folder gdy uzytkownik kliknie na
* tabele klienta Twozry folder w zadanym miejscu
*
* @author <NAME>
* @version 1.0
* @see view.MainClientWindow#clientPath
*/
class CreateDirectoryPML implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
String s = (String) JOptionPane.showInputDialog(mcw,
"Podaj nazwe folderu:", "Podaj nazwe folderu",
JOptionPane.PLAIN_MESSAGE);
if ((s != null) && (s.length() > 0)) {
try {
File f = new File(mcw.clientPath + File.separator + s);
f.mkdir();
File roo = new File(mcw.clientPath);
mcw.clientFiles = roo.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(mcw,
"Blad przy tworzeniu katalogu lokalnie !",
"IOException !", JOptionPane.INFORMATION_MESSAGE);
}
return;
}
}
}
/**
* Klasa bedaca listenerem opcji usun gdy uzytkownik kliknie na tabele z
* plikami klienta Usuwa zadany plik za poloca funkcji.
*
* @see #deleteClientFilefunction(String name, String path)
* @author <NAME>
* @version 1.0
*/
class DeleteClientFile implements ActionListener {// usuwa lokalny folder
// wraz z podfolderami
// rekurencyjnie nizej
// funkcja
// dobre robione 12 stycznia
@Override
public void actionPerformed(ActionEvent e) {
int row = mcw.clientContentTable.getSelectedRow();
String filename = (String) mcw.clientTableModel.getValueAt(row, 1);
deleteClientFilefunction(filename, mcw.clientPath + File.separator
+ filename);
mcw.clientFiles = mcw.currentClientDirectory.listFiles();
mcw.displayFilesInClientTable(mcw.clientFiles);
}
}
/**
* Meotoda usuwa plik po stronie klienta, jesli zawiera folder to zawartosc jest usuwana rekurencyjnie.
*@param name nazwa pliku do usuniecia
*@param path sciezka tego pliku
*/
public void deleteClientFilefunction(String name, String path) {
File f = new File(path);
File[] files = f.listFiles();
if (f.isDirectory() && files.length > 0) {
for (int i = 0; i < files.length; i++)
deleteClientFilefunction(files[i].getName(),
files[i].getAbsolutePath());
}
f.delete();
/*
* if (f.delete()) System.out.println("usunalem" + f.getAbsolutePath());
* else System.out.println("nie usunalem" + f.getAbsolutePath());
*/
}
}
<file_sep>package model;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.AbstractTableModel;
/**
*Model tablicy plikow servera
*@author <NAME>
*@version 1.0
*/
@SuppressWarnings("serial")
public class ServerTableModel extends AbstractTableModel {
/**
* Skladowa reprezentujaca folder aktualny po stronie serwera.
*/
private FileWrapper upDirectory = new FileWrapper();
/**
* Lista zawiera pliki z aktualnego katalogu po stronie serwera.
*/
private ArrayList<FileWrapper> filesInServerDirectory = new ArrayList<FileWrapper>();
/**
* Ta skladowa umozliwia poprawne ikony w tabeli reprezentujace pliki/foldery.
*/
private FileSystemView fileSystemView = FileSystemView.getFileSystemView();
/**
* Nazwy kolumn tabeli.
*/
private String[] columns = { "Typ", "Nazwa", "Data"};
/**
* Kontruktor domyslny.
*/
public ServerTableModel() {
}
/**
* Kontruktor ktory ustawia liste plikow po stronie serwera.
* @param files
*/
ServerTableModel(ArrayList<FileWrapper> files) {
this.filesInServerDirectory = files;
}
/**
* Przeslonieta metoda zwracajaca obiekt znajdujacy sie w tabeli w okreslonym miejscu.
* @param row wiersz
* @param column kolumna
*
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int column) {
FileWrapper file;
if (row < 1)
file = upDirectory;// dla zera zwraca ..
else
file = filesInServerDirectory.get(row - 1);// wybor wiersza , dla
// jedynki zwraca
// files[0]
switch (column) {
case 0:
File f = new File(file.getName());
if (file.isDir()) f.mkdir();
else
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Icon i = fileSystemView.getSystemIcon(f);
f.delete();
return i;
case 1:
if(file == null )return "..";
return file.getName();
case 2:
if(file == null )return null;
return file.getLastModificationDate();
}
return null;
}
/**
* zwraca ilosc kolumn
*/
public int getColumnCount() {
return columns.length;
}
/**
* Zwraca obiekt class odpowiedni dla danej kolumny.
*/
public Class<?> getColumnClass(int col) {
switch (col) {
case 0:
return ImageIcon.class;
case 1:
return String.class;
case 2:
return String.class;
}
return null;
}
public String getColumnName(int column) {
return columns[column];
}
public int getRowCount() {
// return files.length;
return filesInServerDirectory.size()+1;
}
/**
* Zwraca obiekt reprezentujacy okreslony plik po stronie serwera
* @param row wiersz
* @return obiekt reprezentujacy okreslony plik po stronie serwera
*/
public FileWrapper getServerFile(int row) {
// return files[row];
if (row >= 1)
return filesInServerDirectory.get(row - 1);
return upDirectory;
}
/**
* Ustawia liste plikow serwera.
* Odswieza tabele.
* @param files2 lista plikow.
*/
public void setServerFiles(ArrayList<FileWrapper> files2) {
this.filesInServerDirectory = files2;
fireTableDataChanged();
}
}<file_sep>package model;
/**
*Klasa opakowujaca plik przechowywany na serwerze, widoczny w tabeli plików serwera.
*Dostarcza niezbednych informacji o nim i imituje klase File.
*@author <NAME>
*@version 1.0
*/
public class FileWrapper {
/**
*Czy jest to folder.
*/
public boolean isDir = false;
/**
*Prawa pliku/folderu
*/
private String CHMODstring;
/**
*Nazwa pliku/folderu
*/
public String name;
/**
* Data ostatniej modyfikacji pliku/folderu
*/
private String lastModificationDate;
public FileWrapper() {
name = "..";
lastModificationDate = null;
isDir = true;
}
/**
*
* @param fileInfo wiadomosci o pliku wyslane z serwera postaci // Nazwa"drwrw"MM/dd/yyyy HH:mm:ss
*/
public FileWrapper(String fileInfo) {
String[] result = fileInfo.split("\"");
for (int x = 0; x < result.length; x++)
System.out.println(result[x]);
name = result[0];
if (result[1].charAt(0) == 'd') {
isDir = true;
System.out.println("folder");
} else {
isDir = false;
System.out.println("plik");
}
CHMODstring = result[1].substring(1);
lastModificationDate = result[2];
}
/**
*
* @return true jesli to katalog else false
*/
public boolean isDir() {
return isDir;
}
/**
* @return zwrraca nazwe pliku/folderu
*/
public String getName() {
return name;
}
/**
* @return data ostaniej modyfikacj w postaci string
*/
public String getLastModificationDate() {
return lastModificationDate;
}
/**
* @return prawa pliku zapisane w postaci string
*/
public String getCHMODstring() {
return CHMODstring;
}
}<file_sep>/**
*
*/
package view;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/**
* Klasa bedaca popupmenu dla tabeli plikow serwera.
*
* @author <NAME>
* @version 1.0
*/
@SuppressWarnings("serial")
public class ServerPM extends JPopupMenu {
/**
* Skladowe reprezentujace opcje menu "pobierz" "usun" "nowy katalog"
*/
public JMenuItem downloadMI, mkDirMI, deleteMI;
/**
* Referencja do glownego okna
*/
private MainClientWindow view = null;
public ServerPM(MainClientWindow view) {
this.view = view;
downloadMI = new JMenuItem("Pobierz");
add(downloadMI);
mkDirMI = new JMenuItem("Utwórz folder");
add(mkDirMI);
deleteMI = new JMenuItem("Usun");
add(deleteMI);
}
/**
* Jesli klikniey na jscrollpane ma nie byc delete i download ale ma byc
* stworz nowy folder
*/
public void setVisible(boolean b) {
super.setVisible(b);
if (this.getInvoker() instanceof JScrollPane) {
setMI(false);
} else if (view.getServerTable()
.getValueAt(view.getServerTable().getSelectedRow(), 1)
.equals("..")) {
setMI(false);
} else {
setMI(true);
}
}
/**
* Jesli klikniey na jscrollpane ma nie byc delete i download ale ma byc
* stworz nowy folder
*
* @param isClickable
*/
private void setMI(boolean isClickable) {
deleteMI.setEnabled(isClickable);
downloadMI.setEnabled(isClickable);
}
/**
* Sprawdzamy czy klient kliknal na tabele a nie na jscrollpane Jesli na
* tabele funkcja zwroci true i actionlistener tabeli ustawi popupmenu na
* visible
*
* @return
*/
public boolean onTableClicked() {
if (this.getInvoker() instanceof JTable)
return true;
else
return false;
}
}<file_sep>/**
*
*/
package view;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/**
* Klasa popupmenu do tabeli plikow klienta
*
* @author <NAME>
* @version 1.0
*/
@SuppressWarnings("serial")
public class ClientPM extends JPopupMenu {
/**
* Opcje menu - usun,nowy folder,pobierz
*/
public JMenuItem sendMI, mkdirMI, deleteMI;
/**
* Referencja do glownego okna aplikacji.
*/
private MainClientWindow view = null;
/**
* Konstruktor parametrowy.
*
* @param view
* Referencja do glownego okna aplikacji.
*/
public ClientPM(MainClientWindow view) {
this.view = view;
sendMI = new JMenuItem("Wyslij");
add(sendMI);
mkdirMI = new JMenuItem("Stworz katalog");
add(mkdirMI);
deleteMI = new JMenuItem("Usun");
add(deleteMI);
}
/**
* Przeslonieta funkcja ktora ustawia odpowiednie elementy menu na widoczne
* badz nie. Jesli kliknelismy na menu ale nie na konkretny plik opcje
* "Pobierz " i "Usun" beda niewidoczne.
*/
public void setVisible(boolean b) {
super.setVisible(b);
if (this.getInvoker() instanceof JScrollPane) {
setMI(false);
} else if (view.getServerTable().getSelectedRow() == 0) {
setMI(false);
} else {
setMI(true);
}
}
/**
* Odpowiednio wlacza lyb wylacza opcje menu
*
* @param isClickable
*/
private void setMI(boolean isClickable) {
deleteMI.setEnabled(isClickable);
sendMI.setEnabled(isClickable);
}
/**
* Umozliwia sprawdzenie czy menu powinno byc widoczne po kliknieciu na
* obszar tabeli.
*
* @return true jesli kliknelismy na tabele else false.
*/
public boolean onTableClicked() {
if (this.getInvoker() instanceof JTable)
return true;
else
return false;
}
}<file_sep>package model;
import java.io.File;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.AbstractTableModel;
/**
* Klasa reprezentuje model tabeli plikow klienta.
*
* @see view.MainClientWindow#clientTablePanel
* @author <NAME>
* @version 1.0
*/
@SuppressWarnings("serial")
public class ClientTableModel extends AbstractTableModel {
/**
* Pole reprezentujace wyswietlany w tabeli katalog.
*/
private File upDirectory = null;
/**
* Tablica plikow ktore zawierja sie w aktualnie wyswietlanym katalogu
*/
private File[] filesInClientDirectory;
/**
* Składowa potrzebna do otzrymania ikon plików w tabeli.
*/
private FileSystemView fileSystemView = FileSystemView.getFileSystemView();
/**
* Nazwy kolumn
*/
private String[] columnNames = { "Typ", "Nazwa", "Data" };
/**
* Kontruktor domyslny
*/
public ClientTableModel() {
this(new File[0]);
}
/**
* Konstruktor ktory inicjalizuje tablice plikow.
*
* @param files
* tablica plikow aktualnego folderu do wyswietlania w tabeli
*/
ClientTableModel(File[] files) {
this.filesInClientDirectory = files;
}
/**
* Przeciazona funkcja wymagana w definiowaniu własnego modelu tablicy.
* @param row rzad tabeli
* @param column kolumna tabeli
* @return obiekt z tabeli o okreslonych wspolrzednych
*/
public Object getValueAt(int row, int column) {
File file;
if (row < 1)
file = upDirectory;// dla zera zwraca ..
else
file = filesInClientDirectory[row - 1];// wybor wiersza , dla
// jedynki zwraca files[0]
switch (column) {
case 0:
return fileSystemView.getSystemIcon(file);
case 1:
if (row == 0)
return "..";
else
return fileSystemView.getSystemDisplayName(file);
case 2:
if (row == 0)
return null;
else
return file.lastModified();
}
return null;
}
/**
* Przesłonieta metoda która zwraca liczbe kolumn
* @return liczba kolumn w tabeli
*/
public int getColumnCount() {
return columnNames.length;
}
/**
* Przeslonieta metoda zwracajaca obiekt class danej kolumny
* @param col numer kolumny
* @return obiekt class
*/
public Class<?> getColumnClass(int col) {
switch (col) {
case 0:
return ImageIcon.class;
case 1:
return String.class;
case 2:
return Date.class;
}
return null;
}
/**
* Przeslonieta metoda zwraca nazwe kolumny o danym numerze
* @param col numer kolumn
* @return nazwa kolumny
*/
public String getColumnName(int col) {
return columnNames[col];
}
/**
* Zwraca ilosc wierszy w tabeli
*/
public int getRowCount() {
return filesInClientDirectory.length + 1;// no bo jeszcze ..
}
/**
* method gets file at passed row
*
* @param row
* number of row for which we want to get file
* @return
*/
public File getClientFile(int row) {
if (row > 1)
return filesInClientDirectory[row - 1];
return upDirectory;
}
/**
* Ustawia tabele plikow aktualnej sciezki do wyswietlenia
* @param files tabela plikow ktora pzypisujemy do zmiennej
*/
public void setClientFiles(File[] files) {
this.filesInClientDirectory = files;
fireTableDataChanged();
// Notifies all listeners that all cell values in the table's rows
// may have changed. The number of rows may also have changed and the
// JTable should redraw the table from scratch. The structure of the
// table
// (as in the order of the columns) is assumed to be the same.
}
} | d3f726fdede770caec4a81d3805eb6b075cb7e3a | [
"Java"
] | 8 | Java | michwilk/Client | 405ba45fb322ddea983014906299192ee10ad9f7 | 70a224bfd5111f5e40774cd19dab5c79d857633d |
refs/heads/master | <repo_name>crossz/scrapy_coverspick<file_sep>/covers/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class CoversItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date_string = scrapy.Field()
game_string = scrapy.Field()
leader = scrapy.Field()
pick_product = scrapy.Field()
pick_team = scrapy.Field()
pick_line = scrapy.Field()
pick_desc = scrapy.Field()
class ScoreItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date_string = scrapy.Field()
game_string = scrapy.Field()
team_away = scrapy.Field()
team_home = scrapy.Field()
score_away = scrapy.Field()
score_home = scrapy.Field()
ats = scrapy.Field()
hilo = scrapy.Field()
class ExpertpickItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date_string = scrapy.Field()
game_string = scrapy.Field()
product1_left = scrapy.Field() # i.e. ats_away
product1_right = scrapy.Field() # i.e. ats_home
product2_left = scrapy.Field() # i.e. hilo_high
product2_right = scrapy.Field() # i.e. hilo_low<file_sep>/README.md
# Covers: Expert picks crawler
## 3 types of items
- ScoreItem: for matchup, scores and closing lines
- ExperpickItem: counts for experts' picks
- CoverspickItem: descriptions for individual expert status and pick
## multiple collections joint
1. simple joint with ScoreItem and ExpertpickItem
This is the basic analysis based on summaried counts for expert pick and scores, i.e. not going for the details about individual expert ranking and performance.
``` javascript
db.ScoreItem.aggregate([
{
$lookup:{
from: "ExpertpickItem",
localField: "game_string",
foreignField: "game_string",
as: "joint_with_expertpickitem"
}
}
])
```
<file_sep>/covers/spiders/coverspick.py
# -*- coding: utf-8 -*-
import scrapy
import re
import time
import datetime
from covers.items import CoversItem
from covers.items import ScoreItem
from covers.items import ExpertpickItem
class CoverspickSpider(scrapy.Spider):
name = 'coverspick'
allowed_domains = ['covers.com']
## mode for one-day-guide/review.
start_urls = ['https://www.covers.com/Sports/NBA/Matchups']
## mode for batch download w/ start_date/end_date.
# start_urls = ['https://www.covers.com/Sports/NBA/Matchups?selectedDate=2019-10-22']
# end_date = '2019-12-31'
# %% season 2017-18; No expert pick data already on season 2019-20.
# start_urls = ['https://www.covers.com/Sports/NBA/Matchups?selectedDate=2017-10-17']
# end_date = '2017-12-31'
# start_urls = ['https://www.covers.com/Sports/NBA/Matchups?selectedDate=2018-01-01']
# end_date = '2018-06-09'
# %% season 2018-19; No expert pick data already from Jan 2020.
# start_urls = ['https://www.covers.com/Sports/NBA/Matchups?selectedDate=2018-10-16']
# end_date = '2018-12-31'
# start_urls = ['https://www.covers.com/Sports/NBA/Matchups?selectedDate=2019-01-01']
# end_date = '2019-06-13'
if 'end_date' not in locals():
# end_date = str(datetime.date.today() + datetime.timedelta(+1))
end_date = str(datetime.date.today())
def parse(self, response):
# %% predict analysis purpose: tomorrow game list
next_page = response.xpath('//*[@class="cmg_matchup_three_day_navigation"]/a[3]/@href').extract_first()
## '/Sports/NBA/Matchups?selectedDate=2018-03-09'
page_tomorrow = response.urljoin(next_page)
# %% today: alive games (game finished or not determined by the time)
current_page = response.xpath('//*[@class="cmg_matchup_three_day_navigation"]/a[2]/@href').extract_first()
page_today = response.urljoin(current_page)
## ---------------- mode for daily one-page-guide/review or batch download w/ start_date/end_date ----------------
## the date to be passed
if response.url.find('=') == -1:
matchup_date_string = str(datetime.date.today() + datetime.timedelta(-1))
else:
matchup_date_string = response.url[response.url.find('=')+1:] ## the date to be passed
## */ ---------------- mode END ----------------
# condition to stop crawling
if time.strptime(matchup_date_string, "%Y-%m-%d") <= time.strptime(self.end_date, "%Y-%m-%d"):
# # pick page to crawl
# for href in response.xpath('//*[@id="content"]//div//a[.="Consensus"]/@href'):
# yield response.follow(href, self.parse_consensus_page, meta={'date_string':matchup_date_string})
# score, teams, date to crawl
for matchup in response.css('div.cmg_matchup_game'):
item = ScoreItem()
div_teams = matchup.xpath('.//div[@class="cmg_team_name"]/text()').extract()
team_away = div_teams[0].strip()
team_home = div_teams[3].strip()
score_away = matchup.xpath('.//div[@class="cmg_matchup_list_score"]').css('div.cmg_matchup_list_score_away::text').extract_first()
score_home = matchup.xpath('.//div[@class="cmg_matchup_list_score"]').css('div.cmg_matchup_list_score_home::text').extract_first()
ats = matchup.xpath('.//div[@class="cmg_matchup_game_box cmg_game_data"]/@data-game-odd').extract_first()
hilo = matchup.xpath('.//div[@class="cmg_matchup_game_box cmg_game_data"]/@data-game-total').extract_first()
# ats =
# hilo =
# matchup_date_string = response.url[response.url.find('=')+1:]
game_string = team_away + '@' + team_home + '_ON_' + matchup_date_string
item['game_string'] = game_string
item['date_string'] = matchup_date_string
item['team_away'] = team_away
item['team_home'] = team_home
item['score_away'] = score_away
item['score_home'] = score_home
item['ats'] = ats
item['hilo'] = hilo
yield item
# consensus link to crawl
# for matchup in response.css('div.cmg_matchup_game'):
consensus_href = matchup.xpath('.//div//a[.="Consensus"]/@href').extract_first()
yield response.follow(consensus_href, self.parse_consensus_page, meta={'date_string':matchup_date_string, 'game_string': game_string})
# next page to crawl
yield scrapy.Request(page_tomorrow, callback=self.parse)
def parse_consensus_page(self, response):
'''
To find the real link to the expert lines api, then send requests.
'''
page_url = response.request.url
# # 'https://contests.covers.com/Consensus/MatchupConsensusDetails/a80513f5-5ca8-47cc-ae21-a87e00f145d9?showExperts=False'
searchObj = re.search(r'https://contests.covers.com/Consensus/MatchupConsensusDetails/(.*)\?showExperts.*', page_url)
gameHash = searchObj.group(1)
expertApi_prefix = 'https://contests.covers.com/Consensus/MatchupConsensusExpertDetails/'
expert_api_url = expertApi_prefix + gameHash
print(' ------------------========================------------------------- ' + expert_api_url)
# current date
# date_string = response.xpath('//*[@id="mainContainer"]/p/text()').extract()[2].split(',')[1].strip()
## ' - Thursday, March 1, 2018 7:30 PM\r\n'
date_string = response.meta['date_string']
game_string = response.meta['game_string']
yield scrapy.Request(expert_api_url, callback=self.parse_consensus_expertlines, meta={'date_string':date_string, 'game_string': game_string})
# %% issues:
'''
# %% Covers' consensus using a dynamic api to retrieve expert lines, which scrapy can not directly crawl:
# https://contests.covers.com/Consensus/MatchupConsensusDetails/a80513f5-5ca8-47cc-ae21-a87e00f145d9?showExperts=False
# %% 抓不到: 因为这步是动态加载的另外一个接口, 需要用到 splash 的 js 渲染引擎.
# //*[@id="expert_lines"]
response.xpath('//*[@id="expert_lines"]').extract()
# 截取第一个, 生成第二个:
# https://contests.covers.com/Consensus/MatchupConsensusDetails/a80513f5-5ca8-47cc-ae21-a87e00f145d9?showExperts=False
# https://contests.covers.com/Consensus/MatchupConsensusExpertDetails/e1bee5ea-2171-4e98-80d8-a87e00f1483f
'''
'''
To extract the summarized experts picks.
This can be used to generate one-page-overview for daily betting; Also, this can be used to do simple review for expert group's performance.
# 这个其实可以和 ScoreItem 放在一起, 但是由于这些数据不在同一个页面, 不方便同时存入一行数据里, 所以拆成 2 种 item 数据用以存储和分析.
'''
left_wagers_list = response.xpath('//div[@id="experts_analysis_content"]//div[@class="covers-CoversConsensusDetailsTable-awayWagers"]/text()').extract()
right_wagers_list = response.xpath('//div[@id="experts_analysis_content"]//div[@class="covers-CoversConsensusDetailsTable-homeWagers"]/text()').extract()
item = ExpertpickItem()
item['game_string'] = game_string
item['date_string'] = date_string
item['product1_left'] = left_wagers_list[0]
item['product1_right'] = right_wagers_list[0]
item['product2_left'] = left_wagers_list[1]
item['product2_right'] = right_wagers_list[1]
print(' ------------------========================------------------------- ' + game_string + ': ' + left_wagers_list[0] + ' vs ' + right_wagers_list[0] + ' AND ' + left_wagers_list[1] + ' vs ' + right_wagers_list[1])
yield item
def parse_consensus_expertlines(self, response):
'''
find the real link to the expert lines api, then send requests.
'''
def prepare_item(this_game_string, pick_product):
item = CoversItem()
item['game_string'] = response.meta['game_string']
item['pick_line'] = pick.xpath('td[2]/div/span//text()').extract_first()
item['pick_team'] = pick.xpath('td[2]/div/a//text()').extract_first()
item['pick_desc'] = pick.xpath('td[3]//text()').extract_first()
item['pick_product'] = pick_product
item['date_string'] = response.meta['date_string']
item['leader'] = pick.xpath('td[1]//text()').extract_first()
# return item
desc = item['pick_desc']
if desc.find("#1 ") != -1 or desc.find("#2 ") != -1:
return item
else:
pass
# pick_options = response.css('div.covers-CoversConsensus-leagueHeader::text').extract()
# team_away = pick_options[0][pick_options[0].find('for ')+4:]
# team_home = pick_options[1][pick_options[1].find('for ')+4:]
# this_game = team_away + ' AT ' + team_home
this_game = response.css('p.covers-CoversConsensus-detailsGameDate span::text').extract_first()
# item for ats_away
picks_ats_away = response.xpath('/html/body/div[1]/table/tbody/tr')
if len(picks_ats_away.extract()) > 1:
# temp1 = list([picks_ats_away[1]])
# for pick in temp1:
for pick in picks_ats_away[1:]:
item = prepare_item(this_game, 'ats_away')
yield item
# item for ats_home
picks_ats_home = response.xpath('/html/body/div[2]/table/tbody/tr')
if len(picks_ats_home.extract()) > 1:
for pick in picks_ats_home[1:]:
item = prepare_item(this_game, 'ats_home')
yield item
# item for ov_over
# item for ov_under
| 2633a052a40f90405ec5493a5539118dd4704008 | [
"Markdown",
"Python"
] | 3 | Python | crossz/scrapy_coverspick | 9a9e2c9589bb43cba44e096b20fb1e03cb6c3691 | ed70e77bc335e72d67b2465e125f346200532b12 |
refs/heads/master | <file_sep>import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;
public class UnionTest
{
private Vector a, b;
@Before // Set up - Called before every test method.
public void setUp()
{
a = new Vector(5);
b = new Vector(5);
}
@Test
public void repeatElement()
{
a.addElement(2);
a.addElement(3);
a.addElement(2);
b.addElement(2);
b.addElement(5);
b.addElement("a");
Vector c = new Vector(5);
c.addElement(2);
c.addElement(3);
c.addElement(5);
c.addElement("a");
assertTrue("A same element is in both vectors", c.equals(Union.union(a, b)));
}
@Test
public void nullElement()
{
a.addElement(2);
a.addElement(3);
a.addElement(null);
b.addElement(4);
b.addElement(5);
b.addElement("a");
Vector c = new Vector(5);
c.addElement(2);
c.addElement(3);
c.addElement(null);
c.addElement(4);
c.addElement(5);
c.addElement("a");
assertTrue("A vector contain null element", c.equals(Union.union(a, b)));
}
@Test (expected = NullPointerException.class)
public void nullVector()
{
a = null;
b.addElement(4);
Union.union(a, b);
}
}
| 4107ef5bd073818bc9ff3073cee7c1099f216e26 | [
"Java"
] | 1 | Java | SheilaOM/ISI-Pract_junit_idm_indiv | 961f7803d8a80245c0c14eb65187c896f2a63717 | 0629cd95f221085e5cf74226f7846776261a3415 |
refs/heads/master | <repo_name>halgurx/halgurx.github.io<file_sep>/openlayers/ol_function.js
function flash(feature,number) {
var start = new Date().getTime();
var listenerKey;
var duration = 10000;
function animate(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
var flashGeom = feature.getGeometry().clone();
var elapsed = frameState.time - start;
var elapsedRatio = elapsed / duration;
// radius will be 5 at start and 30 at end.
var radius = ol.easing.easeOut(elapsedRatio) * 10 + 5;
var opacity = ol.easing.easeOut(1 - elapsedRatio);
var style
if(true){
style = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
snapToPixel: false,
stroke: new ol.style.Stroke({
color: 'rgba(255, 0, 0, ' + opacity + ')',
width: 0.25 + opacity
})
})
});
}else style = new ol.style.Style();
style.setZIndex(100000);
vectorContext.setStyle(style);
vectorContext.drawGeometry(flashGeom);
if (elapsed > duration) {
ol.Observable.unByKey(listenerKey);
}
// tell OpenLayers to continue postcompose animation
map.render();
}
listenerKey = map.on('postcompose', animate);
//broken_aniarr[number]=setTimeout(function(){flash(feature,number)},10000);
}
var createIcon = function(icon,scale, name, offx, offy) {
var imageicon;
var opacity;
imageicon=icon;
opacity=1;
var obj = {
image: new ol.style.Icon( ({
scale: scale ? scale : 1,
src: icon,
rotation : 0,//rotation ? rotation * Math.PI / 180 : 0
opacity : opacity
}))
};
//레이블 폰트
if(name){
obj.text = new ol.style.Text({
text: name,
scale:1,
offsetY: offy || 20,
offsetX: offx || 0,
stroke: new ol.style.Stroke({color: "#000", width:0.5}),
fill: new ol.style.Fill({
color: '#000'
})
});
};
return new ol.style.Style(obj);
}
// overlay element 요소 생성
// name과 point는 필수요소 나머지는 선택
function makeLabel(obj){
var options={
name: obj.name, //표현할 텍스트
point: obj.point, //overlay가 표시될 [경도,위도] 데이터
class: (obj.class)? obj.class : "vessel_name_box", //해당 element에 부여될 class
color: (obj.color)? obj.color : "#FFF", //문자 색상
bgcolor: (obj.bgcolor)? obj.bgcolor : "#000", //배경색
positioning: (obj.positioning)? obj.positioning : "center-left", //point 좌표에서 어느쪽으로 element를 생성할지 결정
offset: (obj.offset)? obj.offset : [0,0] // [x,y]축 만큼 생성된 element를 이동 시킵니다.
}
var popupOpt = {};
if(options.point){
// 위경도 좌표를 데이터에 맞게 변환
options.point=ol.proj.fromLonLat(options.point);
//web element 정의
var el = document.createElement("div");
el.className = options.class;
el.style.color = options.color;
el.style.backgroundColor = options.bgcolor;
el.innerHTML = options.name;
//overlay option
popupOpt = {
element: el,
offset: options.offset, // 배치좌표에서 x축 y축으로 얼마나 이동시킬지 세부조정
position: options.point, //배치 좌표
positioning : options.positioning, // 배치좌표에서 element 생성 시작점
autoPan: false
}
}
var overlay= new ol.Overlay(popupOpt) //오버레이 생성
//LabelOverlay.push(overlay); //오버레이는 일괄적인 삭제가 불가능하고 하나하나 지정해서 지워야 하기떼믄에 전역배열변수에 추가.
return overlay;
}
function getroutepathCoord(datarow){
var route_arr=[];
var data =JSON.parse(datarow);
for(var i=0;i<data.length;i++){
route_arr.push(data[i]);
}
return route_arr;
}
//route 경로를 그리는 함수.
function routeDraw(obj){
var options={
data:obj.data,
dataType:(obj.dataType)? obj.dataType:"json",
icon:(obj.icon)? obj.icon:false,
iconImage:(obj.iconImage)? obj.iconImage:false
}
var routeLayer;
var routeFea= [];
var portFea=[];
var data;
if(options.dataType=="json"){
data=getroutepathCoord(options.data);
}else{
data=options.data;
}
//Feature 별 스타일 만들기, 함수로 만들어서 이름에 따라 아이콘 변경하기
var styles = {
'route_end': new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#b1e545',
width: 5
}),
zIndex : 9100
}),
'icon': new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#3399CC'
})
}),
zIndex : 9999
}),
'sel_icon': new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#CC9933'
})
}),
zIndex : 9999
}),
'marker' : function(feature){
var iconImage = feature.get("iconImage");
//var name = feature.get("name");
var style = new ol.style.Style({
image: new ol.style.Icon({
opacity:1,
anchor: [0.5, 1],
scale:0.8,
src:iconImage
}),
/*text : new ol.style.Text({
text: name,
scale:1,
offsetY: 10,
offsetX: 0,
stroke: new ol.style.Stroke({color: "#333", width:0.5}),
fill: new ol.style.Fill({
color: '#eee'
})
})*/
});
return style;
}
};
var arcCoordLength;
if(data.length > 1){
//경로의 각 꼭지점에 아이콘 생성
if(options.icon){
for(k = 0; k<data.length; k++){
if(!options.iconImage){
portFea.push(
new ol.Feature({
type: 'icon',
geometry: new ol.geom.Point(ol.proj.fromLonLat(data[k])),
sel_style:styles['sel_icon']
})
)
}else{
portFea.push(
new ol.Feature({
type: 'marker',
iconImage : options.iconImage,
geometry: new ol.geom.Point(ol.proj.fromLonLat(data[k]))
})
);
}
}
}
arcCoordLength = data.length-1;
//멀티라인 좌표로 만들기
for(j = 0; j<arcCoordLength; j++){
var lineCoord = [];
lineCoord.push(data[j], data[j+1]);
if(Math.abs(lineCoord[0][0] - lineCoord[1][0]) > 200){
if(lineCoord[0][0] > 0 && lineCoord[1][0] < 0){
lineCoord[1][0]=lineCoord[1][0]+360;
}else if(lineCoord[0][0]< 0 && lineCoord[1][0] > 0){
lineCoord[0][0]=lineCoord[0][0]+360;
}
}
routeFea.push(
new ol.Feature({
type: 'route_end',
geometry: new ol.geom.MultiLineString([[ol.proj.fromLonLat(lineCoord[0]),ol.proj.fromLonLat(lineCoord[1])]])
})
);
}
}
var allFeatures = routeFea.concat(portFea);
routeLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: allFeatures
}),
style: function(feature) {
var type = feature.get('type');
if(type === 'marker'){
return styles[type](feature);
}
return styles[type];
}
});
//routeLayer.setZIndex(1201);
return routeLayer;
}
function DDolrouteDraw(obj){
var options={
data:obj.data,
dataType:(obj.dataType)? obj.dataType:"json",
icon:(obj.icon)? obj.icon:false,
iconImage:(obj.iconImage)? obj.iconImage:false
}
var popupdata =obj.popupdata
var namedata =obj.namedata
var routeLayer;
var routeFea= [];
var portFea=[];
var data;
if(options.dataType=="json"){
data=getroutepathCoord(options.data);
}else{
data=options.data;
}
//Feature 별 스타일 만들기, 함수로 만들어서 이름에 따라 아이콘 변경하기
var styles = {
'route_end': new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#b1e545',
width: 5
}),
zIndex : 9100
}),
'icon': new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#3399CC'
})
}),
zIndex : 9999
}),
'DDolicon':function(feature){
var name=feature.get("name");
var style =new ol.style.Style({
image: new ol.style.Icon({
opacity:1,
anchor: [0.5, 1],
scale:0.05,
src:"./img/Sports_Mountain_Biking_icon.png"
}),
text : new ol.style.Text({
text: name,
scale:1.4,
offsetY: -35,
offsetX: -3,
stroke: new ol.style.Stroke({color: "#000000", width:0.5}),
fill: new ol.style.Fill({
color: '#000000'
})
}),
zIndex : 9999
})
return style;
},
'sel_icon': new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#CC9933'
})
}),
zIndex : 9999
}),
'marker' : function(feature){
var iconImage = feature.get("iconImage");
var name = feature.get("name");
var style = new ol.style.Style({
image: new ol.style.Icon({
opacity:1,
anchor: [0.55,0.55],
scale:1,
src:iconImage
}),
text : new ol.style.Text({
text: name,
scale:1.5,
offsetY: 18,
offsetX: 0,
stroke: new ol.style.Stroke({color: "#3333ff", width:0.5}),
fill: new ol.style.Fill({
color: '#3333ff'
})
}),
zIndex : 9999
});
return style;
}
};
var arcCoordLength;
if(data.length > 1){
//경로의 각 꼭지점에 아이콘 생성
if(options.icon){
for(k = 0; k<data.length; k++){
if(!options.iconImage){
portFea.push(
new ol.Feature({
type: 'icon',
geometry: new ol.geom.Point(ol.proj.fromLonLat(data[k])),
sel_style:styles['sel_icon']
})
)
}else{
portFea.push(
new ol.Feature({
type: 'marker',
iconImage : options.iconImage,
geometry: new ol.geom.Point(ol.proj.fromLonLat(data[k])),
name: namedata[k]
})
);
if(k!=data.length-1){
portFea.push(
new ol.Feature({
type: 'DDolicon',
geometry: new ol.geom.Point(ol.proj.fromLonLat([(data[k][0]+data[k+1][0])/2,(data[k][1]+data[k+1][1])/2])),
sel_style:"DDolicon",
popup:popupdata[k],
name: (k+1)+"부"
})
)
}
}
}
}
arcCoordLength = data.length-1;
//멀티라인 좌표로 만들기
for(j = 0; j<arcCoordLength; j++){
var lineCoord = [];
lineCoord.push(data[j], data[j+1]);
if(Math.abs(lineCoord[0][0] - lineCoord[1][0]) > 200){
if(lineCoord[0][0] > 0 && lineCoord[1][0] < 0){
lineCoord[1][0]=lineCoord[1][0]+360;
}else if(lineCoord[0][0]< 0 && lineCoord[1][0] > 0){
lineCoord[0][0]=lineCoord[0][0]+360;
}
}
routeFea.push(
new ol.Feature({
type: 'route_end',
geometry: new ol.geom.MultiLineString([[ol.proj.fromLonLat(lineCoord[0]),ol.proj.fromLonLat(lineCoord[1])]])
})
);
}
}
var allFeatures = routeFea.concat(portFea);
routeLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: allFeatures
}),
style: function(feature) {
var type = feature.get('type');
if(type === 'marker'||type === 'DDolicon'){
return styles[type](feature);
}
return styles[type];
}
});
//routeLayer.setZIndex(1201);
return routeLayer;
}
function iconDraw(option){
var options={
data: option.data,
type: (option.type)? option.type:"normal"
}
var IconFeas = [];
var data = options.data;
var i = 0, Length = data.length;
for(;i < Length; i++){
var point = ol.proj.fromLonLat(data[i].point);
var IconFea = new ol.Feature(new ol.geom.Point(point));
IconFea.set('IconKey', data[i].key);
IconFea.set('popup', data[i].popup);
IconFea.set('type',options.type);
//icon, rotation, scale, name, offx, offy
IconFea.set('style', createIcon(data[i].icon, 1));
IconFea.set('sel_style', createIcon(data[i].icon,1)); //선택 인터렉션이 들어올때의 아이콘
IconFea.set('namestyle', createIcon(data[i].icon, 1, data[i].name)); //아이콘 하단에 텍스트 추가.
IconFeas.push(IconFea);
}
var IconVector = new ol.source.Vector({
features: IconFeas
});
//iconLayer = QvOSM_PVM_CUSTOM_MAP.removeLayer(iconLayer);
iconLayer = new ol.layer.Vector({
style : function(feature) {
return (LabelC)? feature.get('namestyle'):feature.get('style');
},
source:IconVector
});
iconLayer.setZIndex(9999);
return iconLayer;
}
//bubble 그리는 함수
var bubbleDraw = function(option){
var bubblesource_p = new ol.source.Vector();
var bubbles_p;
var bubbleData=option;
for(var bk in bubbleData){
var bRow = bubbleData[bk];
var type = bRow["t"];
var lonLat = bRow["point"];
var point = new ol.geom.Point(lonLat);
var rate = bRow["rate"];;
point.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
var radius = 100*rate;
if(radius < 10)radius = 10;
if(rate == 1)radius = 10;
if(rate == 0)radius = 1;
var feature = new ol.Feature(point);
feature.set("i",{"t":type,"cd":bRow["key"],"nm":bRow["kname"],"r":radius*2});
bubblesource_p.addFeature(feature);
}
bubbles_p = new ol.layer.Vector({
source: bubblesource_p,
opacity:0.5,
style:function(feature){
var info = feature.get("i");
var nm = info["nm"];
var scale = info["r"];
var b = {};
b.image =new ol.style.Circle({
radius: scale,
fill: new ol.style.Fill({
color:'#63b34b'
})
});
var style = new ol.style.Style(b);
return style;
},
zIndex:1000
});
return bubbles_p
}
| 030bf4ea13da2648e0946520afa3615000db9616 | [
"JavaScript"
] | 1 | JavaScript | halgurx/halgurx.github.io | cec58bf10c449db0d2342d46b36fc8b0789a12e4 | f3b83afead1006a9e999002d20b6d8d486173470 |
refs/heads/master | <file_sep># Seknova Health Care System
A Pen created on CodePen.io. Original URL: [https://codepen.io/shannon1012/pen/wvGzgQN](https://codepen.io/shannon1012/pen/wvGzgQN).
<file_sep>//show default start date
var year = new Date().getFullYear().toString();
var month = (new Date().getMonth() + 1).toString();
var date = (new Date().getDate() - 7).toString();
function timeAdd0(str) {
if (str.length <= 1) {
str = "0" + str;
}
return str;
}
year = timeAdd0(year);
month = timeAdd0(month);
date = timeAdd0(date);
var dateControl = document.querySelector('input[type="date"]');
dateControl.value = year + "-" + month + "-" + date;
//convert start time format into post request format
function SendFormData() {
var formElement = document.getElementById("form");
var StartDateTime = [],
EndDateTime = [];
var UserID = String(formElement[0].value);
StartDateTime.push(formElement[1].value[8]);
StartDateTime.push(formElement[1].value[9]);
StartDateTime.push("/");
StartDateTime.push(formElement[1].value[5]);
StartDateTime.push(formElement[1].value[6]);
StartDateTime.push("/");
StartDateTime.push(formElement[1].value[0]);
StartDateTime.push(formElement[1].value[1]);
StartDateTime.push(formElement[1].value[2]);
StartDateTime.push(formElement[1].value[3]);
StartDateTime = String(StartDateTime);
StartDateTime = StartDateTime.replace(/,/g, "");
StartDateTime = StartDateTime.concat("T00:00:00");
//show end date after submit start date and duration
var enddatetime = String(formElement[1].value);
EndDateTime = new Date(
parseInt(enddatetime.substring(0, 4)),
parseInt(enddatetime.substring(5, 7)),
parseInt(enddatetime.substring(8, 10))
);
Date.prototype.addDays = function (days) {
this.setDate(this.getDate() + days);
return this;
};
EndDateTime = EndDateTime.addDays(parseInt(formElement[2].value) * 7);
var year = EndDateTime.getFullYear().toString();
var month = EndDateTime.getMonth().toString();
var date = EndDateTime.getDate().toString();
function timeAdd0(str) {
if (str.length <= 1) {
str = "0" + str;
}
return str;
}
year = timeAdd0(year);
month = timeAdd0(month);
date = timeAdd0(date);
document.getElementById("EndDateTime").innerHTML =
year + "/" + month + "/" + date;
//system time
var NowDate = new Date();
var year = NowDate.getFullYear();
var month = NowDate.getMonth() + 1;
var date = NowDate.getDate();
function addMonths(date, months) {
var NowDateCompare = NowDate.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != NowDateCompare) {
date.setDate(0);
}
return date;
}
NowDateCompare = addMonths(NowDate,1)
document.getElementById("time").innerHTML =
year + "年" + month + "月" + date + "日";
setTimeout("ShowTime()", 1000);
//alert if time interval is less one week
if (NowDateCompare.valueOf() < EndDateTime.valueOf()) {
alert("Time interval must be at least one week!");
}
//convert start time format into post request format
var Enddatetime = date + "/" + month + "/" + year;
Enddatetime = Enddatetime.concat("T00:00:00");
//set variables and user information
var SystemTime = [];
var EventsStartTime = [],
EventsEndTime = [];
var Min = [],
Max = [],
Q1 = [],
Q2 = [],
Q3 = [],
MaxMinRange = [],
PercentageOfGlucose = [],
Data = [],
boxcolor = [];
var SD,
eA1C,
CV,
DataSufficency,
AUC,
TimesOfHypo,
TimesOfHyper,
EventCount,
Mean,
RecordsMaxCount;
var RecordsIntervalTime = "";
var information = {
CmdID: 9,
UserID: UserID,
StartDatetime: StartDateTime,
EndDatetime: Enddatetime
};
//get data with jquery
$.ajax({
url: "https://05q4eqlbt3.execute-api.us-east-1.amazonaws.com/default/web",
data: JSON.stringify(information),
dataType: "json",
async: false,
type: "POST",
success: function (data) {
//simple calculations
SD = data.SD;
eA1C = data.eA1C;
CV = data.CV;
DataSufficiency = data.DataSufficiency;
AUC = data.AUC;
TimesOfHypo = data.TimesOfHypo;
TimesOfHyper = data.TimesOfHyper;
document.getElementById("sd").innerHTML = SD;
document.getElementById("ea1c").innerHTML = eA1C;
document.getElementById("cv").innerHTML = CV;
document.getElementById("datasufficiency").innerHTML =
DataSufficiency + "%";
document.getElementById("auc").innerHTML = AUC;
document.getElementById("timesofhypo").innerHTML = TimesOfHypo;
document.getElementById("timesofhyper").innerHTML = TimesOfHyper;
//events count and event datails
EventsCount = data.EventsCount;
document.getElementById("eventscount").innerHTML = EventsCount;
//turn json into talbes(Events)
Data = data.Events;
var forTable = $(".for-table tbody");
var eventsum = Data.length;
for (var i = 0; i < eventsum; i++) {
forTable.append(
"<tr>" +
"<td>" +
"#" +
(i + 1) +
"</td>" +
"<td>" +
Data[i].StartTime +
"</td>" +
"<td>" +
Data[i].EndTime +
"</td>" +
"<td>" +
Data[i].Note +
"</td>" +
"</tr>"
);
}
//set events highlight data
for (var i = 0; i < 15; i++) {
if (Data[i] != null) {
EventsStartTime.push(Data[i].StartTime);
EventsEndTime.push(Data[i].EndTime);
} else {
EventsStartTime.push("none");
EventsEndTime.push("none");
}
}
//record informations(system time code is written after ajax code)
RecordsIntervalTime = data.RecordsIntervalTime;
RecordsMaxCount = data.RecordsMaxCount;
Mean = data.Mean;
document.getElementById(
"recordsintervaltime"
).innerHTML = RecordsIntervalTime;
document.getElementById("recordsmaxcount").innerHTML = RecordsMaxCount;
document.getElementById("mean").innerHTML = Mean;
//set data for charts
//linechart
for (var i = 0; i < data["Records"].length; i++) {
SystemTime.push(data.Records[i].SystemTime);
Min.push(data.Records[i].Min);
Max.push(data.Records[i].Max);
Q1.push(data.Records[i].Q1);
Q2.push(data.Records[i].Q2);
Q3.push(data.Records[i].Q3);
}
//barchart
MaxMinRange.push(data.MinRangeAtSleep);
MaxMinRange.push(data.MaxRangeAtSleep);
MaxMinRange.push(data.MinRangeAtWake);
MaxMinRange.push(data.MaxRangeAtWake);
MaxMinRange.push(data.MinRangeAt24h);
MaxMinRange.push(data.MaxRangeAt24h);
//piechart
PercentageOfGlucose.push(data.PercentageOfL2Hypo);
PercentageOfGlucose.push(data.PercentageOfL1Hypo);
PercentageOfGlucose.push(data.PercentageOfNormal);
PercentageOfGlucose.push(data.PercentageOfL2Hyper);
PercentageOfGlucose.push(data.PercentageOfL1Hyper);
},
error: function () {
alert("error");
}
});
//charts
//set chart colors
var chartColors = {
transparent: "rgb(0,0,0,0)",
red: "rgb(197, 23, 41)",
darkgreen: "rgb(0,100,0)",
yellow: "rgb(250, 250, 0)",
lightgrey: "rgb(200, 200, 200)",
darkgrey: "rgb(120, 120, 120)",
darkorchid: "rgb(153,50,204)",
blue: "rgb(0, 0, 150)"
};
//linechart
var config = {
type: "line",
data: {
labels: SystemTime,
datasets: [
{
label: "Max",
backgroundColor: chartColors.lightgrey,
borderColor: chartColors.red,
borderWidth: 2,
data: Max,
fill: false,
lineTension: 1
},
{
label: "Q3",
backgroundColor: chartColors.lightgrey,
borderColor: chartColors.yellow,
borderWidth: 2,
data: Q3,
fill: false,
lineTension: 1
},
{
label: "Q2",
fill: false,
backgroundColor: chartColors.lightgrey,
borderColor: chartColors.darkgreen,
borderWidth: 2,
data: Q2,
fill: false,
lineTension: 1
},
{
label: "Q1",
backgroundColor: chartColors.lightgrey,
borderColor: chartColors.blue,
borderWidth: 2,
data: Q1,
fill: "-2",
lineTension: 1
},
{
label: "Min",
backgroundColor: chartColors.lightgrey,
borderColor: chartColors.darkorchid,
borderWidth: 2,
data: Min,
fill: false,
lineTension: 1
}
]
},
options: {
//assume that events will not occur over 15 times
annotation: {
annotations: [
{
id: "event1",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[0],
xMax: EventsEndTime[0],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event2",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[1],
xMax: EventsEndTime[1],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event3",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[2],
xMax: EventsEndTime[2],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event4",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[3],
xMax: EventsEndTime[3],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event5",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[4],
xMax: EventsEndTime[4],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event6",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[5],
xMax: EventsEndTime[5],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event7",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[6],
xMax: EventsEndTime[6],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event8",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[7],
xMax: EventsEndTime[7],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event9",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[8],
xMax: EventsEndTime[8],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event10",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[9],
xMax: EventsEndTime[9],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event11",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[10],
xMax: EventsEndTime[10],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event12",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[11],
xMax: EventsEndTime[11],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event13",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[12],
xMax: EventsEndTime[12],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event14",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[13],
xMax: EventsEndTime[13],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
},
{
id: "event15",
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: EventsStartTime[14],
xMax: EventsEndTime[14],
yMin: 2,
yMax: 498,
backgroundColor: chartColors.transparent,
borderColor: chartColors.darkgrey,
borderWidth: 2
}
]
},
responsive: true,
tooltips: {
mode: "index",
intersect: false
},
hover: {
mode: "nearest",
intersect: true
},
elements: { point: { radius: 0 } },
scales: {
xAxes: [
{
display: true,
scaleLabel: {
display: true,
labelString: "Time"
}
}
],
yAxes: [
{
display: true,
scaleLabel: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 500
}
}
]
}
}
};
var line = document.getElementById("14days").getContext("2d");
var myLine = new Chart(line, config);
//barchart
var barChartData = {
labels: [
"MinRangeAtSleep",
"MaxRangeAtSleep",
"MinRangeAtWake",
"MaxRangeAtWake",
"MaxRangeAt24h",
"MaxRangeAt24h"
],
datasets: [
{
backgroundColor: [
chartColors.darkgrey,
chartColors.darkgrey,
chartColors.blue,
chartColors.blue,
chartColors.red,
chartColors.red
],
borderColor: "black",
borderWidth: 1,
data: MaxMinRange
}
]
};
var chartOptions = {
layout: {
padding: {
left: 20,
right: 0,
top: 0,
bottom: 0
}
},
plugins: {
labels: {
render: "value",
precision: 0,
fontSize: 12,
fontStyle: "normal"
}
},
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{ barPercentage: 0.6 }],
yAxes: [
{
ticks: {
beginAtZero: true,
suggestedMin: 0,
suggestedMax: 500
}
}
]
}
};
var bar = document.getElementById("sleepwake").getContext("2d");
myBar = new Chart(bar, {
type: "bar",
data: barChartData,
options: chartOptions
});
//piechart
var pie = document.getElementById("percentage");
var myChart = new Chart(pie, {
type: "pie",
data: {
labels: ["L2Hypo", "L1Hypo", "Normal", "L2Hyper", "L1Hyper"],
datasets: [
{
data: PercentageOfGlucose,
backgroundColor: [
chartColors.blue,
chartColors.yellow,
chartColors.lightgrey,
chartColors.darkgrey,
chartColors.red
],
borderColor: "black",
borderWidth: 1
}
]
},
options: {
layout: {
padding: {
left: 20,
right: 0,
top: 0,
bottom: 0
}
},
legend: {
display: true,
position: "right",
align: "center"
},
responsive: true,
plugins: {
labels: {
render: "percentage",
precision: 0,
fontSize: 15,
fontStyle: "normal",
position: "outside"
}
}
}
});
}<file_sep># *Seknova Health Care System Report*
A web report to show your glucose informations. It is also allow to print it.
This web created on CodePen.[See on CodePen](https://codepen.io/shannon1012/pen/wvGzgQN)
## *Input*
* Your User ID
* Date you want to start with
* Date time duration (1 or 2 weeks)
* Click Submit button to show the report
## *Informations and Charts*
#### Informations
- SD, eA1C, CV, Data Sufficiency, Time of Hypo, Time of Hyper
- Events Count and Events' Details
- Records Interval Time, Records Max Count, Mean, System Time
#### Charts
- Line Chart : Glucose level line during 1 or 2 weeks (base on your selection)
- Show lines with Max, Q3, Q2, Q1 and Min
- Note the events and highlight the event time intervals
- Bar chart : Maximum and Minimum glucose level at sleeptime, waketime, and 24 hours
- Pie chart : Percentage of L2 Hypo, L1 Hypo, Normal, L2 Hyper, L1 Hyper
## *CDN Sources*
* [jQuery](http://jquery.com)
* [Chart.js](https://www.chartjs.org/docs/latest/)
* [Chart.js/plugin](https://www.chartjs.org/docs/latest/developers/plugins.html)
* [Chart.js/plugin/annotation](https://github.com/chartjs/chartjs-plugin-annotation) | a3c5a866b99238afaacd74743d59ab9609170afc | [
"Markdown",
"JavaScript"
] | 3 | Markdown | shannon1012/Seknova_Health_Care_System | 6ff8e32dae15b1a5f0f10e9cb801b91fbd103cc6 | 163d799403e0c3e2db5f076e24d3f9e500d2cfa8 |
refs/heads/master | <file_sep># site_visits
Site Visits
This is code to help prioritize site visits based on location and other attributes
.
The code files all start with the letter r for run.
r1 takes the site visit location Excel file on the WSDOT sharepoint site and converts the addresses into lat/long that can be added to maps.
r2 calculates the distances in miles and minutes between any pair of sites. The calculation assumes noon on a Tuesday for average midweek travel times given that one site visit would have already occured that day.
r3 produces a basic ggmap to show the locations of the sites across the site.
r4 is the shiny web app. This is a zoomable map that zooms to any grantee site selected and shows all other sites that you could get to within 60 minutes. Popups show the names of the sites as well as the days since the last site visit by visit type. If there are no sites within 60 minutes, only the site selected is show and the map zooms out to the state level. The site selection drop down is searchable.
r5 is the code outside of the shiny app for producing the type and days since last visit data frame from the Excel file on the SSO sharepoint site.
<file_sep># Site visit pririization and data analysis
# r1 address geocoding
# Set Working directory to Github folder, change path for your machine
setwd("~/GitHub/site_visits")
# Packages
library(openxlsx) # open xlsx files, note that readxl doesn't read urls... Come on Hadley...
library(tidyverse) # For all that is good and holy in this world
library(ggmap) # geocoding and mapping
# link to the data from Seth
# locations_url <- "http://sharedot/eso/so/pubtcb/Docs/19-21%20S_V%20Planning.xlsx" # original file, using updated addresses in sheet below.
locations_url <- "http://sharedot/eso/so/pubtcb/Docs/2019-11-08 - S_V Criteria Prioritization Draft.xlsx"
# Create a data frame from the data
locations <- openxlsx::read.xlsx(locations_url,
sheet = "SV All") # adding specification for sheet name, different from initial version.
#startRow = 8) # from older address sheet. don't need here.
# Just keep the address (useful) fields
# locations <- locations %>%
# dplyr::select(Grantee, Mailing.Address, Mailing.Address.City, Mailing.Address.State)
# Cannot use dplyr here because spreadsheet has two identical colums names Grantee, and the tidyverse doesn't accept shitty data, so instead:
locations <- locations[,c("Grantee",
"Mailing.Address",
"Mailing.Address.City",
"Mailing.Address.State",
"Mailing.Address.Zip")]
# Clean up the address field to remove extranious information, eg suite numbers
locations$Mailing.Address <- gsub("(.*),.*", "\\1", locations$Mailing.Address)
# Only keep records with complete information as to not have places with no address. Want this to avoid geocoding w/o an address, which google will attempt
locations <- locations %>%
tidyr::drop_na()
# Create a field with a complete address
locations$full_address <- paste(locations$Mailing.Address,
locations$Mailing.Address.City,
locations$Mailing.Address.State,
locations$Mailing.Address.Zip,
sep = ", ")
# Keep only the Grantee name and full address for the sake of a tidyer DF
locations <- locations %>%
dplyr::select(Grantee, full_address)
# Tell stupid google about the api key, note, this is the location of mine
api <- readLines("H:/personal/google.api")
ggmap::register_google(key = api, account_type = "standard")
# geocode the locations
locations_df <- locations %>%
ggmap::mutate_geocode(full_address)
# Remove large Urban or small Rural grantees that are not subject to the site visit requirements for WSDOT
# per email from <NAME> and <NAME> on 20191119
# Updated request on 20191218 to reinstate some of these
locations_df <- locations_df %>%
dplyr::filter(!(#Grantee == "<NAME>" |
Grantee == "City of Selah" |
#Grantee == "City of Yakima" |
Grantee == "Clark County Public Transportation Benefit Area (C - Tran)" |
#Grantee == "Community Action of Skagit County" |
#Grantee == "Entiat Valley Community Services (EVCS)" |
#Grantee == "Everett Transit" |
#Grantee == "King County Metro Transit" |
#Grantee == "Kitsap County Public Transportation Benefit Area Authority" |
#Grantee == "Lower Elwha Klallam Tribe" |
#Grantee == "Pierce Transit" |
Grantee == "Samish Indian Nation" |
#Grantee == "Snohomish County Workforce Development Council" |
#Grantee == "Spokane Transit Authority" |
Grantee == "Stanwood Community & Senior Center" |
#Grantee == "Thurston County Public Benefit Transportation Area (Intercity Transit)" |
Grantee == "Whatcom Transportation Authority" |
Grantee == "Yakima Valley Conference of Governments (YVCOG)"))
# Export list of addresses for giggles
write.csv(locations_df, "data/locations_df.csv", row.names = FALSE)
<file_sep># Site visit pririization and data analysis
# r3 basic map
# Packages
library(readr) # sane way of reading files
library(tidyverse) # For all that is good and holy in this world
library(ggmap) # make map
# Set Working directory to Github folder, change path for your machine
setwd("~/GitHub/site_visits")
# Bring in the file either from r2 or from data, note that if refreshing for new sites, will need to run r1 and r2
distances_df <- readr::read_csv("data/distances_df.csv")
# Bring the long and lat back to two fields instead of one
# and make new fields numeric
distances_df <- distances_df %>%
tidyr::separate(latlong1,
c("lat_origin","long_origin"),
sep = "\\+") %>%
dplyr::mutate(long_origin = as.numeric(long_origin)) %>%
dplyr::mutate(lat_origin = as.numeric(lat_origin))
# start with an ugly plot
ugly_plot <- plot(lat_origin ~ long_origin,
data = distances_df)
# Tell stupid google about the api key, note, this is the location of mine
api <- readLines("H:/personal/google.api")
ggmap::register_google(key = api, account_type = "standard")
# make a bounding box for the observations
site_visit_bbox <- ggmap::make_bbox(long_origin,
lat_origin,
distances_df,
f = .05)
# Make a simple map just to see hwat we have
get_stamenmap(site_visit_bbox,
zoom = 10,
maptype = "toner") %>%
ggmap() +
geom_point(aes(x = long_origin,
y = lat_origin),
data = distances_df,
colour = "red",
size = 1) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
theme(axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())
ggplot2::ggsave("graphics/basic_map.png")
# And let's finish cleaning up the data frame for use in leaflet mapping
# make the destination lat long useful again
# Bring the long and lat back to two fields instead of one
# and make new fields numeric
# turn seconds into minutes and round up
distances_df <- distances_df %>%
tidyr::separate(latlong2,
c("lat_destination","long_destination"),
sep = "\\+") %>%
dplyr::mutate(long_destination = as.numeric(long_destination)) %>%
dplyr::mutate(lat_destination = as.numeric(lat_destination)) %>%
dplyr::mutate(minutes = ceiling(seconds/60)) %>%
dplyr::select(-seconds) %>%
dplyr::rename(grantee_origin = grantee1) %>%
dplyr::rename(grantee_destination = grantee2)
# write out DF as grantee to be used in leaflet mapping
write.csv(distances_df, "data/grantee_df.csv", row.names = FALSE)
<file_sep># Site visit pririization and data analysis
# r5 types and date since last visit data frame
library(openxlsx) # open xlsx files, note that readxl doesn't read urls... Come on Hadley...
library(tidyverse) # for all that is good and holy in this world
# Set Working directory to Github folder, change path for your machine
setwd("~/GitHub/site_visits")
# Bring in the data on visit type and date since last visit
types <- openxlsx::read.xlsx("http://sharedot/eso/so/pubtcb/Docs/2019-11-08 - S_V Criteria Prioritization Draft.xlsx",
sheet = "SV Time Since SV",
startRow = 5,
cols = 2:6,
detectDates = TRUE) %>%
dplyr::rename(grantee = Grantee,
admin = Date.of.Last.Site.Visit,
capital = X3,
drug = X4,
financial = X5) %>%
dplyr::filter(!(grantee == "<NAME>" |
grantee == "City of Selah" |
grantee == "City of Yakima" |
grantee == "Clark County Public Transportation Benefit Area (C - Tran)" |
grantee == "Community Action of Skagit County" |
grantee == "Entiat Valley Community Services (EVCS)" |
grantee == "Everett Transit" |
grantee == "King County Metro Transit" |
grantee == "Kitsap County Public Transportation Benefit Area Authority" |
grantee == "Lower Elwha Klallam Tribe" |
grantee == "Pierce Transit" |
grantee == "Samish Indian Nation" |
grantee == "Snohomish County Workforce Development Council" |
grantee == "Spokane Transit Authority" |
grantee == "Stanwood Community & Senior Center" |
grantee == "Thurston County Public Benefit Transportation Area (Intercity Transit)" |
grantee == "Whatcom Transportation Authority" |
grantee == "Yakima Valley Conference of Governments (YVCOG)")) %>%
tidyr::pivot_longer(c("admin","capital","drug","financial"),
names_to = "type",
values_to = "date_since") %>%
dplyr::filter(substr(date_since,1,1)=="2") %>%
dplyr::mutate(date_since = as.Date(date_since)) %>%
dplyr::mutate(days_since = Sys.Date() - date_since) %>%
dplyr::select(-date_since) %>%
tidyr::pivot_wider(names_from = type,
values_from = days_since) %>%
dplyr::select(grantee, admin, capital, drug, financial)
# write out the DF
write.csv(types, "data/types_df.csv", row.names = FALSE)
# Creating a new version that allows for comments in addition to dates and times since the last visit
# Will make two DFs based on whether or not there is a date in them.
# then put the DFs back together into a final one for display purposes back in the application.
# types with a date:
types_number <- openxlsx::read.xlsx("http://sharedot/eso/so/pubtcb/Docs/2019-11-08 - S_V Criteria Prioritization Draft.xlsx",
sheet = "SV Time Since SV",
startRow = 5,
cols = 2:6,
detectDates = TRUE) %>%
dplyr::rename(grantee = Grantee,
admin = Date.of.Last.Site.Visit,
capital = X3,
drug = X4,
financial = X5) %>%
dplyr::filter(!(#Grantee == "<NAME>" |
grantee == "City of Selah" |
#Grantee == "City of Yakima" |
grantee == "Clark County Public Transportation Benefit Area (C - Tran)" |
#Grantee == "Community Action of Skagit County" |
#Grantee == "Entiat Valley Community Services (EVCS)" |
#Grantee == "Everett Transit" |
#Grantee == "King County Metro Transit" |
#Grantee == "Kitsap County Public Transportation Benefit Area Authority" |
#Grantee == "Lower Elwha Klallam Tribe" |
#Grantee == "Pierce Transit" |
grantee == "Samish Indian Nation" |
#Grantee == "Snohomish County Workforce Development Council" |
#Grantee == "Spokane Transit Authority" |
grantee == "Stanwood Community & Senior Center" |
#Grantee == "Thurston County Public Benefit Transportation Area (Intercity Transit)" |
grantee == "Whatcom Transportation Authority" |
grantee == "Yakima Valley Conference of Governments (YVCOG)")) %>%
tidyr::pivot_longer(c("admin","capital","drug","financial"),
names_to = "type",
values_to = "date_since") %>%
dplyr::filter(substr(date_since,1,1)=="2") %>%
dplyr::mutate(date_since = as.Date(date_since)) %>%
dplyr::mutate(days_since = Sys.Date() - date_since) %>%
dplyr::select(-date_since) %>%
dplyr::mutate(days_since = as.character(days_since))
# types with text
types_text <- openxlsx::read.xlsx("http://sharedot/eso/so/pubtcb/Docs/2019-11-08 - S_V Criteria Prioritization Draft.xlsx",
sheet = "SV Time Since SV",
startRow = 5,
cols = 2:6,
detectDates = TRUE) %>%
dplyr::rename(grantee = Grantee,
admin = Date.of.Last.Site.Visit,
capital = X3,
drug = X4,
financial = X5) %>%
dplyr::filter(!(#Grantee == "<NAME>" |
grantee == "City of Selah" |
#Grantee == "City of Yakima" |
grantee == "Clark County Public Transportation Benefit Area (C - Tran)" |
#Grantee == "Community Action of Skagit County" |
#Grantee == "Entiat Valley Community Services (EVCS)" |
#Grantee == "Everett Transit" |
#Grantee == "King County Metro Transit" |
#Grantee == "Kitsap County Public Transportation Benefit Area Authority" |
#Grantee == "Lower Elwha Klallam Tribe" |
#Grantee == "Pierce Transit" |
grantee == "Samish Indian Nation" |
#Grantee == "Snohomish County Workforce Development Council" |
#Grantee == "Spokane Transit Authority" |
grantee == "Stanwood Community & Senior Center" |
#Grantee == "Thurston County Public Benefit Transportation Area (Intercity Transit)" |
grantee == "Whatcom Transportation Authority" |
grantee == "Yakima Valley Conference of Governments (YVCOG)")) %>%
tidyr::pivot_longer(c("admin","capital","drug","financial"),
names_to = "type",
values_to = "date_since") %>%
dplyr::filter(substr(date_since,1,1)!="2") %>%
dplyr::rename(days_since = date_since)
# put them together
types <-
rbind(types_number, types_text) %>%
tidyr::pivot_wider(names_from = type,
values_from = days_since) %>%
dplyr::select(grantee, admin, capital, drug, financial) %>%
dplyr::arrange(grantee)
# write out the DF
write.csv(types, "data/types_df.csv", row.names = FALSE)
<file_sep># r6 static map
# Packages
library(readr) # sane way of reading files
library(tidyverse) # For all that is good and holy in this world
library(ggmap) # make map
library(leaflet) # make maps differently
# Set Working directory to Github folder, change path for your machine
setwd("~/GitHub/site_visits")
# Bring in the clean data frame
grantee_df <- readr::read_csv("data/grantee_df.csv")
# Reduce to indivdual locations
grantee_df <- grantee_df %>%
dplyr::select(grantee_origin, lat_origin, long_origin) %>%
dplyr::distinct()
# make a bounding box for the observations
site_visit_bbox <- ggmap::make_bbox(long_origin,
lat_origin,
grantee_df,
f = .05)
# Make a simple map just to see hwat we have
get_stamenmap(site_visit_bbox,
zoom = 10,
maptype = "toner") %>%
ggmap() +
geom_point(aes(x = long_origin,
y = lat_origin),
data = grantee_df,
colour = "red",
size = 2) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
theme(axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank())
ggplot2::ggsave("graphics/static_map1.png",
width = 11,
height = 8.5,
units = "in",
dpi = 300)
# and try it in leaflet
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=grantee_df$long_origin,
lat=grantee_df$lat_origin,
label=grantee_df$grantee_origin,
labelOptions = labelOptions(noHide = T))
m # Print the map
# Simple version of this map is published on RPubs at:
# http://rpubs.com/bassoka/static_site_visit_map
<file_sep># Site visit pririization and data analysis
# r4 leaflet map
# packages
library(readr) # sane way of reading files
library(openxlsx) # open xlsx files, note that readxl doesn't read urls... Come on Hadley...
library(tidyverse) # for all that is good and holy in this world
library(leaflet) # javascript web mapping
library(leaflet.extras) # full screen control among other useful things
library(shiny)
# Set Working directory to Github folder, change path for your machine
# setwd("~/GitHub/site_visits")
# Bring in the clean data frame with distances
grantee_df <- readr::read_csv("data/grantee_df.csv")
# Bring in the types and date since last visit data
types_df <- readr::read_csv("data/types_df.csv") # if bringing it in from DF, but updateable version here
#types_df <- openxlsx::read.xlsx("http://sharedot/eso/so/pubtcb/Docs/2019-11-08 - S_V Criteria Prioritization Draft.xlsx",
# startRow = 5,
# cols = 2:6,
# detectDates = TRUE) %>%
# dplyr::rename(grantee = Grantee,
# admin = Date.of.Last.Site.Visit,
# capital = X3,
# drug = X4,
# financial = X5) %>%
# dplyr::filter(!(grantee == "<NAME>" |
# grantee == "City of Selah" |
# grantee == "City of Yakima" |
# grantee == "Clark County Public Transportation Benefit Area (C - Tran)" |
# grantee == "Community Action of Skagit County" |
# grantee == "Entiat Valley Community Services (EVCS)" |
# grantee == "Everett Transit" |
# grantee == "King County Metro Transit" |
# grantee == "Kitsap County Public Transportation Benefit Area Authority" |
# grantee == "Lower Elwha Klallam Tribe" |
# grantee == "Pierce Transit" |
# grantee == "Samish Indian Nation" |
# grantee == "Snohomish County Workforce Development Council" |
# grantee == "Spokane Transit Authority" |
# grantee == "Stanwood Community & Senior Center" |
# grantee == "Thurston County Public Benefit Transportation Area (Intercity Transit)" |
# grantee == "Whatcom Transportation Authority" |
# grantee == "Yakima Valley Conference of Governments (YVCOG)")) %>%
# tidyr::pivot_longer(c("admin","capital","drug","financial"),
# names_to = "type",
# values_to = "date_since") %>%
# dplyr::filter(substr(date_since,1,1)=="2") %>%
# dplyr::mutate(date_since = as.Date(date_since)) %>%
# dplyr::mutate(days_since = Sys.Date() - date_since) %>%
# dplyr::select(-date_since) %>%
# tidyr::pivot_wider(names_from = type,
# values_from = days_since) %>%
# dplyr::select(grantee, admin, capital, drug, financial)
# Join grantee and type DFs so can have popups for type and date since last visit
# Hack to join DFs; simpler to do before it needs to be a function on the server side
grantee_df <- merge(grantee_df, types_df, by.x = "grantee_origin", by.y = "grantee", all.x = TRUE)
# And some badness for a stupidly wide data frame, but expediency wins here...
grantee_df <- merge(grantee_df, types_df, by.x = "grantee_destination", by.y = "grantee", all.x = TRUE)
# Make the shiny app
shinyApp(
ui = bootstrapPage(
tags$style(type="text/css",
"html, body {width:100%;height:100%}",
".selectize-input { font-size: 12px; line-height: 14px;} .selectize-dropdown { font-size: 12px; line-height: 14px; }"),
leafletOutput("MapPlot1", width="100%", height="100%"),
absolutePanel(id = "controls", class = "panel panel-default", fixed = FALSE,
draggable = TRUE, top = "5", left = "auto", right = "5", bottom = "auto",
width = "300", height = "auto",
uiOutput("siteSelect"),
#checkboxInput("ViewAllSites", "View all sites", FALSE),
fluidRow(align = "center",
sliderInput("slider1",
label = "Drive time (minutes)",
min = 0,
max = 180,
value = 60,
width = "85%")),
img(src="wsdot-logo.png", width = 280),
fluidRow("Last updated on 2019-12-18" , align = "center"),
fluidRow("From: 2019-11-08 - S_V Criteria Prioritization Draft.xlsx" , align = "center")
)
),
server = function(input, output) {
filtered <- reactive({
grantee_df[grantee_df$grantee_origin == input$siteName &
grantee_df$minutes < input$slider1,]
})
filtered_single <- reactive({
grantee_df[grantee_df$grantee_origin == input$siteName,]
})
flitered_single <- reactive({
unique(filtered_single[,c(1:3)],)
})
output$siteSelect <- renderUI({
siteNames <- sort(unique(grantee_df$grantee_origin))
selectInput("siteName", "Grantee", choices = siteNames, selected = siteNames[8])
})
output$MapPlot1 <- renderLeaflet({
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
setView(lng = -120.3103, lat = 47.4235, zoom = 7) %>%
leaflet.extras::addFullscreenControl()
})
MapPlot1_proxy <- leafletProxy("MapPlot1")
observeEvent(c(input$siteName,input$slider1), {
fdata <- filtered()
fdata2 <- fdata %>%
pivot_longer(c("long_origin","long_destination"), names_to = "f2long", values_to = "long") %>%
pivot_longer(c("lat_origin","lat_destination"), names_to = "f2lat", values_to = "lat")
fdata_single <- filtered_single()
if(nrow(fdata)!=0){
maxLong = max(fdata2$long)
maxLat = max(fdata2$lat)
minLong = min(fdata2$long)
minLat = min(fdata2$lat)
}else{
maxLong = -116.915989
maxLat = 49.002494
minLong = -124.763068
minLat = 45.543541
}
if(nrow(fdata)==0){
MapPlot1_proxy %>%
clearMarkers() %>%
clearMarkerClusters() %>%
addCircleMarkers(lng = fdata_single$long_origin,
lat = fdata_single$lat_origin,
radius = 20,
color = "#E69F00",
#label = fdata_single$grantee_origin,
#labelOptions = labelOptions(noHide = T),
popup = paste(fdata_single$grantee_origin, "<br>","<br>",
"Days since last visit:","<br>",
"Admin:", fdata_single$admin.x,"<br>",
"Capital:", fdata_single$capital.x,"<br>",
"Drug & alcohol:", fdata_single$drug.x,"<br>",
"Financial:", fdata_single$financial.x)) %>%
#popup = as.character(fdata_single$grantee_origin)) %>%
fitBounds(minLong,minLat,maxLong,maxLat)
}else{
MapPlot1_proxy %>%
clearMarkers() %>%
clearMarkerClusters() %>%
addCircleMarkers(lng = fdata$long_origin,
lat = fdata$lat_origin,
radius = 20,
color = "#E69F00",
label = fdata$grantee_origin,
labelOptions = labelOptions(noHide = T),
popup = paste(fdata$grantee_origin, "<br>","<br>",
"Days since last visit:","<br>",
"Admin:", fdata$admin.x,"<br>",
"Capital:", fdata$capital.x,"<br>",
"Drug & alcohol:", fdata$drug.x,"<br>",
"Financial:", fdata$financial.x)) %>%
addCircleMarkers(lng = fdata$long_destination,
lat = fdata$lat_destination,
radius = 10,
color = "#56B4E9",
clusterOptions = markerClusterOptions(),
label = fdata$grantee_destination,
labelOptions = labelOptions(noHide = T),
popup = paste(fdata$grantee_destination, "<br>","<br>",
"Travel:","<br>",
"Miles:",round(fdata$miles,1),"<br>",
"Minutes:",fdata$minutes,"<br>","<br>",
"Days since last visit:","<br>",
"Admin:", fdata$admin.y,"<br>",
"Capital:", fdata$capital.y,"<br>",
"Drug & alcohol:", fdata$drug.y,"<br>",
"Financial:", fdata$financial.y)) %>%
fitBounds(minLong,minLat,maxLong,maxLat)
}
})
}
)
# Not run
# output table
#site_visit_travel_time <- grantee_df %>%
# dplyr::filter(minutes<60) %>%
# dplyr::arrange(grantee_origin, minutes) %>%
# dplyr::select(grantee_origin, admin.x, capital.x, drug.x, financial.x,
# grantee_destination, admin.y, capital.y, drug.y, financial.y,
# miles, minutes) %>%
# dplyr::rename(admin_orig = admin.x,
# capital_orig = capital.x,
# drug_orig = drug.x,
# financial_orig = financial.x,
# admin_dest = admin.y,
# capital_dest = capital.y,
# drug_dest = drug.y,
# financial_dest = financial.y)
#
# write.csv(site_visit_travel_time, "site_visit_travel_time.csv", row.names = FALSE)
<file_sep># Site visit pririization and data analysis
# r2 distance calculations between sites
# Packages
library(readr) # sane way of reading files
library(tidyverse) # For all that is good and holy in this world
library(gmapsdistance) # distance calculations, install with devtools::install_github("rodazuero/gmapsdistance")
# Set Working directory to Github folder, change path for your machine
setwd("~/GitHub/site_visits")
# Bring in the file either from r1 or from data, note that if refreshing for new sites, will need to run r1
locations_df <- readr::read_csv("data/locations_df.csv")
# Create a field for lat and long that gmapsdistance can work with
# locations_df$latlong <- paste('"',locations_df$lat,'+',locations_df$lon,'"')
# previous line gives quotes per documentation, but only needed for calling directly
# If calling from a field than use the following
locations_df$latlong <- paste(locations_df$lat,'+',locations_df$lon)
# get rid of spaces in new field
locations_df$latlong <- gsub('\\s+', '', locations_df$latlong)
# Keep just what we want
locations_df <- locations_df %>%
dplyr::select(grantee=Grantee, latlong)
# Get all possible pairs
locations_df <- locations_df %>%
tidyr::unite("granteelatlong1",grantee:latlong) %>%
dplyr::mutate(granteelatlong2 = granteelatlong1) %>%
expand.grid() %>%
dplyr::filter(granteelatlong1 != granteelatlong2) %>%
arrange(granteelatlong1) %>%
tidyr::separate(granteelatlong1,c("grantee1","latlong1"),sep="_") %>%
tidyr::separate(granteelatlong2,c("grantee2","latlong2"),sep="_")
# Tell stupid google about the api key, note, this is the location of mine
api <- readLines("H:/personal/google.api")
# testing with gmapsdistance
TEST_gmapdistance <- gmapsdistance(origin = locations_df$latlong1,
destination = locations_df$latlong2,
combinations = "pairwise",
mode = "driving",
key = api,
shape = "long",
dep_date = "2019-12-24", # a Tuesday
dep_time = "12:00:00")
# Turn it into a data frame and keep just what is useful
TEST_gmapdistance <- as.data.frame(TEST_gmapdistance)
TEST_gmapdistance <- TEST_gmapdistance %>%
dplyr::mutate_if(is.factor, as.character) %>%
dplyr::rename(latlong1 = Time.or) %>%
dplyr::rename(latlong2 = Time.de) %>%
dplyr::rename(seconds = Time.Time) %>% # this will return seconds
dplyr::rename(miles = Distance.Distance) %>% # this will return meters
dplyr::select(latlong1,latlong2,seconds,miles) %>%
dplyr::mutate(miles = miles / 1609.344 )
# Combine OD table and distance table
distances_df <-
dplyr::left_join(locations_df,
TEST_gmapdistance,
by=c("latlong1" = "latlong1",
"latlong2" = "latlong2"))
# remove duplicates
distances_df <- distances_df %>%
dplyr::distinct()
# export the table of grantees and distances
write.csv(distances_df, "data/distances_df.csv", row.names = FALSE)
| 29aa865f48677548daa634ce3b226d9b2bfc61b9 | [
"Markdown",
"R"
] | 7 | Markdown | ptddatateam/site_visits | 14daedbc207ae983d7a039554e3cbcfa46a65254 | 07e5fba28dc52c8d230cacbf20f04a1316714fa1 |
refs/heads/main | <file_sep><?php
$matches = [
partita1=>[
casa => ['torino', 73],
ospite => ['milano',50],
],
partita2=>[
casa => ['genova', 60],
ospite => ['milano',50],
],
partita3=>[
casa => ['napoli', 73],
ospite => ['pisa',50],
],
partita4=>[
casa => ['pisa', 73],
ospite => ['torino',50],
],
partita5=>[
casa => ['catania', 10],
ospite => ['trofarello',150],
],
partita6=>[
casa => ['trofarello', 73],
ospite => ['catania',10],
],
partita7=>[
casa => ['genova', 73],
ospite => ['catania',50],
]
];
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>php-snacks-b1</title>
</head>
<body>
<h1>php-snacks-b1</h1>
<h2>punti partite</h2>
<ul>
<?php
// var_dump($matches);
foreach ($matches as $match) {
$casa = $match['casa'][0];
$ospite = $match['ospite'][0];
$puntiCasa = $match['casa'][1];
$puntiOspite = $match['ospite'][1];
echo "<li>$casa - $ospite | $puntiCasa - $puntiOspite</li>";
}
?>
</ul>
<h2>validazione</h2>
<form class="" action="test.php" method="get">
<h3>NAME</h3>
<input type="text" name="name" value="">
<h3>MAIL</h3>
<input type="text" name="email" value="">
<h3>AGE</h3>
<input type="text" name="age" value=""><br>
<input type="submit">
</form>
<h2>
<?php
$name = $_GET['name'];
$mail = $_GET['email'];
$age = $_GET['age'];
if (strlen($name) > 3 && stripos( $mail , '@') && stripos( $mail , '.') && is_numeric ( $age )) {
echo 'Accesso riuscito';
}else{
echo 'Accesso non riuscito';
};
?>
</h2>
</body>
</html>
| 889737269be584e5431f2888bae39bc6496c1c70 | [
"PHP"
] | 1 | PHP | edoardocollo/php-snacks-b1 | 60d63b4ba2e4fe10293c1042460d9383880f9b64 | 83bf025fa5447f85abedeaefbc221dd6c19d793e |
refs/heads/master | <repo_name>DebraBowen/datasciencecoursera<file_sep>/cachematrix.R
## makCacheMatrix() builds a set of functions and returns the functions in a list
## to the parent environment.
## to run, use the following steps:
## 1. m <- matrix(c(1:4), nrow = 2, ncol = 2)
## 2. matr1 <- makeCacheMatrix(m)
## 3. cacheSolve(matr1)
makeCacheMatrix <- function(x = matrix()) {
## m is the inverse matrix to an original matrix; it is set to NULL in case the original
## matrix changes
m <- NULL
## the set function allows m to be initialized if the matrix (& therefore its inverse) changes
set <- function(y) {
x <<- y
m <<- NULL
}
## get() is used to retrieve the original matrix
get <- function() x
## setmatrix() is used to call the solve function and assign the inverse matrix to m
setmatrix <- function(solve) m <<- solve
## getmatrix() is used to retrieve the cached inverse matrix
getmatrix <- function() m
## the functions created are assigned to names so they can later be accessed using $
list(set = set, get = get,
setmatrix = setmatrix,
getmatrix = getmatrix)
}
## cacheSolve() requires an argument of the object type returned by function makeCacheMatrix()
## in order to retrieve the cached inverse matrix stored in the makeCacheMatrix() object's
## environment
cacheSolve <- function(x, ...) {
## m is the inverse of an original matrix
## function getmatrix(), from the list of functions created in makecacheMatrix() is accessed
m <- x$getmatrix()
## if the inverse matrix has previously been created and cached, it is retrieved and
## a message is printed to the console
## the retrieved inverse matrix is returned to the console
if(!is.null(m)) {
message("getting cached matrix")
return(m)
}
## if the inverse matrix has not yet been cached, the original matrix is retrieved
data <- x$get()
## the inverse is found and stored in m
m <- solve(data, ...)
## function setmatrix() from the makecacheMatrix() object is accessed to cache the matrix
x$setmatrix(m)
## the inverse matrix is printed to the console
m
} | a2687d3d630f2705e4d70c6ffc0428899b2cdd5a | [
"R"
] | 1 | R | DebraBowen/datasciencecoursera | e5da46b91038cbcf042f39b4d8d26c15dab0fbf4 | 5763e2cfe0d36ad868e0efd80edfdc2056c6d7c7 |
refs/heads/master | <file_sep>################################################################################
# Automatically-generated file. Do not edit or delete the file
################################################################################
Computer Controlled_Robo.c
uart.c
<file_sep>#include<avr\io.h>
#include<avr\interrupt.h>
#include <util\delay.h>
#include "uart.h"
// sensor PB0 LEFT, PB1 MIDDLE , PB2 RIGHT
#define Robot PORTC
#define Forward 0x06
#define Backward 0x09
#define Left 0x0a
#define Right 0x05
#define Stop 0x00
unsigned char key;
//unsigned char volatile F_NewKey=0;
void main(void)
{
Robot = 0xff;
UART_Init(9600);
UART_TxString("Computer controlled Robot!\n\r");
DDRC = 0xff; //making port c output
//DDRD = 0x00;// inputs
PORTC = 0xff;
_delay_ms(100);
while(1)
{
key = UART_RxChar();
UART_TxChar(key);
switch(key)
{
case 'w' :Robot = Forward; UART_TxChar(Robot+0x30);_delay_ms(100); Robot = Stop;break;
case 's' :Robot = Backward;_delay_ms(100); Robot = Stop;break;
case 'a' :Robot = Left;_delay_ms(100);UART_TxChar(Robot+0x30); Robot = Stop;break ;
case 'd' :Robot = Right;_delay_ms(100); Robot = Stop;break;
default:Robot = Stop; break;
}
}
}
<file_sep>#include<avr\io.h>
#include<avr\interrupt.h>
#include <util\delay.h>
#include "uart.h"
// sensor PB0 LEFT, PB1 MIDDLE , PB2 RIGHT
#define Forward 0x06
#define Backward 0x09
#define Left 0x0a
#define Right 0x05
#define Stop 0x00
#define mobile PIND
#define Robot PORTC
#define Sensor PORTB
unsigned char key;
unsigned char volatile F_NewKey=0;
volatile unsigned char cnt=0, Prev_Dirn=0,duty=40,new_value,old_value;
ISR (TIMER1_OVF_vect) // Timer1 ISR
{
cnt++; // Increment the cnt value each time the isr is executed
if(cnt > duty)
{
Robot = Stop;
}
else if(cnt < duty)
{
Robot = Prev_Dirn;
}
else if(cnt==100)
{
Robot = Prev_Dirn;
cnt =0;
}
TCNT1H=0xff; // Reload the 16-bit count value
TCNT1L=0x00; // in timer1 count registers
}
void main(void)
{
DDRC = 0xff; //making port c output
DDRD = 0x00;// inputs
DDRB = 0X00;// sensor inputs.
UART_Init(9600);
PORTB = 0X07;
while(1)
{
UART_TxChar((PINB & 0X07)+0x30);
switch(PINB & 0X07)
{
case 0: Prev_Dirn=Robot=Forward; break;
case 1: Prev_Dirn=Robot = Left;_delay_ms(100); break;
case 2: Prev_Dirn=Robot = Backward;_delay_ms(500);Robot = Left;_delay_ms(100); break;
case 3: Prev_Dirn=Robot = Left;_delay_ms(100); break;
case 4: Prev_Dirn=Robot = Right; _delay_ms(100); break;
case 5: Prev_Dirn=Robot = Backward;_delay_ms(500);Robot = Left;_delay_ms(100); break;
case 6: Prev_Dirn=Robot = Right; _delay_ms(100); break;
case 7: Prev_Dirn=Robot = Backward;_delay_ms(500);Robot = Left;_delay_ms(100); break;
default: Robot = Stop; break;
}
}
}
<file_sep>#include<avr\io.h>
#include<avr\interrupt.h>
#include <util\delay.h>
#include "uart.h"
// sensor PB0 LEFT, PB1 MIDDLE , PB2 RIGHT
#define Forward 0x06
#define Backward 0x09
#define Left 0x0a
#define Right 0x05
#define Stop 0x00
#define mobile PIND
#define Robot PORTC
#define Sensor PORTB
volatile unsigned char cnt=0, Prev_Dirn=0,duty=90;
ISR (TIMER1_OVF_vect) // Timer1 ISR
{
cnt++; // Increment the cnt value each time the isr is executed
if(cnt > duty)
{
Robot = Stop;
}
else if(cnt < duty)
{
Robot = Prev_Dirn;
}
else if(cnt==100)
{
Robot = Prev_Dirn;
cnt =0;
}
TCNT1H=0xff; // Reload the 16-bit count value
TCNT1L=0x00; // in timer1 count registers
}
unsigned char key;
unsigned char volatile F_NewKey=0;
void main(void)
{
unsigned char old_value=0, new_value=0;
DDRC = 0xff; //making port c output
DDRD = 0xff;// inputs
DDRB = 0X00;// sensor inputs.
UART_Init(9600);
PORTB = 0X07;
TCNT1H=0xEF; // Load the 16-bit count value
TCNT1L=0x00; // for 1 sec at 7.3728MHz
TCCR1A=0x00;
TCCR1B=0x01; // Timer mode with 1024 prescler
TIMSK1=0x01; // Enable timer1 overflow interrupt(TOIE1)
sei(); // Enable global interrupts by setting global interrupt enable bit in SREG
while(1)
{
new_value = PINB & 0X07;
PORTD = new_value<<4;
if(new_value!=old_value)
{
Robot = Stop;
switch(new_value)
{
case 0: Prev_Dirn= Robot = Stop; break;
case 1: Prev_Dirn= Robot = Right; break;
case 2: Prev_Dirn= Robot = Forward; break;
case 3: Prev_Dirn= Robot = Right; break;
case 4: Prev_Dirn= Robot = Left; break;
case 5: Prev_Dirn= Robot = Forward; break;
case 6: Prev_Dirn= Robot = Left; break;
case 7: Prev_Dirn= Robot = Forward; break;
default: Prev_Dirn= Robot = Stop; break;
}
old_value = new_value;
cnt = 0;
// UART_TxChar(new_value + 0x30);
}
}
}
<file_sep>#include<avr\io.h>
#include<avr\interrupt.h>
#include <util\delay.h>
#include "uart.h"
// sensor PB0 LEFT, PB1 MIDDLE , PB2 RIGHT
#define Forward 0x06
#define Backward 0x09
#define Left 0x0a
#define Right 0x05
#define Stop 0xff
#define mobile PIND
#define Robot PORTC
unsigned char volatile key;
unsigned char volatile F_NewKey=0;
ISR(INT1_vect)
{
F_NewKey = 1;
}
void main(void)
{
//UART_Init();
//aUART_TxString("AVR Robo TEST\n\r");
DDRC = 0xff; //making port c output
DDRD = 0x00;// inputs
PORTC = 0xff;
_delay_ms(100);
EICRA |= (1 << ISC00) | (1 << ISC01); // The rising edge of INTx generates an interrupt request
EIMSK |= (1 << INT1); // Turns on INT1
MCUCR = 0x0c;
SREG = 0X80;
sei(); //global interrupt enable
//key = UART_RxChar();
while(1)
{
if(F_NewKey ==1)
{
key = (mobile&0xf0);
F_NewKey =0;
}
switch(key)
{
case 0x20 :Robot = Forward;break;
case 0x80 :Robot = Backward;break;
case 0x40 :Robot = Left;_delay_ms(5); Robot = 0x00; key=0;break ;
case 0x60 :Robot = Right;_delay_ms(5); Robot = 0x00;key=0;break;
default:Robot = Stop; key=0;; break;
}
}
}
| 2d681f14878cb806462c812b5f6fa87104460eea | [
"C",
"Makefile"
] | 5 | Makefile | ExploreEmbedded/ExploreRobo_Sample-Code | f2b971b732b1384a7c110b1c83b8820bd5823b56 | 5616aeceddc377a7632d838fa6ba3ece2ae72d87 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
set -e
set -x
CONF=$(vagrant ssh-config)
function field {
grep "$1 " <<<"$CONF" | awk '{print $2}' | tr -d '"'
}
exec fab \
--no_agent \
--no-keys \
--disable-known-hosts \
--user="$(field User)" \
--password=<PASSWORD> \
--hosts="$(field HostName)" \
--port="$(field Port)" \
"$@"
<file_sep>#!/usr/bin/env python2.7
"""Skipjack
Usage:
skipjack bootstrap (--hosts=<hosts>|--vagrant) [--key=<file>] <repo>
skipjack provision (--hosts=<hosts>|--vagrant)
"""
import os
import subprocess
from docopt import docopt
def init_fab_args(opts):
if opts["--vagrant"]:
return ["./fab-vagrant"]
else:
return ["fab", "-H", opts["--hosts"]]
def bootstrap_task(opts):
repo = opts["<repo>"]
key_file = opts["--key"] or ""
return "bootstrap:%s,%s" % (repo, key_file)
def main(opts):
print(opts)
fab_args = init_fab_args(opts)
if opts["bootstrap"]:
fab_args.append(bootstrap_task(opts))
elif opts["provision"]:
fab_args.append("provision")
subprocess.check_call(fab_args, close_fds=True)
if __name__ == "__main__":
main(docopt(__doc__))
<file_sep>#!/usr/bin/env bash
set -e
KEY_FILE="secret_key"
SECRETS_DIR="config"
if [ ! -f "$KEY_FILE" ]; then
echo "No $KEY_FILE; skipping decryption step."
exit 0
fi
if [ ! -d "$SECRETS_DIR" ]; then
echo "No $SECRETS_DIR; skipping decryption step."
exit 0
fi
for i in $(find "$SECRETS_DIR" -name '*.bfe'); do
cat secret_key | bcrypt "$i" 2>/dev/nul
done
<file_sep>#!/usr/bin/env bash
set -e
BRANCH_PREFIX="refs/heads/"
function get_branch_name {
FULL_NAME="$1"
if [ "${FULL_NAME:0:${#BRANCH_PREFIX}}" = "$BRANCH_PREFIX" ]; then
echo "${FULL_NAME:${#BRANCH_PREFIX}}"
else
echo "Not a normal branch: $FULL_NAME!" 1>&2
exit 1
fi
}
HEAD_NAME="$(git rev-parse --symbolic-full-name HEAD)"
BRANCH_NAME="$(get_branch_name "$HEAD_NAME")"
REMOTE_NAME="$(git config --get "branch.$BRANCH_NAME.remote" || echo .)"
if [ "$REMOTE_NAME" = "." ]; then
echo "Branch $BRANCH_NAME doesn't have a real remote!" 1>&2
exit 1
fi
REMOTE_MERGE="$(git config --get "branch.$BRANCH_NAME.merge" || true)"
if [ -z "$REMOTE_MERGE" ]; then
echo "Branch $BRANCH_NAME doesn't have a remote merge spec!" 1>&2
exit 1
fi
REMOTE_BRANCH_NAME="$(get_branch_name "$REMOTE_MERGE")"
HEAD_COMMIT="$(git rev-parse HEAD)"
REMOTE_FULL_NAME="refs/remotes/$REMOTE_NAME/$REMOTE_BRANCH_NAME"
if git rev-list "$REMOTE_FULL_NAME" | grep -qF "$HEAD_COMMIT"; then
echo "Remote is up-to-date." 1>&2
else
read -p "Remote is out-of-date. Push? [y] " SHOULD_PUSH
if grep -qi '^y' <<<"$SHOULD_PUSH"; then
git push "$REMOTE_NAME" "$HEAD_NAME:$REMOTE_MERGE"
else
echo "Not pushing." 1>&2
fi
fi
echo -n "$REMOTE_BRANCH_NAME"
<file_sep>#!/usr/bin/env bash
exec 2>&1
cd /root/skipjack
exec sleep 60
<file_sep>#!/usr/bin/env bash
set -e
source ENV/bin/activate
pip -q install -r requirements.prod.txt
if [ -d config ]; then
./git-obliterate.sh config
fi
./decrypt.sh
SKIPJACK="$PWD"
cd config
puppet apply $* \
--modulepath "modules:$SKIPJACK/modules" \
--confdir . \
"$SKIPJACK/manifests/site.pp"
<file_sep>#!/usr/bin/env bash
set -e
set -x
if [ -z "$1" ]; then
exit 1
fi
cd "$1"
if [ -n "$2" ]; then
REMOTE_BRANCH_NAME="$2"
else
REMOTE_BRANCH_NAME="master"
fi
git fetch
git reset --hard "origin/$REMOTE_BRANCH_NAME"
<file_sep>#!/usr/bin/env bash
set -e
sleep 1
GITBLIT_PATH="<%= root %>"
GITBLIT_BASE_FOLDER="<%= data %>"
GITBLIT_USER="<%= user %>"
. /lib/lsb/init-functions
cd "$GITBLIT_PATH"
exec sudo -u "$GITBLIT_USER" -- \
java -server -Xmx1024M -Djava.awt.headless=true \
-jar "$GITBLIT_PATH/gitblit.jar" \
--baseFolder "$GITBLIT_BASE_FOLDER"
<file_sep>#!/usr/bin/env python2.7
import os.path
import tempfile
import shutil
from subprocess import check_output, Popen
from fabric.api import *
env.user = 'root'
fab_dir = os.path.dirname(env.real_fabfile)
CLONE_ADDRESS = "127.0.0.1"
CLONE_PORT = 8149
CLONE_DIR = "skipjack-config.git"
KEY = None
def get_key(path):
global KEY
if path == "":
KEY = prompt("Decryption key?").strip()
else:
with open(path, "r") as key_file:
KEY = key_file.read().strip()
def put_key():
with shell_env(KEY=KEY):
run("""cat - <<<"$KEY" >secret_key""")
run("chmod 600 secret_key")
def clone_local_config(repo):
git_daemon = Popen([
"git", "daemon",
"--strict-paths", "--export-all", "--base-path=" + repo,
"--listen=127.0.0.1", "--port=" + CLONE_PORT, repo])
try:
with remote_tunnel(CLONE_PORT, remote_bind_address=CLONE_ADDRESS):
run("git clone git://%s:%s/ %s" %
(CLONE_ADDRESS, CLONE_PORT, CLONE_DIR))
return CLONE_DIR
finally:
git_daemon.terminate()
def pick_source():
return check_output(["./pick-source.sh"])
def bootstrap(repo, key_file):
get_key(key_file)
if repo.startswith("/"):
repo = clone_local_config(repo)
run('apt-get install -q -y ruby git python-pip bcrypt')
run('pip -q install virtualenv')
run('gem install --no-ri --no-rdoc puppet')
branch = pick_source()
run("git clone -b '%s' git://github.com/fishsilo/skipjack.git" % branch)
with cd('skipjack'):
put_key()
run('virtualenv ENV')
run('git clone %s config' % repo)
provision(fresh=True)
def provision(fresh=False):
with cd('skipjack'):
if not fresh:
run("./git-obliterate.sh . '%s'" % pick_source())
run('./run.sh')
<file_sep>Fabric==1.6.0
paramiko==1.10.1
pycrypto==2.6
pycurl==7.19.0
wsgiref==0.1.2
PyYAML==3.10
docopt==0.6.1
jinja2==2.6
| b79a562ce86a8a4f3c940702598c91f2e0a3a64c | [
"Python",
"Text",
"Shell"
] | 10 | Shell | fishsilo/skipjack | 52c4a496e86975e599930dceb7ef94abf7704a57 | b0a932addb7dabde4cec9eb0852ab47da3b45a09 |
refs/heads/master | <file_sep>#pragma once
#include "defines.h"
#include "material.h"
#include "light.h"
//游戏渲染接口
class CRenderInterface
{
public:
CRenderInterface() :m_screenWidth(0),
m_screenHeight(0),
m_near(0),
m_far(0) {}
virtual ~CRenderInterface() {}
virtual bool Initialize(int w, int h,WinHWND mainWin, bool fullScreen) = 0;
virtual void OneTimeInit() = 0;
virtual void CalculateProjMatrix(float fov, float n, float f) = 0;
virtual void CalculateOrthoMatrix(float n, float f) = 0;
//清屏颜色
virtual void SetClearCol(float r, float g, float b) = 0;
//开始渲染
virtual void StartRender(bool bColor, bool bDepth, bool bStencil) = 0;
//结束渲染
virtual void EndRender() = 0;
//清除渲染缓存-》工作到一半又不想做了
virtual void ClearBuffers(bool bColor,bool bDepth,bool bStencil) = 0;
//参数一:顶点类型
virtual int CreateStaticBuffer(VertexType , PrimType, int totalVerts,int totalIndeces,int stride,void **data ,unsigned int *indices,int *staticId) = 0;
//释放资源
virtual void Shutdown() = 0;
//渲染函数
virtual int Render(int staticId) = 0;
//设置材质
virtual void SetMaterial(stMaterial *mat) = 0;
//设置光照
virtual void SetLight(stLight *light, int index) = 0;
//把某个光关掉
virtual void DisabledLight(int index) = 0;
//纹理//
//设置透明的
virtual void SetTranspency(RenderState state, TransState src, TransState dst) =0;
//添加纹理
virtual int AddTexture2D(char *file, int *texId) = 0;
virtual void SetTextureFilter(int index, int filter, int val) = 0;
//设置多重纹理
virtual void SetMultiTexture() = 0;
//应用纹理
virtual void ApplyTexture(int index,int texId) = 0;
//保存屏幕截图
virtual void SaveScreenShot(char *file) = 0;
virtual void EnablePointerSprites(float size, float min, float a, float b, float c) = 0;
virtual void DisablePointSprites() = 0;
protected:
int m_screenWidth; //屏幕窗口的宽度
int m_screenHeight; //屏幕窗口的高度
bool m_fullScreen; //是否全屏
WinHWND m_mainHandle;
float m_near;
float m_far;
};
<file_sep>#include "D3DRenderer.h"
inline unsigned long FtoDW(float v)
{
return *((unsigned long *)&v);
}
bool CreateD3DRenderer(CRenderInterface **pObj)
{
if (!*pObj)*pObj = new CD3DRenderer();
else
return false;
return true;
}
unsigned long CreateD3DFVF(int flags)
{
unsigned long fvf = 0;
return fvf;
}
CD3DRenderer::CD3DRenderer()
{
m_Direct3D = NULL;
m_Device = NULL;
m_renderingScene = false;
m_numStaticBuffers = 0;
m_activeStaticBuffer = UGP_INVALID;
m_staticBufferList = NULL;
m_textureList = NULL;
m_numTextures = 0;
}
CD3DRenderer::~CD3DRenderer()
{
Shutdown();
}
bool CD3DRenderer::Initialize(int w, int h, WinHWND mainWin, bool fullScreen)
{
Shutdown();
m_mainHandle = mainWin;
if (!m_mainHandle)return false;
m_fullScreen = fullScreen;
D3DDISPLAYMODE mode;
D3DCAPS9 caps;
D3DPRESENT_PARAMETERS Params;
ZeroMemory(&Params, sizeof(Params));
m_Direct3D = Direct3DCreate9(D3D_SDK_VERSION);
if (!m_Direct3D) return false;
if (FAILED(m_Direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode)))return false;
if (FAILED(m_Direct3D->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps)))return false;
DWORD processing = 0;
if (caps.VertexProcessingCaps != 0)
processing = D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE;
else
processing = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
if (m_fullScreen)
{
Params.FullScreen_RefreshRateInHz = mode.RefreshRate;
Params.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
}
else
{
Params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
}
Params.Windowed = !m_fullScreen;
Params.BackBufferWidth = w;
Params.BackBufferHeight = h;
Params.hDeviceWindow = m_mainHandle;
Params.SwapEffect = D3DSWAPEFFECT_DISCARD;
Params.BackBufferFormat = mode.Format;
Params.BackBufferCount = 1;
Params.EnableAutoDepthStencil = TRUE;
Params.AutoDepthStencilFormat = D3DFMT_D16;
m_screenWidth = w;
m_screenHeight = h;
if (FAILED(m_Direct3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_mainHandle, processing, &Params, &m_Device))) return false;
if (m_Device == NULL) return false;
OneTimeInit();
return true;
}
void CD3DRenderer::OneTimeInit()
{
if (m_Device)return;
m_Device->SetRenderState(D3DRS_LIGHTING,FALSE);
m_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
CalculateProjMatrix(D3DX_PI/4,0.1f,1000);
}
void CD3DRenderer::CalculateProjMatrix(float fov, float n, float f)
{
if (!m_Device)return;
D3DXMATRIX projection;
D3DXMatrixPerspectiveFovLH(&projection, fov, (float)m_screenWidth / (float)m_screenHeight, n, f);
m_Device->SetTransform(D3DTS_PROJECTION, &projection);
}
void CD3DRenderer::CalculateOrthoMatrix(float n, float f)
{
if (!m_Device)return;
D3DXMATRIX ortho;
D3DXMatrixOrthoLH(&ortho, (float)m_screenWidth, (float)m_screenHeight, n, f);
m_Device->SetTransform(D3DTS_PROJECTION, &ortho);
}
//清屏颜色
void CD3DRenderer::SetClearCol(float r, float g, float b)
{
m_Color = D3DCOLOR_COLORVALUE(r, g, b, 1.0f);
}
//开始渲染
void CD3DRenderer::StartRender(bool bColor, bool bDepth, bool bStencil)
{
if (!m_Device)return;
unsigned int buffers = 0;
if (bColor)buffers |= D3DCLEAR_TARGET;
if (bDepth)buffers |= D3DCLEAR_ZBUFFER;
if (bStencil)buffers |= D3DCLEAR_STENCIL;
if (FAILED(m_Device->Clear(0, NULL, buffers, m_Color, 1, 0)))
return;
if (FAILED(m_Device->BeginScene()))
return;
m_renderingScene = true; //开始渲染
}
//结束渲染
void CD3DRenderer::EndRender()
{
if (!m_Device)return;
m_Device->EndScene();
m_Device->Present(NULL, NULL, NULL, NULL); //将渲染的图形显示出来
m_renderingScene = false; //渲染结束
}
void CD3DRenderer::ClearBuffers(bool bColor, bool bDepth, bool bStencil)
{
if (!m_Device)return;
unsigned int buffers = 0;
if (bColor)buffers |= D3DCLEAR_TARGET;
if (bDepth)buffers |= D3DCLEAR_ZBUFFER;
if (bStencil)buffers |= D3DCLEAR_STENCIL;
if(m_renderingScene) m_Device->EndScene();
if (FAILED(m_Device->Clear(0, NULL, buffers, m_Color, 1, 0)))
return;
if (m_renderingScene)
if (FAILED(m_Device->BeginScene())) //开始渲染
return;
}
//创建静态缓存
int CD3DRenderer::CreateStaticBuffer(VertexType vType, PrimType primType,
int totalVerts, int totalIndices, int stride, void **data, unsigned int *indices, int *staticId)
{
void *ptr;
int index = m_numStaticBuffers;
if (!m_staticBufferList)
{
m_staticBufferList = new stD3DStaticBuffer[1];
if (!m_staticBufferList)return UGP_FAIL;
}
else
{
stD3DStaticBuffer *temp;
temp = new stD3DStaticBuffer[m_numStaticBuffers + 1];
memcpy(temp, m_staticBufferList, sizeof(stD3DStaticBuffer)*m_numStaticBuffers);
delete[] m_staticBufferList;
m_staticBufferList = temp;
}
m_staticBufferList[index].numVerts = totalVerts;
m_staticBufferList[index].numIndices = totalIndices;
m_staticBufferList[index].primType = primType;
m_staticBufferList[index].stride = stride;
m_staticBufferList[index].fvf = CreateD3DFVF(vType);
//如果有顶点索引 就创建顶点缓存
if (totalIndices > 0)
{
if (FAILED(m_Device->CreateIndexBuffer(sizeof(unsigned int)*totalIndices, D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_staticBufferList[index].ibPtr, NULL)))
{
return UGP_FAIL;
}
if (FAILED(m_staticBufferList[index].ibPtr->Lock(0, 0, (void**)&ptr, 0)))
return UGP_FAIL;
memcpy(ptr, indices, sizeof(unsigned int)*totalIndices);
m_staticBufferList[index].ibPtr->Unlock();
}
else
{
m_staticBufferList[index].ibPtr = NULL;
}
if (FAILED(m_Device->CreateVertexBuffer(totalVerts*stride, D3DUSAGE_WRITEONLY, m_staticBufferList[index].fvf,
D3DPOOL_DEFAULT, &m_staticBufferList[index].vbPtr, NULL)))
return UGP_FAIL;
if (FAILED(m_staticBufferList[index].vbPtr->Lock(0, 0, (void**)&ptr, 0)))
return UGP_FAIL;
memcpy(ptr, data, totalVerts*stride);
m_staticBufferList[index].vbPtr->Unlock();
*staticId = m_numStaticBuffers;
m_numStaticBuffers++;
return UGP_OK;
}
void CD3DRenderer::Shutdown()
{
for (int s = 0; s < m_numStaticBuffers; s++)
{
if (m_staticBufferList[s].vbPtr)
{
m_staticBufferList[s].vbPtr->Release();
m_staticBufferList[s].vbPtr = NULL;
}
if (m_staticBufferList[s].ibPtr)
{
m_staticBufferList[s].ibPtr->Release();
m_staticBufferList[s].ibPtr = NULL;
}
}
m_numStaticBuffers = 0;
if (m_staticBufferList)delete[] m_staticBufferList;
m_staticBufferList = NULL;
for (unsigned int s = 0; s < m_numTextures; s++)
{
if (m_textureList[s].fileName)
{
delete[] m_textureList[s].fileName;
m_textureList[s].fileName = NULL;
}
if (m_textureList[s].image)
{
m_textureList[s].image->Release();
m_textureList[s].image = NULL;
}
}
m_numTextures = 0;
if (m_textureList)delete[] m_textureList;
m_textureList = NULL;
if (m_Device)m_Device->Release();
if (m_Direct3D)m_Direct3D->Release();
m_Device = NULL;
m_Direct3D = NULL;
}
int CD3DRenderer::Render(int staticId)
{
if (staticId >= m_numStaticBuffers) return UGP_FAIL;
if (m_activeStaticBuffer != staticId)
{
if(m_staticBufferList[staticId].ibPtr != NULL)
m_Device->SetIndices(m_staticBufferList[staticId].ibPtr);
m_Device->SetStreamSource(0,m_staticBufferList[staticId].vbPtr,0,m_staticBufferList[staticId].stride);
m_Device->SetFVF(m_staticBufferList[staticId].fvf);
m_activeStaticBuffer = staticId;
}
if (m_staticBufferList[staticId].ibPtr != NULL)
{
//索引缓存画法
switch (m_staticBufferList[staticId].primType)
{
case POINT_LIST:
if(FAILED(m_Device->DrawPrimitive(D3DPT_POINTLIST,0,m_staticBufferList[staticId].numVerts)))
return UGP_FAIL;
break;
case TRIANGLE_LIST:
if (FAILED(m_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_staticBufferList[staticId].numVerts / 3, 0, m_staticBufferList[staticId].numIndices)))
return UGP_FAIL;
break;
case TRIANGLE_STRIP:
if (FAILED(m_Device->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP, 0, 0, m_staticBufferList[staticId].numVerts / 2, 0, m_staticBufferList[staticId].numIndices)))
return UGP_FAIL;
break;
case TRIANGLE_FAN:
if (FAILED(m_Device->DrawIndexedPrimitive(D3DPT_TRIANGLEFAN, 0, 0, m_staticBufferList[staticId].numVerts / 3, 0, m_staticBufferList[staticId].numIndices)))
return UGP_FAIL;
break;
case LINE_LIST:
if (FAILED(m_Device->DrawIndexedPrimitive(D3DPT_LINELIST, 0, 0, m_staticBufferList[staticId].numVerts / 3, 0, m_staticBufferList[staticId].numIndices)))
return UGP_FAIL;
break;
case LINE_STRIP:
if (FAILED(m_Device->DrawIndexedPrimitive(D3DPT_LINESTRIP, 0, 0, m_staticBufferList[staticId].numVerts / 3, 0, m_staticBufferList[staticId].numIndices)))
return UGP_FAIL;
break;
default:
return UGP_FAIL;
}
//m_Device->DrawIndexedPrimitive();
}
else
{
//顶点缓存画法
switch (m_staticBufferList[staticId].primType)
{
case POINT_LIST:
if (FAILED(m_Device->DrawPrimitive(D3DPT_POINTLIST, 0, m_staticBufferList[staticId].numVerts)))
return UGP_FAIL;
break;
case TRIANGLE_LIST:
if (FAILED(m_Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, (int)(m_staticBufferList[staticId].numVerts / 3))))
return UGP_FAIL;
break;
case TRIANGLE_STRIP:
if (FAILED(m_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, (int)(m_staticBufferList[staticId].numVerts / 2))))
return UGP_FAIL;
break;
case TRIANGLE_FAN:
if (FAILED(m_Device->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, (int)(m_staticBufferList[staticId].numVerts / 2))))
return UGP_FAIL;
break;
case LINE_LIST:
if (FAILED(m_Device->DrawPrimitive(D3DPT_LINELIST, 0, (int)(m_staticBufferList[staticId].numVerts / 2))))
return UGP_FAIL;
break;
case LINE_STRIP:
if (FAILED(m_Device->DrawPrimitive(D3DPT_LINESTRIP, 0, (int)(m_staticBufferList[staticId].numVerts / 2))))
return UGP_FAIL;
break;
default:
return UGP_FAIL;
}
}
return UGP_OK;
}
//设置材质
void CD3DRenderer::SetMaterial(stMaterial *mat)
{
if (!mat || !m_Device) return;
D3DMATERIAL9 m =
{
mat->diffuseR,
mat->diffuseG,
mat->diffuseB,
mat->diffuseA,
mat->ambientR,
mat->ambientG,
mat->ambientB,
mat->ambientA,
mat->specularR,
mat->specularG,
mat->specularB,
mat->specularA,
mat->emissiveR,
mat->emissiveG,
mat->emissiveB,
mat->emissiveA,
mat->power
};
m_Device->SetMaterial(&m);
}
//设置光照
void CD3DRenderer::SetLight(stLight *light, int index)
{
if (!light || !m_Device || index < 0)return;
D3DLIGHT9 l;
l.Ambient.a = light->ambientA;
l.Ambient.r = light->ambientR;
l.Ambient.g = light->ambientG;
l.Ambient.b = light->ambientB;
l.Attenuation0 = light->attenuation0;
l.Attenuation1 = light->attenuation1;
l.Attenuation2 = light->attenuation2;
l.Diffuse.a = light->diffuseA;
l.Diffuse.r = light->diffuseR;
l.Diffuse.g = light->diffuseG;
l.Diffuse.b = light->diffuseB;
l.Direction.x = light->dirX;
l.Direction.y = light->dirY;
l.Direction.z = light->dirZ;
l.Falloff = light->falloff;
l.Phi = light->phi;
l.Position.x = light->posX;
l.Position.y = light->posY;
l.Position.z = light->posZ;
l.Range = light->range;
l.Specular.a = light->specularA;
l.Specular.r = light->specularR;
l.Specular.g = light->specularG;
l.Specular.b = light->specularB;
l.Theta = light->theta;
if (light->type == LIGHT_POINT) l.Type = D3DLIGHT_POINT;
else if (light->type == LIGHT_SPOT)l.Type = D3DLIGHT_SPOT;
else l.Type = D3DLIGHT_DIRECTIONAL;
m_Device->SetLight(index, &l);
m_Device->LightEnable(index,TRUE);
}
//把某个光关掉
void CD3DRenderer::DisabledLight(int index)
{
m_Device->LightEnable(index, FALSE);
}
//纹理处理//
//设置透明的
void CD3DRenderer::SetTranspency(RenderState state, TransState src, TransState dst)
{
if (!m_Device)return;
if (state == TRANSPARENCY_NONE)
{
m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
return;
}
if (state == TRANSPARENCY_ENABLE)
{
m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,true);
switch (src)
{
case TRANS_ZERO:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
break;
case TRANS_ONE:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
break;
case TRANS_SRCCOLOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);
break;
case TRANS_INVSRCOLOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVSRCCOLOR);
break;
case TRANS_SRCALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
break;
case TRANS_INVSRCALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVSRCALPHA);
break;
case TRANS_DSTALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_DESTALPHA);
break;
case TRANS_INVDSTALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVDESTALPHA);
break;
case TRANS_DSTCOLOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);
break;
case TRANS_INVDSTCOLOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVDESTCOLOR);
break;
case TRANS_SRCALPHASAT:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHASAT);
break;
case TRANS_BOTHSRCALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_BOTHSRCALPHA);
break;
case TRANS_INVBOTHSRCALPHA:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_BOTHINVSRCALPHA);
break;
case TRANS_BLENDFACTOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_BLENDFACTOR);
break;
case TRANS_INVBLENDFACTOR:
m_Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_INVBLENDFACTOR);
break;
default:
m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
return;
break;
}
switch (dst)
{
case TRANS_ZERO:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);
break;
case TRANS_ONE:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
break;
case TRANS_SRCCOLOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR);
break;
case TRANS_INVSRCOLOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
break;
case TRANS_SRCALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCALPHA);
break;
case TRANS_INVSRCALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
break;
case TRANS_DSTALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_DESTALPHA);
break;
case TRANS_INVDSTALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVDESTALPHA);
break;
case TRANS_DSTCOLOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_DESTCOLOR);
break;
case TRANS_INVDSTCOLOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVDESTCOLOR);
break;
case TRANS_SRCALPHASAT:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCALPHASAT);
break;
case TRANS_BOTHSRCALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_BOTHSRCALPHA);
break;
case TRANS_INVBOTHSRCALPHA:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_BOTHINVSRCALPHA);
break;
case TRANS_BLENDFACTOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_BLENDFACTOR);
break;
case TRANS_INVBLENDFACTOR:
m_Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVBLENDFACTOR);
break;
default:
m_Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
return;
break;
}
}
}
//添加纹理
int CD3DRenderer::AddTexture2D(char *file, int *texId)
{
if (!file || !m_Device)return UGP_FAIL;
int len = strlen(file);
if (!len)return UGP_FAIL;
int index = m_numTextures;
if (!m_textureList)
{
m_textureList = new stD3DTexture[1];
if (!m_textureList)return UGP_FAIL;
}
else
{
stD3DTexture *temp;
temp = new stD3DTexture[m_numTextures + 1];
memcpy(temp,m_textureList,sizeof(stD3DTexture)*m_numTextures);
delete[] m_textureList;
m_textureList = temp;
}
m_textureList[index].fileName = new char[len];
memcpy(m_textureList[index].fileName,file,len);
D3DCOLOR colorkey = 0<KEY>;
D3DXIMAGE_INFO info;
if (D3DXCreateTextureFromFileEx(m_Device, file, 0, 0, 0, 0,
D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT,
D3DX_DEFAULT, colorkey, &info, NULL, &m_textureList[index].image) != D3D_OK)
return false;
m_textureList[index].width = info.Width;
m_textureList[index].heigh = info.Height;
*texId = m_numTextures;
m_numTextures++;
return UGP_OK;
}
//纹理过滤器
void CD3DRenderer::SetTextureFilter(int index, int filter, int val)
{
if (!m_Device || index < 0)return;
//采样器
D3DSAMPLERSTATETYPE fil = D3DSAMP_MINFILTER;
int v = D3DTEXF_POINT; //设置成点过滤器
if (filter == MIN_FILTER) fil = D3DSAMP_MINFILTER;
if (filter == MAG_FILTER) fil = D3DSAMP_MAGFILTER;
if (filter == MIP_FILTER) fil = D3DSAMP_MIPFILTER;
if (val == POINT_TYPE) v = D3DTEXF_POINT;
if (val == LINEAR_TYPE) v = D3DTEXF_LINEAR;
if (val == ANISOTROPIC_TYPE) v = D3DTEXF_ANISOTROPIC;
m_Device->SetSamplerState(index, fil, v);
}
//设置多重纹理
void CD3DRenderer::SetMultiTexture()
{
if (!m_Device)return;
m_Device->SetTextureStageState(0,D3DTSS_TEXCOORDINDEX,0);
m_Device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_MODULATE);
m_Device->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_TEXTURE);
m_Device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
m_Device->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1);
m_Device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
m_Device->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE);
m_Device->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
}
//应用纹理
void CD3DRenderer::ApplyTexture(int index, int texId)
{
if (!m_Device)return;
if (index < 0 || texId < 0)
m_Device->SetTexture(0, NULL);
else
m_Device->SetTexture(index,m_textureList[texId].image);
}
//保存屏幕截图
void CD3DRenderer::SaveScreenShot(char *file)
{
if (!file)return;
LPDIRECT3DSURFACE9 surface = NULL;
D3DDISPLAYMODE disp;
m_Device->GetDisplayMode(0, &disp);
m_Device->CreateOffscreenPlainSurface(disp.Width, disp.Height,
D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &surface, NULL);
m_Device->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&surface);
D3DXSaveSurfaceToFile(file, D3DXIFF_JPG, surface, NULL, NULL);
if (surface != NULL)surface->Release();
surface = NULL;
}
void CD3DRenderer::EnablePointerSprites(float size, float min, float a, float b, float c)
{
if (!m_Device)return;
m_Device->SetRenderState(D3DRS_POINTSPRITEENABLE,TRUE);
m_Device->SetRenderState(D3DRS_POINTSCALEENABLE,TRUE);
m_Device->SetRenderState(D3DRS_POINTSIZE, FtoDW(size));
m_Device->SetRenderState(D3DRS_POINTSIZE_MIN,FtoDW(min));
m_Device->SetRenderState(D3DRS_POINTSCALE_A,FtoDW(a));
m_Device->SetRenderState(D3DRS_POINTSCALE_B, FtoDW(b));
m_Device->SetRenderState(D3DRS_POINTSCALE_C, FtoDW(c));
}
void CD3DRenderer::DisablePointSprites()
{
m_Device->SetRenderState(D3DRS_POINTSPRITEENABLE,FALSE);
m_Device->SetRenderState(D3DRS_POINTSCALEENABLE,FALSE);
}<file_sep>#ifndef _UGP_MAIN_H_
#define _UGP_MAIN_H_
#include "../StrandedEngine/engine.h"
#pragma comment(lib,"../Debug/StrandedEngine.lib")
#define WINDOW_CLASS "StrandedGame"
#define WINDOW_TITLE "Stranded"
#define WIN_WIDTH 800
#define WIN_HEIGHT 600
#define FULLSCREENN 0
//初始化游戏引擎
bool InitializeEngine();
//释放游戏引擎
void ShutdownEngine();
//初始化游戏
bool GameInitialize();
//游戏循环处理
void GameLoop();
//释放游戏资源
void GameShutdown();
#endif //_UGP_MAIN_H_<file_sep>#include "main.h"
HWND g_hwnd;
CRenderInterface *g_Render = NULL;
//消息处理函数
//参数1:窗口句柄
//参数2:消息
//参数3:消息参数
//参数4:消息参数
LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
//处理你想要处理的消息
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
case WM_KEYUP:
if (wParam = VK_ESCAPE)
{
PostQuitMessage(0);
}
break;
default:
break;
}
//其他消息 可以转给window去处理
return DefWindowProc(hWnd, msg, wParam, lParam);
}
//HINSTANCE : 应用程序句柄
//HWND : 窗口句柄
//WinMain函数时系统提供给用户Windows应用程序入口点
//参数1(:HINSTANCE) : 是当前应用长须实例的Handle
//参数2(HINSTANCE) : 是应用程序上一个实例的Handle.(MSDN:如果你想要知道程序是否有另一个实例,
// 建议使用Mutex来实现,用Mutex可以实现只运行一个实例)
//参数3(LPTSTR) : 字符串,是命令行参数
//参数4(int) : int型,指明windows应该怎么实现,windows定义了一系列的宏来帮助记忆,以SW开头,
// 如:SW_SHOW(返回值是一个int型)
int WINAPI WinMain(HINSTANCE h,
HINSTANCE p,
LPTSTR cmd,
int show)
{
//属于一个窗台类
WNDCLASSEX wc =
{
sizeof(WNDCLASSEX),
CS_CLASSDC,
MsgProc,
0,
0,
h,
NULL,
NULL,
NULL,
NULL,
WINDOW_CLASS,
NULL
};
//注册窗口
RegisterClassEx(&wc);
if (FULLSCREENN)
{
g_hwnd = CreateWindowEx(NULL, WINDOW_CLASS, WINDOW_TITLE,
WS_POPUP | WS_SYSMENU | WS_VISIBLE,
NULL, NULL, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, h, NULL);
}
else
{
g_hwnd = CreateWindowEx(NULL, WINDOW_CLASS, WINDOW_TITLE,
WS_OVERLAPPEDWINDOW|WS_VISIBLE,
NULL, NULL, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, h, NULL);
}
if (g_hwnd)
{
//该功能设置指定窗口的显示状态
ShowWindow(g_hwnd, SW_SHOWDEFAULT);
//立即刷新窗口
UpdateWindow(g_hwnd);
}
//初始化游戏引擎
if (InitializeEngine())
{
//初始化游戏
if (GameInitialize())
{
//Windows程序中,消息是由MSG结构体来表示的
MSG msg;
//对结构体对象进行初始化或清零
ZeroMemory(&msg, sizeof(msg));
//设置鼠标的位置
SetCursorPos(0,0);
//循环访问消息并处理
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
GameLoop();
}
}
}
}
GameShutdown(); //关闭游戏
ShutdownEngine(); //关闭游戏引擎
//注销一个窗口类
//参数1:它指定窗口类的名称。
//参数2:句柄的模块的创建类的实例
UnregisterClass(WINDOW_CLASS, h);
}
//初始化游戏引擎
bool InitializeEngine()
{
//创建D3D的渲染器(如何创建失败直接返回)
if(!CreateD3DRenderer(&g_Render))return false;
if (!g_Render->Initialize(WIN_WIDTH, WIN_HEIGHT, g_hwnd, FULLSCREENN)) return false;
g_Render->SetClearCol(0,0,0);
return true;
}
//释放游戏引擎
void ShutdownEngine()
{
if (g_Render)
{
g_Render->Shutdown();
delete g_Render;
g_Render = NULL;
}
}
//初始化游戏
bool GameInitialize()
{
return true;
}
//游戏循环处理
void GameLoop()
{
if (!g_Render)return;
g_Render->StartRender(1, 1,0); //开始渲染
//g_Render->ClearBuffers();
g_Render->EndRender(); //结束渲染
}
//释放游戏资源
void GameShutdown()
{
}
<file_sep>#pragma once
#include <Windows.h>
#define UGP_INVALID -1
#define UGP_OK 1
#define UGP_FAIL 0
#define LIGHT_POINT 1
#define LIGHT_DIRECTIONAL 2
#define LIGHT_SPOT 3
#define WinHWND HWND
typedef long VertexType;
enum PrimType
{
NULL_TYPE,
POINT_LIST,
TRIANGLE_LIST,
TRIANGLE_STRIP,
TRIANGLE_FAN,
LINE_LIST,
LINE_STRIP
};
//渲染状态
enum RenderState
{
CULL_NONE,
CULL_CW,
CULL_CCW,
DEPTH_NONE,
DEPTH_READONLY,
DEPTH_READWRITE,
SHADE_POINTS,
SHADE_SOLIDTRI,
SHADE_WIRETR,
SHADE_WIREPOLY,
TRANSPARENCY_NONE,
TRANSPARENCY_ENABLE
};
//透明度
enum TransState
{
TRANS_ZERO = 1,
TRANS_ONE,
TRANS_SRCCOLOR,
TRANS_INVSRCOLOR,
TRANS_SRCALPHA,
TRANS_INVSRCALPHA,
TRANS_DSTALPHA,
TRANS_INVDSTALPHA,
TRANS_DSTCOLOR,
TRANS_INVDSTCOLOR,
TRANS_SRCALPHASAT,
TRANS_BOTHSRCALPHA,
TRANS_INVBOTHSRCALPHA,
TRANS_BLENDFACTOR,
TRANS_INVBLENDFACTOR,
};
//纹理
enum TextureState
{
MIN_FILTER,
MAG_FILTER,
MIP_FILTER,
};
//纹理过滤器的过滤状态
enum FilterType
{
POINT_TYPE,
LINEAR_TYPE,
ANISOTROPIC_TYPE
};
<file_sep>#pragma once
#include "RenderInterface.h"
#include "D3DRenderer.h"
<file_sep>#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include "RenderInterface.h"
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
//D3D 缓存结构
struct stD3DStaticBuffer
{
stD3DStaticBuffer() :vbPtr(0), ibPtr(0), numVerts(0),
numIndices(0), stride(0), fvf(0), primType(NULL_TYPE) {}
LPDIRECT3DVERTEXBUFFER9 vbPtr;
LPDIRECT3DINDEXBUFFER9 ibPtr;
int numVerts;
int numIndices;
int stride;
unsigned long fvf;
PrimType primType;
};
//纹理结构
struct stD3DTexture
{
char *fileName;
int width, heigh;
LPDIRECT3DTEXTURE9 image;
};
//游戏渲染器
//class CD3DRenderer : public CRenderInterface {
class CD3DRenderer :public CRenderInterface {
public:
CD3DRenderer();
~CD3DRenderer();
bool Initialize(int w, int h, WinHWND mainWin, bool fullScreen);
void CalculateProjMatrix(float fov, float n, float f);
void CalculateOrthoMatrix(float n, float f);
void SetClearCol(float r, float g, float b);
//开始渲染
void StartRender(bool bColor, bool bDepth, bool bStencil);
//结束渲染
void EndRender();
void ClearBuffers(bool bColor, bool bDepth, bool bStencil);
//参数一:顶点类型
int CreateStaticBuffer(VertexType, PrimType, int totalVerts, int totalIndeces, int stride, void **data, unsigned int *indices, int *staticId);
//释放资源
void Shutdown();
//渲染
int Render(int staticId);
//设置材质
void SetMaterial(stMaterial *mat);
//设置光照
void SetLight(stLight *light, int index);
//把某个光关掉
void DisabledLight(int index);
//设置透明的
void SetTranspency(RenderState state, TransState src, TransState dst);
//添加纹理
int AddTexture2D(char *file, int *texId);
void SetTextureFilter(int index, int filter, int val);
//设置多重纹理
void SetMultiTexture();
//应用纹理
void ApplyTexture(int index, int texId);
//保存屏幕截图
void SaveScreenShot(char *file);
void EnablePointerSprites(float size, float min, float a, float b, float c);
void DisablePointSprites();
private:
void OneTimeInit();
private :
D3DCOLOR m_Color; //d3d颜色
LPDIRECT3D9 m_Direct3D; //d3d对象
LPDIRECT3DDEVICE9 m_Device; //d3d设备
bool m_renderingScene; //是否渲染
stD3DStaticBuffer *m_staticBufferList; //静态缓存数组
int m_numStaticBuffers; //静态缓存的大小
int m_activeStaticBuffer; //当前静态缓存数量
stD3DTexture *m_textureList;
unsigned int m_numTextures;
};
bool CreateD3DRenderer(CRenderInterface **pObj);
| 39ae39387e272cb7442c2508774491ad19cba635 | [
"C",
"C++"
] | 7 | C++ | qianchedu/D3GameProject | 8c8a9afbaeec436fed3e830ca7580e56a9ae57a8 | f398a9272b9f2cfacec11edb54e19554db64b5be |
refs/heads/master | <repo_name>scrpatlolla/learning-redux<file_sep>/src/index.js
import 'regenerator-runtime/runtime';
import { createStore, applyMiddleware } from 'redux';
import createBehavioralMiddleware from './bp-middleware';
import {
findWins,
generateThreads,
matchAny
} from './utils';
const log = document.getElementById('log');
const threads = [
function* blockOverflowingBoard() {
yield {
block: [
function(event, payload) {
if (payload && payload.length) {
return payload[0] > 2 || payload[1] > 2;
} else {
return false;
}
}
]
};
},
...generateThreads(
findWins,
([x1, x2, x3]) =>
function* detectWinByX() {
const eventFn = matchAny('X', [x1, x2, x3]);
yield {
wait: [eventFn]
};
yield {
wait: [eventFn]
};
yield {
wait: [eventFn]
};
yield {
request: ['XWins']
};
}
),
...generateThreads(
findWins,
([x1, x2, x3]) =>
function* detectWinByO() {
const eventFn = matchAny('O', [x1, x2, x3]);
yield {
wait: [eventFn]
};
yield {
wait: [eventFn]
};
yield {
wait: [eventFn]
};
yield {
request: ['OWins']
};
}
),
...generateThreads(
function*() {
const values = [0, 1, 2];
for (var i = 0; i < values.length; i++) {
for (var y = 0; y < values.length; y++) {
yield [i, y];
}
}
},
([x, y]) =>
function* disallowSquareReuse() {
const event = (e, payload) =>
(e === 'X' || e === 'O') &&
payload[0] === x &&
payload[1] === y;
yield {
wait: [event]
};
yield {
block: [event]
};
}
),
function* enforcePlayerTurns() {
while (true) {
yield { wait: ['X'], block: ['O'] };
yield { wait: ['O'], block: ['X'] };
}
},
// Strategy
...generateThreads(
function*() {
const values = [0, 1, 2];
for (var i = 0; i < values.length; i++) {
for (var y = 0; y < values.length; y++) {
yield [i, y];
}
}
},
([x, y]) =>
function* defaultMoves() {
while (true) {
yield {
request: ['O'],
payload: [x, y]
};
}
}
),
function* afterWinAllowOnlyReset() {
while (true) {
yield { wait: ['OWins', 'XWins'] };
yield {
wait: ['RESET'],
block: ['X', 'O']
};
}
},
function* logger() {
while (true) {
yield {
wait: [
(event, payload) => {
log.innerHTML =
JSON.stringify({
type: event,
payload,
bpThread: true
}) +
'\n' +
log.innerHTML;
return true;
}
]
};
}
}
];
const defaultState = [
['_', '_', '_'],
['_', '_', '_'],
['_', '_', '_']
];
const content = document.getElementById('content');
function reducer(state = defaultState, action) {
if (action.type === 'RESET') {
return defaultState;
}
let row, column;
if (
action.payload &&
(action.type === 'X' || action.type === 'O')
) {
row = action.payload[0];
column = action.payload[1];
let newState = JSON.parse(JSON.stringify(state));
newState[row][column] = action.type;
return newState;
}
return state;
}
const store = createStore(
reducer,
applyMiddleware(createBehavioralMiddleware(threads))
);
const render = () => {
content.innerHTML = JSON.stringify(
store.getState(),
function(k, v) {
if (v.length && v[0] instanceof Array) return v;
if (v instanceof Array)
return JSON.stringify(v).replace(/"/g, '');
return v;
},
2
);
};
store.subscribe(render);
render();
document
.getElementById('dispatch')
.addEventListener('click', () => {
store.dispatch(
JSON.parse(
document.getElementById('action').value
)
);
});
<file_sep>/src/utils.js
export function generateThreads(fnGenerator, fn) {
let threads = [];
for (let o of fnGenerator()) {
threads.push(fn(o));
}
return threads;
}
export function* findWins() {
// Horizontal lines
yield [[0, 0], [0, 1], [0, 2]];
yield [[1, 0], [1, 1], [1, 2]];
yield [[2, 0], [2, 1], [2, 2]];
// Vertical lines
yield [[0, 0], [1, 0], [2, 0]];
yield [[0, 1], [1, 1], [2, 1]];
yield [[0, 2], [1, 2], [2, 2]];
// Diagonal
yield [[0, 0], [1, 1], [2, 2]];
yield [[0, 2], [1, 1], [2, 0]];
}
export const matchAny = (inputEvent, [x1, x2, x3]) => (event, [x, y] = []) =>
event === inputEvent &&
((x === x1[0] && y === x1[1]) ||
(x === x2[0] && y === x2[1]) ||
(x === x3[0] && y === x3[1]));
| a4949e74d36beaba73546eae13015aa4d7fc757b | [
"JavaScript"
] | 2 | JavaScript | scrpatlolla/learning-redux | 168e10de01c986e64f2cd3f5e6d8223ab9bcb30e | b5d8213c6d0fe681ce4585bd0da2f54d646a9e08 |
refs/heads/master | <file_sep>// Run script after DOM has loaded
document.addEventListener('DOMContentLoaded', function() {
// Store submit button in a variable for easy reference
var optionsButton = document.getElementById("options_submit");
// Capture input value to determine board size and color and set up the board
optionsButton.addEventListener("click", function(){
// If play button is clicked, change to reset
optionsButton.innerHTML = "Reset";
// These functions will come in handy
function isEven(value){
if (value % 2 == 0) {
return true;
} else {
return false;
};
};
function isOdd(value){
if (value % 1 == 0) {
return true;
} else {
return false;
};
};
function allSame(array) { // Ultimately got this solution from stack overflow, I had a lot of difficulty getting it to work on my own
var first = array[0];
if (array[0] == "") {
return false;
} else {
return array.every(function(element) {
return element == first;
});
};
};
// * Fun! Let the user choose the background color
var customBackground = document.getElementById("boardcolor_input").value;
// Set board size according to input value parsed to integer
var boardSize = parseInt(document.getElementById("boardsize_input").value);
// Create variable game board (empty array)
var gameBoard = [];
// create variable numSquares, which is gameboard size squared
var numSquares = (boardSize * boardSize);
// Create gameboard array containing [] of board size squared
for (var i = 0; i < numSquares; i++) {
gameBoard.push(i);
};
// Create a wrapper div called "board" inside of "game" div
document.getElementById("game").innerHTML = '<div id="board"></div>';
// Store board div inside of a variable
var board = document.getElementById("board");
// Center board in middle of page by adding margin css
board.style.margin = '0 auto';
// To make scalable, set wrapper div width and height 100px* board size
board.style.height = (100 * boardSize) + 'px';
board.style.width = (100 * boardSize) + 'px';
// Add border to board for visibility
board.style.border = 'solid 1px black';
// Iterate over gameboard, for every index in gameboard, print to document a div
for (var i = 0; i < numSquares; i++) {
board.innerHTML += '<div class="square"></div>'; // Need to add += or else divs overwrite each other!!
};
// Store square divs in a variable - need to include in global scope
var squares = document.getElementsByClassName("square");
// Mandatory square div styling
for (var i = 0; i < numSquares; i++) {
// set div squares to 100px x 100px
squares[i].style.height = '100px';
squares[i].style.width = '100px';
// Float square divs left
squares[i].style.float = "left";
// Set div line height to 100px
squares[i].style.lineHeight = "100px";
// Set unique DIV IDs to each square
squares[i].setAttribute("id", i.toString());
};
// ** Fancy! Make every other square light gray
if (numSquares % 2 !== 0) { // If board size is odd
for (var i = 0; i < numSquares; i += 2) { // make every other square light gray
squares[i].style.backgroundColor = customBackground;
};
} else { // If board size is even ### This was extremely hard to nail down ###
for (i = 0; i < numSquares; i += 1) {
if (isEven(i/boardSize)) { // make even rows alternate color
for (var squareNum = i; squareNum < (i + boardSize); squareNum += 2) {
squares[squareNum].style.backgroundColor = customBackground;
};
} else if (isOdd(i/boardSize)) { // make odd rows alternate color
for (var squareNum = i+1; squareNum < (i + boardSize); squareNum += 2) {
squares[squareNum].style.backgroundColor = customBackground;
};
} else {
};
};
};
// Store turn indicator div in a variable for easy access
var turnIndicator = document.getElementById("turnIndicator")
// After board is made, indicate who goes first
turnIndicator.style.color = "black";
turnIndicator.innerHTML = "X's Turn";
// Declare a global click counter
var boardClicks = 0;
// If board is clicked, increment global click counter
board.addEventListener("click", function() {
if (determineWinner()) { // determineWinner will return true if it finds a winning combination
turnIndicator.style.color = "blue";
turnIndicator.innerHTML = winningPlayer[0] + ' wins!';
} else if (isEven(boardClicks)) {
turnIndicator.style.color = "red";
turnIndicator.innerHTML = "O's Turn";
} else {
turnIndicator.style.color = "black";
turnIndicator.innerHTML = "X's Turn";
};
boardClicks++;
}); // End board click function
// Make an array to hold square click data
var squareClicks = [];
// Set squareclick data for each square to 0
for (var i = 0; i < numSquares; i++) {
squareClicks[i] = 0;
};
// Make a variable to store winning combination
var winningPlayer;
// Add function to determine winner based on clicks array
var determineWinner = function() {
// Check for win by row
for (i = 0; i < numSquares; i += 1) { // iterate over entire board
if ((i % boardSize) == 0) {
var rowCheck = [];
for (var squareNum = i; squareNum < (i + boardSize); squareNum += 1) { // iteration over column 1
rowCheck.push(squares[squareNum].innerHTML);
};
console.log('Row ' + i + ' is ' + rowCheck);
console.log(allSame(rowCheck));
if (allSame(rowCheck)) {
winningPlayer = rowCheck; // Push winning player data
return true;
};
};
};
// Check for win by column
for (i = 0; i < numSquares; i += 1) { // iterate over entire board
if (i < boardSize) { //
var colCheck = [];
for (var squareNum = i; squareNum < numSquares; squareNum += boardSize) { // iteration over row 1
colCheck.push(squares[squareNum].innerHTML);
};
console.log('Column ' + i + 'is ' + colCheck);
console.log(allSame(colCheck));
if (allSame(colCheck)) {
winningPlayer = colCheck; // Push winning player data
return true;
};
};
};
// Check for win by left diagonal
var diag1Check = []; // Needs to be outside of for loop to prevent overwriting array
for (i = 0; i < numSquares; i += 1) { // first iteration over board
if ((i % (boardSize + 1)) == 0) { // use condition if iterator % BOARDSIZE + 1 === 0 to get left diagonals
console.log(i)
diag1Check.push(squares[i].innerHTML);
};
};
console.log(diag1Check) // These also need to be outside of for loop to prevent checks on incomplete arrays
console.log(allSame(diag1Check));
if (allSame(diag1Check)) { // As does the return statement
winningPlayer = diag1Check; // Push winning player data
return true;
};
// Check for win by right diagonal
var diag2Check = []; // Needs to be outside of for loop to prevent overwriting array
for (i = (boardSize - 1); i < (numSquares - 1); i += 1) { // first iteration over board
if ((i % (boardSize - 1)) == 0) { // use condition if iterator % BOARDSIZE - 1 === 0 to get right diagonals
console.log(i)
diag2Check.push(squares[i].innerHTML);
};
};
console.log(diag2Check) // These also need to be outside of for loop to prevent checks on incomplete arrays
console.log(allSame(diag2Check));
if (allSame(diag2Check)) { // As does the return statement
winningPlayer = diag2Check; // Push winning player data
return true;
};
}; // End determineWinner function
// Add function to count square clicks
var countClicks = function() {
var divID = this.getAttribute("id");
squareClicks[divID] += 1;
// If global click counter is odd and local click is == 1, change innerhtml of div to 'X'
if (isEven(boardClicks) && squareClicks[divID] == 1) {
this.innerHTML = 'X';
// If global click counter is even and local click is == 1, change innerhtml of div to 'O'
} else if (isOdd(boardClicks) && squareClicks[divID] == 1) {
this.innerHTML = 'O';
this.style.color = "red";
// If local click counter is greater than 1, alert player and subtract 1 from global clicks
} else if (!determineWinner()){
alert('You cannot move there. That space is taken.');
boardClicks -= 1;
} else {
};
// Check for winner, if true, lock all local clicks
if (determineWinner()) { // determine winner will return true or false if it identifies a winning combination
// Set all square clicks to 2 to "lock" them to prevent further moves from taking place
for (var i = 0; i < numSquares; i++) {
squareClicks[i] = 2;
};
// Change play button to say play again
document.getElementById("options_submit").innerHTML = "Play again?"
};
};
// Add local click counter to each square on the board
for (var i = 0; i < numSquares; i++) {
squares[i].addEventListener("click", countClicks);
};
}); // End makeboard function
}); // End document load function | 846553b52dc09132c568153da1dd1a351467a84d | [
"JavaScript"
] | 1 | JavaScript | jsakalys/scalable-tic-tac-toe | 177d4b059d5c385942eb64b7cb62a01ac3f1a400 | a1226825998f1aa2d9b5831e38684991a3a55ad9 |
refs/heads/master | <repo_name>HxHexa/spring2019-spendings-tracker<file_sep>/spendEntry.cpp
/* spendClass.cpp - implementations of spendClass functions
* <NAME> 5/26/2019
* Final project for Spring2019 - spendings-tracker
* */
#include "spendEntry.h"
<file_sep>/namedList.h
/* namedList.h - header for named list class
* basically a linked list but with a name, for use with hashing funcs
* <NAME> - 5/27/2019
* Spring2019 final project - spendings-tracker
*
* info on inheritance in C++ found here:
* https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm
* */
#ifndef NAMEDLIST_H
#define NAMEDLIST_H
#include <string>
#include "linkedList.h"
using namespace std;
template <class Item>
class NamedList: public LList<Item> {
private:
string name;
public:
NamedList(string listName);
void rename(string newName);
string getName();
void displayList();
bool operator== (NamedList<Item>);
};
#endif
<file_sep>/hashTable.cpp
/* hashTable.cpp - implementations of functions in header file
* <NAME> 5/31/2019
* Part of finals
* */
#include <iostream>
#include "hashTable.h"
using namespace std;
template <class Item>
HashTable<Item>::HashTable() {
for (int i = 0; i < ARRAY_LENGTH; i++) {
status_table[i] = 0;
table[i] = NULL;
}
eleCount = 0;
}
template <class Item>
HashTable<Item>::~HashTable() {
//value not taken from memory heap so delete table[i] is unneccesary, apparently
//https://stackoverflow.com/questions/9235770/segfault-when-deleting-pointer
//for values passed in, delete them individually
for (int i = 0; i < ARRAY_LENGTH; i++) {
table[i] = NULL;
}
cout << "Destroyed hash table.\n";
}
template <class Item>
void HashTable<Item>::insertItem(Item* newEntry) {
if (eleCount >= MAX_ELE_COUNT) {
cout << "Maximum number of values in table reached (20)." << endl;
return;
}
int hashValue = hashFunction(*newEntry);
int iteratorValue = hashFunctionIterator(*newEntry);
while(true) {
if (table[hashValue] == NULL) {
table[hashValue] = newEntry;
status_table[hashValue] = 1;
eleCount += 1;
break;
}
else if (*table[hashValue] == *newEntry) {
cout << "Duplicate value.\n";
break;
}
else {
hashValue = (hashValue + iteratorValue) % ARRAY_LENGTH;
}
}
return;
}
template <class Item>
Item* HashTable<Item>::findItem(Item* findEntry) {
int hashValue = hashFunction(*findEntry);
int iteratorValue = hashFunctionIterator(*findEntry);
while(true) {
if (table[hashValue] != NULL &&
((*table[hashValue] == *findEntry) || (**table[hashValue] == **findEntry))) {
cout << "Item found at index " << hashValue << endl;
return findEntry;
}
else if (status_table[hashValue] == 0) {
cout << "Item not found.\n";
return NULL;
}
else {
hashValue = (hashValue + iteratorValue) % ARRAY_LENGTH;
}
}
}
template <class Item>
Item* HashTable<Item>::deleteItem(Item* deleteEntry) {
int hashValue = hashFunction(*deleteEntry);
int iteratorValue = hashFunctionIterator(*deleteEntry);
while(true) {
if (table[hashValue] != NULL &&
((*table[hashValue] == *deleteEntry) || (**table[hashValue] == **deleteEntry))) {
status_table[hashValue] = -1;
table[hashValue] = NULL;
return deleteEntry;
}
else if (status_table[hashValue] == 0) {
cout << "Item not found.\n";
return NULL;
}
else {
hashValue = (hashValue + iteratorValue) % ARRAY_LENGTH;
}
}
}
//for testing purposes
template<class Item>
int HashTable<Item>::hashTest(Item* value) {
return hashFunction(*value);
}
template<class Item>
int HashTable<Item>::hashTestIterator(Item* value) {
return hashFunctionIterator(*value);
}
template<class Item>
void HashTable<Item>::display() {
cout << "Elements Count: " << eleCount << endl;
for (int i = 0; i < ARRAY_LENGTH; i++) {
cout << i << " " << status_table[i] << " ";
if (table[i] == NULL) {
cout << "NULL";
}
else {
cout << *table[i] << " " << table[i];
}
cout << endl;
}
}
<file_sep>/README.md
# spring2019-spendings-tracker
Final project for Bennington College's Data Structures in C++ course: a (hopefully) functional spendings tracking program. Inspired by the tiring work of having to keep my Excel spreadsheet updated.
So far only the basic structures are set up.
UPDATE: I probably will just leave the project as is and call it an implementation of a Hash Table in C++. Plans are that I will make this into an actual thing, but rebuilt from scratch using Python, since it is way easier there. It is not as if I would require C++ for this offline program for personal use anyways, though if I were to expand it...
Anyways, those thoughts are for a future far away. Right now, it would make way more sense to just build the program in Python to get a functioning version of it out quicker instead of having to worry about the little things. Have the structure done first then worry about the polishing later, I suppose?
<file_sep>/main.cpp
/* main.cpp - main for spending tracker
test1 -> displayList();
* <NAME> - 5/24/2019
* For Spring 2019 Spending Tracker project
* compile and run normally. No special flags needed.
* */
#include <iostream>
#include <string>
//for some reason I could not get it to work with including the headers.
//Something wrong with the linker? I have no idea
#include "hashTable.cpp"
#include "spendEntry.cpp"
#include "namedList.cpp"
#include "linkedList.cpp"
using namespace std;
int main() {
HashTable<NamedList<int>*>* source = new HashTable<NamedList<int>*>();
HashTable<NamedList<int>*>* category = new HashTable<NamedList<int>*>();
NamedList<int>* test1 = new NamedList<int>("test1");
test1 -> addToEnd(7);
test1 -> addToEnd(6);
test1 -> addToEnd(5);
NamedList<int>* test2 = new NamedList<int>("test1");
test2 -> addToEnd(7);
test2 -> addToEnd(6);
test2 -> addToEnd(5);
test1 -> displayList(); test2 -> displayList();
/*if (*test1 == *test2) cout << "equal";
else cout << "unequal";*/
source -> insertItem(&test1);
source -> findItem(&test2);
source -> deleteItem(&test2);
test1 -> displayList(); test2 -> displayList();
source -> display();
return 0;
}
<file_sep>/namedList.cpp
/* namedList.cpp - implementation of namedList.h functions
* <NAME> - 5/27/2019
* */
#include <string>
#include <iostream>
#include "linkedList.h"
#include "namedList.h"
using namespace std;
//very basic implementations
//there might be some work needed to be done in regards to special characters
//or empty string
//for now, this is just a demo that hopefully works
template <class Item>
NamedList<Item>::NamedList(string listName) {
name = listName;
}
template <class Item>
void NamedList<Item>::rename(string newName) {
name = newName;
}
template <class Item>
string NamedList<Item>::getName() {
return name;
}
template <class Item>
void NamedList<Item>::displayList() {
cout << name << ": ";
LList<Item>::displayList();
}
//operator overloading taken from
//https://www.tutorialspoint.com/cplusplus/relational_operators_overloading.htm
template <class Item>
bool NamedList<Item>::operator== (NamedList<Item> n) {
if (name != n.getName()) return false;
else return true;
}
<file_sep>/spendEntry.h
/* spendClass.h - header file for class for spendings
* <NAME> 5/25/2019
* Final project for Spring2019 - spendings-tracker
* */
#ifndef SPENDENTRY_H
#define SPENDENTRY_H
#include <string>
using namespace std;
class SpendEntry {
private:
string name;
public:
};
#endif
<file_sep>/hashTable.h
/* hashTable.h - header file for hash table structure
* supports a maximum of 20 items
* <NAME> 5/30/2019
* Part of finals
* */
//#include guard found from
//https://en.wikipedia.org/wiki/Include_guard
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <string>
#include "namedList.h"
#define MAX_ELE_COUNT 20
#define ARRAY_LENGTH 23
using namespace std;
template <class Item>
class HashTable {
private:
//using an array of pointers to object type Item here
//makes it easier for deletion by setting to NULL
Item* table[ARRAY_LENGTH];
int status_table[ARRAY_LENGTH];
int eleCount = 0;
//imiplementation of multiple hash function using function overloading from
//https://stackoverflow.com/questions/6053444/c-template-method-changing-the-behavior-based-on-the-template-class
//i decided to not have a default template case after all. In afterthought,
//that was a dumb idea
int hashFunction(int value) {
return value % ARRAY_LENGTH;
}
//ARRAY_LENGTH - 4 is 19, for the purpose of getting good results
int hashFunctionIterator(int value) {
return value % (ARRAY_LENGTH - 4);
}
//iterating over string using range-based for loop found at
//https://www.techiedelight.com/iterate-over-characters-string-cpp/
int hashFunction(string value) {
int hashValue = 0;
int weight = 1;
for (const char& i : value) {
hashValue += weight * i;
weight += 2;
}
return hashFunction(hashValue);
}
int hashFunctionIterator(string value) {
int hashValue = 0;
int weight = 1;
for (const char& i : value) {
hashValue += weight * i;
weight += 2;
}
return hashFunctionIterator(hashValue);
}
template <class T>
int hashFunction(NamedList<T>* value) {
return hashFunction(value -> getName());
}
template <class T>
int hashFunctionIterator(NamedList<T>* value) {
return hashFunctionIterator(value -> getName());
}
public:
HashTable();
~HashTable();
void insertItem(Item*);
Item* findItem(Item*);
Item* deleteItem(Item*);
int hashTest(Item*);
int hashTestIterator(Item*);
void display();
};
#endif
<file_sep>/linkedList.h
/* linkedList.h - header file for attempting to wrap linkedList up as a class
* <NAME> 5/23/2019
* Final project for Spring2019 - spendings-tracker
* */
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template <class Item>
class LList {
protected:
struct node {
Item value;
node* next;
node (Item v, node* n) {
value = v;
next = n;
}
};
node* startNode;
int length;
public:
LList();
~LList();
LList(const LList&);
LList<Item>& operator=(const LList&);
void displayList();
int getLength();
void addToEnd(Item value);
void addToBeginning(Item value);
int addAtIndex(Item value, int index);
node* removeAtIndex(int index);
int removeByValue(Item value);
node* removeAtStart();
node* removeAtEnd();
node* findByValue(Item value);
};
#endif
<file_sep>/linkedList.cpp
/* linkedList.cpp - task1-7 of lab 3 on linked lists
* <NAME> - 3/5/2019
*
* COMPILE: g++ linkedList.cpp
* RUN: ./a.out
* */
#include <iostream>
#include "linkedList.h"
using namespace std;
/* simple initiator that sets startNode as NULL
* should not take any parameters
* */
template <class Item>
LList<Item>::LList() {
startNode = NULL;
length = 0;
}
/* deconstructor
* */
template <class Item>
LList<Item>::~LList() {
while (startNode != NULL) {
delete removeAtStart();
}
delete(startNode);
}
/* rule of 3 found from
* https://stackoverflow.com/questions/44809676/c-operator-overload-calling-destructor
* https://en.cppreference.com/w/cpp/language/rule_of_three
* used to assist with overloading of operator== not deleting the structure
* */
//copy construcor with help from
//https://www.tutorialspoint.com/cplusplus/cpp_copy_constructor.htm
//https://www.geeksforgeeks.org/copy-constructor-in-cpp/
template <class Item>
LList<Item>::LList(const LList& org) {
startNode = NULL;
length = 0;
if (org.startNode == NULL) return;
else {
node* traverser = org.startNode;
while (traverser != NULL) {
addToEnd(traverser -> value);
traverser = traverser -> next;
}
}
}
//copy assignment operator
//https://www.geeksforgeeks.org/copy-constructor-vs-assignment-operator-in-c/
template <class Item>
LList<Item>& LList<Item>::operator=(const LList& org) {
LList<Item> copy;
copy.startNode = NULL;
copy.length = 0;
if (org.startNode == NULL) return copy;
else {
node* traverser = org.startNode;
while (traverser != NULL) {
addToEnd(traverser -> value);
traverser = traverser -> next;
}
return copy;
}
}
/* displayList()
* input: none
* return: void
* displays the list. Used mainly for testing
* */
template <class Item>
void LList<Item>::displayList() {
//print a single arrow if startNode is NULL (empty list)
if (startNode == NULL) {
cout << ">" << endl;
return;
}
node* travelPointer = startNode; //initializing a pointer for traversing
//do while loop for traversing and printing the list
//information from: https://en.cppreference.com/w/cpp/language/do
do {
cout << travelPointer -> value << " > ";
travelPointer = travelPointer -> next;
} while(travelPointer != NULL);
cout << endl;
}
/* getLength()
* input: void
* return: int
* returns the length of the list
* */
template <class Item>
int LList<Item>::getLength() {
return length;
}
/* addToEnd
* input: Item value
* return: void
* adds an Item object to the list at the end
* */
template <class Item>
void LList<Item>::addToEnd(Item value) {
//initializing newNode
node* newNode = new node(value, NULL);
//checking whether the first node is NULL
//if the intention is to have a new list
//since we have newNode already, just use that
if (startNode == NULL) {
startNode = newNode;
length += 1;
return;
}
node* travelPointer = startNode; //initializing a pointer for traversing
//while loop that traverses the travelPointer until the end of the lsit
while (travelPointer -> next != NULL) {
travelPointer = travelPointer -> next;
}
//adding the newNode
travelPointer -> next = newNode;
length += 1;
}
/* addToBeginning
* input: Item value
* return: void
* adds an Item object to the list at the beginning
* */
template <class Item>
void LList<Item>::addToBeginning(Item value) {
//initialize newNode
node* newNode = new node(value, NULL);
//checking whether the newNode is NULL
//in the case it is, the function ends,
//startNode NULL case handling is altered for the class
if (newNode == NULL) {
return;
}
if (startNode == NULL) {
startNode = newNode;
length += 1;
return;
}
//setting the next pointer of newNode to the first node
newNode -> next = startNode;
//changing the first node to newNode
startNode = newNode;
length += 1;
}
/* addAtIndex
* input: Item value, int index
* return: int
* adds an Item object to the list at index given in input
* returns 0 if success, 1 if failed
* */
template <class Item>
int LList<Item>::addAtIndex(Item value, int index) {
//initialize newNode
node* newNode = new node(value, NULL);
//for negative index, the function returns an error code
if (index < 0) {
return 1;
}
//for NULL startNode, the function returns an error code
//in the case where the user is trying to initialize a new list,
//then an index would not make sense.
if (newNode == NULL) {
return 1;
}
//special indices cases
if (index == 0) {
addToBeginning(value);
return 0;
}
if (index == length) {
addToEnd(value);
return 0;
}
if (startNode == NULL) {
return 1;
}
node* traverser = startNode; //initializing a pointer for traversing
//putting the traverser on the index to add the node
//if next is NULL, then the function returns an error code
//in the case someone wants to add a node at the end, just use addToEnd
for (int i = 1; i < index; i++) {
if (traverser -> next != NULL) {
traverser = traverser -> next;
}
else {
return 1;
}
}
//making the newNode points to the nextNode
//if newNode is NULL, this step is skipped. The list will be cut there.
//*the "feature" above is now removed bc users could use removeAtEnd instead
//additionally, it's too much work traversing the rest of the list and
//delete each one of them for memory purposes
newNode -> next = traverser -> next;
//making the traverser, now on the index, points to newNode
traverser -> next = newNode;
length += 1;
return 0;
}
/* removeAtIndex
* input: int index
* return: node*
* remove a value at a designated index
* returns removed node
* */
template <class Item>
typename LList<Item>::node* LList<Item>::removeAtIndex(int index) {
//for negative index, the function returns an error code
if (index < 0) {
return NULL;
}
//for NULL startNode, the function returns an error code
//in the case where the user is trying to initialize a new list,
//then an index would not make sense. Use AddToBeginning instead
if (startNode == NULL) {
return NULL;
}
//if index = 0 calls removeAtStart
if (index == 0) {
return removeAtStart();
}
if (index == length - 1) {
return removeAtEnd();
}
node* iterator = startNode;
node* traverser = startNode; //initializing a pointer for traversing
//putting the traverser on the index to add the node
//if next is NULL, then the function returns an error code
//in the case someone wants to remove a node at the end, just use removeAtEnd
for (int i = 0; i < index; i++) {
if (traverser -> next != NULL) {
iterator = traverser;
traverser = traverser -> next;
}
else {
return NULL;
}
}
//remove the node
iterator -> next = traverser -> next;
traverser -> next = NULL;
length -= 1;
return traverser;
}
/* removeByValue
* input: Item value
* return: int
* removes all Item with value given in input
* returns the number of deleted items
* */
template <class Item>
int LList<Item>::removeByValue(Item delValue) {
//checking for NULL startNode
//there is nothing to remove from a NULL startNode, so the function returns an error
if (startNode == NULL) {
return -1;
}
//initialize a counter for number of vals deleted
int counter = 0;
//initialize an iterator at start
node* iterator = startNode;
//initialize a tracker node, for deleting
node* tracker = startNode;
//traversing the list, deleting delValue
//delete command usage found from https://stackoverflow.com/questions/4134323/c-how-to-delete-a-structure
//if the list has only 1 value, cancels the whole thing and jump to remove startNode
if (tracker -> next != NULL) {
while (1) {
tracker = iterator -> next;
if (tracker == NULL) {
break;
}
else {
if (tracker -> value == delValue) {
iterator -> next = tracker -> next;
delete tracker;
counter += 1;
}
else {
iterator = tracker;
}
}
}
}
//special part for removing the start node
if ((startNode) -> value == delValue) {
delete removeAtStart();
}
length -= counter;
return counter;
}
/* removeAtStart
* input: none
* return: node*
* remove the value at the start of the list and returns it
* */
template <class Item>
typename LList<Item>::node* LList<Item>::removeAtStart() {
//checking whether the startNode is NULL
if (startNode == NULL) {
return NULL;
}
//copy the part about removing startnode from above
node* tracker = startNode;
startNode = startNode -> next;
length -= 1;
return tracker;
}
/* removeAtEnd
* input: none
* return: node*
* removes the ending node of the list, returning the removed node
* */
template <class Item>
typename LList<Item>::node* LList<Item>::removeAtEnd() {
//checking whether the startNode is NULL
if (startNode == NULL) {
return NULL;
}
//traverser and tracker
node* traverser = startNode;
node* tracker = startNode;
//special case for when the list has only 1 element: just delete it
//else, also just delete it
if (startNode -> next == NULL) {
startNode = NULL;
length -= 1;
return tracker;
}
else {
while (traverser -> next -> next != NULL) {
traverser = traverser -> next;
}
}
tracker = traverser -> next;
traverser -> next = NULL;
length -= 1;
return tracker;
}
/* findByValue
* input: Item value
* return: node*
* find a node in the list with corresponding value, returning the first iteration
* */
template <class Item>
typename LList<Item>::node* LList<Item>::findByValue(Item value) {
//initialize newNode
node* newNode = new node(value, NULL);
//no NULL startNode
if (startNode == NULL) {
return NULL;
}
//initialize traverser
node* traverser = startNode;
//traversing through the list and find the node with the value
//if found, the node is returned
while (traverser != NULL) {
if (traverser -> value == value) {
delete newNode;
return traverser;
}
traverser = traverser -> next;
}
//default case to return NULL if no node with value is found
return NULL;
}
| bf2bba04b51177572a2a41c4f74627bf728970cb | [
"Markdown",
"C++"
] | 10 | C++ | HxHexa/spring2019-spendings-tracker | 5ba3e39d316ad12cceaddad9a30403c01d964509 | 452559fa940a2bd8718a7193892e8e9386f763cb |
refs/heads/master | <file_sep>// Parallelized async/ await promiseall .map()-loop
// Handy for inserting values into a database all at once
// (be sure to open enough db connections)
async function parallelize(value) {
return new Promise(async (resolve, reject) => {
const vals = value.split(',');
const loop = async() => {
console.log('loop()');
// Use array.map() to parallelize operations
const promises = await vals.map(async v => {
const execQuery = new Promise((res, rej) => {
// '1' takes longer to finish executing,
// returns last bc operations are parallelized
const _ms = v === '1' ? 500 : 50;
setTimeout(() => {
console.log(v, '--> done');
res();
}, _ms);
});
return execQuery;
});
await Promise.all(promises);
console.log('resolve()');
resolve();
};
loop();
});
};
async function start () {
await parallelize('1,2,3');
console.log('--- end ---');
}
console.log('--- start ---');
start();
<file_sep># PATH general use
export PATH="/usr/bin:$PATH"
export PATH="/usr/local/bin:$PATH"
export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
# fancy ls
alias ls="ls -Gh"
# fancy whoami
_HOST="$HOSTNAME"
alias whoami="whoami && echo @$_HOST"
# terminal colors
export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
# git branch in bash prompt
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
# bash prompt
export PS1="\u ✨ \[\e[36;40m\]\W\[\e[33;1m\]\$(parse_git_branch) \[\e[32;1m\]>\[\e[0m\] "
# my shortcuts
alias GH="cd ~/github"
alias BB="cd ~/bitbucket"
alias CHEAT="open https://github.com/laurengarcia/cheatsheets"
# check open ports
alias open-ports="lsof -i -P -n | grep LISTEN"
<file_sep>// Serialized async/ await promiseall .reduce()-loop
// Handy for inserting values into a database that depend on each other
async function serialize(value) {
return new Promise(async (resolve, reject) => {
const vals = value.split(',');
async function saveInDatabase(v) {
return new Promise(async (res, rej) => {
// '1' takes longer to finish executing,
// returns in order bc operations are serialized
const _ms = v === '1' ? 500 : 50;
setTimeout(() => {
console.log(v, '--> done');
res();
}, _ms);
});
}
// Serizalize using array.reduce()
vals.reduce(function(promise, v) {
return promise.then(function() {
return saveInDatabase(v).then((result) => console.log(result));
});
}, Promise.resolve()).then(function() {
// all done here
console.log('resolve()');
resolve();
}).catch(function(err) {
// error here
console.error(err.message);
reject();
});
});
}
async function start () {
await serialize('1,2,3');
console.log('--- end ---');
}
console.log('--- start ---');
start();
<file_sep># Truffle + Ganache + Deployment
### Install Dependencies
#### Truffle CLI
Dev env, test framework, and asset pipeline to prod Ethereum:
```
$ npm install -g truffle
```
#### Ganache CLI or GUI
Ganache CLI or GUI (was called TestRPC). Runs a virtual Eth blockchain locally. Also comes in GUI form as well.
```
$ npm install -g ganache-cli
```
#### Smart Contract Dependency Flattener
When you find code in the wild you can use truffle-flattener to compile the contract with all of its dependencies into one .sol file. Install:
```
$ npm install -D truffle-flattener --save
```
Usage:
```
$ truffle-flattener ./contracts/examples/Whitelist.sol > flattend.sol
```
## Init, Test & Deploy Contract to Local Ganache
Reference: [Hackernoon tutorial](https://hackernoon.com/ethereum-development-walkthrough-part-2-truffle-ganache-geth-and-mist-8d6320e12269)
1. Init project
```
$ mkdir myproject
$ truffle init
```
2. Contract & Migrations:
- Your solidity contract file goes into the /contracts dir.
- Next, go to /migrations and create a new file:
```
$ touch migrations/2_deploy_contracts.js
```
3. Config:
Set correct network settings inside of root dir truffle_config.js file
4. Start Ganache (in new terminal)
...or run from standalone desktop application
```
$ ganache-cli -p 8545
```
5. Compile (in /myproject dir)
- Compiles solidity to bytecode for EVM.
- NOTE: you may need to rm -rf the entire ./build directory before compiling, esp when deployment or config changes. Can make this a step in your build pipeline.
```
$ truffle compile
```
6. Migration
In /migrations/2_deploy_contract.js, use something like this code (assumes Wrestling.sol is your contract in /contracts):
```
const Wrestling = artifacts.require("./Wrestling.sol")
module.exports = function(deployer) {
deployer.deploy(Wrestling);
};
```
7. Deploy to local blockchain set in truffle-config.js by running this via cli. Contract address is spit out in terminal next to Solidity file name. In Ganache terminal, contract address is next to where it says "Contract created:"
- NOTE: If there is extra/ unused cruft code in your contracts, it may throw a spurious error related to gas. Go crop that code out (and remove it from build). You'll need to rm -rf the /build dir and re-compile/re-migrate.
```
$ truffle migrate --network development
```
8. Start Truffle console
```
$ truffle console --network development
```
9. Assign users that Ganache CLI generated via truffle cli:
```
`$ account0 = web3.eth.accounts[0]
`$ account1 = web3.eth.accounts[1]
```
10. Create contract instance from console, create an instance of the contract:
```
$ Wrestling.deployed().then(inst => { WrestlingInstance = inst })
```
11. Query contract properties. Truffle console lets you interact with the contract as if it were deployed to the public Eth blockchain. You can call functions etc. Call into contract and get current state of public properties:
```
$ WrestlingInstance.<public property>.call()
```
12. Calling contract functions. Call functions in the contract as one of the users that Ganache created and we wired up to the truffle cli above.
- `value` is used to send ether from the sender with the txn.
- `web3` is the js library used to talk to Ganache/EVM.
- `.toWei()` converts the amt in Eth to the smallest unit of Ether.
```
WrestlingInstance.wrestle({from: account0, value: web3.toWei(2, "ether")})
WrestlingInstance.wrestle({from: account1, value: web3.toWei(3, "ether")})
// End of the first round
WrestlingInstance.wrestle({from: account0, value: web3.toWei(5, "ether")})
WrestlingInstance.wrestle({from: account1, value: web3.toWei(20, "ether")})
// End of the wrestling
WrestlingInstance.withdraw({ from: account1 })
```
## Deploy to Public Network
Make sure you have gas in your Metamask account if its a testnet. There are different faucets for diff't testnets.
* [Kovan faucet link](https://faucet.kovan.network/)
* [Rinkeby faucet link](https://faucet.rinkeby.io/)
Make sure you're on the right network!
You can use different toolings deployment methods, including truffle by just configuring `truffle-config.js` in your project's home dir.
[Remix](https://remix.ethereum.org) is pretty awesome, great for debugging, and it has [great docs here](https://remix-ide.readthedocs.io/en/latest/run.html). highly recommend.
One thing to note about Remix is that you'll need to use `truffle-flattener` before deploying. See section at top for details.
<file_sep># Cheatsheets
Collection of notes & references I use locally for developement. Sample integration with ~/.bash_profile included.
<file_sep>To work develop smart contracts locally with Metamask and Ganache:
### Setup: Start Ganache and Connect Metamask
1. FIRST! Back up your primary Metamask seed phrase so you can recover your accounts using it.
2. Lock Metamask via "Log Out" button if you haven't already.
Start Ganache in terminal cli:
```
$ ganache-cli -p 8545
```
3. Copy seed phrase. Your dev env seed phrase will appear as "Mnemonic" under "HD Wallet" in the startup output. Copy seed phrase and open Metamask > Import using account seed phrase.
4. Select Network. In Metamask network selector, choose "Custom RPC" and enter "localhost:8545". The network selector will now say "Private Network".
5. Compile, migrate & deploy smart contract to ganache. See `truffle-ganache.md` for details.
```
$ truffle compile
$ truffle migrate --network development
```
6. Copy smart contract address from deployment output into dapp local configuration.
<file_sep>// Async-Await are just syntax sugar for Promises
// https://javascript.info/async-await
// Async keyword
// just means the function always returns a promise
// even if a fn actually returns a non-promise value, prepending `async`
// tells js to automatically wrap value in a resolved promise
async function f() {
return 1;
}
f().then(alert); // 1
// Await keyword
// works only inside async functions,
// !cant use `await` in regular fns!
let value = await promise;
// fn execution pauses at the `await`, resumes when promise settles
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait till the promise resolves (*)
alert(result); // "done!"
}
f();
// Class methods: just add `async`
class Waiter {
async wait() {
return await Promise.resolve(1);
}
}
new Waiter()
.wait()
.then(alert); // 1
// Error handling
// Two approaches:
// - try/catch inside of async fn
// - .catch() handler when calling async fn
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
// catches errors both in fetch and response.json
alert(err);
}
}
f();
// OR
async function f() {
let response = await fetch('http://no-such-url');
}
// f() becomes a rejected promise
f().catch(alert); // TypeError: failed to fetch
// Await accepts Thenables
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve, reject) {
alert(resolve); // function() { native code }
// resolve with this.num*2 after 1000ms
setTimeout(() => resolve(this.num * 2), 1000); // (*)
}
};
async function f() {
// waits for 1 second, then result becomes 2
let result = await new Thenable(1);
alert(result);
}
f();
// Call async from non-async
// just use .then() syntax instead of `await` keyword
async function wait() {
await new Promise(resolve => setTimeout(resolve, 1000));
return 10;
}
function f() {
// shows 10 after 1 second
wait().then(result => alert(result));
}
f();
// Example AJAX call
async function loadJson(url) { // (1)
let response = await fetch(url); // (2)
if (response.status == 200) {
let json = await response.json(); // (3)
return json;
}
throw new Error(response.status);
}
loadJson('no-such-user.json')
.catch(alert); // Error: 404 (4)
<file_sep># Ethereum
### Learn Solidity
- [Solidity Docs](https://docs.soliditylang.org/)
- [Solidity By Example](https://solidity-by-example.org/)
- [Cryptozombies](https://cryptozombies.io/)
- [Smart Contract Engineer](https://www.smartcontract.engineer/)
### Dev Tools
- [Remix IDE](https://remix.ethereum.org/): Solidity IDE in browser
- [Truffle + Ganache](truffle-ganache.md)
- [Truffle Flattener](truffle-ganache.md): compiling smart contract & deps
- [Truffle Box](https://truffle-box.github.io/)
- [Hardhat](https://hardhat.org/): Dev env w debugging, test
- [Scaffold-ETH](https://github.com/scaffold-eth/scaffold-eth): <NAME>'s dev kit
- [Solhint](https://github.com/protofire/solhint): Solidity linter via npm
- [ZepKit](https://npm.io/search/keyword:zepkit): hot reloader for smart contracts via npm by Open Zeppelin
### Best Practices
- [Open Zeppelin Solidity Library for Smart Contract Dev (github)](https://github.com/OpenZeppelin/openzeppelin-solidity/)
- [Consensys: Smart Contract Best Practices (github)](https://github.com/ConsenSys/smart-contract-best-practices)
### Security
- [Web3 Security Library by Immunefi](https://github.com/immunefi-team/Web3-Security-Library)
- [Mastering Ethereum Ch 9: Smart Contract Security](https://github.com/ethereumbook/ethereumbook/blob/develop/09smart-contracts-security.asciidoc)
### Security Audit Tools
- [Fuzzing by Consensys Diligence](https://consensys.net/diligence/fuzzing/)
### Wallets
- [Metamask](https://metamask.io)
- [Gnosis Multi-Sig](https://gnosis-safe.io/)
### JS Libraries
- [Web3.js](https://web3js.readthedocs.io/)
- [Ethers.js](https://docs.ethers.io/)
| a3dd73b8fda89286c0785be34fde128da9139e8b | [
"JavaScript",
"Markdown",
"Shell"
] | 8 | JavaScript | laurengarcia/cheatsheets | 6103af16bd7d330e3b282d2e78a76b34e3b40005 | 018173b8fe7c02f6c888675ed9ee889b6b546273 |
refs/heads/master | <repo_name>deerabby123/triangle-rest<file_sep>/triangle/test/triangle/test.java
package triangle;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class test {
private triangle calc;
@Before
public void setUp() throws Exception {
System.out.println("²âÊÔÒÔǰ");
}
@After
public void tearDown() throws Exception {
System.out.println("²âÊÔÒÔºó");
}
@Test
public void test() {
calc = new triangle ();
assertEquals (2, calc.triangles(2,5,5));
}
}
<file_sep>/triangle/src/triangle/triangle.java
package triangle;
public class triangle {
public int triangles(int a, int b, int c){
if (a+b<=c||a+c<=b||b+c<=a){
return 0;
}else if(a==b&&b==c){
return 1;
}else if(a==b||b==c||a==c){
return 2;
}else{
return 3;
}
}
} | 13a126a7fcf5ad537da9565e8d073afa9773af8d | [
"Java"
] | 2 | Java | deerabby123/triangle-rest | 18be4a61f0dfd79fda8afb343df762270e5ff9b5 | 69b1623c7445699c246ea4f7bfc92d8f67468439 |
refs/heads/main | <file_sep>/* QUICK NOTES
Grid must be a square nummber of user input
Auto-grid used for both row/column in grid-template
*/
// Create input bar for users to add the number of grid boxes
const form = document.createElement('form');
const label = document.createElement('label');
const input = document.createElement('input');
const output = document.createElement('output');
input.setAttribute('id', 'quantity');
input.setAttribute('type', 'range');
input.setAttribute('min', '1');
input.setAttribute('max', '100');
input.setAttribute('value', '1');
input.setAttribute('onchange', 'rangeValue.value=value');
label.setAttribute('for', 'quantity');
label.textContent = 'Set number : ';
output.setAttribute('id', 'rangeValue');
output.textContent = '1';
form.append(label, output, input);
// Create user input div and button, also add eventLiserner to button
// Button will create the grid object
const button = document.createElement('button');
button.classList.add('.btn');
button.textContent = 'Create Grid'
button.addEventListener('click', () => {
// Remove all childNodes of grid before creating new grid
clear();
// Assign user input to variable and create grid template string of autos
let userNumber = Number(input.value);
let gridSize = 'auto '.repeat(userNumber);
// Re-write grid info object
gridInfo = {
'display': 'grid',
'grid-template': `${gridSize} / ${gridSize}`,
'flex': 'wrap'
}
Object.assign(gridDiv.style, gridInfo);
for (let i=0; i <= userNumber-1; i++) {
for (let j=0; j <= userNumber-1; j++) {
let newDiv = document.createElement('div');
newDiv.classList.add('gridDiv');
newDiv.setAttribute('style', 'background-color: yellow');
newDiv.textContent = '';
gridDiv.append(newDiv);
}
}
createHoverEffect();
});
// Create divs from user input and append to grid at end of script
const inputContainer = document.createElement('div');
inputContainer.classList.add('inputContainer');
inputContainer.setAttribute('style', 'display: flex; justify-content: space-between; ;width: 500px; background-color: blue;');
inputContainer.append(form, button);
// Create Grid Area info as global variable
// retrieve main div box and create grid div to build etch-a-sketch.
let gridInfo = {
"display": "grid",
"grid-template": "auto"/ "auto",
"height": "inherit",
"width": "inherit",
"gap": "1px"
}
const container = document.querySelector('.container');
const gridDiv = document.createElement('div');
gridDiv.classList.add('grid')
Object.assign(gridDiv.style, gridInfo);
container.append(gridDiv);
// Create hover effect using onMouseOver event (bind to each div in grid)
function basicHoverEffect() {
const boxes = document.querySelector('.grid').querySelectorAll('div');
//var x = document.getElementById("myDIV").querySelectorAll(".example");
boxes.forEach(box => {
box.addEventListener('mouseover', () => {
box.setAttribute('style', 'background-color: black;');
});
});
// Create onMouseLeave event to rever the colour back to origina state
boxes.forEach(box => {
box.addEventListener('mouseout', () => {
box.setAttribute('style', 'background-color: white;');
});
});
}
function RainbowHoverEffect() {
const boxes = document.querySelector('.grid').querySelectorAll('div');
//var x = document.getElementById("myDIV").querySelectorAll(".example");
boxes.forEach(box => {
let r = Math.floor(Math.random() *255);
let g = Math.floor(Math.random() *255);
let b = Math.floor(Math.random() *255);
box.addEventListener('mouseover', () => {
box.setAttribute('style', `background-color: ${r}${g}${b};`);
});
});
// Create onMouseLeave event to rever the colour back to origina state
boxes.forEach(box => {
box.addEventListener('mouseout', () => {
box.setAttribute('style', 'background-color: white;');
});
});
}
function clear() {
while (gridDiv.firstChild) {
gridDiv.removeChild(gridDiv.lastChild);
}
}
const body = document.querySelector('body');
body.insertBefore(inputContainer, container);
| 7702312ba9cd4d2d1f84331af5f9adf288459bd3 | [
"JavaScript"
] | 1 | JavaScript | blitheryjibits/Etch-a-Sketch | 809a98806f6d9c9d2a482b0c608728541597e8fc | 04ca9f620d0f6486fa96b28b1af1d05076e6f2fd |
refs/heads/master | <file_sep>import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
String id;
String userid;
List<Product> products = new ArrayList<Product>();
ShoppingCart(String id, String userid){
this.id = id;
this.userid = userid;
}
public void addProduct(Product prod){
this.products.add(prod);
}
public List<Product> getProducts(){
return products;
}
}
<file_sep>public class User {
String username;
String password;
User(String username,String password){
this.username = username;
this.password = <PASSWORD>;
}
@Override
public boolean equals(Object obj) {
if(obj == null) return false;
if(!(obj instanceof User)) return false;
User newuser = (User) obj;
return this.username.equals(newuser.username) && this.password.equals(<PASSWORD>);
}
}
<file_sep>import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
HttpSession session = req.getSession();
if(req.getParameter("remember") == "true"){
session.setAttribute("username",req.getParameter("username"));
session.setAttribute("password",req.getParameter("password"));
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
String currname = req.getParameter("username");
String currpass = req.getParameter("password");
String remember = req.getParameter("remember");
HttpSession session = req.getSession();
session.setAttribute("Username",currname);
session.setAttribute("Password",<PASSWORD>);
if("yes".equals(remember)){
Cookie c = new Cookie("Username", currname);
c.setMaxAge(60*60*24*30);
resp.addCookie(c);
} else {
Cookie c = new Cookie("Username", null);
c.setMaxAge(0);
resp.addCookie(c);
}
User newUser = new User(currname,currpass);
boolean userFound = false;
Userdata userdata = new Userdata();
for (User u : userdata.users ) {
if(u.equals(newUser)) userFound = true;
}
if (userFound == true) {
resp.sendRedirect("login.jsp");
}else {
req.setAttribute("err_msg","Username and/or password is invalid!");
req.getRequestDispatcher("index.jsp").forward(req,resp);
};
}
}
| c420713178449e6d25a424e5eb6c78a415dca3ab | [
"Java"
] | 3 | Java | Ariunjin/Lab13 | 9b07b90fc551b44245903858b0a24420013406f2 | 6ae64eff3f90008d1f20f67090b4b8dabcd501cd |
refs/heads/master | <repo_name>jeromevs/currency-converter<file_sep>/src/App.js
import React, { useState } from "react";
import "./App.css";
import Dollar from "./images/dollar.png";
import Arrow from "./images/arrow.png";
import Arrowup from "./images/arrowup.png";
import rates from "./Rates";
const deviseItems = [];
Object.keys(rates).forEach(devise => {
deviseItems.push(devise);
});
console.log(deviseItems);
function App() {
const [currency1, setCurrency1] = useState("");
const [currency2, setCurrency2] = useState("");
const [button, setButton] = useState("");
const [devise1, setDevise1] = useState("USD");
const [devise2, setDevise2] = useState("EUR");
const handleSubmit = event => {
event.preventDefault();
if (button === "down") {
setCurrency2((currency1 * rates[devise2]) / rates[devise1]);
} else if (button === "up") {
setCurrency1((currency2 * rates[devise1]) / rates[devise2]);
}
};
return (
<>
<div className="convertisseur">
<div className="header">
<img
src={Dollar}
alt="dollar"
style={{ height: "50px", width: "100px" }}
/>
<h1>Eur to Usd</h1>
<img
src={Dollar}
alt="dollar"
style={{ height: "50px", width: "100px" }}
/>
</div>
<form autoComplete="off" onSubmit={handleSubmit}>
<p>
<input
type="text"
name="toconvert"
placeholder="0"
value={currency1}
onChange={event => {
setCurrency1(event.target.value);
}}
/>
<select
value={devise1}
onChange={event => {
setDevise1(event.target.value);
}}
>
{deviseItems.map(deviseName => {
return <option value={deviseName}>{deviseName}</option>;
})}
</select>
</p>
<div className="arrow">
<button
onClick={() => {
setButton("down");
}}
name="down"
type="submit"
>
<img
src={Arrow}
alt="arrow"
style={{ height: "80px", width: "80px", border: "none" }}
/>
</button>
<button
onClick={() => {
setButton("up");
}}
name="up"
type="submit"
>
<img
src={Arrowup}
alt="arrowup"
style={{ height: "80px", width: "80px", border: "none" }}
/>
</button>
</div>
<p>
<input
type="text"
name="toconverted"
placeholder="0"
value={currency2}
onChange={event => {
setCurrency2(event.target.value);
}}
/>
<select
value={devise2}
onChange={event => {
setDevise2(event.target.value);
}}
>
{deviseItems.map(deviseName => {
return <option value={deviseName}>{deviseName}</option>;
})}
</select>
</p>
</form>
</div>
</>
);
}
export default App;
| bda05165ed17a97a783789510b5b291bdab0c12b | [
"JavaScript"
] | 1 | JavaScript | jeromevs/currency-converter | 767daf02ce9a11902bb2fce396af4f698056c2a1 | f0daa0e25d7eea56cf0ba80fd80f4a2b5fb00ab1 |
refs/heads/master | <repo_name>MarkFrando/MemoryApplication<file_sep>/app/src/main/java/com/midterm/frando/memorygame/ScoreActivity.java
package com.midterm.frando.memorygame;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ScoreActivity extends Activity {
SharedPreferences prefs;
TextView score, hiscore;
String name;
int points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
prefs = getPreferences(MODE_PRIVATE);
Intent get = getIntent();
points = get.getIntExtra("POINTS", 0);
name = get.getStringExtra("NAME");
score = (TextView) findViewById(R.id.score);
hiscore = (TextView) findViewById(R.id.hiscore);
add();
read();
}
public void save() {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("HNAME", name);
editor.putInt("HSCORE", points);
editor.commit();
}
public void read(){
String readName = prefs.getString("HNAME", "");
int readPoints = prefs.getInt("HSCORE", -1);
if(points > readPoints){
save();
score.setText("New Hiscore!");
hiscore.setText("The current Hiscore is held by " + name + " at " + points + " points.");
}else{
score.setText("Thank you for playing " + name + "\nYour Score is: \n" + points);
hiscore.setText("The current Hiscore is held by " + readName + " at " + readPoints + " points.");
}
}
public void onReplay(View view) {
Intent replay = new Intent(this, NameActivity.class);
startActivity(replay);
}
public void add(){
DatabaseOpenHelper dbHandler = new DatabaseOpenHelper(this, null, null, 1);
Scores score = new Scores(name, points);
dbHandler.addScore(score);
}
}
<file_sep>/app/src/main/java/com/midterm/frando/memorygame/GameActivity.java
package com.midterm.frando.memorygame;
import android.app.Activity;
import android.content.Intent;
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 java.util.Random;
public class GameActivity extends Activity {
Random rand = new Random();
String colour, name;
int points;
int[] colours, numbers;
TextView num1, num2, num3, num4;
private static final String NAME = "name";
private static final String POINT = "point";
private static final String COL = "coloured";
private static final String NUM = "numbered";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Intent get = getIntent();
points = get.getIntExtra("POINTS", 0);
name = get.getStringExtra("NAME");
num1 = (TextView) findViewById(R.id.num1);
num2 = (TextView) findViewById(R.id.num2);
num3 = (TextView) findViewById(R.id.num3);
num4 = (TextView) findViewById(R.id.num4);
numbers = createNumbers();
colours = createColourID();
if (savedInstanceState != null) {
name = savedInstanceState.getString(NAME, "");
points = savedInstanceState.getInt(POINT, 0);
colours = savedInstanceState.getIntArray(COL);
numbers = savedInstanceState.getIntArray(NUM);
}
num1.setText(String.valueOf(numbers[0]));
num2.setText(String.valueOf(numbers[1]));
num3.setText(String.valueOf(numbers[2]));
num4.setText(String.valueOf(numbers[3]));
num1.setBackgroundColor(Color.parseColor(createColour(colours[0])));
num2.setBackgroundColor(Color.parseColor(createColour(colours[1])));
num3.setBackgroundColor(Color.parseColor(createColour(colours[2])));
num4.setBackgroundColor(Color.parseColor(createColour(colours[3])));
if(points >= 1) Toast.makeText(this, "Points: " + points, Toast.LENGTH_SHORT).show();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i("Memory", "onSaveInstanceState");
savedInstanceState.putString(NAME, name);
savedInstanceState.putInt(POINT, points);
savedInstanceState.putIntArray(COL, colours);
savedInstanceState.putIntArray(NUM, numbers);
}
public int[] createNumbers(){
int[] nums = {(rand.nextInt(10)), (rand.nextInt(10)), (rand.nextInt(10)), (rand.nextInt(10))};
return nums;
}
public int[] createColourID(){
int[] colourID = {(int)(Math.random() * 4 + 1), (int)(Math.random() * 4 + 1), (int)(Math.random() * 4 + 1), (int)(Math.random() * 4 + 1)};
return colourID;
}
public String createColour(int id){
switch(id){
case 1:
colour = "#ff0000";
break;
case 2:
colour = "#00ff00";
break;
case 3:
colour = "#0000ff";
break;
case 4:
colour = "#ffff00";
break;
}
return colour;
}
public void onMemorized(View view) {
int activity = (int)(Math.random() * 2 + 1);
Intent memorize;
if(activity == 1){
memorize = new Intent(this, GuessNumActivity.class);
}else{
memorize = new Intent(this, GuessColActivity.class);
}
memorize.putExtra("NUMS", numbers);
memorize.putExtra("COLS", colours);
memorize.putExtra("POINTS", points);
memorize.putExtra("NAME", name);
startActivity(memorize);
}
}
<file_sep>/app/src/main/java/com/midterm/frando/memorygame/DatabaseOpenHelper.java
package com.midterm.frando.memorygame;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
private static final String TABLE_SCORES = "scores";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_SCORE = "score";
public DatabaseOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_SCORE_TABLE = "create table " + TABLE_SCORES + "(" +
COLUMN_NAME + " text primary key, " +
COLUMN_SCORE + " integer)";
db.execSQL(CREATE_SCORE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, score.getName());
values.put(COLUMN_SCORE, score.getScore());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public boolean deleteScore(String name){
boolean result = false;
String query = "select * from " + TABLE_SCORES +
" where " + COLUMN_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Scores score = new Scores();
if(cursor.moveToFirst()){
db.delete(TABLE_SCORES, COLUMN_NAME + " = ?",
new String[] { String.valueOf(name)});
cursor.close();
result = true;
}
db.close();
return result;
}
public Scores findScore(String name){
String query = "select * from " + TABLE_SCORES +
" where " + COLUMN_NAME + " =\"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Scores score = new Scores();
if(cursor.moveToFirst()){
cursor.moveToFirst();
score.setName(cursor.getString(0));
score.setScore(Integer.parseInt(cursor.getString(1)));
cursor.close();
}else{
score = null;
}
db.close();
return score;
}
}
| 76fab24709847edc2e9a513bf94aa4329fe57d36 | [
"Java"
] | 3 | Java | MarkFrando/MemoryApplication | 05d4b1ed463747f5672ccd231dde27225ccb1705 | aa1ba871371cd278121da5ab8f75f0dcdeb41b0f |
refs/heads/master | <repo_name>askergali/alice<file_sep>/test(original).py
import requests
from random import sample, shuffle, randint
from flask import Flask, request
import logging
import json
def randomBooks_and_Authors():
questions_authors, answers_authors = [], []
for i in range(5):
book, author = random_book()
questions_authors.append(book)
answers_authors.append(author)
return questions_authors, answers_authors
def randomBook_and_Genre():
global book_names, books_4genres
questions_genres, answers_genres = [], []
for i in range(5):
book_g = book_names[randint(0, len(book_names)-1)]
correctGenre = books_4genres[book_g]
questions_genres.append(book_g)
answers_genres.append(correctGenre)
return questions_genres, answers_genres
class User:
def __init__(self, id, name):
self.id = id
self.name = name
self.book = None
self.isTakingQuizGenre = False
self.quizGenre = None
self.isTakingQuizAuthor = False
self.quizAuthor = None
def is_logged(self):
if self.name is not None:
return True
else:
return False
def startedQuizGenre(self, quizGenre):
self.quizGenre = quizGenre
self.isTakingQuizGenre = True
def startedQuizAuthor(self, quizAuthor):
self.quizAuthor = quizAuthor
self.isTakingQuizAuthor = True
def get_quizAuthor(self):
return self.quizAuthor
def get_quizGenre(self):
return self.quizGenre
def get_name(self):
return self.name
def set_book(self, book):
self.book = book
def get_book(self):
return self.book
class QuizGenre:
def __init__(self, questions, answers):
self.questions = questions
self.answers = answers
self.currentQuestion = 0
self.totalScore = 0
def quizGenre(self):
global genres
book = self.questions[self.currentQuestion-1]
genre = self.answers[self.currentQuestion-1]
options = []
while len(options) <= 2:
option = genres[randint(0, len(genres)-1)]
if option != genre:
options.append(option)
options.append(genre)
shuffled_genres = sample(options, len(options))
return book, genre, shuffled_genres
def answer(self, answer):
if answer == self.answers[self.currentQuestion-1]:
self.totalScore += 1
self.currentQuestion += 1
else:
self.currentQuestion += 1
return self.currentQuestion, self.totalScore
def end_quiz(self):
user.isTakingQuizGenre = False
class QuizAuthor:
def __init__(self, questions, answers):
self.questions = questions
self.answers = answers
self.currentQuestion = 0
self.totalScore = 0
def quizAuthor(self):
global all_authors
book = self.questions[self.currentQuestion-1]
author = self.answers[self.currentQuestion-1]
choices = []
while len(choices) <= 2:
choice = all_authors[randint(0, len(all_authors)-1)]
if choice != author:
choices.append(choice)
choices.append(author)
shuffled_authors = sample(choices, len(choices))
return book, author, shuffled_authors
def answer(self, answer):
if answer == self.answers[self.currentQuestion-1]:
self.totalScore += 1
self.currentQuestion += 1
return self.currentQuestion, self.totalScore
def end_quiz(self):
user.isTakingQuizAuthor = False
class Book:
def __init__(self, title, rating, author, desc, cover):
self.title = title
self.rating = rating
self.author = author
self.desc = desc
self.cover = cover
def get_cover(self):
return self.cover
user = None
app = Flask(__name__)
logging.basicConfig(level=logging.INFO, filename='app.log',
format='%(asctime)s %(levelname)s %(name)s %(message)s')
sessionStorage = {}
def get_rating(book_name):
try:
url = "https://www.googleapis.com/books/v1/volumes"
params = {
'q': book_name,
'key': "<KEY>"
}
response = requests.get(url, params=params)
books_json = response.json()
rating = books_json['items'][0]['volumeInfo']['averageRating']
name_book = books_json['items'][0]['volumeInfo']['title']
return rating, name_book
except Exception as e:
return None, e
def get_description(book_name):
try:
url = "https://www.googleapis.com/books/v1/volumes"
params = {
'q': book_name,
'key': "<KEY>"
}
response = requests.get(url, params=params)
books_json = response.json()
author = books_json['items'][0]['volumeInfo']['authors'][0]
description = books_json['items'][0]['volumeInfo']['description']
return author, description
except Exception as e:
return e, None
def get_cover(book_name):
try:
url = "https://www.googleapis.com/books/v1/volumes"
params = {
'q': book_name,
'key': "<KEY>"
}
response = requests.get(url, params=params)
books_json = response.json()
cover = books_json['items'][0]['volumeInfo']['imageLinks']['thumbnail']
return cover
except Exception:
return None
def get_first_name(req):
for entity in req['request']['nlu']['entities']:
if entity['type'] == 'YANDEX.FIO':
return entity['value'].get('first_name', None)
all_books = []
all_authors = []
author_book = {}
def get_book_and_author():
global all_books, all_authors, author_book
try:
response = requests.get(
"https://api.nytimes.com/svc/books/v3/lists/best-sellers/history.json?api-key=<KEY>")
books_json = response.json()
for i in range(20):
book = books_json['results'][i]['title']
all_books.append(book)
author = books_json['results'][i]['author']
all_authors.append(author)
author_book[book] = author
except Exception as e:
return e
return all_books, all_authors, author_book
def random_book():
global all_books
shuffle(all_books)
return all_books[0], author_book[all_books[0]]
get_book_and_author()
genres = ['Fiction', 'Action', 'Classic', 'Comic', 'Detective', 'Drama', 'Horror']
book_names = ['<NAME>', 'The Hobbit', '1984', 'Batman', '<NAME>', 'Hamlet', 'The Shining']
books_4genres = {
'Harry Potter': 'Fiction',
'The Hobbit': 'Action',
'1984': 'Classic',
'Batman': 'Comic',
'Sherlock Holmes': 'Detective',
'Hamlet': 'Drama',
'The Shining': 'Horror'
}
@app.route('/post', methods=['POST'])
def main():
logging.info('Request: %r', request.json)
response = {
'session': request.json['session'],
'version': request.json['version'],
'response': {
'end_session': False
}
}
handle_dialog(response, request.json)
logging.info('Request: %r', response)
return json.dumps(response)
def handle_dialog(res, req):
global user
user_id = req['session']['user_id']
if req['session']['new']:
res['response']['text'] = 'Привет! Это навык Книги. Представься, пожалуйста'
sessionStorage[user_id] = {
'first_name': None,
'prev_answer': ""
}
return
if user is None:
user = User(user_id, get_first_name(req))
if user.get_name() is None:
res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста'
else:
user = User(user_id, get_first_name(req))
res['response']['text'] = 'Приятно познакомиться, ' + user.get_name().title() \
+ '. Я - Алиса. Я могу порекомендовать тебе книгу, дать рецензию на уже ' \
'интересующую или проверить твои знания в литературе!'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
},
{
'title': 'Google Books API',
'url': 'https://developers.google.com/books/docs/overview',
'hide': True
},
{
'title': 'New York Times API',
'url': 'https://developer.nytimes.com/docs/books-product/1/overview',
'hide': True
}
]
else:
if 'рекомендация' in req['request']['nlu']['tokens']:
book, author = random_book()
res['response']['text'] = 'Советую почитать ' + book + ' от автора ' + author + ', ' + user.get_name().title()
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
elif 'тест' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Ты решил пройти тест! По авторам или по жанрам?'
res['response']['buttons'] = [
{
'title': 'По авторам',
'hide': True
},
{
'title': 'По жанрам',
'hide': True
}
]
elif 'авторам' in req['request']['nlu']['tokens']:
questions_authors, answers_authors = randomBooks_and_Authors()
quiz_author = QuizAuthor(questions=questions_authors, answers=answers_authors)
user.startedQuizAuthor(quizAuthor=quiz_author)
user.isTakingQuizAuthor = True
book_author, author_author, varianti = user.quizAuthor.quizAuthor()
res['response']['text'] = 'Назовите автора данной книги: ' + '\n' + book_author
res['response']['buttons'] = [
{
'title': varianti[0],
'hide': True
},
{
'title': varianti[1],
'hide': True
},
{
'title': varianti[2],
'hide': True
},
{
'title': varianti[3],
'hide': True
}
]
elif user.isTakingQuizAuthor:
answer = req['request']['command']
current, total = user.quizAuthor.answer(answer=answer)
book_author, author_author, varianti = user.quizAuthor.quizAuthor()
if current < 5:
res['response']['text'] = 'Ваш нынешний результат: ' + str(total) + '/5' + '\n' + 'Назовите автора данной книги: ' + '\n' + book_author
res['response']['buttons'] = [
{
'title': varianti[0],
'hide': True
},
{
'title': varianti[1],
'hide': True
},
{
'title': varianti[2],
'hide': True
},
{
'title': varianti[3],
'hide': True
}
]
else:
res['response']['text'] = 'Вы прошли тест на литературные знания.' + '\n' + 'Ваш результат: ' + str(total) + '/5'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
user.isTakingQuizAuthor = False
elif 'жанрам' in req['request']['nlu']['tokens']:
questions_genres, answers_genres = randomBook_and_Genre()
quiz_genre = QuizGenre(questions=questions_genres, answers=answers_genres)
user.startedQuizGenre(quizGenre=quiz_genre)
user.isTakingQuizGenre = True
book_genre, genre_genre, varianti_genre = user.quizGenre.quizGenre()
res['response']['text'] = 'Назовите жанр данной книги: ' + '\n' + book_genre
res['response']['buttons'] = [
{
'title': varianti_genre[0],
'hide': True
},
{
'title': varianti_genre[1],
'hide': True
},
{
'title': varianti_genre[2],
'hide': True
},
{
'title': varianti_genre[3],
'hide': True
}
]
elif user.isTakingQuizGenre:
answer_genre = req['request']['command']
current_g, total_g = user.quizGenre.answer(answer=answer_genre)
book_genre, genre_genre, varianti_genre = user.quizGenre.quizGenre()
if current_g < 5:
res['response']['text'] = 'Ваш нынешний результат: ' + str(total_g) + '/5' + '\n' + 'Назовите жанр данной книги: ' + '\n' + book_genre
res['response']['buttons'] = [
{
'title': varianti_genre[0],
'hide': True
},
{
'title': varianti_genre[1],
'hide': True
},
{
'title': varianti_genre[2],
'hide': True
},
{
'title': varianti_genre[3],
'hide': True
}
]
else:
res['response']['text'] = 'Вы прошли тест на литературные знания.' + '\n' + 'Ваш результат: ' + str(total_g) + '/5'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
user.isTakingQuizGenre = False
elif 'рецензия' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Напиши название книги (на английском языке)'
elif 'api' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Что-то еще?'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
elif 'обложка' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Что-то еще?'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
elif user.get_book() is None:
book_name = req['request']['command']
rating, name_book = get_rating(book_name)
if rating is None:
res['response']['text'] = 'Недостаточно данных'
return
author_name_book, description = get_description(book_name)
if description is None:
res['response']['text'] = 'Недостаточно данных'
return
cover = get_cover(book_name)
if cover is None:
res['response']['text'] = 'Недостаточно данных'
return
book = Book(title=name_book, rating=rating, author=author_name_book, desc=description, cover=cover)
user.set_book(book)
res['response']['text'] = name_book + ':' + '\n' + 'Автор - ' + author_name_book + '\n' + 'Рейтинг - ' + str(
rating) + '\n' + 'Описание - ' + description + '\n' + 'Хотите увидеть обложку?'
res['response']['buttons'] = [
{
'title': 'Да',
'hide': True
},
{
'title': 'Нет',
'hide': True
}
]
elif user.get_book():
if 'да' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Перейди по ссылке чтоб посмотреть на обложку'
res['response']['buttons'] = [
{
'title': 'Обложка',
'url': user.get_book().get_cover(),
'hide': True
}
]
else:
res['response']['text'] = 'Что-то еще?'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
user.set_book(None)
else:
res['response']['text'] = 'Ты должен выбрать!'
res['response']['buttons'] = [
{
'title': 'Рекомендация',
'hide': True
},
{
'title': 'Рецензия',
'hide': True
},
{
'title': 'Тест',
'hide': True
}
]
if __name__ == '__main__':
app.run(port=31373)
<file_sep>/README.md
# Alice's skill - Books
## Описание навыка
Навык для Яндекс Алисы, разработанный для работы с книгами при использовании сторонних API.
## Описание работы навыка
Навык запрашивает имя пользователя и предлагает ему на выбор три опции - Рекомендация, Рецензия или Тест, выполняемые сколько угодно раз.
## Подробнее о возможностях навыка
```
1) О функции Рекомендация: возращает рандомную книгу и ее автор. Осуществляется при помощи New York Times Books API.
2) О функции Рецензия: возвращает правильное название, автора, средний рейтинг, описание и, по желанию, обложку интересующей пользователя книги. Осуществляется при помощи Google Books API.
3) О функции Тест: на выбор пользователя начинается тест по авторам или по жанрам. Всего в тесте 5 вопросов с четырьмя вариантами ответов. Осуществляется при помощи New York Times Books API.
```
## Библиотеки и работа с API
1) Используются библиотеки requests, random, flask, logging и json.
2) Два API: New York Times Books API и Google Books API.
New York Times Books API: [link to documentation](https://developer.nytimes.com/docs/book-product/1/overview)
Google Books API: [link to documentation](https://developers.google.com/books/docs/overview)
## Классы
В данном навыке используется 4 класса: классы User, Book, QuizGenre и QuizAuthor.
## Автор проекта
**Askergali Aigerim** - [askergali](https://github.com/askergali)
| 1493806f99e1bac3ecf1158ca84487e62424e8b7 | [
"Markdown",
"Python"
] | 2 | Python | askergali/alice | c213335aa4ffe7229aedabdfaa8adfb69025eff6 | 90daff278d823cc736aa6de9325fdc29fa6fe3b6 |
refs/heads/main | <repo_name>dbushy727/space-invader<file_sep>/app/Commands/PollSpaceInvader.php
<?php
namespace App\Commands;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use LaravelZero\Framework\Commands\Command;
class PollSpaceInvader extends Command
{
/**
* The signature of the command.
*
* @var string
*/
protected $signature = 'poll:spaceinvader';
/**
* The description of the command.
*
* @var string
*/
protected $description = 'Poll the spaceinvader shop and ping if the product page is up';
protected const BASE_URL = 'https://space-invaders.com/spaceshop/product';
protected const KNOWN_PRODUCT_IDS = [21, 30];
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->pollKnownProductPages();
$this->pollUnknownProductPages();
}
protected function pollKnownProductPages()
{
collect(self::KNOWN_PRODUCT_IDS)->each(
fn ($productId) => $this->pollKnownProductPage($productId)
);
}
protected function pollUnknownProductPages()
{
$this->productIds()->each(
fn ($productId) => $this->pollUnknownProductPage($productId)
);
}
protected function isNewProductLink($productLink)
{
$productId = last(explode("/", $productLink));
return !in_array($productId, self::KNOWN_PRODUCT_IDS);
}
protected function pollKnownProductPage($productId)
{
$url = sprintf("%s/%s", self::BASE_URL, $productId);
$this->line("Polling {$url}");
$response = Http::get($url);
$body = $response->body();
if (str_contains($body, 'AVAILABLE<br>SOON') || str_contains($body, 'SOLD OUT')) {
$this->line('Page still contains AVAILABLE SOON or SOLD OUT');
return;
}
$this->sendNotification("Hit: {$url}");
}
protected function productIds(): Collection
{
return collect()
->range(1, 100)
->reject(fn ($num, $key) => in_array($num, self::KNOWN_PRODUCT_IDS))
->values();
}
protected function pollUnknownProductPage(int $productId)
{
$url = sprintf("%s/%s", self::BASE_URL, $productId);
$this->line("Polling {$url}");
$response = Http::get($url);
if ($response->failed()) {
$this->line("Page still fails with error code: {$response->status()}");
return;
}
$this->sendNotification("Hit: {$url}");
}
protected function sendNotification(string $content)
{
Http::post(env('DISCORD_WEBHOOK_URL'), [
'content' => $content,
]);
}
/**
* Define the command's schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
public function schedule(Schedule $schedule): void
{
// $schedule->command(static::class)->everyFiveMinutes();
}
}
<file_sep>/README.md
# Spaceinvader Bot
This bot looks at the space invader shop site and monitors for available products to purchase.
## Two Methods
This bot is utilizing two methods of crawling for different needs.
### Method 1
This method checks product pages it already knows, and checks if their status changes to purchasable. This method utilizes Laravel Zero to simply fetch the site, and check the body for specific strings like "AVAILABLE SOON" or "SOLD OUT".
This method also does a very dumb brute force crawl where it checks for product pages that exist with ids 1-100.
Relevant code is in `app/Commands/PollSpaceInvader.php`
### Method 2
This method utilizes cypress to actually spin up a headless browser and visit the site. It will then find the "next product" button, and look for pages it hasn't seen before. If it finds a new page, it sends out a notification via Discord, and adds it to its simple database of known pages.
Relevant code is in `cypress/integration/crawler/pollForNewProducts.spec.js`
| a2a407591c851d9d637f14e592c355fa0aa632f9 | [
"Markdown",
"PHP"
] | 2 | PHP | dbushy727/space-invader | b08a8ee68dbc52d011d5ef45b4c813662ae035fd | 060bd90cad0c5754d32b8239f01e08310db916e4 |
refs/heads/master | <file_sep>SysDashboard
============
A dashboard for metrics.
Installation
------------
```bash
npm install -g sysdashboard
sysdashboard board:create myboard
cd myboard
sysdashboard server:start 3333
```
Widget
------
A widget displays something: a number, a graph, an image, etc.
Create a new widget:
```bash
cd path/to/myboard
sysdashboard widget:create number
```
This command returns an ID. You can customize the widget here: `path/to/myboard/widgets/{id}/`.
Get the list of available types:
```bash
sysdashboard widget:types
```
Layout
------
The widgets are displayed on a layout.
Create a new layout:
```bash
cd path/to/myboard
sysdashboard layout:create single --add-widget {id}
```
Get the list of available types:
```bash
sysdashboard layout:types
```
Screen
------
By default, the website displays the first screen with the first layout.
You can change the layout of the screen via the menu or the API.
Create a new screen:
```bash
cd path/to/myboard
sysdashboard screen:create {id}
```
You have an access to the screen with the URL: `http://myboard/screen/{id}`
A screen is synchronized to all the browers that display the screen.
Worker
------
A worker is used to collect and/or store data in order to update widgets.
It is an optional feature to extend the board automation.
The worker can change the screens and widgets appearance.
Create a new worker:
```bash
cd path/to/myboard
sysdashboard worker:create
```
This command returns an ID. You can customize the worker here: `path/to/myboard/workers/{id}/`.
API
---
- Change the layout of a screen
- Update the data of a widget
- Send data to a worker
More ?
------
- Create a new type of widget
- Create a new type of layout
<file_sep>#!/bin/bash
node --harmony --harmony-proxies "$@"
<file_sep>#!/usr/bin/env sysdashboard-node
import solfege from "solfegejs";
import cli from "solfegejs-cli";
import server from "solfegejs-server";
import middlewareStatic from "solfegejs-server-static";
import Sysdashboard from "./Sysdashboard";
// Initialize the application
let application = new solfege.kernel.Application(__dirname);
// Add the external bundles
application.addBundle("console", new cli.Console);
application.addBundle("server", new server.HttpServer);
application.addBundle("static", new middlewareStatic.Static);
// Add the internal bundle
application.addBundle("sysdashboard", new Sysdashboard);
let configuration = require(__dirname + "/../config/default");
application.overrideConfiguration(configuration);
// Start the application
application.start();
<file_sep>import solfege from "solfegejs";
/**
* The website bundle
*
* @class Sysdashboard
*/
export default class Sysdashboard
{
/**
* Constructor
*/
constructor()
{
}
}
| e72cf3d40db22fdd2416ec7dde822cd968a9629b | [
"Markdown",
"JavaScript",
"Shell"
] | 4 | Markdown | neolao/sysdashboard | aa202c09b496ad4d48ee756cd3d2e12c263a53a1 | fa33dd9e9464cb46798b527bc5c3a3ef7fd31105 |
refs/heads/master | <file_sep># coordinate_structure.py
# <NAME> / 11.2015
#
# A basic class for dealing with geographic coordinates. Data is stored in a Numpy ndarry, with entries corresponding to rows.
# Basic usage:
# cs = coordinate_struct()
# cs.set_coords(lats, lons, alts, 'geographic')
# cs.set_coords(L, lons, alts, 'L_dipole')
# cs.set_cooords(x,y,z,'ecef')
# cs.transform_to('L_dipole')
#
# ...etc. If the three inputs are of different length, all unique combinations will be stored.
#
#
# To do: Make sure I did all the transformations right.
# Use Cython / numexpr / etc for speed boost
# Incorporate pyproj / pysatel / some other coordinate structure format
import numpy as np
import itertools
#import geopy.distance
#import numexpr as ne
class coordinate_structure(object):
''' Coordinate-holding object'''
def __init__(self, in1= None, in2 = None, in3 = None, datatype=None):
self.type = None
self.data = None
self.xtra_data = None
# Radius of the earth
self.R_earth = 6.3710e6 # Meters
#self.R_earth = geopy.distance.EARTH_RADIUS*1e3
# Radians, degrees
self.d2r = np.pi/180.0
self.r2d = 180.0/np.pi
# Degree rotations between geographic and geomagnetic
self.theta = -10.46; # Shift in theta
self.phi = 71.57; # Shift in phi
self.valid_types = ["geographic", "geomagnetic", "L_dipole", "ecef"]
# If we have data, initialize
if (not in1 is None) and (not in2 is None) and (not in3 is None) and (datatype):
# if (not in1 is None) and (not in2 is None) and (not in3 is None) and (datatype):
# print "Have data!"
# print datatype
self.set_coords(in1, in2, in3, datatype)
def set_coords(self, in1, in2, in3, datatype):
if not datatype in self.valid_types:
print "invalid data type!"
return
self.type = datatype
unique_counts = np.unique([np.size(in1),np.size(in2),np.size(in3)])
if len(unique_counts) == 1:
# easy
#print "single"
if np.size(in1)==1 and np.size(in2) == 1 and np.size(in3) == 1:
self.data = np.atleast_2d([in1, in2, in3])
else:
self.data = np.array([np.array(in1), np.array(in2), np.array(in3)]).T
else:
#print "multing"
# Enumerate all possible combinations of the input data:
# (This works great, but it's slow! An explicit solution might work better)
self.data = np.array([t for t in itertools.product(*[np.array(in1),np.array(in2),np.array(in3)])])
self.data.view('i8,i8,i8').sort(order=['f1'],axis=0)
#print self.data
#print "Loaded data shape: ", np.shape(self.data)
def transform_to(self,target_type):
if not target_type in self.valid_types:
print "invalid data type!"
return
if target_type == self.type:
print "No rotation needed"
return
# First, rotate to ECEF:
#print self.data
self.rotate_to_ECEF()
#print self.data
self.rotate_from_ECEF(target_type)
#print self.data
def rotate_to_ECEF(self):
'''Rotate from current coords to ECEF'''
if self.type == "geographic":
lats = self.data[:,0]
lons = self.data[:,1]
alts = self.data[:,2]
self.data = self.spherical_to_cartesian(lats, lons, alts)
if self.type == "geomagnetic":
lats = self.data[:,0]
lons = self.data[:,1]
alts = self.data[:,2]
xyz = self.spherical_to_cartesian(lats, lons, alts)
# rotate to ECEF:
R = self.rotz(-self.phi).dot(self.roty(-self.theta)).T
self.data = xyz.dot(R)
# self.data = self.rotz(-self.phi).dot(self.roty(-self.theta)).dot(xyz)
if self.type == "L_dipole":
RL = np.abs(self.data[:,0])*self.R_earth
Ro = self.R_earth + self.data[:,2]
#print Ro
dip_angle = np.arccos(np.sqrt(Ro/RL)) # Dip angle in radians
hem = np.sign(self.data[:,0]) # Sign of L (hemisphere notation)
lats = self.r2d*hem*dip_angle
lons = self.data[:,1]
alts = self.data[:,2]
#print "data size: ", np.shape(self.data)
xyz = self.spherical_to_cartesian(lats, lons, alts)
#print "xyz size: ", np.shape(xyz)
# rotate to ECEF:
R = self.rotz(-self.phi).dot(self.roty(-self.theta)).T
self.data = xyz.dot(R)
# self.data = self.rotz(-self.phi).dot(self.roty(-self.theta)).dot(xyz)
#print self.data
self.type = "ecef"
def rotate_from_ECEF(self,target_type):
'''Rotate from ECEF to target type'''
if not (self.type == "ecef"):
print "not in ECEF!"
return
if target_type == "geographic":
self.data = self.cartesian_to_spherical(self.data[:,0],self.data[:,1],self.data[:,2])
self.type = target_type
if target_type == "geomagnetic":
R = self.roty(self.theta).dot(self.rotz(self.phi)).T
self.data = self.data.dot(R)
self.data = self.cartesian_to_spherical(self.data[:,0],self.data[:,1],self.data[:,2])
self.type = target_type
if target_type == "L_dipole":
R = self.roty(self.theta).dot(self.rotz(self.phi)).T
self.data = self.data.dot(R)
self.data = self.cartesian_to_spherical(self.data[:,0],self.data[:,1],self.data[:,2])
lats = self.data[:,0]
lons = self.data[:,1]
alts = self.data[:,2]
L = np.sign(lats)*(self.R_earth + alts)/(self.R_earth*np.power(np.cos(self.d2r*lats),2))
self.data[:,0] = L
self.type=target_type
def spherical_to_cartesian(self, lats, lons, alts):
#print lats, lons, alts
x = (alts + self.R_earth)*np.cos(self.d2r*lats)*np.cos(self.d2r*lons)
y = (alts + self.R_earth)*np.cos(self.d2r*lats)*np.sin(self.d2r*lons)
z = (alts + self.R_earth)*np.sin(self.d2r*lats)
#print x, y, z
return np.atleast_2d(np.array([x, y, z])).T
def cartesian_to_spherical(self, x, y, z):
alts = np.linalg.norm([x,y,z],axis=0)
lons = self.r2d*np.arctan2(y, x);
lats = self.r2d*np.arcsin(z/alts)
alts = alts - self.R_earth
return np.atleast_2d(np.array([lats, lons, alts])).T
# Rotation matrices
def rotz(self,theta):
return np.array([[np.cos(theta*self.d2r), -np.sin(theta*self.d2r), 0],
[np.sin(theta*self.d2r), np.cos(theta*self.d2r), 0],
[0 , 0 , 1]]);
# Rotation matrices
def roty(self,theta):
return np.array([[np.cos(theta*self.d2r), 0, np.sin(theta*self.d2r)],
[0 , 1, 0],
[-np.sin(theta*self.d2r), 0, np.cos(theta*self.d2r)]]);
# Getters:
def lat(self):
if self.type in ["geographic","geomagnetic"]:
return self.data[:,0]
else:
print "No latitude in current system"
def lon(self):
if self.type in ["geographic","geomagnetic","L_dipole"]:
return self.data[:,1]
else:
print "No longitude in current system"
def alt(self):
if self.type in ["geographic","geomagnetic","L_dipole"]:
return self.data[:,2]
else:
print "no altitude in current system"
def len(self):
return np.shape(self.data)[0]
# def __iter__(self):
# return self
# def next(self):
# if
def transform_coords(a, b, c, source, destination):
m = coordinate_structure(a,b,c,source)
m.transform_to(destination)
return m.data
if __name__ == "__main__":
cs = coordinate_structure()
cs.set_coords(3,10,100,"L_dipole")
cs.transform_to("ecef")
print cs.type
print cs.data
# cs.transform_to("L_dipole")
# cs.transform_to("geographic")
<file_sep># The main event! Determine optimal sampling modes for a satellite at a given location, using reinforcement learning.
# import matplotlib as mpl
# mpl.use('Agg')
import numpy as np
import pickle
#from build_database import flux_obj
from scipy import interpolate
import matplotlib.pyplot as plt
#from matplotlib import pyplot as plt
from GLD_file_tools import GLD_file_tools
from satellite import Satellite
import datetime
import ephem
from coordinate_structure import coordinate_structure
from coordinate_structure import transform_coords
from longitude_scaling import longitude_scaling
from ionoAbsorp import ionoAbsorp
import os
#from mpl_toolkits.basemap import Basemap
from precip_model import precip_model
import itertools
from measurement_model import measurement_model
import random
#from scaling import get_time_scaling, get_map_scaling
def get_map_scaling(grid_lats, grid_lons, in_coords, Rmax=1000):
''' Get scaling coefficients, based on squared distance from input coordinates.
Output is a 2d array with dimensions grid_lats, grid_lons
'''
d2r = np.pi/180.0
iLat = in_coords.lat()
iLon = in_coords.lon()
# Great circle distance, in radians -- haversine formula. V E C T O R I Z E D
a = np.outer(np.sin(d2r*(grid_lats - iLat)/2.0)**2, np.ones_like(grid_lons))
b = np.outer(np.cos(d2r*iLat)*np.cos(d2r*grid_lats), np.sin(d2r*(grid_lons - iLon)/2.0)**2)
dists = 6371*2*np.arcsin(np.sqrt(a + b))
# Select entries around a small patch, and scale quadratically:
weights = (np.maximum(0, Rmax - dists))**2
# Normalize selection to 1
return weights/np.sum(weights)
# return weights/np.max(weights)
def get_time_scaling(grid_times, cur_coords, cur_time):
'''Coarsely bin into a local time of day, with the idea that
lightning has some hourly time dependence (i.e., rarely lightning in the morning)
'''
if len(grid_times)==1:
return 1.0
else:
d2r = np.pi/180.0
if not cur_coords.type=='geographic':
print "Not in Geographic coordinates!"
# time_bins = np.linspace(0,23,4) # Vector of times to quantize to
d = cur_coords.lon()[0]*24/360 # Hour shift in longitude
LT = cur_time - datetime.timedelta(hours=d)
d2r = np.pi/180.0
# Great circle distance, in radians -- haversine formula. V E C T O R I Z E D
b = np.sin(d2r*(360/24)*(LT.hour - grid_times)/2.0)
dists = 2*24*np.arcsin(np.abs(b))
weights = np.maximum(0,(48 - dists))**2
return weights/np.sum(weights)
def fluxMDP(start_time = datetime.datetime(2015,11,01,01,45,00),
stop_time = datetime.datetime(2015,11,1,2,45,00),
storage_penalty = 1,
detector_area = 1e3,
switching_penalty = 0.05,
smoothing_radius = 1000,
alpha = 0.9,
gamma = 0.1,
greed_rate = 2,
fixed_greed = None,
outDir = 'MDP_saves',
gActs = ['continuous','off'],
previous_measurements = None,
stored_policy = None,
num_lats =90,
num_lons =180,
num_times=1):
db_name = "database_dicts.pkl"
print "Database name: ", db_name
print "start time: ", start_time
print "stop time: ", stop_time
print "storage penalty: ", storage_penalty
print "switching penalty: ", switching_penalty
print "smoothing radius: ", smoothing_radius
print "alpha: ", alpha
print "gamma: ", gamma
print "fixed_greed: ",fixed_greed
print "greed rate: ", greed_rate
print "outDir: ",outDir
print "Actions: ", gActs
print "num_times: ",num_times
if previous_measurements:
print "Loading previous measurements file " + previous_measurements
using_previous = True
with open(previous_measurements,'rb') as file:
prev_db = pickle.load(file)
else:
using_previous = False
# ------------------- Initial setup --------------------
# GLD_root = 'alex/array/home/Vaisala/feed_data/GLD'
# NLDN_root = 'alex/array/home/Vaisala/feed_data/NLDN'
GLD_root = 'GLD'
sat_TLE = ["1 40378U 15003C 15293.75287141 .00010129 00000-0 48835-3 0 9990",
"2 40378 99.1043 350.5299 0153633 201.4233 158.0516 15.09095095 39471"]
# Satellite object:
sat = Satellite(sat_TLE[0], sat_TLE[1],'Firebird 4')
# Measurement object:
f = measurement_model(database = db_name, GLD_root=GLD_root, multiple_bands = True)
# Start time:
# start_time = "2015-11-01T00:45:00"
tStep = datetime.timedelta(seconds=30) # Step size thru model
cur_time = start_time
mid_time = start_time + datetime.timedelta(days=15) # Midpoint of greediness-increasing curve
max_greed = 0.95 # Maximum greed asypmtote
#cur_time = datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S")
# Stop time:
#stop_time = datetime.datetime(2015,11,1,2,45,00)
# # State space:
# gLats = np.linspace(-90,90,90)
# gLons = np.linspace(-180,180,180)
# #gTimes = np.linspace(0,24,4)
# gTimes = np.linspace(0,24,1)
# # gActs = ['continuous','off','low','mid','high']
bands = dict()
bands['low'] = [1,2]
bands['mid'] = [3, 4, 5]
bands['high']= [6, 7, 8]
# # Tweaking parameters:
# storage_penalty = 1
# switching_penalty = 0.05
# alpha = 0.9
# gamma = 0.1
# greed_rate = 2 # Percent increase per four hours
# greed = 0.01
if fixed_greed:
greed = fixed_greed
else:
greed = 0
# outDir = 'MDP_saves'
if not os.path.exists(outDir):
os.makedirs(outDir)
reward_table = []
# Q matrix
if stored_policy:
print "Using previously-computed policy"
using_stored_policy = True
with open(stored_policy,'rb') as file:
Q = pickle.load(file)
else:
using_stored_policy = False
Q = np.zeros([num_lats, num_lons, num_times, np.size(gActs)])
# State space:
gLats = np.linspace(-90,90,np.shape(Q)[0])
gLons = np.linspace(-180,180,np.shape(Q)[1])
gTimes = np.linspace(0,24,np.shape(Q)[2])
# Log simulation parameters in a dictionary (text would have been fine too)
odb = dict()
odb['lats'] = gLats
odb['lons'] = gLons
odb['times'] = gTimes
odb['actions'] = gActs
odb['bands'] = bands
odb['start_time'] = start_time
odb['stop_time'] = stop_time
odb['storage_penalty'] = storage_penalty
odb['detector_area'] = detector_area
odb['switching_penalty'] = switching_penalty
odb['smoothing_radius'] = smoothing_radius
odb['alpha'] = alpha
odb['gamma'] = gamma
odb['greed_rate'] = greed_rate
odb['fixed_greed'] = fixed_greed
odb['outDir'] = outDir
odb['gActs'] = gActs
odb['previous_measurements'] = previous_measurements
odb['stored_policy'] = stored_policy
odb['num_lats'] = num_lats
odb['num_lons'] = num_lons
odb['num_times']= num_times
with open(outDir + '/odb.pkl','wb') as file:
pickle.dump(odb, file)
sat.compute(cur_time)
# Get time scaling weights:
time_weight = get_time_scaling(gTimes, sat.coords, cur_time)
sat.coords.transform_to('geomagnetic')
# Get distance interpolating weights:
map_weights = get_map_scaling(gLats, gLons, sat.coords, Rmax=smoothing_radius)
# 3d weight (lat, lon, time):
W = map_weights[:,:,None]*time_weight
print "W isnans: ",np.sum(np.isnan(W))
print "Q isnans: ",np.sum(np.isnan(Q))
action = gActs[0]
print "Starting run from ", cur_time
ind = 0 # iteration counter
#for ind in range(100):
while cur_time < stop_time:
#try:
#print "i: ", ind
#print "mod i: ", np.mod(ind,10)
# select an action
prev_action = action
brains = np.random.choice(['greedy','adventurous'],p=[greed, 1.0-greed])
print "Greed factor: ", greed
# ------------------- Use previously-computed measurements only: ---------------------
if using_previous:
if cur_time in prev_db:
avail_measurements = prev_db[cur_time].keys()
#Q_inds = [gActs.index(a) for a in avail_measurements if a in gActs]
print "available measurements: ", avail_measurements
if brains == 'greedy':
#a_tmp = np.argmax([np.sum(Q[:,:,:,i]*W) for i in Q_inds])
a = np.argmax([np.sum(Q[:,:,:,gActs.index(i)]*W) for i in gActs])
#a = Q_inds[a_tmp]
action = gActs[a]
elif brains == 'adventurous':
# a = np.random.choice(Q_inds)
action = np.random.choice(gActs)
#action = gActs[a]
a = gActs.index(action)
meas = prev_db[cur_time][action]
if action =='off':
reward = 0 - switching_penalty*(not(action==prev_action))
elif action =='continuous':
reward = meas*detector_area - storage_penalty - switching_penalty*(not(action==prev_action))
elif action in ['low','mid','high']:
reward = meas*detector_area - (len(bands[action])/8.0)*storage_penalty- switching_penalty*(not(action==prev_action))
else:
# Missing stored data --- escape current iteration, increment clock, try again:
cur_time += tStep
continue
else:
# ------------------ Compute fresh measurements: -------------------------------------
if brains =='greedy':
a = np.argmax([np.sum(Q[:,:,:,i]*W) for i in range(len(gActs))])
action = gActs[a]
elif brains =='adventurous':
action = np.random.choice(gActs)
a = gActs.index(action)
#print "Feeling", brains,":",action
#action = 'continuous' #random.choice(gActs)
#a = gActs.index(action)
# take a measurement, calculate reward:
if action =='off':
meas = 0
reward = 0 - switching_penalty*(not(action==prev_action))
if action =='continuous':
meas = np.sqrt(f.get_measurement(cur_time, sat.coords, mode='continuous'))
# reward = meas*detector_area - storage_penalty*(action not in ['off']) - switching_penalty*(not(action==prev_action))
reward = meas*detector_area - storage_penalty - switching_penalty*(not(action==prev_action))
if action in ['low','mid','high']:
meas = np.sqrt(f.get_measurement(cur_time, sat.coords, mode='banded',bands=bands[action]))
# reward = meas*detector_area - (len(bands[action])/8.0)*storage_penalty*(action not in ['off']) - switching_penalty*(not(action==prev_action))
reward = meas*detector_area - (len(bands[action])/8.0) - switching_penalty*(not(action==prev_action))
print "action: ", action
#cur_state_continuous = [sat.coords.lat()[0], sat.coords.lon()[0], cur_time, action]
cur_state_continuous = [sat.coords, cur_time, action]
# Get Q(t,a)
Qcur = np.sum(Q[:,:,:,a]*W)
print "Qcur: ", Qcur
# increment timestep:
cur_time += tStep
# Update satellite position for t+1:
sat.compute(cur_time)
#geo_coords = sat.coords # Save geographic longitude for time binning on the next iteration
# Get time scaling weights at t+1:
time_weight_next = get_time_scaling(gTimes, sat.coords, cur_time)
# Back to geomagnetic (time weights need geographic):
sat.coords.transform_to('geomagnetic')
# Get distance interpolating weights at t+1:
map_weights_next = get_map_scaling(gLats, gLons, sat.coords, Rmax=smoothing_radius)
# 3d weight (lat, lon, time):
W_next = map_weights_next[:,:,None]*time_weight_next
# Get max{a} Q(t+1,a):
# Qmax = np.max([np.sum(Q[:,:,i]*map_weights) for i in range(len(gActs))])
Qmax = np.max([np.sum(Q[:,:,:,i]*W_next) for i in range(len(gActs))])
print "Qmax: ",Qmax
# update Q
# tmp2 = alpha*(reward + gamma*Qmax - Qcur)*map_weights
# print "tmp2 is: ",np.shape(tmp2)
#Q[:,:,a] = Q[:,:,a] + alpha*(reward + gamma*Qmax - Qcur)*map_weights
Q[:,:,:,a] = Q[:,:,:,a] + alpha*(reward + gamma*Qmax - Qcur)*W
#raw_input("idling...")
# Rename the weights for the next round:
W = W_next
# map_weights = map_weights_next
# time_weight = time_weight_next
# Store the current state, action, and reward
cv = [cur_state_continuous, meas, reward]
print cv
reward_table.append(cv)
# Increment greediness:
if not fixed_greed:
greed = max_greed/(1 + np.exp(-greed_rate*((cur_time - mid_time).total_seconds()/(24*3600))))
# if (np.mod(cur_time.hour, 4)==0) and (cur_time.minute == 0) and (cur_time.second == 0):
# # Get greedier:
# print "Getting greedier..."
# greed = greed*(1 + greed_rate/100.0)
if (np.mod(cur_time.day,2)==0) and (cur_time.hour ==0) and (cur_time.minute == 0) and (cur_time.second == 0):
print "Saving progress..."
# Archive where we're at:
with open(outDir + '/data_i%g.pkl' % ind,'wb') as file:
pickle.dump(reward_table,file)
reward_table = []
with open(outDir + '/Q_i%g.pkl' % ind,'wb') as file:
pickle.dump(Q,file)
ax_x = int(np.ceil(np.sqrt(len(gTimes))))
ax_y = 1
while (ax_x*ax_y < len(gTimes)):
ax_y += 1
# Q plots
Q_clims = [np.min(Q), np.max(Q)]
for act in gActs:
fig, ax = plt.subplots(ax_x, ax_y)
if len(gTimes) == 1:
ax.pcolor(gLons, gLats, Q[:,:,0,gActs.index(act)]/np.max(Q),clim=Q_clims)
ax.set_title(gTimes[0])
ax.axis('off')
ax.scatter(sat.coords.lon(),sat.coords.lat(),marker='x')
fig.suptitle('action: %s, %g iterations: \n%s' % (act, ind, cur_time))
else:
ax = ax.flat
for x in range(len(gTimes)):
ax[x].pcolor(gLons, gLats, Q[:,:,x,gActs.index(act)]/np.max(Q), clim=Q_clims)
ax[x].set_title(gTimes[x])
ax[x].axis('off')
ax[x].scatter(sat.coords.lon(),sat.coords.lat(),marker='x')
fig.suptitle('action: %s, %g iterations: \n%s' % (act, ind, cur_time))
figname = outDir + '/Q_%g_%s.png' % (ind, act)
print "Save filename: ", figname
plt.savefig(figname)
plt.close(fig)
# Policy plot
policy = np.argmax(Q, axis=3)
#print np.shape(policy)
#print np.min(policy)
fig, ax = plt.subplots(ax_x, ax_y)
if len(gTimes) == 1:
ax.pcolor(gLons, gLats, policy[:,:,0])
ax.set_title(gTimes[0])
ax.axis('off')
else:
ax = ax.flat
for x in range(np.size(gTimes)):
ax[x].pcolor(gLons, gLats, policy[:,:,x])
ax[x].set_title(gTimes[x])
ax[x].axis('off')
fig.suptitle('Policy Evaluation: %g iterations: \n%s' % (ind, cur_time))
figname = outDir + '/policy_%g_%s.png' % (ind, act)
print "save filename: ", figname
plt.savefig(figname)
plt.close(fig)
# except:
# print "Something messed up! Trying the next step"
# cur_time += tStep
ind += 1
if __name__ =='__main__':
fluxMDP(gActs=['off','continuous'])
<file_sep>import numpy as np
import pickle
from build_database import flux_obj
from scipy import interpolate
# from sklearn.svm import SVR
# from sklearn.svm import NuSVR
from matplotlib import pyplot as plt
from coordinate_structure import coordinate_structure
def plot_precip(x, y, data):
plt.figure()
plt.pcolor(x, y, np.log10(data.T))
plt.clim([-4, 4])
if __name__ == "__main__":
with open('database_multiple.pkl','rb') as file:
db = pickle.load(file)
print db.keys()
for lat in db.keys():
x = db[lat].t
y = db[lat].coords.lat()
data = db[lat].N
plot_precip(x,y,data)
plt.title(lat)
plt.show()
# px = int(np.ceil(np.sqrt(np.size(db.keys()))))
# py = int(np.ceil(np.sqrt(np.size(db.keys()))))
# f2, axarr = plt.subplots(px,py)
# axa = axarr.flatten()
# for ind, ll in enumerate():
# axa[ind].plot(t,N_totals[:,ind])
# axa[ind].set_ylim([-4,2])
# axa[ind].set_xlabel(ll)
# plt.setp([a.get_xticklabels() for a in axarr[:,:].flatten()], visible=False)
# plt.setp([a.get_yticklabels() for a in axarr[:,:].flatten()], visible=False)
# plt.show()
<file_sep>import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import pickle
from build_database import flux_obj
# from scipy import interpolate
# from matplotlib import pyplot as plt
# from GLD_file_tools import GLD_file_tools
# from satellite import Satellite
import datetime
# import ephem
# from coordinate_structure import coordinate_structure
# from coordinate_structure import transform_coords
# from longitude_scaling import longitude_scaling
# from ionoAbsorp import ionoAbsorp
import os
# from mpl_toolkits.basemap import Basemap
# from precip_model import precip_model
import itertools
# from measurement_model import measurement_model
import random
# from scaling import get_time_scaling, get_map_scaling
import fluxMDP
# ---- more options run:
name = 'full'
gActs = ['off','continuous','low','mid','high']
start_time= datetime.datetime(2015,10, 8,18,30,00)
stop_time = datetime.datetime(2015,11,22,23,00,00)
fluxMDP.fluxMDP(outDir = "outputs/run_2_" + name,
start_time = start_time,
stop_time=stop_time,
gActs = gActs)<file_sep>
import numpy as np
import pickle
#from build_database import flux_obj
from scipy import interpolate
# from sklearn.svm import SVR
# from sklearn.svm import NuSVR
from matplotlib import pyplot as plt
from coordinate_structure import coordinate_structure
import itertools
import geopy.distance
class precip_model(object):
def __init__(self,database="database.pkl", multiple_bands=False):
self.R_earth = geopy.distance.EARTH_RADIUS
self.d2r = np.pi/180.0
self.path_atten = -12 # db per 1000 km attenuation (approximation of decay for earth-ionsphere waveguide)
with open(database,'rb') as file:
self.db = pickle.load(file)
in_lats = sorted(self.db.keys())
self.multiple_bands = multiple_bands
# Simple dataset using total flux -- interpolates input latitude, output latitude, time.
N = []
S = []
for i in in_lats:
obj = self.db[i]
N.append(obj['N'])
S.append(obj['S'])
N = np.array(N).swapaxes(1,2)
S = np.array(S).swapaxes(1,2)
self.I0 = obj['I0']
self.N_interp = interpolate.RegularGridInterpolator((in_lats, obj['coords'].lat(), obj['t']), N, fill_value=0,bounds_error=False)
self.S_interp = interpolate.RegularGridInterpolator((in_lats, obj['coords'].lat(), obj['t']), S, fill_value=0,bounds_error=False)
if multiple_bands:
# Split into multiple bands -- input latitude, output latitude, energy, time.
N_E = []
S_E = []
for i in in_lats:
obj = self.db[i]
N_E.append(obj['N_E'])
S_E.append(obj['S_E'])
N_E = np.array(N_E).swapaxes(1,3)
S_E = np.array(S_E).swapaxes(1,3)
# print np.shape(N_E)
self.E_bands = np.linspace(1,np.shape(N_E)[2], np.shape(N_E)[2])
# print self.E_bands
self.N_E_interp = interpolate.RegularGridInterpolator((in_lats, obj['coords'].lat(), self.E_bands, obj['t']), N_E, fill_value=0,bounds_error=False)
self.S_E_interp = interpolate.RegularGridInterpolator((in_lats, obj['coords'].lat(), self.E_bands, obj['t']), S_E, fill_value=0,bounds_error=False)
def get_precip_at(self, in_lat, out_lat, t):
''' in_lat: Flash latitude (degrees)
out_lat: Satellite latitude (degrees)
t: Time elapsed from flash (seconds)
'''
# print in_lat
# print out_lat
# print t
#inps = np.array([t for t in itertools.product(*[np.array(in_lat),np.array(out_lat),np.array(t)])])
#inps = self.tile_keys(np.array([in_lat, out_lat]), t)
#print "inps: ", inps
# Model is symmetric around northern / southern hemispheres (mag. dipole coordinates):
# If in = N, out = N --> Northern hemisphere
# in = N, out = S --> Southern hemisphere
# in = S, out = N --> Southern hemisphere
# in = S, out = S --> Northern hemisphere
use_southern_hemi = (in_lat > 0) ^ (out_lat > 0)
inps = self.tile_keys(np.array([np.abs(in_lat), np.abs(out_lat)]), t)
if use_southern_hemi:
return self.S_interp(inps)
else:
return self.N_interp(inps)
def get_multiband_precip_at(self, in_lat, out_lat, energy, t):
if not self.multiple_bands:
print "No multi-band!"
else:
use_southern_hemi = (in_lat > 0) ^ (out_lat > 0)
inps = self.tile_keys(np.array([np.abs(in_lat), np.abs(out_lat), energy]), t)
# inps = self.tile_keys(np.array([in_lat, out_lat, energy]), t)
if use_southern_hemi:
return self.S_E_interp(inps)
else:
return self.N_E_interp(inps)
def tile_keys(self, key1, key2):
return np.vstack([np.outer(key1, np.ones(np.size(key2))), key2]).T
def get_longitude_scaling(self, inp_lat, inp_lon, out_lon, I0=None, db_scaling = False):
''' inp_lat: Scalar latitude
inp_lon: Scalar longitude
out_lon: vector of longitudes to compute at
'''
# ----------- Old version: In all your computed measurements, rats (12.2.2015) ----
#dist_lon = (self.R_earth)*np.abs(inp_lon - out_lon)*self.d2r*np.cos(self.d2r*inp_lat)*1e-3
#vals = dist_lon*self.path_atten
# ----------- New version: Actually works, does wraparound properly -------
b = np.cos(self.d2r*inp_lat)*np.sin(self.d2r*(inp_lon - out_lon)/2.0)
dist_lon = self.R_earth*2*np.arcsin(np.abs(b))
vals = dist_lon*self.path_atten/1000.0
if db_scaling:
return vals
else:
if not I0:
return np.power(10,vals/10.0)
else:
return np.power(10,vals/10.0)*(I0**2)/(self.I0**2)
if __name__ =="__main__":
m = precip_model("database_dicts.pkl",multiple_bands=True)
t = np.linspace(0,30,300)
tmp = m.get_multiband_precip_at(30,45,5,t)
plt.plot(t,tmp)
plt.show()
#tmp = [m.get_precip_at(30,45,x,t,"N") for x in m.E_bands]
#print tmp
# t = np.linspace(0,30,100)
# out_lats = np.linspace(30,70,60)
# in_lat = 19
# res = []
# for o in out_lats:
# points = m.tile_keys((in_lat, o), t)
# res.append(m.N_interp(points))
# res = np.log10(np.array(res))
# plt.pcolor(t, out_lats, res)
# plt.clim([-4,4])
# plt.show()
<file_sep>#import threading
import time
#from Queue import Queue
import logging
import numpy as np
import os
import datetime
#import matplotlib
#matplotlib.use('GTKAgg')
#from matplotlib import pyplot as plt
#from mpl_toolkits.basemap import Basemap
import datetime
#import ephem
import math
#from StreamReader import StreamReader
#import json
import fnmatch
# ----------------------------------------------------------
# A set of modules to quickly search and parse GLD entries
# ----------------------------------------------------------
class GLD_file_tools(object):
def __init__(self,filepath, prefix='GLD'):
self.GLD_root = filepath
self.file_list = []
self.suffix = '.dat'
self.prefix = prefix
#self.refresh_directory()
def refresh_directory(self):
''' Get file list within directory '''
logging.info('Refreshing file list')
self.file_list = []
# Get datetime objects for each file in directory:
for root, dirs, files in os.walk(self.GLD_root):
if file.endswith(self.suffix):
print file
self.file_list.append([(datetime.datetime.strptime(file,self.prefix + '-%Y%m%d%H%M%S.dat')),
(os.path.join(root,file))])
#filepaths.append(os.path.join(root,file))
#startdates.append(datetime.datetime.strptime(file,'GLD-%Y%m%d%H%M%S.dat'))
self.file_list.sort(key=lambda tup: tup[0])
#logging.info('Refreshed file list')
#print file_list
# def get_filename(self, t):
# '''returns a subdirectory string -- just here to avoid
# a ton of redundant string parsing'''
# folder = datetime.datetime.strftime(t,'%Y-%m-%d')
# files = os.listdir(os.path.join(self.GLD_root,folder))
# file_list = []
# for file in files:
# if file.endswith(self.suffix):
# print file
# file_list.append([(datetime.datetime.strptime(file,self.prefix + '-%Y%m%d%H%M%S.dat')),
# (os.path.join(self.GLD_root,file))])
# file_list.sort(key=lambda tup: tup[0])
# return file_list[-1] # newest file
def get_file_at(self,t):
''' t: datetime object
Finds the last file in self.file_list with time less than t
'''
#startfile = filter(lambda row: row[0] <= t, self.file_list)[-1]
#startfiles = filter(lambda row: row[0] <= t, self.file_list)
# if len(startfiles) > 0:
# return startfiles[-1]
# else:
# logging.info("No files found!")
# return
folder = datetime.datetime.strftime(t,'%Y-%m-%d')
if not os.path.exists(os.path.join(self.GLD_root,folder)):
return None, None
files = os.listdir(os.path.join(self.GLD_root,folder))
file_list = []
for file in files:
if file.endswith(self.suffix):
#print file
file_list.append([(datetime.datetime.strptime(file,self.prefix + '-%Y%m%d%H%M%S.dat')),
(os.path.join(self.GLD_root,folder,file))])
file_list.sort(key=lambda tup: tup[0])
#logging.info(file_list)
return file_list[-1] # newest file
def load_flashes(self, t, dt = datetime.timedelta(0,0,0,0,1,0)):
'''filepath: GLD file to sift thru
t: datetime object to search around
dt: datetime.timedelta
returns: A list of tuples: <time ob
'''
filetime,filepath = self.get_file_at(t)
if filetime is None:
return None, None
else:
tprev = t - dt
#print t
#print tprev
#buff_size = 100000 # bytes
# Binary search thru entries:
imax = np.floor(os.path.getsize(filepath)).astype('int')
imin = 0
thefile = open(filepath,'r')
# Find closest index to target time:
t_ind = self.recursive_search_kernel(thefile, t, imin, imax)
#print self.datetime_from_row(self.parse_line(thefile,t_ind))
# Find closest index to window time:
tprev_ind = self.recursive_search_kernel(thefile,tprev,imin,imax)
#print self.datetime_from_row(self.parse_line(thefile,tprev_ind))
if (t_ind is None) or (tprev_ind is None):
return None, None
# Load rows between tprev_ind and t_ind:
rows = []
times = []
while (thefile.tell() < t_ind):
curr_line = self.parse_line(thefile,thefile.tell())
rows.append(curr_line)
times.append(self.datetime_from_row(curr_line))
logging.info(" Found " + str(len(rows)) + " entries between " + str(tprev) + " and " + str(t))
if len(rows) > 0:
return np.asarray(rows), np.asarray(times)
else:
return None, None
def recursive_search_kernel(self, thefile, target_time, imin, imax, n= 0 ):
''' Recursively searches thefile (previously open) for the closest entry
to target_time (datetime object)
'''
imid = imin + ((imax - imin)/2)
#imid = ((imax-imin)/2)
l = self.parse_line(thefile,imid)
if l is None:
return None
#print l
y,m,d,H,M,S = l[0:6].astype('int')
curr_time = datetime.datetime(y,m,d,H,M,S)
if n > 50:
print 'max recursions!'
return None
if abs(imin - imax) <= 100:
#print n, imin, imax, imid, imax-imin, curr_time
return imin
else:
if curr_time > target_time:
#print 'too high: ',imin, imax, imid, imax-imin, curr_time
imax = imid
#imax -=1
else:
#print 'too low: ',imin, imax, imid, imax-imin, curr_time
imin = imid
#imin += 1
# Uncomment this to show recursion (hella sweet)
#print imin, imax, imax-imin, curr_time
return self.recursive_search_kernel(thefile,target_time,imin,imax,n+1)
def parse_line(self, thefile, theindex, n=0):
'''
Returns a parsed line; recursively skips forward if line isn't full-length
'''
thefile.seek(theindex,0)
line = thefile.readline()
vec = line.split('\t')
if n > 5:
logging.info("Failed to find an entry")
return None
if len(vec)==25:
return np.array(vec[1:11],'float')
else:
# if (thefile.tell() == theindex):
# # At end of file -- jump back a few lines, use that value
# logging.info("Hit end of file hit -- jumping backwards " + str(n) + ' ' + str(theindex))
# thefile.seek(theindex - (n+1)*200,0) # Healthy line is ~96 long
return self.parse_line(thefile=thefile,theindex=thefile.tell(), n=(n+1))
def datetime_from_row(self, row):
y,m,d,H,M,S,n = row[0:7].astype('int')
micros = n/1000
return datetime.datetime(y,m,d,H,M,S,micros)
# ---------------------------
# Main block
# ---------------------------
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-10s) %(message)s',
)
GLD_root = 'alex/array/home/Vaisala/feed_data/GLD'
t = datetime.datetime(2015,04,02,16,20,00)
#startfile, startfile_time = get_file_at(t)
#startfile ='alex/array/home/Vaisala/feed_data/GLD/2015-03-26/GLD-201503260223.dat'
print 'initializing'
G = GLD_file_tools(GLD_root)
print 'doing'
#G.load_flashes(t)
for hours in xrange(0,24):
for mins in xrange(0,60):
f = G.load_flashes(datetime.datetime(2015,04,02, hours, mins,0))
<file_sep># Plot an event from the saved SVR:
import numpy as np
import pickle
from build_database import flux_obj
from sklearn.svm import SVR
from sklearn.svm import NuSVR
from matplotlib import pyplot as plt
from coordinate_structure import coordinate_structure
with open('S.pkl','rb') as file:
S = pickle.load(file)
with open('database_lat.pkl','rb') as file:
db = pickle.load(file)
L = []
for k in db.keys():
#print k[3]
L.extend([k[3]])
L = sorted(np.unique(L))
print L
lat = 30
LP = 5.39
I0 = -200000.0
t = np.linspace(0,30,600)
N = []
for ind, val in enumerate(L):
a = np.outer([lat,LP,I0, val], np.ones(600))
b = t
# print np.shape(a)
# print np.shape(b)
X = np.vstack([ a, b ]).T
tmp = S.predict(X)
print np.shape(tmp)
N.append(tmp)
print np.shape(N)
N = np.maximum(0.0, N)
N_log = np.maximum(-100, np.log10(N))
cs = coordinate_structure(L,[-10],[0],'L_dipole')
cs.transform_to('geomagnetic')
print cs.lat()
plt.figure()
plt.pcolor(t,np.flipud(cs.lat()), N_log)
plt.colorbar()
plt.show()
<file_sep># Let's try some machine learning! On a very small set!
import numpy as np
import pickle
from build_database import flux_obj
from sklearn.svm import SVR
from sklearn.svm import NuSVR
from matplotlib import pyplot as plt
with open('database_lat.pkl','rb') as file:
db = pickle.load(file)
print db.keys()
S = NuSVR(kernel='rbf')
X = []
Y = []
for k in db.keys():
#k = db.keys()[5]
# print np.array(k)
t = np.linspace(0,db[k].RES_FINT,db[k].NUM_T)
#X = np.atleast_2d(t).T
#Y = np.power(10,db[k].N)
inp = np.vstack([np.outer(np.array([k[0],k[3]]), np.ones(int(db[k].NUM_T))), t]).T
X.extend(inp)
Y.extend(np.power(10,db[k].N))
#Y.extend(db[k].N)
ramp = np.arange(np.size(Y))
np.random.shuffle(ramp)
n_train = 50000
#n_train = np.size(Y) - 1000
n_test = 10000
train_mask = ramp[0:n_train]
test_mask = ramp[n_train+1:n_train + n_test + 1]
# print "Max ramp: ", np.max(ramp)
# print "Max shuf: ", np.max(ramp)
# plt.plot(train_mask)
# plt.show()
# print np.shape(train_mask)
# print np.shape(inp)
#inp2 = np.vstack([inp, t])
X = np.array(X)
Y = np.array(Y)
print "X: ", np.shape(X)
print "Y: ", np.shape(Y)
print "isnans: ", np.sum(np.isnan(Y))
print "Fitting to S..."
S.fit(X[train_mask,:],Y[train_mask])
print "Saving S "
with open('S.pkl','wb') as file:
pickle.dump(S, file, pickle.HIGHEST_PROTOCOL)
# plt.figure()
plt.plot(Y[test_mask],color='red',marker='.')
plt.plot(S.predict(X[test_mask,:]))
plt.show()
<file_sep>import numpy as np
import pickle
#from build_database import flux_obj
from GLD_file_tools import GLD_file_tools
from satellite import Satellite
import datetime
import ephem
from coordinate_structure import coordinate_structure
from coordinate_structure import transform_coords
from longitude_scaling import longitude_scaling
import os
from precip_model import precip_model
class measurement_model(object):
'''Instantiate this bad boy to make precipitation measurements'''
def __init__(self,
database='database.pkl',
GLD_root = 'alex/array/home/Vaisala/feed_data/GLD',
multiple_bands=False):
self.m = precip_model(database, multiple_bands)
self.RES_DT = self.m.db[self.m.db.keys()[0]]['RES_DT']
self.RES_FINT = self.m.db[self.m.db.keys()[0]]['RES_FINT']
self.td = datetime.timedelta(seconds = 5 + self.RES_FINT) # Maximum previous time to examine flashes in.
# Ideally 2*self.RES_INT to assure we don't miss anything.
# Lightning database
self.gld = GLD_file_tools(GLD_root, prefix='GLD')
# Column indices
self.lat_ind = 7;
self.lon_ind = 8;
self.mag_ind = 9;
def get_measurement(self, in_time, coordinates, mode='continuous', bands=None):
''' Take a flux measurement at a given time and location, with a given sensor setting'''
# Get flashes within timeframe:
flashes, flash_times = self.gld.load_flashes(in_time, self.td)
if flashes is None:
print "No flashes found at ", in_time
return 0.0
flashes = flashes[:,(self.lat_ind, self.lon_ind, self.mag_ind, self.mag_ind)]
flash_coords = transform_coords(flashes[:,0], flashes[:,1], np.zeros_like(flashes[:,0]), 'geographic', 'geomagnetic')
flashes[:,:2] = flash_coords[:,:2]
flashes[:,3] = [(in_time - s).microseconds*1e-6 + (in_time - s).seconds for s in flash_times]
# So! No we have an array of relevant flashes -- lat, lon, mag, time offset.
# Let's model the flux at the satellite.
flux = 0
time_sampling_vector = np.linspace(-self.RES_FINT,0,np.round(self.RES_FINT/self.RES_DT))
if mode=='continuous':
for f in flashes:
#print td.seconds - f[3]
flux += np.sum( self.m.get_precip_at(f[0], coordinates.lat(), time_sampling_vector + f[3]) *
self.m.get_longitude_scaling(f[0], f[1], coordinates.lon(), I0=f[2]) * self.RES_DT )
if mode=='banded':
for f in flashes:
flux += np.sum(( np.array([self.m.get_multiband_precip_at(f[0],
coordinates.lat(), energy,
time_sampling_vector + f[3]) for energy in bands]) *
self.m.get_longitude_scaling(f[0], f[1], coordinates.lon(), I0=f[2]) * self.RES_DT ))
# #
return flux
if __name__== "__main__":
# -------------- Here's how to create a satellite and take some flux measurements: -------------
#GLD_root = 'alex/array/home/Vaisala/feed_data/GLD'
#NLDN_root = 'alex/array/home/Vaisala/feed_data/NLDN'
GLD_root = 'GLD'
sat_TLE = ["1 40378U 15003C 15293.75287141 .00010129 00000-0 48835-3 0 9990",
"2 40378 99.1043 350.5299 0153633 201.4233 158.0516 15.09095095 39471"]
# Satellite object:
sat = Satellite(sat_TLE[0], sat_TLE[1],'Firebird 4')
# Measurement object:
f = measurement_model(database = "database_dicts.pkl", GLD_root = GLD_root, multiple_bands = True)
# ---- Do The Thing:
inTime = "2015-11-01T00:45:00"
plottime = datetime.datetime.strptime(inTime, "%Y-%m-%dT%H:%M:%S")
sat.compute(plottime)
sat.coords.transform_to('geomagnetic')
# bands is a list of energy bands to sample at (depending on database, 1 thru 8)
print "From banded measurement (all on):"
print f.get_measurement(plottime, sat.coords, mode='banded',bands=f.m.E_bands)
print "From single measurement:"
print f.get_measurement(plottime, sat.coords, mode='continuous',bands=f.m.E_bands)
<file_sep>import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import pickle
import datetime
import os
import itertools
import random
import fluxMDP
import string
# Random run:
name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
gActs = np.random.choice([['off','continuous','low','mid','high'],['off','continuous']])
num_times = np.random.choice([1,4])
smoothing_radius = np.random.choice([2000,3000,4000])
switching_penalty = np.random.choice([0,0.2,0.5,1])
greed_rate = 0.5
alpha = np.random.choice([0.8,0.9,0.95])
gamma = np.random.choice([0.1, 0.25, 0.5])
storage_penalty = np.random.choice([0.5,1,2])
start_time= datetime.datetime(2015,10, 8,18,30,00)
stop_time = datetime.datetime(2015,11,17,00,00,00)
fluxMDP.fluxMDP(outDir = "outputs/random_runs/run_" + name,
start_time = start_time,
stop_time=stop_time,
gActs = gActs,
num_times=num_times,
smoothing_radius=smoothing_radius,
switching_penalty=switching_penalty,
greed_rate=greed_rate,
alpha=alpha,
gamma=gamma,
storage_penalty=storage_penalty,
detector_area=1000,
previous_measurements='outputs/complete_filled_measurements.pkl')
<file_sep>#!/bin/bash
# Start multiple jobs.
#run_nums=( 5 )
num_runs=300
#for run in ${run_nums[@]}; do
for run in `seq 1 $num_runs`; do
echo "Starting run $run"
qsub -N run$run -j oe -o logs/random_run_$run.txt -l nodes=1:ppn=1 -l walltime=1000:00:00 -q batch \
-v run_path=`pwd`,cmd="/shared/users/asousa/software/anaconda2/bin/python random_run.py" run_job.pbs
done
# -v run_path=`pwd`,cmd="/shared/users/asousa/software/anaconda2/bin/python run_$run.py" run_job.pbs
<file_sep># Load_phi_files.py
# 11.12.2015
# <NAME>
#
# Loads all Phi files from a directory
# Returns N, S, L
# N and S are numpy ndarrays (num_T, num_E, num_L).
# Data are in units of [counts / (cm^2 keV s)]
# L is a vector of L-shells found in the directory.
#
# V1.0. Seems to match the Matlab verson!
import os
import glob
import re
#import struct
import numpy as np
#from matplotlib import pyplot as plt
def load_phi_files(dataDir, num_E=1000, num_T=600):
allfiles = os.listdir(os.getcwd() + '/' + dataDir)
n_files = sorted([f for f in allfiles if 'phi_' in f and '_N' in f])
s_files = sorted([f for f in allfiles if 'phi_' in f and '_S' in f])
if not n_files and not s_files:
print "No phi files found!"
#print n_files
L_n = sorted([float(f[4:(len(f) - 2)]) for f in n_files])
L_s = sorted([float(f[4:(len(f) - 2)]) for f in s_files])
#L_n = sorted([float(re.findall("\d+\.\d+",f)[0]) for f in n_files])
#L_s = sorted([float(re.findall("\d+\.\d+",f)[0]) for f in s_files])
if not (L_n == L_s):
print "North / South mismatch!"
L = np.zeros(np.size(L_n))
N = np.zeros([num_T, num_E, len(L_n)])
#for ind, filename in enumerate(n_files):
for ind in xrange(len(L_n)):
filename = "phi_%g_N" % L_n[ind]
with open(dataDir + '/' + filename, mode='rb') as file:
N[:,:,ind] = np.fromfile(file, np.single).reshape(num_E, num_T).T
L[ind] = float(filename[4:(len(filename) - 2)])
#print L[ind]
S = np.zeros([num_T, num_E, len(L_s)])
#for ind, filename in enumerate(s_files):
for ind in xrange(len(L_s)):
filename = "phi_%g_S" % L_s[ind]
with open(dataDir + '/' + filename, mode='rb') as file:
S[:,:,ind] = np.fromfile(file, np.single).reshape(num_E, num_T).T
print "Total N: %d" % len(L_n)
print "Total S: %d" % len(L_s)
print "N NaNs: %d" % np.sum(np.isnan(N))
print "S NaNs: %d" % np.sum(np.isnan(S))
return N, S, L
if __name__ == '__main__':
# ----------------------------------
# Main Program
# ----------------------------------
N, S, L = load_phi_files("outputs/run_GIOEEV/in_45", num_E = 128, num_T = 600)
<file_sep>import ephem
import math
import datetime
from coordinate_structure import coordinate_structure
# 11.2015 -- Modifying to use coordinate structure
class Satellite(object):
def __init__(self,tle1, tle2, name):
self.tle_rec = ephem.readtle(name, tle1, tle2)
self.curr_time = None
self.name = name
#self.coords = None # Long, Lat! XY on a map, but isn't pleasant to say out loud.
self.coords = coordinate_structure()
def compute(self,plotdate):
self.tle_rec.compute(plotdate)
self.curr_time = plotdate
lat = (180.0/math.pi)*self.tle_rec.sublat
lon = (180.0/math.pi)*self.tle_rec.sublong
alt = self.tle_rec.elevation*1e-3 #kilometers
self.coords.set_coords(lat, lon, alt, "geographic")
#self.coords = [(180.0/math.pi)*self.tle_rec.sublong, (180.0/math.pi)*self.tle_rec.sublat]
def coords_at(self,plotdate):
self.tle_rec.compute(plotdate)
return self.tle_rec.hour()
def local_time():
return ephem
#def coords(self):
# return [(180.0/math.pi)*self.tle_rec.sublong, (180.0/math.pi)*self.tle_rec.sublat]
#def curr_time(self):
# return self.datetime
<file_sep>from GLD_file_tools import GLD_file_tools
from satellite import Satellite
import datetime
import ephem
import numpy as np
from coordinate_structure import coordinate_structure
from longitude_scaling import longitude_scaling
from ionoAbsorp import ionoAbsorp
#from mpl_toolkits.basemap import Basemap
from matplotlib import pyplot as plt
# Check
GLD_root = 'alex/array/home/Vaisala/feed_data/GLD'
NLDN_root = 'alex/array/home/Vaisala/feed_data/NLDN'
sat_TLE = ["1 40378U 15003C 15293.75287141 .00010129 00000-0 48835-3 0 9990",
"2 40378 99.1043 350.5299 0153633 201.4233 158.0516 15.09095095 39471"]
# Satellite object
sat = Satellite(sat_TLE[0], sat_TLE[1],'Firebird 4')
# Lightning-gettin' object
gld = GLD_file_tools(GLD_root, prefix='GLD')
# Column ind
lat_ind = 7;
lon_ind = 8;
mag_ind = 9;
# Input time
inTime = "2015-11-01T00:25:00"
td = datetime.timedelta(seconds = 30) # Maximum time back to check for lightning (pulse can be up to a minute! But how patient are we, really)
plottime = datetime.datetime.strptime(inTime, "%Y-%m-%dT%H:%M:%S")
print plottime
# Get satellite location
sat.compute(plottime)
sat.coords.transform_to('geomagnetic')
# Get flashes within timeframe:
flashes, flash_times = gld.load_flashes(plottime, td)
lats = [f[lat_ind] for f in flashes]
lons = [f[lon_ind] for f in flashes]
flash_coords = coordinate_structure(lats, lons, np.zeros(np.size(lats)),'geographic')
# flash_coords.transform_to('geomagnetic')
# (Use these to make a nice grid)
lats = np.linspace(-90,90,90)
lons = np.linspace(-180,180,90)
flash_coords = coordinate_structure(lats, lons, [0],'geomagnetic')
print "%g flashes (pre-filter)" % flash_coords.len()
atten_factors = longitude_scaling(flash_coords, sat.coords)
mask = atten_factors < 24
#mask = (np.abs(flash_coords.lon() - sat.coords.lon()) < 20)
#mask = ionoAbsorp(flash_coords.lat(),4000) < 10
#print "%g flashes (post-filter)" % np.sum(mask)
mLats = flash_coords.data[mask,0]
mLons = flash_coords.data[mask,1]
masked_coords = coordinate_structure(mLats, mLons, np.zeros(np.size(mLats)),'geomagnetic')
#masked_coords.transform_to('geographic')
#flash_coords.transform_to('geographic')
#sat.coords.transform_to('geographic')
#masked_coords = coordinate_structure(flash_coords.lat()[mask], flash_coords.lon()[mask], np.zeros(np.size(mask)),'geomagnetic')
plt.figure()
plt.scatter(flash_coords.lon(),flash_coords.lat(),marker='.',color='blue')
plt.scatter(sat.coords.lon(),sat.coords.lat(),marker='o',color='green')
plt.scatter(masked_coords.lon(), masked_coords.lat(),marker='x',color='red')
plt.xlim([-180,180])
plt.ylim([-90,90])
plt.figure()
plt.plot(-1.0*ionoAbsorp(np.linspace(-90,90,90),4000))
plt.show()<file_sep>import os
import glob
import re
import numpy as np
from coordinate_structure import coordinate_structure
from matplotlib import pyplot as plt
from load_phi_files import load_phi_files
import subprocess
import re
import sys
import pickle
class flux_obj(object):
def __init__(self):
self.t = None
self.coords = coordinate_structure()
self.data = None
self.N = None
self.N_E = None
self.S_E = None
self.S = None
self.L = None
self.consts_list = None
self.LK = None
self.I0 = None
self.RES_DT = None
self.RES_FINT = None
self.NUM_T = None
def build_database(input_dir_name='outputs', output_filename='database.pkl'):
ev2joule = (1.60217657)*1e-19 # Joules / ev
joule2millierg = 10*1e10
print ""
rootDir = os.getcwd() + '/' + input_dir_name + '/'
d = os.listdir(rootDir)
runs = sorted([f for f in d if 'run_' in f])
print runs
database = dict()
for r in runs:
d = os.listdir(rootDir + "/" + r)
ins = sorted([f for f in d if 'in_' in f])
print "Run: ", r
consts_file = r + "/codesrc/consts.h"
# Parse consts.h
# Loads as many lines from the constants file as it can... will fail on
consts_list = []
with open(rootDir + consts_file,'r') as file:
for line in file:
if "#define" in line and line[0:1] is not "//":
l = line.split()
#if len(l)>=3:
try:
exec('%s=%f'% (l[1], eval(l[2])))
consts_list.append(l)
#print l[1], eval(l[1])
except:
#print "failed: ", l
None
for i in ins:
# Load some actual data!
# try:
inp_lat = int(i[3:])
NUM_T = RES_FINT/RES_DT
obj = dict()
#obj = flux_obj()
N, S, L = load_phi_files( input_dir_name + "/" + r + "/" + i, num_E = NUM_E, num_T = NUM_T)
obj['consts_list'] = consts_list
#obj.consts_list = consts_list
NUM_L = len(L)
obj['NUM_T'] = NUM_T
obj['I0'] = I0
obj['LK'] = LK
obj['RES_DT'] = RES_DT
obj['RES_FINT'] = RES_FINT
# obj.NUM_T = NUM_T
# obj.I0 = I0
# obj.LK = LK
# obj.RES_DT = RES_DT
# obj.RES_FINT = RES_FINT
# # Scale by energy bin values:
# E_EXP_BOT = np.log10(E_MIN)
# E_EXP_TOP = np.log10(E_MAX)
# DE_EXP = ((E_EXP_TOP - E_EXP_BOT)/NUM_E)
# E_EXP = E_EXP_BOT + np.linspace(1,NUM_E,NUM_E)*DE_EXP
# E = np.power(10,E_EXP)
# E_scaled = ev2joule*joule2millierg*E
# tmp = np.tile(E_scaled.T, [NUM_T, 1]).T
# N_scaled = N*np.tile(tmp, [NUM_L,1,1]).T
# S_scaled = S*np.tile(tmp, [NUM_L,1,1]).T
# N_totals = np.sum(N_scaled,axis=1)
# S_totals = np.sum(S_scaled,axis=1)
N_totals = np.sum(N,axis=1)
S_totals = np.sum(S,axis=1)
# Load each (lat, Lk, I0, L-shell) vector separately
coords = coordinate_structure(L,[-10],[0],'L_dipole')
coords.transform_to('geomagnetic')
# Total flux vs time and latitude
obj['N'] = N_totals
obj['S'] = S_totals
# obj.N = N_totals
# obj.S = S_totals
# 3D array, flux vs time, latitude, energy
obj['N_E'] = N
obj['S_E'] = S
obj['coords'] = coords
obj['t'] = np.linspace(0,RES_FINT, NUM_T)
key = (inp_lat)
database[key] = obj
# ------------------- for single row entries
# for ind, val in enumerate(coords.lat()):
# #print val
# obj.N = N_totals[:,ind]
# obj.S = S_totals[:,ind]
# #obj.L = val
# obj.Lat = round(100*val)/100.0
# print np.shape(obj.N)
# key = (inp_lat, LK, I0, round(100*val)/100)
# database[key] = obj
# N_totals = np.maximum(-1000, np.log10(np.sum(N_scaled,axis=1)))
# S_totals = np.maximum(-1000, np.log10(np.sum(S_scaled,axis=1)))
print inp_lat
# key = (inp_lat, LK, I0)
# database[key] = obj
# except:
# print "bruh ;_;"
#print [o[1].L for o in database.items()]
print "Saving database"
with open(output_filename,'wb') as f:
pickle.dump(database,f,pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
build_database(input_dir_name="outputs/probably/",output_filename="database_dicts.pkl")
<file_sep># Return longitude scaling for a set of inputs
import numpy as np
import geopy.distance
from ionoAbsorp import ionoAbsorp
from coordinate_structure import coordinate_structure
import pickle
def longitude_scaling(flash_coords, out_coords):
''' Returns dB attenuation of a wave, based on the WIPP ionosphere input model '''
H_IONO = 1e5
# H_E = 5000.0
# Z0 = 377.0
# A = 5e3
# B = 1e5
path_atten = 12 # db per 1000 km (Completely handwaved, but I can't get the trig from the C code right)
R_earth = geopy.distance.EARTH_RADIUS
D2R = np.pi/180.0
#f = 4000 #Hz
# Ionospheric absorption at output points
#iono_atten = ionoAbsorp(flash_coords.lat(),f)
# Separation in longitude, kilometers
dist_lon = (R_earth)*np.abs(flash_coords.lon() - out_coords.lon())*D2R*np.cos(D2R*flash_coords.lat())*1e-3
#return path_atten*dist_lon/1000.0# - iono_atten
return dist_lon*path_atten
# Approx attenuation factor (db per 1000 km):
# Note: Still ignoring vertical propagation losses
if __name__ == '__main__':
fc1 = coordinate_structure(45,45,0,'geographic')
fc2 = coordinate_structure(45,50,0,'geographic')
print longitude_scaling(fc1, fc2) | efd4925c1ee12b99857bc414d31e32e014c84470 | [
"Python",
"Shell"
] | 16 | Python | asousa/fluxMDP | 751b90eb068b4bc4d3ea6f3ec3a357bd2045cae8 | 3974ee9532e04bf2aed1a82802ab3d4090610e24 |
refs/heads/master | <repo_name>jasonhutchens/hacktile<file_sep>/www/deploy.rb
gem "fog"
require "fog"
secret = nil
if ARGV.length > 0
secret = ARGV[0]
end
if secret.nil? || secret.length < 10
puts "Please specify the amazon secret key as the first argument."
exit
end
dist_dir = "./dist"
# deploy to root
begin
files = Dir.open(dist_dir).reject{|x| File.directory?(x) || x == ".DS_Store" }
aws = Fog::Storage.new({
:provider => 'AWS',
:aws_secret_access_key => secret,
:aws_access_key_id => "<KEY>"
})
bucket = aws.directories.get("hacktile")
puts "Deploying to Amazon S3:"
files.each do |filename|
puts " - #{filename}"
bucket.files.create(
:key => filename,
:body => File.open("#{dist_dir}/#{filename}"),
:public => true
)
end
rescue Excon::Errors::Forbidden => e
puts "Errors connecting to S3, perhaps one of the keys are wrong or they don't match?"
end
# deploy to version archive
begin
# get dist version
ver = ""
File.open("#{dist_dir}/ver", "r") do |f|
ver = f.read
end
puts
puts "Deploying to version archive #{ver}:"
files = Dir.open(dist_dir).reject{|x| File.directory?(x) || x == ".DS_Store" }
aws = Fog::Storage.new({
:provider => 'AWS',
:aws_secret_access_key => secret,
:aws_access_key_id => "<KEY>"
})
bucket = aws.directories.get("hacktile")
puts "Deploying to Amazon S3:"
files.each do |filename|
puts " - #{filename}"
bucket.files.create(
:key => "#{ver}/#{filename == "index.html" ? "i.htm" : filename}",
:body => File.open("#{dist_dir}/#{filename}"),
:public => true
)
end
rescue Excon::Errors::Forbidden => e
puts "Errors connecting to S3, perhaps one of the keys are wrong or they don't match?"
end<file_sep>/www/public/compact.js
/* takes a compact hacktile program and expands it into a prettyier version */
function pretty(compact_code)
{
}
/* takes a pretty hacktile program and compacts it */
function compact(pretty_code)
{
c = $.trim(pretty_code);
// if the string is all one line then it's already compact and return!
if (!c.match( /\n/ )) {
return c;
}
//ignore whitespace at start of line
c = c.replace( /^\s*/mg, "" );
//ignore whitespace at end of line
c = c.replace( /\s*$/mg, "" );
// remove all comments
c = c.replace( /^#.*$/gm, "" )
//clear out any whitespace only lines
c = c.replace( /^\s*\n/gm, "" )
// expand inline transformation matricies
// ... ...
// .x. -> .y.
// ... ...
// becomes
// ....x....'....y....
c = c.replace(
/(...) (...)\n(...) -> (...)\n(...) (...)/gm,
",$1$3$5`$2$4$6"
)
c = c.replace(
/^(...)\n(...)\n(...)$/gm,
",$1$2$3"
)
//compact some rules
c = c.replace( /(^\d+x\d+)\n/g, "$1,\n"); // dimensions
c = c.replace( /^0x([0-9a-f]*)$/gm, "$1," ); // colour
c = c.replace( /(\d+) random (.)'s/gm, "'$2$1-" );
c = c.replace( /4-way\n,/gm, ",'4" ); // these also catch the rule on the next line
c = c.replace( /8-way\n,/gm, ",'8" );
c = c.replace( /unordered\n,/gm, ",'0" );
c = c.replace( /\nif (.) is pressed/gm, "k$1" ); // these append to the previous line
c = c.replace( /\nmove (.) to (\d)/gm, "m$1$2" );
//push onto one line
c = c.replace( /^--$/gm, "_");
c = c.replace( /\n_\n/gm, "_");
c = c.replace( /_,/gm, "_");
c = c.replace( /-_/gm, "_");
c = c.replace( /\n/gm, "");
c = c.replace( /-'/gm, "-");
// the following breaks URLs
c = c.replace( /\./gm, "+");
c = c.replace( / /gm, "+");
/*
// find the dimensions
dimensions = c.match( /^\d+x\d+\n/)[0].split("x");
x = parseInt(dimensions[0]);
y = parseInt(dimensions[1]);
// find the playfield definition and collapse it with no delimiter
regex = new RegExp( "(^{"+x+"}$)" )
*/
return c
}
<file_sep>/www/app.rb
# encoding: utf-8
require 'rubygems'
gem 'sinatra'
require 'sinatra'
gem 'sinatra-static-assets'
require 'sinatra/static_assets'
gem 'haml'
require 'haml'
require 'sass'
enable :html5
enable :run
set :public, File.dirname(__FILE__) + '/public'
set :views, File.dirname(__FILE__) + '/views'
set :haml, {format: :html5, ugly: true}
set :sass, {style: :compact}
VERSION = "1"
get '/' do
haml :index
end
get '/most_popular.html' do
haml :most_popular
end
get '/retro_remakes.html' do
haml :retro_remakes
end
get '/chunky_animations.html' do
haml :chunky_animations
end
get '/pixel_art.html' do
haml :pixel_art
end
get '/music.html' do
haml :music
end
get '/tutorial.html' do
haml :tutorial
end
get '/favourites.html' do
haml :favourites
end
get '/laboratory.html' do
haml :laboratory
end
get '/about.html' do
haml :about
end
get '/test' do
"#_1x1,88ff44,what+a+interesting+thing+I+find!_!_"
end
get '/ver' do
VERSION
end
get '/style.css' do
content_type 'text/css', :charset => 'utf-8'
sass :style
end
IE6_WARNING = <<BLOB
<div style='border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative;'>
<div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'><a href='#' onclick='javascript:this.parentNode.parentNode.style.display="none"; return false;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/></a></div>
<div style='width: 640px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>
<div style='width: 75px; float: left;'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div>
<div style='width: 275px; float: left; font-family: Arial, sans-serif;'>
<div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>You are using an outdated browser</div>
<div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>For a better experience using this site, please upgrade to a modern web browser.</div>
</div>
<div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div>
<div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div>
<div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div>
<div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div>
</div>
</div>
BLOB
GOOGLE_ANALYTICS = <<BLOB
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24453836-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
BLOB
NO_SCRIPT = <<BLOB
<noscript>
<div id="static"></div>
</noscript>
BLOB
<file_sep>/www/build.rb
require "fileutils"
require 'net/http'
require 'uri'
def open(url)
Net::HTTP.get(URI.parse(url))
end
DIRECTORY = Dir::pwd + "/" + "dist"
Dir::mkdir(DIRECTORY) unless FileTest::directory?(DIRECTORY)
def grab_file( file, remote_path=nil )
remote_path ||= file
File.open("#{DIRECTORY}/#{file}", "w") do |f|
f.write(open("http://localhost:4567/#{remote_path}"))
end
end
grab_file "index.html", ""
grab_file "most_popular.html"
grab_file "retro_remakes.html"
grab_file "chunky_animations.html"
grab_file "pixel_art.html"
grab_file "music.html"
grab_file "tutorial.html"
grab_file "favourites.html"
grab_file "laboratory.html"
grab_file "about.html"
grab_file "style.css"
grab_file "ver"
FileUtils.cp_r Dir.glob(Dir::pwd + "/" + "public/."), DIRECTORY
<file_sep>/www/test/compact_test.js
var example_compact = "_10x10,f00,Puck+Man_"+
"aaaaaaaaaaa........aa.bb.....aa.bb.....aa........aa........aa........aa.....c..aa....ccc.aa........aaaaaaaaaaa'x10-920_"+
"*x*******'*y*******,'4*c*******m23kw_"
var example_pretty = "" +
"# dimensions - yes, comments are allowed" + "\n" +
"10x10" + "\n" +
"" + "\n" +
"# background colour" + "\n" +
"0xf00" + "\n" +
"" + "\n" +
"#description" + "\n" +
"Puck Man" + "\n" +
"" + "\n" +
"--" + "\n" +
"" + "\n" +
"aaaaaaaaaa" + "\n" +
"a........a" + "\n" +
"a.bb.....a" + "\n" +
"a.bb.....a" + "\n" +
"a........a" + "\n" +
"a........a" + "\n" +
"a........a" + "\n" +
"a.....c..a" + "\n" +
"a....ccc.a" + "\n" +
"a........a" + "\n" +
"aaaaaaaaaa" + "\n" +
"" + "\n" +
"10 random x's" + "\n" +
"20 random 9's" + "\n" +
"" + "\n" +
"--" + "\n" +
"" + "\n" +
"... ..." + "\n" +
".x. -> .y." + "\n" +
"... ..." + "\n" +
"" + "\n" +
"4-way" + "\n" +
"" + "\n" +
".c." + "\n" +
"..." + "\n" +
"..." + "\n" +
"" + "\n" +
"move 2 to 3" + "\n" +
"if w is pressed" + "\n";
$(function(){
$("#pretty").text(example_pretty);
$("#make_compact").click( function(){
$("#compact").text( compact($("#pretty").text()));
});
});<file_sep>/proxy/Makefile
include $(GOROOT)/src/Make.inc
TARG=proxy
GOFILES=\
proxy.go\
include $(GOROOT)/src/Make.cmd
fmt:
@gofmt -w -tabwidth=4 -tabindent=false -spaces=true $(GOFILES)
<file_sep>/proxy/proxy.go
package main
import (
"http"
"log"
"fmt"
"bufio"
"regexp"
"bytes"
"html"
)
func handler(writer http.ResponseWriter, request *http.Request) {
// Our target is given as the only query
targetURL := request.URL.RawQuery
if (len(request.Host) == 0) {
log.Printf("ERROR Loop detected")
http.NotFound(writer, request)
return
}
// Patch the URL because Get() borks if it doesn't specify a scheme
if (len(targetURL)<7 || targetURL[:7] != "http://") {
targetURL = "http://" + targetURL
}
// Log the request for our benefit
log.Printf("REQUEST %s|%s|%s|%s|%s\n", request.Host, targetURL, request.RemoteAddr, request.Referer, request.UserAgent)
// Retrieve the remote URL
response, error := http.Get(targetURL)
// Return a 404 if something goes wrong and log the error for our benefit
if (error != nil) {
log.Printf("ERROR Get - %s\n", error)
http.NotFound(writer, request)
return
}
// Read the body (first 100kb or less)
reader, error := bufio.NewReaderSize(response.Body, 100 * 1024)
if (error != nil) {
log.Printf("ERROR Reader - %s\n", error)
http.NotFound(writer, request)
return
}
// Extract HTML to get just the raw text
buffer := bytes.NewBufferString("");
tokenizer := html.NewTokenizer(reader)
for tokenizer.Error() == nil {
tt := tokenizer.Next()
if tt == html.TextToken {
fmt.Fprint(buffer, string(tokenizer.Text()));
fmt.Fprint(buffer, "\n");
}
}
body := buffer.String();
response.Body.Close()
// Munge everything up into a single line
body = regexp.MustCompile("[\n\r]").ReplaceAllString(body, "<br>")
// Rip out potential HackTile code; fail if none
match, error := regexp.Compile("\\[hacktile\\]([^[]+)\\[\\/hacktile\\]")
if (error != nil) {
log.Printf("ERROR Compile - %s\n", error)
http.NotFound(writer, request)
return
}
find := match.FindAllStringSubmatch(body, 1000)
if (find == nil) {
log.Printf("ERROR No HackTile Code Found")
http.NotFound(writer, request)
return
}
// Stringify the matches
buffer = bytes.NewBufferString("");
for _, tmp := range find {
fmt.Fprint(buffer, tmp[1]);
}
code := buffer.String();
// De-munge everything
code = regexp.MustCompile("<br>").ReplaceAllString(code, "\n")
// Replace HTML thingoes
//code = html.UnescapeString(code)
// Log the code for our benefit
log.Printf("RESPONSE %s\n", code)
// Write the response
writer.Header().Add("Access-Control-Allow-Origin", "http://www.hacktile.net");
fmt.Fprintf(writer, code)
}
// No threading ATM; will add that later
func main() {
log.Print("HackTile Proxy Server\n")
http.HandleFunc("/", http.HandlerFunc(handler))
error := http.ListenAndServe(":80", nil)
if (error != nil) {
log.Printf("ERROR - ListenAndServe %s\n", error)
}
}
| 449662cf496fcd4224f599068edfe01e0a43f37e | [
"JavaScript",
"Ruby",
"Go",
"Makefile"
] | 7 | Ruby | jasonhutchens/hacktile | 352c808b63ae05449675ca6525c753f95f7d4655 | 61f22f945aa101a3d28650359cf80eb29ada08ea |
refs/heads/master | <repo_name>haranguri2020/ENTELGY<file_sep>/src/main/java/com/miempresa/rest/GreetingController.java
package com.miempresa.rest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import javax.json.JsonValue;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.miempresa.bean.Greeting;
import com.miempresa.bean.Objecto;
import com.miempresa.bean.Objecto2;
import com.miempresa.bean.ObtenerPeticionesResponse;
import com.miempresa.clientImpl.ConsultaTransaccionesClientImpl;
import com.miempresa.util.UtilEAI;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
private static final Logger LOG = Logger.getLogger(ConsultaTransaccionesClientImpl.class);
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
Greeting respuesta=null;
ObtenerPeticionesResponse response = new ObtenerPeticionesResponse();
try {
LOG.info( "hans ");
// Esto es lo que vamos a devolver
StringBuilder resultado = new StringBuilder();
// Crear un objeto de tipo URL
// URL url = new URL("http://jsonplaceholder.typicode.com/comments/1");
URL url = new URL("http://jsonplaceholder.typicode.com/comments");
// Abrir la conexión e indicar que será de tipo GET
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
// Búferes para leer
BufferedReader rd = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
String linea;
// Mientras el BufferedReader se pueda leer, agregar contenido a resultado
while ((linea = rd.readLine()) != null) {
resultado.append(linea);
}
// Cerrar el BufferedReader
rd.close();
// LOG.info( "resultado " + resultado.toString());
//// Object objeto=resultado.toString();
//
// com.google.gson.JsonParser fichero = null;
// Object objeto = fichero.parse(resultado.toString());
//
// JsonArray detalle = (JsonArray) objeto;
// Iterator<JsonElement> iterator = detalle.iterator();
//
// while (iterator.hasNext()) {
// JsonObject jsonObject = (JsonObject) iterator.next();
//
// jsonObject.keySet().forEach((key) -> {
// System.out.println(key + ":" + jsonObject.get(key));
// });
// }
String resultadoss="{\"data\":"+resultado.toString()+"}";
LOG.info( "resultadoss " + resultadoss);
// JSONParser parser = new JSONParser(resultado.toString());
// JSONObject pagesObject = (JSONObject) parser.parse();
// System.out.println(pagesObject.get("id"));
// System.out.println(pagesObject.get("pages").getClass().getName());
// JSONArray jsonArray= (JSONArray) pagesObject.get("pages");
//
// for(int i=0; i<jsonArray.size(); i++){
// System.out.println(jsonArray.get(i));
// }
//
//// JSONArray detalle = (JSONArray) objeto;
//
//
// JsonArray detalle = (JsonArray) objeto;
// Iterator<JsonElement> iterator = detalle.iterator();
//
// while (iterator.hasNext()) {
// JsonObject jsonObject = (JsonObject) iterator.next();
//
// jsonObject.keySet().forEach((key) -> {
// System.out.println(key + ":" + jsonObject.get(key));
// });
// }
//
//
// json.
//
// //Recorro el array para parsear cada cliente
// for (JSONObject jclient : json){
// //Instancia tu modelo de Cliente para que contenga los datos que vayas a necesitar
// Cliente cliente = new Cliente();
//
// //Asi consigo finalmente los campos del json
// cliente.nombre = jclient.getString("nombre");
// cliente.tel1 = jclient.getString("tel1");
// cliente.tel2 = jclient.getDouble("tel2");
// //Continuar con los demas campos...
// clientes.add(cliente)
// }
ObjectMapper mapper = new ObjectMapper();
response = mapper.readValue( resultadoss , ObtenerPeticionesResponse.class);
respuesta=new Greeting();
List<Objecto2> lista=new ArrayList<Objecto2>();
Objecto2 ofinal=null;
for(Objecto o:response.getData()) {
ofinal=new Objecto2();
ofinal.setPostId(o.getPostId());
ofinal.setId(o.getId());
ofinal.setEmail(o.getEmail());
lista.add(ofinal);
}
LOG.info( "clave java a json LISTA response:\n " + UtilEAI.printPrettyJSONString(response));
respuesta.setData(lista);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return respuesta;
}
}<file_sep>/src/main/java/com/miempresa/clientImpl/ConsultaTransaccionesClientImpl.java
package com.miempresa.clientImpl;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.miempresa.bean.ObtenerPeticionesResponse;
import com.miempresa.client.ConsultaTransaccionesClient;
import com.miempresa.util.UtilEAI;
//
import org.apache.log4j.Logger;
////import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
////import org.springframework.stereotype.Repository;
//import org.springframework.stereotype.Service;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
//
////import pe.com.claro.common.bean.HeaderRequestBean;
//import pe.com.claro.common.property.Constantes;
//import pe.com.claro.common.resource.exception.WSException;
//import pe.com.claro.common.util.JAXBUtilitarios;
//import pe.com.claro.postventa.peticionescliente.canonical.bean.HeaderRequestBean;
//import pe.com.claro.postventa.peticionescliente.canonical.request.ObtenerPeticionesRequest;
//import pe.com.claro.postventa.peticionescliente.canonical.response.ObtenerPeticionesResponse;
//import pe.com.claro.postventa.peticionescliente.integration.client.ConsultaTransaccionesClient;
//import pe.com.claro.postventa.peticionescliente.integration.util.UtilEAI;
//import pe.com.claro.postventa.peticionescliente.integration.util.UtilIntegration;
//import pe.com.claro.postventa.peticionescliente.shared.util.Propiedades;
//import pe.com.claro.restclient.AbstractRestClient;
@Service
//public class ConsultaTransaccionesClientImpl extends AbstractRestClient implements ConsultaTransaccionesClient {
public class ConsultaTransaccionesClientImpl implements ConsultaTransaccionesClient {
private static final Logger LOG = Logger.getLogger(ConsultaTransaccionesClientImpl.class);
// private UtilIntegration util = new UtilIntegration();
// @Autowired
// Propiedades properties;
@Override
public ObtenerPeticionesResponse obtenerPeticiones( )
throws Exception {
long tiempoInicio = System.currentTimeMillis();
ObtenerPeticionesResponse response = new ObtenerPeticionesResponse();
try {
ObjectMapper mapper = new ObjectMapper();
Client clientRest = Client.create();
clientRest.setReadTimeout(5000);
WebResource webResource = clientRest.resource("https://jsonplaceholder.typicode.com/comments");
Builder builder = webResource.type("application/json");
// util.setHeaderBuilder(builder, header);
// LOG.info("seteando el util " + header);
// LOG.info("el builder " + builder);
//
// LOG.info("******HEADER***: " + UtilEAI.printPrettyJSONString(header));
// LOG.info("******REQUEST***: " + UtilEAI.printPrettyJSONString(request));
//
// LOG.info("antes del obtenerPeticiones response");
ClientResponse clientResponse = builder.post(ClientResponse.class, mapper.writeValueAsString(null));// **
String data = clientResponse.getEntity(String.class);
response = mapper.readValue(data, ObtenerPeticionesResponse.class);
LOG.info( "obtenerPeticiones response:\n " + UtilEAI.printPrettyJSONString(response));
} catch (Exception e) {
// LOG.error( e.getMessage(), e);
// String errorMsg = e + Constantes.VACIO;
// String nombreWs = properties.consultaTransaccionesNombreWS;
// LOG.error(mensaje + Constantes.EXCEPCION_REST + nombreWs + Constantes.DOSPUNTOS + errorMsg, e);
} finally {
// LOG.info(mensaje + "Tiempo invocacion (ms): " + (System.currentTimeMillis() - tiempoInicio) + " milisegundos");
}
return response;
}
}<file_sep>/src/main/java/com/miempresa/util/UtilEAI.java
package com.miempresa.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.DateFormat;
import java.text.ParseException;
public class UtilEAI
{
private final Logger logger = Logger.getLogger(getClass().getName());
public static final String SALTOLINEA = "\n";
private static HashMap<Class, JAXBContext> objMapaContexto = new HashMap();
private static HashMap<Class, JAXBContext> mapContexts = new HashMap();
public Object deserializeBytes(byte[] bytes)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bytesIn);
Object obj = ois.readObject();
ois.close();
return obj;
}
public static String generateTraIdByDate()
{
return new SimpleDateFormat("yyyyMMddHHmmssms", Locale.getDefault()).format(GregorianCalendar.getInstance().getTime());
}
public String transformarAnyObjectToJsonText(String mensajeTransaccion, Object objJaxB)
{
String commandoRequestEnJson = null;
JAXBContext objContexto = null;
try
{
objContexto = obtenerContextoJaxBFromClass(mensajeTransaccion, objJaxB.getClass());
Marshaller objMarshaller = objContexto.createMarshaller();
StringWriter objStringWritter = new StringWriter();
objMarshaller.setProperty("eclipselink.media-type", "application/json");
objMarshaller.setProperty("jaxb.formatted.output", Boolean.valueOf(true));
objMarshaller.setProperty("jaxb.fragment", Boolean.valueOf(true));
objMarshaller.setProperty("eclipselink.json.include-root", Boolean.valueOf(true));
objMarshaller.marshal(new JAXBElement(new QName("", objJaxB.getClass().getSimpleName()), objJaxB.getClass(), objJaxB), objStringWritter);
commandoRequestEnJson = objStringWritter.toString();
}
catch (Exception e)
{
this.logger.error(mensajeTransaccion + " ERROR parseando object to 'JSON': ", e);
}
return commandoRequestEnJson;
}
private JAXBContext obtenerContextoJaxBFromClass(String mensajeTransaccion, Class objClase)
{
JAXBContext objContexto = null;
objContexto = (JAXBContext)objMapaContexto.get(objClase);
if (objContexto == null) {
try
{
this.logger.info(mensajeTransaccion + " INICIALIZANDO: [JaxContext...]");
objContexto = JAXBContext.newInstance(new Class[] { objClase });
objMapaContexto.put(objClase, objContexto);
}
catch (Exception e)
{
this.logger.error(mensajeTransaccion + " ERROR creando 'JAXBContext': ", e);
}
}
return objContexto;
}
private static JAXBContext obtainJaxBContextFromClass(Class clas)
{
JAXBContext context = (JAXBContext)mapContexts.get(clas);
if (context == null) {
try
{
context = JAXBContext.newInstance(new Class[] { clas });
mapContexts.put(clas, context);
}
catch (Exception localException) {}
}
return context;
}
// public String anyObjectToXmlText(Object anyObject)
// {
// String commandoRequestEnXml = null;
// try
// {
// JAXBContext context = obtainJaxBContextFromClass(anyObject.getClass());
//
// Marshaller marshaller = context.createMarshaller();
//
// StringWriter xmlWriter = new StringWriter();
// marshaller.marshal(new JAXBElement(new QName("", anyObject
// .getClass().getSimpleName()), anyObject.getClass(),
// anyObject), xmlWriter);
//
// XmlObject xmlObj = XmlObject.Factory.parse(xmlWriter.toString());
//
// commandoRequestEnXml = xmlObj.toString();
// }
// catch (Exception e)
// {
// this.logger.error("Error parseando object to xml:", e);
// }
// return commandoRequestEnXml;
// }
public static String getStackTraceFromException(Exception exception)
{
StringWriter stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter, true));
return stringWriter.toString();
}
public static String obtenerIP()
{
String sHostName = "";
try
{
InetAddress address = InetAddress.getLocalHost();
sHostName = address.getHostAddress();
}
catch (Exception localException) {}
return sHostName;
}
public static Date parsearFecha( String fecha, String formatoFecha ) throws Exception{
Date date = null;
try{
if( fecha != null && !fecha.isEmpty() && formatoFecha != null && !formatoFecha.isEmpty() ){
SimpleDateFormat formatter = new SimpleDateFormat( formatoFecha, Locale.getDefault() );
date = formatter.parse( fecha );
}
}
catch( Exception e ){
throw e;
}
return date;
}
public static XMLGregorianCalendar convertDateToGregorianCalendar(Date fecha) {
GregorianCalendar calender = new GregorianCalendar();
calender.setTime(fecha);
XMLGregorianCalendar xmlCalendar = null;
try {
xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(calender);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return xmlCalendar;
}
public static Date convierteFechaStringToDate(String fecha)
{
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
Date fechaDate = null;
try {
fechaDate = formato.parse(fecha);
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
public static java.sql.Date convierteFechaStringToSQLDate(String fecha)
{
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date fechaDate = null;
try {
fechaDate = new java.sql.Date ( formato.parse(fecha).getTime() );
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
public static String convierteSQLDateToString(java.sql.Date fecha)
{
java.util.Date fechaDate = new java.util.Date( fecha.getTime() );
return convierteFechaDateToString( fechaDate);
}
public static String convierteFechaDateToString(Date fecha)
{
String fechaString="";
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
fechaString = sdf.format(fecha);
return fechaString;
}
public static String getTagValue(String xml, String tagName) {
return xml.split("<" + tagName + ">")[1].split("</" + tagName + ">")[0];
}
public static String printPrettyJSONString(Object o) {
try {
return new ObjectMapper().setDateFormat(UtilEAI.getLocalFormat())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).writerWithDefaultPrettyPrinter()
.writeValueAsString(o);
} catch (JsonProcessingException e) {
return null;
}
}
/**
* Remueve los saltos de linea de una cadena
* @param cadena cadena a modificar
* @return cadena sin saltos de linea
*/
// public static String cleanStringJson(String cadena) {
// return printPrettyJSONString(UtilEAI.removerSaltosLinea(StringEscapeUtils.unescapeJava(cadena), StringUtils.EMPTY,
// true));
// }
/**
* Reemplaza los saltos de linea de una cadena y tambien los espacios en blanco de ser solicitado
* @param cadena cadena a modificar
* @param reemplazo reemplazo para los saltos de linea
* @param sinEspacios reemplazar espacios tambien
* @return nueva cadena
*/
// public static String removerSaltosLinea(String cadena, String reemplazo, boolean sinEspacios) {
// return cadena != null ? cadena.replaceAll("\r?\n|\r" + (sinEspacios ? "|\\s" : StringUtils.EMPTY), reemplazo) : null;
// }
public static DateFormat getLocalFormat() {
//DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSXXX", Locale.getDefault());
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", Locale.getDefault());
dateFormat.setTimeZone(TimeZone.getDefault());
return dateFormat;
}
public static java.sql.Date obtenerFechaActualSql() {
return new java.sql.Date(new Date().getTime());
}
// public static String obtenerTimeStamp(){
// Date fecha = new Date();
// SimpleDateFormat formato = new SimpleDateFormat(Constantes.FORMATO_TIMESTAMP);
// return formato.format(fecha);
//
// }
} | fda4b64bf850e2b597498f19ae57b0b171f4d1a3 | [
"Java"
] | 3 | Java | haranguri2020/ENTELGY | 5e19a61bd9bb5f8107ebc9e48ac2baa9b9d6c398 | c03f001ecb2974565bad63c7f727c0b975512b75 |
refs/heads/master | <repo_name>tcoenraad/rolit<file_sep>/tests/test_server_bonus.py
import pytest
from mock import Mock, call, patch
from rolit.server import *
from test_server import TestServer
@patch.object(random, 'shuffle', Mock())
class TestServerBonus(TestServer):
def test_chat_when_enabled_and_in_lobby(self):
self.server.chat(self.clients[0], "This is a test message")
args = call("%s %s %s%s" % (Protocol.CHAT, self.clients[0]['name'], "This is a test message", Protocol.EOL))
self.clients[0]['socket'].sendall.assert_has_calls(args)
self.clients[1]['socket'].sendall.assert_has_calls(args)
self.clients[2]['socket'].sendall.assert_has_calls(args)
assert self.clients[3]['socket'].sendall.call_count == 7
def test_chat_when_enabled_and_in_game(self):
self.start_game_with_two_players()
self.server.chat(self.clients[0], "This is a test message and it is my turn")
self.server.chat(self.clients[1], "This is a test message and it is not my turn")
self.server.chat(self.clients[2], "This is a test message and I am not in game")
args = [call("%s %s %s%s" % (Protocol.CHAT, self.clients[0]['name'], "This is a test message and it is my turn", Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHAT, self.clients[1]['name'], "This is a test message and it is not my turn", Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
self.clients[1]['socket'].sendall.assert_has_calls(args)
args = call("%s %s %s%s" % (Protocol.CHAT, self.clients[2]['name'], "This is a test message and I am not in game", Protocol.EOL))
self.clients[2]['socket'].sendall.assert_has_calls(args)
def test_chat_with_disabled_clients(self):
self.server.chat(self.clients[1], "This is a test message and I am not in game")
assert self.clients[3]['socket'].sendall.call_count == 7
def test_chat_when_disabled(self):
with pytest.raises(ClientError):
self.server.chat(self.clients[3], "This is a test message")
def test_challenge_client_itself(self):
with pytest.raises(ClientError):
self.server.challenge(self.clients[0], "%s" % (self.clients[0]['name']))
def test_challenge_with_too_many_people(self):
with pytest.raises(ClientError):
self.server.challenge(self.clients[0], "a", "b", "c", "d")
def test_challenge_when_challengee_disabled_challenges(self):
with pytest.raises(ClientError):
self.server.challenge(self.clients[0], self.clients[2]['name'])
def test_challenge_when_challenger_disabled_challenges(self):
with pytest.raises(ClientError):
self.server.challenge(self.clients[2], self.clients[0]['name'])
def test_challenge_someone_that_does_not_exist(self):
with pytest.raises(ClientError):
self.server.challenge(self.clients[0], "<NAME>")
def test_create_when_already_in_challenge(self):
self.server.challenge(self.clients[0], self.clients[1]['name'])
with pytest.raises(ClientError):
self.server.create_game(self.clients[0])
def test_challenge_someone_that_is_already_challenged(self):
self.server.challenge(self.clients[0], self.clients[1]['name'])
with pytest.raises(ClientError):
self.server.challenge(self.clients[4], self.clients[1]['name'])
def test_challenge_someone_that_is_already_in_a_not_started_game(self):
self.server.create_game(self.clients[0])
with pytest.raises(ClientError):
self.server.challenge(self.clients[1], self.clients[0]['name'])
def test_challenge_someone_that_is_already_in_a_started_game(self):
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.challenge(self.clients[4], self.clients[1]['name'])
def test_challenge_requests(self):
self.server.challenge(self.clients[0], self.clients[1]['name'], self.clients[4]['name'])
args = call("%s %s %s %s%s" % (Protocol.CHALLENGE, self.clients[0]['name'], self.clients[1]['name'], self.clients[4]['name'], Protocol.EOL))
self.clients[1]['socket'].sendall.assert_has_calls(args)
self.clients[4]['socket'].sendall.assert_has_calls(args)
assert self.clients[3]['socket'].sendall.call_count == 7
def test_challenge_response_when_not_challenged(self):
with pytest.raises(ClientError):
self.server.challenge_response(self.clients[1], Protocol.TRUE)
def test_challenge_availability(self):
self.server.challenge(self.clients[0], self.clients[1]['name'])
self.server.disconnect(self.clients[1])
args = [call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[0]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[1]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[4]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[5]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[0]['name'], Protocol.FALSE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[1]['name'], Protocol.FALSE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[0]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[1]['name'], Protocol.FALSE, Protocol.EOL))]
self.clients[5]['socket'].sendall.assert_has_calls(args)
def test_availability_on_connect(self):
self.server.challenge(self.clients[0], self.clients[1]['name'])
sock = Mock()
self.server.connect(sock, "Bestuur_35", Protocol.CHAT_AND_CHALLENGE)
args = [call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[0]['name'], Protocol.FALSE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[1]['name'], Protocol.FALSE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[4]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, self.clients[5]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGABLE, "Bestuur_35", Protocol.TRUE, Protocol.EOL))]
sock.sendall.assert_has_calls(args)
def test_challenge_request_accepted(self):
self.server.initiate_game = Mock(wraps=self.server.initiate_game)
self.server.challenge(self.clients[0], self.clients[1]['name'], self.clients[4]['name'])
self.server.challenge_response(self.clients[1], Protocol.TRUE)
with pytest.raises(ClientError):
self.server.start_game(self.clients[0])
self.server.challenge_response(self.clients[4], Protocol.TRUE)
self.server.start_game(self.clients[0])
assert sorted(self.server.initiate_game.call_args[0][0]) == sorted([self.clients[0], self.clients[1], self.clients[4]])
def test_challenge_request_rejected(self):
self.server.challenge(self.clients[0], self.clients[1]['name'], self.clients[4]['name'])
self.server.challenge_response(self.clients[1], Protocol.TRUE)
self.server.challenge_response(self.clients[4], Protocol.FALSE)
with pytest.raises(ClientError):
self.server.start_game(self.clients[0])
args = [call("%s %s %s%s" % (Protocol.CHALLENGE_RESPONSE, self.clients[1]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHALLENGE_RESPONSE, self.clients[4]['name'], Protocol.FALSE, Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
self.clients[1]['socket'].sendall.assert_has_calls(args)
self.clients[4]['socket'].sendall.assert_has_calls(args)
assert self.clients[3]['socket'].sendall.call_count == 7
<file_sep>/tests/test_server_setup.py
import pytest, time
from mock import Mock, call, patch
from rolit.server import *
from test_server import TestServer
@patch.object(random, 'shuffle', Mock())
class TestServerSetup(TestServer):
def test_it_connects(self):
sock = Mock()
self.server.create_game(self.clients[0])
self.server.connect(sock, "Bestuur_35", Protocol.CHAT_AND_CHALLENGE)
args = [call("%s %s %s%s" % (Protocol.HANDSHAKE, Protocol.CHAT_AND_CHALLENGE, Server.VERSION, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 1, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[0]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[1]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[2]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[3]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[4]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[5]['name'], Protocol.TRUE, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, "Bestuur_35", Protocol.TRUE, Protocol.EOL))]
sock.sendall.assert_has_calls(args)
def test_it_disconnects(self):
self.server.lobbies = { self.clients[0]['name'] : [self.clients[0], self.clients[1], self.clients[2]] }
self.server.join_game(self.clients[3], self.clients[0]['name'])
self.server.disconnect(self.clients[1])
self.server.join_game(self.clients[4], self.clients[0]['name'])
with pytest.raises(ClientError):
self.server.join_game(self.clients[5], self.clients[0]['name'])
self.server.disconnect(self.clients[0])
args = [call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 4, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 3, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.ONLINE, self.clients[1]['name'], Protocol.FALSE, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 4, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.UNDEFINED, 4, Protocol.EOL))]
self.clients[5]['socket'].sendall.assert_has_calls(args)
assert self.clients[5]['socket'].sendall.call_count == 17
def test_it_validates_name_is_unique(self):
with pytest.raises(ServerError):
self.server.connect(Mock(), "Met_TOM_op_de_koffie!")
self.server.disconnect(self.clients[0])
self.server.connect(Mock(), "Met_TOM_op_de_koffie!")
<file_sep>/tests/test_server_auth.py
import pytest
from mock import Mock, call, patch
import socket
from base64 import b64decode
from rolit.server import *
from test_server import TestServer
authentication_socket = Mock()
authentication_socket.recv = Mock(return_value="PUBKEY <KEY>)
@patch.object(random, 'shuffle', Mock())
@patch.object(random, 'random', Mock(return_value=35))
@patch.object(socket, 'socket', Mock(return_value=authentication_socket))
class TestServerAuth(TestServer):
def test_it_connects_with_authentication(self):
sock = Mock()
self.server.connect(sock, "player_twan", Protocol.CHAT_AND_CHALLENGE)
args = [call("%s %s %s %s%s" % (Protocol.HANDSHAKE, Protocol.CHAT_AND_CHALLENGE, Server.VERSION, "7a4f07ef7ac81ec31e04d55faffe33bdde93ec2398c338760e0d98adab7ba5acf2c39b2da1782f45e8a5a4d337dedcc647afebddd531782af42bafae98ce7ed5", Protocol.EOL))]
sock.sendall.assert_has_calls(args)
def test_a_client_authenticates_itself(self):
sock = Mock()
client = self.server.connect(sock, "player_twan", Protocol.CHAT_AND_CHALLENGE)
self.server.auth(client, "<KEY>/<KEY>)
args = [call("%s%s" % (Protocol.AUTH_OK, Protocol.EOL))]
sock.sendall.assert_has_calls(args)
def test_a_client_authenticates_itself_incorrectly(self):
sock = Mock()
client = self.server.connect(sock, "player_twan", Protocol.CHAT_AND_CHALLENGE)
with pytest.raises(ClientError):
self.server.auth(client, "MzU=")
def test_a_client_without_keypair_authenticates_itself(self):
sock = Mock()
client = self.server.connect(sock, "twan", Protocol.CHAT_AND_CHALLENGE)
with pytest.raises(ClientError):
self.server.auth(client, "MzU=")
<file_sep>/tests/test_server_stats.py
import pytest, time
from mock import Mock, call, patch
from rolit.server import *
from test_server import TestServer
@patch.object(random, 'shuffle', Mock())
class TestServerStats(TestServer):
def test_it_validates_timestamp_for_date_stats(self):
with pytest.raises(ClientError):
self.server.stats(self.clients[0], Protocol.STAT_DATE, 'Inter-Actief')
def test_it_validates_requested_stat(self):
with pytest.raises(ClientError):
self.server.stats(self.clients[0], Protocol.STAT_PLAYER + '...', self.clients[0]['name'])
def test_it_gives_the_right_date_stats(self):
self.clients[0]['verified'] = True
game = self.start_game_with_two_players()
self.server.move(self.clients[0], '5', '3')
self.server.game_over(self.server.network_games[id(game)])
self.server.stats(self.clients[0], Protocol.STAT_DATE, str(time.strftime("%Y-%m-%d")))
self.server.stats(self.clients[0], Protocol.STAT_DATE, "2013-09-03")
args = [call("%s %s %s %s %s%s" % (Protocol.STATS, Protocol.STAT_DATE, str(time.strftime("%Y-%m-%d")), self.clients[0]['name'], '1', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.STATS, Protocol.STAT_DATE, "2013-09-03", Protocol.UNDEFINED, Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
with pytest.raises(ClientError):
self.server.stats(self.clients[0], Protocol.STAT_DATE, "35")
with pytest.raises(ClientError):
self.server.stats(self.clients[0], Protocol.STAT_DATE, "03-09-2014")
def test_it_gives_the_right_player_stats(self):
self.clients[0]['verified'] = True
game = self.start_game_with_two_players()
self.server.move(self.clients[0], '5', '3')
self.server.game_over(self.server.network_games[id(game)])
self.server.stats(self.clients[0], Protocol.STAT_PLAYER, self.clients[0]['name'])
self.server.stats(self.clients[0], Protocol.STAT_PLAYER, self.clients[1]['name'])
self.server.stats(self.clients[0], Protocol.STAT_PLAYER, self.clients[2]['name'])
args = [call("%s %s %s %s%s" % (Protocol.STATS, Protocol.STAT_PLAYER, self.clients[0]['name'], '1', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.STATS, Protocol.STAT_PLAYER, self.clients[1]['name'], '0', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.STATS, Protocol.STAT_PLAYER, self.clients[2]['name'], Protocol.UNDEFINED, Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
<file_sep>/rolit/client.py
import copy
from base64 import b64encode
from rolit.game import GameOverError
from rolit.games import TwoPlayerGame, ThreePlayerGame, FourPlayerGame
from rolit.board import Board, BoardError
from rolit.helpers import Helpers
from rolit.protocol import Protocol
from rolit.protocol_extended import ProtocolExtended
from rolit.server import Server
class Client(object):
class Router(object):
routes = { Protocol.ONLINE : { 'method' : 'online' },
Protocol.CHALLENGABLE : { 'method' : 'challengable'},
Protocol.HANDSHAKE : { 'method' : 'handshake' },
Protocol.AUTH_OK : { 'method' : 'auth' },
Protocol.GAME : { 'method' : 'game' },
Protocol.START : { 'method' : 'start' },
Protocol.MOVE : { 'method' : 'move' },
Protocol.MOVED : { 'method' : 'moved' },
Protocol.GAME_OVER : { 'method' : 'game_over' },
Protocol.STATS : { 'method' : 'stats' },
ProtocolExtended.GAMES : { 'method' : 'games' },
ProtocolExtended.GAME_PLAYERS : { 'method' : 'game_players' },
ProtocolExtended.GAME_BOARD : { 'method' : 'game_board' } }
def __init__(self, client):
self.client = client
@staticmethod
def online(name, status):
Helpers.notice("[online] `%s`: %s" % (name, status == Protocol.TRUE))
@staticmethod
def challengable(name, status):
Helpers.notice("[challengable] `%s`: %s" % (name, status == Protocol.TRUE))
@staticmethod
def error(message):
print("Oops, that is an error: `%s`" % message)
@staticmethod
def game(name, status, number_of_players):
Helpers.notice("[game_update] `%s`, with `%s` players has status: %s" % (name, number_of_players, status))
def move(self):
if self.client.auto_fire:
self.client.ai()
else:
print("You may now enter a coord!")
print("[x] <xy> (autofire once with [a], enable auto_fire with [xa], disable with [xm])")
def moved(self, name, x, y):
x = int(x)
y = int(y)
Helpers.notice("A move is done by %s at x=%s, y=%s" % (name, x, y))
try:
self.client.game.place(x, y)
except GameOverError:
pass
except BoardError:
print("An invalid move is made!")
print(self.client.game.board)
def game_over(self, score, *players):
Helpers.notice("Game is over!")
print("Score was: %s, for winners: %s" % (score, list(players)))
def start(self, *players):
Helpers.notice("A game has started!")
print("Players are: %s" % list(players))
number_of_players = len(players)
if number_of_players == 2:
self.client.game = TwoPlayerGame()
elif number_of_players == 3:
self.client.game = ThreePlayerGame()
elif number_of_players == 4:
self.client.game = FourPlayerGame()
print(self.client.game.board)
def handshake(self, *options):
Helpers.notice("Connected established")
Helpers.notice("Chat = %s and challenge = %s" % (options[0] == Protocol.CHAT_ENABLED or options[0] == Protocol.CHAT_AND_CHALLENGE, options[0] == Protocol.CHALLENGE_ENABLED or options[0] == Protocol.CHAT_AND_CHALLENGE))
if len(options) >= 3:
signature = b64encode(Helpers.sign_data(self.client.private_key, options[2]))
self.client.socket.sendall("%s %s%s" % (Protocol.AUTH, signature, Protocol.EOL))
@staticmethod
def auth():
Helpers.warning("Authentication was successful")
@staticmethod
def games(games):
print("The following game ids are running:")
print(games)
@staticmethod
def game_players(*players):
print("The following players are in game `%s` active:" % players[0])
print(players[1:])
@staticmethod
def game_board(game_id, *board):
print("The board for game `%s` looks like:" % game_id)
if not board[0] == Protocol.UNDEFINED:
print(Board.decode(Protocol.SEPARATOR.join(board[0:])))
@staticmethod
def stats(stat, arg, *result):
if stat == Protocol.STAT_DATE:
print("The following player was at date `%s` best player:" % arg)
print(result)
elif stat == Protocol.STAT_PLAYER:
print("The following score was best of player `%s` best player:" % arg)
print(result)
options = { 'h' : { 'method': 'menu', 'args': 0, 'description': "Show this help menu" },
'1' : { 'method': 'create_game', 'args': 0, 'description': "Create a game" },
'2' : { 'method': 'join_game', 'args': 1, 'description': "<player> Join a game of that player" },
'3' : { 'method': 'get_games', 'args': 0, 'description': "Get all running games" },
'4' : { 'method': 'get_game_players', 'args': 1, 'description': "<id> Show game players" },
'5' : { 'method': 'get_game_board', 'args': 1, 'description': "<id> Show game board" },
'6' : { 'method': 'get_stat_date', 'args': 1, 'description': "<YYYY-MM-DD> Show best player on that date" },
'7' : { 'method': 'get_stat_player', 'args': 1, 'description': "<player> Show best score of that player" },
's' : { 'method': 'start_game', 'args': 0, 'hidden': True },
'x' : { 'method': 'place', 'args': 1, 'hidden': True },
'xa': { 'method': 'enable_ai', 'args': 0, 'hidden': True },
'xm': { 'method': 'disable_ai', 'args': 0, 'hidden': True },
'a' : { 'method': 'ai', 'args': 0, 'hidden': True }
}
def __init__(self, socket, private_key=None):
self.socket = socket
self.auto_fire = False
self.router = Client.Router(self)
self.private_key = private_key
@staticmethod
def menu():
Helpers.notice('-' * 16)
for key in sorted(Client.options.keys()):
value = Client.options[key]
if 'hidden' in value.keys():
continue
print("%s|%s" % (key, value['description']))
Helpers.notice('-' * 16)
def handshake(self, name):
if name.startswith('player_') and not self.private_key:
raise NoPrivateKeyError("When a player name starting with player_ is given, a private key is expected")
self.socket.sendall("%s %s %s %s%s" % (Protocol.HANDSHAKE, name, Protocol.CHAT_AND_CHALLENGE, Server.VERSION, Protocol.EOL))
def get_games(self):
self.socket.sendall("%s%s" % (ProtocolExtended.GAMES, Protocol.EOL))
def get_game_players(self, game_id):
self.socket.sendall("%s %s%s" % (ProtocolExtended.GAME_PLAYERS, game_id[0], Protocol.EOL))
def get_game_board(self, game_id):
self.socket.sendall("%s %s%s" % (ProtocolExtended.GAME_BOARD, game_id[0], Protocol.EOL))
def get_stat_date(self, date):
self.socket.sendall("%s %s %s%s" % (Protocol.STATS, Protocol.STAT_DATE, date[0], Protocol.EOL))
def get_stat_player(self, player):
self.socket.sendall("%s %s %s%s" % (Protocol.STATS, Protocol.STAT_PLAYER, player[0], Protocol.EOL))
def create_game(self):
self.socket.sendall("%s%s" % (Protocol.CREATE_GAME, Protocol.EOL))
print("Game created, wait for others to join")
print("Start this game with [s]")
def join_game(self, player):
self.socket.sendall("%s %s%s" % (Protocol.JOIN_GAME, player[0], Protocol.EOL))
print("Joined game `%s`, waiting for other to join and creator to start" % player)
def start_game(self):
self.socket.sendall("%s%s" % (Protocol.START_GAME, Protocol.EOL))
def place(self, coord):
try:
x = int(coord[0][0])
y = int(coord[0][1])
except ValueError:
return
game = copy.deepcopy(self.game)
try:
game.place(x, y)
except GameOverError:
pass
except BoardError:
print("The move you suggested is not valid, make another move please")
return
self.socket.sendall("%s %s %s%s" % (Protocol.MOVE, x, y, Protocol.EOL))
def enable_ai(self):
self.auto_fire = True
def disable_ai(self):
self.auto_fire = False
def ai(self):
game = copy.deepcopy(self.game)
for x in range(Board.DIM):
for y in range(Board.DIM):
try:
game.place(x, y)
except GameOverError:
pass
except BoardError:
continue
self.socket.sendall("%s %s %s%s" % (Protocol.MOVE, x, y, Protocol.EOL))
return
class NoPrivateKeyError(Exception): pass
<file_sep>/bin/server.py
import socket
import threading
import ConfigParser
from rolit.server import Server, ServerError, ClientError
from rolit.protocol import Protocol
from rolit.helpers import Helpers
class ClientHandler(threading.Thread):
def __init__(self, server, sock, client_address):
threading.Thread.__init__(self)
self.server = server
self.socket = sock
self.client_address = str(client_address)
self.name = str(client_address)
def run(self):
try:
line_reader = Helpers.read_lines(self.socket)
line = next(line_reader).strip()
Helpers.log("`%s`: `%s`" % (self.name, line))
data = line.split(Protocol.SEPARATOR)
# before everything else, HANDSHAKE
if not data[0] == Protocol.HANDSHAKE or len(data) < 2:
return
if len(data) == 2:
self.client = self.server.connect(self.socket, data[1])
else:
self.client = self.server.connect(self.socket, data[1], data[2])
self.name = self.client['name']
Helpers.notice('Client %s introduced itself as `%s`' % (self.client_address, self.name))
while True:
line = next(line_reader).strip()
if not line:
break
Helpers.log("`%s`: `%s`" % (self.name, line))
data = line.split(Protocol.SEPARATOR)
try:
route = self.server.routes[data[0]]
if len(data) >= 2:
getattr(self.server, route['method'])(self.client, *data[1:])
else:
getattr(self.server, route['method'])(self.client)
except (KeyError):
raise ClientError('Invalid command `%s`, refer to protocol' % line)
except(TypeError):
raise ClientError('Invalid arguments `%s`, refer to protocol' % line)
except ServerError as e:
Helpers.error('500 Internal Server Error: `%s`' % e)
self.socket.sendall('%s 500 Internal Server Error: `%s`%s' % (Protocol.ERROR, e, Protocol.EOL))
except ClientError as e:
Helpers.error('Client `%s` made a 400 Bad Request: `%s`' % (self.name, e))
self.socket.sendall('%s 400 Bad Request: `%s`%s' % (Protocol.ERROR, e, Protocol.EOL))
except (IOError, StopIteration) as e:
Helpers.error('Connection error `%s` with %s' % (e, self.name))
finally:
Helpers.log('Connection lost to %s' % self.name)
self.socket.close()
if hasattr(self, 'client'):
self.server.disconnect(self.client)
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
port = 3535
config = ConfigParser.ConfigParser()
config.read('config')
if config.has_option('server', 'port'):
port = config.getint('server', 'port')
sock.bind(('0.0.0.0', port))
sock.listen(1)
server = Server()
Helpers.log('A Rolit server has started for `%s` on port %s' % (socket.gethostname(), port))
while True:
conn, client_address = sock.accept()
Helpers.log('Connection established with %s' % str(client_address))
thread = ClientHandler(server, conn, client_address)
thread.daemon = True
thread.start()
if __name__ == "__main__":
main()
<file_sep>/rolit/server.py
import random, datetime
import hashlib
from base64 import b64decode
from rolit.helpers import Helpers
from rolit.games import TwoPlayerGame, ThreePlayerGame, FourPlayerGame
from rolit.game import GameOverError
from rolit.board import Board, BoardError
from rolit.protocol import Protocol
from rolit.protocol_extended import ProtocolExtended
from rolit.leaderboard import Leaderboard, NoHighScoresError
class Server(object):
SUPPORTS = Protocol.CHAT_AND_CHALLENGE
VERSION = 35
WINNING_SCORE = 1
LOSING_SCORE = 0
routes = {
Protocol.AUTH : { 'method' : 'auth' },
Protocol.CREATE_GAME : { 'method' : 'create_game' },
Protocol.START_GAME : { 'method' : 'start_game' },
Protocol.JOIN_GAME : { 'method' : 'join_game' },
Protocol.MOVE : { 'method' : 'move' },
Protocol.CHAT : { 'method' : 'chat' },
Protocol.CHALLENGE : { 'method' : 'challenge' },
Protocol.CHALLENGE_RESPONSE : { 'method' : 'challenge_response' },
Protocol.STATS : { 'method' : 'stats' },
ProtocolExtended.GAMES : { 'method' : 'send_games' },
ProtocolExtended.GAME_PLAYERS : { 'method' : 'send_game_players' },
ProtocolExtended.GAME_BOARD : { 'method' : 'send_game_board' }
}
def __init__(self):
self.leaderboard = Leaderboard()
self.clients = []
self.network_games = {}
self.lobbies = {}
self.challenge_list = {}
def get_client(self, name):
for client in self.clients:
if client['name'] == name:
return client
return False
def get_clients_in_lobbies(self):
return [item for sublist in self.lobbies.values() for item in sublist]
def get_clients_in_challenges(self):
return [item for sublist in self.challenge_list.values() for item in sublist]
def connect(self, socket, name, supported = Protocol.BAREBONE):
if self.get_client(name):
raise ServerError("Given name is already in use")
client = { 'socket' : socket,
'name' : name,
'chat' : supported == Protocol.CHAT_ENABLED or supported == Protocol.CHAT_AND_CHALLENGE,
'challenge' : supported == Protocol.CHALLENGE_ENABLED or supported == Protocol.CHAT_AND_CHALLENGE }
# authenticate
if name.startswith(Protocol.AUTH_PREFIX):
client['nonce'] = hashlib.sha512(str(random.random())).hexdigest()
client['socket'].sendall("%s %s %s %s%s" % (Protocol.HANDSHAKE, Server.SUPPORTS, Server.VERSION, client['nonce'], Protocol.EOL))
else:
client['socket'].sendall("%s %s %s%s" % (Protocol.HANDSHAKE, Server.SUPPORTS, Server.VERSION, Protocol.EOL))
for (lobby, clients) in self.lobbies.items():
client['socket'].sendall("%s %s %s %s%s" % (Protocol.GAME, lobby, Protocol.NOT_STARTED, len(clients), Protocol.EOL))
# push online clients
for c in self.clients:
client['socket'].sendall("%s %s %s%s" % (Protocol.ONLINE, c['name'], Protocol.TRUE, Protocol.EOL))
self.broadcast("%s %s %s%s" % (Protocol.ONLINE, name, Protocol.TRUE, Protocol.EOL))
client['socket'].sendall("%s %s %s%s" % (Protocol.ONLINE, name, Protocol.TRUE, Protocol.EOL))
# push challengable clients
if client['challenge']:
challengees = self.get_clients_in_challenges()
for c in self.clients:
if c['challenge']:
client['socket'].sendall("%s %s %s%s" % (Protocol.CHALLENGABLE, c['name'], Protocol.FALSE if c['name'] in challengees else Protocol.TRUE, Protocol.EOL))
self.broadcast("%s %s %s%s" % (Protocol.CHALLENGABLE, name, Protocol.TRUE, Protocol.EOL), 'challenge')
client['socket'].sendall("%s %s %s%s" % (Protocol.CHALLENGABLE, name, Protocol.TRUE, Protocol.EOL))
self.clients.append(client)
return client
def disconnect(self, client):
self.clients.remove(client)
for (lobby, clients) in self.lobbies.items():
if lobby == client['name']:
del(self.lobbies[lobby])
self.broadcast("%s %s %s %s%s" % (Protocol.GAME, lobby, Protocol.UNDEFINED, len(clients), Protocol.EOL))
elif client in clients:
clients.remove(client)
self.broadcast("%s %s %s %s%s" % (Protocol.GAME, lobby, Protocol.NOT_STARTED, len(clients), Protocol.EOL))
if client['challenge']:
try:
self.challenge_response(client, Protocol.FALSE)
self.broadcast("%s %s %s%s" % (Protocol.CHALLENGABLE, client['name'], Protocol.FALSE, Protocol.EOL), 'challenge')
except ClientError:
pass
self.broadcast("%s %s %s%s" % (Protocol.ONLINE, client['name'], Protocol.FALSE, Protocol.EOL))
if 'game_id' in client:
self.game_over(self.network_games[client['game_id']])
def auth(self, client, signature):
if 'nonce' not in client:
raise ClientError("You cannot authenticate yourself without a nonce")
if Helpers.verify_sign(client['name'], b64decode(signature), client['nonce']):
client['verified'] = True
client['socket'].sendall("%s%s" % (Protocol.AUTH_OK, Protocol.EOL))
else:
raise ClientError("Given signature is not correct")
def broadcast(self, msg, supported=""):
for client in self.clients:
if supported == "" or client[supported]:
client['socket'].sendall(msg)
def create_game(self, client):
if client['name'] in self.lobbies:
raise ClientError("You have already created a game")
if client in self.get_clients_in_lobbies():
raise ClientError("You have already joined a game")
if client['name'] in self.get_clients_in_challenges():
raise ClientError("You are already in challenge")
clients = self.lobbies[client['name']] = [ client ]
self.broadcast("%s %s %s %s%s" % (Protocol.GAME, client['name'], Protocol.NOT_STARTED, len(clients), Protocol.EOL))
def join_game(self, client, creator):
try:
clients = self.lobbies[creator]
except KeyError:
raise ClientError("Given client has not created a game")
if client in clients:
raise ClientError("You have already joined a game")
if len(clients) == 4:
raise ClientError("Given name points to a full game lobby")
clients.append(client)
self.broadcast("%s %s %s %s%s" % (Protocol.GAME, creator, Protocol.NOT_STARTED, len(clients), Protocol.EOL))
def start_game(self, creator):
try:
clients = self.lobbies[creator['name']]
if len(clients) == 1:
raise ClientError("You cannot start a game with only one player")
self.broadcast("%s %s %s %s%s" % (Protocol.GAME, creator['name'], Protocol.STARTED, len(clients), Protocol.EOL))
del(self.lobbies[creator['name']])
except KeyError:
try:
challengees = self.challenge_list[creator['name']]
if not all(challengees.values()):
raise ClientError("You cannot start a game until everyone accepts the challenge")
clients = [self.get_client(client_name) for client_name in challengees]
except KeyError:
raise ClientError("You have not created a game")
return self.initiate_game(clients)
def initiate_game(self, clients):
if len(clients) == 2:
game = TwoPlayerGame()
elif len(clients) == 3:
game = ThreePlayerGame()
elif len(clients) == 4:
game = FourPlayerGame()
game_id = id(game)
random.shuffle(clients)
self.network_games[game_id] = { 'clients' : clients, 'game' : game }
for client in clients:
client['game_id'] = game_id
client['socket'].sendall("%s %s%s" % (Protocol.START, ' '.join(c['name'] for c in clients), Protocol.EOL))
clients[0]['socket'].sendall("%s%s" % (Protocol.MOVE, Protocol.EOL))
return game
def move(self, client, x, y):
try:
network_game = self.network_games[client['game_id']]
except KeyError:
raise ClientError("Client is not in-game, refer to protocol")
try:
try:
x = int(x)
y = int(y)
except ValueError:
raise ClientError("Given coordinate `(%s, %s)` is not an integer, refer to protocol" % (x, y))
if x < 0 or x >= Board.DIM or y < 0 or y >= Board.DIM:
raise ClientError("Given coordinate `(%s, %s)` does not exist on board, refer to protocol" % (x, y))
if network_game['game'].current_player != network_game['clients'].index(client):
raise ClientError("Client is not current player of game, refer to protocol")
for c in network_game['clients']:
c['socket'].sendall("%s %s %s %s%s" % (Protocol.MOVED, client['name'], x, y, Protocol.EOL))
try:
network_game['game'].place(x, y)
except BoardError:
raise ClientError("Given coordinate `%s` is not a valid move on the current board" % [x, y])
network_game['clients'][network_game['game'].current_player]['socket'].sendall("%s%s" % (Protocol.MOVE, Protocol.EOL))
except (ClientError, GameOverError) as e:
self.game_over(network_game)
if isinstance(e, ClientError):
raise e
def game_over(self, network_game):
for client in network_game['clients']:
if client in self.clients:
winning_players = network_game['game'].winning_players()
winning_clients = [network_game['clients'][p] for p in winning_players]
client['socket'].sendall("%s %s %s%s" % (Protocol.GAME_OVER, Server.WINNING_SCORE, ' '.join(client['name'] for client in winning_clients), Protocol.EOL))
if client in winning_clients and 'verified' in client:
self.leaderboard.add_score(client['name'], datetime.datetime.now(), Server.WINNING_SCORE)
else:
self.leaderboard.add_score(client['name'], datetime.datetime.now(), Server.LOSING_SCORE)
del(client['game_id'])
del self.network_games[id(network_game['game'])]
def chat(self, sender, *message):
if not sender['chat']:
raise ClientError("You said you did not support chat, so you cannot send a chat message")
if 'game_id' in sender:
clients = self.network_games[sender['game_id']]['clients']
else:
clients = [client for client in self.clients if 'game_id' not in client]
chat_clients = [client for client in clients if client['chat']]
for chat_client in chat_clients:
chat_client['socket'].sendall("%s %s %s%s" % (Protocol.CHAT, sender['name'], " ".join(message), Protocol.EOL))
def challenge(self, challenger, *challenged_names):
if not challenger['challenge']:
raise ClientError("You said you did not support challenges, so you cannot send a challenge request")
if len(challenged_names) > 3:
raise ClientError("You challenged more than 3 players, refer to the protocol")
challenged_clients = [self.get_client(challengee) for challengee in challenged_names]
if challenger in challenged_clients:
raise ClientError("You challenged yourself, what do you think?")
if False in challenged_clients:
raise ClientError("You challenged someone who does not exist")
if False in [challenged_client['challenge'] for challenged_client in challenged_clients]:
raise ClientError("You challenged someone who does not support challenges")
if True in [challenged_client in self.get_clients_in_lobbies() for challenged_client in challenged_clients]:
raise ClientError("You challenged someone who already is in a not started game")
if True in ['game_id' in challenged_client for challenged_client in challenged_clients]:
raise ClientError("You challenged someone who already is in started game")
all_challengees = [item for sublist in self.challenge_list.values() for item in sublist]
if len(list(set(all_challengees) & set(challenged_names))) > 0:
raise ClientError("You challenged someone who already is in challenge")
self.challenge_list[challenger['name']] = { challenger['name'] : True }
self.broadcast("%s %s %s%s" % (Protocol.CHALLENGABLE, challenger['name'], Protocol.FALSE, Protocol.EOL), 'challenge')
for challenged_client in challenged_clients:
self.challenge_list[challenger['name']][challenged_client['name']] = False
challenged_client['socket'].sendall("%s %s %s%s" % (Protocol.CHALLENGE, challenger['name'], Protocol.SEPARATOR.join(challenged_names), Protocol.EOL))
self.broadcast("%s %s %s%s" % (Protocol.CHALLENGABLE, challenged_client['name'], Protocol.FALSE, Protocol.EOL), 'challenge')
def challenge_response(self, challenger, response):
response = Protocol.TRUE if response == Protocol.TRUE else Protocol.FALSE
for (challenge, challengees) in self.challenge_list.iteritems():
if challenger['name'] in challengees:
for challengee in challengees:
if self.get_client(challengee):
self.get_client(challengee)['socket'].sendall("%s %s %s%s" % (Protocol.CHALLENGE_RESPONSE, challenger['name'], response, Protocol.EOL))
if response == Protocol.TRUE:
challengees[challenger['name']] = True
else:
self.remove_challenge(challenge)
return
raise ClientError("You responded while you were not challenged")
def remove_challenge(self, challenger):
for challengee in self.challenge_list[challenger]:
if self.get_client(challengee):
self.broadcast("%s %s %s%s" % (Protocol.CHALLENGABLE, challengee, Protocol.TRUE, Protocol.EOL), 'challenge')
del(self.challenge_list[challenger])
def stats(self, client, stat, query):
try:
if stat == Protocol.STAT_DATE:
try:
date = query.split("-")
if not len(date) == 3:
raise ClientError("Given argument `%s` is malformed, refer to protocol" % date)
date = datetime.datetime(int(date[0]), int(date[1]), int(date[2]))
except ValueError:
raise ClientError("Given argument `%s` cannot be converted to a valid date" % query)
score = self.leaderboard.best_score_of_date(date)
client['socket'].sendall("%s %s %s %s %s%s" % (Protocol.STATS, stat, query, score.name, score.score, Protocol.EOL))
elif stat == Protocol.STAT_PLAYER:
score = self.leaderboard.best_score_of_player(query)
client['socket'].sendall("%s %s %s %s%s" % (Protocol.STATS, stat, query, score.score, Protocol.EOL))
else:
raise ClientError("Given stat `%s` is not recognized, refer to protocol" % stat)
except NoHighScoresError:
client['socket'].sendall("%s %s %s %s%s" % (Protocol.STATS, stat, query, Protocol.UNDEFINED, Protocol.EOL))
def send_games(self, client):
game_ids = [str(game) for game in self.network_games.keys()]
if not game_ids:
game_ids = [Protocol.UNDEFINED]
client['socket'].sendall("%s %s%s" % (ProtocolExtended.GAMES, Protocol.SEPARATOR.join(game_ids), Protocol.EOL))
def send_game_players(self, client, game_id):
try:
game_players = [player['name'] for player in self.network_games[int(game_id)]['clients']]
client['socket'].sendall("%s %s %s%s" % (ProtocolExtended.GAME_PLAYERS, game_id, Protocol.SEPARATOR.join(game_players), Protocol.EOL))
except (ValueError, KeyError):
client['socket'].sendall("%s %s %s%s" % (ProtocolExtended.GAME_PLAYERS, game_id, Protocol.UNDEFINED, Protocol.EOL))
def send_game_board(self, client, game_id):
try:
board = self.network_games[int(game_id)]['game'].board
client['socket'].sendall("%s %s %s%s" % (ProtocolExtended.GAME_BOARD, game_id, board.encode(), Protocol.EOL))
except (ValueError, KeyError):
client['socket'].sendall("%s %s %s%s" % (ProtocolExtended.GAME_BOARD, game_id, Protocol.UNDEFINED, Protocol.EOL))
class ServerError(Exception): pass
class ClientError(Exception): pass
<file_sep>/requirements.txt
termcolor
pytest
pytest-cov
pytest-xdist
mock
pycrypto
pbkdf2
ConfigParser
<file_sep>/rolit/game.py
import abc
from rolit.board import Board
from rolit.ball import Ball
class Game(object):
__metaclass__ = abc.ABCMeta
def __init__(self, player_amount):
self.board = Board()
self.board.board[Board.DIM/2 - 1][Board.DIM/2 - 1] = Ball(Ball.RED)
self.board.board[Board.DIM/2 - 1][Board.DIM/2] = Ball(Ball.BLUE)
self.balls_left = Board.DIM * Board.DIM - 4
self.player_amount = player_amount
self.current_player = 0
@abc.abstractmethod
def players(self):
return
def winning_players(self):
stats = self.board.stats()
player_stats = dict((color, amount) for color, amount in stats.items() if color in self.players().values())
player_max = max(player_stats.values())
return [player for (player, color) in self.players().items() if stats[color] == player_max]
def place(self, x, y):
color = self.players()[self.current_player]
self.board.place(x, y, color)
self.current_player = (self.current_player + 1) % self.player_amount
self.balls_left -= 1
if self.balls_left == 0:
raise GameOverError('Game is over and won by %s' % self.winning_players())
class GameOverError(Exception): pass
<file_sep>/README.md
Rolit
=====
[](https://travis-ci.org/tcoenraad/rolit)
[](https://landscape.io/github/tcoenraad/rolit/master)
a Rolit server for Softwaresystemen - Python edition
Requirements
============
- [Python 2.7](http://www.python.org/download/releases/2.7/)
- [pip](http://www.pip-installer.org/en/latest/installing.html)
- For [pycrypto](https://pypi.python.org/pypi/pycrypto) you need, depending on your OS, `python-dev` or other build tools
How to set-up
=============
$ sudo pip install -r requirements.txt
How to run
==========
Run server:
$ python bin/server.py
Run client:
$ python bin/client.py [host = localhost [port = 3535 [player_name = Monitor_[0-3535] [private_key_file=./private_key]]]]
Run tests:
$ py.test
Run tests with coverage:
$ py.test --cov rolit tests/
Screenshot
==========

<file_sep>/tests/test_games.py
from rolit.games import *
from rolit.game import *
from rolit.board import *
from rolit.ball import Ball
import pytest
class TestGame(object):
def test_it_gives_right_winners_for_two_player_games(self):
two_player_game = TwoPlayerGame()
two_player_game.balls_left = 6
assert two_player_game.winning_players() == [0, 1]
two_player_game.place(5, 3)
assert two_player_game.winning_players() == [0]
two_player_game.place(4, 2)
two_player_game.place(5, 5)
two_player_game.place(2, 5)
assert two_player_game.winning_players() == [0, 1]
two_player_game.place(2, 4)
with pytest.raises(GameOverError):
two_player_game.place(2, 3)
assert two_player_game.winning_players() == [1]
def test_it_gives_right_winners_for_three_player_games(self):
three_player_game = ThreePlayerGame()
three_player_game.balls_left = 5
assert three_player_game.winning_players() == [0, 1, 2]
three_player_game.place(3, 5)
assert three_player_game.winning_players() == [0]
three_player_game.place(2, 3)
three_player_game.place(2, 6)
three_player_game.place(5, 5)
with pytest.raises(GameOverError):
three_player_game.place(5, 3)
assert three_player_game.winning_players() == [1]
def test_it_gives_right_winners_for_four_player_games(self):
four_player_game = FourPlayerGame()
four_player_game.balls_left = 4
assert four_player_game.winning_players() == [0, 1, 2, 3]
four_player_game.place(3, 5)
four_player_game.place(2, 3)
assert four_player_game.winning_players() == [0]
four_player_game.place(2, 6)
assert four_player_game.winning_players() == [2]
with pytest.raises(GameOverError):
four_player_game.place(2, 5)
assert four_player_game.winning_players() == [2, 3]
<file_sep>/tests/test_server_extended.py
import pytest
from mock import Mock, call, patch
from rolit.server import *
from test_server import TestServer
@patch.object(random, 'shuffle', Mock())
class TestServerExtended(TestServer):
def test_send_games(self):
self.server.send_games(self.clients[0])
args = call("%s %s%s" % (ProtocolExtended.GAMES, Protocol.UNDEFINED, Protocol.EOL))
self.clients[0]['socket'].sendall.assert_has_calls(args)
game = self.start_game_with_two_players()
self.server.send_games(self.clients[0])
args = call("%s %s%s" % (ProtocolExtended.GAMES, id(game), Protocol.EOL))
self.clients[0]['socket'].sendall.assert_has_calls(args)
def test_send_game_players(self):
game = self.start_game_with_two_players()
self.server.send_game_players(self.clients[0], 'Inter-Actief')
self.server.send_game_players(self.clients[0], id(game))
args = [call("%s %s %s%s" % (ProtocolExtended.GAME_PLAYERS, 'Inter-Actief', Protocol.UNDEFINED, Protocol.EOL)),
call("%s %s %s %s%s" % (ProtocolExtended.GAME_PLAYERS, id(game), self.clients[0]['name'], self.clients[1]['name'], Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
def test_send_game_board(self):
game = self.start_game_with_two_players()
self.server.send_game_board(self.clients[0], 'Inter-Actief')
self.server.send_game_board(self.clients[0], id(game))
args = [call("%s %s %s%s" % (ProtocolExtended.GAME_BOARD, 'Inter-Actief', Protocol.UNDEFINED, Protocol.EOL)),
call("%s %s %s%s" % (ProtocolExtended.GAME_BOARD, id(game), game.board.encode(), Protocol.EOL))]
self.clients[0]['socket'].sendall.assert_has_calls(args)
<file_sep>/rolit/ball.py
from termcolor import colored
from rolit.protocol_extended import ProtocolExtended
class Ball(object):
EMPTY = 0
RED = 1
YELLOW = 2
BLUE = 3
GREEN = 4
def __init__(self, color = EMPTY):
self.color = color
def recolor(self, color):
self.color = color
def encode(self):
if self == Ball(Ball.RED):
return ProtocolExtended.RED
elif self == Ball(Ball.BLUE):
return ProtocolExtended.BLUE
elif self == Ball(Ball.YELLOW):
return ProtocolExtended.YELLOW
elif self == Ball(Ball.GREEN):
return ProtocolExtended.GREEN
else:
return ProtocolExtended.EMPTY
@staticmethod
def decode(color):
if color == ProtocolExtended.RED:
return Ball(Ball.RED)
elif color == ProtocolExtended.BLUE:
return Ball(Ball.BLUE)
elif color == ProtocolExtended.YELLOW:
return Ball(Ball.YELLOW)
elif color == ProtocolExtended.GREEN:
return Ball(Ball.GREEN)
else:
return Ball(Ball.EMPTY)
def __eq__(self, other):
return isinstance(other, self.__class__) and self.color == other.color
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
if self == Ball(Ball.RED):
return colored(Ball.RED, 'red')
elif self == Ball(Ball.BLUE):
return colored(Ball.BLUE, 'blue')
elif self == Ball(Ball.YELLOW):
return colored(Ball.YELLOW, 'yellow')
elif self == Ball(Ball.GREEN):
return colored(Ball.GREEN, 'green')
else:
return str(Ball.EMPTY)
<file_sep>/bin/client.py
import readline
import socket
import sys
import threading
import random
from rolit.client import Client, NoPrivateKeyError
from rolit.protocol import Protocol
from rolit.helpers import Helpers
class ServerHandler(threading.Thread):
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
def run(self):
while True:
response = self.client.socket.recv(4096)
# wait for Protocol.EOL
if not response:
break
sys.stdout.write('\r')
lines = response.strip().split(Protocol.EOL)
for line in lines:
data = line.split(Protocol.SEPARATOR)
try:
if len(data) == 1:
getattr(self.client.router, Client.Router.routes[data[0]]['method'])()
else:
getattr(self.client.router, Client.Router.routes[data[0]]['method'])(*data[1:])
except KeyError:
self.client.Router.error(line)
sys.stdout.write('$ ' + readline.get_line_buffer())
sys.stdout.flush()
def main():
host = 'localhost'
port = 3535
name = "Monitor_%s" % random.randint(0, 3535)
private_key_file = "./private_key"
if len(sys.argv) >= 2:
host = sys.argv[1]
if len(sys.argv) >= 3 and sys.argv[2].isdigit():
port = int(sys.argv[2])
if len(sys.argv) >= 4:
name = sys.argv[3]
if len(sys.argv) >= 5:
private_key_file = sys.argv[4]
try:
private_key = open(private_key_file, "r").read()
except IOError:
private_key = None
client = Client(socket.socket(socket.AF_INET, socket.SOCK_STREAM), private_key)
client.socket.connect((host, port))
thread = ServerHandler(client)
thread.daemon = True
thread.start()
try:
client.handshake(name)
except NoPrivateKeyError as e:
Helpers.error(e)
return
print("Welcome to the Rolit monitor, %s!" % name)
Client.menu()
while True:
s = raw_input('$ ')
data = s.split(Protocol.SEPARATOR)
try:
option = data[0]
if not Client.options[option]['args'] == len(data) - 1:
continue
if len(data) == 1:
getattr(client, Client.options[option]['method'])()
else:
getattr(client, Client.options[option]['method'])(data[1:])
except (KeyError, ValueError):
continue
if __name__ == "__main__":
main()
<file_sep>/tests/test_leaderboard.py
import pytest
import datetime
from rolit.leaderboard import *
from rolit.protocol import Protocol
class TestLeaderboard(object):
def setup_method(self, method):
self.leaderboard = Leaderboard()
def test_it_gives_high_score(self):
with pytest.raises(NoHighScoresError):
self.leaderboard.high_scores()
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 1)
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 3), 1)
assert sorted(self.leaderboard.high_scores().keys()) == ['Eva', 'Twan']
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 3), 1)
assert sorted(self.leaderboard.high_scores().keys()) == ['Eva']
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 1)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 1)
assert sorted(self.leaderboard.high_scores().keys()) == ['Twan']
def test_it_gives_best_score_of_player(self):
with pytest.raises(NoHighScoresError):
self.leaderboard.best_score_of_player('Twan')
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 1)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 3)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 2)
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 3), 2)
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 3), 1)
assert self.leaderboard.best_score_of_player('Twan').score == 3
assert self.leaderboard.best_score_of_player('Eva').score == 2
def test_it_gives_best_score_of_date(self):
with pytest.raises(NoHighScoresError):
self.leaderboard.best_score_of_date(datetime.datetime(2013, 9, 2))
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 1)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 3), 3)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 4), 2)
self.leaderboard.add_score('Twan', datetime.datetime(2013, 9, 4), 4)
assert self.leaderboard.best_score_of_date(datetime.datetime(2013, 9, 3)).score == 3
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 3), 5)
self.leaderboard.add_score('Eva', datetime.datetime(2013, 9, 4), 1)
assert self.leaderboard.best_score_of_date(datetime.datetime(2013, 9, 3)).score == 5
assert self.leaderboard.best_score_of_date(datetime.datetime(2013, 9, 4)).score == 4
<file_sep>/rolit/protocol_extended.py
class ProtocolExtended(object):
GAMES = 'games'
GAME_PLAYERS = 'game_players'
GAME_BOARD = 'game_board'
RED = 'red'
YELLOW = 'yellow'
BLUE = 'blue'
GREEN = 'green'
EMPTY = 'empty'
<file_sep>/rolit/games.py
from game import Game
from board import Board
from ball import Ball
class TwoPlayerGame(Game):
def __init__(self):
super(TwoPlayerGame, self).__init__(2)
def players(self):
return {
0 : Ball.RED,
1 : Ball.GREEN
}
class ThreePlayerGame(Game):
def __init__(self):
super(ThreePlayerGame, self).__init__(3)
self.board.board[Board.DIM/2][Board.DIM/2 - 1] = Ball(Ball.YELLOW)
def players(self):
return {
0 : Ball.RED,
1 : Ball.BLUE,
2 : Ball.GREEN
}
class FourPlayerGame(Game):
def __init__(self):
super(FourPlayerGame, self).__init__(4)
self.board.board[Board.DIM/2][Board.DIM/2 - 1] = Ball(Ball.YELLOW)
self.board.board[Board.DIM/2][Board.DIM/2] = Ball(Ball.GREEN)
def players(self):
return {
0 : Ball.RED,
1 : Ball.BLUE,
2 : Ball.GREEN,
3 : Ball.YELLOW
}<file_sep>/rolit/protocol.py
class Protocol(object):
HANDSHAKE = 'hello'
GAME = 'game'
CREATE_GAME = 'createGame'
JOIN_GAME = 'joinGame'
START_GAME = 'startGame'
START = 'start'
MOVE = 'move'
MOVED = 'moveDone'
GAME_OVER = 'gameOver'
CHAT = 'message'
ONLINE = 'online'
CHALLENGE = 'challenge'
CHALLENGE_RESPONSE = 'challengeResponse'
CHALLENGABLE = 'canBeChallenged'
STATS = 'highscore'
STAT_DATE = 'date'
STAT_PLAYER = 'player'
BAREBONE = '0'
CHAT_ENABLED = '1'
CHALLENGE_ENABLED = '2'
CHAT_AND_CHALLENGE = '3'
AUTH_PREFIX = 'player_'
AUTH = 'auth'
AUTH_OK = 'authOk'
SEPARATOR = ' '
EOL = "\r\n"
TRUE = 'true'
FALSE = 'false'
STARTED = '1'
NOT_STARTED = '0'
UNDEFINED = '-1'
ERROR = 'error'
<file_sep>/rolit/leaderboard.py
class Leaderboard(object):
def __init__(self):
self.scores = []
def add_score(self, name, date, score):
self.scores.append(self.Score(name, date, score))
def scores_per_player(self):
if len(self.scores) == 0:
raise NoHighScoresError("No high scores available")
scores_per_player = {}
for score in self.scores:
scores_per_player.setdefault(score.name, 0)
scores_per_player[score.name] += score.score
return scores_per_player
def high_scores(self):
scores_per_player = self.scores_per_player()
max_score = max(scores_per_player.values())
return dict((player, score) for player, score in scores_per_player.iteritems() if score == max_score)
def best_score_of_date(self, date):
scores = [score for score in self.scores if score.date.date() == date.date()]
if len(scores) == 0:
raise NoHighScoresError("No high scores on this date")
return max(scores, key = lambda x: x.score)
def best_score_of_player(self, name):
scores = [score for score in self.scores if score.name == name]
if len(scores) == 0:
raise NoHighScoresError("No high scores for this player")
return max(scores, key = lambda x: x.score)
class Score(object):
def __init__(self, name, date, score):
self.name = name
self.date = date
self.score = score
class NoHighScoresError(Exception): pass
<file_sep>/tests/test_board.py
from rolit.board import *
from rolit.ball import Ball
import pytest
class TestBoard():
def setup_method(self, method):
self.board = Board()
def test_it_setups(self):
assert self.board.field(3, 3) == Ball(Ball.RED)
assert self.board.field(3, 4) == Ball(Ball.BLUE)
assert self.board.field(4, 3) == Ball(Ball.YELLOW)
assert self.board.field(4, 4) == Ball(Ball.GREEN)
def test_it_places_fields_vertically(self):
assert self.board.field(3, 2) == Ball(Ball.EMPTY)
with pytest.raises(ForcedMoveError):
self.board.place(3, 2, Ball.RED)
self.board.place(3, 2, Ball.BLUE)
assert self.board.field(3, 2) == Ball(Ball.BLUE)
assert self.board.field(3, 3) == Ball(Ball.BLUE)
def test_it_places_fields_horizontally(self):
assert self.board.field(5, 4) == Ball(Ball.EMPTY)
with pytest.raises(ForcedMoveError):
self.board.place(5, 4, Ball.RED)
self.board.place(5, 4, Ball.BLUE)
assert self.board.field(5, 4) == Ball(Ball.BLUE)
assert self.board.field(4, 4) == Ball(Ball.BLUE)
def test_it_places_fields_diagonally_up(self):
assert self.board.field(5, 2) == Ball(Ball.EMPTY)
with pytest.raises(ForcedMoveError):
self.board.place(5, 2, Ball.RED)
self.board.place(5, 2, Ball.BLUE)
assert self.board.field(5, 2) == Ball(Ball.BLUE)
assert self.board.field(4, 3) == Ball(Ball.BLUE)
with pytest.raises(ForcedMoveError):
self.board.place(2, 5, Ball.BLUE)
def test_it_places_fields_diagonally_down(self):
assert self.board.field(5, 5) == Ball(Ball.EMPTY)
with pytest.raises(ForcedMoveError):
self.board.place(5, 5, Ball.BLUE)
self.board.place(5, 5, Ball.RED)
assert self.board.field(5, 5) == Ball(Ball.RED)
assert self.board.field(4, 4) == Ball(Ball.RED)
with pytest.raises(ForcedMoveError):
self.board.place(2, 2, Ball.RED)
def test_it_takes_no_double_placements(self):
self.board.place(3, 2, Ball.BLUE)
with pytest.raises(AlreadyOccupiedError):
self.board.place(3, 2, Ball.BLUE)
def test_it_validates_given_coordinates_represent_a_field_on_board(self):
with pytest.raises(AlreadyOccupiedError):
self.board.place(-1, 0, Ball.RED)
with pytest.raises(AlreadyOccupiedError):
self.board.place(8, 8, Ball.RED)
with pytest.raises(AlreadyOccupiedError):
self.board.place('a', 'b', Ball.RED)
def test_it_only_allows_adjacent_placements(self):
with pytest.raises(NotAdjacentError):
self.board.place(6, 2, Ball.GREEN)
self.board.place(5, 3, Ball.RED)
self.board.place(6, 2, Ball.GREEN)
assert self.board.field(6, 2) == Ball(Ball.GREEN)
assert self.board.field(5, 3) == Ball(Ball.GREEN)
def test_it_allows_any_move_if_blocking_is_not_forced(self):
with pytest.raises(ForcedMoveError):
self.board.place(2, 2, Ball.YELLOW)
self.board.place(5, 3, Ball.RED)
self.board.place(2, 2, Ball.YELLOW)
def test_an_edge_case(self):
self.board.place(5, 5, Ball.RED)
self.board.place(6, 6, Ball.GREEN)
self.board.place(7, 7, Ball.RED)
assert self.board.field(7, 7) == Ball(Ball.RED)
self.board.place(7, 6, Ball.GREEN)
assert self.board.field(7, 7) == Ball(Ball.RED)
def test_an_edge_line(self):
self.board.place(5, 5, Ball.RED)
self.board.place(6, 6, Ball.GREEN)
self.board.place(7, 7, Ball.RED)
self.board.place(7, 6, Ball.GREEN)
self.board.place(7, 5, Ball.RED)
self.board.place(7, 4, Ball.GREEN)
self.board.place(7, 3, Ball.RED)
self.board.place(7, 2, Ball.GREEN)
self.board.place(7, 1, Ball.RED)
assert self.board.field(7, 7) == Ball(Ball.RED)
self.board.place(7, 0, Ball.GREEN)
assert self.board.field(7, 7) == Ball(Ball.RED)
self.board.place(5, 3, Ball.RED)
self.board.place(6, 0, Ball.GREEN)
assert self.board.field(6, 0) == Ball(Ball.GREEN)
def test_it_encodes(self):
assert self.board.encode() == "empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty red yellow empty empty empty empty empty empty blue green empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty"
def test_it_decode(self):
board = Board.decode("empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty red yellow empty empty empty empty empty empty blue green empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty empty")
assert board.field(3, 3) == Ball(Ball.RED)
assert board.field(3, 4) == Ball(Ball.BLUE)
assert board.field(4, 3) == Ball(Ball.YELLOW)
assert board.field(4, 4) == Ball(Ball.GREEN)
<file_sep>/tests/test_client_handler.py
import pytest
from mock import Mock, call
from socket import socket
from bin.server import ClientHandler
from rolit.server import Server
from rolit.protocol import Protocol
class TestClientHandler(object):
def test_it_handles_eol_correctly(self):
sock = Mock()
return_values = ["%s " % Protocol.HANDSHAKE,
"Tw",
"an",
" %s 35" % Protocol.CHAT_AND_CHALLENGE,
"%s%s" % (Protocol.EOL, Protocol.CREATE_GAME),
"%s" % Protocol.EOL,
"%s Dit is "
"een test! %s" % (Protocol.CHAT, Protocol.EOL)]
sock.recv.side_effect = lambda(self): return_values.pop(0) if len(return_values) > 0 else ""
clienthandler = ClientHandler(Server(), sock, "mocked_client_handler")
clienthandler.run()
args = [call("%s %s %s%s" % (Protocol.HANDSHAKE, Server.SUPPORTS, Server.VERSION, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, "Twan", 0, 1, Protocol.EOL)),
call("%s %s %s%s" % (Protocol.CHAT, "Twan", "Dit is een test!", Protocol.EOL))]
sock.sendall.assert_has_calls(args, True)
<file_sep>/rolit/board.py
# -*- coding: utf-8 -*-
from rolit.ball import Ball
from rolit.protocol import Protocol
class Board(object):
DIM = 8
def __init__(self):
self.board = [[Ball() for __ in range(Board.DIM)] for __ in range(Board.DIM)]
self.board[Board.DIM/2 - 1][Board.DIM/2 - 1] = Ball(Ball.RED)
self.board[Board.DIM/2 - 1][Board.DIM/2] = Ball(Ball.BLUE)
self.board[Board.DIM/2][Board.DIM/2 - 1] = Ball(Ball.YELLOW)
self.board[Board.DIM/2][Board.DIM/2] = Ball(Ball.GREEN)
def stats(self):
stats = {
Ball.RED : 0,
Ball.BLUE : 0,
Ball.YELLOW : 0,
Ball.GREEN : 0
}
for row in self.board:
for field in row:
if field == Ball(Ball.RED):
stats[Ball.RED] += 1
elif field == Ball(Ball.BLUE):
stats[Ball.BLUE] += 1
elif field == Ball(Ball.YELLOW):
stats[Ball.YELLOW] += 1
elif field == Ball(Ball.GREEN):
stats[Ball.GREEN] += 1
return stats
def field(self, x, y):
if x >= Board.DIM or x < 0 or y >= Board.DIM or y < 0:
return False
return self.board[x][y]
def direct_adjacent_fields(self, x, y):
return [self.field(x + offset_x, y + offset_y) for offset_x in range(-1, 2) for offset_y in range(-1, 2)]
def direct_adjacent_colors(self, x, y):
return filter((lambda x: x != Ball(Ball.EMPTY)), self.direct_adjacent_fields(x, y))
def any_forced_move(self, color):
for x in range(Board.DIM):
for y in range(Board.DIM):
if not self.field(x, y) == Ball(Ball.EMPTY):
continue
elif len(self.direct_adjacent_colors(x, y)) == 0:
continue
elif len(self.filtered_adjacent_fields(x, y, color)) > 0:
return (x, y)
return False
def filtered_adjacent_fields(self, x, y, color):
filtered_fields = []
for orientation in ['horizontal', 'vertical', 'diagonal-up', 'diagonal-down']:
for direction in [-1, 1]:
fields = []
# bounce from edge to edge, please!
for shift in range(1, Board.DIM + 2):
x_coord = x
y_coord = y
if orientation == 'horizontal':
x_coord += direction * shift
elif orientation == 'vertical':
y_coord += direction * shift
elif orientation == 'diagonal-up':
x_coord += direction * shift
y_coord += direction * shift
elif orientation == 'diagonal-down':
x_coord -= direction * shift
y_coord += direction * shift
field = self.field(x_coord, y_coord)
# stop walking a direction if field is:
# empty (then clear the found fields as you did not find your own color)
# or your own color (then return all results till than)
if not field or field == Ball(Ball.EMPTY):
fields = []
break
elif field == Ball(color):
break
else:
fields.append(field)
filtered_fields += fields
return filtered_fields
def place(self, x, y, color):
if not self.field(x, y) == Ball(Ball.EMPTY):
raise AlreadyOccupiedError('Field is already occupied or not on this board')
if len(self.direct_adjacent_colors(x, y)) == 0:
raise NotAdjacentError('Field is not directly adjacent to any field')
filtered_adjacent_fields = self.filtered_adjacent_fields(x, y, color)
any_forced_move = self.any_forced_move(color)
if len(filtered_adjacent_fields) == 0 and any_forced_move:
raise ForcedMoveError('This move is not forced, while forced moves are left, like `x=%s, y=%s`' % any_forced_move)
for field in filtered_adjacent_fields:
field.recolor(color)
self.field(x, y).recolor(color)
def encode(self):
string = ""
for y in range(Board.DIM):
for x in range(Board.DIM):
field = self.field(x, y)
string += Protocol.SEPARATOR
string += field.encode()
return string.strip()
@staticmethod
def decode(board_string):
board_fields = board_string.split(Protocol.SEPARATOR)
board = Board()
for y in range(Board.DIM):
for x in range(Board.DIM):
board.board[x][y] = Ball.decode(board_fields[y * Board.DIM + x])
return board
def __str__(self):
string = '\n'
for y in range(Board.DIM):
string += str(y) + '|'
for x in range(Board.DIM):
field = self.field(x, y)
string += ' '
string += str(field)
string += '\n' # one new line per column
string += ' '
for col in range(Board.DIM):
string += '– '
string += '\n '
for col in range(Board.DIM):
string += str(col) + ' '
return string
class BoardError(Exception): pass
class AlreadyOccupiedError(BoardError): pass
class NotAdjacentError(BoardError): pass
class ForcedMoveError(BoardError): pass
<file_sep>/tests/test_server.py
import pytest, time
from mock import Mock, call, patch
from rolit.server import *
@patch.object(random, 'shuffle', Mock())
class TestServer(object):
def setup_method(self, method):
self.server = Server()
self.mocked_clients = [{ 'socket' : Mock(), 'name' : "Met_TOM_op_de_koffie!", 'supported' : Protocol.CHAT_AND_CHALLENGE },
{ 'socket' : Mock(), 'name' : "Yorinf", 'supported' : Protocol.CHAT_AND_CHALLENGE },
{ 'socket' : Mock(), 'name' : "Tegel_14", 'supported' : Protocol.CHAT_ENABLED },
{ 'socket' : Mock(), 'name' : "Lalala_geld", 'supported' : Protocol.BAREBONE },
{ 'socket' : Mock(), 'name' : "IEOEDMB", 'supported' : Protocol.CHALLENGE_ENABLED },
{ 'socket' : Mock(), 'name' : "Inter-Actief", 'supported' : Protocol.CHAT_AND_CHALLENGE }]
self.clients = []
for client in self.mocked_clients:
self.clients.append(self.server.connect(client['socket'], client['name'], client['supported']))
def start_game_with_two_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
return self.server.start_game(self.clients[0])
def start_game_with_three_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.join_game(self.clients[2], self.clients[0]['name'])
return self.server.start_game(self.clients[0])
def start_game_with_four_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.join_game(self.clients[2], self.clients[0]['name'])
self.server.join_game(self.clients[3], self.clients[0]['name'])
return self.server.start_game(self.clients[0])
<file_sep>/rolit/helpers.py
import time
import socket
from termcolor import colored
from rolit.protocol import Protocol
class Helpers(object):
@staticmethod
def log(message):
message = "[%s] %s" % (time.strftime("%H:%M:%S"), message)
print(message)
@staticmethod
def notice(message):
print(colored(message, 'blue'))
@staticmethod
def warning(message):
print(colored(message, 'yellow'))
@staticmethod
def error(message):
print(colored(message, 'red'))
@staticmethod
def read_lines(sock):
read_buffer = ''
data = True
while data:
data = sock.recv(4096)
read_buffer += data
while not read_buffer.find(Protocol.EOL) == -1:
line, read_buffer = read_buffer.split(Protocol.EOL, 1)
yield line
return
@staticmethod
def sign_data(private_key, data):
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
try:
rsa_key = RSA.importKey(private_key)
except ValueError as e:
Helpers.error(e)
return
signer = PKCS1_v1_5.new(rsa_key)
digest = SHA.new()
digest.update(data)
try:
sign = signer.sign(digest)
except TypeError as e:
Helpers.error(e)
return
return sign
@staticmethod
def verify_sign(player_name, signature, data):
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('ss-security.student.utwente.nl', 2013))
sock.send("%s %s%s" % ("PUBLICKEY", player_name, Protocol.EOL))
response = sock.recv(4096)
if not response:
return False
response = response.strip().split(" ")
if response[0] == "ERROR":
return False
pub_key = "-----BEGIN PUBLIC KEY-----\n"
pub_key += response[1]
pub_key += "\n-----END PUBLIC KEY-----\n"
rsa_key = RSA.importKey(pub_key)
signer = PKCS1_v1_5.new(rsa_key)
digest = SHA.new()
digest.update(data)
if signer.verify(digest, signature):
return True
return False
<file_sep>/tests/test_server_game.py
import pytest
from mock import Mock, call, patch
from rolit.server import *
from test_server import TestServer
@patch.object(random, 'shuffle', Mock())
class TestServerGame(TestServer):
def test_it_ensures_that_a_game_goes_game_over_once(self):
self.server.game_over = Mock(wraps=self.server.game_over)
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], '0', '0')
with pytest.raises(ClientError):
self.server.move(self.clients[0], '0', '0')
assert self.server.game_over.call_count == 1
def test_it_validates_given_number_represents_a_field_on_board(self):
self.server.game_over = Mock(wraps=self.server.game_over)
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], '-', '1')
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], '8', '8')
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], 'a', 'b')
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], '0', '000')
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[0], '3', '3')
assert self.server.game_over.call_count == 5
def test_it_validates_client_is_in_game(self):
with pytest.raises(ClientError):
self.server.move(self.clients[0], '5', '3')
game = self.start_game_with_two_players()
game.balls_left = 1
self.server.move(self.clients[0], '5', '3')
with pytest.raises(ClientError):
self.server.move(self.clients[0], '5', '3')
def test_it_validates_it_is_clients_turn(self):
self.start_game_with_two_players()
with pytest.raises(ClientError):
self.server.move(self.clients[1], '5', '2')
def test_it_cannot_create_a_game_twice(self):
self.server.create_game(self.clients[0])
with pytest.raises(ClientError):
self.server.create_game(self.clients[0])
def test_it_cannot_create_a_game_after_joining(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
with pytest.raises(ClientError):
self.server.create_game(self.clients[1])
def test_it_cannot_join_twice(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
with pytest.raises(ClientError):
self.server.join_game(self.clients[1], self.clients[0]['name'])
def test_it_cannot_join_after_creating_a_game(self):
self.server.create_game(self.clients[0])
with pytest.raises(ClientError):
self.server.join_game(self.clients[0], self.clients[0]['name'])
def test_it_cannot_join_before_game_is_created(self):
with pytest.raises(ClientError):
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
def test_it_validates_max_number_of_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.join_game(self.clients[2], self.clients[0]['name'])
self.server.join_game(self.clients[3], self.clients[0]['name'])
with pytest.raises(ClientError):
self.server.join_game(self.clients[4], self.clients[0]['name'])
def test_it_validates_starts(self):
with pytest.raises(ClientError):
self.server.start_game(self.clients[0])
self.server.create_game(self.clients[0])
with pytest.raises(ClientError):
self.server.start_game(self.clients[0])
def test_game_goes_game_over_on_disconnect(self):
self.start_game_with_two_players()
self.server.disconnect(self.clients[1])
args = "%s %s %s %s%s" % (Protocol.GAME_OVER, Server.WINNING_SCORE, self.clients[0]['name'], self.clients[1]['name'], Protocol.EOL)
self.clients[0]['socket'].sendall.assert_has_calls(call(args))
def test_it_starts_for_two_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.start_game(self.clients[0])
args = [call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 1, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 2, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.STARTED, 2, Protocol.EOL))]
self.clients[2]['socket'].sendall.assert_has_calls(args)
def test_it_starts_for_three_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.join_game(self.clients[2], self.clients[0]['name'])
self.server.start_game(self.clients[0])
args = [call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 1, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 2, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 3, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.STARTED, 3, Protocol.EOL))]
self.clients[3]['socket'].sendall.assert_has_calls(args)
def test_it_starts_for_four_players(self):
self.server.create_game(self.clients[0])
self.server.join_game(self.clients[1], self.clients[0]['name'])
self.server.join_game(self.clients[2], self.clients[0]['name'])
self.server.join_game(self.clients[3], self.clients[0]['name'])
self.server.start_game(self.clients[0])
args = [call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 1, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 2, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 3, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.NOT_STARTED, 4, Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.GAME, self.clients[0]['name'], Protocol.STARTED, 4, Protocol.EOL))]
self.clients[4]['socket'].sendall.assert_has_calls(args)
def test_it_moves_for_two_players(self):
game = self.start_game_with_two_players()
game.balls_left = 1
self.server.move(self.clients[0], '5', '3')
args = [call("%s %s %s%s" % (Protocol.START, self.clients[0]['name'], self.clients[1]['name'], Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[0]['name'], '5', '3', Protocol.EOL)),
call("%s %s %s%s" % (Protocol.GAME_OVER, Server.WINNING_SCORE, self.clients[0]['name'], Protocol.EOL))]
args.insert(1, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[0]['socket'].sendall.assert_has_calls(args)
args.pop(1)
self.clients[1]['socket'].sendall.assert_has_calls(args)
assert self.clients[2]['socket'].sendall.call_count == 10
def test_it_moves_for_three_players(self):
game = self.start_game_with_three_players()
game.balls_left = 2
self.server.move(self.clients[0], '5', '3')
self.server.move(self.clients[1], '5', '2')
args = [call("%s %s %s %s%s" % (Protocol.START, self.clients[0]['name'], self.clients[1]['name'], self.clients[2]['name'], Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[0]['name'], '5', '3', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[1]['name'], '5', '2', Protocol.EOL)),
call("%s %s %s%s" % (Protocol.GAME_OVER, Server.WINNING_SCORE, self.clients[1]['name'], Protocol.EOL))]
args.insert(1, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[0]['socket'].sendall.assert_has_calls(args)
args.pop(1)
args.insert(2, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[1]['socket'].sendall.assert_has_calls(args)
args.pop(2)
self.clients[2]['socket'].sendall.assert_has_calls(args)
assert self.clients[3]['socket'].sendall.call_count == 11
def test_it_moves_for_four_players(self):
game = self.start_game_with_four_players()
game.balls_left = 3
self.server.move(self.clients[0], '5', '3')
self.server.move(self.clients[1], '5', '2')
self.server.move(self.clients[2], '2', '4')
args = [call("%s %s %s %s %s%s" % (Protocol.START, self.clients[0]['name'], self.clients[1]['name'], self.clients[2]['name'], self.clients[3]['name'], Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[0]['name'], '5', '3', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[1]['name'], '5', '2', Protocol.EOL)),
call("%s %s %s %s%s" % (Protocol.MOVED, self.clients[2]['name'], '2', '4', Protocol.EOL)),
call("%s %s %s%s" % (Protocol.GAME_OVER, Server.WINNING_SCORE, self.clients[2]['name'], Protocol.EOL))]
args.insert(1, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[0]['socket'].sendall.assert_has_calls(args)
args.pop(1)
args.insert(2, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[1]['socket'].sendall.assert_has_calls(args)
args.pop(2)
args.insert(3, call("%s%s" % (Protocol.MOVE, Protocol.EOL)))
self.clients[2]['socket'].sendall.assert_has_calls(args)
args.pop(3)
self.clients[3]['socket'].sendall.assert_has_calls(args)
assert self.clients[4]['socket'].sendall.call_count == 16
| 1609eb88798d335e04cfb2bde1592977f354f969 | [
"Markdown",
"Python",
"Text"
] | 25 | Python | tcoenraad/rolit | 39285a28a238be907c7df8fbffcfe88d394ed04e | 6641cd93c0ffd190e1b5bcc7f3546a6524402075 |
refs/heads/main | <repo_name>Lemout17/goit-react-hw-08-phonebook<file_sep>/src/redux/contacts/contacts-selectors.js
import { createSelector } from "@reduxjs/toolkit";
const getContacts = (state) => state.contacts.items;
const getFilter = (state) => state.contacts.filter;
const getLoading = (state) => state.contacts.loading;
const getError = (state) => state.contacts.contactsError;
const getFilteredContacts = createSelector(
[getContacts, getFilter],
(contacts, value) =>
contacts.filter((contact) =>
contact.name.toLowerCase().includes(value.toLowerCase())
)
);
export default {
getContacts,
getFilter,
getLoading,
getError,
getFilteredContacts,
};
<file_sep>/src/views/HomeView.js
const HomeView = () => {
return (
<div>
<h1>PhoneBook</h1>
</div>
);
};
export default HomeView;
<file_sep>/src/components/Contacts/Contacts.js
import { connect } from "react-redux";
import contactsOperations from "../../redux/contacts/contactsOperations";
import contactsSelectors from "../../redux/contacts/contacts-selectors";
import s from "./Contacts.module.css";
import { MDBBtn } from "mdb-react-ui-kit";
const Contacts = ({ contacts, onDelete }) => {
return (
<>
{contacts.length > 0 && (
<div className={s.container}>
<ul className={s.list}>
{contacts.map(({ id, name, number }) => (
<li className={s.item} key={id}>
<span className={s.text}>{name} :</span>
<span className={s.text}>{number}</span>
<MDBBtn
outline
rounded
size="sm"
className="mx-2"
color="danger"
onClick={() => {
onDelete(id);
}}
>
Delete
</MDBBtn>
{/* <button
className={s.button}
onClick={() => {
onDelete(id)
}}
>
Delete
</button> */}
</li>
))}
</ul>
</div>
)}
</>
);
};
const mapStateToProps = (state) => ({
contacts: contactsSelectors.getFilteredContacts(state),
});
const mapDispatchToProps = (dispatch) => ({
onDelete: (id) => dispatch(contactsOperations.deleteContact(id)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Contacts);
<file_sep>/src/components/Clock/Clock.js
import { useState, useEffect } from "react";
export default function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const clockIterval = setInterval(() => {
setTime(new Date());
}, 1000);
return () => {
clearInterval(clockIterval);
};
}, []);
return (
<div>
<p> Current time: {time.toLocaleTimeString()}</p>
</div>
);
}
<file_sep>/src/redux/auth/auth-selectors.js
const getIsAuth = (state) => state.auth.isAuthenticated;
const getUserName = (state) => state.auth.user.name;
export default {
getIsAuth,
getUserName,
};
<file_sep>/src/components/App/App.js
import "modern-normalize/modern-normalize.css";
// import "bootstrap/dist/css/bootstrap.min.css";
import "mdb-react-ui-kit/dist/css/mdb.min.css";
import s from "./App.module.css";
import { Component, Suspense, lazy } from "react";
import { Switch } from "react-router-dom";
import { connect } from "react-redux";
import { authOperations } from "../../redux/auth";
import routes from "../../routes";
import PrivateRoute from "./PrivateRoute";
import PublicRoute from "./PublicRoute";
// import Container from "../Container"
import AppBar from "../App/AppBar";
import Loader from "react-loader-spinner";
const HomeView = lazy(() =>
import("../../views/HomeView" /* webpackChunkName: "home-page" */)
);
const ContactsView = lazy(() =>
import("../../views/ContactsView" /* webpackChunkName: "contacts-page" */)
);
const LoginView = lazy(() =>
import("../../views/LoginView" /* webpackChunkName: "login-page" */)
);
const RegisterView = lazy(() =>
import("../../views/RegisterView" /* webpackChunkName: "register-page" */)
);
class App extends Component {
componentDidMount() {
this.props.getUser();
}
render() {
return (
<>
<AppBar />
<Suspense
fallback={
<Loader
className={s.loader}
type="Rings"
color="#00BFFF"
height={80}
width={80}
/>
}
>
<Switch>
<PublicRoute exact path={routes.home} component={HomeView} />
<PublicRoute
path={routes.register}
restricted
redirectTo={routes.contacts}
component={RegisterView}
/>
<PublicRoute
path={routes.login}
restricted
redirectTo={routes.contacts}
component={LoginView}
/>
<PrivateRoute
path={routes.contacts}
component={ContactsView}
redirectTo={routes.login}
/>
</Switch>
</Suspense>
</>
);
}
}
const mapDispatchToProps = {
getUser: authOperations.getCurrentUser,
};
export default connect(null, mapDispatchToProps)(App);
<file_sep>/src/components/App/AuthNav.js
import { NavLink } from "react-router-dom";
import routes from "../../routes";
import s from "./Navigation.module.css";
const AuthNav = () => {
return (
<div>
<NavLink
to={routes.login}
className={s.nav_link}
activeClassName={s.nav_link__active}
>
Log in
</NavLink>
<NavLink
to={routes.register}
className={s.nav_link}
activeClassName={s.nav_link__active}
>
Register
</NavLink>
</div>
);
};
export default AuthNav;
<file_sep>/src/views/ContactsView.js
import { Component } from "react";
import { connect } from "react-redux";
import Section from "../components/Section";
import Form from "../components/Form";
import Contacts from "../components/Contacts";
import ContactsFilter from "../components/Contacts/ContactsFilter";
import Loader from "react-loader-spinner";
import contactsOperations from "../redux/contacts/contactsOperations";
import contactsSelectors from "../redux/contacts/contacts-selectors";
import s from "./ContactsView.module.css";
class ContactsView extends Component {
componentDidMount() {
this.props.fetchContact();
}
render() {
const { isLoading, contactsError, contacts } = this.props;
return (
<main>
<Section title={"Contacts"}>
<div className={s.container}>
<Form />
{contacts.length > 0 && <ContactsFilter />}
{isLoading ? (
<Loader
className={s.loader}
type="Rings"
color="#00BFFF"
height={80}
width={80}
/>
) : contactsError ? (
<h2 className={s.error}>
Sorry, something went wrong({contactsError})
</h2>
) : (
<Contacts />
)}
</div>
</Section>
</main>
);
}
}
const mapStateToProps = (state) => ({
contacts: contactsSelectors.getContacts(state),
isLoading: contactsSelectors.getLoading(state),
contactsError: contactsSelectors.getError(state),
});
const mapDispatchToProps = (dispatch) => ({
fetchContact: () => dispatch(contactsOperations.fetchContact()),
});
export default connect(mapStateToProps, mapDispatchToProps)(ContactsView);
<file_sep>/src/components/App/UserMenu.js
import { connect } from "react-redux";
import { authSelectors, authOperations } from "../../redux/auth";
import defaultImage from "../../img/poggers.png";
import s from "./UserMenu.module.css";
// import Button from "react-bootstrap/Button"
import { MDBBtn } from "mdb-react-ui-kit";
const UserMenu = ({ avatar, name, onLogout }) => {
return (
<div className={s.container}>
<img className={s.img} src={avatar} alt="" />
<span className={s.text}>Hi, {name}</span>
<MDBBtn rounded className="mx-2" color="danger" onClick={onLogout}>
Log out
</MDBBtn>
</div>
);
};
const mapStateToProps = (state) => ({
name: authSelectors.getUserName(state),
avatar: defaultImage,
});
const mapDispatchToProps = {
onLogout: authOperations.logOut,
};
export default connect(mapStateToProps, mapDispatchToProps)(UserMenu);
<file_sep>/src/components/Form/Form.js
import { Component } from "react";
import { connect } from "react-redux";
import contactsOperations from "../../redux/contacts/contactsOperations";
import contactsSelectors from "../../redux/contacts/contacts-selectors";
import s from "./Form.module.css";
import { MDBInput } from "mdb-react-ui-kit";
import { MDBBtn } from "mdb-react-ui-kit";
class Form extends Component {
state = {
name: "",
number: "",
};
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = (e) => {
const { contacts, onSubmit } = this.props;
const { name, number } = this.state;
e.preventDefault();
contacts.find((contact) => contact.name === name)
? alert(`This person ${name} is already in contacts`)
: contacts.find((contact) => contact.number === number)
? alert(`This number ${number} is already in contacts`)
: onSubmit(this.state);
this.setState({
name: "",
number: "",
});
};
render() {
const { name, number } = this.state;
return (
<form className={s.form} onSubmit={this.handleSubmit}>
<MDBInput
className="text-light"
label="Name"
id="typeText"
contrast
autoComplete="off"
type="text"
name="name"
value={name}
onChange={this.handleChange}
pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$"
title="Имя может состоять только из букв, апострофа, тире и пробелов. Например Adrian, <NAME>, <NAME> и т. п."
required
/>
<MDBInput
className="text-light"
label="Number"
id="typePhone"
contrast
autoComplete="off"
type="tel"
name="number"
value={number}
onChange={this.handleChange}
pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}"
title="Номер телефона должен состоять цифр и может содержать пробелы, тире, круглые скобки и может начинаться с +"
required
/>
<MDBBtn rounded>Add contact</MDBBtn>
</form>
);
}
}
const mapStateToProps = (state) => ({
contacts: contactsSelectors.getContacts(state),
});
const mapDispatchToProps = (dispatch) => ({
onSubmit: ({ name, number }) =>
dispatch(contactsOperations.addContact({ name, number })),
});
export default connect(mapStateToProps, mapDispatchToProps)(Form);
<file_sep>/src/views/RegisterView.js
import { Component } from "react";
import { connect } from "react-redux";
import { authOperations } from "../redux/auth";
// import Button from "react-bootstrap/Button"
import { MDBInput } from "mdb-react-ui-kit";
import { MDBBtn } from "mdb-react-ui-kit";
import s from "../components/Form/Form.module.css";
class RegisterView extends Component {
state = {
name: "",
email: "",
password: "",
};
handleChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });
};
handleSubmit = (e) => {
e.preventDefault();
this.props.onRegister(this.state);
this.reset();
};
reset = () => {
this.setState({
name: "",
email: "",
password: "",
});
};
render() {
const { name, email, password } = this.state;
return (
<div className={s.container}>
<h1>Register</h1>
<form className={s.form} onSubmit={this.handleSubmit}>
<MDBInput
className="text-light"
label="Name"
id="typeText"
contrast
autoComplete="off"
type="text"
name="name"
value={name}
onChange={this.handleChange}
/>
<MDBInput
className="text-light"
label="Email"
id="typeEmail"
contrast
autoComplete="off"
type="email"
name="email"
value={email}
onChange={this.handleChange}
/>
<MDBInput
className="text-light"
label="Password"
id="typePassword"
contrast
type="password"
name="password"
value={password}
onChange={this.handleChange}
/>
<MDBBtn rounded>Register</MDBBtn>
</form>
</div>
);
}
}
const mapDispatchToProps = {
onRegister: authOperations.register,
};
export default connect(null, mapDispatchToProps)(RegisterView);
<file_sep>/src/components/Contacts/ContactsFilter.js
import { connect } from "react-redux";
import contactsActions from "../../redux/contacts/contacts-actions";
import contactsSelectors from "../../redux/contacts/contacts-selectors";
import s from "./ContactsFilter.module.css";
import { MDBInput } from "mdb-react-ui-kit";
const ContactsFilter = ({ value, onChange }) => {
return (
<form className={s.form}>
<MDBInput
className="text-light"
label="Filter contacts by name"
id="typeText"
contrast
type="text"
name="name"
value={value}
onChange={onChange}
/>
{/* <label className={s.label}>
Filter contacts by name
<input
className={s.input}
type="text"
value={value}
onChange={onChange}
/>
</label> */}
</form>
);
};
const mapStateToProps = (state) => ({
value: contactsSelectors.getFilter(state),
});
const mapDispatchToProps = (dispatch) => ({
onChange: (e) => dispatch(contactsActions.filterContact(e.target.value)),
});
export default connect(mapStateToProps, mapDispatchToProps)(ContactsFilter);
| ed2e2022fa50fed1f804d5977b461a75f366f599 | [
"JavaScript"
] | 12 | JavaScript | Lemout17/goit-react-hw-08-phonebook | 936612d6c1462ed1184b763ac3b1cd58deb8ade6 | cadbf3d92d76c2cbeee1112693963865569ba3ff |
refs/heads/master | <file_sep># Movies
Movies is a React-Native App using the TMDB API, it allows users to search for a film by his name, date, actors etc. Also users can add films to their favorite list or watched movies list.
<file_sep>import 'react-native-gesture-handler';
import React from 'react';
import {StyleSheet, Image} from 'react-native';
import Search from './Components/Search';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import FilmDetail from './Components/FilmDetail';
import {Provider} from 'react-redux';
import Store from './Store/configureStore';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Favorite from './Components/Favorite';
import Test from './Components/Test';
import NewFilms from './Components/NewFilms';
import WatchedFilms from './Components/WatchedFilms';
import {persistStore} from 'redux-persist';
import {PersistGate} from 'redux-persist/es/integration/react';
export default class App extends React.Component {
render() {
let persistor = persistStore(Store);
return (
<Provider store={Store}>
<PersistGate persistor={persistor}>
<NavigationContainer>
<Tab.Navigator
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
if (route.name === 'Search') {
iconName = focused ? 'ios-search' : 'ios-search-outline';
} else if (route.name === 'Favorite') {
iconName = focused ? 'ios-heart' : 'ios-heart-outline';
} else if (route.name === 'NewFilms') {
iconName = require('./Images/ic_fiber_new.png');
return (
<Image
style={styles.tabBar_icon}
source={iconName}></Image>
);
} else if (route.name === 'WatchedFilms') {
iconName = require('./Images/ic_watched_film.png');
return (
<Image
style={styles.watchedFilms_icon}
source={iconName}></Image>
);
}
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}>
<Tab.Screen
name="Search"
component={SearchStackScreen}
options={{tabBarLabel: 'Recherche'}}
/>
<Tab.Screen
name="Favorite"
component={FavoriteStackScreen}
options={{tabBarLabel: 'Favoris'}}
/>
<Tab.Screen
name="NewFilms"
component={NewFilmsStackScreen}
options={{tabBarLabel: 'News'}}
/>
<Tab.Screen
name="WatchedFilms"
component={WatchedFilmsStackScreen}
options={{tabBarLabel: 'Mes films vus'}}
/>
</Tab.Navigator>
</NavigationContainer>
</PersistGate>
</Provider>
);
}
}
function SearchStackScreen() {
return (
<StackSearch.Navigator>
<StackSearch.Screen
name="Search"
component={Search}
options={{title: 'Recherche'}}
/>
<StackSearch.Screen name="Details" component={FilmDetail} />
</StackSearch.Navigator>
);
}
function FavoriteStackScreen() {
return (
<StackFavorite.Navigator>
<StackFavorite.Screen
name="Favorite"
component={Favorite}
options={{title: 'Films Favoris'}}
/>
<StackFavorite.Screen name="Details" component={FilmDetail} />
</StackFavorite.Navigator>
);
}
function WatchedFilmsStackScreen() {
return (
<StackWatchedFilms.Navigator>
<StackWatchedFilms.Screen
name="WatchedFilms"
component={WatchedFilms}
options={{title: 'Mes Films Vus'}}
/>
<StackWatchedFilms.Screen name="Details" component={FilmDetail} />
</StackWatchedFilms.Navigator>
);
}
function NewFilmsStackScreen() {
return (
<StackNewFilms.Navigator>
<StackNewFilms.Screen
name="NewFilms"
component={NewFilms}
options={{title: 'Les Derniers Films'}}
/>
<StackNewFilms.Screen name="Details" component={FilmDetail} />
</StackNewFilms.Navigator>
);
}
const styles = StyleSheet.create({
tabBar_icon: {
width: 30,
height: 30,
},
watchedFilms_icon: {
width: 30,
height: 30,
},
});
const Tab = createBottomTabNavigator();
const StackSearch = createStackNavigator();
const StackFavorite = createStackNavigator();
const StackNewFilms = createStackNavigator();
const StackWatchedFilms = createStackNavigator();
| c8298ff08afd6ad9fc9309d363dd679a262b8f10 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | boudja/Movies | 5a3e57a051dc811bfedf429f5250bfd4504e55f5 | dcce084f25fdf780bd243e05bcfda9f53c61266f |
refs/heads/main | <file_sep>#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a positive integer for displaying its table\n";
cin>>n;
for(int c=1;c<=10;c++)//c is counter
{
cout<<n<<"*"<<c<<"="<<n*c<<endl;
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
//user clicks button i.e enters values among a,b,c,d,e and corresponding result is displayed.
char button;
cin>>button;
switch(button)
{
case 'a':
{
cout<<"Apple";
break;
}
case 'b':
{
cout<<"Banana";
break;
}
case 'c':
{
cout<<"Caramel";
break;
}
case 'd':
{
cout<<"dragonfruit";
break;
}
case 'e':
{
cout<<"english tea";
break;
}
default:
{
cout<<"TEA";
}
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
int a,b;
char op;
cout<<"Enter in the format no operator no. E.g. 2*5\n";
cin>>a>>op>>b;
switch(op)
{
case '+':
{
cout<<a<<op<<b<<"="<<a+b;
break;
}
case '-':
{
cout<<a<<op<<b<<"="<<a-b;
break;
}
case '*':
{
cout<<a<<op<<b<<"="<<a*b;
break;
}
case '/':
{
cout<<a<<op<<b<<"="<<a/b;
break;
}
default:
{
cout<<"Enter only add, sub, multiply and div operators!";
}
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter an alphabet to check if its a vowel or consonant.\n";
cin>>ch;
switch(ch)
{
case 'a':
{
cout<<"This is a vowel";
break;
}
case 'A':
{
cout<<"This is a vowel";
break;
}
case 'e':
{
cout<<"This is a vowel";
break;
}
case 'E':
{
cout<<"This is a vowel";
break;
}
case 'i':
{
cout<<"This is a vowel";
break;
}
case 'I':
{
cout<<"This is a vowel";
break;
}
case 'o':
{
cout<<"This is a vowel";
break;
}
case 'O':
{
cout<<"This is a vowel";
break;
}
case 'U':
{
cout<<"This is a vowel";
break;
}
case 'u':
{
cout<<"This is a vowel";
break;
}
default:
{
cout<<"This is a consonant";
}
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter the sides of your triangle\n";
cin>>a>>b>>c;
if(a==b)
{
if(b==c)
{
cout<<"Triangle is equilateral";
}
else
{
cout<<"Triangle is isoceles";
}
}
else if(b==c)
{
cout<<"Triangle is isoceles";
}
else
{
cout<<"Triangle is scalene";
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter no. to check prime or not prime.";
cin>>n;
for(int i=1;i<=n;i++)
{
int div=2;
if(n>div)
{
if(n%div==0)
{
cout<<"non-prime";
}
else{
div++;
}
}
else{
cout<<"prime";
}
}
return 0;
}
<file_sep>//This code keeps taking value from user and keeps adding them,until the no. is positive.If no is negative the sum will be displayed.
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter your no: ";
cin>>n;
int sum=0;
while(n>=0)
{
sum+=n;
cout<<"Enter your no: ";
cin>>n;
}
cout<<"The end sum is: "<<sum<<endl;
return 0;
}<file_sep>//This pgm is used to display prime nos between a range given by user.
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter limits to print prime no.s from.\n";
cin>>a>>b;
for(int n=a;n<=b;n++)//This loop is used to check if entered no is greater 2..
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)//we check if given no is divisible by 2. If it is ,then its a non prime no. and we break from loop.its non prime because n is> than 2 and divisible be 2, which means n is divisible by 2 no.s hence non-prime.
{
break;
}
}
if(n==i)//The loop is over we will check if i is changed or not if it is and its equal to n, it means its prime.
{
cout<<n<<endl;
}
}
// if not understood go to this link https://youtu.be/Stf7KBiA1vs
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main()
{
int s;
cout<<"Enter savings:"<<endl;
cin>>s;
if(s>5000)
{
cout<<"Neha\n";
if(s>10000)
{
cout<<"Party";
}
else
{
cout<<"shopping";
}
}
else if(s>2000)
{
cout<<"Rashmi\n";
}
else
{
cout<<"frineds";
}
return 0;
}<file_sep>This repository contains all the C++ codes that I have solved till now. I aim to update it everyday as I solve new problems. If You want to add some codes. You most welcome
<file_sep>#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter an alphabet:\n";
cin>>ch;
if(ch=='a'||ch=='A'||ch=='i'||ch=='I'||ch=='e'||ch=='E'||ch=='o'||ch=='O'||ch=='u'||ch=='U')
{
cout<<"You entered a vowel\n";
}
else
{
cout<<"You entered a consonant\n";
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter no. to check prime or not prime.\n";
cin>>n;
int i;
for(i=2;i<n;i++)//This loop is used to check if entered no is greater 2..
{
if(n%i==0)//we check if given no is divisible by 2. If it is ,then its a non prime no. and we break from loop.its non prime because n is> than 2 and divisible be 2, which means n is divisible by 2 no.s hence non-prime.
{
cout<<"Non-prime";
break;
}
}
if(n==i)//The loop is over we will check if i is changed or not if it is and its equal to n, it means its prime.
{
cout<<"Prime";
}
else if(n==1||n==0)
{
cout<<n<<" is non-prime and non-composite number";
}
return 0;
}
<file_sep>//this program prints the value given by user till the user provides positive value. As soon as user will give negative or 0, the program will stop printing value given by user.
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
cout<<endl;
while(n>0)
{
cout<<n<<endl;
cin>>n;
}
return 0;
}<file_sep>#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter a no.\n";
cin>>a;
if(a%2==0)
{
cout<<"You entered even no.";
}
else
{
cout<<"odd no";
}
return 0;
} | 375cedfd9eda545db98d1561d5fc7b8d8820854e | [
"Markdown",
"C++"
] | 14 | C++ | KhushbooMishra7/Cpp_codes | 14e21109d11a037680c6ac2d727bf82b8f3baadb | 984441230e62a654bd5308a7ba0c5486adda99e6 |
refs/heads/master | <repo_name>jiaqingw/jjw72p<file_sep>/app/models/spree_product_decorator.rb
Spree::Product.class_eval do
attr_accessible :count_on_hand, :created_at, :updated_at
# Returns all the Products that are related to this record for the given RelationType.
#
# Uses the Relations to find all the related items, and then filters
# them using +Product.relation_filter+ to remove unwanted items.
def relations_for_relation_type(relation_type)
# Find all the relations that belong to us for this RelationType
related_ids = relations.where(:relation_type_id => relation_type.id).select(:related_to_id).collect(&:related_to_id)
# Construct a query for all these records
result = self.class.where(:id => related_ids)
# Merge in the relation_filter if it's available
result = result.merge(self.class.relation_filter.scoped) if relation_filter
result
end
end
<file_sep>/app/helpers/spree/users_helper_decorator.rb
Spree::UsersHelper.module_eval do
def breadcrumbs(taxon, separator=" » ")
return "" if current_page?("/") || taxon.nil?
separator = raw(separator)
crumbs = [link_to(t(:home) , root_path) + separator]
if taxon
crumbs << link_to(t('products') , products_path) + separator
crumbs << taxon.ancestors.collect { |ancestor| link_to(ancestor.name , seo_url(ancestor)) + separator } unless taxon.ancestors.empty?
crumbs << content_tag(:span, taxon.name)
else
crumbs << content_tag(:span, t('products'))
end
crumb_list = raw(crumbs.flatten.map{|li| li.mb_chars}.join)
#content_tag(:div, crumb_list + tag(:br, {:class => 'clear'}, false, true), :id => 'breadcrumbs')
end
def product_model(pps)
pps.each do |pp|
if pp.property.name == 'model'
return pp.value
end
end
"N/A"
end
def product_manufacturer(pps)
pps.each do |pp|
if pp.property.name == 'manufacturer'
return pp.value
end
end
"N/A"
end
def get_taxonomies
@taxonomies ||= Spree::Taxonomy.includes(:taxons).includes(:root => :children).joins(:root)
end
=begin
def checkout_progress
states = checkout_states
items = states.map do |state|
text = t("order_state.#{state}").titleize
css_classes = []
current_index = states.index(@order.state)
state_index = states.index(state)
if state_index < current_index
css_classes << 'completed'
text = link_to text, checkout_state_path(state)
end
css_classes << 'next' if state_index == current_index + 1
css_classes << 'current' if state == @order.state
css_classes << 'first' if state_index == 0
css_classes << 'last' if state_index == states.length - 1
# It'd be nice to have separate classes but combining them with a dash helps out for IE6 which only sees the last class
content_tag('li', content_tag('span', text), :class => css_classes.join(' '))
end
content_tag('ol', raw(items.join("\n")), :class => 'progress-steps', :id => "checkout-step-#{@order.state}")
end
=end
Spree::Image.attachment_definitions[:attachment][:styles][:product300] = '300x300>'
Spree::Image.attachment_definitions[:attachment][:styles].each do |style, v|
define_method "#{style}_image" do |product, *options|
options = options.first || {}
if product.images.empty?
image_tag "noimage/#{style}.png", options
else
image = product.images.first
options.reverse_merge! :alt => image.alt.blank? ? product.name : image.alt
image_tag image.attachment.url(style), options
end
end
end
end
<file_sep>/app/controllers/devise_controller_decorator.rb
DeviseController.class_eval do
=begin
before_filter :set_current_order
def set_current_order
@order = current_order(true)
end
=end
end
<file_sep>/config/initializers/spree_config.rb
Spree::Config.set(:max_level_in_taxons_menu=>10)
Spree::Config.set(:site_url=>"www.easyonlinelive.com")
<file_sep>/app/models/spree_product_datasheet_decorator.rb
Spree::ProductDatasheet.class_eval do
attr_accessible :xls
end
<file_sep>/README.md
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="">
<meta name="keywords" content="">
<script type="text/JavaScript">
</script>
<style type="text/css">
</style>
</head>
<body>
<p>
<h2>Intro:</h2>
This applications is a fully-functional eCommerce site, based off the famous Spree framework. I customized it to have different skin other than the default theme provided by Spree framework. My friend bought this lovely "Shopica" fluid style web template and I modified it to fit this site.
</p>
<p>
<h2>Installation:</h2>
<code>
<pre>
git clone https://github.com/jiaqingw/jjw72p.git
cd jjw72p
bundle install
bundle exec rails server
</pre>
<code>
</p>
<p>
<h2>Access</h2>
Open a web browser and go to http://localhost:3000
</p>
</body>
</html>
<file_sep>/app/controllers/spree_admin_base_controller_decorator.rb
Spree::Admin::BaseController.class_eval do
#skip_before_filter :set_current_order
end
<file_sep>/app/controllers/spree_home_controller_decorator.rb
Spree::HomeController.class_eval do
before_filter :set_current_order
def set_current_order
@order = current_order(true)
end
end
| 736551ef411eab0442a5f53469aa102dd0064321 | [
"Markdown",
"Ruby"
] | 8 | Ruby | jiaqingw/jjw72p | 61ee08cb3d9fff4828cfe569a8ec17aa90eac22a | 5157c2f36137b13c2a6f15afff57056db5881db2 |
refs/heads/master | <repo_name>sc28/frontend-nanodegree-resume<file_sep>/js/resumeBuilder.js
/*
This is empty on purpose! Your code to build the resume will go here.
Open questions
-How does this script know references to helper.js without pointing to it?
-Why don't images display? --misnamed properties, and HTML format tags as well (fixed)
-How to resize images?
*/
//************************DATA INPUT*******************************
//Resume sections are listed below (work, projects, bio, education)
//Work
/*
work contains an array of jobs. Each object in the jobs array should
contain an employer, title, location, dates worked and description strings.
*/
var work = {
"jobs": [
{
"employer": "EIFER",
"title": "Research Engineer",
"location": "Karlsruhe, Germany",
"dates": "May 2014 - ongoing",
"description": "PhD candidate in the framework of the CINERGY project Thesis topic on a decision support methodology for urban energy system planning"
},
{
"employer": "DGE",
"title": "Junior project manager",
"location": "Lausanne, Switzerland",
"dates": "July 2012 - March 2014",
"description": "Planned and organized the restructuring of the state services of Energy, Nature conservation, and Urban environment (>400 collaborators) Developed a dashboard on state energy policies to guide decision-making Defined the state's priority research projects for the Swiss Federal Institute for Forest, Snow and Landscape Research (WSL)"
},
{
"employer": "SFFN & ILEX sàrl",
"title": "Junior project manager",
"location": "Lausanne, Switzerland",
"dates": "September 2011 - February 2012",
"description": "Developed a field and numerical tool to increase biodiversity awareness among forest professionals, students and public Expert and advisor for the professional training course on forest biodiversity"
}
]
}
//Projects
/*
projects contains an array of projects. Each object in the projects array should
contain title, dates and description strings, and an images array with URL strings
for project images.
*/
var projects = {
"projects": [
{
"title": "CINERGY",
"dates": "October 2013 - September 2017",
"description": "Smart and low carbon cities",
"images": ["images/cinergy.png","images/mariecurie.png"]
}
]
}
//Bio
/*
bio contains name, role, welcomeMessage, and biopic strings, contacts object and
skills array of skill strings. The contacts object should contain a mobile number,
email address, github username, twitter handle and location. The twitter property
is optional.
*/
var bio = {
"name": "<NAME>",
"role": "Research Engineer",
"welcomeMessage": "Hi, welcome to my online CV! Have a look around, and please contact me for any questions :)",
"biopic": "images/biopic.png",
"contacts": {
"mobile": "+49 157 5476 95 43",
"email": "<EMAIL>",
"github": "sc28",
"twitter": "",
"location": "Karlsruhe, Germany"
},
"skills": ["Languages", " open-mindedness", " rigour", " awesomeness", " JavaScript", " curiosity", " and more..."]
}
//Education
/*
education contains an array of schools. Each object in the schools array contains
name, location, degree dates and url strings, and amajors array of major strings.
education also contains an onlineCourses array. Each object in the onlineCourses
array should contain a title, school, dates and url strings.
*/
var education = {
"schools": [
{
"name": "EPFL",
"location": "Lausanne, Switzerland",
"degree": ["Master", "Minor", "Bachelor"],
"dates": "2006-2011",
"url": "http://www.epfl.ch",
"major": ["Master in Environmental sciences and engineering", " Minor in Area and cultural studies"]
},
{
"name": "Kyoto University",
"location": "Kyoto, Japan",
"degree": ["Master"],
"dates": "2011",
"url": "http://www.kyoto-u.ac.jp/en",
"major": ["Master in Environmental sciences and engineering"]
},
{
"name": "Tongji University",
"location": "Shanghai, China",
"degree": ["Minor"],
"dates": "2010",
"url": "http://www.tongji.edu.cn",
"major": [" Minor in Area and cultural studies"]
},
{
"name": "Institute for Social and Economic Change",
"location": "Bangalore, India",
"degree": ["Minor"],
"dates": "2010",
"url": "http://www.isec.ac.in",
"major": [" Minor in Area and cultural studies"]
},
{
"name": "Kaiser Elementary School",
"location": "California, USA",
"degree": [""],
"dates": "1990-1995",
"url": "http://www.kaiserelementary.org",
"major": [""]
}
],
"onlineCourses": [
{
"title": "JavaScript Basics",
"platform": "Udacity",
"dates": "2016",
"university": "-",
"url": "https://classroom.udacity.com/courses/ud804"
},
{
"title": "Model Thinking",
"platform": "Coursera",
"dates": "2015",
"university": "University of Michigan",
"url": "https://www.coursera.org/course/modelthinking"
},
{
"title": "Learning How to Learn: Powerful mental tools to help you master tough subjects",
"platform": "Coursera",
"dates": "2015",
"university": "University of California, San Diego",
"url": "https://www.coursera.org/course/learning"
},
{
"title": "Reason and Persuasion: Thinking Through Three Dialogues By Plato",
"platform": "Coursera",
"dates": "2015",
"university": "National University of Singapore",
"url": "https://www.coursera.org/course/reasonandpersuasion"
},
{
"title": "L'avenir de la décision : connaître et agir en complexité",
"platform": "Coursera",
"dates": "2015",
"university": "ESSEC Business School",
"url": "https://www.coursera.org/course/lavenirdeladecision"
},
{
"title": "Introduction to Thermodynamics: Transferring Energy from Here to There",
"platform": "Coursera",
"dates": "2014",
"university": "University of Michigan",
"url": "https://www.coursera.org/course/introthermodynamics"
},
{
"title": "How Green Is That Product? An Introduction to Life Cycle Environmental Assessment",
"platform": "Coursera",
"dates": "2014",
"university": "Northwestern University",
"url": "https://www.coursera.org/course/introtolca"
},
{
"title": "A Look at Nuclear Science and Technology",
"platform": "Coursera",
"dates": "2014",
"university": "University of Pittsburgh",
"url": "https://www.coursera.org/course/nuclearscience"
},
{
"title": "Energy, the Environment, and Our Future",
"platform": "Coursera",
"dates": "2014",
"university": "The Pennsylvania State University",
"url": "https://www.coursera.org/course/energy"
},
{
"title": "Inspiring Leadership through Emotional Intelligence",
"platform": "Coursera",
"dates": "2013",
"university": "Case Western Reserve University",
"url": "https://www.coursera.org/course/lead-ei"
}
]
}
//************************DISPLAY OF DATA*******************************
//Display functions for each category below (bio, work, )
//Display BIO
bio.display = function() {
//Display role property after name
var formattedRole = HTMLheaderRole.replace("%data%", bio.role);
$("#header").prepend(formattedRole);
//Display bio name in header
var formattedName = HTMLheaderName.replace("%data%", bio.name);
$("#header").prepend(formattedName);
//Display contact infos
var formattedMobile = HTMLmobile.replace("%data%",bio.contacts.mobile);
$("#topContacts").append(formattedMobile);
var formattedEmail = HTMLemail.replace("%data%",bio.contacts.email);
$("#topContacts").append(formattedEmail);
var formattedGithub = HTMLgithub.replace("%data%",bio.contacts.github);
$("#topContacts").append(formattedGithub);
var formattedLocation = HTMLlocation.replace("%data%",bio.contacts.location);
$("#topContacts").append(formattedLocation);
//Display picture
var formattedBiopic = HTMLbioPic.replace("%data%",bio.biopic);
$("#header").append(formattedBiopic);
//Display Welcome message
var formattedWelcomeMessage = HTMLwelcomeMsg.replace("%data%", bio.welcomeMessage);
$("#header").append(formattedWelcomeMessage);
//Displaying skills in a single array
$("#header").append(HTMLskillsStart);
var formattedSkill = HTMLskills.replace("%data%", bio.skills);
$("#skills").append(formattedSkill);
}
bio.display();
//Display WORK
function displayWork() {
for (jobsKey in work.jobs){
if (work.jobs.hasOwnProperty(jobsKey)) {
//console.log(work.jobs[jobsKey]);
$("#workExperience").append(HTMLworkStart);
var formattedEmployer = HTMLworkEmployer.replace("%data%", work.jobs[jobsKey].employer);
var formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[jobsKey].title);
var formattedEmployerTitle = formattedEmployer + formattedTitle;
$(".work-entry:last").append(formattedEmployerTitle);
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[jobsKey].location);
$(".work-entry:last").append(formattedLocation);
var formattedDates = HTMLworkDates.replace("%data%", work.jobs[jobsKey].dates);
$(".work-entry:last").append(formattedDates);
var formattedDescription = HTMLworkDescription.replace("%data%", work.jobs[jobsKey].description);
$(".work-entry:last").append(formattedDescription);
}
}
}
displayWork();
//Display PROJECTS (with encapsulated function)
projects.display = function() {
for (project in projects.projects) {
$("#projects").append(HTMLprojectStart);
var formattedTitle = HTMLprojectTitle.replace("%data%",projects.projects[project].title);
$(".project-entry:last").append(formattedTitle);
var formattedDates = HTMLprojectDates.replace("%data%",projects.projects[project].dates);
$(".project-entry:last").append(formattedDates);
var formattedDescription = HTMLprojectDescription.replace("%data%",projects.projects[project].description);
$(".project-entry:last").append(formattedDescription);
for (image in projects.projects[project].images) {
var formattedImage = HTMLprojectImage.replace("%data%",projects.projects[project].images[image]);
$(".project-entry:last").append(formattedImage);
}
}
}
projects.display();
//Display EDUCATION (with encapsulated function)
education.display = function() {
for (school in education.schools) {
$("#education").append(HTMLschoolStart);
var formattedSchoolName = HTMLschoolName.replace("%data%",education.schools[school].name).replace("#",education.schools[school].url);
$(".education-entry:last").append(formattedSchoolName);
//var formattedDegree = HTMLschoolDegree.replace("%data%",education.schools[school].degree);
//$(".education-entry:last").append(formattedDegree);
var formattedDates = HTMLschoolDates.replace("%data%",education.schools[school].dates);
$(".education-entry:last").append(formattedDates);
//var formattedSchoolURL = HTMLschoolURL.replace("%data%",education.schools[school].url);
//$(".education-entry:last").append(formattedSchoolURL);
var formattedLocation = HTMLschoolLocation.replace("%data%",education.schools[school].location);
$(".education-entry:last").append(formattedLocation);
var formattedMajor = HTMLschoolMajor.replace("%data%",education.schools[school].major);
$(".education-entry:last").append(formattedMajor);
}
$("#education").append(HTMLonlineClasses);
for (onlineCourse in education.onlineCourses) {
$("#education").append(HTMLonlineCourseStart);
var formattedOnlineTitle = HTMLonlineTitle.replace("%data%",education.onlineCourses[onlineCourse].title).replace("#",education.onlineCourses[onlineCourse].url);
$(".onlineCourse-entry:last").append(formattedOnlineTitle);
var formattedPlatform = HTMLonlinePlatform.replace("%data%",education.onlineCourses[onlineCourse].platform);
$(".onlineCourse-entry:last").append(formattedPlatform);
var formattedOnlineUniversity = HTMLonlineUniversity.replace("%data%",education.onlineCourses[onlineCourse].university);
$(".onlineCourse-entry:last").append(formattedOnlineUniversity);
var formattedOnlineDates = HTMLonlineDates.replace("%data%",education.onlineCourses[onlineCourse].dates);
$(".onlineCourse-entry:last").append(formattedOnlineDates);
//var formattedOnlineURL = HTMLonlineURL.replace("%data%",education.onlineCourses[onlineCourse].url);
//$(".onlineCourse-entry:last").append(formattedOnlineURL);
}
}
education.display();
//************************OTHER FUNCTIONALITIES*******************************
//Here are other features like maps, buttons...
//Add a map
$("#mapDiv").append(googleMap);
//Quizz about click locations
$(document).click(function(loc) {
// your code goes here
var x = loc.pageX;
var y = loc.pageY;
logClicks(x,y);
});
//Add button to capitalize last name
function inName(name) {
name = name.trim().split(" ");
console.log(name);
name[1] = name[1].toUpperCase();
name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();
return name[0] + " " + name[1];
}
$("#main").append(internationalizeButton);
<file_sep>/js/old1_resumeBuilder.js
/*
This is empty on purpose! Your code to build the resume will go here.
*/
// $("#main").append("Sébastien2"); //this is a selector searching ID main
var name = "<NAME>";
var age = 30;
var role = "Environmental engineer";
var awesomeThoughts = "I am Séb and I'm awesome!";
console.log(awesomeThoughts);
var skills = ["Awesomeness", "Team spirit", "JavaScript"];
var email = "<EMAIL>";
var pictureURL = "images/me.jpg"
var funThoughts = awesomeThoughts.replace("awesome","fun");
//$("#main").append(funThoughts);
//Quizz to display role and name using helper format, and prepend it to existing header object
var formattedRole = HTMLheaderRole.replace("%data%",role);
$("#header").prepend(formattedRole);
var formattedName = HTMLheaderName.replace("%data%",name);
$("#header").prepend(formattedName);
//add Skills
//$("#main").append(skills);
//add Bio object and display it
var bio = {
"name": name,
"role": role,
"contactInfo": email,
"picture": pictureURL,
"welcomeMessage": "Hi there, welcome to my Resume",
"skills": skills};
$("#main").append(bio.contactInfo);
$("#main").append(bio.picture);
//Create object using dot notation
var work = {};
work.position = "research engineer";
work.employer = "EIFER";
$("#main").append(work.employer);
var education= {
"schools": [
{
"name": "EPFL",
"city": "Lausanne, Vaud, Switzerland",
"degree": ["BA","MA"],
"dates": 2011,
"major": ["Environmental sciences and engineering", "Cultural Studies"]
},
{
"name": "Kyoto University",
"city": "Kyoto, Japan",
"degree": ["MA"],
"dates": 2011,
"major": ["Environmental sciences and engineering"]
}
],
"MOOCs": [
{
"title": "JavaScript Basics",
"platform": "Udacity",
"university": [],
"dates": 2016,
"url": "www"
},
{
"title": "Learning how to learn",
"platform": "Coursera",
"university": ["Michigan University"],
"dates": 2015,
"url": "www"
}
]
}
| 1cb2a0667fe1a9556b36bcec1024b8edbe8d77a7 | [
"JavaScript"
] | 2 | JavaScript | sc28/frontend-nanodegree-resume | a62b827edb1c91778d8a16f7190fdd3eaaa21260 | ec5b1f6917d07829db7a609b001f08bedee5b0bb |
refs/heads/main | <repo_name>yudjinn/nwbnk-frontend<file_sep>/README.md
# nwbnk
## Project setup
```
npm install
```
### Compiles and hot-reloads for development - currently hits the stage server. We can create another env if localhost is server.
```
npm run dev
```
### Compiles and minifies for stge
```
npm run stage
```
### Compiles and minifies for production (still need host name in .env.prod)
```
npm run prod
```
### Lints and fixes files
```
npm run lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
<file_sep>/src/util/NetClient.js
import axios from 'axios'
var NetClient = {
router: null,
creds: {
access_token: '',
token_type: ''
},
user: {
id: '',
username: ''
},
company: '',
init: function(_router) {
this.router = _router
},
doGet: function (_svc, _params) {
var nc = this
return new Promise(function (resolve, reject) {
axios({
method: 'get',
params: _params,
baseURL: process.env.VUE_APP_HOST_NAME,
url: _svc,
headers: { 'Authorization': nc.creds.token_type + ' ' + nc.creds.access_token }
}).then(axresp => {
var msg = axresp.data
console.log(axresp)
if(typeof msg == 'undefined')
{
reject(new Error('Invalid response from server. No data element found'))
return
}
resolve(msg)
}).catch(err => {
if(typeof err.response.status != 'undefined')
{
if(err.response.status == 401) nc.router.push({name: 'Login'})
}
})
})
},
doPost: function (_svc, _req) {
return this.doPostPut('post',_svc,_req)
},
doPut: function (_svc, _req) {
return this.doPostPut('put',_svc,_req)
},
doPostPut: function (_method, _svc, _req) {
var nc = this
return new Promise(function (resolve, reject) {
axios({
method: _method,
baseURL: process.env.VUE_APP_HOST_NAME,
url: _svc,
headers: { 'Authorization': nc.creds.token_type + ' ' + nc.creds.access_token },
data: _req
}).then(axresp => {
var msg = axresp.data
if(typeof msg == 'undefined')
{
reject(new Error('Invalid response from server. No data element found'))
return
}
resolve(msg)
}).catch(err => {
console.log('error in response!')
reject(err)
})
})
},
}
export default NetClient
<file_sep>/src/util/RankEnum.js
var RankEnum = {
1: 'Settler',
2: 'Officer',
3: 'Consul',
4: 'Governer',
keys: [1,2,3,4]
}
export default RankEnum
<file_sep>/src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import 'jquery/dist/jquery.slim.js'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.js'
import('@/assets/elc.css')
import NetClient from '@/util/NetClient.js'
NetClient.init(router)
createApp(App).use(router).mount('#app')
| 1687b571106f4e25ba0fa6b18864a08a0be737be | [
"Markdown",
"JavaScript"
] | 4 | Markdown | yudjinn/nwbnk-frontend | 8235870beaefcbf879ac49122eeb70ccc6dbbbdb | 847c7cba8d4cac521a652a23d1d6deb6d4bebda9 |
refs/heads/master | <repo_name>ZioPepito/PaunApp<file_sep>/src/Screens/UnityScreen.js
import React from "react";
import { SafeAreaView } from "react-native";
import UnityView from "react-native-unity-view";
import { UnityModule } from 'react-native-unity-view';
export default function UnityScreen({ navigation }) {
const id = navigation.getParam('id');
const ip = navigation.getParam('ip');
UnityModule.postMessageToUnityManager(id + '&' + ip); //sending a message to Unity app
const onUnityMessage = (handler) => { //handling messages from Unity app
if (handler.name == 'getInfo') {
UnityModule.postMessageToUnityManager(id + '&' + ip);
}else if (handler.name == 'ARSessionEnded') {
navigation.goBack();
} else {
console.log('LOGREACT: ' + handler.name);
const locID = handler.name;
navigation.navigate('GoToStation', { id, locID }); //this is for testing purpose. *
console.log('LOGREACT: log dopo navigate');
//*TODO: navigate to a screen waiting for the user to finish playing
//and let him click to confirm that he is leaving the workstation
}
}
return (
<SafeAreaView style={{
position: 'absolute', top: 0, bottom: 0, left: 0, right: 0,
justifyContent: 'center', alignItems: 'center', backgroundColor: 'black'
}}>
<UnityView
style={{ position: 'absolute', top: 1, left: 0, right: 0, bottom: 0 }}
onUnityMessage={onUnityMessage.bind(this)}
/>
</SafeAreaView>
);
}<file_sep>/src/App.js
import React from 'react';
import Stack from './Routes/Stack';
import { Provider } from 'react-redux';
import { store } from './Redux';
import AsyncStorage from '@react-native-community/async-storage';
import PushNotification from 'react-native-push-notification';
import GetLocation from 'react-native-get-location';
import BackgroundGeolocation from '@mauron85/react-native-background-geolocation';
import * as Workstations from './Workstations/Workstations';
import { checkSession } from './Networking/ServerCom';
/**
* @author: <NAME> <<EMAIL>>
* @author: <NAME> <<EMAIL>>
* @copyright ISISLab, Università degli Studi di Salerno
*/
function distance(lat1, lon1, lat2, lon2, unit) { //function to calculate the distance between 2 coordinates points on Earth
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1 / 180;
var radlat2 = Math.PI * lat2 / 180;
var theta = lon1 - lon2;
var radtheta = Math.PI * theta / 180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
if (unit == "K") { dist = dist * 1.609344 }
if (unit == "N") { dist = dist * 0.8684 }
return dist;
}
}
function workstationNearby(location, lastWorkstation) { //function to know if user is close to a workstation
const lat = location.latitude.toString();
const long = location.longitude.toString();
var workstation = 0;
if (distance(lat, long, Workstations.workstation1.lat, Workstations.workstation1.long, 'K') <= 0.01) workstation = 1;
else if (distance(lat, long, Workstations.workstation2.lat, Workstations.workstation2.long, 'K') <= 0.01) workstation = 2;
else if (distance(lat, long, Workstations.workstation3.lat, Workstations.workstation3.long, 'K') <= 0.01) workstation = 3;
else if (distance(lat, long, Workstations.workstation4.lat, Workstations.workstation4.long, 'K') <= 0.01) workstation = 4;
else if (distance(lat, long, Workstations.workstation5.lat, Workstations.workstation5.long, 'K') <= 0.01) workstation = 5;
else if (distance(lat, long, Workstations.workstation6.lat, Workstations.workstation6.long, 'K') <= 0.01) workstation = 6;
console.log('Utente vicino alla workstation ' + workstation);
return workstation == lastWorkstation ? 0 : workstation;
}
export default function App() {
var lastVisitedWorkstation = 0; //variable to know wich was the last workstation visited
var userID;
//PUSH NOTIFICATION CONFIGURATION
PushNotification.configure({
onRegister: function (token) {
console.log("TOKEN:", token);
},
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',
});
//BACKGROUND LOCATION TRACKING CONFIGURATION
BackgroundGeolocation.configure({
locationProvider: BackgroundGeolocation.DISTANCE_FILTER_PROVIDER,
desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
stationaryRadius: 10,
distanceFilter: 5,
debug: false,
stopOnTerminate: true,
startOnBoot: false,
interval: 9000,
fastestInterval: 4000,
activitiesInterval: 9000,
stopOnStillActivity: false,
notificationsEnabled: false,
startForeground: false,
notificationTitle: 'PaunApp traccia la poszione',
notificationText: 'per avvisarti quando ti avvicini ad una postazione',
url: 'http://192.168.81.15:3000/location',
httpHeaders: {},
// customize post properties
postTemplate: null,
});
//BACKGROUND LOCATION TRACKING USAGE (works only in background, not working when app killed)
BackgroundGeolocation.start();
BackgroundGeolocation.on('location', (location) => {
console.log('BackGeoLoc: ', location);
const workstation = workstationNearby(location, lastVisitedWorkstation);
AsyncStorage.getItem('RegID').then(id => { userID = id });
console.log('ID UTENTE: ' + userID);
try {
checkSession(userID, workstation,
() => console.log('già giocato alla postazione ' + workstation),
(status) => {
if (workstation != 0 && status == 404) {
lastVisitedWorkstation = workstation;
PushNotification.localNotificationSchedule({
title: "Sei vicino alla postazione " + workstation, // (optional)
message: "Scansiona il QR per utilizzarla", // (required)
date: new Date(Date.now() + 1 * 1000),
allowWhileIdle: true,
});
}
})
} catch (error) {
console.log(error);
}
});
//GET LOCATION every 10 seconds and notify if near workstation (doesn't work in background)
setInterval(() => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000
}).then(location => {
console.log('ForeGetLoc: ', location);
const workstation = workstationNearby(location, lastVisitedWorkstation);
AsyncStorage.getItem('RegID').then(id => { userID = id });
console.log('ID UTENTE: ' + userID);
try {
checkSession(userID, workstation,
() => console.log('già giocato alla postazione ' + workstation),
(status) => {
if (workstation != 0 && status == 404) {
lastVisitedWorkstation = workstation;
PushNotification.localNotificationSchedule({
title: "Sei vicino alla postazione " + workstation, // (optional)
message: "Scansiona il QR per utilizzarla", // (required)
date: new Date(Date.now() + 1 * 1000),
allowWhileIdle: true,
});
}
})
} catch (error) {
console.log(error);
}
}).catch(error => {
const { code, message } = error;
console.warn(code, message);
})
}, 9000);
return (
<Provider store={store}>
<Stack />
</Provider>
);
}<file_sep>/src/Style/Styles.js
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 0.87,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#fff'
},
noSocial: {
flex: 0.13,
justifyContent: 'center',
alignItems: 'center',
},
noSocialBtn: {
elevation: 2,
backgroundColor: "#c2cfdc",
borderRadius: 2,
padding: 3
},
nickname: {
marginTop: '5%',
marginBottom: '20%',
borderWidth: 1,
borderRadius: 5,
borderColor: '#ccc',
fontSize: 18
},
ip: {
marginTop: '5%',
marginLeft: '2%',
marginRight: '2%',
borderWidth: 1,
borderRadius: 5,
borderColor: '#ccc',
fontSize: 18
},
logout: {
flex: 0.13,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
backgroundColor: '#fff'
},
H6: {
fontSize: 20,
fontFamily: 'Titillium-Regular'
}
});
export { styles };<file_sep>/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
lng: "it",
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
resources: {
it: {
translation: {
"Welcome": "Benvenuto",
"Please login": "Accedi per sbloccare tutti i contenuti dell'app.",
"Login with Google": "Accedi con Google",
"Login with Twitter": "Accedi con Twitter",
}
}
}
});
export default i18n;
<file_sep>/src/Hooks/usePermissionManager/index.js
import React, { useEffect, useState } from "react";
import { PermissionsAndroid } from "react-native";
function requestFineLocationPermission() {
return PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'PAUN Geolocalization',
message: 'PAUN needs to retrieve your position in order to guide you.',
buttonNeutral: 'Ask me later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
}
/**
* usePermissionManager is a hook that encapsulate permission requests to the OS.
*/
export default function usePermissionManager() {
const [hasLocationPermission, setLocationPermission] = useState(false);
useEffect(() => {
requestFineLocationPermission()
.then(result => setLocationPermission(result === PermissionsAndroid.RESULTS.GRANTED))
.catch(() => setLocationPermission(false));
}, []);
// Return an object containing several useful info
return {
hasLocationPermission,
}
}<file_sep>/src/Routes/Stack.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import HomeScreen from '../Screens/HomeScreen';
import ChooseNicknameScreen from '../Screens/ChooseNicknameScreen';
import GameScreen from '../Screens/GamesScreen';
import UnityScreen from '../Screens/UnityScreen';
import GoToStationScreen from '../Screens/GoToStationScreen';
import LeaveStationScreen from '../Screens/LeaveStationScreen';
const screens = {
Home: {
screen: HomeScreen,
navigationOptions: {
headerShown: false
}
},
ChooseNickname: {
screen: ChooseNicknameScreen,
navigationOptions: {
headerShown: false
}
},
Game: {
screen: GameScreen,
navigationOptions: {
headerShown: false
}
},
Unity: {
screen: UnityScreen,
navigationOptions: {
headerShown: false
}
},
GoToStation: { //only for testing purpose
screen: GoToStationScreen,
navigationOptions: {
headerShown: false
}
},
LeaveStation: { //only for testing purpose
screen: LeaveStationScreen,
navigationOptions: {
headerShown: false
}
}
}
const stack = createStackNavigator(screens);
export default createAppContainer(stack);<file_sep>/src/Screens/LeaveStationScreen.js
import React from 'react';
import { View, ScrollView, Text, Button } from 'react-native';
import { endSession } from '../Networking/ServerCom';
import { styles } from '../Style/Styles';
import LanguageSelectionPanel from '.././Ui/LanguageSelectionPanel';
import Logo from '.././Ui/Logo';
export default function LeaveStationScreen({ navigation }) {
const id = navigation.getParam('id');
const locationId = navigation.getParam('locationId');
return (
<ScrollView contentContainerStyle={{ flex: 1 }}>
<View style={styles.container}>
<LanguageSelectionPanel />
<Logo />
<Text style={styles.H6}>Premi il pulsante per terminare</Text>
<View style={{ marginTop: '10%' }}>
<Button
title="Lascia postazione"
onPress={
async () => {
try {
endSession(id, locationId, 'dado:true;coins:5',
() => {
console.log('session ended');
navigation.navigate('Game')
}, error => console.log(error))
} catch (error) {
console.log(error);
}
}
}
/>
</View>
</View>
</ScrollView>
);
}<file_sep>/src/Context/ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext('default');
export const Themes = {
'default': {
Text: { }
},
'playful': {
Button: {
fontFamily: "Kalam-Regular"
},
Text: {
color: "green",
fontFamily: "Kalam-Regular"
}
}
}
export default ThemeContext;
<file_sep>/README.md
# PAUN React Native App
L'app è sviluppata utilizzando [React Native](https://facebook.github.io/react-native/)
## Per iniziare
Lanciare 'npm install' nella cartella del progetto per scaricare tutti i moduli necessari all'applicazione (la cartella node_modules verrà creata).
Lanciare 'npx react-native run-android' (oppure run-ios) per eseguire l'app su un dispositivo collegato o su un emulatore attivo.
## Funzionalità
L'app permette di effettuare il login attraverso social network (Google o Facebbok) oppure come opsite.
A scopo di test è possibile inserire l'ip del server con il quale comunicare, se si vuole testare con un istanza del server avviata in locale.
Alla schermata con pulsante di avvio di Unity è presente anche un pulsante che simula le fasi di comunicazione con il server nel caso di avvio, conferma e chiusura di una sessione di utilizzo di una postazione.
## In via di sviluppo
Monitoraggio della posizione dell'utente attraverso GPS per notificare in caso di vicinanza ad una postazione e invogliare l'utente ad utilizzarla mediante scan del QR Code
## Unity
Il progetto Unity integrato è un progetto di esempio con un semplice cubo che gira. Lo scopo è solo di mostrare come integrare un progetto Unity in un app sviluppata con React Native.
## Build Android
1. Aprire il progetto in Unity
1. Eseguire Build => Export Android
1. Aprire la cartella Builds ed eliminare il file "PaunApp-0.1-v1.symbols.zip" se presente
1. Effettuare la build dell'app React-Native
## Build iOS
1. Aprire il progetto in Unity
1. Eseguire build => Export iOS
1. Installazione dipendenze:
* Eseguire "npm install" nella root del progetto react
* Eseguire "pod install" nella cartella ios
1. Aprire il file .xcworkspace in xcode
1. Configurazione header
* Selezionare RNUnityView.xcodeproj nella cartella Libraries
* Selezionare il target RNUnityView
* Selezionare il tab Build Settings
* Aggiungere a Header Search Paths "$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core" e "$(SRCROOT)/../../../node_modules/react-native/ReactCommon/yoga"
* Aprire il file Libraries => RNUnityView.xcodeproj => UnityUtils.mm e commentare la riga 39 "UnityInitStartupTime();"
1. Aprire in xcode la cartella UnityExport/Classes e rimuovere le referenze ai file "DynamicLibEngineAPI-functions.h" e "DynamicLibEngineAPI.mm"
1. Aprire dal menu di xcode Product => Scheme => Edit scheme, selezionare Run dalla barra laterale, selezionare il tab info e modificare Build configuration in Release
1. Assicurarsi che il device selezionato come target non sia un simulatore prima di effettuare la build
1. Effettuare la build dell'app React-Native
# Integrazione Unity
Per integrare un proprio progetto Unity è necessario innanzitutto inserirlo all'interno della cartella /unity al posto del progetto di esempio, successivamente si deve copiare la cartella [`Assets/Scripts`](https://github.com/ZioPepito/PaunApp/tree/master/unity/IntegrationSample/Assets/Scripts) e il file [`link.xml`](https://github.com/ZioPepito/PaunApp/blob/master/unity/IntegrationSample/Assets/link.xml) nel proprio progetto. È necessario utilizzare una versione di Unity non superiore a 2019.2.x. Il modulo utilizzato per l'integrazione è presente al seguente link https://www.npmjs.com/package/react-native-unity-view.
## Passaggi aggiuntivi Android
In *Player Settings -> Other Settings* impostare come segue:
1. Scripting Backend: IL2CPP
1. Api compatibility level: .NET 4.x
1. Auto Graphics API: non selezionato
1. Graphics API: OpenGLES3 e OpenGLES2 in quest'ordine
1. Target Architectures: ARM64 selezionato
In *Player Setting -> Resolution and presentation* deselezionare *Start in full screen mode* e *Render outside safe area*.
## Passaggi aggiuntivi iOS
In *Player Settings -> Other Settings* selezionare *Auto Graphics API*
# PaunApp dettagli tecnici
Versione React Native: 0.61.0
Versione Node: 12.9.1
Versione npm: 6.10.2
Versione Unity: 2019.2.x
<file_sep>/src/Screens/GamesScreen.js
import React, { useState } from 'react';
import { Text, View, Button, ScrollView, TouchableOpacity } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { useDispatch } from 'react-redux';
import { updateLogoutAction } from '../Redux';
import { startSession } from '../Networking/ServerCom';
import { styles } from '../Style/Styles';
import LanguageSelectionPanel from '.././Ui/LanguageSelectionPanel';
import Logo from '.././Ui/Logo';
export default function GameScreen({ navigation }) {
const dispatch = useDispatch();
const [id, setId] = useState(navigation.getParam('id'));
const [ip, setIp] = useState(navigation.getParam('ip'));
if (id !== undefined) AsyncStorage.setItem('RegID', id).catch(err => console.log(err));
if (id == undefined) AsyncStorage.getItem('RegID').then(RegID => setId(RegID)).catch(err => console.log(err));
if (ip == undefined) AsyncStorage.getItem('ip').then(ip => setIp(ip)).catch(err => console.log(err));
return (
<ScrollView contentContainerStyle={{ flex: 1 }}>
<View style={styles.container}>
<LanguageSelectionPanel />
<Logo />
<Text style={styles.H6}>
Benvenuto {navigation.getParam('nickname')}! {/*this is temp*/}
</Text>
<View style={{ marginTop: '8%' }}>
<Button
title="Realta' aumentata"
onPress={() => navigation.navigate('Unity', { id , ip })}
/>
</View>
<View style={{ marginTop: '6%' }}>
<Button
title="Simulazione QRCode"
onPress={
async () => {
try {
startSession(id, '1',
(gameStates) => {
console.log(gameStates);
navigation.navigate('GoToStation', { id, locID: 1 })
}, (error) => console.log(error))
} catch (error) {
console.log(error);
}
}
}
/>
</View>
</View>
<View style={styles.logout}>
<Text style={{ fontFamily: 'Titillium-Regular' }}> {navigation.getParam('nickname')} </Text>
<TouchableOpacity>
<Text
style={{ textDecorationLine: 'underline', fontFamily: 'Titillium-Regular'}}
onPress={
async () => {
try {
await AsyncStorage.removeItem('Nickname');
await AsyncStorage.removeItem('RegID');
} catch (error) {
console.log(value);
}
navigation.navigate('Home');
dispatch(updateLogoutAction(true));
}
}
> Logout </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}<file_sep>/android/settings.gradle
rootProject.name = 'PaunApp'
include ':@mauron85_react-native-background-geolocation-common'
project(':@mauron85_react-native-background-geolocation-common').projectDir = new File(rootProject.projectDir, '../node_modules/@mauron85/react-native-background-geolocation/android/common')
include ':@mauron85_react-native-background-geolocation'
project(':@mauron85_react-native-background-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/@mauron85/react-native-background-geolocation/android/lib')
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = file('../node_modules/react-native-push-notification/android')
include ':@react-native-community_geolocation'
project(':@react-native-community_geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/geolocation/android')
include ':react-native-unity-view'
project(':react-native-unity-view').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-unity-view/android')
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
include ":UnityExport"
project(":UnityExport").projectDir = file("./UnityExport")<file_sep>/ios/Readme.md
## Configurazione preliminare per iOS
1. Aprire il progetto in Unity
1. Eseguire build => Export iOS
1. Installazione dipendenze:
* Eseguire "npm install" nella root del progetto react
* Eseguire "pod install" nella cartella ios
1. Aprire il file .xcworkspace in xcode
1. Configurazione header
* Selezionare RNUnityView.xcodeproj nella cartella Libraries
* Selezionare il target RNUnityView
* Selezionare il tab Build Settings
* Aggiungere a Header Search Paths "$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core" e "$(SRCROOT)/../../../node_modules/react-native/ReactCommon/yoga"
* Aprire il file Libraries => RNUnityView.xcodeproj => UnityUtils.mm e commentare la riga 39 "UnityInitStartupTime();"
1. Aprire in xcode la cartella UnityExport/Classes e rimuovere le referenze ai file "DynamicLibEngineAPI-functions.h" e "DynamicLibEngineAPI.mm"
1. Aprire dal menu di xcode Product => Scheme => Edit scheme, selezionare Run dalla barra laterale, selezionare il tab info e modificare Build configuration in Release
1. Assicurarsi che il device selezionato come target non sia un simulatore prima di effettuare la build<file_sep>/android/Readme.md
## Configurazione preliminare per Android
1. Aprire il progetto in Unity
1. Aprire File => Build Settings => Player Settings
1. Verificare che "Scripting Backend" sia "IL2CPP" e "Api Compatibility Level" sia ".NET 4.x"
1. Eseguire Build => Export Android
1. Aprire la cartella Builds ed eliminare il file "PaunApp-0.1-v1.symbols.zip"<file_sep>/react-native.config.js
module.exports = {
project: {
ios: {},
android: {}
},
assets: [
"./src/Fonts/Titillium"
],
}<file_sep>/src/Screens/HomeScreen.js
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Button, ScrollView, Image, TextInput } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { useSelector, useDispatch } from 'react-redux';
import { updateLogoutAction } from '../Redux';
import { register, setURL } from '../Networking/ServerCom';
import { styles } from '../Style/Styles';
// Custom PAUN hooks
import useAuthenticationManager from '.././Hooks/useAuthenticationManager';
import LanguageSelectionPanel from '.././Ui/LanguageSelectionPanel';
import Logo from '.././Ui/Logo';
export default function HomeScreen({ navigation }) {
const [ip, setIp] = useState('');
AsyncStorage.getItem('ip')
.then(ip => {
if (ip !== null) {
setIp(ip);
setURL(ip);
}
})
const logout = useSelector((state) => state.logout);
const dispatch = useDispatch();
AsyncStorage.getItem('Nickname')
.then(nickname => {
if (nickname !== null) {
navigation.navigate('Game', { nickname });
}
})
.catch(err => console.log(err));
const authManager = useAuthenticationManager();
const userAvatar = authManager.isLogged && authManager.userProfile && authManager.userProfile.picture;
const userName = authManager.userProfile && authManager.userProfile.name;
const guest = (
<Button
title="Connetti con un social"
onPress={() => !authManager.isLogged ? authManager.requestAuthentication() : dispatch(updateLogoutAction(false))}
/>
);
const logged = (
<View style={{ flex: 1 }}>
<View style={{ flex: 1, flexDirection: "row", alignItems: "center", paddingHorizontal: 12 }}>
{userAvatar && (
<Image
resizeMode="stretch"
style={{ aspectRatio: 1, height: 50, borderRadius: 50, marginRight: 10 }}
source={{ uri: userAvatar }}
/>
)}
<Text style={{ flexGrow: 1, marginRight: 10, fontFamily: 'Titillium-Regular' }}>
{userName}
</Text>
<Button
title="Logout"
onPress={() => authManager.clearSession()}
/>
</View>
<View>
<Button
title="Continua"
onPress={
async () => {
try {
await AsyncStorage.setItem('userProfile', JSON.stringify(authManager.userProfile));
} catch (error) {
console.log(error);
}
try {
if (authManager.userProfile.sub.includes('google')) {
register((id) => navigation.navigate('ChooseNickname', { userName, id }),
(error) => console.log(error), userName, null, authManager.userProfile.email);
} else if (authManager.userProfile.sub.includes('facebook')) {
register((id) => navigation.navigate('ChooseNickname', { userName, id }),
(error) => console.log(error), userName, authManager.userProfile.name, null);
} else console.log('Unsupported social');
} catch (error) {
console.log(error);
}
}
}
/>
</View>
</View>
);
return (
<ScrollView contentContainerStyle={{ flex: 1 }}>
<View style={styles.container}>
<LanguageSelectionPanel />
<Logo />
{(authManager.isLogged && !logout) ? logged : guest}
<TextInput
style={styles.ip}
placeholder="Inserisci IP"
onChangeText={
async (ip) => {
setIp(ip); setURL(ip);
try {
await AsyncStorage.setItem('ip', ip);
} catch (error) {
console.log(error);
}
}
}
defaultValue={ip}
/>
</View>
<View style={styles.noSocial}>
<TouchableOpacity style={styles.noSocialBtn}>
<Text
style={{ fontFamily: 'Titillium-Regular' }}
onPress={() => navigation.navigate('ChooseNickname', { ip })}
> Prosegui senza social </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}<file_sep>/src/Redux/index.js
import { createStore } from 'redux';
const initialState = {
logout: false
}
export const store = createStore(reducer, initialState);
function reducer(state, action) {
switch (action.type) {
case 'UPDATE_LOGOUT':
return {
state,
logout: action.payload
};
default:
return state;
}
}
export const updateLogoutAction = (logout) => ({
type: 'UPDATE_LOGOUT',
payload: logout
})<file_sep>/src/Ui/LanguageSelectionPanel.js
import React, { useContext } from 'react';
import { View, Button, StyleSheet } from 'react-native';
//import TransContext from "../Context/TransContext";
export default function LanguageSelectionPanel() {
//const { t, i18n } = useContext(TransContext);
return (
<View style={styles.panel}>
<View style={{ margin: 6 }}>
<Button
//onPress={() => i18n.changeLanguage("it-IT")}
title="Italiano"
/>
</View>
<View style={{ margin: 6 }}>
<Button
//onPress={() => i18n.changeLanguage("en-US")}
title="English"
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
panel: {
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: '#fff',
paddingTop: 10,
marginBottom: 10,
}
});<file_sep>/src/Networking/ServerCom.js
var URL = "http://isiswork03.di.unisa.it:1337"
export async function setURL(newURL) {
URL = newURL;
}
export async function register(success, error, username, facebookid = null, googleid = null) {
let data = "username=" + username;
if (facebookid != null)
data += "&facebookid=" + facebookid;
if (googleid != null)
data += "&googleid=" + googleid;
fetch(URL+'/register', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success(response.headers.get("id"));
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function associateFacebook(userid, facebookid, success, error) {
let data = "userid=" + userid;
data += "&facebookid=" + facebookid;
fetch(URL+'/associatefacebook', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function startSession(userid, locationid, success, error) {
let data = "userid=" + userid;
data += "&locationid=" + locationid;
fetch(URL + '/startsession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
response.json().then(gameStates => success(gameStates));
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function startSessionToken(userid, locationid, token, success, error) {
let data = "userid=" + userid;
data += "&locationid=" + locationid;
data += "&token=" + token;
fetch(URL + '/startsessiontoken', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function confirmSession(userid, locationid, success, error) {
let data = "userid=" + userid;
data += "&locationid=" + locationid;
fetch(URL + '/confirmsession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
response.json().then(gameStates => success(gameStates));
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function endSession(userid, locationid, gameState, success, error) {
let data = "userid=" + userid;
data += "&locationid=" + locationid;
data += "&gamestate=" + gameState;
fetch(URL + '/endsession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function getSessionToken(locationid, success, error) {
let data = "locationid=" + locationid;
fetch(URL + '/getsessiontoken', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success(response.headers.get("token"));
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function getNewSession(locationid, success, error) {
let data = "locationid=" + locationid;
fetch(URL + '/getnewsession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success(response.headers.get("sessionid"), response.headers.get("userid"));
else
response.text().then(data => error(data));
}, e => error(e));
}
export async function checkSession(userid, locationid, success, error) { //function to know if a user has already played with a location
if (userid == undefined || userid == null) error(404);
let data = "userid=" + userid;
data += "&locationid=" + locationid;
fetch(URL + '/checksession?' + data, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow'
}).then(response => {
if (response.status == 200)
success();
else
error(response.status);
}, e => error(e));
}
//admin
async function getUser(userid, success, error) {
let data = "userid=" + userid;
fetch(URL + '/getuser?' + data, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow'
}).then(response => {
if (response.status == 200)
response.json().then(user => success(user));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function listUsers(success, error) {
fetch(URL + '/listusers', {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow'
}).then(response => {
if (response.status == 200)
response.json().then(users => success(users));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function updateUser(success, error, userid, username = null, facebookid = null) {
let data = "userid=" + userid;
if (facebookid != null)
data += "&facebookid=" + facebookid;
if (username != null)
data += "&username=" + username;
fetch(URL + '/updateuser', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
async function addUser(success, error, username, facebookid = null) {
let data = "username=" + username;
if (facebookid != null)
data += "&facebookid=" + facebookid;
fetch(URL + '/adduser', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success(response.headers.get("id"));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function removeUser(userid, success, error) {
let data = "userid=" + userid;
fetch(URL + '/removeuser', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
async function getSession(sessionid, success, error) {
let data = "sessionid=" + sessionid;
fetch(URL + '/getsession?' + data, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow'
}).then(response => {
if (response.status == 200)
response.json().then(session => success(session));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function listSessions(success, error) {
fetch(URL + '/listsessions', {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow'
}).then(response => {
if (response.status == 200)
response.json().then(sessions => success(sessions));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function updateSession(sessionid, userid, locationid, state, gamestate, success, error) {
let data = "sessionid=" + sessionid;
if (userid != null && userid != undefined)
data += "&userid=" + userid;
if (locationid != null && locationid != undefined)
data += "&locationid=" + locationid;
if (state != null && state != undefined)
data += "&state=" + state;
if (gamestate != null && gamestate != undefined)
data += "&gamestate=" + gamestate;
fetch(URL + '/updatesession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
async function addSession(success, error, userid, locationid, state, gamestate = null) {
let data = "userid=" + userid;
data += "&locationid=" + locationid;
data += "&state=" + state;
if (gamestate != null && gamestate != undefined)
data += "&gamestate=" + gamestate;
fetch(URL + '/addsession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success(response.headers.get("sessionid"));
else
response.text().then(data => error(data));
}, e => error(e));
}
async function removeSession(sessionid, success, error) {
let data = "sessionid=" + sessionid;
fetch(URL + '/removesession', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
body: data
}).then(response => {
if (response.status == 200)
success();
else
response.text().then(data => error(data));
}, e => error(e));
}
<file_sep>/src/Screens/ChooseNicknameScreen.js
import React, { useState } from 'react';
import { View, Button, ScrollView, TextInput } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { register } from '../Networking/ServerCom';
import { styles } from '../Style/Styles';
import LanguageSelectionPanel from '.././Ui/LanguageSelectionPanel';
import Logo from '.././Ui/Logo';
export default function ChooseNicknameScreen({ navigation }) {
const [nickname, setNickname] = useState(navigation.getParam('userName'));
const error = 'Il tuo nickname deve contenere piu\' di 5 caratteri';
const id = navigation.getParam('id');
const ip = navigation.getParam('ip');
return (
<ScrollView contentContainerStyle={{ flex: 1 }}>
<View style={styles.container}>
<LanguageSelectionPanel />
<Logo />
<TextInput
style={styles.nickname}
placeholder="Scegli nickname"
onChangeText={ nickname => setNickname(nickname) }
defaultValue={nickname}
maxLength={20}
/>
<Button
title="Conferma"
onPress={
async () => {
if (nickname != null && nickname.length > 5) {
try {
await AsyncStorage.setItem('Nickname', nickname);
} catch (error) {
console.log(error);
}
if (navigation.getParam('userName') == undefined) {
try {
register((id) => navigation.navigate('Game', { nickname, id, ip }),
(error) => console.log(error), nickname);
} catch (error) {
console.log(error);
}
} else
navigation.navigate('Game', { nickname, id, ip });
} else
alert(error);
}
}
/>
</View>
</ScrollView>
);
} | 8eee93672d7afadf717050f4b5d4d6b9fc8f293e | [
"JavaScript",
"Markdown",
"Gradle"
] | 19 | JavaScript | ZioPepito/PaunApp | 84b3c0260ae853e1ce5f344051573ebf2818a320 | 0073678f00cff2969f985e5ac17b5e51e5f33281 |
refs/heads/master | <repo_name>Drkilla/AspNetTPObjectsView<file_sep>/TP_Train_passages_objets/Controllers/WagonController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TP_Train_passages_objets.Controllers
{
public class Passagers
{
public string nom;
public Passagers(string pNom)
{
nom = pNom;
}
public Passagers()
{
}
}
public class Wagon
{
public int nombre;
public int numero;
public int nombrePassagers;
public List<Passagers> listPassagers = new List<Passagers>();
public Wagon(int pNombre,int pNumero,List<Passagers>LstPassagers)
{
nombre = pNombre;
numero = pNumero;
this.listPassagers = LstPassagers;
}
public Wagon()
{
}
}
public class Train
{
public List<Wagon> lstWagons = new List<Wagon>();
public Train(List<Wagon>lstWagon)
{
lstWagons = lstWagon;
}
public Train()
{
}
}
public class WagonController : Controller
{
// GET: Wagon
public ActionResult Index()
{
Passagers mesPassagers = new Passagers();
Wagon wagon1 = new Wagon();
Train monTrain = new Train();
wagon1.listPassagers.Add(new Passagers("Alice"));
wagon1.listPassagers.Add(new Passagers("Bob"));
wagon1.listPassagers.Add(new Passagers("Soshana"));
wagon1.listPassagers.Add(new Passagers("Jeremie"));
wagon1.numero = 1;
Wagon wagon2 = new Wagon();
wagon2.listPassagers.Add(new Passagers("Kevin"));
wagon2.listPassagers.Add(new Passagers("Jean"));
wagon2.listPassagers.Add(new Passagers("Donald"));
wagon2.numero = 2;
monTrain.lstWagons.Add(wagon1);
monTrain.lstWagons.Add(wagon2);
return View(monTrain);
}
}
} | 06322b017e45f66429fadc421cdc2502afe267e6 | [
"C#"
] | 1 | C# | Drkilla/AspNetTPObjectsView | 291faf3dae94e6aa9d3ad5ebbb11ad2ccf537a3d | 94bb2164855e4b9ca64b681e13516ba1d35764fd |
refs/heads/master | <file_sep>import React from "react"
import Session from "../Components/session/Session"
import Header from "../Components/header"
import "../Styles/login.css"
function Login () {
return (
<>
<Header/>
<Session/>
</>
)
}
export default Login<file_sep>import React, { useEffect, useState } from "react"
import axios from "axios"
import { Field, FieldArray, Form, Formik } from "formik"
import { useHistory } from "react-router"
import { IoMdAddCircle } from "react-icons/io"
import Content from "../Content"
import baseUrl from "../../../fetch/url"
import Button from "../../../Button"
import CharacterCard from "./CharacterCard"
import useDataFetch from "../../../fetch/useDataFetch"
function GameNpcs ({url}) {
const history = useHistory()
const [{data, isLoading}] = useDataFetch(`games/sheet/${url}`)
const [npcs, setNpcs] = useState([{game_id: url, id:"", name: "", image: "", fields: [] || []}])
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.post(baseUrl + `games/getnpcs`, {game_id: url})
if (result.data.length !== 0)
setNpcs(result.data)
else
setNpcs([{game_id: url, id:"", name: "", image: "", fields: data}])
}catch(error) {
alert(error)
}
}
fetchData()
}, [url, data])
if (isLoading) return null
const fields = data? (data.map((field) => {
return {name: field.name, type: field.type, sheet_id: field.sheet_id, value: ""}
})): null
return (
<Content name="Npcs">
<Formik
initialValues={{
game_id: url,
id: "",
name: "",
image: "",
fields: fields || []
}}
onSubmit= {async (values) => {
try {
await axios.post(baseUrl + "games/savenpc", values)
history.go()
}catch(err) {
alert(err)
}
}}>
{({ values, setValues, errors, touched }) => (
<Form>
<FieldArray name="fields">
<>
{npcs.map((npc) => {
return (
<div key={npc.name} style={{marginBottom:"10px", justifyContent:"flex-start"}} className="form-line">
<p style={{marginRight: "10px"}} className="cursor bold" onClick={() => setValues(npc)}>{npc.name}</p>
{values.id === npc.id? <p>{"<--"}</p>:null}
</div>
)
})}
<div className="form-line">
<label htmlFor={values.name}>Name</label>
<Field className="content-input" style={{width: "70%", margin: "10px"}} name="name"/>
</div>
<div className="form-line">
<label htmlFor={values.name}>Image</label>
<Field className="content-input" style={{width: "70%", margin: "10px"}} name="image"/>
</div>
<div style={{display:"flex", justifyContent: "center"}}>
<CharacterCard name={values.name} image={values.image}/>
</div>
{values.fields.length > 0 && values.fields.map((field, index) => (
<div key={index} className="form-line">
<label htmlFor={`fields.${index}.value`}>{field.name}</label>
<Field className={`content-${field.type}`} as={field.type} style={{width: "70%", margin: "10px"}} name={`fields.${index}.value`}/>
</div>
))}
</>
</FieldArray>
<Button type="submit" classes="button end" text="Save"/>
<div onClick={() => setValues({game_id: url, id:"", name: "", image: "", fields: fields || []})} className="add-button cursor">
<IoMdAddCircle/>
</div>
</Form>
)}
</Formik>
</Content>
)
}
export default GameNpcs<file_sep>import React from "react"
import Fadein from "react-fade-in"
import Button from "../Button"
import "./modal.css"
function Modal ({title, close, children, className}) {
return (
<Fadein className={`modal ${className}`}>
<header id="modal-header">
<h1>{title}</h1>
<p onClick={() => close()} className="cursor">X</p>
</header>
<div id="modal-children">
{children}
</div>
<footer id="modal-footer">
<Button type="button" func={() => close()} classes="button modal-button" text="Close"/>
<Button type="submit" classes="button modal-button" text="Save"/>
</footer>
</Fadein>
)
}
export default Modal<file_sep>import React, { useEffect, useState } from "react"
import axios from "axios"
import { Field, FieldArray, Form, Formik } from "formik"
import { useHistory } from "react-router"
import Content from "../Content"
import baseUrl from "../../../fetch/url"
import Button from "../../../Button"
import CharacterCard from "./CharacterCard"
function GameCharacter ({url}) {
const user_id = localStorage.getItem("id")
const history = useHistory()
const [character, setCharacter] = useState()
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.post(baseUrl + `games/getcharacter`, {user_id: user_id, game_id: url})
setCharacter(result.data)
}catch(error) {
alert(error)
}
}
fetchData()
}, [url, user_id])
if (!character) return null
return (
<Content name="Character">
<Formik
initialValues={{
game_id: url,
user_id: user_id,
name: character.name,
image: character.image,
fields: character.fields
}}
onSubmit= {async (values) => {
try {
await axios.post(baseUrl + "games/savecharacter", values)
history.go()
}catch(err) {
alert(err)
}
}}>
{({ values, errors, touched }) => (
<Form>
<FieldArray name="fields">
<>
<div className="form-line">
<label htmlFor={values.name}>Name</label>
<Field className="content-input" style={{width: "70%", margin: "10px"}} name="name"/>
</div>
<div className="form-line">
<label htmlFor={values.name}>Image</label>
<Field className="content-input" style={{width: "70%", margin: "10px"}} name="image"/>
</div>
<div style={{display:"flex", justifyContent: "center"}}>
<CharacterCard name={values.name} image={values.image}/>
</div>
{values.fields.length > 0 && values.fields.map((field, index) => (
<div key={index} className="form-line">
<label htmlFor={`fields.${index}.value`}>{field.name}</label>
<Field className={`content-${field.type}`} as={field.type} style={{width: "70%", margin: "10px"}} name={`fields.${index}.value`}/>
</div>
))}
</>
</FieldArray>
<Button type="submit" classes="button end" text="Save"/>
</Form>
)}
</Formik>
</Content>
)
}
export default GameCharacter<file_sep>import sqlite3
from flask import jsonify
import random
class Game():
def __init__(self):
pass
def __generate_id(self):
chars = 'abcdefghijklmnopqrstuvwxyz1234567890'
game_id = ''
for i in range(7):
game_id += random.choice(chars)
return game_id
def add_user(self, c, request):
try:
game_id, user_id = request['game_id'], request['user_id']
c.execute('INSERT INTO GamePermissions VALUES (NULL, ?, ?)', (game_id, user_id,))
return jsonify(True)
except:
return jsonify("It was not possible to join the game"), 400
def create_game(self, c, request):
try:
id = self.__generate_id()
owner_id, gamename, genre, description, image = request['owner_id'], request['gamename'], request['genre'], request['description'], request['image']
c.execute('INSERT INTO Games VALUES (?, ?, ?, ?, ?, ?, 0)', (id, owner_id, gamename, genre, image, description))
c.execute('INSERT INTO GamePermissions VALUES(NULL, ?, ?)', (id, owner_id,))
return jsonify(True)
except:
return jsonify("It was not possible to create the game"), 400
def game_info(self, c, id):
try:
players = []
c.execute('SELECT * FROM Games WHERE id = ? AND erased = 0', (id,))
info = c.fetchone()
if info == None:
return jsonify("Game doesn't exist"), 400
for row in c.execute('''SELECT Users.id, Users.username
FROM Users
INNER JOIN GamePermissions ON Users.id=GamePermissions.user_id
WHERE game_id=?''', (id,)):
players.append({'id': row[0], 'name': row[1]})
response = {
'id': info[0],
'owner_id': info[1],
'gamename': info[2],
'genre': info[3],
'image': info[4],
'description': info[5],
'players': players,
}
return jsonify(response)
except:
return jsonify("Game doesn't exist"), 400
def user_games(self, c, id):
try:
response = []
for row in c.execute('''SELECT *
FROM Games
WHERE owner_id = ? AND erased = 0''', (id,)):
response.append({'id': row[0],'owner_id': row[1], 'gamename': row[2], 'genre': row[3], 'image': row[4], 'description': row[5]})
for row in c.execute('''SELECT *
FROM Games
INNER JOIN GamePermissions ON games.id=GamePermissions.game_id
WHERE GamePermissions.user_id = ? AND games.owner_id <> ? AND games.erased = 0''', (id, id,)):
response.append({'id': row[0],'owner_id': row[1], 'gamename': row[2], 'genre': row[3], 'image': row[4], 'description': row[5]})
return jsonify(response)
except:
return jsonify("The user doesn't exist"), 400<file_sep>import sqlite3
from flask import jsonify
class Sheet():
def __init__(self):
pass
def get_sheet(self, c, id):
try:
sheet = []
for row in c.execute('SELECT id, name, type FROM SheetFields WHERE game_id = ? AND erased = 0', (id,)):
sheet.append({'sheet_id': row[0],'name': row[1], 'type': row[2]})
return jsonify(sheet)
except:
return jsonify("It was not possible to get the sheet"), 400
def save_sheet(self, c, request):
try:
game_id = request['game_id']
fields = {}
c.execute('UPDATE SheetFields SET erased = 1 WHERE game_id = ?', (game_id,))
for field in request['fields']:
c.execute('INSERT INTO SheetFields VALUES (NULL, ?, ?, ?, 0)', (game_id, field['type'], field['name'],))
return jsonify(True)
except:
return jsonify("It was not possible to save the fields"), 400<file_sep>import sqlite3
conn = sqlite3.connect('RPGHub.db')
c = conn.cursor()
c.execute('pragma foreign_keys = on')
c.execute('''
CREATE TABLE Users (
id INTEGER NOT NULL,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
)
''')
c.execute('''
CREATE TABLE Games(
id TEXT NOT NULL UNIQUE,
owner_id INTEGER NOT NULL,
gamename TEXT NOT NULL,
genre TEXT,
image TEXT,
description TEXT,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(owner_id) REFERENCES Users(id)
)
''')
c.execute('''
CREATE TABLE GamePermissions(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(user_id) REFERENCES Users(id)
FOREIGN KEY(game_id) REFERENCES Games(id)
)
''')
c.execute('''
CREATE TABLE SheetFields(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
type TEXT NOT NULL,
name TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(game_id) REFERENCES Games(id)
)
''')
c.execute('''
CREATE TABLE Resources(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
name TEXT NOT NULL,
link TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(game_id) REFERENCES Games(id)
)
''')
c.execute('''
CREATE TABLE Notes(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
user_id TEXT NOT NULL,
text TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(game_id) REFERENCES Games(id)
FOREIGN KEY(user_id) REFERENCES Users(id)
)
''')
c.execute('''
CREATE TABLE Characters(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
user_id TEXT NOT NULL,
name TEXT NOT NULL,
image TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(game_id) REFERENCES Games(id)
FOREIGN KEY(user_id) REFERENCES Users(id)
)
''')
c.execute('''
CREATE TABLE CharacterFields(
id INTEGER NOT NULL,
sheet_id INTEGER NOT NULL,
user_id TEXT NOT NULL,
value TEXT,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(sheet_id) REFERENCES SheetFields(id)
FOREIGN KEY(user_id) REFERENCES Users(id)
)
''')
c.execute('''
CREATE TABLE Npcs(
id INTEGER NOT NULL,
game_id INTEGER NOT NULL,
name TEXT NOT NULL,
image TEXT NOT NULL,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(game_id) REFERENCES Games(id)
)
''')
c.execute('''
CREATE TABLE NpcFields(
id INTEGER NOT NULL,
sheet_id INTEGER NOT NULL,
npc_id TEXT NOT NULL,
value TEXT,
erased INTEGER NOT NULL,
PRIMARY KEY (id)
FOREIGN KEY(sheet_id) REFERENCES SheetFields(id)
FOREIGN KEY(npc_id) REFERENCES Npcs(id)
)
''')
conn.commit()
c.close()<file_sep>import React, { useState } from "react"
import "./content.css"
function Content ({name, children}) {
const [open, setOpen] = useState(false)
return (
<div className="content-container">
<div onClick={() => setOpen(!open)} className="content-header cursor">
<i className={open? "arrow-down": "arrow-right"}></i>
<h3>{name}</h3>
</div>
{open && <div className="content-children">
{children}
</div>}
</div>
)
}
export default Content<file_sep>import React from "react"
import ReactLoading from "react-loading"
import useDataFetch from "../fetch/useDataFetch"
import GamePageHeader from "./GamePageHeader"
import GameBody from "./GameBody"
import InviteScreen from "./inviteScreen"
function GamePage ({url}) {
const [{data, isLoading, isError}] = useDataFetch(`${url}`)
function checkPermission() {
const player = data.players.map((player) => player.id).filter(player_id => Number(localStorage.getItem("id")) === player_id)
return player === null || player.length === 0
}
if (isLoading) return <ReactLoading className="loading" type="spin"/>
else if (isError) return <div>The game doesn't exist</div>
else if (checkPermission()) return <InviteScreen gamename={data.gamename} id={url}/>
return (
<div id="game-container">
<div id="game-content">
<GamePageHeader image={data.image}/>
<GameBody data={data} url={url} permission={data.owner_id === Number(localStorage.getItem("id"))}/>
</div>
</div>
)
}
export default GamePage<file_sep>import React from "react"
import { useHistory } from "react-router"
import "../../Styles/header.css"
import icon from "../../Assets/logo.png"
function Header () {
const history = useHistory()
return (
<header id="header">
<div id="header-icon">
<img onClick={() => history.push("/")} className="cursor" src={icon} alt="icon"></img>
</div>
<div id="header-content">
</div>
<div id="header-login">
</div>
</header>
)
}
export default Header<file_sep>import React, { useEffect, useState } from "react"
import { Formik, Form, Field } from "formik"
import { useHistory } from "react-router";
import axios from "axios"
import Content from "./Content"
import baseUrl from "../../fetch/url"
import Button from "../../Button"
function GameSelfNotes ({url}) {
const [notes, setNotes] = useState("")
const user_id = localStorage.getItem("id")
const history = useHistory()
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.post(baseUrl + `games/getnotes`, {user_id: user_id, game_id: url})
setNotes(result.data)
}catch(error) {
alert(error)
}
}
fetchData()
})
return (
<Content name="Self-Notes">
<Formik
initialValues={{
text: notes || "",
game_id: url,
user_id: user_id
}}
onSubmit= {async (values) => {
try {
await axios.post(baseUrl + `games/savenotes`, values)
history.go()
}catch(err) {
alert(err)
}
}}
>
<Form>
<p>Only you can see these notes.</p>
<Field as="textarea" name="text" className="text-area"/>
<Button type="submit" classes="button end" text="Save"/>
</Form>
</Formik>
</Content>
)
}
export default GameSelfNotes<file_sep>import sqlite3
from flask import jsonify
class Resource():
def __init__(self):
pass
def add_resource(self, c, request):
try:
game_id, name, value = request['game_id'], request['name'], request['value']
c.execute('INSERT INTO Resources VALUES (NULL, ?, ?, ?, 0)', (game_id, name, value,))
return jsonify(True)
except:
return jsonify("It was not possible to create the resource"), 400
def get_resources(self, c, id):
try:
resources = []
for row in c.execute('SELECT id, name, link FROM Resources WHERE game_id = ? AND erased = 0', (id,)):
resources.append(
{'id': row[0],
'name':row[1],
'link': row[2]
})
return jsonify(resources)
except:
return jsonify('It was not possible to get the resources'), 400
def remove_resource(self, c, request):
try:
id = request['id']
c.execute('UPDATE Resources SET erased = 1 WHERE id = ?', (id,))
return jsonify(True)
except:
return jsonify('An error ocurred upon trying to delete the resource.')<file_sep>import sqlite3
from flask import jsonify
class Npc():
def __init__(self):
pass
def get_npcs(self, c, request):
response = []
counter = 0
game_id = request['game_id']
c.execute('SELECT id, name, image FROM Npcs WHERE game_id = ? AND erased = 0', (game_id,))
npcs = c.fetchall()
for npc in npcs:
print(counter)
response.append({'game_id': game_id,'id': npc[0],'name': npc[1], 'image': npc[2], 'fields': []})
c.execute('SELECT id, name, type FROM SheetFields WHERE game_id = ? AND erased = 0', (game_id,))
fields = c.fetchall()
for field in fields:
c.execute('SELECT value FROM NpcFields WHERE sheet_id = ? AND npc_id = ?', (field[0], npc[0]))
value = c.fetchone()
if value != None:
value = value[0]
else:
value = ""
response[counter]['fields'].append({'sheet_id': field[0],'name': field[1], 'type': field[2], 'value': value})
counter += 1
return jsonify(response)
def save_npc(self, c, request):
id, game_id, name, image, fields = request['id'], request['game_id'], request['name'], request['image'], request['fields']
c.execute('SELECT * FROM Npcs WHERE id = ? AND erased = 0', (id,))
character = c.fetchone()
if character != None:
c.execute('UPDATE Npcs SET name = ?, image = ? WHERE id = ?', (name, image, id, ))
else:
c.execute('INSERT INTO Npcs VALUES(NULL, ?, ?, ?, 0)', (game_id, name, image,))
c.execute('SELECT id FROM Npcs WHERE id = (SELECT MAX(id) FROM Npcs)')
new_id = c.fetchone()
id = new_id[0]
for field in fields:
print(id)
c.execute('UPDATE NpcFields SET erased = 1 WHERE sheet_id = ?', (field['sheet_id'],))
c.execute('INSERT INTO NpcFields VALUES (NULL, ?, ?, ?, 0)', (field['sheet_id'], id, field['value'],))
return jsonify(True)
<file_sep>import React, { useState } from "react"
import { IoMdAddCircle } from "react-icons/io"
import { IconContext } from "react-icons";
import { Link, useHistory } from "react-router-dom"
import { AiFillDelete } from "react-icons/ai"
import axios from "axios";
import Content from "./Content"
import RegisterResources from "./RegisterResources"
import useDataFetch from "../../fetch/useDataFetch"
import baseUrl from "../../fetch/url"
function GameResources ({permission, url}) {
const [{data, isLoading}] = useDataFetch(`games/resources/${url}`)
const [modal, setModal] = useState(false)
const history = useHistory()
async function deleteResource(id) {
await axios.post(baseUrl + "games/removeresource", {id: id})
history.go()
}
if (isLoading) return null
const list = data.map((resource) => {
return(
<div key={"oi"} className="flex-end content-line">
<Link className="big-font bold" to={{ pathname: resource["link"] }} target="_blank">{resource["name"].toUpperCase()}</Link>
{permission?<AiFillDelete onClick={() => deleteResource(resource["id"])} className="cursor"/>: null}
</div>
)
})
return (
<IconContext.Provider value={{ size: "1.5em"}}>
<Content name="Resources">
{list.length === 0? <p>No resources have been added.</p>: list}
{permission?
<IconContext.Provider value={{ size: "2em"}}>
<div onClick={() => setModal(true)} className="add-button cursor">
<IoMdAddCircle/>
</div>
</IconContext.Provider>:
null}
</Content>
{modal? <RegisterResources url={url} close={() => setModal(false)}/>: null}
</IconContext.Provider>
)
}
export default GameResources<file_sep>import React from "react"
import { Redirect } from "react-router-dom"
function UserLogin () {
const session = localStorage.getItem("id")
return (
<div>
{!session && <Redirect to="/login"/>}
</div>
)
}
export default UserLogin<file_sep>import React from "react"
import { IoMdAddCircle } from "react-icons/io"
import { IconContext } from "react-icons";
function CreateGame ({ func }) {
return (
<IconContext.Provider value={{ size: "2.5em"}}>
<div onClick={() => func()} className="game-container center cursor">
<div id="create-game-button">
<IoMdAddCircle/>
<h3>Create new game</h3>
</div>
</div>
</IconContext.Provider>
)
}
export default CreateGame<file_sep>import React from "react"
import { Formik, Form, Field } from "formik";
import axios from "axios"
import { useHistory } from "react-router";
import Modal from "../../modals/Modal";
import baseUrl from "../../fetch/url";
import "../../../Styles/form.css"
function RegisterResources ({close, url}) {
const history = useHistory()
function validateName (value) {
let error
if (!value)
error = "Required"
else if (value.length > 30)
error = "Name must be shorter than 30 characters"
return error
}
function validateValue (value) {
let error
// eslint-disable-next-line
var regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/
if (!value)
error = "Required"
else if (!regex.exec(value))
error = "Invalid URL"
return error
}
return (
<Formik
initialValues={{
game_id: url,
name: "",
value: ""
}}
onSubmit= {async (values) => {
try {
await axios.post(baseUrl + "games/addresource", values)
history.go()
}catch(err) {
alert(err)
}
}}>
{({ errors, touched }) => (
<Form className="container">
<Modal close={() => close()} title="Add resource" className="resource-modal">
<div className="form-line">
<label htmlFor="name">Name</label>
<Field name="name" validate={validateName}/>
</div>
{errors.name && touched.name ? <div className="exception exception-modal">{errors.name}</div>: null}
<div className="form-line">
<label htmlFor="value">URL</label>
<Field name="value" validate={validateValue}/>
</div>
{errors.value && touched.value ? <div className="exception exception-modal">{errors.value}</div>: null}
</Modal>
</Form>
)}
</Formik>
)
}
export default RegisterResources<file_sep>import sqlite3
from flask import jsonify
class Note():
def __init__(self):
pass
def get_notes(self, c, request):
try:
game_id, user_id = request['game_id'], request['user_id']
c.execute('SELECT text FROM Notes WHERE game_id = ? AND user_id = ?', (game_id, user_id,))
notes = c.fetchone()
return jsonify(notes[0])
except:
return jsonify("")
def save_notes(self, c, request):
try:
game_id, user_id, text = request['game_id'], request['user_id'], request['text']
c.execute('SELECT * FROM Notes WHERE game_id = ? AND user_id = ?', (game_id, user_id,))
if c.fetchone():
c.execute('UPDATE Notes SET text = ? WHERE game_id = ? AND user_id = ?', (text, game_id, user_id,))
else:
c.execute('INSERT INTO Notes VALUES (NULL, ?, ?, ?, 0)', (game_id, user_id, text,))
return jsonify(True)
except:
return jsonify("It was not possible to save the notes"), 400<file_sep>import React from "react"
import Header from "../Components/header"
import GamePage from "../Components/gamePage"
import "../Styles/game.css"
function Game({match}) {
return(
<>
<Header/>
<GamePage url={match.params.gameid}/>
</>
)
}
export default Game<file_sep>import React, { useState } from "react"
import ReactLoading from "react-loading"
import useDataFetch from "../fetch/useDataFetch"
import CreateGame from "./CreateGame"
import RegisterGame from "./RegisterGame"
import GameCard from "./GameCard"
function GameList () {
const id = Number(localStorage.getItem("id"))
const [modal, setModal] = useState(false)
const [{data, isLoading}] = useDataFetch(`games/${id}`)
if (isLoading) return <ReactLoading className="loading" type="spin"/>
const userGames = data.map((game) => {
return (
<GameCard
key={game.id}
id={game.id}
name={game.gamename}
genre={game.genre}
description={game.description}
owner={game.owner_id === id? true: false}
image={game.image}/>
)
})
return (
<div id="home-container">
<div className="game-list">
<h1>Your Games</h1>
<CreateGame func={() => setModal(true)}/>
{userGames}
</div>
{modal && <RegisterGame close={() => setModal(false)}/>}
</div>
)
}
export default GameList<file_sep>import sqlite3
from flask import Flask, request, g
from flask_cors import CORS
from controller.usercontroller import User
from controller.resourcecontroller import Resource
from controller.notecontroller import Note
from controller.sheetcontroller import Sheet
from controller.charactercontroller import Character
from controller.npccontroller import Npc
from controller.gamecontroller import Game
app = Flask(__name__)
CORS(app)
DATABASE = 'database/RPGHub.db'
user = User()
game = Game()
resource = Resource()
note = Note()
sheet = Sheet()
character = Character()
npc = Npc()
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
#TABLE - USERS
@app.route('/register', methods=['POST'])
def create_user():
c = get_db().cursor()
response = user.create_user(c, request.json)
get_db().commit()
return response
@app.route('/usernames', methods=['POST'])
def get_users():
c = get_db().cursor()
response = user.get_usernames(c, request.json)
return response
@app.route('/login', methods=['POST'])
def login():
c = get_db().cursor()
return user.login(c, request.json)
#TABLE - RESOURCES
@app.route('/games/addresource', methods=['POST'])
def add_resource():
c = get_db().cursor()
response = resource.add_resource(c, request.json)
get_db().commit()
return response
@app.route('/games/resources/<game_id>', methods=['GET'])
def get_resources(game_id):
c = get_db().cursor()
return resource.get_resources(c, game_id)
@app.route('/games/removeresource', methods=['POST'])
def remove_resource():
c = get_db().cursor()
response = resource.remove_resource(c, request.json)
get_db().commit()
return response
#TABLE - NOTES
@app.route('/games/getnotes', methods=['POST'])
def get_notes():
c = get_db().cursor()
response = note.get_notes(c, request.json)
get_db().commit()
return response
@app.route('/games/savenotes', methods=['POST'])
def save_notes():
c = get_db().cursor()
response = note.save_notes(c, request.json)
get_db().commit()
return response
#TABLE - SHEETS
@app.route('/games/sheet/<game_id>', methods=['GET'])
def get_sheet(game_id):
c = get_db().cursor()
return sheet.get_sheet(c, game_id)
@app.route('/games/savesheet', methods=['POST'])
def save_sheet():
c = get_db().cursor()
response = sheet.save_sheet(c, request.json)
get_db().commit()
return response
#TABLE - CHARACTERS
@app.route('/games/getcharacter', methods=['POST'])
def get_character():
c = get_db().cursor()
response = character.get_character(c, request.json)
get_db().commit()
return response
@app.route('/games/savecharacter', methods=['POST'])
def save_character():
c = get_db().cursor()
response = character.save_character(c, request.json)
get_db().commit()
return response
#TABLE - NPCS
@app.route('/games/getnpcs', methods=['POST'])
def get_npcs():
c = get_db().cursor()
response = npc.get_npcs(c, request.json)
get_db().commit()
return response
@app.route('/games/savenpc', methods=['POST'])
def save_npc():
c = get_db().cursor()
response = npc.save_npc(c, request.json)
get_db().commit()
return response
#TABLE - GAMES
@app.route('/games/adduser', methods=['POST'])
def add_user():
c = get_db().cursor()
response = game.add_user(c, request.json)
get_db().commit()
return response
@app.route('/games/create', methods=['POST'])
def create_game():
c = get_db().cursor()
response = game.create_game(c, request.json)
get_db().commit()
return response
@app.route('/<game_id>', methods=['GET'])
def game_info(game_id):
c = get_db().cursor()
return game.game_info(c, game_id)
@app.route('/games/<user_id>', methods=['GET'])
def user_games(user_id):
c = get_db().cursor()
return game.user_games(c, user_id)<file_sep>import sqlite3
from flask import jsonify
class Character():
def __init__(self):
pass
def get_character(self, c, request):
response = {"fields": []}
id = ""
game_id, user_id = request['game_id'], request['user_id']
c.execute('SELECT name, image FROM Characters WHERE game_id = ? AND user_id = ? AND erased = 0', (game_id, user_id,))
character = c.fetchone()
if character:
response["name"], response["image"] = character[0], character[1]
else:
response["name"], response["image"] = "", ""
c.execute('SELECT id, name, type FROM SheetFields WHERE game_id = ? AND erased = 0', (game_id,))
fields = c.fetchall()
for field in fields:
id = field[0]
c.execute('SELECT value FROM CharacterFields WHERE sheet_id = ? AND user_id = ?', (field[0], user_id))
value = c.fetchone()
if value != None:
value = value[0]
else:
value = ""
response['fields'].append({'sheet_id': field[0],'name': field[1], 'type': field[2], 'value': value})
return jsonify(response)
def save_character(self, c, request):
try:
game_id, user_id, name, image, fields = request['game_id'], request['user_id'], request['name'], request['image'], request['fields']
c.execute('SELECT * FROM Characters WHERE game_id = ? AND user_id = ? AND erased = 0', (game_id, user_id,))
character = c.fetchone()
if character != None:
c.execute('UPDATE Characters SET name = ?, image = ? WHERE game_id = ? AND user_id = ?', (name, image, game_id, user_id,))
else:
c.execute('INSERT INTO Characters VALUES(NULL, ?, ?, ?, ?, 0)', (game_id, user_id, name, image,))
for field in fields:
c.execute('UPDATE CharacterFields SET erased = 1 WHERE sheet_id = ?', (field['sheet_id'],))
c.execute('INSERT INTO CharacterFields VALUES (NULL, ?, ?, ?, 0)', (field['sheet_id'], user_id, field['value'],))
return jsonify(True)
except:
return jsonify("It was not possible to save the notes"), 400<file_sep>import React, { useState } from "react"
import { useHistory } from "react-router-dom"
import Fadein from "react-fade-in"
import { Formik, Form, Field } from "formik";
import axios from "axios"
import baseUrl from "../fetch/url"
import Button from "../Button"
import icon from "../../Assets/logo.png"
function Session () {
const history = useHistory()
//Flag to change between Login/Register. true means login and false means register
const [login, setLogin] = useState(true)
function validateUserName (value) {
let error
if (!value) {
error = "Required"
} else if (value.length < 5) {
error = "Must be 5 characters or more"
}
return error
}
function validatePassword (value) {
let error
if (!value) {
error = "Required"
} else if (value.length < 5) {
error = "Must be 5 characters or more"
}
return error
}
return (
<Fadein>
<Formik
initialValues={{username: "", password: ""}}
onSubmit= {async (values) => {
try {
const response = login? await axios.post(baseUrl + "login", values): await axios.post(baseUrl + "register", values)
localStorage.setItem("id", response.data)
history.push("/")
}catch(err) {
alert(err)
}
}}
>
{({ errors, touched }) => (
<Form id="login-container">
<img src={icon} alt="icon"></img>
<Field name="username" placeholder="Username" validate={validateUserName}/>
{errors.username && touched.username ? <div className="exception exception-login">{errors.username}</div>: null}
<Field type="password" name="password" placeholder="<PASSWORD>" validate={validatePassword}/>
{errors.password && touched.password ? <div className="exception exception-login">{errors.password}</div>: null}
<Button id="login-button" classes="button" text={login? "Login": "Register"}/>
<p className="cursor" onClick={() => setLogin(!login)}>{login? "Don't have an account?" : "Already have an account?"}</p>
</Form>
)}
</Formik>
</Fadein>
)
}
export default Session<file_sep>import React from "react"
import Fadein from "react-fade-in"
import Button from "../Button"
import "./modal.css"
function Confirmation ({title, close, text, func, className}) {
return (
<div className="container">
<Fadein className={`confirmation ${className}`}>
<header id="confirmation-header">
<h1>{title}</h1>
<p onClick={() => close()} className="cursor">X</p>
</header>
<div id="modal-children">
<p>{text}</p>
</div>
<footer id="confirmation-footer">
<Button type="button" func={() => close()} classes="button" text="Cancel"/>
<Button type="button" func={() => func()} classes="button" text="Confirm"/>
</footer>
</Fadein>
</div>
)
}
export default Confirmation<file_sep>import React from "react"
import { Formik, Form, Field, FieldArray } from "formik";
import { useHistory } from "react-router";
import { AiFillDelete } from "react-icons/ai"
import { IconContext } from "react-icons";
import axios from "axios"
import Modal from "../../modals/Modal";
import baseUrl from "../../fetch/url";
import "../../../Styles/form.css"
import Button from "../../Button";
import useDataFetch from "../../fetch/useDataFetch";
function RegisterSheet ({close, url}) {
const history = useHistory()
const [{data, isLoading}] = useDataFetch(`games/sheet/${url}`)
if (isLoading) return null
return (
<Formik
initialValues={{
game_id: url,
fields: data
}}
onSubmit= {async (values) => {
try {
await axios.post(baseUrl + "games/savesheet", values)
history.go()
}catch(err) {
alert(err)
}
}}>
{({ values, errors, touched }) => (
<Form className="container">
<Modal close={() => close()} title="Edit Sheet" className="resource-modal">
<FieldArray name="fields">
{({ insert, remove, push }) => (
<IconContext.Provider value={{ size: "2em"}}>
{values.fields.length > 0 && values.fields.map((field, index) => (
<div key={index} className="form-line">
<label htmlFor={`fields.${index}.name`}>Field</label>
<Field style={{width: "60%", margin: "10px"}} name={`fields.${index}.name`}/>
<label htmlFor={`fields.${index}.type`}>Type</label>
<Field style={{width: "20%", margin: "10px"}} name={`fields.${index}.type`} as="select">
<option value="input">Text</option>
<option value="textarea">Textarea</option>
</Field>
<AiFillDelete style={{alignSelf: "center"}} className="cursor" onClick={() => remove(index)}/>
</div>
))}
<Button
type="button"
classes="button margin"
text="Add field"
func={() => push({ name: "", type: "input"})}
/>
</IconContext.Provider>
)}
</FieldArray>
</Modal>
</Form>
)}
</Formik>
)
}
export default RegisterSheet<file_sep>import sqlite3
from flask import jsonify
import json
class User():
def __init__(self):
pass
def create_user(self, c, request):
try:
username, password = request['username'], request['password']
c.execute('INSERT INTO Users VALUES (NULL, ?, ?, 0)', (username, password))
c.execute('SELECT id FROM Users WHERE username = ?', (username,))
select = c.fetchone()
response = select[0]
return jsonify(response)
except:
return jsonify("Username already taken"), 400
def get_usernames(self, c, request):
try:
users = []
for id in request['ids']:
c.execute('SELECT username FROM Users WHERE id = ?', (id,))
select = c.fetchone()
users.append(select[0])
return jsonify(users)
except:
return jsonify("There is an id that doesn't exist in the array"), 400
def login(self, c, request):
try:
username = request['username']
password = request['<PASSWORD>']
c.execute('SELECT id FROM Users WHERE username = ? AND password = ? AND erased = 0', (username, password))
select = c.fetchone()
response = select[0]
return jsonify(response)
except:
return jsonify("Username and/or password are incorrect"), 400
<file_sep>import React from "react"
import { BrowserRouter, Switch, Route } from "react-router-dom"
import Home from "./Pages/Home"
import Login from "./Pages/Login"
import Game from "./Pages/Game"
function Routes() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/game/:gameid" component={Game}/>
</Switch>
</BrowserRouter>
)
}
export default Routes | b90f200efab74c867af8e0d79758e3f3ad3572a7 | [
"JavaScript",
"Python"
] | 27 | JavaScript | felipecapistrano/RPGHub | ad869ab1a92cb1157424c66f61e8d34d6e794657 | 48eb70550bc72e3392176cc7567c2ce736152bc3 |
refs/heads/master | <repo_name>SamiMurtaza/Fractals-in-Nature<file_sep>/code.py
from turtle import Turtle, tracer
from time import clock
class Stack:
def __init__(self):
self.stuff = []
def isEmpty(self):
return bool(self.stuff)
def push(self, item):
self.stuff.append(item)
def pop(self):
return self.stuff.pop()
def getExpr(axiom, iterations, rules): #generates the expression
start = axiom
for i in range(iterations-1):
for j in rules:
start = start.replace(j ,rules[j])
return start
def draw(axiom, angle, iterations, rules, d=8): #gets the expression and draws it
stack = Stack()
turtle = Turtle()
turtle.seth(90)
turtle.penup()
turtle.setposition(0,-350)
turtle.pendown()
turtle.speed(0)
tracer(500,500) #change this to alter speed, currently set to not too fast, not too slow
turtle.pensize(2)
for i in getExpr(axiom, iterations, rules):
if i == "F":
turtle.fd(d)
if i == "-":
turtle.rt(angle)
if i == "+":
turtle.lt(angle)
if i == "[":
stack.push((turtle.pos(), turtle.heading()))
if i == "]":
turtle.penup()
popped = stack.pop()
turtle.setpos(popped[0])
turtle.setheading(popped[1])
turtle.pendown()
def q0():
draw("F", 25.7, 5, {"F":"F[+F]F[-F]F"})
def q1():
draw("F", 20, 6, {"F":"F[+F]F[-F][F]"},12)
def q2():
draw("F", 22.5, 5, {"F":"FF-[-F+F+F] + [+F-F-F]"}, 12)
def q3():
draw("X", 20, 7, {"F":"FF", "X":"F[+X]F[-X]+X"}, 6)
def q4():
draw("X", 25.7, 7, {"F":"FF", "X":"F[+X][-X]FX"}, 6)
def q5():
draw("X", 22.5, 5, {"F":"FF", "X":"F-[[X]+X]+F[+FX]-X"}, 15)
| 2f765aa8dc110b84c07dd6eb39a1c77d928fda45 | [
"Python"
] | 1 | Python | SamiMurtaza/Fractals-in-Nature | 355f51fcad68e0d20a0f8223e35d4f5733a4285a | 8a4e1328593b1f73bb23edf97851b5879a546ceb |
refs/heads/master | <repo_name>rainbow911/CHHook<file_sep>/Demo/PrintTest.swift
//
// PrintTest.swift
// Demo
//
// Created by shenzhen-dd01 on 2019/6/17.
// Copyright © 2019 rainbow. All rights reserved.
//
import UIKit
class PrintTest: NSObject {
@objc class func printSomething() {
print("this is swift print!")
}
}
<file_sep>/README.md
# CHHook
## 说明
* 实现无入侵式的调试项目,有以下两个功能:
* 打印当前视图控制器的名称
* 打印App进行的网络请求(参考了[Hook_NSURLSession](https://github.com/yangqian111/PPSAnalytics/tree/master/Hook_NSURLSession),进行了优化,实现打印请求参数!)
* 技术点:
* load 方法,自动执行
* runtime methodSwizzle
* 使用场景:
* 当我们手上有一个新的项目的使用,我们在运行的项目的时候,可以随时打印当前项目进入到了哪个视图控制器,而不需要点击 Xcode 上的按钮来进行查看。相比起来更方便更快捷。
* 另外就是项目如果有网络请求,也是可以随时打印当前视图控制器进行的网络请求的参数。
## 安装
使用CocoaPods集成到项目中,在`Podfile`文件中添加:
```ruby
target '<Your Target Name>' do
//根据需要选择需要添加的字库
pod 'CHHook/Print' //hook打印,目前还有点问题
pod 'CHHook/URLSession' //hook网络请求
pod 'CHHook/UIViewController' //hook控制器,打印当前的控制器
end
```
然后运行下面的命令:
```bash
$ pod install
```
### URLSession Hook 日志打印说明
* 默认是不打印的,如果需要打印日志需要使用`NSUserDefaults`写入`Bool`控制参数`CH_URLSession_Hook`,并设置成`YES`
Swift:
```Swift
#if DEBUG
UserDefaults.standard.set(true, forKey: "CH_URLSession_Hook")
UserDefaults.standard.synchronize()
#endif
```
Objective-C:
```Objective-C
#ifdef DEBUG
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"CH_URLSession_Hook"];
[[NSUserDefaults standardUserDefaults] synchronize];
#endif
```
## 版本说明:
* 如果是单独使用请使用版本`0.0.3`,Podfile中设置`pod 'CHHook', '0.0.3'`;
* 如果是配合 CHLog 使用,请使用版本`0.0.4`,此版本为特殊版本,去掉了 NSLog。<file_sep>/CHHook.podspec
#
# Be sure to run `pod lib lint CHHook.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'CHHook'
s.version = '0.0.7'
s.summary = 'CHHook is Debug Tool'
s.description = <<-DESC
0.0.7:URLSession Hook增加日志打印控制参数,优化日志打印效果
0.0.6:增加httpCode返回,子库化
0.0.5:增加Hook NSLog方法,但是Swift Print Hook 无效
0.0.4:去掉日志打印,方便和CHLog配合使用
0.0.3:设置请求成功后打印后台返回的Header信息
0.0.2:增加多种解析,避免获取不到请求参数
0.0.1:初始版本
CHHook is Debug Tool, let you quick enter project
DESC
s.homepage = 'ttps://github.com/rainbow911'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.source = { :git => 'https://github.com/rainbow911/CHHook.git', :tag => s.version.to_s}
# OC库,无需制定swift版本
s.ios.deployment_target = '9.0'
s.subspec 'Print' do |ss|
ss.source_files = 'CHHook/Print/*'
end
s.subspec 'URLSession' do |ss|
ss.source_files = 'CHHook/URLSession/*'
end
s.subspec 'UIViewController' do |ss|
ss.source_files = 'CHHook/UIViewController/*'
end
end
| 0402a2406d29ef76af176558e60c654f15c4a9f2 | [
"Swift",
"Ruby",
"Markdown"
] | 3 | Swift | rainbow911/CHHook | 7c907d29e9bacb53f5451b8e9efc9a23455b774f | 89fae4707a1137d46ee8c3d4e98e5891dc285862 |
refs/heads/master | <repo_name>LoyaniX/long-map<file_sep>/src/main/java/de/comparus/opensource/longmap/impl/LongMapImpl.java
package de.comparus.opensource.longmap.impl;
import de.comparus.opensource.longmap.LongMap;
import de.comparus.opensource.longmap.models.Entry;
import java.lang.reflect.Array;
import java.util.Arrays;
public class LongMapImpl<V> implements LongMap<V>
{
private int size = 0;
private final int DEFAULT_MAP_SIZE = 16;
private float LOAD_FACTOR = 0.75f;
private int sizeToDouble;
private Entry[] entryTable;
public LongMapImpl()
{
entryTable = new Entry[DEFAULT_MAP_SIZE];
sizeToDouble = (int) (DEFAULT_MAP_SIZE * LOAD_FACTOR);
}
public LongMapImpl(int mapSize)
{
entryTable = new Entry[mapSize];
sizeToDouble = (int) (mapSize * LOAD_FACTOR);
}
public V put(long key, V value)
{
int keyHash = getHash(key);
Entry<V> entry = new Entry<>(keyHash, key, value);
int index = getIndex(entry);
if (entryTable[index] == null)
{
entryTable[index] = entry;
}
else
{
Entry previousEntry = entryTable[index];
if (previousEntry.getKey() == entry.getKey())
{
previousEntry.setValue(entry.getValue());
return (V) previousEntry.getValue();
}
else
{
entryTable[index] = new Entry(keyHash, key, value, previousEntry);
}
}
size ++;
if(size == sizeToDouble) changeMapSize();
return entry.getValue();
}
public V get(long key) {
for (Entry entry : entryTable)
{
if(entry != null)
{
if(entry.getKey() == key) return (V) entry.getValue();
while (entry.getNextEntry() != null)
{
entry = entry.getNextEntry();
if(entry.getKey() == key) return (V) entry.getValue();
}
}
}
return null;
}
public V remove(long key)
{
if (!containsKey(key)) return null;
V removalValue = null;
for (int i = 0; i < entryTable.length; i++)
{
if (entryTable[i] != null && (entryTable[i].getKey() == key))
{
removalValue = (V) entryTable[i].getValue();
entryTable[i] = null;
size--;
}
}
return removalValue;
}
public boolean isEmpty() {
return size == 0;
}
public boolean containsKey(long key) {
return Arrays.stream(keys()).
anyMatch(findKey -> findKey == key);
}
public boolean containsValue(V value) {
return Arrays.stream(values()).
anyMatch(findValue -> findValue == value);
}
public long[] keys() {
long[] keys = new long[size];
int index = 0;
for (Entry entry : entryTable)
{
if (entry != null)
{
keys[index] = entry.getKey();
index++;
}
}
return keys;
}
public V[] values() {
V[] values = (V[]) new Object[size];
int index = 0;
for (Entry entry : entryTable)
{
if (entry != null)
{
values[index] = (V) entry.getValue();
index++;
}
}
V[] result = (V[]) Array.newInstance(values[0].getClass(), size);
System.arraycopy(values, 0, result, 0, size);
return result;
}
public long size()
{
return size;
}
public void clear()
{
int oldLength = entryTable.length;
entryTable = new Entry[oldLength];
size = 0;
}
private void changeMapSize()
{
Entry[] entries = new Entry[entryTable.length * 2];
size = 0;
for (Entry entry : entryTable)
{
if (entry == null) continue;
int index = getIndex(entry);
entries[index] = entry;
size++;
}
entryTable = entries;
sizeToDouble = (int) (entryTable.length * LOAD_FACTOR);
}
private int getIndex(Entry<V> entry)
{
return entry.getHashValue() % (entryTable.length - 1);
}
private int getHash(long key)
{
return (int)(key ^ (key >>> 32));
}
}
<file_sep>/src/test/java/de/comparus/opensource/longmap/LongMapTest.java
/*
* This module is part of the CSF experimental system
* Copyright (c) Soft Computer Consultants, Inc.
* All Rights Reserved
* This document contains unpublished, confidential and proprietary
* information of Soft Computer Consultants, Inc. No disclosure or use of
* any portion of the contents of these materials may be made without the
* express written consent of Soft Computer Consultants, Inc.
*/
package de.comparus.opensource.longmap;
import de.comparus.opensource.longmap.impl.LongMapImpl;
import org.junit.Assert;
import org.junit.Test;
public class LongMapTest
{
@Test
public void putMapElementTest()
{
//Given
String expectValue = "Test String";
LongMap<String> testMap = new LongMapImpl<>();
String actualValue = testMap.put(3L, expectValue);
//When
long actualSize = testMap.size();
//Than
Assert.assertEquals(1, actualSize);
Assert.assertEquals(expectValue, actualValue);
}
@Test
public void replaceExistsMapElementTest()
{
//Given
String expectValue = "Test String";
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(3L, expectValue);
String actualValue = testMap.get(3L);
Assert.assertEquals(expectValue, actualValue);
//When
testMap.put(3L, "New value");
long actualSize = testMap.size();
actualValue = testMap.get(3L);
//Than
Assert.assertEquals(1, actualSize);
Assert.assertNotEquals(expectValue, actualValue);
Assert.assertEquals("New value", actualValue);
}
@Test
public void put1000MapElementsTest()
{
//Given
String expectValue = "Test String";
LongMap<String> testMap = new LongMapImpl<>();
for (long i = 0L; i < 1000L; i++)
{
testMap.put(i, expectValue);
}
//When
long actualSize = testMap.size();
boolean isValueEqual = testMap.containsValue(expectValue);
//Than
Assert.assertEquals(1000, actualSize);
Assert.assertTrue(isValueEqual);
}
@Test
public void getMapElementTest()
{
//Given
String expectValue = "TEST STRING3";
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(0L, "TEST STRING1");
testMap.put(1L, "TEST STRING2");
testMap.put(2L, "TEST STRING3");
testMap.put(3L, "TEST STRING4");
testMap.put(10L, "TEST STRING1");
testMap.put(11L, "TEST STRING2");
testMap.put(12L, "TEST STRING3");
testMap.put(13L, "TEST STRING4");
testMap.put(20L, "TEST STRING1");
testMap.put(21L, "TEST STRING2");
testMap.put(22L, "TEST STRING3");
testMap.put(23L, "TEST STRING4");
testMap.put(30L, "TEST STRING1");
testMap.put(31L, "TEST STRING2");
testMap.put(32L, "TEST STRING3");
testMap.put(33L, "TEST STRING4");
//When
String actualValue = testMap.get(2L);
//Than
Assert.assertEquals(expectValue, actualValue);
}
@Test
public void getFromEmptyMapTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
//When
long actualSize = testMap.size();
String actualValue = testMap.get(-1L);
//Than
Assert.assertEquals(0, actualSize);
Assert.assertNull(actualValue);
}
@Test
public void putAndGetElementsWithNotPositiveKeys()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(-3L, "Test String-3");
testMap.put(0L, "Test String0");
testMap.put(-321L, "Test String-321");
testMap.put(-1L, "Test String-1");
//When
long actualSize = testMap.size();
String actualValue1 = testMap.get(-3L);
String actualValue2 = testMap.get(0L);
String actualValue3 = testMap.get(-321L);
String actualValue4 = testMap.get(-1L);
//Than
Assert.assertEquals("Test String-3", actualValue1);
Assert.assertEquals("Test String0", actualValue2);
Assert.assertEquals("Test String-321", actualValue3);
Assert.assertEquals("Test String-1", actualValue4);
Assert.assertEquals(4, actualSize);
}
@Test
public void removeTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(0L, "TEST STRING1");
testMap.put(1L, "TEST STRING2");
testMap.put(2L, "TEST STRING3");
testMap.put(3L, "TEST STRING4");
//When
testMap.remove(2L);
boolean isKeyContains = testMap.containsKey(2L);
//Than
Assert.assertFalse(isKeyContains);
}
@Test
public void isEmptyWithNotEmptyMapTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(0L, "TEST STRING1");
testMap.put(1L, "TEST STRING2");
testMap.put(2L, "TEST STRING3");
testMap.put(3L, "TEST STRING4");
//When
boolean isEmpty = testMap.isEmpty();
//Than
Assert.assertFalse(isEmpty);
}
@Test
public void isEmptyWithEmptyMapTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
//When
boolean isEmpty = testMap.isEmpty();
//Than
Assert.assertTrue(isEmpty);
}
@Test
public void containsKeyTest()
{
//Given
String expectValue = "Test String";
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(3L, expectValue);
//When
long actualSize = testMap.size();
boolean isKeyExist = testMap.containsKey(3L);
//Than
Assert.assertEquals(1, actualSize);
Assert.assertTrue(isKeyExist);
}
@Test
public void containsValueTest()
{
//Given
String expectValue = "Test String";
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(3L, expectValue);
//When
long actualSize = testMap.size();
boolean isValueExist = testMap.containsValue("Test String");
//Than
Assert.assertEquals(1, actualSize);
Assert.assertTrue(isValueExist);
}
@Test
public void getAllKeysTest()
{
//Given
LongMap<Long> testMap = new LongMapImpl<>();
long[] expectedKeys = {1L, 2L, 3L, 5L, 6L};
for (long key : expectedKeys)
{
testMap.put(key, key);
}
//When
long actualSize = testMap.size();
long[] actualKeys = testMap.keys();
//Than
Assert.assertEquals(5, actualSize);
Assert.assertArrayEquals(expectedKeys, actualKeys);
}
@Test
public void getAllValuesTest()
{
//Given
LongMap<Long> testMap = new LongMapImpl<>();
Long[] expectedValue = {1L, 2L, 3L, 5L, 6L};
for (long key : expectedValue)
{
testMap.put(key, key);
}
//When
long actualSize = testMap.size();
Long[] actualValue = testMap.values();
//Than
Assert.assertEquals(5, actualSize);
Assert.assertArrayEquals(expectedValue, actualValue);
}
@Test
public void emptyMapSizeTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
//When
long size = testMap.size();
//Than
Assert.assertEquals(0L, size);
}
@Test
public void NotEmptryMapSizeTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(0L, "TEST STRING1");
testMap.put(1L, "TEST STRING2");
testMap.put(2L, "TEST STRING3");
testMap.put(3L, "TEST STRING4");
//When
long size = testMap.size();
//Than
Assert.assertEquals(4L, size);
}
@Test
public void clearTest()
{
//Given
LongMap<String> testMap = new LongMapImpl<>();
testMap.put(0L, "TEST STRING1");
testMap.put(1L, "TEST STRING2");
testMap.put(2L, "TEST STRING3");
testMap.put(3L, "TEST STRING4");
long size = testMap.size();
Assert.assertEquals(4, size);
//When
testMap.clear();
//Than
size = testMap.size();
Assert.assertEquals(0, size);
}
}
| 3cb6046fac047655d76ccfdc785374ca61e4f7c3 | [
"Java"
] | 2 | Java | LoyaniX/long-map | c753da6f5557bd042a45a992c40e7009736c1db9 | 680f4389a74fd0e7779ae223833683d70164a92f |
refs/heads/master | <repo_name>azaleas/camper-leaderboard<file_sep>/src/App.js
import React, { Component } from 'react';
import './App.css';
import api from './api';
import { Table } from 'react-bootstrap';
/*
Dummy data
const dataJSON = [
{
username: "alan",
recent: 100,
alltime: 1000,
},
{
username: "aan",
recent: 10,
alltime: 100,
},
{
username: "aln",
recent: 1012,
alltime: 11000,
},
{
username: "qwe",
recent: 40,
alltime: 1000,
},
{
username: "rew",
recent: 5,
alltime: 12000,
}
];
*/
const Loader = () => {
return(
<div className="loaderWrapper">
<div className="outerCircle"></div>
<div className="innerCircle"></div>
</div>
)
}
const LeaderboardTable = (props) =>{
return(
<div className="tableWrapper">
<Table striped bordered condensed hover>
<thead>
<tr>
<th
className="clickable"
onClick={props.sortElement}
name="id"
>
# {props.arrows.arrowID}
</th>
<th>Username</th>
<th
className="clickable"
onClick={props.sortElement}
name="recentPoints"
>
Recent Points {props.arrows.arrowRecent}
</th>
<th
className="clickable"
onClick={props.sortElement}
name="totalPoints"
>
All time Points {props.arrows.arrowTotal}
</th>
</tr>
</thead>
<tbody>
{
(
props.data.map((el, index) => {
return(
<tr
key={el.id}
>
<td>
{el.id}
</td>
<td>
{el.username}
</td>
<td>
{el.recent}
</td>
<td>
{el.alltime}
</td>
</tr>
)
})
)
}
</tbody>
</Table>
</div>
);
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: "",
allData: "",
arrows: "",
isLoaded: false,
};
}
componentDidMount(){
this.getDataRecent();
}
getDataRecent = () => {
api
.fetchRecent()
.then((dataJSON) => {
this.setDataWithId(dataJSON);
});
/*
Test with dummy data
let data = dataJSON.map((el, index) => {
let newEl = Object.assign({}, el, {id: index + 1});
return newEl;
});
this.setState({
isLoaded: true,
data,
arrows: {
arrowID: "↑",
arrowRecent: "↑",
arrowTotal: "↑",
}
})
*/
}
getDataTotal = () => {
api
.fetchAlltime()
.then((dataJSON) => {
this.setDataWithId(dataJSON);
});
/*
Test with dummy data
let data = dataJSON.map((el, index) => {
let newEl = Object.assign({}, el, {id: index + 1});
return newEl;
});
this.setState({
isLoaded: true,
data,
arrows: {
arrowID: "↑",
arrowRecent: "↑",
arrowTotal: "↑",
}
})
*/
}
setDataWithId = (dataJSON) => {
let data = dataJSON.map((el, index) => {
let newEl = Object.assign({}, el, {id: index + 1});
return newEl;
});
this.setState({
isLoaded: true,
data,
allData: data,
arrows: {
arrowID: "↑",
arrowRecent: "↑",
arrowTotal: "↑",
}
})
}
sortElement = (event) =>{
let eventOwner = event.target.getAttribute('name');
if(eventOwner === "id"){
this.sortDataByArrow(eventOwner, "id");
}
else if(eventOwner === "recentPoints"){
this.sortDataByArrow(eventOwner, "recent");
}
else if(eventOwner === "totalPoints"){
this.sortDataByArrow(eventOwner, "alltime");
}
}
sortDataByArrow = (eventOwner, objectKey) => {
if(this.state.arrows.arrowRecent === "↑"){
let dataSorted = this.state.data.sort((a, b) => {
return b[objectKey] - a[objectKey];
});
let state = Object.assign(this.state, {
data: Object.assign(this.state.data, {dataSorted}),
arrows: Object.assign(this.state.arrows, {arrowRecent: "↓"})
});
this.setState({state});
}
else if(this.state.arrows.arrowRecent === "↓"){
let dataSorted = this.state.data.sort((a, b) => {
return a[objectKey] - b[objectKey];
});
let state = Object.assign(this.state, {
data: Object.assign(this.state.data, {dataSorted}),
arrows: Object.assign(this.state.arrows, {arrowRecent: "↑"})
});
this.setState({state});
}
}
getDataButton = (event) => {
let eventOwner = event.target.getAttribute('name');
if(eventOwner === "recent"){
this.getDataRecent();
}
else{
this.getDataTotal();
}
}
liveSearch = (event) => {
let searchValue = event.target.value;
let searchregexp = new RegExp(searchValue);
let searchResults = this.state.allData.filter((element, index) => {
return searchregexp.test(element.username);
});
if(searchResults.length === 0){
let searchResults = this.state.allData;
let state = Object.assign(this.state, {
data: searchResults,
});
this.setState({state});
}
else{
let state = Object.assign(this.state, {
data: searchResults,
});
this.setState({state});
}
}
render() {
return (
<div className="App container">
<h3 className="bg-primary title">FCC Camper Leaderboard</h3>
{
this.state.isLoaded
? (
<div>
<div className="controlBoard">
<button onClick={this.getDataButton} name="recent" className="btn btn-primary">Recent</button>
<button onClick={this.getDataButton} name="total" className="btn btn-success">Total</button>
<input type="text" placeholder="Live Username Search..." onChange={this.liveSearch}/>
</div>
<LeaderboardTable
data={this.state.data}
sortElement={this.sortElement}
arrows={this.state.arrows}
/>
</div>
)
: (
<Loader/>
)
}
</div>
);
}
}
export default App;<file_sep>/README.md
Camper Leaderboard
#FCC React Project 2
[Codepen Demo](http://codepen.io/azaleas/pen/ZLJPpv)<file_sep>/src/api.js
const API_STEM = 'https://fcctop100.herokuapp.com/api/fccusers/top';
let api = {
fetchRecent: () => {
let URL = `${API_STEM}/recent`;
return fetch(URL)
.then((response) => response.json())
.then((responseJSON) => responseJSON)
.catch(function(err){
console.warn("Error in fetchData", err);
})
},
fetchAlltime: () => {
let URL = `${API_STEM}/alltime`;
return fetch(URL)
.then((response) => response.json())
.then((responseJSON) => responseJSON)
.catch(function(err){
console.warn("Error in fetchData", err);
})
}
};
export default api; | 894cb66145da94953365812f6af7486589dc4056 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | azaleas/camper-leaderboard | 12bdf35e4a0692cdc6c4786e4405de4284ceae9a | 39227a216365bcceca24b0a416e6a29f1b794e62 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package threads;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Nikolaj
*/
public class PrintFrom10 implements Runnable{
@Override
public void run() {
int count = 10;
try {
while (true) {
Thread.sleep(3000);
System.out.println(count++);
}
} catch (InterruptedException ex) {
System.out.print("PrintFrom10 interupted");
}
}
}
| 3a09c380e0b75633ae1f40509ecd064a8c098b8a | [
"Java"
] | 1 | Java | brunnernikolaj/CPH-Assignments | 4e6e00ae898cfc1100612429a0a2c5c38be1b510 | ceab92a9c2236388ee2634486cc7df94a4914a03 |
refs/heads/master | <repo_name>iuthub/lab-4-otabek1998<file_sep>/webpage/sucker1.php
<?php
include("task1.html");
?><file_sep>/webpage/sucker2.php
<?php
include("task2.html");
?><file_sep>/webpage/sucker3.php
<?php
include("task3.html");
?><file_sep>/webpage/sucker.php
<?php
include("datas/task1.html");
?><file_sep>/webpage/sucker4.php
<?php
include("task4.html");
?><file_sep>/webpage/data4.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Buy Your Way to a Better Education!</title>
<link href="buyagrade.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php if(!empty($_REQUEST["names"])) {
if(!empty($_REQUEST["ccard"])) {
# code...?>
<h1>Thanks, sucker!</h1>
<p>
Your information has been recorded
</p>
<dl>
<dt>Name</dt>
<dd>
Your name is: <?php echo $_POST["names"]; ?>
</dd>
<dt>Section</dt>
<dd>
Your section is: <?php echo $_POST["selection"]; ?>
</dd>
<dt>Credit Card</dt>
<dd>
Your credit card number is: <?php echo $_POST["ccard"]; print " (".$_POST["cc"] . ")";?>
</dd>
</dl>
<?php
$myfile=fopen("datafile4.txt", "a+") or die("Unable to open file");
$data=$_POST["names"]."; ";
fwrite($myfile, $data);
$data=$_POST["selection"]."; ";
fwrite($myfile, $data);
$data=$_POST["ccard"]."; ";
fwrite($myfile, $data);
$data=$_POST["cc"]."; ";
fwrite($myfile, $data);
$n="\n";
fwrite($myfile, $n);
fclose($myfile);
?>
<p>
Here are all the suckers who have submitted here:
</p>
<?php
$myfile = fopen("datafile4.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
}
else{
?>
<h1>Sorry</h1>
<p>
You didn't fill out the form completely. <a href="task4.html">Try again?</a>
</p>
<?php }
}else{
?>
<h1>Sorry</h1>
<p>
You didn't fill out the form completely. <a href="task4.html">Try again?</a>
</p>
<?php } ?>
</body>
</html> | dd606690b2c1438bd44fb6cc8410ed7aeda3d282 | [
"PHP"
] | 6 | PHP | iuthub/lab-4-otabek1998 | 2d4c5f4d39274ac0715d0ce986dbfe8992b5d14e | fdf04e8174ca6ca9da270dbed06ee29c2d39d019 |
refs/heads/master | <file_sep>import React from 'react'
import { useDispatch } from 'react-redux';
import { deleteOrder } from '../../actions/OrderAction';
import './Cart.css';
import { incrementQuantity, decrementQuantity } from '../../actions/OrderAction';
import { currencyFormatter } from '../../utils/currencyFormatter';
const CartItem = ({order}) => {
const dispatch = useDispatch();
return (
<tr className="cart-order-row">
<td>{order.name}</td>
<td>{currencyFormatter(order.price)}</td>
<td>
<button className="btn" type="button" onClick={() => decrementQuantity(dispatch, order.id)}>-</button>
<span>{order.qty}</span>
<button className="btn" type="button" onClick={() => incrementQuantity(dispatch, order.id)}>+</button>
</td>
<td>{currencyFormatter(order.totalPrice)}</td>
<td><button className="btn btn-danger" type="button" onClick={() => deleteOrder(dispatch, order.id)}>Remove</button> </td>
</tr>
)
}
export default CartItem
<file_sep>import React from 'react'
import { useSelector } from 'react-redux';
import CartItem from './CartItem';
import { currencyFormatter } from '../../utils/currencyFormatter';
const Cart = () => {
const { orders, totalPrice, totalQuantity } = useSelector(state => state.orderListReducer)
return (
<div className="cart">
<h1 className="page-title">Cart Details</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{orders.map(order => <CartItem key={order.id} order={order}/>)}
<tr>
<td></td>
<td></td>
<td><h2>{totalQuantity}</h2></td>
<td><h2>{currencyFormatter(totalPrice)}</h2></td>
<td></td>
</tr>
</tbody>
</table>
</div>
)
}
export default Cart
<file_sep># React App using Redux and Routing
Sample Restaurant App using Redux for handling state management. UI styling using Bootstrap
<file_sep>import Header from './components/header/Header';
import Home from './pages/home/Home';
import Cart from './pages/cart/Cart';
import Admin from './pages/admin/Admin';
import { Route, Switch } from 'react-router-dom';
import './App.css';
function App() {
return (
<>
<Header />
<div className="container">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/admin" component={Admin} />
<Route path="/cart" component={Cart} />
</Switch>
</div>
</>
);
}
export default App;
<file_sep>import { createStore, combineReducers } from 'redux';
import { menuListReducer } from './reducers/MenuListReducer';
import { orderListReducer } from './reducers/OrderListReducer';
const reducers = combineReducers({
menuListReducer: menuListReducer,
orderListReducer: orderListReducer
})
const store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;<file_sep>import React from 'react'
import MenuList from './menulist/MenuList';
import MenuDetail from './menuDetail/MenuDetail';
import './Home.css';
const Home = () => {
return (
<main>
<div className="row">
<div className="col-lg-3 col-md-4"><MenuList/></div>
<div className="col-lg-9 col-md-8"><MenuDetail/></div>
</div>
</main>
)
}
export default Home
<file_sep>import * as ActionTypes from '../actions/Actions';
const initialState =
{
productSelected: {},
products: [
{
category: 'Dessert',
categoryId: 0,
items: [
{
id: 0,
name: 'Cake',
desc: 'Cake Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 30,
qty: 0,
totalPrice: 0,
image: 'https://media.istockphoto.com/photos/healthy-homemade-carrot-cake-picture-id466724890?k=6&m=466724890&s=612x612&w=0&h=FSbEkebA-FPoQqJJt_GHKxErxsF_Hx23cyRl5QKrlhI='
},
{
id: 1,
name: 'Ice cream',
desc: 'Ice cream Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 30,
qty: 0,
totalPrice: 0,
image: 'https://expertphotography.com/wp-content/uploads/2020/06/ice-cream-photography9.jpg'
}
]
},
{
category: 'Appetizer',
categoryId: 1,
items: [
{
id: 2,
name: 'Soup',
desc: 'Soup Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 30,
qty: 0,
totalPrice: 0,
image: 'https://www.biscuitsandburlap.com/wp-content/uploads/2018/09/she-crab-soup-3.jpg'
},
{
id: 3,
name: 'Salad',
desc: 'Salad Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 30,
qty: 0,
totalPrice: 0,
image: 'https://eskipaper.com/images/garden-salad-1.jpg'
}
]
},
{
category: 'Main Course',
categoryId: 2,
items: [
{
id: 10,
name: '<NAME>',
desc: 'B<NAME> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 120,
qty: 0,
totalPrice: 0,
image: 'https://media.istockphoto.com/photos/grilled-beef-steaks-picture-id882548344?k=6&m=882548344&s=612x612&w=0&h=bQ5ZlptD7rKZdjrvr7adBHXYVVS9p0iISvm1MTshXRU='
},
{
id: 11,
name: '<NAME>',
desc: 'Shrimp Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 180,
qty: 0,
totalPrice: 0,
image: 'https://img.sndimg.com/food/image/upload/w_555,h_416,c_fit,fl_progressive,q_95/v1/img/recipes/12/70/29/uoTJVprzStylivGnLAjn_pr.jpg'
},
{
id: 12,
name: '<NAME>',
desc: 'Pork Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec et porttitor velit, eu dapibus enim. Curabitur rhoncus pretium rutrum. Nulla facilisi. Nulla maximus sed magna non placerat. Ut in porttitor eros, et finibus odio. ',
price: 100,
qty: 0,
totalPrice: 0,
image: 'https://img.lovepik.com/photo/50068/9055.jpg_wh860.jpg'
}
]
}
]
}
export const menuListReducer = (state = initialState, action) => {
switch(action.type) {
case ActionTypes.GET_MENU_LIST:
return state;
case ActionTypes.GET_MENU_ITEM:
return { ...state, productSelected: findProductSelected(state, action) };
case ActionTypes.ADD_MENU_LIST:
return addNewListItem(state, action);
default:
return state;
}
}
const addNewListItem = (oldState, action) => {
const state = {...oldState};
const itemObj = action.payload.item;
const newItem = {
id: Date.now(),
name: itemObj.name,
desc: itemObj.desc,
price: itemObj.price,
qty: 0,
totalPrice: 0,
image: itemObj.image
}
for(let category of state.products) {
if(+category.categoryId === +itemObj.categoryId) {
category.items = [...category.items, newItem];
}
}
return state;
}
const findProductSelected = (state, action) => {
let selected;
for(let category of state.products) {
for(let item of category.items) {
if(item.id === action.payload.id) {
selected = item;
break;
}
}
}
return selected;
}<file_sep>import * as ActionTypes from './Actions';
export const addOrder = (dispatch, item) => {
dispatch({ type: ActionTypes.ADD_ORDER_ITEM, payload: { item: item }});
}
export const deleteOrder = (dispatch, id) => {
dispatch({ type: ActionTypes.DELETE_ORDER_ITEM, payload: { id: id }});
}
export const incrementQuantity = (dispatch, id) => {
dispatch({ type: ActionTypes.INCREMENT_QUANTITY, payload: { id: id }});
}
export const decrementQuantity = (dispatch, id) => {
dispatch({ type: ActionTypes.DECREMENT_QUANTITY, payload: { id: id }});
}
<file_sep>import * as ActionTypes from './Actions';
export const getMenuList = (dispatch) => {
dispatch({ type: ActionTypes.GET_MENU_LIST });
}
export const getMenuItem = (dispatch, id) => {
dispatch({ type: ActionTypes.GET_MENU_ITEM, payload: { id: id }});
}
export const addMenuList = (dispatch, item) => {
dispatch({ type: ActionTypes.ADD_MENU_LIST, payload: { item: item }});
}
| 2785f48071c83ea04a1b3791cf281b79572da05b | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | paulalonte/react-redux-app | c462b425451806838d4bbaed686c74081cd8c578 | f0abb563299732267db6bceb096a7fa245b476ce |
refs/heads/master | <repo_name>mukeshyadav/cypress-test<file_sep>/cypress/integration/domops.spec.js
describe('UI TESTS', () => {
beforeEach(() => {
cy.visit('http://example.cypress.io/commands/actions')
})
it('should clear the inpute text field', () => {
// cy.get('.action-email').type('<EMAIL>').should('have.value', '<EMAIL>')
cy.get('.action-email').type('<EMAIL>').clear().should('have.value', '')
})
it('should able to edit on dblclick', () => {
cy.get('.action-div').dblclick().should('not.be.visible').should('have.value', '')
})
it('should check the first checkbox', () => {
cy.get('.action-checkboxes [type="checkbox"]').check(['checkbox1', 'checkbox3']).should('be.checked')
})
it('should uncheck the checkbox', () => {
cy.get('.action-checkboxes [type="checkbox"]').check(['checkbox1', 'checkbox3']).should('be.checked')
cy.get(".action-checkboxes [type='checkbox']").uncheck(['checkbox1']).should('not.be.checked')
})
it('should select value from dropdown', () => {
cy.get('.action-select').select('apples').should('contain', 'apples')
})
it('should select multiple values from dropdown', () => {
cy.get('.action-select-multiple').select(['apples', 'oranges'])
})
})
<file_sep>/README.md
# UI test using cyress
<file_sep>/index.js
const express = require('express')
const path = require('path')
const app = new express()
const PORT = 3000
// adding delay to
// app.use((req, res, next) => {
// setTimeout(next, 3000)
// })
// serve index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
// serve login page
app.post('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'logged-in.html'))
})
// serve signout page
app.post('/logout', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'sign-out.html'))
})
app.listen(PORT, () => console.log(`Server started on ${PORT}`))
<file_sep>/cypress/integration/loginapp.spec.js
describe('UI TESTS', () => {
beforeEach(() => {
cy.visit('http://localhost:3000')
})
it('should open login page correctly', () => {
cy.get('[data-cy=login-title]').should('have.length', 1)
cy.get('[data-cy=login-title]').should('be.visible')
})
it('should not allow to login if username not provided', () => {
cy.get('[data-cy=password]').type(<PASSWORD>)
cy.get('[data-cy=btn-submit]').click()
cy.get('[data-cy=login-title]').should('have.length', 1)
cy.get('[data-cy=title-loggedin]').should('have.length', 0)
})
it('should not allow to login if password not provided', () => {
cy.get('[data-cy=username]').type('<EMAIL>')
cy.get('[data-cy=btn-submit]').click()
cy.get('[data-cy=login-title]').should('have.length', 1)
cy.get('[data-cy=title-loggedin]').should('have.length', 0)
})
it('If user logged in with valid credentials, go to success page', () => {
cy.get('[data-cy=username]').type('<EMAIL>')
cy.get('[data-cy=password]').type(<PASSWORD>)
cy.get('[data-cy=btn-submit]').click()
cy.get('[data-cy=btn-loggedout]').should('be.visible')
cy.get('[data-cy=btn-loggedout]').should('have.class', 'btn-secondary')
cy.get('[data-cy=btn-loggedout]').should('not.have.class', 'btn-some')
})
it('should fail and take screenshot', () => {
cy.get('[data-cy=logintext]').should('exist')
})
})
<file_sep>/cypress/tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".../node_modules",
"types": ["cypress"]
},
"includes": ["**/*.*"]
}
| e11c163ab6a399807ba9ddbd96b06ff0ee21bf7e | [
"JavaScript",
"JSON with Comments",
"Markdown"
] | 5 | JavaScript | mukeshyadav/cypress-test | 4aeea827d8f99361a1eb6529202fb417fc9819fe | a6fd2c80125012f499994e15188506e72fdca05d |
refs/heads/master | <file_sep>import { TestBed } from '@angular/core/testing';
import { CarserService } from './carser.service';
describe('CarserService', () => {
let service: CarserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CarserService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>import { Car } from './../models/car.module';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CarserService {
cars: Array<Car> =
[
{id: 0, brandName: 'Ford', modelName: 'Focus', priceInRub: 700000},
{id: 1, brandName: 'BMW', modelName: 'M5', priceInRub: 8000000},
{id: 2, brandName: 'Mazda', modelName: 'CX5', priceInRub: 2000000},
];
constructor() { }
getCars()
{
return this.cars;
}
getCar(id: number)
{
return this.cars.find((el) => el.id === id);
}
addCar(car: Car)
{
car.id = this.getCars().length;
this.cars.push(car);
}
}
<file_sep>import { Car } from './../../models/car.module';
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-car',
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
@Input() carInput: Car;
car: Car;
check: boolean = true;
constructor() { }
ngOnInit(): void {
}
}
| 5e6bfd23154b0cfabb613a03e0a2781e4c651bb4 | [
"TypeScript"
] | 3 | TypeScript | Technopark-Altair/adv-test-2-Vatiora | 3e1466d06ab3bd3bd93a52a0c03b00b757e28676 | abe3fbb41945bc816d9d1af537eafb7d4a8029f9 |
refs/heads/master | <file_sep>package AccessModifier.ProtectedEx;
public class ProtectedEx1 {
protected String lastName = "CHOI";
}
<file_sep>package AccessModifier.DefaultEx;
public class DefaultEx1 {
String lastName = "CHOI";
}
<file_sep>package AccessModifier.ProtectedEx.pt2;
import AccessModifier.ProtectedEx.ProtectedEx1;
// 상속받은 클래스의 변수, 메소드가 protected면 접근 가능하다.
public class ProtectedEx2 extends ProtectedEx1 {
public static void main(String[] args) {
ProtectedEx2 pt2 = new ProtectedEx2();
System.out.println(pt2.lastName);
}
}
<file_sep>package inputOutput.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// 라인 단위로 읽어오기
// 라인이 없으면 종료
public class BufferedReaderTest {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("./out.txt"));
while(true) {
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
br.close();
}
}
<file_sep>package inputOutput.Console;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamTestWithChar {
public static void main(String[] args) throws Exception {
InputStream is = System.in;
InputStreamReader reader = new InputStreamReader(is);
char[] a = new char[3];
reader.read(a);
System.out.println(a); // abc
}
}
<file_sep>package Thread;
// 순서가 일정치 않음 ---> 쓰레드는 순서에 상관없이 동시에 실행된다는 것을 알 수 있다.
// 메인메소드가 쓰레드 종료 전에 종료 되어버림 ---> JOIN으로 해결
// 쓰레드 프로그래밍 시 가장 많이 실수하는 부분이 쓰레드가 종료되지 않았는데 쓰레드가 종료된 줄 알고 그 다음 로직을 수행하게 만드는 일이다.
// 쓰레드 종료 후 그 다음 로직 수행해야할 때 꼭 필요한 것이 Join 메소드!
import java.util.ArrayList;
public class TenThreadTestWithJoin extends Thread {
int seq;
public TenThreadTestWithJoin(int seq) {
this.seq = seq;
}
public void run() {
System.out.println(this.seq + " thread start");
try {
Thread.sleep(1000);
} catch (Exception e) {
}
System.out.println(this.seq + " thread end");
}
public static void main(String[] args) {
ArrayList<Thread> threads = new ArrayList<Thread>();
for(int i = 0; i < 10; i++) {
Thread th = new TenThreadTest(i);
th.start();
threads.add(th);
}
for(int i = 0; i < threads.size(); i++) {
Thread th = threads.get(i);
try{
th.join();
} catch (Exception e) {
}
}
System.out.println("Main Method End");
}
}
<file_sep>package abstractEx_Bank;
public abstract class Bank {
String name, account;
int totalAmount;
public Bank() {
System.out.println("Bank constructor");
}
public Bank(String name, String account, int totalAmount) {
System.out.println("Bank constructor have parameter");
this.name = name;
this.account = account;
this.totalAmount = totalAmount;
}
// 예금
public void deposit() {
System.out.println("--- Deposit START ---");
}
// 출금
public void withdraw() {
System.out.println("--- Withdraw START ---");
}
// 적금
public abstract void installmnentSavings();
// 해약
public abstract void cancellation();
// 정보출력
public void getInfo() {
System.out.println("name : " + name);
System.out.println("account : " + account);
System.out.println("totalAmount : " + totalAmount);
}
}
<file_sep>package inputOutput.Console;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// next : 단어
// nextLine : 라인
// nextInt : 정수
// Console 출력
// System.out
System.out.println(sc.next());
}
}
<file_sep>public class Arrays {
public static void main(String[] args) {
// 배열의 길이는 고정되어 있다.
// String[] weeks = new String[]; 이러면 오류
String[] weeks = new String[7];
weeks[0] = "월";
weeks[1] = "화";
weeks[2] = "수";
weeks[3] = "목";
weeks[4] = "금";
weeks[5] = "토";
weeks[6] = "일";
for(int i=0; i< weeks.length; i++) {
System.out.println(weeks[i]);
}
String[] eatList = {"Coffee", "Cake"};
System.out.println(eatList[0]); // Coffee
}
}
<file_sep>package extendsEx;
public class ParentClass {
public ParentClass() {
System.out.println("ParentClass Constructor");
}
public void parentFunc() {
System.out.println("--- parentFunc() START ---");
}
private void privateFunc() {
System.out.println("Private!!!");
}
}
<file_sep>package extendsEx;
public class MainClass {
public static void main(String[] args) {
ChildClass childClass = new ChildClass();
childClass.childFunc();
childClass.parentFunc();
// private 접근 불가
// childClass.privateFunc();
}
}
<file_sep>package StaticEx.StaticMethod;
// SingletonPattern
// : 단 하나의 객체만을 생성하는 패턴
// : 클래스를 통해 생성할 수 있는 객체는 단 한개만 되도록 만드는 패턴
class Singleton {
private Singleton() {
}
// 에러 해결 ---> 그러나 싱글톤이 아니게 됨.
// public static Singleton getInstance() {
// return new Singleton();
// }
// Singleton에 one 이라는 static 변수를 두고 getInstance 메소드에서
// one 값이 null 인 경우에만 객체를 생성하도록 하여 one 객체가 한번만 만들어 지도록 한다.
private static Singleton one;
// 최초 호출 시 one은 null --> new 로 객체가 생성된다.
// 그 이후 호출 시 one은 null이 아니므로 기존에 있던 one을 계속 리턴해준다.
public static Singleton getInstance() {
if(one == null) {
one = new Singleton();
}
return one;
}
}
public class SingletonPatternEx {
public static void main(String[] args) {
// Error! : 생성자가 private! 외부 클래스에서 new 사용하여 생성 불가.
// Singleton singleton = new Singleton();
// getInstance 호출 할 때마다 새로운 객체 생성 ---> 싱글톤 아님!
// Singleton singleton = Singleton.getInstance();
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}
<file_sep>package inputOutput;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyMain {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream("txt/hello.txt");
os = new FileOutputStream("txt/helloCopy.txt");
byte[] arr = new byte[3];
while(true) {
int len = is.read(arr);
if(len == -1) break;
os.write(arr, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
<file_sep>package AccessModifier.PrivatEx;
public class PrivateEx {
// 접근제어자
// 1. private : 해당 클래스에서만 접근이 가능하다.
// secret 변수와 getSecret 메소드는 해당 클래스에서만 접근 가능하다.
private String secret;
private String getSecret() {
return this.secret;
}
}
<file_sep>package ExceptionEx.ThrowsThrow;
public class ExceptionEx extends Exception {
}
<file_sep>package construct;
public class MainClass {
public static void main(String[] args) {
int[] iArr = {10, 20, 30};
ObjectClass obj1 = new ObjectClass("Hello", iArr);
}
}
<file_sep>package extendsOverride;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 기본 자료형처럼 클래스도 자료형이다!
ChildClass childRecipe = new ChildClass();
childRecipe.recipe();
}
}
<file_sep>package construct;
public class ObjectClass {
public ObjectClass(String n, int[] iArr) {
// TODO Auto-generated constructor stub
System.out.println(n);
// 배열은 객체기 때문에 해당 메모리의 주소가 출력된다.
System.out.println(iArr);
}
}
<file_sep>package extendsOverride;
public class TwoChilds_SecondChildClass extends TwoChilds_ParentClass {
public TwoChilds_SecondChildClass() {
// TODO Auto-generated constructor stub
}
@Override
public void recipe() {
System.out.println("--- TwoChilds_SecondChildClass's recipe with TwoChilds_ParentClass's recipe --- ");
}
}
<file_sep>package socketChat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientClass {
public static void main(String[] args) {
Socket socket = null;
OutputStream ouputStream = null;
DataOutputStream dataOps = null;
InputStream inputStream = null;
DataInputStream dataIps = null;
Scanner scanner = null;
try {
socket = new Socket("localhost", 9000);
System.out.println("Connected Server");
ouputStream = socket.getOutputStream();
dataOps = new DataOutputStream(ouputStream);
inputStream = socket.getInputStream();
dataIps = new DataInputStream(inputStream);
scanner = new Scanner(System.in);
while (true) {
System.out.println("Write Message : ");
String outMsg = scanner.nextLine();
dataOps.writeUTF(outMsg);
dataOps.flush();
String inMsg = dataIps.readUTF();
System.out.println("In Message : " + inMsg);
if(outMsg.equals("STOP")) break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(dataIps != null) dataIps.close();
if(inputStream != null) inputStream.close();
if(dataOps != null) dataOps.close();
if(ouputStream != null) ouputStream.close();
if(socket != null) socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<file_sep>public class Hello {
public static void main(String[] args) { // main method
// 프로그램 실행 시 전달되는 파라미터는 메소드의 입력 파라미터 String[] args에 저장된다.
System.out.println("Hello JAVA");
}
}
<file_sep>package ObjectOriented.Interface;
/*
인터페이스 : 프로젝트의 설계도, 기능에 대해 선언만 한 상태
- 모든 메서드의 선언만 정의하고 메서드의 기능에 대해 주석만 기입한 상태
- 인터페이스는 자식 클래스에서 상속 받아 사용되므로 다형성의 특성을 가지고 있다.
- 왜 필요? : 클래스 사이에서 독립적으로 만드는 거기 떄문에 클래스간 결합도가 낮아진다.(인터페이스를 쓰는 클래스가 변경이 돼도 상관이 없음)
컴퓨터 : ZooKeeper
USB 포트 : Predator ---> Interface!
하드디스크, 카메라 ... : Tiger, Lion, Crocodile
*/
public class Zookeeper {
public void feed(Predator predator) {
System.out.println("feed : " + predator.getFood());
}
public static void main(String[] args) {
Zookeeper zooKeeper = new Zookeeper();
Tiger tiger = new Tiger();
Lion lion = new Lion();
Crocodile crocodile = new Crocodile();
zooKeeper.feed(tiger);
zooKeeper.feed(lion);
zooKeeper.feed(crocodile);
}
}
<file_sep>package collections;
import java.util.ArrayList;
public class ListMainClass {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
System.out.println("list's size : " + list.size());
System.out.println();
System.out.println("ADD");
list.add("Hello");
list.add("C");
list.add("World");
System.out.println("list's size : " + list.size());
System.out.println("list : " + list);
list.add(2, "Programming");
System.out.println("list : " + list);
list.set(1, "JAVA");
System.out.println("list : " + list);
System.out.println();
System.out.println("GET");
// Get
String str = list.get(2);
System.out.println("list get(2) : " + str);
System.out.println("list : " + list);
System.out.println();
System.out.println("REMOVE");
// Remove
str = list.remove(2);
System.out.println("list.remove(2) : " + str);
System.out.println("list : " + list);
System.out.println();
System.out.println("CLEAR");
// All Remove -> clear
list.clear();
System.out.println("list : " + list);
boolean b = list.isEmpty();
System.out.println("Is Empty? : " + b);
}
}
<file_sep>package exception;
public class ThrowsMainClass {
public static void main(String[] args) {
// 예외 발생 시 예외처리를 직접 하지 않고 호출한 곳으로 넘긴다.
ThrowsMainClass thMainClass = new ThrowsMainClass();
try {
thMainClass.firstMethod();
} catch (Exception e){
e.printStackTrace();
}
}
public void firstMethod() throws Exception {
secondMethod();
}
public void secondMethod() throws Exception {
thirdMethod();
}
public void thirdMethod() throws Exception {
System.out.println("thirdMethod() 실행");
}
}
<file_sep>package Thread;
// 순서가 일정치 않음 ---> 쓰레드는 순서에 상관없이 동시에 실행된다는 것을 알 수 있다.
// 메인메소드가 쓰레드 종료 전에 종료 되어버림 ---> JOIN으로 해
public class TenThreadTest extends Thread {
int seq;
public TenThreadTest(int seq) {
this.seq = seq;
}
public void run() {
System.out.println(this.seq + " thread start");
try {
Thread.sleep(1000);
} catch (Exception e) {
}
System.out.println(this.seq + " thread end");
}
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
Thread th = new TenThreadTest(i);
th.start();
}
System.out.println("Main Method End");
}
}
<file_sep>package Thread;
import java.util.ArrayList;
public class RunnableTest implements Runnable {
// 인터페이스를 이용했으니 상속 및 다른 부분에서 좀 더 유연한 프로그램으로 발전!
int seq;
public RunnableTest(int seq) {
this.seq = seq;
}
@Override
public void run() {
System.out.println(this.seq + " thread start");
try{
Thread.sleep(1000);
} catch (Exception e) {
}
System.out.println(this.seq + " thread end.");
}
public static void main(String[] args) {
ArrayList<Thread> threads = new ArrayList<Thread>();
for(int i = 0; i < 10; i++) {
Thread th = new Thread(new RunnableTest(i));
th.start();
threads.add(th);
}
for(int i = 0; i < threads.size(); i++) {
Thread th = threads.get(i);
try{
th.join();
} catch (Exception e) {
}
}
System.out.println("Main Method End");
}
}
<file_sep>package interfaceEx_Toy;
public class Toy_Robot implements Toy{
@Override
public void walk() {
System.out.println("Toy_Robot - Can Walk");
}
@Override
public void run() {
System.out.println("Toy_Robot - Can Run");
}
@Override
public void alarm() {
System.out.println("Toy_Robot - Have no Alarm");
}
@Override
public void light() {
System.out.println("Toy_Robot - Have a light");
}
}
<file_sep>package finalize;
public class ObjectClass {
int num;
String str;
int nums[];
public ObjectClass() {
System.out.println("Default constructor");
}
public ObjectClass(int i) {
System.out.println("Custom constructor");
num = i;
}
public ObjectClass(String s, int i[]) {
System.out.println("UserDefined constructor");
str = s;
nums = i;
}
public ObjectClass(int i, String s, int is[]) {
System.out.println("UserDefined constructor");
this.num = i;
this.str = s;
this.nums = is;
}
@Override
protected void finalize() throws Throwable {
System.out.println("--- finalize() method start ---");
super.finalize();
}
}
| 2e145a68b8b46954023b919e7797862831a71e00 | [
"Java"
] | 28 | Java | soo-dev/java-practice | e9a65283a5eee4e6d3498d43005124c8e672c6bb | 669e7aebcef85ea4b14c1fde5e9d7a3b7de4504d |
refs/heads/master | <repo_name>kmolik/file-upload-app<file_sep>/src/app/app.component.ts
import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private http: HttpClient) {
}
selectedFile: File = null;
onFileSelected(event) {
this.selectedFile = event.target.files[0] as File;
}
onUpload() {
console.log(this.selectedFile);
const fd = new FormData();
fd.append('file', this.selectedFile, 'test');
console.log(fd);
this.http.post('http://localhost:3000/upload', fd).subscribe(event => {
console.log(event);
});
}
}
| 713a1dc57cb6aa9a71fc7eee034dec32fd152d2c | [
"TypeScript"
] | 1 | TypeScript | kmolik/file-upload-app | 04fd83e24678e01bd349243153eee55d1fa05800 | 0a32a67a6f7dc519ed474b567b6becb996732ab4 |
refs/heads/master | <repo_name>Danejerosa/Projects<file_sep>/Yelp2V18/YelpProject/GUISetup/QuerySetup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.GUISetup
{
class QuerySetup
{
private SQL.SQLQueries newQuery = new SQL.SQLQueries();
private SQL.IllegalInput inputChk = new SQL.IllegalInput();
private SQL.SQLConstants sq = new SQL.SQLConstants();
private Classes.ClassConstants c = new Classes.ClassConstants();
private Dictionary<string, List<string>> query;
private Classes.User newUser;
private Classes.Business newBusiness;
private Classes.Business currBusiness;
private Map.MapDriver map = new Map.MapDriver();
public List<Object[]> GetUser(String username)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.U_id });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.U_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.U_name });
query.Add(sq.SQL_COND, new List<string>() { username });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Object[]> GetBusiness(String BUsername)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.B_id });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.B_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_name });
query.Add(sq.SQL_COND, new List<string>() { BUsername });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public Classes.Business GetBusinessDetails(String businessID)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.B_id, c.B_name, c.B_stars,
c.B_city, c.B_zipcode, c.B_address, c.B_latitude, c.B_longitude, c.B_reviewCount, c.B_reviewRating
,c.B_numCheckins, c.B_state});
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.B_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id });
query.Add(sq.SQL_COND, new List<string>() { businessID });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
Classes.Business tempBusiness = new Classes.Business() {
business_id = newObject[0][0].ToString(),
name = newObject[0][1].ToString(),
stars = Double.Parse(newObject[0][2].ToString()),
city = newObject[0][3].ToString(),
zipcode = newObject[0][4].ToString(),
address = newObject[0][5].ToString(),
latitute = Double.Parse(newObject[0][6].ToString()),
longtitude = Double.Parse(newObject[0][7].ToString()),
review_count = Int32.Parse(newObject[0][8].ToString()),
review_rating = Double.Parse(newObject[0][9].ToString()),
num_checkins = Int32.Parse(newObject[0][10].ToString()),
state = newObject[0][11].ToString()
};
return tempBusiness;
}
public Classes.User GetUserDetails(String userID)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT,c.U_id, c.U_name, c.U_avgStars, c.U_fans, c.U_yelpingSince, c.U_funny,
c.U_cool, c.U_useful, c.U_latitude, c.U_longitude});
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.U_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.U_id });
query.Add(sq.SQL_COND, new List<string>() { userID });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
foreach(Object[] users in newObject)
{
Classes.User tempUser = new Classes.User()
{
user_Id = users[0].ToString(),
username = users[1].ToString(),
average_stars = Double.Parse(users[2].ToString()),
fans = Int32.Parse(users[3].ToString()),
yelping_since = users[4].ToString(),
funny = Int32.Parse(users[5].ToString()),
cool = Int32.Parse(users[6].ToString()),
useful = Int32.Parse(users[7].ToString()),
user_latitude = Double.Parse(users[8].ToString()),
user_longitude = Double.Parse(users[9].ToString())
};
return tempUser;
}
return null;
}
public void SetCurrentUser(Classes.User user)
{
newUser = user;
}
public void SetCurrentBusiness(Classes.Business business)
{
newBusiness = business;
}
public Classes.Business GetCurrentBusiness()
{
return newBusiness;
}
public void SetLoggedInBusiness(Classes.Business business)
{
currBusiness = business;
}
public Classes.Business GetLoggedInBusiness()
{
return currBusiness;
}
public List<Object[]> GetFriends()
{
if (newUser != null)
{
Classes.User tempUser = new Classes.User();
List<Classes.User> tempUserList = new List<Classes.User>();
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<String>() { sq.SQL_SELECT, c.FR_id });
query.Add(sq.SQL_FROM, new List<String>() { sq.SQL_FROM, c.FR_table });
query.Add(sq.SQL_WHERE, new List<String>() { c.FR_uid });
query.Add(sq.SQL_COND, new List<String>() { newUser.user_Id });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
return null;
}
public List<Object[]> GetFriendReview(List<Object[]> tempUserList)
{
List<Object[]> newObject = GetReviewByDate(tempUserList);
List<Object[]> tempSolutionList = new List<object[]>();
foreach (Object[] temp in newObject)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.B_name, c.B_city, c.R_text, c.R_date });
query.Add(sq.SQL_FROM, new List<String>() { sq.SQL_FROM,c.B_table, c.R_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.R_date, c.R_user });
query.Add(sq.SQL_COND, new List<string>() { temp[0].ToString(), temp[1].ToString() });
List<Object[]> secondObjectQuery = newQuery.SQLSelectQuery(query);
foreach(Object[] item in secondObjectQuery)
{
// Temporary solution as of now.
var newTempA = GetUserDetails(temp[1].ToString()).username;
var newTempB = item[0];
var newTempC = item[1];
var newTempD = item[2];
var newTempE = item[3];
Object[] tempArray = new Object[] { newTempA, newTempB, newTempC, newTempD, newTempE };
tempSolutionList.Add(tempArray);
}
}
return tempSolutionList;
}
public List<Object[]> GetReviewByDate(List<Object[]> tempUserList)
{
List<Object[]> newObject = new List<Object[]>();
foreach (Object[] temp in tempUserList)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.R_date, c.R_user });
query.Add(sq.SQL_FROM, new List<String>() { sq.SQL_FROM, c.B_table, c.R_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.U_id });
query.Add(sq.SQL_COND, new List<string>() { temp[0].ToString() });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, sq.SQL_DESC, c.R_date });
//review logic, only adding first object? temp[0] is one user_id
List<Object[]> reviewDate = newQuery.SQLSelectQuery(query);
if(reviewDate != null && reviewDate.Count > 0)
newObject.Add(reviewDate[0]);
}
return newObject;
}
public List<Object[]> GetStates()
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.B_state });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.B_table });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.B_state });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Object[]> GetCities(String state)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.B_city });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.B_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_state });
query.Add(sq.SQL_COND, new List<string>() {state });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.B_city });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Object[]> GetZipcodes(List<string> location)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.B_zipcode });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.B_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_state, c.B_city });
query.Add(sq.SQL_COND, new List<string>() { location[0], location[1] });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.B_zipcode });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Object[]> GetCategories(List<string> location)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.CAT_name });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM,c.B_table, c.CAT_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_state, c.B_city, c.B_zipcode });
query.Add(sq.SQL_COND, new List<string>() { location[0], location[1], location[2] });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.CAT_name });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Classes.Business> GetBusinesses(List<Classes.Attributes> tempAttr, List<string> location, List<string> catArray, List<string> order)
{
query = new Dictionary<string, List<string>>();
List<String> test = new List<String>();
List<String> test2 = new List<String>();
List<Classes.Business> tempBusinessList = new List<Classes.Business>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.SPEC_id,c.B_name, c.B_address, c.B_city, c.B_state,
c.B_latitude, c.B_longitude, c.B_stars, c.B_reviewCount, c.B_reviewRating, c.B_numCheckins});
if(tempAttr.Count > 0)
{
foreach(Classes.Attributes attr in tempAttr)
{
test.Add(attr.attribute_name);
test2.Add(attr.attribute_value);
}
query.Add(sq.SQL_ATTR, test);
query.Add(sq.SQL_VAL, test2);
}
if(catArray.Count > 0)
query.Add(sq.SQL_CAT, catArray);
query.Add(sq.SQL_WHERE, new List<string>() { c.B_state, c.B_city, c.B_zipcode });
query.Add(sq.SQL_COND, new List<string>() { location[0], location[1], location[2] });
String origOrder = order[0];
order[0] = order[0].Equals(c.ORD_distance) ? order[0] = c.ORD_name : order[0];
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, order[1], order[0] });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
Double ratingParse;
for(int i = 0; i < newObject.Count; i++)
{
Double.TryParse(Double.Parse(newObject[i][9].ToString()).ToString("#.##"), out ratingParse);
Classes.Business tempBusiness = new Classes.Business()
{
business_id = newObject[i][0].ToString(),
name = newObject[i][1].ToString(),
address = newObject[i][2].ToString(),
city = newObject[i][3].ToString(),
state = newObject[i][4].ToString(),
latitute = Double.Parse(newObject[i][5].ToString()),
longtitude = Double.Parse(newObject[i][6].ToString()),
stars = Double.Parse(newObject[i][7].ToString()),
review_count = Int32.Parse(newObject[i][8].ToString()),
review_rating = ratingParse,
num_checkins = Int32.Parse(newObject[i][10].ToString()),
business_distance = "0"
};
if (newUser != null)
{
map.CalculateDistance(new Microsoft.Maps.MapControl.WPF.Location(tempBusiness.latitute, tempBusiness.longtitude),
new Microsoft.Maps.MapControl.WPF.Location(newUser.user_latitude, newUser.user_longitude));
double dist = map.GetDistance();
tempBusiness.business_distance = dist.ToString(".## ");
}
tempBusinessList.Add(tempBusiness);
}
if(newUser != null && origOrder.Equals(c.ORD_distance))
{
tempBusinessList.Sort(delegate (Classes.Business x, Classes.Business y) {
return x.business_distance.CompareTo(y.business_distance);
});
}
return tempBusinessList;
}
public int UpdateUserLocation(List<string> location)
{
if(newUser != null)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_UPDATE, c.U_table });
query.Add(sq.SQL_SET, new List<string>() { sq.SQL_SET, c.U_latitude, c.U_longitude });
query.Add(sq.SQL_VAL, new List<string>() { "I",location[0], location[1] });
query.Add(sq.SQL_WHERE, new List<string>() { sq.SQL_WHERE, c.U_id });
query.Add(sq.SQL_COND, new List<string>() { newUser.user_Id });
return newQuery.SQLNonQuery(query);
}
return 0;
}
public List<Object[]> GetCurrentBusinessCategories(String businessID)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.CAT_name });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.CAT_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id});
query.Add(sq.SQL_COND, new List<string>() { businessID });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.CAT_name });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public List<Object[]> GetCurrentBusinessAttributes(String businessID)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.ATTR_name, c.ATTR_val });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.ATTR_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id });
query.Add(sq.SQL_COND, new List<string>() { businessID });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.ATTR_name });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public Classes.Hours GetCurrentBusinessHours(String businessID, String day)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.HRS_day, c.HRS_open, c.HRS_close });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.HRS_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id, c.HRS_day });
query.Add(sq.SQL_COND, new List<string>() { businessID, day });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.HRS_day });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
if(newObject.Count > 0)
{
Classes.Hours newHours = new Classes.Hours()
{
hours_day = newObject[0][0].ToString(),
hours_open = DateTime.Parse(newObject[0][1].ToString()),
hours_close = DateTime.Parse(newObject[0][2].ToString())
};
return newHours;
}
return null;
}
public void InsertCheckins(Classes.Business business)
{
DateTime rightNow = DateTime.Now;
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_UPDATE, c.CHK_table });
query.Add(sq.SQL_SET, new List<string>() { sq.SQL_SET, c.CHK_count });
query.Add(sq.SQL_VAL, new List<string>() { "I",c.CHK_count +" + 1" });
query.Add(sq.SQL_WHERE, new List<string>() { sq.SQL_WHERE, c.CHK_day, c.CHK_time, c.B_id });
query.Add(sq.SQL_COND, new List<string>() { rightNow.ToString("dddd"), rightNow.ToString("hh:mm"), business.business_id });
int updated = newQuery.SQLNonQuery(query);
//Does not exist in table so do an insert.
if (updated == 0)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_INSERT, c.CHK_table });
query.Add(sq.SQL_VAL, new List<string>() { sq.SQL_VAL, rightNow.ToString("dddd"),
rightNow.ToString("hh:mm"), "1", business.business_id });
int newUpdate = newQuery.SQLNonQuery(query);
ShowStatusUpdate(newUpdate, "Check In");
}
else
{
ShowStatusUpdate(updated, "Check In");
}
}
public List<Classes.Review> GetBusinessReviews(Classes.Business business)
{
List<Classes.Review> reviewList = new List<Classes.Review>();
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.R_date, c.R_reviewStars,
c.R_text, c.R_funny, c.R_useful, c.R_cool, c.R_user });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.R_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id });
query.Add(sq.SQL_COND, new List<string>() { business.business_id });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, sq.SQL_DESC, c.R_date });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
foreach(Object[] review in newObject)
{
Classes.Review newReview = new Classes.Review()
{
review_date = DateTime.Parse(review[0].ToString()).ToString("d"),
review_stars = Int32.Parse(review[1].ToString()),
review_text = review[2].ToString(),
funny_vote = Int32.Parse(review[3].ToString()),
useful_vote = Int32.Parse(review[4].ToString()),
cool_vote = Int32.Parse(review[5].ToString()),
review_username = GetUserDetails(review[6].ToString()).username
};
reviewList.Add(newReview);
}
return reviewList;
}
public void InsertReview(String reviewText, Classes.Business currBuss, String rating)
{
if(newUser != null)
{
if(reviewText.Length > 0)
{
DateTime rightNow = DateTime.Now;
query = new Dictionary<string, List<string>>();
String reviewID = new StringHasher.SimpleStringHasher().GetHash();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_INSERT, c.R_table, "(review_id, business_id, user_id, review_stars, review_date, review_text, funny_vote, useful_vote, cool_vote)" });
query.Add(sq.SQL_VAL, new List<string>() { sq.SQL_VAL, reviewID, currBuss.business_id, newUser.user_Id,
rating, rightNow.ToString("MM/dd/yyyy"), reviewText, "0", "0", "0" });
int updated = newQuery.SQLNonQuery(query);
ShowStatusUpdate(updated, "Add Review");
}
else
ShowStatusUpdate(0, "Please add text, Add Review");
}
}
public int CheckFavoritesBeforeAdd()
{
int status = 0;
if(newUser != null && newBusiness != null)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.FAV_uid });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.FAV_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.FAV_uid, c.FAV_bid });
query.Add(sq.SQL_COND, new List<string>() { newUser.user_Id, newBusiness.business_id });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
status = newObject != null ? newObject.Count : 0;
}
return status;
}
public void InsertToFavorites(Classes.Business currBuss)
{
if(newUser != null)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_INSERT, c.FAV_table });
query.Add(sq.SQL_VAL, new List<string>() { sq.SQL_VAL, newUser.user_Id , currBuss.business_id});
int updated = newQuery.SQLNonQuery(query);
ShowStatusUpdate(updated, "Add to Favorites");
}
}
public List<Object[]> GetUserFavorites()
{
if(newUser != null)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.FAV_bid });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.FAV_table });
query.Add(sq.SQL_WHERE, new List<String>() { c.FAV_uid });
query.Add(sq.SQL_COND, new List<String>() { newUser.user_Id });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
return null;
}
public int RemoveBusiness(String businessID)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_DELETE, c.FAV_table });
query.Add(sq.SQL_WHERE, new List<string>() { sq.SQL_WHERE, c.B_id });
query.Add(sq.SQL_COND, new List<string>() { businessID });
int updated = newQuery.SQLNonQuery(query);
ShowStatusUpdate(updated, "Remove Business");
return updated;
}
public Classes.Review GetBusinessFriendReviews(String friendID)
{
if(newUser != null)
{
List<Classes.Review> reviewList = new List<Classes.Review>();
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, c.R_date, c.R_reviewStars,
c.R_text, c.R_funny, c.R_useful, c.R_cool, c.R_user });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.R_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id, c.U_id });
query.Add(sq.SQL_COND, new List<string>() { newBusiness.business_id, friendID });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, sq.SQL_DESC, c.R_date });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
foreach (Object[] review in newObject)
{
if (review != null)
{
Classes.Review newReview = new Classes.Review()
{
review_date = review[0].ToString(),
review_stars = Int32.Parse(review[1].ToString()),
review_text = review[2].ToString(),
funny_vote = Int32.Parse(review[3].ToString()),
useful_vote = Int32.Parse(review[4].ToString()),
cool_vote = Int32.Parse(review[5].ToString()),
review_username = GetUserDetails(review[6].ToString()).username,
actual_review_date = review[0].ToString()
};
return newReview;
}
}
}
return null;
}
public List<Object[]> GetBusinessCheckinDays(Classes.Business business)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECTDIST, c.CHK_day });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.CHK_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id });
query.Add(sq.SQL_COND, new List<string>() { business.business_id });
query.Add(sq.SQL_ORDER, new List<string>() { sq.SQL_ORDER, ";", c.CHK_day });
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
return newObject;
}
public Classes.Checkins GetBusinessCheckins(Classes.Business business, String checkinsDay)
{
query = new Dictionary<string, List<string>>();
query.Add(sq.SQL_PROJECT, new List<string>() { sq.SQL_SELECT, "SUM(" + c.CHK_count + ")" });
query.Add(sq.SQL_FROM, new List<string>() { sq.SQL_FROM, c.CHK_table });
query.Add(sq.SQL_WHERE, new List<string>() { c.B_id, c.CHK_day});
query.Add(sq.SQL_COND, new List<string>() { business.business_id , checkinsDay});
List<Object[]> newObject = newQuery.SQLSelectQuery(query);
if(newObject != null && newObject.Count > 0)
{
return new Classes.Checkins() {
checkin_day = checkinsDay,
checkin_count = Int32.Parse(newObject[0][0].ToString())
};
}
return null;
}
public void ShowStatusUpdate(int status, String statText)
{
DialogSetup newDialog = new DialogSetup(status, statText);
}
public List<string> GetOrder(int index)
{
String orderby = "";
String order = "";
switch (index)
{
case 0:
orderby = c.ORD_name;
order = sq.SQL_ASC;
break;
case 1:
orderby = c.ORD_stars;
order = sq.SQL_DESC;
break;
case 2:
orderby = c.ORD_reviwed;
order = sq.SQL_DESC;
break;
case 3:
orderby = c.ORD_rating;
order = sq.SQL_DESC;
break;
case 4:
orderby = c.ORD_checkin;
order = sq.SQL_DESC;
break;
case 5:
orderby = c.ORD_distance;
order = sq.SQL_ASC;
break;
}
return new List<string>() { orderby, order };
}
}
}
<file_sep>/Yelp2V18/YelpProject/SQL/SQLConnString.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.SQL
{
class SQLConnString
{
private String database;
private String password;
private String port;
public SQLConnString(String database, String pass) {
this.database = database;
this.password = <PASSWORD>;
}
public SQLConnString(String database, String pass, String port)
{
this.database = database;
this.password = <PASSWORD>;
this.port = port;
}
public String BuildConnString()
{
if(port == null)
return "Host=localhost; Username=postgres; Password= " + password + " ; Database =" + database + ";";
else
return "Host=localhost; Username=postgres; Password= " + <PASSWORD> + " ; Database =" + database + " ;Port = " + port +";";
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class User
{
public String user_Id { get; set; }
public String username { get; set; }
public String yelping_since { get; set; }
public double average_stars { get; set; }
public double user_latitude { get; set; }
public double user_longitude { get; set; }
public int fans { get; set; }
public int cool { get; set; }
public int funny { get; set; }
public int useful { get; set; }
public int review_count { get; set; }
List<String> friends;
public User() { }
public void PostReviews() { }
public List<String> FriendsList() {
friends = new List<String>();
return friends;
}
}
}
<file_sep>/Yelp2V18/YelpProject/GUISetup/DataGridSetup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
namespace YelpProject.GUISetup
{
class DataGridSetup
{
public void AddColumnToGrid(DataGrid grid, Dictionary<string, List<String>> bindingDictionary)
{
foreach (String item in bindingDictionary.Keys)
{
DataGridTextColumn col = new DataGridTextColumn();
col.Header = item;
col.Binding = new Binding(bindingDictionary[item][0]);
col.Width = Int32.Parse(bindingDictionary[item][1]);
col.IsReadOnly = true;
grid.Columns.Add(col);
}
}
}
}
<file_sep>/Yelp2V18/YelpProject/Map/TestMap.xaml.cs
using Microsoft.Maps.MapControl.WPF;
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.Shapes;
namespace YelpProject.Map
{
/// <summary>
/// Interaction logic for Map.xaml
/// </summary>
public partial class Map : Window
{
public Map()
{
InitializeComponent();
}
public MapCore GetMap()
{
newMap.Center = new Location(15.10, 16.0);
newMap.ZoomLevel = 5;
Pushpin newPin = new Pushpin();
newPin.Location = new Location(15.10, 16.0);
newMap.Children.Add(newPin);
return newMap;
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Hours.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Hours
{
public String hours_day { get; set; }
public DateTime hours_close { get; set; }
public DateTime hours_open { get; set; }
public String open { get; set; }
public String closed { get; set; }
public Hours() { }
}
}
<file_sep>/Yelp2V18/YelpProject/SQL/SQLConstants.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.SQL
{
class SQLConstants
{
//SQL constants
public readonly String SQL_PROJECT = "PROJECTION";
public readonly String SQL_SELECT = "SELECT";
public readonly String SQL_SELECTDIST = "SELECT DISTINCT";
public readonly String SQL_FROM = "FROM";
public readonly String SQL_WHERE = "WHERE";
public readonly String SQL_COND = "COND";
public readonly String SQL_INSERT = "INSERT INTO";
public readonly String SQL_DELETE = "DELETE FROM";
public readonly String SQL_UPDATE = "UPDATE";
public readonly String SQL_ORDER = "ORDER BY";
public readonly String SQL_DESC = "DESC";
public readonly String SQL_ASC = "ASC";
public readonly String SQL_CAT = "CATEGORIES";
public readonly String SQL_ATTR = "ATTRIBUTES";
public readonly String SQL_VAL = "VALUES";
public readonly String SQL_SET = "SET";
public readonly String SQL_COUNT = "COUNT(*)";
}
}
<file_sep>/Yelp2V18/YelpProject/MainWindow.xaml.cs
using Microsoft.Maps.MapControl.WPF;
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;
namespace YelpProject
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeMap();
InitializeFriendGrid();
InitializeFriendReviewGrid();
IntializeSearchBusinessGrid();
InitializeFavoriteBusinessGrid();
InitializeFriendBusinessReviewGrid();
InitializeLogInBusinessReviewGrid();
LoadState();
}
SQL.IllegalInput inputChk = new SQL.IllegalInput();
GUISetup.QuerySetup query = new GUISetup.QuerySetup();
GUISetup.DataGridSetup grid = new GUISetup.DataGridSetup();
Classes.ClassConstants c = new Classes.ClassConstants();
/**
* Description: Container class object for friend review.
* Temporary for now until a better solution is found.
*/
private class FriendReview
{
public String Rusername { get; set; }
public String Rname { get; set; }
public String Rcity { get; set; }
public String Rtext { get; set; }
public String Rdate { get; set; }
}
private void InitializeMap()
{
Map.MapDriver test = new Map.MapDriver(myMap);
test.ClearMap();
test.InitializeMap();
}
private void AddPin(Location newLocation, String business, Color color)
{
Map.MapDriver test = new Map.MapDriver(myMap);
test.AddPin(newLocation, business, color);
}
private void InitializeFriendGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("Name", new List<string>() {c.U_name, "100"});
binding.Add("Avg Stars", new List<string>() { c.U_avgStars, "100" });
binding.Add("Yelping Since", new List<string>() { c.U_yelpingSince, "70" });
grid.AddColumnToGrid(friendDataGrid, binding);
}
private void InitializeFriendReviewGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("User Name", new List<string>() { "Rusername", "100" });
binding.Add("Business", new List<string>() { "Rname", "100" });
binding.Add("City", new List<string>() { "Rcity", "100" });
binding.Add("Text", new List<string>() { "Rtext", "500" });
binding.Add("Date", new List<string>() { "Rdate", "80" });
grid.AddColumnToGrid(friendReviewDataGrid, binding);
}
private void IntializeSearchBusinessGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding = new Dictionary<string, List<string>>();
binding.Add("BusinessName", new List<String> { c.B_name, "150" });
binding.Add("Address", new List<String> { c.B_address, "150" });
binding.Add("City", new List<String> { c.B_city, "100" });
binding.Add("State", new List<String> { c.B_state, "50" });
binding.Add("Distance (Miles)", new List<String> { c.B_distance, "100" });
binding.Add("Stars", new List<String> { c.B_stars, "50" });
binding.Add("# of Reviews", new List<String> { c.B_reviewCount, "50" });
binding.Add("Avg Review Rating", new List<String> { c.B_reviewRating, "50" });
binding.Add("Total Checkins", new List<String> { c.B_numCheckins, "50" });
grid.AddColumnToGrid(searchDataGrid, binding);
}
private void InitializeFavoriteBusinessGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("Business Name", new List<String>() { c.B_name, "150" });
binding.Add("Stars", new List<String> { c.B_stars, "50" });
binding.Add("City", new List<String> { c.B_city, "150" });
binding.Add("Zipcode", new List<String> { c.B_zipcode, "75" });
binding.Add("Address", new List<String> { c.B_address, "150" });
grid.AddColumnToGrid(favoriteDataGrid, binding);
}
private void InitializeFriendBusinessReviewGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("Username", new List<String>() { c.R_username, "150" });
binding.Add("Date", new List<String> { c.R_actDate, "100" });
binding.Add("Text", new List<String> { c.R_text, "500" });
grid.AddColumnToGrid(businessFriendReviewDataGrid, binding);
}
public void InitializeLogInBusinessReviewGrid()
{
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("Date", new List<string>() { c.R_date, "100" });
binding.Add("User Name", new List<string>() { c.R_username, "100" });
binding.Add("Stars", new List<string>() { c.R_reviewStars, "100" });
binding.Add("Text", new List<string>() { c.R_text, "500" });
binding.Add("Funny", new List<string>() { c.R_funny, "65" });
binding.Add("Useful", new List<string>() { c.R_useful, "65" });
binding.Add("Cool", new List<string>() { c.R_cool, "65" });
grid.AddColumnToGrid(businessLogInReviewDataGrid, binding);
}
private void UserTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
LoadUser();
latTextBox.IsEnabled = false;
longTextBox.IsEnabled = false;
//searchDataGrid.Items.Clear();
//favoriteDataGrid.Items.Clear();
}
private void BusinessLogInTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
LoadBusiness();
}
private void UserListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadUserDetails();
LoadUserFriends();
LoadUserFriendReviews();
LoadFavorites();
latTextBox.IsEnabled = false;
longTextBox.IsEnabled = false;
editButton.IsEnabled = true;
updateButton.IsEnabled = true;
//searchDataGrid.Items.Clear();
}
private void BusinessLogInListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
GetLoginBusinessDetails();
GetLoginBusinessReviews();
GetLoginBusinessCategories();
GetLoginBusinessAttributes();
GetLoginBusinessHours(dayComboBox.Text);
}
private void StateComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadCity();
categoryListBox.Items.Clear();
categorySearchListBox.Items.Clear();
}
private void CityListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadZipcode();
categoryListBox.Items.Clear();
categorySearchListBox.Items.Clear();
}
private void ZipcodeListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadCategories();
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
if (categoryListBox.SelectedIndex > -1 && !categorySearchListBox.Items.Contains(categoryListBox.SelectedItem))
{
String item = categoryListBox.SelectedItem.ToString();
categorySearchListBox.Items.Add(item);
}
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
categorySearchListBox.Items.Remove(categorySearchListBox.SelectedItem);
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
latTextBox.IsEnabled = true;
longTextBox.IsEnabled = true;
}
private void UpdateButton_Click(object sender, RoutedEventArgs e)
{
double userLat;
double userLong;
if (double.TryParse(latTextBox.Text, out userLat) && double.TryParse(longTextBox.Text, out userLong))
{
latTextBox.IsEnabled = false;
longTextBox.IsEnabled = false;
int status = query.UpdateUserLocation(new List<string>() { latTextBox.Text, longTextBox.Text });
GUISetup.DialogSetup newDialog = new GUISetup.DialogSetup(status, "Update Location");
}
else
{
latTextBox.Focus();
longTextBox.Focus();
}
}
private void SearchDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
reviewTextBox.IsEnabled = true;
query.SetCurrentBusiness((Classes.Business)searchDataGrid.SelectedItem);
GetCurrentBusinessDetails();
GetCurrentBusinessFriendReviews();
}
private void CheckinButton_Click(object sender, RoutedEventArgs e)
{
if (searchDataGrid.Items.Count > 0)
{
InsertCheckins();
LoadSearchedBusinesses();
}
}
private void ShowReviewButton_Click(object sender, RoutedEventArgs e)
{
GetBusinessReview();
}
private void AddReviewButton_Click(object sender, RoutedEventArgs e)
{
if (searchDataGrid.Items.Count > 0)
{
AddReview();
LoadSearchedBusinesses();
}
}
private void AddToFavButton_Click(object sender, RoutedEventArgs e)
{
AddToFavorites();
}
private void FavButton_Click_1(object sender, RoutedEventArgs e)
{
RemoveFromFavorites();
}
private void ShowCheckinButton_Click(object sender, RoutedEventArgs e)
{
GetCheckins();
}
private void SortByComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(searchDataGrid.Items.Count > 0)
{
LoadSearchedBusinesses();
}
}
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
LoadSearchedBusinesses();
}
private void LoadDayComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//fix this. Doesnt get the correct day
GetLoginBusinessHours(dayComboBox.Text);
}
private void BusinessLogInViewCheckinButton_Click(object sender, RoutedEventArgs e)
{
GetLogInBusinessCheckins();
}
private void LoadCategories()
{
if (stateComboBox.SelectedIndex > -1 && cityListBox.SelectedIndex > -1 && zipcodeListBox.SelectedIndex > -1)
{
categoryListBox.Items.Clear();
categorySearchListBox.Items.Clear();
List<Object[]> newObject = query.GetCategories(new List<string>() {stateComboBox.SelectedItem.ToString(),
cityListBox.SelectedItem.ToString(), zipcodeListBox.SelectedItem.ToString()});
for (int i = 0; i < newObject.Count; i++)
{
categoryListBox.Items.Add(newObject[i][0]);
}
}
}
private void LoadState()
{
stateComboBox.Items.Clear();
List<Object[]> newObject = query.GetStates();
for (int i = 0; i < newObject.Count; i++)
stateComboBox.Items.Add(newObject[i][0]);
}
private void LoadCity()
{
if(stateComboBox.SelectedIndex > -1)
{
cityListBox.Items.Clear();
zipcodeListBox.Items.Clear();
List<Object[]> newObject = query.GetCities(stateComboBox.SelectedItem.ToString());
for (int i = 0; i < newObject.Count; i++)
cityListBox.Items.Add(newObject[i][0]);
}
}
private void LoadZipcode()
{
if(stateComboBox.SelectedIndex > -1 && cityListBox.SelectedIndex > -1)
{
zipcodeListBox.Items.Clear();
List<Object[]> newObject = query.GetZipcodes(new List<string>() { stateComboBox.SelectedItem.ToString(),
cityListBox.SelectedItem.ToString() });
for (int i = 0; i < newObject.Count; i++)
zipcodeListBox.Items.Add(newObject[i][0]);
}
}
private void LoadUser()
{
String username = userTextBox.Text;
if (inputChk.SQLInjectionCheck(username))
{
userListBox.Items.Clear();
List<Object[]> newObject = query.GetUser(username);
for (int i = 0; i < newObject.Count; i++)
userListBox.Items.Add(newObject[i][0]);
}
}
private void LoadUserDetails()
{
if (userListBox.SelectedIndex > -1)
{
Classes.User currUser = query.GetUserDetails(userListBox.SelectedItem.ToString());
nameTextBox.Text = currUser.username;
starsTextBox.Text = currUser.average_stars.ToString();
fansTextBox.Text = currUser.fans.ToString();
yelpingTextBox.Text = currUser.yelping_since.ToString();
funnyTextBox.Text = currUser.funny.ToString();
coolTextBox.Text = currUser.cool.ToString();
usefulTextBox.Text = currUser.useful.ToString();
latTextBox.Text = currUser.user_latitude.ToString();
longTextBox.Text = currUser.user_longitude.ToString();
query.SetCurrentUser(currUser);
}
}
private void LoadUserFriends()
{
friendDataGrid.Items.Clear();
List<Object[]> newObject = query.GetFriends();
foreach(Object[] item in newObject)
{
Classes.User friend = query.GetUserDetails(item[0].ToString());
friendDataGrid.Items.Add(friend);
}
}
private void LoadUserFriendReviews()
{
friendReviewDataGrid.Items.Clear();
List<Object[]> newObject = query.GetFriendReview(query.GetFriends());
foreach (Object[] reviewObj in newObject)
{
friendReviewDataGrid.Items.Add(new FriendReview() { Rusername = reviewObj[0].ToString(),
Rname = reviewObj[1].ToString(), Rcity = reviewObj[2].ToString(), Rtext = reviewObj[3].ToString(),
Rdate = DateTime.Parse(reviewObj[4].ToString()).ToString("d")});
}
}
//For business information
private void LoadBusiness()
{
String BUsername = businessLogInTextBox.Text;
if (inputChk.SQLInjectionCheck(BUsername))
{
businessLogInListBox.Items.Clear();
List<Object[]> newObject = query.GetBusiness(BUsername);
for (int i = 0; i < newObject.Count; i++)
businessLogInListBox.Items.Add(newObject[i][0]);
}
}
private List<Classes.Attributes> LoadAttributes()
{
businessTextBox.Text = "";
List<Classes.Attributes> attr_list = new List<Classes.Attributes>();
if (priceOneCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_pricerange, attribute_value = "1" }); }
if (priceTwoCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_pricerange, attribute_value = "2" }); }
if (priceThreeCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_pricerange, attribute_value = "3" }); }
if (priceFourCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_pricerange, attribute_value = "4" }); }
if (creditCardCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_card, attribute_value = "True" }); }
if (reservationCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_reservation, attribute_value = "True" }); }
if (wheelchairCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_wheelchair, attribute_value = "True" }); }
if (outdoorCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_outdoor, attribute_value = "True" }); }
if (kidsCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_kids, attribute_value = "True" }); }
if (groupCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_groups, attribute_value = "True" }); }
if (deliveryCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_delivery, attribute_value = "True" }); }
if (takeOutCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_takeout, attribute_value = "True" }); }
if (wifiCheckBox.IsChecked ?? false) {attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_wifi, attribute_value = "free" }); }
if (bikeCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_bike, attribute_value = "True" }); }
if (breakfastCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_breakfast, attribute_value = "True" }); }
if (brunchCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_brunch, attribute_value = "True" }); }
if (lunchCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_lunch, attribute_value = "True" }); }
if (dinnerCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_dinner, attribute_value = "True" }); }
if (dessertCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_dessert, attribute_value = "True" }); }
if (lateNightCheckBox.IsChecked ?? false) { attr_list.Add(new Classes.Attributes()
{ attribute_name = c.ATTR_latenight, attribute_value = "True" }); }
return attr_list;
}
//for search business
private void LoadSearchedBusinesses()
{
if (stateComboBox.SelectedIndex > -1 && cityListBox.SelectedIndex > -1 && zipcodeListBox.SelectedIndex > -1)
{
InitializeMap();
searchDataGrid.Items.Clear();
List<Classes.Business> businessList = query.GetBusinesses(LoadAttributes(), new List<string>() {stateComboBox.SelectedItem.ToString(),
cityListBox.SelectedItem.ToString(), zipcodeListBox.SelectedItem.ToString()}, GetSearchCategories(), GetBusinessOrder());
foreach (Classes.Business business in businessList)
{
searchDataGrid.Items.Add(business);
AddPin(new Location(business.latitute, business.longtitude), business.name, Colors.Red);
}
businessNumLabel.Content = businessList.Count;
}
}
private void SearchMapButton_Click(object sender, RoutedEventArgs e)
{
if(searchMapTextBox.Text.Length > 0)
{
SearchMapAddress(searchMapTextBox.Text);
}
}
private void SearchMapAddress(String address)
{
Map.MapDriver test = new Map.MapDriver(myMap);
//test.InitializeMap();
test.SearchAddressMap(address);
}
// try to get this on query setup
private void GetCurrentBusinessDetails()
{
if(searchDataGrid.SelectedIndex > -1)
{
Classes.Business currentBusiness = (Classes.Business)searchDataGrid.SelectedItem;
addressTextBox.Text = currentBusiness.address;
businessTextBox.Text = currentBusiness.name;
List<Object[]> newObject = query.GetCurrentBusinessCategories(currentBusiness.business_id);
StringBuilder sb = new StringBuilder();
foreach (Object[] item in newObject)
{
sb.Append(item[0] + "\n");
}
categoryTextBox.Text = sb.ToString();
sb = new StringBuilder();
newObject = query.GetCurrentBusinessAttributes(currentBusiness.business_id);
foreach (Object[] item in newObject)
{
if (!item[1].ToString().Equals("False"))
{
if (item[1].ToString().Equals("True"))
sb.AppendLine(item[0].ToString());
else
sb.AppendLine(item[0].ToString() + " : " + item[1].ToString());
}
//sb.Append(item[0] + " : " + item[1]+ "\n");
}
attributesTextBox.Text = sb.ToString();
sb = new StringBuilder();
DateTime today = DateTime.Now;
Classes.Hours newHours = query.GetCurrentBusinessHours(currentBusiness.business_id, today.ToString("dddd"));
if(newHours != null)
{
sb.Append("Today(" + newHours.hours_day + ")\n");
sb.Append("Opens: " + newHours.hours_open.ToString("hh:mm") + "\n");
sb.Append("Closed: " + newHours.hours_close.ToString("hh:mm"));
}
else
{
sb.Append("Today(" + today.ToString("dddd") + ")\n");
sb.Append("Opens: N/A \n");
sb.Append("Closed: N/A");
}
hoursTextBox.Text = sb.ToString();
AddPin(new Location(currentBusiness.latitute, currentBusiness.longtitude), currentBusiness.name, Colors.Green);
}
}
private void GetCurrentBusinessFriendReviews()
{
if (searchDataGrid.SelectedIndex > -1)
{
businessFriendReviewDataGrid.Items.Clear();
List<Object[]> newObject = query.GetFriends();
if (newObject != null)
{
Classes.Business tempBusiness = (Classes.Business)favoriteDataGrid.SelectedItem;
foreach (Object[] item in newObject)
{
Classes.Review newReview = query.GetBusinessFriendReviews(item[0].ToString());
if(newReview != null)
businessFriendReviewDataGrid.Items.Add(newReview);
}
}
}
}
private List<String> GetSearchCategories()
{
List<String> catList = new List<String>();
if (categorySearchListBox.Items.Count > 0)
foreach (String item in categorySearchListBox.Items)
catList.Add(item);
return catList;
}
private void InsertCheckins()
{
if (searchDataGrid.SelectedIndex > -1)
{
Classes.Business currentBusiness = (Classes.Business)searchDataGrid.SelectedItem;
query.InsertCheckins(currentBusiness);
}
}
private void GetBusinessReview()
{
if (searchDataGrid.SelectedIndex > -1)
{
Window newWindow = new GUISetup.WindowSetup("Review by Users",
query.GetBusinessReviews((Classes.Business)searchDataGrid.SelectedItem)).GetWindow();
newWindow.Show();
}
}
private void AddReview()
{
if (searchDataGrid.SelectedIndex > -1)
{
String indexx = (ratingComboBox.SelectedIndex + 1).ToString();
query.InsertReview(reviewTextBox.Text, (Classes.Business)searchDataGrid.SelectedItem, indexx);
}
}
private void AddToFavorites()
{
if (searchDataGrid.SelectedIndex > -1)
{
if (query.CheckFavoritesBeforeAdd() == 0)
{
query.InsertToFavorites((Classes.Business)searchDataGrid.SelectedItem);
LoadFavorites();
}
else
query.ShowStatusUpdate(0, "Already added, Add To Favorites");
}
}
private void LoadFavorites()
{
favoriteDataGrid.Items.Clear();
List<Object[]> businessList = query.GetUserFavorites();
if(businessList != null)
{
foreach (Object[] item in businessList)
{
Classes.Business tempBusiness = query.GetBusinessDetails(item[0].ToString());
favoriteDataGrid.Items.Add(tempBusiness);
}
}
}
private void RemoveFromFavorites()
{
if(favoriteDataGrid.SelectedIndex > -1)
{
Classes.Business tempBusiness = (Classes.Business)favoriteDataGrid.SelectedItem;
int updated = query.RemoveBusiness(tempBusiness.business_id);
if (updated == 1)
LoadFavorites();
}
}
private void GetCheckins()
{
if(searchDataGrid.SelectedIndex > -1)
{
List<Classes.Checkins> checkinList = new List<Classes.Checkins>();
List<Object[]> newObject = query.GetBusinessCheckinDays((Classes.Business)searchDataGrid.SelectedItem);
foreach(Object[] checkinDay in newObject)
{
checkinList.Add(query.GetBusinessCheckins((Classes.Business)searchDataGrid.SelectedItem,checkinDay[0].ToString()));
}
GUISetup.WindowSetup createChart = new GUISetup.WindowSetup("My New Chart", checkinList);
Window newChartWindow = createChart.GetWindow();
newChartWindow.Show();
}
}
private List<string> GetBusinessOrder()
{
int item = sortByComboBox.SelectedIndex;
List<string> orderList= query.GetOrder(item);
return orderList;
}
public void GetLoginBusinessDetails()
{
if(businessLogInListBox.SelectedIndex > -1)
{
Classes.Business tempBusiness = query.GetBusinessDetails(businessLogInListBox.SelectedItem.ToString());
businessLogInNameTextBox.Text = tempBusiness.name;
businessLogInAddressTextBox.Text = tempBusiness.address;
businessLogInStateTextBox.Text = tempBusiness.state;
businessLogInCityTextBox.Text = tempBusiness.city;
businessLogInZipTextBox.Text = tempBusiness.zipcode;
businessLogInStarsTextBox.Text = tempBusiness.stars.ToString();
businessLogInCountTextBox.Text = tempBusiness.review_count.ToString();
businessLogInRatingTextBox.Text = tempBusiness.review_rating.ToString();
businessLogInCheckinsTextBox.Text = tempBusiness.num_checkins.ToString();
businessLatitudeTextBox.Text = tempBusiness.latitute.ToString();
businessLongitudeTextBox.Text = tempBusiness.longtitude.ToString();
query.SetLoggedInBusiness(tempBusiness);
}
}
public void GetLoginBusinessReviews()
{
if (businessLogInListBox.SelectedIndex > -1 && query.GetLoggedInBusiness() != null)
{
Classes.Business currLoginBusiness = query.GetLoggedInBusiness();
List<Classes.Review> reviewList = query.GetBusinessReviews(currLoginBusiness);
if(reviewList.Count > 0)
{
foreach (Classes.Review item in reviewList)
{
businessLogInReviewDataGrid.Items.Add(item);
}
}
}
}
public void GetLoginBusinessCategories()
{
if (businessLogInListBox.SelectedIndex > -1 && query.GetLoggedInBusiness() != null)
{
Classes.Business currLoginBusiness = query.GetLoggedInBusiness();
List<Object[]> newObject = query.GetCategories(new List<String>() {currLoginBusiness.state,
currLoginBusiness.city, currLoginBusiness.zipcode });
if(newObject.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (Object[] item in newObject)
{
sb.AppendLine(item[0].ToString());
}
loggedInCategories.Text = sb.ToString();
}
}
}
public void GetLoginBusinessAttributes()
{
if (businessLogInListBox.SelectedIndex > -1 && query.GetLoggedInBusiness() != null)
{
Classes.Business currLoginBusiness = query.GetLoggedInBusiness();
List<Object[]> newObject = query.GetCurrentBusinessAttributes(currLoginBusiness.business_id);
if (newObject.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (Object[] item in newObject)
{
if(!item[1].ToString().Equals("False"))
{
if(item[1].ToString().Equals("True"))
sb.AppendLine(item[0].ToString());
else
sb.AppendLine(item[0].ToString() + " : " + item[1].ToString());
}
}
loggedInAttributes.Text = sb.ToString();
}
}
}
public void GetLoginBusinessHours(String currentDay)
{
if (businessLogInListBox.SelectedIndex > -1 && query.GetLoggedInBusiness() != null)
{
Classes.Business currLoginBusiness = query.GetLoggedInBusiness();
Classes.Hours newHour = query.GetCurrentBusinessHours(currLoginBusiness.business_id, currentDay);
StringBuilder sb = new StringBuilder();
if (newHour != null)
{
sb.Append("Opens: " + newHour.hours_open.ToString("hh:mm") + "\n");
sb.Append("Closed: " + newHour.hours_close.ToString("hh:mm"));
}
else
{
sb.Append("Opens: N/A \n");
sb.Append("Closed: N/A");
}
loggedInHours.Text = sb.ToString();
}
}
public void GetLogInBusinessCheckins()
{
if (businessLogInListBox.SelectedIndex > -1 && query.GetLoggedInBusiness() != null)
{
Classes.Business currLoginBusiness = query.GetLoggedInBusiness();
List<Classes.Checkins> checkinList = new List<Classes.Checkins>();
List<Object[]> newObject = query.GetBusinessCheckinDays(currLoginBusiness);
foreach (Object[] checkinDay in newObject)
{
checkinList.Add(query.GetBusinessCheckins(currLoginBusiness, checkinDay[0].ToString()));
}
GUISetup.WindowSetup createChart = new GUISetup.WindowSetup("My New Chart", checkinList);
Window newChartWindow = createChart.GetWindow();
newChartWindow.Show();
}
}
}
}
<file_sep>/Yelp2V18/YelpProject/SQL/IllegalInput.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.SQL
{
class IllegalInput
{
private SQLConstants cc = new SQLConstants();
private readonly List<String> testList = new List<String>() { "SELECT", "UNION", "FROM", "SET", "INSERT", "DELETE", "UPDATE", "--", "information_schema", "'" };
public bool SQLInjectionCheck(String input)
{
foreach (String item in testList)
{
if (input.ToLower().Trim().Contains(item.ToLower().Trim()))
return false;
}
return true;
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Business.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Business
{
public String business_id { get; set; }
public String name { get; set; }
public String city { get; set; }
public String state { get; set; }
public String zipcode { get; set; }
public String address { get; set; }
public double latitute { get; set; }
public double longtitude { get; set; }
public double stars { get; set; }
public double review_rating { get; set; }
public String business_distance { get; set; }
public double review_count { get; set; }
public int num_checkins { get; set; }
public Boolean is_open { get; set; }
public Business() { }
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Attributes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Attributes
{
public String attribute_name { get; set; }
public String attribute_value { get; set; }
public Attributes() { }
}
}
<file_sep>/Yelp2V18/YelpProject/Map/MapDriver.cs
using Microsoft.Maps.MapControl.WPF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Windows.Media;
using BingMapsRESTToolkit;
namespace YelpProject.Map
{
class MapDriver
{
private MapCore newMap;
private System.Windows.Controls.Label newLabel;
private double distance;
public MapDriver(MapCore map) {
newMap = map;
}
public MapDriver() { }
public void InitializeMap()
{
newMap.Mode = new AerialMode(true);
newMap.ZoomLevel = 2;
}
public void AddPin(Microsoft.Maps.MapControl.WPF.Location newLocation, String businessName, Color color)
{
SolidColorBrush brushColor = new SolidColorBrush(color);
newMap.ZoomLevel = 15;
newMap.Center = newLocation;
Pushpin newPin = new Pushpin()
{
Location = newLocation,
Content = businessName,
Background = brushColor,
Foreground = brushColor,
FontSize = 1
};
newPin.MouseEnter += NewPin_MouseEnter;
newPin.MouseLeave += NewPin_MouseLeave;
newPin.MouseDown += NewPin_MouseDown;
newPin.MouseDoubleClick += NewPin_MouseDoubleClick;
newMap.Children.Add(newPin);
}
public void SetUserLocation(Microsoft.Maps.MapControl.WPF.Location newLocation)
{
Pushpin newPin = new Pushpin()
{
Location = newLocation,
Content = "YOU ARE HERE",
Background = Brushes.DarkOrange,
Foreground = Brushes.DarkOrange,
FontSize = 1
};
newPin.MouseEnter += NewPin_MouseEnter;
newMap.Children.Add(newPin);
}
private void NewPin_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Pushpin tempPin = sender is Pushpin ? (Pushpin)sender : null;
AddPin(tempPin.Location, tempPin.Content.ToString(), Colors.Red);
newMap.Children.Remove(tempPin);
newLabel.Content = "";
newLabel.Background = null;
newLabel = new System.Windows.Controls.Label();
}
private void NewPin_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Pushpin tempPin = sender is Pushpin ? (Pushpin)sender : null;
tempPin.MouseEnter -= NewPin_MouseEnter;
tempPin.MouseLeave -= NewPin_MouseLeave;
tempPin.Background = Brushes.Green;
newLabel.Content = tempPin.Content + "\n (DOUBLE CLICK TO REMOVE)";
}
private void NewPin_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
Pushpin tempPin = sender is Pushpin ? (Pushpin)sender : null;
tempPin.Background = Brushes.Red;
newLabel.Content = "";
newLabel.Background = null;
}
private void NewPin_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
Pushpin tempPin = sender is Pushpin ? (Pushpin)sender : null;
tempPin.Background = Brushes.Aqua;
newLabel = new System.Windows.Controls.Label();
newLabel.Content = tempPin.Content + "\n (CLICK TO PIN)";
newLabel.Background = new SolidColorBrush(Colors.White);
MapLayer.SetPosition(newLabel, tempPin.Location);
newMap.Children.Add(newLabel);
}
public void ClearMap()
{
newMap.Children.Clear();
}
public async void SearchAddressMap(String query)
{
var request = new GeocodeRequest()
{
Query = query,
IncludeIso2 = true,
IncludeNeighborhood = true,
MaxResults = 25,
BingMapsKey = "<KEY>"
};
//Process the request by using the ServiceManager.
var response = await ServiceManager.GetResponseAsync(request);
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
AddPin(new Microsoft.Maps.MapControl.WPF.Location(result.Point.GetCoordinate().Latitude,
result.Point.GetCoordinate().Longitude), "", Colors.Blue);
}
}
public async void CalculateDistance(Microsoft.Maps.MapControl.WPF.Location a, Microsoft.Maps.MapControl.WPF.Location b)
{
SimpleWaypoint place1 = new SimpleWaypoint(a.Latitude,a.Longitude);
SimpleWaypoint place2 = new SimpleWaypoint(b.Latitude, b.Longitude);
var request = new DistanceMatrixRequest()
{
Origins = new List<SimpleWaypoint>() { place1 },
Destinations = new List<SimpleWaypoint>() { place2 },
DistanceUnits = DistanceUnitType.Miles,
BingMapsKey = "<KEY>"
};
var testDistc = await request.GetEuclideanDistanceMatrix();
distance = testDistc.GetDistance(0, 0);
}
public double GetDistance()
{
return distance;
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Friends.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Friends
{
public String user_id { get; set; }
public String friend_id { get; set; }
public Friends() { }
}
}
<file_sep>/Yelp2V18/YelpProject/GUISetup/WindowSetup.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.Controls.DataVisualization.Charting;
namespace YelpProject.GUISetup
{
class WindowSetup
{
private Window newWindow;
Chart newChart;
List<KeyValuePair<string, int>> chartData;
public WindowSetup(String title, List<Classes.Review> review) {
newWindow = new Window();
newWindow.Title = title;
newWindow.ResizeMode = 0;
newWindow.SizeToContent = SizeToContent.WidthAndHeight;
AddDataGrid(review);
}
public WindowSetup(String title, List<Classes.Checkins> checkinList)
{
newWindow = new Window();
newWindow.Title = title;
newWindow.ResizeMode = 0;
newWindow.SizeToContent = SizeToContent.WidthAndHeight;
MakeChart(checkinList);
}
private void AddDataGrid(List<Classes.Review> review)
{
DataGrid reviewDataGrid = new DataGrid();
StackPanel panel = new StackPanel();
SetDataBinding(reviewDataGrid);
foreach (Classes.Review item in review)
reviewDataGrid.Items.Add(item);
panel.Children.Add(reviewDataGrid);
newWindow.Content = panel;
}
private void SetDataBinding(DataGrid dg)
{
Classes.ClassConstants c = new Classes.ClassConstants();
GUISetup.DataGridSetup gridSetup = new DataGridSetup();
Dictionary<string, List<string>> binding = new Dictionary<string, List<string>>();
binding.Add("Date", new List<string>() { c.R_date, "100" });
binding.Add("User Name", new List<string>() { c.R_username, "100" });
binding.Add("Stars", new List<string>() { c.R_reviewStars, "100" });
binding.Add("Text", new List<string>() { c.R_text, "500" });
binding.Add("Funny", new List<string>() { c.R_funny, "65" });
binding.Add("Useful", new List<string>() { c.R_useful, "65" });
binding.Add("Cool", new List<string>() { c.R_cool, "65" });
gridSetup.AddColumnToGrid(dg, binding);
}
public void MakeChart(List<Classes.Checkins> checkinList)
{
newChart = new Chart() {
Height = 400,
Width = 1100,
Title = "Number of Checkins Per Day of the Week"
};
ColumnChart( checkinList);
ColumnSeries newSeries = new ColumnSeries()
{
ItemsSource = chartData,
DependentValuePath = "Value",
IndependentValuePath = "Key",
Title = "# of Checkins"
};
newChart.Series.Add(newSeries);
StackPanel panel = new StackPanel();
panel.Children.Add(newChart);
newWindow.Content = panel;
}
public void ColumnChart(List<Classes.Checkins> checkinList)
{
Classes.Checkins GetSort = new Classes.Checkins();
checkinList = GetSort.SortDays(checkinList);
chartData = new List<KeyValuePair<string, int>>();
if(checkinList != null)
{
foreach (Classes.Checkins item in checkinList)
{
chartData.Add(new KeyValuePair<string, int>(item.checkin_day, item.checkin_count));
}
}
newChart.DataContext = chartData;
}
public Window GetWindow()
{
return newWindow;
}
}
}
<file_sep>/DatabaseInserter/DansTest/Program.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DansTest
{
class Program
{
static void Main(string[] args)
{
string screwedUpReviews = string.Empty;
// CHANGE THIS FOR YOUR DATABASE INFO. DANE'S IS PORT 5433 SO IT WAS ADDED
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;User Id=postgres;Password=<PASSWORD>;Database=Milestone1DB;Port=5433;");
conn.Open();
// YOU CAN HARDCORE FOLDER/FILE NAME HERE. Make sure to use the @ at the start so the \ aren't all fucked up
// Format: @"C:\Users\User\Desktop\team4\JSONInserter\JSONInserter\yelp_user.sql"
using (StreamReader sr = new StreamReader(@"C:\Users\User\Desktop\team4\JSONInserter\JSONInserter\yelp_review.SQL"))
{
string line;
int rowsInput = 0;
while ((line = sr.ReadLine()) != null)
{
if (line[line.Length-1] == ';')
{
line = line.Substring(0, line.Length - 1);
line += " ON CONFLICT do nothing;";
screwedUpReviews += line;
var cmd = new NpgsqlCommand(screwedUpReviews, conn);
cmd.ExecuteNonQuery();
Console.Write("Rows Input: " + ++rowsInput + "\r");
screwedUpReviews = string.Empty;
}
else
{
screwedUpReviews += line;
}
}
}
// Close connection
conn.Close();
Console.Write("\nALL DONE");
Console.ReadKey();
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Review.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Review
{
public String review_id { get; set; }
public String review_text { get; set; }
public String review_date { get; set; }
public String user_id { get; set; }
public String review_username { get; set; }
public int review_stars { get; set; }
public int useful_vote { get; set; }
public int funny_vote { get; set; }
public int cool_vote { get; set; }
public String actual_review_date { get; set; }
public Review() { }
}
}
<file_sep>/Yelp2V18/YelpProject/GUISetup/DialogSetup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace YelpProject.GUISetup
{
class DialogSetup
{
public DialogSetup(int status, String text) {
OpenDialog(status,text);
}
private void OpenDialog(int status, String text)
{
MessageBoxButton button = MessageBoxButton.OK;
string caption = "Status Update";
if (status != 0)
{
string messageBoxText = text + " Success!";
MessageBoxImage icon = MessageBoxImage.Information;
MessageBox.Show(messageBoxText, caption, button, icon);
}
else
{
string messageBoxText = text + " Fail!";
MessageBoxImage icon = MessageBoxImage.Error;
MessageBox.Show(messageBoxText, caption, button, icon);
}
}
}
}
<file_sep>/Yelp2V18/YelpProject/SQL/SQLQueries.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.SQL
{
class SQLQueries
{
private SQLConnString db3String = new SQLConnString("Milestone1DB", "Fart", "5433");
private SQLConstants c = new SQLConstants();
public SQLQueries() { }
public List<Object[]> SQLSelectQuery(Dictionary<String, List<String>> queryDictionary)
{
List<Object[]> ObjList = new List<Object[]>();
using (var conn = new NpgsqlConnection(db3String.BuildConnString()))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = SimpleCommandString(queryDictionary);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Object[] objArray = new Object[reader.FieldCount];
reader.GetValues(objArray);
ObjList.Add(objArray);
}
}
}
conn.Close();
}
return ObjList;
}
// return tuples changed, if 0 we can use an insert, if not the dont....
public int SQLNonQuery(Dictionary<String, List<String>> queryDictionary)
{
int updated = 0;
using (var conn = new NpgsqlConnection(db3String.BuildConnString()))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = GetCommandString(queryDictionary);
updated = cmd.ExecuteNonQuery();
}
conn.Close();
}
return updated;
}
private String SimpleCommandString(Dictionary<String, List<String>> queryDictionary)
{
List<String> projectionList = queryDictionary.ContainsKey(c.SQL_PROJECT) ? queryDictionary[c.SQL_PROJECT] : null;
List<String> conditionList = queryDictionary.ContainsKey(c.SQL_COND) ? queryDictionary[c.SQL_COND] : null;
List<String> fromList = queryDictionary.ContainsKey(c.SQL_FROM) ? queryDictionary[c.SQL_FROM] : null;
List<String> whereList = queryDictionary.ContainsKey(c.SQL_WHERE) ? queryDictionary[c.SQL_WHERE] : null;
List<String> orderList = queryDictionary.ContainsKey(c.SQL_ORDER) ? queryDictionary[c.SQL_ORDER] : null;
String queryString = "";
String specialCaseString = "";
if (projectionList != null)
{
queryString += projectionList[0] + " ";
for (int i = 1; i < projectionList.Count; i++)
{
if (i == projectionList.Count - 1)
queryString += projectionList[i] + " ";
else
queryString += projectionList[i] + ",";
}
}
if (fromList != null)
{
queryString += " " + fromList[0] +" ";
for (int i = 1; i < fromList.Count; i++)
{
if (i == fromList.Count-1 && fromList.Count > 2)
queryString += "natural join " + fromList[i] + " ";
else
queryString += fromList[i] + " ";
}
}
if(queryDictionary.ContainsKey(c.SQL_ATTR) || queryDictionary.ContainsKey(c.SQL_CAT))
{
List<String> specialCase = SpecialCase(queryDictionary);
queryString += specialCase[0];
specialCaseString += specialCase[1];
}
if (whereList != null)
{
if (!queryDictionary.ContainsKey(c.SQL_ATTR) && !queryDictionary.ContainsKey(c.SQL_CAT) && !queryDictionary.ContainsKey(c.SQL_FROM))
queryString += "from business as B ";
queryString += " where ";
for (int i = 0; i < conditionList.Count; i++)
{
if (i == conditionList.Count - 1)
queryString += whereList[i] + " = '" + conditionList[i] + "' ";
else
queryString += whereList[i] + " = '" + conditionList[i] + "' " + " and ";
}
queryString += specialCaseString;
}
if (orderList != null)
{
queryString += " " + orderList[0] + " ";
for (int i = 2; i < orderList.Count; i++)
{
if (i == orderList.Count - 1)
queryString += orderList[i] + " ";
else
queryString += orderList[i] + ",";
}
queryString += orderList[1];
}
return queryString;
}
private List<String> SpecialCase(Dictionary<String, List<String>> queryDictionary)
{
List<String> categoryList = queryDictionary.ContainsKey(c.SQL_CAT) ? queryDictionary[c.SQL_CAT] : null;
List<String> attributeList = queryDictionary.ContainsKey(c.SQL_ATTR) ? queryDictionary[c.SQL_ATTR] : null;
List<String> attrValList = queryDictionary.ContainsKey(c.SQL_VAL) ? queryDictionary[c.SQL_VAL] : null;
String queryString = "";
String specialCaseString = "";
if (categoryList != null)
{
queryString += "from categories as C0";
for (int i = 0; i < categoryList.Count; i++)
{
queryString += " inner join categories as C" + (i + 1) + " on C" + i + ".business_id = C" + (i + 1) + ".business_id";
specialCaseString += " and C" + i + ".category_name = '" + categoryList[i] + "'";
}
queryString += " inner join business as B on B.business_id = C0.business_id ";
}
if (attributeList != null)
{
queryString += categoryList != null ? "inner join attributes as A0 on A0.business_id = B.business_id" : "from attributes as A0";
//queryString += "from attributes as A0";
for (int i = 0; i < attributeList.Count; i++)
{
queryString += " inner join attributes as A" + (i + 1) + " on A" + i + ".business_id = A" + (i + 1) + ".business_id";
specialCaseString += " and A" + i + ".attr_name = '" + attributeList[i] + "' and A" + i + ".attr_value ='" + attrValList[i] + "'";
}
queryString += categoryList != null ? "" : " inner join business as B on B.business_id = A0.business_id ";
}
return new List<String>() { queryString, specialCaseString};
}
private String GetCommandString(Dictionary<String, List<String>> queryDictionary)
{
List<String> conditionList = queryDictionary.ContainsKey(c.SQL_COND) ? queryDictionary[c.SQL_COND] : null;
List<String> fromList = queryDictionary.ContainsKey(c.SQL_FROM) ? queryDictionary[c.SQL_FROM] : null;
List<String> whereList = queryDictionary.ContainsKey(c.SQL_WHERE) ? queryDictionary[c.SQL_WHERE] : null;
List<String> attrValList = queryDictionary.ContainsKey(c.SQL_VAL) ? queryDictionary[c.SQL_VAL] : null;
List<String> setList = queryDictionary.ContainsKey(c.SQL_SET) ? queryDictionary[c.SQL_SET] : null;
String queryString = "";
if (fromList != null)
{
for (int i = 0; i < fromList.Count; i++)
{
queryString += fromList[i] + " ";
}
}
if(attrValList != null && setList == null)
{
queryString += attrValList[0] + "( ";
for (int i = 1; i < attrValList.Count; i++)
{
if (i == attrValList.Count - 1)
queryString += " '" + attrValList[i] + "'" + ") ";
else
queryString += " '" + attrValList[i] + "'" + ",";
}
}
if(setList != null)
{
queryString += setList[0] + " ";
for (int i = 1; i < setList.Count; i++)
{
if(attrValList[0].Equals("S"))
{
attrValList[i] = "'" + attrValList[i] + "'";
}
if (i == setList.Count - 1)
queryString += setList[i] + " = " + attrValList[i] + " ";
else
queryString += setList[i] + " = " + attrValList[i] + ", ";
}
}
if (whereList != null)
{
queryString += whereList[0] + " ";
conditionList.Insert(0, null);
for (int i = 1; i < conditionList.Count; i++)
{
if (i == conditionList.Count - 1)
queryString += whereList[i] + " = '" + conditionList[i] + "' ";
else
queryString += whereList[i] + " = '" + conditionList[i] + "' and ";
}
}
return queryString;
}
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/ClassConstants.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class ClassConstants
{
//Business class constants
public readonly String B_id = "business_id";
public readonly String B_name = "name";
public readonly String B_city = "city";
public readonly String B_state = "state";
public readonly String B_zipcode = "zipcode";
public readonly String B_latitude = "latitude";
public readonly String B_longitude = "longitude";
public readonly String B_address = "address";
public readonly String B_reviewCount = "review_count";
public readonly String B_numCheckins = "num_checkins";
public readonly String B_reviewRating = "review_rating";
public readonly String B_isOpen = "is_open";
public readonly String B_stars = "stars";
public readonly String B_distance = "business_distance";
//Business table name
public readonly String B_table = "business";
//Business special case
public readonly String SPEC_id = "B.business_id";
//User class constants
public readonly String U_id = "user_id";
public readonly String U_name = "username";
public readonly String U_avgStars = "average_stars";
public readonly String U_cool = "cool";
public readonly String U_funny = "funny";
public readonly String U_useful = "useful";
public readonly String U_fans = "fans";
public readonly String U_reviewCount = "review_count";
public readonly String U_yelpingSince = "yelping_since";
public readonly String U_latitude = "user_latitude";
public readonly String U_longitude = "user_longitude";
//User table name
public readonly String U_table = "userinfo";
//Review class constants
public readonly String R_id = "review_id";
public readonly String R_reviewStars = "review_stars";
public readonly String R_date = "review_date";
public readonly String R_actDate = "actual_review_date";
public readonly String R_user = "user_id";
public readonly String R_username = "review_username";
public readonly String R_text = "review_text";
public readonly String R_cool = "cool_vote";
public readonly String R_funny = "funny_vote";
public readonly String R_useful = "useful_vote";
//Review table name
public readonly String R_table = "review";
//Category class constants
public readonly String CAT_name = "category_name";
//Category table name
public readonly String CAT_table = "categories";
//Attribute class constants
public readonly String ATTR_name = "attr_name";
public readonly String ATTR_val = "attr_value";
//Attribute table name
public readonly String ATTR_table = "attributes";
//Hours class constants
public readonly String HRS_day = "hours_day";
public readonly String HRS_close = "hours_closed";
public readonly String HRS_open = "hours_open";
//Hours table name
public readonly String HRS_table = "hours";
//Checkins class constants
public readonly String CHK_day = "checkin_day";
public readonly String CHK_time = "checkin_time";
public readonly String CHK_count = "checkin_count";
//Checkins table name
public readonly String CHK_table = "checkins";
//Friends class constants
public readonly String FR_uid = "user_id";
public readonly String FR_id = "friend_id";
public readonly String FR_table = "friends";
//Favorites class constants
public readonly String FAV_uid = "user_id";
public readonly String FAV_bid = "business_id";
public readonly String FAV_table = "favorites";
//Attribute attr_names
public readonly String ATTR_card = "BusinessAcceptsCreditCards";
public readonly String ATTR_reservation = "RestaurantsReservations";
public readonly String ATTR_wheelchair = "WheelchairAccessible";
public readonly String ATTR_outdoor = "OutdoorSeating";
public readonly String ATTR_kids = "GoodForKids";
public readonly String ATTR_groups = "RestaurantsGoodForGroups";
public readonly String ATTR_delivery = "RestaurantsDelivery";
public readonly String ATTR_takeout = "RestaurantsTakeOut";
public readonly String ATTR_wifi = "WiFi";
public readonly String ATTR_bike = "BikeParking";
public readonly String ATTR_breakfast = "breakfast";
public readonly String ATTR_brunch = "brunch";
public readonly String ATTR_lunch = "lunch";
public readonly String ATTR_dinner = "dinner";
public readonly String ATTR_dessert = "dessert";
public readonly String ATTR_latenight = "latenight";
public readonly String ATTR_pricerange = "RestaurantsPriceRange2";
//Business Order Combo Box constants
public readonly String ORD_name = "name";
public readonly String ORD_stars = "stars";
public readonly String ORD_reviwed = "review_count";
public readonly String ORD_rating = "review_rating";
public readonly String ORD_checkin = "num_checkins";
public readonly String ORD_distance = "business_distance";
}
}
<file_sep>/Yelp2V18/YelpProject/Classes/Checkins.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.Classes
{
class Checkins
{
enum Day
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
public String checkin_day { get; set; }
public DateTime checkin_time { get; set; }
public int checkin_count { get; set; }
public Checkins() { }
public List<Checkins> SortDays(List<Checkins> unorderedDays)
{
unorderedDays.Sort((a, b) => a.CompareTo(b));
return unorderedDays;
}
private int CompareTo(Checkins b)
{
Day thisDay;
Day compareDay;
Enum.TryParse(this.checkin_day, out thisDay);
Enum.TryParse(b.checkin_day, out compareDay);
return thisDay < compareDay ? -1 : 1;
}
}
}
<file_sep>/Yelp2V18/YelpProject/StringHasher/SimpleStringHasher.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YelpProject.StringHasher
{
class SimpleStringHasher
{
private int hashLength = 22;
private String hashChars = "0123456789qwertyuioplkjhgfdsazxcvbnmMNBVCXZASDFGHJKLPOQIWUEYRT-_!";
Random rand = new Random();
public String GetHash()
{
String code = "";
for (int i = 0; i < hashLength; i++)
{
code += hashChars[rand.Next(hashChars.Length)];
}
return code;
}
}
}
| 88390d238050cff96d694e94b800193077dd5de3 | [
"C#"
] | 21 | C# | Danejerosa/Projects | fb81f0b6777bcd67af3283f3c6098276e9b94fdc | fbb4f219b85c2a2564368330eb7799813c5a0bd4 |
refs/heads/master | <repo_name>xkWeiMeng/X-1<file_sep>/OurGame/Scenes.h
#pragma once
//包含此头文件即可包含所有场景的声明。
#include"Scene.h"
#include"HomeScene.h"
#include"AboutScene.h"
#include"GamingScene.h"
#include "DesignMapScene.h"
#include "GameSettingScene.h"
<file_sep>/OurGame/Scene.h
#pragma once
#include"DirectX.h"
#include"DirectSound.h"
//所有场景的基类,用于统一接口调用
class Scene
{
public:
virtual ~Scene() {};
//场景的初始化函数,在切换场景时会被执行一次
virtual bool Init() { return true; };
//场景的关闭函数,在切换场景时会被执行一次
virtual void End() {};
//场景的渲染函数
virtual void Render() {};
//场景的逻辑更新函数
virtual void Update() {};
};<file_sep>/OurGame/Sound.h
#pragma once
#include"Global.h"
#include"DirectX.h"
#include"DirectSound.h"
namespace Sound {
void Sound_Init();
extern CSound*Start;
extern CSound*GameOver;
extern CSound*Moving;
extern CSound*Stop;
extern CSound*BGM;
extern CSound*PlayerBoom;
}
<file_sep>/OurGame/GamingScene.h
#pragma once
#include<fstream>
#include<vector>
#include"Scene.h"
#include"DirectX.h"
#include"Global.h"
#include"Sound.h"
#include"GameMain.h"
enum Dirction {
up,
right,
below,
lift
};
class Bullet {
public:
SPRITE bullet;
int Shooter;//子弹射击者
int Speed;//子弹速度
int Dir;//子弹方向
float MovedPixel;
unsigned long ID;
int BoomFlag;
int PowerLevel;
Bullet(int,int ,int,int,int,int);//子弹初始化
bool Logic();//子弹碰撞检测
bool Draw();
int FlickerFrame;
int LastFrametime;
private:
};
struct BulletList {
Bullet*bullet;
BulletList*next;
BulletList*last;
};
struct BulletListHead {
BulletList*next;
};
class GamingScene:public Scene
{
public:
virtual bool Init();
virtual void End();
virtual void Render();
virtual void Update();
};
class Player {
public:
SPRITE player;
Player();
int FlickerFrame;
int Lift;;//玩家生命数
int Health_Point;//玩家血量
int BulletSpeed;//玩家子弹飞行速度
int Speed;//移动速度
int Attack_Speed;//攻击速度
int Dir;//玩家方向
int Grade;//玩家等级
int PowerLevel;
bool Alive;//存在标志
bool FlashFlag;//闪光标志
bool Shoot(int,int);
bool Draw();
bool Logic(int);
bool GetHurt(int power);
void Born();
};
class Player2 :public Player
{
public:
Player2();
bool Draw();
bool Logic(int);
void Born();
};
class Enemy :public Player
{
public:
Enemy(int x,int y,int speed,int hp,int as,int,int);
bool Draw();
bool Logic(bool);
int DamageFlag;//毁坏标志
bool MoveStage;//移动状态
bool CrashingFlag;//碰撞标志
unsigned long ID;
int Time;
};
struct EnemyList {
Enemy *enemy;
EnemyList*last, *next;
};
struct EnemyListHead {
EnemyList*next;
};
class BoomFire {
public:
int x;
int y;
unsigned long ID;
int Dir;
int Time;
int WhatBoom;
bool Draw();
void Logic();
BoomFire(int ,int ,int ,int);
};
struct BoomList{
BoomFire*boom;
BoomList*last, *next;
};
struct BoomListHead {
BoomList*next;
};
//无用对象链表
struct UselessObj{
unsigned long ID;
UselessObj*next;
};
struct UselessObjHead
{
UselessObj*next;
};
struct RectList
{
RECT*rect;
RectList*last, *next;
};
struct RectListHead {
RectList*next;
};
class MapPiece {
public:
int X;
int Y;
RectListHead*rectlisthead;
MapPiece();
void Draw();
void CreateMapRect(int x, int y, int wight, int hight);
bool Create(int mapid);
bool BeingCrash(bool,RECT&rect,int dir,int x,int y);
int PECrach(int dir,RECT&rect);
};
struct MapPieceList
{
MapPiece*mappiece;
MapPieceList*last, *next;
};
struct MapPieceListHead {
MapPieceList*next;
};
<file_sep>/OurGame/AboutScene.h
#pragma once
#include"Scene.h"
#include"DirectX.h"
#include"Global.h"
#include"Sound.h"
class AboutScene : public virtual Scene
{
public:
bool Init();
void End();
void Render();
void Update();
private:
LPDIRECT3DSURFACE9 background = NULL;
LPDIRECT3DTEXTURE9 Mountain = NULL;
LPDIRECT3DTEXTURE9 Could1 = NULL;
LPDIRECT3DTEXTURE9 Could2 = NULL;
LPDIRECT3DTEXTURE9 Could3 = NULL;
LPDIRECT3DTEXTURE9 Feiting = NULL;
};
<file_sep>/OurGame/WinMain.cpp
#include <windows.h>
#include <iostream>
#include <time.h>
#include"Global.h"
#include"GameMain.h"
#include "winres.h"
#include"resource1.h"
using namespace std;
HWND window;
HDC device;
bool Gameover = false;
// Window callback function
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static RECT rect;
switch (message)
{
case WM_DESTROY:
Gameover = true;
PostQuitMessage(0);
break;
case WM_PAINT:
//获取窗口在屏幕的坐标
if (!Global::Window::FullScreen)
{
GetClientRect(hWnd, &rect);
Global::Window::x = rect.left;
Global::Window::y = rect.top;
}
if (!Gameover)
Game_Render(hWnd, device);
break;
/*case WM_SIZE://不绘制标题栏
LONG_PTR Style = ::GetWindowLongPtr(hWnd, GWL_STYLE);
Style = Style &~WS_CAPTION &~WS_SYSMENU &~WS_SIZEBOX;
::SetWindowLongPtr(hWnd, GWL_STYLE, Style);
break;*/
case WM_ACTIVATE:
Global::Window::isActity = !(wParam == WA_INACTIVE);
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// MyRegiserClass function sets program window properties
ATOM MyRegisterClass(HINSTANCE hInstance)
{
//create the window class structure
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
//fill the struct with info
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor =NULL;
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = Global::Window::GameTitle.c_str();
wc.hIconSm = NULL;
//set up the window with the class info
return RegisterClassEx(&wc);
}
// Helper function to create the window and refresh it
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
//create a new window
long MetricsX = ::GetSystemMetrics(SM_CXSCREEN);//获取显示器分辨率用于让窗口居中
long MetricsY = ::GetSystemMetrics(SM_CYSCREEN);
//create a new window
//根据用户屏幕分辨率分配游戏窗口大小
const float GameY_Screen_rate = 0.8888889;
const float GameY_GameX_rate = 0.9375;
int GameScreenHeight = MetricsY*GameY_Screen_rate;
int GameScreenWidth = GameScreenHeight / GameY_GameX_rate;
Global::Window::ScreenHeight = GameScreenHeight;
Global::Window::ScreenWidth = GameScreenWidth;
window = CreateWindow(
Global::Window::GameTitle.c_str(), //window class
Global::Window::GameTitle.c_str(), //title bar
WS_OVERLAPPEDWINDOW, //window style
MetricsX / 2 - GameScreenWidth / 2, //x position of window
MetricsY / 2 - GameScreenHeight / 2, //y position of window
GameScreenWidth, //width of the window
GameScreenHeight, //height of the window
NULL, //parent window
NULL, //menu
hInstance, //application instance
NULL); //window parameters
//was there an error creating the window?
if (window == 0) return 0;
//display the window
ShowWindow(window, nCmdShow);
UpdateWindow(window);
//get device context for drawing
device = GetDC(window);
return 1;
}
DWORD currentTime = 0;
DWORD lastCurrentTime = 0;
int currentCount = 0;
int refreshTime = 0;
// Entry point function
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
//create window
MyRegisterClass(hInstance);
if (!InitInstance(hInstance, nCmdShow)) return -1;
//initialize the game
if (!Game_Init(window)) {
ShowMessage("游戏初始化失败");
return -1;
}
while (!Gameover)
{
//如果有Windows消息则优先处理
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
//如果窗口没有激活,并且也不允许后台运行游戏时,就跳过所有逻辑处理
if (Global::Window::isActity == false) {
if (Global::Window::EnableBackgroundRunning == false)
continue;
}
//获取当前时间,精确到毫秒
currentTime = timeGetTime();
//-------计算帧率--------
//每执行一次循环currentCount自加1
currentCount++;
//相比上一次循环过了1秒钟后,currentCount即为当前的FPS帧率
if (currentTime > lastCurrentTime + 1000)
{
Global::Debug::currentFPS = currentCount;
currentCount = 0;
lastCurrentTime = currentTime;
}
//-----------------------
//设定逻辑刷新速度为指定的帧率,当与上一次刷新的时间间隔超过了帧率的倒数时,执行Update
if (currentTime > refreshTime + 1000.0f / Global::Window::targetFps)
{
refreshTime = currentTime;
Game_Update(window);//DirectX循环
}
//其余时间全用来渲染
Game_Render(window, device);//DirectX渲染
}
}
//释放资源
Game_Free(window, device);
return msg.wParam;
}
//结束游戏
void EndApplication()
{
PostMessage(window, WM_DESTROY, 0, 0);
}
//弹出一个以游戏标题为标题,带有一个确定按钮的消息框
void ShowMessage(string text)
{
MessageBox(window, text.c_str(), Global::Window::GameTitle.c_str(), MB_OK);
}
<file_sep>/OurGame/Sound.cpp
#include "Sound.h"
namespace Sound {
CSound*Start;
CSound*GameOver;
CSound*Moving;
CSound*Stop;
CSound*BGM;
CSound*PlayerBoom;
}
using namespace Sound;
void Sound::Sound_Init()
{
Start=LoadSound(Resource::Sound_Rescource::Start);
if (Start == NULL)
ShowMessage("开始声音装载失败");
Moving = LoadSound(Resource::Sound_Rescource::Moving);
if (Moving == NULL)
ShowMessage("坦克移动声音装载失败");
Stop = LoadSound(Resource::Sound_Rescource::Stop);
if (Stop == NULL)
ShowMessage("坦克停止引擎声音装载失败");
BGM = LoadSound(Resource::Sound_Rescource::BGM);
if (BGM == NULL)
ShowMessage("BGM装载失败");
PlayerBoom= LoadSound(Resource::Sound_Rescource::PlayerBoom);
if (PlayerBoom == NULL)
ShowMessage("玩家爆炸声音装载失败");
/*
GameOver = LoadSound(Resource::Sound_Rescource::GameOver);
if (GameOver == NULL)
ShowMessage("游戏失败声音装载失败");
*/
}
<file_sep>/OurGame/Resource.h
#pragma once
#include<iostream>
#include"DirectX.h";
using namespace std;
//所有资源的路径
namespace Resource {
namespace Home {
char* const Backgroud = "Resources\\Home\\UI.bmp";
//char* const BGM = "Resources\\Home\\3.wav";
const D3DCOLOR SelectedColor = D3DCOLOR_XRGB(255, 128, 128);
const D3DCOLOR UnselectedColor = D3DCOLOR_XRGB(64, 64, 64);
char* const OptionsStr[] = { "单人游戏","双人游戏","设计地图","游戏设定","关于我们" };
}
namespace Cursor {
char* const Normal = "Resources\\Cursor\\光标.png";
}
namespace About {
char* const Backgroud = "Resources\\About\\Background.jpg";
char* const BKG = "Resources\\About\\山景.bmp";
char* const Cloud1 = "Resources\\About\\云1.png";
char* const Cloud2 = "Resources\\About\\云2.png";
char* const Cloud3 = "Resources\\About\\云3.png";
char* const Feiting = "Resources\\About\\飞艇.tga";
}
namespace Sound_Rescource {
char* const Start = "Resources\\Sound\\开始1.wav";
char*const Moving = "Resources\\Sound\\坦克移动.wav";
char*const Stop = "Resources\\Sound\\坦克停止移动.wav";
char*const GameOver = "Resources\\Sound\\游戏结束.aif";
char*const BGM = "Resources\\Sound\\bgm.wav";
char*const PlayerBoom = "Resources\\Sound\\爆炸.wav";
}
namespace Texture {
char*const Flag = "Resources\\Texture\\旗子.bmp";
char*const Something = "Resources\\Texture\\杂项.bmp";
char*const Tile = "Resources\\Texture\\砖.bmp";
char*const Player_1 = "Resources\\Texture\\wxz.png";
char*const Player_2 = "Resources\\Texture\\玩家二.bmp";
char*const Bullet = "Resources\\Texture\\子弹.bmp";
char*const Boom1 = "Resources\\Texture\\爆炸一.bmp";
char*const Boom2 = "Resources\\Texture\\爆炸二.bmp";
char*const Enemy = "Resources\\Texture\\敌人.bmp";
char*const Award = "Resources\\Texture\\奖励.bmp";
char*const GameOver = "Resources\\Texture\\游戏结束.bmp";
char*const Shield = "Resources\\Texture\\盾牌.bmp";
char*const Hole = "Resources\\Texture\\孔.bmp";
char*const Number = "Resources\\Texture\\数字.bmp";
char*const GameSetting = "Resources\\Texture\\GameSetting.png";
}
}
<file_sep>/OurGame/DebugTools.cpp
#include"DebugTools.h"
#include"DirectX.h"
namespace DebugTools {
string int2str(int int_temp) {
stringstream stream;
stream << int_temp;
return stream.str();
}
void PrintMouseInfo() {
static LPD3DXFONT font = MakeFont("ËÎÌå", 18);
string text;
text += "Total FPS£º";
text += int2str(Global::Debug::currentFPS);
text += " Logical FPS£º";
text += int2str(Global::Window::targetFps);
text += "\n";
text += "Êó±ê X£º";
text += int2str(Mouse_X());
text += " Y: ";
text += int2str(Mouse_Y());
text += "\n";
FontPrint(font, 0, 0, text, D3DCOLOR_XRGB(255, 255, 255));
}
}<file_sep>/OurGame/DebugTools.h
#pragma once
namespace DebugTools {
void PrintMouseInfo();
}<file_sep>/OurGame/DirectX.h
#pragma once
//header files
#define WIN32_EXTRA_LEAN
#define DIRECTINPUT_VERSION 0x0800
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <dinput.h>
#include <xinput.h>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <io.h>
#include <algorithm>
#include "Global.h"
using namespace std;
//libraries
#pragma comment(lib,"winmm.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"gdi32.lib")
#pragma comment(lib,"dxguid.lib")
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"xinput.lib")
#pragma comment(lib,"legacy_stdio_definitions.lib")
//macro to detect key presses
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
//Direct3D objects
extern LPDIRECT3D9 d3d;
extern LPDIRECT3DDEVICE9 d3dDev;
extern LPDIRECT3DSURFACE9 backBuffer;
extern LPD3DXSPRITE spriteObj;
//sprite structure
struct SPRITE
{
bool alive; //added ch14
float x, y;
int frame, columns;
int width, height;
float scaling, rotation;
int startframe, endframe;
int starttime, delay;
int direction;
float velx, vely;
D3DCOLOR color;
SPRITE()
{
frame = 0;
columns = 1;
width = height = 0;
scaling = 1.0f;
rotation = 0.0f;
startframe = endframe = 0;
direction = 1;
starttime = delay = 0;
velx = vely = 0.0f;
color = D3DCOLOR_XRGB(255, 255, 255);
}
};
bool Direct3D_Init(HWND hwnd, int width, int height, bool fullscreen);
void Direct3D_Shutdown();
LPDIRECT3DSURFACE9 LoadSurface(string filename);
void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source);
LPDIRECT3DTEXTURE9 LoadTexture(string filename, D3DCOLOR transcolor = D3DCOLOR_XRGB(0, 0, 0));
void Sprite_Draw_Frame(LPDIRECT3DTEXTURE9 texture, int destx, int desty,
int framenum, int framew, int frameh, int columns);
void Sprite_Animate(int &frame, int startframe, int endframe, int direction, int &starttime, int delay);
void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, int width, int height,
int frame = 0, int columns = 1, float rotation = 0.0f,
float scaleW = 1.0f, float scaleH = 1.0f, D3DCOLOR color = D3DCOLOR_XRGB(255, 255, 255));
void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, RECT*rect,
int frame, int columns, float rotation, float scaleW, float scaleH, D3DCOLOR color);
void Sprite_Transform_Draw(LPDIRECT3DTEXTURE9 image, int x, int y, int width, int height,
int frame = 0, int columns = 1, float rotation = 0.0f, float scaling = 1.0f,
D3DCOLOR color = D3DCOLOR_XRGB(255, 255, 255));
//bounding box collision detection
int Collision(SPRITE sprite1, SPRITE sprite2);
//distance based collision detection
bool CollisionD(SPRITE sprite1, SPRITE sprite2);
//DirectInput对象
extern LPDIRECTINPUT8 dInput;
//鼠标设备
extern LPDIRECTINPUTDEVICE8 diMouse;
//键盘设备
extern LPDIRECTINPUTDEVICE8 diKeyboard;
////鼠标状态
//extern DIMOUSESTATE mouseState;
//手柄状态
extern XINPUT_GAMEPAD controllers[4];
//鼠标坐标
extern POINT mousePoint;
#define MLButton 0
#define MRButton 1
#define MMButton 2
bool Key_Up(int);
bool DirectInput_Init(HWND);
void DirectInput_Update(HWND);
void DirectInput_Shutdown();
bool Key_Down(int);
int Mouse_Button(int);
int Mouse_X();
int Mouse_Y();
void XInput_Vibrate(int contNum = 0, int amount = 65535);
bool XInput_Controller_Found();
//font functions
LPD3DXFONT MakeFont(string name, int size);
void FontPrint(LPD3DXFONT font, int x, int y, string text, D3DCOLOR color = D3DCOLOR_XRGB(255, 255, 255));
//DirectSound code added in chapter 11
#include "DirectSound.h"
#pragma comment(lib,"dsound.lib")
#pragma comment(lib,"dxerr.lib")
//primary DirectSound object
extern CSoundManager *dsound;
//function prototypes
bool DirectSound_Init(HWND hwnd);
void DirectSound_Shutdown();
CSound *LoadSound(string filename);
void PlaySound(CSound *sound);
void LoopSound(CSound *sound);
void StopSound(CSound *sound);
//define the MODEL struct
struct MODEL
{
LPD3DXMESH mesh;
D3DMATERIAL9* materials;
LPDIRECT3DTEXTURE9* textures;
DWORD material_count;
D3DXVECTOR3 translate;
D3DXVECTOR3 rotate;
D3DXVECTOR3 scale;
MODEL()
{
material_count = 0;
mesh = NULL;
materials = NULL;
textures = NULL;
translate = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
rotate = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
scale = D3DXVECTOR3(1.0f, 1.0f, 1.0f);
}
};
//3D mesh function prototypes
void DrawModel(MODEL *model);
void DeleteModel(MODEL *model);
MODEL *LoadModel(string filename);
bool FindFile(string *filename);
bool DoesFileExist(const string &filename);
void SplitPath(const string& inputPath, string* pathOnly, string* filenameOnly);
void SetCamera(float posx, float posy, float posz, float lookx = 0.0f, float looky = 0.0f, float lookz = 0.0f);
<file_sep>/OurGame/Global.h
#pragma once
#include<iostream>
#include<Windows.h>
#include"Resource.h"
#include"WinMain.h"
#include"DirectX.h"
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } //释放资源
using namespace std;
enum GAME_STATE
{
//无任何场景(初始状态)
None = 0,
//欢迎场景
Home = 1,
//游戏场景
SinglePlayer = 2,
//
DoublePlayer = 3,
//设计地图
DesignMap=4,
//关于场景
About = 5,
//游戏设定场景
GameSatting=6
};
namespace Global {
namespace Window {
const string GameTitle = "Our Game";
extern int ScreenWidth;
extern int ScreenHeight ;
//窗口的坐标
extern int x, y;
extern bool EnableBackgroundRunning;
extern bool isActity;
//鼠标灵敏度
const float CursorSensitivity = 1.0f;
const bool FullScreen = false;
//指定逻辑刷新速度
const float targetFps = 480.0f;
//当前的游戏状态
extern int Now_GAME_STATE;
}
namespace Home {
//最终的选项,0:单人游戏;1:双人游戏;2:设计地图;3:关于我们
extern int selectedType;
}
namespace Debug {
//是否显示调试信息
const bool ShowDebugInfo = true;
//当前总帧率
extern int currentFPS;
}
namespace DesignMap {
//新设计地图的名称
extern string NewMapName;
}
namespace PlayerControl {
//玩家一的控制方式
extern int Player1[5];
//玩家二的控制方式
extern int Player2[5];
}
namespace Sound {
//音乐开关
extern bool SoundSwicth;
}
}
<file_sep>/OurGame/Resource.cpp
#include"Resource.h"<file_sep>/OurGame/WinMain.h
#pragma once
void EndApplication();
void ShowMessage(string text);<file_sep>/OurGame/GUIs.h
#pragma once
#include"CursorGUI.h"<file_sep>/OurGame/CursorGUI.h
#pragma once
#include"DirectX.h"
namespace GUI {
namespace Cursor {
bool Init();
void Render();
void Update();
extern SPRITE Cursor;
}
}
<file_sep>/OurGame/GamingScene.cpp
#include "GamingScene.h"
#define EnemyNumberMAX 21
namespace GS {
LPDIRECT3DSURFACE9 GrayRect = NULL;
LPDIRECT3DSURFACE9 BlackRect = NULL;
/*纹理*/
LPDIRECT3DTEXTURE9 Flag = NULL;
LPDIRECT3DTEXTURE9 Something = NULL;
LPDIRECT3DTEXTURE9 Tile = NULL;
LPDIRECT3DTEXTURE9 Player_1 = NULL;
LPDIRECT3DTEXTURE9 Player_2 = NULL;
LPDIRECT3DTEXTURE9 Bullet_TXTTURE = NULL;
LPDIRECT3DTEXTURE9 Enemy_TXTTURE = NULL;
LPDIRECT3DTEXTURE9 Award = NULL;
LPDIRECT3DTEXTURE9 Boom1 = NULL;
LPDIRECT3DTEXTURE9 Boom2 = NULL;
LPDIRECT3DTEXTURE9 GameOver = NULL;
LPDIRECT3DTEXTURE9 Shield = NULL;
LPDIRECT3DTEXTURE9 Hole = NULL;
LPDIRECT3DTEXTURE9 Number = NULL;
LPDIRECT3DTEXTURE9 Flicker[9] = { NULL };
/*变量*/
vector<int> BornPlayer1MapPiece;
vector<int> BornPlayer2MapPiece;
vector<int> BornEnemyMapPiece;
string NowMapName = "stage1";
unsigned long lasttime = 0;
int HaveBornEnemyNumber = 0;
int StartTime = 0, NowTime, SurplusTime = 0;
bool ShowTime = false;
bool GameOverFlag = false;
bool IsDoublePlayer = false;
int SGOy = 960;
int EnemyNumber = 30;
/*对象*/
Player player;
Player2 player2;
Player &Player1 = player;
void ShowGameOver();
/*工具函数*/
int Crash(int iswho, int x, int y, int speed, int dir, int shooter, unsigned long id, int);
void DrawMap();
void CreateMapPiece();
bool ReadMapInHD(string filename);
bool ReadMapInHD(char * filename);
bool WriteMapToHD(char * filename);
void FillRect(RECT & rect, long l, long r, long t, long b);
void ReadMap(int x, int y, RECT&rect1, RECT&rect2);//读取地图信息
void AddUselessObj(unsigned long id);
bool DelListNode(EnemyList*listhead, unsigned long id);//删除成功返回true,否则返回false
bool DelListNode(BulletList*listhead, unsigned long id);//删除成功返回true,否则返回false
bool DelListNode(BoomList*listhead, unsigned long id);//删除成功返回true,否则返回false
void DelUselessObj();
void DrawNet();
void ClearUselessObj();
void CreateEnemy(int x, int y, int speed, int hp, int as, int grade, int dir);
void CreateBoom(int x, int y, int whatboom, int Dir);
// int MaxNumber(int m1, int m2, int m3, int m4, bool r1, bool r2, bool r3, bool r4);
// int MinNumber(int m1, int m2, int m3, int m4, bool r1, bool r2, bool r3, bool r4);
void DIDA();
void NewStage();
void ReadNextMap();
void StartNextStage();
void RestartThisStage();
/*工具函数*/
BulletListHead bulletlisthead;//子弹链表头
EnemyListHead enemylisthead;//敌人链表头
UselessObjHead uselessobjhead;//失效对象链表头
BoomListHead boomlisthead;//爆炸链表头
MapPieceListHead mappiecelisthead;
static unsigned long IDNumber = 0;
int EnemyXY[EnemyNumberMAX][2];//敌人位置坐标表
int Map[13][13]; //第一个是y轴,第二个是x轴
}
using namespace GS;
/*--------------------------------------------------------------------
GamingScene的方法
----------------------------------------------------------------------*/
//场景初始化
bool GamingScene::Init()
{
//
srand((unsigned)time(0));
for (int i = 0; i < EnemyNumberMAX; i++)//初始化敌人坐标表
{
EnemyXY[i][0] = -1;
EnemyXY[i][1] = -1;
}
//
HRESULT result = d3dDev->CreateOffscreenPlainSurface(
100,
100,
D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT,
&GrayRect,
NULL
);
if (result != D3D_OK)
{
ShowMessage("灰色-格子 初始化失败!");
return false;
}
result = d3dDev->CreateOffscreenPlainSurface(
100,
100,
D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT,
&BlackRect,
NULL
);
if (result != D3D_OK)
{
ShowMessage("黑色-格子 初始化失败!");
return false;
}
d3dDev->ColorFill(GrayRect, NULL, D3DCOLOR_XRGB(110, 110, 110));
d3dDev->ColorFill(BlackRect, NULL, D3DCOLOR_XRGB(69, 139, 116));
Flag = LoadTexture(Resource::Texture::Flag, D3DCOLOR_XRGB(255, 255, 255));
if (!Flag)
{
ShowMessage("装载 旗子 纹理失败!");
return false;
}
Something = LoadTexture(Resource::Texture::Something, D3DCOLOR_XRGB(255, 255, 255));
if (!Something)
{
ShowMessage("装载 杂项 纹理失败!");
return false;
}
Tile = LoadTexture(Resource::Texture::Tile, D3DCOLOR_XRGB(4, 4, 4));
if (!Tile)
{
ShowMessage("装载 砖 纹理失败!");
return false;
}
Player_1 = LoadTexture(Resource::Texture::Player_1, D3DCOLOR_XRGB(0, 0, 0));
if (!Player_1)
{
ShowMessage("装载 主玩家 纹理失败!");
return false;
}
Bullet_TXTTURE = LoadTexture(Resource::Texture::Bullet, D3DCOLOR_XRGB(4, 4, 4));
if (!Bullet_TXTTURE)
{
ShowMessage("装载 子弹 纹理失败!");
return false;
}
Boom1 = LoadTexture(Resource::Texture::Boom1, D3DCOLOR_XRGB(0, 0, 0));
if (!Boom1)
{
ShowMessage("装载 爆炸一 纹理失败!");
return false;
}
Boom2 = LoadTexture(Resource::Texture::Boom2, D3DCOLOR_XRGB(4, 4, 4));
if (!Boom2)
{
ShowMessage("装载 爆炸二 纹理失败!");
return false;
}
Player_2 = LoadTexture(Resource::Texture::Player_2, D3DCOLOR_XRGB(0, 0, 0));
if (!Player_2)
{
ShowMessage("装载 玩家二 纹理失败!");
return false;
}
Award = LoadTexture(Resource::Texture::Award, D3DCOLOR_XRGB(234, 234, 234));
if (!Award)
{
ShowMessage("装载 奖励 纹理失败!");
return false;
}
Shield = LoadTexture(Resource::Texture::Shield, D3DCOLOR_XRGB(234, 234, 234));
if (!Shield)
{
ShowMessage("装载 盾牌 纹理失败!");
return false;
}
GameOver = LoadTexture(Resource::Texture::GameOver, D3DCOLOR_XRGB(0, 0, 0));
if (!GameOver)
{
ShowMessage("装载 游戏结束 纹理失败!");
return false;
}
Enemy_TXTTURE = LoadTexture(Resource::Texture::Enemy, D3DCOLOR_XRGB(4, 4, 4));
if (!Enemy_TXTTURE)
{
ShowMessage("装载 敌人 纹理失败!");
return false;
}
Hole = LoadTexture(Resource::Texture::Hole, D3DCOLOR_XRGB(4, 4, 4));
if (!Hole)
{
ShowMessage("装载 孔 纹理失败!");
return false;
}
Number = LoadTexture(Resource::Texture::Number, D3DCOLOR_XRGB(255, 255, 255));
if (!Number)
{
ShowMessage("装载 数字 纹理失败!");
return false;
}
//装载闪光
string png = ".png";
string path = "Resources\\Texture\\";
string buf;
char buf1;
for (int i = 0; i < 9; i++)
{
buf1 = i + 48;
buf = buf1 + png;
Flicker[i] = LoadTexture(path + buf);
if (!Flicker[i])
ShowMessage(buf);
}
RECT rect;
int n = 0, i = 960;//无论窗口大小,游戏分辨率总是不变
int delayOld = GetTickCount();
d3dDev->BeginScene();
for (; n < Global::Window::ScreenHeight / 2; n += 8, i -= 8)
{
FillRect(rect, 0, 1024, n, n + 8);
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 0, 1024, i - 8, i);
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
d3dDev->EndScene();
d3dDev->Present(NULL, NULL, NULL, NULL);
Sleep(5);
/**
while (1)
{
if (GetTickCount() > delayOld + 1)
{
delayOld = GetTickCount();
break;
}
}
*/
}
//在这选择关卡
if (Global::DesignMap::NewMapName.length() != 0)
ReadMapInHD(Global::DesignMap::NewMapName);
else
ReadMapInHD(NowMapName);
//读取地图信息并创建地图块
CreateMapPiece();
//判断是否双人游戏
IsDoublePlayer = Global::Home::selectedType == 1 ? true : false;
//播放开始声音
if(Global::Sound::SoundSwicth)
Sound::Start->Play();
player.Born();
if (IsDoublePlayer)
player2.Born();
return 1;
}
void GamingScene::End()
{
//清除地图块
MapPieceList*buf;
MapPieceList*mp = mappiecelisthead.next;
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
while (mp != NULL)
{
if (i == mp->mappiece->X&&j == mp->mappiece->Y)
{
buf = mp;
mp = mp->next;
delete buf;
}
else
mp = mp->next;
}
}
mappiecelisthead.next = NULL;
//清除敌人
EnemyList* ep = enemylisthead.next;
while (ep != NULL)
{
AddUselessObj(ep->enemy->ID);
ep = ep->next;
}
//清除子弹
BulletList*bp = bulletlisthead.next;
while (bp != NULL)
{
AddUselessObj(bp->bullet->ID);
bp = bp->next;
}
//清除爆炸
BoomList*boomp = boomlisthead.next;
while (boomp != NULL)
{
AddUselessObj(boomp->boom->ID);
boomp = boomp->next;
}
ClearUselessObj();
//重置玩家数据
player.Speed = 5 * 64;
player.Attack_Speed = 5;
player.Dir = Dirction::up;
player.Grade = 3;
player.player.x = 64 * 6;
player.player.y = 64 * 13;
player.BulletSpeed = 64 * 12;
player.Lift = 1;
player.Health_Point = 1;//玩家血量
if (IsDoublePlayer)
{
player2.Speed = 5 * 64;
player2.Attack_Speed = 9;
player2.Dir = Dirction::up;
player2.Grade = 3;
player2.player.x = 64 * 6;
player2.player.y = 64 * 13;
player2.BulletSpeed = 64 * 12;
player2.Lift = 1;
player2.Health_Point = 1;//玩家血量
}
//重置地图变量
SGOy = 960;
GameOverFlag = false;
}
//游戏渲染
void GamingScene::Render()
{
d3dDev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
/*游戏边框*/
RECT rect;
FillRect(rect, 0, 1024, 32, 64); //分辨率不为1024*960时需要修改
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 0, 64, 64, 896);
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 896, 1024, 64, 896);
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 0, 1024, 896, 928);
d3dDev->StretchRect(GrayRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
DrawNet();//画网格,正式版删除
/*游戏内容*/
spriteObj->Begin(D3DXSPRITE_ALPHABLEND);
Sprite_Transform_Draw(Flag, 926, 704, 32, 32, 0, 1, 0, 2.0, D3DCOLOR_XRGB(255, 255, 255));
//玩家一的信息
Sprite_Transform_Draw(Something, 928, 512, 14, 14, 2, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Something, 960, 512, 14, 14, 3, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Something, 928, 544, 14, 14, 1, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
//玩家二的信息
if (IsDoublePlayer) {
Sprite_Transform_Draw(Something, 928, 608, 14, 14, 4, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Something, 960, 608, 14, 14, 3, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Something, 928, 640, 14, 14, 1, 6, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
}
//画玩家一
if(player.Alive)
player.Draw();
//画玩家二
if (player2.Alive)
{
if (IsDoublePlayer)
player2.Draw();
}
//画地图
MapPieceList* mp = mappiecelisthead.next;
while (mp != NULL)
{
mp->mappiece->Draw();
mp = mp->next;
}
// DrawMap();
// Sprite_Transform_Draw(Tile, 512, 832, 32, 32, 5, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
//渲染子弹 并清除已失效子弹
BulletList*bp = bulletlisthead.next;
while (bp != NULL)
{
bp->bullet->Draw();
bp = bp->next;
}
//渲染敌人
EnemyList *ep = enemylisthead.next;
while (ep != NULL)
{
ep->enemy->Draw();
ep = ep->next;
}
//渲染爆炸
BoomList *pboom = boomlisthead.next, *bbuf;
while (pboom != NULL)
{
pboom->boom->Draw();
pboom = pboom->next;
}
//游戏结束
if (GameOverFlag)
{
ShowGameOver();
}
DIDA();//产生时间信息
}
//游戏逻辑更新
void GamingScene::Update()
{
unsigned long newtime;
//
if (Key_Up(DIK_ESCAPE))
{
Game_ChangeScene(GAME_STATE::Home);
}
static bool StarSoundPlaying = true;
if (Global::Sound::SoundSwicth)
{
if (StarSoundPlaying)
if (!Sound::Start->IsSoundPlaying())
{
Sound::BGM->Play(0, DSBPLAY_LOOPING);
StarSoundPlaying = false;
}
}
if (!GameOverFlag) {
//检查敌人数量 判断是否胜利
if (EnemyNumber <= 0)
{
StartNextStage();
}
//玩家一
if (player.Alive)
{
if (KEY_DOWN(VK_UP) && !KEY_DOWN(VK_RIGHT) && !KEY_DOWN(VK_LEFT))
{
player.Logic(Dirction::up);
//up
}
if (KEY_DOWN(VK_DOWN) && !KEY_DOWN(VK_RIGHT) && !KEY_DOWN(VK_LEFT))
{
player.Logic(Dirction::below);
//blow
}
if (KEY_DOWN(VK_LEFT))
{
player.Logic(Dirction::lift);
//left
}
if (KEY_DOWN(VK_RIGHT))
{
player.Logic(Dirction::right);
//right
}
//玩家射击
static int ShootTime = 10;
if (ShowTime)
ShootTime++;
if (KEY_DOWN(0x58) || KEY_DOWN(VK_NUMPAD0))
{
if (ShootTime > 10 / player.Attack_Speed)
{
player.Shoot(0, 3);
ShootTime = 0;
}
}
}
//玩家二
static int ShootTime2 = 10;
if (player2.Alive)
{
if (IsDoublePlayer)
{
if (KEY_DOWN(0x57) && !KEY_DOWN(0x44) && !KEY_DOWN(0x41))
{
player2.Logic(Dirction::up);
//up
}
if (KEY_DOWN(0x53) && !KEY_DOWN(0x44) && !KEY_DOWN(0x41))
{
player2.Logic(Dirction::below);
//blow
}
if (KEY_DOWN(0x41))
{
player2.Logic(Dirction::lift);
//left
}
if (KEY_DOWN(0x44))
{
player2.Logic(Dirction::right);
//right
}
//玩家射击
if (ShowTime)
ShootTime2++;
if (KEY_DOWN(0x4A))
{
if (ShootTime2 > 10 / player2.Attack_Speed)
{
player2.Shoot(0, player2.PowerLevel);
ShootTime2 = 0;
}
}
}
}
//更新子弹逻辑
BulletList*bp = bulletlisthead.next;
while (bp != NULL)
{
bp->bullet->Logic();
bp = bp->next;
}
//更新敌人逻辑
EnemyList*ep = enemylisthead.next;
while (ep != NULL)
{
ep->enemy->Logic(ShowTime);
ep = ep->next;
}
//生成新敌人
static int BornEnemy = 30;//生成敌人记时器
static int NeedBornEnemy = 1;
if (NeedBornEnemy)
if (ShowTime)//ShowTime 100ms一次
BornEnemy++;
if (BornEnemy >= 10)//生成新的敌人
{
if (HaveBornEnemyNumber > 30)
NeedBornEnemy = 0;
if (BornEnemyMapPiece.size() != 0)
{
//根据敌人生成点来随机生成敌人
int atbuf= rand() % (BornEnemyMapPiece.size() / 2);
CreateEnemy((BornEnemyMapPiece.at(atbuf*2)+1) * 64,
(BornEnemyMapPiece.at(atbuf*2+1)+1) * 64,
5 * 64, 1, 1, rand() % 8, rand() % 4);
// CreateEnemy((BornEnemyMapPiece.at(2)+1) * 64, (BornEnemyMapPiece.at(3)+1) * 64, 5 * 64, 1, 1, rand() % 8, rand() % 4);
HaveBornEnemyNumber++;
}
else
{
HaveBornEnemyNumber++;
CreateEnemy(12 * 64, 12 * 64, 5 * 64, 1, 1, rand() % 8, rand() % 4);
}
// CreateEnemy(12 * 64, 3 * 64, 5, 1, 1, rand() % 7, rand() % 4);
// CreateEnemy(4 * 64, 3 * 64, 10, 1, 1, rand() % 7, rand() % 4);
BornEnemy = 0;
}
//更新爆炸逻辑
BoomList*boomp = boomlisthead.next;
while (boomp != NULL)
{
boomp->boom->Logic();
boomp = boomp->next;
}
//判断玩家血量以决定游戏状态
if (!IsDoublePlayer)
{
if (player.Health_Point <= 0)
{
player.Lift--;
if (player.Lift <= 0)
player.Alive = false;
else
Player1.Born();
//创建爆炸
CreateBoom(player.player.x,player.player.y, 2, player.Dir);
}
if (player.Lift <= 0)
{
GameOverFlag = true;
}
}
else
{
if (player.Alive)
{
if (player.Health_Point <= 0)
{
player.Lift--;
if (player.Lift <= 0)
player.Alive = false;
else
Player1.Born();
//创建爆炸
CreateBoom(player.player.x, player.player.y, 2, player.Dir);
}
}
if (player2.Alive)
{
if (player2.Health_Point <= 0)
{
player2.Lift--;
if (player2.Lift <= 0)
player2.Alive = false;
else
//创建爆炸
CreateBoom(player2.player.x, player2.player.y, 2, player2.Dir);
player2.Born();
}
}
if (!player.Alive && !player2.Alive)
{
GameOverFlag = true;
}
}
//清除失效对象
ClearUselessObj();
//读取时间完毕
}
else
{
if (KEY_DOWN(VK_RETURN))
{
RestartThisStage();
GameOverFlag = false;
}
}
ShowTime = false;
lasttime = GetTickCount();
}
/*--------------------------------------------------------------------
GamingScene的方法到此结束
----------------------------------------------------------------------*/
/*--------------------------------------------------------------------
GameScene的方法
----------------------------------------------------------------------*/
//游戏结束画面
void GS::ShowGameOver()
{
static int oldtime = GetTickCount();
if (GetTickCount() > oldtime + 17)
{
SGOy -= 8;
oldtime = GetTickCount();
}
if (SGOy < 320)
Sprite_Transform_Draw(GameOver, 232, 320, 248, 160,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
else
Sprite_Transform_Draw(GameOver, 232, SGOy, 248, 160,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
}
//专门服务于bullet::logic的碰撞检测函数
int GS::Crash(int iswho, int x, int y, int speed, int dir,
int shooter, unsigned long id, int movedmixel) {
//地图边界
static RECT MapEdgeTop = { 0,0,1024,64 },
MapEdgeBelow = { 0,896,1024,960 },
MapEdgeLeft = { 0,0,64,960 },
MapEdgeRight = { 896,0,1024,960 };
//先检测子弹是否碰撞到敌人
RECT BulletRect;
switch (dir)
{
case Dirction::up:
BulletRect.bottom = y + 16 + movedmixel;
BulletRect.left = x;
BulletRect.right = x + 16;
BulletRect.top = y;
break;
case Dirction::right:
BulletRect.bottom = y + 16;
BulletRect.left = x - movedmixel;
BulletRect.right = x + 16;
BulletRect.top = y;
break;
case Dirction::below:
BulletRect.bottom = y + 16;
BulletRect.left = x;
BulletRect.right = x + 16;
BulletRect.top = y - movedmixel;
break;
case Dirction::lift:
BulletRect.bottom = y + 16;
BulletRect.left = x;
BulletRect.right = x + 16 + movedmixel;
BulletRect.top = y;
break;
default:
break;
}
RECT EnemyRect, Rect;
EnemyList* ep = enemylisthead.next;
if (shooter == 0)
{
while (ep != NULL)
{
EnemyRect.left = ep->enemy->player.x;
EnemyRect.top = ep->enemy->player.y;
EnemyRect.bottom = ep->enemy->player.y + 56;
EnemyRect.right = ep->enemy->player.x + 56;
if (IntersectRect(&Rect, &EnemyRect, &BulletRect))
{
CreateBoom(ep->enemy->player.x, ep->enemy->player.y, 2, ep->enemy->Dir);
DelListNode(enemylisthead.next, ep->enemy->ID);
EnemyNumber--;
return 2;//销毁自己
}
ep = ep->next;
}
}
//检测敌人子弹是否命中玩家
RECT PlayerRect;
if (shooter == 2)
{
if (Player1.Alive)
{
PlayerRect.bottom = Player1.player.y + 56;
PlayerRect.right = Player1.player.x + 56;
PlayerRect.left = Player1.player.x;
PlayerRect.top = Player1.player.y;
if (IntersectRect(&Rect, &PlayerRect, &BulletRect))
{
Player1.GetHurt(0);
return 1;
}
}
if (IsDoublePlayer)
{
if (player2.Alive)
{
PlayerRect.bottom = player2.player.y + 56;
PlayerRect.right = player2.player.x + 56;
PlayerRect.left = player2.player.x;
PlayerRect.top = player2.player.y;
if (IntersectRect(&Rect, &PlayerRect, &BulletRect))
{
player2.GetHurt(0);
return 1;
}
}
}
}
//检测子弹碰撞
BulletList*bp = bulletlisthead.next;
RECT BulletRectTest;
while (bp != NULL)
{
BulletRectTest.bottom = bp->bullet->bullet.y + 16;
BulletRectTest.right = bp->bullet->bullet.x + 16;
BulletRectTest.top = bp->bullet->bullet.y;
BulletRectTest.left = bp->bullet->bullet.x;
if (IntersectRect(&Rect, &BulletRectTest, &BulletRect))
{
if (id != bp->bullet->ID)
{
AddUselessObj(bp->bullet->ID);
return 1;
}
}
bp = bp->next;
}
/*
for (int i = 0; i < EnemyNumberMAX; i++)
{
if (EnemyXY[i][0] == -1)
continue;
EnemyRect.left=EnemyXY[i][0];
EnemyRect.top=EnemyXY[i][1];
EnemyRect.bottom = EnemyXY[i][1] + 56;
EnemyRect.right = EnemyXY[i][0] + 56;
if (IntersectRect(&Rect, &EnemyRect, &BulletRect))
{
while (ep != NULL)
{
if (ep->enemy->player.x == EnemyRect.left)
if (ep->enemy->player.y == EnemyRect.top)
{
AddUselessObj(ep->enemy->ID);
EnemyXY[i][0] = -1;
}
ep = ep->next;
}
return 2;//目前为测试状态 正式版应为爆炸2
}
}*/
//检测是否碰撞到砖块
// int x1 = x - 20, y1 = y - 20;
int X1, Y1, X2, Y2;
switch (dir)
{
case Dirction::up:
X1 = (x - 20) / 64;
Y1 = y / 64;
X2 = (x + 36) / 64;
Y2 = y / 64;
break;
case Dirction::right:
X1 = (x + 16) / 64;
Y1 = (y - 20) / 64;
X2 = (x + 16) / 64;
Y2 = (y + 36) / 64;
break;
case Dirction::below:
X1 = (x - 20) / 64;
Y1 = (y + 16) / 64;
X2 = (x + 36) / 64;
Y2 = (y + 16) / 64;
break;
case Dirction::lift:
X1 = x / 64;
Y1 = (y - 20) / 64;
X2 = x / 64;
Y2 = (y + 36) / 64;
break;
default:
break;
}
//RECT BoomRect = { x - 20,y - 20,x + 36,y + 36 };
MapPieceList*mp = mappiecelisthead.next;
bool crashflag1 = false, crashflag2 = false;
if (X1 == X2&&Y1 == Y2)
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
crashflag1 = mp->mappiece->BeingCrash(0, BulletRect, dir, x, y);
mp = mp->next;
}
}
else
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
crashflag1 = mp->mappiece->BeingCrash(0, BulletRect, dir, x, y);
mp = mp->next;
}
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X2 - 1 == mp->mappiece->X)
if (Y2 - 1 == mp->mappiece->Y)
crashflag2 = mp->mappiece->BeingCrash(crashflag1, BulletRect, dir, x, y);
mp = mp->next;
}
}
if (!crashflag1)
{
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
crashflag1 = mp->mappiece->BeingCrash(crashflag2, BulletRect, dir, x, y);
mp = mp->next;
}
}
else if (!crashflag2)
{
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X2 - 1 == mp->mappiece->X)
if (Y2 - 1 == mp->mappiece->Y)
crashflag2 = mp->mappiece->BeingCrash(crashflag1, BulletRect, dir, x, y);
mp = mp->next;
}
}
if (crashflag1 || crashflag2)
return 1;
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
if (IntersectRect(&Rect, &MapEdgeBelow, &BulletRect))
return 3;
break;
case 1:
if (IntersectRect(&Rect, &MapEdgeLeft, &BulletRect))
return 3;
break;
case 2:
if (IntersectRect(&Rect, &MapEdgeRight, &BulletRect))
return 3;
break;
case 3:
if (IntersectRect(&Rect, &MapEdgeTop, &BulletRect))
return 3;
break;
default:
break;
}
}
}
//游戏地图绘画函数
void GS::DrawMap()
{
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++) {
switch (Map[j][i])
{
case 0:break;
//
case 13:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 26:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 27:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 2, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 28:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 3, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 29:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 4, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
//
case 1:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 2:Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 3:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 96,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 4:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 5:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 6:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 7:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 8:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 9:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 10:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 11:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 12:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 96,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 14:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 15:Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 16:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 96,
16, 16, 16, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 17:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 18:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 19:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 20:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 21:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 22:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 23:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 24:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 25:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
default:
break;
}
}
}
//创建地图精灵
void GS::CreateMapPiece()
{
for (int x = 0; x < 13; x++)
for (int y = 0; y < 13; y++) {
if (Map[y][x] != 0) {
//记录玩家一的出生地点
if (Map[y][x] == 31)
{
BornPlayer1MapPiece.push_back(x);
BornPlayer1MapPiece.push_back(y);
}
//记录玩家二的出生地点
if (Map[y][x] == 32)
{
BornPlayer2MapPiece.push_back(x);
BornPlayer2MapPiece.push_back(y);
}
//记录敌人的出生地点
if (Map[y][x] == 33)
{
BornEnemyMapPiece.push_back(x);
BornEnemyMapPiece.push_back(y);
}
MapPiece*b = new MapPiece;
MapPieceList*h = mappiecelisthead.next;
MapPieceList*New = new MapPieceList;
New->mappiece = b;
b->X = x;
b->Y = y;
b->Create(Map[y][x]);
//把新地图块链接到链表
if (h == NULL)
{
mappiecelisthead.next = New;
New->last = NULL;
New->next = NULL;
}
else
{
if (h->next != NULL)
{
New->next = h->next;
h->next = New;
New->next->last = New;
New->last = h;
}
else
{
h->next = New;
New->last = h;
New->next = NULL;
}
}
}
}
}
//读取硬盘上地图的信息
bool GS::ReadMapInHD(string filename)
{
char buf[13][13];
string sbuf = "Map\\";
sbuf += filename;
sbuf += ".map";
ifstream in(sbuf, ios::in | ios::binary);
if (!in.is_open())
{
//ShowMessage("sd");
return false;
}
//从文件中读取地图信息
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
in.read(&buf[i][j], 1);
}
//转换为当前地图
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
Map[i][j] = buf[i][j];
}
return true;
}
bool GS::ReadMapInHD(char*filename)
{
char buf[13][13];
string sbuf = "Map\\";
sbuf += filename;
sbuf += ".map";
ifstream in(sbuf, ios::in | ios::binary);
if (!in.is_open())
{
ShowMessage(sbuf);
}
//从文件中读取地图信息
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
in.read(&buf[i][j], 1);
}
//转换为当前地图
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
Map[i][j] = buf[i][j];
}
return 0;
}
//写当前地图信息到硬盘
bool GS::WriteMapToHD(char*filename)
{
char buf;
ofstream out(filename, ios::out | ios::binary);
if (!out.is_open())
{
ShowMessage(filename);
}
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
buf = Map[i][j];
out.write(&buf, 1);
}
return 0;
}
//创建爆炸
void GS::CreateBoom(int x, int y, int whatboom, int Dir)
{
BoomFire*b = new BoomFire(x, y, whatboom, Dir);
IDNumber++;
b->ID = IDNumber;
BoomList*h = boomlisthead.next;
BoomList*New = new BoomList;
New->boom = b;
if (h == NULL)
{
boomlisthead.next = New;
New->last = NULL;
New->next = NULL;
}
else
{
if (h->next != NULL)
{
New->next = h->next;
h->next = New;
New->next->last = New;
New->last = h;
}
else
{
h->next = New;
New->last = h;
New->next = NULL;
}
}
}
//创建敌人
void GS::CreateEnemy(int x, int y, int speed, int hp,
int as, int grade, int dir)
{
int NewEnemyX = x;
int NewEnemyY = y;
//生成敌人对象
Enemy*e = new Enemy(NewEnemyX, NewEnemyY, speed, hp, as, grade, dir);
IDNumber++;
e->ID = IDNumber;
EnemyList*h = enemylisthead.next;
EnemyList*newE = new EnemyList;
newE->enemy = e;
if (h == NULL)
{
enemylisthead.next = newE;
newE->last = NULL;
newE->next = NULL;
}
else
{
if (h->next != NULL)
{
newE->next = h->next;
h->next = newE;
newE->next->last = newE;
newE->last = h;
}
else
{
h->next = newE;
newE->last = h;
newE->next = NULL;
}
}
}
/*工具函数*/
//填充RECT
void GS::FillRect(RECT&rect, long l = -1, long r = -1,
long t = -1, long b = -1)
{
rect.left = l;
rect.right = r;
rect.top = t;
rect.bottom = b;
}
//读取地图信息
void GS::ReadMap(int x, int y, RECT&rect1, RECT&rect2)
{
switch (Map[y][x])
{
case 0:
case 27:
case 28:
case 29:
FillRect(rect1);
FillRect(rect2);
break;
case 1:
case 14:
FillRect(rect1, 64 * x + 64, 64 * x + 96, 64 * y + 64, 64 * y + 96);
FillRect(rect2);
break;
case 2:
case 15:
FillRect(rect1, 64 * x + 96, 64 * x + 128, 64 * y + 64, 64 * y + 96);
FillRect(rect2);
break;
case 3:
case 16:
FillRect(rect1, 64 * x + 96, 64 * x + 128, 64 * y + 96, 64 * y + 128);
FillRect(rect2);
break;
case 4:
case 17:
FillRect(rect1, 64 * x + 64, 64 * x + 96, 64 * y + 96, 64 * y + 128);
FillRect(rect2);
break;
case 5:
case 18:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 64, 64 * y + 96);
FillRect(rect2);
break;
case 6:
case 19:
FillRect(rect1, 64 * x + 96, 64 * x + 128, 64 * y + 64, 64 * y + 128);
FillRect(rect2);
break;
case 7:
case 20:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 96, 64 * y + 128);
FillRect(rect2);
break;
case 8:
case 21:
FillRect(rect1, 64 * x + 64, 64 * x + 96, 64 * y + 64, 64 * y + 128);
FillRect(rect2);
break;
//
case 9:
case 22:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 64, 64 * y + 96);
FillRect(rect2, 64 * x + 64, 64 * x + 96, 64 * y + 96, 64 * y + 128);
break;
case 10:
case 23:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 64, 64 * y + 96);
FillRect(rect2, 64 * x + 96, 64 * x + 128, 64 * y + 96, 64 * y + 128);
break;
case 11:
case 24:
FillRect(rect1, 64 * x + 96, 64 * x + 128, 64 * y + 64, 64 * y + 128);
FillRect(rect2, 64 * x + 64, 64 * x + 96, 64 * y + 96, 64 * y + 128);
break;
case 12:
case 25:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 96, 64 * y + 128);
FillRect(rect2, 64 * x + 64, 64 * x + 96, 64 * y + 64, 64 * y + 96);
break;
case 13:
case 26:
FillRect(rect1, 64 * x + 64, 64 * x + 128, 64 * y + 64, 64 * y + 128);
FillRect(rect2);
break;
default:
break;
}
}
//画辅助网格
void GS::DrawNet()
{
RECT rect;
for (int i = 0; i < 12; i++)
{
FillRect(rect, 128 + i * 64, 129 + i * 64, 64, 896);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
for (int i = 0; i < 12; i++)
{
FillRect(rect, 64, 896, 128 + i * 64, 129 + i * 64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
}
//清除失效对象
void GS::ClearUselessObj()
{
UselessObj*up = uselessobjhead.next;
//清除失效子弹
BulletList*b = bulletlisthead.next;
while (up != NULL)
{
while (b != NULL&&up != NULL)
{
if (b->bullet->ID != up->ID)
b = b->next;
else
{
DelListNode(bulletlisthead.next, b->bullet->ID);
DelUselessObj();
up = uselessobjhead.next;
break;
}
}
if (bulletlisthead.next == NULL)
break;
else
b = bulletlisthead.next;
if (up != NULL)
up = up->next;
}
//清除失效敌人并创造爆炸
up = uselessobjhead.next;
EnemyList*ep = enemylisthead.next;
while (up != NULL)
{
while (ep!=NULL&&up != NULL)
{
if (ep->enemy->ID != up->ID)
ep = ep->next;
else
{
//CreateBoom(ep->enemy->player.x, ep->enemy->player.y, 2, ep->enemy->Dir);
DelListNode(enemylisthead.next, ep->enemy->ID);
DelUselessObj();
up = uselessobjhead.next;
break;
}
}
if (enemylisthead.next == NULL)
break;
else
ep = enemylisthead.next;
if (up != NULL)
up = up->next;
}
//清除失效爆炸
up = uselessobjhead.next;
BoomList*bp = boomlisthead.next;
while (up != NULL)
{
while (bp != NULL&&up != NULL)
{
if (bp->boom->ID != up->ID)
bp = bp->next;
else
{
DelListNode(boomlisthead.next, bp->boom->ID);
DelUselessObj();
up = uselessobjhead.next;
break;
}
}
if (boomlisthead.next == NULL)
break;
else
bp = boomlisthead.next;
if (up != NULL)
up = up->next;
}
}
//
void GS::AddUselessObj(unsigned long id)
{
UselessObj*p = new UselessObj;
p->next = uselessobjhead.next;
p->ID = id;
uselessobjhead.next = p;
}
//删除链表元素
void GS::DelUselessObj()
{
UselessObj*p = uselessobjhead.next;
if (p != NULL)
uselessobjhead.next = p->next;
delete p;
}
bool GS::DelListNode(EnemyList*listhead, unsigned long id)//删除成功返回true,否则返回false
{
EnemyList*p = listhead;
while (p != NULL)
{
if (p->enemy->ID != id)
p = p->next;
else
{
if (p->last != NULL)
{
if (p->next != NULL) {
p->last->next = p->next;
p->next->last = p->last;
}
else
p->last->next = NULL;
}
else if (p->next != NULL)
{
p->next->last = NULL;
enemylisthead.next = p->next;
}
else
{
enemylisthead.next = NULL;
}
delete p;
return true;
}
}
return false;
}
bool GS::DelListNode(BulletList*listhead, unsigned long id)//删除成功返回true,否则返回false
{
BulletList*p = listhead;
while (p != NULL)
{
if (p->bullet->ID != id)
p = p->next;
else
{
if (p->last != NULL)
{
if (p->next != NULL) {
p->last->next = p->next;
p->next->last = p->last;
}
else
p->last->next = NULL;
}
else if (p->next != NULL)
{
p->next->last = NULL;
bulletlisthead.next = p->next;
}
else
{
bulletlisthead.next = NULL;
}
delete p;
return true;
}
}
return false;
}
bool GS::DelListNode(BoomList*listhead, unsigned long id)//删除成功返回true,否则返回false
{
BoomList*p = listhead;
while (p != NULL)
{
if (p->boom->ID != id)
p = p->next;
else
{
if (p->last != NULL)
{
if (p->next != NULL) {
p->last->next = p->next;
p->next->last = p->last;
}
else
p->last->next = NULL;
}
else if (p->next != NULL)
{
p->next->last = NULL;
boomlisthead.next = p->next;
}
else
{
boomlisthead.next = NULL;
}
delete p;
return true;
}
}
return false;
}
//产生时间脉冲
void GS::DIDA() {
NowTime = (int)GetTickCount();
if (NowTime > StartTime + 100)
{
if (StartTime != 0)
SurplusTime = NowTime - StartTime + 100;
StartTime = NowTime;
ShowTime = true;
}
}
void GS::NewStage()
{
//清除地图块
MapPieceList*buf;
MapPieceList*mp = mappiecelisthead.next;
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
while (mp != NULL)
{
if (i == mp->mappiece->X&&j == mp->mappiece->Y)
{
buf = mp;
mp = mp->next;
delete buf;
}
else
mp = mp->next;
}
}
mappiecelisthead.next = NULL;
//清除敌人
EnemyList* ep = enemylisthead.next;
while (ep != NULL)
{
AddUselessObj(ep->enemy->ID);
ep = ep->next;
}
//清除子弹
BulletList*bp = bulletlisthead.next;
while (bp != NULL)
{
AddUselessObj(bp->bullet->ID);
bp = bp->next;
}
//清除爆炸
BoomList*boomp = boomlisthead.next;
while (boomp != NULL)
{
AddUselessObj(boomp->boom->ID);
boomp = boomp->next;
}
ClearUselessObj();
//重置玩家数据
player.Speed = 5 * 64;
player.Attack_Speed = 5;
player.Dir = Dirction::up;
player.Grade = 3;
player.player.x = 64 * 6;
player.player.y = 64 * 13;
player.BulletSpeed = 64 * 12;
player.Lift = 1;
player.Health_Point = 1;//玩家血量
if (IsDoublePlayer)
{
player2.Speed = 5 * 64;
player2.Attack_Speed = 5;
player2.Dir = Dirction::up;
player2.Grade = 3;
player2.player.x = 64 * 6;
player2.player.y = 64 * 13;
player2.BulletSpeed = 64 * 12;
player2.Lift = 1;
player2.Health_Point = 1;//玩家血量
}
//重置地图变量
SGOy = 960;
GameOverFlag = false;
EnemyNumber = 30;
player.Alive = true;
player.Born();
player2.Alive = true;
player2.Born();
HaveBornEnemyNumber = 0;
}
void GS::ReadNextMap()
{
//使当前地图文件名变为下一个文件名
string sbuf=NowMapName.substr(5,NowMapName.size());
int ibuf = atoi(sbuf.c_str());
ibuf++;
char cbuf[20];
_itoa_s(ibuf, cbuf, 10);
NowMapName.erase(5, NowMapName.size());
NowMapName += cbuf;
//
if(!ReadMapInHD(NowMapName))
{
Game_ChangeScene(GAME_STATE::Home);
}
//
CreateMapPiece();
}
void GS::StartNextStage()
{
NewStage();
ReadNextMap();
}
void GS::RestartThisStage()
{
NewStage();
CreateMapPiece();
}
/*--------------------------------------------------------------------
GameScene的方法到此结束
----------------------------------------------------------------------*/
//敌人AI
int* idiot(int state, bool cflag)
{
int a[2];
if (cflag)
{
if ((rand() % 5) == 1)
{
a[0] = state;
a[1] = 1;//开炮
return a;
}
a[0] = rand() % 4;
a[1] = 0;
return a;
}
if ((rand() % 100) == 1)
{
a[0] = state;
a[1] = 1;
return a;
}
if ((rand() % 60) == 13)
{
a[0] = rand() % 4;
a[1] = 0;
return a;
}
a[0] = state;
a[1] = 0;
return a;
}
//敌人的构造函数
Enemy::Enemy(int x, int y, int speed, int hp,
int as,int grade,int dir)
{
player.x = x;
player.y = y;
Speed = speed;
Health_Point = hp;
Attack_Speed = as;
Grade = grade;
Dir = dir;
Time = 0;
}
//敌人的渲染方法
bool Enemy::Draw()
{
if (Grade <= 3) {
if (MoveStage) {
Sprite_Transform_Draw(Enemy_TXTTURE, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
MoveStage = !MoveStage;
}
else
{
Sprite_Transform_Draw(Enemy_TXTTURE, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2 + 1, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
MoveStage = !MoveStage;
}
}
else
{
if (MoveStage) {
Sprite_Transform_Draw(Enemy_TXTTURE, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2 + 24, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
MoveStage = !MoveStage;
}
else
{
Sprite_Transform_Draw(Enemy_TXTTURE, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2 + 25, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
MoveStage = !MoveStage;
}
}
return true;
}
//敌人逻辑
bool Enemy::Logic(bool st)
{
int *a=idiot(Dir, CrashingFlag);
CrashingFlag = false;
int d = *a;
if (*(a + 1) == 1)
Shoot(2,PowerLevel);
/**
if (st)
Time++;
if (Time == 6)
{
d = rand() % 4;
Time = 0;
Shoot(2);
}
*/
double srtime = GetTickCount() - lasttime;
switch (d)
{
case Dirction::up:
Dir = Dirction::up;
player.y -= Speed*srtime / 1000;
if (player.y < 64)
player.y = 64;
break;
case Dirction::right:
Dir = Dirction::right;
player.x += Speed*srtime / 1000;
if (player.x > 840)
player.x = 840;
break;
case Dirction::below:
Dir = Dirction::below;
player.y += Speed*srtime / 1000;
if (player.y > 840)
player.y = 840;
break;
case Dirction::lift:
Dir = Dirction::lift;
player.x -= Speed*srtime / 1000;
if (player.x < 64)
player.x = 64;
break;
default:
break;
}
RECT PlayerRect = { player.x,player.y,player.x + 56,player.y + 56 };
RECT Rect;
//和地图块的碰撞检测
{
int X1, Y1, X2, Y2;
switch (d)
{
case Dirction::up:
X1 = player.x / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = Y1;
break;
case Dirction::right:
X1 = (player.x + 56) / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = (player.y + 56) / 64;
break;
case Dirction::below:
X1 = (player.x + 56) / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = Y1;
break;
case Dirction::lift:
X1 = player.x / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = player.y / 64;
break;
default:
break;
}
MapPieceList*mp = mappiecelisthead.next;
int result1 = 0, result2 = 0;
if (X1 == X2&&Y1 == Y2)
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
else
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X2 - 1 == mp->mappiece->X)
if (Y2 - 1 == mp->mappiece->Y)
result2 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
if (result1 != 0 || result2 != 0)
{
CrashingFlag = true;
switch (d)
{
case Dirction::up:
if (result1 > result2)
player.y = result1;
else
player.y = result2;
break;
case Dirction::right:
if (result2 == 0)
player.x = result1 - 56;
else if (result1 == 0)
player.x = result2 - 56;
else if (result1<result2)
player.x = result1 - 56;
else
player.x = result2 - 56;
break;
case Dirction::below:
if (result2 == 0)
player.y = result1 - 56;
else if (result1 == 0)
player.y = result2 - 56;
else if (result1<result2)
player.y = result1 - 56;
else
player.y = result2 - 56;
break;
case Dirction::lift:
if (result1 > result2)
player.x = result1;
else
player.x = result2;
break;
default:
break;
}
}
}
RECT EnemyRect;
if (player.alive)
{
EnemyRect.bottom = Player1.player.y + 56;
EnemyRect.right = Player1.player.x + 56;
EnemyRect.left = Player1.player.x;
EnemyRect.top = Player1.player.y;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
CrashingFlag = true;
switch (d)
{
case Dirction::up:
player.y = Player1.player.y + 56;
break;
case Dirction::right:
player.x = Player1.player.x - 56;
break;
case Dirction::below:
player.y = Player1.player.y - 56;
break;
case Dirction::lift:
player.x = Player1.player.x + 56;
break;
default:
break;
}
}
}
if (IsDoublePlayer)
{
if (player2.Alive)
{
EnemyRect.bottom = player2.player.y + 56;
EnemyRect.right = player2.player.x + 56;
EnemyRect.left = player2.player.x;
EnemyRect.top = player2.player.y;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
CrashingFlag = true;
switch (d)
{
case Dirction::up:
player.y = player2.player.y + 56;
break;
case Dirction::right:
player.x = player2.player.x - 56;
break;
case Dirction::below:
player.y = player2.player.y - 56;
break;
case Dirction::lift:
player.x = player2.player.x + 56;
break;
default:
break;
}
}
}
}
return false;
}
//爆炸渲染方法
bool BoomFire::Draw()
{
if (WhatBoom == 1)
{
if(rand()%2==1)
Sprite_Transform_Draw(Boom1, x+rand()%5, y-rand()%5,
28, 28, 0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
}
else
{
Sprite_Transform_Draw(Boom1, x, y,
28, 28, 0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (GetTickCount() >= Time + 25)
Sprite_Transform_Draw(Boom2, x - 36 - rand() % 5, y - 36 + rand() % 5,
64, 64, 0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
}
return true;
}
//爆炸逻辑
void BoomFire::Logic()
{
if (WhatBoom == 1)
{
if (GetTickCount() >= Time+100)
AddUselessObj(ID);
}
else {
if (GetTickCount() >= Time + 100)
AddUselessObj(ID);
}
return;
}
//爆炸构造函数
BoomFire::BoomFire(int x, int y, int wb, int d) :
x(x), y(y), WhatBoom(wb), Dir(d)
{
Time = GetTickCount();
}
/*--------------------------------------------------------------------
玩家的方法
----------------------------------------------------------------------*/
//初始化玩家信息
Player::Player()
{
Health_Point = 1;//玩家血量
Speed = 5*64;
Attack_Speed = 5;
Dir = Dirction::up;
Grade = 3;
player.scaling = 2;
player.columns = 8;
player.frame = 0;
player.color= D3DCOLOR_XRGB(255, 255, 255);
player.x = 64*6;
player.y = 64*13;
player.width = 28;
player.height = 28;
BulletSpeed = 64*12;
FlickerFrame = 0;
Lift = 99;
PowerLevel = 0;
Alive = true;
FlashFlag = false;
}
//玩家射击
bool Player::Shoot(int shooter,int powlv) {
Bullet*b = new Bullet(shooter,Player::player.x,Player::player.y,
Player::BulletSpeed, Player::Dir,powlv);
IDNumber++;
b->ID = IDNumber;
if (b == NULL)
return false;
BulletList*c = bulletlisthead.next;
if (c == NULL)
{
bulletlisthead.next = new BulletList;//将子弹插入子弹链表
bulletlisthead.next->bullet = b;
bulletlisthead.next->next = c;
bulletlisthead.next->last = NULL;
}
else
{
BulletList*d = new BulletList;
d->bullet = b;
if (c->next != NULL)
{
d->next = c->next;
c->next = d;
d->next->last = d;
d->last = c;
}
else
{
c->next = d;
d->last = c;
d->next = NULL;
}
}
return true;
}
//玩家渲染方法
bool Player::Draw()
{
static int FlashTimes = 300;
static int lasttime=GetTickCount();
static bool ChangeFrame = false;
Sprite_Transform_Draw(Number, 960, 544, 14, 14, Lift / 10, 10, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Number, 993, 544, 14, 14, Lift % 10, 10, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
//2222222222222
if (ChangeFrame) {
Sprite_Transform_Draw(Player_1, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (KEY_DOWN(VK_LEFT) || KEY_DOWN(VK_RIGHT) || KEY_DOWN(VK_UP) || KEY_DOWN(VK_DOWN))
ChangeFrame = !ChangeFrame;
}
else {
Sprite_Transform_Draw(Player_1, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2 + 1, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (KEY_DOWN(VK_LEFT) || KEY_DOWN(VK_RIGHT) || KEY_DOWN(VK_UP) || KEY_DOWN(VK_DOWN))
ChangeFrame = !ChangeFrame;
}
if (FlashFlag)
{
if (GetTickCount() > lasttime + 50)
{
FlickerFrame = FlickerFrame < 8 ? FlickerFrame + 1 : 0;
lasttime = GetTickCount();
}
Sprite_Draw_Frame(Flicker[FlickerFrame], player.x - 372, player.y - 272, 0, 800, 600, 1);
FlashTimes--;
if (FlashTimes == 0)
{
FlashTimes = 300;
FlashFlag = false;
}
}
return false;
}
//玩家逻辑方法
bool Player::Logic(int d)
{
double srtime = GetTickCount() - lasttime;
switch (d)
{
case Dirction::up:
Dir = Dirction::up;
player.y -= Speed*srtime / 1000;
if (player.y < 64)
player.y = 64;
break;
case Dirction::right:
Dir = Dirction::right;
player.x += Speed*srtime / 1000;
if (player.x > 840)
player.x = 840;
break;
case Dirction::below:
Dir = Dirction::below;
player.y += Speed*srtime / 1000;
if (player.y > 840)
player.y = 840;
break;
case Dirction::lift:
Dir = Dirction::lift;
player.x -= Speed*srtime / 1000;
if (player.x < 64)
player.x = 64;
break;
default:
break;
}
RECT PlayerRect = { player.x,player.y,player.x + 56,player.y + 56 };
RECT EnemyRect, Rect;
//和地图块的碰撞检测
{
int X1, Y1, X2, Y2;
switch (d)
{
case Dirction::up:
X1 = player.x / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = Y1;
break;
case Dirction::right:
X1 = (player.x + 56) / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = (player.y + 56) / 64;
break;
case Dirction::below:
X1 = (player.x + 56) / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = Y1;
break;
case Dirction::lift:
X1 = player.x / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = player.y / 64;
break;
default:
break;
}
MapPieceList*mp = mappiecelisthead.next;
int result1 = 0, result2 = 0;
if (X1 == X2&&Y1 == Y2)
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
else
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X2 - 1 == mp->mappiece->X)
if (Y2 - 1 == mp->mappiece->Y)
result2 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
if (result1 != 0 || result2 != 0)
{
switch (d)
{
case Dirction::up:
if (result1 > result2)
player.y = result1;
else
player.y = result2;
break;
case Dirction::right:
if (result2 == 0)
player.x = result1 - 56;
else if (result1 == 0)
player.x = result2 - 56;
else if(result1<result2)
player.x = result1 - 56;
else
player.x = result2 - 56;
break;
case Dirction::below:
if (result2 == 0)
player.y = result1 - 56;
else if (result1 == 0)
player.y = result2 - 56;
else if (result1<result2)
player.y = result1 - 56;
else
player.y = result2 - 56;
break;
case Dirction::lift:
if (result1 > result2)
player.x = result1;
else
player.x = result2;
break;
default:
break;
}
}
}
//和敌人的碰撞检测
EnemyList* ep = enemylisthead.next;
while (ep != NULL)
{
EnemyRect.left = ep->enemy->player.x;
EnemyRect.top = ep->enemy->player.y;
EnemyRect.bottom = ep->enemy->player.y + 56;
EnemyRect.right = ep->enemy->player.x + 56;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
// 碰到敌人后回退移动距离
switch (d)
{
case Dirction::up:
player.y = ep->enemy->player.y + 56;
break;
case Dirction::right:
player.x = ep->enemy->player.x - 56;
break;
case Dirction::below:
player.y = ep->enemy->player.y - 56;
break;
case Dirction::lift:
player.x = ep->enemy->player.x + 56;
break;
default:
break;
}
}
ep = ep->next;
}
//和玩家二的碰撞检测
if (IsDoublePlayer)
{
if (player2.Alive)
{
EnemyRect.bottom = player2.player.y + 56;
EnemyRect.right = player2.player.x + 56;
EnemyRect.left = player2.player.x;
EnemyRect.top = player2.player.y;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
switch (d)
{
case Dirction::up:
player.y = player2.player.y + 56;
break;
case Dirction::right:
player.x = player2.player.x - 56;
break;
case Dirction::below:
player.y = player2.player.y - 56;
break;
case Dirction::lift:
player.x = player2.player.x + 56;
break;
default:
break;
}
}
}
}
return false;
}
//玩家被击中处理方法
bool Player::GetHurt(int power)
{
Health_Point--;
if (Health_Point == 0)
return false;
else
true;
}
//玩家重新生成方法
void Player::Born()
{
Health_Point = 1;
FlashFlag = true;
if (BornPlayer1MapPiece.size() != 0)
{
int atbuf = rand() % (BornPlayer1MapPiece.size() / 2);
player.x = (BornPlayer1MapPiece.at(atbuf*2) + 1) * 64;
player.y = (BornPlayer1MapPiece.at(atbuf*2 + 1) + 1) * 64;
}
else
{
}
}
//玩家二
//初始化玩家二信息
Player2::Player2()
{
Health_Point = 1;//玩家血量
Speed = 5 * 64;
Attack_Speed = 5;
Dir = Dirction::up;
Grade = 3;
player.scaling = 2;
player.columns = 8;
player.frame = 0;
player.color = D3DCOLOR_XRGB(255, 255, 255);
player.x = 64 * 9;
player.y = 64 * 13;
player.width = 28;
player.height = 28;
BulletSpeed = 64 * 12;
FlickerFrame = 0;
Lift = 99;
}
//玩家二渲染方法
bool Player2::Draw()
{
static int FlashTimes = 300;
static int lasttime = GetTickCount();
static bool ChangeFrame = false;
Sprite_Transform_Draw(Number, 960, 640, 14, 14, Lift / 10, 10, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Number, 992, 640, 14, 14, Lift % 10, 10, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (ChangeFrame) {
Sprite_Transform_Draw(Player_2, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (KEY_DOWN(0x41) || KEY_DOWN(0x44) || KEY_DOWN(0x57) || KEY_DOWN(0x53))
ChangeFrame = !ChangeFrame;
}
else {
Sprite_Transform_Draw(Player_2, player.x, player.y, player.width, player.height,
Dir * 8 + Grade * 2 + 1, player.columns, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
if (KEY_DOWN(0x41) || KEY_DOWN(0x44) || KEY_DOWN(0x57) || KEY_DOWN(0x53))
ChangeFrame = !ChangeFrame;
}
if (FlashFlag)
{
if (GetTickCount() > lasttime + 50)
{
FlickerFrame = FlickerFrame < 8 ? FlickerFrame + 1 : 0;
lasttime = GetTickCount();
}
Sprite_Draw_Frame(Flicker[FlickerFrame], player.x - 372, player.y - 272, 0, 800, 600, 1);
FlashTimes--;
if (FlashTimes == 0)
{
FlashTimes = 300;
FlashFlag = false;
}
}
return false;
}
//玩家二逻辑方法
bool Player2::Logic(int d)
{
double srtime = GetTickCount() - lasttime;
switch (d)
{
case Dirction::up:
Dir = Dirction::up;
player.y -= Speed*srtime / 1000;
if (player.y < 64)
player.y = 64;
break;
case Dirction::right:
Dir = Dirction::right;
player.x += Speed*srtime / 1000;
if (player.x > 840)
player.x = 840;
break;
case Dirction::below:
Dir = Dirction::below;
player.y += Speed*srtime / 1000;
if (player.y > 840)
player.y = 840;
break;
case Dirction::lift:
Dir = Dirction::lift;
player.x -= Speed*srtime / 1000;
if (player.x < 64)
player.x = 64;
break;
default:
break;
}
RECT PlayerRect = { player.x,player.y,player.x + 56,player.y + 56 };
RECT EnemyRect, Rect;
//和地图块的碰撞检测
{
int X1, Y1, X2, Y2;
switch (d)
{
case Dirction::up:
X1 = player.x / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = Y1;
break;
case Dirction::right:
X1 = (player.x + 56) / 64;
Y1 = player.y / 64;
X2 = (player.x + 56) / 64;
Y2 = (player.y + 56) / 64;
break;
case Dirction::below:
X1 = (player.x + 56) / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = Y1;
break;
case Dirction::lift:
X1 = player.x / 64;
Y1 = (player.y + 56) / 64;
X2 = player.x / 64;
Y2 = player.y / 64;
break;
default:
break;
}
MapPieceList*mp = mappiecelisthead.next;
int result1 = 0, result2 = 0;
if (X1 == X2&&Y1 == Y2)
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
else
{
while (mp != NULL)
{
if (X1 - 1 == mp->mappiece->X)
if (Y1 - 1 == mp->mappiece->Y)
result1 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
mp = mappiecelisthead.next;
while (mp != NULL)
{
if (X2 - 1 == mp->mappiece->X)
if (Y2 - 1 == mp->mappiece->Y)
result2 = mp->mappiece->PECrach(d, PlayerRect);
mp = mp->next;
}
}
if (result1 != 0 || result2 != 0)
{
switch (d)
{
case Dirction::up:
if (result1 > result2)
player.y = result1;
else
player.y = result2;
break;
case Dirction::right:
if (result2 == 0)
player.x = result1 - 56;
else if (result1 == 0)
player.x = result2 - 56;
else if (result1 < result2)
player.x = result1 - 56;
else
player.x = result2 - 56;
break;
case Dirction::below:
if (result2 == 0)
player.y = result1 - 56;
else if (result1 == 0)
player.y = result2 - 56;
else if (result1 < result2)
player.y = result1 - 56;
else
player.y = result2 - 56;
break;
case Dirction::lift:
if (result1 > result2)
player.x = result1;
else
player.x = result2;
break;
default:
break;
}
}
}
//和敌人的碰撞检测
EnemyList* ep = enemylisthead.next;
while (ep != NULL)
{
EnemyRect.left = ep->enemy->player.x;
EnemyRect.top = ep->enemy->player.y;
EnemyRect.bottom = ep->enemy->player.y + 56;
EnemyRect.right = ep->enemy->player.x + 56;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
// 碰到敌人后回退移动距离
switch (d)
{
case Dirction::up:
player.y = ep->enemy->player.y + 56;
break;
case Dirction::right:
player.x = ep->enemy->player.x - 56;
break;
case Dirction::below:
player.y = ep->enemy->player.y - 56;
break;
case Dirction::lift:
player.x = ep->enemy->player.x + 56;
break;
default:
break;
}
}
ep = ep->next;
}
//和玩家一的碰撞检测
if (Player1.Alive)
{
EnemyRect.bottom = Player1.player.y + 56;
EnemyRect.right = Player1.player.x + 56;
EnemyRect.left = Player1.player.x;
EnemyRect.top = Player1.player.y;
if (IntersectRect(&Rect, &EnemyRect, &PlayerRect))
{
switch (d)
{
case Dirction::up:
player.y = Player1.player.y + 56;
break;
case Dirction::right:
player.x = Player1.player.x - 56;
break;
case Dirction::below:
player.y = Player1.player.y - 56;
break;
case Dirction::lift:
player.x = Player1.player.x + 56;
break;
default:
break;
}
}
}
return false;
}
//
void Player2::Born()
{
Health_Point = 1;
FlashFlag = true;
if (BornPlayer2MapPiece.size() != 0)
{
int atbuf = rand() % (BornPlayer2MapPiece.size() / 2);
player.x = (BornPlayer2MapPiece.at(atbuf*2) + 1) * 64;
player.y = (BornPlayer2MapPiece.at(atbuf*2 + 1) + 1) * 64;
}
else
{
}
}
/*--------------------------------------------------------------------
玩家的方法到此结束
----------------------------------------------------------------------*/
//子弹对象构造函数
Bullet::Bullet(int shooter,int x, int y, int S, int D,int powlv) :Speed(S), Dir(D),Shooter(shooter)
{
BoomFlag = 0;
PowerLevel = powlv;
bullet.width = 16;
bullet.height = 16;
FlickerFrame = 0;
LastFrametime = GetTickCount();
switch (D)
{
case Dirction::up:
bullet.x = x + 20;
bullet.y = y;
break;
case Dirction::below:
bullet.x = x+20;
bullet.y = y+40;
break;
case Dirction::lift:
bullet.x = x;
bullet.y = y+20;
break;
case Dirction::right:
bullet.x = x + 40;
bullet.y = y + 20;
break;
default:
break;
}
}
//子弹移动和碰撞检测方法
bool Bullet::Logic()
{
//碰撞检测
double srtime = GetTickCount() - lasttime;
MovedPixel = Speed*srtime / 1000;
switch (Dir)
{
case Dirction::up:
bullet.y = bullet.y- MovedPixel;
break;
case Dirction::below:
bullet.y = bullet.y + MovedPixel;
break;
case Dirction::lift:
bullet.x = bullet.x- MovedPixel;
break;
case Dirction::right:
bullet.x = bullet.x+ MovedPixel;
break;
default:
break;
}
int result = Crash( 0,bullet.x, bullet.y, Speed, Dir,Shooter,ID, MovedPixel);
if (result == 1)
{
if(PowerLevel==0)
AddUselessObj(ID);//记录对象ID用于销毁
//创建爆炸
CreateBoom(bullet.x-20, bullet.y-20, 1, Dir);
}
if (result == 2)
{
if (PowerLevel == 0)
AddUselessObj(ID);
}
if (result == 3)
{
AddUselessObj(ID);
CreateBoom(bullet.x - 20, bullet.y - 20, 1, Dir);
}
if (result == 1 || result == 2||result==3)
return true;
return false;
}
//子弹渲染方法
bool Bullet::Draw()
{
if (BoomFlag == 0) {
switch (Dir)
{
case Dirction::up:
Sprite_Transform_Draw(Bullet_TXTTURE, bullet.x, bullet.y,
8, 8, 0, 4, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
break;
case Dirction::below:
Sprite_Transform_Draw(Bullet_TXTTURE, bullet.x, bullet.y,
8, 8, 2, 4, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
break;
case Dirction::lift:
Sprite_Transform_Draw(Bullet_TXTTURE, bullet.x, bullet.y,
8, 8, 3, 4, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
break;
case Dirction::right:
Sprite_Transform_Draw(Bullet_TXTTURE, bullet.x, bullet.y,
8, 8, 1, 4, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
break;
default:
break;
}
if (PowerLevel == 3)
{
if (GetTickCount() > LastFrametime + 50)
{
FlickerFrame = FlickerFrame < 8 ? FlickerFrame + 1 : 0;
LastFrametime = GetTickCount();
}
Sprite_Draw_Frame(Flicker[FlickerFrame], bullet.x - 392, bullet.y - 292, 0, 800, 600, 1);
}
return true;
}
else
{
return false;
}
}
/*--------------------------------------------------------------------
Class MapPiece的方法
----------------------------------------------------------------------*/
MapPiece::MapPiece()
{
rectlisthead = new RectListHead;
rectlisthead->next = NULL;
}
void MapPiece::Draw()
{
RectList*rp = rectlisthead->next;
while (rp != NULL)
{
if(rp->rect->left<32)
Sprite_Transform_Draw(Tile, (X+1)*64+rp->rect->left*2, (Y + 1) * 64+rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2,D3DCOLOR_XRGB(255, 255, 255));
else if(rp->rect->left<64)
Sprite_Transform_Draw(Tile, (X+1)*64+(rp->rect->left-32)*2, (Y + 1) * 64+rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2,D3DCOLOR_XRGB(255, 255, 255));
else if(rp->rect->left<96)
Sprite_Transform_Draw(Tile, X * 64 + rp->rect->left*2-64, (Y + 1) * 64 + rp->rect->top,
rp->rect, 0, 1, 0, 2, 2, D3DCOLOR_XRGB(255, 255, 255));
else if (rp->rect->left<128)
Sprite_Transform_Draw(Tile, (X + 1) * 64 + (rp->rect->left-96)*2, (Y + 1) * 64 + rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2, D3DCOLOR_XRGB(255, 255, 255));
else if (rp->rect->left<160)
Sprite_Transform_Draw(Tile, (X + 1) * 64 + (rp->rect->left-128)*2, (Y + 1) * 64 + rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2, D3DCOLOR_XRGB(255, 255, 255));
else if (rp->rect->left<192)
Sprite_Transform_Draw(Tile, (X + 1) * 64 + (rp->rect->left-160)*2, (Y + 1) * 64 + rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2, D3DCOLOR_XRGB(255, 255, 255));
else
Sprite_Transform_Draw(Tile, (X + 1) * 64 +( rp->rect->left-192)*2, (Y + 1) * 64 + rp->rect->top*2,
rp->rect, 0, 1, 0, 2, 2, D3DCOLOR_XRGB(255, 255, 255));
rp = rp->next;
}
}
//创建地图方框
void MapPiece::CreateMapRect(int x, int y, int wight, int hight)
{
RECT *b = new RECT;
b->left = x;
b->top = y;
b->right = x + wight;
b->bottom = y + hight;
RectList*New = new RectList;
New->rect = b;
if (rectlisthead->next == NULL)
{
rectlisthead->next = New;
New->last = NULL;
New->next = NULL;
}
else
{
if (rectlisthead->next->next != NULL)
{
New->next = rectlisthead->next->next;
rectlisthead->next->next = New;
New->next->last = New;
New->last = rectlisthead->next;
}
else
{
rectlisthead->next->next = New;
New->last = rectlisthead->next;
New->next = NULL;
}
}
}
bool MapPiece::Create(int mapid)
{
switch (mapid)
{
case 0:
break;
case 1:
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
break;
case 2:
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
break;
case 3:
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
break;
case 4:
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
break;
case 5:
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
break;
case 6:
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
break;
case 7:
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
break;
case 8:
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
break;
case 9:
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
break;
case 10:
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
break;
case 11:
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
break;
case 12:
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
break;
case 13:
CreateMapRect(16, 16, 8, 8);
CreateMapRect(24, 16, 8, 8);
CreateMapRect(16, 24, 8, 8);
CreateMapRect(24, 24, 8, 8);
CreateMapRect(0, 16, 8, 8);
CreateMapRect(8, 16, 8, 8);
CreateMapRect(0, 24, 8, 8);
CreateMapRect(8, 24, 8, 8);
CreateMapRect(0, 0, 8, 8);
CreateMapRect(8, 0, 8, 8);
CreateMapRect(0, 8, 8, 8);
CreateMapRect(8, 8, 8, 8);
CreateMapRect(16, 0, 8, 8);
CreateMapRect(24, 0, 8, 8);
CreateMapRect(16, 8, 8, 8);
CreateMapRect(24, 8, 8, 8);
break;
case 14:
CreateMapRect(32, 0, 16, 16);
break;
case 15:
CreateMapRect(48, 0, 16, 16);
break;
case 16:
CreateMapRect(48, 16, 16, 16);
break;
case 17:
CreateMapRect(32, 16, 16, 16);
break;
case 18:
CreateMapRect(32, 0, 16, 16);
CreateMapRect(48, 0, 16, 16);
break;
case 19:
CreateMapRect(48, 0, 16, 16);
CreateMapRect(48, 16, 16, 16);
break;
case 20:
CreateMapRect(48, 16, 16, 16);
CreateMapRect(32, 16, 16, 16);
break;
case 21:
CreateMapRect(32, 0, 16, 16);
CreateMapRect(32, 16, 16, 16);
break;
case 22:
CreateMapRect(32, 0, 16, 16);
CreateMapRect(48, 0, 16, 16);
CreateMapRect(32, 16, 16, 16);
break;
case 23:
CreateMapRect(32, 0, 16, 16);
CreateMapRect(48, 0, 16, 16);
CreateMapRect(48, 16, 16, 16);
break;
case 24:
CreateMapRect(48, 16, 16, 16);
CreateMapRect(32, 16, 16, 16);
CreateMapRect(48, 0, 16, 16);
break;
case 25:
CreateMapRect(48, 16, 16, 16);
CreateMapRect(32, 16, 16, 16);
CreateMapRect(32, 0, 16, 16);
break;
case 26:
CreateMapRect(48, 16, 16, 16);
CreateMapRect(32, 16, 16, 16);
CreateMapRect(32, 0, 16, 16);
CreateMapRect(48, 0, 16, 16);
break;
case 27:
CreateMapRect(64, 0, 32, 32);
break;
case 28:
CreateMapRect(96, 0, 32, 32);
break;
case 29:
CreateMapRect(128, 0, 32, 32);
break;
case 30:
CreateMapRect(160, 0, 32, 32);
break;
case 38:
CreateMapRect(192, 0, 32, 32);
break;
default:
break;
}
return false;
}
bool MapPiece::BeingCrash(bool flag2, RECT & rect, int dir, int x, int y)
{
bool flag = false, flag1 = true;
RECT Rect, Rect1, BoomRect = { 0 };
RectList*rp = rectlisthead->next;
if (rp == NULL)
return flag;
if (flag2)
{
switch (dir)
{
case Dirction::up:
BoomRect.left = x - 20;
BoomRect.top = y;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::right:
BoomRect.left = x - 40;
BoomRect.top = y - 20;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::below:
BoomRect.left = x - 20;
BoomRect.top = y - 40;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::lift:
BoomRect.left = x;
BoomRect.top = y - 20;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
default:
break;
}
}
if (rp->rect->left < 32)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + rp->rect->left * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &rect, &Rect1) || IntersectRect(&Rect, &BoomRect, &Rect1))
{
if (rp->last != NULL)
{
if (rp->next != NULL) {
rp->last->next = rp->next;
rp->next->last = rp->last;
}
else
rp->last->next = NULL;
}
else if (rp->next != NULL)
{
rp->next->last = NULL;
rectlisthead->next = rp->next;
}
else
{
rectlisthead->next = NULL;
}
delete rp;
flag = true;
if (flag1)
{
switch (dir)
{
case Dirction::up:
BoomRect.left = x - 20;
BoomRect.top = y;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::right:
BoomRect.left = x - 40;
BoomRect.top = y - 20;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::below:
BoomRect.left = x - 20;
BoomRect.top = y - 40;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
case Dirction::lift:
BoomRect.left = x;
BoomRect.top = y - 20;
BoomRect.right = BoomRect.left + 56;
BoomRect.bottom = BoomRect.top + 56;
break;
default:
break;
}
flag1 = false;
}
rp = rectlisthead->next;
}
else
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left < 64)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 32) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &rect, &Rect1))
{
if (rp->last != NULL)
{
if (rp->next != NULL) {
rp->last->next = rp->next;
rp->next->last = rp->last;
}
else
rp->last->next = NULL;
}
else if (rp->next != NULL)
{
rp->next->last = NULL;
rectlisthead->next = rp->next;
}
else
{
rectlisthead->next = NULL;
}
delete rp;
flag = true;
rp = rectlisthead->next;
}
else
rp = rp->next;
if (rp == NULL)
break;
}
}
else
{
return flag;
}
return flag;
}
int MapPiece::PECrach(int dir, RECT&playerrect)
{
RectList*rp = rectlisthead->next;
RECT Rect, Rect1;
int result = 0;
if (rp == NULL)
return result;
switch (dir)
{
case Dirction::up: {
if (rp->rect->left < 32)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + rp->rect->left * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (Rect1.bottom > result)
result = Rect1.bottom;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left < 64)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 32) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (Rect1.bottom > result)
result = Rect1.bottom;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left >= 96 && rp->rect->left < 128)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 96) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.bottom;
}
}
else if (rp->rect->left >= 128 && rp->rect->left < 160)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 128) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.bottom;
}
}
else if (rp->rect->left >= 160 && rp->rect->left < 192)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 160) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.bottom;
}
}
else
{
return 0;
}
break;
}
case Dirction::right: {
if (rp->rect->left < 32)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + rp->rect->left * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (result>Rect1.left || result == 0)
result = Rect1.left;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left < 64)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 32) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (result>Rect1.left || result == 0)
result = Rect1.left;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left >= 96 && rp->rect->left < 128)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 96) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.left;
}
}
else if (rp->rect->left >= 128 && rp->rect->left < 160)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 128) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.left;
}
}
else if (rp->rect->left >= 160 && rp->rect->left < 192)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 160) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.left;
}
}
else
{
return 0;
}
break;
}
case Dirction::below: {
if (rp->rect->left < 32)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + rp->rect->left * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (result>Rect1.top || result == 0)
result = Rect1.top;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left < 64)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 32) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (result>Rect1.top || result == 0)
result = Rect1.top;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left >= 96 && rp->rect->left < 128)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 96) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.top;
}
}
else if (rp->rect->left >= 128 && rp->rect->left < 160)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 128) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.top;
}
}
else if (rp->rect->left >= 160 && rp->rect->left < 192)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 160) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.top;
}
}
else
{
return 0;
}
break;
}
case Dirction::lift: {
if (rp->rect->left < 32)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + rp->rect->left * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (Rect1.right > result)
result = Rect1.right;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left < 64)
{
while (rp != NULL)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 32) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
if (Rect1.right > result)
result = Rect1.right;
}
rp = rp->next;
if (rp == NULL)
break;
}
}
else if (rp->rect->left >= 96 && rp->rect->left < 128)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 96) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.right;
}
}
else if (rp->rect->left >= 128 && rp->rect->left < 160)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 128) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.right;
}
}
else if (rp->rect->left >= 160 && rp->rect->left < 192)
{
Rect1.left = (X + 1) * 64 + (rp->rect->left - 160) * 2;
Rect1.top = (Y + 1) * 64 + rp->rect->top * 2;
Rect1.bottom = Rect1.top + (rp->rect->bottom - rp->rect->top) * 2;
Rect1.right = Rect1.left + (rp->rect->right - rp->rect->left) * 2;
if (IntersectRect(&Rect, &playerrect, &Rect1))
{
result = Rect1.right;
}
}
else
{
return 0;
}
break;
}
default:
break;
}
return result;
}
/*--------------------------------------------------------------------
Class MapPiece的方法到此结束
----------------------------------------------------------------------*/
<file_sep>/OurGame/Global.cpp
#include"Global.h"
namespace Global {
namespace Window {
int x = 0, y = 0;
bool EnableBackgroundRunning = true;
bool isActity = true;
int ScreenWidth;
int ScreenHeight;
int Now_GAME_STATE;
}
namespace Home {
int selectedType;
}
namespace Debug {
int currentFPS = 0;
}
namespace DesignMap {
string NewMapName;
}
namespace PlayerControl {
int Player1[5];
int Player2[5];
}
namespace Sound {
bool SoundSwicth;
}
}
<file_sep>/OurGame/DesignMapScene.cpp
#include "DesignMapScene.h"
using namespace std;
namespace DMS {
int Map[13][13];
int MapPieceChoose;
int NowMyChoose;
int NowPage;
bool IsDesigning;
void DrawNet();
void DrawMapPieceChoose(int choose);
void DrawMapPiece(int choose, int x, int y);
void DrawMap();
void UsingMouseChoose(RECT & mrect);
void DrawBlackRect(int x, int y);
void DesignMapName();
char ReadK_B();
bool WriteMapToHD(string filename);
void FillRect(RECT&rect, long l = -1, long r = -1, long t = -1, long b = -1);
string FileNameBuf;
RECT mouseRect;
LPD3DXFONT font;
LPD3DXFONT NumFont;
LPDIRECT3DTEXTURE9 Player_1 = NULL;
LPDIRECT3DTEXTURE9 Player_2 = NULL;
LPDIRECT3DTEXTURE9 Enemy_TXTTURE = NULL;
LPDIRECT3DSURFACE9 BlackRect = NULL;
LPDIRECT3DTEXTURE9 Tile = NULL;
}
using namespace DMS;
bool DesignMapScene::Init()
{
NowPage = 0;
NowMyChoose = 1;
IsDesigning = false;
HRESULT result;
font = MakeFont("微软雅黑", 86);
NumFont=MakeFont("微软雅黑", 24);
result = d3dDev->CreateOffscreenPlainSurface(
100,
100,
D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT,
&BlackRect,
NULL
);
if (result != D3D_OK)
{
ShowMessage("黑色-格子 初始化失败!");
return false;
}
Tile = LoadTexture(Resource::Texture::Tile, D3DCOLOR_XRGB(4, 4, 4));
if (!Tile)
{
ShowMessage("装载 砖 纹理失败!");
return false;
}
Enemy_TXTTURE = LoadTexture(Resource::Texture::Enemy, D3DCOLOR_XRGB(4, 4, 4));
if (!Enemy_TXTTURE)
{
ShowMessage("装载 敌人 纹理失败!");
return false;
}
Player_1 = LoadTexture(Resource::Texture::Player_1, D3DCOLOR_XRGB(0, 0, 0));
if (!Player_1)
{
ShowMessage("装载 主玩家 纹理失败!");
return false;
}
Player_2 = LoadTexture(Resource::Texture::Player_2, D3DCOLOR_XRGB(0, 0, 0));
if (!Player_2)
{
ShowMessage("装载 玩家二 纹理失败!");
return false;
}
return true;
}
void DesignMapScene::End()
{
Player_2->Release();
Player_1->Release();
Enemy_TXTTURE->Release();
BlackRect->Release();
Tile->Release();
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
Map[j][i] = 0;
FileNameBuf.clear();
}
void DesignMapScene::Update()
{
int mX, mY;
//编辑开始
if(IsDesigning)
{
if (Mouse_Button(MLButton))
{
mX = mousePoint.x / 64 - 1;
mY = mousePoint.y / 64 - 1;
if (mX >= 0 && mY >= 0 && mX <= 12 && mY <= 12)
Map[mY][mX]=NowMyChoose;
mouseRect = { mousePoint.x,mousePoint.y,mousePoint.x + 10,mousePoint.y + 10 };
UsingMouseChoose(mouseRect);
}
if (Mouse_Button(MRButton))
{
mX = mousePoint.x / 64 - 1;
mY = mousePoint.y / 64 - 1;
if (mX >= 0 && mY >= 0 && mX <= 12 && mY <= 12)
Map[mY][mX] = 0;
}
//回车键保存地图并退回主页面
if (Key_Up(DIK_RETURN))
{
WriteMapToHD(FileNameBuf);
Global::DesignMap::NewMapName = FileNameBuf;
Game_ChangeScene(GAME_STATE::Home);
}
if (Key_Up(DIK_UP))
{
NowMyChoose=NowMyChoose==1?33:NowMyChoose-1;
}
if (Key_Up(DIK_DOWN))
{
NowMyChoose=NowMyChoose==33?1:NowMyChoose+1;
}
if (Key_Up(DIK_LEFT))
{
MapPieceChoose=MapPieceChoose==0?4:MapPieceChoose-1;
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 1;
break;
case 1:
NowMyChoose = 7;
break;
case 2:
NowMyChoose = 14;
break;
case 3:
NowMyChoose = 20;
break;
case 4:
NowMyChoose = 27;
break;
default:
break;
}
}
if (Key_Up(DIK_RIGHT))
{
MapPieceChoose=MapPieceChoose==4?0:MapPieceChoose+1;
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 1;
break;
case 1:
NowMyChoose = 7;
break;
case 2:
NowMyChoose = 14;
break;
case 3:
NowMyChoose = 20;
break;
case 4:
NowMyChoose = 27;
break;
default:
break;
}
}
}
//确认文件名
else
{
DesignMapName();
}
if (Key_Up(DIK_ESCAPE))
{
Game_ChangeScene(GAME_STATE::Home);
}
}
void DesignMapScene::Render()
{
if (IsDesigning)
{
DrawNet();
DrawMap();
//画当前选择的地图块并加黑方框凸显
DrawMapPiece(NowMyChoose, mousePoint.x+10, mousePoint.y+20);
DrawBlackRect(mousePoint.x+10, mousePoint.y+20);
DrawMapPieceChoose(MapPieceChoose);
}
else
{
d3dDev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
FontPrint(font, 128, 400, "地图名称:");
if(FileNameBuf.length()!=0)
FontPrint(font, 458, 400, FileNameBuf);
}
}
void DMS::DrawBlackRect(int x, int y)
{
RECT rect;
FillRect(rect, x-3, x+67, y-3, y);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x-3, x+67, y+64, y+67);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x-3, x, y, y+64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x+64, x+67, y, y+64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
void DMS::DesignMapName()
{
char cbuf;
cbuf = ReadK_B();
if (cbuf == -2)
{
string buf = "Map\\";
buf += FileNameBuf;
buf += ".map";
ifstream find(buf);
if (find.is_open()) {
ShowMessage("已有地图使用该名称。");
FileNameBuf.clear();
}
else {
// FileNameBuf = buf;
IsDesigning = true;
}
return;
}
else if (cbuf == -1)
{
if (FileNameBuf.length() != 0)
FileNameBuf.pop_back();
}
else if (cbuf != 0)
FileNameBuf.push_back(cbuf);
}
//读取键盘按键信息
char DMS::ReadK_B()
{
if (Key_Up(DIK_BACK))
return -1;
if (Key_Up(DIK_RETURN))
return -2;
if (Key_Up(DIK_A))
return 'a';
if (Key_Up(DIK_B))
return 'b';
if (Key_Up(DIK_C))
return 'c';
if (Key_Up(DIK_D))
return 'd';
if (Key_Up(DIK_E))
return 'e';
if (Key_Up(DIK_F))
return 'f';
if (Key_Up(DIK_G))
return 'g';
if (Key_Up(DIK_H))
return 'h';
if (Key_Up(DIK_I))
return 'i';
if (Key_Up(DIK_J))
return 'j';
if (Key_Up(DIK_K))
return 'k';
if (Key_Up(DIK_L))
return 'l';
if (Key_Up(DIK_M))
return 'm';
if (Key_Up(DIK_N))
return 'n';
if (Key_Up(DIK_O))
return 'o';
if (Key_Up(DIK_P))
return 'p';
if (Key_Up(DIK_Q))
return 'q';
if (Key_Up(DIK_R))
return 'r';
if (Key_Up(DIK_S))
return 's';
if (Key_Up(DIK_T))
return 't';
if (Key_Up(DIK_U))
return 'u';
if (Key_Up(DIK_V))
return 'v';
if (Key_Up(DIK_W))
return 'w';
if (Key_Up(DIK_X))
return 'x';
if (Key_Up(DIK_Y))
return 'y';
if (Key_Up(DIK_Z))
return 'z';
if (Key_Up(DIK_0))
return '0';
if (Key_Up(DIK_1))
return '1';
if (Key_Up(DIK_2))
return '2';
if (Key_Up(DIK_3))
return '3';
if (Key_Up(DIK_4))
return '4';
if (Key_Up(DIK_5))
return '5';
if (Key_Up(DIK_6))
return '6';
if (Key_Up(DIK_7))
return '7';
if (Key_Up(DIK_8))
return '8';
if (Key_Up(DIK_9))
return '9';
return 0;
}
//写当前地图信息到硬盘
bool DMS::WriteMapToHD(string filename)
{
char buf;
string sbuf = "Map\\";
sbuf += FileNameBuf;
sbuf += ".map";
ofstream out(sbuf, ios::out | ios::binary);
if (!out.is_open())
{
ShowMessage(sbuf);
out.close();
}
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++)
{
buf = Map[i][j];
out.write(&buf, 1);
}
out.close();
return 0;
}
//填充RECT
void DMS::FillRect(RECT&rect, long l, long r , long t, long b)
{
rect.left = l;
rect.right = r;
rect.top = t;
rect.bottom = b;
}
//画辅助网格
void DMS::DrawNet()
{
RECT rect;
//for (int i = 0; i < 5; i++)
// FontPrint(font, 558 + i * 86, 400, FileNameBuf);
for (int i = 0; i < 12; i++)
{
FillRect(rect, 128 + i * 64, 131 + i * 64, 64, 896);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
for (int i = 0; i < 12; i++)
{
FillRect(rect, 64, 896, 128 + i * 64, 131 + i * 64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
FillRect(rect, 64, 896, 64, 67);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 64, 896, 895, 899);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 64, 67, 64, 896);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, 895, 899, 64, 896);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
//画地图块选项
void DMS::DrawMapPieceChoose(int choose)
{
switch (choose)
{
case 0:
DrawMapPiece(1, 928, 256);
DrawBlackRect(928, 256);
DrawMapPiece(2, 928, 340);
DrawBlackRect(928, 340);
DrawMapPiece(3, 928, 424);
DrawBlackRect(928, 424);
DrawMapPiece(4, 928, 508);
DrawBlackRect(928, 508);
DrawMapPiece(5, 928, 592);
DrawBlackRect(928, 592);
DrawMapPiece(6, 928, 676);
DrawBlackRect(928, 676);
break;
case 1:
DrawMapPiece(7, 928, 256);
DrawBlackRect(928, 256);
DrawMapPiece(8, 928, 340);
DrawBlackRect(928, 340);
DrawMapPiece(9, 928, 424);
DrawBlackRect(928, 424);
DrawMapPiece(10, 928, 508);
DrawBlackRect(928, 508);
DrawMapPiece(11, 928, 592);
DrawBlackRect(928, 592);
DrawMapPiece(12, 928, 676);
DrawBlackRect(928, 676);
DrawMapPiece(13, 928, 760);
DrawBlackRect(928, 760);
break;
case 2:
DrawMapPiece(14, 928, 256);
DrawBlackRect(928, 256);
DrawMapPiece(15, 928, 340);
DrawBlackRect(928, 340);
DrawMapPiece(16, 928, 424);
DrawBlackRect(928, 424);
DrawMapPiece(17, 928, 508);
DrawBlackRect(928, 508);
DrawMapPiece(18, 928, 592);
DrawBlackRect(928, 592);
DrawMapPiece(19, 928, 676);
DrawBlackRect(928, 676);
break;
case 3:
DrawMapPiece(20, 928, 256);
DrawBlackRect(928, 256);
DrawMapPiece(21, 928, 340);
DrawBlackRect(928, 340);
DrawMapPiece(22, 928, 424);
DrawBlackRect(928, 424);
DrawMapPiece(23, 928, 508);
DrawBlackRect(928, 508);
DrawMapPiece(24, 928, 592);
DrawBlackRect(928, 592);
DrawMapPiece(25, 928, 676);
DrawBlackRect(928, 676);
DrawMapPiece(26, 928, 760);
DrawBlackRect(928, 760);
break;
case 4:
DrawMapPiece(27, 928, 256);
DrawBlackRect(928, 256);
DrawMapPiece(28, 928, 340);
DrawBlackRect(928, 340);
DrawMapPiece(29, 928, 424);
DrawBlackRect(928, 424);
DrawMapPiece(30, 928, 508);
DrawBlackRect(928, 508);
DrawMapPiece(31, 928, 592);
DrawBlackRect(928, 592);
DrawMapPiece(32, 928, 676);
DrawBlackRect(928, 676);
DrawMapPiece(33, 928, 760);
DrawBlackRect(928, 760);
break;
default:
break;
}
}
//
void DMS::DrawMapPiece(int choose,int x,int y)
{
switch (choose)
{
case 0:break;
//
case 13:Sprite_Transform_Draw(Tile, x, y,
32, 32, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 26:Sprite_Transform_Draw(Tile, x, y,
32, 32, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 27:Sprite_Transform_Draw(Tile, x, y,
32, 32, 2, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 28:Sprite_Transform_Draw(Tile, x, y,
32, 32, 3, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 29:Sprite_Transform_Draw(Tile, x, y,
32, 32, 4, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 30:Sprite_Transform_Draw(Tile, x, y,
32, 32, 5, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 31:Sprite_Transform_Draw(Player_1, x, y, 28, 28,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 32:Sprite_Transform_Draw(Player_2, x, y, 28, 28,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 33:Sprite_Transform_Draw(Enemy_TXTTURE, x,y, 28, 28,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
//
case 1:Sprite_Transform_Draw(Tile, x, y,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 2:Sprite_Transform_Draw(Tile, x+32, y,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 3:Sprite_Transform_Draw(Tile, x+32, y+32,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 4:Sprite_Transform_Draw(Tile, x, y+32,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 5:Sprite_Transform_Draw(Tile, x, y,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 6:Sprite_Transform_Draw(Tile, x+32, y,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 7:Sprite_Transform_Draw(Tile, x, y+32,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 8:Sprite_Transform_Draw(Tile, x, y,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 9:Sprite_Transform_Draw(Tile, x, y,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 10:Sprite_Transform_Draw(Tile, x, y,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 11:Sprite_Transform_Draw(Tile, x, y+32,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 12:Sprite_Transform_Draw(Tile, x, y,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y+32,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 14:Sprite_Transform_Draw(Tile, x, y,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 15:Sprite_Transform_Draw(Tile, x+32, y,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 16:Sprite_Transform_Draw(Tile, x+32, y+32,
16, 16, 16, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 17:Sprite_Transform_Draw(Tile, x, y+32,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 18:Sprite_Transform_Draw(Tile, x, y,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 19:Sprite_Transform_Draw(Tile, x+32, y,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 20:Sprite_Transform_Draw(Tile, x, y+32,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 21:Sprite_Transform_Draw(Tile, x, y,
16, 32, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 22:Sprite_Transform_Draw(Tile, x, y,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x, y+32,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 23:Sprite_Transform_Draw(Tile, x, y,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 24:Sprite_Transform_Draw(Tile, x, y+32,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x+32, y,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 25:Sprite_Transform_Draw(Tile, x, y+32,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, x, y,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
default:
break;
}
}
//游戏地图绘画函数
void DMS::DrawMap()
{
for (int i = 0; i<13; i++)
for (int j = 0; j < 13; j++) {
switch (Map[j][i])
{
case 0:break;
//
case 13:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 26:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 27:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 2, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 28:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 3, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 29:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 4, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 30:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
32, 32, 5, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 31:Sprite_Transform_Draw(Player_1, (i + 1) * 64, (j + 1) * 64, 28, 28,
0,1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 32:Sprite_Transform_Draw(Player_2, (i + 1) * 64, (j + 1) * 64, 28, 28,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 33:Sprite_Transform_Draw(Enemy_TXTTURE, (i + 1) * 64, (j + 1) * 64, 28, 28,
0, 1, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
//
case 1:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 2:Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 3:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 96,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 4:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 5:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 6:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 7:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 8:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 9:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 10:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 0, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 11:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 14, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 12:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 1, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 96,
16, 16, 15, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 14:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 15:Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 16:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 96,
16, 16, 16, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 17:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 18:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 19:Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 20:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 21:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
16, 32, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 22:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 64,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
16, 16, 17, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 23:Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, 64 * j + 64,
16, 32, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 24:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, 64 * i + 96, (j + 1) * 64,
16, 16, 3, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
case 25:Sprite_Transform_Draw(Tile, 64 * i + 64, 64 * j + 96,
32, 16, 1, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Tile, (i + 1) * 64, (j + 1) * 64,
16, 16, 2, 14, 0, 2, D3DCOLOR_XRGB(255, 255, 255)); break;
default:
break;
}
}
}
//用鼠标选择地图块
void DMS::UsingMouseChoose(RECT &mrect)
{
RECT rect,nothing;
rect = { 928,256,992,256 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 1;
break;
case 1:
NowMyChoose = 7;
break;
case 2:
NowMyChoose = 14;
break;
case 3:
NowMyChoose = 20;
break;
case 4:
NowMyChoose = 27;
break;
default:
break;
}
return;
}
rect = { 928,256,992,340 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 2;
break;
case 1:
NowMyChoose = 8;
break;
case 2:
NowMyChoose = 15;
break;
case 3:
NowMyChoose = 21;
break;
case 4:
NowMyChoose = 28;
break;
default:
break;
}
return;
}
rect = { 928,256,992,424 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 3;
break;
case 1:
NowMyChoose = 9;
break;
case 2:
NowMyChoose = 16;
break;
case 3:
NowMyChoose = 22;
break;
case 4:
NowMyChoose = 29;
break;
default:
break;
}
return;
}
rect = { 928,256,992,508 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 4;
break;
case 1:
NowMyChoose = 10;
break;
case 2:
NowMyChoose = 17;
break;
case 3:
NowMyChoose = 23;
break;
case 4:
NowMyChoose = 30;
break;
default:
break;
}
return;
}
rect = { 928,256,992,592 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 5;
break;
case 1:
NowMyChoose = 11;
break;
case 2:
NowMyChoose = 18;
break;
case 3:
NowMyChoose = 24;
break;
case 4:
NowMyChoose = 31;
break;
default:
break;
}
return;
}
rect = { 928,256,992,676 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 6;
break;
case 1:
NowMyChoose = 12;
break;
case 2:
NowMyChoose = 19;
break;
case 3:
NowMyChoose = 25;
break;
case 4:
NowMyChoose = 32;
break;
default:
break;
}
return;
}
if (!(MapPieceChoose == 0 || MapPieceChoose == 2))
{
rect = { 928,256,992,760 + 64 };
if (IntersectRect(¬hing, &rect, &mrect))
{
switch (MapPieceChoose)
{
case 0:
NowMyChoose = 2;
break;
case 1:
NowMyChoose = 13;
break;
case 2:
NowMyChoose = 20;
break;
case 3:
NowMyChoose = 26;
break;
case 4:
NowMyChoose = 33;
break;
default:
break;
}
return;
}
}
}<file_sep>/OurGame/GameMain.h
#pragma once
#include<Windows.h>
#include"Global.h"
bool Game_Init(HWND window);
void Game_Update(HWND window);
void Game_Free(HWND window, HDC device);
void Game_Render(HWND window, HDC device);
void Game_ChangeScene(GAME_STATE to);<file_sep>/OurGame/HomeScene.h
#pragma once
#include"Scene.h"
//»¶Ó³¡¾°
class HomeScene : public virtual Scene
{
public:
bool Init();
void End();
void Update();
void Render();
private:
LPDIRECT3DSURFACE9 background = NULL;
LPD3DXFONT font;
CSound *bgm;
int choose;
private:
void Draw_Background();
bool Create_Background();
};
<file_sep>/OurGame/HomeScene.cpp
#include "HomeScene.h"
#include "Global.h"
#include "DirectX.h"
#include"GameMain.h"
using namespace Global;
using namespace Global::Window;
bool HomeScene::Create_Background()
{
background = LoadSurface(Resource::Home::Backgroud);
return background != NULL;
}
void HomeScene::Draw_Background()
{
RECT source_rect = {
0,
0,
ScreenWidth,
ScreenHeight
};
d3dDev->StretchRect(background, NULL, backBuffer, &source_rect, D3DTEXF_NONE);
}
bool HomeScene::Init()
{
OutputDebugString("欢迎场景开始初始化\n");
if (!HomeScene::Create_Background())
{
ShowMessage("背景图载入失败");
return false;
}
HomeScene::choose = 0;
HomeScene::font = MakeFont("微软雅黑", 32);
//DXSound组件是软解码,库里暂时只支持wav
//if (bgm = LoadSound(Resource::Home::BGM), bgm == NULL) {
//ShowMessage("BGM载入失败");
//return false;
//}
//LoopSound(bgm);
return true;
}
void HomeScene::End()
{
//释放背景图
background->Release();
//delete bgm;
}
void HomeScene::Update()
{
//if (Mouse_Button(MLButton))
//{
// OutputDebugString("左键单击");
//}
if (Key_Up(DIK_DOWN))
{
HomeScene::choose++;
HomeScene::choose %= 5;
}
if (Key_Up(DIK_UP))
{
HomeScene::choose = HomeScene::choose > 0 ? HomeScene::choose - 1 : 4;
HomeScene::choose %= 5;
}
if (Key_Up(DIK_SPACE))
{
Global::Home::selectedType = choose;
Global::Window::Now_GAME_STATE = 1;
switch (choose)
{
case 0:
case 1://双人游戏和单人游戏的接口一样
Game_ChangeScene(GAME_STATE::SinglePlayer);
break;
case 2:
Game_ChangeScene(GAME_STATE::DesignMap);
break;
case 3:
Game_ChangeScene(GAME_STATE::GameSatting);
break;
case 4:
Game_ChangeScene(GAME_STATE::About);
break;
default:
break;
}
}
}
void HomeScene::Render()
{
HomeScene::Draw_Background();
for (int i = 0; i < 5; i++) {
FontPrint(font, 450, 700 + i * 40, Resource::Home::OptionsStr[i], i == HomeScene::choose ? Resource::Home::SelectedColor : Resource::Home::UnselectedColor);
}
}<file_sep>/OurGame/CursorGUI.cpp
#include "CursorGUI.h"
#include"DirectX.h"
namespace GUI {
namespace Cursor {
LPDIRECT3DTEXTURE9 Cursor_Texture = NULL;
SPRITE Cursor;
//将当前鼠标位置更新到鼠标精灵位置
void Update() {
Cursor.x = mousePoint.x;
Cursor.y = mousePoint.y;
}
void Render() {
Sprite_Transform_Draw(
Cursor_Texture,
Cursor.x, Cursor.y,
Cursor.width,
Cursor.height,
0, 1, 0.0f, 1.0f,
D3DCOLOR_XRGB(255, 255, 255));
}
bool Init()
{
D3DXIMAGE_INFO Info;
//得到图片文件信息到Info
if (D3D_OK != (D3DXGetImageInfoFromFile(Resource::Cursor::Normal, &Info)))
{
MessageBox(NULL, "得到图象信息错误!", "LOAD PIC ERROR", MB_OK);
}
Cursor_Texture = LoadTexture(Resource::Cursor::Normal);
if (!Cursor_Texture) return false;
Cursor.x = Cursor.y = 0;
Cursor.width = Info.Width;
Cursor.height = Info.Height;
}
}
}
<file_sep>/OurGame/GameSettingScene.h
#pragma once
#include"Scene.h"
#include<fstream>
#include"DirectX.h"
#include"Global.h"
#include"Sound.h"
#include"GameMain.h"
class GameSettingScene :public Scene
{
public:
bool Init();
void End();
void Update();
void Render();
};<file_sep>/OurGame/AboutScene.cpp
#include "AboutScene.h"
#include"DirectX.h"
#include"GameMain.h"
float cx1 = 150, cx2 = 200, cx3 = 300;
float cx4 = 777, cx5 = 500, cx6 = 50;
float cx7 = 2333, cx8 = 666, cx9 = 555;
float c1=255, c2=255, c3 = 255;
static LPD3DXFONT font;
bool AboutScene::Init()
{
font = MakeFont("ËÎÌå", 50);
background = LoadSurface(Resource::About::Backgroud);
Could1 = LoadTexture(Resource::About::Cloud1, D3DCOLOR_XRGB(255, 255, 255));
Could2 = LoadTexture(Resource::About::Cloud2, D3DCOLOR_XRGB(255, 255, 255));
Could3 = LoadTexture(Resource::About::Cloud3, D3DCOLOR_XRGB(255, 255, 255));
Mountain = LoadTexture(Resource::About::BKG);
Feiting =LoadTexture(Resource::About::Feiting);
// return background != NULL;
if (Global::Sound::SoundSwicth)
LoopSound(Sound::BGM);
return true;
}
void AboutScene::End()
{
Sound::BGM->Stop();
background->Release();
}
/*
SPRITE sprite[5];
sprite[0].height = 80;
sprite[0].width = 200;
sprite[0].x = 124;
sprite[0].y = 440;
sprite[1].height = 144;
sprite[1].width = 354;
sprite[1].x = 600;
sprite[1].y = 300;
sprite[2].height = 62;
sprite[2].width = 210;
sprite[2].x = 700;
sprite[2].y = 700;
sprite[3].height = 135;
sprite[3].width = 314;
sprite[3].x = 211;
sprite[3].y = 0;
*/
void AboutScene::Render()
{
d3dDev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
RECT source_rect = {
0,
0,
Global::Window::ScreenWidth,
Global::Window::ScreenHeight
};
// d3dDev->StretchRect(Mountain, NULL, backBuffer, &source_rect, D3DTEXF_NONE);
Sprite_Transform_Draw(Mountain, 0, 120, 1000, 625, 0, 1, 0, 1.03, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could1, cx1, 270, 200, 80, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could2, cx2, 220, 354, 144, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could3, cx3, 280, 210, 62, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could1, cx4, 400, 200, 80, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could2, cx5, 300, 354, 144, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could3, cx6, 350, 210, 62, 0, 1, 0, 1.06, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could1, cx7, 450, 200, 80, 0, 1, 0, 1.0, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could2, cx8, 350, 354, 144, 0, 1, 0, 0.5, D3DCOLOR_XRGB(255, 255, 255));
Sprite_Transform_Draw(Could3, cx9, 480, 210, 62, 0, 1, 0, 1.01, D3DCOLOR_XRGB(255, 255, 255));
string text;
text += "×÷ÕߣºXK|YYQ";
FontPrint(font, 0, 90 ,text, D3DCOLOR_XRGB((int)c1, (int)c2, (int)c3));
c1 -= 0.5;
c2 -= 0.4;
c3 -= 0.3;
if (c1 < 0) { c1 = 255.0; }
if (c2 < 0) { c2 = 255.0; }
if (c3 < 0) { c3 = 255.0; }
cx1 -= 0.31;
cx2 -= 0.30;
cx3 -= 0.31;
if (cx1 <= -300)
{
cx1 = Global::Window::ScreenWidth+300;
}
if (cx2 <= -300)
{
cx2 = Global::Window::ScreenWidth+300;
}
if (cx3 <= -300)
{
cx3 = Global::Window::ScreenWidth+300;
}
cx4 -= 0.22;
cx5 -= 0.2;
cx6 -= 0.22;
if (cx4 <= -400)
{
cx4 = Global::Window::ScreenWidth+400;
}
if (cx5 <= -400)
{
cx5 = Global::Window::ScreenWidth + 400;
}
if (cx6 <= -400)
{
cx6 = Global::Window::ScreenWidth + 400;
}
cx7 -= 0.15;
cx8 -= 0.1;
cx9 -= 0.15;
if (cx7 <= -500)
{
cx7 = Global::Window::ScreenWidth+500;
}
if (cx8 <= -500)
{
cx8 = Global::Window::ScreenWidth + 500;
}
if (cx9 <= -500)
{
cx9 = Global::Window::ScreenWidth + 500;
}
}
void AboutScene::Update()
{
if (Key_Up(DIK_ESCAPE))
{
Game_ChangeScene(GAME_STATE::Home);
}
}
<file_sep>/OurGame/GameSettingScene.cpp
#include "GameSettingScene.h"
#pragma warning(disable:4996)
namespace GSS {
LPD3DXFONT font;
LPDIRECT3DSURFACE9 BlackRect = NULL;
LPDIRECT3DTEXTURE9 GameSettingPNG=NULL;
RECT mouseRect;
int Choose=0;
void ShowSetting(int x, int y);
bool WritePlayerSettingIbHD();
int ReadK_B();
void UsingMouseChoose(RECT & mrect);
void NowSettingFoucs();
void DrawChooseBlackRect();
void DrawBlackRect(int x, int y);
void FillRect(RECT & rect, long l, long r, long t, long b);
}
using namespace GSS;
bool GameSettingScene::Init()
{
font = MakeFont("微软雅黑", 64);
GameSettingPNG = LoadTexture(Resource::Texture::GameSetting, D3DCOLOR_XRGB(255, 255, 255));
if (!GameSettingPNG)
{
ShowMessage("装载 设置背景 纹理失败!");
return false;
}
d3dDev->CreateOffscreenPlainSurface(
100,
100,
D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT,
&BlackRect,
NULL
);
return true;
}
void GameSettingScene::End()
{
font->Release();
BlackRect->Release();
}
void GameSettingScene::Update()
{
if (Key_Up(DIK_ESCAPE))
{
WritePlayerSettingIbHD();
Game_ChangeScene(GAME_STATE::Home);
}
if (Key_Up(DIK_RETURN))
{
WritePlayerSettingIbHD();
Game_ChangeScene(GAME_STATE::Home);
}
if (Mouse_Button(MLButton))
{
mouseRect = { mousePoint.x,mousePoint.y,mousePoint.x + 10,mousePoint.y + 10 };
UsingMouseChoose(mouseRect);
}
NowSettingFoucs();
}
void GameSettingScene::Render()
{
// Sprite_Transform_Draw(GameSettingPNG, 0, 0,
// 510, 430, 0, 7, 0, 2, D3DCOLOR_XRGB(255, 255, 255));
ShowSetting(200, 100);
DrawChooseBlackRect();
}
void GSS::ShowSetting(int x, int y)
{
char buf[10];
const int Ymove = 100;
FontPrint(font, x-128, y, "玩家一:");
FontPrint(font, x, y + 1 * Ymove, "上:");
FontPrint(font, x, y + 2 * Ymove, "下:");
FontPrint(font, x, y + 3 * Ymove, "左:");
FontPrint(font, x, y + 4 * Ymove, "右:");
FontPrint(font, x, y + 5 * Ymove, "攻击:");
itoa(Global::PlayerControl::Player1[0], buf, 10);
FontPrint(font, x + 96, y + 1 * Ymove, buf);
itoa(Global::PlayerControl::Player1[1], buf, 10);
FontPrint(font, x + 96, y + 2 * Ymove, buf);
itoa(Global::PlayerControl::Player1[2], buf, 10);
FontPrint(font, x + 96, y + 3 * Ymove, buf);
itoa(Global::PlayerControl::Player1[3], buf, 10);
FontPrint(font, x + 96, y + 4 * Ymove, buf);
itoa(Global::PlayerControl::Player1[4], buf, 10);
FontPrint(font, x + 160, y + 5 * Ymove, buf);
const int Xmove = 400;
FontPrint(font, x + Xmove-128, y, "玩家二:");
FontPrint(font, x + Xmove, y + 1 * Ymove, "上:");
FontPrint(font, x + Xmove, y + 2 * Ymove, "下:");
FontPrint(font, x + Xmove, y + 3 * Ymove, "左:");
FontPrint(font, x + Xmove, y + 4 * Ymove, "右:");
FontPrint(font, x + Xmove, y + 5 * Ymove, "攻击:");
itoa(Global::PlayerControl::Player2[0], buf, 10);
FontPrint(font, x + 96 + Xmove, y + 1 * Ymove, buf);
itoa(Global::PlayerControl::Player2[1], buf, 10);
FontPrint(font, x + 96 + Xmove, y + 2 * Ymove, buf);
itoa(Global::PlayerControl::Player2[2], buf, 10);
FontPrint(font, x + 96 + Xmove, y + 3 * Ymove, buf);
itoa(Global::PlayerControl::Player2[3], buf, 10);
FontPrint(font, x + 96 + Xmove, y + 4 * Ymove, buf);
itoa(Global::PlayerControl::Player2[4], buf, 10);
FontPrint(font, x + 160 + Xmove, y + 5 * Ymove, buf);
FontPrint(font, 384, 832, "音乐:");
if (Global::Sound::SoundSwicth)
FontPrint(font, 544, 832, "开");
else
FontPrint(font, 544, 832, "关");
}
bool GSS::WritePlayerSettingIbHD()
{
char buf;
ofstream out("GameSet.set", ios::out | ios::binary);
if (!out.is_open())
{
ShowMessage("无法打开游戏的设置文件");
out.close();
return false;
}
out.seekp(0, ios::beg);
for (int i = 0; i < 5; i++)
{
buf= Global::PlayerControl::Player1[i];
out.write(&buf, 1);
}
for (int i = 0; i < 5; i++)
{
buf = Global::PlayerControl::Player2[i];
out.write(&buf, 1);
}
buf = Global::Sound::SoundSwicth;
out.write(&buf, 1);
out.close();
return true;
}
//扫描键盘按键信息
int GSS::ReadK_B()
{
if (Key_Up(DIK_A))
return DIK_A;
if (Key_Up(DIK_B))
return DIK_B;
if (Key_Up(DIK_C))
return DIK_C;
if (Key_Up(DIK_D))
return DIK_D;
if (Key_Up(DIK_E))
return DIK_E;
if (Key_Up(DIK_F))
return DIK_F;
if (Key_Up(DIK_G))
return DIK_G;
if (Key_Up(DIK_H))
return DIK_H;
if (Key_Up(DIK_I))
return DIK_I;
if (Key_Up(DIK_J))
return DIK_J;
if (Key_Up(DIK_K))
return DIK_K;
if (Key_Up(DIK_L))
return DIK_L;
if (Key_Up(DIK_M))
return DIK_M;
if (Key_Up(DIK_N))
return DIK_N;
if (Key_Up(DIK_O))
return DIK_O;
if (Key_Up(DIK_P))
return DIK_P;
if (Key_Up(DIK_Q))
return DIK_Q;
if (Key_Up(DIK_R))
return DIK_R;
if (Key_Up(DIK_S))
return DIK_S;
if (Key_Up(DIK_T))
return DIK_T;
if (Key_Up(DIK_U))
return DIK_U;
if (Key_Up(DIK_V))
return DIK_V;
if (Key_Up(DIK_W))
return DIK_W;
if (Key_Up(DIK_X))
return DIK_X;
if (Key_Up(DIK_Y))
return DIK_Y;
if (Key_Up(DIK_Z))
return DIK_Z;
if (Key_Up(DIK_0))
return DIK_0;
if (Key_Up(DIK_1))
return DIK_1;
if (Key_Up(DIK_2))
return DIK_2;
if (Key_Up(DIK_3))
return DIK_3;
if (Key_Up(DIK_4))
return DIK_4;
if (Key_Up(DIK_5))
return DIK_5;
if (Key_Up(DIK_6))
return DIK_6;
if (Key_Up(DIK_7))
return DIK_7;
if (Key_Up(DIK_8))
return DIK_8;
if (Key_Up(DIK_9))
return DIK_9;
if (Key_Up(DIK_BACK))
return DIK_BACK;
if (Key_Up(DIK_RETURN))
return DIK_RETURN;
if (Key_Up(DIK_MINUS))
return DIK_MINUS;
if (Key_Up(DIK_EQUALS))
return DIK_EQUALS;
if (Key_Up(DIK_BACK))
return DIK_BACK;
if (Key_Up(DIK_TAB))
return DIK_TAB;
if (Key_Up(DIK_LBRACKET))
return DIK_LBRACKET;
if (Key_Up(DIK_RBRACKET))
return DIK_RBRACKET;
if (Key_Up(DIK_RETURN))
return DIK_RBRACKET;
if (Key_Up(DIK_LCONTROL))
return DIK_LCONTROL;
if (Key_Up(DIK_SEMICOLON))
return DIK_SEMICOLON;
if (Key_Up(DIK_APOSTROPHE))
return DIK_APOSTROPHE;
if (Key_Up(DIK_GRAVE))
return DIK_GRAVE;
if (Key_Up(DIK_LSHIFT))
return DIK_LSHIFT;
if (Key_Up(DIK_BACKSLASH))
return DIK_BACKSLASH;
if (Key_Up(DIK_COMMA))
return DIK_COMMA;;
if (Key_Up(DIK_PERIOD))
return DIK_PERIOD;
if (Key_Up(DIK_SLASH))
return DIK_SLASH;
if (Key_Up(DIK_RSHIFT))
return DIK_RSHIFT;
if (Key_Up(DIK_MULTIPLY))
return DIK_MULTIPLY;
if (Key_Up(DIK_LMENU))
return DIK_LMENU;
if (Key_Up(DIK_SPACE))
return DIK_SPACE;
if (Key_Up(DIK_CAPITAL))
return DIK_CAPITAL;
if (Key_Up(DIK_NUMLOCK))
return DIK_NUMLOCK;
if (Key_Up(DIK_SCROLL))
return DIK_SCROLL;
if (Key_Up(DIK_NUMPAD7))
return DIK_NUMPAD7;
if (Key_Up(DIK_NUMPAD8))
return DIK_NUMPAD8;
if (Key_Up(DIK_NUMPAD9))
return DIK_NUMPAD9;
if (Key_Up(DIK_SUBTRACT))
return DIK_SUBTRACT;
if (Key_Up(DIK_NUMPAD4))
return DIK_NUMPAD4;
if (Key_Up(DIK_NUMPAD5))
return DIK_NUMPAD5;
if (Key_Up(DIK_NUMPAD6))
return DIK_NUMPAD6;
if (Key_Up(DIK_ADD))
return DIK_ADD;
if (Key_Up(DIK_NUMPAD1))
return DIK_NUMPAD1;
if (Key_Up(DIK_NUMPAD2))
return DIK_NUMPAD2;
if (Key_Up(DIK_NUMPAD3))
return DIK_NUMPAD3;
if (Key_Up(DIK_NUMPAD0))
return DIK_NUMPAD0;
if (Key_Up(DIK_DECIMAL))
return DIK_DECIMAL;
if (Key_Up(DIK_OEM_102))
return DIK_OEM_102;
if (Key_Up(DIK_KANA))
return DIK_KANA;
if (Key_Up(DIK_ABNT_C1))
return DIK_ABNT_C1;
if (Key_Up(DIK_CONVERT))
return DIK_CONVERT;
if (Key_Up(DIK_NOCONVERT))
return DIK_NOCONVERT;
if (Key_Up(DIK_YEN))
return DIK_YEN;
if (Key_Up(DIK_ABNT_C2))
return DIK_ABNT_C2;
if (Key_Up(DIK_NUMPADEQUALS))
return DIK_NUMPADEQUALS;
if (Key_Up(DIK_PREVTRACK))
return DIK_PREVTRACK;
if (Key_Up(DIK_AT))
return DIK_AT;
if (Key_Up(DIK_COLON))
return DIK_COLON;
if (Key_Up(DIK_UNDERLINE))
return DIK_UNDERLINE;
if (Key_Up(DIK_KANJI))
return DIK_KANJI;
if (Key_Up(DIK_STOP))
return DIK_STOP;
if (Key_Up(DIK_AX))
return DIK_AX;
if (Key_Up(DIK_UNLABELED))
return DIK_UNLABELED;
if (Key_Up(DIK_NEXTTRACK))
return DIK_NEXTTRACK;
if (Key_Up(DIK_NUMPADENTER))
return DIK_NUMPADENTER;
if (Key_Up(DIK_RCONTROL))
return DIK_RCONTROL;;
if (Key_Up(DIK_MUTE))
return DIK_MUTE;
if (Key_Up(DIK_CALCULATOR))
return DIK_CALCULATOR;
if (Key_Up(DIK_PLAYPAUSE))
return DIK_PLAYPAUSE;
if (Key_Up(DIK_MEDIASTOP))
return DIK_MEDIASTOP;
if (Key_Up(DIK_VOLUMEDOWN))
return DIK_VOLUMEDOWN;
if (Key_Up(DIK_VOLUMEUP))
return DIK_VOLUMEUP;
if (Key_Up(DIK_WEBHOME))
return DIK_WEBHOME;
if (Key_Up(DIK_NUMPADCOMMA))
return DIK_NUMPADCOMMA;
if (Key_Up(DIK_DIVIDE))
return DIK_DIVIDE;;
if (Key_Up(DIK_SYSRQ))
return DIK_SYSRQ;
if (Key_Up(DIK_RMENU))
return DIK_RMENU;
if (Key_Up(DIK_PAUSE))
return DIK_PAUSE;
if (Key_Up(DIK_HOME))
return DIK_HOME;
if (Key_Up(DIK_UP))
return DIK_UP;
if (Key_Up(DIK_PRIOR))
return DIK_PRIOR;
if (Key_Up(DIK_LEFT))
return DIK_LEFT;
if (Key_Up(DIK_RIGHT))
return DIK_RIGHT;
if (Key_Up(DIK_END))
return DIK_END;
if (Key_Up(DIK_DOWN))
return DIK_DOWN;
if (Key_Up(DIK_NEXT))
return DIK_NEXT;
if (Key_Up(DIK_INSERT))
return DIK_INSERT;
if (Key_Up(DIK_DELETE))
return DIK_DELETE;
if (Key_Up(DIK_LWIN))
return DIK_LWIN;
if (Key_Up(DIK_RWIN))
return DIK_RWIN;
if (Key_Up(DIK_APPS))
return DIK_APPS;
if (Key_Up(DIK_POWER))
return DIK_POWER;
if (Key_Up(DIK_SLEEP))
return DIK_SLEEP;
if (Key_Up(DIK_WAKE))
return DIK_WAKE;
if (Key_Up(DIK_WEBSEARCH))
return DIK_WEBSEARCH;
if (Key_Up(DIK_WEBFAVORITES))
return DIK_WEBFAVORITES;
if (Key_Up(DIK_WEBREFRESH))
return DIK_WEBREFRESH;
if (Key_Up(DIK_WEBSTOP))
return DIK_WEBSTOP;
if (Key_Up(DIK_WEBFORWARD))
return DIK_WEBFORWARD;
if (Key_Up(DIK_WEBBACK))
return DIK_WEBBACK;
if (Key_Up(DIK_MYCOMPUTER))
return DIK_MYCOMPUTER;
if (Key_Up(DIK_MAIL))
return DIK_MAIL;
if (Key_Up(DIK_MEDIASELECT))
return DIK_MEDIASELECT;
return -1;
}
//使用鼠标进行选择
void GSS::UsingMouseChoose(RECT&mrect)
{
RECT rect, nothing;
rect = { 296,200,424,264 };
//设置玩家一
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 0;
rect = { 296,300,424,364 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 1;
rect = { 296,400,424,464 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 2;
rect = { 296,500,424,564 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 3;
rect = { 296,600,424,664 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 4;
//设置玩家二
rect = { 696,200,824,264 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 5;
rect = { 696,300,824,364 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 6;
rect = { 696,400,824,464 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 7;
rect = { 696,500,824,564 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 8;
rect = { 696,600,824,664 };
if (IntersectRect(¬hing, &rect, &mrect))
Choose = 9;
//设置音乐开关
rect = { 544,832,608,896 };
if (IntersectRect(¬hing, &rect, &mrect))
Global::Sound::SoundSwicth= !Global::Sound::SoundSwicth;
}
//现在的设置焦点
void GSS::NowSettingFoucs()
{
int buf;
if (Choose / 5 == 0)
{
buf= ReadK_B();
if (buf != -1)
{
Global::PlayerControl::Player1[Choose] = buf;
Choose = Choose == 9 ? 0 : Choose + 1;
}
}
else
{
buf = ReadK_B();
if (buf != -1)
{
Global::PlayerControl::Player2[Choose-5] = buf;
Choose = Choose == 9 ? 0 : Choose + 1;
}
}
}
//用黑框凸显现在选择的选项
void GSS::DrawChooseBlackRect()
{
switch (Choose)
{
case 0:
DrawBlackRect(296,200);
break;
case 1:
DrawBlackRect(296,300);
break;
case 2:
DrawBlackRect(293,400);
break;
case 3:
DrawBlackRect(296,500);
break;
case 4:
DrawBlackRect(360,600);
break;
case 5:
DrawBlackRect(696,200);
break;
case 6:
DrawBlackRect(696,300);
break;
case 7:
DrawBlackRect(696,400);
break;
case 8:
DrawBlackRect(696,500);
break;
case 9:
DrawBlackRect(760,600);
break;
default:
break;
}
}
//画黑色方框
void GSS::DrawBlackRect(int x, int y)
{
RECT rect;
FillRect(rect, x - 3, x + 67, y - 3, y);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x - 3, x + 67, y + 64, y + 67);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x - 3, x, y, y + 64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
FillRect(rect, x + 64, x + 67, y, y + 64);
d3dDev->StretchRect(BlackRect, NULL, backBuffer, &rect, D3DTEXF_NONE);
}
//填充RECT
void GSS::FillRect(RECT&rect, long l, long r, long t, long b)
{
rect.left = l;
rect.right = r;
rect.top = t;
rect.bottom = b;
}
<file_sep>/OurGame/GameMain.cpp
#include"GameMain.h"
#include"Global.h"
#include"Scenes.h"
#include"DebugTools.h"
#include"GUIs.h"
#include"DirectSound.h"
//当前游戏的场景
Scene *scene = NULL;
//当前游戏状态
GAME_STATE Game_State;
//读取游戏设置
bool ReadPlayerSettingInHD();
// Startup and loading code goes here
bool Game_Init(HWND window)
{
if (!Direct3D_Init(window, Global::Window::ScreenWidth, Global::Window::ScreenHeight, Global::Window::FullScreen))
{
ShowMessage("Direct3D初始化失败");
return false;
}
if (!DirectInput_Init(window))
{
ShowMessage("Direct Input 初始化失败");
return false;
}
if (!DirectSound_Init(window)) {
ShowMessage("Direct Sound 初始化失败");
return false;
}
//初始化声音资源
Sound::Sound_Init();
//
GUI::Cursor::Init();
//
ReadPlayerSettingInHD();
//
Global::Window::Now_GAME_STATE = 0;
//声音开关
//Global::Sound::SoundSwicth = true;
//初始化玩家控制键 //完整版需要读取硬盘中的游戏配置
{
//玩家一
Global::PlayerControl::Player1[0] = VK_UP;
Global::PlayerControl::Player1[1] = VK_DOWN;
Global::PlayerControl::Player1[2] = VK_LEFT;
Global::PlayerControl::Player1[3] = VK_RIGHT;
Global::PlayerControl::Player1[4] = 0x58;
//玩家二
Global::PlayerControl::Player2[0] = 0x57;
Global::PlayerControl::Player2[1] = 0x53;
Global::PlayerControl::Player2[2] = 0x41;;
Global::PlayerControl::Player2[3] = 0x44;
Global::PlayerControl::Player2[4] = 0x4A;
}
//切换到欢迎场景
Game_ChangeScene(GAME_STATE::Home);
return true;
}
/*
逻辑处理函数
*/
void Game_Update(HWND window)
{
//获取最新的鼠标键盘输入
DirectInput_Update(window);
GUI::Cursor::Update();
//执行当前场景的Update逻辑处理函数
if (scene != NULL)
scene->Update();
//在主界面检测退出键按下后退出游戏
if (Global::Window::Now_GAME_STATE == 0)
{
if (Key_Up(DIK_ESCAPE))
PostMessage(window, WM_DESTROY, 0, 0);
}
}
/*
渲染处理函数
*/
void Game_Render(HWND window, HDC device)
{
//确认DX已经生效
if (!d3dDev) return;
//清屏
d3dDev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB(0, 65, 105, 225 ), 1.0f, 0);
//开始渲染
if (d3dDev->BeginScene())
{
spriteObj->Begin(D3DXSPRITE_ALPHABLEND);
//调用当前场景的渲染函数
if (scene != NULL)
scene->Render();
if (Global::Debug::ShowDebugInfo)
{
DebugTools::PrintMouseInfo();
}
GUI::Cursor::Render();
spriteObj->End();
d3dDev->EndScene();
//把后台缓存刷到前台显示
d3dDev->Present(NULL, NULL, NULL, NULL);
}
}
//切换游戏场景
void Game_ChangeScene(GAME_STATE to)
{
if (to != Game_State)
{
if (scene != NULL)
{
//释放当前场景的资源
scene->End();
delete scene;
}
switch (to)
{
case GAME_STATE::Home:
Global::Window::Now_GAME_STATE = 0;
scene = new HomeScene();
break;
case GAME_STATE::DoublePlayer:
case GAME_STATE::SinglePlayer:
Global::Window::Now_GAME_STATE = 1;
scene = new GamingScene();
break;
case GAME_STATE::DesignMap:
Global::Window::Now_GAME_STATE = 1;
scene = new DesignMapScene();
break;
case GAME_STATE::About:
Global::Window::Now_GAME_STATE = 1;
scene = new AboutScene();
break;
case GAME_STATE::GameSatting:
Global::Window::Now_GAME_STATE = 1;
scene = new GameSettingScene();
break;
default:
Global::Window::Now_GAME_STATE = 0;
scene = NULL;
break;
}
//调用场景的初始化函数
if (scene == NULL || !scene->Init())
{
//如果场景初始化出错则结束游戏
//这里应弹出窗口说明出错
EndApplication();
}
Game_State = to;
}
}
// 只允许在消息处理函数WinProc中调用此函数,要想关闭游戏,调用WinMain里的EndApplication
void Game_Free(HWND window, HDC device)
{
//调用场景的关闭函数并释放场景
if (scene != NULL)
{
scene->End();
delete scene;
}
DirectInput_Shutdown();
DirectSound_Shutdown();
Direct3D_Shutdown();
ReleaseDC(window, device);
}
//读取游戏设置
bool ReadPlayerSettingInHD()
{
char buf;
ifstream in("GameSet.set", ios::in | ios::binary);
if (!in.is_open())
{
ShowMessage("无法打开游戏的设置文件");
return false;
}
for (int i = 0; i < 5; i++)
{
in.read(&buf, 1);
Global::PlayerControl::Player1[i]=buf;
}
for (int i = 0; i < 5; i++)
{
in.read(&buf, 1);
Global::PlayerControl::Player2[i]=buf;
}
in.read(&buf, 1);
Global::Sound::SoundSwicth=buf;
in.close();
return true;
}
| 08771a55a94c9461a751afa324e8b9ed9ca983b0 | [
"C",
"C++"
] | 27 | C | xkWeiMeng/X-1 | ccff3fac40a2d096769fffa8540a9785e562c05f | 51e8f430594de035813b2b1a20ab958c0aa03bed |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 10:19:34 2020
@author: Danilo
"""
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier as dc
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
import pandas as pd
import utils as u
from sklearn.neighbors import KNeighborsClassifier
dataset= load_iris() #carico il dataset
dataset1=pd.read_csv(r'C:\Users\Danilo\Downloads\Ing.Conoscenza\prove\iris.csv')
X= dataset['data'] #divido i dati in due categorie: i dati morfologici
y= dataset['target'] #e l'ultima colonna contiene la classe di appartenenza del fiore
C = 10
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.5) #*train porzione di dati su cui fare training
Alb_dec=dc()
StateVector=SVC(gamma=2, kernel='linear', C=C)
knn= KNeighborsClassifier(3)
StateVector.fit(X_train,y_train) #☻addestramento dei classificatori sul training-set
Alb_dec.fit(X_train,y_train)
knn.fit(X_train,y_train)
#creazione curva precision-recall
pred_tra=Alb_dec.predict(X_train) #calcolo delle predizioni per il test-set
pred=Alb_dec.predict(X_test)
pred_SVC=StateVector.predict(X_test)
pred_knn=knn.predict(X_test)
u.pr_curve(pred,y_test,pred_SVC,pred_knn)#curva precision recall
#u.mostra_predizioni(pred.size,pred,pred_SVC,y_test,X_test)
print("Accuratezza delle predizioni sul test-set (Albero decisione) %0.1f%% "%(accuracy_score(pred,y_test)*100))
print("Accuratezza delle predizioni sul test-set (SVC) %0.1f%% " %(accuracy_score(pred_SVC,y_test)*100))
print("Accuratezza delle predizioni sul test-set (knn) %0.1f%% " %(accuracy_score(pred_knn,y_test)*100))
"""suggestion per nuovo fiore da cercare 4.9,3.1,1.5,0.1 Iris-setosa
5.6,2.8,4.9,2.0 Iris-virginica
6.3,2.3,4.4,1.3 Iris-versicolor"""
nuovo_fiore=[[4.9,3.1,1.5,0.1]]
nuovo_test_a =Alb_dec.predict(nuovo_fiore)
nuovo_test_b=StateVector.predict(nuovo_fiore)
nuovo_test_c=knn.predict(nuovo_fiore)
categoria= u.category_name(nuovo_test_a)
categoria2= u.category_name(nuovo_test_b)
categoria3= u.category_name(nuovo_test_c)
print(f'Categoria nuovo Fiore --> Albero decisione:{categoria}\n\t\t\t SVC:{categoria2}\n\t\t\t Knn:{categoria3}')
<file_sep># Progetto Ingegneria della conoscenza
Studente: <NAME>
Matricola: 676436
E-mail: <EMAIL>
## • Introduzione
Il sistema progettato consiste essenzialmente nell'applicazione di una serie di tre classificatori
di tipo Content-based ad un dataset per addestrarli e testarli su nuovi elementi, trattasi quindi di apprendimento supervisionato.
## • Algoritmi utilizzati
Nella fattispecie i tre classificatori utilizzati sono il K-Nearest-Neighbor, che effettua le sue predizioni basandosi esclusivamente sulle previsioni già date agli elementi che più gli si avvicinano secondo il criterio della similarità, appunto i suoi "vicini", l'Albero di Decisione, che partendo dalla radice valuta ogni condizione incontrata
e segue l'arco corrispondente al risultato fino ad arrivare ad una foglia che conterrà la stima puntuale della classe e il Support Vector Machine con una funzione kernel lineare che rappresenta gli esempi come punti nello spazio, mappati in modo tale che gli esempi appartenenti alle diverse categorie siano chiaramente separati da uno spazio il più possibile ampio, i nuovi esempi sono quindi mappati nello stesso spazio e la predizione della categoria alla quale appartengono viene fatta sulla base del lato nel quale ricade.
## • Apprendimento
Il dataset scelto per questo sistema si chiama Iris, ogni tupla si compone di 4 caratteristiche morfologiche del fiore ovvero: lunghezza e ampiezza del sepalo e lunghezza e ampiezza del petalo in cm', nell'ultima colonna invece vi è la classe di appartenenza del fiore, la quale è ovviamente influenzata dalle 4 caratteristiche precedenti (in questo caso ci sono 3 differenti tipi di iris: Setosa, Versicolour, e Virginica ).

Sono presenti nel dataset un totale di 150 esempi classificati.
## • Processo di sviluppo
1) Prima di tutto divido il dataset in 2 parti, una parte (Training-set) la utilizzo per addestrare i classificatori e la restante parte viene utilizzata per testare questi ultimi e le loro performance (Test-set).
2) Dopo valuto le performance dei classificatori tramite il calcolo dell'accuratezza di ciascuna predizione e il confronto di questa con il rispettivo valore reale.
3) I valori prodotti verranno poi utilizzati per calcolare per ciascun classificatore la rispettiva curva di precisione-richiamo, in modo da poterle poi mettere insieme su un grafico ed avere un confronto visivo.

I grafici sono stati integrati con la metrica AUC (Area Under the Curve) che calcola, come suggerisce il nome, l'area sottesa alla curva di precisione-richiamo, che fornisce quindi un ulteriore e più preciso confronto fra i classificatori (area > indica precisione più alta, 1 = precisione assoluta).
## • Altre funzioni
E' possibile inoltre, data una nuova tupla di caratteristiche del fiore, scelta dall'utente, utilizzare i classificatori per vedere la sua classe di appartenenza.
## • Librerie utilizzate
Per questo sistema sono state utilizzate alcune librerie, come ad esempio sklearn (https://scikit-learn.org/stable/) che permette la definizione e gestione di classificatori di questo tipo in modo abbastanza intuitivo, e pylab per la costruzione del grafico, altri metodi e metriche necessarie per il tutto sono state scritte manualmente integrando la conoscenza teorica anche di
altre discipline.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 10:29:16 2020
@author: Danilo
"""
from sklearn.datasets import load_iris
import pylab as pl
from sklearn.metrics import auc
dataset=load_iris()
X=dataset['data']
y=dataset['target']
def category_name(nuovo_test): #output nome della categoria (virginica,setosa,versicolor)
if nuovo_test==0:
categoria1= dataset.target_names[0]
elif nuovo_test==1:
categoria1= dataset.target_names[1]
else:
categoria1= dataset.target_names[2]
return categoria1
def pr_curve(pred,y_test,pred_SV,pred_knn):
#definizione variabili
precision=[]
precision_SV=[]
precision_knn=[]
recall=[]
recall_SV=[]
recall_knn=[]
k=0
#calcolo P-R per ogni predizione per il KNN
for d in range(pred_knn.size):
if(pred_knn[d]==y_test[d]):
if d==0:
precision_knn.append(1)
k=k+1
else:
precision_knn.append((k/d)) #precisione =True Positive/(False Positive+True positive)
k=k+1
else:
if d==0:
precision_knn.append(0)
else:
precision_knn.append(k/d)
recall_knn.append(k/pred_knn.size) #recall= True Positive/(True Positive+False Negative)
k=0
#calcolo P-R per ogni predizione per l'SVM
for d in range(pred_SV.size):
if(pred_SV[d]==y_test[d]):
if d==0:
precision_SV.append(1)
k=k+1
else:
precision_SV.append((k/d))
k=k+1
else:
if d==0:
precision_SV.append(0)
else:
precision_SV.append(k/d)
recall_SV.append(k/pred_SV.size)
#calcolo P-R per ogni predizione per l'albero di decisione
k=0
for d in range(pred.size):
if(pred[d]==y_test[d]):
if d==0:
precision.append(1)
k=k+1
else:
precision.append((k/d))
k=k+1
else:
if d==0:
precision.append(0)
else:
precision.append(k/d)
recall.append(k/pred.size)
# print("{%0.2f}" %precision[d],d,"{%0.2f}" %recall[d])
area = auc(recall, precision)
area_sv=auc(recall_SV,precision_SV)
area_k= auc(recall_knn,precision_knn)
print("Area Under Curve(Decision Tree): %0.2f" % area)
print("Area Under Curve(SVM): %0.2f" % area_sv)
print("Area Under Curve(Knn): %0.2f" % area_k)
pl.clf()
pl.plot(recall, precision, label="Decision Tree")
pl.plot(recall_SV,precision_SV, label="State Vector Machine")
pl.plot(recall_knn,precision_knn, label="Knn")
pl.xlabel("Recall")
pl.ylabel("Precision")
pl.ylim([0.0, 1.05])
pl.xlim([0.0, 1.0])
pl.title("Precision-Recall example: AUC=%0.2f" % ((area+area_sv+area_k)/3))
pl.legend(loc="lower left")
pl.show()
#output tutte le previsioni dei classificatori sul test-set e confronto con valori reali
def mostra_predizioni(x,pred,pred_SVC,y_test,X_test):
for d in range(x):
classe=category_name(pred[d])
classe1=category_name(pred_SVC[d])
classe2=category_name(y_test[d])
print(X_test[d],"Alb:",classe," -SVC:",classe1,"-Classe:",classe2,"\n")
| 6efb1cab9c0c9ce7f0c4b4f7faff420e739db312 | [
"Markdown",
"Python"
] | 3 | Python | DaniMe98/ICon-progetto | db29dca7a8b4480ca7da0c9213289deec996140c | a777a92b7135fe8d3500c01cb1c132a2e3514ebb |
refs/heads/master | <repo_name>pj-92-gh/project-3-turnin<file_sep>/nevada-caucus-sentiment-master/static/js/test-data/testing-data-format-3.js
var data = [
{
candidate: "<NAME>",
overall_result: "Positive",
Positive_Sentiment_Score: 67.3,
Negative_Sentiment_Score: 30.7,
general_sentiment_score: 2,
tweet_count: 6035,
positive_tweets: [
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "SalKappa",
tweet: "#PresidentSanders #BernieWonIowa #BernieWonNewHampshire #BernieBeatsTrump #BerniesGonnaWin #NevadaCaucus #SouthCarolina #FeelTheBern #NotMeUs #BigUs #Bernie2020 #Sanders2020 #BernieSanders2020 #BernieSanders #DemocraticPrimaries #2020Dem #Election2020 #TrumpFearsBerniehttps://twitter.com/kubethy/status/1229950096286081024"
},
{
status: "Post-Caucus",
date: "2020-02-19",
username: "chad_b_morrow",
tweet: "Absolutely absurd how long the line is for early voting in #NevadaCaucus"
},
{
status: "Post-Caucus",
date: "2020-02-19",
username: "DestiGrace1",
tweet: "Lordie the discussion is about dirty AF #CorruptBarr via #Maddow. Forget #PeteButtigieg you guys, @maddow is about to drop more dirty on the CORRUPT USAG #DisBarr. Apparently dude has been clandestinely shutting down cases against #CrookedTRUMP. #CNNTownHall #NevadaCaucus https://twitter.com/DestiGrace1/status/1229721358126505984"
},
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "iamwillkeating",
tweet: "#<NAME> just said his religious faith “does have implications for how I approach public office.” So much for the separation of church and state. #NevadaCaucus #2020election #CNNTownHall"
},
{
status: "Post-Caucus",
date: "2020-02-19",
username: "Magsaliciouss",
tweet: "Just picked up my Precinct Captain box for Saturday, RSVP'd to see and hear @PeteButtigieg one more time before caucus day and I'm excited for #TeamPete to bring this home in Nevada."
},
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "GoHawksThe12",
tweet: "Bernie is now the ONLY candidate with NO billionaire donors!!! #warren2020 #Bernie2020 #PetesBillionaires #WarrenMediaBlackout #PeteForAmerica #PeteForPresident #Biden2020 #Biden #SCprimary #SouthCarolinaPrimary #NVCaucus #NevadaCaucus https://twitter.com/bern_identity/status/1229945043932237824"
}
],
negative_tweets: [
{
status: "Post-Caucus",
date: "2020-02-18",
username: "gatewaypundit",
tweet: "Joe Biden Channels Hillary Clinton, Musters Fake Accent When Speaking at Nevada Black Legislative Caucus (VIDEO) @CristinaLaila1 https://www.thegatewaypundit.com/2020/02/joe-biden-channels-hillary-clinton-musters-fake-accent-when-speaking-at-nevada-black-legislative-caucus-video/ … via @gatewaypundit"
},
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "KLHirst1",
tweet: "Buffon Joe Biden Channels Hillary Clinton, Musters Fake Accent When Speaking at Nevada Black Legislative Caucus (VIDEO) https://www.thegatewaypundit.com/2020/02/joe-biden-channels-hillary-clinton-musters-fake-accent-when-speaking-at-nevada-black-legislative-caucus-video/ … via @gatewaypundit"
},
{
status: "Post-Caucus",
date: "2020-02-18",
username: "Writing_Destiny",
tweet: "Tomorrow Watch the #DemocraticDebate hosted by @NBCNews and @MSNBC Our moderators, @LesterHoltNBC @HallieJackson @ChuckTodd @VanessaHauc @RalstonReports will put the remaining candidates to the test just days ahead of the Nevada Caucus. Watch on Wednesday, 2/19 at 9PM ET. pic.twitter.com/LaNevAujXe"
},
{
status: "Post-Caucus",
date: "2020-02-18",
username: "onebagel",
tweet: "We wouldn't want to cut defense when we can let poor people suffer more and die earlier. Wow, just wow... #NVCaucus #NevadaCaucus We need a resounding @SenSanders victory in NV ti send this kind of thinking away."
},
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "mdslock",
tweet: "Major Latino group backs Sanders on eve of Nevada caucus https://www.politico.com/news/2020/02/18/national-latino-group-endorses-bernie-sanders-115712 …"
},
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "ArbaxasIsGay",
tweet: "Hey Nevada! Today's the last day to get out and EARLY VOTE for the caucus! Lots of polling locations are open around the state and you can find your closest location at http://caucus.nvdems.com ! #NVCaucus #NVcaucus2020 #FeelTheBern #Bernie2020"
}
]
},
{
candidate: "<NAME>",
overall_result: "Positive",
Positive_Sentiment_Score: 50.8,
Negative_Sentiment_Score: 46.2,
general_sentiment_score: 3,
tweet_count: 4167,
positive_tweets: [
{
status: "Post-Caucus",
date: "2020-02-19",
username: "4HollyF",
tweet: "It didn't matter to me and I just stood in line for 3 hours in LV to vote for Liz, Amy, Pete, Bernie, Joe at the Clusterfuhk Nevada calls an early caucus vote. I have a new respect for those in voter suppression states who stand line much longer. What a mess."
},
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "1nd1obravo",
tweet: "is bloomberg not participating in the nevada town hall? (maybe he bought the entire town hall?) #NevadaCaucus"
},
{
status: "Post-Caucus",
date: "2020-02-19",
username: "Steveninformed",
tweet: "#CNNTownHall #BernieSanders rocked the #NevadaCaucus wow. Excellent job. Viewer. #Democrats"
},
{
status: "Post-Caucus",
date: "2020-02-19",
username: "miamibeachfella",
tweet: "I wonder how much Bloomberg paid all the news and radio stations to get his poll numbers up. #NevadaCaucus #Bloomberg #DemocraticDebate #BernieSanders"
},
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "MIWNV",
tweet: "“You have the right to vote so exercise your right and SHOW UP, Nevada you have until 8 P.M. PACIFIC TIME to get out to early vote for the caucus” -Tameka, MIWN Ambassador https://www.facebook.com/HigherHeights4/videos/608548459712282/ …pic.twitter.com/kUYMpPraBO"
},
{
status: "Pre-Caucus",
date: "2020-02-19",
username: "engrqamarabbas5",
tweet: "Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus - CBS News https://ift.tt/2V1KLL1 Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus CBS News 2020 Nevada caucus just a week away ABC News"
}
],
negative_tweets: [
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "RoryTDC",
tweet: "'Complete Disaster' Fears Grow Over Potential Nevada Caucus Malfunction (Video) https://thedailycoin.org/2020/02/18/complete-disaster-fears-grow-over-potential-nevada-caucus-malfunction-video/ …"
},
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "DemocraticLuntz",
tweet: "Obviously conditioned on Nevada not being a caucus"
},
{
status: "Post-Caucus",
date: "2020-02-18",
username: "LilMamaMayhem",
tweet: "I've got to remember to record the Nevada Caucus tomorrow now Bloomberg got accepted to be there. This will be too funny not to see. All your money cant protect you from your worst enemy: yourself. Here's a campaign ad for all his 'supporters' pic.twitter.com/KdZgts2PSh"
},
{
status: "Post-Caucus",
date: "2020-02-18",
username: "itsstevenhudson",
tweet: "2020 Nevada caucus just a week away - https://www.youtube.com/watch?v=S9kL8Tl4-pw …"
},
{
status: "Post-Caucus",
date: "2020-02-18",
username: "DemocraticLuntz",
tweet: "Delaware and Nevada on the same day as the new first in the nation states, should Iowa and New Hampshire violate then any candidate who files for their primaries/caucus is banned from eligibility from the nomination https://twitter.com/marcushjohnson/status/1229502435116318720 …"
},
{
status: "Pre-Caucus",
date: "2020-02-18",
username: "sdmartinez2",
tweet: "#TheFixIsInNVCaucus @KyleKulinski @jimmy_dore BREAKING: Volunteers WARN Nevada Caucus Voting App WILL NOT WORK & Be 'A... https://youtu.be/R9V5f2ra3g0 via @YouTube"
}
]
}
];
<file_sep>/README.md
# project-3-turnin
Proposal:
This project will examine sentiment towards the candidates of the Nevada 2020 Caucus. We will be scraping Twitter in order to gather data, which will then be fed into our Machine Learning model. Once the data is processed, it will be displayed on an interactive website displaying sentiment statistics and a random selection of positive and negative tweets for each candidate.
<file_sep>/nevada-caucus-sentiment-master/SQL/create_tables.sql
-- ******************************************************************************************************
-- ******************************************************************************************************
-- 1. CREATE A POSTGRES DATABASE CALLED: democratic_primary_db
-- 2. RUN ALL SCRIPTS BELOW (NO NEED TO RUN ONE AT A TIME, JUST HIGHLIGHT THEM ALL AND RUN)
-- 3. RIGHT CLICK ON "Schemas" AND SELECT "Refresh"; YOU SHOULD HAVE EIGHT (8) TABLES
-- 4. IMPORT THE FOLLOWING TWO .CSV FILES INTO THE INDICATED TABLES:
--
-- IMPORT FILE INTO TABLE
-- combined_predicted.csv load_tweets
-- probability_summary_candidate_sentiment.csv probability_summary
--
-- 5. AFTER IMPORTING .CSV FILES, RUN THE processing_script.sql IN ITS ENTIRETY AFTER READING INSTRUCTIONS
-- 6. THEN, YOU SHOULD BE READY TO EXPORT TABLE FILES
-- ******************************************************************************************************
-- ******************************************************************************************************
DROP TABLE IF EXISTS aggregate_sentiment_exclude_caucus;
DROP TABLE IF EXISTS aggregate_sentiment_include_caucus;
DROP TABLE IF EXISTS load_tweets;
DROP TABLE IF EXISTS negative_tweets;
DROP TABLE IF EXISTS positive_tweets;
DROP TABLE IF EXISTS predicted_tweets CASCADE;
DROP TABLE IF EXISTS tweets_staged;
DROP TABLE IF EXISTS probability_summary;
CREATE TABLE "load_tweets" (
"index_pandas" int NOT NULL,
"time_stamp" timestamp NOT NULL,
"to_user" varchar(250) NULL,
"replies" int NOT NULL,
"retweets" int NOT NULL,
"favorites" int NOT NULL,
"username" varchar(250) NOT NULL,
"tweet_text" varchar(800) NOT NULL,
"geo" varchar(30) NULL,
"mentions" varchar(250) NULL,
"hashtags" varchar(500) NULL,
"tweet_id" varchar(50) NOT NULL,
"permalink" varchar(500) NOT NULL,
"predictor" varchar(15) NOT NULL,
"candidate" varchar(250) NULL,
"fromfile" varchar(20) NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_load_tweets" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "predicted_tweets" (
"index_pandas" int NOT NULL,
"time_stamp" timestamp NOT NULL,
"to_user" varchar(250) NULL,
"replies" int NOT NULL,
"retweets" int NOT NULL,
"favorites" int NOT NULL,
"username" varchar(250) NOT NULL,
"tweet_text" varchar(800) NOT NULL,
"geo" varchar(30) NULL,
"mentions" varchar(250) NULL,
"hashtags" varchar(500) NULL,
"tweet_id" varchar(50) NOT NULL,
"permalink" varchar(500) NOT NULL,
"predictor" varchar(15) NOT NULL,
"candidate" varchar(250) NULL,
"fromfile" varchar(20) NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"sanders" int NULL,
"biden" int NULL,
"klobuchar" int NULL,
"warren" int NULL,
"buttigieg" int NULL,
"steyer" int NULL,
"yang" int NULL,
"gabbard" int NULL,
"bloomberg" int NULL,
"trump" int NULL,
"dnc" int NULL,
"democrats" int NULL,
"caucus" int NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_predicted_tweets" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "tweets_staged" (
"candidate" varchar(20) NOT NULL,
"sentiment" varchar(15) NOT NULL,
"time_stamp" timestamp NOT NULL,
"date" date NOT NULL,
"to_user" varchar(250) NULL,
"replies" int NOT NULL,
"retweets" int NOT NULL,
"favorites" int NOT NULL,
"username" varchar(250) NOT NULL,
"tweet_text" varchar(800) NOT NULL,
"geo" varchar(30) NULL,
"mentions" varchar(250) NULL,
"hashtags" varchar(500) NULL,
"tweet_id" varchar(50) NOT NULL,
"permalink" varchar(500) NOT NULL,
"fromfile" varchar(20) NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"random_integer" int NULL,
"time_period" varchar(30) NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_tweets_staged" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "positive_tweets" (
"candidate" varchar(20) NOT NULL,
"sentiment" varchar(15) NOT NULL,
"time_period" varchar(20) NOT NULL,
"date" date NOT NULL,
"username" varchar(250) NOT NULL,
"tweet_text" varchar(800) NOT NULL,
"pos_tweet_id" bigint NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_positive_tweets" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "negative_tweets" (
"candidate" varchar(20) NOT NULL,
"sentiment" varchar(15) NOT NULL,
"time_period" varchar(20) NOT NULL,
"date" date NOT NULL,
"username" varchar(250) NOT NULL,
"tweet_text" varchar(800) NOT NULL,
"neg_tweet_id" bigint NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_negative_tweets" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "aggregate_sentiment_exclude_caucus" (
"candidate" varchar(20) NOT NULL,
"sentiment" varchar(15) NOT NULL,
"time_period" varchar(20) NOT NULL,
"date" date NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"count" int NOT NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_aggregate_sentiment_exclude_caucus" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "aggregate_sentiment_include_caucus" (
"candidate" varchar(20) NOT NULL,
"sentiment" varchar(15) NOT NULL,
"time_period" varchar(20) NOT NULL,
"date" date NOT NULL,
"tweeter_type" varchar(15) NOT NULL,
"count" int NOT NULL,
"primary_key" serial NOT NULL,
CONSTRAINT "pk_aggregate_sentiment_include_caucus" PRIMARY KEY (
"primary_key"
)
);
CREATE TABLE "probability_summary" (
"index_pandas" int NOT NULL,
"candidate" varchar(20) NOT NULL,
"negative_probability" float NOT NULL,
"positive_probability" float NOT NULL,
"results" varchar(15) NOT NULL,
"scenario" varchar(20) NOT NULL
);
ALTER TABLE "positive_tweets" ADD CONSTRAINT "fk_positive_tweets_pos_tweet_id" FOREIGN KEY("pos_tweet_id")
REFERENCES "tweets_staged" ("primary_key");
ALTER TABLE "negative_tweets" ADD CONSTRAINT "fk_negative_tweets_neg_tweet_id" FOREIGN KEY("neg_tweet_id")
REFERENCES "tweets_staged" ("primary_key");
<file_sep>/nevada-caucus-sentiment-master/static/js/visuals-tableau-initialization.js
// The following JavaScript was created by Tableau when embedding the Tableau dashboard on the Visuals.html page.
// var divElement = document.getElementById('viz1582749600472');
// var vizElement = divElement.getElementsByTagName('object')[0];
// // if ( divElement.offsetWidth > 800 ) {
// // vizElement.style.width='1366px';
// // vizElement.style.height='795px';
// // } else if ( divElement.offsetWidth > 500 ) {
// // vizElement.style.width='100%';
// // vizElement.style.height=(divElement.offsetWidth*0.75)+'px';
// // } else {
// vizElement.style.width='100%';
// vizElement.style.height='700px';
// // }
// var scriptElement = document.createElement('script');
// scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';
// vizElement.parentNode.insertBefore(scriptElement, vizElement);
var divElement = document.getElementById('viz1582749600472');
var vizElement = divElement.getElementsByTagName('object')[0];
// if ( divElement.offsetWidth > 800 ) {
// vizElement.style.width='1366px';
// vizElement.style.height='795px';
// } else if ( divElement.offsetWidth > 500 ) {
// vizElement.style.width='100%';
// vizElement.style.height=(divElement.offsetWidth*0.75)+'px';
// } else {
vizElement.style.width='100%';
vizElement.style.height='700px';
// }
var scriptElement = document.createElement('script');
scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js';
vizElement.parentNode.insertBefore(scriptElement, vizElement);
<file_sep>/nevada-caucus-sentiment-master/static/js/test-data/testing-data-format-4.js
var data = [
{
candidate: "<NAME>",
electoral_data: [
{
period: "Overall",
overall_result: "Positive",
Positive_Sentiment_Score: 57.3,
Negative_Sentiment_Score: 40.7,
general_sentiment_score: 2,
tweet_count: 9347,
positive_tweets: [
{
date: "2020-02-16",
username: "randyslovacek",
tweet: "Attended #NevadaCaucus today. Lots of long lines and patient folks waiting to cast their votes. Walking up and down the line, I heard a lot of folks talking about @PeteButtigieg and @JoeBiden. Just thought I'd throw that out there. @nvdemspic.twitter.com/bRU0ZpTZa5"
},
{
date: "2020-02-16",
username: "nyltak2015",
tweet: "#Latinos #Bernie2020 #Tulsi2020 #YangGang #NevadaCaucus @msnbc @thehill #ImmigrationReform #Borderwallpic.twitter.com/rGsRwDCO0t"
},
{
date: "2020-02-16",
username: "startledsquirel",
tweet: "No. Because it is. #corruption in the #NevadaCaucus but let’s make sure everyone knows. https://twitter.com/abdulelsayed/status/1228798156583788544 …"
},
{
date: "2020-02-16",
username: "caroltpsworld",
tweet: "Check out #NevadaCaucus #EarlyVoting there might be long lines and take a bit of time ...I think our #democracy is worth. #GoodTrouble"
},
{
date: "2020-02-16",
username: "clevergrrly",
tweet: "A great day to vote in #Nevada! Getting out in Henderson to participate in the Democratic process. #NevadaCaucus #CaucusWeekend2020 #CaucusForBernie #BernieSanders2020 #Bernie2020 #BernieSanders2020 #BernieBeatsTrump #OnlyVegaspic.twitter.com/2Urj6dGHMO – at Water Street District"
},
{
date: "2020-02-16",
username: "OzoneSwag",
tweet: "Doesn’t Nevada caucus???"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "PapaESoCo",
tweet: "Nevada's Caucus Could Implode Like Iowa: ‘They Were Handed a Complete Shit Sandwich’ https://www.vice.com/en_us/article/y3mnmy/nevadas-caucus-could-implode-like-iowa-they-were-handed-a-complete-shit-sandwich?utm_campaign=sharebutton … via @vice"
},
{
date: "2020-02-16",
username: "demmyiv",
tweet: "Not sure about that. Nevada is having early ranked choice voting for people who can't attend the caucus."
},
{
date: "2020-02-16",
username: "CBCWorldNews",
tweet: "Health care top of mind for early Democratic caucus voters in Nevada https://www.cbc.ca/news/world/nevada-democratic-caucus-health-care-1.5465667?cmp=rss …pic.twitter.com/2bhYbywflk"
},
{
date: "2020-02-16",
username: "MikeHipp10",
tweet: "#Pete2020 - Growing up gay, I thought I was the only one - #Buttigieg2020 - #ButtigiegForPresident - #Buttigieg - #TurnThePage - #WinTheEra - #NevadaCaucus - #NevadaForPete - #SouthCarolinaForPete - #LGBTQForPetepic.twitter.com/Pze7Cvmfni"
},
{
date: "2020-02-16",
username: "davwim",
tweet: "I would've said that 8 months ago. The problem is the DNC just got caught cheating in Iowa, and now one of the caucus captains is saying Nevada may be worse."
},
{
date: "2020-02-16",
username: "AbbyBrickler",
tweet: "So we’ve got the #NevadaCaucus & the #SouthCarolinaPrimary coming up soon! If you want @SenSanders to go 4 for 4, here’s what you can do:pic.twitter.com/hLHhTNrsuf"
}
]
},
{
period: "Pre-Caucus",
overall_result: "Positive",
Positive_Sentiment_Score: 67.3,
Negative_Sentiment_Score: 30.7,
general_sentiment_score: 2,
tweet_count: 6035,
positive_tweets: [
{
date: "2020-02-19",
username: "SalKappa",
tweet: "#PresidentSanders #BernieWonIowa #BernieWonNewHampshire #BernieBeatsTrump #BerniesGonnaWin #NevadaCaucus #SouthCarolina #FeelTheBern #NotMeUs #BigUs #Bernie2020 #Sanders2020 #BernieSanders2020 #BernieSanders #DemocraticPrimaries #2020Dem #Election2020 #TrumpFearsBerniehttps://twitter.com/kubethy/status/1229950096286081024"
},
{
date: "2020-02-19",
username: "iamwillkeating",
tweet: "#Mayor<NAME> just said his religious faith “does have implications for how I approach public office.” So much for the separation of church and state. #NevadaCaucus #2020election #CNNTownHall"
},
{
date: "2020-02-19",
username: "GoHawksThe12",
tweet: "Bernie is now the ONLY candidate with NO billionaire donors!!! #warren2020 #Bernie2020 #PetesBillionaires #WarrenMediaBlackout #PeteForAmerica #PeteForPresident #Biden2020 #Biden #SCprimary #SouthCarolinaPrimary #NVCaucus #NevadaCaucus https://twitter.com/bern_identity/status/1229945043932237824"
},
{
date: "2020-02-19",
username: "chad_b_morrow",
tweet: "Absolutely absurd how long the line is for early voting in #NevadaCaucus"
},
{
date: "2020-02-19",
username: "DestiGrace1",
tweet: "Lordie the discussion is about dirty AF #CorruptBarr via #Maddow. Forget #PeteButtigieg you guys, @maddow is about to drop more dirty on the CORRUPT USAG #DisBarr. Apparently dude has been clandestinely shutting down cases against #CrookedTRUMP. #CNNTownHall #NevadaCaucus https://twitter.com/DestiGrace1/status/1229721358126505984"
},
{
date: "2020-02-19",
username: "Magsaliciouss",
tweet: "Just picked up my Precinct Captain box for Saturday, RSVP'd to see and hear @PeteButtigieg one more time before caucus day and I'm excited for #TeamPete to bring this home in Nevada."
}
],
negative_tweets: [
{
date: "2020-02-18",
username: "gatewaypundit",
tweet: "Joe Biden Channels Hillary Clinton, Musters Fake Accent When Speaking at Nevada Black Legislative Caucus (VIDEO) @CristinaLaila1 https://www.thegatewaypundit.com/2020/02/joe-biden-channels-hillary-clinton-musters-fake-accent-when-speaking-at-nevada-black-legislative-caucus-video/ … via @gatewaypundit"
},
{
date: "2020-02-18",
username: "KLHirst1",
tweet: "<NAME>iden Channels Hillary Clinton, Musters Fake Accent When Speaking at Nevada Black Legislative Caucus (VIDEO) https://www.thegatewaypundit.com/2020/02/joe-biden-channels-hillary-clinton-musters-fake-accent-when-speaking-at-nevada-black-legislative-caucus-video/ … via @gatewaypundit"
},
{
date: "2020-02-18",
username: "Writing_Destiny",
tweet: "Tomorrow Watch the #DemocraticDebate hosted by @NBCNews and @MSNBC Our moderators, @LesterHoltNBC @HallieJackson @ChuckTodd @VanessaHauc @RalstonReports will put the remaining candidates to the test just days ahead of the Nevada Caucus. Watch on Wednesday, 2/19 at 9PM ET. pic.twitter.com/LaNevAujXe"
},
{
date: "2020-02-18",
username: "onebagel",
tweet: "We wouldn't want to cut defense when we can let poor people suffer more and die earlier. Wow, just wow... #NVCaucus #NevadaCaucus We need a resounding @SenSanders victory in NV ti send this kind of thinking away."
},
{
date: "2020-02-18",
username: "mdslock",
tweet: "Major Latino group backs Sanders on eve of Nevada caucus https://www.politico.com/news/2020/02/18/national-latino-group-endorses-bernie-sanders-115712 …"
},
{
date: "2020-02-18",
username: "ArbaxasIsGay",
tweet: "Hey Nevada! Today's the last day to get out and EARLY VOTE for the caucus! Lots of polling locations are open around the state and you can find your closest location at http://caucus.nvdems.com ! #NVCaucus #NVcaucus2020 #FeelTheBern #Bernie2020"
}
]
},
{
period: "Post-Caucus",
overall_result: "Positive",
Positive_Sentiment_Score: 63.3,
Negative_Sentiment_Score: 34.7,
general_sentiment_score: 2,
tweet_count: 4387,
positive_tweets: [
{
date: "2020-02-16",
username: "Jacq4Peace",
tweet: "I am not leaving it up to one guy. I just saying Reid is the person who can actually determine how the candidates will perform in the Nevada caucus, period. I support @JoeBiden 2020 for president and I am not changing."
},
{
date: "2020-02-16",
username: "re1nhardsanders",
tweet: "I thought Bloomberg was trying to get into the Nevada caucus?"
},
{
date: "2020-02-16",
username: "MikeHipp10",
tweet: "#Pete2020 - Building an encompassing coalition - #ButtigiegForPresident - #Buttigieg2020 - #Buttigieg - #TeamPete - #TurnThePage - #WinTheEra - #NevadaCaucus - #NevadaForPete - #SouthCarolinaPrimary - #SouthCarolinapic.twitter.com/ZXgvucvmBn"
},
{
date: "2020-02-16",
username: "Chacelounge",
tweet: "Vegas is favoring Bernie to win. Hard. Bernie: -330 Biden : +345 Buttigieg : +655 Klobachar: +2150 Warren: +3750 #NevadaCaucus #Bernie2020 #BernieSanders #BernieBeatsTrump #NotMeUshttps://www.google.com/amp/s/www.sportsbettingdime.com/amp/news/politics/opening-odds-win-nevada-caucuses-favor-bernie-sanders-2020/ …"
},
{
date: "2020-02-16",
username: "MangoTangoMeri",
tweet: "(2/2) I’m sure the timing has nothing to do with the fact that early voting in the Nevada caucus starts today. 'Bernie campaign surrogates and low level followers lied and smeared Yang. I have receipts...' https://bit.ly/2u2wXFd (from @BlacksForYang)"
},
{
date: "2020-02-16",
username: "nwdem",
tweet: "Important comment about the GOP pushing their voters to vote Bernie in the #NevadaCaucus to screw with our nomination process https://twitter.com/RalstonReports/status/1228780464065761280 …"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "CCEA_SJC",
tweet: "Nevada Caucus = Long Gruelling Lines https://twitter.com/peterkoltak/status/1228855874078162944 …"
},
{
date: "2020-02-16",
username: "TheWashingtonRT",
tweet: "Candidates Klobuchar and Steyer forgot the name of the president of Mexico, during their campaign in Nevada. #15thFeb #EEUU #TOPNEWS #WashigtonToday #AmyKlobuchar #TomSteyer #LopezObrador #NevadaCaucus CreditsNews https://cnn.it/2SvY5FW pic.twitter.com/1CIkq4HA21"
},
{
date: "2020-02-16",
username: "TheNVIndy",
tweet: "ICYMI Late to organize in Nevada, Klobuchar fans say Minnesota senator hitting her stride on eve of caucus Via @MichelleRindelshttps://thenevadaindependent.com/article/late-to-organize-in-nevada-klobuchar-fans-say-minnesota-senator-hitting-her-stride-on-eve-of-caucus …"
},
{
date: "2020-02-16",
username: "stefaniefogel",
tweet: "Still waiting in line at the #NevadaCaucus over 3 hours later. And there's still a ton of people here."
},
{
date: "2020-02-16",
username: "CharismaWhee",
tweet: "This goes for every single day of early voting. If you are doing the in-person caucus on the 22nd and are in line by NOON they cannot turn you away!! STAY IN LINE!!! #NevadaCaucus #NVCaucushttps://twitter.com/BiancaRecto/status/1228852572909273088 …"
},
{
date: "2020-02-16",
username: "nicktalksalot",
tweet: "It took four days for me to arrange rides for my friends to vote, despite early voting. EVERY VOTE NEEDS TO BE A NATIONAL HOLIDAY. It's easy to do and anything less is. BLATANT voter suppression. #NevadaCaucus #Bernie2020 #NVcaucus2020 #NVLocal @AndrewYang supported this idea."
}
]
},
{
period: "Pre-Debate",
overall_result: "Positive",
Positive_Sentiment_Score: 57.4,
Negative_Sentiment_Score: 41.6,
general_sentiment_score: 2,
tweet_count: 2222,
positive_tweets: [
{
date: "2020-02-16",
username: "TheRealMoatsad",
tweet: "#Nevada #NVCaucus #NevadaCaucus #NevadaCaucuses #UnidosConBernie ¡Atención! #Latinoamérica #latinos #lagente #tiobernie #latinos #latinx #EEUUhttps://twitter.com/peterdaou/status/1228859481435594752 …"
},
{
date: "2020-02-16",
username: "silentspider14",
tweet: "#NevadaCaucus #NevadaForBerniehttps://twitter.com/BiancaRecto/status/1228852572909273088 …"
},
{
date: "2020-02-16",
username: "DemocratHoosier",
tweet: "Reminder: to get any delegates from this race, the candidate has to finish at 15% or higher in the caucus. The goal for some candidates right now isn't necessarily to WIN Nevada, but to finish well enough to get delegates."
},
{
date: "2020-02-16",
username: "EdWytkind",
tweet: "Very proud that my dear friends at the 60,000 member strong @Culinary226 @unitehere are at the center of the #NVCaucus #NevadaCaucus and will be heard very loudly #PresidentialElectionhttps://twitter.com/culinary226/status/1228783118988894208 …"
},
{
date: "2020-02-16",
username: "nfoertch",
tweet: "This is the first year Nevada has early voting for the caucus and it started today at 10am"
},
{
date: "2020-02-16",
username: "LMarieB1978",
tweet: "#NevadaCaucus https://twitter.com/michigandeb1/status/1228817609757536256 …"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "bakes781",
tweet: "#NevadaCaucus https://twitter.com/DenaePFA/status/1228818623000535040 …"
},
{
date: "2020-02-16",
username: "K12Mlissa2004",
tweet: "Find early voting locations and times here. Nevada Democratic caucus early voting set to begin | Las Vegas Review-Journal #vote2020 https://www.reviewjournal.com/news/politics-and-government/nevada-democratic-caucus-early-voting-set-to-begin-1956467/amp/ …"
},
{
date: "2020-02-16",
username: "Bernie2020WA",
tweet: "There are so many amazing volunteers traveling to early primary/caucus states everyday from across Washington State! Here, Iggy, stopped by the Seattle Field Office for a send off before heading to Nevada to go knock on doors before they caucus! Thank you to the both of you! https://twitter.com/ChickenMcPoopy/status/1228757331233525760 …pic.twitter.com/jjw9ZiL026"
},
{
date: "2020-02-16",
username: "spundun",
tweet: "I read on Twitter that last time Nevada caucus was a chaos too, do you have a podcast for that?"
},
{
date: "2020-02-16",
username: "Saabturbo9000",
tweet: "yeah just ignore it. pretend like you dont know. the expectations are very stupid."
},
{
date: "2020-02-16",
username: "HRCpersists",
tweet: "Do you want Nevada to cancel it's caucus then? Because you're only going to get calm again if Bernie wins a landslide. The only thing that happened in Iowa was the party messed up while trying to implement the new DNC rules for caucuses that Bernie wanted."
}
]
},
{
period: "Post-Debate",
overall_result: "Positive",
Positive_Sentiment_Score: 67.4,
Negative_Sentiment_Score: 51.6,
general_sentiment_score: 2,
tweet_count: 3649,
positive_tweets: [
{
date: "2020-02-16",
username: "ivypacdotorg",
tweet: "#IVYPAC Nevadans and we implore you to #StayInLine to early vote in the #NevadaCaucus! If you're in line when the polls close, you will be allowed to cast your ballot https://store.ivypac.org/products/nevada-3-ivypac-feminine-cut-short-sleeve-t-shirt …"
},
{
date: "2020-02-16",
username: "PoliticsAlt77",
tweet: "This is because Nevada is a caucus, and it works differently. If one candidate doesn’t meet a minimum threshold they can join other candidates."
},
{
date: "2020-02-16",
username: "woltgan",
tweet: "THIS IS THE NEXT PRESIDENT. @BernieSanders ONE WITH THE PEOPLE! HUELGA!! @verakingxxx #BernieIsMyPresident #BernieSanders #Bernie2020 #democraticsocialism #Huelga #BernieBeatsTrump #AOC #NevadaCaucus #NevadaForBernie #LasVegas #getupstanduphttps://twitter.com/famishedcreator/status/1228779874040471552 …"
},
{
date: "2020-02-16",
username: "poop_doctor",
tweet: "Hey early voting is here for dems too. I'm currently at an early voting location for the dem caucus. You can find locations and times if you go onto the Nevada dem party site"
},
{
date: "2020-02-16",
username: "Earth2500",
tweet: "The #Bloomberg + #HillaryClinton pairing > continues the extreme corruption of #TRUMP but more systemic/tyrannical, not just focused on helping Trump + Russia. #NevadaCaucus #Nevada #SouthCarolinaPrimary #democraticdebate #BernieSanders #BernieBeatsTrump #NevadaForBerniehttps://twitter.com/sahouraxo/status/1228839321643503616 …"
},
{
date: "2020-02-16",
username: "iambatmandoug",
tweet: "On the trail: Inside the Nevada Caucus https://youtu.be/nc_n-JnWF1Y via @YouTube"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "Trumpenator2",
tweet: "@JoeBiden Black and Brown people, Joe pushed for Mass incarceration and imprisonment of minorities. He is a racist, don't be fooled. I am the one pushing for prison reform #NevadaCaucus #SouthCarolina #biden #biden2020"
},
{
date: "2020-02-16",
username: "Saabturbo9000",
tweet: "Wish they would expand on this, I like the idea that there is no standard measurement of time and it depends where you are in the galaxy."
},
{
date: "2020-02-16",
username: "TwoThousand_17",
tweet: "Actually the drama is going to come from the early votes who are going to be “virtually caucusing” with their living breathing neighbors at the actual caucus and somehow their realignment votes are supposed to be seamlessly folded into the live action votes!"
},
{
date: "2020-02-16",
username: "bakes781",
tweet: "#NevadaCaucus https://twitter.com/toJamesConnor/status/1228848078645387264 …"
},
{
date: "2020-02-16",
username: "IndianWoof",
tweet: "Knocking doors in Nevada #Bernie2020 6 early caucus commit cards (one card is husband and wife) pic.twitter.com/Im7dZJWns6"
},
{
date: "2020-02-16",
username: "Josh_Reif",
tweet: "PREDICTION: After next week, the Nevada Caucus will be renamed the Fyre Festival caucus. #NevadaCaucus"
}
]
}
]
},
{
candidate: "<NAME>",
electoral_data: [
{
period: "Overall",
overall_result: "Positive",
Positive_Sentiment_Score: 55.8,
Negative_Sentiment_Score: 41.2,
general_sentiment_score: 3,
tweet_count: 8026,
positive_tweets: [
{
date: "2020-02-16",
username: "CherylSeas",
tweet: "Congratulations to the people in Nevada who patiently waited to vote in the most important caucus of their lives! Thank you!"
},
{
date: "2020-02-16",
username: "cfirmleader",
tweet: "Trump to rally in Las Vegas on eve of Nevada's crucial Democratic presidential caucus- so you not see Satans pattern in Trump? It is there folks- Satan/Trump they are synonyms in 2020 https://flip.it/pwt350"
},
{
date: "2020-02-16",
username: "2Dmonds1Pistol",
tweet: "#NevadaCaucus #NVEarlyVoting Votes are voided if you fill out early vote preference wrong. You can fill in the list up to 5 candidates. You will get vote voided if you put one name three times. Put <NAME> then uncommitted on next 2 lines."
},
{
date: "2020-02-16",
username: "DrStapes85",
tweet: "Line was over 2 hours at library with no movement for over 30 minutes. Trying another location... this doesn’t bode well for #NevadaCaucus or @TheDemocrats."
},
{
date: "2020-02-16",
username: "SalKappa",
tweet: "#MedicareForAll #PresidentSanders #BernieWonIowa #BernieWonNewHampshire #BernieBeatsTrump #BerniesGonnaWin #NevadaCaucus #SouthCarolina #FeelTheBern #NotMeUs #BigUs #Bernie2020 #Sanders2020 #BernieSanders2020 #BernieSanders #DemocraticPrimaries #2020Dem #Election2020https://twitter.com/HeatherGautney/status/1228820798892380160 …"
},
{
date: "2020-02-16",
username: "VillarosaArts",
tweet: "If only there was senator running for President in #Election2020 whom Obama really liked and really accomplished a lot with..... #NevadaCaucus #California #SouthCarolinaPrimary https://twitter.com/PhotosByBeanz/status/1228711305353269248 …pic.twitter.com/d3e8GC0i6T"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "PolitiMonkey",
tweet: "We’re experimenting with #BernieSanders phone cases... Let us know what you think. #BernieIsMyPresident #BernieSanders2020 #Democrats2020 #NevadaCaucus #NevadaForBernie #NevadaCaucusespic.twitter.com/VNxWZ3oIv5"
},
{
date: "2020-02-16",
username: "LeeBorowska",
tweet: "#CulinaryUnion #Culinary226 workers, of course #Bernie supports you as do I! #Unionstrong !! #NV #NVCaucus #Nevadacaucus #NVUnion #NVDemocrats #NV4Berniehttps://twitter.com/CPDAction/status/1228777272519221248 …"
},
{
date: "2020-02-16",
username: "SGailAdam",
tweet: "Caucus worker warns Nevada is 'on the path to becoming another Iowa' https://www.fox5vegas.com/news/caucus-worker-warns-nevada-is-on-the-path-to-becoming/article_d5dfb1f6-4e30-11ea-a2cd-676e8152b2f9.html?utm_medium=social&utm_source=twitter&utm_campaign=user-share … via @fox5vegas"
},
{
date: "2020-02-16",
username: "CrazyBernie2020",
tweet: "#NevadaCaucus https://twitter.com/BernieSanders/status/1228727331851788288 …"
},
{
date: "2020-02-16",
username: "LeeBorowska",
tweet: "#CulinaryUnion #Culinary226 workers, of course #Bernie supports you as do I! #Unionstrong !! #NV #NVCaucus #Nevadacaucus #NVUnion #NVDemocrats #NV4Berniehttps://twitter.com/GaiaBoy/status/1228778309506326528 …"
},
{
date: "2020-02-16",
username: "JordiAGarcia",
tweet: "Another Iowa caucus debacle. 3 and a half hour wait to vote in Nevada. The Dems have to get there act together to have a shot against the man himself. @realDonaldTrump #NevadaCaucus #Democrats2020 #Republican #CNN @CNN #vote #VoteBlue #VoteRedpic.twitter.com/b2fGT0cEYj"
}
]
},
{
period: "Pre-Caucus",
overall_result: "Positive",
Positive_Sentiment_Score: 50.8,
Negative_Sentiment_Score: 46.2,
general_sentiment_score: 3,
tweet_count: 4167,
positive_tweets: [
{
date: "2020-02-19",
username: "4HollyF",
tweet: "It didn't matter to me and I just stood in line for 3 hours in LV to vote for Liz, Amy, Pete, Bernie, Joe at the Clusterfuhk Nevada calls an early caucus vote. I have a new respect for those in voter suppression states who stand line much longer. What a mess."
},
{
date: "2020-02-19",
username: "1nd1obravo",
tweet: "is bloomberg not participating in the nevada town hall? (maybe he bought the entire town hall?) #NevadaCaucus"
},
{
date: "2020-02-19",
username: "Steveninformed",
tweet: "#CNNTownHall #BernieSanders rocked the #NevadaCaucus wow. Excellent job. Viewer. #Democrats"
},
{
date: "2020-02-19",
username: "miamibeachfella",
tweet: "I wonder how much Bloomberg paid all the news and radio stations to get his poll numbers up. #NevadaCaucus #Bloomberg #DemocraticDebate #BernieSanders"
},
{
date: "2020-02-19",
username: "MIWNV",
tweet: "“You have the right to vote so exercise your right and SHOW UP, Nevada you have until 8 P.M. PACIFIC TIME to get out to early vote for the caucus” -Tameka, MIWN Ambassador https://www.facebook.com/HigherHeights4/videos/608548459712282/ …pic.twitter.com/kUYMpPraBO"
},
{
date: "2020-02-19",
username: "engrqamarabbas5",
tweet: "Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus - CBS News https://ift.tt/2V1KLL1 Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus CBS News 2020 Nevada caucus just a week away ABC News"
}
],
negative_tweets: [
{
date: "2020-02-18",
username: "RoryTDC",
tweet: "'Complete Disaster' Fears Grow Over Potential Nevada Caucus Malfunction (Video) https://thedailycoin.org/2020/02/18/complete-disaster-fears-grow-over-potential-nevada-caucus-malfunction-video/ …"
},
{
date: "2020-02-18",
username: "DemocraticLuntz",
tweet: "Obviously conditioned on Nevada not being a caucus"
},
{
date: "2020-02-18",
username: "LilMamaMayhem",
tweet: "I've got to remember to record the Nevada Caucus tomorrow now Bloomberg got accepted to be there. This will be too funny not to see. All your money cant protect you from your worst enemy: yourself. Here's a campaign ad for all his 'supporters' pic.twitter.com/KdZgts2PSh"
},
{
date: "2020-02-18",
username: "itsstevenhudson",
tweet: "2020 Nevada caucus just a week away - https://www.youtube.com/watch?v=S9kL8Tl4-pw …"
},
{
date: "2020-02-18",
username: "DemocraticLuntz",
tweet: "Delaware and Nevada on the same day as the new first in the nation states, should Iowa and New Hampshire violate then any candidate who files for their primaries/caucus is banned from eligibility from the nomination https://twitter.com/marcushjohnson/status/1229502435116318720 …"
},
{
date: "2020-02-18",
username: "sdmartinez2",
tweet: "#TheFixIsInNVCaucus @KyleKulinski @jimmy_dore BREAKING: Volunteers WARN Nevada Caucus Voting App WILL NOT WORK & Be 'A... https://youtu.be/R9V5f2ra3g0 via @YouTube"
}
]
},
{
period: "Post-Caucus",
overall_result: "Positive",
Positive_Sentiment_Score: 58.8,
Negative_Sentiment_Score: 38.2,
general_sentiment_score: 3,
tweet_count: 5051,
positive_tweets: [
{
date: "2020-02-16",
username: "Anti45Potus2020",
tweet: "Caucus worker warns Nevada is 'on the path to becoming another Iowa' | Las Vegas Local Breaking News, Headlines | http://fox5vegas.com https://www.fox5vegas.com/news/caucus-worker-warns-nevada-is-on-the-path-to-becoming/article_d5dfb1f6-4e30-11ea-a2cd-676e8152b2f9.html …"
},
{
date: "2020-02-16",
username: "Ray_Phenicie",
tweet: "For anyone doing #EarlyVoting in NV, listen up. #NevadaCaucus https://twitter.com/amy4thepeople/status/1228690217642733570 …"
},
{
date: "2020-02-16",
username: "monkeymoo1992",
tweet: "I'm new to the state. This is my first time voting in Nevada. It is a paper ballot. You pick three in different columns. You can choose Andrew Yang in each column. Not sure what to do but will show up on caucus day to do what I can."
},
{
date: "2020-02-16",
username: "wilnernau",
tweet: "The Technology 202: Google is working with Nevada caucus officials to prevent an Iowa repeat - https://goo.gl/alerts/d9NdE #GoogleAlerts"
},
{
date: "2020-02-16",
username: "Saabturbo9000",
tweet: "I still can't find any information on how people within Star Wars count years. It can't be BBY/ABY before the Battle of Yavin because how would people in the Clone Wars know to count down to that battle happening in 20 years."
},
{
date: "2020-02-16",
username: "ThisIsReno",
tweet: "Sen. <NAME> returns to northern Nevada ahead of Democratic caucus https://buff.ly/2SZW6Jd"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "bakes781",
tweet: "#NevadaCaucus #dacahttps://twitter.com/PeteForAmerica/status/1228850086689595397 …"
},
{
date: "2020-02-16",
username: "TheRealMoatsad",
tweet: "what do you know @NVDEMS my son gets to the to early vote after 4 hours in line - I double check his registration prior, and yesterday. and behold - has to re register because they cannot find his records that I know are good. @NVDEMS @BERNIESANDERS #NevadaCaucus #NVCaucus"
},
{
date: "2020-02-16",
username: "CharlieFeigin",
tweet: "Don't get too excited. #NewHampshirePrimary definitely didn't skew to the most optimistic polls/forecasts. But if we work hard enough to smash the #NevadaCaucus we may even take the #SouthCarolinaPrimary for @BernieSanders #NotMeUshttps://twitter.com/PpollingNumbers/status/1228855541264453632 …"
},
{
date: "2020-02-16",
username: "HilarieGrey",
tweet: "Hey that’s my photo Still here, 1 hour & 40 minutes in #persist #NVcaucus2020 #NevadaCaucus #NVerthelesshttps://twitter.com/8NewsNow/status/1228838844407189504 …"
},
{
date: "2020-02-16",
username: "keith_silver",
tweet: "We want <NAME>. #NevadaCaucus #NeverBloomberg"
},
{
date: "2020-02-16",
username: "Blindedbyreligi",
tweet: "#NevadaCaucus super impressed with the long ass line for early voting. Closes in 20 minutes and I'm wayyyyy back in line"
}
]
},
{
period: "Pre-Debate",
overall_result: "Positive",
Positive_Sentiment_Score: 63.8,
Negative_Sentiment_Score: 38.2,
general_sentiment_score: 3,
tweet_count: 5123,
positive_tweets: [
{
date: "2020-02-16",
username: "MSNBCNN1",
tweet: "#NevadaCaucus DNC rule is trying to undermine the voters with no second and third choice by making it confusing and throwing out ballots with just @BernieSanders selected. Democracy at action."
},
{
date: "2020-02-16",
username: "honorverity",
tweet: "TRUMP PLANS TO DISRUPT DEMOCRATIC EVENTS AND FLOOD CITIES WITH COUNTER TRUMP RALLY CROWDS. Trump to rally in Las Vegas on eve of Nevada's crucial Democratic presidential caucus https://flip.it/8fe2Qq"
},
{
date: "2020-02-16",
username: "MonicaHabla",
tweet: "NEVADA I LOVE YOU. Six hours straight of early caucus goers and I barely had a chance to look up from my lists. Bravo @nvdems!!!"
},
{
date: "2020-02-16",
username: "CCDBC",
tweet: "The 'pay for play' crippling #Congress & #politics in America has got to STOP. We simply want our government back. One that serves the American people, not just corporate interests #WealthGap #justiceReforms #EducationEquity #equality #BernieSanders #NevadaCaucus @NevadaforBerniepic.twitter.com/kd4NWKM1dU"
},
{
date: "2020-02-16",
username: "MSNBCNN1",
tweet: "#NevadaCaucus DNC rule is trying to undermine the voters with no second and third choice by making it confusing and throwing out ballots with just @BernieSanders selected. Democracy at action."
},
{
date: "2020-02-16",
username: "e_c_sanders",
tweet: "Nevada voters, important information regarding early voting! #NevadaForBernie #GOTV #NevadaCaucus #nevadaprimarypic.twitter.com/VZPkIl1WuA"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "quizzaciou",
tweet: "a contested convention in the nevada caucus?"
},
{
date: "2020-02-16",
username: "PaulaVotesBLUE",
tweet: "#Nevada our early voting started TODAY! Thanks to an entirely #DEMOCRATIC Gov't. You couldn't do this before. You had to #caucus on one day only. If you had it off. Only in one place. But you have three more days to vote in ANY PLACE YOU EARLY VOTE. #GOTV"
},
{
date: "2020-02-16",
username: "Electric_Erik",
tweet: "#NVcaucus2020 This is how to vote for Bernie! #Bernie2020 #NevadaForBernie #NevadaCaucus #UnidosConBernie #TioBerniehttps://twitter.com/fightdenial/status/1228833139339849729 …"
},
{
date: "2020-02-16",
username: "Dr4Socialist",
tweet: "If this happens, fireworks my friends. #Bernie2020 #NevadaCaucus https://twitter.com/PpollingNumbers/status/1228855541264453632 …"
},
{
date: "2020-02-16",
username: "ungaro",
tweet: "Can anyone pls deny or verify this? “Nevada Dem Party made a last min rule change to toss ballots that only name one choice (rather than top 3 choices).” @JamesFallows @donnabrazile @CiaraVinzant @TomPerez #NevadaDemParty #NevadaCaucus @BP4B2020 #NevadaEarlyVoting @Latinx4Bernie https://twitter.com/abdulelsayed/status/1228798156583788544 …"
},
{
date: "2020-02-16",
username: "marteeno9",
tweet: "Two hour wait to early caucus? I’m going to vote for tRump. This is asinine. Nevada needs to do it like Oregon. Mail in ballots, only. And a real primary. Forget this caucus nonsense!!!"
}
]
},
{
period: "Post-Debate",
overall_result: "Negative",
Positive_Sentiment_Score: 43.8,
Negative_Sentiment_Score: 58.2,
general_sentiment_score: 3,
tweet_count: 2346,
positive_tweets: [
{
date: "2020-02-16",
username: "lesleyanna87",
tweet: "So. Darn. Heartwarming. #NevadaCaucus https://twitter.com/joebiden/status/1228806692353249280 …"
},
{
date: "2020-02-16",
username: "wheresmyelf",
tweet: "This is literally fucking voter suppression. #NevadaCaucus #Nevadavotersuppression the party knows a lot of Bernie supporters are singularly Bernie voters and they are pulling the padge! #dempartypullingthepadgehttps://twitter.com/BernieSanders/status/1228727331851788288 …"
},
{
date: "2020-02-16",
username: "letitbe1023",
tweet: "#DemDebate #NevadaCaucus #SouthCarolinaPrimary #BernieIsACommunist #BloombergIsAFascist #warrenisasnake #ButtigiegIsAMarxisthttps://twitter.com/bee_a_rebel/status/1228796152532746240 …"
},
{
date: "2020-02-16",
username: "Culinary226",
tweet: "First day of early voting almost done! Hundreds of Culinary Union members came down to cast their ranked preferences today. Tomorrow the early vote location at the Culinary Union (1630 South Commerce Street Las Vegas, NV 89102) is open from 1-5pm. #NevadaCaucus #wevotewewinpic.twitter.com/Z44VrTD2oY"
},
{
date: "2020-02-16",
username: "FR3SH0PS",
tweet: "Very hard to game Nevada caucus... that is short of ballot stuffing/deadvote/grammy/throwing away/misplacing votes. LOL"
},
{
date: "2020-02-16",
username: "TheRealMoatsad",
tweet: "#Nevada #NevadaCaucus #NVCaucus #NevadaCaucus #NevadaCaucuses #UnidosConBernie ¡Atención! #Latinoamérica #latinos #lagente #tiobernie #latinos #latinx #EEUUhttps://twitter.com/TheRealMoatsad/status/1228850262963453953 …"
}
],
negative_tweets: [
{
date: "2020-02-16",
username: "rmgg5553",
tweet: "Re: Nevada Caucus - 'digital tool' not yet available. https://twitter.com/JordanChariton/status/1228796930756694022 …"
},
{
date: "2020-02-16",
username: "tmgj24",
tweet: "#NevadaCaucuses, #NevadaCaucus, #EarlyVoting Waiting in line to early vote. Line is not moving at all!"
},
{
date: "2020-02-16",
username: "HRC_NV",
tweet: "NEVADA: Early voting has begun! Find caucus and early voting info at http://hrc.org/Nevada . @HRC is out at the @thecenterlv's early vote site — if you're in the area, come join us and cast your ballot. Thanks to @GovSisolak for turning out today!pic.twitter.com/E7jfUQv1Lz"
},
{
date: "2020-02-16",
username: "MizJoni",
tweet: "Faith, Deb! We started early voting in Nevada today ahead of the 2/22 caucus. I sense a quiet revolution going on that enough is enough."
},
{
date: "2020-02-16",
username: "RyanMcTHANOS",
tweet: "YO WHEN DO THE RESULTS OF THE EARLY VOTING AT THE NEVADA CAUCUS COME IN? OR DOES IT GET COUNTED ON ELECTION NIGHT? #Bernie2020"
},
{
date: "2020-02-16",
username: "rhoadstweet",
tweet: "Insubordinate........ and Churlish #NevadaCaucus #NevadaForPete 'Buttigieg campaign says actor Keegan-Michael Key is not endorsing him'https://twitter.com/i/events/1228744865975898112 …"
}
]
}
]
}
];
<file_sep>/nevada-caucus-sentiment-master/static/js/test-data/informative-features.js
var feature_data = [
{
word: "presidential",
sentiment: "gen : neg",
weighting: 28.3,
ratio: 1.0
},
{
word: "season",
sentiment: "gen : pos",
weighting: 28.2,
ratio: 1.0
},
{
word: "biden",
sentiment: "neg : gen",
weighting: 25.4,
ratio: 1.0
},
{
word: "eve",
sentiment: "gen : neg",
weighting: 24.5,
ratio: 1.0
},
{
word: "backs",
sentiment: "pos : neg",
weighting: 23.5,
ratio: 1.0
},
{
word: "major",
sentiment: "pos : neg",
weighting: 23.5,
ratio: 1.0
},
{
word: "berniebeatstrump",
sentiment: "pos : gen",
weighting: 22.5,
ratio: 1.0
},
{
word: "notmeus",
sentiment: "pos : gen",
weighting: 21.8,
ratio: 1.0
},
{
word: "group",
sentiment: "pos : neg",
weighting: 17.4,
ratio: 1.0
},
{
word: "like",
sentiment: "neg : gen",
weighting: 17.4,
ratio: 1.0
},
{
word: "nvcaucus",
sentiment: "pos : gen",
weighting: 17.1,
ratio: 1.0
},
{
word: "video",
sentiment: "neg : gen",
weighting: 16.6,
ratio: 1.0
},
{
word: "legislative",
sentiment: "neg : gen",
weighting: 15.7,
ratio: 1.0
},
{
word: "channels",
sentiment: "neg : pos",
weighting: 14.9,
ratio: 1.0
},
{
word: "fake",
sentiment: "neg : pos",
weighting: 14.9,
ratio: 1.0
},
{
word: "accent",
sentiment: "neg : pos",
weighting: 14.9,
ratio: 1.0
},
{
word: "musters",
sentiment: "neg : pos",
weighting: 14.9,
ratio: 1.0
},
{
word: "clinton",
sentiment: "neg : pos",
weighting: 14.1,
ratio: 1.0
},
{
word: "disaster",
sentiment: "neg : pos",
weighting: 12.4,
ratio: 1.0
},
{
word: "latino",
sentiment: "pos : neg",
weighting: 11.5,
ratio: 1.0
},
{
word: "reno",
sentiment: "gen : neg",
weighting: 11.3,
ratio: 1.0
},
{
word: "joe",
sentiment: "neg : gen",
weighting: 10.9,
ratio: 1.0
},
{
word: "medicareforall",
sentiment: "pos : gen",
weighting: 10.4,
ratio: 1.0
},
{
word: "candidates",
sentiment: "gen : neg",
weighting: 10.0,
ratio: 1.0
},
{
word: "bloomberg",
sentiment: "neg : gen",
weighting: 9.9,
ratio: 1.0
},
{
word: "speaking",
sentiment: "neg : gen",
weighting: 9.9,
ratio: 1.0
},
{
word: "hillary",
sentiment: "neg : pos",
weighting: 9.4,
ratio: 1.0
},
{
word: "process",
sentiment: "neg : pos",
weighting: 9.2,
ratio: 1.0
},
{
word: "warren",
sentiment: "pos : gen",
weighting: 8.4,
ratio: 1.0
},
{
word: "primary",
sentiment: "gen : neg",
weighting: 8.0,
ratio: 1.0
},
{
word: "rallies",
sentiment: "gen : neg",
weighting: 8.0,
ratio: 1.0
},
{
word: "university",
sentiment: "gen : neg",
weighting: 8.0,
ratio: 1.0
},
{
word: "many",
sentiment: "neg : gen",
weighting: 7.7,
ratio: 1.0
},
]<file_sep>/nevada-caucus-sentiment-master/README.md
# final-project
Proposal:
This project will examine sentiment towards the candidates of the Nevada 2020 Caucus. We will be scraping Twitter in order to gather data, which will then be fed into our Machine Learning model. Once the data is processed, it will be displayed on an interactive website displaying sentiment statistics and a random selection of positive and negative tweets for each candidate.
# TRAINING RULES
1. We will be more skewed toward positive sentiment than negative sentiment (example: "Bloomberg isn't that good at politics, I like Amy, Bernie is okay too" - +Amy, +Bernie, -Bloomberg)
<file_sep>/nevada-caucus-sentiment-master/static/js/tweet-predictor.js
// Select the submission button
var submit_button = d3.select("#tweet-submit-button");
// Apply an On-Click function to the button to retrieve the input value, return the text and fire the sentiment analysis model
submit_button.on("click", tweet_analyzer)
function tweet_analyzer() {
// Select the text predictor input element and retrieve the value
var text_predictor_input = d3.select("#text-form-input");
var inputValue = text_predictor_input.property("value");
var full_tweet_output_field = d3.select("#text-input-output-field")
var sentiment_prediction_field = d3.select("#sentiment-prediction-output")
var predicted_positive_percent = d3.select("#predicted-positive-percent-tag")
var predicted_negative_percent = d3.select("#predicted-negative-percent-tag")
var predicted_neutral_percent = d3.select("#predicted-general-percent-tag")
// Check for input value before proceeding
// If input value is blank, return a message
if (inputValue!== ``) {
// Packaging the input text for the API
var packaged_input_text= `"${inputValue}"`
// API Base URL that the data will be sent to
var model_api_url = "https://twitter-sentiment-app-du.herokuapp.com/api/v1/tweet_predictor/"
// Build the full URL by appending the packaged text to the base URL
var tweet_api_destination = model_api_url + packaged_input_text
// Make a JSON call to the API to retrieve the data
d3.json(tweet_api_destination).then(function(retrieved_tweet_data) {
console.log("Input value received: ", packaged_input_text);
var data_unpack_layer_one= retrieved_tweet_data
var {Sentiment: sentiment_data} = data_unpack_layer_one
var data_unpack_layer_two = sentiment_data
var {
Tweet: returned_tweet_text,
Overall_Sentiment: returned_tweet_overall,
Negative_Percent: returned_tweet_negative_percent,
Positive_Percent: returned_tweet_positive_percent,
General_Percent: returned_tweet_general_percent
} = data_unpack_layer_two
// Wipe any values already displayed
full_tweet_output_field.selectAll('p').remove();
predicted_positive_percent.selectAll('p').remove();
predicted_negative_percent.selectAll('p').remove();
predicted_neutral_percent.selectAll('p').remove();
// Display the text that the user wants analyzed in the output field
full_tweet_output_field
.append('p')
.attr('id', 'tweet-output-format')
.text(returned_tweet_text);
// Display the model's prediction for the input value
sentiment_prediction_field.selectAll('p').remove();
if (returned_tweet_overall === "pos") {
sentiment_prediction_field
.append('p')
.attr('id', 'sentiment-prediction-positive')
.text("POSITIVE")
} else if (returned_tweet_overall === "neg") {
sentiment_prediction_field
.append('p')
.attr('id', 'sentiment-prediction-negative')
.text("NEGATIVE")
} else {
sentiment_prediction_field
.append('p')
.attr('id', 'sentiment-prediction-neutral')
.text("NEUTRAL")
}
predicted_positive_percent
.append('p')
.attr('id', 'predicted-percent-pos')
.text(`${returned_tweet_positive_percent}%`)
predicted_negative_percent
.append('p')
.attr('id', 'predicted-percent-neg')
.text(`${returned_tweet_negative_percent}%`)
predicted_neutral_percent
.append('p')
.attr('id', 'predicted-general-percent')
.text(`${returned_tweet_general_percent}%`)
})
// The Else clause of this if-statement handles situations when there is no value in the input field
} else {
// Wipe any values already displayed
sentiment_prediction_field.selectAll('p').remove();
full_tweet_output_field.selectAll('p').remove();
predicted_positive_percent.selectAll('p').remove();
predicted_negative_percent.selectAll('p').remove();
predicted_neutral_percent.selectAll('p').remove();
// Insert a message in the output field requesting that the user inputs a value
full_tweet_output_field
.append('p')
.attr('id', 'tweet-output-format-need-text')
.text(`Please input a value.`);
sentiment_prediction_field
.append('p')
.attr('id', 'sentiment-prediction-need-text')
.text("-")
predicted_positive_percent
.append('p')
.attr('id', 'predicted-sent-need-text')
.text(`-`)
predicted_negative_percent
.append('p')
.attr('id', 'predicted-sent-need-text')
.text(`-`)
predicted_neutral_percent
.append('p')
.attr('id', 'predicted-sent-need-text')
.text(`-`)
}
}
// Initialize the page by calling the function
tweet_analyzer()
// Data from informative-features.js
var word_data = feature_data;
// Populate Model Word Sentiment table and create Plot
// Create the table
var word_weight_table = d3.select("#word-weight-tag")
word_weight_table.selectAll('tr').remove();
function Build_Word_Table(array) {
array.forEach(word => {
var word_table_row = word_weight_table.append('tr');
Object.entries(word).forEach(([key, value]) => {
word_table_row
.append('td')
.attr('class', 'table-item-center')
.text(value)
});
});
}
Build_Word_Table(word_data)
word_list = []
// Unpack data from the API into an list for easy iteration
word_data.forEach((item) => {
var item_list = []
// Iterate through each key/value
Object.entries(item).forEach(([key, value]) => {
// Add all values relevant to one timepoint to timepoint_list
item_list.push(value)
})
// Append the timepoint data to the master Period List
word_list.push(item_list)
})
// Sent graph word list collects the words and is used as the X-values in the graph
sent_graph_word_list = []
// Sent graph value list collects the sentiment values and is used as the Y-values in the graph
sent_graph_value_list = []
word_list.forEach((item) => {
// Collect the words
sent_graph_word_list.push(item[0])
// Collect the sentiment values
sent_graph_value_list.push(parseFloat(item[2]))
})
// Line Chart to display how sentiment is weighted
var trace = {
x: sent_graph_word_list,
y: sent_graph_value_list,
type: "line"
};
var sent_graph_data = [trace];
var sent_graph_layout = {
title: "Model Word Sentiment Value",
xaxis: {
title: "Words"
},
yaxis: {
title: "Sentiment Value"
}
};
var responsive_functionality = {
responsive: true
}
Plotly.newPlot("sentiment-line-chart", sent_graph_data, sent_graph_layout, responsive_functionality)
<file_sep>/nevada-caucus-sentiment-master/static/js/test-data/testing-data-format-2.js
var data = [
{
candidate: "<NAME>",
Positive_Sentiment_Score: 67.3,
Negative_Sentiment_Score: 30.7,
Margin_of_Error: 2,
tweet_count: 6035,
Tweets: [
{
date: "2020-02-19",
username: "SalKappa",
tweet: "#PresidentSanders #BernieWonIowa #BernieWonNewHampshire #BernieBeatsTrump #BerniesGonnaWin #NevadaCaucus #SouthCarolina #FeelTheBern #NotMeUs #BigUs #Bernie2020 #Sanders2020 #BernieSanders2020 #BernieSanders #DemocraticPrimaries #2020Dem #Election2020 #TrumpFearsBerniehttps://twitter.com/kubethy/status/1229950096286081024"
},
{
date: "2020-02-19",
username: "chad_b_morrow",
tweet: "Absolutely absurd how long the line is for early voting in #NevadaCaucus"
},
{
date: "2020-02-19",
username: "DestiGrace1",
tweet: "Lordie the discussion is about dirty AF #CorruptBarr via #Maddow. Forget #PeteButtigieg you guys, @maddow is about to drop more dirty on the CORRUPT USAG #DisBarr. Apparently dude has been clandestinely shutting down cases against #CrookedTRUMP. #CNNTownHall #NevadaCaucus https://twitter.com/DestiGrace1/status/1229721358126505984"
},
{
date: "2020-02-19",
username: "iamwillkeating",
tweet: "#MayorPete Buttigieg just said his religious faith “does have implications for how I approach public office.” So much for the separation of church and state. #NevadaCaucus #2020election #CNNTownHall"
},
{
date: "2020-02-19",
username: "Magsaliciouss",
tweet: "Just picked up my Precinct Captain box for Saturday, RSVP'd to see and hear @PeteButtigieg one more time before caucus day and I'm excited for #TeamPete to bring this home in Nevada."
},
{
date: "2020-02-19",
username: "GoHawksThe12",
tweet: "Bernie is now the ONLY candidate with NO billionaire donors!!! #warren2020 #Bernie2020 #PetesBillionaires #WarrenMediaBlackout #PeteForAmerica #PeteForPresident #Biden2020 #Biden #SCprimary #SouthCarolinaPrimary #NVCaucus #NevadaCaucus https://twitter.com/bern_identity/status/1229945043932237824"
}
]
},
{
candidate: "<NAME>",
Positive_Sentiment_Score: 50.8,
Negative_Sentiment_Score: 46.2,
Margin_of_Error: 3,
tweet_count: 4167,
Tweets: [
{
date: "2020-02-19",
username: "4HollyF",
tweet: "It didn't matter to me and I just stood in line for 3 hours in LV to vote for Liz, Amy, Pete, Bernie, Joe at the Clusterfuhk Nevada calls an early caucus vote. I have a new respect for those in voter suppression states who stand line much longer. What a mess."
},
{
date: "2020-02-19",
username: "1nd1obravo",
tweet: "is bloomberg not participating in the nevada town hall? (maybe he bought the entire town hall?) #NevadaCaucus"
},
{
date: "2020-02-19",
username: "Steveninformed",
tweet: "#CNNTownHall #BernieSanders rocked the #NevadaCaucus wow. Excellent job. Viewer. #Democrats"
},
{
date: "2020-02-19",
username: "miamibeachfella",
tweet: "I wonder how much Bloomberg paid all the news and radio stations to get his poll numbers up. #NevadaCaucus #Bloomberg #DemocraticDebate #BernieSanders"
},
{
date: "2020-02-19",
username: "MIWNV",
tweet: "“You have the right to vote so exercise your right and SHOW UP, Nevada you have until 8 P.M. PACIFIC TIME to get out to early vote for the caucus” -Tameka, MIWN Ambassador https://www.facebook.com/HigherHeights4/videos/608548459712282/ …pic.twitter.com/kUYMpPraBO"
},
{
date: "2020-02-19",
username: "engrqamarabbas5",
tweet: "Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus - CBS News https://ift.tt/2V1KLL1 Democratic presidential candidates ramp up attacks against Bloomberg ahead of Nevada caucus CBS News 2020 Nevada caucus just a week away ABC News"
}
]
}
];
<file_sep>/nevada-caucus-sentiment-master/app.py
from flask import Flask, jsonify
import pandas as pd
import main
import pickle
from flask_cors import CORS
## Flask setup
app = Flask(__name__)
CORS(app)
@app.route("/")
def welcome():
return "Home Page of DB"
@app.route("/api/v1/tweet_predictor/<tweet>")
def test_model(tweet):
s = main.run(tweet)
return s
@app.route("/api/v1/candidates")
def create_api():
api_call = main.create_dash_api()
return api_call
if __name__ == "__main__":
app.run(debug=True)<file_sep>/nevada-caucus-sentiment-master/SQL/processing_script.sql
-- ******************************************************************************************************
-- ******************************************************************************************************
-- RUN ALL SCRIPTS BELOW (NO NEED TO RUN ONE AT A TIME, JUST HIGHLIGHT THEM ALL AND RUN)
-- WHEN SCRIPTS ARE FINISHED, YOU CAN EXPORT THE FOLLOWING TABLES:
--
-- aggregate_sentiment_exclude_caucus (counts by candidate, time_period, sentiment, tweeter_type)
-- negative_tweets (random sample of negative tweets)
-- positive_tweets (random sample of positive tweets)
-- probability_summary (Pranav's candidate_sentiment probabilities)
-- ******************************************************************************************************
-- ******************************************************************************************************
-- ==========================================================
-- INSERT DISTINCT RECORDS FROM LOAD TABLE TO PREDICTED TABLE
-- ==========================================================
INSERT INTO predicted_tweets (
index_pandas,
time_stamp,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
predictor,
candidate,
fromfile,
tweeter_type
)
SELECT DISTINCT
lt.index_pandas,
lt.time_stamp,
lt.to_user,
lt.replies,
lt.retweets,
lt.favorites,
lt.username,
lt.tweet_text,
lt.geo,
lt.mentions,
lt.hashtags,
lt.tweet_id,
lt.permalink,
lt.predictor,
lt.candidate,
lt.fromfile,
lt.tweeter_type
FROM load_tweets lt
WHERE lt.tweet_id NOT IN(SELECT tweet_id FROM predicted_tweets)
;
-- =======================================================
-- THE FOLLOWING QUERIES FIND CANDIDATES IN THE TWEET TEXT
-- =======================================================
UPDATE predicted_tweets
SET
sanders = 0,
biden = 0,
klobuchar = 0,
warren = 0,
buttigieg = 0,
steyer = 0,
yang = 0,
bloomberg = 0,
gabbard = 0,
trump = 0,
dnc = 0,
democrats = 0,
caucus = 0;
UPDATE predicted_tweets
SET
sanders = 1
WHERE lower(tweet_text) ~~ ANY('{%bernie%,%sanders%,%bsanders%,%bernie sanders%, %berniesanders%, %bernard%, %bernardsanders%, %bernard sanders%}');
UPDATE predicted_tweets
SET
biden = 1
WHERE lower(tweet_text) ~~ ANY('{%joe%,%biden%,%joebiden%,%joe biden%, %jbiden%, %joseph biden%, %josephbiden%, %joseph%}');
UPDATE predicted_tweets
SET
klobuchar = 1
WHERE lower(tweet_text) ~~ ANY('{%amy%,%klobuchar%,%amyklobuchar%,%amy klobuchar%, %aklobuchar%}');
UPDATE predicted_tweets
SET
warren = 1
WHERE lower(tweet_text) ~~ ANY('{%liz%,%warren%,%lizwarren%,%liz warren%, %ewarren%, %elizabeth%, %elizabethwarren%, %elizabeth warren%}');
UPDATE predicted_tweets
SET
buttigieg = 1
WHERE lower(tweet_text) ~~ ANY('{%pete%,%buttigieg%,%petebuttigieg%,%pete buttigieg%, %pbuttigieg%, %mayor pete%, %mayorpete%}');
UPDATE predicted_tweets
SET
steyer = 1
WHERE lower(tweet_text) ~~ ANY('{%tom%,%steyer%,%tomsteyer%,%tom steyer%, %tsteyer%, %thomas steyer%, %thomassteyer%, %thomas%}');
UPDATE predicted_tweets
SET
yang = 1
WHERE lower(tweet_text) ~~ ANY('{%andrew%,%yang%,%andrewyang%,%andrew yang%, %ayang%, %yang gang%, %yanggang%}');
UPDATE predicted_tweets
SET
bloomberg = 1
WHERE lower(tweet_text) ~~ ANY('{%mike%,%bloomberg%,%mikebloomberg%,%mike bloomberg%, %mbloomberg%, %mayor bloomberg%, %mayorbloomberg%, %michael%, %michael bloomberg%, %michaelbloomberg%}');
UPDATE predicted_tweets
SET
gabbard = 1
WHERE lower(tweet_text) ~~ ANY('{%tulsi%,%gabbard%,%tulsigabbard%,%tulsi gabbard%, %tgabbard%}');
UPDATE predicted_tweets
SET
trump = 1
WHERE lower(tweet_text) ~~ ANY('{%donald%,%trump%,%donaldtrump%,%donald trump%, %dtrump%, %president trump%, %presidenttrump%}');
UPDATE predicted_tweets
SET
dnc = 1
WHERE lower(tweet_text) ~~ ANY('{%dnc%,%perez%,%tom perez%,%tperez%}');
UPDATE predicted_tweets
SET
democrats = 1
WHERE lower(tweet_text) ~~ ANY('{%democrats%}');
UPDATE predicted_tweets
SET
caucus = 1
WHERE lower(tweet_text) ~~ ANY('{%caucus%}');
-- =================================================
-- INSERT SANDERS TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Sanders', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(pt.candidate) ~~ ANY('{%bernie%, %sanders%, %bsanders%, %bernie sanders%, %berniesanders%, %bernard%, %bernardsanders%, %bernard sanders%}'))
OR pt.sanders = 1);
-- =================================================
-- INSERT BIDEN TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Biden', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%joe%, %biden%, %joebiden%, %joe biden%, %jbiden%, %joseph biden%, %josephbiden%, %joseph%}'))
OR pt.biden = 1);
-- =================================================
-- INSERT BUTTIGIEG TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Buttigieg', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%pete%,%buttigieg%,%petebuttigieg%,%pete buttigieg%, %pbuttigieg%, %mayor pete%, %mayorpete%}'))
OR pt.buttigieg = 1);
-- =================================================
-- INSERT KLOBUCHAR TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Klobuchar', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%amy%, %klobuchar%, %amyklobuchar%, %amy klobuchar%, %aklobuchar%}'))
OR pt.klobuchar = 1);
-- =================================================
-- INSERT BLOOMBERG TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Bloomberg', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%mike%, %bloomberg%, %mikebloomberg%, %mike bloomberg%, %mbloomberg%, %mayor bloomberg%, %mayorbloomberg%, %michael%, %michael bloomberg%, %michaelbloomberg%}'))
OR pt.bloomberg = 1);
-- =================================================
-- INSERT YANG TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Yang', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%andrew%, %yang%, %andrewyang%, %andrew yang%, %ayang%, %yang gang%, %yanggang%}'))
OR pt.yang = 1);
-- =================================================
-- INSERT WARREN TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Warren', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%liz%, %warren%, %lizwarren%, %liz warren%, %ewarren%, %elizabeth%, %elizabethwarren%, %elizabeth warren%}'))
OR pt.warren = 1);
-- =================================================
-- INSERT STEYER TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Steyer', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%tom%, %steyer%, %tomsteyer%, %tom steyer%, %tsteyer%, %thomas steyer%, %thomassteyer%, %thomas%}'))
OR pt.steyer = 1);
-- =================================================
-- INSERT GABBARD TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Gabbard', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%tulsi%, %gabbard%, %tulsigabbard%, %tulsi gabbard%, %tgabbard%}'))
OR pt.gabbard = 1);
-- =================================================
-- INSERT TRUMP TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Trump', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%donald%, %trump%, %donaldtrump%, %donald trump%, %dtrump%, %president trump%, %presidenttrump%}'))
OR pt.trump = 1);
-- =================================================
-- INSERT DNC TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'DNC', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%dnc%, %perez%, %tom perez%, %tperez%}'))
OR pt.dnc = 1);
-- =================================================
-- INSERT DEMOCRATS TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Democrats', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%democrats%}'))
OR pt.democrats = 1);
-- =================================================
-- INSERT CAUCUS TWEETS INTO STAGING TABLE
-- =================================================
INSERT INTO tweets_staged (
candidate,
sentiment,
time_stamp,
date,
to_user,
replies,
retweets,
favorites,
username,
tweet_text,
geo,
mentions,
hashtags,
tweet_id,
permalink,
fromfile,
tweeter_type
)
SELECT
'Caucus', -- change to candidate in WHERE clause
pt.predictor,
pt.time_stamp,
date(pt.time_stamp),
pt.to_user,
pt.replies,
pt.retweets,
pt.favorites,
pt.username,
pt.tweet_text,
pt.geo,
pt.mentions,
pt.hashtags,
pt.tweet_id,
pt.permalink,
pt.fromfile,
pt.tweeter_type
FROM predicted_tweets pt
WHERE ((lower(candidate) ~~ ANY('{%caucus%}'))
OR pt.caucus = 1);
-- =================================================
-- SET RANDOM_INTEGER BETWEEN 1 AND 20 IN tweets_staged TABLE (for selecting tweet samples)
-- =================================================
UPDATE tweets_staged
SET
random_integer = floor(random() * 20 + 1)::int;
-- =================================================
-- RESET PRIMARY KEY IN tweets_staged TABLE
-- =================================================
UPDATE tweets_staged
SET
time_period =
CASE
WHEN time_stamp < '2020-02-19 18:00:00' THEN 'Pre-Debate'
WHEN time_stamp < '2020-02-22 16:00:00' THEN 'Post-Debate'
ELSE 'Post-Caucus'
END
;
-- =================================================
-- INSERT INTO positive_tweets TABLE
-- =================================================
INSERT INTO positive_tweets (
candidate,
sentiment,
time_period,
date,
username,
tweet_text,
pos_tweet_id,
tweeter_type
)
SELECT
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.username,
staged.tweet_text,
staged.primary_key,
staged.tweeter_type
FROM tweets_staged staged
WHERE staged.sentiment = 'positive'
-- AND staged.candidate IS NOT NULL
AND staged.candidate IN ('Sanders', 'Biden', 'Warren', 'Klobuchar', 'Trump', 'Bloomberg', 'Buttigieg', 'Steyer', 'Gabbard', 'Yang')
AND staged.random_integer IN ('7', '9', '11', '17', '19');
-- =================================================
-- INSERT INTO negative_tweets TABLE
-- =================================================
INSERT INTO negative_tweets (
candidate,
sentiment,
time_period,
date,
username,
tweet_text,
neg_tweet_id,
tweeter_type
)
SELECT
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.username,
staged.tweet_text,
staged.primary_key,
staged.tweeter_type
FROM tweets_staged staged
WHERE staged.sentiment = 'negative'
-- AND staged.candidate IS NOT NULL
AND staged.candidate IN ('Sanders', 'Biden', 'Warren', 'Klobuchar', 'Trump', 'Bloomberg', 'Buttigieg', 'Steyer', 'Gabbard', 'Yang')
AND staged.random_integer IN ('3', '5', '7', '9', '11', '17', '19');
-- =================================================
-- INSERT INTO aggregate_sentiment_exclude_caucus TABLE
-- =================================================
INSERT INTO aggregate_sentiment_exclude_caucus (
candidate,
sentiment,
time_period,
date,
tweeter_type,
count
)
SELECT
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.tweeter_type,
count(*)
FROM tweets_staged staged
WHERE staged.candidate NOT IN ('Caucus', 'DNC', 'Democrats') AND staged.sentiment IN ('positive', 'negative')
GROUP BY
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.tweeter_type
;
-- =================================================
-- INSERT INTO aggregate_sentiment_include_caucus TABLE
-- =================================================
INSERT INTO aggregate_sentiment_include_caucus (
candidate,
sentiment,
time_period,
date,
tweeter_type,
count
)
SELECT
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.tweeter_type,
count(*)
FROM tweets_staged staged
WHERE staged.sentiment IN ('positive', 'negative')
GROUP BY
staged.candidate,
staged.sentiment,
staged.time_period,
staged.date,
staged.tweeter_type
;
<file_sep>/nevada-caucus-sentiment-master/main.py
import pickle
import string
import re
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
from nltk import classify
from nltk import NaiveBayesClassifier
import json
import random
import pandas as pd
overall_df = pd.read_csv('overall_counts.csv')
neg_tweets = pd.read_csv('negative_tweets.csv')
pos_tweets = pd.read_csv('positive_tweets.csv')
full_tweets = neg_tweets.append(pos_tweets, sort=True)
app3 = full_tweets
df_sent1 = pd.read_csv('pre_debate_candidate_sentiment.csv')
df_sent1['scenario'] = 'pre_debate'
df_sent2 = pd.read_csv('post_debate_candidate_sentiment.csv')
df_sent3 = pd.read_csv('pre_election_candidate_sentiment.csv')
df_sent4 = pd.read_csv('post_election_candidate_sentiment.csv')
df_sent1 = df_sent1[['Name','Negative Probability','Positive Probability','Results','scenario']]
df_sent2 = df_sent2[['Name','Negative Probability','Positive Probability','Results','scenario']]
df_sent3 = df_sent3[['Name','Negative Probability','Positive Probability','Results','scenario']]
df_sent4 = df_sent4[['Name','Negative Probability','Positive Probability','Results','scenario']]
sent_app1 = df_sent1.append(df_sent2)
sent_app2 = sent_app1.append(df_sent3)
sent_app3 = sent_app2.append(df_sent4)
sent_app3['Staging'] = sent_app3['Negative Probability'] + sent_app3['Positive Probability']
sent_app3['General_Probability'] = 1 - sent_app3['Staging']
sent_app3['General_Probability'] = sent_app3['General_Probability']*100
sent_app3['Negative Probability'] = sent_app3['Negative Probability']*100
sent_app3['Positive Probability'] = sent_app3['Positive Probability']*100
avg_group = sent_app3.groupby('Name').mean().reset_index()
def clean_tweets(tweet):
stopwords_english = stopwords.words('english')
stopwords_english = stopwords.words('english')
tweet = re.sub(r'\$\w*', '', tweet)
## Cleaing up RTs
tweet = re.sub(r'^RT[\s]+', '', tweet)
## Removing hyperlinks
tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet)
## Removing hastags
tweet = re.sub(r'#', '', tweet)
# tokenize tweets
tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)
tweet_tokens = tokenizer.tokenize(tweet)
tweets_clean = []
for word in tweet_tokens:
if (word not in stopwords_english and # remove stopwords
word not in string.punctuation): # remove punctuation
##stem_word = stemmer.stem(word) # stemming word
tweets_clean.append(word)
return tweets_clean
def bag_of_words(tweet):
words = clean_tweets(tweet)
words_dictionary = dict([word, True] for word in words)
return words_dictionary
def run(tweet):
filename = 'pre_debate_model.sav'
loaded_model = pickle.load(open(filename, 'rb'))
user_input = tweet
custom_tweet_set = bag_of_words(user_input)
prob_result = loaded_model.prob_classify(custom_tweet_set)
final_result = str(prob_result.max())
negative_percent = round(((prob_result.prob("neg"))*100),2)
positive_percent = round(((prob_result.prob("pos"))*100),2)
general_percent = round(((prob_result.prob("gen"))*100),2)
jsondata = {}
json_final = {}
json_final['Tweet'] = user_input
json_final['Overall_Sentiment'] = final_result
json_final['Negative_Percent'] = negative_percent
json_final['Positive_Percent'] = positive_percent
json_final['General_Percent'] = general_percent
jsondata['Sentiment'] = json_final
myjson = json.dumps(jsondata)
return myjson
def random_tweets(name,col,time):
save_tweets = []
time_df = app3[app3['time_period']==time]
name_df = time_df[time_df['candidate']==name]
get_df = name_df[name_df['sentiment']==col].reset_index()
for x in range(5):
date = get_df['date'].iloc[random.randint(1,20)]
username = get_df['username'].iloc[random.randint(1,20)]
tweet = get_df['tweet_text'].iloc[random.randint(1,20)]
save = {'date' : date, 'username': username, 'tweet': tweet}
save_tweets.append(save)
return save_tweets
def get_elements(name, col, scenario):
df_cand = sent_app3[sent_app3['scenario']==scenario]
df_sent = df_cand[df_cand['Name']==name]
for i in df_sent[col]:
return i
def get_avg(name,col):
avg_group = sent_app3.groupby('Name').mean().reset_index()
df_sent = avg_group[avg_group['Name']==name]
for i in df_sent[col]:
return i
def get_agg(name,period):
name_agg = overall_df[overall_df['Name']==name]
per_agg = name_agg[period]
for i in per_agg:
return i
def create_dash_api():
jsondata = {}
candidate_1 = {}
electoral_data = {}
## Create Bernie Candidate
candidate_1 = '<NAME>'
## Create electoral data
electoral_data['period4'] = 'Overall'
electoral_data['positive_sentitment_score_4'] = get_avg('Sanders','Positive Probability')
electoral_data['negative_sentiment_score_4'] = get_avg('Sanders','Negative Probability')
electoral_data['general_sentitment_score_4'] = get_avg('Sanders','General_Probability')
electoral_data['tweet_count_4'] = get_agg('Sanders','Overall')
positive_tweets = random_tweets('Sanders','positive','Pre-Debate')
negative_tweets = random_tweets('Sanders','negative','Pre-Debate')
electoral_data['positive_tweets_4'] = [positive_tweets]
electoral_data['negative_tweets_4'] = [negative_tweets]
electoral_data['period1'] = 'pre_debate'
electoral_data['positive_sentitment_score_1'] = get_elements('Sanders','Positive Probability','pre_debate')
electoral_data['negative_sentiment_score_1'] = get_elements('Sanders','Negative Probability','pre_debate')
electoral_data['general_sentitment_score_1'] = get_elements('Sanders','General_Probability','pre_debate')
electoral_data['tweet_count_1'] = get_agg('Sanders','Pre-Debate')
positive_tweets = random_tweets('Sanders','positive','Pre-Debate')
negative_tweets = random_tweets('Sanders','negative','Pre-Debate')
electoral_data['positive_tweets_1'] = [positive_tweets]
electoral_data['negative_tweets_1'] = [negative_tweets]
electoral_data['period2'] = 'post_debate'
electoral_data['positive_sentitment_score_2'] = get_elements('Sanders','Positive Probability','post_debate')
electoral_data['negative_sentiment_score_2'] = get_elements('Sanders','Negative Probability','post_debate')
electoral_data['general_sentitment_score_2'] = get_elements('Sanders','General_Probability','post_debate')
electoral_data['tweet_count_2'] = get_agg('Sanders','Post-Debate')
positive_tweets = random_tweets('Sanders','positive','Post-Debate')
negative_tweets = random_tweets('Sanders','negative','Post-Debate')
electoral_data['positive_tweets_2'] = [positive_tweets]
electoral_data['negative_tweets_2'] = [negative_tweets]
electoral_data['period3'] = 'post_election'
electoral_data['positive_sentitment_score_3'] = get_elements('Sanders','Positive Probability','post_election')
electoral_data['negative_sentiment_score_3'] = get_elements('Sanders','Negative Probability','post_election')
electoral_data['general_sentitment_score_3'] = get_elements('Sanders','General_Probability','post_election')
electoral_data['tweet_count_3'] = get_agg('Sanders','Post-Caucus')
positive_tweets = random_tweets('Sanders','positive','Post-Caucus')
negative_tweets = random_tweets('Sanders','negative','Post-Caucus')
electoral_data['positive_tweets_3'] = [positive_tweets]
electoral_data['negative_tweets_3'] = [negative_tweets]
## Liz Warren JSON
candidate_2 = {}
electoral_data_2 = {}
## Create Candidate
candidate_2 = '<NAME>'
## Create electoral data for Liz Warren
electoral_data_2['period4'] = 'Overall'
electoral_data_2['positive_sentitment_score_4'] = get_avg('Warren','Positive Probability')
electoral_data_2['negative_sentiment_score_4'] = get_avg('Warren','Negative Probability')
electoral_data_2['general_sentitment_score_4'] = get_avg('Warren','General_Probability')
electoral_data_2['tweet_count_4'] = get_agg('Warren','Overall')
positive_tweets = random_tweets('Warren','positive','Post-Caucus')
negative_tweets = random_tweets('Warren','negative','Post-Caucus')
electoral_data_2['positive_tweets_4'] = [positive_tweets]
electoral_data_2['negative_tweets_4'] = [negative_tweets]
electoral_data_2['period1'] = 'pre_debate'
electoral_data_2['positive_sentitment_score_1'] = get_elements('Warren','Positive Probability','pre_debate')
electoral_data_2['negative_sentiment_score_1'] = get_elements('Warren','Negative Probability','pre_debate')
electoral_data_2['general_sentitment_score_1'] = get_elements('Warren','General_Probability','pre_debate')
electoral_data_2['tweet_count_1'] = get_agg('Warren','Pre-Debate')
positive_tweets = random_tweets('Warren','positive','Pre-Debate')
negative_tweets = random_tweets('Warren','negative','Pre-Debate')
electoral_data_2['positive_tweets_1'] = [positive_tweets]
electoral_data_2['negative_tweets_1'] = [negative_tweets]
electoral_data_2['period2'] = 'post_debate'
electoral_data_2['positive_sentitment_score_2'] = get_elements('Warren','Positive Probability','post_debate')
electoral_data_2['negative_sentiment_score_2'] = get_elements('Warren','Negative Probability','post_debate')
electoral_data_2['general_sentitment_score_2'] = get_elements('Warren','General_Probability','post_debate')
electoral_data_2['tweet_count_2'] = get_agg('Warren','Post-Debate')
positive_tweets = random_tweets('Warren','positive','Post-Debate')
negative_tweets = random_tweets('Warren','negative','Post-Debate')
electoral_data_2['positive_tweets_2'] = [positive_tweets]
electoral_data_2['negative_tweets_2'] = [negative_tweets]
electoral_data_2['period3'] = 'post_election'
electoral_data_2['positive_sentitment_score_3'] = get_elements('Warren','Positive Probability','post_election')
electoral_data_2['negative_sentiment_score_3'] = get_elements('Warren','Negative Probability','post_election')
electoral_data_2['general_sentitment_score_3'] = get_elements('Warren','General_Probability','post_election')
electoral_data_2['tweet_count_3'] = get_agg('Warren','Post-Caucus')
positive_tweets = random_tweets('Warren','positive','Post-Caucus')
negative_tweets = random_tweets('Warren','negative','Post-Caucus')
electoral_data_2['positive_tweets_3'] = [positive_tweets]
electoral_data_2['negative_tweets_3'] = [negative_tweets]
## Kloobuchar build
candidate_3 = {}
electoral_data_3 = {}
candidate_3 = '<NAME>'
## Create for Amy
electoral_data_3['period4'] = 'Overall'
electoral_data_3['positive_sentitment_score_4'] = get_avg('Klobuchar','Positive Probability')
electoral_data_3['negative_sentiment_score_4'] = get_avg('Klobuchar','Negative Probability')
electoral_data_3['general_sentitment_score_4'] = get_avg('Klobuchar','General_Probability')
electoral_data_3['tweet_count_4'] = get_agg('Klobuchar','Overall')
positive_tweets = random_tweets('Klobuchar','positive','Post-Caucus')
negative_tweets = random_tweets('Klobuchar','negative','Post-Caucus')
electoral_data_3['positive_tweets_4'] = [positive_tweets]
electoral_data_3['negative_tweets_4'] = [negative_tweets]
electoral_data_3['period1'] = 'pre_debate'
electoral_data_3['positive_sentitment_score_1'] = get_elements('Klobuchar','Positive Probability','pre_debate')
electoral_data_3['negative_sentiment_score_1'] = get_elements('Klobuchar','Negative Probability','pre_debate')
electoral_data_3['general_sentitment_score_1'] = get_elements('Klobuchar','General_Probability','pre_debate')
electoral_data_3['tweet_count_1'] = get_agg('Klobuchar','Pre-Debate')
positive_tweets = random_tweets('Klobuchar','positive','Pre-Debate')
negative_tweets = random_tweets('Klobuchar','negative','Pre-Debate')
electoral_data_3['positive_tweets_1'] = [positive_tweets]
electoral_data_3['negative_tweets_1'] = [negative_tweets]
electoral_data_3['period2'] = 'post_debate'
electoral_data_3['positive_sentitment_score_2'] = get_elements('Klobuchar','Positive Probability','post_debate')
electoral_data_3['negative_sentiment_score_2'] = get_elements('Klobuchar','Negative Probability','post_debate')
electoral_data_3['general_sentitment_score_2'] = get_elements('Klobuchar','General_Probability','post_debate')
electoral_data_3['tweet_count_2'] = get_agg('Klobuchar','Post-Debate')
positive_tweets = random_tweets('Klobuchar','positive','Post-Debate')
negative_tweets = random_tweets('Klobuchar','negative','Post-Debate')
electoral_data_3['positive_tweets_2'] = [positive_tweets]
electoral_data_3['negative_tweets_2'] = [negative_tweets]
electoral_data_3['period3'] = 'post_election'
electoral_data_3['positive_sentitment_score_3'] = get_elements('Klobuchar','Positive Probability','post_election')
electoral_data_3['negative_sentiment_score_3'] = get_elements('Klobuchar','Negative Probability','post_election')
electoral_data_3['general_sentitment_score_3'] = get_elements('Klobuchar','General_Probability','post_election')
electoral_data_3['tweet_count_3'] = get_agg('Klobuchar','Post-Caucus')
positive_tweets = random_tweets('Klobuchar','positive','Post-Caucus')
negative_tweets = random_tweets('Klobuchar','negative','Post-Caucus')
electoral_data_3['positive_tweets_3'] = [positive_tweets]
electoral_data_3['negative_tweets_3'] = [negative_tweets]
## Buttigieg Build
candidate_4 = {}
electoral_data_4 = {}
candidate_4 = '<NAME>'
## Create for Pete
electoral_data_4['period4'] = 'Overall'
electoral_data_4['positive_sentitment_score_4'] = get_avg('Buttigieg','Positive Probability')
electoral_data_4['negative_sentiment_score_4'] = get_avg('Buttigieg','Negative Probability')
electoral_data_4['general_sentitment_score_4'] = get_avg('Buttigieg','General_Probability')
electoral_data_4['tweet_count_4'] = get_agg('Buttigieg','Overall')
positive_tweets = random_tweets('Buttigieg','positive','Post-Caucus')
negative_tweets = random_tweets('Buttigieg','negative','Post-Caucus')
electoral_data_4['positive_tweets_4'] = [positive_tweets]
electoral_data_4['negative_tweets_4'] = [negative_tweets]
electoral_data_4['period1'] = 'pre_debate'
electoral_data_4['positive_sentitment_score_1'] = get_elements('Buttigieg','Positive Probability','pre_debate')
electoral_data_4['negative_sentiment_score_1'] = get_elements('Buttigieg','Negative Probability','pre_debate')
electoral_data_4['general_sentitment_score_1'] = get_elements('Buttigieg','General_Probability','pre_debate')
electoral_data_4['tweet_count_1'] = get_agg('Buttigieg','Pre-Debate')
positive_tweets = random_tweets('Buttigieg','positive','Pre-Debate')
negative_tweets = random_tweets('Buttigieg','negative','Pre-Debate')
electoral_data_4['positive_tweets_1'] = [positive_tweets]
electoral_data_4['negative_tweets_1'] = [negative_tweets]
electoral_data_4['period2'] = 'post_debate'
electoral_data_4['positive_sentitment_score_2'] = get_elements('Buttigieg','Positive Probability','post_debate')
electoral_data_4['negative_sentiment_score_2'] = get_elements('Buttigieg','Negative Probability','post_debate')
electoral_data_4['general_sentitment_score_2'] = get_elements('Buttigieg','General_Probability','post_debate')
electoral_data_4['tweet_count_2'] = get_agg('Buttigieg','Post-Debate')
positive_tweets = random_tweets('Buttigieg','positive','Post-Debate')
negative_tweets = random_tweets('Buttigieg','negative','Post-Debate')
electoral_data_4['positive_tweets_2'] = [positive_tweets]
electoral_data_4['negative_tweets_2'] = [negative_tweets]
electoral_data_4['period3'] = 'post_election'
electoral_data_4['positive_sentitment_score_3'] = get_elements('Buttigieg','Positive Probability','post_election')
electoral_data_4['negative_sentiment_score_3'] = get_elements('Buttigieg','Negative Probability','post_election')
electoral_data_4['general_sentitment_score_3'] = get_elements('Buttigieg','General_Probability','post_election')
electoral_data_4['tweet_count_3'] = get_agg('Buttigieg','Post-Caucus')
positive_tweets = random_tweets('Buttigieg','positive','Post-Caucus')
negative_tweets = random_tweets('Buttigieg','negative','Post-Caucus')
electoral_data_4['positive_tweets_3'] = [positive_tweets]
electoral_data_4['negative_tweets_3'] = [negative_tweets]
## Biden Build
candidate_5 = {}
electoral_data_5 = {}
candidate_5 = '<NAME>'
## Create for Biden
electoral_data_5['period4'] = 'Overall'
electoral_data_5['positive_sentitment_score_4'] = get_avg('Biden','Positive Probability')
electoral_data_5['negative_sentiment_score_4'] = get_avg('Biden','Negative Probability')
electoral_data_5['general_sentitment_score_4'] = get_avg('Biden','General_Probability')
electoral_data_5['tweet_count_4'] = get_agg('Biden','Overall')
positive_tweets = random_tweets('Biden','positive','Post-Caucus')
negative_tweets = random_tweets('Biden','negative','Post-Caucus')
electoral_data_5['positive_tweets_4'] = [positive_tweets]
electoral_data_5['negative_tweets_4'] = [negative_tweets]
electoral_data_5['period1'] = 'pre_debate'
electoral_data_5['positive_sentitment_score_1'] = get_elements('Biden','Positive Probability','pre_debate')
electoral_data_5['negative_sentiment_score_1'] = get_elements('Biden','Negative Probability','pre_debate')
electoral_data_5['general_sentitment_score_1'] = get_elements('Biden','General_Probability','pre_debate')
electoral_data_5['tweet_count_1'] = get_agg('Biden','Pre-Debate')
positive_tweets = random_tweets('Biden','positive','Pre-Debate')
negative_tweets = random_tweets('Biden','negative','Pre-Debate')
electoral_data_5['positive_tweets_1'] = [positive_tweets]
electoral_data_5['negative_tweets_1'] = [negative_tweets]
electoral_data_5['period2'] = 'post_debate'
electoral_data_5['positive_sentitment_score_2'] = get_elements('Biden','Positive Probability','post_debate')
electoral_data_5['negative_sentiment_score_2'] = get_elements('Biden','Negative Probability','post_debate')
electoral_data_5['general_sentitment_score_2'] = get_elements('Biden','General_Probability','post_debate')
electoral_data_5['tweet_count_2'] = get_agg('Biden','Post-Debate')
positive_tweets = random_tweets('Biden','positive','Post-Debate')
negative_tweets = random_tweets('Biden','negative','Post-Debate')
electoral_data_5['positive_tweets_2'] = [positive_tweets]
electoral_data_5['negative_tweets_2'] = [negative_tweets]
electoral_data_5['period3'] = 'post_election'
electoral_data_5['positive_sentitment_score_3'] = get_elements('Biden','Positive Probability','post_election')
electoral_data_5['negative_sentiment_score_3'] = get_elements('Biden','Negative Probability','post_election')
electoral_data_5['general_sentitment_score_3'] = get_elements('Biden','General_Probability','post_election')
electoral_data_5['tweet_count_3'] = get_agg('Biden','Post-Caucus')
positive_tweets = random_tweets('Biden','positive','Post-Caucus')
negative_tweets = random_tweets('Biden','negative','Post-Caucus')
electoral_data_5['positive_tweets_3'] = [positive_tweets]
electoral_data_5['negative_tweets_3'] = [negative_tweets]
## Bloomberg Build
candidate_6 = {}
electoral_data_6 = {}
candidate_6 = '<NAME>'
## Build for Bloomberg
electoral_data_6['period4'] = 'Overall'
electoral_data_6['positive_sentitment_score_4'] = get_avg('Bloomberg','Positive Probability')
electoral_data_6['negative_sentiment_score_4'] = get_avg('Bloomberg','Negative Probability')
electoral_data_6['general_sentitment_score_4'] = get_avg('Bloomberg','General_Probability')
electoral_data_6['tweet_count_4'] = get_agg('Bloomberg','Overall')
positive_tweets = random_tweets('Bloomberg','positive','Post-Caucus')
negative_tweets = random_tweets('Bloomberg','negative','Post-Caucus')
electoral_data_6['positive_tweets_4'] = [positive_tweets]
electoral_data_6['negative_tweets_4'] = [negative_tweets]
electoral_data_6['period1'] = 'pre_debate'
electoral_data_6['positive_sentitment_score_1'] = get_elements('Bloomberg','Positive Probability','pre_debate')
electoral_data_6['negative_sentiment_score_1'] = get_elements('Bloomberg','Negative Probability','pre_debate')
electoral_data_6['general_sentitment_score_1'] = get_elements('Bloomberg','General_Probability','pre_debate')
electoral_data_6['tweet_count_1'] = get_agg('Bloomberg','Pre-Debate')
positive_tweets = random_tweets('Bloomberg','positive','Pre-Debate')
negative_tweets = random_tweets('Bloomberg','negative','Pre-Debate')
electoral_data_6['positive_tweets_1'] = [positive_tweets]
electoral_data_6['negative_tweets_1'] = [negative_tweets]
electoral_data_6['period2'] = 'post_debate'
electoral_data_6['positive_sentitment_score_2'] = get_elements('Bloomberg','Positive Probability','post_debate')
electoral_data_6['negative_sentiment_score_2'] = get_elements('Bloomberg','Negative Probability','post_debate')
electoral_data_6['general_sentitment_score_2'] = get_elements('Bloomberg','General_Probability','post_debate')
electoral_data_6['tweet_count_2'] = get_agg('Bloomberg','Post-Debate')
positive_tweets = random_tweets('Bloomberg','positive','Post-Debate')
negative_tweets = random_tweets('Bloomberg','negative','Post-Debate')
electoral_data_6['positive_tweets_2'] = [positive_tweets]
electoral_data_6['negative_tweets_2'] = [negative_tweets]
electoral_data_6['period3'] = 'post_election'
electoral_data_6['positive_sentitment_score_3'] = get_elements('Bloomberg','Positive Probability','post_election')
electoral_data_6['negative_sentiment_score_3'] = get_elements('Bloomberg','Negative Probability','post_election')
electoral_data_6['general_sentitment_score_3'] = get_elements('Bloomberg','General_Probability','post_election')
electoral_data_6['tweet_count_3'] = get_agg('Bloomberg','Post-Caucus')
positive_tweets = random_tweets('Bloomberg','positive','Post-Caucus')
negative_tweets = random_tweets('Bloomberg','negative','Post-Caucus')
electoral_data_6['positive_tweets_3'] = [positive_tweets]
electoral_data_6['negative_tweets_3'] = [negative_tweets]
## Bernie - done
jsondata['candidate1'] = candidate_1
jsondata['electoral_data'] = electoral_data
##Warren - done
jsondata['candidate2'] = candidate_2
jsondata['electoral_data_2'] = electoral_data_2
##Klobuchar - done
jsondata['candidate3'] = candidate_3
jsondata['electoral_data_3'] = electoral_data_3
##Buttigieg - done
jsondata['candidate4'] = candidate_4
jsondata['electoral_data_4'] = electoral_data_4
##Biden
jsondata['candidate5'] = candidate_5
jsondata['electoral_data_5'] = electoral_data_5
##Bloomberg
jsondata['candidate6'] = candidate_6
jsondata['electoral_data_6'] = electoral_data_6
final_json = json.dumps(jsondata)
return final_json<file_sep>/nevada-caucus-sentiment-master/requirements.txt
certifi==2019.11.28
Flask==1.1.1
gunicorn==20.0.4
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
psycopg2==2.7.6.1
Flask-Cors==3.0.8
nltk==3.4.5
pickleshare==0.7.5
json5==0.9.1
pandas==0.24.2 | 6b118dabe50a3ea991d54347e8c451cfce044b7d | [
"SQL",
"JavaScript",
"Markdown",
"Python",
"Text"
] | 13 | JavaScript | pj-92-gh/project-3-turnin | e111ad2c482b654f8f6a2ce68db1573fc23dc17e | 40e7b4ed048dba76f75c654d687c5b3de2ec6dc6 |
refs/heads/master | <repo_name>justperson94/Machine-Learning-Exercise<file_sep>/Data_Download/Data_Download_using_urlopen.py
import urllib.request
url = "http://uta.pw/shodou/img/28/214.png"
savename = "test_urlopen.png"
# urlopen() >> url에 있는 읽어들이고 파이썬 메모리에 저장한다, 저장후 mem 변수에 저장
mem = urllib.request.urlopen(url).read()
with open(savename, mode="wb") as f:
f.write(mem)
print("Saved")
<file_sep>/README.md
# Machine-Learning-Exercise
# Machine-Learning-Exercise
<file_sep>/Data_Download/Data_Download_using_urllib_request.py
# 라이브러리 읽어들이기
import urllib.request # urllib 패키지 내부에 있는 request 모듈을 읽어 들인다.
# URL과 저장 경로 설정
url = "http://uta.pw/shodou/img/28/214.png"
savename = "test.png"
# 다운로드를 요청하는 코드
urllib.request.urlretrieve(url, savename)
print("Saved") | 0085e3d7a46852ec651818841421ae02da1a4ee7 | [
"Markdown",
"Python"
] | 3 | Python | justperson94/Machine-Learning-Exercise | 9f46c7b7b32738d4a7592c233992b745283445bb | c076009db7f4814f89ff29f8542df69e9951388d |
refs/heads/master | <file_sep>from django.db import models
# Create your models here.
class Board(models.Model):
ttl = models.CharField(max_length=50)
contents = models.TextField()
writer = models.CharField(max_length=20)<file_sep>from django.shortcuts import redirect, render
## Model 추가
from .models import Board
# Create your views here.
def index(request):
return render(request,'main/index.html')
def board(request):
# DB에서 Board 데이터 조회
boardList = Board.objects.all()
# 페이지에 데이터를 던져주어 페이지에서 boardList 데이터를 받을 수 있다.
return render(request, 'main/board/board.html', {'boardList':boardList})
## 데이터 등록
def new_board(request):
## request method가 POST이면 아래 로직 수행
if request.method == 'POST':
Board.objects.create(
ttl=request.POST['ttl'],
contents=request.POST['contents'],
writer=request.POST['writer']
)
## 등록이 성공하면 목록 페이지로 이동
return redirect('/board/')
## POST 요청이 아니면 등록 화면으로 이동
return render(request, 'main/board/new_board.html')
def edit_board(request, pk):
data = Board.objects.get(
pk=pk
)
if request.method == 'POST':
data.ttl = request.POST['ttl']
data.contents = request.POST['contents']
data.writer = request.POST['writer']
data.save()
return redirect('/board/')
## POST 요청이 아니면 수정 화면으로 이동
return render(request, 'main/board/edit_board.html', {'board': data})
def del_board(request, pk):
## pk로 데이터를 조회한 후
data = Board.objects.get(
pk=pk
)
## 데이터 삭제
data.delete()
## 다시 목록 페이지로 이동
return redirect('/board/')<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('board/', views.board),
path('board/new_board', views.new_board),
path('board/<int:pk>/', views.edit_board),
path('board/<int:pk>/remove/', views.del_board)
] | dade9553233bf25d421c93092eca5a2155259efe | [
"Python"
] | 3 | Python | lineaheshsh/djangoProject | 75fbe345b65328d57ba16de7f7ea017a3e53c13b | 863e8c9f14ae0bbbf4c5ad795f6b878c1f61f517 |
refs/heads/main | <file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-la-libertad',
templateUrl: './la-libertad.component.html',
styleUrls: ['./la-libertad.component.css']
})
export class LaLibertadComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-morazan',
templateUrl: './morazan.component.html',
styleUrls: ['./morazan.component.css']
})
export class MorazanComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SantaAnaComponent } from './santa-ana.component';
describe('SantaAnaComponent', () => {
let component: SantaAnaComponent;
let fixture: ComponentFixture<SantaAnaComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ SantaAnaComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SantaAnaComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>$(function () {
$("form[name='registration']").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
},
messages: {
firstname: "Por favor, introduzca su nombre",
lastname: "Por favor, introduzca su apellido",
password: {
required: "<PASSWORD> una <PASSWORD>",
minlength: "Su contraseña debe tener al menos 5 caracteres."
},
email: "Por favor, introduce una dirección de correo electrónico válida",
},
submitHandler: function (form) {
form.submit();
}
});
});
$(document).ready(function () {
$('.telefono').mask('0000-0000');
})<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-san-miguel',
templateUrl: './san-miguel.component.html',
styleUrls: ['./san-miguel.component.css']
})
export class SanMiguelComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SanSalvadorComponent } from './components/san-salvador/san-salvador.component';
import { HomeComponent } from './components/home/home.component';
import { FormularioComponent } from './components/formulario/formulario.component';
import { LaPazComponent } from './components/la-paz/la-paz.component';
import { AhuachapanComponent } from './components/ahuachapan/ahuachapan.component';
import { CaballasComponent } from './components/caballas/caballas.component';
import { ChalatenangoComponent } from './components/chalatenango/chalatenango.component';
import { CuscatlanComponent } from './components/cuscatlan/cuscatlan.component';
import { LaUnionComponent } from './components/la-union/la-union.component';
import { SanMiguelComponent } from './components/san-miguel/san-miguel.component';
import { LaLibertadComponent } from './components/la-libertad/la-libertad.component';
import { SanVicenteComponent } from './components/san-vicente/san-vicente.component';
import { SantaAnaComponent } from './components/santa-ana/santa-ana.component';
import { MorazanComponent } from './components/morazan/morazan.component';
import { UsulutanComponent } from './components/usulutan/usulutan.component';
import { SonsonateComponent } from './components/sonsonate/sonsonate.component';
import { RegistroComponent } from './components/registro/registro.component';
@NgModule({
declarations: [
AppComponent,
SanSalvadorComponent,
HomeComponent,
FormularioComponent,
LaPazComponent,
AhuachapanComponent,
CaballasComponent,
ChalatenangoComponent,
CuscatlanComponent,
LaUnionComponent,
SanMiguelComponent,
LaLibertadComponent,
SanVicenteComponent,
SantaAnaComponent,
MorazanComponent,
UsulutanComponent,
SonsonateComponent,
RegistroComponent,
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SanSalvadorComponent } from './components/san-salvador/san-salvador.component';
import { HomeComponent } from './components/home/home.component';
import { FormularioComponent } from './components/formulario/formulario.component';
import { LaPazComponent } from './components/la-paz/la-paz.component';
import { AhuachapanComponent } from './components/ahuachapan/ahuachapan.component';
import { CaballasComponent } from './components/caballas/caballas.component';
import { ChalatenangoComponent } from './components/chalatenango/chalatenango.component';
import { CuscatlanComponent } from './components/cuscatlan/cuscatlan.component';
import { LaLibertadComponent } from './components/la-libertad/la-libertad.component';
import { LaUnionComponent } from './components/la-union/la-union.component';
import { MorazanComponent } from './components/morazan/morazan.component';
import { SanMiguelComponent } from './components/san-miguel/san-miguel.component';
import { SanVicenteComponent } from './components/san-vicente/san-vicente.component';
import { SantaAnaComponent } from './components/santa-ana/santa-ana.component';
import { UsulutanComponent } from './components/usulutan/usulutan.component';
import { SonsonateComponent } from './components/sonsonate/sonsonate.component';
import { RegistroComponent } from './components/registro/registro.component';
const routes: Routes = [
{ path: 'sansalvador',
component: SanSalvadorComponent
},{
path: 'inicio',
component: HomeComponent
},{
path: 'form',
component: FormularioComponent
},{
path: 'paz',
component : LaPazComponent
},{
path: 'ahuachapan',
component : AhuachapanComponent
},{
path : 'cabañas',
component : CaballasComponent
},{
path : 'chalate',
component : ChalatenangoComponent
},{
path : 'cusca',
component : CuscatlanComponent
},{
path : 'libertad',
component : LaLibertadComponent
},{
path : 'union',
component : LaUnionComponent
},{
path : 'morazan',
component : MorazanComponent
},{
path : 'miguel',
component : SanMiguelComponent
},{
path : 'vicente',
component : SanVicenteComponent
},{
path : 'ana',
component : SantaAnaComponent
},{
path : 'usulutan',
component : UsulutanComponent
},{
path : 'sonsonate',
component : SonsonateComponent
},{
path :'registro',
component : RegistroComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
| 26f798e188ab4674bb02ff454350abd5f60bf0f3 | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | Elizabeth186/CATEDRA_DAW | 4f39506c9108f5c17364c3cb25a947bc7eccf200 | 53f886f88dfa08a506aeb2c5299dbaa70b3b54f2 |
refs/heads/master | <repo_name>avatarwefa/Insight_Photography<file_sep>/admin/schedule/select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
// echo "<script type='text/javascript'>alert('Get here!');</script>";
$output = '';
$sql = "SELECT * FROM SCHEDULE ORDER BY SCHEDULE_ID DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="50%">Thông Tin</th>
<th width="10%">Dụng cụ</th>
<th width="10%">Ngày</th>
<th width="10%">Cơ Sở</th>
<th width="5%">Miễn phí?</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["SCHEDULE_ID"].'</td>
<td class="SCHEDULE_INFO" data-id1="'.$row["SCHEDULE_ID"].'" contenteditable>'.$row["SCHEDULE_INFO"].'</td>
<td class="SCHEDULE_GADGETS" data-id2="'.$row["SCHEDULE_ID"].'" contenteditable>'.$row["SCHEDULE_GADGETS"].'</td>
<td class="SCHEDULE_DATE" data-id3="'.$row["SCHEDULE_ID"].'" contenteditable>'.$row["SCHEDULE_DATE"].'</td>
<td class="SCHEDULE_AREA" data-id4="'.$row["SCHEDULE_ID"].'" contenteditable>'.$row["SCHEDULE_AREA"].'</td>
<td class="SCHEDULE_FREE" data-id5="'.$row["SCHEDULE_ID"].'" contenteditable>'.$row["SCHEDULE_FREE"].'</td>
<td><button type="button" name="delete_btn" data-id6="'.$row["SCHEDULE_ID"].'" class="btn btn-xs btn-danger btn_delete">Delete</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="SCHEDULE_INFO" contenteditable></td>
<td id="SCHEDULE_GADGETS" contenteditable></td>
<td id="SCHEDULE_DATE" contenteditable></td>
<td id="SCHEDULE_AREA" contenteditable></td>
<td id="SCHEDULE_FREE" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td></td>
<td id="SCHEDULE_INFO" contenteditable></td>
<td id="SCHEDULE_GADGETS" contenteditable></td>
<td id="SCHEDULE_DATE" contenteditable></td>
<td id="SCHEDULE_AREA" contenteditable></td>
<td id="SCHEDULE_FREE" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr> ';
}
$output .= '</table>
</div>';
echo $output;
?><file_sep>/pages/viewprofile.php
<!-- -->
<?php
if(isset($_POST["btnSignout"]))
{
unset($_SESSION["USER_ID"]);
unset($_SESSION["USER_NAME"]);
unset($_SESSION["PASSWORD"]);
unset($_SESSION["FULL_NAME"]);
unset($_SESSION["TRIAL_DATE"]);
unset($_SESSION["EMAIL"]);
unset($_SESSION["IDGROUP"]);
header("Refresh:0");
}
//header("Location:index.php")
?>
<li>
<div class="card-container">
<span class="pro" style="left: 5px;"><?php switch ($_SESSION["IDGROUP"]) {
case 1:
case 3:
echo "Nâng Cao";
# code...
break;
case 2:
case 4:
echo "Chuyên Nghiệp";
# code...
break;
case 5:
echo "Admin";
# code...
break;
default:
# code...
echo "Cơ Bản";
break;
} ?></span>
<img class="round" style="object-fit: contain; width: 20vh;" src="https://i.dlpng.com/static/png/5065892-my-profile-icon-png-327283-free-icons-library-profile-icon-png-500_500_preview.png" alt="user" />
<h3><?php echo $_SESSION["FULL_NAME"] ?></h3>
<?php if ($_SESSION['TRIAL_DATE'] != '0000-00-00')
{
$time = date('Y-m-d',strtotime($_SESSION["TRIAL_DATE"]));
//$time = DateTime::createFromFormat('Y-m-d', $_SESSION["TRIAL_DATE"]);
//$time = strtotime($_SESSION["TRIAL_DATE"]);
// $_SESSION['TRIAL_DATE'] = strtotime($_SESSION['TRIAL_DATE']);
//$time = $time->modify('+1 month');
echo "<h6> Hết hạn : ". $time ."</h6>";
}
?>
<p><?php echo $_SESSION['EMAIL'] ?></p>
<div class="buttons">
<a class="btn btn-outline-dark" href="course.php" role="button">Khóa Học Của Bạn</a>
</div>
<div class="buttons">
<a class="btn btn-outline-dark" href="pages/editProfile.php" role="button">Thay đổi thông tin người dùng</a>
<form method="post">
<button class="primary ghost" name="btnSignout">
Đăng Xuất
</button>
</form>
</div>
</div>
</li><file_sep>/pages/viewSchedule.php
<div class="container">
<div class="section">
<!-- Blog style taken from https://codepen.io/Michael-luke/pen/PzGywb?editors=1000 -->
<div class="blog-post blog-single-post">
<div class="single-post-title">
<h2>Lịch các buổi học offline sắp tới</h2>
</div>
<div class="single-post-content">
<table class="events-list">
<?php
$connect = mysqli_connect('localhost', 'root', '', 'insight');
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$now_date = date("Y-m-d");
//câu truy vấn
$sql = "SELECT * FROM SCHEDULE WHERE SCHEDULE.SCHEDULE_DATE > '$now_date' ORDER BY SCHEDULE_DATE ASC";
//kiểm tra
$result = mysqli_query($connect, $sql);
while($EventList = mysqli_fetch_array($result))
{
$event_date = $EventList['SCHEDULE_DATE'];
$event_date = date("jS F, Y", strtotime($event_date));
?>
<tr>
<td>
<div class="event-date">
<div class="event-day"><?php echo date("jS", strtotime($event_date)); ?></div>
<div class="event-month"><?php echo date("F", strtotime($event_date)); ?></div>
</div>
</td>
<td style="color: #404040">
<?php echo $EventList['SCHEDULE_INFO'] ; ?>
</td>
<td class="event-venue hidden-xs" style="color: #404040;"><i class="icon-map-marker"><?php echo $EventList['SCHEDULE_GADGETS'] ; ?> </i></td>
<td class="event-price hidden-xs" style="color: #404040"><?php if ($EventList['SCHEDULE_FREE']==0) { echo 'FREE';} else echo 'VIP' ; ?></td>
<td><a href="#" class="btn btn-grey btn-sm event-more"><?php echo $EventList['SCHEDULE_AREA'] ; ?> </a></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</div>
<file_sep>/admin/users/insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
echo $sql = "INSERT INTO user(USER_NAME,PASSWORD,EMAIL,FULL_NAME,TRIAL_DATE,IDGROUP) VALUES('".$_POST["USER_NAME"]."','".md5($_POST["PASSWORD"])."' ,'".$_POST["EMAIL"]."','".$_POST["FULL_NAME"]."','".$_POST["TRIAL_DATE"]."','".$_POST["IDGROUP"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Thêm dữ liệu';
}
?> <file_sep>/index.php
<?php
include "lib/queries.php";
ob_start();
session_start();
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Insight Photography's Homepage</title>
<!-- Bootstrap -->
<link href="bootstrap/css/theme.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="style.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,300,700,100' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway:300,700,900,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/typicons/2.0.7/typicons.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/pushy.css">
<link rel="stylesheet" href="assets/css/masonry.css">
<link rel="stylesheet" href="assets/css/animate.css">
<link rel="stylesheet" href="assets/css/magnific-popup.css">
<link rel="stylesheet" href="assets/css/odometer-theme-default.css">
<!-- Hook -->
<script>
window.odometerOptions = {
selector: '.odometer',
format: '(,ddd)', //group số, và số chữ số sau digit
duration: 13000, // thời gian đợi của javascript
theme: 'default'
};
</script>
</head>
<body class="">
<!-- Pushy Menu -->
<nav class="pushy pushy-left">
<ul class="list-unstyled">
<?php if (!isset($_SESSION['USER_NAME'])) {
require('pages/viewlogin.php');
} else {
require('pages/viewprofile.php');
} ?>
<li><a href="#news">Chúng tôi là ai</a></li>
<li><a href="#achievement">Những thành tựu</a></li>
<li><a href="#Features">Tính năng của khoá học</a></li>
<li><a href="#review">Học viên nói gì</a></li>
<li><a href="#pricing">Bảng giá</a></li>
<li><a href="#photos">Hình ảnh từ khoá học</a></li>
<li><a href="#newsletter">Đăng kí newsletter</a></li>
<li><a href="#contact">Liên hệ!</a></li>
<li><a href="https://www.youtube.com/watch?v=dFz5E1rZqR4" target="_blank">Buổi học thử</a></li>
</ul>
</nav>
<!-- Site Overlay -->
<div class="site-overlay"></div>
<header id="home">
<div class="container-fluid">
<!-- Thay đổi hình ảnh tại style.css to the class header .container-fluid [approximately row 50] -->
<div class="container">
<div class="row">
<div class="col-xs-2 text-center">
<div class="menu-btn"><span class="hamburger">☰</span></div>
</div>
</div>
<div class="jumbotron">
<h1><small>Nơi khơi nguồn cho đam mê</small>
<strong>Nhiếp ảnh</strong></h1>
<p>Đây là nơi bạn có thể biến những khoảnh khắc thành những bước ảnh đắc giá cho hành trình của bạn.</p>
<p><a class="btn btn-primary btn-lg" role="button">Tìm hiểu thêm</a> <a target="_blank" href="#Features" class="btn btn-lg btn-danger" role="button">Chúng tôi trên Youtube</a></p>
</div>
</div>
</div>
</header>
<section id="schedule">
<?php if (isset($_SESSION['USER_NAME']))
{
require('pages/viewSchedule.php');
}
?>
</section>
<section id="news" class="blog wow fadeInUp" data-wow-delay="300ms">
<div class="container">
<div class="row">
<div class="col-md-7">
<h2>Insight Photography, chúng tôi là ai?.</h2>
<p>Nhiếp ảnh là một bộ môn nghệ thuật mới, nhưng để học được nó không phải ai cũng nắm rõ các kỹ năng. Vì vậy chúng tôi - những chuyên gia về lĩnh vực nhiếp ảnh ở đây để giúp bạn.</p>
<p>Chúng tối biết, việc học là vô tận, vì vậy chúng tôi luôn cập nhật các bài giảng của chúng tôi cùng với các công nghệ tân tiến nhất.</p>
<p>Mọi nội dung được chúng tôi chọn lựa kỹ càng và đem đến cho người dùng một trải nghiệm tuyệt vời, để các học viên luôn đến với chúng tôi với mục đích giải trí, đồng thời khơi gợi lên những khao khát về nghệ thuật bên trong bạn.</p>
<a class="btn btn-danger btn-lg" href="#photos"> Lượn 1 vòng <i class="fa fa-arrow-circle-o-right"></i> </a>
</div>
<div class="col-md-5">
<a href="#">
<img src="https://images.unsplash.com/photo-1563206748-a8d1142ea31c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="img-responsive">
</a>
</div>
</div>
</div>
</section>
<section id="achievement" class="number wow fadeInUp" data-wow-delay="300ms">
<!-- thay đổi ảnh tại style.css ở class .number .container-fluid [approximately row 102] -->
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-6 opaline col-md-offset-6">
<div class="row">
<div class="col-md-offset-1 col-md-10">
<h3>Các thống kê sơ bộ</h3>
<h5>Mắt thẩm mỹ và tính chuyên nghiệp là thứ có thể học được!</h5>
<p>Chúng tôi đã "cho ra lò" hàng loạt các nhiếp ảnh gia thứ thiệt mà sản phẩm của những bạn trẻ này đã len lõi trên khắp các mặt báo nổi tiếng ở Việt Nam.</p>
</div>
</div>
<div class="row text-center">
<!-- thay đổi số tại assets/js/scripts.js -->
<div class="col-md-4 boxes col-xs-6 col-xs-offset-3 col-lg-4 col-lg-offset-1 col-md-offset-1 col-sm-6 wow fadeInUp">
<h5>Số học viên theo học</h5>
<h3 class="odometer 01">00000</h3>
</div>
<div class="col-md-4 boxes col-xs-6 col-xs-offset-3 col-lg-4 col-lg-offset-2 col-md-offset-2 col-sm-6 wow fadeInUp" data-wow-delay="300ms">
<h5>Số đơn vị bài học</h5>
<h3 class="odometer 02">00000</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="Features">
<div class="container">
<div class="row features">
<h1 class="arrow" style="text-align:center">KHOÁ HỌC NÀY CÓ GÌ?</h1>
<div class="col-md-4 text-center wow fadeInUp" data-wow-delay="100ms">
<span class="typcn typcn-pencil x3"></span>
<h4>Lý thuyết về nhiếp ảnh</h4>
<p>Bạn lo sợ vì xuất phát từ con số 0? Khoá học sẽ bao gồm các kiến thức nền tảng và căn bản nhất về nhiếp ảnh. Các bố cục cần có để nhiếp ảnh đẹp và các kiến thức và các loại máy ảnh, lens trên thị trường.</p>
</div>
<div class="col-md-4 text-center wow fadeInUp" data-wow-delay="300ms">
<span class="typcn typcn-camera-outline x3"></span>
<h4>Thao tác thật.</h4>
<p>Các bạn sẽ được cùng đoàn của chúng tôi đi tới những vùng đất kì diệu, được thực hành các kiến thức đã học.</p>
</div>
<div class="col-md-4 text-center wow fadeInUp" data-wow-delay="500ms">
<span class="typcn typcn-bookmark x3"></span>
<h4>Ảnh đẹp cần có filter</h4>
<p>Các kiến thức về chỉnh sửa ảnh trên các ứng dụng tối tân nhất hiện nay, từ Adobe Photoshop hay chỉ là Snapseed trên điện thoại, các khái niệm về chỉnh sửa ảnh sẽ đáp ứng các tiêu chí của bạn để cho ra một bức ảnh không thể tuyệt vời hơn.</p>
</div>
</div>
</div>
</section>
<section id="review" class="story wow fadeInUp" data-wow-delay="300ms">
<!-- thay đổi ảnh tại style.css ở class .story .container-fluid [approximately row 141] -->
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-6 opaline">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p class="lead"><i>Nâng cao kỹ năng và học hỏi không ngừng, đó là những gì tôi đã học được trong khoá học của Insight Photography.</i></p>
<p><i>Là một nhà báo tác nghiệp hơn 5 năm, tôi hiểu được câu nói "Một bức tranh hơn ngàn lời nói", khoá học là thú vui thanh tao sau những giờ làm việc căng thẳng, và sau những trải nghiệm đó là nấc thang cao hơn cho sự nghiệp.</i></p>
<h6 class="lead"> – <NAME></h6>
<p><small>Phóng viên - biên tập viên<br>
Tại website tin tức hàng đầu Việt Nam VN-Express.</small></p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--Pricing-->
<section class="intro text-center section-padding" id="intro">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 wp1">
<h1 class="arrow">BẢNG GIÁ DỊCH VỤ</h1>
<p>Chúng tôi đã tính toán và cân nhắc rất kỹ khi đưa ra những khoá học sau để phù hợp vơi nhiều đối tượng nhất có thể, khoá học phía bên phải đã bao gồm các tính năng của khoá học bên trái nó cộng với các tính năng cao cấp hơn.</p>
</div>
</div>
</div>
</section>
<section id="pricing" class="blog wow fadeInUp" data-wow-delay="300ms">
<div class="background">
<div class="container">
<div class="panel pricing-table">
<?php
if (!isset($_SESSION['USER_NAME'])) {
require('pages/viewlogin.php');
} else {
require('pages/viewprice.php');
}
?>
<!-- <div class="pricing-plan">
<img src="https://s22.postimg.cc/8mv5gn7w1/paper-plane.png" alt="" class="pricing-img">
<h2 class="pricing-header">CƠ BẢN</h2>
<ul class="pricing-features">
<li class="pricing-features-item">Stream các video về nhiếp ảnh cơ bản, các tips mới nhất</li>
<li class="pricing-features-item">Tutorial về chỉnh sửa ảnh & challenge hàng tuần</li>
</ul>
<span class="pricing-price">MIỄN PHÍ</span>
<a href="#/" class="pricing-button">Đăng kí</a>
</div>
<div class="pricing-plan">
<img src="https://s28.postimg.cc/ju5bnc3x9/plane.png" alt="" class="pricing-img">
<h2 class="pricing-header">CHUYÊN NGHIỆP</h2>
<ul class="pricing-features">
<li class="pricing-features-item">Các video chuyên sâu về nhiếp ảnh</li>
<li class="pricing-features-item">Các buổi học offline và truy cập vào kho nội dung trực tuyến có thể tải về</li>
</ul>
<span class="pricing-price">$150</span>
<a href="#/" class="pricing-button is-featured">DÙNG THỬ</a>
</div>
<div class="pricing-plan">
<img src="https://s21.postimg.cc/tpm0cge4n/space-ship.png" alt="" class="pricing-img">
<h2 class="pricing-header">NÂNG CAO</h2>
<ul class="pricing-features">
<li class="pricing-features-item">Đi các chuyến dã ngoại thực hành các kỹ năng đã học</li>
<li class="pricing-features-item">Nhận được feedback và hướng dẫn trong suốt khoá học</li>
</ul>
<span class="pricing-price">$400</span>
<a href="#/" class="pricing-button">DÙNG THỬ</a>
</div> -->
</div>
</div>
</div>
</section>
<section id="photos" class="gallery wow fadeInUp" data-wow-delay="300ms">
<div class="container">
<h3 class="text-center">Các hình ảnh "tác nghiệp" của học viên.</h3>
<div class="row">
<div class="masonry image-gallery">
<div class="grid-sizer"></div>
<div class="gutter-sizer"></div>
<?php
$connect = myConnect();
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT * FROM images";
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
while ($row = mysqli_fetch_array($result)) {
//hiển thị dữ liệu
// echo 'Dữ liệu thứ ' . $i . ' gồm: ' . $row['url'] . '-' . $row['title'] . '-' . $row['content'] . '<br/>';
//tăng $i lên 1
echo '<div class="item item-width1">
<a href=' . $row['url'] . '>
<img src=' . $row['url'] . ' alt="" />
</a>
</div>';
$i++;
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?>
</div>
</div>
</div>
</section>
<section class="clients wow fadeInUp" data-wow-delay="300ms">
<div class="container">
<h4 class="text-center">Các đối tác của chúng tôi</h4>
<div class="row">
<div class="col-md-2">
<img src="images/logo-sample-01.jpg" class="img-responsive" alt="logo-sample1" />
</div>
<div class="col-md-2">
<img src="images/logo-sample-02.jpg" class="img-responsive" alt="logo-sample2" />
</div>
<div class="col-md-2">
<img src="images/logo-sample-03.png" class="img-responsive" alt="logo-sample3" />
</div>
<div class="col-md-2">
<img src="images/logo-sample-04.jpg" class="img-responsive" alt="logo-sample4" />
</div>
<div class="col-md-2">
<img src="images/logo-sample-05.jpg" class="img-responsive" alt="logo-sample5" />
</div>
<div class="col-md-2">
<img src="images/logo-sample-06.png" class="img-responsive" alt="logo-sample6" />
</div>
</div>
</div>
</section>
<section id="newsletter" class="prefooter wow fadeInUp" data-wow-delay="300ms">
<!-- change the image in style.css to the class .prefooter .container-fluid [approximately row 154] -->
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Để không bỏ lỡ những cập nhật mới.</h3>
<p>Đăng kí hộp thư newsletter để nhận ngay những thông tin mới nhất về những ưu đãi về khoá học, cũng như các buổi workshop miễn phí để không ngừng đột phá trong những shoot ảnh của bạn.</p>
<div class="row">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Your Email Here...">
<br>
<button type="button" class="btn btn-danger">Đăng kí Newsletter</button>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="dark-bg text-center section-padding contact-wrap" id="contact" data-wow-delay="300ms">
<a href="#top" class="up-btn"><i class="fa fa-chevron-up"></i></a>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="arrow">Liên hệ với chúng tôi</h1>
</div>
</div>
<div class="row contact-details">
<?php
// khởi tạo kết nối
$connect = myConnect();
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT value FROM ADDRESS";
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
while ($row = mysqli_fetch_array($result)) {
//hiển thị dữ liệu
echo '<div class="col-md-4">
<div class="light-box box-hover">
<h3><i class="fa fa-mobile"></i></h3>
<h2>
<span>Địa chỉ</span></h2>
<p>' . $row['value'] . '</p>
</div>
</div>';
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?>
<?php
// khởi tạo kết nối
$connect = myConnect();
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT value FROM PHONE";
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
while ($row = mysqli_fetch_array($result)) {
//hiển thị dữ liệu
echo '<div class="col-md-4">
<div class="light-box box-hover">
<h3><i class="fa fa-mobile"></i></h3>
<h2>
<span>Điện thoại</span></h2>
<p>' . $row['value'] . '</p>
</div>
</div>' //tăng $i lên 1
;
$i++;
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?>
<?php
// khởi tạo kết nối
$connect = myConnect();
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT value FROM EMAIL";
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
while ($row = mysqli_fetch_array($result)) {
//hiển thị dữ liệu
echo '<div class="col-md-4">
<div class="light-box box-hover">
<h3><i class="fa fa-mobile"></i></h3>
<h2>
<span>Email</span></h2>
<p><a href="#">' . $row['value'] . '</a></p>
</div>
</div>' //tăng $i lên 1
;
$i++;
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Kết nối qua mạng xã hội</h3>
<p>© 2019 Insight Photography. Được thế kế bởi Từ <NAME> <a target="_blank" href="http://www.facebook.com/NgocHuyTuVEVO">InsightPhotography.com</a></p>
</div>
<div class="col-md-4">
<p class="text-right social"><i class="typcn typcn-social-facebook-circular"></i><i class="typcn typcn-social-twitter-circular"></i><i class="typcn typcn-social-tumbler-circular"></i><i class="typcn typcn-social-github-circular"></i><i class="typcn typcn-social-dribbble-circular"></i></p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/js/bootstrap-scrollspy.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="http://masonry.desandro.com/masonry.pkgd.js"></script>
<script src="assets/js/masonry.js"></script>
<script src="assets/js/pushy.min.js"></script>
<script src="assets/js/jquery.magnific-popup.min.js"></script>
<script src="assets/js/wow.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/odometer.js"></script>
</body>
</html><file_sep>/admin/schedule/edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
$SCHEDULE_ID = $_POST["SCHEDULE_ID"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
$sql = "UPDATE SCHEDULE SET ".$column_name."='".$text."' WHERE SCHEDULE_ID='".$USER_ID."'";
if(mysqli_query($connect, $sql))
{
echo 'Update dữ liệu';
}
?><file_sep>/course.php
<?php
require "lib/queries.php";
ob_start();
session_start();
if (!isset($_SESSION['USER_NAME']))
{
echo "<script type='text/javascript'>alert('Bạn phải đăng nhập trước!!');</script>";
header("location:index.php");
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Insight Photography's Homepage</title>
<!-- Bootstrap -->
<link href="bootstrap/css/theme.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="style.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,300,700,100' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway:300,700,900,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/typicons/2.0.7/typicons.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/pushy.css">
<link rel="stylesheet" href="assets/css/masonry.css">
<link rel="stylesheet" href="assets/css/animate.css">
<link rel="stylesheet" href="assets/css/magnific-popup.css">
<link rel="stylesheet" href="assets/css/odometer-theme-default.css">
<!-- Hook -->
<script>
window.odometerOptions = {
selector: '.odometer',
format: '(,ddd)', //group số, và số chữ số sau digit
duration: 13000, // thời gian đợi của javascript
theme: 'default'
};
</script>
</head>
<body class="">
<!-- Pushy Menu -->
<nav class="pushy pushy-left">
<ul class="list-unstyled">
<?php if (!isset($_SESSION['USER_NAME'])) {
require('pages/viewlogin.php');
} else {
require('pages/viewprofile.php');
} ?>
<li><a href="pages/index.php">Đăng Kí/ Đăng Nhập</a></li>
<li><a href="#news">Chúng tôi là ai</a></li>
<li><a href="#achievement">Những thành tựu</a></li>
<li><a href="#Features">Tính năng của khoá học</a></li>
<li><a href="#review">Học viên nói gì</a></li>
<li><a href="#pricing">Bảng giá</a></li>
<li><a href="#photos">Hình ảnh từ khoá học</a></li>
<li><a href="#newsletter">Đăng kí newsletter</a></li>
<li><a href="#contact">Liên hệ!</a></li>
<li><a href="https://www.youtube.com/watch?v=dFz5E1rZqR4" target="_blank">Buổi học thử</a></li>
</ul>
</nav>
<!-- Site Overlay -->
<div class="site-overlay"></div>
<header id="home">
<div class="container-fluid">
<!-- Thay đổi hình ảnh tại style.css to the class header .container-fluid [approximately row 50] -->
<div class="container">
<div class="row">
<div class="col-xs-2 text-center">
<div class="menu-btn"><span class="hamburger">☰</span></div>
</div>
</div>
<div class="jumbotron">
<h1><small>Nơi khơi nguồn cho đam mê</small>
<strong>Nhiếp ảnh</strong></h1>
<p>Đây là nơi bạn có thể biến những khoảnh khắc thành những bước ảnh đắc giá cho hành trình của bạn.</p>
</div>
</div>
</div>
</header>
<section id="news" class="blog wow fadeInUp" data-wow-delay="300ms">
<div class="container">
<div class="row ">
<form class ="search center" action="course.php" method="get">
<input type="text" name="search" placeholder="Nhập từ khóa cần tìm"/>
<input type="submit" name="ok" value="Tìm kiếm" />
</form>
<?php
if (isset($_REQUEST['ok'])) {
$search = addslashes($_GET['search']);
if (empty($search)) {
echo "Yeu cau nhap du lieu vao o trong";
}
else {
$connect = mysqli_connect('localhost', 'root', '', 'insight');
mysqli_set_charset($connect, "UTF8");
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
$query = "select * from course where name like '%$search%'";
if ($result = mysqli_query($connect, $query)) {
$num = mysqli_num_rows($result);
$i =1;
if ($num > 0 && $search != "")
{
echo "$num Kết quả trả về cho từ khóa <b>$search</b><br><br>";
while ($row = mysqli_fetch_assoc($result)) {
//hiển thị dữ liệu
// echo 'Dữ liệu thứ ' . $i . ' gồm: ' . $row['id'] . '-' . $row['title'] . '-' . $row['content'] . '<br/>';
?>
<div class="col-lg-4 col-md-6">
<article class=" border-0 rounded-0 mb-4">
<img src=' <?php echo $row['thumb'] ?> ' alt="" class="img-responsive">
<div class="mt-3 px-4 py-3 ">
<a href="lessons.php?course_id=<?php echo $row['course_id']?>">
<h3><?php echo $row['name'] ?> </h3>
</a>
<h2 class="mb-3 font-secondary"><?php echo $row['teacher'] ?></h2>
<p><?php echo $row['description'] ?></p>
</div>
</article>
</div>
<?php
$i++;
}
} else
//Hiện thông báo khi không thành công
echo "<script>
alert('Không tìm thấy khóa học bạn vừa nhập!');
window.location.href='course.php';
</script>";
// . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
}
}
}
else {
$connect = mysqli_connect('localhost', 'root', '', 'insight');
mysqli_set_charset($connect, "UTF8");
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT * FROM COURSE";
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
while ($row = mysqli_fetch_array($result)) {
//hiển thị dữ liệu
// echo 'Dữ liệu thứ ' . $i . ' gồm: ' . $row['id'] . '-' . $row['title'] . '-' . $row['content'] . '<br/>';
?>
<div class="col-lg-4 col-md-6" style="margin-top:30px;">
<article class=" border-0 rounded-0 mb-4">
<img src=' <?php echo $row['thumb'] ?> ' alt="" class="img-responsive">
<div class="mt-3 px-4 py-3 ">
<a href="lessons.php?course_id=<?php echo $row['course_id']?>">
<h3><?php echo $row['name'] ?> </h3>
</a>
<h2 class="mb-3 font-secondary"><?php echo $row['teacher'] ?></h2>
<p><?php echo $row['description'] ?></p>
</div>
</article>
</div>
<?php
$i++;
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
}
?>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Kết nối qua mạng xã hội</h3>
<p>© 2019 Insight Photography. Được thế kế bởi Từ Ng<NAME> <a target="_blank" href="http://www.facebook.com/NgocHuyTuVEVO">InsightPhotography.com</a></p>
</div>
<div class="col-md-4">
<p class="text-right social"><i class="typcn typcn-social-facebook-circular"></i><i class="typcn typcn-social-twitter-circular"></i><i class="typcn typcn-social-tumbler-circular"></i><i class="typcn typcn-social-github-circular"></i><i class="typcn typcn-social-dribbble-circular"></i></p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/js/bootstrap-scrollspy.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="http://masonry.desandro.com/masonry.pkgd.js"></script>
<script src="assets/js/masonry.js"></script>
<script src="assets/js/pushy.min.js"></script>
<script src="assets/js/jquery.magnific-popup.min.js"></script>
<script src="assets/js/wow.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/odometer.js"></script>
</body>
</html>
<file_sep>/pages/index.php
<?php
ob_start();
session_start();
require "../lib/queries.php";
$conn = myConnect();
if (isset($_POST["btnSignup"]))
{
$flag = 0;
$username = $_POST["txtUsername"];
$password = $_POST["txtPassword"];
$retypepassword = $_POST["txtRetypePassword"];
$fullname = $_POST["txtFullName"];
$gender = $_POST["gender"];
$email = $_POST["txtEmail"];
$date = date("Y-m-d ");
$date = date('Y-m-d',strtotime($date. ' + 1 month'));
$idgroup = $_POST["idgroup"];
$qr1 =
"
select * from USER
where USER.USER_NAME = '$username' or USER.EMAIL = '$email'
";
$result = mysqli_query($conn,$qr1);
if ($username == "" || $password == "" || $fullname == "" || $gender == "" || $idgroup == "")
{
$flag = 1;
echo "<script type='text/javascript'>alert('Kiểm tra các cột nhập liệu!');</script>";
}
if ( $password != $retypepassword && $flag == 0 )
{
$flag = 1;
echo "<script type='text/javascript'>alert('Mật khẩu bạn nhập cần trùng khớp nhau');</script>";
}
if (mysqli_num_rows($result) > 0 && $flag == 0)
{
$flag = 1;
echo "<script type='text/javascript'>alert('Tên đăng nhập đã có người sở hữu! Hãy thay bằng tên khác!');</script>";
}
if ($flag == 0)
{
$password = md5($password);
if ($idgroup == 0)
{
#$date = null;
$date = '0000-00-00';
}
$qr = "
INSERT INTO USER VALUES
(null,'$username','$password','$gender','$email' ,'$fullname', '$date' ,'$idgroup')
";
mysqli_query($conn,$qr);
echo "<script type='text/javascript'>alert('Đăng kí thành công! Bạn có thể đăng nhập ngay bây giờ.);</script>";
// echo($qr);
}
}
?>
<?php
//require "../../lib/queries.php";
//$conn = myConnect();
if (isset($_POST["btnLogin"]))
{
$user = $_POST["txtUser"];
$pass = $_POST["txtPass"];
$qr1 =
"
select * from USER
where USER.USER_NAME = '$user'
";
$result = mysqli_query($conn,$qr1);
$row_user = mysqli_fetch_array($result);
if ($user == $row_user['USER_NAME'] && md5($pass) == $row_user['PASSWORD'])
{
if($row_user['IDGROUP'] == 5){
$_SESSION["IDGROUP"] = $row_user['IDGROUP'];
echo "<script type='text/javascript'>alert('Chào mừng bạn đến với trang quản trị Admin!');
window.location.href='../admin/index.php';</script>";
}
$_SESSION["IDGROUP"] = $row_user['IDGROUP'];
$user_id = $row_user['USER_ID'];
$_SESSION["USER_ID"] = $row_user['USER_ID'];
$_SESSION["TRIAL_DATE"] =$row_user['TRIAL_DATE'];
if($_SESSION["IDGROUP"]==1 or $_SESSION["IDGROUP"]==2)
{
$time = date('Y-m-d',strtotime($_SESSION["TRIAL_DATE"]));
if(date('Y-m-d') > $time)
{
$qr1 = "
UPDATE USER SET USER.IDGROUP=0 WHERE USER.USER_ID = $user_id
";
$_SESSION["IDGROUP"] = 0;
$result = mysqli_query($conn,$qr1);
echo "<script type='text/javascript'>alert('Dùng thử đã hết hạn!');</script>";
}
}
$_SESSION["USER_NAME"] = $row_user['USER_NAME'];
$fullname = $row_user['FULL_NAME'];
$_SESSION["PASSWORD"] = $row_user['PASSWORD'];
$_SESSION["FULL_NAME"] = $row_user['FULL_NAME'];
$date = $_SESSION["TRIAL_DATE"];
$_SESSION["EMAIL"] =$row_user['EMAIL'];
$_SESSION["GENDER"] =$row_user['GENDER'];
echo "<script> alert('Xin chào quay trở lại, $fullname ');
window.setTimeout(function(){
window.location.href = '../index.php';
}, 1000);
</script>";
}
else
{
echo "<script type='text/javascript'>alert('Đăng Nhập Thất Bại, Thử Lại Sau');</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Colorlib Templates">
<meta name="author" content="Colorlib">
<meta name="keywords" content="Colorlib Templates">
<!-- Title Page-->
<title>Insight Sign Up!</title>
<!-- Icons font CSS-->
<link href="vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">
<!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Vendor CSS-->
<link href="vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="vendor/datepicker/daterangepicker.css" rel="stylesheet" media="all">
<!-- Main CSS-->
<link href="css/main.css" rel="stylesheet" media="all">
<!-- Include this for Ajax use-->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#txtSignUp').click(function()
{
$('.card-body').load('login/login.php');
})
});
</script>
</head>
<body>
<div class="hello" id="hello">
</div>
<div class="page-wrapper bg-gra-02 p-t-130 p-b-100 font-poppins">
<div class="wrapper wrapper--w680">
<div class="card card-4">
<div class="card-body" div="card-body">
<h2 class="title">Form Đăng Nhập!</h2>
<form method="POST">
<div class="row row-space">
</div>
<div class="row row-space">
</div>
<div class="input-group">
<div class="input-group">
<label class="label">Username</label>
<input class="input--style-4" type="text" name="txtUser" minlength="5" maxlength="30">
</div>
</div>
<div class="input-group">
<div class="input-group">
<label class="label">Password</label>
<input class="input--style-4" type="Password" name="txtPass" minlength="5" maxlength="30">
</div>
</div>
<div class="p-t-15">
<button class="btn btn--radius-2 btn--blue" name="btnLogin" id="btnLogin" type="submit">Đăng Nhập</button>
</div>
<br>
<div class="input-group" >
<label class="label" ></label>
<a href="#" type="button" id="txtSignUp" >Chưa tạo tài khoản? Đăng Kí tại đây!</a><br><br>
<a href="../ResetPassword/forgotPassword.php" type="button" id="txtSignUp" >Quên mật khẩu?</a>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Jquery JS-->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Vendor JS-->
<script src="vendor/select2/select2.min.js"></script>
<script src="vendor/datepicker/moment.min.js"></script>
<script src="vendor/datepicker/daterangepicker.js"></script>
<!-- Main JS-->
<script src="js/global.js"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html>
<!-- end document--><file_sep>/admin/users/index.php
<html>
<head>
<title>User Table Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">AJAX DATA TABLE</h3><br />
<p align="center"> Username Table Admin!</p>
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var USER_NAME = $('#USER_NAME').text();
var PASSWORD = $('#<PASSWORD>').text();
var EMAIL = $('#EMAIL').text();
var FULL_NAME = $('#FULL_NAME').text();
var TRIAL_DATE = $('#TRIAL_DATE').text();
var IDGROUP = $('#IDGROUP').text();
// if(HoTen == '' || HoTen.length <2 || HoTen.length > 40)
// {
// alert("Enter name with range of 5-40 characters");
// return false;
// }
// if(idGroup == '' || isNaN(year))
// {
// alert("Enter idGroup in NUMBER ");
// return false;
// }
$.ajax({
url:"insert.php",
method:"POST",
data:{USER_NAME:USER_NAME, EMAIL:EMAIL,FULL_NAME:FULL_NAME,TRIAL_DATE:TRIAL_DATE,IDGROUP:IDGROUP, PASSWORD:<PASSWORD>},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
function edit_data(USER_ID, text, column_name)
{
$.ajax({
url:"edit.php",
method:"POST",
data:{USER_ID:USER_ID, text:text, column_name:column_name},
dataType:"text",
success:function(data){
alert(data);
}
});
}
$(document).on('blur', '.USER_NAME', function(){
var USER_ID = $(this).data("id1");
var USER_NAME = $(this).text();
edit_data(USER_ID, USER_NAME, "USER_NAME");
});
$(document).on('blur', '.EMAIL', function(){
var USER_ID = $(this).data("id2");
var EMAIL = $(this).text();
edit_data(USER_ID, EMAIL, "EMAIL");
});
$(document).on('blur', '.FULL_NAME', function(){
var USER_ID = $(this).data("id3");
var FULL_NAME = $(this).text();
edit_data(USER_ID, FULL_NAME, "FULL_NAME");
});
$(document).on('blur', '.TRIAL_DATE', function(){
var USER_ID = $(this).data("id4");
var TRIAL_DATE = $(this).text();
edit_data(USER_ID, TRIAL_DATE, "TRIAL_DATE");
});
$(document).on('blur', '.IDGROUP', function(){
var USER_ID = $(this).data("id5");
var IDGROUP = $(this).text();
edit_data(USER_ID,IDGROUP, "IDGROUP");
});
$(document).on('blur', '.PASSWORD', function(){
var USER_ID = $(this).data("id6");
var PASSWORD = $(this).text();
edit_data(USER_ID,PASSWORD, "PASSWORD");
});
$(document).on('click', '.btn_delete', function(){
var USER_ID = $(this).data("id7");
if(confirm("Bạn muốn xoá hàng này?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{USER_ID:USER_ID},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script><file_sep>/lessons.php
<?php
require "lib/queries.php";
ob_start();
session_start();
if (!isset($_SESSION['USER_NAME']))
{
echo "<script type='text/javascript'>alert('Bạn phải đăng nhập trước!!');</script>";
header("location:index.php");
}
//echo "<script type='text/javascript'>alert('$_SESSION['USER_NAME']');</script>";
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Insight Photography's Homepage</title>
<!-- Bootstrap -->
<link href="bootstrap/css/theme.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="style.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,300,700,100' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway:300,700,900,500' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/typicons/2.0.7/typicons.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/pushy.css">
<link rel="stylesheet" href="assets/css/masonry.css">
<link rel="stylesheet" href="assets/css/animate.css">
<link rel="stylesheet" href="assets/css/magnific-popup.css">
<link rel="stylesheet" href="assets/css/odometer-theme-default.css">
<!-- Hook -->
<script>
window.odometerOptions = {
selector: '.odometer',
format: '(,ddd)', //group số, và số chữ số sau digit
duration: 13000, // thời gian đợi của javascript
theme: 'default'
};
</script>
</head>
<body class="">
<!-- Pushy Menu -->
<nav class="pushy pushy-left">
<ul class="list-unstyled">
<?php if (!isset($_SESSION['USER_NAME'])) {
require('pages/viewlogin.php');
} else {
require('pages/viewprofile.php');
} ?>
<li><a href="pages/index.php">Đăng Kí/ Đăng Nhập</a></li>
<li><a href="#news">Chúng tôi là ai</a></li>
<li><a href="#achievement">Những thành tựu</a></li>
<li><a href="#Features">Tính năng của khoá học</a></li>
<li><a href="#review">Học viên nói gì</a></li>
<li><a href="#pricing">Bảng giá</a></li>
<li><a href="#photos">Hình ảnh từ khoá học</a></li>
<li><a href="#newsletter">Đăng kí newsletter</a></li>
<li><a href="#contact">Liên hệ!</a></li>
<li><a href="https://www.youtube.com/watch?v=dFz5E1rZqR4" target="_blank">Buổi học thử</a></li>
</ul>
</nav>
<!-- Site Overlay -->
<div class="site-overlay"></div>
<header id="home">
<div class="container-fluid">
<!-- Thay đổi hình ảnh tại style.css to the class header .container-fluid [approximately row 50] -->
<div class="container">
<div class="row">
<div class="col-xs-2 text-center">
<div class="menu-btn"><span class="hamburger">☰</span></div>
</div>
</div>
<div class="jumbotron">
<h1><small>Nơi khơi nguồn cho đam mê</small>
<strong>Nhiếp ảnh</strong></h1>
<p>Đây là nơi bạn có thể biến những khoảnh khắc thành những bước ảnh đắc giá cho hành trình của bạn.</p>
<p><a class="btn btn-primary btn-lg" role="button">Tìm hiểu thêm</a> <a target="_blank" href="#Features" class="btn btn-lg btn-danger" role="button">Chúng tôi trên Youtube</a></p>
</div>
</div>
</div>
</header>
<section id="news" class="blog wow fadeInUp" data-wow-delay="300ms">
<div class="container">
<div class="row">
<?php
$course_id = -1;
if (isset($_GET["course_id"])) {
$id = intval($_GET['course_id']);
}
$connect = mysqli_connect('localhost', 'root', '', 'insight');
mysqli_set_charset($connect, "UTF8");
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
$sql = "SELECT * FROM COURSE WHERE course_id=$id";
if ($result = mysqli_query($connect, $sql)) {
$row = mysqli_fetch_array($result)
?>
<h4><?php echo $row['name']; ?> - Giảng viên: <?php echo $row['teacher']; ?><h4><hr>
<div class="col-lg-8 col-md-8">
<?php
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?>
<?php
$connect = mysqli_connect('localhost', 'root', '', 'insight');
mysqli_set_charset($connect, "UTF8");
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
$i = 1;
//câu truy vấn
$sql = "SELECT * FROM LESSONS WHERE course_id = $id";
//kiểm tra
if ($result1 = mysqli_query($connect, $sql)) {
$data = mysqli_fetch_array($result1);
?>
<iframe class= "videoarea" id="youtube"
src="https://www.youtube.com/embed/<?php echo $data["video_id"] ?> "
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
<h5 id = "vidtitle">
Bài <?php echo $data["lessons_id"] ?>: <?php echo $data["title"] ?>
</h5>
<p id="description">
<?php echo $data["description"] ?>
</p>
</div>
<div class="col-lg-4 col-md-4">
<div class="playlist" data-spy="scroll" data-target="#myScrollspy" data-offset="10">
<div class = "item">
<a href="javascript:void(0)"
title = "<?php echo $data["title"] ?>"
des = "<?php echo $data["description"] ?>"
idx = "<?php echo $data["lessons_id"] ?>"
data-src="https://www.youtube.com/embed/<?php echo $data["video_id"] ?>"
class="src">
<img src = "https://i.ytimg.com/vi/<?php echo $data["video_id"] ?>/maxresdefault.jpg">
<div class ="title">
Bài <?php echo $data["lessons_id"] ?>: <?php echo $data["title"] ?>
<p class ="des"> <?php echo $data["description"] ?>
</div>
</a>
</div>
<hr>
<?php
while ($data = mysqli_fetch_array($result1)) {
?>
<div class = "item inner">
<a href="javascript:void(0)"
title = "<?php echo $data["title"] ?>"
des = "<?php echo $data["description"] ?>"
idx = "<?php echo $data["lessons_id"] ?>"
data-src="https://www.youtube.com/embed/<?php echo $data["video_id"] ?>"
class="src ">
<img src = "https://i.ytimg.com/vi/<?php echo $data["video_id"] ?>/maxresdefault.jpg">
<div class ="title">
Bài <?php echo $data["lessons_id"] ?>: <?php echo $data["title"] ?>
<p class ="des"> <?php echo $data["description"] ?>
</div>
</a>
</div>
<hr>
<?php
$i++;
}
?>
</div>
</div>
<?php
while ($data = mysqli_fetch_array($result1)) {
?>
<a href="javascript:void(0)"
title = "<?php echo $data["title"] ?>"
data-src="https://www.youtube.com/embed/<?php echo $data["video_id"] ?>"
class="src">
<?php echo $data["title"] ?></a><br>
<?php
$i++;
}
?>
</div>
<?php
} else
echo 'Không thành công. Lỗi' . mysqli_error($connect);
mysqli_close($connect);
?>
</div>
<div class="container">
<div class="row">
<h5>Phần bình luận</h5>
<div class="col-lg-8 col-md-8">
<div class="comment" data-spy="scroll" data-target="#myScrollspy" data-offset="10">
<?php
// include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
myConnect();
// mysqli_select_db("insight");
error_reporting(E_ALL ^ E_NOTICE);
$notify = "";
// $name = $_POST['name'];
$comment = $_POST['comment'];
$submit = $_POST['submit'];
// if (isset($_POST['notify_box'])) {
// $notify = $_POST['notify_box'];
// }
$dbLink = myConnect();
mysqli_query($dbLink, "SET character_set_client=utf8");
mysqli_query($dbLink, "SET character_set_connection=utf8");
if ($submit) {
if ($comment) {
$sql = "INSERT INTO comment (name,comment) VALUES (\"".$_SESSION['USER_NAME']."\",'$comment') ";
$insert = mysqli_query($dbLink, $sql) or die(mysqli_error($dbLink));
} else {
echo "please fill comment";
}
}
$dbLink = mysqli_connect('localhost', 'root', '', 'insight');
mysqli_query($dbLink, "SET character_set_results=utf8");
mb_language('uni');
mb_internal_encoding('UTF-8');
$sql = "SELECT * FROM comment";
$getquery = mysqli_query($dbLink, $sql);
if ($getquery = mysqli_query($dbLink, $sql)) {
while ($row = mysqli_fetch_array($getquery)) {
echo "<div class =\"item\">
<div class =\"username\">
<img style=\"margin: 20px;\" width=\"7%\" src = \"images/user.png\">
<b>" . $row['name'] . "</b>
</div>
" . $row['comment'] . "
</div><hr> ";
}
}
?>
</div>
<br>
</div>
<div class=" col-lg-4 col-md-4 input">
<form action="lessons.php" method="POST">
<input type="text" name="comment" placeholder="Nhập comment" />
<input type="submit" name="submit" value="Gửi" />
</form>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Kết nối qua mạng xã hội</h3>
<p>© 2019 Insight Photography. Được thế kế bởi <NAME> <a target="_blank" href="http://www.facebook.com/NgocHuyTuVEVO">InsightPhotography.com</a></p>
</div>
<div class="col-md-4">
<p class="text-right social"><i class="typcn typcn-social-facebook-circular"></i><i class="typcn typcn-social-twitter-circular"></i><i class="typcn typcn-social-tumbler-circular"></i><i class="typcn typcn-social-github-circular"></i><i class="typcn typcn-social-dribbble-circular"></i></p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/js/bootstrap-scrollspy.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="assets/js/ie10-viewport-bug-workaround.js"></script>
<script src="http://masonry.desandro.com/masonry.pkgd.js"></script>
<script src="assets/js/masonry.js"></script>
<script src="assets/js/pushy.min.js"></script>
<script src="assets/js/jquery.magnific-popup.min.js"></script>
<script src="assets/js/wow.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/odometer.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.src', function() {
var src = $(this).attr('data-src');
var title = $(this).attr('title');
var idx = $(this).attr('idx');
var des = $(this).attr('des');
var caption = "Bài " + idx + ": " + title
$("#youtube").attr('src', src += '?autoplay=1');
$("#vidtitle").html(caption);
$("#description").html(des);
});
});
</script>
</body>
</html><file_sep>/pages/editProfile.php
<?php
ob_start();
session_start();
require "../lib/queries.php";
if (!isset($_SESSION['USER_ID']))
{
echo "<script type='text/javascript'>alert('Bạn phải đăng nhập trước!');</script>";
header("location : ../index.php");
}
?>
<?php
if (isset($_POST["btnEdit"]))
{
$USER_ID = $_SESSION['USER_ID'];
$conn = MyConnect();
# code..
if ($_POST['txtFullName'] != $_SESSION['FULL_NAME'])
{
$FULL_NAME = $_POST['txtFullName'];
$qr = "UPDATE USER SET USER.FULL_NAME = '$FULL_NAME' WHERE USER.USER_ID = '$USER_ID'";
mysqli_query($conn,$qr);
}
if ($_POST['GENDER'] != $_SESSION['GENDER'])
{
$GENDER = $_POST['GENDER'];
$qr = "UPDATE USER SET USER.GENDER = '$GENDER' WHERE USER.USER_ID = '$USER_ID'";
mysqli_query($conn,$qr);
}
if ($_POST['txtEmail'] != $_SESSION['EMAIL'])
{
$EMAIL = $_POST['txtEmail'];
$qr = "UPDATE USER SET USER.EMAIL = '$EMAIL' WHERE USER.USER_ID = '$USER_ID'";
mysqli_query($conn,$qr);
}
if ($_POST['txtPassword'] != "" && $_POST['txtRetypePassword'] != "")
{
if ($_POST['txtPassword'] == $_POST['txtRetypePassword'])
{
$Password = md5($_POST['txtPassword']);
$qr = "UPDATE USER SET USER.Password = '$<PASSWORD>' WHERE USER.USER_ID = '$USER_ID' ";
mysqli_query($conn,$qr);
}
else
{
echo "<script> alert('Mật khẩu không trùng khớp')";
return false;
}
}
unset($_SESSION["PASSWORD"]);
unset($_SESSION["GENDER"]);
unset($_SESSION["EMAIL"]);
unset($_SESSION["FULL_NAME"]);
$qr1 =
"
select * from USER
where USER.USER_ID = '$USER_ID'
";
$result = mysqli_query($conn,$qr1);
$row_user = mysqli_fetch_array($result);
$_SESSION["PASSWORD"] = $row_user['<PASSWORD>'];
$_SESSION["FULL_NAME"] = $row_user['FULL_NAME'];
$_SESSION["EMAIL"] =$row_user['EMAIL'];
$_SESSION["GENDER"] =$row_user['GENDER'];
echo "<script> alert('Cập nhật thông tin thành công');
window.setTimeout(function(){
window.location.href = 'editProfile.php';
}, 3000);
</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Colorlib Templates">
<meta name="author" content="Colorlib">
<meta name="keywords" content="Colorlib Templates">
<!-- Title Page-->
<title>Insight Edit!</title>
<!-- Icons font CSS-->
<link href="vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">
<!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Vendor CSS-->
<link href="vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="vendor/datepicker/daterangepicker.css" rel="stylesheet" media="all">
<!-- Main CSS-->
<link href="css/main.css" rel="stylesheet" media="all">
<!-- Include this for Ajax use-->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
</head>
<body>
<div class="hello" id="hello">
</div>
<div class="page-wrapper bg-gra-02 p-t-130 p-b-100 font-poppins">
<div class="wrapper wrapper--w680">
<div class="card card-4">
<div class="card-body" div="card-body">
<h2 class="title">Chỉnh sửa thông tin!</h2>
<form method="POST">
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Mật khẩu</label>
<input class="input--style-4" type="Password" name="txtRetypePassword">
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Nhập lại mật khẩu</label>
<input class="input--style-4" type="Password" name="txtPassword">
</div>
</div>
</div>
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Giới Tính</label>
<div class="p-t-10">
<label class="radio-container m-r-45">Nam
<input type="radio" <?php if ($_SESSION['GENDER'] == '1' ) echo 'Checked' ?> value="1" name="GENDER">
<span class="checkmark"></span>
</label>
<label class="radio-container">Nữ
<input type="radio" <?php if ($_SESSION['GENDER'] == '0' ) echo 'Checked' ?> value="0" name="GENDER">
<span class="checkmark"></span>
</label>
</div>
</div>
</div>
</div>
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Email</label>
<input class="input--style-4" type="email" name="txtEmail" value="<?php echo $_SESSION['EMAIL'] ?>">
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Tên đầy đủ</label>
<input class="input--style-4" type="text" name="txtFullName" value="<?php echo $_SESSION['FULL_NAME'] ?>">
</div>
</div>
</div>
<div class="p-t-15">
<button id="btnEdit" class="btn btn--radius-2 btn--blue" name="btnEdit" type="submit">Lưu thay đổi</button>
</div>
<br>
<div class="input-group" >
<label class="label" ></label>
<a href="../index.php" type="button" id="txtSignIn" >Trở về trang chủ!</a>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Jquery JS-->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Vendor JS-->
<script src="vendor/select2/select2.min.js"></script>
<script src="vendor/datepicker/moment.min.js"></script>
<script src="vendor/datepicker/daterangepicker.js"></script>
<!-- Main JS-->
<script src="js/global.js"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html><file_sep>/admin/courses/insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
mysqli_set_charset($connect, 'UTF8');
echo $sql = "INSERT INTO course(NAME,TEACHER,THUMB,DESCRIPTION) VALUES('".$_POST["NAME"]."','".md5($_POST["TEACHER"])."' ,'".$_POST["THUMB"]."','".$_POST["DESCRIPTION"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Thêm dữ liệu';
}
?> <file_sep>/insight.sql
-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 09, 2020 at 11:03 PM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 7.2.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `insight`
--
-- --------------------------------------------------------
--
-- Table structure for table `address`
--
CREATE TABLE `address` (
`ID` int(11) NOT NULL,
`value` text
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `address`
--
INSERT INTO `address` (`ID`, `value`) VALUES
(1, '113 LY THUONG KIET');
-- --------------------------------------------------------
--
-- Table structure for table `bundle`
--
CREATE TABLE `bundle` (
`ID` int(11) NOT NULL,
`BUNDLE_NAME` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`BUNDLE_DES` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci,
`BUNDLE_PRICE` varchar(10) CHARACTER SET latin1 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `bundle`
--
INSERT INTO `bundle` (`ID`, `BUNDLE_NAME`, `BUNDLE_DES`, `BUNDLE_PRICE`) VALUES
(1, 'CƠ BẢN', 'Stream các video về nhiếp ảnh cơ bản, các tips mới nhất <br> Tutorial về chỉnh sửa ảnh & challenge hàng tuần', '$0'),
(2, 'CH<NAME>', 'Các video chuyên sâu về nhiếp ảnh <br>Các buổi học offline và truy cập vào kho nội dung trực tuyến có thể tải về', '$150'),
(3, 'NÂNG CAO', 'Đi các chuyến dã ngoại thực hành các kỹ năng đã học<br> Nhận được feedback và hướng dẫn trong suốt khoá học', '$400');
-- --------------------------------------------------------
--
-- Table structure for table `comment`
--
CREATE TABLE `comment` (
`name` text NOT NULL,
`comment` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `comment`
--
INSERT INTO `comment` (`name`, `comment`) VALUES
('k', 'k'),
('a ', 'a'),
('b', 'b');
-- --------------------------------------------------------
--
-- Table structure for table `course`
--
CREATE TABLE `course` (
`course_id` int(10) NOT NULL,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`teacher` text COLLATE utf8_unicode_ci NOT NULL,
`thumb` text COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `course`
--
INSERT INTO `course` (`course_id`, `name`, `teacher`, `thumb`, `description`) VALUES
(1, 'CHO NGƯỜI MỚI BẮT ĐẦU', 'Nguyễn Văn A', 'https://eus-www.sway-cdn.com/s/5qXqnkeuHtzDFomD/images/cJ0CtSFtqsGN-Y?quality=480&allowAnimation=true&embeddedHost=true', 'Description'),
(2, '<NAME>', '<NAME>', 'https://phongvu.vn/cong-nghe/wp-content/uploads/2019/09/may-co-demifilm.png', 'Description'),
(3, 'CÁC TIPS KHI HỌC NHIẾP ẢNH', '<NAME>', 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSva5Lqr2haWdl4YfnXGWDa4ucgbHW1puybSQ&usqp=CAU', 'Description');
-- --------------------------------------------------------
--
-- Table structure for table `email`
--
CREATE TABLE `email` (
`ID` int(11) NOT NULL,
`value` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `email`
--
INSERT INTO `email` (`ID`, `value`) VALUES
(1, '<EMAIL>');
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE `images` (
`ID` int(11) NOT NULL,
`url` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `images`
--
INSERT INTO `images` (`ID`, `url`) VALUES
(1, 'https://unsplash.it/600/300?image=529'),
(2, 'https://unsplash.it/600/300?image=523'),
(3, 'https://unsplash.it/600/300?image=503'),
(4, 'https://unsplash.it/600/300?image=505'),
(5, 'https://unsplash.it/600/300?image=454'),
(6, 'https://unsplash.it/600/300?image=515'),
(7, 'https://unsplash.it/600/300?image=451'),
(8, 'https://unsplash.it/600/300?image=524'),
(9, 'https://unsplash.it/600/300?image=526');
-- --------------------------------------------------------
--
-- Table structure for table `lessons`
--
CREATE TABLE `lessons` (
`lessons_id` int(11) NOT NULL,
`course_id` int(11) NOT NULL,
`video_id` text COLLATE utf8_unicode_ci NOT NULL,
`title` text COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `lessons`
--
INSERT INTO `lessons` (`lessons_id`, `course_id`, `video_id`, `title`, `description`) VALUES
(1, 1, 'uleakGTkIoA', 'Nhiếp ảnh là gì? Học nhiếp ảnh?', 'Description bài 1'),
(2, 1, 'TBq9jfRP0sM\r\n', 'Chọn máy ảnh', 'Description bài 2'),
(3, 1, 'tAaUbRt6jqM', 'Title', 'Description bài 3'),
(4, 1, '2VjHjA0GlbM', 'Title4', 'Description bài 4');
-- --------------------------------------------------------
--
-- Table structure for table `phone`
--
CREATE TABLE `phone` (
`ID` int(11) NOT NULL,
`value` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `phone`
--
INSERT INTO `phone` (`ID`, `value`) VALUES
(1, '01234534325');
-- --------------------------------------------------------
--
-- Table structure for table `resetpassword`
--
CREATE TABLE `resetpassword` (
`id` int(11) NOT NULL,
`code` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `schedule`
--
CREATE TABLE `schedule` (
`SCHEDULE_ID` int(11) NOT NULL,
`SCHEDULE_INFO` varchar(200) NOT NULL,
`SCHEDULE_GADGETS` varchar(50) NOT NULL,
`SCHEDULE_DATE` date NOT NULL,
`SCHEDULE_AREA` varchar(20) NOT NULL,
`SCHEDULE_FREE` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `schedule`
--
INSERT INTO `schedule` (`SCHEDULE_ID`, `SCHEDULE_INFO`, `SCHEDULE_GADGETS`, `SCHEDULE_DATE`, `SCHEDULE_AREA`, `SCHEDULE_FREE`) VALUES
(1, 'Cac thao tac cam may co ban', 'Camera', '2020-07-13', 'CS1', 1),
(2, 'Chinh sua hinh anh', 'Laptop, Dien Thoai', '2020-07-23', 'CS2', 0);
INSERT INTO `schedule` (`SCHEDULE_ID`, `SCHEDULE_INFO`, `SCHEDULE_GADGETS`, `SCHEDULE_DATE`, `SCHEDULE_AREA`, `SCHEDULE_FREE`) VALUES (NULL, 'Góc chụp và hệ thống lưới 3x3', 'Điện thoại/ Camera', '2020-08-05', 'LiveStream Youtube', '1'), (NULL, 'Sử dụng Adobe Photoshop và Lightroom để chỉnh màu sắc', 'Máy tính, App', '2020-08-12', 'Cơ sở 2', '1');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`USER_ID` int(11) NOT NULL,
`USER_NAME` varchar(30) NOT NULL,
`PASSWORD` varchar(60) NOT NULL,
`GENDER` tinyint(1) NOT NULL,
`EMAIL` varchar(60) NOT NULL,
`FULL_NAME` varchar(60) CHARACTER SET utf8 NOT NULL,
`TRIAL_DATE` date NOT NULL DEFAULT '0000-00-00',
`IDGROUP` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`USER_ID`, `USER_NAME`, `PASSWORD`, `GENDER`, `EMAIL`, `FULL_NAME`, `TRIAL_DATE`, `IDGROUP`) VALUES
(4, 'admin', 'e10adc3949ba59abbe56e057f20f883e', 1, '<EMAIL>', 'T? <NAME>', '2020-07-09', 1),
(5, 'Trantran', 'e10adc3949ba59abbe56e057f20f883e', 1, '<EMAIL>', '<NAME>', '2020-07-09', 5);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `address`
--
ALTER TABLE `address`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `bundle`
--
ALTER TABLE `bundle`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `course`
--
ALTER TABLE `course`
ADD PRIMARY KEY (`course_id`);
--
-- Indexes for table `email`
--
ALTER TABLE `email`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `phone`
--
ALTER TABLE `phone`
ADD PRIMARY KEY (`ID`);
--
-- Indexes for table `schedule`
--
ALTER TABLE `schedule`
ADD PRIMARY KEY (`SCHEDULE_ID`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`USER_ID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `address`
--
ALTER TABLE `address`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `bundle`
--
ALTER TABLE `bundle`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `course`
--
ALTER TABLE `course`
MODIFY `course_id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `email`
--
ALTER TABLE `email`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `phone`
--
ALTER TABLE `phone`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `schedule`
--
ALTER TABLE `schedule`
MODIFY `SCHEDULE_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `USER_ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
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>/comment.php
<?php
// include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
require "lib/queries.php";
myConnect();
// mysqli_select_db("insight");
error_reporting(E_ALL ^ E_NOTICE);
$notify = "";
$name = $_POST['name'];
$comment = $_POST['comment'];
$submit = $_POST['submit'];
if (isset($_POST['notify_box'])) {
$notify = $_POST['notify_box'];
}
$dbLink = myConnect();
mysqli_query($dbLink, "SET character_set_client=utf8");
mysqli_query($dbLink, "SET character_set_connection=utf8");
if ($submit) {
if ($name && $comment) {
$insert = mysqli_query($dbLink, "INSERT INTO comment (name,comment) VALUES ('$name','$comment') ");
echo "INSERT INTO comment (name,comment) VALUES ('$name','$comment') ";
echo "submit roi ne :'(";
} else {
echo "please fill out all fields";
}
}
$dbLink = myConnect();;
mysqli_query($dbLink, "SET character_set_results=utf8");
mb_language('uni');
mb_internal_encoding('UTF-8');
$sql = "SELECT * FROM comment";
echo $sql;
$getquery = mysqli_query($dbLink, $sql);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Comment box</title>
<style type="text/css">
body {
margin: auto 48px;
}
</style>
</head>
<body>
<div>
<table id="commentTable">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead>
<tr>
<th>Name</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
<?php
if ($getquery = mysqli_query($dbLink, $sql)) {
while ($row = mysqli_fetch_array($getquery)) {
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['comment'] . '</td>';
}
}
?>
</tbody>
</table>
</div>
<form action="comment.php" method="POST">
<colgroup>
<col widht="25%" style="vertical-align:top;" />
<col widht="75%" style="vertical-align:top;" />
</colgroup>
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td><label for="comment">Comment:</label></td>
<td><textarea name="comment" rows="10" cols="50"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Comment"></td>
</tr>
</table>
</form>
</body>
</html><file_sep>/pages/backup/login.php
<?php
echo "<script type='text/javascript'>alert('Stop Watering Successfully');</script>";
?>
<h2 class="title">Form Đăng Nhập!</h2>
<form method="POST">
<div class="row row-space">
</div>
<div class="row row-space">
</div>
<div class="input-group">
<div class="input-group">
<label class="label">Username</label>
<input class="input--style-4" type="text" name="txtUsername">
</div>
</div>
<div class="input-group">
<div class="input-group">
<label class="label">Password</label>
<input class="input--style-4" type="<PASSWORD>" name="txt<PASSWORD>">
</div>
</div>
<div class="p-t-15">
<button class="btn btn--radius-2 btn--blue" type="submit">Đăng Nhập</button>
</div>
</form>
<file_sep>/pages/viewprice.php
<?php
$connect = myConnect();
//Kiểm tra kết nối
if (!$connect) {
die('kết nối không thành công ' . mysqli_connect_error());
}
//khởi tạo biến $i để đếm;
$i = 1;
//câu truy vấn
$sql = "SELECT * FROM BUNDLE";
// var_dump($sql);
//kiểm tra
if ($result = mysqli_query($connect, $sql)) {
// var_dump($result);
while ($row = mysqli_fetch_array($result)) {
// var_dump($row);
//hiển thị dữ liệu
// echo 'Dữ liệu thứ ' . $i . ' gồm: ' . $row['id'] . '-' . $row['title'] . '-' . $row['content'] . '<br/>';
echo '<div class="pricing-plan">
<img src="https://s22.postimg.cc/8mv5gn7w1/paper-plane.png" alt="" class="pricing-img">
<h2 class="pricing-header">'.$row['BUNDLE_NAME'].'</h2>
<p>'.$row['BUNDLE_DES'].'<p>
<span class="pricing-price">'.$row['BUNDLE_PRICE'].'</span>';
if ($row['ID']==1)
{
echo "<a href='Trial2.php?coban=true' class='pricing-button'>Dùng thử</a>
</div>";
}
else if ($row['ID']==2)
{
echo "<a href='Trial2.php?chuyennghiep=true' class='pricing-button'>Dùng thử</a>
</div>";
}
else if($row['ID']==3)
{
echo "<a href='Trial2.php?nangcao=true' class='pricing-button'>Dùng thử</a>
</div>";
}
// echo '<a href="#/" class="pricing-button">Đăng kí</a>
// </div>';
//tăng $i lên 1
$i++;
}
} else
//Hiện thông báo khi không thành công
echo 'Không thành công. Lỗi' . mysqli_error($connect);
//ngắt kết nối
mysqli_close($connect);
?><file_sep>/admin/courses/delete.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
mysqli_set_charset($connect, 'UTF8');
$sql = "DELETE FROM course WHERE course.course_id = '".$_POST["course_id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Xoá dữ liệu';
}
?><file_sep>/admin/users/select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
$output = '';
$sql = "SELECT * FROM user ORDER BY USER_ID";
$result = mysqli_query($connect, $sql);
mysqli_set_charset($connect, 'UTF8');
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="15%">Username</th>
<th width="15%">Email</th>
<th width="15%">Họ Tên</th>
<th width="15%">TRIAL DATE</th>
<th width="5%">idGroup</th>
<th width="20%">Password</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["USER_ID"].'</td>
<td class="USER_NAME" data-id1="'.$row["USER_ID"].'" contenteditable>'.$row["USER_NAME"].'</td>
<td class="EMAIL" data-id2="'.$row["USER_ID"].'" contenteditable>'.$row["EMAIL"].'</td>
<td class="FULL_NAME" data-id3="'.$row["USER_ID"].'" contenteditable>'.$row["FULL_NAME"].'</td>
<td class="TRIAL_DATE" data-id4="'.$row["USER_ID"].'" contenteditable>'.$row["TRIAL_DATE"].'</td>
<td class="IDGROUP" data-id5="'.$row["USER_ID"].'" contenteditable>'.$row["IDGROUP"].'</td>
<td class="PASSWORD" data-id6="'.$row["USER_ID"].'" contenteditable>'.$row["PASSWORD"].'</td>
<td><button type="button" name="delete_btn" data-id7="'.$row["USER_ID"].'" class="btn btn-xs btn-danger btn_delete">Delete</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="USER_NAME" contenteditable></td>
<td id="EMAIL" contenteditable></td>
<td id="FULL_NAME" contenteditable></td>
<td id="TRIAL_DATE" contenteditable></td>
<td id="IDGROUP" contenteditable></td>
<td id="PASSWORD" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td></td>
<td id="USER_NAME" contenteditable></td>
<td id="EMAIL" contenteditable></td>
<td id="FULL_NAME" contenteditable></td>
<td id="TRIAL_DATE" contenteditable></td>
<td id="IDGROUP" contenteditable></td>
<td id="PASSWORD" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr> ';
}
$output .= '</table>
</div>';
echo $output;
?><file_sep>/Trial2.php
<?php
ob_start();
session_start();
require "lib/queries.php";
$conn = myConnect();
$date = date("Y-m-d");
// var_dump($date);
// $qr = "UPDATE `user` SET `TRIAL_DATE`="$date,`IDGROUP`=[value-8] WHERE `USER_ID`=[value-1]";
// $qr = "
// INSERT INTO USER VALUES
// (null,'$username','$password','$gender','$email' ,'$fullname', '$date' ,'$idgroup')
// ";
// echo($qr);
// mysqli_query($conn,$qr);
$user = $_SESSION["USER_NAME"];
$pass = $_SESSION["PASSWORD"];
// echo($user);
// echo($pass);
if (isset($_GET["coban"])) {
if($user == "" or $pass ==""){
header("location:pages/index.php?");
}
else{
echo "<script>
alert('Bạn đã đăng nhập!');
window.location.href='index.php';
</script>";
}
}
else {
// echo"hi";
$qr1 =
"
SELECT * from USER
WHERE USER.USER_NAME = '$user'
";
// var_dump($qr1);
$result = mysqli_query($conn, $qr1);
$row_user = mysqli_fetch_array($result);
// var_dump($row_user);
if ($user == $row_user['USER_NAME'] && ($pass) == $row_user['PASSWORD'])
// if ($user == $row_user['USER_NAME'] && md5($pass) == $row_user['PASSWORD'])
{
$_SESSION["IDGROUP"] = $row_user['IDGROUP'];
$_SESSION["USER_ID"] = $row_user['USER_ID'];
$_SESSION["TRIAL_DATE"] = $row_user['TRIAL_DATE'];
$user_id = $row_user['USER_ID'];
// var_dump($user_id);
if ($_SESSION["IDGROUP"] == 1 or $_SESSION["IDGROUP"] == 2) {
$time = date('Y-m-d', strtotime($_SESSION["TRIAL_DATE"] . ' + 1 month'));
// var_dump(date('Y-m-d'));
// var_dump($date);
// var_dump($time);
//$time là trial
if ($date > $time) {
$qr1 = "
UPDATE user SET USER.IDGROUP=0 WHERE USER.USER_ID = $user_id
";
echo $qr1;
$_SESSION["IDGROUP"] = 0;
$result = mysqli_query($conn, $qr1);
echo "<script type='text/javascript'>alert('Dùng thử đã hết hạn!');</script>";
}
else{
echo "<script type='text/javascript'>alert('Chưa hết hạn dùng thử!');
window.location.href='index.php';</script>";
}
} else if ($_SESSION["IDGROUP"] == 0 && $_SESSION["TRIAL_DATE"] == "0000-00-00") {
if (isset($_GET["chuyennghiep"]) or ($_SESSION["IDGROUP"] ==2)) {
$qr1 = "
UPDATE user SET user.IDGROUP = 2 WHERE user.USER_ID = $user_id;
";
$qr11 = "
UPDATE user SET user.TRIAL_DATE= '$date' WHERE user.USER_ID = $user_id;
";
$_SESSION["IDGROUP"] = 2;
$result = mysqli_query($conn, $qr1);
$result = mysqli_query($conn, $qr11);
// var_dump($result);
// echo $qr1;
echo "<script type='text/javascript'>alert('Bắt đầu dùng thử gói chuyên nghiệp');
window.location.href='index.php';</script>";
} else if (isset($_GET["nangcao"]) or ($_SESSION["IDGROUP"] == 1)) {
$qr1 = "
UPDATE USER SET USER.IDGROUP=1 WHERE USER.USER_ID = $user_id;
UPDATE USER SET USER.TRIAL_DATE= '$date' WHERE USER.USER_ID = $user_id;
";
echo $qr1;
$_SESSION["IDGROUP"] = 1;
$result = mysqli_query($conn, $qr1);
echo "<script type='text/javascript'>alert('Bắt đầu dùng thử gói nâng cao');
window.location.href='index.php';</script>";
}
} else if ($_SESSION["IDGROUP"] == 0) {
echo "<script type='text/javascript'>alert('Mỗi tài khoản chỉ có một phiên dùng thử');
window.location.href='index.php';</script>";
}
else if ($_SESSION["IDGROUP"] == 1){
}
}
}
<file_sep>/admin/lessons/select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
mysqli_set_charset($connect, 'UTF8');
$output = '';
$sql = "SELECT * FROM lessons ORDER BY lessons_id";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">LESSONS_ID</th>
<th width="20%">COURSE_ID</th>
<th width="40%">VIDEO</th>
<th width="20%">TITLE</th>
<th width="10%">Delete</th>
</tr>';
// var_dump($sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["lessons_id"].'</td>
<td class="course_id" data-id1="'.$row["lessons_id"].'" contenteditable>'.$row["course_id"].'</td>
<td class="video" data-id2="'.$row["lessons_id"].'" contenteditable>'.$row["video_id"].'</td>
<td class="title" data-id3="'.$row["lessons_id"].'" contenteditable>'.$row["title"].'</td>
<td><button type="button" name="delete_btn" data-id7="'.$row["lessons_id"].'" class="btn btn-xs btn-danger btn_delete">Delete</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="course_id" contenteditable></td>
<td id="video" contenteditable></td>
<td id="title" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td></td>
<td id="course_id" contenteditable></td>
<td id="video" contenteditable></td>
<td id="title" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">Add</button></td>
</tr> ';
}
$output .= '</table>
</div>';
echo $output;
?><file_sep>/admin/users/edit.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
$USER_ID = $_POST["USER_ID"];
$text = $_POST["text"];
$column_name = $_POST["column_name"];
if ($column_name == "PASSWORD")
{
$text = md5($text);
}
$sql = "UPDATE user SET ".$column_name."='".$text."' WHERE USER_ID='".$USER_ID."'";
if(mysqli_query($connect, $sql))
{
echo 'Update dữ liệu';
}
?><file_sep>/admin/schedule/insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
echo $sql = "INSERT INTO SCHEDULE(SCHEDULE_INFO,SCHEDULE_GADGETS,SCHEDULE_DATE,SCHEDULE_AREA,SCHEDULE_FREE) VALUES('".$_POST["SCHEDULE_INFO"]."','".$_POST["SCHEDULE_GADGETS"]."','".$_POST["SCHEDULE_DATE"]."','".$_POST["SCHEDULE_AREA"]."','".$_POST["SCHEDULE_FREE"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Thêm dữ liệu';
}
?> <file_sep>/admin/lessons/insert.php
<?php
$connect = mysqli_connect("localhost", "root", "", "insight");
mysqli_set_charset($connect, 'UTF8');
echo $sql = "INSERT INTO lessons(course_id,video,title) VALUES('".$_POST["course_id"]."','".$_POST["video"]."','".$_POST["title"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Thêm dữ liệu';
}
?> <file_sep>/admin/index.php
<?php
//Chuyển hướng k bị lỗi
// ob_start();
// session_start();
// echo $_SESSION["idGroup"];
// if(!isset($_SESSION["idUser"]) || $_SESSION["idGroup"] != 1){
// header("location:../index.php");
// }
//ket noi csdl
// require "../lib/dbCon.php";
// require "../lib/quantri.php";
require "lib/dbCon.php";
// require "lib/trangchu.php";
$conn = MyConnect();
ob_start();
session_start();
?>
<?php
if(isset($_POST["btnSignout"]))
{
unset($_SESSION["USER_ID"]);
unset($_SESSION["USER_NAME"]);
unset($_SESSION["PASSWORD"]);
unset($_SESSION["FULL_NAME"]);
unset($_SESSION["TRIAL_DATE"]);
unset($_SESSION["EMAIL"]);
unset($_SESSION["IDGROUP"]);
header("location:../pages/index.php");
}
//header("Location:index.php")
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="description" content="" />
<meta name="author" content="" />
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<title>ADMIN</title>
<!-- BOOTSTRAP CORE STYLE -->
<link href="assets/css/bootstrap.css" rel="stylesheet" />
<!-- FONT AWESOME STYLE -->
<link href="assets/css/font-awesome.css" rel="stylesheet" />
<!-- CUSTOM STYLE -->
<link href="assets/css/style.css" rel="stylesheet" />
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
<!-- GOOGLE FONT -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<style>
.cont {
/*border: 1px solid black;*/
/*background-color: lightblue;*/
padding-top: 200px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
font-size: 25px;
}
</style>
<body>
<div class="navbar navbar-inverse set-radius-zero" >
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="">
TRANG QUẢN TRỊ
</a>
<div class="text-danger">Xin chào <?php echo $_SESSION["FULL_NAME"] ?></div>
</div>
<div class="right-div">
<form method="post">
<button class="btn btn-primary" name="btnSignout">
LOG ME OUT
</button>
</form>
</div>
</div>
</div>
<!-- LOGO HEADER END-->
<section class="menu-section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="navbar-collapse collapse ">
<ul id="menu-top" class="nav navbar-nav navbar-right">
<li><a href="" >TRANG CHỦ</a></li>
<li><a href="quanLyThanhVien.php">QUẢN LÝ THÀNH VIÊN</a></li>
<li><a href="quanLyKhoaHoc.php" >QUẢN LÝ KHÓA HỌC </a></li>
<li><a href="quanLyBaiHoc.php" >QUẢN LÝ BÀI HỌC </a></li>
<li><a href="newsletter.php">NEWSLETTER</a></li>
<li><a href="quanLyLichTrinh.php" >QUẢN LÝ LỊCH HỌC </a></li>
<!-- <li><a href="./listQuangCao.php">QUẢN lÝ QUẢNG CÁO</a></li> -->
</ul>
</div>
</div>
</div>
</div>
</section>
<!-- MENU SECTION END-->
<div class="container-fluid">
<div class="row">
<div class="col-md-5 cont">WELCOME ADMINISTRATOR</div>
<div class="col-md-7">
<img src="admin.png">
</div>
</div>
</div>
</div>
<!-- CONTENT-WRAPPER SECTION END-->
<section class="footer-section">
<div class="container">
<div class="row">
<div class="col-md-12">
© INSIGHT | 2019-2020
</div>
</div>
</div>
</section>
<!-- FOOTER SECTION END-->
<!-- JAVASCRIPT FILES PLACED AT THE BOTTOM TO REDUCE THE LOADING TIME -->
<!-- CORE JQUERY -->
<!-- <script src="assets/js/jquery-1.10.2.js"></script> -->
<!-- BOOTSTRAP SCRIPTS -->
<!-- <script src="assets/js/bootstrap.js"></script> -->
<!-- CUSTOM SCRIPTS -->
<!-- <script src="assets/js/custom.js"></script> -->
</body>
</html>
| cf363db84b50671554f23c1839bc52d407dc5e7d | [
"SQL",
"PHP"
] | 24 | PHP | avatarwefa/Insight_Photography | 5cee178a2774d56380c24905ef96c753350c91af | 4b5371c870e6cbec6c4b25e955278514563441f3 |
refs/heads/master | <repo_name>owdelc/ECO<file_sep>/Proyecto 2.0/Contador_Oxigeno.java
import java.text.DecimalFormat;
public class Contador_Oxigeno{
DecimalFormat df = new DecimalFormat("#.000000");
public String Contador(int anos_trascurridos){
double disminucion_oxigeno = 0.7;
int anos = anos_trascurridos - 2000;
double porcentaje = anos * 0.00000088;
disminucion_oxigeno = disminucion_oxigeno + porcentaje;
return "Para el agno " + anos_trascurridos + " habra disminuido " + df.format(disminucion_oxigeno) + "%.";
}
public void Informacion_oxigeno(){
System.out.println("Según estudios realizados recientemente, los cientificos han descubierto que en los últimos 800,000 agnos los niveles de oxigeno han decaido un 0.7% y no se sabe cual es la causa de esto");
System.out.println("Hay diferentes hipótesis que tratan de explicar esto. Una de ellas (la más apoyada) dice que es debido al cambio climático");
}
public void Aportacion_arboles(int cant_arboles){
int arboles = cant_arboles;
System.out.println("Se necesitan aproximadamente 22 arboles para suplir la demanda de oxigeno de una persona");
if (arboles >= 22){
System.out.println("Excelente! Estas contribuyendo mucho al planeta");
} else if (arboles == 0) {
System.out.println("Todavia no has contribuido. Apoya al planeta y empieza a sembrar!");
} else {
System.out.println("Estas contribuyendo! Sigue sembrando");
}
}
}
/* ********************************
Referencias:
1. Zahumenszki, Carlos(2016). "La atmosfera de la Tierra esta perdiendo oxigeno"
https://es.gizmodo.com/la-atmosfera-de-la-tierra-esta-perdiendo-oxigeno-y-los-1786971190
2. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>:
A Pleistocene ice core record of atmospheric O2 concentrations. Science (2016).
*/<file_sep>/Proyecto 2.0/Controlador.java
public class Controlador{
Contador_Oxigeno contador_oxigeno = new Contador_Oxigeno();
Contacto contacto = new Contacto();
Tips tips = new Tips();
Donacion donacion = new Donacion();
Simulador simulador = new Simulador();
public String I_Contacto(int x){
String p = " ";
if (x == 1){
p=contacto.I_AmigosLagoAmatitlan();
} else if(x == 2){
p=contacto.I_DefensoresNaturaleza();
} else if(x == 3){
p=contacto.I_Guateambiente();
} else if(x == 4){
p=contacto.I_Fundaeco();
}
return p;
}
public void paginas_contacto(int x){
if (x==1){
contacto.pagina_AmigosLagoAmatitlan();
} else if(x==2){
contacto.pagina_DefensoresNaturaleza();
} else if(x==3){
contacto.pagina_Guateambiente();
} else if(x==4){
contacto.pagina_Fundaeco();
}
}
public String disminucion_oxigeno(int x){
return contador_oxigeno.Contador(x);
}
public void info_oxigeno(){
contador_oxigeno.Informacion_oxigeno();
}
public void aportacion_oxigeno(int x){
contador_oxigeno.Aportacion_arboles(x);
}
public void Tips(){
tips.Introduccion();
}
public void Paypal(){
donacion.redirigir();
}
public void Simulador(){
simulador.ejecutar_Simulador();
}
}<file_sep>/Proyecto 2.0/Donacion.java
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Donacion{
public void redirigir(){
if(java.awt.Desktop.isDesktopSupported()){
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
if(desktop.isSupported(java.awt.Desktop.Action.BROWSE)){
try{
java.net.URI uri= new java.net.URI("https://www.paypal.com/gt/home");
desktop.browse(uri);
} catch(URISyntaxException | IOException ex){}
}
}
}
} | 861975481b66c9e7ebf5925624ee37bae9c8e345 | [
"Java"
] | 3 | Java | owdelc/ECO | aa16895571a34c507987b3db6058f85e78e10b21 | c90b26fe6ec4d6fe053cfd93ad09b8640c1501e2 |
refs/heads/master | <file_sep># 'hello, {name}!'と出力してください 。
def hello(name):
print('hello, John!')
pass
# sentence の文字数を出力してください
def length(sentence):
s = sentence
print(len(s))
pass
# sentence の2文字目から5文字目まで(5文字目は含まない)を出力してください
def slicing2to5(sentence):
print(sentence[2:5])
pass
# number の符号を出力してください。ただし、0は'0'と出力してください
def number_sign(number):
if number < 0:
print("-")
elif number == 0:
print("'0'")
else:
print("+")
pass
# number が素数なら'ok',そうでないなら'ng'と出力してください
def prime_number(number):
counter = 0
primes = []
for n in range(2, 1001):
prime = True
for i in range(2, n):
counter += 1
if n % i == 0:
prime = False
break
if prime:
primes.append(n)
print(primes, len(primes))
print(u'除算を行った回数:%d' % counter)
pass
# 1からnumberまでの合計を出力してください
def sum_from_1_to(number):
ans = 0
for i in range(number+1):
ans += i
return ans
pass
# numberの階乗(factorial)を出力してください
def factorial(number):
if number == 0:
return 1
return number * factorial(number-1)
pass
# リストdataの各要素(整数)を3乗した結果をリスト型として返してください
def cubic_list(data):
data = ([1, 2, 3, 4, 5])
cubic_list = [x**3 for x in range(1, 5)]
pass
# 底辺x,高さyの直角三角形(right angled triangle)の残り1つの辺の長さを返してください
def calc_hypotenuse(x, y):
print(x ** 2 + y ** 2)
pass
# 底辺x,斜辺vの直角三角形の残り1つの辺の長さを返してください
def calc_subtense(x, v):
print(x ** 2 - v ** 2)
pass
# 三辺の長さがそれぞれx,y,zの三角形の面積を返してください
def calc_area_triangle(x, y, z):
print(x * y / 2)
pass
# 引数a,b,cを小数点以下2桁表示で空白切りで表示してください
def point_two_digits(a, b, c):
print("{0:.2f}' '".format(a, b, c))
pass
# リストdataの内容を小さい順でソートした結果を返してください
def list_sort(data):
print(data.sort())
pass
# 文字列の並びを逆にしたものを返してください
def reverse_string(sentence):
print(sentence[::-1])
pass
# dateから2016年4月1日までの日数を返してください
from datetime import date
def days_from_date(point):
a = date(2016, 4, 1)
print('days_from_date - a')
pass
<file_sep># 課題2016
クリックするとゲームが始まります。
ブロックを作って、ボールが当たるとブロックが消えるようにしました。
スピードも変化します。
| 8e6500d33ae4dbda667e60d27a780fa0490b95c5 | [
"Markdown",
"Python"
] | 2 | Python | n16009/exam201602 | 64ffbeb988cd4e96a8e4f5403e4de2de43ebcf06 | acd9388ad2032aa1eabd15d9ef006699965f1c75 |
refs/heads/master | <repo_name>Timbinous/calcinator<file_sep>/spec/lib/calculator_spec.rb
require 'rails_helper'
describe Calculator do
describe "#calculate" do
context "multiplying" do
it 'multiplies 2 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\*[\d]+)/, '*', '10*10+5')).to eq('100.0+5')
end
it 'multiplies 3 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\*[\d]+)/, '*', '10*10+5*10')).to eq('100.0+50.0')
end
end
context "dividing" do
it 'divides 2 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\/[\d]+)/, '/', '10/10+5')).to eq('1.0+5')
end
it 'divides 3 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\/[\d]+)/, '/', '10/10+20/10')).to eq('1.0+2.0')
end
end
context "adding" do
it 'adds 2 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\+[\d]+)/, '+', '10/10+20/10')).to eq('10/30.0/10')
end
it 'adds 3 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\+[\d]+)/, '+', '10+10/20+10')).to eq('20.0/30.0')
end
end
context "subtracting" do
it 'subtracts 2 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\-[\d]+)/, '-', '10/20-10/10')).to eq('10/10.0/10')
end
it 'subtracts 3 numbers and injects the result into the string' do
expect(Calculator.loop_calculation_string(/([\d]+\-[\d]+)/, '-', '10-10/20-10')).to eq('0.0/10.0')
end
end
context "using calculate" do
it 'uses the correct order of operations to get the right answer' do
expect(Calculator.calculate('10*10/2+5*10')).to eq(100)
end
end
context "code exercise examples" do
it 'calculates the first example correctly' do
expect(Calculator.calculate('5*3+1+6/2+9*100')).to eq(919)
end
it 'calculates the second example correctly' do
expect(Calculator.calculate('5*3+1+6/85+9*100')).to eq(916.07)
end
end
end
end
<file_sep>/app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
def index
end
def calculate
@original_question = params[:calculating_string].dup
@result = Calculator.calculate(params[:calculating_string])
end
end
<file_sep>/app/lib/calculator.rb
class Calculator
class << self
def calculate(calculation_string)
calculation_string.gsub!(/\s+/, '')
loop_calculation_string(/([\d\.]+\*[\d\.]+)/, '*', calculation_string)
loop_calculation_string(/([\d\.]+\/[\d\.]+)/, '/', calculation_string)
loop_calculation_string(/([\d\.]+\+[\d\.]+)/, '+', calculation_string)
loop_calculation_string(/([\d\.]+\-[\d\.]+)/, '-', calculation_string)
if calculation_string.to_i == calculation_string.to_f
calculation_string.to_i
else
calculation_string.to_f.round(2)
end
end
def loop_calculation_string(regex, operator, calculation_string)
loop do
break if calculation_string.exclude?(operator)
calc = calculate_operator(operator, calculation_string.match(regex))
calculation_string.sub!(regex, calc)
end
calculation_string
end
def calculate_operator(operator, match)
match.to_s.split(operator).map(&:to_f).inject(&operator.to_sym).to_s
end
end
end
| 22983cab08d9c60efcbce687abaa2db7d7b5d584 | [
"Ruby"
] | 3 | Ruby | Timbinous/calcinator | 7baaf039425b42c92514d800a3727f18c081586d | e0acdd6cb51756cb963f34f6df6080390a12a213 |
refs/heads/master | <repo_name>cherryfletcher/ProgrammingAssignment2<file_sep>/cachematrix.R
## The following functions cache the inverse of a matrix
## makeCacheMatrix creates a special matrix that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
s<- NULL
set<- function(y) {
x<<- y
s<<- NULL
}
get<- function() x
setSolve<- function(solve) s<<-solve
getSolve<- function() s
list(set = set, get = get, setSolve = setSolve, getSolve = getSolve)
}
## cacheSolve computes the inverse of the special matrix.
## If the inverse has already been calculated, the inverse is retrieved from the cache
cacheSolve <- function(x, ...) {
s<- x$getSolve()
if(!is.null(s)) {
message("getting cached data")
return(s)
}
data<- x$get()
s<- solve(data, ...)
x$setSolve(s)
s
}
| d62c2cf15843709c2c322df5784588badd4e0f19 | [
"R"
] | 1 | R | cherryfletcher/ProgrammingAssignment2 | 51503b9c57efa79a61047df5025d7629d7851d67 | fb9f4242b2b6220256dc2ffec06972766a4fcdad |
refs/heads/master | <file_sep>const moonPath="M26 54C26 83.8234 54 108 54 108C24.1766 108 0 83.8234 0 54C0 24.1766 24.1766 0 54 0C54 0 26 24.1766 26 54Z";
const sunPath="M108 54C108 83.8234 83.8234 108 54 108C24.1766 108 0 83.8234 0 54C0 24.1766 24.1766 0 54 0C83.8234 0 108 24.1766 108 54Z";
const darkMode=document.querySelector('#darkMode');
let toggle=false;
darkMode.addEventListener('click', ()=>{
//anime.js
const timeline=anime.timeline({
duration: 750,
easing: "easeOutExpo"
});
timeline.add({
targets: ".sun",
d:[
toggle ? {value:sunPath}:{value: moonPath}
]
})
.add({
targets: "#darkMode",
rotate: 320
}, '-= 350')
.add({
targets: "section",
backgroundColor: toggle ? 'rgb(20, 197, 228)':'rgb(22,22,22)',
color: toggle ? 'rgb(22,22,22)':'rgb(20, 197, 228)'
}, '-=700');
//toggle
if(!toggle){
toggle=true;
}else {
toggle=false;
}
})<file_sep># DarkMode-Animation
Dark Mode Animation for websites

| 13f1fa79d89467b0716e79fbdf34218a87abb5a7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Cindy1229/DarkMode-Animation | 7d034112aed9d536a9501d1fcd02fadb55452547 | 288e8ce029deadb4b089781e226fd97d6d7a535c |
refs/heads/master | <file_sep>package com.yash.aws.dynamodb.repository;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue;
import com.yash.aws.dynamodb.model.Student;
@Repository
public class DynamoDbRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamoDbRepository.class);
@Autowired
private DynamoDBMapper mapper;
public void insertIntoDynamoDB(Student student) {
mapper.save(student);
}
public Student getOneStudentDetails(String studentId, String lastName) {
return mapper.load(Student.class, studentId, lastName);
}
public void updateStudentDetails(Student student) {
try {
mapper.save(student, buildDynamoDBSaveExpression(student));
} catch (ConditionalCheckFailedException exception) {
LOGGER.error("invalid data - " + exception.getMessage());
}
}
public void deleteStudentDetails(Student student) {
mapper.delete(student);
}
public DynamoDBSaveExpression buildDynamoDBSaveExpression(Student student) {
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
Map<String, ExpectedAttributeValue> expected = new HashMap<>();
expected.put("studentId", new ExpectedAttributeValue(new AttributeValue(student.getStudentId()))
.withComparisonOperator(ComparisonOperator.EQ));
saveExpression.setExpected(expected);
return saveExpression;
}
}<file_sep># Spring MVC REST API with DynamoDB
REST API developed using Spring MVC with AWS DynamoDB
| e90dff8c2dd5367b73eb4d89c73f68c3def1ef34 | [
"Markdown",
"Java"
] | 2 | Java | andreprawira/AWS-DynamoDB-SpringBoot | 4bec2fb12f423a04ee4d0a1c550bbdf03dbc8891 | b709ed882051f967389ce7323fb0b3cdb75a1030 |
refs/heads/master | <repo_name>stelligent/hab-demo-pipeline<file_sep>/bootstrap.sh
#!/bin/bash -x
set -o pipefail
error(){ echo ${1}; exit 1; }
# env variables
[ -z ${AWS_PROFILE} ] && error "Please be sure AWS_PROFILE is set in the environment"
[ -z ${LAMBDA_BUCKET} ] && error "Please be sure LAMBDA_BUCKET is set in the environment"
LAMBDA_ARCHIVE="dist/pipeline-runner.zip"
aws s3api create-bucket --bucket ${LAMBDA_BUCKET} --profile ${AWS_PROFILE}
if [ ! -e lambda/${LAMBDA_ARCHIVE} ] || [ "$1" = "lambda" ]; then
pushd .
cd lambda
npm install
rm ${LAMBDA_ARCHIVE}
zip -r ${LAMBDA_ARCHIVE} * -i "./package.json" "./index.js" "./lib/*" "./node_modules/*"
aws s3 cp ${LAMBDA_ARCHIVE} s3://${LAMBDA_BUCKET}/ --profile ${AWS_PROFILE}
popd
fi
if [ "$1" != "lambda" ]; then
node bootstrap.js "$1"
fi
<file_sep>/bootstrap.js
'use strict';
var fs = require('fs');
var CFNRunner = require('cfn-runner');
var baseConfig = './awsConfig.json';
var localConfig = './awsConfig.local.json';
try {
fs.accessSync(localConfig, fs.F_OK);
console.log("using local config file: " + localConfig);
baseConfig = localConfig;
} catch (e) {
console.log("using default config file: " + baseConfig);
}
var config = JSON.parse(fs.readFileSync(baseConfig));
config.config = baseConfig;
config.template = './cfn/pipeline.json';
var runner = new CFNRunner(config);
var callback = function(err) {
if (err) {
console.log(err);
} else {
console.log('success');
}
};
if (process.argv[2] === 'delete') {
// Delete the stack
runner.deleteStack(callback);
} else if (process.argv[2] === 'deploy') {
// Create or update the stack.
runner.deployStack(callback);
} else {
console.log("command '" + process.argv[2] + "' is not supported.");
}
<file_sep>/README.md
## hab-demo-pipeline
This is a POC for automating Habitat with AWS CodePipeline
**Prereqs**
```
nodejs
npm
aws-cli
```
**Setup**
```
git clone https://github.com/stelligent/hab-demo-pipeline
cd hab-demo-pipeline
npm install
```
**Config**
```
1. export AWS_PROFILE=your-profile-name
export LAMBDA_BUCKET=a-unique-bucket-name
2. Update the values in awsConfig.json or copy it to a new file called awsConfig.local.json.
awsConfig.local.json will be used if it exists.
```
**Usage**
```
# Build and deploy the Lambda package and stage it on S3
./bootstrap lambda
# Deploy a CFN stack to create the Lambda function and CodePipeline
./bootstrap.sh deploy
# Delete the CFN stack
./bootstrap.sh destroy
```
| af5fa5ecace09bbb635e3dbb1e3a17e38fc1fdc6 | [
"JavaScript",
"Markdown",
"Shell"
] | 3 | Shell | stelligent/hab-demo-pipeline | a42343c48f334cfeeff16c9bfcceeb7b9ceb314a | e6692989c9e9dfa75c6826311917a65a4f974098 |
refs/heads/master | <repo_name>tbaranes/FriendsPictureQuiz<file_sep>/Podfile
workspace './FriendsPictureQuiz.xcworkspace'
xcodeproj './FriendsPictureQuiz/FriendsPictureQuiz.xcodeproj'
platform :ios, '7.0'
pod 'FSI', '~> 0.1.0'
pod 'MBProgressHUD', '~> 0.8'<file_sep>/README.md
# FriendsPictureQuiz
FriendsPictureQuiz's was a small application developed and released in 2014. It has been available on the store a few years but removed from sales because of API breaking changes. This code is now just a souvenir.
### What is it?
*Description from the Apple Store*
Do you think you know your friends? Could you recognise each features of them ? If yes, accept this challenge!
Through a universe playful and funny, find out all your friends who are hiding behind their blurred pictures. Try to find all of them to show you are really incollable.
Find out your friends who are using this application with Facebook. Facebook is too easy? Challenge yourself and find out your Twitter's friends.
| 51550decf1f0fe2aa06aa3936c4af854970748cd | [
"Markdown",
"Ruby"
] | 2 | Ruby | tbaranes/FriendsPictureQuiz | 5adce27c1dceaf629e1463acc742ca7539626120 | f73e86ae397715e214e8b086ffad2a2b08afad3e |
refs/heads/master | <file_sep>/*****************************************
* UW User ID: uwuserid
* Submitted for ECE 250
* Department of Electrical and Computer Engineering
* University of Waterloo
* Calender Term of Submission: (Winter|Spring|Fall) 20NN
*
* By submitting this file, I affirm that
* I am the author of all modifications to
* the provided code.
*****************************************/
#ifndef DOUBLE_SENTINEL_LIST_H
#define DOUBLE_SENTINEL_LIST_H
#include <iostream>
#include "Exception.h"
template <typename Type>
class Double_sentinel_list {
public:
class Double_node {
public:
Double_node( Type const & = Type(), Double_node * = nullptr, Double_node * = nullptr );
Type value() const;
Double_node *previous() const;
Double_node *next() const;
Type node_value;
Double_node *previous_node;
Double_node *next_node;
};
Double_sentinel_list();
Double_sentinel_list( Double_sentinel_list const & );
Double_sentinel_list( Double_sentinel_list && );
~Double_sentinel_list();
// Accessors
int size() const;
bool empty() const;
Type front() const;
Type back() const;
Double_node *begin() const;
Double_node *end() const;
Double_node *rbegin() const;
Double_node *rend() const;
Double_node *find( Type const & ) const;
int count( Type const & ) const;
// Mutators
void swap( Double_sentinel_list & );
Double_sentinel_list &operator=( Double_sentinel_list );
Double_sentinel_list &operator=( Double_sentinel_list && );
void push_front( Type const & );
void push_back( Type const & );
void pop_front();
void pop_back();
int erase( Type const & );
private:
Double_node *list_head;
Double_node *list_tail;
int list_size;
// List any additional private member functions you author here
// Friends
template <typename T>
friend std::ostream &operator<<( std::ostream &, Double_sentinel_list<T> const & );
};
/////////////////////////////////////////////////////////////////////////
// Public member functions //
/////////////////////////////////////////////////////////////////////////
template <typename Type>
Double_sentinel_list<Type>::Double_sentinel_list():
// Updated the initialization list here
list_head( nullptr ),
list_tail( nullptr ),
list_size( 0 )
{
// Declare head and tail sentinel nodes
Double_node* headSent = new Double_node;
Double_node* tailSent = new Double_node;
//Since list is initially empty, the sentinel nodes point to eachother
headSent->next_node = tailSent;
headSent->previous_node = nullptr;
tailSent->next_node = nullptr;
tailSent->previous_node = headSent;
//Point list_head to head sentinel node and list_tail to list sentinel node
list_tail = tailSent;
list_head = headSent;
list_size = 0;
}
template <typename Type>
Double_sentinel_list<Type>::Double_sentinel_list( Double_sentinel_list<Type> const &list ): //Copy constructor
// Updated the initialization list here
list_head( nullptr ),
list_tail( nullptr ),
list_size( 0 )
{
// Declare head and tail sentinel nodes for list that will be copied to
Double_node* headSent = new Double_node;
Double_node* tailSent = new Double_node;
//Since list is initially empty, the sentinel nodes point to eachother
headSent->next_node = tailSent;
headSent->previous_node = nullptr;
tailSent->next_node = nullptr;
tailSent->previous_node = headSent;
//Point list_head to head sentinel node and list_tail to list sentinel node
list_tail = tailSent;
list_head = headSent;
list_size = 0;
//Create pointer to the front of the list that is passed in.
Double_node* traverse = list.begin();
while(traverse->next_node != nullptr){
push_back(traverse->node_value); //Push value to back of new list from the node traverse points to
traverse = traverse->next_node;
}
}
template <typename Type>
Double_sentinel_list<Type>::Double_sentinel_list( Double_sentinel_list<Type> &&list ): //Move constructor
// Updated the initialization list here
list_head( nullptr ),
list_tail( nullptr ),
list_size( 0 )
{
// Declare head and tail sentinel nodes for list that will be copied to
Double_node* headSent = new Double_node;
Double_node* tailSent = new Double_node;
//Since list is initially empty, the sentinel nodes point to eachother
headSent->next_node = tailSent;
headSent->previous_node = nullptr;
tailSent->next_node = nullptr;
tailSent->previous_node = headSent;
//Point list_head to head sentinel node and list_tail to list sentinel node
list_tail = tailSent;
list_head = headSent;
list_size = 0;
//Swap the list_head, list_tail and list_size of the list being created and the lsit passsed in
swap(list);
}
template <typename Type>
Double_sentinel_list<Type>::~Double_sentinel_list() {
Double_node* traverse = list_head; //Create traverse pointer to move through each node in the list
while(traverse != nullptr) // Iterate through entire list until nullptr is reached which will be the end
{
Double_node* del = traverse; //Create pointer to node that should be deleted
traverse = traverse->next_node;
delete del;
}
list_size = 0;
}
template <typename Type>
int Double_sentinel_list<Type>::size() const {
//Create traverse node pointer to traverse entire list and add to counter
Double_node *traverse = list_head;
int count = 0;
while(traverse != nullptr) // Iterate through entire list until nullptr is reached which will be the end
{
traverse = traverse->next_node;
count++;
}
return count - 2; // Subtract two from total count to account for both sentinel nodes.
}
template <typename Type>
bool Double_sentinel_list<Type>::empty() const {
if(list_size == 0)//Check list_size, if 0, the list must be empty
return true;
return false;
}
template <typename Type>
Type Double_sentinel_list<Type>::front() const {
// Check to see if list is empty before getting front node value
if(empty())
throw underflow();
else
return list_head->next_node->value(); //list_head points to the head sentinel node so the next node after that will be the front node.
return Type();
}
template <typename Type>
Type Double_sentinel_list<Type>::back() const {
// Check to see if list is empty before getting back node value
if(empty())
throw underflow();
else
return list_tail->previous_node->value(); //list_tail points to the tail sentinel node so the previous node before that will be the back node.
return Type(); // This returns a default value of Type
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::begin() const {
// list_head points to head sentinel node, next node after sentinel node will the first node in the list
return list_head->next_node;
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::end() const {
// list_tail point to the tail sentinel node
return list_tail;
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::rbegin() const {
// previous_node of list_tail is the last node in the list
return list_tail->previous_node;
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::rend() const {
// list_head point to the head sentinel node
return list_head;
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::find( Type const &obj ) const {
//Create traverse node pointer to iterate through each node in the list
Double_node *traverse = list_head->next_node;
while(traverse != nullptr)
{
if(traverse->node_value == obj) //If the node that traverse is pointing to has the same value as obj, return traverse pointer
return traverse;
else
traverse = traverse->next_node; //If the values dont match, point traverse to the next node in the list
}
return end();
}
template <typename Type>
int Double_sentinel_list<Type>::count( Type const &obj ) const {
//Create traverse node pointer to iterate through each node in the list
Double_node *traverse = list_head->next_node;
int count = 0;
while(traverse != nullptr)
{
if(traverse->node_value == obj) //If the node that traverse is pointing to has the same value as obj, increment count
count++;
traverse = traverse->next_node; //Always move the traverse pointer to the next node in the list
}
return count;
}
template <typename Type>
void Double_sentinel_list<Type>::swap( Double_sentinel_list<Type> &list ) {
// This is done for you
std::swap( list_head, list.list_head );
std::swap( list_tail, list.list_tail );
std::swap( list_size, list.list_size );
}
// The assignment operator
template <typename Type>
Double_sentinel_list<Type> &Double_sentinel_list<Type>::operator=( Double_sentinel_list<Type> rhs ) {
// This is done for you
swap( rhs );
return *this;
}
// The move operator
template <typename Type>
Double_sentinel_list<Type> &Double_sentinel_list<Type>::operator=( Double_sentinel_list<Type> &&rhs ) {
// This is done for you
swap( rhs );
return *this;
}
template <typename Type>
void Double_sentinel_list<Type>::push_front( Type const &obj ) {
// Create new node to add to list holding the value passed in
Double_node *n = new Double_node;
//Re-arrange next an dprevious poinbters to add new node to list
n->node_value = obj;
n->next_node = list_head->next_node;
n->previous_node = list_head;
list_head->next_node->previous_node = n;
list_head ->next_node = n;
list_size++;
}
template <typename Type>
void Double_sentinel_list<Type>::push_back( Type const &obj ) {
// Create new node to add to list holding the value passed in
Double_node *n = new Double_node;
//Re-arrange next an dprevious poinbters to add new node to list
n->node_value = obj;
n->next_node = list_tail;
n->previous_node = list_tail->previous_node;
list_tail->previous_node->next_node = n;
list_tail->previous_node = n;
list_size++;
}
template <typename Type>
void Double_sentinel_list<Type>::pop_front() {
// Check to see if list is empty before attempting to remove first node
if(empty())
throw underflow();
Double_node* nodePop = list_head->next_node; //Assign temporary pointer to the last node in the list (besides sentinel)
//Move pointers around first node in list to establish a new first node
list_head->next_node = nodePop->next_node;
list_head->next_node->previous_node = list_head;
//Delete node after pointers have been allocated correctly
delete nodePop;
list_size--;
}
template <typename Type>
void Double_sentinel_list<Type>::pop_back() {
// Check to see if list is empty before attempting to remove first node
if(empty())
throw underflow();
Double_node* nodePop = list_tail->previous_node; //Assign temporary pointer to the first node in the list (besides sentinel)
//Move pointers around first node in list to establish a new first node
list_tail->previous_node = nodePop->previous_node;
list_tail->previous_node->next_node = list_tail;
//Delete node after pointers have been allocated correctly
delete nodePop;
list_size--;
}
template <typename Type>
int Double_sentinel_list<Type>::erase( Type const &obj ) {
//Create counter to count how mamny nodes are erased
int numDelete = 0;
//Create traverse pointer to navigate list
Double_node* traverse = list_head->next_node;
while(traverse->next_node != nullptr)
{
if(traverse->node_value == obj){ //If the node value matches the value passed in,
Double_node* del = traverse; //Create temporary pointer to node that is to be deleted
del->previous_node->next_node = traverse->next_node; // Re-arrange pointers to avoid the node to be deleted
del->next_node->previous_node = traverse->previous_node;
traverse = traverse->next_node; // Move traverse to next node to ensure it is not lost
delete del; // Delete desired node
numDelete++;
list_size--;
}
else
traverse = traverse->next_node; //If the node value does not match the value passed in, move traverse to next node in list
}
return numDelete;
}
template <typename Type>
Double_sentinel_list<Type>::Double_node::Double_node(
Type const &nv,
typename Double_sentinel_list<Type>::Double_node *pn,
typename Double_sentinel_list<Type>::Double_node *nn ):
// Updated the initialization list here
node_value( Type() ), // This assigns 'node_value' the default value of Type
previous_node( nullptr ),
next_node( nullptr )
{
// Enter your implementation here
}
template <typename Type>
Type Double_sentinel_list<Type>::Double_node::value() const {
return node_value; // This returns the value of the node
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::Double_node::previous() const {
// Return previous_node pointer
return previous_node;
}
template <typename Type>
typename Double_sentinel_list<Type>::Double_node *Double_sentinel_list<Type>::Double_node::next() const {
//Return next_node pointer
return next_node;
}
/////////////////////////////////////////////////////////////////////////
// Private member functions //
/////////////////////////////////////////////////////////////////////////
// If you author any additional private member functions, include them here
/////////////////////////////////////////////////////////////////////////
// Friends //
/////////////////////////////////////////////////////////////////////////
// You can modify this function however you want: it will not be tested
template <typename T>
std::ostream &operator<<( std::ostream &out, Double_sentinel_list<T> const &list ) {
out << "head";
for ( typename Double_sentinel_list<T>::Double_node *ptr = list.rend(); ptr != nullptr; ptr = ptr->next() ) {
if ( ptr == list.rend() || ptr == list.end() ) {
out << "->S";
} else {
out << "->" << ptr->value();
}
}
out << "->0" << std::endl << "tail";
for ( typename Double_sentinel_list<T>::Double_node *ptr = list.end(); ptr != nullptr; ptr = ptr->previous() ) {
if ( ptr == list.rend() || ptr == list.end() ) {
out << "->S";
} else {
out << "->" << ptr->value();
}
}
out << "->0";
return out;
}
#endif
| 9b8e752435e4038c894c19274fd77da178176a70 | [
"C++"
] | 1 | C++ | Ryanschmied/Double_Sentinel_Linked_List | 2302c92f4c520b0132ce6fe19a85c09ab4c5be61 | 1dfe79f078d31c0ef8e5147360915b3eb774543e |
refs/heads/master | <file_sep>package org.launchcode.java.exercises;
import java.util.Scanner;
public class Alice2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String firstLine = "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'";
System.out.println("What word are you looking for?");
String searchTerm = input.nextLine();
if (firstLine.contains(searchTerm.toLowerCase())) {
System.out.println("Congratulations! '" + searchTerm + "' is at an index of " + firstLine.indexOf(searchTerm) + " and is " + searchTerm.length() + " characters long.");
String wordGone = firstLine.replace(searchTerm, "");
System.out.println(wordGone);
} else {
System.out.println("Try again!");
}
}
}
<file_sep>package org.launchcode.java.studios.areaofacircle;
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int validRadius = 0;
do {
System.out.println("Radius of your circle: ");
double radius = input.nextDouble();
if (radius < 0) {
System.out.println("Please enter a radius that is not negative.");
} else {
System.out.println("The area of a circle of radius " + radius + " is: " + Circle.getArea(radius));
validRadius = 1;
}
} while (validRadius == 0);
}
}
<file_sep>package org.launchcode.java.exercises;
import java.util.Arrays;
public class ArrayPractice {
public static void main(String[] args) {
// Number Array
// int nums[] = {1, 1, 2, 3, 5, 8};
//
// for (int i : nums) {
// System.out.println(i);
// }
// Word Array
String sentence = "I would not, could not, in a box. I would not, could not with a fox. I will not eat them in a house. I will not eat them with a mouse.";
String[] wordArray = sentence.split("\\.");
System.out.println(Arrays.toString(wordArray));
}
}
| 63a5e2517cf40e3db18961a47bd4c7994059207b | [
"Java"
] | 3 | Java | bonniewhy/java-web-dev-exercises | e6202f34454d28979683238fe920dcf1b5423e80 | f639f6d5f9c14ca76a65052051f704f442da2695 |
refs/heads/main | <repo_name>matt-halliday/logstash-local<file_sep>/Makefile
NO_COLOR=$(shell tput sgr0)
GREEN=$(shell tput bold)$(shell tput setaf 2)
DC = docker-compose
default: start
start:
@echo '${GREEN}Starting logstash${NO_COLOR}'
@${DC} up -d --force-recreate && ./wait.sh
clear:
@echo '${GREEN}Clearing logs${NO_COLOR}'
@echo > ./input.txt
@echo > ./output.json
rm:
@echo '${GREEN}Removing container and cleaning up${NO_COLOR}'
@${DC} down -v --remove-orphans
@docker system prune --volumes -f
<file_sep>/wait.sh
#!/bin/bash
echo -n "Waiting for logstash"
until curl -s 'localhost:9600' > /dev/null; do
echo -n "."
sleep 1;
done
echo -e "\rLogstash is up and running!"
<file_sep>/README.md
# Logstash Local
This project provides a safe environment in which to test
logstash config.
It requires Docker.
## Usage
Fork/clone/download this repo and `cd` into it in your terminal.
To start the local environment, run `make` in your terminal
Wait for logstash to be ready.
Add lines to the `input.txt` file and save, then open the
`output.json` file to see the resulting log format.
To clear both of these files, run `make clear`.
Add filters etc to the `logstash.conf` file. The logstash container
is configured to watch and automatically reload the config if
it changes.
To tear it all down, run `make rm`
| 1fbb670cc3d6a11d942194f8a253d8aafee4dfbd | [
"Markdown",
"Makefile",
"Shell"
] | 3 | Makefile | matt-halliday/logstash-local | 15a430ae7749c7fa35ca4c864c9a076fd8ba0c06 | bfff8085039401a8d47eddd8f9c49e66b9785d3a |
refs/heads/master | <repo_name>mjrdev/dastcursos-frontend<file_sep>/src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../views/Main.vue'
// views
import Login from '../views/Login.vue'
import MyCourses from '../views/My-courses.vue'
import Store from '../views/Store.vue'
import NotFound from '../views/NotFound.vue'
import Profile from '../views/Profile.vue'
// components childen views
import Course from '../components/store/course/course.vue'
Vue.use(VueRouter)
const childrens = {
store: { path: 'course', component: Course }
}
const routes = [
{ path: '*', component: NotFound },
{ path: '/', component: Login },
{ path: '/main', component: Main },
{ path: '/my-courses', component: MyCourses },
{ path: '/profile', component: Profile },
{ path: '/store', component: Store, children: [ childrens.store ] }
]
const router = new VueRouter({ routes })
export default router<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
user: {
name: '<NAME>',
email: '<EMAIL>'
}
},
mutations: {
}
})
export default store<file_sep>/timeController.md
# controle de tempo
> iniciado em 06/11/19 23h
> prazo 13/11/19 23h59m
| 7bd133f4b729cf26731f6ab7ed18314d8b1ab995 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mjrdev/dastcursos-frontend | 64e538c7f4ee540025f93566d8908e2d82381224 | 07cf0abd4b022384fa5273dc217cf8dd18dd45a6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.