branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>ZiadHamwi/AR-Home<file_sep>/AR Home/DataLoader.swift
//
// DataLoader.swift
// CardSlider
//
// Created by Farah on 5/14/21.
//
import Foundation
@available(iOS 13.0, *)
public class DataLoader{
@Published var userData = [Houses]()
init() {
load()
}
func load() {
if let filelocation = Bundle.main.url(forResource: "houses", withExtension: "json"){
//do catch in case of error
do {
let data = try Data(contentsOf: filelocation)
let jsonDecoder = JSONDecoder()
let dataFromJson = try jsonDecoder.decode([Houses].self, from: data)
self.userData = dataFromJson
} catch {
print(error)
}
}
}
// func sort(){
// self.userData = self.userData.sorted
// }
}
<file_sep>/README.md
<div align="center">
<h1> AR Home </h2>
CMPS 299 Final Year Project <br>
<img src="AR Home/Assets.xcassets/AppIcon.appiconset/pngwing.com-6.png" width="200" height="200"> <br>
<i><b>Team Members:</b></i>
<br> <NAME>
<br> <NAME>
<br> <NAME>
</div>
<br>
<br>
# Project Description:
<div align="justify">
AR Home is a real estate iOS application that gives you a more realistic experience while searching for your
next home. Using AR, the user can feel themselves as if the house is right in front of them, but even better.
Users are able to browse through the plethora of homes we have available on the app. In addition, they will be
able to view the interior of each house, along with a description of it, all in augmented reality.
</div>
<br>
# Components:
<div align="justify">
We designed our app exclusively for iOS at the moment so all work was handled within Xcode; we used ARKit in
conjunction with SceneKit as the main framework of our app.
<br><br>
We used numerous controllers throughout our app. These controllers help us organize our app’s controls, i.e. buttons,
image views, etc., in a specific way and we can exchange data between different controllers based on the user’s input on
the preceding controller. We also used a navigation controller within our app to allow easy navigation between the
different controllers.
<br><br>
Key Controllers:
<ul style="list-style: none;">
<li>ViewController</li>
<li>PostController</li>
<li>CardSliderViewController</li>
<li>ARViewController</li>
</ul>
<br>
<ul>
<li>The <b>ViewController</b> is the main “home screen” of our app, it consists of numerous elements, including a
collection view used to give the user a slidable/scrollable preview of the houses, a search bar, and some buttons to
interact with the app. </li>
<li>The <b>PostController</b> handles the “PostHouses” portion of our app, it consists of a few text fields, to enter
information about the house the user is currently posting, an interactive map view imported from MapKit, a photo
selector (allows the user to either take a photo or upload an existing photo), as well as a button to take the user to
the next screen which prompts the user to enter his/her contact information.</li>
<li>The <b>CardSliderViewController</b> initially came from a library, CardSlider, that we imported using Cocoapods. We
used it as a template to design our main interface to browse through houses. It can show an image preview of the
house, the title of the house, a description of the house, the price of the house, as well as a button to present the
house in augmented reality to the user. Pressing the AR button takes the user to the ARViewController.</li>
<li>The <b>ARViewController</b> is the main view controller that presents the user with an AR view of the house, the user
can select whether he/she wants an interior or exterior view of the house and the app previews the house using AR
in the user’s desired way. It also handles tapping functionalities, i.e. when the user taps a house in AR, it presents
some useful information about the house; it displays them around the house using AR.</li>
</ul>
</div>
<br>
# Screen Mockups:
<div align="center">
<img src="Screen_Mockups/Picture1.png">
<img src="Screen_Mockups/Picture2.png"><br>
<img src="Screen_Mockups/Picture3.png">
<img src="Screen_Mockups/Picture4.png"><br>
<img src="Screen_Mockups/Picture5.png">
<img src="Screen_Mockups/Picture6.png">
<img src="Screen_Mockups/Picture7.png"><br>
<img src="Screen_Mockups/Picture8.png">
<img src="Screen_Mockups/Picture9.png"><br>
</div>
<br>
# Working Features:
<div align="justify">
Upon using the application, the user can use a variety of features:
<ul>
<li>The user can scroll through an array of houses and get useful information about each house </li>
<li>The user can tap on a house and view it in AR</li>
<li>The user can tap a button which automatically takes them to the interior of the house or back to the
exterior </li>
<li>The user will be able to enter a “Post House” form where they can specify the location of the listing, an
image, contact information, along with the basic house description. </li>
</div>
# Improvements:
<div align="justify">
There are certain features in our application that need improvement:
<ul>
<li>Add a “contact buyer” feature under the information of each house </li>
<li>Make the “Post House” view functional with a backend </li>
<li>Make the search bar search between the houses in the database in the backend </li>
<li>Make the AR experience more robust </li>
<li>Allow the user to drag and move around the AR house within the plane </li>
<li>Create an appropriate database in the backend that keeps track and stores all houses </li>
</ul>
</div>
# Future Components:
<div align="justify">
For the future we would like to add a few components that we see would improve the application:
<ul>
<li>Create a database that contains information about the house listings we have. </li>
<li>Filter houses according to location and price. </li>
<li>Share the house information through WhatsApp or other social media platforms </li>
<li>Mark the house as sold when the house gets sold. </li>
<li>Post houses from the app into the database. </li>
<li>Create an account for each user, where they can favorite and save the houses they view. </li>
<li>Add contact information for each house where the user will be able to directly be in contact with the
owner/real estate agent. </li>
</ul>
</div>
# Lessons Learned:
<div align="justify">
Throughout this year, we have learned so much from starting this application. This application
strengthened our knowledge in Swift and iOS mobile programming. We also delved into a relatively new topic
for us, which is Augmented Reality. We learned how to anchor 3D objects on flat surfaces, display text on top
of the object, and even go inside the object to view its interior. We also learned how to add components to the
application's front end, both programmatically and using the storyboard. One other notable topic we learned
throughout this journey is using Cocoapods within our Xcode projects. It is a very powerful dependency
manager that gives us the ability to import third-party libraries into our project. We imported CardSlider and
used it as a template to design our main interface to browse through houses. We also experimented with
SwiftSoup initially, which allowed us to read data from online web pages and do some web scraping which was
helpful at first but later on, we decided to eliminate it since we felt that it wasn't essential for the key
functionality of our app which mainly is augmented reality. Hence, we decided to dedicate most of our
resources to improving the AR experience. Additionally, we learned how to create a GitHub repository for our
application that enabled easy access of the app between the group members.
</div>
<file_sep>/AR Home/ViewController.swift
//
// ViewController.swift
// Prototype01
//
// Created by <NAME> on 1/18/21.
//
import UIKit
import SceneKit
import ARKit
import CardSlider
import AVFoundation
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
struct Item:CardSliderItem {
var image: UIImage
var rating: Int?
var title: String
var subtitle: String?
var description: String?
}
struct CustomData {
var title: String
var url: String
var backgroundImage: UIImage
}
class House {
var house_title: String = ""
var house_description: String = ""
var house_image_link: String = ""
var house_price: String = ""
init() {
self.house_title = ""
self.house_description = ""
self.house_image_link = ""
self.house_price = ""
}
init(_ house_title: String, _ house_description: String, _ house_image_link: String, _ house_price: String) {
self.house_title = house_title
self.house_description = house_description
self.house_image_link = house_image_link
self.house_price = house_price
}
}
class ViewController: UIViewController, ARSCNViewDelegate, CardSliderDataSource, UISearchBarDelegate {
//load data from json
let ARhouse = DataLoader().userData
fileprivate let data = [
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Mansion")),
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Macchiato Mansion")),
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Cozy Green House")),
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Cottage")),
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Residential Building")),
CustomData(title: "", url: "", backgroundImage: #imageLiteral(resourceName: "Two Story House"))
]
fileprivate let collectionView:UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.register(CustomCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
let configuration = ARWorldTrackingConfiguration()
var indicator = UIPageControl()
var link1 = ""
var link2 = ""
var link3 = ""
var link4 = ""
var link5 = ""
var link6 = ""
var data2 = [Item]()
func item(for index: Int) -> CardSliderItem {
return data2[index]
}
func numberOfItems() -> Int {
return data2.count
}
@IBOutlet var sceneView: ARSCNView!
var timer = Timer()
let exploreHouses = UIButton()
let postHouses = UIButton()
// let searchBar = UISearchBar()
lazy var searchBar:UISearchBar = UISearchBar()
var houseImages: [UIImage] = []
var houseImagesIndex = 0
var houses: [House] = []
var houseListingLinks: [String] = []
func appendImagesToArray() {
// houseImages.append(UIImage(named: "Cottage")!)
// houseImages.append(UIImage(named: "Residential Building")!)
// houseImages.append(UIImage(named: "Two Story House")!)
// houseImages.append(UIImage(named: "House")!)
//loop over the houses in the json file and output their images
for houses in ARhouse{
houseImages.append(UIImage(named: houses.houseName)!)
}
}
@IBAction func unwindToViewController(sender: UIStoryboardSegue) {
}
func loadCardSliderData() {
// for x in 3...5 {
// if let h1 = try? Data(contentsOf: URL(string: "https:" + houses[0].house_image_link)!) {
// data.append(Item(image: UIImage(data: h1)!, rating: nil, title: houses[0].house_title, subtitle: "House subtitle", description: houses[0].house_description))
//
// }
// if let h2 = try? Data(contentsOf: URL(string: "https:" + houses[1].house_image_link)!) {
// data.append(Item(image: UIImage(data: h2)!, rating: nil, title: houses[1].house_title, subtitle: "House subtitle", description: houses[1].house_description))
////
// }
// }
// data2.append(Item(image: UIImage(named: "House")!, rating: nil, title: "model", subtitle: "House", description: "This compact plan features a fully equipped kitchen with a walk-in pantry and eating bar that comfortably seats up to four. The spacious floor plan accommodates full sized furniture and appliances. 9' ceilings and pocket doors throughout the home create a spacious and open feeling. The pocket doors leading into the master suite and guest room can either be closed for privacy or can provide a large 5' wide opening. The modern walk-in shower in the master suite provides both easy access and eliminates the maintenance required by glass doors. Measuring over 6' from end to end, the shower accommodates dual shower heads. The master suite also includes a dual vanity and a large walk-in closet. This design also features a covered front porch, double garage, mudroom/laundry room and a full bath for guests."))
//
// data2.append(Item(image: UIImage(named: "Cottage")!, rating: nil, title: "Cottage", subtitle: "Cottage House", description: "This compact plan features a fully equipped kitchen with a walk-in pantry and eating bar that comfortably seats up to four. The spacious floor plan accommodates full sized furniture and appliances. 9' ceilings and pocket doors throughout the home create a spacious and open feeling. The pocket doors leading into the master suite and guest room can either be closed for privacy or can provide a large 5' wide opening. The modern walk-in shower in the master suite provides both easy access and eliminates the maintenance required by glass doors. Measuring over 6' from end to end, the shower accommodates dual shower heads. The master suite also includes a dual vanity and a large walk-in closet. This design also features a covered front porch, double garage, mudroom/laundry room and a full bath for guests."))
// data2.append(Item(image: UIImage(named: "Residential Building")!, rating: nil, title: "Residential Building", subtitle: "Residential Building", description: "A residential building is defined as the building which provides more than half of its floor area for dwelling purposes. In other words, residential building provides sleeping accommodation with or without cooking or dining or both facilities."))
// data2.append(Item(image: UIImage(named: "Two Story House")!, rating: nil, title: "Two Story House", subtitle: "Two Story House", description: "2 story house plans (sometimes written \"two story house plans\") are probably the most popular story configuration for a primary residence. A traditional 2 story house plan presents the main living spaces (living room, kitchen, etc) on the main level, while all bedrooms reside upstairs."))
//loop over the item in the json file and output the houses
for houses in ARhouse{
data2.append(Item(image: UIImage(named: houses.houseName)!, rating: nil, title: houses.houseName, subtitle: houses.price, description: houses.description + "\n\nLocation: \n " + houses.location + "\n\nContact: \n " + houses.contactName + "\n " + houses.contactNum + "\n " + houses.contactEmail))
}
}
func displayHomeScreenElements() {
UIView.animate(withDuration: 0.2) {
self.searchBar.alpha = 1
}
delay(0.3) {
UIView.animate(withDuration: 0.3) {
self.collectionView.alpha = 1
}
self.delay(0.3) {
UIView.animate(withDuration: 0.3) {
self.exploreHouses.alpha = 1
}
self.delay(0.3) {
UIView.animate(withDuration: 0.1) {
self.postHouses.alpha = 1
}
}
}
}
}
func getNumberofHouseImages() -> Int {
return houseImages.count
}
// Explore Houses Button
@objc func exploreHousesButton(sender : UIButton) {
AudioServicesPlaySystemSound(1519)
var vc = CardSliderViewController()
// var vc = UIViewController()
vc = CardSliderViewController.with(dataSource: self)
vc.navigationItem.title = "Explore Houses"
// vc.view.backgroundColor = .red
navigationController?.pushViewController(vc, animated: true)
}
@objc func exploreHousesTouchDown_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.exploreHouses.alpha = 0.4
}
}
@objc func exploreHousesTouchUpInside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.exploreHouses.alpha = 1
}
}
@objc func exploreHousesTouchUpOutside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.exploreHouses.alpha = 1
}
}
@objc func exploreHousesTouchDragOutside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.exploreHouses.alpha = 1
}
}
//END of Explore Houses
// Post Houses Button
@objc func postHousesButton(sender : UIButton) {
AudioServicesPlaySystemSound(1519)
let postHousesVC = storyboard?.instantiateViewController(identifier: "PostHouses_VC") as! postController
// present(ARViewController(), animated: true, completion: nil)
navigationController?.pushViewController(postHousesVC, animated: true)
// // Run the view's session
// self.sceneView.session.run(self.configuration)
// UIView.animate(withDuration: 0.5) {
// self.view.backgroundColor = .black
// }
}
@objc func postHousesTouchDown_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.postHouses.alpha = 0.4
}
}
@objc func postHousesTouchUpInside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.postHouses.alpha = 1
}
}
@objc func postHousesTouchUpOutside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.postHouses.alpha = 1
}
}
@objc func postHousesTouchDragOutside_button(sender : UIButton) {
UIView.animate(withDuration: 0.3) {
self.postHouses.alpha = 1
}
}
//END of Post Houses
@objc func indicatorChanged(sender : UIPageControl) {
let current = sender.currentPage
var indexPath: IndexPath!
indexPath = IndexPath(item: current, section: 0)
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
// print(current)
}
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.prefersLargeTitles = true
// Create a session configuration
// Run the view's session
// sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
// sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
var color = UIColor(red: 54/255, green: 240/255, blue: 255/255, alpha: 1)
func configureButton(_ button:UIButton, _ title:String) {
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 34)
button.backgroundColor = .white
button.clipsToBounds = true
button.tintColor = .white
button.layer.cornerRadius = 30
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.clear.cgColor
button.setTitleColor(.black, for: .normal)
button.alpha = 0
button.backgroundColor = color
}
func createHomeScreenElements() {
appendImagesToArray()
configureButton(exploreHouses, "Explore Houses")
exploreHouses.translatesAutoresizingMaskIntoConstraints = false
exploreHouses.addTarget(self, action: #selector(self.exploreHousesButton), for: .touchUpInside)
exploreHouses.addTarget(self, action: #selector(self.exploreHousesTouchDown_button), for: .touchDown)
exploreHouses.addTarget(self, action: #selector(self.exploreHousesTouchUpInside_button), for: .touchUpInside)
exploreHouses.addTarget(self, action: #selector(self.exploreHousesTouchUpOutside_button), for: .touchUpOutside)
exploreHouses.addTarget(self, action: #selector(self.exploreHousesTouchDragOutside_button), for: .touchDragOutside)
view.addSubview(exploreHouses)
configureButton(postHouses, "Post Houses")
postHouses.translatesAutoresizingMaskIntoConstraints = false
postHouses.addTarget(self, action: #selector(self.postHousesButton), for: .touchUpInside)
postHouses.addTarget(self, action: #selector(self.postHousesTouchDown_button), for: .touchDown)
postHouses.addTarget(self, action: #selector(self.postHousesTouchUpInside_button), for: .touchUpInside)
postHouses.addTarget(self, action: #selector(self.postHousesTouchUpOutside_button), for: .touchUpOutside)
postHouses.addTarget(self, action: #selector(self.postHousesTouchDragOutside_button), for: .touchDragOutside)
view.addSubview(postHouses)
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.alpha = 0
searchBar.placeholder = "Search Houses"
// searchBar.layer.borderWidth = 10
searchBar.showsCancelButton = true
indicator.addTarget(self, action: #selector(self.indicatorChanged), for: .valueChanged)
view.addSubview(indicator)
// indicator.frame = CGRect(x: 0, y: 595, width: view.frame.width, height: 50)
indicator.alpha = 1
indicator.layer.cornerRadius = 12
indicator.translatesAutoresizingMaskIntoConstraints = false
indicator.numberOfPages = data.count
indicator.currentPage = 0
// searchBar.searchBarStyle = UISearchBar.Style.prominent
// searchBar.placeholder = "Search Houses"
// searchBar.sizeToFit()
// searchBar.isTranslucent = false
// searchBar.backgroundImage = UIImage()
// searchBar.delegate = self
// navigationItem.titleView = searchBar
view.addSubview(searchBar)
}
private let myView: UIView = {
let myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
return myView
}()
// func searchBar(searchBar: UISearchBar, textDidChange textSearched: String)
// {
// }
//
//
// func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// searchBar.endEditing(true)
//// self.searchBar.dism
// }
//
// func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// searchBar.endEditing(true)
//
// }
func addConstraints() {
var constraints = [NSLayoutConstraint]()
//myView
constraints.append((myView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)))
constraints.append((myView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)))
constraints.append((myView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)))
constraints.append((myView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)))
//searchBar
constraints.append(searchBar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor))
constraints.append(searchBar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor))
constraints.append(searchBar.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 0.08))
constraints.append(searchBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor))
constraints.append(searchBar.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: -12))
//CollectionView
constraints.append(collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10))
constraints.append(collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10))
constraints.append(collectionView.topAnchor.constraint(equalTo: searchBar.bottomAnchor, constant: 12))
constraints.append(collectionView.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 0.6))
constraints.append(collectionView.bottomAnchor.constraint(equalTo: indicator.topAnchor, constant: -10))
// indicator
constraints.append(indicator.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10))
constraints.append(indicator.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10))
constraints.append(indicator.topAnchor.constraint(equalTo: collectionView.bottomAnchor, constant: 10))
constraints.append(indicator.bottomAnchor.constraint(equalTo: exploreHouses.topAnchor, constant: -10))
//postHouses
// constraints.append(postHouses.topAnchor.constraint(equalTo: exploreHouses.bottomAnchor, constant: 20))
constraints.append(postHouses.bottomAnchor.constraint(equalTo: myView.bottomAnchor, constant: -1))
constraints.append(postHouses.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 0.1))
constraints.append(postHouses.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10))
constraints.append(postHouses.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10))
//exploreHouses
constraints.append(exploreHouses.bottomAnchor.constraint(equalTo: postHouses.topAnchor, constant: -20))
constraints.append(exploreHouses.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10))
constraints.append(exploreHouses.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10))
constraints.append(exploreHouses.heightAnchor.constraint(equalTo: myView.heightAnchor, multiplier: 0.1))
//Activate the constraints
NSLayoutConstraint.activate(constraints)
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
// webScrapeSomeDataAndGetHouseListingsLinks()
// houses.append(getHouseData(houseListingLinks[0]))
if self.traitCollection.userInterfaceStyle == .dark {
// User Interface is Dark
myView.backgroundColor = .black
color = .yellow
} else {
// User Interface is Light
indicator.backgroundColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1)
myView.backgroundColor = .white
}
title = "Home"
view.addSubview(myView)
view.addSubview(collectionView)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = .white
collectionView.delegate = self
collectionView.dataSource = self
self.collectionView.backgroundColor = view.backgroundColor
collectionView.isPagingEnabled = true
collectionView.contentMode = .scaleAspectFill
loadCardSliderData()
createHomeScreenElements()
displayHomeScreenElements()
addConstraints()
// Set the view's delegate
sceneView.delegate = self
// print(houses[0].house_title)
// print(houses[1].house_title)
// print(houses[2].house_title)
// print(houses[3].house_title)
// print(houses[4].house_title)
// print(houses[5].house_title)
// Show statistics such as fps and timing information
// sceneView.showsStatistics = true
// Create a new scene
// let scene = SCNScene(named: "art.scnassets/ship.scn")!
// Set the scene to the view
// sceneView.scene = scene
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
for cell in collectionView.visibleCells {
let indexPath = collectionView.indexPath(for: cell)
indicator.currentPage = indexPath![1]
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return CGSize(width: collectionView.frame.width/2.5, height: collectionView.frame.width/2)
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.data = self.data[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
class CustomCell: UICollectionViewCell {
var data: CustomData? {
didSet {
guard let data = data else { return }
bg.image = data.backgroundImage
}
}
fileprivate let bg: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.layer.cornerRadius = 30
return iv
}()
override init(frame: CGRect) {
super.init(frame: .zero)
contentView.addSubview(bg)
bg.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
bg.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
bg.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
bg.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/AR Home/postController.swift
//
// postController.swift
// Post Houses
//
// Created by Farah on 2/25/21.
//
import UIKit
import MapKit
import CoreLocation
class postController: UIViewController, UINavigationControllerDelegate, MKMapViewDelegate, CLLocationManagerDelegate, UIImagePickerControllerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//
self.hideKeyboardWhenTappedAround()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
//
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped))
houseLocation?.addGestureRecognizer(tapGesture)
}
@objc func mapViewTapped(gestureRecognizer: UIGestureRecognizer) {
let touchPoint = gestureRecognizer.location(in: houseLocation)
let coordinate = houseLocation.convert(touchPoint, toCoordinateFrom: houseLocation)
addPin(at: coordinate)
}
func addPin(at coordinate: CLLocationCoordinate2D) {
let newAnnotation = MKPointAnnotation()
let allAnnotations = houseLocation.annotations
houseLocation.removeAnnotations(allAnnotations)
newAnnotation.coordinate = coordinate
print("locations = \(coordinate.latitude) \(coordinate.longitude)")
houseLocation.addAnnotation(newAnnotation)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
// print("locations = \(locValue.latitude) \(locValue.longitude)")
// let annotation = MKPointAnnotation()
// annotation.coordinate = locValue
// houseLocation.addAnnotation(annotation)
// annotation.title = "Your Location"
// let coordinateRegion = MKCoordinateRegion(center: annotation.coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
// houseLocation.setRegion(coordinateRegion, animated: false)
}
@IBOutlet weak var imageView: UIImageView!
@IBAction func didTapButton(){
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction( UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}
else {
print("Camera not available")
}
}))
actionSheet.addAction( UIAlertAction(title: "Photo Library", style: .default, handler: {(action:UIAlertAction) in imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
@IBOutlet weak var contactName: UITextField!
@IBOutlet weak var contactNumber: UITextField!
@IBOutlet weak var contactEmail: UITextField!
@IBOutlet weak var houseName: UITextField!
@IBOutlet weak var houseDesc: UITextView!
@IBOutlet weak var houseLocation: MKMapView!
@IBAction func postHouse(_ sender: Any) {
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
let isPresentingInAddMealMode = presentingViewController is UINavigationController
// present(ViewController(), animated: true, completion: nil)
if isPresentingInAddMealMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController{
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The postController is not inside a navigation controller.")
}
}
}
| 66dad2e65b590c81b9b2539f913ab4dd6c5ec3c7 | [
"Swift",
"Markdown"
] | 4 | Swift | ZiadHamwi/AR-Home | 35980e475997543412e924ffb6076ae81936b94d | a36aa1b37cd250c80ca8727724983632bc66e863 |
refs/heads/master | <file_sep>import Vue from 'vue';
import App from './App';
import router from './router';
import axios from 'axios';
import ElementUI from 'element-ui';
import '../static/css/theme-green/index.css'; // 浅绿色主题
import "babel-polyfill";
Vue.use(ElementUI);
Vue.prototype.$ajax = axios;
new Vue({
router,
render: h => h(App)
}).$mount('#app');
/******************拦截器设置请参考这部分(开始)******************/
axios.interceptors.request.use(
config => {
const token = sessionStorage.getItem("token")
// console.log(token)
// const token = '<PASSWORD>';
if (token) {
config.headers.token = token;
}
return config
},
error => {
return Promise.reject(error)
});
/******************拦截器设置请参考这部分(结束)******************/
| 9035ccdfb5b6f825e7827848d5902fa9534f1d07 | [
"JavaScript"
] | 1 | JavaScript | jingloveing/app_manage | d8288dc5309fe1b508c26efcca6dc223ce285cf0 | eda946cf4a18b48b9451dfaa0fba90cc5b0dc6e1 |
refs/heads/master | <file_sep>/**
* Compose trigger function that fires when the compose action is
* selected. Builds and returns a compose UI for inserting images.
*
* @param {event} e The compose trigger event object. Not used in
* this example.
* @return {Card[]}
*/
function getSCQAPromptsUI(e) {
return [buildSCQAPromptsCard()];
}
var TOP_DOWN = [
{
title: "What subject are you discussing?",
fieldName: 'discussed_subject',
hint: "e.g. q4 new expansion plans"
},
{
title: "What question are you answering in your reader's mind?",
fieldName: 'question_in_reader_mind',
hint: "e.g. which age segment should we market our diapers to?"
},
{
title: "What's the answer?",
fieldName: 'answer',
hint: ""
},
];
var SCQA_PROMPTS = [
{
title: "What are the uncontroversial, unambiguous, and relevant facts?",
fieldName: 'situation',
hint: "e.g. watches are critical to our growth. 15% of sales. gateway to jewelry and shoes.",
multiline: true
},
{
title: "What change must we respond to?",
fieldName: 'complication',
hint: "e.g. repeat purchases are 10% since last month."
},
{
title: "What's the key question in the reader's mind?",
fieldName: 'question',
hint: "e.g. How do we respond to this 10% drop?"
},
{
title: "What's the answer?",
fieldName: 'answer',
hint: "e.g. Test (1) Increase cross-marketing and (2) price-promo to lapsed buyers."
},
];
/**
* Build a card to prompt the user for SCQA structure
*
* @return {Card}
*/
function buildSCQAPromptsCard() {
var card = CardService.newCardBuilder();
var cardSection = CardService.newCardSection().setHeader('SCQA');
for (var i=0; i < SCQA_PROMPTS.length; i++) {
var prompt = SCQA_PROMPTS[i];
cardSection.addWidget(
CardService.newTextInput()
.setTitle(prompt.title)
.setFieldName(prompt.fieldName)
.setHint(prompt.hint)
.setMultiline(!!prompt.multiline)
);
}
cardSection.addWidget(
CardService.newTextButton()
.setText('insert into email')
.setOnClickAction(
CardService.newAction()
.setFunctionName('insertSCQAToEmail')
)
);
return card.addSection(cardSection).build();
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function formatQuestion(question) {
var qTrimmed = question.trim();
var endsWithQMark = qTrimmed.slice(-1) === '?';
if (!endsWithQMark) {
return qTrimmed + "?";
}
else {
return qTrimmed;
}
}
function formatComplication(complication) {
var cTrimmed = complication.trim();
var buts = ['But', 'However'];
var firstWord = cTrimmed.split(/[\s,]/)[0];
var startsWithBut = buts.indexOf(firstWord) != -1;
if (!startsWithBut) {
return "But " + cTrimmed;
}
else {
return cTrimmed;
}
};
function formatEmail(formInput) {
return "" + formInput.situation.trim() + '<br/><br/><br/>'
+ formatComplication(formInput.complication) + '<br/><br/>'
+ formatQuestion(formInput.question) + '<br/><br/>'
+ formInput.answer.trim();
}
/**
* inserts the SCQA into the body of the email.
*
* @param {event} e The incoming event object.
* @return {UpdateDraftActionResponse}
*/
function insertSCQAToEmail(e) {
var updateDraftActionResponse = CardService.newUpdateDraftActionResponseBuilder()
.setUpdateDraftBodyAction(
CardService.newUpdateDraftBodyAction()
.addUpdateContent(
formatEmail(e.formInput),
CardService.ContentType.MUTABLE_HTML)
.setUpdateType(
CardService.UpdateDraftBodyType.IN_PLACE_INSERT))
.build();
return updateDraftActionResponse;
}
<file_sep>Copyright 2019 - present, <NAME>
# pyramid gmail addon
Helps you construct clear, logical messages for your recipient.
### guide to push/pull/publish with clasp
clasp pull
clasp push
etc.
# for my own reference
* gmail scopes: https://developers.google.com/gmail/add-ons/concepts/scopes#gmail_add-on_scopes
| 3f9876110b0ffe051c9662bcb5b11a27196f12a4 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | benmathes/pyramid_gmail_addon | c5e1b4dcb4099be91b2bc18eb086eee4a9e4fd58 | bb673c4da6f2f67d940358c0e932d48f306902d9 |
refs/heads/master | <repo_name>2220227512/ssm-search<file_sep>/src/main/java/com/taotao/search/mapper/ItemMapper.java
package com.taotao.search.mapper;
import java.util.List;
import com.taotao.search.pojo.Item;
/**
* solr 获得商品信息mapper
* <p>Title: ItemMapper</p>
* <p>Description: </p>
* @author 唯
* @date 2018-1-14
*/
public interface ItemMapper {
List<Item> getItemAll();
}
<file_sep>/src/main/java/com/taotao/search/service/impl/SearchServiceImpl.java
package com.taotao.search.service.impl;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.SearchService;
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private SearchDao searchDao;
@Override
public SearchResult getALlSearch(String queryString, int page, int rows)
throws Exception {
//创建查询对象
SolrQuery query=new SolrQuery();
query.setQuery(queryString);
//设置分页
query.setStart((page-1)*rows);
query.setRows(rows);
//设置默认搜素域
query.set("df", "item_keywords");
//设置高亮显示
query.setHighlight(true);
query.addHighlightField("item_title");
query.setHighlightSimplePre("<em style=\"color:red\">");
query.setHighlightSimplePost("</em>");
//执行查询
SearchResult allSearch = searchDao.getAllSearch(query);
//计算查询结果总页数
long recordCount = allSearch.getRecordCount();
/*long pageCount = recordCount / rows;
if (recordCount % rows > 0) {
pageCount++;
}*/
long pageCount=recordCount % rows > 0?recordCount / rows+1:recordCount / rows;
allSearch.setPageCount(pageCount);
allSearch.setCurPage(page);
return allSearch;
}
}
| 0c1f01a2afa633b39606a3682b2d791f4fed9048 | [
"Java"
] | 2 | Java | 2220227512/ssm-search | 98deee8de4fa76e62fdb1c09b668b69be7eeb580 | 036d35fd896e1d5936fca27693e75b819e5f0851 |
refs/heads/main | <repo_name>celiamacrae/TriviaGame<file_sep>/server/api/questions.js
const router = require('express').Router()
const {Question} = require('../db/models')
module.exports = router
const shuffle = require('../helpers')
router.get('/', async (req, res, next) => {
try {
const questions = await Question.findAll()
let shuffledQs = shuffle(questions).slice(0, 10)
res.json(shuffledQs)
} catch (err) {
next(err)
}
})
router.post('/', async (req, res, next) => {
try {
const question = await Question.create(req.body)
res.send(question)
} catch (err) {
next(err)
}
})
<file_sep>/server/helpers.spec.js
const {expect} = require('chai')
import shuffle from './helpers'
describe('Helper functions', () => {
let arr = []
for (let i = 0; i < 1000; i++) {
arr.push(i)
}
it('shuffle', () => {
const shuffle1 = shuffle(arr)
const shuffle2 = shuffle(arr)
expect(shuffle1).to.equal(shuffle2)
})
})
<file_sep>/README.md
# Tandem Trivia Challenge
_Created by <NAME>_
Tech Stack:
`node.js`
`express`
`sequelize`
`react`
`redux`
`mocha`
`chai`
(refer to package.json to see all dependencies)
Check out the deployed version here
[Tandem Trivia App][trivia-link]
[trivia-link]: https://tandem-trivia-challenge.herokuapp.com/game
## Setup
To use this as trivia app, you'll need to take the following steps:
* Fork & clone this repo to your local machine.
* run `npm install` command to install dependencies
* Create two postgres databases (`MY_APP_NAME` should match the `name`
parameter in `package.json`):
```
export MY_APP_NAME=trivia
createdb $trivia
createdb $trivia-test
```
* By default, running `npm test` will use `trivia-test`, while
regular development uses `trivia`
* Running `npm run start-dev` will make great things happen!
If you want to run the server and/or `webpack` separately, you can also
`npm run start-server` and `npm run build-client`.
From there, just follow your bliss.
## Features of this Application
* [x] User login is required to keep track of max score and rounds played
* [x] A leaderboard component lists top performers by nickname
* [x] User can play a round of trivia, consisting of 10 questions
* [x] For each round of trivia, questions are randomized
* [x] For each question, answers will be displayed in random order
* [x] After each question, user will be notifyed whether or not they got the question correct and score will update in live time
* [x] At the end of a round, user will be given their final score and user will be prompted to checkout how they compare to others by viewing scoreboard
* [x] Code features several unit tests on front-end and back-end
## Future Goals
* [ ] Improve Design -- with very limited time to create this project I focused on functionality over appearence.
* [ ] Add more unit tests -- again, with limited time I was not able to implement as many unit tests as I would have liked to but I did try to implement a variety of tests to show proficiency.
<file_sep>/client/components/gameboard.js
import logger from 'redux-logger'
import React from 'react'
const Board = props => {
const q = props.q
let shuffledQuestions = props.shuffleQuestions(
q.correct,
q.incorrect1,
q.incorrect2,
q.incorrect3
)
return (
<div id="board">
<h1>Question # {props.num}</h1>
<h3>{q.q}</h3>
<div id="buttons">
{shuffledQuestions.map(question => {
return (
<button
className="ansbox"
disabled={props.selected}
onClick={props.selectBox}
value={question}
>
{question}
</button>
)
})}
</div>
</div>
)
}
export default Board
<file_sep>/client/components/leaderboard.js
import React from 'react'
import {connect} from 'react-redux'
import {fetchUsers} from '../store/allUsers'
class LeaderBoard extends React.Component {
constructor() {
super()
}
async componentDidMount() {
await this.props.fetchUsers()
}
render() {
const users = this.props.users
return users.length ? (
<div id="leaderboard">
<h3>LEADERBOARD</h3>
<table>
<thead>
<tr>
<th>Nickname</th>
<th>Points</th>
</tr>
</thead>
<tbody>
{users.map(user => {
if (user.points > 0) {
return (
<tr key={user.id}>
<td>{user.nickname}</td>
<td>{user.points}</td>
</tr>
)
}
})}
</tbody>
</table>
</div>
) : (
<div />
)
}
}
const mapState = state => ({
users: state.allUsers
})
const mapDispatch = dispatch => ({
fetchUsers: () => dispatch(fetchUsers())
})
export default connect(mapState, mapDispatch)(LeaderBoard)
<file_sep>/server/helpers.js
function shuffle(arr) {
let currIdx = arr.length
let tempVal
let randomIdx
while (currIdx !== 0) {
randomIdx = Math.floor(Math.random() * currIdx)
currIdx -= 1
tempVal = arr[currIdx]
arr[currIdx] = arr[randomIdx]
arr[randomIdx] = tempVal
}
return arr
}
module.exports = shuffle
<file_sep>/client/store/allUsers.js
import axios from 'axios'
import history from '../history'
/**
* ACTION TYPES
*/
const GET_ALL_USERS = 'GET_ALL_USERS'
/**
* INITIAL STATE
*/
const defaultUsers = []
/**
* ACTION CREATORS
*/
const getAllUsers = users => ({type: GET_ALL_USERS, users})
/**
* THUNK CREATORS
*/
export const fetchUsers = () => async dispatch => {
try {
let res = await axios.get('/api/users')
dispatch(getAllUsers(res.data))
} catch (err) {
console.error(err)
}
}
/**
* REDUCER
*/
export default function(state = defaultUsers, action) {
switch (action.type) {
case GET_ALL_USERS:
return action.users
default:
return state
}
}
<file_sep>/server/db/models/question.js
const crypto = require('crypto')
const Sequelize = require('sequelize')
const db = require('../db')
const Question = db.define('question', {
q: {
type: Sequelize.STRING,
allowNull: false
},
correct: {
type: Sequelize.STRING,
allowNull: false
},
incorrect1: {
type: Sequelize.STRING,
allowNull: false
},
incorrect2: {
type: Sequelize.STRING,
allowNull: false
},
incorrect3: {
type: Sequelize.STRING,
allowNull: false
}
})
module.exports = Question
<file_sep>/server/api/questions.spec.js
/* global describe beforeEach it */
const {expect} = require('chai')
const request = require('supertest')
const db = require('../db')
const app = require('../index')
const Question = db.model('question')
describe('Question routes', () => {
beforeEach(() => {
return db.sync({force: true})
})
const newQuestion = {
q: 'New Question',
correct: 'Correct Answer for New Q',
incorrect1: 'incorrect1 Answer for New Q',
incorrect2: 'incorrect2 Answer for New Q',
incorrect3: 'incorrect3 Answer for New Q'
}
beforeEach(() => {
return Question.create({
q: 'Question',
correct: 'Correct Answer',
incorrect1: 'incorrect1',
incorrect2: 'incorrect2',
incorrect3: 'incorrect3'
})
})
describe('/api/questions/', () => {
it('GET /api/questions', async () => {
const res = await request(app)
.get('/api/questions')
.expect(200)
expect(res.body).to.be.an('array')
expect(res.body[0].correct).to.be.equal('Correct Answer')
})
it('POST /api/questions', async () => {
const res = await request(app)
.post('/api/questions')
.send(newQuestion)
.expect(200)
let question = await Question.findOne({where: {q: 'New Question'}})
expect(res.body).to.be.an('object')
expect(question.q).to.be.equal(newQuestion.q)
})
}) // end describe('/api/questions')
}) // end describe('Question routes')
<file_sep>/client/components/answer.js
import logger from 'redux-logger'
import React from 'react'
import {Link} from 'react-router-dom'
const Answer = props => {
return props.selected ? (
<div id="answer">
<h1>{props.correct}</h1>
{props.correct === 'Incorrect' ? (
<h3>The correct answer is "{props.correctAnswer}"</h3>
) : (
<div />
)}
{props.counter < 9 ? (
<button
id="next"
onClick={props.nextQuestion}
disabled={props.counter === 9}
>
Next Question
</button>
) : (
<div id="finalscore">
<h3>You answered {props.score}/10 questions correctly.</h3>
<Link to="/leaderboard">
<button id="next">View Leaderboard</button>
</Link>
</div>
)}
</div>
) : (
<div />
)
}
export default Answer
<file_sep>/server/api/users.js
const router = require('express').Router()
const {User} = require('../db/models')
module.exports = router
router.get('/', async (req, res, next) => {
try {
const users = await User.findAll({
// explicitly select only the id and email fields - even though
// users' passwords are encrypted, it won't help if we just
// send everything to anyone who asks!
attributes: ['id', 'email', 'nickname', 'points', 'roundsPlayed']
})
let copy = [...users]
copy.sort((a, b) => b.points - a.points)
res.json(copy)
} catch (err) {
next(err)
}
})
router.put('/:userid/addRound', async (req, res, next) => {
try {
const userid = req.params.userid
let user = await User.findOne({
where: {
id: req.params.userid
}
})
let newRounds = user.roundsPlayed + 1
user.update({roundsPlayed: newRounds})
res.send(user)
} catch (err) {
next(err)
}
})
router.put('/:userid/updatePoints', async (req, res, next) => {
try {
const userid = req.params.userid
let user = await User.findOne({
where: {
id: req.params.userid
}
})
let newPoints = req.body.points
await user.update({points: newPoints})
res.send(user)
} catch (err) {
next(err)
}
})
<file_sep>/script/seed.js
'use strict'
const db = require('../server/db')
const {User, Question} = require('../server/db/models')
async function seed() {
await db.sync({force: true})
console.log('db synced!')
const users = await Promise.all([
User.create({nickname: 'Cody', email: '<EMAIL>', password: '123'}),
User.create({
nickname: 'Murphy',
email: '<EMAIL>',
password: '123'
})
])
console.log(`seeded ${users.length} users`)
const questions = await Promise.all([
Question.create({
q: 'What was Tandem previous name?',
correct: 'Devmynd',
incorrect1: 'Tandem',
incorrect2: '<NAME>',
incorrect3: 'Extraordinary Humans'
}),
Question.create({
q: "In Shakespeare's play Julius Caesar, Caesar's last words were...",
correct: 'Et tu, Brute?',
incorrect1: 'Iacta alea est!',
incorrect2: 'Vidi, vini, vici',
incorrect3: 'Aegri somnia vana'
}),
Question.create({
q: 'A group of tigers are referred to as:',
correct: 'Ambush',
incorrect1: 'Chowder',
incorrect2: 'Pride',
incorrect3: 'Destruction'
}),
Question.create({
q: 'What is the top speed an average cat can travel?',
correct: '31 mph',
incorrect1: '42 mph',
incorrect2: '13 mph',
incorrect3: '9 mph'
}),
Question.create({
q: 'A cat can jump to _____ times its own height:',
correct: '5',
incorrect1: '3',
incorrect2: '9',
incorrect3: '7'
}),
Question.create({
q: "What is the only letter that doesn't appear in a US state name?",
correct: 'Q',
incorrect1: 'M',
incorrect2: 'Z',
incorrect3: 'X'
}),
Question.create({
q: 'What is the name for a cow-bison hybrid?',
correct: 'Beefalo',
incorrect1: 'Cowson',
incorrect2: 'Bicow',
incorrect3: 'Mooson'
}),
Question.create({
q: 'What is the largest freshwater lake in the world?',
correct: 'Lake Superior',
incorrect1: 'Lake Baikal',
incorrect2: 'Lake Michigan',
incorrect3: 'Lake Victoria'
}),
Question.create({
q:
'In a game of bingo, what number is represented by the name two little ducks?',
correct: '22',
incorrect1: '20',
incorrect2: '55',
incorrect3: '77'
}),
Question.create({
q: 'According to Greek mythology, who was the first woman on Earth?',
correct: 'Pandora',
incorrect1: 'Lilith',
incorrect2: 'Eve',
incorrect3: 'Hera'
}),
Question.create({
q: 'In which European city would you find Orly airport?',
correct: 'Paris',
incorrect1: 'London',
incorrect2: 'Belgium',
incorrect3: 'Munich'
}),
Question.create({
q: 'Where would you find the Sea of Tranquility?',
correct: 'The Moon',
incorrect1: 'California',
incorrect2: 'Siberia',
incorrect3: 'China'
}),
Question.create({
q: "Which artist painted 'Girl with a <NAME>'?",
correct: 'Vermeer',
incorrect1: '<NAME>',
incorrect2: 'Picasso',
incorrect3: '<NAME>'
}),
Question.create({
q: "What is the official name for the 'hashtag' symbol?",
correct: 'Octothorpe',
incorrect1: 'Number sign',
incorrect2: 'Hash Sign',
incorrect3: 'Pound'
}),
Question.create({
q: 'Not American at all, where is apple pie from?',
correct: 'England',
incorrect1: 'Japan',
incorrect2: 'Ethiopia',
incorrect3: 'Canada'
}),
Question.create({
q: 'What is the national animal of Scotland?',
correct: 'Unicorn',
incorrect1: 'Bear',
incorrect2: 'Rabbit',
incorrect3: 'Seal'
}),
Question.create({
q: 'Where in the world is the only place where Canada is *due south*',
correct: 'Detroit',
incorrect1: 'Alaska',
incorrect2: 'Russia',
incorrect3: 'Washington'
}),
Question.create({
q: 'Approximately how many grapes go into a bottle of wine?',
correct: '700',
incorrect1: '500',
incorrect2: '200',
incorrect3: '1000'
}),
Question.create({
q: 'How much does a US One Dollar Bill cost to make?',
correct: '$0.05',
incorrect1: '$0.25',
incorrect2: '$1',
incorrect3: '$5'
}),
Question.create({
q:
'The Vatican bank has the only ATM in the world that allows users to do what?',
correct: 'Perform transactions in Latin',
incorrect1: 'Receive withdrawls in rosary beads',
incorrect2: 'Vote for the Pope',
incorrect3: 'Purchase indulgences'
}),
Question.create({
q: 'In a website address bar, what does WWW stand for?',
correct: 'World Wide Web',
incorrect1: 'Wild Wild West',
incorrect2: 'War World Web',
incorrect3: 'Wide World Web'
})
])
console.log(`seeded ${questions.length} questions`)
console.log(`seeded successfully`)
}
// We've separated the `seed` function from the `runSeed` function.
// This way we can isolate the error handling and exit trapping.
// The `seed` function is concerned only with modifying the database.
async function runSeed() {
console.log('seeding...')
try {
await seed()
} catch (err) {
console.error(err)
process.exitCode = 1
} finally {
console.log('closing db connection')
await db.close()
console.log('db connection closed')
}
}
// Execute the `seed` function, IF we ran this module directly (`node seed`).
// `Async` functions always return a promise, so we can use `catch` to handle
// any errors that might occur inside of `seed`.
if (module === require.main) {
runSeed()
}
// we export the seed function for testing purposes (see `./seed.spec.js`)
module.exports = seed
<file_sep>/client/components/myPoints.js
import logger from 'redux-logger'
import React from 'react'
const MyPoints = props => {
return (
<div id="my_points">
<h3 id="curr_points">Current Points: {props.currScore}</h3>
</div>
)
}
export default MyPoints
| 5c4804138fcbee4c53bbf38feb1ec5c4ab41acb1 | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | celiamacrae/TriviaGame | 75ce868758c0c6cc72c26b041521a8c34b89e988 | 09a8ee1b9164aad0a5106996e6531e15ebdbf150 |
refs/heads/master | <repo_name>ESTECHTI/ChatApp<file_sep>/src/Colors.js
export const redColor = '#ff0000';
export const strongYellow = '#e29802';
export const lightGray = '#adadad';
export const whiteColor = '#fff';
export const beigeColor = '#eee4dc';
export const blackColor = '#000000';
export const lightGreen = '#fc914e';<file_sep>/src/components/FormLogin.js
import React, { Component } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Actions } from 'react-native-router-flux';
import { connect } from 'react-redux';
import { modificaEmail, modificaSenha, autenticarUsuario } from '../actions/AutenticacaoActions';
import { redColor, strongYellow, lightGray, whiteColor } from '../Colors';
class formLogin extends Component {
_autenticarUsuario() {
const { email, senha } = this.props;
this.props.autenticarUsuario({ email, senha });
this.props.navigation.navigate('Principal')
}
renderBtnAcessar(){
if(this.props.loading_login) {
return (
<ActivityIndicator size= "large" color= {redColor}/>
)
}
return(
<TouchableOpacity style={{
backgroundColor: redColor,
height: 40,
borderRadius: 20,
justifyContent: 'center', }}
onPress={() => this._autenticarUsuario()}
>
<Text style={{ alignSelf: 'center', fontSize: 20, color: whiteColor }}>Acessar</Text>
</TouchableOpacity>
)
}
render(){
return(
<View style={{ flex: 1, padding: 10, backgroundColor: whiteColor }}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row' }}>
<Text style={{ fontSize: 25, color: redColor }}>TellMe</Text>
<Icon name='forum' size={40} color= {redColor} />
</View>
<View style={{ flex: 2 }}>
<TextInput value={this.props.email} style={{ fontSize: 20, height: 45, color: redColor }} placeholder="E-mail" placeholderTextColor={redColor} onChangeText={texto => this.props.modificaEmail(texto)}/>
<TextInput secureTextEntry value={this.props.senha} style={{ fontSize: 20, height: 45, color: redColor }} placeholder="Senha" placeholderTextColor={redColor} onChangeText={texto => this.props.modificaSenha(texto)}/>
<Text style={{ fontSize: 18, color: strongYellow }}>{this.props.erroLogin}</Text>
<TouchableOpacity onPress={() => Actions.formCadastro()}>
<Text style={{ fontSize: 18, color: lightGray }}>
Ainda não tem cadastro? Cadastra-se!
</Text>
</TouchableOpacity>
</View>
<View style={{ flex: 2 }}>
{this.renderBtnAcessar()}
</View>
</View>
)
}
}
const mapStateToProps = state => (
{
email: state.AutenticacaoReducer.email,
senha: state.AutenticacaoReducer.senha,
erroLogin: state.AutenticacaoReducer.erroLogin,
loading_login: state.AutenticacaoReducer.loading_login
}
)
export default connect(mapStateToProps, {modificaEmail, modificaSenha, autenticarUsuario})(formLogin)<file_sep>/README.md
# ChatApp
Aplicativo de Chat
<file_sep>/src/components/FormCadastro.js
import React, { Component } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import { modificaEmail, modificaSenha, modificaNome, cadastraUsuario } from '../actions/AutenticacaoActions';
import { redColor, strongYellow, whiteColor } from '../Colors';
class formCadastro extends Component {
_cadastraUsuario(){
const { nome, email, senha } = this.props;
this.props.cadastraUsuario({ nome, email, senha });
}
renderBtnCadastro() {
if(this.props.loading_cadastro) {
return (
<ActivityIndicator size= "large" color= {redColor}/>
)
}
return(
<TouchableOpacity style={{ backgroundColor: redColor, justifyContent: 'center', height: 40 }} onPress={() => this._cadastraUsuario()}>
<Text style={{ color: whiteColor, fontSize: 20, textAlign: 'center' }}>Cadastrar</Text>
</TouchableOpacity>
)
}
render(){
return(
<View style={{ flex: 1, padding: 10, backgroundColor: whiteColor }}>
<View style={{ flex: 4, justifyContent: 'center' }}>
<TextInput value={this.props.nome} placeholder="Nome" placeholderTextColor= {redColor} style={{ fontSize: 20, height: 45, color: redColor }} onChangeText={texto => this.props.modificaNome(texto)}/>
<TextInput value={this.props.email} placeholder="E-mail" placeholderTextColor= {redColor} style={{ fontSize: 20, height: 45, color: redColor }} onChangeText={texto => this.props.modificaEmail(texto)}/>
<TextInput secureTextEntry value={this.props.senha} placeholder="Senha" placeholderTextColor= {redColor} style={{ fontSize: 20, height: 45, color: redColor }} onChangeText={texto => this.props.modificaSenha(texto)}/>
<Text style={{ color: strongYellow, fontSize: 18 }}>{this.props.erroCadastro}</Text>
</View>
<View style={{ flex: 1 }}>
{this.renderBtnCadastro()}
</View>
</View>
)
}
}
const mapStateToProps = state => {
return(
{
nome: state.AutenticacaoReducer.nome,
email: state.AutenticacaoReducer.email,
senha: state.AutenticacaoReducer.senha,
erroCadastro: state.AutenticacaoReducer.erroCadastro,
loading_cadastro: state.AutenticacaoReducer.loading_cadastro
}
);
}
export default connect(mapStateToProps, {modificaEmail, modificaSenha, modificaNome, cadastraUsuario})(formCadastro);<file_sep>/App.js
import { registerRootComponent } from 'expo';
import React from 'react';
import App from './src/App';
const app = props => (
<App />
)
export default registerRootComponent(app);
<file_sep>/src/components/Conversa.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import { View, TextInput, TouchableOpacity, ListView, Text, KeyboardAvoidingView} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { redColor, strongYellow, lightGray, whiteColor, beigeColor, blackColor, lightGreen } from '../Colors';
import { modificaMensagem, enviarMensagem, conversaUsuarioFetch } from '../actions/AppActions';
class Conversa extends Component {
componentWillMount() {
this.props.conversaUsuarioFetch(this.props.contatoEmail)
this.criaFonteDeDados( this.props.conversa );
}
componentWillReceiveProps(nextProps) {
if(this.props.contatoEmail != nextProps.contatoEmail) {
this.props.conversaUsuarioFetch(nextProps.contatoEmail)
}
this.criaFonteDeDados(nextProps.conversa);
}
criaFonteDeDados( conversa ) {
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.dataSource = ds.cloneWithRows( conversa )
}
_enviarMensagem() {
const { mensagem, contatoNome, contatoEmail } = this.props;
this.props.enviarMensagem(mensagem, contatoNome, contatoEmail)
}
renderRow(texto) {
if(texto.tipo === 'e') {
return (
<View style={{ alignItems: 'flex-end', marginTop: 5, marginBottom: 5, marginLeft: 40 }}>
<Text style={{
fontSize: 18,
borderRadius: 8,
color: whiteColor,
padding: 10,
backgroundColor: lightGreen,
elevation: 1
}}>{texto.mensagem}</Text>
</View>
)
}
return (
<View style={{ alignItems: 'flex-start', marginTop: 5, marginBottom: 5, marginRight: 40 }}>
<Text style={{
fontSize: 18,
borderRadius: 8,
color: whiteColor,
padding: 10,
backgroundColor: lightGreen,
elevation: 1
}}>{texto.mensagem}</Text>
</View>
)
}
render(){
return(
<View style={{ flex: 1, backgroundColor: beigeColor, padding: 10 }}>
<View style={{flex: 1, paddingBottom: 20 }}>
<ListView
enableEmptySections
dataSource={this.dataSource}
renderRow={this.renderRow}
/>
<View style={{ flexDirection: 'row', height: 60 }}>
<TextInput
value={this.props.mensagem}
onChangeText={texto => this.props.modificaMensagem(texto)}
style={{ flex: 4, backgroundColor: whiteColor, fontSize: 18, borderRadius: 15 }}
keyboardType='default'
/>
<TouchableOpacity
onPress={this._enviarMensagem.bind(this)}
>
<Icon name='paper-plane' size={40} color= {redColor}/>
</TouchableOpacity>
</View>
</View>
</View>
)
}
}
mapStateToProps = state => {
const conversa = _.map(state.ListaConversaReducer, (val, uid) => {
return { ...val, uid };
});
return ({
conversa,
mensagem: state.AppReducer.mensagem
})
}
export default connect(mapStateToProps, { modificaMensagem, enviarMensagem, conversaUsuarioFetch })(Conversa) | c84ed5ca363bb9ae1118c2557d4c5a17bc67ea54 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | ESTECHTI/ChatApp | 05863a696fd6d2e41e861e2fd0b624c63cdb01c3 | f9de06a4f69fe090331937a57d1ec6584e8fb41c |
refs/heads/master | <file_sep>DROP DATABASE IF EXISTS bamazon_DB;
CREATE DATABASE bamazon_DB;
USE bamazon_DB;
CREATE TABLE products
(
item_id INT NOT NULL
AUTO_INCREMENT,
product_name VARCHAR
(100) NOT NULL,
department_name VARCHAR
(45) NOT NULL,
price INT default 0,
stock_quantity INT default 0,
PRIMARY KEY
(item_id)
);
INSERT INTO products
(product_name, department_name, price, stock_quantity)
VALUES
("MagicEraser", "cleaning", 4.00, 7),
("Wheel", "automotive", 250.00, 4),
("Microphone", "entertainment", 150.50, 9),
("Headphones", "entertainment", 124.99, 6),
("Mouse", "entertainment", 115.00, 2),
("Headphones", "entertainment", 74.56, 11),
("Bike", "excersise", 82.00, 4),
("Pants", "apparel", 16.48, 6),
("Running Shoes", "apparel", 14.37, 16),
("Shirt", "apparel", 11.24, 7),
("Pants", "apparel", 16.48, 6);
<file_sep>var mysql = require('mysql');
var inquirer = require('inquirer');
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "",
database: "bamazon_DB"
});
connection.connect(function (err) {
if (err) throw err;
connection.query("SELECT * FROM products", function (err, result) {
if (err) throw err;
selectItem(result);
})
});
function selectItem(result) {
console.log(result);
inquirer.prompt([
{
name: "product",
type: "input",
message: "What is the id of the item you would like to buy?"
},
{
name: "quantity",
type: "input",
message: "How many units would you like to buy?"
}
])
.then(function (answer) {
var id = answer.product;
var howMany = answer.quantity;
var chosenItem;
connection.query(`SELECT * FROM products WHERE item_id = ${id}`, function (err, result) {
console.log(`
The information for the item you requested is:
Item ID: ${result[0].item_id}
Product Name: ${result[0].product_name}
Department Name:${result[0].department_name}
Unit Price: ${result[0].price}
Stock Avaliable: ${result[0].stock_quantity}
`);
if (result[0].stock_quantity >= howMany) {
// result[0].stock_quantity -= howMany;
connection.query(`UPDATE products SET stock_quantity = ${result[0].stock_quantity} - ${howMany} WHERE item_id = ${id}`);
console.log(`The new avaliable stock is ${result[0].stock_quantity - howMany}`);
}
else console.log(`I'm sorry, there are not enough units avaliable`);
});
})
};
| 8e222dc7ddd9c7d6f5734b0e701856dc6356044b | [
"JavaScript",
"SQL"
] | 2 | SQL | DavidVizena/bamazon | 9ff9d7a92e970c141659e4beefae274f1e611a8f | 8190394c4576b3f2bcafd4871830dabd2c8d1bd8 |
refs/heads/master | <repo_name>borainlee/bigNews<file_sep>/assets/js/article/art_list.js
$(function () {
var layer = layui.layer
var form = layui.form
var laypage = layui.laypage
// 定义美化时间的过滤器
template.defaults.imports.dataFormat = function (date) {
const dt = new Date(date)
var y = padZero(dt.getFullYear())
var m = padZero(dt.getMonth() + 1)
var d = padZero(dt.getDate())
var hh = padZero(dt.getHours())
var mm = padZero(dt.getMinutes())
var ss = padZero(dt.getSeconds())
return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
}
// 定义补零操作
function padZero(n) {
return n > 9 ? n : '0' + n
}
// 定义查询参数对象
// 请求数据时,将请求参数对象提交到服务器
var q = {
pagenum: 1, //页码值,默认为1
pagesize: 2,//每页显示数据,默认2
cate_id: '', //文章分类id
state: '' //文章发布状态
}
initTable()
initCate()
//获取文章列表
function initTable() {
$.ajax({
url: '/my/article/list',
method: 'GET',
data: q,
success: function (res) {
if (res.status !== 0) {
return layer.msg(res.message)
}
var tableHtml = template('tpl-table', res)
$('tbody').html(tableHtml)
// 调用渲染分页
renderPage(res.total)
}
})
}
// 渲染所有分类
function initCate() {
$.ajax({
url: '/my/article/cates',
method: 'GET',
success: function (res) {
if (res.status !== 0) {
return layer.msg(res.message)
}
var cateHtml = template('tpl-cate', res)
console.log(cateHtml);
$('.layui-form [name=cate_id]').html(cateHtml)
// 通过layui重新渲染ui结构
form.render()
}
})
}
// 筛选
$('#form-search').on('submit', function (e) {
e.preventDefault()
var newCateId = $('.layui-form [name=cate_id]').val()
var newState = $('.layui-form [name=state]').val()
q.state = newState
q.cate_id = newCateId
initTable()
})
// 定义渲染分页的方法
function renderPage(total) {
// 调用laypage.render()方法渲染分页的结构
laypage.render({
elem: 'pageBox', //分页器的id
count: total, //总数据条数
limit: q.pagesize, //每页的条数
curr: q.pagenum, //起始页面
layout: ['count', 'limit', 'prev', 'page', 'next', 'skip', 'refresh'],
limits: [2, 3, 5, 10],
// 分页发生切换的时候,触发jump回调
// 初始化的时候,调用laypage.render
// 点击页码,会触发
jump: function (obj, first) {
console.log(obj.curr);
console.log(first);
// 把最新的页码值赋值给q
q.pagenum = obj.curr
// 把最新的条目数赋值给q
q.pagesize = obj.limit
// 根据最新的q过去对应的数据列表,并渲染表格
// 如果first是ture,说明在初始化时,不调用initTable()
// 如果不是,调用
if (!first) {
initTable()
}
}
})
}
// 删除文章
$('tbody').on('click', '#delete-btn', function (e) {
e.preventDefault()
// 获取删除按钮的个数
var len = $('#delete-btn').length
var artId = $(this).attr('data-id')
layer.confirm('是否删除文章?', { icon: 3, title: '提示' }, function (index) {
//do something
$.ajax({
url: `/my/article/delete/${artId}`,
method: 'GET',
success: function (res) {
if (res.status !== 0) {
return layer.msg(res.message)
}
layer.msg('删除成功')
if (len === 1) {
// 当按钮只有一个时
q.pagenum = q.pagenum === 1 ? 1 : q.pagenum - 1
}
initTable()
layer.close(index);
}
})
});
})
}) | 413c5505c45bba404d4e86e85e21dca53e8bfedb | [
"JavaScript"
] | 1 | JavaScript | borainlee/bigNews | 89cc6a7f23a921c1d563bd913c7758fa118ee468 | a3e8b9033654901f8f7d1a6f502763ca5cc871c6 |
refs/heads/master | <repo_name>dkkim93/vicon_optitrack_merge<file_sep>/src/trajectory/data.py
import numpy as np
from transformation import Transformation
class Data(object):
def __init__(self):
self.vicon_lists = []
self.vicon_ts = []
self.vicon_x = []
self.vicon_y = []
self.vicon_z = []
self.vicon_qw = []
self.vicon_qx = []
self.vicon_qy = []
self.vicon_qz = []
self.opti_lists = []
self.opti_ts = []
self.opti_x = []
self.opti_y = []
self.opti_z = []
self.opti_qw = []
self.opti_qx = []
self.opti_qy = []
self.opti_qz = []
self.opti_orig_lists = [] # Original (i.e., opti to wand) before transformation
self.opti_orig_ts = []
self.opti_orig_x = []
self.opti_orig_y = []
self.opti_orig_z = []
self.opti_orig_qw = []
self.opti_orig_qx = []
self.opti_orig_qy = []
self.opti_orig_qz = []
self.T_ts = []
self.T_x = []
self.T_y = []
self.T_z = []
self.T_qw = []
self.T_qx = []
self.T_qy = []
self.T_qz = []
self.T_vicon_to_opti_positions = []
self.T_vicon_to_opti_quats = []
self.T_obj = Transformation()
def add_vicon_data(self, data):
self.vicon_lists.append(data)
def add_opti_data(self, data):
self.opti_lists.append(data)
def add_opti_orig_data(self, data):
self.opti_orig_lists.append(data)
def set_vicon(self):
self.vicon_ts = np.asarray([data[0] for data in self.vicon_lists])
self.vicon_x = np.asarray([data[1] for data in self.vicon_lists])
self.vicon_y = np.asarray([data[2] for data in self.vicon_lists])
self.vicon_z = np.asarray([data[3] for data in self.vicon_lists])
self.vicon_qw = np.asarray([data[4] for data in self.vicon_lists])
self.vicon_qx = np.asarray([data[5] for data in self.vicon_lists])
self.vicon_qy = np.asarray([data[6] for data in self.vicon_lists])
self.vicon_qz = np.asarray([data[7] for data in self.vicon_lists])
def set_opti(self):
self.opti_ts = np.asarray([data[0] for data in self.opti_lists])
self.opti_x = np.asarray([data[1] for data in self.opti_lists])
self.opti_y = np.asarray([data[2] for data in self.opti_lists])
self.opti_z = np.asarray([data[3] for data in self.opti_lists])
self.opti_qw = np.asarray([data[4] for data in self.opti_lists])
self.opti_qx = np.asarray([data[5] for data in self.opti_lists])
self.opti_qy = np.asarray([data[6] for data in self.opti_lists])
self.opti_qz = np.asarray([data[7] for data in self.opti_lists])
def set_opti_orig(self):
self.opti_orig_ts = np.asarray([data[0] for data in self.opti_orig_lists])
self.opti_orig_x = np.asarray([data[1] for data in self.opti_orig_lists])
self.opti_orig_y = np.asarray([data[2] for data in self.opti_orig_lists])
self.opti_orig_z = np.asarray([data[3] for data in self.opti_orig_lists])
self.opti_orig_qw = np.asarray([data[4] for data in self.opti_orig_lists])
self.opti_orig_qx = np.asarray([data[5] for data in self.opti_orig_lists])
self.opti_orig_qy = np.asarray([data[6] for data in self.opti_orig_lists])
self.opti_orig_qz = np.asarray([data[7] for data in self.opti_orig_lists])
def find_nearest_idx(self, array, value):
idx = (np.abs(array-value)).argmin()
return idx
def diff(self, value_1, value_2):
return np.absolute(value_1 - value_2)
def optimize_T(self):
for vicon_idx in range(len(self.vicon_ts)):
opti_idx = self.find_nearest_idx(self.opti_ts, self.vicon_ts[vicon_idx])
x_diff = self.diff(self.vicon_x[vicon_idx], self.opti_x[opti_idx])
y_diff = self.diff(self.vicon_y[vicon_idx], self.opti_y[opti_idx])
z_diff = self.diff(self.vicon_z[vicon_idx], self.opti_z[opti_idx])
qw_diff = self.diff(np.absolute(self.vicon_qw[vicon_idx]), np.absolute(self.opti_qw[opti_idx]))
qx_diff = self.diff(np.absolute(self.vicon_qx[vicon_idx]), np.absolute(self.opti_qx[opti_idx]))
qy_diff = self.diff(np.absolute(self.vicon_qy[vicon_idx]), np.absolute(self.opti_qy[opti_idx]))
qz_diff = self.diff(np.absolute(self.vicon_qz[vicon_idx]), np.absolute(self.opti_qz[opti_idx]))
if x_diff <= 0.03 and y_diff <= 0.03 and z_diff <= 0.03 and \
qw_diff <= 0.03 and qx_diff <= 0.03 and qy_diff <= 0.03 and qz_diff <= 0.03:
# T_vicon_to_wand
T_vicon_to_wand = self.T_obj.convert_to_T_matrix(
position=np.array([self.vicon_x[vicon_idx],
self.vicon_y[vicon_idx],
self.vicon_z[vicon_idx]]),
quat=np.array([self.vicon_qw[vicon_idx],
self.vicon_qx[vicon_idx],
self.vicon_qy[vicon_idx],
self.vicon_qz[vicon_idx]]))
# T_opti_to_wand
T_opti_to_wand = self.T_obj.convert_to_T_matrix(
position=np.array([self.opti_orig_x[opti_idx],
self.opti_orig_y[opti_idx],
self.opti_orig_z[opti_idx]]),
quat=np.array([self.opti_orig_qw[opti_idx],
self.opti_orig_qx[opti_idx],
self.opti_orig_qy[opti_idx],
self.opti_orig_qz[opti_idx]]))
# T_wand_to_opti
T_wand_to_opti = self.T_obj.inverse_matrix(T_opti_to_wand)
# T_vicon_to_opti
T_vicon_to_opti = np.dot(T_vicon_to_wand, T_wand_to_opti)
T_vicon_to_opti_position, T_vicon_to_opti_quat = \
self.T_obj.convert_T_matrix_to_position_and_quat(T_vicon_to_opti)
print 'T_vicon_to_opti: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
T_vicon_to_opti_position, T_vicon_to_opti_quat)
# Save result
self.T_vicon_to_opti_positions.append(T_vicon_to_opti_position)
self.T_vicon_to_opti_quats.append(T_vicon_to_opti_quat)
# Add data for visualization
self.T_ts.append(self.opti_ts[opti_idx])
self.T_x.append(self.opti_x[opti_idx])
self.T_y.append(self.opti_y[opti_idx])
self.T_z.append(self.opti_z[opti_idx])
self.T_qw.append(self.opti_qw[opti_idx])
self.T_qx.append(self.opti_qx[opti_idx])
self.T_qy.append(self.opti_qy[opti_idx])
self.T_qz.append(self.opti_qz[opti_idx])
print len(self.T_vicon_to_opti_positions)
print np.mean(self.T_vicon_to_opti_positions, axis=0)
print np.mean(self.T_vicon_to_opti_quats, axis=0)
def error(self):
x_err = []
y_err = []
z_err = []
qx_err = []
qy_err = []
qz_err = []
qw_err = []
self.vicon_ts = self.vicon_ts[::5]
self.vicon_x = self.vicon_x[::5]
self.vicon_y = self.vicon_y[::5]
self.vicon_z = self.vicon_z[::5]
self.vicon_qw = self.vicon_qw[::5]
self.vicon_qx = self.vicon_qx[::5]
self.vicon_qy = self.vicon_qy[::5]
self.vicon_qz = self.vicon_qz[::5]
self.opti_ts = self.opti_ts[::5]
self.opti_x = self.opti_x[::5]
self.opti_y = self.opti_y[::5]
self.opti_z = self.opti_z[::5]
self.opti_qw = self.opti_qw[::5]
self.opti_qx = self.opti_qx[::5]
self.opti_qy = self.opti_qy[::5]
self.opti_qz = self.opti_qz[::5]
for vicon_idx in range(len(self.vicon_ts)):
print vicon_idx, '/', len(self.vicon_ts)
opti_idx = self.find_nearest_idx(self.opti_ts, self.vicon_ts[vicon_idx])
if self.diff(self.vicon_ts[vicon_idx], self.opti_ts[opti_idx]) < 0.1:
x_err.append(self.diff(self.vicon_x[vicon_idx], self.opti_x[opti_idx]))
y_err.append(self.diff(self.vicon_y[vicon_idx], self.opti_y[opti_idx]))
z_err.append(self.diff(self.vicon_z[vicon_idx], self.opti_z[opti_idx]))
qw_err.append(self.diff(self.vicon_qw[vicon_idx], -self.opti_qw[opti_idx]))
qx_err.append(self.diff(self.vicon_qx[vicon_idx], -self.opti_qx[opti_idx]))
qy_err.append(self.diff(self.vicon_qy[vicon_idx], -self.opti_qy[opti_idx]))
qz_err.append(self.diff(self.vicon_qz[vicon_idx], -self.opti_qz[opti_idx]))
print np.mean(x_err)
print np.mean(y_err)
print np.mean(z_err)
print np.mean(qw_err)
print np.mean(qx_err)
print np.mean(qy_err)
print np.mean(qz_err)
<file_sep>/src/vicon_opti_T/main.py
import numpy as np
from data import Data
from transformation import Transformation
from pyquaternion import Quaternion
if __name__ == "__main__":
# Objects
data_obj = Data()
T_obj = Transformation()
data_keys = data_obj.return_data_keys()
T_vicon_to_opti_positions = []
T_vicon_to_opti_quats = []
for data_key in data_keys:
print '\n[ STATUS ] data_key: {}'.format(data_key)
# T_vicon_to_wand
position = data_obj.return_vicon_position(data_key)
quat = data_obj.return_vicon_quat(data_key)
T_vicon_to_wand = T_obj.convert_to_T_matrix(position, quat)
T_vicon_to_wand_position, T_vicon_to_wand_quat = \
T_obj.convert_T_matrix_to_position_and_quat(T_vicon_to_wand)
print 'T_vicon_to_wand: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
T_vicon_to_wand_position, T_vicon_to_wand_quat)
# T_opti_to_wand
position = data_obj.return_opti_position(data_key)
quat = data_obj.return_opti_quat(data_key)
T_opti_to_wand = T_obj.convert_to_T_matrix(position, quat)
T_opti_to_wand_position, T_opti_to_wand_quat = \
T_obj.convert_T_matrix_to_position_and_quat(T_opti_to_wand)
print 'T_opti_to_wand: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
T_opti_to_wand_position, T_opti_to_wand_quat)
# T_wand_to_opti
T_wand_to_opti = T_obj.inverse_matrix(T_opti_to_wand)
T_wand_to_opti_position, T_wand_to_opti_quat = \
T_obj.convert_T_matrix_to_position_and_quat(T_wand_to_opti)
print 'T_wand_to_opti: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
T_wand_to_opti_position, T_wand_to_opti_quat)
# T_vicon_to_opti
T_vicon_to_opti = np.dot(T_vicon_to_wand, T_wand_to_opti)
T_vicon_to_opti_position, T_vicon_to_opti_quat = \
T_obj.convert_T_matrix_to_position_and_quat(T_vicon_to_opti)
print 'T_vicon_to_opti: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
T_vicon_to_opti_position, T_vicon_to_opti_quat)
# Save result
T_vicon_to_opti_positions.append(T_vicon_to_opti_position)
T_vicon_to_opti_quats.append(T_vicon_to_opti_quat)
# Get average
T_vicon_to_opti_positions = np.asarray(T_vicon_to_opti_positions)
T_vicon_to_opti_quats = np.asarray(T_vicon_to_opti_quats)
print '\nAveraged T_vicon_to_opti: \nPos (x y z): {}\nQuat (w x y z): {}'.format(
np.mean(T_vicon_to_opti_positions, axis=0), np.mean(T_vicon_to_opti_quats, axis=0))
<file_sep>/src/trajectory/draw.py
import matplotlib.pyplot as plt
import seaborn as sns
class Draw(object):
def __init__(self):
dummy = 1
def draw_plot(self, vicon_ts, vicon_data, opti_ts, opti_data, T_ts, T_data,
title, xlabel, ylabel, vicon_legend, opti_legend, T_legend):
plt.figure()
plt.title(title, fontsize=18)
plt.plot(vicon_ts, vicon_data, label=vicon_legend)
plt.plot(opti_ts, opti_data, label=opti_legend)
if T_ts is not None and T_data is not None:
plt.plot(T_ts, T_data, 'o', label=T_legend)
plt.xlabel(xlabel, fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.legend()
<file_sep>/src/vicon_opti_T/data.py
import numpy as np
class Data(object):
def __init__(self):
self.vicon_positions = {}
self.opti_positions = {}
self.vicon_quats = {}
self.opti_quats = {}
self._add_vicon_data()
self._add_opti_data()
self._check_err()
"""
Data 1:
- Vicon: data_yes_adjsut/2018-02-18-23-59-26.bag
- Opti: data_yes_adjust/2018-02-18-23-59-15.bag
Data 2:
- Vicon: data_yes_adjsut/2018-02-19-00-01-43.bag
- Opti: data_yes_adjust/2018-02-19-00-01-43.bag
Data 3:
- Vicon: data_yes_adjsut/2018-02-19-00-02-24.bag
- Opti: data_yes_adjust/2018-02-19-00-02-24.bag
"""
def _add_vicon_data(self):
# Data 1
position = np.array([1.27146427388, 0.0982186137085, 0.0617510854658]) # x y z
self._add_to_dict(self.vicon_positions, 'data_1', position)
quat = np.array([0.999339563026, 0.00527315805089, 0.00285273824411, 0.0358398306381]) # w x y z
self._add_to_dict(self.vicon_quats, 'data_1', quat)
# Data 2
position = np.array([1.54398658889, -0.410228881554, 1.16198586478]) # x y z
self._add_to_dict(self.vicon_positions, 'data_3', position)
quat = np.array([0.999571524024, -0.000650802997162, 0.00282766945741, -0.0291264330444]) # w x y z
self._add_to_dict(self.vicon_quats, 'data_3', quat)
# Data 3
position = np.array([0.661849322701, -1.56916648039, 1.17596197592]) # x y z
self._add_to_dict(self.vicon_positions, 'data_4', position)
quat = np.array([0.987117015305, 0.00537348658354, 0.00700438753698, 0.159756259006]) # w x y z
self._add_to_dict(self.vicon_quats, 'data_4', quat)
def _add_opti_data(self):
# Data 1
position = np.array([-0.0284148845822, 10.7996358871, 0.0901763662696]) # x y z
self._add_to_dict(self.opti_positions, 'data_1', position)
quat = np.array([-0.700189054012, -0.00834508985281, 0.00316851167008, 0.713901758194]) # w x y z
self._add_to_dict(self.opti_quats, 'data_1', quat)
# Data 2
position = np.array([-0.56702709198, 10.5713949203, 1.17146623135]) # x y z
self._add_to_dict(self.opti_positions, 'data_3', position)
quat = np.array([0.652602374554, 0.0024211734999, 0.00287404307164, -0.757691323757]) # w x y z
self._add_to_dict(self.opti_quats, 'data_3', quat)
# Data 3
position = np.array([-1.6251026392, 11.5489768982, 1.18096828461]) # x y z
self._add_to_dict(self.opti_positions, 'data_4', position)
quat = np.array([-0.782936692238, -0.00750978616998, 0.000981374876574, 0.622055411339])
self._add_to_dict(self.opti_quats, 'data_4', quat)
def _add_to_dict(self, target_dict, key, data):
target_dict[key] = data
def _check_err(self):
if len(self.vicon_positions.keys()) != len(self.vicon_quats.keys()):
RuntimeError("[ ERROR ] vicon positions and quats don't have same number of data")
if len(self.opti_positions.keys()) != len(self.opti_quats.keys()):
RuntimeError("[ ERROR ] opti positions and quats don't have same number of data")
if len(self.vicon_positions.keys()) != len(self.opti_positions.keys()):
RuntimeError("[ ERROR ] vicon and opti don't have same number of data")
def return_data_keys(self):
return self.vicon_positions.keys()
def return_vicon_position(self, key):
return self.vicon_positions[key]
def return_vicon_quat(self, key):
return self.vicon_quats[key]
def return_opti_position(self, key):
return self.opti_positions[key]
def return_opti_quat(self, key):
return self.opti_quats[key]
<file_sep>/README.md
# DESCRIPTION #
This repository provides ROS package to merge two tracking systems, Vicon and Optitrack, in the MIT Building 31's high bay.
### SETUP ###
* Install prerequisites
```
sudo pip install pyquaternion
```
### DATA ###
Please download data and put it `data/` folder.
Data can be found at: `https://drive.google.com/drive/folders/1k5D_k6xLRdH1TWRTjlZ8tqHJ-GOyM9Zb?usp=sharing`.
### RESULT ###
Transformation between Vicon to Opti (based on 3 data points):
```
Position (x, y, z): 12.0174229, 1.11216997, -0.0175561
Quaternion (qx, qy, qz, qw): -0.00083867, 0.00084894, 0.7387037, 0.67402662
```
Further optimized transformation between Vicon to Opti (based on a trajectory):
```
Position (x, y, z): 12.0343504107, 1.039922734, 0.131514931278
Quaternion (qx, qy, qz, qw): -0.0115611628667, 0.00209857996667, 0.7371048285, 0.675638377167
```
### CONTRIBUTION GUIDELINES ###
* Create a new branch if you want to add a new feature to the code base:
```
git checkout -b <branch_name>
```
* Once the feature is complete, create a pull request for a senior student to review your work
```
git add <list files you want to commit>
git commit -m "<commit description>"
git push -u origin <branch_name>
```
### CONTACT ###
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
<file_sep>/src/trajectory/main.py
import rosbag
import numpy as np
import matplotlib.pyplot as plt
from data import Data
from transformation import Transformation
from draw import Draw
from acl_msgs.msg import ViconState
from geometry_msgs.msg import PoseStamped
from decimal import Decimal
OPTIMIZE_T_MODE = False
ERROR_MODE = True
def return_timestamp(data):
nsec = str(data.header.stamp.nsecs)
if len(nsec) == 7:
nsec = str(00) + nsec # Append 0 for digits that missed 0 in front
if len(nsec) == 8:
nsec = str(0) + nsec # Append 0 for digits that missed 0 in front
ts = str(data.header.stamp.secs) + "." + nsec
if len(ts) != 20:
RuntimeError("Timestamp does not match!")
return Decimal(ts)
def vicon_cb(data, data_obj):
ts = return_timestamp(data)
# Put timestamp, position, and quat into list and append
vicon_list = [ts, data.pose.position.x, data.pose.position.y, data.pose.position.z,
data.pose.orientation.w, data.pose.orientation.x, data.pose.orientation.y,
data.pose.orientation.z]
data_obj.add_vicon_data(vicon_list)
def opti_cb(data, T_vicon_to_opti, data_obj):
ts = return_timestamp(data)
# position and quat
position = np.array([data.pose.position.x,
data.pose.position.y,
data.pose.position.z])
quat = np.array([data.pose.orientation.w,
data.pose.orientation.x,
data.pose.orientation.y,
data.pose.orientation.z])
opti_orig_list = [ts, data.pose.position.x, data.pose.position.y, data.pose.position.z,
data.pose.orientation.w, data.pose.orientation.x, data.pose.orientation.y,
data.pose.orientation.z]
data_obj.add_opti_orig_data(opti_orig_list)
# Transformation
T_opti_to_wand = T_obj.convert_to_T_matrix(position, quat)
T_vicon_to_wand = np.dot(T_vicon_to_opti, T_opti_to_wand)
opti_position, opti_quat = \
T_obj.convert_T_matrix_to_position_and_quat(T_vicon_to_wand)
opti_list = [ts, opti_position[0], opti_position[1], opti_position[2],
opti_quat[0], opti_quat[1], opti_quat[2], opti_quat[3]]
data_obj.add_opti_data(opti_list)
if __name__ == "__main__":
# Class initialization
data_obj = Data()
T_obj = Transformation()
draw_obj = Draw()
T_vicon_to_opti = T_obj.return_T_vicon_to_opti()
# Read data and store
bag = rosbag.Bag("../../data/data_trajectory/optitrack/2018-02-19-18-02-18.bag")
# bag = rosbag.Bag("../../data/data_trajectory/optitrack/2018-02-19-18-10-05.bag")
vicon_topic = "/dongki/vicon"
opti_topic = "/Robot_2/pose"
for topic, msg, t in bag.read_messages(topics=[opti_topic, vicon_topic]):
if topic == "/dongki/vicon":
vicon_cb(msg, data_obj)
elif topic == "/Robot_2/pose":
opti_cb(msg, T_vicon_to_opti, data_obj)
else:
RuntimeError("Non-valid topic found.")
data_obj.set_vicon()
data_obj.set_opti()
data_obj.set_opti_orig()
# Further optimize T
if OPTIMIZE_T_MODE:
data_obj.optimize_T()
if ERROR_MODE:
data_obj.error()
# Draw plot
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_x,
data_obj.opti_ts, data_obj.opti_x,
None, None,
'Position x', 'Timestamp (UNIX)', 'Meter',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_y,
data_obj.opti_ts, data_obj.opti_y,
None, None,
'Position y', 'Timestamp (UNIX)', 'Meter',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_z,
data_obj.opti_ts, data_obj.opti_z,
None, None,
'Position z', 'Timestamp (UNIX)', 'Meter',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_qw,
data_obj.opti_ts, -data_obj.opti_qw,
None, None,
'Quaternion w', 'Timestamp (UNIX)', 'Quaternion',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_qx,
data_obj.opti_ts, -data_obj.opti_qx,
None, None,
'Quaternion x', 'Timestamp (UNIX)', 'Quaternion',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_qy,
data_obj.opti_ts, -data_obj.opti_qy,
None, None,
'Quaternion y', 'Timestamp (UNIX)', 'Quaternion',
'Vicon', 'OptiTrack', 'Data used for Optimization')
draw_obj.draw_plot(data_obj.vicon_ts, data_obj.vicon_qz,
data_obj.opti_ts, -data_obj.opti_qz,
None, None,
'Quaternion z', 'Timestamp (UNIX)', 'Quaternion',
'Vicon', 'OptiTrack', 'Data used for Optimization')
plt.show()
<file_sep>/src/vicon_opti_T/transformation.py
import numpy as np
from pyquaternion import Quaternion
class Transformation(object):
def convert_to_T_matrix(self, position, quat):
R_matrix = self._convert_quat_to_R_matrix(quat)
T_matrix = np.zeros((4, 4))
T_matrix[0, 0] = R_matrix[0, 0]
T_matrix[0, 1] = R_matrix[0, 1]
T_matrix[0, 2] = R_matrix[0, 2]
T_matrix[0, 3] = position[0]
T_matrix[1, 0] = R_matrix[1, 0]
T_matrix[1, 1] = R_matrix[1, 1]
T_matrix[1, 2] = R_matrix[1, 2]
T_matrix[1, 3] = position[1]
T_matrix[2, 0] = R_matrix[2, 0]
T_matrix[2, 1] = R_matrix[2, 1]
T_matrix[2, 2] = R_matrix[2, 2]
T_matrix[2, 3] = position[2]
T_matrix[3, 0] = 0
T_matrix[3, 1] = 0
T_matrix[3, 2] = 0
T_matrix[3, 3] = 1
return T_matrix
def inverse_matrix(self, T_matrix):
R_matrix = T_matrix[0:3, 0:3]
R_inv_matrix = R_matrix.transpose()
position = T_matrix[0:3, 3].reshape((3, 1))
position_inv = np.dot(-R_inv_matrix, position)
T_matrix = np.zeros((4, 4))
T_matrix[0, 0] = R_inv_matrix[0, 0]
T_matrix[0, 1] = R_inv_matrix[0, 1]
T_matrix[0, 2] = R_inv_matrix[0, 2]
T_matrix[0, 3] = position_inv[0]
T_matrix[1, 0] = R_inv_matrix[1, 0]
T_matrix[1, 1] = R_inv_matrix[1, 1]
T_matrix[1, 2] = R_inv_matrix[1, 2]
T_matrix[1, 3] = position_inv[1]
T_matrix[2, 0] = R_inv_matrix[2, 0]
T_matrix[2, 1] = R_inv_matrix[2, 1]
T_matrix[2, 2] = R_inv_matrix[2, 2]
T_matrix[2, 3] = position_inv[2]
T_matrix[3, 0] = 0
T_matrix[3, 1] = 0
T_matrix[3, 2] = 0
T_matrix[3, 3] = 1
return T_matrix
def convert_T_matrix_to_position_and_quat(self, T_matrix):
position = T_matrix[0:3, 3]
R_matrix = T_matrix[0:3, 0:3]
return position, self._convert_R_matrix_to_quat(R_matrix)
def _convert_R_matrix_to_quat(self, R_matrix):
quat_obj = Quaternion(matrix=R_matrix)
quat_obj = quat_obj.normalised
return np.array([quat_obj[0], quat_obj[1], quat_obj[2], quat_obj[3]])
def _convert_quat_to_R_matrix(self, quat):
quat_obj = Quaternion(quat)
quat_obj = quat_obj.normalised
return quat_obj.rotation_matrix
| cfaf18ccb70ac8ae272ed6670a8a15fb151171a6 | [
"Markdown",
"Python"
] | 7 | Python | dkkim93/vicon_optitrack_merge | b0e03d2cb404115dd36ac91fc58e46a29bd6003c | f564b1afcc9b71026e58795f7c52080cac330609 |
refs/heads/master | <repo_name>rsliva/ExData_Plotting1<file_sep>/plot4.R
# plot4.R
# Creates plot4.png - a 4 panel plot forthe two days 2/1/2007 - 2/2/2007
# Global Active Power
# Voltage
# Energy sub metering
# Global reactive power
options(StringsAsFactors=F)
# load the source data - it is n the parent directory
hpc <- read.table("../household_power_consumption.txt", header=TRUE, sep=";", na.strings="?")
# create a subset using just two days - 2/1/2007 and 2/2/2007
hpc2 <- hpc[(hpc$Date=="1/2/2007") | (hpc$Date=="2/2/2007"),]
# remove original data.frame from memory
rm(hpc)
# fix the dates
hpc2$Date <- as.Date(hpc2$Date,format="%d/%m/%Y")
hpc2$DateTime <- as.POSIXct(paste(hpc2$Date, as.character(hpc2$Time)))
# list of colors to use for sub metering line plot
colList <- c("black","red", "blue")
# create a 4-panel plot
png(filename="plot4.png", width = 480, height = 480)
par(mfrow = c(2, 2), mar = c(4, 4, 4, 4), oma = c(1, 1, 1, 1))
with(hpc2, {
#Global active power
plot(hpc2$DateTime,hpc2$Global_active_power,type="l",xlab="",ylab="Global Active Power (kilowatts)" )
# Voltage
plot(hpc2$DateTime,hpc2$Voltage,type="l", xlab="datetime", ylab="Voltage")
#plot the three Sub metering line plots with legend
plot(hpc2$DateTime,hpc2$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering" )
lines(hpc2$DateTime,hpc2$Sub_metering_2,type="l",col=colList[2])
lines(hpc2$DateTime,hpc2$Sub_metering_3,type="l",col=colList[3])
legend("topright", lty = 1, col = colList, legend = names(hpc2)[7:9], bty="n")
# plot Global reactive power
plot(hpc2$DateTime,hpc2$Global_reactive_power,type="l", xlab="datetime", ylab="Global_reactive_power")
})
dev.off()
<file_sep>/plot3.R
# plot3.R
# Creates plot3.png - a multi-variable line plot of Sub metering values
# during the 2 days 2/1/2007 - 2/2/2007
options(StringsAsFactors=F)
# load the source data - it is n the parent directory
hpc <- read.table("../household_power_consumption.txt", header=TRUE, sep=";", na.strings="?")
# create a subset using just two days - 2/1/2007 and 2/2/2007
hpc2 <- hpc[(hpc$Date=="1/2/2007") | (hpc$Date=="2/2/2007"),]
# remove original data.frame from memory
rm(hpc)
# fix the dates
hpc2$Date <- as.Date(hpc2$Date,format="%d/%m/%Y")
hpc2$DateTime <- as.POSIXct(paste(hpc2$Date, as.character(hpc2$Time)))
# list of colors to use for plot/legend
colList <- c("black","red", "blue")
# create line chart and save as plot2.png
png("plot3.png", width = 480, height = 480)
#plot the three line plots with legend
plot(hpc2$DateTime,hpc2$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering" )
lines(hpc2$DateTime,hpc2$Sub_metering_2,type="l",col=colList[2])
lines(hpc2$DateTime,hpc2$Sub_metering_3,type="l",col=colList[3])
legend("topright", lty = 1, col = colList, legend = names(hpc2)[7:9])
dev.off()<file_sep>/plot1.R
# plot1.R
# Creates plot1.png - a frequency histogram of global active power for the days 2/1/2007 - 2/2/2007
options(StringsAsFactors=F)
# load the source data - it is n the parent directory
hpc <- read.table("../household_power_consumption.txt", header=TRUE, sep=";", na.strings="?")
# create a subset using just two days - 2/1/2007 and 2/2/2007
hpc2 <- hpc[(hpc$Date=="1/2/2007") | (hpc$Date=="2/2/2007"),]
# remove original data.frame from memory
rm(hpc)
# create histogram and save as plot1.png using png driver
png(filename=paste(getwd(),"/plot1.png",sep=""), width = 480, height = 480)
hist(hpc2$Global_active_power, main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency", col="Red")
dev.off()
| 539ce382078c0f3df655b977be6a5dc8836fba01 | [
"R"
] | 3 | R | rsliva/ExData_Plotting1 | fa904d9f19690721cef83d9242ed8abef4e1970b | 1c6567508b78e2e1bcdd9a2f51bbe05a560c9fcd |
refs/heads/master | <repo_name>cloudwerkstatt/semantic-wiki<file_sep>/Dockerfile
FROM registry.access.redhat.com/rhel7.2:latest
MAINTAINER <NAME> <<EMAIL>>
ENV MEDIA_WIKI_VERSION 1.26
ENV MEDIA_WIKI_MINOR 2
RUN yum -y update \
&& yum install -y tar httpd php php-mysql php-xml php-gd ImageMagick \
&& yum clean all \
&& cd /tmp \
&& curl -LO https://releases.wikimedia.org/mediawiki/${MEDIA_WIKI_VERSION}/mediawiki-${MEDIA_WIKI_VERSION}.${MEDIA_WIKI_MINOR}.tar.gz \
&& tar xzvf mediawiki-${MEDIA_WIKI_VERSION}.${MEDIA_WIKI_MINOR}.tar.gz \
&& rm -f mediawiki-${MEDIA_WIKI_VERSION}.${MEDIA_WIKI_MINOR}.tar.gz \
&& mv mediawiki-${MEDIA_WIKI_VERSION}.${MEDIA_WIKI_MINOR}/* /var/www/html/ \
&& chmod -R 777 /var/www/ \
&& chmod -R 777 /run/httpd
ADD container-files /
ENV MEDIAWIKI_SITE_NAME semantic-wiki
ENV MEDIAWIKI_DB_HOST mysql
ENV MEDIAWIKI_DB_USER defaultuser
ENV MEDIAWIKI_DB_PASSWORD <PASSWORD>
ENV MEDIAWIKI_DB_NAME mediawiki
ENV MEDIAWIKI_ADMIN_PASSWORD <PASSWORD>
ENV MEDIAWIKI_ADMIN_USER adminpassword
EXPOSE 8080
CMD /docker-entrypoint.sh
<file_sep>/container-files/check.sh
#!/bin/bash
while [ true ]; do
echo "Trying to connect to $MEDIAWIKI_DB_HOST..."
if [ cat < /dev/tcp/$MEDIAWIKI_DB_HOST/3306 ]; then
break;
fi
sleep 3;
done
echo "$MEDIAWIKI_DB_HOST:3306 is reachable, continuing..."
sleep 2
<file_sep>/container-files/docker-entrypoint.sh
#!/bin/bash
cd /var/www/html/maintenance
echo "Configuring MediaWiki with install.php"
echo $MEDIAWIKI_SITE_NAME
echo $MEDIAWIKI_DB_HOST
echo $MEDIAWIKI_DB_USER
echo $MEDIAWIKI_DB_PASSWORD
echo $MEDIAWIKI_DB_NAME
echo $MEDIAWIKI_ADMIN_PASSWORD
echo $MEDIAWIKI_ADMIN_USER
echo "Waiting for mysql database"
/check.sh
php install.php --scriptpath="" --dbname=$MEDIAWIKI_DB_NAME --dbuser=$MEDIAWIKI_DB_USER --dbpass=$MEDIAWIKI_DB_PASSWORD --dbserver=$MEDIAWIKI_DB_HOST --installdbpass=$MEDIAWIKI_DB_PASSWORD --installdbuser=$MEDIAWIKI_DB_USER --pass=$MEDIAWIKI_ADMIN_PASSWORD $MEDIAWIKI_SITE_NAME $MEDIAWIKI_ADMIN_USER
httpd -e debug -DFOREGROUND
| 44d54813bdd54648f91bda71feabfc2fa12d63a0 | [
"Dockerfile",
"Shell"
] | 3 | Dockerfile | cloudwerkstatt/semantic-wiki | f908a5647bc46e96006d94e1cacd7d43631bf5d2 | ca918ba5862ec89e0003ad392dbbf41ce71c71d5 |
refs/heads/master | <file_sep>from django.http import HttpResponse
from tagging.models import Tag
from cmsplugin_news.models import News
from django.utils import simplejson
from django.core import serializers
from datetime import datetime
def pull(request, **kwargs):
#raise Exception("Got arguments: %s, %s" % (request, kwargs))
response = HttpResponse(content_type="application/json")
delimiter = "_"
tail = kwargs['tagnames']
tags = []
#explode URL to tag list
while delimiter != '':
(tag, delimiter, tail) = tail.partition(delimiter)
tags += [tag]
existing_tags = Tag.objects.all()
#test, which tags exist
tags_found = []
for existing_tag in existing_tags:
for tag in tags:
if existing_tag.name == tag:
tags_found += [existing_tag]
tags.remove(tag)
break
#response.write("<h3>Found tags:</h3> <br />")
#search for related news
tag_ids = []
for tag in tags_found:
#response.write("%s <br />" % tag.name)
tag_ids += [tag.id]
news_found = News.objects.filter(tags__id__in = tag_ids)
#news_found.order_by("pub_date")
#news_found = news_found.reverse()
news_found = news_found.distinct()
news_found = list(news_found)
def compare_news(item1, item2):
if item1.pub_date > item2.pub_date:
return 1
elif item1.pub_date < item2.pub_date:
return -1
else:
return 0
#print news
#response.write("<h3>Found news:</h3> <br />")
#news_found.sort(compare_news,reverse=True)
if len(news_found):
#news_simple = []
#for news_item in news_found:
# #response.write("%s %s <br />" % (news_item.pub_date, news_item.title))
# news_item_simple = {
# "pub_date":news_item.pub_date,
# "title":news_item.title,
# "excerpt":news_item.excerpt,
# "content":news_item.content,
# "url":"newsurl"}
# news_simple += [news_item_simple]
news = []
for news_item in news_found:
news_item.url = "news_url"
news += [news_item]
#news_json = simplejson.dumps(news_simple)
news_serialized = serializers.serialize("json", news)
response.write(news_serialized)
else:
raise Exception("No records found for tags specified")
return response
def pull_simple(request, **kwargs):
"""
Дергает новости не в виде объектов CMSPluginNews,
а в виде dict'ов
"""
#raise Exception("Got arguments: %s, %s" % (request, kwargs))
response = HttpResponse(content_type="application/json")
response["Access-Control-Allow-Origin"] = "*"
delimiter = "_"
tail = kwargs['tagnames']
tags = []
#explode URL to tag list
while delimiter != '':
(tag, delimiter, tail) = tail.partition(delimiter)
tags += [tag]
existing_tags = Tag.objects.all()
#test, which tags exist
tags_found = []
for existing_tag in existing_tags:
for tag in tags:
if existing_tag.name == tag:
tags_found += [existing_tag]
tags.remove(tag)
break
#response.write("<h3>Found tags:</h3> <br />")
#search for related news
tag_ids = []
for tag in tags_found:
#response.write("%s <br />" % tag.name)
tag_ids += [tag.id]
news_found = News.objects.filter(tags__id__in = tag_ids)
#news_found.order_by("pub_date")
#news_found = news_found.reverse()
news_found = news_found.distinct()
news_found = list(news_found)
def compare_news(item1, item2):
if item1.pub_date > item2.pub_date:
return 1
elif item1.pub_date < item2.pub_date:
return -1
else:
return 0
#print news
#response.write("<h3>Found news:</h3> <br />")
#news_found.sort(compare_news,reverse=True)
if len(news_found):
#news_simple = []
#for news_item in news_found:
# #response.write("%s %s <br />" % (news_item.pub_date, news_item.title))
# news_item_simple = {
# "pub_date":news_item.pub_date,
# "title":news_item.title,
# "excerpt":news_item.excerpt,
# "content":news_item.content,
# "url":"newsurl"}
# news_simple += [news_item_simple]
def is_published(news_item):
if (not news_item.pub_date) or (news_item.pub_date>=datetime.now()):
return False
if news_item.unpub_date and news_item.unpub_date<=datetime.now():
return False
return news_item.is_published
news_record = lambda news_item: {
"pub_date":None if news_item.pub_date is None else news_item.pub_date.strftime("%Y-%m-%d %H:%M:%S"),
"unpub_date":None if news_item.unpub_date is None else news_item.unpub_date.strftime("%Y-%m-%d %H:%M:%S"),
"is_published":is_published(news_item),
"title":news_item.title,
"excerpt":news_item.excerpt,
"content":news_item.content,
"tags":[tag.name for tag in news_item.tags.all()],
"url":news_item.get_absolute_url()}
news = [news_record(news_item) for news_item in news_found]
#news = []
#for news_item in news_found:
# news_item.url = "news_url"
# news += [news_item]
#news_json = simplejson.dumps(news_simple)
#news_serialized = serializers.serialize("json", news)
serializers._load_serializers()
news_serialized = serializers.json.simplejson.dumps(news)
response.write(news_serialized)
else:
raise Exception("No records found for tags specified")
return response
<file_sep>from django.db import models
#no models for this app needed
<file_sep>from django.conf.urls.defaults import *
from tag_puller.core import pull
urlpatterns = patterns('',
url(r'(?P<tagnames>[\w-]+)/', pull),
)
| 7cff186612afdbebd7c2ebf49319923ece83d6ec | [
"Python"
] | 3 | Python | side2k/django-tag-puller | ae16e979153a9d750eb9cf5bc005520d2f23c97f | 7f30fed63d94efc4f8a29ed6051982f236032ba7 |
refs/heads/master | <repo_name>Hecoz/CrossPare<file_sep>/CrossPare/src/main/java/de/ugoe/cs/cpdp/execution/SclModelAbstractCrossProjectExperiment.java
// Copyright 2015 Georg-August-Universität Göttingen, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.ugoe.cs.cpdp.execution;
import de.ugoe.cs.cpdp.ExperimentConfiguration;
import de.ugoe.cs.cpdp.dataprocessing.IProcessesingStrategy;
import de.ugoe.cs.cpdp.dataprocessing.ISetWiseProcessingStrategy;
import de.ugoe.cs.cpdp.dataselection.IPointWiseDataselectionStrategy;
import de.ugoe.cs.cpdp.dataselection.ISetWiseDataselectionStrategy;
import de.ugoe.cs.cpdp.eval.IEvaluationStrategy;
import de.ugoe.cs.cpdp.eval.IResultStorage;
import de.ugoe.cs.cpdp.loader.IVersionLoader;
import de.ugoe.cs.cpdp.training.*;
import de.ugoe.cs.cpdp.versions.IVersionFilter;
import de.ugoe.cs.cpdp.versions.SoftwareVersion;
import de.ugoe.cs.util.console.Console;
import org.apache.commons.collections4.list.SetUniqueList;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
/**
* Class responsible for executing an experiment according to an {@link ExperimentConfiguration}.
* The steps of an experiment are as follows:
* <ul>
* <li>load the data from the provided data path</li>
* <li>filter the data sets according to the provided version filters</li>
* <li>execute the following steps for each data sets as test data that is not ignored through the
* test version filter:
* <ul>
* <li>filter the data sets to setup the candidate training data:
* <ul>
* <li>remove all data sets from the same project</li>
* <li>filter all data sets according to the training data filter
* </ul>
* </li>
* <li>apply the setwise preprocessors</li>
* <li>apply the setwise data selection algorithms</li>
* <li>apply the setwise postprocessors</li>
* <li>train the setwise training classifiers</li>
* <li>unify all remaining training data into one data set</li>
* <li>apply the preprocessors</li>
* <li>apply the pointwise data selection algorithms</li>
* <li>apply the postprocessors</li>
* <li>train the normal classifiers</li>
* <li>evaluate the results for all trained classifiers on the training data</li>
* </ul>
* </li>
* </ul>
*
* Note that this class implements {@link Runnable}, i.e., each experiment can be started in its own
* thread.
*
* @author <NAME>
*/
public abstract class SclModelAbstractCrossProjectExperiment implements IExecutionStrategy {
/**
* configuration of the experiment
*/
protected final ExperimentConfiguration config;
/**
* Constructor. Creates a new experiment based on a configuration.
*
* @param config
* configuration of the experiment
*/
@SuppressWarnings("hiding")
public SclModelAbstractCrossProjectExperiment(ExperimentConfiguration config) {
this.config = config;
}
/**
* <p>
* Defines which products are allowed for training.
* </p>
*
* @param trainingVersion
* training version
* @param testVersion
* test candidate
* @param versions
* all software versions in the data set
* @return true if test candidate can be used for training
*/
protected abstract boolean isTrainingVersion(SoftwareVersion trainingVersion,
SoftwareVersion testVersion,
List<SoftwareVersion> versions);
/**
* Helper method that combines a set of Weka {@link Instances} sets into a single
* {@link Instances} set.
*
* @param traindataSet
* set of {@link Instances} to be combines
* @return single {@link Instances} set
*/
public static Instances makeSingleTrainingSet(SetUniqueList<Instances> traindataSet) {
Instances traindataFull = null;
for (Instances traindata : traindataSet) {
if (traindataFull == null) {
traindataFull = new Instances(traindata);
}
else {
for (int i = 0; i < traindata.numInstances(); i++) {
traindataFull.add(traindata.instance(i));
}
}
}
return traindataFull;
}
/**
* Executes the experiment with the steps as described in the class comment.
*
* @see Runnable#run()
*/
@SuppressWarnings("boxing")
@Override
public void run() {
final List<SoftwareVersion> versions = new LinkedList<>();
for (IVersionLoader loader : this.config.getLoaders()) {
versions.addAll(loader.load());
}
for (IVersionFilter filter : this.config.getVersionFilters()) {
filter.apply(versions);
}
boolean writeHeader = true;
int versionCount = 1;
int testVersionCount = 0;
for (SoftwareVersion testVersion : versions) {
if (isVersion(testVersion, this.config.getTestVersionFilters())) {
testVersionCount++;
}
}
testVersionCount*=10;
// sort versions
Collections.sort(versions);
for(int time = 0;time < 10;time++) {
Random rand = new Random(time + 1);
SoftwareVersion vtmp;
Instances tmpInstance;
for(int i = 0;i < versions.size();i++){
vtmp = versions.get(i);
tmpInstance = vtmp.getInstances();
tmpInstance.randomize(rand);
List<Double> efforts = getEfforts(tmpInstance);
List<Double> numBugs = getNumBugs(tmpInstance);
SoftwareVersion newVersion = new SoftwareVersion(vtmp.getDataset(),vtmp.getProject(),vtmp.getVersion(),tmpInstance,efforts,numBugs);
versions.set(i,newVersion);
//versions.get(i).getInstances().randomize(rand);
}
for (int fold = 0; fold < 10; fold++) {
SetUniqueList<Instances> traindataSet = SetUniqueList.setUniqueList(new LinkedList<Instances>());
for (SoftwareVersion version : versions) {
//Setup traindata
traindataSet.add(version.getInstances().testCV(10, fold));
}
for (SoftwareVersion version : versions) {
// Setup testdata
Instances testdata = version.getInstances().trainCV(10, fold);
List<Double> efforts = getEfforts(testdata);
List<Double> numBugs = getNumBugs(testdata);
for (ISetWiseProcessingStrategy processor : this.config.getSetWisePreprocessors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise preprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
version.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindataSet);
}
for (ISetWiseDataselectionStrategy dataselector : this.config
.getSetWiseSelectors()) {
Console
.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying setwise selection %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
dataselector.getClass().getName()));
dataselector.apply(testdata, traindataSet);
}
for (ISetWiseProcessingStrategy processor : this.config
.getSetWisePostprocessors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise postprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
version.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindataSet);
}
for (ISetWiseTrainingStrategy setwiseTrainer : this.config.getSetWiseTrainers()) {
Console
.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying setwise trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
setwiseTrainer.getName()));
setwiseTrainer.apply(traindataSet);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config
.getSetWiseTestdataAwareTrainers()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying testdata aware setwise trainer %s",
this.config.getExperimentName(), versionCount, testVersionCount,
version.getVersion(), setwiseTestdataAwareTrainer.getName()));
setwiseTestdataAwareTrainer.apply(traindataSet, testdata);
}
Instances traindata = makeSingleTrainingSet(traindataSet);
//model building
for (IProcessesingStrategy processor : this.config.getPreProcessors()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying preprocessor %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
processor.getClass().getName()));
processor.apply(testdata, traindata);
}
for (IPointWiseDataselectionStrategy dataselector : this.config
.getPointWiseSelectors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying pointwise selection %s",
this.config.getExperimentName(), versionCount, testVersionCount,
version.getVersion(), dataselector.getClass().getName()));
traindata = dataselector.apply(testdata, traindata);
}
for (IProcessesingStrategy processor : this.config.getPostProcessors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise postprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
version.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindata);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
trainer.getName()));
trainer.apply(traindata);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
trainer.getName()));
trainer.apply(testdata, traindata);
}
File resultsDir = new File(this.config.getResultsPath());
if (!resultsDir.exists()) {
resultsDir.mkdir();
}
for (IEvaluationStrategy evaluator : this.config.getEvaluators()) {
Console.traceln(Level.FINE, String.format("[%s] [%02d/%02d] %s: applying evaluator %s",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion(),
evaluator.getClass().getName()));
List<ITrainer> allTrainers = new LinkedList<>();
for (ISetWiseTrainingStrategy setwiseTrainer : this.config.getSetWiseTrainers()) {
allTrainers.add(setwiseTrainer);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config.getSetWiseTestdataAwareTrainers()) {
allTrainers.add(setwiseTestdataAwareTrainer);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
allTrainers.add(trainer);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
allTrainers.add(trainer);
}
if (writeHeader) {
evaluator.setParameter(this.config.getResultsPath() + "/" +
this.config.getExperimentName() + ".csv");
}
evaluator.apply(testdata, traindata, allTrainers, efforts, numBugs, writeHeader, this.config.getResultStorages());
writeHeader = false;
}
Console.traceln(Level.INFO,
String.format("[%s] [%02d/%02d] %s: finished",
this.config.getExperimentName(), versionCount,
testVersionCount, version.getVersion()));
versionCount++;
}
}
}
}
/**
* Helper method that checks if a version passes all filters.
*
* @param version
* version that is checked
* @param filters
* list of the filters
* @return true, if the version passes all filters, false otherwise
*/
private static boolean isVersion(SoftwareVersion version, List<IVersionFilter> filters) {
boolean result = true;
for (IVersionFilter filter : filters) {
result &= !filter.apply(version);
}
return result;
}
/**
* <p>
* helper function that checks if the results are already in the data store
* </p>
*
* @param version
* version for which the results are checked
* @return
*/
private int resultsAvailable(SoftwareVersion version) {
if (this.config.getResultStorages().isEmpty()) {
return 0;
}
List<ITrainer> allTrainers = new LinkedList<>();
for (ISetWiseTrainingStrategy setwiseTrainer : this.config.getSetWiseTrainers()) {
allTrainers.add(setwiseTrainer);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config
.getSetWiseTestdataAwareTrainers())
{
allTrainers.add(setwiseTestdataAwareTrainer);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
allTrainers.add(trainer);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
allTrainers.add(trainer);
}
int available = Integer.MAX_VALUE;
for (IResultStorage storage : this.config.getResultStorages()) {
String classifierName = ((IWekaCompatibleTrainer) allTrainers.get(0)).getName();
int curAvailable = storage.containsResult(this.config.getExperimentName(),
version.getVersion(), classifierName);
if (curAvailable < available) {
available = curAvailable;
}
}
return available;
}
/**
* <p>
* Sets the efforts for the instances
* </p>
*
* @param data
* the data
* @return
*/
@SuppressWarnings("boxing")
public static List<Double> getEfforts(Instances data) {
// attribute in the JURECZKO data and default
Attribute effortAtt = data.attribute("loc");
if (effortAtt == null) {
// attribute in the NASA/SOFTMINE/MDP data
effortAtt = data.attribute("LOC_EXECUTABLE");
}
if (effortAtt == null) {
// attribute in the AEEEM data
effortAtt = data.attribute("numberOfLinesOfCode");
}
if (effortAtt == null) {
// attribute in the RELINK data
effortAtt = data.attribute("CountLineCodeExe");
}
if (effortAtt == null) {
// attribute in the SMARTSHARK data
effortAtt = data.attribute("LOC");
}
List<Double> efforts = new ArrayList<>(data.size());
for (int i = 0; i < data.size(); i++) {
if(effortAtt!=null) {
efforts.add(data.get(i).value(effortAtt));
} else {
// add constant effort per instance (default)
efforts.add(1.0);
}
}
return efforts;
}
/**
* <p>
* Retrieves the number of bugs from the class attribute of the data and stores it separately in
* a list.
* </p>
*
* @param data
* the data
* @return list with bug counts
*/
private static List<Double> getNumBugs(Instances data) {
List<Double> numBugs = new ArrayList<>(data.size());
for (Instance instance : data) {
numBugs.add(instance.classValue());
}
return numBugs;
}
}
<file_sep>/CrossPare/src/main/java/de/ugoe/cs/cpdp/execution/SingleTrainAbstractCrossProjectExperiment.java
// Copyright 2015 Georg-August-Universität Göttingen, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package de.ugoe.cs.cpdp.execution;
import de.ugoe.cs.cpdp.ExperimentConfiguration;
import de.ugoe.cs.cpdp.dataprocessing.IProcessesingStrategy;
import de.ugoe.cs.cpdp.dataprocessing.ISetWiseProcessingStrategy;
import de.ugoe.cs.cpdp.dataselection.IPointWiseDataselectionStrategy;
import de.ugoe.cs.cpdp.dataselection.ISetWiseDataselectionStrategy;
import de.ugoe.cs.cpdp.eval.IEvaluationStrategy;
import de.ugoe.cs.cpdp.eval.IResultStorage;
import de.ugoe.cs.cpdp.loader.IVersionLoader;
import de.ugoe.cs.cpdp.training.*;
import de.ugoe.cs.cpdp.versions.IVersionFilter;
import de.ugoe.cs.cpdp.versions.SoftwareVersion;
import de.ugoe.cs.util.console.Console;
import org.apache.commons.collections4.list.SetUniqueList;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.filters.unsupervised.instance.RemovePercentage;
import java.io.File;
import java.util.*;
import java.util.logging.Filter;
import java.util.logging.Level;
/**
* Class responsible for executing an experiment according to an {@link ExperimentConfiguration}.
* The steps of an experiment are as follows:
* <ul>
* <li>load the data from the provided data path</li>
* <li>filter the data sets according to the provided version filters</li>
* <li>execute the following steps for each data sets as test data that is not ignored through the
* test version filter:
* <ul>
* <li>filter the data sets to setup the candidate training data:
* <ul>
* <li>remove all data sets from the same project</li>
* <li>filter all data sets according to the training data filter
* </ul>
* </li>
* <li>apply the setwise preprocessors</li>
* <li>apply the setwise data selection algorithms</li>
* <li>apply the setwise postprocessors</li>
* <li>train the setwise training classifiers</li>
* <li>unify all remaining training data into one data set</li>
* <li>apply the preprocessors</li>
* <li>apply the pointwise data selection algorithms</li>
* <li>apply the postprocessors</li>
* <li>train the normal classifiers</li>
* <li>evaluate the results for all trained classifiers on the training data</li>
* </ul>
* </li>
* </ul>
*
* Note that this class implements {@link Runnable}, i.e., each experiment can be started in its own
* thread.
*
* @author <NAME>
*/
public abstract class SingleTrainAbstractCrossProjectExperiment implements IExecutionStrategy {
/**
* configuration of the experiment
*/
protected final ExperimentConfiguration config;
/**
* Constructor. Creates a new experiment based on a configuration.
*
* @param config
* configuration of the experiment
*/
@SuppressWarnings("hiding")
public SingleTrainAbstractCrossProjectExperiment(ExperimentConfiguration config) {
this.config = config;
}
/**
* <p>
* Defines which products are allowed for training.
* </p>
*
* @param trainingVersion
* training version
* @param testVersion
* test candidate
* @param versions
* all software versions in the data set
* @return true if test candidate can be used for training
*/
protected abstract boolean isTrainingVersion(SoftwareVersion trainingVersion,
SoftwareVersion testVersion,
List<SoftwareVersion> versions);
/**
* Helper method that combines a set of Weka {@link Instances} sets into a single
* {@link Instances} set.
*
* @param traindataSet
* set of {@link Instances} to be combines
* @return single {@link Instances} set
*/
public static Instances makeSingleTrainingSet(SetUniqueList<Instances> traindataSet) {
Instances traindataFull = null;
for (Instances traindata : traindataSet) {
if (traindataFull == null) {
traindataFull = new Instances(traindata);
}
else {
for (int i = 0; i < traindata.numInstances(); i++) {
traindataFull.add(traindata.instance(i));
}
}
}
return traindataFull;
}
/**
* Executes the experiment with the steps as described in the class comment.
*
* @see Runnable#run()
*/
@SuppressWarnings("boxing")
@Override
public void run() {
final List<SoftwareVersion> versions = new LinkedList<>();
for (IVersionLoader loader : this.config.getLoaders()) {
versions.addAll(loader.load());
}
for (IVersionFilter filter : this.config.getVersionFilters()) {
filter.apply(versions);
}
boolean writeHeader = true;
int versionCount = 1;
int testVersionCount = 0;
for (SoftwareVersion testVersion : versions) {
if (isVersion(testVersion, this.config.getTestVersionFilters())) {
testVersionCount++;
}
}
// sort versions
Collections.sort(versions);
for(int time = 0;time < 50;time++) {
Random rand = new Random(time + 1);
for (SoftwareVersion trainingVersion : versions) {
if (isVersion(trainingVersion, this.config.getTestVersionFilters())) {
Console.traceln(Level.INFO,String.format("[%s] [%02d/%02d] %s: starting",
this.config.getExperimentName(),
versionCount,
testVersionCount,
trainingVersion.getVersion()));
SetUniqueList<Instances> traindataSet = SetUniqueList.setUniqueList(new LinkedList<Instances>());
for (SoftwareVersion testVersion : versions) {
if (isVersion(testVersion, this.config.getTrainingVersionFilters())) {
if (testVersion != trainingVersion) {
if (isTrainingVersion(trainingVersion, testVersion, versions)) {
traindataSet.add(trainingVersion.getInstances());
int numResultsAvailable = resultsAvailable(testVersion);
if (numResultsAvailable >= this.config.getRepetitions()) {
Console.traceln(Level.INFO, String
.format("[%s] [%02d/%02d] %s: results already available; skipped",
this.config.getExperimentName(), versionCount, testVersionCount,
testVersion.getVersion()));
versionCount++;
continue;
}
// Setup testdata and training data
Instances testdata = testVersion.getInstances();
testdata.randomize(rand);
try {
RemovePercentage removeFilter = new RemovePercentage();
removeFilter.setOptions(new String[]{"-P","5"});
removeFilter.setInputFormat(testdata);
testdata = weka.filters.Filter.useFilter(testdata,removeFilter);
} catch (Exception e) {
e.printStackTrace();
}
List<Double> efforts = getEfforts(testdata);
List<Double> numBugs = getNumBugs(testdata);
SoftwareVersion newVersion = new SoftwareVersion(testVersion.getDataset(),testVersion.getProject(),testVersion.getVersion(),testdata,efforts,numBugs);
if( traindataSet.isEmpty() ) {
Console.traceln(Level.WARNING, String
.format("[%s] [%02d/%02d] %s: no training data this product; skipped",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion()));
versionCount++;
continue;
}
for (ISetWiseProcessingStrategy processor : this.config.getSetWisePreprocessors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise preprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindataSet);
}
for (ISetWiseDataselectionStrategy dataselector : this.config
.getSetWiseSelectors())
{
Console
.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying setwise selection %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
dataselector.getClass().getName()));
dataselector.apply(testdata, traindataSet);
}
for (ISetWiseProcessingStrategy processor : this.config
.getSetWisePostprocessors())
{
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise postprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindataSet);
}
for (ISetWiseTrainingStrategy setwiseTrainer : this.config.getSetWiseTrainers()) {
Console
.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying setwise trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
setwiseTrainer.getName()));
setwiseTrainer.apply(traindataSet);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config
.getSetWiseTestdataAwareTrainers())
{
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying testdata aware setwise trainer %s",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion(), setwiseTestdataAwareTrainer.getName()));
setwiseTestdataAwareTrainer.apply(traindataSet, testdata);
}
Instances traindata = makeSingleTrainingSet(traindataSet);
traindata.randomize(rand);
//model train
for (IProcessesingStrategy processor : this.config.getPreProcessors()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying preprocessor %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
processor.getClass().getName()));
processor.apply(testdata, traindata);
}
for (IPointWiseDataselectionStrategy dataselector : this.config
.getPointWiseSelectors())
{
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying pointwise selection %s",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion(), dataselector.getClass().getName()));
traindata = dataselector.apply(testdata, traindata);
}
for (IProcessesingStrategy processor : this.config.getPostProcessors()) {
Console.traceln(Level.FINE, String
.format("[%s] [%02d/%02d] %s: applying setwise postprocessor %s",
this.config.getExperimentName(), versionCount, testVersionCount,
newVersion.getVersion(), processor.getClass().getName()));
processor.apply(testdata, traindata);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
trainer.getName()));
trainer.apply(traindata);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying trainer %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
trainer.getName()));
trainer.apply(testdata, traindata);
}
File resultsDir = new File(this.config.getResultsPath());
if (!resultsDir.exists()) {
resultsDir.mkdir();
}
for (IEvaluationStrategy evaluator : this.config.getEvaluators()) {
Console.traceln(Level.FINE,
String.format("[%s] [%02d/%02d] %s: applying evaluator %s",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion(),
evaluator.getClass().getName()));
List<ITrainer> allTrainers = new LinkedList<>();
for (ISetWiseTrainingStrategy setwiseTrainer : this.config
.getSetWiseTrainers())
{
allTrainers.add(setwiseTrainer);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config
.getSetWiseTestdataAwareTrainers())
{
allTrainers.add(setwiseTestdataAwareTrainer);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
allTrainers.add(trainer);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
allTrainers.add(trainer);
}
if (writeHeader) {
evaluator.setParameter(this.config.getResultsPath() + "/" +
this.config.getExperimentName() + ".csv");
}
evaluator.apply(testdata, traindata, allTrainers, efforts, numBugs, writeHeader,
this.config.getResultStorages());
writeHeader = false;
}
Console.traceln(Level.INFO,
String.format("[%s] [%02d/%02d] %s: finished",
this.config.getExperimentName(), versionCount,
testVersionCount, newVersion.getVersion()));
versionCount++;
traindataSet.clear();
}
}
}
}
}
}
}
}
/**
* Helper method that checks if a version passes all filters.
*
* @param version
* version that is checked
* @param filters
* list of the filters
* @return true, if the version passes all filters, false otherwise
*/
private static boolean isVersion(SoftwareVersion version, List<IVersionFilter> filters) {
boolean result = true;
for (IVersionFilter filter : filters) {
result &= !filter.apply(version);
}
return result;
}
/**
* <p>
* helper function that checks if the results are already in the data store
* </p>
*
* @param version
* version for which the results are checked
* @return
*/
private int resultsAvailable(SoftwareVersion version) {
if (this.config.getResultStorages().isEmpty()) {
return 0;
}
List<ITrainer> allTrainers = new LinkedList<>();
for (ISetWiseTrainingStrategy setwiseTrainer : this.config.getSetWiseTrainers()) {
allTrainers.add(setwiseTrainer);
}
for (ISetWiseTestdataAwareTrainingStrategy setwiseTestdataAwareTrainer : this.config
.getSetWiseTestdataAwareTrainers())
{
allTrainers.add(setwiseTestdataAwareTrainer);
}
for (ITrainingStrategy trainer : this.config.getTrainers()) {
allTrainers.add(trainer);
}
for (ITestAwareTrainingStrategy trainer : this.config.getTestAwareTrainers()) {
allTrainers.add(trainer);
}
int available = Integer.MAX_VALUE;
for (IResultStorage storage : this.config.getResultStorages()) {
String classifierName = ((IWekaCompatibleTrainer) allTrainers.get(0)).getName();
int curAvailable = storage.containsResult(this.config.getExperimentName(),
version.getVersion(), classifierName);
if (curAvailable < available) {
available = curAvailable;
}
}
return available;
}
/**
* <p>
* Sets the efforts for the instances
* </p>
*
* @param data
* the data
* @return
*/
@SuppressWarnings("boxing")
public static List<Double> getEfforts(Instances data) {
// attribute in the JURECZKO data and default
Attribute effortAtt = data.attribute("loc");
if (effortAtt == null) {
// attribute in the NASA/SOFTMINE/MDP data
effortAtt = data.attribute("LOC_EXECUTABLE");
}
if (effortAtt == null) {
// attribute in the AEEEM data
effortAtt = data.attribute("numberOfLinesOfCode");
}
if (effortAtt == null) {
// attribute in the RELINK data
effortAtt = data.attribute("CountLineCodeExe");
}
if (effortAtt == null) {
// attribute in the SMARTSHARK data
effortAtt = data.attribute("LOC");
}
List<Double> efforts = new ArrayList<>(data.size());
for (int i = 0; i < data.size(); i++) {
if(effortAtt!=null) {
efforts.add(data.get(i).value(effortAtt));
} else {
// add constant effort per instance (default)
efforts.add(1.0);
}
}
return efforts;
}
/**
* <p>
* Retrieves the number of bugs from the class attribute of the data and stores it separately in
* a list.
* </p>
*
* @param data
* the data
* @return list with bug counts
*/
private static List<Double> getNumBugs(Instances data) {
List<Double> numBugs = new ArrayList<>(data.size());
for (Instance instance : data) {
numBugs.add(instance.classValue());
}
return numBugs;
}
}
<file_sep>/Script/02code/meanstd.r
library("effsize")
strategys <- c("Nam15","Peters15","Turhan09")
projects <- c("AEEEM-Mask","MORPH-Mask","RELINK-Mask","SOFTLAB-Mask")
methods <- c("NB","RF","DT","LR","NET","SVM")
for (sidx in seq(length(strategys))) {
tmeans <- NULL
tstd <- NULL
strategy <- strategys[sidx]
for(pidx in seq(length(projects))){
project <- projects[pidx]
filename <- file.path("..","01results-csv",paste(project,"-",strategy,".csv",sep=""), fsep=.Platform$file.sep)
alldata <- read.csv(filename,header=T)
data.tmp <- data.frame(alldata[,"version"])
colnames(data.tmp) <- c("version")
for(method in methods){
fcol <- paste("fscore_",method,sep = "")
aucol <- paste("auc_",method,sep = "")
data.tmp <- cbind(data.tmp,alldata[,c(fcol,aucol)])
}
nrows <- nrow(data.tmp)
pnum <- nrows/10
adds <- pnum - 1
data <- NULL
for(i in seq(pnum)){
for(j in seq(i,nrows,by = pnum)){
data <- rbind(data,data.tmp[j,])
}
}
for(i in seq(1,nrows,by = 10)){
#tmeans <- rbind(tmeans,colMeans(data[i:(i+9),2:13]))
tmeans <- rbind(tmeans,apply(data[i:(i+9),2:13], 2, mean))
}
for(i in seq(1,nrows,by = 10)){
tstd <- rbind(tstd,apply(data[i:(i+9),2:13], 2, sd))
}
}
results <- cbind(tmeans,tstd)
filename <- file.path("..","03output",paste(strategy,".csv",sep=""), fsep=.Platform$file.sep)
write.csv(results,filename)
}<file_sep>/CrossPare/data/benchmark/data/Relink_Mask/01code/dataProcessing.r
path <- getwd()
folds <- dir("../",full.names=T,all.files=F,recursive=T)
folds <- list.dirs("../")
for(fold in folds){
files <- list.files(fold)
for(file in files){
file <- file.path(fold,file, fsep=.Platform$file.sep)
if (file.exists(file) & grepl(".csv",file)) {
changeToZero(file)
}
}
}
changeToZero <- function(file) {
if (!file.exists(file)) { return(NULL) }
all.data <- read.csv(file,header = TRUE)
all.data$Defective <- ifelse(all.data$Defective == "1", 1, 0)
write.csv(all.data,file = file,sep = "",row.names = FALSE)
}
| 7f931989f3c7ea4cf1fa5ce29a110a8d41a168f2 | [
"Java",
"R"
] | 4 | Java | Hecoz/CrossPare | 046d228bdb2ae1925a4461ddc77155066f25c9a7 | 1156f4e53893a5f7ee6997a1fd45a727c71d1f69 |
refs/heads/main | <repo_name>pburkett/vendr<file_sep>/app/Models/Currency.js
export default class Currency {
constructor(num) {
this.num = num
console.log('hello from Currency.js');
}
dis() {
console.log(`${this.num} quarters`);
}
}
<file_sep>/app/Services/InventoryService.js
import { ProxyState } from "../AppState.js";
import ItemForSale from "../Models/ItemForSale.js";
class InventoryService {
constructor() {
console.log('hello from inventoryservice.js');
ProxyState.inventory = {
cookie: new ItemForSale("Chocolate Chip Cookies", 3.75, 5, false),
butter: new ItemForSale("Butter", 3.25, 3, false),
pickle: new ItemForSale("Pickle", 1, 1, false),
krispie: new ItemForSale("Rice Krispie Treat", .5, 20, false)
}
}
buy(itemKey) {
let items = ProxyState.inventory
ProxyState.currency = ProxyState.currency - items[itemKey]['price']
items[itemKey]['quantity'] -= 1
if (items[itemKey]['quantity'] == 0) {
delete items[itemKey]
}
ProxyState.inventory = items
}
}
export const inventoryService = new InventoryService()<file_sep>/app/main.js
import ValuesController from "./Controllers/ValuesController.js";
import InventoryController from "./Controllers/InventoryController.js"
import CurrencyController from "./Controllers/CurrencyController.js"
class App {
valuesController = new ValuesController();
inventoryController = new InventoryController();
currencyController = new CurrencyController();
}
window["app"] = new App();
<file_sep>/app/Services/CurrencyService.js
import { ProxyState } from "../AppState.js";
import Currency from "../Models/Currency.js";
class CurrencyService {
constructor() {
console.log('hello from currencyService.js');
}
addQuarter() {
console.log('quarter added');
ProxyState.currency = ProxyState.currency + .25
for (let key in ProxyState.inventory) {
console.log(`checked ${key} for afford`);
(ProxyState.inventory[key].purchasable) = (ProxyState.inventory[key].price <= ProxyState.currency)
ProxyState.inventory = ProxyState.inventory
}
}
}
export const currencyService = new CurrencyService();
| 5309dd5a90443bdc5d5a5fe34edb7b4a15640c87 | [
"JavaScript"
] | 4 | JavaScript | pburkett/vendr | 90730db96a9e4ed827a38d61457ac66cc8195e32 | d203df3a1cf64229d0acd052fca2f8cd1e2e7b2a |
refs/heads/master | <file_sep>using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccess.Abstract;
namespace DataAccess.Concrete
{
//public class InMemoryCarDal : ICarDal
public class InMemoryCarDal
{
//List<Car> _cars;
//public InMemoryCarDal()
//{
// _cars = new List<Car>
// {
// new Car {CarId = 1, BrandId = new Brand{BrandId = 1,BrandName = "BMW"}, ColorId = new Color{ColorId = 1,ColorName = "BLACK"}, DailyPrice = 250, Description = "316i Diesel Manuel", ModelYear = 2020},
// new Car {CarId = 2, BrandId = new Brand{BrandId = 1,BrandName = "BMW"}, ColorId = new Color{ColorId = 2,ColorName = "GREY"}, DailyPrice = 300, Description = "320d Diesel Automatic", ModelYear = 2018},
// new Car {CarId = 3, BrandId = new Brand{BrandId = 2,BrandName = "FORD"}, ColorId = new Color{ColorId = 3,ColorName = "WHITE"}, DailyPrice = 150, Description = "Focus Diesel Manuel", ModelYear = 2019},
// new Car {CarId = 4, BrandId = new Brand{BrandId = 3,BrandName = "FIAT"}, ColorId = new Color{ColorId = 3,ColorName = "WHITE"}, DailyPrice = 100, Description = "Linea 1.6 Diesel Manuel", ModelYear = 2018},
// new Car {CarId = 5, BrandId = new Brand{BrandId = 4,BrandName = "FIAT"}, ColorId = new Color{ColorId = 1,ColorName = "BLACK"}, DailyPrice = 150, Description = "1.5 T3 Diesel Automatic", ModelYear = 2019},
// new Car {CarId = 6, BrandId = new Brand{BrandId = 4,BrandName = "VOLVO"}, ColorId = new Color{ColorId = 1,ColorName = "BLACK"}, DailyPrice = 250, Description = "150b T3 Diesel Manuel", ModelYear = 2019},
// new Car {CarId = 7, BrandId = new Brand{BrandId = 4,BrandName = "VOLVO"}, ColorId = new Color{ColorId = 4,ColorName = "RED"}, DailyPrice = 300, Description = "1.6 XQ Diesel Manuel", ModelYear = 2019}
// };
//}
//public void Add(Car car)
//{
// _cars.Add(car);
//}
//public void Delete(Car car)
//{
// Car carToDelete = _cars.SingleOrDefault(c => c.CarId == car.CarId);
// _cars.Remove(carToDelete);
//}
//public void Update(Car car)
//{
// Car carToUpdate = _cars.SingleOrDefault(c => c.CarId == car.CarId);
// carToUpdate.BrandId = car.BrandId;
// carToUpdate.ColorId = car.ColorId;
// carToUpdate.DailyPrice = car.DailyPrice;
// carToUpdate.Description = car.Description;
// carToUpdate.ModelYear = car.ModelYear;
//}
//public List<Car> GetAll()
//{
// return _cars;
//}
//public List<Car> GetById(int carId)
//{
// return _cars.Where(c => c.CarId == carId).ToList();
//}
//public List<Car> GetByColor(Color color)
//{
// return _cars.Where(c =>c.ColorId.ColorName == color.ColorName).ToList();
//}
//public List<Car> GetByBrand(Brand brand)
//{
// return _cars.Where(c => c.BrandId.BrandName == brand.BrandName).ToList();
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Business.Abstract;
using DataAccess.Abstract;
using Entities.Concrete;
using Entities.DTOs;
namespace Business.Concrete
{
public class CarManager : ICarService
{
ICarDal _carDal;
public CarManager(ICarDal carDal)
{
_carDal = carDal;
}
public void Add(Car car)
{
if (car.DailyPrice > 0)
{
_carDal.Add(car);
Console.WriteLine("Car Id: {0}\t DailyPrice: {1}\t başarıyla eklendi.", car.CarId, car.DailyPrice);
}
else
{
Console.WriteLine("Başarısız. Eklenemedi. Fiyat 0'dan fazla olmalı.");
}
}
public void Delete(Car car)
{
_carDal.Delete(car);
Console.WriteLine("Başarıyla silindi.");
}
public List<Car> GetAll()
{
return _carDal.GetAll();
}
public List<Car> GetByDailyPrice(decimal min, decimal max)
{
return _carDal.GetAll(c => c.DailyPrice >= min && c.DailyPrice <= max);
}
public Car GetById(int carId)
{
return _carDal.Get(c => c.CarId == carId);
}
public List<Car> GetByModelYear(string modelYear)
{
return _carDal.GetAll(c => c.ModelYear == modelYear);
}
public List<CarDetailDto> GetCarDetails()
{
return _carDal.GetCarDetails();
}
public List<Car> GetCarsByBrandId(int brandId)
{
return _carDal.GetAll(b => b.BrandId == brandId);
Console.WriteLine("ID = " + brandId + " Olan arabalar");
}
public List<Car> GetCarsByColorId(int colorId)
{
return _carDal.GetAll(co => co.ColorId == colorId);
}
public void Update(Car car)
{
_carDal.Update(car);
Console.WriteLine("Başarıyla güncellendi.");
}
}
}
<file_sep>using Business.Concrete;
using System;
using System.Threading.Channels;
using DataAccess.Concrete;
using DataAccess.Concrete.EntityFramework.Repository;
using Entities.Concrete;
using Entities.DTOs;
namespace ConsoleUserInterface
{
public class Program
{
static void Main(string[] args)
{
CarManager carManager = new CarManager(new EfCarDal());
ColorManager colorManager = new ColorManager(new EfColorDal());
BrandManager brandManager = new BrandManager(new EfBrandDal());
Console.WriteLine("\t\t Ne yapmak istiyorsunuz? \t\t");
Console.WriteLine(" 1 - Yeni Araba Ekle\n 2 - Yeni Marka Ekle\n 3 - Yeni Renk Ekle\n 4 - Renk ID'sine göre getir.\n 5 - Marka ID'sine Göre Getir.\n 6 - Günlük Kiralama Fiyatına Göre Getir.\n 7 - Model Yılına Göre Getir.\n 8 - Hepsini Getir.");
var deger = Convert.ToInt32(Console.ReadLine());
string karakterselDeger = "";
int degerInt = 0;
switch (deger)
{
case 1:
Car car1 = new Car();
Console.Write("Marka İsmi: ");
car1.BrandId = Convert.ToInt32(Console.ReadLine());
Console.Write("\nRenk: ");
car1.ColorId = Convert.ToInt32(Console.ReadLine());
Console.Write("\nKiralama Fiyatı: ");
car1.DailyPrice = Convert.ToInt32(Console.ReadLine());
Console.Write("\nModel Yılı: ");
car1.ModelYear = Console.ReadLine();
Console.Write("\nBilgi: ");
car1.Description = Console.ReadLine();
carManager.Add(car1);
break;
case 2:
Brand brand1 = new Brand();
Console.WriteLine("Marka İsmi: ");
brand1.BrandName = Console.ReadLine();
brandManager.Add(brand1);
break;
case 3:
Color color1 = new Color();
Console.Write("Renk: ");
color1.ColorName = Console.ReadLine();
colorManager.Add(color1);
break;
case 4:
Console.Write("Renk ID Giriniz: ");
degerInt = Convert.ToInt32(Console.ReadLine());
foreach (var car in carManager.GetCarsByColorId(degerInt))
{
Console.WriteLine(car.CarId + car.BrandId + car.ColorId + car.DailyPrice + car.ModelYear + car.Description);
}
break;
case 5:
Console.Write("Marka ID Giriniz: ");
degerInt = Convert.ToInt32(Console.ReadLine());
foreach (var car in carManager.GetCarsByBrandId(degerInt))
{
Console.WriteLine(car.CarId + car.BrandId + car.ColorId + car.DailyPrice + car.ModelYear + car.Description);
}
break;
case 6:
Console.WriteLine("--Günlük Kiralama Fiyat Aralığı Giriniz--");
Console.Write("En Düşük: ");
var sayiMin = Convert.ToInt32(Console.ReadLine());
Console.Write("En Yüksek: ");
var sayiMax = Convert.ToInt32(Console.ReadLine());
foreach (var car in carManager.GetByDailyPrice(sayiMin, sayiMax))
{
ShowData(car);
}
break;
case 7:
Console.Write("İstediğiniz Model Tarihi Giriniz: ");
karakterselDeger = Console.ReadLine();
foreach (var car in carManager.GetByModelYear(karakterselDeger))
{
ShowData(car);
}
break;
case 8:
foreach (var car in carManager.GetCarDetails())
{
ShowDataDetails(car);
}
break;
}
}
private static void ShowData(Car car)
{
Console.WriteLine(
"Car ID: {0}\t Brand ID: {1}\t Color ID: {2}\t DailyPrice: {3}\t Model Year: {4}\t Description: {5}", car.CarId,
car.BrandId, car.ColorId, car.DailyPrice, car.ModelYear, car.Description);
}
private static void ShowDataDetails(CarDetailDto car)
{
Console.WriteLine("Car ID: {0}\t Brand: {1}\t Color: {2}\t DailyPrice: {3}", car.CarId, car.BrandName,
car.ColorName, car.DailyPrice);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Business.Abstract;
using DataAccess.Abstract;
using Entities.Concrete;
namespace Business.Concrete
{
public class BrandManager : IBrandService
{
IBrandDal _brandDal;
public BrandManager(IBrandDal brandDal)
{
_brandDal = brandDal;
}
public void Add(Brand brand)
{
if (brand.BrandName.Length > 2)
{
_brandDal.Add(brand);
Console.WriteLine(brand.BrandName+" başarıyla eklendi.");
}
else
{
Console.WriteLine("Lütfen 2 karakterden fazla karakter giriniz.");
}
}
public void Delete(Brand brand)
{
_brandDal.Delete(brand);
Console.WriteLine(brand.BrandName +" başarıyla silindi.");
}
public List<Brand> GetAll()
{
return _brandDal.GetAll();
}
public Brand GetById(int brandId)
{
return _brandDal.Get(b => b.BrandId == brandId);
}
public void Update(Brand brand)
{
_brandDal.Update(brand);
Console.WriteLine(brand.BrandName+" başarıyla güncellendi.");
}
}
}
| e08375872af8ee4346b6b3efbad033b4e831c20d | [
"C#"
] | 4 | C# | haydarrgobell/ReCapProject | 4844c11546e03dba4b6ff7789ee6880399defab6 | 113819ecbf03647576a6afda19e8e57d0d62600a |
refs/heads/master | <repo_name>bhupesh17040/Shortest-distance-calculator<file_sep>/gitpart5.py
# HOMEWORK ASSIGNMENT 3
from sys import maxsize as maxi
#FUNCTION TO INPUT GLOBAL LISTS
def lists_input(n=5,connections=[],weights=[]):
T=''
for i in range (n):
x =[]
z =[]
T = int(input())
for j in range(T):
y =str(input())
y =y.split(' ')
x.append(int(y[0]))
z.append(int(y[1]))
weights.append(z)
connections.append(x)
#FUNCTION TO SOLVE DIJKSTRA'S SINGLE SOURCE SHORTEST PATH PROBLEM
def dijkstra(a,graph):
#SPLITTING THE GRAPH BACK INTO CONNECTIONS,WEIGHTS
connections=graph[0]
weights=graph[1]
#LIST OF UNVISITED VERTICES
Q=[]
#LIST CONTAINING DIJKSTRA DISTANCE
dist =[]
# FOR LOOP TO INITIALISE ((Q WITH ALL THE VERTICES)) AND ((DIST WITH INFINITY))
for i in range(len(connections)):
dist.append(maxi)
Q.append(i)
dist[a] = 0
while len(Q) > 0:
# LIST CONTAINING DISTANCES FROM SOURCE OF VERICES PRESENT IN Q
dist_copy =[]
for i in Q:
dist_copy.append(dist[i])
#FINDING THE VERTEX NUMBER AT MINIMUM DISTANCE
for i in Q:
if min(dist_copy)== dist[i]:
u = i
break
Q.remove(u)
#GETTING THE DISTANCES OF THAT VERTEX'S NEIGHBOURS
i=0
for v in connections[u]:
temp = dist[u] + weights[u][i]
dist[v] = min(dist[v],temp)
#INCREMENTING IT TO ACCESS THE NEXT INDEX OF WEIGHT
i+=1
#RETURNING THE DIJKSTRA DISTANCE
return dist
#FUNCTION TO SOLVE BREADTH FIRST SEARCH PROBLEM
def breadthfirstsearch(a,graph):
# SPLITTING THE GRAPH BACK INTO CONNECTIONS,WEIGHTS
connections=graph[0]
weights=graph[1]
#LIST OF UNVISITED VERTCES
Q=[]
#LIST CONTAINING DIJKSTRA DISTANCE
dist=[]
dist=dijkstra(a,graph)
dist_bfs=[]
#INITIALISING Q WITH VERTICES WITHOUT INFINITE DISTANCES
for i in range(len(dist)):
dist_bfs.append(maxi)
if dist[i]!= maxi:
Q.append(i)
# LIST TO TAKE THE BFS PATH
bfs=[]
# LIST TO TAKE ALL THE LAYERS, WITH EACH LAYER IN EACH INDEX
layers=[]
layers.append([a])
# WILL BE USED TO ACCESS THE FIRST LAYER
i=0
dist_bfs[a]=0
# CREATING A COPY OF Q, WILL BE USED IN FINDING THE DIST_BFS
Q_copy=list(Q)
# THIS LOOP WILL CREATE A LIST OF LAYERS
# THIS LOOP WILL ITERATE TILL Q IS EMPTY
while len(Q) > 0:
x= [] # INITIALLY THE LOOP WILL ITERATE FOR 0'TH LAYER
# IN SECOND ITERATION OF WHILE, IT WILL ITERATE ON 1ST LAYER
#THIS INCREMENT IS MADE THROUGH THE (( i+=1 )) GIVEN AFTER WHILE LOOP
for j in layers[i]:
# VISITED VERTICE WILL NOT VIEWED AGAIN
if j in Q:
#VIEWING IT NOW, SO REMOVING IT FROM Q
Q.remove(j)
#CHECKING OUT THE NEIGHBOURS OF j AND IF IT NOT IN ANY OF THE LAYERS
for v in connections[j]:
if v in Q :
if v in x :
pass
else:
k =False
for i in range(len(layers)):
if v in layers[i]:
k = True
if not k:
#ADDING VERTICES IN iTH LAYER
x.append(v)
# ADDING THE NEXT LAYER
layers.append(x)
#INCREMENTING i TO ACCESS THE NEXT LAYER
i+=1
i=0
j=0
Q_copy.remove(a)
for i in range(len(layers)):
for j in layers[i]:
z=0
for k in connections[j]:
if k in Q_copy:
Q_copy.remove(k)
temp=dist_bfs[j]+weights[j][z]
dist_bfs[k]=temp
z+=1
for i in range(len(layers)):
for j in layers[i]:
bfs.append(j)
#return bfs
return dist_bfs
# FUNCTION TO CHANGE THE WEIGHTS TO 1
def change_weights(graph):
connections=graph[0]
weights=graph[1]
for i in range(len(connections)):
for j in range(len(connections[i])):
weights[i][j]=1
graph=[connections,weights]
# APPLICATION SCRIPT
if __name__ == '__main__':
connections =[]
weights = []
n = int(input())
lists_input(n,connections,weights)
graph=[connections,weights]
# a is the source vertice
a = int(input())
dist = dijkstra(a,graph)
#a is the layer 0 vertice
b = int(input())
dist_bfs = breadthfirstsearch(b,graph)
print (dist)
print (dist_bfs)
change_weights(graph)
dist = dijkstra(a,graph)
dist_bfs = breadthfirstsearch(b,graph)
print (dist)
print (dist_bfs)
<file_sep>/README.md
# shortestdist_17
Added functionality and optimizations(DFS and BFS)
| eadd55fbd702280299eb577f011e4f848b5e0d35 | [
"Markdown",
"Python"
] | 2 | Python | bhupesh17040/Shortest-distance-calculator | d0f659738ad4a3943cedfb28ec72ddcb43063d4b | 8365f1bcbb2a3a9600efdc254664b3f2862160a4 |
refs/heads/master | <file_sep>using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace NaiveBayesSpamminator
{
public class NaiveBayesClassifier
{
private Dictionary<string, Dictionary<bool, double>> vocabularyProbability = new Dictionary<string, Dictionary<bool, double>>();
private Dictionary<bool, double> mailProbability = new Dictionary<bool, double>();
private readonly IList<bool> hypotesis = new List<bool>() { true, false };
public void Learn(string jsonMailProbability, string jsonVocabularyProbability)
{
vocabularyProbability = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<bool, double>>>(jsonVocabularyProbability);
mailProbability = JsonConvert.DeserializeObject<Dictionary<bool, double>>(jsonMailProbability);
}
public void Learn(IList<MailObject> mails) => Learn(mails, new List<string> { });
public void Learn(IList<MailObject> mails, IList<string> stopWords)
{
vocabularyProbability = mails.SelectMany(mail => mail.Text.Split(" "))
.Distinct()
.Where(word => word != string.Empty)
.Where(word => !stopWords.Contains(word))
.ToDictionary(d => d, d => new Dictionary<bool, double>());
foreach (var hypotesi in hypotesis)
{
var docs = mails.Where(d => d.IsSpam == hypotesi);
mailProbability.Add(hypotesi, (docs.Count() + 0.0) / mails.Count());
var builder = new StringBuilder();
foreach (var doc in docs) builder.Append(doc.Text + " ");
var textWords = builder.ToString().Split(" ").Where(d => d != string.Empty);
var totalWordsInText = textWords.Count();
foreach (var wordInVocabulary in vocabularyProbability)
{
var totalOfCasesInTheText = textWords.Count(d => d == wordInVocabulary.Key);
var element = vocabularyProbability.FirstOrDefault(d => d.Key == wordInVocabulary.Key);
element.Value.Add(hypotesi, (totalOfCasesInTheText + 0.0) / (totalWordsInText + vocabularyProbability.Count()));
}
}
//Normalize
foreach (var vocabularyWord in vocabularyProbability)
Normalize(vocabularyWord.Value);
Normalize(mailProbability);
var jsonVocabularyProbability = JsonConvert.SerializeObject(vocabularyProbability);
var jsonEmailProbability = JsonConvert.SerializeObject(mailProbability);
// File.Create($"{Directory.GetCurrentDirectory()}/Data/mail.json");
File.WriteAllBytes($"{Directory.GetCurrentDirectory()}/Data/mail.json", Encoding.UTF8.GetBytes(jsonEmailProbability));
// File.Create($"{Directory.GetCurrentDirectory()}/Data/vocabulary.json");
File.WriteAllBytes($"{Directory.GetCurrentDirectory()}/Data/vocabulary.json", Encoding.UTF8.GetBytes(jsonVocabularyProbability));
}
private void Normalize(Dictionary<bool, double> dict)
{
var total = (dict[true] + dict[false]);
dict[true] = dict[true] / total;
dict[false] = dict[false] / total;
}
public Dictionary<bool, double> Classify(string email)
{
var wordsInVocabulary = email.Split(" ").Where(text => vocabularyProbability.ContainsKey(text));
var probability = new Dictionary<bool, double>();
foreach (var hypotesi in hypotesis)
probability.Add(hypotesi, mailProbability.GetValueOrDefault(hypotesi, 1) * ProbabilityProdutory(wordsInVocabulary, hypotesi));
Normalize(probability);
return probability;
}
private double ProbabilityProdutory(IEnumerable<string> words, bool isSpam)
{
double prod = 1.0;
foreach (var word in words)
{
var multiplier = vocabularyProbability.GetValueOrDefault(word, new Dictionary<bool, double>
{
{ isSpam, 1 }
}).GetValueOrDefault(isSpam, 1);
if (multiplier == 0)
multiplier = 1;
prod *= multiplier;
}
return prod;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace NaiveBayesSpamminator
{
public class Program
{
public static void Main(string[] args)
{
var fileNames = Directory.GetFiles($"{Directory.GetCurrentDirectory()}/TrainingData", "*.csv");
var random = new Random(42);
var mails = new List<MailObject>();
foreach (var fileName in fileNames)
{
var csvLines = File.ReadAllLines(fileName, Encoding.UTF8)
.Skip(1)
.OrderBy(d => random.Next())
.ToList();
foreach (var line in csvLines.Take(100).ToList())
{
var item = line.Split("\",");
mails.Add(new MailObject
{
Text = item[0],
IsSpam = item[1] == "1"
});
}
}
var spamCount = mails.Where(d => d.IsSpam).Count();
var notSpamCount = mails.Where(d => !d.IsSpam).Count();
Console.WriteLine("Spams: " + spamCount);
Console.WriteLine("Não Spams: " + notSpamCount);
var trainingDataCount = (int)(mails.Count() * 0.8);
var trainingData = mails.Take(trainingDataCount).ToList();
var validationDataCount = mails.Count() - trainingDataCount;
var validationData = mails.TakeLast(validationDataCount).ToList();
var withoutStopWordsBayes = new NaiveBayesClassifier();
Console.WriteLine("Sem Stop Words");
Analyze(withoutStopWordsBayes, trainingData, validationData, new List<string> { });
Console.WriteLine();
Console.WriteLine("Com Stop Words");
var withStopWordsBayes = new NaiveBayesClassifier();
var stopWords = trainingData.Where(d => d.IsSpam)
.SelectMany(d => d.Text.Split(" "))
.GroupBy(d => d)
.Select(d => new
{
Word = d.Key,
Count = d.Count()
})
.Where(d => d.Count >= 150)
.OrderByDescending(d => d.Count)
.ToList();
var stringBuilder = new StringBuilder();
foreach (var word in stopWords)
stringBuilder.AppendLine($"{word.Word}=={word.Count}");
File.WriteAllBytes($"{Directory.GetCurrentDirectory()}/Data/stopWords.csv", Encoding.UTF8.GetBytes(stringBuilder.ToString()));
Analyze(withStopWordsBayes, trainingData, validationData, stopWords.Select(d => d.Word).ToList());
Console.ReadLine();
}
private static void Analyze(NaiveBayesClassifier bayes, List<MailObject> trainingData, List<MailObject> validationData, IList<string> stopWords)
{
bayes.Learn(trainingData, stopWords);
var success = 0;
var fail = 0;
foreach (var mail in validationData)
{
var result = bayes.Classify(mail.Text);
if (result[mail.IsSpam] >= 0.5)
success++;
else
fail++;
}
Console.WriteLine("Acertos: " + success);
Console.WriteLine("Erros: " + fail);
Console.WriteLine("Total: " + (success + fail));
}
}
}
<file_sep>using System;
namespace NaiveBayesSpamminator
{
public class MailObject
{
public string Text { get; set; }
public bool IsSpam { get; set; }
public MailObject() { }
public MailObject(string text) : this(text, "\n") { }
public MailObject(string text, string separator)
{
var separatedText = text.Split(separator);
Text = separatedText[0];
IsSpam = Convert.ToBoolean(separatedText[1]);
}
}
}
| 0469e03d8b604a477c065b77f06779caeee022f4 | [
"C#"
] | 3 | C# | Ander02/NaiveBayesSpamminator | ccec14459c6f82d3a8013659bd02a6eff0eb4b83 | b20c5140d37db3c483cdce876d3c83e03f2d3d29 |
refs/heads/master | <repo_name>dpadawer/ShrimpScampi<file_sep>/sim.py
#Based on Rapid Game Development In Python, by <NAME>
#http://osdcpapers.cgpublisher.com/product/pub.84/prod.11/m.1?
# INTIALISATION
import pygame, math, sys
import random
from pygame.locals import *
screen = pygame.display.set_mode((1920, 760), FULLSCREEN)
clock = pygame.time.Clock()
TOTAL_LANES = 3
THRESHOLD = .1
LTORBIAS = 0
RTOLBIAS = 0
XLIMIT = 1920 * 20
EPSILON = .01
DMG = 2
COMFORTBRAKE = 3
MINSPACE = 20
DTH = 1.5
LENGTH = 5
MAXACCEL = 1
SAFETYCRIT = 10
TIMEWARP = 1
CRASHES = 0
SPAWNTHRESHOLD = .95
TOPBUF = 9
addIdx = 0
#Since a car is 5 pixels wide, we will define a lane as 9 pixels
#Lane centers will start at y = 9 (then 18, 27, 36...)
class CarSprite(pygame.sprite.Sprite):
def __init__(self, image, xposition, yposition, startVelocity, desiredVelocity, desiredMinGap, comfortableBraking, politeness, minSpace, desTimeHead, length, maxAcceleration, name):
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(image)
#print(name, xposition, yposition)
self.xpos = xposition
self.ypos = yposition
self.name = name
self.curVel = startVelocity
self.curAcc = 0
self.desVel = desiredVelocity
self.desMinGap = desiredMinGap
self.safetyCrit = SAFETYCRIT
self.length = length
self.curLane = int((self.ypos - TOPBUF) / 9)
self.targetLane = int((self.ypos - TOPBUF) / 9)
self.maxAccel = maxAcceleration
self.comfortBrake = comfortableBraking
self.pol = politeness
self.minSpacing = minSpace
self.desTimeHeadway = desTimeHead
self.rect = pygame.Rect(self.xpos, self.ypos, 5, 2)
self.crashed = False
self.passing = False
self.color = ((0, 255, 0))
def __repr__(self):
return self.name + "={Pos: " + str((self.xpos, self.ypos)) + "; curVel, desVel: " + str((self.curVel, self.desVel)) + "; curLane, targetLane: " + str((self.curLane, self.targetLane)) + ", Color: " + str(self.color) + ", Passing?: " + str(self.passing) + "}"
#Problem: if we update acc, vel, and pos all in one pass, there is simultaneousness being removed
#Hacky solution: 2 passes - first is update acc/vel, second is position
#We claim this is valid (with regards to possesing a lane) since people (hopefully) use their blinker
def update(self, deltat, carGroup, passNo, screen):
# SIMULATION
#print("Updating " + self.__repr__() + ". Pass " + str(passNo))
if(self.xpos <= -200 or self.ypos >= 760 or self.ypos <= -200):
carGroup.remove(self)
self.kill()
return
if(self.xpos >= XLIMIT):
carGroup.remove(self)
return
'''
self.xpos = self.xpos - XLIMIT
self.ypos = self.ypos + 150
'''
if(passNo == 0):
self.color = ((0, 255, 0))
nears = self.findNears(carGroup)
#print(nears)
accels = self.calcAccels(nears, carGroup)
#print("Calculated accels:")
#print(accels)
accels[0] = accels[0] + RTOLBIAS
accels[2] = accels[2] + LTORBIAS
#print(self.name)
#print("Modified accels:")
#if(self.curLane == 1 and not self.passing):
#print(accels)
which = accels.index(max(accels))
#if(self.curLane == 1 and not self.passing):
#print("Desired is " + str(which))
if(accels[2] >= accels[1] + THRESHOLD and accels[2] >= accels[0] + THRESHOLD):
which = 2
elif(accels[1] >= accels[2] + THRESHOLD and accels[1] >= accels[0] + THRESHOLD):
which = 1
else:
which = accels.index(max(accels))
accels[0] = accels[0] - RTOLBIAS
accels[2] = accels[2] - LTORBIAS
#print("Chose " + str(which))
#print("Passing? " + str(self.passing))
if(max(accels) < -20):
car_group.remove(self)
return
if(not self.passing):
if(which == 2 and self.isSafe(nears[4], nears[5], SAFETYCRIT)):
#Merge right
self.targetLane = self.curLane + 1
self.curAcc = accels[2]
self.passing = True
#print("Switching right")
elif(which == 0 and self.isSafe(nears[0], nears[1], SAFETYCRIT)):
#Merge left
self.targetLane = self.curLane - 1
self.curAcc = accels[0]
self.passing = True
#print("Switching left")
else:
#Don't bother
self.targetLane = self.curLane
self.curAcc = accels[1]
#if(self.curLane == 1 and not self.passing):
#print("Staying put")
else:
self.curAcc = accels[1]
self.curVel = self.curVel + self.curAcc
elif(passNo == 1):
self.xpos = self.xpos + self.curVel
if(self.curLane > self.targetLane):
#print(self.ypos)
self.ypos = self.ypos - 3
#print("Moving left")
#print(self.ypos)
#self.curLane = self.targetLane
elif(self.curLane < self.targetLane):
#print(self.ypos)
self.ypos = self.ypos + 3
#print("Moving right")
#print(self.ypos)
#self.curLane = self.targetLane
if(self.ypos % 9 == 0):
self.curLane = self.targetLane
#print("Set curLane of " + self.__repr__() + " to " + str(self.curLane) + ", target lane is " + str(self.targetLane))
self.targetLane = self.curLane
self.passing = False
#else:
#self.color = ((0, 0, 255))
#print(self.__repr__())
#print(self.name)
self.rect = self.src_image.get_rect()
#print(self.xpos, int(self.xpos))
self.rect.centerx = int(self.xpos)
#print(self.ypos, int(self.ypos))
self.rect.centery = int(self.ypos)
self.happiness = math.fabs(self.curVel - self.desVel)
#So wrong.
if(passNo == 2):
carsHit = pygame.sprite.spritecollide(self, carGroup, False)
# > 1 instead of > 0 since spritecollide(car, carGroup) will always return it crashed with itself
if(len(carsHit) > 1):
self.crashed = True
else:
self.crashed = False
if(self.happiness <= 5):
self.color = ((0, 255, 0))
elif(self.happiness <= 10):
self.color = ((0, 0, 255))
else:
self.color = ((255, 0, 0))
if(self.crashed):
#print("That's a crash!")
self.color = ((255, 255, 255))
self.curVel = self.curVel / 2
tmp = self.curLane
self.curLane = self.targetLane
self.targetLane = tmp
pygame.draw.rect(screen, self.color, self.rect)
#print("Finished updating " + self.__repr__())
if(self.curVel < 0):
#print(self.name + " has a velocity of " + str(self.curVel))
self.curVel = 0
#sys.exit(0)
if(math.fabs(self.curVel) > 1000000):
carGroup.remove(self)
def findNears(self, carGroup):
#We now want a list with 6 elements: nearestAheadLeft, nearestBehindLeft, nearestAheadSame, nearestBehindSame, nearestAheadRight, nearestBehindRight
#We define "ahead" as ypos >= to ours,
# behind as ypos < ours
# (So we don't get a car marked as both ahead of and behind us)
#TODO: Is that actually appropraite/acceptable/correct?
dists = [sys.maxint for x in range(6)]
nears = [None for x in range(6)]
#Might be able to do this some clever way, but this is (fairly) simple, albeit ugly
for car in carGroup:
if(car == self): continue
dist = math.fabs(car.xpos - self.xpos)
if(car.curLane == self.curLane - 1 or car.targetLane == self.curLane - 1):
if(car.xpos >= self.xpos):
if(dist < dists[0]):
nears[0] = car
dists[0] = dist
else:
if(dist < dists[1]):
nears[1] = car
dists[1] = dist
elif(car.curLane == self.curLane or car.targetLane == self.curLane):
if(car.xpos >= self.xpos):
if(dist < dists[2]):
nears[2] = car
dists[2] = dist
else:
if(dist < dists[3]):
nears[3] = car
dists[3] = dist
elif(car.curLane == self.curLane + 1 or car.targetLane == self.curLane + 1):
if(car.xpos >= self.xpos):
if(dist < dists[4]):
nears[4] = car
dists[4] = dist
else:
if(dist < dists[5]):
nears[5] = car
dists[5] = dist
'''
if(nears[0] != None): print ("Returning left: " + nears[0].name)
else: print("None on left")
if(nears[2] != None): print ("Returning center: " + nears[2].name)
else: print("None on center")
if(nears[4] != None): print ("Returning right: " + nears[4].name)
else: print("None on right")
'''
return nears
def calcAccels(self, nears, carGroup):
accels = [0 for x in range(3)]
if(self.curLane == 0):
accels[0] = -sys.maxint
else:
if(nears[0] == None):
accels[0] = self.maxAccel * self.calcAccelFree()
else:
accels[0] = self.maxAccel * self.calcAccelInt(nears[0], carGroup)
if(nears[2] == None):
accels[1] = self.maxAccel * self.calcAccelFree()
else:
accels[1] = self.maxAccel * self.calcAccelInt(nears[2], carGroup);
if(self.curLane == TOTAL_LANES - 1):
accels[2] = -sys.maxint
else:
if(nears[4] == None):
accels[2] = self.maxAccel * self.calcAccelFree()
else:
accels[2] = self.maxAccel * self.calcAccelInt(nears[4], carGroup);
if(not self.isSafe(nears[0], nears[1], self.safetyCrit)):
#print("left not safe")
accels[0] = -sys.maxint
if(not self.isSafe(nears[4], nears[5], self.safetyCrit)):
#print("right not safe")
accels[2] = -sys.maxint
return accels
def calcAccelDanny(self, ahead):
if(self.curVel <= self.desVel):
if(ahead == None):
#Treat as at infinity
return min((self.desVel - self.curVel / self.desVel), self.maxAccel)
else:
return min((self.desVel - min(self.curVel, ahead.curVel)) / self.desVel, self.maxAccel)
else:
return -min(math.fabs(self.comfortBrake), math.fabs((self.desVel - self.curVel) / self.desVel))
def calcAccelFree(self):
#print("calcAccelFree Returning " + str(self.maxAccel * (1 - ((self.curVel / self.desVel) ** 4))))
return (1 - ((self.curVel / self.desVel) ** 4))
def calcAccelInt(self, ahead, carGroup):
#print("self: " + self.__repr__())
#print("ahead: " + ahead.__repr__())
#delvalpha = self.curVel - ahead.curVel
delvalpha = self.curVel - ahead.curVel
if(math.fabs(delvalpha) > 250):
print("dangerous delvalpha found: self: " + self.__repr__() + "; ahead: " + ahead.__repr__())
#print("self.curVel: " + str(self.curVel) + ", ahead.curVel: " + str(ahead.curVel))
'''
term3Num = self.curVel * delvalpha
term3Denom = 2 * math.sqrt(self.maxAccel * self.comfortBrake)
term3 = term3Num / term3Denom
term2 = self.curVel * self.desTimeHeadway
term1 = self.minSpacing
sstar = term1 + term2 + term3
'''
term1 = self.minSpacing
term2 = self.desTimeHeadway * self.curVel
term3Num = delvalpha
term3Denom = 2 * self.desTimeHeadway * math.sqrt(self.maxAccel * self.comfortBrake)
term3 = term3Num / term3Denom
actualTerm2 = math.exp(term3) * term2
sstar = term1 + actualTerm2
salpha = ahead.xpos - self.xpos - ahead.length
if(salpha == 0):
#print("calcAccelInt Returning -sys.maxint")
return -sys.maxint
freeAccel = self.calcAccelFree()
interim = (sstar ** 2) / (salpha ** 2)
#print("calcAccelInt Returning " + str(-self.maxAccel * ((sstar / salpha) ** 2)))
return (freeAccel - interim)
#TODO: Potentially set different safety criteria for ahead and behind
def isSafe(self, aheadCar, behindCar, safetyCrit):
#Account for length?
#print("In isSafe with " + self.name)
forwardVal = 0
behindVal = 0
if(aheadCar == None):
forwardVal = sys.maxint
else:
forwardVal = math.fabs(aheadCar.xpos - self.xpos)
forwardVal = self.desMinGap + self.curVel * self.desTimeHeadway
#print(forwardVal)
if(behindCar == None):
behindVal = sys.maxint
else:
behindVal = math.fabs(behindCar.xpos - self.xpos)
behindVal = self.desMinGap + behindCar.curVel * self.desTimeHeadway
#print(behindVal)
if(forwardVal > safetyCrit and behindVal > safetyCrit):
#print("Returning true")
return True
#print("Returning false")
return False
def DrawRoad(screen, startY):
pygame.draw.line(screen, (255, 255, 255), [0, startY], [1920, startY], 1)
for i in range(1, TOTAL_LANES):
pygame.draw.line(screen, (125, 125, 125), [0, startY + 9 * i], [1920, startY + 9 * i], 1)
pygame.draw.line(screen, (255, 255, 255), [0, startY + TOTAL_LANES * 9], [1920, startY + TOTAL_LANES * 9], 1)
def GetLaneStats(laneNo, carGroup):
totalR = 0
totalB = 0
totalG = 0
totalCurSpeed = 0
totalDesSpeed = 0
for car in carGroup:
if(car.curLane != laneNo): continue
if(car.happiness <= 5):
totalG = totalG + 1
elif(car.happiness <= 10):
totalB = totalB + 1
else:
totalR = totalR + 1
totalCurSpeed = totalCurSpeed + car.curVel
totalDesSpeed = totalDesSpeed + car.desVel
totalCars = totalR + totalB + totalG
avgCurSpeed = 0 if totalCars == 0 else totalCurSpeed / totalCars
avgDesSpeed = 0 if totalCars == 0 else totalDesSpeed / totalCars
print("(R, G, B): " + str((totalR, totalG, totalB)) + "; Average Speeds (cur, des): " + str((avgCurSpeed, avgDesSpeed)))
def DumpAll(carGroup, curTime):
for car in carGroup:
print(str((curTime, car.name, car.curLane, car.targetLane, car.curVel, car.desVel, car.xpos, car.ypos, car.curAcc)))
def CountCrashes(carGroup):
toRet = 0
for car in carGroup:
if(car.crashed):
toRet = toRet + 1
return toRet
# Make a couple of cars
#img, xPos, yPos, startVel, desVel, DMG, comfortBrake, politeness, minSpace, DTH, len, maxAcc):
'''
car1 = CarSprite('car1.png', 50, TOTAL_LANES * 9, 30, 45, 10, 3, 1, 5, 1.5, 10, 1, "Car1") #Red
car2 = CarSprite('car2.png', 75, TOTAL_LANES * 9, 24, 35, 10, 3, 1, 5, 1.5, 10, 1, "Car2") #Blue
car3 = CarSprite('car3.png', 100, TOTAL_LANES * 9, 21, 25, 10, 3, 1, 5, 1.5, 10, 1, "Car3") #Green
cars = [car1, car2, car3]
#cars = [car1]
'''
cars = []
car_group = pygame.sprite.RenderPlain(*cars);
curTime = 0
crashes = 0
while 1:
# USER INPUT
deltat = clock.tick(10)
if(addIdx % 1 == 0 and len(cars) < 1000):
for i in range(0, TOTAL_LANES):
for j in range(0, 1):
startVel = random.randint(30, 35) / TIMEWARP
#car = CarSprite('car' + str(random.randint(1,3)) + ".png", random.randrange(25, 75, 25), random.randrange(9, 9 * TOTAL_LANES, 9), startVel, startVel + (random.randint(-10, 10) / TIMEWARP), DMG, COMFORTBRAKE, 1, MINSPACE, DTH, LENGTH, MAXACCEL, "Car" + str(len(cars)))
#car = CarSprite('car' + str(random.randint(1,3)) + ".png", random.randrange(25, 75, 25), 9 * TOTAL_LANES, startVel, startVel + (random.randint(-10, 10) / TIMEWARP), DMG, COMFORTBRAKE, 1, MINSPACE, DTH, LENGTH, MAXACCEL, "Car" + str(len(cars)))
car = CarSprite('car' + str(random.randint(1,3)) + ".png", j * 50, 9 * (i + 1), startVel, startVel + (random.randint(0, 5) / TIMEWARP), DMG, COMFORTBRAKE, 1, MINSPACE, DTH, LENGTH, MAXACCEL, "Car" + str(len(cars)))
nears = car.findNears(car_group)
if(car.isSafe(nears[0], None, SAFETYCRIT) and car.isSafe(nears[2], None, SAFETYCRIT) and car.isSafe(nears[4], None, SAFETYCRIT) and max(car.calcAccels(nears, car_group)) >= 0):
if(random.random() >= SPAWNTHRESHOLD):
cars.append(car)
car_group = pygame.sprite.RenderPlain(*cars)
#print("Added car:")
#print(car.__repr__())
#print("TICK")
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN
if event.key == K_ESCAPE: sys.exit(0)
# RENDERING
screen.fill((0,0,0))
DrawRoad(screen, 5)
#DrawRoad(screen, 155)
#DrawRoad(screen, 305)
#DrawRoad(screen, 455)
#DrawRoad(screen, 605)
car_group.update(deltat, car_group, 0, screen)
car_group.update(deltat, car_group, 1, screen)
car_group.update(deltat, car_group, 2, screen)
pygame.display.flip()
CRASHES = CRASHES + CountCrashes(car_group)
DumpAll(car_group, curTime)
curTime = curTime + 1
if(curTime >= 500):
print("Total crashes: " + str(CRASHES))
sys.exit(0)
addIdx = addIdx + 1<file_sep>/README.md
ShrimpScampi
============
MCM2014A
Made for the 2014 Mathematical Competition in Modeling, Problem A.
The java file is discrete time steps and places.
sim.py and sim2.py are made with PyGame. sim2.py is a (theoretically) cleaner rewrite of sim.py, once I woke up on day 3 and realized how ugly the code had gotten.
<file_sep>/sim2.py
#Based on Rapid Game Development In Python, by <NAME>
#http://osdcpapers.cgpublisher.com/product/pub.84/prod.11/m.1?
#INITIALISATION
DISPLAYWIDTH = 1800
import pygame, math, sys, random
from pygame.locals import *
screen = pygame.display.set_mode((DISPLAYWIDTH, 700))
clock = pygame.time.Clock()
#Road stuff
LANEWIDTH = 9
UPPERBUF = 9
TOTALLANES = 5
XLIMIT = 50000
#Merging stuff
THRESHOLD = .5
LTORBIAS = 10
RTOLBIAS = 0
#Spawn stuff
SPAWNPERCENT = 1
BASESPEED = 0
SPEEDVAR = 20
#Values from papers
#Note: Length is 12 for display purposes, thus all other distance constants is also multiplied by 3
#These values specifically from http://www.itrn.ie/uploads/sesc3_id153.pdf
COMFBRAKE = 6
POLITENESS = 0
MINSPACE = 6
DESTIMEHEADWAY = 1.2
LENGTH = 12
HEIGHT = 6
MAXACC = 4.5
SAFETYCRIT = LENGTH * 4
#COLORS
GREEN = ((0, 255, 0))
RED = ((255, 0, 0))
BLUE = ((0, 0, 255))
BLACK = ((0, 0, 0))
WHITE = ((255, 255, 255))
GRAY = ((125, 125, 125))
MergeCount = 0
CollisionCount = 0
#HELPER FUNCTIONS
def GetLane(ypos):
return ((ypos - UPPERBUF) / LANEWIDTH) - 1
def GetYForLane(laneNo):
return ((laneNo + 1) * LANEWIDTH) + UPPERBUF
def CompletelyInLane(ypos):
return (ypos - UPPERBUF) % LANEWIDTH == 0
def DumpAll(carGroup, curTime):
for car in carGroup:
if(car.name == "dummy"): continue
print(str(curTime) + ", " + car.name + ", " + str(car.xpos) + ", " + str(car.ypos) + ", " + str(car.curVel) + ", " + str(car.desVel) + ", " + str(car.curAccel) + ", " + str(car.curLane) + ", " + str(car.targetLane))
def DrawLanes(offset):
pygame.draw.line(screen, WHITE, [0, UPPERBUF + offset], [DISPLAYWIDTH, UPPERBUF + offset], 1)
for i in range(1, TOTALLANES):
pygame.draw.line(screen, GRAY, [0, LANEWIDTH * i + UPPERBUF + offset], [DISPLAYWIDTH, LANEWIDTH * i + UPPERBUF + offset], 1)
pygame.draw.line(screen, WHITE, [0, LANEWIDTH * TOTALLANES + UPPERBUF + offset], [DISPLAYWIDTH, LANEWIDTH * TOTALLANES + UPPERBUF + offset], 1)
#GAME CLASSES
class CarSprite(pygame.sprite.Sprite):
def __init__(self, xposition, yposition, startVelocity, desiredVelocity, comfortableBraking, politeness, minimumSpacing, desiredTimeHeadway, length, height, maximumAcceleration, safetyCriteria, name):
pygame.sprite.Sprite.__init__(self)
self.xpos = xposition
self.ypos = yposition
self.curVel = startVelocity
self.desVel = desiredVelocity
self.curAccel = 0
self.maxAccel = maximumAcceleration
self.comfBrake = comfortableBraking
self.minSpace = minimumSpacing
self.desTimeHeadway = desiredTimeHeadway
self.length = length
self.height = height
self.curLane = GetLane(yposition)
self.targetLane = self.curLane
self.passing = False
self.colliding = False
self.name = name
self.politeness = politeness
self.safetyCrit = safetyCriteria
self.rect = pygame.Rect(self.xpos, self.ypos, length, height)
self.color = GREEN
def __repr__(self):
return str((self.name, self.xpos, self.ypos, self.curVel, self.desVel, self.curAccel, self.curLane, self.targetLane))
def update(self, carGroup):
if(self.name == "dummy"): return
#Update accel, then vel, the pos
#print("Updating " + self.__repr__())
if(self.xpos < -100 or self.xpos > XLIMIT):
#print(self.__repr__())
carGroup.remove(self)
self.rect = pygame.Rect(0, 0, 0, 0)
self = None
return
#Can only change lanes if not already mid-change
nears = self.calcNears(carGroup)
#print(nears)
myAccels = [0 for x in range(3)]
rearAccels = [0 for x in range(3)]
rearNewAccels = [0 for x in range(3)]
accelUtilities = [0 for x in range(3)]
#Where I can go
myAccels[1] = self.calcAccel(nears[2])
if(not self.passing):
myAccels[0] = self.calcAccel(nears[0])# if self.curLane > 0 else 0
myAccels[2] = self.calcAccel(nears[4])# if self.curLane < TOTALLANES else 0
#Their accelerations assuming I'm there
rearAccels[0] = nears[1].calcAccel(self)
rearAccels[1] = nears[3].calcAccel(self)
rearAccels[2] = nears[5].calcAccel(self)
#Their accelerations assuming I leave
rearNewAccels[0] = nears[1].calcAccel(nears[0])
rearNewAccels[1] = nears[3].calcAccel(nears[2])
rearNewAccels[2] = nears[5].calcAccel(nears[4])
#Let's calculate them
accelUtilities = [0 for x in range(3)]
accelUtilities[0] = myAccels[0] - self.politeness * (rearAccels[0] + rearNewAccels[1]) + RTOLBIAS
accelUtilities[1] = myAccels[1]
accelUtilities[2] = myAccels[2] - self.politeness * (rearAccels[2] + rearNewAccels[1]) + LTORBIAS
'''
print(self.name + " accels:")
print(myAccels)
print("rearAccels:")
print(rearAccels)
print("rearNewAccels:")
print(rearNewAccels)
print("accel utilities")
print(accelUtilities)
'''
together = zip(accelUtilities, [0,1,2])
sortedTogether = sorted(together)
sortedOrder = [x[1] for x in reversed(sortedTogether)]
#print(sortedOrder)
#if(nears[0].passing or nears[1].passing or nears[2].passing or nears[3].passing or nears[4].passing or nears[5].passing):
#if(nears[1].passing or nears[3].passing or nears[5].passing):
#x = [1]
for x in sortedOrder:
#Check if we can make the merge. If we can, do it and exit the loop
#Otherwise, keep looking
if(x == 2):
if(accelUtilities[2] >= THRESHOLD and self.isSafe(nears[4], nears[5]) and self.curLane < TOTALLANES - 1):
#Merge right
self.curAccel = myAccels[2]
whichLane = 2
self.targetLane = self.curLane + 1
self.passing = True
#print("Choosing right")
break
elif(x == 0):
if(accelUtilities[0] >= THRESHOLD and self.isSafe(nears[0], nears[1]) and self.curLane > 0):
#Merge left
self.curAccel = myAccels[0]
self.targetLane = self.curLane - 1
whichLane = 0
self.passing = True
#print("Choosing left")
break;
else:
#Stay here
self.curAccel = myAccels[1]
#print("Staying put")
break
else:
self.curAccel = myAccels[1]
if(self.passing):
if(self.curLane > self.targetLane):
self.ypos -= 3
else:
self.ypos += 3
if(GetLane(self.ypos) == self.targetLane and CompletelyInLane(self.ypos)):
self.curLane = self.targetLane
self.passing = False
global MergeCount
MergeCount += 1
self.curVel += self.curAccel
self.xpos += self.curVel
#Check for crashes
collisions = pygame.sprite.spritecollide(self, carGroup, False)
if(len(collisions) > 1):
self.color = RED
global CollisionCount
CollisionCount += 1
#print(self.__repr__())
self.rect = pygame.Rect(0, 0, 0, 0)
self.xpos = XLIMIT + 5
self.ypos = 1000
self = None
return
else:
tmp = (math.fabs(self.curVel - self.desVel) / self.desVel)
self.color = ((0, min(max(255 - int(255 * tmp), 0), 255), min(max(0, int(255 * tmp)), 255)))
#print("Finished updating " + self.__repr__())
#Draw
if(self.curVel < 0 or self.xpos < -100 or self.xpos > XLIMIT):
#print(self.__repr__())
self = None
return
#print((self.xpos, self.ypos, self.length, self.height))
self.rect = pygame.Rect(round(self.xpos), round(self.ypos), self.length, self.height)
pygame.draw.rect(screen, self.color, self.rect)
def calcAccel(self, ahead):
if(self.name == "dummy" or ahead == None):
return 0
vav0d = (self.curVel / self.desVel) ** 4
#print("vav0d: " + str(vav0d))
sStarTerm1 = self.minSpace
sStarTerm2 = self.curVel * self.desTimeHeadway
sStarTerm3Num = self.curVel - ahead.curVel
sStarTerm3Denom = 2 * self.desTimeHeadway * math.sqrt(self.maxAccel * self.comfBrake)
sStarTerm3 = sStarTerm3Num / sStarTerm3Denom
if(sStarTerm3 >= 50):
return self.maxAccel
sAlpha = ahead.xpos - self.xpos - ahead.length
if(sAlpha == 0):
#Results in a crash. lim -> -oo, so we're returning a really negative number
return -100000
sStar = sStarTerm1 + sStarTerm2 * math.exp(sStarTerm3)
finalTerm = (sStar / sAlpha) ** 2
#print("sStar / sAlpha squared: " + str(finalTerm))
calcedAccel = self.maxAccel * (1 - vav0d - finalTerm)
#print("Returning " + str(calcedAccel))
return calcedAccel
def calcNears(self, carGroup):
#print("calcNears for " + self.__repr__())
dists = [sys.maxint for x in range(6)]
nears = [None for x in range(6)]
for car in carGroup:
if(car == self): continue
curDist = math.fabs(self.xpos - car.xpos)
#print("Looking at car " + car.__repr__())
#Everybody loook left
if(car.curLane == self.curLane - 1 or car.targetLane == self.curLane - 1):
if(car.xpos >= self.xpos and curDist < dists[0]):
dists[0] = curDist
nears[0] = car
elif(car.xpos <= self.xpos and curDist < dists[1]):
dists[1] = curDist
nears[1] = car
#Everybody loooook right
elif(car.curLane == self.curLane + 1 or car.targetLane == self.curLane + 1):
if(car.xpos >= self.xpos and curDist < dists[4]):
dists[4] = curDist
nears[4] = car
elif(car.xpos <= self.xpos and curDist < dists[5]):
dists[5] = curDist
nears[5] = car
#Everywhere you look...
elif(car.curLane == self.curLane or car.targetLane == self.curLane):
if(car.xpos >= self.xpos and curDist < dists[2]):
dists[2] = curDist
nears[2] = car
elif(car.xpos <= self.xpos and curDist < dists[3]):
dists[3] = curDist
nears[3] = car
#print("calcNears returning " + str(nears))
return nears
def isSafe(self, ahead, behind):
if(ahead == None and behind == None):
return True
elif(ahead == None):
return self.xpos - behind.xpos >= self.safetyCrit
elif(behind == None):
return ahead.xpos - self.xpos >= self.safetyCrit
else:
return ((ahead.xpos - self.xpos >= self.safetyCrit) and (self.xpos - behind.xpos >= self.safetyCrit))
def oldisSafe(self, ahead, behind):
#print("new set")
#print("In is safe for " + self.__repr__())
#print("Ahead: " + ahead.name + "; behind: " + behind.name)
#print(ahead.__repr__())
#Check ahead
if(ahead != None):
sStarTerm1A = self.minSpace
sStarTerm2A = self.curVel * self.desTimeHeadway
sStarTerm3NumA = self.curVel - ahead.curVel
sStarTerm3DenomA = 2 * self.desTimeHeadway * math.sqrt(self.maxAccel * self.comfBrake)
sStarTerm3A = sStarTerm3NumA / sStarTerm3DenomA
if(sStarTerm3A >= 50):
return True
sStarA = sStarTerm1A + sStarTerm2A * math.exp(sStarTerm3A)
if(sStarA < self.safetyCrit):
return false;
#print("sStarA: " + str(sStarA))
if(behind != None):
#Check behind
sStarTerm1B = self.minSpace
#print(sStarTerm1B)
sStarTerm2B = self.curVel * self.desTimeHeadway
#print(sStarTerm2B)
sStarTerm3NumB = self.curVel - behind.curVel
sStarTerm3DenomB = 2 * self.desTimeHeadway * math.sqrt(self.maxAccel * self.comfBrake)
sStarTerm3B = sStarTerm3NumB / sStarTerm3DenomB
#print(sStarTerm3B)
if(sStarTerm3B >= 50):
return True
sStarB = sStarTerm1B + sStarTerm2B * math.exp(sStarTerm3B)
#print("sStarB: " + str(sStarB))
if(sStarB < self.safetyCrit):
return false;
#if((sStarA >= self.safetyCrit * self.curVel or ahead.name == "dummy") and (sStarB >= self.safetyCrit * self.curVel or behind.name == "dummy")):
return True
#START UP SPRITES
#self, x, y, startVel, desVel, comfBrake, p, minSpace, desiredTime, length, height, maxAcc, safetyCrit, name):
#car1 = CarSprite(50, GetYForLane(1), 10, 120, 2, .5, 2, 1.2, 4, 2, 1.5, 25, "car1")
#truck1 = CarSprite(225, GetYForLane(1), 35, 40, 2, 0, 2, 1.2, 12, 6, 1.5, 25, "truck1")
#truck2 = CarSprite(125, GetYForLane(1), 35, 45, 2, 0, 2, 1.2, 12, 6, 1.5, 25, "truck2")
#truck3 = CarSprite(25, GetYForLane(1), 35, 50, 2, 0, 2, 1.2, 12, 6, 1.5, 25, "truck3")
#cars = [car1, truck1]
#cars = [truck1, truck2, truck3]
cars = []
#Add dummy cars beyond infinity, so we can avoid ugly cases in calcAccel
for i in range(-1, TOTALLANES + 2):
endDummyCar = CarSprite(sys.maxint, GetYForLane(i), 120, 120, 1, 1, 1, 1, 1, 1, 1, 1, "dummy")
cars.append(endDummyCar)
startDummyCar = CarSprite(-(sys.maxint / 2), GetYForLane(i), 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, "dummy")
cars.append(startDummyCar)
carGroup = pygame.sprite.RenderPlain(*cars)
curTime = 0
totalSpawned = 0
#GAME LOOP
while 1:
#USER INPUT
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN
if event.key == K_ESCAPE: sys.exit(0)
#UPDATE STUFF
#Draw the background
screen.fill(BLACK)
DrawLanes(7)
#Add any new cars
if(curTime % 3 == 0):
for i in range(0, TOTALLANES):
vel = random.randrange(BASESPEED, BASESPEED + SPEEDVAR)
newCar = CarSprite(25, GetYForLane(i), 0, vel + random.randrange(5, SPEEDVAR), COMFBRAKE, POLITENESS, MINSPACE, DESTIMEHEADWAY, LENGTH, HEIGHT, MAXACC, SAFETYCRIT, "car" + str(totalSpawned))
nears = newCar.calcNears(carGroup)
# and newCar.isSafe(nears[2], nears[3])
if(random.random() <= SPAWNPERCENT):
cars.append(newCar)
totalSpawned += 1
#Update cars appropriately
carGroup = pygame.sprite.RenderPlain(*cars)
carGroup.update(carGroup)
if(curTime % 25 == 0):
print("Time: " + str(curTime) + ", merges: " + str(MergeCount) + ", collisions: " + str(CollisionCount))
#DumpAll(carGroup, curTime)
clock.tick(10)
curTime += 1
pygame.display.flip()
#print("\n") | 69df164836b6032bd89da7ea73482618523e2f13 | [
"Markdown",
"Python"
] | 3 | Python | dpadawer/ShrimpScampi | c3832958012d5407f9ee7ecbb5dd9c103001b437 | 6a8fb7783cfc4773ca5c588faece45fcca0ade24 |
refs/heads/master | <repo_name>DylanKojiCheslin/hackCooper<file_sep>/algorithm/models/Hackathon.js
const mongoose = require("mongoose");
const HackathonSchema = new mongoose.Schema({
name: String,
popularity: Number
});
module.exports = mongoose.model("hackathon", HackathonSchema);
<file_sep>/algorithm/README.md
# Hack-a-find
Monitors Twitter for new hackathons
To collect tweets, run
```shell
node . \
--consumer_key WHATEVER \
--consumer_secret WHATEVER \
--access_token_key WHATEVER \
--access_token_secret WHATEVER
```
To find hackathons from the saved tweets, run `node src/findHackathons.js`
<file_sep>/lambda/isHackathon/README.md
# isHackathon
This AWS Lambda function accepts a name URL parameter and determines if the name is the name of a
hackathon. It determines this by Googling the name and, if the results mention the exact name often
and the word "hackathon" often, it is a hackathon.
To deploy, run `npm run zip && npm run deploy`
<file_sep>/README.md

# Find-A-Hack (Hack Cooper)
As hackers, we know how hard it is to find hackathons, so we designed a web app that scrapes the internet for hackathons. That way, people like us can just open up a website and it'll show ALL the hackathons on the internet, not just the ones that humans found.
# Features
Uses Geocoding from Google API's to use the users current location to only display hackathons that are nearby. We also have a feature that allows the user to choose the max distance from hackathons to display.
# A.I. Algorithm
We parsed through hundreds of recent tweets that include the word "hackathon" and extracted the nouns with NLP. Once we had the nouns, we Googled each noun and, if the results included the noun and had the word "hackathon" often, we assumed that the noun is a hackathon, which we found to be an accurate system. However, Google realized that we were using their search engine hundreds of times a second, so they blocked our IP. We then used AWS Lambda to spawn new virtual computers with various IP addresses; Google couldn't block all the addresses, so we managed to get around Google's anti-spam measures. Amazon 1 Google 0
# Problems/Issues
Our system works fairly well, but in order for this system to work well many requests need to be made. Google and Twitter (as well as many other valuable sources) have rate limits and we can not freely scrape without being resorted to paying for these queries. Our quick fix was trying to use AWS Lambda to generate fake IP-Addresses over a span of time so that we could fool the API's into to giving us more requests/queries... This albeit clever still did not solve the problem fully.
# Overall
We think that using A.I. to find hackathons is a great solution to the lack of a comprehensive list of hackathons.
# API's/Tools
Google Geocoding API
Google Custom Search API
AWS Lambda
Twitter API
Google Search
<file_sep>/Find-A-Hack/app/assets/javascripts/cover.js
//var API_KEY = <KEY>;
//var GEO_KEY = <KEY>;
$(document).ready(function() {
// var newList = getNearBy();
var jsonhacks = generateFakeJson();
var numberOfHacks = jsonhacks.length;
for (var i = 0; i < numberOfHacks; i++) {
createHackViews( jsonhacks[i].name, jsonhacks[i].date,
jsonhacks[i].location, jsonhacks[i].popularity);
//createHackViews('Hack-Cooper', 'September 25, 2016', 'The Cooper Union', '96');
}
// var distance = document.getElementById('distance');
var latLngB = getGeoCodeOf("The Cooper Union");
getLocation(latLngB, 30);
});
/* hard coding some json data until we can implement it on the backend */
function generateFakeJson(){
var json = {};
var hackathons = {};
var hackathon1 = {};
hackathon1["name"] = "Hack-Cooper";
hackathon1["date"] = "September 25, 2016";
hackathon1["location"] = "The Cooper Union";
hackathon1["popularity"] = "100";
var hackathon2 = {};
hackathon2["name"] = "HackRu";
hackathon2["date"] = "Oct 2, 2016";
hackathon2["location"] = "Rutgers University";
hackathon2["popularity"] = "100";
var hackathon3 = {};
hackathon3["name"] = "YettyYU";
hackathon3["date"] = "Oct 5, 2016";
hackathon3["location"] = "Yetty University";
hackathon3["popularity"] = "90";
var hackathon4 = {};
hackathon4["name"] = "<NAME>";
hackathon4["date"] = "Oct 15, 2016";
hackathon4["location"] = "Chicago NYU";
hackathon4["popularity"] = "50";
var hackathon5 = {};
hackathon5["name"] = "<NAME>";
hackathon5["date"] = "Nov 12, 2016";
hackathon5["location"] = "SoHo Texas";
hackathon5["popularity"] = "10";
var hackathon6 = {};
hackathon6["name"] = "<NAME>";
hackathon6["date"] = "Dec 28, 2016";
hackathon6["location"] = "Mexico City";
hackathon6["popularity"] = "76";
json["hackathons"] = [hackathon1, hackathon2, hackathon3, hackathon4, hackathon5, hackathon6];
return json["hackathons"];
}
function getLocation(latLngB, maxDist) {
navigator.geolocation.getCurrentPosition(function(position) {
var latLngA = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// var latLngB = new google.maps.LatLng(lat, lon);
var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);
if(distance < maxDist){
alert(distance);
return true;
} else {
return false;
}
}, function() {
alert("geolocation not supported!!");
});
}
function getGeoCodeOf(address){
var geocoder= new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
var latLngB = new google.maps.LatLng(lat, lon);
return latLngB;
}
});
}
function createHackViews(rname, rdate, rloc, rpop) {
var myDiv = document.getElementById('hack-container');
var newDiv = document.createElement('div');
newDiv.className = 'hackathons-view';
var name = document.createElement('div');
name.id = 'name';
name.innerHTML = rname;
var date = document.createElement('div');
var pdate = document.createElement('p');
date.id = 'date';
$(date).append(pdate);
pdate.innerHTML = rdate;
var location = document.createElement('div');
var ploc = document.createElement('p');
location.id = 'location';
$(location).append(ploc);
ploc.innerHTML = rloc;
var icon = document.createElement('div');
icon.id = 'icon';
var popularity = document.createElement('p');
popularity.id = 'popularity';
icon.innerHTML = rpop;
popularity.innerHTML = '★'
$(popularity).append(icon);
$(newDiv).append(name);
$(newDiv).append(date);
$(newDiv).append(location);
$(newDiv).append(popularity);
$(myDiv).append(newDiv);
}
function getHackathons() {
var element = document.getElementById("name");
element.innerHTML = "New Hackathon";
}
<file_sep>/algorithm/src/findHackathons.js
const fs = require("fs");
const nlp = require("nlp_compromise");
const mongoose = require("mongoose");
const request = require("request");
const Tweet = require("../models/Tweet");
const Hackathon = require("../models/Hackathon");
const isHackathon = (name, ifIsHackathon, ifIsNotHackathon) => request(
`https://kmk26hrd6j.execute-api.us-east-1.amazonaws.com/prod/isHackathon?name=${name}`,
(error, code, result) => {
if (error) {
console.log(error);
return;
}
try {
if (JSON.parse(result).isHackathon && ifIsHackathon) {
ifIsHackathon(name);
} else if (ifIsNotHackathon) {
ifIsNotHackathon(name);
}
} catch (exception) {}
}
);
mongoose.connect('mongodb://localhost/hackafind');
const flatten = (a, b) => a.concat(b);
Tweet.find({}).then((tweets) => {
const hackathonNames = tweets
.map(tweet => tweet.text) // extract just the text of the tweet
.map(text => nlp.text(text)) // analyze the text
.map(analysis => analysis.sentences)
.reduce(flatten, [])
.map(sentences => sentences.nouns())
.reduce(flatten, [])
.map(noun => noun.normal)
.forEach(name => isHackathon(name, console.log));
const popularity = (name) => hackathonNames
.reduce((count, hackathon) => hackathon === name ? count + 1 : count, 0);
});
<file_sep>/algorithm/models/Tweet.js
const mongoose = require("mongoose");
const TweetSchema = new mongoose.Schema({
username: String,
userDescription: String,
userURL: String,
text: { type: String, index: true }
});
module.exports = mongoose.model("tweet", TweetSchema);
<file_sep>/algorithm/src/server.js
const mongoose = require("mongoose");
const Hackathon = require("../models/Hackathon");
const Tweet = require("../models/Tweet");
mongoose.connect('mongodb://localhost/hackafind');
Hackathon.find({}).then(hackathons => {
const sortedByPopularity = hackathons.sort((a, b) => b.popularity - a.popularity);
console.log(sortedByPopularity);
});
| f041cd61ce323651e2d0e90e6e0b55c64d2028eb | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | DylanKojiCheslin/hackCooper | 1d60c4b3de685e0d47e259235de3f9f79ef0c315 | 8de353784781bec1fd9989fc2ed66874ce3a01ff |
refs/heads/master | <file_sep>
#!/usr/bin/env python
# coding: utf-8
import imageio
import imageio.core.util
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import random
import re
import sklearn
import time
import keras
keras.__version__
from keras import layers
from keras import models
from keras import optimizers
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dropout
#################################################### Data currently in Excel files.
#################################################### Create directories for new .PNG images
####################################################
def mkNewDirs(val_dir, train_dir, SubdirsFrom):
os.makedirs(val_dir, exist_ok=True)
os.makedirs(train_dir, exist_ok=True)
list_classes = os.listdir(SubdirsFrom)
for class_name in list_classes:
os.makedirs("{}/{}".format(val_dir, class_name), exist_ok=True)
os.makedirs("{}/{}".format(train_dir, class_name), exist_ok=True)
return list_classes
list_classes = mkNewDirs("validation_dir", "train_dir", "ExcelData")
list_classes = mkNewDirs("validation_PerPerson_dir", "train_PerPerson_dir", "ExcelData")
####################################################
#################################################### Normalise the RSSI values
####################################################
### Upload one example excel file into Pandas
current_file = pd.read_csv("Ex 1.1_0EC3_151500.csv")
### Function: fix the coordinates.
### round the left x-value Coordinate.
### add 9 to the y-value Coordinate, then round the y-value.
def round_coordinates(current_file):
current_file['x_round'] = current_file['x'].round() - 1
current_file['y_round'] = current_file['y'] + 8
current_file['y_round'] = current_file['y_round'].round()
return current_file
def normalise_rssi(current_file):
### create new column -- "rssi_normalised"
current_file['rssi_normalised'] = "NaN"
### specify min and max "avg_rssi" values --- note: need the () at the end to ensure it is a scalar (or will give Series)
temp_min = current_file['avg_rssi'].min()
temp_max = current_file['avg_rssi'].max()
### assert values are within sensible range.
assert temp_min > -200
assert temp_max < 0
######### GET RID OF EXTREME RSSI VALUES #########
### replace "avg_rssi" as Zero, if it's under -100
current_file.loc[current_file['avg_rssi'] < -100, 'avg_rssi'] = 0
### replace "rssi_normalised" as Zero, if avg_rssi is under -100
# current_file['rssi_normalised'].where(current_file["avg_rssi"] > 100, 0)
current_file.loc[current_file['avg_rssi'] < -100, 'rssi_normalised'] = 0
######### NORMALISATION OF RSSI #########
### replace "rssi_normalised" as Zero, if "avg_rssi" equals the minimum "avg_rssi"
current_file.loc[current_file['avg_rssi'] == temp_min, 'rssi_normalised'] = 0
### normalise "rssi_normalised", if "avg_rssi" exceeds the minimum rssi
current_file.loc[(current_file['avg_rssi'] > temp_min) & (current_file['avg_rssi'] < 0), 'rssi_normalised'] = (current_file['avg_rssi'] - temp_min) / (temp_max - temp_min)
return current_file
round_coordinates(current_file)
normalise_rssi(current_file)
print(current_file)
####################################################
#################################################### Build func to convert to .PNG image.
####################################################
#### Cancel the warning for loss of precision for PNG image saving.
def silence_imageio_warning(*args, **kwargs):
pass
imageio.core.util._precision_warn = silence_imageio_warning
class_counter = 0
file_counter = 100
dir1 = "train_dir"
def convert_to_png(current_file, split_method, current_file_name):
print("current_file_name: {}".format(current_file_name))
### create empty matrix - 34x15
png_matrix = np.zeros([34,15])
png_matrix
########### Insert the rssi_normalised values into png_matrix ###########
# Works basically like this: png_matrix[x,y] = rssi_normalised
for counter in range(20):
png_matrix[int(current_file.at[counter,'y_round']), int(current_file.at[counter,'x_round'])] = current_file.at[counter,'rssi_normalised']
#.astype(np.uint8)
a_num = np.random.rand()
png_matrix
png_matrix.ndim
png_matrix.shape
if split_method == "per_file":
if a_num < 0.7:
dir1 = "train_dir"
if a_num >= 0.7 :
dir1 = "validation_dir"
if split_method == "per_name":
train = 0
for ID_training_persons in train_seven:
if ID_training_persons in current_file_name:
train = 1
if train == 0:
dir1 = "validation_PerPerson_dir"
if train == 1:
dir1 = "train_PerPerson_dir"
imageio.imwrite('{}/{}/npimage{}.png'.format(dir1, list_classes[class_counter], file_counter), png_matrix)
# test run:
# convert_to_png(current_file)
####################################################
#################################################### Cycle through all CSVs, and apply func to save as PNG files
####################################################
##### different person IDs in each class -- so better to automate instead of hard coding each class separately.
def train_test_split_by_person(list_files):
list_of_ten_person_ids = []
for x in list_files:
m = re.search('_(.+?)_', x)
list_of_ten_person_ids.append(m.group(1))
list_of_ten_person_ids = set(list_of_ten_person_ids)
print("list_of_ten_person_ids: {}".format(list_of_ten_person_ids))
train_seven = random.sample(list_of_ten_person_ids, 7)
val_three = [x for x in list_of_ten_person_ids if x not in train_seven]
print("train_seven: {}".format(train_seven))
print("val_three: {}".format(val_three))
return train_seven, val_three
####################################################
#################################################### Cycle through all CSVs, and apply func to save as PNG files
####################################################
"""
### counter for the classes (directories)
class_counter = 0
very_start_time = time.time()
### iterate over classes (directories).
while class_counter < len(list_classes):
start_time = time.time()
### list all the files associated with a particular class.
list_files = os.listdir("ExcelData/{}".format(list_classes[class_counter]))
### specify the 3 people for validation // and 3 for training:
train_seven, val_three = train_test_split_by_person(list_files)
### create counter for files in a class.
file_counter = 0
### iterate over files.
while file_counter < len(list_files):
### read one file as "current_file"
current_file = pd.read_csv("ExcelData/{}/{}".format(list_classes[class_counter], list_files[file_counter] ))
current_file_name = list_files[file_counter]
round_coordinates(current_file)
normalise_rssi(current_file)
convert_to_png(current_file, "per_file", current_file_name)
convert_to_png(current_file, "per_name", current_file_name)
file_counter += 1
class_counter += 1
print("Class: {}, Number of files converted to PNG: {}".format(class_counter, file_counter))
end_time = time.time()
print("total time taken to create PNGs this class: ", end_time - start_time)
print("")
very_end_time = time.time()
print("total time taken to convert all classes to PNG: ", very_end_time - very_start_time)
"""
####################################################
#################################################### Prepare image files for Keras - ImageDataGenerator - Chollet book approach.
####################################################
# No need to rescale images by 1./255 --- already rescaled in RSSI section.
### per file train-test split (i.e. random number generator for each file - if <0.7 then Training data)
train_datagen = ImageDataGenerator()
validation_datagen = ImageDataGenerator()
### per person train-test split: (i.e. randomly select 7 of 10 people for training data in each class)
train_PP_datagen = ImageDataGenerator()
validation_PP_datagen = ImageDataGenerator()
### golden master -- png images -- train-test directories:
train_GM_datagen = ImageDataGenerator()
validation_GM_datagen = ImageDataGenerator()
### per file train-test split
train_generator = train_datagen.flow_from_directory(
# This is the target directory
"train_dir",
# All images will be resized to 34x15
target_size=(34,15),
batch_size=44,
# > 2 labels. (i.e. loss function is categorical_crossentropy)
class_mode='categorical',
color_mode= 'grayscale')
validation_generator = validation_datagen.flow_from_directory(
"validation_dir",
target_size=(34,15),
batch_size=44,
class_mode='categorical',
color_mode= 'grayscale')
### per person train-test split
train_PP_generator = train_PP_datagen.flow_from_directory(
# This is the target directory
"train_PerPerson_dir",
# All images will be resized to 34x15
target_size=(34,15),
batch_size=44,
# > 2 labels. (i.e. loss function is categorical_crossentropy)
class_mode='categorical',
color_mode= 'grayscale')
validation_PP_generator = validation_PP_datagen.flow_from_directory(
"validation_PerPerson_dir",
target_size=(34,15),
batch_size=44,
class_mode='categorical',
color_mode= 'grayscale')
### GOLDEN MASTER train-test split
train_GM_generator = train_GM_datagen.flow_from_directory(
# This is the target directory
"GOLDEN_MASTER png data/pixeldata2/train",
# All images will be resized to 34x15
target_size=(34,15),
batch_size=44,
# > 2 labels. (i.e. loss function is categorical_crossentropy)
class_mode='categorical',
color_mode= 'grayscale')
validation_GM_generator = validation_GM_datagen.flow_from_directory(
"GOLDEN_MASTER png data/pixeldata2/test",
target_size=(34,15),
batch_size=44,
class_mode='categorical',
color_mode= 'grayscale')
####################################################
#################################################### Build model_1 architecture
####################################################
model_1 = models.Sequential()
model_1.add(layers.Conv2D(32, (7, 7), activation='relu', input_shape=(34, 15, 1)))
model_1.add(layers.MaxPooling2D((2, 2)))
model_1.add(Dropout(0.3))
model_1.add(layers.Conv2D(32, (3, 3), activation='relu'))
model_1.add(layers.MaxPooling2D((2, 2)))
model_1.add(Dropout(0.3))
model_1.add(layers.Flatten())
model_1.add(layers.Dense(128, activation='relu'))
model_1.add(Dropout(0.3))
model_1.add(layers.Dense(21, activation='softmax'))
model_1.summary()
####################################################
#################################################### Build model_2 architecture
#################################################### change #1: 7x7 to (5x5 and 3x3)
model_2 = models.Sequential()
model_2.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=(34, 15, 1)))
model_2.add(layers.Conv2D(32, (3, 3), activation='relu'))
model_2.add(layers.MaxPooling2D((2, 2)))
model_2.add(Dropout(0.3))
model_2.add(layers.Conv2D(32, (3, 3), activation='relu'))
model_2.add(layers.MaxPooling2D((2, 2)))
model_2.add(Dropout(0.3))
model_2.add(layers.Flatten())
model_2.add(layers.Dense(128, activation='relu'))
model_2.add(Dropout(0.3))
model_2.add(layers.Dense(21, activation='softmax'))
model_2.summary()
####################################################
#################################################### Build model_3 architecture
#################################################### change #2: dense layer to 64 nodes.
model_3 = models.Sequential()
model_3.add(layers.Conv2D(32, (5, 5), activation='relu', input_shape=(34, 15, 1)))
model_3.add(layers.Conv2D(32, (3, 3), activation='relu'))
model_3.add(layers.MaxPooling2D((2, 2)))
model_3.add(Dropout(0.3))
model_3.add(layers.Conv2D(32, (3, 3), activation='relu'))
model_3.add(layers.MaxPooling2D((2, 2)))
model_3.add(Dropout(0.3))
model_3.add(layers.Flatten())
model_3.add(layers.Dense(64, activation='relu'))
model_3.add(Dropout(0.3))
model_3.add(layers.Dense(21, activation='softmax'))
model_3.summary()
####################################################
#################################################### Compile and run model
####################################################
model_1.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# fit method using generator.
"""
history_perFile = model_1.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=100,
validation_data=validation_generator,
validation_steps=50)
model_1.save('cnn_perFile.h5')
history_perPerson = model_1.fit_generator(
train_PP_generator,
steps_per_epoch=100,
epochs=100,
validation_data=validation_PP_generator,
validation_steps=50)
model_1.save('cnn_perPerson.h5')
"""
history_goldenMaster = model_1.fit_generator(
train_GM_generator,
steps_per_epoch=100,
epochs=100,
validation_data=validation_GM_generator,
validation_steps=50)
model_1.save('cnn_goldenMaster.h5')
####################################################
####################################################
####################################################
"""
# loading model saved locally in test_model_1.h5
model_filepath = 'cnn_image.h5'
prev_model = keras.models.load_model(model_filepath)
# making the prediction
prediction = prev_model_1.predict(train_generator)
# logging each on a separate line
for single_prediction in prediction:
print(single_prediction)
"""
####################################################
#################################################### plot loss and accuracy over training and validation data during training
####################################################
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
plt.savefig(loss_accuracy_curve)
"""
USER IDENTIFIER:
_X_
TIME:
_NNNNNN (6 DIGITS)
XXX change the number for "steps_per_epoch": ie this depends on the number of samples in training / test data.
even though it will just be an approximatino, because the number can fluctuate (ie. using >0.7) --- fine to approximate it.
can later come up with a better method to split -- ie that gives consistently same number in train/test.
XXX - add another densely connected network on top -- i.e. for time series analysis.
To take advantage of the temporal information of each tag, a separate artificial neural network (ANN) was also designed, and can be seen in Fig 4. This artificial network required thirty consecutive seconds of data from a particular tag in order to make a prediction. First, the trained CNN above would classify each individual image to yield a probability vector. The probability vectors for all thirty seconds would then be combined and used as the input layer for the ANN. This included the current time,t, as well as the twenty-nine previous seconds (t−1,t−2,...,t−29). The ANN was designed with a total of three layers. The first two layers each include 125 neural nodes activated using ReLU. The final layer is a softmax layer yielding the final probability vector, the maximum of which is the final classification.
Hyperparameters:
rmsprop
vanilla backprop
size of network
dropout settings
"""
<file_sep># dsp
Signal processing
A quick Python 3 review of some signal processing algorithms.
implemented in Numpy
note: still to add CNN / LSTM for sensor fusion <br>
particle filter
| 295dce9be18da656615ddb7fdef3046810129c25 | [
"Markdown",
"Python"
] | 2 | Python | padhr2810/dsp | 893f50b13ea5e5ce08ec72222e8deea518bba703 | 793b6e5498588c8fe95d5fbe3cdde97c6304c334 |
refs/heads/master | <file_sep>#!/bin/bash
set -xeou pipefail
mkdir -p ~/.minikube/files/audit
curl -fsSL https://raw.githubusercontent.com/tamalsaha/tasty-kube/master/minikube/1.9/auditing/audit-policy.yaml > ~/.minikube/files/audit/audit-policy.yaml
minikube delete || true
minikube start \
--kubernetes-version=v1.9.0 \
--bootstrapper=kubeadm --extra-config=apiserver.admission-control="NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ValidatingAdmissionWebhook,ResourceQuota,DefaultTolerationSeconds,MutatingAdmissionWebhook" \
--mount --mount-string="$HOME/.minikube/files:/.minikube/files" \
--feature-gates=AdvancedAuditing=true
<file_sep>#!/bin/bash
set -xeou pipefail
minikube delete || true
# https://github.com/kubernetes/kubeadm/issues/629
minikube start \
--kubernetes-version=v1.9.0 \
--bootstrapper=kubeadm \
--extra-config=apiserver.admission-control="NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,ValidatingAdmissionWebhook,ResourceQuota,DefaultTolerationSeconds,MutatingAdmissionWebhook"
| 711f0469e822810dfd49e7af728989e24ca75c82 | [
"Shell"
] | 2 | Shell | aerokite/tasty-kube | 334e1905344bd687effcf53ac50ea41432d356ce | 529903a35ef05491c007abd2296c72287ebd710c |
refs/heads/master | <repo_name>cupOJoseph/arduino-sensor-automations<file_sep>/sensoroutline-Joseph/combined-sensor/combined-sensor.ino
//define other files to load.
//depending on file location you may need to use "<dht.h>" instead of ""dht.h"" Use ""dht.h"" for local files, an other for files in default library location.
#include "dht.h"
//Global scope variables.
#define TemperatureAndHumidity_pin 7 // set pin for temp and humidity. this (and all pins) can be changed here.
//define global scope variables here
dht DHT; //temp and humidity global object - DO NOT RENAME THIS VARIABLE
//Oxygen Air Sensor variables
const float VRefer = 3.3;// voltage of adc reference
const int OxygenSensorPin = A5;
// ====================================================
// | Standard Functions |
// | |
// ====================================================
void setup(){
Serial.begin(9600); //begin the serial to print to.
Serial.println("Starting your farm.");
// put your setup code here, to run once when the program is sent:
//
//
}
void loop() {
// put your main code here, to run repeatedly:
String status_string = ""; //a string to build a status with and print out at the end.
//example using get temperature function
double temp = getTemperature();
status_string += "temp = ";
status_string += temp;
//example using get humidity function
double humi = getHumidity();
status_string += "; humidity = ";
status_string += humi;
//example using get oxygen
Serial.println(status_string);
delay(1000);
}
// =============================================================
// | HELPER FUNCTIONS |
// | |
// =============================================================
//This area below for Joseph's custom functions.
/* This function will record the temperature using the
* sensor assigned to pin TemperatureAndHumidity_pin.
* Then it will return the current temp as a double in celcius.
* Sometimes this will return -999. Please check this.
*/
double getTemperature(){
int check = DHT.read11(TemperatureAndHumidity_pin);
return DHT.temperature;
}
/* This function will record the Humidity using the
* sensor assigned to pin TemperatureAndHumidity_pin.
* Then it will return the current humidity as a double in celcius.
* Sometimes this will return -999. Please check this.
*/
double getHumidity(){
int check = DHT.read11(TemperatureAndHumidity_pin);
return DHT.humidity;
}
/**get the oxygen level of the air.
* I think this sensor is just for air.
*
*/
float getOxygenInAir(){
float Vout =0;
Vout = readO2VoutAir();
return readConcentrationAir();
}
//================ O2 sensor helper functions ===================/
// THIS SECTION SECTION UN TESTED!
//
float readO2VoutAir()
{
long sum = 0;
for(int i=0; i<32; i++)
{
sum += analogRead(OxygenSensorPin);
}
sum >>= 5;
float MeasuredVout = sum * (VRefer / 1023.0);
return MeasuredVout;
}
float readConcentrationAir()
{
// Vout samples are with reference to 3.3V
float MeasuredVout = readO2VoutAir();
//float Concentration = FmultiMap(MeasuredVout, VoutArray,O2ConArray, 6);
//when its output voltage is 2.0V,
float Concentration = MeasuredVout * 0.21 / 2.0;
float Concentration_Percentage=Concentration*100;
return Concentration_Percentage;
}
// ================================================== ^End O2 helpers =================================== //
<file_sep>/README.md
# arduino-sensor-automations<file_sep>/sensoroutline-Joseph/temperature-example/temperature-example.ino
//define other files to load.
//depending on file location you may need to use "<dht.h>" instead of ""dht.h""
#include "dht.h"
#define DHT11_PIN 7
//define global scope variables here
dht DHT;
void setup(){
Serial.begin(9600);
// put your setup code here, to run once when the program is sent:
Serial.println("start");
}
void loop() {
// put your main code here, to run repeatedly:
int check = DHT.read11(DHT11_PIN);
//temp in C
double temp = DHT.temperature;
double hum = DHT.humidity;
if(temp > -900){
Serial.print("temp = ");
Serial.println(DHT.temperature);
}
delay(1000);
}
<file_sep>/sensoroutline-Joseph/gasOxygen-example/gasOxygen-example.ino
//get gas O2 from sensor
// http://wiki.seeedstudio.com/Grove-Gas_Sensor-O2/
const float VRefer = 3.3;// voltage of adc reference
const int OxygenSensorPin = A5;
void setup() {
Serial.begin(9600);
}
//The O2 sensor writes votage directly, must be converted to a useful number
void loop() {
float x = getOxygenInAir();
delay(500);
}
/**get the oxygen level of the air.
* I think this sensor is just for air.
*
*/
float getOxygenInAir(){
float Vout =0;
Vout = readO2VoutAir();
return readConcentrationAir();
}
//================ O2 sensor helper functions ===================/
// THIS SECTION SECTION UN TESTED!
//
float readO2VoutAir()
{
long sum = 0;
for(int i=0; i<32; i++)
{
sum += analogRead(OxygenSensorPin);
}
sum >>= 5;
float MeasuredVout = sum * (VRefer / 1023.0);
return MeasuredVout;
}
float readConcentrationAir()
{
// Vout samples are with reference to 3.3V
float MeasuredVout = readO2VoutAir();
//float Concentration = FmultiMap(MeasuredVout, VoutArray,O2ConArray, 6);
//when its output voltage is 2.0V,
float Concentration = MeasuredVout * 0.21 / 2.0;
float Concentration_Percentage=Concentration*100;
return Concentration_Percentage;
}
| 75905a85b838e8ffdf4b91d46c6f9d6e0cbc5ecc | [
"Markdown",
"C++"
] | 4 | C++ | cupOJoseph/arduino-sensor-automations | 38ad02afbdbb576fd2f903d5283d55b6e411e16b | bcb680d05fb0927e20e49947cf75e9f01b31a81d |
refs/heads/main | <file_sep>$(function() {
function rollem() {
initArray = []
// get the mod
var phillipaMod = $("#phillipa-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#phillipa-roll").text(roll);
// Add mod to total
var phillipaTotal = parseInt(phillipaMod) + roll;
$("#phillipa-total").text(phillipaTotal);
initArray.unshift({
"name": "Phillipa",
"roll": phillipaTotal
});
// get the mod
var zenaMod = $("#zena-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#zena-roll").text(roll);
// Add mod to total
var zenaTotal = parseInt(zenaMod) + roll;
$("#zena-total").text(zenaTotal);
initArray.unshift({
"name": "Zena",
"roll": zenaTotal
});
// get the mod
var digbyMod = $("#digby-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#digby-roll").text(roll);
// Add mod to total
var digbyTotal = parseInt(digbyMod) + roll;
$("#digby-total").text(digbyTotal);
initArray.unshift({
"name": "Digby",
"roll": digbyTotal
});
// get the mod
var wearyMod = $("#weary-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#weary-roll").text(roll);
// Add mod to total
var wearyTotal = parseInt(wearyMod) + roll;
$("#weary-total").text(wearyTotal);
initArray.unshift({
"name": "Weary",
"roll": wearyTotal
});
// get the mod
var razMod = $("#raz-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#raz-roll").text(roll);
// Add mod to total
var razTotal = parseInt(razMod) + roll;
$("#raz-total").text(razTotal);
initArray.unshift({
"name": "Raz",
"roll": razTotal
});
// get the mod
var linneaMod = $("#linnea-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#linnea-roll").text(roll);
// Add mod to total
var linneaTotal = parseInt(linneaMod) + roll;
$("#linnea-total").text(linneaTotal);
initArray.unshift({
"name": "Linnea",
"roll": linneaTotal
});
// get the mod
var monsterMod = $("#monster-mod").val();
// make the roll
var roll = Math.round(Math.random() * 20 + 1);
// Write the roll to the field
$("#monster-roll").text(roll);
// Add mod to total
var monsterTotal = parseInt(monsterMod) + roll;
$("#monster-total").text(monsterTotal);
initArray.unshift({
"name": "Monster",
"roll": monsterTotal
});
// Sort the array
initArray.sort((a, b) => {
return b.roll - a.roll;
});
}
function appendToList() {
for (var i = 0; i < initArray.length; i++) {
switch (initArray[i].name) {
case "Monster":
$("#randomized-list").append("<li class='list-group-item bg-mistyrose'><i class='fad fa-fw text-danger fa-dragon mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Linnea":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-shield-cross mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Raz":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-shield-cross mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Digby":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-hood-cloak mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Phillipa":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-helmet-battle mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Weary":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-hat-wizard mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
case "Zena":
$("#randomized-list").append("<li class='list-group-item'><i class='fad fa-fw text-primary fa-mandolin mr-3'></i>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
break;
}
// if (initArray[i].name == "Monster") {
//
// $("#randomized-list").append("<li class='list-group-item bg-mistyrose'>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
//
// } else {
//
// $("#randomized-list").append("<li class='list-group-item'>" + initArray[i].name + "<span class='badge'>" + initArray[i].roll + "</span></li>");
// }
}
}
$("#clear").on("click", function() {
location.reload();
});
$("#roll-em").on("click", function() {
$("#randomized-list").empty();
rollem();
appendToList();
});
});
// document.ready
| 6cc34c970d88f7b4c41919984a2d5a3184853cf9 | [
"JavaScript"
] | 1 | JavaScript | randal-sean-harrison/dnd | f9f735341a19ad5a152b853a4e29e9545f1a37c2 | 780a266923df837ddfb57fa087ac75b066a98e39 |
refs/heads/master | <repo_name>zhangyiwen114/chartOptions<file_sep>/chartOptions.js
/**
* 饼图:消费人群年龄分布
* @param {Array} data 数据
* @return {Object} 图表配置项
*/
const ring = (data) => {
const $xAxis = [];
data.forEach((item) => {
$xAxis.push(item.name);
});
return {
legend: {
data: $xAxis,
left: 0,
top: 140,
bottom: 0,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
tooltip: {
trigger: 'item',
formatter: '{b}: {d}%'
},
calculable: true,
color: ['#2dabdf', '#4dc5fc', '#4fdffd', '#51f7fe', '#51fd83',
'#61ec47', '#dfdb41', '#fec02f', '#fd9e2a', '#fd7625',
'#fc4320', '#d84ffc', '#c42ddf'
],
series: [{
type: 'pie',
center: ['50%', '25%'],
clockWise: false,
radius: [30, 60],
roseType: 'radius',
legendHoverLink: false,
hoverAnimation: false,
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
lableLine: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data
}]
};
};
/**
* 饼图:消费人群年龄分布
* @param {Array} data 数据
* @return {Object} 图表配置项
*/
const contrastRing = (name1, name2, data1, data2) => {
const $xAxis = [];
data1.forEach((item) => {
$xAxis.push(item.name);
});
if ($xAxis.length === 0) {
data2.forEach((item) => {
$xAxis.push(item.name);
});
}
return {
title: [{
text: name1,
top: 110,
left: '12%',
textStyle: {
color: 'rgba(255, 255, 255, 0.6)',
fontSize: '12'
}
},
{
text: name2,
top: 110,
right: '15%',
textStyle: {
color: 'rgba(255, 255, 255, 0.6)',
fontSize: '12'
}
}],
legend: {
x: 'left',
y: 'top',
left: -5,
top: 150,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10,
data: $xAxis
},
tooltip: {
trigger: 'item',
formatter: '{b}: {d}%'
},
calculable: true,
color: ['#2dabdf', '#4dc5fc', '#4fdffd', '#51f7fe', '#51fd83',
'#61ec47', '#dfdb41', '#fec02f', '#fd9e2a', '#fd7625',
'#fc4320', '#d84ffc', '#c42ddf'
],
series: [{
type: 'pie',
center: [65, 55],
clockWise: false,
radius: [20, 45],
roseType: 'radius',
legendHoverLink: false,
hoverAnimation: false,
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
lableLine: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data1
},
{
type: 'pie',
center: [190, 55],
clockWise: false,
radius: [20, 45],
roseType: 'radius',
legendHoverLink: false,
hoverAnimation: false,
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
lableLine: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data2
}
]
};
};
/**
* 柱状图图:学历构成
* @param {Array} data 数据
* @return {Object} 图表配置项
*/
const barGrade = (data) => {
const $xAxis = [];
const $seriesDtat = [];
data.forEach((item) => {
$seriesDtat.push(Math.round(item.value * 100) / 100);
$xAxis.push(item.name);
});
return {
color: ['#2dabdf'],
legend: {
data: ['学历构成'],
left: 0,
show: false,
textStyle: {
color: '#bbb'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
grid: {
left: '12%',
right: '13%',
bottom: '20%',
top: '20',
containLabel: false
},
xAxis: [{
type: 'category',
boundaryGap: false,
data: $xAxis,
axisLine: {
lineStyle: {
color: '#bbb'
},
show: false
},
axisTick: {
show: false
},
axisLabel: {
interval: 0
}
}],
yAxis: [{
type: 'value',
show: false
}],
series: [{
type: 'bar',
data: $seriesDtat,
barMaxWidth: 20,
label: {
normal: {
show: true,
position: 'top',
formatter: '{c}%',
textStyle: {
color: '#999',
fontSize: 12
}
}
}
}]
};
};
/**
* 比较柱状图图:学历构成
* @param {Array} data 数据
* @return {Object} 图表配置项
*/
const contrastBarGrade = (name1, name2, data1, data2) => {
const $xAxis = [];
let $seriesDtat1 = [];
let $seriesDtat2 = [];
data1.forEach((item) => {
$seriesDtat1.push(Math.round(item.value * 100) / 100);
$xAxis.push(item.name);
});
data2.forEach((item) => {
$seriesDtat2.push(Math.round(item.value * 100) / 100);
});
if (data1.length === 0) {
data2.forEach((item) => {
$xAxis.push(item.name);
});
$seriesDtat1 = ['-', '-', '-', '-'];
}
if (data2.length === 0) {
$seriesDtat2 = ['-', '-', '-', '-'];
}
return {
color: ['#3891b3'],
tooltip: {
trigger: 'axis',
formatter(param) {
if (param[0] && param[1]) {
return ` ${param[0].seriesName} : ${param[0].value}% <br/>
${param[1].seriesName} : ${param[1].value}%`;
}
return ` ${param[0].seriesName} : ${param[0].value}% `;
}
},
legend: {
// orient: 'vertical',
data: [name1, name2],
top: 0,
left: -5,
textStyle: {
color: '#bbb'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
grid: {
left: '11.5%',
right: '12%',
bottom: '20%',
top: '30%',
containLabel: false
},
xAxis: [{
type: 'category',
boundaryGap: false,
data: $xAxis,
axisLine: {
lineStyle: {
color: '#bbb'
},
show: false
},
axisTick: {
show: false
}
}],
yAxis: [{
type: 'value',
show: false
}],
series: [{
barMaxWidth: 16, // 最大宽度
barGap: 0,
name: name1,
type: 'bar',
itemStyle: {
normal: {
color: '#2dabdf',
label: {
position: 'top',
textStyle: {
fontSize: 18
}
}
}
},
data: $seriesDtat1
}, {
barMaxWidth: 16,
name: name2,
type: 'bar',
itemStyle: {
normal: {
color: '#2ddf81',
label: {
position: 'top',
textStyle: {
fontSize: 18
}
}
}
},
data: $seriesDtat2
}]
};
};
/**
* 环形图: 车辆拥有情况
* @param {Number} data 数据 dealNumPercent 字段对应的值
* @return {Object} 图表配置项
*/
const pieRegion = (data) => {
const $xAxis = [];
const $seriesDtat = [];
data.forEach((item) => {
$seriesDtat.push(Math.round(item.value * 100) / 100);
$xAxis.push(item.name);
});
return {
color: ['#2dabdf', 'rgba(45, 120, 152, 0.7)', 'rgba(45, 69, 80, 0.7)'],
legend: {
right: 13,
data: $xAxis,
top: 0,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
series: [{
hoverAnimation: false,
type: 'pie',
radius: ['36', '51'], // 内径 外径
center: ['50%', '60%'], // 图表位置
label: {
normal: {
formatter: '{d}%',
textStyle: {
color: '#999',
fontSize: 12
}
}
},
labelLine: {
normal: {
show: true
}
},
data
}]
};
};
/**
* 比较环形图: 车辆拥有情况
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const contrastPieRegion = (data1, data2) => {
const $xAxis = [];
data1.forEach((item) => {
$xAxis.push(item.name);
});
if ($xAxis.length === 0) {
data2.forEach((item) => {
$xAxis.push(item.name);
});
}
return ({
color: ['#2dabdf', 'rgba(45, 120, 152, 0.7)', 'rgba(45, 69, 80, 0.7)'],
legend: {
data: $xAxis,
left: -5,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
tooltip: {
trigger: 'item',
formatter: '{b}: {d}%'
},
series: [{
hoverAnimation: false,
type: 'pie',
radius: ['30', '45'],
center: [60, 93],
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data1
},
{
hoverAnimation: false,
type: 'pie',
radius: ['30', '45'],
center: [190, 93], // 图表位置
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data2
}
]
});
};
/**
* 环形图: 房产拥有情况
* @param {Number} data 数据 dealNumPercent 字段对应的值
* @return {Object} 图表配置项
*/
const pieHouse = (data) => {
const $xAxis = [];
const $seriesDtat = [];
data.forEach((item) => {
$seriesDtat.push(Math.round(item.value * 100) / 100);
$xAxis.push(item.name);
});
return {
color: ['#2ddf81', 'rgba(22, 154, 106, .8)', 'rgba(22, 154, 106, 0.3)'],
legend: {
data: $xAxis,
top: 0,
right: 13,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
series: [{
hoverAnimation: false,
type: 'pie',
radius: ['36', '51'], // 内径 外径
center: ['50%', '60%'], // 图表位置
label: {
normal: {
formatter: '{d}%',
textStyle: {
color: '#999',
fontSize: 12
}
}
},
labelLine: {
normal: {
show: true
}
},
data
}]
};
};
/**
* 比较环形图: 房产拥有情况
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const contrastPieHouse = (data1, data2) => {
const $xAxis = [];
data1.forEach((item) => {
$xAxis.push(item.name);
});
if ($xAxis.length === 0) {
data2.forEach((item) => {
$xAxis.push(item.name);
});
}
return ({
color: ['#2ddf81', 'rgba(22, 154, 106, .8)', 'rgba(22, 154, 106, 0.3)'],
legend: {
x: 'left',
y: 'top',
data: $xAxis,
left: -5,
textStyle: {
color: 'rgba(255, 255, 255, 0.5)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
tooltip: {
trigger: 'item',
formatter: '{b}: {d}%'
},
series: [{
hoverAnimation: false,
type: 'pie',
radius: ['30', '45'],
center: [60, 93],
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data1
},
{
hoverAnimation: false,
type: 'pie',
radius: ['30', '45'],
center: [190, 93], // 图表位置
label: {
normal: {
show: false
},
emphasis: {
show: false
}
},
data: data2
}
]
});
};
/**
* 条图: 性别
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const sex = (data) => {
const $xAxis = [];
data.forEach((item) => {
$xAxis.push(item.name);
});
return ({
color: ['#c62621', '#0fac5e'],
grid: {
top: 68,
left: '0%',
right: '0%'
},
legend: {
selectedMode: false,
x: 'right',
y: 'top',
right: 'right',
data: $xAxis,
textStyle: {
color: 'rgba(255, 255, 255, 1)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
xAxis: [{
type: 'value',
show: false
}],
yAxis: {
type: 'category',
show: false,
data: $xAxis
},
series: [{
type: 'bar',
name: data[0].name,
data: [{
name: data[0].name,
value: data[0].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}, {
type: 'bar',
name: data[1].name,
data: [{
name: data[1].name,
value: data[1].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}]
});
};
/**
* 条图: 性别
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const sexcontrast = (name, data) => {
const $xAxis = [];
data.forEach((item) => {
$xAxis.push(item.name);
});
return ({
color: ['#c62621', '#0fac5e'],
title: [
{
text: name,
bottom: 5,
left: 0,
textStyle: {
color: 'rgba(255, 255, 255, 0.6)',
fontSize: '12'
}
}
],
grid: {
top: '45%',
left: '0%',
right: '0'
},
xAxis: [{
type: 'value',
show: false
}],
yAxis: {
type: 'category',
show: false,
data: $xAxis
},
series: [{
type: 'bar',
name: data[0].name,
data: [{
name: data[0].name,
value: data[0].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}, {
type: 'bar',
name: data[1].name,
data: [{
name: data[1].name,
value: data[1].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}]
});
};
/**
* 条图: family
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const family = (data) => {
const $xAxis = [];
data.forEach((item) => {
$xAxis.push(item.name);
});
return ({
color: ['#2dabdf', '#2ddf81', '#ffc107'],
grid: {
top: 30,
left: '0%',
right: '0%'
},
legend: {
selectedMode: false,
x: 'left',
y: 'bottom',
data: $xAxis,
textStyle: {
color: 'rgba(255, 255, 255, 1)'
},
icon: 'circle',
itemWidth: 20,
itemHeight: 10
},
xAxis: [{
type: 'value',
show: false
}],
yAxis: {
type: 'category',
show: false,
data: $xAxis
},
series: [{
type: 'bar',
name: data[0].name,
data: [{
name: data[0].name,
value: data[0].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}, {
type: 'bar',
name: data[1].name,
data: [{
name: data[1].name,
value: data[1].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
},
{
type: 'bar',
name: data[2].name,
data: [{
name: data[2].name,
value: data[2].value
}],
label: {
normal: {
show: true,
position: 'top',
paddingTop: 20,
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}]
});
};
/**
* 条图: familycontrast
* @param {Array} data1 data1
* @param {Array} data2 data2
* @return {Object} 图表配置项
*/
const familycontrast = (name, data) => {
const $xAxis = [];
data.forEach((item) => {
$xAxis.push(item.name);
});
return ({
color: ['#2dabdf', '#2ddf81', '#ffc107'],
title: [
{
text: name,
bottom: 3,
left: 0,
textStyle: {
color: 'rgba(255, 255, 255, 0.6)',
fontSize: '12'
}
}
],
grid: {
top: '45%',
left: '0%',
right: '0'
},
xAxis: [{
type: 'value',
show: false
}],
yAxis: {
type: 'category',
show: false,
data: $xAxis
},
series: [{
type: 'bar',
name: data[0].name,
data: [{
name: data[0].name,
value: data[0].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}, {
type: 'bar',
name: data[1].name,
data: [{
name: data[1].name,
value: data[1].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
},
{
type: 'bar',
name: data[2].name,
data: [{
name: data[2].name,
value: data[2].value
}],
label: {
normal: {
show: true,
position: 'top',
formatter(obj) {
return `${obj.value}%`;
}
}
},
stack: 'income',
barWidth: 15
}]
});
};
/**
* 条图: nodata
* @param {Array} name name
* @return {Object} 图表配置项
*/
const nodata = name =>
({
title: [
{
text: name,
bottom: 3,
left: 0,
textStyle: {
color: 'rgba(255, 255, 255, 0.6)',
fontSize: '12'
}
}
],
grid: {
top: '80%',
left: '0%',
right: '0'
},
color: ['#999'],
xAxis: {
data: [],
type: 'value',
show: false
},
yAxis: {
type: 'category',
show: false
},
series: [{
type: 'bar',
name: '',
data: [100],
stack: 'income',
barWidth: 12,
label: {
normal: {
show: true,
position: 'top',
formatter: '暂无数据'
}
}
}]
});
export default {
ring,
pieRegion,
pieHouse,
barGrade,
contrastRing,
contrastPieHouse,
contrastPieRegion,
contrastBarGrade,
sex,
sexcontrast,
family,
familycontrast,
nodata
};
| 15977b21a8cb921c273cb1d3bcea7fc3f2c0daed | [
"JavaScript"
] | 1 | JavaScript | zhangyiwen114/chartOptions | 81d314a916db08d614061c4bc25053cb7c0f12aa | dac323768044683921d6bb539ccd702e7b727312 |
refs/heads/master | <repo_name>GleefullyChill/snake-client<file_sep>/input.js
const { ctrlC, up, down, right, left, mesOne, mesTwo, mesThr, mesFou, mesFiv, mesSix, mesSev, mesEig, mesNin, mesZer } = require('./constants');
let connection;
const handleUserInput = data => {
switch (data) {
case ctrlC:
process.exit();
break;
case up:
connection.write("Move: up");
break;
case down:
connection.write("Move: down");
break;
case right:
connection.write("Move: right");
break;
case left:
connection.write("Move: left");
break;
}
switch (data) {
case mesOne:
connection.write('Say: Does life mean?');
break;
case mesTwo:
connection.write('Say: Does hope come?');
break;
case mesThr:
connection.write('Say: God has abandoned. 👿');
break;
case mesFou:
connection.write('Say: The right to judge ME?');
break;
case mesFiv:
connection.write('Say: YOU have the attitude problem. 🙄');
break;
case mesSix:
connection.write(`Say: NO ONE CARES 😭`);
break;
case mesSev:
connection.write(`Say: 'But with a whimper'`);
break;
case mesEig:
connection.write('Say: <NAME>!');
break;
case mesNin:
connection.write("Say: Drink water!");
break;
case mesZer:
connection.write("Say: Get up and move!");
break;
}
};
const setupInput = function(conn) {
const stdin = process.stdin;
stdin.setRawMode(true);
stdin.setEncoding("utf8");
stdin.resume();
connection = conn;
stdin.on("data", handleUserInput);
return stdin;
};
module.exports = setupInput;<file_sep>/constants.js
const IP = '192.168.127.12'
const PORT = 50542;
const ctrlC = "\u0003";
const up = "\u0077";
const down = "\u0073";
const right = "\u0064";
const left = "\u0061";
const mesOne = "\u0031";
const mesTwo = "\u0032";
const mesThr = "\u0033";
const mesFou = "\u0034";
const mesFiv = "\u0035";
const mesSix = "\u0036";
const mesSev = "\u0037";
const mesEig = "\u0038";
const mesNin = "\u0039";
const mesZer = "\u0030";
module.exports = {
IP,
PORT,
mesOne,
mesTwo,
mesThr,
mesFou,
mesFiv,
mesSix,
mesSev,
mesEig,
mesNin,
mesZer,
ctrlC,
up,
down,
left,
right
}; | e8bfe0d6a0c5413fcb21cede8e4e57c8bd9d79a1 | [
"JavaScript"
] | 2 | JavaScript | GleefullyChill/snake-client | 23fdb5b982787363b2ce0653f3340ea890924677 | 7d4bfea38de5884f0b3ab1ffa0bb3fea5d995554 |
refs/heads/master | <repo_name>FrankMaYuke/my_practice_basic_C_language<file_sep>/a.py
name = "李金"
print("hello "+name)
| d6b9ca8f1dc6c1d43a342bd6b9ce736558d10413 | [
"Python"
] | 1 | Python | FrankMaYuke/my_practice_basic_C_language | acc51c55e3096c0f1c216e2c05288274d11eb63e | c860900acf6af73723aa411ecb74bec0e44b545a |
refs/heads/master | <file_sep>import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LibraryTest {
Library library;
Book book;
@Before
public void before() {
library = new Library();
book = new Book();
}
@Test
public void libraryStartsEmpty(){
assertEquals(0, library.bookCount());
}
@Test
public void addBookToLibrary(){
library.addBook(book);
assertEquals(1, library.bookCount());
}
// if book count is less than capacity then add book
@Test
public void addBookToLibraryIfCapacity(){
library.addBookIfCapacity(book);
assertEquals(1, library.bookCount());
}
}
| 831109b846e9666ba83dbdb17886f3e4319fea29 | [
"Java"
] | 1 | Java | sarahmurphy86/Java_Multiple_Classes_Homework | d00ad2691c323096974f56e5491e9a8e734856c0 | 8a79505d8012fe50d3f3432e710d80b82d068624 |
refs/heads/master | <repo_name>RFSOU/Curso-Python<file_sep>/exercicios/exercicio_019_random.py
from random import choice # carrega o metodo choice do modulo random
n1 = str (input ('primeiro aluno:'))
n2= str (input('segundo aluno'))
n3= str (input('terceiro aluno'))
n4= str (input('quarto aluno'))
lista = [n1,n2,n3,n4] # cria uma lsita com as variaveis n1,n2,n3,n4
escolhido = choice(lista) #aplica o metodo choice na lista e insere na
# variavel escolhido
print ('O aluno escolhido foi:{}'.format(escolhido))
<file_sep>/exercicios/exercicio_053_palindromo_strings.py
'''crie um programa que leia uma frase qualquer e diga se ela é um palindromo
desconsidenrando os espaços'''
frase = str(input('Escreva uma frase.')).strip().upper()# nesta entrada tiramos os espaços com strip e mudamos tudo para maisculo com upper
palavras = frase.split()#palavras recebe frase splitada
junto = ''.join(palavras)# junto recebe palavras todas juntas sem espaço
#for letra in range (len(junto)-1,-1,-1): '''esse for conta os caracteres na variavel junto,,, letra vai correr todas as letras de junto o atributo -1 quer dizer se tem 20 letras vai contar - uma e -1 por que vai contar até 0 e -1 porque vai ser contagem regressiva essa é uma forma de analisar uma palavra do final para começo utilizando o for'''
inverso = junto[::-1]# atributo de fatiamento ::-1 pega o conteundo davariavel junto do começo ao final e joga do final para o começo na variavel inverso
if inverso == junto: # compara
print('{} e {} são iguais'.format(inverso,junto))
print('É um Palindromo')
else:
print('{} e {} não são iguais'.format(inverso, junto))
print('Não é um Palindromo')
'''if (frase.find('joão paulo'))== 0: #retorna um -1 se a frase não for encontrada
print('ok')
else:
print('errado')'''<file_sep>/exercicios/exercicio_037_conversor_binario.py
'''escreva um programa que leia um numero inteiro qualquer e peça para o usuario escolher qual sera a base de conversão:
-1 para binario
-2 para octal
-3 para hexadecimal
'''
numero = int(input('Escreva um numero inteiro'))
base = str(input('Para qual base você que converter:-Binario-Octal ou Hexadecimal?')).strip()
if base[:35].upper() == 'BINARIO':
print('Ok vamos converter para',base,)
print(bin(numero))
elif base[:35].upper() == 'HEXADECIMAL':
print('Ok vamos converter para',base)
print(hex (numero))
elif base[:35].upper() == 'OCTAL':
print('Ok vamos converter para',base)
print(oct (numero))
else:
print('Você só pode escolher 3 opções Binario Hexadecimal e Octal')<file_sep>/aulas_basico/aula_09_frases.py
#Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender
# são o Fatiamento de String, Análise com len(), count(), find(),
# transformações com replace(), upper(), lower(), capitalize(), title(),
# strip(), junção com join().
# para imprimir um texto inteiro longo basta digitar ''' no começo e no fim da frase.
#fatiamento
# colchete no python é o identificado de uma estrutura de dados chamada
# de lista
frase = ('curso em video python')
'''print(frase[0:5])
print(frase[:5])
print(frase[0:])
print(frase[9::3])
print(frase[15:])
print(len(frase)) #analisa o tamanho da frase'''
#print(frase.count('o')) # conta quantas letras o tem na variavel frase
#print(frase.count('o',0,13))# mostra quantas letras "o" tem entre a posição
#0,13
#print(frase.find('deo'))# indica onde começa "deo" na frase
#print(frase.find('joão'))# respode com -1 quando não encontra a string.
print('video' in frase)
#print(frase.replace('python','android'))# substitui python por android.
#print(frase.upper()) # upper trasforma tudo que é minusculo em maiusculo
#print(frase.lower()) # lower trasforme tudo que é maisculo em minusculo.
#print(frase.capitalize())# capitalize trasfoma só a primeira palavra em
# maiusculo
#print(frase.title()) # coloca todas as palavras da frase com começo em
# maiusculo
#print(frase.strip()) # remove espaços no começo e no fim desneceçario
#print(frase.rstrip())# remove espaços na direita
#print(frase.lstrip())# remove espaços na esquerda
#print(frase.split()) # faz a divisão da frase fazendo com que ela tenha
# indices novos
print(''.join(frase))
<file_sep>/README.md
# Curso-Python
# Curso basico de Python, aulas e execicios.
<file_sep>/exercicios/exercicio_031_if_else.py
#Exercício Python 031: Desenvolva um programa que pergunte a distância de uma
#viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens
#de até 200Km e R$0,45 parta viagens mais longas.
distancia = float(input('\033[7;30;45mDe quantos Km éa distancia da sua viajem\033[m'))
print('***'*20)
print(' \033[7;30;45mVocê esta prestes a começar uma viagem de {} km.\033[m'.format(distancia))
print('***'*20)
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print(' \033[7;30;45mO preço de sua passagem sera de R$ {:.2f}\033[m '.format(preço))
<file_sep>/aulas_basico/aula_07_input.py
nome = input ("Qual é o seu nome?")
print('Prazer em te conhecer {:=^20}!' .format(nome))
# Obs... o : ^> < 20 dentro do {} cria um espaço de 20 caracteres
# onde vai formatar o espaço escrito a variavel nome.
<file_sep>/exercicios/exercicio_020_random.py
import random # carrega o metodo choice do modulo random
n1 = str (input ('primeiro aluno:'))
n2= str (input('segundo aluno'))
n3= str (input('terceiro aluno'))
n4= str (input('quarto aluno'))
lista = [n1,n2,n3,n4] # cria uma lsita com as variaveis n1,n2,n3,n4
random.shuffle(lista) # mistura o coteudo da lista.
print ('A ordem de apresentação sera')
print (lista)
<file_sep>/exercicios/exercicio_06_formatação.py
n1 = int (input ('Entre com um numero.'))
print ('O dobro do numero digitado é {}'.format (n1*2), end=' ' )
print ('o triplo do numero digitado é {}'.format (n1*3), end=' ' )
print ('E a raiz quadrada do numero digitado é {:.3f}'.format (n1**(1/2)), end=' ' )
# end --- faz com que o print fique tudo junto sem quebra de linha :.3f --- faz com o de uma divisão seja somente
# com 3 casa depois da virgula e seja uma variavel flutuante no resultado <file_sep>/exercicios/exercicio_026_string.py
'''Faça um programa que leia uma frase pelo teclado e mostre quantas vezes
aparece a letra "A", em que posição ela aparece a
primeira vez e em que posição ela aparece a última vez.'''
frase = str (input('escreva uma frase')).upper() .strip() #neste caso foi
# possivel usar o upper na 'str e o strip para eliminar espaços'
print('\033[0;31;0mA letra A aparece {} vezes na frase.'.format(frase.count ('A')))
print('A primeira letra A aparece na posição {}'.format(frase.find('A')+1)) # find procura da
# esquerda para direta
print ('A ultima letra A apareceu na posição {}'.format(frase.rfind('A')+1)) #rfind procura
#da direita
#para esquerda
<file_sep>/exercicios/exercicio_021_player.py
#import pygame # não esta executando desta forma
#pygame.init()
#pygame.mixer.music.load('desafio021.mp3')
#pygame.mixer.music.play()
#pygame.event.wait()
# codigo funcionando
#from pygame import mixer # importa o mixer do pygame
#mixer.init() # inicia o mixer do pygame
#mixer.music.load('musica.mp3') #carrega musica
#mixer.music.play() # toca musica
#input('Agora você escuta?')
from os import startfile # executa a musica no player padrão
startfile('musica.mp3')
<file_sep>/exercicios/exercicio_051_progressão_aritimetica.py
'''Desenvolva uma programa que leia o primeiro termo e a razão de uma PA.
No final, mostre os 10 primeiros termos dessa progressão.'''
a1=0
a1 = int(input('Qual o primeiro termo da PA'))
r = int(input('Qual é a razão da PA'))
print(' PA DE RAZÃO {} = {}'.format(r,a1))
for c in range(0,9):
if c <=11:
a1=a1+r
print((' PA DE RAZÃO {} = {}').format(r,a1))
print('fim')
<file_sep>/aulas_basico/aula_08_bibliotecas.py
import math # importa uma biblioteca no caso a biblioteca math inteira
num =int(input('Digite um numero:'))
raiz = math.sqrt(num) # no caso a biblioteca math.sqrt tira a raiz quadrada do (num)
print('A raiz de {} é igual a {:.2f}'.format(num,raiz))
<file_sep>/exercicios/exercicio_012_preco_do_produto.py
n1 = float (input ('Qual o preço do produto?'))
print ('O preço do produto com 5% de desconto é {}' .format (n1-(n1*5)/100,))
<file_sep>/exercicios/exercicio_043_elif.py
'''desenvolva uma logica que leia o peso e altura de uma pessoa, calcule seu IMC e mostre seu status, de acordo com a tabela abaixo: - Abaixo de 18.5 abaixo do peso
-Entre 18.5 e 25: peso ideal
-25 até 30 sobrepeso
-30 até 40 obesidade
-acima de 40 obesidade morbida'''
peso = float(input('Qual é o seu peso?'))
altura =float(input('Qual é a sua altura?'))
imc = peso/altura
if imc<=18.5:
print('Você esta a baixo do peso.')
elif imc>18.5 and imc < 25:
print('Seu esta peso ideal')
elif imc >25 and imc < 30:
print('Você esta com sobre peso.')
elif imc > 30 and imc < 40:
print(' Você esta obeso.')
elif imc > 40:
print('Você esta com obsidade morbida.')
else:
print('Obrigado')<file_sep>/exercicios/exercicio_058_while.py
''' Melhore o jogo do Desafio 028 onde o computador vai pensar em um numero entre 0 e 10.
Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.'''
from random import randint
from time import sleep
jogador = 1
computador = 0
palpite = 0
while computador != jogador:
computador = randint(0, 10) # faz o computador pensar um numero de 0 a 10 e joga na variavel computador.
print('\033[0;31;0m-=-\033[m' * 20) # cria uma linha de 20 caracteres
print('\033[0;31;0m Eu Pensei em um numero entre 0 e 10. Tente Adivinhar...\033[m')
print('\033[0;31;0m-=-\033[m' * 20) # cria uma linha de 20 caracteres
jogador = int(input('\033[0;31;0m Em que numero eu pensei?\033[m')) # Jogador tenta adivinhar
print('\033[0;30;41m PROCESSANDO...\033[m')
sleep(3) # do metodo time faz o computador dormir conforme atributo.
palpite = palpite + 1 # conta um ciclo de pensamento do computador e acumula.
if jogador != computador:
print('\033[0;31;0m GANHEI! eu pensei no numero \033[0;31;0m{} \033[0;31;0m e não no \033[0;31;0m{}!''\033[m'.format(
computador, jogador))# computador ganhou.
else:
print('\033[0;31;0m PARABÉNS! Você conseguiu me vencer em {} palpites!\033[m'.format(palpite))# jogador ganhou.
print('FIM')# FIM .
<file_sep>/aulas_basico/aula_06_tipos_primitivos.py
'''Nessa aula 06, vamos aprender como funcionam os tipos primitivos no Python e as peculiaridades do int() float() bool() e str(). Além disso, veremos como fazer as primeiras
operações com a função print() do Python.
int = 7 -4 0 9875 numeros inteiros
float = 4.5 0.0075 -15.223 7.0 numeros reais
bool = true e false
str. "Olá" '7.5' são considerados escritas para impressão.
metodo format é constituido por {} dentro do print que espera do .format(s)
o ewsultado da variavel s no caso.
'''
n1 = int (input ('digite um valor:'))
n2 = int (input ('digite uoutro:'))
s= n1+n2
#print ('A soma entre ',n1, 'e', n2, 'vale', s)
print ('a soma entre {} e {} vale {}' .format(n1,n2,s))
<file_sep>/exercicios/exercicio_052_numero_primo.py
'''Faça um programa que leia um numero inteiro e diga se ele é ou não um numero
primo '''
np = int(input('digite um numero inteiro'))
if np == 0:
print('não é primo')
elif np == 1:
print('não é primo')
elif np%2==0 and np!=2:
print('não é primo')
elif np/1!=np and np/np!=1:
print('não é primo')
elif np%5==0 and np!=5:
print('não é primo')
else:
print('é primo')
<file_sep>/aulas_basico/aula_08_import.py
from math import floor,ceil
n1 = float(input('entre com o valor do cateto oposto'))
n2 = float(input('entre com o valor do cateto adjacente'))
print('O valor da ipotenusa é {}'.format((n1**2)+(n2**2)))
<file_sep>/exercicios/exercicio_013_salario_funcionario.py
n1 = float (input ('Qual o salario do funcionario?'))
print ('O salario do funcionario com 15% de aumento é {:.2f} Reais' .format (n1+(n1*15)/100,))<file_sep>/exercicios/exercicio_59_menu.py
opcao = 0
while opcao != 5:
v1 = float(input('Digite um novo valor '))
v2 = float(input('Digite outro valor '))
print('Escolha uma opção:')
print('[1] SOMAR')
print('[2] MULTIPLICAR')
print('[3] MAIOR')
print('[4] NOVOS NUMEROS')
print('[5] SAIR DO PROGRAMA')
opcao = float(input('DIGITE A OPÇÃO '))
if opcao == 1:
soma = v1+v2
print('A soma de {:.2f} + {:.2f} é = {:.2f}'.format(v1,v2,soma))
elif opcao == 2:
mult = v1*v2
print('A Multiplicação {:.2f} X {:.2f} é = a {:.2f}'.format(v1,v2,mult))
elif opcao == 4:
print('')
elif opcao == 3 and v1>v2:
maior = v1
print('O Maior entre {:.2f} e {:.2f} é {:.2f}'.format(v1, v2, maior))
elif opcao == 3 and v2>v1:
maior = v2
print('O Maior entre {:.2f} e {:.2f} é {:.2f}'.format(v1,v2,maior))
else:
print('FIM')<file_sep>/exercicios/exercicio_042_elif.py
'''refaça o desafio 35 dos triamgulos acrescentando o recurso de mostrar que tipo de triangulo sera formado:
- Equilatero: todos os lados iguais
- Isoceles: dois lados iguais
- Escaleno: Todos os lados diferentes
'''
a = float(input('Escreva o comprimento da reta 1 ='))
b = float(input('Escreva o comprimento da reta 2 ='))
c = float(input('Escreva o comprimento da reta 3 ='))
if b-c<a and a<b+c:
if a-c<b and b<a+c:
if a-b<c and c<a+b:
print('O comprimento destas retas podem formar um triangulo ')
else:
print('O comprimento destas retas não podem ser um triangulo')
if b==c==a:
print('Este triangulo é equilatero.')
elif b!=a and c!=a and c!=b:
print('Este triangulo é escaleno.')
else:
print('Este triangulo é isoceles')
<file_sep>/exercicios/exercicio_063_fibonacci.py
'''
Faça um programas que leia o numero de termos que você quer e mostre em sequencia fibonacci.
'''
n = float(input('Qual o numero de termos fibonacci você deseja ver '))
t1 = 0
t2 = 1
if n == 1:
print(t1)
else:
print('{},{},'.format(t1,t2),end='')
cont = 3
while cont <= n:
cont = cont + 1
print('{},'.format(t1+t2),end='')
t3=t1+t2
t1=t2
t2=t3
<file_sep>/exercicios/exercicio_024_string.py
''' Crie um programa que leia o nome de uma cidade diga se ela começa ou
não com o nome SANTO '''
cid= str(input('Em que cidade você nasceu?')).strip() # .strip() elimina
# espaços depois do input
print(cid[:5].upper() == 'SANTO') # No caso [:5] são os caracteres
# a serem impressos
#.upper joga tudo que foi digitado para maiusculo para que elimini
# a possibilidade de erro quando o usuario for digitar
<file_sep>/aulas_basico/aula_08_randon.py
import random # este modulo gera um numnero randomico que fica
# mudando conforme é executado, randint (1,10) ele mostra numeros
# aleatorios de a 10
num = random.randint(1,10)
print (num)
<file_sep>/exercicios/exercicio_018_biblioteca_math.py
import math
ângulo = float (input('digite o angulo que você deseja:'))# digitar ângulo para variavel ângulo
seno = math.sin(math.radians(ângulo)) # carrega o metodo sin para o calculo do SENO
print ('O ângulo de {} tem o seno de {:.2f}'.format(ângulo,seno))
cosseno= math.cos(math.radians(ângulo))# carrega o metodo cos para o calculo do COSSENO
print ('O ângulo de {} tem o cosseno de {:.2f}'.format(ângulo,cosseno))
tangente = math.tan(math.radians(ângulo)) #carrega o metodo tan para o calculo da TANGENTE
print('O ângulo de {} tem a tangente de {:.2f}'.format(ângulo,tangente))
<file_sep>/exercicios/exercício_03_soma.py
n1= int(input("digite o valor 1"))
n2= int(input("digite 0 valor 2"))
print('A soma entre os numeros é:',n1+n2)
# desafio 3:
# crie um programa que leia dois numeros e mostra a soma entre eles.
<file_sep>/exercicios/exercicio_028_randint.py
'''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e
peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
from random import randint
from time import sleep
computador = randint(0,5) # faz o computador pensar um numero de 0 a 5 e joga na variavel computador.
print('\033[0;31;0m-=-\033[m'*20) # cria uma linha de 20 caracteres
print('\033[0;31;0m Vou Pensar em um numero entre 0 e 5. Tente Adivinhar...\033[m')
print('\033[0;31;0m-=-\033[m'*20) # cria uma linha de 20 caracteres
jogador = int(input('\033[0;31;0m Em que numero eu pensei?\033[m'))
# Jogador tenta adivinhar
print('\033[0;30;41m PROCESSANDO...\033[m')
sleep(3) # do metodo time faz o computador
# dormir conforme
if jogador == computador:
print('\033[0;31;0m PARABÉNS! Você conseguiu me vencer!\033[m')
else:
print('\033[0;31;0m GANHEI! eu pensei no numero \033[0;31;0m{} \033[0;31;0m e não no \033[0;31;0m{}!'
'\033[m'.format(computador, jogador))
print()
<file_sep>/exercicios/exercicio_035_formacao_traingulo.py
'''Exercício Python 035: Desenvolva um programa que leia o comprimento de
três retas e diga ao usuário se elas podem ou não formar um triângulo.'''
comprimento1= float(input('Escreva o valor do primeiro comprimento'))
comprimento2= float(input('Escreva o valor doseomprimento'))
comprimento3= float(input('Escreva o valor do primeiro comprimento'))<file_sep>/exercicios/exercicio_045_jokenpo.py
'''Crie um programa que faça o computador jogar jokenpô com você'''
from random import randint
from time import sleep
itens = ('Pedra','Papel','Tezoura')
computador = randint(0,2)
print('''Vamos jogar JOKENPO escolha Sua opção:
[0] PEDRA
[1] PAPEL
[2] TESOURA''')
jogador = int(input('Qual é a sua jogada '))
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
sleep(1)
print('=-'*11)
print('O você escolheu {}'.format(itens[jogador]))
print('O computador escolheu {}'.format(itens[computador]))
print('=-'*11)
if computador==0:#computador jogou pedra
if jogador==0:
print('Empate')
elif jogador==1:
print('Jogador venceu!')
elif jogador==2:
print('Computadpr venceu!')
else:
print('Jogada Invalida!')
elif computador==1:#computador jogou papel
if jogador==0:
print('Computador venceu!')
elif jogador==1:
print('EMPATE')
elif jogador==2:
print('Jogador venceu!')
else:
print('Jogada Invalida!')
elif computador==2:#computador jogou tesousa
if jogador==0:
print('Jogador Venceu!')
elif jogador==1:
print('Computador Venceu!')
elif jogador==2:
print('Empate!')
else:
print('Jogada Invalida!')
<file_sep>/exercicios/exercicio_046_cont_regress.py
'''faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artificio, indo de 10 até 0, com uma pausa de 1 segundo entre eles.'''
from time import sleep
for c in range(10,0-1,-1):
sleep(1)
print(c)
print('FIM ')#teste
<file_sep>/exercicios/exercicio_029_If_else.py
#Escreva um programa que leia a velocidade de um carro.
# Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado.
# A multa vai custar R$7,00 por cada Km acima do limite.
velocidade = float(input('\033[7;30;0m Qual é a velocidade atual do carro?\033[m'))
if velocidade > 80:
print('-=-'*20)# Cria uma linha divisoria
print('\033[7;30;0m MULTADO! Você excedeu o limete permitido que é de 80km/h \033[m')
multa = (velocidade -80)*7
print('-=-' * 20)
print('\033[7;30;31m Você deve pagar uma multa de R$ {:.2f}\033[m'.format(multa))
else:
print('\033[0;30;31m Tenha um bom dia! Dirija com segurança!\033[m')
# \033[0;30;31m "cria um padrão com estilo cor de texto e cor de fundo".
# \033[m "encerra na linha um padrão de cores a ser impressa".<file_sep>/exercicios/exercicio_036_aprova_emprestimo.py
'''Escreva um programa para aprovar o empréstimo bancário para compra de uma casa.
O programa vai perguntar o valor da casa,
o salario do comprador
e em quantos anos ele vai pagar.
calcule o valor da prestação mensal sabendo que ela não pode exceder 30% do salario ou então o emprestimo sera negado.'''
vcasa = float(input('Qual o valor da casa?'))
sdocomprador = float(input('Qual é o valor do dalario do comprador'))
<file_sep>/exercicios/exercicio_062_while_PA.py
a1 = int(input('Qual o primeiro termo da PA'))
r = int(input('Qual é a razão da PA'))
print(' PA DE RAZÃO {} = {}'.format(r,a1))
n = 1
total = 0
mais = 10
while mais != 0:
total = total+mais
while n < total:
a1 = a1+r
n = n+1
print((' PA DE RAZÃO {} = {}').format(r, a1))
print('PAUSA')
mais = int(input('Quantos termos você quer mostrar mais?'))
print('O total de PA solicitado foi {}, obrigado.'.format(total))
<file_sep>/exercicios/exercicio_033_if.py
#Exercício Python 033: #Faça um programa que leia três números e
# mostre qual é o maior e qual é o menor.
a= int(input('primeiro valor'))
b= int(input('segundo valor'))
c= int(input('terceiro valor'))
if a<b and a<c:
menor= a
if b<a and b<c:
menor=b
if c<a and c<b:
menor = c
print('O menor valor digitado foi {}'.format(menor))
<file_sep>/exercicios/exercicio_048_soma_entre_impares.py
'''faça um programa que calcula a soma entre todos os numeros impares que são multiplos de três e que se encontram no intervalo de 1 até 500'''
soma = 0
cont = 0
for c in range(1,501,2):
if c %3 == 0:#se divisivel por 3 é multiplo de 3 sendo resto =0 então é multiplo de 3
soma += c # no caso aqui é um acumulador soma recebe c + soma a cada repitição
cont += 1# no caso contador cont recebe cont +1 em cada repetição
print('A soma de todos os {} valores solicitados é {}'.format(cont,soma))
<file_sep>/aulas_basico/aula_06_isalnum.py
n = str(input("digite um valor"))
print(n.isalnum()) # metodos de serie de tipos
# pesquisa qua o tipo primitivo entre outros.
<file_sep>/exercicios/exercicio_10_conversor_dolar.py
n1 = float (input ('Quanto dinheiro você tem na carteira? R$'))
print ('com a quantia de dinheiro na sua carteira você pode comprar ${:.2f} dolar'.format(n1/3.27))
<file_sep>/exercicios/exercicio_038_if_else.py
'''Esceva um programa que leia 2 numeros inteiros e compare-os mosntrando na tela uma mensagem:
- O primeiro valor é maior
- O segundo valor é maior
- Não existe valor maior os dois são iguais'''
valor1 = int(input('Escreva o primeiro numero'))
valor2 = int(input('Escreva o segundo numero'))
if valor1 > valor2:
print('O primeiro valor é maior que o segundo')
elif valor2>valor1:
print('O segundo valor é maior que o primeiro')
else:
print('Não existe valor maior os dois são iguais. ')
<file_sep>/exercicios/exercício_01_print_input.py
'''crie um script python que leia o nome de uma pessoa e mostre uma
messagem de boas vindas de acordo com valor digitado'''
nome = input('Escreva seu nome.')
print('Seja bem vindo',nome)
<file_sep>/exercicios/exercicio_039_ano_nascimento.py
''' faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade:
-Se ele ainda vai se alistar ao serviço militar
_Se éa hora de se alistar
-Se ja passou o tempo do alistamento
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo'''
from datetime import date #modulo de data e tempo
'''anonasc = int(input('Qual o seu ano de nascimento?'))
anoatual = date.today().year #função que coloca o ano atual na variavel de forma para fazer calculo de diferença c/ date
idade = anoatual - anonasc
if idade >= 19:
print('Sua idade é:', idade,'anos')
print('Já passou o tempo do seu alistamento!')
print('ja se passaram',idade - 18, 'anos')
elif idade <= 17:
print('Sua idade é:', idade,'anos')
print('Você ainda vai se alistar.')
print('faltam',18-idade,'anos')
elif idade == 18:
print('Sua idade é:', idade,'anos')
print('É hora de se alistar!')
else:'''
dia = int(input('Digite o dia do seu nacimento.'))
mes = int(input('Digite o mês do seu nacimento.'))
ano = int(input('Digite o ano do seu nacimento.'))
print('Faltam para',date.today().year-(ano),'anos')
print(date.today().month-(-mes+2),'mesês')
print(date.today().day-(dia),'dias')
ano=((date.today().year-ano)*365)
mes=((date.today().month-mes)*30)
dia=(date.today().day-dia)
ano= ano+mes+dia
print('Você tem',(ano//366),'anos')
if mes<0:
print(((mes)+360)//30,'mesês')
else:
print((mes)//30,'mesês')
print((dia),'dias')
<file_sep>/exercicios/exercicio_025_string.py
'''Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA"
no nome'''
nome = str(input('Qual éo seu nome?')).strip()
print('Seu nome tem silva?{}'.format('silva'in nome.lower()))
# o operador "in" diz se o silva esta dentro da variavel nome eo nome.lower
# coloca tudo
# que for digitado pelo usuario em minusculo para não ter erro de digitação ao
# ser pesquisado.
<file_sep>/exercicios/exercicio_049_tabuada.py
t= int(input('Qual o numero da tabuada quer?'))
for c in range(1,11):
print(' {} x {} = {}'.format(t,c, (t*c)))
print('FIM')
<file_sep>/aulas_basico/aula_011_cores.py
'''Nessa aula, vamos aprender como utilizar os códigos de escape sequence ANSI
para configurar cores para os seus programas em Python. Veja como utilizar
o código \
style 0 none 1 bold 4 anderline
text 30,31 a 37
back 40 a 47
\033[0:30:41m codigo das cores'''
print('\033[0;30;46m Rodrigo\033[m')
<file_sep>/exercicios/exercicio_061_while.py
'''
Refazer o desafio 051 lendo primeiro termo e a razão de uma PA,mostrando os 10 primeiros termos da progressão usando a estrutura while
'''
a1=0
n=1
a1 = int(input('Qual o primeiro termo da PA'))
r = int(input('Qual é a razão da PA'))
print(' PA DE RAZÃO {} = {}'.format(r,a1))
while n < 10:
a1=a1+r
n = n+1
print((' PA DE RAZÃO {} = {}').format(r,a1))
print('fim')<file_sep>/exercicios/exercicio_034_if_else.py
'''Exercício Python 034: Escreva um programa que pergunte o
salário de um funcionário e calcule o valor do seu aumento.
Para salários superiores a R$1250,00, calcule um aumento de 10%.
Para os inferiores ou iguais, o aumento é de 15%.'''
salario =float(input('Qual o valor do seu salario?'))
if salario >= 1250.00:
calculo = salario * 10/100
print('O valor do salario com aumento é {:.2f}'.format(salario+calculo))
else:
calculo = salario*15/100
print('O valor do salario com aumento é {:.2f}'.format(salario+calculo))
<file_sep>/exercicios/exercicio_018_alngulo.py
from math import radians, sin, cos,tan # escrever cada metodo nesta linha faz com que não precise ser mecionado o math (modulo) no codigo
ângulo = float (input('digite o angulo que você deseja:'))# digitar ângulo para variavel ângulo
seno = sin(radians(ângulo)) # carrega o metodo sin para o calculo do SENO
print ('O ângulo de {} tem o seno de {:.2f}'.format(ângulo,seno))
cosseno= cos(radians(ângulo))# carrega o metodo cos para o calculo do COSSENO
print ('O ângulo de {} tem o cosseno de {:.2f}'.format(ângulo,cosseno))
tangente = tan(radians(ângulo)) #carrega o metodo tan para o calculo da TANGENTE
print('O ângulo de {} tem a tangente de {:.2f}'.format(ângulo,tangente))
<file_sep>/exercicios/exercicio_08_metros.py
'''Desafio 08 Escreva um programa que leia um valor em metros eo
exiba convertido em centimetros'''
n1 = int (input ('Entre com o valor em metros .'))
print ('O Valor dado em metros é {} centimetros'.format(n1*100), end=' ')
print ('ou {} milimetros'.format(n1*1000))<file_sep>/exercicios/exercicio_041_elif.py
'''A confederação nacional de natação prescisa de um programa que leia o ano de nacimento de um atleta e mostre sua categoria de acordo com sua idade:
-até 9 anos:mirim
-até 14 anos: infantil
-até 19 anos: junior
-até 20 anos: senior
_ Acima:master'''
from datetime import date
nascimento = int(input('Qua o ano do seu nascimento?'))
idade = date.today().year - nascimento
if idade <= 9:
print('Sua categoria éa Mirim')
elif idade > 9 and idade <=14:
print('Sua categoria éa Infantil')
elif idade > 14 and idade <= 19:
print('Sua categoria éa Junior')
elif idade > 18 and idade <=20:
print('Sua categoria éa Senior')
else:
print('Sua categoria éa Master')
<file_sep>/aulas_basico/aula_012_if_else.py
'''aula 12 condições aninhadas dentro dessa estrutura pode ser usado
quantos elif forem precisos else 1 ou nenhum e 1 if no inicio'''
#if (carro.esquerdo()):
#elif (carro.direito()):
#else:()
'''nome = str(input('Qual é seu nome?'))
if nome == 'Rodrigo':
print('Que bonito nome!')# até estrutura simples
else:
print('Seu nome é bem normal.')
print('Tenha um bom dia, {}!'.format(nome)) # estrutura composta
print()'''
n = str(input('Qual é seu nome?')).strip()
nome = n.capitalize()
if nome == 'Rodrigo':
print('Que bonito nome!')# até estrutura simples
elif nome == 'Pedro' or nome == 'Maria' or nome == 'Paulo':
print('Seu nome é bem popular no Brasil.') #estrutura CONDICIONAL aninhada
else:
print('Seu nome é bem normal.')
print('Tenha um bom dia, {}!'.format(nome)) # estrutura composta
<file_sep>/exercicios/exercicio_016_biblioteca_matematica.py
from math import floor,ceil
n1 = float(input('entre com um numero'))
print ('O mumero inteiro é {}'.format (floor (n1)))
<file_sep>/exercicios/exercicio_035_if_triangulo.py
'''Exercício Python 035: Desenvolva um programa que leia o comprimento de
três retas e diga ao usuário se elas podem ou não formar um triângulo.'''
a = float(input('Escreva o comprimento da reta 1 ='))
b = float(input('Escreva o comprimento da reta 2 ='))
c = float(input('Escreva o comprimento da reta 3 ='))
if b-c<a and a<b+c:
if a-c<b and b<a+c:
if a-b<c and c<a+b:
print('O comprimento destas retas podem formar um triangulo ')
else:
print('O comprimento destas retas não podem ser um triangulo')
<file_sep>/aulas_basico/aula_013_laço_for.py
'''Nesta aula o for inicia um laça de repeticão depois do range (1,10,2)temos entre esses parentes de 1 a 10 uma repiticão de 9 vezes e o 2 significa pulando de 2 em 2 se fosse -1 significaria que a repetição seria decrescente'''
# dessa forma o range conta crescente
'''for c in range(0,10):
print(c)
print('fim')'''
# dessa forma o range conta decrescente
'''for c in range(10,0,-1):
print(c)
print('fim')'''
# dessa forma o comando for soma N+1 na entrada que faz o range inteiro porque se você digita 10 no range ele roda até 9 um a menos.
''''n = int (input('Digite um numero:'))
for c in range(0,n+1):
print(c)
print('fim')'''
# dessa forma o input esta capturando variavel e jogando dentro do range do for
'''i = int (input('inicio'))
p= int (input('passo'))
f = int (input('fim'))
for c in range(i,f+1,p):#range = (inicio,fim+1,passo ou pulo)
print(c)
print('fim')'''
# dessa forma esta fazendo somatoria
'''s = 0
for c in range(0, 4):
n=int(input('digite uma valor'))#esse input vai rodar 4 vezes
s += n # aqui é igua a variavel s recebendo n+1 ( s=n+1 ou s+=n)
print('O somatorio de todos os valores foi {}'.format(s))'''
<file_sep>/exercicios/exercicio_040_elife.py
'''Crie um programa que leia 2 notas de um aluno e calcule sua média.mostrando uma mensagem no final, de acordo com a média atingida:
-Média abaixo de 5.0:
reprovado
-Média entre 5.0 e 6.9:
Recuperação
- Média entre 5.0 e 6.9:
recuperação
_Média 7'''
nota1 = float (input('Qual a primeira nota?'))
nota2 = float (input('Qual a segunda nota?'))
media = (nota1+nota2)/2
if media<5:
print('Você foi reprovado')
elif media>=5.0and media<= 6.9:
print('Você esta de recuperação')
else:
print('Você foi aprovado!')<file_sep>/aulas_basico/aula_010_if.py
'''Nessa aula, vamos aprender como utilizar estruturas condicionais simples e compostas nos seus
programas em Python.
Veja como aplicar os comandos if: e else: no Python.
---------------------------------------------------------------------'''
n1 = float (input('\033[7;35;40m Digite a primeira nota: \033[m'))
n2 = float (input('\033[7;30;31m Digite a segunda nota: \033[m'))
m = (n1 + n2)/2
print('***'*20)
print('\033[7;35;40m A sua média foi {:.1f}\033[m'.format(m))
if m >= 6.0:
print('\033[0;30;31m sua média foi boa! PARABENS!\033[m ')
else:
print('***'*20)
print('\033[7;30;41m Sua media foi ruim! ESTUDE MAIS!\033[m ')
'''\033[0;30;31m "cria um padrão com estilo cor de texto e cor de fundo".
\033[m "encerra na linha um padrão de cores a ser impressa".'''
<file_sep>/exercicios/exercicio_067_ tabuada_break.py
'''Faça um programa que mostre a tabuada de varios numeros,
um de cada vez, para cada valor digitado pelo usuario.
O programa será interrompido quando o numero solicitado
for negativo.'''
cont =0
while True:
cont = cont+1
t = int(input('Qual o numero da tabuada você quer?'))
if t < 0:
break
for c in range(1,11):
print(' {} x {} = {}'.format(t, c, (t * c)))
print('FIM')
<file_sep>/aulas_basico/aula_08_dica_import.py
from math import sqrt, floor # neste caso from importou da biblioteca
# math somente sqrt e floor que aredonda para baixo
num = int(input('Digite um numero:'))
raiz = sqrt (num)
print ('A raiz de {} é igual {:.2f}'.format( num,floor(raiz)))
# agora que foi chamado as funções no inicio você não precisa usar o math.
<file_sep>/aulas_basico/aula_07_format.py
n1 = int (input('um Valor'))
n2 = int (input('outro valor'))
s = n1+n2
m = n1*n2
d = n1/n2
di = n1//n2
e = n1**n2 # ou pow(4,3)
print('A soma é {}, o produto é {}' .format(s, m, d), end=' ')
# o format pega as chaves {} vazias e coloca as variaveis dentro
# na sequencia apresentada.
# % == a sobra de uma divisão
# calcular a raiz quadrada de um numero é o mesmo que calcular a potência
# dele por **1/2 no caso raiz cubica **(1/3)
# Dentro do print tambem temos no metodo 'print{}' .format {:=^20} que
# coloca o nome no meio entre 20 sinais de igual de cada lado.
# Tambem pode se ser usado {:.3F} que da só o resultado de 3 casas após a virgula.
# Para continua a resta de um print de outra linha na mesma linha se usa
# and='' no final do primeiro print e para quebrar \n onde desejar a quebra.
print ('Divisão inteira {} e potência {}' .format (di,e))
# o end ='' junta os dois print. /n quebra linha.
# ORDEM DE PRECEDENCIA NO PYTHON:
# 1 (...) PARENTESES
# 3 * --/-- //-- %
# 4 + -
# 5 pow COMANDO PARA POTENCIA pow(3,4) = 64
# __________________________________________
# // DIVISÃO INTEIRA
# / DIVISÃO NORMAL
# % SOBRA DA DIVISÃO
# Criar a raiz quadrada de um numero é o mesmo que criar a potência do mesmo por 1/2 entre parenteses no Python.
<file_sep>/exercicios/exercício_06_input.py
n1 = int (input ('Entre com um numero.'))
print ('O numero sucessor do numero digitado é {}'.format (n1+1) )
print ('E o numero antecessor do numero digitado é {}'.format (n1-1) )
<file_sep>/exercicios/exercicio_048_ somatoria.py
for c in range(1,500,3):
s= c+3
print('a soma dos numero impares com multiplo de 3 é: {}:'.format(s))<file_sep>/exercicios/exercicio_050_soma_ pares.py
'''Desenvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for impar desconsidere-o'''
n=0
soma=0
for c in range(0,6):
n = int(input('Digite um numero.'))
if n%2==0:
soma = n+soma
print('A soma dos numeros pares é:',soma)
<file_sep>/exercicios/exercicio_054_ano_de_7_pessoas.py
'''Crie um programa que leia o ano de nascimento de sete pessoas. No final mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores. '''
maior = 0
menor = 0
from datetime import date
for pessoas in range (0,7):
ano = int(input('Qual o ano do nascimento.'))
ano = (date.today().year-(ano))
if ano < 18:
menor += 1# menor recebe menor +1
elif ano > 18:
maior += 1# maior recebe maior +1
else:
print('temos {} maior de idade'.format(maior))
print('temos {} menor de idade'.format(menor))
print('Total de {} pessoas'.format(pessoas+1))
<file_sep>/exercicios/exercicio_027_string.py
'''Faça um programa que leia o nome completo de uma pessoa, mostrando em
seguida o primeiro e o último nome separadamente'''
n = str (input('\033[07;30;44mEscreva o seu nome completo. \033[m')) .strip()
nome = n.split()
print('Muito prazer em te conhecer!')
print('Seu primeiro nome é {}'.format(nome[0]))
print('Seu ultimo nome é {}'.format(nome[len(nome)-1]))
# a funão len conta os nomes e pode ser determinado apartir da onde começa
# no caso -1 para iniciar no zero o primeiro nome ja que a contagem
# dos caracteres começa em o então -1= 0 e 0 =1.
<file_sep>/exercicios/exercicio_056_for.py
'''Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. no final do programa mostre:
A média de idade do grupo
Qual é o nome do homem mais velho do grupo
Quantas mulheres tem menos de 20 anos.'''
somaidade = 0
mediaidade = 0
maioridadehomem = 0
menoridademulher = 0
nomevelho =''
for p in range(1,5):
nome = str(input('Qual o nome {} pessoa?'.format(p)))
idade = int(input('Qual a idade da {} pessoa?'.format(p)))
sexo = str(input('qual o sexo da {} pessoa?'.format(p)))
somaidade += idade
if p == 1 and sexo in 'Mm':
maioridadehome = idade
nomevelho = nome
if sexo in'Mn' and idade > maioridadehomem:
maioridadehomem = idade
nomevelho = nome
if sexo in 'Ff' and idade < 20:
menoridademulher += 1
médiaidade = somaidade/4
print('A média da idade do grupo é:{}'.format(médiaidade))
print('O homem mais velho do grupo é: {} '.format(nomevelho))
print('{} mulheres são menores de 20 anos'.format(menoridademulher))
<file_sep>/exercicios/exercicio_047_numeros_pares_ de_1_a_50.py
'''Crie um programa que mostre na tela todos os numeros pares que estão no estão no intervalo entre 1 e 50'''
for c in range(0,50,2):
print(c)
<file_sep>/aulas_basico/aula_06_mostra_primitivo.py
n = str(input("digite um valor"))
print(type(n)) # type mostra o tipo primitivo
<file_sep>/exercicios/exercicio_044_elif.py
'''Elabore um programa que cacule o valor a ser pago por um produto considerando o seu preço normal e condição de pagamento:
- À vista dinheiro / cheque :10% de desconto
- À vista no cartão: 5% de desconto
- Em até 2x no cartão preço normal
- 3x ou mais no cartão 20% de juros'''
produto =float(input('Qual o preço do produto? '))
formapag = float(input('Digite uma opção para forma de pagamento:\n''1 pagamento a vista no dinheiro\n''2 pagamento a vista no cartão\n''3 pagamento em 2x no catão\n''4 pagamento em 3x ou mais'))
if(formapag == 1):
print('OK seu pagamento sera a vista em dinheiro\n'' e você vai pagar {:.2f}'.format(produto-produto*10/100))
elif (formapag == 2):
print('OK seu pagamento sera a vista em cartão\n''e você vai pagar {:.2f}'.format(produto-produto*5/100))
elif (formapag == 3):
print('OK seu pagamento sera em 2x no cartão\n''e você vai pagar {:.2f}'.format(produto))
elif (formapag == 4):
print('OK seu pagamento sera em 3 x ou mais cartão\n''e você vai pagar {:.2f}'.format(produto + produto * 20 / 100))
else:
print('ok')
<file_sep>/exercicios/exercicio_066_break.py
'''Crie um programa que leia varios numeros inteiros pelo teclado.
O programa só vai parar quando o usuario digiitar o valor 999. que é a condiçao de parada.No final mostre quantos numeros foram digitados e qual foi a soma entre eles'''
total = 0
n2 = 0
while True:
total = total+1
n = int(input('Digite um numero'))
n1 = n
n2 = (n1+n2)
n2 = n2
if n == 999:
break
print(f'total de numeros digitados forão: {total-1}')
print(f'A soma dos numeros digitados foi:{n2-999}')
<file_sep>/exercicios/exercicio_017_raiz_quadrada.py
from math import floor,ceil,sqrt
cateto_op = float(input('entre com o valor do cateto oposto'))
cateto_ad = float(input('entre com o valor do cateto adjacente'))
soma_dos_lados_do_triangulo_retangulo_ao_quadrado = ((cateto_op**2)+(cateto_ad**2))
Raiz_quadrada_da_soma_dos_Lados_ao_quadrado = sqrt(soma_dos_lados_do_triangulo_retangulo_ao_quadrado)
print ('O valor da ipotenusa é {:.2f}'.format(Raiz_quadrada_da_soma_dos_Lados_ao_quadrado))
<file_sep>/aulas_basico/aula_04_print.py
'''Quarta aula como criar interações entre o computador e o usuário,
vendo o funcionamento das funções print() e input(), diretamente
usando Variáveis.'''
#No Python todos os comandos são considerados funções e todas as
# funções tem parenteses ().2018
print('Olá mundo')# mostra o texto dentro de aspas
print (7+4) #mostra o resultado do calculo da expressão matématica sem aspas
print ('7' + '4') #desta forma o Sinal de + não soma e sim junta as sentenças
# ser usado tambem uma , para juntar em casos que um outro vai ser melhor.
# utilize as variaves = objetos, sempre em letra minuscula.
# as variaveis recebem dados usando-se o sinal de = chamado em python recebe,
# exemplo: ....nome = João
nome ='Rodrigo'
idade= 25
peso = 72.8
print(nome, idade, peso) # se fosse usado sinal de mais não juntaria pois
# só junta mensagem com mensagem numero com numero
# recebendo função especifica se usa o input declara a mensagem na tela e
# envia para dentro da variavel o valor digitado
nome = input('Qual seu nome?') # exemplo
dia = 17
mes = 'Mar'
ano = 1978
print('você nasceu',dia,'do mes de',mes,'do ano de ',ano)
<file_sep>/exercicios/exercicio_011_pintar_parede.py
n1 = float (input ('Qual a largura da parede?'))
n2 = float (input ('Qual a altura da parede?'))
print ('A quantidade de tinta para pintar a area calculada é {} litros de tinta' .format ((n1*n2)/2,))
<file_sep>/aulas_basico/aula_014_while.py
'''
Aula 14.
O laço for e o laço while pode ser usado em alguns semalhantes casos a diferença é que o laço for só pode ser usado quando temos o parametro incial eo final, já o laço while e deteminado somente 1 parametro de parada.
Exemplo:
'''
'''
r = 'S'
while r == 'S':
n = int(input('Digite um valor.'))
r = str(input('Quer continuar?[S/N]')).upper()
print('Fim')
'''
n = 1
while n != 0:
n = int(input('Digite um valor:'))
print('FIM!')
<file_sep>/exercicios/exercicio_057_while.py
'''Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'
caso esteja errado, peça a digitação novamente até ter um valor correto.'''
sexo = 'a'
while sexo != 'M' and sexo != 'F':
sexo = str(input('Qual éo sexo?[M/F]')).upper()
if sexo == 'M':
sexo = 'Masculino'
else:
sexo = 'Feminino'
print('Seu sexo é:{}'.format(sexo))
<file_sep>/exercicios/exercicio_07_media.py
n1 = int (input ('Entre com a primeira nota .'))
n2 = int (input ('Entre com a segunda nota.'))
print ('A média das notas entradas é {}'.format((n1+n2)//2)) | ae04d655c78837d6f4a0b1e543b88969ba6a0c23 | [
"Markdown",
"Python"
] | 74 | Python | RFSOU/Curso-Python | 4e43278b224a1d8b38e1586c942e0c263fa3dc08 | ba48ebdb9c0ef57b1afd5ab1055d148b442e155c |
refs/heads/master | <repo_name>ryanturner/HamWAN-Memphis-Metro-Website<file_sep>/protected/views/layouts/main.php
<?php /* @var $this Controller */ ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>HamWAN Memphis Metro - <?php echo CHtml::encode($this->pageTitle); ?></title>
<!-- Bootstrap core CSS -->
<link rel="icon" type="image/png" href="<?php echo Yii::app()->request->baseUrl; ?>/images/favicon.png" />
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/template.css" rel="stylesheet">
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" rel="stylesheet">
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/glyphicons.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>(th
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.glyphicons:before, .glyphicons {
font-size: 96px;
width: 96px;
height: 96px;
color: #aaa;
}
<?php if((Yii::app()->controller->id != 'site')): ?>
div.navbar-wrapper {
display: block !important;
position: relative !important;
}
<?php endif; ?>
</style>
<!-- Custom styles for this template -->
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/carousel.css" rel="stylesheet">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/modernizr.js"></script>
</head>
<!-- NAVBAR
================================================== -->
<body>
<div class="navbar-wrapper">
<div class="container">
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo $this->createUrl('site/'); ?>"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/hamwan-logo.png" /></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li<?php if(Yii::app()->controller->id == 'site') echo ' class="active"'; ?>><a href="<?php echo $this->createUrl('site/'); ?>">Home</a></li>
<li<?php if(Yii::app()->controller->id == 'about') echo ' class="active"'; ?>><a href="<?php echo $this->createUrl('about/'); ?>">About</a></li>
<li<?php if(Yii::app()->controller->id == 'getInvolved') echo ' class="active"'; ?>><a href="<?php echo $this->createUrl('getInvolved/'); ?>">Get Involved</a></li>
<li<?php if(Yii::app()->controller->id == 'contact') echo ' class="active"'; ?>><a href="<?php echo $this->createUrl('contact/'); ?>">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Technical Resources <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://www.hamwan.org/">HamWAN.org</a></li>
<li><a href="http://www.heywhatsthat.com/profiler.html">HeyWhatsThat Path Profiler</a></li>
<li><a href=
"http://caltopo.com/map?id=0G4I">
Potential sites and viewshed</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php if(($this->id == 'site') && ($this->action->id == 'index')): ?>
<?php echo $content; ?>
<div class="container">
<?php else: ?>
<div class="container">
<?php echo $content; ?>
<?php endif; ?>
<footer>
<p class="pull-right"><a href="#">Back to top</a></p>
<p>Licensed <a href=
"http://creativecommons.org/licenses/by/3.0/us/">creative commons
attribution 3.0</a>, <?php echo date('Y'); ?> MemHamWAN. · <a href="#">Privacy</a> ·
<a href="#">Terms</a></p>
</footer>
</div><!-- /.container -->
</body>
</html>
<file_sep>/protected/views/contact/index.php
<?php
/* @var $this SiteController */
$this->pageTitle = 'About';
?>
<div class="jumbotron">
<h1>Get in touch with us!</h1>
<p>Whether you're well versed in WISP technologies or entirely new to the concepts, feel free to contact us for more information! We're always interested in speaking with potential users, interested organizations, and infrastructure owners.</p>
</div>
<div class="container contact">
<div class="row">
<div class="col-md-12">
Feel free to reach out to us in any of the following places!
<ul>
<li><a href="http://webchat.freenode.net/?nick=MemHamWAN..&channels=%23HamWAN">Freenode IRC chatroom #HamWAN</a></li>
<li><a href="https://groups.google.com/forum/#!forum/memhamwan">Google Group</a></li>
<li><a href="mailto:<EMAIL>">Email</a></li>
</ul>
</div>
</div>
</div><file_sep>/protected/views/about/index.php
<?php
/* @var $this SiteController */
$this->pageTitle = 'About';
?>
<div class="row">
<div class="col-md-12">
<h1>About HamWAN Memphis Metro</h1>
<p class="lead">We are an amateur radio group interested in implementing
the HamWAN project in Memphis. At this point, we're
collecting resources, planning, and preparing for our first
site deployment. What is HamWAN generally?</p>
<h2>Emergency communications when other systems go
down</h2>
<p>HamWAN supports local agencies and
individuals during emergencies by providing them with
network connectivity when traditional systems are
unavailable.</p>
<p>HF, VHF, and UHF amateur infrastructure has proven
itself time and again as a critical resource in emergency.
As the volume of data ever increases, emergency
communication needs are changing. Agencies depend more and
more on software to support their operations. Providing
network connectivity in emergency situations enables better
coordination and cooperation.</p>
<h2>Research and development in the realm of microwave
networking</h2>
<p>Our unique project helps further software
and hardware projects by contributing useful data; we're
open-source, allowing for anyone to contribute to the
project.</p>
<p>We strive to offer back helpful information to the community
about the successes and challenges involved with our project.
As such, information like antenna performance analyses, true
power consumption, practical throughput, and optimal configurations
are all published for public use.</p>
<p>Additionally, development of custom software, as well as
hardware, is a key goal of our project. With some of the same
expensive equipment used for evaluating hardware, new hardware
can be made too. Custom power systems, antennas, and mounting
systems are all part of the development that HamWAN furthers.
</p>
<h2>A means of free digital communication for anyone who is
or becomes a licensed radio amateur</h2>
<p>Connecting remotely-controlled SDRs, internet
gateways, repeaters, or an entire shack is simplified by
bringing network connectivity where it may not be otherwise
practical.</p>
<p>HamWAN uses <a href="http://www.ampr.org">AMPR</a> also known
as 44net for address space and network access. Existing
infrastructure within the 172.16.17.32/8 network is fully
supported, each part of our network uses 44net address
space. Thus, integration with existing digital radio
infrastructure is made easy. In addition, existing networks that
depend on internet like IRLP, Echolink, D-Star, and APRS are
fully supported.</p>
<p>As with all amateur radio communication in the USA, encryption
is strictly forbidden unless in time of emergency. Additionally,
pecuniary interest in communications is forbidden as well. Much
like existing repeater infrastructure operates, the end user
is responsible for the proper utilization of the system. We
encourage legitimate amateur radio use of the network to help
meet your needs and requirements.</p>
<h2>An educational resource in spreading the knowledge of
how to create, operate and use such networks</h2>
<p>For many amateur radio operators, our experience
doesn't go beyond using a wireless router at home. Microwave data
networks are an entirely new tool to learn.</p>
<p>Network infrastructure is a key component of our lives, and
wireless network connectivity is increasingly being relied upon.
HamWAN allows amateurs to learn about these technologies on a scale
and use that typically exceeds a home network, while also learning
about microwave RF behaviour. It's a great resource for those with
interest both in physics and computer science.</p>
</div>
</div><file_sep>/protected/views/getInvolved/index.php
<?php
/* @var $this SiteController */
$this->pageTitle = 'About';
?>
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading">Connect with us. <span class="text-muted">We'll help you get started.</span></h2>
<p class="lead">We're still working on our first cell site deployments, but now is a great time to get involved. By organizing interest and having members join early, HamWAN Memphis Metro will be a member-driven organization as envisioned by the founders. <a href="https://groups.google.com/forum/#!forum/memhamwan">Join our google group</a> to get started.</p>
</div>
<div class="col-md-5">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/installed-old-client-node.png" style="width: 100%;" />
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-5">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/lab.png" style="width: 100%;" />
</div>
<div class="col-md-7">
<h2 class="featurette-heading">Donate your resources. <span class="text-muted">Contacts, equipment, and funding are all needed.</span></h2>
<p class="lead">Emergency and experimental users of the HamWAN network are key to its success, but getting these organizations involved requires trusted sources facilitating the conversation. Additionally, network and server equipment is required to support the services planned. The easiest way to support us, however, is with a monetary donation. <a href="<?php echo $this->createUrl('contact/'); ?>">Contact us</a> if you'd like to make a donation.</p>
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading">Share us. <span class="text-muted">Talk to your club about our project.</span></h2>
<p class="lead">Engaging existing amateur radio and technology groups is key to our success. We invite you to discuss our project with your peers or even reach out to us and have one of our public affairs representatives speak with your group. Awareness is vital to our project. <a href="<?php echo $this->createUrl('contact/'); ?>">Contact us</a> to request a presentation, or check out the resources on <a href="http://www.hamwan.org/">hamwan.org</a> to make your own!</p>
</div>
<div class="col-md-5">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/presentation-500px.png" style="width: 100%;" />
</div>
</div>
<hr class="featurette-divider">
<h1>Who should join?</h1>
<p>Agencies and organizations</p>
<p>Amateur radio operators</p>
<p>Radio Infrastructure Owners</p><file_sep>/protected/views/site/index.php
<?php
/* @var $this SiteController */
$this->pageTitle = 'Home';
?>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/portable-node-banner.jpg" alt="portable node" style="max-width: 100000% !important;">
<div class="container">
<div class="carousel-caption" style="text-shadow: 0px 0px 0.5em #000, 0px 0px 0.75em #000, 0px 0px 1em #000, 0px 0px 2em #000, 0 1px 2px rgba(0, 0, 0, 0.6);">
<h1 style="">Memphis' Amateur Radio Multi-Megabit IP Network</h1>
<p>Offering network access for experimentation and learning on amateur microwave (5.9 GHz) frequencies using affordable, scalable, high-powered equipment.</p>
<p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
</div>
</div>
</div>
</div>
</div>
<!-- Marketing messaging and featurettes
================================================== -->
<!-- Wrap the rest of the page in another container to center all the content. -->
<div class="container marketing">
<!-- Three columns of text below the carousel -->
<div class="row">
<div class="col-lg-4">
<a class="glyphicons settings"></a>
<h2>What is it used for</h2>
<p>From experimentation to remote site access, HamWAN can be used as a high-speed data network to augment your existing amateur radio interests. Use it to bring internet access to a repeater, transfer emergency aerial surveys, or chat with friends on IRC.</p>
<p><a class="btn btn-default" href="<?php echo $this->createUrl('about/'); ?>" role="button">View details »</a></p>
</div><!-- /.col-lg-4 -->
<div class="col-lg-4">
<a class="glyphicons circle_question_mark"></a>
<h2>Why HamWAN</h2>
<p>HamWAN is a forward-thinking amateur IP network. It scales well, is security focused, and is friendly with other ham networks (AMPR and even NW-MESH/HSMM-MESH to a degree). It's more flexible, configurable, and higher performance than other solutions as well.</p>
<p><a class="btn btn-default" href="Why-HamWAN.pdf" role="button">View details »</a></p>
</div><!-- /.col-lg-4 -->
<div class="col-lg-4">
<a class="glyphicons group"></a>
<h2>How can I get involved</h2>
<p>Right now, in Memphis we're still in the planning stages. Join us in our live chat at <a href="http://webchat.freenode.net/?nick=MemHamWANGuest&channels=%23HamWAN">#HamWAN on Freenode</a> to discuss the project! We're modelling the system directly off of the <a href="https://www.hamwan.org/t/tiki-index.php?page=Puget+Sound+Data+Ring&structure=HamWAN">PSDR</a>.</p>
<p><a class="btn btn-default" href="<?php echo $this->createUrl('getInvolved/'); ?>" role="button">View details »</a></p>
</div><!-- /.col-lg-4 -->
</div><!-- /.row -->
</div> | 567cf0dad29acc5b14a7937e4ad1971b3da7cb2b | [
"PHP"
] | 5 | PHP | ryanturner/HamWAN-Memphis-Metro-Website | 1f71c6ef837f62670353d44691b2c1dd4e95aecb | 78f46b3376d4a1ac273ae56066ed4ea65f1272de |
refs/heads/master | <repo_name>marble/typo3-ExtendingSphinxForTYPO3<file_sep>/src/t3sphinx/writers/__init__.py
# -*- coding: utf-8 -*-
"""
t3sphinx.writers
~~~~~~~~~~~~~~~~~
Contains Sphinx writers for TYPO3
:copyright: Copyright 2012-2099 by the TYPO3 documentation team,
see AUTHORS.
:license: BSD, see LICENSE for details.
"""
<file_sep>/README.rst
typo3-ExtendingSphinxForTYPO3
=============================
This is a modernized version of https://git.typo3.org/Documentation/RestTools.git/tree/HEAD:/ExtendingSphinxForTYPO3
The following part of this README is outdated and needs to be updated.
==========
README.txt
==========
mb, 2012-05-30, 2013-03-16
ExtendingSphinxForTYPO3 is a Python package that extends the capabilities
of Sphinx specifically for TYPO3. After installation it can be loaded
in Python as module 't3sphinx'::
import t3sphinx
The package has been tested with Python 2.x. At the moment it will
probably not run with Python 3.x.
Installation
============
To install go to the directory ./ExtendingSphinxForTYPO3 where the
setup.py file is located and run ``python setup.py install``. To
reinstall you can do this as often as you want.
At the commandline::
$ cd ./ExtendingSphinxForTYPO3
$ python setup.py install
or maybe, if you need to be administrator on linux::
$ cd ./ExtendingSphinxForTYPO3
$ sudo python setup.py install
.. important::
To make anything work of what this module 't3sphinx' provides
you have to manually add the codeblock from
``ExtendingSphinxForTYPO3/src/t3sphinx/resources/typo3_codeblock_for_conf.py`` to your
``conf.py`` file.
What does it do?
================
Assuming that your conf.py contains the ``typo3_codeblock_for_conf.py``
code block:
- It provides the 'typo3sphinx' theme and sets ``html_theme = 'typo3sphinx'``
- It provides GlobalSettings.yml (YAML)
- It will read and apply GlobalSettings.yml and Settings.yml (YAML)
- It makes the "t3-field-list-table" directive available.
See http://mbless.de/4us/typo3-oo2rest/06-The-%5Bfield-list-table%5D-directive/1-demo.rst.html
for a preliminary description. Other than described there use
``t3-field-list-table`` instead of ``field-list-table``.
Updates of ExtendingSphinxForTYPO3
==================================
A typical commit message is this:
Update the TYPO3 specific extensions for Sphinx to reflect the lastest
state we are using on the server.
Whenever a new version of "ExtendingSphinxForTYPO3" is issued do these
three steps to update your local machine::
$ git clone git://git.typo3.org/Documentation/RestTools.git RestTools
$ cd RestTools/ExtendingSphinxForTYPO3
$ (sudo) python setup.py install
Enjoy!
End.
<file_sep>/src/t3sphinx/t3docutils/directives/__init__.py
# -*- coding: utf-8 -*-
"""
t3sphinx.t3docutils.directives
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
"""
<file_sep>/src/t3sphinx/t3docutils/__init__.py
# -*- coding: utf-8 -*-
"""
t3sphinx.t3docutils
~~~~~~~~~~~~~~~~~~~
...
"""
<file_sep>/src/t3sphinx/writers/t3htmlwriter.py
# -*- coding: utf-8 -*-
"""
t3sphinx.writers.t3htmlwriter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Customize HTML writing for TYPO3
:copyright: Copyright 2007-2099 by the TYPO3 Documentation Team
:license: BSD, see LICENSE for details.
"""
from sphinx.writers.html import HTMLTranslator, _, Image, os, posixpath
class T3HTMLTranslator(HTMLTranslator):
def visit_image(self, node):
olduri = node['uri']
s = olduri.lower()
go = True
go = go and not Image is None
go = go and not (s.endswith('svg') or
s.endswith('svgz') or
s.endswith('swf'))
go = go and not (node.has_key('width') or
node.has_key('height') or
node.has_key('scale'))
if go and node.has_key('classes'):
go = go and not 'screenshot-detail' in node['classes']
if go:
# Try to figure out image height and width. Docutils does that too,
# but it tries the final file name, which does not necessarily exist
# yet at the time the HTML file is written.
try:
im = Image.open(os.path.join(self.builder.srcdir, olduri))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
go = False # better warn?
else:
im_width = str(im.size[0])
im_height = str(im.size[1])
del im
if go:
# rewrite the URI if the environment knows about it
if olduri in self.builder.images:
node['uri'] = posixpath.join(self.builder.imgpath,
self.builder.images[olduri])
atts = {}
atts['src'] = node['uri']
if not node.has_key('classes'):
node['classes'] = ['img-scaling']
elif not 'img-scaling' in node['classes']:
node['classes'].append('img-scaling')
else:
pass
atts['style'] = 'max-width: %spx;' % im_width
if node.has_key('alt'):
atts['alt'] = node['alt']
else:
atts['alt'] = node['uri']
if node.has_key('align'):
self.body.append('<div align="%s" class="align-%s">' %
(node['align'], node['align']))
self.context.append('</div>\n')
else:
self.context.append('')
self.body.append(self.emptytag(node, 'img', '', **atts))
else:
del s, go
HTMLTranslator.visit_image(self,node)
return
def visit_literal(self, node):
self.body.append(self.starttag(node, 'span', '', CLASS='docutils literal tt'))
self.protect_literal_text += 1
def depart_literal(self, node):
self.protect_literal_text -= 1
self.body.append('</span>')
def visit_span(self, node):
# ToDo: handle class and id
self.body.append(self.starttag(node, 'span'))
def depart_span(self, node):
self.body.append('</span>')
def depart_title(self, node):
close_tag = self.context[-1]
if (self.permalink_text and self.builder.add_permalinks and node.parent.hasattr('ids') and node.parent['ids']):
aname = ''
for id in node.parent['ids']:
if self.builder.env.domaindata['std']['labels'].has_key(id):
ref_text = '. Label :ref:`%s`' % id
aname = id
break
if aname:
link_text = ':ref:'
else:
ref_text = ''
aname = node.parent['ids'][0]
link_text = self.permalink_text
# add permalink anchor
if close_tag.startswith('</h'):
what = u'<a class="headerlink" href="#%s" ' % aname + u'title="%s">%s</a>' % (
_('Permalink to this headline') + ref_text, link_text)
if 0:
print 'what:', repr(what)
print 'aname:', repr(aname)
self.body.append(what)
elif close_tag.startswith('</a></h'):
what = u'</a><a class="headerlink" href="#%s" ' % aname + u'title="%s">%s' % (
_('Permalink to this headline') + ref_text, link_text)
if 0:
print 'what:', repr(what)
print 'aname:', repr(aname)
self.body.append(what)
HTMLTranslator.depart_title(self, node)
<file_sep>/src/t3sphinx/__init__.py
# -*- coding: utf-8 -*-
"""
t3sphinx
~~~~~~~~
TYPO3 specific extensions for Sphinx
:copyright: Copyright 2012-2099 by the TYPO3 Documentation Team
and TYPO3 community, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Keep this file executable as-is in Python 3!
# (Otherwise getting the version out of it from setup.py is impossible.)
import os
import yamlsettings
__version__ = '0.3.0'
# absolute path to the 't3sphinx' package
package_dir = os.path.abspath(os.path.dirname(__file__))
# absolute path to the ./locale folder
locale_dir = os.path.join(package_dir, 'locale')
# absolute path to the ./themes folder
themes_dir = os.path.join(package_dir, 'themes')
# absolute path to /.../t3sphinx/settings/GlobalSettings.yml
pathToGlobalYamlSettings = os.path.join(package_dir, 'settings', 'GlobalSettings.yml')
# absolute path to /.../t3sphinx/resources/typo3_codeblock_for_conf.py
typo3_codeblock_for_conf_py = os.path.join(package_dir, 'resources', 'typo3_codeblock_for_conf.py')
# register the FieldListTable directive in docutils as 't3-field-list-table'
from docutils.parsers.rst import directives
from t3sphinx.t3docutils.directives import fieldlisttable
directives.register_directive('t3-field-list-table', fieldlisttable.FieldListTable)
<file_sep>/src/t3sphinx/builders/t3htmlbuilder.py
# -*- coding: utf-8 -*-
"""
t3sphinx.builders.t3htmlbuilder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Several HTML builders for TYPO3
:copyright: Copyright 2007-2099 by the TYPO3 documentation team,
see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinx.builders.html import StandaloneHTMLBuilder, jsonimpl, _, \
pickle, ENV_PICKLE_FILENAME, LAST_BUILD_FILENAME, OptionParser, \
__version__, new_document, b, Publisher, DocTreeInput, \
StringOutput, DoctreeReader, SEP, path, os_path, ensuredir, \
codecs, copyfile, bold, darkgreen, brown, inline_all_toctrees, \
nodes, os
import sphinx.util.osutil
import docutils.nodes
class span(docutils.nodes.Inline, docutils.nodes.TextElement):
pass
class T3StandaloneHTMLBuilder(StandaloneHTMLBuilder):
name = 't3html'
mb_publisher = None
mb_doccount = 0
# too bad we need this class variables at the moment ...
LAST_CUR_NODE = None
LAST_TOC_DIV = None
def write_doc(self, docname, doctree):
StandaloneHTMLBuilder.write_doc(self, docname, doctree)
if 0 and 'dump files for inspection':
self.mb_doccount += 1
if self.mb_doccount == 1:
from pprint import pprint
if 1:
outfilename = self.get_outfilename(docname) + '.intersphinx_cache.pprint.txt'
f2 = codecs.open(outfilename, 'w', 'utf-8')
pprint(self.env.intersphinx_cache, f2, width=160)
f2.close
if 1:
outfilename = self.get_outfilename(docname) + '.intersphinx_inventory.pprint.txt'
f2 = codecs.open(outfilename, 'w', 'utf-8')
pprint(self.env.intersphinx_inventory, f2, width=160)
f2.close
if 1:
outfilename = self.get_outfilename(docname) + '.intersphinx_named_inventory.pprint.txt'
f2 = codecs.open(outfilename, 'w', 'utf-8')
pprint(self.env.intersphinx_named_inventory, f2, width=160)
f2.close
if 1:
outfilename = self.get_outfilename(docname) + '.pformat.txt'
# outfilename's path is in general different from self.outdir
sphinx.util.osutil.ensuredir(os.path.dirname(outfilename))
output = doctree.pformat()
try:
f = codecs.open(outfilename, 'w', 'utf-8', 'xmlcharrefreplace')
try:
f.write(output)
finally:
f.close()
except (IOError, OSError), err:
self.warn("error writing file %s: %s" % (outfilename, err))
def handle_page(self, pagename, addctx, templatename='page.html',
outfilename=None, event_arg=None):
"""addctx['toc'] is only here. To make that accessible
we add it to self.
"""
self.t3addctx = addctx
StandaloneHTMLBuilder.handle_page(self, pagename, addctx,
templatename, outfilename, event_arg)
def get_doc_context(self, docname, body, metatags):
"""Collect items for the template context of a page."""
# TYPO3: remove 'documentation' from end of 'shorttitle'
shorttitle = self.globalcontext.get('shorttitle', '')
if shorttitle and shorttitle.endswith(' documentation'):
shorttitle = shorttitle[0:-14].rstrip()
self.globalcontext['shorttitle'] = shorttitle
# find out relations
# TYPO3: always have order 'previous', 'up', 'next'
prev = up = next = None
parents = []
rellinks = self.globalcontext['rellinks'][:]
related = self.relations.get(docname)
titles = self.env.titles
if related and related[1]:
try:
prev = {
'link': self.get_relative_uri(docname, related[1]),
'title': self.render_partial(titles[related[1]])['title']
}
rellinks.append((related[1], prev['title'], 'P', _('previous')))
except KeyError:
# the relation is (somehow) not in the TOC tree, handle
# that gracefully
prev = None
if related and related[0]:
try:
up = {
'link': self.get_relative_uri(docname, related[0]),
'title': self.render_partial(titles[related[0]])['title']
}
rellinks.append((related[0], up['title'], 'U', _('up')))
except KeyError:
# the relation is (somehow) not in the TOC tree, handle
# that gracefully
prev = None
if related and related[2]:
try:
next = {
'link': self.get_relative_uri(docname, related[2]),
'title': self.render_partial(titles[related[2]])['title']
}
rellinks.append((related[2], next['title'], 'N', _('next')))
except KeyError:
next = None
while related and related[0]:
try:
parents.append(
{'link': self.get_relative_uri(docname, related[0]),
'title': self.render_partial(titles[related[0]])['title']})
except KeyError:
pass
related = self.relations.get(related[0])
if parents:
parents.pop() # remove link to the master file; we have a generic
# "back to index" link already
parents.reverse()
# title rendered as HTML
title = self.env.longtitles.get(docname)
title = title and self.render_partial(title)['title'] or ''
# the name for the copied source
sourcename = self.config.html_copy_source and docname + '.txt' or ''
# metadata for the document
meta = self.env.metadata.get(docname)
# local TOC and global TOC tree
self_toc = self.env.get_toc_for(docname, self)
toc = self.render_partial(self_toc)['fragment']
return dict(
parents = parents,
prev = prev,
next = next,
title = title,
meta = meta,
body = body,
metatags = metatags,
rellinks = rellinks,
sourcename = sourcename,
toc = toc,
# only display a TOC if there's more than one item to show
display_toc = (self.env.toc_num_entries[docname] > 1),
)
def _get_local_toctree(self, docname, collapse=True, **kwds):
"""Create menu in a form that suits the TYPO3 menu structure.
"""
toctree_for = self.env.get_toctree_for(docname, self, collapse, **kwds)
def dumpit(fname='/sphinx/tmp/t3htmlbuilder/LOG.txt'):
import codecs
f2 = codecs.open(fname,'a','utf-8','xmlrefreplace')
f2.write('%s: %s\n' % ('self', self))
f2.write('%s: %s\n' % ('docname', docname))
f2.write('%s: %s\n' % ('collapse', collapse))
f2.write('%s: %r\n' % ('kwds', kwds))
f2.write('%s: %r\n' % ('toctree_for', toctree_for))
f2.write('%s: %r\n' % ("self.render_partial(toctree_for)['fragment']", self.render_partial(toctree_for)['fragment']))
# f2.write('%s: %s\n' % ('toctree_for.asdom().toxml()', toctree_for.asdom().toxml()))
f2.write('%s: %s\n' % ('toctree_for.pformat()', toctree_for.pformat()))
f2.write('#####' * 10)
f2.close()
if 0:
dumpit()
def debugpublish():
import docutils
# def publish_from_doctree(document, destination_path=None,
# writer=None, writer_name='pseudoxml',
# settings=None, settings_spec=None,
# settings_overrides=None, config_section=None,
# enable_exit_status=False)
document = toctree_for
destination_path = 'U:\\htdocs\\LinuxData200\\py-dev\\LOG.txt'
writer=None
writer_name='pseudoxml'
settings=None
settings_spec=None
settings_overrides=None
config_section=None
enable_exit_status=False
docutils.core.publish_from_doctree(document, destination_path=None,
writer=None, writer_name='pseudoxml',
settings=None, settings_spec=None,
settings_overrides=None, config_section=None,
enable_exit_status=False)
if 0:
result = debugpublish()
def publishAsXml(doc):
if self.mb_publisher is Non9e:
self.mb_publisher = Publisher(
source_class = DocTreeInput,
destination_class=StringOutput)
self.mb_publisher.set_components(
'standalone','restructuredtext', 'pseudoxml')
pub = self.mb_publisher
pub.reader = DoctreeReader()
pub.writer = sphinx_writers_html_HTMLWriter(self)
pub.process_programmatic_settings(
None, {'output_encoding': 'unicode'}, None)
pub.set_source(doc, None)
pub.set_destination(None, None)
pub.publish()
result = pub.writer.parts
if 0:
# doesn't work yet!?!
publishAsXml(toctree_for)
# def traverse(self, condition=None, include_self=1, descend=1,
# siblings=0, ascend=0)
class visitor(docutils.nodes.GenericNodeVisitor):
ul_level = 0
last_nav_aside_lvl = ''
cnt = 0
def default_visit(self, node):
"""Override for generic, uniform traversals."""
if hasattr(node, 'attributes'):
self.cnt += 1
classes = node.attributes.get('classes', [])
newlist = []
iscurrent = False
for cl in classes:
if not cl in newlist:
newlist.append(cl)
if cl.startswith('toctree-l'):
self.last_nav_aside_lvl = 'nav-aside-lvl%s' % (cl[9:],)
newlist.append(self.last_nav_aside_lvl)
if cl == 'current':
newlist.append('cur')
iscurrent = True
if node.attributes.get('iscurrent', False) and type(node.parent) == nodes.list_item:
# print node.pformat()
T3StandaloneHTMLBuilder.LAST_CUR_NODE = node
try:
self_toc = self.t3addctx['self_toc']
except:
self_toc = None
if self_toc:
T3StandaloneHTMLBuilder.LAST_TOC_DIV = nodes.container(ids=["flyOutToc"], classes=['flyOutToc'])
T3StandaloneHTMLBuilder.LAST_TOC_DIV.append(nodes.paragraph(text='within this page:'))
T3StandaloneHTMLBuilder.LAST_TOC_DIV.append(self_toc)
newlist.append('cnt-%s' % self.cnt)
if isinstance(node, docutils.nodes.reference) and self.last_nav_aside_lvl and not (self.last_nav_aside_lvl in newlist):
newlist.append(self.last_nav_aside_lvl)
if isinstance(node, docutils.nodes.bullet_list):
self.ul_level += 1
if self.ul_level == 1:
node['ids'].insert(0, 'nav-aside')
else:
newlist.append('nav-aside-lvl%s' % self.ul_level)
node['classes'] = newlist
if isinstance(node, docutils.nodes.Text):
if self.ul_level > 1:
# n = docutils.nodes.inline(rawsource='', text='abc', *children, ** attributes)
newnode = span(rawsource='', text=b(node))
node.parent.children = [newnode]
## improve css classes here!
if 0 and hasattr(node, 'attributes'):
n = node
mycount = 0
while 'cur' in n.attributes.get('classes', []):
print '%03d: %s' % (mycount, n)
mycount -= 1
n = n.parent
if mycount != 0:
print
def default_departure(self, node):
"""Override for generic, uniform traversals."""
if isinstance(node, docutils.nodes.bullet_list):
self.ul_level -= 1
def unknown_visit(self, node):
"""
Called when entering unknown `Node` types.
Raise an exception unless overridden.
"""
pass
def unknown_departure(self, node):
"""
Called before exiting unknown `Node` types.
Raise exception unless overridden.
"""
pass
if toctree_for:
doc = new_document(b('<partial node>'))
doc.append(toctree_for)
# make self.t3addctx['toc'] available
# make it a visitor class variable
visitor.t3addctx = self.t3addctx
toctree_for.walkabout(visitor(doc))
if not T3StandaloneHTMLBuilder.LAST_TOC_DIV is None:
T3StandaloneHTMLBuilder.LAST_CUR_NODE.replace_self([T3StandaloneHTMLBuilder.LAST_CUR_NODE, T3StandaloneHTMLBuilder.LAST_TOC_DIV])
T3StandaloneHTMLBuilder.LAST_CUR_NODE = None
T3StandaloneHTMLBuilder.LAST_TOC_DIV = None
result = self.render_partial(toctree_for)['fragment']
else:
result = ''
return result
class T3DirectoryHTMLBuilder(T3StandaloneHTMLBuilder):
"""
A StandaloneHTMLBuilder that creates all HTML pages as "index.html" in
a directory given by their pagename, so that generated URLs don't have
``.html`` in them.
"""
name = 't3dirhtml'
def get_target_uri(self, docname, typ=None):
if docname == 'index':
return ''
if docname.endswith(SEP + 'index'):
return docname[:-5] # up to sep
return docname + SEP
def get_outfilename(self, pagename):
if pagename == 'index' or pagename.endswith(SEP + 'index'):
outfilename = path.join(self.outdir, os_path(pagename)
+ self.out_suffix)
else:
outfilename = path.join(self.outdir, os_path(pagename),
'index' + self.out_suffix)
return outfilename
def prepare_writing(self, docnames):
T3StandaloneHTMLBuilder.prepare_writing(self, docnames)
self.globalcontext['no_search_suffix'] = True
class T3SingleFileHTMLBuilder(T3StandaloneHTMLBuilder):
"""
A StandaloneHTMLBuilder subclass that puts the whole document tree on one
HTML page.
"""
name = 't3singlehtml'
copysource = False
def get_outdated_docs(self):
return 'all documents'
def get_target_uri(self, docname, typ=None):
if docname in self.env.all_docs:
# all references are on the same page...
return self.config.master_doc + self.out_suffix + \
'#document-' + docname
else:
# chances are this is a html_additional_page
return docname + self.out_suffix
def get_relative_uri(self, from_, to, typ=None):
# ignore source
return self.get_target_uri(to, typ)
def fix_refuris(self, tree):
# fix refuris with double anchor
fname = self.config.master_doc + self.out_suffix
for refnode in tree.traverse(nodes.reference):
if 'refuri' not in refnode:
continue
refuri = refnode['refuri']
hashindex = refuri.find('#')
if hashindex < 0:
continue
hashindex = refuri.find('#', hashindex+1)
if hashindex >= 0:
refnode['refuri'] = fname + refuri[hashindex:]
def assemble_doctree(self):
master = self.config.master_doc
tree = self.env.get_doctree(master)
tree = inline_all_toctrees(self, set(), master, tree, darkgreen)
tree['docname'] = master
self.env.resolve_references(tree, master, self)
self.fix_refuris(tree)
return tree
def get_doc_context(self, docname, body, metatags):
# no relation links...
toc = self.env.get_toctree_for(self.config.master_doc, self, False)
# if there is no toctree, toc is None
if toc:
self.fix_refuris(toc)
toc = self.render_partial(toc)['fragment']
display_toc = True
else:
toc = ''
display_toc = False
return dict(
parents = [],
prev = None,
next = None,
docstitle = None,
title = self.config.html_title,
meta = None,
body = body,
metatags = metatags,
rellinks = [],
sourcename = '',
toc = toc,
display_toc = display_toc,
)
def write(self, *ignored):
docnames = self.env.all_docs
self.info(bold('preparing documents... '), nonl=True)
self.prepare_writing(docnames)
self.info('done')
self.info(bold('assembling single document... '), nonl=True)
doctree = self.assemble_doctree()
self.info()
self.info(bold('writing... '), nonl=True)
self.write_doc_serialized(self.config.master_doc, doctree)
self.write_doc(self.config.master_doc, doctree)
self.info('done')
def finish(self):
# no indices or search pages are supported
self.info(bold('writing additional files...'), nonl=1)
# additional pages from conf.py
for pagename, template in self.config.html_additional_pages.items():
self.info(' '+pagename, nonl=1)
self.handle_page(pagename, {}, template)
if self.config.html_use_opensearch:
self.info(' opensearch', nonl=1)
fn = path.join(self.outdir, '_static', 'opensearch.xml')
self.handle_page('opensearch', {}, 'opensearch.xml', outfilename=fn)
self.info()
self.copy_image_files()
self.copy_download_files()
self.copy_static_files()
self.copy_extra_files()
self.write_buildinfo()
self.dump_inventory()
class T3SerializingHTMLBuilder(T3StandaloneHTMLBuilder):
"""
An abstract builder that serializes the generated HTML.
"""
#: the serializing implementation to use. Set this to a module that
#: implements a `dump`, `load`, `dumps` and `loads` functions
#: (pickle, simplejson etc.)
implementation = None
implementation_dumps_unicode = False
#: additional arguments for dump()
additional_dump_args = ()
#: the filename for the global context file
globalcontext_filename = None
supported_image_types = ['image/svg+xml', 'image/png',
'image/gif', 'image/jpeg']
def init(self):
self.config_hash = ''
self.tags_hash = ''
self.theme = None # no theme necessary
self.templates = None # no template bridge necessary
self.init_translator_class()
self.init_highlighter()
def get_target_uri(self, docname, typ=None):
if docname == 'index':
return ''
if docname.endswith(SEP + 'index'):
return docname[:-5] # up to sep
return docname + SEP
def dump_context(self, context, filename):
if self.implementation_dumps_unicode:
f = codecs.open(filename, 'w', encoding='utf-8')
else:
f = open(filename, 'wb')
try:
self.implementation.dump(context, f, *self.additional_dump_args)
finally:
f.close()
def handle_page(self, pagename, ctx, templatename='page.html',
outfilename=None, event_arg=None):
ctx['current_page_name'] = pagename
self.add_sidebars(pagename, ctx)
if not outfilename:
outfilename = path.join(self.outdir,
os_path(pagename) + self.out_suffix)
self.app.emit('html-page-context', pagename, templatename,
ctx, event_arg)
ensuredir(path.dirname(outfilename))
self.dump_context(ctx, outfilename)
# if there is a source file, copy the source file for the
# "show source" link
if ctx.get('sourcename'):
source_name = path.join(self.outdir, '_sources',
os_path(ctx['sourcename']))
ensuredir(path.dirname(source_name))
copyfile(self.env.doc2path(pagename), source_name)
def handle_finish(self):
# dump the global context
outfilename = path.join(self.outdir, self.globalcontext_filename)
self.dump_context(self.globalcontext, outfilename)
# super here to dump the search index
T3StandaloneHTMLBuilder.handle_finish(self)
# copy the environment file from the doctree dir to the output dir
# as needed by the web app
copyfile(path.join(self.doctreedir, ENV_PICKLE_FILENAME),
path.join(self.outdir, ENV_PICKLE_FILENAME))
# touch 'last build' file, used by the web application to determine
# when to reload its environment and clear the cache
open(path.join(self.outdir, LAST_BUILD_FILENAME), 'w').close()
class T3PickleHTMLBuilder(T3SerializingHTMLBuilder):
"""
A Builder that dumps the generated HTML into pickle files.
"""
implementation = pickle
implementation_dumps_unicode = False
additional_dump_args = (pickle.HIGHEST_PROTOCOL,)
indexer_format = pickle
indexer_dumps_unicode = False
name = 't3pickle'
out_suffix = '.fpickle'
globalcontext_filename = 'globalcontext.pickle'
searchindex_filename = 'searchindex.pickle'
# compatibility alias
T3WebHTMLBuilder = T3PickleHTMLBuilder
class T3JSONHTMLBuilder(T3SerializingHTMLBuilder):
"""
A builder that dumps the generated HTML into JSON files.
"""
implementation = jsonimpl
implementation_dumps_unicode = True
indexer_format = jsonimpl
indexer_dumps_unicode = True
name = 't3json'
out_suffix = '.fjson'
globalcontext_filename = 'globalcontext.json'
searchindex_filename = 'searchindex.json'
def init(self):
if jsonimpl.json is None:
raise SphinxError(
'The module simplejson (or json in Python >= 2.6) '
'is not available. The JSONHTMLBuilder builder will not work.')
T3SerializingHTMLBuilder.init(self)
<file_sep>/src/t3sphinx/ext/t3extras.py
# -*- coding: utf-8 -*-
"""
t3sphinx.ext.t3extras
~~~~~~~~~~~~~~~~~~~~~
Extending Sphinx ...
:copyright: Copyright 2012-2099 by the TYPO3 documentation team, \
see AUTHORS.
:license: BSD, see LICENSE for details.
:author: <NAME> <<EMAIL>>
"""
from t3sphinx.builders.t3htmlbuilder import T3StandaloneHTMLBuilder,\
T3DirectoryHTMLBuilder, T3SingleFileHTMLBuilder, \
T3PickleHTMLBuilder, T3JSONHTMLBuilder
def setup(app):
app.add_builder(T3StandaloneHTMLBuilder)
app.add_builder(T3DirectoryHTMLBuilder)
app.add_builder(T3SingleFileHTMLBuilder)
app.add_builder(T3PickleHTMLBuilder)
app.add_builder(T3JSONHTMLBuilder)
| f0bd2dc07689b7d75e5d5218020d5fee36c6d6bf | [
"Python",
"reStructuredText"
] | 8 | Python | marble/typo3-ExtendingSphinxForTYPO3 | 80cb349cc98e84a72f0687837e9e1afe44b5e3db | 0177a61fde08866d231655fb4cd80c8c5e41826b |
refs/heads/master | <repo_name>orgofzero/rexistum<file_sep>/kernel/page.c
#include <kernel/page.h>
#include <kernel/memory.h>
#define PAGE_DIRS_SIZE 1024
unsigned int *kernel_page_dir; //kernel page directory
unsigned int *page_dirs[PAGE_DIRS_SIZE];
/* initialize page management */
void page_init(void)
{
for(int i = 0; i < PAGE_DIRS_SIZE; i++)
{
page_dirs[i] = 0;
}
kernel_page_dir = page_alloc();
unsigned int kernel_page_table = (unsigned int)memfrag_alloc_4k(1024);
/* set directories */
for(short i = 0; i < PAGE_DIRS_SIZE; i++)
{
page_set_dir(kernel_page_dir , i, kernel_page_table + i);
}
/* set tables */
for(short table = 0; table < PAGE_DIRS_SIZE; table++)
{
for(short page = 0; page < PAGE_DIRS_SIZE; page++)
{
page_set_table(kernel_page_dir, table, page, table * 1024 + page);
}
}
page_switch(kernel_page_dir);
}
/* allocate page directory */
unsigned int* page_alloc(void)
{
for(int i = 0; i < PAGE_DIRS_SIZE; i++)
{
if(page_dirs[i] == 0)
{
page_dirs[i] = memfrag_alloc_4k(1);
return page_dirs[i];
}
}
return 0;
}
/* release page directory */
void page_free(void *page)
{
for(int i = 0; i < PAGE_DIRS_SIZE; i++)
{
if(page_dirs[i] == (unsigned int*)page)
{
memfrag_free(page);
page_dirs[i] = 0;
return;
}
}
}
/* set page */
void page_set(unsigned int *page_dir, unsigned int phy_addr_4k, unsigned int virt_addr_4k)
{
int table = virt_addr_4k / 1024;
int page = virt_addr_4k % 1024;
if(page_dir[table] == 0)
{
page_set_dir(page_dir, table, (unsigned int)memfrag_alloc_4k(1) / 4096);
}
page_set_table(page_dir, table, page, phy_addr_4k);
}
/* allock 4k memory and set page */
void* page_add(unsigned int *page_dir, unsigned int virt_addr_4k)
{
unsigned int addr = (unsigned int)memfrag_alloc_4k(1) / 4096;
int table = virt_addr_4k / 1024;
int page = virt_addr_4k % 1024;
if(page_dir[table] == 0)
{
page_set_dir(page_dir, page, (unsigned int)memfrag_alloc_4k(1) / 4096);
}
page_set_table(page_dir, table, page, addr);
return (void*)(addr * 4096);
}
/* unset page */
void page_unset(unsigned int *page_dir, unsigned int virt_addr_4k)
{
int table = virt_addr_4k / 1024;
int page = virt_addr_4k % 1024;
unsigned int *page_table = (unsigned int*)page_dir[table];
memfrag_free((void*)page_table[page]);
page_table[page] = 0;
}
/* reload page table */
void page_reload(void)
{
page_disable();
page_enable();
}
/* switch page table */
void page_switch(void *page_dir)
{
page_disable();
set_cr3(page_dir);
page_enable();
}
<file_sep>/include/kernel/fs/inode.h
#define TYPE_AVAILABLE 0
#define TYPE_FILE 1
#define TYPE_DIRECTOR 2
#define INODE_TABLE_SIZE sizeof(struct inode)
#define INODE_NUM (4096 / INODE_TABLE_SIZE)
/* inode数据 */
struct inode
{
char name[16]; //inode(文件)名
int parent_inode;
int index_block; //索引块编号
int size;
int type; //inode类型
};
extern struct inode inode_list[INODE_NUM];
extern int inode_count;
int inode_get_available(void);
void inode_load(void);
void inode_save(void);<file_sep>/include/kernel/fifo.h
struct fifo8
{
void* addr; //缓冲区地址
int size; //缓冲区大小
int free; //缓冲区可用空间
int write, read; //数据读写位置
};
void fifo_init(struct fifo8*, void*, int);
int fifo_get_info(struct fifo8);
void fifo_write_data(struct fifo8*, char);
char fifo_read_data(struct fifo8*);<file_sep>/include/kernel/task.h
#include <arch/x86/task.h>
#define TASKS_MAX 1024
#define UNIT_TIME 100
#define TASK_AVAILABLE 0
#define TASK_PENDING 1
#define TASK_RUNNING 2
#define TASK_SLEEPING 3
#define TASK_DEFAULT_PRIORITY 0
#define TASK_NICE_MAX 19
#define TASK_NICE_MIN -20
#define TASK_IDLE_PID 0
#define TASK_INIT_PID 1
#define TASK_CODE_ADDR (1 * 1024 * 1024 * 1024)
#define KERNEL_CODE_ADDR 0x100000
#define KERNEL_CODE_SIZE (1 * 1024 * 1024) //1MB
#define MAX_PID 0x400000
/* 任务初始化信息,释放任务时需要 */
struct task_init_info
{
void *stack_addr;
void *code_addr;
};
struct task_info
{
struct task_init_info init_info;
struct task_state state; //任务状态
unsigned int *page;
char name[30]; //任务名称
int pid, ppid, uid;
int nice;
int flags;
int cpu_time; //1s中需要运行的时间
unsigned int cpu_count;
};
struct task_priority
{
struct task_info *task_list[1024];
int pointer;
};
extern struct task_info task_list[TASKS_MAX];
extern int current_pid;
void task_init(void);
void task_priority_init(void);
void task_init_register(struct task_state*);
int task_get_next_proc(void);
void task_switch(void);
int task_alloc(void*);
void task_run(int);
void task_kill(int);
void task_wait(int);
void task_sleep(int);
void task_wakeup(int);
void task_set_name(int, char*);
void task_get_name(char*, int);
int task_get_pid(void);
int task_get_uid(int);
int task_get_ppid(int);
int task_get_list(int*);
void task_set_nice(int, int);
void scheduler_add(struct task_info*);
void scheduler_remove(struct task_info*);
<file_sep>/arch/x86/kernel/error_int.c
#include <kernel/strfmt.h>
/* #DE: 除零错误 */
void interrupt00h(void)
{
printfmt("kernel panic: int00: division exception\n");
}
/* #OF: 溢出 */
void interrupt04h(void)
{
printfmt("kernel panic: int04: overflow\n");
}
/* #UD: 无效指令 */
void interrupt06h(void)
{
printfmt("kernel panic: int06: undefined code\n");
}
/* #DF: 双重错误 */
void interrupt08h(void)
{
printfmt("kernel panic: int08: double fault\n");
}
/* #SS: 堆栈段异常 */
void interrupt0ch(void)
{
printfmt("kernel panic: int0c: stack segfault\n");
}
/* #GP: 通用保护异常 */
void interrupt0dh(void)
{
printfmt("kernel panic: int0d: general protection exception\n");
}
/* #PF: 页错误 */
void interrupt0eh(void)
{
printfmt("kernel panic: int0e: page fault\n");
}
<file_sep>/device/input/keyboard.c
#include <kernel/fifo.h>
#include <device/video/cli_print.h>
#include <device/input/keyboard.h>
struct fifo8 key_fifo;
char key_caps = KEY_UP; //1未按下, 2按下
char key_shift = KEY_UP; //1未按下, 2按下
char keyboard_set[] = {' ', ' ', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '-', '=', 0x0e, ' ', 'q', 'w', 'e', 'r',
't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', ' ',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';',
'\'', '`', 0, '\\', 'z', 'x', 'c', 'v', 'b', 'n',
'm', ',', '.', '/', 0, ' ', ' ', ' ', 0, ' '};
char keyboard_set_shift[] = {' ', ' ', '!', '@', '#', '$', '%', '^', '&', '*',
'(', ')', '_', '+', 0x0e, ' ', 'Q', 'W', 'E', 'R',
'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n', ' ',
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':',
'"', '~', 0, '|', 'Z', 'X', 'C', 'V', 'B', 'N',
'M', '<', '>', '?', 0, ' ', ' ', ' ', 0, ' '};
/* 输入字符串 */
int input(char *str)
{
int i = 0;
while(1)
{
char data = input_char();
if(data == 0)
{
continue;
}
/* 退格键的处理 */
if(data == 0x0e)
{
if(i == 0)
{
continue; //str长度为0
}
cli_print_char(0x0e);
i -= 1; //删除上一个字符
continue; //仅打印不写入退格符
}
str[i] = data;
cli_print_char(data);
if(data == '\n')
{
break;
}
i += 1;
}
str[i] = '\0';
return i; //返回输入数据大小
}
/* 单字符输入 */
char input_char(void)
{
while(1)
{
if(fifo_get_info(key_fifo) != 0)
{
unsigned char data = fifo_read_data(&key_fifo);
/* 按键抬起 */
if(data > 0x7f)
{
continue;
}
if(key_shift == KEY_UP)
{
char c = keyboard_set[(int)data];
/* caps lock且输入是字母 */
if(key_caps == KEY_DOWN && c >= 0x61 && c <= 0x7a)
{
return c - 32;
}
return c;
}
else if(key_shift == KEY_DOWN)
{
char c = keyboard_set_shift[(int)data];
/* caps lock且输入是字母 */
if(key_caps == KEY_DOWN && c >= 0x41 && c <= 0x5a)
{
return c + 32;
}
return c;
}
}
}
}
/* 获取一个输入按键的键码 */
unsigned char input_code()
{
while(1)
{
if(fifo_get_info(key_fifo) != 0)
{
unsigned char data = fifo_read_data(&key_fifo);
return data;
}
}
}
<file_sep>/lib/Makefile
kernel_objs += lib/string.o lib/types.o lib/args.o<file_sep>/kernel/fs/dir.c
#include <kernel/fs/fs.h>
#include <kernel/fs/inode.h>
#include <kernel/fs/path.h>
#include <lib/string.h>
/* 创建文件夹 */
int dir_create(char *path)
{
/* 避免重复创建根目录 */
if(!str_cmp(path, "/") && is_fs())
{
return FS_FAILED;
}
ST_FILE dir;
if(file_create(&dir, path) == FS_FAILED)
{
return FS_FAILED;
}
inode_list[dir.inode].type = TYPE_DIRECTOR; //类型更改为文件夹
inode_save();
return FS_SUCCESS;
}
/* 列出子目录及文件inode */
int dir_list_inode(int *ret, char *path)
{
int inode = path_get_inode(path);
int count = 0;
for(int i = 1; i < inode_count; i++)
{
if(inode_list[i].parent_inode == inode && inode_list[i].type != TYPE_AVAILABLE)
{
ret[count] = i;
count += 1;
}
}
return count;
}<file_sep>/kernel/fs/fs.c
#include <kernel/fs/block.h>
/* 检测磁盘上有没有没有文件系统 */
int is_fs(void)
{
if(sblock.fs_header[0] != 0x31 ||
sblock.fs_header[1] != 0x22 ||
sblock.fs_header[2] != 0x33 ||
sblock.fs_header[3] != 0x31)
{
return 0;
}
return 1;
}<file_sep>/device/disk/disk.c
#include <arch/x86/cpu.h>
#include <kernel/time.h>
/* LBA读取磁盘 */
void lba28_read(short *buf, unsigned int offset, unsigned char count)
{
io_out8(0x1f2, count);
io_out8(0x1f3, offset & 0xff);
io_out8(0x1f4, (offset & 0xff00) >> 8);
io_out8(0x1f5, (offset & 0xff0000) >> (2 * 8));
io_out8(0x1f6, (offset >> 3 * 8 & 0x0f) | 0xe0);
io_out8(0x1f7, 0x20); //读取磁盘
int i = 0;
for(; i < count * 512 / 2; i++)
{
/* 等待磁盘驱动器 */
while(!(io_in8(0x1f7) & 0x40));
buf[i] = io_in16(0x1f0);
}
}
/* LBA写入磁盘 */
void lba28_write(short *data, unsigned int offset, unsigned char count)
{
io_out8(0x1f2, count);
io_out8(0x1f3, offset & 0xff);
io_out8(0x1f4, (offset & 0xff00) >> 8);
io_out8(0x1f5, (offset & 0xff0000) >> (2 * 8));
io_out8(0x1f6, (offset >> 3 * 8 & 0x0f) | 0xe0);
io_out8(0x1f7, 0x30); //写入磁盘
int i = 0;
for(; i < count * 512 / 2; i++)
{
/* 等待磁盘驱动器 */
while(!(io_in8(0x1f7) & 0x40));
io_out16(0x1f0, data[i]);
}
}<file_sep>/arch/x86/kernel/task.c
#include <arch/x86/task.h>
/* 初始化寄存器 */
void task_init_register(struct task_state *state)
{
state->eax = 0;
state->ebx = 0;
state->ecx = 0;
state->edx = 0;
state->esi = 0;
state->edi = 0;
state->ebp = 0;
}
/* 设置任务栈地址 */
void task_set_stack(struct task_state *state, void *addr)
{
state->esp = (unsigned int)addr;
}
<file_sep>/include/kernel/random.h
void random_init(void);
unsigned int random(void);<file_sep>/lib/string.c
/* 获取字符串大小 */
int str_len(char *str)
{
int i = 0;
while(str[i] != '\0')
{
i += 1;
}
return i;
}
/* 比较字符串 */
int str_cmp(char *a, char *b)
{
if(str_len(a) != str_len(b))
{
return -1;
}
int i = 0;
while(a[i] != '\0')
{
if(a[i] != b[i])
{
return -1;
}
i += 1;
}
return 0;
}
/* 复制字符串 */
void str_cpy(char *a, char *b)
{
int i = 0;
while(b[i] != '\0')
{
a[i] = b[i];
i += 1;
}
a[i] = '\0';
}
/* 拼接字符串 */
void str_cat(char *a, char *b)
{
int i = str_len(a);
int j = 0;
while(b[j] != '\0')
{
a[i] = b[j];
i += 1;
j += 1;
}
a[i] = '\0';
}
/* 查找字符串 */
int str_find(char *origin, char *str, int index)
{
int size = str_len(origin) - str_len(str);
for(int i = 0; i <= size; i++)
{
/* 测试origin[i]处是否匹配str */
int j = 0;
while(str[j] != '\0')
{
if(origin[i + j] != str[j])
{
break;
}
j += 1;
}
/* origin[i]处匹配str */
if(j == str_len(str))
{
index -= 1;
}
if(index == -1)
{
return i; //返回字符串位置
}
}
return -1;
}
/* 统计字符串中出现字符串次数 */
int str_count(char *origin, char *str)
{
int count = 0;
int len = str_len(str);
while(1)
{
int i = str_find(origin, str, 0);
if(i == -1)
{
break;
}
count += 1;
origin += len + i;
}
return count;
}
/* 分割字符串 */
void str_split(char *ret, char *str, char *symbol, int index)
{
int start = 0;
/* 获取原字符串开始位置 */
if(index != 0)
{
start = str_find(str, symbol, index - 1) + str_len(symbol);
}
int end = str_find(str, symbol, index); //获取原字符串结束位置
if(end == -1)
{
end = str_len(str);
}
int i = 0;
/* 复制字符串 */
while(start < end)
{
ret[i] = str[start];
start += 1;
i += 1;
}
ret[i] = '\0'; //字符串结尾标志
}
/* 字符串切片 */
void str_slice(char *ret, char *src, int start, int end)
{
char str[100];
str_cpy(str, src);
str[end + 1] = '\0';
str_cpy(ret, str + start);
}
/* 替换字符串 */
void str_replace(char *str, char *a, char *b)
{
int len_a = str_len(a);
int len_b = str_len(b);
char bak[100];
while(1)
{
int i = str_find(str, a, 0);
if(i == -1)
{
break;
}
str_cpy(bak, str + len_a + i);
str_cpy(str + i, b);
str_cat(str, bak);
str += len_b + i;
}
}
<file_sep>/tools/edimg/disk.c
#include <stdio.h>
char image_file[50];
void lba28_read(char *buf, unsigned int offset, unsigned char count)
{
FILE *fp = fopen(image_file, "r");
fseek(fp, offset * 512, 0);
for(int i = 0; i < count * 512; i++)
{
buf[i] = fgetc(fp);
}
fclose(fp);
}
void lba28_write(char *data, unsigned int offset, unsigned char count)
{
FILE *fp = fopen(image_file, "a+");
fseek(fp, offset * 512, 0);
for(int i = 0; i < count * 512; i++)
{
fputc(data[i], fp);
}
fclose(fp);
}<file_sep>/kernel/sysinfo.c
#include <kernel/sysinfo.h>
struct sysinfo sysinfo;
void sysinfo_init(void)
{
sysinfo.mem_size = 0;
sysinfo.mem_free = 0;
}<file_sep>/include/kernel/memory.h
/* 用来记录一个内存碎片 */
struct mem_fragment
{
void *addr;
unsigned int size;
};
void memfrag_init(void);
void* mem_get_size(void);
void* memfrag_alloc(unsigned int);
void* memfrag_alloc_4k(unsigned int);
void memfrag_alloc_with_addr(void*, unsigned int);
void memfrag_free(void*);
void* mem_get_free_size(void);
<file_sep>/device/video/Makefile
kernel_objs += device/video/cli_print.o device/video/cursor.o<file_sep>/include/lib/types.h
void uint2str(char*, unsigned int);
void int2str(char*, int);
int str2uint(char*);
int str2int(char*);<file_sep>/device/interrupt/timer.c
#include <arch/x86/cpu.h>
#include <kernel/task.h>
unsigned int time_count = 0;/* 记录经过的时间,10ms */
unsigned int timer_list[1000];
int timer_num = 0;
void interrupt20h(void)
{
io_out8(0x20, 0x60); //通知PIC已经发生中断
time_count += 1;
task_switch();
io_cli(); //iretd之前要禁用中断
}
<file_sep>/tools/edimg/edimg.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <kernel/fs/fs.h>
#define IMAGE argv[1]
#define OPTION argv[2]
#define ARG1 argv[3]
#define ARG2 argv[4]
extern char image_file[50];
static int get_file_size(char *file)
{
struct stat statbuf;
stat(file, &statbuf);
return statbuf.st_size;
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("edimg tool version 0.1\n");
printf("usage:\n");
printf("edimg <image> <option> <args>...\n");
printf("options:\n\
create\tCreate a file-system.\n\
write\tWrite a file into image.\n");
exit(0);
}
strcpy(image_file, IMAGE);
fs_init();
ST_FILE file;
FILE *fp;
if(!strcmp(OPTION, "create"))
{
fs_create();
}
/* 写入文件 */
else if(!strcmp(OPTION, "write"))
{
file_create(&file, ARG2);
int size = get_file_size(ARG1);
fp = fopen(ARG1, "r");
char *data = malloc(size);
for(int i = 0; i < size; i++)
{
data[i] = fgetc(fp);
}
file_write(&file, data, size);
fclose(fp);
}
/* 读取文件 */
else if(!strcmp(OPTION, "read"))
{
if(file_open(&file, ARG1) == FS_FAILED)
{
printf("edimg: unable to open '%s'.\n", ARG1);
return -1;
}
fp = fopen(ARG2, "w");
int size = file_get_size(file);
char *data = malloc(size);
file_read(&file, data, 0);
for(int i = 0; i < size; i++)
{
fputc(data[i], fp);
}
fclose(fp);
}
else
{
printf("edimg: %s: unkown option.\n", OPTION);
}
return 0;
}<file_sep>/config/sources.mk
#存放源代码目录及子目录
include init/Makefile
include lib/Makefile
include kernel/Makefile
include device/Makefile
include $(ARCH_DIR)/kernel/Makefile
<file_sep>/kernel/fs/file.c
#include <kernel/fs/fs.h>
#include <kernel/fs/bitmap.h>
#include <kernel/fs/inode.h>
#include <kernel/fs/block.h>
#include <kernel/fs/path.h>
#include <lib/string.h>
#include <kernel/memory.h>
/* 创建文件 */
int file_create(ST_FILE *file, char *name)
{
char dirname[50];
path_get_dirname(dirname, name);
/* 文件已存在 */
if(path_exist(name) && str_cmp(name, "/"))
{
return FS_FAILED;
}
/* 父级目录不存在 */
else if(!path_exist(dirname))
{
return FS_FAILED;
}
int inode = inode_get_available();
/* 未找到未使用的块 */
if(inode == -1)
{
return FS_FAILED;
}
/* 为文件分配块索引 */
for(int i = DATA_BLOCK_BEGIN; i < 1024; i++)
{
/* 找到未使用的块 */
if(!bitmap_get_used(i))
{
bitmap_set_used(i); //标记块为已用
bitmap_save();
inode_list[inode].index_block = i; //当前索引块编号保存到inode
block_cleanup(i); //清除索引块数据
break;
}
}
inode_list[inode].parent_inode = path_get_inode(dirname);
inode_list[inode].type = TYPE_FILE;
path_get_basename(inode_list[inode].name, name);
inode_save(); //保存inode索引
file->inode = inode;
file->seek = 0;
return FS_SUCCESS;
}
/* 获取文件大小 */
int file_get_size(ST_FILE file)
{
return inode_list[file.inode].size;
}
/* 打开文件 */
int file_open(ST_FILE *file, char *path)
{
/* 文件不存在 */
if(!path_exist(path))
{
return FS_FAILED;
}
int i = 0;
char dirname[50], basename[50];
path_get_basename(basename, path);
path_get_dirname(dirname, path);
int parent_inode = path_get_inode(dirname);
for(; i < inode_count; i++)
{
/* 此inode未被分配 */
if(inode_list[i].type == TYPE_AVAILABLE)
{
continue;
}
else if(!str_cmp(inode_list[i].name, basename))
{
if(inode_list[i].parent_inode != parent_inode)
{
continue;
}
file->inode = i;
file->seek = 0;
return FS_SUCCESS;
}
}
return FS_FAILED;
}
/* 写入文件 */
void file_write(ST_FILE *file, char *data, int size)
{
int *index_data = memfrag_alloc_4k(1);
block_load(inode_list[file->inode].index_block, index_data); //获取此inode中的索引块数据
int i = 1;
/* 释放此inode占用的数据块 */
for(; i < 1024; i++)
{
if(index_data[i] != 0)
{
bitmap_set_unused(i); //标记块为未用
index_data[i] = 0;
}
}
bitmap_save();
block_cleanup(inode_list[file->inode].index_block); //清除引导块
/* end = 写入数据块数 */
int end = size / 4096;
if(size % 4096 != 0)
{
end += 1;
}
char *data_block = memfrag_alloc_4k(1);
int data_w = 0; //用于访问data位置
int w = 0;
int index_block = inode_list[file->inode].index_block; //当前引导块编号
/* 循环写入使用数据 */
for(i = 1; i < end + 1; i++)
{
int j = DATA_BLOCK_BEGIN;
if(i == 1024)
{
/* 分配下一个引导块 */
for(; j < 1024; j++)
{
/* 找到未使用的块 */
if(bitmap_get_used(j) == 0)
{
bitmap_set_used(j);
bitmap_save();
block_cleanup(j); //清除此数据块数据
break;
}
}
/* index_data[0]记录了下一个索引块编号, 为0则没有下一个 */
index_data[0] = j;
block_save(index_block, index_data); //保存当前索引块
index_block = j;
index_data[0] = 0;
end -= 1024 - 1;
i = 1;
}
/* 分配一个用于存数据的块 */
for(; j < 1024; j++)
{
/* 找到未使用的块 */
if(!bitmap_get_used(j))
{
bitmap_set_used(j);
bitmap_save();
block_cleanup(j); //清除此数据块数据
break;
}
}
index_data[i] = j;
w = 0;
/* 将4 kb数据写入当前块 */
for(j = 0; j < 4096; j++)
{
data_block[w] = data[data_w];
w += 1;
data_w += 1;
/* 已写入所有数据 */
if(data_w == size)
{
inode_list[file->inode].size = size;
block_save(index_data[i], data_block); //保存当前块数据
block_save(index_block, index_data); //保存索引块
inode_save(); //保存inode
memfrag_free(data_block);
memfrag_free(index_data);
return;
}
}
block_save(index_data[i], data_block); //保存当前块数据
}
}
/* 读取文件 */
int file_read(ST_FILE *file, char *data, int size)
{
if(size == 0)
{
size = file_get_size(*file);
}
int *index_data = memfrag_alloc_4k(1);
char *data_block = memfrag_alloc_4k(1);
block_load(inode_list[file->inode].index_block, index_data); //加载块索引
int i = 1;
int data_r = 0;
int r;
for(; i <= 1024; i++)
{
/* 加载下一个引导块 */
if(i == 1024 && index_data[0] != 0)
{
block_load(index_data[0], index_data); //加载下一个引导块
i = 1;
}
else if(i == 1024)
{
break;
}
/* 数据块未使用 */
if(index_data[i] == 0)
{
continue;
}
block_load(index_data[i], data_block); //加载数据块
int j = 0;
r = 0;
/* 读取4 kb数据 */
for(; j < 4096; j++)
{
data[data_r] = data_block[r];
data_r += 1;
r += 1;
/* 已读取所有数据 */
if(data_r == size)
{
memfrag_free(data_block);
memfrag_free(index_data);
return size;
}
}
}
return 0;
}
/* 删除文件 */
void file_remove(char *filename)
{
struct file file;
/* 文件不存在 */
if(file_open(&file, filename) == FS_FAILED)
{
return;
}
int *index_data = memfrag_alloc_4k(1);
block_load(inode_list[file.inode].index_block, index_data); //获取此inode中的索引块数据
int i = 1;
int index_block = inode_list[file.inode].index_block;
/* 释放此inode占用的数据块 */
for(; i <= 1024; i++)
{
/* 加载下一个引导块 */
if(i == 1024 && index_data[0] != 0)
{
block_load(index_data[0], index_data); //加载下一个引导块
bitmap_set_unused(index_block);
index_block = index_data[0];
i = 1;
}
else if(i == 1024)
{
break;
}
if(index_data[i] != 0)
{
bitmap_set_unused(i); //标记块为未用
index_data[i] = 0;
}
}
bitmap_set_unused(index_block);
bitmap_save();
inode_list[file.inode].type = TYPE_AVAILABLE; //此unode标记为未用
inode_save(); //保存inode
memfrag_free(index_data);
}
/* 通过inode获取文件名 */
void file_get_name_by_inode(char *ret, int inode)
{
str_cpy(ret, inode_list[inode].name);
}<file_sep>/kernel/pipe.c
#include <kernel/pipe.h>
#include <kernel/memory.h>
#include <kernel/task.h>
int pipe_count = 0; //pipe数量
struct pipe *pipe_list[1024];
/* allocate a pipe */
void pipe_create(struct pipe *pipe, int target_pid)
{
fifo_init(&pipe->fifo, memfrag_alloc(1024), 1024);
pipe->target_pid = target_pid;
pipe_list[pipe_count] = pipe;
pipe_count += 1;
}
/* get pipe */
int pipe_get(struct pipe **pipe)
{
for(int i = 0; i < pipe_count; i++)
{
if(task_get_pid() == pipe_list[i]->target_pid)
{
*pipe = pipe_list[i];
return 0;
}
}
return -1;
}
/* write to pipe */
int pipe_write(struct pipe *pipe, char *data, int size)
{
for(int i = 0; i < size; i++)
{
fifo_write_data(&pipe->fifo, data[i]);
}
return size;
}
/* read from pipe */
int pipe_read(struct pipe *pipe, char* data, int size)
{
for(int i = 0; i < size; i++)
{
if(fifo_get_info(pipe->fifo) == 0)
{
return i;
}
data[i] = fifo_read_data(&pipe->fifo);
}
return size;
}
/* close pipe */
void pipe_close(struct pipe *pipe)
{
for(int i = 0; i < pipe_count; i++)
{
if(pipe_list[i] == pipe)
{
for(; i < pipe_count - 1; i++)
{
pipe_list[i] = pipe_list[i + 1];
}
pipe_count -= 1;
return;
}
}
}
<file_sep>/include/device/disk/disk.h
void lba28_read(short*, int, unsigned char);
void lba28_write(short*, int, unsigned char);<file_sep>/include/arch/x86/task.h
struct task_state
{
unsigned int esp, ebp; //栈指针
unsigned int eax, ebx, ecx, edx; //通用寄存器
unsigned int esi, edi; //目标寄存器
};
void asm_task_switch(struct task_state*, struct task_state*);
void task_set_stack(struct task_state*, void*);
<file_sep>/init/shell.c
#include <version.h>
#include <kernel/fs/fs.h>
#include <kernel/task.h>
#include <kernel/user.h>
#include <kernel/memory.h>
#include <lib/string.h>
#include <lib/types.h>
#include <kernel/strfmt.h>
#include <device/video/cli_print.h>
#include <device/input/keyboard.h>
void shell(void)
{
char user[20];
user_get_name(user, task_get_uid(task_get_pid()));
for(;;)
{
int i = 0;
printfmt("[%s /] ", user);
char inp[21],cmd[11];
char dirname[20];
input(inp);
str_split(cmd, inp, " ", 0);
/* 显示内核版本 */
if(!str_cmp(cmd, "rever"))
{
printfmt("%s %s\n", KERNEL_NAME, KERNEL_VERSION);
}
/* 打印任务 */
else if(!str_cmp(cmd, "ps"))
{
int pids[1024];
int i = task_get_list(pids);
int j = 0;
cli_print("PID PPID UID Name\n");
for(; j < i; j++)
{
char name[11];
int ppid = task_get_ppid(pids[j]);
int uid = task_get_uid(pids[j]);
task_get_name(name, j);
printfmt("%d %d %d %s\n", pids[j], ppid, uid, name);
}
}
/* 杀死任务 */
else if(!str_cmp(cmd, "kill"))
{
char strpid[5];
str_split(strpid, inp, " ", 1);
int pid = str2uint(strpid);
task_kill(pid);
}
/* 打印子目录及文件 */
else if(!str_cmp(cmd, "ls"))
{
int inode_list[20];
str_split(dirname, inp, " ", 1);
int count = dir_list_inode(inode_list, dirname);
for(i = 0; i < count; i++)
{
file_get_name_by_inode(dirname, inode_list[i]);
printfmt("%s\n", dirname);
}
}
/* 创建文件夹 */
else if(!str_cmp(cmd, "mkdir"))
{
str_split(dirname, inp, " ", 1);
dir_create(dirname);
}
/* 显示文件内容 */
else if(!str_cmp(cmd, "cat"))
{
ST_FILE fp;
char filename[10];
char data[1024];
str_cpy(data, "");
str_split(filename, inp, " ", 1);
if(file_open(&fp, filename) == -1)
{
printfmt("%s: no such file.\n", filename);
continue;
}
int size = file_read(&fp, data, 0);
for(i = 0; i < size; i++)
{
cli_print_char(data[i]);
}
}
/* 删除文件 */
else if(!str_cmp(cmd, "rm"))
{
char filename[10];
str_split(filename, inp, " ", 1);
file_remove(filename);
}
/* 打印内存使用情况 */
else if(!str_cmp(cmd, "mem"))
{
unsigned int size = (unsigned int)mem_get_size() / 1024;
printfmt("Total: %d KB\n", size);
size = (unsigned int)mem_get_free_size() / 1024;
printfmt("Free: %d KB\n", size);
}
else if(str_cmp(cmd, ""))
{
printfmt("%s: unkown command.\n", cmd);
}
}
}<file_sep>/doc/PM.md
### 1.简介
保护模式(Protect Mode)下可以访问4GB的内存,并且CPU会对可疑指令进行屏蔽.
### 2.切换到保护模式
* 加载GDTR寄存器.
* 启用A20
* cr0寄存器的PE为置1
* far jump以刷新管道
#### 2.1 启用A20
只需将`0x92端口`的第1位置1即可.
#### 2.2 cr0寄存器的PE为置1
cr0寄存器不能直接赋值,所以先将cr0的值移到通用寄存器中,在将第0位(PE位)置1即可.<file_sep>/include/kernel/strfmt.h
void printfmt(char*, ...);
void strfmt(char*, char*, ...);<file_sep>/init/main.c
#include <arch/x86/cpu.h>
#include <kernel/init.h>
#include <kernel/task.h>
#include <kernel/fs/fs.h>
void shell(void);
int main(void)
{
kernel_init(); //初始化内核
fs_create();
fs_init();
int pid = task_alloc(shell);
task_set_name(pid, "shell");
task_run(pid);
task_set_nice(TASK_IDLE_PID, TASK_NICE_MAX);
while(1)
{
cpu_halt();
}
}
<file_sep>/include/kernel/fs/dir.h
int dir_create(char*);
int dir_list_inode(int*, char*);<file_sep>/include/kernel/time.h
struct local_time
{
int Y, m, d; //year, month, day
int H, M, S; //hour, minute, second
};
/* 64-bit time stamp */
struct time_stamp
{
int ts_low, ts_hight;
};
typedef struct time_stamp TIME_STAMP;
typedef struct local_time LOCAL_TIME;
void delay(unsigned int);
void time_local_time(struct local_time*);
void time_get_stamp(struct time_stamp*, struct local_time);<file_sep>/kernel/fs/path.c
#include <kernel/fs/inode.h>
#include <kernel/fs/path.h>
#include <lib/string.h>
/* 获取路径基名称 */
void path_get_basename(char *ret, char *path)
{
char tmp_path[50];
str_cpy(tmp_path, path);
str_split(ret, path, "/", str_count(path, "/"));
}
/* 获取父目录名称 */
void path_get_dirname(char *ret, char *path)
{
char tmp_path[50];
str_cpy(tmp_path, path);
tmp_path[str_find(path, "/", str_count(path, "/") - 1)] = '\0';
str_cpy(ret, tmp_path);
if(ret[0] == '\0')
{
str_cpy(ret, "/");
}
}
/* 通过路径获取文件inode编号 */
int path_get_inode(char *path)
{
if(!str_cmp(path, "/"))
{
return 0;
}
if(path_exist(path) == 0)
{
return -1;
}
char now_name[20];
int times = 0;
int i = 0;
int now = 0;
for(; times < str_count(path, "/"); times++)
{
str_split(now_name, path, "/", times + 1); //获取目录名
for(i = 1; i < inode_count; i++)
{
if(!str_cmp(inode_list[i].name, now_name))
{
if(inode_list[i].parent_inode == now)
{
now = i;
}
}
}
}
return now;
}
/* 检查路径是否存在 */
int path_exist(char *path)
{
if(!str_cmp(path, "/"))
{
return 1;
}
char now_name[20];
int now = 0;
for(int times = 0; times < str_count(path, "/"); times++)
{
str_split(now_name, path, "/", times + 1); //获取目录名
for(int i = 1; i < inode_count; i++)
{
if(!str_cmp(inode_list[i].name, now_name) && inode_list[i].parent_inode == now)
{
/* 存在 */
if(inode_list[i].type != TYPE_AVAILABLE)
{
if(times == str_count(path, "/") - 1)
{
return 1;
}
now = i;
}
}
}
}
return 0;
}<file_sep>/include/kernel/fs/block.h
#define SUPER_BLOCK 1
#define DATA_BLOCK_BEGIN 3
/* 超级块数据 */
struct super_block
{
unsigned char fs_header[4]; //文件系统标识
unsigned int bitmap_block; //bitmap块编号
unsigned int inode_table[1024 - 2]; //inode块编号
};
extern struct super_block sblock;
void super_block_load(void);
void super_block_save(void);
int super_block_get_index(void);
void block_load(unsigned int, void*);
void block_save(unsigned int, void*);
void block_cleanup(unsigned int);
int block_create(void);<file_sep>/device/interrupt/init.c
#include <arch/x86/cpu.h>
#include <device/interrupt/init.h>
/* 初始化PIC */
void PIC_init(void)
{
io_out8(0x21, 0xff); //禁止所有中断
io_out8(0xa1, 0xff); //禁止所有中断
/* 下面初始化PIC0 */
io_out8(0x20, 0x11); //边沿触发模式
io_out8(0x21, 0x20); //IRQ0-7由INT20-27接收
io_out8(0x21, 1 << 2); //PIC1由IRQ2连接
io_out8(0x21, 0x01); //无缓冲区模式
/* 下面初始化PIC1 */
io_out8(0xa0, 0x11); //边沿触发模式
io_out8(0xa1, 0x28); //IRQ8-15由INT28-2f接收
io_out8(0xa1, 2); //PIC1由IRQ2连接
io_out8(0xa1, 0x01); //无缓冲区模式
io_out8(0x21, 0xfc); //重新启用中断
io_out8(0xa1, 0xff);
PIT_init();
}
#define HZ 100
#define CLOCK_TICK_RATE 1193180 //发生中断次数
void PIT_init(void)
{
io_out8(0x43, 0x34);
/* 设定值=1193180/频率 */
io_out8(0x40, 0xff & (CLOCK_TICK_RATE / HZ)); //每10ms产生一次中断
io_out8(0x40, (CLOCK_TICK_RATE / HZ) >> 8);
}<file_sep>/include/device/input/keyboard.h
#define KEY_UP 1
#define KEY_DOWN 2
extern struct fifo8 key_fifo;
extern char key_caps;
extern char key_shift;
int input(char*);
char input_char(void);
unsigned char input_code(void);
<file_sep>/doc/LBA28.md
### 1.简介
LBA28可以识别小于137GB的硬盘.
### 2.使用
|端口号|作用|
|:---:|:---:|
|0x1f2|操作的扇区数|
|0x1f3|LBA 0~7位|
|0x1f4|LBA 8~15位|
|0x1f5|LBA 16~23位|
|0x1f6|LBA 24~27位|
|0x1f7|0x20: 读盘<br>0x30: 写盘|
然后可以通过读取(写入)`0x1f0端口`读取2字节数据,直到读取(写入)完所有数据.<file_sep>/device/interrupt/keyboard.c
#include <arch/x86/cpu.h>
#include <kernel/fifo.h>
#include <device/input/keyboard.h>
/* 键盘中断程序 */
void interrupt21h(void)
{
io_out8(0x20, 0x61); //通知PIC已经发生中断
unsigned char data = io_in8(0x60); //读取键盘数据
/* shift抬起 */
if(data == 0xaa || data == 0xb6)
{
key_shift = KEY_UP;
}
/* shift按下 */
else if(data == 0x2a || data == 0x36)
{
key_shift = KEY_DOWN;
}
/* caps按下 */
else if(data == 0xba)
{
if(key_caps == KEY_UP)
{
key_caps = KEY_DOWN;
}
else if(key_caps == KEY_DOWN)
{
key_caps = KEY_UP;
}
}
fifo_write_data(&key_fifo, data); //将数据写入缓冲区
}<file_sep>/doc/C Language.md
### 1.调用
当C语言调用一个函数时,会将函数返回时的地址压如栈(即[esp]),函数返回时会将eax的值作为返回值.
函数参数:第一个参数[esp+8],第二个[esp+8],以此类推...
### 2.局部变量
C语言的局部变量存储在栈中,栈地址由esp寄存器存储.<file_sep>/init/Makefile
kernel_objs += init/main.o init/shell.o<file_sep>/include/kernel/timer.h
int timer_alloc(void);
int timer_get_time(int);
void timer_free(int);<file_sep>/Makefile
include config/arch.mk
include config/sources.mk
include config/toolchain.mk
include config/env.mk
all:
@$(MAKE) -s -C $(ARCH_DIR)/boot
@$(MAKE) -s kernel.bin
@$(MAKE) -s image
#系统内核文件
kernel.sys:$(kernel_bins) $(kernel_objs)
@echo "LD kernel.sys"
@$(LD) $(LD_FLAGS) $(kernel_bins) $(kernel_objs) -o kernel.sys
kernel.bin:kernel.sys
objcopy -S -O binary kernel.sys kernel.bin
%.bin:%.S
@echo "AS $@"
@$(AS) $*.S --32 -o $*.bin
%.o:%.c
@echo "CC $@"
@$(CC) $(C_FLAGS) -c $*.c -o $*.o
#内核镜像
image:
@echo "DD hda.img"
dd if=$(ARCH_DIR)/boot/boot.bin of=hda.img bs=512 count=1
dd if=$(ARCH_DIR)/boot/loader.bin of=hda.img bs=512 seek=1 count=8
dd if=kernel.bin of=hda.img bs=512 seek=9 count=10240
qemu-img resize hda.img 10M
#运行
run:
@$(MAKE) -s all
@$(QEMU) -drive file=hda.img,format=raw -serial stdio
#清理生成的文件
clean:
rm $(kernel_bins) $(kernel_objs)
rm kernel.sys
rm kernel.bin
$(MAKE) -s -C $(ARCH_DIR)/boot clean
rm hda.img
<file_sep>/include/kernel/pipe.h
#include <kernel/fifo.h>
struct pipe
{
int target_pid;
void *data_addr; //数据的内存地址
struct fifo8 fifo;
};
void pipe_create(struct pipe*, int);
int pipe_get(struct pipe**);
int pipe_write(struct pipe*, char*, int);
int pipe_read(struct pipe*, char*, int);
void pipe_close(struct pipe*);<file_sep>/doc/code style.md
### 1.函数命名
#### 函数采用下划线命名法
#### 设备名_操作名
* 设备名: 主语或标明函数所在的模块
* 操作名: 一般是谓语或谓语+宾语
### 2.代码中的符号
* 数学运输符前后要有一个空格
```c
int x = a + b;
```
* `,`, `;`, `:`等符号在后面加空格
```c
int func(int a, int b, ...);
```<file_sep>/kernel/task.c
#include <kernel/task.h>
#include <kernel/memory.h>
#include <kernel/page.h>
#include <lib/string.h>
#include <arch/x86/cpu.h>
void init_proc(void);
struct task_info task_list[1024];
int current_proc = 0; //当前运行的任务pid
int get_proc_by_pid(int pid)
{
for(int i = 0; i < TASKS_MAX; i++)
{
if(task_list[i].pid == pid)
{
return i;
}
}
return -1;
}
/* 生成未使用的PID */
static int generate_pid(void)
{
static int max_pid = 0;
if(max_pid > MAX_PID)
{
max_pid = 0;
}
for(int pid = max_pid + 1; pid < MAX_PID; pid++)
{
if(get_proc_by_pid(pid) == -1)
{
max_pid = pid;
return pid;
}
}
return -1;
}
/* 初始化多任务 */
void task_init(void)
{
for(int i = 1; i < TASKS_MAX; i++)
{
task_list[i].pid = -1;
task_list[i].uid = -1;
task_list[i].flags = TASK_AVAILABLE;
}
/* 创建初始化任务 */
task_list[0].flags = TASK_RUNNING;
task_list[0].uid = 0;
task_list[0].pid = 0;
task_list[0].ppid = 0;
task_list[0].nice = 0;
task_list[0].page = kernel_page_dir;
str_cpy(task_list[0].name, "idle");
scheduler_add(&task_list[0]);
/* 创建init进程 */
//int init_pid = task_alloc(init_proc);
//task_run(init_pid);
//task_set_name(init_pid, "init");
}
/* 切换任务 */
void task_switch()
{
int proc = task_get_next_proc();
if(proc != -1 && proc != current_proc)
{
int old_proc = current_proc;
current_proc = proc;
printfmt("%d\n", proc);
io_sti(); //重新启用中断
page_switch(task_list[proc].page);
//asm_task_switch(&task_list[old_proc].state, &task_list[proc].state);
}
}
#define PAGE_DIRS_SIZE 1024
/* 创建任务 */
int task_alloc(void *addr)
{
for(int i = 0; i < TASKS_MAX; i++)
{
if(task_list[i].flags == TASK_AVAILABLE)
{
void *stack_addr = memfrag_alloc(1024) + 1024; //分配该任务的栈地址
task_init_register(&task_list[i].state);
/* copy process code */
task_list[i].init_info.code_addr = memfrag_alloc(1);
unsigned char *code = task_list[i].init_info.code_addr;
unsigned char *source = addr;
for(int off = 0; off < 4096; off++)
{
code[off] = source[off];
}
task_list[i].init_info.stack_addr = stack_addr;
task_list[i].flags = TASK_PENDING;
task_list[i].uid = task_list[current_proc].uid;
task_list[i].pid = generate_pid();
task_list[i].ppid = task_list[current_proc].pid;
task_list[i].nice = TASK_DEFAULT_PRIORITY;
task_list[i].name[0] = '\0';
task_list[i].page = page_alloc();
page_set(task_list[i].page, (unsigned int)task_list[i].init_info.code_addr / 4096, TASK_CODE_ADDR / 4096);
/* map low 1 MB */
for(int j = 0; j < 1024 * 1024 / 4096; j++)
{
page_set(task_list[i].page, j, j);
}
/* map kernel code */
for(int j = 0; j < KERNEL_CODE_SIZE / 4096; j++)
{
page_set(task_list[i].page, KERNEL_CODE_ADDR / 4096 + j, KERNEL_CODE_ADDR / 4096 + j);
}
/* map GDT table */
for(int j = 0; j < GDT_SIZE / 4096; j++)
{
page_set(task_list[i].page, GDT_ADDR / 4096 + j, GDT_ADDR / 4096 + j);
}
/* map IDT table */
for(int j = 0; j < IDT_SIZE; j++)
{
page_set(task_list[i].page, IDT_ADDR / 4096 + j, IDT_ADDR / 4096 + j);
}
task_list[i].cpu_count = 0;
int *p = (int*)stack_addr;
*p = (int)TASK_CODE_ADDR; //[esp]为任务跳转地址
task_set_stack(&task_list[i].state, stack_addr);
task_list[i].cpu_time = 20 - task_list[i].nice;
return task_list[i].pid; //返回pid
}
}
return -1;
}
/* 运行任务 */
void task_run(int pid)
{
int proc = get_proc_by_pid(pid);
if(task_list[proc].flags == TASK_PENDING)
{
task_list[proc].flags = TASK_RUNNING;
scheduler_add(&task_list[proc]);
}
}
/* 设置任务名字 */
void task_set_name(int pid, char *str)
{
int proc = get_proc_by_pid(pid);
if(pid != 0 && proc != -1)
{
str_cpy(task_list[proc].name, str);
}
}
/* 获取任务名字 */
void task_get_name(char *ret, int pid)
{
int proc = get_proc_by_pid(pid);
/* 任务没有运行 */
if(proc != -1)
{
str_cpy(ret, task_list[proc].name);
return;
}
ret[0] = '\0';
}
/* 获取当前任务的pid */
int task_get_pid(void)
{
return task_list[current_proc].pid;
}
/* 获取进程uid */
int task_get_uid(int pid)
{
int proc = get_proc_by_pid(pid);
if(proc != -1)
{
return task_list[proc].uid;
}
return -1;
}
/* 获取父进程pid */
int task_get_ppid(int pid)
{
int proc = get_proc_by_pid(pid);
if(proc != -1)
{
return task_list[proc].ppid;
}
return -1;
}
/* 等待任务结束 */
void task_wait(int pid)
{
int proc = get_proc_by_pid(pid);
/* 不是当前任务的子进程 */
if(task_list[proc].ppid != current_proc)
{
return;
}
while(task_list[proc].flags != TASK_AVAILABLE);
}
/* 杀死任务 */
void task_kill(int pid)
{
int proc = get_proc_by_pid(pid);
/* 不能杀死idle进程 && 任务不在运行 */
if(pid != 0 && proc != -1)
{
task_list[proc].flags = TASK_AVAILABLE;
task_list[proc].pid = -1;
memfrag_free((void*)task_list[proc].init_info.stack_addr);
scheduler_remove(&task_list[proc]);
int i = 0;
/* 为子进程重新分配父进程 */
for(; i < TASKS_MAX; i++)
{
if(task_list[i].flags != TASK_AVAILABLE && task_list[i].ppid == pid)
{
task_list[i].ppid = 0;
}
}
}
/* 杀死当前任务 */
if(proc == current_proc)
{
task_switch();
}
}
/* 获取任务pid列表 */
int task_get_list(int *ret)
{
int i, j = 0;
for(i = 0; i < TASKS_MAX; i++)
{
if(task_list[i].flags != TASK_AVAILABLE)
{
ret[j] = task_list[i].pid;
j += 1;
}
}
return j; //返回pid个数
}
/* 休眠任务 */
void task_sleep(int pid)
{
int proc = get_proc_by_pid(pid);
if(task_list[proc].flags == TASK_RUNNING)
{
task_list[proc].flags = TASK_SLEEPING;
scheduler_remove(&task_list[proc]);
}
}
/* 唤醒任务 */
void task_wakeup(int pid)
{
int proc = get_proc_by_pid(pid);
if(task_list[proc].flags == TASK_SLEEPING)
{
task_list[proc].flags = TASK_RUNNING;
scheduler_add(&task_list[proc]);
}
}<file_sep>/kernel/fs/block.c
#include <device/disk/disk.h>
#include <kernel/memory.h>
#include <kernel/fs/bitmap.h>
#include <kernel/fs/block.h>
/* 读取一个块的数据 */
void block_load(unsigned int block, void *data)
{
lba28_read((short*)data, block * 8, 8);
}
/* 写入一个块的数据 */
void block_save(unsigned int block, void *data)
{
lba28_write((short*)data, block * 8, 8);
}
/* 清除一个块的数据 */
void block_cleanup(unsigned int block)
{
char *data = memfrag_alloc_4k(1);
for(int i = 0; i < 4096; i++)
{
data[i] = 0;
}
block_save(block, data);
memfrag_free(data);
}
struct super_block sblock;
/* 加载超级块的数据 */
void super_block_load(void)
{
block_load(SUPER_BLOCK, &sblock); //加载超级块
}
/* 保存超级块的数据 */
void super_block_save(void)
{
block_save(SUPER_BLOCK, &sblock); //保存超级块
}
/* 获取引导块的位置 */
int super_block_get_index(void)
{
return sblock.bitmap_block;
}
/* 创建一个块 */
int block_create(void)
{
for(int i = 2; i < 1024; i++)
{
/* 找到未使用的块 */
if(!bitmap_get_used(i))
{
bitmap_set_used(i); //设置为已用
bitmap_save();
block_cleanup(i); //清除此数据块数据
return i;
}
}
return -1;
}
<file_sep>/include/kernel/init.h
void kernel_init(void);<file_sep>/kernel/fs/Makefile
kernel_objs += kernel/fs/fs.o\
kernel/fs/init.o kernel/fs/bitmap.o kernel/fs/inode.o\
kernel/fs/block.o kernel/fs/file.o kernel/fs/dir.o kernel/fs/path.o<file_sep>/kernel/schedule.c
#include <kernel/task.h>
struct task_info *tasks[TASKS_MAX];
int tasks_count = 0;
int tasks_posit = 1;
extern struct task_info task_list[TASKS_MAX];
extern unsigned int time_count;
extern int get_proc_by_pid(int);
/* calculate CPU count */
static int get_cpu_time(int nice)
{
int prio = (TASK_NICE_MAX + 1) - nice;
int max_prio = 0;
for(int i = 0; i < tasks_count; i++)
{
max_prio += (TASK_NICE_MAX + 1) - tasks[i]->nice;
}
float cpu_time = UNIT_TIME * ((float)prio / (float)max_prio);
return (int)cpu_time;
}
/* get next pid */
int task_get_next_proc()
{
for(int i = tasks_posit; i < tasks_count; i++)
{
/* tasks[tasks_posit]的CPU时间未计算 */
if(tasks[tasks_posit]->cpu_time == -1)
{
tasks[tasks_posit]->cpu_time = get_cpu_time(tasks[tasks_posit]->nice);
tasks[tasks_posit]->cpu_count += tasks[tasks_posit]->cpu_time;
tasks[tasks_posit]->cpu_time -= 1;
return tasks_posit;
}
/* CPU count is 0, prepare next task */
else if(tasks[tasks_posit]->cpu_time == 0)
{
tasks[tasks_posit]->cpu_time = -1;
tasks_posit += 1;
}
else
{
tasks[tasks_posit]->cpu_time -= 1;
return tasks_posit;
}
}
tasks_posit = 0;
return 0;
}
/* add a task to the scheduler */
void scheduler_add(struct task_info *task)
{
tasks[tasks_count] = task;
tasks_count += 1;
task->cpu_time = -1;
}
/* remove task */
void scheduler_remove(struct task_info *task)
{
for(int i = 0; i < TASKS_MAX; i++)
{
if(tasks[i] == 0)
{
return;
}
if(tasks[i] == task)
{
for(int j = i; j < tasks_count - 1; j++)
{
tasks[j] = tasks[j + 1];
}
tasks_count -= 1;
}
}
}
void task_set_nice(int pid, int nice)
{
int proc = get_proc_by_pid(pid);
scheduler_remove(&task_list[proc]);
task_list[proc].nice = nice;
scheduler_add(&task_list[proc]);
}
<file_sep>/include/kernel/fs/path.h
void path_get_basename(char*, char*);
void path_get_dirname(char*, char*);
int path_exist(char*);
int path_get_inode(char*);<file_sep>/tools/edimg/mem.c
#include <stdlib.h>
/*
kernel/memory.c 的C语言实现
*/
void* memfrag_alloc(size_t size)
{
return malloc(size);
}
void* memfrag_alloc_4k(size_t size)
{
return malloc(4096 * size);
}
void memfrag_free(void *addr)
{
free(addr);
}<file_sep>/include/kernel/fs/init.h
void fs_init(void);
void fs_create(void);<file_sep>/doc/pic.md
### 1.PIC简介
可编程中断控制器(programmable interrupt controller,PIC).PIC可以接受外部设备的中断信号,并通知CPU.
### 2.PIC初始化
中断屏蔽寄存器(interrupt mask register,IMR),可以写入8位数据.每一位对应一个IRQ.置1则屏蔽中断.(主PIC 0x21,从PIC 0xa1)
初始化:
先向ICW1(主PIC 0x20,从PIC 0xa0)写入8位数据,再依次写入ICW2、ICW3、ICW4(主PIC 0x21,从PIC 0xa1),一点要按顺序写入.
#### PIT
PIT(programmable interval timer)用于计时器中断.
初始化: 向0x43端口写入0x34,0x40端口依次写入中断周期低8位,高8位。
#### PIC中断
|IRQ编号|说明|
|---|---|
|IRQ 0|计时器中断|
|IRQ 1|键盘中断|
|IRQ 2|连接从PIC|
### 3.PIC通知
中断发生后应向中断控制器(主PIC 0x20,从PIC 0xa0)写入一字节的数据(0x60+中断编号).否则此中断不会再次发生.<file_sep>/kernel/memory.c
#include <kernel/memory.h>
#include <kernel/sysinfo.h>
struct mem_fragment mem_frag_list[4096];
int mem_frag_num = 0; //lenth og fragments
/* refresh remaining size */
static void refresh_free_size(void)
{
sysinfo.mem_free = sysinfo.mem_size;
for(int i = 1; i <= mem_frag_num; i++)
{
sysinfo.mem_free -= mem_frag_list[i].size;
}
}
/* get memory full size */
void* mem_get_size(void)
{
/* 已经检测过内存则返回该值 */
if(sysinfo.mem_size != 0)
{
return sysinfo.mem_size;
}
int *p, old;
for(p = (int*)0x100000; p < (int*)0xffffffff; p += 4096)
{
old = *p; //保存初始内存内容
*p = 0xff00ff00;
if(*p != 0xff00ff00)
{
break;
}
*p = old;
}
return (void*)p;
}
/* initialize memory management */
void memfrag_init(void)
{
sysinfo.mem_size = mem_get_size();
sysinfo.mem_free = sysinfo.mem_size;
mem_frag_list[0].addr = (void*)0x100000;
mem_frag_list[0].size = 0;
mem_frag_list[1].addr = sysinfo.mem_size; //结尾的地址为内存大小
mem_frag_list[1].size = 0;
}
/* allocate memory area */
void* memfrag_alloc(unsigned int size)
{
int i = 1;
for(; i <= mem_frag_num + 1; i++)
{
/* 找到了足够大的内存碎片 */
if(mem_frag_list[i].addr - mem_frag_list[i - 1].size -\
mem_frag_list[i - 1].addr >= size)
{
break;
}
}
void *addr = mem_frag_list[i - 1].addr + mem_frag_list[i - 1].size;
for(int j = mem_frag_num + 1; j >= i; j--)
{
mem_frag_list[j + 1] = mem_frag_list[j];
}
mem_frag_list[i].addr = addr;
mem_frag_list[i].size = size;
mem_frag_num += 1;
refresh_free_size();
return addr;
}
/* 以4kb为单位分配内存 */
void* memfrag_alloc_4k(unsigned int size)
{
size *= 4096;
int i = 1;
void* addr;
for(; i <= mem_frag_num + 1; i++)
{
addr = (void*)(((unsigned int)mem_frag_list[i - 1].addr + mem_frag_list[i - 1].size + 0xfff) & 0xfffff000);
/* 找到了足够大的内存碎片 */
if(mem_frag_list[i].addr - addr >= size)
{
break;
}
}
for(int j = mem_frag_num + 1; j >= i; j--)
{
mem_frag_list[j + 1] = mem_frag_list[j];
}
mem_frag_list[i].addr = addr;
mem_frag_list[i].size = size;
mem_frag_num += 1;
refresh_free_size();
return addr;
}
/* allocate memory with address */
void memfrag_alloc_with_addr(void *addr, unsigned int size)
{
int i = 1;
/* 查找插入内存片段位置 */
for(; i <= mem_frag_num + 1; i++)
{
if(mem_frag_list[i].addr > addr)
{
break;
}
}
/* 需要分配的内存已被使用 */
if(mem_frag_list[i - 1].addr + mem_frag_list[i - 1].size > addr || \
addr + size > mem_frag_list[i].addr)
{
return;
}
int j = mem_frag_num + 1; //j为最后一个成员位置
/* 向后移动成员 */
for(; j >= i; j--)
{
mem_frag_list[j + 1] = mem_frag_list[j];
}
mem_frag_list[i].addr = addr;
mem_frag_list[i].size = size;
mem_frag_num += 1;
refresh_free_size();
}
/* release memory area */
void memfrag_free(void* addr)
{
for(int i = 1; i <= mem_frag_num; i++)
{
if(mem_frag_list[i].addr == addr)
{
/* 向前移动成员 */
for(; i <= mem_frag_num; i++)
{
mem_frag_list[i] = mem_frag_list[i + 1];
}
mem_frag_num -= 1;
break;
}
}
refresh_free_size();
}
/* get remaining space */
void* mem_get_free_size(void)
{
return sysinfo.mem_free;
}
<file_sep>/kernel/fs/bitmap.c
#include <kernel/fs/block.h>
#include <kernel/fs/bitmap.h>
/* 创建引导块 */
void bitmap_create(void)
{
block_cleanup(2);
sblock.bitmap_block = 2; //设置super block中的引导块编号
super_block_save();
}
char bitmap_data[4096];
/* 加载引导块 */
void bitmap_load(void)
{
block_load(sblock.bitmap_block, bitmap_data);
}
/* 保存引导块 */
void bitmap_save(void)
{
block_save(sblock.bitmap_block, bitmap_data);
}
/* 获取块是否使用 */
int bitmap_get_used(unsigned int block)
{
int offset = block / 8; //计算用于存放信息的位置,char为8 bits
char p = block % 8;
if((bitmap_data[offset] & (0x100 >> (p + 1))) != 0)
{
return 1;
}
return 0;
}
/* 标记block已经使用 */
void bitmap_set_used(unsigned int block)
{
int offset = block / 8;
char p = block % 8;
bitmap_data[offset] |= (0x100 >> (p + 1));
}
/* 标记block为可用 */
void bitmap_set_unused(unsigned int block)
{
int offset = block / 8;
char p = block % 8;
bitmap_data[offset] &= !(0x100 >> (p + 1));
}<file_sep>/include/arch/x86/cpu.h
#define GDT_ADDR (8 * 0x100000 + 0x800)
#define GDT_SIZE (8 * 0x2000)
#define IDT_ADDR (8 * 0x100000)
#define IDT_SIZE (8 * 0x100)
#define ACC_CODE 0b10011000
#define ACC_DATA 0b10010000
#define ACC_READ 0b0010
#define ACC_WRITE 0b0010
/* GDT数据结构体 */
struct GDT_data
{
short limit_low, base_low;
char base_mid, access;
char limit_high, base_high;
};
/* IDT数据结构体 */
struct IDT_data
{
short offset_low, selector;
char count, access;
short offset_high;
};
void cpu_init(void);
void GDT_set(short, int, int, short);
void IDT_set(char, int, short, char);
void GDTR_load(int, int);
void IDTR_load(int, int);
void io_out8(int, int);
int io_in8(int);
void io_out16(int, int);
int io_in16(int);
void io_cli(void);
void io_sti(void);
void cpu_halt(void);
<file_sep>/kernel/random.c
#include <kernel/time.h>
#include <lib/types.h>
#include <lib/string.h>
unsigned int seed = 0;
/* adjust random seed */
static int adjust_seed(int origin_seed)
{
if(origin_seed < 1000)
{
origin_seed += 1000;
}
/* 最后2位为0以后的随机数最后2位的0会重复 */
if(origin_seed % 100 == 0)
{
origin_seed += 30;
}
return origin_seed;
}
/* initialize random seed */
void random_init(void)
{
LOCAL_TIME tm;
TIME_STAMP ts;
time_local_time(&tm);
time_get_stamp(&ts, tm);
seed = ts.ts_low;
if(seed > 9999)
{
char str[10];
uint2str(str, seed);
seed = str2int(&str[str_len(str) - 4]);
}
seed = adjust_seed(seed);
}
/* generate a random */
unsigned int random(void)
{
seed = seed * seed;
char str[10];
uint2str(str, seed);
/* 不足8位高位补0 */
if(str_len(str) == 7)
{
int i = str_len(str);
for(; i >= 0; i--)
{
str[i + 1] = str[i];
}
str[0] = '0';
}
int i = 0;
while(str[i] != '\0')
{
str[i] = str[i + 2];
i += 1;
}
str[4] = '\0';
seed = str2uint(str);
seed = adjust_seed(seed);
int randint = seed;
/* 根据时间戳调整随机数种子以增强不确定性 */
LOCAL_TIME tm;
TIME_STAMP ts;
time_local_time(&tm);
time_get_stamp(&ts, tm);
if(ts.ts_low % 2 == 0)
{
seed += 2;
}
if(ts.ts_low % 3 == 0)
{
seed += 3;
}
if(ts.ts_low % 5 == 0)
{
seed += 5;
}
return randint;
}<file_sep>/include/lib/args.h
struct arg
{
void *start;
int count;
};
void arg_init(struct arg*, void*);
void arg_get_next(struct arg*, void*, int);
<file_sep>/kernel/timer.c
#include <device/interrupt/interrupt.h>
/* allocate a timer */
int timer_alloc(void)
{
timer_num += 1;
timer_list[timer_num - 1] = time_count;
return timer_num - 1; //返回计时器编号
}
/* get past seconds */
int timer_get_time(int num)
{
return time_count - timer_list[num];
}
/* release timer */
void timer_free(int num)
{
for(; num < timer_num - 1; num++)
{
timer_list[num] = timer_list[num + 1];
}
timer_num -= 1;
}
<file_sep>/device/serial/io.c
#include <arch/x86/cpu.h>
/* 串口发送一个字符数据 */
void serial_send_char(char c)
{
io_out8(0x3f8, c);
}
/* 串口发送数据 */
void serial_send(char *str)
{
int i = 0;
while(str[i] != '\0')
{
serial_send_char(str[i]);
i += 1;
}
}
/* 串口接收一个字符数据 */
char serial_recv_char(void)
{
while((io_in8(0x3f8 + 5) & 1) == 0);
return io_in8(0x3f8);
}
/* 串口发送数据 */
void serial_recv(char *ret)
{
int i = 0;
while(1)
{
ret[i] = serial_recv_char();
/* 回车 */
if(ret[i] == '\r')
{
serial_send_char('\n');
ret[i] = '\0';
return;
}
else
{
serial_send_char(ret[i]);
i += 1;
}
}
}<file_sep>/arch/x86/kernel/clock.c
#include <arch/x86/cpu.h>
#include <kernel/time.h>
/* 获取系统时间 */
void time_local_time(struct local_time* lt)
{
io_out8(0x70, 0x0);
char S = io_in8(0x71);
io_out8(0x70, 0x2);
char M = io_in8(0x71);
io_out8(0x70, 0x4);
char H = io_in8(0x71);
io_out8(0x70, 0x7);
char d = io_in8(0x71);
io_out8(0x70, 0x8);
char m = io_in8(0x71);
io_out8(0x70, 0x9);
char Y = io_in8(0x71);
io_out8(0x70, 0x32);
char Y10 = io_in8(0x71); //获取公元数
lt->S = (S >> 4) * 10 + (S & 0xf);
lt->M = (M >> 4) * 10 + (M & 0xf);
lt->H = (H >> 4) * 10 + (H & 0xf);
lt->d = (d >> 4) * 10 + (d & 0xf);
lt->m = (m >> 4) * 10 + (m & 0xf);
Y10 = (Y10 >> 4) * 10 + (Y10 & 0xf);
lt->Y = Y10 * 100 + (Y >> 4) * 10 + (Y & 0xf);
}<file_sep>/include/arch/x86/cpuid.h
void cpuid_get_vendorid(char*);
void cpuid_get_brand(char*);<file_sep>/kernel/fs/inode.c
#include <kernel/fs/inode.h>
#include <kernel/fs/block.h>
#include <device/disk/disk.h>
struct inode inode_list[INODE_NUM];
int inode_count = 0; //node的数量
/* 获取可用inode编号 */
int inode_get_available(void)
{
int i = 0;
/* 循环查找未使用的inode */
for(; i < inode_count; i++)
{
/* inode未使用 */
if(inode_list[i].type == 0)
{
return i; //返回此inode编号
}
}
/* 所有的inode已经使用 */
int new = block_create(); //分配一个新的块作为inode表
if(new != -1)
{
for(i = 0; i < 1024 - 1; i++)
{
/* 将这个块写入超级块 */
if(sblock.inode_table[i] == 0)
{
sblock.inode_table[i] = new;
super_block_save(); //写入数据
break;
}
}
inode_load(); //重新加载inode
for(i = 0; i < inode_count; i++)
{
if(inode_list[i].type == 0)
{
return i;
}
}
}
return -1;
}
/* 从超级块加载inode */
void inode_load(void)
{
int j = 0;
for(int i = 0; i < sizeof(sblock.inode_table) / sizeof(sblock.inode_table[0]); i++)
{
/* 指向了一个存在的块 */
if(sblock.inode_table[i] != 0)
{
block_load(sblock.inode_table[i], &inode_list[INODE_NUM * j]); //加载该块的数据
j += 1;
}
}
inode_count = j * INODE_NUM; //更新inode数量
}
/* 保存inode */
void inode_save(void)
{
for(int i = 0; i < inode_count / INODE_NUM; i++)
{
block_save(sblock.inode_table[i], &inode_list[INODE_TABLE_SIZE * i]);
}
}
<file_sep>/kernel/fifo.c
#include <kernel/fifo.h>
/* initialize FIFO */
void fifo_init(struct fifo8 *fifo, void* addr, int size)
{
fifo->addr = addr;
fifo->size = size;
fifo->free = size;
fifo->write = 0;
fifo->read = 0;
}
/* get unread size */
int fifo_get_info(struct fifo8 fifo)
{
return fifo.size - fifo.free;
}
/* write to FIFO */
void fifo_write_data(struct fifo8 *fifo, char data)
{
/* 缓冲区空间已满 */
if(fifo->free == 0)
{
return;
}
/* 写入位置达到最后一位 */
if(fifo->write >= fifo->size)
{
fifo->write = 0;
}
char *p = (char*)fifo->addr;
p[fifo->write] = data;
fifo->write += 1;
fifo->free -= 1;
}
/* read from FIFO */
char fifo_read_data(struct fifo8 *fifo)
{
/* 缓冲区数据大小为0 */
if(fifo_get_info(*fifo) == 0)
{
return -1;
}
/* 读到缓冲区最后一位 */
if(fifo->read >= fifo->size)
{
fifo->read = 0;
}
char *p = (char*)fifo->addr;
char data = p[fifo->read];
fifo->read += 1;
fifo->free += 1;
return data;
}<file_sep>/include/device/interrupt/init.h
void PIC_init(void);
void PIT_init(void);<file_sep>/config/toolchain.mk
CC = gcc
LD = ld
AS = as
MAKE = make
ifeq ($(ARCH), x86)
QEMU = qemu-system-i386
endif<file_sep>/config/env.mk
C_FLAGS = -Wall -fno-stack-protector -Iinclude
LD_FLAGS = -e _start -Ttext 0x100000
ifeq ($(ARCH), x86)
C_FLAGS += -m32
LD_FLAGS += -m elf_i386
endif
#是否启用KVM
ifeq ($(KVM), y)
QEMU += -enable-kvm
endif<file_sep>/include/lib/string.h
int str_len(char*);
int str_cmp(char*, char*);
void str_cpy(char*, char*);
int str_find(char*, char*, int);
int str_count(char*, char*);
void str_cat(char*, char*);
void str_split(char*, char*, char*, int);
void str_slice(char*, char*, int, int);
void str_replace(char*, char*, char*);
<file_sep>/include/device/video/cli_print.h
#define VGA_ADDR 0xb8000
void cli_print(char*);
void cli_print_char(char);
void video_cleanup(void);
void video_move_cursor(short);<file_sep>/include/device/serial/io.h
void serial_send(char*);
void serial_send_char(char);
void serial_recv(char*);
char serial_recv_char(void);<file_sep>/device/input/Makefile
kernel_objs += device/input/keyboard.o<file_sep>/kernel/user.c
#include <kernel/user.h>
#include <lib/string.h>
struct user users[100];
void user_init(void)
{
str_cpy(users[0].name, "root");
users[0].uid = 0;
for(int i = 1; i < 100; i++)
{
users[i].name[0] = '\0';
users[i].uid = -1;
}
}
/* register a user */
int user_register(char *name, int uid)
{
for(int i = 0; i < 100; i++)
{
/* user exists */
if(!str_cmp(users[uid].name, name))
{
return -1;
}
}
if(users[uid].uid != -1)
{
return -1;
}
str_cpy(users[uid].name, name);
users[uid].uid = uid;
return 0;
}
/* get username by uid */
int user_get_name(char *ret, int uid)
{
if(users[uid].uid == -1)
{
return -1;
}
str_cpy(ret, users[uid].name);
return 0;
}
/* get UID */
int user_get_uid(char *name)
{
for(int uid = 0; uid < 100; uid++)
{
if(!str_cmp(users[uid].name, name))
{
return users[uid].uid;
}
}
return -1;
}<file_sep>/arch/x86/kernel/Makefile
kernel_objs += arch/x86/kernel/cpu.o arch/x86/kernel/task.o arch/x86/kernel/clock.o\
arch/x86/kernel/page.o arch/x86/kernel/error_int.o
kernel_bins += arch/x86/kernel/_start.bin arch/x86/kernel/x86_asm.bin\
arch/x86/kernel/interrupt.bin arch/x86/kernel/task.bin arch/x86/kernel/cpuid.bin\
arch/x86/kernel/page.bin
<file_sep>/doc/file_system.md
### 1.1块
块(block),是文件系统管理的标准单位,1个块大小为4 kb(8扇区).
### 1.2超级块
磁盘的的一个块为文件系统的超级块,记录了文件系统的信息.
主要存储了以下数据:
* bitmap块: 记录了那些块可用.
* inode table块: 记录了inode数据.
#### bitmap块
用1 bit的数据代表一个块,记录文件系统中块的使用情况,从而做到快速分配数据块.
### 2.inode
inode(index node)记录了一个文件的基本信息,包含一下信息:
* name: inode名,即文件名
* index_block: 索引块,记录了数据块编号
* size: 文件大小
* type: inode类型,文件还是文件夹
索引块储存了一个数据块编号列表,可以通过遍历列表读取文件内容。<file_sep>/device/serial/Makefile
kernel_objs += device/serial/io.o<file_sep>/kernel/time.c
#include <kernel/time.h>
#include <kernel/timer.h>
/* delay, unit: ms */
void delay(unsigned int time)
{
int i = timer_alloc(); //分配一个计时器
while(1)
{
/* 经过的时间到了需要等待的时间 */
if(timer_get_time(i) >= time)
{
break;
}
}
timer_free(i);
}
/* delay, unit: s */
void sleep(unsigned int time)
{
delay(100 * time);
}
#define Y_SEC (365 * 24 * 60 * 60)
#define D_SEC (24 * 60 * 60)
/* get current timestamp */
void time_get_stamp(struct time_stamp *ts, struct local_time lt)
{
ts->ts_low += Y_SEC * (lt.Y - 1970);
int i = 1972; //1970后第一个闰年
for(; i < lt.Y; i += 4)
{
ts->ts_low += D_SEC;
}
/* 加上每个月的秒数 */
for(i = 1; i < lt.m; i++)
{
if((i % 2 != 0 && i <= 7) || (i % 2 == 0 && i >=8))
{
ts->ts_low += 31 * D_SEC;
}
else
{
if(i == 2)
{
ts->ts_low += 28 * D_SEC;
continue;
}
ts->ts_low += 30 * D_SEC;
}
}
ts->ts_low += (lt.d - 1) * D_SEC;
ts->ts_low += lt.H * 60 * 60;
ts->ts_low += lt.M * 60;
ts->ts_low += lt.S;
}
<file_sep>/kernel/strfmt.c
#include <lib/types.h>
#include <lib/args.h>
#include <lib/string.h>
#include <device/video/cli_print.h>
/* 格式化输出 */
void printfmt(char *str, ...)
{
int i = 0;
struct arg arg;
arg_init(&arg, &str);
while(str[i] != '\0')
{
if(str[i] == '%')
{
if(str[i + 1] == 's')
{
char *str0;
arg_get_next(&arg, &str0, sizeof(str0));
cli_print(str0);
}
else if(str[i + 1] == 'd')
{
int int0;
arg_get_next(&arg, &int0, sizeof(int0));
char str1[50];
int2str(str1, int0);
cli_print(str1);
}
else if(str[i + 1] == 'u')
{
int int0;
arg_get_next(&arg, &int0, sizeof(int0));
char str1[50];
uint2str(str1, int0);
cli_print(str1);
}
else if(str[i + 1] == '%')
{
cli_print_char('%');
}
i += 2;
continue;
}
cli_print_char(str[i]);
i += 1;
}
}
/* 格式化字符串 */
void strfmt(char *ret, char *str, ...)
{
int i = 0;
int j = i;
struct arg arg;
arg_init(&arg, &str);
while(str[i] != '\0')
{
if(str[i] == '%')
{
if(str[i + 1] == 's')
{
char *str0;
arg_get_next(&arg, &str0, sizeof(str0));
str_cat(ret, str0);
j += str_len(str0);
}
else if(str[i + 1] == 'd')
{
int int0;
arg_get_next(&arg, &int0, sizeof(int0));
char str1[50];
int2str(str1, int0);
str_cat(ret, str1);
j += str_len(str1);
}
else if(str[i + 1] == 'u')
{
int int0;
arg_get_next(&arg, &int0, sizeof(int0));
char str1[50];
uint2str(str1, int0);
str_cat(ret, str1);
j += str_len(str1);
}
else if(str[i + 1] == '%')
{
ret[j] = '%';
j += 1;
}
i += 2;
continue;
}
ret[j] = str[i];
ret[j + 1] = '\0';
i += 1;
j += 1;
}
}<file_sep>/device/interrupt/Makefile
kernel_objs += device/interrupt/init.o device/interrupt/timer.o\
device/interrupt/keyboard.o<file_sep>/arch/x86/kernel/cpu.c
#include <arch/x86/cpu.h>
#include "interrupts.h"
/* 初始化cpu */
void cpu_init(void)
{
short i;
for(i = 0; i < 0x2000; i++)
{
GDT_set(i, 0, 0, 0);
}
GDT_set(1, 0, 0xffffffff, 0x4000 | ACC_CODE | ACC_READ);
GDT_set(2, 0, 0xffffffff, 0x4000 | ACC_DATA | ACC_WRITE);
GDTR_load(GDT_ADDR, 0xffff); //加载GDTR寄存器
for(i = 0; i < 256; i++)
{
IDT_set((char)i, 0, 0, 0);
}
IDT_set(0x00, (int)asm_interrupt00h, 8, 0x8e);
IDT_set(0x04, (int)asm_interrupt04h, 8, 0x8e);
IDT_set(0x06, (int)asm_interrupt06h, 8, 0x8e);
IDT_set(0x08, (int)asm_interrupt08h, 8, 0x8e);
IDT_set(0x0c, (int)asm_interrupt0ch, 8, 0x8e);
IDT_set(0x0d, (int)asm_interrupt0dh, 8, 0x8e);
IDT_set(0x0e, (int)asm_interrupt0eh, 8, 0x8e);
IDT_set(0x20, (int)asm_interrupt20h, 8, 0x8e);
IDT_set(0x21, (int)asm_interrupt21h, 8, 0x8e);
IDTR_load(IDT_ADDR, 0x7ff); //加载IDTR寄存器
}
/* 设置GDT数据 */
void GDT_set(short count, int base, int limit, short access)
{
struct GDT_data *GDT = (struct GDT_data*)GDT_ADDR;
GDT += count; //设置GDT地址到地count个GDT处
/* 大于1MB则置G为1 */
if(limit > 0xfffff)
{
access |= 0x8000;
limit /= 0x1000;
}
GDT->base_high = base >> 24; //取base高8位
GDT->base_mid = base >> 16 & 0xff; //取base中间8位
GDT->base_low = base & 0xffff; //取base低16位
GDT->limit_high = (limit >> 16 & 0x0f) | (access >> 8 & 0xf0);
GDT->limit_low = limit & 0xffff; //取limit低16位
GDT->access = access & 0xff; //取access低8位
}
/* 设置IDT数据 */
void IDT_set(char count, int offset, short selector, char access)
{
struct IDT_data *IDT = (struct IDT_data*)IDT_ADDR;
IDT += count; //设置IDT地址到地count个IDT处
IDT->offset_high = offset >> 16; //取offset高16位
IDT->offset_low = offset & 0xffff; //取offset低16位
IDT->selector = selector;
IDT->count = 0;
IDT->access = access;
}<file_sep>/kernel/Makefile
include kernel/fs/Makefile
kernel_objs += kernel/init.o kernel/init_proc.o kernel/fifo.o kernel/memory.o\
kernel/timer.o kernel/time.o kernel/task.o kernel/schedule.o\
kernel/pipe.o kernel/strfmt.o kernel/random.o kernel/sysinfo.o\
kernel/user.o kernel/page.o<file_sep>/kernel/init_proc.c
/* init process, PID = 1 */
void init_proc(void)
{
for(;;);
}
<file_sep>/include/kernel/page.h
extern unsigned int *kernel_page_dir;
extern unsigned int *page_dirs[];
void page_init(void);
unsigned int* page_alloc(void);
void page_free(void*);
void page_enable(void);
void page_disable(void);
void page_set_table(unsigned int*, short, short, unsigned int);
void page_set_dir(unsigned int*, short, unsigned int);
void page_set(unsigned int*, unsigned int, unsigned int);
void* page_add(unsigned int*, unsigned int);
void page_unset(unsigned int*, unsigned int);
void page_switch(void*);
void set_cr3(void*);<file_sep>/lib/args.c
#include <lib/args.h>
void arg_init(struct arg *arg, void *last_arg)
{
arg->start = last_arg + sizeof(void*);
arg->count = 0;
}
void arg_get_next(struct arg *arg, void* ret, int size)
{
char *val = arg->start + arg->count;
arg->count += sizeof(void*);
char *ret0 = ret;
for(int i = 0 ;i < size; i++)
{
ret0[i] = val[i];
}
}
<file_sep>/config/arch.mk
#支持的架构: x86
ARCH = x86
ARCH_DIR = arch/$(ARCH)<file_sep>/include/kernel/sysinfo.h
/* 系统信息 */
struct sysinfo
{
void *mem_size, *mem_free;
};
extern struct sysinfo sysinfo;
void sysinfo_init(void);
<file_sep>/include/kernel/fs/bitmap.h
void bitmap_create();
void bitmap_load();
void bitmap_save();
int bitmap_get_used(unsigned int);
void bitmap_set_used(unsigned int);
void bitmap_set_unused(unsigned int);<file_sep>/doc/multi_task.md
### 1.多任务简介
多任务是为不同的程序分配cpu时间片来实现多个程序同时运行.
### 2.多任务实现
在x86架构中有一个叫tr的任务寄存器,它回记录cpu的寄存器信息,从而在任务切换的时候恢复该任务状态.
内核由计时器中断发生时进行任务切换(抢占式多任务).
#### 切换任务的过程
`计时器中断 -> 保存当前寄存器数据 -> 恢复下一任务寄存器数据 -> 中断返回`
#### 子进程
子进程通常由另一个进程创建,创建它的进程称为父进程.
PPID(Parent Process PID),父进程PID,当一子进程的父进程被杀死后,其PPID会成为0(即init进程PID).<file_sep>/device/disk/Makefile
kernel_objs += device/disk/disk.o<file_sep>/kernel/fs/init.c
#include <kernel/fs/fs.h>
#include <kernel/fs/block.h>
#include <kernel/fs/bitmap.h>
#include <kernel/fs/inode.h>
#include <kernel/fs/dir.h>
extern struct super_block sblock;
/* 初始化文件系统 */
void fs_init(void)
{
inode_count = 0;
super_block_load(); //加载超级块
/* 磁盘上没有文件系统 */
if(!is_fs())
{
return;
}
bitmap_load();
inode_load(); //加载inode表到内存
}
/* 创建文件系统 */
void fs_create(void)
{
block_cleanup(SUPER_BLOCK); //清除超级块
super_block_load();
bitmap_create();
bitmap_load();
bitmap_set_used(2);
bitmap_save();
dir_create("/"); //创建根目录
sblock.fs_header[0] = 0x31;
sblock.fs_header[1] = 0x22;
sblock.fs_header[2] = 0x33;
sblock.fs_header[3] = 0x31;
super_block_save();
fs_init();
}<file_sep>/device/video/cli_print.c
#include <device/video/cli_print.h>
int vga_addr = VGA_ADDR; //显存地址
int screen_x_size = 80; //屏幕宽
int screen_y_size = 25; //屏幕高
/* 打印字符串 */
void cli_print(char *str)
{
int i = 0;
while(str[i] != '\0')
{
cli_print_char(str[i]);
i += 1;
}
}
/* 打印单字符 */
void cli_print_char(char c)
{
/* 回车字符处理 */
if(c == '\n')
{
int t = vga_addr - VGA_ADDR;
t -= t % (2 * screen_x_size);
t += 2 * screen_x_size;
vga_addr = t + VGA_ADDR;
video_move_cursor((vga_addr - VGA_ADDR) / 2);
}
/* 退格键 */
if(c == 0x0e)
{
vga_addr -= 2;
short *bak_cln = (short*)vga_addr;
*bak_cln = 0x0700;
video_move_cursor((vga_addr - VGA_ADDR) / 2);
return;
}
/* 超出屏幕范围则下滚一行 */
if((vga_addr - VGA_ADDR + 2) > 2 * screen_x_size * screen_y_size)
{
short *i;
/* 处最后一行整体向前移一行 */
for(i = (short*)VGA_ADDR; i < \
(short*)(VGA_ADDR + 2 * screen_x_size * (screen_y_size - 1)); i++)
{
*i = *(i + screen_x_size);
}
/* 填充最后一行 */
for(; i <= (short*)(VGA_ADDR + 2 * screen_x_size * screen_y_size); i++)
{
*i = 0x0700; //覆盖文本内容
}
vga_addr = VGA_ADDR + 2 * screen_x_size * (screen_y_size - 1); //显存指针在最后一行第一字符
}
/* 不为回车则打印当前字符 */
if(c != '\n')
{
char *p;
p = (char*)vga_addr;
*p = c;
p = (char*)vga_addr + 1;
*p = 0x07; //字体颜色
vga_addr += 2; //一个字符占2-byte
}
video_move_cursor((vga_addr - VGA_ADDR) / 2);
}
/* 清屏 */
void video_cleanup(void)
{
int i;
short *p = (short*)VGA_ADDR;
for(i = screen_x_size * screen_y_size; i > 0; i--)
{
*p = 0x0700; //覆盖文本内容
p += 1;
}
vga_addr = VGA_ADDR; //重置显存地址
}<file_sep>/include/device/interrupt/interrupt.h
extern unsigned int time_count;/* 记录经过的时间 */
extern unsigned int timer_list[1000];
extern int timer_num;
<file_sep>/device/Makefile
include device/disk/Makefile
include device/input/Makefile
include device/interrupt/Makefile
include device/video/Makefile
include device/serial/Makefile<file_sep>/arch/x86/kernel/interrupts.h
void interrupt00h(void);
void interrupt04h(void);
void interrupt06h(void);
void interrupt08h(void);
void interrupt0ch(void);
void interrupt0dh(void);
void interrupt0eh(void);
void interrupt20h(void);
void interrupt21h(void);
void asm_interrupt00h(void);
void asm_interrupt04h(void);
void asm_interrupt06h(void);
void asm_interrupt08h(void);
void asm_interrupt0ch(void);
void asm_interrupt0dh(void);
void asm_interrupt0eh(void);
void asm_interrupt20h(void);
void asm_interrupt21h(void);
<file_sep>/arch/x86/boot/Makefile
#/arch/x86/boot
BINS = $(patsubst %.asm, %.bin, $(wildcard *.asm))
all:$(BINS);
%.bin:%.asm
@echo "AS arch/x86/boot/$@"
@nasm $*.asm -o $*.bin
clean:
rm *.bin<file_sep>/lib/types.c
#include <lib/string.h>
/* 无符号整形数字转字符串 */
void uint2str(char *str, unsigned int num)
{
char str0[11];
int check = 10; //用于检测最低位是否为0
int i = 9; //用于从后到前写入str0字符
int j = 0; //用于记录最低位的大小
while(1)
{
/* 最低位为0 */
/* i+num=0则num最高位为0 */
if(num % check == 0 || i + num == 0)
{
str0[i] = j + 48;
check *= 10; //最低位为个位、十位以此类推
i -= 1;
j = 0;
if(num == 0)
{
break;
}
}
else
{
j += 1;
/* 检测最高为时check会溢出 */
if(i == 0)
{
num -= 1e9;
}
else
{
num -= check / 10;
}
}
}
str_cpy(str, str0 + i + 1);
}
/* 整形数字转字符串 */
void int2str(char *str, int num)
{
char str0[11];
if(num >= 0)
{
uint2str(str, num);
}
else
{
uint2str(str0, -num);
str[0] = '-';
str[1] = '\0';
str_cat(str, str0);
}
}
/* 字符串转无符号整形数字 */
unsigned int str2uint(char *str)
{
unsigned int i = 0; //i用来累计str数值
int x, y, t;
x = 0; //用来从高到低取str
int j = str_len(str) - 1;
while(str[x] != '\0')
{
t = str[x] - 48; //获取那一位的数字
/* t = t * 10 ^ j */
for(y = 0; y < j; y++)
{
t *= 10;
}
i += t;
x += 1; //接下来取str的下一个数字
j -= 1;
}
return i;
}
/* 字符串转整形数字 */
int str2int(char *str)
{
if(str[0] == '-')
{
return -str2uint(str + 1);
}
else
{
return -str2uint(str + 1);
}
}<file_sep>/include/kernel/fs/file.h
struct file
{
int inode;
int seek;
};
typedef struct file ST_FILE;
int file_create(ST_FILE*, char*);
int file_open(ST_FILE*, char*);
void file_write(ST_FILE*, char*, int);
int file_read(ST_FILE*, char*, int);
void file_remove(char*);
void file_get_name_by_inode(char*, int);
int file_get_size(ST_FILE);
<file_sep>/include/kernel/user.h
struct user
{
char name[10];
int uid;
};
void user_init(void);
int user_get_name(char*, int);
int user_get_uid(char*);
<file_sep>/include/kernel/fs/fs.h
#include <kernel/fs/init.h>
#include <kernel/fs/file.h>
#include <kernel/fs/dir.h>
#define FS_SUCCESS 0
#define FS_FAILED -1
int is_fs(void);<file_sep>/kernel/init.c
#include <arch/x86/cpu.h>
#include <device/interrupt/init.h>
#include <device/input/keyboard.h>
#include <kernel/page.h>
#include <kernel/user.h>
#include <kernel/task.h>
#include <kernel/pipe.h>
#include <kernel/memory.h>
#include <kernel/timer.h>
#include <kernel/random.h>
#include <kernel/sysinfo.h>
#include <kernel/fs/fs.h>
#include <device/video/cli_print.h>
/* initialize kernel */
void kernel_init(void)
{
sysinfo_init();
memfrag_init();
memfrag_alloc_with_addr((void*)GDT_ADDR, GDT_SIZE);
memfrag_alloc_with_addr((void*)IDT_ADDR, IDT_SIZE);
memfrag_alloc_with_addr((void*)0x100000, 4 * 0x100000); //为内核分配4MB空间
fifo_init(&key_fifo, memfrag_alloc_4k(1), 0x1000);
page_init();
task_init();
cpu_init();
PIC_init();
io_sti(); //enable interruption
random_init();
fs_init();
user_init();
}
<file_sep>/tools/edimg/Makefile
fs_objs = ../../kernel/fs/fs.o\
../../kernel/fs/init.o ../../kernel/fs/bitmap.o ../../kernel/fs/inode.o\
../../kernel/fs/block.o ../../kernel/fs/file.o ../../kernel/fs/dir.o ../../kernel/fs/path.o\
../../kernel/string.o
all:$(fs_objs) mem.o disk.o
gcc -I../../include edimg.c $(fs_objs) mem.o disk.o -o edimg
%.o:%.c
@echo "HOSTCC $@"
@gcc -Wall -I../../include -c $*.c -o $*.o
clean_deps:
rm $(fs_objs)
clean:
rm mem.o disk.o edimg
<file_sep>/README.md
## illumi kernel
### 一. 简介
#### 0x0 主要功能
* 内存管理
* 多任务
* 文件系统
* 设备管理 (未实现)
* API系统调用 (未实现)
#### 0x1 目录说明
| 目录 | 说明 |
|-------|--------|
|arch | 存放cpu架构相关代码.|
|include| 存放头文件.|
|init | 内核入口点.|
|kernel | 系统内核代码.|
|device | 存放一些设备的驱动代码.|
|lib | 常用函数库.|
|doc | 存放了操作系统开发文档.|
|config | 内核编译时的配置文件.|
|tools | 一些实用工具.|
#### 0x2 内核架构
```
USER MODE:
+-------------------------+
| Applications |
+-------------------------+
| syscall | libs |
+-------------------------+
KERNEL MODE:
+-----------------------+
| interrupts |
+-----------------------+
| Kernel |
+-----------------------+
| Hardware |
+-----------------------+
```
### 二. 编译与调试
#### 0x0 编译环境
```shell
$ sudo apt install nasm build-essential qemu-system-x86 #Debian based system
$ sudo yum install nasm make gcc qemu #Redhat based system
```
#### 0x1 命令行选项
```shell
$ make #编译
$ make run #编译并运行
$ make clean #清理输出文件
```
<file_sep>/device/video/cursor.c
#include <arch/x86/cpu.h>
/* 移动光标 */
void video_move_cursor(short p)
{
io_out8(0x3d4, 0xe);
io_out8(0x3d5, p >> 8);
io_out8(0x3d4, 0xf);
io_out8(0x3d5, p & 0xff);
}<file_sep>/include/version.h
#define KERNEL_NAME "illumi Kernel"
#define KERNEL_VERSION "0.0.3"<file_sep>/arch/x86/kernel/page.c
#include <kernel/memory.h>
/* set page table */
void page_set_table(unsigned int *page_dir, short table, short page, unsigned addr_4k)
{
addr_4k <<= 12;
unsigned int *page_table = (void*)(page_dir[table] & 0xfffff000);
addr_4k |= 0b11;
page_table[page] = addr_4k;
}
/* set page directory */
void page_set_dir(unsigned int *page_dir, short page, unsigned addr_4k)
{
addr_4k <<= 12;
addr_4k |= 0b11;
page_dir[page] = addr_4k;
}
| 860c4025b3aeef66c14fa824ede46187d1987ec4 | [
"Markdown",
"C",
"Makefile"
] | 103 | C | orgofzero/rexistum | b45b8f103e89722aab08edfd70934b64f5a47520 | 72b9d13b0a8bed5fc208be87524549dce1fa72d8 |
refs/heads/master | <file_sep><?php
define('OAUTH_CONSUMER_KEY', '<KEY>');
define('OAUTH_CONSUMER_SECRET', '<KEY>');
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
//$oauth = new OAuth('PwZrcFPPZwZu', '<KEY>');
$req_token = $oauth->getRequestToken("http://openapi.etsy.com/v2/sandbox/oauth/request_token", 'oob');
$login_url = sprintf(
"%s?oauth_consumer_key=%s&oauth_token=%s",
$req_token['login_url'],
$req_token['oauth_consumer_key'],
$req_token['oauth_token']
);
print "go to this url:\n\n ".$login_url."\n\n";
print "then tell me what the verifier code you get back is: \n\n";
$handle = fopen("php://stdin","r");
$line = fgets($handle);
$request_token = $req_token['oauth_token'];
$request_token_secret = $req_token['oauth_token_secret'];
$verifier = trim($line);
print "you said {$verifier}\n\n";
print "now let's see what we can get back from Etsy...\n\n";
$oauth->setToken($request_token, $request_token_secret);
try {
$access_token = $oauth->getAccessToken("http://openapi.etsy.com/v2/sandbox/oauth/access_token", null, $verifier);
} catch (OAuthException $e) {
print_r($e->getMessage());
}
$oauth_token = $access_token['oauth_token'];
$oauth_token_secret = $access_token['oauth_token_secret'];
$oauth->setToken($oauth_token, $oauth_token_secret);
try {
$data = $oauth->fetch("http://openapi.etsy.com/v2/sandbox/private/users/__SELF__");
$json = $oauth->getLastResponse();
print_r(json_decode($json, true));
} catch (OAuthException $e) {
error_log($e->getMessage());
error_log(print_r($oauth->getLastResponse(), true));
error_log(print_r($oauth->getLastResponseInfo(), true));
exit;
}
?>
<file_sep><?php
define ( 'OAUTH_CONSUMER_KEY', '<KEY>' );
define ( 'OAUTH_CONSUMER_SECRET', '<KEY>' );
// instantiate the OAuth object
// OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET are constants holding your key and secret
// and are always used when instantiating the OAuth object
$oauth = new OAuth ( OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET );
$oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
try{
// make an API request for your request tokens
//$req_token = $oauth->getRequestToken("http://openapi.etsy.com/v2/oauth/request_token", 'oob');
$req_token = $oauth->getRequestToken ( "http://openapi.etsy.com/v2/sandbox/oauth/request_token", 'oob' );
} catch (Exception $e)
{
var_dump($e);
}
// create the Etsy login url
$login_url = sprintf ( "%s?oauth_consumer_key=%s&oauth_token=%s", $req_token ['login_url'], $req_token ['oauth_consumer_key'], $req_token ['oauth_token'] );
print $login_url . "\n";
| d81a68a19bd372df3626ac8903d3e7324e731bc6 | [
"PHP"
] | 2 | PHP | sirshurf/phpetsy_sdk | 90b10e31e5585af8ad57b4d25da90bd552f2dc2d | 039ed26f80e60d4f725947d5cb2578911dd90e96 |
refs/heads/main | <file_sep> $(document).ready(function () {
//Cargo la página con el select inicializado
$.get("xml/ClientesXML.xml", function (data) {
var select = $("#selectempleados");
var clientes = $(data).find("CLIENTE");
var html = "";
clientes.each(function () {
var nombre = $(this).find("NOMBRE").text();
var id = $(this).attr("IDCLIENTE");
var opt = $("<option>");
opt.attr("value", id);
opt.text(nombre);
select.append(opt);
});
select.change(function () {
var html = "";
$("option").each(function () {
if ($(this).is(":selected")) {
var id = $(this).attr("value");
//alert(id);
//AGARRO TODO EL ELEMENTO CLIENTE
var cliente = $(data).find("CLIENTE[IDCLIENTE=" + id + "]");
var nombre = cliente.find("NOMBRE").text();
var direccion = cliente.find("DIRECCION").text();
var email = cliente.find("EMAIL").text();
var cp = cliente.find("CODIGOPOSTAL").text();
var paginaweb = cliente.find("PAGINAWEB").text();
var img = cliente.find("IMAGENCLIENTE").text();
html += "<h5> Nombre: " + nombre + "</h5><h5> Dirección: " + direccion + "</h5><h5> Email: " + email + "</h5><h5> Código postal: " + cp + "</h5><h5> Página Web: " + paginaweb + "</h5><br><img class='tamaño' class='img-thumbnail' src=" + img + " ></img>";
}
$("#datooficio").html(html);
}); //fin each option
});
})//fin get
});//fin ready<file_sep># tajamar_jquery
Proyectos Jquery
<file_sep>var Empleado = function(idEmpleado,apellido,oficio,fechaalta,salario,departamento){
this.idempleado= idEmpleado;
this.apellido = apellido;
this.oficio = oficio;
this.fechaalta = fechaalta;
this.salario = salario;
this.departamento = departamento;
var objeto = this;
this.salarioAnual = function(){
return this.salario * 12;
}
this.antiguedad = function(){
var anioParse = this.fechaalta.substr(6);
var actual = new Date();
var anio = actual.getFullYear(); // --> 2020
var dif = parseInt(anio) - parseInt(anioParse);
return dif;
}
this.salarioTotal = function(){
return this.antiguedad() * this.salarioAnual();
}
} | 825f05287aa2b5de542f41645689275ad8a539d7 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | VictoriaCastroDotta/tajamar_jquery | 947deb739aa78855f48125eef8d871ac46d863f2 | 117d884a7be90221afff943c27cd000b48463bbd |
refs/heads/master | <file_sep># Pull image.
FROM bitnami/mongodb:latest
#docker build -t graphql-course -f Dockerfile .
#docker run -p 27017:27017 --name graphql-course -d mongo<file_sep>import { GraphQLSchema } from 'graphql'
import RootQueryType from './types/rootQueryType'
import mutation from './mutations'
export default new GraphQLSchema({
query: RootQueryType,
mutation
})
<file_sep>import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
const configuration: webpack.Configuration = {
mode: 'development',
entry: './client/index.tsx',
output: {
path: '/',
filename: 'bundle.js'
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['.ts', '.tsx', '.js', 'jsx']
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
},
{
test: /\.(ts|tsx)?$/,
exclude: [/node_modules/],
use: ['ts-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html'
})
]
}
export default configuration
<file_sep>import passport from 'passport'
import { Strategy as LocalStrategy } from 'passport-local'
import User, { IUserModel } from '../models/user'
// SerializeUser is used to provide some identifying token that can be saved
// in the users session. We traditionally use the 'ID' for this.
passport.serializeUser((user: IUserModel, done) => {
done(null, user.id)
})
// The counterpart of 'serializeUser'. Given only a user's ID, we must return
// the user object. This object is placed on 'req.user'.
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user)
})
})
// Instructs Passport how to authenticate a user using a locally saved email
// and password combination. This strategy is called whenever a user attempts to
// log in. We first find the user model in MongoDB that matches the submitted email,
// then check to see if the provided password matches the saved password. There
// are two obvious failure points here: the email might not exist in our DB or
// the password might not match the saved one. In either case, we call the 'done'
// callback, including a string that messages why the authentication process failed.
// This string is provided back to the GraphQL client.
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) {
return done(err)
}
if (!user) {
return done(null, false, { message: 'Invalid Credentials' })
}
user.comparePassword(password, (err: any, isMatch: boolean) => {
if (err) {
return done(err)
}
if (isMatch) {
return done(null, user)
}
return done(null, false, { message: 'Invalid Credentials' })
})
})
})
)
// Creates a new user account. We first check to see if a user already exists
// with this email address to avoid making multiple accounts with identical addresses
// If it does not, we save the existing user. After the user is created, it is
// provided to the 'req.logIn' function. This is apart of Passport JS.
// Notice the Promise created in the second 'then' statement. This is done
// because Passport only supports callbacks, while GraphQL only supports promises
// for async code! Awkward!
const signup = (email: string, password: string, req: any) => {
const user = new User({ email, password })
if (!email || !password) {
throw new Error('You must provide an email and password.')
}
return User.findOne({ email })
.then(existingUser => {
if (existingUser) {
throw new Error('Email in use')
}
return user.save()
})
.then(user => {
return new Promise((resolve, reject) => {
req.logIn(user, (err: any) => {
if (err) {
reject(err)
}
resolve(user)
})
})
})
}
// Logs in a user. This will invoke the 'local-strategy' defined above in this
// file. Notice the strange method signature here: the 'passport.authenticate'
// function returns a function, as its indended to be used as a middleware with
// Express. We have another compatibility layer here to make it work nicely with
// GraphQL, as GraphQL always expects to see a promise for handling async code.
const login = (email: string, password: string, req: any) => {
return new Promise((resolve, reject) => {
passport.authenticate('local', (_, user: IUserModel) => {
if (!user) {
reject('Invalid credentials.')
}
req.login(user, () => resolve(user))
})({ body: { email, password } })
})
}
export { signup, login }
<file_sep>import express from 'express'
import graphqlHTTP from 'express-graphql'
import mongoose from 'mongoose'
import session from 'express-session'
import passport from 'passport'
import connectMongo from 'connect-mongo'
import webpackMiddleware from 'webpack-dev-middleware'
import webpack from 'webpack'
import webpackConfig from '../webpack.config'
// Create a new Express application
const app = express()
const MongoStore = connectMongo(session)
// Replace with your mongoLab URI
const MONGO_URI = 'mongodb://localhost:27017/lyricaldb'
// Mongoose's built in promise library is deprecated, replace it with ES2015 Promise
mongoose.Promise = global.Promise
// Connect to the mongoDB instance and log a message
// on success or failure
mongoose.connect(MONGO_URI)
mongoose.connection
.once('open', () => console.log('Connected to MongoLab instance.'))
.on('error', error => console.log('Error connecting to MongoLab:', error))
import schema from './schema/schema'
// Configures express to use sessions. This places an encrypted identifier
// on the users cookie. When a user makes a request, this middleware examines
// the cookie and modifies the request object to indicate which user made the request
// The cookie itself only contains the id of a session; more data about the session
// is stored inside of MongoDB.
app.use(
session({
resave: true,
saveUninitialized: true,
secret: 'aaabbbccc',
store: new MongoStore({ url: MONGO_URI, autoReconnect: true })
})
)
// Passport is wired into express as a middleware. When a request comes in,
// Passport will examine the request's session (as set by the above config) and
// assign the current user to the 'req.user' object. See also servces/auth.js
app.use(passport.initialize())
app.use(passport.session())
// Instruct Express to pass on any request made to the '/graphql' route
// to the GraphQL instance.
app.use(
'/graphql',
graphqlHTTP({
schema,
graphiql: true
})
)
app.use(webpackMiddleware(webpack(webpackConfig)))
export default app
<file_sep>import { GraphQLObjectType } from 'graphql'
import UserType from './userType'
const RootQueryType = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
resolve(_, _args, req) {
return req.user
}
}
}
})
export default RootQueryType
<file_sep>import bcrypt from 'bcrypt-nodejs'
import mongoose, { Schema, Document, Model } from 'mongoose'
export interface IUserDocument extends Document {
email: string
password: string
}
export interface IUserModel extends IUserDocument {
comparePassword: (
this: IUserModel,
candidatePassword: string,
cb: any
) => null
}
export interface IUser extends Model<IUserModel> {}
// Every user has an email and password. The password is not stored as
// plain text - see the authentication helpers below.
const UserSchema: Schema = new mongoose.Schema({
email: { type: String },
password: { type: String }
})
// The user's password is never saved in plain text. Prior to saving the
// user model, we 'salt' and 'hash' the users password. This is a one way
// procedure that modifies the password - the plain text password cannot be
// derived from the salted + hashed version. See 'comparePassword' to understand
// how this is used.
UserSchema.pre<IUserModel>('save', function(next) {
const user = this
if (!user.isModified('password')) {
return next()
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err)
}
bcrypt.hash(
user.password,
salt,
() => {},
(err, hash) => {
if (err) {
return next(err)
}
user.password = <PASSWORD>
next()
}
)
})
})
// We need to compare the plain text password (submitted whenever logging in)
// with the salted + hashed version that is sitting in the database.
// 'bcrypt.compare' takes the plain text password and hashes it, then compares
// that hashed password to the one stored in the DB. Remember that hashing is
// a one way process - the passwords are never compared in plain text form.
UserSchema.methods.comparePassword = function comparePassword(
this: IUserModel,
candidatePassword: string,
cb: any
) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch)
})
}
const User: IUser = mongoose.model<IUserModel, IUser>('user', UserSchema)
export default User
<file_sep>import gql from 'graphql-tag'
export type CurrentUserResponse = {
user: { id: string; email: string }
}
export default gql`
{
user {
id
email
}
}
`
<file_sep>import { GraphQLObjectType, GraphQLString } from 'graphql'
import UserType from './types/userType'
import { signup, login } from '../services/auth'
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
signup: {
type: UserType,
args: {
email: { type: GraphQLString },
password: { type: GraphQLString }
},
resolve(_, { email, password }, req) {
return signup(email, password, req)
}
},
logout: {
type: UserType,
resolve(_, _args, req) {
const { user } = req
req.logout()
return user
}
},
login: {
type: UserType,
args: {
email: { type: GraphQLString },
password: { type: GraphQLString }
},
resolve(_, { email, password }, req) {
return login(email, password, req)
}
}
}
})
export default mutation
| 67c8ff1aaa9665b914d183a4fd8d5b8d3ab75650 | [
"TypeScript",
"Dockerfile"
] | 9 | Dockerfile | crespocarlos/graphql-auth | d39007701fccaeae9df5a1258d58516e9b1c8d3c | d09d877ff8b30efd11729aa68027b62192380b17 |
refs/heads/master | <file_sep># SimpleShell
Some helpful reading:
http://stephen-brennan.com/2015/01/16/write-a-shell-in-c/
<file_sep>/******************************************************************************
@file SimgpleShell.c
@author <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
@date Thursday, 11/02/2016
@brief
*******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAXIN 512
#define MAXPARA 50
#define MAXPATH 120
#define HISTORY_COUNT 20
#define ALLIAS_COUNT 10
#define NoPError "function takes no parameters"
#define UnExPError "unexpected parameters"
#define PathError "path expected"
#define InValError "invalid input"
#define RangeError "command out of range"
typedef struct {
int number;
char command[MAXIN];
} history_t;
typedef struct {
char name[MAXIN];
char command[MAXIN];
} allias_t;
void invokeHistory(history_t * hist[], char* line, int current) {
char *input = strdup(line);
int number;
if (strcspn(input, "!") == 0) {
if (sscanf(++input, "%d", &number) == 1) {
if (number < 0) {
if (number > (0-HISTORY_COUNT) && number >= (0-current)) {
strncpy(line, hist[(current+number)%HISTORY_COUNT]->command, MAXIN);
}
else printf("error: %s\n", RangeError);
}
else if (number > (current-HISTORY_COUNT) && number <= current) {
strncpy(line, hist[(number-1)%HISTORY_COUNT]->command, MAXIN);
}
else printf("error: %s\n", RangeError);
}
else printf("error: %s\n", InValError);
}
}
void getLine(char *line) {
if (fgets(line, MAXIN, stdin) != NULL)
(line[strlen(line)-1] == '\n')? line[strlen(line)-1] = '\0' : 0;
else {
strcpy(line, "exit");
}
}
void splitLine(char *line, char* strings[]) {
char delim[] = " |><,&;\t";
char* token;
token = strtok(line, delim);
int i = 0;
while (token != NULL) {
strings[i++] = token;
token = strtok(NULL, delim);
}
}
int execute(char* strings[]) {
pid_t pid = fork();
if (pid < 0) {
perror(strings[0]);
return 1;
}
else if (pid == 0) {
execvp(strings[0], strings);
perror(strings[0]);
exit(0);
}
else {
wait(NULL);
return 1;
}
}
char* getPath(char* strings[]) {
char* path;
if (strings[1] != NULL) {
printf("getpath error: %s\n", NoPError);
return "";
}
printf("%s\n",(path = getenv("PATH")));
return path;
}
int setPath(char* strings[]) {
if (strings[2] != NULL) {
printf("setpath error: %s\n", UnExPError);
}
else if (strings[1] == NULL) {
printf("setpath error: %s\n", PathError);
}
else {
char* newPath = strings[1];
if (setenv("PATH", newPath, 1) == 0) return 1;
else perror("setpath error");
}
return 0;
}
void changeDirectory(char* strings[]) {
if (strings[2] != NULL) {
printf("cd error: %s\n", UnExPError);
}
else if (strings[1] == NULL) {
chdir(getenv("HOME"));
} else if (chdir(strings[1]) != 0) perror("cd");
}
void printHistory(history_t *hist[], char* strings[]) {
if (strings[1] != NULL) printf("history error: %s\n", UnExPError);
else {
int current = 0;
int i = 0;
while (hist[i] != NULL && i < HISTORY_COUNT) {
if (current < (hist[i]->number)) {
current = hist[i]->number;
}
i++;
}
i = (current % HISTORY_COUNT);
do {
if (hist[i] != NULL) {
printf("%d: %s\n", hist[i]->number, hist[i]->command);
}
i = ((i + 1) % HISTORY_COUNT);
} while (i != (current % HISTORY_COUNT));
}
}
void addAllias(allias_t* allias[], char* strings[]) {
if (strings[3] != NULL) printf("allias error: %s", UnExPError);
for (int i = 0; i < ALLIAS_COUNT; i++) {
if (allias[i] != NULL) {
if (strcmp(strings[1], allias[i]->name) == 0) {
printf("overwriting allias %s\n", strings[1]);
strncpy(allias[i]->command, strings[2], MAXIN);
return;
}
else if (i == 9) printf("Alliases full!\n");
}
else {
strncpy(allias[i]->name, strings[1], MAXIN);
strncpy(allias[i]->command, strings[2], MAXIN);
}
}
}
void unAllias(allias_t* allias[], char* strings[]) {
if (strings[2] != NULL) printf("unallias error: %s\n", UnExPError);
else for (int i = 0; i < ALLIAS_COUNT; i++) {
if (allias[i] != NULL) {
if (strcmp(strings[1], allias[i]->command) == 0) {
allias[i] == NULL;
}
}
}
}
void processTokens(allias_t* allias[], history_t* hist[], char* strings[], bool* exitShell) {
if ((strcmp("exit", strings[0]) == 0)) {
if (strings[1] != NULL) printf("exit error: %s\n", NoPError);
else *exitShell = true;
}
else if (strcmp("getpath", strings[0]) == 0) {
getPath(strings);
}
else if (strcmp("setpath", strings[0]) == 0) {
setPath(strings);
}
else if (strcmp("cd", strings[0]) == 0){
changeDirectory(strings);
}
else if (strcmp("history", strings[0]) == 0)
printHistory(hist, strings);
else if (strcmp("allias", strings[0]) == 0) {
allias(allias, strings);
}
else if (strcmpe("unallias", strings[0]) == 0) {
unAllias(allias, strings);
}
else execute(strings);
}
void addHistory(history_t* hist[], int* current, char* line) {
history_t *newCommand = malloc(sizeof(history_t));
newCommand->number = *current + 1;
strncpy(newCommand->command, line, MAXIN);
hist[*current % HISTORY_COUNT] = newCommand;
*current = *current + 1;
}
void checkAllias(allias_t* allias[], char* strings[]) {
for (int i = 0; i < ALLIAS_COUNT; i++) {
if (allias[i] != NULL) {
for (int j = 0; j < MAXPARA) {
if (strings[j] != NULL) {
if (strcmp(allias[i]->name, strings[j]) == 0) {
strncpy(strings[j], allias[i]->command, MAXIN);
}
}
}
}
}
}
void runShell(history_t* hist[], int* current) {
char *currentDir = malloc(sizeof(char)*MAXPATH);
char *line = malloc(sizeof(char)*MAXIN);
char *strings[MAXPARA];
memset(strings, 0, sizeof(strings));
allias_t *allias[ALLIAS_COUNT];
memset(allias, 0, sizeof(allias));
bool exitShell = false;
while(!exitShell) {
printf("%s>", getcwd( currentDir, MAXPATH));
getLine(line);
if (strcmp("", line) == 0) continue;
invokeHistory(hist, line, *current);
addHistory(hist, current, line);
splitLine(line, strings);
checkAllias(allias, strings);
processTokens(hist, strings, &exitShell);
memset(strings, 0, sizeof(strings));
}
free(line);
}
int loadHistory(history_t* hist[], int* current){
if( access( "hist_list.txt", F_OK ) != -1 ) {
char* line = malloc(sizeof(int)+(sizeof(char)*MAXIN));
FILE *fp = fopen("hist_list.txt", "r");
if (fp == 0) {
fprintf(stderr, "failed to open hist_list.txt\n");
perror("load");
return 0;
}
while (fgets(line, MAXIN, fp)) {
char* strings[2];
char* tempChar = malloc(sizeof(char)*MAXIN);
splitLine(line, strings);
sscanf(strings[0], "%d", current);
sscanf(strings[1], "%s", tempChar);
addHistory(hist, current, tempChar);
free(tempChar);
}
fclose(fp);
free(line);
return 1;
} else {
fopen("hist_list.txt", "w");
return 0;
}
}
void writeHistory(history_t* hist[]){
FILE *fp;
fp=fopen("hist_list.txt","w");
for(int n=0;n<HISTORY_COUNT;n++) {
if (hist[n] != NULL) fprintf(fp,"%d: %s\n",hist[n]->number, strcat(hist[n]->command, " "));
}
fclose(fp);
}
int main() {
char* path = getenv("PATH");
chdir(getenv("HOME"));
history_t *hist[HISTORY_COUNT];
memset(hist, 0, sizeof(hist));
int current = 0;
loadHistory(hist, ¤t);
runShell(hist, ¤t);
setenv("PATH", path, 1);
writeHistory(hist);
}
| 6503e929bc9226650d0f229cf910f91c28d067b2 | [
"Markdown",
"C"
] | 2 | Markdown | Solln/SimpleShell | 7115b3660a9540d432076d1ef4129f3c48e87b7d | 472a0d3922e356025ff56f8021e3c0077f75420c |
refs/heads/master | <file_sep>platform :ios, '7.0'
pod 'SDWebImage'
pod 'AFNetworking'
<file_sep># -
21世纪周末儿欢乐事的必备神器,吃喝玩乐,应有尽有,快快放下你的烦恼,下载并打开欢乐周末儿来畅想所有愉快吧!
| df91edfa3f8c16ba40942e7bbc69eac721040f85 | [
"Markdown",
"Ruby"
] | 2 | Ruby | BurapaLi/HaoppyWeekDayer | 53d8cea1353441c70593d3db794d3704b69d5022 | eaea874f1abe95bcc4e822f0d8e9605d36b64324 |
refs/heads/master | <repo_name>cataltas/sr_multisignals<file_sep>/min_distance_mm.py
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 13:21:22 2017
@author: Efe
"""
import numpy as np
import matplotlib.pyplot as plt
def dirichlet(f,t):
if t== 0:
return(1)
else:
return(np.sin((2*f+1)*np.pi*t)/ ((2*f+1)*np.sin(np.pi*t) ) )
def dirichlet_1(f,t):
if t==0:
return(0)
else:
return(np.pi/np.sin(np.pi*t) * (np.cos((2*f+1)*np.pi*t )-dirichlet(f,t)*np.cos(np.pi*t) ) )
def build_support(distance, n_spikes, jitter_ratio, jitter_factor):
jitter = distance/jitter_factor;
tspikes_aux = np.linspace(distance/2, (n_spikes+3/2)*distance, num=n_spikes+2 );
#offsets = np.cumsum(jitter*np.random.rand((n_spikes,1))* (np.random.rand((n_spikes,1))<jitter_ratio) );
offsets =0;
tspikes = tspikes_aux[0:n_spikes] + offsets;
return(tspikes, (n_spikes+2)*distance);
def kernel_fit(tspikes, distance, fc, pattern, K):
nspikes = tspikes.size;
t = np.linspace(distance/2, (nspikes+3/2)*distance, 10*nspikes );
t = np.outer(t, np.ones((1, nspikes))) - np.outer(np.ones((t.size, 1)), tspikes);
dirichlet_vec = np.vectorize(dirichlet, otypes=[np.float])
M = dirichlet_vec(fc, t);
dirichlet_1_vec = np.vectorize(dirichlet_1, otypes=[np.float])
M = np.concatenate((M , dirichlet_1_vec(fc,t)), axis=1 );
print(np.shape(M))
return(0)
def main():
repetitions = 2;
jitter_factor = 100;
jitter_ratio=0.75;
fc_vector = np.array([40]); #[30 40 50];
n_spikes=25;
K=1;
distance_vector = [] ;
successes = [];
for ind_fc in range(fc_vector.size ):
fc = fc_vector[ind_fc];
distance_vector.append(np.array([0.64]));#( 0.6:0.01:1 );
successes.append(np.zeros((distance_vector[ind_fc].size,1)));
for ind_distance in range(distance_vector[ind_fc].size):
distance = distance_vector[ind_fc][ind_distance]/fc;
for ind_rep in range(repetitions):
tspikes, interval = build_support(distance, n_spikes, jitter_ratio, jitter_factor);
aux_pattern = np.random.randn(n_spikes,K)+1j*np.random.randn(n_spikes,K);
pattern = aux_pattern/np.matlib.repmat(np.sqrt(np.sum(np.conj(aux_pattern)*aux_pattern,1 )),1,K);
successes[ind_fc][ind_distance] = successes[ind_fc][ind_distance]+kernel_fit(tspikes, distance, fc, pattern,K)
# print(tspikes)
if __name__ == "__main__" :
main()<file_sep>/plt_util.py
"""Tools for plotting diagnostic info."""
from matplotlib import pyplot as plt
import numpy as np
figsize = (8,6)
def plot_trig_poly_magnitude(p, ax=None, points=200, c='blue'):
ax = ax or plt.gca()
ts = np.linspace(0.0, 1.0, points)
values = p(ts)
if len(values.shape) == 1:
ys = np.absolute(values)
else:
ys = np.linalg.norm(values, axis=0)
ax.plot(ts, ys, c=c)
plt.ylabel('N(t)')
def plot_trig_poly_magnitude_der_2ndder(p, support, ax=None, points=200, c='blue'):
ts = np.linspace(0.0, 1.0, points)
values = p(ts)
values_1 = p.derivative(ts)
values_2 = p.derivative2(ts)
N_1 = 2*np.real(np.diagonal(np.matrix(values_1).H.dot(values) ))
N_2 = 2*np.real(np.diagonal(np.matrix(values_2).H.dot(values) )) + 2*(np.diagonal(np.matrix(values_1).H.dot(values_1) ))
plt.figure()
ax = ax or plt.gca()
ax.plot(ts, N_1, c=c)
ax.plot(support, np.zeros(len(support)), 'go', ms = 5)
plt.ylabel('N\'(t)')
print(2*np.real(np.diagonal(np.matrix(p.derivative(support)).H.dot(p(support)) )))
plt.figure()
ax = plt.gca()
ax.plot(ts, N_2, c=c)
ax.plot(support, np.zeros(len(support)), 'go', ms = 5)
plt.ylabel('N\'\'(t)')
print(2*np.real(np.diagonal(np.matrix(p.derivative2(support)).H.dot(p(support)) )) + 2*(np.diagonal(np.matrix(p.derivative(support)).H.dot(p.derivative(support)) )))
def plot_trig_poly_each_interpolant(p, support, ax=None, points=200, c='blue'):
ts = np.linspace(0.0, 1.0, points)
values = p(ts)
vshape = values.shape
if len(vshape) == 1:
plt.figure(0)
ax = ax or plt.gca()
ys = np.absolute(values)
ax.plot(ts, ys, c=c)
else:
for i in range(vshape[0]):
plt.figure(i)
ax = plt.gca()
ys = values[i,:]
ax.plot(ts, np.absolute(ys), c=c)
plot_support_magnitude_lines(support)
plot_magnitude_bounds()
def plot_individual_magnitude(p, support, qs, ts, points=200, plot_Nt = True):
values = p(ts)
plt.figure(figsize=figsize, dpi=100)
ax = plt.gca()
ys = np.linalg.norm(values, axis=0)
if plot_Nt:
ax.plot(ts, ys, c='C0', label = r'$N(t)$')
j=1
for k in [qss-1 for qss in qs]:
ys = values[k,:]
ax.plot(ts, np.absolute(ys), c = 'C'+str(j), label = r'$\Vert q_{%d}(t)\Vert $'%(k+1) )
j = j+1
plot_support_magnitude_lines(support[[qss-1 for qss in qs]], start = 0.9, c = 'C'+str(j) )
j = j+1
ax.axhline(1.0, c = 'C'+str(j))
leg = plt.legend(loc=2, ncol=1, fancybox=True, bbox_to_anchor=(1.03, 1))
leg.get_frame().set_alpha(0.5)
def plot_individual_components(coeffs, support, kernel, kernel_1, qs, ts, hops, diff_color = False):
plt.figure(figsize=figsize, dpi=100)
ax = plt.gca()
j = 1;
n = support.shape[0]
for k in [qss-1 for qss in qs]:
for s in range(max( k - hops, 0), min(k+hops+1, n) ):
alp_k_s = kernel.sum_shifts([-support[s]], [coeffs[4*k*n+s]] ) + kernel.sum_shifts([-support[s]], [coeffs[(4*k+2)*n+s] * 1j])
ax.plot(ts, np.real(alp_k_s(ts)), c = 'C'+str(j), label=r'Re{$\alpha_{%d,%d} K(t-t_{%d}) $}'%(s+1,k+1,s+1) )
if diff_color:
j = j+1
if s == k:
beta_k_s = kernel_1.sum_shifts([-support[s]], [coeffs[(4*k+1)*n+s]] ) + kernel_1.sum_shifts([-support[s]], [coeffs[(4*k+3)*n + s] * 1j] )
ax.plot(ts, np.real(beta_k_s(ts)), '--', c = 'C'+str(j), label = r'Re{$\beta_{%d} K^\prime(t-t_{%d})$}'%(k+1,k+1) )
if diff_color:
j = j+1
if ~diff_color:
j = j+1
plot_support_magnitude_lines(support[[qss-1 for qss in qs]], start = 0.0, c = 'C'+str(j) )
j = j+1
ax.axhline(0.0, c = 'C'+str(j))
ax.axhline(1.0, c = 'C'+str(j))
leg = plt.legend(loc=2, ncol=1, fancybox=True, bbox_to_anchor=(1.03, 1))
leg.get_frame().set_alpha(0.5)
def plot_2ndder_zoom(p, support, q, ts, hops):
values = p(ts)
values_1 = p.derivative(ts)
values_2 = p.derivative2(ts)
n = values_1.shape[0]
plt.figure(figsize=figsize, dpi=100)
ax = plt.gca()
j = 1
y_1 = 2*np.real(np.diagonal(np.matrix(values).H.dot(np.matrix(values_2)) ))
ax.plot(ts, y_1, c = 'C'+str(j), label = r'2Re{$\langle q(t), q^{\prime\prime}(t)\rangle $}' )
j = j+1
N_2 = y_1
for i in range(max( q - hops, 0), min(q + hops+1, n) ):
if i == q:
continue
# j = j+1
else:
y_2_i = 2*(np.diagonal(np.matrix(values_1[i,:]).H.dot(np.matrix(values_1[i,:]) ) ))
ax.plot(ts, y_2_i, c = 'C'+str(j), label = r'$2\Vert q_{%d}(t)\Vert ^2$'%(i))
N_2 = N_2 + y_2_i
j = j+1
ax.plot(ts, N_2, c = 'C'+str(j), label = r'$N^{\prime\prime}(t)$')
j = j+1
ax.plot(support[q-1], 0, 'C'+str(j)+'o', ms = 5)
j = j+1
ax.plot([support[i] for i in range(len(support)) if i!=q-1 ], np.zeros(len(support)-1), 'C'+str(j)+'o', ms = 4)
j = j+1
ax.axhline(0.0, c = 'C'+str(j))
leg = plt.legend(loc=2, ncol=1, fancybox=True, bbox_to_anchor=(1.03, 1))
leg.get_frame().set_alpha(0.5)
def plot_2ndder_bycomponent(p, support, ts, k):
values = p(ts)
values_1 = p.derivative(ts)
values_2 = p.derivative2(ts)
n = values_1.shape[0]
k = k-1
plt.figure(figsize=figsize, dpi=100)
ax = plt.gca()
j = 1
# y_1 = np.real(np.matrix(values_2))[k,:] .T
# ax.plot(ts, y_1, c = 'C'+str(j), label = r'$q_{k,R}^{(2)}(t)$' )
# j = j+1
# y_4 = np.real(np.matrix(values))[k,:].T
# ax.plot(ts, y_4, c = 'C'+str(j), label = r'$q_{k,R}(t)$' )
# j = j+1
# y_5 = np.imag(np.matrix(values))[k,:].T
# ax.plot(ts, y_5, c = 'C'+str(j), label = r'$q_{k,I}(t)$' )
# j = j+1
# y_1 = 2*np.multiply(np.real(np.matrix(values))[k,:], np.real(np.matrix(values_2))[k,:] ).T
# ax.plot(ts, y_1, c = 'C'+str(j), label = r'$2q_{k,R}(t)q_{k,R}^{(2)}(t)$' )
# j = j+1
# y_2 = 2*np.multiply(np.imag(np.matrix(values))[k,:], np.imag(np.matrix(values_2))[k,:] ).T
# ax.plot(ts, y_2, c = 'C'+str(j), label = r'$2q_{k,I}(t)q_{k,I}^{(2)}(t)$' )
# j = j+1
y_3 = 2*np.multiply(np.real(values_1[k,:]), np.real(values_1[k,:])).T
ax.plot(ts, y_3, c = 'C'+str(j), label = r'$2(q_{k,R}^{(1)}(t))^2$' )
j = j+1
# y_4 = 2*np.multiply(np.imag(values_1[k,:]), np.imag(values_1[k,:])).T
# ax.plot(ts, y_4, c = 'C'+str(j), label = r'$2(q_{k,I}^{(1)}(t))^2$' )
# j = j+1
leg = plt.legend(loc=2, ncol=1, fancybox=True, bbox_to_anchor=(1.03, 1))
leg.get_frame().set_alpha(0.5)
plot_support_magnitude_lines(support, start = -0.1*max(np.absolute(y_3)), c = 'C'+str(j) )
def plot_coeffs(coeffs, m, fc):
n = len(coeffs)/4/m;
alphas_real = [coeffs[4*k*n:(4*k+1)*n] for k in range(m)]
betas_real = [fc*coeffs[(4*k+1)*n:(4*k+2)*n] for k in range(m)]
alphas_real = np.reshape(alphas_real, (n,m)).T
betas_real = np.reshape(betas_real, (n,m)).T
alphas_imag = [coeffs[(4*k+2)*n:(4*k+3)*n] for k in range(m)]
betas_imag = [coeffs[(4*k+3)*n:(4*k+4)*n] for k in range(m)]
alphas_imag = np.reshape(alphas_imag, (n,m)).T
betas_imag = np.reshape(betas_imag, (n,m)).T
plt.figure(figsize=[2.5*f for f in figsize], dpi=100)
plt.subplot(221)
plt.imshow(np.absolute(alphas_real))
for (j,i),label in np.ndenumerate(np.around(np.absolute(alphas_real),3)):
plt.text(i,j,label,ha='center',va='center')
plt.ylabel(r'$j$')
plt.xlabel(r'$k$')
plt.title(r'$|\alpha_{jk}|$')
plt.colorbar()
plt.gca().set_xticklabels([int(i+1) for i in plt.gca().get_xticks()])
plt.gca().set_yticklabels([int(i+1) for i in plt.gca().get_yticks()])
plt.subplot(222)
plt.imshow(np.absolute(betas_real))
for (j,i),label in np.ndenumerate(np.around(np.absolute(betas_real),3)):
plt.text(i,j,label,ha='center',va='center')
plt.ylabel(r'$j$')
plt.xlabel(r'$k$')
plt.title(r'$|\beta_{jk}|$')
plt.colorbar()
plt.gca().set_xticklabels([int(i+1) for i in plt.gca().get_xticks()])
plt.gca().set_yticklabels([int(i+1) for i in plt.gca().get_yticks()])
def plot_support_magnitude_lines(support, start= 0.0, height=1.0, ax=None, c='green'):
ax = ax or plt.gca()
ax.vlines(support, start, height, color=c)
def plot_magnitude_bounds(xmin=0.0, xmax=1.0, c='red', ax=None):
ax = ax or plt.gca()
ax.hlines([1.0], xmin, xmax, color=c)
<file_sep>/dual_certificates.py
"""Tools for creating interpolation-based dual certificates."""
from trig_poly import TrigPoly, MultiTrigPoly
import mpmath
import numpy as np
from scipy import linalg as sp_linalg
def _interpolator_norm_quadratic_form(support, kernel):
"""Quadratic form calculating L2 norm of interpolator from coefficients."""
n = support.shape[0]
kernel_1 = kernel.derivative()
kernel_inners = kernel.inners_of_shifts(support)
kernel_1_inners = kernel_1.inners_of_shifts(support)
cross_inners = kernel.inners_of_shifts_and_derivative_shifts(support)
S = np.zeros((4*n, 4*n)).astype(np.complex128)
S[:n, :n] = kernel_inners
S[n:2*n, n:2*n] = kernel_1_inners
S[n:2*n, :n] = cross_inners.T
S[:n, n:2*n] = cross_inners
S[2*n:3*n, 2*n:3*n] = kernel_inners
S[3*n:, 3*n:] = kernel_1_inners
S[3*n:, 2*n:3*n] = cross_inners.T
S[2*n:3*n, 3*n:] = cross_inners
# TODO: Make sure it's ok to cast to real here
S = (S + S.T).real * 0.5
return S
def _interpolator_linear_constraints(support, sign_pattern, kernel):
"""Build linear constraint data for tangent plane derivative problem."""
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_1 = kernel.derivative()
kernel_2 = kernel_1.derivative()
kernel_values = kernel(time_deltas)
kernel_1_values = kernel_1(time_deltas)
kernel_2_values = kernel_2(time_deltas)
sign_pattern_real = np.real(sign_pattern)
sign_pattern_imag = np.imag(sign_pattern)
zeros = np.zeros((n, n))
problem_mx_rows = []
problem_obj_cols = []
for k in range(m):
# Row of real part constraint
row1 = []
for _ in range(4 * k):
row1.append(zeros)
row1.append(kernel_values)
row1.append(kernel_1_values)
row1.append(zeros)
row1.append(zeros)
for _ in range(4 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
# Row of imaginary part constraint
row2 = []
for _ in range(4 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_values)
row2.append(kernel_1_values)
for _ in range(4 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
gradient_row = []
for k in range(m):
# Row of gradient constraint
single_sign_pattern_real = sign_pattern_real[:, k]
single_sign_pattern_imag = sign_pattern_imag[:, k]
gradient_row.append(
single_sign_pattern_real.reshape((n, 1)) * kernel_1_values)
gradient_row.append(
single_sign_pattern_real.reshape((n, 1)) * kernel_2_values)
gradient_row.append(
single_sign_pattern_imag.reshape((n, 1)) * kernel_1_values)
gradient_row.append(
single_sign_pattern_imag.reshape((n, 1)) * kernel_2_values)
# Objective
problem_obj_cols.append(single_sign_pattern_real)
problem_obj_cols.append(single_sign_pattern_imag)
problem_mx_rows.append(gradient_row)
problem_mx = np.bmat(problem_mx_rows)
problem_obj_cols.append(np.zeros(n))
problem_obj = np.hstack(problem_obj_cols)
return problem_mx, problem_obj
def _interpolator_linear_constraints_kernel_only(
support, sign_pattern, kernel):
"""Build linear constraint data for tangent plane derivative problem."""
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_values = kernel(time_deltas)
sign_pattern_real = np.real(sign_pattern)
sign_pattern_imag = np.imag(sign_pattern)
zeros = np.zeros((n, n))
problem_mx_rows = []
problem_obj_cols = []
for k in range(m):
# Row of real part constraint
row1 = []
for _ in range(2 * k):
row1.append(zeros)
row1.append(zeros)
row1.append(kernel_values)
for _ in range(2 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
# Row of imaginary part constraint
row2 = []
for _ in range(2 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_values)
for _ in range(2 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
for k in range(m):
single_sign_pattern_real = sign_pattern_real[:, k]
single_sign_pattern_imag = sign_pattern_imag[:, k]
# Objective
problem_obj_cols.append(single_sign_pattern_real)
problem_obj_cols.append(single_sign_pattern_imag)
problem_mx = np.bmat(problem_mx_rows)
problem_obj_cols.append(np.zeros(n))
problem_obj = np.hstack(problem_obj_cols)
return problem_mx, problem_obj
def _interpolator_linear_constraints_with_derivatives(
support, sign_pattern, kernel, support_derivatives):
"""Build linear constraint data for fixed derivative problem.
kernel (fn)
support (np.array(s))
sign_pattern (np.array(s, m))
support_derivatives (np.array(s, m))
"""
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_1 = kernel.derivative()
kernel_2 = kernel_1.derivative()
kernel_values = kernel(time_deltas)
kernel_1_values = kernel_1(time_deltas)
kernel_2_values = kernel_2(time_deltas)
sign_pattern_real = np.real(sign_pattern)
sign_pattern_imag = np.imag(sign_pattern)
problem_mx = np.bmat([
[kernel_values, kernel1_values],
[kernel1_values, kernel2_values]])
coeffss = []
for k in range(m):
single_sign_pattern = sign_pattern[:, k]
problem_obj = np.hstack(
[single_sign_pattern, np.zeros(single_sign_pattern.shape[0])])
coeffss.append(np.linalg.solve(problem_mx, problem_obj))
zeros = np.zeros((n, n))
problem_mx_rows = []
problem_obj_cols = []
for k in range(m):
# Row of real part constraint
row1 = []
for _ in range(4 * k):
row1.append(zeros)
row1.append(kernel_values)
row1.append(kernel_1_values)
row1.append(zeros)
row1.append(zeros)
for _ in range(4 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
problem_obj_cols.append(sign_pattern_real[:, k])
# Row of imaginary part constraint
row2 = []
for _ in range(4 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_values)
row2.append(kernel_1_values)
for _ in range(4 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
problem_obj_cols.append(sign_pattern_imag[:, k])
multiplier = 500
for k in range(m):
# Row of derivative real part constraint
row1 = []
for _ in range(4 * k):
row1.append(zeros)
row1.append(kernel_1_values / multiplier)
row1.append(kernel_2_values / multiplier)
row1.append(zeros)
row1.append(zeros)
for _ in range(4 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
problem_obj_cols.append(np.real(support_derivatives[:, k]) / multiplier)
# Row of derivative imaginary part constraint
row2 = []
for _ in range(4 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_1_values / multiplier)
row2.append(kernel_2_values / multiplier)
for _ in range(4 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
problem_obj_cols.append(np.imag(support_derivatives[:, k]) / multiplier)
problem_mx = np.bmat(problem_mx_rows)
problem_obj = np.hstack(problem_obj_cols)
return problem_mx, problem_obj
def _optimize_quadratic_form(S, A, y, multiplier=1.0):
"""Maximize x^T S x subject to Ax = y.
The multiplier is a factor multiplied into S in formulating the linear
problem, which can help mitigate ill-conditioned systems (resulting from
magnitude discrepancies between S and A).
"""
m = A.shape[0]
n = S.shape[0]
# This expression for the solution is derived with Lagrange multipliers,
# the multiplier vector of the constraint Ax = y being in the last m
# coordinates of the result, which we discard.
return np.linalg.solve(
np.bmat([[multiplier * S, A.T], [A, np.zeros((m, m))]]),
np.hstack([np.zeros(n), y]))[:n]
#
# Interpolation functions
#
def interpolate(support, sign_pattern, kernel):
assert support.shape == sign_pattern.shape
# assert np.all(np.absolute(np.absolute(sign_pattern) - 1.0) < 1e-10)
n = support.shape[0]
# time_deltas[i, j] = t_i - t_j
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_values = kernel(time_deltas)
coeffs = np.linalg.solve(kernel_values, sign_pattern)
return kernel.sum_shifts(-support, coeffs)
def interpolate_with_derivative(support, sign_pattern, kernel):
assert support.shape == sign_pattern.shape
assert np.all(np.absolute(np.absolute(sign_pattern) - 1.0) < 1e-10)
n = support.shape[0]
# time_deltas[i, j] = t_i - t_j
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
# NOTE: This is assuming that the kernel is real-valued.
kernel_1 = kernel.derivative()
kernel_2 = kernel_1.derivative()
kernel_values = kernel(time_deltas)
kernel_1_values = kernel_1(time_deltas)
kernel_2_values = kernel_2(time_deltas)
sign_pattern_real = np.real(sign_pattern)
sign_pattern_imag = np.imag(sign_pattern)
zeros = np.zeros((n, n))
# Build linear constraint objects
A = np.bmat([
[kernel_values, kernel_1_values, zeros, zeros],
[zeros, zeros, kernel_values, kernel_1_values],
[sign_pattern_real.reshape((n, 1)) * kernel_1_values,
sign_pattern_real.reshape((n, 1)) * kernel_2_values,
sign_pattern_imag.reshape((n, 1)) * kernel_1_values,
sign_pattern_imag.reshape((n, 1)) * kernel_2_values]]).astype(
np.float64)
y = np.hstack(
[sign_pattern_real,
sign_pattern_imag,
np.zeros(sign_pattern.shape[0])])
# Build objective quadratic form corresponding to interpolator L2 norm:
S = _interpolator_norm_quadratic_form(support, kernel)
coeffs = _optimize_quadratic_form(S, A, y)
return (
kernel.sum_shifts(-support, coeffs[:n]) +
kernel_1.sum_shifts(-support, coeffs[n:2*n]) +
kernel.sum_shifts(-support, coeffs[2*n:3*n] * 1j) +
kernel_1.sum_shifts(-support, coeffs[3*n:] * 1j))
def interpolate_direct(support, sign_pattern, kernel):
"""Toy interpolation model multiplying kernel copies by sign pattern."""
m = sign_pattern.shape[1]
return MultiTrigPoly([
sum(
(kernel.shift(-t) * sign
for t, sign in zip(support, sign_pattern[:, i])),
TrigPoly.zero())
for i in range(m)
])
def interpolate_multidim_fixed_derivatives(
support, sign_pattern, kernel, support_derivatives,
return_coeffs=False):
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
assert support_derivatives.shape == sign_pattern.shape
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_1 = kernel.derivative()
kernel_2 = kernel_1.derivative()
kernel_values = kernel(time_deltas)
kernel_1_values = kernel_1(time_deltas)
kernel_2_values = kernel_2(time_deltas)
multiplier = 100.0
problem_mx = np.bmat([
[kernel_values, kernel_1_values / multiplier],
[kernel_1_values / multiplier, kernel_2_values / multiplier / multiplier]]).real
coeffss = []
for k in range(m):
problem_obj = np.hstack(
[sign_pattern[:, k], support_derivatives[:, k] / multiplier])
coeffss.append(np.linalg.lstsq(problem_mx, problem_obj)[0])
return MultiTrigPoly([
kernel.sum_shifts(-support, coeffs[:n]) +
kernel_1.sum_shifts(-support, coeffs[n:] / multiplier)
for coeffs in coeffss])
problem_mx, problem_obj = (
_interpolator_linear_constraints_with_derivatives(
support, sign_pattern, kernel, support_derivatives))
coeffs = np.linalg.solve(problem_mx, problem_obj)
kernel_coeffs = [
coeffs[4*k*n:(4*k+1)*n] + coeffs[(4*k+2)*n:(4*k+3)*n] * 1j
for k in range(m)]
kernel_derivative_coeffs = [
coeffs[(4*k+1)*n:(4*k+2)*n] + coeffs[(4*k+3)*n:(4*k+4)*n] * 1j
for k in range(m)]
if return_coeffs:
return kernel_coeffs, kernel_derivative_coeffs
else:
return MultiTrigPoly([
kernel.sum_shifts(-support, kernel_coeffs[k]) +
kernel.derivative().sum_shifts(
-support, kernel_derivative_coeffs[k])
for k in range(m)])
def interpolate_multidim_only_kernel(support, sign_pattern, kernel):
"""Interpolate only using kernels, no kernel derivatives or derivative
constraints.
"""
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_values = kernel(time_deltas)
coeffss = []
for k in range(m):
single_sign_pattern = sign_pattern[:, k]
coeffss.append(
np.linalg.solve(kernel_values, single_sign_pattern))
return MultiTrigPoly([
kernel.sum_shifts(-support, coeffs)
for coeffs in coeffss])
def interpolate_multidim_l2_min(
support, sign_pattern, kernel, return_coeffs=False):
"""Interpolation fixing derivatives at interpolated points in tangent
plane of sphere, and minimizing L2 norm of the polynomial subject to this
constraint.
"""
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
n = support.shape[0]
m = sign_pattern.shape[1]
problem_mx, problem_obj = _interpolator_linear_constraints(
support, sign_pattern, kernel)
#
# Build objective quadratic form
#
# S is block-diagonal, with k blocks of size 4n x 4n each of which is the
# same as the objective quadratic form from the one-sample case.
S_diag_block = _interpolator_norm_quadratic_form(support, kernel)
S = np.kron(np.identity(m), S_diag_block)
# This multiplier value is heuristically chosen.
multiplier = (
kernel.derivative().squared_norm() / kernel.squared_norm() * 1e6)
coeffs = _optimize_quadratic_form(
S,
problem_mx,
problem_obj,
multiplier=multiplier)
kernel_coeffs = [
coeffs[4*k*n:(4*k+1)*n] + coeffs[(4*k+2)*n:(4*k+3)*n] * 1j
for k in range(m)]
kernel_derivative_coeffs = [
coeffs[(4*k+1)*n:(4*k+2)*n] + coeffs[(4*k+3)*n:(4*k+4)*n] * 1j
for k in range(m)]
if return_coeffs:
return kernel_coeffs, kernel_derivative_coeffs
else:
return MultiTrigPoly([
kernel.sum_shifts(-support, kernel_coeffs[k]) +
kernel.derivative().sum_shifts(
-support, kernel_derivative_coeffs[k])
for k in range(m)])
def interpolate_multidim_only_kernel_l2_min(
support, sign_pattern, kernel, return_coeffs=False):
"""Interpolation fixing derivatives at interpolated points in tangent
plane of sphere, and minimizing L2 norm of the polynomial subject to this
constraint.
"""
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
n = support.shape[0]
m = sign_pattern.shape[1]
problem_mx, problem_obj = _interpolator_linear_constraints_kernel_only(
support, sign_pattern, kernel)
print problem_mx.shape
#
# Build objective quadratic form
#
# S is block-diagonal, with k blocks of size 4n x 4n each of which is the
# same as the objective quadratic form from the one-sample case.
S_diag_block = kernel.inners_of_shifts(support)
S = np.kron(np.identity(2 * m), S_diag_block)
# This multiplier value is heuristically chosen.
multiplier = (
kernel.derivative().squared_norm() / kernel.squared_norm() * 1e6)
coeffs = _optimize_quadratic_form(
S,
problem_mx,
problem_obj,
multiplier=multiplier)
print coeffs
kernel_coeffs = [
coeffs[2*k*n:2*(k+1)*n] + coeffs[(k+2)*n:(2*k+3)*n] * 1j
for k in range(m)]
kernel_derivative_coeffs = [
coeffs[(4*k+1)*n:(4*k+2)*n] + coeffs[(4*k+3)*n:(4*k+4)*n] * 1j
for k in range(m)]
if return_coeffs:
return kernel_coeffs, kernel_derivative_coeffs
else:
return MultiTrigPoly([
kernel.sum_shifts(-support, kernel_coeffs[k]) +
kernel.derivative().sum_shifts(
-support, kernel_derivative_coeffs[k])
for k in range(m)])
#Fix the derivative to the difference of next and previous samples projected on the tangent plane
def interpolate_multidim_adjacent_samples(
support, sign_pattern, kernel):
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
n = support.shape[0]
m = sign_pattern.shape[1]
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_1 = kernel.derivative()
kernel_2 = kernel_1.derivative()
kernel_values = kernel(time_deltas)
kernel_1_values = kernel_1(time_deltas)
kernel_2_values = kernel_2(time_deltas)
sign_pattern_real = np.real(sign_pattern)
sign_pattern_imag = np.imag(sign_pattern)
#
# Build linear constraint data
#
zeros = np.zeros((n, n))
problem_mx_rows = []
problem_obj_cols = []
rand_scale = 1.0 / np.sqrt(n)
vj_p1_real = np.append(np.asarray([sign_pattern_real[i + 1,:] for i in range(n-1)]), np.zeros((1,m))).reshape((n,m))
vj_m1_real = np.append(np.zeros((1,m)), np.asarray([sign_pattern_real[i ,:] for i in range(n-1)])).reshape((n,m))
# vj_p1_real = np.random.normal(loc=0.0, scale=rand_scale, size=(n, m))
# vj_m1_real = np.random.normal(loc=0.0, scale=rand_scale, size=(n, m))
vj_coeffs_real = np.diagonal((vj_p1_real - vj_m1_real).dot(sign_pattern_real.T) )
vj_p1_imag = np.append(np.asarray([sign_pattern_imag[i + 1,:] for i in range(n-1)]), np.zeros((1,m))).reshape((n,m))
vj_m1_imag = np.append(np.zeros((1,m)), np.asarray([sign_pattern_imag[i ,:] for i in range(n-1)])).reshape((n,m))
# vj_p1_imag = np.random.normal(loc=0.0, scale=rand_scale, size=(n, m))
# vj_m1_imag = np.random.normal(loc=0.0, scale=rand_scale, size=(n, m))
vj_coeffs_imag = np.diagonal((vj_p1_imag - vj_m1_imag).dot(sign_pattern_imag.T) )
for k in range(m):
# Row of real part constraint
row1 = []
for _ in range(4 * k):
row1.append(zeros)
row1.append(kernel_values)
row1.append(kernel_1_values)
row1.append(zeros)
row1.append(zeros)
for _ in range(4 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
# Row of imaginary part constraint
row2 = []
for _ in range(4 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_values)
row2.append(kernel_1_values)
for _ in range(4 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
# Objective
problem_obj_cols.append(sign_pattern_real[:, k])
problem_obj_cols.append(sign_pattern_imag[:, k])
for k in range(m):
row1 = []
for _ in range(4 * k):
row1.append(zeros)
row1.append(kernel_1_values)
row1.append(kernel_2_values)
row1.append(zeros)
row1.append(zeros)
for _ in range(4 * (m - 1 - k)):
row1.append(zeros)
problem_mx_rows.append(row1)
# Row of imaginary part constraint
row2 = []
for _ in range(4 * k):
row2.append(zeros)
row2.append(zeros)
row2.append(zeros)
row2.append(kernel_1_values)
row2.append(kernel_2_values)
for _ in range(4 * (m - 1 - k)):
row2.append(zeros)
problem_mx_rows.append(row2)
# Objective
problem_obj_cols.append(
(vj_p1_real[:, k] - vj_m1_real[:, k] -
np.multiply(vj_coeffs_real, sign_pattern_real[:, k])) / 1000.0)
problem_obj_cols.append(
(vj_p1_imag[:, k] - vj_m1_imag[:, k] -
np.multiply(vj_coeffs_imag, sign_pattern_imag[:, k])) / 1000.0)
problem_mx = np.bmat(problem_mx_rows)
problem_obj = np.hstack(problem_obj_cols)
#
# Solve
#
coeffs = np.linalg.solve(problem_mx, problem_obj)
#Or L2 min
# S_diag_block = _interpolator_norm_quadratic_form(kernel, support)
# S = np.kron(np.identity(m), S_diag_block)
# # This multiplier value is heuristically chosen.
# multiplier = kernel_1.squared_norm() / kernel.squared_norm() * 1e3
# coeffs = _optimize_quadratic_form(
# S,
# problem_mx,
# problem_obj,
# multiplier=multiplier)
return MultiTrigPoly([
(kernel.sum_shifts(-support, coeffs[4*k*n:(4*k+1)*n]) +
kernel_1.sum_shifts(-support, coeffs[(4*k+1)*n:(4*k+2)*n]) +
kernel.sum_shifts(-support, coeffs[(4*k+2)*n:(4*k+3)*n] * 1j) +
kernel_1.sum_shifts(-support, coeffs[(4*k+3)*n:(4*k+4)*n] * 1j))
for k in range(m)])
def interpolate_multidim_0Grad(support, sign_pattern, kernel):
assert support.shape[0] == sign_pattern.shape[0]
assert np.all(
np.absolute(
np.sum(np.absolute(sign_pattern) ** 2, axis=1) - 1.0) < 1e-10)
n = support.shape[0]
m = sign_pattern.shape[1]
kernel1 = kernel.derivative()
kernel2 = kernel1.derivative()
time_deltas = np.outer(support, np.ones(n)) - np.outer(np.ones(n), support)
kernel_values = kernel(time_deltas)
kernel1_values = kernel1(time_deltas)
kernel2_values = kernel2(time_deltas)
problem_mx = np.bmat([
[kernel_values, kernel1_values],
[kernel1_values, kernel2_values]])
coeffss = []
for k in range(m):
single_sign_pattern = sign_pattern[:, k]
problem_obj = np.hstack(
[single_sign_pattern, np.zeros(single_sign_pattern.shape[0])])
coeffss.append(np.linalg.solve(problem_mx, problem_obj))
return MultiTrigPoly([
(TrigPoly(
kernel.freqs,
sum(kernel.coeffs * np.exp(2.0 * np.pi * 1j * kernel.freqs * -t) * c
for c, t in zip(coeffs[:n], support))) +
TrigPoly(
kernel1.freqs,
sum(kernel1.coeffs * np.exp(2.0 * np.pi * 1j * kernel1.freqs * -t) * c
for c, t in zip(coeffs[n:], support))))
for coeffs in coeffss])
return MultiTrigPoly([
sum([kernel.shift(-t) * c for c, t in zip(coeffs[:n], support)],
TrigPoly.zero()) +
sum([kernel1.shift(-t) * c for c, t in zip(coeffs[n:], support)],
TrigPoly.zero())
for coeffs in coeffss])
#
# Validation functions
#
_EPSILON = 1e-7
def validate(support, sign_pattern, interpolator, grid_pts=1e3):
max_deviation = float('-inf')
for i in range(support.shape[0]):
if len(sign_pattern.shape) == 1:
sign_pattern_slice = sign_pattern[i]
else:
sign_pattern_slice = sign_pattern[i, :]
max_deviation = max(
max_deviation,
np.max(
np.absolute(
interpolator(support[i]).T - sign_pattern_slice)))
values_achieved = max_deviation <= _EPSILON
grid = np.linspace(0.0, 1.0, grid_pts)
grid_values = interpolator(grid)
if len(grid_values.shape) == 1:
grid_magnitudes = np.absolute(grid_values)
else:
grid_magnitudes = np.linalg.norm(grid_values, axis=0)
grid_magnitudes = np.ma.array(grid_magnitudes)
for t in support:
left_ix = np.searchsorted(grid, t)
grid_magnitudes[left_ix % grid_magnitudes.shape[0]] = np.ma.masked
grid_magnitudes[(left_ix + 1) % grid_magnitudes.shape[0]] = (
np.ma.masked)
bound_achieved = np.all(grid_magnitudes < 1.0)
status = values_achieved and bound_achieved
return {
'status': status,
'values_achieved': values_achieved,
'max_deviation': max_deviation,
'bound_achieved': bound_achieved}
<file_sep>/phase_transition.py
"""Tools for assessing the recoverability phase transition."""
import dual_certificates
import functools
import numpy as np
def point_probability(support_fn, sign_pattern_fn, kernel, interpolation_fn,
num_experiments=10):
"""Estimates success probability for a single problem distribution."""
num_successes = 0
for _ in range(num_experiments):
support = support_fn()
if support is None:
# num_successes += 1
continue
sign_pattern = sign_pattern_fn()
interpolator = interpolation_fn(support, sign_pattern, kernel)
success = dual_certificates.validate(
support, sign_pattern, interpolator)['status']
if success:
num_successes += 1
return num_successes / float(num_experiments)
def grid_probabilities(
support_fn,
sign_pattern_fn,
kernel,
interpolation_fn,
num_support_points_grid,
minimum_separation_grid,
num_experiments=10,
verbose=False):
results = np.zeros(
(len(num_support_points_grid), len(minimum_separation_grid)))
for i, num_support_points in enumerate(num_support_points_grid):
for j, min_separation in enumerate(minimum_separation_grid):
if verbose:
print i, j
this_support_fn = functools.partial(
support_fn, num_support_points, min_separation=min_separation)
this_sign_pattern_fn = functools.partial(
sign_pattern_fn, num_support_points)
results[i, j] = point_probability(
this_support_fn,
this_sign_pattern_fn,
kernel,
interpolation_fn,
num_experiments=num_experiments)
return results
| 264f452f2bfb0499cbd7594a943f6cb0d0bf7388 | [
"Python"
] | 4 | Python | cataltas/sr_multisignals | 7bea64ffa2aa19169273878e6e07f2a621dcb461 | ecba2c31d77228d360380766ef4aaaaed20b7339 |
refs/heads/main | <repo_name>green47336/dealers_choice_react<file_sep>/server/db/kitty.js
const Sequelize = require("sequelize");
const db = require("./db");
const { STRING } = Sequelize;
const Kitty = db.define("kitties", {
name: {
type: STRING,
unique: true,
allowNull: false,
},
imageUrl: {
type: STRING,
unique: true,
allowNull: false,
},
info: {
type: STRING,
unique: true,
},
});
module.exports = Kitty;
<file_sep>/src/Main.js
import React from "react";
import axios from "axios";
import FactionList from "./FactionList";
import SingleFaction from "./SingleFaction";
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
factions: [],
selectedFaction: {},
};
this.selectFaction = this.selectFaction.bind(this);
this.resetSelection = this.resetSelection.bind(this);
}
async componentDidMount() {
try {
const res = await axios.get("/api/faction");
const factions = res.data;
this.setState({ factions });
} catch (ex) {
console.log(ex);
}
}
async selectFaction(factionId) {
try {
const res = await axios.get(`/api/faction/${factionId}`);
const selectedFaction = res.data;
this.setState({ selectedFaction });
} catch (ex) {
console.log(ex);
}
}
resetSelection() {
const selectedFaction = {};
this.setState({ selectedFaction });
}
render() {
return (
<div id="main" className="container">
{this.state.selectedFaction.id ? (
<SingleFaction
selectedFaction={this.state.selectedFaction}
resetSelection={this.resetSelection}
/>
) : (
<FactionList
factions={this.state.factions}
selectFaction={this.selectFaction}
/>
)}
{this.state.selectedFaction.id ? (
<p onClick={() => this.resetSelection()}>
Click here to return to factions
</p>
) : (
""
)}
</div>
);
}
}
<file_sep>/server/db/index.js
const db = require("./db");
const Kitty = require("./kitty.js");
const Pupper = require("./pupper.js");
const Faction = require("./faction.js");
Kitty.belongsTo(Faction, { as: "faction" });
Faction.hasMany(Kitty, { as: "kitties", foreignKey: "factionId" });
Pupper.belongsTo(Faction, { as: "faction" });
Faction.hasMany(Pupper, { as: "puppers", foreignKey: "factionId" });
module.exports = {
db,
Kitty,
Pupper,
Faction,
};
<file_sep>/server/main.js
const PORT = 3000;
const server = require("./index");
const { db } = require("./db");
const init = async () => {
try {
await db.sync();
server.listen(PORT, () =>
console.log(`Listening on port ${PORT}: http://localhost:${PORT}/`)
);
} catch (ex) {
console.log(`Something went wrong.`, ex);
}
};
init();
<file_sep>/bin/seed.js
const { db, Kitty, Pupper, Faction } = require("../server/db");
const seed = async () => {
await db.sync({ force: true });
//Factions
const alliance = await Faction.create({
name: "canine alliance",
imageUrl: "alliance.jpg",
});
const monarchy = await Faction.create({
name: "feline monarchy",
imageUrl: "monarchy.jpg",
});
const horrors = await Faction.create({
name: "the horrors",
imageUrl: "horrors.jpg",
});
//Kitties
const sirHarrisonIv = await Kitty.create({
name: "<NAME>",
imageUrl: "kitty3.jpg",
info: "<NAME> is the faction leader of the feline monarchy. it has only been 2 year since he ascended the throne after his father's mysterious death. the horrors coincidentally arrived shortly after and have tested the new ruler's mettle.",
factionId: monarchy.id,
});
const charles = await Kitty.create({
name: "charles",
imageUrl: "kitty1.jpg",
info: "your average kittizen in the feline monarchy. innocent, adorable, and determined. ted is his older brother.",
factionId: monarchy.id,
});
const ted = await Kitty.create({
name: "ted",
imageUrl: "kitty2.png",
info: "a strange, self-absorbed kitty who cares little for current events. ted mostly fills his days with hunting, screaming, and critiquing literary works. charles is his younger brother.",
factionId: monarchy.id,
});
const redacted = await Kitty.create({
name: "[REDACTED]",
imageUrl: "kitty0.jpeg",
info: "not much is known about [REDACTED]. the only thing we do know is that it was the original horror. wherever it goes, more are sure to follow.",
factionId: horrors.id,
});
//Puppers
const pupper1 = await Pupper.create({
name: "doug",
imageUrl: "pupper1.jpg",
info: "leader of the canine alliance. very cool dude.",
factionId: alliance.id,
});
const pupper2 = await Pupper.create({
name: "poppy",
imageUrl: "pupper2.jpg",
info: "just the sweetest little thing. would gladly sacrifice the lives of others for the cause.",
factionId: alliance.id,
});
const pupper3 = await Pupper.create({
name: "ranger",
imageUrl: "pupper3.jpg",
info: "the lawman of the realm.",
factionId: alliance.id,
});
const pupper0 = await Pupper.create({
name: "gemini",
imageUrl: "pupper0.jpg",
info: "while originally thought two be two distinct beings, it is now understood to be one.",
factionId: horrors.id,
});
const pupper01 = await Pupper.create({
name: "shank",
imageUrl: "pupper01.jpg",
info: "these photos of shank are a dime a dozen. it's said you'll only be able to snap a photo at the expense of your own life.",
factionId: horrors.id,
});
db.close();
console.log(`Seed successful`);
};
seed().catch((ex) => {
db.close();
console.log(`
Seed unsucessful:
${ex.message}
${ex.stack}
`);
});
<file_sep>/server/api/faction.js
const router = require("express").Router();
const { Faction, Kitty, Pupper } = require("../db");
router.put("/", async (req, res, next) => {
console.log("lol");
});
router.get("/", async (req, res, next) => {
try {
res.send(
await Faction.findAll({
include: [
{
model: Kitty,
as: "kitties",
},
{
model: Pupper,
as: "puppers",
},
],
})
);
} catch (ex) {
next(ex);
}
});
router.get("/:id", async (req, res, send) => {
try {
res.send(
await Faction.findByPk(req.params.id, {
include: [
{
model: Kitty,
as: "kitties",
},
{
model: Pupper,
as: "puppers",
},
],
})
);
} catch (ex) {
next(ex);
}
});
module.exports = router;
<file_sep>/server/index.js
const path = require("path");
const express = require("express");
const app = express();
module.exports = app;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "..", "public")));
app.use("/dist", express.static(path.join(__dirname, "..", "dist")));
app.use("/api", require("./api"));
app.get("/", (req, res, next) => {
res.sendFile(path.join(__dirname, "..", "src", "index.html"));
});
app.use((ex, req, res, next) => {
console.error(ex);
console.error(ex.stack);
res.status(ex.status || 500).send(ex.message || "No clue bro.");
});
<file_sep>/src/SingleFaction.js
import React from "react";
const SingleFaction = (props) => {
const { selectedFaction } = props;
const { kitties, puppers } = selectedFaction;
const all = kitties.concat(puppers);
//const { name, imageUrl, info } = selectedFaction;
return (
<div className="single-faction">
{all.map((individual) => {
return (
<div key={individual.imageUrl}>
<img src={`${individual.imageUrl}`} />
<p>{individual.name}</p>
{/* <li>{individual.info}</li> */}
</div>
);
})}
</div>
);
};
export default SingleFaction;
| 900cd62f13188ef62e9f4befae57f1596d8e592f | [
"JavaScript"
] | 8 | JavaScript | green47336/dealers_choice_react | ec0f4f1df0087a7281a2e4861d91f611cb1eecb8 | 7f2f2672b16475a023c0aac345150952923932a2 |
refs/heads/master | <file_sep>
def rec_sum(root, depth):
ans = depth
for el in root.values():
ans += rec_sum(el, depth + 1)
return ans
def find_path(root, target):
for lab, sub in root.items():
if lab == target:
return [lab]
res = find_path(sub, target)
if res:
return [lab, *res]
return None
def task1(tree):
print(rec_sum(tree, 0))
def task2(tree):
pa = find_path(tree, 'SAN')
pb = find_path(tree, 'YOU')
lca_depth = 0
for ea, eb in zip(pa, pb):
if ea != eb:
break
lca_depth += 1
print(len(pa) + len(pb) - lca_depth * 2 - 2)
if __name__ == '__main__':
tree = {}
while 1:
try:
par, sub = input().strip().split(')')
except EOFError:
break
if par not in tree:
tree[par] = {}
if sub not in tree:
tree[sub] = {}
tree[par][sub] = tree[sub]
# task1(tree['COM'])
task2(tree['COM'])
<file_sep>
def task1():
c = 0
while 1:
try:
x = int(input())
except EOFError:
break
c += x // 3 - 2
return c
def task2():
c = 0
while 1:
try:
x = int(input())
except EOFError:
break
while x >= 6:
x = x // 3 - 2
c += x
return c
if __name__ == '__main__':
# task1()
task2()
print(c)
<file_sep>
dmap = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0),
'R': (1, 0),
}
def task1(d1, d2):
pts = set()
cx, cy = 0, 0
for s in d1:
c = s[0]
n = int(s[1:])
dx, dy = dmap[c]
for _ in range(n):
cx += dx
cy += dy
pts.add((cx, cy))
ints = set()
cx, cy = 0, 0
for s in d2:
c = s[0]
n = int(s[1:])
dx, dy = dmap[c]
for _ in range(n):
cx += dx
cy += dy
if (cx, cy) in pts:
ints.add((cx, cy))
print(min(map(lambda z: abs(z[0]) + abs(z[1]), ints)))
def task2(d1, d2):
pts = {}
cx, cy = 0, 0
step = 0
for s in d1:
c = s[0]
n = int(s[1:])
dx, dy = dmap[c]
for _ in range(n):
cx += dx
cy += dy
step += 1
pts[(cx, cy)] = step
ints = {}
cx, cy = 0, 0
step = 0
for s in d2:
c = s[0]
n = int(s[1:])
dx, dy = dmap[c]
for _ in range(n):
cx += dx
cy += dy
step += 1
if (cx, cy) in pts:
ints[(cx, cy)] = step + pts[(cx, cy)]
print(min(ints.values()))
if __name__ == '__main__':
d1 = input().strip().split(',')
d2 = input().strip().split(',')
# task1(d1, d2)
task2(d1, d2)
<file_sep>
def run(d, inp):
p = 0
while 1:
instr = d[p] % 100
ia = d[p] // 100 % 10
ib = d[p] // 1000 % 10
ix = d[p] // 10000 % 10
if instr == 1:
# ADD
a, b, x = d[p+1:p+4]
if ix:
print('Error: invalid instr %d: output not in position mode!' % d[p])
return None
d[x] = (a if ia else d[a]) + (b if ib else d[b])
p += 4
elif instr == 2:
# MUL
a, b, x = d[p+1:p+4]
if ix:
print('Error: invalid instr %d: output not in position mode!' % d[p])
return None
d[x] = (a if ia else d[a]) * (b if ib else d[b])
p += 4
elif instr == 3:
# INPUT
dst = d[p+1]
if ia:
print('Error: invalid instr %d: dest not in position mode!' % d[p])
return None
print('INPUT [%d] -> %d' % (inp, dst))
d[dst] = inp
p += 2
elif instr == 4:
# OUTPUT
src = d[p+1]
print('OUTPUT <- %d' % (src if ia else d[src]))
p += 2
elif instr == 5:
# JT
test, jmp = d[p+1], d[p+2]
if (test if ia else d[test]) != 0:
p = jmp if ib else d[jmp]
else:
p += 3
elif instr == 6:
# JF
test, jmp = d[p+1], d[p+2]
if (test if ia else d[test]) == 0:
p = jmp if ib else d[jmp]
else:
p += 3
elif instr == 7:
# LT
a, b, x = d[p+1:p+4]
if ix:
print('Error: invalid instr %d: output not in position mode!' % d[p])
return None
d[x] = 1 if (a if ia else d[a]) < (b if ib else d[b]) else 0
p += 4
elif instr == 8:
# EQ
a, b, x = d[p+1:p+4]
if ix:
print('Error: invalid instr %d: output not in position mode!' % d[p])
return None
d[x] = 1 if (a if ia else d[a]) == (b if ib else d[b]) else 0
p += 4
elif d[p] % 100 == 99:
return d[0]
else:
print('Unknown instruction %d' % d[p])
return None
def task1(d):
run(d, 1)
def task2(d):
run(d, 5)
if __name__ == '__main__':
d = list(map(int, input().strip().split(',')))
# task1(d)
task2(d)
<file_sep>
def run(d):
p = 0
while 1:
if d[p] == 1:
a, b, x = d[p+1:p+4]
d[x] = d[a] + d[b]
p += 4
elif d[p] == 2:
a, b, x = d[p+1:p+4]
d[x] = d[a] * d[b]
p += 4
elif d[p] == 99:
return d[0]
else:
return None
def task1(d):
d[1] = 12
d[2] = 2
print(run(d))
def task2(d):
for i in range(0, 100):
for j in range(0, 100):
d_copy = d[:]
d_copy[1] = i
d_copy[2] = j
out = run(d_copy)
if out != 19690720:
continue
print(i, j)
return
if __name__ == '__main__':
d = list(map(int, input().strip().split(',')))
# task1(d)
task2(d)
<file_sep>
def task1(d1, d2):
cnt = 0
for i in range(d1, d2+1):
s = str(i)
has_double = False
prev = chr(ord('0')-1)
ok = True
for c in s:
if c == prev:
has_double = True
elif c < prev:
ok = False
break
prev = c
if ok and has_double:
cnt += 1
print(cnt)
def task2(d1, d2):
cnt = 0
for i in range(d1, d2+1):
s = str(i)
has_exactly_double = False
streak = 0
prev = chr(ord('0')-1)
ok = True
for c in s:
if c == prev:
streak += 1
else:
if streak == 1:
has_exactly_double = True
streak = 0
if c < prev:
ok = False
break
prev = c
if streak == 1:
has_exactly_double = True
if ok and has_exactly_double:
cnt += 1
print(i)
print(cnt)
if __name__ == '__main__':
d1, d2 = map(int, input().strip().split('-'))
# task1(d1, d2)
task2(d1, d2)
| d539d7d7e7b0a18ad24fc441bbd1bfc2e718a57d | [
"Python"
] | 6 | Python | andy0130tw/advent-of-code-2019 | aeaeb50db3170e619aef41756ce0608793a64baa | 4eb74eb795ea5b8e504aa0cef7fa3957892e404a |
refs/heads/master | <file_sep>import random
print(" THE INSTRUCTIONS ")
print("_______________________________________________________________________")
print("SUBTRACT SQUARE. This is a two-player mathematical game of strategy")
print("It is played by two people with a pile of coins ")
print("The players take turns removing coins from the pile")
print("Always removing a non-zero square number of coins (1, 4, 9, 16, …)")
print("The player who removes the last coin wins.")
print("_______________________________________________________________________")
print("To Play Against Human Enter 1 ")
print("To Play Against Computer Enter 2 ")
c=[4,9,16,25,1,36,49,64,81]
t=len(c)
x=int(input("Enter Number :" ))
#against human
if x==1:
print("Enter 1 To Input The Number Of Coins ")
print("Enter 2 To Input Random Select Coins ")
a=int(input("Enter Number :"))
if a==1:
y=int(input("Eter The Amount Of Coins : ") )
print("The Amount Of Coins Is :\n ", y)
else:
y=random.randint(25,100)
print("The Amount Of Coins Is :\n ",y)
while y!=0 :
for i in range(t):
b=int(input(" Player One Enter Square Number:"))
if b in c:
if b<=y:
y=y-b
if y<=0:
print("Player One win ")
print("game end")
else:
print("The Amount Of Coins Is :\n ", y)
break
else:
print("The number you have entered is bigger than coins ")
print("Enter Square Number Less or Equal to The coins ")
continue
else:
print("The number you have entered is not square ")
continue
while y!=0:
b=int(input(" Player Two Enter Square Number:"))
if b in c:
if b<=y:
y=y-b
if y<=0:
print("Player Two win ")
print("game end")
g=int(input())
break
else:
print("The Amount Of Coins Is :\n ", y)
break
else:
print("The number you have entered is bigger than coins ")
print("Enter Square Number Less or Equal to The coins ")
continue
else:
print("The number you have entered is not square ")
continue
#against computer
if x == 2:
print("Against Comuter")
print("Enter 1 To Input The Number Of Coins ")
print("Enter 2 To Input Random Coins ")
a=int(input("Enter Number :"))
if a==1:
y=int(input("Enter The Amount Of Coins : ") )
print("The Amount Of Coins Is :\n ", y)
else:
y=random.randint(25,100)
print("The Amount Of Coins Is :\n ",y)
while y!=0:
for i in range(t):
b=int(input(" Player One Enter Square Number:"))
if b in c :
if b<=y:
y=y-b
if y<=0:
print("Player One win ")
print("game end")
break
else:
print("The Amount Of Coins Is :\n ", y)
break
else:
print("The number you have entered is bigger than coins ")
print("Enter Square Number Less or Equal to The coins ")
continue
else:
print("The number you have entered is not square ")
continue
for k in range (50):
b=random.choice(c)
if b <=y :
print(" The Computer Entered :\n ",b )
y=y-b
if y <=0:
print("Computer win ")
print("game end")
else:
print("The Amount Of Coins Is :\n ", y)
break
else:
continue
<file_sep># suabtraction-square-game
python code
| fe764c8b0863d8c4a0c34f809a1f268433437020 | [
"Markdown",
"Python"
] | 2 | Python | bahaeldin/suabtraction-square-game | 51533135add3110eb776bb27848e83e0c803c92b | 009d674c397fa6518821beafbaacbc81c239a7b2 |
refs/heads/master | <file_sep>#!/bin/sh
find ./source/ -type f -iname "*.xml" | xargs -I '{}' xmllint --format '{}' --output '{}'
<file_sep>task xmllint(type: Exec) {
commandLine './xmllint.sh'
}
task odt(type: Zip) {
from 'source/'
include '*'
include '*/*'
include '*/*/*'
include '*/*/*/*'
archiveName 'macro.odt'
}
task unzip(type: Copy) {
def zipFile = file('macro.odt')
def outputDir = file('source')
from zipTree(zipFile)
into outputDir
include '*'
include '*/*'
include '*/*/*'
include '*/*/*/*'
}
task raw(dependsOn: ['unzip', 'xmllint'])
| 197be00e99f09ec81f6552800ad872e573c84ee8 | [
"Shell",
"Gradle"
] | 2 | Shell | litvinovg/editors-basic-macro | 46a4108ba1a51f0d982c1185d6341d9c9c699b70 | 65d1ddb9587f77de8e828f481d4372a3c7d4805b |
refs/heads/master | <file_sep>/**
* 绘制一个节点
* ctx:上下文
* node:节点数据{desc: string,count:number,percent:number,pieData:[]}
* x:节点中心横坐标
* y:节点中心纵坐标
* width:节点容器宽度
* height:节点容器高度
* radius:外环半径
* innerRadius:内环半径
* scale:缩放比例
* mousePoint:鼠标对象
* isRingRange:鼠标是否在圆环上
* treePage:当前页面对象
*/
export const drawNode = (ctx, node, x, y, width = 300, height = 150,
radius, innerRadius, pieColor, scale, mousePoint, isRingRange, treePage) => {
//绘制节点容器,一个矩形框
ctx.strokeStyle = '#E9E9E9';
ctx.lineWidth = 1.5 * scale;
width = width * scale;
height = height * scale;
ctx.strokeRect(x - width / 2, y - height / 2, width, height);
//绘制第一行显示文本
let fontSize = 12 * scale;
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#9c9c9c";
let textX1 = x - width * 0.25;
let textY1 = y - 14 * scale;
ctx.fillText(node.desc, textX1, textY1);
//绘制第二行显示文本
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#7E317E";
let textX2 = x - width * 0.25;
let textY2 = y + 14 * scale;
ctx.fillText(node.count, textX2, textY2);
drawRingPie(ctx, node, x + width * 0.25, y, radius * scale, innerRadius * scale,
pieColor, scale, mousePoint, isRingRange, treePage);
// ctx.restore();
}
/**
* 画环形饼图
* ctx:上下文
* node:节点信息
* x:饼图圆心横坐标
* y:饼图圆心纵坐标
* radius:外层圆半径
* innerRadius:内层圆半径
* color:饼图颜色数组
* scale:缩放比例
* mousePoint:鼠标对象
* isRingRange:鼠标是否在圆环上
* treePage:当前页面对象
*/
export const drawRingPie = (ctx, node, x, y, radius, innerRadius, color, scale = 1, mousePoint = null, isRingRange, treePage) => {
//画外层圆环
ctx.save();
ctx.translate(x, y);
ctx.scale(scale, scale);
let startRadian = 0, endRadian = 0;
for (let i = 0; i < node.pieData.length; i++) {
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
endRadian += node.pieData[i].value * Math.PI * 2;
//以圆心为起点,0度开始绘制一个圆
ctx.arc(0, 0, radius, startRadian, endRadian, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = color[i];
ctx.fill();
startRadian = endRadian;
if (mousePoint && ctx.isPointInPath(mousePoint.x, mousePoint.y) && isRingRange) {//鼠标点击了并且在该部分圆环上
ctx.clearRect(-radius, -radius, 2 * radius, 2 * radius);
drawDynamicPie(ctx, node, radius, color, i);//重绘圆
let tipNode = {
desc: node.desc,
name: node.pieData[i].name,
value: floatMul(node.pieData[i].value, 100) + "%"
}
treePage.setState({ tipNode: tipNode, mousePosition: { x: mousePoint.clientX, y: mousePoint.clientY } });
}
}
/**
* 画内层圆
*/
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
//以圆心为起点,0度开始绘制一个圆
ctx.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = "#ffffff";
ctx.stroke();
ctx.fill();
ctx.restore();
/**
* 环心填充文字
*/
let fontSize = 12 * scale;
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#000";
ctx.fillText(node.percent + "%", x, y);
}
//绘制动态圆
const drawDynamicPie = (ctx, node, radius, color, index, treePage) => {
let startRadian = 0, endRadian = 0;
for (let i = 0; i < node.pieData.length; i++) {
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
endRadian += node.pieData[i].value * Math.PI * 2;
//以圆心为起点,0度开始绘制一个圆
if (index == i) {
ctx.arc(0, 0, radius + 5, startRadian, endRadian, false);
} else {
ctx.arc(0, 0, radius, startRadian, endRadian, false);
}
ctx.closePath();
// 填充颜色
ctx.fillStyle = color[i];
ctx.fill();
startRadian = endRadian;
}
}
/**
* 画连接线
* ctx:上下文
* x0:起始节点的横坐标
* y0:起始节点的纵坐标
* x1:终止节点的横坐标
* y1:终止节点的纵坐标
* height:节点容器高度
*/
export const drawLine = (ctx, x0, y0, x1, y1, height = 150) => {
ctx.strokeStyle = "#169BD5";
ctx.beginPath();
ctx.lineWidth = 1.5;
ctx.moveTo(x0, y0 + height / 2);
if (x1 !== x0) {//折线
ctx.lineTo(x0, y0 + (y1 - y0) / 2);
ctx.stroke();
ctx.moveTo(x0, y0 + (y1 - y0) / 2);
ctx.lineTo(x1, y0 + (y1 - y0) / 2);
ctx.stroke();
ctx.moveTo(x1, y0 + (y1 - y0) / 2);
ctx.lineTo(x1, y1 - height / 2);
ctx.stroke();
//绘制箭头
ctx.moveTo(x1, y1 - height / 2);
ctx.lineTo(x1 - 5, y1 - (height / 2) - 5);
ctx.lineTo(x1 + 5, y1 - (height / 2) - 5);
ctx.closePath();
ctx.fill();
} else {//直线
ctx.lineTo(x1, y1 - height / 2);
ctx.stroke();
//绘制箭头
ctx.moveTo(x1, y1 - height / 2);
ctx.lineTo(x1 - 5, y1 - (height / 2) - 5);
ctx.lineTo(x1 + 5, y1 - (height / 2) - 5);
ctx.closePath();
ctx.fill();
}
}
export const drawFromLine = (ctx, x0, y0, x1, y1, width = 200) => {
ctx.strokeStyle = "#169BD5";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(x0 + width / 2, y0);
ctx.lineTo(x1 - width / 2, y1);
ctx.stroke();
//绘制箭头
ctx.moveTo(x1 - width / 2, y1);
ctx.lineTo(x1 - width / 2 - 5, y1 - 5);
ctx.lineTo(x1 - width / 2 - 5, y1 + 5);
ctx.closePath();
ctx.fillStyle = "#169BD5";
ctx.fill();
}
//生成uuid
export const createGuid = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//获取最大深度
export const getMaxDepth = (treeData) => {
let depth = 1;
for (let node of treeData) {
depth = Math.max(depth, node.depth);
}
return depth;
}
//数字处理为每3位逗号隔开
export const dealNumber = (num) => {
if (num != 0 && num) {
num = num + "";
let decimalsStr = "";
let splitList = num.split(".");
//先处理小数部分
if (splitList[1]) {
//如果有2位小数则保留2位,只有1位则添0
decimalsStr = decimalsStr.substring(0, 2).length == 2 ? decimalsStr.substring(0, 2) : decimalsStr.substring(0, 2) + "0";
}
//整数部分
let intStrList = splitList[0].split("").reverse().join('').match(/(\d{1,3})/g);
let intStr = intStrList.join(',').split('').reverse().join('');
return intStr + decimalsStr;
}
return num;
}
//设备像素比
export const getPixelRatio = (context) => {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
//点击位置是否在圆环上(数据为列表)
export const isRingPostion = (mousePoint, treeData, nodeWidth, innerRadius, radius) => {
if (!mousePoint) {
return false;
}
let eventX = mousePoint.x;
let eventY = mousePoint.y;
for (let node of treeData) {
//点击位置到圆心的距离,勾股定理计算
let cricleX = node.x + nodeWidth / 4;//圆心x坐标
let cricleY = node.y;
let distanceFromCenter = Math.sqrt(Math.pow(cricleX - eventX, 2)
+ Math.pow(cricleY - eventY, 2))
//是否在圆环上
if (distanceFromCenter > innerRadius && distanceFromCenter < radius) {
return true;
}
}
return false;
}
//点击位置是否在矩形节点上
export const isNodePosition = (mousePoint, treeData, nodeWidth, nodeHeight) => {
if (!mousePoint) {
return false;
}
let eventX = mousePoint.x;
let eventY = mousePoint.y;
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
if (eventX > node.x - nodeWidth / 2 && eventX < node.x + nodeWidth / 2 &&
eventY > node.y - nodeHeight / 2 && eventY < node.y + nodeHeight / 2) {
return true;
}
}
}
return false;
}
//小数乘法
export const floatMul = (a, b) => {
let m = 0, n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1].length;
} catch (error) {
console.log(error)
}
try {
n = e.split(".")[1].length;
} catch (error) {
console.log(error)
}
let maxInt = Math.pow(10, m + n); //将数字转换为整数的最大倍数
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / maxInt;
}
//小数加法
export const floatAdd = (a, b) => {
let m = 0, n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1].length;
} catch (error) {
console.log(error)
}
try {
n = e.split(".")[1].length;
} catch (error) {
console.log(error)
}
let maxInt = Math.pow(10, Math.max(m, n)); //将数字转换为整数的最大倍数
return (floatMul(a, maxInt) + floatMul(b, maxInt)) / maxInt;
}
//小数减法
export const floatSub = (a, b) => {
let m = 0, n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1].length;
} catch (error) {
console.log(error)
}
try {
n = e.split(".")[1].length;
} catch (error) {
console.log(error)
}
let maxInt = Math.pow(10, Math.max(m, n)); //将数字转换为整数的最大倍数
return (floatMul(a, maxInt) - floatMul(b, maxInt)) / maxInt;
}
//小数除法
export const floatDivision = (a, b) => {
let m = 0, n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1].length;
} catch (error) {
console.log(error)
}
try {
n = e.split(".")[1].length;
} catch (error) {
console.log(error)
}
let maxInt = Math.pow(10, Math.max(n, m)); //将数字转换为整数的最大倍数
let aInt = floatMul(a, maxInt);
let bInt = floatMul(b, maxInt);
return aInt / bInt;
}
<file_sep>###1.下载依赖
```
npm install
```
###2.启动项目
```
npm start
```
> 项目启动后的访问路径为:http://localhost:3000/
###3.组件替换入口(App.js)
组件替换入口文件位置为:src\App.js
```js
import React, { Component } from 'react';
import './App.css';
// import CustomTree from './components/familyNum/familyNum';
import CustomTree from './components/customTree/CustomCanvas';
class App extends Component {
render() {
return (
<CustomTree fit={true}/>
);
}
}
export default App;
```
### 4.公共方法文件(TreeNode.js)
公共方法文件位置为:\src\components\common\TreeNode.js
> 项目是由create-react-app脚手架创建的,如有不理解的地方可去查看脚手架文档。<file_sep>import React, { Component } from 'react';
import { drawNode, drawLine, drawRingPie, dealNumber, getPixelRatio, isRingPostion } from '../common/TreeNode';
import underscore from 'underscore';
class PayAbilityCrowdGroupTree extends Component {
constructor(props) {
super(props);
this.state = {
color: ['#bd94ff', '#E9E9E9'],
pieColor: ['#bd94ff', '#FCDA56', '#69D389', '#e295d5', '#62ca9a'],
treeData: this.treeSource(this.props.source) || [],
tipNode: null,
mousePosition: {
x: 0,
y: 0
}
}
}
static defaultProps = {
treeId: 'payAbilityCrowdTree',
source: [
{
id: 1, depth: 1, desc: "T0待转化用户", count: 2321341, percent: 100,
pieData: [{ name: "T0待转化用户", value: "1" }, { name: "其他", value: "0" }],
children: [
{
id: 2, depth: 2, desc: "淘宝来源", count: 2321341, percent: 50,
pieData: [{ name: "淘宝来源", value: "0.5" }, { name: "其他", value: "0.5" }],
children: [
{
id: 21, depth: 3, desc: "普遍性", count: 2321341, percent: 100,
pieData: [{ name: "普遍性", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 22, depth: 3, desc: "低龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 23, depth: 3, desc: "低龄高龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄高龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 24, depth: 3, desc: "低龄中龄高龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄中龄高龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 25, depth: 3, desc: "低龄", count: 2321341, percent: 100,
pieData: [{ name: "低龄", value: "0.3" }, { name: "其他", value: "0.7" }]
},
]
},
{
id: 3, depth: 2, desc: "支付宝来源", count: 2321341, percent: 60,
pieData: [{ name: "支付宝来源", value: "0.6" }, { name: "其他", value: "0.4" }],
children: [
{
id: 31, depth: 3, desc: "普遍性", count: 2321341, percent: 100,
pieData: [{ name: "普遍性", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 32, depth: 3, desc: "低龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 33, depth: 3, desc: "低龄高龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄高龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 34, depth: 3, desc: "低龄中龄高龄未知", count: 2321341, percent: 100,
pieData: [{ name: "低龄中龄高龄未知", value: "0.3" }, { name: "其他", value: "0.7" }]
},
{
id: 35, depth: 3, desc: "低龄", count: 2321341, percent: 100,
pieData: [{ name: "低龄", value: "0.3" }, { name: "其他", value: "0.7" }]
},
]
},
]
}],
fit: false,
width: 1500,
height: 1000,
nodeWidth: 300,
nodeHeight: 150,
radius: 65, //nodeWidth*0.2-10
innerRadius: 40, //nodeWidth*0.2-25
pieRadius: 70,
pieInnerRadius: 50
}
//源数据处理
treeSource(source) {
return source;
}
//为节点添加x,y坐标
dealData(canvas, scale) {
const width = canvas.width;
const height = canvas.height;
let treeData = this.state.treeData;
let depth = 3;
const nodeYSacle = (height - this.props.nodeHeight * scale / 2 - 30 - this.props.pieRadius * scale) * depth / 8;
this.setNodePoint(treeData, width, height, nodeYSacle, scale);
}
//设置节点的x,y坐标
setNodePoint(treeData, width, height, nodeYSacle, scale) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
let depthList = this.getNodeDepathNum(this.state.treeData, node.depth);
if (node.depth < 3) {
let nodeXScale = width / (Math.pow(2, node.depth));
let nodeIndex = depthList.findIndex(item => item.id === node.id);
node.x = nodeXScale * (2 * (nodeIndex + 1) - 1);;
node.y = nodeYSacle * (node.depth - 1) + this.props.nodeHeight * scale / 2 + 15;
} else {
let nodeXScale = (width / 2 - this.props.pieRadius * scale * 2 - 30) / (nodeLength - 1);//30为左右各留15px间距
let nodeIndex = depthList.findIndex(item => item.id === node.id);
if (nodeIndex < nodeLength) {
node.x = nodeXScale * nodeIndex + 15 + this.props.pieRadius * scale;
} else {
node.x = width / 2 + 15 + nodeXScale * (nodeIndex - 5) + this.props.pieRadius * scale;
}
node.y = height - this.props.pieRadius * scale - 15;//第3级为最底层
}
if (node.children) {
this.setNodePoint(node.children, width, height, nodeYSacle, scale);
}
}
}
}
//获取相应深度节点数
getNodeDepathNum(treeData, depth, floorList = []) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
if (node.depth === depth) {
floorList.push(node);
continue;
}
if (node.children) {
this.getNodeDepathNum(node.children, depth, floorList)
}
}
}
return floorList;
}
componentDidMount() {
this.redrawTree(this.state.treeData);
}
redrawTree(treeData) {
let canvas = document.getElementById(this.props.treeId);
let ctx = canvas.getContext('2d');
let ratio = getPixelRatio(ctx);
let scale = 1;
if (this.props.fit) {
if (canvas.parentNode.offsetWidth > 1500) {
canvas.width = canvas.parentNode.offsetWidth * ratio;
canvas.height = this.props.height * scale * ratio;
} else {
scale = canvas.parentNode.offsetWidth / 1500;
canvas.width = canvas.parentNode.offsetWidth * ratio;
canvas.height = this.props.height * scale * ratio;
}
}
this.dealData(canvas, scale)
this.drawTree(ctx, treeData, null, canvas.width, canvas.height, scale);
canvas.addEventListener('mousemove', (e) => {
let eventX = e.clientX - canvas.getBoundingClientRect().left;
let eventY = e.clientY - canvas.getBoundingClientRect().top;
let mousePoint = { x: eventX, y: eventY, clientX: e.clientX, clientY: e.clientY };
let isRingRange = this.isRingRangePostion(mousePoint, treeData, this.props.nodeWidth * scale,
this.props.innerRadius * scale, this.props.radius * scale, this.props.pieRadius * scale, this.props.pieInnerRadius * scale);
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.drawTree(ctx, treeData, null, canvas.width, canvas.height, scale, mousePoint, isRingRange);
if (!isRingRange) {
this.setState({ tipNode: null });
}
}, false)
}
componentWillReceiveProps(nextProps) {
if (!underscore.isEqual(nextProps.source, this.props.source)) {
let newData = this.treeSource(nextProps.source)
this.setState({ treeData: newData }, function () {
this.redrawTree(newData);
});
}
}
isPrevBrother(node) {
let brotherList = this.getNodeDepathNum(this.state.treeData, node.depth);
let nodeIndex = brotherList.findIndex(item => item.id === node.id);
return brotherList[nodeIndex - 1] ? true : false;
}
drawTree(ctx, treeData, parentNode, width, height, scale, mousePoint = null, isRingRange) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
if (node.depth < 3) {
drawNode(ctx, node, node.x, node.y, this.props.nodeWidth, this.props.nodeHeight,
this.props.radius, this.props.innerRadius, this.state.color, scale, mousePoint, isRingRange, this);
if (parentNode) {
drawLine(ctx, parentNode.x, parentNode.y, node.x, node.y, this.props.nodeHeight * scale);
}
if (node.children) {
this.drawTree(ctx, node.children, node, width, height, scale, mousePoint, isRingRange);
if (node.depth === 2) {
const nodeYSacle = (height - this.props.nodeHeight * scale / 2 - 30 - this.props.pieRadius * scale) * 3 / 8;
drawLine(ctx, node.x, node.y, node.x, node.y + nodeYSacle - 3, this.props.nodeHeight * scale);//分割线宽度为3
//画分割横线
ctx.beginPath();
let nodeY = node.y + nodeYSacle - this.props.nodeHeight * scale / 2;
ctx.lineWidth = 3;
if (!this.isPrevBrother(node)) {//第一个元素
ctx.moveTo(15, nodeY);
ctx.strokeStyle = "#9570E5"; //设置线的颜色状态
ctx.lineTo(width / 2 - 15, nodeY);
ctx.stroke();
//说明文字。放在这里是确保只画一次,不重复画
var img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, nodeY - 50, 30, 30);
}
img.src = "https://t.alipayobjects.com/images/rmsweb/T11aVgXc4eXXXXXXXX.svg";
ctx.font = "12px Arial";
let textX2 = 120;
let textY2 = nodeY - 36;
let explain = "待支付能力升级转化人群分组"
ctx.fillText(explain, textX2, textY2);
//画说明下划横线
ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo(0, nodeY - 12)
ctx.lineTo(220, nodeY - 12);
ctx.strokeStyle = "#DBDBDB"; //设置线的颜色状态
ctx.stroke();
} else {
ctx.moveTo(width / 2 + 15, nodeY);
ctx.strokeStyle = "#E16757"; //设置线的颜色状态
ctx.lineTo(width - 15, nodeY);
}
ctx.stroke();
}
}
} else {
const nodeYSacle = (height - this.props.nodeHeight * scale / 2 - 30 - this.props.pieRadius * scale) * 3 / 8;
let nodeY = parentNode.y + nodeYSacle - this.props.nodeHeight * scale / 2;
//画断线
ctx.beginPath();
ctx.moveTo(node.x, nodeY)
if (node.desc.length > 4) {
ctx.lineTo(node.x, nodeY + nodeYSacle / 3 - 14);//断线只有nodeYScale的1/3
} else {
ctx.lineTo(node.x, nodeY + nodeYSacle / 3 - 7);
}
ctx.strokeStyle = "#169BD5";
ctx.stroke();
//写描述
let fontSize = 12;
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
if (node.desc.length > 4) {
ctx.fillText(node.desc.substring(0, 4), node.x, nodeY + nodeYSacle / 3 - 7);
ctx.fillText(node.desc.substring(4), node.x, nodeY + nodeYSacle / 3 + 7);
} else {
ctx.fillText(node.desc, node.x, nodeY + nodeYSacle / 3);
}
//画下半断线
ctx.beginPath();
if (node.desc.length > 4) {
ctx.lineTo(node.x, nodeY + nodeYSacle / 3 + 14);
} else {
ctx.lineTo(node.x, nodeY + nodeYSacle / 3 + 7);
}
ctx.lineTo(node.x, nodeY + nodeYSacle);
ctx.strokeStyle = "#169BD5";
ctx.stroke();
//绘制箭头
ctx.moveTo(node.x, node.y - this.props.pieRadius * scale);
ctx.lineTo(node.x - 5, node.y - this.props.pieRadius * scale - 5);
ctx.lineTo(node.x + 5, node.y - this.props.pieRadius * scale - 5);
ctx.closePath();
ctx.fill();
//画统计数量
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillText(dealNumber(node.count), node.x, node.y - this.props.pieRadius * scale - 20);
//画饼图
//生成0~4的随机数
let numIndex = treeData.findIndex(item => item.id == node.id);
let pieColor = [this.state.pieColor[numIndex], '#E9E9E9']
drawRingPie(ctx, node, node.x, node.y, this.props.pieRadius, this.props.pieInnerRadius, pieColor, scale, mousePoint, isRingRange, this)
}
}
}
}
isRingRangePostion(mousePoint, treeData, nodeWidth, innerRadius, radius, pieRadius, pieInnerRadius) {
if (!mousePoint) {
return false;
}
let nodeLength = treeData.length;
let eventX = mousePoint.x;
let eventY = mousePoint.y;
if (nodeLength > 0) {
for (let node of treeData) {
if (node.depth < 3) {
//点击位置到圆心的距离,勾股定理计算
let cricleX = node.x + nodeWidth / 4;//圆心x坐标
let cricleY = node.y;
let distanceFromCenter = Math.sqrt(Math.pow(cricleX - eventX, 2)
+ Math.pow(cricleY - eventY, 2))
//是否在圆环上
if (distanceFromCenter > innerRadius && distanceFromCenter < radius) {
return true;
}
if (node.children) {
let ring = this.isRingRangePostion(mousePoint, node.children, nodeWidth, innerRadius, radius, pieRadius, pieInnerRadius);
if (ring) {
return true;
}
}
} else {
let distanceFromCenter1 = Math.sqrt(Math.pow(node.x - eventX, 2)
+ Math.pow(node.y - eventY, 2))
if (distanceFromCenter1 > innerRadius && distanceFromCenter1 < radius) {
return true;
}
}
}
}
return false;
}
//获取提示的定位位置
getTipPosition() {
let tipDiv = document.getElementById(`${this.props.treeId}Tip`);
let mousePosition = this.state.mousePosition;
let top1 = mousePosition.y + 12;
let left = mousePosition.x + 12;
if (tipDiv) {
if (mousePosition.x + tipDiv.offsetWidth + 30 > window.innerWidth) {
left = mousePosition.x - 12 - tipDiv.offsetWidth;
}
if (mousePosition.y + tipDiv.offsetHeight + 30 > window.innerHeight) {
top1 = mousePosition.y - 12 - tipDiv.offsetHeight;
}
}
return { top:top1, left:left }
}
render() {
let position = this.getTipPosition();
let tipClass = {
position: 'fixed',
zIndex: 999,
visibility: this.state.tipNode ? 'visible' : 'hidden',
backgroundColor: '#826d6d',
top: position.top,
left: position.left,
padding: '15px',
color: '#fff',
borderRadius: '5px',
textAlign: 'left'
}
return (
<div>
<canvas id={this.props.treeId} width={this.props.width} height={this.props.height}></canvas>
<div style={tipClass} id={`${this.props.treeId}Tip`}>
<div>支付人群分组</div>
<div>{this.state.tipNode ? this.state.tipNode.name : null} : {this.state.tipNode ? this.state.tipNode.value : null}</div>
</div>
</div>
)
}
}
export default PayAbilityCrowdGroupTree;
<file_sep>import React, { Component } from 'react';
import lodash from 'lodash';
const data = {
desc: "自定义图形", //第一行描述文字
count: 2321341, //第二行描述文字
percent: 60, //圆环中心显示数字
pieData: [{ desc: '圆环', name: "A", value: "0.6" }, { desc: '圆环', name: "B", value: "0.4" }],//环图数据
x: 250, //图形中心点在画布的x轴坐标
y: 250 //图形中心点在画布Y轴坐标
}
class CustomCanvas extends Component {
constructor(props) {
super(props);
this.state = {
color: ['#bd94ff', '#48eaa7'],
ratio: 1,
tipNode: null,
mousePosition: {
x: 0,
y: 0
}
}
}
static defaultProps = {
canvasId: 'customCanvas',
data: data,
width: 500,
height: 500,
nodeWidth: 300,
nodeHeight: 150,
radius: 65, //nodeWidth*0.25-10
innerRadius: 40, //nodeWidth*0.25-35
}
componentDidMount() {
this.redrawTree(this.props.data);
}
componentWillReceiveProps(nextProps) {
if (!lodash.isEqual(nextProps.data, this.props.data)) {
this.redrawTree(nextProps.data);
}
}
//重绘
redrawTree(data) {
const canvas = document.getElementById(this.props.canvasId);
const ctx = canvas.getContext('2d');
let ratio = this.getPixelRatio(ctx);
let scale = ratio;
this.setState({ ratio: 1 / ratio });
this.drawNode(ctx, data, data.x, data.y, this.props.nodeWidth, this.props.nodeHeight,
this.props.radius, this.props.innerRadius, this.state.color, scale, null, false, this);
canvas.addEventListener('mousemove', (e) => {
let eventX = e.clientX * ratio - canvas.getBoundingClientRect().left;
let eventY = e.clientY * ratio - canvas.getBoundingClientRect().top;
let mousePoint = { x: eventX, y: eventY, clientX: e.clientX, clientY: e.clientY };
let isRingRange = this.isRingPostion(mousePoint, data, this.props.nodeWidth,
this.props.innerRadius, this.props.radius, scale);
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.drawNode(ctx, data, data.x, data.y, this.props.nodeWidth, this.props.nodeHeight,
this.props.radius, this.props.innerRadius, this.state.color, scale, mousePoint, isRingRange, this);
if (!isRingRange) {
this.setState({ tipNode: null });
}
}, false)
canvas.addEventListener('wheel', (e) => {
this.setState({ tipNode: null });
})
}
/**
* 绘制一个节点
* ctx:上下文
* node:节点数据{desc: string,count:number,percent:number,pieData:[]}
* x:节点中心横坐标
* y:节点中心纵坐标
* width:节点容器宽度
* height:节点容器高度
* radius:外环半径
* innerRadius:内环半径
* scale:缩放比例
* mousePoint:鼠标对象
* isRingRange:鼠标是否在圆环上
* treePage:当前页面对象
*/
drawNode(ctx, node, x, y, width = 300, height = 150,
radius, innerRadius, pieColor, scale = 1, mousePoint = null, isRingRange = false, treePage) {
//绘制节点容器,一个矩形框
ctx.strokeStyle = '#E9E9E9';
ctx.lineWidth = 1.5 * scale;
width = width * scale;
height = height * scale;
ctx.strokeRect(x - width / 2, y - height / 2, width, height);
//绘制第一行显示文本
let fontSize = 12 * scale;
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#9c9c9c";
let textX1 = x - width * 0.25;
let textY1 = y - 14 * scale;
ctx.fillText(node.desc, textX1, textY1);
//绘制第二行显示文本
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#7E317E";
let textX2 = x - width * 0.25;
let textY2 = y + 14 * scale;
ctx.fillText(node.count, textX2, textY2);
//绘制圆环
this.drawRingPie(ctx, node, x + width * 0.25, y, radius * scale, innerRadius * scale,
pieColor, scale, mousePoint, isRingRange, treePage);
}
/**
* 画环形饼图
* ctx:上下文
* node:节点信息
* x:饼图圆心横坐标
* y:饼图圆心纵坐标
* radius:外层圆半径
* innerRadius:内层圆半径
* color:饼图颜色数组
* scale:缩放比例
* mousePoint:鼠标对象
* isRingRange:鼠标是否在圆环上
* treePage:当前页面对象
*/
drawRingPie(ctx, node, x, y, radius, innerRadius, color, scale = 1, mousePoint = null, isRingRange, treePage) {
//画外层圆环
ctx.save();
ctx.translate(x, y);
ctx.scale(scale, scale);
let startRadian = 0, endRadian = 0;
for (let i = 0; i < node.pieData.length; i++) {
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
endRadian += node.pieData[i].value * Math.PI * 2;
//以圆心为起点,0度开始绘制一个圆
ctx.arc(0, 0, radius, startRadian, endRadian, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = color[i];
ctx.fill();
startRadian = endRadian;
if (mousePoint && ctx.isPointInPath(mousePoint.x, mousePoint.y) && isRingRange) {//鼠标点击了并且在该部分圆环上
ctx.clearRect(-radius, -radius, 2 * radius, 2 * radius);
this.drawDynamicPie(ctx, node, radius, color, i);//重绘圆
let tipNode = {
desc: node.desc,
name: node.pieData[i].name,
value: this.floatMul(node.pieData[i].value, 100) + "%"
}
treePage.setState({ tipNode: tipNode, mousePosition: { x: mousePoint.clientX, y: mousePoint.clientY } });
}
}
/**
* 画内层圆
*/
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
//以圆心为起点,0度开始绘制一个圆
ctx.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = "#ffffff";
ctx.stroke();
ctx.fill();
ctx.restore();
/**
* 环心填充文字
*/
let fontSize = 12 * scale;
ctx.font = fontSize + "px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#000";
ctx.fillText(node.percent + "%", x, y);
}
//绘制动态圆
drawDynamicPie(ctx, node, radius, color, index) {
let startRadian = 0, endRadian = 0;
for (let i = 0; i < node.pieData.length; i++) {
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(0, 0);
endRadian += node.pieData[i].value * Math.PI * 2;
//以圆心为起点,0度开始绘制一个圆
if (index == i) {
ctx.arc(0, 0, radius + 5, startRadian, endRadian, false);
} else {
ctx.arc(0, 0, radius, startRadian, endRadian, false);
}
ctx.closePath();
// 填充颜色
ctx.fillStyle = color[i];
ctx.fill();
startRadian = endRadian;
}
}
/*点击位置是否在圆环上(数据为列表)
*mousePoint:鼠标对象位置记录
*node:详细数据
*nodeWidth:矩形的宽度
*innerRadius:外层圆半径
*radius:内层圆半径
*scale:缩放比例
*/
isRingPostion(mousePoint, node, nodeWidth, innerRadius, radius, scale) {
if (!mousePoint) {
return false;
}
nodeWidth = nodeWidth * scale;
innerRadius = innerRadius * scale;
radius = radius * scale;
let eventX = mousePoint.x;
let eventY = mousePoint.y;
//点击位置到圆心的距离,勾股定理计算
let cricleX = node.x + nodeWidth / 4;//圆心x坐标
let cricleY = node.y;
let distanceFromCenter = Math.sqrt(Math.pow(cricleX - eventX, 2)
+ Math.pow(cricleY - eventY, 2))
//是否在圆环上
if (distanceFromCenter > innerRadius && distanceFromCenter < radius) {
return true;
}
return false;
}
//浮点数乘法
floatMul(a, b) {
let m = 0, n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1].length;
} catch (error) {
console.log(error)
}
try {
n = e.split(".")[1].length;
} catch (error) {
console.log(error)
}
let maxInt = Math.pow(10, m + n); //将数字转换为整数的最大倍数
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / maxInt;
}
//设备像素比
getPixelRatio(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
//获取提示的定位位置
getTipPosition() {
let tipDiv = document.getElementById(`${this.props.treeId}Tip`);
let mousePosition = this.state.mousePosition;
let top1 = mousePosition.y + 12;
let left = mousePosition.x + 12;
if (tipDiv) {
if (mousePosition.x + tipDiv.offsetWidth > window.innerWidth) {
left = mousePosition.x - 12 - tipDiv.offsetWidth;
}
if (mousePosition.y + tipDiv.offsetHeight > window.innerHeight) {
top1 = mousePosition.y - 12 - tipDiv.offsetHeight;
}
}
return { top: top1, left: left }
}
render() {
let position = this.getTipPosition();
let tipClass = {
position: 'fixed',
zIndex: 999,
visibility: this.state.tipNode ? 'visible' : 'hidden',
backgroundColor: '#826d6d',
top: position.top,
left: position.left,
padding: '15px',
color: '#fff',
borderRadius: '5px',
textAlign: 'left'
}
return (
<div style={{ padding: 100 }}>
<canvas id={this.props.canvasId} width={this.props.width} height={this.props.height}
style={{ zoom: this.state.ratio}}></canvas>
<div style={tipClass} id={`${this.props.treeId}Tip`}>
<div>{this.state.tipNode ? this.state.tipNode.desc : null}</div>
<div>{this.state.tipNode ? this.state.tipNode.name : null} : {this.state.tipNode ? this.state.tipNode.value : null}</div>
</div>
</div>
);
}
}
export default CustomCanvas;
<file_sep>import React, { Component } from 'react';
import { drawNode, drawLine, getPixelRatio, isRingPostion } from '../common/TreeNode';
import underscore from 'underscore';
class PayAbilityLoginTree extends Component {
constructor(props) {
super(props);
this.state = {
color: ['#bd94ff', '#48eaa7'],
treeData: this.treeSource(this.props.source) || [],
tipNode: null,
mousePosition: {
x: 0,
y: 0
}
}
}
static defaultProps = {
source: [
{
position: "root", depth: 1, desc: "当日登陆用户", count: 2321341, percent: 100,
pieData: [{ name: "当日登陆用户", value: "1" }]
},
{
position: "left", depth: 2, desc: "当日新增登陆", count: 2321341, percent: 50,
pieData: [{ name: "当日新增登陆", value: "0.6" }, { name: "非当日新增登陆", value: "0.4" }]
},
{
position: "right", depth: 2, desc: "非当日新增登陆", count: 2321341, percent: 60,
pieData: [{ name: "非当日新增登陆", value: "0.4" }, { name: "当日新增登陆", value: "0.6" }]
},
{
position: "left", depth: 3, desc: "非T4用户", count: 2321341, percent: 20,
pieData: [{ name: "非T4用户", value: "0.2" }, { name: "T4用户", value: "0.8" }]
},
{
position: "right", depth: 3, desc: "非T4用户", count: 2321341, percent: 30,
pieData: [{ name: "非T4用户", value: "0.2" }, { name: "T4用户", value: "0.8" }]
},
{
position: "left", depth: 4, desc: "当日T4转化", count: 2321341, percent: 33,
pieData: [{ name: "当日T4转化", value: "0.33" }, { name: "当日T4转化", value: "0.67" }]
},
{
position: "right", depth: 4, desc: "当日T4转化", count: 2321341, percent: 22,
pieData: [{ name: "当日T4转化", value: "0.22" }, { name: "非当日T4转化", value: "0.78" }]
},
{
position: "left", depth: 5, desc: "七日T4转化", count: 2321341, percent: 66,
pieData: [{ name: "七日T4转化", value: "0.66" }, { name: "非七日T4转化", value: "0.34" }]
},
{
position: "right", depth: 5, desc: "七日T4转化", count: 2321341, percent: 55.5,
pieData: [{ name: "七日T4转化", value: "0.555" }, { name: "非七日T4转化", value: "0.445" }]
},
{
position: "left", depth: 6, desc: "三十日T4转化", count: 2321341, percent: 36.66,
pieData: [{ name: "三十日T4转化", value: "0.3666" }, { name: "非三十日T4转化", value: "0.6334" }]
},
{
position: "right", depth: 6, desc: "三十日T4转化", count: 2321341, percent: 23,
pieData: [{ name: "三十日T4转化", value: "0.23" }, { name: "非三十日T4转化", value: "0.77" }]
}
],
treeId: "payAbilityLoginTree",
fit: false,
width: 1000,
height: 1400,
nodeWidth: 300,
nodeHeight: 150,
radius: 65, //nodeWidth*0.25-10
innerRadius: 40 //nodeWidth*0.25-35
}
//源数据处理
treeSource(source) {
return source;
}
//为节点添加x,y坐标
dealData(canvas, scale) {
const width = canvas.width;
const height = canvas.height;
let treeData = this.state.treeData;
let depth = 6;
const nodeYSacle = (height - this.props.nodeHeight * scale) / (depth - 1);
this.setNodePoint(treeData, width, nodeYSacle, scale);
}
//设置节点的x,y坐标
setNodePoint(treeData, width, nodeYSacle, scale) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
if (node.position == "root") {
let nodeXSacle = width / 2;
node.x = nodeXSacle;
} else {
let nodeXSacle = (width - 300 * scale) / 6; //左右各留150px的留白
if (node.position == "left") {
node.x = nodeXSacle + this.props.nodeWidth * scale / 2;
} else {
node.x = nodeXSacle * 5 + this.props.nodeWidth * scale / 2;
}
}
node.y = nodeYSacle * (node.depth - 1) + this.props.nodeHeight * scale / 2;
}
}
}
componentDidMount() {
this.redrawTree(this.state.treeData);
}
redrawTree(treeData) {
const canvas = document.getElementById("payAbilityLoginTree");
const ctx = canvas.getContext('2d');
let ratio = getPixelRatio(ctx);
let scale = ratio;
if (this.props.fit) {
if (canvas.parentNode.offsetWidth > 1000) {
canvas.width = canvas.parentNode.offsetWidth * ratio;
canvas.height = this.props.height * ratio;
} else {
scale = (canvas.parentNode.offsetWidth / 1000) * ratio;
canvas.width = canvas.parentNode.offsetWidth * ratio;
canvas.height = this.props.height * scale * ratio;
scale = scale * ratio;
}
}
this.setState({ ratio: 1 / ratio });
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.dealData(canvas, scale)
this.drawTree(ctx, treeData, scale);
canvas.addEventListener('mousemove', (e) => {
let eventX = e.clientX * ratio - canvas.getBoundingClientRect().left;
let eventY = e.clientY * ratio - canvas.getBoundingClientRect().top;
let mousePoint = { x: eventX, y: eventY, clientX: e.clientX, clientY: e.clientY };
let isRingRange = isRingPostion(mousePoint, treeData, this.props.nodeWidth * scale,
this.props.innerRadius * scale, this.props.radius * scale);
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.drawTree(ctx, treeData, scale, mousePoint, isRingRange);
if (!isRingRange) {
this.setState({ tipNode: null });
}
}, false)
canvas.addEventListener('wheel', (e) => {
this.setState({ tipNode: null });
}, false)
}
componentWillReceiveProps(nextProps) {
if (!underscore.isEqual(nextProps.source, this.props.source)) {
let newData = this.treeSource(nextProps.source)
this.setState({ treeData: newData }, function () {
this.redrawTree(newData);
});
}
}
drawTree(ctx, treeData, scale, mousePoint = null, isRingRange = false) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
let parentNode = null;
if (node.depth == 1) {
} else if (node.depth == 2) {
parentNode = treeData.find(item => item.depth == node.depth - 1 && item.position == "root");
} else {
parentNode = treeData.find(item => item.depth == node.depth - 1 && item.position == node.position);
}
drawNode(ctx, node, node.x, node.y, this.props.nodeWidth, this.props.nodeHeight,
this.props.radius, this.props.innerRadius, this.state.color, scale, mousePoint, isRingRange, this);
if (parentNode) {
drawLine(ctx, parentNode.x, parentNode.y, node.x, node.y, this.props.nodeHeight * scale);
}
}
}
}
//获取提示的定位位置
getTipPosition() {
let tipDiv = document.getElementById(`${this.props.treeId}Tip`);
let mousePosition = this.state.mousePosition;
let top1 = mousePosition.y + 12;
let left = mousePosition.x + 12;
if (tipDiv) {
if (mousePosition.x + tipDiv.offsetWidth > window.innerWidth) {
left = mousePosition.x - 12 - tipDiv.offsetWidth;
}
if (mousePosition.y + tipDiv.offsetHeight > window.innerHeight) {
top1 = mousePosition.y - 12 - tipDiv.offsetHeight;
}
}
return { top: top1, left: left }
}
render() {
let position = this.getTipPosition();
let tipClass = {
position: 'fixed',
zIndex: 999,
visibility: this.state.tipNode ? 'visible' : 'hidden',
backgroundColor: '#826d6d',
top: position.top,
left: position.left,
padding: '15px',
color: '#fff',
borderRadius: '5px',
textAlign: 'left'
}
return (
<div style={{ padding: 15 }}>
<canvas id={this.props.treeId} width={this.props.width} height={this.props.height} style={{ zoom: this.state.ratio }}></canvas>
<div style={tipClass} id={`${this.props.treeId}Tip`}>
<div>{this.state.tipNode ? this.state.tipNode.desc : null}</div>
<div>{this.state.tipNode ? this.state.tipNode.name : null} : {this.state.tipNode ? this.state.tipNode.value : null}</div>
</div>
</div>
)
}
}
export default PayAbilityLoginTree;
<file_sep>/*
*防抖动
*fn:回调函数
*delay:延迟时间
*/
export const debounce = (fn, delay) => {
let timer = null;
return () => {
let args = arguments;
if (timer) {//存在定时器则重新计时
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
/*
*节流
*fn:回调函数
*delay:延迟时间
*/
export const throttle = (fn, delay) => {
let timer = null;
return () => {
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
clearTimeout(timer);
timer = null;//上次执行完成后才重新计时
}, delay);
}
}
}<file_sep>import React from "react";
import {
G2,
Chart,
Geom,
Axis,
Tooltip,
Coord,
Label,
Legend,
View,
Guide,
} from "bizcharts";
import './ExplanatoryBar.less';
const Html = Guide.Html;
class ExplanatoryBar extends React.Component {
constructor(props) {
super(props);
}
//获取辅助信息位置
getGuidePosition(info, data) {
const width = document.body.clientWidth;
const axisX = width / (data.length * 2);
const index = data.findIndex(item=>item.year == info.year);
let horizontal = 'right';
let vertical = 'Up';
if(axisX*index < 320){
horizontal = 'right'
}
return this.getGuideHtml(info, 'rightUp');
}
//获取辅助信息
getGuideHtml(info, pos) {
const template = `
<div>
<strong>2018年8月2日</strong>
<strong style="padding: 0 10px">星期二</strong>
</div>
<div>
<strong>最近一周</strong>
<strong style="padding: 0 10px">T4用户净增长量</strong>
<strong style="padding: 0 10px">为</strong>
<span style="color: #3023FF">19</span>
<span>万</span>
</div>
<div>
<span>对比上一周T4用户均净增长量为</span>
<span style="padding-left:0px">12万</span>
<sqpn>,</sqpn>
</div>
<div>
<span>周环比增长</span>
<span style="padding-left: 10px; color: #3023FF">78.1</span>
<span>%</span>
</div>
<div class="explanLine"></div>
`;
switch (pos) {
case 'leftDown':
return <Html
position={info}
html={`<div class="explanatoryBox leftDown">${template}</div>`}
offsetY={94}
offsetX={-270}
key={info.year}
/>
case 'rightDown':
return <Html
position={info}
html={`<div class="explanatoryBox rightDown">${template}</div>`}
offsetY={94}
offsetX={270}
key={info.year}
/>
case 'leftUp':
return <Html
position={info}
html={`<div class="explanatoryBox leftUp">${template}</div>`}
offsetY={-124}
offsetX={-170}
key={info.year}
/>
case 'top':
return <Html
position={info}
html={`<div class="explanatoryBox top">${template}</div>`}
offsetY={-124}
offsetX={0}
key={info.year}
/>
default:
return <Html
position={info}
html={`<div class="explanatoryBox">${template}</div>`}
offsetY={-124}
offsetX={170}
key={info.year}
/>
}
}
render() {
const data = [
{
year: "1951 年",
sales: 38
},
{
year: "1952 年",
sales: 52
},
{
year: "1956 年",
sales: 61
},
{
year: "1957 年",
sales: 145
},
{
year: "1958 年",
sales: 48
},
{
year: "1959 年",
sales: 38
},
{
year: "1960 年",
sales: 38
},
{
year: "1962 年",
sales: 38
},
{
year: "1963 年",
sales: 38
},
{
year: "1964 年",
sales: 38
},
{
year: "1965 年",
sales: 38
},
{
year: "1966 年",
sales: 38
},
{
year: "1967 年",
sales: 38
},
{
year: "1968 年",
sales: 38
}
];
const cols = {
sales: {
alias: 'Y轴刻度'
}
};
const guideInfo = [
{ year: "1960 年", sales: 38 },
{ year: "1957 年", sales: 145 },
{ year: "1965 年", sales: 38 }
]
return (
<div>
<Chart height={600} data={data} scale={cols} forceFit>
<Axis name="year" />
<Axis name="sales" title="true" />
<Tooltip
crosshairs={{
type: "y"
}}
/>
<Geom type="interval" position="year*sales" />
<Guide>
{
guideInfo.map(item => {
return this.getGuidePosition(item,data,guideInfo);
})
}
</Guide>
</Chart>
</div>
);
}
}
export default ExplanatoryBar;
<file_sep>import React, { Component } from 'react';
import { Row, Col, Icon, Table, Progress, DatePicker,Button } from 'antd';
import './familyNum.css';
const { RangePicker } = DatePicker;
class FamilyNum extends Component {
constructor(props) {
super(props);
}
render() {
const columns = [{
title: 'Name',
dataIndex: 'name',
render: text => <a href="javascript:;">{text}</a>,
}, {
title: 'Age',
dataIndex: 'age',
}, {
title: 'Address',
dataIndex: 'address',
}];
const data = [{
key: '1',
name: '<NAME>',
age: 32,
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: '<NAME>',
age: 42,
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: '<NAME>',
age: 32,
address: 'Sidney No. 1 Lake Park',
}, {
key: '4',
name: '<NAME>',
age: 99,
address: 'Sidney No. 1 Lake Park',
}];
// rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: record => ({
disabled: record.name === 'Disabled User', // Column configuration not to be checked
name: record.name,
}),
};
return (
<div>
<div className="stepItem">
<div className="stepLine"></div>
<div>
<div className="stepNum">已开通</div>
</div>
<div className="content">
<div className="stepTitle">
开通亲情号
</div>
<section>
<Row gutter="20">
<Col span="6">
<div className="card">
<div className="desc">开通对数</div>
<div className="number">126,560</div>
<div className="percent">
<div>同周比</div>
<Icon type="caret-up" className="percentTrend" />
<div>12%</div>
</div>
<hr className="splithr" />
</div>
</Col>
<Col span="6">
<div className="card">
<div className="desc">解绑对数</div>
<div className="number">126,560</div>
<div className="percent">
<div>同周比</div>
<Icon type="caret-up" className="percentTrend" />
<div>12%</div>
</div>
<hr className="splithr" />
</div>
</Col>
<Col span="6">
<div className="card">
<div className="desc">开通对数</div>
<div className="number">126,560</div>
<div className="percent">
<div>同周比</div>
<Icon type="caret-up" className="percentTrend" />
<div>12%</div>
</div>
<hr className="splithr" />
</div>
</Col>
<Col span="6">
<div className="card">
<div className="desc">开通对数</div>
<div className="number">126,560</div>
<div className="percent">
<div>同周比</div>
<Icon type="caret-up" className="percentTrend" />
<div>12%</div>
</div>
<hr className="splithr" />
</div>
</Col>
</Row>
</section>
<section>
<div className="comparsionTable">
<div className="comparsionTableTilte">开通亲情号</div>
<div className="comparsion">
<div className="comparsionRadio">
<div calssName="selected"></div>
</div>
<div >同比</div>
</div>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} bordered="true" />
</section>
</div>
</div>
<div className="stepItem">
<div className="stepLine"></div>
<div>
<Icon type="check-circle-o" className="finished" />
</div>
<div className="content">
<div className="stepTitleDesc">
<div className="title">开通关系分析</div>
<div className="desc">分析开通的用户的关系类型</div>
</div>
<Row gutter="20">
<Col span="12">
<div className="chartDesc">关系类型分析</div>
<hr className="splithr" />
<div className="chartTable">
<div className="chartTableItem">
<div className="cricle"></div>
<div className="legend">爸爸</div>
<div className="split">|</div>
<div className="percent">36%</div>
<div>4,544</div>
</div>
<div className="chartTableItem">
<div className="cricle"></div>
<div className="legend">爸爸</div>
<div className="split">|</div>
<div className="percent">36%</div>
<div>4,544</div>
</div>
<div className="chartTableItem">
<div className="cricle"></div>
<div className="legend">爸爸</div>
<div className="split">|</div>
<div className="percent">36%</div>
<div>4,544</div>
</div>
</div>
</Col>
<Col span="12">
<div className="chartDesc">关系类型分析</div>
<hr className="splithr" />
<Row gutter="20">
<Col span="6">
<div className="lineName">主动开通数</div>
<div className="lineCount">
<span className="pd-r-5">1233</span>
<span>万对</span>
</div>
</Col>
<Col span="6">
<div className="lineName">开通成功数</div>
<div className="lineCount">
<span className="pd-r-5">1233</span>
<span>万对</span>
</div>
</Col>
<Col span="6">
<div className="lineName">求开通数</div>
<div className="lineCount">
<span className="pd-r-5">1233</span>
<span>万对</span>
</div>
</Col>
<Col span="6">
<div className="lineName">求开通成功数</div>
<div className="lineCount">
<span className="pd-r-5">1233</span>
<span>万对</span>
</div>
</Col>
</Row>
</Col>
</Row>
<section>
<div className="comparsionTable">
<div className="comparsionTableTilte">开通关系分析</div>
<div className="comparsion">
<div className="comparsionRadio">
<div calssName="selected"></div>
</div>
<div >同比</div>
</div>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} bordered="true" />
</section>
</div>
</div>
<div className="stepItem">
<div className="stepLine"></div>
<div>
<div className="stepNum">2</div>
</div>
<div className="content">
<div className="stepTitleDesc">
<div className="title">开通设置分析</div>
<div className="desc">分析用户的设置信息</div>
</div>
<Row gutter="20">
<Col span="6">
<div className="card" style={{ paddingBottom: '5px' }}>
<div className="desc">当天设置比例</div>
<div className="number">78%</div>
<Progress percent={78} showInfo={false} />
<hr className="splithr" />
<div className="count">
设置用户数:125,324
</div>
</div>
</Col>
<Col span="6">
<div className="card" style={{ paddingBottom: '5px' }}>
<div className="desc">更改默认额度设置比例</div>
<div className="number">78%</div>
<Progress percent={78} showInfo={false} />
<hr className="splithr" />
<div className="count">
设置用户数:125,324
</div>
</div>
</Col>
<Col span="6">
<div className="card" style={{ paddingBottom: '5px' }}>
<div className="desc">设置扣款需要同意的比例</div>
<div className="number">78%</div>
<Progress percent={78} showInfo={false} />
<hr className="splithr" />
<div className="count">
设置用户数:125,324
</div>
</div>
</Col>
<Col span="6">
<div className="card" style={{ paddingBottom: '5px' }}>
<div className="desc">付款提醒设置比例</div>
<div className="number">78%</div>
<Progress percent={78} showInfo={false} />
<hr className="splithr" />
<div className="count">
设置用户数:125,324
</div>
</div>
</Col>
</Row>
<div>
<div className="descTilte">额度设置</div>
<hr className="splithr" />
<Row gutter="20">
<Col span="4">
<div>对数:125,125,568</div>
</Col>
<Col span="4">1</Col>
<Col span="4">1</Col>
<Col span="4">1</Col>
<Col span="4">1</Col>
<Col span="4">1</Col>
</Row>
</div>
<section>
<div className="comparsionTable">
<div className="comparsionTableTilte">额度设置分析</div>
<div className="comparsion">
<div className="comparsionRadio">
<div calssName="selected"></div>
</div>
<div >同比</div>
</div>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} bordered="true" />
</section>
</div>
</div>
<div className="stepItem">
<div className="stepLine waitLine"></div>
<div>
<div className="stepNum waitStepNum">3</div>
</div>
<div className="content">
<div className="stepTitleDesc">
<div className="title wait">支付能力评估与开通使用</div>
<div className="desc">评估用户支付能力,分析用户开通亲情号的场景使用、额度使用</div>
</div>
<div>
<div className="descTilte">开通亲情号之前,用户当天支付能力状态</div>
<hr className="splithr" />
</div>
<section>
<div className="comparsionTable">
<div className="comparsionTableTilte">开通亲情号之前,用户当天的支付能力状态</div>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} bordered="true" />
</section>
</div>
</div>
<div className="stepItem">
<div className="stepLine waitLine"></div>
<div>
<div className="stepNum waitStepNum">3</div>
</div>
<div className="content">
<div className="stepTitleDesc">
<div className="title wait">开通使用分析</div>
<div className="desc">分析开通亲情号的用户的场景使用,额度使用</div>
</div>
<div>
<div className="descTilte">亲情号开通使用分析</div>
<hr className="splithr" />
<Row gutter="20">
<Col span="8">
<div className="listItem">
<div className="itemDesc">亲情号使用笔数</div>
<div className="itemValue">126,560</div>
<div className="itemPercent">
<div>同周比</div>
<Icon type="caret-up" className="percentUp" />
<div>12%</div>
</div>
</div>
<div className="listItem">
<div className="itemDesc">亲情号使用金额</div>
<div className="itemValue">126,560</div>
<div className="itemPercent">
<div>同周比</div>
<Icon type="caret-down" className="percentDown" />
<div>12%</div>
</div>
</div>
<div className="listItem">
<div className="itemDesc">亲情号使用用户数</div>
<div className="itemValue">126,560</div>
<div className="itemPercent">
<div>同周比</div>
<Icon type="caret-up" className="percentUp" />
<div>12%</div>
</div>
</div>
</Col>
<Col span="16">
<div className="condition">
<div className="leftPart">使用笔数</div>
<div className="rightPart">
<Button className="pickerBtn">今日</Button>
<Button className="pickerBtn">本周</Button>
<Button className="pickerBtn mg-r-15">本月</Button>
<RangePicker format="YYYY-MM-DD" />
</div>
</div>
</Col>
</Row>
</div>
<section>
<div className="comparsionTable">
<div className="comparsionTableTilte">开通亲情号之前,用户当天的支付能力状态</div>
</div>
<Table rowSelection={rowSelection} columns={columns} dataSource={data} bordered="true" />
</section>
</div>
</div>
</div>
)
}
}
export default FamilyNum;
<file_sep>import React from "react";
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入柱状图
import 'echarts/lib/chart/sankey';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import numeral from 'numeral';
const data = {
"nodes": [
{ name: "统一结果页面", value: 1564646 },
{ name: "标准页面", value: 766767 },
{ name: "密码验证页面", value: 7686786 },
{ name: "收银台渠道切换页面", value: 5756756 },
{ name: "短信验证页面", value: 1564646 },
{ name: "卡号输入页面", value: 4353454 },
{ name: "花呗签约页面", value: 2342342 },
{ name: "四要素页面", value: 4564565 },
{ name: "还有6个页面", value: 1432423423 },
{ name: "还有9个页面", value: 455546 },
{ name: "还有10个页面", value: 1564646 },
{ name: "Mali", value: 1564646 },
{ name: "China", value: 1564646 },
{ name: "India", value: 1564646 },
{ name: "Japan", value: 1564646 }
],
"links": [
{ "source": 0, "target": 1, "value": 5 }, { "source": 0, "target": 2, "value": 1 }, { "source": 0, "target": 3, "value": 1 }, { "source": 0, "target": 4, "value": 1 },
{ "source": 5, "target": 1, "value": 1 }, { "source": 5, "target": 2, "value": 5 }, { "source": 5, "target": 4, "value": 1 },
{ "source": 6, "target": 1, "value": 1 }, { "source": 6, "target": 2, "value": 1 }, { "source": 6, "target": 3, "value": 5 }, { "source": 6, "target": 4, "value": 1 }, { "source": 7, "target": 1, "value": 1 },
{ "source": 7, "target": 2, "value": 1 }, { "source": 7, "target": 3, "value": 1 }, { "source": 7, "target": 4, "value": 5 }, { "source": 1, "target": 8, "value": 2 },
{ "source": 1, "target": 9, "value": 1 }, { "source": 1, "target": 10, "value": 1 }, { "source": 1, "target": 11, "value": 3 },
{ "source": 2, "target": 8, "value": 1 }, { "source": 2, "target": 9, "value": 3 }, { "source": 2, "target": 12, "value": 3 }, { "source": 2, "target": 10, "value": 3 }, { "source": 2, "target": 11, "value": 1 },
{ "source": 3, "target": 9, "value": 1 }, { "source": 3, "target": 10, "value": 3 }, { "source": 3, "target": 11, "value": 1 },
{ "source": 4, "target": 8, "value": 1 }, { "source": 4, "target": 9, "value": 1 }, { "source": 4, "target": 10, "value": 2 }, { "source": 4, "target": 11, "value": 7 },
{ "source": 11, "target": 13, "value": 5 }, { "source": 11, "target": 14, "value": 1 }, { "source": 11, "target": 15, "value": 3 },
{ "source": 8, "target": 13, "value": 5 }, { "source": 8, "target": 14, "value": 1 }, { "source": 8, "target": 15, "value": 3 },
{ "source": 9, "target": 13, "value": 5 }, { "source": 9, "target": 14, "value": 1 }, { "source": 9, "target": 15, "value": 3 },
{ "source": 12, "target": 13, "value": 5 }, { "source": 12, "target": 14, "value": 1 }, { "source": 12, "target": 15, "value": 3 },
{ "source": 10, "target": 13, "value": 5 }, { "source": 10, "target": 14, "value": 1 }, { "source": 10, "target": 15, "value": 3 }
]
}
class Sankey extends React.Component {
componentDidMount() {
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('sankeyChart'));
let option = {
title: { text: '访问页面' },
tooltip:{
trigger:'item'
},
series: {
type: 'sankey',
layout: 'none',
right: '5%',
nodeWidth: 300,
nodeGap: 30,
label: {
position: 'bottom',
fontSize: 16,
fontWeight: 'bold',
formatter: (params) => {
const regex = /^还有(\d)+个页面$/;
if (regex.test(params.name)) {
return numeral(params.value).format('0,0.00zh') + " " + params.name + " {morePage|}"
} else {
return numeral(params.value).format('0,0.00zh') + " " + params.name
}
},
rich: {
morePage: {
backgroundColor: {
image: 'https://gw.alipayobjects.com/zos/rmsportal/rcCQRFENMeAHTavDtwAu.png'
},
height: 16
}
}
},
itemStyle: {
color: '#B3DEFD',
borderColor: '#72A9DC',
},
data: data.nodes,
links: data.links
}
}
// 绘制图表
myChart.setOption(option);
myChart.on('click', (event) => {
const regex = /^还有(\d)+个页面$/;
if (regex.test(event.name)) {
myChart.clear();
myChart.setOption(option);
} else {
return;
}
}
)
}
render() {
return (
<div id="sankeyChart" style={{ width: "100%", height: 600 }}></div>
)
}
}
export default Sankey;
<file_sep>import React, { Component } from 'react';
class CustomTree extends Component {
constructor(props) {
super(props);
this.state = {
color: ['#bd94ff', '#48eaa7'],
treeData: this.treeSource(this.props.source) || []
}
}
static defaultProps = {
/*
is_register_today:1(历史注册),0(今日注册)
trade_from:0(淘宝注册),1(支付宝注册)
*/
source: [
{ is_register_today: "1", trade_from: "0", user_cnt: 2000 },
{ is_register_today: "1", trade_from: "1", user_cnt: 4000 },
{ is_register_today: "0", trade_from: "0", user_cnt: 3000 },
{ is_register_today: "0", trade_from: "1", user_cnt: 5000 },
],
fit: false,
width: 1400,
height: 900,
nodeWidth: 300,
nodeHeight: 150,
radius: 65, //nodeWidth*0.25-10
innerRadius: 40 //nodeWidth*0.25-25
}
//封装树
treeSource() {
let source = this.props.source;
//遍历数组生成id
let todayChildren = [];
let historyChildren = [];
for (let item of source) {
if (item.is_register_today == "0") {
todayChildren.push(item);
} else {
historyChildren.push(item);
}
item.id = this.createGuid();
}
//封装今日注册
let todayTree = this.createTreeNode(todayChildren);
todayTree.desc = "今日注册用户";
todayTree.id = this.createGuid();
//封装历史注册用户
let historyTree = this.createTreeNode(historyChildren);
historyTree.desc = "历史注册用户";
historyTree.id = this.createGuid();
//封装总注册用户
let rootChildren = [todayTree, historyTree];
let rootTree = this.createTreeNode(rootChildren);
rootTree.desc = "总注册用户";
rootTree.percent = 100;
rootTree.pieData = [1];
rootTree.id = this.createGuid();;
return [rootTree];
}
//根据子节点反向创建一个父节点
createTreeNode(treeChildren) {
let todayNode = {};
todayNode.count = 0;
//遍历获取父节点总注册用户
for (let node of treeChildren) {
node.count = node.user_cnt;
if (!node.desc) {
if (node.trade_from == "0") {
node.desc = "淘宝注册用户";
} else {
node.desc = "支付宝注册用户";
}
}
todayNode.count += node.count;
}
//遍历设置今日淘宝支付宝注册占比
for (let node of treeChildren) {
node.percent = Math.round((node.user_cnt * 10000 / todayNode.count)) / 100;
node.pieData = [node.percent / 100, 1 - node.percent / 100];
}
todayNode.user_cnt = todayNode.count;
todayNode.children = treeChildren;
return todayNode;
}
//生成uuid
createGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//设置每级深度
setNodeDepth(treeData, depth = 1) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
node.depth = depth;
if (node.children) {
this.setNodeDepth(node.children, depth + 1)
}
}
}
}
//获取最大深度
getMaxDepath(treeData) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
let maxDepth = 1;
if (node.children) {
maxDepth = Math.max(maxDepth, this.getMaxDepath(node.children) + 1)
return maxDepth
} else {
maxDepth = 1;
return maxDepth;
}
}
}
}
//获取相应深度节点数
getNodeDepathNum(treeData, depth, floorList = []) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
if (node.depth == depth) {
floorList.push(node);
continue;
}
if (node.children) {
this.getNodeDepathNum(node.children, depth, floorList)
}
}
}
return floorList;
}
//为节点添加x,y坐标
dealData(canvas) {
const width = canvas.width;
const height = canvas.height;
let treeData = this.state.treeData;
const depth = this.getMaxDepath(treeData);
this.setNodeDepth(treeData);
const nodeYSacle = height / (depth + 1);
this.setNodePoint(treeData, width, height, nodeYSacle);
}
//设置节点的x,y坐标
setNodePoint(treeData, width, height, nodeYSacle) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
let nodeXScale = 0;
for (let i = 0; i < nodeLength; i++) {
let floorList = this.getNodeDepathNum(this.state.treeData, treeData[i].depth);
nodeXScale = width / (Math.pow(2, treeData[i].depth)); //横纵度量:2的depth次方为每个深度最大的节点数
let nodeIndex = floorList.findIndex((node) => node.id === treeData[i].id);
treeData[i].x = nodeXScale * (2 * (nodeIndex + 1) - 1); //每个节点间的距离2n-1
treeData[i].y = nodeYSacle * treeData[i].depth;
if (treeData[i].children) {
this.setNodePoint(treeData[i].children, width, height, nodeYSacle);
}
}
}
}
componentDidMount() {
const canvas = document.getElementById("customTree");
let scale = 1;
if (this.props.fit) {
if (canvas.parentNode.offsetWidth > 1400) {
canvas.width = canvas.parentNode.offsetWidth;
} else {
scale = canvas.parentNode.offsetWidth / 1400;
canvas.width = canvas.parentNode.offsetWidth;
canvas.height = canvas.height * scale;
}
}
const ctx = canvas.getContext('2d');
this.dealData(canvas)
let treeData = this.state.treeData;
this.drawTree(ctx, treeData, null, scale);
}
// getPixelRatio(context) {
// let backingStore = context.backingStorePixelRatio
// || context.webkitBackingStorePixelRatio
// || context.mozBackingStorePixelRatio
// || context.msBackingStorePixelRatio
// || context.oBackingStorePixelRatio
// || context.backingStorePixelRatio || 1;
// return (window.devicePixelRatio || 1) / backingStore;
// }
drawTree(ctx, treeData, parentNode,scale) {
let nodeLength = treeData.length;
if (nodeLength > 0) {
for (let node of treeData) {
this.drawNode(ctx, node, node.x, node.y, this.props.nodeWidth, this.props.nodeHeight,scale);
if (parentNode) {
this.drawLine(ctx, parentNode.x, parentNode.y, node.x, node.y, this.props.nodeHeight*scale);
}
if (node.children) {
this.drawTree(ctx, node.children, node,scale);
}
}
}
}
/**
* 绘制一个节点
* ctx:上下文
* node:节点数据{desc:string,count:number,percent:number}
* x:节点中心横坐标
* y:节点中心纵坐标
* width:节点容器宽度
* height:节点容器高度
*/
drawNode(ctx, node, x, y, width = this.props.nodeWidth, height = this.props.nodeHeight,scale) {
//绘制节点容器,一个矩形框
ctx.strokeStyle = '#e0e0e0';
ctx.save();
ctx.translate(x,y);
ctx.scale(scale,scale);
ctx.strokeRect( - width / 2, - height / 2, width, height);
//绘制第一行显示文本
ctx.font = "14px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#ce9797";
let textX1 = - width * 0.25;
let textY1 = - 14;
ctx.fillText(node.desc, textX1, textY1);
//绘制第二行显示文本
ctx.font = "14px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#ce9797";
let textX2 = - width * 0.25;
let textY2 = 14;
ctx.fillText(node.count, textX2, textY2);
this.drawRingPie(ctx, node, width * 0.25, 0, this.props.radius, this.props.innerRadius)
ctx.restore();
}
/**
* 画环形饼图
* ctx:上下文
* data:饼图数据[float,float,...]
* x:饼图圆心横坐标
* y:饼图圆心饼图圆心纵坐标
* radius:外层圆半径
* innerRadius:内层圆半径
*/
drawRingPie(ctx, node, x, y, radius, innerRadius) {
//画外层圆环
let color = this.state.color;
let startRadian = 0, endRadian = 0;
for (let i = 0; i < node.pieData.length; i++) {
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(x, y);
endRadian += node.pieData[i] * Math.PI * 2;
//以圆心为起点,0度开始绘制一个圆
ctx.arc(x, y, radius, startRadian, endRadian, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = color[i];
ctx.fill();
startRadian = endRadian;
}
/**
* 画内层圆
*/
ctx.beginPath();
//起始点移动到圆心
ctx.moveTo(x, y);
//以圆心为起点,0度开始绘制一个圆
ctx.arc(x, y, innerRadius, 0, Math.PI * 2, false);
ctx.closePath();
// 填充颜色
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = "#ffffff";
ctx.stroke();
ctx.fill();
/**
* 环心填充文字
*/
ctx.font = "14px Arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#000";
ctx.fillText(node.percent + "%", x, y);
}
/**
* 画连接线
* ctx:上下文
* x0:起始节点的横坐标
* y0:起始节点的纵坐标
* x1:终止节点的横坐标
* y1:终止节点的纵坐标
* height:节点容器高度
*/
drawLine(ctx, x0, y0, x1, y1, height = this.props.nodeHeight) {
ctx.strokeStyle = "#e0e0e0";
ctx.beginPath();
ctx.moveTo(x0, y0 + height / 2);
if (x1 != x0) {//折线
ctx.lineTo(x0, y0 + (y1 - y0) / 2);
ctx.stroke();
ctx.moveTo(x0, y0 + (y1 - y0) / 2);
ctx.lineTo(x1, y0 + (y1 - y0) / 2);
ctx.stroke();
ctx.moveTo(x1, y0 + (y1 - y0) / 2);
ctx.lineTo(x1, y1 - height / 2);
ctx.stroke();
} else {//直线
ctx.lineTo(x1, y1 - height / 2);
ctx.stroke();
}
}
render() {
return (
<div >
<canvas id="customTree" width={this.props.width} height={this.props.height}></canvas>
</div>
)
}
}
export default CustomTree;
| 9316f69aaeed28bde53cd05cbe5be7abb08b89df | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | windSandEye/custom-tree | aeb9eed7922da82ed2fc1e3bcf96cef2d689a840 | b908fe56ba80840ba28bd28d8a5ebb781a7731ec |
refs/heads/master | <repo_name>Giounona/LearnPytorch<file_sep>/README.md
# LearnPytorch
pytorch example scripts
<file_sep>/tensorboard_MNIST.py
from __future__ import print_function, division
import os
import torch
import pandas as pd
from PIL import Image
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torchvision import datasets
from tensorboardX import SummaryWriter
num_epochs = 10
batch_size = 100
learning_rate = 0.001
class MNISTDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations and absolute image paths.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
# create a list with image names
tmp_df = pd.read_csv(csv_file)
self.tmp_df = tmp_df
self.img_names = tmp_df['im_path']
self.labels = tmp_df['label']
# assert tmp_df['image_name'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all(),
self.transform = transform
def __len__(self):
return len(self.img_names.index)
def __getitem__(self, idx):
img_name = self.img_names[idx]
image = np.float32(np.asarray(Image.open(img_name)))
# image = image.convert('RGB')
# label = np.float32(np.asarray([self.labels[idx]]))
label = self.labels[idx]
# label = torch.from_numpy(np.asarray(label).reshape([1, 1]))
# label = torch.from_numpy(np.asarray(label))
# label = torch.from_numpy(label)
image = np.reshape(image, [1, image.shape[0], image.shape[1]])
image = torch.from_numpy(image)
if self.transform:
image = self.transform(image)
return image, label
transformations = transforms.Compose([transforms.ToTensor()])
dset_train = MNISTDataset('train_mnist.csv') # ,transformations)
train_loader = DataLoader(dset_train,
batch_size=batch_size,
shuffle=True,
num_workers=10 # 1 for CUDA
# pin_memory=True # CUDA only
)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2))
self.fc = nn.Linear(7 * 7 * 32, 10)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
writer = SummaryWriter()
cnn = CNN()
# cnn.cuda()
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(cnn.parameters(), lr=learning_rate)
# Train the Model
num_epochs = 100
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images) # .cuda()
labels = Variable(labels) # .cuda()
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = cnn(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
print('Epoch [%d/%d], Iter [%d/%d] Loss: %.4f'
% (epoch + 1, num_epochs, i + 1, dset_train.__len__() // batch_size, loss.data[0]))
niter = epoch*len(train_loader)+i
writer.add_scalar('Train/Loss', loss.data[0], niter)
writer.add_text('Text', 'text logged at step:' + str(i), i)
dataset = datasets.MNIST('mnist', train=False, download=True)
images = dataset.test_data[:100].float()
label = dataset.test_labels[:100]
features = images.view(100, 784)
writer.add_embedding(features, metadata=label, label_img=images.unsqueeze(1))
# export scalar data to JSON for external processing
writer.export_scalars_to_json("./all_scalars.json")
writer.close()<file_sep>/write_csv.py
import os
from natsort import natsorted
import pandas as pd
data_path='/mnt/fs3/qa_analitics/Person_Re_Identification/mnist/test'
test=os.listdir(data_path)
namelist=[]
classlist=[]
#namelist_dict = {}
file = open('test_mnist.txt', 'w')
if os.path.isdir(data_path):
classes=os.listdir(data_path)
classes = natsorted(classes, key=lambda y: y.lower())
for class_name in classes:
images = os.listdir(os.path.join(data_path , class_name))
images = natsorted(images, key=lambda y: y.lower())
for image_name in images:
namelist.append(os.path.join(data_path, class_name, image_name))
classlist.append(class_name)
#namelist_dict.update({'path':os.path.join(data_path, class_name, image_name), 'label':class_name})
file.write(os.path.join(data_path , class_name, image_name)+ ' '+class_name+'\n')
#print(data_path + name+'/'+class_name+'/'+image_name+'\n')
file.close()
df = pd.DataFrame(zip(namelist, classlist), columns=["im_path", "label"])
df.to_csv('test_mnist.csv', index=False)
<file_sep>/Custom_Data_loading.py
from __future__ import print_function, division
import os
import torch
import pandas as pd
from PIL import Image
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn.functional as F
import torch.optim as optim
num_epochs = 10
batch_size = 100
learning_rate = 0.001
class MNISTDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations and absolute image paths.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
#create a list with image names
tmp_df = pd.read_csv(csv_file)
self.tmp_df=tmp_df
self.img_names = tmp_df['im_path']
self.labels=tmp_df['label']
# assert tmp_df['image_name'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all(),
self.transform = transform
def __len__(self):
return len(self.img_names.index)
def __getitem__(self, idx):
img_name = self.img_names[idx]
image = np.float32(np.asarray(Image.open(img_name)))
#image = image.convert('RGB')
#label = np.float32(np.asarray([self.labels[idx]]))
label = self.labels[idx]
#label = torch.from_numpy(np.asarray(label).reshape([1, 1]))
#label = torch.from_numpy(np.asarray(label))
#label = torch.from_numpy(label)
image = np.reshape(image, [1, image.shape[0], image.shape[1]])
image = torch.from_numpy(image)
if self.transform:
image = self.transform(image)
return image, label
transformations = transforms.Compose([transforms.ToTensor()])
dset_train = MNISTDataset('train_mnist.csv')#,transformations)
dset_test = MNISTDataset('test_mnist.csv')#,transformations)
train_loader = DataLoader(dset_train,
batch_size=batch_size,
shuffle=True,
num_workers=10 # 1 for CUDA
# pin_memory=True # CUDA only
)
test_loader = DataLoader(dset_test,
batch_size=batch_size,
shuffle=True,
num_workers=10 # 1 for CUDA
# pin_memory=True # CUDA only
)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2))
self.fc = nn.Linear(7 * 7 * 32, 10)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
cnn = CNN()
#cnn.cuda()
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(cnn.parameters(), lr=learning_rate)
# Train the Model
num_epochs=100
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images)#.cuda()
labels = Variable(labels)#.cuda()
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = cnn(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
print ('Epoch [%d/%d], Iter [%d/%d] Loss: %.4f'
% (epoch + 1, num_epochs, i + 1, dset_train.__len__() // batch_size, loss.data[0]))
# Test the Model
cnn.eval() # Change model to 'eval' mode (BN uses moving mean/var).
correct = 0
total = 0
for images, labels in test_loader:
images = Variable(images)#.cuda()
outputs = cnn(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted.cpu() == labels).sum()
print('Test Accuracy of the model on the 10000 test images: %d %%' % (100 * correct / total))
# Save the Trained Model
torch.save(cnn.state_dict(), 'cnn.pkl') | 2843ec77a93aacf05fb935f302c2faf724852e59 | [
"Markdown",
"Python"
] | 4 | Markdown | Giounona/LearnPytorch | aa5c1d50659d7c8d04dc97dfb6ae7ddb9a3fdd0f | 72a4ff6e75248aa43e3165f4ac2c5f69b21674cb |
refs/heads/master | <repo_name>diwasx/neural_network_scratch<file_sep>/Implementation_NN/2_nn_XNOR_gate_training_visualization.py
#!/bin/python3
import sys
import random
import numpy as np
sys.path.append('..')
from neural_network import NeuralNetwork
inputLen = 2
hiddenLen = 7
outputLen = 1
learningRate = 0.1
n = NeuralNetwork(inputLen, hiddenLen, outputLen)
training_data = {
1: {'inputs': np.array([[0],[0]]), 'targets': np.array([[1]])},
2: {'inputs': np.array([[0],[1]]), 'targets': np.array([[0]])},
3: {'inputs': np.array([[1],[0]]), 'targets': np.array([[0]])},
4: {'inputs': np.array([[1],[1]]), 'targets': np.array([[1]])},
}
# Supervised Training with Visualization
loopForVisualization = 300
loopForSpeedUp = 30
for i in range(loopForVisualization):
print("Training no: " + str(i+1))
for j in range (loopForSpeedUp):
x = random.choice(list(training_data.values()))
inputs = x.get('inputs')
targets = x.get('targets')
n.trainSVLearing(inputs,targets,learningRate)
x = random.choice(list(training_data.values()))
inputs = x.get('inputs')
targets = x.get('targets')
tk = n.trainSVLearingVisualization(inputs,targets,learningRate)
# Testing Part
print("\033[4m" + "\n### Testing Phase ###" + "\033[0m")
inputs = np.array([
[0],
[0]
])
print(n.feedForward(inputs))
inputs = np.array([
[0],
[1]
])
print(n.feedForward(inputs))
inputs = np.array([
[1],
[0]
])
print(n.feedForward(inputs))
inputs = np.array([
[1],
[1]
])
print(n.feedForward(inputs))
tk.mainloop()
<file_sep>/Implementation_Perceptron/8_perceptron_OR_gate_visualization_sign.py
#!/bin/python3
import sys
sys.path.append('..')
from perceptron import Perceptron
from tkinter import *
import random
import time
tk = Tk()
widthSize = 500
heightSize = 500
frameRate = 60
frameSpeed = int(1 / frameRate * 1000)
canvas = Canvas(tk, width=widthSize, height=heightSize, background="black")
tk.title("Drawing_float")
canvas.pack()
inputLen = 3
learnRate = 0.1
bias = 1
p = Perceptron(inputLen,"sign")
def classification(x):
if ( x == -1):
return 0
else:
return 1
# for i in range(20):
def training():
inputs = [bias,0,0]
target = 0
p.train(inputs,target, learnRate, classification)
inputs = [bias,0,1]
target = 1
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,0]
target = 1
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,1]
target = 1
p.train(inputs,target, learnRate, classification)
# for i in range(100):
while True:
training()
resolution = 10
cols = widthSize/resolution
rows = heightSize/resolution
for i in range(int(cols)):
for j in range(int(rows)):
x1 = i/cols
x2 = j/rows
inputs = [bias,x1,x2]
print("Input Drawing = " + str(inputs))
y = p.guess(inputs)
output = classification(y)
if (output == 0):
color = '#000000000'
else:
color = '#fffffffff'
rect = canvas.create_rectangle(i*resolution, j*resolution, (i+1)*resolution, (j+1)*resolution, outline='red')
canvas.itemconfig(rect, fill=color)
tk.after(frameSpeed, tk.update()) # for every give time updates frame
tk.mainloop()
<file_sep>/README.md
# neural_network_scratch
Basic Neural Network Library from scratch.
## Requirement
>python3, pip3
## Installation
```
git clone https://github.com/diwasx/neural_network_scratch
cd neural_network_scratch
pip3 install -r requirements.txt --user
```
## Library usage
**Creating object and initializing constructor:**
NeuralNetwork (inputLength, hiddenLength, outputLength)
```
n = NeuralNetwork(3, 10, 9)
```
**Generating output using FeedForward**
```
n.feedForward(inputs)
```
**Neural Network Structure**
```
n.nnStructure()
```
**Training NN with know data (supervised learning)**
```
n.trainSVLearing(inputs,targets,learningRate)
```
**Training Visualization with weights and biases changes**
```
n.trainSVLearingVisualization(inputs,targets,learningRate)
```
## Library Implementation (Examples)
* Logical Gates
* Digit Recognition
* Machine Play T-rex game using NN and genetic algorithm (NEAT algorithm)
<file_sep>/Backup/neural_network_verbose.py
#!/bin/python3
# Two layer neural network (Fully connected)
import random
import math
import sys
from tkinter import *
import numpy as np
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# Function return value between 0 and 1 for all element of matrix
def sigmoid(x):
tmpMatrix = np.zeros(shape=(len(x),1))
# f(x) = 1/(1+e^-x)
for i in range(len(x)):
# Argument is a large negative value, so it is calling exp() with a large positive value. It is very easy to exceed floating point range that way
# This condition solve that problem
if (x[i][0]) < 0:
tmpMatrix[i][0] = 1 - 1/(1+math.exp(x[i][0]))
else:
# Original sigmoid function
tmpMatrix[i][0] = 1/(1+math.exp(-x[i][0]))
return (tmpMatrix)
# Function return derivative value of sigmoid function for all element of matrix
def dSigmoid(x):
tmpMatrix = np.zeros(shape=(len(x),1))
# sig'(x) = sig(x)[1-sig(x)]
for i in range(len(x)):
tmpMatrix[i][0] = x[i][0] * (1 - x[i][0])
return (tmpMatrix)
class NeuralNetwork:
# Constructor
def __init__(self, inputLen, hiddenLen, outputLen):
self.i = inputLen # input
self.j = hiddenLen # hidden
self.k = outputLen # output
self.scaleFac = 1
self.gapVal = 200
self.tk = Tk()
self.tk.title("Drawing_float")
widthSize = 800
heightSize = 700
self.canvas = Canvas(self.tk, width=widthSize, height=heightSize)
# Creating weights and assiging random values
# Weights for Hidden
self.weightsHid = np.zeros(shape=(self.j,self.i)) # w
for m in range(self.j):
for n in range(self.i):
randVal = random.uniform(-1,1)
self.weightsHid[m][n] = randVal
print("\nWeights of hidden\n" + str(self.weightsHid))
# Weights for Output
self.weightsOut = np.zeros(shape=(self.k,self.j)) # w'
for m in range(self.k):
for n in range(self.j):
randVal = random.uniform(-1,1)
self.weightsOut[m][n] = randVal
print("\nWeights of output\n" + str(self.weightsOut))
# Creating Bias and assiging random values
# Bias for Hidden
self.biasHid = np.zeros(shape=(self.j,1))
for j in range(self.j):
randVal = random.uniform(-1,1)
self.biasHid[j][0] = randVal
print("\nBias of hidden\n" + str(self.biasHid))
# Bias for Output
self.biasOut = np.zeros(shape=(self.k,1))
for k in range(self.k):
randVal = random.uniform(-1,1)
self.biasOut[k][0] = randVal
print("\nBias of output\n" + str(self.biasOut))
print("\n")
# Algorithm that computes output based on weight and bias (similar to guess function in perceptron)
def feedForward(self,inputs):
print("\n<-- Feed forward --->")
self.inputs = inputs
print("\nInput matrix\n" + str(self.inputs))
self.hiddens = self.weightsHid.dot(self.inputs) + self.biasHid
print("\nMatrix of Hiddens \n"+ str(self.hiddens))
self.hiddens = sigmoid(self.hiddens)
print("\nMatrix of Hiddens after activation\n"+ str(self.hiddens))
self.outputs = self.weightsOut.dot(self.hiddens) + self.biasOut
print("\nMatrix of Outputs \n" + str(self.outputs))
self.outputs = sigmoid(self.outputs)
print(bcolors.OKBLUE + "\nMatrix of Outputs after activation\n"+ str(self.outputs) + bcolors.ENDC)
return self.outputs
# Training NN using Supervised learning
def trainSVLearing(self, inputs, targets, learningR):
# Guess outputs from inputs
self.feedForward(inputs)
print("\n<-- Backpropagation --->")
# Calculate output errors
output_errors = targets - self.outputs
print("\nMatrix of Inputs\n"+ str(inputs))
print("\nMatrix of Targets\n"+ str(targets))
print("\nMatrix of Outputs \n"+ str(self.outputs))
print("\nMatrix of Output Errors\n"+ str(output_errors))
print("\n<-- Gradient Descent of Output--->")
# Output Gradient
output_gradient = dSigmoid(self.outputs)
print("\nOutput Gradient\n"+ str(output_gradient))
# Delta Output weights
# weightsOut_delta = learningR * output_errors * output_gradient ∙ hiddens.transpose()
# * represent hadamard product dot(∙) represent matrix dot product
tmpOut = learningR * output_errors * output_gradient
print("\ntmpOut\n"+ str(tmpOut))
print("\nHiddens Transpose\n"+ str(self.hiddens.transpose()))
weightsOut_delta = tmpOut.dot(self.hiddens.transpose())
print("\nOutput deltaWeight\n"+ str(weightsOut_delta))
# New Output weights
self.weightsOut += weightsOut_delta
print(bcolors.OKBLUE + "\nNew Output Weights\n"+ str(self.weightsOut))
# new biasOut += learningR * output_errors * output_gradient
self.biasOut+=tmpOut
print("\nNew Output Bias\n"+ str(self.biasOut) + bcolors.ENDC)
# Calculate hidden errors
weightsOutTranspose = self.weightsOut.transpose()
print("\nWeight of outputs transpose\n"+ str(weightsOutTranspose))
hidden_errors = weightsOutTranspose.dot(output_errors)
print("\nMatrix of Hidden Errors\n"+ str(hidden_errors))
print("\n<-- Gradient Descent of Hidden--->")
# Hidden Gradient
hidden_gradient = dSigmoid(self.hiddens)
print("\nHiddens Gradient\n"+ str(hidden_gradient))
# Delta Hidden weights
# weightsHid_delta = learningR * hidden_errors * hidden_gradient ∙ inputs.transpose()
# (*) represent hadamard product dot(∙) represent matrix dot product
tmpHid = learningR * hidden_errors * hidden_gradient
print("\ntmpHid\n"+ str(tmpHid))
print("\nInputs Transpose\n"+ str(self.inputs.transpose()))
weightsHid_delta = tmpHid.dot(self.inputs.transpose())
print("\nHidden deltaWeight\n"+ str(weightsHid_delta))
# New Hiddens weights
self.weightsHid += weightsHid_delta
print(bcolors.OKBLUE + "\nNew Hiddens Weights\n"+ str(self.weightsHid))
# new biasHid += learningR * hidden_errors * hidden_gradient
self.biasHid+=tmpHid
print("\nNew Hiddens Bias\n"+ str(self.biasHid) + bcolors.ENDC)
def nnStructure(self):
# Best view upto 18 nodes
frameRate = 60
frameSpeed = int(1 / frameRate * 1000)
widthSize = 800
heightSize = 700
self.canvas.pack()
# For input layer
inputNodes = [None] * self.i
hiddenWLines = [None] * self.i
y = 0
# Starting Position
yStart = 50 * self.scaleFac
for m in range(self.i):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.nnStructure()
x1, y1 = 50/self.scaleFac, yStart+y
x2, y2 = 90/self.scaleFac, yStart+y+40
inputNodes[m] = self.canvas.create_oval(x1*self.scaleFac, y1*self.scaleFac, x2*self.scaleFac, y2*self.scaleFac, fill="white")
# For hidden weight line
xic, yic = (x1+x2)/2, (y1+y2)/2
yTmp = 0
yStartTmp = 50 * self.scaleFac
for n in range(self.j):
x1, y1 = 350/self.scaleFac, yStartTmp+yTmp
x2, y2 = 390/self.scaleFac, yStartTmp+yTmp+40
xhc, yhc = (x1+x2)/2, (y1+y2)/2
weight = self.weightsHid[n][m]
if(weight > 0):
color = "red";
else:
color = "green";
hiddenWLines = self.canvas.create_line(xic*self.scaleFac, yic*self.scaleFac, xhc*self.scaleFac, yhc*self.scaleFac, fill=color, width=3)
# GapsTmp
yTmp = yTmp + self.gapVal
# Gaps
y = y + self.gapVal
# For Hidden layer
hiddenNodes = [None] * self.j
y = 0
yStart = 50 * self.scaleFac
for m in range(self.j):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.nnStructure()
x1, y1 = 350/self.scaleFac, yStart+y
x2, y2 = 390/self.scaleFac, yStart+y+40
hiddenNodes[m] = self.canvas.create_oval(x1* self.scaleFac, y1* self.scaleFac, x2* self.scaleFac, y2* self.scaleFac, fill="white")
# For output weight line
xhc, yhc = (x1+x2)/2, (y1+y2)/2
yTmp = 0
yStartTmp = 50* self.scaleFac
for n in range(self.k):
x1, y1 = 650/self.scaleFac, yStartTmp+yTmp
x2, y2 = 690/self.scaleFac, yStartTmp+yTmp+40
xoc, yoc = (x1+x2)/2, (y1+y2)/2
weight = self.weightsOut[n][m]
if(weight > 0):
color = "red";
else:
color = "green";
hiddenWLines = self.canvas.create_line(xhc* self.scaleFac, yhc* self.scaleFac, xoc* self.scaleFac, yoc* self.scaleFac, fill=color, width=3)
# GapsTmp
yTmp = yTmp + self.gapVal
# Gaps
y = y + self.gapVal
# For Output layer
outputNodes = [None] * self.k
y = 0
yStart = 50* self.scaleFac
for m in range(self.k):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.nnStructure()
x1, y1 = 650/self.scaleFac, yStart+y
x2, y2 = 690/self.scaleFac, yStart+y+40
outputNodes[m] = self.canvas.create_oval(x1* self.scaleFac, y1* self.scaleFac, x2* self.scaleFac, y2* self.scaleFac, fill="white")
# Gaps
y = y + self.gapVal
# while True:
self.tk.after(frameSpeed, self.tk.update())
return (self.tk)
def trainSVLearingVisualization(self,inputs,targets,learningRate):
# Best view upto 18 nodes
self.canvas.pack()
widthSize = 800
heightSize = 700
frameRate = 60
frameSpeed = int(1 / frameRate * 1000)
# For input layer
inputNodes = [None] * self.i
hiddenWLines = [None] * self.i
y = 0
# Starting Position
yStart = 50 * self.scaleFac
for m in range(self.i):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.trainSVLearingVisualization(inputs,targets,learningRate)
x1, y1 = 50/self.scaleFac, yStart+y
x2, y2 = 90/self.scaleFac, yStart+y+40
inputNodes[m] = self.canvas.create_oval(x1*self.scaleFac, y1*self.scaleFac, x2*self.scaleFac, y2*self.scaleFac, fill="white")
# For hidden weight line
xic, yic = (x1+x2)/2, (y1+y2)/2
yTmp = 0
yStartTmp = 50 * self.scaleFac
for n in range(self.j):
x1, y1 = 350/self.scaleFac, yStartTmp+yTmp
x2, y2 = 390/self.scaleFac, yStartTmp+yTmp+40
xhc, yhc = (x1+x2)/2, (y1+y2)/2
weight = self.weightsHid[n][m]
if(weight > 0):
color = "red";
else:
color = "green";
hiddenWLines = self.canvas.create_line(xic*self.scaleFac, yic*self.scaleFac, xhc*self.scaleFac, yhc*self.scaleFac, fill=color, width=3)
# GapsTmp
yTmp = yTmp + self.gapVal
# Gaps
y = y + self.gapVal
# For Hidden layer
hiddenNodes = [None] * self.j
y = 0
yStart = 50 * self.scaleFac
for m in range(self.j):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.trainSVLearingVisualization(inputs,targets,learningRate)
x1, y1 = 350/self.scaleFac, yStart+y
x2, y2 = 390/self.scaleFac, yStart+y+40
hiddenNodes[m] = self.canvas.create_oval(x1* self.scaleFac, y1* self.scaleFac, x2* self.scaleFac, y2* self.scaleFac, fill="white")
# For output weight line
xhc, yhc = (x1+x2)/2, (y1+y2)/2
yTmp = 0
yStartTmp = 50* self.scaleFac
for n in range(self.k):
x1, y1 = 650/self.scaleFac, yStartTmp+yTmp
x2, y2 = 690/self.scaleFac, yStartTmp+yTmp+40
xoc, yoc = (x1+x2)/2, (y1+y2)/2
weight = self.weightsOut[n][m]
if(weight > 0):
color = "red";
else:
color = "green";
hiddenWLines = self.canvas.create_line(xhc* self.scaleFac, yhc* self.scaleFac, xoc* self.scaleFac, yoc* self.scaleFac, fill=color, width=3)
# GapsTmp
yTmp = yTmp + self.gapVal
# Gaps
y = y + self.gapVal
# For Output layer
outputNodes = [None] * self.k
y = 0
yStart = 50* self.scaleFac
for m in range(self.k):
# If object is out of canvas, small scale factor
if(y >= heightSize):
self.scaleFac = self.scaleFac * 0.999
self.gapVal -= 0.8
self.canvas.delete("all")
return self.trainSVLearingVisualization(inputs,targets,learningRate)
x1, y1 = 650/self.scaleFac, yStart+y
x2, y2 = 690/self.scaleFac, yStart+y+40
outputNodes[m] = self.canvas.create_oval(x1* self.scaleFac, y1* self.scaleFac, x2* self.scaleFac, y2* self.scaleFac, fill="white")
# Gaps
y = y + self.gapVal
self.tk.after(frameSpeed, self.tk.update())
self.trainSVLearing(inputs,targets,learningRate)
return (self.tk)
# For Neuro Evolution
def copy(self):
return (self)
def mutate(self, mutationRate):
def mutateElement(val):
if (random.uniform(0,1) < mutationRate):
# x = (random.uniform(0,100))
x = 2 * random.uniform(0,1) - 1
return x
else:
return val
vfunc = np.vectorize(mutateElement)
self.weightsHid = vfunc(self.weightsHid)
self.weightsOut = vfunc(self.weightsOut)
self.biasHid = vfunc(self.biasHid)
self.biasOut = vfunc(self.biasOut)
<file_sep>/Implementation_Perceptron/4_perceptron_NOR_gate_sigmoid.py
#!/bin/python3
import sys
sys.path.append('..')
from perceptron import Perceptron
inputLen = 3
learnRate = 0.1
bias = 1
p = Perceptron(inputLen,"sigmoid")
# Classification function to be used and pass to perceptron when training
# Kind of regresssion
def classification(x):
if ( x < 0.5):
return 0
else:
return 1
for i in range(20):
inputs = [bias,0,0]
target = 1
p.train(inputs,target, learnRate, classification)
inputs = [bias,0,1]
target = 0
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,0]
target = 0
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,1]
target = 0
p.train(inputs,target, learnRate, classification)
result = p.guess([bias,0,0])
output = classification(result)
print("After training => " + str(output))
result = p.guess([bias,0,1])
output = classification(result)
print("After training => " + str(output))
result = p.guess([bias,1,0])
output = classification(result)
print("After training => " + str(output))
result = p.guess([bias,1,1])
output = classification(result)
print("After training => " + str(output))
<file_sep>/Implementation_NN/3_nn_XOR_gate_visualization.py
#!/bin/python3
import sys
import random
import numpy as np
sys.path.append('..')
from neural_network import NeuralNetwork
import time
from tkinter import *
tk = Tk()
widthSize = 500
heightSize = 500
frameRate = 60
frameSpeed = int(1 / frameRate * 1000)
canvas = Canvas(tk, width=widthSize, height=heightSize, background="black")
tk.title("Drawing_float")
canvas.pack()
inputLen = 2
hiddenLen = 4
outputLen = 1
learningRate = 0.1
n = NeuralNetwork(inputLen, hiddenLen, outputLen)
# With this structure, answer may not be predicted sometimes
# n = NeuralNetwork(2, 2, 1)
training_data = {
1: {'inputs': np.array([[0],[0]]), 'targets': np.array([[0]])},
2: {'inputs': np.array([[0],[1]]), 'targets': np.array([[1]])},
3: {'inputs': np.array([[1],[0]]), 'targets': np.array([[1]])},
4: {'inputs': np.array([[1],[1]]), 'targets': np.array([[0]])},
}
def training():
x = random.choice(list(training_data.values()))
inputs = x.get('inputs')
targets = x.get('targets')
n.trainSVLearing(inputs,targets,learningRate)
n.tk.destroy()
while True:
for i in range(2000):
training()
resolution = 10
cols = widthSize/resolution
rows = heightSize/resolution
for i in range(int(cols)):
for j in range(int(rows)):
x1 = i/cols
x2 = j/rows
inputs = np.array([[x1],[x2]])
print ("Inputs = "+ str(inputs))
y = n.feedForward(inputs)
print ("Output = "+ str(y))
output = y
# print("Value of y is = " + str(output))
color = int(output * 255)
# print("Value of color is = " + str(color))
hexColor = format(color, '02x')
# print("Value of hex is = " + str(hexColor))
finalColor = "#" + hexColor + hexColor + hexColor
print("finalColor = " + str(finalColor))
# rect = canvas.create_rectangle(i*resolution, j*resolution, (i+1)*resolution, (j+1)*resolution, outline='red')
rect = canvas.create_rectangle(i*resolution, j*resolution, (i+1)*resolution, (j+1)*resolution)
# canvas.itemconfig(rect, fill="#ff00ff")
canvas.itemconfig(rect, fill=finalColor)
tk.after(frameSpeed, tk.update()) # for every give time updates frame
tk.mainloop()
<file_sep>/Backup/perceptron.py_old
#!/bin/python3
import random
import math
# Function return 1 for positive and -1 for negative value
def sign(a):
if (a > 0):
return 1
elif (a <= 0):
return -1
# Function return value between 0 and 1 for x input
def sigmoid(a):
out = 1/(1+math.exp(-a))
return (out)
class Perceptron:
# Constructor
def __init__(self,inputLen):
self.weights = [None] * inputLen
self.inputs = []
self.learnRate = 0
# Assiging random values to weights
for i in range(len(self.weights)):
# for i in self.weights: # (similar to for each)
# randVal = randint(0,9)
randVal = random.uniform(-1,1)
self.weights[i] = randVal
# print("Random weights = " + str(self.weights))
# Function for guessing output
def guess(self,inputs):
self.inputs = inputs
total = 0
for i in range(len(self.weights)):
total += self.inputs[i]*self.weights[i]
# print("Sum = " + str(total))
# Activation function
output = sign(total)
# print("Output = " + str(output))
if (output == -1):
return 0
else:
return 1
def guessAnimate(self,inputs):
self.inputs = inputs
total = 0
for i in range(len(self.weights)):
total += self.inputs[i]*self.weights[i]
print("Sum = " + str(total))
# Activation function
return sigmoid(total)
# Training perceptron with known answer (supervised learning)
def train(self, inputs, target, r):
self.learnRate = r
self.inputs = inputs
guessVal = self.guess(self.inputs)
# print("Inputs value = " + str(inputs))
# print("Target value = " + str(target))
# print("Guess value = " + str(guessVal))
error = target - guessVal
# print("Error = " + str(error))
# Tuning weights
for i in range(len(self.weights)):
# Gradient descent
deltaWeight = error * self.inputs[i] * self.learnRate
print("deltaWeight [" + str(i) + "] = " + str(deltaWeight))
self.weights[i] += deltaWeight
print("New weight [" + str(i) + "] = " + str(self.weights))
print("Succesfully trained\n")
<file_sep>/Implementation_NN/1_nn_XOR_gate.py
#!/bin/python3
import sys
import os
import random
import numpy as np
sys.path.append('..')
from neural_network import NeuralNetwork
# from neural_network_verbose import NeuralNetwork
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
inputLen = 2
hiddenLen = 4
outputLen = 1
learningRate = 0.1
n = NeuralNetwork(inputLen, hiddenLen, outputLen)
# n = NeuralNetwork(2, 2, 1)
training_data = {
1: {'inputs': np.array([[0],[0]]), 'targets': np.array([[0]])},
2: {'inputs': np.array([[0],[1]]), 'targets': np.array([[1]])},
3: {'inputs': np.array([[1],[0]]), 'targets': np.array([[1]])},
4: {'inputs': np.array([[1],[1]]), 'targets': np.array([[0]])},
}
print("\033[4m" + "\n### Training ###" + "\033[0m")
# x = random.choice(list(training_data.values()))
# print (x.get('inputs'))
for i in range(10000):
# for i in range(8000):
# x = random.choice(list(training_data.keys()))
x = random.choice(list(training_data.values()))
inputs = x.get('inputs')
targets = x.get('targets')
# print("Input = " + str(inputs))
# print("Targets = " + str(targets) + "\n")
blockPrint()
n.trainSVLearing(inputs,targets,learningRate)
enablePrint()
print("\033[4m" + "\n### Testing Phase ###" + "\033[0m")
inputs = np.array([
[0],
[0]
])
print(n.feedForward(inputs))
inputs = np.array([
[0],
[1]
])
print(n.feedForward(inputs))
inputs = np.array([
[1],
[0]
])
print(n.feedForward(inputs))
inputs = np.array([
[1],
[1]
])
print(n.feedForward(inputs))
tkVis = n.nnStructure()
tkVis.mainloop()
<file_sep>/Implementation_NN/5_nn_digit_recognition.py
#!/bin/python3
import sys
import random
import numpy as np
from tkinter import *
# from sklearn import datasets as d
import sklearn.datasets as d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from PIL import ImageTk, Image, ImageDraw, ImageOps
import PIL
sys.path.append('..')
from neural_network import NeuralNetwork
learningRate = 0.1
# nn = NeuralNetwork(64, 100, 10)
nn = NeuralNetwork(64, 150, 10)
# nn = NeuralNetwork(18, 18, 18)
digits = d.load_digits()
def normalization(x):
minX = 0
maxX = 16
y = (x-minX)/(maxX-minX)
y = y*255
return int(y)
def showPic(i):
imgTrain = digits.images[i]
target = digits.target[i]
# print(imgTrain)
# print(target)
# Diplaying image
style.use('fivethirtyeight')
fig = plt.figure(1,figsize=(5,6))
fig = plt.gcf()
plt.xlabel("Target = " + str(target))
fig.canvas.set_window_title('Drawing_float')
# print(imgTrain)
vfunc = np.vectorize(normalization)
normalizedImg = vfunc(imgTrain)
normalizedImgInv = 255-normalizedImg
# print(normalizedImg)
print(normalizedImgInv)
# plt.imshow(normalizedImg, cmap=plt.cm.gray_r, interpolation='nearest')
# plt.imshow(normalizedImg, cmap=plt.cm.gray, interpolation='nearest')
plt.imshow(normalizedImgInv, cmap=plt.cm.gray, interpolation='nearest')
# plt.imshow(normalizedImg)
plt.show()
def training():
print ("\nTraining -------\n")
# for i in range (10):
for i in range (10):
# (total no of data = 1797)
for i in range(1437):
imgTrain = digits.images[i]
target = digits.target[i]
# print(imgTrain)
# print(target)
# Training NN with training images
imgVec = np.zeros(shape=(64,1))
targetVec = np.zeros(shape=(10,1))
targetVec[target] = 1
n = 0
for i in range(8):
for j in range(8):
imgVec[n] = imgTrain[i][j]
n+=1
# print ("\nImage Vector is \n" + str(imgVec) + "\n")
# print ("\nTarget Vector is \n" + str(targetVec) + "\n")
nn.trainSVLearing(imgVec, targetVec, learningRate)
def testing():
# Testing NN with testing images
a = 0
start=1437
end=1797
# start=1
# end=1437
print ("\nTesting")
for z in range(start,end):
imgTest = digits.images[z]
imgVec = np.zeros(shape=(64,1))
n = 0
for i in range(8):
for j in range(8):
imgVec[n] = imgTest[i][j]
n+=1
outputMat = nn.feedForward(imgVec)
maxVal = outputMat.max()
output = outputMat.tolist().index(maxVal)
target = digits.target[z]
# print ("\nOutput Matrix\n" + str(outputMat) + "\n")
# print ("\nGuess Value \n" + str(output) + "\n")
# print ("\nActual Value\n" + str(target) + "\n")
if (output == target):
a+=1
accuracy = a/(end-start)
print ("Accuracy %\n" + str(accuracy) + "\n")
def drawingCanvas():
width = 100
height = 100
# width = 400
# height = 400
white = (255, 255, 255)
green = (0,128,0)
def save():
filename = "image.png"
image1.save(filename)
original_image = Image.open("image.png")
size = (8,8)
resizeImg = ImageOps.fit(original_image, size, Image.ANTIALIAS).convert('L')
# print (resizeImg)
# img = Image.open('image.png')
# img = Image.open('image.png').convert('LA')
arr = np.array(resizeImg)
normalizeArr = 255-arr
# print(arr)
# print(normalizeArr)
imgVec = np.zeros(shape=(64,1))
n = 0
for i in range(8):
for j in range(8):
imgVec[n] = normalizeArr[i][j]
n+=1
# print(imgVec)
outputMat = nn.feedForward(imgVec)
maxVal = outputMat.max()
output = outputMat.tolist().index(maxVal)
print("Machine Predicted: " +str(output))
def machineImg():
randVal = random.randint(0,1796)
target = digits.target[randVal]
if (target == output):
imgTrain = digits.images[randVal]
vfunc = np.vectorize(normalization)
normalizedImg = vfunc(imgTrain)
global machineArr
machineArr = 255-normalizedImg
# print("MachineArr:\n" + str(machineArr))
return;
machineImg()
machineImg()
# print("User Img:\n" + str(arr))
global machineArr
# print("Machine Predicted:\n" + str(machineArr))
plt.subplot(1,2,1);
plt.imshow(arr, cmap=plt.cm.gray, interpolation='nearest')
plt.subplot(1,2,2);
plt.imshow(machineArr, cmap=plt.cm.gray, interpolation='nearest')
plt.show()
def paint(event):
# python_green = "#476042"
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
# cv.create_oval(x1, y1, x2, y2, fill="black",width=10)
cv.create_line(x1, y1, x2, y2, fill="black",width=7)
draw.line([x1, y1, x2, y2],fill="black",width=7)
# draw.ellipse([x1, y1, x2*1.2, y2*1.2],fill="black",width=10)
def clear():
cv.delete("all")
draw.rectangle([0, 0, 400, 400],fill="white",width=10)
root = Tk()
root.title( "Drawing_float" )
# Tkinter create a canvas to draw on
cv = Canvas(root, width=width, height=height, bg='white')
cv.pack(padx=10, pady=10)
cv.pack()
# PIL create an empty image and draw object to draw on memory only, not visible
image1 = PIL.Image.new("RGB", (width, height), white)
draw = ImageDraw.Draw(image1)
# Tkinter canvas drawings (visible)
# cv.create_line([0, center, width, center], fill='green')
cv.pack(expand=YES, fill=BOTH)
cv.bind("<B1-Motion>", paint)
buttonPredict=Button(root,text="save",command=save)
buttonClear=Button(root,text="clear",command=clear)
buttonPredict.pack()
buttonClear.pack()
root.mainloop()
# showPic(6)
# nn.nnVisualization()
training()
testing()
nn.tk.destroy()
drawingCanvas()
<file_sep>/Implementation_NN/game/TRex-run/TRex_NEAT_nnVisualization.py
#!/bin/python
import pygame
import random
import time
import sys
import numpy as np
sys.path.append('../../..')
from neural_network import NeuralNetwork
pygame.init()
highScore = 0
population = 130
# population = 180
generation = 1
class Dino():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.scoreVal = 0
self.fitness = 0
self.height = height
self.isJump = False
self.jumpCount = 15
# self.brain = NeuralNetwork(6,100,3)
# self.brain = NeuralNetwork(6,50,3)
self.brain = NeuralNetwork(6,18,3)
# self.brain = NeuralNetwork(6,80,3)
self.color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
def draw(self, win):
self.rectangle = pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))
# return a
def collisionDetect(self, rectObs):
if(self.rectangle.colliderect(rectObs)):
global dinosours
# print("Dinosour poped" + str(self))
savedDino.append(self)
index = dinosours.index(self)
dinosours.pop(index)
print("Dinosours left " + str(len(dinosours)))
def think(self):
global obstacles, speed
if (len(obstacles) != 0):
aiSeeX = obstacles[0].x
aiSeeY = obstacles[0].y
aiSeeWidth = obstacles[0].width
aiSeeHeight = obstacles[0].height
aiSeeSpeed = speed
if self.isJump == True:
aiSeeJump = 1
else:
aiSeeJump = 0
inputs = np.array([[aiSeeX],[aiSeeY], [aiSeeWidth], [aiSeeHeight], [aiSeeSpeed], [aiSeeJump]])
output = self.brain.feedForward(inputs)
# print(output)
maxVal = output.max()
output = output.tolist().index(maxVal)
# print(output)
if (output == 0):
# print("Duck")
if not(self.isJump):
# Ducking
self.width,self.height = 90,30
self.y +=60
elif (output == 1):
# print("Jump")
if not(self.isJump):
self.isJump = True
# else:
# print("Do nothing")
if (self.isJump):
if self.jumpCount >= -15:
self.y -= (self.jumpCount * 2)
self.jumpCount -= 1
else:
self.isJump = False
self.jumpCount = 15
class Obstacle():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
def draw(self, win, speed):
b = pygame.draw.rect(win, (255,0,0), (self.x, self.y, self.width, self.height))
self.x -= self.vel * speed
return b
def redrawGameWindow():
global gen
global speed
global obstacles
global highScore
global score
global font
global dinosours
global generation
speed +=.0008
score +=1
if (highScore < score):
highScore = score
gen +=1
# Clearing window
win.fill((0,0,0))
# Scrores
font = pygame.font.SysFont('Arial', 25)
win.blit(font.render("Score: "+str(score), True, (255,0,255)), (1000, 50))
win.blit(font.render("Highscore: "+str(highScore), True, (0,255,255)), (780, 50))
win.blit(font.render("Generation: "+str(generation), True, (255,255,0)), (580, 50))
pygame.draw.line(win, (255,0,0), (0,400), (screenWidth, 400))
# Dino part
for dinosour in dinosours:
dinosour.draw(win)
dinosour.scoreVal+=1
dinosour.width,dinosour.height = 30,90
if not(dinosour.isJump):
dinosour.y=310
# Obstacle part
rand = random.randint(0,50)
if (gen > 25):
if (rand == 0):
tmp = random.randint(0,15)
# print (tmp)
# Cactus normal
if (tmp > 0 and tmp <=4):
c = Obstacle(screenWidth,340,50,60)
# Cactus large
elif (tmp > 4 and tmp <=8):
c = Obstacle(screenWidth,340,80,60)
# Cactus tall
elif (tmp > 8 and tmp <=12):
c = Obstacle(screenWidth,310,20,90)
# Bird high
elif (tmp == 13):
c = Obstacle(screenWidth,270,30,30)
# Bird medium
elif (tmp == 14):
c = Obstacle(screenWidth,80,30,260)
# Bird low
else:
c = Obstacle(screenWidth,110,30,260)
gen = 0
obstacles.append(c)
# Looping thought all obstacle and drawing
for obstacle in obstacles:
rectObs = obstacle.draw(win,speed)
# Deleting obstacle if goes beyond left wall
if obstacle.x < 0:
obstacles.pop(obstacles.index(obstacle))
for dinosour in dinosours:
dinosour.collisionDetect(rectObs)
pygame.display.update()
dinosours = [None] * population
for i in range(population):
dinosours[i] = Dino(30,310,30,90)
def main():
global screenWidth, screenHeight, win, fps, clock, dinosours, obstacles, gen, speed, run, score, highScore, savedDino
savedDino = []
score = 0
screenWidth, screenHeight = 1200, 500
win = pygame.display.set_mode((screenWidth,screenHeight))
pygame.display.set_caption("TRex Run")
fps = 60
# fps = 120
clock = pygame.time.Clock()
# dinosour = Dino(30,310,30,90)
obstacles = []
gen = 0
speed = 1
# Mainloop
run = True
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
for dinosour in dinosours:
dinosour.think()
redrawGameWindow()
# If all dino dies, loop end
if len(dinosours) == 0:
run = False
win.fill((0,0,0))
time.sleep(0.2)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
# print("Restart")
nextGen()
def nextGen():
global generation
global savedDino
global total
global population
# print ("\n" + str(savedDino))
# Calculate fitness value
total = 0
for dino in savedDino:
total += dino.scoreVal
# print ("Total = "+ str(total))
maxFitness = 0
for dino in savedDino:
dino.fitness = dino.scoreVal / total
# print (str(dino.fitness))
if maxFitness < dino.fitness:
maxFitness = dino.fitness
bestDino = dino
for dino in savedDino:
if (dino != bestDino):
dino.brain.tk.destroy()
tkStruct = bestDino.brain.nnStructure()
global bestTk
if 'bestTk' in globals():
bestTk.destroy()
# Best Dino NN Structure
bestTk = bestDino.brain.tk
# tkStruct.mainloop()
# Selection based on fitness value
for i in range(population):
index = 0
r = random.uniform(0,1);
while (r>0):
r = r - savedDino[index].fitness;
index +=1;
index -=1
tmp = savedDino[index]
child = Dino(30,310,30,90)
# child.brain = tmp.brain.copy()
child.brain.weightsHid = tmp.brain.weightsHid
child.brain.weightsOut = tmp.brain.weightsOut
child.brain.biasHid = tmp.brain.biasHid
child.brain.biasOut = tmp.brain.biasOut
child.brain.mutate(0.03)
dinosours.append(child)
# print(len(dinosours))
# print(dinosours)
generation +=1
main()
main()
<file_sep>/Implementation_NN/game/TRex-run/TRex_game.py
#!/bin/python
import pygame
import random
import time
pygame.init()
highScore = 0
class Dino():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.isJump = False
self.jumpCount = 15
def draw(self, win):
a = pygame.draw.rect(win, (0,255,0), (self.x, self.y, self.width, self.height))
return a
class Obstacle():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
def draw(self, win, speed):
b = pygame.draw.rect(win, (255,0,0), (self.x, self.y, self.width, self.height))
self.x -= self.vel * speed
return b
def redrawGameWindow():
global gen
global speed
global obstacles
global score
global highScore
global font
speed +=.0008
score+=1
if (highScore < score):
highScore = score
# print(speed)
gen +=1
# Clearing window
win.fill((0,0,0))
# Scrores
font = pygame.font.SysFont('Arial', 25)
win.blit(font.render("Score: "+str(score), True, (255,0,255)), (1000, 50))
win.blit(font.render("Highscore: "+str(highScore), True, (0,255,255)), (780, 50))
pygame.draw.line(win, (255,0,0), (0,400), (screenWidth, 400))
# Dino part
rectDino = d1.draw(win)
d1.width,d1.height = 30,90
if not(d1.isJump):
d1.y=310
# Obstacle part
rand = random.randint(0,50)
if (gen > 25):
if (rand == 0):
tmp = random.randint(0,15)
# print (tmp)
# Cactus normal
if (tmp > 0 and tmp <=4):
c = Obstacle(screenWidth,340,50,60)
# Cactus large
elif (tmp > 4 and tmp <=8):
c = Obstacle(screenWidth,340,80,60)
# Cactus tall
elif (tmp > 8 and tmp <=12):
c = Obstacle(screenWidth,310,20,90)
# Bird high
elif (tmp == 13):
c = Obstacle(screenWidth,270,30,30)
# Bird medium
elif (tmp == 14):
c = Obstacle(screenWidth,320,30,30)
# Bird low
else:
c = Obstacle(screenWidth,350,30,30)
gen = 0
obstacles.append(c)
# Looping thought all obstacle and drawing
for obstacle in obstacles:
rectObs = obstacle.draw(win,speed)
# Deleting obstacle if goes beyond left wall
if obstacle.x < 0:
obstacles.pop(obstacles.index(obstacle))
# Collision detection
if(rectDino.colliderect(rectObs)):
# print ("collision")
global run
run = False
# pygame.quit()
# print(cactii)
pygame.display.update()
def main():
global screenWidth, screenHeight, win, fps, clock, d1, obstacles, gen, speed, run, score, highScore
score = 0
screenWidth, screenHeight = 1200, 500
win = pygame.display.set_mode((screenWidth,screenHeight))
pygame.display.set_caption("TRex Run")
fps = 60
clock = pygame.time.Clock()
d1 = Dino(30,310,30,90)
obstacles = []
gen = 0
speed = 1
# Mainloop
run = True
while run:
clock.tick(fps)
# pygame.time.delay(int(1/fps*1000))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN] and d1.x > 0:
if not(d1.isJump):
# Ducking
d1.width,d1.height = 90,30
d1.y +=60
if not(d1.isJump):
if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
d1.isJump = True
if not(d1.isJump):
if keys[pygame.K_ESCAPE]:
run = False
else:
if d1.jumpCount >= -15:
d1.y -= (d1.jumpCount * 2)
d1.jumpCount -= 1
else:
d1.isJump = False
d1.jumpCount = 15
redrawGameWindow()
win.fill((0,0,0))
win.blit(font.render("Score: "+str(score), True, (255,0,255)), (1000, 50))
win.blit(font.render("Highscore: "+str(highScore), True, (0,255,255)), (780, 50))
win.blit(font.render("Game Over, press Space to play again", True, (0,255,255)), (400, 200))
time.sleep(1)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
print("Restart")
main()
if keys[pygame.K_ESCAPE]:
print("Quit")
pygame.quit()
pygame.display.update()
main()
<file_sep>/requirements.txt
numpy
sklearn
matplotlib
sklearn
pillow
pygame
<file_sep>/Resource/Todo.txt
- total cost function of network
- graphical visualization of network
<file_sep>/perceptron.py
#!/bin/python3
import random
import math
# Function return 1 for positive and -1 for negative value
def sign(a):
if (a > 0):
return 1
elif (a <= 0):
return -1
# Function return value between 0 and 1 for x input
def sigmoid(x):
out = 1/(1+math.exp(-x))
return (out)
class Perceptron:
# Constructor
def __init__(self,inputLen,activationFunc):
self.weights = [None] * inputLen
self.inputs = []
self.learnRate = 0
self.activationFunc = activationFunc
# Assiging random values to weights
for i in range(len(self.weights)):
# for i in self.weights: # (similar to for each)
# randVal = randint(0,9)
randVal = random.uniform(-1,1)
self.weights[i] = randVal
print("Random weights = " + str(self.weights))
# Function for guessing output
def guess(self,inputs):
self.inputs = inputs
total = 0
for i in range(len(self.weights)):
total += self.inputs[i]*self.weights[i]
print("Sum = " + str(total))
# Activation function
if (self.activationFunc == "sign"):
output = sign(total)
elif (self.activationFunc == "sigmoid"):
output = sigmoid(total)
print("Output = " + str(output))
return output
# Training perceptron with known answer (supervised learning)
def train(self, inputs, target, r, classification):
self.learnRate = r
self.inputs = inputs
result = self.guess(self.inputs)
print("result value = " + str(result))
# User classification function
classifyFunc = classification
guessVal = classifyFunc(result)
print("Inputs value = " + str(inputs))
print("Target value = " + str(target))
print("Guess value = " + str(guessVal))
error = target - guessVal
print("Error = " + str(error))
# Tuning weights
for i in range(len(self.weights)):
# Gradient descent
deltaWeight = error * self.inputs[i] * self.learnRate
print("deltaWeight [" + str(i) + "] = " + str(deltaWeight))
self.weights[i] += deltaWeight
print("New weight [" + str(i) + "] = " + str(self.weights))
print("Succesfully trained\n")
<file_sep>/Implementation_Perceptron/8_perceptron_OR_gate_visualization_sigmoid.py
#!/bin/python3
import sys
sys.path.append('..')
from perceptron import Perceptron
from tkinter import *
import random
import time
tk = Tk()
widthSize = 500
heightSize = 500
frameRate = 60
frameSpeed = int(1 / frameRate * 1000)
canvas = Canvas(tk, width=widthSize, height=heightSize, background="black")
tk.title("Drawing_float")
canvas.pack()
inputLen = 3
learnRate = 0.1
bias = 1
p = Perceptron(inputLen,"sigmoid")
def classification(x):
if ( x < 0.5):
return 0
else:
return 1
# for i in range(20):
def training():
inputs = [bias,0,0]
target = 0
p.train(inputs,target, learnRate, classification)
inputs = [bias,0,1]
target = 1
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,0]
target = 1
p.train(inputs,target, learnRate, classification)
inputs = [bias,1,1]
target = 1
p.train(inputs,target, learnRate, classification)
# for i in range(100):
while True:
training()
resolution = 10
cols = widthSize/resolution
rows = heightSize/resolution
for i in range(int(cols)):
for j in range(int(rows)):
x1 = i/cols
x2 = j/rows
inputs = [bias,x1,x2]
y = p.guess(inputs)
output = classification(y)
# output = y
# print("Value of y is = " + str(output))
# color = int(output * 255)
# print("Value of color is = " + str(color))
# hexColor = format(color, '02x')
# print("Value of hex is = " + str(hexColor))
# finalColor = "#" + hexColor + hexColor + hexColor
# print("finalColor = " + str(finalColor))
if (output == 0):
color = '#000000000'
else:
color = '#fffffffff'
rect = canvas.create_rectangle(i*resolution, j*resolution, (i+1)*resolution, (j+1)*resolution, outline='red')
# rect = canvas.create_rectangle(i*resolution, j*resolution, (i+1)*resolution, (j+1)*resolution)
# canvas.itemconfig(rect, fill="#ff00ff")
# canvas.itemconfig(rect, fill=finalColor)
canvas.itemconfig(rect, fill=color)
tk.after(frameSpeed, tk.update()) # for every give time updates frame
tk.mainloop()
| 547b2bdc69427d1386125d743eea0a9220fea766 | [
"Markdown",
"Python",
"Text"
] | 15 | Python | diwasx/neural_network_scratch | 950f63b07a3bed74e8677c633734781603959e35 | 17d383b47920a1a577cf86d57d2d1666d04693c9 |
refs/heads/main | <repo_name>sarimk80/segment_control<file_sep>/views/firstListView.swift
//
// firstListView.swift
// segment_control
//
// Created by <NAME> on 16/10/2021.
//
import SwiftUI
struct firstListView: View {
var body: some View {
NavigationView {
List{
Text(/*@START_MENU_TOKEN@*/"Placeholder"/*@END_MENU_TOKEN@*/)
Text("Placeholder")
Text("Placeholder")
Text(/*@START_MENU_TOKEN@*/"Placeholder"/*@END_MENU_TOKEN@*/)
}
.padding()
.navigationBarHidden(/*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/)
}
}
}
struct firstListView_Previews: PreviewProvider {
static var previews: some View {
firstListView()
}
}
<file_sep>/views/SecondListView.swift
//
// SecondListView.swift
// segment_control
//
// Created by <NAME> on 16/10/2021.
//
import SwiftUI
struct SecondListView: View {
var body: some View {
NavigationView {
List{
Text(/*@START_MENU_TOKEN@*/"Placeholder"/*@END_MENU_TOKEN@*/)
Text("Placeholder")
Text("Placeholder")
Text(/*@START_MENU_TOKEN@*/"Placeholder"/*@END_MENU_TOKEN@*/)
}
.padding(.top)
.navigationBarHidden(/*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/)
}
}
}
struct SecondListView_Previews: PreviewProvider {
static var previews: some View {
SecondListView()
}
}
<file_sep>/views/ContentView.swift
//
// ContentView.swift
// segment_control
//
// Created by <NAME> on 16/10/2021.
//
import SwiftUI
struct ContentView: View {
@State private var selectedpicker = 0
var body: some View {
NavigationView {
VStack {
Picker(selection: $selectedpicker, label: /*@START_MENU_TOKEN@*/Text("Picker")/*@END_MENU_TOKEN@*/) {
Text("1").tag(0)
Text("2").tag(1)
}
.padding(.horizontal)
.pickerStyle(SegmentedPickerStyle())
if selectedpicker == 0 {
firstListView()
}else{
SecondListView()
}
}
.navigationTitle("Picker")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice("iPhone 12 mini")
}
}
| cc5054952217eae8e1864d004d37d8a62ecd61fd | [
"Swift"
] | 3 | Swift | sarimk80/segment_control | 6cd42c9869693d0fdd49bc3f5aa5719951a1c9f8 | 1965c1f81d3b8b30dbdefdaf8bb756dda8c5a3a0 |
refs/heads/master | <repo_name>Adamhingoro/serverless-todo-app<file_sep>/backend/src/businessLogic/Todo.ts
import {TodoItem} from "../models/TodoItem";
import {TodoResource} from "../resources/TodoResource";
import {parseUserId} from "../auth/utils";
import {CreateTodoRequest} from "../requests/CreateTodoRequest";
import {UpdateTodoRequest} from "../requests/UpdateTodoRequest";
import {TodoUpdate} from "../models/TodoUpdate";
import { configure, getLogger } from "log4js";
const logger = getLogger("BusinessLogin");
logger.level = "debug";
logger.debug("Logging Inititiated");
const uuidv4 = require('uuid/v4');
const todoResource = new TodoResource();
// Get all Todos by User ID
export async function getAllToDo(jwtToken: string): Promise<TodoItem[]> {
const userId = parseUserId(jwtToken);
logger.debug("GetAll Todos");
return todoResource.getAllToDo(userId);
}
// Updating the Todo by userid, todoid and the new todo object.
export function updateToDo(updateTodoRequest: UpdateTodoRequest, todoId: string, jwtToken: string): Promise<TodoUpdate> {
const userId = parseUserId(jwtToken);
logger.debug("Updated Todo");
return todoResource.updateToDo(updateTodoRequest, todoId, userId);
}
// Deleting the todo by todoid and user id
export function deleteToDo(todoId: string, jwtToken: string): Promise<string> {
const userId = parseUserId(jwtToken);
logger.debug("Delete Todo");
return todoResource.deleteToDo(todoId, userId);
}
// Generating the signed URL for the S3 bucket
export function generateUploadUrl(todoId: string , jwtToken: string): Promise<string> {
const userId = parseUserId(jwtToken);
logger.debug("generate upload Url");
return todoResource.generateUploadUrl(todoId , userId);
}
// Create TODO
export function createToDo(createTodoRequest: CreateTodoRequest, jwtToken: string): Promise<TodoItem> {
const userId = parseUserId(jwtToken);
logger.debug("create Todo");
return todoResource.createToDo({
userId: userId,
todoId: uuidv4(),
createdAt: new Date().getTime().toString(),
done: false,
...createTodoRequest,
});
} | 11f878041454800f31f608d8e3d5a956fbb93787 | [
"TypeScript"
] | 1 | TypeScript | Adamhingoro/serverless-todo-app | 1e871c3ea437c482736ee0ada2c53de27c337711 | 4abce10a88ff051db0c6b449d3ca1d4afa00c5e6 |
refs/heads/master | <repo_name>kmandal/SUSY<file_sep>/Binselection.h
#ifndef BINSELECTION_H
#define BINSELECTION_H
class Binselection {
public:
// Returns result of search region bin
static unsigned int searchBin(double met, double mt2, unsigned int nBjets, unsigned int nTop);
};
unsigned int Binselection::searchBin(double met, double mt2, unsigned int nBjets, unsigned int nTop) {
unsigned int bin = 0;//this will contain total events
if(nBjets ==1 && nTop == 1){
if(met== && mt2==)bin == ;
}
if(nBjets ==2 && nTop == 1){
if(met== && mt2==)bin == ;
}
if(nBjets >=3 && nTop == 1){
if(met== && mt2==)bin == ;
}
if(nBjets ==1 && nTop == 2){
if(met== && mt2==)bin == ;
}
if(nBjets ==2 && nTop == 2){
if(met== && mt2==)bin == ;
}
if(nBjets >=3 && nTop == 2){
if(met== && mt2==)bin == ;
}
if(nBjets ==1 && nTop == 3){
if(met== && mt2==)bin == ;
}
if(nBjets ==2 && nTop == 3){
if(met== && mt2==)bin == ;
}
if(nBjets >=3 && nTop == 3){
if(met== && mt2==)bin == ;
}
return bin;
}
#endif
<file_sep>/baselineDef.h
#ifndef ANABASELINE_BASELINEDEF_H
#define ANABASELINE_BASELINEDEF_H
#include "NTupleReader.h"
#include "customize.h"
#include "Math/VectorUtil.h"
#include <sstream>
#include <iostream>
#include <fstream>
class BaselineVessel
{
private:
const std::string spec;
public:
BaselineVessel(const std::string specialization = "") : spec(specialization) { }
void passBaseline(NTupleReader &tr)
{
bool debug = false;
bool doIsoTrksVeto = true;
bool doMuonVeto = true;
bool incZEROtop = false;
bool passBaseline = true;
bool passBaselineNoTag = true;
std::string jetVecLabel = "jetsLVec";
std::string CSVVecLabel = "recoJetsBtag_0";
std::string METLabel = "met";
std::string METPhiLabel = "metphi";
if( spec.compare("noIsoTrksVeto") == 0)
{
doIsoTrksVeto = false;
}
if( spec.compare("incZEROtop") == 0)
{
incZEROtop = true;
}
if( spec.compare("hadtau") == 0)
{
doMuonVeto = false;
}
if( spec.compare("lostlept") == 0)
{
doMuonVeto = false;
}
if(spec.compare("Zinv") == 0)
{
jetVecLabel = "cleanJetpt30ArrVec";//"jetsLVec";//"prodJetsNoMu_jetsLVec";
CSVVecLabel = "cleanJetpt30ArrBTag";//"recoJetsBtag_0";
METLabel = "cleanMetPt";
METPhiLabel = "cleanMetPhi";
doMuonVeto = false;
}
// Form TLorentzVector of MET
TLorentzVector metLVec; metLVec.SetPtEtaPhiM(tr.getVar<double>(METLabel), 0, tr.getVar<double>(METPhiLabel), 0);
// Calculate number of leptons
int nMuons = AnaFunctions::countMuons(tr.getVec<TLorentzVector>("muonsLVec"), tr.getVec<double>("muonsMiniIso"), tr.getVec<double>("muonsMtw"), AnaConsts::muonsMiniIsoArr);
int nElectrons = AnaFunctions::countElectrons(tr.getVec<TLorentzVector>("elesLVec"), tr.getVec<double>("elesMiniIso"), tr.getVec<double>("elesMtw"), tr.getVec<unsigned int>("elesisEB"), AnaConsts::elesMiniIsoArr);
int nIsoTrks = AnaFunctions::countIsoTrks(tr.getVec<TLorentzVector>("loose_isoTrksLVec"), tr.getVec<double>("loose_isoTrks_iso"), tr.getVec<double>("loose_isoTrks_mtw"), tr.getVec<int>("loose_isoTrks_pdgId"));
// Calculate number of jets and b-tagged jets
int cntCSVS = AnaFunctions::countCSVS(tr.getVec<TLorentzVector>(jetVecLabel), tr.getVec<double>(CSVVecLabel), AnaConsts::cutCSVS, AnaConsts::bTagArr);
int cntNJetsPt50Eta24 = AnaFunctions::countJets(tr.getVec<TLorentzVector>(jetVecLabel), AnaConsts::pt50Eta24Arr);
int cntNJetsPt30Eta24 = AnaFunctions::countJets(tr.getVec<TLorentzVector>(jetVecLabel), AnaConsts::pt30Eta24Arr);
int cntNJetsPt30 = AnaFunctions::countJets(tr.getVec<TLorentzVector>(jetVecLabel), AnaConsts::pt30Arr);
// Calculate deltaPhi
std::vector<double> * dPhiVec = new std::vector<double>();
(*dPhiVec) = AnaFunctions::calcDPhi(tr.getVec<TLorentzVector>(jetVecLabel), metLVec.Phi(), 3, AnaConsts::dphiArr);
// Prepare jets and b-tag working points for top tagger
std::vector<TLorentzVector> *jetsLVec_forTagger = new std::vector<TLorentzVector>(); std::vector<double> *recoJetsBtag_forTagger = new std::vector<double>();
AnaFunctions::prepareJetsForTagger(tr.getVec<TLorentzVector>(jetVecLabel), tr.getVec<double>(CSVVecLabel), (*jetsLVec_forTagger), (*recoJetsBtag_forTagger));
if( debug ) std::cout<<"\njetsLVec_forTagger->size : "<<jetsLVec_forTagger->size()<<" recoJetsBtag_forTagger->size : "<<recoJetsBtag_forTagger->size()<<" passBaseline : "<<passBaseline<<std::endl;
// Pass lepton veto?
bool passLeptVeto = true, passMuonVeto = true, passEleVeto = true, passIsoTrkVeto = true;
if( doMuonVeto && nMuons != AnaConsts::nMuonsSel ){ passBaseline = false; passBaselineNoTag = false; passLeptVeto = false; passMuonVeto = false; }
if( nElectrons != AnaConsts::nElectronsSel ){ passBaseline = false; passBaselineNoTag = false; passLeptVeto = false; passEleVeto = false; }
// Isolated track veto is disabled for now
if( doIsoTrksVeto && nIsoTrks != AnaConsts::nIsoTrksSel ){ passBaseline = false; passBaselineNoTag = false; passLeptVeto = false; passIsoTrkVeto = false; }
if( debug ) std::cout<<"nMuons : "<<nMuons<<" nElectrons : "<<nElectrons<<" nIsoTrks : "<<nIsoTrks<<" passBaseline : "<<passBaseline<<std::endl;
// Pass number of jets?
bool passnJets = true;
if( cntNJetsPt50Eta24 < AnaConsts::nJetsSelPt50Eta24 ){ passBaseline = false; passBaselineNoTag = false; passnJets = false; }
if( cntNJetsPt30Eta24 < AnaConsts::nJetsSelPt30Eta24 ){ passBaseline = false; passBaselineNoTag = false; passnJets = false; }
if( debug ) std::cout<<"cntNJetsPt50Eta24 : "<<cntNJetsPt50Eta24<<" cntNJetsPt30Eta24 : "<<cntNJetsPt30Eta24<<" cntNJetsPt30 : "<<cntNJetsPt30<<" passBaseline : "<<passBaseline<<std::endl;
// Pass deltaPhi?
bool passdPhis = true;
if( dPhiVec->at(0) < AnaConsts::dPhi0_CUT || dPhiVec->at(1) < AnaConsts::dPhi1_CUT || dPhiVec->at(2) < AnaConsts::dPhi2_CUT ){ passBaseline = false; passBaselineNoTag = false; passdPhis = false; }
if( debug ) std::cout<<"dPhi0 : "<<dPhiVec->at(0)<<" dPhi1 : "<<dPhiVec->at(1)<<" dPhi2 : "<<dPhiVec->at(2)<<" passBaseline : "<<passBaseline<<std::endl;
// Pass number of b-tagged jets?
bool passBJets = true;
if( !( (AnaConsts::low_nJetsSelBtagged == -1 || cntCSVS >= AnaConsts::low_nJetsSelBtagged) && (AnaConsts::high_nJetsSelBtagged == -1 || cntCSVS < AnaConsts::high_nJetsSelBtagged ) ) ){ passBaseline = false; passBJets = false; }
if( debug ) std::cout<<"cntCSVS : "<<cntCSVS<<" passBaseline : "<<passBaseline<<std::endl;
// Pass the baseline MET requirement?
bool passMET = true;
if( metLVec.Pt() < AnaConsts::defaultMETcut ){ passBaseline = false; passBaselineNoTag = false; passMET = false; }
if( debug ) std::cout<<"met : "<<tr.getVar<double>("met")<<" defaultMETcut : "<<AnaConsts::defaultMETcut<<" passBaseline : "<<passBaseline<<std::endl;
// Calculate top tagger related variables.
// Note that to save speed, only do the calculation after previous base line requirements.
int nTopCandSortedCnt = -1;
if( passnJets && cntNJetsPt30 >= AnaConsts::nJetsSel ){
type3Ptr->processEvent((*jetsLVec_forTagger), (*recoJetsBtag_forTagger), metLVec);
nTopCandSortedCnt = type3Ptr->nTopCandSortedCnt;
}
// Pass top tagger requirement?
bool passTagger = type3Ptr->passNewTaggerReq() && (incZEROtop || nTopCandSortedCnt >= AnaConsts::low_nTopCandSortedSel);
if( !passTagger ) passBaseline = false;
// bool passNewCuts = type3Ptr->passNewCuts();
// Register all the calculated variables
tr.registerDerivedVar("nMuons_CUT" + spec, nMuons);
tr.registerDerivedVar("nElectrons_CUT" + spec, nElectrons);
tr.registerDerivedVar("nIsoTrks_CUT" + spec, nIsoTrks);
tr.registerDerivedVar("cntNJetsPt50Eta24" + spec, cntNJetsPt50Eta24);
tr.registerDerivedVar("cntNJetsPt30Eta24" + spec, cntNJetsPt30Eta24);
tr.registerDerivedVec("dPhiVec" + spec, dPhiVec);
tr.registerDerivedVar("cntCSVS" + spec, cntCSVS);
tr.registerDerivedVec("jetsLVec_forTagger" + spec, jetsLVec_forTagger);
tr.registerDerivedVec("recoJetsBtag_forTagger" + spec, recoJetsBtag_forTagger);
tr.registerDerivedVar("cntNJetsPt30" + spec, cntNJetsPt30);
tr.registerDerivedVar("passLeptVeto" + spec, passLeptVeto);
tr.registerDerivedVar("passMuonVeto" + spec, passMuonVeto);
tr.registerDerivedVar("passEleVeto" + spec, passEleVeto);
tr.registerDerivedVar("passIsoTrkVeto" + spec, passIsoTrkVeto);
tr.registerDerivedVar("passnJets" + spec, passnJets);
tr.registerDerivedVar("passdPhis" + spec, passdPhis);
tr.registerDerivedVar("passBJets" + spec, passBJets);
tr.registerDerivedVar("passMET" + spec, passMET);
tr.registerDerivedVar("passTagger" + spec, passTagger);
tr.registerDerivedVar("passBaseline" + spec, passBaseline);
tr.registerDerivedVar("passBaselineNoTag" + spec, passBaselineNoTag);
// tr.registerDerivedVar("passNewCuts" + spec, passNewCuts);
tr.registerDerivedVar("nTopCandSortedCnt" + spec, nTopCandSortedCnt);
tr.registerDerivedVar("best_lept_brJet_MT" + spec, type3Ptr->best_lept_brJet_MT);
tr.registerDerivedVar("best_had_brJet_MT" + spec, type3Ptr->best_had_brJet_MT);
tr.registerDerivedVar("best_had_brJet_mTcomb" + spec, type3Ptr->best_had_brJet_mTcomb);
tr.registerDerivedVar("best_had_brJet_MT2" + spec, type3Ptr->best_had_brJet_MT2);
double HT = AnaFunctions::calcHT(tr.getVec<TLorentzVector>(jetVecLabel), AnaConsts::pt50Eta24Arr);
tr.registerDerivedVar("HT" + spec, HT);
if( debug ) std::cout<<"passBaseline : "<<passBaseline<<" passBaseline : "<<passBaseline<<std::endl;
}
void operator()(NTupleReader &tr)
{
passBaseline(tr);
}
} blv;
void passBaselineFunc(NTupleReader &tr)
{
blv(tr);
}
namespace stopFunctions
{
class CleanJets
{
public:
void operator()(NTupleReader& tr) {internalCleanJets(tr);}
void setMuonIso(const std::string muIsoFlag)
{
if(muIsoFlag.compare("mini") == 0)
{
muIsoStr_ = "muonsMiniIso";
muIsoReq_ = AnaConsts::muonsMiniIsoArr;
}
else if(muIsoFlag.compare("rel") == 0)
{
muIsoStr_ = "muonsRelIso";
muIsoReq_ = AnaConsts::muonsArr;
}
else
{
std::cout << "cleanJets(...): muon iso mode not recognized!!! Using \"rel iso\" settings." << std::endl;
muIsoStr_ = "muonsRelIso";
muIsoReq_ = AnaConsts::muonsArr;
}
}
void setElecIso(const std::string elecIsoFlag)
{
if(elecIsoFlag.compare("mini") == 0)
{
std::cout << "cleanJets(...): electron mini iso mode not implemented yet!!! Using \"rel iso\" settings." << std::endl;
//elecIsoStr = "elesMiniIso";
//elecIsoReq = AnaConsts::elessMiniIsoArr;
elecIsoStr_ = "elesRelIso";
elecIsoReq_ = AnaConsts::elesArr;
}
else if(elecIsoFlag.compare("rel") == 0)
{
elecIsoStr_ = "elesRelIso";
elecIsoReq_ = AnaConsts::elesArr;
}
else
{
std::cout << "cleanJets(...): muon iso mode not recognized!!! Using \"rel iso\" settings." << std::endl;
elecIsoStr_ = "elesRelIso";
elecIsoReq_ = AnaConsts::elesArr;
}
}
CleanJets()
{
setMuonIso("rel");
setElecIso("rel");
}
private:
std::string muIsoStr_, elecIsoStr_;
AnaConsts::IsoAccRec muIsoReq_;
AnaConsts::ElecIsoAccRec elecIsoReq_;
void internalCleanJets(NTupleReader& tr)
{
const std::vector<TLorentzVector>& jetsLVec = tr.getVec<TLorentzVector>("jetsLVec");
const std::vector<TLorentzVector>& elesLVec = tr.getVec<TLorentzVector>("elesLVec");
const std::vector<TLorentzVector>& muonsLVec = tr.getVec<TLorentzVector>("muonsLVec");
const std::vector<double>& elesIso = tr.getVec<double>(elecIsoStr_);
const std::vector<double>& muonsIso = tr.getVec<double>(muIsoStr_);
const std::vector<double>& recoJetsBtag_0 = tr.getVec<double>("recoJetsBtag_0");
const std::vector<int>& muMatchedJetIdx = tr.getVec<int>("muMatchedJetIdx");
const std::vector<int>& eleMatchedJetIdx = tr.getVec<int>("eleMatchedJetIdx");
const std::vector<unsigned int>& elesisEB = tr.getVec<unsigned int>("elesisEB");
if(elesLVec.size() != elesIso.size()
|| elesLVec.size() != eleMatchedJetIdx.size()
|| elesLVec.size() != elesisEB.size()
|| muonsLVec.size() != muonsIso.size()
|| muonsLVec.size() != muMatchedJetIdx.size()
|| jetsLVec.size() != recoJetsBtag_0.size())
{
std::cout << "MISMATCH IN VECTOR SIZE!!!!! Aborting jet cleaning algorithm!!!!!!" << std::endl;
return;
}
std::vector<TLorentzVector>* cleanJetVec = new std::vector<TLorentzVector>();
std::vector<double>* cleanJetBTag = new std::vector<double>;
std::vector<TLorentzVector>* cleanJetpt30ArrVec = new std::vector<TLorentzVector>();
std::vector<double>* cleanJetpt30ArrBTag = new std::vector<double>;
std::vector<int>* rejectJetIdx_formuVec = new std::vector<int>();
std::vector<int>* rejectJetIdx_foreleVec = new std::vector<int>();
const double jldRMax = 0.15;
const double HT_jetPtMin = 50;
const double HT_jetEtaMax = 2.4;
const double MTH_jetPtMin = 30.0;
double HT = 0.0, HTNoIso = 0.0;
TLorentzVector MHT;
std::vector<bool> keepJetPFCandMatch(jetsLVec.size(), true);
for(int iM = 0; iM < muonsLVec.size() && iM < muonsIso.size() && iM < muMatchedJetIdx.size(); ++iM)
{
if(!AnaFunctions::passMuon(muonsLVec[iM], muonsIso[iM], 0.0, muIsoReq_)){ rejectJetIdx_formuVec->push_back(-1); continue; }
if(muMatchedJetIdx[iM] >= 0){ keepJetPFCandMatch[muMatchedJetIdx[iM]] = false; rejectJetIdx_formuVec->push_back(muMatchedJetIdx[iM]); }
else
{
//If muon matching to PF candidate has failed, use dR matching as fallback
int match = AnaFunctions::jetLepdRMatch(muonsLVec[iM], jetsLVec, jldRMax);
if(match >= 0){ keepJetPFCandMatch[match] = false; rejectJetIdx_formuVec->push_back(match); }
else rejectJetIdx_formuVec->push_back(-1);
}
}
for(int iE = 0; iE < elesLVec.size() && iE < elesIso.size() && iE < eleMatchedJetIdx.size(); ++iE)
{
if(!AnaFunctions::passElectron(elesLVec[iE], elesIso[iE], 0.0, elesisEB[iE], elecIsoReq_)){ rejectJetIdx_foreleVec->push_back(-1); continue; }
if(eleMatchedJetIdx[iE] >= 0){ keepJetPFCandMatch[eleMatchedJetIdx[iE]] = false; rejectJetIdx_foreleVec->push_back(eleMatchedJetIdx[iE]); }
else
{
//If electron matching to PF candidate has failed, use dR matching as fallback
int match = AnaFunctions::jetLepdRMatch(elesLVec[iE], jetsLVec, jldRMax);
if(match >= 0){ keepJetPFCandMatch[match] = false; rejectJetIdx_foreleVec->push_back(match); }
else rejectJetIdx_foreleVec->push_back(-1);
}
}
int jetsKept = 0;
for(int iJet = 0; iJet < jetsLVec.size(); ++iJet)
{
if(keepJetPFCandMatch[iJet])
{
++jetsKept;
cleanJetVec->push_back(jetsLVec[iJet]);
cleanJetBTag->push_back(recoJetsBtag_0[iJet]);
if(AnaFunctions::jetPassCuts(jetsLVec[iJet], AnaConsts::pt30Arr))
{
cleanJetpt30ArrVec->push_back(jetsLVec[iJet]);
cleanJetpt30ArrBTag->push_back(recoJetsBtag_0[iJet]);
}
if(jetsLVec[iJet].Pt() > HT_jetPtMin && fabs(jetsLVec[iJet].Eta()) < HT_jetEtaMax) HT += jetsLVec[iJet].Pt();
if(jetsLVec[iJet].Pt() > MTH_jetPtMin) MHT += jetsLVec[iJet];
}
}
tr.registerDerivedVar("nJetsRemoved", static_cast<int>(jetsLVec.size() - jetsKept));
tr.registerDerivedVar("cleanHt", HT);
tr.registerDerivedVar("cleanMHt", MHT.Pt());
tr.registerDerivedVar("cleanMHtPhi", MHT.Phi());
tr.registerDerivedVec("cleanJetVec", cleanJetVec);
tr.registerDerivedVec("cleanJetBTag", cleanJetBTag);
tr.registerDerivedVec("cleanJetpt30ArrVec", cleanJetpt30ArrVec);
tr.registerDerivedVec("cleanJetpt30ArrBTag", cleanJetpt30ArrBTag);
tr.registerDerivedVec("rejectJetIdx_formuVec", rejectJetIdx_formuVec);
tr.registerDerivedVec("rejectJetIdx_foreleVec", rejectJetIdx_foreleVec);
}
} cjh;
void cleanJets(NTupleReader& tr)
{
cjh(tr);
}
}
#endif
<file_sep>/Closure.cc
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <set>
#include <cstdio>
#include <ctime>
#include <sstream>
#include <fstream>
#include <iostream>
#include <vector>
#include "SusyAnaTools/Tools/samples.h"
#include "SusyAnaTools/Tools/customize.h"
#include "SusyAnaTools/Tools/baselineDef.h"
#include "SusyAnaTools/Tools/searchBins.h"
#include "TStopwatch.h"
#include "TString.h"
#include "SusyAnaTools/Tools/NTupleReader.h"
#include "Closure.h"
#include "TH1.h"
#include "TH1D.h"
#include "TFile.h"
#include "TString.h"
#include "TVector2.h"
#include "TMath.h"
#include "TLorentzVector.h"
#include "TTree.h"
#include "TChain.h"
#include "TauResponse.h"
#include "utils.h"
#include "Efficiency.h"
#include "TRandom3.h"
using namespace std;
static const int nSB = 48;
void passBaselineFunc1(NTupleReader &tr)
{
bool passBaseline = true;
//Form TLorentzVector of MET
TLorentzVector metLVec; metLVec.SetPtEtaPhiM(tr.getVar<double>("met"), 0, tr.getVar<double>("metphi"), 0);
//Calculate number of leptons
int nMuons = AnaFunctions::countMuons(tr.getVec<TLorentzVector>("muonsLVec"), tr.getVec<double>("muonsMiniIso"), tr.getVec<double>("muonsMtw"), AnaConsts::muonsMiniIsoArr);
int nElectrons = AnaFunctions::countElectrons(tr.getVec<TLorentzVector>("elesLVec"), tr.getVec<double>("elesMiniIso"), tr.getVec<double>("elesMtw"), tr.getVec<unsigned int>("elesisEB"), AnaConsts::elesArr);
// int nIsoTrks = AnaFunctions::countIsoTrks(tr.getVec<TLorentzVector>("loose_isoTrksLVec"), tr.getVec<double>("loose_isoTrks_iso"), tr.getVec<double>("loose_isoTrks_mtw"), AnaConsts::isoTrksArr);
//Calculate number of jets and b-tagged jets
int cntCSVS = AnaFunctions::countCSVS(tr.getVec<TLorentzVector>("jetsLVec"), tr.getVec<double>("recoJetsBtag_0"), AnaConsts::cutCSVS, AnaConsts::bTagArr);
int cntNJetsPt50Eta24 = AnaFunctions::countJets(tr.getVec<TLorentzVector>("jetsLVec"), AnaConsts::pt50Eta24Arr);
int cntNJetsPt30Eta24 = AnaFunctions::countJets(tr.getVec<TLorentzVector>("jetsLVec"), AnaConsts::pt30Eta24Arr);
int cntNJetsPt30 = AnaFunctions::countJets(tr.getVec<TLorentzVector>("jetsLVec"), AnaConsts::pt30Arr);
//Calculate deltaPhi
std::vector<double> * dPhiVec = new std::vector<double>();
(*dPhiVec) = AnaFunctions::calcDPhi(tr.getVec<TLorentzVector>("jetsLVec"), tr.getVar<double>("metphi"), 3, AnaConsts::dphiArr);
std::vector<TLorentzVector> *jetsLVec_forTagger = new std::vector<TLorentzVector>(); std::vector<double> *recoJetsBtag_forTagger = new std::vector<double>();
AnaFunctions::prepareJetsForTagger(tr.getVec<TLorentzVector>("jetsLVec"), tr.getVec<double>("recoJetsBtag_0"), (*jetsLVec_forTagger), (*recoJetsBtag_forTagger));
//Pass lepton veto?
bool passLeptVeto = true;
if( nMuons != AnaConsts::nMuonsSel ){ passBaseline = false; passLeptVeto = false; }
if( nElectrons != AnaConsts::nElectronsSel ){ passBaseline = false; passLeptVeto = false; }
//Pass number of jets?
bool passnJets = true;
if( cntNJetsPt50Eta24 < AnaConsts::nJetsSelPt50Eta24 ){ passBaseline = false; passnJets = false;}
if( cntNJetsPt30Eta24 < AnaConsts::nJetsSelPt30Eta24 ){ passBaseline = false; passnJets = false;}
//Pass deltaPhi?
bool passdPhis = true;
if( dPhiVec->at(0) < AnaConsts::dPhi0_CUT || dPhiVec->at(1) < AnaConsts::dPhi1_CUT || dPhiVec->at(2) < AnaConsts::dPhi2_CUT ){ passBaseline = false; passdPhis = false; }
//Pass number of b-tagged jets?
bool passBJets = true;
if( !( (AnaConsts::low_nJetsSelBtagged == -1 || cntCSVS >= AnaConsts::low_nJetsSelBtagged) && (AnaConsts::high_nJetsSelBtagged == -1 || cntCSVS < AnaConsts::high_nJetsSelBtagged ) ) ){ passBaseline = false; passBJets = false; }
//Pass the baseline MET requirement?
bool passMET = true;
if( tr.getVar<double>("met") < AnaConsts::defaultMETcut ){ passBaseline = false; passMET = false; }
//Calculate top tagger related variables.
//Note that to save speed, only do the calculation after previous base line requirements.
int nTopCandSortedCnt = -1;
double MT2 = -1;
double mTcomb = -1;
if( passnJets && cntNJetsPt30 >= AnaConsts::nJetsSel ){
type3Ptr->processEvent((*jetsLVec_forTagger), (*recoJetsBtag_forTagger), metLVec);
nTopCandSortedCnt = type3Ptr->nTopCandSortedCnt;
MT2 = type3Ptr->best_had_brJet_MT2;
// mTcomb = type3Ptr->mTbJet + 0.5*type3Ptr->mTbestTopJet;
mTcomb = type3Ptr->best_had_brJet_mTcomb;
}
//Pass top tagger requirement?
bool passTagger = type3Ptr->passNewTaggerReq();
if( !passTagger ) passBaseline = false;
bool passNewCuts = type3Ptr->passNewCuts();
//register new var
tr.registerDerivedVar("nMuons_CUT2", nMuons);
tr.registerDerivedVar("nElectrons_CUT2", nElectrons);
tr.registerDerivedVar("cntNJetsPt30Eta24", cntNJetsPt30Eta24);
tr.registerDerivedVar("passBaseline", passBaseline);
tr.registerDerivedVar("passLeptVeto", passLeptVeto);
tr.registerDerivedVar("passMET", passMET);
tr.registerDerivedVar("passnJets", passnJets);
tr.registerDerivedVar("passdPhis", passdPhis);
tr.registerDerivedVar("passBJets", passBJets);
tr.registerDerivedVar("passTagger", passTagger);
tr.registerDerivedVar("cntCSVS", cntCSVS);
tr.registerDerivedVar("nTopCandSortedCnt", nTopCandSortedCnt);
tr.registerDerivedVar("MT2_new", MT2);
tr.registerDerivedVar("mTcomb_new", mTcomb);
tr.registerDerivedVar("passNewCuts", passNewCuts);
}
// === Main Function ===================================================
int main(int argc, char* argv[]) {
if (argc < 3)
{
std::cerr <<"Please give 3 arguments " << "inputList " << " " <<" "<<"input template"<<" "<< "outputFileName" << std::endl;
std::cerr <<" Valid configurations are " << std::endl;
std::cerr <<" ./Closure List1_ttbar.txt HadTau_TauResponseTemplates.root HadTau_Closure.root" << std::endl;
return -1;
}
const char *inputFileList = argv[1];
const char *respTempl = argv[2];
const char *outFileName = argv[3];
TChain *fChain = new TChain("stopTreeMaker/AUX");
if(!FillChain(fChain, inputFileList))
{
std::cerr << "Cannot get the tree " << std::endl;
}
NTupleReader tr(fChain);
AnaFunctions::prepareTopTagger();
tr.registerFunction(&passBaselineFunc1);
// Add cleanJets function
stopFunctions::cjh.setMuonIso("mini");
stopFunctions::cjh.setElecIso("mini");
tr.registerFunction(&stopFunctions::cleanJets);
BaseHistgram myBaseHistgram;
myBaseHistgram.BookHistgram(outFileName);
TauResponse tauResp(respTempl);
TRandom3 * rndm = new TRandom3(12345);
// --- Analyse events --------------------------------------------
std::cout<<"First loop begin: "<<std::endl;
int entries = tr.getNEntries();
std::cout<<"\nentries : "<<entries<<std::endl;
std::vector<double> pred_from_taumuVec(49);
int cnt_nomtw=0,cnt_mtw=0;
// Loop over the events (tree entries)
int k = 0;
while(tr.getNextEvent()){
k++;
// Add print out of the progress of looping
if( tr.getEvtNum()-1 == 0 || tr.getEvtNum() == entries || (tr.getEvtNum()-1)%(entries/10) == 0 ) std::cout<<"\n Processing the "<<tr.getEvtNum()-1<<"th event ..."<<std::endl;
const vector<TLorentzVector> &muonsLVec = tr.getVec<TLorentzVector>("muonsLVec");
const vector<double> &muonsRelIso = tr.getVec<double>("muonsRelIso");
const vector<double> &muonsMiniIso = tr.getVec<double>("muonsMiniIso");
const vector<double> &muonsMtw = tr.getVec<double>("muonsMtw");
const vector<TLorentzVector> &genDecayLVec = tr.getVec<TLorentzVector>("genDecayLVec");
const vector<int> &genDecayIdxVec = tr.getVec<int>("genDecayIdxVec");
const vector<int> &genDecayPdgIdVec = tr.getVec<int>("genDecayPdgIdVec");
const vector<int> &W_emuVec = tr.getVec<int>("W_emuVec");
const vector<int> &W_tau_emuVec = tr.getVec<int>("W_tau_emuVec");
const vector<TLorentzVector> &jetsLVec = tr.getVec<TLorentzVector>("jetsLVec");
const vector<double> &recoJetsBtag_0 = tr.getVec<double>("recoJetsBtag_0");
int nElectrons = tr.getVar<int>("nElectrons_CUT2");
int nMuons = tr.getVar<int>("nMuons_CUT2");
double met=tr.getVar<double>("met");
double metphi=tr.getVar<double>("metphi");
double ht=tr.getVar<double>("ht");
vector<int> W_tau_prongsVec = tr.getVec<int>("W_tau_prongsVec");
TLorentzVector metLVec; metLVec.SetPtEtaPhiM(met, 0, metphi, 0);
//Expectation part -- do it before prediction & do NOT skipping events
bool passBaseline_tru = tr.getVar<bool>("passBaseline");
const int nJets_tru = tr.getVar<int>("cntNJetsPt30Eta24");
const int nbJets_tru = tr.getVar<int>("cntCSVS");
const int nTops_tru = tr.getVar<int>("nTopCandSortedCnt");
const double MT2_tru = tr.getVar<double>("MT2_new");
const double mTcomb_tru = tr.getVar<double>("mTcomb_new");
//Select only events where the W decayed into a hadronically decaying tau
//Note that for ttbar this includes (for two W's)
// ] W->tau->had, W->tau->had
// ] W->tau->had, W->qq
// ] W->tau->had, W->e/mu (e or mu is lost)
if(W_tau_prongsVec.size() !=0 && passBaseline_tru){
int jSR = find_Binning_Index(nbJets_tru, nTops_tru, MT2_tru, met);
if( jSR!= -1 && (jSR>=0 && jSR<48)) {
myBaseHistgram.hTrueYields->Fill(jSR);
}
myBaseHistgram.hTrueYields->Fill(48);
myBaseHistgram.hTrueHt->Fill(ht);
myBaseHistgram.hTruemet->Fill(met);
myBaseHistgram.hTrueNJets->Fill(nJets_tru);
myBaseHistgram.hTrueNbJets->Fill(nbJets_tru);
myBaseHistgram.hTrueNTops->Fill(nTops_tru);
myBaseHistgram.hTrueMT2->Fill(MT2_tru);
myBaseHistgram.hTruemTcomb->Fill(mTcomb_tru);
}
//Prediction part
//Control sample
// The kinematic properties of the well-reconstructed, isolated muon
vector<TLorentzVector> isomuonsLVec;
vector<int> isomuonsIdxVec;
for(unsigned int im=0; im<muonsLVec.size(); im++){
if( AnaFunctions::passMuon(muonsLVec.at(im), muonsMiniIso.at(im), muonsMtw.at(im), AnaConsts::muonsMiniIsoArr) ){ isomuonsLVec.push_back(muonsLVec.at(im)); isomuonsIdxVec.push_back(im); }
}
// Require one and only one muon
// Veto events with additional electrons (same veto criteria as baseline for electrons)
if( nMuons == 1 && nElectrons == AnaConsts::nElectronsSel ) {
if( nMuons != isomuonsLVec.size() ){ std::cout<<"ERROR ... mis-matching between veto muon and selected muon! Skipping..."<<std::endl; continue; }
const TLorentzVector muLVec = isomuonsLVec.at(0);
// Use only events where the muon is inside acceptance
if( muLVec.Pt() < TauResponse::ptMin() ) continue;
if( fabs(muLVec.Eta()) > TauResponse::etaMax() ) continue;
//mtW correction
const double mtw = calcMT(muLVec, metLVec);
bool pass_mtw = false;
if(mtw<100)pass_mtw = true;
// Find events that contain W->tau->mu
// Note that any code using gen info should be checked if they work for data or not!
bool istaumu = false, istaumu_genRecoMatch = false;
for(unsigned int ig=0; ig<W_tau_emuVec.size(); ig++){
int genIdx = W_tau_emuVec.at(ig);
if( std::abs(genDecayPdgIdVec.at(genIdx)) == 13 ){
istaumu = true;
const TLorentzVector & genLVec = genDecayLVec.at(genIdx);
if( muLVec.DeltaR(genLVec) < 0.2 ) istaumu_genRecoMatch = true;
}
}
// if( W_emuVec.empty() && istaumu && !istaumu_genRecoMatch ) std::cout<<"WARNING ... reco muon does NOT match to the tau->mu?!"<<std::endl;
// "Cross cleaning": find the jet that corresponds to the muon
const std::vector<TLorentzVector>& cleanJetVec = tr.getVec<TLorentzVector>("cleanJetVec");
const std::vector<double>& cleanJetBtag = tr.getVec<double>("cleanJetBTag");
// Get the cleaned jet indice (pointing to the jetsLVec) for the corresponding muons
const std::vector<int>& rejectJetIdx_formuVec = tr.getVec<int>("rejectJetIdx_formuVec");
const double & cleanHt = tr.getVar<double>("cleanHt");
const double & cleanMHt = tr.getVar<double>("cleanMHt");
const double & cleanMHtPhi = tr.getVar<double>("cleanMHtPhi");
TLorentzVector selMhtLVec; selMhtLVec.SetPtEtaPhiM(cleanMHt, 0, cleanMHtPhi, 0);
// Force the mass to be 0 for met and mht
TLorentzVector selmetLVec; selmetLVec.SetVectM( (metLVec+ muLVec).Vect(), 0 );
int selNJetPt30Eta24 = AnaFunctions::countJets(cleanJetVec, AnaConsts::pt30Eta24Arr);
int selNJetPt50Eta24 = AnaFunctions::countJets(cleanJetVec, AnaConsts::pt50Eta24Arr);
// rejecting events with nJets less than requirements even adding one more tau jet
if( selNJetPt30Eta24 < AnaConsts::nJetsSelPt30Eta24 - 1 ) continue;
if( selNJetPt50Eta24 < AnaConsts::nJetsSelPt50Eta24 - 1 ) continue;
// Get random number from tau-response template
// The template is chosen according to the muon pt
const double scale = tauResp.getRandom(muLVec.Pt());
// Scale muon pt and energy with tau response --> simulate tau jet pt and energy
const double simTauJetPt = scale * muLVec.Pt();
const double simTauJetE = scale * muLVec.E();
const double simTauJetEta = muLVec.Eta();
const double simTauJetPhi = muLVec.Phi();
TLorentzVector tauJetLVec; tauJetLVec.SetPtEtaPhiE(simTauJetPt, simTauJetEta, simTauJetPhi, simTauJetE);
// Decide the CSV value for the tau jet -> use the CSV of the associated muon-jet as the tau jet CSV
// Default set to be 0 (low enough to be NOT a b jet)
double oriJetCSVS = 0;
if( rejectJetIdx_formuVec.at(isomuonsIdxVec.at(0)) != -1 ) oriJetCSVS = recoJetsBtag_0[rejectJetIdx_formuVec.at(isomuonsIdxVec.at(0))];
double mistag = Efficiency::mistag(Efficiency::Ptbin1(simTauJetPt));
double rno = rndm->Rndm();
if( rno < mistag) oriJetCSVS = 1.0;
// cout<<mistag<<" "<<rno<<endl;
vector<TLorentzVector> combNJetVec;
vector<double> combJetsBtag;
bool includeTauJet = false;
for(unsigned int ij=0; ij<cleanJetVec.size(); ij++){
if( tauJetLVec.Pt() > cleanJetVec.at(ij).Pt() && !includeTauJet ){
combNJetVec.push_back(tauJetLVec); combJetsBtag.push_back(oriJetCSVS);
includeTauJet = true;
}
combNJetVec.push_back(cleanJetVec.at(ij)); combJetsBtag.push_back(cleanJetBtag.at(ij));
}
// it's possible that the tau jet is the least energetic jet so that it's not added into the combNJetVec during the loop
if( !includeTauJet ){ combNJetVec.push_back(tauJetLVec); combJetsBtag.push_back(oriJetCSVS); }
// Taking into account the simulated tau jet, recompute
// HT, MHT, and N(jets)
double simHt = cleanHt;
TLorentzVector simMhtLVec;
// If simulted tau-jet meets same criteria as as HT jets,
// recompute HT and MH
if( tauJetLVec.Pt() > htJetPtMin() && fabs(tauJetLVec.Eta()) < htJetEtaMax()) {
simHt += tauJetLVec.Pt();
}
if( tauJetLVec.Pt() > mhtJetPtMin() && fabs(tauJetLVec.Eta()) < mhtJetEtaMax()) {
simMhtLVec.SetVectM( (selMhtLVec-tauJetLVec).Vect(), 0);
}
//recompute met
TLorentzVector simmetLVec; simmetLVec.SetVectM( (selmetLVec - tauJetLVec).Vect(), 0);
const double simMht = simMhtLVec.Pt();
const double simmet = simmetLVec.Pt();
const double simmetPhi = simmetLVec.Phi();
//recompute jetVec
int combNJetPt30Eta24 = AnaFunctions::countJets(combNJetVec, AnaConsts::pt30Eta24Arr);
int combNJetPt50Eta24 = AnaFunctions::countJets(combNJetVec, AnaConsts::pt50Eta24Arr);
//recompute deltaphi
std::vector<double> * deltaPhiVec = new std::vector<double>();
(*deltaPhiVec) = AnaFunctions::calcDPhi(combNJetVec, simmetPhi, 3, AnaConsts::dphiArr);
bool passdeltaPhi = true;
if( deltaPhiVec->at(0) < AnaConsts::dPhi0_CUT || deltaPhiVec->at(1) < AnaConsts::dPhi1_CUT || deltaPhiVec->at(2) < AnaConsts::dPhi2_CUT){
passdeltaPhi = false;
}
//recompute bjet
int cnt1CSVS = AnaFunctions::countCSVS(combNJetVec, combJetsBtag, AnaConsts::cutCSVS, AnaConsts::bTagArr);
bool passbJets = true;
if( !( (AnaConsts::low_nJetsSelBtagged == -1 || cnt1CSVS >= AnaConsts::low_nJetsSelBtagged) && (AnaConsts::high_nJetsSelBtagged == -1 || cnt1CSVS < AnaConsts::high_nJetsSelBtagged ) ) ){
passbJets = false;
}
//top tagger input
int comb30_pre = AnaFunctions::countJets(combNJetVec, AnaConsts::pt30Arr);
std::vector<TLorentzVector> *jetsLVec_forTagger_pre = new std::vector<TLorentzVector>(); std::vector<double> *recoJetsBtag_forTagger_pre = new std::vector<double>();
AnaFunctions::prepareJetsForTagger(combNJetVec, combJetsBtag, (*jetsLVec_forTagger_pre), (*recoJetsBtag_forTagger_pre));
int nTopCandSortedCnt_pre = -1;
double MT2_pre = -1;
double mTcomb_pre = -1;
//Apply baseline cut
if(combNJetPt30Eta24<AnaConsts::nJetsSelPt30Eta24) continue;
if(combNJetPt50Eta24<AnaConsts::nJetsSelPt50Eta24) continue;
if(simmet<AnaConsts::defaultMETcut) continue;
if(!passdeltaPhi) continue;
if(!passbJets) continue;
//Apply Top tagger
if(comb30_pre >= AnaConsts::nJetsSel ){
type3Ptr->processEvent((*jetsLVec_forTagger_pre), (*recoJetsBtag_forTagger_pre), simmetLVec);
nTopCandSortedCnt_pre = type3Ptr->nTopCandSortedCnt;
MT2_pre = type3Ptr->best_had_brJet_MT2;
mTcomb_pre = type3Ptr->best_had_brJet_mTcomb;
}
bool passTopTagger = type3Ptr->passNewTaggerReq();
//New tagger cuts
bool passNewCuts = type3Ptr->passNewCuts();
if(!passTopTagger) continue;
//mtw count
cnt_nomtw++;
if(pass_mtw)cnt_mtw++;
//Activity variable calculation:
double muact = AnaFunctions::getMuonActivity(muLVec, jetsLVec, tr.getVec<double>("recoJetschargedHadronEnergyFraction"), tr.getVec<double>("recoJetschargedEmEnergyFraction"),AnaConsts::muonsAct);
//correction factor:
const double corrBRWToTauHad = 0.65; // Correction for the BR of hadronic tau decays
const double corrBRTauToMu = Efficiency::taumucor(Efficiency::Ptbin1(muLVec.Pt()));//correction from tauonic mu contamination
const double corrMuAcc = 1./Efficiency::acc(Efficiency::Njetbin(combNJetPt30Eta24)); // Correction for muon acceptance
const double corrMuRecoEff = 1./Efficiency::reco(Efficiency::Ptbin(muLVec.Pt()), Efficiency::Actbin(muact)); // Correction for muon reconstruction efficiency
const double corrMuIsoEff = 1./Efficiency::iso(Efficiency::Ptbin(muLVec.Pt()), Efficiency::Actbin(muact)); // Correction for muon isolation efficiency
const double corrmtWEff = 1./0.8897;
//The overall correction factor
// const double corr = corrBRTauToMu * corrBRWToTauHad * corrMuAcc * corrMuRecoEff * corrMuIsoEff;
// For MC, no need of applying the corrBRTauToMu as you know if this event is from W->tau->mu or not
// However, we need know the fraction so that we can apply it to data (can be got from the printout)
const double corr = corrBRWToTauHad * corrMuAcc * corrMuRecoEff * corrMuIsoEff * corrmtWEff;
// iSR: this should be determined by search region requirement
int kSR = find_Binning_Index(cnt1CSVS, nTopCandSortedCnt_pre, MT2_pre, simmet);
if( !istaumu_genRecoMatch && pass_mtw){
if( kSR!=-1 && (kSR>=0 && kSR<48)) {
myBaseHistgram.hPredYields->Fill(kSR,corr);
}
myBaseHistgram.hPredYields->Fill(48,corr);
}
if( istaumu_genRecoMatch ){
pred_from_taumuVec[48] += corr;
if(kSR!=-1 && (kSR>=0 && kSR<48)) pred_from_taumuVec[kSR] += corr;
}
// Fill the prediction
if( !istaumu_genRecoMatch && pass_mtw){
myBaseHistgram.hPredHt->Fill(simHt,corr);
myBaseHistgram.hPredmet->Fill(simmet,corr);
myBaseHistgram.hPredNJets->Fill(combNJetPt30Eta24,corr);
myBaseHistgram.hPredNbJets->Fill(cnt1CSVS,corr);
myBaseHistgram.hPredNTops->Fill(nTopCandSortedCnt_pre,corr);
myBaseHistgram.hPredMT2->Fill(MT2_pre,corr);
myBaseHistgram.hPredmTcomb->Fill(mTcomb_pre,corr);
}
}//control sample loop
}
// --- Save the Histograms to File -----------------------------------
std::cout<<"lastbin:"<<myBaseHistgram.hPredmet->GetBinContent(myBaseHistgram.hPredmet->GetXaxis()->GetNbins())<<std::endl;
std::cout<<"overflow:"<<myBaseHistgram.hPredmet->GetBinContent(myBaseHistgram.hPredmet->GetXaxis()->GetNbins() + 1)<<std::endl;
drawOverFlowBin(myBaseHistgram.hPredmet);
drawOverFlowBin(myBaseHistgram.hTruemet);
drawOverFlowBin(myBaseHistgram.hPredMT2);
drawOverFlowBin(myBaseHistgram.hTrueMT2);
drawOverFlowBin(myBaseHistgram.hPredNbJets);
drawOverFlowBin(myBaseHistgram.hTrueNbJets);
(myBaseHistgram.oFile)->Write();
// This print out can be used to extract the corrBRTauToMu ratio
std::cout<<"\nPrediction in numbers ..."<<std::endl;
for(unsigned int ib=0; ib<=nSB; ib++){
std::cout<<"ib : "<<ib<<" "<<pred_from_taumuVec[ib]<<std::endl;
}
std::cout<<std::endl;
std::cout<<"True: "<<myBaseHistgram.hTrueYields->GetBinContent(49)<<" "<<"Prediction: "<<myBaseHistgram.hPredYields->GetBinContent(49)<<std::endl;
std::cout<<cnt_nomtw<<" "<<cnt_mtw<<std::endl;
return 0;
}
| d3623a3cf2d05c5987933d23d0818b8086ffd58e | [
"C++"
] | 3 | C++ | kmandal/SUSY | 10ac100218d9729fce2ce82704709f23cd573737 | 64ad420459a53610eb4cae676e179f18839cbb16 |
refs/heads/master | <file_sep>import {CastingContext} from 'clime';
import * as globby from 'globby';
export class Matches extends Array<string> {
private constructor(...args: any[]) {
super(...args);
}
static async cast(
globsStr: string,
context: CastingContext<Matches>,
): Promise<Matches> {
let globs = globsStr
.split(',')
.map(glob => glob.trim())
.filter(glob => !!glob);
let paths = await globby(globs, {cwd: context.cwd});
return new this(...paths);
}
}
<file_sep>[](https://www.npmjs.com/package/clime-glob)
[](https://travis-ci.org/vilic/clime-glob)
# Clime Glob Objects
Provides easy access to glob matching for Clime command.
## Installation
```sh
npm install clime-glob --save
```
## Classes
| Constructor | Description |
| --- | --- |
| `Matches` | Find file names that match the given comma separated glob patterns. |
## License
MIT License.
| 3f287d7b515dc9e526f7e29ed46f1d259becf11e | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | vilic/clime-glob | 1bfbf6dc2fc331d1dac5f9d36298ae82ea2a42a4 | c39e15ddfe14a4d451d6898585734a741a23a615 |
refs/heads/master | <repo_name>mdmdmd111/EscapeRoom<file_sep>/Assets/Scripts/UIButtonMusicPlay.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIButtonMusicPlay : MonoBehaviour {
public AudioClip audioSFX;
public Button yourButton;
void Start()
{
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
// play sound effect if set
if (audioSFX) {
if (gameObject.GetComponent<AudioSource> ()) { // the projectile has an AudioSource component
// play the sound clip through the AudioSource component on the gameobject.
// note: The audio will travel with the gameobject.
gameObject.GetComponent<AudioSource> ().PlayOneShot (audioSFX);
} else {
// dynamically create a new gameObject with an AudioSource
// this automatically destroys itself once the audio is done
AudioSource.PlayClipAtPoint (audioSFX, gameObject.transform.position);
}
}
}
}<file_sep>/Assets/Scripts/TargetBehavior.cs
using UnityEngine;
using System.Collections;
public class TargetBehavior : MonoBehaviour
{
// Reference to AudioClip to play
public AudioClip shootSFX;
public GameObject mainCanvas;
public GameObject activeCanvas;
// when collided with another gameObject
void OnCollisionEnter (Collision newCollision)
{
// exit if there is a game manager and the game is over
if (GameManager.gm) {
if (GameManager.gm.gameIsOver)
return;
}
// only do stuff if hit by a projectile
if (newCollision.gameObject.tag == "Projectile") {
// play sound effect if set
if (shootSFX)
{
if (gameObject.GetComponent<AudioSource> ()) { // the projectile has an AudioSource component
// play the sound clip through the AudioSource component on the gameobject.
// note: The audio will travel with the gameobject.
gameObject.GetComponent<AudioSource> ().PlayOneShot (shootSFX);
}
/*else {
// dynamically create a new gameObject with an AudioSource
// this automatically destroys itself once the audio is done
AudioSource.PlayClipAtPoint (shootSFX, gameObject.transform.position);
}*/
}
bool isPlaying;
while (gameObject.GetComponent<AudioSource> ().isPlaying) {
isPlaying = true;
}
isPlaying = false;
if (!isPlaying && activeCanvas) {
mainCanvas.SetActive (false);
// make the mouse pointer visible
Cursor.visible = true;
// unlock the mouse pointer so player can click on other windows
Cursor.lockState = CursorLockMode.None;
activeCanvas.SetActive(true);
}
// destroy the projectile
Destroy (newCollision.gameObject);
}
}
}
<file_sep>/Assets/Scripts/MusicTest.cs
using UnityEngine;
using System.Collections;
public class MusicTest : MonoBehaviour {
private MusicPlayer music;
void Start () {
music = (GetComponent("MusicPlayer") as MusicPlayer);
}
void OnGUI()
{
if(GUI.Button(new Rect(750, 500, 50, 50), "music")){
music.Play("water");
}
}
} | cdf6dae93fe2e8c93e93223071d8b3c5ce258c91 | [
"C#"
] | 3 | C# | mdmdmd111/EscapeRoom | 95cb76e7b2bad1815560e5809242211988d1602a | 9b396d8a943ccaa85f7447da1ecfc83d3d3a5968 |
refs/heads/master | <repo_name>anoam99/targil<file_sep>/src/components/CountryData.js
import React, { useEffect, useState } from 'react'
import { useParams, Link } from "react-router-dom";
import axios from 'axios';
import Graph from './Graph'
const CountryData = () => {
const {country} = useParams();
const [countryParams, setCountryParams] = useState([])
useEffect(()=>{
axios({
url: 'https://graphql.country/graphql',
method: 'post',
data: {
query: `
{
countries(name_Icontains: "${country}") {
edges {
node {
name
latLng
area
population
capital
}
}
}
}
`
}
}).then((result) => {
setCountryParams({
"name": result.data.data.countries.edges[0].node.name,
"lat": result.data.data.countries.edges[0].node.latLng[0],
"lng": result.data.data.countries.edges[0].node.latLng[1],
"area": result.data.data.countries.edges[0].node.area,
"population": result.data.data.countries.edges[0].node.population,
"capital": result.data.data.countries.edges[0].node.capital
})
})
},[country])
return (
<div>
<Link to={"/"}>
<button>back</button>
</Link>
<h1>{country}</h1>
<Graph data={countryParams}/>
</div>
)
}
export default CountryData
<file_sep>/src/components/Graph.js
import React, {useState} from 'react'
import {ScatterChart, CartesianGrid, XAxis, YAxis, ZAxis, Tooltip, Scatter, } from "recharts";
const Graph = ({data}) => {
const [filterByArea, setFilterByArea] = useState(true)
console.log(data.population)
return (
<div>
<ScatterChart
width={800}
height={600}
margin={{
top: 20, right: 20, bottom: 20, left: 20,
}}
>
<CartesianGrid />
<XAxis
domain={[-180, 180]}
type="number"
dataKey="x"
name='latitude' />
<YAxis domain={[-180, 180]}
type="number"
dataKey="y"
name='longitude' />
<ZAxis type="number"
dataKey="z"
range={filterByArea? [1, data.area/100]: [1,data.population/10000] }
name={filterByArea? 'area': 'population'}/>
<Scatter name="A school"
data={[{'x': data.lat, 'y':data.lng, "z": filterByArea? data.area: data.population}]}
fill="#8884d8" />
<Tooltip cursor={{ strokeDasharray: "3 3" }} />
</ScatterChart>
<button onClick={()=>setFilterByArea(!filterByArea)}>Change Filter</button>
</div>
)
}
export default Graph
<file_sep>/src/components/CountryPicker.js
import React, {useState, useEffect} from 'react'
import {Link} from 'react-router-dom';
import axios from 'axios'
const Countrypicker = ({handleCountryChange}) => {
const [countriesNames, setCountriesNames ] = useState([])
const [curContry, setCurCountry] = useState('Israel')
useEffect(()=>{
axios({
url: 'https://graphql.country/graphql',
method: 'post',
data: {
query: `
{
countries {
edges {
node {
name
}
}
}
}
`
}
}).then((result) => {
setCountriesNames(result.data.data.countries.edges)
})
},[])
return (
<div>
<select onChange={(e)=>setCurCountry(e.target.value)}>
{countriesNames.map(item =>{
return(
<option key={item.node.name}>{item.node.name}</option>
)
})}
</select>
<Link to={`/${curContry}`}>
<button>submit</button>
</Link>
</div>
)
}
export default Countrypicker
| ce5b19d644da68f56bcf26eb5f2609f67d068078 | [
"JavaScript"
] | 3 | JavaScript | anoam99/targil | 2d0153f31c022b2d391fbc7153ddf6f8be407fd3 | 510add40d0504cb92d9f72cf65bea489a685f3bb |
refs/heads/master | <file_sep><?php declare(strict_types = 1);
namespace Apitte\Debug\DI;
use Apitte\Core\DI\ApiExtension;
use Apitte\Core\DI\Plugin\AbstractPlugin;
use Apitte\Core\DI\Plugin\CoreSchemaPlugin;
use Apitte\Core\DI\Plugin\PluginCompiler;
use Apitte\Debug\Negotiation\Transformer\DebugDataTransformer;
use Apitte\Debug\Negotiation\Transformer\DebugTransformer;
use Apitte\Debug\Schema\Serialization\DebugSchemaDecorator;
use Apitte\Debug\Tracy\BlueScreen\ApiBlueScreen;
use Apitte\Debug\Tracy\BlueScreen\ValidationBlueScreen;
use Apitte\Debug\Tracy\Panel\ApiPanel;
use Apitte\Negotiation\DI\NegotiationPlugin;
use Nette\DI\ContainerBuilder;
use Nette\PhpGenerator\ClassType;
use Tracy\Debugger;
class DebugPlugin extends AbstractPlugin
{
public const PLUGIN_NAME = 'debug';
/** @var mixed[] */
protected $defaults = [
'debug' => true,
];
public function __construct(PluginCompiler $compiler)
{
parent::__construct($compiler);
$this->name = self::PLUGIN_NAME;
}
/**
* Register services
*/
public function loadPluginConfiguration(): void
{
$builder = $this->getContainerBuilder();
$global = $this->compiler->getExtension()->getConfig();
$config = $this->getConfig();
if ($global['debug'] !== true && $config['debug'] !== true) return;
$builder->addDefinition($this->prefix('panel'))
->setClass(ApiPanel::class);
$this->loadNegotiationDebugConfiguration();
// BueScreen - runtime
ApiBlueScreen::register(Debugger::getBlueScreen());
ValidationBlueScreen::register(Debugger::getBlueScreen());
}
protected function loadNegotiationDebugConfiguration(): void
{
// Skip if plugin apitte/negotiation is not loaded
if (!$this->compiler->getPluginByType(NegotiationPlugin::class)) return;
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('transformer.debug'))
->setFactory(DebugTransformer::class)
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => 'debug']);
$builder->addDefinition($this->prefix('transformer.debugdata'))
->setFactory(DebugDataTransformer::class)
->addTag(ApiExtension::NEGOTIATION_TRANSFORMER_TAG, ['suffix' => 'debugdata']);
// Setup debug schema decorator
CoreSchemaPlugin::$decorators['debug'] = new DebugSchemaDecorator();
}
public function afterPluginCompile(ClassType $class): void
{
$global = $this->compiler->getExtension()->getConfig();
$config = $this->getConfig();
$initialize = $class->getMethod('initialize');
$initialize->addBody('?::register($this->getService(?));', [ContainerBuilder::literal(ApiBlueScreen::class), 'tracy.blueScreen']);
$initialize->addBody('?::register($this->getService(?));', [ContainerBuilder::literal(ValidationBlueScreen::class), 'tracy.blueScreen']);
if ($global['debug'] === true && $config['debug'] === true) {
$initialize->addBody('$this->getService(?)->addPanel($this->getByType(?));', ['tracy.bar', ApiPanel::class]);
}
}
}
<file_sep># Apitte/Debug
## Content
- [Installation - how to register a plugin](#plugin)
- [Tracy - debugging](#tracy)
- [Bridges - extra features](#bridges)
- [Playground - real examples](#playground)
## Plugin
This plugin requires [Apitte/Core](https://github.com/apitte/core) library.
At first you have to register the main extension.
```yaml
extensions:
api: Apitte\Core\DI\ApiExtension
```
Secondly, add the `DebugPlugin` plugin.
```yaml
api:
plugins:
Apitte\Debug\DI\DebugPlugin:
```
## Tracy
This plugin adds 2 Tracy extensions:
- panel
- bluescreen panel
## Bridges
### Apitte/Negotiation
This plugin also adds some extra features if you use `apitte/negotiation`. At first take a [quick look at documentation](https://github.com/apitte/negotiation/tree/master/.docs).
This plugins register 2 more transformers:
- `DebugTransformer` - You can type `example.com/user.debug` and you'll see dump of `Apitte\Core\Http\ApiResponse`. In case of exception, you'll see the Tracy-exception.
- `DebugDataTransformer` - You can type `example.com/user.debugdata` and you'll see dump of response entity data.
## Playground
I've made a repository with full applications for education.
Take a look: https://github.com/apitte/playground
| bc0ead1a2b4509c87ddda093c27721ace0f5d4ca | [
"Markdown",
"PHP"
] | 2 | PHP | FVesely/debug | 8dc64784ce347b651c3f2c9469d55b5ac3ab108b | 3d72729048e19b44962c3468b163a409f7d36b52 |
refs/heads/master | <repo_name>reactomoss/trove-crm-frontend<file_sep>/src/app/shared/echarts/echarts.component.ts
import { Component, Input } from '@angular/core';
import * as echarts from 'echarts';
@Component({
selector: 'app-echarts',
templateUrl: './echarts.component.html',
styleUrls: ['./echarts.component.css']
})
export class EchartsComponent {
@Input() chartOption: echarts.EChartsOption;
constructor() { }
}
<file_sep>/src/app/pages/settings/pipelinestages/pipelinestages.component.ts
import {
AfterViewInit,
Component,
OnInit,
ViewChild,
ChangeDetectorRef,
AfterContentChecked,
} from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
FormArray,
} from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { SnackBarService } from '../../../shared/snack-bar.service';
import { extractErrorMessagesFromErrorResponse } from '../../../services/extract-error-messages-from-error-response';
import { FormStatus } from '../../../services/form-status';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import {
Subscription,
Observable,
of as observableOf,
BehaviorSubject,
combineLatest,
merge,
} from 'rxjs';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
import { MatInputModule } from '@angular/material/input';
/*For PipelineStages Table*/
export interface PIPELINESTAGE {
pipelineStages: string;
dealStages: any;
}
/*For PipelineStages Table*/
@Component({
selector: 'app-pipelinestages',
templateUrl: './pipelinestages.component.html',
styleUrls: ['./pipelinestages.component.css'],
})
export class PipelinestagesComponent implements OnInit,AfterViewInit {
/*For PipelineStages Table*/
displayedPipelineColumns: any[] = ['pipelineStages', 'dealStages', 'action'];
dataSourcePipeline: MatTableDataSource<PIPELINESTAGE>;
pipelines: PIPELINESTAGE[];
/*For PipelineStages Table*/
/*Form Validation*/
addPipelineForm: FormGroup;
initPipelineForm(data: any = []) {
if (data) {
this.updatePipelineId = data.id;
this.addPipelineForm = this.fb.group({
pipeline: [data.name, Validators.required],
});
} else {
this.addPipelineForm = this.fb.group({
pipeline: ['', Validators.required],
/*stages: this.fb.array([
this.addPipelineStage()
])*/
});
}
}
/*Form Validation*/
closeResult = '';
constructor(
private modalService: NgbModal,
private fb: FormBuilder,
private sb: SnackBarService,
private settingsApiService: SettingsApiService,
private cdref: ChangeDetectorRef
) {
this.initPipelineForm();
}
/*Modal dialog*/
open(content, id = '') {
if (id) {
this.settingsApiService.getPipelineById(id).subscribe(
(res: any) => {
if (res.success) {
if (res.data.menu_previlages.create == 1) {
this.initPipelineForm(res.data.id);
if (res.data.id.stages) {
this.dragElements = [];
var self = this;
res.data.id.stages.forEach(function (value, key) {
self.dragElements.push({
id: value.id,
name: value.name,
order: value.order,
probability: value.probability,
});
});
}
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(
reason
)}`;
}
);
} else {
this.triggerSnackBar(res.message, 'Close');
}
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
} else {
this.dragElements = [];
this.addPipelineStage();
this.initPipelineForm();
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
/*Modal dialog*/
// Pipeline drag and drop
dragElements: any = [];
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.dragElements, event.previousIndex, event.currentIndex);
}
// add pipeline method
addPipelineStage(): void {
this.dragElements.push({
name: '',
order: 0,
probability: 0,
});
this.calculateProbability();
}
// remove pipeline method
removePipelineStage(index: number) {
this.dragElements.splice(index, 1);
this.calculateProbability();
}
// Pipeline drag and drop
ngOnInit(): void {
// For Pipeline table
this.addPipelineStage();
}
ngAfterViewInit() {
this.listPipelines();
}
/** ========================================================================================= */
displayedColumnsPipeline: string[] = ['name', 'stages_count', 'action'];
formStatus = new FormStatus();
private subscriptions: Subscription[] = [];
errors = [];
menu_previlages = {
create: 0,
delete: 0,
edit: 0,
view: 0,
};
PipelineList: Observable<any[]>;
filterValue = '';
updatePipelineId = '';
deletePipelineId = '';
pipelineConfirmationForDelete = false;
resultsLength = 0;
isLoadingResults = true;
isRateLimitReached = false;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
savePipeline() {
var self = this;
if (!this.addPipelineForm.valid) {
return false;
} else {
// 2 - Call onFormSubmitting to handle setting the form as submitted and
// clearing the error and success messages array
this.formStatus.onFormSubmitting();
this.dragElements.map((r, key) => {
r.order = key + 1;
});
const formData = {
pipeline_name: this.addPipelineForm.get('pipeline').value,
stages: this.dragElements,
};
if(this.updatePipelineId){
const subs_query_param = this.settingsApiService
.updatePipeline(formData, this.updatePipelineId)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listPipelines();
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.stageServerError(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
} else {
const subs_query_param = this.settingsApiService
.addPipeline(formData)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listPipelines();
},
(errorResponse: HttpErrorResponse) => {
this.errors = errorResponse.error.data;
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
//this.addPipelineForm.setErrors({ 'invalid': true });
this.stageServerError(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
}
}
}
listPipelines() {
this.PipelineList = merge(this.sort.sortChange, this.paginator.page).pipe(
// startWith([undefined, ]),
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.settingsApiService.listPipelines(
this.sort.active,
this.sort.direction,
this.paginator.pageIndex,
this.paginator.pageSize
);
}),
map((data) => {
// Flip flag to show that loading has finished.
this.isLoadingResults = false;
this.isRateLimitReached = false;
this.resultsLength = data.data.recordsTotal;
this.menu_previlages = data.menu_previlages;
/*this.menu_previlages.create = data.menu_previlages.create;
this.menu_previlages.delete = data.menu_previlages.delete;
this.menu_previlages.edit = data.menu_previlages.edit;
this.menu_previlages.view = data.menu_previlages.view;*/
return data.data.data;
}),
catchError(() => {
this.isLoadingResults = false;
// Catch if the API has reached its rate limit. Return empty data.
this.isRateLimitReached = true;
return observableOf([]);
})
);
}
deleteModal(content, id) {
this.deletePipelineId = id;
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
deletePipeline(id) {
this.settingsApiService.deletePipeline(id).subscribe(
(res: any) => {
if (res.success) {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listPipelines();
this.deletePipelineId = '';
this.pipelineConfirmationForDelete = false;
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
closeModal() {
this.updatePipelineId = '';
this.deletePipelineId = '';
this.modalService.dismissAll();
}
resetPagingRole(): void {
this.paginator.pageIndex = 0;
}
//defining method for display of SnackBar
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
ngAfterContentChecked() {
this.cdref.detectChanges();
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
markAsPristine(){
this.addPipelineForm.markAsPristine();
this.addPipelineForm.controls.value.markAsDirty();
}
stagename(event, obj){
var text = event.target.value;
if(text){
//this.addPipelineForm.setErrors({ 'valid': true });
delete obj.errors;
} else {
//this.addPipelineForm.setErrors({ 'invalid': true });
if(!("errors" in obj)){
obj['errors'] = [];
}
if(!obj['errors'].includes('stage name is required')){
obj['errors'].push('stage name is required');
}
}
}
stageprobability(event, obj){
var text = event.target.value;
if(text > 0){
//this.addPipelineForm.setErrors({ 'valid': true });
delete obj.errors;
} else {
//this.addPipelineForm.setErrors({ 'invalid': true });
if(!("errors" in obj)){
obj['errors'] = [];
}
if(!obj['errors'].includes('stage probability must be 1')){
obj['errors'].push('stage probability must be 1');
}
}
}
stageServerError(errorResponse){
this.dragElements.forEach(function(v){ delete v.errors });
for (const property in errorResponse.error.data) {
var myArray = property.split('.');
if(myArray.length == 3){
if(!("errors" in this.dragElements[myArray[1]])){
this.dragElements[myArray[1]]['errors'] = [];
}
const propertyErrors: Array<string> = errorResponse.error.data[property];
propertyErrors.forEach(error => this.dragElements[myArray[1]]['errors'].push(error));
this.dragElements[myArray[1]]['errors'] = Array.from(new Set(this.dragElements[myArray[1]]['errors']));
}
};
}
calculateProbability(){
var total = this.dragElements.length;
var percent = 100;
var probabilityValue = percent/total;
this.dragElements.forEach(function(v){
v.probability = probabilityValue;
});
}
}
<file_sep>/src/app/pages/leads/lead-table/lead-table.component.ts
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
export interface PeriodicElement {
avatar: string;
name: string;
description: string;
stage: string;
value: number;
day: number;
owner: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description1", stage: 'Qualified', value: 0, day: 1, owner: 'Packet Monster, Inc.' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description2", stage: 'Evolution', value: 400, day: 1, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description3", stage: 'Evolution', value: 300, day: 1, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description4", stage: 'Evolution', value: 40, day: 1, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description5", stage: 'Evolution', value: 2, day: 2, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description6", stage: 'Evolution', value: 10000, day: 1, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description7", stage: 'Evolution', value: 200, day: 1, owner: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description8", stage: 'Evolution', value: 60, day: 3, owner: 'Me' },
]
@Component({
selector: 'app-lead-table',
templateUrl: './lead-table.component.html',
styleUrls: ['./lead-table.component.css']
})
export class LeadTableComponent implements AfterViewInit {
displayedColumns: string[] = ['name', 'stage', 'value', 'day', 'owner'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
selectedTh = ''
constructor(private router: Router) { }
@ViewChild(MatSort, {static: false}) sort: MatSort;
ngAfterViewInit (): void {
this.dataSource.sort = this.sort;
}
clickRow(row) {
console.log('row', row)
this.router.navigate(['/pages/lead_detail']);
}
clickTh(type) {
this.selectedTh = type
console.log(this.selectedTh)
}
}
<file_sep>/src/app/pages/detail/widget/widget.component.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
export class Task {
constructor(public name: string, public icon: string , public color: string, public desc: string, public selected?: boolean) {
if (selected === undefined) selected = false
}
}
export class Appointment {
constructor(public name: string, public icon: string , public color: string, public desc: string, public selected?: boolean) {
if (selected === undefined) selected = false
}
}
export class File {
constructor(public name: string, public type: string, public description: string) {
}
}
@Component({
selector: 'app-widget',
templateUrl: './widget.component.html',
styleUrls: ['./widget.component.css']
})
export class WidgetComponent implements OnInit {
@Output() addTaskClicked = new EventEmitter()
@Output() addAppointClicked = new EventEmitter()
tasks: Task[] = [
new Task("Packet Monster Sales opportunity", "notification", "default", "Today at 9:00"),
new Task("Ux design meeting at 17:30hrs.", "calendar", "red", "Sat, 21 Apr, 2021"),
new Task("Landing page required for new CRM app", "notification", "default", "Sun, 22 Apr, 2021"),
new Task("Meeting required for new CRM app", "calendar", "default", "Mon, 23 Apr, 2021"),
]
appointments: Appointment[] = [
new Appointment("Packet Monster Sales opportunity", "notification", "default", "Today at 9:00"),
new Appointment("Appointment meeting at 17:30hrs.", "calendar", "red", "Sat, 21 Apr, 2021"),
new Appointment("Landing page required for new CRM app", "notification", "default", "Sun, 22 Apr, 2021"),
new Appointment("UX required for new CRM app", "calendar", "default", "Mon, 23 Apr, 2021"),
]
files: File[] = [
new File("Sales guide to file.docx", "word", "57.35KB, 2021/01/16 14:05"),
new File("Weekly sales reort(Jan 1-7).xls", "excel", "5 Bytes, 2021/01/16 14:05"),
new File("FIle export-status.pdf", "pdf", "3.9 MB, 2021/01/16 14:05"),
new File("Sales guide to file1.docx", "word", "57.35KB, 2021/02/1 14:05"),
new File("Sales guide to file2.docx", "pdf", "57.35KB, 2021/02/2 15:05"),
new File("Sales guide to file3.docx", "excel", "57.35KB, 2021/02/3 16:05"),
new File("Sales guide to file4.docx", "word", "57.35KB, 2021/02/4 17:05")
]
constructor() { }
ngOnInit(): void {
}
addAppoint() {
console.log('add appoint')
this.addAppointClicked.emit(false)
}
editAppoint() {
console.log('Edit appoint')
this.addAppointClicked.emit(true)
}
addTask() {
console.log('add task')
this.addTaskClicked.emit(false)
}
editTask() {
console.log('add task')
this.addTaskClicked.emit(true)
}
}
<file_sep>/src/app/services/lead-api.service.ts
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
HttpParams,
} from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class LeadApiService {
baseURL = environment.baseUrl;
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
constructor(private httpClient: HttpClient) {}
initLeadForm(id = ''): Observable<any> {
var param = '';
if (id) {
param = '/' + id;
}
let API_URL = `${this.baseURL + environment.leads + param}`;
return this.httpClient.get(API_URL);
}
addLead(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.leads}`, data);
}
}
<file_sep>/src/app/services/settings-api.service.ts
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
HttpParams,
} from '@angular/common/http';
//import { start } from 'repl';
@Injectable({
providedIn: 'root',
})
export class SettingsApiService {
baseURL = environment.baseUrl;
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
};
constructor(private httpClient: HttpClient) {}
// Settings Profile View From
accountMe(): Observable<any> {
let API_URL = `${this.baseURL + environment.me}`;
return this.httpClient.get(API_URL);
}
updateProfile(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.profile}`, data);
}
changePassword(data: any): Observable<any> {
return this.httpClient.post(
`${this.baseURL + environment.changePassword}`,
data
);
}
preferenceMe(): Observable<any> {
let API_URL = `${this.baseURL + environment.preference}`;
return this.httpClient.get(API_URL);
}
updatePreference(data: any): Observable<any> {
return this.httpClient.post(
`${this.baseURL + environment.preference}`,
data
);
}
changeProfilePic(profile_pic: any): Observable<any> {
// Create form data
const formData = new FormData();
// Store form name as "file" with file data
formData.append('profile_pic', profile_pic, profile_pic.name);
return this.httpClient.post(
`${this.baseURL + environment.profile_picture}`,
formData
);
}
removeProfilePic(){
return this.httpClient.get(`${this.baseURL + environment.profile_picture}`);
}
initUserForm(id = ''): Observable<any> {
var param = "";
if(id){
param = "/"+id;
}
return this.httpClient.get(`${this.baseURL + environment.users + param}`);
}
addUser(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.users}`, data);
}
updateUser(data: any, id): Observable<any>{
return this.httpClient.post(`${this.baseURL + environment.users + "/" + id +"?_method=PUT"}`, data);
}
changeUserStatus(status, id){
return this.httpClient.put(`${this.baseURL + environment.users + "/status/"+ id}`, {user_status: status});
}
deleteUser(id): Observable<any>{
return this.httpClient.delete(`${this.baseURL + environment.users + "/" + id}`);
}
listUser(
sort: string,
order: string,
page: number,
pageSize: number,
search: string = ''
): Observable<any> {
var start, length;
var items_per_page = 10;
var data = {
search: search,
start: page * pageSize,
length: pageSize,
};
if (typeof sort != 'undefined' && typeof order != 'undefined') {
data['order'] = [{ column: sort, dir: order }];
}
return this.httpClient.post(
`${this.baseURL + environment.listusers}`,
data
);
}
initRoleForm(id = ''): Observable<any> {
var param = "";
if(id){
param = "/"+id;
}
return this.httpClient.get(
`${this.baseURL + environment.roles + param}`
);
}
addRole(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.roles}`, data);
}
updateRole(data:any, id): Observable<any>{
return this.httpClient.post(`${this.baseURL + environment.roles + "/" + id +"?_method=PUT"}`, data);
}
changeRoleStatus(status, id){
return this.httpClient.put(`${this.baseURL + environment.roles + "/status/"+ id}`, {user_status: status});
}
listRoles(
sort: string,
order: string,
page: number,
pageSize: number,
search: string = ''
): Observable<any> {
var start, length;
var items_per_page = 10;
var data = {
search: search,
start: page * pageSize,
length: pageSize,
};
if (typeof sort != 'undefined' && typeof order != 'undefined') {
data['order'] = [{ column: sort, dir: order }];
}
return this.httpClient.post(
`${this.baseURL + environment.listroles}`,
data
);
}
deleteRole(id): Observable<any>{
return this.httpClient.delete(`${this.baseURL + environment.roles + "/" + id}`);
}
getNotificationSettings(): Observable<any> {
return this.httpClient.get(`${this.baseURL + environment.notifications}`);
}
saveNotificationSettings(data: any): Observable<any> {
return this.httpClient.post(
`${this.baseURL + environment.notifications}`,
data
);
}
addPipeline(data): Observable<any> {
return this.httpClient.post(
`${this.baseURL + environment.pipelines}`,
data
);
}
getPipelineById(id): Observable<any>{
return this.httpClient.get(`${this.baseURL + environment.pipelines + "/" + id}`);
}
listPipelines(
sort: string,
order: string,
page: number,
pageSize: number,
search: string = ''
): Observable<any> {
var start, length;
var items_per_page = 10;
var data = {
search: search,
start: page * pageSize,
length: pageSize,
};
if (typeof sort != 'undefined' && typeof order != 'undefined') {
data['order'] = [{ column: sort, dir: order }];
}
return this.httpClient.post(
`${this.baseURL + environment.pipelines + "/list"}`,
data
);
}
updatePipeline(data:any, id): Observable<any>{
return this.httpClient.put(`${this.baseURL + environment.pipelines + "/" + id}`, data);
}
deletePipeline(id): Observable<any>{
return this.httpClient.delete(`${this.baseURL + environment.pipelines + "/" + id}`);
}
}
<file_sep>/src/app/pages/sourcechart/source-filter/source-filter.component.ts
import { Component, OnInit, ViewChildren, QueryList, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { Options } from "@angular-slider/ngx-slider";
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith,take, tap } from 'rxjs/operators';
import { DateService } from '../../../service/date.service'
export interface createContact {
name: string;
isChecked?: boolean;
}
export interface createCompany {
name: string;
isChecked?: boolean;
}
// multi autocomplete
export class Contact {
constructor(public name: string, public selected?: boolean) {
if (selected === undefined) selected = false;
}
}
export class Source {
constructor(public name: string, public selected?: boolean) {
if (selected === undefined) selected = false;
}
}
@Component({
selector: 'app-source-filter',
templateUrl: './source-filter.component.html',
styleUrls: ['./source-filter.component.css']
})
export class SourceFilterComponent implements OnInit {
@ViewChildren("checkboxes") checkboxes: QueryList<ElementRef>
// @Input() filterCount:number
@Output() filterCountChanged: EventEmitter<number> = new EventEmitter();
// @Input() listShow:boolean
@Output() closeDialog = new EventEmitter();
@Output() count = new EventEmitter<any>();
contactCtrl = new FormControl();
companyCtrl = new FormControl();
filteredCont: Observable<createContact[]>;
filteredComp: Observable<createCompany[]>;
selectedCreatedBy: createContact[] = [];
selectedCompany: createCompany[] = [];
filterCount: number = 0
myControl = new FormControl();
searchOptions: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
minValue: number = 100;
highValue: number = 9000;
sliderOptions: Options = {
floor: 0,
ceil: 100000
}
contactActive: number = 0
selectedPipe: string[] = []
dateTypes: number[] = [0, 1, 2, 3, 4, 5, 6]
dateTypeString: string[] = ['Today', 'Yesterday', 'Last Week', 'This month', 'Last month', 'This Quarter', 'Custom']
dateType: number
statusType: string = ''
selectedSource: string[] = []
public startDate: Date = null
public endDate: Date = null
scrollOptions = { autoHide: true, scrollbarMinSize: 30 }
// multi autocomplete
sources = [
new Source('SMS'),
new Source('Website'),
new Source('News'),
new Source('Test1'),
new Source('Test2'),
]
sourceAll: boolean = false
createdBySelection(contact: createContact){
if(contact.isChecked) {
this.selectedCreatedBy = [...this.selectedCreatedBy, contact]
}else {
let index = this.selectedCreatedBy.findIndex(c => c.name === contact.name);
this.selectedCreatedBy.splice(index,1);
}
}
companySelection(contact: createCompany){
if(contact.isChecked) {
this.selectedCompany = [...this.selectedCompany, contact]
}else {
let index = this.selectedCompany.findIndex(c => c.name === contact.name);
this.selectedCompany.splice(index,1);
}
}
contacts: createContact[] = [
{
name: 'Arkansas',
},
{
name: 'California'
},
{
name: 'Florida'
},
{
name: 'Texas'
}
];
companys: createCompany[] = [
{
name: 'Company 1',
},
{
name: 'Company 2'
},
{
name: 'Company 3'
},
{
name: 'Company 4'
}
];
constructor(private dateService: DateService) {
this.filteredCont = this.contactCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStates(state) : this.contacts.slice())
);
this.filteredComp = this.companyCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStatesComp(state) : this.companys.slice())
);
}
ngOnInit(): void {
}
calculateFilterCount(): number {
this.filterCount = 0;
if(this.statusType) {
this.filterCount += 1;
}
if(this.selectedCreatedBy.length > 0) {
this.filterCount += 1;
}
if(this.selectedCompany.length > 0) {
this.filterCount += 1;
}
if(this.dateType != -1 && (this.dateType || this.dateType == 0)) {
this.filterCount += 1;
}
if(this.getSelectedSource() != '') {
this.filterCount += 1;
}
if(this.selectedPipe.length > 0){
this.filterCount += 1;
}
if(this.minValue != null && this.highValue != null){
this.filterCount += 1;
}
this.count.emit(this.filterCount);
return this.filterCount;
}
clearAll() {
this.clearStatus();
this.clearCreatedBy();
this.clearCompany();
this.clearDate();
this.clearSource();
this.clearPipe();
this.clearValueClick();
}
public clearSource() {
this.sources.forEach(e => {
e.selected = false;
})
this.sourceAll= false
}
public clearDate() {
this.dateType = -1
}
public clearStatus() {
this.statusType = undefined;
}
public clearPipe() {
this.selectedPipe = [];
}
public clearCreatedBy() {
this.selectedCreatedBy = [];
this.filteredCont.pipe(
tap(data => {
data.forEach(c => {
c.isChecked = false;
})
}),
take(1)
).subscribe();
}
public clearCompany() {
this.selectedCompany = [];
this.filteredComp.pipe(
tap(data => {
data.forEach(c => {
c.isChecked = false;
})
}),
take(1)
).subscribe();
}
displayFn(value: Contact[] | string): string | undefined {
return ""
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.searchOptions.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
}
public clearValueClick() {
this.minValue = null
this.highValue = null
}
public clickDiscovery(item) {
const index = this.selectedPipe.indexOf(item, 0);
if (index > -1) {
this.selectedPipe.splice(index, 1);
} else {
this.selectedPipe.push(item)
}
}
public checkPipe(item) {
const index = this.selectedPipe.indexOf(item, 0);
if (index > -1) {
return true
} else {
return false
}
}
//source
public sourceSelect(source) {
source.selected = !source.selected
this.sourceAll = this.sources != null && this.sources.every(t => t.selected);
}
//source
public allSourceSelect(event) {
const checked = event.checked
this.sources.forEach(e => e.selected = checked)
}
//source
getSelectedSource() {
let arr = []
this.sources.forEach(e => {
e.selected && arr.push(e.name)
})
return this.displayArray(arr)
}
public displayArray(arr) {
let ret = ''
arr.length == 1 && (ret += arr[0])
arr.length == 2 && (ret += arr[0] + ', ' + arr[1])
arr.length > 2 && (ret += arr[0] + ', ' + arr[1] + ' +' + (arr.length - 2))
return ret
}
public getSelectedDate() {
if (this.dateType == -1) {
return ''
}
switch (this.dateType) {
case 0:
const today = this.dateService.getToday()
return today + ' ~ ' + today
case 1:
const yesterday = this.dateService.getYesterday()
return yesterday + ' ~ ' + yesterday
case 2:
return this.dateService.getLastWeek()
case 3:
return this.dateService.getThisMonth()
case 4:
return this.dateService.getLastMonth()
case 5:
return this.dateService.getThisQuarter()
case 6:
let firstDay = '', lastDay = ''
this.startDate && (firstDay = this.dateService.dateToString(this.startDate))
this.endDate && (lastDay = this.dateService.dateToString(this.endDate))
return firstDay + ' ~ ' + lastDay
}
}
private _filterStates(value: string): createContact[] {
const filterValue = value.toLowerCase();
return this.contacts.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);
}
private _filterStatesComp(value: string): createContact[] {
const filterValue = value.toLowerCase();
return this.companys.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);
}
}
<file_sep>/src/app/user-registration/forgot-password/new-password/new-password.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationExtras } from '@angular/router';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { AccountApiService } from './../../../services/account-api.service';
import { ConfirmedValidator } from './../../../services/confirmed.validator';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-new-password',
templateUrl: './new-password.component.html',
styleUrls: ['./new-password.component.css'],
})
export class NewPasswordComponent implements OnInit, OnDestroy {
public error = [];
public form = {
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
reset_token: null,
};
apiResponse: any;
clicked = false;
private subscriptions: Subscription[] = [];
constructor(
public formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private account: AccountApiService
) {
const subs_query_param = route.queryParams.subscribe((params) => {
this.form.reset_token = params['token'];
const subs_validate_token = this.account
.validateResetPasswordToken(params['token'])
.subscribe(
(response) => {
this.apiResponse = response;
},
(err) => {
//console.log(err.error);
let objToSend: NavigationExtras = {
queryParams: {
success: false,
message: err.error.message,
},
};
this.router.navigate(['login'], {
state: objToSend,
});
}
);
this.subscriptions.push(subs_validate_token);
});
this.subscriptions.push(subs_query_param);
const subs_value_change = this.ResetPasswordForm.valueChanges.subscribe(
(data) => {
//console.log("value change");
this.apiResponse = false;
}
);
this.subscriptions.push(subs_value_change);
}
ngOnInit(): void {}
pwd = true;
confirmPwd = true;
ResetPasswordForm = this.formBuilder.group(
{
password: [
'',
[
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,12}$'
),
],
],
password_confirmation: [
'',
[
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,12}$'
),
],
],
},
{
validator: ConfirmedValidator('password', 'password_confirmation'),
}
);
onSubmit() {
if (!this.ResetPasswordForm.valid) {
return false;
} else {
this.clicked = true;
this.form.password = <PASSWORD>.get('password').value;
this.form.password_confirmation = <PASSWORD>.ResetPasswordForm.get(
'password_confirmation'
).value;
this.account.resetPassword(this.form).subscribe(
(response) => {
this.clicked = false;
let objToSend: NavigationExtras = {
queryParams: {
success: true,
message: response.message,
},
};
this.router.navigate(['login'], {
state: objToSend,
});
//this.router.navigate(['login'], {queryParams: { reset: 'true' } });
},
(err) => {
this.clicked = false;
this.apiResponse = err.error;
}
);
}
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/app/shared/snack-bar.service.ts
import { Injectable } from '@angular/core';
import {
MatSnackBar,
MatSnackBarHorizontalPosition,
MatSnackBarVerticalPosition,
} from '@angular/material/snack-bar';
import { SnackbarComponent } from './snackbar/snackbar.component';
@Injectable({
providedIn: 'root'
})
export class SnackBarService {
horizontalPositionLeft: MatSnackBarHorizontalPosition = 'left';
horizontalPositionCenter: MatSnackBarHorizontalPosition = 'center';
horizontalPositionRight: MatSnackBarHorizontalPosition = 'right';
verticalPositionTop: MatSnackBarVerticalPosition = 'top';
verticalPositionBottom: MatSnackBarVerticalPosition = 'bottom';
constructor(private snackBar:MatSnackBar) { }
openSnackBarTopLeft(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
horizontalPosition: this.horizontalPositionLeft,
verticalPosition: this.verticalPositionTop,
});
}
openSnackBarTopCenter(message: string, action: string, duration: number) {
this.snackBar.open(message, action, {
duration: 2000,
horizontalPosition: this.horizontalPositionCenter,
verticalPosition: this.verticalPositionTop,
});
}
openSnackBarTopCenterAsDuration(message: string, action: string, duration: number) {
this.snackBar.open(message, action, {
duration: duration,
horizontalPosition: this.horizontalPositionCenter,
verticalPosition: this.verticalPositionTop,
});
}
openSnackBarTopRight(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
horizontalPosition: this.horizontalPositionRight,
verticalPosition: this.verticalPositionTop,
});
}
openSnackBarBottomLeft(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
horizontalPosition: this.horizontalPositionLeft,
verticalPosition: this.verticalPositionBottom,
});
}
openSnackBarBottomCenter(message: string, action: string) {
this.snackBar.openFromComponent(SnackbarComponent, {
data: {
message: message,
action : action
},
duration: 2000,
horizontalPosition: this.horizontalPositionCenter,
verticalPosition: this.verticalPositionBottom,
panelClass: 'themeSnackbar'
});
}
openSnackBarBottomRight(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
horizontalPosition: this.horizontalPositionRight,
verticalPosition: this.verticalPositionBottom,
});
}
}
<file_sep>/src/app/pages/settings/account/preference-data.ts
export interface TIMEZONES {
id: number;
zones: string;
value: string
abbr: string
utc: string
offset: string
status: number
created_at: string
updated_at: string
}
export interface TIMEFORMATS {
id: number;
timeformat: string
status: number
created_at?: string
updated_at: string
}
export interface DATEFORMATS {
id: number
dateformat: string
status: number
created_at?: string
updated_at?:string
}
export interface CURRENCYFORMATS {
id: number;
name: string
symbol: string
symbol_native: string
decimal_digits: number
code: string
status: number
created_at: string
updated_at: string
}
export interface PREFERENCEDATA {
id: number
user_id: number
timezone_id: number
currency_id: number
timeformat_id: number
dateformat_id: number
status: number
created_at: string
updated_at: string
}
<file_sep>/src/app/pages/company/filter/filter.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { DateService } from '../../../service/date.service'
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { filter, map, startWith, take, tap } from 'rxjs/operators';
export interface CompanyFilters {
count: number
status: string
activity: number
activityStartDate: Date
activityEndDate: Date
addedon: number
addedonStartDate: Date
addedonEndDate: Date
owners: number[]
}
export interface CompanyOwner {
id: number;
full_name: string;
isChecked?: boolean;
}
@Component({
selector: 'company-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css']
})
export class CompanyFilterComponent implements OnInit {
@Input() companyOwners: CompanyOwner[] = [];
@Output() closeDialog = new EventEmitter();
@Output() notifyFilters = new EventEmitter<CompanyFilters>();
ownerFilterCtrl = new FormControl();
ownerFilterObserver: Observable<CompanyOwner[]>;
selectedOwners: CompanyOwner[] = [];
statusTypes: string[] = ['All', 'Active', 'Inactive']
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
filters: CompanyFilters = {
count: 0,
status: null,
activity: -1,
activityStartDate: null,
activityEndDate: null,
addedon: -1,
addedonStartDate: null,
addedonEndDate: null,
owners: [],
}
dateFormat = 'DD/MM/YYYY'
filterByOwner(item: CompanyOwner){
if (item.isChecked) {
this.selectedOwners = [...this.selectedOwners, item]
}
else {
let index = this.selectedOwners.findIndex(c => c.full_name === item.full_name);
this.selectedOwners.splice(index, 1);
}
this.filters.owners = this.selectedOwners.map(s => s.id)
this.notify()
}
dateTypes: number[] = [0, 1, 2, 3, 4, 5, 6]
dateTypeString: string[] = ['Today', 'Yesterday', 'Last Week', 'This month', 'Last month', 'This Quarter', 'Custom']
dateType: number
addDateTypes: number[] = [0, 1, 2, 3, 4, 5, 6]
addDateTypeString: string[] = ['Today', 'Yesterday', 'Last Week', 'This month', 'Last month', 'This Quarter', 'Custom']
constructor(private dateService: DateService) {
this.ownerFilterObserver = this.ownerFilterCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStates(state) : this.companyOwners.slice())
);
}
ngOnInit(): void {
}
public getSelectedDate() {
if (this.filters.activity == -1) {
return ''
}
if (this.filters.activity == 6) {
let firstDay = '', lastDay = ''
this.filters.activityStartDate && (firstDay = this.dateService.dateToString(this.filters.activityStartDate))
this.filters.activityEndDate && (lastDay = this.dateService.dateToString(this.filters.activityEndDate))
return firstDay + ' ~ ' + lastDay
}
const {startDate, lastDate} = this.dateService.getDateRange(this.filters.activity)
return startDate.format(this.dateFormat) + '~' + lastDate.format(this.dateFormat)
}
public getAddSelectedDate() {
if (this.filters.addedon == -1) {
return ''
}
if (this.filters.activity == 6) {
let firstDay = '', lastDay = ''
this.filters.addedonStartDate && (firstDay = this.dateService.dateToString(this.filters.addedonStartDate))
this.filters.addedonEndDate && (lastDay = this.dateService.dateToString(this.filters.addedonEndDate))
return firstDay + ' ~ ' + lastDay
}
const {startDate, lastDate} = this.dateService.getDateRange(this.filters.addedon)
return startDate.format(this.dateFormat) + '~' + lastDate.format(this.dateFormat)
}
calculateFilterCount(): number {
let filterCount = 0;
if (this.filters.status) {
filterCount += 1;
}
if (this.selectedOwners.length > 0) {
filterCount += 1;
}
if (this.filters.activity != -1 && (this.filters.activity || this.filters.activity == 0)) {
filterCount += 1;
}
if (this.filters.addedon != -1 && (this.filters.addedon || this.filters.addedon == 0)) {
filterCount += 1;
}
return filterCount;
}
clearAll() {
this.clearStatus();
this.clearOwner();
this.clearDate();
this.clearAddDate();
}
public clearStatus() {
this.filters.status = null;
this.notify()
}
public clearOwner() {
this.selectedOwners = [];
this.ownerFilterObserver.pipe(
tap(data => {
data.forEach(c => {
c.isChecked = false;
})
}),
take(1)
).subscribe();
}
public clearDate() {
this.filters.activity = -1
this.notify()
}
public clearAddDate() {
this.filters.addedon = -1
this.notify()
}
public stateFilterChanged(e) {
console.log('stateFilterChanged', e)
this.filters.status = e.value
this.notify()
}
public activityFilterChanged(e) {
console.log('activityFilterChanged', e)
this.filters.activity = e.value
this.notify()
}
public addedonFilterChanged(e) {
console.log('addedonFilterChanged', e)
this.filters.addedon = e.value
this.notify()
}
public notify() {
this.filters.count = this.calculateFilterCount()
this.notifyFilters.emit(this.filters);
}
public closeFilterDilaog() {
this.closeDialog.emit(this.filters)
}
private _filterStates(value: string): CompanyOwner[] {
const filterValue = value.toLowerCase();
return this.companyOwners.filter(state => state.full_name.toLowerCase().indexOf(filterValue) === 0);
}
}
<file_sep>/src/app/pages/leads/leads.component.ts
import { Component, OnInit } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
@Component({
selector: 'app-leads',
templateUrl: './leads.component.html',
styleUrls: ['./leads.component.css']
})
export class LeadsComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
showFilter: boolean = false
listShow: boolean = false
stages: string[] = ['Discovery', 'Qualified', 'Evolution', 'Negotiation', 'Closed']
discovery: number[] = [100, 2, 3, 4, 5]
qualified: number[] = [1, 2]
evolution: number[] = [1]
negotiation: number[] = [1]
closed: number[] = [1, 2, 3]
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
active: number = 1
filterCount: number = 0
viewLeads = "pipe1"
constructor(private router: Router) { }
ngOnInit(): void {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
)
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
}
public activeClass(num) {
if (num == this.active)
return 'activeBtn'
else
return ''
}
public setActive(num) {
console.log('set active', num)
this.active = num
if (num == 1) {
this.options = ['One', 'Two', 'Three']
} else if (num == 2) {
this.options = ['Four', 'Five', 'Six']
} else if (num == 3) {
this.options = ['Seven', 'Eight', 'Nine']
}
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
)
}
public onSelectionChange(event) {
console.log(event.option.value)
}
showList() {
this.listShow = true
}
showCards() {
this.listShow = false
this.showFilter = false
}
dropped(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(
event.container.data,
event.previousIndex,
event.currentIndex
)
} else {
transferArrayItem(
event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex
)
}
}
clickCard() {
this.router.navigate(['/pages/lead_detail']);
}
filterCountChangedHandler(e) {
this.filterCount = e
}
clickFilter(){
this.showFilter = true
}
}
<file_sep>/src/app/user-registration/user-registration.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'signup', pathMatch: 'full' },
{
path: 'signup',
loadChildren: () =>
import('./signup/signup.module').then((m) => m.SignupModule),
},
{
path: 'login',
loadChildren: () =>
import('./login/login.module').then((m) => m.LoginModule),
},
{
path: 'forgot-password',
loadChildren: () =>
import('./forgot-password/forgot-password.module').then(
(m) => m.ForgotPasswordModule
),
},
{
path: 'verify-email',
loadChildren: () =>
import('./verify-email/verify-email.module').then((m) => m.VerifyEmailModule),
},
];
@NgModule({
declarations: [],
imports: [CommonModule, RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class UserRegistrationModule {}
<file_sep>/src/environments/environment.local.ts
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
envName: 'local',
baseUrl: 'http://127.0.0.1:8000/api/',
/** API Methods */
register: 'account/register',
login: 'account/login',
me: 'account/me',
sendPasswordResetLink: 'account/sendPasswordResetLink',
resetPassword: '<PASSWORD>',
validateResetPasswordToken: '<PASSWORD>',
logout: 'account/logout',
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
<file_sep>/src/app/pages/task/task.component.ts
import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TaskDialog } from '../detail/detail.component';
export class Task {
constructor(public name: string, public date: string, public time: string,
public created: string, public selected?: boolean) {
if (selected === undefined) selected = false;
}
}
@Component({
selector: 'app-task',
templateUrl: './task.component.html',
styleUrls: ['./task.component.css']
})
export class TaskComponent implements OnInit {
filterCount: number = 0
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
showFilter: boolean = false
tasks: Task[] = [
new Task("Packet Monster Sales opportunity.", "Mon, 11 Jan", "Today at 9:00", "Mon, 11 Jan"),
new Task("UX design meeting at 17:30 hrs. sales pipeline design discussion.", "Thu, 20 Dec, 2020 ", "", "Wed, 19 Jan"),
new Task("Landing page required for new CRM app", "", "", "Wed, 19 Jan"),
new Task("Packet Monster Sales opportunity", "Mon, 11 Jan", "", "Wed, 19 Jan"),
new Task("UX design meeting at 17:30 hrs. sales pipeline design discussion.", "", "", "Wed, 19 Jan"),
new Task("Landing page required for new CRM app", "", "", "Wed, 19 Jan")
]
completedTasks: Task[] = []
constructor(public dialog: MatDialog) { }
ngOnInit(): void {
}
clickCheckBox(task, i: number) {
task.selected = !task.selected
this.completedTasks = this.getCompletedTasks();
}
getCompletedTasks() {
return this.tasks.reduce((acc, cur) => {
if (cur.selected)
acc.push(cur)
return acc
}, [])
}
clickCompleteCheck(task) {
let found = this.tasks.find(e => e == task)
found.selected = false
this.completedTasks = this.getCompletedTasks();
}
clickAddTask(isEdit: boolean) {
const dialogRef = this.dialog.open(TaskDialog, {
width: '405px',
autoFocus: false,
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
filterCountChangedHandler(e) {
this.filterCount = e
}
clickFilter(){
this.showFilter = true
}
}
<file_sep>/src/app/services/auth-twitter.service.ts
import { Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
export interface User {
uid: string;
email: string;
displayName: string;
photoURL: string;
emailVerified: boolean;
}
@Injectable({
providedIn: 'root'
})
export class AuthTwitterService implements OnInit {
public userData: any;
public user: firebase.User;
constructor(
public afs: AngularFirestore,
public afAuth: AngularFireAuth,
public router: Router,
) {
/*this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
console.log(this.userData);
} else {
localStorage.setItem('user', null);
}
});*/
}
ngOnInit(): void { }
//Sign in with Twitter
signInTwitter() {
return this.AuthLogin(new auth.TwitterAuthProvider());
}
//Sign in with Twitter
signUpTwitter() {
return this.AuthLogin(new auth.TwitterAuthProvider());
}
/* SignOut method for logging out from the Angular/Firebase app */
SignOut() {
return this.afAuth.auth.signOut().then(() => {
this.router.navigate(['sign-in']);
})
}
// Auth logic to run auth providers
AuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((result) => {
console.log('You have been successfully logged in!')
}).catch((error) => {
//window.alert(error);
console.log(error);
})
}
}
<file_sep>/src/app/pages/sourcechart/sourcechart.component.ts
import { Component, OnInit } from '@angular/core';
import * as echarts from 'echarts';
@Component({
selector: 'app-sourcechart',
templateUrl: './sourcechart.component.html',
styleUrls: ['./sourcechart.component.css']
})
export class SourcechartComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
filterCount: number = 0
showFilter: boolean = false
colorsourceChart = ['#7184b8']
sourceChart: echarts.EChartsOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['SMS', 'Website', 'News', 'Task'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Source',
type: 'bar',
barWidth: '10%',
data: [10, 52, 100, 200]
}
],
color: this.colorsourceChart,
};
constructor() { }
ngOnInit(): void {
}
filterCountChangedHandler(e) {
this.filterCount = e
}
clickFilter(){
this.showFilter = true
}
}
<file_sep>/src/app/pages/settings/profile/user-profile.ts
export interface UserProfile {
id: number;
account_id: string;
first_name: string;
last_name: string;
email: string;
no_of_employees: string;
benifical_user: number;
company_name: string;
phone_number?: number;
work_number?: number;
profile_pic: string;
address?: string;
description?: string;
skype_id?: string;
parent_id: number;
welcome_email_sent_at?: string;
verifi_email_sent_at?: string;
email_verified_at?: string;
email_verification_token?: string;
platform: number;
device_token?: string;
record_status: number;
created_by: number;
created_at: string;
created_ip: string;
updated_by?: number;
updated_at: string;
updated_ip?: string;
deleted_by?: number;
deleted_at?: string;
deleted_ip?: string;
role_id?: number;
}
<file_sep>/src/app/services/http-interceptor.service.ts
import { TokenService } from './token.service';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { SpinnerOverlayService } from './spinner-overlay.service';
import { finalize } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
constructor(private token: TokenService, private readonly spinnerOverlayService: SpinnerOverlayService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
//console.log("Interceptor");
this.spinnerOverlayService.show();
const newReq = req.clone({
setHeaders: {
Authorization: `Bearer ${this.token.get()}`
}
});
return next.handle(newReq).pipe(finalize(() => this.spinnerOverlayService.hide()));
}
}
<file_sep>/src/app/pages/detail/detail.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { MatSnackBar, MatSnackBarConfig, MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { LeadDialog } from 'src/app/shared/header/header.component';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {
stages: string[];
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
status:string = "Progress"
selectedStage: number
// selectedDisplay = "all"
constructor(private router: Router, public dialog: MatDialog, private _snackBar: MatSnackBar) { }
ngOnInit(): void {
this.stages = ["Discovery", "Qualified", "Evolution", "Negotiation", "Closed"]
}
goToList() {
this.router.navigate(['/pages/leads']);
}
getStageClass(i) {
if (i == 0) {
return "stage-first stage-item"
} else {
return "stage-item"
}
}
clickStage(index) {
this.selectedStage = index
}
openStageDialog(): void {
const dialogRef = this.dialog.open(StageDialog, {
width: '470px'
})
dialogRef.afterClosed().subscribe(result => {
if (result && result.data && result.data == 'create') {
let stageName = result.name
!stageName && (stageName = 'Demo')
this.stages.push(stageName)
this.selectedStage = this.stages.length - 1
this._snackBar.openFromComponent(StageSnack, {
data: { name: stageName},
panelClass: 'stage-success',
duration: 4000,
horizontalPosition: 'center',
verticalPosition: 'bottom'
})
}
})
}
openEditDialog() {
const dialogRef = this.dialog.open(EditDialog, {
width: '560px',
autoFocus: false
});
dialogRef.afterClosed().subscribe(result => {
console.log('result ', result)
if (result && result.data && result.data == 'delete') {
this.openConfirmDialog()
}
})
}
openConfirmDialog() {
const dialogRef = this.dialog.open(ConfirmDialog, {
width: '560px',
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
openTaskDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(TaskDialog, {
width: '405px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
openAppointDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(AppointDialog, {
width: '740px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
getLeftOffset(index) {
return -10 * index
}
getStageSrc(index) {
// if (index == 0) {
// if (this.selectedStage == 0) {
// return '../../../assets/images/stage/start-active-stage-lg.svg'
// } else {
// return '../../../assets/images/stage/start-stage-lg.svg'
// }
// }
if (index == this.selectedStage) {
return '../../../assets/images/stage/active-stage-lg.svg'
}
return '../../../assets/images/stage/mid-stage-lg.svg'
}
editLead() {
const dialogRef = this.dialog.open(LeadDialog, {
width: '560px',
autoFocus: false,
data : { isEdit : true}
})
dialogRef.afterClosed().subscribe(result => {
})
}
}
// Dialogs
@Component({
selector: 'stage-dialog',
templateUrl: 'stage-dialog/stage-dialog.html',
styleUrls: ['stage-dialog/stage-dialog.css']
})
export class StageDialog {
public stageName:string = "Demo"
stagePosition = "before"
constructor(
public dialogRef: MatDialogRef<StageDialog>
// @Inject(MAT_DIALOG_DATA) public data: DialogData
) { }
onNoClick(): void {
this.dialogRef.close({data: 'cancel'});
}
onCreateClick() {
console.log('stage name', this.stageName)
this.dialogRef.close({data: 'create', name: this.stageName});
}
}
@Component({
selector: 'edit-dialog',
templateUrl: 'edit-dialog/edit-dialog.html',
styleUrls: ['edit-dialog/edit-dialog.css']
})
export class EditDialog {
searchControl = new FormControl()
options: string[] = ['Lead Name', 'Primary Contact', 'Value', 'Company', 'Owner', 'Source', 'Secondary Contact',
'Added On']
filteredOptions: Observable<string[]>
showMandatory: boolean = false
search: string = ''
constructor(
public dialogRef: MatDialogRef<EditDialog>
// @Inject(MAT_DIALOG_DATA) public data: DialogData
) {
this.filteredOptions = this.searchControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
)
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
checkMandatory(e) {
this.showMandatory = e.checked
}
onNoClick(): void {
this.dialogRef.close({ data: 'cancel' })
}
onDeleteClick() {
this.dialogRef.close({ data: 'delete' })
}
checkShow(name) {
if (!this.search)
return true
if (name.toUpperCase().search(this.search.toUpperCase()) == -1)
return false
else
return true
}
}
@Component({
selector: 'confirm-dialog',
templateUrl: 'confirm-dialog/confirm-dialog.html',
styleUrls: ['confirm-dialog/confirm-dialog.css']
})
export class ConfirmDialog {
constructor(
public dialogRef: MatDialogRef<ConfirmDialog>
// @Inject(MAT_DIALOG_DATA) public data: DialogData
) { }
onNoClick(): void {
this.dialogRef.close();
}
}
@Component({
selector: 'task-dialog',
templateUrl: 'task-dialog/task-dialog.html',
styleUrls: ['task-dialog/task-dialog.css'],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
],
})
export class TaskDialog {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
myControl = new FormControl()
options: any[] = [
{
name: "Person", description: "One", icon: "person"
},
{
name: "Person", description: "Two", icon: "person"
},
{
name: "Person", description: "Three", icon: "person"
}
]
filteredOptions: Observable<any[]>;
selected: any[] = []
showAuto: boolean = true
isEdit: boolean = false;
active: number = 1
constructor(
public dialogRef: MatDialogRef<AppointDialog>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.isEdit = data.isEdit;
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}
public onSelectionChange(event) {
this.selected.push(event.option.value)
this.showAuto = false
}
public clickAdd() {
console.log('click add')
this.showAuto = !this.showAuto
}
public activeClass(num) {
if (num == this.active)
return 'activeBtn'
else
return ''
}
public setActive(num) {
console.log('set active', num)
this.active = num
if (num == 1) {
this.options = [{
name: "Person", description: "One", icon: "person"
},
{
name: "Person", description: "Two", icon: "person"
}
,
{
name: "Person", description: "Three", icon: "person"
}]
} else if (num == 2) {
this.options = [{
name: "Company", description: "One", icon: "business"
},
{
name: "Company", description: "Two", icon: "business"
}
,
{
name: "Company", description: "Three", icon: "business"
}]
} else if (num == 3) {
this.options = [{
name: "Leads", description: "One", icon: "leaderboard"
},
{
name: "Leads", description: "Two", icon: "leaderboard"
}
,
{
name: "Leads", description: "Three", icon: "leaderboard"
}]
}
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
)
}
setEmpty(){
this.myControl.setValue('');
}
onNoClick(): void {
this.dialogRef.close();
}
deleteSelected(e) {
const index = this.selected.indexOf(e)
this.selected.splice(index, 1)
this.selected.length == 0 && (this.showAuto = true)
}
}
@Component({
selector: 'appoint-dialog',
templateUrl: 'appoint-dialog/appoint-dialog.html',
styleUrls: ['appoint-dialog/appoint-dialog.css'],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
],
})
export class AppointDialog {
myControl = new FormControl();
options: any[] = [
{
name: "Person", description: "One", icon: "person"
},
{
name: "Person", description: "Two", icon: "person"
},
{
name: "Person", description: "Three", icon: "person"
}
]
filteredOptions: Observable<any[]>;
selected: any[] = []
isEdit: boolean = false;
showAuto: boolean = true
active: number = 1
constructor(
public dialogRef: MatDialogRef<AppointDialog>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.isEdit = data.isEdit;
console.log(this.isEdit);
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}
public onSelectionChange(event) {
this.selected.push(event.option.value)
this.showAuto = false
}
public clickAdd() {
console.log('click add')
this.showAuto = !this.showAuto
}
public activeClass(num) {
if (num == this.active)
return 'activeBtn'
else
return ''
}
public setActive(num) {
console.log('set active', num)
this.active = num
if (num == 1) {
this.options = [{
name: "Person", description: "One", icon: "person"
},
{
name: "Person", description: "Two", icon: "person"
}
,
{
name: "Person", description: "Three", icon: "person"
}]
} else if (num == 2) {
this.options = [{
name: "Company", description: "One", icon: "business"
},
{
name: "Company", description: "Two", icon: "business"
}
,
{
name: "Company", description: "Three", icon: "business"
}]
} else if (num == 3) {
this.options = [{
name: "Leads", description: "One", icon: "leaderboard"
},
{
name: "Leads", description: "Two", icon: "leaderboard"
}
,
{
name: "Leads", description: "Three", icon: "leaderboard"
}]
}
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
setEmpty(){
this.myControl.setValue('');
}
onNoClick(): void {
this.dialogRef.close();
}
deleteSelected(e) {
const index = this.selected.indexOf(e)
this.selected.splice(index, 1)
this.selected.length == 0 && (this.showAuto = true)
}
}
@Component({
selector: 'stage-snack',
templateUrl: 'stage-snack/stage-snack.html',
styleUrls: ['stage-snack/stage-snack.css']
})
export class StageSnack {
constructor(
public snackBarRef: MatSnackBarRef<StageSnack>,
@Inject(MAT_SNACK_BAR_DATA) public data: any) { }
}
<file_sep>/src/app/services/account-api.service.ts
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { HttpClient, HttpHeaders, HttpErrorResponse, HttpParams } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AccountApiService {
baseURL = environment.baseUrl;
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private httpClient: HttpClient) {}
// Create
createAccount(data): Observable<any> {
let API_URL = `${this.baseURL + environment.register}`;
return this.httpClient.post(API_URL, data, this.httpOptions)
/*.pipe(
catchError(this.handleError)
)*/
}
//login
login(data): Observable<any> {
let API_URL = `${this.baseURL + environment.login}`;
return this.httpClient.post(API_URL, data);
}
//sendPasswordResetLink
sendPasswordResetLink(email): Observable<any> {
let API_URL = `${this.baseURL + environment.sendPasswordResetLink}`;
return this.httpClient.post(API_URL, {"email" : email});
}
resetPassword(data): Observable<any> {
let API_URL = `${this.baseURL + environment.resetPassword}`;
return this.httpClient.post(API_URL, data);
}
validateResetPasswordToken(token): Observable<any> {
let API_URL = `${this.baseURL + environment.validateResetPasswordToken}`;
let params = new HttpParams()
.set('reset_token', token);
return this.httpClient.get(API_URL, {params});
}
verifyEmail(token): Observable<any> {
let API_URL = `${this.baseURL + environment.verifyEmail}`;
let params = new HttpParams()
.set('verify_token', token);
return this.httpClient.get(API_URL, {params});
}
//me
me(){
let API_URL = `${this.baseURL + environment.me}`;
return this.httpClient.get(API_URL).toPromise();
}
//logout
logout(): Observable<any> {
let API_URL = `${this.baseURL + environment.logout}`;
return this.httpClient.get(API_URL);
}
isLoggedIn(){
if (localStorage.getItem("token") === null) {
return false;
}
return true;
}
// Handle Errors
handleError(error: HttpErrorResponse) {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
// Client-side errors
errorMessage = `Error: ${error.error.message}`;
} else {
// Server-side errors
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(errorMessage);
}
}
<file_sep>/src/app/user-registration/signup/signup.component.ts
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnDestroy, OnInit,NgZone } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AccountApiService } from '../../services/account-api.service';
import { extractErrorMessagesFromErrorResponse } from './../../services/extract-error-messages-from-error-response';
import { FormStatus } from './../../services/form-status';
import {
SocialAuthService,
GoogleLoginProvider,
FacebookLoginProvider,
SocialUser,
} from 'angularx-social-login';
//import { AuthTwitterService } from './../../services/auth-twitter.service';
import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import {
AngularFirestore,
AngularFirestoreDocument,
} from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
import { Subscription } from 'rxjs';
import { TokenService } from 'src/app/services/token.service';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css'],
})
export class SignupComponent implements OnInit, OnDestroy {
fbLoginOptions = {
scope: 'email',
return_scopes: true,
enable_profile_selector: true,
}; // https://developers.facebook.com/docs/reference/jaPvascript/FB.login/v2.11
googleLoginOptions = {
scope: 'profile email https://www.googleapis.com/auth/contacts.readonly',
}; // https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauth2clientconfig
apiResponse: any;
clicked = false;
hide = true;
socialUser: SocialUser;
isLoggedin: boolean;
sub_social_auth;
private subscriptions: Subscription[] = [];
// 1 - Initialize a form status object for the component
formStatus = new FormStatus();
constructor(
public fb: FormBuilder,
private account: AccountApiService,
private router: Router,
private token: TokenService,
private socialAuthService: SocialAuthService,
//public authTwitterService: AuthTwitterService,
public afs: AngularFirestore,
public afAuth: AngularFireAuth,
public ngZone: NgZone,
) {
const subs_valuechange = this.registrationForm.valueChanges.subscribe(
(data) => {
this.apiResponse = false;
}
);
this.subscriptions.push(subs_valuechange);
}
ngOnInit(): void {
if (this.isLoggedin) {
this.logOut();
this.TwitterSignOut();
}
}
/*##################### Google Auth #####################*/
async loginWithGoogle(): Promise<void> {
await this.socialAuthService.signIn(
GoogleLoginProvider.PROVIDER_ID,
this.googleLoginOptions
).then((user) => {
this.socialUser = user;
this.isLoggedin = user != null;
this.formStatus.onFormSubmitting();
if (this.socialUser && typeof this.socialUser.email !== 'undefined') {
let postData = {
first_name: this.socialUser.firstName,
last_name: this.socialUser.lastName,
email: this.socialUser.email,
platform: 'web',
type: this.socialUser.provider,
social_user_id: this.socialUser.id,
auth_token: this.socialUser.authToken,
profile_pic: this.socialUser.photoUrl,
};
const sub_social = this.account.createAccount(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.logOut();
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.logOut();
}
);
this.subscriptions.push(sub_social);
} else {
this.formStatus.onFormSubmitResponse({
success: false,
messages: [
"Your social media doesn't have email, so kindly signup with email.",
],
});
this.logOut();
}
})
.catch((error) => {
//window.alert(error);
console.log(error);
});
}
async loginWithFacebook(): Promise<void> {
await this.socialAuthService.signIn(
FacebookLoginProvider.PROVIDER_ID,
this.fbLoginOptions
).then((user) => {
this.socialUser = user;
this.isLoggedin = user != null;
this.formStatus.onFormSubmitting();
if (this.socialUser && typeof this.socialUser.email !== 'undefined') {
let postData = {
first_name: this.socialUser.firstName,
last_name: this.socialUser.lastName,
email: this.socialUser.email,
platform: 'web',
type: this.socialUser.provider,
social_user_id: this.socialUser.id,
auth_token: this.socialUser.authToken,
profile_pic: this.socialUser.photoUrl,
};
const sub_social = this.account.createAccount(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.logOut();
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.logOut();
}
);
this.subscriptions.push(sub_social);
} else {
this.formStatus.onFormSubmitResponse({
success: false,
messages: [
"Your social media doesn't have email, so kindly signup with email.",
],
});
this.logOut();
}
})
.catch((error) => {
//window.alert(error);
console.log(error);
});
}
// signUp With Twitter
signUpTwitter(): void {
this.AuthTwitter(new auth.TwitterAuthProvider());
}
// Auth logic to run auth providers
AuthTwitter(provider) {
this.afAuth.auth
.signInWithPopup(provider).then((result: any) => {
let user = result.additionalUserInfo.profile;
this.isLoggedin = user != null;
this.formStatus.onFormSubmitting();
if(typeof user !== 'undefined' && user.email != ""){
let postData = {
first_name: user.name,
email: user.email,
platform: 'web',
type: 'TWITTER',
social_user_id: user.id,
auth_token: result.credential.accessToken,
profile_pic: user.profile_image_url_https || '',
};
const sub_social = this.account.createAccount(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.ngZone.run(() => {
this.router.navigate(['pages/dashboard']);
});
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.TwitterSignOut();
}
);
this.subscriptions.push(sub_social);
} else {
this.formStatus.onFormSubmitResponse({
success: false,
messages: [
"Your social media doesn't have email, so kindly signup with email.",
],
});
this.TwitterSignOut();
}
})
.catch((error) => {
//window.alert(error);
console.log(error);
});
}
logOut(): void {
if (this.isLoggedin) {this.socialAuthService.signOut().then().catch(this.yourHandler);}
}
/* SignOut method for logging out from the Angular/Firebase app */
TwitterSignOut() {
if (this.isLoggedin) {this.afAuth.auth.signOut().then().catch(this.yourHandler);}
}
yourHandler(){
console.log("Social logged out");
}
/*##################### Registration Form #####################*/
registrationForm = this.fb.group({
first_name: [
'',
[
Validators.required,
Validators.minLength(2),
Validators.maxLength(255),
//Validators.pattern('^[_A-z0-9]*((-|s)*[_A-z0-9])*$'),
],
],
last_name: ['', [Validators.maxLength(255)]],
email: [
'',
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
password: [
'',
[
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,12}$'
),
],
],
company_name: ['', [Validators.maxLength(255)]],
no_of_employees: '',
platform: '',
type: '',
});
// Submit Registration Form
async onSubmit() {
if (!this.registrationForm.valid) {
//console.log(this.registrationForm.controls.first_name.errors);
return false;
} else {
// 2 - Call onFormSubmitting to handle setting the form as submitted and
// clearing the error and success messages array
this.formStatus.onFormSubmitting();
this.registrationForm.patchValue({ platform: 'web', type: 'form' });
const subs_form = await this.account
.createAccount(this.registrationForm.value)
.subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
/*if (errorResponse.error.code === 253) {
const validationErrors = { email: errorResponse.error.message };
Object.keys(validationErrors).forEach((prop) => {
const formControl = this.registrationForm.get(prop);
if (formControl) {
formControl.setErrors({
serverError: validationErrors[prop],
});
}
});
} else {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
// call onFormSubmitResponse with the submission success status (false) and the array of messages
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
}*/
}
);
this.subscriptions.push(subs_form);
}
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
//this.sub_social_auth.unsubscribe();
this.logOut();
this.TwitterSignOut();
}
}
<file_sep>/src/app/pages/settings/usersroles/usersroles.component.ts
import {
AfterViewInit,
Component,
OnInit,
ViewChild,
ChangeDetectorRef,
AfterContentChecked,
} from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
FormArray,
} from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { SnackBarService } from '../../../shared/snack-bar.service';
import { extractErrorMessagesFromErrorResponse } from '../../../services/extract-error-messages-from-error-response';
import { FormStatus } from '../../../services/form-status';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription, Observable, of as observableOf, BehaviorSubject, combineLatest, merge } from 'rxjs';
import {catchError, map, startWith, switchMap} from 'rxjs/operators';
import {MatInputModule} from '@angular/material/input';
//import { AnyARecord } from 'dns';
interface ADDPERSONROLE {
value: string;
viewValue: string;
}
/*For Role Table*/
export interface ROLE {
role: string;
accessLevel: string;
}
/*For Role Table*/
/*For User Table*/
export interface USER {
profile: string;
user: string;
role: string;
accessLevel: string;
}
/*For User Table*/
@Component({
selector: 'app-usersroles',
templateUrl: './usersroles.component.html',
styleUrls: ['./usersroles.component.css'],
})
export class UsersrolesComponent implements OnInit, AfterViewInit {
closeResult = '';
/*Browse File*/
addPersonImage: File = null;
addPersonImageUrl: string | ArrayBuffer =
'../../../assets/images/settingsProfile.png';
/*Add Person Mandatory checkbox*/
isAddPersonMand: boolean;
/*Add Person Mandatory checkbox*/
addPersonForm: FormGroup;
constructor(
private modalService: NgbModal,
private fb: FormBuilder,
private sb: SnackBarService,
private settingsApiService: SettingsApiService,
private cdref: ChangeDetectorRef
) {
//this.initaddPersonForm();
}
/*Browse file*/
addPersonImageEvent(event) {
this.addPersonImage = event.target.files[0];
}
removeAddPersonImage() {
this.addPersonImage = null;
this.addPersonImageUrl = '../../../assets/images/settingsProfile.png';
}
onChangeAddPerson(profile: File) {
if (profile) {
this.addPersonImage = profile;
const reader = new FileReader();
reader.readAsDataURL(profile);
reader.onload = (event) => {
this.addPersonImageUrl = reader.result;
};
}
}
/*Browse file*/
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
/** Users Code */
ngOnInit(): void {}
ngAfterViewInit() {
this.listUsers();
}
/**=============================================================================================================== */
// 1 - Initialize a form status object for the component
formStatus = new FormStatus();
private subscriptions: Subscription[] = [];
filterValue = "";
userData = {
role_id: 1
};
rolesList = [];
/**============ User Section ============*/
displayedColumns: string[] = ['first_name', 'name', 'access_level', 'record_status', 'Action'];
data: Observable<any[]>;
UsersList: Observable<any[]>;
updateUserId = "";
deleteUserId = "";
userConfirmationForDelete = false;
resultsLength = 0; resultsLengthRole = 0;
isLoadingResults = true;
isRateLimitReached = false;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
initaddPersonForm(data: any = []) {
if (data) {
this.updateUserId = data.id;
this.addPersonForm = this.fb.group({
first_name: [
data.first_name,
[
Validators.required,
Validators.minLength(2),
Validators.maxLength(255),
//Validators.pattern('^[_A-z0-9]*((-|s)*[_A-z0-9])*$'),
],
],
last_name: [data.last_name, [Validators.required, Validators.maxLength(255)]],
email: [
data.email,
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
mobile_code: ['+91', Validators.required],
mobile_number: [data.phone_number, [Validators.required, Validators.maxLength(32)]],
work_number: [data.work_number, [Validators.required, Validators.maxLength(32)]],
user_role_id: [data.role_id, []],
address: [data.address, []],
skype_id: [data.skype_id, []],
description: [data.description, []],
});
} else {
this.addPersonForm = this.fb.group({
first_name: [
'',
[
Validators.required,
Validators.minLength(2),
Validators.maxLength(255),
//Validators.pattern('^[_A-z0-9]*((-|s)*[_A-z0-9])*$'),
],
],
last_name: ['', [Validators.required, Validators.maxLength(255)]],
email: [
'',
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
mobile_code: ['+91', Validators.required],
mobile_number: ['', [Validators.required, Validators.maxLength(32)]],
work_number: ['', [Validators.required, Validators.maxLength(32)]],
user_role_id: [this.rolesList[0].id, []],
address: ['', []],
skype_id: ['', []],
description: ['', []],
});
}
}
/*Modal dialog*/
open(content, id="") {
this.settingsApiService.initUserForm(id).subscribe(
(res: any) => {
if (res.success) {
if (res.data.menu_previlages.create == 1) {
this.userData = res.data.user;
this.rolesList = res.data.roles;
this.initaddPersonForm(this.userData);
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(
reason
)}`;
}
);
} else {
this.triggerSnackBar(res.message, 'Close');
}
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
onSubmit() {
if (!this.addPersonForm.valid) {
return false;
} else {
// 2 - Call onFormSubmitting to handle setting the form as submitted and
// clearing the error and success messages array
this.formStatus.onFormSubmitting();
var formData: any = new FormData();
if(this.addPersonImage){
formData.append("profile_pic", this.addPersonImage, this.addPersonImage.name);
}
formData.append("address", this.addPersonForm.get('address').value);
formData.append("description", this.addPersonForm.get('description').value);
formData.append("email", this.addPersonForm.get('email').value);
formData.append("first_name", this.addPersonForm.get('first_name').value);
formData.append("last_name", this.addPersonForm.get('last_name').value);
formData.append("mobile_code", this.addPersonForm.get('mobile_code').value);
formData.append("mobile_number", this.addPersonForm.get('mobile_number').value);
formData.append("skype_id", this.addPersonForm.get('skype_id').value);
formData.append("user_role_id", this.addPersonForm.get('user_role_id').value);
formData.append("work_number", this.addPersonForm.get('work_number').value);
if(this.updateUserId){
const subs_query_param = this.settingsApiService
.updateUser(formData, this.updateUserId)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listUsers();
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
} else {
const subs_query_param = this.settingsApiService
.addUser(formData)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listUsers();
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
}
}
}
listUsers(){
this.UsersList = merge(this.sort.sortChange, this.paginator.page)
.pipe(
// startWith([undefined, ]),
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.settingsApiService.listUser(
this.sort.active, this.sort.direction, this.paginator.pageIndex, this.paginator.pageSize, this.filterValue);
}),
map(data => {
// Flip flag to show that loading has finished.
this.isLoadingResults = false;
this.isRateLimitReached = false;
this.resultsLength = data.data.recordsTotal;
return data.data.data;
}),
catchError(() => {
this.isLoadingResults = false;
// Catch if the GitHub API has reached its rate limit. Return empty data.
this.isRateLimitReached = true;
return observableOf([]);
})
);
}
resetPaging(): void {
this.paginator.pageIndex = 0;
}
closeModal(){
this.updateUserId = "";
this.deleteUserId = "";
this.modalService.dismissAll();
}
filterUsers(){
this.resetPaging();
this.listUsers();
}
changeUserStatus(enable: boolean, id){
var status = 2
if(enable){
status = 1;
}
const subs_query_changeuser = this.settingsApiService
.changeUserStatus(status, id)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_changeuser);
}
deleteModal(content, id){
this.deleteUserId = id;
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(
reason
)}`;
}
);
}
deleteUser(id){
this.settingsApiService.deleteUser(id).subscribe(
(res: any) => {
if (res.success) {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listUsers();
this.deleteUserId = "";
this.userConfirmationForDelete = false;
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
ngAfterContentChecked() {
this.cdref.detectChanges();
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
tabLoadTimes: Date[] = [];
getTimeLoaded(index: number) {
if (!this.tabLoadTimes[index]) {
this.tabLoadTimes[index] = new Date();
}
return this.tabLoadTimes[index];
}
compareFunction(o1: any, o2: any) {
return (o1 == o2);
}
}
<file_sep>/src/app/pages/settings/account/account.component.ts
import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
} from '@angular/forms';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import {
TIMEFORMATS,
TIMEZONES,
DATEFORMATS,
CURRENCYFORMATS,
PREFERENCEDATA,
} from './preference-data';
import { SnackBarService } from '../../../shared/snack-bar.service';
import { Subscription } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { extractErrorMessagesFromErrorResponse } from 'src/app/services/extract-error-messages-from-error-response';
@Component({
selector: 'app-account',
templateUrl: './account.component.html',
styleUrls: ['./account.component.css'],
})
export class AccountComponent implements OnInit, AfterViewInit {
userProfile = JSON.parse(localStorage.getItem('me'));
account_id = this.userProfile.account_id;
timeZonesData = [];
timeFormatsData= [];
dateFormatsData= [];
currencyFormatsData= [];
preferenceData = [];
accountForm: FormGroup;
private subscriptions: Subscription[] = [];
time = new Date();
intervalId;
/*For Account -- time zone select box*/
constructor(
private settingsApiService: SettingsApiService,
private sb: SnackBarService,
private fb: FormBuilder
) {
this.accountForm = new FormGroup({
time_zone: new FormControl(),
time_format: new FormControl(),
date_format: new FormControl(),
currency: new FormControl(),
});
}
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
ngOnInit(): void {
//console.log(' ChildComponent==>ngOnInit');
// Using Basic Interval
this.intervalId = setInterval(() => {
this.time = new Date();
}, 1000);
const subs_query_param_get = this.settingsApiService.preferenceMe().subscribe(
(res: any) => {
this.timeZonesData = res.data.timezones;
this.timeFormatsData = res.data.timeformats;
this.dateFormatsData = res.data.deteformats;
this.currencyFormatsData = res.data.currencies;
this.preferenceData = res.data.preference;
this.accountForm = this.fb.group({
time_zone: [this.preferenceData ? res.data.preference.timezone_id : ''],
time_format: [this.preferenceData ? res.data.preference.timeformat_id : ''],
date_format: [this.preferenceData ? res.data.preference.dateformat_id : ''],
currency: [this.preferenceData ? res.data.preference.currency_id : '']
});
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param_get);
}
ngAfterViewInit() {
//console.log('ChildComponent==>AfterViewInit');
}
ngAfterContentInit() {
//console.log(' ChildComponent==>ngAfterContentInit');
}
updatePreference() {
const data = this.accountForm.value;
const subs_query_param = this.settingsApiService
.updatePreference(data)
.subscribe((res: any) => {
this.triggerSnackBar(res.message, 'Close');
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
});
this.subscriptions.push(subs_query_param);
}
ngOnDestroy() {
clearInterval(this.intervalId);
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/app/shared/header/header.component.ts
import { TokenService } from './../../services/token.service';
import { Component, Inject, Input, OnInit } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { AccountApiService } from '../../services/account-api.service';
import { ContactApiService } from '../../services/contact-api.service';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA,
} from '@angular/material/dialog';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
FormArray,
FormGroupDirective,
} from '@angular/forms';
import { Observable, Subscription } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
} from '@angular/material/core';
import { SnackBarService } from '../../shared/snack-bar.service';
import { extractErrorMessagesFromErrorResponse } from '../../services/extract-error-messages-from-error-response';
import { FormStatus } from '../../services/form-status';
import { LeadApiService } from '../../services/lead-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import { A11yModule } from '@angular/cdk/a11y';
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
isNotification: boolean = false;
menus: any[];
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;
active: number = 1;
selectedStage: number = 3;
constructor(
private router: Router,
private account: AccountApiService,
private contactService: ContactApiService,
private token: TokenService,
public dialog: MatDialog,
private sb: SnackBarService
) {}
ngOnInit(): void {
this.menus = [
{
icon: 'menu001.png',
link: '/pages/dashboard',
},
{
icon: 'menu006.png',
link: '/pages/leads',
},
{
icon: 'menu002.png',
link: '/pages/contact',
},
{
icon: 'menu003.png',
link: '/pages/company',
},
{
icon: 'menu004.png',
link: '/pages/task',
},
{
icon: 'menu005.png',
link: '/pages/appointments',
},
];
}
showNotification() {
this.isNotification = !this.isNotification;
}
public activeClass(num) {
if (num == this.active) return 'activeBtn';
else return '';
}
public setActive(num) {
console.log('set active', num);
this.active = num;
if (num == 1) {
this.options = ['One', 'Two', 'Three'];
} else if (num == 2) {
this.options = ['Four', 'Five', 'Six'];
} else if (num == 3) {
this.options = ['Seven', 'Eight', 'Nine'];
}
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map((value) => this._filter(value))
);
}
onSelectionChange(event) {}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(
(option) => option.toLowerCase().indexOf(filterValue) === 0
);
}
logout() {
this.account.logout().subscribe(
(response) => {
console.log(response);
this.token.remove();
//this.router.navigate(['login']);
let objToSend: NavigationExtras = {
queryParams: {
success: response.success,
message: response.message,
},
};
this.router.navigate(['login'], {
state: objToSend,
});
//this.router.navigate(['login'], {queryParams: { logout: 'true' } });
},
(err) => {
console.log(err);
if (err.error.code == 113) {
this.token.remove();
let objToSend: NavigationExtras = {
queryParams: {
success: true,
message: 'Logged out successfully!',
},
};
this.router.navigate(['login'], {
state: objToSend,
});
//this.router.navigate(['login'], {queryParams: { logout: 'true' } });
}
}
);
}
clickLead() {
const dialogRef = this.dialog.open(LeadDialog, {
width: '560px',
autoFocus: false,
});
dialogRef.afterClosed().subscribe((result) => {});
}
clickContact() {
const openCreateContactDialog = () => {
const dialogRef = this.dialog.open(ContactDialog, {
width: '531px',
autoFocus: false,
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.sb.openSnackBarBottomCenter(result, 'Close');
}
})
}
if (this.contactService.contactData) {
openCreateContactDialog()
return
}
this.contactService.getContacts().subscribe((res: any) => {
console.log('contacts', res);
if (!res.success) {
this.sb.openSnackBarBottomCenter(res.message, 'Close')
return
}
if (res.data.menu_previlages.create !== 1) {
this.sb.openSnackBarBottomCenter("You don't have permission", 'Close')
return
}
this.contactService.contactData = res.data
openCreateContactDialog()
})
}
clickCompany() {
const openCreateCompanyDialog = () => {
const dialogRef = this.dialog.open(CompanyDialog, {
width: '560px',
autoFocus: false,
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.sb.openSnackBarBottomCenter(result, 'Close')
}
})
}
if (this.contactService.companyData) {
openCreateCompanyDialog();
return
}
this.contactService.getCompanies().subscribe((res: any) => {
if (!res.success) {
this.sb.openSnackBarBottomCenter(res.message, 'Close')
return
}
if (res.data.menu_previlages.create !== 1) {
this.sb.openSnackBarBottomCenter("You don't have permission", 'Close')
return
}
this.contactService.companyData = res.data
openCreateCompanyDialog()
})
}
}
export const MY_DATE_FORMATS = {
parse: {
dateInput: 'MM/DD/YYYY',
},
display: {
dateInput: 'MM/DD/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'lead-dialog',
templateUrl: 'lead-dialog/lead-dialog.html',
styleUrls: ['lead-dialog/lead-dialog.css'],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }, //MAT_MOMENT_DATE_FORMATS
],
})
export class LeadDialog {
searchControl = new FormControl();
options: string[] = [
'<NAME>',
'Primary Contact',
'Value',
'Company',
'Owner',
'Source',
'Secondary Contact',
'Added On',
'Estimate Close Date',
'Pipeline Category',
'Stage',
'Description',
];
filteredOptions: Observable<string[]>;
showMandatory: boolean = false;
search: string = '';
stages: any[] = [];
selectedStage = 0;
isEdit: boolean = false;
@Input() addLeadForm: FormGroup;
formStatus = new FormStatus();
pipelines: any[] = [];
currency: any[] = [];
organizations: any[] = [];
sources: any[] = [];
contacts: any[] = [];
owners: any[] = [];
formLoaded = false;
selectedContacts: any[];
userProfile = JSON.parse(localStorage.getItem('me'));
private subscriptions: Subscription[] = [];
constructor(
public dialogRef: MatDialogRef<LeadDialog>,
@Inject(MAT_DIALOG_DATA) public data: any,
private sb: SnackBarService,
private LeadApiService: LeadApiService,
private fb: FormBuilder
) {
this.isEdit = this.data?.isEdit;
this.filteredOptions = this.searchControl.valueChanges.pipe(
startWith(''),
map((value) => this._filter(value))
);
//this.sb.openSnackBarBottomCenter("Test", '');
}
ngOnInit() {
this.LeadApiService.initLeadForm().subscribe(
(res: any) => {
console.log('Lead Init form');
console.log(res);
if (res.success) {
this.formLoaded = true;
this.pipelines = res.data.pipelines;
this.currency = res.data.currency;
this.organizations = res.data.organizations;
this.sources = res.data.sources;
this.contacts = res.data.contacts;
this.owners = res.data.owner;
//this.currencypostvalue.id = res.data.currency.id;
if (res.data.lead) {
this.initaddLeadForm(res.data.lead);
} else {
this.initaddLeadForm();
}
this.addLeadForm.get('currency.id').patchValue(res.data.currency.id);
this.sb.openSnackBarBottomCenter(res.message, 'Close');
} else {
this.sb.openSnackBarBottomCenter(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.sb.openSnackBarBottomCenter(messages.toString(), 'Close');
}
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter((option) =>
option.toLowerCase().includes(filterValue)
);
}
onNoClick(): void {
this.dialogRef.close();
}
checkMandatory(e) {
this.showMandatory = e.checked;
}
checkShow(name) {
if (!this.search) return true;
if (name.toUpperCase().search(this.search.toUpperCase()) == -1)
return false;
else return true;
}
getLeftOffset(index) {
return -8 * index;
}
getStageSrc(index) {
if (index == 0) {
if (this.selectedStage == 0) {
return '../../../../assets/images/stage/start-active-stage-md.svg';
} else {
return '../../../../assets/images/stage/start-stage-md.svg';
}
}
if (index == this.selectedStage) {
return '../../../../assets/images/stage/active-stage-md.svg';
}
return '../../../../assets/images/stage/mid-stage-md.svg';
}
initaddLeadForm(data: any = []) {
//alert("Form Init");
if (data.length > 0) {
this.addLeadForm = this.fb.group({
name: [
data.name,
[
Validators.required,
Validators.minLength(1),
Validators.maxLength(100),
],
],
organization_id: [data.organization_id, [Validators.required]],
owner_id: [data.owner_id, [Validators.required]],
pipeline_id: [data.pipeline_id, []],
stage_id: [data.stage_id, []],
currency: this.fb.group({
id: ['', [Validators.required]],
value: ['', [Validators.required]],
}),
source_id: [data.source_id, []],
added_on: [data.added_on, [Validators.required]],
closed_on: [data.closed_on, [Validators.required]],
description: [data.description, []],
contacts: [null, [Validators.required]],
});
let assignedContacts = [];
data.contacts.forEach((contact) => {
assignedContacts.push(contact.id);
});
this.addLeadForm.controls.contacts.setValue(assignedContacts);
} else {
this.addLeadForm = this.fb.group({
name: [
'',
[
Validators.required,
Validators.minLength(1),
Validators.maxLength(100),
],
],
organization_id: ['', [Validators.required]],
owner_id: [this.userProfile.id, [Validators.required]],
pipeline_id: ['', []],
stage_id: ['', []],
currency: this.fb.group({
id: ['', [Validators.required]],
value: ['', [Validators.required]],
}),
source_id: ['', []],
added_on: ['', [Validators.required]],
closed_on: ['', [Validators.required]],
description: ['', Validators.maxLength(100)],
contacts: [null, [Validators.required]],
});
}
}
saveLead() {
if (!this.addLeadForm.valid) {
return false;
} else {
// 2 - Call onFormSubmitting to handle setting the form as submitted and
// clearing the error and success messages array
this.formStatus.onFormSubmitting();
//console.log(this.selectedContacts.value);
this.addLeadForm.patchValue({
//contacts: this.selectedContacts.value,
stage_id: this.selectedStage,
// formControlName2: myValue2
});
console.log('submitting');
//console.log(this.selectedContacts.value);
//console.log(this.selectedStage);
console.log(this.addLeadForm.value);
const subs_form = this.LeadApiService
.addLead(this.addLeadForm.value)
.subscribe((response) => {
this.dialogRef.close();
this.sb.openSnackBarBottomCenter(response.message, 'Close');
},
(errorResponse: HttpErrorResponse) => {
if (errorResponse.error.code === 252) {
const validationErrors = {};
Object.keys(validationErrors).forEach((prop) => {
const formControl = this.addLeadForm.get(prop);
if (formControl) {
formControl.setErrors({
serverError: validationErrors[prop],
});
}
});
} else {
const messages =
extractErrorMessagesFromErrorResponse(errorResponse);
// call onFormSubmitResponse with the submission success status (false) and the array of messages
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.sb.openSnackBarBottomCenter(messages.toString(), 'Close');
}
}
);
this.subscriptions.push(subs_form);
}
}
onPipelineChange(ob) {
let selectedPipeline = ob.value;
console.log(selectedPipeline);
var result = this.pipelines.find((obj) => {
return obj.id === selectedPipeline;
});
this.stages = result.stages;
this.selectedStage = result.stages[0].id;
}
onContactChange(selected) {
this.selectedContacts = selected;
this.addLeadForm.controls.contacts.setValue(this.selectedContacts);
}
compareFunction(o1: any, o2: any) {
return o1 == o2;
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
//this.sub_social_auth.unsubscribe();
}
}
@Component({
selector: 'contact-dialog',
templateUrl: 'contact-dialog/contact-dialog.html',
styleUrls: ['contact-dialog/contact-dialog.css'],
})
export class ContactDialog {
searchControl = new FormControl();
options: string[] = [
'First Name',
'<NAME>',
'Mobile Number',
'Work Number',
'Company Name',
'Email Address',
'Contact Type',
'Contact Group',
'Address',
'Skype ID',
'Description',
];
filteredOptions: Observable<string[]>;
form: FormGroup;
showMandatory: boolean = false;
search: string = '';
mobileCode = 'USA';
userHover: boolean = false;
imageHover: boolean = false;
imageSrc: string;
isEdit: boolean = false;
countries = [];
companyList = [];
emailOwners = [];
dialCodes = [];
errors = null
constructor(
private contactService: ContactApiService,
private sb: SnackBarService,
public fb: FormBuilder,
public dialogRef: MatDialogRef<ContactDialog>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.isEdit = this.data?.isEdit;
this.countries = this.contactService.getCountries()
this.emailOwners = this.contactService.getEmailOwners()
this.dialCodes = this.contactService.getDialCodes()
this.companyList = this.contactService.getContactCompanyList()
this.filteredOptions = this.searchControl.valueChanges.pipe(
startWith(''),
map((value) => this._filter(value))
);
this.reactiveForm()
}
reactiveForm() {
this.form = this.fb.group({
first_name: ['Loneyn', [Validators.required]],
last_name: ['Messoal', [Validators.required]],
mobile_code: ['', [Validators.required]],
mobile_number: [
'3334411298',
[
Validators.required,
Validators.minLength(10),
Validators.maxLength(10),
Validators.pattern('^[0-9]*$'),
],
],
work_phone: [
'',
[
Validators.minLength(10),
Validators.maxLength(10),
Validators.pattern('^[0-9]*$'),
],
],
email: ['<EMAIL>', [Validators.required, Validators.email]],
owner_id: ['', [Validators.required]],
organization: [''],
address: [''],
skype_id: [''],
description: [''],
});
}
hasValidationError(key) {
return this.form.controls[key].invalid && this.form.controls[key].errors;
}
getValidationMessage(key) {
const control = this.form.controls[key];
if (control.hasError('required')) return 'This field is required';
if (control.hasError('email')) return 'Please enter a valid email address';
if (control.hasError('pattern')) {
if (control.errors.pattern.requiredPattern == '^[0-9]*$')
return 'Please input numbers only';
}
if (control.hasError('minlength'))
return `The minimum length is ${control.errors.minlength.requiredLength}.`;
if (control.hasError('maxlength'))
return `The minimum length is ${control.errors.maxlength.requiredLength}.`;
return '';
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter((option) =>
option.toLowerCase().includes(filterValue)
);
}
onNoClick(): void {
this.dialogRef.close();
}
submitForm(): void {
console.log('contact.submit', this.form.value, 'Image:', this.imageSrc);
if (!this.form.valid) {
return;
}
const post_data = {
...this.form.value,
mobile: {
code: this.form.value.mobile_code,
number: this.form.value.mobile_number,
},
};
/*if (this.imageSrc) {
post_data['profile_pic'] = this.imageSrc
}*/
this.contactService.createContact(post_data).subscribe(
(res: any) => {
console.log('contact created', res);
if (res.success) {
this.dialogRef.close(res.message);
this.contactService.notify();
} else {
this.sb.openSnackBarBottomCenter(res.message, 'Close');
}
},
(err) => {
this.errors = {};
const data = err.error.data;
for (const key in data) {
if (Array.isArray(data[key])) this.errors[key] = data[key][0];
else this.errors[key] = data[key];
}
console.log('this.errors', this.errors);
const messages = Object.values(this.errors).join('\r\n');
console.log(messages);
this.sb.openSnackBarTopCenterAsDuration(messages, 'Close', 4000);
}
);
}
checkMandatory(e) {
this.showMandatory = e.checked;
}
checkShow(name) {
if (!this.search) return true;
if (name.toUpperCase().search(this.search.toUpperCase()) == -1)
return false;
else return true;
}
getUserIcon() {
if (!this.userHover) return 'account_circle';
return 'add';
}
userIcon() {
let element: HTMLElement = document.getElementById(
'fileInput'
) as HTMLElement;
element.click();
this.imageHover = false;
}
readURL(event: HTMLInputEvent): void {
console.log('readURL', event.target)
if (event.target.files && event.target.files[0]) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => (this.imageSrc = reader.result as string);
reader.readAsDataURL(file);
}
this.imageHover = false;
}
removeImage() {
this.imageSrc = '';
}
showOverlay() {
return this.imageHover;
}
}
@Component({
selector: 'company-dialog',
templateUrl: 'company-dialog/company-dialog.html',
styleUrls: ['company-dialog/company-dialog.css'],
})
export class CompanyDialog {
searchControl = new FormControl();
options: string[] = [
'Company Name',
'Mobile Number',
'Work Number',
'Address',
'City',
'Post Code',
'State/Region',
'Country',
'Email Address',
'Owner',
'Skype ID',
'Description',
];
filteredOptions: Observable<string[]>;
form: FormGroup;
showMandatory: boolean = false;
search: string = '';
addressSelect = false;
isEdit: boolean = false;
countries = [];
emailOwners = [];
dialCodes = []
errors = null
constructor(
private contactService: ContactApiService,
private sb: SnackBarService,
public fb: FormBuilder,
public dialogRef: MatDialogRef<CompanyDialog>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
this.isEdit = this.data?.isEdit;
this.countries = this.contactService.getCountries()
this.emailOwners = this.contactService.getEmailOwners()
this.dialCodes = this.contactService.getDialCodes()
this.filteredOptions = this.searchControl.valueChanges.pipe(
startWith(''),
map((value) => this._filter(value))
);
this.reactiveForm();
}
reactiveForm() {
this.form = this.fb.group({
organization_name: ['', [Validators.required]],
mobile_code: ['', [Validators.required]],
mobile_number: [
'',
[
Validators.required,
Validators.minLength(10),
Validators.maxLength(10),
Validators.pattern('^[0-9]*$'),
],
],
work_phone: [
'',
[
Validators.minLength(10),
Validators.maxLength(10),
Validators.pattern('^[0-9]*$'),
],
],
email: ['', [Validators.required, Validators.email]],
address: [''],
city: [''],
postal_code: [''],
state: [''],
country: [''],
owner_id: ['', [Validators.required]],
skype_id: [''],
description: [''],
});
}
hasValidationError(key) {
return this.form.controls[key].invalid && this.form.controls[key].errors;
}
getValidationMessage(key) {
const control = this.form.controls[key];
if (control.hasError('required')) return 'This field is required';
if (control.hasError('email')) return 'Please enter a valid email address';
if (control.hasError('pattern')) {
if (control.errors.pattern.requiredPattern == '^[0-9]*$')
return 'Please input numbers only';
}
if (control.hasError('minlength'))
return `The minimum length is ${control.errors.minlength.requiredLength}.`;
if (control.hasError('maxlength'))
return `The minimum length is ${control.errors.maxlength.requiredLength}.`;
return '';
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter((option) =>
option.toLowerCase().includes(filterValue)
);
}
onNoClick(): void {
this.dialogRef.close();
}
submitForm(): void {
console.log(this.form.value);
if (!this.form.valid) {
return;
}
const post_data = {
...this.form.value,
mobile: {
code: this.form.value.mobile_code,
number: this.form.value.mobile_number,
},
};
this.contactService.createCompany(post_data).subscribe(
(res: any) => {
console.log('company created', res);
if (res.success) {
this.dialogRef.close(res.message);
this.contactService.notify();
} else {
this.sb.openSnackBarBottomCenter(res.message, 'Close');
}
},
(err) => {
this.errors = {};
const data = err.error.data;
for (const key in data) {
if (Array.isArray(data[key])) this.errors[key] = data[key][0];
else this.errors[key] = data[key];
}
console.log('this.errors', this.errors);
const messages = Object.values(this.errors).join('\r\n');
console.log(messages);
this.sb.openSnackBarTopCenterAsDuration(messages, 'Close', 4000);
}
);
}
checkMandatory(e) {
this.showMandatory = e.checked;
}
checkShow(name) {
if (!this.search) return true;
if (name.toUpperCase().search(this.search.toUpperCase()) == -1)
return false;
else return true;
}
}
<file_sep>/src/app/pages/settings/data/data.component.ts
import { Component, OnInit } from '@angular/core';
import {MatTableDataSource} from '@angular/material/table';
/*For import history Table*/
export interface IMPORTHISTORY{
importName: string;
importType: string;
importDate: any;
}
/*For import history Table*/
@Component({
selector: 'app-data',
templateUrl: './data.component.html',
styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
/*For Import History Table*/
displayedImportColumns: any[] = ['importName' , 'importType' , 'importDate'];
dataSourceImport: MatTableDataSource<IMPORTHISTORY>;
importHistory: IMPORTHISTORY[];
/*For Import History Table*/
constructor() { }
//Drag and drop file upload
files: any[] = [];
/**
* on file drop handler
*/
onFileDropped($event) {
this.prepareFilesList($event);
}
/**
* handle file from browsing
*/
fileBrowseHandler(files) {
this.prepareFilesList(files);
}
/**
* Delete file from files list
* @param index (File index)
*/
deleteFile(index: number) {
this.files.splice(index, 1);
}
/**
* Simulate the upload process
*/
uploadFilesSimulator(index: number) {
setTimeout(() => {
if (index === this.files.length) {
return;
} else {
const progressInterval = setInterval(() => {
if (this.files[index].progress === 100) {
clearInterval(progressInterval);
this.uploadFilesSimulator(index + 1);
} else {
this.files[index].progress += 5;
}
}, 200);
}
}, 1000);
}
/**
* Convert Files list to normal array list
* @param files (Files List)
*/
prepareFilesList(files: Array<any>) {
for (const item of files) {
item.progress = 0;
this.files.push(item);
}
this.uploadFilesSimulator(0);
}
/**
* format bytes
* @param bytes (File size in bytes)
* @param decimals (Decimals point)
*/
formatBytes(bytes, decimals) {
if (bytes === 0) {
return '0 Bytes';
}
const k = 1024;
const dm = decimals <= 0 ? 0 : decimals || 2;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//Drag and drop file upload
ngOnInit(): void {
this.importHistory = [
{
importName: '<NAME>',
importType: 'google contacts',
importDate: '23/04/2020'
},
{
importName: '<NAME>',
importType: 'CSV upload',
importDate: '24/04/2020'
}
];
this.dataSourceImport = new MatTableDataSource(this.importHistory)
}
}
<file_sep>/src/app/pages/company-detail/company-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {MatDialog} from '@angular/material/dialog';
import { AppointDialog, TaskDialog } from '../detail/detail.component';
import { CompanyDialog } from 'src/app/shared/header/header.component';
import {SnackBarService} from 'src/app/shared/snack-bar.service'
@Component({
selector: 'app-company-detail',
templateUrl: './company-detail.component.html',
styleUrls: ['./company-detail.component.css']
})
export class CompanyDetailComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
status = "active"
// selectedDisplay = "all"
constructor(private router: Router , public dialog: MatDialog) { }
ngOnInit(): void {
}
goToList() {
this.router.navigate(['/pages/company']);
}
openTaskDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(TaskDialog, {
width: '405px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
openAppointDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(AppointDialog, {
width: '740px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
editCompany() {
const dialogRef = this.dialog.open(CompanyDialog, {
width: '560px',
autoFocus: false,
data : { isEdit : true}
})
dialogRef.afterClosed().subscribe(result => {
})
}
}
<file_sep>/src/app/user-registration/forgot-password/reset-email/reset-email.component.ts
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { AccountApiService } from 'src/app/services/account-api.service';
@Component({
selector: 'app-reset-email',
templateUrl: './reset-email.component.html',
styleUrls: ['./reset-email.component.css']
})
export class ResetEmailComponent implements OnInit {
formDisplay = 'formHide';
timerFinished = false;
clicked = false;
apiResponse: any;
private subscriptions: Subscription[] = [];
constructor(
public formBuilder: FormBuilder,
private account: AccountApiService,
private router: Router
) {
const subs_value_change = this.resetPasswordForm.valueChanges.subscribe((data) => {
this.apiResponse = false;
});
this.subscriptions.push(subs_value_change);
}
resetPasswordForm = this.formBuilder.group({
email: [
'',
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
});
ngOnInit(): void {
this.apiResponse = {"success": true};
}
onTimerFinished(e:Event){
if (e["action"] == "done"){
this.formDisplay = 'formShow';
this.timerFinished = true;
}
}
// Submit Registration Form
onSubmit() {
if (!this.resetPasswordForm.valid) {
return false;
} else {
this.clicked = true;
const subs_send_password_link = this.account.sendPasswordResetLink(this.resetPasswordForm.controls['email'].value).subscribe(
(response) => {
this.clicked = false;
this.apiResponse = response;
//this.router.navigate(['/user/forgot-password/reset-email']);
this.formDisplay = 'formHide';
this.timerFinished = false;
},
(err) => {
this.clicked = false;
if (err.error.code === 254) {
const formControl = this.resetPasswordForm.get('email');
if (formControl) {
formControl.setErrors({
serverError: err.error.message,
});
}
} else {
this.apiResponse = err.error;
}
}
);
this.subscriptions.push(subs_send_password_link);
}
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/app/pages/settings/profile/profile.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
} from '@angular/forms';
import { SnackBarService } from '../../../shared/snack-bar.service';
import { AccountApiService } from 'src/app/services/account-api.service';
import { TokenService } from 'src/app/services/token.service';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import { UserProfile } from './user-profile';
import { Subscription } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { Router, NavigationExtras } from '@angular/router';
import { extractErrorMessagesFromErrorResponse } from 'src/app/services/extract-error-messages-from-error-response';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css'],
})
export class ProfileComponent implements OnInit, OnDestroy {
/*Browse File*/
private subscriptions: Subscription[] = [];
profile: File = null;
userData: UserProfile;
imageUrl: string | ArrayBuffer = '../../../assets/images/settingsProfile.png';
/*Browse File*/
changePasswordForm: FormGroup;
createChangePasswordForm() {
this.changePasswordForm = this.fb.group({
old_password: ['', Validators.required],
password: ['', Validators.required],
password_confirmation: ['', Validators.required],
});
}
closeResult = '';
profileForm: FormGroup;
account_id: string;
// constructor starts
constructor(
private modalService: NgbModal,
private fb: FormBuilder,
private sb: SnackBarService,
private settingsApiService: SettingsApiService,
private account: AccountApiService,
private token: TokenService,
private router: Router,
) {
// this.changePassword();
}
// constructor ends
//defining method for display of SnackBar
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
/*Modal dialog*/
open(content) {
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
/*Modal dialog*/
profilePicture(event) {
this.profile = event.target.files[0];
}
removeProfilePicture() {
this.settingsApiService.removeProfilePic().subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.profile = null;
this.imageUrl = '../../../assets/images/settingsProfile.png';
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
onChangeProfile(profile: File) {
if (profile) {
this.profile = profile;
const reader = new FileReader();
reader.readAsDataURL(profile);
reader.onload = (event) => {
this.imageUrl = reader.result;
};
this.settingsApiService.changeProfilePic(this.profile).subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.imageUrl = res.data.profile_image_url;
},
(errorResponse: HttpErrorResponse) => {
this.profile = null;
this.imageUrl = '../../../assets/images/settingsProfile.png';
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
}
ngOnInit(): void {
const subs_query_param_get = this.settingsApiService
.accountMe()
.subscribe((res: any) => {
this.userData = res.data;
this.account_id = res.data.account_id;
if(res.success){
this.imageUrl = res.data.profile_pic;
}
});
this.subscriptions.push(subs_query_param_get);
}
createProfileForm() {
this.profileForm = this.fb.group({
email: [
this.userData.email,
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
first_name: [this.userData.first_name, [Validators.required]],
last_name: [this.userData.last_name, [Validators.required]],
});
this.profileForm.controls.email.disable();
}
updateProfile() {
const data = this.profileForm.value;
const subs_query_param = this.settingsApiService
.updateProfile(data)
.subscribe((res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.userData.first_name = data.first_name;
this.userData.last_name = data.last_name;
this.modalService.dismissAll();
});
this.subscriptions.push(subs_query_param);
}
updateChangePassword() {
const data = this.changePasswordForm.value;
this.settingsApiService.changePassword(data).subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.logout();
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
logout() {
this.account.logout().subscribe(
(response) => {
this.token.remove();
//this.router.navigate(['login']);
let objToSend: NavigationExtras = {
queryParams: {
success: response.success,
message: response.message,
},
};
this.router.navigate(['login'], {
state: objToSend,
});
//this.router.navigate(['login'], {queryParams: { logout: 'true' } });
},
(err) => {
if (err.error.code == 113) {
this.token.remove();
let objToSend: NavigationExtras = {
queryParams: {
success: true,
message: 'Password Changed successfully!',
},
};
this.router.navigate(['login'], {
state: objToSend,
});
//this.router.navigate(['login'], {queryParams: { logout: 'true' } });
}
}
);
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
envName: 'prod',
baseUrl: 'http://apimikontact.cullsy.com/api/',
/** API Methods */
register: 'account/register',
login: 'account/login',
me: 'account/me',
sendPasswordResetLink: 'account/sendPasswordResetLink',
resetPassword: '<PASSWORD>',
validateResetPasswordToken: 'account/validateResetPasswordToken',
logout: 'account/logout',
};
<file_sep>/src/app/pages/settings/usersroles/roles/roles.component.ts
import {
AfterViewInit,
Component,
OnInit,
ViewChild,
ChangeDetectorRef,
AfterContentChecked,
} from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
FormArray,
} from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { SnackBarService } from '../../../../shared/snack-bar.service';
import { extractErrorMessagesFromErrorResponse } from '../../../../services/extract-error-messages-from-error-response';
import { FormStatus } from '../../../../services/form-status';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import {
Subscription,
Observable,
of as observableOf,
BehaviorSubject,
combineLatest,
merge,
} from 'rxjs';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
@Component({
selector: 'app-roles',
templateUrl: './roles.component.html',
styleUrls: ['./roles.component.scss'],
})
export class RolesComponent implements OnInit {
constructor(
private modalService: NgbModal,
private fb: FormBuilder,
private sb: SnackBarService,
private settingsApiService: SettingsApiService,
private cdref: ChangeDetectorRef
) {
this.initaddRoleForm();
}
ngOnInit() {}
ngAfterViewInit() {
this.listRoles();
}
/**==================================== Roles Section ====================================*/
displayedColumnsRoles: string[] = ['name', 'description', 'status', 'Action'];
Permissions = [];
closeResult = '';
newRoleForm;
LoopingVar = [];
RolesList: Observable<any[]>;
formStatus = new FormStatus();
private subscriptions: Subscription[] = [];
filterValue = '';
updateRoleId = '';
deleteRoleId = '';
roleConfirmationForDelete = false;
resultsLengthRole = 0;
isLoadingResults = true;
isRateLimitReached = false;
@ViewChild(MatPaginator) paginatorRoleList: MatPaginator;
@ViewChild(MatSort) sortRoleList: MatSort;
initaddRoleForm(data: any = []) {
if (data) {
this.updateRoleId = data.id;
this.newRoleForm = this.fb.group({
role_name: [data.name, Validators.required],
role_description: [data.description],
menus: this.fb.array([]),
});
} else {
this.newRoleForm = this.fb.group({
role_name: ['', Validators.required],
role_description: '',
menus: this.fb.array([]),
});
}
}
private addmenu() {
var self = this;
var formControlKey = -1;
this.Permissions.forEach(function (value, key) {
var temparr = [];
formControlKey++;
var obj = {
menu_id: value.id,
permission_create: value.user_has_permission_create,
permission_edit: value.user_has_permission_edit,
permission_view: value.user_has_permission_view,
permission_delete: value.user_has_permission_delete,
title: value.title,
parent_id: value.parent_id,
user_has_menu: value.user_has_menu,
index: key,
index_child: '',
formControlKey: formControlKey,
};
self.newRoleForm.controls.menus.push(self.addMenuFormGroup(obj));
temparr.push(obj);
if (value.child_menus.length > 0) {
value.child_menus.forEach(function (child_value, child_key) {
formControlKey++;
var obj = {
menu_id: child_value.id,
permission_create: child_value.user_has_permission_create,
permission_edit: child_value.user_has_permission_edit,
permission_view: child_value.user_has_permission_view,
permission_delete: child_value.user_has_permission_delete,
title: child_value.title,
parent_id: child_value.parent_id,
user_has_menu: child_value.user_has_menu,
index: key,
index_child: child_key,
formControlKey: formControlKey,
};
self.newRoleForm.controls.menus.push(self.addMenuFormGroup(obj));
temparr.push(obj);
});
}
self.LoopingVar[key] = temparr;
});
//this.Permissions.forEach((menu) => this.newRoleForm.controls.menus.push(this.addMenuFormGroup(menu)));
}
addMenuFormGroup(data: any = []): FormGroup {
if (data) {
return this.fb.group({
menu_id: [data.menu_id],
permission_create: [data.permission_create],
permission_edit: [data.permission_edit],
permission_view: [data.permission_view],
permission_delete: [data.permission_delete],
title: [data.title],
parent_id: [data.parent_id],
user_has_menu: [data.user_has_menu],
//index: [data.index],
//index_child: [data.index_child],
formControlKey: [data.formControlKey],
});
}
}
openNewRole(content, id = '') {
this.settingsApiService.initRoleForm(id).subscribe(
(res: any) => {
if (res.success) {
if (res.data.menu_previlages.create == 1) {
this.Permissions = res.data.menus;
this.initaddRoleForm(res.data.role);
this.addmenu();
this.modalService
.open(content, { ariaLabelledBy: 'dialog001', size: 'xl' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(
reason
)}`;
}
);
} else {
this.triggerSnackBar(res.message, 'Close');
}
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
onSubmitRoleForm() {
if (!this.newRoleForm.valid) {
return false;
} else {
// 2 - Call onFormSubmitting to handle setting the form as submitted and
// clearing the error and success messages array
this.formStatus.onFormSubmitting();
if (this.updateRoleId) {
const subs_query_param = this.settingsApiService
.updateRole(this.newRoleForm.value, this.updateRoleId)
.subscribe(
(res: any) => {
this.updateRoleId = '';
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listRoles();
},
(errorResponse: HttpErrorResponse) => {
const messages =
extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
} else {
const subs_query_param = this.settingsApiService
.addRole(this.newRoleForm.value)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listRoles();
},
(errorResponse: HttpErrorResponse) => {
const messages =
extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
}
}
}
changeRoleStatus(enable: boolean, id) {
var status = 2;
if (enable) {
status = 1;
}
const subs_query_changeuser = this.settingsApiService
.changeRoleStatus(status, id)
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_changeuser);
}
listRoles() {
this.RolesList = merge(
this.sortRoleList.sortChange,
this.paginatorRoleList.page
).pipe(
// startWith([undefined, ]),
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.settingsApiService.listRoles(
this.sortRoleList.active,
this.sortRoleList.direction,
this.paginatorRoleList.pageIndex,
this.paginatorRoleList.pageSize,
this.filterValue
);
}),
map((data) => {
// Flip flag to show that loading has finished.
this.isLoadingResults = false;
this.isRateLimitReached = false;
this.resultsLengthRole = data.data.recordsTotal;
return data.data.data;
}),
catchError(() => {
this.isLoadingResults = false;
// Catch if the GitHub API has reached its rate limit. Return empty data.
this.isRateLimitReached = true;
return observableOf([]);
})
);
}
deleteModal(content, id) {
this.deleteRoleId = id;
this.modalService
.open(content, { ariaLabelledBy: 'dialog001' })
.result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeModal();
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
}
);
}
deleteRole(id) {
this.settingsApiService.deleteRole(id).subscribe(
(res: any) => {
if (res.success) {
this.triggerSnackBar(res.message, 'Close');
this.modalService.dismissAll();
this.listRoles();
this.deleteRoleId = '';
this.roleConfirmationForDelete = false;
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
closeModal() {
this.updateRoleId = '';
this.deleteRoleId = '';
this.modalService.dismissAll();
}
resetPagingRole(): void {
this.paginatorRoleList.pageIndex = 0;
}
filterRoles() {
this.resetPagingRole();
this.listRoles();
}
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
ngAfterContentChecked() {
this.cdref.detectChanges();
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
selectAllMenus(index, obj) {
var stat = 0;
if (obj.user_has_menu) {
stat = 1;
}
this.LoopingVar[index].map((r) => {
r.user_has_menu = obj.user_has_menu;
});
}
SelectMenu(parent, child, obj) {
if (!obj.user_has_menu) {
this.LoopingVar[parent][0].user_has_menu = false;
this.LoopingVar[parent][child].permission_view = 0;
this.LoopingVar[parent][child].permission_create = 0;
this.LoopingVar[parent][child].permission_edit = 0;
} else if (
this.LoopingVar[parent].length - 1 ===
this.LoopingVar[parent].filter((r) => {
return r.user_has_menu === true;
}).length
) {
this.LoopingVar[parent][0].user_has_menu = true;
}
}
selectAllPermission(permission, index, obj) {
var stat = 0;
if (obj[permission]) {
stat = 1;
}
this.LoopingVar[index].map((r) => {
r[permission] = stat;
});
}
SelectPermission(permission, parent, child, obj) {
if (!obj[permission]) {
this.LoopingVar[parent][0][permission] = 0;
obj[permission] = 0;
} else {
obj[permission] = 1;
if (
this.LoopingVar[parent].length - 1 ===
this.LoopingVar[parent].filter((r) => {
return r[permission] === 1;
}).length
) {
//length matched
this.LoopingVar[parent][0][permission] = 1;
}
}
}
}
<file_sep>/src/app/pages/contact/contact-table/contact-table.component.ts
import { Component, OnInit, Input, AfterViewInit, ViewChild, EventEmitter, Output } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { DateService } from '../../../service/date.service';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
export interface item {
name: string;
owner: string;
contactCount: number;
email: string;
companyName: string;
company: boolean;
last: Date;
}
@Component({
selector: 'app-contact-table',
templateUrl: './contact-table.component.html',
styleUrls: ['./contact-table.component.css']
})
export class ContactTableComponent implements AfterViewInit {
@Input() length
@Input() pageSize
@Input() propItems
@Input() selectedItems
@Output() pagination = new EventEmitter();
displayedColumns: string[] = ['contact', 'company', 'last', 'since', 'city', 'added', 'status', 'phone'];
dataSource
selectedTh: string = ''
items = []
page = null
constructor(private dateService: DateService, private router: Router) {
}
@ViewChild(MatSort, { static: false }) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
ngAfterViewInit(): void {
}
ngOnChanges() {
console.log('ngOnChanges', this.length, this.propItems)
this.items = [...this.propItems]
if (this.items.length > 0 && this.items.length < this.length) {
const displayItems = this.items.length % this.pageSize;
if (displayItems == this.pageSize - 1) {
this.items.push({}) //for pagination
}
}
this.dataSource = new MatTableDataSource(this.items)
this.dataSource.sort = this.sort
this.dataSource.paginator = this.paginator
}
clickCheck(event, item) {
event.preventDefault()
const index = this.selectedItems.indexOf(item, 0);
if (index > -1) {
this.selectedItems.splice(index, 1);
} else {
this.selectedItems.push(item)
}
console.log(this.selectedItems)
}
setCheckStatus(item) {
const index = this.selectedItems.indexOf(item, 0);
if (index > -1) {
return true
} else {
return false
}
}
dateToString(date) {
return this.dateService.dateToString(date)
}
clickTh(th) {
this.selectedTh = th
}
clickItem(item) {
this.router.navigate(['/pages/contact_detail'])
}
pageChanged(event) {
this.page = event
this.pagination.emit(event)
}
}
<file_sep>/src/app/app.module.ts
import { HttpInterceptorService } from './services/http-interceptor.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import { SharedModule } from './shared/shared.module';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AccountApiService } from './services/account-api.service';
import { TokenService } from './services/token.service';
import { UserRegistrationModule } from './user-registration/user-registration.module';
import { ContactApiService } from './services/contact-api.service';
import {
SocialLoginModule,
SocialAuthServiceConfig,
} from 'angularx-social-login';
import { GoogleLoginProvider, FacebookLoginProvider } from 'angularx-social-login';
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { environment } from '../environments/environment';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AuthTwitterService } from './services/auth-twitter.service';
import { MaterialModule } from './material/material.module';
import { SpinnerOverlayComponent } from './core/spinner-overlay/spinner-overlay.component';
import {SettingsApiService} from './services/settings-api.service';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
const routes: Routes = [
{ path: '', redirectTo: 'pages/dashboard', pathMatch: 'full' },
{ path: 'login', redirectTo: 'user/login', pathMatch: 'full' },
{ path: 'signup', redirectTo: 'user/signup', pathMatch: 'full' },
{
path: 'user',
loadChildren: () =>
import('./user-registration/user-registration.module').then(
(m) => m.UserRegistrationModule
),
},
{
path: 'pages',
loadChildren: () =>
import('./pages/pages.module').then((m) => m.PagesModule),
},
{
path: '',
loadChildren: () =>
import('./shared/shared.module').then((m) => m.SharedModule),
},
];
const config: ExtraOptions = {
//useHash: true,
onSameUrlNavigation: 'reload'
};
@NgModule({
declarations: [AppComponent, SpinnerOverlayComponent],
imports: [
BrowserModule,
RouterModule.forRoot(routes, config),
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
SharedModule,
HttpClientModule,
SocialLoginModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
AngularFirestoreModule,
MaterialModule
],
providers: [
AccountApiService,
TokenService,
ContactApiService,
SettingsApiService,
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider(
'830281107448-r8aj5hj1nvqrvom4eq9lp21hgtr9apbs.apps.googleusercontent.com'
)
},
{
id: FacebookLoginProvider.PROVIDER_ID,
provider: new FacebookLoginProvider("447613193049348")
}
]
} as SocialAuthServiceConfig,
},
AuthTwitterService,
NgbModule,
],
exports: [RouterModule],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>/src/environments/environment.ts
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false,
firebase: {
apiKey: "AIzaSyAxIWcCA6BhngwYB-JuSleua4GaU6Tm_6Y",
authDomain: "trove-crm.firebaseapp.com",
projectId: "trove-crm",
storageBucket: "trove-crm.appspot.com",
messagingSenderId: "287909577050",
appId: "1:287909577050:web:ebc04308247c94620fb363"
},
envName: 'Development',
baseUrl: 'https://ct.trovecrm.in/api/v1/', //http://127.0.0.1:8000/api/v1/ | https://ct.trovecrm.in/api/v1/
/** API Methods */
/*======= Account ====================*/
register: 'account/register',
login: 'account/login',
me: 'account/me',
sendPasswordResetLink: 'account/sendPasswordResetLink',
resetPassword: 'account/resetPassword',
validateResetPasswordToken: 'account/validateResetPasswordToken',
verifyEmail: 'account/verifyEmail',
logout: 'account/logout',
/*======= Settings ====================*/
profile: 'settings/profile',
profile_picture: 'settings/profile-picture',
changePassword: '<PASSWORD>',
preference: 'settings/preference',
users: 'settings/users',
listusers: 'settings/users/index',
roles: 'settings/roles',
listroles: 'settings/roles/index',
notifications: 'settings/notifications',
pipelines: 'settings/pipeline',
company: 'organizations',
company_index: 'organizations/index',
company_delete: 'organizations',
company_delete_multiple: 'organizations?_method=DELETE',
contacts: 'contacts',
contacts_index: 'contacts/index',
contacts_delete: 'contacts',
contacts_delete_multiple: 'contacts?_method=DELETE',
leads: 'leads',
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.
<file_sep>/src/app/user-registration/login/login.component.ts
import { TokenService } from './../../services/token.service';
import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, Component, OnInit, DoCheck, OnDestroy, NgZone } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AccountApiService } from '../../services/account-api.service';
import { extractErrorMessagesFromErrorResponse } from './../../services/extract-error-messages-from-error-response';
import { FormStatus } from './../../services/form-status';
import {
SocialAuthService,
GoogleLoginProvider,
FacebookLoginProvider,
SocialUser,
} from 'angularx-social-login';
import { Subscription } from 'rxjs';
import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import {
AngularFirestore,
AngularFirestoreDocument,
} from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit, OnDestroy {
apiResponse: any;
clicked = false;
hide = true;
infoMessage = '';
infoStatus = 'alertBox';
socialUser: SocialUser;
isLoggedin: boolean;
NavigationExtrasResponse:any;
private subscriptions: Subscription[] = [];
// 1 - Initialize a form status object for the component
formStatus = new FormStatus();
constructor(
public formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private account: AccountApiService,
private token: TokenService,
private socialAuthService: SocialAuthService,
public afs: AngularFirestore,
public afAuth: AngularFireAuth,
public ngZone: NgZone,
) {
this.NavigationExtrasResponse = this.router.getCurrentNavigation().extras.state;
//console.log(this.NavigationExtrasResponse);
if (account.isLoggedIn()) {
router.navigate(['pages/dashboard']);
}
const subs_valuechange = this.loginForm.valueChanges.subscribe((data) => {
this.apiResponse = false;
});
const subs_query_param = this.route.queryParams
.subscribe(params => {
if(params.logout !== undefined && params.logout === 'true') {
this.infoMessage = 'Logged out successfully.';
} else if(params.reset !== undefined && params.reset === 'true'){
this.infoMessage = 'Password changed successfully.';
} else if(params.resettoken !== undefined && params.resettoken === 'false'){
this.infoMessage = 'Password reset token is invalid/expired.';
this.infoStatus = 'alertBoxError';
} else if(params.verifyemail !== undefined && params.verifyemail === 'false'){
this.infoMessage = 'Invalid token.';
this.infoStatus = 'alertBoxError';
} else if(params.verifyemail !== undefined && params.verifyemail === 'verified'){
this.infoMessage = 'Email already verified.';
this.infoStatus = 'alertBoxError';
}
});
this.subscriptions.push(subs_valuechange);
this.subscriptions.push(subs_query_param);
}
ngOnInit(): void {
}
/*##################### Google Auth #####################*/
loginWithGoogle(): void {
this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID).then((user) => {
this.socialUser = user;
this.isLoggedin = user != null;
//console.log(this.isLoggedin);
this.formStatus.onFormSubmitting();
if ( this.socialUser && typeof this.socialUser.email !== 'undefined') {
let postData = {
email: this.socialUser.email,
platform: 'web',
type: this.socialUser.provider,
social_user_id: this.socialUser.id,
};
const sub_social = this.account.login(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.logOut();
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.logOut();
}
);
this.subscriptions.push(sub_social);
} else {
this.formStatus.onFormSubmitResponse({
success: false,
messages: ['Your social media doesn\'t have email, so kindly signup with email.']
});
this.logOut();
}
})
.catch((error) => {
//window.alert(error);
console.log(error)
});
}
loginWithFacebook(): void {
this.socialAuthService.signIn(FacebookLoginProvider.PROVIDER_ID).then((user) => {
this.socialUser = user;
this.isLoggedin = user != null;
this.formStatus.onFormSubmitting();
if ( this.socialUser && typeof this.socialUser.email !== 'undefined') {
let postData = {
email: this.socialUser.email,
platform: 'web',
type: this.socialUser.provider,
social_user_id: this.socialUser.id,
};
const sub_social = this.account.login(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.logOut();
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
this.logOut();
}
);
this.subscriptions.push(sub_social);
} else {
this.logOut();
this.formStatus.onFormSubmitResponse({
success: false,
messages: ['Your social media doesn\'t have email, so kindly signup with email.']
});
}
})
.catch((error) => {
//window.alert(error);
console.log(error);
});
}
// signUp With Twitter
loginWithTwitter(): void {
this.AuthTwitter(new auth.TwitterAuthProvider());
}
// Auth logic to run auth providers
AuthTwitter(provider) {
this.afAuth.auth
.signInWithPopup(provider).then((result: any) => {
let user = result.additionalUserInfo.profile;
this.isLoggedin = user != null;
this.formStatus.onFormSubmitting();
if(typeof user !== 'undefined' && user.email != ""){
let postData = {
email: user.email,
platform: 'web',
type: 'TWITTER',
social_user_id: user.id,
};
const sub_social = this.account.login(postData).subscribe(
(response) => {
this.apiResponse = response;
this.token.handle(response.data.token);
this.formStatus.onFormSubmitResponse({
success: true,
messages: [],
});
this.ngZone.run(() => {
this.router.navigate(['pages/dashboard']);
});
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
}
);
this.subscriptions.push(sub_social);
} else {
this.formStatus.onFormSubmitResponse({
success: false,
messages: [
"Your social media doesn't have email, so kindly signup with email.",
],
});
}
})
.catch((error) => {
//window.alert(error);
console.log(error);
});
}
logOut(): void {
if(this.isLoggedin){
this.socialAuthService.signOut().then().catch(this.yourHandler);
}
}
/* SignOut method for logging out from the Angular/Firebase app */
TwitterSignOut() {
if(this.isLoggedin){
this.afAuth.auth.signOut().then().catch(this.yourHandler);
}
}
yourHandler(){
console.log("Social logged out");
}
/*##################### Login Form #####################*/
loginForm = this.formBuilder.group({
email: [
'',
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
password: [
'',
[
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,12}$'
),
],
],
platform:"",
type: ""
});
// Submit Registration Form
onSubmit() {
if (!this.loginForm.valid) {
return false;
} else {
this.clicked = true;
this.formStatus.onFormSubmitting();
this.loginForm.patchValue({ platform: 'web', type: 'form' });
const subs_form = this.account.login(this.loginForm.value).subscribe(
(response) => {
this.clicked = false;
this.apiResponse = response;
this.token.handle(response.data.token);
localStorage.setItem('me', JSON.stringify(response.data.me));
this.router.navigate(['pages/dashboard']);
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
// call onFormSubmitResponse with the submission success status (false) and the array of messages
this.formStatus.onFormSubmitResponse({
success: false,
messages: messages,
});
}
);
this.subscriptions.push(subs_form);
}
}
ngOnDestroy() {
//console.log("ngOnDestroy")
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
if(this.isLoggedin){
this.logOut();
this.afAuth.auth.signOut();
}
}
}
<file_sep>/src/app/shared/shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent, LeadDialog, ContactDialog, CompanyDialog } from './header/header.component';
import { RouterModule,Routes } from '@angular/router';
import { MaterialModule } from '../material/material.module';
import { SnackbarComponent } from './snackbar/snackbar.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { EchartsComponent } from './echarts/echarts.component';
import { NgxEchartsModule } from 'ngx-echarts';
const routes: Routes = [
]
@NgModule({
declarations: [HeaderComponent, SnackbarComponent, LeadDialog,ContactDialog,
CompanyDialog,
EchartsComponent
],
imports: [
CommonModule,RouterModule.forChild(routes),MaterialModule,
FormsModule,
ReactiveFormsModule,
NgxEchartsModule.forRoot({
echarts: () => import('echarts')
})
],
exports: [HeaderComponent,RouterModule,EchartsComponent]
})
export class SharedModule { }
<file_sep>/src/app/pages/contact/contact.component.ts
import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatTabChangeEvent } from '@angular/material/tabs';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { SnackBarService} from '../../shared/snack-bar.service'
import { NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import { ContactApiService } from '../../services/contact-api.service';
import { ContactFilters, ContactOwner } from './filter/filter.component';
import { DateService } from '../../service/date.service'
import * as moment from 'moment';
export interface item {
id: number;
name: string;
owner: string;
contactCount: number;
email: string;
companyName: string;
company: boolean;
last: Date;
city: string;
}
export interface selectedData {
items: item[]
}
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
@ViewChild('drawer') drawer
showFilter: boolean = false
filters: ContactFilters = null
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
hoveredItem = null
pageSize = 10
recordsTotal = 0
items = []
companies: ContactOwner[] = []
selectedItems: item[] = []
currentCategory = null
lastQuery: any = {}
listShow: boolean = false
closeResult = '';
constructor(
private modalService: NgbModal,
public contactService: ContactApiService,
public dialog: MatDialog,
private router: Router,
private dateService: DateService,
private sb: SnackBarService) {
}
triggerSnackBar(message:string, action:string) {
this.sb.openSnackBarBottomCenter(message, action);
}
/*Modal dialog*/
open(content) {
this.modalService.open(content, {ariaLabelledBy: 'dialog001'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
/*Modal dialog*/
ngOnInit(): void {
this.contactService.obs.subscribe(() => this.update());
this.showGrid()
}
update() {
this.lastQuery = {}
this.listShow ? this.showList() : this.showGrid()
}
showList() {
this.listShow = true
this.selectedItems = []
this.items = []
this.applyFilter()
}
showGrid() {
this.listShow = false
this.selectedItems = []
this.applyFilter()
}
private fetchListView(query) {
this.contactService
.getContactList(query)
.subscribe((res: any) => {
console.log('fetchListView', res)
if (!res.success) {
this.triggerSnackBar(res.message, 'Close')
return
}
const contacts = res.data.contacts
this.recordsTotal = contacts.recordsFiltered
this.items = this.items.concat(contacts.data)
this.updateCompanies()
},
err => {
this.triggerSnackBar(err.error.message, 'Close')
})
}
private fetchGridView(query) {
this.contactService
.getContactList(query)
.subscribe((res: any) => {
console.log('fetchGridView', res)
if (!res.success) {
this.triggerSnackBar(res.message, 'Close')
return
}
this.items = []
const data = res.data.contacts.data
for (const activity in data) {
const contacts: any[] = data[activity]
contacts.map((contact, index) => {
this.items.push({...contact, category: activity, company: false})
})
}
this.updateCompanies()
},
err => {
this.triggerSnackBar(err.error.message, 'Close')
})
}
private updateCompanies() {
this.companies = []
let idArray = [], nameArray = []
this.items.forEach(item => {
if (item.organization_id && item.organization_id.length > 0) {
idArray = idArray.concat(item.organization_id)
nameArray = nameArray.concat(item.organization_name.split(','))
}
})
idArray = Array.from(new Set(idArray))
nameArray = Array.from(new Set(nameArray))
if (idArray.length === nameArray.length) {
this.companies = idArray.map((id, index) => {
return {id: id, name: nameArray[index]}
})
}
console.log('updateCompanies', this.companies)
}
pageChanged(e) {
console.log('pageChanged', e)
if (this.items.length >= e.length) {
return
}
const start = e.pageIndex * e.pageSize
const query = { view_type: 'list', draw: 0, start: start, length: e.pageSize }
this.fetchListView(query)
}
clickCard(item) {
this.router.navigate(['/pages/contact_detail'])
}
clickCompanyPage() {
this.router.navigate(['/pages/company'])
}
clickCheck(e, item) {
e.preventDefault()
const index = this.selectedItems.indexOf(item, 0)
if (index > -1) {
this.selectedItems.splice(index, 1)
} else {
this.selectedItems.push(item)
}
}
setCheckStatus(item) {
const index = this.selectedItems.indexOf(item, 0)
if (index > -1) {
return true
} else {
return false
}
}
showCardCheckBox(item) {
const index = this.selectedItems.indexOf(item, 0);
if (this.hoveredItem == item || index > -1)
return true
return false
}
setHoveredItem(item) {
this.hoveredItem = item
}
clickEmptyCheck() {
this.selectedItems = [...this.items]
}
clickIndeterminate() {
this.selectedItems = []
}
clickEmail() {
const dialogRef = this.dialog.open(MailDialog, {
width: '745px',
autoFocus: false,
data: {items: this.selectedItems}
})
dialogRef.afterClosed().subscribe(result => {
console.log('result ', result)
// if (result && result.data && result.data == 'delete') {
// this.openConfirmDialog()
// }
})
}
filterClosedStart() {
setTimeout(() => this.applyFilter(), 10)
}
setFilter(filters: ContactFilters) {
this.filters = filters
}
applyFilter() {
let query = { }
if (this.contactService.searchText) {
query['search'] = this.contactService.searchText
}
const filters = this.filters
if (filters) {
console.log('applyFilter', filters)
if (filters.owners.length > 0) {
query['Created_organization'] = filters.owners
}
if (filters.addedon >= 0) {
let startDate = null, lastDate = null
if (filters.activity == 6) {
startDate = moment(this.filters.addedonStartDate)
lastDate = moment(this.filters.addedonEndDate)
}
else {
const dateRange = this.dateService.getDateRange(this.filters.addedon)
startDate = dateRange.startDate?.format('DD-MM-YYYY')
lastDate = dateRange.lastDate?.format('DD-MM-YYYY')
}
query['added'] = {from: startDate, to: lastDate}
}
if (filters.activity >= 0) {
let startDate = null, lastDate = null
if (filters.activity == 6) {
startDate = moment(this.filters.activityStartDate)
lastDate = moment(this.filters.activityEndDate)
}
else {
const dateRange = this.dateService.getDateRange(this.filters.activity)
startDate = dateRange.startDate?.format('DD-MM-YYYY')
lastDate = dateRange.lastDate?.format('DD-MM-YYYY')
}
query['modified'] = {from: startDate, to: lastDate}
}
if (filters.status && filters.status !== 'All') {
query['status'] = filters.status == 'Active' ? 1 : 2
}
}
query['view_type'] = this.listShow? 'list' : 'grid'
console.log('applyFilter, query=', query, this.lastQuery)
// Compare query
if (!this.compareQuery(this.lastQuery, query)) {
this.lastQuery = query
this.items = []
if (this.listShow) this.fetchListView(query)
else this.fetchGridView(query)
}
}
compareQuery(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (object1[key] !== object2[key]) {
return false;
}
}
return true;
}
clickFilter() {
this.drawer.toggle()
this.showFilter = true
}
checkCategory(item) {
if (item == null) {
this.currentCategory = null
return false
}
if (item.category && item.category != this.currentCategory) {
this.currentCategory = item.category
return true
}
return false
}
deleteItem(e) {
console.log('deleteCompnay', this.selectedItems)
const companyIds = this.selectedItems.map(item => item.id)
this.contactService
.deleteContact(companyIds)
.subscribe((res: any) => {
if (res.success) {
this.deleteSelectedItems()
this.triggerSnackBar(res.message, 'Close')
}
},
err => {
this.triggerSnackBar(err.error.message, 'Close')
})
}
deleteSelectedItems() {
console.log('deleteSelectedItems', this.selectedItems)
this.selectedItems.forEach(item => {
const index = this.items.indexOf(item)
index >= 0 && this.items.splice(index, 1)
})
this.selectedItems = []
}
}
@Component({
selector: 'mail-dialog',
templateUrl: 'mail-dialog/mail-dialog.html',
styleUrls: ['mail-dialog/mail-dialog.css']
})
export class MailDialog {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
activeTabIndex = 0
items: selectedData
constructor(
public dialogRef: MatDialogRef<MailDialog>,
@Inject(MAT_DIALOG_DATA) public data: selectedData
) {
this.items = data
}
onNoClick(): void {
this.dialogRef.close();
}
public handleTabChange(e: MatTabChangeEvent) {
this.activeTabIndex = e.index
console.log(this.items)
}
public titleOptions1: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'<KEY>',
toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public titleOptions2: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'<KEY>',
toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public titleOptions3: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'<KEY>',
toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public deleteSelected(item) {
const index = this.items.items.indexOf(item)
this.items.items.splice(index, 1)
}
}
<file_sep>/src/app/pages/detail/text-editor/text-editor.component.ts
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { MatTabChangeEvent } from '@angular/material/tabs';
@Component({
selector: 'app-text-editor',
templateUrl: './text-editor.component.html',
styleUrls: ['./text-editor.component.css']
})
export class TextEditorComponent implements AfterViewInit {
@ViewChild('tabGroup', { static: false })
public tabGroup: any;
public activeTabIndex: number | undefined = undefined;
public editorShow: boolean = true;
public titleOptions1: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'<KEY>',
toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public titleOptions2: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'<KEY>',
toolbarBottom: true,
imageEditButtons: ['imageReplace', 'imageAlign', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public titleOptions3: Object = {
// placeholderText: 'Edit Your Content Here!',
// charCounterCount: false,
// toolbarInline: true,
key:'cJC7bA5D3G2F2C2G2yQNDMIJg1IQNSEa1EUAi1XVFQd1EaG3C2A5D5C4E3D2D4D2B2==',
toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
public handleTabChange(e: MatTabChangeEvent) {
this.activeTabIndex = e.index;
console.log('tabIndex', this.activeTabIndex)
}
// input data for company,leads,contacts
optionsPerson: any[] = [
{
name: "Person",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
}
]
optionsCompany: any[] = [
{
name: "Company", icon: "business" , isChecked: false,
desc: "Sample Description"
},
{
name: "Company 2", icon: "business" , isChecked: false,
desc: "Sample Description2"
},
{
name: "Company 3", icon: "business" , isChecked: false,
desc: "Sample Description3"
}
]
optionsLeads: any[] = [
{
name: "Leads", icon: "leaderboard" , isChecked: false,
desc: "Sample Description"
},
{
name: "Leads 2", icon: "leaderboard" , isChecked: false,
desc: "Sample Description2"
},
{
name: "Leads 3", icon: "leaderboard" , isChecked: false,
desc: "Sample Description3"
}
]
selected: any[] = []
// input data for company,leads,contacts
// input data for company,leads,contacts
optionsPersonEmail: any[] = [
{
name: "Person",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
}
]
optionsCompanyEmail: any[] = [
{
name: "Company", icon: "business" , isChecked: false,
desc: "Sample Description"
},
{
name: "Company 2", icon: "business" , isChecked: false,
desc: "Sample Description2"
},
{
name: "Company 3", icon: "business" , isChecked: false,
desc: "Sample Description3"
}
]
optionsLeadsEmail: any[] = [
{
name: "Leads", icon: "leaderboard" , isChecked: false,
desc: "Sample Description"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description2"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description3"
}
]
selectedEmail: any[] = []
// input data for company,leads,contacts
// input data for company,leads,contacts
optionsPersonCall: any[] = [
{
name: "Person",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
}
]
optionsCompanyCall: any[] = [
{
name: "Company", icon: "business" , isChecked: false,
desc: "Sample Description"
},
{
name: "Company 2", icon: "business" , isChecked: false,
desc: "Sample Description2"
},
{
name: "Company 3", icon: "business" , isChecked: false,
desc: "Sample Description3"
}
]
optionsLeadsCall: any[] = [
{
name: "Leads", icon: "leaderboard" , isChecked: false,
desc: "Sample Description"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description2"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description3"
}
]
selectedCall: any[] = []
// input data for company,leads,contacts
constructor() {
this.activeTabIndex = 0;
}
// input data for company,leads,contacts
public onSelectionChange(event) {
if(event.isChecked) {
this.selected.push(event);
}
else{
this.deleteSelected(event);
}
}
deleteSelected(e) {
e.isChecked = false;
const index = this.selected.indexOf(e)
this.selected.splice(index, 1)
}
// input data for company,leads,contacts
// input data for company,leads,contacts
public onSelectionChangeEmail(event) {
if(event.isChecked) {
this.selectedEmail.push(event);
}
else{
this.deleteSelectedEmail(event);
}
}
deleteSelectedEmail(e) {
e.isChecked = false;
const index = this.selectedEmail.indexOf(e)
this.selectedEmail.splice(index, 1)
}
// input data for company,leads,contacts
// input data for company,leads,contacts
public onSelectionChangeCall(event) {
if(event.isChecked) {
this.selectedCall.push(event);
}
else{
this.deleteSelectedCall(event);
}
}
deleteSelectedCall(e) {
e.isChecked = false;
const index = this.selectedCall.indexOf(e)
this.selectedCall.splice(index, 1)
}
// input data for company,leads,contacts
ngAfterViewInit(): void {
this.activeTabIndex = this.tabGroup.selectedIndex;
}
public showEditor() {
this.editorShow = true
}
public hideEditor() {
this.editorShow = false
}
}
<file_sep>/src/app/pages/task/task-filter/task-filter.component.ts
import { Component, EventEmitter, Input, OnInit, Output, Inject } from '@angular/core';
import { DateService } from '../../../service/date.service'
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith, take, tap } from 'rxjs/operators';
import { MatTabChangeEvent } from '@angular/material/tabs';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
export class Type {
constructor(public name: string, public selected?: boolean) {
if (selected === undefined) selected = false;
}
}
export interface createContact {
name: string;
isChecked?: boolean;
}
export interface createCompany {
name: string;
isChecked?: boolean;
}
// multi autocomplete
export class Contact {
constructor(public name: string, public selected?: boolean) {
if (selected === undefined) selected = false;
}
}
@Component({
selector: 'app-task-filter',
templateUrl: './task-filter.component.html',
styleUrls: ['./task-filter.component.css']
})
export class TaskFilterComponent implements OnInit {
@Output() closeDialog = new EventEmitter();
@Output() count = new EventEmitter<any>();
contactCtrl = new FormControl();
companyCtrl = new FormControl();
filteredCont: Observable<createContact[]>;
filteredComp: Observable<createCompany[]>;
selectedCreatedBy: createContact[] = [];
selectedCompany: createCompany[] = [];
status: string
statusTypes: string[] = ['All', 'Active', 'Inactive']
filterCount: number = 0
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
createdBySelection(contact: createContact){
if(contact.isChecked) {
this.selectedCreatedBy = [...this.selectedCreatedBy, contact]
}else {
let index = this.selectedCreatedBy.findIndex(c => c.name === contact.name);
this.selectedCreatedBy.splice(index,1);
}
}
companySelection(contact: createCompany){
if(contact.isChecked) {
this.selectedCompany = [...this.selectedCompany, contact]
}else {
let index = this.selectedCompany.findIndex(c => c.name === contact.name);
this.selectedCompany.splice(index,1);
}
}
dateTypes: number[] = [0, 1, 2, 3, 4, 5, 6]
dateTypeString: string[] = ['Today', 'Yesterday', 'Last Week', 'This month', 'Last month', 'This Quarter', 'Custom']
dateType: number
startDate: Date = null
endDate: Date = null
addDateTypes: number[] = [0, 1, 2, 3, 4, 5, 6]
addDateTypeString: string[] = ['Today', 'Yesterday', 'Last Week', 'This month', 'Last month', 'This Quarter', 'Custom']
addDateType: number
addStartDate: Date = null
addEndDate: Date = null
dueDateTypes: number[] = [0, 1, 2, 3, 4]
dueDateTypeString: string[] = ['Today', 'Tomorrow', 'Next 7 days', 'Overdue', 'Custom']
dueDateType: number
dueStartDate: Date = null
dueEndDate: Date = null
contactType: string = 'contact'
contacts: createContact[] = [
{
name: 'Arkansas',
},
{
name: 'California'
},
{
name: 'Florida'
},
{
name: 'Texas'
}
];
companys: createCompany[] = [
{
name: 'Company 1',
},
{
name: 'Company 2'
},
{
name: 'Company 3'
},
{
name: 'Company 4'
}
];
types: Type[] = [
new Type('Added by user'),
new Type('Import from CSV'),
new Type('Google contacts'),
new Type('Twitter contacts'),
new Type('Outlook contacts')
]
// multi autocomplete
constructor(private dateService: DateService) {
this.filteredCont = this.contactCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStates(state) : this.contacts.slice())
);
this.filteredComp = this.companyCtrl.valueChanges
.pipe(
startWith(''),
map(state => state ? this._filterStatesComp(state) : this.companys.slice())
);
}
ngOnInit(): void {
}
public displayArray(arr) {
let ret = ''
arr.length == 1 && (ret += arr[0])
arr.length == 2 && (ret += arr[0] + ', ' + arr[1])
arr.length > 2 && (ret += arr[0] + ', ' + arr[1] + ' +' + (arr.length - 2))
return ret
}
clickType(e, type) {
type.selected = e.checked
}
displaySelectedTypes() {
let arr = []
this.types.forEach(e => {
e.selected && arr.push(e.name)
})
return this.displayArray(arr)
}
public getSelectedDate() {
if (this.dateType == -1) {
return ''
}
switch (this.dateType) {
case 0:
const today = this.dateService.getToday()
return today + ' ~ ' + today
case 1:
const yesterday = this.dateService.getYesterday()
return yesterday + ' ~ ' + yesterday
case 2:
return this.dateService.getLastWeek()
case 3:
return this.dateService.getThisMonth()
case 4:
return this.dateService.getLastMonth()
case 5:
return this.dateService.getThisQuarter()
case 6:
let firstDay = '', lastDay = ''
this.startDate && (firstDay = this.dateService.dateToString(this.startDate))
this.endDate && (lastDay = this.dateService.dateToString(this.endDate))
return firstDay + ' ~ ' + lastDay
}
}
public getAddSelectedDate() {
if (this.addDateType == -1) {
return ''
}
switch (this.addDateType) {
case 0:
const today = this.dateService.getToday()
return today + ' ~ ' + today
case 1:
const yesterday = this.dateService.getYesterday()
return yesterday + ' ~ ' + yesterday
case 2:
return this.dateService.getLastWeek()
case 3:
return this.dateService.getThisMonth()
case 4:
return this.dateService.getLastMonth()
case 5:
return this.dateService.getThisQuarter()
case 6:
let firstDay = '', lastDay = ''
this.addStartDate && (firstDay = this.dateService.dateToString(this.addStartDate))
this.addEndDate && (lastDay = this.dateService.dateToString(this.addEndDate))
return firstDay + ' ~ ' + lastDay
}
}
public getDueSelectedDate() {
if (this.dueDateType == -1) {
return ''
}
switch (this.dueDateType) {
case 0:
const today = this.dateService.getToday()
return today + ' ~ ' + today
case 1:
const tomorrow = this.dateService.getTomorrow();
return tomorrow + ' ~ ' + tomorrow
case 2:
return this.dateService.getNext7Days()
case 3:
const yesterday = this.dateService.getYesterday()
return yesterday
case 4:
let firstDay = '', lastDay = ''
this.dueStartDate && (firstDay = this.dateService.dateToString(this.dueStartDate))
this.dueEndDate && (lastDay = this.dateService.dateToString(this.dueEndDate))
return firstDay + ' ~ ' + lastDay
}
}
calculateFilterCount(): number {
this.filterCount = 0;
if(this.status) {
this.filterCount += 1;
}
if(this.selectedCreatedBy.length > 0) {
this.filterCount += 1;
}
if(this.selectedCompany.length > 0) {
this.filterCount += 1;
}
if(this.dateType != -1 && (this.dateType || this.dateType == 0)) {
this.filterCount += 1;
}
if(this.addDateType != -1 && (this.addDateType || this.addDateType == 0)) {
this.filterCount += 1;
}
if(this.dueDateType != -1 && (this.dueDateType || this.dueDateType == 0)) {
this.filterCount += 1;
}
if(this.displaySelectedTypes() != '') {
this.filterCount += 1;
}
this.count.emit(this.filterCount);
return this.filterCount;
}
clearAll() {
this.clearType();
this.clearStatus();
this.clearCreatedBy();
this.clearCompany();
this.clearDate();
this.clearAddDate();
this.clearDueDate();
}
clearType() {
this.types.forEach(e => {
e.selected = false;
})
}
public clearStatus() {
this.status = undefined;
}
public clearCreatedBy() {
this.selectedCreatedBy = [];
this.filteredCont.pipe(
tap(data => {
data.forEach(c => {
c.isChecked = false;
})
}),
take(1)
).subscribe();
}
public clearCompany() {
this.selectedCompany = [];
this.filteredComp.pipe(
tap(data => {
data.forEach(c => {
c.isChecked = false;
})
}),
take(1)
).subscribe();
}
public clearDate() {
this.dateType = -1
}
public clearAddDate() {
this.addDateType = -1
}
public clearDueDate() {
this.dueDateType = -1
}
private _filterStates(value: string): createContact[] {
const filterValue = value.toLowerCase();
return this.contacts.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);
}
private _filterStatesComp(value: string): createContact[] {
const filterValue = value.toLowerCase();
return this.companys.filter(state => state.name.toLowerCase().indexOf(filterValue) === 0);
}
filterCountChangedHandler(e) {
this.filterCount = e
}
}
<file_sep>/src/app/user-registration/login/login.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { RouterModule , Routes } from '@angular/router';
import {MatButtonModule} from '@angular/material/button';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
const routes: Routes = [
{path:'', component:LoginComponent}
]
@NgModule({
declarations: [LoginComponent],
imports: [
CommonModule,
RouterModule.forChild(routes),MatButtonModule,FormsModule,ReactiveFormsModule,MatFormFieldModule,MatInputModule,MatIconModule
],
exports:[RouterModule]
})
export class LoginModule { }
<file_sep>/src/app/user-registration/verify-email/verify-email.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AccountApiService } from 'src/app/services/account-api.service';
@Component({
selector: 'app-verify-email',
templateUrl: './verify-email.component.html',
styleUrls: ['./verify-email.component.scss']
})
export class VerifyEmailComponent implements OnInit {
apiResponse: any;
constructor(
private account: AccountApiService,
private router: Router,
private route: ActivatedRoute,
) {
route.queryParams.subscribe(params => {
this.account.verifyEmail(params['token']).subscribe(
(response) => {
this.apiResponse = response;
},
(err) => {
//console.log(err.error);
if(err.error.code == 256){
this.router.navigate(['login'], {queryParams: { verifyemail: 'false' } });
} else if(err.error.code == 257){
this.router.navigate(['login'], {queryParams: { verifyemail: 'verified' } });
}
}
);
});
}
ngOnInit() {
}
}
<file_sep>/src/app/pages/pages.component.ts
import { Component, OnInit } from '@angular/core';
import * as echarts from 'echarts';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AppointDialog, TaskDialog } from './detail/detail.component';
export class Task {
constructor(public name: string, public selected?: boolean) {
if (selected === undefined) selected = false
}
}
export class Appointment {
constructor(public name: string, public icon: string , public color: string, public desc: string) {
}
}
@Component({
selector: 'app-pages',
templateUrl: './pages.component.html',
styleUrls: ['./pages.component.css']
})
export class PagesComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 };
tasks: Task[] = [
new Task("Packet Monster Sales opportunity"),
new Task("Ux design meeting at 17:30hrs."),
new Task("Landing page required for new CRM app"),
new Task("Meeting required for new CRM app"),
]
appointments: Appointment[] = [
new Appointment("Packet Monster Sales opportunity", "notification", "default", "Today at 11:00"),
new Appointment("Ux design meeting at 17:30hrs.", "calendar", "red", "Sat, 23 Apr, 2021"),
new Appointment("Landing page required for new CRM app", "notification", "default", "Sun, 24 Apr, 2021"),
new Appointment("Meeting required for new CRM app", "calendar", "default", "Mon, 25 Apr, 2021"),
]
colorsourceChart = ['#7184b8']
sourceChart: echarts.EChartsOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['SMS', 'Website', 'News', 'Task'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Source',
type: 'bar',
barWidth: '60%',
data: [10, 52, 100, 200]
}
],
color: this.colorsourceChart,
};
colormonthlyChart = ['#c6a887']
monthlyChart: echarts.EChartsOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Monthly',
type: 'bar',
barWidth: '60%',
data: [10, 52, 200, 170, 250]
}
],
color: this.colormonthlyChart,
};
colorpipelineChart = ['#595393', '#ffa33e', '#c6a887', '#7184b8']
pipelineChart: echarts.EChartsOption = {
tooltip: {
trigger: 'item'
},
legend: {
bottom: 0,
left: 'left',
show: true
},
series: [
{
name: 'Pipeline',
type: 'pie',
radius: ['50%', '80%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '13',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{value: 1048, name: 'Pipeline 1'},
{value: 735, name: 'Pipeline 2'},
{value: 580, name: 'Pipeline 3'},
{value: 484, name: 'Pipeline 4'}
]
}
],
color: this.colorpipelineChart,
};
constructor(public dialog: MatDialog) { }
ngOnInit(): void {
}
openTaskDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(TaskDialog, {
width: '405px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
openAppointDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(AppointDialog, {
width: '740px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
}
<file_sep>/src/app/pages/settings/settings.component.ts
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.css'],
})
export class SettingsComponent implements OnInit {
constructor() {
}
//defining method for display of SnackBar
// triggerSnackBar(message:string, action:string)
// {
// this.sb.openSnackBarBottomCenter(message, action);
// }
tabLoadTimes: Date[] = [];
getTimeLoaded(index: number) {
if (!this.tabLoadTimes[index]) {
this.tabLoadTimes[index] = new Date();
}
return this.tabLoadTimes[index];
}
ngOnInit(): void {
}
}
<file_sep>/src/app/pages/contact-detail/contact-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { AppointDialog, TaskDialog } from '../detail/detail.component';
import { ContactDialog } from 'src/app/shared/header/header.component';
@Component({
selector: 'app-contact-detail',
templateUrl: './contact-detail.component.html',
styleUrls: ['./contact-detail.component.css']
})
export class ContactDetailComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
status = "active"
// selectedDisplay = "all"
constructor(private router: Router , public dialog: MatDialog) { }
ngOnInit(): void {
}
goToList() {
this.router.navigate(['/pages/contact']);
}
openTaskDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(TaskDialog, {
width: '405px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
openAppointDialog(isEdit: boolean) {
const dialogRef = this.dialog.open(AppointDialog, {
width: '740px',
data : { isEdit: isEdit}
});
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog sent: ${result}`);
})
}
editContact() {
const dialogRef = this.dialog.open(ContactDialog, {
width: '531px',
autoFocus: false,
data : { isEdit : true}
})
dialogRef.afterClosed().subscribe(result => {
})
}
}
// @Component({
// selector: 'task-dialog',
// templateUrl: '../detail/task-dialog/task-dialog.html',
// styleUrls: ['../detail/task-dialog/task-dialog.css'],
// providers: [
// // The locale would typically be provided on the root module of your application. We do it at
// // the component level here, due to limitations of our example generation script.
// {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
// // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// // `MatMomentDateModule` in your applications root module. We provide it at the component level
// // here, due to limitations of our example generation script.
// {
// provide: DateAdapter,
// useClass: MomentDateAdapter,
// deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
// },
// {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
// ],
// })
// export class TaskDialog {
// scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
// myControl = new FormControl()
// options: string[] = ['One', 'Two', 'Three']
// filteredOptions: Observable<string[]>;
// selected: string[] = []
// showAuto: boolean = true
// active: number = 1
// constructor(
// public dialogRef: MatDialogRef<AppointDialog>
// // @Inject(MAT_DIALOG_DATA) public data: DialogData
// ) {
// this.filteredOptions = this.myControl.valueChanges.pipe(
// startWith(''),
// map(value => this._filter(value))
// );
// }
// private _filter(value: string): string[] {
// const filterValue = value.toLowerCase();
// return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
// }
// public onSelectionChange(event) {
// this.selected.push(event.option.value)
// this.showAuto = false
// }
// public clickAdd() {
// console.log('click add')
// this.showAuto = !this.showAuto
// }
// public activeClass(num) {
// if (num == this.active)
// return 'activeBtn'
// else
// return ''
// }
// public setActive(num) {
// console.log('set active', num)
// this.active = num
// if (num == 1) {
// this.options = ['One', 'Two', 'Three']
// } else if (num == 2) {
// this.options = ['Four', 'Five', 'Six']
// } else if (num == 3) {
// this.options = ['Seven', 'Eight', 'Nine']
// }
// this.filteredOptions = this.myControl.valueChanges.pipe(
// startWith(''),
// map(value => this._filter(value))
// )
// }
// onNoClick(): void {
// this.dialogRef.close();
// }
// deleteSelected(e) {
// const index = this.selected.indexOf(e)
// this.selected.splice(index, 1)
// this.selected.length == 0 && (this.showAuto = true)
// }
// }
// @Component({
// selector: 'appoint-dialog',
// templateUrl: '../detail/appoint-dialog/appoint-dialog.html',
// styleUrls: ['../detail/appoint-dialog/appoint-dialog.css'],
// providers: [
// // The locale would typically be provided on the root module of your application. We do it at
// // the component level here, due to limitations of our example generation script.
// {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
// // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// // `MatMomentDateModule` in your applications root module. We provide it at the component level
// // here, due to limitations of our example generation script.
// {
// provide: DateAdapter,
// useClass: MomentDateAdapter,
// deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
// },
// {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
// ],
// })
// export class AppointDialog {
// myControl = new FormControl();
// options: string[] = ['One', 'Two', 'Three'];
// filteredOptions: Observable<string[]>;
// selected: string[] = []
// showAuto: boolean = true
// active: number = 1
// constructor(
// public dialogRef: MatDialogRef<AppointDialog>
// // @Inject(MAT_DIALOG_DATA) public data: DialogData
// ) {
// this.filteredOptions = this.myControl.valueChanges.pipe(
// startWith(''),
// map(value => this._filter(value))
// );
// }
// private _filter(value: string): string[] {
// const filterValue = value.toLowerCase();
// return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
// }
// public onSelectionChange(event) {
// this.selected.push(event.option.value)
// this.showAuto = false
// }
// public clickAdd() {
// console.log('click add')
// this.showAuto = !this.showAuto
// }
// public activeClass(num) {
// if (num == this.active)
// return 'activeBtn'
// else
// return ''
// }
// public setActive(num) {
// console.log('set active', num)
// this.active = num
// if (num == 1) {
// this.options = ['One', 'Two', 'Three']
// } else if (num == 2) {
// this.options = ['Four', 'Five', 'Six']
// } else if (num == 3) {
// this.options = ['Seven', 'Eight', 'Nine']
// }
// this.filteredOptions = this.myControl.valueChanges.pipe(
// startWith(''),
// map(value => this._filter(value))
// )
// }
// onNoClick(): void {
// this.dialogRef.close();
// }
// deleteSelected(e) {
// const index = this.selected.indexOf(e)
// this.selected.splice(index, 1)
// this.selected.length == 0 && (this.showAuto = true)
// }
// }
<file_sep>/src/app/pages/sourcechart/source-table/source-table.component.ts
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MatPaginator } from '@angular/material/paginator';
export interface PeriodicElement {
avatar: string;
name: string;
description: string;
value: number;
stage: string;
contact: any;
owner: string;
company: string;
source: string;
closedate: string;
category: string;
addedon: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description1", stage: 'Qualified', value: 0, contact: '8006589521', owner: 'Packet Monster, Inc.',
company: 'Company 1' , source: 'Source 1', closedate: '22/05/2021', category: 'Category 1', addedon: '12/04/2021'
},
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description2", stage: 'Evolution', value: 400, contact: '8006589526', owner: '',
company: 'Company 1' , source: 'Source 1', closedate: '22/05/2021', category: 'Category 2', addedon: '12/03/2021'
},
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description3", stage: 'Evolution', value: 300, contact: '8006589527', owner: '',
company: 'Company 1' , source: 'Source 1', closedate: '22/05/2021', category: 'Category 3', addedon: '10/04/2021' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description4", stage: 'Evolution', value: 40, contact: '8006589525', owner: '',
company: 'Company 1' , source: 'Source 1', closedate: '22/05/2021', category: 'Category 4', addedon: '' },
{ avatar: '../../../assets/images/user-sample.png', name: '<NAME>', description: "description5", stage: 'Evolution', value: 2, contact: '8006589524', owner: '',
company: 'Company 1' , source: 'Source 1', closedate: '22/05/2021', category: 'Category 5' , addedon: '' }
]
@Component({
selector: 'app-source-table',
templateUrl: './source-table.component.html',
styleUrls: ['./source-table.component.css']
})
export class SourceTableComponent implements AfterViewInit {
displayedColumns: string[] = ['name', 'stage', 'value', 'owner', 'company', 'category', 'addedon', 'closedate', 'contact', 'source'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
selectedTh = ''
constructor(private router: Router) { }
@ViewChild(MatSort, {static: false}) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
ngAfterViewInit (): void {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator
}
}
<file_sep>/src/app/services/contact-api.service.ts
import { Injectable } from '@angular/core'
import { BehaviorSubject, Observable, ReplaySubject, throwError } from 'rxjs'
import { environment } from 'src/environments/environment'
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
HttpParams,
} from '@angular/common/http'
@Injectable({
providedIn: 'root',
})
export class ContactApiService {
subject: ReplaySubject<any> = new ReplaySubject()
obs: Observable<any> = this.subject.asObservable()
baseURL = environment.baseUrl
public searchText: string = null
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
}
public companyData = null
public contactData = null
constructor(private httpClient: HttpClient) {}
/* Contact API Service */
getContacts(): Observable<any> {
const API_URL = `${this.baseURL + environment.contacts}`
return this.httpClient.get(API_URL)
}
createContact(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.contacts}`, data)
}
getContactList(data): Observable<any> {
const API_URL = `${this.baseURL + environment.contacts_index}`
return this.httpClient.post(API_URL, data)
}
deleteContact(companyIds: any[]): Observable<any> {
if (companyIds.length > 1) {
const data = { ids: companyIds }
const API_URL = `${this.baseURL + environment.contacts_delete_multiple}`
return this.httpClient.post(API_URL, data)
} else {
const companyId = companyIds[0]
const API_URL = `${
this.baseURL + environment.contacts_delete
}/${companyId}`
return this.httpClient.delete(API_URL)
}
}
/* Company API Service */
getCompanies(): Observable<any> {
const API_URL = `${this.baseURL + environment.company}`
return this.httpClient.get(API_URL)
}
createCompany(data: any): Observable<any> {
return this.httpClient.post(`${this.baseURL + environment.company}`, data)
}
getCompanyList(data): Observable<any> {
const API_URL = `${this.baseURL + environment.company_index}`
return this.httpClient.post(API_URL, data)
}
deleteCompany(companyIds: any[]): Observable<any> {
if (companyIds.length > 1) {
const data = { ids: companyIds }
const API_URL = `${this.baseURL + environment.company_delete_multiple}`
return this.httpClient.post(API_URL, data)
} else {
const companyId = companyIds[0]
const API_URL = `${
this.baseURL + environment.company_delete
}/${companyId}`
return this.httpClient.delete(API_URL)
}
}
/* Helper Functions */
getCountries() {
if (this.contactData) {
return this.contactData.country
}
if (this.companyData) {
return this.companyData.countries
}
return null
}
getEmailOwners() {
if (this.contactData) {
return this.contactData.owners
}
if (this.companyData) {
return this.companyData.owners
}
return null
}
getContactCompanyList() {
if (this.contactData) {
return this.contactData.organizations;
}
return null;
}
getDialCodes() {
const countries = this.getCountries()
if (countries) {
const dialCodes = countries
.filter((x) => x.dial_code)
.map((x) => x.dial_code)
return this.sortDialCodes(dialCodes)
}
return null
}
private sortDialCodes(dialCodes: string[]) {
return dialCodes.sort((a: string, b: string) => {
const a1 = a.replace(/ /g, '')
const b1 = b.replace(/ /g, '')
if (a1.length < b1.length) return -1
else if (a1.length > b1.length) return 1
return a1.localeCompare(b1)
})
}
notify() {
this.subject.next()
}
ngOnDestroy() {}
}
<file_sep>/src/app/pages/settings/notification/notification.component.ts
import {
AfterViewInit,
Component,
OnInit,
ViewChild,
ChangeDetectorRef,
AfterContentChecked,
} from '@angular/core';
import {
FormGroup,
FormControl,
FormBuilder,
Validators,
FormArray,
} from '@angular/forms';
import { SnackBarService } from '../../../shared/snack-bar.service';
import { extractErrorMessagesFromErrorResponse } from '../../../services/extract-error-messages-from-error-response';
import { FormStatus } from '../../../services/form-status';
import { SettingsApiService } from 'src/app/services/settings-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-notification',
templateUrl: './notification.component.html',
styleUrls: ['./notification.component.css'],
})
export class NotificationComponent implements OnInit {
/*Notification user checkbox*/
isNotiUserAll: boolean;
notificationUser: any = [
{
name: 'When deal is assigned',
isSelected: false,
},
{
name: 'When task is assigned',
isSelected: false,
},
{
name: 'When contact is assigned',
isSelected: false,
},
];
/*Notification user checkbox*/
/*Notification System checkbox*/
isNotiSystemAll: boolean;
notificationSystem: any = [
{
name: 'When import is completed',
isSelected: false,
},
{
name: 'When export is completed',
isSelected: false,
},
];
/*Notification user checkbox*/
constructor(
private fb: FormBuilder,
private sb: SnackBarService,
private settingsApiService: SettingsApiService,
private cdref: ChangeDetectorRef
) {
this.initnotificationForm();
}
/*Notification user checkbox*/
selectAllNotiUser() {
this.notificationUser.map((r) => {
r.isSelected = this.isNotiUserAll;
});
}
unSelectNotiUser(isSelected) {
if (!isSelected) {
this.isNotiUserAll = false;
} else if (
this.notificationUser.length ===
this.notificationUser.filter((r) => {
return r.isSelected === true;
}).length
) {
this.isNotiUserAll = true;
}
}
/*Notification user checkbox*/
/*Notification System checkbox*/
selectAllNotification(index, obj) {
var stat = 0;
if(obj.user_notification) {
stat = 1;
}
this.LoopingVar[index][0].email_notification = stat;
this.LoopingVar[index][0].push_notification = stat;
this.LoopingVar[index].map((r) => {
r.user_notification = obj.user_notification;
});
}
SelectNotificationSetting(parent, child, obj) {
if (!obj.user_notification) {
this.isNotiSystemAll = false;
this.LoopingVar[parent][0].user_notification = false;
this.LoopingVar[parent][child].email_notification = 0;
this.LoopingVar[parent][child].push_notification = 0;
} else if (
(this.LoopingVar[parent].length -1) ===
this.LoopingVar[parent].filter((r) => {
return r.user_notification === true;
}).length
) {
this.LoopingVar[parent][0].user_notification = true;
this.isNotiSystemAll = true;
}
}
/*Notification System checkbox*/
/**==================================================================== */
notificationForm;
notificationSettings = [];
LoopingVar = [];
formStatus = new FormStatus();
private subscriptions: Subscription[] = [];
ngOnInit(): void {
this.settingsApiService.getNotificationSettings().subscribe(
(res: any) => {
if (res.success) {
if (res.data.menu_previlages.create == 1) {
this.notificationSettings = res.data.notifications;
this.addnotification();
} else {
this.triggerSnackBar(res.message, 'Close');
}
} else {
this.triggerSnackBar(res.message, 'Close');
}
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(errorResponse);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
}
initnotificationForm() {
this.notificationForm = this.fb.group({
notifications: this.fb.array([]),
});
}
private addnotification() {
var self = this;
var formControlKey = -1;
this.notificationSettings.forEach(function (value, key) {
var temparr = [];
formControlKey++;
var obj = {
notification_id: value.id,
title: value.title,
user_notification: value.user_notification,
email_notification: value.email_notification,
push_notification: value.push_notification,
parent_id: value.parent_id,
formControlKey: formControlKey,
};
self.notificationForm.controls.notifications.push(self.addNotificationFormGroup(obj));
temparr.push(obj);
if (value.child_nofications.length > 0) {
value.child_nofications.forEach(function (child_value, child_key) {
formControlKey++;
var obj = {
notification_id: child_value.id,
title: child_value.title,
user_notification: child_value.user_notification,
email_notification: child_value.email_notification,
push_notification: child_value.push_notification,
parent_id: child_value.parent_id,
formControlKey: formControlKey,
};
self.notificationForm.controls.notifications.push(self.addNotificationFormGroup(obj));
temparr.push(obj);
});
}
self.LoopingVar[key] = temparr;
//self.newRoleForm.controls.menus.push(temparr);
//this.push(key + ': ' + value);
});
//this.Permissions.forEach((menu) => this.newRoleForm.controls.menus.push(this.addMenuFormGroup(menu)));
}
addNotificationFormGroup(data: any = []): FormGroup {
if (data) {
return this.fb.group({
notification_id: [data.notification_id],
user_notification: [data.user_notification],
email_notification: [data.email_notification],
push_notification: [data.push_notification],
title: [data.title],
parent_id: [data.parent_id],
formControlKey: [data.formControlKey],
});
}
}
saveNotificationSetting(){
if (!this.notificationForm.valid) {
//console.log(this.registrationForm.controls.first_name.errors);
return false;
} else {
this.formStatus.onFormSubmitting();
var postNotifications = [];
this.notificationForm.value.notifications.forEach(function (value, key) {
postNotifications.push({
notification_id: value.notification_id,
email_notification: value.email_notification,
push_notification: value.push_notification
})
});
const subs_query_param = this.settingsApiService
.saveNotificationSettings({notifications: postNotifications})
.subscribe(
(res: any) => {
this.triggerSnackBar(res.message, 'Close');
},
(errorResponse: HttpErrorResponse) => {
const messages = extractErrorMessagesFromErrorResponse(
errorResponse
);
this.triggerSnackBar(messages.toString(), 'Close');
}
);
this.subscriptions.push(subs_query_param);
}
}
triggerSnackBar(message: string, action: string) {
this.sb.openSnackBarBottomCenter(message, action);
}
ngAfterContentChecked() {
this.cdref.detectChanges();
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/app/pages/editnote/editnote.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-editnote',
templateUrl: './editnote.component.html',
styleUrls: ['./editnote.component.css']
})
export class EditnoteComponent implements OnInit {
scrollOptions = { autoHide: true, scrollbarMinSize: 50 }
// input data for company,leads,contacts
optionsPerson: any[] = [
{
name: "Person",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
},
{
name: "<NAME>",
icon: "person",
isChecked: false,
email: "<EMAIL>"
}
]
optionsCompany: any[] = [
{
name: "Company", icon: "business" , isChecked: false,
desc: "Sample Description"
},
{
name: "Company 2", icon: "business" , isChecked: false,
desc: "Sample Description2"
},
{
name: "Company 3", icon: "business" , isChecked: false,
desc: "Sample Description3"
}
]
optionsLeads: any[] = [
{
name: "Leads", icon: "leaderboard" , isChecked: false,
desc: "Sample Description"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description2"
},
{
name: "<NAME>", icon: "leaderboard" , isChecked: false,
desc: "Sample Description3"
}
]
selected: any[] = []
// input data for company,leads,contacts
constructor() { }
// input data for company,leads,contacts
public onSelectionChange(event) {
if(event.isChecked) {
this.selected.push(event);
}
else{
this.deleteSelected(event);
}
}
deleteSelected(e) {
e.isChecked = false;
const index = this.selected.indexOf(e)
this.selected.splice(index, 1)
}
// input data for company,leads,contacts
public titleOptions1: Object = {
key:'<KEY>',
// toolbarBottom: true,
events: {
"initialized": () => {
console.log('initialized');
},
"contentChanged": () => {
console.log("content changed");
}
}
}
attachmentItems: any[] = [
{
name: "Sales guide to file.docx",
size: "55kb"
},
{
name: "Sales guide to file2.docx",
size: "75kb"
},
{
name: "Sales guide to file3.docx",
size: "175kb"
}
]
ngOnInit(): void {
}
}
<file_sep>/src/app/pages/pages.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PagesComponent } from './pages.component';
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { SharedModule } from '../shared/shared.module';
import { AuthGuardService } from '../services/auth-guard.service';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { LeadsComponent } from './leads/leads.component';
import { LeadTableComponent } from './leads/lead-table/lead-table.component';
import {MaterialModule} from '../material/material.module';
import { SettingsComponent } from './settings/settings.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FlexLayoutModule } from '@angular/flex-layout';
import { DetailComponent, StageDialog, EditDialog, ConfirmDialog, TaskDialog, AppointDialog, StageSnack } from './detail/detail.component';
import { EditorModule } from "@tinymce/tinymce-angular";
import { TextEditorComponent } from './detail/text-editor/text-editor.component';
import { WidgetComponent } from './detail/widget/widget.component';
import { FilterComponent } from './leads/filter/filter.component';
import { ProfileComponent } from './settings/profile/profile.component';
import { UsersrolesComponent } from './settings/usersroles/usersroles.component';
import { AccountComponent } from './settings/account/account.component';
import { NotificationComponent } from './settings/notification/notification.component';
import { DragdropDirective } from './settings/data/dragdrop.directive';
import { DataComponent } from './settings/data/data.component';
import { PipelinestagesComponent } from './settings/pipelinestages/pipelinestages.component';
import { TermsservicesComponent } from './settings/termsservices/termsservices.component';
import { PrivacypolicyComponent } from './settings/privacypolicy/privacypolicy.component';
import { PlanspricingComponent } from './settings/planspricing/planspricing.component';
import { SimplebarAngularModule } from 'simplebar-angular';
import { NgxSliderModule } from "@angular-slider/ngx-slider";
import { ContactFilterComponent } from './contact/filter/filter.component';
import { ContactComponent, MailDialog } from './contact/contact.component';
import { ContactTableComponent } from './contact/contact-table/contact-table.component';
import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg';
import { ContactDetailComponent } from './contact-detail/contact-detail.component';
import { TaskComponent } from './task/task.component';
import { TaskFilterComponent } from './task/task-filter/task-filter.component';
import {NgxMaterialTimepickerModule} from 'ngx-material-timepicker';
import { CompanyComponent, CompanyMailDialog } from './company/company.component';
import { CompanyTableComponent } from './company/company-table/company-table.component';
import { CompanyDetailComponent } from './company-detail/company-detail.component';
import {CompanyFilterComponent} from './company/filter/filter.component';
import { EditnoteComponent } from './editnote/editnote.component';
import { AddnoteComponent } from './addnote/addnote.component';
import { SourcechartComponent } from './sourcechart/sourcechart.component';
import { SourceFilterComponent } from './sourcechart/source-filter/source-filter.component';
import { SourceTableComponent } from './sourcechart/source-table/source-table.component';
import { ActivitylogComponent } from './activitylog/activitylog.component';
import { ActivitylistComponent } from './detail/activitylist/activitylist.component';
import { ContactActivitylistComponent } from './contact-detail/contact-activitylist/contact-activitylist.component';
import { CompanyActivitylistComponent } from './company-detail/company-activitylist/company-activitylist.component';
import { RolesComponent } from './settings/usersroles/roles/roles.component';
//canActivate:[AuthGuardService]
const routes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: PagesComponent, canActivate:[AuthGuardService]},
// {path:'settings' , loadChildren: () => import('./settings/settings.module') .then(m=>m.SettingsModule)},
{ path: 'settings', component: SettingsComponent, canActivate:[AuthGuardService]},
{ path: 'leads', component: LeadsComponent, canActivate:[AuthGuardService]},
{ path: 'lead_detail', component: DetailComponent, canActivate:[AuthGuardService]},
{ path: 'contact', component: ContactComponent, canActivate:[AuthGuardService]},
{ path: 'contact_detail', component: ContactDetailComponent, canActivate:[AuthGuardService]},
{ path: 'task', component: TaskComponent, canActivate:[AuthGuardService]},
{ path: 'company', component: CompanyComponent, canActivate:[AuthGuardService]},
{ path: 'company_detail', component: CompanyDetailComponent, canActivate:[AuthGuardService]},
{ path: 'addnote', component: AddnoteComponent, canActivate:[AuthGuardService]},
{ path: 'editnote', component: EditnoteComponent, canActivate:[AuthGuardService]},
{ path: 'sourcedetail' , component: SourcechartComponent, canActivate:[AuthGuardService]},
{ path: 'activities', component: ActivitylogComponent, canActivate:[AuthGuardService]},
]
@NgModule({
declarations: [
PagesComponent,LeadsComponent,LeadTableComponent,SettingsComponent,
DetailComponent,
StageDialog,
EditDialog,
TaskDialog,
AppointDialog,
ConfirmDialog,
StageSnack,
TextEditorComponent,
WidgetComponent,
FilterComponent,
ProfileComponent,
UsersrolesComponent,
RolesComponent,
AccountComponent,
NotificationComponent,
DragdropDirective,
DataComponent,
PipelinestagesComponent,
TermsservicesComponent,
PrivacypolicyComponent,
PlanspricingComponent,
ContactFilterComponent,
ContactComponent,
ContactTableComponent,
MailDialog,
ContactDetailComponent,
TaskComponent,
TaskFilterComponent,
CompanyComponent,
CompanyTableComponent,
CompanyDetailComponent,
CompanyFilterComponent,
CompanyMailDialog,
EditnoteComponent,
AddnoteComponent,
SourcechartComponent,
SourceFilterComponent,
SourceTableComponent,
ActivitylogComponent,
ActivitylistComponent,
ContactActivitylistComponent,
CompanyActivitylistComponent
],
imports: [
CommonModule,
RouterModule.forChild(routes),
SharedModule,
NgbModule,
MaterialModule,
ReactiveFormsModule,
FormsModule,
FlexLayoutModule,
EditorModule,
SimplebarAngularModule,
NgxSliderModule,
FroalaEditorModule.forRoot(),
FroalaViewModule.forRoot(),
NgxMaterialTimepickerModule,
],
exports: [RouterModule],
})
export class PagesModule {}
<file_sep>/src/app/user-registration/forgot-password/forgot-password.component.ts
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { AccountApiService } from 'src/app/services/account-api.service';
@Component({
selector: 'app-forgot-password',
templateUrl: './forgot-password.component.html',
styleUrls: ['./forgot-password.component.css']
})
export class ForgotPasswordComponent implements OnInit {
clicked = false;
hide = true;
apiResponse: any;
private subscriptions: Subscription[] = [];
constructor(
public formBuilder: FormBuilder,
private account: AccountApiService,
private router: Router
) {
const subs_value_change = this.forgotPasswordForm.valueChanges.subscribe((data) => {
this.apiResponse = false;
});
this.subscriptions.push(subs_value_change);
}
ngOnInit(): void {
}
forgotPasswordForm = this.formBuilder.group({
email: [
'',
[
Validators.required,
Validators.maxLength(255),
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
});
// Submit Registration Form
onSubmit() {
if (!this.forgotPasswordForm.valid) {
return false;
} else {
this.clicked = true;
const subs_send_password_link = this.account.sendPasswordResetLink(this.forgotPasswordForm.controls['email'].value).subscribe(
(response) => {
this.clicked = false;
this.router.navigate(['/user/forgot-password/reset-email']);
},
(err) => {
this.clicked = false;
if (err.error.code === 254) {
const formControl = this.forgotPasswordForm.get('email');
if (formControl) {
formControl.setErrors({
serverError: err.error.message,
});
}
} else {
this.apiResponse = err.error;
}
}
);
this.subscriptions.push(subs_send_password_link);
}
}
ngOnDestroy() {
this.subscriptions.forEach((sub) => {
sub.unsubscribe();
});
}
}
<file_sep>/src/app/service/date.service.ts
import { Injectable } from '@angular/core';
import * as moment from 'moment';
@Injectable({
providedIn: 'root'
})
export class DateService {
constructor() { }
leftpad(val, resultLength = 2, leftpadChar = '0'): string {
return (String(leftpadChar).repeat(resultLength)
+ String(val)).slice(String(val).length);
}
dateToString(date) {
return this.leftpad(date.getDate(), 2) + '/' + this.leftpad(date.getMonth() + 1, 2) + '/' + date.getFullYear();
}
getToday() {
return this.dateToString(new Date())
}
getTomorrow() {
let date = new Date();
date.setDate(date.getDate() + 1);
return this.dateToString(date)
}
getYesterday() {
let date = new Date();
date.setDate(date.getDate() - 1);
return this.dateToString(date)
}
getLastWeek() {
let curr = new Date; // get current date
let first = curr.getDate() - curr.getDay() - 7 // First day is the day of the month - the day of the week
let last = first + 6; // last day is the first day + 6
let firstDay = this.dateToString(new Date(curr.setDate(first)))
let lastDay = this.dateToString(new Date(curr.setDate(last)))
return firstDay + ' ~ ' + lastDay
}
getNext7Days() {
let curr = new Date; // get current date
let first = curr.getDate() - curr.getDay() + 7 // First day is the day of the month - the day of the week
let last = first + 6; // last day is the first day + 6
let firstDay = this.dateToString(new Date(curr.setDate(first)))
let lastDay = this.dateToString(new Date(curr.setDate(last)))
return firstDay + ' ~ ' + lastDay
}
getThisMonth() {
let date = new Date()
let firstDay = this.dateToString(new Date(date.getFullYear(), date.getMonth(), 1))
let lastDay = this.dateToString(new Date(date.getFullYear(), date.getMonth() + 1, 0))
return firstDay + ' ~ ' + lastDay
}
getLastMonth() {
let date = new Date()
let firstDay = this.dateToString(new Date(date.getFullYear(), date.getMonth() - 1, 1))
let lastDay = this.dateToString(new Date(date.getFullYear(), date.getMonth(), 0))
return firstDay + ' ~ ' + lastDay
}
getThisQuarter() {
let d = new Date()
let quarter = Math.floor((d.getMonth() / 3))
let firstDate = new Date(d.getFullYear(), quarter * 3, 1)
let endDate = new Date(firstDate.getFullYear(), firstDate.getMonth() + 3, 0)
let firstDay = this.dateToString(firstDate)
let lastDay = this.dateToString(endDate)
return firstDay + ' ~ ' + lastDay
}
getDateRange(index): { startDate: moment.Moment, lastDate: moment.Moment} {
let startDate = null, lastDate = null
switch (index) {
case 0://Today
startDate = lastDate = moment()
break
case 1://Yesterday
startDate = lastDate = moment().subtract(1, 'days')
break
case 2://Last Week
startDate = moment().subtract(1, 'weeks').startOf('week')
lastDate = moment().subtract(1, 'weeks').endOf('week')
break
case 3://This Month
startDate = moment().clone().startOf('month')
lastDate = moment().clone().endOf('month')
break
case 4://Last Month
startDate = moment().subtract(1, 'months').startOf('month')
lastDate = moment().subtract(1, 'months').endOf('month')
break
case 5://This Quarter
startDate = moment().quarter(moment().quarter()).startOf('quarter');
lastDate = moment().quarter(moment().quarter()).endOf('quarter');
break
}
return {startDate, lastDate}
}
}
| f127a75e1ea3ba858d853594bbbfd53e5d94f7ee | [
"TypeScript"
] | 51 | TypeScript | reactomoss/trove-crm-frontend | 04d37b45e17458f7137f856326e4aa0c4ce9edfb | 1f073be16f44173c02985b8451bace101a303a17 |
refs/heads/master | <file_sep>#ASM86
Very small subset of a X86 assembler with the syntax of NASM.
It is written in PLA and a DOS COM-program.
<file_sep># ASM86
Small subset of a X86 assembler with the syntax of NASM.
It is written in PLA and a DOS COM-program with only 12 KBytes!
You get source code and binaries.
AS is a one pass compiler, so you have the following restrictions:
* global variables must be declared before use
* code must be in procedures, surrounded by PROC and ENDP
* jmp and jcc are relative (NEAR,SHORT) and must be in the same procedure
* call for a procedure is near, relative and must be backwards,
so the MAIN procedure is the last procedure in the program.
* jmp to the main proc is automatically made by the PLA compiler
AS is a COM-program and uses only one segment with 64 KByte.
About 12 KByte for program and constants, the rest for tables and the
binary output file.
Adjust the following constants to your needs:
1. FILEBINMAX 22000 max. length of output file
2. LABELADRMAX 600 max. global and local labels
all local labels will be destroyed after leaving the procedure.
it is roughly the number of the procedures and a bit for local names.
LabelNames[6000] array for storing the label names
3. JMPMAX 200 max.jmp and call
JmpNames[4000] space for names of jmp, call
The output com file must be the same with ASM86 and NASM.
NASM must be calles the the options: -dPROC -dENDP
because NASM does not know the two words.
AS NASM is a multi pass compiler set off the optimization with -O1
<file_sep>char Version1[]="ASM.C V1.2.1";//Assembler like NASM, 11912bytes. 8381 stack
//todo mov ebx, 10 crash
//todo 1. array[] Label not found
//todo L=L+1 OK, L+=1 only byte added, L++ invalid op code
//todo CS:seg override [mem] OK, [es:2Ch] not OK
//todo not implemented: 14,15,16,41,51
//todo input hex as A.C getDigit 0x1234
//fixed JmpMaxIx > 0 line 1007
#define IDLENMAX 31
char Symbol[IDLENMAX]; //next symbol to decode
char SymbolUpper[IDLENMAX];//set toupper in getName
char ProcName[IDLENMAX];//name of actual proc
char isPrint=1; //print to screen on
char isInProc=0; //is inside a procedure
unsigned int SymbolInt; //integer value set in getDigit
#define INPUTBUFMAX 255
char InputBuf[INPUTBUFMAX];//filled in getLine
unsigned char *InputPtr;//position in InputBuf
char namein [67]; //input file name .S
char namelst[67]; //list file name .LST
char namebin[67]; //output file name .COM
int asm_fd; //input file descriptor
int lst_fd; //list file descriptor
int bin_fd; //output file descriptor
int DOS_ERR=0; //global var
int ErrorCount=0; //number of errors
int DOS_NoBytes; //number of bytes read (0 or 1)
char DOS_ByteRead; //the byte just read by DOS
unsigned int PC=0; //program counter
unsigned int Origin=0; //ORG nn
unsigned int AbsoluteLab=0;//uninitialised data
unsigned int PCStart; //PC at start of line by PrintLine()
char isLabel; //by getName()
#define DIGIT 1 //0-9
#define LETTERE 2 //a-z A-Z @ . _
#define ALNUME 3 //a-z A-Z @ . _ 0-9
#define NOALNUME 4 //other char
char TokeType; //0, DIGIT, LETTERE, ALNUME, NOALNUME
#define BYTE 1
#define WORD 2
#define DWORD 3
#define SEGREG 4
#define IMM 1 //const ,123
#define REG 2 // ,BX mode=11
#define ADR 3 //DIRECT: VALUE ,var1 mod=00, r/m=110
#define MEM 4 //[var1],[BX+SI],[table+BX],[bp-4] disp0,8,16
char Op; //1. operand: 0, IMM, REG, ADR, MEM
char Op2; //2. operand
char CodeType; //1-207 by searchSymbol(), must be byte size
char Code1; //1. Opcode
char R2No; //0 - 7 AL, CL, ... set in testReg()
char R1No; //temp for 1. register
char R2Type; //0=no reg, BYTE, WORD, DWORD, SEGREG
char R1Type; //temp for 1. register
char OpSize; //0, BYTE, WORD, DWORD by getCodeSize()
char wflag; //wordflag: 0=byte, 1=word/dword
char dflag; //directionflag: 1=to reg MOV,ALU
char sflag; //sign extended, imm8 to word PUSH,ALU,IMUL3
char rm; //combination of index and base reg
char isDirect; //set in process and getMeM, need in WriteEA
int disp; //displacement 0-8 bytes
unsigned int imme; //immediate 0-8 bytes
#define OPMAXLEN 5
char OpPos[OPMAXLEN]; //array for one opcode to list
int OpPrintIndex; //0-OPMAXLEN, pos to print opcode, by genCode8
char *OpCodePtr; //position in OpCodeTable by searchSymbol
char PrintRA; //print * for forward relocative jmp
#define LABELNAMESMAX 6000
char LabelNames[LABELNAMESMAX];//space for names of all labels
char *LabelNamePtr; //first free position
char *tmpLabelNamePtr; //set after PROC to LabelNamePtr
#define LABELADRMAX 600
unsigned int LabelAddr[LABELADRMAX];//addr of each label
int LabelMaxIx=0; //actual # of stored labels. 1 to LABELADRMAX-1
int tmpLabelMaxIx; //set after PROC to LabelMaxIx
int LabelIx; //actual # of just searched label
#define JMPNAMESMAX 4000
char JmpNames[JMPNAMESMAX];//space for names of jmp, call
char *JmpNamePtr; //first free position
char *tmpJmpNamePtr; //set after PROC to JmpNamePtr
#define JMPMAX 200 //max. jmp and call
unsigned int JmpAddr[JMPMAX];//addr to be fixed
unsigned int JmpMaxIx=0; //actual # of jmp, call. 1 to JMPMAX-1
unsigned int tmpJmpMaxIx=0; //set after PROC to JmpMaxIx
#define FILEBINMAX 25000
char FileBin [FILEBINMAX];//output binary file
unsigned int BinLen=0; //length of binary file
char *arglen=0x80; // for main only
char *argv=0x82; // for main only
int writetty() {//char in AL
ah=0x0E;
asm push bx
bx=0; //page in BH
inth 0x10;
asm pop bx
}
int putch(char c) {
if (c==10) {// LF
al=13; // CR, write CR first and then LF
writetty();
}
al=c;
writetty();
}
int cputs(char *s) {
char c;
while(*s) {
c=*s;
putch(c);
s++;
}
}
int mkneg(int n) {
n; // ax=n;
asm neg ax
}
int DosInt() {
inth 0x21;
__emit__(0x73, 04); //jnc over DOS_ERR++
DOS_ERR++;
}
int openR (char *s) {
dx=s;
ax=0x3D02;
DosInt();
}
int creatR(char *s) {
dx=s;
cx=0;
ax=0x3C00;
DosInt();
}
int fcloseR(int fd) {
bx=fd;
ax=0x3E00;
DosInt();
}
int exitR (char c) {
ah=0x4C;
al=c;
DosInt();
}
int readRL(char *s, int fd, int len){
dx=s;
cx=len;
bx=fd;
ax=0x3F00;
DosInt();
}
int fputcR(char *n, int fd) {
__asm{lea dx, [bp+4]}; /* = *n */
cx=1;
bx=fd;
ax=0x4000;
DosInt();
}
int letterE(char c) {
if (c=='_') return 1;
if (c=='.') return 1;
if (c=='?') return 1;
if (c=='$') return 1;
if (c> 'z') return 0;
if (c< '@') return 0; // at included
if (c> 'Z') { if (c< 'a') return 0; }
return 1;
}
int digit(char c){
if(c<'0') return 0;
if(c>'9') return 0;
return 1;
}
int alnumE(char c) {
if (digit(c)) return 1;
if (letterE(c)) return 1;
return 0;
}
int strlen(char *s) { int c;
c=0;
while (*s!=0) {s++; c++;}
return c;
}
int strcpy(char *s, char *t) {
do { *s=*t; s++; t++; }
while (*t!=0);
*s=0;
return s;
}
int eqstr(char *p, char *q) {
while(*p) {
if (*p != *q) return 0;
p++;
q++;
}
if(*q) return 0;
return 1;
}
int strcat1(char *s, char *t) {
while (*s != 0) s++;
strcpy(s, t);
}
int toupper(char *s) {
while(*s) {
if (*s >= 'a') if (*s <= 'z') *s=*s-32;
s++;
}
}
int testReg() {
//ret:RegNo: 0 - 7 AL, CL set:R2Type: 0=no reg,BYTE,WORD,SEGREG,DWORD
R2Type=0;
if (strlen(Symbol) < 2) return 0;
if (strlen(Symbol) > 3) return 0;
R2Type=BYTE;
if (eqstr(SymbolUpper, "AL")) return 0;
if (eqstr(SymbolUpper, "CL")) return 1;
if (eqstr(SymbolUpper, "DL")) return 2;
if (eqstr(SymbolUpper, "BL")) return 3;
if (eqstr(SymbolUpper, "AH")) return 4;
if (eqstr(SymbolUpper, "CH")) return 5;
if (eqstr(SymbolUpper, "DH")) return 6;
if (eqstr(SymbolUpper, "BH")) return 7;
R2Type=WORD;
if (eqstr(SymbolUpper, "AX")) return 0;
if (eqstr(SymbolUpper, "CX")) return 1;
if (eqstr(SymbolUpper, "DX")) return 2;
if (eqstr(SymbolUpper, "BX")) return 3;
if (eqstr(SymbolUpper, "SP")) return 4;
if (eqstr(SymbolUpper, "BP")) return 5;
if (eqstr(SymbolUpper, "SI")) return 6;
if (eqstr(SymbolUpper, "DI")) return 7;
R2Type=SEGREG;
if (eqstr(SymbolUpper, "ES")) return 0;
if (eqstr(SymbolUpper, "CS")) return 1;
if (eqstr(SymbolUpper, "SS")) return 2;
if (eqstr(SymbolUpper, "DS")) return 3;
if (eqstr(SymbolUpper, "FS")) return 4;
if (eqstr(SymbolUpper, "GS")) return 5;
R2Type=DWORD;
if (eqstr(SymbolUpper, "EAX"))return 0;
if (eqstr(SymbolUpper, "ECX"))return 1;
if (eqstr(SymbolUpper, "EDX"))return 2;
if (eqstr(SymbolUpper, "EBX"))return 3;
if (eqstr(SymbolUpper, "ESP"))return 4;
if (eqstr(SymbolUpper, "EBP"))return 5;
if (eqstr(SymbolUpper, "ESI"))return 6;
if (eqstr(SymbolUpper, "EDI"))return 7;
R2Type=0; return 0;
}
int prc(unsigned char c) {
if (isPrint) {
if (c==10) {
ax=13;
writetty();
}
al=c;
writetty();
}
fputcR(c, lst_fd);
}
int prscomment(unsigned char *s) {
unsigned char c;
while (*s){
c=*s;
prc(c);
s++;
}
}
int printstring(unsigned char *s) {
unsigned char c;
int com;
com=0;
while (*s) {
c=*s;
if (c==34) {
if (com) com=0;
else com=1;
}
if (c==92) {
if (com==0) {
s++;
c=*s;
if (c=='n') c=10;
if (c=='t') c= 9;
}
}
prc(c);
s++;
}
}
int printhex4(unsigned char c) {
c += 48;
if (c > 57) c += 7;
prc(c);
}
int printhex8(unsigned char c) {
unsigned char nib;
nib = c >> 4; printhex4(nib);
nib = c & 15; printhex4(nib);
}
int printhex16(unsigned int i) {
unsigned int half;
half = i >> 8; printhex8(half);
half = i & 255; printhex8(half);
}
int printunsigned(unsigned int n) {
unsigned int e;
if (n >= 10) {
e=n/10; //DIV
printunsigned(e);
}
n = n % 10; //unsigned mod
n += '0';
prc(n);
}
int printLine() {
unsigned int i; char c;
printstring("\n");
i=PCStart + Origin;
printhex16(i);
if (OpPrintIndex == 0) printstring(" ");
else {
// prc(' ');
i=0;
do {
c=OpPos[i];
prc(' ');
printhex8(c);
i++;
} while (i < OpPrintIndex);
while (i < OPMAXLEN) {// fill rest with blank
printstring(" ");
i++;
}
}
prc(PrintRA);
prscomment(InputBuf);
}
int epilog() {
unsigned int i; int j; char c;
isPrint=1;
printstring(", Output: ");
printstring(namelst);
if (ErrorCount == 0) {
printstring(", no errors, ");
printstring(namebin);
printstring("= ");
printunsigned(BinLen);
printstring(" bytes.");
bin_fd=creatR(namebin);
if(DOS_ERR){
cputs("can not create COM file: ");
cputs(namebin);
exitR(2);
}
i=0;
do {
c = FileBin[i];
fputcR(c, bin_fd);
i++;
} while (i < BinLen);
fcloseR(bin_fd);
}
fcloseR(asm_fd);
fcloseR(lst_fd);
exitR(ErrorCount);
}
int error1(char *s) {
isPrint=1;
ErrorCount++;
printLine();
printstring("\n*** ERROR: ");
printstring(s);
printstring(", Symbol >>");
printstring(Symbol);
printstring("<< in proc ");
printstring(ProcName);
epilog();
}
int notfounderror(){
printstring("\n LabelIx:"); printunsigned(LabelIx);
error1("label not found: ");}
int dataexit() {error1("DB,DW,DD or RESB,W,D expected");}
int addrerror() {error1("address missing");}
int immeerror() {error1("immediate not allowed here");}
int implerror() {error1("not implemented");}
int indexerror() {error1("invalid index register");}
int invaloperror() {error1("invalid or no operands");}
int numbererror() {error1("number expected");}
int regmemerror() {error1("only register or memory allowed");}
int reg16error() {error1("only reg16, no segreg allowed");}
int segregerror() {error1("segment register not allowed");}
int syntaxerror() {error1("syntax");}
int ifEOL(char c) {//unix LF, win CRLF= 13/10, mac CR
if (c == 10) return 1;//LF
if (c == 13) {//CR
DOS_NoBytes=readRL(&DOS_ByteRead, asm_fd, 1);
if (DOS_ByteRead != 10) error1("missing LF(10) after CR(13)");
return 1;
}
return 0;
}
int getLine() {// make ASCIIZ, skip LF=10 and CR=13
unsigned int i;
InputPtr= &InputBuf;
*InputPtr=0;//if last line is empty
do {
DOS_NoBytes=readRL(&DOS_ByteRead, asm_fd, 1);
if (DOS_ERR) error1("Reading Source");
if (DOS_NoBytes == 0) return;
*InputPtr = DOS_ByteRead;
InputPtr++;
i = InputPtr - &InputBuf;
if (i >= INPUTBUFMAX) error1("input line too long");
} while (ifEOL(DOS_ByteRead) == 0);
InputPtr--;
*InputPtr=0;
}
int skipBlank() {
skipblank1:
if (*InputPtr == ' ') { InputPtr++; goto skipblank1; }
if (*InputPtr == 9 ) { InputPtr++; goto skipblank1; }
}
int getDigit(unsigned char c) {//ret: SymbolInt
unsigned int CastInt;
SymbolInt=0;//todo input hex with 0x1234 as digit in A.C
do {
c-='0';
SymbolInt=SymbolInt*10;
ax=0;
CastInt=c; //cast b2w
SymbolInt=SymbolInt+CastInt;
InputPtr++;
c = *InputPtr;
} while(digit(c));
}
int getName(unsigned char c) {//ret: Symbol, SymbolUpper, isLabel
char *p; unsigned int i;
p = &Symbol;
*p = c;
p++;
while (alnumE(c)) {
InputPtr++;
c = *InputPtr;
*p = c;
p++;
i = p - &Symbol;
if (i >= IDLENMAX) error1("symbol too long");
}
if (c == ':') isLabel=1; else isLabel=0;
p--;
*p = 0;
strcpy(SymbolUpper, Symbol);
toupper(SymbolUpper);
}
//OpName, 0, CodeType, Code1
// 1: 1 byte opcod
char T00[]={'P','U','S','H','A',0,1,0x60, 'P','O','P','A',0, 1,0x61};
char T01[]={'N','O','P',0, 1,0x90, 'C','B','W',0, 1,0x98};
char T02[]={'C','W','D','E',0, 1,0x98, 'C','W','D',0, 1,0x99};
char T03[]={'C','D','Q',0, 1,0x99, 'W','A','I','T',0, 1,0x9B};
char T04[]={'P','U','S','H','F',0,1,0x9C, 'P','O','P','F',0, 1,0x9D};
char T05[]={'S','A','H','F',0, 1,0x9E, 'L','A','H','F',0, 1,0x9F};
char T06[]={'M','O','V','S','B',0,1,0xA4, 'M','O','V','S','W',0,1,0xA5};
char T07[]={'C','M','P','S','B',0,1,0xA6, 'C','M','P','S','W',0,1,0xA7};
char T08[]={'S','T','O','S','B',0,1,0xAA, 'S','T','O','S','W',0,1,0xAB};
char T09[]={'L','O','D','S','B',0,1,0xAC, 'L','O','D','S','W',0,1,0xAD};
char T10[]={'S','C','A','S','B',0,1,0xAE, 'S','C','A','S','W',0,1,0xAF};
char T11[]={'L','E','A','V','E',0,1,0xC9, 'I','N','T','3',0, 1,0xCC};
char T12[]={'I','N','T','O',0, 1,0xCE, 'I','R','E','T',0, 1,0xCF};
char T13[]={'X','L','A','T',0, 1,0xD7, 'L','O','C','K',0, 1,0xF0};
char T14[]={'R','E','P','N','E',0,1,0xF2, 'R','E','P','N','Z',0,1,0xF2};
char T15[]={'R','E','P','E',0, 1,0xF3, 'R','E','P','Z',0, 1,0xF3};
char T16[]={'H','L','T',0, 1,0xF4, 'C','L','C',0, 1,0xF8};
char T17[]={'S','T','C',0, 1,0xF9, 'C','L','I',0, 1,0xFA};
char T18[]={'S','T','I',0, 1,0xFB, 'C','L','D',0, 1,0xFC};
char T19[]={'S','T','D',0, 1,0xFD};
// 2: mem reg 16 bit
char T20[]={'I','N','C',0, 2, 0, 'D','E','C',0, 2, 1};
char T21[]={'N','O','T',0, 2, 2, 'N','E','G',0, 2, 3};
char T22[]={'M','U','L',0, 2, 4, 'I','M','U','L',0, 2, 5};
//IMUL acc only
char T23[]={'D','I','V',0, 2, 6, 'I','D','I','V',0, 2, 7};
// 3: les, lda, lea, lss, lfs, lgs
char T24[]={'L','E','S',0, 3,0xC4, 'L','D','S',0, 3,0xC5};
char T25[]={'L','E','A',0, 3,0x8D, 'L','S','S',0, 3,0xB2};
char T26[]={'L','F','S',0, 3,0xB4, 'L','G','S',0, 3,0xB5};
// 4: acc,imm reg,imm index,reg
char T27[]={'A','D','D',0, 4, 0, 'O','R',0, 4, 1};
char T28[]={'A','D','C',0, 4, 2, 'S','B','B',0, 4, 3};
char T29[]={'A','N','D',0, 4, 4, 'S','U','B',0, 4, 5};
char T30[]={'X','O','R',0, 4, 6, 'C','M','P',0, 4, 7};
// 5: mov
char T31[]={'M','O','V',0, 5, 0};
// 6: single byte relative jump
char T32[]={'J','O',0, 6, 0, 'J','N','O',0, 6, 1};
char T33[]={'J','B',0, 6, 2, 'J','C',0, 6, 2};
char T34[]={'J','N','B',0, 6, 3};
char T35[]={'J','A','E',0, 6, 3, 'J','N','C',0, 6, 3};
char T36[]={'J','E',0, 6, 4, 'J','Z',0, 6, 4};
char T37[]={'J','N','E',0, 6, 5, 'J','N','Z',0, 6, 5};
char T38[]={'J','B','E',0, 6, 6, 'J','N','A',0, 6, 6};
char T39[]={'J','A',0, 6, 7, 'J','S',0, 6, 8};
char T40[]={'J','N','S',0, 6, 9};
char T41[]={'J','P',0, 6,10, 'J','P','E',0, 6,10};
char T42[]={'J','N','P',0, 6,11, 'J','P','O',0, 6,11};
char T43[]={'J','L',0, 6,12};
char T44[]={'J','N','L',0, 6,13, 'J','G','E',0, 6,13};
char T45[]={'J','L','E',0, 6,14, 'J','N','G',0, 6,14};
char T46[]={'J','G',0, 6,15};
// 7: jmp, call
char T47[]={'J','M','P',0, 7,0xE9, 'C','A','L','L',0, 7,0xE8};
// 8: ret
char T48[]={'R','E','T',0, 8,0xC3, 'R','E','T','F',0, 8,0xCB};
// 9: seg, r/m
char T49[]={'P','U','S','H',0, 9,0x50, 'P','O','P',0, 9,0x58};
// 11: shift, rotates
char T50[]={'R','O','L',0, 11, 0, 'R','O','R',0, 11, 1};
char T51[]={'R','C','L',0, 11, 2, 'R','C','R',0, 11, 3};
char T52[]={'S','H','L',0, 11, 4, 'S','A','L',0, 11, 4};
char T53[]={'S','H','R',0, 11, 5, 'S','A','R',0, 11, 7};
// 12: int
char T54[]={'I','N','T',0, 12,0xCD};
// 14: in/out not implemented
char T55[]={'I','N',0, 14,0xE4, 'I','N','S','B',0, 14,0x6C};
char T56[]={'I','N','S','W',0, 14,0x6D, 'I','N','S','D',0, 14,0x6D};
char T57[]={'O','U','T',0, 14,0xE6, 'O','U','T','B',0, 14,0x6E};
char T58[]={'O','U','T','W',0, 14,0x6F, 'O','U','T','D',0, 14,0x6F};
// 15: xch not implemented
char T59[]={'X','C','H','G',0, 15,0x86};
// 16: loop, jcxz not implemented
char T60 []={'L','O','O','P','N','Z',0,16,0xE0};
char T60a[]={'L','O','O','P','N','E',0,16,0xE0};
char T61[]={'L','O','O','P','Z',0,16,0xE1,'L','O','O','P','E',0,16,0xE1};
char T62[]={'L','O','O','P',0, 16,0xE2};
char T63[]={'J','C','X','Z',0, 16,0xE3,'J','E','C','X','Z',0,16,0xE3};
// 30: other
char T64[]={'E','N','T','E','R',0,30,0};
// not implemented
char T65[]={'T','E','S','T',0, 41,0xF6};
char T66[]={'M','O','V','S','X',0,51,0xBE,'M','O','V','Z','X',0,51,0xB6};
// 100: directives
char T67[]={'O','R','G',0, 101, 0};
// section, segment .TEXT .DATA .BSS
char T68[]={'S','E','C','T','I','O','N',0, 102, 0};
char T69[]={'S','E','G','M','E','N','T',0, 102, 0};
char T70[]={'A','B','S','O','L','U','T','E',0, 110, 0};
char T71[]={'P','R','O','C',0, 111, 0, 'E','N','D','P',0, 112, 0};
char T72[]={'D','B',0, 200, 0, 'D','W',0, 201, 0};
char T73[]={'D','D',0, 202, 0, 'R','E','S','B',0, 203, 0};
char T74[]={'R','E','S','W',0, 204, 0, 'R','E','S','D',0, 205, 0};
char TEND=0;// end of table char
int lookCode1() {//ret: CodeType, Code1
OpCodePtr= &T00;
do {
if (eqstr(SymbolUpper, OpCodePtr)) {
while(*OpCodePtr!=0) OpCodePtr++;
OpCodePtr++;
CodeType = *OpCodePtr;
OpCodePtr++;
Code1 = *OpCodePtr;
return;
}
while(*OpCodePtr!=0) OpCodePtr++;
OpCodePtr += 3;
} while(*OpCodePtr!=0);
CodeType=0;
}
int genCode8(char c) {
//set: BinLen++, OpPrintIndex++
FileBin[BinLen]=c;
BinLen++;
PC++;
if (BinLen >= FILEBINMAX) error1("COM file too long");
if (OpPrintIndex < OPMAXLEN) {
OpPos[OpPrintIndex]=c;
OpPrintIndex++;
}
}
int gen66h() {genCode8(0x66);
}
int genCode2(char c, char d) {
c = c + d;
genCode8(c);
}
int genCodeW(char c) {
c = c + wflag;
genCode8(c);
}
int genCode16(unsigned int i) {
genCode8(i); i=i >> 8;
genCode8(i);
}
int genCode32(unsigned long L) {
genCode16(L); L=L >>16;
genCode16(L);
}
int writeEA(char xxx) {//value for reg/operand
//need: Op, Op2, disp, R1No, R2No, rm, isDirect
//mod-bits: mode76, reg/opcode543, r/m210
//Op: 0, IMM, REG, ADR, MEM
int disploc;
char len;
len=0;
xxx = xxx << 3;//in reg/opcode field
if (Op == REG) {
xxx |= 0xC0;
if (Op2 <= IMM) xxx = xxx + R1No;//empty or IMM
else {
if (Op2 == REG) xxx = xxx + R1No;
else xxx = xxx + R2No;
}
}
if (Op == MEM) {
if (isDirect) {
xxx |= 6;
len = 2;
}
else {
xxx = xxx + rm;
if (rm == 6) {//make [BP+00]
len=1;
if (disp == 0) xxx |= 0x40;
}
if (disp != 0) {//compare word!
disploc=disp;
if (disploc < 0) disploc=mkneg(disploc);
if (disploc > 127) len=2;
else len=1;
if (len == 1) xxx |= 0x40;
else xxx |= 0x80;
}
}
}
genCode8(xxx);// gen second byte
if (len == 1) genCode8 (disp);
if (len == 2) genCode16(disp);
}
int genImmediate() {
if (wflag) if (OpSize == DWORD) genCode32(imme);
//todo imme long
else genCode16(imme);
else genCode8 (imme);
}
int setwflag() {//word size, bit 0
wflag=0;
if (OpSize == 0) {//do not override OpSize
if (Op == REG) OpSize=R1Type;
if (Op2== REG) OpSize=R2Type;
if (R2Type== SEGREG) OpSize=WORD;
if (R1Type == SEGREG) OpSize=WORD;
}
if (OpSize == DWORD) {gen66h(); wflag=1;}
if (OpSize == WORD) wflag=1;
}
int setsflag() {//sign-extend, bit 1, only PUSH, ALU, IMUL3
unsigned int ui;
sflag=2;
ui = imme & 0xFF80;//is greater than signed 127?
if(ui != 0) sflag = 0;
if (OpSize == BYTE) {
if (imme > 255) error1("too big for byte r/m");
sflag=0;//byte reg does not need sign extended
}
}
int checkConstSize(unsigned int ui) {
if (ui > 127 ) return 0;//is near; return sflag
if (ui < 0xFF80) return 0;//-128dez
return 2;// is short
}
int ChangeDirection() {
char c;
c=Op; Op =Op2; Op2 =c;
c=R1Type; R1Type=R2Type; R2Type=c;
c=R1No; R1No =R2No; R2No =c;
dflag=2;
}
int getTokeType() {
char c;
skipBlank();
c = *InputPtr;
if (c == 0) {TokeType=0; return; }//last line or empty line
if (c == ';') {TokeType=0; return; }//comment
if (digit(c)) {getDigit(c); TokeType=DIGIT; return;}//ret:1=SymbolInt
if (letterE (c)) {getName(c); TokeType=ALNUME; return;}//ret:2=Symbol
TokeType=NOALNUME;
}
int isToken(char c) {
skipBlank();
if (*InputPtr == c) {
InputPtr++;
return 1;
}
return 0;
}
int need(char c) {
if (isToken(c)) {
getTokeType();
return;
}
isPrint=1;
printstring(" need: ");
prc(c);
error1("character misssing");
}
int skipRest() {
getTokeType();
if(TokeType)error1("extra char ignored");
}
int checkOpL() {
if (Op == ADR) implerror();
if (R1Type==SEGREG) {segregerror();return;}//only move,push,pop
setwflag();
if (OpSize == 0) error1("no op size declared");
if (OpSize == R1Type) return;
if (Op == REG) if (R1Type==0) error1("no register defined");
}
int searchLabel() {
int LIx; char *p;
p = &LabelNames;
LIx = 1;
while (LIx <= LabelMaxIx) {
if (eqstr(p, Symbol)) return LIx;//pos of label
p=strlen(p) + p;
p++;
LIx++;
}
return 0;
}
int getOp1() {//scan for a single operand
//return:0, IMM, REG, ADR (not MEM)
//set :R2Type, R2No by testReg
//set :LabelIx by searchLabel
if (TokeType == 0) return 0;
if (TokeType == DIGIT) return IMM;
if (TokeType == ALNUME) {
R2No=testReg();
if (R2Type) return REG;
LabelIx=searchLabel();
return ADR;
}
return 0;
}
int getIndReg1() {
if (R2Type !=WORD) indexerror();
if (R2No==3) rm=7;//BX
if (R2No==5) rm=6;//BP, change to BP+0
if (R2No==7) rm=5;//DI
if (R2No==6) rm=4;//SI
if (rm==0) indexerror();
}
int getIndReg2() {char m; m=4;//because m=0 is BX+DI
if (R2Type !=WORD) indexerror();
if (R2No==7) if (rm==6) m=3;//BP+DI
else if (rm==7) m=1;//BX+DI
if (R2No==6) if (rm==6) m=2;//BP+SI
else if (rm==7) m=0;//BX+SI
if (m > 3) indexerror();
return m;
}
int getMEM() {// e.g. [CS: array + bp+si -4]
//set: disp, rm, R2Type
char c;
disp=0; rm=0;
do {
getTokeType();
c=getOp1();
if (R2Type == SEGREG) {//put segment prefix
if (R2No == 0) genCode8(0x26);//ES:
if (R2No == 1) genCode8(0x2E);//CS:
if (R2No == 2) genCode8(0x36);//SS:
if (R2No == 3) genCode8(0x3E);//DS:
if (R2No == 4) genCode8(0x64);//FS:
if (R2No == 5) genCode8(0x65);//GS:
need(':');// includes getTokeType();
c=getOp1();
}
if (c == 0) syntaxerror();
if (c == REG) {
isDirect=0;
if (rm) rm=getIndReg2();
else getIndReg1();
}
if (c == ADR) {
if (LabelIx) disp=disp+LabelAddr[LabelIx];
else notfounderror();
}
if (c == IMM) disp=disp+SymbolInt;
if (isToken('-')) {
getTokeType();
if (TokeType != DIGIT) numbererror();
disp = disp - SymbolInt;
}
} while (isToken('+'));
if (isToken(']') == 0) error1("] expected");
}
int getOpR() {
Op2=getOp1();
if (isToken('[')) {Op2 = MEM; getMEM(); return;}
if (Op2 == 0) {invaloperror(); return;}
if (Op2 == IMM) {imme=SymbolInt; return;}
if (Op2 == REG) return;
if (Op2 == ADR) {
if (LabelIx == 0) disp=0;
else disp=LabelAddr[LabelIx];
return;}
error1("Name of operand expected");
}
int getOpL() {//set: op=0,IMM,REG,ADR,MEM
getOpR();
Op=Op2; Op2=0;
R1No=R2No; R2No=0;
R1Type=R2Type; R2Type=0;
}
int get2Ops() {
getOpL();
need(',');
getOpR();
}
int check2Ops() {
get2Ops();
if (Op == 0) addrerror();
if (Op == ADR) invaloperror();
if (Op == IMM) immeerror();
if (Op2== 0) addrerror();
setwflag();
}
int storeJmp() {
unsigned int i;
JmpMaxIx++;
if (JmpMaxIx >= JMPMAX) error1("too many Jmp");
JmpNamePtr=strcpy(JmpNamePtr, Symbol);
JmpNamePtr++;
i = JmpNamePtr - &JmpNames;
i += IDLENMAX;
if ( i >= JMPNAMESMAX) error1("too many Jmp names");
JmpAddr[JmpMaxIx] = PC;
}
int storeLabel() {
unsigned int i;
if(searchLabel()) error1("duplicate label");
LabelMaxIx++;
if (LabelMaxIx >= LABELADRMAX) error1("too many labels");
LabelNamePtr=strcpy(LabelNamePtr, Symbol);
LabelNamePtr++;
i = LabelNamePtr - &LabelNames;
i += IDLENMAX;
if (i >= LABELNAMESMAX) error1("too many label names");
LabelAddr[LabelMaxIx] = PC + Origin;
}
int genDB() {
char c; char isloop;
isloop = 0;
do {
if (isloop) getTokeType();//omit ,
if (TokeType == DIGIT) genCode8(SymbolInt);
else {
skipBlank();
if (isToken('"')) {
do {
c= *InputPtr;
genCode8(c);
InputPtr++;
} while (*InputPtr != '"' );
InputPtr++;
}
}
isloop = 1;
} while (isToken(','));
}
int getVariable() {
char c;
storeLabel();
getTokeType();
if(TokeType==ALNUME) {//getName
lookCode1();
if (CodeType < 200) dataexit();
if (CodeType > 205) dataexit();
if (CodeType== 200) {//DB
do {
getTokeType();
if (TokeType == DIGIT) genCode8(SymbolInt);
else {
skipBlank();
if (isToken('"')) {
do {
c= *InputPtr;
genCode8(c);
InputPtr++;
} while (*InputPtr != '"' );
InputPtr++;
}
}
} while (isToken(','));
}
if (CodeType == 201) {//DW
do {
getTokeType();
if (TokeType ==DIGIT) genCode16(SymbolInt);
} while (isToken(','));
}
if (CodeType == 202) {//DD
do {
getTokeType();
if (TokeType ==DIGIT) { genCode16(SymbolInt);
genCode16(0);}//todo genCode32(SymbolLong);
} while (isToken(','));
}
if (CodeType >= 203) {//resb, resw, resd
getTokeType();
if (TokeType == DIGIT) {
if (SymbolInt <= 0) syntaxerror();
if (AbsoluteLab == 0) error1("Absolute is null");
LabelAddr[LabelMaxIx] = AbsoluteLab;
if (CodeType == 204) SymbolInt=SymbolInt+SymbolInt;//resw
if (CodeType == 205) SymbolInt=SymbolInt * 4;//resd
AbsoluteLab = AbsoluteLab + SymbolInt;
} else numbererror();
}
}
else dataexit();
}
int getCodeSize() {
if (TokeType ==ALNUME) {
if (eqstr(SymbolUpper,"BYTE")) {getTokeType(); return BYTE;}
if (eqstr(SymbolUpper,"WORD")) {getTokeType(); return WORD;}
if (eqstr(SymbolUpper,"DWORD")){getTokeType(); return DWORD;}
}
return 0;
}
int FixOneJmp(unsigned int hex) {
int Ix; char c;
Ix=searchLabel();
if (Ix == 0) notfounderror();
disp = LabelAddr[Ix];
c = FileBin[hex];//look for 'A' push Absolute
if (c != 0xAA) {
disp = disp - hex;
disp = disp -2;//PC points to next instruction
disp = disp - Origin;
}
FileBin[hex] = disp;//fix low byte
hex++;
disp = disp >> 8;
FileBin[hex] = disp;
}
int fixJmp() {
unsigned int hex; unsigned int i;
char *p;
p = &JmpNames;
i = 1;
while (i <= JmpMaxIx) {
strcpy(Symbol, p);
p = strlen(Symbol) + p;
p++;
hex = JmpAddr[i];
FixOneJmp(hex);
i++;
}
}
int fixJmpMain() {
if (JmpMaxIx > 0) {
printstring(" *** JmpMaxIx= ");
printunsigned(JmpMaxIx);
error1("resting global jmp");
}
strcpy(Symbol, "main");
FixOneJmp(1);//first instruction, PC=1
}
int process() {
char c;
unsigned int i;
Op=Op2=R1Type=R2Type=R1No=R2No=dflag=wflag=rm=0;//char
disp=imme=0;//int
isDirect=1; //set in getMeM=0, need in WriteEA
getTokeType();//0, DIGIT, ALNUME, NOALNUME
OpSize=getCodeSize();//0, BYTE, WORD, DWORD
if (CodeType == 1) {//1 byte opcode
genCode8(Code1);
return;
}
if (CodeType == 2) {//inc,dec,not,neg,mul,imul,div,idiv
getOpL();
checkOpL();
if (Code1 < 2) {//inc,dec
if (Op == REG) {//short
if (wflag) {
if (Code1) genCode2(0x48, R1No);//DEC
else genCode2(0x40, R1No);//INC
return;
}
}
}
if (Code1 == 5) {//imul extension?
getTokeType();
if (TokeType) implerror();
}
if (Code1 < 2) genCodeW(0xFE);
else genCodeW(0xF6);
writeEA(Code1);
return;
}
if (CodeType == 3) {//les,lds,lea,lss,lfs,lgs
check2Ops(); //setwflag not applicable
if (R1Type != WORD) reg16error();//only r16
if (Op2 != MEM) addrerror();//only m16
if (Code1 >= 0xB2) {
if (Code1 <= 0xB5) genCode8(0x0F);//lss,lfs,lgs
}
genCode8(Code1);
Op=Op2;//set MEM for writeEA
writeEA(R1No);
return;
}
if (CodeType == 4) {//add,or,adc,sbb,and,sub,xor,cmp,->test
check2Ops();
if (Op2 == ADR) {
if (LabelIx == 0) notfounderror();
imme=LabelAddr[LabelIx];
Op2=IMM;//got the addr and fall through
}
if (Op2 == IMM) {//second operand is imm
setsflag();
if (Op == REG) {
if (R1No == 0) {// acc,imm
if (sflag == 0) {
c = Code1 << 3;
c += 4;
genCodeW(c);
genImmediate();
return;
}
}
}
//r/m, imm: 80 sign-extended,TTT,imm
c = sflag + 0x80;
genCodeW(c);
writeEA(Code1);
if (sflag) genCode8(imme);
else genImmediate();
return;
}
c = Code1 << 3;//r/m, r/r
if (Op == REG) {
if (Op2 == MEM) {//reg, mem
c += 2;//add direction flag
genCodeW(c);
Op=Op2;//set MEM for writeEA
writeEA(R1No);
return;
}
}
if (Op2 == REG) {//mem,reg reg,reg
genCodeW(c);
writeEA(R2No);//2. Op in reg-field
return;
}
syntaxerror();
return;
}
if (CodeType == 5) {//mov (movsx, movzx=51)
check2Ops();
if (Op2 == ADR) {
if (disp) imme=disp;
else notfounderror();
Op2=IMM;//continue with IMM
}
if (Op2 == IMM) {// r,i
if (Op == REG) {
c = wflag << 3;
c += 0xB0;
genCode2(c, R1No);
genImmediate();
return;
}
if (Op == MEM) {// m,i
genCodeW(0xC6);
writeEA( 0 );
genImmediate();
return;
}
regmemerror();
return;
}
if (R1Type == SEGREG) ChangeDirection();//sreg,rm
if (R2Type == SEGREG) {//rm,sreg
if (OpSize != WORD) reg16error();
genCode2(0x8C, dflag);
writeEA(R2No);
return;
}
if (Op2 == MEM) {//acc, moffs16
if (Op == REG) {
if (R1No == 0) {
if (isDirect) {
genCodeW(0xA0);
genCode16(disp);
return;
}
}
}
}
if (Op == MEM) {//moffs16, acc
if (Op2 == REG) {
if (R2No == 0) {
if (isDirect) {
genCodeW(0xA2);
genCode16(disp);
return;
}
}
}
}
if (Op2 == REG) {//rm, r
genCodeW(0x88);
writeEA(R2No);
return;
}
if (Op2 == MEM) {//r, m
if (Op == REG) {
ChangeDirection();
genCodeW(0x8A);
writeEA(R2No);
return;
}
}
syntaxerror();
return;
}
if (CodeType == 6) {//Jcc
if (TokeType == ALNUME) {
LabelIx=searchLabel();
if (LabelIx > 0) {
disp=LabelAddr[LabelIx];
disp = disp - PC;
disp = disp - Origin;
if (checkConstSize(disp) ) {
genCode2(Code1, 0x70);//short
disp -= 2;
genCode8(disp);
} else {
genCode8(0x0F);
genCode2(Code1, 0x80);//near
disp -= 4;
genCode16(disp);
}
}
else {//jump forward, near only
genCode8(0x0F);
genCode2(Code1, 0x80);
storeJmp();
genCode16(0);
PrintRA='r';
}
return;
}
}
if (CodeType == 7) {//jmp, call
if (TokeType == ALNUME) {
LabelIx=searchLabel();
if (LabelIx > 0) {
disp=LabelAddr[LabelIx];
disp = disp - PC;
disp = disp - Origin;
if (checkConstSize(disp) ) {
if (Code1 == 0xE9) {//jmp only
genCode8(0xEB);//short
disp -= 2;
genCode8(disp);
}
else {
genCode8(Code1);//near
disp -= 3;
genCode16(disp);
}
}
else {
genCode8(Code1);//near
disp -= 3;
genCode16(disp);
}
}
else {//jump forward, near only
genCode8(Code1);
if (PC != 1) storeJmp();//omit jmp main
genCode16(0);
PrintRA='R';
}
return;
}
}
if (CodeType == 8) {//ret,retf
if (TokeType == DIGIT) {
if (Code1 == 0xC3) genCode8(0xC2);//ret n
else genCode8(0xCA);//retf n
genCode16(SymbolInt);
return;
}
genCode8(Code1);
return;
}
if (CodeType == 9) {//push, pop
getOpL();
if (Code1 == 0x50) {//push only
if (Op == IMM) {//push imm8,16
setsflag();
genCode2(0x68, sflag);
if (sflag) genCode8 (imme);
else genCode16(imme);
return;
}
if (Op == ADR) {//push string ABSOLUTE i16
if (disp) {
genCode8(0x68);
genCode16(disp);
return;
}
else {
genCode8(0x68);
storeJmp();
genCode16(0xAAAA);//magic for abs ADR
PrintRA='A';
return;
}
}
}
if (R1Type == SEGREG) {
if (Code1 == 0x58) {//pop only
if (R1No == 1) error1("pop cs not allowed");
}
c = R1No <<3;
if (R1No > 3) {//FS, GS
c += 122; //0x7A
genCode8(0x0F);
}
if (Code1 == 0x50) c +=6;//push
else c += 7;//pop
genCode8(c);
return;
}
checkOpL();//sorts out:ADR,SEGREG resting: REG, MEM
if (Op == MEM) {
if (Code1 == 0x50) {//push word [bp+6]
genCode8(0xFF);
writeEA(6);
}else {
genCode8(0x8F);
writeEA(0);
}
return;
}
if (R1Type == BYTE) reg16error();
if (R1Type == WORD) {//is REG, w/o SEGREG
genCode2(Code1, R1No);
return;
}
syntaxerror();
return;
}
if (CodeType == 11) {//shift, rotate
check2Ops();
if (Op2 == IMM) {
if (imme == 1) {
genCodeW(0xD0);
writeEA(Code1);
return;
}
genCodeW(0xC0);//80186
writeEA(Code1);
genCode8(imme);
return;
}
if (Op2 == REG) {
if (R2Type == BYTE) {
if (R2No == 1) {//CL-REG
if (R1Type == WORD) wflag=1;//hack
genCodeW(0xD2);
writeEA(Code1);
return;
}
}
}
}
if (CodeType == 12) {//int
if (TokeType == DIGIT) {
genCode8(Code1);
genCode8(SymbolInt);
return;
}
}
if (CodeType == 14) {//in, out
implerror();
return;
}
if (CodeType == 15) {//xchg
implerror();
return;
}
if (CodeType == 16) {//loop
implerror();
return;
}
if (CodeType == 30) {//enter i18,i8
genCode8(0xC8);
Op=getOp1();
if (Op == IMM) genCode16(SymbolInt);
else numbererror();
need(',');
Op=getOp1();
if (Op == IMM) genCode8 (SymbolInt);
else numbererror();
return;
}
if (CodeType == 41) {//test
implerror();
return;
}
if (CodeType == 51) {//movsx, movzx=51
implerror();
return;
}
if (CodeType==101) {//ORG nn
if (TokeType != DIGIT) numbererror();
Origin=SymbolInt;
return;
}
if (CodeType == 102) {//section, segment
//getTokeType();//ignore .bss .text .data
AbsoluteLab=0;//nasm resets erevy time
return;
}
if (CodeType == 110) {//absolute
if (TokeType != DIGIT) numbererror();
AbsoluteLab=SymbolInt;
return;
}
if (CodeType == 111) {//name: PROC
if (isInProc == 0) {
printstring("\n\nentering: ");
printstring(ProcName);
isInProc=1;
tmpLabelNamePtr = LabelNamePtr;
tmpLabelMaxIx = LabelMaxIx;
tmpJmpNamePtr = JmpNamePtr;
tmpJmpMaxIx = JmpMaxIx;
} else error1("already in PROC");
return;
}
if (CodeType == 112) {//ENDP
if (isInProc == 0) error1("not in PROC");
printstring("\n\nleaving: ");
printstring(ProcName);
printstring(", loc labels: ");
i = LabelMaxIx - tmpLabelMaxIx;
printunsigned(i);
printstring(", loc jmp forward: ");
i = JmpMaxIx - tmpJmpMaxIx;
printunsigned(i);
fixJmp();
isInProc=0;
LabelNamePtr = tmpLabelNamePtr;//delete local Labels
LabelMaxIx = tmpLabelMaxIx;
JmpNamePtr = tmpJmpNamePtr;//delete local Jmp
JmpMaxIx = tmpJmpMaxIx;
printstring(" JmpMaxIx= ");
printunsigned(JmpMaxIx);
return;
}
if (CodeType == 200) {//db
genDB();
return;
}
error1("Command not implemented or syntax error");
}
int parse() {
LabelNamePtr = &LabelNames;
JmpNamePtr= &JmpNames;
LabelMaxIx=0;
JmpMaxIx=0;
BinLen=0;
isInProc=0;
isPrint=0;
do {//process a new line
PCStart=PC;
OpSize=0;
OpPrintIndex=0;
PrintRA=' ';
getLine();
if (DOS_NoBytes) {
InputPtr = &InputBuf;
getTokeType();//getCode in SymbolUpper,
//set TokeType,isLabel by getName
if (TokeType == ALNUME) {
if (isLabel) {//set in getName
if (isInProc == 0) strcpy(ProcName, Symbol);
storeLabel();
InputPtr++;//remove :
getTokeType();
}
}
if (TokeType == ALNUME) {
lookCode1();
if(CodeType) process();
else getVariable();
skipRest();
}
else if(TokeType >ALNUME)error1(
"Label or instruction expected");
else if(TokeType==DIGIT )error1(
"No digit allowed at start");
printLine();
}
} while (DOS_NoBytes != 0 );
isPrint=1;
}
int getarg() {
int arglen1; int i; char *c;
arglen1=*arglen;
if (arglen1==0) {
cputs(Version1);
cputs(", Usage: AS.COM filename [w/o .S] : ");
exitR(3);
}
i=arglen1+129;
*i=0;
arglen1--;
toupper(argv);
strcpy(namein, argv); strcat1(namein, ".S");
strcpy(namelst,argv); strcat1(namelst,".LST");
strcpy(namebin,argv); strcat1(namebin,".COM");
DOS_ERR=0; PC=0; ErrorCount=0;
asm_fd=openR (namein);
if(DOS_ERR){
cputs("Source file missing: ");
cputs(namein);
exitR(1);
}
lst_fd=creatR(namelst);
if(DOS_ERR){
cputs("can not create list file: ");
cputs(namelst);
exitR(2);
}
printstring(";");
printstring(Version1);
printstring(", Input: "); printstring(namein);
}
int main() {
getarg();
parse();
fixJmpMain();
epilog();
}
<file_sep>char Version1[]="PLA compiler A.COM V1.0.1";//16759 bytes. 32905 stack
//todo:op=reg not recognized
#define IDLENMAX 31//max length of names
#define COLUMNMAX 128//output, input is 100
#define T_NAME 256//the following defines for better clearity
#define T_CONST 257
#define T_STRING 258
#define T_DEFINE 511
#define T_RETURN 512
#define T_IF 513
#define T_ELSE 514
#define T_WHILE 515
#define T_DO 516
#define T_INT 517
#define T_ASM 518
#define T_ASMBLOCK 519
#define T_ASMDIRECT 525
#define T_EMIT 520
#define T_GOTO 521
#define T_VOID 529
#define T_CHAR 530
#define T_SIGNED 531
#define T_UNSIGNED 532
#define T_LONG 533
#define T_INTH 600
#define T_EQ 806
#define T_NE 807
#define T_GE 811
#define T_LE 824
#define T_PLUSPLUS 1219
#define T_MINUSMINUS 1225
#define T_PLUSASS 1230
#define T_MINUSASS 1231
#define T_MULASS 1232
#define T_DIVASS 1233
#define T_ANDASS 1234
#define T_ORASS 1235
#define T_LESSLESS 1240
#define T_GREATGREAT 1241
char isPrint=1;//set screen listing
#define ORGDATA 20000//set it to end of text
unsigned int orgDataOriginal=20000;//must be ORGDATA
unsigned int orgDatai;//actual max of array, must be less than stack
#define COMAX 3000
char co[COMAX];//constant storage
int maxco=0;
int maxco1=0;
#define CMDLENMAX 67
char Symbol[COLUMNMAX];
char fname[CMDLENMAX];
char namein[CMDLENMAX];
char namelst[CMDLENMAX];
char *cloc=0;
int fdin=0;
int fdout=0;
int token=0;
int column=0;
char thechar=0; //reads one char forward
int iscmp=0;
int nconst=0;
int nreturn=0;
int nlabel=0;‚
unsigned int lexval=0;
int typei; char istype;
int signi; char issign;
int widthi; char iswidth;
int wi=0;
#define VARMAX 400//max global and local var
char GType [VARMAX]; // 0=V, 1=*, 2=&,#
char GSign [VARMAX]; // 0=U, 1=S
char GWidth[VARMAX]; // 0, 1, 2, 4
int GData [VARMAX];
#define VARNAMESMAX 4000
char VarNames[VARNAMESMAX];//Space for global and local var names
char *VarNamePtr; //first free position
int GTop=1; //0 = empty
// int LStart=1 ; //max global var
int LTop=1;
#define FUNCMAX 300//max functions
#define FUNCTIONNAMESMAX 3000//Space for preceeding functon names
char FunctionNames[FUNCTIONNAMESMAX];
char *FunctionNamePtr; //first free position in FunctionNames
int FunctionMaxIx=0; //number of functions
char fgetsdest[COLUMNMAX];
unsigned char *fgetsp=0;
unsigned int lineno=1;
unsigned char *pt=0;
unsigned char *p1=0;
int DOS_ERR=0;
int DOS_NoBytes=0;
char DOS_ByteRead=0;
int ireg1;
int mod2;
int ireg2;
int writetty() {//char in AL
ah=0x0E;
asm push bx
bx=0; //page in BH
inth 0x10;
asm pop bx
}
int putch(char c) {
if (c==10) {// LF
al=13; // CR, write CR first and then LF
writetty();
}
al=c;
writetty();
}
int cputs(char *s) {
char c;
while(*s) {
c=*s;
putch(c);
s++;
}
}
int mkneg(int n) {
n; // ax=n;
asm neg ax
}
int DosInt() {
inth 0x21;
__emit__(0x73, 04); //jnc over DOS_ERR++
DOS_ERR++;
}
int openR (char *s) {
dx=s;
ax=0x3D02;
DosInt();
}
int creatR(char *s) {
dx=s;
cx=0;
ax=0x3C00;
DosInt();
}
int fcloseR(int fd) {
bx=fd;
ax=0x3E00;
DosInt();
}
int exitR (char c) {
ah=0x4C;
al=c;
DosInt();
}
int readRL(char *s, int fd, int len){
dx=s;
cx=len;
bx=fd;
ax=0x3F00;
DosInt();
}
int fputcR(char *n, int fd) {
asm lea dx, [bp+4]; *n todo: why not mov
asm mov cx, 1; cx=1;
asm mov bx, [bp+6]; bx=fd;
asm mov ax, 16384; ax=0x4000;
DosInt();
}
int letter(char c) {
if (c=='_') return 1;
if (c=='.') return 1;
if (c=='?') return 1;
if (c=='$') return 1;
if (c> 'z') return 0;
if (c< '@') return 0;// at included
if (c> 'Z') { if (c< 'a') return 0; }
return 1;
}
int digit(char c){
if(c<'0') return 0;
if(c>'9') return 0;
return 1;
}
int alnum(char c) {
if (digit (c)) return 1;
if (letter(c)) return 1;
return 0;
}
int strlen(char *s) { int c;
c=0;
while (*s!=0) {s++; c++;}
return c;
}
int strcpy(char *s, char *t) {
do { *s=*t; s++; t++; }
while (*t!=0);
*s=0;
return s;
}
int eqstr(char *p, char *q) {
while(*p) {
if (*p != *q) return 0;
p++;
q++;
}
if(*q) return 0;
return 1;
}
int strcat(char *s, char *t) {
while (*s != 0) s++;
strcpy(s, t);
}
int toupper(char *s) {
while(*s) {
if (*s >= 'a') if (*s <= 'z') *s=*s-32;
s++;
}
}
int instr1(char *s, char c) {
while(*s) {
if (*s==c) return 1;
s++;
}
return 0;
}
int eprc(char c) {
*cloc=c;
cloc++;
}
int eprs(char *s) {
char c;
while(*s) {
c=*s;
eprc(c);
s++;
}
}
int prc(unsigned char c) {
if (isPrint) {
if (c==10) {
asm mov ax, 13
writetty();
}
asm mov al, [bp+4]; al=c;
writetty();
}
fputcR(c, fdout);
}
int prscomment(unsigned char *s) {
unsigned char c;
while(*s){
c=*s;
prc(c);
s++;
}
}
int printstring(unsigned char *s) {
unsigned char c; int com;
com=0;
while(*s) {
c=*s;
if (c==34) if (com) com=0;
else com=1;
if (c==92) {
if (com==0) {
s++;
c=*s;
if (c=='n') c=10;
if (c=='t') c= 9;
}
}
prc(c);
s++;
}
}
int eprnum(int n){//for docall procedure
int e;
if(n<0) {
eprc('-');
n=mkneg(n);
}
if (n >= 10) {
e=n/10;
eprnum(e);
}
n=n%10;
n=n+'0';
eprc(n);
}
int printinteger (int n){
int e;
if(n<0) { prc('-'); n=mkneg(n); }
if (n >= 10) {
e=n/10;
printinteger(e);
}
n=n%10;
n += '0';
prc(n);
}
int printunsigned(unsigned int n) {
unsigned int e;
if (n >= 10) {
e=n/10;
printunsigned(e);
}
n = n % 10; /*unsigned mod*/
n += '0';
prc(n);
}
int end1(int n) {
fcloseR(fdin);
fcloseR(fdout);
exitR(n);
}
int error1(char *s) {
isPrint=1;
lineno--;
printstring("\n ");
prscomment(&fgetsdest);
printstring(";Line: ");
printunsigned(lineno);
printstring(" ************** ERROR: ");
printstring(s);
printstring(" in column: ");
printunsigned(column);
printstring("\nToken: ");
printunsigned(token);
printstring(", Symbol: ");
printstring(Symbol);
end1(1);
}
int printinputline() {
int col;
col=0;
fgetsp=&fgetsdest;
do {
DOS_NoBytes=readRL(&DOS_ByteRead, fdin, 1);
if (DOS_NoBytes == 0) return;
*fgetsp=DOS_ByteRead;
fgetsp++;
col++;
if (col >100) error1("input line longer than 100 char");
}
while (DOS_ByteRead != 10);
*fgetsp=0;
printstring("\n;-");
printunsigned(lineno);
prc(' ');
lineno++;
prscomment(&fgetsdest);
}
int fgets1() {
char c;
c=*fgetsp;
if (c==0) {
printinputline();
if (DOS_NoBytes == 0) return 0;
fgetsp=&fgetsdest;
c=*fgetsp;
column=0;
}
fgetsp++;
column++;
return c;
}
int next() {
char r;
r = thechar;
thechar = fgets1();
return r;
}
int storeVarName() {
unsigned int i;
VarNamePtr=strcpy(VarNamePtr, Symbol);
VarNamePtr++;
i = VarNamePtr - &VarNames;
i += IDLENMAX;
if (i > VARNAMESMAX) error1("too many variable names");
}
/*
int searchVarName() {
char *p; int i;
p = &VarNames;
i=1;//start with 1
while (i < VARMAX) {
if (eqstr(p, Symbol)) return i;
p=strlen(p) + p;
p++;
i++;
}
return 0;
}
*/
int getVarName(unsigned int i) {
int j; char *p;
j = 1;
p = &VarNames;
while (j < i) {
while (*p) p++;
p++;
j++;
}
return p;
}
int printName(unsigned int i) {
if (i < GTop) {
i=getVarName(i);
printstring(i);
}
else {
printstring("[bp");
i = GData[i];
if (i>0) prc('+');
printinteger(i);
prc(']');
}
}
int ifEOL(char c) {//unix LF, win CRLF= 13/10, mac CR
if (c == 10) return 1;//LF
if (c == 13) {//CR
if (thechar == 10) c=next();
return 1;
}
return 0;
}
char symboltemp[80];
int getlex() {
char c; char *p;
int i; int j;
g1: c=next();
if (c == 0) return 0;
if (c <= ' ') goto g1;
if (c=='=') {if(thechar=='=') {next(); return T_EQ; }}
if (c=='!') {if(thechar=='=') {next(); return T_NE; }}
if (c=='<') {if(thechar=='=') {next(); return T_LE; }}
if (c=='>') {if(thechar=='=') {next(); return T_GE; }}
if (c=='<') {if(thechar=='<') {next(); return T_LESSLESS; }}
if (c=='>') {if(thechar=='>') {next(); return T_GREATGREAT;}}
if (c=='+') {if(thechar=='+') {next(); return T_PLUSPLUS; }}
if (c=='-') {if(thechar=='-') {next(); return T_MINUSMINUS;}}
if (c=='+') {if(thechar=='=') {next(); return T_PLUSASS; }}
if (c=='-') {if(thechar=='=') {next(); return T_MINUSASS; }}
if (c=='&') {if(thechar=='=') {next(); return T_ANDASS; }}
if (c=='|') {if(thechar=='=') {next(); return T_ORASS; }}
if (c=='*') {if(thechar=='=') {next(); return T_MULASS; }}
if (c=='/') {if(thechar=='=') {next(); return T_DIVASS; }}
if (instr1("()[]{},;*:%-><=+!&|#?", c)) return c ;
if (c == '/') {
if (thechar == '/') {
do c=next();
while(ifEOL(c)==0) return getlex();
}
}
if (c == '/') {
if (thechar == '*') {
g2: c=next();
if (c != '*') goto g2;
if (thechar != '/') goto g2;
c=next();
return getlex();
} else return '/';
}
if (c == '"') {
p=&Symbol;
c=next();
while (c != '"') {
*p=c;
p++;
c=next();
}
*p=0;
return T_STRING;
}
if (digit(c)) {
lexval=0;
lexval=c-'0'; // lexval=int hi=0, c=char
if (thechar=='x') thechar='X';
if (thechar=='X') {
next();
while(alnum(thechar)) {
c=next();
if(c>96) c=c-39;
if (c>64) c=c-7;
c=c-48;
lexval=lexval << 4; // * 16
i=0;
i=c;
lexval=lexval+i;
}
}else {
while(digit(thechar)) {
c=next();
c=c-48;
lexval=lexval*10;
i=0;
i=c;
lexval=lexval+i;
}
}
return T_CONST;
}
if (c==39) {
lexval=next();
if (lexval==92) {
lexval=next();
if (lexval=='n') lexval=10;
if (lexval=='t') lexval= 9;
if (lexval=='0') lexval= 0;
}
next();
return T_CONST;
}
if (alnum(c)) {
strcpy(symboltemp, Symbol);
p=&Symbol;
*p=c;
p++;
while(alnum(thechar)) {
c=next();
*p=c;
p++;
}
*p=0;
if (eqstr(Symbol,"signed" )) return T_SIGNED;
if (eqstr(Symbol,"unsigned")) return T_UNSIGNED;
if (eqstr(Symbol,"void" )) return T_VOID;
if (eqstr(Symbol,"int" )) return T_INT;
if (eqstr(Symbol,"long" )) return T_LONG;
if (eqstr(Symbol,"inth" )) return T_INTH;
if (eqstr(Symbol,"char" )) return T_CHAR;
if (eqstr(Symbol,"asm" )) return T_ASM;
if (eqstr(Symbol,"__asm" )) return T_ASMBLOCK;
if (eqstr(Symbol,"push" )) return T_ASMDIRECT;
if (eqstr(Symbol,"pop" )) return T_ASMDIRECT;
if (eqstr(Symbol,"iret" )) return T_ASMDIRECT;
if (eqstr(Symbol,"ret" )) return T_ASMDIRECT;
if (eqstr(Symbol,"cli" )) return T_ASMDIRECT;
if (eqstr(Symbol,"sti" )) return T_ASMDIRECT;
if (eqstr(Symbol,"__emit__")) return T_EMIT;
if (eqstr(Symbol,"return" )) return T_RETURN;
if (eqstr(Symbol,"if" )) return T_IF;
if (eqstr(Symbol,"else" )) return T_ELSE;
if (eqstr(Symbol,"while" )) return T_WHILE;
if (eqstr(Symbol,"do" )) return T_DO;
if (eqstr(Symbol,"goto" )) return T_GOTO;
if (eqstr(Symbol,"define" )) return T_DEFINE;
i=0;//convert define to value
while (i < GTop) {
j=getVarName(i);
if (eqstr(Symbol,j)) {
if (GType[i]=='#') {
lexval=GData[i];
strcpy(Symbol, symboltemp);
return T_CONST;
}
}
i++;
}
return T_NAME; }
error1("Input item not recognized");
}
int istoken(int t) {
if (token == t) {
token=getlex();
return 1;
}
return 0;
}
int expect(int t) {
if (istoken(t)==0) {
*cloc=0;
printstring(co);
printstring("\nExpected ASCII(dez): ");
printinteger(t);
error1(" not found");
}
}
int v(unsigned int i) {//value
if (i < GTop) prc('[');
printName(i);
if (i < GTop) prc(']');
}
int checknamelen() {
int i;
i=strlen(Symbol);
if (i > IDLENMAX) error1("Item name is too long)");
}
int checkName() {
unsigned int i; unsigned int j;
i=GTop;
while(i<LTop) {//todo look for local var first
j=getVarName(i);
if(eqstr(Symbol,j))return i;
i++;
}
i=1;
while(i<GTop) {
j=getVarName(i);
if(eqstr(Symbol,j))return i;
i++;
}
return 0;
}
int searchname() {
unsigned int i;
i=checkName();
if (i == 0) error1("Variable unknown");
return i;
}
int name1() {
if (token!=T_NAME) error1("Name expected");
token=getlex();
}
int typeName() {
int m; //0=V,1=*,2=&
issign='S';
if(istoken(T_SIGNED)) issign='S';
if(istoken(T_UNSIGNED)) issign='U';
iswidth=2;
if(istoken(T_VOID)) iswidth=0;
if(istoken(T_CHAR)) iswidth=1;
if(istoken(T_INT)) iswidth=2;
if(istoken(T_LONG)) iswidth=4;
istype='V';
m=0;
if(istoken('*')) {istype='*'; m=1;}
if(istoken('&')) {istype='&'; m=2;}
name1();
return m;
}
int gettypes(int i) {
char c;
c=GSign [i];
if (c=='S') signi =1; else signi =0;
c=GWidth[i];
widthi=0;
wi=0;
if (c==1) {widthi=1;wi=1;}
if (c==2) {widthi=2;wi=2;}
if (c==4) {widthi=4;wi=4;}
c=GType [i];
typei=0;
if (c=='*') {typei=1;wi=2;}
if (c=='&') typei=2;
return i;
}
int addlocal() {
if(LTop >= VARMAX) error1("Local variable table full");
if (checkName() != 0) error1("Variable already defined");
GSign[LTop]=issign;
GWidth[LTop]=iswidth;
GType[LTop]=istype;
pt=getVarName(LTop);
strcpy(pt, Symbol);
storeVarName();
}
int cmpneg(int ids) {
if(iscmp==T_EQ) printstring("\n jne ."); //ZF=0
else if(iscmp==T_NE) printstring("\n je ."); //ZF=1
else if(iscmp==T_LE) if (ids) printstring("\n jg .");//ZF=0 SF=O
else printstring("\n ja .");//ZF=0 CF=0
else if(iscmp==T_GE) if (ids){printstring(" ;unsigned : ");
printunsigned(ids);
printstring("\n jl .");}//SF!=O
else {printstring(" ;unsigned : ");
printunsigned(ids);
printstring("\n jb .");}//jb=jc=CF=1
else if(iscmp=='<' ) printstring("\n jge ."); //SF=O
else if(iscmp=='>' ) printstring("\n jle ."); //ZF=1 | SF!=O
else error1("internal error compare unknown in CMPNEG()");
}
int isrelational() {
if (token==T_EQ) goto w;
if (token==T_NE) goto w;
if (token==T_LE) goto w;
if (token==T_GE) goto w;
if (token=='<' ) goto w;
if (token=='>' ) goto w;
return 0;
w: iscmp=token;
token=getlex();
return 1;
}
int checkreg() { // >=17 = 16bit, >=47 = 32bit
if (strlen(Symbol) < 2) return 0;
if (eqstr(Symbol,"al")) return 1; if (eqstr(Symbol,"cl")) return 3;
if (eqstr(Symbol,"dl")) return 5; if (eqstr(Symbol,"bl")) return 7;
if (eqstr(Symbol,"ah")) return 9; if (eqstr(Symbol,"ch")) return 11;
if (eqstr(Symbol,"dh")) return 13; if (eqstr(Symbol,"bh")) return 15;
if (eqstr(Symbol,"ax")) return 17; if (eqstr(Symbol,"cx")) return 19;
if (eqstr(Symbol,"dx")) return 21; if (eqstr(Symbol,"bx")) return 23;
if (eqstr(Symbol,"sp")) return 25; if (eqstr(Symbol,"bp")) return 27;
if (eqstr(Symbol,"si")) return 29; if (eqstr(Symbol,"di")) return 31;
if (eqstr(Symbol,"es")) return 33; if (eqstr(Symbol,"cs")) return 35;
if (eqstr(Symbol,"ss")) return 37; if (eqstr(Symbol,"ds")) return 39;
if (eqstr(Symbol,"fs")) return 41; if (eqstr(Symbol,"gs")) return 43;
// (eqstr(Symbol,"ip")) return 45;
if (strlen(Symbol) > 3) return 0;
if (eqstr(Symbol,"eax")) return 47; if (eqstr(Symbol,"ecx")) return 50;
if (eqstr(Symbol,"edx")) return 53; if (eqstr(Symbol,"ebx")) return 56;
if (eqstr(Symbol,"esp")) return 59; if (eqstr(Symbol,"ebp")) return 62;
if (eqstr(Symbol,"esi")) return 65; if (eqstr(Symbol,"edi")) return 68;
// if (eqstr(Symbol,"cr0")) return 71;
return 0;
}
char printregstr[]
="*alcldl<KEY>";
int printreg(int i) {
unsigned int k; unsigned char c;
k = &printregstr + i;
c=*k;
prc(c);
i++;
k = &printregstr + i;
c=*k;
prc(c);
if (i > 47) {
i++;
k = &printregstr + i;
c=*k;
prc(c);
}
}
char ops[5];
int doreg1(int iscmp1) {
int i;
if (istoken('=')) strcpy(ops, "mov");
if (istoken(T_PLUSASS)) strcpy(ops, "add");
if (istoken(T_MINUSASS)) strcpy(ops, "sub");
if (istoken(T_ANDASS)) strcpy(ops, "and");
if (istoken(T_ORASS)) strcpy(ops, "or" );
if (istoken(T_LESSLESS)) strcpy(ops, "shl");
if (istoken(T_GREATGREAT)) strcpy(ops, "shr");
if (iscmp1 == 1) {
token=getlex();
if (isrelational() ==0) error1("Relational expected");
strcpy(ops, "cmp");
}
printstring("\n ");
printstring(ops);
printstring(" ");
printreg(ireg1); //todo
printstring(", ");
if (istoken(T_CONST)) {
printunsigned(lexval);
goto reg1;
}
mod2=typeName();
ireg2=checkreg();
if (ireg2) {
printreg(ireg2);
goto reg1;
}
i=searchname();
if (mod2 == 2) printName(i);
else v(i);
reg1: if (iscmp1 == 1) {
cmpneg(0);
printstring(fname);
expect(')');
}
}
int compoundass(char *op, int mode, int id1) {
if(mode) error1("only scalar variable allowed");
printstring("\n ");
printstring(op);
printstring(" ");
gettypes(id1);
if (wi==2) printstring("word");
else printstring("byte");
v(id1);
printstring(", ");
expect(T_CONST);
printunsigned(lexval);
}
int dovar1(int mode, int op, int ixarr, int id1) {
gettypes(id1);
if (mode==1) {// * = ptr
printstring("\n mov bx, ");
v(id1); printstring("\n ");
printstring(op);
if(widthi == 1) printstring(" al, [bx]\n mov ah, 0");
if(widthi == 2) printstring(" ax, [bx]");
return;
}
if (mode==2){// & = adr
printstring("\n ");
printstring(op);
printstring(" ax, ");
printName(id1);
return;
}
if (ixarr) {//array
printstring("\n mov bx, ");
v(ixarr);
if (wi==2) printstring("\n shl bx, 1");
printstring("\n ");
printstring(op);
if (wi==2) printstring(" ax, ");
else printstring(" al, ");
prc('[');
printName(id1);
printstring(" + bx]");
return;
}
printstring("\n ");
printstring(op);
if(wi==1) printstring(" al, ");
if(wi==2) printstring(" ax, ");
if(wi==4) printstring(" eax, ");
v(id1);
}
int rterm(char *op) {
int mode; int opint; int ixarr; int id1;
if (istoken(T_CONST)) {
printstring("\n ");
printstring(op);
if (wi==1) printstring(" al, ");
if (wi==2) printstring(" ax, ");
if (wi==4) printstring(" eax, ");
printunsigned(lexval);
return;
}
mode=typeName();
id1=searchname();
ixarr=0;
if (istoken('[')) {
ixarr=searchname();
expect(T_NAME);
expect(']');
gettypes(ixarr);
if (widthi != 2) error1("Array index must be int");
}
if (eqstr(Symbol,"ax")) return;
opint=op;
dovar1(mode, opint, ixarr, id1);
}
int doassign(int mode, int i, int ixarr, int ixconst) {
gettypes(i);
if (mode==1) {// * = ptr
printstring("\n mov bx, ");
v(i);
if (widthi == 2) printstring("\n mov [bx], ax");
else printstring("\n mov [bx], al");
return;
}
if (mode==2) {// & = adr
printstring("\n mov ");
printName(i);
printstring(", ax");
return;
}
if (ixarr) {
printstring("\n mov bx, ");
if(ixconst) printunsigned(ixarr);
else v(ixarr);
if (wi==2) printstring("\n shl bx, 1");
printstring("\n mov [");
printName(i);
if (wi==2) printstring("+bx], ax");
else printstring("+bx], al");
return;
}
if (wi==1){
printstring("\n mov ");
if(i<GTop) printstring("byte ");
v(i);
printstring(", al");
return;
}
if (wi==2){
printstring("\n mov ");
if(i<GTop) printstring("word ");
v(i);
printstring(", ax");
return;
}
if (wi==4){
printstring("\n mov ");
if(i<GTop) printstring("dword ");
v(i);
printstring(", eax");
return;
}
}
int domul(int ids) {
if (ids) rterm("imul");
else {
if (istoken(T_CONST)) {
printstring("\n mov bx, ");
printunsigned(lexval);
printstring("\n mul bx");
}
else error1("with MUL only const number as multipl. allowed");
}
}
int doidiv(int ids) {
int mode; int id1;
if (istoken(T_CONST)) {
printstring("\n mov bx, ");
printunsigned(lexval);
if (ids) printstring("\n cwd\n idiv bx");
else printstring("\n mov dx, 0\n div bx");
}
else {
mode=typeName();
id1=searchname();
if (mode) error1("only const number or int as divisor allowed");
gettypes(id1);
if (typei) error1("only int as simple var divisor allowed");
if (wi!=2) error1("only int, no byte as divisor allowed");
printstring("\n mov bx, ");
v(id1);
if (ids) printstring("\n cwd\n idiv bx");
else printstring("\n mov dx, 0\n div bx");
}
}
int domod(int ids) {
doidiv(ids);
printstring("\n mov ax, dx");
}
int docalltype[10]; int docallvalue[10];
char procname[17]; // 1=CONST, 2=String, 3=&, 4=Name
int docall() {
int i; int narg; int t0; int n0; int sz32;
narg=0;
sz32=0;
checknamelen();
strcpy(&procname, Symbol);
expect('(');
if (istoken(')') ==0 ) {
do {
narg++;
if (narg >9 ) error1("Max. 9 parameters");
t0=0;
if(istoken(T_CONST)) {
t0=1;
n0=lexval;
}
if(istoken(T_STRING)){
t0=2;
n0=nconst;
eprs("\n");
eprs(fname);
eprc(95);
eprnum(nconst);
eprs(" db ");
eprc(34);
eprs(Symbol);
eprc(34);
eprs(",0");
nconst++;
}
if(istoken('&')) {
t0=3;
name1();
n0=searchname();
}
if(istoken(T_NAME)) {
t0=4;
n0=searchname();
p1=>ype;
p1=p1+n0;
if (*p1=='&') t0=3;
}
if (t0==0) error1("parameter not recognized (no * allowed)");
docalltype [narg] = t0;
docallvalue[narg] = n0;
} while (istoken(','));
expect(')');
i=narg;
do {
t0 = docalltype [i];
n0 = docallvalue[i];
if(t0==1){
printstring("\n push ");
printunsigned(n0);
}
if(t0==2){
printstring("\n push ");
printstring(fname);
prc(95);
printunsigned(n0);
}
if(t0==3){
printstring("\n lea ax, ");
v(n0);
printstring("\n push ax");
}
if(t0==4){
gettypes(n0);
if(wi==2) {
printstring("\n push word ");
v(n0);
}
else {
printstring("\n mov al, byte ");
v(n0);
printstring("\n mov ah, 0\n push ax");
}
}
if(t0==5){
printstring("\n push ");
printreg(n0);
if (n0 >= 47) sz32+2;
}
i--;
} while (i > 0);
}
printstring("\n call ");
printstring(&procname);
if (narg>0) {
printstring("\n add sp, ");
narg=narg+narg;
narg=narg+sz32;
printunsigned(narg);
}
}
int expr() {
int mode; int id1;
int ixarr; int ixconst;
int ids; int isCONST;
int i; unsigned char *p;
if (istoken(T_CONST)) {// constant ;
printstring("\n mov ax, ");
printunsigned(lexval);
return 4;
}
mode=typeName(); /*0=variable, 1=* ptr, 2=& adr*/
ireg1=checkreg();//todo
if (ireg1) {
doreg1(0);
return;
}
if (token=='(') {
docall();
goto e1;
}
id1=searchname();
gettypes(id1);
ids=signi;
ixarr=0;
ixconst=0;
if (istoken('[')) {
if (istoken(T_CONST)) {
ixconst=1;
ixarr=lexval;
expect(']');
}
else {
ixarr=searchname();
expect(T_NAME);
expect(']');
gettypes(ixarr);
if (widthi != 2) error1("Array index must be number or int");
}
}
if (istoken(T_PLUSPLUS )) {
if(mode)error1("Only var allowed");
printstring("\n inc ");
if (wi==2) printstring("word"); else printstring("byte");
v(id1);
goto e1;
}
if (istoken(T_MINUSMINUS)) {
if(mode)error1("Only var allowed");
printstring("\n dec ");
if (wi==2) printstring("word"); else printstring("byte");
v(id1);
goto e1;
}
if (istoken(T_PLUSASS )) {compoundass("add", mode, id1); goto e1; }
if (istoken(T_MINUSASS)) {compoundass("sub", mode, id1); goto e1; }
if (istoken(T_ANDASS )) {compoundass("and", mode, id1); goto e1; }
if (istoken(T_ORASS )) {compoundass("or" , mode, id1); goto e1; }
if (istoken(T_MULASS )) error1("not implemented");
if (istoken(T_DIVASS )) error1("not implemented");
if (istoken('=')) {
expr();
doassign(mode, id1, ixarr, ixconst);
goto e1;
}
dovar1(mode, "mov", ixarr, id1);
e1: if (istoken('+')) rterm("add");
else if (istoken('-')) rterm("sub");
else if (istoken('&')) rterm("and");
else if (istoken('|')) rterm("or" );
else if (istoken(T_LESSLESS)) rterm("shl");
else if (istoken(T_GREATGREAT)) rterm("shr");
else if (istoken('*')) domul (ids);
else if (istoken('/')) doidiv(ids);
else if (istoken('%')) domod (ids);
if (isrelational()) {
rterm("cmp");
cmpneg(ids);
}
return 0;
}
int pexpr() {//called from if, do, while
expect('(');
iscmp=0;
if (token==T_NAME) {
ireg1=checkreg();
if (ireg1) {
doreg1(1);
return;
}
}
expr();
if (iscmp==0) printstring("\n or al, al\n je .");
printstring(fname);
expect(')');
}
int prlabel(int n) {
printstring("\n.");
printstring(fname);
printunsigned(n);
prc(':');
}
int prjump (int n) {
printstring("\n jmp .");
printstring(fname);
printunsigned(n);
}
int stmt() {
int c; char cha;
int jdest; int tst; int jtemp;
if(istoken('{')) {
while(istoken('}')==0) stmt();
}
else if(istoken(T_IF)) {
pexpr();
nlabel++;
jdest=nlabel;
printinteger(jdest);
stmt();
if (istoken(T_ELSE)) {
nlabel++;
tst=nlabel;
prjump(tst);
prlabel(jdest);
stmt();
prlabel(tst);
}
else prlabel(jdest);
}
else if(istoken(T_DO)) {
nlabel++;
jdest=nlabel;
prlabel(jdest);
stmt();
expect(T_WHILE);
pexpr();
nlabel++;
jtemp=nlabel;
printinteger(jtemp);
prjump(jdest);
prlabel(jtemp);
}
else if(istoken(T_WHILE)) {
nlabel++;
jdest=nlabel;
prlabel(jdest);
pexpr();
nlabel++;
tst=nlabel;
printinteger(tst);
stmt();
prjump(jdest);
prlabel(tst);
}
else if(istoken(T_GOTO)) {
printstring("\n jmp .");
name1();
printstring(Symbol);
expect(';');
}
else if(token==T_ASM) {
printstring("\n");
c=next();
while(c != '\n') {
prc(c);
c=next();
};
token=getlex();
}
else if(token==T_ASMDIRECT) {
printstring("\n");
printstring(Symbol);
c=next();
while(c != '\n') {
prc(c);
c=next();
};
token=getlex();
}
else if(istoken(T_ASMBLOCK)) {
if (token== '{' ) {
printstring("\n"); cha=next();
while(cha!= '}') {
prc(cha);
cha=next();
}
token=getlex();
} else error1("Curly open expected");
}
else if(istoken(T_INTH)) {
printstring("\n int ");
expect(T_CONST);
printunsigned(lexval);
expect(';');
}
else if(istoken(T_EMIT)) {
printstring("\n db ");
L1: token=getlex();
printunsigned(lexval);
token=getlex();
if (token== ',') {
prc(',');
goto L1;
}
expect(')');
}
else if(istoken(';')) { }
else if(istoken(T_RETURN)) {
if (token!=';') expr();
printstring("\n jmp .retn");
printstring(fname);
nreturn++;
expect(';');
}
else if(thechar==':') {
printstring("\n."); // Label
printstring(Symbol); prc(':');
expect(T_NAME);
expect(':');
}
else {expr();; expect(';'); }
}
int isvariable() {
if(token==T_SIGNED) goto v1;
if(token==T_UNSIGNED) goto v1;
if(token==T_CHAR) goto v1;
if(token==T_INT) goto v1;
if(token==T_LONG) goto v1;
return 0;
v1: return 1;
}
//***************************************************************
int listvar(unsigned int i) {
unsigned int j;
char c;
printstring("\n;");
printunsigned(i);
prc(32);
c=GType [i];
if(c=='V')printstring("var ");
if(c=='*')printstring("ptr ");
if(c=='&')printstring("arr ");
if(c=='#')printstring("def ");
c=GSign [i];
if(c=='S')printstring("sign ");
if(c=='U')printstring("unsg ");
c=GWidth[i];
if(c== 0)printstring("NULL " );
if(c== 1)printstring("byte " );
if(c== 2)printstring("word " );
if(c== 4)printstring("long " );
pt=getVarName(i);
// j=i*32;
// pt=&GNameField + j;
printstring(pt);
if(GType[i]=='#') {
prc('=');
j=GData[i];
printunsigned(j);
}
if(GType[i]=='&') {
prc('[');
j=GData[i];
printunsigned(j);
prc(']');
}
if (i >= GTop) {
printstring(" = bp");
j=GData[i];
if (j > 0) prc('+');
printinteger(j);
}
}
int listproc() {
int i;
if (LTop > GTop) {
printstring("\n;Function : ");
printstring(fname);
printstring(", Number local Var: ");
i=LTop - GTop;
printunsigned(i);
printstring("\n; # type sign width local variables");
i=GTop;
while (i < LTop) {
listvar(i);
i++;
}
}
}
int searchFunction() {
int FunctionIndex; char *p;
p= &FunctionNames;
FunctionIndex=1; //0=function name not found
while (FunctionIndex <= FunctionMaxIx ) {
if (eqstr(p, Symbol)) return FunctionIndex;
p = strlen(p) + p;
p++;
FunctionIndex++;
}
return 0; //no function found
}
int storeFunction() {
unsigned int i;
FunctionMaxIx++; //leave 0 empty for function not notfound
if (FunctionMaxIx >= FUNCMAX) error1("Function table full");
FunctionNamePtr=strcpy(FunctionNamePtr, Symbol);
FunctionNamePtr++; //function name is saved
i = FunctionNamePtr - &FunctionNames;
i += IDLENMAX;
if (i >= FUNCTIONNAMESMAX) error1("too many function names");
}
int dofunc() {
int nloc; unsigned int j;int narg;
int VarNamePtrLocalStart;
cloc=&co;
checknamelen();
strcpy(fname, Symbol);
if(searchFunction()) error1("Function already defined");
storeFunction();
printstring("\n\n");
printstring(Symbol);
printstring(": PROC");
expect('(');
// LStart=GTop;
LTop=GTop;
VarNamePtrLocalStart=VarNamePtr;
if (istoken(')')==0) {
narg=2;
do {
typeName();
addlocal();
narg+=2;
GData[LTop]=narg;
if (iswidth == 4) narg+=2;
LTop++;
}
while (istoken(','));
expect(')');
}
expect('{'); /*body*/
nloc=0;
nreturn=0;
nconst=0;
while(isvariable()) {
do {
typeName();
checknamelen();
addlocal();
nloc-=2;
if (iswidth == 4) nloc-=2;
GData[LTop]=nloc;
if (istoken('[')){
istype='&';
GType[LTop]='&';
expect(T_CONST);
expect(']');
nloc=nloc-lexval;
nloc+=2;
GData[LTop]=nloc;
}
LTop++;
} while (istoken(','));
expect(';');
}
listproc();
if (LTop>GTop){
printstring(";\n ENTER ");
nloc=mkneg(nloc);
printunsigned (nloc);
printstring(",0");
}
while(istoken('}')==0) stmt();
if (nreturn) {
printstring("\n .retn");
printstring(fname);
prc(':');
}
if (LTop > GTop) printstring("\n LEAVE");
printstring("\n ret");
*cloc=0;
printstring(co);
maxco1=strlen(co);
if (maxco1 > maxco) maxco=maxco1;
printstring("\nENDP");
VarNamePtr=VarNamePtrLocalStart;//delete local names
}
char doglobName[IDLENMAX];
int doglob() {
int i; int j; int isstrarr;
isstrarr=0;
if (GTop >= VARMAX) error1("Global table full");
if (iswidth == 0) error1("no VOID as var type");
checknamelen();
if (checkName() != 0) error1("Variable already defined");
if (istoken('[')) {
istype='&';
if (istoken(T_CONST)) {
printstring("\nsection .bss\nabsolute ");
printunsigned(orgDatai);
printstring("\n"); printstring(Symbol);
if (iswidth==1) printstring(" resb ");
if (iswidth==2) printstring(" resw ");
if (iswidth==4) printstring(" resd ");
printunsigned(lexval);
printstring("\nsection .text");
orgDatai=orgDatai+lexval;
if (iswidth==2) orgDatai=orgDatai+lexval;
if (iswidth==4) {i= lexval * 3; orgDatai=orgDatai + i;}
GData[GTop]=lexval;
expect(']');
}else {
expect(']');
if (iswidth != 1) error1("Only ByteArray allowed");
printstring("\n");
printstring(Symbol);
printstring(" db ");
isstrarr=1;
strcpy(doglobName, Symbol);//save Symbol name
expect('=');
if (istoken(T_STRING)) {
prc(34);
prscomment(Symbol);
prc(34);
printstring(",0");
i=strlen(Symbol);
GData[GTop]=i;
}
else if (istoken('{' )) {
i=0;
do {
if(i) prc(',');
expect(T_CONST);
printunsigned(lexval);
i=1;
}
while (istoken(','));
expect('}');
}
else error1("String or number array expected");
};
}else { //expect('=');
printstring("\n");
printstring(Symbol);
if (istype=='*') printstring(" dw ");
else {
if (iswidth==1) printstring(" db ");
else if (iswidth==2) printstring(" dw ");
else printstring(" dd ");
}
if(istoken('-')) prc('-');
if (istoken('=')) {
expect(T_CONST);
printunsigned(lexval);
}else printunsigned(0);
}
GSign[GTop]=issign;
GWidth[GTop]=iswidth;
GType[GTop]=istype;
pt=getVarName(GTop);
if (isstrarr) strcpy(pt, doglobName);
else strcpy(pt, Symbol);
if (isstrarr) strcpy(Symbol, doglobName);
storeVarName();
GTop++;
expect(';');
}
int dodefine() {
expect(T_NAME);
if (token==T_CONST) {
if (GTop >= VARMAX) error1("global table (define) full");
checknamelen();
if (checkName() != 0) error1("#Define var already defined");
if (eqstr(Symbol, "ORGDATA")) {
orgDataOriginal=lexval;
orgDatai=lexval;
expect(T_CONST);
return;
}
GSign [GTop]='U';
GWidth[GTop]=1;
GType [GTop]='#';
pt=getVarName(GTop);
strcpy(pt, Symbol);
storeVarName();
GData[GTop]=lexval;
expect(T_CONST);
GTop++;
}
}
int parse() {
token=getlex();
do {
if (token <= 0) return 1;
if (istoken('#')) {
if (istoken(T_DEFINE)) dodefine();
else error1("define expected");
}
else{
typeName();
if (token=='(') dofunc();
else doglob(); }
} while(1);
}
char *arglen=0x80; char *argv=0x82;
int getarguments() {
int arglen1; unsigned int i; char *c;
isPrint=1;
arglen1=*arglen;
if (arglen1 == 0) {
cputs(Version1);
cputs(" Usage: A.COM in_file[.C]: ");
exitR(3);
}
i=arglen1+129;
*i=0;
arglen1--;
toupper(argv);
strcpy(namein, argv);
if (instr1(namein, '.') == 0) strcat(namein, ".C");
strcpy(namelst, namein);
i=strlen(namelst);
i--;
c=&namelst+i;
*c='S';
}
int openfiles() {
fdin=openR (namein);
if(DOS_ERR){
cputs("Source file missing (.C): ");
cputs(namein);
exitR(1);
}
fdout=creatR(namelst);
if(DOS_ERR){
cputs("list file not creatable: ");
cputs(namelst);
exitR(2);
}
printstring(";");
printstring(Version1);
printstring(", Input: "); printstring(namein);
printstring(", Output: "); printstring(namelst);
}
int epilog() {
unsigned int i;
isPrint=1;
GTop--;
printstring("\n;Glob. variables:"); printunsigned(GTop);
printstring(" ("); printunsigned(VARMAX);
i = VarNamePtr - &VarNames;
printstring("):"); printunsigned(i);
printstring(" ("); printunsigned(VARNAMESMAX);
printstring("), Functions:"); printunsigned(FunctionMaxIx);
printstring(" ("); printunsigned(FUNCMAX);
i = FunctionNamePtr - &FunctionNames;
printstring("):"); printunsigned(i);
printstring(" ("); printunsigned(FUNCTIONNAMESMAX);
printstring(")\n;Lines:"); printunsigned(lineno);
printstring(", Constant: "); printunsigned(maxco);
printstring(" ("); printunsigned(COMAX);
i = COMAX;
i = i - maxco;
if (i<=1000)printstring("\n ** Warning ** constant area too small");
printstring("), stacksize: ");
i=65535;
i=i-orgDatai;
printunsigned(i);
if (i <= 1000) printstring("\n *** Warning *** Stack too small");
}
int main() {
getarguments();
openfiles();
isPrint=0;
printstring("\norg 256 \njmp main");
GTop = 1;
VarNamePtr= &VarNames;
FunctionNamePtr= &FunctionNames;
FunctionMaxIx=0;
orgDatai=orgDataOriginal;
fgetsp=&fgetsdest;
*fgetsp=0;
thechar=fgets1();
parse();
epilog();
end1(0);
}
| c0c88dced4904b36295f1e6e0b8fae8a36075b0e | [
"Markdown",
"C"
] | 4 | Markdown | ALANGUAGE/ASM86 | 6b8c2d7ecbf12c56f9218fdfe4332d6b03e49bea | 32a4ab969333d8f2487bceac6122f79a410f7fa9 |
refs/heads/master | <repo_name>obedparla/hydrate-server<file_sep>/src/hydrate/hydrate-router.js
const express = require('express');
const knex = require('knex');
const { DATABASE_URL } = require('../config');
const { requireAuth } = require('../middleware/basic-auth');
const bcrypt = require('bcryptjs')
const moment = require('moment');
const jsonParser = express.json()
const jsonBodyParser = express.json()
const hydrateRouter = express.Router();
const knexInstance = knex({
client: 'pg',
connection: DATABASE_URL,
});
hydrateRouter
.route('/api/user')
.get((req, res) => { //get all users
knexInstance
.select('*')
.from('hydrate_users')
.then(results => {
res.json(results)
})
})
.post(jsonParser, (req, res, next) => { //register new users
const { username, glasses } = req.body;
const password = <PASSWORD>.hashSync(req.body.password, 8);
const newUser = { username, password, glasses };
const userColumns = [ 'id', 'username', 'glasses' ]
const quotaColumns = [ 'amount' ]
if (parseInt(glasses) <= 0 || parseInt(glasses) > 10) {
return res.status(400).json({error: 'Needs to be between 1-10'})
}
knexInstance
.insert(newUser)
.into('hydrate_users')
.returning(userColumns)
.then(([ user ]) => knexInstance
.insert({
user_id: user.id,
date: 'now()',
amount: 0
})
.into('hydrate_quotas')
.returning(quotaColumns)
.then(([ quota ]) => res.status(201)
.json({
...user,
...quota
})
)
)
})
hydrateRouter
.route('/api/user/login')
.post(jsonBodyParser, (req, res, next) => { //user login
const { username, password } = req.body
const loginUser = { username, password }
const userColumns = [ 'id', 'username', 'glasses' ]
const quotaColumns = [ 'amount' ]
for (const [key, value] of Object.entries(loginUser))
if (value == null)
return res.status(400).json({
error: `Missing '${key}' in request body`
})
knexInstance
.from('hydrate_users')
.where({ username })
.first()
.returning(userColumns)
.then(user => {
if (!user || !bcrypt.compareSync(password, user.password))
return res.status(400).json({
error: 'Incorrect username or password'
})
knexInstance
.from('hydrate_quotas')
.where({
user_id: user.id,
date: 'now()'
})
.select('user_id')
.then(rows => {
if (rows.length > 0)
return res.status(200).json(user)
knexInstance
.insert({
user_id: user.id,
date: 'now()',
amount: 0
})
.into('hydrate_quotas')
.returning(quotaColumns)
.then(([ quota ]) =>
res.status(201).json({
...user,
...quota
}))
})
})
.catch(next)
})
hydrateRouter
.route('/api/user/:id')
.all(requireAuth)
.get((req, res, next) => { //display current user profile
const {id} = req.params;
knexInstance
.from('hydrate_users')
.select('*')
.where('id', id)
.first()
.then(user => {
res.json(user)
})
.catch(next)
})
.patch(requireAuth, jsonParser, (req, res, next) => { //edit water consumption goal
const { glasses } = req.body
const glassesUpdate = { glasses }
const { id } = req.params
const numberOfValues = Object.values(glassesUpdate).filter(Boolean).length
if (numberOfValues === 0)
return res.status(400).json({
error: { message: `Request body must contain 'glasses'` }
})
knexInstance('hydrate_users')
.where( {id} )
.update({glasses})
.then(user => {
res.status(204).end();
})
.catch(next)
})
hydrateRouter
.route('/api/user/waterconsumed/:user_id')
.all(requireAuth)
.get((req, res, next) => { //display water consumed/day
const {user_id} = req.params;
knexInstance
.from('hydrate_quotas')
.select('amount', 'date')
.where('user_id', user_id)
.first()
.then(water => {
res.json(water)
})
.catch(next)
})
.patch(requireAuth, jsonParser, (req, res, next) => { //update water consumed
const { amount } = req.body
const amountUpdate = { amount }
const { user_id } = req.params
const numberOfValues = Object.values(amountUpdate).filter(Boolean).length
if (numberOfValues === 0)
return res.status(400).json({
error: { message: `Request body must contain 'amount'` }
})
amountUpdate.user = req.user.id
knexInstance('hydrate_quotas')
.where({
user_id: user_id,
date: 'now()'
})
.update( {amount} )
.then(amount => {
res.status(204).end();
})
.catch(next)
})
hydrateRouter
.route('/api/user/water/week/:user_id')
.all(requireAuth)
.get((req, res, next) => { //display water consumed/week
const {user_id} = req.params;
const past = moment().subtract(4, 'days').format("YYYY-MM-DD");
knexInstance
.from('hydrate_quotas')
.select('amount', 'date')
.where('user_id', user_id)
.whereBetween('date', [past, 'now()'])
.orderBy('date','desc')
.then(water => {
res.json(water)
})
.catch(next)
})
// VERSION 2 UPDATE //
hydrateRouter
.route('/api/fact')
.get((req, res) => { //get all facts
knexInstance
.select('fact')
.from('hydrate_facts')
.first()
.then(results => {
res.json(results)
})
})
module.exports = hydrateRouter; | cc703a438f27956190118a4298dab110ad0591a8 | [
"JavaScript"
] | 1 | JavaScript | obedparla/hydrate-server | 337f902b593e9b7793a6b320d3c608a1bcfc3d50 | edcac01e33d135160c1dd64d28bc3ec636707edb |
refs/heads/master | <repo_name>dijs/nlp-links<file_sep>/index.js
var LinkGrammar = require('link-grammar');
var linkGrammar = new LinkGrammar();
module.exports = function(nlp) {
return {
Sentence: {
withLinks: function() {
var linkage = linkGrammar.parse(this.str);
this.terms.forEach(function(term) {
term.links = linkage.getConnectorWords(term.text);
});
return this;
}
}
};
};
<file_sep>/test/test.js
require('should');
var nlp = require('nlp_compromise');
nlp.plugin(require('../index'));
describe('Link Grammar Plugin', function() {
it('should find word connections', function() {
var sen = nlp.sentence('I fed the dog').withLinks();
sen.terms[1].text.should.equal('fed');
sen.terms[1].links[1].target.word.should.equal('dog');
sen.terms[1].links[1].target.label.should.equal('Os');
});
});
<file_sep>/README.md
## Link Grammar plugin for nlp_compromise
### How to install
```bash
npm install nlp-links
```
### How to use
```js
var nlp = require('nlp_compromise');
nlp.plugin(require('nlp-links'));
var sen = nlp.sentence('I fed the dog').withLinks();
sen.terms[1].text.should.equal('fed');
// Each term now has links to words they are grammatically connected to
sen.terms[1].links[1].target.word.should.equal('dog');
sen.terms[1].links[1].target.label.should.equal('Os');
```
### Source library
https://www.npmjs.com/package/link-grammar
| 5e2c13b9e8e0f2ba2913f7eeb0da221f9b56ca8d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | dijs/nlp-links | 20439d560e73c41ed6335a9fdb756044a0dfcf27 | b1fc608dcc9bfade73ec353d7517e18960e8e2b1 |
refs/heads/master | <repo_name>MosesThobakgale/Prac2<file_sep>/MyStrings/MyStrings/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ThinkLib;
namespace MyStrings
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int length(string s)
{
int count = 0;
// int i = 0;
foreach (int h in s)
{
count++;
}
return count;
}
private bool contains(string s, string subs)
{
if (s == subs)
{
return true;
}
string o = "";
int i = 0;
int u = 0;
int lengthOfString = length(s);
int lengthOfSubs = length(subs);
int y = length(subs);
while(lengthOfString >= y)
{
//if(u == length(subs) -1)
//{
//}
if(s[i] == subs[u])
{
o = o + s[i];
u++;
if(o == subs)
{
return true;
}
lengthOfString = lengthOfString - 1;
}
i++;
}
return false;
}
private void btnLength_Click(object sender, RoutedEventArgs e)
{
//string p = "<NAME>";
//MessageBox.Show(Convert.ToString(length(p)));
MessageBox.Show(Convert.ToString(contains("mosessmo", "ll")));
}
}
}
| d0f5fcdb77efdef53ecdfcb52bac7fcbc35de105 | [
"C#"
] | 1 | C# | MosesThobakgale/Prac2 | 2645c104d61e1f117de6cc4d1ec0ad6a72786b9f | bcdce621eba0f498dae3227538c39c1a9143c2e8 |
refs/heads/master | <file_sep># read version from installed package
from importlib.metadata import version
__version__ = version("cipher_ky2458")<file_sep>def cipher(text, shift, encrypt=True):
"""
The function:
-------------
Each letter is replaced by a letter some fixed number of positions down the alphabet.
Inputs:
-------------
'text': str. The word or sentence that you want to encrypt.
'shift': int. It means the direction and position you want to encrypt your word or sentence.
Outputs:
-------------
The text(str) after cipher.
Example:
-------------
>>> import cipher_ky2458
>>> text = 'K'
>>> shift = 1
>>> m = cipher_ky2458.cipher(a, b)
>>> print(m)
L
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text
<file_sep>from cipher_ky2458 import cipher_ky2458
def test_cipher():
text = 'K'
expected = 'L'
actual = cipher_ky2458.cipher(text, 1)
assert actual == expected, "Cipher failed." | 9cedc9cfabf74e8dae955e0bc0e9e0be11d2ec4a | [
"Python"
] | 3 | Python | QMSS-G5072-2021/cipher_kun_yao | 503955bcf0fb68742997ceca21890d42b787c4cc | 2fdbbc89b874505fdf4562d927f724926ee30747 |
refs/heads/master | <repo_name>rogerbooyou/jsfl<file_sep>/StretchTimeline_v1.jsfl
//
// Stretch Timeline Flash Extension Command
// v1
//
// This extension will automatically stretch the selected frames
// to the given factor of the currently selected timeline.
//
// Compatible with Adobe Flash CS3/CS4.
//
// Based on Reineir Feijen's Flash Extensions.
//
// Copyright 2010 <NAME>, NERVES
// <EMAIL> | www.nerves.ch
//
// Init
var valid = true;
var factor = 1.0;
// Sanity check and factor input
if (fl.getDocumentDOM() == null || fl.getDocumentDOM().getTimeline() == null) {
alert("No timeline is selected!");
} else {
var ret = prompt("Stretch Timeline by a factor. For example, 0.8 would speed up the timeline while 1.4 would slow it down...\n ");
if(ret != null) {
factor = parseFloat(ret);
if (isNaN(factor)) {
alert("The factor '"+ret+"' is not valid!");
} else {
// Rock n Roll!
stretchTimeline(fl.getDocumentDOM().getTimeline(),factor);
}
}
}
// Strech the timeline
function stretchTimeline(timeline_obj, factor) {
// Init
var tl = timeline_obj;
var sel = tl.getSelectedFrames().concat([]);
// Loop selection
for (var i=0;i<sel.length;i+=3) {
var splices = [];
var changed = 0;
tl.setSelectedFrames([sel[i],sel[i+1],sel[i+2]]);
// Calculate splices
for (var j=sel[i+1];j<sel[i+2]+1;j++) {
if (j==sel[i+2] || (tl.layers[sel[i]].frames[j] && j==tl.layers[sel[i]].frames[j].startFrame)) {//only keyframes and last frame
var goal = sel[i+1]+Math.round((j-sel[i+1])*factor);
if (factor>=1) {
var df = goal-(j+changed);
var at = j-1+changed;
} else {
var df = (j-changed)-goal;
var at = j-changed;
}
if(df>0) {
splices.push([at, df]);
changed += df;
}
}
}
// Insert/remove necessary frames
// TODO: does not work properly on empty frames
if (factor>=1) {
for (var j=0;j<splices.length;j++) {
tl.insertFrames(splices[j][1], false, splices[j][0]);
}
} else {
for (var j=0;j<splices.length;j++) {
tl.removeFrames(splices[j][0]-splices[j][1], splices[j][0]);
}
}
}
}
| 47c73e2b45463be832d28a5a9e6771e64c893c01 | [
"JavaScript"
] | 1 | JavaScript | rogerbooyou/jsfl | 9143c7f9140d3510e4550bd1b750f9f8eea1a547 | 009fe05701d1c43811546540452e0d1c0564715d |
refs/heads/master | <file_sep>package com.thebubblenetwork.bubblelobby.ultracosmetics;
import com.thebubblenetwork.api.framework.BubbleNetwork;
import com.thebubblenetwork.api.framework.player.BukkitBubblePlayer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.plugin.SimplePluginManager;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.logging.Level;
public class GiveGadgetCommand extends Command{
private static GiveGadgetCommand command;
public static void register(){
if(command != null)unregister();
command = new GiveGadgetCommand();
Field commandMap;
try {
commandMap = SimplePluginManager.class.getDeclaredField("commandMap");
commandMap.setAccessible(true);
} catch (NoSuchFieldException e) {
BubbleNetwork.getInstance().getLogger().log(Level.WARNING, "Could not setup UC command");
return;
}
CommandMap map;
try {
map = (CommandMap) commandMap.get(Bukkit.getServer().getPluginManager());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
//Cannot happen
}
command.register(map);
map.register("_",command);
}
public static void unregister(){
Field commandMap;
Field knownCommands;
try {
commandMap = SimplePluginManager.class.getDeclaredField("commandMap");
knownCommands = SimpleCommandMap.class.getDeclaredField("knownCommands");
commandMap.setAccessible(true);
knownCommands.setAccessible(true);
} catch (NoSuchFieldException e) {
BubbleNetwork.getInstance().getLogger().log(Level.WARNING, "Could not unregister UC command");
return;
}
CommandMap map;
Map<String,Command> commands;
try {
map = (CommandMap) commandMap.get(Bukkit.getServer().getPluginManager());
commands = (Map<String, Command>) commandMap.get(null);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
//Cannot happen
}
command.unregister(map);
commands.values().remove(command);
command = null;
}
public GiveGadgetCommand() {
super("givegadget");
}
public boolean execute(CommandSender commandSender, String s, String[] strings) {
BukkitBubblePlayer player = BukkitBubblePlayer.getObject(Bukkit.getPlayer(strings[0]).getUniqueId());
String gadget = strings[1].replace("ultracosmetics.","");
String split[] = gadget.split("\\.");
if(player.getHubItemUsable(gadget)){
int random = BubbleNetwork.getRandom().nextInt(100)+ 100;
player.getPlayer().sendMessage(BubbleNetwork.getPrefix() + "You already this! Giving " + ChatColor.BLUE + random + ChatColor.RESET + " Tokens");
player.setTokens(player.getTokens() + random);
}
else{
player.setHubItemUsable(gadget, true);
}
return false;
}
}
| c04398f5a78f862877c23923aed934d0d48a63f1 | [
"Java"
] | 1 | Java | BubbleNetwork/BubbleLobby | 435711649f1661b22b64e21e60da7eceb29cb45c | 97ca84505ca738387743a267b7258c50b87cd324 |
refs/heads/master | <repo_name>devheptagon/GraphQL-Product-Listing-Demo<file_sep>/src/theme/colors.js
export const Colors = {
whiteSmoke: '#F7F7F2',
pearl: '#E4E6C3',
lightGray: '#EEEEEE',
artichoke: '#899878',
raisinBlack: '#222725',
licorice: '#121113',
mellowYellow: '#F3E37C',
sandStorm: '#F3D34A',
neonCarrot: '#EEA243'
}
<file_sep>/src/components/listing/product-list.jsx
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { withRouter } from "react-router"
import { Container, List } from './listing.style'
import Pager from '../shared/pager'
import { preFetchProductsAction } from '../../redux/appActions'
import Loading from '../shared/loading'
import ProductListItem from './product-list-item'
import ThemeSelector from '../shared/theme-selector'
import Empty from './empty'
export class ProductList extends Component {
componentDidMount() {
let currentPage = this.getCurrentPage()
this.props.fetchProducts(currentPage)
}
onNext = (e) => {
let currentPage = this.getCurrentPage()
let page = ++currentPage
this.loadPage(page)
}
onPrevious = (e) => {
let currentPage = this.getCurrentPage()
let page = currentPage > 1 ? --currentPage : 1
this.loadPage(page)
}
loadPage = (page) => {
const url = `/product-list/${page}`
this.props.history.push(url)
this.props.fetchProducts(page)
}
getCurrentPage = () => this.props.match.params.page ? +this.props.match.params.page : 1
render() {
const { isLoading, products } = this.props
return (
<Container>
<List>
{
isLoading
? <Loading />
: products && products.length > 0
? [
<ThemeSelector key='theme-selector' />,
<ProductListItem key='header-row'
isHeaderRow={true}
product={products[0]} />,
products.map(emp => <ProductListItem key={emp.productID} product={emp} />)
]
:
<Empty />
}
</List>
<Pager onNext={this.onNext} onPrevious={this.onPrevious} />
</Container>
);
}
}
ProductList.propTypes = {
isLoading: PropTypes.bool,
products: PropTypes.array
}
const mapStateToProps = (state) => {
return {
products: state.appReducer.products,
isLoading: state.appReducer.isLoading
}
}
const mapDispatchToProps = ({
fetchProducts: preFetchProductsAction
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ProductList))<file_sep>/src/components/shared/__tests__/pager.test.jsx
import React from 'react'
import { shallow } from 'enzyme'
import Pager from '../pager'
describe('Pager is being tested', () => {
let mountedPager = null
beforeAll(() => {
const onPrevious = jest.fn()
const onNext = jest.fn()
mountedPager = shallow(<Pager onNext={onNext} onPrevious={onPrevious} />)
})
test('renders without crashing', () => {
})
test('has previous and next buttons', () => {
const buttons = mountedPager.find('Button')
expect(buttons.length).toBe(2)
})
})
<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### Tech Stack:
- Hosted at AWS EC2, running on Apache
- Bootstrap for responsive design
- Styled-components for styling (should be preferred over CSS/LESS/SASS according to React official docs)
- Context api for Theming
- Redux for state management
- React-router for client side routing
- Redux-saga for saga async design pattern
- GraphQL proxy as query target (https://graphql-compose.herokuapp.com/northwind/?)
- Axios for fetching data
- Enzyme and React-test-render for testing
<file_sep>/src/components/shared/__tests__/theme-selector.test.jsx
import React from 'react'
import { shallow } from 'enzyme'
import ThemeSelector from '../theme-selector'
it('renders without crashing', () => {
let mounted = shallow(<ThemeSelector />)
});
<file_sep>/src/components/shared/loading.jsx
import React from 'react'
import { LoadingContainer } from './shared.style'
import loadingIcon from '../../assets/loading.gif'
export const Loading = () => <LoadingContainer>
<img src={loadingIcon} alt='loading icon' />
</LoadingContainer>
export default Loading<file_sep>/src/routes.js
import React from 'react'
import Home from './components/home/home'
import ProductList from './components/listing/product-list'
import { Route } from "react-router-dom"
export const Routes = <React.Fragment>
<Route path="/" exact component={Home} />
<Route path="/product-list/:page" component={ProductList} />
</React.Fragment><file_sep>/src/components/shared/pager.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { PagerContainer } from './shared.style'
import Button from './button'
export const Pager = (props) => <PagerContainer>
<Button onClick={props.onPrevious}><< Previous</Button>
<Button onClick={props.onNext}>Next >></Button>
</PagerContainer>
Pager.propTypes = {
onPrevious: PropTypes.func.isRequired,
onNext: PropTypes.func.isRequired
}
export default Pager<file_sep>/src/index.jsx
import React from 'react'
import 'core-js/es6/map'
import 'core-js/es6/set'
import ReactDOM from 'react-dom'
import Layout from './components/layout'
import { BrowserRouter as Router } from "react-router-dom"
import { Provider } from 'react-redux'
import rootReducer from './redux/rootReducer'
import { rootSaga } from './sagas/rootSaga'
import createStore from './redux/store'
import { ThemeContext, ThemeList } from './theme/themes'
const store = createStore(rootReducer, rootSaga)
class Entry extends React.Component {
toggleTheme = (newTheme) => {
let container = {...this.state.themeContainer, theme: newTheme}
this.setState({ themeContainer: container})
}
state = {
themeContainer: {
theme: ThemeList.LightTheme,
toggleTheme: this.toggleTheme
}
}
render () {
return <ThemeContext.Provider value={this.state.themeContainer}>
<Provider store={store}>
<Router>
<Layout />
</Router>
</Provider>
</ThemeContext.Provider>
}
}
ReactDOM.render(<Entry />, document.getElementById('root'));<file_sep>/src/components/listing/listing.style.jsx
import React from 'react'
import styled from 'styled-components'
export const Container = styled.div`
height: 100%;
`
export const List = styled.div`
height: 90%;
& div:nth-child(2) {
border-radius: 10px 10px 0 0
};
& div:last-child {
border-radius: 0 0 10px 10px
};
@media (max-height: 700px) {
overflow-y: scroll
}
`
export const ListItem = (props) => props.isHeaderRow
? <ListHeaderItem {...props}>{props.children}</ListHeaderItem>
: <ListRegularItem {...props}>{props.children}</ListRegularItem>
export const ListItemBase = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-start;
&: last-child {
border-bottom: 0;
};
& div {
flex: 1;
};
& div:nth-child(2) {
flex: 3;
};
& div:last-child {
text-align: right;
font-weight: bold;
};
@media (max-width: 600px) {
font-size: small;
& div {
overflow: hidden;
};
& div:first-child {
display: none
}
}
`
export const ListHeaderItem = styled(ListItemBase)`
border-bottom: 1px dotted ${props => props.theme.rowBorderColor};
background: ${props => props.theme.headerRowBackground};
font-weight: bold;
text-transform: uppercase;
`
export const ListRegularItem = styled(ListItemBase)`
border-bottom: 1px dotted ${props => props.theme.rowBorderColor};
background: ${props => props.theme.rowBackground};
font-weight: normal;
&: hover {
background: ${props => props.theme.rowHoverBackground};
color: ${props => props.theme.rowHoverColor};
};
`
export const ListItemField = styled.div`
padding: 8px;
`
export const EmptyContainer = styled.div`
padding: 50px;
font-size: 30px;
text-align: center;
`<file_sep>/src/components/listing/__tests__/product-list.test.jsx
import React from 'react'
import { ProductList } from '../product-list'
import { shallow, mount } from 'enzyme'
import { ThemeList, ThemeContext } from '../../../theme/themes'
describe('Product-List is being tested', () => {
const history = []
const props = {
match: {
params: {
page: 1
}
},
fetchProducts: (page) => history.push(page),
history: []
}
test('renders without crashing', () => {
let mounted = shallow(<ProductList {...props} />)
})
test('previous button pushes correct url to history', () => {
const mounted = mount(<ThemeContext.Provider value={ThemeList.DarkTheme}>
<ProductList {...props} />
</ThemeContext.Provider>)
const buttons = mounted.find('button')
expect(buttons.length).toBe(2)
const previousButton = buttons.at(0)
previousButton.simulate('click')
expect(history.pop()).toBe(1)
})
test('next button pushes correct url to history', () => {
const mounted = mount(<ThemeContext.Provider value={ThemeList.DarkTheme}>
<ProductList {...props} />
</ThemeContext.Provider>)
const buttons = mounted.find('button')
const nextButton = buttons.at(1)
nextButton.simulate('click')
nextButton.simulate('click')
expect(history.pop()).toBe(2)
})
})<file_sep>/src/components/listing/empty.jsx
import React from 'react'
import { EmptyContainer } from './listing.style'
const Empty = () => <EmptyContainer>End Of List</EmptyContainer>
export default Empty<file_sep>/src/components/shared/__tests__/loading.test.jsx
import React from 'react'
import { shallow } from 'enzyme'
import Loading from '../loading'
describe('Loading is being tested', () => {
test('renders without crashing', () => {
let mounted = shallow(<Loading />)
})
test('renders a loading image', () => {
let mounted = shallow(<Loading />)
expect(mounted.html()).toContain('loading.gif')
})
})
<file_sep>/src/theme/themes.js
import React from 'react'
import { Colors } from "./colors";
export const ThemeContext = React.createContext()
const SharedItems = {
borderColor: Colors.lightGray
}
export const LightTheme = {
descriptor: 'LightTheme',
...SharedItems,
mainBackgroundColor: Colors.whiteSmoke,
buttonTextColor: Colors.whiteSmoke,
containerBackgroundColor: Colors.pearl,
headerRowBackground: Colors.sandStorm,
rowBackground: Colors.whiteSmoke,
rowHoverBackground: Colors.mellowYellow,
rowHoverColor: Colors.raisinBlack,
rowBorderColor: Colors.neonCarrot
}
export const DarkTheme = {
descriptor: 'DarkTheme',
...SharedItems,
mainBackgroundColor: Colors.raisinBlack,
buttonTextColor: Colors.whiteSmoke,
containerBackgroundColor: Colors.artichoke,
headerRowBackground: Colors.neonCarrot,
rowBackground: Colors.pearl,
rowHoverBackground: Colors.mellowYellow,
rowHoverColor: Colors.raisinBlack,
rowBorderColor: Colors.whiteSmoke
}
export const ThemeList = {
LightTheme,
DarkTheme
}<file_sep>/src/components/shared/button.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { ButtonContent } from './shared.style'
import { Button as BootstrapButton} from 'react-bootstrap'
import { ThemeContext } from '../../theme/themes'
const Button = (props) => <BootstrapButton bsStyle="primary" {...props}>
<ThemeContext.Consumer>
{
({theme}) => <ButtonContent theme={theme}>{props.children}</ButtonContent>
}
</ThemeContext.Consumer>
</BootstrapButton>
Button.propTypes = {
children: PropTypes.any,
theme: PropTypes.object
}
export default Button<file_sep>/src/sagas/rootSaga.js
import { all } from 'redux-saga/effects'
import { appSagas } from './appSagas'
export function* rootSaga() {
yield all([
appSagas()
])
}<file_sep>/src/components/home/home.jsx
import React, { Component } from 'react'
import { Wrapper } from './home.style'
import { Link } from 'react-router-dom'
import { Jumbotron } from 'react-bootstrap'
class Home extends Component {
render() {
return (
<Wrapper>
<Jumbotron>
<p>
This is a sample React.JS application fetching data from a public GraphQL server for demo purposes.
</p>
<p>
<Link to="/product-list/1">
START SAMPLE APPLICATION
</Link>
</p>
</Jumbotron>
</Wrapper>
)
}
}
export default Home
<file_sep>/src/components/shared/shared.style.jsx
import styled from 'styled-components'
export const ButtonContent = styled.div`
min-width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
& > a {
color: ${props => props.theme.buttonTextColor};
text-decoration: none;
font-weight: bold;
}
`
export const LoadingContainer = styled.div`
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
& > img {
width: 100px;
height: 100px;
}
`
export const PagerContainer = styled.div`
width: 100%;
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
`
export const ThemeSelectorWrapper = styled.div`
width: 100%;
padding: 10px;
display: flex;
justify-content: flex-end;
font-weight: bold;
& input {
margin-left: 5px;
margin-right: 20px;
cursor: pointer
}
`
<file_sep>/src/utils/__tests__/proxy.test.jsx
import Proxy from '../proxy'
import axios from 'axios'
jest.mock('axios')
describe('proxy functions are being tested', () => {
test('fetches data from graphql server', async () => {
expect.assertions(1)
const mockedResponse = {
data: {
productList: [
{
productID: '123',
name: 'pie',
unitPrice: '100'
}
]
}
}
axios.mockResolvedValue(mockedResponse)
Proxy.postData(1).then(r => {
expect(r).toEqual(mockedResponse.data)
})
})
})
<file_sep>/src/redux/__tests__/appReducer.test.js
import { postFetchProductsAction, setLoadingAction } from '../appActions'
import { appReducer } from '../appReducer'
const initialState = {
products: [],
isLoading: false
}
describe('App Reducer is being tested', () => {
test('postFetchProductsAction returns products in new state', () => {
const products = [{ productID: 1}]
const state = appReducer(initialState, postFetchProductsAction(products))
expect(state.products).toEqual(products)
})
test('setLoadingAction sets isLoading properly in new state', () => {
let state = appReducer(initialState, setLoadingAction(true))
expect(state.isLoading).toEqual(true)
state = appReducer(initialState, setLoadingAction(false))
expect(state.isLoading).toEqual(false)
})
})<file_sep>/src/redux/actionTypes.js
export const PREFETCH_PRODUCTS_TYPE = 'PREFETCH_PRODUCTS_TYPE'
export const POSTFETCH_PRODUCTS_TYPE = 'POSTFETCH_PRODUCTS_TYPE'
export const SET_LOADING_TYPE = 'SET_LOADING_TYPE'
<file_sep>/src/utils/__tests__/helper.test.jsx
import { formatMoney } from '../helper'
describe('helper functions are being tested', () => {
test('formats money properly', () => {
const amounts = [0.1, 1, 100]
const formattedAmounts = ['£0.10', '£1.00', '£100.00']
amounts.map((amount, index) => expect(formatMoney(amount)).toBe(formattedAmounts[index]))
})
})
<file_sep>/src/sagas/appSagas.js
import { put, call, takeLatest } from 'redux-saga/effects'
import { PREFETCH_PRODUCTS_TYPE } from '../redux/actionTypes'
import { setLoadingAction, postFetchProductsAction } from '../redux/appActions'
import Proxy from '../utils/proxy'
export function* preFetchProductsSaga(action) {
yield put(setLoadingAction(true))
const response = yield call(Proxy.postData, action.payload.page)
const products =
(response.data && response.data.viewer.productList)
? response.data.viewer.productList
: []
yield put(postFetchProductsAction(products))
yield put(setLoadingAction(false))
}
export function* appSagas() {
yield takeLatest(PREFETCH_PRODUCTS_TYPE, preFetchProductsSaga)
}<file_sep>/src/components/listing/__tests__/empty.test.jsx
import React from 'react'
import { shallow } from 'enzyme'
import Empty from '../empty'
it('renders without crashing', () => {
let mounted = shallow(<Empty />)
});
<file_sep>/src/components/listing/product-list-item.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { ListItem, ListItemField } from './listing.style'
import { formatMoney } from '../../utils/helper'
import { ThemeContext } from '../../theme/themes'
const formatFieldValue = (key, value) => key === 'unitPrice' ? formatMoney(value) : value
const ProductListItem = (props) => {
const { product, isHeaderRow } = props
return (
<ThemeContext.Consumer>
{
({ theme }) => <ListItem isHeaderRow={isHeaderRow} theme={theme}>
{
Object.keys(product).map(key =>
<ListItemField key={key}>
{isHeaderRow ? key : formatFieldValue(key, product[key])}
</ListItemField>)
}
</ListItem>
}
</ThemeContext.Consumer>
)
}
ProductListItem.propTypes = {
product: PropTypes.object.isRequired,
isHeaderRow: PropTypes.bool
}
export default ProductListItem | 579b246b172b7e33c9724dcc5a09079cf4adf854 | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | devheptagon/GraphQL-Product-Listing-Demo | 1181fd28487902e10f6062f8c9d83f01b57260da | 0883846ac41eba5fbff768801ec12c503a634abd |
refs/heads/master | <file_sep>file=${1-intro/intro-cypher-movies/training-intro-cypher-movies.adoc}
presenter=${2-"Neo4j"}
email=${4-"<EMAIL>"}
twitter=${4-"neo4j"}
./run.sh content/training/$file -a presenter=$presenter -a email=$email -a twitter=$twitter
<file_sep>git submodule init
git submodule update
ADOC_VERSION=$(asciidoctor -v)
if [ ! $? ]; then
echo "Installing AsciiDoctor"
bundle install
else
echo "Installed"
echo $ADOC_VERSION
fi
echo -n "Your Name: "
read name
echo -n "Your Twitter: "
read twitter
echo -n "Your Email: "
read email
function create {
./run.sh content/training/$1 -a presenter="$name" -a twitter="$twitter" -a email="$email"
}
SLIDES="advanced_cypher/training-advanced-cypher.adoc import/training-data-import.adoc modeling/training-data-modeling.adoc production/training-neo4j-in-production.adoc intro/intro-cypher-movies/training-intro-cypher-movies.adoc intro/intro-cypher-relational/training-intro-cypher-relational.adoc intro/intro-cypher-interactive/training-intro-cypher-interactive.adoc intro/graph-days-movies/training-graph-days-cypher-movies.adoc"
for i in $SLIDES; do
echo "Rendering $i"
create $i
done
./http index.html
| 75a49c68923e5004d8bc9869bdf17fca1ab3bb08 | [
"Shell"
] | 2 | Shell | sarmbruster/asciidoc-slides | 9af44d34cef7460fc92e718f4a3faba7d7165ad8 | 4073b6e823f00bb9dfcb2cdbe0aa85fddb385d04 |
refs/heads/master | <repo_name>imakiro/Stack-Exchange-Bot<file_sep>/src/BotMain.java
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class BotMain {
static String loginID = null;
static String loginPW = null;
static String loginUrl = null;
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver = setAppProperties(args[0]);
driver.get(loginUrl);
driver.findElement(By.id("email")).sendKeys(loginID);
driver.findElement(By.id("password")).sendKeys(<PASSWORD>);
driver.findElement(By.id("submit-button"));
driver.findElement(By.id("submit-button")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("a.-link.js-site-switcher-button.js-gps-track")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("log out")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("button.grid--cell.s-btn.s-btn__primary")).click();
driver.quit();
}
private static WebDriver setAppProperties(String cfgfile) throws IOException {
InputStream is = new FileInputStream(cfgfile);
Properties p = new Properties();
p.load(is);
is.close();
loginID = p.getProperty("Email");
loginPW = p.getProperty("<PASSWORD>");
loginUrl = p.getProperty("LoginUrl");
String os = System.getProperty("os.name");
ChromeOptions coptions = new ChromeOptions();
coptions.setHeadless(true);
FirefoxOptions foptions = new FirefoxOptions();
foptions.setHeadless(true);
if (os.startsWith("Windows")) {
if (!p.getProperty("ChromeWindows").equals("")) {
System.setProperty("webdriver.chrome.driver", p.getProperty("ChromeWindows"));
return new ChromeDriver(coptions);
}
System.setProperty("webdriver.gecko.driver", p.getProperty("FireFoxWindows"));
return new FirefoxDriver(foptions);
} else {
if (!p.getProperty("ChromeLinux").equals("")) {
System.setProperty("webdriver.chrome.driver", p.getProperty("ChromeLinux"));
return new ChromeDriver(coptions);
}
System.setProperty("webdriver.gecko.driver", p.getProperty("FireFoxLinux"));
return new FirefoxDriver(foptions);
}
}
}
| c4780415b96050b8da81918ee976008ede7b61a5 | [
"Java"
] | 1 | Java | imakiro/Stack-Exchange-Bot | f849df81a08588b79a6d2a3330f9168b7313af72 | 6a0621ee9504d78cb5a96bffa3daa32313af2cfc |
refs/heads/main | <file_sep>// скрипт для маленьких экранов вызова меню и слайда
$(document).ready(function () {
// создаем кнопку меню
const mMenuBtn = $('.m-menu-button');
// новый элем- т для меню с классом
const mMenu = $('.m-menu');
// переменная для смены таблици актеры создатели
const tab = $('.tab');
// нахожу кнопку и совершаю событие клик
// переменная.событие, выполняется ф-я открывается наше меню
mMenuBtn.on('click', function () {
// этому меню присваеваем класс activ через toggleClass это будет обозначать что меню активно
mMenu.toggleClass('activ');
// для тега body приеним toggleClass не скролить в css его опишем d начале
$('body').toggleClass('no-scroll');
});
// актеры создатели 25-07 скрипт переключения актерыисоздатели по приципу табов
tab.on("click", function () {
// сделать ремуф очистку от класса active
tab.removeClass('active');
$(this).toggleClass('active');
// сделать чистку всех классов от класса visible
$('.tabs-content').removeClass('visible');
// у this вытащить атрибут attr
// $(this).attr('data-target');
//data-target содержит то что мы поместили в него в HTML
// console.log($(this).attr('data-target'));
// сщздадим для таргетф переменную 28-34
let activeTabContent = $(this).attr('data-target');
// обращаемся к переменной activeTabContent и применим для него через toggleClass класс 'visible'
$(activeTabContent).toggleClass('visible');
});
// слайды
const swiper = new Swiper('.swiper-container', {
// в одном слайде 4 карточки слайда
slidesPerView: 4,
// растояние между карточками слайды
saceBetween: 25,
loop: true,
// размеры для разных экранов
breakpoints: {
992: {
slidesPerView: 4,
},
768: {
slidesPerView: 2,
},
560: {
slidesPerView: 2,
},
320: {
slidesPerView: 1,
slidesOffsetAfter: 70,
navigation: {
nextEl: ".button-next",
},
},
}
});
});
// слайды
const swiper = new Swiper('.swiper-container', {
// в одном слайде 4 карточки слайда
slidesPerView: 4,
// растояние между карточками слайды
saceBetween: 25,
loop: true,
// размеры для разных экранов
breakpoints: {
992: {
slidesPerView: 4,
},
768: {
slidesPerView: 2,
},
560: {
slidesPerView: 2,
},
320: {
slidesPerView: 1,
slidesOffsetAfter: 70,
navigation: {
nextEl: ".button-next",
},
},
}
})
// 9-49<file_sep># Treler-Oxotnik-za-privedeniyami- | b10cf678469510b59b9bf1b67be6c084e533c9d3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Irinka04/Treler-Oxotnik-za-privedeniyami- | 2242a97f711ea4459f9d1995e2f468f9d2cd4ffb | df61438cb51ae82fe00ce65a512fb28b3bc3907a |
refs/heads/master | <repo_name>LukaszNiewinski/Castle_Game_min_max<file_sep>/GameController.py
from GameView import *
from GameMenu import *
from GameModel import *
from GameOptions import *
import sys
class Gauntlet(pygame.sprite.Sprite):
resolution = (60, 60)
def __init__(self):
super().__init__()
self.image = FunContainer.load_image("gauntlet.jpg", -1)
self.clickedImage = pygame.transform.scale(self.image, (self.resolution[0]-8, self.resolution[1]-8))
self.normalImage = pygame.transform.scale(self.image, self.resolution)
self.image = self.normalImage
self.rect = self.image.get_rect()
pygame.mouse.set_visible(False)
self.clickedSound = FunContainer.load_sound("click.wav")
self.muted = None
def update(self):
self.rect.midtop = pygame.mouse.get_pos()
def clicked(self):
if not self.muted:
self.clickedSound.play()
self.image = self.clickedImage
def unclicked(self):
self.image = self.normalImage
class GameController:
FPS = 30
music = "stronghold.mp3"
def __init__(self, gameView: GameView, gameMenu: GameMenu, gameOptions: GameOptions, deep: tuple):
self.muted = False
self.game_mode = None
self.deep = deep
self.gauntlet = Gauntlet()
self.gauntlet.muted = self.muted
self.gameView = gameView
self.gameView.gauntlet = self.gauntlet
self.gameModel = self.gameView.gameModel
self.gameOptions = gameOptions
self.gameOptions.gauntlet = self.gauntlet
self.gameOptions.backToMenuButton.action = self.main_menu
self.gameOptions.soundButton.action = self.on_off_sound
self.gameOptions.changePlayerButton.action = self.change_mode
self.set_indicators()
self.gameMenu = gameMenu
self.gameMenu.gauntlet = self.gauntlet
self.gameMenu.optionsButton.action = self.main_options
self.gameMenu.playButton.action = self.game_mode
self.gameMenu.quitButton.action = self.exit
self.clock = pygame.time.Clock()
pygame.mixer.music.load(os.path.join(FunContainer.data_dir, self.music))
def set_indicators(self):
self.gameOptions.changePlayerIndicator.set_state(False)
self.gameOptions.soundIndicator.set_state(False)
self.game_mode = self.player_vs_computer
def main_menu(self):
if not pygame.mixer.music.get_busy() and not self.muted:
pygame.mixer.music.play(-1)
pygame.time.delay(500)
self.gameMenu.init_draw()
while True:
self.clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.exit()
elif event.type == MOUSEBUTTONDOWN:
self.gauntlet.clicked()
pos = pygame.mouse.get_pos()
spriteClicked = self.gameMenu.allButtons.focused_sprite(pos)
if spriteClicked:
self.gameMenu.view_update()
spriteClicked.action()
elif event.type == MOUSEBUTTONUP:
self.gauntlet.unclicked()
self.gameMenu.view_update()
def main_game(self):
pygame.time.delay(500)
pygame.mixer.music.stop()
self.gameView.init_draw()
spriteClicked = None
while True:
self.clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.main_menu()
elif event.type == MOUSEBUTTONDOWN:
self.gauntlet.clicked()
if not spriteClicked:
pos1 = pygame.mouse.get_pos()
pos1 = self.gameView.cartesian2board(pos1)
ballsClickedColor = self.gameModel.ballsMap[pos1]
if ballsClickedColor == self.gameModel.activePlayer.color:
spriteClicked = True
print("bill taken correctly")
else:
pos2 = pygame.mouse.get_pos()
pos2 = self.gameView.cartesian2board(pos2)
try:
if self.gameModel.move_ball(pos1, pos2):
self.gameView.balls_update()
if self.gameModel.check_if_game_finish():
raise EndGame
self.gameModel.change_player()
print("bill moved corectly")
except(SystemExit):
exit(0)
# self.game.new_game()
# self.set_player_indicator()
# self.main_menu()
spriteClicked = False
elif event.type == MOUSEBUTTONUP:
self.gauntlet.unclicked()
self.gameView.view_update()
def computer_vs_computer(self):
pygame.time.delay(500)
pygame.mixer.music.stop()
self.gameView.init_draw()
player1Turn = True
while True:
self.clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.main_menu()
if player1Turn:
if event.type == MOUSEBUTTONDOWN:
print("Player 1 - Black - is making his move", self.gameModel.activePlayer.color)
self.gameModel.intelligent_move(self.deep[0])
self.gameView.balls_update()
print("Computer 1 made his move!")
if self.gameModel.check_if_game_finish():
raise EndGame
player1Turn = False
self.gameModel.change_player()
else:
print("Player 2 - White - is making his move", self.gameModel.activePlayer.color)
self.gameModel.intelligent_move(self.deep[1])
self.gameView.balls_update()
print("Computer 2 made his move!")
if self.gameModel.check_if_game_finish():
raise EndGame
player1Turn = True
self.gameModel.change_player()
self.gameView.view_update()
def player_vs_computer(self):
pygame.time.delay(500)
pygame.mixer.music.stop()
self.gameView.init_draw()
spriteClicked = None
player1Turn = True
while True:
self.clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.main_menu()
if player1Turn:
if event.type == MOUSEBUTTONDOWN:
self.gauntlet.clicked()
if not spriteClicked:
pos1 = pygame.mouse.get_pos()
pos1 = self.gameView.cartesian2board(pos1)
ballsClickedColor = self.gameModel.ballsMap[pos1]
if ballsClickedColor == self.gameModel.activePlayer.color:
spriteClicked = True
print("Sprite clicked")
else:
pos2 = pygame.mouse.get_pos()
pos2 = self.gameView.cartesian2board(pos2)
try:
if self.gameModel.move_ball(pos1, pos2):
self.gameView.balls_update()
self.gameModel.change_player()
player1Turn = False
print("player changed")
except(SystemExit):
exit(0)
# self.game.new_game()
# self.set_player_indicator()
# self.main_menu()
print("Sprite unclicked")
spriteClicked = False
elif event.type == MOUSEBUTTONUP:
self.gauntlet.unclicked()
else:
#funkcja inteligent move, atrybut to parametr określający głębokość drzewa przeszukiwania
self.gameModel.intelligent_move(self.deep[1])
self.gameView.balls_update()
if self.gameModel.check_if_game_finish():
raise EndGame
self.gameModel.change_player()
player1Turn = True
self.gameView.view_update()
def main_options(self):
pygame.time.delay(500)
self.gameOptions.init_draw()
while True:
self.clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == QUIT:
self.exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.main_menu()
elif event.type == MOUSEBUTTONDOWN:
self.gauntlet.clicked()
pos = pygame.mouse.get_pos()
spriteClicked = self.gameOptions.allButtons.focused_sprite(pos)
if spriteClicked:
self.gameOptions.view_update()
spriteClicked.action()
elif event.type == MOUSEBUTTONUP:
self.gauntlet.unclicked()
self.gameOptions.view_update()
def change_mode(self):
self.gameOptions.changePlayerIndicator.change_state()
if self.game_mode == self.player_vs_computer:
self.game_mode = self.computer_vs_computer
self.gameMenu.playButton.action = self.game_mode
print("Computer vs computer set")
else:
self.game_mode = self.player_vs_computer
self.gameMenu.playButton.action = self.game_mode
print("Player vs computer set")
def on_off_sound(self):
self.gameOptions.soundIndicator.change_state()
if self.muted:
pygame.mixer.unpause()
pygame.mixer.music.play()
self.muted = False
print("Sound turned on")
else:
pygame.mixer.music.stop()
pygame.mixer.pause()
self.muted = True
print("Sound turned off")
self.gauntlet.muted = self.muted
@classmethod
def exit(cls):
pygame.time.delay(500)
pygame.quit()
sys.exit(0)
<file_sep>/start.py
#! /usr/bin/python3
import pygame
import GameView
import GameController
import GameMenu
import GameModel
import GameOptions
if __name__ == "__main__":
deep1 = input("Player1's deep: ")
deep2 = input("Player2's deep: ")
deep1 = int(deep1)
deep2 = int(deep2)
deep = (deep1, deep2)
pygame.mixer.pre_init(44100, -16, 2, 4096)
pygame.mixer.init()
pygame.init()
gameModel = GameModel.GameModel()
gameMenu = GameMenu.GameMenu()
gameView = GameView.GameView(gameMenu.screen, gameModel)
gameOptions = GameOptions.GameOptions(gameMenu.screen)
gameController = GameController.GameController(gameView, gameMenu, gameOptions, deep)
gameController.main_menu()
<file_sep>/GameView.py
import pygame
from pygame.locals import *
import pickle
from GameModel import *
from GameMenu import *
if not pygame.font:
print("Warning, fonts disabled")
if not pygame.mixer:
print("Warning, sound disabled")
class Ball(pygame.sprite.Sprite):
resolution = (35, 35)
color = None
def __init__(self):
super().__init__()
self.image = None
self.rect = None
def on_init(self):
self.image = pygame.transform.scale(self.image, (self.resolution[0], self.resolution[1]))
self.rect = self.image.get_rect()
class WhiteBall(Ball):
color = GameColor.WHITE
def __init__(self):
super().__init__()
self.image = FunContainer.load_image("white-ball.jpg", -1)
self.on_init()
class BlackBall(Ball):
color = GameColor.BLACK
def __init__(self):
super().__init__()
self.image = FunContainer.load_image("black-ball.jpg", -1)
self.on_init()
class BallsContainer(pygame.sprite.RenderPlain):
def __init__(self, ballsList):
super().__init__()
self.ballsList = ballsList
class GameView:
windowWidth = GameMenu.windowWidth
windowHeight = GameMenu.windowHeight
marginWidth = 10
marginHeight = 10
numOfCells = GameModel.numOfCells
cellWidth = np.floor_divide(windowWidth-2*marginWidth, numOfCells)
marginWidth += np.floor_divide(np.remainder(windowWidth-2*marginWidth, numOfCells), 2)
cellHeight = np.floor_divide(windowHeight-2*marginHeight, numOfCells)
marginHeight += np.floor_divide(np.remainder(windowHeight-2*marginHeight, numOfCells), 2)
linesColor = (25, 25, 110)
def __init__(self, screen: pygame.Surface, gameModel: GameModel):
super().__init__()
self.gameModel = gameModel
self.board = self.board_init()
self.screen = screen
self.background = FunContainer.load_image("background.jpg")
self.background = pygame.transform.scale(self.background, (self.windowWidth, self.windowHeight))
self.draw_lines()
self.draw_thrones()
self.draw_walls()
self.gauntlet = None
self.blackBalls = None
self.whiteBalls = None
self.balls_init()
self.init_draw()
def balls_init(self):
if self.gameModel.player1.color == GameColor.BLACK:
blackBalls = self.gameModel.player1.balls
whiteBalls = self.gameModel.player2.balls
else:
blackBalls = self.gameModel.player2.balls
whiteBalls = self.gameModel.player1.balls
self.blackBalls = BallsContainer(blackBalls)
self.whiteBalls = BallsContainer(whiteBalls)
for position in self.blackBalls.ballsList:
blackBall = BlackBall()
blackBall.rect.center = Rect(self.board[position]).center
self.blackBalls.add(blackBall)
for position in self.whiteBalls.ballsList:
whiteBall = WhiteBall()
whiteBall.rect.center = Rect(self.board[position]).center
self.whiteBalls.add(whiteBall)
def balls_update(self):
activeColor = self.gameModel.activePlayer.color
if self.gameModel.player1Color == GameColor.WHITE:
self.whiteBalls.ballsList = self.gameModel.player1.balls
self.blackBalls.ballsList = self.gameModel.player2.balls
else:
self.whiteBalls.ballsList = self.gameModel.player2.balls
self.blackBalls.ballsList = self.gameModel.player1.balls
if activeColor == GameColor.WHITE:
numOfSprites = len(self.blackBalls)
numOfBalls = len(self.blackBalls.ballsList)
balls = self.whiteBalls
opballs = self.blackBalls
else:
numOfSprites = len(self.whiteBalls)
numOfBalls = len(self.whiteBalls.ballsList)
balls = self.blackBalls
opballs = self.whiteBalls
if numOfBalls != numOfSprites:
opballs.sprites()[0].kill()
for i in range(len(balls)):
balls.sprites()[i].rect.center = Rect(self.board[balls.ballsList[i]]).center
def init_draw(self):
self.screen.blit(self.background, (0, 0))
self.blackBalls.draw(self.screen)
self.whiteBalls.draw(self.screen)
def board_init(self):
board = np.array([[Rect([0]*4)]*self.numOfCells]*self.numOfCells)
for i in range(self.numOfCells):
for j in range(self.numOfCells):
board[j][i] = Rect(i*self.cellWidth+self.marginWidth, j*self.cellHeight+self.marginHeight, self.cellWidth-1, self.cellHeight-1)
return board
def cartesian2board(self, pos):
x = np.floor_divide(pos[1] - self.marginWidth, self.cellWidth)
if x >= self.numOfCells:
x = self.numOfCells - 1
elif x <= 0:
x = 0
y = np.floor_divide(pos[0] - self.marginHeight, self.cellHeight)
if y >= self.numOfCells:
y = self.numOfCells - 1
elif y <= 0:
y = 0
return x, y
def draw_lines(self):
for i in range(self.numOfCells):
start = Rect(self.board[i][0]).center
stop = Rect(self.board[i][self.numOfCells-1]).center
pygame.draw.line(self.background, self.linesColor, start, stop, 1)
for j in range(self.numOfCells):
start = Rect(self.board[0][j]).center
stop = Rect(self.board[self.numOfCells-1][j]).center
pygame.draw.line(self.background, self.linesColor, start, stop, 1)
def draw_thrones(self):
resolution = (60, 60)
blueThrone = FunContainer.load_image("blue-throne.jpg", -1)
redThrone = FunContainer.load_image("red-throne.jpg", -1)
blueThrone = pygame.transform.scale(blueThrone, resolution)
redThrone = pygame.transform.scale(redThrone, resolution)
FunContainer.center_blit(self.background, blueThrone, Rect(self.board[self.gameModel.player1ThronePos]))
FunContainer.center_blit(self.background, redThrone, Rect(self.board[self.gameModel.player2ThronePos]))
def draw_walls(self):
resolution = (42, 42)
wallImage = FunContainer.load_image("wall.jpg")
wallImage = pygame.transform.scale(wallImage, resolution)
for i in range(self.numOfCells):
for j in range(self.numOfCells):
if self.gameModel.wallsMap[i][j]:
FunContainer.center_blit(self.background, wallImage, Rect(self.board[(i, j)]))
def view_update(self):
self.screen.blit(self.background, self.gauntlet.rect, self.gauntlet.rect)
self.blackBalls.clear(self.screen, self.background)
self.blackBalls.draw(self.screen)
self.whiteBalls.clear(self.screen, self.background)
self.whiteBalls.draw(self.screen)
self.gauntlet.update()
self.screen.blit(self.gauntlet.image, self.gauntlet.rect)
pygame.display.update()
<file_sep>/README.md
# Castle game
An implementation of an artificial inteligence algorithm min-max with alfa-beta pruning.
Algorithm together with heuristic function extends game created by
<a href="https://github.com/wojciech1871/PADPy-PD1">wojciech1871</a> and <a href="https://github.com/MichalTurski">MichalTurski</a>.
### 1. Requirements
* Python 3.* (version 3.6.5 or higher recommended).
* Python packages: `pygame` nad `numpy`.
### 2. Game launching
* Download repository from Github, go to project's directory and type in terminal:
`<python_interpreter> start.py`
* For each player provide a parameter that definces a depth of the search tree.
Higher value results in a better artificial inteligence of computer players.
Game enables to watch a match between two computer players with different search depth.
Computer with higher depth search value wins. <br>
It is recommended for parameters to be within range 1-4.
* example:
`Player1's deep: 2` <br>
`Player2's deep: 4` <br>
### 3. Game rules
<p align="center">
<img width="600" height="600" src="resources/game-board-example.png">
</p>
* **Walls and castle** - There are 3 type of cells: walls, thrones and normal (ground)
From the setup all stones are on wall cells.
* **Turn** - At each turn, each player moves a friendly stone
A stone may orthogonally slide any number of empty cells.
Sliding is only valid on the ground or on the wall. A slide cannot cross both types of cells.
A stone may move to a different type of cell (from a wall to the ground, or vice versa) if that cell is orthogonally adjacent.
It's possible to capture by replacement (capture is not mandatory).
* **Goal** - A player wins when he places one stone at the opponent throne.
### 4. Game options
* Turning sound on/off.
* Choosing game mode between 'Playes vs Computer' and 'Computer vs Computer'
* During game:
- press `ESC` button in order to back to menu.
<file_sep>/GameMenu.py
import pygame
from pygame.locals import *
import os
import pickle
class FunContainer:
main_dir = os.path.split(os.path.abspath(__file__))[0]
data_dir = os.path.join(main_dir, "resources")
def __init__(self):
pass
@classmethod
def load_image(cls, name, colorkey=None):
fullname = os.path.join(cls.data_dir, name)
try:
image = pygame.image.load(fullname)
except pygame.error:
print("Cannot load image {}".format(name))
raise SystemExit
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image
@classmethod
def load_sound(cls, name):
class NoneSound:
def play(self): pass
if not pygame.mixer:
return NoneSound()
fullname = os.path.join(cls.data_dir, name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error:
print("Cannot load sound: {}".format(name))
raise SystemExit
return sound
@classmethod
def font_render(cls, text, size):
fullname = os.path.join(cls.data_dir, "Aller_Lt.ttf")
font = pygame.font.Font(fullname, size)
return font.render(text, 1, (0, 0, 0))
@classmethod
def center_blit(cls, destination: pygame.Surface, image: pygame.Surface, area: pygame.Rect):
imageRect = image.get_rect()
imageRect.center = area.center
destination.blit(image, imageRect)
class Button(pygame.sprite.Sprite):
def __init__(self, size, text, position):
super().__init__()
self.baseImage = FunContainer.font_render(text, size)
self.onFocusImage = FunContainer.font_render(text, size + 5)
self.image = self.baseImage
self.rect = self.image.get_rect()
self.rect.center = position.center
def focus(self):
self.image = self.onFocusImage
def unfocus(self):
self.image = self.baseImage
def update(self):
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.focus()
else:
self.unfocus()
def action(self):
pass
class ButtonsContainer(pygame.sprite.RenderPlain):
def __init__(self):
super().__init__()
def focused_sprite(self, position):
for sprite in self.sprites():
if sprite.rect.collidepoint(position):
return sprite
return None
class GameMenu:
windowWidth = 800
windowHeight = 800
windowName = "Castle game"
def __init__(self):
self.screen = pygame.display.set_mode((self.windowWidth, self.windowHeight))
pygame.display.set_caption(self.windowName)
self.icon = FunContainer.load_image("castle-icon.jpg")
self.icon = pygame.transform.scale(self.icon, (32, 32))
pygame.display.set_icon(self.icon)
self.background = FunContainer.load_image("castle-menu.jpg")
self.background = pygame.transform.scale(self.background, (self.windowWidth, self.windowHeight))
self.playButton = Button(55, "Play", Rect(110, 90, 100, 50))
self.optionsButton = Button(55, "Options", Rect(110, 200, 100, 50))
self.quitButton = Button(55, "Quit", Rect(110, 310, 100, 50))
self.allButtons = ButtonsContainer()
self.allButtons.add(self.playButton, self.quitButton, self.optionsButton)
self.gauntlet = None
def init_draw(self):
self.screen.blit(self.background, (0, 0))
self.allButtons.draw(self.screen)
pygame.display.update()
def view_update(self):
self.screen.blit(self.background, self.gauntlet.rect, self.gauntlet.rect)
self.allButtons.update()
self.allButtons.clear(self.screen, self.background)
self.allButtons.draw(self.screen)
self.gauntlet.update()
self.screen.blit(self.gauntlet.image, self.gauntlet.rect)
pygame.display.update()
<file_sep>/GameModel.py
import numpy as np
from enum import Enum
import pygame
from pygame.locals import *
class EndGame(Exception):
pass
class GameColor(Enum):
WHITE = 0
BLACK = 1
@classmethod
def second_color(cls, color):
if color == cls.WHITE:
return cls.BLACK
elif color == cls.BLACK:
return cls.WHITE
class Player:
def __init__(self, color, balls, opponentThrone):
self.color = color
self.balls = balls
self.opponentThrone = opponentThrone
class GameModel:
numOfCells = 19
initPlayer1BallPositions = [(11, 2), (11, 16), (18, 5), (18, 13), (13, 7), (13, 11), (17, 7), (17, 11)]
initPlayer2BallPositions = [(7, 2), (7, 16), (0, 5), (0, 13), (5, 7), (5, 11), (1, 7), (1, 11)]
player1ThronePos = (3, 9)
player2ThronePos = (15, 9)
player1Color = GameColor.BLACK
wallsMap=None
def __init__(self):
self.player1 = Player(self.player1Color, self.initPlayer1BallPositions.copy(), self.player2ThronePos)
self.player2 = Player(GameColor.second_color(self.player1Color), self.initPlayer2BallPositions.copy(), self.player1ThronePos)
self.ballsMap = None
self.model_state_init()
self.activePlayer = self.player1
def model_state_init(self):
GameModel.wallsMap = np.array([[False]*self.numOfCells]*19, dtype=bool)
self.wall_map_init()
self.ballsMap = np.array([[None]*19]*19, dtype=GameColor)
self.set_balls_map(self.initPlayer1BallPositions, self.initPlayer2BallPositions)
def wall_map_init(self):
wallsMap = GameModel.wallsMap
for i in range(1, 8):
wallsMap[(i, 2)] = True
wallsMap[(i, 16)] = True
wallsMap[(self.numOfCells - i - 1, 2)] = True
wallsMap[(self.numOfCells - i - 1, 16)] = True
for i in range(0, 6):
wallsMap[(i, 5)] = True
wallsMap[(i, 13)] = True
wallsMap[(self.numOfCells - i - 1, 5)] = True
wallsMap[(self.numOfCells - i - 1, 13)] = True
for i in range(1, 6):
wallsMap[(i, 7)] = True
wallsMap[(i, 11)] = True
wallsMap[(self.numOfCells - i - 1, 7)] = True
wallsMap[(self.numOfCells - i - 1, 11)] = True
for i in range(3, 9):
wallsMap[(7, i)] = True
wallsMap[(11, i)] = True
wallsMap[(7, self.numOfCells - i - 1)] = True
wallsMap[(11, self.numOfCells - i - 1)] = True
for i in range(7, 12):
wallsMap[(5, i)] = True
wallsMap[(13, i)] = True
wallsMap[(1, 8)] = True
wallsMap[(1, 10)] = True
wallsMap[(17, 8)] = True
wallsMap[(17, 10)] = True
def set_balls_map(self, player1_balls, player2_balls):
self.ballsMap = np.array([[None]*19]*19, dtype=GameColor)
for position in player1_balls:
self.ballsMap[position] = self.player1.color
for position in player2_balls:
self.ballsMap[position] = self.player2.color
def is_something_between(self, map: np.ndarray, startPos: tuple, endPos: tuple, direction, delta, negated=False):
# negated parameter:
# if false check if there is any wall between clear cells
# if true check if there is any clear cell between walls
if delta < 0:
startPos, endPos = endPos, startPos
if direction == 0:
for cell in map[startPos[0]+1:endPos[0], startPos[1]]:
if np.logical_xor(bool(cell), negated):
return True
elif direction == 1:
for cell in map[startPos[0], startPos[1]+1:endPos[1]]:
if np.logical_xor(bool(cell), negated):
return True
return False
def valid_move(self, startPos: tuple, endPos: tuple):
dy = endPos[0] - startPos[0]
dx = endPos[1] - startPos[1]
delta = dy
direction = 0
if not np.logical_xor(dx, dy):
return False
if not dy:
delta = dx
direction = 1
isStartWall = GameModel.wallsMap[startPos]
isEndWall = GameModel.wallsMap[endPos]
if np.logical_xor(isStartWall, isEndWall):
if abs(delta) > 1:
return False
elif not isStartWall and not isEndWall:
if self.is_something_between(GameModel.wallsMap, startPos, endPos, direction, delta):
return False
else:
if self.is_something_between(GameModel.wallsMap, startPos, endPos, direction, delta, True):
return False
if direction:
if self.player1ThronePos[0] == startPos[0]:
if min(startPos[1], endPos[1]) < self.player1ThronePos[1] < max(startPos[1], endPos[1]):
return False
if self.player2ThronePos[0] == startPos[0]:
if min(startPos[1], endPos[1]) < self.player2ThronePos[1] < max(startPos[1], endPos[1]):
return False
else:
if self.player1ThronePos[1] == startPos[1]:
if min(startPos[0], endPos[0]) < self.player1ThronePos[0] < max(startPos[0], endPos[0]):
return False
if self.player2ThronePos[1] == startPos[1]:
if min(startPos[0], endPos[0]) < self.player2ThronePos[0] < max(startPos[0], endPos[0]):
return False
return True
def change_player(self):
self.activePlayer = self.second_player()
def second_player(self):
if self.activePlayer == self.player1:
return self.player2
else:
return self.player1
def move_ball(self, startPos: tuple, endPos: tuple) -> bool:
ballsMoving = self.activePlayer.balls
if not self.valid_move(startPos, endPos):
return False
else:
if self.ballsMap[endPos]:
self.beat(endPos)
self.ballsMap[startPos] = None
self.ballsMap[endPos] = self.activePlayer.color
ballsMoving[ballsMoving.index(startPos)] = endPos
if self.activePlayer.opponentThrone == endPos:
raise EndGame
return True
def beat(self, endPos: tuple):
ballsFromWhichRemoving = self.second_player().balls
ballsFromWhichRemoving.remove(endPos)
# Artificial intelligence core, finds best move and overwrites players bills positions
def intelligent_move(self, depth):
if self.activePlayer.color == self.player1Color:
maximizingPlayer=True
else:
maximizingPlayer=False
current_state = Node(self.player1.balls, self.player2.balls)
best_child = self.min_max_algorythm(current_state, depth, maximizingPlayer)
self.player1.balls=best_child.player1_balls.copy()
self.player2.balls=best_child.player2_balls.copy()
self.set_balls_map(self.player1.balls, self.player2.balls)
# min-max algorythm, it returns the greatest of the child nodes - depends on who is current active player
def min_max_algorythm(self, node, depth, maximizingPlayer):
nodes_evaluation=[]
nodes_evaluation=nodes_evaluation+self.alphabeta_prunning_init(node, depth, -np.inf, np.inf, maximizingPlayer)
# print("I have checked ", len(nodes_evaluation), " of possible movements to take")
if maximizingPlayer:
i=-np.inf
for state_and_value in nodes_evaluation:
if state_and_value[0]>i:
i=state_and_value[0]
best_node=state_and_value[1]
# print("I am maximizing player and I chose one with max value which is", i)
return best_node
else:
i=+np.inf
for state_and_value in nodes_evaluation:
if state_and_value[0]<i:
i=state_and_value[0]
best_node=state_and_value[1]
# print("I am minimizing player and I chose one with min value which is", i)
return best_node
# initilizing alphabetta prunning, returning nodes and evaluated value
def alphabeta_prunning_init(self, node, depth, alfa, beta, maximizingPlayer):
depth=depth-1
new_nodes=node.generate_new_nodes(maximizingPlayer)
# print("Number of generated child nodes ", len(new_nodes), "from level ", depth+1)
nodes_and_values=[]
if maximizingPlayer:
for state in new_nodes:
alfa=max(alfa, self.alphabeta_prunning(state,depth,alfa,beta, False))
if alfa>=beta:
nodes_and_values.append((beta, state))
else:
nodes_and_values.append((alfa, state))
else:
for state in new_nodes:
beta=min(beta, self.alphabeta_prunning(state,depth,alfa,beta, True))
if alfa>=beta:
nodes_and_values.append((alfa, state))
else:
nodes_and_values.append((beta, state))
return nodes_and_values
# alpha-beta prunning working in recursion, returns only value
def alphabeta_prunning(self, node, depth, alfa, beta, maximizingPlayer):
# it takes at least 11 turns to reach terminal node,
if depth==0 or node.terminal_node:
return self.heuristic_function(node)
depth=depth-1
new_nodes=node.generate_new_nodes(maximizingPlayer)
# print("Number of generated child nodes ", len(new_nodes), "from level ", depth+1)
if maximizingPlayer:
for state in new_nodes:
alfa=max(alfa, self.alphabeta_prunning(state,depth,alfa,beta, False))
if alfa>=beta:
return beta
return alfa
else:
value=np.inf
for state in new_nodes:
beta=min(beta, self.alphabeta_prunning(state,depth,alfa,beta, True))
if alfa>=beta:
return alfa
return beta
# minimize player: WHITE, maximizing player: BLACK
def heuristic_function(self, node):
start_value=0
# checking balls positions, awarding those being in chosen areas of an enemy castle
for ball in node.player2_balls:
if ball[0] in range(0,18) and ball[1] in range(8,11):
start_value-=5
if ball[0] in range(2,17) and ball[1] in range(0,8):
start_value-=10
if ball[0] in range(5,14) and ball[1] in range(0,6):
start_value-=10
if ball[0] in range(7,12) and ball[1] in range(0,6):
start_value-=10
if ball==self.player1ThronePos:
start_value-=1000000
for ball in node.player2_balls:
if ball[0] in range(0,18) and ball[1] in range(8,11):
start_value+=5
if ball[0] in range(2,17) and ball[1] in range(11,19):
start_value+=10
if ball[0] in range(5,14) and ball[1] in range(13,19):
start_value+=10
if ball[0] in range(7,12) and ball[1] in range(13,19):
start_value+=10
if ball==self.player1ThronePos:
start_value+=1000000
# heuristic which awards player with bigger quantity of bills left
start_value=start_value+(len(node.player1_balls)-len(node.player2_balls))*15
return start_value
def check_if_game_finish(self):
for position in self.player1.balls:
if position == self.player1ThronePos:
print("Player black won!")
return True
for position in self.player2.balls:
if position == self.player2ThronePos:
print("Player white won!")
return True
return False
class Node(GameModel):
def __init__(self, balls_1: list, balls_2: list, terminal_node=False):
self.player1_balls=balls_1
self.player2_balls=balls_2
self.terminal_node=terminal_node
# function that finds child nodes, returns list of class Node objects
def generate_new_nodes(self, maximizingPlayer) -> list:
child_nodes=[]
if maximizingPlayer:
for ball in self.player1_balls:
list_possible_endpos=self.find_possible_endpos(ball)
while list_possible_endpos:
player1_balls_copy=self.player1_balls.copy()
player2_balls_copy=self.player2_balls.copy()
player1_balls_copy.remove(ball)
endpos=list_possible_endpos.pop(0)
player1_balls_copy.append(endpos)
if endpos in self.player2_balls:
player2_balls_copy.remove(endpos)
if endpos == self.player1ThronePos:
terminal_node=True
print("Terminal node found! Check..!")
else: terminal_node=False
child_nodes.append(Node(player1_balls_copy, player2_balls_copy, terminal_node))
else:
for ball in self.player2_balls:
list_possible_endpos=self.find_possible_endpos(ball)
while list_possible_endpos:
player1_balls_copy=self.player1_balls.copy()
player2_balls_copy=self.player2_balls.copy()
player2_balls_copy.remove(ball)
endpos=list_possible_endpos.pop(0)
player2_balls_copy.append(endpos)
if endpos in self.player1_balls:
player1_balls_copy.remove(endpos)
if endpos == self.player2ThronePos:
terminal_node=True
print("Terminal node found! Check..!")
else: terminal_node=False
child_nodes.append(Node(player1_balls_copy, player2_balls_copy, terminal_node))
return child_nodes
# function that finds possible endpositions for ball position on input
def find_possible_endpos(self, ball: tuple) -> list:
list_endpos=[]
i=ball[0]
j=ball[1]
for coordinate in range(j+1, 19):
endPos=(i, coordinate)
if self.valid_move(ball, endPos):
list_endpos.append(endPos)
else: break
for coordinate in range(i+1, 19):
endPos=(coordinate, j)
if self.valid_move(ball, endPos):
list_endpos.append(endPos)
else: break
for coordinate in range(0, i):
endPos=(coordinate, j)
if self.valid_move(ball, endPos):
list_endpos.append(endPos)
else: break
for coordinate in range(0, j):
endPos=(i, coordinate)
if self.valid_move(ball, endPos):
list_endpos.append(endPos)
else: break
return list_endpos
<file_sep>/GameOptions.py
import pygame
from GameMenu import *
class Indicator(pygame.sprite.Sprite):
def __init__(self, size, textTrue, textFalse, position):
super().__init__()
self.trueImage = FunContainer.font_render(textTrue, size)
self.falseImage = FunContainer.font_render(textFalse, size)
self.trueRect = self.trueImage.get_rect()
self.falseRect = self.falseImage.get_rect()
self.trueRect.center = position.center
self.falseRect.center = position.center
self.image = None
self.rect = None
self.state = None
def set_state(self, state):
self.state = state
if self.state:
self.image = self.trueImage
self.rect = self.trueRect
else:
self.image = self.falseImage
self.rect = self.falseRect
def change_state(self):
if not self.state:
self.image = self.trueImage
self.rect = self.trueRect
else:
self.image = self.falseImage
self.rect = self.falseRect
self.state = not self.state
class GameOptions:
windowWidth = GameMenu.windowWidth
windowHeight = GameMenu.windowHeight
def __init__(self, screen: pygame.Surface):
self.screen = screen
self.background = FunContainer.load_image("castle-options.jpg")
self.background = pygame.transform.scale(self.background, (self.windowWidth, self.windowHeight))
self.soundButton = Button(55, "Sound", Rect(550, 90, 100, 50))
self.soundIndicator = Indicator(45, "Off", "On", Rect(550, 160, 100, 50))
self.changePlayerButton = Button(55, "Game mode", Rect(550, 230, 100, 50))
self.changePlayerIndicator = Indicator(45, "CvsC", "PvsC", Rect(550, 300, 100, 50))
self.backToMenuButton = Button(55, "Back to menu", Rect(550, 370, 100, 50))
self.allButtons = ButtonsContainer()
self.allIndicators = pygame.sprite.RenderPlain()
self.allButtons.add(self.soundButton, self.changePlayerButton, self.backToMenuButton)
self.allIndicators.add(self.soundIndicator, self.changePlayerIndicator)
self.gauntlet = None
def init_draw(self):
self.screen.blit(self.background, (0, 0))
self.allButtons.draw(self.screen)
pygame.display.update()
def view_update(self):
self.screen.blit(self.background, self.gauntlet.rect, self.gauntlet.rect)
self.allButtons.update()
self.allButtons.clear(self.screen, self.background)
self.allButtons.draw(self.screen)
self.allIndicators.update()
self.allIndicators.clear(self.screen, self.background)
self.allIndicators.draw(self.screen)
self.gauntlet.update()
self.screen.blit(self.gauntlet.image, self.gauntlet.rect)
pygame.display.update()
| 7f6c32dfba741234c6a68f20da3a708bb05d819b | [
"Markdown",
"Python"
] | 7 | Python | LukaszNiewinski/Castle_Game_min_max | c6eef01a11d15babcc58543d2904f54aa49deaa4 | 33fcc294c9d4242510dc0e82c62066786db73014 |
refs/heads/master | <repo_name>PemrogramanWebDasarDPH2I44101/update-dan-delete-hafizhazizin<file_sep>/formupdate.php
<?php
require("koneksi.php");
$id = $_GET['id'];
$sql = $pdo -> prepare("SELECT * FROM mahasiswa WHERE id = '$id'");
$sql -> execute();
$data = $sql -> fetch(PDO::FETCH_ASSOC);
?>
<form method="post">
<table>
<th><h3>Silahkan Isi Data Dibawah Ini</h3></th>
<tr>
<td>Nim</td>
<td>:</td>
<td><input type="text" name="nim" id="nim" value="<?php echo $data['nim'] ?>"></td>
</tr>
<tr>
<td>Nama</td>
<td>:</td>
<td><input type="text" name="nama" id="nama" value="<?php echo $data['nama'] ?>"></td>
</tr>
<tr>
<td>Kelas</td>
<td>:</td>
<td><select name="kelas">
<option value="<?php echo $data['kelas'] ?>"><?php echo $data['kelas'] ?></option>
</select></td>
</tr>
<tr>
<td>Tanggal Lahir</td>
<td>:</td>
<td><input type="date" name="tgl" id="tgl" value="<?php echo $data['tgl_lahir'] ?>"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['nama'])){
$nim =$_POST['nim'];
$nama =$_POST['nama'];
$kelas =$_POST['kelas'];
$tgl =$_POST['tgl'];
$sql= $pdo -> prepare("UPDATE mahasiswa SET nim='$nim',nama='$nama',kelas='$kelas',tgl_lahir='$tgl'");
$sql -> execute();
if($sql){
header("Location:view.php");
}else{
echo "Data gagal Update";
}
}
?>
<file_sep>/list.php
<?php
require("koneksi.php");
?>
<form method="post">
<table border="1">
<th>No</th>
<th>Nim</th>
<th>Nama</th>
<th>Kelas</th>
<th>Tanggal Lahir</th>
<?php
$no=1;
$query = $pdo -> prepare("SELECT * FROM mahasiswa");
$query -> execute();
while($data =$query -> fetch(PDO :: FETCH_ASSOC)){
?>
<tr>
<td><?php echo $no;?></td>
<td><?php echo $data['nim'];?></td>
<td><?php echo $data['nama'];?></td>
<td><?php echo $data['kelas'];?></td>
<td><?php echo $data['tgl_lahir'];?></td>
<td><a href="delet.php?id=<?php echo $data['id']?>">Hapus</a> | <a href="formupdate.php?id=<?php echo $data['id']?>">Update</a></td>
</tr>
<?php
$no++;
}
?>
</table>
</form>
<file_sep>/submit.php
<?php
require("koneksi.php");
?>
<?php
if (isset($_POST['nim'])) {
$nim =$_POST['nim'];
$nama =$_POST['nama'];
$kelas =$_POST['kelas'];
$tgl =$_POST['tgl'];
$query =$pdo ->prepare("INSERT INTO mahasiswa(nim,nama,kelas,tgl_lahir) VALUES ('$nim','$nama','$kelas','$tgl')");
$query -> execute();
if($query)
header("location:view.php");
else{
die("Tambah Data Gagal");
}
}
?>
<file_sep>/delet.php
<?php
require("koneksi.php");
$id = $_GET['id'];
$sql = $pdo -> prepare("DELETE FROM mahasiswa WHERE id = $id");
$sql -> execute();
if ($sql) {
header("Location:view.php");
}else {
echo "Data gagal di hapus";
}
?>
| caa6bf81afd6feb755bbdaa7867450bd648e5ac8 | [
"PHP"
] | 4 | PHP | PemrogramanWebDasarDPH2I44101/update-dan-delete-hafizhazizin | 706d2fdc120cf3ead3deeefa6fcf2152b635e742 | 9d2c70921f427bbd3b8f7ce50a5064dc4a1e9cd8 |
refs/heads/master | <repo_name>shreelimbkar/node-pa11i-codecept<file_sep>/index.js
const express = require('express');
const app = require('express')();
const bodyParser = require('body-parser');
const hbs = require('hbs');
const server = require('http').Server(app);
const port = 4400;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// hbs.registerPartials(__dirname + './views');
app.set('views', __dirname + '/public/views');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', (req, res) => {
// res.sendFile(__dirname + '/public/index.html');
res.render('index');
});
app.post('/welcome', (req, res) => {
// console.log('params', req.body);
// res.sendFile(__dirname + '/public/welcome.html');
res.render('welcome', { name: req.body.uname })
});<file_sep>/README.md
# Node webapp demonstarte - pa11i and codecept
| 6e84bc14ed0715ad9b88eb758f4faed1640e9373 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | shreelimbkar/node-pa11i-codecept | b3d57dbb0ebcda47a50538d2d099c3dde254e470 | 2e47470339fdc08856b44315ebd65ab2039f3b8d |
refs/heads/master | <repo_name>SuhasAcharya/groupchat<file_sep>/index.js
var express = require('express');
var socket = require('socket.io');
//App Setup
var port = process.env.PORT || 5000;
var app = express();
var server = app.listen(port,function(){
console.log('listing to port 5000');
});
//Static Files
app.use(express.static('public'));
//Socket setup
var io = socket(server);
io.on('connection',function(socket){
console.log('connection was successful');
socket.on('chat',function(data){
io.sockets.emit('chat',data);
});
socket.on('typing',function(data){
socket.broadcast.emit('typing', data);
});
});<file_sep>/requirements.txt
appdirs==1.4.3
click==7.1.1
distlib==0.3.0
filelock==3.0.12
Flask==1.1.2
Flask-SocketIO==4.3.1
Flask-SQLAlchemy==2.4.1
gunicorn==20.0.4
importlib-metadata==1.6.0
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
peewee==3.13.3
Pygments==2.6.1
python-engineio==3.13.1
python-socketio==4.6.0
six==1.14.0
SQLAlchemy==1.3.16
sqlite-db-tools==0.1
sqlite-web==0.3.6
virtualenv==20.0.18
Werkzeug==1.0.1
zipp==3.1.0
| 722fd808bcc66190f74af52e242ecfad8df62ffb | [
"JavaScript",
"Text"
] | 2 | JavaScript | SuhasAcharya/groupchat | 35197a922f47f681948c00526ba892ff84872ebb | 96e7c2c2af19a72060089d7e2d10ebb32aa0534a |
refs/heads/master | <repo_name>pkibbey/routing<file_sep>/index.js
window.addEventListener('hashchange', () => {
// Output current hash
console.log('complete hash = ', window.location.hash);
// strip the first hash and the forward slash from the string
let urlHash = window.location.hash.substring(2);
console.log('urlHash = ', urlHash);
});
<file_sep>/README.md
# routing
JavaScript routing algorithm
| 1a672d794edb4b33bfd0d1adcabfebb210deaace | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | pkibbey/routing | ebad60ffd114a402a80e4961aba043aaae61c284 | 4b1aeba86bf3663d8d805b3911bfcb2684c9d0ac |
refs/heads/master | <repo_name>Sridharv-ec/SeleniumPrograms<file_sep>/src/main/java/apache/poi/WordpressLogin.java
package apache.poi;
import common.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class WordpressLogin {
WebDriver driver;
@Test(dataProvider = "wordpressData")
public void loginToWordPress(String userName, String password) throws InterruptedException {
ChromeOptions chromeOptions = new ChromeOptions();
//if(System.getProperty("os.name") .toLowerCase().indexOf("win")>0){
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\src\\main\\resources\\webdriver\\chromedriver.exe");
chromeOptions.addArguments("--start-maximized");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--disable-popup-blocking");
Thread.sleep(2000);
driver = new ChromeDriver(chromeOptions);
//((FirefoxDriver)driver).manage().window().maximize();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
driver.findElement(By.id("user_login")).sendKeys(userName);
driver.findElement(By.id("user_pass")).sendKeys(<PASSWORD>);
driver.findElement(By.id("wp-submit")).click();
Thread.sleep(5000);
org.testng.Assert.assertTrue(driver.getTitle().contains("Dashboard"),"user not able to login successfully");
System.out.println("Page title verified - user able to login successfully");
}
@DataProvider(name="wordpressData")
public Object[][] passData(){
Object[][] data = new Object[3][2];
data[0][0] = "admin1";
data[0][1] = "demo1";
data[1][0] = "admin";
data[1][1] = "demo123";
data[2][0] = "admin2";
data[2][1] = "demo1234";
return data;
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SeleniumPrograms</groupId>
<artifactId>SeleniumProject</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jexcelapi/jxl -->
<dependency>
<groupId>jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.13.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>E:\Sridhar\AutomationFolder\AutomationBySridhar\Frameworks\cucumber-jvm-testng-integration-master\testng.xml</suiteXmlFile>
</suiteXmlFiles>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/main/java/Selenium/ChromeDesiredCapabilities.java
package Selenium;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
public class ChromeDesiredCapabilities {
WebDriver driver;
@BeforeClass
void setup(){
System.out.println("Launching IE browser");
System.setProperty("webdriver.chrome.driver","E:\\Sridhar\\AutomationFolder\\AutomationBySridhar\\SeleniumProgramms\\src\\main\\resources\\webdriver\\IEDriverServer.exe");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
Proxy proxy = new Proxy();
proxy.setHttpProxy("myhttpproxy:3337");
options.setProxy(proxy);
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
}
}
<file_sep>/src/main/java/csv/ReadCsvFiles.java
package csv;
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public class ReadCsvFiles {
public static void main(String[] args) throws IOException {
CSVReader csvReader = new CSVReader(new FileReader("E:\\Sridhar\\AutomationFolder\\AutomationBySridhar\\SeleniumProgramms\\src\\main\\resources\\DataFiles\\DataSheet - Copy.csv"));
List<String[]> li = csvReader.readAll();
Iterator<String[]> itr = li.iterator();
while (itr.hasNext()){
String[] str = itr.next();
System.out.println(" Values are ");
for(int i = 0; i < str.length; i++){
System.out.println(" "+str[i]);
}
System.out.println(" ");
}
}
}
| b6939ab1383077f138165a8645613ea9a69a18c1 | [
"Java",
"Maven POM"
] | 4 | Java | Sridharv-ec/SeleniumPrograms | 443556fc1c2b3f3478c8dbc28ffd3e28937fba2a | 5e13ab770712fd791a8222871699bc4bb9015597 |
refs/heads/master | <file_sep>import java.io.*;
import java.util.*;
/*
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
*/
class NimGame {
public static void main(String[] args) {
int n = 7;
if(canWinNim(n)){
System.out.println("You will be able to win");
}else{
System.out.println("You will not be able to win");
}
}
public static boolean canWinNim(int n){
if(n%4==0){
return false;
}else{
return true;
}
// 0: unable to win; 1/2/3: able to win if 1/2/3 are entered in that run
//0 1 2 3 0 1 2 3 0 1 2 3
//4 5 6 7 8 9 10 11 12
}
}
<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Birthday Cake Candles
Colleen is turning n years old! She has n candles of various heights on her cake, and candle i has height i . Because the taller candles tower over the shorter ones, Colleen can only blow out the tallest candles.
Given the height i for each individual candle, find and print the number of candles she can successfully blow out.
Input Format
The first line contains a single integer, n, denoting the number of candles on the cake.
The second line contains n space-separated integers, where each integer i describes the height of candle i.
Constraints
1. 1 <= n <= 10^5
2. 1 <= height i <= 10^7
Output Format
Print the number of candles Colleen blows out on a new line.
Sample Input 0
4
3 2 1 3
Sample Output 0
2
Explanation 0
We have one candle of height 1, one candle of height 2, and two candles of height 3. Colleen only blows out the tallest candles, meaning the candles where height = 3. Because there are 2 such candles, we print 2 on a new line.
*/
public class BlowCandles {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int height[] = new int[n];
int tallest = 0;
int count = 0;
int current;
for(int height_i=0; height_i < n; height_i++){
current = in.nextInt();
height[height_i] = current;
if(current > tallest){
tallest = current;
count = 1;
}else if(current == tallest){
count++;
}
}
System.out.println(count);
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Facebook
*
* Print all subsets of a given set
*
* E.g. set = [1,2,3]
*
* Output: {}, 1, 2, 3, {1,2}, {1,3}, {2,3}, {1,2,3}
*
* Iterative Solution
* Time Complexity = O(n 2 ^ n)
*
*
*/
class AllSubsets {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3};
ArrayList<ArrayList<Integer>> lst = subsets(arr);
for(int i = 0; i < lst.size(); i++){
System.out.print("{ ");
for(int j = 0; j < lst.get(i).size(); j++){
System.out.print(lst.get(i).get(j) + " ");
}
System.out.println("}");
}
}
public static ArrayList<ArrayList<Integer>> subsets(int[] arr){
int len = arr.length;
ArrayList<ArrayList<Integer>> lst = new ArrayList<ArrayList<Integer>>();
// 2^n subsets can be formed from an array of size n
int size = (int)Math.pow(2, len);
for(int i = 0; i < size; i++){
String num = Integer.toBinaryString(i);
ArrayList<Integer> inner = new ArrayList<Integer>();
// Iterate from (2^n)-1 to 0
for(int j = num.length()-1; j >= 0; j--){
// 1 represents that this subset has this element
if(Integer.valueOf(num.charAt(j)+"") == 1){
inner.add(arr[num.length()-1-j]);
}
}
lst.add(i, inner);
}
return lst;
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* LeetCode.com
*
* Given a non-negative integer num, repeatedly add all its digits until the
* result has only one digit.
* For example:
* Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has
* only one digit, return it.
*
*/
class AddDigits {
public static void main(String[] args) {
int num = 9991;
System.out.println(addDigit(num));
System.out.println(digitalRoot(num));
}
//Method using while loop
public static int addDigit(int num){
int count = 0;
while(num > 9){
while(num > 9){
count += num % 10;
num /= 10;
}
num = count + num;
count = 0;
}
return num;
}
//Method using formula - O(1) Constant time
public static int digitalRoot(int num){
return num - 9*(int)(Math.floor((num-1) / 9));
}
}
<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Kangaroo
There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?
Input Format
A single line of four space-separated integers denoting the respective values of x1, v1, x2, and v2.
Constraints
1. 0 <= x1 <= x2 <= 10000
2. 1 <= v1 <= 10000
3. 1 <= v2 <= 10000
Output Format
Print YES if they can land on the same location at the same time; otherwise, print NO.
Note: The two kangaroos must land at the same location after making the same number of jumps.
Sample Input 0
0 3 4 2
Sample Output 0
YES
Explanation 0
The two kangaroos jump through the following sequence of locations:
1. 0 --> 3 --> 6 --> 9 --> 12
2. 4 --> 6 --> 8 --> 10 --> 12
Thus, the kangaroos meet after 4 jumps and we print YES.
Sample Input 1
0 2 5 3
Sample Output 1
NO
Explanation 1
The second kangaroo has a starting location that is ahead (further to the right) of the first kangaroo's starting location (i.e., x2 > x1). Because the second kangaroo moves at a faster rate (meaning v2 > v1) and is already ahead of the first kangaroo, the first kangaroo will never be able to catch up. Thus, we print NO.
*/
public class Kangaroo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x1 = in.nextInt();
int v1 = in.nextInt();
int x2 = in.nextInt();
int v2 = in.nextInt();
boolean flag = false;
int small = 0;
int big = 0;
int smallCount = 0;
int bigCount = 0;
if((x1 > x2 && v1 >= v2) || (x1 < x2 && v1 <= v2)){
flag = false;
}else{
if(x1 == x2 || ((x1 + v1) == (x2 + v2))){
flag = true;
}else{
if(x1 + v1 < x2 + v2){
small = x1 + v1;
big = x2 + v2;
smallCount = v1;
bigCount = v2;
}else{
small = x2 + v2;
big = x1 + v1;
smallCount = v2;
bigCount = v1;
}
while(small < big){
small += smallCount;
big += bigCount;
}
if(small == big){
flag = true;
}else{
flag = false;
}
}
}
if(flag){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Determine whether an integer is a palindrome.
* Do this without extra space.
*
*
*
*/
class PalindromeNumber {
public static void main(String[] args) {
int x = 15351;
//System.out.println(x);
System.out.println(isPalindrome(x));
}
public static boolean isPalindrome(int num){
String str = Integer.toString(num);
int len = str.length();
for(int i = 0; i < str.length()/2; i++){
if(str.charAt(i) != str.charAt(len-i-1)){
return false;
}
}
return true;
}
}
<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Day of the Programmer
Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.
From 1700 to 1917, Russia's official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia.
In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar, leap years are either of the following:
- Divisible by 400.
- Divisible by 4 and not divisible by 100.
Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
Input Format
A single integer denoting year y.
Constraints
1. 1700 <= y <= 2700
Output Format
Print the full date of Day of the Programmer during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.
Sample Input 0
2017
Sample Output 0
13.09.2017
Explanation 0
In the year y = 2017, January has 31 days, February has 28 days, March has 31 days, April has 30 days, May has 31 days, June has 30 days, July has 31 days, and August has 31 days. When we sum the total number of days in the first eight months, we get 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 = 243. Day of the Programmer is the 256th day, so then calculate 256 - 243 = 13 to determine that it falls on day 13 of the 9th month (September). We then print the full date in the specified format, which is 13.09.2017.
Sample Input 1
2016
Sample Output 1
12.09.2016
Explanation 1
Year y = 2016 is a leap year, so February has 29 days but all the other months have the same number of days as in . When we sum the total number of days in the first eight months, we get . Day of the Programmer is the 256th day, so then calculate 256 - 244 = 12 to determine that it falls on day 12 of the 9th month (September). We then print the full date in the specified format, which is 12.09.2016.
*/
public class DayOfProgrammer {
static boolean isLeap(int year){
return ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)));
}
static String solve(int year){
// Complete this function
int days = 31 + 31 + 30 + 31 + 30 + 31 + 31;
int feb;
if(year > 1918){
if(isLeap(year)){
feb = 29;
}else {
feb = 28;
}
}else if (year < 1918){
if(year % 4 == 0){
feb = 29;
}else{
feb = 28;
}
}else{
if(year % 4 == 0){
feb = 29;
}else{
feb = 28;
}
feb -= 14;
feb+=1;
}
days += feb;
int day = 256 - days;
return Integer.toString(day) + ".09." + Integer.toString(year);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int year = in.nextInt();
String result = solve(year);
System.out.println(result);
}
}
<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Apple and Orange
Sam's house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where s is the start point and t is the end point. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point a and the orange tree is at point b.
When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. A negative value of d means the fruit fell d units to the tree's left, and a positive value of d means it falls d units to the tree's right.
Given the value of d for m apples and n oranges, can you determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range [s,t])? Print the number of apples that fall on Sam's house as your first line of output, then print the number of oranges that fall on Sam's house as your second line of output.
Input Format
The first line contains two space-separated integers denoting the respective values of s and t.
The second line contains two space-separated integers denoting the respective values of a and b.
The third line contains two space-separated integers denoting the respective values of m and n.
The fourth line contains m space-separated integers denoting the respective distances that each apple falls from point a.
The fifth line contains n space-separated integers denoting the respective distances that each orange falls from point b.
Constraints
1. 1 <= s,t,a,b,m,n <= 10^5
2. -10^5 <= d <= 10^5
3. a < s < t < b
Output Format
Print two lines of output:
1. On the first line, print the number of apples that fall on Sam's house.
2. On the second line, print the number of oranges that fall on Sam's house.
Sample Input 0
7 11
5 15
3 2
-2 2 1
5 -6
Sample Output 0
1
1
Explanation 0
The first apple falls at position 5 - 2 = 3.
The second apple falls at position 5 + 2 = 7.
The third apple falls at position 5 + 1 = 6.
The first orange falls at position 15 + 5 = 20.
The second orange falls at position 15 - 6 = 9.
Only one fruit (the second apple) falls within the region between 7 and 11, so we print 1 as our first line of output.
Only the second orange falls within the region between 7 and 11, so we print 1 as our second line of output.
*/
public class AppleOrange {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int t = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int m = in.nextInt();
int n = in.nextInt();
int pos, dist;
int app = 0;
int oran = 0;
int[] apple = new int[m];
for(int apple_i=0; apple_i < m; apple_i++){
dist = in.nextInt();
apple[apple_i] = dist;
pos = a + dist;
if(pos >= s && pos <= t){
app++;
}
}
int[] orange = new int[n];
for(int orange_i=0; orange_i < n; orange_i++){
dist = in.nextInt();
orange[orange_i] = dist;
pos = b + dist;
if(pos >= s && pos <= t){
oran++;
}
}
System.out.println(app);
System.out.println(oran);
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Check if a given string is Palindrome
*/
class PalindromeString {
public static void main(String[] args) {
String str = "A man, a plan, a canal, Panama";
if(isPalindrome(str)){
System.out.println("This is a Palindrome");
}else{
System.out.println("This is not a Palindrome");
}
}
public static boolean isPalindrome(String strOriginal){
String str = strOriginal.toLowerCase();
if(str.length() == 0 || str.length() == 1){
return true;
}
int leftPtr = 0;
int rightPtr = str.length();
while(leftPtr <= rightPtr){
Character left = str.charAt(leftPtr);
Character right = str.charAt(rightPtr-1);
if(!Character.isDigit(left) && !Character.isLetter(left)){
leftPtr++;
continue;
}
if(!Character.isDigit(right) && !Character.isLetter(right)){
rightPtr--;
continue;
}
if(str.charAt(leftPtr) != str.charAt(rightPtr-1)){
return false;
}
leftPtr++;
rightPtr--;
}
return true;
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Reverse digits of an integer.
*
*
* Example1: x = 123, return 321
* Example2: x = -123, return -321
*
*
*/
class Solution {
public static void main(String[] args) {
int x = -214;
System.out.println(reverseInteger(x));
}
public static int reverseInteger(int num){
int ans;
boolean positive;
if(num >= 0){
positive = true;
if(num < 10 && num >= 0){
return num;
}
}else{
positive = false;
if(num == Math.abs(num)){
return 0;
}
num = Math.abs(num);
}
String res = new String("");
while(num > 9){
int digit = num % 10;
res = res.concat(Integer.toString(digit));
num /= 10;
}
res = res.concat(Integer.toString(num));
ans = convertToInt(res);
if(!positive){
ans *= -1;
}
return ans;
}
public static int convertToInt(String str){
int res = 0;
try{
res = Integer.parseInt(str);
}catch(NumberFormatException e){
return 0;
}
return res;
}
}
<file_sep>/*
LeetCode.com
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
*/
class PalindromePermutation {
public static void main(String[] args){
String str = "code";
System.out.println(formPalindrome(str));
}
public static boolean formPalindrome(String str){
int[] arr = new int[256];
Arrays.fill(arr, 0);
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
arr[(int)c]++;
}
int count = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] % 2 != 0){
count += 1;
}
}
return count <= 1;
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Given an array nums, write a function to move all 0's to the end of it
* while maintaining the relative order of the non-zero elements.
*
*
* For example, given nums = [0, 1, 0, 3, 12], after calling your function,
* nums should be [1, 3, 12, 0, 0].
*
* 1. You must do this in-place without making a copy of the array.
* 2. Minimize the total number of operations.
*
*
*/
class MoveZeros {
public static void main(String[] args) {
int[] arr = new int[]{0,1,0,3,12};
int[] res = new int[arr.length];
res = moveZeros(arr);
for(int i = 0; i < res.length; i++){
System.out.println(res[i]);
}
}
public static int[] moveZeros(int[] arr){
int pointer = 0;
boolean set = false;
for(int i = 0; i < arr.length; i++){
if(!set && arr[i] == 0){
pointer = i;
set = true;
continue;
}
if(set && arr[i] != 0){
int tmp = arr[i];
arr[i] = arr[pointer];
arr[pointer] = tmp;
pointer++;
}
}
return arr;
}
}
<file_sep>/*
VMWare Interview Round 2
Implement Binary Search
Implement Generic Binary Search (Java Generics)
Implement Node Class Declaration
*/
public class BinarySearch<T extends Comparable<T>> {
private T[] data;
public BinarySearch(T[] data) {
this.data = data;
}
public int search(Comparable<T> key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
T midVal = data[mid];
int result = key.compareTo(midVal);
if (result < 0) {
high = mid - 1;
}
else if (result > 0) {
low = mid + 1;
}
else {
return mid;
}
}
return -1;
}
}
public int binarySearch(int[] data, int size, int key){
int low = 0;
int high = size - 1;
while(high >= low){
int mid = (high + low) / 2;
if(data[mid] == key){
return mid;
}
if(data[mid] < key){
low = mid + 1;
}
if(data[mid] > key){
high = mid - 1;
}
}
return -1;
}
class Node{
int data;
Node left;
Node right;
public Node(int num){
data = num;
Node left = null;
Node right = null;
}
}<file_sep>import java.io.*;
import java.util.*;
/*
* LeetCode.com
*
*
* Given an array of integers, find if the array contains any duplicates.
* Your function should return true if any value appears at least twice in
* the array, and it should return false if every element is distinct.
*
*
*/
class ContainsDuplicates {
public static void main(String[] args) {
int[] nums = new int[]{1,2,3,4,5,6,21,9};
System.out.println(containsDuplicate(nums));
}
public static boolean containsDuplicate(int[] nums){
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(set.contains(nums[i])) return true;
set.add(nums[i]);
}
return false;
}
}
<file_sep>
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Sequence Equation
You are given a sequence of n integers, p(1), p(2), p(3),..., p(n). Each element in the sequence is distinct and satisfies 1 <= p(x) <= n. For each x where 1<= x <= n, find any integer y such that p(p(y)) = x and print the value of y on a new line.
Input Format
The first line contains an integer, n, denoting the number of elements in the sequence.
The second line contains n space-separated integers denoting the respective values of p(1), p(2), p(3),..., p(n).
Constraints
1. 1 <= n <= 50
2. 1 <= p(x) <= 50, where 1 <= x <= n.
3. Each element in the sequence is distinct.
Output Format
For each x from 1 to n, print an integer denoting any valid y satisfying the equation p(p(y)) = x on a new line.
Sample Input 0
3
2 3 1
Sample Output 0
2
3
1
Explanation 0
Given the values of p(1) = 2, p(2) = 3, and p(3) = 1, we calculate and print the following values for each x from 1 to n:
x = 1 => p(3) = p(p(2)) = p(p(y)) , so we print the value of y=2 on a new line.
x = 2 => p(1) = p(p(3)) = p(p(y)) , so we print the value of y=3 on a new line.
x = 3 => p(2) = p(p(1)) = p(p(y)) , so we print the value of y=1 on a new line.
*/
public class SequenceEquation {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
int x = i+1;
map.put(arr[i], x);
}
for(int i = 0; i < arr.length; i++){
int j = i+1;
int res = map.get(map.get(j));
System.out.println(res);
}
}
}
<file_sep>/*
Hackerrank.com
Designer PDF Viewer
When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In a new kind of PDF viewer, the selection of each word is independent of the other words; this means that each rectangular selection area forms independently around each highlighted word. For example:
In this type of PDF viewer, the width of the rectangular selection area is equal to the number of letters in the word times the width of a letter, and the height is the maximum height of any letter in the word.
Consider a word consisting of lowercase English alphabetic letters, where each letter is 1mm wide. Given the height of each letter in millimeters (mm), find the total area that will be highlighted by blue rectangle in when the given word is selected in our new PDF viewer.
Input Format
The first line contains 26 space-separated integers describing the respective heights of each consecutive lowercase English letter (i.e., ha, hb, hc, ..., hy, hz).
The second line contains a single word, consisting of lowercase English alphabetic letters.
Constraints
1 <= h? <= 7, where ? is an English lowercase letter.
Word contains no more than 10 letters.
Output Format
Print a single integer denoting the area of highlighted rectangle when the given word is selected. The unit of measurement for this is square millimeters (mm^2), but you must only print the integer.
Sample Input
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
abc
Sample Output
9
Explanation
We are highlighting the word abc:
The tallest letter in abc is b, and hb = 3. The selection area for this word is 3 * 1mm * 3mm = 9mm^2.
Note: Recall that the width of each character is 1mm.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class PDFViewer {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 26;
int h[] = new int[n];
for(int h_i=0; h_i < n; h_i++){
h[h_i] = in.nextInt();
}
String word = in.next();
int max_ht = 0;
int ascii = 97;
for(int i = 0; i < word.length(); i++){
int index = (int)word.charAt(i) - ascii;
if(max_ht < h[index]){
max_ht = h[index];
}
}
int area = max_ht * word.length();
System.out.println(area);
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* LeetCode.com
*
* Given an array of size n, find the majority element. The majority element
* is the element that appears more than ⌊ n/2 ⌋ times.
*
* You may assume that the array is non-empty and the majority element always
* exist in the array.
*
*
*/
class MajorityElement {
public static void main(String[] args) {
int[] nums = new int[]{1,2,3,3,2,3,2,2,3,2,2};
System.out.println(majorityElement(nums));
}
public static int majorityElement(int[] nums){
int count = nums.length / 2;
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
int freq = 0;
if(map.containsKey(nums[i])){
freq = map.get(nums[i]);
map.remove(nums[i]);
}
freq++;
map.put(nums[i], freq);
if(freq > count){
return nums[i];
}
}
return -1;
}
}
<file_sep>/*
Hackerrank.com
Mini-Max Sum
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
Input Format
A single line of five space-separated integers.
Constraints
Each integer is in the inclusive range [1, 10^9].
Output Format
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)
Sample Input
1 2 3 4 5
Sample Output
10 14
Explanation
Our initial numbers are 1, 2, 3, 4, and 5. We can calculate the following sums using four of the five integers:
If we sum everything except 1, our sum is 14.
If we sum everything except 2, our sum is 13.
If we sum everything except 3, our sum is 12.
If we sum everything except 4, our sum is 11.
If we sum everything except 5, our sum is 10.
As you can see, the minimal sum is 10 and the maximal sum is 14. Thus, we print these minimal and maximal sums as two space-separated integers on a new line.
Hints: Beware of integer overflow! Use 64-bit Integer.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class MinMaxSum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long a = in.nextLong();
long b = in.nextLong();
long c = in.nextLong();
long d = in.nextLong();
long e = in.nextLong();
long[] arr = new long[]{a,b,c,d,e};
int max_index = 0;
int min_index = 0;
long max = a;
long min = a;
for(int i = 0; i < arr.length; i++){
if(max < arr[i]){
max = arr[i];
max_index = i;
}
if(min > arr[i]){
min = arr[i];
min_index = i;
}
}
max = 0;
min = 0;
for(int i = 0; i < arr.length; i++){
if(i != max_index){
min += arr[i];
}
if(i != min_index){
max += arr[i];
}
}
System.out.println(min + " " + max);
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Facebook Careercup
*
* Given an array of positive, unique, increasingly sorted numbers A, e.g. A =
* [1, 2, 3, 5, 6, 8, 9, 11, 12, 13]. Given a positive value K, e.g. K = 3.
* Output all pairs in A that differ exactly by K.
*
* e.g. 2, 5
* 3, 6
* 5, 8
* 6, 9
* 8, 11
* 9, 12
*
* What is the runtime for your code?
*
*
* Runtime of code below: O(N)
*
*/
class OutputPairs {
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 3, 5, 6, 8, 9, 11, 12, 13};
int k = 3;
outputPairs(arr, k);
}
public static void outputPairs(int[] arr, int k){
Set<Integer> st = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++){
st.add(arr[i]);
}
for(int i = 0; i < arr.length; i++){
if(st.contains(arr[i] + k)){
int sum = arr[i] + k;
System.out.println(arr[i] + ", " + sum);
}
}
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* LeetCode.com
*
* Write a function that takes an unsigned integer and returns the number of
* ’1' bits it has (also known as the Hamming weight).
*
* For example, the 32-bit integer ’11' has binary representation
* 00000000000000000000000000001011, so the function should return 3.
*
*
*/
class HammingWeight {
public static void main(String[] args) {
int num = 11;
System.out.println(hammingWeight(num));
}
public static int hammingWeight(int n){
String bits = Integer.toBinaryString(n);
int count = 0;
for(int i = 0; i < bits.length(); i++){
if(bits.charAt(i) == '1') count++;
}
return count;
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Facebook Careercup
*
* On a given array with N numbers, find subset of size M (exactly M elements)
* that equal to SUM
*
* This solution shows the permutation approach
*
*
* Time Complexity = O(n C m) where n = N and m = M
*
*
*/
class SubsetSumPermutation {
public static void main(String[] args) {
int[] arr = new int[]{1,4,2,5,9,7,6};
int N = 7;
int M = 3;
int SUM = 9;
//int [] res = findSubset(arr, N, M, SUM);
//System.out.println(Arrays.toString(res));
findSubset(arr, N, M, SUM);
}
public static void findSubset(int[] arr, int n, int m, int sum){
ArrayList<Integer> array = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++){
array.add(arr[i]);
}
ArrayList<Integer> temp = new ArrayList<Integer>();
findSubset(temp, array, m, sum);
}
public static void findSubset(ArrayList<Integer> temp, ArrayList<Integer> arr, int m, int sum){
int len = temp.size();
if(len == m && checkSum(temp, sum)){
for(int i = 0; i < len; i++){
System.out.print(temp.get(i) + " ");
}
System.out.println();
}else{
for(int i = 0; i < arr.size(); i++){
ArrayList<Integer> cur_arr = new ArrayList<Integer>();
ArrayList<Integer> cur_temp = new ArrayList<Integer>();
cur_arr.addAll(arr.subList(0, i));
cur_arr.addAll(arr.subList(i+1, arr.size()));
for(int j = 0; j < temp.size(); j++){
cur_temp.add(temp.get(j));
}
cur_temp.add(arr.get(i));
findSubset(cur_temp, cur_arr, m, sum);
}
}
}
public static boolean checkSum(ArrayList<Integer> temp, int sum){
int cur_sum = 0;
for(int i = 0; i < temp.size(); i++){
cur_sum += temp.get(i);
}
return cur_sum == sum;
}
}
<file_sep>import java.io.*;
import java.util.*;
/*
* Print the nodes of a tree level by level - Level Order Traversal
*
*/
class LevelOrderTraversal {
public static void main(String[] args) {
Node root = new Node();
//Assume buildTree builds a random tree and returns the root of the tree
root = buildTree(root);
Levelorder(root);
}
public static void LevelOrder(Node root){
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while(!q.isEmpty()){
Node cur = q.poll();
System.out.print(cur.data + " “);
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
}
}
<file_sep>
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
The Hurdle Race
Dan is playing a video game in which his character competes in a hurdle race by jumping over n hurdles with heights h0, h1, ..., hn-1. He can initially jump a maximum height of k units, but he has an unlimited supply of magic beverages that help him jump higher! Each time Dan drinks a magic beverage, the maximum height he can jump during the race increases by 1 unit.
Given n, k, and the heights of all the hurdles, find and print the minimum number of magic beverages Dan must drink to complete the race.
Input Format
The first line contains two space-separated integers describing the respective values of n (the number of hurdles) and k (the maximum height he can jump without consuming any beverages).
The second line contains n space-separated integers describing the respective values of h0, h1, ..., hn-1.
Constraints
1. 1 <= n, k <= 100
2. 1 <= hi <= 100
Output Format
Print an integer denoting the minimum number of magic beverages Dan must drink to complete the hurdle race.
Sample Input 0
5 4
1 6 3 5 2
Sample Output 0
2
Explanation 0
Dan's character can jump a maximum of k=4 units, but the tallest hurdle has a height of h1 = 6.
To be able to jump all the hurdles, Dan must drink 6 - 4 = 2 magic beverages.
Sample Input 1
5 7
2 5 4 5 2
Sample Output 1
0
Explanation 1
Dan's character can jump a maximum of k = 7 units, which is enough to cross all the hurdles:
image
Because he can already jump all the hurdles, Dan needs to drink 0 magic beverages.
*/
public class HurdleRace {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] height = new int[n];
for(int height_i=0; height_i < n; height_i++){
height[height_i] = in.nextInt();
}
// your code goes here
int drinks = 0;
int ht = k;
for(int i = 0; i < n ; i++){
if(ht < height[i]){
drinks += (height[i] - ht);
ht = height[i];
}
}
System.out.println(drinks);
}
}
<file_sep>
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Electronics Shop
Monica wants to buy exactly one keyboard and one USB drive from her favorite electronics store. The store sells n different brands of keyboards and m different brands of USB drives. Monica has exactly s dollars to spend, and she wants to spend as much of it as possible (i.e., the total cost of her purchase must be maximal).
Given the price lists for the store's keyboards and USB drives, find and print the amount money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
Note: She will never buy more than one keyboard and one USB drive even if she has the leftover money to do so.
Input Format
The first line contains three space-separated integers describing the respective values of s (the amount of money Monica has), n (the number of keyboard brands) and m (the number of USB drive brands).
The second line contains n space-separated integers denoting the prices of each keyboard brand.
The third line contains m space-separated integers denoting the prices of each USB drive brand.
Constraints
1. 1 <= n, m <= 1000
2. 1 <= s <= 10^6
The price of each item is in the inclusive range [1, 10^6].
Output Format
Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
Sample Input 0
10 2 3
3 1
5 2 8
Sample Output 0
9
Explanation 0
She can buy the 2nd keyboard and the 3rd USB drive for a total cost of 8 + 1 = 9.
Sample Input 1
5 1 1
4
5
Sample Output 1
-1
Explanation 1
There is no way to buy one keyboard and one USB drive because 4 + 5 > 5, so we print -1.
*/
public class ElectronicsShop {
static int getMoneySpent(Integer[] keyboards, int[] drives, int s){
// Complete this function
/*
Time Complexity: O(n+m (log (n+m))) //We sort in n+m (log (n+m)) then iterate in n+m
Space Complexity: O(1) //We consider the arrays as given
*/
//Sort takes O(n log n) & O(m log m)
Arrays.sort(keyboards, Collections.reverseOrder()); //sort in descending order
Arrays.sort(drives); // sort in ascending order
int max = -1;
for(int i = 0, j = 0; i < keyboards.length; i++){
//for(; j < drives.length; j++){
while(j < drives.length){
if(keyboards[i] + drives[j] > s){
break;
}
if(keyboards[i] + drives[j] > max){
max = keyboards[i] + drives[j];
}
j++;
}
}
return max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int n = in.nextInt();
int m = in.nextInt();
Integer[] keyboards = new Integer[n];
for(int keyboards_i=0; keyboards_i < n; keyboards_i++){
keyboards[keyboards_i] = in.nextInt();
}
int[] drives = new int[m];
for(int drives_i=0; drives_i < m; drives_i++){
drives[drives_i] = in.nextInt();
}
// The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
int moneySpent = getMoneySpent(keyboards, drives, s);
System.out.println(moneySpent);
}
}
<file_sep>
import java.io.*;
import java.util.*;
/*
Hacker Rank
Beautiful Days at the Movies
Lily likes to play games with integers and their reversals. For some integer x, we define reversed(x) to be the reversal of all digits in x. For example, reversed(123) = 321, reversed(21) = 12, and reversed(120) = 21.
Logan wants to go to the movies with Lily on some day x satisfying i <= x <= j, but he knows she only goes to the movies on days she considers to be beautiful. Lily considers a day to be beautiful if the absolute value of the difference between x and reversed(x) is evenly divisible by k.
Given i, j, and k, count and print the number of beautiful days when Logan and Lily can go to the movies.
Input Format
A single line of three space-separated integers describing the respective values of i, j, and k.
Constraints
1. 1 <= i <= j <= 2 x 10^6
2. 1 <= k <= 2 x 10^9
Output Format
Print the number of beautiful days in the inclusive range between i and j.
Sample Input
20 23 6
Sample Output
2
Explanation
Logan wants to go to the movies on days 20, 21, 22, and 23. We perform the following calculations to determine which days are beautiful:
Day 20 is beautiful because the following evaluates to a whole number: | 20 - 02 | / 6 = 3
Day 21 is not beautiful because the following doesn't evaluate to a whole number: | 21 - 12 | / 6 = 1.5
Day 22 is beautiful because the following evaluates to a whole number: | 22 - 22 | / 6 = 0
Day 23 is not beautiful because the following doesn't evaluate to a whole number: | 23 - 32 | / 6 = 1.5
Only two days, 20 and 22 , in this interval are beautiful. Thus, we print 2 as our answer.
*/
public class BeautifulDaysMovies {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
int k = sc.nextInt();
int count = 0;
for(int m = i; m < j; m++){
String str = Integer.toString(m);
String num_str = new StringBuilder(str).reverse().toString();
int num = Integer.parseInt(num_str);
int diff = Math.abs(m - num);
if(diff % k == 0){
count++;
}
}
System.out.println(count);
}
}<file_sep>
import java.io.*;
import java.util.*;
/*
Hacker Rank
Non-Divisible Subset
Given a set, S, of n distinct integers, print the size of a maximal subset, S', of S where the sum of any 2 numbers in S' is not evenly divisible by k.
Input Format
The first line contains 2 space-separated integers, n and k, respectively.
The second line contains n space-separated integers (we'll refer to the ith value as ai) describing the unique values of the set.
Constraints
1. 1 <= n <= 10^5
2. 1 <= k <= 100
3. 1 <= ai <= 10^9
4. All of the given numbers are distinct.
Output Format
Print the size of the largest possible subset (S').
Sample Input
4 3
1 7 2 4
Sample Output
3
Explanation
The largest possible subset of integers is S' = {1,7,4}, because no two integers will have a sum that is evenly divisible by k=3:
- 1 + 7 = 8, and 8 is not evenly divisible by 3.
- 1 + 4 = 5, and 5 is not evenly divisible by 3.
- 7 + 4 = 11, and 11 is not evenly divisible by 3.
The number 2 cannot be included in our subset because it will produce an integer that is evenly divisible by when summed with any of the other integers in our set:
1 + 2 = 3, and 3/3 = 1 (remainder = 0).
4 + 2 = 6, and 6/3 = 2 (remainder = 0).
7 + 2 = 9, and 9/3 = 3 (remainder = 0).
Thus, we print the length of S' on a new line, which is 3.
*/
public class NonDivisibleSubset {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
//Store elements in array
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = in.nextInt();
}
Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i < k; i++){
map.put(i, new ArrayList<Integer>());
}
//Store remainder, r(key) and list of indices (value) whose corresponding elements give r whem % k
for(int i = 0; i < n; i++){
int rem = arr[i] % k;
ArrayList<Integer> lst = map.get(rem);
lst.add(i);
map.put(rem, lst);
}
//Store the count of numbers that give remanider r when % with k
int[] count = new int[k];
for (Map.Entry<Integer, ArrayList<Integer>> entry : map.entrySet()){
int key = entry.getKey();
ArrayList<Integer> value = entry.getValue();
count[key] = value.size();
}
int length = 0;
if(count[0] > 0){
length++;
}
for(int i = 1; i < k; i++){
int j = k-i;
if(i > j){
break;
}
if(i == j){
length+=1;
}else if(count[i] > count[j]){
length += count[i];
}else{
length += count[j];
}
}
System.out.println(length);
}
}<file_sep>
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Cats and a Mouse
Two cats named A and B are standing at integral points on the x-axis. Cat A is standing at point x and cat B is standing at point y. Both cats run at the same speed, and they want to catch a mouse named C that's hiding at integral point z on the x-axis. Can you determine who will catch the mouse?
You are given q queries in the form of x, y, and z. For each query, print the appropriate answer on a new line:
If cat A catches the mouse first, print Cat A.
If cat B catches the mouse first, print Cat B.
If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes.
Input Format
The first line contains a single integer, q, denoting the number of queries.
Each of the q subsequent lines contains three space-separated integers describing the respective values of x (cat A's location), y (cat B's location), and (mouse C's location).
Constraints
1. 1 <= q <= 100
2. 1 <= x, y, z<= 100
Output Format
On a new line for each query, print Cat A if cat catches the mouse first, Cat B if cat catches the mouse first, or Mouse C if the mouse escapes.
Sample Input 0
3
1 2 3
1 3 2
2 1 3
Sample Output 0
Cat B
Mouse C
Cat A
Explanation 0
Query 0: The positions of the cats and mouse are shown below.
Cat B will catch the mouse first, so we print Cat B on a new line.
Query 1: In this query, cats A and B reach mouse C at the exact same time.
Because the mouse escapes, we print Mouse C on a new line.
*/
public class CatsAndMouse {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for(int a0 = 0; a0 < q; a0++){
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
int diff1 = (int)Math.abs(z - y);
int diff2 = (int)Math.abs(z - x);
if(diff1 > diff2){
System.out.println("Cat A");
}else if(diff1 < diff2){
System.out.println("Cat B");
}else{
System.out.println("Mouse C");
}
}
}
}
<file_sep>
/*
Hackerrank.com
CamelCase
Alice wrote a sequence of words in CamelCase as a string of letters, s, having the following properties:
It is a concatenation of one or more words consisting of English letters.
All letters in the first word are lowercase.
For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase.
Given s, print the number of words in s on a new line.
Input Format
A single line containing string s.
Constraints
Output Format
Print the number of words in string s.
Sample Input
saveChangesInTheEditor
Sample Output
5
Explanation
String contains five words:
save
Changes
In
The
Editor
Thus, we print 5 on a new line.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class CamelCase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
String word = new String();
int count = 0;
for(int i = 0; i < s.length(); i++){
if(Character.isUpperCase(s.charAt(i))){
//System.out.println(word);
word = new String();
count++;
}
word = word + "" + s.charAt(i);
}
count++;
System.out.println(count);
}
}<file_sep>
import java.io.*;
import java.util.*;
/*
Given a 6x6 2D Array, A:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:
a b c
d
e f g
There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values.
Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Input Format
There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of -9 to 9.
Constraints
1. -9 <= A[i][j] <= 9
2. 0 <= i, j <= 5
Output Format
Print the largest (maximum) hourglass sum found in A.
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
Explanation
contains the following hourglasses:
1 1 1 1 1 0 1 0 0 0 0 0
1 0 0 0
1 1 1 1 1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0
1 1 0 0
0 0 2 0 2 4 2 4 4 4 4 0
1 1 1 1 1 0 1 0 0 0 0 0
0 2 4 4
0 0 0 0 0 2 0 2 0 2 0 0
0 0 2 0 2 4 2 4 4 4 4 0
0 0 2 0
0 0 1 0 1 2 1 2 4 2 4 0
The hourglass with the maximum sum (19) is:
2 4 4
2
1 2 4
*/
public class TwoDArray {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int[][] matrix = new int[6][6];
int rows = 6;
int cols = 6;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
matrix[i][j] = sc.nextInt();
}
}
int maxsum = -9 * 7;
int sum = 0;
for(int i = 0; i < rows-2; i++){
for(int j = 0; j < cols-2; j++){
sum += matrix[i][j] + matrix[i][j+1] + matrix[i][j+2];
sum += matrix[i+1][j+1];
sum += matrix[i+2][j] + matrix[i+2][j+1] + matrix[i+2][j+2];
if(sum > maxsum){
maxsum = sum;
}
sum = 0;
}
}
System.out.println(maxsum);
}
}<file_sep>import java.io.*;
import java.util.*;
/*
* Google Careercup
*
* Rearrange characters in a string so that no character repeats twice.
*
* Input: aaabc
* Output: abaca
*
* Input: aa
* Output: No valid output
*
* Input: aaaabc
* Output: No valid output
*
*/
class Rearrange {
public static void main(String[] args) {
String str = new String("aaabc");
String str2 = new String("aa");
String str3 = new String("aaaabc");
System.out.println(rearrange(str));
System.out.println(rearrange(str2));
System.out.println(rearrange(str3));
}
public static String rearrange(String str){
char[] arr = str.toCharArray();
int len = str.length();
int left = 1;
char prev = arr[0];
int prior = -1;
int count = 0;
while(left < len){
if(arr[left] != prev){
if(prior != -1) {
char temp = arr[prior];
arr[prior] = arr[left];
arr[left] = temp;
count--;
prior+=2;
if (count == 0) {
prior = -1;
}
}
prev = arr[left];
}else{
prior = (prior == -1) ? left : prior;
count++;
}
left++;
}
if(count != 0){
return "No valid output";
}
return new String(arr);
}
}
<file_sep>
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Sock Merchant
John's clothing store has a pile of n loose socks where each sock i is labeled with an integer, ci, denoting its color. He wants to sell as many socks as possible, but his customers will only buy them in matching pairs. Two socks, i and j, are a single matching pair if c_i = c_j.
Given n and the color of each sock, how many pairs of socks can John sell?
Input Format
The first line contains an integer, n, denoting the number of socks.
The second line contains n space-separated integers describing the respective values of c_0, c_1, c_2, ..., c_n-1.
Constraints
1. 1 <= n <= 100
2. 1 <= c_i <= 100
Output Format
Print the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
*/
public class SockMerchant {
static int sockMerchant(int n, int[] ar) {
// Complete this function
int[] freq = new int[101];
for(int i = 0; i < freq.length; i++){
freq[i] = 0;
}
for(int i = 0; i < ar.length; i++){
freq[ar[i]]++;
}
int pairs = 0;
for(int i = 0; i < freq.length; i++){
pairs += (freq[i] / 2);
}
return pairs;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int ar_i = 0; ar_i < n; ar_i++){
ar[ar_i] = in.nextInt();
}
int result = sockMerchant(n, ar);
System.out.println(result);
}
}
<file_sep>
/*
Hackerrank.com
Mars Exploration
Sami's spaceship crashed on Mars! She sends n sequential SOS messages to Earth for help.
Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, S, determine how many letters of Sami's SOS have been changed by radiation.
Input Format
There is one line of input: a single string, S.
Note: As the original message is just SOS repeated n times, S's length will be a multiple of 3.
Constraints
S will contain only uppercase English letters.
Output Format
Print the number of letters in Sami's message that were altered by cosmic radiation.
Sample Input 0
SOSSPSSQSSOR
Sample Output 0
3
Sample Input 1
SOSSOT
Sample Output 1
1
Explanation
Sample 0
S = SOSSPSSQSSOR, and signal length |S| = 12. Sami sent 4 SOS messages (i.e.: 12/3 = 4).
Expected signal: SOSSOSSOSSOS
Recieved signal: SOSSPSSQSSOR
We print the number of changed letters, which is 3.
Sample 1
= SOSSOT, and signal length |S| = 6. Sami sent 2 SOS messages (i.e.: 6/3 = 2).
Expected Signal: SOSSOS
Received Signal: SOSSOT
We print the number of changed letters, which is 1.
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class MarsExploration {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String S = in.next();
String message = "SOS";
int count = 0;
for(int i = 0; i < S.length()-2; i++){
if(S.charAt(i) != message.charAt(0)){
count++;
}
if(S.charAt(i+1) != message.charAt(1)){
count++;
}
if(S.charAt(i+2) != message.charAt(2)){
count++;
}
i+=2;
}
System.out.println(count);
}
}<file_sep>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
/*
Hacker Rank
Breaking the Records
Maria plays n games of college basketball in a season. Because she wants to go pro, she tracks her points scored per game sequentially in an array defined as score = [s0, s1, s2, ..., sn-1]. After each game i, she checks to see if score si breaks her record for most or least points scored so far during that season.
Given Maria's array of scores for a season of n games, find and print the number of times she breaks her record for most and least points scored during the season.
Note: Assume her records for most and least points at the start of the season are the number of points scored during the first game of the season.
Input Format
The first line contains an integer denoting n(the number of games).
The second line contains n space-separated integers describing the respective values of s0, s1, s2, ..., sn-1.
Constraints
1. 1 <= n <= 100
2. 0 <= si <= 10^8
Output Format
Print two space-seperated integers describing the respective numbers of times her best (highest) score increased and her worst (lowest) score decreased.
Sample Input 0
9
10 5 20 20 4 5 2 25 1
Sample Output 0
2 4
Explanation 0
Depicts the number of times Maria broke her best and worst records throughout the season:
She broke her best record twice (after games 2 and 7) and her worst record four times (after games 1, 4, 6, and 8), so we print 2 4 as our answer. Note that she did not break her record for best score during game 3, as her score during that game was not strictly greater than her best record at the time.
Sample Input 1
10
3 4 21 36 10 28 35 5 24 42
Sample Output 1
4 0
Explanation 1
Depicts the number of times Maria broke her best and worst records throughout the season:
She broke her best record four times (after games 1, 2, 3, and 9) and her worst record zero times (no score during the season was lower than the one she earned during her first game), so we print 4 0 as our answer.
*/
public class BreakRecords {
static int[] getRecord(int[] s){
// Complete this function
int min = s[0];
int max = s[0];
int best = 0;
int worst = 0;
for(int i = 1; i < s.length; i++){
if(min > s[i]){
min = s[i];
worst++;
}else if(max < s[i]){
max = s[i];
best++;
}
}
int[] res = new int[2];
res[0] = best;
res[1] = worst;
return res;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] s = new int[n];
for(int s_i=0; s_i < n; s_i++){
s[s_i] = in.nextInt();
}
int[] result = getRecord(s);
String separator = "", delimiter = " ";
for (Integer val : result) {
System.out.print(separator + val);
separator = delimiter;
}
System.out.println("");
}
}
| 74b5e34d5fde7b43c9f747d9bffb304cf691ac02 | [
"Java"
] | 33 | Java | girish92/Coding-Questions | 775c85d6cf0b664847e78f8f3a475bba3b853e5f | b77d013677442511b83793c19436fd6596498f88 |
refs/heads/main | <repo_name>akhilbiju/ShopTrade<file_sep>/src/components/products/listcontrol/ListHeader.js
import { useRef } from 'react';
import './ListHeader.scss';
function ListHeader({ filterChange, count, filterList }) {
const filterRef = useRef();
const allSelect = filterList.join('') === 'all';
/**
* Send the latest filter data to parent component
* @param {*} event - Filter change event
*/
const onFilterChange = (event) => {
const selectedOption = event.target.dataset.filter;
const options = [...filterRef.current.children];
for (const option of options) {
if (selectedOption === 'all') {
if (option.dataset.filter !== 'all') {
option.classList.remove('active');
} else {
option.classList.add('active');
}
} else if (selectedOption === option.dataset.filter) {
if (option.classList.contains('active')) {
option.classList.remove('active');
} else {
option.classList.add('active');
}
} else if (option.dataset.filter === 'all') {
option.classList.remove('active');
}
}
const opt = options.filter((option) => option.classList.contains('active'));
const mapFilterData = opt.map((data) => data.dataset.filter);
filterChange(mapFilterData);
};
return (
<div className="control-header">
<h2>{(allSelect ? 'All Products' : 'Others') + ` (${count})`}</h2>
<div className="filter">
<span>FILTERS:</span>
<div onClick={onFilterChange} ref={filterRef} className="filterlist">
<div data-filter="all" className="active">
All Products
</div>
<div data-filter="T-shirt">Tee Shirt</div>
<div data-filter="Denim">Denim</div>
<div data-filter="Sweatshirts">Sweatshirts</div>
<div data-filter="polo">Polo Tee Shirt</div>
<div data-filter="shirt">Shirt</div>
</div>
</div>
<div className="sortlist"></div>
</div>
);
}
export default ListHeader;
<file_sep>/src/components/header/Header.js
import React, { useState } from 'react';
import { NavLink } from 'react-router-dom';
import './Header.scss';
import logo from '../../images/logo.png';
import search from '../../images/search.png';
import user from '../../images/user.png';
import cart from '../../images/cart.png';
import SideNav from '../sidenav/SideNav';
import { NAV_LINKS } from '../../constants/App';
import { StoreContext } from '../../contexts/StoreContext';
function Header() {
const { storeState } = React.useContext(StoreContext);
const [menuState, setMenuState] = useState(false);
const inputStyle = {
background: 'url(' + search + ') 95% no-repeat',
backgroundSize: '15px',
};
const handleMenuEvent = (value) => {
setMenuState(value);
};
return (
<>
<header>
<div className="logo">
<div onClick={() => setMenuState(true)} className="hamburger">
{[1, 2, 3].map((data) => (
<div key={data}></div>
))}
</div>
<NavLink to="/">
<img src={logo} alt="logo"></img>
</NavLink>
</div>
<div className="navlinks">
{NAV_LINKS.map((route) => (
<NavLink
to={route.path}
activeClassName="active"
key={route.path}
className="navItem"
>
{route.name}
</NavLink>
))}
</div>
<div className="controls">
<input className="searchbox-large" style={inputStyle}></input>
<img className="searchIcon" src={search} alt="search"></img>
<img src={user} alt="user"></img>
<NavLink to="/cart">
<img src={cart} alt="cart"></img>
{storeState.cartItems.totalItems > 0 && (
<span className="cartcount">
{storeState.cartItems.totalItems}
</span>
)}
</NavLink>
</div>
</header>
<SideNav opened={menuState} menuevent={handleMenuEvent} />
</>
);
}
export default Header;
<file_sep>/src/components/products/lazimage/LazyImage.js
import { useState } from 'react';
import LazyLoad from 'react-lazy-load';
import './LazyImage.scss';
function LazyImage({ src, alt, width, height }) {
const [loading, setLoading] = useState(true);
const imgStyle = {
width: `${+width}px`,
height: `${+height}px`,
objectFit: 'cover',
};
return (
<LazyLoad
width={+width}
height={+height}
debounce={false}
offsetVertical={100}
>
<img
className={loading ? ' loading' : ''}
style={imgStyle}
src={src}
alt={alt}
onLoad={() => setLoading(false)}
/>
</LazyLoad>
);
}
export default LazyImage;
<file_sep>/src/components/App.js
import { Route, Switch, Redirect } from 'react-router-dom';
import './App.scss';
import Header from './header/Header';
import ProductList from './products/productlist/ProductList';
import Cart from '../components/cart/Cart';
import { StoreProvider } from '../contexts/StoreContext';
function App() {
return (
<StoreProvider>
<Header />
<Switch>
<Route exact path="/" render={() => <Redirect to="/shop" />} />
<Route path="/shop" component={ProductList} />
<Route path="/cart" component={Cart} />
<Route render={() => <Redirect to="/shop" />} />
</Switch>
</StoreProvider>
);
}
export default App;
<file_sep>/src/constants/Actions.js
export const ADD_ITEM = 'ADD_CART_ITEM';
export const REMOVE_ITEM = 'REMOVE_CART_ITEM';
<file_sep>/src/contexts/StoreContext.js
import React, { useReducer, createContext, useEffect } from 'react';
import cartReducer from '../reducers/CartReducer';
import { ADD_ITEM, REMOVE_ITEM } from '../constants/Actions';
const StoreContext = createContext();
const localStorageKey = 'storeData';
const initialState = {
cartItems: { items: [], totalAmount: 0, totalItems: 0 },
};
const StoreProvider = (props) => {
const [storeState, dispatch] = useReducer(cartReducer, initialState, () => {
const persistData = localStorage.getItem(localStorageKey);
return persistData ? JSON.parse(persistData) : initialState;
});
/**
* Store data in localstorage to persist cart data on refresh
*/
useEffect(() => {
localStorage.setItem(localStorageKey, JSON.stringify(storeState));
}, [storeState]);
const actions = {
itemAdd: (item) => {
dispatch({ type: ADD_ITEM, payload: item });
},
itemRemove: (item) => {
dispatch({ type: REMOVE_ITEM, payload: item });
},
};
return (
<StoreContext.Provider
value={{
storeState: storeState,
storeActions: actions,
}}
>
{props.children}
</StoreContext.Provider>
);
};
export { StoreProvider, StoreContext };
<file_sep>/src/components/products/productlist/ProductList.js
import React, { useState } from 'react';
import { productlist } from '../../../constants/ProductList';
import { StoreContext } from '../../../contexts/StoreContext';
import LazyImage from '../lazimage/LazyImage';
import { SIZE_LABEL } from '../../../constants/App';
import './ProductList.scss';
import { getDiscount, getSize } from '../../utils/helper';
import ListHeader from '../listcontrol/ListHeader';
function ProductList() {
const { storeActions } = React.useContext(StoreContext);
const [selectionState, setSelectionState] = useState({});
const [productData, setProductData] = useState(productlist);
const [filterList, setFilterList] = useState(['all']);
/**
* Apply filter values to the list
* @param {*} filter - Filter values
*/
const filterChange = (filter) => {
setFilterList(filter);
if (filter instanceof Array && filter[0] === 'all') {
setProductData(productlist);
} else {
setProductData(
productlist.filter((product) => filter.includes(product.tag)),
);
}
};
/**
* Add item to the cart
* @param {*} item The product item
*/
const addToCart = (item) => {
storeActions.itemAdd({
data: selectionState[item.id].item,
optionData: selectionState[item.id].variant,
});
removeSelection(item);
};
/**
* Add variant selection to the state
* @param {*} item - The item to be selected
* @param {*} variant - Variant of the item
*/
const addSelection = (item, variant) => {
const newState = { ...selectionState, [item.id]: { variant, item } };
setSelectionState(newState);
};
/**
* Remove item selection from state
* @param {*} item - Item to be removed
*/
const removeSelection = (item) => {
if (selectionState[item.id]) {
const newState = { ...selectionState };
delete newState[item.id];
setSelectionState(newState);
}
};
return (
<>
<ListHeader
filterChange={filterChange}
count={productData.length}
filterList={filterList}
/>
<div className="productlist">
{productData.map((item) => {
return (
<div
onMouseLeave={() => removeSelection(item)}
key={filterList.join('') + item.id}
className="card"
>
<LazyImage
src={item.image_src[0]}
width="300"
height="400"
alt="preview"
/>
<div className="footer">
<div className="name">{item.vendor}</div>
<div className="description">{item.name}</div>
<div className="price">
<div className="variant">
<div className={!selectionState[item.id] ? '' : 'hidden'}>
<span className="variant-label">Select Size</span>
<div className="variant-list">
{item.options.map((variant) => {
return (
<span
onClick={() => addSelection(item, variant)}
key={variant.id}
>
{getSize(variant)}
</span>
);
})}
</div>
</div>
<button
onClick={() => addToCart(item)}
className={selectionState[item.id] ? '' : 'hidden'}
>
ADD TO CART
</button>
<span className="sizelist">{SIZE_LABEL}</span>
</div>
<span className="listprice">{item.price}</span>
<span className="maxprice">{item.compare_at_price}</span>
<span className="discount">{getDiscount(item)}</span>
</div>
</div>
</div>
);
})}
{!productData.length && (
<p style={{ textAlign: 'center' }}>Nothing to show</p>
)}
</div>
</>
);
}
export default ProductList;
<file_sep>/src/constants/App.js
export const NAV_LINKS = [
{
name: 'Shop',
path: '/shop',
},
{
name: 'About Us',
path: '/about',
},
{
name: 'Our Stores',
path: '/store',
},
{
name: 'Contact Us',
path: '/contact',
},
];
export const PRODUCT_SIZES = {
xs: 38,
small: 39,
medium: 40,
large: 44,
xl: 46,
US_8: 38,
US_9: 39,
US_10: 40,
US_11: 44,
US_13: 46,
};
export const SIZE_LABEL = 'Sizes: XS, S, M, L, XL, XXL';
<file_sep>/src/components/utils/helper.js
import { PRODUCT_SIZES } from '../../constants/App';
/**
* Calculate discount applied
* @param {*} item - The product item object
*/
export const getDiscount = (item) => {
const price = item.price;
const max_price = item.compare_at_price;
const percent = ((max_price - price) / max_price) * 100;
return `(${Math.floor(percent)}% OFF)`;
};
/**
* Get the size in numbers
* @param {*} variant - The variant of the selected item
*/
export const getSize = (variant) => {
if (variant.value.startsWith('US')) {
return PRODUCT_SIZES['US_' + variant.value.split(' ')[1]];
}
return PRODUCT_SIZES[variant.value] || variant.value;
};
| 8006867f170a3fabcc27105c82924f309d1243d3 | [
"JavaScript"
] | 9 | JavaScript | akhilbiju/ShopTrade | b3e78b06e1c9e3bd8788ebf6d71d93a4a851eed7 | 3ff89eebc7ac18495a809c52dcba5d450fb47475 |
refs/heads/master | <repo_name>imzfz/JavaWeb<file_sep>/JavaWebE2/src/cn/imzfz/exp2/Check.java
package cn.imzfz.exp2;
import java.io.Serializable;
import java.sql.ResultSet;
import static cn.imzfz.exp2.SqlConnect.*;
/**
* Created by zfz on 2017/10/26.
*/
public class Check implements Serializable{
private String uid;
private String user;
private String pass;
private final static String TABLE = "Users";
private final static String UNAME = "user_name";
private final static String UPASS = "<PASSWORD>";
public Check(){
}
public void setUser(String user) {
this.user = user;
}
public void setPass(String pass) {
this.pass = pass;
}
public boolean isValid(){
try {
SqlConnect connect = new SqlConnect();
connect.setStatement(connect.getConnection().createStatement());
ResultSet res = connect.getStatement().
executeQuery("SELECT * from " + TABLE + " WHERE user_name = '" + user + "'");
while(res.next()){
if(res.getString(2).equals(user) && res.getString(3).equals(pass)){
return true;
}
}
System.out.println("check");
res.close();
connect.getConnection().close();
}
catch (Exception e){
e.printStackTrace();
}
return false;
}
public String getUser() {
return user;
}
public String getPass() {
return pass;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/bean/Select.java
package cn.imzfz.model.bean;
/**
* Created by zfz on 2017/11/1.
*/
public class Select {
private String id;
private String choiceA;
private String choiceB;
private String choiceC;
private String choiceD;
private String answer;
public Select(String choiceA, String choiceB, String choiceC, String choiceD) {
this.choiceA = choiceA;
this.choiceB = choiceB;
this.choiceC = choiceC;
this.choiceD = choiceD;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getChoiceA() {
return choiceA;
}
public void setChoiceA(String choiceA) {
this.choiceA = choiceA;
}
public String getChoiceB() {
return choiceB;
}
public void setChoiceB(String choiceB) {
this.choiceB = choiceB;
}
public String getChoiceC() {
return choiceC;
}
public void setChoiceC(String choiceC) {
this.choiceC = choiceC;
}
public String getChoiceD() {
return choiceD;
}
public void setChoiceD(String choiceD) {
this.choiceD = choiceD;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/servlet/QuestionServlet.java
package cn.imzfz.model.servlet;
import cn.imzfz.model.dao.ChoiceDAO;
import cn.imzfz.model.dao.QuestionDAO;
import cn.imzfz.model.impl.ChoiceList;
import cn.imzfz.model.impl.QuestionList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by zfz on 2017/11/15.
*/
public class QuestionServlet extends HttpServlet {
private QuestionDAO ql;
private ChoiceDAO choice;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ql = new QuestionList();
choice = new ChoiceList();
ql.initQuestion();
choice.initChoice();
System.out.println("Question servlet");
req.setAttribute("ql", ql.getQuestionMap());
req.setAttribute("totalNum", ql.getQuestionMap().size());
req.setAttribute("cho", choice.getList());
if(req.getRequestURI().equals("/question")) {
req.getRequestDispatcher("/question.jsp").forward(req, resp);
}
if(req.getRequestURI().equals("/editquestion")){
req.getRequestDispatcher("/editquestion.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/bean/User.java
package cn.imzfz.model.bean;
/**
* Created by zfz on 2017/11/24.
*/
public class User {
private String username = "";
private String pass = "";
private int auth = 0;
public User(String username, String pass) {
this.username = username;
this.pass = pass;
}
public String getUsername() {
return username;
}
public String getPass() {
return pass;
}
public int getAuth() {
return auth;
}
public void setAuth(int auth) {
this.auth = auth;
}
}
<file_sep>/JavaWebE1/src/cn/imzfz/faq/Check.java
package cn.imzfz.faq;
/**
* Created by zfz on 2017/10/16.
* 本类用于检查用户名密码是否合法
*/
public class Check {
private String user;
private String pass;
public Check(){
}
public void setUser(String user) {
this.user = user;
}
public void setPass(String pass) {
this.pass = pass;
}
public boolean isValid(){
if(user.equals("zhangfangzi") && pass.equals("<PASSWORD>")){
return true;
}
return false;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/dao/QuestionDAO.java
package cn.imzfz.model.dao;
import cn.imzfz.model.bean.Question;
import java.util.Map;
/**
* Created by zfz on 2017/11/16.
*/
public interface QuestionDAO {
void initQuestion();
boolean addQuestion(Question question) throws Exception;
boolean delQuestion(String id) throws Exception;
boolean updateQuestion(Question question) throws Exception;
Map<String, Question> getQuestionMap();
}
<file_sep>/JavaWebE2/src/cn/imzfz/exp2/TrueOrFalse.java
package cn.imzfz.exp2;
/**
* Created by zfz on 2017/11/1.
*/
public class TrueOrFalse {
private String id;
private final String choiceYes = "对";
private final String choiceNo = "错";
public TrueOrFalse(){
}
}
<file_sep>/JavaWebE2/src/cn/imzfz/exp2/Choice.java
package cn.imzfz.exp2;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static cn.imzfz.exp2.SqlConnect.*;
/**
* Created by zfz on 2017/10/30.
*/
public class Choice {
private Map<String, Object> list = new HashMap<>();
private final static String TABLE = "Choice";
public Choice() {
}
public void connect() {
try {
SqlConnect connect = new SqlConnect();
connect.setStatement(connect.getConnection().createStatement());
ResultSet res = connect.getStatement().
executeQuery("SELECT * FROM Choice ORDER BY qid ASC ");
while (res.next()) {
switch (res.getString(9)) {
case "tf":
list.put(res.getString(8), new TrueOrFalse());
break;
case "select":
list.put(res.getString(8), new Select(res.getString(2),
res.getString(3), res.getString(4), res.getString(5)));
break;
}
}
System.out.println("choice");
res.close();
connect.getConnection().close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*public void select(String id) {
try {
SqlConnect connect = new SqlConnect();
connect.setStatement(connect.getConnection().createStatement());
ResultSet res = connect.getStatement().executeQuery("SELECT choiceA, choiceB, choiceC, choiceD, qid FROM " + TABLE + " WHERE qid=" + id +" ORDER by qid ASC");
while (res.next()) {
System.out.println(res.getString(1) + "aaa");
list.put(res.getString(5),
new Select(res.getString(1),
res.getString(2),
res.getString(3),
res.getString(4)));
}
res.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void TorF(String id){
try {
SqlConnect connect = new SqlConnect();
connect.setStatement(connect.getConnection().createStatement());
ResultSet res = connect.getStatement().executeQuery("SELECT choiceYes, choiceNo, qid FROM " + TABLE + " WHERE qid=" + id + " ORDER by qid ASC");
while (res.next()) {
System.out.println(res.getString(3) + "bbb");
list.put(res.getString(3),
new TrueOrFalse());
}
res.close();
} catch (Exception e) {
e.printStackTrace();
}
}*/
public Map<String, Object> getList() {
return list;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/servlet/ResultServlet.java
package cn.imzfz.model.servlet;
import cn.imzfz.model.bean.Question;
import cn.imzfz.model.impl.ResultImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Created by zfz on 2017/11/28.
*/
public class ResultServlet extends HttpServlet {
int total = 0;
Map<String, String> submit = new HashMap<>();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
total = Integer.parseInt(req.getParameter("totalId"));
int score;
for(int i = 1; i <= total; i++){
String single[] = req.getParameterValues("single_" + i);
String tf[] = req.getParameterValues("tf_" + i);
if(single != null){
submit.put(i + "", single[0]);
}
if(tf != null){
submit.put(i + "", tf[0]);
}
}
ResultImpl result = new ResultImpl(submit);
result.initJudge();
score = result.judge();
req.getSession().setAttribute("score", score);
req.getRequestDispatcher("result.jsp").forward(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/");
}
public Map<String, String> getSubmit() {
return submit;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/dao/DBConnection.java
package cn.imzfz.model.dao;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Created by zfz on 2017/11/15.
*/
public class DBConnection {
private Connection connection;
private static final String URL = "jdbc:mysql://172.16.17.32:3306/zhangfangzi";
private static final String SQLUSER = "cas";
private static final String SQLPASS = "<PASSWORD>";
public DBConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e){
System.out.println("找不到数据库驱动");
e.printStackTrace();
}
}
public Connection connection(String host, String username, String password, String port, String tableName){
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + tableName, username, password);
}catch (Exception e){
System.out.println("连接失败");
e.printStackTrace();
}
return connection;
}
public Connection connection(){
try {
connection = DriverManager.getConnection(URL, SQLUSER, SQLPASS);
}catch (Exception e){
System.out.println("连接失败");
e.printStackTrace();
}
return connection;
}
public void close(){
try{
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/dao/ChoiceDAO.java
package cn.imzfz.model.dao;
import cn.imzfz.model.bean.Question;
import cn.imzfz.model.bean.Select;
import cn.imzfz.model.bean.TrueOrFalse;
import cn.imzfz.model.impl.ChoiceList;
import java.util.Map;
/**
* Created by zfz on 2017/11/16.
*/
public interface ChoiceDAO {
void initChoice();
Map<String, Object> getList();
boolean addChoice(Question question, Select select) throws Exception;
boolean addChoice(Question question, TrueOrFalse trueOrFalse) throws Exception;
boolean delChoice(String id) throws Exception;
boolean updateChoice(Question question, Select select) throws Exception;
boolean updateChoice(Question question, TrueOrFalse trueOrFalse) throws Exception;
}
<file_sep>/JavaWebE3/src/js/question.js
/**
* Created by zfz on 2017/11/16.
*/
var id;
//添加信息完整性检查
function checkValid() {
var title = document.getElementById("newTitle").value;
var score = document.getElementById("score").value;
var choiceA = document.getElementById("newA").value;
var choiceB = document.getElementById("newB").value;
var choiceC = document.getElementById("newC").value;
var choiceD = document.getElementById("newD").value;
var answer = document.getElementsByName("answer");
var type = document.getElementById("question_type");
if (title.match(/^[ ]*$/)) {
alert("标题不能为空");
return false;
}
else if (title.length > 255) {
alert("标题过长");
return false;
}
if (type.value == "select") {
if (choiceA.match(/^[ ]*$/) || choiceB.match(/^[ ]*$/) || choiceC.match(/^[ ]*$/) || choiceD.match(/^[ ]*$/)) {
alert("选项不能为空");
return false;
}
else if (choiceA.length > 255 || choiceB.length > 255 || choiceC.length > 255 || choiceD.length > 255) {
alert("选项过长");
return false;
}
}
if (score.match(/^[ ]*$/)) {
alert("分值不能为空");
return false;
}
else if (score.length > 4) {
alert("分值过大");
return false;
}
for (var i = 0; i < answer.length; i++) {
if (answer[i].checked) {
break;
}
if (i == answer.length - 1) {
alert("未选择正确答案");
return false;
}
}
return true;
}
//修改信息完整性检查
function checkValidUpdate() {
var title = document.getElementById("updateTitle").value;
var score = document.getElementById("updateScore").value;
var choiceA = document.getElementById("updateA").value;
var choiceB = document.getElementById("updateB").value;
var choiceC = document.getElementById("updateC").value;
var choiceD = document.getElementById("updateD").value;
var answer = document.getElementsByName("answer");
var type = document.getElementById("update_question_type");
if (title.match(/^[ ]*$/)) {
alert("标题不能为空");
return false;
}
else if (title.length > 255) {
alert("标题过长");
return false;
}
if (type.value == "select") {
if (choiceA.match(/^[ ]*$/) || choiceB.match(/^[ ]*$/) || choiceC.match(/^[ ]*$/) || choiceD.match(/^[ ]*$/)) {
alert("选项不能为空");
return false;
}
else if (choiceA.length > 255 || choiceB.length > 255 || choiceC.length > 255 || choiceD.length > 255) {
alert("选项过长");
return false;
}
}
if (score.match(/^[ ]*$/)) {
alert("分值不能为空");
return false;
}
else if (score.length > 4) {
alert("分值过大");
return false;
}
for (var i = 0; i < answer.length; i++) {
if (answer[i].checked) {
break;
}
if (i == answer.length - 1) {
alert("未选择正确答案");
return false;
}
}
return true;
}
//提交添加的信息
function sub() {
if (checkValid()) {
document.addForm.submit();
}
}
//提交修改的信息
function subUpdate() {
if (checkValidUpdate()) {
document.updateForm.submit();
}
}
//选项列表的修改与显示
function loadjs() {
document.getElementById("newId").value = document.getElementById("getId").value;
var selectArea = document.getElementById("addSelect");
var tfArea = document.getElementById("addTf");
var type = document.getElementById("question_type");
if (type.value == "tf") {
selectArea.style.display = "none";
tfArea.style.display = "block";
}
if (type.value == "select") {
selectArea.style.display = "block";
tfArea.style.display = "none";
}
}
//填充已有信息
function update() {
var whoIsSelected = document.getElementsByName("checkbox");
var selectArea = document.getElementById("updateSelect");
var tfArea = document.getElementById("updateTf");
// var type = document.getElementById("update_question_type");
var count = 0;
for(var i = 0; i < whoIsSelected.length; i++){
count++;
var type = document.getElementById("showType_" + (i + 1)).innerHTML;
if(whoIsSelected.item(i).checked){
document.getElementById("updateId").value = document.getElementById("showId_" + (i + 1)).innerHTML;
document.getElementById("updateTitle").value = document.getElementById("showTitle_" + (i + 1)).innerHTML;
document.getElementById("updateScore").value = document.getElementById("showScore_" + (i + 1)).innerHTML;
document.getElementById("update_question_type").options[1].selected = true;
if(type == "选择") {
document.getElementById("update_question_type").options[0].selected = true;
document.getElementById("updateA").value = document.getElementsByName("getChoice_" + (i + 1)).item(0).value;
document.getElementById("updateB").value = document.getElementsByName("getChoice_" + (i + 1)).item(1).value;
document.getElementById("updateC").value = document.getElementsByName("getChoice_" + (i + 1)).item(2).value;
document.getElementById("updateD").value = document.getElementsByName("getChoice_" + (i + 1)).item(3).value;
}
var ans = document.getElementById("showAnswer_" + (i + 1)).innerHTML;
document.getElementById("answer_" + ans).checked = true;
break;
}
}
if (type == "判断") {
selectArea.style.display = "none";
tfArea.style.display = "block";
}
if (type == "选择") {
selectArea.style.display = "block";
tfArea.style.display = "none";
}
}
function getChange_update() {
var selectArea = document.getElementById("updateSelect");
var tfArea = document.getElementById("updateTf");
var type = document.getElementById("update_question_type");
if (type.value == "tf") {
selectArea.style.display = "none";
tfArea.style.display = "block";
}
if (type.value == "select") {
selectArea.style.display = "block";
tfArea.style.display = "none";
}
}
//编辑和删除 验证
function beforeDelorUpdate() {
var whoIsSelected = document.getElementsByName("checkbox");
var delBtn = document.getElementById("delButton");
var updateBtn = document.getElementById("updateButton");
for(var i = 0; i < whoIsSelected.length; i++){
if(whoIsSelected.item(i).checked){
delBtn.disabled = false;
updateBtn.disabled = false;
break;
}
else{
delBtn.disabled = true;
updateBtn.disabled = true;
}
}
}
function doDelete() {
if(confirm("确定删除所选问题?")){
document.doDel.submit();
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/bean/Check.java
package cn.imzfz.model.bean;
/**
* Created by zfz on 2017/11/13.
*/
public class Check{
private String user;
private String pass;
public Check(String user, String pass){
this.user = user;
this.pass = pass;
}
public boolean isValid(){
if(user.equals("zfz") && pass.equals("123")){
return true;
}
return false;
}
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/dao/UserDao.java
package cn.imzfz.model.dao;
import cn.imzfz.model.bean.User;
/**
* Created by zfz on 2017/11/24.
*/
public interface UserDao {
boolean isValid(User user);
}
<file_sep>/JavaWebE3/src/cn/imzfz/model/bean/Question.java
package cn.imzfz.model.bean;
/**
* Created by zfz on 2017/11/15.
*/
public class Question {
private String id = "";
private String title = "";
private String score = "";
private String type = "";
private String answer = "";
public Question(String id, String title, String score, String answer, String type){
this.id = id;
this.title = title;
this.score = score;
this.type = type;
this.answer = answer;
}
public Question(String title, String score, String answer){
this.title = title;
this.score = score;
this.answer = answer;
}
public Question(String id, int score, String answer){
this.title = id;
this.score = score + "";
this.answer = answer;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getScore() {
return score;
}
public String getType() {
return type;
}
public String getAnswer() {
return answer;
}
public void setId(String id) {
this.id = id;
}
}
| a046e394808d9d538b6ab1aa6b1df5a534a0f927 | [
"JavaScript",
"Java"
] | 15 | Java | imzfz/JavaWeb | f1512627ec1dc796c143a8e8de7554614cceed94 | d6994cd2190688ed86fcfe6803e19bb73f453269 |
refs/heads/master | <file_sep>// DEPENDENCIES
require("dotenv").config();
const router = require("express").Router();
/* ----------------------- */
const controllers = require("../controllers/iconcontrollers");
// USER
router.get("/iconsearch", controllers.search);
module.exports = router;
<file_sep>require("dotenv").config();
const puppeteer = require("puppeteer");
const fs = require("fs");
const application = require("../services/youtubeservices");
module.exports = {
// USER LOGIN
main: async (req, res) => {
const { id, url, limit } = req.query;
// chromium setup for deploy
const browser = await puppeteer.launch({
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox"],
executablePath:
"/usr/src/app/node_modules/puppeteer/.local-chromium/linux-901912/chrome-linux/chrome",
});
// for local test
// const browser = await puppeteer.launch({
// headless: true,
// });
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto(url);
await page.evaluate((_) => {
window.scrollBy(1, window.innerHeight);
});
let listdata = [];
let downloaddata = [];
let downloaded = 0;
let videos = await page.$$("#items #dismissible");
// find get data from database
try {
console.log("main");
// const getdata = await application.dbdata(id);
const getdata = await application.dbdata(id);
listdata = getdata.rows;
} catch (err) {
console.log("no data");
listdata = [];
}
try {
for (i = 1; i <= videos.length; i++) {
let boolean = false;
const videoUrl = await page.$$eval(
`#items ytd-grid-video-renderer:nth-child(${i}) #dismissible #details #meta #video-title`,
(nodes) => nodes.map((n) => n.href)
);
if (listdata.length > 1) {
console.log("checking");
for (j = 0; j < listdata.length; j++) {
if (listdata[j].doc.url == videoUrl) {
console.log(j, listdata[j].doc.url);
boolean = true;
}
}
}
// console.log(i);
// download video and get data
if (boolean == false) {
const downloadFile = await application.download(
videoUrl.toString(),
id
);
downloaded += 1;
await downloaddata.push(downloadFile);
console.log("Downloaded files from : " + videoUrl.toString());
console.log("files downloaded " + downloaded);
}
// auto save downloaded file list every 10 videos
if (i % 10 == 0) {
const savelist = await application.savedata(downloaddata);
}
//checking videos qty
for (j = 0; j < 5; j++) {
if (i == videos.length - 1) {
console.log("checking length");
page.evaluate((_) => {
window.scrollBy(0, window.innerHeight);
});
await page.waitForTimeout(5000);
videos = await page.$$("#items #dismissible");
}
}
// Boolean(download == limit);
if (downloaded >= limit) {
const savelist = await application.savedata(downloaddata);
break;
}
}
} catch (error) {
console.log(error);
}
res.status(201).send({ message: `Downloaded files: ${downloaded}` });
},
data: async (req, res) => {
try {
const getdata = await application.getall();
if (getdata == undefined) {
res.status(401).send({ message: "data with that id is not found" });
} else {
res.status(201).send(getdata);
}
} catch (error) {
console.log(error);
}
},
search: async (req, res) => {
const keyword = req.query.keyword;
const limit = req.query.limit;
const skip = req.query.skip;
try {
const searchdata = await application.search(keyword, limit, skip);
res.status(201).send(searchdata);
} catch (err) {
console.log(err);
}
},
};
<file_sep>// defines router
const psdRouter = require("./psdroutes");
const ytRouter = require("./ytroutes");
const iconRouter = require("./iconroutes");
// export router for server.js
module.exports = {
psdRouter,
ytRouter,
iconRouter,
};
<file_sep>const application = require("../services/iconservices");
module.exports = {
// icon scout //
search: async (req, res) => {
const { query, product_type, asset, per_page, page, sort } = req.query;
const data = { query, product_type, asset, per_page, page, sort };
try {
const search = await application.searchicon(data);
console.log(search);
res.status(200).send({ data: search });
} catch (error) {
console.log(error);
}
},
};
<file_sep>// DEPENDENCIES
require("dotenv").config();
const router = require("express").Router();
/* ----------------------- */
const controllers = require("../controllers/psdcontrollers");
const middleware = require("../middlewares/psdmiddlewares");
const multer = require("multer");
// USER
router.post("/upload", middleware.single("file"), controllers.maincontroller);
router.get("/psdsearch", controllers.search);
router.get("/getall", controllers.getall);
module.exports = router;
<file_sep>FROM node:14
ENV NODE_ENV=development
WORKDIR /usr/src/app
COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]
RUN npm install
RUN apt-get update && \
apt-get -y install xvfb gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 \
libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 \
libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 \
libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 \
libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget && \
rm -rf /var/lib/apt/lists/*
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
<file_sep>require("dotenv").config();
const axios = require("axios").default;
// Set config defaults when creating the instance
const { CI, SK } = process.env;
// // Alter defaults after instance has been created
// instance.defaults.headers.common["ID"] = CI;
module.exports = {
searchicon: async (data) => {
// console.log(data);
try {
const searching = await axios.get("https://api.iconscout.com/v3/search", {
headers: { "content-type": "application/json", "Client-ID": CI },
params: {
query: data.query,
product_type: data.product_type,
asset: data.asset,
per_page: data.per_page,
page: data.page,
sort: data.sort,
},
});
const result = searching.data.response.items;
return result;
} catch (error) {
console.log(error);
}
},
};
<file_sep>// DEPENDENCIES
require("dotenv").config();
const router = require("express").Router();
/* ----------------------- */
const controllers = require("../controllers/ytcontrollers");
// USER
router.get("/", controllers.main);
router.get("/data", controllers.data);
router.get("/ytsearch", controllers.search);
module.exports = router;
| 86096e6a132543aedff4c88dc2953ed0ee010dbd | [
"JavaScript",
"Dockerfile"
] | 8 | JavaScript | yan099915/converter-app | 7928fcadaccb1618f1ea6403c292db9b75b08558 | 2fd38611910ba5ab96d79292553712b4c04db633 |
refs/heads/master | <file_sep><?php
function view($view, $data = [])
{
\App\View::show($view, $data);
}
function view_share($var, $value = null)
{
\App\View::setGlobals($var, $value);
}
function view_var($varname, $default = null)
{
\App\View::getGlobal($varname, $default);
}
function redirect_to($url)
{
if (!$url) {
exit('No URL provided for redirection');
}
header('location:'.
getenv('SITE_URL') . '/' .
trim($url, '/')
);
exit();
}
<file_sep><?php
namespace App\Interfaces;
interface ModelInterface {
}<file_sep><?php
/**
* List all your middleware with route name
* Middleware can be a function or a class with method->boot()
* @key route
* @value middleware
*/
$middleware = [
'*' => \Middleware\InitMiddleware::class,
'admin/*' => \Middleware\AuthMiddleware::class,
];
<file_sep><?php
namespace App;
use App\Interfaces\ModelInterface;
class Model implements ModelInterface
{
protected
$tableName,
$tablePrefix
;
protected $errorMessages = [
'no_model_name' => 'No Model Class Provided',
'unable_to_load' => 'Unable to load Model'
];
public $pdo;
public function __construct()
{
$this->tablePrefix = getenv('TABLE_PREFIX');
$this->setTableName();
$this->setPDO(Boot::getGlobal('pdo'));
}
public function setAttributes($arr)
{
if (!empty($arr) && sizeof($arr) > 0) {
foreach ($arr as $item => $value) {
$this->$item = $value;
}
return true;
}
return false;
}
public function setAttribute($name, $value) {
if (!empty($name)) {
$this->$name = $value;
return true;
}
return false;
}
protected function loadModel($model, $arguments = null)
{
try {
if (empty($model))
throw new \Exception($this->errorMessages['no_model_name']);
$newModel = new $model($arguments);
if (!$newModel)
throw new \Exception($this->errorMessages['unable_to_load']);
$modelClassNamespace = explode(
'\\',
get_class($newModel)
);
$modelClassName = sizeof($modelClassNamespace) > 0 ?
lcfirst(
$modelClassNamespace[count($modelClassNamespace) - 1]
) :
$modelClassNamespace
;
$this->$modelClassName = $newModel;
} catch (\Exception $exception) {
die($exception->getMessage());
}
}
private function setPDO($pdo)
{
$this->pdo = $pdo;
}
private function setTableName()
{
$classNamespace = get_called_class();
$classPath = explode('\\', $classNamespace);
$className = $classPath[count($classPath) - 1];
$pieces = Utility::splitByUpperCase($className);
$table = '';
if (sizeof($pieces) > 1) {
foreach ($pieces as $piece) {
$table .= !empty($piece) ? strtolower($piece) . '_' : '';
}
}
$this->tableName = !empty($this->tablePrefix) ?
$this->tablePrefix . rtrim($table, '_') :
rtrim($table, '_');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aqeel
* Date: 2/13/19
* Time: 12:45 PM
*/
namespace Middleware;
use App\Utility;
class AuthMiddleware
{
public function boot()
{
$err = <<<EOB
You're trying to access the route
which is protected by AuthMiddleware middleware <br>
To remove this restriction of middleware
go to config/middleware.php file and update
the \$middleware list or <br>
come to middleware/AuthMiddleware.php file and update me(boot function)
EOB;
Utility::print($err);
}
}<file_sep><?php
namespace App;
class Boot
{
protected static $globals = [];
public static function AppDir()
{
chdir(__DIR__ . '/../');
return getcwd();
}
public static function getGlobals()
{
return (object)self::$globals;
}
public static function getGlobal($name)
{
if (!isset(self::$globals[$name]))
return null;
return self::$globals[$name];
}
public static function setGlobals($arr)
{
if (!is_array($arr)) {
return false;
}
foreach ($arr as $key => $val) {
self::$globals[$key] = $val;
}
return true;
}
public static function setEnvVars($filePath)
{
if (file_exists($filePath)) {
require $filePath;
foreach ($vars as $key => $var) {
putenv("$key=$var");
}
}
return true;
}
public static function initSession()
{
session_start();
}
}<file_sep><?php
namespace App;
class Route
{
protected
$path,
$routesPath;
public
$page404,
$errorMessage;
public function __construct()
{
$this->path = isset($_GET['path']) ? $_GET['path'] : null;
$this->routesPath = 'routes';
$this->page404 = "404.php";
$this->errorMessage = "Nothing found";
}
public function boot()
{
if (!$this->path) {
return $this->loadIndexRoute();
} else {
return $this->loadRoute();
}
}
protected function loadIndexRoute()
{
$this->loadRouteFile($this->routesPath . '/index.php');
return $this;
}
protected function loadRoute()
{
chdir(Boot::AppDir());
$inCase1 = $this->routesPath . '/' . $this->path . '.php';
$inCase2 = $this->routesPath . '/' .
str_replace('/', '_', $this->path) .
'.php';
$inCase3 = $this->routesPath . '/' . $this->path . '/index.php';
$ofError404 = View::path() . '/404.php';
if (file_exists($inCase1)) {
$this->loadRouteFile($inCase1);
} elseif (file_exists($inCase2)) {
$this->loadRouteFile($inCase2);
} elseif (file_exists($inCase3)) {
$this->loadRouteFile($inCase3);
} elseif (file_exists($ofError404)) {
http_response_code(404);
$this->loadRouteFile($ofError404);
} else {
die($this->errorMessage);
}
return $this;
}
protected function loadRouteFile($filename)
{
$this->bootMiddleware();
require $filename;
}
protected function bootMiddleware()
{
require Boot::AppDir() . '/config/middleware.php';
if (isset($middleware) && !empty($middleware)) {
foreach ($middleware as $key => $item) {
if (is_array($item)) {
// in case of multiple middleware
foreach ($item as $innerValue) {
if (!empty($key) && !empty($innerValue)) {
$this->applyMiddleware(
$key,
$innerValue
);
}
}
continue;
}
if (!empty($key) && !empty($item)) {
$this->applyMiddleware($key, $item);
}
}
}
}
protected function applyMiddleware($route, $middleware)
{
if (preg_match("/\*/", $route)) {
$routeMatch = str_replace('*', '', $route);
$isMiddleware = !empty($routeMatch) && !empty($this->path) ?
strpos(
trim($this->path, '/'),
trim($routeMatch, '/')
) : null ;
if (
( empty($routeMatch) && empty($isMiddleware) ) ||
( $isMiddleware !== false && $isMiddleware === 0 )
) {
$this->runMiddleware($middleware);
}
} elseif (trim($this->path, '/') === trim($route, '/')) {
$this->runMiddleware($middleware);
}
}
protected function runMiddleware($class)
{
$obj = new $class();
$obj->boot($this);
}
}<file_sep><?php
/**
* Add all of your environment variables
* @key name of variable
* @value value of variable
*/
$vars = [
// Database Credentials
'DB_USER' => 'root',
'DB_PASS' => '<PASSWORD>',
'DB_NAME' => 'dbname',
'DB_HOST' => 'localhost',
'TABLE_PREFIX' => '',
'DEV_MOD' => false,
'SITE_URL' => 'http://localhost/',
'PUBLIC_PATH' => 'public',
];
<file_sep><?php
require 'vendor/autoload.php';
$activeDir = getcwd();
// Change directory to current file location
chdir(__DIR__);
use App\Route;
use App\View;
use App\Boot;
/*
* Init Session
* */
Boot::initSession();
/*
* - Set Environment variables
* */
Boot::setEnvVars(getcwd() . '/config/env.php');
/*
* - Setup Database Connection
* */
try {
$pdo = new \PDO(
"mysql:host=localhost;dbname=".getenv('DB_NAME').";charset=utf8mb4",
getenv('DB_USER'),
getenv('DB_PASS')
);
if (getenv('DEV_MOD')) {
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}
} catch (Exception $exception) {
if (getenv('DEV_MOD')) {
die($exception->getMessage());
}
}
/*
* - Init View Instance
* */
$view = new View();
/*
* - Set Globals
* */
Boot::setGlobals([
'view' => $view,
'pdo' => isset($pdo) ? $pdo : null
]);
/*
* - Init the Route
* - After route boot() the process will move to route file
* */
$route = new Route();
$route->boot();
// Change directory to active public file
chdir($activeDir);<file_sep><?php
namespace App;
class Utility
{
public static function splitByUpperCase($str)
{
return preg_split('/(?=[A-Z])/',$str);
}
public static function dump(...$vars)
{
echo "<pre>";
foreach ($vars as $var) {
var_dump($var);
}
echo "</pre>";
die();
}
public static function print(...$vars)
{
echo "<pre>";
foreach ($vars as $var) {
print_r($var);
}
echo "</pre>";
die();
}
public static function uniqueMultidimArray($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: aqeel
* Date: 2/13/19
* Time: 11:41 AM
*/
namespace Middleware;
class InitMiddleware
{
public function boot()
{
// this middleware has been applied to all routes
// check in config/middleware.php
}
}<file_sep><?php
namespace Model;
use App\Model;
class Cashmails extends Model
{
}<file_sep><?php
set_time_limit(0);
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require '../bootstrap.php';
<file_sep><?php
namespace App;
class View {
public static $globals = [];
public function __construct()
{
}
public function load($view, $data = [])
{
View::show($view. $data);
}
public static function show($view, $data = [])
{
$viewFilePath = str_replace('.', '/', $view);
$viewFile = __DIR__ . '/../views/'. $viewFilePath .'.php';
if (!file_exists($viewFile)) {
throw new \Exception("Unable to load view file ". $viewFile);
}
// Start
ob_start();
if (!empty($data))
extract($data);
if (!empty(self::$globals))
extract(self::$globals);
include $viewFile;
ob_end_flush();
// End
}
public static function path()
{
return Boot::AppDir() . '/views';
}
public static function setGlobals($var, $value = null)
{
if (is_array($var) && !empty($var)) {
foreach ($var as $item => $value) {
self::$globals[$item] = $value;
}
} elseif (!empty($var)) {
self::$globals[$var] = $value;
}
}
public static function getGlobal($varname, $default = null)
{
if (
isset(self::$globals[$varname]) &&
self::$globals[$varname] !== false
) {
return self::$globals[$varname];
} else {
return $default;
}
}
} | 624e238e5a8b91ab4f04e8c6af3b0aa09636efaa | [
"PHP"
] | 14 | PHP | smaqeelkazmi/php-starter-kit | d3b943f13f7b1af12aeccff95ad0b2e87353d1e3 | c58040530751ecc476c5ecd0ffbf60648ae0c4d6 |
refs/heads/master | <repo_name>jsw883/fas-solver<file_sep>/core/gio.cpp
// =============================================================================
/* Title : gio.cpp
* Summary : Methods for graph input / output functionality
* Author : <NAME>
* Date : 2015-09-17
* Version : 1.0
*
* Implements load and save methods for graph input / output functionality.
*/
// =============================================================================
// Headers
#include "gio.h"
// =============================================================================<file_sep>/core/unpair.h
// =============================================================================
/* Title : unpair.h
* Summary : Splits pair return type implicitly
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* Splits pair return type and assigns first and second to separate variables
* implicitly, using a struct functor to do variable assignment by reference
* and avoid unnecessary copies.
*
* // declare variables
* T1 var1;
* T2 var2;
*
* // unpair values
* unpair(var1, var2) = ...;
*/
// =============================================================================
// Headers
#ifndef UNPAIR_H
#define UNPAIR_H
#include <utility>
// =============================================================================
// Template functor
template <typename T1, typename T2>
struct unpair_functor {
public:
T1& a1;
T2& a2;
public:
explicit unpair_functor(T1& a1, T2& a2): a1(a1), a2(a2) { }
unpair_functor<T1,T2>& operator = (const std::pair<T1,T2>& p) {
a1 = p.first;
a2 = p.second;
return *this;
}
};
// =============================================================================
// Functor helper
template <typename T1, typename T2>
unpair_functor<T1,T2> unpair(T1& a1, T2& a2) {
return unpair_functor<T1,T2>(a1, a2);
}
// =============================================================================
#endif
// =============================================================================<file_sep>/core/fas.cpp
// =============================================================================
/* Title : fas.cpp
* Summary : Solvers for the Feedback Arc Set (FAS)
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* These solvers for the Feedback Arc Set (FAS) are from the paper by Hassin and
* Rubinstein, "Approximations for the maximum acyclic subgraph problem" (1994).
*
* Method 1
*
* Let A1 = {(i,j) ∈ A | i < j}, A2 = {(i,j) ∈ A | i > j}. Clearly, (V, A1) and
* (V, A2) are directed acyclic graphs, and since A1 ∪ A2 = A, we have the bound
* max(w(A1), w(A2)) ≥ 0.5*w(A), where w(α) is the sum of weights in the induced
* subgraph (V, α).
*/
// =============================================================================
// Headers
#include "fas.h"
// =============================================================================<file_sep>/core/graph.cpp
// =============================================================================
/* Title : graph.cpp
* Summary : Directed, weighted graph data structure using C++11
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* Implements a directed, weighted graph data structure based on the new C++11
* unordered map for efficient node storage, where edges are stored in vectors
* under each node, where edge weights are duplicated to prevent cache misses.
*
* Currently, variables are public and can be manipulated directly, but should
* eventually be private with an appropriate collection of getters and setters
* allowing nodes and edges to be accessed conveniently (and yet efficiently).
*
* The edge vectors should be implemented as a set, which is based on a binary
* search tree, allowing for fast search, insertion, and deletion of nodes, as
* graphs are often manipulated during algorithms.
*/
// =============================================================================
// Headers
#include "graph.h"
// =============================================================================<file_sep>/solver.cpp
// =============================================================================
/* Title : solver.h
* Summary : Main method for solving the Feedback Arc Set (FAS)
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* Main method for solving the Feedback Arc Set (FAS).
*/
// =============================================================================
// Headers
#include <string>
#include "timing.h"
#include "unpair.h"
#include "graph.h"
#include "fas.h"
#include "gio.h"
// =============================================================================
// Main method
// Print usage and exit with status 0
void usage(char* name) {
printf("usage: %s -i <source file name> -o <output base name> [-w]\n", name);
printf("computes an approximate solution to the feedback arc set (FAS)\n");
printf("-w\tsource graph weighted\n");
exit(0);
}
// Main method for solving the Feedback Arc Set (FAS)
int main(int argc, char *argv[]) {
setbuf(stdout, NULL); // disables buffer so printf displays immediately
// declare variables
std::string
source_filename = "./data/USairport2010.edges",
output_basename = "./data/USairport2010";
bool weighted = true;
Graph<double> source_graph, fas_graph, dag_graph;
// parse command line arguments (could use external library)
for (int i = 1; i < argc; i++) {
switch(argv[i][1]) {
case 'i':
source_filename = argv[i+1];
i++;
break;
case 'o':
output_basename = argv[i+1];
i++;
break;
case 'w':
weighted = true;
break;
case 'h':
usage(argv[0]);
default:
printf("\nerror: switch %s not recognized\n", argv[i]);
usage(argv[0]);
}
}
// print header
printf("[%s build: %s %s time: %s]\n", argv[0], __TIME__, __DATE__,
get_time());
printf("Loading %s\n", source_filename.c_str());
// =========================================================================
// read source graph and print simple graph summary
load_graph(source_graph, source_filename, weighted);
printf("Source graph "); source_graph.summary();
// FAS simple approximation method
fas_method1(source_graph, fas_graph, dag_graph);
// save output graph and print simple graph summary
save_graph(fas_graph, output_basename + "-fas.edges", weighted);
save_graph(dag_graph, output_basename + "-dag.edges", weighted);
printf("FAS graph "); fas_graph.summary();
printf("DAG graph "); dag_graph.summary();
// =========================================================================
}
// =============================================================================<file_sep>/core/gio.h
// =============================================================================
/* Title : gio.cpp
* Summary : Methods for graph input / output functionality
* Author : <NAME>
* Date : 2015-09-17
* Version : 1.0
*
* Implements load and save methods for graph input / output functionality.
*/
// =============================================================================
// Headers
#ifndef GIO_H
#define GIO_H
#include <string>
#include <fstream>
#include "unpair.h"
#include "graph.h"
// =============================================================================
// Load a saved graph edgelist (directed, possibly weighted)
template<typename EdgeW>
void load_graph(Graph<EdgeW>& graph, std::string filename, bool weighted) {
// file input stream for reading
std::ifstream finput;
finput.open(filename.c_str());
// declare variables for while loop
typename std::unordered_map<int, typename Graph<EdgeW>::Node>::iterator iter,
src_iter, dst_iter;
int src_id, dst_id;
EdgeW w = 1;
bool src_flag, dst_flag;
// initialize counters
graph.num_nodes = 0;
graph.num_edges = 0;
graph.sum_weights = 0;
// while there exist edges to read
while (!finput.eof()) {
// read edge
if (weighted) {
finput >> src_id >> dst_id >> w;
} else {
finput >> src_id >> dst_id;
}
// attempt to insert node and / or get iterator
unpair(src_iter, src_flag) = graph.nodes.emplace(src_id,
typename Graph<EdgeW>::Node(src_id));
unpair(dst_iter, dst_flag) = graph.nodes.emplace(dst_id,
typename Graph<EdgeW>::Node(dst_id));
graph.num_nodes += src_flag + dst_flag;
// add edge
src_iter->second.out_edges.push_back(std::make_pair(dst_id, w));
dst_iter->second.in_edges.push_back(std::make_pair(src_id, w));
graph.num_edges++;
graph.sum_weights += w;
}
finput.close();
}
// Save a graph edgelist (directed, possibly weighted)
template<typename EdgeW>
void save_graph(Graph<EdgeW>& graph, std::string filename, bool weighted) {
// file output stream for writing
std::ofstream foutput;
foutput.open(filename.c_str());
// declare variables for while loop
typename std::unordered_map<int, typename Graph<EdgeW>::Node>::iterator
node_iter;
typename std::vector<std::pair<int, EdgeW> > edges;
typename std::vector<std::pair<int, EdgeW> >::iterator edge_iter;
int src_id, dst_id;
EdgeW w = 1;
// iterate nodes
for (node_iter = graph.nodes.begin(); node_iter != graph.nodes.end();
node_iter++) {
// get src id
src_id = node_iter->first;
// iterate out edges (as in edges are copies for traversal efficiency)
edges = node_iter->second.out_edges;
for (edge_iter = edges.begin(); edge_iter != edges.end(); edge_iter++) {
// get dst id and w
dst_id = edge_iter->first;
w = edge_iter->second;
// write edge
if (weighted) {
foutput << src_id << " " << dst_id << " " << w << "\n";
} else {
foutput << src_id << " " << dst_id << "\n";
}
}
}
foutput.close();
}
// =============================================================================
#endif
// =============================================================================<file_sep>/core/graph.h
// =============================================================================
/* Title : graph.h
* Summary : Directed, weighted graph data structure using C++11
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* Implements a directed, weighted graph data structure based on the new C++11
* unordered map for efficient node storage, where edges are stored in vectors
* under each node, where edge weights are duplicated to prevent cache misses.
*
* Currently, variables are public and can be manipulated directly, but should
* eventually be private with an appropriate collection of getters and setters
* allowing nodes and edges to be accessed conveniently (and yet efficiently).
*
* The edge vectors should be implemented as a set, which is based on a binary
* search tree, allowing for fast search, insertion, and deletion of nodes, as
* graphs are often manipulated during algorithms.
*/
// =============================================================================
// Headers
#ifndef GRAPH_H
#define GRAPH_H
#include <utility>
#include <unordered_map>
#include <vector>
// =============================================================================
// Graph class
template <class EdgeW>
class Graph {
public:
// declare data structures
typedef std::pair<int, EdgeW> Edge;
class Node {
public:
int id_;
std::vector<Edge> in_edges, out_edges;
public:
Node(int id) : id_(id) { }
};
public:
// declare variables
std::unordered_map<int, Node> nodes;
int num_nodes;
int num_edges;
EdgeW sum_weights;
public:
// constructors
Graph() : num_nodes(0), num_edges(0), sum_weights(0) { }
// supplementary
void clear();
void summary();
};
// empty everything
template <class EdgeW>
void Graph<EdgeW>::clear() {
// clear node map
nodes.clear();
// reset counters
num_nodes = 0;
num_edges = 0;
sum_weights = 0;
}
// print simple graph summary
template <class EdgeW>
void Graph<EdgeW>::summary() {
// print summary
printf("summary\n");
printf(" nodes: %d\n", num_nodes);
printf(" edges: %d\n", num_edges);
printf(" sum of weights: %f\n", sum_weights);
}
// =============================================================================
#endif
// =============================================================================<file_sep>/README.md
Feedback Arc Set (FAS)
======================
This repository contains a approximate solvers for the Feedback Arc Set (FAS),
from the paper [Approximations for the maximum acyclic subgraph problem](http://www.shlomir.com/papers/acyclic.pdf)
by Hassin and Rubenstein (1994). Currently, only the first and trivial method
has been implemented.
However, this exercise also provided an opportunity to build an efficient and
straightforward graph class using C++11, and the [core](./core) classes and
functions are intended to be improved and reused for later graph related work
such as fully contained, highly efficient graph algorithms.
### Dependencies ###
All you need is gcc / g++ greater than 4.8.
```bash
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-5 g++-5
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 50
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 50
```
### Build ###
It's easy, and usage is contained in [solver.cpp](solver.cpp) already.
```bash
make
./solver
```<file_sep>/core/fas.h
// =============================================================================
/* Title : fas.h
* Summary : Solvers for the Feedback Arc Set (FAS)
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* These solvers for the Feedback Arc Set (FAS) are from the paper by Hassin and
* Rubinstein, "Approximations for the maximum acyclic subgraph problem" (1994).
*
* Method 1
*
* Let A1 = {(i,j) ∈ A | i < j}, A2 = {(i,j) ∈ A | i > j}. Clearly, (V, A1) and
* (V, A2) are directed acyclic graphs, and since A1 ∪ A2 = A, we have the bound
* max(w(A1), w(A2)) ≥ 0.5*w(A), where w(α) is the sum of weights in the induced
* subgraph (V, α).
*/
// =============================================================================
// Headers
#ifndef FAS_H
#define FAS_H
#include "graph.h"
// =============================================================================
// Feedback Arc Set (FAS)
// Method 1
template<typename EdgeW>
void fas_method1(Graph<EdgeW>& source_graph, Graph<EdgeW>& fas_graph,
Graph<EdgeW>& dag_graph) {
// declare variables for while loop
Graph<EdgeW> graph1, graph2;
typename std::unordered_map<int, typename Graph<EdgeW>::Node>::iterator node_iter,
src_iter, dst_iter;
typename std::vector<std::pair<int, EdgeW> > edges;
typename std::vector<std::pair<int, EdgeW> >::iterator edge_iter;
int src_id, dst_id;
EdgeW w;
bool src_flag, dst_flag;
// iterate nodes
for (node_iter = source_graph.nodes.begin();
node_iter != source_graph.nodes.end(); node_iter++) {
// get src id
src_id = node_iter->first;
// iterate out edges (as in edges are copies for traversal efficiency)
edges = node_iter->second.out_edges;
for (edge_iter = edges.begin(); edge_iter != edges.end(); edge_iter++) {
// get dst id and w
dst_id = edge_iter->first;
w = edge_iter->second;
// select graph reference based on node id inequality
Graph<EdgeW>& active_graph = (src_id < dst_id) ? graph1 : graph2;
// attempt to insert node and / or get iterator
unpair(src_iter, src_flag) = active_graph.nodes.emplace(src_id,
typename Graph<EdgeW>::Node(src_id));
unpair(dst_iter, dst_flag) = active_graph.nodes.emplace(dst_id,
typename Graph<EdgeW>::Node(dst_id));
active_graph.num_nodes += src_flag + dst_flag;
// add edge
src_iter->second.out_edges.push_back(std::make_pair(dst_id, w));
dst_iter->second.in_edges.push_back(std::make_pair(src_id, w));
active_graph.num_edges++;
active_graph.sum_weights += w;
}
}
// return directed acyclic graph with most weight retained
fas_graph = (graph1.sum_weights < graph2.sum_weights) ? graph1 : graph2;
dag_graph = (graph1.sum_weights > graph2.sum_weights) ? graph1 : graph2;
}
// =============================================================================
#endif
// =============================================================================
<file_sep>/core/timing.h
// =============================================================================
/* Title : timing.h
* Summary : Helper functions for timing
* Author : <NAME>
* Date : 2015-09-15
* Version : 1.0
*
* Currently contains a helper function for getting a simple time string, using
* strftime to format the string to match the __TIME__ and __DATE__ formatting.
*
*/
// =============================================================================
// Headers
#ifndef TIMING_H
#define TIMING_H
#include <ctime>
// =============================================================================
// Get simple time string
char * get_time() {
char *timestr = new char[80];
time_t rawtime;
time(&rawtime);
strftime(timestr, 80, "%H:%M:%S %b %d %G", localtime(&rawtime));
return timestr;
}
// =============================================================================
#endif
// =============================================================================<file_sep>/Makefile
# Makefile for Feedback Arc Set (FAS)
include ./Makefile.config
all: $(MAIN)
# COMPILE
$(MAIN): $(MAIN).cpp $(DEPH) $(DEPCPP)
$(CC) $(CXXFLAGS) -o $(MAIN) $(MAIN).cpp $(DEPCPP) -I$(CORE) $(LDFLAGS) $(LIBS)
clean:
rm -f *.o $(MAIN) $(MAIN).exe
| a0f0d9f7cdecd7ca2104b8e9bd7d07c8c83ef6f6 | [
"Markdown",
"C",
"Makefile",
"C++"
] | 11 | C++ | jsw883/fas-solver | 6f5751b63629cf9da65df94587f73c700509191b | e2bee3b818aca827ee8429c6a9d773ab88d17da9 |
refs/heads/master | <file_sep># adamalston<span></span>.com · [](https://app.circleci.com/pipelines/github/adamalston/v2) [](https://app.netlify.com/sites/adamalston/deploys)
The second iteration of [adamalston.com](https://www.adamalston.com) built with [React](https://reactjs.org/) and hosted with [Netlify](https://www.netlify.com/).
Previous iteration: [v1](https://github.com/adamalston/v1)
<img float="left" width="auto" height="370px" src="src/assets/preview.png" alt="Website Preview" role="img" aria-label="Screenshot of the website" /> <img align="right" height="370px" src="src/assets/mobile.png" alt="Website Preview" role="img" aria-label="Screenshot of the website" />
This website is designed to be simple and accessible. The dynamic particles make it both interactive and visually inviting. The website defaults to dark mode and can be toggled to light mode. Once toggled, the theme should persist between tabs, windows, and page reloads.
## :key: Open Source
I made this website open source under the assumption that others would use the code to create their own websites. I only ask that you use this code with attribution as I have spent a significant amount of time writing it.
If you use this code, please give me proper credit by linking back to [adamalston.com](https://www.adamalston.com/). Thanks!
##  Icons
[Font Awesome](https://fontawesome.com/) icons
| Use | Icon |
| ---------- | ---------------------------------------------------------------- |
| Dark Mode |  `['far', 'moon']` |
| Light Mode |  `['far', 'sun']` |
| GitHub |  `['fab', 'github']` |
| LinkedIn |  `['fab', 'linkedin'` |
| Resume |  `['fas', 'file-alt']` |
| Email |  `['fas', 'paper-plane']` |
## :art: Color Reference
Text and icons meet a color contrast ratio of 4.5:1 against the background of the website, conforming with [WCAG 2.1](https://www.w3.org/TR/WCAG21/) Section 1.4.3.
| Color | Hex |
| ----------- | ------------------------------------------------------------------ |
| Black |  `#000000` |
| Purple |  `#C311E7` |
| Turquoise |  `#4DC9FF` |
| Light Green |  `#90EE90` |
| Gold |  `#FFD300` |
| Light Red |  `#FF6961` |
| Silver |  `#BBBBBB` |
| Light Gray |  `#EEEEEE` |
Particle colors can be changed in [`src/components/Particles.jsx`](src/components/Particles.jsx#L14).
---
If you have any questions or feedback, open an issue and I will get back to you :​)
<file_sep>import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<div className="footer-container">
<p className="footer-text" aria-label="Designed and built by <NAME>">Designed and built by
<a className="footer-link" href="https://www.adamalston.com/"><NAME></a>
</p>
</div>
)
}
}
export default Footer;
| 7951301e02016c9a8dce6f2cbd90d71837f95eb3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | delta94/v2 | 7e191311597c01226932e146a3e12bbad5cdcb11 | 93d30921675f41d63222bdec0cdbb63919a5f160 |
refs/heads/master | <repo_name>prabhudorairaj85/My3-Automation<file_sep>/MY3_Automation/src/Pages/WebDriverTestBasePage.java
package Pages;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import listeners.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import util.WaitUtility;
/*
* @Class for WebDriver Test Base Page and related function,
* @Date:12-07-2014.
*/
public class WebDriverTestBasePage extends WaitUtility {
/** This page's WebDriver */
public static WebDriver driver;
protected String browser;
public static boolean TestResult = true;
/**
* Initialize test properties ( WebDriver, implicitlyWait, and etc).
**/
protected void initialize(WebDriver driver) {
setImplicitWait(driver, 15);
WebDriverTestBasePage.driver = driver;
driver.manage().window().maximize();
}
public void scrollDownWindow(WebDriver driver) {
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,600)", "");
}
public void scrollUpWindow(WebDriver driver) {
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,-600)", "");
}
public void clickonSVGObject(String xPathlocator) {
EventFiringWebDriver myTestDriver = new EventFiringWebDriver(driver);
myTestDriver.manage().window().maximize();
Locatable hoverItem = (Locatable) myTestDriver.findElement(By
.xpath(xPathlocator));
Coordinates MyTestCoordinates = hoverItem.getCoordinates();
try {
myTestDriver.getMouse().mouseMove(MyTestCoordinates);
myTestDriver.getMouse().mouseDown(MyTestCoordinates);
myTestDriver.getMouse().mouseUp(MyTestCoordinates);
} catch (Exception e1) {
System.out.println(e1);
}
}
public void verifyText(String expected, String actual, String msg) {
try {
Assert.assertTrue(expected.equals(actual), "Expected Text : "
+ expected + " is not equal to the Actual Text : " + actual);
} catch (Error e) {
Reporter.log("<br/> <font color='red'>" + msg);
Reporter.log("<br/>Text Verification Failed with Error: "
+ e.getMessage() +"</font>");
WebDriver driver = WebDriverManager.getDriverInstance();
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat(
"dd_MMM_yyyy__hh_mm_ssaa");
String destDir = "html/screenshots";
new File(destDir).mkdirs();
String destFile = dateFormat.format(new Date()) + ".png";
try {
FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
} catch (IOException e1) {
e1.printStackTrace();
}
Reporter.setEscapeHtml(false);
Reporter.log("<br/> Saved");
Reporter.log("<a target='_blank' href='../html/screenshots/"
+ destFile + "'>View Screenshot</a>");
TestResult = false;
}
}
public void verifyTextContains(String expected, String actual, String msg) {
try {
Assert.assertTrue(actual.contains(expected), "Expected Text : "
+ expected + " is not equal to the Actual Text : " + actual);
} catch (Error e) {
Reporter.log("<br/> <font color='red'>" + msg);
Reporter.log("<br/>Text Verification Failed with Error: "
+ e.getMessage() +"</font>");
WebDriver driver = WebDriverManager.getDriverInstance();
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat(
"dd_MMM_yyyy__hh_mm_ssaa");
String destDir = "html/screenshots";
new File(destDir).mkdirs();
String destFile = dateFormat.format(new Date()) + ".png";
try {
FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
} catch (IOException e1) {
e1.printStackTrace();
}
Reporter.setEscapeHtml(false);
Reporter.log("<br/> Saved");
Reporter.log("<a target='_blank' href='../html/screenshots/"
+ destFile + "'>View Screenshot</a>");
TestResult = false;
}
}
@Parameters("browser")
@BeforeClass
public void openUrl(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("ie")) {
// System.setProperty("webdriver.ie.driver",
// "C:/IEDriverServer_x64_2.39.0/IEDriverServer.exe");
// driver = new InternetExplorerDriver();
}
}
}
<file_sep>/MY3_Automation/src/Pages/OverviewPage.java
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.asserts.SoftAssert;
/*
* @Class for Overview Page elements and related function,
* @Date:14-07-2014.
*/
public class OverviewPage extends LoginPage {
@FindBy(xpath = "//div[@class='usage-summary-disc']//*[name()='svg']/*[name()='text'][7]/*[name()='tspan']")
private WebElement header_center_point_txt;
@FindBy(xpath = "//div[@class='usage-summary-disc']//*[name()='svg']/*[name()='text'][6]/*[name()='tspan']")
private WebElement header_center_three_pott_txt;
@FindBy(xpath = "//div[@class='usage-summary-module']//a[@class='active']")
private WebElement lnk_username;
@FindBy(xpath = "//*[@id='usage-summary-module']/div[2]/header/p/a" )
private WebElement Subscriptiontype_inoverviewpage;
@FindBy(id = "notifications-list-container" )
private WebElement Notification_in_overviewpage;
@FindBy(xpath = "//*[@id='ctl02']/div[3]/main/section[1]/div/div/div[2]/div/div[2]/p/span")
private WebElement subscription_in_overviewpage;
@FindBy(xpath = "//*[@id='new-invoice']/div/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/span" )
private WebElement Invoice_in_overviewpage;
@FindBy(xpath = "//*[name()='svg']/*[name()='text'][13]/*[name()='tspan']")
private WebElement circle_minute_Point;
@FindBy(xpath = "//div[@class='usage-summary-sub-discs']//*[name()='svg']/*[name()='text'][9]/*[name()='tspan']")
private WebElement circle_SMS_Point;
@FindBy(xpath = "//div[@class='usage-summary-sub-discs']//*[name()='svg']/*[name()='text'][5]/*[name()='tspan']")
private WebElement circle_KB_data_Point;
@FindBy(xpath = "//button[@class='button close-details']")
private WebElement btn_back;
@FindBy(xpath = "//div[@class='usage-summary-details']//button[@class='button close-details']")
private WebElement btn_back_AfterSubCircleClicked;
@FindBy(xpath = "//div[@class='usage-sum']//h1/span[contains(.,'sek')]")
private WebElement span_minute_point_kr_txt;
@FindBy(xpath = "//div[@class='usage-sum']//h1/span[contains(.,'St')]")
private WebElement span_SMS_point_kr_txt;
@FindBy(xpath = "//div[@class='usage-sum']//h1/span[contains(.,'KB')]")
private WebElement span_KB_data_point_kr_txt;
@FindBy(xpath = "//*[@id='sub-nav']//a[contains(.,'Abonnemang')]")
private WebElement lnk_subscription;
@FindBy(xpath = "//*[@id='sub-nav']//a[contains(.,'Faktura')]")
private WebElement lnk_invoice;
@FindBy(xpath = "//*[@id='sub-nav']//a[contains(.,'Notifieringar')]")
private WebElement lnk_notification;
@FindBy(xpath = "//div[@class='site-operations container']//li[4]/a")
private WebElement lnk_account_settings;
public void verifyCenter_points() {
isElementPresent(header_center_point_txt);
verifyText("169", header_center_point_txt.getText().toString(),
"Center Point doesn't contain the text 69.");
Reporter.log("<br/> Assertion: Center Point 69 verified.");
}
public void verifyCenter_threePott() {
isElementPresent(header_center_three_pott_txt);
verifyText("3Pott", header_center_three_pott_txt.getText(),
"Center text doesn't contain the text 3Pott.");
Reporter.log("<br/>Assertion: Center text 3Pott verified.");
}
public void verify_Subscriptiontype() {
isElementPresent(Subscriptiontype_inoverviewpage);
verifyText("3Pott 399",Subscriptiontype_inoverviewpage.getText(), "its not a 3Pott 69 subscription.");
Reporter.log("<br/>Assertion: Its a" + Subscriptiontype_inoverviewpage.getText() + "Subscription" );
}
public void verify_UserName() {
isElementPresent(lnk_username);
verifyText("<NAME> 3", lnk_username.getText(),
"UserName Mannen från 3 in the bottom of the page is not displayed.");
Reporter.log("<br/>Assertion: UserName in the bottom of the page verified.");
}
public void verify_Notification(){
isElementPresent(Notification_in_overviewpage);
Reporter.log("<br/> Notificaiton is loaded on the overview page");
}
public void verify_susbcription_overview() {
isElementPresent(subscription_in_overviewpage);
verifyText("072 3009 821", subscription_in_overviewpage.getText(), "Subscription details(number) are not loaded on the overview page");
Reporter.log("<br/> Assertion : subscription details are loaded on the overview page");
}
public void verify_invoice_overview() {
isElementPresent(Invoice_in_overviewpage);
verifyText("10063300148", Invoice_in_overviewpage.getText(), "Faktura is not loaded on the overview page");
Reporter.log("<br/> Assertion : faktura is loaded on the overview page");
}
public void clickOnCircle() {
clickonSVGObject("//*[@r='140']");
Reporter.log("<br/>Center Circle Clicked.");
}
public void clickOnAccountSettingsLink() {
lnk_account_settings.click();
Reporter.log("<br/>Account Settings link Clicked.");
}
public void verifyCircle_Minutes_points() {
verifyText("0", circle_minute_Point.getText(),
"Circle with minute doesn't contain the text");
Reporter.log("<br/> Assertion: Minute Circle Point 0 verified.");
}
public void verifyCircle_SMS_points() {
isElementPresent(circle_SMS_Point);
verifyText("0", circle_SMS_Point.getText(),
"Circle with SMS/MMS doesn't contain the text.");
Reporter.log("<br/> Assertion: SMS/MMS Circle Point 0 verified.");
}
public void verifyCircle_KB_data_points() {
isElementPresent(circle_KB_data_Point);
verifyText("0", circle_KB_data_Point.getText(),
"Circle with KB data doesn't contain the text.");
Reporter.log("<br/> Assertion: KB data Circle Point 0 verified.");
}
public void clickOnMinuteCircle() {
clickonSVGObject("//*[name()='svg']/*[name()='text'][13]/*[name()='tspan']");
Reporter.log("<br/>Minute Center Circle Clicked.");
}
public void clickOnSMSCircle() {
clickonSVGObject("//div[@class='usage-summary-sub-discs']//*[name()='svg']/*[name()='text'][9]/*[name()='tspan']");
Reporter.log("<br/>SMS Circle Clicked.");
}
public void clickOnKBdataCircle() {
clickonSVGObject("//div[@class='usage-summary-sub-discs']//*[name()='svg']/*[name()='text'][5]/*[name()='tspan']");
Reporter.log("<br/>KB data Circle Clicked.");
}
public void clickOnBackButton() {
btn_back.click();
Reporter.log("<br/>Back Button Clicked.");
}
public void clickOnKrBackButton() {
btn_back_AfterSubCircleClicked.click();
Reporter.log("<br/>Back Button After Kr Verification Clicked.");
}
public void verify_Minutes_points_kr() {
isElementPresent(span_minute_point_kr_txt);
verifyTextContains("0 kr", span_minute_point_kr_txt.getText(),
"Text with sek doesn't contain the 0 kr text.");
Reporter.log("<br/> Assertion: Minutes Point 0 kr verified.");
}
public void verify_SMS_points_kr() {
isElementPresent(span_SMS_point_kr_txt);
verifyTextContains("0 kr", span_SMS_point_kr_txt.getText(),
"Text with st doesn't contain the 0 kr text.");
Reporter.log("<br/> Assertion: SMS Point with St 0 kr verified.");
}
public void verify_KB_data_points_kr() {
isElementPresent(span_KB_data_point_kr_txt);
verifyTextContains("0 kr", span_KB_data_point_kr_txt.getText(),
"Text with KB doesn't contain the 0 kr text.");
Reporter.log("<br/> Assertion: KB data Point with KB 0 kr verified.");
}
public void clickOnSubscriptionLink() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isElementPresent(lnk_subscription);
Reporter.log("<br/>Before subscription link clicking.");
lnk_subscription.click();
Reporter.log("<br/>Subscription Link Clicked.");
}
public void clickOnInvoiceLink() {
lnk_invoice.click();
Reporter.log("<br/>Invoice Link Clicked.");
}
public void clickOnNotificationsLink() {
lnk_notification.click();
Reporter.log("<br/>Notification Link Clicked.");
}
public void verify_SubCircleDetails() {
verifyCircle_Minutes_points();
verifyCircle_SMS_points();
verifyCircle_KB_data_points();
clickOnMinuteCircle();
verify_Minutes_points_kr();
clickOnKrBackButton();
verifyCircle_SMS_points();
clickOnSMSCircle();
verify_SMS_points_kr();
clickOnKrBackButton();
verifyCircle_KB_data_points();
clickOnKBdataCircle();
verify_KB_data_points_kr();
clickOnKrBackButton();
clickOnBackButton();
}
}
<file_sep>/MY3_Automation/src/Pages/LoginPage.java
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.Reporter;
/*
* @Class for Login Page elements and related function,
* @Date:12-07-2014.
*/
public class LoginPage extends HomePage {
@FindBy(xpath = "//*[@id='txtUsername']")
private WebElement txt_userName;
@FindBy(xpath = "//*[@id='txtPassword']")
private WebElement txt_password;
@FindBy(xpath = "//*[@id='btnLogin']")
private WebElement btn_logIn;
@FindBy(xpath = "//h2[contains(.,'Logga in på Mitt3')]")
private WebElement header_logIn;
@FindBy(xpath = "//p[@class='error-message colored']")
private WebElement para_Error;
public void fillCredentials(String uid, String Password) {
txt_userName.clear();
txt_userName.sendKeys(uid);
txt_password.clear();
txt_password.sendKeys(<PASSWORD>);
btn_logIn.click();
}
public void verifyLoginHeader() {
waitForJQueryProcessing(driver, 10);
isElementPresent(header_logIn);
}
public void verifyErrorMessage() {
Assert.assertTrue(
para_Error
.getText()
.contains(
"Fel användarnamn/telefonnummer. Vänligen försök igen."),
"Error message not displayed");
Reporter.log(" Error Message displayed is: " + para_Error.getText());
}
public void signOut() {
}
}
<file_sep>/MY3_Automation/src/Pages/NotificationPage.java
package Pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import org.testng.Reporter;
/*
* @Class for Notification Page elements and related function,
* @Date:14-07-2014.
*/
public class NotificationPage extends LoginPage {
@FindBy(xpath = "//div[@class='notification']//h2")
private WebElement header_notification;
@FindBy(xpath = "//div[@id='notifications-table-header']//div[1]/p")
private WebElement txt_Date;
@FindBy(xpath = "//div[@id='notifications-table-header']//div[2]/p")
private WebElement txt_description;
/*
* @FindBy(xpath =
* "//div[@id='notifications-list-container']/div[4]//span[1]/strong")
* private WebElement txt_Jul2;
*/
@FindBy(xpath = "//div[@id='notifications-list-container']/div[1]//div[2]/a")
private WebElement Notification_loaded;
public void verify_NotificationHeader() {
isElementPresent(header_notification);
verifyText("Notifieringar", header_notification.getText(),
"Notification Header doesn't contain the Notifieringar text.");
Reporter.log("<br/> Assertion: Notification Header with Notifieringar text verified.");
}
public void verify_DateHeader() {
isElementPresent(txt_Date);
verifyText("Datum", txt_Date.getText(),
"Date Header doesn't contain the Datum text.");
Reporter.log("<br/> Assertion: Date Header with Datum text verified.");
}
public void verify_DescriptionHeader() {
isElementPresent(txt_description);
verifyText("Beskrivning", txt_description.getText(),
"Description Header doesn't contain the Beskrivning text.");
Reporter.log("<br/> Assertion: Description Header with Beskrivning text verified.");
}
/*
* public void verify_July2Text() {
* Assert.assertTrue(isElementPresent(txt_Jul2));
* Assert.assertTrue(txt_Jul2.getText().contains("Jul 2"),
* "Second row doesn't contain the Jul 2 text.");
* Reporter.log("<br/> Assertion: Second row with Jul 2 text verified."); }
*/
public void verify_Notification() {
isElementPresent(Notification_loaded);
Reporter.log("<br/> Assertion: Second row's Link verified.");
}
}
<file_sep>/MY3_Automation/src/Pages/HomePage.java
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.Reporter;
/*
* @Class for Home Page elements and related function,
* @Date:31-07-2014.
*/
public class HomePage extends WebDriverTestBasePage {
@FindBy(xpath = "///span[contains(.,'Registrera')]")
private WebElement lnk_register;
@FindBy(xpath = "//span[contains(.,'Logga in på Mitt3')]")
private WebElement lnk_login;
@FindBy(xpath = "//div[@id='im-close']")
private WebElement div_popUp;
public void clickRegisterLink() {
isElementPresent(lnk_register);
lnk_register.click();
Reporter.log("<br/> Register Link clicked.");
}
public void closeInitialPopup() {
if (isElementPresent(div_popUp)) {
div_popUp.click();
Reporter.log("<br/> Initial PopUp Closed.");
} else {
Reporter.log("<br/> Initial PopUp Not opened.");
}
}
public void clickLogInLink() {
isElementPresent(lnk_login);
lnk_login.click();
Reporter.log("<br/> Login link clicked");
}
public void verify_LoginLink() {
isElementPresent(lnk_login);
verifyText("Logga in på Mitt3", lnk_login.getText(),
"Login Link doesn't contain the Logga in på Mitt3 text.");
Reporter.log("<br/> Assertion: Login Link with Logga in på Mitt3 text verified.");
}
}
<file_sep>/MY3_Automation/src/listeners/ScreenShotOnFailure.java
package listeners;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.Reporter;
/*
* @Class for Capturing screenshot on Failure,
* @Date:12-07-2014.
*/
public class ScreenShotOnFailure extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult tr) {
WebDriver driver = WebDriverManager.getDriverInstance();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");
String destDir = "html/screenshots";
new File(destDir).mkdirs();
String destFile = dateFormat.format(new Date()) + ".png";
try {
FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
} catch (IOException e) {
e.printStackTrace();
}
Reporter.setEscapeHtml(false);
Reporter.log("<br/> Saved");
Reporter.log("<a target='_blank' href='../html/screenshots/"+ destFile +"'>View Screenshot</a>");
}
}<file_sep>/MY3_Automation/src/Pages/InvoicePage.java
package Pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import org.testng.Reporter;
/*
* @Class for Invoice Page elements and related function,
* @Date:14-07-2014.
*/
public class InvoicePage extends LoginPage {
@FindBy(xpath = "//div[@class='mod-autogiro']//h1")
private WebElement header_invoice_overview;
@FindBy(xpath = "//*[@id='invoice_513129154029']/div[1]/div[1]/div[1]")
private WebElement txt_technology;
@FindBy(xpath = "//*[@id='invoice_513129154029']/div[1]/div[1]/div[6]/a")
private WebElement lnk_see_Invoice;
public void verify_invoiceOverviewHeader() {
isElementPresent(header_invoice_overview);
verifyText("Faktura÷versikt", header_invoice_overview.getText(),
"Invoice Overview Header doesn't contain the Faktura÷versikt text.");
Reporter.log("<br/> Assertion: Invoice Overview Header with Faktura÷versikt text verified.");
}
public void verify_Technology() {
isElementPresent(txt_technology);
verifyTextContains("Technology Madeleine Bergl÷f", txt_technology.getText(),
"Technology doesn't contain the Technology Madeleine Bergl÷f text.");
Reporter.log("<br/> Assertion: Technology with Technology Madeleine Bergl÷f text verified.");
}
public void clickOnSeeInvoiceLink() {
lnk_see_Invoice.click();
Reporter.log("<br/>See Invoice Link Clicked.");
}
}
| 5892d0221cce2ffa9ae0aaa4bfbd78fba2465ddf | [
"Java"
] | 7 | Java | prabhudorairaj85/My3-Automation | b8bd534f3817d99919cd8ae7122b398c3bc71fe8 | ec3c60d250435196cd22a2380cd167017040901c |
refs/heads/master | <repo_name>MatheusBrunoAlmeida/CadastroPessoa<file_sep>/src/app/pessoas/lista-pessoas/lista-pessoas.component.ts
import {Component, OnInit} from '@angular/core';
import { PessoaModule } from '../../shared/pessoa.module';
import { ApiService } from '../../api.service';
import {DataService} from '../../shared/data.service';
import {Router} from '@angular/router';
import {PagerService} from '../../pager.service';
@Component({
selector: 'app-lista-pessoas',
templateUrl: './lista-pessoas.component.html',
styleUrls: ['./lista-pessoas.component.css']
})
export class ListaPessoasComponent implements OnInit {
query = '';
pessoas: PessoaModule[] = [];
pessoasVisiveis: PessoaModule[] = [];
pessoasPaginadas: PessoaModule[] = [];
pager: any = {};
constructor(private pagerService: PagerService, public api: ApiService, private data: DataService, private router: Router) { }
ngOnInit() {
this.getPessoas();
}
getPessoas() {
this.api.getAllPessoas().subscribe((data: PessoaModule[]) => {
this.pessoas = data;
this.pessoasVisiveis = this.pessoas;
this.pessoasPaginadas = this.pessoas;
this.onMudarPaginas(1);
}, () => {
this.data.storage = 'Erro: Não foi possível acessar o banco de dados.';
this.router.navigate(['/erro']);
});
}
onMudarPaginas(pagina: number) {
this.pager = this.pagerService.getPager(this.pessoasVisiveis.length, pagina);
this.pessoasPaginadas = this.pessoasVisiveis.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
filtrarPessoas() {
/* consultado: https://stackoverflow.com/questions/40678206/angular-2-filter-search-list */
if (this.query === '') {
this.pessoasVisiveis = this.pessoas;
} else {
this.pessoasVisiveis = Object.assign([], this.pessoas).filter(
pessoa => pessoa.nome.toLowerCase().indexOf(this.query.toLowerCase()) > -1
);
}
this.onMudarPaginas(1);
}
}
<file_sep>/src/app/pessoas/pessoas.component.ts
import { Component, OnInit } from '@angular/core';
import {DataService} from '../shared/data.service';
@Component({
selector: 'app-pessoas',
templateUrl: './pessoas.component.html'
})
export class PessoasComponent implements OnInit {
pessoaCadastrada = false;
constructor(private data: DataService) { }
ngOnInit() {
this.pessoaCadastrada = this.data.add;
}
}
<file_sep>/src/app/shared/pessoa.module.ts
import { Inject, InjectionToken, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
/* consultado: https://stackoverflow.com/questions/51275878/angular-cant-resolve-all-parameters-for-component-ng-build-prod */
export const ID: InjectionToken<string> = new InjectionToken<number>('ID');
export const NOME: InjectionToken<string> = new InjectionToken<string>('NOME');
export const EMAIL: InjectionToken<string> = new InjectionToken<string>('EMAIL');
export const IDADE: InjectionToken<string> = new InjectionToken<number>('IDADE');
export const LOGIN: InjectionToken<string> = new InjectionToken<string>('LOGIN');
export const SENHA: InjectionToken<string> = new InjectionToken<string>('SENHA');
export const STATUS: InjectionToken<string> = new InjectionToken<boolean>('STATUS');
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class PessoaModule {
constructor(
@Inject(ID) public id: number,
@Inject(NOME) public nome: string,
@Inject(EMAIL) public email: string,
@Inject(IDADE) public idade: number,
@Inject(LOGIN) public login: string,
@Inject(SENHA) public senha: string,
@Inject(STATUS) public status: boolean) {}
}
<file_sep>/src/app/pessoas/pessoa-detalhes/pessoa-detalhes.component.ts
import {Component, OnInit} from '@angular/core';
import {PessoaModule} from '../../shared/pessoa.module';
import {ActivatedRoute, Router} from '@angular/router';
import {ApiService} from '../../api.service';
import {DataService} from '../../shared/data.service';
@Component({
selector: 'app-pessoa-detalhes',
templateUrl: './pessoa-detalhes.component.html'
})
export class PessoaDetalhesComponent implements OnInit {
pessoa: PessoaModule = null;
senhaInvisivel = true;
constructor( private data: DataService, public api: ApiService, private route: ActivatedRoute, private router: Router) {
}
ngOnInit() {
this.route.url.subscribe(params => {
if (params[0]) {
const id = parseInt(params[0].path, 10);
if (!isNaN(id)) {
this.getPessoaDetalhes(id);
} else {
this.data.storage = 'Erro: ID não é um número.';
this.router.navigate(['/erro']);
}
}
});
}
getPessoaDetalhes(id: number) {
this.api.getPessoaById(id).subscribe((data) => {
if (data['status'] !== 404) {
this.pessoa = data;
} else {
this.data.storage = 'Erro: ID não existe no banco de dados.';
this.router.navigate(['/erro']);
}
});
}
}
<file_sep>/README.md
# Projeto Cadastro Pessoa
Projeto simples para cadastro e consulta de pessoas.
Feito para relembrar o angular<file_sep>/src/app/api.service.ts
/* consultado: https://www.djamware.com/post/5b87894280aca74669894414/angular-6-httpclient-consume-restful-api-example+ */
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
const API_URL = environment.apiUrl;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
return of(error as T);
};
}
private extrairDados(res: Response) {
let body = res;
return body || { };
}
// API: GET /pessoas
public getAllPessoas() {
return this.http.get(API_URL + '/pessoas').pipe(
map(this.extrairDados));
}
// API: POST /pessoas
public createPessoa(pessoa) {
return this.http.post<any>(API_URL + '/pessoas', JSON.stringify(pessoa), httpOptions).pipe(
catchError(this.handleError<any>('createPessoa'))
);
}
// API: GET /pessoas/:id
public getPessoaById(pessoaId: number) {
return this.http.get(API_URL + '/pessoas/' + pessoaId).pipe(
map(this.extrairDados),
catchError(this.handleError<any>('getPessoaById'))
);
}
}
<file_sep>/src/app/shared/data.service.ts
/* consultado: https://www.thepolyglotdeveloper.com/2016/10/passing-complex-data-angular-2-router-nativescript/ */
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
storage: any;
add = false;
public constructor() {}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { PessoasComponent } from './pessoas/pessoas.component';
import { ListaPessoasComponent } from './pessoas/lista-pessoas/lista-pessoas.component';
import { PessoaDetalhesComponent } from './pessoas/pessoa-detalhes/pessoa-detalhes.component';
import { CriarPessoaComponent } from './criar-pessoa/criar-pessoa.component';
import { ErroComponent } from './erro/erro.component';
import { ApiService } from './api.service';
import { DataService } from './shared/data.service';
import {PagerService} from './pager.service';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
PessoasComponent,
ListaPessoasComponent,
PessoaDetalhesComponent,
CriarPessoaComponent,
ErroComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
ReactiveFormsModule
],
providers: [ApiService, DataService, PagerService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CriarPessoaComponent } from './criar-pessoa/criar-pessoa.component';
import { PessoasComponent } from './pessoas/pessoas.component';
import { ErroComponent } from './erro/erro.component';
const routes: Routes = [
{ path: 'criar', component: CriarPessoaComponent },
{ path: 'lista', children: [
{ path: '', component: PessoasComponent },
{ path: ':id', component: PessoasComponent }
]
},
{ path: '',
redirectTo: '/criar',
pathMatch: 'full'
},
{ path: 'erro', component: ErroComponent },
{ path: '**', redirectTo: '/erro'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
| bf163c56792f0140a50e458f3552107a3c4cf543 | [
"Markdown",
"TypeScript"
] | 9 | TypeScript | MatheusBrunoAlmeida/CadastroPessoa | df77ce7d0ebec890ce48289a0aa7a0ba4da39f41 | c218ce428fcec50a72dcf3f0411285302a5804b4 |
refs/heads/master | <repo_name>biscuitderg/ProtoBot<file_sep>/cogs/events.py
import asyncio
import datetime
import discord
from discord.ext import commands
from cogs.utils.loggerEntry import JoinLeave, Ban, Unban
from cogs.utils.modUtils import ModUtils
class Events(commands.Cog, ModUtils):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
self.msg_flag_channel = self.get_channel('msg_flag_channel')
def get_mod(self):
return self.bot.get_cog("Moderator")
@commands.Cog.listener()
async def on_command_completion(self, ctx):
cmd = ctx.command
args = ctx.args[2:]
kwargs = list(ctx.kwargs.values())
full_args = args + kwargs
complete_args = []
try:
for count, key in enumerate(cmd.clean_params.keys()):
complete_args.append((key, full_args[count]))
except IndexError:
return
author = ctx.author
mentioned = ctx.message.mentions
cog = self.get_mod()
if cmd.cog == cog:
embed = discord.Embed(
title=f'Moderator command used ({cmd.name}):',
color=discord.Color(0xe62169),
timestamp=datetime.datetime.utcnow()
)
embed.add_field(
name='Command:',
value=cmd
)
embed.add_field(
name='User:',
value=author
)
if complete_args:
embed.add_field(
name='Parameters:',
value='\n'.join(f'"{a}: {v}"' for a, v in complete_args)
)
if mentioned:
embed.add_field(
name='Mentioned/affected users:',
value=', '.join([f"{u} ({u.mention})" for u in mentioned])
)
channel_id = cog.log_channel
channel = self.bot.get_channel(channel_id)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
author = payload.member
emoji = payload.emoji
channel_id = payload.channel_id
msg_id = payload.message_id
channel = self.bot.get_channel(channel_id)
msg = await channel.fetch_message(msg_id)
url = msg.jump_url
if str(emoji) == '❌':
channel = msg.channel
if channel.id != 510561673971499023:
embed = discord.Embed(
title=f'Message flagged in {channel}',
description=f"[Jump to message]({url})",
color=discord.Color(0xe62169),
timestamp=datetime.datetime.utcnow()
)
if msg.attachments:
attachments = msg.attachments
embed.set_image(url=attachments[0].url)
length = len(attachments)
if length > 1:
embed.add_field(
name=f'There were in total {length} attachments to this message.',
value='This was just the first one in the attachments list.'
)
embed.set_footer(text=f"Message ID: {msg_id}")
await msg.add_reaction('✅')
log_channel = channel.guild.get_channel(self.msg_flag_channel)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_join(self, member):
guild = member.guild
cog = self.get_mod()
diff = datetime.datetime.utcnow() - member.created_at
if diff.total_seconds() < 604800:
acc_created = '{:%b %d, %Y at %I:%M:%S %p} (UTC-0)\n`[Less than one week old]`'.format(member.created_at)
else:
acc_created = '{:%b %d, %Y at %I:%M:%S %p} (UTC-0)'.format(member.created_at)
await cog.log_entry(
member,
title='Member Joined',
description=f"{member} ({member.mention}) has joined the guild.\n"
f"Account Created: **{acc_created}**\n"
f"**{guild}** now has **{guild.member_count}** users!\n",
entry_type=JoinLeave,
set_thumbnail={"url": member.avatar_url_as(static_format='png')}
)
@commands.Cog.listener()
async def on_member_remove(self, member):
guild = member.guild
cog = self.get_mod()
await cog.log_entry(
member,
title='Member Left',
description=f"**{member}** ({member.mention}) has left the guild.\n"
f"**{guild}** now has **{guild.member_count}** users.\n",
entry_type=JoinLeave,
set_thumbnail={"url": member.avatar_url_as(static_format='png')}
)
@commands.Cog.listener()
async def on_member_ban(self, guild, member):
await asyncio.sleep(1)
cog = self.get_mod()
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
if entry.target == member:
resp_user = entry.user
return await cog.log_entry(
member,
guild=guild,
title="Member Banned",
description=f"**{member}** ({member.mention}) was banned from the guild.\n"
f"**{guild}** now has **{guild.member_count}** users.\n",
entry_type=Ban,
set_thumbnail={"url": member.avatar_url_as(static_format='png')},
add_field={"name": "Responsible User",
"value": f"{resp_user} ({resp_user.mention})",
"inline": False}
)
@commands.Cog.listener()
async def on_member_unban(self, guild, member):
cog = self.get_mod()
await asyncio.sleep(1)
async for entry in guild.audit_logs(action=discord.AuditLogAction.unban):
if entry.target == member:
resp_user = entry.user
return await cog.log_entry(
member,
guild=guild,
title='Member Unbanned',
description=f"**{member}** ({member.mention}) was unbanned from **{guild}**.",
entry_type=Unban,
set_thumbnail={"url": member.avatar_url_as(static_format='png')},
add_field={"name": "Responsible User",
"value": f"{resp_user} ({resp_user.mention})",
"inline": False}
)
def setup(bot):
bot.add_cog(Events(bot))
<file_sep>/cogs/utils/loggerEntry.py
from functools import wraps
class InvalidLoggerTypeArgumentException(Exception): # Really long amirite ;)
pass
class LoggerEntry:
@property
def channel(self):
return f"{str(self)}_channel"
def __repr__(self):
return self.__class__.__name__
def __str__(self):
return self.__class__.__name__
@staticmethod
def converter(func):
@wraps(func)
def wrapper(*args, **kwargs):
final_args = {}
for name, value in kwargs.items():
adapt = func.__annotations__.get(name)
if adapt is not None:
final_args[name] = adapt(value)
else:
final_args[name] = value
return func(*args, **kwargs)
return wrapper
@staticmethod
def check(param):
return LoggerEntry._check(param())
@classmethod
def _check(cls, argument):
if isinstance(argument, LoggerEntry):
return argument
else:
raise InvalidLoggerTypeArgumentException(
"Invalid logger type passed: '{}'".format(argument)
)
class Warn(LoggerEntry):
pass
class RoleUpdate(LoggerEntry):
pass
class Mute(LoggerEntry):
pass
class Unmute(LoggerEntry):
pass
class Kennel(LoggerEntry):
pass
class Unkennel(LoggerEntry):
pass
class JoinLeave(LoggerEntry):
pass
class CommandUsed(LoggerEntry):
pass
class Ban(LoggerEntry):
pass
class Unban(LoggerEntry):
pass
class Notify(LoggerEntry):
pass
<file_sep>/cogs/fun.py
import json
import random
from discord.ext import commands
from cogs.utils.modUtils import ModUtils
class FunMsgs:
def __init__(self):
with open("./jsons/fun_msgs.json", encoding='utf-8') as f:
msgs = json.load(f)
self.msgs = msgs
def get(self, param):
return self.msgs[param]
class Fun(commands.Cog):
def __init__(self, bot):
self.fun_msgs = FunMsgs()
self.bot = bot
self.owo_msg = self.fun_msgs.get("owo_msg")
self.nut = self.fun_msgs.get("nut")
self.seals = self.fun_msgs.get("seals")
self.quote_channel = ModUtils.get_channel('quote_channel')
@commands.command(description="What's this?")
async def owo(self, ctx):
""" What's this? """
author = ctx.author
await ctx.send(f"{author.mention},\n{self.owo_msg}")
@commands.command(description="█▀█ █▄█ ▀█▀")
async def bignut(self, ctx):
""" █▀█ █▄█ ▀█▀ """
await ctx.send(self.nut)
@commands.command(description="Prints random navy seal copypasta!")
async def seal(self, ctx):
""" Prints random navy seal copypasta! """
await ctx.send(random.choice(self.seals))
def setup(bot):
bot.add_cog(Fun(bot))
<file_sep>/cogs/random_msgs.py
import asyncio
import markovify as markov # we would be overriding this with our class if I didn't do this
from discord.ext import commands, tasks
from cogs.utils.modUtils import ModUtils
class Markovify(commands.Cog, ModUtils):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
self.msg_channel = self.get_channel('markovify_channel')
with open('./messages.txt', encoding='utf-8') as f:
self.msgs = f.read()
self.text_model = markov.NewlineText(self.msgs)
self.generate_messages.start()
@tasks.loop(seconds=1800.0)
async def generate_messages(self):
msg = self.text_model.make_sentence()
channel = self.bot.get_channel(self.msg_channel)
await channel.send(msg)
@generate_messages.before_loop
async def before_messages(self):
await self.bot.wait_until_ready()
@commands.command(description="Change cooldown of the markovify messages.")
async def change_cooldown(self, ctx, cooldown: int):
""" Change cooldown of the markovify messages. """
self.generate_messages.change_interval(seconds=cooldown)
await ctx.send("The cooldown has been changed to {}.".format(cooldown))
def setup(bot):
bot.add_cog(Markovify(bot))
<file_sep>/cogs/utils/modUtils.py
import asyncio
import datetime
import json
import math
import random
import re
from sqlite3 import OperationalError
import discord
from cogs.utils.database import Database
from cogs.utils.loggerEntry import LoggerEntry, RoleUpdate
class ModUtils:
""" Utils for the Moderator cog, to clean up that file. """
def __init__(self, bot):
"""
I would put all the channel IDs into a dict for their respective attrs and IDs but
I don't feel like dealing with instance errors
"""
self.bot = bot
self.pagination_amt = 5
self.scrape_channel = self.get_channel('scrape_channel')
self.kenneled_role = self.get_channel('kenneled_role')
self.muted_role = self.get_channel('muted_role')
self.log_channel = self.get_channel('log_channel')
self.error_channel = self.get_channel('error_channel')
self.kennel_channel = self.get_channel('kennel_channel')
self.joins_channel = self.get_channel('joins_channel')
self.starboard_channel = self.get_channel('starboard_channel')
self.ban_channel = self.get_channel('ban_channel')
self.unban_channel = self.get_channel('unban_channel')
self.db = Database('./dbs/moderator.db')
async def ensure_tables(self):
await self.db.ensure(
"""
CREATE TABLE IF NOT EXISTS muted
(user string,
role string,
UNIQUE(user, role))
""",
"""
CREATE TABLE IF NOT EXISTS warns
(id string,
user string,
issuer string,
reason string,
date timestamp DEFAULT CURRENT_TIMESTAMP)
""",
"""
CREATE TABLE IF NOT EXISTS kenneled
(user string,
role string,
UNIQUE(user, role))
"""
)
@property
def now(self):
return datetime.datetime.utcnow()
@staticmethod
def strptime(date):
return datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
@classmethod
def get_config(cls, file):
""" Fetch data from a configuration JSON file. """
with open(f'./jsons/{file}.json') as f:
config = json.load(f)
return config
@classmethod
def set_config(cls, file, param, value):
""" Edit data in a configuration JSON file. """
config = cls.get_config(file)
config[param] = value
with open(f'./jsons/{file}.json', 'w') as f:
json.dump(config, f, indent=4)
@classmethod
def get_channel(cls, param):
channels = cls.get_config('channels')
try:
channel = channels[param]
if channel is None:
raise KeyError
else:
return channel
except KeyError:
return channels['LoggerEntry_channel']
@classmethod
def get_role(cls, param):
roles = cls.get_config('roles')
return roles[param]
async def get_user(self, user_id):
user_id = int(user_id)
user = self.bot.get_user(user_id)
if user is None:
return await self.bot.fetch_user(user_id)
else:
return user
async def _edit_roles(self, ctx, role, user):
if role in user.roles:
reason = f'Changed roles for {user}, -{role.name}'
await user.remove_roles(
role,
reason=f'Role removal requested by {ctx.author}'
)
else:
reason = f'Changed roles for {user}, +{role.name}'
await user.add_roles(
role,
reason=f'Role add requested by {ctx.author}'
)
await self.log_entry(ctx, text=reason, entry_type=RoleUpdate, title='Role update')
async def paginate(self, msg, author, embed):
""" Paginate across an embed. """
emoji_list = ['⏪', '⬅️', '➡️', '⏩']
footer = embed.footer.text
pattern = re.compile(r'.*?(\d+).*?(\d+)')
match = pattern.match(footer)
page = int(match.group(1))
end = int(match.group(2))
for reaction in emoji_list:
await msg.add_reaction(reaction)
def check(r, u):
return u == author and r.emoji in emoji_list
try:
reaction, user = await self.bot.wait_for(
'reaction_add',
timeout=180.0,
check=check
)
await reaction.remove(author)
except asyncio.TimeoutError:
await msg.delete()
else:
if reaction.emoji == '⏪':
await self._paginate(*[msg, author, embed], 1)
elif reaction.emoji == '⬅️':
await self._paginate(*[msg, author, embed], page - 1)
elif reaction.emoji == '➡️':
await self._paginate(*[msg, author, embed], page + 1)
else:
await self._paginate(*[msg, author, embed], end)
async def _paginate(self, msg, author, embed, page):
total = math.ceil(len(embed.fields) / self.pagination_amt)
if (page > total) or (page == 0):
return await self.paginate(msg, author, embed)
else:
embed.set_footer(text=f"Page {page} of {total}")
_embed = embed.copy()
start = (page - 1) * self.pagination_amt
end = start + self.pagination_amt
em_dict = _embed.to_dict()
em_dict["fields"] = em_dict["fields"][start:end]
await msg.edit(embed=discord.Embed.from_dict(em_dict))
await self.paginate(msg, author, embed)
@LoggerEntry.converter
async def log_entry(self,
ctx,
*,
guild=None,
title=None,
description=None,
entry_type: LoggerEntry.check,
**kwargs):
""" Adds an entry to ProtoBot logs """
if guild is None:
guild = ctx.guild
color = guild.me.color
embed = discord.Embed(
title=title,
description=description,
color=color,
timestamp=self.now,
)
if entry_type:
embed.set_author(
name=f"New {entry_type()} Event Occurred:"
)
for k, v in kwargs.items():
# equivalent to "embed.set_{k}(v[key]=v[value])"
getattr(embed, k)(**v) # for example "embed.set_description(url=<url>)"
_channel = self.get_channel(entry_type().channel)
channel = guild.get_channel(int(_channel))
await channel.send(embed=embed)
async def generate_id(self):
""" Generates a random ID to use - Ensures no other entry has the same ID """
random_number = random.randint(0, 65536)
_id = str(hex(random_number))[2:]
if await self.id_exists(_id):
return await self.generate_id()
else:
return _id
async def id_exists(self, _id):
""" Checks if ID exists already in database. """
try:
return await self.db.search("warns", id=_id)
except OperationalError:
return False
async def fetch_user_warns(self, user):
"""
Fetches all warns under a specified user.
Parameters
------------
user: :class:`discord.Member`
The user to look up warns for
Returns
------------
params: [:class:`str`]
[ID, author, reason, date]
"""
return await self.db.getall(
"SELECT id, issuer, reason, date FROM warns WHERE user=?",
(user.id,)
)
async def fetch_warn(self, identifier):
"""
Fetches a warn using the specified ID.
Parameters
------------
identifier: :class:`int`
The ID to look for
Returns
------------
params: [:class:`str`]
[user, author, reason, date]
"""
return await self.db.get(
"SELECT user, issuer, reason, date FROM warns WHERE id=?",
(identifier,)
)
async def change_warn(self, identifier, reason):
"""
Change the reason of a warn using the specified ID.
Parameters
------------
identifier: :class:`int`
The ID to look for
reason: :class:`str`
The new reason to enter into the warn
Returns
------------
:class:`bool`
Whether the specified warn was found and edited.
"""
if await self.fetch_warn(identifier):
await self.db.execute(
"UPDATE warns SET reason=? WHERE id=?",
(reason, identifier)
)
return True
else:
return False
async def delete_warn(self, identifier):
"""
Deletes a warn using the specified ID.
Parameters
------------
identifier: :class:`int`
The ID to look for
Returns
------------
:class:`bool`
Whether the specified warn was deleted.
"""
before = bool(await self.fetch_warn(identifier))
await self.db.get(
"DELETE FROM warns WHERE id=?",
(identifier,)
)
after = bool(await self.fetch_warn(identifier))
if before == after:
return False
else:
return True
async def log_warn(self, identifier, user, author, reason):
"""
Logs a warn for the specified user.
Parameters
------------
identifier: :class:`str`
The warn ID to log it for
user: :class:`discord.Member`
The user to log the warn for
author: :class:`discord.Member`
The issuer of the warn
reason: :class:`str`
The reason to log
"""
await self.db.execute(
"INSERT INTO warns (id, user, issuer, reason) VALUES (?, ?, ?, ?)",
(identifier, user.id, author.id, reason)
)
async def is_kenneled(self, user):
"""
Check if the user is kenneled.
Parameters
------------
user: :class:`discord.Member`
The user to check for
Returns
------------
:class:`bool`
If the user is kenneled or not.
"""
return await self.db.search(
"kenneled", user=user.id
)
async def is_muted(self, user):
"""
Check if the user is muted.
Parameters
------------
user: :class:`discord.Member`
The user to check for
Returns
------------
:class:`bool`
If the user is muted or not.
"""
return await self.db.search(
"muted", user=user.id
)
async def add_kenneled(self, user, roles):
"""
Add this user to the kenneled database.
Parameters
-----------
user: :class:`discord.Member`
The user to add.
roles: [:class:`discord.Role`]
The role(s) to add.
"""
if len(roles) > 0:
await self.db.executemany(
"INSERT INTO kenneled (user, role) VALUES (?, ?)",
([(user.id, r.id) for r in roles])
)
else:
await self.db.execute(
"INSERT INTO kenneled (user, role) VALUES (?, ?)",
(user.id, 0)
)
async def add_muted(self, user, roles):
"""
Add this user to the muted database.
Parameters
-----------
user: :class:`discord.Member`
The user to add.
roles: [:class:`discord.Role`]
The role(s) to add.
"""
if len(roles) > 0:
await self.db.executemany(
"INSERT INTO muted (user, role) VALUES (?, ?)",
([(user.id, r.id) for r in roles])
)
else:
await self.db.execute(
"INSERT INTO muted (user, role) VALUES (?, ?)",
(user.id, 0)
)
async def remove_kenneled(self, user):
"""
Remove this user from the kenneled database.
Parameters
------------
user: :class:`discord.Member`
Returns
--------
[:class:`int`]
The roles to add back, if the user is kenneled.
:class:`NoneType`
If the user was not found to be kenneled.
"""
roles = await self.db.getall(
"SELECT role FROM kenneled WHERE user=?",
(user.id,)
)
await self.db.execute(
"DELETE FROM kenneled WHERE user=?",
(user.id,)
)
if roles:
return [r[0] for r in roles] # stupid sqlite returns a one-tuple for each row, soo
else:
return None
async def remove_muted(self, user):
"""
Remove this user from the muted database.
Parameters
------------
user: :class:`discord.Member`
Returns
--------
[:class:`int`]
The roles to add back, if the user is muted.
:class:`NoneType`
If the user was not found to be muted.
"""
roles = await self.db.getall(
"SELECT role FROM muted WHERE user=?",
(user.id,)
)
await self.db.execute(
"DELETE FROM muted WHERE user=?",
(user.id,)
)
if roles:
return [r[0] for r in roles] # stupid sqlite returns a one-tuple for each row, soo
else:
return None
async def get_kenneled_roles(self, user):
"""
Get current roles of kenneled user.
Parameters
------------
user: :class:`discord.Member`
Returns
--------
[:class:`int`]
The roles the user had.
:class:`NoneType`
If the user was not found to be kenneled.
"""
return await self.db.getall(
"SELECT role FROM kenneled WHERE user=?",
(user.id,)
)
async def get_muted_roles(self, user):
"""
Get current roles of muted user.
Parameters
------------
user: :class:`discord.Member`
Returns
--------
[:class:`int`]
The roles the user had.
:class:`NoneType`
If the user was not found to be muted.
"""
return await self.db.getall(
"SELECT role FROM muted WHERE user=?",
(user.id,)
)
<file_sep>/main.py
import json
import os
from discord.ext import commands
def get_prefix(bot, message):
guild = message.guild
with open("./jsons/prefixes.json") as f:
prefixes = json.load(f)
try:
return prefixes[str(guild.id)]
except KeyError:
set_prefix(message.guild, '$')
get_prefix(bot, message)
except AttributeError:
return "$"
def set_prefix(guild, prefix):
with open('./jsons/prefixes.json') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = prefix
with open('./jsons/prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
client = commands.Bot(command_prefix=get_prefix)
client.remove_command("help")
owners = [579413130506010654, 570405078498934796]
def is_owner():
async def predicate(ctx):
return ctx.author.id in owners
return commands.check(predicate)
@client.event
async def on_ready():
print(f"{client.user.name} is ready.")
for file in os.listdir("./cogs"):
if file.endswith(".py") and not file.startswith("_"):
print("Loading {}".format(file))
client.load_extension(f"cogs.{file[:-3]}")
with open('token.txt') as token:
client.run(token.read())
<file_sep>/cogs/utils/cExceptions.py
class MissingPermissions(Exception):
def __init__(self, msg):
super().__init__("You are missing the permission(s): {}.".format(msg))
class NoAccess(Exception):
def __init__(self, msg):
super().__init__("No access: {}".format(msg))
<file_sep>/cogs/mod.py
import json
import math
import datetime
import discord
from discord.ext import commands
from cogs.utils.cExceptions import *
from cogs.utils.loggerEntry import *
from cogs.utils.modUtils import ModUtils
from cogs.utils.database import Database
def is_user():
def pred(ctx):
if isinstance(ctx.channel, discord.DMChannel):
raise commands.NoPrivateMessage() # We assume any command with perms check can't be used in DMs
cmd = str(ctx.command)
cmd = "warn" if cmd == "warns" else cmd
author = ctx.author
user_roles = [r.id for r in author.roles]
with open('./jsons/permissions.json') as f:
perms = json.load(f)
try:
cmd_roles = perms[cmd]
except KeyError:
"""
If the cummand is not in the JSON file, assume everyone has access,
including standard members. (This is useful for fun commands, where
they do not modify the server in any way, and saves you time by not
writing them in the file.)
"""
return True
else:
"""
Else if the command *is* in the JSON file, and there is no blacklisted
roles specified, everyone who can access the bot in general (i.e.
moderators, etc.) can use it. But still not normal users. (This is good
for commands like ban, unban, or just cummands that you want anyone who
has access to the bot to use, but not *everyone* in the *server*.)
"""
# Check if the user is a moderator:
for r_id in user_roles:
if r_id in perms['moderator_role_ids']:
for _r_id in user_roles:
if _r_id in cmd_roles:
perms = f'"USE_{cmd.upper()}"'
raise MissingPermissions(perms)
return True
raise NoAccess(f"You are not authorized to use `{ctx.me.name}` at this time.")
return commands.check(pred)
class Moderator(commands.Cog, ModUtils):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
self.pagination_amt = 5
self.muted_role = self.get_role("muted_role")
self.kenneled_role = self.get_role("kenneled_role")
self.kenneled_channel = self.get_channel("kenneled_channel")
self.db = Database('./dbs/reminders.db')
async def add_reminder(self, author, channel, delta, message):
"""
Adds a reminder to the database.
Parameters
-----------
author: :class:`discord.Member`
The author of the reminder.
channel: :class:`discord.Channel`
The channel of the reminder.
delta: :class:`datetime.datetime`
The date to initiate the reminder.
message: :class:`str`
The message of the reminder.
"""
await self.db.execute(
"INSERT INTO reminders (author, channel, delta, message) "
"VALUES(?, ?, ?, ?)",
(author.id, channel.id, delta, message)
)
@commands.Cog.listener()
async def on_ready(self):
await self.ensure_tables()
@commands.command(description="Run SQL Queries.")
@commands.has_permissions(administrator=True)
async def run_sql(self, ctx, *, query):
""" Run SQL Queries. """
resp = await self.db.get(
query
)
await ctx.send("Response: {}".format(resp))
@commands.command(description="Change bot prefix.")
@is_user()
async def update_prefix(self, ctx, prefix):
""" Change bot prefix. """
with open('./jsons/prefixes.json') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('./jsons/prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@commands.command(description="Adds or removes roles specified to/from a user.")
@is_user()
async def role(self, ctx, user : discord.Member , *args):
"""Adds removes or toggles roles for a user"""
# parse roles to add or remove based on dyno syntax
roles = ' '.join(args)
roles = [r.strip() for r in roles.split(',')]
roles_mentioned = [r[1:].lower() for r in roles if r.startswith('+') or r.startswith('-')]
roles_mentioned += [r.lower() for r in roles if not (r.startswith('+') or r.startswith('-'))]
roles_mentioned = list(set(roles_mentioned))
roles_to_add = [r[1:].lower() for r in roles if r.startswith('+')]
roles_to_remove = [r[1:].lower() for r in roles if r.startswith('-')]
roles = [r.lower() for r in roles_mentioned if r.lower() not in roles_to_add or r.lower() not in roles_to_remove]
# get user, current roles
user_id = user.id
user_to_change = user
if user_to_change:
user_has = [r.name.lower() for r in user_to_change.roles]
roles_to_add += [r for r in roles if r.lower() not in user_has and r.lower() not in roles_to_add]
roles_to_remove += [r for r in roles if r.lower() in user_has and r.lower() not in roles_to_remove and r.lower() not in roles_to_add]
roles_to_add = [r for r in roles_to_add if r.lower() not in roles_to_remove]
failed_roles = []
msg = 'Made the following changes to ' + user_to_change.name + '#' + user_to_change.discriminator + ': '
add_roles = []
remove_roles = []
for role in roles_to_add:
role_to_add = discord.utils.find(lambda m: m.name.lower() == role, ctx.guild.roles)
if role_to_add and role_to_add < ctx.guild.me.top_role:
msg += '+' + role_to_add.name + ', '
add_roles.append(role_to_add)
else:
failed_roles.append(role)
for role in roles_to_remove:
role_to_remove = discord.utils.find(lambda m: m.name.lower() == role, ctx.guild.roles)
if role_to_remove and role_to_remove < ctx.guild.me.top_role:
msg += '-' + role_to_remove.name + ', '
remove_roles.append(role_to_remove)
else:
failed_roles.append(role)
try:
await user_to_change.add_roles(*add_roles)
await user_to_change.remove_roles(*remove_roles)
except discord.Forbidden:
await ctx.channel.send('I don\'t have the proper permissions!')
except discord.HTTPException:
await ctx.channel.send('Failed to change roles!')
else:
if not add_roles and not remove_roles:
await ctx.channel.send('No changes made!')
else:
if failed_roles:
msg = msg[:-2] + '\nFailed to change roles: ' + ', '.join(failed_roles)
else:
msg = msg[:-2]
await ctx.channel.send(msg)
logged_entry = f"{ctx.author.mention} used role command on {user_to_change.mention}"
await self.log_entry(
ctx,
description=logged_entry,
entry_type=RoleUpdate
)
@commands.command(description="Mute a user and remove all their roles.")
@is_user()
async def mute(self, ctx, user: discord.Member, *, reason="No reason given."):
""" Mute a user and remove all their roles. """
author = ctx.author
guild = ctx.guild
channel = ctx.channel
if await self.is_muted(user):
await ctx.send(
"That user is already muted!"
)
else:
muted = guild.get_role(self.muted_role)
user_roles = [
r for r in user.roles if r < guild.me.top_role
and not (r.is_default() or r.managed)
]
if len(user_roles) > 0:
await user.remove_roles(*user_roles, reason="Muting user...")
await self.add_muted(user, user_roles)
await user.add_roles(muted, reason=reason)
await channel.send('User muted! Set a reminder to remind you to unmute!')
identifier = await self.generate_id()
await self.log_warn(identifier, user, author, f"(Auto-warn: type `mute`) - {reason}")
try:
await user.send(
f"You were muted in **`{guild}`** for **`{reason}`**"
)
except discord.Forbidden:
pass
logged_entry = f"{author.mention} Muted {user.mention} for {reason}"
await self.log_entry(
ctx,
description=logged_entry,
entry_type=Mute
)
@commands.command(description="Kennel a user and remove all their roles.")
@is_user()
async def kennel(self, ctx, user: discord.Member, *, reason="No reason given."):
""" Kennel a user and remove all their roles. """
author = ctx.author
guild = ctx.guild
channel = ctx.channel
if await self.is_kenneled(user):
await ctx.send(
"That user is already kenneled!"
)
else:
kenneled = guild.get_role(self.kenneled_role)
user_roles = [
r for r in user.roles if r < guild.me.top_role
and not (r.is_default() or r.managed)
]
if len(user_roles) > 0:
await user.remove_roles(*user_roles, reason="Kenneling user...")
await self.add_kenneled(user, user_roles)
await user.add_roles(kenneled, reason=reason)
await channel.send('User kenneled! Set a reminder to remind you to unmute!')
identifier = await self.generate_id()
await self.log_warn(identifier, user, author, f"(Auto-warn: type `kennel`) - {reason}")
try:
await user.send(
f"You were kenneled in **`{guild}`** for **`{reason}`**\n"
f"Please check out the **<#{self.kenneled_channel}>** for more information."
)
except discord.Forbidden:
pass
logged_entry = f"{author.mention} kenneled {user.mention} for {reason}"
await self.log_entry(
ctx,
description=logged_entry,
entry_type=Kennel
)
@commands.command(description="Unmute a user and return all their roles.")
@is_user()
async def unmute(self, ctx, user: discord.Member, *, reason='No reason given.'):
""" Unmute a user and return all their roles. """
author = ctx.author
guild = ctx.guild
muted = guild.get_role(self.muted_role)
await user.remove_roles(muted)
if await self.is_muted(user):
_roles = await self.get_muted_roles(user) # Get role IDs from muted user
roles = [guild.get_role(r[0]) for r in _roles]
await self.remove_muted(user)
if any(roles):
await user.add_roles(*roles)
await ctx.send("Unmuted that user.")
try:
await user.send(f"You were unmuted in **`{guild}`**.")
except discord.Forbidden:
pass
await self.log_entry(
ctx,
description=f"**{author}** ({author.mention}) `unkenneled` **{user}** ({user.mention}).\n"
f"**Reason:** `{reason}`.",
entry_type=Unmute
)
else:
await ctx.send(f"{author.mention}, that user was not muted!")
@commands.command(description="Unkennel a user and return all of their roles.")
@is_user()
async def unkennel(self, ctx, user: discord.Member, *, reason='No reason given.'):
""" Unkennel a user and return all of their roles. """
author = ctx.author
guild = ctx.guild
kenneled = guild.get_role(self.kenneled_role)
await user.remove_roles(kenneled)
if await self.is_kenneled(user):
# Get role IDs from muted user
_roles = await self.get_kenneled_roles(user)
roles = [guild.get_role(r[0]) for r in _roles]
await self.remove_kenneled(user)
if any(roles):
await user.add_roles(*roles)
await ctx.send("Unkenneled that user.")
try:
await user.send(f"You were unkenneled in **`{guild}`**.")
except discord.Forbidden:
pass
logged_entry = f"`{author}` ({author.mention}) unkenneled `{user}` ({user.mention})\n`reason:` {reason}"
await self.log_entry(
ctx,
description=logged_entry,
entry_type=Unkennel
)
else:
await ctx.send(f"{author.mention}, that user was not kenneled!")
@commands.command(description="Shorthand version to `[p]warn getall (user)`. List all warns from a user.")
@is_user()
async def warns(self, ctx, user: discord.Member):
""" Shorthand version to `[p]warn getall (user)`. List all warns from a user. """
await self.getall(ctx, user)
@commands.group(description="Handles all warn-related commands. Type '[p]help warn' for more information.")
@is_user()
async def warn(self, ctx):
""" Handles all warn-related commands. """
if ctx.invoked_subcommand is None:
cmd = self.bot.get_command("warn add")
# Get new ctx since the old one had removed user param from params because it thinks that's the sub-command
new_ctx = await self.bot.get_context(ctx.message)
await cmd.invoke(new_ctx)
@warn.command(description="Adds a new warn to the user.")
async def add(self, ctx, user: discord.Member, *, reason='No reason given.'):
""" Adds a new warn to the user. """
author = ctx.author
guild = ctx.guild
identifier = await self.generate_id()
await self.log_warn(identifier, user, author, reason)
await ctx.send(
f"User {user.mention} was warned for {reason} and with a log ID of `{identifier}`."
)
try:
await user.send(
f"You were warned in **`{guild}`** for **`{reason}`**"
)
except discord.Forbidden:
pass
await self.log_entry(
ctx,
description=f"{author.mention} Warned {user.mention} for {reason}"
f" and with a log ID of `{identifier}`",
entry_type=Warn
)
@warn.command(aliases=['fetch', 'grab', 'list'], description="Get a warn via specified ID.")
async def get(self, ctx, identifier):
""" Get a warn via specified ID. """
ret = await self.fetch_warn(identifier)
if ret:
user_id, author_id, reason, date = ret
user = await self.get_user(user_id)
author = await self.get_user(author_id)
embed = discord.Embed(
title=f"Warn retrieved with ID of {identifier}:",
timestamp=self.strptime(date),
color=discord.Color(0xe62169)
)
embed.add_field(
name='User:',
value=f"{user.id} ({user.mention})",
inline=False
)
embed.add_field(
name='Reason:',
value=reason,
inline=False
)
embed.add_field(
name='Issuer:',
value=f"{author.id} ({author.mention})",
inline=False
)
embed.set_footer(
text="Warn issued on ->"
)
await ctx.send(embed=embed)
else:
await ctx.send(f"No warn found with ID {identifier}.")
@warn.command(aliases=['del', 'rem'], description="Delete a warn via specified ID.")
@commands.has_role(507601219041361929)
async def remove(self, ctx, identifier):
""" Delete a warn via specified ID. """
ret = await self.delete_warn(identifier)
if ret:
await ctx.send(f"Deleted the warn with ID {identifier}.")
else:
await ctx.send(f"No warn found with ID {identifier}.")
@warn.command(aliases=['change', 'cng'], description="Edit a specified warn's [reason].")
async def edit(self, ctx, identifier, *, reason):
""" Edit a specified warn's [reason]. """
ret = await self.change_warn(identifier, reason)
if ret:
await ctx.send(f"Edited warn `#{identifier}` to `{reason}`.")
else:
await ctx.send(f"No warn found with ID {identifier}.")
@warn.command(aliases=['fetchall', 'graball', 'listall'], description="List all warns of a user.")
async def getall(self, ctx, user: discord.Member):
""" List all warns of a user. """
warns = await self.fetch_user_warns(user)
author = None
embed = discord.Embed(
title=f'Fetching warns for `{user}`...',
description=f"{len(warns)} warns in total for this user.",
timestamp=self.now,
color=discord.Color(0xe62169)
)
for entry, warn in enumerate(warns):
warn_id, warn_author, warn_reason, warn_ts = warn
ts = self.strptime(warn_ts)
formatted = ts.strftime("%b %d, %Y at %I:%M:%S %p (UTC-0)")
author = await self.get_user(warn_author)
embed.add_field(
name=f'Entry #{entry + 1}:',
value=f"**`ID:`** #{warn_id}\n"
f"**`Issuer:`** {author.id} ({author.mention})\n"
f"**`Reason:`** {warn_reason}\n"
f"**`Occurred on:`** {formatted}",
inline=False
)
total = math.ceil(len(embed.fields) / self.pagination_amt)
embed.set_footer(text=f"Page 1 of {total}")
if len(embed.fields) > 0:
_embed = embed.copy()
_embed._fields = _embed._fields[:self.pagination_amt]
msg = await ctx.send(embed=_embed)
await self.paginate(msg, author, embed)
else:
await ctx.send(f"No warns were found for {user.mention}.")
@commands.command(description='Warn a user for a ToS/Rulebreaking pfp, status, or username. \n Valid types are nsfw, hitler, status, or name')
@is_user()
async def notify(self, ctx, type : str, user : discord.Member):
if type.lower() == 'nsfw' or type.lower() == 'pfp':
msg = 'We noticed you have a NSFW profile picture. We do not allow this as it violates Discord ToS. If you don\'' \
+ 't change it within 24 hours we will have no choice but to ban you from the server until you have a SFW '\
+ 'icon. Thanks for understanding ^^ - <@' + str(ctx.author.id) + '> at /r/yiff'
reason = 'NSFW pfp'
elif type.lower() == 'hitler':
msg = 'We noticed you have a rulebreaking profile picture. We do not allow this as it violates server rules on allowable images. If you don\'' \
+ 't change it within 24 hours we will have no choice but to ban you from the server until you have an acceptable ' \
+ 'icon. Thanks for understanding ^^ - <@' + str(ctx.author.id) + '> at /r/yiff'
reason = 'rulebreaking pfp'
elif type.lower() == 'status':
msg = 'We noticed you have a rulebreaking Discord status. We do not allow this as it violates server rules on allowable content. If you don\'' \
+ 't change it within 24 hours we will have no choice but to ban you from the server until you have an acceptable ' \
+ 'status. Thanks for understanding ^^ - <@' + str(ctx.author.id) + '> at /r/yiff'
reason = 'status'
elif type.lower() == 'name' or type.lower() == 'nickname' or type.lower() == 'nick':
msg = 'We noticed you have a rulebreaking Discord name or nickname. We do not allow this as it violates server rules on allowable content. If you don\'' \
+ 't change it within 24 hours we will have no choice but to ban you from the server until you have an acceptable ' \
+ 'name or nickname. Thanks for understanding ^^ - <@' + str(ctx.author.id) + '> at /r/yiff'
reason = 'name/nickname'
else:
await ctx.channel.send('Invalid warn type given! Try one of these: `nsfw`, `hitler`, `status`, `name`, `custom`!')
return
try:
await user.send(msg)
except (discord.HTTPException, discord.Forbidden):
await ctx.channel.send('Could not send DM!')
else:
await ctx.channel.send('User ' + user.name + '#' + user.discriminator + ' notified!')
embed_text = '<@' + str(
ctx.author.id) + '> ' + ctx.author.name + '#' + ctx.author.discriminator + ' used `$notify` command on <@'\
+ str(user.id) + '> ' + user.name + '#' + user.discriminator + '\nReason: ' + reason
await self.log_entry(
ctx,
description=embed_text,
entry_type=Notify
)
reminder_text = 'Check on <@' + str(user.id) + '>\'s ' + reason + '!'
dt_td = datetime.timedelta(seconds=86400)
delta = self.now + dt_td
await self.add_reminder(
ctx.author,
ctx.channel,
delta.replace(microsecond=0),
reminder_text
)
await ctx.channel.send('Reminder added!')
@commands.command(description="Ban the specified user")
@is_user()
async def ban(self, ctx, user : str, *args):
if user.startswith('<'):
user = await self.bot.fetch_user(int(user[1:-2]))
else:
user = await self.bot.fetch_user(int(user))
reason = ' '.join(args)
if not reason:
reason = "No reason given!"
await ctx.guild.ban(user, reason=reason)
await ctx.send(f"{user.mention} banned!")
@commands.command(description="Unban the specified user")
@is_user()
async def unban(self, ctx, user):
banned_users = await ctx.guild.bans()
for ban_entry in banned_users:
banned_user = ban_entry.user
if user == banned_user.id or user == banned_user.mention:
await ctx.guild.unban(banned_user)
await ctx.send(f"{banned_user.mention} unbanned!")
def setup(bot):
bot.add_cog(Moderator(bot))
<file_sep>/cogs/reminders.py
import datetime
import re
import discord
from discord.ext import commands, tasks
from cogs.utils.database import Database
from cogs.utils.modUtils import ModUtils
class Reminders(commands.Cog, ModUtils):
def __init__(self, bot):
super().__init__(bot)
self.bot = bot
self.db = Database('./dbs/reminders.db')
self.check_reminders.start()
@staticmethod
def get_unit(param):
params = {
"w": "weeks",
"d": "days",
"h": "hours",
"m": "minutes",
"s": "seconds"
}
return params[param]
@commands.Cog.listener()
async def on_ready(self):
await self.db.ensure(
"""
CREATE TABLE IF NOT EXISTS reminders
(author string,
channel string,
delta timestamp,
message string,
UNIQUE(author, channel, delta, message))
"""
)
@tasks.loop(seconds=5.0)
async def check_reminders(self):
for r in await self.db.execute("SELECT * FROM reminders"):
author, channel, delta, message = r
if self.strptime(delta) <= self.now:
await self._remind(int(author), int(channel), message)
@check_reminders.before_loop
async def before_check(self):
await self.bot.wait_until_ready()
async def _remind(self, author_id, channel_id, message):
author = await self.get_user(author_id)
channel = self.bot.get_channel(channel_id)
if channel is None:
channel = await self.bot.fetch_channel(channel_id)
embed = discord.Embed(
title="New Reminder!",
description=f"{author.mention}, you have a new reminder:",
timestamp=self.now,
color=discord.Color(0xe62169)
)
embed.add_field(
name="Reminder:",
value=f'"{message}"'
)
await channel.send(content=author.mention, embed=embed)
await self.del_reminder(author, message)
async def del_reminder(self, author, message):
"""
Removes a reminder from the database.
Parameters
-----------
author: :class:`discord.Member`
The author of the reminder.
message: :class:`str`
The message of the reminder.
"""
await self.db.execute(
"DELETE FROM reminders WHERE author=? AND message=?",
(author.id, message)
)
async def add_reminder(self, author, channel, delta, message):
"""
Adds a reminder to the database.
Parameters
-----------
author: :class:`discord.Member`
The author of the reminder.
channel: :class:`discord.Channel`
The channel of the reminder.
delta: :class:`datetime.datetime`
The date to initiate the reminder.
message: :class:`str`
The message of the reminder.
"""
await self.db.execute(
"INSERT INTO reminders (author, channel, delta, message) "
"VALUES(?, ?, ?, ?)",
(author.id, channel.id, delta, message)
)
@commands.command(aliases=['add_reminder', 'remind_me', 'reminder'], description="Set up a new reminder for yourself.")
async def remind(self, ctx, *, message):
""" Set up a new reminder for yourself. """
v_pattern = re.compile(r'(in.?)(\d+)')
value = [v.group(2) for v in v_pattern.finditer(message)][0]
u_pattern = re.compile(r'([A-Za-z])([A-Za-z])*$')
unit_initial = [v.group(1) for v in u_pattern.finditer(message)][0]
unit = self.get_unit(unit_initial)
dt_td = datetime.timedelta(**{unit: int(value)})
delta = self.now + dt_td
message = message \
.replace([v.group(0) for v in v_pattern.finditer(message)][0], "") \
.replace(unit_initial, "") \
.strip()
await self.add_reminder(
ctx.author,
ctx.channel,
delta.replace(microsecond=0),
message
)
await ctx.send(
"Reminder set. I will remind you in {} {} about {}.".format(value, unit, message)
)
def setup(bot):
bot.add_cog(Reminders(bot))
<file_sep>/cogs/misc.py
import datetime
import discord
from discord.ext import commands
from cogs.mod import is_user
class Misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot_version = '3.0.0'
@commands.command(description="Check client websocket connection latency.")
@is_user()
async def ping(self, ctx):
""" Check client websocket connection latency. """
latency = self.bot.latency
embed = discord.Embed(
title='Ping!',
description='{}ms'.format(round(latency * 1000)),
timestamp=datetime.datetime.utcnow(),
color=discord.Color(0xe62169)
)
await ctx.send(embed=embed)
@commands.command(description="Check current bot version.")
@is_user()
async def version(self, ctx):
""" Check current bot version. """
await ctx.send(
f'I am currently running on ProtoBot version {self.bot_version}'
) # *tuple(sys.version_info)[:2]
def setup(bot):
bot.add_cog(Misc(bot))
<file_sep>/cogs/utils/database.py
import asyncio
import cogs.utils.asqlite as asqlite
class Database:
def __init__(self, connection):
self.loop = asyncio.get_event_loop()
self.conn = self.loop.run_until_complete(asqlite.connect(connection))
self.cursor = self.conn.cursor()
async def ensure(self, *statements):
""" Ensures tables exist, etc. """
for s in statements:
await self.execute(s)
async def search(self, table, **kwargs):
"""
Search for if a data pair exists in inputted table. Returns boolean of if found.
"""
clauses = " AND ".join([f"{k} = {v}" for k, v in kwargs.items()])
return await self.get(
f"SELECT * FROM {table} WHERE {clauses}"
)
async def get(self, resp, args=()):
"""
Selects 1 row matching provided resp and optional args.
Returns value if len(row) == 1 else :class:`tuple`(*args)
Returns None if none found.
"""
async with self.cursor as c:
await c.execute(resp, args)
row = await c.fetchone()
if row:
_row = tuple(row)
return _row[0] if len(_row) == 1 else _row
else:
return None
async def getall(self, resp, args=()):
"""
Generator for all rows matching provided response and optional args.
Returns a :class:`list` of all entires, or `None` if nothing found.
"""
async with self.cursor as c:
await c.execute(resp, args)
rows = await c.fetchall()
if rows:
return [tuple(r) for r in rows]
else:
return None
async def execute(self, resp, args=()):
""" Modifies data in rows, and returns any returned rows. """
async with self.cursor as c:
await c.execute(resp, args)
return await c.fetchall()
async def executemany(self, resp, args=[()]):
""" Modifies data using `executemany`, and returns any returned rows. """
async with self.cursor as c:
await c.executemany(resp, args)
return await c.fetchall()
<file_sep>/README.md
# ProtoBot
Proto Bot for our discord server
# Commands
(default prefix is $)
$version : prints current bot version
$ping : pong!
$help : prints help message
$owo : what's this?
$bignut : █▀█ █▄█ ▀█▀
$reminder [duration in seconds] [message] : sends a reminder after the given number of seconds
$log [channel] [optional: month] : generates csv file for given channel and given month, or latest full month if none specified
$updateprefix [new_prefix] : changes prefix to given prefix (max 3 characters)
protobot reset prefix : reset prefix to default<file_sep>/cogs/ErrorHandling.py
import math
import sys
import traceback
import discord
from discord.ext import commands
from discord.ext.commands.errors import *
from cogs import mod
class ErrorHandling(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
cmd = ctx.command
if hasattr(cmd, 'on_error'):
return
error = getattr(error, 'original', error)
if isinstance(error, CommandNotFound):
return
elif isinstance(error, mod.MissingPermissions) or isinstance(error, mod.NoAccess):
await ctx.send(f"Error in command: `{cmd}`:\n```{error}```")
elif isinstance(error, CheckFailure):
if isinstance(error, NSFWChannelRequired):
await ctx.send(f'Error in command `{cmd}`:\n```{error}```')
if not isinstance(ctx.channel, discord.DMChannel):
await ctx.message.delete()
elif isinstance(error, PrivateMessageOnly) or isinstance(error, NoPrivateMessage) or isinstance(error,
commands.BotMissingPermissions):
await ctx.send(f'Error in command `{cmd}`:\n```{error}```')
else:
return
elif isinstance(error, CommandOnCooldown):
cooldown = cooldown_formatter(error.retry_after)
await ctx.send(f"You must wait {cooldown} before you can use the command ``{cmd}`` again.")
elif isinstance(error, commands.UserInputError):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send_help(cmd)
else:
await ctx.send(f'Error in command `{cmd}`:\n```{type(error).__name__}: {error}```')
else:
print(f'>>> Occurred in {ctx.guild}, in {ctx.channel} by user {ctx.author}')
await ctx.send(f'Error in command `{cmd}`:\n```{type(error).__name__}: {error}```')
print('Ignoring exception in command {}:'.format(cmd), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
# Cooldown formatter
def cooldown_formatter(cooldown):
cooldown = round(cooldown)
days = math.floor(cooldown / 86400)
hours = math.floor(cooldown / 3600) - (days * 24)
minutes = math.floor(cooldown / 60) - (hours * 60) - (days * 24 * 60)
seconds = cooldown - (minutes * 60) - (hours * 3600) - (days * 86400)
dt = date_string(days, 'day')
ht = date_string(hours, 'hour')
mt = date_string(minutes, 'minute')
st = date_string(seconds, 'second')
times_before = [dt, ht, mt, st]
times_after = []
for time_unit in times_before:
if time_unit == '':
continue
else:
times_after.append(time_unit)
if len(times_after) == 1:
return times_after[0]
else:
beginning = ' '.join(times_after[:-1])
end = f'and {times_after[-1]}'
return f'{beginning} {end}'
# Date string
def date_string(time, unit):
time = int(time)
if time == 1:
if unit == 'second':
return f'1 {unit}'
else:
return f'1 {unit},'
elif time == 0:
return ''
else:
if unit == 'second':
return f'{time} {unit}s'
return f'{time} {unit}s,'
def setup(bot):
bot.add_cog(ErrorHandling(bot))<file_sep>/cogs/help.py
import datetime
import discord
from didyoumean import didyoumean as dym
from discord.ext import commands
from cogs import mod
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.biscuit = 570405078498934796
self.tauxxy = 579413130506010654
self.uptime = datetime.datetime.utcnow()
@commands.command(description="See what commands you have access to.")
async def help(self, ctx, command=None):
""" See what commands you have access to. """
bot = self.bot
author = ctx.author
prefix = ctx.prefix
if not command:
embed = discord.Embed(
title=f'Type help {prefix}<command> if you would like more info on a command!',
description=(
'This bot was originally made by <@{}>, '
'And improved on by <@{}>!'.format(self.biscuit, self.tauxxy)
),
color=discord.Color(0xe62169),
timestamp=datetime.datetime.utcnow()
)
embed.set_author(name=author.display_name, icon_url=author.avatar_url)
final_cmds = {}
for (cog) in bot.cogs:
final_cmds[str(cog)] = []
for command in bot.get_cog(cog).walk_commands():
if command not in final_cmds[str(cog)]:
if command.parent:
continue
try:
await command.can_run(ctx)
except (mod.MissingPermissions, mod.NoAccess):
continue
else:
final_cmds[str(cog)].append(command)
for cog, cmds in final_cmds.items():
if len(cmds) > 0:
embed.add_field(
name=f"**{cog}:**",
value="\n".join(f"`{c.qualified_name}:` *{c.description}*" for c in cmds)
)
await ctx.send(embed=embed)
else:
command = bot.get_command(command)
try:
if command.commands:
new_line = "\n"
cmds = f'{new_line}'.join([f' {v}' for v in command.commands])
to_send = [
command.description,
help_formatter(command, command.clean_params),
f"Sub-commands:\n{cmds}",
'Type "[p]help <command>" for more info on a specific command or sub command.'
'i.e. "[p]help warn add" for help on the "add" sub-command of "warn".'
]
await ctx.send(f"```{f'{new_line}{new_line}'.join(to_send)}```")
else:
help_msg = help_formatter(command, command.clean_params)
desc = '```Description: {}```'.format(command.description)
await ctx.send(f"```{help_msg}``` {desc}")
except AttributeError:
dym.threshold = 1
output = dym.didYouMean(command, (c.name.replace('_', '') for c in bot.commands if not c.hidden))
await ctx.send(f"That is not a valid command! Did you mean {output}?")
# Help formatter
def help_formatter(cmd, cmd_params):
params = []
for key, value in cmd_params.items():
if str(value).count('=None') == 0:
params.append(key.replace('_and_', '+').replace('_or_', '/').replace('_', ''))
else:
params.append(f"(Optional: {key.replace('_and_', '+').replace('_or_', '/').replace('_', '')})")
if len(params) > 0:
return 'Usage: [p]{} <{}>'.format(cmd, '> <'.join(params))
else:
return 'Usage: [p]{}'.format(cmd)
def setup(bot):
bot.add_cog(Help(bot))
| 0c4f1aa926896677bf548037fa28736c7d5c13c5 | [
"Markdown",
"Python"
] | 14 | Python | biscuitderg/ProtoBot | 8d754a826ff8268d1aba2303b1a0f92d53fb5ce6 | a6b5d3a1fc7d7a69be0f5ec6941a1dc1d0b0fa7a |
refs/heads/master | <repo_name>lucaslima18/DownFy<file_sep>/settings.py
import argparse
parser = argparse.ArgumentParser(description="")
parser.add_argument("--link", required=False,default="", type=str)
parser.add_argument("--service", required=True, type=str)
arguments = parser.parse_args()
SERVICE = arguments.service
LINK = arguments.link
if (
arguments.service == "playlist"
or arguments.service == "albun"
or arguments.service == "music"
):
SERVICE_TYPE = arguments.service
else:
#deixar textos mais completos aqui
print("\nThis option is not avaliable, please reload and try one of this options:\n")
print("playlist\nalbun\nmusic\n")
exit()<file_sep>/main.py
import sys, os
from settings import *
from functions import *
client_id = ''
client_secret = ''
os.system(f"export SPOTIPY_CLIENT_ID={client_id}")
os.system(f"export SPOTIPY_CLIENT_SECRET={client_secret}")
service = SERVICE
link = LINK
if service == 'playlist':
getPlaylist(link)
elif service == 'albun':
pass
elif service == 'music':
searchMiusic()
<file_sep>/README.md
# DownFy
An Python project to download miusics and spotfy playlist/albuns.
<file_sep>/functions.py
from __future__ import unicode_literals
import spotipy, youtube_dl, json
from spotipy.oauth2 import SpotifyClientCredentials
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
def searchMiusic():
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'playlistend': 1,
'writethumbnail': True,
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
nome = input('Give your music name:')
try:
ydl.download([f'https://www.youtube.com/results?search_query={nome}'])
except:
print("One problem happen! sorry...")
def catchPlaylistMiusic():
for line in f:
print(line)
def getAlbum(link):
urn = 'spotify:album:6GzqMW6Tq0drVxlBUvivzd'
album = sp.album_tracks(urn)
print(album)
def getPlaylist(link):
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'playlistend': 1,
'writethumbnail': True,
}
music_count = 0
playlist = sp.playlist(link, None, None)
total = playlist['tracks']['total']
print(f"Start Download the playlist: {playlist['name']} de {playlist['owner']['display_name']}...\n")
for item in playlist['tracks']['items']:
music_count = music_count + 1
artists = item['track']['album']['artists'][0]['name']
item = item['track']['name']
music = f'{item}, {artists}'
print(f"Downloading({music_count}/{total}): {item}, {artists}...")
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
try:
ydl.download([f'https://www.youtube.com/results?search_query={music}'])
except:
print("One problem happen! sorry...")
print("\n") | a106346c3b9389b8738f8975f04bc7fc81deb255 | [
"Markdown",
"Python"
] | 4 | Python | lucaslima18/DownFy | b46648c45c933c2a27e95875c0a44e41285a8ee3 | a2a4715c980fb05996cd796b48f77e07fafb9ae7 |
refs/heads/master | <file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <iostream>
#include <glm/ext.hpp>
#include <imgui.h>
#include "Gfx_demo.h"
#include "util.h"
using namespace std;
using namespace glm;
using namespace Sc_lib;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
struct Imgui_info {
vec2 translation;
vec2 scale;
};
//----------------------------------------------------------------------------------------------------------------------
struct Matrix_info {
mat4 model;
mat4 view;
mat4 projection;
mat4 mv;
mat4 mvp;
mat4 normal;
};
//----------------------------------------------------------------------------------------------------------------------
struct Light_info {
vec4 translation;
vec4 ambient;
vec4 diffuse;
vec4 specular;
};
//----------------------------------------------------------------------------------------------------------------------
struct Material_info {
vec4 ambient;
vec4 diffuse;
vec3 specular;
float shininess;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace
//----------------------------------------------------------------------------------------------------------------------
Gfx_demo::Gfx_demo() :
cfgs_ {}
{
init_cfgs_();
init_device_();
init_light_resources_();
}
//----------------------------------------------------------------------------------------------------------------------
Gfx_demo::~Gfx_demo()
{
device_->wait_idle();
fini_imgui_();
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::connect(Platform_lib::Window* window)
{
init_swap_chain_(window);
init_cmd_buffer_();
init_fence_();
init_imgui_();
init_imgui_resources_();
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::render()
{
if (!fence_->signaled())
fence_->wait_signal();
fence_->reset();
cmd_buffer_->reset();
record_light_render_pass_();
record_present_render_pass_();
cmd_buffer_->end();
device_->submit(cmd_buffer_.get(), fence_.get());
swap_chain_->present();
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::touch_down()
{
ImGui::GetIO().MouseDown[0] = true;
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::touch_move(float x, float y)
{
ImGui::GetIO().MousePos = {x, y};
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::touch_up()
{
ImGui::GetIO().MouseDown[0] = false;
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_cfgs_()
{
cfgs_.cube.rotation.x = 45.0f;
cfgs_.cube.rotation.y = 45.0f;
cfgs_.cube.ambient = {0.135f, 0.2225f, 0.1575f};
cfgs_.cube.diffuse = {0.54f, 0.89f, 0.63f};
cfgs_.cube.specular = {0.316228f, 0.316228f, 0.316228f};
cfgs_.cube.shininess = 0.1f * 128.0f;
cfgs_.torus.translation = {1.75f, 0.0f, 0.0f};
cfgs_.torus.rotation.x = 125.0f;
cfgs_.torus.rotation.y = 45.0f;
cfgs_.torus.style = 1;
cfgs_.torus.ambient = {0.19225f, 0.19225f, 0.19225f};
cfgs_.torus.diffuse = {0.50754f, 0.50754f, 0.50754f};
cfgs_.torus.specular = {0.508273f, 0.508273f, 0.508273f};
cfgs_.torus.shininess = 0.4f * 128.0f;
cfgs_.sphere.translation = {-1.75f, 0.0f, 0.0f};
cfgs_.sphere.style = 2;
cfgs_.sphere.ambient = {0.24725f, 0.1995f, 0.0745f};
cfgs_.sphere.diffuse = {0.75164f, 0.60648f, 0.22648f};
cfgs_.sphere.specular = {0.628281f, 0.555802f, 0.366065f};
cfgs_.sphere.shininess = 0.4f * 128.0f;
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_device_()
{
try {
device_ = Device::create();
}
catch(exception& e) {
throw runtime_error("fail to create a demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_light_resources_()
{
Plane plane {1.0f, 1.0f};
try {
Buffer_desc buffer_desc;
buffer_desc.data = &plane.vertices[0];
buffer_desc.size = sizeof(Vertex) * plane.vertices.size();
buffers_["plane_vertex"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.data = &plane.indices[0];
buffer_desc.size = sizeof(uint16_t) * plane.indices.size();
buffers_["plane_index"] = device_->create(buffer_desc);
draw_counts_["plane"] = plane.indices.size();
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
Cube cube {1.0f};
try {
Buffer_desc buffer_desc;
buffer_desc.data = &cube.vertices[0];
buffer_desc.size = sizeof(Vertex) * cube.vertices.size();
buffers_["cube_vertex"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.data = &cube.indices[0];
buffer_desc.size = sizeof(uint16_t) * cube.indices.size();
buffers_["cube_index"] = device_->create(buffer_desc);
draw_counts_["cube"] = cube.indices.size();
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
Torus torus {0.3f, 0.6f, 64, 64};
try {
Buffer_desc buffer_desc;
buffer_desc.data = &torus.vertices[0];
buffer_desc.size = sizeof(Vertex) * torus.vertices.size();
buffers_["torus_vertex"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.data = &torus.indices[0];
buffer_desc.size = sizeof(uint16_t) * torus.indices.size();
buffers_["torus_index"] = device_->create(buffer_desc);
draw_counts_["torus"] = torus.indices.size();
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
Sphere sphere {0.7f, 64, 64};
try {
Buffer_desc buffer_desc;
buffer_desc.data = &sphere.vertices[0];
buffer_desc.size = sizeof(Vertex) * sphere.vertices.size();
buffers_["sphere_vertex"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.data = &sphere.indices[0];
buffer_desc.size = sizeof(uint16_t) * sphere.indices.size();
buffers_["sphere_index"] = device_->create(buffer_desc);
draw_counts_["sphere"] = sphere.indices.size();
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.size = align_pow2(sizeof(Matrix_info), 256) * 7;
buffers_["matrix_info"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.size = sizeof(Light_info);
buffers_["light_info"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc buffer_desc;
buffer_desc.size = align_pow2(sizeof(Material_info), 256) * 7;
buffers_["material_info"] = device_->create(buffer_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Image_desc image_desc;
image_desc.format = Format::rgba8_unorm;
image_desc.extent = {1280, 720, 1};
auto light_image = device_->create(image_desc);
images_["light_color"] = move(light_image);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Image_desc desc;
desc.format = Format::d24_unorm_s8_uint;
desc.extent = {1280, 720, 1};
images_["light_depth_stencil"] = device_->create(desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Sampler_desc desc;
samplers_["light_linear"] = device_->create(desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/lamp.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/lamp.frag"
#else
"../../../gfx/res/shader/lamp.vert",
"../../../gfx/res/shader/lamp.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_input = torus.vertex_input;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.depth_stencil.depth_test = true;
pipeline_desc.fragment_shader = shaders[1].get();
pipeline_desc.output_merger.color_formats[0] = Format::rgba8_unorm;
pipeline_desc.output_merger.depth_stencil_format = Format::d24_unorm_s8_uint;
pipelines_["lamp"] = device_->create(pipeline_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/flat.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/flat.frag"
#else
"../../../gfx/res/shader/flat.vert",
"../../../gfx/res/shader/flat.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_input = torus.vertex_input;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.depth_stencil.depth_test = true;
pipeline_desc.fragment_shader = shaders[1].get();
pipeline_desc.output_merger.color_formats[0] = Format::rgba8_unorm;
pipeline_desc.output_merger.depth_stencil_format = Format::d24_unorm_s8_uint;
pipelines_["flat"] = device_->create(pipeline_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/gouraud.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/gouraud.frag"
#else
"../../../gfx/res/shader/gouraud.vert",
"../../../gfx/res/shader/gouraud.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_input = torus.vertex_input;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.depth_stencil.depth_test = true;
pipeline_desc.fragment_shader = shaders[1].get();
pipeline_desc.output_merger.color_formats[0] = Format::rgba8_unorm;
pipeline_desc.output_merger.depth_stencil_format = Format::d24_unorm_s8_uint;
pipelines_["gouraud"] = device_->create(pipeline_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/phong.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/phong.frag"
#else
"../../../gfx/res/shader/phong.vert",
"../../../gfx/res/shader/phong.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_input = torus.vertex_input;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.depth_stencil.depth_test = true;
pipeline_desc.fragment_shader = shaders[1].get();
pipeline_desc.output_merger.color_formats[0] = Format::rgba8_unorm;
pipeline_desc.output_merger.depth_stencil_format = Format::d24_unorm_s8_uint;
pipelines_["phong"] = device_->create(pipeline_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::record_light_render_pass_()
{
auto light_info = reinterpret_cast<Light_info*>(buffers_["light_info"]->map());
light_info->translation = {cfgs_.light.translation, 1.0};
light_info->ambient = {cfgs_.light.ambient, 1.0};
light_info->diffuse = {cfgs_.light.diffuse, 1.0};
light_info->specular = {cfgs_.light.specular, 1.0};
auto view = lookAt(cfgs_.camera.translation, {0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f});
auto projection = perspective(radians(cfgs_.camera.fov),
cfgs_.camera.aspect,
cfgs_.camera.near, cfgs_.camera.far);
buffers_["light_info"]->unmap();
auto matrix_info_contents = static_cast<uint8_t*>(buffers_["matrix_info"]->map());
// update light matrix info.
auto lamp_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents);
lamp_matrix_info->model = translate(mat4 {1.0}, cfgs_.light.translation);
lamp_matrix_info->model = scale(lamp_matrix_info->model, {0.2f, 0.2f, 0.2f});
lamp_matrix_info->view = view;
lamp_matrix_info->projection = projection;
lamp_matrix_info->mv = view * lamp_matrix_info->model;
lamp_matrix_info->mvp = projection * lamp_matrix_info->mv;
lamp_matrix_info->normal = inverse(transpose(lamp_matrix_info->mv));
auto bottom_plane_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents + 512 * 2);
bottom_plane_matrix_info->model = translate(mat4 {1.0}, {0.0f, -1.0f, 0.0f});
bottom_plane_matrix_info->model = rotate(bottom_plane_matrix_info->model, radians(-90.0f), {1.0f, 0.0f, 0.0f});
bottom_plane_matrix_info->model = scale(bottom_plane_matrix_info->model, {10.0f, 10.0f, 1.0f});
bottom_plane_matrix_info->view = view;
bottom_plane_matrix_info->projection = projection;
bottom_plane_matrix_info->mv = view * bottom_plane_matrix_info->model;
bottom_plane_matrix_info->mvp = projection * bottom_plane_matrix_info->mv;
bottom_plane_matrix_info->normal = inverse(transpose(bottom_plane_matrix_info->mv));
auto far_plane_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents + 512 * 3);
far_plane_matrix_info->model = translate(mat4 {1.0}, {0.0f, 4.0f, -5.0f});
far_plane_matrix_info->model = scale(far_plane_matrix_info->model, {10.0f, 10.0f, 1.0f});
far_plane_matrix_info->view = view;
far_plane_matrix_info->projection = projection;
far_plane_matrix_info->mv = view * far_plane_matrix_info->model;
far_plane_matrix_info->mvp = projection * far_plane_matrix_info->mv;
far_plane_matrix_info->normal = inverse(transpose(far_plane_matrix_info->mv));
// update cube matrix info.
auto cube_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents + 512 * 4);
if (cfgs_.cube.animation)
cfgs_.cube.rotation.z += 1.0f;
cube_matrix_info->model = translate(mat4 {1.0}, cfgs_.cube.translation);
cube_matrix_info->model = rotate(cube_matrix_info->model, radians(cfgs_.cube.rotation.x), {1.0f, 0.0f, 0.0f});
cube_matrix_info->model = rotate(cube_matrix_info->model, radians(cfgs_.cube.rotation.y), {0.0f, 1.0f, 0.0f});
cube_matrix_info->model = rotate(cube_matrix_info->model, radians(cfgs_.cube.rotation.z), {0.0f, 0.0f, 1.0f});
cube_matrix_info->model = scale(cube_matrix_info->model, cfgs_.cube.scale);
cube_matrix_info->view = view;
cube_matrix_info->projection = projection;
cube_matrix_info->mv = view * cube_matrix_info->model;
cube_matrix_info->mvp = projection * cube_matrix_info->mv;
cube_matrix_info->normal = inverse(transpose(cube_matrix_info->mv));
// update torus matrix info.
auto torus_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents + 512 * 5);
if (cfgs_.torus.animation)
cfgs_.torus.rotation.y += 1.0f;
torus_matrix_info->model = translate(mat4 {1.0}, cfgs_.torus.translation);
torus_matrix_info->model = rotate(torus_matrix_info->model, radians(cfgs_.torus.rotation.x), {1.0f, 0.0f, 0.0f});
torus_matrix_info->model = rotate(torus_matrix_info->model, radians(cfgs_.torus.rotation.y), {0.0f, 1.0f, 0.0f});
torus_matrix_info->model = rotate(torus_matrix_info->model, radians(cfgs_.torus.rotation.z), {0.0f, 0.0f, 1.0f});
torus_matrix_info->model = scale(torus_matrix_info->model, cfgs_.torus.scale);
torus_matrix_info->view = view;
torus_matrix_info->projection = projection;
torus_matrix_info->mv = view * torus_matrix_info->model;
torus_matrix_info->mvp = projection * torus_matrix_info->mv;
torus_matrix_info->normal = inverse(transpose(torus_matrix_info->mv));
// update torus matrix info.
auto sphere_matrix_info = reinterpret_cast<Matrix_info*>(matrix_info_contents + 512 * 6);
if (cfgs_.sphere.animation)
cfgs_.sphere.rotation.z += 1.0f;
sphere_matrix_info->model = translate(mat4 {1.0}, cfgs_.sphere.translation);
sphere_matrix_info->model = rotate(sphere_matrix_info->model, radians(cfgs_.sphere.rotation.x), {1.0f, 0.0f, 0.0f});
sphere_matrix_info->model = rotate(sphere_matrix_info->model, radians(cfgs_.sphere.rotation.y), {0.0f, 1.0f, 0.0f});
sphere_matrix_info->model = rotate(sphere_matrix_info->model, radians(cfgs_.sphere.rotation.z), {0.0f, 0.0f, 1.0f});
sphere_matrix_info->model = scale(sphere_matrix_info->model, cfgs_.sphere.scale);
sphere_matrix_info->view = view;
sphere_matrix_info->projection = projection;
sphere_matrix_info->mv = view * sphere_matrix_info->model;
sphere_matrix_info->mvp = projection * sphere_matrix_info->mv;
sphere_matrix_info->normal = inverse(transpose(sphere_matrix_info->mv));
buffers_["matrix_info"]->unmap();
auto material_info_contents = reinterpret_cast<uint8_t*>(buffers_["material_info"]->map());
auto bottom_plane_material_info = reinterpret_cast<Material_info*>(material_info_contents + 256 * 2);
bottom_plane_material_info->ambient = {0.2125f, 0.1275f, 0.054f, 0.0f};
bottom_plane_material_info->diffuse = {0.714f, 0.4284f, 0.18144f, 0.0f};
bottom_plane_material_info->specular = {0.393548f, 0.271906f, 0.166721f};
bottom_plane_material_info->shininess = 0.25f * 128.0f;
auto far_plane_material_info = reinterpret_cast<Material_info*>(material_info_contents + 256 * 3);
far_plane_material_info->ambient = {0.2125f, 0.1275f, 0.054f, 0.0f};
far_plane_material_info->diffuse = {0.714f, 0.4284f, 0.18144f, 0.0f};
far_plane_material_info->specular = {0.393548f, 0.271906f, 0.166721f};
far_plane_material_info->shininess = 0.25f * 128.0f;
auto cube_material_info = reinterpret_cast<Material_info*>(material_info_contents + 256 * 4);
cube_material_info->ambient = {cfgs_.cube.ambient, 0.0};
cube_material_info->diffuse = {cfgs_.cube.diffuse, 0.0};
cube_material_info->specular = cfgs_.cube.specular;
cube_material_info->shininess = cfgs_.cube.shininess;
auto torus_material_info = reinterpret_cast<Material_info*>(material_info_contents + 256 * 5);
torus_material_info->ambient = {cfgs_.torus.ambient, 0.0};
torus_material_info->diffuse = {cfgs_.torus.diffuse, 0.0};
torus_material_info->specular = cfgs_.torus.specular;
torus_material_info->shininess = cfgs_.torus.shininess;
auto sphere_material_info = reinterpret_cast<Material_info*>(material_info_contents + 256 * 6);
sphere_material_info->ambient = {cfgs_.sphere.ambient, 0.0};
sphere_material_info->diffuse = {cfgs_.sphere.diffuse, 0.0};
sphere_material_info->specular = cfgs_.sphere.specular;
sphere_material_info->shininess = cfgs_.sphere.shininess;
buffers_["material_info"]->unmap();
Render_encoder_desc render_encoder_desc;
render_encoder_desc.colors[0].image = images_["light_color"].get();
render_encoder_desc.colors[0].load_op = Load_op::clear;
render_encoder_desc.colors[0].clear_value.r = 0.15f;
render_encoder_desc.colors[0].clear_value.g = 0.15f;
render_encoder_desc.colors[0].clear_value.b = 0.15f;
render_encoder_desc.colors[0].clear_value.a = 1.0f;
render_encoder_desc.depth_stencil.image = images_["light_depth_stencil"].get();
render_encoder_desc.depth_stencil.load_op = Load_op::clear;
render_encoder_desc.depth_stencil.clear_value.d = 1.0f;
render_encoder_desc.depth_stencil.clear_value.s = 0;
render_encoder_desc.depth_stencil.store_op = Store_op::dont_care;
auto pipeline = [&](uint32_t style) {
switch (style) {
case 0:
return pipelines_["flat"].get();
case 1:
return pipelines_["gouraud"].get();
case 2:
return pipelines_["phong"].get();
default:
throw runtime_error("invalid the light style");
}
};
auto render_encoder = cmd_buffer_->create(render_encoder_desc);
render_encoder->vertex_buffer(buffers_["cube_vertex"].get(), 0, 0);
render_encoder->index_buffer(buffers_["cube_index"].get(), 0, Index_type::uint16);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 0, 0);
render_encoder->pipeline(pipelines_["lamp"].get());
render_encoder->draw_indexed(draw_counts_["cube"]);
render_encoder->vertex_buffer(buffers_["plane_vertex"].get(), 0, 0);
render_encoder->index_buffer(buffers_["plane_index"].get(), 0, Index_type::uint16);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 512 * 2, 0);
render_encoder->shader_buffer(buffers_["light_info"].get(), 0, 1);
render_encoder->shader_buffer(buffers_["material_info"].get(), 256 * 2, 2);
render_encoder->pipeline(pipelines_["phong"].get());
render_encoder->draw_indexed(draw_counts_["plane"]);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 512 * 3, 0);
render_encoder->shader_buffer(buffers_["light_info"].get(), 0, 1);
render_encoder->shader_buffer(buffers_["material_info"].get(), 256 * 3, 2);
render_encoder->draw_indexed(draw_counts_["plane"]);
render_encoder->vertex_buffer(buffers_["cube_vertex"].get(), 0, 0);
render_encoder->index_buffer(buffers_["cube_index"].get(), 0, Index_type::uint16);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 512 * 4, 0);
render_encoder->shader_buffer(buffers_["light_info"].get(), 0, 1);
render_encoder->shader_buffer(buffers_["material_info"].get(), 256 * 4, 2);
render_encoder->pipeline(pipeline(cfgs_.cube.style));
render_encoder->draw_indexed(draw_counts_["cube"]);
render_encoder->vertex_buffer(buffers_["torus_vertex"].get(), 0, 0);
render_encoder->index_buffer(buffers_["torus_index"].get(), 0, Index_type::uint16);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 512 * 5, 0);
render_encoder->shader_buffer(buffers_["light_info"].get(), 0, 1);
render_encoder->shader_buffer(buffers_["material_info"].get(), 256 * 5, 2);
render_encoder->pipeline(pipeline(cfgs_.torus.style));
render_encoder->draw_indexed(draw_counts_["torus"]);
render_encoder->vertex_buffer(buffers_["sphere_vertex"].get(), 0, 0);
render_encoder->index_buffer(buffers_["sphere_index"].get(), 0, Index_type::uint16);
render_encoder->shader_buffer(buffers_["matrix_info"].get(), 512 * 6, 0);
render_encoder->shader_buffer(buffers_["light_info"].get(), 0, 1);
render_encoder->shader_buffer(buffers_["material_info"].get(), 256 * 6, 2);
render_encoder->pipeline(pipeline(cfgs_.sphere.style));
render_encoder->draw_indexed(draw_counts_["sphere"]);
render_encoder->end();
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::record_present_render_pass_()
{
ImGui::NewFrame();
ImGui::Begin("configs");
if (ImGui::CollapsingHeader("camera")) {
auto& cfgs = cfgs_.camera;
ImGui::DragFloat3("camera translation", &cfgs.translation[0], 0.1f);
ImGui::SliderFloat("camera fov", &cfgs.fov, 30.0f, 90.0f);
ImGui::SliderFloat("camera aspect", &cfgs.aspect, 0.0f, 10.0f);
ImGui::SliderFloat("camera near", &cfgs.near, 0.01f, 1.0f);
ImGui::SliderFloat("camera far", &cfgs.far, 100.0f, 1000.0f);
}
if (ImGui::CollapsingHeader("light")) {
auto& cfgs = cfgs_.light;
ImGui::DragFloat3("light translation", &cfgs.translation[0], 0.1f);
ImGui::ColorEdit3("light ambient", &cfgs.ambient[0]);
ImGui::ColorEdit3("light diffuse", &cfgs.diffuse[0]);
ImGui::ColorEdit3("light specular", &cfgs.specular[0]);
}
array<const char*, 3> items {"flat", "gouraud", "phong"};
if (ImGui::CollapsingHeader("cube")) {
auto& cfgs = cfgs_.cube;
ImGui::Checkbox("cube animation", &cfgs.animation);
ImGui::DragFloat3("cube translation", &cfgs.translation[0], 0.1f);
ImGui::DragFloat3("cube scale", &cfgs.scale[0], 0.1f);
ImGui::DragFloat3("cube rotation", &cfgs.rotation[0], 0.1f);
ImGui::Combo("cube style", &cfgs.style, &items[0], items.size());
ImGui::ColorEdit3("cube ambient", &cfgs.ambient[0]);
ImGui::ColorEdit3("cube diffuse", &cfgs.diffuse[0]);
ImGui::ColorEdit3("cube specular", &cfgs.specular[0]);
ImGui::SliderFloat("cube shininess", &cfgs.shininess, 1.0f, 200.0f);
}
if (ImGui::CollapsingHeader("torus")) {
auto& cfgs = cfgs_.torus;
ImGui::Checkbox("torus animation", &cfgs.animation);
ImGui::DragFloat3("torus translation", &cfgs.translation[0], 0.1f);
ImGui::DragFloat3("torus scale", &cfgs.scale[0], 0.1f);
ImGui::DragFloat3("torus rotation", &cfgs.rotation[0], 0.1f);
ImGui::Combo("torus style", &cfgs.style, &items[0], items.size());
ImGui::ColorEdit3("torus ambient", &cfgs.ambient[0]);
ImGui::ColorEdit3("torus diffuse", &cfgs.diffuse[0]);
ImGui::ColorEdit3("torus specular", &cfgs.specular[0]);
ImGui::SliderFloat("torus shininess", &cfgs.shininess, 1.0f, 200.0f);
}
if (ImGui::CollapsingHeader("sphere")) {
auto& cfgs = cfgs_.sphere;
ImGui::Checkbox("sphere animation", &cfgs.animation);
ImGui::DragFloat3("sphere translation", &cfgs.translation[0], 0.1f);
ImGui::DragFloat3("sphere scale", &cfgs.scale[0], 0.1f);
ImGui::DragFloat3("sphere rotation", &cfgs.rotation[0], 0.1f);
ImGui::Combo("sphere style", &cfgs.style, &items[0], items.size());
ImGui::ColorEdit3("sphere ambient", &cfgs.ambient[0]);
ImGui::ColorEdit3("sphere diffuse", &cfgs.diffuse[0]);
ImGui::ColorEdit3("sphere specular", &cfgs.specular[0]);
ImGui::SliderFloat("sphere shininess", &cfgs.shininess, 1.0f, 200.0f);
}
ImGui::End();
ImGui::Render();
ImGui::EndFrame();
auto draw_data = ImGui::GetDrawData();
if (draw_data->CmdListsCount) {
auto vertex_data {static_cast<ImDrawVert*>(buffers_["imgui_vertex"]->map())};
auto index_data {static_cast<ImDrawIdx*>(buffers_["imgui_index"]->map())};
for (auto i = 0; i != draw_data->CmdListsCount; ++i) {
auto cmd_list = draw_data->CmdLists[i];
memcpy(vertex_data, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
vertex_data += cmd_list->VtxBuffer.Size;
memcpy(index_data, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
index_data += cmd_list->IdxBuffer.Size;
}
}
Render_encoder_desc desc;
desc.colors[0].image = swap_chain_->acquire();
desc.colors[0].load_op = Load_op::dont_care;
auto render_encoder = cmd_buffer_->create(desc);
render_encoder->shader_texture(images_["light_color"].get(), samplers_["light_linear"].get(), 0);
render_encoder->pipeline(pipelines_["composite"].get());
render_encoder->draw(3, 0);
if (draw_data->CmdListsCount) {
render_encoder->shader_buffer(buffers_["imgui_shader_Imgui_info"].get(), 0, 0);
render_encoder->shader_texture(images_["imgui_font"].get(), samplers_["light_linear"].get(), 0);
render_encoder->pipeline(pipelines_["imgui"].get());
auto vertex_buffer_offset {0};
auto index_buffer_offset {0};
for (auto i = 0; i != draw_data->CmdListsCount; ++i) {
render_encoder->vertex_buffer(buffers_["imgui_vertex"].get(), vertex_buffer_offset, 0);
render_encoder->index_buffer(buffers_["imgui_index"].get(), index_buffer_offset, Index_type::uint16);
auto cmd_list = draw_data->CmdLists[i];
for (auto& cmd : cmd_list->CmdBuffer)
render_encoder->draw_indexed(cmd.ElemCount, cmd.IdxOffset);
vertex_buffer_offset += cmd_list->VtxBuffer.Size * sizeof(ImDrawVert);
index_buffer_offset += cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx);
}
}
render_encoder->end();
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_swap_chain_(Platform_lib::Window* window)
{
try {
// create a swap chain.
Swap_chain_desc swap_chain_desc;
#if __APPLE__
swap_chain_desc.image_format = Format::bgra8_unorm;
#else
swap_chain_desc.image_format = Format::rgba8_unorm;
#endif
swap_chain_desc.image_extent = window->extent();
swap_chain_desc.window = window->window();
swap_chain_ = device_->create(swap_chain_desc);
}
catch(exception& e) {
throw runtime_error("fail to create a demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_cmd_buffer_()
{
try {
cmd_buffer_ = device_->create(Cmd_buffer_desc {});
}
catch(exception& e) {
throw runtime_error("fail to create a demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_fence_()
{
try {
fence_ = device_->create(Fence_desc { true });
}
catch(exception& e) {
throw runtime_error("fail to create a demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_imgui_()
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui::StyleColorsDark();
auto& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;
io.DisplaySize.x = swap_chain_->image_extent().w;
io.DisplaySize.y = swap_chain_->image_extent().h;
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::init_imgui_resources_()
{
try {
Buffer_desc desc;
desc.size = 5 * 1024 * 1024;
buffers_["imgui_vertex"] = device_->create(desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
Buffer_desc desc;
desc.size = 1024 * 1024;
buffers_["imgui_index"] = device_->create(desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
auto& io = ImGui::GetIO();
Imgui_info imgui_info {
{-1.0f, 1.0f},
{2.0f / io.DisplaySize.x, 2.0f / -io.DisplaySize.y}
};
Buffer_desc desc;
desc.size = sizeof(Imgui_info);
desc.data = &imgui_info;
buffers_["imgui_shader_Imgui_info"] = device_->create(desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
uint8_t* pixels;
int32_t width, height;
auto& imgui_io = ImGui::GetIO();
imgui_io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
Buffer_desc buffer_desc;
buffer_desc.size = width * height * 4;
buffer_desc.data = pixels;
auto staging_buffer = device_->create(buffer_desc);
Image_desc image_desc;
image_desc.format = Format::rgba8_unorm;
image_desc.extent = {static_cast<uint32_t>(width), static_cast<uint32_t>(height), 1};
images_["imgui_font"] = device_->create(image_desc);
auto cmd_buffer = device_->create(Cmd_buffer_desc {});
auto blit_encoder = cmd_buffer->create(Blit_encoder_desc {});
Buffer_image_copy_region copy_region;
copy_region.buffer_row_size = width * 4;
copy_region.buffer_image_height = height;
copy_region.image_extent = image_desc.extent;
blit_encoder->copy(staging_buffer.get(), images_["imgui_font"].get(), copy_region);
blit_encoder->end();
cmd_buffer->end();
device_->submit(cmd_buffer.get());
device_->wait_idle();
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/composite.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/composite.frag"
#else
"../../../gfx/res/shader/composite.vert",
"../../../gfx/res/shader/composite.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.fragment_shader = shaders[1].get();
#if __APPLE__
pipeline_desc.output_merger.color_formats[0] = Format::bgra8_unorm;
#else
pipeline_desc.output_merger.color_formats[0] = Format::rgba8_unorm;
#endif
pipelines_["composite"] = device_->create(pipeline_desc);
}
catch (exception& e) {
throw runtime_error("fail to create gfx demo");
}
try {
// create shaders.
const vector<string> pathes {
#if defined(__ANDROID__)
"/sdcard/Android/data/com.ff.gfx_demo/files/imgui.vert",
"/sdcard/Android/data/com.ff.gfx_demo/files/imgui.frag"
#else
"../../../gfx/res/shader/imgui.vert",
"../../../gfx/res/shader/imgui.frag"
#endif
};
array<unique_ptr<Shader>, 2> shaders;
for (auto i = 0; i != 2; ++i) {
Shader_desc shader_desc;
shader_desc.type = static_cast<Shader_type>(i);
shader_desc.src = compiler_.compile(pathes[i]);
shaders[i] = device_->create(shader_desc);
}
Vertex_input vertex_input;
vertex_input.attributes[0].binding = 0;
vertex_input.attributes[0].format = Format::rg32_float;
vertex_input.attributes[0].offset = IM_OFFSETOF(ImDrawVert, pos);
vertex_input.attributes[1].binding = 0;
vertex_input.attributes[1].format = Format::rgba8_unorm;
vertex_input.attributes[1].offset = IM_OFFSETOF(ImDrawVert, col);
vertex_input.attributes[2].binding = 0;
vertex_input.attributes[2].format = Format::rg32_float;
vertex_input.attributes[2].offset = IM_OFFSETOF(ImDrawVert, uv);
vertex_input.bindings[0].stride = sizeof(ImDrawVert);
// create a pipeline.
Pipeline_desc pipeline_desc;
pipeline_desc.vertex_input = vertex_input;
pipeline_desc.vertex_shader = shaders[0].get();
pipeline_desc.rasterization.front_face = Front_face::clockwise;
pipeline_desc.fragment_shader = shaders[1].get();
pipeline_desc.color_blend.attachments[0].blend = true;
pipeline_desc.color_blend.attachments[0].src_rgb_blend_factor = Blend_factor::src_alpha;
pipeline_desc.color_blend.attachments[0].dst_rgb_blend_factor = Blend_factor::one_minus_src_alpha;
pipeline_desc.color_blend.attachments[0].src_a_blend_factor = Blend_factor::src_alpha;
pipeline_desc.color_blend.attachments[0].dst_a_blend_factor = Blend_factor::one_minus_src_alpha;
pipeline_desc.output_merger.color_formats[0] = swap_chain_->image_format();
pipelines_["imgui"] = device_->create(pipeline_desc);
}
catch( exception& e) {
throw runtime_error("fail to create gfx demo");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Gfx_demo::fini_imgui_()
{
ImGui::DestroyContext();
}
//----------------------------------------------------------------------------------------------------------------------
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "ogl_lib.h"
#include "Ogl_framebuffer.h"
#include "Ogl_image.h"
using namespace std;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline bool is_swap_chain_image(Ogl_image* image)
{
if (!image)
return false;
return Image_type::swap_chain == image->type();
}
//----------------------------------------------------------------------------------------------------------------------
}
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_framebuffer::Ogl_framebuffer(const Ogl_framebuffer_desc& desc, Ogl_device* device) :
device_ {device},
extent_ {0, 0, 1},
colors_ {desc.colors},
depth_stencil_ {desc.depth_stencil},
framebuffer_ {0}
{
init_extent_();
init_framebuffer_();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_framebuffer::~Ogl_framebuffer()
{
fini_framebuffer_();
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_framebuffer::init_extent_()
{
extent_ = colors_[0]->extent();
// check all attachments has a same extent.
for (auto i = 1; i != 4; ++i) {
auto& color = colors_[i];
if (!color)
continue;
if (color->extent() != extent_)
throw runtime_error("fail to create a framebuffer");
}
if (depth_stencil_) {
if (depth_stencil_->extent() != extent_)
throw runtime_error("fail to create a framebuffer");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_framebuffer::init_framebuffer_()
{
if (end(colors_) != find_if(colors_, is_swap_chain_image))
return;
glGenFramebuffers(1, &framebuffer_);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
for (auto i = 0; i != 4; ++i) {
auto& color = colors_[i];
if (!color)
continue;
glBindTexture(GL_TEXTURE_2D, color->texture());
glFramebufferTexture2D(GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0 + i,
GL_TEXTURE_2D,
color->texture(),
0);
}
if (depth_stencil_) {
glBindTexture(GL_TEXTURE_2D, depth_stencil_->texture());
glFramebufferTexture2D(GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D,
depth_stencil_->texture(),
0);
glFramebufferTexture2D(GL_FRAMEBUFFER,
GL_STENCIL_ATTACHMENT,
GL_TEXTURE_2D,
depth_stencil_->texture(),
0);
}
if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus(GL_FRAMEBUFFER))
throw runtime_error("fail to create a framebuffer");
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_framebuffer::fini_framebuffer_()
{
if (framebuffer_)
glDeleteFramebuffers(1, &framebuffer_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_SWAP_CHAIN_GUARD
#define GFX_SWAP_CHAIN_GUARD
#include <platform/Extent.h>
#include "enums.h"
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
class Image;
//----------------------------------------------------------------------------------------------------------------------
struct Swap_chain_desc final {
uint32_t image_count {3};
Format image_format {Format::invalid};
Extent image_extent {0, 0, 1};
Color_space color_space {Color_space::srgb_non_linear};
void* window {nullptr};
};
//----------------------------------------------------------------------------------------------------------------------
class Swap_chain {
public:
explicit Swap_chain(const Swap_chain_desc& desc) noexcept :
image_format_ {desc.image_format},
image_extent_ {desc.image_extent},
color_space_ {desc.color_space},
frame_count_ {0}
{}
virtual ~Swap_chain() = default;
virtual Image* acquire() = 0;
virtual void present() = 0;
virtual Device* device() const = 0;
inline Format image_format() const noexcept
{ return image_format_; }
inline Extent image_extent() const noexcept
{ return image_extent_; }
inline Color_space color_space() const noexcept
{ return color_space_; }
inline uint64_t frame_count() const noexcept
{ return frame_count_; }
protected:
Format image_format_;
Extent image_extent_;
Color_space color_space_;
uint64_t frame_count_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_SWAP_CHAIN_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_BUFFER_GUARD
#define GFX_OGL_BUFFER_GUARD
#include <GLES3/gl3.h>
#include "Buffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_buffer final : public Buffer {
public:
Ogl_buffer(const Buffer_desc& desc, Ogl_device* device);
~Ogl_buffer();
void* map() override;
void unmap() override;
Device* device() const override;
inline auto& buffer() const noexcept
{ return buffer_; }
private:
void init_buffer_(const void* data);
void fini_buffer_();
private:
Ogl_device* device_;
GLuint buffer_;
void* contents_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_BUFFER_GUARD<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_DEVICE_GUARD
#define GFX_MTL_DEVICE_GUARD
#include <mutex>
#include <Foundation/Foundation.h>
#include <Metal/Metal.h>
#include "Device.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device final : public Device {
public:
Mtl_device();
std::unique_ptr<Buffer> create(const Buffer_desc& desc) override;
std::unique_ptr<Image> create(const Image_desc& desc) override;
std::unique_ptr<Sampler> create(const Sampler_desc& desc) override;
std::unique_ptr<Shader> create(const Shader_desc& desc) override;
std::unique_ptr<Pipeline> create(const Pipeline_desc& desc) override;
std::unique_ptr<Swap_chain> create(const Swap_chain_desc& desc) override;
std::unique_ptr<Cmd_buffer> create(const Cmd_buffer_desc& desc) override;
std::unique_ptr<Fence> create(const Fence_desc& desc) override;
void submit(Cmd_buffer* cmd_buffer, Fence* fence = nullptr) override;
void wait_idle() override;
inline auto device() const noexcept
{ return device_; }
inline auto command_queue() const noexcept
{ return command_queue_; }
private:
void init_device_();
void init_caps_();
void init_command_queue_();
private:
id<MTLDevice> device_;
id<MTLCommandQueue> command_queue_;
NSMutableSet<id<MTLCommandBuffer>>* used_command_buffers_;
std::mutex queue_mutex_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_DEVICE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_DEMO_UTIL_GUARD
#define GFX_DEMO_UTIL_GUARD
#include <cstdint>
#include <vector>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <gfx/Pipeline.h>
//----------------------------------------------------------------------------------------------------------------------
template <typename T>
T align_pow2(T value, uint64_t alignment)
{
return ((value + static_cast<T>(alignment) - 1) & ~(static_cast<T>(alignment) - 1));
}
//----------------------------------------------------------------------------------------------------------------------
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 tex_coords;
};
//----------------------------------------------------------------------------------------------------------------------
class Primitive {
public:
std::vector<Vertex> vertices;
Gfx_lib::Vertex_input vertex_input;
std::vector<uint16_t> indices;
uint32_t draw_count;
virtual ~Primitive() = default;
};
//----------------------------------------------------------------------------------------------------------------------
class Plane : public Primitive {
public:
Plane(float w, float h);
private:
void init_vertices_(float half_x, float half_y);
void init_indices_();
};
//----------------------------------------------------------------------------------------------------------------------
class Cube : public Primitive {
public:
explicit Cube(float size = 1.0f);
private:
void init_vertices_(float half_size);
void init_indices_();
};
//----------------------------------------------------------------------------------------------------------------------
class Sphere : public Primitive {
public:
Sphere(float r, uint32_t sector, uint32_t stack);
private:
void init_vertices_(float r, uint32_t sector, uint32_t stack);
void init_indices_(uint32_t sector, uint32_t stack);
};
//----------------------------------------------------------------------------------------------------------------------
class Torus : public Primitive {
public:
Torus(float inner_radius, float outer_radius, uint32_t side_count, uint32_t ring_count);
private:
void init_vertices_(float inner_radius, float outer_radius, uint32_t side_count, uint32_t ring_count);
void init_indices_(uint32_t side_count, uint32_t ring_count);
};
//----------------------------------------------------------------------------------------------------------------------
#endif // GFX_DEMO_UTIL_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <platform/Window.h>
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_swap_chain.h"
#include "Vlk_device.h"
#include "Vlk_image.h"
#include "Vlk_cmd_buffer.h"
#include "Vlk_fence.h"
#if TARGET_OS_OSX
#include <QuartzCore/CAMetalLayer.h>
#include "mtl_lib.h"
#endif
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_swap_chain::Vlk_swap_chain(const Swap_chain_desc& desc, Vlk_device* device) :
Swap_chain {desc},
device_ {device},
surface_ {VK_NULL_HANDLE},
swapchain_ {VK_NULL_HANDLE},
images_ {desc.image_count},
image_index_ {UINT32_MAX},
acquire_fence_ {nullptr},
cmd_buffers_ {desc.image_count},
submit_fences_ {desc.image_count},
submit_semaphores_ {desc.image_count},
frame_index_ {0}
{
init_surface_(desc.window);
init_swapchain_();
init_images_();
init_acquire_fence_();
init_cmd_buffers_();
init_submit_fences_();
init_submit_semaphores_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_swap_chain::~Vlk_swap_chain()
{
fini_submit_semaphores_();
fini_swapchain_();
fini_surface_();
}
//----------------------------------------------------------------------------------------------------------------------
Image* Vlk_swap_chain::acquire()
{
if (UINT32_MAX == image_index_) {
acquire_fence_->reset();
vkAcquireNextImageKHR(device_->device(), swapchain_,
UINT64_MAX, VK_NULL_HANDLE, acquire_fence_->fence(),
&image_index_);
acquire_fence_->wait_signal();
}
return images_[image_index_].get();
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::present()
{
// query a fence is signaled or not, if not wait a fence to signal.
if (!cur_submit_fence_()->signaled())
cur_submit_fence_()->wait_signal();
// reset a fence and a command buffer.
cur_submit_fence_()->reset();
cur_cmd_buffer_()->reset();
// configure an image barrier.
VkImageMemoryBarrier image_barrier {};
image_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
image_barrier.srcAccessMask = cur_image_()->access_mask();
image_barrier.dstAccessMask = 0;
image_barrier.oldLayout = cur_image_()->layout();
image_barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
image_barrier.image = cur_image_()->image();
image_barrier.subresourceRange.aspectMask = cur_image_()->aspect_mask();
image_barrier.subresourceRange.levelCount = cur_image_()->mip_levels();
image_barrier.subresourceRange.layerCount = cur_image_()->array_layers();
// update image meta data.
cur_image_()->access_mask_ = 0;
cur_image_()->layout_ = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
// record barrier command.
vkCmdPipelineBarrier(cur_cmd_buffer_()->command_buffer(),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
0, nullptr,
0, nullptr,
1, &image_barrier);
cur_cmd_buffer_()->end();
// configure a submit info.
VkSubmitInfo submit_info {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cur_cmd_buffer_()->command_buffer();
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = &cur_submit_semaphore_();
// submit a command buffer.
vkQueueSubmit(device_->queue(), 1, &submit_info, cur_submit_fence_()->fence());
// configure a present info.
VkPresentInfoKHR present_info {};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = &cur_submit_semaphore_();
present_info.swapchainCount = 1;
present_info.pSwapchains = &swapchain_;
present_info.pImageIndices = &image_index_;
// present.
vkQueuePresentKHR(device_->queue(), &present_info);
image_index_ = UINT32_MAX;
frame_index_ = ++frame_count_ % images_.size();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_swap_chain::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_surface_(void* window)
{
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
// configure an android surface create info.
VkAndroidSurfaceCreateInfoKHR create_info {};
create_info.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
create_info.window = static_cast<ANativeWindow*>(window);
// try to create an android surface.
if (vkCreateAndroidSurfaceKHR(device_->instance(), &create_info, nullptr, &surface_))
throw runtime_error("fail to create a swap chain");
#elif defined(VK_USE_PLATFORM_WIN32_KHR)
// configure a win32 surface create info.
VkWin32SurfaceCreateInfoKHR create_info {};
create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.hinstance = GetModuleHandle(NULL);
create_info.hwnd = static_cast<HWND>(window);
// try to create an win32 surface.
if (vkCreateWin32SurfaceKHR(device_->instance(), &create_info, nullptr, &surface_))
throw runtime_error("fail to create a swap chain");
#elif defined(VK_USE_PLATFORM_MACOS_MVK)
// create a metal layer.
auto layer = [CAMetalLayer layer];
if (!layer)
throw runtime_error("fail to create a swap chain");
// configure a metal layer.
layer.pixelFormat = to_MTLPixelFormat(image_format_);
layer.framebufferOnly = NO;
layer.maximumDrawableCount = images_.size();
// set a metal layer to a view.
[[(__bridge NSWindow*)window contentView] setLayer:layer];
// configure an osx surface create info.
VkMacOSSurfaceCreateInfoMVK create_info {};
create_info.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
create_info.pView = (__bridge void*)[(__bridge NSWindow*)window contentView];
// try to create an osx surface.
if (vkCreateMacOSSurfaceMVK(device_->instance(), &create_info, nullptr, &surface_))
throw runtime_error("fail to create a swap chain");
#endif
// query the physical device supports the surface.
VkBool32 supported;
vkGetPhysicalDeviceSurfaceSupportKHR(device_->physical_device(), device_->queue_family_index(),
surface_, &supported);
assert(supported);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_swapchain_()
{
// query the surface capabilities.
VkSurfaceCapabilitiesKHR surface_caps;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device_->physical_device(), surface_, &surface_caps);
// configure a swapchain create info.
VkSwapchainCreateInfoKHR create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
create_info.surface = surface_;
create_info.minImageCount = images_.size();
create_info.imageFormat = to_VkFormat(image_format_);
create_info.imageColorSpace = to_VkColorSpaceKHR(color_space_);
create_info.imageExtent = surface_caps.currentExtent;
create_info.imageArrayLayers = 1;
create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
create_info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
create_info.clipped = VK_TRUE;
// try to create a swapchain.
if (vkCreateSwapchainKHR(device_->device(), &create_info, nullptr, &swapchain_))
throw runtime_error("fail to create a swap chain");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_images_()
{
// query the swapchain image count.
uint32_t count;
vkGetSwapchainImagesKHR(device_->device(), swapchain_, &count, nullptr);
// query the swapchain images.
assert(count == images_.size());
vector<VkImage> images(count);
vkGetSwapchainImagesKHR(device_->device(), swapchain_, &count, &images[0]);
// configure an image desc.
Image_desc desc;
desc.type = Image_type::swap_chain;
desc.format = image_format_;
desc.extent = image_extent_;
// create images.
for (auto i = 0; i != images_.size(); ++i) {
try {
images_[i] = make_unique<Vlk_image>(desc, device_, this, images[i]);
}
catch (exception& except) {
throw runtime_error("fail to create a swap chain");
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_acquire_fence_()
{
// configure a fence descriptor.
Fence_desc desc;
desc.signaled = true;
// try to create fences.
try {
acquire_fence_ = make_unique<Vlk_fence>(desc, device_);
}
catch (exception& e) {
throw runtime_error("fail to create a swap chain");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_cmd_buffers_()
{
// try to create command buffers.
for (auto& cmd_buffer : cmd_buffers_)
cmd_buffer = make_unique<Vlk_cmd_buffer>(device_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_submit_fences_()
{
// try to create fences.
for (auto& fence : submit_fences_) {
// configure a fence descriptor.
Fence_desc desc;
desc.signaled = true;
try {
fence = make_unique<Vlk_fence>(desc, device_);
}
catch (exception& e) {
throw runtime_error("fail to create a swap chain");
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::init_submit_semaphores_()
{
for (auto& semaphore : submit_semaphores_) {
// configure a semaphore create info.
VkSemaphoreCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
// try to create submit semaphores.
if (vkCreateSemaphore(device_->device(), &create_info, nullptr, &semaphore))
throw runtime_error("fail to create a swap chain");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::fini_surface_()
{
vkDestroySurfaceKHR(device_->instance(), surface_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::fini_swapchain_()
{
vkDestroySwapchainKHR(device_->device(), swapchain_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_swap_chain::fini_submit_semaphores_()
{
for (auto& semaphore : submit_semaphores_) {
vkDestroySemaphore(device_->device(), semaphore, nullptr);
}
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#define VMA_IMPLEMENTATION
#include <metrohash.h>
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_device.h"
#include "Vlk_buffer.h"
#include "Vlk_image.h"
#include "Vlk_sampler.h"
#include "Vlk_shader.h"
#include "Vlk_pipeline.h"
#include "Vlk_swap_chain.h"
#include "Vlk_cmd_buffer.h"
#include "Vlk_fence.h"
#include "Vlk_render_pass.h"
#include "Vlk_framebuffer.h"
using namespace std;
using namespace Platform_lib;
using namespace Gfx_lib;
//----------------------------------------------------------------------------------------------------------------------
#define DEFINE_VLK_SYMBOL(name) PFN_##name name;
#define LOAD_VLK_BOOTSTRAP_SYMBOL(name) name = library_.symbol<PFN_##name>(#name);
#define LOAD_VLK_INSTANCE_SYMBOL(name) name = (PFN_##name)vkGetInstanceProcAddr(instance_, #name);
#define LOAD_VLK_DEVICE_SYMBOL(name) name = (PFN_##name)vkGetDeviceProcAddr(device_, #name);
//----------------------------------------------------------------------------------------------------------------------
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline constexpr auto all_flags(uint32_t src, uint32_t test) noexcept
{
return test == (src & test);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
APPLY_VLK_BOOTSTRAP_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_CORE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_SURFACE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_ANDROID_SURFACE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_WIN32_SURFACE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_OSX_SURFACE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_DEBUG_REPORT_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_DEVICE_CORE_SYMBOLS(DEFINE_VLK_SYMBOL)
APPLY_VLK_DEVICE_SWAPCHAIN_SYMBOLS(DEFINE_VLK_SYMBOL)
//----------------------------------------------------------------------------------------------------------------------
Vlk_device::Vlk_device() :
Device(),
library_ {},
instance_ { VK_NULL_HANDLE },
physical_device_ { VK_NULL_HANDLE },
queue_family_index_ { UINT32_MAX },
device_ { VK_NULL_HANDLE },
queue_ { VK_NULL_HANDLE },
allocator_ { VK_NULL_HANDLE },
command_pool_ { VK_NULL_HANDLE },
render_pass_pool_ {},
framebuffer_pool_ {}
{
init_library_();
init_bootstrap_symbols_();
init_instance_();
init_instance_symbols_();
init_physical_device_();
init_queue_family_index_();
init_device_();
init_device_symbols_();
init_caps_();
init_queue_();
init_allocator_();
init_command_pool_();
init_pipeline_cache_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_device::~Vlk_device()
{
framebuffer_pool_.clear();
render_pass_pool_.clear();
fini_pipeline_cache_();
fini_command_pool_();
fini_allocator_();
fini_device_();
fini_instance_();
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Buffer> Vlk_device::create(const Buffer_desc& desc)
{
return make_unique<Vlk_buffer>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Image> Vlk_device::create(const Image_desc& desc)
{
return make_unique<Vlk_image>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Sampler> Vlk_device::create(const Sampler_desc& desc)
{
return make_unique<Vlk_sampler>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Shader> Vlk_device::create(const Shader_desc& desc)
{
return make_unique<Vlk_shader>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Pipeline> Vlk_device::create(const Pipeline_desc& desc)
{
return make_unique<Vlk_pipeline>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Swap_chain> Vlk_device::create(const Swap_chain_desc& desc)
{
return make_unique<Vlk_swap_chain>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Cmd_buffer> Vlk_device::create(const Cmd_buffer_desc& desc)
{
return make_unique<Vlk_cmd_buffer>(this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Fence> Vlk_device::create(const Fence_desc& desc)
{
return make_unique<Vlk_fence>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::submit(Cmd_buffer* cmd_buffer, Fence* fence)
{
// cast to the implementation.
auto cmd_buffer_impl = static_cast<Vlk_cmd_buffer*>(cmd_buffer);
auto fence_impl = static_cast<Vlk_fence*>(fence);
// configure a submit info.
VkSubmitInfo submit_info {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &cmd_buffer_impl->command_buffer();
// submit a command buffer.
vkQueueSubmit(queue_, 1, &submit_info, fence_impl ? fence_impl->fence() : VK_NULL_HANDLE);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::wait_idle()
{
vkDeviceWaitIdle(device_);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_render_pass* Vlk_device::render_pass(const Vlk_render_pass_desc& desc)
{
// calculate a hash value.
uint64_t key { 0 };
MetroHash64::Hash(reinterpret_cast<const uint8_t*>(&desc), sizeof(Vlk_render_pass_desc),
reinterpret_cast<uint8_t*>(&key));
// check a render pass exists and if not then create it.
if (!render_pass_pool_.contains(key))
render_pass_pool_.emplace(key, desc, this);
return *render_pass_pool_.find(key);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_framebuffer* Vlk_device::framebuffer(const Vlk_framebuffer_desc& desc)
{
// calculate a hash value.
uint64_t key { 0 };
MetroHash64::Hash(reinterpret_cast<const uint8_t*>(&desc), sizeof(Vlk_framebuffer_desc),
reinterpret_cast<uint8_t*>(&key));
// check a framebuffer exists and if not then create it.
if (!framebuffer_pool_.contains(key))
framebuffer_pool_.emplace(key, desc, this);
return *framebuffer_pool_.find(key);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_library_()
{
try {
#if defined(__ANDROID__)
library_ = Library { "libvulkan.so" };
#elif defined(_WIN32)
library_ = Library { "vulkan-1.dll" };
#elif defined(VK_USE_PLATFORM_MACOS_MVK)
library_ = Library { "libvulkan.dylib" };
#endif
}
catch (exception& e) {
throw runtime_error("fail to create a device");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_bootstrap_symbols_()
{
APPLY_VLK_BOOTSTRAP_SYMBOLS(LOAD_VLK_BOOTSTRAP_SYMBOL)
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_instance_()
{
vector<const char*> extensions {
#if defined(_DEBUG) || !defined(NDEBUG)
VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
#endif
VK_KHR_SURFACE_EXTENSION_NAME,
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
#elif defined(VK_USE_PLATFORM_WIN32_KHR)
VK_KHR_WIN32_SURFACE_EXTENSION_NAME
#elif defined(VK_USE_PLATFORM_MACOS_MVK)
VK_MVK_MACOS_SURFACE_EXTENSION_NAME
#endif
};
// configure the application info.
VkApplicationInfo app_info {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0);
// configure the instance create info.
VkInstanceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pApplicationInfo = &app_info;
create_info.enabledExtensionCount = extensions.size();
create_info.ppEnabledExtensionNames = &extensions[0];
// try to create an instance.
if (vkCreateInstance(&create_info, nullptr, &instance_))
throw runtime_error("fail to create a device");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_instance_symbols_()
{
APPLY_VLK_INSTANCE_CORE_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
APPLY_VLK_INSTANCE_SURFACE_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
APPLY_VLK_INSTANCE_ANDROID_SURFACE_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
APPLY_VLK_INSTANCE_WIN32_SURFACE_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
APPLY_VLK_INSTANCE_OSX_SURFACE_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
APPLY_VLK_INSTANCE_DEBUG_REPORT_SYMBOLS(LOAD_VLK_INSTANCE_SYMBOL)
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_physical_device_()
{
// query the physical device count.
uint32_t count;
vkEnumeratePhysicalDevices(instance_, &count, nullptr);
if (!count)
throw runtime_error("fail to create a device");
// query physical devices
vector<VkPhysicalDevice> physical_devices(count);
vkEnumeratePhysicalDevices(instance_, &count, &physical_devices[0]);
// todo: find the best physical device.
physical_device_ = physical_devices[0];
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_queue_family_index_()
{
// query the physical device queue family properties count.
uint32_t count;
vkGetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, nullptr);
// query the physical device queue family properties.
assert(count);
std::vector<VkQueueFamilyProperties> properties(count);
vkGetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, &properties[0]);
// query the queue family index supporting the graphics and the compute.
constexpr auto queue_flags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
for (auto i = 0; i != properties.size(); ++i) {
if (all_flags(properties[i].queueFlags, queue_flags)) {
queue_family_index_ = i;
break;
}
}
if (UINT32_MAX == queue_family_index_)
throw runtime_error("fail to create a deivce");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_device_()
{
vector<const char*> extensions {
"VK_KHR_swapchain",
"VK_KHR_maintenance1"
};
// configure the device create info.
VkDeviceQueueCreateInfo queue_create_info {};
constexpr auto queue_priority { 0.0f };
queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_create_info.queueFamilyIndex = queue_family_index_;
queue_create_info.queueCount = 1;
queue_create_info.pQueuePriorities = &queue_priority;
// configure the device create info.
VkDeviceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.queueCreateInfoCount = 1;
create_info.pQueueCreateInfos = &queue_create_info;
create_info.enabledExtensionCount = extensions.size();
create_info.ppEnabledExtensionNames = &extensions[0];
// try to create a device
if (vkCreateDevice(physical_device_, &create_info, nullptr, &device_))
throw runtime_error("fail to create a deivce");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_device_symbols_()
{
APPLY_VLK_DEVICE_CORE_SYMBOLS(LOAD_VLK_DEVICE_SYMBOL)
APPLY_VLK_DEVICE_SWAPCHAIN_SYMBOLS(LOAD_VLK_DEVICE_SYMBOL)
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_caps_()
{
caps_.window_coords = Coords::origin_upper_left;
caps_.texture_coords = Coords::origin_upper_left;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_queue_()
{
vkGetDeviceQueue(device_, queue_family_index_, 0, &queue_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_allocator_()
{
// set vulkan functions.
VmaVulkanFunctions functions {};
functions.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
functions.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
functions.vkAllocateMemory = vkAllocateMemory;
functions.vkFreeMemory = vkFreeMemory;
functions.vkMapMemory = vkMapMemory;
functions.vkUnmapMemory = vkUnmapMemory;
functions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
functions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
functions.vkBindBufferMemory = vkBindBufferMemory;
functions.vkBindImageMemory = vkBindImageMemory;
functions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
functions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
functions.vkCreateBuffer = vkCreateBuffer;
functions.vkDestroyBuffer = vkDestroyBuffer;
functions.vkCreateImage = vkCreateImage;
functions.vkDestroyImage = vkDestroyImage;
functions.vkCmdCopyBuffer = vkCmdCopyBuffer;
// configure an allocator create info.
VmaAllocatorCreateInfo create_info {};
create_info.physicalDevice = physical_device_;
create_info.device = device_;
create_info.pVulkanFunctions = &functions;
create_info.instance = instance_;
create_info.vulkanApiVersion = VK_MAKE_VERSION(1, 0, 0);
// try to create an allocator.
if (vmaCreateAllocator(&create_info, &allocator_))
throw runtime_error("fail to create a deivce");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_command_pool_()
{
// configure the command pool create info.
VkCommandPoolCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
create_info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
create_info.queueFamilyIndex = queue_family_index_;
// try to create a command pool.
if (vkCreateCommandPool(device_, &create_info, nullptr, &command_pool_))
throw runtime_error("fail to create a device");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::init_pipeline_cache_()
{
// configure a pipeline cache create info.
VkPipelineCacheCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
// try to create a pipeline cache.
if (vkCreatePipelineCache(device_, &create_info, nullptr, &pipeline_cache_))
throw runtime_error("fail to create a device");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::fini_instance_()
{
vkDestroyInstance(instance_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::fini_device_()
{
vkDestroyDevice(device_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::fini_allocator_()
{
vmaDestroyAllocator(allocator_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_device::fini_command_pool_()
{
vkDestroyCommandPool(device_, command_pool_, nullptr);
}
void Vlk_device::fini_pipeline_cache_()
{
vkDestroyPipelineCache(device_, pipeline_cache_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_IMAGE_GUARD
#define GFX_OGL_IMAGE_GUARD
#include <vulkan/vulkan.h>
#include <vk_mem_alloc.h>
#include "gfx/Image.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_image final : public Image {
public:
Ogl_image(const Image_desc& desc, Ogl_device* device);
~Ogl_image() override;
Device* device() const override;
inline auto texture() const noexcept
{ return texture_; }
private:
void init_texture_();
void fini_texture_();
private:
Ogl_device* device_;
GLuint texture_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_IMAGE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_BUFFER_GUARD
#define GFX_VLK_BUFFER_GUARD
#include <vulkan/vulkan.h>
#include <vk_mem_alloc.h>
#include "gfx/Buffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_buffer final : public Buffer {
public:
Vlk_buffer(const Buffer_desc& desc, Vlk_device* device);
~Vlk_buffer();
void* map() override;
void unmap() override;
Device* device() const override;
inline auto& buffer() const noexcept
{ return buffer_; }
private:
void init_buffer_and_alloc_(const void* data);
void fini_buffer_and_alloc_();
private:
Vlk_device* device_;
VkBuffer buffer_;
VmaAllocation alloc_;
void* contents_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_PIPELINE_GUARD
#define GFX_MTL_PIPELINE_GUARD
#include <utility>
#include <Metal/Metal.h>
#include "Pipeline.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_pipeline final : public Pipeline {
public:
Mtl_pipeline(const Pipeline_desc& desc, Mtl_device* device);
Device* device() const override;
inline auto render_pipeline_state() const noexcept
{ return render_pipeline_state_; }
inline auto depth_stencil_state() const noexcept
{ return depth_stencil_state_; }
private:
void init_render_pipeline_state_(Shader* vertex_shader, Shader* fragment_shader);
void init_depth_stencil_state_();
private:
Mtl_device* device_;
id<MTLRenderPipelineState> render_pipeline_state_;
id<MTLDepthStencilState> depth_stencil_state_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_PIPELINE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_LRU_CACHE_GUARD
#define GFX_LRU_CACHE_GUARD
#include <cstdint>
#include <memory>
#include <optional>
#include <iterator>
#include <list>
#include <unordered_map>
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
template<typename T, uint32_t N = 256>
class Lru_cache final
{
public:
Lru_cache() :
history_ {},
pool_ {}
{
}
template<typename... Args>
void emplace(uint64_t key, Args&&... args)
{
assert(!contains(key));
if (N == pool_.size()) {
pool_.erase(history_.back());
history_.pop_back();
}
pool_.emplace(key, std::make_unique<T>(args...));
history_.remove(key);
history_.push_front(key);
}
std::optional<T*> find(uint64_t key)
{
auto iter = pool_.find(key);
if (std::end(pool_) != iter)
return iter->second.get();
return std::nullopt;
}
bool contains(uint64_t key) const
{
return std::end(pool_) != pool_.find(key);
}
void clear()
{
pool_.clear();
history_.clear();
}
private:
std::list<uint64_t> history_;
std::unordered_map<uint64_t, std::unique_ptr<T>> pool_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_LRU_CACHE_GUARD<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_render_pass.h"
#include "Vlk_device.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_render_pass::Vlk_render_pass(const Vlk_render_pass_desc& desc, Vlk_device* device) :
device_ { device },
render_pass_ { VK_NULL_HANDLE }
{
init_render_pass_(desc);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_render_pass::~Vlk_render_pass()
{
fini_render_pass_();
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_pass::init_render_pass_(const Vlk_render_pass_desc& desc)
{
// convert to attachment descriptions.
vector<VkAttachmentDescription> attachments;
{
for (auto& color : desc.colors) {
if (Format::invalid == color.format)
continue;
VkAttachmentDescription attachment {};
attachment.format = to_VkFormat(color.format);
attachment.samples = to_VkSampleCountFlagBits(color.samples);
attachment.loadOp = to_VkAttachmentLoadOp(color.load_op);
attachment.storeOp = to_VkAttachmentStoreOp(color.store_op);
attachment.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
attachments.push_back(attachment);
}
auto& depth_stencil = desc.depth_stencil;
if (Format::invalid != depth_stencil.format) {
VkAttachmentDescription attachment {};
attachment.format = to_VkFormat(depth_stencil.format);
attachment.samples = to_VkSampleCountFlagBits(depth_stencil.samples);
attachment.loadOp = to_VkAttachmentLoadOp(depth_stencil.load_op);
attachment.storeOp = to_VkAttachmentStoreOp(depth_stencil.store_op);
attachment.stencilLoadOp = attachment.loadOp;
attachment.stencilStoreOp = attachment.storeOp;
attachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments.push_back(attachment);
}
}
// convert to attachment references.
array<VkAttachmentReference, 4> color_references;
VkAttachmentReference depth_stencil_reference {};
{
auto attachment { 0 };
for (auto i = 0 ; i != 4; ++i) {
auto& color = desc.colors[i];
if (Format::invalid == color.format)
color_references[i].attachment = VK_ATTACHMENT_UNUSED;
else
color_references[i].attachment = attachment++;
color_references[i].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
auto& depth_stencil = desc.depth_stencil;
if (Format::invalid == depth_stencil.format)
depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED;
else
depth_stencil_reference.attachment = attachment;
depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
// configure a subpass description.
VkSubpassDescription subpass {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
// subpass.colorAttachmentCount = color_references.size();
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_references[0];
subpass.pDepthStencilAttachment = &depth_stencil_reference;
// configure a render pass create info.
VkRenderPassCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
create_info.attachmentCount = attachments.size();
create_info.pAttachments = &attachments[0];
create_info.subpassCount = 1;
create_info.pSubpasses = &subpass;
// try to create a render pass.
if (vkCreateRenderPass(device_->device(), &create_info, nullptr, &render_pass_))
throw runtime_error("fail to create a render pass");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_pass::fini_render_pass_()
{
vkDestroyRenderPass(device_->device(), render_pass_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId = 'com.ff.gfx_demo'
minSdkVersion 14
targetSdkVersion 28
ndk.abiFilters 'arm64-v8a'
externalNativeBuild {
cmake {
arguments '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=c++_static'
cppFlags '-std=c++1z'
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
version '3.16.2'
path '../../../CMakeLists.txt'
}
}
sourceSets {
main {
jniLibs {
srcDirs "${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs"
}
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
}
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_FENCE_GUARD
#define GFX_FENCE_GUARD
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
//----------------------------------------------------------------------------------------------------------------------
struct Fence_desc final {
bool signaled {false};
};
//----------------------------------------------------------------------------------------------------------------------
class Fence {
public:
virtual ~Fence() = default;
virtual void wait_signal() = 0;
virtual void reset() = 0;
virtual Device* device() const = 0;
virtual bool signaled() const = 0;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_FENCE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_LIB_GUARD
#define GFX_OGL_LIB_GUARD
#include <stdexcept>
#include <GLES3/gl3.h>
#include <GLES2/gl2ext.h>
#include <sc/enums.h>
#include "enums.h"
#define APPLY_OGL_DRAW_BUFFERS_INDEXED_SYMBOLS(macro) \
macro(glEnablei) \
macro(glDisablei) \
macro(glBlendEquationi) \
macro(glBlendEquationSeparatei) \
macro(glBlendFunci) \
macro(glBlendFuncSeparatei) \
macro(glColorMaski) \
macro(glIsEnabledi)
using PFN_glEnablei = PFNGLENABLEIOESPROC;
using PFN_glDisablei = PFNGLDISABLEIOESPROC;
using PFN_glBlendEquationi = PFNGLBLENDEQUATIONIOESPROC;
using PFN_glBlendEquationSeparatei = PFNGLBLENDEQUATIONSEPARATEIOESPROC;
using PFN_glBlendFunci = PFNGLBLENDFUNCIOESPROC;
using PFN_glBlendFuncSeparatei = PFNGLBLENDFUNCSEPARATEIOESPROC;
using PFN_glColorMaski = PFNGLCOLORMASKIOESPROC;
using PFN_glIsEnabledi = PFNGLISENABLEDIOESPROC;
#define DECLARE_OGL_SYMBOL(name) extern PFN_##name name;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
APPLY_OGL_DRAW_BUFFERS_INDEXED_SYMBOLS(DECLARE_OGL_SYMBOL);
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLDataUsage(Heap_type type)
{
switch (type) {
case Heap_type::local:
return GL_STATIC_DRAW;
case Heap_type::upload:
return GL_DYNAMIC_DRAW;
case Heap_type::readback:
return GL_DYNAMIC_DRAW;
default:
throw std::runtime_error("invalid heap type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLTextureTarget(Image_type type)
{
switch (type) {
case Image_type::two_dim:
return GL_TEXTURE_2D;
case Image_type::cube:
return GL_TEXTURE_CUBE_MAP;
default:
throw std::runtime_error("invalid image type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLInternalFormat(Format format)
{
switch (format) {
case Format::rgba8_unorm:
return GL_RGBA8;
case Format::bgra8_unorm:
return GL_RGBA8;
default:
throw std::runtime_error("invalid format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLFormat(Format format)
{
switch (format) {
case Format::rgba8_unorm:
return GL_RGBA;
case Format::bgra8_unorm:
return GL_RGBA;
default:
throw std::runtime_error("invalid format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLDataType(Format format)
{
switch (format) {
case Format::rgb8_unorm:
return GL_UNSIGNED_BYTE;
case Format::rgba8_unorm:
return GL_UNSIGNED_BYTE;
case Format::bgra8_unorm:
return GL_UNSIGNED_BYTE;
case Format::r32_float:
return GL_FLOAT;
case Format::rg32_float:
return GL_FLOAT;
case Format::rgb32_float:
return GL_FLOAT;
case Format::rgba32_float:
return GL_FLOAT;
case Format::d24_unorm_s8_uint:
return GL_UNSIGNED_INT_24_8;
default:
throw std::runtime_error("invalid format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLSamplerParam(Filter filter)
{
switch (filter) {
case Filter::nearest:
return GL_NEAREST;
case Filter::linear:
return GL_LINEAR;
default:
throw std::runtime_error("invalid the filter");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLSamplerParam(Filter min_filter, Mip_filter mip_filter)
{
if (Filter::nearest == min_filter) {
switch (mip_filter) {
case Mip_filter::nearest:
return GL_NEAREST_MIPMAP_NEAREST;
case Mip_filter::linear:
return GL_NEAREST_MIPMAP_LINEAR;
default:
throw std::runtime_error("invalid the filter");
}
}
else {
switch (mip_filter) {
case Mip_filter::nearest:
return GL_LINEAR_MIPMAP_NEAREST;
case Mip_filter::linear:
return GL_LINEAR_MIPMAP_LINEAR;
default:
throw std::runtime_error("invalid the filter");
}
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLSamplerWrapMode(Address_mode mode)
{
switch (mode) {
case Address_mode::repeat:
return GL_REPEAT;
case Address_mode::clamp_to_edge:
return GL_CLAMP_TO_EDGE;
default:
throw std::runtime_error("invalid the address mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLShaderType(Sc_lib::Shader_type type)
{
switch (type) {
case Sc_lib::Shader_type::vertex:
return GL_VERTEX_SHADER;
case Sc_lib::Shader_type ::fragment:
return GL_FRAGMENT_SHADER;
default:
throw std::runtime_error("invalid shader type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLPrimitiveMode(Topology topology)
{
switch (topology) {
case Topology::triangle_list:
return GL_TRIANGLES;
case Topology::triangle_strip:
return GL_TRIANGLE_STRIP;
case Topology::point:
return GL_POINTS;
default:
throw std::runtime_error("invalid the topology");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLIndexType(Index_type type)
{
switch (type) {
case Index_type::uint16:
return GL_UNSIGNED_SHORT;
case Index_type::uint32:
return GL_UNSIGNED_INT;
default:
throw std::runtime_error("invalid the index type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLCullMode(Cull_mode mode)
{
switch (mode) {
case Cull_mode::front:
return GL_FRONT;
case Cull_mode::back:
return GL_BACK;
case Cull_mode::none:
return GL_NONE;
default:
throw std::runtime_error("invalid the cull mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLCompareFunc(Compare_op op)
{
switch (op) {
case Compare_op::never:
return GL_NEVER;
case Compare_op::less:
return GL_LESS;
case Compare_op::greater:
return GL_GREATER;
case Compare_op::equal:
return GL_EQUAL;
case Compare_op::not_equal:
return GL_NOTEQUAL;
case Compare_op::less_or_equal:
return GL_LEQUAL;
case Compare_op::greater_or_equal:
return GL_GEQUAL;
case Compare_op::always:
return GL_ALWAYS;
default:
throw std::runtime_error("invalid the compare op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLBlendFactor(Blend_factor factor)
{
switch (factor) {
case Blend_factor::zero:
return GL_ZERO;
case Blend_factor::one:
return GL_ONE;
case Blend_factor::src_alpha:
return GL_SRC_ALPHA;
case Blend_factor::one_minus_src_alpha:
return GL_ONE_MINUS_SRC_ALPHA;
case Blend_factor::dst_alpha:
return GL_DST_ALPHA;
case Blend_factor::one_minus_dst_alpha:
return GL_ONE_MINUS_DST_ALPHA;
default:
throw std::runtime_error("invalid the blend factor");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline GLenum to_GLBlendFunc(Blend_op op)
{
switch (op) {
case Blend_op::add:
return GL_FUNC_ADD;
case Blend_op::subtract:
return GL_FUNC_SUBTRACT;
case Blend_op::reverse_subtract:
return GL_FUNC_REVERSE_SUBTRACT;
case Blend_op::min:
return GL_MIN;
case Blend_op::max:
return GL_MAX;
default:
throw std::runtime_error("invalid the blend op");
}
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_LIB_GUARD<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_DEVICE_GUARD
#define GFX_DEVICE_GUARD
#include <memory>
#include "enums.h"
#include "Buffer.h"
#include "Image.h"
#include "Sampler.h"
#include "Shader.h"
#include "Pipeline.h"
#include "Swap_chain.h"
#include "Cmd_buffer.h"
#include "Fence.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
struct Caps final {
Coords window_coords {Coords::invalid};
Coords texture_coords {Coords::invalid};
};
//----------------------------------------------------------------------------------------------------------------------
class Device {
public:
static std::unique_ptr<Device> create();
virtual ~Device() = default;
virtual std::unique_ptr<Buffer> create(const Buffer_desc& desc) = 0;
virtual std::unique_ptr<Image> create(const Image_desc& desc) = 0;
virtual std::unique_ptr<Sampler> create(const Sampler_desc& desc) = 0;
virtual std::unique_ptr<Shader> create(const Shader_desc& desc) = 0;
virtual std::unique_ptr<Pipeline> create(const Pipeline_desc& desc) = 0;
virtual std::unique_ptr<Swap_chain> create(const Swap_chain_desc& desc) = 0;
virtual std::unique_ptr<Cmd_buffer> create(const Cmd_buffer_desc& desc) = 0;
virtual std::unique_ptr<Fence> create(const Fence_desc& desc) = 0;
virtual void submit(Cmd_buffer* cmd_buffer, Fence* fence = nullptr) = 0;
virtual void wait_idle() = 0;
inline auto caps() const noexcept
{ return caps_; }
protected:
Caps caps_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_DEVICE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_SET_LAYOUT_GUARD
#define GFX_VLK_SET_LAYOUT_GUARD
#include <vector>
#include <vulkan/vulkan.h>
#include "enums.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_set_layout_desc {
std::vector<VkDescriptorSetLayoutBinding> bindings;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_set_layout final {
public:
Vlk_set_layout(const Vlk_set_layout_desc& desc, Vlk_device* device);
~Vlk_set_layout();
inline auto& desc_set_layout() const noexcept
{ return desc_set_layout_; }
VkDescriptorSet desc_set();
private:
void init_desc_set_layout_(const Vlk_set_layout_desc& desc);
void init_desc_pool_(const Vlk_set_layout_desc& desc);
void fini_desc_set_layout_();
void fini_desc_pool_();
private:
Vlk_device* device_;
VkDescriptorSetLayout desc_set_layout_;
VkDescriptorPool desc_pool_;
std::vector<VkDescriptorSet> desc_sets_;
uint64_t desc_set_index_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_SET_LAYOUT_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <platform/build_target.h>
#include "Device.h"
#if TARGET_OS_IOS || TARGET_OS_OSX
#include "Mtl_device.h"
#endif
#if defined(__ANDROID__) || defined(_WIN32)
#include "Vlk_device.h"
#endif
#if defined(__ANDROID__)
#include "Ogl_device.h"
#endif
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Device> Device::create()
{
#if TARGET_OS_IOS || TARGET_OS_OSX
return make_unique<Mtl_device>();
#endif
#if defined(__ANDROID__)
try {
return make_unique<Vlk_device>();
}
catch (exception& e) {
return make_unique<Ogl_device>();
}
#endif
#if defined(_WIN32)
return make_unique<Vlk_device>();
#endif
return nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_BUFFER_GUARD
#define GFX_BUFFER_GUARD
#include <cstddef>
#include "enums.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
//----------------------------------------------------------------------------------------------------------------------
struct Buffer_desc final {
const void* data {nullptr};
uint64_t size {0};
Heap_type heap_type {Heap_type::upload};
};
//----------------------------------------------------------------------------------------------------------------------
class Buffer {
public:
explicit Buffer(const Buffer_desc& desc) noexcept :
size_ {desc.size},
heap_type_ {desc.heap_type}
{}
virtual ~Buffer() = default;
virtual void* map() = 0;
virtual void unmap() = 0;
virtual Device* device() const = 0;
inline uint64_t size() const noexcept
{ return size_; }
inline Heap_type heap_type() const noexcept
{ return heap_type_; }
protected:
uint64_t size_;
Heap_type heap_type_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_FENCE_GUARD
#define GFX_MTL_FENCE_GUARD
#include <dispatch/dispatch.h>
#include "Fence.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_fence final : public Fence {
public:
Mtl_fence(const Fence_desc& desc, Mtl_device* device);
void wait_signal() override;
void reset() override;
Device* device() const override;
bool signaled() const override;
inline auto semaphore() const noexcept
{ return semaphore_; }
private:
void init_semaphore_();
private:
Mtl_device* device_;
bool signaled_;
dispatch_semaphore_t semaphore_;
friend class Mtl_device;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_FENCE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_SHADER_GUARD
#define GFX_SHADER_GUARD
#include <vector>
#include <sc/enums.h>
#include <sc/Spirv_reflector.h>
#include "enums.h"
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
//----------------------------------------------------------------------------------------------------------------------
struct Shader_desc final {
Sc_lib::Shader_type type;
std::vector<uint32_t> src;
};
//----------------------------------------------------------------------------------------------------------------------
class Shader {
public:
explicit Shader(const Shader_desc& desc) :
type_ {desc.type}
{}
virtual ~Shader() = default;
virtual Device* device() const = 0;
virtual Sc_lib::Signature reflect() const noexcept = 0;
inline Sc_lib::Shader_type type() const noexcept
{ return type_; }
protected:
Sc_lib::Shader_type type_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_SHADER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_FRAMEBUFFER_GUARD
#define GFX_VLK_FRAMEBUFFER_GUARD
#include <array>
#include <vulkan/vulkan.h>
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_image;
class Vlk_render_pass;
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_framebuffer_desc {
Vlk_render_pass* render_pass;
std::array<Vlk_image*, 4> colors;
Vlk_image* depth_stencil;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_framebuffer final {
public:
Vlk_framebuffer(const Vlk_framebuffer_desc& desc, Vlk_device* device);
~Vlk_framebuffer();
inline auto& extent() const noexcept
{ return extent_; }
inline auto& framebuffer() const noexcept
{ return framebuffer_; }
private:
void init_extent_(const Vlk_framebuffer_desc& desc);
void init_framebuffer_(const Vlk_framebuffer_desc& desc);
void fini_framebuffer_();
private:
Vlk_device* device_;
Extent extent_;
VkFramebuffer framebuffer_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_FRAMEBUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_DEMO_GUARD
#define GFX_DEMO_GUARD
#include <unordered_map>
#include <glm/glm.hpp>
#include <platform/Window.h>
#include <sc/Spirv_compiler.h>
#include <gfx/Device.h>
//----------------------------------------------------------------------------------------------------------------------
struct Camera_cfgs {
int32_t projection {0};
glm::vec3 translation {4.5f, 8.0f, 10.0f};
float fov {45.0f};
float aspect {1.778f};
float near {0.01f};
float far {100.0f};
};
//----------------------------------------------------------------------------------------------------------------------
struct Light_cfgs {
glm::vec3 translation {-1.0f, 1.0f, 1.7f};
glm::vec3 ambient {0.4f, 0.4f, 0.4f};
glm::vec3 diffuse {1.0f, 1.0f, 1.0f};
glm::vec3 specular {1.0f, 1.0f, 1.0f};
};
//----------------------------------------------------------------------------------------------------------------------
struct Primitive_cfgs {
bool animation {true};
glm::vec3 translation {0.0f, 0.0f, 0.0f};
glm::vec3 scale {1.0f, 1.0f, 1.0f};
glm::vec3 rotation {0.0f, 0.0f, 0.0f};
int32_t style {0};
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
float shininess {100.0f};
};
//----------------------------------------------------------------------------------------------------------------------
struct Cfgs {
Camera_cfgs camera;
Light_cfgs light;
Primitive_cfgs cube;
Primitive_cfgs torus;
Primitive_cfgs sphere;
};
//----------------------------------------------------------------------------------------------------------------------
class Gfx_demo final {
public:
Gfx_demo();
~Gfx_demo();
void connect(Platform_lib::Window* window);
void render();
void touch_down();
void touch_move(float x, float y);
void touch_up();
private:
void init_cfgs_();
void init_device_();
void init_light_resources_();
void init_swap_chain_(Platform_lib::Window* window);
void init_cmd_buffer_();
void init_fence_();
void init_imgui_();
void init_imgui_resources_();
void fini_imgui_();
void record_light_render_pass_();
void record_present_render_pass_();
private:
Cfgs cfgs_;
Sc_lib::Spirv_compiler compiler_;
std::unique_ptr<Gfx_lib::Device> device_;
std::unordered_map<std::string, std::unique_ptr<Gfx_lib::Buffer>> buffers_;
std::unordered_map<std::string, uint32_t> draw_counts_;
std::unordered_map<std::string, std::unique_ptr<Gfx_lib::Image>> images_;
std::unordered_map<std::string, std::unique_ptr<Gfx_lib::Sampler>> samplers_;
std::unordered_map<std::string, std::unique_ptr<Gfx_lib::Pipeline>> pipelines_;
std::unique_ptr<Gfx_lib::Swap_chain> swap_chain_;
std::unique_ptr<Gfx_lib::Cmd_buffer> cmd_buffer_;
std::unique_ptr<Gfx_lib::Fence> fence_;
};
//----------------------------------------------------------------------------------------------------------------------
#endif // GFX_DEMO_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_PIPELINE_GUARD
#define GFX_PIPELINE_GUARD
#include <array>
#include <unordered_map>
#include "limitations.h"
#include "enums.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
class Shader;
//----------------------------------------------------------------------------------------------------------------------
struct Vertex_input_attribute final {
uint32_t binding {UINT32_MAX};
Format format {Format::invalid};
uint32_t offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Vertex_input_binding final {
uint32_t stride {UINT32_MAX};
Step_rate step_rate {Step_rate::vertex};
};
//----------------------------------------------------------------------------------------------------------------------
struct Vertex_input final {
std::array<Vertex_input_attribute, max_vertex_input_attributes> attributes;
std::array<Vertex_input_binding, max_vertex_input_bindings> bindings;
};
//----------------------------------------------------------------------------------------------------------------------
struct Input_assembly final {
Topology topology {Topology::triangle_list};
bool restart {false};
};
//----------------------------------------------------------------------------------------------------------------------
struct Rasterization final {
bool depth_clamp {false};
Cull_mode cull_mode {Cull_mode::back};
Front_face front_face {Front_face::counter_clockwise};
bool depth_bias {false};
float depth_bias_constant_factor {0.0f};
float depth_bias_clamp {1.0f};
float depth_bias_slope_factor {1.0f};
};
//----------------------------------------------------------------------------------------------------------------------
struct Multisample final {
uint8_t samples {1};
};
//----------------------------------------------------------------------------------------------------------------------
struct Stencil final {
Stencil_op stencil_fail_op {Stencil_op::keep};
Stencil_op depth_fail_op {Stencil_op::keep};
Stencil_op depth_stencil_pass_op {Stencil_op::keep};
Compare_op compare_op {Compare_op::always};
uint32_t read_mask {0xFFFF};
uint32_t write_mask {0xFFFF};
uint32_t referece {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Depth_stencil final {
bool depth_test {false};
bool write_mask {true};
Compare_op depth_compare_op {Compare_op::less};
bool stencil_test {false};
Stencil front_stencil;
Stencil back_stencil;
};
//----------------------------------------------------------------------------------------------------------------------
struct Color_blend_attachment final {
bool blend {false};
Blend_factor src_rgb_blend_factor {Blend_factor::one};
Blend_factor dst_rgb_blend_factor {Blend_factor::zero};
Blend_op rgb_blend_op {Blend_op::add};
Blend_factor src_a_blend_factor {Blend_factor::one};
Blend_factor dst_a_blend_factor {Blend_factor::zero};
Blend_op a_blend_op { Blend_op::add };
uint32_t write_mask { 0xF };
};
//----------------------------------------------------------------------------------------------------------------------
struct Color_blend final {
std::array<Color_blend_attachment, max_color_attachments> attachments;
std::array<float, max_color_attachments> constant;
};
//----------------------------------------------------------------------------------------------------------------------
struct Output_merger final {
std::array<Format, max_color_attachments> color_formats {
Format::invalid, Format::invalid, Format::invalid, Format::invalid
};
Format depth_stencil_format {Format::invalid};
};
//----------------------------------------------------------------------------------------------------------------------
struct Reflection {
std::unordered_map<uint32_t, uint32_t> buffers;
std::unordered_map<uint32_t, uint32_t> textures;
};
//----------------------------------------------------------------------------------------------------------------------
struct Pipeline_desc final {
Vertex_input vertex_input;
Input_assembly input_assembly;
Shader* vertex_shader;
Rasterization rasterization;
Shader* fragment_shader;
Multisample multisample;
Depth_stencil depth_stencil;
Color_blend color_blend;
Output_merger output_merger;
};
//----------------------------------------------------------------------------------------------------------------------
class Pipeline {
public:
explicit Pipeline(const Pipeline_desc& desc);
virtual ~Pipeline() = default;
virtual Device* device() const = 0;
inline auto vertex_input() const noexcept
{ return vertex_input_; }
inline auto input_assembly() const noexcept
{ return input_assembly_; }
inline auto rasterization() const noexcept
{ return rasterization_; }
inline auto multisample() const noexcept
{ return multisample_; }
inline auto depth_stencil() const noexcept
{ return depth_stencil_; }
inline auto color_blend() const noexcept
{ return color_blend_; }
inline auto output_merger() const noexcept
{ return output_merger_; }
inline auto reflection() const noexcept
{ return reflection_; }
private:
void init_reflection_(const std::vector<Shader*> shaders);
protected:
Vertex_input vertex_input_;
Input_assembly input_assembly_;
Rasterization rasterization_;
Multisample multisample_;
Depth_stencil depth_stencil_;
Color_blend color_blend_;
Output_merger output_merger_;
Reflection reflection_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_PIPELINE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_STD_LIB_MODULES_GUARD
#define GFX_STD_LIB_MODULES_GUARD
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <iostream>
#include <memory>
#include <array>
#include <vector>
#include <deque>
#include <unordered_map>
#include <algorithm>
#include <mutex>
//----------------------------------------------------------------------------------------------------------------------
template<typename T>
inline auto etoi(T e) noexcept
{
return static_cast<typename std::underlying_type<T>::type>(e);
}
//----------------------------------------------------------------------------------------------------------------------
template<typename R, typename F>
inline F for_each(R& range, F func)
{
return std::for_each(std::begin(range), std::end(range), func);
}
//----------------------------------------------------------------------------------------------------------------------
template<typename R, typename O, typename F>
inline O transform(R& range, O iter, F func)
{
return std::transform(std::begin(range), std::end(range), iter, func);
}
//----------------------------------------------------------------------------------------------------------------------
template<typename R, typename F>
inline auto find_if(R& range, F func)
{
return std::find_if(std::begin(range), std::end(range), func);
}
//----------------------------------------------------------------------------------------------------------------------
#endif // GFX_STD_LIB_MODULES_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_pipeline.h"
#include "Vlk_device.h"
#include "Vlk_shader.h"
#include "Vlk_render_pass.h"
#include "Vlk_set_layout.h"
using namespace std;
using namespace Sc_lib;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline auto to_VkShaderStageFlags(uint32_t stages)
{
VkShaderStageFlags flags {0};
if (stages & etoi(Pipeline_stage::vertex_shader))
flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
if (stages & etoi(Pipeline_stage::fragment_shader))
flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
return flags;
}
//----------------------------------------------------------------------------------------------------------------------
inline auto to_VkPipelineShaderStageCreateInfo(Shader* shader)
{
VkPipelineShaderStageCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
create_info.stage = to_VkShaderStageFlagBits(shader->type());
create_info.module = static_cast<Vlk_shader*>(shader)->shader_module();
create_info.pName = "main";
return create_info;
}
//----------------------------------------------------------------------------------------------------------------------
inline auto to_VkStencilOpState(const Stencil& stencil)
{
VkStencilOpState state {};
state.failOp = to_VkStencilOp(stencil.stencil_fail_op);
state.passOp = to_VkStencilOp(stencil.depth_stencil_pass_op);
state.depthFailOp = to_VkStencilOp(stencil.depth_fail_op);
state.compareOp = to_VkCompareOp(stencil.compare_op);
state.compareMask = stencil.read_mask;
state.writeMask = stencil.write_mask;
state.reference = stencil.referece;
return state;
}
//----------------------------------------------------------------------------------------------------------------------
inline auto to_Render_pass_desc(const Multisample &multisample, const Output_merger &output_merger)
{
// configure a render pass desc.
Vlk_render_pass_desc render_pass_desc {};
for (auto i = 0; i != 4; ++i) {
render_pass_desc.colors[i].format = output_merger.color_formats[i];
render_pass_desc.colors[i].samples = multisample.samples;
}
render_pass_desc.depth_stencil.format = output_merger.depth_stencil_format;
render_pass_desc.depth_stencil.samples = multisample.samples;
return render_pass_desc;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_pipeline::Vlk_pipeline(const Pipeline_desc& desc, Vlk_device* device) :
Pipeline {desc},
device_ {device},
pipeline_layout_ {VK_NULL_HANDLE},
pipeline_ {VK_NULL_HANDLE}
{
init_set_layouts_(desc.vertex_shader, desc.fragment_shader);
init_pipeline_layout_();
init_pipeline_(desc.vertex_shader, desc.fragment_shader);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_pipeline::~Vlk_pipeline()
{
fini_pipeline_();
fini_pipeline_layout_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_pipeline::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_pipeline::init_set_layouts_(Shader* vertex_shader, Shader* fragment_shader)
{
Vlk_set_layout_desc buffer_set_layout_desc;
auto& buffer_bindings = buffer_set_layout_desc.bindings;
for (auto& [index, stages] : reflection_.buffers) {
VkDescriptorSetLayoutBinding binding {};
binding.binding = index;
binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
binding.descriptorCount = 1;
binding.stageFlags = to_VkShaderStageFlags(stages);
buffer_bindings.emplace_back(binding);
}
if (!buffer_bindings.empty())
set_layouts_[0] = make_unique<Vlk_set_layout>(buffer_set_layout_desc, device_);
Vlk_set_layout_desc texture_set_layout_desc;
auto& texture_bindings = texture_set_layout_desc.bindings;
for (auto& [index, stages] : reflection_.textures) {
VkDescriptorSetLayoutBinding binding {};
binding.binding = index;
binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
binding.descriptorCount = 1;
binding.stageFlags = to_VkShaderStageFlags(stages);
texture_bindings.push_back(binding);
}
if (!texture_bindings.empty())
set_layouts_[1] = make_unique<Vlk_set_layout>(texture_set_layout_desc, device_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_pipeline::init_pipeline_layout_()
{
std::vector<VkDescriptorSetLayout> desc_set_layouts;
for (auto& set_layout : set_layouts_) {
desc_set_layouts.push_back(set_layout->desc_set_layout());
}
VkPipelineLayoutCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
create_info.setLayoutCount = static_cast<uint32_t>(desc_set_layouts.size());
create_info.pSetLayouts = &desc_set_layouts[0];
if (vkCreatePipelineLayout(device_->device(), &create_info, nullptr, &pipeline_layout_))
throw runtime_error("fail to create a pipeline.");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_pipeline::init_pipeline_(Shader* vertex_shader, Shader* fragment_shader)
{
// configure a vertex and a fragment shader stages.
array<VkPipelineShaderStageCreateInfo, 2> shader_stages {
to_VkPipelineShaderStageCreateInfo(vertex_shader),
to_VkPipelineShaderStageCreateInfo(fragment_shader)
};
// configure vertex input bindings.
vector<VkVertexInputBindingDescription> vertex_input_bindings;
for (auto i = 0; i != 2; ++i) {
if (UINT32_MAX == vertex_input_.bindings[i].stride)
continue;
VkVertexInputBindingDescription binding {};
binding.binding = static_cast<uint32_t>(i);
binding.stride = vertex_input_.bindings[i].stride;
binding.inputRate = to_VkVertexInputRate(vertex_input_.bindings[i].step_rate);
vertex_input_bindings.push_back(binding);
}
// configure vertex input attributes.
vector<VkVertexInputAttributeDescription> vertex_input_attributes;
for (auto i = 0; i != 16; ++i) {
if (UINT32_MAX == vertex_input_.attributes[i].binding)
continue;
VkVertexInputAttributeDescription attribute {};
attribute.location = static_cast<uint32_t>(i);
attribute.binding = vertex_input_.attributes[i].binding;
attribute.format = to_VkFormat(vertex_input_.attributes[i].format);
attribute.offset = vertex_input_.attributes[i].offset;
vertex_input_attributes.push_back(attribute);
}
// configure a vertex input stage.
VkPipelineVertexInputStateCreateInfo vertex_input_state {};
vertex_input_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state.vertexBindingDescriptionCount = static_cast<uint32_t>(vertex_input_bindings.size());
vertex_input_state.pVertexBindingDescriptions = &vertex_input_bindings[0];
vertex_input_state.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_input_attributes.size());
vertex_input_state.pVertexAttributeDescriptions = &vertex_input_attributes[0];
// configure an input assembly state.
VkPipelineInputAssemblyStateCreateInfo input_assembly_state {};
input_assembly_state.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly_state.topology = to_VkPrimitiveTopology(input_assembly_.topology);
input_assembly_state.primitiveRestartEnable = static_cast<VkBool32>(input_assembly_.restart);
// configure a viewport state create info.
VkPipelineViewportStateCreateInfo viewport_state {};
viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state.viewportCount = 1;
viewport_state.scissorCount = 1;
// configure a rasterization state.
VkPipelineRasterizationStateCreateInfo rasterization_state {};
rasterization_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterization_state.depthClampEnable = rasterization_.depth_clamp;
rasterization_state.polygonMode = VK_POLYGON_MODE_FILL;
rasterization_state.cullMode = to_VkCullModeFlags(rasterization_.cull_mode);
rasterization_state.frontFace = to_VkFrontFace(rasterization_.front_face);
rasterization_state.depthBiasEnable = rasterization_.depth_bias;
rasterization_state.depthBiasConstantFactor = rasterization_.depth_bias_constant_factor;
rasterization_state.depthBiasClamp = rasterization_.depth_bias_clamp;
rasterization_state.depthBiasSlopeFactor = rasterization_.depth_bias_slope_factor;
// configure a multisample state create info.
VkPipelineMultisampleStateCreateInfo multisample_state {};
multisample_state.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisample_state.rasterizationSamples = to_VkSampleCountFlagBits(multisample_.samples);
// configure a depth stencil state.
VkPipelineDepthStencilStateCreateInfo depth_stencil_state {};
depth_stencil_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil_state.depthTestEnable = depth_stencil_.depth_test;
depth_stencil_state.depthWriteEnable = depth_stencil_.write_mask;
depth_stencil_state.depthCompareOp = to_VkCompareOp(depth_stencil_.depth_compare_op);
depth_stencil_state.stencilTestEnable = depth_stencil_.stencil_test;
depth_stencil_state.front = to_VkStencilOpState(depth_stencil_.front_stencil);
depth_stencil_state.back = to_VkStencilOpState(depth_stencil_.back_stencil);
depth_stencil_state.minDepthBounds = 0.0f;
depth_stencil_state.maxDepthBounds = 1.0f;
// configure pipeline color blend attachment states.
std::vector<VkPipelineColorBlendAttachmentState> color_blend_attachment_states;
for (auto i = 0; i != 4; ++i) {
if (Format::invalid == output_merger_.color_formats[i])
continue;
auto& attachment = color_blend_.attachments[i];
VkPipelineColorBlendAttachmentState attachment_state {};
attachment_state.blendEnable = attachment.blend;
attachment_state.srcColorBlendFactor = to_VkBlendFactor(attachment.src_rgb_blend_factor);
attachment_state.dstColorBlendFactor = to_VkBlendFactor(attachment.dst_rgb_blend_factor);
attachment_state.colorBlendOp = to_VkBlendOp(attachment.rgb_blend_op);
attachment_state.srcAlphaBlendFactor = to_VkBlendFactor(attachment.src_a_blend_factor);
attachment_state.dstAlphaBlendFactor = to_VkBlendFactor(attachment.dst_a_blend_factor);
attachment_state.alphaBlendOp = to_VkBlendOp(attachment.a_blend_op);
attachment_state.colorWriteMask = attachment.write_mask;
color_blend_attachment_states.push_back(attachment_state);
}
// configure pipeline color blend state info.
VkPipelineColorBlendStateCreateInfo color_blend_state {};
color_blend_state.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend_state.attachmentCount = color_blend_attachment_states.size();
color_blend_state.pAttachments = &color_blend_attachment_states[0];
color_blend_state.blendConstants[0] = color_blend_.constant[0];
color_blend_state.blendConstants[1] = color_blend_.constant[1];
color_blend_state.blendConstants[2] = color_blend_.constant[2];
color_blend_state.blendConstants[3] = color_blend_.constant[3];
constexpr array<VkDynamicState, 4> dynamic_states {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR,
VK_DYNAMIC_STATE_LINE_WIDTH,
VK_DYNAMIC_STATE_DEPTH_BIAS
};
// configure dynamic state create info.
VkPipelineDynamicStateCreateInfo dynamic_state {};
dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state.dynamicStateCount = dynamic_states.size();
dynamic_state.pDynamicStates = &dynamic_states[0];
// configure a graphics pipeline create info.
VkGraphicsPipelineCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
create_info.stageCount = shader_stages.size();
create_info.pStages = &shader_stages[0];
create_info.pVertexInputState = &vertex_input_state;
create_info.pInputAssemblyState = &input_assembly_state;
create_info.pViewportState = &viewport_state;
create_info.pRasterizationState= &rasterization_state;
create_info.pMultisampleState = &multisample_state;
create_info.pDepthStencilState = &depth_stencil_state;
create_info.pColorBlendState = &color_blend_state;
create_info.pDynamicState = &dynamic_state;
create_info.layout = pipeline_layout_;
create_info.renderPass = device_->render_pass(to_Render_pass_desc(multisample_, output_merger_))->render_pass();
// try to create a graphics pipeline.
if (vkCreateGraphicsPipelines(device_->device(), device_->pipeline_cache(), 1, &create_info, nullptr, &pipeline_))
throw runtime_error("fail to create a pipeline.");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_pipeline::fini_pipeline_layout_()
{
vkDestroyPipelineLayout(device_->device(), pipeline_layout_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_pipeline::fini_pipeline_()
{
vkDestroyPipeline(device_->device(), pipeline_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_FRAMEBUFFER_GUARD
#define GFX_OGL_FRAMEBUFFER_GUARD
#include <array>
#include <GLES3/gl3.h>
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
class Ogl_image;
//----------------------------------------------------------------------------------------------------------------------
struct Ogl_framebuffer_desc {
std::array<Ogl_image*, 4> colors;
Ogl_image* depth_stencil;
};
//----------------------------------------------------------------------------------------------------------------------
class Ogl_framebuffer final {
public:
Ogl_framebuffer(const Ogl_framebuffer_desc& desc, Ogl_device* device);
~Ogl_framebuffer();
inline auto extent() const noexcept
{ return extent_; }
inline auto color_image(uint64_t index) const noexcept
{ return colors_[index]; }
inline auto depth_stencil() const noexcept
{ return depth_stencil_; }
inline auto framebuffer() const noexcept
{ return framebuffer_; }
private:
void init_extent_();
void init_framebuffer_();
void fini_framebuffer_();
private:
Ogl_device* device_;
std::array<Ogl_image*, 4> colors_;
Ogl_image* depth_stencil_;
Extent extent_;
GLuint framebuffer_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_FRAMEBUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "ogl_lib.h"
#include "Ogl_sampler.h"
#include "Ogl_device.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_sampler::Ogl_sampler(const Sampler_desc& desc, Ogl_device* device) :
Sampler {desc},
device_ {device},
sampler_ {0}
{
init_sampler_();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_sampler::~Ogl_sampler()
{
fini_sampler_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_sampler::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_sampler::init_sampler_()
{
glGenSamplers(1, &sampler_);
glSamplerParameteri(sampler_, GL_TEXTURE_MIN_LOD, 0);
glSamplerParameteri(sampler_, GL_TEXTURE_MIN_FILTER, to_GLSamplerParam(min_, mip_));
glSamplerParameteri(sampler_, GL_TEXTURE_MAG_FILTER, to_GLSamplerParam(mag_));
glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_S, to_GLSamplerWrapMode(u_));
glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_T, to_GLSamplerWrapMode(v_));
// glSamplerParameteri(sampler_, GL_TEXTURE_WRAP_R, to_GLSamplerWrapMode(w_));
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_sampler::fini_sampler_()
{
glDeleteSamplers(1, &sampler_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_LIB_GUARD
#define GFX_MTL_LIB_GUARD
#include <stdexcept>
#include <Metal/Metal.h>
#include "limitations.h"
#include "enums.h"
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
constexpr auto vertex_buffer_index_offset = 31 - max_vertex_input_bindings;
//----------------------------------------------------------------------------------------------------------------------
inline MTLResourceOptions to_MTLResourceOptions(Heap_type type)
{
switch (type) {
case Heap_type::local:
return MTLResourceStorageModePrivate;
case Heap_type::upload:
return MTLResourceCPUCacheModeWriteCombined;
case Heap_type::readback:
return MTLResourceCPUCacheModeDefaultCache;
default:
throw std::runtime_error("invalid the heap type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLTextureType to_MTLTextureType(Image_type type)
{
switch (type) {
case Image_type::two_dim:
return MTLTextureType2D;
case Image_type::cube:
return MTLTextureTypeCube;
default:
throw std::runtime_error("invalid the image type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLPixelFormat to_MTLPixelFormat(Format format)
{
switch (format) {
case Format::rgba8_unorm:
return MTLPixelFormatRGBA8Unorm;
case Format::bgra8_unorm:
return MTLPixelFormatBGRA8Unorm;
case Format::r32_float:
return MTLPixelFormatR32Float;
case Format::rg32_float:
return MTLPixelFormatRG32Float;
case Format::rgba32_float:
return MTLPixelFormatRGBA32Float;
case Format::d24_unorm_s8_uint:
return MTLPixelFormatDepth32Float_Stencil8;
default:
throw std::runtime_error("invalid the format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLSamplerMinMagFilter to_MTLSamplerMinMagFilter(Filter filter)
{
switch (filter) {
case Filter::nearest:
return MTLSamplerMinMagFilterNearest;
case Filter::linear:
return MTLSamplerMinMagFilterLinear;
default:
throw std::runtime_error("invalid the filter");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLSamplerMipFilter to_MTLSamplerMipFilter(Mip_filter filter)
{
switch (filter) {
case Mip_filter::nearest:
return MTLSamplerMipFilterNearest;
case Mip_filter::linear:
return MTLSamplerMipFilterLinear;
default:
throw std::runtime_error("invalid the filter");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLSamplerAddressMode to_MTLSamplerAddressMode(Address_mode mode)
{
switch (mode) {
case Address_mode::repeat:
return MTLSamplerAddressModeRepeat;
case Address_mode::clamp_to_edge:
return MTLSamplerAddressModeClampToEdge;
default:
throw std::runtime_error("invalid the address mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLVertexStepFunction to_MTLVertexStepFunction(Step_rate rate)
{
switch (rate) {
case Step_rate::vertex:
return MTLVertexStepFunctionPerVertex;
case Step_rate::instance:
return MTLVertexStepFunctionPerInstance;
default:
throw std::runtime_error("invalid the step rate");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLVertexFormat to_MTLVertexFormat(Format format)
{
switch (format) {
case Format::rgb8_unorm:
return MTLVertexFormatUChar3;
case Format::rgba8_unorm:
return MTLVertexFormatUChar4;
case Format::rg32_float:
return MTLVertexFormatFloat2;
case Format::rgb32_float:
return MTLVertexFormatFloat3;
case Format::rgba32_float:
return MTLVertexFormatFloat4;
default:
throw std::runtime_error("invalid the format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLIndexType to_MTLIndexType(Index_type type)
{
switch (type) {
case Index_type::uint16:
return MTLIndexTypeUInt16;
case Index_type::uint32:
return MTLIndexTypeUInt32;
default:
throw std::runtime_error("invalid the index type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLBlendFactor to_MTLBlendFactor(Blend_factor factor)
{
switch (factor) {
case Blend_factor::zero:
return MTLBlendFactorZero;
case Blend_factor::one:
return MTLBlendFactorOne;
case Blend_factor::src_alpha:
return MTLBlendFactorSourceAlpha;
case Blend_factor::one_minus_src_alpha:
return MTLBlendFactorOneMinusSourceAlpha;
case Blend_factor::dst_alpha:
return MTLBlendFactorDestinationAlpha;
case Blend_factor::one_minus_dst_alpha:
return MTLBlendFactorOneMinusDestinationAlpha;
default:
throw std::runtime_error("invalid the blend factor");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLBlendOperation to_MTLBlendOperation(Blend_op op)
{
switch (op) {
case Blend_op::add:
return MTLBlendOperationAdd;
case Blend_op::subtract:
return MTLBlendOperationSubtract;
case Blend_op::reverse_subtract:
return MTLBlendOperationReverseSubtract;
case Blend_op::min:
return MTLBlendOperationMin;
case Blend_op::max:
return MTLBlendOperationMax;
default:
throw std::runtime_error("invalid the blend op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLPrimitiveTopologyClass to_MTLPrimitiveTopologyClass(Topology topology)
{
switch (topology) {
case Topology::triangle_list:
case Topology::triangle_strip:
return MTLPrimitiveTopologyClassTriangle;
case Topology::point:
return MTLPrimitiveTopologyClassPoint;
default:
throw std::runtime_error("invalid the topology");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLPrimitiveType to_MTLPrimitiveType(Topology topology)
{
switch (topology) {
case Topology::triangle_list:
return MTLPrimitiveTypeTriangle;
case Topology::triangle_strip:
return MTLPrimitiveTypeTriangleStrip;
case Topology::point:
return MTLPrimitiveTypePoint;
default:
throw std::runtime_error("invalid the topology");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLCullMode to_MTLCullMode(Cull_mode mode)
{
switch (mode) {
case Cull_mode::front:
return MTLCullModeFront;
case Cull_mode::back:
return MTLCullModeBack;
case Cull_mode::none:
return MTLCullModeNone;
default:
throw std::runtime_error("invalid the cull mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLWinding to_MTLWinding(Front_face face)
{
switch (face) {
case Front_face::counter_clockwise:
return MTLWindingCounterClockwise;
case Front_face::clockwise:
return MTLWindingClockwise;
default:
throw std::runtime_error("invalid the front face");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLStencilOperation to_MTLStencilOperation(Stencil_op op)
{
switch (op) {
case Stencil_op::keep:
return MTLStencilOperationKeep;
case Stencil_op::zero:
return MTLStencilOperationZero;
case Stencil_op::replace:
return MTLStencilOperationReplace;
case Stencil_op::increment_and_clamp:
return MTLStencilOperationIncrementClamp;
case Stencil_op::decrement_and_clamp:
return MTLStencilOperationDecrementClamp;
case Stencil_op::invert:
return MTLStencilOperationInvert;
case Stencil_op::increment_and_wrap:
return MTLStencilOperationIncrementWrap;
case Stencil_op::decrement_and_wrap:
return MTLStencilOperationDecrementWrap;
default:
throw std::runtime_error("invalid the stencil op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLCompareFunction to_MTLCompareFunction(Compare_op op)
{
switch (op) {
case Compare_op::never:
return MTLCompareFunctionNever;
case Compare_op::less:
return MTLCompareFunctionLess;
case Compare_op::greater:
return MTLCompareFunctionGreater;
case Compare_op::equal:
return MTLCompareFunctionEqual;
case Compare_op::not_equal:
return MTLCompareFunctionNotEqual;
case Compare_op::less_or_equal:
return MTLCompareFunctionLessEqual;
case Compare_op::greater_or_equal:
return MTLCompareFunctionGreaterEqual;
case Compare_op::always:
return MTLCompareFunctionAlways;
default:
throw std::runtime_error("invalid the stencil op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLLoadAction to_MTLLoadAction(Load_op op)
{
switch (op) {
case Load_op::load:
return MTLLoadActionLoad;
case Load_op::clear:
return MTLLoadActionClear;
case Load_op::dont_care:
return MTLLoadActionDontCare;
default:
throw std::runtime_error("invalid the load op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLStoreAction to_MTLStoreAction(Store_op op)
{
switch (op) {
case Store_op::store:
return MTLStoreActionStore;
case Store_op::dont_care:
return MTLStoreActionDontCare;
default:
throw std::runtime_error("invalid the store op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLClearColor to_MTLClearColor(Clear_value clear_value)
{
return MTLClearColorMake(clear_value.r, clear_value.g, clear_value.b, clear_value.a);
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLViewport to_MTLViewport(Viewport viewport)
{
return { viewport.x, viewport.y, viewport.w, viewport.h, 0.0, 1.0 };
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLScissorRect to_MTLScissorRect(Scissor scissor)
{
return { scissor.x, scissor.y, scissor.w, scissor.h };
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLOrigin to_MTLOrigin(Offset offset)
{
return MTLOriginMake(offset.x, offset.y, offset.z);
}
//----------------------------------------------------------------------------------------------------------------------
inline MTLSize to_MTLSize(Extent extent)
{
return MTLSizeMake(extent.w, extent.h, extent.d);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_LIB_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_SHADER_GUARD
#define GFX_MTL_SHADER_GUARD
#include <Metal/Metal.h>
#include "Shader.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_shader final : public Shader {
public:
Mtl_shader(const Shader_desc& desc, Mtl_device* device);
Device* device() const override;
Sc_lib::Signature reflect() const noexcept override;
inline auto function() const noexcept
{ return function_; }
private:
void init_signature_(const std::vector<uint32_t>& src);
void init_function_(const std::string& src);
private:
Mtl_device* device_;
Sc_lib::Signature signature_;
id<MTLFunction> function_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_SHADER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_framebuffer.h"
#include "Vlk_device.h"
#include "Vlk_image.h"
#include "Vlk_render_pass.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_framebuffer::Vlk_framebuffer(const Vlk_framebuffer_desc& desc, Vlk_device* device) :
device_ { device },
extent_ { 0, 0, 1 },
framebuffer_ { VK_NULL_HANDLE }
{
init_extent_(desc);
init_framebuffer_(desc);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_framebuffer::~Vlk_framebuffer()
{
fini_framebuffer_();
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_framebuffer::init_extent_(const Vlk_framebuffer_desc& desc)
{
extent_ = desc.colors[0]->extent();
// check all attachments has a same extent.
for (auto i = 1; i != 4; ++i) {
auto& color = desc.colors[i];
if (!color)
continue;
if (color->extent() != extent_)
throw runtime_error("fail to create a framebuffer");
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil) {
if (depth_stencil->extent() != extent_)
throw runtime_error("fail to create a framebuffer");
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_framebuffer::init_framebuffer_(const Vlk_framebuffer_desc& desc)
{
// collect image view.
vector<VkImageView> image_views;
for (auto& color : desc.colors) {
if (!color)
continue;
image_views.push_back(color->image_view());
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil)
image_views.push_back(depth_stencil->image_view());
// configure a framebuffer create info.
VkFramebufferCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
create_info.renderPass = desc.render_pass->render_pass();
create_info.attachmentCount = image_views.size();
create_info.pAttachments = &image_views[0];
create_info.width = extent_.w;
create_info.height = extent_.h;
create_info.layers = 1;
// try to create a framebuffer.
if (vkCreateFramebuffer(device_->device(), &create_info, nullptr, &framebuffer_))
throw runtime_error("fail to create a framebuffer");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_framebuffer::fini_framebuffer_()
{
vkDestroyFramebuffer(device_->device(), framebuffer_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "ogl_lib.h"
#include "Ogl_image.h"
#include "Ogl_device.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_image::Ogl_image(const Image_desc& desc, Ogl_device* device) :
Image {desc},
device_ {device},
texture_ {0}
{
init_texture_();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_image::~Ogl_image()
{
fini_texture_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_image::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_image::init_texture_()
{
if (Image_type::two_dim == type_ || Image_type::cube == type_) {
glGenTextures(1, &texture_);
if (Image_type::two_dim == type_) {
glBindTexture(GL_TEXTURE_2D, texture_);
glTexStorage2D(GL_TEXTURE_2D, 1, to_GLInternalFormat(format_), extent_.w, extent_.h);
}
else {
glBindTexture(GL_TEXTURE_CUBE_MAP, texture_);
for (auto i = 0; i != 6; ++i) {
glTexStorage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
1, to_GLInternalFormat(format_), extent_.w, extent_.h);
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_image::fini_texture_()
{
if (Image_type::two_dim == type_ || Image_type::cube == type_)
glDeleteTextures(1, &texture_);
}
//----------------------------------------------------------------------------------------------------------------------
} // namespace of Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_cmd_buffer.h"
#include "Vlk_device.h"
#include "Vlk_buffer.h"
#include "Vlk_image.h"
#include "Vlk_sampler.h"
#include "Vlk_pipeline.h"
#include "Vlk_render_pass.h"
#include "Vlk_framebuffer.h"
#include "Vlk_set_layout.h"
using namespace std;
using namespace Sc_lib;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline void execute(function<void ()>& func)
{
func();
}
//----------------------------------------------------------------------------------------------------------------------
inline Viewport to_viewport(const Extent& extent)
{
return {0.0f, 0.0f, static_cast<float>(extent.w), static_cast<float>(extent.h)};
}
//----------------------------------------------------------------------------------------------------------------------
inline Scissor to_scissor(const Extent& extent)
{
return {0, 0, extent.w, extent.h};
}
//----------------------------------------------------------------------------------------------------------------------
inline auto to_render_pass_desc(const Render_encoder_desc& desc)
{
Vlk_render_pass_desc render_pass_desc {};
for (auto i = 0; i != 4; ++i) {
auto& color = desc.colors[i];
if (!color.image)
continue;
render_pass_desc.colors[i].format = color.image->format();
render_pass_desc.colors[i].samples = color.image->samples();
render_pass_desc.colors[i].load_op = color.load_op;
render_pass_desc.colors[i].store_op = color.store_op;
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil.image) {
render_pass_desc.depth_stencil.format = depth_stencil.image->format();
render_pass_desc.depth_stencil.samples = depth_stencil.image->samples();
render_pass_desc.depth_stencil.load_op = depth_stencil.load_op;
render_pass_desc.depth_stencil.store_op = depth_stencil.store_op;
}
return render_pass_desc;
}
//----------------------------------------------------------------------------------------------------------------------
inline auto to_framebuffer_desc(Vlk_render_pass* render_pass, const Render_encoder_desc& desc)
{
Vlk_framebuffer_desc framebuffer_desc {};
framebuffer_desc.render_pass = render_pass;
for (auto i = 0; i != 4; ++i) {
auto& color = desc.colors[i];
if (!color.image)
continue;
framebuffer_desc.colors[i] = static_cast<Vlk_image*>(color.image);
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil.image)
framebuffer_desc.depth_stencil = static_cast<Vlk_image*>(depth_stencil.image);
return framebuffer_desc;
}
//----------------------------------------------------------------------------------------------------------------------
}
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_arg_table::Vlk_arg_table() :
args_ {}
{
clear();
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_arg_table::clear()
{
for (auto& args : args_)
args.fill({});
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_render_encoder::Vlk_render_encoder(const Render_encoder_desc& desc,
Vlk_device* device, Vlk_cmd_buffer* cmd_buffer) :
Render_encoder(),
device_ {device},
cmd_buffer_ {cmd_buffer},
cmds_ {},
vertex_streams_ {},
index_stream_ {},
arg_table_ {},
pipeline_ {nullptr},
render_pass_ {nullptr},
framebuffer_ {nullptr},
viewport_ {0.0f, 0.0f, 0.0f, 0.0f},
scissor_ {0, 0, 0, 0}
{
begin_render_pass_(desc);
viewport(to_viewport(framebuffer_->extent()));
scissor(to_scissor(framebuffer_->extent()));
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::end()
{
end_render_pass_();
for (auto& [priority, cmds] : cmds_)
for_each(cmds, execute);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::draw(uint32_t count, uint32_t first)
{
update_desc_sets_();
bind_desc_sets_();
cmds_[2].push_back([=]() {
vkCmdDraw(cmd_buffer_->command_buffer(), count, 1, first, 0);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::draw_indexed(uint32_t count, uint32_t first)
{
update_desc_sets_();
bind_desc_sets_();
cmds_[2].push_back([=]() {
vkCmdDrawIndexed(cmd_buffer_->command_buffer(), count, 1, first, 0, 0);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index)
{
Vlk_vertex_stream vertex_stream {static_cast<Vlk_buffer*>(buffer), offset};
if (vertex_stream == vertex_streams_[index])
return;
cmds_[2].push_back([=]() {
vkCmdBindVertexBuffers(cmd_buffer_->command_buffer(),
index, 1, &vertex_stream.buffer->buffer(), &vertex_stream.offset);
});
// update a vertex stream.
vertex_streams_[index] = vertex_stream;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type)
{
Vlk_index_stream index_stream {static_cast<Vlk_buffer*>(buffer), offset, index_type};
if (index_stream == index_stream_)
return;
cmds_[2].push_back([=]() {
vkCmdBindIndexBuffer(cmd_buffer_->command_buffer(),
index_stream.buffer->buffer(), index_stream.offset,
to_VkIndexType(index_stream.index_type));
});
// update an index buffer.
index_stream_ = index_stream;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index)
{
auto buffer_impl = static_cast<Vlk_buffer*>(buffer);
auto& args = arg_table_[0];
if (buffer_impl != args[index].buffer) {
args.dirty_flags = 0x1;
args[index].buffer = buffer_impl;
}
if (offset != args[index].offset) {
args[index].dirty_flags = 0x1;
args[index].offset = offset;
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::shader_texture(Image* image, Sampler* sampler, uint32_t index)
{
auto image_impl = static_cast<Vlk_image*>(image);
auto sampler_impl = static_cast<Vlk_sampler*>(sampler);
cmds_[0].push_back([=]() {
if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == image_impl->layout())
return;
// configure an image barrier.
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = image_impl->access_mask();
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = image_impl->layout();
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image_impl->image();
barrier.subresourceRange.aspectMask = image_impl->aspect_mask();
barrier.subresourceRange.levelCount = image_impl->mip_levels();
barrier.subresourceRange.layerCount = image_impl->array_layers();
// update image meta data.
image_impl->access_mask_ = VK_ACCESS_SHADER_READ_BIT;
image_impl->layout_ = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// record barrier command.
vkCmdPipelineBarrier(cmd_buffer_->command_buffer(),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
0, nullptr,
0, nullptr,
1, &barrier);
});
auto& args = arg_table_[1];
if (image_impl != args[index].image) {
args.dirty_flags |= 0x1;
args[index].image = image_impl;
}
if (sampler_impl != args[index].sampler) {
args.dirty_flags |= 0x2;
args[index].sampler = sampler_impl;
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::pipeline(Pipeline* pipeline)
{
auto pipeline_impl = static_cast<Vlk_pipeline*>(pipeline);
if (pipeline_impl == pipeline_)
return;
cmds_[2].push_back([=]() {
vkCmdBindPipeline(cmd_buffer_->command_buffer(),
VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_impl->pipeline());
});
// update a pipeline.
pipeline_ = pipeline_impl;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::viewport(const Viewport& viewport)
{
if (viewport == viewport_)
return;
cmds_[2].push_back([=]() {
auto vk_viewport = to_VkViewport(viewport);
vkCmdSetViewport(cmd_buffer_->command_buffer(), 0, 1, &vk_viewport);
});
viewport_ = viewport;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::scissor(const Scissor& scissor)
{
if (scissor == scissor_)
return;
cmds_[2].push_back([=]() {
auto vk_scissor = to_VkRect2D(scissor);
vkCmdSetScissor(cmd_buffer_->command_buffer(), 0, 1, &vk_scissor);
});
scissor_ = scissor;
}
//----------------------------------------------------------------------------------------------------------------------
Cmd_buffer* Vlk_render_encoder::cmd_buffer() const
{
return cmd_buffer_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::begin_render_pass_(const Render_encoder_desc& desc)
{
render_pass_ = device_->render_pass(to_render_pass_desc(desc));
framebuffer_ = device_->framebuffer(to_framebuffer_desc(render_pass_, desc));
cmds_[0].push_back([=]() {
vector<VkImageMemoryBarrier> barriers;
for (auto& color : desc.colors) {
if (!color.image)
continue;
auto image_impl = static_cast<Vlk_image*>(color.image);
if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL == image_impl->layout())
continue;
// configure an image barrier.
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
barrier.oldLayout = image_impl->layout();
barrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image_impl->image();
barrier.subresourceRange.aspectMask = image_impl->aspect_mask();
barrier.subresourceRange.levelCount = image_impl->mip_levels();
barrier.subresourceRange.layerCount = image_impl->array_layers();
barriers.push_back(barrier);
// update image meta data.
image_impl->access_mask_ = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
image_impl->layout_ = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil.image) {
auto image_impl = static_cast<Vlk_image*>(depth_stencil.image);
if (VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL != image_impl->layout()) {
// configure an image barrier.
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
barrier.oldLayout = image_impl->layout();
barrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image_impl->image();
barrier.subresourceRange.aspectMask = image_impl->aspect_mask();
barrier.subresourceRange.levelCount = image_impl->mip_levels();
barrier.subresourceRange.layerCount = image_impl->array_layers();
barriers.push_back(barrier);
// update image meta data.
image_impl->access_mask_ = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
image_impl->layout_ = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
}
vkCmdPipelineBarrier(cmd_buffer_->command_buffer(),
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
0, nullptr,
0, nullptr,
barriers.size(), &barriers[0]);
});
cmds_[1].push_back([=]() {
vector<VkClearValue> clear_values;
for (auto& color : desc.colors) {
if (!color.image)
break;
if (Load_op::clear != color.load_op)
continue;
// configure clear value.
VkClearValue clear_value;
clear_value.color.float32[0] = color.clear_value.r;
clear_value.color.float32[1] = color.clear_value.g;
clear_value.color.float32[2] = color.clear_value.b;
clear_value.color.float32[3] = color.clear_value.a;
clear_values.push_back(clear_value);
}
auto& depth_stencil = desc.depth_stencil;
if (depth_stencil.image) {
if (Load_op::clear == depth_stencil.load_op) {
// configure clear value.
VkClearValue clear_value;
clear_value.depthStencil.depth = depth_stencil.clear_value.d;
clear_value.depthStencil.stencil = depth_stencil.clear_value.s;
clear_values.push_back(clear_value);
}
}
// configure a render pass begin info.
VkRenderPassBeginInfo begin_info {};
begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
begin_info.renderPass = render_pass_->render_pass();
begin_info.framebuffer = framebuffer_->framebuffer();
begin_info.renderArea.extent = to_VkExtent2D(framebuffer_->extent());
begin_info.clearValueCount = clear_values.size();
begin_info.pClearValues = &clear_values[0];
vkCmdBeginRenderPass(cmd_buffer_->command_buffer(), &begin_info, VK_SUBPASS_CONTENTS_INLINE);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::end_render_pass_()
{
cmds_[3].push_back([=]() {
vkCmdEndRenderPass(cmd_buffer_->command_buffer());
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::update_desc_sets_()
{
unordered_map<uint32_t, VkDescriptorBufferInfo> buffer_infos;
if (arg_table_[0].dirty_flags) {
arg_table_[0].dirty_flags = 0;
auto set_layout = pipeline_->set_layout(0);
arg_table_[0].desc_set = set_layout->desc_set();
for (auto i = 0; i != 16; ++i) {
if (!arg_table_[0][i].buffer)
continue;
VkDescriptorBufferInfo buffer_info {};
buffer_info.buffer = arg_table_[0][i].buffer->buffer();
buffer_info.offset = 0;
buffer_info.range = VK_WHOLE_SIZE;
buffer_infos.insert({i, buffer_info});
}
}
if (!buffer_infos.empty()) {
vector<VkWriteDescriptorSet> write_desc_sets;
for (auto& [binding, buffer_info] : buffer_infos) {
VkWriteDescriptorSet write_desc_set {};
write_desc_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_desc_set.dstSet = arg_table_[0].desc_set;
write_desc_set.dstBinding = binding;
write_desc_set.descriptorCount = 1;
write_desc_set.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
write_desc_set.pBufferInfo = &buffer_info;
write_desc_sets.push_back(write_desc_set);
}
vkUpdateDescriptorSets(device_->device(),
write_desc_sets.size(), &write_desc_sets[0],
0, nullptr);
}
unordered_map<uint32_t, VkDescriptorImageInfo> image_infos;
if (arg_table_[1].dirty_flags) {
arg_table_[1].dirty_flags = 0;
auto set_layout = pipeline_->set_layout(1);
arg_table_[1].desc_set = set_layout->desc_set();
for (auto i = 0; i != 16; ++i) {
if (!arg_table_[1][i].image && !arg_table_[1][i].sampler)
continue;
VkDescriptorImageInfo image_info {};
image_info.sampler = arg_table_[1][i].sampler->sampler();
image_info.imageView = arg_table_[1][i].image->image_view();
image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_infos.insert({i, image_info});
}
}
if (!image_infos.empty()) {
vector<VkWriteDescriptorSet> write_desc_sets;
for (auto& [binding, image_info] : image_infos) {
VkWriteDescriptorSet write_desc_set {};
write_desc_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write_desc_set.dstSet = arg_table_[1].desc_set;
write_desc_set.dstBinding = binding;
write_desc_set.descriptorCount = 1;
write_desc_set.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write_desc_set.pImageInfo = &image_info;
write_desc_sets.push_back(write_desc_set);
}
vkUpdateDescriptorSets(device_->device(),
write_desc_sets.size(), &write_desc_sets[0],
0, nullptr);
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_render_encoder::bind_desc_sets_()
{
vector<VkDescriptorSet> desc_sets;
vector<uint32_t> offsets;
if (arg_table_[0].desc_set) {
desc_sets.push_back(arg_table_[0].desc_set);
for (auto i = 0; i != 16; ++i) {
if (!arg_table_[0][i].buffer)
continue;
offsets.push_back(arg_table_[0][i].offset);
}
}
if (arg_table_[1].desc_set) {
desc_sets.push_back(arg_table_[1].desc_set);
}
if (desc_sets.empty())
return;
auto pipeline_layout = pipeline_->pipeline_layout();
cmds_[2].push_back([=]() {
vkCmdBindDescriptorSets(cmd_buffer_->command_buffer(),
VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout,
0,
static_cast<uint32_t>(desc_sets.size()), &desc_sets[0],
static_cast<uint32_t>(offsets.size()), &offsets[0]);
});
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_blit_encoder::Vlk_blit_encoder(const Blit_encoder_desc& desc, Vlk_cmd_buffer* cmd_buffer) :
Blit_encoder(),
cmd_buffer_ {cmd_buffer},
cmds_ {}
{
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_blit_encoder::copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region)
{
auto src_buffer_impl = static_cast<Vlk_buffer*>(src_buffer);
auto dst_buffer_impl = static_cast<Vlk_buffer*>(dst_buffer);
cmds_.push_back([=]() {
// configure buffer copy.
VkBufferCopy copy {};
copy.srcOffset = region.src_offset;
copy.dstOffset = region.dst_offset;
copy.size = region.size;
// record a copy command.
vkCmdCopyBuffer(cmd_buffer_->command_buffer(),
src_buffer_impl->buffer(), dst_buffer_impl->buffer(), 1, ©);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_blit_encoder::copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region)
{
auto src_buffer_impl = static_cast<Vlk_buffer*>(src_buffer);
auto dst_image_impl = static_cast<Vlk_image*>(dst_image);
cmds_.push_back([=]() {
if (VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == dst_image_impl->layout())
return;
// configure an image barrier.
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.oldLayout = dst_image_impl->layout();
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = dst_image_impl->image();
barrier.subresourceRange.aspectMask = dst_image_impl->aspect_mask();
barrier.subresourceRange.levelCount = dst_image_impl->mip_levels();
barrier.subresourceRange.layerCount = dst_image_impl->array_layers();
// update image meta data.
dst_image_impl->access_mask_ = VK_ACCESS_TRANSFER_WRITE_BIT;
dst_image_impl->layout_ = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
// recoard a barrier command.
vkCmdPipelineBarrier(cmd_buffer_->command_buffer(),
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
0, nullptr,
0, nullptr,
1, &barrier);
});
cmds_.push_back([=]() {
// configure a buffer image copy.
VkBufferImageCopy copy {};
copy.imageSubresource.aspectMask = dst_image_impl->aspect_mask();
copy.imageSubresource.mipLevel = region.image_subresource.mip_level;
copy.imageSubresource.baseArrayLayer = region.image_subresource.array_layer;
copy.imageSubresource.layerCount = 1;
copy.imageOffset.x = region.image_offset.x;
copy.imageOffset.y = region.image_offset.y;
copy.imageOffset.z = region.image_offset.z;
copy.imageExtent.width = region.image_extent.w;
copy.imageExtent.height = region.image_extent.h;
copy.imageExtent.depth = region.image_extent.d;
// record a copy command.
vkCmdCopyBufferToImage(cmd_buffer_->command_buffer(),
src_buffer_impl->buffer(),
dst_image_impl->image(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ©);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_blit_encoder::copy(Image* src_image, Buffer* dst_buffer, const Buffer_image_copy_region& region)
{
auto src_image_impl = static_cast<Vlk_image*>(src_image);
auto dst_buffer_impl = static_cast<Vlk_buffer*>(dst_buffer);
cmds_.push_back([=]() {
if (VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL == src_image_impl->layout())
return;
// configure an image barrier.
VkImageMemoryBarrier barrier {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = src_image_impl->access_mask();
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.oldLayout = src_image_impl->layout();
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = src_image_impl->image();
barrier.subresourceRange.aspectMask = src_image_impl->aspect_mask();
barrier.subresourceRange.levelCount = src_image_impl->mip_levels();
barrier.subresourceRange.layerCount = src_image_impl->array_layers();
// update image meta data.
src_image_impl->access_mask_ = VK_ACCESS_TRANSFER_READ_BIT;
src_image_impl->layout_ = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
// record barrier command.
vkCmdPipelineBarrier(cmd_buffer_->command_buffer(),
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_DEPENDENCY_BY_REGION_BIT,
0, nullptr,
0, nullptr,
1, &barrier);
});
cmds_.push_back([=]() {
// configure a buffer image copy.
VkBufferImageCopy copy {};
copy.bufferOffset = region.buffer_offset;
copy.bufferRowLength = region.buffer_row_size;
copy.bufferImageHeight = region.buffer_image_height;
copy.imageSubresource.aspectMask = src_image_impl->aspect_mask();
copy.imageSubresource.mipLevel = region.image_subresource.mip_level;
copy.imageSubresource.baseArrayLayer = region.image_subresource.array_layer;
copy.imageSubresource.layerCount = 1;
copy.imageOffset.x = region.image_offset.x;
copy.imageOffset.y = region.image_offset.y;
copy.imageOffset.z = region.image_offset.z;
copy.imageExtent.width = region.image_extent.w;
copy.imageExtent.height = region.image_extent.h;
copy.imageExtent.depth = region.image_extent.d;
// record a copy command.
vkCmdCopyImageToBuffer(cmd_buffer_->command_buffer(),
src_image_impl->image(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
dst_buffer_impl->buffer(),
1, ©);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_blit_encoder::end()
{
for_each(cmds_, execute);
}
//----------------------------------------------------------------------------------------------------------------------
Cmd_buffer* Vlk_blit_encoder::cmd_buffer() const
{
return cmd_buffer_;
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_cmd_buffer::Vlk_cmd_buffer(Vlk_device* device) :
device_ {device},
command_buffer_ {VK_NULL_HANDLE}
{
init_command_buffer_();
begin_command_buffer_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_cmd_buffer::~Vlk_cmd_buffer()
{
fini_command_buffer_();
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Render_encoder> Vlk_cmd_buffer::create(const Render_encoder_desc& desc)
{
return make_unique<Vlk_render_encoder>(desc, device_, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Blit_encoder> Vlk_cmd_buffer::create(const Blit_encoder_desc& desc)
{
return make_unique<Vlk_blit_encoder>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_cmd_buffer::end()
{
vkEndCommandBuffer(command_buffer_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_cmd_buffer::reset()
{
vkResetCommandBuffer(command_buffer_, 0);
begin_command_buffer_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_cmd_buffer::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_cmd_buffer::init_command_buffer_()
{
// configure a command buffer allocate info.
VkCommandBufferAllocateInfo allocateInfo {};
allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocateInfo.commandPool = device_->command_pool();
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocateInfo.commandBufferCount = 1;
// try to create a command buffer.
if (vkAllocateCommandBuffers(device_->device(), &allocateInfo, &command_buffer_))
throw runtime_error("fail to create a cmd buffer");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_cmd_buffer::fini_command_buffer_()
{
vkFreeCommandBuffers(device_->device(), device_->command_pool(), 1, &command_buffer_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_cmd_buffer::begin_command_buffer_()
{
// configure the command buffer begin info.
VkCommandBufferBeginInfo begin_info {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
// start recording.
vkBeginCommandBuffer(command_buffer_, &begin_info);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_DEMO_STB_LIB_GUARD
#define GFX_DEMO_STB_LIB_GUARD
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#endif // GFX_DEMO_STB_LIB_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_IMAGE_GUARD
#define GFX_MTL_IMAGE_GUARD
#include <Metal/Metal.h>
#include "Image.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_image final : public Image {
public:
Mtl_image(const Image_desc& desc, Mtl_device* device);
Device* device() const override;
inline auto texture() const noexcept
{ return texture_; }
private:
void init_texture_();
private:
Mtl_device* device_;
id<MTLTexture> texture_;
friend class Mtl_swap_chain;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_IMAGE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_DEVICE_GUARD
#define GFX_VLK_DEVICE_GUARD
#include <unordered_map>
#include <vulkan/vulkan.h>
#include <vk_mem_alloc.h>
#include <platform/Library.h>
#include "Device.h"
#include "Lru_cache.h"
#include "Vlk_render_pass.h"
#include "Vlk_framebuffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_cmd_buffer;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device final : public Device {
public:
Vlk_device();
~Vlk_device() override;
std::unique_ptr<Buffer> create(const Buffer_desc& desc) override;
std::unique_ptr<Image> create(const Image_desc& desc) override;
std::unique_ptr<Sampler> create(const Sampler_desc& desc) override;
std::unique_ptr<Shader> create(const Shader_desc& desc) override;
std::unique_ptr<Pipeline> create(const Pipeline_desc& desc) override;
std::unique_ptr<Swap_chain> create(const Swap_chain_desc& desc) override;
std::unique_ptr<Cmd_buffer> create(const Cmd_buffer_desc& desc) override;
std::unique_ptr<Fence> create(const Fence_desc& desc) override;
void submit(Cmd_buffer* cmd_buffer, Fence* fence = nullptr) override;
void wait_idle() override;
Vlk_render_pass* render_pass(const Vlk_render_pass_desc& desc);
Vlk_framebuffer* framebuffer(const Vlk_framebuffer_desc& desc);
inline auto instance() const noexcept
{ return instance_; }
inline auto physical_device() const noexcept
{ return physical_device_; }
inline auto queue_family_index() const noexcept
{ return queue_family_index_; }
inline auto device() const noexcept
{ return device_; }
inline auto queue() const noexcept
{ return queue_; }
inline auto allocator() const noexcept
{ return allocator_; }
inline auto command_pool() const noexcept
{ return command_pool_; }
inline auto pipeline_cache() const noexcept
{ return pipeline_cache_; }
private:
void init_library_();
void init_bootstrap_symbols_();
void init_instance_();
void init_instance_symbols_();
void init_physical_device_();
void init_queue_family_index_();
void init_device_();
void init_device_symbols_();
void init_caps_();
void init_queue_();
void init_allocator_();
void init_command_pool_();
void init_pipeline_cache_();
void fini_instance_();
void fini_device_();
void fini_allocator_();
void fini_command_pool_();
void fini_pipeline_cache_();
private:
Platform_lib::Library library_;
VkInstance instance_;
VkPhysicalDevice physical_device_;
uint32_t queue_family_index_;
VkDevice device_;
VkQueue queue_;
VmaAllocator allocator_;
VkCommandPool command_pool_;
VkPipelineCache pipeline_cache_;
Lru_cache<Vlk_render_pass> render_pass_pool_;
Lru_cache<Vlk_framebuffer> framebuffer_pool_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_DEVICE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_CMD_BUFFER_GUARD
#define GFX_VLK_CMD_BUFFER_GUARD
#include <map>
#include <unordered_map>
#include <deque>
#include <functional>
#include <vulkan/vulkan.h>
#include "Cmd_buffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_buffer;
class Vlk_image;
class Vlk_sampler;
class Vlk_pipeline;
class Vlk_cmd_buffer;
class Vlk_render_pass;
class Vlk_framebuffer;
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_vertex_stream final {
Vlk_buffer* buffer {nullptr};
uint64_t offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Vlk_vertex_stream& lhs, const Vlk_vertex_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset);
}
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_index_stream final {
Vlk_buffer* buffer {nullptr};
uint64_t offset {0};
Index_type index_type {Index_type::invalid};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Vlk_index_stream& lhs, const Vlk_index_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset) && (lhs.index_type == rhs.index_type);
}
//----------------------------------------------------------------------------------------------------------------------
template<typename T>
class Vlk_arg_array : public std::array<T, 16> {
public:
VkDescriptorSet desc_set {VK_NULL_HANDLE};
uint32_t dirty_flags {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_arg {
Vlk_buffer* buffer {nullptr};
Vlk_image* image {nullptr};
Vlk_sampler* sampler {nullptr};
uint32_t offset {0};
uint32_t dirty_flags {false};
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_arg_table final {
public:
Vlk_arg_table();
void clear();
inline Vlk_arg_array<Vlk_arg>& operator[](size_t index) noexcept
{ return args_[index]; }
private:
std::array<Vlk_arg_array<Vlk_arg>, 2> args_;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_render_encoder final : public Render_encoder {
public:
Vlk_render_encoder(const Render_encoder_desc& desc, Vlk_device* device, Vlk_cmd_buffer* cmd_buffer);
void end() override;
void draw(uint32_t count, uint32_t first = 0) override;
void draw_indexed(uint32_t count, uint32_t first = 0) override;
void vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index) override;
void index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type) override;
void shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index) override;
void shader_texture(Image* image, Sampler* sampler, uint32_t index) override;
void pipeline(Pipeline* pipeline) override;
void viewport(const Viewport& viewport) override;
void scissor(const Scissor& scissor) override;
Cmd_buffer* cmd_buffer() const override;
private:
void begin_render_pass_(const Render_encoder_desc& desc);
void end_render_pass_();
void update_desc_sets_();
void bind_desc_sets_();
private:
Vlk_device* device_;
Vlk_cmd_buffer* cmd_buffer_;
std::map<uint32_t, std::deque<std::function<void ()>>> cmds_;
std::array<Vlk_vertex_stream, 2> vertex_streams_;
Vlk_index_stream index_stream_;
Vlk_arg_table arg_table_;
Vlk_pipeline* pipeline_;
Vlk_render_pass* render_pass_;
Vlk_framebuffer* framebuffer_;
Viewport viewport_;
Scissor scissor_;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_blit_encoder final : public Blit_encoder {
public:
Vlk_blit_encoder(const Blit_encoder_desc& desc, Vlk_cmd_buffer* cmd_buffer);
void copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region) override;
void copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region) override;
void copy(Image* src_buffer, Buffer* dst_image, const Buffer_image_copy_region& region) override;
void end() override;
Cmd_buffer* cmd_buffer() const override;
private:
Vlk_cmd_buffer* cmd_buffer_;
std::deque<std::function<void ()>> cmds_;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_cmd_buffer final : public Cmd_buffer {
public:
Vlk_cmd_buffer(Vlk_device* device);
~Vlk_cmd_buffer() override;
std::unique_ptr<Render_encoder> create(const Render_encoder_desc& desc) override;
std::unique_ptr<Blit_encoder> create(const Blit_encoder_desc& desc) override;
void end() override;
void reset() override;
Device* device() const override;
inline auto& command_buffer() const noexcept
{ return command_buffer_; }
private:
void init_command_buffer_();
void fini_command_buffer_();
void begin_command_buffer_();
private:
Vlk_device* device_;
VkCommandBuffer command_buffer_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_CMD_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_ENUMS_GUARD
#define GFX_ENUMS_GUARD
#include <cstdint>
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
enum class Vender : uint32_t {
apple = 0x106B, amd = 0x1022, arm = 0x13B5, nvidia = 0x10DE, qualcomm = 0x5143,
};
//----------------------------------------------------------------------------------------------------------------------
enum class Coords : uint8_t {
invalid = 0,
origin_upper_left, origin_lower_left
};
//----------------------------------------------------------------------------------------------------------------------
enum class Format : uint32_t {
invalid = 0,
rgb8_unorm, rgba8_unorm, bgra8_unorm, r32_float, rg32_float, rgb32_float, rgba32_float, d24_unorm_s8_uint
};
//----------------------------------------------------------------------------------------------------------------------
enum class Heap_type : uint8_t {
local = 0, upload, readback
};
//----------------------------------------------------------------------------------------------------------------------
enum class Index_type : uint8_t {
invalid = 0, uint16, uint32
};
//----------------------------------------------------------------------------------------------------------------------
enum class Image_type : uint8_t {
two_dim = 0, cube, swap_chain
};
//----------------------------------------------------------------------------------------------------------------------
enum class Filter : uint8_t {
nearest = 0, linear
};
//----------------------------------------------------------------------------------------------------------------------
enum class Mip_filter : uint8_t {
nearest = 0, linear
};
//----------------------------------------------------------------------------------------------------------------------
enum class Address_mode : uint8_t {
repeat = 0, clamp_to_edge
};
//----------------------------------------------------------------------------------------------------------------------
enum class Pipeline_stage : uint8_t {
invalid = 0,
vertex_shader = 0x01, fragment_shader = 0x02, output_merger = 0x04, transfer = 0x08
};
//----------------------------------------------------------------------------------------------------------------------
enum class Step_rate : uint8_t {
vertex = 0, instance
};
//----------------------------------------------------------------------------------------------------------------------
enum class Topology : uint8_t {
triangle_list = 0, triangle_strip, point
};
//----------------------------------------------------------------------------------------------------------------------
enum class Cull_mode : uint8_t {
none = 0, front, back,
};
//----------------------------------------------------------------------------------------------------------------------
enum class Front_face : uint8_t {
counter_clockwise = 0, clockwise
};
//----------------------------------------------------------------------------------------------------------------------
enum class Compare_op : uint8_t {
never = 0, less, greater, equal, not_equal, less_or_equal, greater_or_equal, always
};
//----------------------------------------------------------------------------------------------------------------------
enum class Stencil_op : uint8_t {
keep = 0, zero, replace, increment_and_clamp, decrement_and_clamp, invert, increment_and_wrap, decrement_and_wrap
};
//----------------------------------------------------------------------------------------------------------------------
enum class Blend_factor : uint8_t {
zero = 0, one, src_alpha, one_minus_src_alpha, dst_alpha, one_minus_dst_alpha
};
//----------------------------------------------------------------------------------------------------------------------
enum class Blend_op : uint8_t {
add = 0, subtract, reverse_subtract, min, max
};
//----------------------------------------------------------------------------------------------------------------------
enum class Load_op : uint8_t {
load = 0, clear, dont_care
};
//----------------------------------------------------------------------------------------------------------------------
enum class Store_op : uint8_t {
store = 0, dont_care
};
//----------------------------------------------------------------------------------------------------------------------
enum class Color_space : uint8_t {
srgb_non_linear = 0
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_ENUMS_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "Pipeline.h"
#include "Shader.h"
using namespace std;
using namespace Sc_lib;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
auto to_Pipeline_stage(Shader_type type)
{
switch (type) {
case Shader_type::vertex:
return Pipeline_stage::vertex_shader;
case Shader_type::fragment:
return Pipeline_stage::fragment_shader;
default:
throw runtime_error("invalid Shader_type");
}
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Pipeline::Pipeline(const Pipeline_desc& desc) :
vertex_input_ {desc.vertex_input},
input_assembly_ {desc.input_assembly},
rasterization_ {desc.rasterization},
multisample_ {desc.multisample},
depth_stencil_ {desc.depth_stencil},
color_blend_ {desc.color_blend},
output_merger_ {desc.output_merger},
reflection_ {}
{
init_reflection_({desc.vertex_shader, desc.fragment_shader});
}
//----------------------------------------------------------------------------------------------------------------------
void Pipeline::init_reflection_(const std::vector<Shader*> shaders)
{
unordered_map<Shader_type, Signature> signatures;
for (auto shader : shaders)
signatures.emplace(shader->type(), shader->reflect());
for (auto& [shader_type, signature] : signatures) {
for (auto& [binding, buffer] : signature.buffers) {
try {
reflection_.buffers[binding] |= etoi(to_Pipeline_stage(shader_type));
}
catch (exception& e) {
throw runtime_error("fail to create a pipeline");
}
}
for (auto& [binding, texture] : signature.textures) {
try {
reflection_.textures[binding] |= etoi(to_Pipeline_stage(shader_type));
}
catch (exception& e) {
throw runtime_error("fail to create a pipeline");
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_CMD_BUFFER_GUARD
#define GFX_MTL_CMD_BUFFER_GUARD
#include <array>
#include <unordered_map>
#include <Metal/Metal.h>
#include "limitations.h"
#include "Cmd_buffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
class Mtl_buffer;
class Mtl_image;
class Mtl_sampler;
class Mtl_pipeline;
class Mtl_cmd_buffer;
//----------------------------------------------------------------------------------------------------------------------
struct Mtl_vertex_stream final {
Mtl_buffer* buffer {nullptr};
uint64_t offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Mtl_vertex_stream& lhs, const Mtl_vertex_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset);
}
//----------------------------------------------------------------------------------------------------------------------
struct Mtl_index_stream final {
Mtl_buffer* buffer {nullptr};
uint64_t offset {0};
Index_type index_type {Index_type::invalid};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Mtl_index_stream& lhs, const Mtl_index_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset) && (lhs.index_type == rhs.index_type);
}
//----------------------------------------------------------------------------------------------------------------------
struct Mtl_arg_buffer final {
Mtl_buffer* buffer {nullptr};
uint32_t buffer_stages {0};
uint32_t offset {0};
uint32_t offset_stages {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Mtl_arg_texture final {
Mtl_image* image {nullptr};
uint32_t image_stages {0};
Mtl_sampler* sampler {nullptr};
uint32_t sampler_stages {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Mtl_arg_table final {
std::array<Mtl_arg_buffer, max_shader_buffers> buffers;
std::array<Mtl_arg_texture, max_shader_textures> textures;
};
//----------------------------------------------------------------------------------------------------------------------
class Mtl_render_encoder final : public Render_encoder {
public:
Mtl_render_encoder(const Render_encoder_desc& desc, Mtl_cmd_buffer* cmd_buffer);
void end() override;
void draw(uint32_t count, uint32_t first = 0) override;
void draw_indexed(uint32_t count, uint32_t first = 0) override;
void vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index) override;
void index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type) override;
void shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index) override;
void shader_texture(Image* image, Sampler* sampler, uint32_t index) override;
void pipeline(Pipeline* pipeline) override;
void viewport(const Viewport& viewport) override;
void scissor(const Scissor& scissor) override;
Cmd_buffer* cmd_buffer() const override;
inline auto render_command_encoder() const noexcept
{ return render_command_encoder_; }
private:
void init_render_command_encoder_(const Render_encoder_desc& desc);
void bind_arg_table_();
void bind_arg_buffer_(uint64_t index, uint32_t stages);
void bind_arg_texture_(uint64_t index, uint32_t stages);
private:
Mtl_cmd_buffer* cmd_buffer_;
id<MTLRenderCommandEncoder> render_command_encoder_;
std::array<Mtl_vertex_stream, 2> vertex_streams_;
Mtl_index_stream index_stream_;
Mtl_arg_table arg_table_;
Mtl_pipeline* pipeline_;
};
//----------------------------------------------------------------------------------------------------------------------
class Mtl_blit_encoder final : public Blit_encoder {
public:
Mtl_blit_encoder(const Blit_encoder_desc& desc, Mtl_cmd_buffer* cmd_buffer);
void copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region) override;
void copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region) override;
void copy(Image* src_buffer, Buffer* dst_image, const Buffer_image_copy_region& region) override;
void end() override;
Cmd_buffer* cmd_buffer() const override;
inline auto blit_command_encoder() const noexcept
{ return blit_command_encoder_; }
private:
void init_blit_command_encoder_();
private:
Mtl_cmd_buffer* cmd_buffer_;
id<MTLBlitCommandEncoder> blit_command_encoder_;
};
//----------------------------------------------------------------------------------------------------------------------
class Mtl_cmd_buffer final : public Cmd_buffer {
public:
Mtl_cmd_buffer(Mtl_device* device);
std::unique_ptr<Render_encoder> create(const Render_encoder_desc& desc) override;
std::unique_ptr<Blit_encoder> create(const Blit_encoder_desc& desc) override;
void end() override;
void reset() override;
Device* device() const override;
inline auto command_buffer() const noexcept
{ return command_buffer_; }
private:
void init_command_buffer_();
private:
Mtl_device* device_;
id<MTLCommandBuffer> command_buffer_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_CMD_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_fence.h"
#include "Vlk_device.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_fence::Vlk_fence(const Fence_desc& desc, Vlk_device* device) :
Fence {},
device_ {device},
fence_ {VK_NULL_HANDLE}
{
init_fence_(desc.signaled);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_fence::wait_signal()
{
vkWaitForFences(device_->device(), 1, &fence_, VK_FALSE, UINT64_MAX);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_fence::reset()
{
vkResetFences(device_->device(), 1, &fence_);
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_fence::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
bool Vlk_fence::signaled() const
{
return !vkGetFenceStatus(device_->device(), fence_);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_fence::init_fence_(bool signaled)
{
// configure a fence create info.
VkFenceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if(signaled)
create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
// try to create a fence.
if (vkCreateFence(device_->device(), &create_info, nullptr, &fence_))
throw runtime_error("fail to create a fence");
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_image.h"
#include "Vlk_device.h"
#include "Vlk_swap_chain.h"
using namespace std;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline bool is_color_format(Format format)
{
switch (format) {
case Format::rgba8_unorm:
case Format::bgra8_unorm:
return true;
default:
return false;
}
}
//----------------------------------------------------------------------------------------------------------------------
inline auto is_depth_stencil_format(Format format)
{
switch (format) {
case Format::d24_unorm_s8_uint:
return true;
default:
return false;
}
}
//----------------------------------------------------------------------------------------------------------------------
}
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_image::Vlk_image(const Image_desc& desc, Vlk_device* device) :
Image {desc},
device_ {device },
swap_chain_ {nullptr},
image_ { VK_NULL_HANDLE },
alloc_ { VK_NULL_HANDLE },
access_mask_ { 0 },
layout_ { VK_IMAGE_LAYOUT_UNDEFINED },
image_view_ { VK_NULL_HANDLE },
aspect_mask_ { to_VkImageAspectFlags(format_) }
{
init_image_and_alloc_();
init_image_view_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_image::Vlk_image(const Image_desc& desc, Vlk_device* device, Vlk_swap_chain* swap_chain, VkImage image) :
Image {desc},
device_ {device},
swap_chain_ {swap_chain},
image_ {image},
alloc_ {VK_NULL_HANDLE},
layout_ {VK_IMAGE_LAYOUT_UNDEFINED},
image_view_ {VK_NULL_HANDLE},
aspect_mask_ { to_VkImageAspectFlags(format_) }
{
init_image_view_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_image::~Vlk_image()
{
fini_image_view_();
if (Image_type::two_dim == type_ || Image_type::cube == type_)
fini_image_and_alloc_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_image::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_image::init_image_and_alloc_()
{
// configure the required image usage.
auto usage {VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT};
if (is_color_format(format_)) {
usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
}
if (is_depth_stencil_format(format_))
usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
// configure an image create info.
VkImageCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
create_info.imageType = to_VkImageType(type_);
create_info.format = to_VkFormat(format_);
create_info.extent = to_VkExtent3D(extent_);
create_info.mipLevels = mip_levels_;
create_info.arrayLayers = array_layers_;
create_info.samples = static_cast<VkSampleCountFlagBits>(samples_);
create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
create_info.usage = usage;
create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
// configure an allocation create info.
VmaAllocationCreateInfo alloc_create_info {};
alloc_create_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
// try to create an image and an allocation.
if (vmaCreateImage(device_->allocator(), &create_info, &alloc_create_info, &image_, &alloc_, nullptr))
throw runtime_error("fail to create an image");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_image::init_image_view_()
{
// configure an image view create info.
VkImageViewCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
create_info.image = image_;
create_info.viewType = to_VkImageViewType(type_);
create_info.format = to_VkFormat(format_);
create_info.subresourceRange.aspectMask = aspect_mask_;
create_info.subresourceRange.levelCount = mip_levels_;
create_info.subresourceRange.layerCount = array_layers_;
// try to create an image view.
if (vkCreateImageView(device_->device(), &create_info, nullptr, &image_view_))
throw runtime_error("fail to create an image");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_image::fini_image_and_alloc_()
{
vkDestroyImage(device_->device(), image_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_image::fini_image_view_()
{
vkDestroyImageView(device_->device(), image_view_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_shader.h"
#include "Vlk_device.h"
using namespace std;
using namespace Sc_lib;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_shader::Vlk_shader(const Shader_desc& desc, Vlk_device* device) :
Shader {desc},
device_ {device},
signature_ {},
shader_module_ {VK_NULL_HANDLE}
{
init_signature_(desc.src);
init_shader_module_(desc.src);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_shader::~Vlk_shader()
{
fini_shader_module();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_shader::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
Sc_lib::Signature Vlk_shader::reflect() const noexcept
{
return signature_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_shader::init_signature_(const std::vector<uint32_t>& src)
{
signature_ = Spirv_reflector().reflect(src);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_shader::init_shader_module_(const std::vector<uint32_t>& src)
{
// configure a shader module create info.
VkShaderModuleCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = sizeof(uint32_t) * src.size();
create_info.pCode = &src[0];
// try to create a shader module.
if (vkCreateShaderModule(device_->device(), &create_info, nullptr, &shader_module_))
throw runtime_error("fail to create a shader");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_shader::fini_shader_module()
{
vkDestroyShaderModule(device_->device(), shader_module_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_SAMPLER_GUARD
#define GFX_VLK_SAMPLER_GUARD
#include <vulkan/vulkan.h>
#include "Sampler.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_sampler final : public Sampler {
public:
Vlk_sampler(const Sampler_desc& desc, Vlk_device* device);
~Vlk_sampler() override;
Device* device() const override;
inline auto& sampler() const noexcept
{ return sampler_; }
private:
void init_sampler_();
void fini_sampler_();
private:
Vlk_device* device_;
VkSampler sampler_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_SAMPLER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "vlk_lib.h"
#include "Vlk_sampler.h"
#include "Vlk_device.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_sampler::Vlk_sampler(const Sampler_desc& desc, Vlk_device* device) :
Sampler {desc},
device_ {device},
sampler_ {VK_NULL_HANDLE}
{
init_sampler_();
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_sampler::~Vlk_sampler()
{
fini_sampler_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_sampler::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_sampler::init_sampler_()
{
// configure a sampler create info.
VkSamplerCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
create_info.magFilter = to_VkFilter(mag_);
create_info.minFilter = to_VkFilter(min_);
create_info.mipmapMode = to_VkSamplerMipmapMode(mip_);
create_info.addressModeU = to_VkSamplerAddressMode(u_);
create_info.addressModeV = to_VkSamplerAddressMode(v_);
create_info.addressModeW = to_VkSamplerAddressMode(w_);
// try to create a sampler.
if (vkCreateSampler(device_->device(), &create_info, nullptr, &sampler_))
throw runtime_error("fail to create sampler");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_sampler::fini_sampler_()
{
vkDestroySampler(device_->device(), sampler_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <cstdint>
#include <string>
#include <cxxopts.hpp>
#include <platform/Window.h>
#include "Gfx_demo.h"
using namespace std;
using namespace cxxopts;
using namespace Platform_lib;
//----------------------------------------------------------------------------------------------------------------------
unique_ptr<Window> window_;
unique_ptr<Gfx_demo> gfx_demo_;
//----------------------------------------------------------------------------------------------------------------------
void on_startup()
{
gfx_demo_->connect(window_.get());
}
//----------------------------------------------------------------------------------------------------------------------
void on_shutdown()
{
gfx_demo_ = nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
void on_render()
{
gfx_demo_->render();
}
//----------------------------------------------------------------------------------------------------------------------
void on_touch_down()
{
gfx_demo_->touch_down();
}
//----------------------------------------------------------------------------------------------------------------------
void on_touch_move(float x, float y)
{
gfx_demo_->touch_move(x, y);
}
//----------------------------------------------------------------------------------------------------------------------
void on_touch_up()
{
gfx_demo_->touch_up();
}
//----------------------------------------------------------------------------------------------------------------------
#if TARGET_OS_IOS || TARGET_OS_OSX
int main(int argc, char* argv[])
{
Options options("gfx_demo", "Various gfx demos");
options.add_options()
("w, width", "window width", value<uint32_t>()->default_value("360"))
("h, height", "window height", value<uint32_t>()->default_value("640"))
("t, target", "demo name", value<string>()->default_value("triangle"));
auto result = options.parse(argc, argv);
auto target = result["target"].as<string>();
Window_desc window_desc;
window_desc.title = L"GFX Demo";
window_desc.extent = { result["w"].as<uint32_t>(), result["h"].as<uint32_t>() };
window_ = make_unique<Window>(window_desc);
window_->startup_signal.connect(&on_startup);
window_->shutdown_signal.connect(&on_shutdown);
window_->render_signal.connect(&on_render);
window_->touch_down_signal.connect(&on_touch_down);
window_->touch_move_signal.connect(&on_touch_move);
window_->touch_up_signal.connect(&on_touch_up);
gfx_demo_ = make_unique<Gfx_demo>();
window_->run();
return 0;
}
#elif defined(__ANDROID__)
void android_main(struct android_app* state)
{
Window_desc window_desc;
window_desc.title = L"GFX Demo";
window_desc.extent = { 360, 640 };
window_desc.app = state;
window_ = make_unique<Window>(window_desc);
window_->startup_signal.connect(&on_startup);
window_->shutdown_signal.connect(&on_shutdown);
window_->render_signal.connect(&on_render);
window_->touch_down_signal.connect(&on_touch_down);
window_->touch_move_signal.connect(&on_touch_move);
window_->touch_up_signal.connect(&on_touch_up);
gfx_demo_ = make_unique<Gfx_demo>();
window_->run();
}
#elif defined(_WIN32)
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow)
{
Window_desc window_desc;
window_desc.title = L"GFX Demo";
window_desc.extent = { 360, 640 };
window_ = make_unique<Window>(window_desc);
window_->startup_signal.connect(&on_startup);
window_->shutdown_signal.connect(&on_shutdown);
window_->render_signal.connect(&on_render);
demo_ = make_unique<Triangle_demo>();
window_->run();
return 0;
}
#endif
//----------------------------------------------------------------------------------------------------------------------
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_CMD_BUFFER_GUARD
#define GFX_OGL_CMD_BUFFER_GUARD
#include <deque>
#include <functional>
#include <GLES3/gl3.h>
#include "Cmd_buffer.h"
#include "Ogl_pipeline.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
class Ogl_buffer;
class Ogl_image;
class Ogl_sampler;
class Ogl_cmd_buffer;
class Ogl_framebuffer;
//----------------------------------------------------------------------------------------------------------------------
struct Ogl_vertex_stream final {
Ogl_buffer* buffer {nullptr};
uint64_t offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Ogl_vertex_stream& lhs, const Ogl_vertex_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset);
}
//----------------------------------------------------------------------------------------------------------------------
struct Ogl_index_stream final {
Ogl_buffer* buffer {nullptr};
uint64_t offset {0};
Index_type index_type {Index_type::invalid};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Ogl_index_stream& lhs, const Ogl_index_stream& rhs)
{
return (lhs.buffer == rhs.buffer) && (lhs.offset == rhs.offset) && (lhs.index_type == rhs.index_type);
}
//----------------------------------------------------------------------------------------------------------------------
template<typename T>
using Ogl_arg_array = std::array<T, 16>;
//----------------------------------------------------------------------------------------------------------------------
struct Ogl_arg_buffer {
Ogl_buffer* buffer {nullptr};
uint32_t offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Ogl_arg_texture {
Ogl_image* image {nullptr};
Ogl_sampler* sampler {nullptr};
};
//----------------------------------------------------------------------------------------------------------------------
class Ogl_arg_table final {
public:
Ogl_arg_table();
void clear();
void arg_buffer(const Ogl_arg_buffer& arg_buffer, uint32_t index);
void arg_texture(const Ogl_arg_texture& arg_texture, uint32_t index);
inline auto arg_buffer(uint32_t index) const noexcept
{ return arg_buffers_[index]; }
inline auto arg_texture(uint32_t index) const noexcept
{ return arg_textures_[index]; }
private:
Ogl_arg_array<Ogl_arg_buffer> arg_buffers_;
Ogl_arg_array<Ogl_arg_texture> arg_textures_;
};
//----------------------------------------------------------------------------------------------------------------------
class Ogl_render_encoder final : public Render_encoder {
public:
Ogl_render_encoder(const Render_encoder_desc& desc, Ogl_device* device, Ogl_cmd_buffer* cmd_buffer);
void end() override;
void draw(uint32_t count, uint32_t first = 0) override;
void draw_indexed(uint32_t count, uint32_t first = 0) override;
void vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index) override;
void index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type) override;
void shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index) override;
void shader_texture(Image* image, Sampler* sampler, uint32_t index) override;
void pipeline(Pipeline* pipeline) override;
void viewport(const Viewport& viewport) override;
void scissor(const Scissor& scissor) override;
Cmd_buffer* cmd_buffer() const override;
private:
void init_framebuffer_(const Render_encoder_desc& desc);
void begin_render_pass_(const Render_encoder_desc& desc);
void end_render_pass_();
void set_up_vertex_input_(const std::array<Ogl_vertex_stream, 2>& vertex_streams,
const Vertex_input& vertex_input);
void set_up_rasterization_(const Rasterization& rasterization);
void set_up_depth_stencil_(const Depth_stencil& depth_stencil);
void set_up_color_blend_(const Color_blend& color_blend);
private:
Ogl_device* device_;
Ogl_cmd_buffer* cmd_buffer_;
Ogl_framebuffer* framebuffer_;
std::deque<std::function<void ()>> cmds_;
std::array<Ogl_vertex_stream, 2> vertex_streams_;
Ogl_index_stream index_stream_;
Index_type index_type_;
Ogl_arg_table arg_table_;
Ogl_pipeline* pipeline_;
Viewport viewport_;
Scissor scissor_;
std::vector<GLenum> discards_;
};
//----------------------------------------------------------------------------------------------------------------------
class Ogl_blit_encoder final : public Blit_encoder {
public:
Ogl_blit_encoder(const Blit_encoder_desc& desc, Ogl_cmd_buffer* cmd_buffer);
void copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region) override;
void copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region) override;
void copy(Image* src_buffer, Buffer* dst_image, const Buffer_image_copy_region& region) override;
void end() override;
Cmd_buffer* cmd_buffer() const override;
private:
Ogl_cmd_buffer* cmd_buffer_;
std::deque<std::function<void ()>> cmds_;
};
//----------------------------------------------------------------------------------------------------------------------
class Ogl_cmd_buffer final : public Cmd_buffer {
public:
Ogl_cmd_buffer(Ogl_device* device);
~Ogl_cmd_buffer() override;
std::unique_ptr<Render_encoder> create(const Render_encoder_desc& desc) override;
std::unique_ptr<Blit_encoder> create(const Blit_encoder_desc& desc) override;
void end() override;
void reset() override;
Device* device() const override;
private:
Ogl_device* device_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_CMD_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_FENCE_GUARD
#define GFX_OGL_FENCE_GUARD
#include <GLES3/gl3.h>
#include "Fence.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_fence final : public Fence {
public:
Ogl_fence(const Fence_desc& desc, Ogl_device* device);
void wait_signal() override;
void reset() override;
Device* device() const override;
bool signaled() const override;
private:
Ogl_device* device_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_FENCE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "ogl_lib.h"
#include "Ogl_buffer.h"
#include "Ogl_device.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_buffer::Ogl_buffer(const Buffer_desc& desc, Ogl_device* device) :
Buffer {desc},
device_ {device},
buffer_ {0},
contents_ {nullptr}
{
init_buffer_(desc.data);
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_buffer::~Ogl_buffer()
{
fini_buffer_();
}
//----------------------------------------------------------------------------------------------------------------------
void* Ogl_buffer::map()
{
if (!contents_)
contents_ = glMapBufferRange(GL_COPY_WRITE_BUFFER, 0, size_, GL_MAP_WRITE_BIT | GL_MAP_READ_BIT);
return contents_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_buffer::unmap()
{
glUnmapBuffer(GL_COPY_WRITE_BUFFER);
contents_ = nullptr;
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_buffer::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_buffer::init_buffer_(const void* data)
{
glGenBuffers(1, &buffer_);
glBindBuffer(GL_COPY_WRITE_BUFFER, buffer_);
glBufferData(GL_COPY_WRITE_BUFFER, size_, data, to_GLDataUsage(heap_type_));
if (Heap_type::local != heap_type_) {
contents_ = glMapBufferRange(GL_COPY_WRITE_BUFFER, 0, size_, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
unmap();
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_buffer::fini_buffer_()
{
glDeleteBuffers(1, &buffer_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_SHADER_GUARD
#define GFX_OGL_SHADER_GUARD
#include <GLES3/gl3.h>
#include "Shader.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_shader final : public Shader {
public:
Ogl_shader(const Shader_desc& desc, Ogl_device* device);
~Ogl_shader() override;
Device* device() const override;
Sc_lib::Signature reflect() const noexcept override;
inline auto shader() const noexcept
{ return shader_; }
private:
void init_signature_(const std::vector<uint32_t>& src);
void init_shader_(const std::string& src);
void fini_shader_();
private:
Ogl_device* device_;
Sc_lib::Signature signature_;
GLuint shader_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_SHADER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "util.h"
using namespace glm;
using namespace Gfx_lib;
//----------------------------------------------------------------------------------------------------------------------
Plane::Plane(float w, float h) :
Primitive {}
{
init_vertices_(w / 2.0f, h / 2.0f);
init_indices_();
}
//----------------------------------------------------------------------------------------------------------------------
void Plane::init_vertices_(float half_x, float half_y)
{
vertices = {
{{-half_x, -half_y, 0.0f}, {0.0f, 0.0f, 1.0f}, {0.0f, 1.0f}},
{{ half_x, -half_y, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f}},
{{-half_x, half_y, 0.0f}, {0.0f, 0.0f, 1.0f}, {0.0f, 0.0f}},
{{ half_x, half_y, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
{{-half_x, -half_y, 0.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 1.0f}},
{{ half_x, -half_y, 0.0f}, {0.0f, 0.0f, -1.0f}, {1.0f, 1.0f}},
{{-half_x, half_y, 0.0f}, {0.0f, 0.0f, -1.0f}, {0.0f, 0.0f}},
{{ half_x, half_y, 0.0f}, {0.0f, 0.0f, -1.0f}, {1.0f, 0.0f}}
};
vertex_input.bindings[0].stride = sizeof(Vertex);
vertex_input.attributes[0].binding = 0;
vertex_input.attributes[0].format = Format::rgb32_float;
vertex_input.attributes[0].offset = offsetof(Vertex, position);
vertex_input.attributes[1].binding = 0;
vertex_input.attributes[1].format = Format::rgb32_float;
vertex_input.attributes[1].offset = offsetof(Vertex, normal);
vertex_input.attributes[2].binding = 0;
vertex_input.attributes[2].format = Format::rg32_float;
vertex_input.attributes[2].offset = offsetof(Vertex, tex_coords);
}
//----------------------------------------------------------------------------------------------------------------------
void Plane::init_indices_()
{
indices = {0, 1, 2, 1, 3, 2, 4, 6, 5, 5, 6, 7};
draw_count = indices.size();
}
//----------------------------------------------------------------------------------------------------------------------
Cube::Cube(float size) :
Primitive {}
{
init_vertices_(size / 2.0f);
init_indices_();
}
//----------------------------------------------------------------------------------------------------------------------
void Cube::init_vertices_(float half_size)
{
vertices = {
{{-half_size, -half_size, half_size}, { 0.0f, 0.0f, 1.0f}, {0.0f, 0.0f}},
{{ half_size, -half_size, half_size}, { 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
{{ half_size, half_size, half_size}, { 0.0f, 0.0f, 1.0f}, {1.0f, 1.0f}},
{{-half_size, half_size, half_size}, { 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f}},
{{ half_size, -half_size, half_size}, { 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f}},
{{ half_size, -half_size, -half_size}, { 1.0f, 0.0f, 0.0f}, {1.0f, 0.0f}},
{{ half_size, half_size, -half_size}, { 1.0f, 0.0f, 0.0f}, {1.0f, 1.0f}},
{{ half_size, half_size, half_size}, { 1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
{{-half_size, -half_size, -half_size}, { 0.0f, 0.0f, -1.0f}, {0.0f, 0.0f}},
{{-half_size, half_size, -half_size}, { 0.0f, 0.0f, -1.0f}, {1.0f, 0.0f}},
{{ half_size, half_size, -half_size}, { 0.0f, 0.0f, -1.0f}, {1.0f, 1.0f}},
{{ half_size, -half_size, -half_size}, { 0.0f, 0.0f, -1.0f}, {0.0f, 1.0f}},
{{-half_size, -half_size, half_size}, {-1.0f, 0.0f, 0.0f}, {0.0f, 0.0f}},
{{-half_size, half_size, half_size}, {-1.0f, 0.0f, 0.0f}, {1.0f, 0.0f}},
{{-half_size, half_size, -half_size}, {-1.0f, 0.0f, 0.0f}, {1.0f, 1.0f}},
{{-half_size, -half_size, -half_size}, {-1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
{{-half_size, -half_size, half_size}, { 0.0f, -1.0f, 0.0f}, {0.0f, 0.0f}},
{{-half_size, -half_size, -half_size}, { 0.0f, -1.0f, 0.0f}, {1.0f, 0.0f}},
{{ half_size, -half_size, -half_size}, { 0.0f, -1.0f, 0.0f}, {1.0f, 1.0f}},
{{ half_size, -half_size, half_size}, { 0.0f, -1.0f, 0.0f}, {0.0f, 1.0f}},
{{-half_size, half_size, half_size}, { 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f}},
{{ half_size, half_size, half_size}, { 0.0f, 1.0f, 0.0f}, {1.0f, 0.0f}},
{{ half_size, half_size, -half_size}, { 0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
{{-half_size, half_size, -half_size}, { 0.0f, 1.0f, 0.0f}, {0.0f, 1.0f}},
};
vertex_input.bindings[0].stride = sizeof(Vertex);
vertex_input.attributes[0].binding = 0;
vertex_input.attributes[0].format = Format::rgb32_float;
vertex_input.attributes[0].offset = offsetof(Vertex, position);
vertex_input.attributes[1].binding = 0;
vertex_input.attributes[1].format = Format::rgb32_float;
vertex_input.attributes[1].offset = offsetof(Vertex, normal);
vertex_input.attributes[2].binding = 0;
vertex_input.attributes[2].format = Format::rg32_float;
vertex_input.attributes[2].offset = offsetof(Vertex, tex_coords);
}
//----------------------------------------------------------------------------------------------------------------------
void Cube::init_indices_()
{
indices = {
0, 1, 2, 0, 2, 3,
4, 5, 6, 4, 6, 7,
8, 9, 10, 8, 10, 11,
12, 13, 14, 12, 14, 15,
16, 17, 18, 16, 18, 19,
20, 21, 22, 20, 22, 23
};
draw_count = indices.size();
}
//----------------------------------------------------------------------------------------------------------------------
Sphere::Sphere(float r, uint32_t sector, uint32_t stack) :
Primitive {}
{
init_vertices_(r, sector, stack);
init_indices_(sector, stack);
}
//----------------------------------------------------------------------------------------------------------------------
void Sphere::init_vertices_(float r, uint32_t sector, uint32_t stack)
{
vertices.reserve((sector + 1) * (stack + 1));
auto sector_step = two_pi<float>() / sector;
auto stack_step = pi<float>() / stack;
for (auto i = 0; i <= stack; ++i) {
auto stack_angle = pi<float>() / 2 - i * stack_step;
auto xy = r * cosf(stack_angle);
for (auto j = 0; j <= sector; ++j) {
auto sector_angle = j * sector_step;
Vertex vertex;
vertex.position = {xy * cosf(sector_angle), xy * sinf(sector_angle), r * sinf(stack_angle)};
vertex.normal = normalize(vertex.position);
vertex.tex_coords = {static_cast<float>(j) / sector, static_cast<float>(i) / stack};
vertices.push_back(vertex);
}
}
vertex_input.bindings[0].stride = sizeof(Vertex);
vertex_input.attributes[0].binding = 0;
vertex_input.attributes[0].format = Format::rgb32_float;
vertex_input.attributes[0].offset = offsetof(Vertex, position);
vertex_input.attributes[1].binding = 0;
vertex_input.attributes[1].format = Format::rgb32_float;
vertex_input.attributes[1].offset = offsetof(Vertex, normal);
vertex_input.attributes[2].binding = 0;
vertex_input.attributes[2].format = Format::rg32_float;
vertex_input.attributes[2].offset = offsetof(Vertex, tex_coords);
}
//----------------------------------------------------------------------------------------------------------------------
void Sphere::init_indices_(uint32_t sector, uint32_t stack)
{
indices.reserve((sector * 2 * (stack - 1)) * 3);
for (auto i = 0; i != stack; ++i) {
auto cur_stack_start = i * (sector + 1);
auto nxt_stack_start = cur_stack_start + sector + 1;
for (auto j = 0; j != sector; ++j, ++cur_stack_start, ++nxt_stack_start) {
if(i != 0) {
indices.push_back(cur_stack_start);
indices.push_back(nxt_stack_start);
indices.push_back(cur_stack_start + 1);
}
if (i != stack - 1) {
indices.push_back(cur_stack_start + 1);
indices.push_back(nxt_stack_start);
indices.push_back(nxt_stack_start + 1);
}
}
}
draw_count = indices.size();
}
//----------------------------------------------------------------------------------------------------------------------
Torus::Torus(float inner_radius, float outer_radius, uint32_t side_count, uint32_t ring_count) :
Primitive {}
{
init_vertices_(inner_radius, outer_radius, side_count, ring_count);
init_indices_(side_count, ring_count);
}
//----------------------------------------------------------------------------------------------------------------------
void Torus::init_vertices_(float inner_radius, float outer_radius, uint32_t side_count, uint32_t ring_count)
{
vertices.reserve(side_count * (ring_count + 1));
auto ring_factor = two_pi<float>() / ring_count;
auto side_factor = two_pi<float>() / side_count;
for (auto ring = 0; ring <= ring_count; ++ring) {
auto u = ring * ring_factor;
auto cos_u = cos(u);
auto sin_u = sin(u);
for (auto side = 0; side != side_count; ++side) {
auto v = side * side_factor;
auto cos_v = cos(v);
auto sin_v = sin(v);
auto r = outer_radius + inner_radius * cos_v;
Vertex vertex {
{ r * cos_u, r * sin_u, inner_radius * sin_v },
{ cos_v * cos_u * r, cos_v * sin_u * r, sin_v * r},
{ u / two_pi<float>(), v / two_pi<float>() }
};
vertex.normal = normalize(vertex.normal);
vertices.push_back(vertex);
}
}
vertex_input.bindings[0].stride = sizeof(Vertex);
vertex_input.attributes[0].binding = 0;
vertex_input.attributes[0].format = Format::rgb32_float;
vertex_input.attributes[0].offset = offsetof(Vertex, position);
vertex_input.attributes[1].binding = 0;
vertex_input.attributes[1].format = Format::rgb32_float;
vertex_input.attributes[1].offset = offsetof(Vertex, normal);
vertex_input.attributes[2].binding = 0;
vertex_input.attributes[2].format = Format::rg32_float;
vertex_input.attributes[2].offset = offsetof(Vertex, tex_coords);
}
//----------------------------------------------------------------------------------------------------------------------
void Torus::init_indices_(uint32_t side_count, uint32_t ring_count)
{
indices.reserve(side_count * ring_count);
for (auto ring = 0; ring != ring_count; ++ring) {
auto cur_ring_offset = ring * side_count;
auto nxt_ring_offset = cur_ring_offset + side_count;
for (auto side = 0; side != side_count; ++side) {
auto nxt_side = (side + 1) % side_count;
indices.push_back(cur_ring_offset + side);
indices.push_back(nxt_ring_offset + side);
indices.push_back(nxt_ring_offset + nxt_side);
indices.push_back(cur_ring_offset + side);
indices.push_back(nxt_ring_offset + nxt_side);
indices.push_back(cur_ring_offset + nxt_side);
}
}
draw_count = indices.size();
}
//----------------------------------------------------------------------------------------------------------------------
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_SAMPLER_GUARD
#define GFX_SAMPLER_GUARD
#include "enums.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
//----------------------------------------------------------------------------------------------------------------------
struct Sampler_desc final {
Filter min {Filter::linear};
Filter mag {Filter::linear};
Mip_filter mip {Mip_filter::linear};
Address_mode u {Address_mode::clamp_to_edge};
Address_mode v {Address_mode::clamp_to_edge};
Address_mode w {Address_mode::clamp_to_edge};
};
//----------------------------------------------------------------------------------------------------------------------
class Sampler {
public:
explicit Sampler(const Sampler_desc& desc) noexcept :
min_ {desc.min},
mag_ {desc.mag},
mip_ {desc.mip},
u_ {desc.u},
v_ {desc.v},
w_ {desc.w}
{}
virtual ~Sampler() = default;
virtual Device* device() const = 0;
inline Filter min() const noexcept
{ return min_; }
inline Filter mag() const noexcept
{ return mag_; }
inline Mip_filter mip() const noexcept
{ return mip_; }
inline Address_mode u() const noexcept
{ return u_; }
inline Address_mode v() const noexcept
{ return v_; }
inline Address_mode w() const noexcept
{ return w_; }
protected:
Filter min_;
Filter mag_;
Mip_filter mip_;
Address_mode u_;
Address_mode v_;
Address_mode w_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_SAMPLER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "ogl_lib.h"
#include "Ogl_pipeline.h"
#include "Ogl_device.h"
#include "Ogl_shader.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_pipeline::Ogl_pipeline(const Pipeline_desc& desc, Ogl_device* device) :
Pipeline {desc},
device_ {device},
program_ {0}
{
init_program_(desc.vertex_shader, desc.fragment_shader);
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_pipeline::~Ogl_pipeline()
{
fini_program_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_pipeline::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_pipeline::init_program_(Shader* vertex_shader, Shader* fragment_shader)
{
program_ = glCreateProgram();
if (!program_)
throw runtime_error("fail to create a pipeline");
glAttachShader(program_, static_cast<Ogl_shader*>(vertex_shader)->shader());
glAttachShader(program_, static_cast<Ogl_shader*>(fragment_shader)->shader());
glLinkProgram(program_);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_pipeline::fini_program_()
{
glDeleteProgram(program_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_SWAP_CHAIN_GUARD
#define GFX_OGL_SWAP_CHAIN_GUARD
#include <memory>
#include <vector>
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include "Swap_chain.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
class Ogl_image;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_swap_chain final : public Swap_chain {
public:
Ogl_swap_chain(const Swap_chain_desc& desc, Ogl_device* device);
~Ogl_swap_chain() override;
Image* acquire() override;
void present() override;
Device* device() const override;
inline auto surface() const noexcept
{ return surface_; }
private:
void init_surface_(void* window);
void init_images_();
void fini_surface_();
private:
Ogl_device* device_;
EGLSurface surface_;
uint64_t image_index_;
std::vector<std::unique_ptr<Ogl_image>> images_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_SWAP_CHAIN_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <metrohash.h>
#include "ogl_lib.h"
#include "Ogl_device.h"
#include "Ogl_buffer.h"
#include "Ogl_image.h"
#include "Ogl_sampler.h"
#include "Ogl_shader.h"
#include "Ogl_pipeline.h"
#include "Ogl_swap_chain.h"
#include "Ogl_cmd_buffer.h"
#include "Ogl_fence.h"
using namespace std;
#define DEFINE_OGL_SYMBOL(name) PFN_##name name;
#define LOAD_OGL_CONTEXT_SYMBOL(name) name = reinterpret_cast<PFN_##name>(eglGetProcAddress(#name));
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
APPLY_OGL_DRAW_BUFFERS_INDEXED_SYMBOLS(DEFINE_OGL_SYMBOL);
//----------------------------------------------------------------------------------------------------------------------
Ogl_device::Ogl_device()
: Device {}
, display_ {EGL_NO_DISPLAY}
, context_ {EGL_NO_CONTEXT}
{
init_display_();
init_context_();
init_context_symbols_();
init_caps_();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_device::~Ogl_device()
{
fini_context_();
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Buffer> Ogl_device::create(const Buffer_desc& desc)
{
return make_unique<Ogl_buffer>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Image> Ogl_device::create(const Image_desc& desc)
{
return make_unique<Ogl_image>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Sampler> Ogl_device::create(const Sampler_desc& desc)
{
return make_unique<Ogl_sampler>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Shader> Ogl_device::create(const Shader_desc& desc)
{
return make_unique<Ogl_shader>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Pipeline> Ogl_device::create(const Pipeline_desc& desc)
{
return make_unique<Ogl_pipeline>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Swap_chain> Ogl_device::create(const Swap_chain_desc& desc)
{
return make_unique<Ogl_swap_chain>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Cmd_buffer> Ogl_device::create(const Cmd_buffer_desc& desc)
{
return make_unique<Ogl_cmd_buffer>(this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Fence> Ogl_device::create(const Fence_desc& desc)
{
return make_unique<Ogl_fence>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::submit(Cmd_buffer* cmd_buffer, Fence* fence)
{
glFlush();
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::wait_idle()
{
glFinish();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_framebuffer* Ogl_device::framebuffer(const Ogl_framebuffer_desc& desc)
{
// calculate a hash value.
uint64_t key { 0 };
MetroHash64::Hash(reinterpret_cast<const uint8_t*>(&desc), sizeof(Ogl_framebuffer_desc),
reinterpret_cast<uint8_t*>(&key));
// check a framebuffer exists and if not then create it.
if (!framebuffer_pool_.contains(key))
framebuffer_pool_.emplace(key, desc, this);
return *framebuffer_pool_.find(key);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::init_display_()
{
display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (EGL_NO_DISPLAY == display_)
throw runtime_error("fail to create a device");
eglInitialize(display_, nullptr, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::init_context_()
{
constexpr EGLint attributes[] {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE
};
context_ = eglCreateContext(display_, 0 ,EGL_NO_CONTEXT, attributes);
if (EGL_NO_CONTEXT == context_)
throw runtime_error("fail to create a device");
eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, context_);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::init_context_symbols_()
{
APPLY_OGL_DRAW_BUFFERS_INDEXED_SYMBOLS(LOAD_OGL_CONTEXT_SYMBOL);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::init_caps_()
{
caps_.window_coords = Coords::origin_lower_left;
caps_.texture_coords = Coords::origin_lower_left;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_device::fini_context_()
{
eglDestroyContext(display_, context_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_FENCE_GUARD
#define GFX_VLK_FENCE_GUARD
#include <vulkan/vulkan.h>
#include "gfx/Fence.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_fence final : public Fence {
public:
Vlk_fence(const Fence_desc& desc, Vlk_device* device);
void wait_signal() override;
void reset() override;
Device* device() const override;
bool signaled() const override;
inline auto fence() const noexcept
{ return fence_; }
private:
void init_fence_(bool signaled);
private:
Vlk_device* device_;
VkFence fence_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_FENCE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_SHADER_GUARD
#define GFX_VLK_SHADER_GUARD
#include <vulkan/vulkan.h>
#include "Shader.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_shader final : public Shader {
public:
Vlk_shader(const Shader_desc& desc, Vlk_device* device);
~Vlk_shader() override;
Device* device() const override;
Sc_lib::Signature reflect() const noexcept override;
inline auto shader_module() const noexcept
{ return shader_module_; }
private:
void init_signature_(const std::vector<uint32_t>& src);
void init_shader_module_(const std::vector<uint32_t>& src);
void fini_shader_module();
private:
Vlk_device* device_;
Sc_lib::Signature signature_;
VkShaderModule shader_module_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_SHADER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_IMAGE_GUARD
#define GFX_VLK_IMAGE_GUARD
#include <vulkan/vulkan.h>
#include <vk_mem_alloc.h>
#include "gfx/Image.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_swap_chain;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_image final : public Image {
public:
Vlk_image(const Image_desc& desc, Vlk_device* device);
Vlk_image(const Image_desc& desc, Vlk_device* device, Vlk_swap_chain* swap_chain, VkImage image);
~Vlk_image() override;
Device* device() const override;
inline auto& image() const noexcept
{ return image_; }
inline auto& access_mask() const noexcept
{ return access_mask_; }
inline auto& layout() const noexcept
{ return layout_; }
inline auto& image_view() const noexcept
{ return image_view_; }
inline auto& aspect_mask() const noexcept
{ return aspect_mask_; }
private:
void init_image_and_alloc_();
void init_image_view_();
void fini_image_and_alloc_();
void fini_image_view_();
private:
Vlk_device* device_;
Vlk_swap_chain* swap_chain_;
VkImage image_;
VmaAllocation alloc_;
VkAccessFlags access_mask_;
VkImageLayout layout_;
VkImageView image_view_;
VkImageAspectFlags aspect_mask_;
friend class Vlk_swap_chain;
friend class Vlk_render_encoder;
friend class Vlk_blit_encoder;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_IMAGE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_SAMPLER_GUARD
#define GFX_OGL_SAMPLER_GUARD
#include <GLES3/gl3.h>
#include "Sampler.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_sampler final : public Sampler {
public:
Ogl_sampler(const Sampler_desc& desc, Ogl_device* device);
~Ogl_sampler() override;
Device* device() const override;
inline auto sampler() const noexcept
{ return sampler_; }
private:
void init_sampler_();
void fini_sampler_();
private:
Ogl_device* device_;
GLuint sampler_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_SAMPLER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_LIB_MODULES_GUARD
#define GFX_VLK_LIB_MODULES_GUARD
#include <platform/build_target.h>
#define VK_NO_PROTOTYPES 1
#if defined(__ANDROID__)
#define VK_USE_PLATFORM_ANDROID_KHR
#elif defined(_WIN32)
#define VK_USE_PLATFORM_WIN32_KHR
#elif TARGET_OS_OSX
#define VK_USE_PLATFORM_MACOS_MVK
#endif
#include <stdexcept>
#include <vulkan/vulkan.h>
#include <vk_mem_alloc.h>
#include "gfx/enums.h"
#include "gfx/types.h"
//----------------------------------------------------------------------------------------------------------------------
#define APPLY_VLK_BOOTSTRAP_SYMBOLS(macro) \
macro(vkGetInstanceProcAddr) \
macro(vkCreateInstance) \
macro(vkDestroyInstance) \
macro(vkEnumerateInstanceExtensionProperties) \
macro(vkEnumerateInstanceLayerProperties) \
macro(vkEnumeratePhysicalDevices) \
macro(vkGetPhysicalDeviceProperties )
#define APPLY_VLK_INSTANCE_CORE_SYMBOLS(macro) \
macro(vkGetDeviceProcAddr) \
macro(vkGetPhysicalDeviceFeatures) \
macro(vkGetPhysicalDeviceFormatProperties) \
macro(vkGetPhysicalDeviceImageFormatProperties) \
macro(vkGetPhysicalDeviceQueueFamilyProperties) \
macro(vkGetPhysicalDeviceMemoryProperties) \
macro(vkGetPhysicalDeviceSparseImageFormatProperties) \
macro(vkCreateDevice) \
macro(vkDestroyDevice) \
macro(vkEnumerateDeviceExtensionProperties) \
macro(vkEnumerateDeviceLayerProperties)
#define APPLY_VLK_INSTANCE_SURFACE_SYMBOLS(macro) \
macro(vkDestroySurfaceKHR) \
macro(vkGetPhysicalDeviceSurfaceSupportKHR) \
macro(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \
macro(vkGetPhysicalDeviceSurfaceFormatsKHR) \
macro(vkGetPhysicalDeviceSurfacePresentModesKHR)
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#define APPLY_VLK_INSTANCE_ANDROID_SURFACE_SYMBOLS(macro) \
macro(vkCreateAndroidSurfaceKHR)
#else
#define APPLY_VLK_INSTANCE_ANDROID_SURFACE_SYMBOLS(macro)
#endif
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#define APPLY_VLK_INSTANCE_WIN32_SURFACE_SYMBOLS(macro) \
macro(vkCreateWin32SurfaceKHR) \
macro(vkGetPhysicalDeviceWin32PresentationSupportKHR)
#else
#define APPLY_VLK_INSTANCE_WIN32_SURFACE_SYMBOLS(macro)
#endif
#if defined(VK_USE_PLATFORM_MACOS_MVK)
#define APPLY_VLK_INSTANCE_OSX_SURFACE_SYMBOLS(macro) \
macro(vkCreateMacOSSurfaceMVK)
#else
#define APPLY_VLK_INSTANCE_OSX_SURFACE_SYMBOLS(macro)
#endif
#define APPLY_VLK_INSTANCE_DEBUG_REPORT_SYMBOLS(macro) \
macro(vkCreateDebugReportCallbackEXT) \
macro(vkDebugReportMessageEXT) \
macro(vkDestroyDebugReportCallbackEXT)
#define APPLY_VLK_DEVICE_CORE_SYMBOLS(macro) \
macro(vkGetDeviceQueue) \
macro(vkQueueSubmit) \
macro(vkQueueWaitIdle) \
macro(vkDeviceWaitIdle) \
macro(vkAllocateMemory) \
macro(vkFreeMemory) \
macro(vkMapMemory) \
macro(vkUnmapMemory) \
macro(vkFlushMappedMemoryRanges) \
macro(vkInvalidateMappedMemoryRanges) \
macro(vkGetDeviceMemoryCommitment) \
macro(vkBindBufferMemory) \
macro(vkBindImageMemory) \
macro(vkGetBufferMemoryRequirements) \
macro(vkGetImageMemoryRequirements) \
macro(vkGetImageSparseMemoryRequirements) \
macro(vkQueueBindSparse) \
macro(vkCreateFence) \
macro(vkDestroyFence) \
macro(vkResetFences) \
macro(vkGetFenceStatus) \
macro(vkWaitForFences) \
macro(vkCreateSemaphore) \
macro(vkDestroySemaphore) \
macro(vkCreateEvent) \
macro(vkDestroyEvent) \
macro(vkGetEventStatus) \
macro(vkSetEvent) \
macro(vkResetEvent) \
macro(vkCreateQueryPool) \
macro(vkDestroyQueryPool) \
macro(vkGetQueryPoolResults) \
macro(vkCreateBuffer) \
macro(vkDestroyBuffer) \
macro(vkCreateBufferView) \
macro(vkDestroyBufferView) \
macro(vkCreateImage) \
macro(vkDestroyImage) \
macro(vkGetImageSubresourceLayout) \
macro(vkCreateImageView) \
macro(vkDestroyImageView) \
macro(vkCreateShaderModule) \
macro(vkDestroyShaderModule) \
macro(vkCreatePipelineCache) \
macro(vkDestroyPipelineCache) \
macro(vkGetPipelineCacheData) \
macro(vkMergePipelineCaches) \
macro(vkCreateGraphicsPipelines) \
macro(vkCreateComputePipelines) \
macro(vkDestroyPipeline) \
macro(vkCreatePipelineLayout) \
macro(vkDestroyPipelineLayout) \
macro(vkCreateSampler) \
macro(vkDestroySampler) \
macro(vkCreateDescriptorSetLayout) \
macro(vkDestroyDescriptorSetLayout) \
macro(vkCreateDescriptorPool) \
macro(vkDestroyDescriptorPool) \
macro(vkResetDescriptorPool) \
macro(vkAllocateDescriptorSets) \
macro(vkFreeDescriptorSets) \
macro(vkUpdateDescriptorSets) \
macro(vkCreateFramebuffer) \
macro(vkDestroyFramebuffer) \
macro(vkCreateRenderPass) \
macro(vkDestroyRenderPass) \
macro(vkGetRenderAreaGranularity) \
macro(vkCreateCommandPool) \
macro(vkDestroyCommandPool) \
macro(vkResetCommandPool) \
macro(vkAllocateCommandBuffers) \
macro(vkFreeCommandBuffers) \
macro(vkBeginCommandBuffer) \
macro(vkEndCommandBuffer) \
macro(vkResetCommandBuffer) \
macro(vkCmdBindPipeline) \
macro(vkCmdSetViewport) \
macro(vkCmdSetScissor) \
macro(vkCmdSetLineWidth) \
macro(vkCmdSetDepthBias) \
macro(vkCmdSetBlendConstants) \
macro(vkCmdSetDepthBounds) \
macro(vkCmdSetStencilCompareMask) \
macro(vkCmdSetStencilWriteMask) \
macro(vkCmdSetStencilReference) \
macro(vkCmdBindDescriptorSets) \
macro(vkCmdBindIndexBuffer) \
macro(vkCmdBindVertexBuffers) \
macro(vkCmdDraw) \
macro(vkCmdDrawIndexed) \
macro(vkCmdDrawIndirect) \
macro(vkCmdDrawIndexedIndirect) \
macro(vkCmdDispatch) \
macro(vkCmdDispatchIndirect) \
macro(vkCmdCopyBuffer) \
macro(vkCmdCopyImage) \
macro(vkCmdBlitImage) \
macro(vkCmdCopyBufferToImage) \
macro(vkCmdCopyImageToBuffer) \
macro(vkCmdUpdateBuffer) \
macro(vkCmdFillBuffer) \
macro(vkCmdClearColorImage) \
macro(vkCmdClearDepthStencilImage) \
macro(vkCmdClearAttachments) \
macro(vkCmdResolveImage) \
macro(vkCmdSetEvent) \
macro(vkCmdResetEvent) \
macro(vkCmdWaitEvents) \
macro(vkCmdPipelineBarrier) \
macro(vkCmdBeginQuery) \
macro(vkCmdEndQuery) \
macro(vkCmdResetQueryPool) \
macro(vkCmdWriteTimestamp) \
macro(vkCmdCopyQueryPoolResults) \
macro(vkCmdPushConstants) \
macro(vkCmdBeginRenderPass) \
macro(vkCmdNextSubpass) \
macro(vkCmdEndRenderPass) \
macro(vkCmdExecuteCommands)
#define APPLY_VLK_DEVICE_SWAPCHAIN_SYMBOLS(macro) \
macro(vkCreateSwapchainKHR) \
macro(vkDestroySwapchainKHR) \
macro(vkGetSwapchainImagesKHR) \
macro(vkAcquireNextImageKHR) \
macro(vkQueuePresentKHR)
#define DECLARE_VLK_SYMBOL(name) extern PFN_##name name;
//----------------------------------------------------------------------------------------------------------------------
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
APPLY_VLK_BOOTSTRAP_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_CORE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_SURFACE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_ANDROID_SURFACE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_WIN32_SURFACE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_OSX_SURFACE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_INSTANCE_DEBUG_REPORT_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_DEVICE_CORE_SYMBOLS(DECLARE_VLK_SYMBOL)
APPLY_VLK_DEVICE_SWAPCHAIN_SYMBOLS(DECLARE_VLK_SYMBOL)
//----------------------------------------------------------------------------------------------------------------------
inline VkExtent2D to_VkExtent2D(Extent extent)
{
return { extent.w, extent.h };
}
//----------------------------------------------------------------------------------------------------------------------
inline VkExtent3D to_VkExtent3D(Extent extent)
{
return { extent.w, extent.h, extent.d };
}
//----------------------------------------------------------------------------------------------------------------------
inline VmaMemoryUsage to_VmaMemoryUsage(Heap_type type)
{
switch (type) {
case Heap_type::local:
return VMA_MEMORY_USAGE_GPU_ONLY;
case Heap_type::upload:
return VMA_MEMORY_USAGE_CPU_TO_GPU;
case Heap_type::readback:
return VMA_MEMORY_USAGE_GPU_TO_CPU;
default:
throw std::runtime_error("invalid the heap type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkImageType to_VkImageType(Image_type type)
{
switch (type) {
case Image_type::two_dim:
case Image_type::cube:
return VK_IMAGE_TYPE_2D;
default:
throw std::runtime_error("invalid the image type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkFormat to_VkFormat(Format format)
{
switch (format) {
case Format::rgb8_unorm:
return VK_FORMAT_R8G8B8_UNORM;
case Format::rgba8_unorm:
return VK_FORMAT_R8G8B8A8_UNORM;
case Format::bgra8_unorm:
return VK_FORMAT_B8G8R8A8_UNORM;
case Format::r32_float:
return VK_FORMAT_R32_SFLOAT;
case Format::rg32_float:
return VK_FORMAT_R32G32_SFLOAT;
case Format::rgb32_float:
return VK_FORMAT_R32G32B32_SFLOAT;
case Format::rgba32_float:
return VK_FORMAT_R32G32B32_SFLOAT;
case Format::d24_unorm_s8_uint:
return VK_FORMAT_D24_UNORM_S8_UINT;
default:
throw std::runtime_error("invalid the format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkImageAspectFlags to_VkImageAspectFlags(Format format)
{
switch (format) {
case Format::rgba8_unorm:
return VK_IMAGE_ASPECT_COLOR_BIT;
case Format::bgra8_unorm:
return VK_IMAGE_ASPECT_COLOR_BIT;
case Format::r32_float:
return VK_IMAGE_ASPECT_COLOR_BIT;
case Format::rg32_float:
return VK_IMAGE_ASPECT_COLOR_BIT;
case Format::rgba32_float:
return VK_IMAGE_ASPECT_COLOR_BIT;
case Format::d24_unorm_s8_uint:
return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
default:
throw std::runtime_error("invalid the format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkSampleCountFlagBits to_VkSampleCountFlagBits(uint8_t samples)
{
return static_cast<VkSampleCountFlagBits>(0x1 << (samples - 1));
}
//----------------------------------------------------------------------------------------------------------------------
inline VkImageViewType to_VkImageViewType(Image_type type)
{
switch (type) {
case Image_type::two_dim:
case Image_type::swap_chain:
return VK_IMAGE_VIEW_TYPE_2D;
case Image_type::cube:
return VK_IMAGE_VIEW_TYPE_CUBE;
default:
throw std::runtime_error("invalid the image type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkFilter to_VkFilter(Filter filter)
{
switch (filter) {
case Filter::nearest:
return VK_FILTER_NEAREST;
case Filter::linear:
return VK_FILTER_LINEAR;
default:
throw std::runtime_error("invalid the filter");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkSamplerMipmapMode to_VkSamplerMipmapMode(Mip_filter filter)
{
switch (filter) {
case Mip_filter::nearest:
return VK_SAMPLER_MIPMAP_MODE_NEAREST;
case Mip_filter::linear:
return VK_SAMPLER_MIPMAP_MODE_LINEAR;
default:
throw std::runtime_error("invalid the filter");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkSamplerAddressMode to_VkSamplerAddressMode(Address_mode mode)
{
switch (mode) {
case Address_mode::repeat:
return VK_SAMPLER_ADDRESS_MODE_REPEAT;
case Address_mode::clamp_to_edge:
return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
default:
throw std::runtime_error("invalid the address mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkShaderStageFlagBits to_VkShaderStageFlagBits(Sc_lib::Shader_type type)
{
switch (type) {
case Sc_lib::Shader_type::vertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case Sc_lib::Shader_type ::fragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
default:
throw std::runtime_error("invalid the shader type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkVertexInputRate to_VkVertexInputRate(Step_rate rate)
{
switch (rate) {
case Step_rate::vertex:
return VK_VERTEX_INPUT_RATE_VERTEX;
case Step_rate::instance:
return VK_VERTEX_INPUT_RATE_INSTANCE;
default:
throw std::runtime_error("invalid the step rate");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkPrimitiveTopology to_VkPrimitiveTopology(Topology topology)
{
switch (topology) {
case Topology::triangle_list:
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
case Topology::triangle_strip:
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
case Topology::point:
return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
default:
throw std::runtime_error("invalid the topology");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkCullModeFlags to_VkCullModeFlags(Cull_mode mode)
{
switch (mode) {
case Cull_mode::front:
return VK_CULL_MODE_FRONT_BIT;
case Cull_mode::back:
return VK_CULL_MODE_BACK_BIT;
case Cull_mode::none:
return VK_CULL_MODE_NONE;
default:
throw std::runtime_error("invalid the cull mode");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkFrontFace to_VkFrontFace(Front_face face)
{
switch (face) {
case Front_face::counter_clockwise:
return VK_FRONT_FACE_COUNTER_CLOCKWISE;
case Front_face::clockwise:
return VK_FRONT_FACE_CLOCKWISE;
default:
throw std::runtime_error("invalid the front face");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkCompareOp to_VkCompareOp(Compare_op op)
{
switch (op) {
case Compare_op::never:
return VK_COMPARE_OP_NEVER;
case Compare_op::less:
return VK_COMPARE_OP_LESS;
case Compare_op::greater:
return VK_COMPARE_OP_GREATER;
case Compare_op::equal:
return VK_COMPARE_OP_EQUAL;
case Compare_op::not_equal:
return VK_COMPARE_OP_NOT_EQUAL;
case Compare_op::less_or_equal:
return VK_COMPARE_OP_LESS_OR_EQUAL;
case Compare_op::greater_or_equal:
return VK_COMPARE_OP_GREATER_OR_EQUAL;
case Compare_op::always:
return VK_COMPARE_OP_ALWAYS;
default:
throw std::runtime_error("invalid the compare op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkStencilOp to_VkStencilOp(Stencil_op op)
{
switch (op) {
case Stencil_op::keep:
return VK_STENCIL_OP_KEEP;
case Stencil_op::zero:
return VK_STENCIL_OP_ZERO;
case Stencil_op::replace:
return VK_STENCIL_OP_REPLACE;
case Stencil_op::increment_and_clamp:
return VK_STENCIL_OP_INCREMENT_AND_CLAMP;
case Stencil_op::decrement_and_clamp:
return VK_STENCIL_OP_DECREMENT_AND_CLAMP;
case Stencil_op::invert:
return VK_STENCIL_OP_INVERT;
case Stencil_op::increment_and_wrap:
return VK_STENCIL_OP_INCREMENT_AND_WRAP;
case Stencil_op::decrement_and_wrap:
return VK_STENCIL_OP_DECREMENT_AND_WRAP;
default:
throw std::runtime_error("invalid the stencil op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkBlendFactor to_VkBlendFactor(Blend_factor factor)
{
switch (factor) {
case Blend_factor::zero:
return VK_BLEND_FACTOR_ZERO;
case Blend_factor::one:
return VK_BLEND_FACTOR_ONE;
case Blend_factor::src_alpha:
return VK_BLEND_FACTOR_SRC_ALPHA;
case Blend_factor::one_minus_src_alpha:
return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
case Blend_factor::dst_alpha:
return VK_BLEND_FACTOR_DST_ALPHA;
case Blend_factor::one_minus_dst_alpha:
return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
default:
throw std::runtime_error("invalid the blend factor");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkBlendOp to_VkBlendOp(Blend_op op)
{
switch (op) {
case Blend_op::add:
return VK_BLEND_OP_ADD;
case Blend_op::subtract:
return VK_BLEND_OP_SUBTRACT;
case Blend_op::reverse_subtract:
return VK_BLEND_OP_REVERSE_SUBTRACT;
case Blend_op::min:
return VK_BLEND_OP_MIN;
case Blend_op::max:
return VK_BLEND_OP_MAX;
default:
throw std::runtime_error("invalid the blend op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkIndexType to_VkIndexType(Index_type type)
{
switch (type) {
case Index_type::uint16:
return VK_INDEX_TYPE_UINT16;
case Index_type::uint32:
return VK_INDEX_TYPE_UINT32;
default:
throw std::runtime_error("invalid the index type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkViewport to_VkViewport(Viewport viewport)
{
return {viewport.x, viewport.h - viewport.y, viewport.w, -viewport.h, 0.0f, 1.0f};
}
//----------------------------------------------------------------------------------------------------------------------
inline VkRect2D to_VkRect2D(Scissor scissor)
{
return {{static_cast<int32_t>(scissor.x), static_cast<int32_t>(scissor.y)}, {scissor.w, scissor.h}};
}
//----------------------------------------------------------------------------------------------------------------------
inline VkAttachmentLoadOp to_VkAttachmentLoadOp(Load_op op)
{
switch (op) {
case Load_op::load:
return VK_ATTACHMENT_LOAD_OP_LOAD;
case Load_op::clear:
return VK_ATTACHMENT_LOAD_OP_CLEAR;
case Load_op::dont_care:
return VK_ATTACHMENT_LOAD_OP_DONT_CARE;
default:
throw std::runtime_error("invalid the load op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkAttachmentStoreOp to_VkAttachmentStoreOp(Store_op op)
{
switch (op) {
case Store_op::store:
return VK_ATTACHMENT_STORE_OP_STORE;
case Store_op::dont_care:
return VK_ATTACHMENT_STORE_OP_DONT_CARE;
default:
throw std::runtime_error("invalid the store op");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline VkColorSpaceKHR to_VkColorSpaceKHR(Color_space space)
{
switch (space) {
case Color_space::srgb_non_linear:
return VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
default:
throw std::runtime_error("invalid color space");
}
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_LIB_MODULES_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_BUFFER_GUARD
#define GFX_MTL_BUFFER_GUARD
#include <Metal/Metal.h>
#include "Buffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_buffer final : public Buffer {
public:
Mtl_buffer(const Buffer_desc& desc, Mtl_device* device);
void* map() override;
void unmap() override;
Device* device() const override;
inline id<MTLBuffer> buffer() const noexcept
{ return buffer_; }
private:
void init_buffer_(const void* data);
private:
Mtl_device* device_;
id<MTLBuffer> buffer_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_TYPES_GUARD
#define GFX_TYPES_GUARD
#include <platform/Extent.h>
#include <sc/enums.h>
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
using Extent = Platform_lib::Extent;
//----------------------------------------------------------------------------------------------------------------------
struct Offset final {
uint64_t x {0};
uint64_t y {0};
uint64_t z {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Clear_value final {
struct {
float r;
float g;
float b;
float a;
};
struct {
float d;
uint32_t s;
};
};
//----------------------------------------------------------------------------------------------------------------------
struct Viewport final {
float x {0.0f};
float y {0.0f};
float w {0.0f};
float h {0.0f};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Viewport& lhs, const Viewport& rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.w == rhs.w && lhs.h == rhs.h;
}
//----------------------------------------------------------------------------------------------------------------------
struct Scissor final {
uint32_t x {0};
uint32_t y {0};
uint32_t w {0};
uint32_t h {0};
};
//----------------------------------------------------------------------------------------------------------------------
inline auto operator==(const Scissor& lhs, const Scissor& rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.w == rhs.w && lhs.h == rhs.h;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_TYPES_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_SAMPLER_GUARD
#define GFX_MTL_SAMPLER_GUARD
#include <Metal/Metal.h>
#include "Sampler.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_sampler final : public Sampler {
public:
Mtl_sampler(const Sampler_desc& desc, Mtl_device* device);
Device* device() const override;
inline auto sampler_state() const noexcept
{ return sampler_state_; }
private:
void init_sampler_state_();
private:
Mtl_device* device_;
id<MTLSamplerState> sampler_state_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_SAMPLER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "ogl_lib.h"
#include "Ogl_cmd_buffer.h"
#include "Ogl_device.h"
#include "Ogl_buffer.h"
#include "Ogl_image.h"
#include "Ogl_sampler.h"
#include "Ogl_pipeline.h"
using namespace std;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
inline auto component_count(Format format)
{
switch (format) {
case Format::r32_float:
return 1;
case Format::rg32_float:
return 2;
case Format::rgb32_float:
return 3;
case Format::rgba32_float:
return 4;
default:
throw runtime_error("invalid format");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline auto byte_size(Index_type type)
{
switch (type) {
case Index_type::uint16:
return sizeof(uint16_t);
case Index_type::uint32:
return sizeof(uint32_t);
default:
throw runtime_error("invalid the index type");
}
}
//----------------------------------------------------------------------------------------------------------------------
inline void execute(function<void ()>& func)
{
func();
}
//----------------------------------------------------------------------------------------------------------------------
inline Ogl_framebuffer_desc to_Ogl_framebuffer_desc(const Render_encoder_desc& desc)
{
array<Ogl_image*, 4> color_images;
for (auto i = 0; i != 4; ++i) {
color_images[i] = static_cast<Ogl_image*>(desc.colors[i].image);
}
return {color_images, static_cast<Ogl_image*>(desc.depth_stencil.image)};
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_arg_table::Ogl_arg_table() :
arg_buffers_ {},
arg_textures_ {}
{
clear();
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_arg_table::clear()
{
arg_buffers_.fill({nullptr, 0});
arg_textures_.fill({nullptr, nullptr});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_arg_table::arg_buffer(const Ogl_arg_buffer& arg_buffer, uint32_t index)
{
arg_buffers_[index] = arg_buffer;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_arg_table::arg_texture(const Ogl_arg_texture& arg_texture, uint32_t index)
{
arg_textures_[index] = arg_texture;
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_render_encoder::Ogl_render_encoder(const Render_encoder_desc& desc, Ogl_device* device, Ogl_cmd_buffer* cmd_buffer) :
Render_encoder {},
device_ {device},
cmd_buffer_ {cmd_buffer},
framebuffer_ {nullptr},
vertex_streams_ {},
index_stream_ {},
index_type_ {Index_type::invalid},
arg_table_ {},
pipeline_ {nullptr},
viewport_ {},
scissor_ {},
discards_ {}
{
init_framebuffer_(desc);
begin_render_pass_(desc);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::end()
{
end_render_pass_();
for_each(cmds_, execute);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::draw(uint32_t count, uint32_t first)
{
auto input_assembly = pipeline_->input_assembly();
cmds_.emplace_back([=]() {
glDrawArrays(to_GLPrimitiveMode(input_assembly.topology), first, count);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::draw_indexed(uint32_t count, uint32_t first)
{
auto input_assembly = pipeline_->input_assembly();
cmds_.emplace_back([=]() {
auto offset = index_stream_.offset + first * byte_size(index_stream_.index_type);
glDrawElements(to_GLPrimitiveMode(input_assembly.topology),
count, to_GLIndexType(index_type_), reinterpret_cast<void*>(offset));
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index)
{
Ogl_vertex_stream vertex_stream {static_cast<Ogl_buffer*>(buffer), offset};
if (vertex_stream == vertex_streams_[index])
return;
vertex_streams_[index] = vertex_stream;
if (!pipeline_)
return;
auto vertex_streams = vertex_streams_;
auto vertex_input = pipeline_->vertex_input();
cmds_.emplace_back([=]() {
set_up_vertex_input_(vertex_streams, vertex_input);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type)
{
Ogl_index_stream index_stream {static_cast<Ogl_buffer*>(buffer), offset, index_type};
if (index_stream == index_stream_)
return;
index_stream_ = index_stream;
cmds_.emplace_back([=]() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_stream.buffer->buffer());
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index)
{
auto buffer_impl = static_cast<Ogl_buffer*>(buffer);
auto arg_buffer = arg_table_.arg_buffer(index);
// skip if a shader buffer and offset are same.
if (buffer_impl == arg_buffer.buffer && offset == arg_buffer.offset)
return;
cmds_.emplace_back([=] {
glBindBuffer(GL_UNIFORM_BUFFER, buffer_impl->buffer());
glBindBufferRange(GL_UNIFORM_BUFFER, index, buffer_impl->buffer(), offset, buffer_impl->size() - offset);
});
// update an arg tables.
arg_table_.arg_buffer({buffer_impl, offset}, index);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::shader_texture(Image* image, Sampler* sampler, uint32_t index)
{
auto image_impl = static_cast<Ogl_image*>(image);
auto sampler_impl = static_cast<Ogl_sampler*>(sampler);
auto arg_texture = arg_table_.arg_texture(index);
// skip if a shader image and shader sampler are same.
if (image_impl == arg_texture.image && sampler_impl == arg_texture.sampler)
return;
cmds_.emplace_back([=]() {
glActiveTexture(GL_TEXTURE0 + index);
glBindTexture(to_GLTextureTarget(image_impl->type()), image_impl->texture());
glBindSampler(index, sampler_impl->sampler());
});
// update an arg tables.
arg_table_.arg_texture({image_impl, sampler_impl}, index);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::pipeline(Pipeline* pipeline)
{
auto pipeline_impl = static_cast<Ogl_pipeline*>(pipeline);
if (pipeline_impl == pipeline_)
return;
pipeline_ = pipeline_impl;
auto vertex_streams = vertex_streams_;
cmds_.emplace_back([=]() {
glUseProgram(pipeline_impl->program());
set_up_vertex_input_(vertex_streams, pipeline_impl->vertex_input());
set_up_rasterization_(pipeline_impl->rasterization());
set_up_depth_stencil_(pipeline_impl->depth_stencil());
set_up_color_blend_(pipeline_impl->color_blend());
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::viewport(const Viewport& viewport)
{
if (viewport_ == viewport)
return;
cmds_.emplace_back([=]() {
glViewport(viewport.x, viewport.y, viewport.w, viewport.h);
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::scissor(const Scissor& scissor)
{
if (scissor_ == scissor)
return;
cmds_.emplace_back([=]() {
glScissor(scissor.x, scissor.y, scissor.w, scissor.h);
});
}
//----------------------------------------------------------------------------------------------------------------------
Cmd_buffer* Ogl_render_encoder::cmd_buffer() const
{
return cmd_buffer_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::init_framebuffer_(const Render_encoder_desc& desc)
{
framebuffer_ = device_->framebuffer(to_Ogl_framebuffer_desc(desc));
cmds_.emplace_back([=]() {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_->framebuffer());
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::begin_render_pass_(const Render_encoder_desc& desc)
{
cmds_.emplace_back([=]() {
vector<GLenum> draw_buffers;
for (GLuint i = 0; i != 4; ++i) {
auto image = framebuffer_->color_image(i);
if (image) {
if (Image_type::swap_chain == image->type())
draw_buffers.push_back(GL_BACK);
else
draw_buffers.push_back(GL_COLOR_ATTACHMENT0 + i);
}
}
glDrawBuffers(static_cast<GLsizei>(draw_buffers.size()), &draw_buffers[0]);
for (GLuint i = 0; i != 4; ++i) {
if (!framebuffer_->color_image(i))
continue;
auto& color = desc.colors[i];
array<float, 4> clear_color { 0.0f, 0.0f, 0.0f, 0.0f };
if (Load_op::clear == color.load_op) {
clear_color[0] = color.clear_value.r;
clear_color[1] = color.clear_value.g;
clear_color[2] = color.clear_value.b;
clear_color[3] = color.clear_value.a;
}
if (Load_op::dont_care != color.load_op)
glClearBufferfv(GL_COLOR, i, &clear_color[0]);
if (Store_op::dont_care == desc.colors[i].store_op)
discards_.push_back(GL_COLOR_ATTACHMENT0 + i);
}
if (framebuffer_->depth_stencil()) {
auto& depth_stencil = desc.depth_stencil;
GLfloat d = 1.0f;
GLint s = 0;
if (Load_op::clear == depth_stencil.load_op) {
d = depth_stencil.clear_value.d;
s = depth_stencil.clear_value.s;
}
if (Load_op::dont_care != depth_stencil.load_op)
glClearBufferfi(GL_DEPTH_STENCIL, 0, d, s);
if (Store_op::dont_care == depth_stencil.store_op)
discards_.push_back(GL_DEPTH_STENCIL_ATTACHMENT);
}
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::end_render_pass_()
{
if (discards_.empty())
return;
cmds_.emplace_back([=]() {
glInvalidateFramebuffer(GL_FRAMEBUFFER, static_cast<GLsizei>(discards_.size()), &discards_[0]);
discards_.clear();
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::set_up_vertex_input_(const std::array<Ogl_vertex_stream, 2>& vertex_streams,
const Vertex_input& vertex_input)
{
for (auto i = 0; i != 2; ++i) {
auto& vertex_stream = vertex_streams[i];
if (!vertex_stream.buffer)
continue;
auto& binding = vertex_input.bindings[i];
glBindBuffer(GL_ARRAY_BUFFER, vertex_stream.buffer->buffer());
for (GLuint j = 0; j != 16; ++j) {
auto& attribute = vertex_input.attributes[j];
if (i != attribute.binding)
continue;
if (Format::invalid == attribute.format) {
glDisableVertexAttribArray(j);
}
else {
glEnableVertexAttribArray(j);
glVertexAttribPointer(j,
component_count(attribute.format),
to_GLDataType(attribute.format),
GL_FALSE,
binding.stride,
reinterpret_cast<void*>(vertex_stream.offset + attribute.offset));
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::set_up_rasterization_(const Rasterization& rasterization)
{
if (Cull_mode::none == rasterization.cull_mode) {
glDisable(GL_CULL_FACE);
}
else {
glEnable(GL_CULL_FACE);
glCullFace(to_GLCullMode(rasterization.cull_mode));
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::set_up_depth_stencil_(const Depth_stencil& depth_stencil)
{
if (depth_stencil.depth_test) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(to_GLCompareFunc(depth_stencil.depth_compare_op));
}
else {
glDisable(GL_DEPTH_TEST);
}
glDepthMask(depth_stencil.write_mask);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_render_encoder::set_up_color_blend_(const Color_blend& color_blend)
{
for (GLuint i = 0; i != 4; ++ i) {
auto& attachment = color_blend.attachments[i];
if (attachment.blend) {
glEnablei(GL_BLEND, i);
glBlendFuncSeparatei(i,
to_GLBlendFactor(attachment.src_rgb_blend_factor),
to_GLBlendFactor(attachment.dst_rgb_blend_factor),
to_GLBlendFactor(attachment.src_a_blend_factor),
to_GLBlendFactor(attachment.dst_a_blend_factor));
glBlendEquationSeparatei(i,
to_GLBlendFunc(attachment.rgb_blend_op),
to_GLBlendFunc(attachment.a_blend_op));
}
else {
glDisablei(GL_BLEND, i);
}
glColorMaski(i,
attachment.write_mask & 0x8,
attachment.write_mask & 0x4,
attachment.write_mask & 0x2,
attachment.write_mask & 0x1);
}
glBlendColor(color_blend.constant[0], color_blend.constant[1], color_blend.constant[2], color_blend.constant[3]);
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_blit_encoder::Ogl_blit_encoder(const Blit_encoder_desc& desc, Ogl_cmd_buffer* cmd_buffer) :
Blit_encoder {},
cmd_buffer_ {cmd_buffer}
{
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_blit_encoder::copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region)
{
auto src_buffer_impl = static_cast<Ogl_buffer*>(src_buffer);
auto dst_buffer_impl = static_cast<Ogl_buffer*>(dst_buffer);
cmds_.emplace_back([=]() {
auto contents = static_cast<uint8_t*>(src_buffer_impl->map());
glBindBuffer(GL_COPY_WRITE_BUFFER, dst_buffer_impl->buffer());
glBufferSubData(GL_COPY_WRITE_BUFFER, region.dst_offset, region.size, contents + region.src_offset);
src_buffer_impl->unmap();
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_blit_encoder::copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region)
{
auto src_buffer_impl = static_cast<Ogl_buffer*>(src_buffer);
auto dst_image_impl = static_cast<Ogl_image*>(dst_image);
cmds_.emplace_back([=]() {
auto contents = src_buffer_impl->map();
glBindTexture(GL_TEXTURE_2D, dst_image_impl->texture());
glTexSubImage2D(GL_TEXTURE_2D,
region.image_subresource.mip_level,
region.image_offset.x,
region.image_offset.y,
region.image_extent.w,
region.image_extent.h,
to_GLFormat(dst_image_impl->format()),
to_GLDataType(dst_image_impl->format()),
contents);
src_buffer_impl->unmap();
});
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_blit_encoder::copy(Image* src_buffer, Buffer* dst_image, const Buffer_image_copy_region& region)
{
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_blit_encoder::end()
{
for_each(cmds_, execute);
}
//----------------------------------------------------------------------------------------------------------------------
Cmd_buffer* Ogl_blit_encoder::cmd_buffer() const
{
return cmd_buffer_;
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_cmd_buffer::Ogl_cmd_buffer(Ogl_device* device) :
Cmd_buffer {},
device_ {device}
{
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_cmd_buffer::~Ogl_cmd_buffer()
{
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Render_encoder> Ogl_cmd_buffer::create(const Render_encoder_desc& desc)
{
return make_unique<Ogl_render_encoder>(desc, device_, this);
}
//----------------------------------------------------------------------------------------------------------------------
std::unique_ptr<Blit_encoder> Ogl_cmd_buffer::create(const Blit_encoder_desc& desc)
{
return make_unique<Ogl_blit_encoder>(desc, this);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_cmd_buffer::end()
{
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_cmd_buffer::reset()
{
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_cmd_buffer::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_IMAGE_GUARD
#define GFX_IMAGE_GUARD
#include <platform/Extent.h>
#include "enums.h"
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
//----------------------------------------------------------------------------------------------------------------------
struct Image_desc final {
Image_type type {Image_type::two_dim};
Format format {Format::invalid};
Extent extent {0, 0, 1};
uint8_t mip_levels {1};
uint8_t array_layers {1};
uint8_t samples {1};
};
//----------------------------------------------------------------------------------------------------------------------
class Image {
public:
explicit Image(const Image_desc& desc) noexcept :
type_ {desc.type},
format_ {desc.format},
extent_ {desc.extent},
mip_levels_ {desc.mip_levels},
array_layers_ {desc.array_layers},
samples_ {desc.samples}
{}
virtual ~Image() = default;
virtual Device* device() const = 0;
inline Image_type type() const noexcept
{ return type_; }
inline virtual Format format() const noexcept
{ return format_; }
inline Extent extent() const noexcept
{ return extent_; }
inline uint8_t mip_levels() const noexcept
{ return mip_levels_; }
inline uint8_t array_layers() const noexcept
{ return array_layers_; }
inline uint8_t samples() const noexcept
{ return samples_; }
protected:
Image_type type_;
Format format_;
Extent extent_;
uint8_t mip_levels_;
uint8_t array_layers_;
uint8_t samples_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_IMAGE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_CMD_BUFFER_GUARD
#define GFX_CMD_BUFFER_GUARD
#include <cstdint>
#include <array>
#include <bitset>
#include <platform/Extent.h>
#include "limitations.h"
#include "enums.h"
#include "types.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Device;
class Buffer;
class Image;
class Sampler;
class Pipeline;
class Cmd_buffer;
//----------------------------------------------------------------------------------------------------------------------
struct Attachment final {
Image* image {nullptr};
Load_op load_op {Load_op::dont_care};
Store_op store_op {Store_op::store};
Clear_value clear_value;
};
//----------------------------------------------------------------------------------------------------------------------
struct Render_encoder_desc final {
std::array<Attachment, max_color_attachments> colors;
Attachment depth_stencil;
};
//----------------------------------------------------------------------------------------------------------------------
class Render_encoder {
public:
virtual ~Render_encoder() = default;
virtual void end() = 0;
virtual void draw(uint32_t count, uint32_t first = 0) = 0;
virtual void draw_indexed(uint32_t count, uint32_t first = 0) = 0;
virtual void vertex_buffer(Buffer* buffer, uint64_t offset, uint32_t index) = 0;
virtual void index_buffer(Buffer* buffer, uint64_t offset, Index_type index_type) = 0;
virtual void shader_buffer(Buffer* buffer, uint32_t offset, uint32_t index) = 0;
virtual void shader_texture(Image* image, Sampler* sampler, uint32_t index) = 0;
virtual void pipeline(Pipeline* pipeline) = 0;
virtual void viewport(const Viewport& viewport) = 0;
virtual void scissor(const Scissor& scissor) = 0;
virtual Cmd_buffer* cmd_buffer() const = 0;
};
//----------------------------------------------------------------------------------------------------------------------
struct Image_subresource final {
uint32_t mip_level {0};
uint32_t array_layer {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Buffer_copy_region final {
uint64_t size {0};
uint64_t src_offset {0};
uint64_t dst_offset {0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Buffer_image_copy_region final {
uint32_t buffer_row_size {0};
uint32_t buffer_image_height {0};
uint32_t buffer_offset {0};
Image_subresource image_subresource;
Platform_lib::Extent image_extent {0, 0, 1};
Offset image_offset {0, 0, 0};
};
//----------------------------------------------------------------------------------------------------------------------
struct Blit_encoder_desc final {
};
//----------------------------------------------------------------------------------------------------------------------
class Blit_encoder {
public:
virtual ~Blit_encoder() = default;
virtual void copy(Buffer* src_buffer, Buffer* dst_buffer, const Buffer_copy_region& region) = 0;
virtual void copy(Buffer* src_buffer, Image* dst_image, const Buffer_image_copy_region& region) = 0;
virtual void copy(Image* src_image, Buffer* dst_buffer, const Buffer_image_copy_region& region) = 0;
virtual void end() = 0;
virtual Cmd_buffer* cmd_buffer() const = 0;
};
//----------------------------------------------------------------------------------------------------------------------
struct Cmd_buffer_desc final {
};
//----------------------------------------------------------------------------------------------------------------------
class Cmd_buffer {
public:
virtual ~Cmd_buffer() = default;
virtual std::unique_ptr<Render_encoder> create(const Render_encoder_desc& desc) = 0;
virtual std::unique_ptr<Blit_encoder> create(const Blit_encoder_desc& desc) = 0;
virtual void end() = 0;
virtual void reset() = 0;
virtual Device* device() const = 0;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_CMD_BUFFER_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_PIPELINE_GUARD
#define GFX_OGL_PIPELINE_GUARD
#include <GLES3/gl3.h>
#include "Pipeline.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_pipeline final : public Pipeline {
public:
Ogl_pipeline(const Pipeline_desc& desc, Ogl_device* device);
~Ogl_pipeline() override;
Device* device() const override;
inline auto program() const noexcept
{ return program_; }
private:
void init_program_(Shader* vertex_shader, Shader* fragment_shader);
void fini_program_();
private:
Ogl_device* device_;
GLuint program_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_PIPELINE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "Ogl_fence.h"
#include "Ogl_device.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_fence::Ogl_fence(const Fence_desc& desc, Ogl_device* device) :
Fence {},
device_ {device}
{
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_fence::wait_signal()
{
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_fence::reset()
{
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_fence::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
bool Ogl_fence::signaled() const
{
return true;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_SWAP_CHAIN_GUARD
#define GFX_VLK_SWAP_CHAIN_GUARD
#include <memory>
#include <vector>
#include <vulkan/vulkan.h>
#include "gfx/Swap_chain.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_image;
class Vlk_cmd_buffer;
class Vlk_fence;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_swap_chain final : public Swap_chain {
public:
Vlk_swap_chain(const Swap_chain_desc& desc, Vlk_device* device);
~Vlk_swap_chain() override;
Image* acquire() override;
void present() override;
Device* device() const override;
inline auto& swapchain() const noexcept
{ return swapchain_; }
inline auto& image_index() const noexcept
{ return image_index_; }
private:
void init_surface_(void* window);
void init_swapchain_();
void init_images_();
void init_acquire_fence_();
void init_cmd_buffers_();
void init_submit_fences_();
void init_submit_semaphores_();
void fini_surface_();
void fini_swapchain_();
void fini_submit_semaphores_();
inline auto cur_image_() const noexcept
{ return images_[image_index_].get(); }
inline auto cur_cmd_buffer_() const noexcept
{ return cmd_buffers_[frame_index_].get(); }
inline auto cur_submit_fence_() const noexcept
{ return submit_fences_[frame_index_].get(); }
inline auto& cur_submit_semaphore_() const noexcept
{ return submit_semaphores_[frame_index_]; }
private:
Vlk_device* device_;
VkSurfaceKHR surface_;
VkSwapchainKHR swapchain_;
std::vector<std::unique_ptr<Vlk_image>> images_;
uint32_t image_index_;
std::unique_ptr<Vlk_fence> acquire_fence_;
std::vector<std::unique_ptr<Vlk_cmd_buffer>> cmd_buffers_;
std::vector<std::unique_ptr<Vlk_fence>> submit_fences_;
std::vector<VkSemaphore> submit_semaphores_;
uint64_t frame_index_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_SWAP_CHAIN_GUARD
<file_sep>cmake_minimum_required(VERSION 3.15.0 FATAL_ERROR)
project(gfx VERSION 0.1.0 LANGUAGES CXX)
add_library(gfx
STATIC
include/gfx/limitations.h
include/gfx/enums.h
include/gfx/types.h
include/gfx/Device.h
include/gfx/Buffer.h
include/gfx/Image.h
include/gfx/Sampler.h
include/gfx/Shader.h
include/gfx/Pipeline.h
include/gfx/Swap_chain.h
include/gfx/Cmd_buffer.h
include/gfx/Fence.h
src/std_lib.h
src/Lru_cache.h
src/Device.cpp
src/Pipeline.cpp
)
target_include_directories(gfx
PUBLIC
include
PRIVATE
include/gfx
src
)
target_link_libraries(gfx
PUBLIC
prebuilt
platform
sc
)
set_target_properties(gfx
PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS ON
)
if(CMAKE_SYSTEM_NAME MATCHES Darwin OR CMAKE_SYSTEM_NAME MATCHES iOS)
target_sources(gfx
PRIVATE
src/mtl/mtl_lib.h
src/mtl/Mtl_device.h
src/mtl/Mtl_device.mm
src/mtl/Mtl_buffer.h
src/mtl/Mtl_buffer.mm
src/mtl/Mtl_image.h
src/mtl/Mtl_image.mm
src/mtl/Mtl_sampler.h
src/mtl/Mtl_sampler.mm
src/mtl/Mtl_shader.h
src/mtl/Mtl_shader.mm
src/mtl/Mtl_pipeline.h
src/mtl/Mtl_pipeline.mm
src/mtl/Mtl_swap_chain.h
src/mtl/Mtl_swap_chain.mm
src/mtl/Mtl_cmd_buffer.h
src/mtl/Mtl_cmd_buffer.mm
src/mtl/Mtl_fence.h
src/mtl/Mtl_fence.mm
)
target_include_directories(gfx
PRIVATE
src/mtl
)
target_compile_options(gfx
PUBLIC
-x objective-c++
)
target_link_libraries(gfx
PUBLIC
"-framework Metal"
"-framework QuartzCore"
)
set_target_properties(gfx
PROPERTIES
XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES
)
endif()
if(CMAKE_SYSTEM_NAME MATCHES Android OR CMAKE_SYSTEM_NAME MATCHES Windows)
target_sources(gfx
PRIVATE
src/vlk/vlk_lib.h
src/vlk/Vlk_device.h
src/vlk/Vlk_device.cpp
src/vlk/Vlk_buffer.h
src/vlk/Vlk_buffer.cpp
src/vlk/Vlk_image.h
src/vlk/Vlk_image.cpp
src/vlk/Vlk_sampler.h
src/vlk/Vlk_sampler.cpp
src/vlk/Vlk_shader.h
src/vlk/Vlk_shader.cpp
src/vlk/Vlk_pipeline.h
src/vlk/Vlk_pipeline.cpp
src/vlk/Vlk_swap_chain.h
src/vlk/Vlk_swap_chain.cpp
src/vlk/Vlk_cmd_buffer.h
src/vlk/Vlk_cmd_buffer.cpp
src/vlk/Vlk_fence.h
src/vlk/Vlk_fence.cpp
src/vlk/Vlk_render_pass.h
src/vlk/Vlk_render_pass.cpp
src/vlk/Vlk_framebuffer.h
src/vlk/Vlk_framebuffer.cpp
src/vlk/Vlk_set_layout.h
src/vlk/Vlk_set_layout.cpp
)
target_include_directories(gfx
PRIVATE
src/vlk
)
endif()
if(CMAKE_SYSTEM_NAME MATCHES Android)
target_sources(gfx
PRIVATE
src/ogl/ogl_lib.h
src/ogl/Ogl_device.h
src/ogl/Ogl_device.cpp
src/ogl/Ogl_buffer.h
src/ogl/Ogl_buffer.cpp
src/ogl/Ogl_image.h
src/ogl/Ogl_image.cpp
src/ogl/Ogl_sampler.h
src/ogl/Ogl_sampler.cpp
src/ogl/Ogl_shader.h
src/ogl/Ogl_shader.cpp
src/ogl/Ogl_pipeline.h
src/ogl/Ogl_pipeline.cpp
src/ogl/Ogl_swap_chain.h
src/ogl/Ogl_swap_chain.cpp
src/ogl/Ogl_cmd_buffer.h
src/ogl/Ogl_cmd_buffer.cpp
src/ogl/Ogl_fence.h
src/ogl/Ogl_fence.cpp
src/ogl/Ogl_framebuffer.h
src/ogl/Ogl_framebuffer.cpp
)
target_include_directories(gfx
PRIVATE
src/ogl
)
target_link_libraries(gfx
PUBLIC
EGL
GLESv3
)
endif()
if(CMAKE_SYSTEM_NAME MATCHES Darwin OR CMAKE_SYSTEM_NAME MATCHES iOS)
add_executable(gfx_demo MACOSX_BUNDLE)
elseif(CMAKE_SYSTEM_NAME MATCHES Android)
add_library(gfx_demo SHARED)
# Export ANativeActivity_onCreate(),
# Refer to: https://github.com/android-ndk/ndk/issues/381.
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -u ANativeActivity_onCreate")
elseif(CMAKE_SYSTEM_NAME MATCHES Windows)
add_executable(gfx_demo WIN32)
endif()
target_sources(gfx_demo
PRIVATE
demo/main.cpp
demo/stb_lib.h
demo/util.h
demo/util.cpp
demo/Gfx_demo.h
demo/Gfx_demo.cpp
)
target_link_libraries(gfx_demo
PUBLIC
gfx
)
set_target_properties(gfx_demo
PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS ON
)
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_buffer.h"
#include "Vlk_device.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_buffer::Vlk_buffer(const Buffer_desc& desc, Vlk_device* device) :
Buffer {desc},
device_ {device},
buffer_ {VK_NULL_HANDLE},
alloc_ {VK_NULL_HANDLE},
contents_ {nullptr}
{
init_buffer_and_alloc_(desc.data);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_buffer::~Vlk_buffer()
{
fini_buffer_and_alloc_();
}
//----------------------------------------------------------------------------------------------------------------------
void* Vlk_buffer::map()
{
return contents_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_buffer::unmap()
{
vmaFlushAllocation(device_->allocator(), alloc_, 0, VK_WHOLE_SIZE);
}
//----------------------------------------------------------------------------------------------------------------------
Device* Vlk_buffer::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_buffer::init_buffer_and_alloc_(const void* data)
{
// configure the required buffer usage.
constexpr auto usage {
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT
};
// configure a buffer create info.
VkBufferCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
create_info.size = size_;
create_info.usage = usage;
// configure an allocation create info.
VmaAllocationCreateInfo alloc_create_info {};
alloc_create_info.usage = to_VmaMemoryUsage(heap_type_);
if (Heap_type::local != heap_type_)
alloc_create_info.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
// try to create a buffer and an allocation.
if (vmaCreateBuffer(device_->allocator(), &create_info, &alloc_create_info, &buffer_, &alloc_, nullptr))
throw runtime_error("fail to create buffer");
if (Heap_type::local != heap_type_)
vmaMapMemory(device_->allocator(), alloc_, &contents_);
if (data) {
memcpy(contents_, data, size_);
vmaFlushAllocation(device_->allocator(), alloc_, 0, VK_WHOLE_SIZE);
}
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_buffer::fini_buffer_and_alloc_()
{
if (Heap_type::local != heap_type_)
vmaUnmapMemory(device_->allocator(), alloc_);
vmaDestroyBuffer(device_->allocator(), buffer_, alloc_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_PIPELINE_GUARD
#define GFX_VLK_PIPELINE_GUARD
#include <memory>
#include <array>
#include <unordered_map>
#include <vulkan/vulkan.h>
#include "Pipeline.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
class Vlk_set_layout;
//----------------------------------------------------------------------------------------------------------------------
using Vlk_set_layout_array = std::array<std::unique_ptr<Vlk_set_layout>, 2>;
//----------------------------------------------------------------------------------------------------------------------
class Vlk_pipeline final : public Pipeline {
public:
Vlk_pipeline(const Pipeline_desc& desc, Vlk_device* device);
~Vlk_pipeline() override;
Device* device() const override;
inline auto set_layout(uint32_t index) const noexcept
{ return set_layouts_[index].get(); }
inline auto& pipeline_layout() const noexcept
{ return pipeline_layout_; }
inline auto& pipeline() const noexcept
{ return pipeline_; }
private:
void init_set_layouts_(Shader* vertex_shader, Shader* fragment_shader);
void init_pipeline_layout_();
void init_pipeline_(Shader* vertex_shader, Shader* fragment_shader);
void fini_pipeline_layout_();
void fini_pipeline_();
private:
Vlk_device* device_;
Vlk_set_layout_array set_layouts_;
VkPipelineLayout pipeline_layout_;
VkPipeline pipeline_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_PIPELINE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_LIMITATIONS_GUARD
#define GFX_LIMITATIONS_GUARD
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
constexpr auto max_vertex_input_attributes {16u};
constexpr auto max_vertex_input_bindings {8u};
constexpr auto max_shader_buffers {16u};
constexpr auto max_shader_textures {16u};
constexpr auto max_color_attachments {4u};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_LIMITATIONS_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_VLK_RENDER_PASS_GUARD
#define GFX_VLK_RENDER_PASS_GUARD
#include <array>
#include <vulkan/vulkan.h>
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Vlk_device;
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_attachment {
Format format { Format::invalid };
uint8_t samples { 0 };
Load_op load_op { Load_op::dont_care };
Store_op store_op { Store_op::dont_care };
};
//----------------------------------------------------------------------------------------------------------------------
struct Vlk_render_pass_desc {
std::array<Vlk_attachment, 4> colors;
Vlk_attachment depth_stencil;
};
//----------------------------------------------------------------------------------------------------------------------
class Vlk_render_pass final {
public:
Vlk_render_pass(const Vlk_render_pass_desc& desc, Vlk_device* device);
~Vlk_render_pass();
inline auto& render_pass() const noexcept
{ return render_pass_; }
private:
void init_render_pass_(const Vlk_render_pass_desc& desc);
void fini_render_pass_();
private:
Vlk_device* device_;
VkRenderPass render_pass_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_VLK_RENDER_PASS_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_MTL_SWAP_CHAIN_GUARD
#define GFX_MTL_SWAP_CHAIN_GUARD
#include <memory>
#include <vector>
#include <Metal/Metal.h>
#include <QuartzCore/CAMetalLayer.h>
#include "Swap_chain.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Mtl_device;
class Mtl_image;
//----------------------------------------------------------------------------------------------------------------------
class Mtl_swap_chain final : public Swap_chain {
public:
Mtl_swap_chain(const Swap_chain_desc& desc, Mtl_device* device);
Image* acquire() override;
void present() override;
Device* device() const override;
private:
void init_layer_();
void init_images();
void connect_to_window_(void* window);
private:
Mtl_device* device_;
CAMetalLayer* layer_;
std::vector<std::unique_ptr<Mtl_image>> images_;
uint32_t image_index_;
id<CAMetalDrawable> drawable_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_MTL_SWAP_CHAIN_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "Ogl_swap_chain.h"
#include "Ogl_device.h"
#include "Ogl_image.h"
using namespace std;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_swap_chain::Ogl_swap_chain(const Swap_chain_desc& desc, Ogl_device* device) :
Swap_chain {desc},
device_ {device},
surface_ {EGL_NO_SURFACE},
image_index_ {0},
images_ {desc.image_count}
{
init_surface_(desc.window);
init_images_();
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_swap_chain::~Ogl_swap_chain()
{
fini_surface_();
}
//----------------------------------------------------------------------------------------------------------------------
Image* Ogl_swap_chain::acquire()
{
return images_[image_index_].get();
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_swap_chain::present()
{
eglSwapBuffers(device_->display(), surface_);
image_index_ = ++frame_count_ % images_.size();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_swap_chain::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_swap_chain::init_surface_(void* window)
{
constexpr EGLint attributes[] {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint config_count;
eglChooseConfig(device_->display(), attributes, nullptr, 0, &config_count);
EGLConfig config;
eglChooseConfig(device_->display(), attributes, &config, 1, &config_count);
surface_ = eglCreateWindowSurface(device_->display(), config,
static_cast<EGLNativeWindowType>(window), nullptr);
if (!surface_)
throw runtime_error("fail to create a swap chain");
eglMakeCurrent(device_->display(), surface_, surface_, device_->context());
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_swap_chain::init_images_()
{
Image_desc desc;
desc.type = Image_type::swap_chain;
desc.format = image_format_;
desc.extent = image_extent_;
for (auto& image : images_) {
try {
image = make_unique<Ogl_image>(desc, device_);
}
catch (exception& e) {
throw runtime_error("fail to create a swap chain");
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_swap_chain::fini_surface_()
{
eglMakeCurrent(device_->display(), EGL_NO_SURFACE, EGL_NO_SURFACE, device_->context());
eglDestroySurface(device_->display(), surface_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_DEVICE_GUARD
#define GFX_OGL_DEVICE_GUARD
#include <EGL/egl.h>
#include "Device.h"
#include "Lru_cache.h"
#include "Ogl_framebuffer.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device : public Device {
public:
Ogl_device();
~Ogl_device() override;
std::unique_ptr<Buffer> create(const Buffer_desc& desc) override;
std::unique_ptr<Image> create(const Image_desc& desc) override;
std::unique_ptr<Sampler> create(const Sampler_desc& desc) override;
std::unique_ptr<Shader> create(const Shader_desc& desc) override;
std::unique_ptr<Pipeline> create(const Pipeline_desc& desc) override;
std::unique_ptr<Swap_chain> create(const Swap_chain_desc& desc) override;
std::unique_ptr<Cmd_buffer> create(const Cmd_buffer_desc& desc) override;
std::unique_ptr<Fence> create(const Fence_desc& desc) override;
void submit(Cmd_buffer* cmd_buffer, Fence* fence = nullptr) override;
void wait_idle() override;
inline auto display() const noexcept
{ return display_; }
inline auto context() const noexcept
{ return context_; }
Ogl_framebuffer* framebuffer(const Ogl_framebuffer_desc& desc);
private:
void init_display_();
void init_context_();
void init_context_symbols_();
void init_caps_();
void fini_context_();
private:
EGLDisplay display_;
EGLContext context_;
Lru_cache<Ogl_framebuffer> framebuffer_pool_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_DEVICE_GUARD
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include "std_lib.h"
#include "vlk_lib.h"
#include "Vlk_set_layout.h"
#include "Vlk_device.h"
using namespace std;
using namespace Gfx_lib;
namespace {
//----------------------------------------------------------------------------------------------------------------------
constexpr auto max_set_count = 1024;
//----------------------------------------------------------------------------------------------------------------------
inline vector<VkDescriptorPoolSize> to_pool_sizes(const Vlk_set_layout_desc& desc)
{
unordered_map<VkDescriptorType, uint32_t> counts;
for (auto& binding : desc.bindings)
++counts[binding.descriptorType];
vector<VkDescriptorPoolSize> pool_sizes;
for (auto& [type, count] : counts)
pool_sizes.push_back({type, count * max_set_count});
return pool_sizes;
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Vlk_set_layout::Vlk_set_layout(const Vlk_set_layout_desc& desc, Vlk_device* device) :
device_ {device},
desc_set_layout_ {VK_NULL_HANDLE},
desc_pool_ {VK_NULL_HANDLE},
desc_sets_ {max_set_count},
desc_set_index_ {0}
{
init_desc_set_layout_(desc);
init_desc_pool_(desc);
}
//----------------------------------------------------------------------------------------------------------------------
Vlk_set_layout::~Vlk_set_layout()
{
fini_desc_set_layout_();
fini_desc_pool_();
}
//----------------------------------------------------------------------------------------------------------------------
VkDescriptorSet Vlk_set_layout::desc_set()
{
auto& desc_set = desc_sets_[desc_set_index_];
if (!desc_set) {
VkDescriptorSetAllocateInfo alloc_info {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = desc_pool_;
alloc_info.descriptorSetCount = 1;
alloc_info.pSetLayouts = &desc_set_layout_;
vkAllocateDescriptorSets(device_->device(), &alloc_info, &desc_set);
}
desc_set_index_ = ++desc_set_index_ % max_set_count;
return desc_set;
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_set_layout::init_desc_set_layout_(const Vlk_set_layout_desc& desc)
{
VkDescriptorSetLayoutCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
create_info.bindingCount = static_cast<uint32_t>(desc.bindings.size());
create_info.pBindings = &desc.bindings[0];
if (vkCreateDescriptorSetLayout(device_->device(), &create_info, nullptr, &desc_set_layout_))
throw runtime_error("");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_set_layout::init_desc_pool_(const Vlk_set_layout_desc& desc)
{
auto pool_sizes = to_pool_sizes(desc);
VkDescriptorPoolCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
create_info.maxSets = max_set_count;
create_info.poolSizeCount = static_cast<uint32_t>(pool_sizes.size());
create_info.pPoolSizes = &pool_sizes[0];
if (vkCreateDescriptorPool(device_->device(), &create_info, nullptr, &desc_pool_))
throw runtime_error("");
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_set_layout::fini_desc_set_layout_()
{
vkDestroyDescriptorSetLayout(device_->device(), desc_set_layout_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
void Vlk_set_layout::fini_desc_pool_()
{
vkDestroyDescriptorPool(device_->device(), desc_pool_, nullptr);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
<file_sep>//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#include <array>
#include <sc/Spirv_reflector.h>
#include <sc/Glsl_compiler.h>
#include "ogl_lib.h"
#include "Ogl_shader.h"
#include "Ogl_device.h"
using namespace std;
using namespace Sc_lib;
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
Ogl_shader::Ogl_shader(const Shader_desc& desc, Ogl_device* device) :
Shader {desc},
device_ {device},
signature_ {},
shader_ {0}
{
init_signature_(desc.src);
init_shader_(Glsl_compiler().compile(desc.src));
}
//----------------------------------------------------------------------------------------------------------------------
Ogl_shader::~Ogl_shader()
{
fini_shader_();
}
//----------------------------------------------------------------------------------------------------------------------
Device* Ogl_shader::device() const
{
return device_;
}
//----------------------------------------------------------------------------------------------------------------------
Sc_lib::Signature Ogl_shader::reflect() const noexcept
{
return signature_;
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_shader::init_signature_(const std::vector<uint32_t>& src)
{
signature_ = Spirv_reflector().reflect(src);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_shader::init_shader_(const std::string& src)
{
shader_ = glCreateShader(to_GLShaderType(type_));
auto contents = src.c_str();
auto length = static_cast<GLint>(src.size());
glShaderSource(shader_, 1, &contents, &length);
glCompileShader(shader_);
}
//----------------------------------------------------------------------------------------------------------------------
void Ogl_shader::fini_shader_()
{
glDeleteShader(shader_);
}
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
| e4f0fbff528af5a371ed753c8f7c87bd3ad98eaa | [
"C",
"CMake",
"C++",
"Gradle"
] | 80 | C++ | kiseop91/gfx | fd64673e14924f102d2a14eaa19dc7345b13310e | d04f0741715779ce797eefafbebbd937081f33a0 |
refs/heads/master | <file_sep>// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var LinkedinStrategy = require('passport-linkedin-oauth2').Strategy;
//npm install passport-linkedin-oauth2
// load up the user model
var User = require('../app/models/user');
var event = require('../app/models/event');
var Message = require('../app/models/message');
// load the auth variables
var configAuth = require('./auth'); // use this one for testing
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : '<PASSWORD>',
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, email, password, done) {
if (email)
email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching
// asynchronous
process.nextTick(function() {
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
// all is well, return user
else
console.log(user);
return done(null, user);
});
});
}));
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : '<PASSWORD>',
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, email, password, done) {
if (email)
email = email.toLowerCase(); // Use lower-case e-mails to avoid case-sensitive e-mail matching
// asynchronous
process.nextTick(function() {
// if the user is not already logged in:
if (!req.user) {
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// create the user
var newUser = new User();
newUser.local.email = email;
newUser.local.password = <PASSWORD>);
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
// if the user is logged in but has no local account...
} else if ( !req.user.local.email ) {
// ...presumably they're trying to connect a local account
// BUT let's check if the email used to connect a local account is being used by another user
User.findOne({ 'local.email' : email }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('loginMessage', 'That email is already taken.'));
// Using 'loginMessage instead of signupMessage because it's used by /connect/local'
} else {
var user = req.user;
user.local.email = email;
user.local.password = user.generateHash(password);
user.save(function (err) {
if (err)
return done(err);
return done(null,user);
});
}
});
} else {
// user is logged in and already has a local account. Ignore signup. (You should log out before trying to create a new account, user!)
return done(null, req.user);
}
});
}));
// =========================================================================
// Linkedin ================================================================
// =========================================================================
passport.use(new LinkedinStrategy({
clientID : configAuth.linkedinAuth.clientID,
clientSecret : configAuth.linkedinAuth.clientSecret,
callbackURL : configAuth.linkedinAuth.callbackURL,
scope: ['r_emailaddress', 'r_basicprofile'],
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, refreshToken, profile, done) {
console.log(profile);
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'linkedin.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.linkedin.token) {
user.linkedin.token = token;
user.linkedin.email = (profile.emails[0].value || '').toLowerCase();
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
newUser.linkedin.id = profile.id;
newUser.linkedin.token = token;
newUser.linkedin.email = (profile.emails[0].value || '').toLowerCase();
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.Linkedin.id = profile.id;
user.Linkedin.email = (profile.emails[0].value || '').toLowerCase();
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
});
}));
// =========================================================================
// FACEBOOK ================================================================
// =========================================================================
passport.use(new FacebookStrategy({
clientID : configAuth.facebookAuth.clientID,
clientSecret : configAuth.facebookAuth.clientSecret,
callbackURL : configAuth.facebookAuth.callbackURL,
profileFields : ['id','name', 'gender','about','email', 'displayName','profileUrl','photos'],
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, refreshToken, profile, done) {
console.log(profile);
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ '_id' : profile.id }, function(err, user) {
if (err)
return done(err);
console.log("asdf" + user);
if (user) {
console.log("asdff" + user);
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.facebook.token) {
user.facebook.token = token;
user._id = profile.id;
user.facebook.id = profile.id;
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.givenName = profile.name.givenName;
user.facebook.familyName = profile.name.familyName;
user.facebook.gender = profile.gender;
user.facebook.photo = profile.photos[0].value;
user.facebook.email = (profile.emails[0].value || '').toLowerCase();
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
console.log("asdfff" + user);
var newUser = new User();
var newEvent = new event();
var newMessage = new Message();
newUser._id = profile.id;
newUser.facebook.id = profile.id;
newUser.facebook.token = token;
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.facebook.givenName = profile.name.givenName;
newUser.facebook.familyName = profile.name.familyName;
newUser.facebook.gender = profile.gender;
newUser.facebook.photo = profile.photos[0].value;
newUser.facebook.email = (profile.emails[0].value || '').toLowerCase();
newUser.neiconn.language = null;
newUser.neiconn.birth.day = null;
newUser.neiconn.birth.month = null;
newUser.neiconn.birth.year = null;
newUser.neiconn.phone = null;
newUser.neiconn.location = null;
newUser.neiconn.about = null;
newUser.neiconn.school = null;
newUser.neiconn.work = null;
newUser.neiconn.reviews = [];
newUser.neiconn.rating = [ 4.5, 4.5, 4.5, 4.5];
newUser.neiconn.ratingtotal = 4.5;
newUser.neiconn.firstName = profile.name.givenName;
newUser.neiconn.lastName = profile.name.familyName;
newMessage.inbox = [];
newMessage.outbox = [];
newMessage._id = profile.id;
newMessage.save(function(err){
if(err) throw err;
console.log("Message box is assigned!");
});
// event as below:
/*
newEvent._id = "00000000001";
newEvent.user._id = profile.id;
newEvent.user.photo = "images/owner1.jpg";
newEvent.user.role = "host",
newEvent.user.name = profile.name.givenName + ' ' + profile.name.familyName;
newEvent.content.title = "Grab Point",
newEvent.content.category = "Eat & Drink",
newEvent.content.date = "2016 3 4",
newEvent.content.duration = 4;
newEvent.content.rule[0] = "Be Happy";
newEvent.content.rule[1] = "Apporiate Clothing";
newEvent.content.rule[2] = "Be gentle";
newEvent.content.location.address = "2000 wolfe road , sunnyVale, CA, 95035";
newEvent.content.location.lon = "-122.013425";
newEvent.content.location.lat = "37.383731";
newEvent.content.photo = "images/sea.jpg";
newEvent.rating = 4.7;
newEvent.category = "upcoming";
newEvent.save(function (err) {
// body...
if (err)
return done(err);
return done(null, newEvent);
});
*/
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
console.log("asdfffff" + user);
var user = req.user; // pull the user out of the session
user._id = profile.id;
user.facebook.id = profile.id;
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.givenName = profile.name.givenName;
user.facebook.familyName = profile.name.familyName;
user.facebook.gender = profile.gender;
user.facebook.photo = profile.photos[0].value;
user.facebook.email = (profile.emails[0].value || '').toLowerCase();
return done(null, user);
}
});
}));
// =========================================================================
// TWITTER =================================================================
// =========================================================================
passport.use(new TwitterStrategy({
consumerKey : configAuth.twitterAuth.consumerKey,
consumerSecret : configAuth.twitterAuth.consumerSecret,
callbackURL : configAuth.twitterAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, tokenSecret, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.twitter.token) {
user.twitter.token = token;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
newUser.twitter.id = profile.id;
newUser.twitter.token = token;
newUser.twitter.username = profile.username;
newUser.twitter.displayName = profile.displayName;
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.twitter.id = profile.id;
user.twitter.token = token;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
});
}));
// =========================================================================
// GOOGLE ==================================================================
// =========================================================================
passport.use(new GoogleStrategy({
clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.google.token) {
user.google.token = token;
user.google.name = profile.displayName;
user.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
return done(null, user);
} else {
var newUser = new User();
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.google.id = profile.id;
user.google.token = token;
user.google.name = profile.displayName;
user.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email
user.save(function(err) {
if (err)
return done(err);
return done(null, user);
});
}
});
}));
};
<file_sep>// load the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var groupSchema = mongoose.Schema({
_id : String, //event_id : one event should have one chatting group
event : {
event_title : String,
event_picture : String,
event_date : String,
event_time : String,
event_duation : Number,
event_amount : Number
}, // event details: this is for event details
member : [{
member_id : String,
member_photo : String
}], // the length of the memeber array is restricted by the event amout
// content should be localstorage, at this time it is for testing purpose
contentStoage : [{
member_id : String,
member_content : String
}]
});
// generating a hash
groupSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
groupSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Group', groupSchema);
<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var messageSchema = mongoose.Schema({
_id : String, //user_id
inbox : [{
sender_id : String,
sender_name : String,
content : String,
timestamp : { type :Date , default : Date.now }
}],
outbox :[{
reciever_id : String,
reciever_name : String,
content : String,
timestamp : { type :Date , default : Date.now }
}]
});
// generating a hash
messageSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
messageSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Message', messageSchema);
<file_sep>angular.module('guide',['ui.bootstrap'])
.controller('guideCtrl', function ($scope){
$scope.max = 5;
$scope.total = 4;
});<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var eventSchema = mongoose.Schema({
_id : String, // Time + IP + UserID
user : {
_id : String, // event host id and photo
photo : String,
role : String,
name : String,
email : String, //host or attend
reviews : Number,
rating : Number
},
content :{
time : Number,
title : String,
category : String,
language : String,
venue : String,
provision : String,
about : String,
date : String,
duration : Number, //number of hours
price : Number,
total_attendees : Number,
rule : [
String
],
location : {
address : String,
lon : String,
lat : String
},
photo : [String] //the photo limit on 9
},
category : String //status : Upcoming History
});
// generating a hash
eventSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
eventSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Event', eventSchema);
<file_sep>angular.module('orderview',['customFilters','ui.bootstrap'])
.controller('orderCtrl', function ($scope, $http){
$scope.hightlightnumber = null;
$scope.item = [];
$scope.preview = false;
$scope.dispu = false;
var data = [{"_id" : "trip001", "name" : "order001", "status" : 1}, {"_id" : "trip002", "name" : "order002", "status" : 1},
{"_id" : "trip003", "name" : "order003", "status" : 1}, {"_id" : "trip004", "name" : "order004", "status" : 1},
{"_id" : "trip005", "name" : "order005", "status" : 2}, {"_id" : "trip006", "name" : "order006", "status" : 1},
{"_id" : "trip007", "name" : "order007", "status" : 2}, {"_id" : "trip008", "name" : "order008", "status" : 1},
{"_id" : "trip009", "name" : "order009", "status" : 1}, {"_id" : "trip010", "name" : "order010", "status" : 3},
{"_id" : "trip011", "name" : "order011", "status" : 5}, {"_id" : "trip012", "name" : "order012", "status" : 1},
{"_id" : "trip013", "name" : "order013", "status" : 1}, {"_id" : "trip014", "name" : "order014", "status" : 4}]
$scope.select = function (num) {
$scope.item.length = 0;
for(var i = 0; i < data.length; i++){
if(num === 0){
$scope.before = false;
$scope.after = false;
$scope.all = true;
$scope.item.push(data[i]);
}else if(data[i].status === num){
$scope.item.push(data[i]);
if(data[i].status === 1){
$scope.before = true;
$scope.after = false;
$scope.all = false;
}else{
$scope.before = false;
$scope.after = true;
$scope.all = false; }
}
}
$scope.preview = false;
}
$scope.chooseTrip = function (id, name){
$scope.hightlightnumber = null;
$scope.name = name;
$scope.orderID = id;
$scope.payment = "FULL PAYMENT";
$scope.status = "Ready";
$scope.paid = "$3000.00";
$scope.preview = true;
$scope.hightlightnumber = id;
}
$scope.dispute = function (){
$scope.dispu = true;
$scope.preview = false;
}
$scope.back = function(){
$scope.dispu = false;
}
//$scope.switches = $scope.tripItem && $scope.reviewD;
});<file_sep>angular.module('tempage')
.factory('db', function ($http){
var item = {}; //The item will hold the value of the http.res
var result = {};
//Backend will recieve the all comments
item.getComments = function () {
$http.get('/getComments')
.then(function (data){
result = data;
})
.catch(function(data, status){
console.error('error', response.status, response.data)
})
.finally (function (){
console.log("finish the get from comments")
});
}
return item;
})<file_sep> var User = require('../app/models/user');
var Event = require('../app/models/event');
var Group = require('../app/models/egroup');
var Temp = require('../app/models/temp');
var Message = require('../app/models/message');
var Review = require('../app/models/reviews');
var Tripgroup = require('../app/models/tripgroup');
var Friendlist = require('../app/models/friendList');
var Trip = require('../app/models/trip');
var Uwoplace = require('../app/models/uwoplace');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport({
service : "Gmail",
auth : {
user: "<EMAIL>",
pass: "<PASSWORD>"
}
});
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads');
},
filename: function (req, file, callback) {
callback(null, Date.now()+file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
function showResult(result) {
document.getElementById('latitude').value = result.geometry.location.lat();
document.getElementById('longitude').value = result.geometry.location.lng();
}
function getLatitudeLongitude(callback, address) {
// If adress is not supplied, use default value 'Ferrol, Galicia, Spain'
address = address || 'Ferrol, Galicia, Spain';
// Initialize the Geocoder
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0]);
}
});
}
}
function getEvent(event, id){
for(var i = 0; i < event.length; i++){
if(event[i]._id == id){
return event[i];
}
}
return null;
}
function check_join(applicants, id){
for(var i = 0; i < applicants.length; i++){
if(applicants[i].applicant_id == id){
return true;
}
}
return false;
}
module.exports = function(app, passport) {
// normal routes ===============================================================
// show the home page (will also have our login links)
app.get('/', function(req, res) {
res.render('main.ejs');
});
app.get('/guide/:id', function (req, res){
Review.find({"reviews.content._id" : req.params.id},{},function (err, review){
console.log('asdfasdfas');
res.render('guide.ejs', {
reviews : review
});
});
});
app.get('/confirm', function(req, res) {
res.render('comfirm.ejs');
});
// PROFILE SECTION =========================
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user
});
});
// LOGOUT ==============================
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/applications',isLoggedIn ,function(req, res){
Temp.find({"host.id" : req.user._id},{},function(err, temp){
res.render("applications.ejs", {
user: req.user,
temps: temp
});
})
});
app.get('/reviews', function(req, res) {
res.render('reviewTemp.ejs');
});
app.get('/gps/:id', function(req, res) {
Trip.find({"tourist._id" : req.params.id},{}, function (err, trip){
console.log(trip);
res.render('gps.ejs', {
trips : trip
});
})
})
app.get('/uwogps/:id', function(req, res) {
Trip.find({"tourist._id" : req.params.id},{}, function (err, trip){
console.log(trip);
res.render('uwogps.ejs', {
trips : trip
});
})
})
app.get('/testTrip', function(req, res){
var Newtrip = new Trip();
Newtrip._id = "trip001";
Newtrip.name = "trip001";
Newtrip.local.push({"_id": "local001", "name" : "local001", "image" : "/images/iconmap.png", "position" : {"_id" : "place001", "name" : "place001", "lon" : "-118.352112" ,"lat": "34.133952"}});
Newtrip.local.push({"_id": "local002", "name" : "local002", "image" : "/images/iconmap.png", "position" : {"_id" : "place002", "name" : "place002", "lon" : "-118.497629" ,"lat": "34.009176"}});
Newtrip.local.push({"_id": "local003", "name" : "local003", "image" : "/images/iconmap.png", "position" : {"_id" : "place003", "name" : "place003", "lon" : "-118.144516" ,"lat": "34.147785"}});
Newtrip.local.push({"_id": "local004", "name" : "local004", "image" : "/images/iconmap.png", "position" : {"_id" : "place004", "name" : "place004", "lon" : "-117.935282" ,"lat": "33.615441"}});
Newtrip.local.push({"_id": "local005", "name" : "local005", "image" : "/images/iconmap.png", "position" : {"_id" : "place005", "name" : "place005", "lon" : "-117.732585" ,"lat": "33.989819"}});
Newtrip.official.push({"_id" : "official001", "name" : "official001", "image" : "/images/owner1.jpg", "lon" : "-118.408530", "lat" : "33.941589" });
Newtrip.tourist.push({"_id" : "tourist001", "name" : "tourist001" , "image" : "/images/owner3.jpg", "lon" : "-118.408530", "lat" : "33.941589"});
Newtrip.tourist.push({"_id" : "tourist002", "name" : "tourist002" , "image" : "/images/owner4.jpg", "lon" : "-118.408530", "lat" : "33.941589"});
Newtrip.tourist.push({"_id" : "tourist003", "name" : "tourist003" , "image" : "/images/owner5.jpg", "lon" : "-118.408530", "lat" : "33.941589"});
Newtrip.tourist.push({"_id" : "tourist004", "name" : "tourist004" , "image" : "/images/owner6.jpg", "lon" : "-118.408530", "lat" : "33.941589"});
Newtrip.save(function (err){
if(err) throw err;
console.log('GPS Group created!');
});
});
app.post('/result', function(req,res){
Event.find({},{},function (err, events){
console.log(events);
req.session.events = events;
res.render('search-result.ejs',{
event : events
});
})
});
app.post('/event', isLoggedIn_event,function(req,res){
console.log(req.body.id);
var id = req.body.id;
var events = getEvent(req.session.events, id);
res.render('event.ejs',{
event : events,
user : req.user
});
});
app.get('/chat/:id', function(req,res){
Tripgroup.find({"member.member_id" : req.params.id}, function (err, group){
Friendlist.find({"_id" : req.params.id}, function (err, list){
console.log(group);
console.log(list);
res.render('chat.ejs',{
groups : group,
lists : list
});
})
})
});
// 1: Operator 2 : Tour operator 3 : local guide 4 : official guide 5 : Tourist
app.get('/testGroup', function (req, res){
var Newtripgroup = new Tripgroup();
Newtripgroup._id = "group001";
Newtripgroup.name = "group001";
Newtripgroup.trip_name = "trip001";
Newtripgroup.trip_id = "trip001";
Newtripgroup.contact.push({"_id" : "local001", "name" : "local001"});
Newtripgroup.contact.push({"_id" : "local002", "name" : "local002"});
Newtripgroup.contact.push({"_id" : "official001", "name" : "official001"});
Newtripgroup.contact.push({"_id" : "operator01", "name" : "operator01"});
Newtripgroup.member.push({"member_id": "local001", "member_name" : "local001", "member_type" : 3});
Newtripgroup.member.push({"member_id": "local002", "member_name" : "local002", "member_type" : 3});
Newtripgroup.member.push({"member_id": "tourist001", "member_name" : "tourist001", "member_type" : 5});
Newtripgroup.member.push({"member_id": "tourist002", "member_name" : "tourist002", "member_type" : 5});
Newtripgroup.save(function (err){
if(err) throw err;
console.log('trip group created!');
})
var Newtripgroupone = new Tripgroup();
Newtripgroupone._id = "group002";
Newtripgroupone.name = "group002";
Newtripgroupone.trip_name = "trip001";
Newtripgroupone.trip_id = "trip001";
Newtripgroupone.contact.push({"_id" : "local003", "name" : "local003"});
Newtripgroupone.contact.push({"_id" : "local004", "name" : "local004"});
Newtripgroupone.contact.push({"_id" : "official002", "name" : "official002"});
Newtripgroupone.contact.push({"_id" : "operator01", "name" : "operator01"});
Newtripgroupone.member.push({"member_id": "local003", "member_name" : "local003", "member_type" : 3});
Newtripgroupone.member.push({"member_id": "local004", "member_name" : "local004", "member_type" : 3});
Newtripgroupone.member.push({"member_id": "tourist003", "member_name" : "tourist003", "member_type" : 5});
Newtripgroupone.member.push({"member_id": "tourist004", "member_name" : "tourist004", "member_type" : 5});
Newtripgroupone.save(function (err){
if(err) throw err;
console.log('trip group created!');
})
});
app.get('/testlist', function (req, res){
var Newfriendlist = new Friendlist();
Newfriendlist._id = "tourist002";
Newfriendlist.name = "tourist002";
Newfriendlist.list.push({"_id" : "tourist001", "name" : "tourist001"});
Newfriendlist.save(function (err){
if(err) throw err;
console.log('friendList created!')
})
});
app.get('/getFriend/:id', function (req, res){
Friendlist.findById(id, function (err, list){
res.end(JSON.stringify(list));
})
})
app.get('/testTourist', function(req, res){
var Newreview = new Review();
Newreview._id = "tourist001";
Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "place_id" : "place001","place_name" : "place001","type" : 1, "name" : "local001"}]});
//Newreview.reviews[0].content.push("_id" : "local001", "type" : 1, "name" : "local001");
//Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "name" : "local001"}]});
Newreview.reviews[0].content.push({"_id" : "local002", "type" : 1,"place_id" : "place002","place_name" : "place002", "name" : "local002"});
Newreview.reviews[0].content.push({"_id" : "offical001", "type" : 2, "name" : "offical001"});
Newreview.reviews[0].content.push({"_id" : "place001", "type" : 3, "name" : "place001"});
Newreview.reviews[0].content.push({"_id" : "place002", "type" : 3, "name" : "place002"});
Newreview.save(function(err){
if(err) throw err;
console.log('reviews queue created');
});
});
//:id is for test purpose
app.get('/getReviews/:id', function(req, res){
console.log(req.params.id);
Review.find({"_id" : req.params.id},{}, function (err, review){
res.render('reviews.ejs' , {
reviews : review
});
});
});
app.get('getReviews/:id/:tripid', function(req, res){
Review.find({"_id": req.params.id},{"reviews.trip_id": req.params.tripid}, function (err, review){
res.render('reviews.ejs', {
reviews : review
});
});
})
app.get('/wallet', function(req, res){
res.render('wallet.ejs');
});
app.get('/uwochat/:id', function(req, res){
Tripgroup.find({"member.member_id" : req.params.id}, function (err, group){
Friendlist.find({"_id" : req.params.id}, function (err, list){
console.log(group);
console.log(list);
res.render('uwochat.ejs',{
groups : group,
lists : list
});
})
})
});
app.post('/updateReview', function(req, res){
console.log(req.body);
Review.findById(req.body.id, function (err, review) {
for(var i = 0; i < review.reviews.length; i++){
console.log(review);
if(req.body.trip_id == review.reviews[i].trip_id){
console.log(review.reviews[i]);
for(var j = 0; j < review.reviews[i].content.length; j++){
if(req.body.review_id == review.reviews[i].content[j]._id){
if(req.body.rating != 0 && req.body.content != ""){
console.log(req.body.content);
review.reviews[i].content[j].rating = req.body.rating;
review.reviews[i].content[j].details = req.body.content;
review.reviews[i].content[j].time = new Date();
review.reviews[i].content[j].status = 3;
review.save(function(err){
if(err) throw err;
console.log('reviews uploaded!');
});
}else if(req.body.rating != 0 || req.body.content != ""){
//review.reviews[i].content[j].time = new Date();
if(req.body.rating != 0){
review.reviews[i].content[j].rating = req.body.rating;
}
if(req.body.content != ""){
review.reviews[i].content[j].details = req.body.content;
}
review.reviews[i].content[j].status = 2;
review.save(function(err){
if(err) throw err;
console.log('reviews uploaded!');
});
}
console.log(review.reviews[i].content[j]);
res.redirect('/getReviews/' + req.body.id)
}
}
}
}
});
});
app.get('/testlocal', function(req, res){
var Newreview = new Review();
Newreview._id = "local001";
Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "offical001", "type" : 2, "name" : "offical001"}]});
//Newreview.reviews[0].content.push("_id" : "local001", "type" : 1, "name" : "local001");
//Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "name" : "local001"}]});
//Newreview.reviews[0].content.push({"_id" : "local002", "type" : 1, "name" : "local002"});
//Newreview.reviews[0].content.push({"_id" : "offical001", "type" : 2, "name" : "offical001"});
//Newreview.reviews[0].content.push({"_id" : "place001", "type" : 3, "name" : "place001"});
Newreview.reviews[0].content.push({"_id" : "place002", "type" : 3, "name" : "place002"});
var NewreviewTwo = new Review();
NewreviewTwo._id = "local002";
NewreviewTwo.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "offical001", "type" : 2, "name" : "offical001"}]});
//Newreview.reviews[0].content.push("_id" : "local001", "type" : 1, "name" : "local001");
//Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "name" : "local001"}]});
//Newreview.reviews[0].content.push({"_id" : "local002", "type" : 1, "name" : "local002"});
//Newreview.reviews[0].content.push({"_id" : "offical001", "type" : 2, "name" : "offical001"});
//Newreview.reviews[0].content.push({"_id" : "place001", "type" : 3, "name" : "place001"});
NewreviewTwo.reviews[0].content.push({"_id" : "place001", "type" : 3, "name" : "place001"});
NewreviewTwo.save(function(err){
if(err) throw err;
console.log('reviews queue created');
});
Newreview.save(function(err){
if(err) throw err;
console.log('reviews queue created');
});
});
app.get('/testoffical', function (req, res){
var Newreview = new Review();
Newreview._id = "offical001";
Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "place_id" : "place001","place_name" : "place001","name" : "local001"}]});
//Newreview.reviews[0].content.push("_id" : "local001", "type" : 1, "name" : "local001");
//Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "name" : "local001"}]});
Newreview.reviews[0].content.push({"_id" : "local002", "type" : 1,"place_id" : "place002","place_name" : "place002", "name" : "local002"});
//Newreview.reviews[0].content.push({"_id" : "offical001", "type" : 2, "name" : "offical001"});
Newreview.reviews[0].content.push({"_id" : "place001", "type" : 3, "name" : "place001"});
Newreview.reviews[0].content.push({"_id" : "place002", "type" : 3, "name" : "place002"});
Newreview.save(function(err){
if(err) throw err;
console.log('reviews queue created');
});
});
app.get('/testOperator', function(req, res){
var Newreview = new Review();
Newreview._id = "operator001";
Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1,"place_id" : "place001","place_name" : "place001", "name" : "local001"}]});
//Newreview.reviews[0].content.push("_id" : "local001", "type" : 1, "name" : "local001");
//Newreview.reviews.push({"trip_id" : "trip001", "trip_name" : "tripAAA", "content" : [{"_id" : "local001", "type" : 1, "name" : "local001"}]});
Newreview.reviews[0].content.push({"_id" : "local002", "type" : 1,"place_id" : "place002","place_name" : "place002", "name" : "local002"});
//Newreview.reviews[0].content.push({"_id" : "offical001", "type" : 2, "name" : "offical001"});
Newreview.reviews[0].content.push({"_id" : "tourop001", "type" : 3, "name" : "tourop001"});
//Newreview.reviews[0].content.push({"_id" : "place002", "type" : 3, "name" : "place002"});
Newreview.save(function(err){
if(err) throw err;
console.log('reviews queue created');
});
})
app.post('/apply', isLoggedIn, function(req, res){
console.log(req.body);
console.log(req.user._id);
Temp.findById(req.body.event_id , function(err, list){
if(err) throw err;
if(list.host.id == req.user._id){
res.send("You can't Join This Event");
}else if(list.applicants.length >= list.host.applicants){
res.send("Sorry The Number is fully");
}else if(check_join(list.applicants, req.user._id)){
res.send("You have already applied this event!")
}else {
list.applicants.push({"applicant_id" : req.user._id, "applicant_photo" : req.user.facebook.photo, "applicant_name" : req.user.neiconn.firstname});
list.save(function(err){
if(err) throw err;
console.log('apply successfully');
smtpTransport.sendMail({
from: "Neiconn <<EMAIL>>", // sender address
to: " < " + req.user.facebook.email + ">", // comma separated list of receivers
subject: "Request Confirm", // Subject line
//text: "Hello world ✔",
html: "<h3>The event host has already received your request. Please be patient! Give the host little more time to process your request.</h3>"// plaintext body
}, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent");
}
});
smtpTransport.sendMail({
from: "Neiconn <<EMAIL>>", // sender address
to: " < " + req.body.event_host+ ">", // comma separated list of receivers
subject: "Request Confirm", // Subject line
//text: "Hello world ✔",
html: "<h3>"+ req.user.facebook.givenName +" wants to join the event:"+ req.body.event_name +"</h3>"
}, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent");
}
});
res.redirect("/mypage");
});
}
});
});
app.get('/getGroup', isLoggedIn,function(req, res){
Group.find({"member.member_id" : req.user._id },{}, function (err, group){
res.end(JSON.stringify(group));
})
});
//Upload user info
app.get('/editprofile', isLoggedIn, function(req, res) {
res.render('profile-edit.ejs',{
user : req.user
});
});
app.post('/accept' ,isLoggedIn, function(req,res){
});
app.post('/sendMessage', isLoggedIn, function(req, res) {
Message.findById(req.body.sender_id, function (err, messager){
if (err) throw err;
messager.outbox.push({"reciever_id" : req.body.reciever_id, "reciever_name" : req.body.reciever_name, "content" : req.body.content});
messager.save(function (err) {
if(err) throw err;
console.log("Message saved!");
});
});
Message.findById(req.body.reciever_id, function (err, messager){
messager.inbox.push({"sender_id" : req.body.sender_id, "sender_name" : req.body.sender_name, "content" : req.body.content});
messager.save(function (err) {
if(err) throw err;
console.log("Message sent!");
});
})
res.redirect('/event');
});
app.get('/orders', function(req, res){
res.render('orders.ejs');
});
app.get('/oporders', function(req, res){
res.render('orderop.ejs');
});
app.get('/gorder', function(req, res){
res.render('orderg.ejs');
})
app.post('/update_user', isLoggedIn, function(req, res){
var id = req.body.id;
User.findById(id, function(err, user) {
if (err) throw err;
console.log(user);
user.neiconn.work = req.body.work;
user.neiconn.birth.month = req.body.month;
user.neiconn.birth.year = req.body.year;
user.neiconn.birth.day = req.body.day;
user.neiconn.phone = req.body.phone;
user.neiconn.location = req.body.location;
user.neiconn.school = req.body.school;
user.neiconn.about = req.body.about;
user.neiconn.language = req.body.language;
user.save(function(err){
if (err) throw err;
console.log('user successfully updated!');
res.redirect("/mypage");
});
});
});
app.post('/admin', function(req, res){
var id = req.body.id;
console.log(req.body);
res.render('admin.ejs');
});
app.get('/adminplace', function (req, res){
// body...
Uwoplace.find({},{}, function (err, data) {
res.end(JSON.stringify(group));
});
});
app.post('/addPlace', function (req, res){
var Newuwoplace = new Uwoplace();
});
//get event
app.post('/createevent', isLoggedIn, function(req, res){
var id = req.body.id;
Event.findById(id, function(err, event) {
if(err) throw err;
if(event){
res.send("Sorry! Please create a valid activity");
}else {
var newEvent = new Event();
var newTemp = new Temp();
var newGroup = new Group();
console.log(newEvent);
newEvent._id = Date.now();
newEvent.category = "upcoming";
newEvent.content.time = req.body.time;
newEvent.content.duration = req.body.duration;
newEvent.content.date = req.body.date;
newEvent.content.category = req.body.category;
newEvent.content.title = req.body.title;
newEvent.content.photo[0] = "images/sea.jpg";
newEvent.content.price = req.body.price;
newEvent.content.total_attendees = req.body.total_attendees;
newEvent.user.email = req.body.email;
newEvent.content.about = req.body.about;
newEvent.content.rule[0] = req.body.rule;
newEvent.content.location.address = req.body.address;
newEvent.content.location.lat = req.body.lat;
newEvent.content.location.lon = req.body.lon;
newEvent.content.language = req.body.language;
newEvent.content.venue = req.body.venue;
newEvent.content.provision = req.body.provision;
newEvent.user.reviews = req.body.reviews;
newEvent.user.rating = req.body.rating;
newEvent.user.name = req.body.name;
newEvent.user.role = "host"; //host must
newEvent.user.photo = req.body.photo,
newEvent.user._id = id;
newGroup._id = newEvent._id;
newGroup.event.event_picture = newEvent.content.photo[0];
newGroup.event.event_date = newEvent.content.date;
newGroup.event.event_time = newEvent.content.time;
newGroup.event.event_duration = newEvent.content.duration;
newGroup.event.event_amount = newEvent.content.total_attendees;
newGroup.event.event_title = newEvent.content.title;
newGroup.member.push({"member_id" : newEvent.user._id, "member_photo": newEvent.user.photo});
newGroup.contentStoage.push({"member_id" : newEvent.user._id, "member_content": "welcome to join this group"});
newTemp._id = newEvent._id;
newTemp.host.name = newEvent.user.name;
newTemp.host.id = newEvent.user._id;
newTemp.host.applicants = 2 * newEvent.content.total_attendees;
newTemp.applicants = [];
newTemp.save(function(err){
if(err) throw err;
console.log('applicants queue created');
});
newGroup.save(function(err){
if(err) throw err;
console.log('group created!');
});
newEvent.save(function(err){
if (err) throw err;
console.log('user successfully updated!');
res.redirect("/mypage");
});
}
});
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
console.log(req.file.filename);
});
});
// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================
// locally --------------------------------
// LOGIN ===============================
// show the login form
app.get('/login', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
// process the login form
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
// SIGNUP =================================
// show the signup form
app.get('/signup', function(req, res) {
res.render('signup.ejs', { message: req.flash('signupMessage') });
});
app.get('/home', function (req, res) {
res.render('home.ejs', {message: req.flash('open Home') });
// body...
})
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
// facebook -------------------------------
// send to facebook to do the authentication
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/mypage',
failureRedirect : '/'
}));
// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================
// locally --------------------------------
app.get('/connect/local', function(req, res) {
res.render('connect-local.ejs', { message: req.flash('loginMessage') });
});
app.post('/connect/local', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
// facebook -------------------------------
// send to facebook to do the authentication
app.get('/connect/facebook', passport.authorize('facebook', { scope : 'email' }));
// handle the callback after facebook has authorized the user
app.get('/connect/facebook/callback',
passport.authorize('facebook', {
successRedirect : '/mypage',
failureRedirect : '/'
}));
// =============================================================================
// UNLINK ACCOUNTS =============================================================
// =============================================================================
// used to unlink accounts. for social accounts, just remove the token
// for local account, remove email and password
// user account will stay active in case they want to reconnect in the future
// local -----------------------------------
app.get('/unlink/local', isLoggedIn, function(req, res) {
var user = req.user;
user.local.email = undefined;
user.local.password = <PASSWORD>;
user.save(function(err) {
res.redirect('/');
});
});
// facebook -------------------------------
app.get('/unlink/facebook', isLoggedIn, function(req, res) {
var user = req.user;
user.facebook.token = undefined;
user.save(function(err) {
res.redirect('/');
});
});
app.get('/reviews', function(req, res){
});
// General Pages
app.get('/main', function (req, res) {
res.render('main.ejs');
// body...
});
app.get('/mypage', isLoggedIn, function(req, res) {
res.render('mypage.ejs', {
user : req.user
});
});
app.get('/post_event', isLoggedIn, function(req, res) {
res.render('post_event.ejs', {
user : req.user
});
});
};
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.send("Please sign up and log in");
}
function isLoggedIn_event(req, res, next) {
if (req.isAuthenticated())
return next();
console.log(req.body.id);
var id = req.body.id;
var events = getEvent(req.session.events, id);
res.render('event.ejs',{
event : events,
user : null
});
}
<file_sep>// load the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var userSchema = mongoose.Schema({
_id : String,
local : {
email : String,
password : String
},
facebook : {
id : String,
token : String,
email : String,
name : String,
gender : String,
photo : String,
familyName : String,
givenName : String,
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
},
linkedin : {
id : String,
token : String,
email : String
},
neiconn :{
language : String,
school : String,
work : String,
about : String,
firstName : String,
lastName : String,
birth : {
year: String,
month: String,
day: String
},
phone : String,
location : String,
recommend : [String],
age : { type:Number , min: 16 , max: 100},
enrollDate : { type:Date , default: Date.now}
},
});
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var placeSchema = mongoose.Schema({
tags : [String],
is_hidden : Boolean,
title : {
en: String,
cn: String
},
introduction : String,
description : String,
photos : {type: [String], default: ['http://www.davidluke.com/wp-content/themes/david-luke/media/ims/placeholder720.gif']},
reviews : Array,
ratings : Array,
score : Number,
address : String,
minutes : {type: Number, default: 90},
admission : String,
phone : String,
website : String,
post_date : {
type : Date,
default: Date.now
},
owner: {
type : mongoose.Schema.ObjectId,
ref : 'User'
},
media_id: {
type : mongoose.Schema.ObjectId,
re : 'Media'
}
});
// generating a hash
placeSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
placeSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Place', placeSchema);
<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our tripgroup model
var tripgroupSchema = mongoose.Schema({
_id : String, // group id
trip_id : String, // trip id
trip_name : String, // trip name
contact : [
{
_id : String,
name : String,
}
],
member : [{
member_id : String, // all members id n the froup = the user's id
member_name : String, // the members name
member_type : String, // 1: Operator 2 : Tour operator 3 : local guide 4 : official guide 5 : Tourist
}]
});
// generating a hash
tripgroupSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
tripgroupSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Tripgroup', tripgroupSchema);
<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var tripSchema = mongoose.Schema({
_id : String, // Trip id
name : String,
local : [{
_id : String,
name : String,
image : String,
position : {
_id : String,
name : String,
lat : String,
lon : String
}
}], // local guide
official : [{
_id : String,
name : String,
image : String,
lat : String,
lon : String
}],
tourist : [{
_id : String,
name : String,
image : String,
lat : String,
lon : String
}]
});
// generating a hash
tripSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
tripSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Trip', tripSchema);<file_sep>var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our tripgroup model
var friendlistSchema = mongoose.Schema({
_id : String, // user id
name : String, // user name
list : [
{
_id : String,
name: String,
}
]
});
// generating a hash
friendlistSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
friendlistSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('Friendlist', friendlistSchema); | efa77283565200d397d48bad02f46f360840a09f | [
"JavaScript"
] | 13 | JavaScript | senzheng/neiconn_2 | d70de11b4858dc4ab7d17ed5fb7d2ad2b81c84ba | 5fd68d2052c52d13cac8e30e176ce64f81dffae8 |
refs/heads/main | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
public class ConnectingSceneController : MonoBehaviour
{
public Text message;
private GameClient client;
// Start is called before the first frame update
void Start()
{
message.text = "Connecting...";
client = GameClient.Instance;
client.OnConnect += OnConnect;
client.OnJoin += OnJoin;
if (!client.Connected)
{
client.Connect();
}
else
{
OnConnect(this, null);
}
}
// Update is called once per frame
void OnConnect(object sender, EventArgs e)
{
message.text = "Finding a game...";
if (!client.Joined)
{
client.Join();
}
else
{
OnJoin(this, null);
}
}
void OnJoin(object sender, EventArgs e)
{
message.text = "Joined! Finding table ...";
}
}
<file_sep>using Colyseus.Schema;
public class State : Schema
{
[Type(1, "array", "int16")]
public ArraySchema<short> player1Shots = new ArraySchema<short>();
[Type(2, "array", "int16")]
public ArraySchema<short> player2Shots = new ArraySchema<short>();
[Type(3, "array", "int16")]
public ArraySchema<short> player3Shots = new ArraySchema<short>();
[Type(4, "array", "int16")]
public ArraySchema<short> player4Shots = new ArraySchema<short>();
}
| 90acb7a55efd986e5e70065b160ed7006ea15601 | [
"C#"
] | 2 | C# | hoangtuan2910/bco_client | cdd8e6bbaac0535712b23ae54e33c1eccbddc314 | 96f07e965265b0cabee6920bf091b4e231c78033 |
refs/heads/main | <file_sep>import Puma from "components/icons/Puma";
import Adidas from "components/icons/Adidas";
import Nike from "components/icons/Nike";
import Reebok from "components/icons/Reebok";
import Gucci from "components/icons/Gucci";
export const Brands = [Puma, Adidas, Nike, Reebok, Gucci];
export const Products = [
{
id: 1,
image: "/assets/1.png",
name: "Puma Human Race",
price: 280,
},
{
id: 2,
image: "/assets/2.png",
name: "Adidas Classic",
price: 350,
},
{
id: 3,
image: "/assets/3.png",
name: "Reebok Ground Up",
price: 200,
},
{
id: 4,
image: "/assets/4.png",
name: "<NAME> 2",
price: 780,
},
{
id: 5,
image: "/assets/5.png",
name: "<NAME>",
price: 415,
},
{
id: 6,
image: "/assets/6.png",
name: "<NAME>",
price: 655,
},
{
id: 7,
image: "/assets/7.png",
name: "<NAME>",
price: 530,
},
];
<file_sep># Framer motion shopping cart animation
This project is just made for fun and learn [Framer Motion](https://framer.com/motion)
<file_sep>import { Variants } from "framer-motion";
type StaggerVariant = {
delay?: number;
direction?: number;
childdelay?: number;
};
export const Stagger: Variants = {
initial: {},
animate: (custom: StaggerVariant | undefined) => {
return {
transition: {
delayChildren: custom && custom.delay ? custom.delay : 0,
staggerChildren: custom && custom.childdelay ? custom.childdelay : 0.1,
when: "beforeChildren",
staggerDirection: custom && custom.direction ? custom.direction : 1,
},
};
},
};
export const AppearY: Variants = {
initial: {
opacity: 0,
y: "40%",
},
animate: {
opacity: 1,
y: 0,
},
exit: {
scale: 0,
},
};
export const AppearX: Variants = {
initial: {
opacity: 0,
x: "40%",
},
animate: {
opacity: 1,
x: 0,
},
};
export const GlobalMessageAnim: Variants = {
initial: {
opacity: 0,
y: "-100%",
x: "-50%",
},
animate: {
opacity: 1,
y: 0,
},
exit: {
opacity: 0,
},
};
export const CartMiniViewAnim: Variants = {
initial: {
height: 0,
},
expanded: {
height: "96px",
},
minimized: {
height: "16px",
},
};
<file_sep>export type Item = {
id: number;
image: string;
name: string;
price: number;
quantity: number;
};
export type GlobalMessageFuncType = {
text: string;
type: "WARNING" | "ALERT" | "NOTIFY";
};
| 8e8651fe9a4440ec83d96d105b9efafd8358a662 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | themashcodee/shoping-cart-animation | cdd76f18433b5fe1ab78a801d78c3aca6e50302a | 9ed939aeaf38350188bd1b5a4ee3a8fbeb8ebf71 |
refs/heads/master | <repo_name>fthebaud/browser-frame-rate<file_sep>/script.js
'use strict';
let framerate = (function () { // eslint-disable-line no-unused-vars
let start;
let timestamp;
let resultats = [];
let towardsRight;
let pixelShift = 1;
function initialisation() {
let button = document.getElementById('launchButton');
button.addEventListener('click', animate);
}
function animate() {
if (!start) {
start = Date.now();
document.getElementById('launchButton').disabled = true;
towardsRight = true;
}
//animate frame
let div = document.getElementById('blueDiv');
let left = Number.parseInt(div.style.left.slice(0, -2)) || 0;
if (left > 100) {
towardsRight = false;
}
if (left <= 0) {
towardsRight = true;
}
if (towardsRight) {
left = left + pixelShift;
} else {
left = left -pixelShift;
}
document.getElementById('blueDiv').style.left = left + 'px';
// calcul fps
if (timestamp) {
let newTimestamp = Date.now();
let delta = newTimestamp - timestamp;
let fps = 1000 / delta;
resultats.push(fps);
timestamp = newTimestamp;
}
else {
timestamp = Date.now();
}
let dureeAnimation = 5000; // en ms
if (Date.now() - start < dureeAnimation) {
// request a render before animating next frame
window.requestAnimationFrame(animate);
}
else {
console.log(resultats);
var moyenne = resultats.reduce(function (previousValue, currentValue, currentIndex, array) {
if (currentIndex === array.length - 1) {
return (previousValue + currentValue) / array.length;
}
return previousValue + currentValue;
}, 0);
let res = `nombre de frames = ${resultats.length}<br/>
average fps = ${moyenne.toFixed(3)}<br/>
fps max = ${Math.max(...resultats).toFixed(3)}<br/>
fps min = ${Math.min(...resultats).toFixed(3)}`;
document.getElementById('resultats').innerHTML = res;
document.getElementById('launchButton').disabled = false;
start = null;
timestamp = null;
resultats.length = 0;
}
}
return {
init: initialisation
};
}());
framerate.init();
| fbe7275e913098a47ba0441f76b384c85652b9b7 | [
"JavaScript"
] | 1 | JavaScript | fthebaud/browser-frame-rate | f1bd30d390a1aeaa23df49ba0c5b391c50f99dc7 | 1ccc41a8c53ceb159eea9020f9d71d8f38af962d |
refs/heads/master | <repo_name>Nonju/WebbShop<file_sep>/Webbshop/hiddenScripts/user/LoggedInHeaderSpace.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-18
* Time: 21:58
*/
include("../../hiddenScripts/DbLogin.php");
$un = $_SESSION['username'];
if(isset($_GET['cartAdd']) && isset($_SESSION['user_ID'])) {
//find out what item is added
$itemToAdd = filter_input(INPUT_GET,'cartAdd',FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "SELECT artName FROM products WHERE artNr='$itemToAdd'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$itemToAdd = $stmt->fetch()[0];
//retrive current cart-string
$sql = "SELECT cart FROM users WHERE username='$un'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$cartString = $stmt->fetch()[0]; //fetch cartContent
//update cart-string
$newCartString = $cartString . '|' . $itemToAdd; //add new product + a divider
$sql = "UPDATE users SET cart='$newCartString' WHERE username='$un'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
//removing the cartAdd "command" from the URL
if(isset($_GET['aNr'])) {
$aNr = filter_input(INPUT_GET,'aNr',FILTER_SANITIZE_SPECIAL_CHARS);
echo "<script> //return
window.location = 'http://hannes.teknikprogrammet.org/Shop/?aNr={$aNr}';
</script>";
}
else {
echo "<script> //return
window.location = 'http://hannes.teknikprogrammet.org/Shop/';
</script>";
}
}
/*
if(isset($_GET['cartID']) && isset($_SESSION['user_ID'])) {
//retrive current cartContent
$cartID = filter_input(INPUT_GET,'cartID',FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "SELECT cart WHERE user_ID='$cartID'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$cartArr = array();
while($row = $stmt->fetch()) {
array_push($cartArr, $row);
}
//lägg till "window.location" här
}*/
?>
<div id="loggedinSpace">
<?php
$user_ID = $_SESSION['user_ID'];
$username = $_SESSION['username'];
echo "<p id='loggedinUser'>Inloggad som: {$username}</p>";
echo "<a href='http://hannes.teknikprogrammet.org/Shop/?signoff=true' id='signoffBtn'>Logga ut</a>";
?>
</div><file_sep>/Webbshop/hiddenScripts/user/ErrorcodeDisplay.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-18
* Time: 13:27
*/
class ErrorcodeDisplay {
public function __construct() { }
public function ShowErrorMsgs($createUserEC,$loginEC) {
$codeString = $createUserEC . $loginEC;
$eCodes = $this->DetectMsgs($codeString);
foreach($eCodes as $eCode) {
$eCode = $this->changeToNr($eCode); //errorcodes with letters didn't work so remaking them into numerical codes
switch($eCode) {
case '00000': //user created
echo "<script>
document.getElementById('formMessageBox').style.display = 'block';
document.getElementById('fmbText').innerHTML += '<br />En ny användare är skapad!! <br /> Prova logga in!';
</script>";
break;
case '23000': //a user with that username already exists
echo "<script>
document.getElementById('formMessageBox').style.display = 'block';
document.getElementById('fmbText').innerHTML += '<br />Det fanns redan en användare med det namnet. Välj ett annat!';
</script>";
break;
case '0001': //space within username
echo "<script>
document.getElementById('formMessageBox').style.display = 'block';
document.getElementById('fmbText').innerHTML += '<br />Använd inte mellanrum i användarnamnet';
</script>";
break;
case '0002': //spaces within password
echo "<script>
document.getElementById('formMessageBox').style.display = 'block';
document.getElementById('fmbText').innerHTML += '<br />Använd inte mellanrum i lösenordet';
</script>";
break;
case '0003': //login failed
echo "<script>
document.getElementById('formMessageBox').style.display = 'block';
document.getElementById('fmbText').innerHTML += '<br />Användarnamnet stämde inte överens med lösenordet '
</script>";
break;
default:
echo "<script>
document.getElementById('formMessageBox').style.display = 'none';
</script>";
break;
}
}
} //end function
private function DetectMsgs($codeString) { //divides $codeString into an array with different messageCodes
$codes = explode(" ", $codeString);
return $codes;
}
private function changeToNr($code) { //remakes the errorcodes into numerical codes
if($code == 'unSpace') {$code = '0001';}
else if($code == 'pwSpace') {$code = '0002';}
else if($code == 'loginFailed') {$code = '0003';}
return $code;
}
}
<file_sep>/Webbshop/public_html/Shop/index.php
<?php
header("Content-Type: text/html; charset=utf-8");
//start new userSession
session_start();
//checks if user is signing off
$signOut = false;
if(isset($_GET['signoff'])) {
$signOut = filter_input(INPUT_GET,'signoff',FILTER_SANITIZE_SPECIAL_CHARS);
if($signOut == 'true') {
session_unset();
echo "<script>
//sends the user back to the startpage when signing off
window.location = 'http://hannes.teknikprogrammet.org/Shop/';
</script>";
}
}
require("../../hiddenScripts/itemDisplayer/DisplayItems.php");
$itemDisplayer = new DisplayItems();
require("../../hiddenScripts/user/LoginUser.php");
require("../../hiddenScripts/user/InsertNewUser.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Webbshop</title>
<link href="css/design.css" rel="stylesheet" /> <!-- .css stylesheet -->
</head>
<body>
<div id="wrappper"> <!-- for possible adjustments -->
<div id="header" > <!-- collection of logoIMG, login and possible searchbar -->
<img src="images/Logga.png" alt="loga" id="headerIMG" />
<div id="headerSpace"> <!-- the space left on header after headerIMG -->
<?php
//displays a messagebox <div> with a message regarding the login/usercreation
require("../../hiddenScripts/user/ErrorcodeDisplay.php");
$ecDisp = new ErrorcodeDisplay();
//decides what to show in the headerSpace
if(isset($_SESSION['user_ID'])) {
//shows customercart and ability to log off
require("../../hiddenScripts/user/LoggedInHeaderSpace.php");
}
else {
//displays the login/createUser-form
require("visibleScripts/loginForm.html");
//require("../../hiddenScripts/user/LoggedInHeaderSpace.php"); //test
}
$ecDisp->ShowErrorMsgs($createUserEC,$loginEC);
//space for searching items
require ("../../hiddenScripts/searchSpace.php");
?>
</div>
</div>
</div>
<div id="categoryMenu" >
<nav class="catMenuNav">
<a href="http://hannes.teknikprogrammet.org/Shop/" class="catMenuSec">Startsida</a>
<a href="http://hannes.teknikprogrammet.org/Shop?category=computer" class="catMenuSec">Datorer</a>
<a href="http://hannes.teknikprogrammet.org/Shop?category=gadget" class="catMenuSec">Tillbehör</a>
<?php
if(isset($_SESSION['user_ID'])){
echo "<a href='http://hannes.teknikprogrammet.org/Shop/?cartID={$user_ID}' class='catMenuSec'>Kundvagn</a>";
}
?>
</nav>
</div>
<div id="articleSpace" > <!-- loads in different articles depending on what's requested by user -->
<?php //Php-function that generates articleObjects
//Called when a category is selected
$selectedCategory = 0;
if(isset($_GET['category'])) {
$selectedCategory = filter_input(INPUT_GET, 'category', FILTER_SANITIZE_SPECIAL_CHARS);
}
$selectedArticle = 0;
if(isset($_GET['aNr'])) {
$selectedArticle = filter_input(INPUT_GET, 'aNr', FILTER_SANITIZE_SPECIAL_CHARS);
}
if(isset($selectedCategory) && $selectedCategory !== 0) {
$itemDisplayer->dispCat($selectedCategory);
}
else if(isset($selectedArticle) && $selectedArticle !== 0) {
$itemDisplayer->dispSelect($selectedArticle);
}
else if(isset($_GET['cartID']) && isset($_SESSION['user_ID'])) {
$itemDisplayer->dispCart();
}
else {
$itemDisplayer->dispAll();
}
?>
</div>
<div class="clear"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="visibleScripts/design.js" type="text/javascript"></script> <!-- .js stylesheet that takes care of all other design details that .css cant do -->
</body>
</html><file_sep>/Webbshop/hiddenScripts/itemDisplayer/cartObject.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-19
* Time: 20:47
*/
class cartObject {
public $artNr;
public $artName;
public $artPrice;
public function __construct($objectArr) {
$this->artNr = $objectArr['artNr'];
$this->artName = $objectArr['artName'];
$this->artPrice = $objectArr['price'];
}
public function DrawOnScreen() {
echo ("
<div id='cartItem'>
<img src='images/productIMGs/{$this->artName}{$this->artNr}.png' alt='{$this->artName}' />
<div id='cartItemInfo'>
<p>{$this->artName}</p>
<p>{$this->artPrice}</p>
</div>
</div>
");
}
} <file_sep>/Webbshop/hiddenScripts/itemDisplayer/ProductPage.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-10
* Time: 23:21
*/
class ProductPage {
public $artNr;
public $artName;
public $artPrice;
public $artDescription;
public $nrInStore;
public function __construct($productInfoArray) {
$this->artNr = $productInfoArray[0]['artNr'];
$this->artName = $productInfoArray[0]['artName'];
$this->artPrice = $productInfoArray[0]['price'];
$this->artDescription = $productInfoArray[0]['description'];
$this->nrInStore = $productInfoArray[0]['nrInStore'];
}
public function DrawOnScreen() {
echo ("
<div id='pPageSpace'>
<img src='images/productIMGs/{$this->artName}{$this->artNr}.png' alt='{$this->artName}' id='ppIMG' />
<div id='ppBuyInfo'>
<p id='ppName'>{$this->artName}</p>
<p id='ppPrice'>{$this->artPrice}</p>
<p id='ppArtNr'>{$this->artNr}</p>
<p id='ppNrInStore'>{$this->nrInStore}</p>
<a href='' >Lägg till i kundvagn</a>
</div>
<p id='ppDescription'>{$this->artDescription}</p>
</div>
");
}
} <file_sep>/Webbshop/hiddenScripts/itemDisplayer/DisplayItems.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-02-03
* Time: 09:13
*/
class DisplayItems {
public function __construct() {
}
private function draw($itemArr) { //draws the wanted objects on the screen
foreach($itemArr as $item) {
$aO = new articleObject($item['artNr'], $item['artName'], $item['price'], $item['description'], $item['nrInStore']);
//echo $item['productGroup'] . " ";
$aO->DrawOnScreen();
}
}
public function dispAll() { //displays all objects (or atleast a reasonable number of them)
unset($itemArray); //clears array before adding new items
require("../../hiddenScripts/DbReciever.php"); //has to be placed individually in every method that uses it
require("../../hiddenScripts/itemDisplayer/articleObject.php");
$dbReciver = new DbReciever();
$itemArr = $dbReciver->DbReciver("SELECT * FROM products");
$this->draw($itemArr); //draws the items on the screen
}
public function dispCat($selectedCategory) {
unset($itemArray); //clears array before adding new items
require("../../hiddenScripts/DbReciever.php"); //has to be placed individually in every method that uses it
require("../../hiddenScripts/itemDisplayer/articleObject.php");
$dbReciver = new DbReciever();
//Retrive objects that belongs to selected category
$itemArr = array();
$tempArr = $dbReciver->DbReciver("SELECT * FROM products");
foreach($tempArr as $item) {
if($item['productGroup'] == $selectedCategory) {
array_push($itemArr, $item);
}
};
$this->draw($itemArr); //draws the items on the screen
}
public function dispSelect($artNr) { //will display selected item and retrive info about that item ONLY!!
unset($itemArray); //clears array before adding new items
require("../../hiddenScripts/DbReciever.php"); //has to be placed individually in every method that uses it
require("../../hiddenScripts/itemDisplayer/ProductPage.php"); //displays the current selected product
$dbReciver = new DbReciever();
$itemArr = $dbReciver->DbReciver("SELECT * FROM products WHERE artNr = $artNr");
$pp = new ProductPage($itemArr);
$pp->DrawOnScreen();
//$this->draw($itemArr); //draws the items on the screen
}
public function dispCart() {
require("../../hiddenScripts/DbLogin.php");
require("../../hiddenScripts/itemDisplayer/cartObject.php"); //displays the current products in the users cart
//retrive current cartContent
$cartID = filter_input(INPUT_GET,'cartID',FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "SELECT cart FROM users WHERE user_ID='$cartID'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
//echo $stmt->fetch()[0];
$cartArr = explode("|",$stmt->fetch()[0]);
foreach($cartArr as $product) {
$sql = "SELECT * FROM products WHERE artName='$product'";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$product = $stmt->fetch();
$cO = new cartObject($product);
$cO->DrawOnScreen();
}
}
//not in this version of the page
public function dispSearch($search) { //use $search to retrive items from database that matches it's value
unset($itemArray); //clears array before adding new items
//unset($objectArray);
require("../../hiddenScripts/DbReciever.php"); //has to be placed individually in every method that uses it
$dbReciver = new DbReciever();
$itemArr = 0; //add sql-question and such ($dbReciver->DbReviver($sql);
if(isset($itemArr)) {
$this->draw($itemArr); //draw the items on the screen
}
else {
alert("Föremålet kunde inte hittas");
}
}
} <file_sep>/Webbshop/hiddenScripts/itemDisplayer/articleObject.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-02-03
* Time: 09:57
*/
class articleObject {
public $artNr;
public $artName;
public $artPrice;
public $artDescription;
public $nrInStore;
public function __construct($artNr, $artName, $artPrice, $artDescription, $nrInStore) {
$this->artNr = $artNr;
$this->artName = $artName;
$this->artPrice = $artPrice;
$this->artDescription = $artDescription;
$this->nrInStore = $nrInStore;
}
public function DrawOnScreen() { // make box bigger and find way to store IMG's
echo "<div class='articleObject'>";
echo "<img src='images/productIMGs/{$this->artName}{$this->artNr}.png' alt='{$this->artName}' class='artIMG'/>"; //echo "<img src='images/productIMGs/Dator1.png' alt='dator'/>";
echo "<div class='nameAndPrice'>";
echo "<a href='http://hannes.teknikprogrammet.org/Shop/?aNr={$this->artNr}' class='artLink'>{$this->artName}</a>";
echo "<p class='artPrice'>{$this->artPrice}:-</p>";
echo "</div>";
echo "<div>";
echo "<p class='artDescrip'>{$this->artDescription}</p>";
echo "</div>";
echo "<div class='lowerDiv'>";
echo "<p>Antal i lager: {$this->nrInStore}</p>";
echo "<a href='http://hannes.teknikprogrammet.org/Shop/?cartAdd={$this->artNr}' class='cartButton'>Lägg till i kundvagn</a>";
echo "</div> \n\n";
//echo "<p>{$this->linkToProductPage}</p>"; //used to test if link reached here
echo "</div>";
}
}<file_sep>/Webbshop/hiddenScripts/user/InsertNewUser.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-17
* Time: 08:33
*/
//Submit new userdata to users-table
include("../../hiddenScripts/DbLogin.php");
require("../../hiddenScripts/user/passwordCrypt.php");
if(isset($_POST['create-user-form']) && $_POST['createUsername'] !== 'Användarnamn'){
$username = filter_input(INPUT_POST,'createUsername',FILTER_SANITIZE_SPECIAL_CHARS);
$password = filter_input(INPUT_POST,'createPassword',FILTER_SANITIZE_SPECIAL_CHARS);
$confirmPass = filter_input(INPUT_POST,'confirmPassword',FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST,'createEmail',FILTER_SANITIZE_SPECIAL_CHARS);
//needs to turn 'true' in order to write to DB
$unCheck = false;
$pwCheck = false;
$createUserEC; //errorCode
//control USERNAME
if(!preg_match('/\s/', $username)) { //checks if username contains space's
$unCheck = true;
}
else {
$createUserEC .= "unSpace ";
}
//control PASSWORD
if(!preg_match('/\s/', $password) && !preg_match('/\s/', $confirmPass)) {
if($password === $confirmPass) {
$pwCheck = true;
}
else { //passwords didnt match
echo "<script>alert('Lösenorden matchade inte!');</script>";
}
}
else {
$createUserEC .= "pwSpace ";
}
if($unCheck === true && $pwCheck === true) {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username,password,email,cart) VALUES ('{$username}','{$passwordHash}','{$email}',NULL);";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$createUserEC .= $stmt->errorCode();
}
}
<file_sep>/Webbshop/hiddenScripts/DbReciever.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-02-12
* Time: 18:11
*/
class DbReciever {
/* not really needed (not now atleast) */
public function __construct() { //removed "$sqlQuestion"
}
/**/
public function DbReciver($sql) {
include("DbLogin.php"); //login-information to database
//include("../../hiddenScripts/DbLogin.php");
$stmt = $dbh->prepare($sql);
$stmt->execute();
$dbArr = array();
while($row = $stmt->fetch()) { //adds items to returned array
array_push($dbArr, $row);
}
return $dbArr;
}
} <file_sep>/README.txt
Webbshop made as a first-php/database-project during High School
This page is not finished by any means and has a lot of small to medium size things that needs to be fixed before being called so.<file_sep>/Webbshop/hiddenScripts/searchSpace.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-10
* Time: 08:32
*/
echo "<div id='searchSpace'>";
echo "<p>SearchSpace</p>";
echo "<p>Finns inte i beta 1.0</p>";
echo "</div>";<file_sep>/Webbshop/hiddenScripts/user/LoginUser.php
<?php
/**
* Created by PhpStorm.
* User: hannesalbinsson
* Date: 2015-03-18
* Time: 16:54
*/
require("../../hiddenScripts/DbLogin.php");
require("../../hiddenScripts/user/passwordCrypt.php");
if(isset($_POST['submit-logon-form']) && $_POST['submitUsername'] !== 'Användarnamn') {
$user_ID; //userID to be set if user's logged in
$user_cart; //the users cart to be set if user's logged in
$username = filter_input(INPUT_POST,'submitUsername',FILTER_SANITIZE_SPECIAL_CHARS);
$password = filter_input(INPUT_POST,'submitPassword',FILTER_SANITIZE_SPECIAL_CHARS);
//needs to turn 'true' in order to login
$unCheck = false;
$pwCheck = false;
$loginEC; //errorcode
//retrives usernames from DB, NOT optimal to retrive every user but works for now
$sql = "SELECT * FROM users";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$dbArr = array();
while($row = $stmt->fetch()) { //adds items to returned array
array_push($dbArr, $row);
}
foreach($dbArr as $user) {
if($username === $user['username']) {
$unCheck = true;
//break;
if(password_verify($password,$user['password'])) {
$pwCheck = true;
//retrive the rest of the useful userdata
$user_ID = $user['user_ID'];
$user_cart = $user['cart'];
}
}
}
if($unCheck && $pwCheck) { //user is logged in
$_SESSION['user_ID'] = $user_ID;
$_SESSION['username'] = $username;
$_SESSION['usercart'] = $user_cart;
}
else { //not logged in
$loginEC .= 'loginFailed ';
}
}
<file_sep>/Webbshop/settings/php-wrapper_5.3
#!/bin/sh
PHPRC=/storage/content/06/192206/hannes.teknikprogrammet.org/settings/php.ini
export PHPRC
export PHP_FCGI_MAX_REQUESTS=5000
export PHP_FCGI_CHILDREN=0
exec /usr/local/php53/bin/php-cgi
<file_sep>/Webbshop/public_html/Shop/visibleScripts/design.js
/**
* Created by hannesalbinsson on 2015-03-01.
*/
//---- HEADER ----\\
//---- headerIMG ----\\
$headerImgWidth = $('#headerIMG').width();
$headerImgHeight = ($headerImgWidth * 0.42);
$('#headerIMG').height($headerImgHeight);
//---- headerHeight ----\\
$('#header').height($headerImgHeight);
//---- headerSpaceHeight ----\\
$('#headerSpace').height($headerImgHeight); //the entire headerSpace
$loginSpaceHeight = ($('#headerSpace').height() * 0.8); //fixed height for both #loginSpace and #loggedinSpace
$('#loginSpace').height($loginSpaceHeight);
$('#loggedinSpace').height($loginSpaceHeight);
$('#searchSpace').height(($('#headerSpace').height() * 0.18));
//---- FORMMESSAGEBOX ----\\
$('#formMessageBox').height($('#headerSpace').height() * 0.3);
//---- CATEGORYMENU ----\\
$catMenuNavHeight = $('.catMenuNav').height();
$('.catMenuLi').height($catMenuNavHeight);
//---- ARTICLE ----\\
//---- artBox ----\\
//sets width to always be about a quater of the width of articleSpace
$artSpaceWidth = $('#articleSpace').width();
$artBoxWidth = (($artSpaceWidth * 0.22)); // 1/4 and some marginal
$('.articleObject').width($artBoxWidth);
//adjusts height to always be proportional to width
$artBoxWidth = $('.articleObject').width();
$artBoxHeight = ($artBoxWidth * 1.5);
$('.articleObject').height($artBoxHeight);
//---- artIMG ----\\
$artBoxHeight = $('.articleObject').height();
$artImgHeight = ($artBoxHeight * 0.5);
$('.artIMG').height($artImgHeight);
//---- lowerDiv ----\\
$lowerDivHeight = ($artBoxHeight * 0.1);
$('.lowerDiv').height($lowerDivHeight); // sets the height for the "lowerDiv"-class
$('.cartButton').height($lowerDivHeight); //sets the shopping cart button to be the same height as .lowerDiv
//---- PRODUCTPAGE ----\\
$('#ppIMG').height($('#ppIMG').width() * 0.8);
$('#ppBuyInfo').height($('#ppIMG').height());
<file_sep>/Webbshop/hiddenScripts/DbLogin.php
<?php
//PDO-connection with password, username and stuff
$dbserver = "hannes2-192206.mysql.binero.se";
$database = "192206-hannes2";
$username = "192206_sx46985";
$password = "..."; //secret
$dbh = new PDO("mysql:host={$dbserver}; dbname={$database}; charset=utf8",$username,$password);
| a59e5d3fbc520703afe2fe15df8ad1b18f438fbd | [
"JavaScript",
"Text",
"PHP",
"Shell"
] | 15 | PHP | Nonju/WebbShop | 18c54bbc1181ed6f779101983e7d3e15864372d8 | a960a95b31f50711f0f685c656c3b9e7f826a532 |
refs/heads/main | <repo_name>erumd/PedaGogue<file_sep>/controllers/index.js
const router = require('express').Router();
// const { Post } = require('../models');
// const { User } = require('../models');
const apiRoutes = require('./api');
const userRoutes = require('../controllers/api/userRoutes');
router.use('/', apiRoutes);
router.use('/', userRoutes);
// router.get('/', (req, res) =>
// res.send('Pedagogue Under Construction. Trying to set up Routes ')
// );
module.exports = router;
<file_sep>/README.md
# Project 2 Proposal
[](https://opensource.org/licenses/MIT)
## Description
As a group of developers with strong ties to education, we chose to create an application that solves one of the main problems within this industry, "who teaches the teachers?". Teachers everywhere need more resources, and new teachers need help with concepts and situations that may come easier for seasoned professionals. Our application solves this problem by giving teachers a safe space to ask teacher questions and receive answers that only a fellow teacher would know. Educators will be able to post questions and respond to questions based on pre-generated categories." " is a free, social application to share our united teacher knowledge.
## Table of Contents (Optional)
If your README is very long, add a table of contents to make it easy for users to find what they need.
- [Deployment](#deployment)
- [Installation](#installation)
- [User Story](#userStory)
- [Credits](#credits)
- [Resources](#resources)
- [License](#license)
## Deployment
https://github.com/erumd/Project2-repository
Heroku Deployment:
https://pedagu-gu.herokuapp.com/profile
## Installation
1. After cloning repo to your device in terminal run "npm install"
2. Open up SQL Workbench and run the db files pedagogue_db.sql.
3. In .envEXAMPLE file set up your connection (database, username, password).
4. Rename .envEXAMPLE to ".env"
5. Open terminal and locate the folder
6. In terminal command line run "npm start"
## User Story
AS A teacher/ instructor
I WANT a place to find resources and advice for me
SO THAT I am more successful in the classroom
## Credits
This project will be completed by
[Jasmine] (https://github.com/jasdjames)
[Erum] (https://github.com/erumd)
[Quincy] (https://github.com/Q-Jones92)
[Michael] (https://github.com/mrllanes)
## Resources
[Random Background](https://stackoverflow.com/questions/18288950/random-fullscreen-background-image-on-browser-refresh)
## License
MIT License
Copyright (c) [2021] [JasDJames, erumd, mrllanes, Q-Jones92]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
<file_sep>/projectProposal.md
# Project 2 Proposal
[](https://opensource.org/licenses/MIT)
## Description
As a group of developers with strong ties to education, we chose to create an application that solves one of the main problems within this industry, "who teaches the teachers?". Teachers everywhere need more resources, and new teachers need help with concepts and situations that may come easier for seasoned professionals. Our application solves this problem by giving teachers a safe space to ask teacher questions and receive answers that only a fellow teacher would know. Educators will be able to post questions and respond to questions based on pre-generated categories." " is a free, social application to share our united teacher knowledge.
## Table of Contents (Optional)
If your README is very long, add a table of contents to make it easy for users to find what they need.
- [User Story](#userStory)
- [Credits](#credits)
- [License](#license)
## Installation
## User Story
AS A teacher/ instructor
I WANT a place to find resources and advice for me
SO THAT I am more successful in the classroom
## Credits
This project will be completed by
[Jasmine] (https://github.com/jasdjames)
[Erum] (https://github.com/erumd)
[Quincy] (https://github.com/Q-Jones92)
[Michael] (https://github.com/mrllanes)
## License
MIT License
Copyright (c) [year] [JasDJames]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
## Features
- TBD
## Possible Names
3.) EduKnow
4.) TeachPad
5.) Ask & Assist
8.) Teach-a-Teach
9.) Teach2Teach
### MVP (Minimum Viable Product)
- Make an account
- Post
- Respond
- Category or Search
- UI/UX
- - Socket.io - Websockets / Polling (Live or Instant Chat)
## Stretch Goals
- Socket.io - Websockets / Polling
- Image Uploads
- JSON Blob -> Probably a good way to store the screens people are creating
- Adding Giphy for responses
- Adding Media
- Also a padlet for student interaction / Student Functionality
upload an image -> (S3 Buckets on AWS -> API)
Store the Image URL in Varchar field
## Features
- TBD
## Possible Names
3.) EduKnow
4.) TeachPad
5.) Ask & Assist
8.) Teach-a-Teach
9.) Teach2Teach
### MVP (Minimum Viable Product)
- Make an account
- Post
- Respond
- Category or Search
- UI/UX
- - Socket.io - Websockets / Polling (Live or Instant Chat)
## Stretch Goals
- Socket.io - Websockets / Polling
- Image Uploads
- JSON Blob -> Probably a good way to store the screens people are creating
- Adding Giphy for responses
- Adding Media
- Also a padlet for student interaction / Student Functionality
upload an image -> (S3 Buckets on AWS -> API)
Store the Image URL in Varchar field
<file_sep>/public/js/login.js
const loginFormHandler = async (event) => {
console.log('login form handler ran');
event.preventDefault();
// Collect values from the login form
const username = document.querySelector('#username-login').value.trim();
const password = document.querySelector('#password-login').value.trim();
if (username && password) {
console.log('example, getting login');
// Send a POST request to the API endpoint
const response = await fetch('/users/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: { 'Content-Type': 'application/json' },
});
console.log(response);
if (response.ok) {
// If successful, redirect the browser to the profile page
document.location.replace('/topicList');
} else {
alert(response.statusText);
}
} else {
console.log(
'missing information',
`Username:${username} Email${email} pass:${password}`
);
}
return false;
};
const signupFormHandler = async (event) => {
event.preventDefault();
const name = document.querySelector('#name-signup').value.trim();
const username = document.querySelector('#username-signup').value.trim();
const email = document.querySelector('#email-signup').value.trim();
const password = document.querySelector('#password-signup').value.trim();
// if (name && username && email && password) {
if (name && username && email && password) {
const response = await fetch('/users', {
method: 'POST',
body: JSON.stringify({ name, username, email, password }),
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
document.location.replace('/topicList');
} else {
alert(response.statusText);
}
}
};
console.log(document.querySelector('.login-form'));
document
.querySelector('.login-form')
.addEventListener('submit', loginFormHandler);
document
.querySelector('.signup-form')
.addEventListener('submit', signupFormHandler);
<file_sep>/Todo.md
Things to To Do
1. create log out button on topic page. check to make sure it is there for all pages
(Erum DONE) 2. Topic list : add in 6 topic as button: 1. STEM (Math/Science/Tech) 2. ELA 3. Social Studies 4. Classroom Management (Elementary , Secondary) 5. Electives 6. Free Resources 7. Miscellaneous 8. Parent Communication
3. Fix route on profile page. Drop downdown for the topics instead of Post Number
4. Comments get put into the correct topic page
5. Dropdown menu of topic to add comments
6. Add images.
7. Hover over image comment
8.
<file_sep>/Worklogs/Erum-Worklog.md
# <NAME>
## Saturday March 27, 2021
Presentation day. Practiced presentations before class.
## Friday March 26, 2021
Added Post for each topic. Delete button now working
## Thursday March 26, 2021
Big merge error. having hard time refershing after
## Tuesday March 23, 2021
## Monday March 22, 2021
Worked on redirecting user to homepage after login. Routes and login
## Sat March 20 2021
As a group got routers to work, got login and signup page to work.
## Fri March 19 2021
Read up on socketio for chat feature.
## Thu Mar 18 2021
Worked on HW
## Wed Mar 17 2021
Class. Worked as a group to add in files. Prettier and Linx
I set up the routes and it worked on the sever. I deployed to Heroku and set up GitHub on SLACK.
## Tue Mar 16 2021
Gathered ideas and researched on npm packages, https://knockoutjs.com/, &
https://stimulus.hotwire.dev/
## Mon Mar 15 2021
Group Work: Created Repo, readme, project name, sand listed resources to read up
<file_sep>/db/schema.sql
-- DROP DATABASE
DROP DATABASE IF EXISTS pedagogue_db;
-- CREATE DATABASE
CREATE DATABASE pedagogue_db;
<file_sep>/config/connection.js
// This is cleaner, learn this instead
const Sequelize = require("sequelize");
require("dotenv").config();
const connectionURI =
process.env.JAWSDB_URL ||
`mysql://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:3306/${process.env.DB_NAME}`;
const sequelize = new Sequelize(connectionURI);
module.exports = sequelize;
<file_sep>/models/index.js
const User = require('./User');
const Topic = require('./Topic');
const Comment = require('./Comment');
Topic.hasMany(Comment, {
foreignKey: 'topic_id',
onDelete: 'CASCADE',
});
module.exports = { User, Topic, Comment };
<file_sep>/Worklogs/jasWorklog.md
# <NAME>
## Thu Mar 18 2021
Could not work on the project due to prior engagements
## Wed Mar 17 2021
Moved project proposal to readME
Meeting during class - Worked on HTML which will become part of the template (HandleBars)
## Tue Mar 16 2021
Read Handlebars.js, sessions documentation, reviewed past projects to prepare for this project
## Mon Mar 15 2021
Group Work: Created Repo, readme, project name, sand listed resources to read up
| 948c31f1d08b7c4c5e31ad27f3e310e2b1517b5f | [
"JavaScript",
"SQL",
"Markdown"
] | 10 | JavaScript | erumd/PedaGogue | 52216388121201d6d842ec0d35abb7f7ffdb5289 | 8d23869c4548eae39d0fcbc687248d4685f773d8 |
refs/heads/master | <file_sep>import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import *
HOMEPAGE = "http://www.scotiabank.com/jm/en/0,,27,00.html"
LOGIN_PAGE = \
"https://www1.online.scotiabank.com/onlineV1/leap/signon/signOn.xhtml?" \
"country=JAM&lang=en&channel=WEB"
chrome_options = Options()
class ScotiaBankSite(object):
PAGE_LOGIN = 'login'
PAGE_SECURITY_QUESTION = 'security-question'
PAGE_ACCOUNTS = 'accounts'
PAGE_ACCOUNT = 'account'
def __init__(self):
self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.login_page = LoginPage(self.driver)
self.accounts_page = AccountsPage(self.driver)
self.account_page = AccountPage(self.driver)
self.current_page = ScotiaBankSite.PAGE_LOGIN
def login(self, account_number=None, password=None):
""" Logs in to the website. Raises an exception if login fails
:param str account_number - the account number
:param str password - the <PASSWORD> for the account
"""
result = self.login_page.login(
account_number=account_number, password=<PASSWORD>)
self.current_page = ScotiaBankSite.PAGE_SECURITY_QUESTION
return result
def get_security_question(self):
""" Returns the security question on the page
"""
return self.login_page.get_security_question()
def answer_security_question(self, answer):
result = self.login_page.answer_security_question(answer)
self.current_page = ScotiaBankSite.PAGE_ACCOUNTS
return result
def get_accounts(self):
return self.accounts_page.get_accounts()
def get_transactions(self, branch_code=None, account_number=None):
self.accounts_page.go_to_account(
branch_code=branch_code,
account_number=account_number)
return self.account_page.get_transactions(
branch_code=branch_code, account_number=account_number)
class BasePage(object):
def __init__(self, driver=None):
self.driver = driver
class LoginPage(BasePage):
""" An ecanpsulation of the login page, allows us to do just that.. login
"""
LOGIN_ERROR_SELECTOR = "span.alert-msg"
SECURITY_QUESTION_INPUT = "#contentForm .RUIFW-form-el"
ANSWER_SECURITY_QUESTION_BUTTON = "#contentForm .RUIFW-btn-primary"
def login(self, account_number=None, password=<PASSWORD>):
""" Logs in to the website using an account number and password
"""
self.driver.get(LOGIN_PAGE)
self.try_to_login(
account_number=account_number, password=<PASSWORD>)
if self.is_logged_in():
print("Logged in successfully")
return True
login_error = self.get_login_error()
self.driver.close()
raise Exception(login_error)
def try_to_login(self, account_number=None, password=None):
""" Attempt login
"""
self.driver.find_element_by_id(
"contentForm:nscard").send_keys(account_number)
self.driver.find_element_by_id(
"contentForm:pwdnMasked").send_keys(<PASSWORD>)
print("Logging In")
self.driver.find_element_by_id("contentForm:signIn").click()
def is_logged_in(self):
""" Tells us if login was successful
"""
return "Security question" in self.driver.page_source
def get_login_error(self):
""" Returns the login error on the page
"""
span = self.driver.find_element_by_css_selector(
LoginPage.LOGIN_ERROR_SELECTOR)
return span.text
def get_security_question(self):
question = self.driver.find_element_by_css_selector(
".RUIFW-col-12 span").text
return question
def answer_security_question(self, answer):
print("Entering answer")
self.driver.find_element_by_css_selector(
LoginPage.SECURITY_QUESTION_INPUT).send_keys(answer)
print("Submitting answer")
self.driver.find_element_by_css_selector(
LoginPage.ANSWER_SECURITY_QUESTION_BUTTON).click()
print("Checking for errors")
error_message = self.get_security_question_error()
if error_message:
raise Exception(error_message)
return True
def get_security_question_error(self):
try:
message = \
self.driver.find_element_by_css_selector(
LoginPage.LOGIN_ERROR_SELECTOR).text
return message
except NoSuchElementException as e:
return ''
class AccountsPage(BasePage):
ACCOUNT_NUMBER_REGEX = \
r'(?P<account_name>.*) \- (?P<branch_code>[0-9]+) ?(?P<account_number>[0-9]+)'
def get_accounts(self):
""" Returns a list of the accounts on the page
"""
WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, "td.account-type")))
accounts = []
elements = self._get_account_elements()
for element in elements:
balance = self._get_account_balance(element)
name = self._get_account_name(element)
account_number = self._get_account_number(element)
branch_code = self._get_branch_code(element)
accounts.append({
"name": name,
"balance": balance,
"account_number": account_number,
"branch_code": branch_code,
})
return accounts
def _get_account_elements(self):
""" Returns the list of elements containing our accounts
"""
return self.driver.find_elements_by_css_selector("td.account-type")
def _get_account_name(self, element):
text = element.text.strip().replace("\n", "")
match = \
re.match(AccountsPage.ACCOUNT_NUMBER_REGEX, text)
name = match.group('account_name')
return name
def _get_account_balance(self, element):
parent = element.find_element_by_xpath('..')
balance = parent.find_element_by_css_selector(
".balance").text
return balance
def _get_branch_code(self, element):
text = element.text.strip().replace("\n", "")
match = \
re.match(AccountsPage.ACCOUNT_NUMBER_REGEX, text)
branch_code = match.group('branch_code')
return branch_code
def _get_account_number(self, element):
text = element.text.strip().replace("\n", "")
match = \
re.match(AccountsPage.ACCOUNT_NUMBER_REGEX, text)
account_number = match.group('account_number')
return account_number
def go_to_account(self, branch_code=None, account_number=None):
""" Goes to the account details page for the given account
"""
print("Going to account page for: {} {}".format(
branch_code, account_number))
for element in self._get_account_elements():
if self._get_branch_code(element) == branch_code and \
self._get_account_number(element) == account_number:
a = element.find_element_by_tag_name("a")
print("Clicking on {}".format(a.text))
a.click()
self.current_page = ScotiaBankSite.PAGE_ACCOUNT
return
raise Exception(
"Could not find account page for {} {}".format(
branch_code, account_number))
class AccountPage(BasePage):
DATE_LIST_SELECTOR_ID = "transDetailsForm:date_list"
TRANSACTIONS_TABLE_ID = "transDetailsForm:current"
def get_transactions(self, branch_code=None, account_number=None):
""" Returns the list of transactions on the page
"""
self.select_this_month_transactions()
transactions = self._get_transasctions_from_table()
return transactions
def select_this_month_transactions(self):
""" This selects this months' transactions from the drop down on
the account details page
"""
element = self.driver.find_element_by_id(
AccountPage.DATE_LIST_SELECTOR_ID)
options = element.find_elements_by_tag_name("option")
for option in options:
if option.text.strip() == "This Month":
option.click()
def _get_transasctions_from_table(self):
transactions = []
table = self.driver.find_element_by_id(
AccountPage.TRANSACTIONS_TABLE_ID)
trs = table.find_elements_by_tag_name("tr")
for tr in trs:
tds = tr.find_elements_by_tag_name("td")
print("Found {} tds in {}".format(len(tds), tr.text))
if len(tds) >= 3:
date = tds[0].text.strip()
description = tds[1].text.strip()
amount = tds[3].text.strip()
transactions.append({
"date": date,
"description": description,
"amount": amount
})
return transactions
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Login from '@/components/Login'
import SecurityQuestion from '@/components/SecurityQuestion'
import Accounts from '@/components/Accounts'
import Account from '@/components/Account'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/security-question',
name: 'SecurityQuestion',
component: SecurityQuestion
},
{
path: '/accounts',
name: 'Accounts',
component: Accounts
},
{
path: '/account/:branchCode/:accountNumber',
name: 'Account',
component: Account
}
]
})
<file_sep>import json
import uuid
from tornado import websocket
from scotia import ScotiaBankSite
SITES = {}
class ScotiaBankSocketHandler(websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
super(ScotiaBankSocketHandler, self).__init__(*args, **kwargs)
self.scotiabank = ScotiaBankSite()
def open(self):
print("We have a connection")
self.send_session_key()
def on_message(self, message):
""" This parses the message receives as JSON then calls a
handle_xxx method based on the message type.
"""
print("Got message: {}".format(message))
message = json.loads(message)
message_type = message.get("messageType")
params = message.get("params") or {}
func_name = "handle_{}".format(message_type.replace("-", "_"))
func = getattr(self, func_name)
func(**params)
def handle_login(self, **params):
""" Callback executed when we receive a message of type 'login'
"""
account_number = params.get("account_number")
password = params.get("password")
print("Logging in with account {}".format(account_number))
try:
self.scotiabank.login(account_number, password)
self.send_message({
'messageType': 'login-success'
})
except Exception as e:
login_error = e.message
self.send_message({
'messageType': 'login-failed',
'params': {
'message': login_error
}
})
def handle_session_key(self, **params):
key = params.get("key")
if key in SITES:
self.scotiabank = SITES.get(key)
else:
SITES[key] = self.scotiabank
def handle_request_session_key(self):
key = str(uuid.uuid4())
self.send_message({
'messageType': 'session-key',
'params': {
'key': key
}
})
def handle_request_security_question(self):
""" Sends the security question over the wire to the customer
"""
question = self.scotiabank.get_security_question()
self.send_message({
'messageType': 'security-question',
'params': {
'security-question': question
}
})
def handle_security_question_answer(self, **params):
""" This is called when we receive a message of type handle answer
security question
"""
answer = params.get("answer")
try:
self.scotiabank.answer_security_question(answer)
self.send_message({
'messageType': 'security-question-correct',
})
except Exception as e:
print(e)
error_message = e.message
self.send_message({
'messageType': 'security-question-incorrect',
'params': {
'message': error_message
}
})
def handle_get_accounts(self):
""" Returns a list of accounts
"""
accounts = self.scotiabank.get_accounts()
self.send_message({
'messageType': 'account-list',
'params': {
'accounts': accounts
}
})
def handle_get_current_page(self):
self.send_message({
'messageType': 'current-page',
'params': {
'page': self.scotiabank.current_page
}
})
def send_message(self, obj):
""" Encodes a message as a JSON string then sends it
"""
self.write_message(json.dumps(obj))
def on_close(self):
print("Socket closed")
def check_origin(self, origin):
""" Allows connections from outside of our origin
"""
return "localhost" in origin
<file_sep>var API_BASE = 'ws://localhost:3000'
var WEBSOCKET_URL = API_BASE + '/ws'
const socket = new WebSocket(WEBSOCKET_URL)
export default function sendMessage (data) {
console.log('Socket send: ', JSON.stringify(data))
if (socket.readyState === 0) {
socket.onopen = () => {
socket.send(JSON.stringify(data))
}
} else {
socket.send(JSON.stringify(data))
}
}
function setupSocket (vm, callback) {
socket.addEventListener('message', function (event) {
console.log('Socket receive: ', event.data)
let obj = JSON.parse(event.data)
vm.$emit('socketMessage', obj)
callback(obj)
})
}
export { sendMessage, socket, setupSocket }
<file_sep>import os
from tornado import web, ioloop
from websocket import ScotiaBankSocketHandler
WEB_SERVER_PORT = 3000
BASE_DIR = os.path.abspath(os.path.dirname("."))
class MainHandler(web.RequestHandler):
def get(self):
print("Loading main page")
return self.render("templates/index.html")
if __name__ == "__main__":
print("Starting up ...")
options = {
'debug': True,
'compiled_template_cache': False,
}
application = web.Application([
(r"/", MainHandler),
(r"/ws", ScotiaBankSocketHandler),
# static files
(r"/static/(.*)", web.StaticFileHandler, {"path": os.path.join(BASE_DIR, "static")})
], **options)
print("Running web server on {}".format(WEB_SERVER_PORT))
application.listen(WEB_SERVER_PORT, address="localhost")
ioloop.IOLoop.current().start()
| e3f710a3349d82f073dd72ebbaa13bee2a4a4054 | [
"JavaScript",
"Python"
] | 5 | Python | jaywhy13/scotiabank-transaction-parser | 4ab2737a4cedd0ef6a4dbd1aa0733960c83ab788 | 72a3f2bb17ae3a63e4a156b8115f83f94203157f |
refs/heads/dev | <repo_name>Warkingg/ClothingStoreProject<file_sep>/src/main/java/com/example/clothingstoreprojectteam/model/Product.java
package com.example.clothingstoreprojectteam.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@Table(name="products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private float price;
private int quantity;
private String size;
private String description;
private String imgUrl;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@ManyToOne
@JoinColumn(name="customer_id")
private Customer customer;
@ManyToOne
@JoinColumn(name="category_id")
private Category category;
}
<file_sep>/settings.gradle
rootProject.name = 'ClothingStoreProjectTeam'
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/model/CartItem.java
package com.example.clothingstoreprojectteam.model;
import javax.persistence.*;
import java.util.List;
public class CartItem {
//private final Product product;
private int quantity;
private float subTotal;
public Product getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getSubTotal() {
subTotal = product.getPrice() * quantity;
return subTotal;
}
public void setSubTotal(float subTotal) {
this.subTotal = subTotal;
}
public CartItem(Product product) {
this.product = product;
this.quantity = 1;
this.subTotal = product.getPrice();
}
@ManyToOne
@JoinColumn(name="customer_id")
private Customer customer;
@OneToOne
@JoinColumn(name = "product_id")
private final Product product;
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/service/category/ICategoryService.java
package com.example.clothingstoreprojectteam.service.category;
import com.example.clothingstoreprojectteam.model.Category;
import com.example.clothingstoreprojectteam.service.IGeneralService;
public interface ICategoryService extends IGeneralService<Category> {
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/repository/ICustomerRepository.java
package com.example.clothingstoreprojectteam.repository;
import com.example.clothingstoreprojectteam.model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ICustomerRepository extends JpaRepository<Customer,Long> {
Customer findByUsername(String userName);
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/service/product/IProductService.java
package com.example.clothingstoreprojectteam.service.product;
import com.example.clothingstoreprojectteam.model.Category;
import com.example.clothingstoreprojectteam.model.Product;
import com.example.clothingstoreprojectteam.service.IGeneralService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface IProductService extends IGeneralService<Product> {
Page<Product> findAllByNameContaining(String name, Pageable pageable);
Page<Product> findAllProductByNameUsingQuery(String name,Pageable pageable);
Page<Product> findAllByCategory(Category category, Pageable pageable);
Product get(Long id);
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/service/Customer/ICustomerService.java
package com.example.clothingstoreprojectteam.service.Customer;
import com.example.clothingstoreprojectteam.model.Customer;
import com.example.clothingstoreprojectteam.service.IGeneralService;
import org.springframework.security.core.userdetails.UserDetailsService;
public interface ICustomerService extends IGeneralService<Customer>, UserDetailsService {
Customer findByUsername(String username);
}
<file_sep>/src/main/resources/static/js/remove.js
function remove(id){
id = id.slice(2)
$.ajax({
url: '/cart/remove/' + id,
type: 'GET',
success: function (data) {
let ele = document.getElementById('rm' + id);
ele.parentElement.parentElement.remove();
}
})
}<file_sep>/src/main/resources/static/js/cart.js
function increase (id) {
id = id.slice(3)
$.ajax({
url: '/cart/update/' + id,
type: 'GET',
success: function (data) {
let ele = document.getElementById('qtn' + id);
ele.innerHTML = data.quantity;
let ele2 = document.getElementById('st' + id);
ele2.innerHTML = data.subTotal;
}
})
}
function increase2 (id) {
id = id.slice(3)
$.ajax({
url: '/cart/update2/' + id,
type: 'GET',
success: function (data) {
let ele = document.getElementById('qtn' + id);
ele.innerHTML = data.quantity;
let ele2 = document.getElementById('st' + id);
ele2.innerHTML = data.subTotal;
}
})
}<file_sep>/src/main/java/com/example/clothingstoreprojectteam/model/Cart.java
package com.example.clothingstoreprojectteam.model;
import lombok.Data;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
public class Cart {
private final List<CartItem> items;
private float total;
public Cart (){
items = new ArrayList<CartItem>();
total = 0;
}
public CartItem getItem(Product p){
for (CartItem item :items){
if (item.getProduct().getId() == p.getId()){
return item;
}
}
return null;
}
public List<CartItem> getItems(){
return items;
}
public int getItemCount(){
return items.size();
}
public void addItem(CartItem item){
addItem(item.getProduct(), item.getQuantity());
}
//add item
public void addItem(Product p , int quantity){
CartItem item = getItem(p);
if (item!= null){
item.setQuantity(item.getQuantity()+quantity);
}else {
item = new CartItem(p);
item.setQuantity(quantity);
items.add(item);
}
}
//sua sp
public void updateItem(Product p , int quantity){
CartItem item = getItem(p);
if(item!= null){
item.setQuantity(quantity);
}
}
//xoa sp
public void removeItem(Product p ){
CartItem item = getItem(p);
if(item!= null){
items.remove(item);
}
}
//xoa tat ca sp
public void clear(){
items.clear();
total = 0;
}
public boolean isEmpty() {
return items.isEmpty();
}
public double getTotal() {
total = 0;
for (CartItem item : items) {
total += item.getSubTotal();
}
return total;
}
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/service/cart/CartService.java
package com.example.clothingstoreprojectteam.service.cart;
import com.example.clothingstoreprojectteam.model.Cart;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
@Service
public class CartService {
private static final String SESSION_KEY_SHOPPING_CART="giohang";
public Cart getCart(HttpSession session){
Cart cart = (Cart) session.getAttribute(SESSION_KEY_SHOPPING_CART);
if (cart == null){
cart = new Cart();
setCart(session , cart);
}
return cart;
}
public void setCart(HttpSession session, Cart cart){
session.setAttribute(SESSION_KEY_SHOPPING_CART, cart);
}
public void removeCart(HttpSession session){
session.removeAttribute(SESSION_KEY_SHOPPING_CART);
}
}
<file_sep>/src/main/resources/messages_vi_vn.properties
username.empty = userName length min 3 and max 30
username.startsWith = name start with A-Z
password.length = passWord length min 3 and max 12
password.startsWith = passWord start with a-z
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/controller/CustomerController.java
package com.example.clothingstoreprojectteam.controller;
import com.example.clothingstoreprojectteam.model.*;
import com.example.clothingstoreprojectteam.repository.IRoleRepository;
import com.example.clothingstoreprojectteam.service.Customer.ICustomerService;
import com.example.clothingstoreprojectteam.service.Province.IProvinceService;
import com.example.clothingstoreprojectteam.service.Role.IRoleService;
import com.example.clothingstoreprojectteam.service.category.ICategoryService;
import com.example.clothingstoreprojectteam.service.product.IProductService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Controller
public class CustomerController {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ICustomerService iCustomerService;
@Autowired
private IProvinceService iProvinceService;
@Autowired
private IRoleService iRoleService;
@Autowired
private IProductService productService;
@ModelAttribute("username")
public String username(Principal userPrinciple){
if (userPrinciple!=null){
return userPrinciple.getName();
}
return null;
}
@ModelAttribute("customer")
public Customer customer(){
return new Customer();
}
@ModelAttribute("provinces")
public List<Province> provinces(){
return (List<Province>) iProvinceService.findAll();
}
@ModelAttribute("products")
public List<Product> products(){
return (List<Product>) productService.findAll();
}
@GetMapping("/login")
public ModelAndView login(){
return new ModelAndView("login");
}
@GetMapping("/shop")
public String shop(){
return "shop";
}
@GetMapping("/")
public ModelAndView home(){
return new ModelAndView("shop");
}
@PostMapping("register")
public ModelAndView register(@Validated @ModelAttribute Customer customer,BindingResult bindingResult){
new Customer().validate(customer,bindingResult);
ModelAndView modelAndView;
if (bindingResult.hasFieldErrors()){
modelAndView = new ModelAndView("login");
}else {
if (iCustomerService.findByUsername(customer.getUsername()) == null) {
customer.setPassword(passwordEncoder.encode(customer.getPassword()));
Set<Role> roles = new HashSet<>();
roles.add(iRoleService.findById(1L).get());
customer.setRoleSet(roles);
iCustomerService.save(customer);
modelAndView = new ModelAndView("shop");
} else {
modelAndView = new ModelAndView("login");
}
}
return modelAndView;
}
@PostMapping("signIn")
public String login(@ModelAttribute Customer customer , Model model){
Customer checkCustomer = iCustomerService.findByUsername(customer.getUsername());
if (checkCustomer.getUsername().equals(customer.getUsername())){
if (passwordEncoder.matches(customer.getPassword(),checkCustomer.getPassword())){
return "redirect:/shop";
}
}
return "login";
}
@GetMapping("/user/information")
public ModelAndView users( @ModelAttribute("username") String username, ModelAndView modelAndView){
if (username != null) {
Customer customer = iCustomerService.findByUsername(username);
modelAndView = new ModelAndView("information");
modelAndView.addObject("informationCustomer", customer);
return modelAndView;
}
return new ModelAndView("login");
}
@PostMapping("user/edit")
public String edit(@Validated @ModelAttribute Customer customer){
iCustomerService.save(customer);
return "redirect:/user/information";
}
}
<file_sep>/src/main/java/com/example/clothingstoreprojectteam/service/Role/RoleService.java
package com.example.clothingstoreprojectteam.service.Role;
import com.example.clothingstoreprojectteam.model.Role;
import com.example.clothingstoreprojectteam.repository.IRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class RoleService implements IRoleService{
@Autowired
private IRoleRepository iRoleRepository;
@Override
public Iterable<Role> findAll() {
return iRoleRepository.findAll();
}
@Override
public Page<Role> findAll(Pageable pageable) {
return iRoleRepository.findAll(pageable);
}
@Override
public Role save(Role role) {
return iRoleRepository.save(role);
}
@Override
public Optional<Role> findById(Long id) {
return iRoleRepository.findById(id);
}
@Override
public void remove(Long id) {
iRoleRepository.deleteById(id);
}
}
| 7e13841d4175b2c49bf94385c4d9974f62843e18 | [
"JavaScript",
"Java",
"INI",
"Gradle"
] | 14 | Java | Warkingg/ClothingStoreProject | 3c9de4c645e9c59e999e3292966b45476118a9c8 | 840e333477b452180a0b3ec327f16fd8a4cb057a |
refs/heads/master | <repo_name>tenhold/home-mixologist-2<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowerRouter as Router, Route } from 'react-router-dom';
import { thisExpression, throwStatement } from '@babel/types';
import axios from 'axios';
import DrinkForm from './components/drinkForm';
import DrinkList from './components/drinkList';
import { drinks } from '../data.json';
const getCocktails = require('../database/helpers/api');
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
username: '',
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSearch = this.handleSearch.bind(this);
}
componentDidMount() {
// get all the users in the database and update the state array with the users
axios.get('http://localhost:8080/users')
.then(res => {
const { data } = res;
this.setState({
users: data
});
})
.catch((err) => console.log('GET error in mount'))
}
displayName() {
}
handleChange(e) {
this.setState({
username: e.target.value
});
}
handleSearch(username) {
// posting the server not to the database adding username to database
axios.post(`http://localhost:8080/users/add`, { username: username.toLowerCase() })
.then(data => {
const { data: { username } } = data;
this.setState(prevState => ({
users: [...prevState.users, data],
username: username
}))
})
.catch(err => console.log('ERROR in handleSearch', err));
}
handleClick() {
console.log(this.state.username)
const { username } = this.state;
this.handleSearch(username);
// this.setState({
// username: ''
// });
}
render() {
const { username } = this.state;
return (
<div>
<div style={{ display: 'flex', justifyContent: 'center' }}>
{!username ? <h1>Sign in</h1> :
<h1>Welcome {username}!</h1>}
</div>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<form>
<input value={username} onChange={this.handleChange}></input>
<button onClick={this.handleClick} type='button'>log in</button>
</form>
</div>
<div>
</div>
<DrinkForm user={username} />
</div>
);
}
}
// const App = () => {
// return (
// <div>
// <DrinkForm />
// </div>
// // <Router>
// // <Route path='/' exact componet={DrinkForm} />
// // </Router>
// );
// };
ReactDOM.render(<App />, document.getElementById('app'));
// handleChange(e) {
// this.setState({
// username: e.target.value
// });
// }
// handleSearch(username) {
// // posting the server not to the database adding username to database
// axios.post(`http://localhost:8080/users/add`, { username })
// .then(data => {
// console.log(data);
// })
// .catch(err => console.log('ERROR in handleSearch', err));
// }
// handleClick() {
// console.log(this.state.username)
// const { username } = this.state;
// this.handleSearch(username);
// this.setState({
// username: ''
// });
// }
// render() {
// const { username } = this.state;
// return (
// <div>
// <div>Hello World</div>
// <div>
// <form>
// <input value={username} onChange={this.handleChange}></input>
// <button onClick={this.handleClick} type='button'>log in</button>
// </form>
// </div>
// <DrinkForm onChange={this.handleSearh}/>
// </div>
// );
// }<file_sep>/database/helpers/api.js
const axios = require('axios');
// const { DRINKS_TOKEN } = process.env;
function getCocktails(liquor) {
/*
pass in the info from the api to get the drink
*/
const options = {
method: 'get',
url: `https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${liquor}`,
}
return axios(options);
}
// function filterDrinks(drinkObj) {
// return drinkObj.map(drink => {
// const { strDrink, strInstructions, strDrinkThumb, strIngredient1, strIngredient2 } = drink;
// return {
// name: strDrink,
// liquor: [strIngredient1, strIngredient2],
// image: strDrinkThumb,
// instructions: strInstructions,
// };
// });
// }
module.exports = {
getCocktails,
};<file_sep>/database/models/drinks.model.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const drinkSchema = new Schema({
name: {
type: String,
unique: true
},
image: String,
alcohol: String,
userId: String,
rating: {
type: String,
default: null
}
});
const Drink = mongoose.model('Drink', drinkSchema);
module.exports = Drink;<file_sep>/database/routes/drinks.js
const router = require('express').Router();
const Drink = require('../models/drinks.model');
const { route } = require('./users');
// const { drinks } = require('../../data.json');
router.route('/').get((req, res) => {
Drink.find()
.then(drink => res.status(200).send(drink))
.catch(err => {
console.log('GET ERROR:', err);
res.sendStatus(404);
});
});
router.route('/add').post((req, res) => {
const { name, image, alcohol, userId } = req.body;
const newDrink = new Drink({ name, image, alcohol, userId });
newDrink.save()
.then(() => {
res.status(201).send(newDrink)
})
.catch(err => {
console.log('POST DRINK ERROR: ', err);
res.sendStatus(404);
})
})
router.route('/:name').delete((req, res) => {
const { name } = req.params
console.log(name)
Drink.findOneAndDelete({ name })
.then(drink => {
drink ? res.status(200).send(drink) : res.sendStatus(404);
})
.catch(() => res.sendStatus(500));
})
router.route('/:name').put((req, res) => {
const { name } = req.params;
Drink.findOneAndUpdate({ name }, {rating: 'favorited!'})
.then(() => {
// drink.rating = 'favorited!';
// console.log(drink.rating, 'put request!')
res.status(200).send();
})
.catch(() => res.sendStatus(500));
})
module.exports = router;
//////////////////// mock up of return array //////////////////////////////
// const drinkName = drinks.map(drink => {
// const { strDrink, strInstructions, strDrinkThumb, strIngredient1, strIngredient2 } = drink;
// return {
// drink: strDrink,
// liquor: [strIngredient1, strIngredient2],
// image: strDrinkThumb,
// instructions: strInstructions,
// };
// });
// console.log(drinkName);
//////////////////////////////////////////////////////////////////////////////////////////////
<file_sep>/PRESS_RELEASE.md
# Project Name
## Heading
## Name the product in a way the reader (i.e. your target customers) will understand.
Home Mixologist
### Sub-Heading
Make your favorite cocktails at home!
## Describe who the market for the product is and what benefit they get. One sentence only underneath the title.
Young city slickers that miss the enjoyment of craft cocktails at there favoirte bar.
# Summary
## Give a summary of the product and the benefit. Assume the reader will not read anything else so make this paragraph good.
With covid-19 making most bars shutter in place how are you able to enjoy your favorite craft cocktail at 5 o'clock on a friday? Our site gives you a one stop shop access to all your favoite drinks in an easy to follow step by set instructions, with pictures.
# Problem
## Describe the problem your product solves.
The craft cocktail scene has exploided in the last few years and people are willing to experiment more with cocktails, with most bars closed around the country our site allows people to look up some of their favoirite cocktails and how to make them.
# Solution
## Describe how your product elegantly solves the problem.
Our site has an easy search bar that connects to our database. You can search for a spirit and will get a list of the top drinks that can be made.
# Quote from You
## A quote from a spokesperson in your company.
"It's never been easier to whip up an old fashioned at home!"
# How to Get Started
## Describe how easy it is to get started.
open the app, see a list of your saved drinks or start typing to find your next favorite cocktail.
# Customer Quote
## Provide a quote from a hypothetical customer that describes how they experienced the benefit.
# Closing and Call to Action
## Wrap it up and give pointers where the reader should go next.<file_sep>/src/components/drinkList.js
// import React from 'react';
// const DrinkList = (drinks) => {
// if (drinks) {
// return (
// <ul>
// hello
// </ul>
// )
// }
// };
// export default DrinkList; | de4ab8df86698970268d3d8e7bf265dec8169252 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | tenhold/home-mixologist-2 | a8d587450e380293e2f500cfd12b07837de19799 | 703a45b3cdc5b273458182f20a7dd9e361e1f786 |
refs/heads/main | <file_sep>#include <M5Stack.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
const char* ssid = "Wifi_SSID";
const char* password = "<PASSWORD>";
WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "hello from M5Stack!");
M5.Lcd.println("accessed on root");
}
void handleNotFound() {
server.send(400, "text/palin", "File Not Found");
M5.Lcd.println("File Not Found");
}
void setup() {
M5.begin();
M5.Lcd.setTextSize(2);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
M5.Lcd.print('.');
}
M5.Lcd.println("");
M5.Lcd.println("WiFi Connected");
M5.Lcd.print("IP address: ");
M5.Lcd.println(WiFi.localIP());
if (MDNS.begin("m5stack")) {
M5.Lcd.println("MDNS responder startted");
}
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
M5.Lcd.println("HTTP server started");
}
void loop() {
server.handleClient();
}
<file_sep>#include <M5StickC.h>
void setup() {
M5.begin();
M5.Lcd.setRotation(3);
M5.Lcd.setCursor(0,0,2);
M5.Lcd.print("Hello World");
}
void loop() {
}
<file_sep>#include <M5Stack.h>
#define LM61BIZ_PIN 35
void setup() {
M5.begin();
pinMode(LM61BIZ_PIN, INPUT);
M5.Lcd.setTextSize(4);
}
void loop() {
int e = analogRead(LM61BIZ_PIN);
float Vout = e / 4095.0 * 3.3 + 0.1132;
float temp = (Vout - 0.6) / 0.01;
M5.Lcd.setCursor(80, 100);
M5.Lcd.print(temp, 1);
M5.Lcd.print("'C");
delay(1000);
}
<file_sep>#include <M5Stack.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#define REPORTING_PERIOD_MS 1000
const int HEART_RATE_HISTORY = 150;
PulseOximeter pox;
int heartRate[HEART_RATE_HISTORY];
uint32_t tsLastReport = 0;
void onBeatDetected()
{
// Serial.println("Beat!");
}
void setup() {
M5.begin();
M5.Lcd.setTextSize(2);
if (!pox.begin()) {
M5.Lcd.println("PulseOximeter is not Started.");
Serial.println("PulseOximeter is not Started.");
for(;;);
}
pox.setOnBeatDetectedCallback(onBeatDetected);
for (int x = 0; x < HEART_RATE_HISTORY; x++) {
heartRate[x] = 0;
}
}
int getX(int i) {
return i * 2;
}
int getY(int i) {
return 200 - (heartRate[i] * 2);
}
void loop() {
pox.update();
int oldX = getX(0);
int oldY = getY(0);
for (int x = 0; x < HEART_RATE_HISTORY - 1; x++) {
M5.Lcd.drawLine(oldX, oldY, getX(x+1), getY(x+1), TFT_BLACK);
oldX = getX(x + 1);
oldY = getY(x + 1);
heartRate[x] = heartRate[x + 1];
}
heartRate[HEART_RATE_HISTORY - 1] = pox.getHeartRate();
for (int x = 0; x < HEART_RATE_HISTORY - 1; x++) {
M5.Lcd.drawLine(getX(x), getY(x), getX(x+1), getY(x+1), TFT_DARKGREEN);
}
if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
M5.Lcd.setCursor(5, 200); M5.Lcd.printf("Heart rate: %3.2fbpm ", pox.getHeartRate());
M5.Lcd.setCursor(5, 220); M5.Lcd.printf("SpO2 : %3d %%", pox.getSpO2());
tsLastReport = millis();
}
}
<file_sep>#include <M5Stack.h>
#include <IRrecv.h>
#include <IRutils.h>
#define SERIAL_BAUD_RATE 11520
const uint16_t IR_RECEIVE_PIN = 22;
const uint16_t IR_SAEND_PIN = 21;
const uint16_t kCaptureBufferSize = 1024;
const uint8_t kTimeout = 50;
IRrecv irrecv(IR_RECEIVE_PIN, kCaptureBufferSize, kTimeout, true);
void setup() {
M5.begin();
irrecv.enableIRIn();
M5.Lcd.setTextSize(2);
}
void loop() {
decode_results results;
if (irrecv.decode(&results)) {
Serial.print(resultToHumanReadableBasic(&results));
Serial.println(results.command);
}
delay(1);
}
<file_sep>#include <M5StickC.h>
#include <WiFi.h>
#include <WebServer.h>
#include <IRsend.h>
// IR Config
const uint16_t IR_SEND_PIN = GPIO_NUM_9;
// WIFI Config
const char* ssid = "Wifi_SSID";
const char* password = "<PASSWORD>";
WebServer server(80);
IRsend irSend(IR_SEND_PIN);
void handleRoot() {
server.send(200, "text/plain", "hello from M5StickC!");
irSend.send(PANASONIC, 0x555AF148288F, 48, 0);
Serial.println("accessed on root");
}
void handleNotFound() {
server.send(400, "text/palin", "File Not Found");
Serial.println("File Not Found");
}
void setup() {
M5.begin();
irSend.begin();
M5.Lcd.setRotation(3);
M5.Lcd.setTextSize(1);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
M5.Lcd.print('.');
}
M5.Lcd.println("");
M5.Lcd.println("WiFi Connected");
M5.Lcd.print("IP address: ");
M5.Lcd.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
M5.Lcd.println("HTTP server started");
}
void loop() {
server.handleClient();
}
<file_sep>#include <M5Stack.h>
struct ConfigItem {
String key;
String value;
};
class ConfigUtil {
public:
const static int MAX_SIZE_CONFIG = 1000;
ConfigUtil();
void loadConfig(String path);
int size();
String getConfig(String key);
private:
int size_of_config;
ConfigItem configs[MAX_SIZE_CONFIG];
};
<file_sep>#define M5STACK_MPU6886
#include <M5Stack.h>
void setup() {
M5.begin();
M5.IMU.Init();
Wire.begin();
M5.Lcd.setTextSize(2);
}
void loop() {
float accX = 0.0f;
float accY = 0.0f;
float accZ = 0.0f;
M5.IMU.getAccelData(&accX, &accY, &accZ);
M5.Lcd.clear();
M5.Lcd.setCursor(0, 0); M5.Lcd.print("MPU6886 acceleration");
M5.Lcd.setCursor(0, 32); M5.Lcd.printf("X: %7.2f mG", 1000 * accX);
M5.Lcd.setCursor(0, 64); M5.Lcd.printf("Y: %7.2f mG", 1000 * accY);
M5.Lcd.setCursor(0, 96); M5.Lcd.printf("Z: %7.2f mG", 1000 * accZ);
delay(2000);
}
<file_sep>#include <M5Stack.h>
void setup() {
M5.begin();
M5.Lcd.setTextSize(2);
M5.Lcd.printf("Hello World from M5Stack");
}
void loop() {
}
<file_sep>---
marp: true
theme: gaia
paginate: true
header: 'M5Stackを使ってみた'
---
# M5Stackを使ってみた
---
## はじめに
- 本資料は個人使用を目的としています。
- サンプルプログラムは、動作実績のあるプログラムを紙面に合わせて変更しています。紙面のプログラムのままでは挙動しない場合があります。
- 本書で使っている機器やセンサは日本国内ではスイッチサイエンス社にて購入可能です。
---
## M5Stackとは

- 中国深圳のM5Stack社提供
- Arduino互換のマイコン
- ESP32(WiFi/BLE)を搭載
- SDカードスロット搭載
- USB TypeC搭載
- Groveコネクタ搭載
- カラーTFT LCD搭載
- 標準機は¥5,000程度
---
## シングルボードコンピュータ
- M5Stackは、シングルボードコンピュータの一種。
- シングルボードコンピュータとは、単一基盤で構成された自己完結型のコンピュータ
- シングルボードコンピュータには以下のようなものがある
| 製品 | 特徴 |
|:--|:--|
| Raspberry Pi | 英国製。元々は子供向けIT教育用途で開発。 |
| Arduino | 伊発祥。オープンソースのハードウェア。 |
| Jetson | NVIDA。人工知能処理を得意とする。 |
---
## "Raspberry Pi"と"M5Stack"の違い
| Arduino | Rspberry Pi|
|:--|:--|
| ハードウェア寄り | ソフトウェア寄り |
| 自由度は低いが、手軽に扱える | 自由度は高いが、とっつきにくい |
| ハードウェア性能は低め | ハードウェア性能は高め |
| OS搭載なし | RaspberryPiOS(Linux) |を標準搭載
| 開発環境はArduinoIDEで固定 | 開発環境は自由 |
| シングルタスク駆動 | マルチタスク駆動 |
| Simple is best | 安価な小型パソコン |
---
## Hello World

```cpp
#include <M5Stack.h>
void setup() {
M5.begin();
M5.Lcd.setTextSize(2);
M5.Lcd.printf("Hello World from M5Stack");
}
void loop() {
}
```
---
## Lチカ

```cpp
#include <M5Stack.h>
#define LED_PIN 2
void setup() {
M5.begin();
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}
```
---
## アナログ温度センサ(Circuit Diagram)

LM61BIZという温度センサーを使って、温度を測ってみます。
LM61BIZでは、Voutピンに周囲の温度に応じた電圧が出力されます。
---
### アナログ温度センサー(Arduino)
```cpp
#define LM61BIZ_PIN 35
void setup() {
M5.begin();
M5.Lcd.setTextSize(4);
pinMode(LM61BIZ_PIN, INPUT);
}
void loop() {
int e = analogRead(LM61BIZ_PIN);
float Vout = e / 4095.0 * 3.3 + 0.1132;
float temp = (Vout - 0.6) / 0.01;
M5.Lcd.setCursor(80, 100); M5.Lcd.printf("%2.1f'C",temp);
delay(1000);
}
```
---
## GROVE気圧センサ(Circuit Diagram)

BMP280を搭載したGROVEの気圧センサを使って温度と気圧を測ってみます。
GROVEとはseeed studioが開発しているさすだけで扱えるセンサなどのモジュールのことです。
---
## Groveセンサ(Arduino)
```cpp
BMP280 bmp280;
void setup() {
M5.begin();
M5.Lcd.setTextSize(3);
bmp280.init();
}
void loop() {
float bmp280temp = bmp280.getTemperature();
uint32_t pressure = bmp280.getPressure();
float altitude = bmp280.calcAltitude(pressure);
M5.Lcd.setCursor(40, 110); M5.Lcd.printf("Temp: %5.1f'C", bmp280temp);
M5.Lcd.setCursor(40, 150); M5.Lcd.printf("Press: %dhPa", pressure / 100);
M5.Lcd.setCursor(40, 190); M5.Lcd.printf("Alti: %5.2fm", altitude);
}
```
---
## 心拍センサ (CircuitDiagram)

MAX30100を搭載したGROVEの心拍センサ。
内蔵されている赤外線LEDと光センサを用いて、血中酸素濃度と心拍数を測定することが可能。
---
## 心拍センサ(Arduino)
```cpp
PulseOximeter pox;
uint32_t tsLastReport = 0;
void onBeatDetected() {Serial.println("Beat!");}
void setup() {
Serial.begin(115200);
pox.begin();
pox.setOnBeatDetectedCallback(onBeatDetected);
}
void loop() {
pox.update();
if (millis() - tsLastReport > 1000) {
Serial.print("Heart rate:"); Serial.print(pox.getHeartRate());
Serial.print("bpm / SpO2:"); Serial.print(pox.getSpO2());
tsLastReport = millis();
}
}
```
---
## IRセンサ (CircuitDiagram)

赤外線発信器と受信器を搭載したを搭載したGROVEの心拍センサ。
赤外線発信器と受信器の両方を搭載しているので、リモコン信号のエンコードだけでなくデコードも行うことが可能。
---
## IRセンサ:受信(Arduino)
```cpp
#include <IRrecv.h>
#include <IRutils.h>
const uint16_t IR_RECEIVE_PIN = 22;
const uint16_t kCaptureBufferSize = 1024;
const uint8_t kTimeout = 50;
IRrecv irrecv(IR_RECEIVE_PIN, kCaptureBufferSize, kTimeout, true);
void setup() {irrecv.enableIRIn();}
void loop() {
decode_results results;
if (irrecv.decode(&results)) {
Serial.print(resultToHumanReadableBasic(&results));
}
delay(1);
}
```
---
## IRセンサ:発信(Arduino)
```cpp
#include <M5Stack.h>
#include <IRsend.h>
const uint16_t IR_SEND_PIN = 21;
IRsend irSend(IR_SEND_PIN);
void setup() {
M5.begin();
irSend.begin();
irSend.send(PANASONIC, 0x555AF148A887, 48, 0); // Volume down
}
void loop() {}
```
---
## Web Server(Arduino-1)
```cpp
#include <M5Stack.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
const char* ssid = "WiFi-SSID";
const char* password = "<PASSWORD>";
WebServer server(80);
void handleRoot() {server.send(200, "text/plain", "hello from M5Stack!");}
void handleNotFound() {server.send(400, "text/palin", "File Not Found");}
```
---
## Web Server(Arduino-2)
```cpp
void setup() {
M5.begin();
M5.Lcd.setTextSize(2);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {delay(500); M5.Lcd.print('.');}
M5.Lcd.println("");
M5.Lcd.println("WiFi Connected");
M5.Lcd.print("IP address: "); M5.Lcd.println(WiFi.localIP());
if (MDNS.begin("m5stack")) {M5.Lcd.println("MDNS responder startted");}
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
M5.Lcd.println("HTTP server started");
}
```
---
## Web Server(Arduino-3)
```cpp
void loop() {
server.handleClient();
}
```
---
## Web Client(Arduino-1)
```cpp
char ssid[] = "XXXXXXXX";
char password[] = "<PASSWORD>";
WiFi wifi;
void connectWifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {Serial.print("."); delay(100);}
Serial.println("connected!");
}
void disconnectWifi() {
WiFi.disconnect();
Serial.println("disconnected!");
}
```
---
## Web Client(Arduino-2)
```cpp
void setup() {
Serial.begin(115200);
connectWifi();
HTTPClient http;
http.begin("http://example.com/index.html");
int httpCode = http.GET();
if(httpCode > 0) {
if(httpCode == HTTP_CODE_OK) { Serial.println(http.getString());}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
disconnectWifi();
}
void loop() {}
```
---
## M5Stackファミリー
M5Stackの種類には下表のようなものがあります。
| 名前 | 概要 |
|:--|:--|
| M5Stack Basic | M5Stack系で一番基本的な種類。 |
| M5Stack Gray | M5StakBasicに加速度、ジャイロ、磁気を<BR/> 計測可能に9軸センサを搭載したモデル。 |
| M5Stack Fire | M5StakGrayにマイクやGrove端子を追加。 |
| M5Stick-C | M5StackBasicよりコンパクト。<br/> SD Card Slotなし、スピーカなし。マイクあり。 |
---
## M5Stack拡張ユニット(センサの一部)
| 名前 | 概要 |
|:--|:--|
| 温湿度気圧センサ | 温度/湿度/気圧が測定できる環境センサ |
|赤外線送受信 | 赤外線発信器と受信器の両方を搭載 |
| 心拍センサ | 血中酸素濃度と心拍数を測定することが可能 |
| TVOC/eCO2 ガスセンサ | 空気中のさまざまな揮発性有機化合物と水素を主に測定 |
| GPSユニット | 衛星測位システムから正確な位置情報を把握 |
---
## M5Stack拡張ユニット(モジュールの一部)
| 名前 | 概要 |
|:--|:--|
| 電池モジュール | 電池モジュール |
| プロトモジュール | ピンソケットを装着したプロトモジュール |
| Commuモジュール | 複数の通信IFを備えたモジュール |
| GPSモジュール | GPSモジュール |
| 3G 拡張ボード | 3G通信機能を追加できるモジュール |
| PLCモジュール | M5StackをPLCとして利用するモジュール |
---
## M5Stackライブラリ(Arduino言語)
| Library | URL |
|:--|:--|
| M5Stack.h | https://github.com/m5stack/M5Stack |
| M5StrickC.h | https://github.com/m5stack/M5StickC |
| WiFi | https://github.com/arduino-libraries/WiFi |
| WebServer | https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer |
| IRDevice | https://github.com/crankyoldgit/IRremoteESP8266 |
| HeartRateSensor | https://github.com/oxullo/Arduino-MAX30100 |
---
## おわり
<file_sep>#include "ConfigUtil.h"
ConfigUtil::ConfigUtil() {
}
void ConfigUtil::loadConfig(String path) {
size_of_config = 0;
String configText;
// ファイルの読み込み
File file = SPIFFS.open(path,"r");
while (file.available()) {
configText += file.readString();
}
file.close();
// 行数の確認
int from = 0;
while (from != -1) {
from = configText.indexOf("\n", from);
if (from != -1 ) {
from++;
size_of_config++;
}
}
// 定義配列の作成
from = 0;
for (int i = 0; i < size_of_config; i++) {
int to = configText.indexOf("\n", from);
int delimIndex = configText.indexOf("=", from);
String key = configText.substring(from, delimIndex);
String value = configText.substring(delimIndex + 1, to);
configs[i] = {key, value};
from = to + 1;
}
}
int ConfigUtil::size() {
return size_of_config;
}
String ConfigUtil::getConfig(String key) {
for (int i =0; i < size_of_config; i++) {
if (configs[i].key == key) {
return configs[i].value;
}
}
return "";
}
<file_sep>#include <M5Stack.h>
#include "Seeed_BMP280.h"
#include <Wire.h>
BMP280 bmp280;
void setup() {
M5.begin();
M5.Lcd.setTextSize(3);
if (!bmp280.init()) {
Serial.println("Device not connected or broken!");
while (true);
}
}
void loop() {
float bmp280temp = bmp280.getTemperature();
uint32_t pressure = bmp280.getPressure();
float altitude = bmp280.calcAltitude(pressure);
M5.Lcd.setCursor(40, 110); M5.Lcd.printf("Temp: %5.1f'C", bmp280temp);
M5.Lcd.setCursor(40, 150); M5.Lcd.printf("Press: %dhPa", pressure / 100);
M5.Lcd.setCursor(40, 190); M5.Lcd.printf("Alti: %5.2fm", altitude);
delay(1000);
}
<file_sep>#include <M5Stack.h>
#include <IRsend.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <SPIFFS.h>
#include "ConfigUtil.h"
const uint16_t IR_SEND_PIN = 21;
const String CONFIG_PATH_WIFI = "/wifi.conf";
const String CONFIG_KEY_WIFI_SSID = "wifi_ssid";
const String CONFIG_KEY_WIFI_PASSWORD = "<PASSWORD>";
const String CONFIG_PATH_IRDATA = "/irdata.conf";
ConfigUtil wifiConfig;
ConfigUtil irDataConfig;
WebServer server(80);
IRsend irSend(IR_SEND_PIN);
void toCharArray(String str, char* c) {
str.toCharArray(c, str.length() + 1);
}
decode_type_t toProtocol(String strProtocol) {
if (strProtocol == "PANASONIC") return PANASONIC;
return UNKNOWN;
}
uint64_t convertStringToU64(String str) {
String HEX_STRING = "0123456789ABCDEF";
uint64_t val = 0;
for (int i = 0; i < str.length(); i++) {
val = val * 16 + HEX_STRING.indexOf(str[i]);
}
return val;
}
void sendIRData(String irDataText) {
int from = 0;
String irData[4];
for (int i = 0; i < 4; i++) {
int to = irDataText.indexOf(",",from);
irData[i] = irDataText.substring(from, to);
from = to + 1;
}
decode_type_t type = toProtocol(irData[0]);
uint64_t code = convertStringToU64(irData[1]);
uint16_t nbits=irData[2].toInt();
uint16_t repeats=irData[3].toInt();
irSend.send(type, code, nbits, repeats);
}
void handleRoot() {
String path="/index.html";
if (SPIFFS.exists(path)) {
File file = SPIFFS.open(path,"r");
server.streamFile(file,"text/html");
file.close();
} else {
Serial.println("handleFileRead: 404 not found");
server.send (404, "text/plain", "ESP: 404 not found");
}
}
void handleSendIRData() {
for (uint8_t i = 0; i < server.args(); i++) {
if (server.argName(i) == "btnid") {
String btnId = server.arg(i);
String irDataText = irDataConfig.getConfig(btnId);
sendIRData(irDataText);
break;
}
}
server.send(200, "text/plain", "OK");
}
void handleNotFound() {
server.send(400, "text/palin", "File Not Found");
Serial.println("File Not Found");
}
void setup() {
M5.begin();
SPIFFS.begin();
irSend.begin();
M5.Lcd.setTextSize(2);
irDataConfig.loadConfig(CONFIG_PATH_IRDATA);
char ssid[30], password[30];
wifiConfig.loadConfig(CONFIG_PATH_WIFI);
toCharArray(wifiConfig.getConfig(CONFIG_KEY_WIFI_SSID), ssid);
toCharArray(wifiConfig.getConfig(CONFIG_KEY_WIFI_PASSWORD), password);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
M5.Lcd.print('.');
}
MDNS.begin("m5stack");
server.on("/", handleRoot);
server.on("/send_ir_data", handleSendIRData);
server.onNotFound(handleNotFound);
server.begin();
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setCursor(0, 0);
M5.Lcd.println("RemoCon:" + WiFi.localIP().toString());
M5.Lcd.qrcode("http://"+WiFi.localIP().toString()+"/", 50, 30, 200, 4);
}
void loop() {
server.handleClient();
}
<file_sep>#include <M5Stack.h>
#include <IRsend.h>
enum RemoconMode {
Volume,
Channel
};
const uint16_t IR_SEND_PIN = 21;
enum RemoconMode mode = Volume;
IRsend irSend(IR_SEND_PIN);
void drawVolumeMode() {
M5.Lcd.fillScreen(BLACK);
M5.Lcd.drawRoundRect( 0, 198, 100, 40, 4, BLUE);
M5.Lcd.drawRoundRect(110, 198, 100, 40, 4, BLUE);
M5.Lcd.drawRoundRect(220, 198, 100, 40, 4, BLUE);
M5.Lcd.setCursor(0, 0); M5.Lcd.print("Mode : Volume");
M5.Lcd.setCursor( 40,206);M5.Lcd.print("-");
M5.Lcd.setCursor(127,206);M5.Lcd.print("Mode");
M5.Lcd.setCursor(260,206);M5.Lcd.print("+");
}
void drawChannelMode() {
M5.Lcd.fillScreen(BLACK);
M5.Lcd.drawRoundRect( 0, 198, 100, 40, 4, BLUE);
M5.Lcd.drawRoundRect(110, 198, 100, 40, 4, BLUE);
M5.Lcd.drawRoundRect(220, 198, 100, 40, 4, BLUE);
M5.Lcd.setCursor(0, 0); M5.Lcd.print("Mode : Channel");
M5.Lcd.setCursor( 15,206);M5.Lcd.print("Down");
M5.Lcd.setCursor(127,206);M5.Lcd.print("Mode");
M5.Lcd.setCursor(250,206);M5.Lcd.print("Up");
}
void setup() {
M5.begin();
irSend.begin();
M5.Lcd.setTextSize(3);
mode = Volume;
drawVolumeMode();
}
void loop() {
M5.update();
if (M5.BtnA.isPressed()) {
if (mode == Volume) {
irSend.send(PANASONIC, 0x555AF148A887, 48, 0);
} else if (mode = Channel) {
irSend.send(PANASONIC, 0x555AF1484889, 48, 0);
}
}
if (M5.BtnC.isPressed()) {
if(mode == Volume) {
irSend.send(PANASONIC, 0x555AF148288F, 48, 0);
} else if (mode = Channel) {
irSend.send(PANASONIC, 0x555AF1488885, 48, 0);
}
}
if (M5.BtnB.wasPressed()) {
if (mode == Volume) {
mode = Channel;
drawChannelMode();
} else if (mode = Channel) {
mode = Volume;
drawVolumeMode();
} else {
mode = Volume;
drawVolumeMode();
}
}
delay(100);
}
| ff25e41a57d71dcf699a31ab6c705d7759dee634 | [
"Markdown",
"C++"
] | 14 | C++ | big-gate-0219/M5Stack | 08194099614b9ada573a0c5e03b9af5c4bb432a5 | df5a4af7a4fcd9c0dd5114073db77c23b0142774 |
refs/heads/master | <file_sep>Writeup 2 - OSINT (Open Source Intelligence)
======
Name: *PUT YOUR NAME HERE*
Section: *PUT YOUR SECTION NUMBER HERE*
I pledge on my honor that I have not given or received any unauthorized assistance on this assignment or examination.
Digital acknowledgement of honor pledge: *PUT YOUR NAME HERE*
## Assignment 2 writeup
### Part 1 (45 pts)
1. <NAME>
2.
A. Email: <EMAIL> – Found this from the cornerstoneairlines.co website on the “About” tab
B. Owner of Cornerstone Airlines – Found this through googling the username and finding the Stwity Page. The page included the website.
C. Lives in Silver Spring – Found this on the Stwity Page
D. Joined Twitter on August, 28 – Found this on his Twitter Page. The Twitter page was a link on his Stwity page
E. Born in 1990 – A given; Found on his Twitter. Also, he is following UMD Cybersecurity and the only follower he has is UMD Cybersecurity
F. Has a reddit under “kruegster1990”
3. 172.16.17.32 – Found this IP address from the Admin page of the cornerstoneairlines.co address.
4.
A. h1dden_fl4g_in_s0urce – Found this on the cornerstoneairlines.co homepage. Opened “view source” and found this in the comments.
B. fly_th3_sk1es_w1th_u5 – Found this on cornerstoneairlines.co/secret. Found this extension through the wayback.
5. 172.16.17.32 – Found this on ipinfo.com. The location of this IP address is in Ontario Canada
6. DigitalOcean, LLC – Found this on ipinfo.com. The location of this IP address is in Ontario Canada
7. Apache/2.4.18 Ubuntu – Found this by typing “cornerstoneairlines.co/ robots.txt
8. Refer to #5
### Part 2 (55 pts)
Using the Script given, I added to the code to create a for loop to read through the Rockstar.txt file and test each password. After running the script, I found the password to be “pokemon”. Then, I went to the home/flight_records directory and with help from the Instagram post of his flight ticket, I found the flag to be: “c0rn3rstone-air-27670”.
<file_sep>import socket
host = "172.16.31.10"
port = 1337 # Port here
wordlist = open("rockyou.txt", "r") # Point to wordlist file
def brute_force():
count = 1
for line in wordlist:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
res = s.recv(1024)
s.send("kruegster" + "\n")
res = s.recv(1024)
s.send(line + "\n")
print(line)
if (not(s.recv(1024) == "Fail\n")):
print("Password: " + line)
break
if __name__ == '__main__':
brute_force()
<file_sep>Writeup 1 - Ethics
======
Name: *PUT YOUR NAME HERE*
Section: *PUT YOUR SECTION NUMBER HERE*
I pledge on my honor that I have not given or received any unauthorized assistance on this assignment or examniation.
Digital acknowledgement: <NAME>
## Assignment Writeup
### Part 1 (25 pts)
This was done via the [ELMS assignment](https://myelms.umd.edu/courses/1251976/assignments/4726433).
### Part 2 (75 pts)
Because of the colossal impact of this decision, I would discuss this with both my boss and trusted individuals first. Ideally, I would want to warn the public to stop the usage of this firmware. However, given that this is firmware, it would be very difficult to request users to stop using it because it is an essential part of many people’s work. This may in turn just cause mass panic and ineffective usage stopping. An argument against not bringing this issue to the public eye is that bad actors may already have found these vulnerabilities and are exploiting them during this time. This situation is similar to the FBI’s Operation Playpen where the agency had gained access over a popular child pornography website but did not take it down until 2 weeks later. They did this, so they could install malware on the viewers computers to make locating and indicting them easier, however this decision caused a continuation of the viewing of child pornography on the site.
I would try to find a way to get these security issues resolved and bring it to the attention of the members in charge of organizing this. However, if I do not see any movement or decision made, I believe I would try releasing this information to the public. I believe that if I do not do anything to help improve this situation, I would be causing harm. It is similar to watching a person have a heart attack. If I do not call 911 or get help, the person may die. It is my responsibility to make sure I do as much as I can to make sure that does not happen. In a similar sense, knowing what I would know in the situation of the ECU, it would be my responsibility, as well as the responsibility of the others who know, to better this situation and cause the least harm to the victims.
<file_sep>Writeup 3 - OSINT II, OpSec and RE
======
Name: <NAME>
Section: 0201
I pledge on my honor that I have not given or received any unauthorized assistance on this assignment or examination.
Digital acknowledgement of honor pledge: Chandan Panguluri
## Assignment 3 Writeup
### Part 1 (100 pts)
Common Vulnerabilities
- Weak Passwords
- One should not be using a password that is a popular word, or something that they are publicly interested in (the password becomes easier to guess).
- Publicly known information and posts made by a user on social media can give hints to their password and/or answers to security questions.
- The longer and the more complicated the password the better. As mentioned by <NAME> when he was being interviewed by <NAME>, a common 8-letter password could take seconds to crack (http://time.com/3815620/edward-snowden-password-john-oliver/).
- Recommendation: Use long passwords with a mix of upper and lower case letters, numbers, and special characters. And use password accounting websites like "Last Pass" to keep track of accounts paired with complicated passwords.
- Not Hiding IP Addresses
- One should not leave IP addresses as ways to access websites or on the address line (like the Admin page of cornerstoneairlines.com did).
- An easily accessable IP Address facilitates an easier time locating a device or server.
- Recommend: Use a firewall like McAfee or WatchGuard to monitor traffic on the site and to hide and protect the internal network address. It would also help report on threats. Using VPN (Virtual Private Network) would also be helpful in thwarting actors malicous actors as it helps mask the location of the device/server and encrypt data transfers.
- Posting Sensitive Information on Social Media
- The only way we could have gotten the right flag was because of the Instagram post with the flight number. This is a clear example of how social media could help facilitate hacking.
- Malicious actors could use public information about a person to obtain sensitive information.
- Example: What people post on social media can be great information for malicious actors when trying to break into a protected and private area. For example, while it is popular to keep location on and post pictures when traveling, burglars can see that as a hint a house is vacant and would be easy to rob. (https://abc7news.com/travel/burglars-use-social-media-to-find-next-victims/448107/) . Similarly, if sensitive information is posted online, malicious actors could use that to find passwords and figure out the answers to security questions (https://www.usatoday.com/story/money/2015/06/01/irs-breach-personal-data-vulnerable/28068875/).
- Recommend: Do not post sensitive information publicly. Also, do not use professional emails for private accounts. Or else it would further facilitate malicious actors in finding sensitive information using public knowledge. | 5a4d0b0d62f6cbf590e72f4700fae2f254c6d2b0 | [
"Markdown",
"Python"
] | 4 | Markdown | cpanguluri/389Rfall18 | 27f55c6004c5dcab7969c7f974e1b3e18b76f6fa | 755a8c7108442d493b00037f79252b78bf5834ec |
refs/heads/main | <repo_name>spatie/laravel-uptime-monitor<file_sep>/docs/monitoring-uptime/getting-started.md
---
title: Adding and removing sites
weight: 1
---
## Creating your first monitor
After you've set up [the package](https://docs.spatie.be/laravel-uptime-monitor/v3/installation-and-setup) you can use the `monitor:create` [artisan](https://laravel.com/docs/5.4/artisan) command to monitor a url. Here's how to add a monitor for `https://laravel.com`:
```php
php artisan monitor:create https://laravel.com
```
You will be asked if the uptime check should look for a specific string on the response. This is handy if you know a few words that appear on the url you want to monitor. If you choose to specify a string and the string is not contained in the response when checking the url, the package will consider that uptime check failed.
If the url you want to monitor starts with `https://` the package will also [start monitoring](https://docs.spatie.be/laravel-uptime-monitor/v3/monitoring-ssl-certificates/getting-started) the ssl certificate of your site.
You've just set up your first monitor. Congratulations! The package will now send you [notifications](https://docs.spatie.be/laravel-uptime-monitor/v3/monitoring-uptime/notifications) when your monitor fails and when it is restored.
Read the [high level overview section](https://docs.spatie.be/laravel-uptime-monitor/v3/high-level-overview) to learn how the uptime checking works in detail.
Instead of using the `monitor:create` command you may also manually create a row in the `monitors` table. Here's [a description of all the fields in that table](https://docs.spatie.be/laravel-uptime-monitor/v3/advanced-usage/manually-modifying-monitors).
## Removing a monitor
You can remove a monitor by running `monitor:delete`. Here's how to delete the monitor for `https://laravel.com`:
```php
php artisan monitor:delete https://laravel.com
```
This will remove the monitor for laravel.com from the database. Want to delete multiple monitors at once? Just pass all the urls as comma-separated list.
Instead of using the `monitor:delete` command you may also manually delete the relevant row in the `monitors` table.
<file_sep>/tests/Integration/Events/UptimeCheckFailedTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Events;
use Illuminate\Support\Facades\Event;
use Spatie\UptimeMonitor\Events\UptimeCheckFailed;
use Spatie\UptimeMonitor\Events\UptimeCheckRecovered;
use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
use Spatie\UptimeMonitor\Test\TestCase;
class UptimeCheckFailedTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
Event::fake();
$this->monitor = Monitor::factory()->create();
}
/** @test */
public function the_down_event_will_be_fired_when_the_uptime_check_failed_for_the_configured_amount_of_times()
{
$this->server->down();
$monitors = MonitorRepository::getForUptimeCheck();
$consecutiveFailsNeeded = config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures');
foreach (range(1, $consecutiveFailsNeeded) as $index) {
$monitors->checkUptime();
if ($index < $consecutiveFailsNeeded) {
Event::assertNotDispatched(UptimeCheckFailed::class);
}
}
Event::assertDispatched(UptimeCheckFailed::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
/** @test */
public function it_will_fire_the_failed_event_again_if_a_monitor_keeps_failing_after_the_configured_amount_of_minutes()
{
$this->server->down();
$monitors = MonitorRepository::getForUptimeCheck();
$consecutiveFailsNeeded = config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures');
foreach (range(1, $consecutiveFailsNeeded) as $index) {
$monitors->checkUptime();
if ($index < $consecutiveFailsNeeded) {
Event::assertNotDispatched(UptimeCheckFailed::class);
}
}
Event::assertDispatched(UptimeCheckFailed::class);
$this->resetEventAssertions();
$monitors->checkUptime();
Event::assertNotDispatched(UptimeCheckFailed::class);
$this->resetEventAssertions();
$this->progressMinutes(config('uptime-monitor.notifications.resend_uptime_check_failed_notification_every_minutes'));
$monitors->checkUptime();
Event::assertDispatched(UptimeCheckFailed::class);
}
/** @test */
public function the_failing_event_will_be_fired_when_a_site_is_but_the_look_for_string_is_not_found_on_the_response()
{
$this->server->setResponseBody('Hi, welcome on the page');
$this->monitor->look_for_string = 'Another page';
$this->monitor->save();
$this->app['config']->set('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures', 1);
MonitorRepository::getForUptimeCheck()->checkUptime();
Event::assertDispatched(UptimeCheckFailed::class);
Event::assertNotDispatched(UptimeCheckSucceeded::class);
Event::assertNotDispatched(UptimeCheckRecovered::class);
}
/** @test */
public function the_uptime_checker_will_fail_without_configured_guzzle_options()
{
$this->server->up();
$this->server->setResponseBody('', 301);
$monitors = MonitorRepository::getForUptimeCheck();
$consecutiveFailsNeeded = config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures');
foreach (range(1, $consecutiveFailsNeeded) as $index) {
$monitors->checkUptime();
if ($index < $consecutiveFailsNeeded) {
Event::assertNotDispatched(UptimeCheckFailed::class);
}
}
Event::assertDispatched(UptimeCheckFailed::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
}
<file_sep>/src/UptimeMonitorServiceProvider.php
<?php
namespace Spatie\UptimeMonitor;
use Illuminate\Support\ServiceProvider;
use Spatie\UptimeMonitor\Commands\CheckCertificates;
use Spatie\UptimeMonitor\Commands\CheckUptime;
use Spatie\UptimeMonitor\Commands\CreateMonitor;
use Spatie\UptimeMonitor\Commands\DeleteMonitor;
use Spatie\UptimeMonitor\Commands\DisableMonitor;
use Spatie\UptimeMonitor\Commands\EnableMonitor;
use Spatie\UptimeMonitor\Commands\ListMonitors;
use Spatie\UptimeMonitor\Commands\SyncFile;
use Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker;
use Spatie\UptimeMonitor\Notifications\EventHandler;
class UptimeMonitorServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
$this->publishes([
__DIR__.'/../config/uptime-monitor.php' => config_path('uptime-monitor.php'),
], 'config');
}
if (! class_exists('CreateMonitorsTable')) {
$timestamp = date('Y_m_d_His', time());
$this->publishes([
__DIR__.'/../database/migrations/create_monitors_table.php.stub' => database_path('migrations/'.$timestamp.'_create_monitors_table.php'),
], 'migrations');
}
}
/**
* Register the application services.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/uptime-monitor.php', 'uptime-monitor');
$this->app['events']->subscribe(EventHandler::class);
$this->app->bind('command.monitor:check-uptime', CheckUptime::class);
$this->app->bind('command.monitor:check-certificate', CheckCertificates::class);
$this->app->bind('command.monitor:sync-file', SyncFile::class);
$this->app->bind('command.monitor:create', CreateMonitor::class);
$this->app->bind('command.monitor:delete', DeleteMonitor::class);
$this->app->bind('command.monitor:enable', EnableMonitor::class);
$this->app->bind('command.monitor:disable', DisableMonitor::class);
$this->app->bind('command.monitor:list', ListMonitors::class);
$this->app->bind(
UptimeResponseChecker::class,
config('uptime-monitor.uptime_check.response_checker')
);
$this->commands([
'command.monitor:check-uptime',
'command.monitor:check-certificate',
'command.monitor:sync-file',
'command.monitor:create',
'command.monitor:delete',
'command.monitor:enable',
'command.monitor:disable',
'command.monitor:list',
]);
}
}
<file_sep>/docs/requirements.md
---
title: Requirements
weight: 3
---
This uptime monitor package requires **PHP 7.4 or higher** and **Laravel 8 or higher**. You should also have **curl 7.47.0 or higher** installed. The `php-intl` must be installed.
<file_sep>/tests/Integration/Events/UptimeCheckRecoveredTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Events;
use Carbon\Carbon;
use Illuminate\Support\Facades\Event;
use Spatie\UptimeMonitor\Events\UptimeCheckRecovered;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
use Spatie\UptimeMonitor\Test\TestCase;
class UptimeCheckRecoveredTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
Event::fake();
$this->monitor = Monitor::factory()->create();
}
/** @test */
public function the_recovered_event_will_be_fired_when_an_uptime_check_succeeds_after_it_has_failed()
{
$monitors = MonitorRepository::getForUptimeCheck();
$this->server->down();
$consecutiveFailsNeeded = config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures');
foreach (range(1, $consecutiveFailsNeeded) as $index) {
$monitors->checkUptime();
}
$this->monitor = $this->monitor->fresh();
$downTimeLengthInMinutes = 10;
$this->progressMinutes($downTimeLengthInMinutes);
$this->server->up();
Event::assertNotDispatched(UptimeCheckRecovered::class);
$monitors->checkUptime();
Event::assertDispatched(UptimeCheckRecovered::class, function (UptimeCheckRecovered $event) use ($downTimeLengthInMinutes) {
if ($event->monitor->id !== $this->monitor->id) {
return false;
}
if ($event->downtimePeriod->startDateTime->toDayDateTimeString() !== Carbon::now()->subMinutes($downTimeLengthInMinutes)->toDayDateTimeString()) {
return false;
}
return true;
});
}
}
<file_sep>/src/Commands/MonitorLists/Disabled.php
<?php
namespace Spatie\UptimeMonitor\Commands\MonitorLists;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class Disabled
{
public static function display()
{
$disabledMonitors = MonitorRepository::getDisabled();
if (! $disabledMonitors->count()) {
return;
}
ConsoleOutput::warn('Disabled monitors');
ConsoleOutput::warn('=================');
$rows = $disabledMonitors->map(function (Monitor $monitor) {
$url = $monitor->url;
return compact('url');
});
$titles = ['URL'];
ConsoleOutput::table($titles, $rows);
ConsoleOutput::line('');
}
}
<file_sep>/docs/monitoring-uptime/events.md
---
title: Events
weight: 2
---
These events are fired by the uptime check of a monitor.
## UptimeCheckFailed
`Spatie\UptimeMonitor\Events\UptimeCheckFailed`
This event is fired when the uptime check of the monitor has consecutively failed a couple of times. The specific number of failures can be configured in the `fire_monitor_failed_event_after_consecutive_failures` key in the config file. This happens when the configured `url` could not be reached or, if you specified it, the `look_for_string` value could not be found in the response.
It has one public property, `$monitor`, that contains an instance of `Spatie\UptimeMonitor\Models\Monitor`.
## UptimeCheckRecovered
`Spatie\UptimeMonitor\Events\UptimeCheckRecovered`
This event is fired after the uptime check is successful after it has failed.
It has one public property, `$monitor`, that contains an instance of `Spatie\UptimeMonitor\Models\Monitor`.
## UptimeCheckSucceeded
`Spatie\UptimeMonitor\Events\UptimeCheckSucceeded`
This event is fired when the monitor could reach the configured `url` and, if you specified it, found the `look_for_string` value in the response. This event only takes the uptime check into consideration, so it will still be fired if the ssl certificate check of the monitor is failing.
It has one public property, `$monitor`, that contains an instance of `Spatie\UptimeMonitor\Models\Monitor`.
<file_sep>/docs/advanced-usage/disabling-monitors.md
---
title: Disabling monitors
weight: 5
---
If you want to temporarily stop the uptime and the certificate check of a monitor you can disable it.
This is how to disable a monitor for `https://laravel.com`
```bash
php artisan monitor:disable https://laravel.com
```
You can re-enable the checks of a monitor with:
```bash
php artisan monitor:enable https://laravel.com
```
Both commands accept multiple urls comma-separated to enable or disable multiple monitors at once.
<file_sep>/src/Events/CertificateCheckFailed.php
<?php
namespace Spatie\UptimeMonitor\Events;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\SslCertificate\SslCertificate;
use Spatie\UptimeMonitor\Models\Monitor;
class CertificateCheckFailed implements ShouldQueue
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
public Monitor $monitor;
/** @var string */
public string $reason;
public ?SslCertificate $certificate;
public function __construct(Monitor $monitor, string $reason, SslCertificate $certificate = null)
{
$this->monitor = $monitor;
$this->reason = $reason;
$this->certificate = $certificate;
}
}
<file_sep>/database/factories/MonitorFactory.php
<?php
namespace Spatie\UptimeMonitor\Database\Factories;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
class MonitorFactory extends Factory
{
protected $model = Monitor::class;
public function definition()
{
return [
'url' => sprintf('http://localhost:%d', getenv('TEST_SERVER_PORT')),
'uptime_status' => UptimeStatus::UP,
'uptime_check_interval_in_minutes' => config('uptime-monitor.uptime_check.run_interval_in_minutes'),
'uptime_status_last_change_date' => Carbon::now(),
'uptime_check_enabled' => true,
'certificate_check_enabled' => false,
];
}
}
<file_sep>/src/Commands/MonitorLists/CertificateCheckFailed.php
<?php
namespace Spatie\UptimeMonitor\Commands\MonitorLists;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class CertificateCheckFailed
{
public static function display()
{
$monitorsWithFailingCertificateChecks = MonitorRepository::getWithFailingCertificateCheck();
if (! $monitorsWithFailingCertificateChecks->count()) {
return;
}
ConsoleOutput::warn('Certificate check failed');
ConsoleOutput::warn('========================');
$rows = $monitorsWithFailingCertificateChecks->map(function (Monitor $monitor) {
$url = $monitor->url;
$reason = $monitor->chunkedLastCertificateCheckFailureReason;
return compact('url', 'reason');
});
$titles = ['URL', 'Problem description'];
ConsoleOutput::table($titles, $rows);
ConsoleOutput::line('');
}
}
<file_sep>/src/MonitorCollection.php
<?php
namespace Spatie\UptimeMonitor;
use Generator;
use GrahamCampbell\GuzzleFactory\GuzzleFactory;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\Promise\EachPromise;
use Illuminate\Support\Collection;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Spatie\UptimeMonitor\Models\Monitor;
class MonitorCollection extends Collection
{
public function checkUptime(): void
{
$this->resetItemKeys();
(new EachPromise($this->getPromises(), [
'concurrency' => config('uptime-monitor.uptime_check.concurrent_checks'),
'fulfilled' => function (ResponseInterface $response, $index) {
$monitor = $this->getMonitorAtIndex($index);
ConsoleOutput::info("Could reach {$monitor->url}");
$monitor->uptimeRequestSucceeded($response);
},
'rejected' => function (TransferException $exception, $index) {
$monitor = $this->getMonitorAtIndex($index);
ConsoleOutput::error("Could not reach {$monitor->url} error: `{$exception->getMessage()}`");
$monitor->uptimeRequestFailed($exception->getMessage());
},
]))->promise()->wait();
}
protected function getPromises(): Generator
{
$client = GuzzleFactory::make(
config('uptime-monitor.uptime_check.guzzle_options', []),
config('uptime-monitor.uptime-check.retry_connection_after_milliseconds', 100)
);
foreach ($this->items as $monitor) {
ConsoleOutput::info("Checking {$monitor->url}");
$promise = $client->requestAsync(
$monitor->uptime_check_method,
$monitor->url,
array_filter([
'connect_timeout' => config('uptime-monitor.uptime_check.timeout_per_site'),
'headers' => $this->promiseHeaders($monitor),
'body' => $monitor->uptime_check_payload,
])
);
yield $promise;
}
}
private function promiseHeaders(Monitor $monitor): array
{
return collect([])
->merge(['User-Agent' => config('uptime-monitor.uptime_check.user_agent')])
->merge(config('uptime-monitor.uptime_check.additional_headers') ?? [])
->merge($monitor->uptime_check_additional_headers)
->toArray();
}
/**
* In order to make use of Guzzle promises we have to make sure the
* keys of the collection are in a consecutive order without gaps.
*/
protected function resetItemKeys(): void
{
$this->items = $this->values()->all();
}
protected function getMonitorAtIndex(int $index): Monitor
{
return $this->items[$index];
}
public function sortByHost(): self
{
return $this->sortBy(function (Monitor $monitor) {
return $monitor->url->getHost();
});
}
}
<file_sep>/docs/advanced-usage/sending-and-verifying-a-payload.md
---
title: Sending and verifying a payload
weight: 8
---
There are cases in which you would like to send a payload and verify the response to determine if its services are up and active for example, if you need to determine if a down stream service is connected and functioning correctly.
To achieve this, you will need to manually update a few fields in the database and optionally create a custom response checker specifically for that monitor to verify the response from the uptime monitor request.
In this example, you will need to set the following fields in the database:
- `uptime_check_method`: `POST`
- `uptime_check_payload`: `{"foo":"bar"}`
- `uptime_check_additional_headers`: `{"Content-Type":"application/json"}`
- `uptime_check_response_checker`: `App\ResponseCheckers\ExampleChecker`
_More details on these fields can be found in the section "[Manually Modifying Monitors](/laravel-uptime-monitor/v3/advanced-usage/manually-modifying-monitors)"_
We will want to do some custom verification specifically for the response of this check.
Our checker could look something like the following:
```php
<?php
namespace App\ResponseCheckers;
use Illuminate\Http\Response;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker;
class ExampleChecker implements UptimeResponseChecker
{
public function isValidResponse(ResponseInterface $response, Monitor $monitor) : bool
{
return $response->getStatusCode() === Response::HTTP_OK
&& (json_decode((string) $response->getBody(), true))['foo'] === 'bar';
}
public function getFailureReason(ResponseInterface $response, Monitor $monitor) : string
{
return vsprintf('Foo returned %s instead of bar with a status code of %s', [
json_decode((string) $response->getBody(), true)['foo'],
$response->getStatusCode()
]);
}
}
```
This workflow is extremely flexible and should allow for some pretty advanced uptime and monitoring checks.
<file_sep>/docs/installation-and-setup.md
---
title: Installation and setup
weight: 6
---
## Basic installation
This package is meant to be installed into an existing Laravel application. If you're not familiar with Laravel head over to [the official documentation](https://laravel.com/docs) to learn how to set up and use this amazing framework. If you have no interest in learning Laravel, but still want to use our uptime monitor, take a look at the [uptime-monitor-app](https://github.com/spatie/uptime-monitor-app) repo which contains a stand alone version of this package.
Standing in the directory of an existing Laravel application you can install the package via composer:
``` bash
composer require spatie/laravel-uptime-monitor
```
The package will automatically register itself.
To publish the config file to `config/uptime-monitor.php` run:
``` bash
php artisan vendor:publish --provider="Spatie\UptimeMonitor\UptimeMonitorServiceProvider"
```
The default contents of the configuration looks like this:
```php
<?php
return [
/*
* You can get notified when specific events occur. Out of the box you can use 'mail'
* and 'slack'. Of course you can also specify your own notification classes.
*/
'notifications' => [
'notifications' => [
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckRecovered::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckSucceeded::class => [],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateExpiresSoon::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckSucceeded::class => [],
],
/*
* The location from where you are running this Laravel application. This location will be
* mentioned in all notifications that will be sent.
*/
'location' => '',
/*
* To keep reminding you that a site is down, notifications
* will be resent every given number of minutes.
*/
'resend_uptime_check_failed_notification_every_minutes' => 60,
'mail' => [
'to' => ['<EMAIL>'],
],
'slack' => [
'webhook_url' => env('UPTIME_MONITOR_SLACK_WEBHOOK_URL'),
],
/*
* Here you can specify the notifiable to which the notifications should be sent. The default
* notifiable will use the variables specified in this config file.
*/
'notifiable' => \Spatie\UptimeMonitor\Notifications\Notifiable::class,
/*
* The date format used in notifications.
*/
'date_format' => 'd/m/Y',
],
'uptime_check' => [
/*
* When the uptime check could reach the url of a monitor it will pass the response to this class
* If this class determines the response is valid, the uptime check will be regarded as succeeded.
*
* You can use any implementation of Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker here.
*/
'response_checker' => Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\LookForStringChecker::class,
/*
* An uptime check will be performed if the last check was performed more than the
* given number of minutes ago. If you change this setting you have to manually
* update the `uptime_check_interval_in_minutes` value of your existing monitors.
*
* When an uptime check fails we'll check the uptime for that monitor every time `monitor:check-uptime`
* runs regardless of this setting.
*/
'run_interval_in_minutes' => 5,
/*
* To speed up the uptime checking process the package can perform the uptime check of several
* monitors concurrently. Set this to a lower value if you're getting weird errors
* running the uptime check.
*/
'concurrent_checks' => 10,
/*
* The uptime check for a monitor will fail if the url does not respond after the
* given number of seconds.
*/
'timeout_per_site' => 10,
/*
* Because networks can be a bit unreliable the package can make three attempts
* to connect to a server in one uptime check. You can specify the time in
* milliseconds between each attempt.
*/
'retry_connection_after_milliseconds' => 100,
/*
* If you want to change the default Guzzle client behaviour, you can do so by
* passing custom options that will be used when making requests.
*/
'guzzle_options' => [
// 'allow_redirects' => false,
],
/*
* Fire `Spatie\UptimeMonitor\Events\MonitorFailed` event only after
* the given number of uptime checks have consecutively failed for a monitor.
*/
'fire_monitor_failed_event_after_consecutive_failures' => 2,
/*
* When reaching out to sites this user agent will be used.
*/
'user_agent' => 'spatie/laravel-uptime-monitor uptime checker',
/*
* When reaching out to the sites these headers will be added.
*/
'additional_headers' => [],
],
'certificate_check' => [
/*
* The `Spatie\UptimeMonitor\Events\SslExpiresSoon` event will fire
* when a certificate is found whose expiration date is in
* the next number of given days.
*/
'fire_expiring_soon_event_if_certificate_expires_within_days' => 10,
],
/*
* To add or modify behaviour to the Monitor model you can specify your
* own model here. The only requirement is that it should extend
* `Spatie\UptimeMonitor\Models\Monitor`.
*/
'monitor_model' => Spatie\UptimeMonitor\Models\Monitor::class,
];
```
As a last step, run the migrations to create the `monitors` table.
```bash
php artisan migrate
```
## Scheduling
After you have performed the basic installation you can check the uptime and ssl certificates of sites using the `monitor:check-uptime` and `monitor:check-certificate` commands. In most cases you'll want to schedule them. We recommend that you run the uptime check every minute and the ssl certificate check daily.
You can schedule the commands, like any other command, in the console Kernel.
```php
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('monitor:check-uptime')->everyMinute();
$schedule->command('monitor:check-certificate')->daily();
}
```
<file_sep>/docs/monitoring-uptime/_index.md
---
title: Monitoring uptime
weight: 1
---
<file_sep>/tests/Integration/Models/MonitorTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Models;
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class MonitorTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
$this->monitor = Monitor::factory()->create([
'url' => 'http://mysite.com',
'uptime_check_enabled' => true,
'certificate_check_enabled' => true,
]);
}
/** @test */
public function it_will_throw_an_exception_when_creating_a_monitor_that_already_exists()
{
$this->expectException(CannotSaveMonitor::class);
Monitor::factory()->create(['url' => 'http://mysite.com']);
}
/** @test */
public function it_will_throw_an_exception_when_updating_a_monitor_to_an_url_of_a_monitor_that_already_exists()
{
$monitor = Monitor::factory()->create(['url' => 'http://myothersite.com']);
$this->expectException(CannotSaveMonitor::class);
$monitor->url = 'http://mysite.com';
$monitor->save();
}
/** @test */
public function it_can_disable_and_enable_itself_for_an_http_url()
{
$this->monitor->disable();
$this->monitor = $this->monitor->fresh();
$this->assertFalse($this->monitor->uptime_check_enabled);
$this->assertFalse($this->monitor->certificate_check_enabled);
$this->monitor->enable();
$this->monitor = $this->monitor->fresh();
$this->assertTrue($this->monitor->uptime_check_enabled);
//it will not enable the certificate check for a non-https site.
$this->assertFalse($this->monitor->certificate_check_enabled);
}
/** @test */
public function raw_url_is_appended_during_serialization()
{
$this->assertEquals(
'http://mysite.com',
$this->monitor->toArray()['raw_url']
);
}
}
<file_sep>/tests/Integration/Models/Traits/SupportsUptimeCheckTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Models\Traits;
use Carbon\Carbon;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class SupportsUptimeCheckTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
$this->monitor = Monitor::factory()->create(['uptime_last_check_date' => Carbon::now()]);
}
/** @test */
public function it_will_determine_that_a_monitor_most_be_rechecked_after_the_specified_amount_of_minutes()
{
$this->assertFalse($this->monitor->shouldCheckUptime());
$this->progressMinutes(config('uptime-monitor.uptime_check.run_interval_in_minutes') - 1);
$this->assertFalse($this->monitor->shouldCheckUptime());
$this->progressMinutes(1);
$this->assertTrue($this->monitor->shouldCheckUptime());
}
/** @test */
public function it_will_determine_that_a_failing_monitor_must_always_be_checked()
{
$this->monitor->uptime_status = UptimeStatus::DOWN;
$this->monitor->save();
foreach (range(1, 10) as $index) {
$this->assertTrue($this->monitor->shouldCheckUptime());
$this->progressMinutes(1);
}
}
/** @test */
public function it_will_determine_that_a_monitor_that_is_not_enabled_must_never_be_checked()
{
$this->monitor->uptime_check_enabled = false;
$this->monitor->save();
foreach (range(1, 10) as $index) {
$this->assertFalse($this->monitor->shouldCheckUptime());
$this->progressMinutes(1);
}
}
/** @test */
public function it_will_set_uptime_status_last_change_date_when_the_status_changes()
{
$this->progressMinutes(5);
$this->server->down();
$this->artisan('monitor:check-uptime');
$this->assertTrue($this->monitorAttributeIsSetToNow('uptime_status_last_change_date'));
$this->progressMinutes(5);
$this->assertFalse($this->monitorAttributeIsSetToNow('uptime_status_last_change_date'));
$this->server->up();
$this->artisan('monitor:check-uptime');
$this->assertTrue($this->monitorAttributeIsSetToNow('uptime_status_last_change_date'));
}
/** @test */
public function it_will_update_the_last_checked_date_no_matter_what_the_uptime_status_of_a_monitor_is()
{
foreach ([UptimeStatus::UP, UptimeStatus::DOWN, UptimeStatus::NOT_YET_CHECKED] as $status) {
$this->monitor->uptime_status = $status;
$this->monitor->save();
foreach (range(1, 10) as $index) {
$this->progressMinutes(10);
$this->artisan('monitor:check-uptime');
$this->assertTrue($this->monitorAttributeIsSetToNow('uptime_last_check_date'));
}
}
}
protected function monitorAttributeIsSetToNow(string $attribute): bool
{
$this->monitor = $this->monitor->fresh();
return $this->monitor->$attribute->diffInMinutes() === 0;
}
}
<file_sep>/src/Helpers/ConsoleOutput.php
<?php
namespace Spatie\UptimeMonitor\Helpers;
use Illuminate\Console\Command;
class ConsoleOutput
{
public static Command $runningCommand;
public function setOutput(Command $runningCommand)
{
static::$runningCommand = $runningCommand;
}
public static function __callStatic(string $method, $arguments)
{
if (! static::$runningCommand) {
return;
}
static::$runningCommand->$method(...$arguments);
}
}
<file_sep>/docs/advanced-usage/syncing-monitors-from-a-file.md
---
title: Syncing monitors from a file
weight: 2
---
Using the `monitor:create` becomes tedious fast if you have a large number of urls that you wish to monitor. Luckily there's also a command to bulk import urls from a json file:
```
php artisan monitor:sync-file <path-to-file>
```
Here's an example of the structure that json file should have:
```json
[
{
"url": "https://www.example.com",
"uptime_check_enabled": true,
"certificate_check_enabled": true
},
{
"url": "http://www.another-example.com",
"uptime_check_enabled": true,
"certificate_check_enabled": false
}
]
```
By default the command will import all missing urls and update existing urls. If you wish to delete urls from the database that are not in the json file you can use the `--delete-missing` flag.
<file_sep>/tests/Integration/Events/CertificateCheckFailedTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Events;
use Illuminate\Support\Facades\Event;
use Spatie\UptimeMonitor\Events\CertificateCheckFailed;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class CertificateCheckFailedTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
Event::fake();
$this->monitor = Monitor::factory()->create(['certificate_check_enabled' => true]);
}
/** @test */
public function the_invalid_certificate_found_event_will_be_fired_when_an_invalid_certificate_is_found()
{
$this->monitor->checkCertificate();
Event::assertDispatched(CertificateCheckFailed::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
}
<file_sep>/tests/Integration/ConfigurationTest.php
<?php
namespace Spatie\UptimeMonitor\Test;
use Spatie\UptimeMonitor\Exceptions\InvalidConfiguration;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class ConfigurationTest extends TestCase
{
/** @test */
public function a_custom_monitor_model_can_be_specified()
{
Monitor::factory()->create();
$customModel = new class () extends Monitor {
public $table = 'monitors';
};
$this->app['config']->set('uptime-monitor.monitor_model', get_class($customModel));
$this->assertInstanceOf(get_class($customModel), MonitorRepository::getEnabled()->first());
}
/** @test */
public function when_an_invalid_monitor_model_is_specified_an_exception_will_be_thrown()
{
$customModel = new class () {
};
$this->app['config']->set('uptime-monitor.monitor_model', get_class($customModel));
$this->expectException(InvalidConfiguration::class);
MonitorRepository::getEnabled();
}
}
<file_sep>/docs/monitoring-ssl-certificates/notifications.md
---
title: Notifications
weight: 3
---
The package can notify you when certain events take place when running the ssl certificate check. You can specify which channels the notifications for certain events should be sent in the config file. If you don't want notifications for a certain event, just pass an empty array. `slack` and `mail` channels are supported out of the box. If you want to use another channel or want to modify the notifications read the section on [customizing notifications](https://docs.spatie.be/laravel-uptime-monitor/v3/advanced-usage/customizing-notifications).
## CertificateCheckFailed
`Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckFailed`
This notification will be sent when the `Spatie\UptimeMonitor\Events\CertificateCheckFailed` event is fired.
This is how the notification looks in Slack.
<img src="./../images/ssl-certificate-failed.jpg" class="screenshot -slack" />
## CertificateExpiresSoon
`Spatie\UptimeMonitor\Notifications\Notifications\CertificateExpiresSoon`
This notification will be sent when the `Spatie\UptimeMonitor\Events\CertificateExpiresSoon` event is fired.
This is how the notification looks in Slack.
<img src="./../images/ssl-expiring-soon.jpg" class="screenshot -slack" />
## CertificateCheckSucceeded
`Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckSucceeded`
This notification will be sent when the `Spatie\UptimeMonitor\Events\CertificateCheckSucceeded` event was fired.
Probably you don't want to be notified of this event as it is fired many many times.
<file_sep>/tests/Integration/Events/CertificateCheckSucceededTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Events;
use Carbon\Carbon;
use Illuminate\Support\Facades\Event;
use Spatie\UptimeMonitor\Events\CertificateCheckSucceeded;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class CertificateCheckSucceededTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
Carbon::setTestNow(null);
Event::fake();
$this->monitor = Monitor::factory()->create([
'certificate_check_enabled' => true,
'url' => 'https://google.com',
]);
}
/** @test */
public function the_valid_certificate_found_event_will_be_fired_when_a_valid_certificate_is_found()
{
$this->skipIfNotConnectedToTheInternet();
$this->monitor->checkCertificate();
Event::assertDispatched(CertificateCheckSucceeded::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
}
<file_sep>/docs/advanced-usage/manually-modifying-monitors.md
---
title: Manually modifying monitors
weight: 1
---
All configured monitors are stored in the `monitors` table in the database. The various `monitor` commands manipulate the data that table:
- `monitor:create` adds a row
- `monitor:delete` deletes a row
- `monitor:enable` and `monitor:disable` change the value of the `enabled` field
- `monitor:list` lists all rows
- `monitor:sync-file` syncs monitors from a json file (see [syncing monitors from a file](https://docs.spatie.be/laravel-uptime-monitor/v3/advanced-usage/syncing-monitors-from-a-file))
You can also manually manipulate the table rows instead. Here's a description of the fields you can manipulate:
- `url`: the url to perform uptime and ssl certificate checks on. Take care not to insert duplicate values.
- `uptime_check_enabled`: determines if the uptime check should be performed for this monitor.
- `certificate_check_enabled`: determines if the ssl certificate check should be performed for this monitor.
- `look_for_string`: if this string is not found in the response the uptime check will fail. You may set this to an empty string to disable the check.
- `uptime_check_interval_in_minutes`: if the uptime check was successful that site won't be checked again for at least this number of minutes. When a monitor is created this field is filled with the value of `uptime_check_interval_in_minutes` in the config file.
- `uptime_check_method`: the `http` method used by the uptime check. If `look_for_string` is specified when creating the monitor this will be set to `get`, otherwise this will be `head`.
- `uptime_check_payload`: a payload that will be sent as the monitor request body. If you are using this field, you should set the `Content-Type` header in the `uptime_check_additional_headers` field.
- `uptime_check_additional_headers`: additional headers that are sent in the request. The value shoule be escaped `JSON`. It will be decoded using `json_decode`. Example: `{"Content-Type":"application\/json"}`
- `uptime_check_response_checker`: the fully qualified class name of a custom response checker that will be used only for this monitor. It must be an implementation of `Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker` and will be resolved using the [service container](https://laravel.com/docs/5.5/container).
All other fields in the `monitors` table are managed by the package and should not be manually modified.
<file_sep>/src/Commands/SyncFile.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Illuminate\Support\Str;
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor;
use Spatie\UptimeMonitor\Models\Monitor;
class SyncFile extends BaseCommand
{
protected $signature = 'monitor:sync-file
{path : Path to JSON file with monitors}
{--delete-missing : Delete monitors from the database if they\'re not found in the monitors file}';
protected $description = 'One way sync monitors from JSON file to database';
public function handle()
{
$json = file_get_contents($this->argument('path'));
$monitorsInFile = collect(json_decode($json, true));
$this->validateMonitors($monitorsInFile);
$this->createOrUpdateMonitorsFromFile($monitorsInFile);
$this->deleteMissingMonitors($monitorsInFile);
}
protected function validateMonitors($monitorsInFile)
{
$monitorsInFile->each(function ($monitorAttributes) {
if (! Str::startsWith($monitorAttributes['url'], ['https://', 'http://'])) {
throw new CannotSaveMonitor("URL `{$monitorAttributes['url']}` is invalid (is the URL scheme included?)");
}
});
}
protected function createOrUpdateMonitorsFromFile($monitorsInFile)
{
$monitorsInFile
->each(function ($monitorAttributes) {
$this->createOrUpdateMonitor($monitorAttributes);
});
$this->info("Synced {$monitorsInFile->count()} monitor(s) to database");
}
protected function createOrUpdateMonitor(array $monitorAttributes)
{
Monitor::firstOrNew([
'url' => $monitorAttributes['url'],
])
->fill($monitorAttributes)
->save();
}
protected function deleteMissingMonitors($monitorsInFile)
{
if (! $this->option('delete-missing')) {
return;
}
Monitor::all()
->reject(function (Monitor $monitor) use ($monitorsInFile) {
return $monitorsInFile->contains('url', $monitor->url);
})
->each(function (Monitor $monitor) {
$path = $this->argument('path');
$this->comment("Deleted monitor for `{$monitor->url}` from database because it was not found in `{$path}`");
$monitor->delete();
});
}
}
<file_sep>/tests/Integration/Notifications/EventHandlerTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Notifications;
use Carbon\Carbon;
use Notification;
use Spatie\UptimeMonitor\Events\CertificateCheckFailed;
use Spatie\UptimeMonitor\Events\UptimeCheckFailed as UptimeCheckFailedEvent;
use Spatie\UptimeMonitor\Events\UptimeCheckRecovered as UptimeCheckRecoveredEvent;
use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded as UptimeCheckSucceededEvent;
use Spatie\UptimeMonitor\Helpers\Period;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Notifications\Notifiable;
use Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckSucceeded as InvalidCertificateFoundNotification;
use Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckFailed;
use Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckRecovered;
use Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckSucceeded;
use Spatie\UptimeMonitor\Test\TestCase;
class EventHandlerTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Models\Monitor */
protected $monitor;
public function setUp(): void
{
parent::setUp();
Notification::fake();
}
/**
* @test
*
* @dataProvider eventClassDataProvider
*/
public function it_can_send_a_notifications_for_certain_events(
$eventClass,
$notificationClass,
$monitorAttributes,
$shouldSendNotification
) {
$this->app['config']->set(
'uptime-monitor.notifications.notifications.'.UptimeCheckSucceeded::class,
['slack']
);
$monitor = Monitor::factory()->create($monitorAttributes);
if (in_array($eventClass, [
UptimeCheckFailedEvent::class,
UptimeCheckRecoveredEvent::class,
])) {
event(new $eventClass($monitor, new Period(Carbon::now(), Carbon::now())));
} else {
event(new $eventClass($monitor));
}
if ($shouldSendNotification) {
Notification::assertSentTo(
new Notifiable(),
$notificationClass,
function ($notification) use ($monitor) {
return $notification->event->monitor->id == $monitor->id;
}
);
}
if (! $shouldSendNotification) {
Notification::assertNotSentTo(
new Notifiable(),
$notificationClass
);
}
}
public function eventClassDataProvider(): array
{
return [
[UptimeCheckSucceededEvent::class, UptimeCheckSucceeded::class, ['uptime_status' => UptimeStatus::UP], true],
[UptimeCheckSucceededEvent::class, UptimeCheckSucceeded::class, ['uptime_status' => UptimeStatus::DOWN], false],
[UptimeCheckFailedEvent::class, UptimeCheckFailed::class, ['uptime_status' => UptimeStatus::DOWN], true],
[UptimeCheckFailedEvent::class, UptimeCheckFailed::class, ['uptime_status' => UptimeStatus::UP], false],
[UptimeCheckRecoveredEvent::class, UptimeCheckRecovered::class, ['uptime_status' => UptimeStatus::UP], true],
[UptimeCheckRecoveredEvent::class, UptimeCheckRecovered::class, ['uptime_status' => UptimeStatus::DOWN], false],
];
}
public function it_send_a_notification_when_the_invalid_certificate_event_is_fired()
{
$monitor = Monitor::factory()->create();
event(new CertificateCheckFailed($monitor, 'fail reason'));
Notification::assertSentTo(
new Notifiable(),
InvalidCertificateFoundNotification::class,
function ($notification) use ($monitor) {
return $notification->event->monitor->id == $monitor->id;
}
);
}
/**
* @test
*
* @dataProvider channelDataProvider
*/
public function it_send_notifications_to_the_channels_configured_in_the_config_file(array $configuredChannels)
{
$this->app['config']->set(
'uptime-monitor.notifications.notifications.'.UptimeCheckSucceeded::class,
$configuredChannels
);
$monitor = Monitor::factory()->create();
event(new UptimeCheckSucceededEvent($monitor));
Notification::assertSentTo(
new Notifiable(),
UptimeCheckSucceeded::class,
function ($notification, $usedChannels) use ($configuredChannels) {
return $usedChannels == $configuredChannels;
}
);
}
public function channelDataProvider(): array
{
return [
[['mail']],
[['mail', 'slack']],
];
}
}
<file_sep>/src/Helpers/UptimeResponseCheckers/LookForStringChecker.php
<?php
namespace Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers;
use Illuminate\Support\Str;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Models\Monitor;
class LookForStringChecker implements UptimeResponseChecker
{
public function isValidResponse(ResponseInterface $response, Monitor $monitor): bool
{
if (empty($monitor->look_for_string)) {
return true;
}
return Str::contains((string) $response->getBody(), $monitor->look_for_string);
}
public function getFailureReason(ResponseInterface $response, Monitor $monitor): string
{
return "String `{$monitor->look_for_string}` was not found on the response.";
}
}
<file_sep>/docs/advanced-usage/customizing-the-uptime-check.md
---
title: Customizing the uptime check
weight: 3
---
This package ships with a default configured uptime check. You can modify the behaviour of the uptime check by changing the values under the `uptime_check` key in the config file.
These are the default values:
```php
'uptime_check' => [
/*
* When the uptime check could reach the url of a monitor it will pass the response to this class
* If this class determines the response is valid, the uptime check will be regarded as succeeded.
*
* You can use any implementation of Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker here.
*/
'response_checker' => Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\LookForStringChecker::class,
/*
* An uptime check will be performed if the last check was performed more than the
* given number of minutes ago. If you change this setting you have to manually
* update the `uptime_check_interval_in_minutes` value of your existing monitors.
*
* When an uptime check fails we'll check the uptime for that montitor every time `monitor:check-uptime`
* runs regardless of this setting.
*/
'run_interval_in_minutes' => 5,
/*
* To speed up the uptime checking process the package can perform the uptime check of several
* monitors concurrently. Set this to a lower value if you're getting weird errors
* running the uptime check.
*/
'concurrent_checks' => 10,
/*
* The uptime check for a monitor will fail if url does not respond after the
* given number of seconds.
*/
'timeout_per_site' => 10,
/*
* Fire `Spatie\UptimeMonitor\Events\MonitorFailed` event only after
* the given number of uptime checks have consecutively failed for a monitor.
*/
'fire_monitor_failed_event_after_consecutive_failures' => 2,
/*
* When reaching out to sites this user agent will be used.
*/
'user_agent' => 'spatie/laravel-uptime-monitor uptime checker',
/*
* When reaching out to the sites these headers will be added.
*/
'additional_headers' => [],
],
```
<file_sep>/tests/Integration/Commands/DisableMonitorCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class DisableMonitorCommandTest extends TestCase
{
/** @test */
public function it_can_disable_an_enabled_monitor()
{
$monitor = Monitor::factory()->create([
'uptime_check_enabled' => true,
'url' => 'http://mysite.com',
]);
$this->assertTrue($monitor->fresh()->uptime_check_enabled);
$this->artisan('monitor:disable', ['url' => 'http://mysite.com']);
$this->assertFalse($monitor->fresh()->uptime_check_enabled);
}
/** @test */
public function it_displays_a_message_if_the_monitor_is_not_found()
{
Artisan::call('monitor:disable', ['url' => 'https://mysite.com']);
$this->seeInConsoleOutput('There is no monitor configured for url');
}
/** @test */
public function it_can_disable_multiple_urls_at_once()
{
$monitor1 = Monitor::factory()->create([
'uptime_check_enabled' => true,
'url' => 'http://mysite.com',
]);
$monitor2 = Monitor::factory()->create([
'uptime_check_enabled' => true,
'url' => 'http://mysite2.com',
]);
$this->artisan('monitor:disable', ['url' => 'http://mysite.com, http://mysite2.com']);
$this->assertFalse($monitor1->fresh()->uptime_check_enabled);
$this->assertFalse($monitor2->fresh()->uptime_check_enabled);
}
}
<file_sep>/tests/server/public/index.php
<?php
use Illuminate\Http\Request;
require_once __DIR__.'/../vendor/autoload.php';
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$storagePath = __DIR__.'/../storage/server-status-code.json';
$app->router->get('/', function () use ($storagePath) {
if (! file_exists($storagePath)) {
return response('Site is up', 200);
}
$response = json_decode(file_get_contents($storagePath), true);
if ($response['statusCode'] == 301) {
return redirect(url('/notfound'), 301);
}
return response($response['body'], $response['statusCode']);
});
$app->router->post('/setServerResponse', function (Request $request) use ($storagePath) {
$response = json_encode($request->all(), true);
file_put_contents($storagePath, $response);
});
$app->router->post('/testPost', function (Request $request) {
if ($request->get('foo') !== 'bar' && $request->header('Content-Type') !== 'application/json') {
return response(null, 500);
}
return response(null, 200);
});
$app->router->get('booted', function () {
return 'app has booted';
});
$app->run();
<file_sep>/database/migrations/create_monitors_table.php.stub
<?php
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMonitorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('monitors', function (Blueprint $table) {
$table->increments('id');
$table->string('url')->unique();
$table->boolean('uptime_check_enabled')->default(true);
$table->string('look_for_string')->default('');
$table->string('uptime_check_interval_in_minutes')->default(5);
$table->string('uptime_status')->default(UptimeStatus::NOT_YET_CHECKED);
$table->text('uptime_check_failure_reason')->nullable();
$table->integer('uptime_check_times_failed_in_a_row')->default(0);
$table->timestamp('uptime_status_last_change_date')->nullable();
$table->timestamp('uptime_last_check_date')->nullable();
$table->timestamp('uptime_check_failed_event_fired_on_date')->nullable();
$table->string('uptime_check_method')->default('get');
$table->text('uptime_check_payload')->nullable();
$table->text('uptime_check_additional_headers')->nullable();
$table->string('uptime_check_response_checker')->nullable();
$table->boolean('certificate_check_enabled')->default(false);
$table->string('certificate_status')->default(CertificateStatus::NOT_YET_CHECKED);
$table->timestamp('certificate_expiration_date')->nullable();
$table->string('certificate_issuer')->nullable();
$table->string('certificate_check_failure_reason')->default('');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('monitors');
}
}
<file_sep>/src/Commands/CheckUptime.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class CheckUptime extends BaseCommand
{
protected $signature = 'monitor:check-uptime
{--url= : Only check these urls}
{--f|force : Force run all monitors }';
protected $description = 'Check the uptime of all sites';
public function handle()
{
$monitors = $this->option('force') ? MonitorRepository::getEnabled() : MonitorRepository::getForUptimeCheck();
if ($url = $this->option('url')) {
$monitors = $monitors->filter(function (Monitor $monitor) use ($url) {
return in_array((string) $monitor->url, explode(',', $url));
});
}
$this->comment('Start checking the uptime of '.count($monitors).' monitors...');
$monitors->checkUptime();
$this->info('All done!');
}
}
<file_sep>/src/Commands/CreateMonitor.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\Url\Url;
class CreateMonitor extends BaseCommand
{
protected $signature = 'monitor:create {url}';
protected $description = 'Create a monitor';
public function handle()
{
$url = Url::fromString($this->argument('url'));
if (! in_array($url->getScheme(), ['http', 'https'])) {
if ($scheme = $this->choice("Which protocol needs to be used for checking `{$url}`?", [1 => 'https', 2 => 'http'], 1)) {
$url = $url->withScheme($scheme);
}
}
if ($this->confirm('Should we look for a specific string on the response?')) {
$lookForString = $this->ask('Which string?');
}
$monitor = Monitor::create([
'url' => trim($url, '/'),
'look_for_string' => $lookForString ?? '',
'uptime_check_method' => isset($lookForString) ? 'get' : 'head',
'certificate_check_enabled' => $url->getScheme() === 'https',
'uptime_check_interval_in_minutes' => config('uptime-monitor.uptime_check.run_interval_in_minutes'),
]);
$this->warn("{$monitor->url} will be monitored!");
}
}
<file_sep>/docs/advanced-usage/customizing-notifications.md
---
title: Customizing notifications
weight: 4
---
This package leverages [Laravel's native notification capabilites](https://laravel.com/docs/5.4/notifications) to send out [several](https://docs.spatie.be/laravel-uptime-monitor/v3/monitoring-uptime/notifications) [notifications](https://docs.spatie.be/laravel-uptime-monitor/v3/monitoring-ssl-certificates/notifications).
```php
'notifications' => [
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckRecovered::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckSucceeded::class => [],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateExpiresSoon::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckSucceeded::class => [],
],
```
Notice that the config keys are fully qualified class names of the `Notification` classes. All notifications have support for `slack` and `mail` out of the box. If you want to add support for more channels or just want to use change some text in the notifications you can specify your own notification classes in the config file. When creating custom notifications, it's probably best to extend the default ones shipped with this package.
<file_sep>/docs/monitoring-uptime/notifications.md
---
title: Notifications
weight: 3
---
The package notifies you if certain events take place when running the uptime check. You can specify which channels the notifications for certain events should be sent in the config file. If you don't want any notifications for a certain event, just pass an empty array. Out of the box `slack` and `mail` are supported. If you want to use another channel or modify the notifications, read the section on [customizing notifications](https://docs.spatie.be/laravel-uptime-monitor/v3/advanced-usage/customizing-notifications).
## UptimeCheckFailed
`Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckFailed`
This notification will be sent when the `Spatie\UptimeMonitor\Events\UptimeCheckFailed` event is fired.
This is how the notification looks in Slack.
<img src="./../images/monitor-failed.jpg" class="screenshot -slack" />
## UptimeCheckRecovered
`Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckRecovered`
This notification will be sent when the `Spatie\UptimeMonitor\Events\UptimeCheckRecovered` event is fired.
This is how the notification looks in Slack.
<img src="./../images/monitor-recovered.jpg" class="screenshot -slack" />
## UptimeCheckSucceeded
`Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckSucceeded`
This notification will be sent when the `Spatie\UptimeMonitor\Events\UptimeCheckSucceeded` event is fired.
You probably don't want to be notified of this event as it is fired many many times.
<file_sep>/src/Notifications/BaseNotification.php
<?php
namespace Spatie\UptimeMonitor\Notifications;
use Illuminate\Notifications\Notification;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Monitor;
abstract class BaseNotification extends Notification
{
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return config('uptime-monitor.notifications.notifications.'.static::class);
}
public function getMonitor(): Monitor
{
return $this->event->monitor;
}
public function getMonitorProperties($extraProperties = []): array
{
$monitor = $this->getMonitor();
$properties = array_merge([], $extraProperties);
if ($monitor->certificate_check_enabled && $monitor->certificate_status === CertificateStatus::VALID) {
$certificateTitle = "Certificate expires in {$monitor->formattedCertificateExpirationDate('forHumans')}";
$certificateIssuer = $monitor->certificate_issuer;
$properties[$certificateTitle] = $certificateIssuer;
}
return array_filter($properties);
}
public function getLocationDescription(): string
{
$configuredLocation = config('uptime-monitor.notifications.location');
if ($configuredLocation == '') {
return '';
}
return "Monitor {$configuredLocation}";
}
public function isStillRelevant(): bool
{
return true;
}
}
<file_sep>/src/Commands/MonitorLists/Healthy.php
<?php
namespace Spatie\UptimeMonitor\Commands\MonitorLists;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class Healthy
{
public static function display()
{
$healthyMonitor = MonitorRepository::getHealthy();
if (! $healthyMonitor->count()) {
return;
}
ConsoleOutput::info('Healthy monitors');
ConsoleOutput::info('================');
$rows = $healthyMonitor->map(function (Monitor $monitor) {
$certificateFound = '';
$certificateExpirationDate = '';
$certificateIssuer = '';
$url = $monitor->url;
$reachable = $monitor->uptimeStatusAsEmoji;
$onlineSince = $monitor->formattedLastUpdatedStatusChangeDate('forHumans');
if ($monitor->certificate_check_enabled) {
$certificateFound = $monitor->certificateStatusAsEmoji;
$certificateExpirationDate = $monitor->formattedCertificateExpirationDate('forHumans');
$certificateIssuer = $monitor->certificate_issuer;
}
return compact('url', 'reachable', 'onlineSince', 'certificateFound', 'certificateExpirationDate', 'certificateIssuer');
});
$titles = ['URL', 'Uptime check', 'Online since', 'Certificate check', 'Certificate Expiration date', 'Certificate Issuer'];
ConsoleOutput::table($titles, $rows);
ConsoleOutput::line('');
}
}
<file_sep>/src/Commands/EnableMonitor.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\MonitorRepository;
class EnableMonitor extends BaseCommand
{
protected $signature = 'monitor:enable {url}';
protected $description = 'Enable a monitor';
public function handle()
{
foreach (explode(',', $this->argument('url')) as $url) {
$this->enableMonitor(trim($url));
}
}
protected function enableMonitor(string $url)
{
if (! $monitor = MonitorRepository::findByUrl($url)) {
$this->error("There is no monitor configured for url `{$url}`.");
return;
}
$monitor->enable();
$this->info("The checks for url `{$url}` are now enabled.");
}
}
<file_sep>/config/uptime-monitor.php
<?php
return [
/*
* You can get notified when specific events occur. Out of the box you can use 'mail'
* and 'slack'. Of course you can also specify your own notification classes.
*/
'notifications' => [
'notifications' => [
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckRecovered::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\UptimeCheckSucceeded::class => [],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckFailed::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateExpiresSoon::class => ['slack'],
\Spatie\UptimeMonitor\Notifications\Notifications\CertificateCheckSucceeded::class => [],
],
/*
* The location from where you are running this Laravel application. This location will be
* mentioned in all notifications that will be sent.
*/
'location' => '',
/*
* To keep reminding you that a site is down, notifications
* will be resent every given number of minutes.
*/
'resend_uptime_check_failed_notification_every_minutes' => 60,
'mail' => [
'to' => ['<EMAIL>'],
],
'slack' => [
'webhook_url' => env('UPTIME_MONITOR_SLACK_WEBHOOK_URL'),
],
/*
* Here you can specify the notifiable to which the notifications should be sent. The default
* notifiable will use the variables specified in this config file.
*/
'notifiable' => \Spatie\UptimeMonitor\Notifications\Notifiable::class,
/*
* The date format used in notifications.
*/
'date_format' => 'd/m/Y',
],
'uptime_check' => [
/*
* When the uptime check could reach the url of a monitor it will pass the response to this class
* If this class determines the response is valid, the uptime check will be regarded as succeeded.
*
* You can use any implementation of Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker here.
*/
'response_checker' => Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\LookForStringChecker::class,
/*
* An uptime check will be performed if the last check was performed more than the
* given number of minutes ago. If you change this setting you have to manually
* update the `uptime_check_interval_in_minutes` value of your existing monitors.
*
* When an uptime check fails we'll check the uptime for that monitor every time `monitor:check-uptime`
* runs regardless of this setting.
*/
'run_interval_in_minutes' => 5,
/*
* To speed up the uptime checking process the package can perform the uptime check of several
* monitors concurrently. Set this to a lower value if you're getting weird errors
* running the uptime check.
*/
'concurrent_checks' => 10,
/*
* The uptime check for a monitor will fail if the url does not respond after the
* given number of seconds.
*/
'timeout_per_site' => 10,
/*
* Because networks can be a bit unreliable the package can make three attempts
* to connect to a server in one uptime check. You can specify the time in
* milliseconds between each attempt.
*/
'retry_connection_after_milliseconds' => 100,
/*
* If you want to change the default Guzzle client behaviour, you can do so by
* passing custom options that will be used when making requests.
*/
'guzzle_options' => [
// 'allow_redirects' => false,
],
/*
* Fire `Spatie\UptimeMonitor\Events\MonitorFailed` event only after
* the given number of uptime checks have consecutively failed for a monitor.
*/
'fire_monitor_failed_event_after_consecutive_failures' => 2,
/*
* When reaching out to sites this user agent will be used.
*/
'user_agent' => 'spatie/laravel-uptime-monitor uptime checker',
/*
* When reaching out to the sites these headers will be added.
*/
'additional_headers' => [],
],
'certificate_check' => [
/*
* The `Spatie\UptimeMonitor\Events\SslExpiresSoon` event will fire
* when a certificate is found whose expiration date is in
* the next number of given days.
*/
'fire_expiring_soon_event_if_certificate_expires_within_days' => 10,
],
/*
* To add or modify behaviour to the Monitor model you can specify your
* own model here. The only requirement is that it should extend
* `Spatie\UptimeMonitor\Models\Monitor`.
*/
'monitor_model' => Spatie\UptimeMonitor\Models\Monitor::class,
];
<file_sep>/src/Exceptions/InvalidPeriod.php
<?php
namespace Spatie\UptimeMonitor\Exceptions;
use Carbon\CarbonInterface;
use Exception;
class InvalidPeriod extends Exception
{
public static function startDateMustComeBeforeEndDate(CarbonInterface $startDateTime, CarbonInterface $endDateTime): self
{
return new static("The given startDateTime `{$startDateTime->toIso8601String()}` is not before `{$endDateTime->toIso8601String()}`");
}
}
<file_sep>/tests/Integration/Commands/EnableMonitorCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Illuminate\Support\Facades\Artisan;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class EnableMonitorCommandTest extends TestCase
{
/** @test */
public function it_can_enable_a_disabled_monitor()
{
$monitor = Monitor::factory()->create([
'uptime_check_enabled' => false,
'certificate_check_enabled' => false,
'url' => 'https://mysite.com',
]);
$this->assertFalse($monitor->fresh()->uptime_check_enabled);
$this->artisan('monitor:enable', ['url' => 'https://mysite.com']);
$monitor = $monitor->fresh();
$this->assertTrue($monitor->uptime_check_enabled);
$this->assertTrue($monitor->certificate_check_enabled);
}
/** @test */
public function it_will_only_not_enable_the_uptime_check_if_the_url_starts_with_http()
{
$monitor = Monitor::factory()->create([
'uptime_check_enabled' => false,
'certificate_check_enabled' => false,
'url' => 'http://mysite.com',
]);
$this->assertFalse($monitor->fresh()->uptime_check_enabled);
$this->artisan('monitor:enable', ['url' => 'http://mysite.com']);
$monitor = $monitor->fresh();
$this->assertTrue($monitor->uptime_check_enabled);
$this->assertFalse($monitor->certificate_check_enabled);
}
/** @test */
public function it_displays_a_message_if_the_monitor_is_not_found()
{
Artisan::call('monitor:enable', ['url' => 'https://mysite.com']);
$this->seeInConsoleOutput('There is no monitor configured for url');
}
/** @test */
public function it_can_enable_multiple_urls_at_once()
{
$monitor1 = Monitor::factory()->create([
'uptime_check_enabled' => false,
'certificate_check_enabled' => false,
'url' => 'https://mysite.com',
]);
$monitor2 = Monitor::factory()->create([
'uptime_check_enabled' => false,
'certificate_check_enabled' => false,
'url' => 'http://mysite2.com',
]);
$this->artisan('monitor:enable', ['url' => 'https://mysite.com, http://mysite2.com']);
$this->assertTrue($monitor1->fresh()->uptime_check_enabled);
$this->assertTrue($monitor2->fresh()->uptime_check_enabled);
$monitor1 = $monitor1->fresh();
$monitor2 = $monitor2->fresh();
$this->assertTrue($monitor1->uptime_check_enabled);
$this->assertTrue($monitor1->certificate_check_enabled);
$this->assertTrue($monitor2->uptime_check_enabled);
$this->assertFalse($monitor2->certificate_check_enabled);
}
}
<file_sep>/src/Models/Traits/SupportsCertificateCheck.php
<?php
namespace Spatie\UptimeMonitor\Models\Traits;
use Exception;
use Spatie\SslCertificate\SslCertificate;
use Spatie\UptimeMonitor\Events\CertificateCheckFailed;
use Spatie\UptimeMonitor\Events\CertificateCheckSucceeded;
use Spatie\UptimeMonitor\Events\CertificateExpiresSoon;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Monitor;
trait SupportsCertificateCheck
{
public function checkCertificate(): void
{
try {
$certificate = SslCertificate::createForHostName($this->url->getHost());
$this->setCertificate($certificate);
} catch (Exception $exception) {
$this->setCertificateException($exception);
}
}
public function setCertificate(SslCertificate $certificate): void
{
$this->certificate_status = $certificate->isValid($this->url)
? CertificateStatus::VALID
: CertificateStatus::INVALID;
$this->certificate_expiration_date = $certificate->expirationDate();
$this->certificate_issuer = $certificate->getIssuer();
$this->save();
$this->fireEventsForUpdatedMonitorWithCertificate($this, $certificate);
}
public function setCertificateException(Exception $exception): void
{
$this->certificate_status = CertificateStatus::INVALID;
$this->certificate_expiration_date = null;
$this->certificate_issuer = '';
$this->certificate_check_failure_reason = $exception->getMessage();
$this->save();
event(new CertificateCheckFailed($this, $exception->getMessage()));
}
protected function fireEventsForUpdatedMonitorWithCertificate(Monitor $monitor, SslCertificate $certificate): void
{
if ($this->certificate_status === CertificateStatus::VALID) {
event(new CertificateCheckSucceeded($this, $certificate));
if ($certificate->expirationDate()->diffInDays() <= config('uptime-monitor.certificate_check.fire_expiring_soon_event_if_certificate_expires_within_days')) {
event(new CertificateExpiresSoon($monitor, $certificate));
}
return;
}
if ($this->certificate_status === CertificateStatus::INVALID) {
$reason = 'Unknown';
if (! $certificate->appliesToUrl($this->url)) {
$reason = "Certificate does not apply to {$this->url} but only to these domains: ".implode(',', $certificate->getAdditionalDomains());
}
if ($certificate->isExpired()) {
$reason = 'The certificate has expired';
}
$this->certificate_check_failure_reason = $reason;
$this->save();
event(new CertificateCheckFailed($this, $reason, $certificate));
}
}
}
<file_sep>/tests/Integration/Commands/CheckCertificatesTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class CheckCertificatesTest extends TestCase
{
/** @test */
public function it_has_a_command_to_check_certificates()
{
$monitor = Monitor::factory()->create(['certificate_check_enabled' => true]);
Artisan::call('monitor:check-certificate');
$monitor = $monitor->fresh();
$this->assertEquals(CertificateStatus::INVALID, $monitor->certificate_status);
$this->seeInConsoleOutput("Checking certificate of {$monitor->url}");
}
/** @test */
public function it_can_check_the_certificate_for_a_specific_monitor()
{
$monitor1 = Monitor::factory()->create(['certificate_check_enabled' => true]);
$monitor2 = Monitor::factory()->create([
'url' => 'https://google.com',
'certificate_check_enabled' => true,
]);
Artisan::call('monitor:check-certificate', ['--url' => $monitor1->url]);
$output = Artisan::output();
$this->assertStringContainsString("Checking certificate of {$monitor1->url}", $output);
$this->assertStringNotContainsString("Checking certificate of {$monitor2->url}", $output);
}
/** @test */
public function it_can_check_the_certificates_for_a_specific_set_of_monitors()
{
$monitor1 = Monitor::factory()->create(['certificate_check_enabled' => false]);
$monitor2 = Monitor::factory()->create([
'url' => 'https://google.com',
'certificate_check_enabled' => true,
]);
$monitor3 = Monitor::factory()->create([
'url' => 'https://bing.com',
'certificate_check_enabled' => true,
]);
Artisan::call('monitor:check-certificate', ['--url' => $monitor2->url.','.$monitor3->url]);
$output = Artisan::output();
$this->assertStringNotContainsString("Checking certificate of {$monitor1->url}", $output);
$this->assertStringContainsString("Checking certificate of {$monitor2->url}", $output);
$this->assertStringContainsString("Checking certificate of {$monitor3->url}", $output);
}
}
<file_sep>/docs/introduction.md
---
title: Introduction
weight: 1
---
Laravel-uptime-monitor is a laravel package that provides a powerful, easy to configure uptime monitor. It will notify you when your site is down (and when it comes back up). You can also be notified a few days before an SSL certificate on one of your sites expires. Under the hood, the package leverages Laravel native notifications, so it's easy to use Slack, Telegram or your preferred notification provider.
## Looking for a hosted solution?
If you're looking for a hosted solution, we can highly recommend [Oh Dear](https://ohdear.app). This service can:
- perform multi-location uptime checks
- crawl your entire site and report any broken links
- check your SSL certificate
- measure your site's performance
- make sure your scheduled jobs run on time
- check if your application is healthy (by monitoring your free disk space, database, Redis, Horizon, security warnings, and more!)
- notify you of any changes to your DNS records
- monitor the expiry date of your domain
- display status pages so you can inform your users about the state of your service
## We have badges!
<section class="article_badges">
<a href="https://github.com/spatie/laravel-uptime-monitor/releases"><img src="https://img.shields.io/github/release/spatie/laravel-uptime-monitor.svg?style=flat-square" alt="Latest Version"></a>
<a href="https://github.com/spatie/laravel-uptime-monitor/blob/master/LICENSE.md"><img src="https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square" alt="Software License"></a>
<a href="https://travis-ci.org/spatie/laravel-uptime-monitor"><img src="https://img.shields.io/travis/spatie/laravel-uptime-monitor/master.svg?style=flat-square" alt="Build Status"></a>
<a href="https://scrutinizer-ci.com/g/spatie/laravel-uptime-monitor"><img src="https://img.shields.io/scrutinizer/g/spatie/laravel-uptime-monitor.svg?style=flat-square" alt="Quality Score"></a>
<a href="https://styleci.io/repos/67774357"><img src="https://styleci.io/repos/67774357/shield?branch=master" alt="StyleCI"></a>
<a href="https://packagist.org/packages/spatie/laravel-uptime-monitor"><img src="https://img.shields.io/packagist/dt/spatie/laravel-uptime-monitor.svg?style=flat-square" alt="Total Downloads"></a>
</section>
<file_sep>/docs/monitoring-ssl-certificates/events.md
---
title: Events
weight: 2
---
These events are fired by a monitor's ssl certificate check.
## CertificateCheckFailed
`Spatie\UptimeMonitor\Events\CertificateCheckFailed`
This event is fired when the certificate check cannot find a certificate or if the certificate is invalid. A certificate is considered invalid if it is expired or it not covering correct domain.
It has the following public properties:
- `$monitor`: the instance of `Spatie\UptimeMonitor\Models\Monitor` that fired the event
- `$reason`: a string explaining why the certificate check failed
- `$certificate`: if a certificate was found, this variable contains an instance of `\Spatie\SslCertificate\SslCertificate`. Refer to the [documentation of `spatie/ssl-certificate`](https://github.com/spatie/ssl-certificate) to learn how to work with this object.
## CertificateCheckSucceeded
`Spatie\UptimeMonitor\Events\CertificateCheckSucceeded`
This event is fired after the certificate check finds a valid certificate.
It has the following public properties:
- `$monitor`: the instance of `Spatie\UptimeMonitor\Models\Monitor` that fired of the event
- `$certificate`: if a valid certificate is found, this variable contains an instance of `\Spatie\SslCertificate\SslCertificate`. Refer to the [documentation of `spatie/ssl-certificate`](https://github.com/spatie/ssl-certificate) to learn how to work with this object.
## CertificateExpiresSoon
`Spatie\UptimeMonitor\Events\CertificateExpiresSoon`
This event is fired in addition to `CertificateCheckSucceeded` when the certificate check finds an ssl certificate that is going to expire in the number of days configured in `fire_expiring_soon_event_if_certificate_expires_within_days` or less.
It has these public properties:
- `$monitor`: the instance of `Spatie\UptimeMonitor\Models\Monitor` that fired the event
- `$certificate`: if an expiring certificate is found, this variable contains an instance of `\Spatie\SslCertificate\SslCertificate` Refer to the [documentation of `spatie/ssl-certificate`](https://github.com/spatie/ssl-certificate) to learn how to work with this object.
<file_sep>/src/Helpers/Period.php
<?php
namespace Spatie\UptimeMonitor\Helpers;
use Carbon\CarbonInterface;
use Spatie\UptimeMonitor\Exceptions\InvalidPeriod;
class Period
{
public CarbonInterface $startDateTime;
public CarbonInterface $endDateTime;
public function __construct(CarbonInterface $startDateTime, CarbonInterface $endDateTime)
{
if ($startDateTime->gt($endDateTime)) {
throw InvalidPeriod::startDateMustComeBeforeEndDate($startDateTime, $endDateTime);
}
$this->startDateTime = $startDateTime;
$this->endDateTime = $endDateTime;
}
public function duration(): string
{
$interval = $this->startDateTime->diff($this->endDateTime);
if (! $this->startDateTime->diffInHours($this->endDateTime)) {
return $interval->format('%im');
}
if (! $this->startDateTime->diffInDays($this->endDateTime)) {
return $interval->format('%hh %im');
}
return $interval->format('%dd %hh %im');
}
public function toText(): string
{
$configuredDateFormat = config('uptime-monitor.notifications.date_format');
return
$this->startDateTime->format('H:i').' '
.($this->startDateTime->isToday() ? '' : "on {$this->startDateTime->format($configuredDateFormat)} ")
.'➡️ '
.$this->endDateTime->format('H:i')
.($this->endDateTime->isToday() ? '' : " on {$this->endDateTime->format($configuredDateFormat)}");
}
}
<file_sep>/tests/Integration/Commands/SyncFileTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class SyncFileTest extends TestCase
{
protected $stubsDirectory = __DIR__.'/../stubs/';
public function setUp(): void
{
parent::setUp();
Monitor::create([
'url' => 'https://www.example.com',
'uptime_check_enabled' => false,
'certificate_check_enabled' => true,
]);
}
/** @test */
public function it_can_create_monitors()
{
Artisan::call('monitor:sync-file', ['path' => $this->stubsDirectory.'sync-file-original.json']);
$this->seeInConsoleOutput('Synced 2 monitor(s) to database');
$importMonitor1 = Monitor::where('url', 'https://www.https-example2.com')->first();
$importMonitor2 = Monitor::where('url', 'http://www.http-example2.com')->first();
$this->assertTrue($importMonitor1->uptime_check_enabled);
$this->assertTrue($importMonitor1->certificate_check_enabled);
$this->assertFalse($importMonitor2->uptime_check_enabled);
$this->assertFalse($importMonitor2->certificate_check_enabled);
}
/** @test */
public function it_throws_an_exception_for_invalid_urls()
{
$this->expectException(CannotSaveMonitor::class);
Artisan::call('monitor:sync-file', ['path' => $this->stubsDirectory.'sync-file-invalid.json']);
$this->assertEmpty(Monitor::where('url', 'www.example.com'));
}
/** @test */
public function it_can_update_existing_monitors()
{
Artisan::call('monitor:sync-file', ['path' => $this->stubsDirectory.'sync-file-update.json']);
$this->seeInConsoleOutput('Synced 1 monitor(s) to database');
$updatedMonitor = Monitor::where('url', 'https://www.example.com')->first();
$this->assertFalse($updatedMonitor->uptime_check_enabled);
$this->assertTrue($updatedMonitor->certificate_check_enabled);
}
/** @test */
public function it_can_delete_monitors_not_found_in_file()
{
Artisan::call('monitor:sync-file', [
'path' => $this->stubsDirectory.'sync-file-original.json',
'--delete-missing' => true,
]);
$deletedMonitor = Monitor::where('url', 'https://www.example.com')->first();
$this->seeInConsoleOutput('Deleted monitor for `https://www.example.com`');
$this->assertEmpty($deletedMonitor);
}
}
<file_sep>/docs/advanced-usage/using-your-own-model.md
---
title: Using your own model
weight: 6
---
By default this package uses the `Spatie\UptimeMonitor\Models\Monitor` model. If you want add some extra functionality you can specify your own model in the `monitor_model` key of the config file. The only requirement for your custom model is that is should extend `Spatie\UptimeMonitor\Models\Monitor`.
<file_sep>/docs/high-level-overview.md
---
title: High level overview
weight: 5
---
## Monitoring uptime
This package can monitor the uptime of sites, api endpoints, or anything that communicates over `http` or `https`. To create a monitor use the `monitor:create` command. This will create a row in the `monitors` table.
The `monitor:check-uptime` task [should be scheduled](https://docs.spatie.be/laravel-uptime-monitor/v3/installation-and-setup#scheduling) to run every minute. When it runs it will send a request to the `url` of every configured monitor. The package can perform requests concurrently, so don't be afraid to configure a large number of monitors.
If a request succeeds the `Spatie\UptimeMonitor\Events\UptimeCheckSucceeded`-event will fire. The uptime of the monitor will be checked again when `monitor:check-uptime` runs after the interval set in the `uptime_check_interval_in_minutes` key in the config file.
When an uptime check fails the uptime check for that monitor will be performed any time `monitor:check-uptime` runs regardless of the value configured in `uptime_check_interval_in_minutes`.
If an uptime check fails consecutively more times than the value you set in `fire_monitor_failed_event_after_consecutive_failures` the `Spatie\UptimeMonitor\Events\UptimeCheckFailed` event will fire.
If an uptime check is successful after failing, the `Spatie\UptimeMonitor\Events\UptimeCheckRecovered` will be fired.
## Monitoring SSL certificates
The package can verify if the ssl certificate of a monitor is valid. By default all monitors whose `url` starts with `https` will be checked. This is done by the `monitor:check-certificate` command which should be scheduled to run daily at least.
When a valid certificate for a monitor is found the `Spatie\UptimeMonitor\Events\CertificateCheckSucceeded` event will fire. If no valid certificate is found, the `Spatie\UptimeMonitor\Events\CertificateCheckFailed` event will be unleashed!
If a valid certificate is found, but it will expire in less days than the value set in `fire_expiring_soon_event_if_certificate_expires_within_days` the `Spatie\UptimeMonitor\Events\CertificateExpiresSoon` event is fired.
<file_sep>/src/MonitorRepository.php
<?php
namespace Spatie\UptimeMonitor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Spatie\UptimeMonitor\Exceptions\InvalidConfiguration;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
class MonitorRepository
{
public static function getEnabled(): Collection
{
$monitors = self::query()->get();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getDisabled(): Collection
{
$modelClass = static::determineMonitorModel();
$monitors = $modelClass::where('uptime_check_enabled', false)
->where('certificate_check_enabled', false)
->get();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getForUptimeCheck(): MonitorCollection
{
$monitors = self::query()->get()->filter->shouldCheckUptime();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getForCertificateCheck(): Collection
{
$monitors = self::query()
->where('certificate_check_enabled', true)
->get();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getHealthy(): Collection
{
$monitors = self::query()->get()->filter->isHealthy();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getWithFailingUptimeCheck(): Collection
{
$monitors = self::query()
->where('uptime_check_enabled', true)
->where('uptime_status', UptimeStatus::DOWN)
->get();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getWithFailingCertificateCheck(): Collection
{
$monitors = self::query()
->where('certificate_check_enabled', true)
->where('certificate_status', CertificateStatus::INVALID)
->get();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getUnhealthy(): Collection
{
$monitors = self::query()->get()->reject->isHealthy();
return MonitorCollection::make($monitors)->sortByHost();
}
public static function getUnchecked(): Collection
{
$modelClass = static::determineMonitorModel();
$monitors = $modelClass::where(function (Builder $query) {
$query
->where('uptime_check_enabled', true)
->where('uptime_status', UptimeStatus::NOT_YET_CHECKED);
})
->orWhere(function (Builder $query) {
$query
->where('certificate_check_enabled', true)
->where('certificate_status', CertificateStatus::NOT_YET_CHECKED);
})
->get();
return MonitorCollection::make($monitors)->sortByHost();
}
/**
* @param string|\Spatie\Url\Url $url
*
* @return \Spatie\UptimeMonitor\Models\Monitor
*/
public static function findByUrl($url)
{
$model = static::determineMonitorModel();
return $model::where('url', (string) $url)->first();
}
protected static function query()
{
$modelClass = static::determineMonitorModel();
return $modelClass::enabled();
}
protected static function determineMonitorModel(): string
{
$monitorModel = config('uptime-monitor.monitor_model') ?? Monitor::class;
if (! is_a($monitorModel, Monitor::class, true)) {
throw InvalidConfiguration::modelIsNotValid($monitorModel);
}
return $monitorModel;
}
}
<file_sep>/src/Exceptions/CannotSaveMonitor.php
<?php
namespace Spatie\UptimeMonitor\Exceptions;
use Exception;
use Spatie\UptimeMonitor\Models\Monitor;
class CannotSaveMonitor extends Exception
{
public static function alreadyExists(Monitor $monitor): self
{
return new static("Could not save a monitor for url `{$monitor->url}` because there already exists another monitor with the same url. ".
'Try saving a monitor with a different url.');
}
}
<file_sep>/docs/monitoring-ssl-certificates/_index.md
---
title: Monitoring ssl certificates
weight: 2
---
<file_sep>/tests/Server.php
<?php
namespace Spatie\UptimeMonitor\Test;
use GuzzleHttp\Client;
class Server
{
public const ENV_SERVER_PORT = 'TEST_SERVER_PORT';
/** @var \GuzzleHttp\Client */
protected $client;
public function __construct(Client $client)
{
static::boot();
$this->client = $client;
$this->up();
}
public function up()
{
$this->setResponseBody('Site is up', 200);
}
public function down()
{
$this->setResponseBody('Site is down', 503);
}
public function setResponseBody(string $text, int $statusCode = 200)
{
$this->client->post(static::getServerUrl('setServerResponse'), [
'form_params' => [
'statusCode' => $statusCode,
'body' => $text,
],
]);
}
public static function boot()
{
if (empty(getenv(self::ENV_SERVER_PORT))) {
throw new \InvalidArgumentException(sprintf('`%s` environment variable is not set', self::ENV_SERVER_PORT));
}
if (! file_exists(__DIR__.'/server/vendor')) {
exec('cd "'.__DIR__.'/server"; composer install');
}
if (static::serverHasBooted()) {
return;
}
$pid = exec('php -S '.static::getServerUrl().' -t ./tests/server/public > /dev/null 2>&1 & echo $!');
while (! static::serverHasBooted()) {
usleep(1000);
}
register_shutdown_function(function () use ($pid) {
exec('kill '.$pid);
});
}
public static function getServerUrl(string $endPoint = ''): string
{
return rtrim(sprintf('localhost:%s/%s', getenv('TEST_SERVER_PORT'), $endPoint), '/');
}
public static function serverHasBooted(): bool
{
return @file_get_contents('http://'.self::getServerUrl('booted')) != false;
}
}
<file_sep>/tests/Integration/Helpers/PeriodTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Helpers;
use Carbon\Carbon;
use Spatie\UptimeMonitor\Exceptions\InvalidPeriod;
use Spatie\UptimeMonitor\Helpers\Period;
use Spatie\UptimeMonitor\Test\TestCase;
class PeriodTest extends TestCase
{
/** @test */
public function it_will_throw_an_exception_when_the_start_date_comes_after_the_end_date()
{
$this->expectException(InvalidPeriod::class);
new Period(Carbon::now(), Carbon::now()->subMinutes(1));
}
/**
* @test
*
* @dataProvider periodDataProvider
*/
public function it_can_generate_a_string_representation_of_the_duration(int $differenceInMinutes, string $formattedString)
{
$period = new Period(Carbon::now(), Carbon::now()->addMinutes($differenceInMinutes));
$this->assertEquals($formattedString, $period->duration());
}
public function periodDataProvider(): array
{
return [
[10, '10m'],
[59, '59m'],
[60, '1h 0m'],
[61, '1h 1m'],
[100, '1h 40m'],
[1000, '16h 40m'],
[1440, '1d 0h 0m'],
];
}
/**
* @test
*
* @dataProvider textDataProvider
*/
public function it_has_a_text_representation(Carbon $startDateTime, Carbon $endDateTime, string $text)
{
$period = new Period($startDateTime, $endDateTime);
$this->assertEquals($text, $period->toText());
}
public function textDataProvider(): array
{
Carbon::setTestNow(Carbon::create(2016, 1, 1, 00, 00, 00));
return [
[Carbon::now(), Carbon::now()->addMinutes(10), '00:00 ➡️ 00:10'],
[Carbon::now()->subMinutes(10), Carbon::now(), '23:50 on 31/12/2015 ➡️ 00:00'],
[Carbon::now()->subHour(1), Carbon::now()->subMinutes(10), '23:00 on 31/12/2015 ➡️ 23:50 on 31/12/2015'],
];
}
}
<file_sep>/src/Commands/CheckCertificates.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class CheckCertificates extends BaseCommand
{
protected $signature = 'monitor:check-certificate
{--url= : Only check these urls}';
protected $description = 'Check the certificates of all sites';
public function handle()
{
$monitors = MonitorRepository::getForCertificateCheck();
if ($url = $this->option('url')) {
$monitors = $monitors->filter(function (Monitor $monitor) use ($url) {
return in_array((string) $monitor->url, explode(',', $url));
});
}
$this->comment('Start checking the certificates of '.count($monitors).' monitors...');
$monitors->each(function (Monitor $monitor) {
$this->info("Checking certificate of {$monitor->url}");
$monitor->checkCertificate();
if ($monitor->certificate_status !== CertificateStatus::VALID) {
$this->error("Could not download certificate of {$monitor->url} because: {$monitor->certificate_check_failure_reason}");
}
});
$this->info('All done!');
}
}
<file_sep>/src/Notifications/EventHandler.php
<?php
namespace Spatie\UptimeMonitor\Notifications;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Spatie\UptimeMonitor\Events\CertificateCheckFailed;
use Spatie\UptimeMonitor\Events\CertificateCheckSucceeded;
use Spatie\UptimeMonitor\Events\CertificateExpiresSoon;
use Spatie\UptimeMonitor\Events\UptimeCheckFailed;
use Spatie\UptimeMonitor\Events\UptimeCheckRecovered;
use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded;
class EventHandler
{
/** @var \Illuminate\Config\Repository */
protected $config;
public function __construct(Repository $config)
{
$this->config = $config;
}
public function subscribe(Dispatcher $events)
{
$events->listen($this->allEventClasses(), function ($event) {
$notification = $this->determineNotification($event);
if (! $notification) {
return;
}
if ($notification->isStillRelevant()) {
$notifiable = $this->determineNotifiable();
$notifiable->notify($notification);
}
});
}
protected function determineNotifiable()
{
$notifiableClass = $this->config->get('uptime-monitor.notifications.notifiable');
return app($notifiableClass);
}
protected function determineNotification($event)
{
$eventName = class_basename($event);
$notificationClass = collect($this->config->get('uptime-monitor.notifications.notifications'))
->filter(function (array $notificationChannels) {
return count($notificationChannels);
})
->keys()
->first(function ($notificationClass) use ($eventName) {
$notificationName = class_basename($notificationClass);
return $notificationName === $eventName;
});
if ($notificationClass) {
return app($notificationClass)->setEvent($event);
}
}
protected function allEventClasses(): array
{
return [
UptimeCheckFailed::class,
UptimeCheckSucceeded::class,
UptimeCheckRecovered::class,
CertificateCheckSucceeded::class,
CertificateCheckFailed::class,
CertificateExpiresSoon::class,
];
}
}
<file_sep>/src/Models/Enums/CertificateStatus.php
<?php
namespace Spatie\UptimeMonitor\Models\Enums;
class CertificateStatus
{
public const NOT_YET_CHECKED = 'not yet checked';
public const VALID = 'valid';
public const INVALID = 'invalid';
}
<file_sep>/tests/Integration/Helpers/ResponseCheckerFailureFake.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Helpers;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker;
use Spatie\UptimeMonitor\Models\Monitor;
class ResponseCheckerFailureFake implements UptimeResponseChecker
{
public const FAILURE_REASON = 'FAKE_CHECK';
public function isValidResponse(ResponseInterface $response, Monitor $monitor): bool
{
return false;
}
public function getFailureReason(ResponseInterface $response, Monitor $monitor): string
{
return self::FAILURE_REASON;
}
}
<file_sep>/src/Models/Enums/UptimeStatus.php
<?php
namespace Spatie\UptimeMonitor\Models\Enums;
class UptimeStatus
{
public const NOT_YET_CHECKED = 'not yet checked';
public const UP = 'up';
public const DOWN = 'down';
}
<file_sep>/src/Helpers/UptimeResponseCheckers/UptimeResponseChecker.php
<?php
namespace Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Models\Monitor;
interface UptimeResponseChecker
{
public function isValidResponse(ResponseInterface $response, Monitor $monitor): bool;
public function getFailureReason(ResponseInterface $response, Monitor $monitor): string;
}
<file_sep>/docs/_index.md
---
title: v3
slogan: A powerful and easy to configure uptime monitor.
githubUrl: https://github.com/spatie/laravel-uptime-monitor
branch: main
---
<file_sep>/docs/upgrading-from-v2.md
---
title: Upgrading from a previous version
weight: 4
---
## From v3 to v4
No changes were made except dropping support for older PHP and Laravel versions
## From v2 to v3
You should rename your config file from `laravel-uptime-monitor` to `uptime-monitor`.
That's it!
<file_sep>/docs/changelog.md
---
title: Changelog
weight: 8
---
All notable changes to `laravel-uptime-monitor` are documented in [the changelog on GitHub](https://github.com/spatie/laravel-uptime-monitor/blob/master/CHANGELOG.md).
<file_sep>/tests/Integration/MonitorRepositoryTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration;
use Illuminate\Support\Collection;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
use Spatie\UptimeMonitor\Test\TestCase;
use Spatie\Url\Url;
class MonitorRepositoryTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
}
/** @test */
public function it_can_get_all_enabled_monitors()
{
Monitor::create(['url' => 'http://enabled1.com', 'uptime_check_enabled' => true]);
Monitor::create(['url' => 'http://disabled1.com', 'uptime_check_enabled' => false]);
Monitor::create(['url' => 'http://enabled2.com', 'uptime_check_enabled' => true]);
Monitor::create(['url' => 'http://disabled2.com', 'uptime_check_enabled' => false]);
$enabledMonitors = MonitorRepository::getEnabled();
$this->assertEquals(['http://enabled1.com', 'http://enabled2.com'], $this->getMonitorUrls($enabledMonitors));
}
/** @test */
public function it_can_get_all_disabled_monitors()
{
Monitor::create(['url' => 'http://enabled1.com', 'uptime_check_enabled' => true]);
Monitor::create(['url' => 'http://disabled1.com', 'uptime_check_enabled' => false]);
Monitor::create(['url' => 'http://enabled2.com', 'uptime_check_enabled' => true]);
Monitor::create(['url' => 'http://disabled2.com', 'uptime_check_enabled' => false]);
$disabledMonitors = MonitorRepository::getDisabled();
$this->assertEquals(['http://disabled1.com', 'http://disabled2.com'], $this->getMonitorUrls($disabledMonitors));
}
/** @test */
public function it_can_get_all_unchecked_monitors()
{
Monitor::create(['url' => 'http://down1.com', 'uptime_status' => UptimeStatus::DOWN]);
Monitor::create(['url' => 'http://up.com', 'uptime_status' => UptimeStatus::UP]);
Monitor::create([
'url' => 'http://checked.com',
'uptime_status' => UptimeStatus::UP,
'certificate_status' => CertificateStatus::VALID,
]);
Monitor::create([
'url' => 'http://unchecked1.com',
'uptime_status' => UptimeStatus::UP,
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::NOT_YET_CHECKED,
]);
Monitor::create([
'url' => 'http://unchecked2.com',
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::NOT_YET_CHECKED,
]);
Monitor::create([
'url' => 'http://disabled1.com',
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'uptime_check_enabled' => false,
'certificate_status' => CertificateStatus::NOT_YET_CHECKED,
]);
Monitor::create([
'url' => 'http://enabled.com',
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'uptime_check_enabled' => false,
'certificate_status' => CertificateStatus::NOT_YET_CHECKED,
'certificate_check_enabled' => true,
]);
$uncheckedMonitors = MonitorRepository::getUnchecked();
$this->assertEquals(['http://enabled.com', 'http://unchecked1.com', 'http://unchecked2.com'], $this->getMonitorUrls($uncheckedMonitors));
}
/** @test */
public function it_can_get_all_monitors_that_are_failing()
{
Monitor::create(['url' => 'http://down1.com', 'uptime_status' => UptimeStatus::DOWN]);
Monitor::create(['url' => 'http://up.com', 'uptime_status' => UptimeStatus::UP]);
Monitor::create(['url' => 'http://down2.com', 'uptime_status' => UptimeStatus::DOWN]);
$failingMonitors = MonitorRepository::getWithFailingUptimeCheck();
$this->assertEquals(['http://down1.com', 'http://down2.com'], $this->getMonitorUrls($failingMonitors));
}
/** @test */
public function it_can_get_all_monitors_that_need_an_certificate_check()
{
Monitor::create(['url' => 'http://site1.com', 'uptime_check_enabled' => false, 'certificate_check_enabled' => false]);
Monitor::create(['url' => 'http://site2.com', 'uptime_check_enabled' => false, 'certificate_check_enabled' => true]);
Monitor::create(['url' => 'http://site3.com', 'uptime_check_enabled' => true, 'certificate_check_enabled' => false]);
Monitor::create(['url' => 'http://site4.com', 'uptime_check_enabled' => true, 'certificate_check_enabled' => true]);
$monitors = MonitorRepository::getForCertificateCheck();
$this->assertEquals(['http://site2.com', 'http://site4.com'], $this->getMonitorUrls($monitors));
}
/** @test */
public function it_can_get_all_monitors_with_certificate_problems()
{
Monitor::create([
'url' => 'http://site1.com',
'uptime_check_enabled' => false,
'certificate_check_enabled' => false,
'certificate_status' => CertificateStatus::INVALID,
]);
Monitor::create([
'url' => 'http://site2.com',
'uptime_check_enabled' => true,
'certificate_check_enabled' => false,
'certificate_status' => CertificateStatus::INVALID,
]);
Monitor::create([
'url' => 'http://site3.com',
'uptime_check_enabled' => true,
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::INVALID,
]);
Monitor::create([
'url' => 'http://site4.com',
'uptime_check_enabled' => true,
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::VALID,
]);
Monitor::create([
'url' => 'http://site5.com',
'uptime_check_enabled' => true,
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::NOT_YET_CHECKED,
]);
$monitors = MonitorRepository::getWithFailingCertificateCheck();
$this->assertEquals(['http://site3.com'], $this->getMonitorUrls($monitors));
}
protected function getMonitorUrls(Collection $monitors)
{
return $monitors
->pluck('url')
->map(function (Url $url) {
return trim($url, '/');
})
->toArray();
}
}
<file_sep>/docs/about-us.md
---
title: About us
weight: 9
---
[Spatie](https://spatie.be) is a webdesign agency based in Antwerp, Belgium.
Open source software is used in all projects we deliver. Laravel, Nginx, Ubuntu are just a few of the free pieces of software we use every single day. For this, we are very grateful.
When we feel we have solved a problem in a way that can help other developers, we release our code as open source software [on GitHub](https://spatie.be/opensource).
This uptime monitor package was made by [<NAME>](https://twitter.com/freekmurze) and code reviewed by [<NAME>](https://github.com/sebastiandedeyne). A big thank you to [<NAME>](https://github.com/blueclock) for proofreading and fixing errors in the docs. On GitHub you can find [a list of other contributors](https://github.com/spatie/laravel-uptime-monitor/graphs/contributors) who devoted time and effort to make this package better.
<file_sep>/src/Events/CertificateCheckSucceeded.php
<?php
namespace Spatie\UptimeMonitor\Events;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\SslCertificate\SslCertificate;
use Spatie\UptimeMonitor\Models\Monitor;
class CertificateCheckSucceeded implements ShouldQueue
{
public Monitor $monitor;
public SslCertificate $certificate;
public function __construct(Monitor $monitor, SslCertificate $certificate)
{
$this->monitor = $monitor;
$this->certificate = $certificate;
}
}
<file_sep>/src/Models/Traits/SupportsUptimeCheck.php
<?php
namespace Spatie\UptimeMonitor\Models\Traits;
use Carbon\Carbon;
use Psr\Http\Message\ResponseInterface;
use Spatie\UptimeMonitor\Events\UptimeCheckFailed;
use Spatie\UptimeMonitor\Events\UptimeCheckRecovered;
use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded;
use Spatie\UptimeMonitor\Helpers\Period;
use Spatie\UptimeMonitor\Helpers\UptimeResponseCheckers\UptimeResponseChecker;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
trait SupportsUptimeCheck
{
public static function bootSupportsUptimeCheck(): void
{
static::saving(function (Monitor $monitor) {
if (is_null($monitor->uptime_status_last_change_date)) {
$monitor->uptime_status_last_change_date = Carbon::now();
return;
}
if ($monitor->getOriginal('uptime_status') != $monitor->uptime_status) {
$monitor->uptime_status_last_change_date = Carbon::now();
}
});
}
public function shouldCheckUptime(): bool
{
if (! $this->uptime_check_enabled) {
return false;
}
if ($this->uptime_status == UptimeStatus::NOT_YET_CHECKED) {
return true;
}
if ($this->uptime_status == UptimeStatus::DOWN) {
return true;
}
if (is_null($this->uptime_last_check_date)) {
return true;
}
return $this->uptime_last_check_date->diffInMinutes() >= $this->uptime_check_interval_in_minutes;
}
public function uptimeRequestSucceeded(ResponseInterface $response): void
{
$uptimeResponseChecker = $this->uptime_check_response_checker
? app($this->uptime_check_response_checker)
: app(UptimeResponseChecker::class);
if (! $uptimeResponseChecker->isValidResponse($response, $this)) {
$this->uptimeCheckFailed($uptimeResponseChecker->getFailureReason($response, $this));
return;
}
$this->uptimeCheckSucceeded();
}
public function uptimeRequestFailed(string $reason): void
{
$this->uptimeCheckFailed($reason);
}
public function uptimeCheckSucceeded(): void
{
$this->uptime_status = UptimeStatus::UP;
$this->uptime_check_failure_reason = '';
$wasFailing = ! is_null($this->uptime_check_failed_event_fired_on_date);
$lastStatusChangeDate = $this->uptime_status_last_change_date ? clone $this->uptime_status_last_change_date : null;
$this->uptime_check_times_failed_in_a_row = 0;
$this->uptime_last_check_date = Carbon::now();
$this->uptime_check_failed_event_fired_on_date = null;
$this->save();
if ($wasFailing) {
$downtimePeriod = new Period($lastStatusChangeDate, $this->uptime_last_check_date);
event(new UptimeCheckRecovered($this, $downtimePeriod));
return;
}
event(new UptimeCheckSucceeded($this));
}
public function uptimeCheckFailed(string $reason): void
{
$this->uptime_status = UptimeStatus::DOWN;
$this->uptime_check_times_failed_in_a_row++;
$this->uptime_last_check_date = Carbon::now();
$this->uptime_check_failure_reason = $reason;
$this->save();
if ($this->shouldFireUptimeCheckFailedEvent()) {
$this->uptime_check_failed_event_fired_on_date = Carbon::now();
$this->save();
$updatedMonitor = $this->fresh();
$downtimePeriod = new Period($updatedMonitor->uptime_status_last_change_date, $this->uptime_last_check_date);
event(new UptimeCheckFailed($this, $downtimePeriod));
}
}
protected function shouldFireUptimeCheckFailedEvent(): bool
{
if ($this->uptime_check_times_failed_in_a_row === config('uptime-monitor.uptime_check.fire_monitor_failed_event_after_consecutive_failures')) {
return true;
}
if (is_null($this->uptime_check_failed_event_fired_on_date)) {
return false;
}
if (config('uptime-monitor.notifications.resend_uptime_check_failed_notification_every_minutes') === 0) {
return false;
}
if ($this->uptime_check_failed_event_fired_on_date->diffInMinutes() >= config('uptime-monitor.notifications.resend_uptime_check_failed_notification_every_minutes')) {
return true;
}
return false;
}
}
<file_sep>/docs/monitoring-ssl-certificates/getting-started.md
---
title: Getting started
weight: 1
---
This package can monitor the validity of ssl certificates. It can notify you when an invalid certificate is found. It can also warn you if a certificate is going to expire soon.
To get started you should [create a monitor](https://docs.spatie.be/laravel-uptime-monitor/v3/monitoring-uptime/getting-started#creating-your-first-monitor). To make life easy for you, if the url starts with `https://` the package will automatically enable a certificate check.
If you want to run an certificate check without running the uptime check you can set `uptime_check_enabled` to `0` in the relevant row in the `monitors` table.
<file_sep>/src/Events/UptimeCheckRecovered.php
<?php
namespace Spatie\UptimeMonitor\Events;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\UptimeMonitor\Helpers\Period;
use Spatie\UptimeMonitor\Models\Monitor;
class UptimeCheckRecovered implements ShouldQueue
{
public Monitor $monitor;
public Period $downtimePeriod;
public function __construct(Monitor $monitor, Period $downtimePeriod)
{
$this->monitor = $monitor;
$this->downtimePeriod = $downtimePeriod;
}
}
<file_sep>/src/Exceptions/InvalidConfiguration.php
<?php
namespace Spatie\UptimeMonitor\Exceptions;
use Exception;
use Spatie\UptimeMonitor\Models\Monitor;
class InvalidConfiguration extends Exception
{
public static function modelIsNotValid(string $className): self
{
return new static("The given model class `{$className}` does not extend `".Monitor::class.'`');
}
}
<file_sep>/docs/advanced-usage/monitoring-from-multiple-locations.md
---
title: Monitoring from multiple locations
weight: 7
---
Monitoring from multiple locations is easy. Just install the package on servers at different locations. If you fill in the `location` field in the config file, that value will be displayed in any notification that is sent.<file_sep>/tests/TestCase.php
<?php
namespace Spatie\UptimeMonitor\Test;
use Artisan;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Notifications\SlackChannelServiceProvider;
use Illuminate\Support\Facades\Event;
use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\UptimeMonitor\UptimeMonitorServiceProvider;
abstract class TestCase extends Orchestra
{
protected Server $server;
public function setUp(): void
{
$this->server = new Server(new Client());
Carbon::setTestNow(Carbon::create(2016, 1, 1, 00, 00, 00));
parent::setUp();
Factory::guessFactoryNamesUsing(
fn (string $modelName) => 'Spatie\\UptimeMonitor\\Database\\Factories\\'.class_basename($modelName).'Factory'
);
}
/**
* @param \Illuminate\Foundation\Application $app
*
* @return array
*/
protected function getPackageProviders($app)
{
return [
SlackChannelServiceProvider::class,
UptimeMonitorServiceProvider::class,
];
}
/**
* @param \Illuminate\Foundation\Application $app
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'sqlite');
$app['config']->set('mail.driver', 'log');
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
'driver' => 'sqlite',
'prefix' => '',
'database' => ':memory:',
]);
$this->setUpDatabase();
}
protected function setUpDatabase()
{
include_once __DIR__.'/../database/migrations/create_monitors_table.php.stub';
(new \CreateMonitorsTable())->up();
}
public function progressMinutes(int $minutes)
{
$newNow = Carbon::now()->addMinutes($minutes);
Carbon::setTestNow($newNow);
}
public function bringTestServerUp()
{
$this->server->up();
}
public function bringTestServerDown()
{
$this->server->down();
}
/**
* @param string|array $searchStrings
*/
protected function seeInConsoleOutput($searchStrings)
{
if (! is_array($searchStrings)) {
$searchStrings = [$searchStrings];
}
$output = Artisan::output();
foreach ($searchStrings as $searchString) {
$this->assertStringContainsString((string) $searchString, $output);
}
}
/**
* @param string|array $searchStrings
*/
protected function dontSeeInConsoleOutput($searchStrings)
{
if (! is_array($searchStrings)) {
$searchStrings = [$searchStrings];
}
$output = Artisan::output();
foreach ($searchStrings as $searchString) {
$this->assertStringNotContainsString((string) $searchString, $output);
}
}
public function skipIfNotConnectedToTheInternet()
{
try {
file_get_contents('https://google.com');
} catch (\ErrorException $e) {
$this->markTestSkipped('No internet connection available.');
}
}
protected function resetEventAssertions()
{
Event::fake();
}
}
<file_sep>/src/Commands/DeleteMonitor.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\Models\Monitor;
class DeleteMonitor extends BaseCommand
{
protected $signature = 'monitor:delete {url}';
protected $description = 'Delete a monitor';
public function handle()
{
$url = $this->argument('url');
$monitor = Monitor::where('url', $url)->first();
if (! $monitor) {
$this->error("Monitor {$url} is not configured");
return;
}
if ($this->confirm("Are you sure you want stop monitoring {$monitor->url}?")) {
$monitor->delete();
$this->warn("{$monitor->url} will not be monitored anymore");
}
}
}
<file_sep>/src/Commands/DisableMonitor.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\MonitorRepository;
class DisableMonitor extends BaseCommand
{
protected $signature = 'monitor:disable {url}';
protected $description = 'Disable a monitor';
public function handle()
{
foreach (explode(',', $this->argument('url')) as $url) {
$this->disableMonitor(trim($url));
}
}
protected function disableMonitor(string $url)
{
if (! $monitor = MonitorRepository::findByUrl($url)) {
$this->error("There is no monitor configured for url `{$url}`.");
return;
}
$monitor->disable();
$this->info("The checks for url `{$url}` are now disabled.");
}
}
<file_sep>/src/Commands/ListMonitors.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Spatie\UptimeMonitor\Commands\MonitorLists\CertificateCheckFailed;
use Spatie\UptimeMonitor\Commands\MonitorLists\Disabled;
use Spatie\UptimeMonitor\Commands\MonitorLists\Healthy;
use Spatie\UptimeMonitor\Commands\MonitorLists\Unchecked;
use Spatie\UptimeMonitor\Commands\MonitorLists\UptimeCheckFailed;
use Spatie\UptimeMonitor\MonitorRepository;
class ListMonitors extends BaseCommand
{
protected $signature = 'monitor:list';
protected $description = 'List all monitors';
public function handle()
{
$this->line('');
if (! MonitorRepository::getEnabled()->count()) {
$this->warn('There are no monitors created or enabled.');
$this->info('You create a monitor using the `monitor:create {url}` command');
}
Unchecked::display();
Disabled::display();
UptimeCheckFailed::display();
CertificateCheckFailed::display();
Healthy::display();
}
}
<file_sep>/tests/Integration/Commands/MonitorCreateCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Mockery as m;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class MonitorCreateCommandTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Commands\CreateMonitor|m\Mock */
protected $command;
public function setUp(): void
{
parent::setUp();
$this->command = m::mock('Spatie\UptimeMonitor\Commands\CreateMonitor[ask, confirm]');
$this->app->bind('command.monitor:create', function () {
return $this->command;
});
}
/** @test */
public function it_can_create_a_monitor_for_a_https_site()
{
$this->command
->shouldReceive('confirm')
->once()
->with('Should we look for a specific string on the response?')
->andReturn('');
Artisan::call('monitor:create', ['url' => 'https://mysite.com']);
$monitor = Monitor::where('url', 'https://mysite.com')->first();
$this->assertSame($monitor->uptime_status, UptimeStatus::NOT_YET_CHECKED);
$this->assertTrue($monitor->certificate_check_enabled);
}
/** @test */
public function it_can_create_a_monitor_for_a_http_site()
{
$this->command
->shouldReceive('confirm')
->once()
->with('Should we look for a specific string on the response?')
->andReturn('');
Artisan::call('monitor:create', ['url' => 'http://mysite.com']);
$monitor = Monitor::where('url', 'http://mysite.com')->first();
$this->assertSame($monitor->uptime_status, UptimeStatus::NOT_YET_CHECKED);
$this->assertFalse($monitor->certificate_check_enabled);
$this->bringTestServerUp();
$this->bringTestServerDown();
}
}
<file_sep>/tests/Integration/Events/UptimeCheckSucceededTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Events;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event;
use Spatie\UptimeMonitor\Events\UptimeCheckSucceeded;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
use Spatie\UptimeMonitor\Test\TestCase;
class UptimeCheckSucceededTest extends TestCase
{
protected $monitor;
public function setUp(): void
{
parent::setUp();
Event::fake();
$this->monitor = Monitor::factory()->create();
}
/** @test */
public function the_succeeded_event_will_be_fired_when_an_uptime_check_succeeds()
{
MonitorRepository::getForUptimeCheck()->checkUptime();
Event::assertDispatched(UptimeCheckSucceeded::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
/** @test */
public function the_succeed_event_will_be_fired_when_a_site_is_up_and_the_look_for_string_is_found_on_the_response()
{
$this->server->setResponseBody('Hi, welcome on the page');
$this->monitor->look_for_string = 'welcome';
$this->monitor->save();
MonitorRepository::getForUptimeCheck()->checkUptime();
Event::assertDispatched(UptimeCheckSucceeded::class);
}
/** @test */
public function the_uptime_checker_will_succeed_with_configured_guzzle_options()
{
$this->server->up();
$this->server->setResponseBody('', 301);
Config::set('uptime-monitor.uptime_check.guzzle_options', [
'allow_redirects' => false,
]);
$monitors = MonitorRepository::getForUptimeCheck();
$monitors->checkUptime();
Config::set('uptime-monitor.uptime_check.guzzle_options', []);
Event::assertDispatched(UptimeCheckSucceeded::class, function ($event) {
return $event->monitor->id === $this->monitor->id;
});
}
}
<file_sep>/src/Notifications/Notifiable.php
<?php
namespace Spatie\UptimeMonitor\Notifications;
use Illuminate\Notifications\Notifiable as NotifiableTrait;
class Notifiable
{
use NotifiableTrait;
/**
* @return string|null
*/
public function routeNotificationForMail()
{
return config('uptime-monitor.notifications.mail.to');
}
/**
* @return string|null
*/
public function routeNotificationForSlack()
{
return config('uptime-monitor.notifications.slack.webhook_url');
}
public function getKey(): string
{
return static::class;
}
}
<file_sep>/src/Notifications/Notifications/UptimeCheckFailed.php
<?php
namespace Spatie\UptimeMonitor\Notifications\Notifications;
use Carbon\Carbon;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackAttachment;
use Illuminate\Notifications\Messages\SlackMessage;
use Spatie\UptimeMonitor\Events\UptimeCheckFailed as MonitorFailedEvent;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Notifications\BaseNotification;
class UptimeCheckFailed extends BaseNotification
{
public MonitorFailedEvent $event;
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$mailMessage = (new MailMessage())
->error()
->subject($this->getMessageText())
->line($this->getMessageText())
->line($this->getLocationDescription());
foreach ($this->getMonitorProperties() as $name => $value) {
$mailMessage->line($name.': '.$value);
}
return $mailMessage;
}
public function toSlack($notifiable)
{
return (new SlackMessage())
->error()
->attachment(function (SlackAttachment $attachment) {
$attachment
->title($this->getMessageText())
->content($this->getMonitor()->uptime_check_failure_reason)
->fallback($this->getMessageText())
->footer($this->getLocationDescription())
->timestamp(Carbon::now());
});
}
public function getMonitorProperties($extraProperties = []): array
{
$since = "Since {$this->event->downtimePeriod->startDateTime->format('H:i')}";
$date = $this->event->monitor->formattedLastUpdatedStatusChangeDate();
$extraProperties = [
$since => $date,
'Failure reason' => $this->getMonitor()->uptime_check_failure_reason,
];
return parent::getMonitorProperties($extraProperties);
}
public function isStillRelevant(): bool
{
return $this->getMonitor()->uptime_status == UptimeStatus::DOWN;
}
public function setEvent(MonitorFailedEvent $event): self
{
$this->event = $event;
return $this;
}
protected function getMessageText(): string
{
return "{$this->getMonitor()->url} seems down";
}
}
<file_sep>/tests/Integration/Commands/CheckUptimeCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\Integration\Helpers\ResponseCheckerFailureFake;
use Spatie\UptimeMonitor\Test\TestCase;
class CheckUptimeCommandTest extends TestCase
{
/** @test */
public function it_has_a_command_to_perform_uptime_checks()
{
$monitor = Monitor::factory()->create(['uptime_status' => UptimeStatus::NOT_YET_CHECKED]);
Artisan::call('monitor:check-uptime');
$monitor = $monitor->fresh();
$this->assertEquals(UptimeStatus::UP, $monitor->uptime_status);
}
/** @test */
public function it_can_perform_an_uptime_check_for_specific_monitor()
{
$monitor1 = Monitor::factory()->create(['uptime_status' => UptimeStatus::NOT_YET_CHECKED]);
$monitor2 = Monitor::factory()->create([
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'url' => 'https://google.com',
]);
Artisan::call('monitor:check-uptime', ['--url' => $monitor1->url]);
$monitor1 = $monitor1->fresh();
$monitor2 = $monitor2->fresh();
$this->assertEquals(UptimeStatus::UP, $monitor1->uptime_status);
$this->assertEquals(UptimeStatus::NOT_YET_CHECKED, $monitor2->uptime_status);
}
/** @test */
public function it_can_perform_an_uptime_checks_for_a_set_of_specific_monitors()
{
$this->skipIfNotConnectedToTheInternet();
$monitor1 = Monitor::factory()->create(['uptime_status' => UptimeStatus::NOT_YET_CHECKED]);
$monitor2 = Monitor::factory()->create([
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'url' => 'https://google.com',
]);
$monitor3 = Monitor::factory()->create([
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'url' => 'https://bing.com',
]);
Artisan::call('monitor:check-uptime', ['--url' => $monitor1->url.','.$monitor2->url]);
$monitor1 = $monitor1->fresh();
$monitor2 = $monitor2->fresh();
$monitor3 = $monitor3->fresh();
$this->assertEquals(UptimeStatus::UP, $monitor1->uptime_status);
$this->assertEquals(UptimeStatus::UP, $monitor2->uptime_status);
$this->assertEquals(UptimeStatus::NOT_YET_CHECKED, $monitor3->uptime_status);
}
/** @test */
public function it_can_post_a_payload()
{
$monitor = Monitor::factory()->create([
'url' => sprintf('http://localhost:%s/testPost', env('TEST_SERVER_PORT')),
'uptime_check_method' => 'post',
'uptime_check_payload' => json_encode(['foo' => 'bar']),
'uptime_check_additional_headers' => ['Content-Type' => 'application/json'],
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
]);
Artisan::call('monitor:check-uptime');
$monitor = $monitor->fresh();
$this->assertEquals(UptimeStatus::UP, $monitor->uptime_status);
}
/** @test */
public function it_can_use_a_custom_response_checker()
{
$monitor = Monitor::factory()->create([
'uptime_status' => UptimeStatus::NOT_YET_CHECKED,
'uptime_check_response_checker' => ResponseCheckerFailureFake::class,
]);
Artisan::call('monitor:check-uptime');
$monitor = $monitor->fresh();
$this->assertEquals(UptimeStatus::DOWN, $monitor->uptime_status);
$this->assertEquals(ResponseCheckerFailureFake::FAILURE_REASON, $monitor->uptime_check_failure_reason);
}
}
<file_sep>/src/Models/Monitor.php
<?php
namespace Spatie\UptimeMonitor\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\UptimeMonitor\Exceptions\CannotSaveMonitor;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Presenters\MonitorPresenter;
use Spatie\UptimeMonitor\Models\Traits\SupportsCertificateCheck;
use Spatie\UptimeMonitor\Models\Traits\SupportsUptimeCheck;
use Spatie\Url\Url;
class Monitor extends Model
{
use SupportsUptimeCheck;
use SupportsCertificateCheck;
use MonitorPresenter;
use HasFactory;
protected $guarded = [];
protected $appends = ['raw_url'];
protected $casts = [
'uptime_check_enabled' => 'boolean',
'certificate_check_enabled' => 'boolean',
'uptime_last_check_date' => 'datetime',
'uptime_status_last_change_date' => 'datetime',
'uptime_check_failed_event_fired_on_date' => 'datetime',
'certificate_expiration_date' => 'datetime',
];
public function getUptimeCheckAdditionalHeadersAttribute($additionalHeaders): array
{
return $additionalHeaders
? json_decode($additionalHeaders, true)
: [];
}
public function setUptimeCheckAdditionalHeadersAttribute(array $additionalHeaders): void
{
$this->attributes['uptime_check_additional_headers'] = json_encode($additionalHeaders);
}
public function scopeEnabled($query)
{
return $query
->where('uptime_check_enabled', true)
->orWhere('certificate_check_enabled', true);
}
public function getUrlAttribute(): ?Url
{
if (! isset($this->attributes['url'])) {
return null;
}
return Url::fromString($this->attributes['url']);
}
public function getRawUrlAttribute(): string
{
return (string) $this->url;
}
public static function booted()
{
static::saving(function (self $monitor) {
if (static::alreadyExists($monitor)) {
throw CannotSaveMonitor::alreadyExists($monitor);
}
});
}
public function isHealthy(): bool
{
if ($this->uptime_check_enabled && in_array($this->uptime_status, [UptimeStatus::DOWN, UptimeStatus::NOT_YET_CHECKED])) {
return false;
}
if ($this->certificate_check_enabled && $this->certificate_status === CertificateStatus::INVALID) {
return false;
}
return true;
}
public function enable(): self
{
$this->uptime_check_enabled = true;
if ($this->url->getScheme() === 'https') {
$this->certificate_check_enabled = true;
}
$this->save();
return $this;
}
public function disable(): self
{
$this->uptime_check_enabled = false;
$this->certificate_check_enabled = false;
$this->save();
return $this;
}
protected static function alreadyExists(self $monitor): bool
{
$query = static::where('url', $monitor->url);
if ($monitor->exists) {
$query->where('id', '<>', $monitor->id);
}
return (bool) $query->first();
}
}
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to `laravel-uptime-monitor` will be documented in this file
## 4.2.1 - 2023-02-17
### What's Changed
- Bump dependabot/fetch-metadata from 1.3.4 to 1.3.5 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/332
- Bump dependabot/fetch-metadata from 1.3.5 to 1.3.6 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/334
- Laravel 10.x Compatibility by @laravel-shift in https://github.com/spatie/laravel-uptime-monitor/pull/335
### New Contributors
- @laravel-shift made their first contribution in https://github.com/spatie/laravel-uptime-monitor/pull/335
**Full Changelog**: https://github.com/spatie/laravel-uptime-monitor/compare/4.2.0...4.2.1
## 4.2.0 - 2022-10-07
### What's Changed
- Bump dependabot/fetch-metadata from 1.1.1 to 1.2.0 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/313
- Bump dependabot/fetch-metadata from 1.2.0 to 1.2.1 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/314
- Bump dependabot/fetch-metadata from 1.2.1 to 1.3.0 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/315
- Bump dependabot/fetch-metadata from 1.3.0 to 1.3.1 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/319
- Bump dependabot/fetch-metadata from 1.3.1 to 1.3.3 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/321
- Add support for php8.1 and Laravel 9. by @Joeri-Abbo in https://github.com/spatie/laravel-uptime-monitor/pull/324
- Bump dependabot/fetch-metadata from 1.3.3 to 1.3.4 by @dependabot in https://github.com/spatie/laravel-uptime-monitor/pull/327
### New Contributors
- @dependabot made their first contribution in https://github.com/spatie/laravel-uptime-monitor/pull/313
- @Joeri-Abbo made their first contribution in https://github.com/spatie/laravel-uptime-monitor/pull/324
**Full Changelog**: https://github.com/spatie/laravel-uptime-monitor/compare/4.1.1...4.2.0
## 4.1.1 - 2022-02-13
## What's Changed
- Modify composer requires to illuminate/* alternatives by @mallardduck in https://github.com/spatie/laravel-uptime-monitor/pull/311
## New Contributors
- @mallardduck made their first contribution in https://github.com/spatie/laravel-uptime-monitor/pull/311
**Full Changelog**: https://github.com/spatie/laravel-uptime-monitor/compare/4.1.0...4.1.1
## 4.1.0 - 2022-01-19
- add support for Laravel 9
## 4.0.0 - 2021-01-14
- typehint all the things
- drop anything below Laravel 8 / PHP 7.4
- add support for PHP 8
- use CarbonInterface instead of Carbon
## 3.9.0 - 2020-10-01
- add support for Laravel 8
## 3.8.1 - 2020-10-01
- general cleanup
## 3.8.0 - 2020-03-11
- add support for Laravel 7
## 3.7.0 - 2020-02-14
- allow configuration of guzzle client options (#181)
## 3.5.0 - 2019-05-17
- Add `raw_url` attribute to serialization [#175](https://github.com/spatie/laravel-uptime-monitor/pull/175)
## 3.4.1 - 2019-04-15
- Fixed issue with migrations stub ([#171](https://github.com/spatie/laravel-uptime-monitor/pull/171))
## 3.4.0 - 2019-03-03
- Dropped support for Laravel 5.7
- Added support for Laravel 5.8, PHPUnit 8
- PHPUnit minimum version is now 7.5
## 3.3.4 - 2018-10-30
- fix if statement to be if not certificate applies to url
## 3.3.3 - 2018-10-20
- fix for PHP 7.3
## 3.3.2 - 2018-10-18
- fix for checking SSL
## 3.3.1 - 2018-08-27
- add support for Laravel 5.7
## 3.3.0 - 2018-03-13
- add option to force run all monitors
## 3.2.1 - 2018-02-08
- add support for L5.6
## 3.2.0 - 2017-12-20
- add ability for monitors to have their own response checkers
## 3.1.0 - 2017-12-11
- add ability to send payload to verify uptime
## 3.0.0 - 2017-08-31
- add support for Laravel 5.5, drop support for Laravel 5.4
- renamed config file from `laravel-uptime-monitor` to `uptime-monitor`
## 2.2.0 - 2017-03-13
- add `retry_connection_after_milliseconds` to config file
## 2.1.0 - 2017-03-13
- add `sync` command
## 2.0.3 - 2017-03-13
- fixed bug in getting unchecked monitors
## 2.0.2 - 2017-03-08
- added monitor location to mail notifications
## 2.0.1 - 2017-01-27
- ask for protocol when creating a monitor
## 2.0.0 - 2017-01-24
- add support for L5.4
- drop support for L5.3
## 1.2.3 - 2017-01-14
- fixed bug where migration could be published multiple times
## 1.2.2 - 2017-01-06
- set fallback text for Slack notifications
## 1.2.1 - 2016-12-22
- fix typos in notifications
## 1.2.0 - 2016-12-22
- improve notifications
## 1.1.2 - 2016-12-19
- fix `CertificateCheckSucceeded` notification
## 1.1.1 - 2016-12-12
- fix typos in command descriptions
## 1.1.0 - 2016-12-03
- added `additional_headers` to config
## 1.0.2 - 2016-11-24
- fix descriptions in config file
## 1.0.1 - 2016-11-21
- fix custom model instructions in config file
## 1.0.0 - 2016-11-21
- initial release
<file_sep>/tests/Integration/Commands/ListMonitorsCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class ListMonitorsCommandTest extends TestCase
{
public function it_display_a_message_when_no_monitors_are_configured()
{
Artisan::call('monitor:list');
$this->seeInConsoleOutput('There are no monitors created or enabled');
$this->dontSeeInConsoleOutput('Healthy monitors');
}
/** @test */
public function it_can_show_monitors_that_have_not_been_checked_yet()
{
$monitor = Monitor::factory()->create(['uptime_status' => UptimeStatus::NOT_YET_CHECKED]);
Artisan::call('monitor:list');
$this->seeInConsoleOutput([
'Not yet checked',
$monitor->url,
]);
}
/** @test */
public function it_can_show_healthy_monitors()
{
$monitor = Monitor::factory()->create(['uptime_status' => UptimeStatus::UP]);
Artisan::call('monitor:list');
$this->seeInConsoleOutput([
'Healthy monitors',
$monitor->url,
]);
}
/** @test */
public function it_can_show_monitors_with_failing_uptime_checks()
{
$monitor = Monitor::factory()->create(['uptime_status' => UptimeStatus::DOWN]);
Artisan::call('monitor:list');
$this->seeInConsoleOutput([
'Uptime check failed',
$monitor->url,
]);
}
/** @test */
public function it_can_show_monitors_that_have_certificate_problems()
{
$monitor = Monitor::factory()->create([
'certificate_check_enabled' => true,
'certificate_status' => CertificateStatus::INVALID,
]);
Artisan::call('monitor:list');
$this->seeInConsoleOutput([
'Certificate check failed',
$monitor->url,
]);
}
/** @test */
public function it_can_show_disabled_monitors()
{
$monitor = Monitor::factory()->create([
'uptime_check_enabled' => false,
]);
Artisan::call('monitor:list');
$this->seeInConsoleOutput([
'Disabled monitors',
$monitor->url,
]);
}
}
<file_sep>/src/Commands/BaseCommand.php
<?php
namespace Spatie\UptimeMonitor\Commands;
use Illuminate\Console\Command;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
abstract class BaseCommand extends Command
{
public function run(InputInterface $input, OutputInterface $output): int
{
app(ConsoleOutput::class)->setOutput($this);
return parent::run($input, $output);
}
}
<file_sep>/src/Commands/MonitorLists/UptimeCheckFailed.php
<?php
namespace Spatie\UptimeMonitor\Commands\MonitorLists;
use Spatie\UptimeMonitor\Helpers\ConsoleOutput;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\MonitorRepository;
class UptimeCheckFailed
{
public static function display()
{
$failingMonitors = MonitorRepository::getWithFailingUptimeCheck();
if (! $failingMonitors->count()) {
return;
}
ConsoleOutput::warn('Uptime check failed');
ConsoleOutput::warn('===================');
$rows = $failingMonitors->map(function (Monitor $monitor) {
$certificateFound = '';
$certificateExpirationDate = '';
$certificateIssuer = '';
$url = $monitor->url;
$reachable = $monitor->uptimeStatusAsEmoji;
$offlineSince = $monitor->formattedLastUpdatedStatusChangeDate('forHumans');
$reason = $monitor->chunkedLastFailureReason;
if ($monitor->certificate_check_enabled) {
$certificateFound = $monitor->certificateStatusAsEmoji;
$certificateExpirationDate = $monitor->formattedCertificateExpirationDate('forHumans');
$certificateIssuer = $monitor->certificate_issuer;
}
return compact('url', 'reachable', 'offlineSince', 'reason', 'certificateFound', 'certificateExpirationDate', 'certificateIssuer');
});
$titles = ['URL', 'Reachable', 'Offline since', 'Reason', 'Certificate', 'Certificate expiration date', 'Certificate issuer'];
ConsoleOutput::table($titles, $rows);
ConsoleOutput::line('');
}
}
<file_sep>/tests/Integration/Commands/DeleteMonitorCommandTest.php
<?php
namespace Spatie\UptimeMonitor\Test\Integration\Commands;
use Artisan;
use Mockery as m;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Test\TestCase;
class DeleteMonitorCommandTest extends TestCase
{
/** @var \Spatie\UptimeMonitor\Commands\DeleteMonitor|m\Mock */
protected $command;
/** @var string */
protected $url;
public function setUp(): void
{
parent::setUp();
$this->command = m::mock('Spatie\UptimeMonitor\Commands\DeleteMonitor[confirm]');
$this->app->bind('command.monitor:delete', function () {
return $this->command;
});
$this->url = 'https://mysite.com';
Monitor::factory()->create(['url' => $this->url]);
}
/** @test */
public function it_can_delete_a_monitor()
{
$this->assertEquals(1, Monitor::where('url', $this->url)->count());
$this->command
->shouldReceive('confirm')
->once()
->with("Are you sure you want stop monitoring {$this->url}?")
->andReturn('yes');
Artisan::call('monitor:delete', ['url' => $this->url]);
$this->assertEquals(0, Monitor::where('url', $this->url)->count());
}
}
<file_sep>/src/Models/Presenters/MonitorPresenter.php
<?php
namespace Spatie\UptimeMonitor\Models\Presenters;
use Spatie\UptimeMonitor\Models\Enums\CertificateStatus;
use Spatie\UptimeMonitor\Models\Enums\UptimeStatus;
trait MonitorPresenter
{
public function getUptimeStatusAsEmojiAttribute(): string
{
if ($this->uptime_status === UptimeStatus::UP) {
return '✅';
}
if ($this->uptime_status === UptimeStatus::DOWN) {
return '❌';
}
return '';
}
public function getCertificateStatusAsEmojiAttribute(): string
{
if ($this->certificate_status === CertificateStatus::VALID) {
return '✅';
}
if ($this->certificate_status === CertificateStatus::INVALID) {
return '❌';
}
return '';
}
public function formattedLastUpdatedStatusChangeDate(string $format = ''): string
{
return $this->formatDate('uptime_status_last_change_date', $format);
}
public function formattedCertificateExpirationDate(string $format = ''): string
{
return $this->formatDate('certificate_expiration_date', $format);
}
public function getChunkedLastFailureReasonAttribute(): string
{
if ($this->uptime_check_failure_reason == '') {
return '';
}
return chunk_split($this->uptime_check_failure_reason, 30, "\n");
}
public function getChunkedLastCertificateCheckFailureReasonAttribute(): string
{
if ($this->certificate_check_failure_reason == '') {
return '';
}
return chunk_split($this->certificate_check_failure_reason, 60, "\n");
}
protected function formatDate(string $attributeName, string $format = ''): string
{
if (! $this->$attributeName) {
return '';
}
if ($format === 'forHumans') {
return $this->$attributeName->diffForHumans();
}
if ($format === '') {
$format = config('uptime-monitor.notifications.date_format');
}
return $this->$attributeName->format($format);
}
}
| f91236515baaf0c185b7860f13f969d6de1141b2 | [
"Markdown",
"PHP"
] | 87 | Markdown | spatie/laravel-uptime-monitor | 429c2953d67b56691e60690053235f9dd5396d39 | 3006e01fb0991b709af77afb968408518c22af1c |
refs/heads/master | <repo_name>BakerWang/erp-1<file_sep>/biz-web/src/main/java/com/f6car/Application.java
package com.f6car;
import com.f6car.interceptor.SetDatasourceInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Created by qixiaobo on 16/5/17.
*/
@Configuration
@ComponentScan("com.f6car")
@EnableAutoConfiguration
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SetDatasourceInterceptor())
.addPathPatterns("/**");
}
}<file_sep>/biz-model/src/main/java/com/f6car/model/base/BaseModel.java
package com.f6car.model.base;
import com.f6car.enums.OperateType;
import java.io.Serializable;
import java.util.Date;
import se.spagettikod.optimist.Identity;
import se.spagettikod.optimist.Version;
/**
* Created by qixiaobo on 16/5/17.
*/
public abstract class BaseModel<PK extends Serializable> implements Serializable {
private Boolean deleteFlag;
private Integer updateUserId;
private Integer createUserId;
private Date createDate;
private Date updateDate;
@Version("version")
private Integer version;
private OperateType operate;
public Boolean getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(Boolean deleteFlag) {
this.deleteFlag = deleteFlag;
}
public Integer getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(Integer updateUserId) {
this.updateUserId = updateUserId;
}
public Integer getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Integer createUserId) {
this.createUserId = createUserId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public OperateType getOperate() {
return operate;
}
public void setOperate(OperateType operate) {
this.operate = operate;
}
public abstract PK getId();
}<file_sep>/code-generator/src/main/java/com/f6car/generator/Generator.java
package com.f6car.generator;
import com.google.common.io.Files;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by qixiaobo on 16/5/19.
*/
@SpringBootApplication
@EnableConfigurationProperties({SampleConfiguration.class})
public class Generator implements CommandLineRunner {
@Autowired
private TableMetaReader tableMetaReader;
@Autowired
private SampleConfiguration sampleConfiguration;
@Autowired
private Configuration freemarkerConfiguration;
public static void main(String[] args) {
SpringApplication.run(Generator.class, args);
}
public void run(String... args) throws Exception {
List<TableInfo> tables = tableMetaReader.readAllTable();
for (TableInfo tableInfo : tables) {
generateFiles(tableInfo);
//TODO mapper && exclude filed
}
}
private void generateFiles(TableInfo table) {
Map<String, Object> data = getData(table);
generateFile(table, data, sampleConfiguration.getController(), "Controller.java");
generateFile(table, data, sampleConfiguration.getSo(), "So.java");
generateFile(table, data, sampleConfiguration.getVo(), "Vo.java");
generateFile(table, data, sampleConfiguration.getRep(), "Repository.java");
generateFile(table, data, sampleConfiguration.getService(), "Service.java");
generateFile(table, data, sampleConfiguration.getServiceImpl(), "ServiceImpl.java");
generateFile(table, data, sampleConfiguration.getMapper(), "Mapper.xml");
generateFile(table, data, sampleConfiguration.getModel(), ".java");
}
private Map<String, Object> getData(TableInfo table) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("table", table);
/*boolean isSecondDir = table.getTableName().split("_").length > 2;//eg: t_order_detail
String secondDir = isSecondDir ? table.getTableName().split("_")[1] : "";
data.put("second",isSecondDir);*/
String secondDir = table.getTableName().split("_")[1];
data.put("second", true);
data.put("subPackage", secondDir);
data.put("excludeVo", sampleConfiguration.getExcludeVo());
data.put("excludePo", sampleConfiguration.getExcludePo());
data.put("excludeSo", sampleConfiguration.getExcludeSo());
return data;
}
private void generateFile(TableInfo table, Map<String, Object> data, String templatePath, String fileSuffix) {
try {
/*boolean isSecondDir = table.getTableName().split("_").length > 2;//eg: t_order_detail
String secondDir = isSecondDir ? table.getTableName().split("_")[1] : "";*/
boolean isSecondDir = true;
String secondDir = table.getTableName().split("_")[1];
String path = sampleConfiguration.getFilePath() + File.separator + secondDir + File.separator + table.getClazzName() + fileSuffix;
if (isSecondDir) {
File dir = new File(sampleConfiguration.getFilePath() + File.separator + secondDir);
if (!dir.exists()) {
dir.mkdir();
}
}
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
Writer writer = Files.newWriter(file, Charset.defaultCharset());
Template controller = freemarkerConfiguration.getTemplate(templatePath);
controller.process(data, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
@Bean
public Configuration freemarkerConfiguration() {
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
//设置FreeMarker的模版文件位置
try {
cfg.setDirectoryForTemplateLoading(new File(getClass().getClassLoader().getResource("").toURI()));
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return cfg;
}
}
<file_sep>/biz-rpc/src/main/java/com/f6car/rpc/HessionExportor.java
package com.f6car.rpc;
import com.f6car.service.base.BaseService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
/**
* Created by qixiaobo on 16/5/22.
*/
@Component
public class HessionExportor implements ApplicationContextAware {
@Value("${hession.deployRoot}")
private String hessionDeployPath;
private ApplicationContext applicationContext;
@PostConstruct
public void init() {
Map<String, BaseService> serviceBeanMap = applicationContext.getBeansOfType(BaseService.class);
for (Map.Entry<String, BaseService> entry : serviceBeanMap.entrySet()) {
BeanDefinitionBuilder exPorter = BeanDefinitionBuilder.genericBeanDefinition(HessianServiceExporter.class);
exPorter.addPropertyValue("service", entry.getValue());
exPorter.addPropertyValue("serviceInterface", entry.getValue().getClass().getInterfaces()[0]);
exPorter.setLazyInit(true);
getBeanDefinitionRegistry().registerBeanDefinition(hessionDeployPath + entry.getKey(), exPorter.getRawBeanDefinition());
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
private BeanDefinitionRegistry getBeanDefinitionRegistry() {
return (BeanDefinitionRegistry) ((ConfigurableApplicationContext)applicationContext).getBeanFactory();
}
}
<file_sep>/biz-mapper/src/main/java/com/f6car/mapper/base/BaseRepository.java
package com.f6car.mapper.base;
import com.f6car.common.query.BaseSo;
import com.f6car.model.base.BaseModel;
import java.io.Serializable;
import java.util.List;
/**
* Created by qixiaobo on 16/5/19.
*/
public interface BaseRepository<PO extends BaseModel, SO extends BaseSo, PK extends Serializable> {
PO findById(PK pk);
int deleteById(PK pk);
int updatePo(PO po);
PK createReturnPK(PO po);
long countBySo(SO so);
List<PO> searchBySo(SO so);
}
<file_sep>/code-generator/src/main/java/com/f6car/generator/SampleConfiguration.java
package com.f6car.generator;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
/**
* Created by qixiaobo on 16/5/20.
*/
@ConfigurationProperties(prefix = "sample")
public class SampleConfiguration {
private String so;
private String vo;
private String model;
private String mapper;
private String controller;
private String rep;
private String service;
private String serviceImpl;
private String filePath;
private List<String> excludeVo;
private List<String> excludePo;
private List<String> excludeSo;
public String getSo() {
return so;
}
public void setSo(String so) {
this.so = so;
}
public String getVo() {
return vo;
}
public void setVo(String vo) {
this.vo = vo;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getMapper() {
return mapper;
}
public void setMapper(String mapper) {
this.mapper = mapper;
}
public String getController() {
return controller;
}
public void setController(String controller) {
this.controller = controller;
}
public String getRep() {
return rep;
}
public void setRep(String rep) {
this.rep = rep;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getServiceImpl() {
return serviceImpl;
}
public void setServiceImpl(String serviceImpl) {
this.serviceImpl = serviceImpl;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public List<String> getExcludeVo() {
return excludeVo;
}
public void setExcludeVo(List<String> excludeVo) {
this.excludeVo = excludeVo;
}
public List<String> getExcludePo() {
return excludePo;
}
public void setExcludePo(List<String> excludePo) {
this.excludePo = excludePo;
}
public List<String> getExcludeSo() {
return excludeSo;
}
public void setExcludeSo(List<String> excludeSo) {
this.excludeSo = excludeSo;
}
}
<file_sep>/biz-web/src/main/java/com/f6car/interceptor/SetDatasourceInterceptor.java
package com.f6car.interceptor;
import com.f6car.datasource.DataSourceHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetDatasourceInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object companyId = request.getHeader("companyId");
if (companyId != null) {
DataSourceHolder.setDataSource(companyId.toString());
}
return true;
}
}
<file_sep>/biz-web/src/main/java/com/f6car/config/JsonConfig.java
package com.f6car.config;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by 晓波 on 2016/5/8 0008.
*/
@Configuration
public class JsonConfig {
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
return new FastJsonHttpMessageConverter();
}
@Bean
@Autowired
public HttpMessageConverters convertersToBeUsed(FastJsonHttpMessageConverter converter) {
return new HttpMessageConverters(converter);
}
}
<file_sep>/utility/src/main/java/com/f6car/common/response/Response.java
package com.f6car.common.response;
import com.f6car.common.query.BaseVo;
/**
* Created by qixiaobo on 16/5/21.
*/
public class Response<VO extends BaseVo> extends BaseResponse {
private VO vo;
public Response(){
}
public Response(VO entity) {
this.vo = entity;
}
public VO getVo() {
return vo;
}
public void setVo(VO vo) {
this.vo = vo;
}
}
<file_sep>/biz-model/src/main/java/com/f6car/enums/OperateType.java
package com.f6car.enums;
public enum OperateType {
NONE, NEW, UPDATE, DELETE, SEARCH;
}
<file_sep>/biz-presentation/src/main/java/com/f6car/biz/order/so/OrderSo.java
package com.f6car.biz.order.so;
import com.f6car.common.query.BaseSo;
/**
* Created by qixiaobo on 16/5/17.
*/
public class OrderSo extends BaseSo {
}
<file_sep>/biz-mapper/src/main/java/com/f6car/aspect/PageAspect.java
package com.f6car.aspect;
import com.f6car.common.query.BaseSo;
import com.f6car.common.query.Sort;
import com.github.pagehelper.PageHelper;
import com.google.common.base.CaseFormat;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* Created by qixiaobo on 16/5/19.
*/
@Component
@Aspect
public class PageAspect {
private static final CaseFormat FROM_FORMAT = CaseFormat.LOWER_CAMEL;
private static final CaseFormat TO_FORMAT = CaseFormat.LOWER_UNDERSCORE;
@Before(value = "execution(* com.f6car.mapper.base.BaseRepository+.*(com.f6car.common.query.BaseSo)) && args(so)")
public void pageIntercept(JoinPoint jp, BaseSo so) {
PageHelper.startPage(so.getCurrentPage(), so.getPageSize());
if (so.getSorts().size() > 0) {
for (Sort sort : so.getSorts()) {
PageHelper.orderBy(getSort(sort));
}
}
}
private String getSort(Sort sort) {
String dbColumn = FROM_FORMAT.to(TO_FORMAT, sort.getSortKey());
return sort.getSortDir() == null ? dbColumn : dbColumn + " " + sort.getSortDir();
}
}
<file_sep>/biz-presentation/src/main/java/com/f6car/biz/order/vo/OrderVo.java
package com.f6car.biz.order.vo;
import com.f6car.common.query.BaseVo;
/**
* Created by qixiaobo on 16/5/17.
*/
public class OrderVo extends BaseVo {
}
<file_sep>/utility/src/main/java/com/f6car/common/query/SearchObject.java
package com.f6car.common.query;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* Created by qixiaobo on 16/5/19.
*/
public class SearchObject implements Pageable, Sortable, Serializable {
private int currentPage;
private int pageSize;
private List<Sort> sorts = new LinkedList<Sort>();
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<Sort> getSorts() {
return sorts;
}
public void setSorts(List<Sort> sorts) {
this.sorts = sorts;
}
public void addSort(Sort sort) {
sorts.add(sort);
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.f6car</groupId>
<artifactId>erp</artifactId>
<version>${f6.version}</version>
<name>f6 root parent</name>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<f6.version>1.0-SNAPSHOT</f6.version>
<java.version>1.7</java.version>
<druid.version>1.0.18</druid.version>
<jjwt.version>0.6.0</jjwt.version>
<fastjson.version>1.2.7</fastjson.version>
<guava.version>18.0</guava.version>
<pagehelper.version>4.1.3</pagehelper.version>
<jsqlparser.version>0.9.4</jsqlparser.version>
<spring.boot.version>1.2.6.RELEASE</spring.boot.version>
<joda.version>2.9.3</joda.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-mapper</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-model</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-presentation</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-rpc</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-service</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-service-impl</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>utility</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<groupId>com.f6car</groupId>
<artifactId>biz-web</artifactId>
<version>${f6.version}</version>
</dependency>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--spring boot end-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>${jsqlparser.version}</version>
</dependency>
<dependency>
<groupId>se.spagettikod</groupId>
<artifactId>optimist</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- http://mvnrepository.com/artifact/ma.glasnost.orika/orika-core -->
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>biz-presentation</module>
<module>utility</module>
<module>biz-service</module>
<module>biz-model</module>
<module>biz-mapper</module>
<module>biz-web</module>
<module>code-generator</module>
<module>biz-rpc</module>
<module>biz-service-impl</module>
</modules>
</project><file_sep>/utility/src/main/java/com/f6car/common/response/BaseResponse.java
package com.f6car.common.response;
/**
* Created by qixiaobo on 16/5/21.
*/
public abstract class BaseResponse {
private int status = 0;
private String message;
private int udf1;//eg return count
private long udf2;
private double udf3;
private boolean udf4;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getUdf1() {
return udf1;
}
public void setUdf1(int udf1) {
this.udf1 = udf1;
}
public long getUdf2() {
return udf2;
}
public void setUdf2(long udf2) {
this.udf2 = udf2;
}
public double getUdf3() {
return udf3;
}
public void setUdf3(double udf3) {
this.udf3 = udf3;
}
public boolean isUdf4() {
return udf4;
}
public void setUdf4(boolean udf4) {
this.udf4 = udf4;
}
}
| fcfb880afc34e1e53256c50fb98fad4ef1fd59d3 | [
"Java",
"Maven POM"
] | 16 | Java | BakerWang/erp-1 | f1d4a73aef7cb8973c91acdb7e489c340f34d188 | f7382b3c2941bc12aabc40cecf8aa746da19f461 |
refs/heads/master | <file_sep># TODO: Make script to generate certificates.
<file_sep>HAPROXY_FOLDER=$PWD
docker run -it --rm --name certbot-renew \
-v "letsencrypt-etc:/etc/letsencrypt" \
-v "letsencrypt-var-lib:/var/lib/letsencrypt" \
-v "${HAPROXY_FOLDER}/secrets:/app/haproxy/secrets" \
-v "haproxy-certs:/certs" \
-v "${HAPROXY_FOLDER}/scripts/le-combiner:/scripts/le-combiner" \
certbot/dns-cloudflare renew --renew-hook "/scripts/le-combiner/le-combiner.sh"
<file_sep>* [Readme (without Docker)](../README.md#combined-certs-without-docker)
* [Readme (with Docker)](https://wiki.lelux.fi/haproxy#docker)
<file_sep>HAPROXY_FOLDER=$PWD
# TODO: Migrate from Ubuntu image to some smaller one.
docker run -it --rm --name le-combiner \
-v "letsencrypt-etc:/etc/letsencrypt" \
-v "haproxy-certs:/certs" \
-v "${HAPROXY_FOLDER}/scripts/le-combiner:/scripts/le-combiner" \
ubuntu:16.04 /bin/bash "/scripts/le-combiner/le-combiner.sh"
<file_sep>screen php -S 127.0.0.1:12345
<file_sep># haproxy-scripts
My Haproxy scripts
## Combined certs without Docker
See [wiki entry](https://wiki.lelux.fi/haproxy/#lets-encrypt).
<file_sep>#!/usr/bin/env bash
# https://askubuntu.com/a/15856
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
FOLDER=/etc/haproxy/certs
# Combine function
combine() {
# move to the correct let's encrypt directory
cd /etc/letsencrypt/live/$SITE
COMBINED_FILE=$FOLDER/$SITE.pem
# cat files to make combined .pem for haproxy
cat fullchain.pem > $COMBINED_FILE
echo "" >> $COMBINED_FILE
cat privkey.pem >> $COMBINED_FILE
chmod 600 $COMBINED_FILE
}
for filename in /etc/letsencrypt/renewal/*.conf; do
filename=$(basename $filename)
domain=${filename%.conf}
echo "Combining $domain"
SITE=$domain combine
done
| d238e6baf341da7e721213d4f00edfa13f570131 | [
"Markdown",
"Shell"
] | 7 | Shell | theel0ja/haproxy-scripts | d13df36dab52a43dad5c9a3094b85273d9b92f59 | 48c71e4756455b73340ed735b19e223d6c2a8b4f |
refs/heads/master | <file_sep>{% extends "badger/base.html" %}
{% load i18n %}
{% block pageid %}badge_awards_by_user{% endblock %}
{% block extrahead %}
<link rel="alternate" type="application/atom+xml"
title="{{ _('Recent awards') }}"
href="{% url badger.feeds.awards_by_user 'atom' user.username %}" />
{% endblock %}
{% block content %}
<section class="awards_list">
<div class="page-header">
<h2>{% blocktrans %}Awards for {{user}}{%endblocktrans%}</h2>
</div>
{% include "badger/includes/awards_as_badges_list.html" %}
</section>
{% endblock %}
<file_sep>=============
django-badger
=============
.. image:: https://secure.travis-ci.org/lmorchard/django-badger.png?branch=master
:target: http://travis-ci.org/lmorchard/django-badger
Badger is a family of Django apps intended to help introduce badges into your
project, to track and award achievements by your users. This can be used to
help encourage certain behaviors, recognize skills, or just generally
celebrate members of your community.
For more about the thinking behind this project, check out this essay:
`Why does Mozilla need a Badger? <http://decafbad.com/2010/07/badger-article/>`_
The ``django-badger`` package is the core Badger app. It offers (or plans to
offer) the following:
- Basic badges, managed by the site owner in code and via Django admin.
- Badge awards, triggered in response to signal-based events with code
collected in per-app ``badges.py`` modules.
- Views and models that enable users to create their own badges and nominate
each other for awards.
- Meta-badges, for which an award is automatically issued when a complete set
of prerequisite badge awards have been collected.
- Progress tracking, for which an award is issued when a user metric reaches
100% of some goal, or in response to some other custom logic.
- Activity streams of badge awards.
If you want to federate or share badges, you should check out
the `Mozilla Open Badges <https://github.com/mozilla/openbadges>`_ project.
Installation
------------
- TBD, see `badg.us <https://github.com/lmorchard/badg.us>`_ for an example
site setup
- ``pip install git://github.com/lmorchard/django-badger.git#egg=django-badger``
Settings
--------
- TBD, see `badg.us <https://github.com/lmorchard/badg.us>`_ for an example
site setup
- TBD, see ``badger/tests/badger_example/badges.py`` for an example.
Templates
---------
There are two sets of templates in the templates folder. The templates
found in ``badger_playdoh`` are intended for use with Playdoh sites, while
those found in ``badger_vanilla`` are meant for plain Django sites.
You'll need to make a copy of one of these folders into a directory named
``templates/badger`` at the top level of your project. Then, you can customize
the templates as necessary for your site.
Creating badges
---------------
- TBD, see ``badger/tests/badger_example/badges.py`` for an example.
Awarding badges
---------------
- TBD, see ``badger/tests/badger_example/badges.py`` for an example.
Testing
-------
- TBD, see `badg.us <https://github.com/lmorchard/badg.us>`_ for an example
site setup
.. vim:set tw=78 ai fo+=n fo-=l ft=rst:
<file_sep>{% load i18n %}
{% load badger_tags %}
{% if not award and user.is_staff %}
<div class="btn-group well ">
{% if badge|permissions_for:request.user|key:'edit_by' %}
<a class="btn btn-large btn-primary edit_badge" href="{% url badger.views.edit badge.slug %}">{{ _('Edit') }}</a>
{% endif %}
{% if badge|permissions_for:request.user|key:'delete_by' %}
<a class="btn btn-large btn-danger delete_badge" href="{% url badger.views.delete badge.slug %}">{{ _('Delete') }}</a>
{% endif %}
</div>
{% endif %}
<div class="badge-detail well" data-slug="{{ badge.slug }}">
<div class="row">
<div class="span4">
{% if award and award.image %}
<div class="image"><a href="#" class="image"><img src="{{ award.image.url }}" /></a></div>
{% else %}
{%if badge.image %}
<div class="image"><a href="#" class="image"><img src="{{ badge.image.url }}"/></a></div>
{%endif%}
{% endif %}
</div>
</div>
<div class="row">
<div class="span3">
<div class="page-header">
<h2 class="title">{{ badge.title }}</h2>
</div>
<div class="row">
<div class="span4">
{% if badge.description %}
<blockquote class="description">{{ badge.description }}</blockquote>
{% endif %}
</div>
</div>
{% if user.is_authenticated %}
<div class="row">
<div class="span3">
<div class="progress progress-success">
<div class="bar" style="width: {{ badge|badge_progress:user }}%;"><span class="label">{{ badge|badge_progress:user }}%</span></div>
</div>
</div>
</div>
<div class="row">
<div class="span4">
{% with badge|claim_code_for_badge:user as code %}
{% if code %}
<a class="btn btn-large btn-success" href="{% url badger.claim_deferred_award code %}"> {% trans "Claim the badge" %}</a>
{% endif %}
{% endwith %}
</div>
</div>
{% endif %}
</div>
</div>
<ul class="actions">
{% if allow_award %}
<li><a class="award_badge" href="{% url badger.award_badge badge.slug %}">{{ _('Issue award') }}</a></li>
{% endif %}
{%comment%}
{# TODO: Can this be done extensibly? with a registry? #}
{% set modules = [ "badger_multiplayer" ] %}
{% for module in modules %}
{% include module ~ "/includes/badge_full_actions.html" %}
{% endfor %}
{%endcomment%}
</ul>
</div>
<div class="badge-bottom"></div>
<file_sep>import json
import random
import time
# django
from django import template
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.utils.safestring import mark_safe
from django.contrib.auth.models import SiteProfileNotAvailable
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from settings import BADGER_UPLOADS_URL
from badger.models import mk_upload_to, Award, Badge, DeferredAward
from taggit.models import Tag, TaggedItem
import hashlib
import urllib
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def permissions_for(obj, user):
try:
return obj.get_permissions_for(user)
except:
return {}
@register.filter
def key(obj, name):
try:
return obj[name]
except:
return None
@register.filter
def badge_progress(badge, user):
try:
Award.objects.get(user=user, badge=badge)
return 100
except Award.DoesNotExist:
percent = badge.progress_for(user).percent
if percent > 100:
percent = 100
return percent
@register.simple_tag
def user_avatar(user, secure=False, size=256, rating='pg', default=''):
try:
profile = user.get_profile()
if profile.avatar:
return profile.avatar.url
except SiteProfileNotAvailable:
pass
except ObjectDoesNotExist:
pass
except AttributeError:
pass
base_url = (secure and 'https://secure.gravatar.com' or
'http://www.gravatar.com')
m = hashlib.md5(user.email)
return '%(base_url)s/avatar/%(hash)s?%(params)s' % dict(
base_url=base_url, hash=m.hexdigest(),
params=urllib.urlencode(dict(
s=size, d=default, r=rating
))
)
@register.simple_tag
def award_image(award):
if award.image:
img_url = award.image.url
elif award.badge.image:
img_url = award.badge.image.url
else:
img_url = "/media/img/default-badge.png"
return img_url
@register.simple_tag
def user_award_list(badge, user):
if badge.allows_award_to(user):
return '<li><a class="award_badge" href="%s">%s</a></li>' % ( reverse('badger.views.award_badge', args=[badge.slug,]), _('Issue award') )
else:
return ''
MK_UPLOAD_TMPL = '%(base)s/%(slug)s_%(field_fn)s_%(ext)s'
def mk_upload_to2(field_fn, ext, tmpl=MK_UPLOAD_TMPL):
"""upload_to builder for file upload fields"""
def upload_to(instance, filename):
base, slug = instance.get_upload_meta()
return tmpl % dict(slug=slug[:50], base=base, field_fn=field_fn,
ext=ext)
return upload_to
def badge(badge, size):
name = mk_upload_to2("medium", "image.png")
return "%s%s" % (BADGER_UPLOADS_URL, name(badge,""))
register.simple_tag(badge)
@register.filter(name="user_award")
def user_award(user):
awards = Award.objects.filter(user=user)
return awards
@register.filter
def claim_code_for_badge(badge, user):
das = DeferredAward.objects.filter(badge=badge, email=user.email)
if len(das) > 0:
da = das[0]
code = da.claim_code
else:
code = ""
return code
@register.filter
def badges_by_tag(tag, badge_ids=None):
badges = Badge.objects.filter(tags__id=tag)
if badge_ids:
badges = badges.filter(id__in=badge_ids)
return badges
@register.filter
def get_tag_name(tag):
try:
return Tag.objects.get(id=tag).name
except Tag.DoesNotExist:
return ""
| 2d0c7c306a4940a008074a0a764f32d987041450 | [
"Python",
"HTML",
"reStructuredText"
] | 4 | HTML | shanbay/django-badger | bd5206ad2d1341a6dc5726efd772f8ea882667ae | f061e88e25b2ae4fae4200fe41a3dbd02371af1a |
refs/heads/master | <file_sep>UPDATE airplane
SET AirlineCompany='Nu Delta Airlines', AirplaneTypeName='Air Hamburg 777'
WHERE AirplaneID='453';
UPDATE airport
SET AName ='Hamburg International Airport', Location='Hamburg'
WHERE AirportId ='4Go6XIuL';
#change flight arrivalid to hnP8JfJK from 4Go6XIuL
UPDATE flight
SET FlightType='domestic', FAirlineCompany='Hamburg',AAirportId='hnP8JfJK'
WHERE FlightNum ='3XTSc0w1';
UPDATE arrives
SET ArrivalTime ='2015-9-23 07:11:23'
WHERE FlightNum ='V0yB0shIgXjuewyw' AND AirportId ='v5sf6ix';
UPDATE departs
SET DepartureTime ='2015-9-22 13:19:26'
WHERE FlightNum ='V0yB0shIgXjuewyw' AND AirportId ='4Go6XIuL';
UPDATE payment
SET BillingAddress='Orangeburg', BillingZip='29115'
WHERE CreditCardNum='9432417733935053' AND CreditCardType='Discover';
UPDATE itinerary
SET SeatNumber ='009A'
WHERE ItineraryId='7q0t92x8Fs';
DELETE from passenger
WHERE IdNum = '228Mt1Pn4bw1' and IdType ='State ID';
INSERT INTO passenger VALUES ('228Mt1Pn4bw1','Passport','Walter','W','White','505-555-1258','<EMAIL>','308 Negra Arroyo Lane','1996-04-07','6824082366125565','6L0r91u4ic');
INSERT INTO payment VALUES ('7049044963388063','MasterCard','2015/05/24','2016/07/24',1,'NBAho99KJLoh',356,'57371 East Bahrain Way','<NAME>','68674');
INSERT INTO passenger VALUES ('8122qaFy7Ya8','License','Cassady','J','Carey','964-946-9768','<EMAIL>','39942 West Central African Republic Blvd.','1967-07-22','7049044963388063','9c0P37N5Kq');
select * from airplane;
select * from airport;
select * from flight;
select * from arrives;
select * from departs;
select * from payment;
select * from itinerary;
select * from passenger;
<file_sep>INSERT INTO airplane VALUES (450,'Ferris Aircrafts',10,227,'Air QOSBXs 682');
INSERT INTO airplane VALUES (451,'Oceanic Airlines',17,116,'Air WPNbFZ 128');
INSERT INTO airplane VALUES (452,'Solar Airways',16,298,'Air BbXYuu 710');
INSERT INTO airplane VALUES (453,'Star Tours Airline',13,305,'Air SSjtiS 498');
INSERT INTO airplane VALUES (454,'Virtual Airline',12,800,'Air ZzAWvV 174');
INSERT INTO airplane VALUES (455,'Wayne Airlines',21,253,'Air YLjEJR 423');
INSERT INTO airplane VALUES (456,'LEX Airways',18,251,'Air MEPsvJ 948');
INSERT INTO airplane VALUES (457,'Laserebeak Airlines',21,312,'Air RXbORg 192');
INSERT INTO airplane VALUES (458,'Phoenix Airlines',20,99,'Air QCOjdx 012');
INSERT INTO airplane VALUES (459,'Stark Airlines',14,357,'Air OvoJfk 900');
INSERT INTO airport VALUES ('gWyc4tfA6t4BtXH','Guantanamo International Airport','Moore');
INSERT INTO airport VALUES ('FwCmHpN','Justice League International Airport','Miami Beach');
INSERT INTO airport VALUES ('nHBE5YFBbzuY','Valkyrie International Airport','Ontario');
INSERT INTO airport VALUES ('hnP8JfJK','Blitz Krieg Airport','New Castle');
INSERT INTO airport VALUES ('4Go6XIuL','Dallas International Airport','Montpelier');
INSERT INTO airport VALUES ('v5sf6ix','Boston Harbor Airport','Visalia');
INSERT INTO airport VALUES ('PwEfmKxhl','Laguardia International Airport','Salinas');
INSERT INTO airport VALUES ('AV5skTl0n2zVz','Denver International Airport','Santa Clara');
INSERT INTO airport VALUES ('7Z2cRr3ITF','Atlantis International Airport','Pullman');
INSERT INTO airport VALUES ('mMWDx4tt','Seattle International Airport','Austin');
INSERT INTO flight VALUES ('Eft2w3uVQ','Transatlantic','Ferris Aircrafts',450,'gWyc4tfA6t4BtXH','FwCmHpN');
INSERT INTO flight VALUES ('LnnlXeQDHFfNp8','Transatlantic','Oceanic Airlines',451,'FwCmHpN','gWyc4tfA6t4BtXH');
INSERT INTO flight VALUES ('cFFowFSb3','Domestic','Solar Airways',452,'nHBE5YFBbzuY','hnP8JfJK');
INSERT INTO flight VALUES ('S4A5JdS3UC1g5A','Domestic','Star Tours Airline',453,'hnP8JfJK','nHBE5YFBbzuY');
INSERT INTO flight VALUES ('3XTSc0w1','Transatlantic','Virtual Airline',454,'4Go6XIuL','v5sf6ix');
INSERT INTO flight VALUES ('V0yB0shIgXjuewyw','Interanational','Wayne Airlines',455,'v5sf6ix','4Go6XIuL');
INSERT INTO flight VALUES ('jU7nSX3Vkjw','Transatlantic','LEX Airways',456,'PwEfmKxhl','AV5skTl0n2zVz');
INSERT INTO flight VALUES ('aAk7c9t','Domestic','Laserebeak Airlines',457,'AV5skTl0n2zVz','PwEfmKxhl');
INSERT INTO flight VALUES ('fEkbR3Ll1ZR1bOdj','Domestic','Phoenix Airlines',458,'7Z2cRr3ITF','mMWDx4tt');
INSERT INTO flight VALUES ('s8wF5NC2WcL','Interanational','Stark Airlines',459,'mMWDx4tt','7Z2cRr3ITF');
INSERT INTO arrives VALUES ('2015-12-19 8:17:47','s8wF5NC2WcL','mMWDx4tt');
INSERT INTO arrives VALUES ('2015-4-23 10:52:39','fEkbR3Ll1ZR1bOdj','7Z2cRr3ITF');
INSERT INTO arrives VALUES ('2015-3-14 5:14:46','aAk7c9t','AV5skTl0n2zVz');
INSERT INTO arrives VALUES ('2015-7-25 3:18:54','jU7nSX3Vkjw','PwEfmKxhl');
INSERT INTO arrives VALUES ('2015-9-22 11:31:39','V0yB0shIgXjuewyw','v5sf6ix');
INSERT INTO arrives VALUES ('2015-2-17 14:28:42','3XTSc0w1','4Go6XIuL');
INSERT INTO arrives VALUES ('2015-11-15 23:04:23','S4A5JdS3UC1g5A','hnP8JfJK');
INSERT INTO arrives VALUES ('2015-8-11 13:26:43','cFFowFSb3','nHBE5YFBbzuY');
INSERT INTO arrives VALUES ('2015-7-12 20:19:20','LnnlXeQDHFfNp8','FwCmHpN');
INSERT INTO arrives VALUES ('2015-10-27 1:53:50','Eft2w3uVQ','gWyc4tfA6t4BtXH');
INSERT INTO departs VALUES ('2015-12-18 5:02:01','s8wF5NC2WcL','7Z2cRr3ITF');
INSERT INTO departs VALUES ('2015-4-22 9:02:43','fEkbR3Ll1ZR1bOdj','mMWDx4tt');
INSERT INTO departs VALUES ('2015-3-13 15:37:48','aAk7c9t','PwEfmKxhl');
INSERT INTO departs VALUES ('2015-7-24 14:16:21','jU7nSX3Vkjw','AV5skTl0n2zVz');
INSERT INTO departs VALUES ('2015-9-21 8:14:52','V0yB0shIgXjuewyw','4Go6XIuL');
INSERT INTO departs VALUES ('2015-2-16 9:24:41','3XTSc0w1','v5sf6ix');
INSERT INTO departs VALUES ('2015-11-14 7:11:51','S4A5JdS3UC1g5A','nHBE5YFBbzuY');
INSERT INTO departs VALUES ('2015-8-10 15:30:52','cFFowFSb3','hnP8JfJK');
INSERT INTO departs VALUES ('2015-7-11 3:19:55','LnnlXeQDHFfNp8','gWyc4tfA6t4BtXH');
INSERT INTO departs VALUES ('2015-10-26 15:08:31','Eft2w3uVQ','FwCmHpN');
INSERT INTO payment VALUES ('4331299394247220','Visa','2015/06/28','2019/07/23',0,'XlRAy57tSx3Z',123,'84483 South Mozambique St.','<NAME>ernandez','26630');
INSERT INTO payment VALUES ('0708457189565092','MasterCard','2015/08/29','2019/01/28',1,'upEWdvhodcz0',345,'40609 North Lithuania Ln.','<NAME>','79796');
INSERT INTO payment VALUES ('0528235582485817','Discover','2015/05/10','2019/09/13',0,'2c0aQGYyHQSp',987,'50686 South Falkland Islands (Malvinas) Ln.','<NAME>','22120');
INSERT INTO payment VALUES ('1638510283552897','American Express','2015/10/22','2016/12/09',1,'bASptOkWKzRZ',852,'16558 South Kona Ct.','<NAME>','49958');
INSERT INTO payment VALUES ('1504932062756989','American Express','2015/02/27','2016/06/03',1,'LMqk5BJUMrpk',357,'1605 East Namibia Blvd.','<NAME>','94592');
INSERT INTO payment VALUES ('2667953123847744','Discover','2015/09/06','2019/08/15',0,'L9lmvpfDav4u',539,'33924 North Cocos (Keeling) Islands Blvd.','<NAME>','08943');
INSERT INTO payment VALUES ('9432417733935053','Discover','2015/01/04','2017/03/09',1,'7kvhdXUGWfSp',789,'84345 West Cambodia St.','Jason X Lane','01724');
INSERT INTO payment VALUES ('3576428735796129','American Express','2015/07/30','2018/09/07',1,'hf41HasPrQjf',423,'58608 North Bulgaria Ln.','<NAME>','35477');
INSERT INTO payment VALUES ('6824082366125565','American Express','2015/06/08','2017/09/06',1,'dw7srtRZWT51',073,'13537 Bangladesh Ln.','<NAME> Guerrero','12290');
INSERT INTO payment VALUES ('7049044963388063','MasterCard','2015/04/24','2016/07/24',0,'Nh09BA9KJLeh',356,'57371 East Bahrain Way','<NAME>','68674');
INSERT INTO itinerary VALUES ('1U9G34g8va',2,'077A');
INSERT INTO itinerary VALUES ('0r3u48p7HI',2,'028C');
INSERT INTO itinerary VALUES ('7q0t92x8Fs',4,'009B');
INSERT INTO itinerary VALUES ('0z1U27j1Ni',0,'191A');
INSERT INTO itinerary VALUES ('6J9F00Z8iv',0,'210B');
INSERT INTO itinerary VALUES ('8R7o79Z1Na',2,'197B');
INSERT INTO itinerary VALUES ('9w0s77m5wu',3,'047C');
INSERT INTO itinerary VALUES ('2z6A63H8lI',3,'020A');
INSERT INTO itinerary VALUES ('6L0r91u4ic',4,'257D');
INSERT INTO itinerary VALUES ('9c0P37N5Kq',2,'002A');
INSERT INTO requires VALUES ('s8wF5NC2WcL','9c0P37N5Kq');
INSERT INTO requires VALUES ('fEkbR3Ll1ZR1bOdj','6L0r91u4ic');
INSERT INTO requires VALUES ('aAk7c9t','2z6A63H8lI');
INSERT INTO requires VALUES ('jU7nSX3Vkjw','9w0s77m5wu');
INSERT INTO requires VALUES ('V0yB0shIgXjuewyw','8R7o79Z1Na');
INSERT INTO requires VALUES ('3XTSc0w1','6J9F00Z8iv');
INSERT INTO requires VALUES ('S4A5JdS3UC1g5A','0z1U27j1Ni');
INSERT INTO requires VALUES ('cFFowFSb3','7q0t92x8Fs');
INSERT INTO requires VALUES ('LnnlXeQDHFfNp8','0r3u48p7HI');
INSERT INTO requires VALUES ('Eft2w3uVQ','1U9G34g8va');
INSERT INTO passenger VALUES ('812Fy7Ya2qa8','License','Cassady','J','Carey','964-946-9768','<EMAIL>','39942 West Central African Republic Blvd.','1967-07-22','7049044963388063','9c0P37N5Kq');
INSERT INTO passenger VALUES ('228Mt1Pn4bw1','State ID','Wyatt','A','Guerrero','058-821-1698','<EMAIL>','28111 New Caledonia Way','1996-04-07','6824082366125565','6L0r91u4ic');
INSERT INTO passenger VALUES ('421Cv0Hz6bv8','License','Chava','G','Pugh','661-996-8856','<EMAIL>','96196 South Beaver Falls Ave.','1985-04-10','3576428735796129','2z6A63H8lI');
INSERT INTO passenger VALUES ('238Xb3Yb1bv1','State ID','Jason','X','Lane','611-427-9882','<EMAIL>','84345 West Cambodia St.','1953-09-16','9432417733935053','9w0s77m5wu');
INSERT INTO passenger VALUES ('977Nm7Rv5uo0','Passport','Amir','H','Fowler','664-043-6230','<EMAIL>','33924 North Cocos (Keeling) Islands Blvd.','1985-04-17','2667953123847744','8R7o79Z1Na');
INSERT INTO passenger VALUES ('129Sw1Yh1ln5','State ID','Phelan','K','Nicholson','594-502-1280','<EMAIL>','1605 East Namibia Blvd.','1984-03-17','1504932062756989','6J9F00Z8iv');
INSERT INTO passenger VALUES ('821Hq4Df6ks9','Passport','Nehru','A','Whitney','581-948-3624','<EMAIL>','16558 South Kona Ct.','2007-05-17','1638510283552897','0z1U27j1Ni');
INSERT INTO passenger VALUES ('532Qt3Ru1fp5','License','Chandler','F','Mercado','804-714-5201','<EMAIL>','50665 South Highland Park Blvd.','1959-08-10','0528235582485817','7q0t92x8Fs');
INSERT INTO passenger VALUES ('316Vy9Lr1zz8','License','Jessica','Y','Willis','629-266-7432','<EMAIL>','40609 North Lithuania Ln.','1980-02-17','0708457189565092','0r3u48p7HI');
INSERT INTO passenger VALUES ('638Pw9Ix2sa6','Passport','Ali','S','Fernandez','204-351-0297','<EMAIL>','64847 East Brunei Darussalam Ct.','1996-12-30','4331299394247220','1U9G34g8va');
INSERT INTO has VALUES (740.26,'9c0P37N5Kq','638Pw9Ix2sa6');
INSERT INTO has VALUES (274.93,'6L0r91u4ic','316Vy9Lr1zz8');
INSERT INTO has VALUES (1674.00,'2z6A63H8lI','532Qt3Ru1fp5');
INSERT INTO has VALUES (958.82,'9w0s77m5wu','821Hq4Df6ks9');
INSERT INTO has VALUES (81.01,'8R7o79Z1Na','129Sw1Yh1ln5');
INSERT INTO has VALUES (470.57,'6J9F00Z8iv','977Nm7Rv5uo0');
INSERT INTO has VALUES (349.93,'0z1U27j1Ni','238Xb3Yb1bv1');
INSERT INTO has VALUES (211.36,'7q0t92x8Fs','421Cv0Hz6bv8');
INSERT INTO has VALUES (443.57,'0r3u48p7HI','228Mt1Pn4bw1');
INSERT INTO has VALUES (278.14,'1U9G34g8va','812Fy7Ya2qa8');
<file_sep>#Basic Queries
select AirlineCompany
from airplane
where AirplaneId='457';
select Aname,Location
from airport
where AirportId='4Go6XIuL';
select FName,Minit,LName
from passenger
where DOB='1959-08-10';
select FlightType,FAirlineCompany
from flight
where FlightNum ='LnnlXeQDHFfNp8';
select IdType
from passenger
where IdNum='812Fy7Ya2qa8';
select Distinct FAirlineCompany,FlightType
from flight,airplane
where FlightNum = 'cFFowFSb3' AND AAirportId ='nHBE5YFBbzuY';
select fare,Email
from passenger,has
where passenger.ItineraryId='1U9G34g8va' AND has.ItineraryId='1U9G34g8va';
select ArrivalTime,DepartureTime,flight.FlightNum
from arrives,departs,flight
where flight.FlightNume=arrives.FlightNum AND arrives.FlightNum = departs.FlightNum;
select FName,Minit,LName,Billingzip,CreditCardType
from passenger,payment
where passenger.Address=payment.BillingAddress;
select distinct avg(fare), count(IdNum)
from has,passenger
where IdType='License' AND IdNum=PassengerId;
select distinct max(CreditCardNum), count(IdNum )
from passenger,payment
where payment.status=0
group by IdNum;
select distinct IdNum, idtype,count(*)
from passenger,payment
where PaymentId=CreditCardNum
group by IdNum,IdType;
select distinct IdNum, idtype,count(*)
from passenger,payment
where PaymentId=CreditCardNum
group by IdNum,IdType
having count(*)>1;
select Fname,LName,Phone
from passenger
where idtype ='Passport'
union
(
select Fname,LName,Phone
from passenger
where idtype ='State ID'
);
SELECT passenger.IdNum, passenger.FName, passenger.Address,payment.BillingAddress
FROM passenger
INNER JOIN payment
ON passenger.PaymentId=payment.CreditCardNum;
create view nationals
as select Fname,Minit,Lname,Email
from passenger
where IdType='State ID' OR IdType='License'
order by Fname;
select * from nationals;
Create view creditdis as
SELECT passenger.IdNum, passenger.FName, passenger.Minit, passenger.Lname,passenger.email,payment.CreditCardType
FROM passenger
INNER JOIN payment
ON passenger.PaymentId=payment.CreditCardNum;
select * from creditdis;
create view unacceptables
as select Fname,Minit,Lname,Email,CreditCardType
from creditdis
where CreditCardType='Discover' OR CreditCardType='American Express'
order by Fname,CreditCardType;
select * from unacceptables;
select Minit from unacceptables;<file_sep>
#airline schema
DROP DATABASE IF EXISTS airline;
CREATE DATABASE airline;
Use airline;
#Drop Table airplane
CREATE TABLE airplane(
AirplaneId VARCHAR(10) NOT NULL,
AirlineCompany VARCHAR(35) NOT NULL,
CrewSeats INTEGER(4),
PassengerSeats INTEGER(4),
AirplaneTypeName VARCHAR(30)NOT NULL,#what is this think about it
PRIMARY KEY(AirplaneId)
);
#Drop Table airport
CREATE TABLE airport (
AirportId VARCHAR(30) NOT NULL,
AName VARCHAR(50) NOT NULL,
Location VARCHAR(30),# what is this?
PRIMARY KEY(AirportId)
);
#Drop Table flight
CREATE TABLE flight(
FlightNum VARCHAR(30) NOT NULL,
FlightType VARCHAR(30),
FAirlineCompany VARCHAR(30),
AirplaneId VARCHAR(10) NOT NULL,
AAirportId VARCHAR(30) NOT NULL,
DAirportId VARCHAR(30) NOT NULL,#
PRIMARY KEY (FlightNum),
FOREIGN KEY(AirplaneId) REFERENCES airplane(AirplaneId)
on update cascade
on delete cascade,
FOREIGN KEY(AAirportId) REFERENCES airport(AirportId)
on update cascade
on delete cascade,
FOREIGN KEY(DAirportId) REFERENCES airport(AirportId)
on update cascade
on delete cascade
);
#Drop Table arrives
CREATE TABLE arrives(
ArrivalTime DATETIME,
FlightNum VARCHAR(30)NOT NULL,
AirportId VARCHAR(30)NOT NULL,
PRIMARY KEY (FlightNum,AirportId),
FOREIGN KEY(FlightNum) REFERENCES flight(FlightNum)
on update cascade
on delete cascade,
FOREIGN KEY(AirportId) REFERENCES airport(AirportId)
on update cascade
on delete cascade);
#Drop Table departs
CREATE TABLE departs(
DepartureTime DATETIME,
FlightNum VARCHAR(30)NOT NULL,
AirportId VARCHAR(30)NOT NULL,
PRIMARY KEY (FlightNum,AirportId),
FOREIGN KEY(FlightNum) REFERENCES flight(FlightNum)
on update cascade
on delete cascade,
FOREIGN KEY(AirportId) REFERENCES airport(AirportId)
on update cascade
on delete cascade);
#Drop Table payment
CREATE TABLE payment(
CreditCardNum VARCHAR(16) NOT Null,
CreditCardType VARCHAR(30)NOT NULL,
PDate DATE,
ExpirationDate DATE,
Status BIT NOT NULL,
ConfirmationNumber VARCHAR(30)NOT NULL,
SecurityCode INTEGER,
BillingAddress VARCHAR(70)NOT NULL,
BillingName VARCHAR(30)NOT NULL,
BillingZip INTEGER,
PRIMARY KEY (CreditCardNum,ConfirmationNumber));
#Drop Table itinerary
CREATE TABLE itinerary(
ItineraryId VARCHAR(30)NOT NULL,
LegNum Integer,
SeatNumber VARCHAR(30)NOT NULL,
#PassengerID VARCHAR ,
PRIMARY KEY(ItineraryId )
/*FOREIGN KEY(PassengerID) REFERENCES PASSENGER(IdNumber)
on update cascade
on delete cascade */
);
#DROP TABLE requires
CREATE TABLE requires(
FlightNum VARCHAR(30) NOT NULL,
ItineraryId VARCHAR(30) NOT NULL,
PRIMARY KEY (FlightNum,ItineraryId),
FOREIGN KEY(FlightNum) REFERENCES FLIGHT(FlightNum)
on update cascade
on delete cascade,
FOREIGN KEY(ItineraryId) REFERENCES ITINERARY(ItineraryId)
on update cascade
on delete cascade);
#DROP TABLE passenger
CREATE TABLE passenger(
IdNum varchar(14) not null,
IdType varchar(8) not null,
FName varchar(15) not null,
Minit varchar(1),
LName varchar(15) not null,
Phone varchar(15),
Email varchar(30),
Address varchar(70),
DOB date,
PaymentId VARCHAR(16) NOT Null,
ItineraryId VARCHAR(30)NOT NULL,
PRIMARY KEY(IdNum,IdType),
FOREIGN KEY (PaymentId) References payment(CreditCardNum)
on update cascade
on delete cascade,
FOREIGN KEY(ItineraryId) REFERENCES itinerary(ItineraryId)
on update cascade
on delete cascade);
#DROP TABLE has
CREATE TABLE has(
Fare DECIMAL(7,2) NOT Null,
ItineraryId VARCHAR(30)NOT NULL,
PassengerId VARCHAR(30)NOT NULL,
PRIMARY KEY (ItineraryId,PassengerId),
FOREIGN KEY(ItineraryId) REFERENCES itinerary(ItineraryId)
on update cascade
on delete cascade,
FOREIGN KEY(PassengerId) REFERENCES passenger(IdNum)
on update cascade
on delete cascade);
| 28d0b948b61a9a3efcb632f155d73cbcccfd2d42 | [
"SQL"
] | 4 | SQL | red37/airdatabase | 3946affbb6a65afa7aa61ce847fe61231d26f8d6 | d3424fbf443182ebb4aaafc180837f6586cc4f31 |
refs/heads/master | <repo_name>jacobNil/LintCode<file_sep>/leetcode/06 review/GenerateParenthesis.java
//generate parenthesis
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if (n <= 0) {
return result;
}
dfsGenerate("", result, n , n);
int dff = 0;
dfsGenerate("". result, diff);
return result;
}
private void dfsGenerate(String curr, List<String> result, int leftNumber,
int rightNumber) {
// 看到了 没说你 哈哈哈哈哈
if (leftNumber > rightNumber) {
return;
}
if (leftNumber > 0) {
dfsGenerate(curr + "(", result, leftNumber - 1, rightNumber);
}
if (rightNumber > 0) {
dfsGenerate(curr + ")", result, leftNumber, rightNumber - 1);
}
if (leftNumber == 0 && rightNumber == 0) {
result,add(curr);
return;
}
}<file_sep>/LeetCode/uberTag/450DeleteNodeInBST.java
// april 30, <NAME>
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
//base case
if(root == null) {
return root;
}
// key is in the left subtree
if(root.val < key) {
root.right = deleteNode(root.right, key);
return root;
}
// key in the right subtree
if(root.val > key) {
root.left = deleteNode(root.left, key);
return root;
}
// current root is key
if(root.val == key) {
// node contains key value has no child
if(root.left == null && root.right == null) {
return null;
}
// node contains key value has one child
if(root.left == null) {
return root.right;
}
if(root.right == null) {
return root.left;
}
// node has both children: use 1)min value of right subtree or 2)max of left subtree
TreeNode minNode = minNodeOfTree(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
return root;
}
return root;
}
// helper funtion can find the min value of a bst.
private TreeNode minNodeOfTree(TreeNode root) {
while(root.left != null) {
root = root.left;
}
return root;
}
}
<file_sep>/leetcode/02 recursion/ReverseLinkedList.java
/**
* 206 reverse linked list
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
//return reverseByIteration(head);
ListNode prev = null;
return reverseByRecursion(prev, head);
}
// iteration version
private ListNode reverseByIteration(ListNode head) {
if (head == null || head.next == null) return head;
ListNode last = null;
ListNode curr = head;
ListNode next = head.next;
while(next != null) {
curr.next = last;
last = curr;
curr = next;
next = next.next;
}
curr.next = last;
return curr;
}
// recursion version
private ListNode reverseByRecursion(ListNode prev, ListNode head) {
ListNode next = head.next;
head.next = prev;
// base case
if (next == null) {
return head;
}
// recursion case
return reverseByRecursion(head, next);
}
}<file_sep>/LeetCode/amazon/amazonTagLeetcode/661. Image Smoother.java
class Solution {
public int[][] imageSmoother(int[][] M) {
if(M == null ||M.length == 0 || M[0] == null || M[0].length == 0) {
return null;
}
int rows = M.length;
int cols = M[0].length;
int[][] result = new int[rows][cols];
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++) {
int sum = 0;
int count = 0;
for(int i : new int[]{-1, 0 ,1}) {
for (int j : new int[]{-1, 0 , 1}) {
if(isValid(rows, cols, row+i, col+j)) {
sum += M[row+i][col+j];
count++;
}
}
}
result[row][col]=sum/count;
}
}
return result;
}
private boolean isValid(int rows, int cols, int i, int j) {
if(i >= 0 && i < rows && j >=0 && j < cols) {
return true;
}
return false;
}
}<file_sep>/README.md
# LintCode
Just a blog for practice of LintCode. No big deal.
Jan-20
* Subset I —> subset with no duplicate element in list
use DFS
* Subset II —> subset with duplicate.
use DFS
be careful with the duplicate part.
//Binary Tree and Divide Conquer
* Maximum Depth of Binary Tree
* Hash Function
* Balanced Binary Tree
two different strategy: 1) create a new class for containing result, with field of maxDepth and isBalanced
2) use only int result to represent maxDepth of subtree when balanced and -1 when the
subtree is not balanced.
* balanced tree sum:
* balanced tree sum ii:
root to any
root to leaf
any to any // the most difficult problem for binary divide and conquer
<file_sep>/lowest common ancestor.java
// lowest common ancestor of binary tree
// use divide conquer and recursion
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if (root == null) {
return root;
}
if (A == null || B == root) {
return B;
}
if (B == null || A == root) {
return A;
}
// divede
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
// conquer or merge
if (left == null) {
return right;
}
if (right == null) {
return left;
}
if (left == A && right ==B || right == A && left == B) {
return root;
}
return null;
}
}
<file_sep>/LeetCode/108. Convert Sorted Array to Binary Search Tree.java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//////////////////////////////////////////////////////////////////////////////////////////
// solution1
//////////////////////////////////////////////////////////////////////////////////////////
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
if(nums.length == 1) {
return new TreeNode(nums[0]);
}
if(nums.length == 2) {
TreeNode result = new TreeNode(nums[0]);
result.right = new TreeNode(nums[1]);
return result;
}
int start = 0;
int end = nums.length - 1;
int mid = start + (end-start)/2;
TreeNode root = new TreeNode(nums[mid]);
addSortedArrayToBST(nums, root, start, mid-1);
addSortedArrayToBST(nums, root, mid+1, end);
return root;
}
private void addSortedArrayToBST(int[] nums, TreeNode root, int start, int end) {
if(start == end) {
addToBST(root, nums[start]);
return;
}
// dead loop will happen when the interval is like (2, 3)
if ((start + 1) == end) {
addToBST(root, nums[start]);
addToBST(root, nums[end]);
return;
}
int mid = start + (end-start)/2;
addToBST(root, nums[mid]);
addSortedArrayToBST(nums, root, start, mid-1);
addSortedArrayToBST(nums, root, mid+1, end);
}
private void addToBST(TreeNode root, int num) {
while(true) {
if(root.val < num) {
if (root.right != null) {
root = root.right;
} else if (root.right == null) {
root.right = new TreeNode(num);
return;
}
} else {
if (root.left != null) {
root = root.left;
} else if (root.left == null) {
root.left = new TreeNode(num);
return;
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// solution 2
// much shorter and cleaner
//////////////////////////////////////////////////////////////////////////////////////////
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
int start = 0;
int end = nums.length - 1;
return addToBST(nums, start, end);
}
private TreeNode addToBST(int[] nums, int start, int end) {
if(start == end) {
return new TreeNode(nums[start]);
}
if(start > end) {
return null;
}
// if start < end
int mid = start + (end-start)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = addToBST(nums, start, mid-1);
root.right = addToBST(nums, mid+1, end);
return root;
}
}
<file_sep>/README.txt
# LintCode
Just a blog for practice of LintCode. No big deal.
Jan-20
> Subset I —> subset with no duplicate element in list
use DFS
> Subset II —> subset with duplicate.
use DFS
be careful with the duplicate part.
//Binary Tree and Divide Conquer
> Maximum Depth of Binary Tree
> Hash Function
> Balanced Binary Tree
two different strategy: 1) create a new class for containing result, with field of maxDepth and isBalanced
2) use only int result to represent maxDepth of subtree when balanced and -1 when the
subtree is not balanced.
Jan-22
binary tree divide conquer
> lowest common ancestor (of two given nodes)
> lowest common ancestor ii
If the node in tree has parent pointer, we can follow the parent pointer from given node to root. So we will
have the path from node to root. If we can find the paths of both nodes, compare the path can help find the LCA.
> Subtree with Maximum Average:
>use traverse and divide conquer. Since the use of traverse, two global variables is necessary:
1) ResultType maxAverage (sum ,count) ----> keep max average record
2) Tree Node subtree ------> keep the subtree with current max average, this is the final return variable
> The recursion function need to 1)return the class ResultType(int sum, int count), which will be used to
calculate average of ParentTreeNode as subtree.
> balanced tree sum:
> balanced tree sum ii:
root to any
root to leaf
any to any // the most difficult problem for binary divide and conquer
<file_sep>/leetcode/06 review/464CanIWin.java
// april 22: time limit exceeded
public class Solution {
public boolean canIWin(int max, int target) {
if(((max + 1) * max /2) < target) {
return false;
}
if(target <= max) {
return true;
}
return dfsHelper(max, target, 0, 0, new HashMap<Integer, Boolean>());
}
private boolean dfsHelper(int max, int target, int current, int used, HashMap<Integer, Boolean> memory ) {
// read memory first---> memorized search
if(current >= target) return false;
if(memory.containsKey(used)) {
return memory.get(used);
}
// if this condition has never been calculated
for(int i = 1; i < max+1; i++) {
// if the number i has been used---> skip this iteration
if((used &= (1<<i)) != 0) {
continue;
}
int nextUsed = used | (1<<i);
// base case
if (!dfsHelper(max, target, current+i, nextUsed, memory)) {
memory.put(used, true);
return true;
}
}
memory.put(used, false);
return false;
}
}
// solution from bittiger 萌萌
public class Solution {
public boolean canIWin(int max, int total) {
if(total <= 0) return true;
if(((max*max + max)/2) < total) return false;
return helper(total, max, 0, new HashMap<Integer, Boolean>());
}
private boolean helper(int total, int max, int state, HashMap<Integer, Boolean> cache) {
// base case
if(total < 0) return true;
// read cache
if(cache.containsKey(state)) return cache.get(state);
// try each possible number
for(int i = 0; i < max; i++) {
// if the number has been used
if((state &= (1<<i)) != 0) {
continue;
}
// induction rules
if(!helper(total-i-1, max, state|(1<<i), cache)) {
cache.put(state, true);
return true;
}
}
cache.put(state, false);
return false;
}
}<file_sep>/leetcode/01 linear data structure/49GroupAnagram.java
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> results = new LinkedList<>();
Arrays.sort(strs);
Map<String, List<String>> anagrams = new HashMap<String, List<String>>(); // when should the angle square be filled??
for (String curr: strs) {
char[] currArray= curr.toCharArray();
Arrays.sort(currArray);
String key = String.valueOf(currArray);
if (!anagrams.containsKey(key)) {
anagrams.put(key, new LinkedList<String>());
}
anagrams.get(key).add(curr);
}
return new ArrayList<List<String>>(anagrams.values());
}
}<file_sep>/lowest common ancestors ii.java
/**
* Definition of ParentTreeNode:
*
* class ParentTreeNode {
* public ParentTreeNode parent, left, right;
* }
*/
public class Solution {
/**
* @param root: The root of the tree
* @param A, B: Two node in the tree
* @return: The lowest common ancestor of A and B
*/
public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root,
ParentTreeNode A,
ParentTreeNode B) {
if (root == null || A == null || B == null) {
return root;
}
ArrayList<ParentTreeNode> ancestorsOfA = new ArrayList<>();
ArrayList<ParentTreeNode> ancestorsOfB = new ArrayList<>();
ancestorsOfA = pathToNode(root, A);
ancestorsOfB = pathToNode(root, B);
int indexA = ancestorsOfA.size() - 1;
int indexB = ancestorsOfB.size() - 1;
// use this LCA ro record the common ancestor until non common node in path
ParentTreeNode LCA = null;
while (indexA >= 0 && indexB >= 0) {
if (ancestorsOfA.get(indexA) != ancestorsOfB.get(indexB)) {
return LCA;
}
LCA = ancestorsOfA.get(indexA);
indexA--;
indexB--;
}
// 1, 2, 4
// 2, 4
return LCA;
}
private ArrayList<ParentTreeNode> pathToNode(ParentTreeNode root, ParentTreeNode node) {
ArrayList<ParentTreeNode> path = new ArrayList<>();
while (node != null) {
path.add(node);
node = node.parent;
}
return path;
}
}
<file_sep>/leetcode/uber tag/242ValidateAnagram.java
// april 26, <NAME>
public class Solution {
public boolean isAnagram(String s, String t) {
// corner case
if(s == null || t == null) return true;
if(s.length() == 0 || s.length() == 0) return true;
if(s.length() != t.length()) return false;
Map<Character, Integer> frequency = new HashMap<>();
// build frequency map based on one string
for(int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
frequency.put(curr, frequency.getOrDefault(curr, 0)+1);
}
// verify the other string
for(int i = 0; i < t.length(); i++) {
char curr = t.charAt(i);
if(frequency.getOrDefault(curr, 0) > 0) {
frequency.put(curr, frequency.get(curr)-1);
} else {
return false;
}
}
// verify nothing left in the table
for(Map.Entry<Character, Integer> entry: frequency.entrySet()) {
if (entry.getValue() != 0) {
return false;
}
}
return true;
}
}<file_sep>/leetcode/uber tag/290WordPattern.java
// april 26
public class Solution {
public boolean wordPattern(String pattern, String str) {
// corner case
if(pattern == null || str == null) return false;
if(pattern.length() == 0 && str.length() == 0) return true;
//split string to form a strng array
String[] words = str.split(" ");
if(pattern.length() != words.length) {
return false;
}
// check with HashMap to see if pattern match
Map<Character, String> bijection = new HashMap<>();
Set<String> element = new HashSet<>();
for(int i = 0; i < pattern.length(); i++) {
if(bijection.containsKey(pattern.charAt(i))) {
if(!bijection.get(pattern.charAt(i)).equals(words[i])) {
return false;
}
} else {
if(element.contains(words[i])) {
return false;
}
bijection.put(pattern.charAt(i), words[i]);
element.add(words[i]);
}
}
return true;
}
}<file_sep>/leetcode/06 review/292NimGame.java
//April 22
// mathematical solution. The only accepted by leetcode
public class Solution {
public boolean canWinNim(int n) {
return ((n%4) != 0);
}
}
// dfs recursion
public class Solution {
public boolean canWinNim(int n) {
if (n <= 3) {
return true;
}
return (!canWinNim(n - 1) || !canWinNim(n - 2) || !canWinNim(n - 3));
}
}
// dp version
public class Solution {
public boolean canWinNim(int n) {
if (n <= 3) {
return true;
}
boolean[] canWin = new boolean[n + 1];
canWin[0] = true;
canWin[1] = true;
canWin[2] = true;
canWin[3] = true;
for(int i = 4; i < canWin.length; i++) {
canWin[i] = (!canWin[i-1]||!canWin[i-2]||!canWin[i-3]);
}
return canWin[n];
}
}
// dp with rolling array version
public class Solution {
public boolean canWinNim(int n) {
if (n <= 3) {
return true;
}
boolean[] canWin = new boolean[4];
canWin[0] = flase;
canWin[1] = true;
canWin[2] = true;
canWin[3] = true;
for(int i = 4; i < canWin.length; i++) {
canWin[i%4] = (!canWin[(i-1)%4]||!canWin[(i-2)%4]||!canWin[(i-3)%4]);
}
return canWin[n%4];
}
}
<file_sep>/leetcode/uber tag/254factorCombination.java
// <NAME>il 29
// solution 1
public class Solution {
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> results = new ArrayList<>();
// corner case
if(n <= 2 || isPrime(n)) {
return results;
}
//get all factors first
List<Integer> factors = getAllFactors(n);
//use dfs? to find all factor combination
dfsHelper(n, 0, factors, results, new ArrayList<Integer>(), new HashSet<String>());
return results;
}
private void dfsHelper(int n,
int index,
List<Integer> factors,
List<List<Integer>> results,
List<Integer> currResult,
Set<String> visited) {
//corner case
if(index == factors.size()) {
if (currResult.size() == 1) {
return;
}
String curr = "";
for(int i : currResult) {
curr += i;
}
if (visited.contains(curr)) {
return;
}
results.add(currResult);
visited.add(curr);
return;
}
//recursion case
// #1 append case
List<Integer> next1 = new ArrayList<>(currResult);
next1.add(factors.get(index));
Collections.sort(next1);
dfsHelper(n, index+1, factors, results, next1, visited);
// combine case
for(int i = 0; i < currResult.size(); i++) {
if(i< currResult.size()-1 && currResult.get(i) == currResult.get(i+1)) {
continue;
}
List<Integer> next2 = new ArrayList<>(currResult);
int newFactor = next2.get(i) * factors.get(index);
next2.set(i, newFactor);
Collections.sort(next2);
dfsHelper(n, index+1, factors, results, next2, visited);
}
}
private boolean isPrime(int n) {
if(n <= 2) {
return true;
}
for(int i = 2; i*i <= n; i++) {
if(n%i == 0) {
return false;
}
}
return true;
}
// output factors should be sorted
private List<Integer> getAllFactors(int n) {
List<Integer> factors = new ArrayList<>();
int i = 2;
while (i <= n) {
if((n%i == 0) && isPrime(i)) {
factors.add(i);
n = n/i;
} else {
i++;
}
}
return factors;
}
}
// solution 2
<file_sep>/LeetCode/uberTag/186ReverseWord.java
// april 30, <NAME>
class Solution {
public void reverseWords(char[] s) {
// corner case
if(s == null || s.length <= 1) {
return;
}
System.out.println(s);
// reverse the whole string
reverse(s, 0, s.length-1);
// reverse each words according to space
int start = 0;
for(int i = 0; i < s.length; i++) {
if(s[i] == ' ') {
reverse(s, start, i-1);
start = i + 1;
}
if(i == (s.length - 1)) {
reverse(s, start, i);
System.out.println("reverse final");
}
}
return;
}
private void reverse(char[] s, int start, int end) {
if(start >= end) {
return;
}
while(start < end) {
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
return;
}
}
<file_sep>/LeetCode/uberTag/13RomantoInteger.java
// April 26
public class Solution {
public int romanToInt(String s) {
//corner case
if(s == null || s.length() == 0) {
return 0;
}
//build a hasp map from roman character to integer value
Map<Character, Integer> roman = new HashMap<>();
roman.put('M', 1000);
roman.put('D', 500);
roman.put('C', 100);
roman.put('L', 50);
roman.put('X', 10);
roman.put('V', 5);
roman.put('I', 1);
int result = roman.get(s.charAt(s.length()-1));
for(int i = s.length()-2; i>=0; i--) {
if (roman.get(s.charAt(i)) >= roman.get(s.charAt(i + 1))) {
result += roman.get(s.charAt(i));
} else {
result -= roman.get(s.charAt(i));
}
}
return result;
}
}<file_sep>/LeetCode/uberTag/36ValidateSoduco.java
// April 29, uber tage
public class Solution {
public boolean isValidSudoku(char[][] board) {
//corner case
if(board == null || board.length != 9 || board[0].length != 9) {
return false;
}
//validate rows
for(int row = 0; row < board.length; row++) {
boolean[] used = new boolean[10];
for(int col = 0; col < board[row].length; col++) {
if(board[row][col] == '.') {
continue;
}
int digit = board[row][col] - '0';
if(used[digit]) {
return false;
}
used[digit] = true;
}
}
//validate cols
for(int col = 0; col < board[0].length; col++) {
boolean[] visited = new boolean[10];
for(int row = 0; row < board.length; row++) {
if(board[row][col] == '.') {
continue;
}
int digit = board[row][col] - '0';
if(visited[digit]) {
return false;
}
visited[digit] = true;
}
}
//validate 3*3 matrices
int matrixSize = 3;
for(int i = 0; i*matrixSize < board.length; i++) {
for(int j = 0; j*matrixSize < board[0].length; j++) {
if (!isMatrixValid(i*matrixSize, j*matrixSize, matrixSize, board)) {
return false;
}
}
}
return true;
}
private boolean isMatrixValid(int row, int col, int matrixSize, char[][] board) {
boolean[] visited = new boolean[10];
for(int i = row; i < (row + matrixSize); i++) {
for(int j = col; j < (col + matrixSize); j++) {
if(board[i][j] == '.') continue;
int digit = board[i][j] - '0';
if(visited[digit]) {
return false;
}
visited[digit] = true;
}
}
return true;
}
}
<file_sep>/LintCode/BinaryTreePreorderTraversial.java
/**
* Binary Tree Preorder Traversial
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
// There algorithm for this problem: 1) recursion - traverse 2) recursion - Divide Conquer 3)iterate
// 1) recursion - traverse: easy but not suggested. because using an almost
// global variable(result as parameter was passed in each level of recursion)
// need a helper function
// 2) recursion - divide and conquer: much better. each level will return a ArrayList as result, and the final result is combined
// 3) use iteration method. will work on that latter.
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
// divide
ArrayList<Integer> left = preorderTraversal(root.left);
ArrayList<Integer> right = preorderTraversal(root.right);
// conquer
result.add(root.val);
result.addAll(left);
result.addAll(right);
// use traverse to find the pre order
// 2) use recursion - travese
// traverse(root, result);
// 3) use iteration
ArrayList<Integer> preorder = new ArrayList<Integer>();
Stack <TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode currRoot = stack.pop();
preorder.add(currRoot.val);
if (currRoot.right != null) {
stack.push(currRoot.right);
}
if (currRoot.left != null) {
stack.push(currRoot.left);
}
}
return preorder;
//return result;
}
// 1 recursion: traverse
// recursion - traverse method can work, but the paramether result
// is more like a global variabe, which is not that good in style.
private void traverse(TreeNode root, ArrayList<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
traverse(root.left, result);
traverse(root.right, result);
}
}
| 95869c96c62388daa7b455084d79995c2ee4289b | [
"Markdown",
"Java",
"Text"
] | 19 | Java | jacobNil/LintCode | 9d4bece0f102d1d101dfa4bf7e50f28b95dc83f7 | d5a892a249389ad955512a1efdc156c368924ba1 |
refs/heads/main | <repo_name>seanrahan/access<file_sep>/enum_groups.py
#!/usr/local/bin/python3
"""
Author: <NAME>
<EMAIL>
Workspace ONE Access script to enumerate all Groups assigned to apps
First iterates through all apps, determines what groups are assigned to each, and then gets the group details
"""
import requests
import json
from requests.exceptions import HTTPError
from requests_oauthlib import OAuth2
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
##--- START DATA TO CHANGE ---##
# define auth (uses bearer / access token)
tenant = 'shanrahan.vidmpreview.com'
clientId = 'python'
sharedSecret = ''
##--- END ---##
#API URL initilization
token_url = 'https://' + tenant + '/SAAS/auth/oauthtoken'
auth_url = 'https://' + tenant + '/SAAS/auth/oauth2/authorize'
login = 'https://'+ tenant + '/SAAS/API/1.0/REST/auth/system/login'
getCatalogItems = 'https://' + tenant + '/SAAS/jersey/manager/api/catalogitems/search' #POST API call to retrieve all catalog items
getCatalogDetail = 'https://' + tenant + '/SAAS/jersey/manager/api/entitlements/definitions/catalogitems/' #GET API call to retrieve catalog item detail
getGroupDetail = 'https://' + tenant + '/SAAS/jersey/manager/api/search/lookup?type=Group' #GeT API call to retrieve group detail
# define API call headers/body
headers_catItems = {
'Accept': 'application/vnd.vmware.horizon.manager.catalog.item.list+json',
'Content-Type': 'application/vnd.vmware.horizon.manager.catalog.search+json'
}
headers_catDetail = {
'Accept': 'application/vnd.vmware.horizon.manager.entitlements.v2.definition.list+json'
}
headers_groupDetail = {
'Accept': 'application/vnd.vmware.horizon.manager.search.items+json'
}
payload_getCatalogItems = {
"nameFilter": "",
"categories": []
}
#variables to capture group names, track item count
groupNames = []
itemNum = 0
### SETUP DONE ###
#initialize session to WS1 Access, get Access token
client = BackendApplicationClient(client_id=clientId)
session = OAuth2Session(client=client)
token = session.fetch_token(token_url=token_url,client_id=id,client_secret=sharedSecret)
# Logic
# 1. get all catalog items
# 2. for each catalog item, get all groups
# 3. for each group get names
try:
# STEP 1 - Get All Catalog Items
# enumerate apps in the OG and below
# main while loop to iterate through result sets
while(True):
catalogItemsReq = session.post(getCatalogItems, headers=headers_catItems, data=json.dumps(payload_getCatalogItems))
catalogItemsReq.raise_for_status()
# parse json response
catalogItems = catalogItemsReq.json()
# if first iteration, print total expected items
if itemNum == 0:
print("Total catalog items: ", catalogItems['totalSize'])
totalNum = catalogItems['totalSize']
#STEP 2 - Get Catalog items detail
# iterate through catalog items in request
for catItem in catalogItems['items']:
catUrl = getCatalogDetail + catItem['uuid']
#get detail for each catalog item
catalogDetailReq = session.get(catUrl, headers=headers_catDetail)
catalogDetailReq.raise_for_status()
# parse JSON response
catalogDetail = catalogDetailReq.json()
# increment catalog item count, provide feedback to user
itemNum += 1
print("Processing ", itemNum, '/',totalNum, ': ' , catItem['name'])
#STEP 3 - Get group detail from each catalog item
#iterate through groups in request
for group in catalogDetail['items']:
#get detail for each catalog item, skip anything that comes back not in a group
if (group['subjectType'] != 'GROUPS'):
continue
grpUrl = getGroupDetail + '&ids=' + group['subjectId']
groupDetailReq = session.get(grpUrl, headers=headers_groupDetail)
groupDetailReq.raise_for_status()
# parse JSON response
groupDetail = groupDetailReq.json()
#append to variable / array
groupNames.append(groupDetail['items'][0]['name'])
#if this is the end of this result-set, iterate to next result-set, otherwise break out of main while loop
if 'next' in catalogItems['_links']:
# print('end of current result-set, fetching next')
getCatalogItems = 'https://' + tenant + catalogItems['_links']['next']['href']
else:
break
except HTTPError as http_err:
print(f'HTTP Error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
print("Complete!")
# sort & dedupe array
result = []
for i in groupNames:
if i not in result:
result.append(i)
result.sort()
# print result
print('\n******************************************************\n***Unique Groups that are assigned to Catalog Items***\n******************************************************\n')
for item in result:
print(item)<file_sep>/enum_apps.py
#!/usr/local/bin/python3
"""
Author: <NAME>
<EMAIL>
Workspace ONE Access script to enumerate all apps in an Access Tenant
Requires remote access app defined with clientId and shared secret
install requests and requests_oauthlib using pip3 if you dont have them. For example:
> pip3 install requests
> pip3 install requests_oauthlib
"""
import requests
import json
from requests.exceptions import HTTPError
from requests_oauthlib import OAuth2
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
##--- START DATA TO CHANGE ---##
# define auth (uses bearer / access token)
tenant = 'shanrahan.vidmpreview.com'
clientId = 'python'
sharedSecret = ''
##--- END ---##
#API URL initilization
token_url = 'https://' + tenant + '/SAAS/auth/oauthtoken'
auth_url = 'https://' + tenant + '/SAAS/auth/oauth2/authorize'
login = 'https://'+ tenant + '/SAAS/API/1.0/REST/auth/system/login'
getCatalogItems = 'https://' + tenant + '/SAAS/jersey/manager/api/catalogitems/search' #POST API call to retrieve all catalog items
# define API call headers/body
headers_catItems = {
'Accept': 'application/vnd.vmware.horizon.manager.catalog.item.list+json',
'Content-Type': 'application/vnd.vmware.horizon.manager.catalog.search+json'
}
payload_getCatalogItems = {
"nameFilter": "",
"categories": []
}
#variable to init results
firstResult = True
### SETUP DONE ###
#initialize session to WS1 Access, get Access token
client = BackendApplicationClient(client_id=clientId)
session = OAuth2Session(client=client)
token = session.fetch_token(token_url=token_url,client_id=id,client_secret=sharedSecret)
# Logic
# 1. get all catalog items
# 2. print type / name for each
try:
# Get All Catalog Items
# main while loop to iterate through result set
while(True):
catalogItemsReq = session.post(getCatalogItems, headers=headers_catItems, data=json.dumps(payload_getCatalogItems))
catalogItemsReq.raise_for_status()
# parse json response
catalogItems = catalogItemsReq.json()
# if first iteration, print total expected items / header
if firstResult == True:
print("Total catalog items: ", catalogItems['totalSize'])
print("\nTYPE \t\t NAME")
print("-----------------------------")
totalNum = catalogItems['totalSize']
firstResult = False
for catItem in catalogItems['items']:
print(catItem['catalogItemType'], ": \t", catItem['name'])
#if this is the end of this result-set, iterate to next result-set, otherwise break out of main while loop
if 'next' in catalogItems['_links']:
# print('end of current result-set, fetching next')
getCatalogItems = 'https://' + tenant + catalogItems['_links']['next']['href']
else:
break
except HTTPError as http_err:
print(f'HTTP Error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
print("\nComplete!")
| 8f6ea835cd656840ca2fa47bcc1ce63af666d092 | [
"Python"
] | 2 | Python | seanrahan/access | 852fa8dcce392ed7a3054d207103d69f824fb3e8 | 769596dc666c9efe4b415446b259e677ba2d78dc |
refs/heads/master | <file_sep># Node-Web-Scraper
Designed to allow a user to enter a websites URL and search HTML tags to grap the text within them and have the option to download the scraping results or to view them in HTML(HTML view not ready yet).
<file_sep>const rp = require('request-promise');
const cheerio = require('cheerio');
const helmet = require('helmet');
const http = require('http');
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
var fs = require('fs');
server.timeout = 1000;
const port = process.env.PORT || 3000;
server.listen(port, () => console.log(`Server running on ${port}`));
const options = {
uri: null,
transform: function (body) {
return cheerio.load(body);
}
};
app.get('/', function async (req, res) {
res.sendFile(__dirname + '/index.html');
io.on('connection', function (socket) {
socket.on('searchRequest', function (data) {
options.uri = data.url;
rp(options)
.then(($) => {
// searchResult = $('body').find(data.keyword)
searchResult = $(`*:contains(${data.keyword})`)
fs.writeFile('response.doc', searchResult.text(), (err) => {
if (err) throw err
console.log('response written')
socket.emit('searchResult')
})
}).catch(err => socket.emit('err', err.message))
});
});
});
app.get('/download', (req, res) => {
console.log('req made for download')
let file = __dirname + '/response.doc'
res.download(file)
})
app.get('/webview', (req, res) => {
console.log('req made for html view')
let file = __dirname + '/response.doc'
try {
res.sendFile(file)
} catch (err) {
res.write('Error')
}
}) | 713dd07fb88718d30a32e0d2e53bbd4e098f65b4 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | CodingWithLaurence/Node-Web-Scraper | b3398c9895d4726e652e12fd02da7484405817bc | b4d3e1bb30114c88c2860d48f5d3ad7aa8a5b75b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.