branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>EugeneItechart/privatePodTesting<file_sep>/PRIVATEPOD/Classes/App/Model/Image.swift
//
// Image.swift
// Tokenization
//
// Created by <NAME> on 4/10/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import UIKit
enum Image {
static var amex: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var camera: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var diners: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var discover: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var genericCreditCard: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var jcb: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var masterCard: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var creditCardPlaceholder: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
static var visa: UIImage {
return UIImage.init(named: "ic_card_generic")!
}
}
<file_sep>/README.md
# privatePodTesting
Test a private pod
<file_sep>/PRIVATEPOD/Classes/App/View/WalletTextField.swift
//
// WalletTextField.swift
// CustomerApp
//
// Created by <NAME> on 28/09/16.
// Copyright © 2016 RockSpoon. All rights reserved.
//
import UIKit
class WalletTextField: UITextField {
var currentKeyboardAppearance: UIKeyboardAppearance = .default
var autocorrection: UITextAutocorrectionType = .no
// TODO: swift_4_migration
var textAttributes: [NSAttributedString.Key: Any]?
// TODO: swift_4_migration
func configureInputView(newInputView: UIView) {
}
//-----------------------------------------------------------------------------
// MARK: - TextInput
//-----------------------------------------------------------------------------
var view: UIView { return self }
var currentText: String? {
get { return text }
set { self.text = newValue }
}
weak var textInputDelegate: UITextViewDelegate?
var currentSelectedTextRange: UITextRange?
var currentBeginningOfDocument: UITextPosition?
var contentInset: UIEdgeInsets = .zero
func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) {
}
func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? {
return nil
}
func changeClearButtonMode(with newClearButtonMode: UITextField.ViewMode) {
}
//-----------------------------------------------------------------------------
// MARK: - Private properties
//-----------------------------------------------------------------------------
fileprivate let defaultPadding: CGFloat = -16
fileprivate var rightViewPadding: CGFloat
fileprivate var disclosureButtonAction: (() -> ())?
override init(frame: CGRect) {
self.rightViewPadding = defaultPadding
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
self.rightViewPadding = defaultPadding
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
delegate = self
addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
return super.rightViewRect(forBounds: bounds).offsetBy(dx: rightViewPadding, dy: 0)
}
func add(disclosureButton button: UIButton, action: @escaping (() -> ())) {
let selector = #selector(disclosureButtonPressed)
if disclosureButtonAction != nil, let previousButton = rightView as? UIButton {
previousButton.removeTarget(self, action: selector, for: .touchUpInside)
}
disclosureButtonAction = action
button.addTarget(self, action: selector, for: .touchUpInside)
rightView = button
}
@objc fileprivate func disclosureButtonPressed() {
disclosureButtonAction?()
}
@objc fileprivate func textFieldDidChange() {
}
}
extension WalletTextField: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
//textInputDelegate?.textInputDidBeginEditing(textInput: self)
}
func textFieldDidEndEditing(_ textField: UITextField) {
//textInputDelegate?.textInputDidEndEditing(textInput: self)
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
}
<file_sep>/PRIVATEPOD/Classes/App/View/Button.swift
//
// Button.swift
// CustomerApp
//
// Created by mac-246 on 19.04.16.
// Copyright © 2016 RockSpoon. All rights reserved.
//
import UIKit
private let highlightedAlpha: CGFloat = 0.499
private let overlayAlpha: CGFloat = 0.5
private func isCGFloatsEqual(first: CGFloat, second: CGFloat) -> Bool {
if abs(first - second) < 0.0001 {
return true
} else {
return false
}
}
class Button: UIButton {
//-----------------------------------------------------------------------------
// MARK: - @IBOutlet
//-----------------------------------------------------------------------------
@IBOutlet var dependentViews: [UIView]?
//-----------------------------------------------------------------------------
// MARK: - Public properties
//-----------------------------------------------------------------------------
override var isHighlighted: Bool {
didSet {
configureHighlight(isHighlighted: isHighlighted)
configureHighlightForDependentViews(isHighlighted: isHighlighted)
}
}
@IBInspectable var hasHighlightedOverlay: Bool = false
@IBInspectable var overlayColor: UIColor? {
get {
return overlayView.backgroundColor
}
set {
overlayView.backgroundColor = newValue
}
}
//-----------------------------------------------------------------------------
// MARK: - Private properties
//-----------------------------------------------------------------------------
fileprivate var animatingViewsOriginalAlphas = [UIView: CGFloat]()
fileprivate let activityIndicator = UIActivityIndicatorView(style: .gray)
fileprivate var buttonImage: UIImage?
fileprivate let overlayView = UIView()
//-----------------------------------------------------------------------------
// MARK: - Initialization
//-----------------------------------------------------------------------------
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override func awakeFromNib() {
activityIndicator.color = layer.borderColor.map { UIColor(cgColor: $0) }
}
//-----------------------------------------------------------------------------
// MARK: - Public methods
//-----------------------------------------------------------------------------
func startAnimating() {
isUserInteractionEnabled = false
isHighlighted = false
if let dependentViews = dependentViews {
animatingViewsOriginalAlphas = [:]
for view in dependentViews {
animatingViewsOriginalAlphas[view] = view.alpha
view.alpha = 0
}
}
buttonImage = imageView?.image
setImage(nil, for: UIControl.State())
titleLabel?.alpha = 0
activityIndicator.startAnimating()
}
func stopAnimating() {
for (view, alpha) in animatingViewsOriginalAlphas {
view.alpha = alpha
}
animatingViewsOriginalAlphas = [:]
if let buttonImage = buttonImage {
setImage(buttonImage, for: UIControl.State())
self.buttonImage = nil
}
titleLabel?.alpha = 1
activityIndicator.stopAnimating()
isUserInteractionEnabled = true
}
func setHighlight(_ highlight: Bool, ignoreDependentViews: Bool) {
configureHighlight(isHighlighted: highlight)
if !ignoreDependentViews {
configureHighlightForDependentViews(isHighlighted: highlight)
}
}
//-----------------------------------------------------------------------------
// MARK: - Private methods
//-----------------------------------------------------------------------------
fileprivate func configure() {
adjustsImageWhenHighlighted = false
addSubview(overlayView)
overlayView.frame = bounds
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.alpha = 0
addSubview(activityIndicator)
activityIndicator.isHidden = true
activityIndicator.hidesWhenStopped = true
activityIndicator.center = CGPoint(x: bounds.midX, y: bounds.midY)
let msk: UIView.AutoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleTopMargin, .flexibleRightMargin]
activityIndicator.autoresizingMask = msk
}
fileprivate func configureHighlight(isHighlighted: Bool) {
if hasHighlightedOverlay {
let newAlpha = isHighlighted ? overlayAlpha : 0
overlayView.alpha = newAlpha
} else {
let newAlpha = isHighlighted ? highlightedAlpha : 1
let oldAlpha = isHighlighted ? 1 : highlightedAlpha
if isCGFloatsEqual(first: alpha, second: oldAlpha) {
alpha = newAlpha
}
}
}
fileprivate func configureHighlightForDependentViews(isHighlighted: Bool) {
guard let dependentViews = dependentViews else { return }
let newAlpha = isHighlighted ? highlightedAlpha : 1
let oldAlpha = isHighlighted ? 1 : highlightedAlpha
for view in dependentViews {
if let button = view as? Button {
button.setHighlight(isHighlighted, ignoreDependentViews: true)
} else {
if isCGFloatsEqual(first: view.alpha, second: oldAlpha) {
view.alpha = newAlpha
}
}
}
}
}
<file_sep>/PRIVATEPOD/Classes/App/View/Color/UIColor+Hex.swift
//
// UIColor+Hex.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: Int = 0xFF) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: CGFloat(alpha) / 255.0
)
}
// let's suppose alpha is the first component (ARGB)
convenience init(argb: Int) {
self.init(
red: (argb >> 16) & 0xFF,
green: (argb >> 8) & 0xFF,
blue: argb & 0xFF,
alpha: (argb >> 24) & 0xFF
)
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/CreditCardType.swift
//
// CreditCardType.swift
// CustomerApp
//
// Created by <NAME> on 01/02/2019.
// Copyright © 2019 RockSpoon. All rights reserved.
//
public enum CardType: String, Codable, CaseIterable {
case amex = "amex"
case diners = "diners"
case discover = "discover"
case jcb = "jcb"
case masterCard = "masterCard"
case rockspoonTestCard = "rockspoonTestCard"
case visa = "visa"
}
extension CardType {
var icon: UIImage {
switch self {
case .amex: return Image.amex
case .diners: return Image.diners
case .discover: return Image.discover
case .jcb: return Image.jcb
case .masterCard: return Image.masterCard
case .rockspoonTestCard: return Image.creditCardPlaceholder
case .visa: return Image.visa
}
}
}
<file_sep>/PRIVATEPOD/Classes/App/InputCreditCard/View/EditCreditCardViewController.swift
//
// EditCreditCardViewController.swift
// Tokenization
//
// Created by <NAME> on 4/3/19.
//
import UIKit
final class EditCreditCardViewController: UIViewController {
@IBOutlet private var cardIconImageView: UIImageView!
@IBOutlet private var cardNumberTextInput: UITextField!
@IBOutlet private var goodThruTextInput: UITextField!
@IBOutlet private var cvcTextInput: UITextField!
@IBOutlet private var cardAliasTextInput: UITextField!
@IBOutlet private var isDefaultSwitch: UISwitch!
@IBOutlet private var scanButton: UIButton!
@IBOutlet private var saveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let cardIcon = Image.genericCreditCard
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/Token.swift
//
// Token.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
public struct Token {
public let id: String
public let provider: TokenProviderID
}
<file_sep>/PRIVATEPOD/Classes/App/Model/TokenProviderID.swift
//
// TokenProviderID.swift
// Tokenization
//
// Created by <NAME> on 2/15/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
public enum TokenProviderID: String {
case ingenico = "INGENICO"
}
<file_sep>/PRIVATEPOD/Classes/App/Model/TokenizationError.swift
//
// TokenizationError.swift
// Tokenization
//
// Created by <NAME> on 2/7/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
public enum TokenizationError: Error {
case tokenizationFailed(message: String)
case invalidParameters
case deallocated
var localizedDescription: String {
switch self {
case .tokenizationFailed(message: let message):
return "Tokenization has failed: \(message)"
case .invalidParameters:
return "Credit card information is incorrect"
case .deallocated:
return "The token provider was deallocated"
}
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/Bundle+Resources.swift
//
// Bundle+Resources.swift
// Tokenization
//
// Created by <NAME> on 2/15/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
fileprivate final class Resources {}
extension Bundle {
static var resources: Bundle {
let path = Bundle(for: Resources.self).path(forResource: "Resources", ofType: "bundle")!
return Bundle(path: path) ?? Bundle.main
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/TokenizedCreditCard.swift
//
// TokenizedCreditCard.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
public struct TokenizedCreditCard {
public let token: Token
public let type: CardType
public let alias: String
public let isDefault: Bool
public let lastFourDigits: String
public let expirationDate: String
}
<file_sep>/PRIVATEPOD/Classes/App/Model/CreditCard.swift
//
// CreditCard.swift
// Tokenization
//
// Created by <NAME> on 4/4/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
struct CreditCard {
let number: String
let expiration: Date
let alias: String
let type: CardType
}
<file_sep>/PRIVATEPOD/Classes/App/Controller/TokenizationCoordinator.swift
//
// TokenizationCoordinator.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
public final class TokenizationCoordinator {
public weak var navigationController: UINavigationController?
let credentials: [String]
public init(navigationController: UINavigationController,
credentials: [String]) {
self.navigationController = navigationController
self.credentials = credentials
}
public func start() {
let bundle = Bundle(for: TokenizationCoordinator.self)
let storyboard = UIStoryboard(name: "RegisterCreditCard", bundle: bundle)
guard let editViewController = storyboard.instantiateViewController(withIdentifier: "EditCreditCardViewController")
as? EditCreditCardViewController
else { return }
navigationController?.pushViewController(editViewController, animated: true)
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/Trie/TrieNode.swift
//
// TrieNode.swift
// Tokenization
//
// Created by <NAME> on 4/4/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
public class TrieNode<Key: Hashable> {
public var key: Key?
public weak var parent: TrieNode?
public var children: [Key: TrieNode] = [:]
public var isTerminating = false
public init(key: Key?, parent: TrieNode?) {
self.key = key
self.parent = parent
}
}
<file_sep>/PRIVATEPOD.podspec
# frozen_string_literal: true
#
# Be sure to run `pod spec lint Tokenization.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = 'PRIVATEPOD'
s.version = '0.0.2'
s.summary = 'WCOOK DEscpritpsdofgjsgj s kg;sdlfgj lksdfjg sjg dfs;lk jglk'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
Oipoipo pi pi pi poi poppy pi popo po cpiopi po top imo op iopiopi op opipoi p
DESC
s.homepage = 'https://github.com/EugeneItechart/privatePodTesting'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'EugeneItechArt' => '<EMAIL>' }
s.source = { :git => 'https://github.com/EugeneItechArt/privatePodTesting.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.swift_version = '5.0'
#s.ios.deployment_target = '11.0'
s.platform = :ios, '11.0'
s.source_files = 'PRIVATEPOD/Classes/**/*'
s.resources = 'PRIVATEPOD/**/*.{png,jpeg,jpg,storyboard,xib,xcassets}'
#s.resource_bundle = { 'Resources' => ['PRIVATEPOD/Classes/Resources'] }
#s.resource_bundles = {
# 'PRIVATEPOD' => ['PRIVATEPOD/Classes/Resources/Images']
#}
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit'
# s.dependency 'AFNetworking', '~> 2.3'
s.static_framework = true
s.requires_arc = true
end
<file_sep>/PRIVATEPOD/Classes/App/Model/LocalizableStrings.swift
//
// LocalizableStrings.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import Foundation
func Localize(_ key: String) -> String {
return NSLocalizedString(key, tableName: nil, bundle: .resources, value: "", comment: "")
}
<file_sep>/PRIVATEPOD/Classes/App/View/UITextField+CursorPosition.swift
//
// UITextField+Utils.swift
// CustomerApp
//
// Created by <NAME> on 29/09/16.
// Copyright © 2016 RockSpoon. All rights reserved.
//
import UIKit
extension UITextField {
var cursorPosition: Int? {
get {
if let selectedRange = self.selectedTextRange {
return self.offset(from: self.beginningOfDocument, to: selectedRange.start)
}
return nil
}
set {
if let newValue = newValue,
let newPosition = self.position(
from: self.beginningOfDocument,
in: UITextLayoutDirection.right,
offset: newValue) {
self.selectedTextRange = self.textRange(from: newPosition, to: newPosition)
}
}
}
}
<file_sep>/PRIVATEPOD/Classes/App/Model/TokenProviderCredential.swift
//
// TokenProviderCredential.swift
// Tokenization
//
// Created by <NAME> on 2/21/19.
//
import Foundation
public protocol TokenProviderCredential {
var username: String { get }
var password: String { get }
}
<file_sep>/PRIVATEPOD/Classes/App/View/Color/UIColor+Constants.swift
//
// UIColor+Constants.swift
// Tokenization
//
// Created by <NAME> on 2/11/19.
// Copyright © 2019 Rockspoon Inc. All rights reserved.
//
import UIKit
extension UIColor {
static var textDark: UIColor {
return UIColor(argb: 0xFF_474747)
}
static var theme: UIColor {
return UIColor(argb: 0xFF_FB1D09)
}
static var gray71: UIColor {
return UIColor(argb: 0xFF_717171)
}
static var buttonBlue: UIColor {
return UIColor(argb: 0xFF_00ADEF)
}
static var buttonGray: UIColor {
return UIColor(argb: 0xFF_DCE2E5)
}
}
|
5ed7ae28e07e2143d4eb10a0ab9c9cef9ab266b3
|
[
"Swift",
"Ruby",
"Markdown"
] | 20
|
Swift
|
EugeneItechart/privatePodTesting
|
f5d025b47a1654e126b4618d406d999389a40ef5
|
0bdb903a2551e1c7f516d17cf175a748d598b073
|
refs/heads/master
|
<repo_name>galetahub/track_tweets_client<file_sep>/lib/track_tweets/client.rb
require "httparty"
require "ostruct"
require "json"
module TrackTweets
class Client < OpenStruct
include ::HTTParty
base_uri File.join("http://tracktweets.aimbulance.com", "api", TrackTweets.api_version)
basic_auth TrackTweets.username, TrackTweets.password
format TrackTweets.format
class << self
protected
def resource(response)
if response && [200, 201].include?(response.code)
body = post_parse(response.parsed_response)
new(body)
else
nil
end
end
def post_parse(body)
return body unless body.is_a?(String)
case format
when :json then JSON.parse(body)
when :xml then Nokogiri::XML.parse(body)
end
end
end
end
end
<file_sep>/README.rdoc
= Track tweets API
== Install
gem 'track_tweets'
== Configuration
TrackTweets.setup do |config|
config.username = 'demo'
config.password = '<PASSWORD>'
config.format = :json
config.api_version = 'v1'
config.group_id = 'your group id'
end
== Usage
group = TrackTweets::Group.create(
:name => 'McDonals Euro Kids',
:timeout => 2 * 60 * 60, # 2 hours
:delay => 50 * 60) # 50 minutes
TrackTweets::Group.destroy(group.id)
Copyright (c) 2011 Aimbulance, released under the MIT license
<file_sep>/lib/track_tweets/group.rb
module TrackTweets
class Group < Client
class << self
def create(attributtes)
resource post("/groups.#{format}", :body => { :group => attributtes })
end
def all(options = {})
resource get("/groups.#{format}", :query => options)
end
def find(id, options = {})
resource get("/groups/#{id}.#{format}", :query => options)
end
def destroy(id)
resource delete("/groups/#{id}.#{format}")
end
def clear_track_tweets(id)
resource delete("/groups/#{id}/track_items/all.#{format}")
end
end
end
end
<file_sep>/lib/track_tweets.rb
module TrackTweets
autoload :Client, 'track_tweets/client'
autoload :Group, 'track_tweets/group'
autoload :TrackItem, 'track_tweets/track_item'
mattr_accessor :username
@@username = 'demo'
mattr_accessor :password
@@password = '<PASSWORD>'
mattr_accessor :format
@@format = :json
mattr_accessor :api_version
@@api_version = 'v1'
mattr_accessor :group_id
@@group_id = nil
def self.setup
yield self
end
end
require 'track_tweets/version'
<file_sep>/lib/track_tweets/track_item.rb
module TrackTweets
class TrackItem < Client
class << self
def create(group_id, attributtes)
resource post("/groups/#{group_id}/track_items.#{format}", :body => { :track_item => attributtes })
end
def all(group_id, options = {})
resource get("/groups/#{group_id}/track_items.#{format}", :query => options)
end
def find(id, options = {})
resource get("/track_items/#{id}.#{format}", :query => options)
end
def destroy(id)
resource delete("/track_items/#{id}.#{format}")
end
def tweets(id, options = {})
resource get("/track_items/#{id}/tweets.#{format}", :query => options)
end
end
end
end
|
f8d4e53b43fd1015edf734dda26f80f8acdda98b
|
[
"RDoc",
"Ruby"
] | 5
|
Ruby
|
galetahub/track_tweets_client
|
977d8670d74e250c6a243fae035f1abab9cce4fc
|
104ed76c86e358e04577e757f7d557e9b23c43bc
|
refs/heads/master
|
<repo_name>kimoi/SendToSeedbox<file_sep>/config.example.php
<?php
return [
'access_key' => 'CHANGE_ME',
'target_path' => '/path/to/torrents/watch',
];
<file_sep>/sendtoseedbox.php
<?php
$config = require('config.php');
header('Access-Control-Allow-Origin: *');
header('Content-Type application/json');
$ret = false;
if($config['access_key'] === 'CHANGE_ME') {
$ret = false;
}
elseif(!isset($_REQUEST['key']) || sha1($_REQUEST['key']) !== sha1($config['access_key'])) {
$ret = false;
}
else {
if(isset($_REQUEST['url'])) {
$ret = copy($_REQUEST['url'], $config['target_path'].'/'.time().'.torrent');
}
}
echo json_encode($ret);
|
380a54070dcc315a3705f07009fc9b6fc3678c32
|
[
"PHP"
] | 2
|
PHP
|
kimoi/SendToSeedbox
|
a5acef1b15d8658e7f29a99c7d5936a0338d4d1e
|
aa0bcfe339967367ef6e2132549c2e614fd6d0e3
|
refs/heads/master
|
<file_sep><html>
<head>
<link rel="stylesheet" href="headbar.css" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="headbar.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "bootstrap1.css">
<link rel="stylesheet" href="main.css">
<style>
.formWrap{
margin:0 auto;
position:relative;
background-color:#999;
padding:2em;
width:25%;
margin-top:3em;
}
.formfield{
margin:0 auto;
width:50%;
display:inline-block;
margin-top: 1em;
margin-bottom: 1em;
}
body{
margin:0;
}
</style>
</head>
<body>
<?php
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// $pass = mysqli_real_escape_string($con, $_POST['passcode']);
$pass = $_GET['pass'];
// if($pass!="<PASSWORD>ass"){
if($pass!="<PASSWORD>"){
echo "<script type='text/javascript'>window.location.href = 'index.php'</script>";
}
?>
<div class = "formWrap">
<form action="createEvent.php" method="post" enctype="multipart/form-data">
<div class ="formfield">Event Name (no spaces plzzz):<br> <input type="text" name="name"></div>
<div class ="formfield">Date: (YYYY-MM-DD)<br> <input type="text" name="date"></div>
<div class ="formfield">Spots: <br> <input type="text" name="spots"></div><br>
<div class= "formfield">Credits: <br><input type= "text" name = "credits"></div><br>
<label for="file">Descrtiption:</label><br>
<input type="file" name="file" id="file"><br>
<div class ="formfield"><input type="submit"></div>
</form>
<!-- <form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>-->
</div>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" type="text/css" href="../events/headbar.css">
<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="../events/tableStyle.css">
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
.headbar{
margin-top:-4em;
}
.Table{
width:70%;
}
body{
}
</style>
</head>
<body>
<div class="nav" >
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = mysqli_real_escape_string($con, $_POST['id']);
$member = mysqli_query($con,"SELECT * FROM members WHERE ID=$id");
while($row = mysqli_fetch_array($member)) {
$name = $row['First']." ".$row['Last'];
$grade = $row['Grade'];
$pos = $row['Position'];
if($pos.length<1)$pos="Member";
$email = $row['Email'];
$khk=$row['KHK'];
$gp =$row['Group_Project'];
$hours =$row['Hours'];
$meetings =$row['Meetings'];
}
echo "<h1>".$name."</h1><br>";
echo "<h2>Statistics</h2>";
echo "<div class='Table'>
<table >
<tr><td>Name</td>
<td>Grade</td>
<td>Position</td>
<td>ID</td>
<td>Email</td>
<td>Hours</td>
<td>Group Project</td>
<td>KHK</td>
<td>Total</td>
<td>Meetings</td>
</tr>";
echo "<tr>
<td >
".$name."
</td>
<td>
".$grade."
</td>
<td>
".$pos."
</td>
<td>
".$id."
</td>
<td>
".$email."
</td>
<td>
".$hours+$khk." hours of 20 hours
</td>
<td>
".$gp." of 2 projects
</td>
<td>
".$khk." hours of 5 hours
</td>
<td>
".$meetings." meetings attended
</td>
</tr>";
mysqli_close($con);
//ending tag ?>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" type="text/css" href="tableStyle.css">
<!--<link rel="stylesheet" type="text/css" href="eventStyle.css">-->
<link rel="stylesheet" type="text/css" href="headbar.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
.headbar{
margin-top:-4em;
}
h1{
color: rgb(0,32,96);
text-align:center;
}
a{
color:rgb(0,32,96);
}
.affix{
top: 0;
width: 100%;
}
body{
background: -webkit-linear-gradient(#002060, #56A0D3);
background: -o-linear-gradient(#002060, #56A0D3);
background: -moz-linear-gradient(#002060,#56A0D3);
background: linear-gradient(#002060,#56A0D3);
background-repeat:no-repeat;
height:100%;
}
</style>
</head>
<body>
<div class="nav"data-spy="affix">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<h1>Events</h1>
<?php //starting tag
//error_reporting(0);
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function runMyFunction($input) {
echo $input;
}
//runMyFunction($_GET['eventName']);
$orderthing = 'Date';
$result = mysqli_query($con,"SELECT * FROM events ORDER BY $orderthing ASC");
echo "<div class='Table'>
<table >
<tr><td>Name</td>
<td >Date</td>
<td>Signed Up</td>
<td>Max Spots</td>
</tr>";
while($row = mysqli_fetch_array($result)) {
/* echo "<tr>";
echo "<td><a href ='http://www.wvnhs.com/events/eventInfo.php?eventName=".$row['Name']."'>" . $row['Name'] . "</a></td>";
echo "<td>" . $row['Date'] . "</td>";
echo "<td>" . $row['Spots_Taken'] . "</td>";
echo "<td>" . $row['Total_Spots'] . "</td>";
echo "</tr>";*/
$date = $row['Date'];
$date2 = date_create($date);
$eventName = $row['Name'];
if($eventName != 'KHK')$newName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $eventName);
else $newName =$eventName;
echo "<tr>
<td >
<a href ='eventInfo.php?eventName=".$row['Name']."'>" . str_replace("_", " ", $newName) . "</a>
</td>
<td>
" . date_format($date2, "M d") . "
</td>
<td>
" . $row['Spots_Taken'] . "
</td>
<td>
" . $row['Total_Spots'] . "
</td>
</tr>";
}
echo "</table>
</div>";
mysqli_close($con);
//ending tag ?>
</body>
</html>
<file_sep>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
</head>
<style>
.headbar{
margin-top:0em;
}
.announcmentWrapper{
margin-top:5em;
}
h2{
text-align: left;
}
body{
background: -webkit-linear-gradient(#93C2E3, #2E7AAF);
background: -o-linear-gradient(#93C2E3, #2E7AAF);
background: -moz-linear-gradient(#93C2E3,#2E7AAF);
background: linear-gradient(#93C2E3,#2E7AAF);
background-repeat:no-repeat;
height:100%;
}
</style>
<body>
<div class="nav" >
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Events ORDER BY Date ASC, Name ASC");
echo "<div class='announcmentWrapper' id='announcment'>
<div class='announcment'>
<h1>Grand Master Bardi Page</h1>";
while($row = mysqli_fetch_array($result)) {
$date = $row['Date'];
$date2 = date_create($date);
if(substr($row['Name'],0,7)==='Library'){
echo "<hr class ='experiencehr'/>";
echo "<h2>".
date_format($date2, "l, F d")
." - ".
preg_replace('/(?<!\ )[0-9]/', ' $0',(substr($row['Name'],15,strlen($row['Name'])-1)))
." </h2>";
$eventName = $row['Name'];
$result2 = mysqli_query($con, "SELECT * FROM $eventName");
echo "<ol>";
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['FirstName']." ".$row2['LastName']."</li><br>";
}
echo "</ol>";
}
else{
// echo (substr($row['Name'],0,6));
}
}
echo "</div></div>";
mysqli_close($con);
?>
</body>
</html>
<file_sep>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">
<link rel="stylesheet" type="text/css" href="../events/headbar.css">-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
</head>
<style>
.headbar{
margin-top:-4em;
}
.announcmentWrapper{
margin-top:5em;
}
h2{
text-align: left;
}
.remove{
float:right;
color:red;
font-weight: bolder;
}
</style>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<h1>Removing From Event</h1><br><br>";
$id = $_GET['id'];
$eventName = $_GET['event'];
$event = mysqli_query($con,"SELECT * FROM Events WHERE Name='$eventName'");
$member = mysqli_query($con,"SELECT * FROM members WHERE ID='$id'");
$membersInEvent = mysqli_query($con,"SELECT * FROM $eventName WHERE ID='$id'");
while($member = mysqli_fetch_array($membersInEvent)) {
echo "Removing ".$member['FirstName']." ".$member['LastName']." from ".$eventName;
}
$del = mysqli_query($con,"DELETE FROM $eventName WHERE ID='$id'"); //Delete the member from the event
while($row = mysqli_fetch_array($event)) {
$oldSpotsTaken = $row['Spots_Taken'];
$newSpotsTaken = $oldSpotsTaken-1;
mysqli_query($con, "UPDATE Events
SET Spots_Taken=$newSpotsTaken
WHERE Name = '$eventName'");
}
//echo "<script type='text/javascript'>window.location.href = ../admin/adminDirectory.php?pass=<PASSWORD>'</script>";
mysqli_close($con);
?>
<script type='text/javascript'>window.location.href = 'eventMemberList.php?pass=<PASSWORD>'</script>
</body>
</html>
<file_sep>
<html>
<head>
<link rel="stylesheet" type="text/css" href="eventInfoStyle.css">
<link rel="stylesheet" type="text/css" href="headbar.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
</head>
<style>
.headbar{
margin-top:-4em;
}
</style>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$event = $_GET['eventName'];
$result = mysqli_query($con,"SELECT * FROM Events WHERE Name='$event'");
while($row = mysqli_fetch_array($result)) {
$eventName=$row['Name'];
$date=$row['Date'];
$spotsTaken=$row['Spots_Taken'];
$totalSpots=$row['Total_Spots'];
$credits_worth= $row['Credits_Worth'];
}
$result = mysqli_query($con,"SELECT * FROM $eventName");
$newName = preg_replace('/(?<!\ )[A-Z]/', ' $0', $eventName);
echo "<h1>".str_replace("_", " ", $newName)."</h1>";
$date2 = date_create($date);
echo "<h2>".date_format($date2, "l, F d")."</h2>";
$file = file_get_contents('uploads/'.$eventName.'.txt', true);
echo "<div class='announcmentWrapper' id='announcment'>
<div class='announcment'>
<h1>Event Details</h1>
<hr class = 'experiencehr'>
<p>".$file."</p>
<hr class = 'experiencehr'>
<p>Spots Taken: ".$spotsTaken."<br>Total Spots: ".$totalSpots." <br>Gives ".$credits_worth. " credits
</div>
</div>
<div class='announcmentWrapper' id='announcment'>
<div class='announcment'>
<h1>Members Attending</h1>
<hr class = 'experiencehr'>
";//<ol>";
$result2 = mysqli_query($con,"SELECT * FROM $event");
// while($row = mysqli_fetch_array($result2)) {
//echo "<p><li>".$row['FirstName']." ".$row['LastName']."</li></p><br>";
echo"<p> To see if you have signed up for this event, please check your <a href ='../myStats'>My Stats</a> page!</p>";
// }
echo
// </ol>
"</div>
</div>";
$canSign = true;
if($spotsTaken>=$totalSpots) $canSign=false;
echo "<div class='announcmentWrapper' id='announcment'>
<div class='announcment'>
<form action='signUp.php?eventName=".$eventName."' method='post'>
<p>User Identification:</p> <input type='text' name='id'><br>
<input type='submit' value='Sign Up!'";
if(!$canSign)echo "disabled";
echo "/>
</form>
<div class = 'sideImage'>
<img src='wvlogo.png'>
</div>
<p>Signing up means that there are less spots for other members.<br> PLEASE don't sign up unless you are 100% sure you can attend.<br>In the event of a last minute emergency, please contact an NHS Board member.</p>
</div></div>";
mysqli_close($con);
?>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../../bootstrap1.css">
<link rel="stylesheet" href="../../main.css">
<script>
$(document).ready(function () {
(function ($) {
$('#filter').keyup(function () {
var rex = new RegExp($(this).val(), 'i');
$('.searchable tr').hide();
$('.searchable tr').filter(function () {
return rex.test($(this).text());
}).show();
})
}(jQuery));
});
</script>
<style>
</style>
</head>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills" >
<li><a href="../../index.html">Home</a></li>
<li><a href="../../forms/index.php">Forms</a></li>
<li><a href="../../myStats/index.php">My Stats</a></li>
<li><a href="../../members/index.php">Members</a></li>
<li><a href="../../events/index.php">Events</a></li>
<li><a href="../../admin/index.php">Admin Login</a></li>
<li><a href="../../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pass = $_GET['pass'];
if($pass!="<PASSWORD>8"){
echo "<script type='text/javascript'>window.location.href = '../admin'</script>";
}
$result = mysqli_query($con,"SELECT * FROM members ORDER BY Position DESC, Last, First ASC");
echo '<div class="input-group"> <span class="input-group-addon">Search</span>
<input id="filter" type="text" class="form-control" placeholder="Type here...">
</div>';
/* class="table table-striped" -----------------for actual table, replace with this----nothing-width="100%" border="0" cellspacing="0" cellpadding="0"*/
echo '<table class="table table-striped">
<thead>
<tr>
<th>Last</th>
<th>First</th>
<th>Grade</th>
<th>Position</th>
<th>User ID</th>
<th>Email</th>
<th>Credits</th>
</tr>
</thead>';
while($row = mysqli_fetch_array($result)) {
echo '<tbody class="searchable">
<tr>
<td >
' . $row['Last'] . '
<form action="changeLast.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit">
</form>
</td>
<td>
' . $row["First"] . '
<form action="changeFirst.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit">
</form>
</td>
<td>
' . $row["Grade"] . '
<form action="changeGrade.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit">
</form>
</td>
<td>
' . $row["Position"] . '
<form action="changePosition.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit">
</form>
</td>
<td>
'.$row["ID"].'
<form action="changeID.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit">
</form>
</td>
<td>
'.$row["Email"].'
<form action="changeEmail.php?id='.$row["ID"].'" method="post">
<br> <input type="text: name="newValue">
<input type="submit">
</form>
</td>
<td>
'.$row["Credits"].' of 100 credits
<form action="changeCredits.php?id='.$row["ID"].'" method="post">
<br> <input type="text" name="newValue">
<input type="submit" name="add" value="add">
<input type="submit" name="change" value="change">
</form>
</td>
</tr>";
</tbody>';
}
echo '</table>';
mysqli_close($con);
//ending tag ?>
</html><file_sep>$(document).ready( function(){
$( "#signup" ).click(function() {
window.location.href = "http://wvnhs.com/members/signup.php";
});
$( "#admin" ).click(function() {
window.location.href = "http://wvnhs.com/admin";
});
$( "#events" ).click(function() {
window.location.href = "http://wvnhs.com/events";
});
$( "#members" ).click(function() {
window.location.href = "http://wvnhs.com/members";
});
$( "#home" ).click(function() {
window.location.href = "http://wvnhs.com";
});
$( "#mystats" ).click(function() {
window.location.href = "http://wvnhs.com/myStats";
});
});
<file_sep><html>
<body>
<?php
session_start();
echo implode('<br>', $_SESSION['events']['user']);
//echo $_SESSION['event'];
?>
</body>
</html><file_sep><html>
<head>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<link rel="stylesheet" href="headbar.css" type="text/css">
<link rel="stylesheet" href="../events/eventInfoStyle.css" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="headbar.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style>
body{
margin:0;
background: -webkit-linear-gradient(white,#93C2E3, #2E7AAF);
background: -o-linear-gradient(white,#93C2E3, #2E7AAF);
background: -moz-linear-gradient(white,#93C2E3,#2E7AAF);
background: linear-gradient(white,#93C2E3,#2E7AAF);
background-repeat:no-repeat;
height:100%;
}
.headbar{
margin-top:-4em;
}
.nav a{
color: #5a5a5a;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase;
}
.adminList a{
font-size: xx-large;
color:#002060;
text-shadow:2px 2px white;
}
.adminList li{
color:white;
line-height: 2em;
text-align: left;
font-family: Helvetica;
}
h1{
color:#002060;
}
</style>
</head>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<h1>Welcome, Admin</h1>
<?php
error_reporting(0);
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$getpass = $_GET['getpass'];
$passcodes = array("<PASSWORD>", "<PASSWORD>$$");
$passlength = count($passcodes);
$isAdmin=false;
$pass = mysqli_real_escape_string($con, $_POST['passcode']);
for($x=0;$x<$passlength;$x++){
if($pass==$passcodes[$x] || $getpass==<PASSWORD>){
$isAdmin=true;
}
}
if(!$isAdmin)
echo "<script type='text/javascript'>window.location.href = '../admin'</script>";
?>
</div>
<!--<div class = "announcmentWrapper">
<div class = "announcment">
<h2>Meeting Attendance</h2>
<form action="SignIn.php" method="post">
<p>User ID:<br> <input type="text" name="id"></p>
<input type="submit" value="Sign In!">
</form>
</div></div>-->
<div class="adminList">
<ul>
<li><a href = 'members?pass=<PASSWORD>'>View All Members</a></li>
<li><a href = 'eventForm.php?pass=<PASSWORD>'>Create Event</a></li>
<li><a href = 'deleteEvent.php?pass=<PASSWORD>'>Delete Event</a></li>
<!--<li><a href = 'http://wvnhs.com/admin/manageMeetings.php?pass=<PASSWORD>'>Add/Remove Meeting</a></li>-->
<li><a href = 'eventMemberList.php?pass=<PASSWORD>'>See Members for Events</a></li>
</ul>
</div>
</body>
</html>
<file_sep>$(document).ready( function(){
var button = $( "#submitButton" );
var form = $('#form1');
var letters = /^[A-Za-z]+$/;
var numbers = /^[12]+$/;
var first ="";
var last="";
var grade="";
var position="";
var id ="";
var email="";
// button.attr('disabled', true);
form1.onkeyup = function(e){
first=form1.value;
}
form2.onkeyup = function(e){
last=form2.value;
}
form3.onkeyup = function(e){
grade=form3.value;
}
form4.onkeyup = function(e){
position=form4.value;
}
form5.onkeyup = function(e){
id=form5.value;
}
form6.onkeyup = function(e){
email=form6.value;
}
window.onkeyup = function(e){
var disabled =true;
// if(first.length>0&&last.length>0&&grade.length==2&&id.length>0&&email.length>0){
// if(first.match(letters)&&last.match(letters)&&grade.match(numbers))
disabled=false;
}
button.attr('disabled',disabled);
}
});
<file_sep><html>
<head>
<link rel="stylesheet" type="text/css" href="../../members/tableStyle.css">
<link rel="stylesheet" type="text/css" href="../../members/indexStyle.css">
<link rel="stylesheet" href="../../members/headbar.css" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../../members/headbar.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
.Table{
width:100%;
}
.nav{
background-color:white;
}
.nav a{
color: #5a5a5a;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase;
}
body{
background: -webkit-linear-gradient(#93C2E3, #2E7AAF);
background: -o-linear-gradient(#93C2E3, #2E7AAF);
background: -moz-linear-gradient(#93C2E3,#2E7AAF);
background: linear-gradient(#93C2E3,#2E7AAF);
background-repeat:no-repeat;
height:100%;
}
h1{
background-color:#56A0D3;
border-radius:25px;
color:#002060;
border:solid 3px ;
text-align:center;
margin-top:50px;
}
.affix{
top: 0;
width: 100%;
}
</style>
</head>
<body>
<div class="nav" data-spy="affix" >
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../../index.html">Home</a></li>
<li><a href="../../forms/index.php">Forms</a></li>
<li><a href="../../myStats/index.php">My Stats</a></li>
<li><a href="../../members/index.php">Members</a></li>
<li><a href="../../events/index.php">Events</a></li>
<li><a href="../../admin/index.php">Admin Login</a></li>
<li><a href="../../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<h1> Members </h1>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pass = $_GET['pass'];
if($pass!="<PASSWORD>"){
echo "<script type='text/javascript'>window.location.href = 'http://wvnhs.com/admin'</script>";
}
$result = mysqli_query($con,"SELECT * FROM members ORDER BY Position DESC, Last, First ASC");
echo "<div class='Table'>
<table >
<tr><td>Last</td>
<td >First</td>
<td >Grade</td>
<td>Position</td>
<td>User Identification</td>
<td>Email</td>
<td>Hours</td>
<td>Group Project</td>
<td>KHK</td>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>
<td >
" . $row['Last'] . "
<form action='changeLast.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
" . $row['First'] . "
<form action='changeFirst.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
" . $row['Grade'] . "
<form action='changeGrade.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
" . $row['Position'] . "
<form action='changePosition.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
".$row['ID']."
<form action='changeID.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
".$row['Email']."
<form action='changeEmail.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit'>
</form>
</td>
<td>
".$row['Hours']." hours of 10 hours
<form action='changeHours.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit' name='add' value='add'>
<input type='submit' name='change' value='change'>
</form>
</td>
<td>
".$row['Group_Project']." of 2 projects
<form action='changeGP.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit' name='add' value='add'>
<input type='submit' name='change' value='change'>
</form>
</td>
<td>
".$row['KHK']." hours of 5 hours
<form action='changeKHK.php?id=".$row['ID']."' method='post'>
<br> <input type='text' name='newValue'>
<input type='submit' name='add' value='add'>
<input type='submit' name='change' value='change'>
</form>
</td>
</tr>";
}
echo "</table>
</div>";
mysqli_close($con);
//ending tag ?>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" type="text/css" href="tableStyle.css">
<!--<link rel="stylesheet" type="text/css" href="indexStyle.css">-->
<link rel="stylesheet" href="headbar.css" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="headbar.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
h1{
text-align:center;
color:rgb(0,32,96);
}
.affix{
top: 0;
width: 100%;
}
body{
background: -webkit-linear-gradient(#002060, #56A0D3);
background: -o-linear-gradient(#002060, #56A0D3);
background: -moz-linear-gradient(#002060,#56A0D3);
background: linear-gradient(#002060,#56A0D3);
}
</style>
</head>
<body>
<div class="nav"data-spy="affix">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<h1 style= "color: rgb(0,32,96)"> Board </h1>
<?php //starting tag
$con = mysqli_connect("localhost", "root", ""); mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM members ORDER BY Position DESC, Last, First ASC");
echo "<div class='Table'>
<table >
<tr><td>Last</td>
<td >First</td>
<td >Grade</td>
<td>Position</td>
</tr>";
while($row = mysqli_fetch_array($result)) {
/* echo "<tr>";
echo "<td><a href ='http://www.wvnhs.com/events/eventInfo.php?eventName=".$row['Name']."'>" . $row['Name'] . "</a></td>";
echo "<td>" . $row['Date'] . "</td>";
echo "<td>" . $row['Spots_Taken'] . "</td>";
echo "<td>" . $row['Total_Spots'] . "</td>";
echo "</tr>";*/
if($row['Position']!=null)
{
echo "<tr>
<td >
" . $row['Last'] . "
</td>
<td>
" . $row['First'] . "
</td>
<td>
" . $row['Grade'] . "
</td>
<td>
" . $row['Position'] . "
</td>
</tr>";
}
}
echo "</table>
</div><br><br><br>";
//mysqli_close($con);
//ending tag ?>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" type="text/css" href="../events/headbar.css">
<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="../events/tableStyle.css">
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
.headbar{
margin-top:-4em;
}
.Table{
border:solid 10px #56A0D3;
border-radius:20px;
width:80%;
}
.red{
color:red;
}
h1{
color: rgb(0,32,96);
font-size: 40px;
font-weight: bold;
padding: 7px 5px;
text-transform: uppercase;
}
h2{
color: rgb(0,32,96);
font-size: 32px;
font-weight: bold;
padding: 7px 5px;
text-transform: uppercase;
}
body{
/*background: -webkit-linear-gradient(#56A0D3, #56A0D3);
background: -o-linear-gradient(#56A0D3, #56A0D3);
background: -moz-linear-gradient(#56A0D3,#56A0D3);
background: linear-gradient(#56A0D3,#56A0D3); */
background-repeat:no-repeat;
}
h3{
color: rgb(0,32,96);
font-size: 32px;
font-weight: bold;
padding: 7px 5px;
text-transform: uppercase;
background-color:#56A0D3;
border-radius:25px;
border:solid 3px rgb(0,32,96);
text-align:center;
width:25%;
margin:auto;
margin-bottom: 10px;
}
.alert{
width:25%;
margin:0 auto;
}
</style>
</head>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = mysqli_real_escape_string($con, $_POST['id']);
//check if ID field is empty
if($id == ""){
echo "<script type='text/javascript'>window.location.href = 'index.php'</script>";
}
$member = mysqli_query($con,"SELECT * FROM members WHERE ID=$id");
while($row = mysqli_fetch_array($member)) {
$name = $row['First']." ".$row['Last'];
$grade = $row['Grade'];
$pos = $row['Position'];
//if($pos.length<1)$pos="Member";
$email = $row['Email'];
$credits=$row['Credits'];
}
echo "<h1>".$name."</h1><br>";
echo "<h3>Statistics<span class='red'>**</span></h3>";
echo "<div class='Table'>
<table >
<tr><td>Name</td>
<td>Grade</td>
<td>Position</td>
<td>User Identification</td>
<td>Email</td>
<td>Credits</td>
</tr>";
echo "<tr>
<td >
".$name."
</td>
<td>
".$grade."
</td>
<td>
".$pos."
</td>
<td>
".$id."
</td>
<td>
".$email."
</td>
<td>
".($credits)." of 100
</td>
</tr></table></div><br><br>";
$events = mysqli_query($con, "SELECT * From Events");
$current_date = new DateTime();
/*echo "<div class = 'announcmentWrapper'>";
echo "<div class = 'announcment'>";
echo "<h2><span class = 'red'>**</span>Statistics Key</h2>";
echo "<hr class = 'experiencehr' />";
echo "<ul>";
echo "<li>20 hours needed by the end of the year, 14 for half year mark.</li><br>";
echo "<br>";
echo "<li>Hours tab includes hours from KHK.</li><br>";
echo "<br>";
echo "<li>1 Group Project needed by half year mark, 2 by the end of the year.</li><br>";
echo "<br>";
echo "<li>Half year mark occurs on February 1st.</li><br>";
echo "</ul>";
echo "</div></div>";*/
echo "<div class = 'announcmentWrapper'>";
echo "<div class = 'announcment'>";
echo "<h2>Events and Updates</h2>";
echo "<hr class = 'experiencehr' />";
while($row = mysqli_fetch_array($events)){
$eventName = $row['Name'];
$creditsAdded= $row['Credits_Added'];
$creditsWorth= $row['Credits_Worth'];
$date = $row['Date'];
//echo "<p>".$eventName."</p><br>";
$event = mysqli_query($con, "SELECT * From $eventName");
while($member = mysqli_fetch_array($event)){
$memberID = $member['ID'];
//echo "<p>".$memberID."</p><br>";
if($memberID===$id){
echo $creditsAdded;
if($creditsAdded == 1){
echo "<p>". $creditsWorth. " credit(s) have been added for ". $eventName. "</p><br>";
}
else{
echo "<p> Credits for ". $eventName. " have not been added yet </p>";
}
echo "<p>You ";
if ($date > $current_date)
echo "are attending ";
else
echo "attended ";
echo str_replace("_", " ", $eventName);
$date2 = date_create($date);
echo " on ".date_format($date2, "l, F d")."</p>";
}
}
}
echo "</div></div>";
mysqli_close($con);
//ending tag ?>
</body>
</html>
<file_sep>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">
<link rel="stylesheet" type="text/css" href="../events/headbar.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
</head>
<style>
.headbar{
margin-top:0em;
}
.announcmentWrapper{
margin-top:5em;
}
h2{
text-align: left;
}
.remove{
float:right;
color:red;
font-weight: bolder;
}
body{
background: -webkit-linear-gradient(#93C2E3, #2E7AAF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#93C2E3, #2E7AAF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#93C2E3,#2E7AAF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#93C2E3,#2E7AAF); /* Standard syntax */
background-repeat:no-repeat;
height:100%;
}
</style>
<body>
<div class="nav" >
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pass = $_GET['pass'];
if($pass!="<PASSWORD>"){
echo "<script type='text/javascript'>window.location.href = '../admin'</script>";
}
$result = mysqli_query($con,"SELECT * FROM Events ORDER BY Name ASC, Date ASC");
echo "<div class='announcmentWrapper' id='announcment'>
<div class='announcment'>
<h1>Admin Event Page</h1>";
$events= array();
while($row = mysqli_fetch_array($result)) {
$date = $row['Date'];
$date2 = date_create($date);
// if(substr($row['Name'],0,7)!='Library'){ // make sure its not a bardi event
$eventName = $row['Name'];
$events[]= $row['Name'];
$result2 = mysqli_query($con, "SELECT * FROM $eventName"); // Get the event table
echo "<hr class ='experiencehr'/>";
echo "<h2>".
preg_replace('/(?<!\ )[A-Z]/', ' $0',$row['Name'])
." - ".
date_format($date2, "l, F d")
." </h2>"
;
echo "<ol>";
$users= array();
while($row2 = mysqli_fetch_array($result2)){
echo "<li>".$row2['FirstName']." ".$row2['LastName']; // print the members
$userID = $row2['ID'];
$users[] = $row2['ID'];
//$_SESSION['users'] = $users; //creates session array
echo "<a href ='removeFromEvent.php?id=$userID&event=$eventName'><span class = 'REMOVE'>Remove</span></a></li><br>
<a href ='addCredits.php?id=$userID&event=$eventName'><span class = 'REMOVE'>ADD CREDITS</span></a></li><br><br>";
}
//$_SESSION['events']['user'] = $users;
//echo implode('<br>', $_SESSION['events']['user']);
//echo implode('<br>',$users); //prints the IDs
//echo "<br>".$eventName;
//echo implode('<br>',$_SESSION['users']); //prints the IDs
//echo "<br>". $_SESSION['event'];
//echo ' <form action="changeCredits.php?id=".$row["ID"]. method="post"><input type="submit" name="add" value="ADD HOURS">';
//echo "<a href ='test.php'><span class = 'REMOVE'>ADD CREDITS</span></a>";
echo "</ol>";
}
echo "</div></div>";
mysqli_close($con);
?>
</body>
</html>
<file_sep><html>
<head>
<!--<link rel="stylesheet" href="headbar.css" type="text/css">
<link rel="stylesheet" href="../events/eventInfoStyle.css" type="text/css">-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--<script type="text/javascript" src="headbar.js"></script>-->
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
.formWrap{
margin:0 auto;
position:relative;
background-color:white;
width:25%;
background-color:#56A0D3;
color:rgb(0,32,96);
margin-top:3em;
border-style:solid;
border-width:5px;
border-radius:25px;
}
.formfield{
width:100%;
display:inline-block;
margin-top: 1em;
margin-bottom: 1em;
text-align:center;
color: rgb(0,32,96);
font-size: 20px;
font-weight: bold;
padding: 7px 5px;
text-transform: uppercase;
}
.headbar{
margin-top:-3em;
}
body{
background: -webkit-linear-gradient(#93C2E3, #2E7AAF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#93C2E3, #2E7AAF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#93C2E3,#2E7AAF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#93C2E3,#2E7AAF); /* Standard syntax */
background-repeat:no-repeat;
height:100%;
}
.adminClass{
background-color:#56A0D3;
}
.affix{
top: 0;
width: 100%;
}
</style>
</head>
<body class= "adminClass">
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
//ending tag ?>
<div class = "formWrap">
<form action="adminDirectory.php" method="post">
<div class ="formfield">Password:<br> <input type="text" name="passcode"></div>
<div class ="formfield"><input type="submit"></div>
</form>
</div>
<!--<div class="container">
<div id="loginbox" style="margin-top:50px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title" style= "color: #002060">Sign In</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<form action="adminDirectory.php" method="post">
<div class ="formfield">Password:<br> <input type="text" name="passcode"></div>
<div class ="formfield"><input type="submit"></div>
</div>
</form>
</div>
</div>
</div>-->
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" href="headbar.css" type="text/css">
<link rel="stylesheet" href="../events/eventInfoStyle.css" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="headbar.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<link rel="stylesheet" href="../main.css">
<style>
body{
margin:0;
}
.headbar{
margin-top:-4em;
}
</style>
</head>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="../myStats/index.php">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<h1>Select The Event</h1>
<?php
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pass = $_GET['pass'];
if($pass!="<PASSWORD>"){
echo "<script type='text/javascript'>window.location.href = '../admin'</script>";
}
$result = mysqli_query($con,"SELECT * FROM Events");
while($row = mysqli_fetch_array($result)) {
$event = $row['Name'];
echo "<a href = 'delete.php?name=".$event."'>".$event."</a><br>";
}
?>
</div>
</body>
</html>
<file_sep><html>
<head>
<link rel="stylesheet" href="../main.css">
<link rel="stylesheet" type="text/css" href="../events/headbar.css">
<!--<link rel="stylesheet" type="text/css" href="../events/eventInfoStyle.css">-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="../events/header.js"></script>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel= "stylesheet" href= "../bootstrap1.css">
<style>
.headbar{
margin-top:-4em;
}
p{
margin-bottom:0em;
}
h1{
text-align:center;
color: rgb(0,32,96);
font-size: 40px;
font-weight: bold;
padding: 7px 5px;
text-transform: uppercase;
}
body{
background: -webkit-linear-gradient(#93C2E3, #2E7AAF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#93C2E3, #2E7AAF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#93C2E3,#2E7AAF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#93C2E3,#2E7AAF); /* Standard syntax */
background-repeat:no-repeat;
height:100%;
}
</style>
</head>
<body>
<div class="nav">
<div class="container">
<ul class= "pull-right nav nav-pills">
<li><a href="../index.html">Home</a></li>
<li><a href="../forms/index.php">Forms</a></li>
<li><a href="">My Stats</a></li>
<li><a href="../members/index.php">Members</a></li>
<li><a href="../events/index.php">Events</a></li>
<li><a href="../admin/index.php">Admin Login</a></li>
<li><a href="../members/signup.php">Create Account</a></li>
</ul>
</div>
</div>
<?php //starting tag
// Check connection
$con = mysqli_connect("localhost", "root", "");mysqli_select_db($con, "WVNHSV2");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<h1>Sign In</h1>";
mysqli_close($con);
//ending tag ?>
<div class = "myStatsLogin">
<form action="Data.php" method="post">
<p>User Identification:<br> <input type="text" name="id"></p>
<input class= "button" type="submit">
</form>
</div>
</body>
</html>
|
ab18e67eeeb0106ab4f2a1beb00339469c596e3d
|
[
"JavaScript",
"PHP"
] | 18
|
PHP
|
saltwicks/newNHS
|
489856342ffaad6a3dcaeb0a95ed7530c7b19a77
|
c99e59023defb64cd0cd87bca426cfe2b05fb014
|
refs/heads/master
|
<file_sep>package org.wikipedia.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Setters and getters for share preferences.
*/
public final class Prefs {
private Prefs() {
}
public static void setUsingExperimentalPageLoad(Context ctx, boolean newValue) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
prefs.edit().putBoolean(PrefKeys.getExperimentalPageLoad(), newValue).apply();
}
public static boolean isUsingExperimentalPageLoad(Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return prefs.getBoolean(PrefKeys.getExperimentalPageLoad(), false);
}
}
<file_sep>package org.wikipedia.util;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
// TODO: Replace with Apache Commons Lang StringUtils.
public final class StringUtil {
@NonNull
public static String emptyIfNull(@Nullable String value) {
return defaultIfNull(value, "");
}
@NonNull
public static CharSequence emptyIfNull(@Nullable CharSequence value) {
return defaultIfNull(value, "");
}
@Nullable
public static String defaultIfNull(@Nullable String value, @Nullable String defaultValue) {
return value == null ? defaultValue : value;
}
@Nullable
public static CharSequence defaultIfNull(@Nullable CharSequence value,
@Nullable CharSequence defaultValue) {
return value == null ? defaultValue : value;
}
private StringUtil() { }
}
|
7071a9fcce1a6f855c46df2f38507751e7258da5
|
[
"Java"
] | 2
|
Java
|
vishnu-narayanan/apps-android-wikipedia
|
d696d40614814cf7a24365e1803cd8d739495f82
|
ae9d4dd5d1e6b8871a4e2d480d288e665c94c4fc
|
refs/heads/main
|
<repo_name>allait/dotfiles<file_sep>/tools/Rakefile
task :install do
linkables("tools").each do |item|
if item == "tools/ssh_config"
install_item 'tools/ssh_config', "#{ENV["HOME"]}/.ssh/config"
else
install_item item
end
end
end
desc 'Update installed packages'
task :update do
system %(brew update && brew outdated)
system %(brew upgrade)
system %(brew cleanup)
system %(brew cask cleanup)
end
desc 'Install common tools from homebrew packages'
task :brew do
puts 'Installing Homebrew packages...'
packages = [
'git',
'zsh',
'vim',
'emacs --cocoa --srgb',
'tmux',
'reattach-to-user-namespace --wrap-pbcopy-and-pbpaste',
'ack',
'ag',
'ctags',
'fasd',
'fzf',
'grc',
'jq',
'mtr',
'ncdu',
'ngrep',
'par',
'proctools',
'repl',
'wget',
'w3m',
'chruby',
'ruby-install',
'caskroom/cask/brew-cask',
]
casks = [
'vagrant',
'karabiner',
]
system %(brew update)
packages.each do |pack|
system %(brew install #{pack})
end
casks.each do |cask|
system %(brew cask install #{cask})
end
system %(brew cleanup)
system %(brew cask cleanup)
end
desc 'Install common tools from npm packages'
task :npm do
puts 'Installing npm packages...'
packages = [
'http-console',
'jshint',
'coffee-script'
]
packages.each do |pack|
system %(npm install -g #{pack})
end
end
desc 'Install common gems'
task :gems do
packages = [
'pry',
'bundler'
]
packages.each do |pack|
system %(gem install #{pack})
end
end
desc 'Install ruby'
task :install_ruby do
system %(ruby-install -c -s build -i ~/.rubies/default ruby)
system %(rm -rf build)
end
<file_sep>/web/vimperator/plugin/twitterrific.js
/*global buffer commands */
commands.addUserCommand(['tweet'],
'Send URL to Twitterrific',
function(args) {
document.location = 'twitterrific:///post?message=' + window.escape(buffer.URL);
});
<file_sep>/zsh/zsh/plugins/command-coloring.zsh
source ~/.zsh/bundle/syntax-highlighting/zsh-syntax-highlighting.zsh
ZSH_HIGHLIGHT_STYLES[alias]='fg=green,bold'
ZSH_HIGHLIGHT_STYLES[builtin]='fg=green,bold'
ZSH_HIGHLIGHT_STYLES[command]='fg=green,bold'
ZSH_HIGHLIGHT_STYLES[function]='fg=green,bold'
<file_sep>/zsh/zsh/lib/history.zsh
# History configuration
HISTFILE=~/.histfile
HISTSIZE=5000
SAVEHIST=5000
# Ignore all duplicates
setopt hist_ignore_all_dups
# Don't autoexecute command found with history search
setopt hist_verify
# Each session will append to history each command
setopt inc_append_history
# Each session has access to other's history
setopt share_history
# Save commands with timestamps
setopt extended_history
# Delete duplicates when size limit reached
setopt hist_expire_dups_first
# Don't save commands starting with space
setopt hist_ignore_space
# Perform ! history expansion
setopt bang_hist
<file_sep>/python/ipython/ipython_config.py
# Configuration file for ipython.
c = get_config()
# Import modules at IPython startup.
c.InteractiveShellApp.exec_lines = [
'import os',
'import sys'
]
# Whether to display a banner upon starting IPython.
c.TerminalIPythonApp.display_banner = False
# Set to confirm when you try to exit IPython with an EOF
c.TerminalInteractiveShell.confirm_exit = False
# Enable completion on elements of lists, results of function calls,
# etc., but can be unsafe because the code is actually evaluated on TAB.
c.IPCompleter.greedy = False
<file_sep>/zsh/zsh/plugins/cdup.zsh
# By ieure@; copied from https://gist.github.com/1474072
function up ()
{
if [ "$1" != "" -a "$2" != "" ]; then
local DIR=$1
local TARGET=$2
elif [ "$1" ]; then
local DIR=$PWD
local TARGET=$1
fi
while [ ! -e $DIR/$TARGET -a $DIR != "/" ]; do
DIR=$(dirname $DIR)
done
test $DIR != "/" && echo $DIR/$TARGET
}
function catup ()
{
local TARGET=`up $1`
test "$TARGET" != "" && cat $TARGET
}
function vimup ()
{
local TARGET=`up $1`
test "$TARGET" != "" && vim $TARGET
}
function lsup ()
{
local TARGET=`up $*`
test "$TARGET" != "" && ls -l $TARGET
}
function cdup ()
{
local TARGET
if [ "$1" != "" ]; then
TARGET=$*
else
TARGET=.git
fi
TARGET=`up $TARGET`
test "$TARGET" != "" && cd $(dirname $TARGET)
}
<file_sep>/Rakefile
require 'rake'
require './dotfiles'
components.each do |component|
namespace component do
load "#{component}/Rakefile" if File.exist?("#{component}/Rakefile")
end
end
desc 'Install dotfiles to $HOME'
task install: [:info, :pull] do
components.each do |component|
if Rake::Task.task_defined? "#{component}:install"
Rake::Task["#{component}:install"].invoke
else
linkables(component).each do |linkable|
install_item(linkable)
end
end
end
end
task :pull do
next if ENV['skip'] && ENV['skip'].include?('pull')
`git pull`
puts 'Initializing submodules...'
`git submodule update --init --rebase`
Dir['.git/modules/vim/vim/bundle/*'].each do |mod|
`echo "doc/tags" > '#{mod}/info/exclude'`
end
end
desc 'Remove installed dotfiles and restore from backup'
task :uninstall do
components.each do |component|
if Rake::Task.task_defined? "#{component}:uninstall"
Rake::Task["#{component}:uninstall"].invoke
else
linkables(component).each do |linkable|
uninstall_item(linkable)
end
end
end
`rm -rf $HOME/.backup $HOME/tmp $HOME/wiki`
end
task default: 'install'
desc 'Clean tmp backup and swap files'
task :clean do
`rm -rf $PWD/build`
`rm -rf $HOME/tmp/swap $HOME/tmp/backup $HOME/tmp/undo`
`mkdir -p $HOME/tmp/swap $HOME/tmp/backup $HOME/tmp/undo`
end
desc 'Create tmp dirs and info files'
task :info do
next if File.exist?("#{ENV['HOME']}/tmp/info")
`mkdir -p $HOME/tmp/info $HOME/tmp/swap $HOME/tmp/backup $HOME/tmp/undo`
print 'Name: '
name = STDIN.gets.chomp
`echo '#{name}' > $HOME/tmp/info/name`
print 'Email: '
email = STDIN.gets.chomp
`echo '#{email}' > $HOME/tmp/info/email`
end
desc 'Update plug.vim and sumbodules'
task :update do
`curl https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim > vim/vim/autoload/plug.vim`
`git submodule foreach git pull origin master`
`git submodule foreach git fetch`
system %(git status)
end
desc 'Setup wiki link'
task :wiki do
next unless File.exist?('../wiki')
`ln -s "$PWD/../wiki" "$HOME/wiki"` unless File.symlink?("#{ENV['HOME']}/wiki")
end
desc 'Install node.js and npm'
task :install_node do
system %(brew install node)
system %(brew cleanup)
end
<file_sep>/zsh/zsh/lib/utils.zsh
# Autoload mass rename
autoload zmv
# Autoload xargs with input from command line
autoload zargs
<file_sep>/web/vimperator/plugin/searches.js
var search_engines = [
{
key: "clj",
title: 'ClojureDocs',
url:'http://clojuredocs.org/search?q=%s'
},
{
key: "mdn",
title: 'Mozilla Developer Network',
url:'https://developer.mozilla.org/en-US/search?q=%s'
},
{
key: "so",
title: "Stack Overflow",
url: "http://stackoverflow.com/search?q=%s"
},
{
key: "gh",
title: "GitHub",
url: "https://github.com/search?q=%s"
},
{
key: "dj",
title: "Django Docs",
url: "https://docs.djangoproject.com/search/?q=%s"
},
];
/*global liberator */
for (var i=0; i < search_engines.length; i++) {
liberator.execute('silent bmark -title "' + search_engines[i].title + '" -keyword ' + search_engines[i].key + ' ' + search_engines[i].url);
}
<file_sep>/tools/bin/each-dir
#!/usr/local/bin/zsh
while read dir
do
echo "---------- ${dir} ----------"
cd ${dir}
eval $@
cd ..
done
<file_sep>/Brewfile
brew "ctags"
brew "direnv"
brew "exa"
brew "fasd"
brew "fd"
brew "fzf"
brew "git"
brew "git-absorb"
brew "jq"
brew "mtr"
brew "ncdu"
brew "neovim"
brew "par"
brew "sd"
brew "the_silver_searcher"
brew "tmux"
brew "tree"
brew "vim"
brew "zsh"
<file_sep>/tools/bin/git-fx
#!/bin/zsh -e
git-fzf-ref() {
git log --color=always --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" |
fzf --ansi --no-sort --reverse --tiebreak=index --preview='git show $(echo {} | cut -d" " -f1)'| cut -d' ' -f1
}
git commit --fixup $(git-fzf-ref HEAD...origin/main)
<file_sep>/iterm/Rakefile
task :install do
next
end
<file_sep>/tools/bin/rpl
#!/usr/bin/env sh
# Simplified version of defunkt/repl in POSIX shell
#
# repl is an interactive program which tenderly wraps another,
# non-interactive program.
# Use the real thing if available
if which repl &> /dev/null; then
exec repl $@
fi
# Apply rlwrap if available
if which rlwrap &> /dev/null && [[ -z $__RLWRAP ]]; then
export __RLWRAP=1
exec rlwrap $0 $*
fi
while true; do
read -p "$1 >> " line
if [[ -n $line ]]; then
$@ $line
fi
done
<file_sep>/zsh/zsh/plugins/grc.zsh
colourify () {
grc -es --colour=auto $@
}
configure () {colourify ./configure $@}
diff () {colourify diff $@}
gcc () {colourify gcc $@}
g++ () {colourify g++ $@}
as () {colourify as $@}
gas () {colourify gas $@}
ld () {colourify ld $@}
netstat () {colourify netstat $@}
ping () {colourify ping $@}
traceroute () {colourify /usr/sbin/traceroute $@}
<file_sep>/osx/defaults.sh
#!/usr/bin/env bash
# System
# ======
# Fix /etc/zshenv misconfiguration
# mv /etc/zshenv /etc/zprofile
# General UX
# ==========
# Save to disk (not to iCloud) by default
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
# Require password immediately after sleep or screen saver begins
defaults write com.apple.screensaver askForPassword -int 1
defaults write com.apple.screensaver askForPasswordDelay -int 0
# Keyboard
# ========
# Enable full keyboard access for all controls (e.g. enable Tab in modal dialogs)
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3
# Disable press-and-hold for keys in favor of key repeat
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
# Set a blazingly fast keyboard repeat rate
defaults write NSGlobalDomain KeyRepeat -int 1
defaults write NSGlobalDomain InitialKeyRepeat -int 10
# Trackpad & Mouse
# ================
defaults write -g com.apple.mouse.scaling -int 3
defaults write -g com.apple.trackpad.scaling -int 3
# Finder
# ======
# Show all filename extensions in Finder
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
# Show status bar in Finder
defaults write com.apple.finder ShowStatusBar -bool true
# Allow text selection in Quick Look
defaults write com.apple.finder QLEnableTextSelection -bool true
# Display full POSIX path as Finder window title
defaults write com.apple.finder _FXShowPosixPathInTitle -bool true
# Avoid creating .DS_Store files on network volumes
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
# Disable the warning when changing a file extension
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
# Disable the warning before emptying the Trash
defaults write com.apple.finder WarnOnEmptyTrash -bool false
# Show the ~/Library folder
chflags nohidden ~/Library
# Dock
# ====
# Enable spring loading for all Dock items
defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true
# Show indicator lights for open applications in the Dock
defaults write com.apple.dock show-process-indicators -bool true
# Automatically hide and show the Dock and reduce delay
defaults write com.apple.dock autohide -bool true
defaults write com.apple.Dock autohide-delay -float 0; killall Dock
# Make Dock icons of hidden applications translucent
defaults write com.apple.dock showhidden -bool true
# Safari
# ======
# Make Safari’s search banners default to Contains instead of Starts With
defaults write com.apple.Safari FindOnPageMatchesWordStartsOnly -bool false
<file_sep>/zsh/zsh/plugins/virtualenv.zsh
# Set up virtualenv variables
export WORKON_HOME=$HOME/.virtualenvs
# Set default python to Python 3
export VIRTUALENV_PYTHON=python3
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_SCRIPT=/usr/local/bin/virtualenvwrapper.sh
source /usr/local/bin/virtualenvwrapper_lazy.sh
<file_sep>/python/virtualenv_hooks/postactivate
#!/bin/zsh
# This hook is run after every virtualenv is activated.
PS1="[`basename \"$VIRTUAL_ENV\"`] $_OLD_VIRTUAL_PS1"
<file_sep>/zsh/zsh/plugins/gpg.zsh
if which gpg-agent >/dev/null; then
if ! pgrep gpg-agent >/dev/null; then
gpg-agent --quiet --daemon 2>/dev/null
fi
if [ -f "${GPG_ENV_FILE}" ]; then
source "${GPG_ENV_FILE}"
export GPG_AGENT_INFO
fi
fi
<file_sep>/vim/Rakefile
desc "Build latest macvim from github"
task :macvim do
`mkdir -p $PWD/build`
puts "Cloning macvim..."
macvim_path = "#{ENV["PWD"]}/build/macvim"
if File.exists?(macvim_path)
system %Q[cd #{macvim_path}; git pull]
else
system %Q[git clone git://github.com/b4winckler/macvim.git #{macvim_path}]
system %Q[cd #{macvim_path}/src/MacVim/icons; curl http://cloud.github.com/downloads/b4winckler/macvim/MacVim-docicon-pack.tbz | tar xj]
end
system %Q[cd #{macvim_path}/src; ./configure --with-features=huge \
--enable-rubyinterp \
--enable-pythoninterp \
--enable-perlinterp \
--enable-cscope \
--with-macarchs=x86_64 ]
system %Q[cd #{macvim_path}/src; make]
`cp #{macvim_path}/src/MacVim/mvim /usr/local/bin/`
`ln -s /usr/local/bin/mvim /usr/local/bin/vim`
`ln -s /usr/local/bin/mvim /usr/local/bin/view`
`ln -s /usr/local/bin/mvim /usr/local/bin/vimdiff`
`open #{macvim_path}/src/MacVim/build/Release/`
end
<file_sep>/osx/Rakefile
require './dotfiles'
task :install do
linkables("osx").each do |item|
if item == 'osx/DefaultKeyBinding.dict.erb'
target = "#{ENV["HOME"]}/Library/KeyBindings"
backup target
`mkdir -p #{target}/`
install_item 'osx/DefaultKeyBinding.dict.erb', "#{target}/DefaultKeyBinding.dict"
elsif item == 'osx/keyremap'
target = "\"#{ENV["HOME"]}/Library/Application Support/Karabiner\""
`mkdir -p #{target}/`
install_item "osx/keyremap/private.xml", "#{target}/private.xml"
elsif item == 'osx/karabiner.json'
target = "\"#{ENV["HOME"]}/.config/karabiner\""
`mkdir -p #{target}/`
install_item "osx/karabiner.json", "#{target}/karabiner.json"
elsif item != 'osx/defaults.sh'
install_item item
end
end
end
desc "Setup OS X configuration settings"
task :defaults do
`bash osx/defaults.sh`
end
task :uninstall do
linkables("osx").each do |item|
if item == 'osx/DefaultKeyBinding.dict'
target = "#{ENV["HOME"]}/Library/KeyBindings"
uninstall_item 'osx/DefaultKeyBinding.dict', "#{target}/DefaultKeyBinding.dict"
restore target
elsif item == 'osx/defaults.sh'
next
else
uninstall_item item
end
end
end
<file_sep>/w3m/Rakefile
require './dotfiles'
task :install do
`mkdir -p $HOME/.w3m/`
linkables("w3m").each do |item|
target = "#{ENV["HOME"]}/.#{item}"
backup target
install_item item, target
end
end
task :uninstall do
linkables("w3m").each do |item|
target = "#{ENV["HOME"]}/.#{item}"
uninstall_item item, target
restore target
end
end
<file_sep>/zsh/zsh/plugins/npm.zsh
# from `npm completion`
_npm_completion() {
compadd -- $(COMP_CWORD=$((CURRENT-1)) \
COMP_LINE=$BUFFER \
COMP_POINT=0 \
npm completion -- "${words[@]}" \
2>/dev/null)
}
compdef _npm_completion npm
<file_sep>/zsh/zsh/lib/completion.zsh
autoload -U compinit
compinit -i
# Treat #~^ as part of patterns
setopt extendedglob
# Don't remove space after completion and before &|
export ZLE_REMOVE_SUFFIX_CHARS=$'\t\n;'
export ZLE_SPACE_SUFFIX_CHARS=$'&|'
# Cd on directory name
setopt autocd
# Show list on ambiguous completion
setopt auto_list
# Add trailing slash to directory names
setopt auto_param_slash
# Make completion list smaller
setopt list_packed
# Don't print 'no matches found' error
unsetopt nomatch
# Complete from within word
setopt complete_in_word
# Jump to word end on successful completion
setopt always_to_end
# Perform implicit tees or cats on redirections
setopt multios
# Keep silent, literally
unsetopt beep list_beep
# Ignore completion functions I don't have
zstyle ':completion:*:functions' ignored-patterns '_*'
# Immediately show completion menu
zstyle ':completion:*' menu select
# Remove trailing slash if using directory as completion
zstyle ':completion:*' squeeze-slashes true
# Set description style
zstyle ':completion:*' format '%F{white}%d%f'
# Use tag name as the name of the group
zstyle ':completion:*' group-name ''
# Perform case-insensitive matching
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
zstyle ':completion:*' keep-prefix
# Disallow remote connections for completion functions
zstyle ':completion:*' remote-access false
# Complete options for commands after directory stack for cd, pushd, ...
zstyle ':completion:*' complete-options true
# Cache completions for commands that support it
zstyle ':completion:*' use-cache true
# Complete only given users
zstyle ':completion:*' users root $(whoami)
# Zsh completion control functions
zstyle ':completion:*' completer _oldlist _complete _match _ignored _list
<file_sep>/python/Rakefile
require './dotfiles'
task :install do
linkables("python").each do |item|
next if item == "python/requirements.txt"
if item == 'python/ipython'
target = "#{ENV["HOME"]}/.ipython"
backup target
`mkdir -p #{target}/profile_default`
install_item 'python/ipython/ipython_config.py', "#{target}/profile_default/ipython_config.py"
elsif item == 'python/virtualenv_hooks'
next if not ENV["WORKON_HOME"]
target = "#{ENV["WORKON_HOME"]}"
`mkdir -p #{target}`
install_item 'python/virtualenv_hooks/postactivate', "#{target}/postactivate"
elsif item == 'python/flake8'
target = "#{ENV["HOME"]}/.config"
`mkdir -p #{target}`
install_item 'python/flake8', "#{target}/flake8"
else
install_item item
end
end
end
task :uninstall do
linkables("python").each do |item|
if item == 'python/ipython'
target = "#{ENV["HOME"]}/.ipython"
uninstall_item 'python/ipython/ipython_config.py', "#{target}/profile_default/ipython_config.py"
restore target
elsif item == 'python/virtualenv_hooks'
next if not ENV["WORKON_HOME"]
target = "#{ENV["WORKON_HOME"]}"
uninstall_item 'python/virtualenv_hooks/postactivate', "#{target}/postactivate"
elsif item == 'python/flake8'
target = "#{ENV["HOME"]}/.config"
uninstall_item 'python/flake8', "#{target}/flake8"
else
uninstall_item item
end
end
end
desc "Setup common python packages"
task :install_pip_tools do
system %Q[pip install -U -r python/requirements.txt]
end
desc "Install python interpreter"
task :install_python do
system %Q[brew install python --framework]
system %Q[brew cleanup]
`sudo rm /Library/Frameworks/Python.framework`
`sudo ln -s $(find /usr/local/Cellar/python -name Python.framework) /Library/Frameworks/Python.framework`
system %Q[/usr/local/share/python/easy_install pip]
system %Q[/usr/local/share/python/pip install --upgrade distribute]
end
<file_sep>/web/Rakefile
require './dotfiles'
task :install do
linkables("web").each do |item|
if item == 'web/vimperator'
target = "#{ENV["HOME"]}/.vimperator"
backup target
`mkdir -p #{target}/`
install_item 'web/vimperator/colors', "#{target}/colors"
install_item 'web/vimperator/plugin', "#{target}/plugin"
else
install_item item
end
end
end
task :uninstall do
linkables("web").each do |item|
if item == 'web/vimperator'
target = "#{ENV["HOME"]}/.vimperator"
uninstall_item 'web/vimperator/colors', "#{target}/colors"
uninstall_item 'web/vimperator/plugin', "#{target}/plugin"
restore target
else
uninstall_item item
end
end
end
<file_sep>/zsh/zsh/plugins/fasd.zsh
# Initialize fasd
if source $(which fasd) 2>/dev/null; then
eval "$(fasd --init zsh-hook zsh-ccomp zsh-ccomp-install zsh-wcomp zsh-wcomp-install)"
fi
fasd_cd() {
if [ $# -le 0 ]; then
cd "$(fasd -dl | fzf)"
else
cd "$(fasd -dl1 "$@")"
fi
}
# Alias j
alias j="fasd_cd"
<file_sep>/fabfile.py
import os
import tempfile
import shutil
from fabric.api import local, env, run, put
def transfer_gpg_keys():
local("gpg --export-secret-keys > ~/tmp/gpg.sec")
local("gpg --export-secret-subkeys > ~/tmp/gpg.sub")
put('~/tmp/gpg.sec', 'gpg.sec')
put('~/tmp/gpg.sub', 'gpg.sub')
run('gpg --import ~/gpg.s* &> /dev/null || rm ~/gpg.sub ~/gpg.sec*')
local('rm ~/tmp/gpg.sub ~/tmp/gpg.sec')
def upload_ssh_key(name='id_rsa'):
with open(os.path.expanduser('~/.ssh/%s.pub' % name)) as fd:
key = fd.readline().strip()
run('mkdir -p ~/.ssh && chmod 700 ~/.ssh')
run("echo '%s' >> ~/.ssh/authorized_keys && chmod 644 ~/.ssh/authorized_keys" % key)
def install_remote_dotfiles(*args):
tmp_dir = tempfile.mkdtemp()
local("HOME=%s rake install components=vim,zsh,git,tools,bash,tmux remote=linux" % tmp_dir)
local('find %s -name ".git" -delete' % tmp_dir)
if args:
for arg in args:
put("%s/%s" % (tmp_dir, arg), "")
else:
put("%s/.*" % tmp_dir, "")
put("%s/*" % tmp_dir, "")
shutil.rmtree(tmp_dir)
# Hosts
def vagrant(path):
env.user = 'vagrant'
env.hosts = ['127.0.0.1:2222']
res = local('cd %s && vagrant ssh-config | grep IdentityFile' % path, capture=True)
env.key_filename = res.split()[1]
<file_sep>/zsh/zsh/plugins/ssh.zsh
ssh-add -K 2>/dev/null
<file_sep>/zsh/zsh/lib/keys.zsh
# Get emacs keybindings
bindkey -e
# Disable ^S/^Q start/stop in ZLE
unsetopt flow_control
# Disable software flow control with ^S/^Q
stty -ixon
# Make word commands stop before and after dots and /
bindkey "^W" vi-backward-kill-word
bindkey "^[b" vi-backward-word
bindkey "^[f" vi-forward-word
# Home/End/Delete keys
bindkey "^[OH" beginning-of-line
bindkey "^[OF" end-of-line
bindkey "^[[3~" delete-char
bindkey ' ' magic-space
# ^U to delete line to beginning instead of whole line
bindkey "^U" backward-kill-line
# Search history for current line contents with up/down keys
bindkey "^[[A" history-search-backward
bindkey "^[[B" history-search-forward
# Push multiline commands too
bindkey "^Q" push-input
# Edit command in default editor
# http://stackoverflow.com/questions/890620/unable-to-have-bash-like-c-x-e-in-zsh
autoload edit-command-line
zle -N edit-command-line
bindkey '^Xe' edit-command-line
# Restore normal history behavior in vi-mode
[[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" up-line-or-history
[[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" down-line-or-history
<file_sep>/zsh/zsh/lib/prompt.zsh
# Parameter expantion and substitution performed in prompts
setopt prompt_subst
function prompt_vcs_info() {
local ref
ref=$(git symbolic-ref HEAD 2> /dev/null) || \
ref=$(git rev-parse --short HEAD 2> /dev/null) || return
echo "$1${ref#refs/heads/}$2"
}
function prompt_host {
if [[ $HOST == *.local || $HOST == *.home ]]; then
return
else
echo "$1%m$2"
fi
}
function prompt_pwd {
if [[ $PWD != $HOME ]]; then
print `echo $PWD|sed -e "s|^$HOME|~|" -e 's-/\([^/]\)\([^/]*\)-/\1-g'``echo $PWD|sed -e 's-.*/[^/]\([^/]*$\)-\1-'`
else
print '~'
fi
}
# Left prompt
if [[ $(tput colors) == 256 ]]; then
PROMPT=$(prompt_host "%F{202}" "%f ")
PROMPT=$PROMPT'%f%F{25}$(prompt_pwd)%f$(prompt_vcs_info " on %F{yellow}" %f) '
PROMPT=$PROMPT'%(?,%F{221},%F{red})%#%f '
else
PROMPT=$(prompt_host "%F{red}" "%f ")
PROMPT=$PROMPT'%F{blue}$(prompt_pwd)%f$(prompt_vcs_info " on %F{yellow}" %f) '
PROMPT=$PROMPT'%(?,%F{yellow},%F{red})%#%f '
fi
# iTerm prompt integration
PROMPT=%{$(printf "\033]133;A\007")%}$PROMPT%{$(printf "\033]133;B\007")%}
# Right prompt
RPROMPT='%1(j,%F{blue}● %f,)%(?,,%F{red}[%?]%f)[%T]'
# Vi mode indication
function zle-line-init zle-keymap-select {
RPS1="${${KEYMAP/vicmd/$VI_NORMAL_MODE}/(main|viins)/$VI_INSERT_MODE}"
RPS2=$RPS1
zle reset-prompt
}
# Vi mode indicators
VI_NORMAL_MODE='%F{red}⚙%f'
VI_INSERT_MODE=$RPROMPT
zle -N zle-line-init
zle -N zle-keymap-select
<file_sep>/python/requirements.txt
# Shell tools
ipython
Fabric
httpie
# Test tools
flake8
# Package installation
virtualenv
virtualenvwrapper
<file_sep>/zsh/zsh/lib/appearance.zsh
# Time commands if executed longer than
REPORTTIME=10
# Show job number when suspending a process
setopt longlistjobs
# Color BSD ls output
export CLICOLOR=1
# Set language
export LANGUAGE=en_US.UTF8
<file_sep>/zsh/zsh/plugins/chruby.zsh
# Load chruby into a shell session.
source /usr/local/opt/chruby/share/chruby/chruby.sh 2> /dev/null
# Complete ruby names from ~/.rubies/*
compctl -g '~/.rubies/*(:t)' chruby
# Set default ruby if chruby is installed
type chruby >/dev/null && chruby default
<file_sep>/README.md
dotfiles
========
My config files for `vim`, `zsh`, `pentadactyl`, `git` and other shell tools. I don't expect them to
be of much use to anyone except myself, however there are some scripts, snippets and utilities that
might be useful and I'll try to list them below.
Features
--------
* Files are organized into separate folders, each representing a stand-alone component. Each component
can define special installation rules in its own Rakefile, as well as add new rake tasks
* Support for ERB templates instead of plain files
* Support for joining files from different parts, depending on the current system and installation
type: e.g. `*.local.darwin` for local OS X specific options and `*.remote.linux` for remote Linux
installation
* Support for partial installation
* Rake and fabric tasks to automate local and remote environment setup
### Vim
* New color scheme: `prefect.vim`
* Some snippets for `UltiSnips`: python, puppet, SQL and more
* Extended javascript completion with support for jQuery and underscore.js
### ZSH
* Custom prompt with current mercurial/git branch name and status flags
* New completion function for `curl`
* Wrapper function `t` for taskwarrior
### Git
* `git l` and `git gl` show git log in custom one-line format
* `git dfm` shows diff using Mac OS X FileMerge
### Pentadactyl
* New color scheme: `light.penta`
* New plugins to send current URL and selection to Delibar, Twitterrific or The Hit List
### iTerm
* New color scheme: `Prime.itermcolors`
### Rake and fabric tasks
* `rake python:install_pip_tools` install python packages from `python/requirements.txt`
* `rake vim:macvim` build MacVim with current python version
* `fab install_remote_dotfiles` build dotfiles and copy them to remote machine
* `fab upload_ssh_key` append `~/.ssh/id_rsa.pub` to remote `authorized_keys`
Installation
------------
Clone the repository to any folder:
git clone git://github.com/allait/dotfiles ~/Dotfiles
cd ~/Dotfiles
Launch automatic installation (`ruby` and `rake` are required for this step):
rake install
This will backup all existing files from `~/` to `~/.backup` and replace them with symlinks to files
inside your local repository clone, pull all external plugins and render `*.erb` templates for
config files, requiring personal information.
### Default installation process
Load existing component Rakefiles, using component name as surrounding rake namespace.
Run `git pull`, initialize and update git submodules. For each component:
1. Invoke `<component>:install` task (defined as `task :install` in `<component>/Rakefile`) if present
Or, if `<component>:install` is not defined:
1. Render all `*.erb` templates
2. Concatenate each file with `*.local` and `*.local.<current-system>` if any. Current system is
determined using `uname -s` result, converted to lowercase.
3. Symlink/copy files from `<component>/name` to `~/.name`
### Custom installation
You can change installation process with `ENV` variables, either setting them before invoking `rake
install`, or passing `key=value` pairs as rake arguments. The following `ENV` variables can be used:
* `HOME=/path/ rake install` install to `/path/` instead of user home directory
* `rake install skip=pull` skip `git pull` and git submodule update during installation
* `rake install components=vim,git,web` installs only selected components
* `rake install remote=linux` performs installation appending `*.remote.linux` files instead of
`*.local.<system>`
Each component can customize its installation process by defining `:install` and `:uninstall` rake
tasks in its own Rakefile. If present, these tasks will be invoked during installation instead of
the default process.
### Removal
To uninstall and restore files from `~/.backup` run `rake uninstall` from repository folder.
Compatibility
-------------
These should work on Mac OS X 10.6 - 10.7. Most of the scripts should work on Linux systems as is, but I've
stopped purposefully making them compatible some time ago. Since there are differences in BSD and
Linux coreutils, some of the zsh functions and plugins aren't expected to work properly.
<file_sep>/web/vimperator/plugin/sslstatus.js
"use strict";
Cu.import("resource://gre/modules/XPCOMUtils.jsm", modules);
const progressListener = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIWebProgressListener]),
onSecurityChange: function onSecurityChange(webProgress, request, state) {
if (state & Ci.nsIWebProgressListener.STATE_IS_INSECURE)
highlight.set("StatusLine", "");
else if (state & Ci.nsIWebProgressListener.STATE_IS_BROKEN)
highlight.set("StatusLine", "color: #f4000f");
else if (state & Ci.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
highlight.set("StatusLine", "color: #11c700");
else if (state & Ci.nsIWebProgressListener.STATE_SECURE_HIGH)
highlight.set("StatusLine", "color: #3152c7");
}
};
config.browser.addProgressListener(progressListener, Ci.nsIWebProgress.NOTIFY_SECURITY);
<file_sep>/zsh/zsh/lib/aliases.zsh
# Enable color output
alias grep='grep --color=auto'
# Find the option for using colors in ls, depending on the version: Linux or BSD
ls --color -d . &>/dev/null 2>&1 && alias ls='ls --color=tty' || alias ls='ls -G'
# ack fix for Debian and it's curious naming scheme
which ack-grep >/dev/null && alias ack=ack-grep
# Shortcuts
alias l='ls -lAh'
alias pu='pushd'
alias po='popd'
# Python aliases
alias pdt='python -m doctest -v'
serve() {(cd ${1-.}; python -m SimpleHTTPServer 8642)}
# Git alias
alias g='git'
<file_sep>/zsh/zsh/functions/man
local -x LESS_TERMCAP_md=$'\E[00;34m' # begin bold
local -x LESS_TERMCAP_me=$'\E[0m' # end mode
local -x LESS_TERMCAP_us=$'\E[00;32m' # begin underline
local -x LESS_TERMCAP_ue=$'\E[0m' # end underline
command man "$@"
<file_sep>/zsh/zshrc
# Load and register completion functions
fpath=(~/.zsh/completions ~/.zsh/bundle/zsh-completions/src $fpath)
# There be user-defined functions
fpath=(~/.zsh/functions $fpath)
autoload ~/.zsh/functions/*(:t)
# Load config files, if we're not in vim or some other terminal
if [[ $TERM != "dumb" ]]; then
for config_file (~/.zsh/lib/*.zsh) source $config_file
unset config_file
# Load plugins
for plugin_file (~/.zsh/plugins/*.zsh) source $plugin_file
unset plugin_file
fi
# Use vim for git commits and stuff
export EDITOR="vim"
# Setup PAGER and less options
export PAGER=less
export LESS="-FiRX"
# Load per-system config if present
source ~/.zshrc.local 2>/dev/null
<file_sep>/zsh/zsh/plugins/fzf.zsh
# Key bindings
# ------------
source /usr/local/opt/fzf/shell/completion.zsh 2>/dev/null
source /usr/local/opt/fzf/shell/key-bindings.zsh 2>/dev/null
# Use fd for CTRL-T completion
export FZF_CTRL_T_COMMAND="fd --follow"
# Use fd for `fzf` command
export FZF_DEFAULT_COMMAND='fd --hidden --follow --exclude ".git"'
# Use fd for ** path completion
_fzf_compgen_path() {
fd --hidden --follow --exclude ".git" . "$1"
}
# Use fd to generate the list for directory completion
_fzf_compgen_dir() {
fd --type d --hidden --follow --exclude ".git" . "$1"
}
# _v_complete() {
# _fzf_complete "--multi --reverse --filter" "$@" <(
# fd -d5
# )
# }
v() {
local editor="nvim"
local files
IFS=$'\n' files=($(fzf --query="$@" --cycle --select-1 --exit-0))
[[ -n "$files" ]] && ${editor} "${files[@]}"
}
# compctl -U -K _v_complete -x 'C[-1,-*e],s[-]n[1,e]' -c - 'c[-1,-A][-1,-D]' -f -- v
<file_sep>/zsh/zprofile
# Keep only unique items in path, moving them when necessary
typeset -U path PATH
path=(~/.bin ~/.cargo/bin /usr/local/bin /usr/local/sbin $path)
<file_sep>/dotfiles.rb
require 'erb'
STRIP_EXTENSIONS = /\.erb/
def components
return ENV["components"].split(",") if ENV["components"]
Dir.glob('*/').map do |component|
component.split("/").last
end
end
def linkables(component)
Dir.glob("#{component}/*").reject do |item|
item =~ /Rakefile|build|\.local|\.remote/
end
end
def remote?
ENV["remote"]
end
def install_item(item, target=nil)
file = item.split('/').last.split(STRIP_EXTENSIONS).last
target = target || "#{ENV["HOME"]}/.#{file}"
backup target
link_item item, target
end
def backup(target)
backup_target = "#{ENV["HOME"]}/.backup/#{target.split('/').last}"
if File.exists?(target) && !File.symlink?(target)
if not File.exists?(backup_target)
`mkdir -p $HOME/.backup/` if not File.directory?("#{ENV["HOME"]}/.backup")
`mv "#{target}" "#{backup_target}"`
else
FileUtils.rm_rf(target)
end
end
end
def link_item(item, target)
type = (remote?)? "remote":"local"
system_name = ENV["remote"] || `uname -s`.strip.downcase
parts = Dir.glob("#{item.split(STRIP_EXTENSIONS).last}.#{type}{.#{system_name},}{.erb,}")
cmd = (remote?)? "cp -rf":"ln -s"
puts "#{cmd} #{target}..."
return `#{cmd} $PWD/#{item} #{target}` if File.directory?(item)
if item =~ /.erb$/
File.open("#{target}", 'w') do |render_file|
render_file.write ERB.new(File.read(item)).result(binding)
end
elsif parts.empty?
`#{cmd} $PWD/#{item} #{target}`
else
`cp $PWD/#{item} #{target}`
end
parts.each do |part|
puts "Appending #{part} to #{item}..."
if part =~ /.erb/
File.open("#{target}", 'a') do |render_file|
render_file.write ERB.new(File.read(part)).result(binding)
end
else
`cat #{part} >> #{target}`
end
end
end
def uninstall_item(item, target=nil)
file = item.split('/').last.split(STRIP_EXTENSIONS).last
target = target || "#{ENV["HOME"]}/.#{file}"
if File.exists?(target)
puts "Removing #{target}..."
FileUtils.rm_rf(target)
end
restore target
end
def restore(target)
backup_target = "#{ENV["HOME"]}/.backup/#{target.split('/').last}"
if File.exists?(backup_target)
FileUtils.rm_rf(target) if File.exists?(target)
`mv "#{backup_target}" "#{target}"`
end
end
<file_sep>/bash/bashrc
# GENERAL {{{1
# =======
# Add .bin and local/bin to PATH
export PATH="$HOME/.bin:/usr/local/bin:$PATH"
# Use vim for everything
export EDITOR="vim"
# If not running interactively, do nothing
[ -z "$PS1" ] && return
# Ignore extensions in file completion
FIGNORE="~:#:.pyc"
# Update the values of LINES and COLUMNS after each command
shopt -s checkwinsize
# Enable bash completion
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
# Setup virtualenv
VIRUTALENV_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh 2>&-
# Setup LESS options
export LESS='-eiRX'
# Color BSD ls output
export CLICOLOR=1
# HISTORY {{{1
# =======
# Do not save lines starting with a space and duplicates
export HISTCONTROL=ignoreboth
# Save lines to history
export HISTFILESIZE=10000
# PROMPT {{{1
# ======
RED="\[\033[0;31m\]"
GREY="\[\033[1;30m\]"
YELLOW="\[\033[0;33m\]"
BLUE="\[\033[0;34m\]"
PS_CLEAR="\[\033[0m\]"
export PS1="${RED}\h${PS_CLEAR} ${BLUE}\w${PS_CLEAR} ${YELLOW}\$${PS_CLEAR} "
# KEYBINDINGS {{{1
# ===========
# Up/down cycles through history commands starting with current prefix
bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward
# ALIASES {{{1
# =======
# Color command output
alias grep="grep --color=auto"
# ls shortcut
alias l="ls -lAh"
# Git shortcut
alias g="git"
# Attach to existing tmux session
alias attach="tmux attach"
<file_sep>/web/vimperator/plugin/thl.js
/*global buffer Ci commands */
commands.addUserCommand(['thl'],
'Add task to The Hit List',
function(args) {
var taskTitle = '';
var url = buffer.URL;
var selection = buffer.selectionController.getSelection(Ci.nsISelectionController.SELECTION_NORMAL).toString();
if (selection) {
taskTitle = selection;
}
else {
taskTitle = "Look at \"" + buffer.title + "\"";
}
document.location = "thehitlist:///inbox/tasks?method=POST&title=" + encodeURIComponent(taskTitle) + "&url=" + encodeURIComponent(url);
});
|
9005f0c23e6ce37e441ff285c64454ccebcd790c
|
[
"Ruby",
"JavaScript",
"Markdown",
"Python",
"Text",
"Shell"
] | 44
|
Ruby
|
allait/dotfiles
|
77cb4a76984dbcd1cdd361363534b6eb8264e01d
|
588ebf036f0eb2e9772daed24811d0abffce404c
|
refs/heads/master
|
<file_sep>const mongoose = require('mongoose')
mongoose.connect('mongodb://mongo/mydatabase',{
useNewUrlParser:true,
useUnifiedTopology:true
})
.then(db=>console.log('DB is connet to', db.connection.host))
.catch(error=>console.error(error))
|
8a0d25223025b568c8e9e87566d3d8fca0ed7a4e
|
[
"JavaScript"
] | 1
|
JavaScript
|
EdsonRosas3/docker-compose-mongo-node
|
870b6a17e69593c92b0d6977d3f8da873aaed060
|
bfeda7d79cdd163ad2169fda28d12dacec8f185c
|
refs/heads/master
|
<repo_name>munterfinger/global-temperature-change-detection<file_sep>/src/globalTemperatureChange.R
# ------------------------------------------------------------------------------
# Change detection in global temperature - universal Kriging
#
# Author: <NAME>
# Date: 26.73.17
# Settings and Variables --------------------------------------------------
rm(list=ls()) # Clean the environment
options(scipen=6) # Display digits, not the scientific version
options(digits.secs=6) # use milliseconds in Date/Time data types
options(warning=FALSE) # Don't show warnings
par(mfrow=c(1,1)) # reset plot placement to normal 1 by 1
maxpixels <- 101250 # Plot resolution
# Get paths
setwd('..')
dataFolder <- file.path(getwd(), "data") # Data folder
figureFolder <- file.path(getwd(), "docs/figures") # Figure Folder
# Libraries
library(ape)
library(dichromat)
library(FNN)
library(ggplot2)
library(gdistance)
library(gridExtra)
library(gstat)
library(raster)
library(rasterVis)
library(rgdal)
library(rgeos)
library(sp)
# Data --------------------------------------------------------------------
# Define CRS
WGS84 <- CRS("+init=epsg:4326")
# Read CSV file for temperature
temp <- read.csv(file.path(dataFolder, "temperature.csv"))
temp <- temp[complete.cases(temp), ]
# Train and validation data
selection <- sample(1:nrow(temp), floor(nrow(temp)*0.05), replace = FALSE)
temp.val <- temp[selection,]
temp <- temp[-selection,]
# Create spdf's and assign CRS
coordinates(temp.val)<-~long+lat
proj4string(temp.val)<-WGS84
coordinates(temp)<-~long+lat
proj4string(temp)<-WGS84
# Read test file
temp.test <- read.csv(file.path(dataFolder, "temperature_test.csv"))
coordinates(temp.test) <- ~long+lat
proj4string(temp.test) <- WGS84
plot(temp, main="All measurements and validation points")
points(temp.val, col="red")
knitr::kable(head(round(as.data.frame(head(temp)),2), caption = "Structure of the temperature data set.", row.names = FALSE))
# Seperate data according to timeFrame and season
temp1970w <-SpatialPointsDataFrame(coords = temp@coords, data = temp@data[,1:2])
temp1970s <-SpatialPointsDataFrame(coords = temp@coords, data = temp@data[,c(1,3)])
temp2010w <-SpatialPointsDataFrame(coords = temp@coords, data = temp@data[,c(1,4)])
temp2010s <-SpatialPointsDataFrame(coords = temp@coords, data = temp@data[,c(1,5)])
col <- c("id", "meansum")
colnames(temp1970s@data) <- col
colnames(temp2010s@data) <- col
colnames(temp1970w@data) <- col
colnames(temp2010w@data) <- col
# Open digital elevation model
DEM <-readGDAL(file.path(dataFolder, "globalDHM.tif"), silent = T)
# Set up grid, for prediction
grid <- spsample(DEM,type="regular",100)
# Downsize
DEM <- raster(DEM)
#DEM <- aggregate(DEM, fact=5.5)
DEM <- aggregate(DEM, fact=16)
# Extract all only land
landDEM <- DEM
landDEM[landDEM<0] <- 0
grid <- SpatialPointsDataFrame(grid@coords,data.frame(elevation=extract(landDEM,grid)))
# Assign elevation to grid for prediction
grid <- SpatialPointsDataFrame(grid@coords,data.frame(elevation=extract(landDEM,grid)))
# Load coastlines for plotting
oceans <- readOGR(dsn="data", "ne_110m_ocean", verbose=F)
# Plot
p <- levelplot(DEM,
main = "DEM",
maxpixels = maxpixels,
par.settings=rasterTheme(region = dichromat(topo.colors(7))), margin=F,
at=seq(-maxValue(abs(DEM)), maxValue(abs(DEM)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p)
# Save plots
pdf(file.path(figureFolder, "DEM.pdf"), width=10.5, height=7.5)
print(p)
invisible(dev.off())
# Clear plots
remove(p)
# Spatial continuity ------------------------------------------------------
## H-scatterplots and autocovariance
### Winter before 1970
temp.dist<-spDists(temp1970w,longlat = FALSE)
temp.index <-knn.index(temp.dist, k=20, algorithm=c("kd_tree"))
temp.h<-data.frame(sum=temp1970w$meansum ,sumNN1=temp1970w$meansum[temp.index[,1]],sumNN5=temp1970w$meansum[temp.index[,5]],sumNN10=temp1970w$meansum[temp.index[,10]],sumNN20=temp1970w$meansum[temp.index[,20]])
par(mfrow=c(2,2))
plot(temp.h$sum,temp.h$sumNN1,main="h = 1")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN5,main="h = 5")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN10,main="h = 10")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN20,main="h = 20")
abline(1,1, col = "blue")
# Autocoavariance plots
temp.mean<-mean(temp.h$sum, na.rm = TRUE)
temp.sd<-sd(temp.h$sum, na.rm = TRUE)
temp.acov.nn1<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN1-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn5<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN5-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn10<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN10-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn20<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN20-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acorr.nn1<-temp.acov.nn1/temp.sd^2
temp.acorr.nn5<-temp.acov.nn5/temp.sd^2
temp.acorr.nn10<-temp.acov.nn10/temp.sd^2
temp.acorr.nn20<-temp.acov.nn20/temp.sd^2
par(mfrow=c(1,2))
plot(c(1,5,10,20),c(temp.acov.nn1,temp.acov.nn5,temp.acov.nn10,temp.acov.nn20),type="l",main="auto-covariance")
plot(c(1,5,10,20),c(temp.acorr.nn1,temp.acorr.nn5,temp.acorr.nn10,temp.acorr.nn20),type="l",main="auto-correlation")
### Winter after 1990
temp.dist<-spDists(temp2010w,longlat = FALSE)
temp.index <-knn.index(temp.dist, k=20, algorithm=c("kd_tree"))
temp.h<-data.frame(sum=temp2010w$meansum ,sumNN1=temp2010w$meansum[temp.index[,1]],sumNN5=temp2010w$meansum[temp.index[,5]],sumNN10=temp2010w$meansum[temp.index[,10]],sumNN20=temp2010w$meansum[temp.index[,20]])
par(mfrow=c(2,2))
plot(temp.h$sum,temp.h$sumNN1,main="h = 1")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN5,main="h = 5")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN10,main="h = 10")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN20,main="h = 20")
abline(1,1, col = "blue")
# Autocoavariance plots
temp.mean<-mean(temp.h$sum, na.rm = TRUE)
temp.sd<-sd(temp.h$sum, na.rm = TRUE)
temp.acov.nn1<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN1-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn5<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN5-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn10<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN10-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn20<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN20-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acorr.nn1<-temp.acov.nn1/temp.sd^2
temp.acorr.nn5<-temp.acov.nn5/temp.sd^2
temp.acorr.nn10<-temp.acov.nn10/temp.sd^2
temp.acorr.nn20<-temp.acov.nn20/temp.sd^2
par(mfrow=c(1,2))
plot(c(1,5,10,20),c(temp.acov.nn1,temp.acov.nn5,temp.acov.nn10,temp.acov.nn20),type="l",main="auto-covariance")
plot(c(1,5,10,20),c(temp.acorr.nn1,temp.acorr.nn5,temp.acorr.nn10,temp.acorr.nn20),type="l",main="auto-correlation")
### Summer before 1970
temp.dist<-spDists(temp1970s,longlat = FALSE)
temp.index <-knn.index(temp.dist, k=20, algorithm=c("kd_tree"))
temp.h<-data.frame(sum=temp1970s$meansum ,sumNN1=temp1970s$meansum[temp.index[,1]],sumNN5=temp1970s$meansum[temp.index[,5]],sumNN10=temp1970s$meansum[temp.index[,10]],sumNN20=temp1970s$meansum[temp.index[,20]])
par(mfrow=c(2,2))
plot(temp.h$sum,temp.h$sumNN1,main="h = 1")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN5,main="h = 5")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN10,main="h = 10")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN20,main="h = 20")
abline(1,1, col = "blue")
# Autocovariance plots
temp.mean <- mean(temp.h$sum, na.rm = TRUE)
temp.sd<-sd(temp.h$sum, na.rm = TRUE)
temp.acov.nn1<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN1-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn5<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN5-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn10<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN10-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn20<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN20-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acorr.nn1<-temp.acov.nn1/temp.sd^2
temp.acorr.nn5<-temp.acov.nn5/temp.sd^2
temp.acorr.nn10<-temp.acov.nn10/temp.sd^2
temp.acorr.nn20<-temp.acov.nn20/temp.sd^2
par(mfrow=c(1,2))
plot(c(1,5,10,20),c(temp.acov.nn1,temp.acov.nn5,temp.acov.nn10,temp.acov.nn20),type="l",main="auto-covariance")
plot(c(1,5,10,20),c(temp.acorr.nn1,temp.acorr.nn5,temp.acorr.nn10,temp.acorr.nn20),type="l",main="auto-correlation")
### Summer after 1990
temp.dist<-spDists(temp2010s,longlat = FALSE)
temp.index <-knn.index(temp.dist, k=20, algorithm=c("kd_tree"))
temp.h<-data.frame(sum=temp2010s$meansum ,sumNN1=temp2010s$meansum[temp.index[,1]],sumNN5=temp2010s$meansum[temp.index[,5]],sumNN10=temp2010s$meansum[temp.index[,10]],sumNN20=temp2010s$meansum[temp.index[,20]])
par(mfrow=c(2,2))
plot(temp.h$sum,temp.h$sumNN1,main="h = 1")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN5,main="h = 5")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN10,main="h = 10")
abline(1,1, col = "blue")
plot(temp.h$sum,temp.h$sumNN20,main="h = 20")
abline(1,1, col = "blue")
# Autocoavariance plots
temp.mean<-mean(temp.h$sum, na.rm = TRUE)
temp.sd<-sd(temp.h$sum, na.rm = TRUE)
temp.acov.nn1<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN1-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn5<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN5-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn10<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN10-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acov.nn20<-sum((temp.h$sum-temp.mean)*(temp.h$sumNN20-temp.mean), na.rm = TRUE)/nrow(temp.h)
temp.acorr.nn1<-temp.acov.nn1/temp.sd^2
temp.acorr.nn5<-temp.acov.nn5/temp.sd^2
temp.acorr.nn10<-temp.acov.nn10/temp.sd^2
temp.acorr.nn20<-temp.acov.nn20/temp.sd^2
par(mfrow=c(1,2))
plot(c(1,5,10,20),c(temp.acov.nn1,temp.acov.nn5,temp.acov.nn10,temp.acov.nn20),type="l",main="auto-covariance")
plot(c(1,5,10,20),c(temp.acorr.nn1,temp.acorr.nn5,temp.acorr.nn10,temp.acorr.nn20),type="l",main="auto-correlation")
# Empirical Variogram -----------------------------------------------------
### Winter before 1970
temp1970w.var1<-variogram(meansum~1,temp1970w,cutoff=1000,width=1)
temp1970w.var5<-variogram(meansum~1,temp1970w,cutoff=150,width=5)
temp1970w.var10<-variogram(meansum~1,temp1970w,cutoff=150,width=10)
temp1970w.var15<-variogram(meansum~1,temp1970w,cutoff=150,width=15)
grid.arrange(plot(temp1970w.var1, main="Bin width 1km"),
plot(temp1970w.var5, main="Bin width 5km"), ncol = 2)
grid.arrange(plot(temp1970w.var10, main="Bin width 10km"),
plot(temp1970w.var15, main="Bin width 15km"), ncol = 2)
bws<-data.frame(np=temp1970w.var1$np,bw=rep("1km",length(temp1970w.var1$np)))
bws<-rbind(bws,data.frame(np=temp1970w.var5$np,bw=rep("5km",length(temp1970w.var5$np))))
bws<-rbind(bws,data.frame(np=temp1970w.var10$np,bw=rep("10km",length(temp1970w.var10$np))))
bws<-rbind(bws,data.frame(np=temp1970w.var15$np,bw=rep("15km",length(temp1970w.var15$np))))
#plotting the numbers of points per bin and bandwidth as a boxplot
ggplot(bws, aes(x=bw, y=np, color=bw)) +
geom_boxplot()
### Winter after 1990
temp2010w.var1<-variogram(meansum~1,temp2010w,cutoff=1000,width=1)
temp2010w.var5<-variogram(meansum~1,temp2010w,cutoff=150,width=5)
temp2010w.var10<-variogram(meansum~1,temp2010w,cutoff=150,width=10)
temp2010w.var15<-variogram(meansum~1,temp2010w,cutoff=150,width=15)
grid.arrange(plot(temp2010w.var1, main="Bin width 1km"),
plot(temp2010w.var5, main="Bin width 5km"), ncol = 2)
grid.arrange(plot(temp2010w.var10, main="Bin width 10km"),
plot(temp2010w.var15, main="Bin width 15km"), ncol = 2)
bws<-data.frame(np=temp2010w.var1$np,bw=rep("1km",length(temp2010w.var1$np)))
bws<-rbind(bws,data.frame(np=temp2010w.var5$np,bw=rep("5km",length(temp2010w.var5$np))))
bws<-rbind(bws,data.frame(np=temp2010w.var10$np,bw=rep("10km",length(temp2010w.var10$np))))
bws<-rbind(bws,data.frame(np=temp2010w.var15$np,bw=rep("15km",length(temp2010w.var15$np))))
#plotting the numbers of points per bin and bandwidth as a boxplot
ggplot(bws, aes(x=bw, y=np, color=bw)) +
geom_boxplot()
### Summer before 1970
temp1970s.var1<-variogram(meansum~1,temp1970s,cutoff=1000,width=1)
temp1970s.var5<-variogram(meansum~1,temp1970s,cutoff=150,width=5)
temp1970s.var10<-variogram(meansum~1,temp1970s,cutoff=150,width=10)
temp1970s.var15<-variogram(meansum~1,temp1970s,cutoff=150,width=15)
grid.arrange(plot(temp1970s.var1, main="Bin width 1km"),
plot(temp1970s.var5, main="Bin width 5km"), ncol = 2)
grid.arrange(plot(temp1970s.var10, main="Bin width 10km"),
plot(temp1970s.var15, main="Bin width 15km"), ncol = 2)
bws<-data.frame(np=temp1970s.var1$np,bw=rep("1km",length(temp1970s.var1$np)))
bws<-rbind(bws,data.frame(np=temp1970s.var5$np,bw=rep("5km",length(temp1970s.var5$np))))
bws<-rbind(bws,data.frame(np=temp1970s.var10$np,bw=rep("10km",length(temp1970s.var10$np))))
bws<-rbind(bws,data.frame(np=temp1970s.var15$np,bw=rep("15km",length(temp1970s.var15$np))))
#plotting the numbers of points per bin and bandwidth as a boxplot
ggplot(bws, aes(x=bw, y=np, color=bw)) +
geom_boxplot()
### Summer after 1990
temp2010s.var1<-variogram(meansum~1,temp2010s,cutoff=1000,width=1)
temp2010s.var5<-variogram(meansum~1,temp2010s,cutoff=150,width=5)
temp2010s.var10<-variogram(meansum~1,temp2010s,cutoff=150,width=10)
temp2010s.var15<-variogram(meansum~1,temp2010s,cutoff=150,width=15)
grid.arrange(plot(temp2010s.var1, main="Bin width 1km"),
plot(temp2010s.var5, main="Bin width 5km"), ncol = 2)
grid.arrange(plot(temp2010s.var10, main="Bin width 10km"),
plot(temp2010s.var15, main="Bin width 15km"), ncol = 2)
bws<-data.frame(np=temp2010s.var1$np,bw=rep("1km",length(temp2010s.var1$np)))
bws<-rbind(bws,data.frame(np=temp2010s.var5$np,bw=rep("5km",length(temp2010s.var5$np))))
bws<-rbind(bws,data.frame(np=temp2010s.var10$np,bw=rep("10km",length(temp2010s.var10$np))))
bws<-rbind(bws,data.frame(np=temp2010s.var15$np,bw=rep("15km",length(temp2010s.var15$np))))
#plotting the numbers of points per bin and bandwidth as a boxplot
ggplot(bws, aes(x=bw, y=np, color=bw)) +
geom_boxplot()
## Fitted Semivariogram
### Winter before 1970
temp1970w.var10<-variogram(meansum~1,temp1970w,cutoff=150,width=10)
models <- c("Exp", "Sph", "Gau", "Mat")
temp1970w.var10.fits <- lapply(X=1:4, FUN=function(x) fit.variogram(temp1970w.var10, model=vgm(models[x])))
grid.arrange(plot(temp1970w.var10, model=temp1970w.var10.fits[[1]], main = "Exponential: 10km"),
plot(temp1970w.var10, model=temp1970w.var10.fits[[2]], main = "Spherical: 10km"), ncol = 2)
grid.arrange(plot(temp1970w.var10, model=temp1970w.var10.fits[[3]], main = "Gaussian: 10km"),
plot(temp1970w.var10, model=temp1970w.var10.fits[[4]], main = "Mat: 10km"), ncol = 2)
### Winter after 1990
temp2010w.var10<-variogram(meansum~1,temp2010w,cutoff=150,width=10)
models <- c("Exp", "Sph", "Gau", "Mat")
temp2010w.var10.fits <- lapply(X=1:4, FUN=function(x) fit.variogram(temp2010w.var10, model=vgm(models[x])))
grid.arrange(plot(temp2010w.var10, model=temp2010w.var10.fits[[1]], main = "Exponential: 10km"),
plot(temp2010w.var10, model=temp2010w.var10.fits[[2]], main = "Spherical: 10km"), ncol = 2)
grid.arrange(plot(temp2010w.var10, model=temp2010w.var10.fits[[3]], main = "Gaussian: 10km"),
plot(temp2010w.var10, model=temp2010w.var10.fits[[4]], main = "Mat: 10km"), ncol = 2)
### Summer before 1970
temp1970s.var10<-variogram(meansum~1,temp1970s,cutoff=150,width=10)
models <- c("Exp", "Sph", "Gau", "Mat")
temp1970s.var10.fits <- lapply(X=1:4, FUN=function(x) fit.variogram(temp1970s.var10, model=vgm(models[x])))
grid.arrange(plot(temp1970s.var10, model=temp1970s.var10.fits[[1]], main = "Exponential: 10km"),
plot(temp1970s.var10, model=temp1970s.var10.fits[[2]], main = "Spherical: 10km"), ncol = 2)
grid.arrange(plot(temp1970s.var10, model=temp1970s.var10.fits[[3]], main = "Gaussian: 10km"),
plot(temp1970s.var10, model=temp1970s.var10.fits[[4]], main = "Mat: 10km"), ncol = 2)
### Summer after 1990
temp2010s.var10<-variogram(meansum~1,temp2010s,cutoff=150,width=10)
models <- c("Exp", "Sph", "Gau", "Mat")
temp2010s.var10.fits <- lapply(X=1:4, FUN=function(x) fit.variogram(temp2010s.var10, model=vgm(models[x])))
grid.arrange(plot(temp2010s.var10, model=temp2010s.var10.fits[[1]], main = "Exponential: 10km"),
plot(temp2010s.var10, model=temp2010s.var10.fits[[2]], main = "Spherical: 10km"), ncol = 2)
grid.arrange(plot(temp2010s.var10, model=temp2010s.var10.fits[[3]], main = "Gaussian: 10km"),
plot(temp2010s.var10, model=temp2010s.var10.fits[[4]], main = "Mat: 10km"), ncol = 2)
# Universal Kriging -------------------------------------------------------
## Continentality
# Load highres coastlines for distance layer
oceans.50m <- readOGR(dsn="data", "ne_50m_ocean", verbose=F)
# Simplify geometry
oceans.simply <-SpatialPolygonsDataFrame(
gSimplify(oceans.50m, tol=1, topologyPreserve=TRUE),
data=oceans.50m@data)
# Build blank raster
r <- DEM
r <- setValues(r, 0)
#r <- aggregate(r, fact=10)
# Make values NA where polygon intesects raster
r <- mask(r, oceans.simply)
# Run distance check
ocean.dist <- distance(r)
# # to restrict your search
# searchLimit <- 100 # the maximum distance in raster units from lakes/boundaries
# oceans.simply.buff <- gBuffer(oceans.simply, width = searchLimit, byid = T)
# rB <- crop(r, extent(oceans.simply.buff))
#
# # much faster...
# rDB <- distance(rB)
# Plot
p <- levelplot(ocean.dist,
main = "Continentality",
maxpixels = maxpixels,
par.settings=YlOrRdTheme(), margin=F,
at=seq(0, max(abs(cellStats(ocean.dist, range))), len=100)) +
layer(sp.polygons(oceans, fill='black', alpha=1))
print(p)
# Save plot
pdf(file.path(figureFolder, "Continentality.pdf"), width=10.5, height=7.5)
print(p)
invisible(dev.off())
# Remove plot
remove(p)
## Surface gradient (North-South)
# Create latitude and longitude layers
lat <- DEM
lat[] <- coordinates(DEM)[, 2]
# Slope and aspect
slope <- terrain(landDEM, opt='slope', unit='radians')
aspect <- terrain(landDEM, opt='aspect', unit='radians')
# Winter
aPer <- (180/2+23)/180
split.hemi.w <- setValues(lat, 1)
split.hemi.w[1:floor((nrow(lat)*aPer)), 1:ncol(lat)] <- -1
# Summer
aPer <- (180/2-23)/180
split.hemi.s <- setValues(lat, 1)
split.hemi.s[1:floor((nrow(lat)*aPer)), 1:ncol(lat)] <- -1
# Calculate the gradient in latitude direction
latGrad <- (cos(aspect)*slope)*180/pi
latGrad.w <- latGrad*split.hemi.w
latGrad.s <- latGrad*split.hemi.s
# Plot
p1 <- levelplot(latGrad.w,
main = "North-South gradient, +23.5° hemisphere corrected",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(latGrad.w)), maxValue(abs(latGrad.w)), len=100)) +
layer(sp.polygons(oceans, fill='transparent', alpha=1))
print(p1)
p2 <- levelplot(latGrad.s,
main = "North-South gradient, -23.5° hemisphere corrected",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(latGrad.s)), maxValue(abs(latGrad.s)), len=100)) +
layer(sp.polygons(oceans, fill='transparent', alpha=1))
print(p1)
# Save plots
pdf(file.path(figureFolder, "gradient_WiHemiCorr.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "gradient_SuHemiCorr.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
# Clear plots
remove(p1, p2)
## Sun inclination angle
## Solar inclination angle (height at midday)
# http://www.geoastro.de/astro/mittag/index.htm; h = 90° - β + δ
# Substract ghradient northern hemisphere and add to the southern
# 21.6 - "Summer"; +23.5°
h.w <- (90-abs(lat + 23.5)+latGrad.w)
h.s <- (90-abs(lat - 23.5)+latGrad.s)
# Plot
p1 <- levelplot(h.w,
main = "Inclination angle sun, winter",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(h.w)), maxValue(abs(h.w)), len=100)) +
layer(sp.polygons(oceans, fill='blue', alpha=0.1))
print(p1)
p2 <- levelplot(h.s,
main = "Inclination angle sun, summer",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(h.w)), maxValue(abs(h.w)), len=100)) +
layer(sp.polygons(oceans, fill='blue', alpha=0.1))
print(p2)
# Save plots
pdf(file.path(figureFolder, "inclination_winter.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "inclination_summer.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
## Atmospheric distance
# Create distance layer
lat.w.rad <- abs(lat + 23.5)*pi/180
atmo.dist.w <- 1-cos(lat.w.rad)
lat.s.rad <- abs(lat - 23.5)*pi/180
atmo.dist.s <- 1-cos(lat.s.rad)
# Plot
p1 <- levelplot(atmo.dist.w,
main = "Atmospheric distance, winter",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=T,
at=seq(-maxValue(abs(atmo.dist.w)), maxValue(abs(atmo.dist.w)), len=100)) +
layer(sp.polygons(oceans, fill='blue', alpha=0.1))
suppressWarnings(print(p1))
p2 <- levelplot(atmo.dist.s,
main = "Atmospheric distance, summer",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=T,
at=seq(-maxValue(abs(atmo.dist.s)), maxValue(abs(atmo.dist.s)), len=100)) +
layer(sp.polygons(oceans, fill='blue', alpha=0.1))
suppressWarnings(print(p2))
# Save plots
pdf(file.path(figureFolder, "atmoDist_winter.pdf"), width=10.5, height=7.5)
suppressWarnings(print(p1))
invisible(dev.off())
pdf(file.path(figureFolder, "atmoDist_summer.pdf"), width=10.5, height=7.5)
suppressWarnings(print(p2))
invisible(dev.off())
remove(p1, p2)
## Interpolation
# Set up grid, for prediction
remove(grid)
#grid <- rasterToPoints(aggregate(landDEM, fact=30))
grid <- rasterToPoints(landDEM)
grid <- grid[,1:2]
grid <- SpatialPointsDataFrame(grid,data.frame(elev=extract(landDEM,grid)))
grid$cont <- extract(ocean.dist, grid)
grid$hsun <- extract(h.w, grid)
grid$dist <- extract(atmo.dist.w, grid)
# Define RMSE function
RMSE <- function(x,y){
tmp <- (x-y)^2
sqrt(mean(tmp))
}
### Winter before 1970
# Extract continentality and elevation at measurement points from rasters
temp1970w$elev <- extract(landDEM, temp1970w)
temp1970w$elev[is.na(temp1970w$elev)] <- 0
temp1970w$cont <- extract(ocean.dist, temp1970w)
temp1970w$cont[is.na(temp1970w$cont)] <- 0
temp1970w$hsun <- extract(h.w, temp1970w)
temp1970w$hsun[is.na(temp1970w$hsun)] <- 0
temp1970w$dist <- extract(atmo.dist.w, temp1970w)
temp1970w$dist[is.na(temp1970w$dist)] <- 0
# Linear Regression
temp1970w.lm.test <- lm(meansum~elev+cont+hsun+dist, data=temp1970w@data)
summary(temp1970w.lm.test)
# Distribution of residuals
temp1970w@data[names(temp1970w.lm.test$residuals),"lmRes"]<-temp1970w.lm.test$residuals
temp1970w@data$lmRes[is.na(temp1970w@data$lmRes)] <- 0
temp1970w$lmResRel<-temp1970w$lmRes/temp1970w$meansum
# Plot results
bubble(temp1970w,"lmRes",main="Residual Values", na.rm=T)
bubble(temp1970w,"lmResRel",main="Relative Residual Values", na.rm=T)
# plot(variogram(lmRes~1,temp1970w,width=10,cutoff=200),main="Residual Variogram")
# Compute distance matrix
temp1970w.d <- as.matrix(dist(cbind(temp1970w@coords[,1], temp1970w@coords[,2])), method = "euclidean", alternative = "greater")
# Inverse distance matrix
temp1970w.d.inv <- 1 / temp1970w.d
# Setting diagonal to 0
diag(temp1970w.d.inv) <- 0
# Print Moran's I
temp.moran <- Moran.I(temp1970w$lmRes, temp1970w.d.inv)
paste("Observed autocorrelation: ",temp.moran$observed)
paste("P-value of H0 (residuals are randomly distributed): ",temp.moran$p.value)
# Universal Kriging
temp1970w.best.m.index <- 3 # Gaussian model
temp1970w.uok <- krige(meansum~elev+cont+hsun+dist,
temp1970w, grid,
model = temp1970w.var10.fits[[temp1970w.best.m.index]])
# Create grid
gridded(temp1970w.uok)<-TRUE
temp1970w.uok.pred<-raster(temp1970w.uok, layer=1, values=TRUE)
temp1970w.uok.var<-raster(temp1970w.uok, layer=2, values=TRUE)
# Extract and append to test data
# "meanWi_before1970" "meanSu_before1970" "meanWi_after1990" "meanSu_after1990"
temp.test$meanWi_before1970 <- extract(temp1970w.uok.pred, temp.test)
# Calculate RMSE of map
temp.val$meanWi_before1970_pred <- extract(temp1970w.uok.pred, temp.val)
paste("Observed RMSE (5% validation data): ", round(RMSE(temp.val$meanWi_before1970, temp.val$meanWi_before1970_pred),2),"°C", sep="")
# Plot
p1 <- levelplot(temp1970w.uok.pred,
main = "Prediction: Winter before 1970",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(temp1970w.uok.pred)), maxValue(abs(temp1970w.uok.pred)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p1)
p2 <- levelplot(temp1970w.uok.var,
main = "Uncertainty: Winter before 1970",
maxpixels = maxpixels,
par.settings=YlOrRdTheme(), margin=F,
at=seq(0, maxValue(abs(temp1970w.uok.var)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p2)
# Save plots
pdf(file.path(figureFolder, "temp1970w_pred.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "temp1970w_var.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
# Clear plots
remove(p1, p2)
# Save raster
writeRaster(temp1970w.uok.pred, file.path(resultsFolder, "temp1970w_pred"), format = "GTiff", overwrite=TRUE)
writeRaster(temp1970w.uok.var, file.path(resultsFolder, "temp1970w_var"), format = "GTiff", overwrite=TRUE)
### Winter after 1990
# Extract continentality and elevation at measurement points from rasters
temp2010w$elev <- extract(landDEM, temp2010w)
temp2010w$elev[is.na(temp2010w$elev)] <- 0
temp2010w$cont <- extract(ocean.dist, temp2010w)
temp2010w$cont[is.na(temp2010w$cont)] <- 0
temp2010w$hsun <- extract(h.w, temp2010w)
temp2010w$hsun[is.na(temp2010w$hsun)] <- 0
temp2010w$dist <- extract(atmo.dist.w, temp2010w)
temp2010w$dist[is.na(temp2010w$dist)] <- 0
# Linear Regression
temp2010w.lm.test <- lm(meansum~elev+cont+hsun+dist, data=temp2010w@data)
summary(temp2010w.lm.test)
# Distribution of residuals
temp2010w@data[names(temp2010w.lm.test$residuals),"lmRes"]<-temp2010w.lm.test$residuals
temp2010w@data$lmRes[is.na(temp2010w@data$lmRes)] <- 0
temp2010w$lmResRel<-temp2010w$lmRes/temp2010w$meansum
# Remove outlier
temp2010w$lmResRel[which.max(temp2010w$lmResRel)] <- mean(temp2010w$lmResRel)
temp2010w$lmResRel[which.max(temp2010w$lmResRel)] <- mean(temp2010w$lmResRel)
temp2010w$lmResRel[which.max(temp2010w$lmResRel)] <- mean(temp2010w$lmResRel)
temp2010w$lmResRel[which.max(temp2010w$lmResRel)] <- mean(temp2010w$lmResRel)
temp2010w$lmResRel[which.max(temp2010w$lmResRel)] <- mean(temp2010w$lmResRel)
# Plot results
bubble(temp2010w,"lmRes",main="Residual Values", na.rm=T)
bubble(temp2010w,"lmResRel",main="Relative Residual Values", na.rm=T)
# Compute distance matrix
temp2010w.d <- as.matrix(dist(cbind(temp2010w@coords[,1], temp2010w@coords[,2])), method = "euclidean", alternative = "greater")
# Inverse distance matrix
temp2010w.d.inv <- 1 / temp2010w.d
# Setting diagonal to 0
diag(temp2010w.d.inv) <- 0
# Print Moran's I
temp.moran <- Moran.I(temp2010w$lmRes, temp2010w.d.inv)
paste("Observed autocorrelation: ",temp.moran$observed)
paste("P-value of H0 (residuals are randomly distributed): ",temp.moran$p.value)
# Universal Kriging
temp2010w.best.m.index <- 3 # Gaussian model
temp2010w.uok <- krige(meansum~elev+cont+hsun+dist,
temp2010w, grid,
model = temp2010w.var10.fits[[temp2010w.best.m.index]])
# Create grid
gridded(temp2010w.uok)<-TRUE
temp2010w.uok.pred<-raster(temp2010w.uok, layer=1, values=TRUE)
temp2010w.uok.var<-raster(temp2010w.uok, layer=2, values=TRUE)
# Extract and append to test data
# "meanWi_before1970" "meanSu_before1970" "meanWi_after1990" "meanSu_after1990"
temp.test$meanWi_after1990 <- extract(temp2010w.uok.pred, temp.test)
# Calculate RMSE of map
temp.val$meanWi_after1990_pred <- extract(temp2010w.uok.pred, temp.val)
paste("Observed RMSE (5% validation data): ", round(RMSE(temp.val$meanWi_after1990, temp.val$meanWi_after1990_pred),2),"°C", sep="")
# Plot
p1 <- levelplot(temp2010w.uok.pred,
main = "Prediction: Winter after 1990",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(temp2010w.uok.pred)), maxValue(abs(temp2010w.uok.pred)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p1)
p2 <- levelplot(temp2010w.uok.var,
main = "Uncertainty: Winter after 1990",
maxpixels = maxpixels,
par.settings=YlOrRdTheme(), margin=F,
at=seq(0, maxValue(abs(temp2010w.uok.var)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p2)
# Save plots
pdf(file.path(figureFolder, "temp2010w_pred.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "temp2010w_var.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
# Clear plots
remove(p1, p2)
# Save raster
writeRaster(temp2010w.uok.pred, file.path(resultsFolder, "temp2010w_pred"), format = "GTiff", overwrite=TRUE)
writeRaster(temp2010w.uok.var, file.path(resultsFolder, "temp2010w_var"), format = "GTiff", overwrite=TRUE)
### Summer before 1970
# !!! Adjust grid for summer
grid$hsun <- extract(h.s, grid)
grid$dist <- extract(atmo.dist.s, grid)
# Extract continentality and elevation at measurement points from rasters
temp1970s$elev <- extract(landDEM, temp1970s)
temp1970s$elev[is.na(temp1970s$elev)] <- 0
temp1970s$cont <- extract(ocean.dist, temp1970s)
temp1970s$cont[is.na(temp1970s$cont)] <- 0
temp1970s$hsun <- extract(h.s, temp1970s)
temp1970s$hsun[is.na(temp1970s$hsun)] <- 0
temp1970s$dist <- extract(atmo.dist.s, temp1970s)
temp1970s$dist[is.na(temp1970s$dist)] <- 0
# Linear Regression
temp1970s.lm.test <- lm(meansum~elev+cont+hsun+dist, data=temp1970s@data)
summary(temp1970s.lm.test)
# Distribution of residuals
temp1970s@data[names(temp1970s.lm.test$residuals),"lmRes"]<-temp1970s.lm.test$residuals
temp1970s@data$lmRes[is.na(temp1970s@data$lmRes)] <- 0
temp1970s$lmResRel<-temp1970s$lmRes/temp1970s$meansum
# Plot results
bubble(temp1970s,"lmRes",main="Residual Values", na.rm=T)
bubble(temp1970s,"lmResRel",main="Relative Residual Values", na.rm=T)
# plot(variogram(lmRes~1,temp1970s,width=10,cutoff=200),main="Residual Variogram")
# Compute distance matrix
temp1970s.d <- as.matrix(dist(cbind(temp1970s@coords[,1], temp1970s@coords[,2])), method = "euclidean", alternative = "greater")
# Inverse distance matrix
temp1970s.d.inv <- 1 / temp1970s.d
# Setting diagonal to 0
diag(temp1970s.d.inv) <- 0
# Print Moran's I
temp.moran <- Moran.I(temp1970s$lmRes, temp1970s.d.inv)
paste("Observed autocorrelation: ",temp.moran$observed)
paste("P-value of H0 (residuals are randomly distributed): ",temp.moran$p.value)
# Universal Kriging
temp1970s.best.m.index <- 3 # Gaussian model
temp1970s.uok <- krige(meansum~elev+cont+hsun+dist,
temp1970s, grid,
model = temp1970s.var10.fits[[temp1970s.best.m.index]])
# Create grid
gridded(temp1970s.uok)<-TRUE
temp1970s.uok.pred<-raster(temp1970s.uok, layer=1, values=TRUE)
temp1970s.uok.var<-raster(temp1970s.uok, layer=2, values=TRUE)
# Extract and append to test data
# "meanWi_before1970" "meanSu_before1970" "meanWi_after1990" "meanSu_after1990"
temp.test$meanSu_before1970 <- extract(temp1970s.uok.pred, temp.test)
# Calculate RMSE of map
temp.val$meanSu_before1970_pred <- extract(temp1970s.uok.pred, temp.val)
paste("Observed RMSE (5% validation data): ", round(RMSE(temp.val$meanSu_before1970, temp.val$meanSu_before1970_pred),2),"°C", sep="")
# Plot
p1 <- levelplot(temp1970s.uok.pred,
main = "Prediction: Summer before 1970",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(temp1970s.uok.pred)), maxValue(abs(temp1970s.uok.pred)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p1)
p2 <- levelplot(temp1970s.uok.var,
main = "Uncertainty: Summer before 1970",
maxpixels = maxpixels,
par.settings=YlOrRdTheme(), margin=F,
at=seq(0, maxValue(abs(temp1970s.uok.var)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p2)
# Save plots
pdf(file.path(figureFolder, "temp1970s_pred.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "temp1970s_var.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
# Clear plots
remove(p1, p2)
# Save raster
writeRaster(temp1970s.uok.pred, file.path(resultsFolder, "temp1970s_pred"), format = "GTiff", overwrite=TRUE)
writeRaster(temp1970s.uok.var, file.path(resultsFolder, "temp1970s_var"), format = "GTiff", overwrite=TRUE)
### Summer after 1990
# Extract continentality and elevation at measurement points from rasters
temp2010s$elev <- extract(landDEM, temp2010s)
temp2010s$elev[is.na(temp2010s$elev)] <- 0
temp2010s$cont <- extract(ocean.dist, temp2010s)
temp2010s$cont[is.na(temp2010s$cont)] <- 0
temp2010s$hsun <- extract(h.s, temp2010s)
temp2010s$hsun[is.na(temp2010s$hsun)] <- 0
temp2010s$dist <- extract(atmo.dist.s, temp2010s)
temp2010s$dist[is.na(temp2010s$dist)] <- 0
# Linear Regression
temp2010s.lm.test <- lm(meansum~elev+cont+hsun+dist, data=temp2010s@data)
summary(temp2010s.lm.test)
# Distribution of residuals
temp2010s@data[names(temp2010s.lm.test$residuals),"lmRes"]<-temp2010s.lm.test$residuals
temp2010s@data$lmRes[is.na(temp2010s@data$lmRes)] <- 0
temp2010s$lmResRel<-temp2010s$lmRes/temp2010s$meansum
# Plot results
bubble(temp2010s,"lmRes",main="Residual Values", na.rm=T)
bubble(temp2010s,"lmResRel",main="Relative Residual Values", na.rm=T)
# plot(variogram(lmRes~1,temp2010s,width=10,cutoff=200),main="Residual Variogram")
# Compute distance matrix
temp2010s.d <- as.matrix(dist(cbind(temp2010s@coords[,1], temp2010s@coords[,2])), method = "euclidean", alternative = "greater")
# Inverse distance matrix
temp2010s.d.inv <- 1 / temp2010s.d
# Setting diagonal to 0
diag(temp2010s.d.inv) <- 0
# Print Moran's I
temp.moran <- Moran.I(temp2010s$lmRes, temp2010s.d.inv)
paste("Observed autocorrelation: ",temp.moran$observed)
paste("P-value of H0 (residuals are randomly distributed): ",temp.moran$p.value)
# Universal Kriging
temp2010s.best.m.index <- 3 # Gaussian model
temp2010s.uok <- krige(meansum~elev+cont+hsun+dist,
temp2010s, grid,
model = temp2010s.var10.fits[[temp2010s.best.m.index]])
# Create grid
gridded(temp2010s.uok)<-TRUE
temp2010s.uok.pred<-raster(temp2010s.uok, layer=1, values=TRUE)
temp2010s.uok.var<-raster(temp2010s.uok, layer=2, values=TRUE)
# Extract and append to test data
# "meanWi_before1970" "meanSu_before1970" "meanWi_after1990" "meanSu_after1990"
temp.test$meanSu_after1990 <- extract(temp2010s.uok.pred, temp.test)
# Calculate RMSE of map
temp.val$meanSu_after1990_pred <- extract(temp2010s.uok.pred, temp.val)
paste("Observed RMSE (5% validation data): ", round(RMSE(temp.val$meanSu_after1990, temp.val$meanSu_after1990_pred),2),"°C", sep="")
# Plot
p1 <- levelplot(temp2010s.uok.pred,
main = "Prediction: Summer after 1990",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(temp2010s.uok.pred)), maxValue(abs(temp2010s.uok.pred)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p1)
p2 <- levelplot(temp2010s.uok.var,
main = "Uncertainty: Summer after 1990",
maxpixels = maxpixels,
par.settings=YlOrRdTheme(), margin=F,
at=seq(0, maxValue(abs(temp2010s.uok.var)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p2)
# Save plots
pdf(file.path(figureFolder, "temp2010s_pred.pdf"), width=10.5, height=7.5)
print(p1)
invisible(dev.off())
pdf(file.path(figureFolder, "temp2010s_var.pdf"), width=10.5, height=7.5)
print(p2)
invisible(dev.off())
# Clear plots
remove(p1, p2)
# Save raster
writeRaster(temp2010s.uok.pred, file.path(resultsFolder, "temp2010s_pred"), format = "GTiff", overwrite=TRUE)
writeRaster(temp2010s.uok.var, file.path(resultsFolder, "temp2010s_var"), format = "GTiff", overwrite=TRUE)
# Save temperature_test_pred.csv
write.csv(temp.test, file = file.path(resultsFolder, "temperature_test_pred"), row.names = FALSE)
# Difference images
## Winter
diff.w <- temp2010w.uok.pred-temp1970w.uok.pred
# Plot
p <- levelplot(diff.w,
main = "Temperature change: Winter",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(diff.w)), maxValue(abs(diff.w)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p)
# Save plots
pdf(file.path(figureFolder, "diff_winter.pdf"), width=10.5, height=7.5)
print(p)
invisible(dev.off())
# Clear plots
remove(p)
# Save raster
writeRaster(diff.w, file.path(resultsFolder, "diff_winter"), format = "GTiff", overwrite=TRUE)
## Summer
diff.s <- temp2010s.uok.pred-temp1970s.uok.pred
# Plot
p <- levelplot(diff.s,
main = "Temperature change: Summer",
maxpixels = maxpixels,
par.settings=BuRdTheme(), margin=F,
at=seq(-maxValue(abs(diff.s)), maxValue(abs(diff.s)), len=100)) +
layer(sp.polygons(oceans, fill='transparent'))
print(p)
# Save plots
pdf(file.path(figureFolder, "diff_summer.pdf"), width=10.5, height=7.5)
print(p)
invisible(dev.off())
# Clear plots
remove(p)
# Save raster
writeRaster(diff.s, file.path(resultsFolder, "diff_summer"), format = "GTiff", overwrite=TRUE)
<file_sep>/README.md
# Change detection in global temperature
Global surface temperature layers are interpolated for two time intervals (1950-1970 & 1990-2010) based on a point measurement data set of the worldwide surface temperature that has been recorded since 1950. For the spatial interpolation, an universal Kriging approach is applied with additional layers for the continentality, the atmospheric distance, the North-South topographic gradient and the sun inclination angle of every pixel. Finally two (summer & winter) difference images are created from the interpolated temperature layers to represent the change in temperature.
## Installation
1. Install R & RStudio
2. Get the needed libraries: `install.packages('library-name')`
3. Clone the repository, by creating a new git project in RStudio
## Data
* Global digital elevation model - [swisstopo](https://www.swisstopo.admin.ch/en/home.html)
* Global temperature measurements
## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D
## Authors
* **<NAME>** - *Development and implementation* - [munterfinger](https://github.com/munterfinger)
* **<NAME>** - *Development and implementation*
## Built With
* [R](https://www.r-project.org) - The R Project for Statistical Computing
* [RStudio](https://www.rstudio.com) - Open source and enterprise-ready professional software for R
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
## References
<NAME>., <NAME>., <NAME>., & <NAME>., 2010. Global surface temperature change. Review of Geophysics, 48, pp.1–29.
<NAME>., <NAME>., <NAME>, <NAME>., <NAME>., <NAME>., & <NAME>. (2008). A European daily high-resolution gridded data set of surface temperature and precipitation for 1950–2006. Journal of Geophysical Research, pp.1–12.
IPCC, 2013. Summary fo Policymakers. Climate Change 2013: The Physical Science Basis.Contribution of Working Group I to the Fifth Assessment Report of the Intergovernmental Panel on Climate Change, pp.1–28.
<NAME>. (2004). Multivariable geostatistics in S: The gstat package. Computers and Geosciences, 30(7), pp.683–691.
|
733c4380db4451c86f89a1b13292d87c5c99d453
|
[
"Markdown",
"R"
] | 2
|
R
|
munterfinger/global-temperature-change-detection
|
cfe673859518229b6a5ec36684300b95a484b288
|
59813630a5cc43632c4429e01a8589c04efb8d2c
|
refs/heads/main
|
<repo_name>kushagra25sharma/meet-up<file_sep>/src/firebase.js
import firebase from "firebase";
// import auth from "firebase/auth";
// import "firebase/firestore";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "whatsapp-clone-a5dd9.firebaseapp.com",
projectId: "whatsapp-clone-a5dd9",
storageBucket: "whatsapp-clone-a5dd9.appspot.com",
messagingSenderId: "407551877909",
appId: "1:407551877909:web:ff1d531eb4830c4529bf1c",
measurementId: "G-9MK3DJ9Y3E"
};
const firebaseApp = firebase.initializeApp(firebaseConfig); // passing firebase config to setup our app
const db = firebaseApp.firestore(); // creating firestore instance db
const auth = firebase.auth(); // authentication handler
const provider = new firebase.auth.GoogleAuthProvider(); // for google authentication sign in with google
export { auth, provider };
export default db;<file_sep>/src/Chat/Chat.js
import { useState, useEffect } from "react";
import "./Chat.css";
import { Avatar, IconButton } from "@material-ui/core";
import { MoreVert, SearchOutlined, InsertEmoticon, Mic } from "@material-ui/icons";
// useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.
import { useParams } from "react-router-dom";
import db from "../firebase";
import { useStateValue } from "../StateProvider";
import firebase from "firebase";
import moment from "moment";
import FileUploader from "./FileUploader";
import Picker from "emoji-picker-react";
const Chat = () => {
const [input, setInput] = useState("");
const [seed, setSeed] = useState(0);
const { roomId } = useParams();// this will give us the roomId that we have passsed in the link /rooms/:roomId
const [roomName, setRoomName] = useState("");
const [messages, setMessages] = useState([]);
const { user } = useStateValue()[0];
const [theme, setTheme] = useState(true);
const [show, setShow] = useState(false);
const theme1 = "https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png";
const theme2 = "https://i.redd.it/ts7vuoswhwf41.jpg";
// console.log(roomId);
useEffect(() => {
if (roomId) {
const unsubscribe = db.collection('rooms').doc(roomId).onSnapshot(snapshot => (setRoomName(snapshot.data().name)));
const unsub = db.collection('rooms').doc(roomId).collection("messages").orderBy("timestamp", "asc").onSnapshot((snapshot) => setMessages(snapshot.docs.map((doc) => doc.data())));
return () => {
unsubscribe();
unsub();
}
}
}, [roomId]) // whenever roomId changes we load the messages of that room
useEffect(() => {
setSeed(Math.floor(Math.random() * 5000));
}, [roomId]);
const handleSubmit = (e) => {
e.preventDefault();
if (input.length > 0) {
db.collection("rooms").doc(roomId).collection("messages").add({
message: input,
name: user.displayName.split(' ')[0],
file: "",
// server's time is always going to be same but users' time can pe different according to there location so user in US gets msgs in his time
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
}
setInput("");
setShow(false);
};
const handleTheme = () => {
setTheme(prev => !prev);
}
const handleFile = (uploadedFile) => {
db.collection("rooms").doc(roomId).collection("messages").add({
message: "",
name: user.displayName.split(' ')[0],
file: uploadedFile,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
}
const handleShow = () => {
setShow(prev => !prev);
}
const handleEmojiClick = (e, obj) => {
const str = input + obj.emoji;
setInput(str);
}
return (
<div className="chat">
<div className="chat__header">
<Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`} />
<div className="chat__headerInfo">
<h5>{roomName}</h5>
<p>{messages.length ? `Last message at ${moment(new Date(messages[messages?.length - 1]?.timestamp?.toDate())).format("LT")}` : "New room created"} </p>
</div>
<div className="chat__headerRight">
<IconButton><SearchOutlined /></IconButton>
<FileUploader handleFile={handleFile} />
<div onClick={handleTheme}><IconButton><MoreVert/></IconButton></div>
</div>
</div>
<div className="chat__body" style={{ backgroundImage: theme ? `url(${theme1})` : `url(${theme2})` }}>
{messages.map((message, index) => (
<p key={index} className={`chat__message ${message.name === user?.displayName.split(' ')[0] && "chat__reciever"}`}>
<span style={{ color: theme ? "black" : "orange"}} className="chat__name">{message.name}</span>
{/* {message.file && console.log(message.file)} */}
{message.message.length ? message.message : <img className="chat__image" src={message?.file} alt="couldn't load" />}
<span className="chat__timestamp">{moment(new Date(message?.timestamp?.toDate()).toUTCString()).format("LT")}</span>
</p>
))}
</div>
<div className="chat__footer">
{show && <Picker onEmojiClick={handleEmojiClick} />}
<IconButton onClick={handleShow}><InsertEmoticon /></IconButton>
<form>
<input placeholder="Type a message" type="input" value={input} onChange={(e) => setInput(e.target.value)} />
<button type="submit" onClick={handleSubmit} >Send the message</button>
</form>
<Mic />
</div>
</div>
);
}
export default Chat;
<file_sep>/src/Chat/FileUploader.js
import { useRef } from "react";
import { Button } from "@material-ui/core";
import { AttachFile } from "@material-ui/icons";
// import FileBase from "react-file-base64";
const FileUploader = ({ handleFile }) => {
// Create a reference to the hidden file input element
const hiddenFileInput = useRef(null);
// Programatically click the hidden file input element
// when the Button component is clicked
const handleClick = (event) => {
hiddenFileInput.current.click();
};
// Call a function (passed as a prop from the parent component)
// to handle the user-selected file
const handleChange = async (event) => {
const fileUploaded = event.target.files[0];
const base64File = await convertBase64(fileUploaded);
handleFile(base64File);
};
const convertBase64 = (file) => {
// Promise is a wrapper around a value that may or may not be known when the
// object is instantiated and provides a method for handling the value after
// it is known (resolve) or is unavailable for a failure reason (reject)
// used when the code can take some time to do something
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);// reads data from file
fileReader.onload = () => { // onload is an event handler which is firred when the data is read
resolve(fileReader.result);
}
fileReader.onerror = (error) => {
reject(error);
}
});
}
return (
<>
<Button onClick={handleClick}>
<AttachFile />
{/* <FileBase type="file" multiple={false} onDone={(base64) => handleFile(base64)} /> */}
</Button>
<input type="file" ref={hiddenFileInput} onChange={handleChange} style={{display: 'none'}} />
</>
);
}
export default FileUploader;<file_sep>/src/Sidebar/Sidebar.js
import { useState, useEffect } from "react";
import db from "../firebase";
import "./Sidebar.css"
import ChatIcon from "@material-ui/icons/Chat";
import DonutLargeIcon from "@material-ui/icons/DonutLarge";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import { Avatar, IconButton } from "@material-ui/core";
import { SearchOutlined } from "@material-ui/icons";
import SidebarChat from "./SidebarChat/SidebarChat";
import { useStateValue } from "../StateProvider";
const Sidebar = () => {
const [rooms, setRooms] = useState([]);
const { user } = useStateValue()[0];
const [value, setValue] = useState("");
useEffect(() => {
// onSnapshot takes the snapshot of the document we have added in our database and in real time too whenever our database gets updated it take a snap
// returns all the created rooms (documents) in our rooms constant ( its a listner)
const unsubscribe = db.collection('rooms').onSnapshot(snapshot => (
setRooms(snapshot.docs.map(doc => ({
id: doc.id,
data: doc.data(),
})))
));
return () => { // clean up function that means we will always detach the above real time listner after we are done using it.
unsubscribe();
}
}, []);
const createChat = () => {
const roomName = prompt("Enter the room name");
if(roomName){
db.collection('rooms').add({
name: roomName,
});
}
}
const filterValue = rooms.filter((room) => {
return room.data.name.toLowerCase().includes(value.toLowerCase());
});
const handleChange = (e) => {
setValue(e.target.value);
}
return (
<div className="sidebar">
<div className="sidebar__header">
<Avatar src={user?.photoURL || "https://avatars.githubusercontent.com/u/69106317?v=4"} />
<div className="sidebar__headerRight">
<IconButton>
<DonutLargeIcon />
</IconButton>
<IconButton onClick={createChat}>
<ChatIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="sidebar__search">
<div className="sidebar__searchContainer">
<SearchOutlined />
<input placeholder="Search for a Chat" type="text" value={value} onChange={handleChange} />
</div>
</div>
<div className="sidebar__chats">
<SidebarChat addNewChat />
{/* adding the rooms already created */}
{filterValue.map(room => (
<SidebarChat key={room.id} id={room.id} name={room.data.name} />
))}
</div>
</div>
);
}
export default Sidebar;<file_sep>/src/StateProvider.js
import React, { createContext, useContext, useReducer} from "react";
export const StateContext = createContext();// this is where our data layout lives (creating the data layout) creating the context
export const StateProvider = ({reducer, initialState, children}) => ( // this is called higher order component
// this help us to set-up our data layout
// it contains single prop called value which is stored in context and that value is available to all the components present in the children prop(we will be render those components)
<StateContext.Provider value = {useReducer(reducer, initialState)}>{children}</StateContext.Provider> // children is the App component which we passed in index.js file
// useReducer takes 2 parameters reducer and action and returns an array containing state and dispatch
// whenever action changes the reducer will return a new state
);
export const useStateValue = () => useContext(StateContext); // allow us to pull information from the data layout<file_sep>/src/reducer.js
// initial state defines how the data layout looks initially when the app starts
export const initialState = { user: null }; // we want the user to be logged out when we start the app
// the actions help us to push information in data layout we do it by using dispatch
export const actionTypes = { SET_USER: "SET_USER" };
const reducer = (state, action) => {
//console.log(action);
// whatever we return shows how we intend to change the state of data layout
switch (action.type){
case actionTypes.SET_USER:
return {...state, user: action.user,};// keep everything as it is in the state and just change the user to what we have dispatch
default:
return state;
}
};
export default reducer;
|
8fc9f69a7a15f143def37da7cf17eb990b23451c
|
[
"JavaScript"
] | 6
|
JavaScript
|
kushagra25sharma/meet-up
|
54af31597339b474f3f4d4012bbbeccdb2eeeb46
|
f6ff684b8d8d93d51454440f139d9adeea2756da
|
refs/heads/master
|
<repo_name>an-hyojin/DataScience<file_sep>/NLP.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import konlpy
import pandas as pd
import re
import csv
from konlpy.tag import Kkma
from konlpy.tag import Okt
from konlpy.utils import pprint
from konlpy.tag import Hannanum
from collections import Counter
kkma = Kkma()
hannanum = Hannanum()
# In[2]:
kkmaRes = []
oktRes = []
with open('allSong.csv') as data:
csv_reader = csv.reader(data)
next(csv_reader) # 헤더 읽음 처리
for song in csv_reader:
for line in song[2].split("\n"):
# pprint(kkma.pos(line))
if len(line.strip())==0:
continue
print(line)
# pprint(kkma.morphs(line))
# pprint(okt.morphs(line))
# kkmaRes.extend(kkma.morphs(line))
# oktRes.extend(okt.morphs(line))
# pprint(hannanum.nouns(line))
# pprint(hannanum.pos(line))
break
# In[3]:
kVocab = Counter(kkmaRes)
print(kVocab)
# In[4]:
oVocab = Counter(oktRes)
print(oVocab)
# In[14]:
dic = {}
regex = re.compile('[0-9]') # 가다01 가다02 이런식으로 되어있는 것들 제거하기 위함
with open('words.csv') as data:
csv_reader = csv.reader(data)
next(csv_reader) # 헤더 읽음 처리
for word_list in csv_reader:
word = word_list[1]
num = regex.search(word)
if num : #num이 들어가있으면 제거
word = word[0:num.start()]
dic[word] = word_list[4]
print(word_list[4])
# In[9]:
song_list = {}
song_lyrics = {}
kor_rex = re.compile('[가-힣]+') #한글만 볼 것
from termcolor import colored
okt = Okt()
with open('allSong.csv') as data:
csv_reader = csv.reader(data)
next(csv_reader) # 헤더 읽음 처리
for song in csv_reader:
words = []
lyric = []
for line in kkma.sentences(song[2]):
# pprint(kkma.pos(line))
for word in okt.morphs(line):
if bool(re.search(kor_rex, word)):
lyric.append(word)
if word in dic:
words.append(word)
print(colored(word,'red'), end=' ')
continue
print(word, end=' ')
print()
song_lyrics[song[0]+"-"+song[1]] = lyric
song_list[song[0]+"-"+song[1]] = words
# In[10]:
for k in song_list:
print(k)
for word in song_list[k]:
if word in dic:
print(word, end=' ')
print()
# In[11]:
stopwords = []
with open('stopwords.csv') as data:
csv_reader = csv.reader(data)
next(csv_reader)
for stopword in csv_reader:
stopwords.extend(stopword)
print(stopword)
# In[12]:
print(stopwords)
# In[13]:
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(stop_words = stopwords)
# In[ ]:
for l in song_lyrics:
print()
vect.fit_transform(song_lyrics[l])
print(vect.vocabulary_)
# In[ ]:
<file_sep>/Regression1.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn import linear_model
house = pd.read_csv('USA_Housing.csv')
house.info()
# In[2]:
sns.pairplot(house)#데이터 상관관계 분석
# In[3]:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
linear_regression = linear_model.LinearRegression()
X = house[['Avg. Area Income']]
y = house['Price']
X_train, X_test, y_train, y_test = train_test_split(X,y, train_size=0.8, test_size=0.2)
slr = LinearRegression()
slr.fit(X_train.values.reshape(-1,1), y_train)
y_predicted = slr.predict(X_test)
plt.scatter(y_test, y_predicted)
plt.xlabel("Actual Price")
plt.ylabel("Predict Price")
plt.show()
print(slr.score(X_test,y_test))#R제곱
# In[4]:
mlr_X = house[['Avg. Area Income', 'Avg. Area House Age','Area Population']]
mlr_Y = house[['Price']]
mlrx_train, mlrx_test, mlry_train, mlry_test = train_test_split(mlr_X, mlr_Y, train_size=0.8, test_size=0.2)
mlr = LinearRegression()
mlr.fit(mlrx_train, mlry_train)
mlry_predict = mlr.predict(mlrx_test)
plt.scatter(mlry_test, mlry_predict)
plt.xlabel("Actual Price")
plt.ylabel("Predict Price")
plt.show()
print(mlr.score(mlrx_test,mlry_test))
# In[ ]:
# In[ ]:
<file_sep>/GenieLinkCrawler.py
#!/usr/bin/env python
# coding: utf-8
# In[33]:
import requests
from bs4 import BeautifulSoup
array = ['https://www.genie.co.kr/detail/songInfo?xgnm=87230562','https://www.genie.co.kr/detail/songInfo?xgnm=88040624','https://www.genie.co.kr/detail/songInfo?xgnm=86700924','https://www.genie.co.kr/detail/songInfo?xgnm=88740322','https://genie.co.kr/detail/songInfo?xgnm=86525645']
res = []
headers = {'User-Agent':""}# 헤더 설정
i =0
for url in array:
req = requests.get(url, headers = headers)
soup = BeautifulSoup(req.text, 'html.parser')
my_titles = soup.select('#pLyrics > div')
my_lylics = soup.select('#pLyrics > p')
res.append([])
res[i].append(my_titles[0].text)
res[i].append(my_lylics[0].text)
i= i+1
for a in res:
print(a[0])
print(a[1])
# In[17]:
my_titles = soup.select('#body-content > h2 > a')
print(my_titles[0].text)
my_lylics = soup.select('#pLyrics > p')
print(my_lylics[0].text)
# In[2]:
from selenium import webdriver
browser = webdriver.Chrome('Users/hyojin/chromedriver')
url = 'https://www.genie.co.kr/chart/top200'
browser.get(url)
# In[ ]:
# In[ ]:
<file_sep>/Classification1.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
heart = pd.read_csv('heart.csv')
heart.info()
# In[2]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(heart.drop('target', 1), heart['target'], test_size=0.2, random_state=10)
# In[3]:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(max_depth=5)
model.fit(X_train, y_train)
# In[4]:
from sklearn.metrics import accuracy_score
y_train_hat_dt = model.predict(X_train)
print('train accuracy: ', accuracy_score(y_train, y_train_hat_dt))
y_test_hat_dt = model.predict(X_test)
print('test accuracy: ' , accuracy_score(y_test, y_test_hat_dt))
# In[5]:
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
clf = SVC(C=100)
clf.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
y_train_hat = clf.predict(X_train_scaled)
print('train accuracy: ', accuracy_score(y_train, y_train_hat))
y_test_hat = clf.predict(X_test_scaled)
print('test accuracy: ' , accuracy_score(y_test, y_test_hat))
# In[6]:
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
print(confusion_matrix(y_test, y_test_hat))
print(classification_report(y_test, y_test_hat, target_names=['A', 'B']))
print(confusion_matrix(y_test, y_test_hat_dt))
print(classification_report(y_test, y_test_hat_dt, target_names=['A', 'B']))
# In[ ]:
<file_sep>/GoodSongFinder.py
#!/usr/bin/env python
# coding: utf-8
# In[16]:
import csv
import re
pattern = re.compile('[가-힣]+')
# In[17]:
def isHangel(str): # 한글이 몇 퍼센트의 비율로 들어가있는지 판단
# \n과 \s+ 제거
lyrics = re.sub('\n',' ', str)
lyrics = re.sub('\s+',' ',lyrics)
lyricArray = lyrics.split(' ')
hangel = 0
for eachlyric in lyricArray:
if bool(re.search(pattern, eachlyric)): # 한글 단어일 경우
hangel = hangel + 1
return hangel/len(lyricArray)
# In[21]:
songList = [] # 적합한 Song List 저장 위함
header=["Singer", "Title", "Lyrics"]
with open('allSong.csv') as data:
csv_reader = csv.reader(data)
next(csv_reader) # 헤더 읽음 처리
for line in csv_reader:
if isHangel(line[2])>=0.6: # 한글 비율이 0.6이상이면 적합하다고 판단
songList.append(line)
# In[22]:
print(len(songList))
for line in songList:
print(line[1])
# In[23]:
import pandas as pd
df = pd.DataFrame(songList)
df.to_csv("GoodSong.csv",header=None, index=None) # csv파일로 변환
# In[ ]:
# In[ ]:
<file_sep>/README.md
# Data Science
데이터분석 관련 파일 정리
<file_sep>/Standardzation.py
#!/usr/bin/env python
# coding: utf-8
# In[43]:
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[44]:
data = pd.read_csv('homework2.csv')
data.head()
# In[45]:
data = data.drop('id', axis=1)
data['diagnosis'] = data['diagnosis'].factorize()[0]
data = data.fillna(value=0)
target = data['diagnosis']
data = data.drop('diagnosis', axis=1)
data.head()
# In[39]:
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# In[40]:
X = data.values
pca = PCA(n_components=2)
pca_2d = pca.fit_transform(X)
tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=2000)
tsne_results = tsne.fit_transform(X)
# In[41]:
plt.figure(figsize=(16,11))
plt.subplot(121)
plt.scatter(pca_2d[:,0], pca_2d[:,1], c=target, cmap="coolwarm", edgecolor="None", alpha=0.35)
plt.colorbar()
plt.title('PCA Scatter Plot')
plt.subplot(122)
plt.scatter(tsne_results[:,0], tsne_results[:,1], c=target, cmap = "coolwarm", edgecolor="None", alpha=0.35)
plt.colorbar()
plt.title('TSNE Scatter Plot')
plt.show()
# In[47]:
from sklearn.preprocessing import StandardScaler
X_std = StandardScaler().fit_transform(X)
# In[26]:
pca = PCA(n_components=2)
pca_2d_std = pca.fit_transform(X_std)
tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=2000)
tsne_results_std = tsne.fit_transform(X_std)
# In[27]:
plt.figure(figsize = (16,11))
plt.subplot(121)
plt.scatter(pca_2d_std[:,0],pca_2d_std[:,1], c = target,
cmap = "RdYlGn", edgecolor = "None", alpha=0.35)
plt.colorbar()
plt.title('PCA Scatter Plot')
plt.subplot(122)
plt.scatter(tsne_results_std[:,0],tsne_results_std[:,1], c = target,
cmap = "RdYlGn", edgecolor = "None", alpha=0.35)
plt.colorbar()
plt.title('TSNE Scatter Plot')
plt.show()
# In[28]:
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters = 2, init = 'k-means++', random_state = 42)
ypca_kmeans = kmeans.fit_predict(pca_2d)
plt.figure(figsize=(16,11))
plt.subplot(121)
sns.scatterplot(pca_2d[ypca_kmeans==0,0], pca_2d[ypca_kmeans ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(pca_2d[ypca_kmeans==1,0], pca_2d[ypca_kmeans ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color = 'red',
label = 'Centroids',s=300,marker=',')
plt.grid(False)
plt.title('PCA')
plt.legend()
plt.show()
ytsne_kmeans = kmeans.fit_predict(tsne_results)
plt.figure(figsize=(16,11))
plt.subplot(122)
sns.scatterplot(tsne_results[ytsne_kmeans==0,0], tsne_results[ytsne_kmeans ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(tsne_results[ytsne_kmeans==1,0], tsne_results[ytsne_kmeans ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color = 'red',
label = 'Centroids',s=300,marker=',')
plt.grid(False)
plt.title('TSNE')
plt.legend()
plt.show()
# In[29]:
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters = 2, init = 'k-means++', random_state = 42)
ypca_std_kmeans = kmeans.fit_predict(pca_2d_std)
plt.figure(figsize=(16,11))
plt.subplot(121)
sns.scatterplot(pca_2d_std[ypca_std_kmeans==0,0], pca_2d_std[ypca_std_kmeans ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(pca_2d_std[ypca_std_kmeans==1,0], pca_2d_std[ypca_std_kmeans ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color = 'red',
label = 'Centroids',s=300,marker=',')
plt.grid(False)
plt.title('PCA')
plt.legend()
plt.show()
ytsne_std_kmeans = kmeans.fit_predict(tsne_results_std)
plt.figure(figsize=(16,11))
plt.subplot(122)
sns.scatterplot(tsne_results_std[ytsne_std_kmeans==0,0], tsne_results_std[ytsne_std_kmeans ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(tsne_results_std[ytsne_std_kmeans==1,0], tsne_results_std[ytsne_std_kmeans ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color = 'red',
label = 'Centroids',s=300,marker=',')
plt.grid(False)
plt.title('TSNE')
plt.legend()
plt.show()
# In[ ]:
# In[ ]:
<file_sep>/VibeTop100Crawler.py
#!/usr/bin/env python
# coding: utf-8
# In[10]:
from selenium import webdriver
#from webdriver_manager.chrome import ChromeDriverManager
browser = webdriver.Chrome('/Users/hyojin/Desktop/chromedriver') #드라이버 설정
url = 'https://vibe.naver.com/chart/total'# 크롤링할 url
browser.get(url)
browser.implicitly_wait(10) # 기다리는 시간 설정
# In[11]:
import time
btn = browser.find_element_by_css_selector("#app > div.modal > div > div > a") # 광고 창 삭제 버튼
btn.click() #삭제 클릭
time.sleep(1) #삭제 기다리기
# In[12]:
ranking_table = browser.find_element_by_css_selector("#content > div.track_section > div:nth-child(1) > div > table > tbody")
# 순위 목록 테이블
rows = ranking_table.find_elements_by_tag_name("tr") # 순위들 리스트로 가져옴
matrix =[]
head = ["Singer","Title", "Lyrics"]
matrix.append(head)
initial_scroll=0
next_scroll = 51
# In[13]:
for row in rows:
lylics_td=row.find_elements_by_css_selector(".lyrics")[0] # 가사 있는 cell
if len(lylics_td.find_elements_by_tag_name("a"))>0: # 가사가 있을 경우
lylics_td.find_elements_by_tag_name("a")[0].click() # 가사 보기 버튼 클릭
time.sleep(1) # 로딩 기다리기
title = browser.find_elements_by_xpath("//*[@id='app']/div[2]/div/div/div[1]/div[2]/div/strong")[0].text;
singer = browser.find_elements_by_xpath("//*[@id='app']/div[2]/div/div/div[1]/div[2]/div/em")[0].text;
lylics = browser.find_elements_by_css_selector("#app > div.modal > div > div > div.ly_contents > p > span:nth-child(2)")[0].text;
data = []
data.append(singer[5:].strip())
data.append(title[2:].strip())
data.append(lylics.strip())
matrix.append(data)
close_btn = browser.find_elements_by_css_selector("#app > div.modal > div > div > a")[0].click() # 가사 창닫기
scroll_command = "window.scrollTo(0,"+str(next_scroll)+");" # 화면 스크롤
browser.execute_script(scroll_command)
initial_scroll = next_scroll;
next_scroll += 51;
# In[16]:
import pandas as pd
df = pd.DataFrame(matrix)
df.to_csv("song.csv",header=None, index=None) # csv파일로 변환
# In[ ]:
<file_sep>/kmeansDBSCAN.py
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(context="notebook", palette="Spectral", style="darkgrid", font_scale=1.5, color_codes =True)
# In[3]:
dataset = pd.read_csv('input.csv', index_col='CustomerID')
# In[4]:
dataset.head()
# In[5]:
dataset.info()
# In[6]:
dataset.describe()
# In[7]:
dataset.isnull().sum()
# In[8]:
dataset.drop_duplicates(inplace=True)
# In[9]:
X = dataset.iloc[:,[2,3]].values
# In[10]:
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters= i, init = 'k-means++', random_state=42)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
# In[11]:
plt.figure(figsize=(10,5))
sns.lineplot(range(1,11), wcss,marker='o', color='red')
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
# In[12]:
kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42)
y_kmeans = kmeans.fit_predict(X)
# In[13]:
plt.figure(figsize=(15,7))
sns.scatterplot(X[y_kmeans==0,0], X[y_kmeans ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(X[y_kmeans==1,0], X[y_kmeans ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(X[y_kmeans==2,0], X[y_kmeans ==2,1], color = 'green', label='Cluster 3 ', s=50)
sns.scatterplot(X[y_kmeans==3,0], X[y_kmeans ==3,1], color = 'grey', label='Cluster 4 ', s=50)
sns.scatterplot(X[y_kmeans==4,0], X[y_kmeans ==4,1], color = 'orange', label='Cluster 5 ', s=50)
sns.scatterplot(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color = 'red',
label = 'Centroids',s=300,marker=',')
plt.grid(False)
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()
# In[42]:
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=10, min_samples=8, metric='euclidean')
y_db = db.fit_predict(X)
plt.figure(figsize=(15,7))
sns.scatterplot(X[y_db==0,0], X[y_db ==0,1], color = 'yellow', label='Cluster 1 ', s=50)
sns.scatterplot(X[y_db==1,0], X[y_db ==1,1], color = 'blue', label='Cluster 2 ', s=50)
sns.scatterplot(X[y_db==2,0], X[y_db ==2,1], color = 'green', label='Cluster 3 ', s=50)
sns.scatterplot(X[y_db==3,0], X[y_db ==3,1], color = 'grey', label='Cluster 4 ', s=50)
sns.scatterplot(X[y_db==4,0], X[y_db ==4,1], color = 'orange', label='Cluster 5 ', s=50)
plt.grid(False)
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()
# In[ ]:
<file_sep>/Classification2.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
card = pd.read_csv('creditcardcsvpresent.csv')
card.head()
# In[2]:
card['Is declined'] = card['Is declined'].str.lower().replace({'y':1, 'n':0})
card['isForeignTransaction'] = card['isForeignTransaction'].str.lower().replace({'y':1, 'n':0})
card['isHighRiskCountry'] = card['isHighRiskCountry'].str.lower().replace({'y':1, 'n':0})
card['isFradulent'] = card['isFradulent'].str.lower().replace({'y':1, 'n':0})
cardX = card.drop('Transaction date', 1)
cardX.head()
# In[3]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(cardX.drop('isFradulent', 1), cardX['isFradulent'], test_size=0.2, random_state=10)
# In[4]:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(max_depth=5)
model.fit(X_train, y_train)
# In[5]:
from sklearn.metrics import accuracy_score
y_train_hat_dt = model.predict(X_train)
print('train accuracy: ', accuracy_score(y_train, y_train_hat_dt))
y_test_hat_dt = model.predict(X_test)
print('test accuracy: ' , accuracy_score(y_test, y_test_hat_dt))
# In[6]:
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
clf = SVC(C=100)
clf.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
y_train_hat = clf.predict(X_train_scaled)
print('train accuracy: ', accuracy_score(y_train, y_train_hat))
y_test_hat = clf.predict(X_test_scaled)
print('test accuracy: ' , accuracy_score(y_test, y_test_hat))
# In[7]:
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
print(confusion_matrix(y_test, y_test_hat))
print(classification_report(y_test, y_test_hat, target_names=['A', 'B']))
print(confusion_matrix(y_test, y_test_hat_dt))
print(classification_report(y_test, y_test_hat_dt, target_names=['A', 'B']))
# In[ ]:
# In[ ]:
|
d9a76c3cfcd8eb4e7c2e4a0918064c08d21dd394
|
[
"Markdown",
"Python"
] | 10
|
Python
|
an-hyojin/DataScience
|
0178a04196db8875f704ad35f1d31d5402b08baf
|
beebd12373e99500cb08ad526b075ab138e1fb99
|
refs/heads/master
|
<repo_name>Jochen-z/python3-programs<file_sep>/crawler/login/zhihu.py
# -*- coding: utf-8 -*-
import io
import time
import requests
import http.cookiejar
from PIL import Image
from bs4 import BeautifulSoup
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0'
}
session = requests.Session()
session.cookies = http.cookiejar.LWPCookieJar(filename = 'zhihu_cookies.txt')
try:
session.cookies.load(ignore_discard = True, ignore_expires = True)
print("Cookie 加载成功")
except:
print("Cookie 加载失败")
# 获取动态参数
def get_xsrf():
print('正在获取动态参数...')
xsrf_url = 'http://www.zhihu.com'
html = session.get(xsrf_url, headers = headers).content
_xsrf = BeautifulSoup(html, "html.parser").find('input', {'name': '_xsrf'})['value']
return _xsrf
# 获取验证码
def get_captcha():
print('正在获取验证码...')
t = str(int(time.time()*1000))
captcha_url = 'http://www.zhihu.com/captcha.gif?r=' + t + '&type=login'
picture = session.get(captcha_url, headers = headers)
try:
stream = io.BytesIO(picture.content)
im = Image.open(stream)
im.show()
im.close()
except:
print('无法加载图片')
captcha = input('请输入验证码 > ')
return captcha
# 通过查看用户个人信息来判断是否已经登录
def isLogin():
url = "https://www.zhihu.com/settings/profile"
response = session.get(url, allow_redirects = False, headers = headers)
if int(response.status_code) == 200:
return True
else:
return False
if isLogin():
print('通过 Cookie 成功登录知乎')
else:
print('正在进行账号登录...')
post_url = 'http://www.zhihu.com/login/email'
post_data = {
'_xsrf': get_xsrf(),
'password': '<PASSWORD>',
'remember_me': 'true',
'email': 'xxxxx'
}
try:
# 不需要验证码直接登录成功
response = session.post(post_url, data = post_data, headers = headers)
if response.status:
if isLogin():
print('通过账号信息成功登录知乎')
except:
# 需要输入验证码后才能登录成功
post_data['captcha'] = get_captcha()
session.post(post_url, data = post_data, headers = headers)
if isLogin():
print('通过账号信息成功登录知乎')
session.cookies.save()
response = session.get('https://www.zhihu.com/', headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
username = soup.find('span', {'class':'name'}).string
print('登录用户名为:' + username)<file_sep>/crawler/login/douban.py
# -*- coding: utf-8 -*-
import io
import requests
import http.cookiejar
from PIL import Image
from bs4 import BeautifulSoup
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0'
}
data = {
'source' : 'None',
'redir' : 'https://www.douban.com/',
'form_email' : 'xxxxx',
'form_password' : '<PASSWORD>',
'remember' : 'on',
'login' : '登录'
}
session = requests.Session()
session.cookies = http.cookiejar.LWPCookieJar(filename = 'douban_cookies.txt')
try:
session.cookies.load(ignore_discard = True, ignore_expires = True)
print("Cookie 加载成功")
except:
print("Cookie 加载失败")
# 通过查看账户信息来判断是否已经登录
def isLogin():
response = session.get('https://www.douban.com/accounts/', allow_redirects = False, headers = headers)
if int(response.status_code) == 200:
return True
else:
return False
if isLogin():
print('通过 Cookie 成功登录豆瓣')
else:
print('正在进行账号登录...')
response = session.get('https://accounts.douban.com/login', headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
item = soup.find('div', {'class':'item item-captcha'})
if item: #需要输入验证码
img = soup.find('img', {'id':'captcha_image'})
picture = session.get(img['src'], headers = headers)
try:
stream = io.BytesIO(picture.content)
im = Image.open(stream)
im.show()
im.close()
except:
print('无法加载图片')
captcha = input('请输入验证码 > ')
data['captcha-solution'] = captcha
data['captcha-id'] = img['src'][39:66]
response = session.post('https://accounts.douban.com/login', data = data, headers = headers)
if isLogin():
print('通过账号信息成功登录豆瓣')
session.cookies.save()
else:
print('登录失败,请检查账号信息')
exit()
response = session.get('https://www.douban.com/', headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
a = soup.find('a', {'class':'bn-more'})
span = a.find_all('span')[0]
print(span.string)<file_sep>/README.md
# python3-programs
Python 3 练习项目
<file_sep>/crawler/proxy_ip/proxy.py
# -*- coding: utf-8 -*-
import re
import requests
from bs4 import BeautifulSoup
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(asctime)s > %(message)s')
# 以生成器方式从 www.mimiip.com 获取代理IP
def get_proxy_ip():
try:
for i in range(1, 5):
url = 'http://www.mimiip.com/gngao/%s' % i
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
ip = ''
for i in table.stripped_strings:
if re.match(r'^\d+\.\d+\.\d+\.\d+$', i):
ip = 'http://' + i + ':'
elif re.match(r'^\d+$', i):
ip += i
yield ip
except:
return False
# 检验代理IP是否有效,ip = {'http':'http://127.0.0.1:80'}
def check_proxy_ip(ip , timeout):
try:
response = requests.get("http://1212.ip138.com/ic.asp", proxies = ip, timeout = timeout)
if response:
# response.encoding = 'gb2312'
# print(response.text)
return True
else:
return False
except Exception as e:
return False
# 更新代理IP数据,并把通过校验的代理IP保存至filename文件
def update_proxies(filename, timeout):
ips = []
for ip in get_proxy_ip():
if check_proxy_ip({'http':ip}, timeout):
ips.append(ip)
if len(ips):
with open(filename, 'w', encoding = 'utf-8') as f:
for i in range(0, len(ips)):
f.write(ips[i] + '\n')
return True
else:
return False
# 获取可用代理IP,以生成器返回
def get_ip(update = True, filename = 'proxies.txt', timeout = 1):
if update:
# 更新代理IP数据
logging.info('正在更新代理IP...')
if update_proxies(filename, timeout):
logging.info('代理IP更新成功!')
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line.strip()
else:
logging.info('代理IP更新失败!')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line.strip()
if __name__ == '__main__':
for ip in get_ip(True):
print(ip)<file_sep>/crawler/toutiao/asyncio_crawler.py
# -*- coding: utf-8 -*-
import os
import asyncio
import aiohttp
import aiofiles
from time import clock
from pathlib import Path
from bs4 import BeautifulSoup
from multiprocessing import Process
# 异步获取图片链接
async def get_img_links(url):
async with aiohttp.request('GET', url) as response:
soup = BeautifulSoup(await response.text(), 'lxml')
div = soup.find_all('div', class_='img-wrap')
links = []
for img in div:
link = img.attrs.get('data-src')
if link is not None:
links.append(link)
print(link)
# urls = {'http://www.toutiao.com/a6339720698021576961/', 'http://www.toutiao.com/a6318898131442827522/'}
# loop = asyncio.get_event_loop()
# f = asyncio.wait([get_img_links(url) for url in urls])
# loop.run_until_complete(f)
# loop.close()
# 设置文件夹,文件夹名为传入的 directory 参数,若不存在会自动创建
def setup_download_dir(directory):
download_dir = Path(directory)
if not download_dir.exists():
download_dir.mkdir()
return download_dir
# 异步下载图片
async def download_link(directory, link):
img_name = '%s.jpg' % os.path.basename(link)
download_path = '%s/%s' % (directory, img_name)
async with aiohttp.request('GET', link) as response:
if response is not None:
async with aiofiles.open(download_path, 'wb') as f:
await f.write(await response.read())
# download_dir = setup_download_dir('async')
# loop = asyncio.get_event_loop()
# loop.run_until_complete(download_link(download_dir, 'http://p3.pstatp.com/origin/bdb00050863c66e1a29'))
# loop.close()
class Test:
def __init__(self, urls, directory):
self.urls = urls
self.queue = asyncio.Queue()
self.directory = directory
self.setup_download_dir()
async def run(self):
await asyncio.wait([self.producer(url) for url in self.urls])
tasks = []
for i in range(5):
# ensure_future() : 安排协程对象的执行
tasks.append(asyncio.ensure_future(self.comsumer()))
await self.queue.join()
for task in tasks:
task.cancel()
# 消费者
async def comsumer(self):
while True:
if not self.queue.empty():
link = self.queue.get_nowait()
await self.download_img(link)
print('Downloading : %s' % link)
self.queue.task_done()
else:
break
# 生产者:异步获取图片链接
async def producer(self, url):
async with aiohttp.request('GET', url) as response:
soup = BeautifulSoup(await response.text(), 'lxml')
div = soup.find_all('div', class_='img-wrap')
for img in div:
link = img.attrs.get('data-src')
if link is not None:
await self.queue.put(link)
print('Producing : %s' % link)
# 异步下载图片
async def download_img(self, link):
img_name = '%s.jpg' % os.path.basename(link)
download_path = '%s/%s' % (self.directory, img_name)
async with aiohttp.request('GET', link) as response:
if response is not None:
async with aiofiles.open(download_path, 'wb') as f:
await f.write(await response.read())
# 设置文件夹,文件夹名为传入的 directory 参数,若不存在会自动创建
def setup_download_dir(self):
download_dir = Path(self.directory)
if not download_dir.exists():
download_dir.mkdir()
class MyProcess(Process):
def __init__(self, name, urls, path):
Process.__init__(self)
self.name = name
self.urls = urls
self.path = path
def run(self):
print('Process(%s) is running!' % self.name)
case = Test(self.urls, self.path)
loop = asyncio.get_event_loop()
loop.run_until_complete(case.run())
loop.close()
print('Process(%s) is done!' % self.name)
def main():
start = clock()
urls = {
'http://www.toutiao.com/a6339720698021576961/',
'http://www.toutiao.com/a6318898131442827522/',
'http://www.toutiao.com/a6334865258125312258/',
'http://www.toutiao.com/a6320233114942816513/',
'http://www.toutiao.com/a6332685306417332482/',
'http://www.toutiao.com/a6328513445851758850/',
'http://www.toutiao.com/a6324816368374776066/',
'http://www.toutiao.com/a6321533135176450305/',
'http://www.toutiao.com/a6323016670126391553/',
'http://www.toutiao.com/a6309427949653885186/',
'http://www.toutiao.com/a6323910192758341890/'
}
case = Test(urls, 'picture')
loop = asyncio.get_event_loop()
loop.run_until_complete(case.run())
loop.close()
spend = clock() - start
print('Took %.2fs' % spend)
if __name__ == '__main__':
main()
# 一共下载了 296 张图片
# Took 68.86s | Took 68.54s<file_sep>/crawler/joke/README.txt
Python 网络爬虫实例3 ——— 爬取糗事百科段子
1. 目标
1) 抓取糗事百科热门段子
2) 过滤带有图片的段子
3) 实现每按一次回车显示一个段子的发布人,点赞数,段子内容。
4) 糗事百科:http://www.qiushibaike.com/hot/page/1
2. 使用:
python QSBK.py
3. 结果展示(2016/10/5):
正在读取糗事百科,按回车查看新段子,Q(q)退出
凤栖舞 ( funny : 11173 )
楼主嘴馋了,偷偷用外婆的手机给老妈发信息 : 闺女,妈想吃榴莲了,待会买一个回来!
!万万没想到,我妈又只字不改的把这条信息转发给我...<file_sep>/crawler/toutiao/crawler3.py
# -*- coding: utf-8 -*-
import os
import requests
from time import clock
from queue import Queue
from pathlib import Path
from threading import Thread
from bs4 import BeautifulSoup
# 负责生成链接
class Producer(Thread):
def __init__(self, queue, urls):
Thread.__init__(self)
self.queue = queue
self.urls = urls
def run(self):
for url in self.urls:
links = self.get_img_links(url)
for link in links:
self.queue.put(link)
print('Producer is done!')
# 解析网页中的全部图片链接,返回一个包含全部图片链接的列表
def get_img_links(self, url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
div = soup.find_all('div', class_='img-wrap')
links = []
for img in div:
src = img.attrs.get('data-src')
if src is not None:
links.append(src)
return links
# 负责下载图片
class Comsumer(Thread):
def __init__(self, queue, directory):
Thread.__init__(self)
self.queue = queue
self.directory = self.setup_download_dir(directory)
def run(self):
while True:
# queue.get()为阻塞调用,无超时
link = self.queue.get()
self.download_img(self.directory, link)
print('%s is running: %s' % (self.name, link))
# 通知Queue队列之前入队的一个任务已经完成,未完成的任务数减一;
# 当未完成的任务数降到0,join()解除阻塞。
# 由队列的消费者线程调用
self.queue.task_done()
# 把图片下载到本地
def download_img(self, directory, link):
img_name = '{}.jpg'.format(os.path.basename(link))
download_path = directory / img_name
response = requests.get(link)
if response is not None:
with download_path.open('wb') as f:
f.write(response.content)
# 设置文件夹,文件夹名为传入的 directory 参数,若不存在会自动创建
def setup_download_dir(self, directory):
download_dir = Path(directory)
if not download_dir.exists():
download_dir.mkdir()
return download_dir
def main():
start = clock()
download_dir = 'crawler3'
urls = {
'http://www.toutiao.com/a6339720698021576961/',
'http://www.toutiao.com/a6318898131442827522/',
'http://www.toutiao.com/a6334865258125312258/',
'http://www.toutiao.com/a6320233114942816513/',
'http://www.toutiao.com/a6332685306417332482/',
'http://www.toutiao.com/a6328513445851758850/',
'http://www.toutiao.com/a6324816368374776066/',
'http://www.toutiao.com/a6321533135176450305/',
'http://www.toutiao.com/a6323016670126391553/',
'http://www.toutiao.com/a6309427949653885186/',
'http://www.toutiao.com/a6323910192758341890/'
}
queue = Queue()
for x in range(6):
c = Comsumer(queue, download_dir)
# 设置为守护线程
c.setDaemon(True)
c.start()
p = Producer(queue, urls)
p.start()
p.join()
# 阻塞消费者线程,直到队列中的所有任务被处理掉。
queue.join()
spend = clock() - start
print('Took %.2fs' % spend)
if __name__ == '__main__':
main()
# 一共下载了 296 张图片
# Took 68.55s | Took 68.42s | Took 68.67s<file_sep>/crawler/toutiao/crawler1.py
# -*- coding: utf-8 -*-
import os
import requests
from time import clock
from pathlib import Path
from bs4 import BeautifulSoup
# 解析网页中的全部图片链接,返回一个包含全部图片链接的列表
def get_img_links(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
div = soup.find_all('div', class_='img-wrap')
links = []
for img in div:
src = img.attrs.get('data-src')
if src is not None:
links.append(src)
return links
# 把图片下载到本地
def download_link(directory, link):
img_name = '{}.jpg'.format(os.path.basename(link))
download_path = directory / img_name
response = requests.get(link)
if response is not None:
with download_path.open('wb') as f:
f.write(response.content)
# 设置文件夹,文件夹名为传入的 directory 参数,若不存在会自动创建
def setup_download_dir(directory):
download_dir = Path(directory)
if not download_dir.exists():
download_dir.mkdir()
return download_dir
def main():
start = clock()
download_dir = setup_download_dir('cralwer1')
urls = {
'http://www.toutiao.com/a6339720698021576961/',
'http://www.toutiao.com/a6318898131442827522/',
'http://www.toutiao.com/a6334865258125312258/',
'http://www.toutiao.com/a6320233114942816513/',
'http://www.toutiao.com/a6332685306417332482/',
'http://www.toutiao.com/a6328513445851758850/',
'http://www.toutiao.com/a6324816368374776066/',
'http://www.toutiao.com/a6321533135176450305/',
'http://www.toutiao.com/a6323016670126391553/',
'http://www.toutiao.com/a6309427949653885186/',
'http://www.toutiao.com/a6323910192758341890/'
}
links = []
for url in urls:
links.extend(get_img_links(url))
for link in links:
download_link(download_dir, link)
print('Downloading: %s' % link)
spend = clock() - start
print('一共下载了 %d 张图片' % len(links))
print('Took %.2fs' % spend)
if __name__ == '__main__':
main()
# 一共下载了 296 张图片
# Took 73.04s | Took 74.23s | Took 73.06s<file_sep>/ascii_art/README.txt
Python 图片转字符画
原理:
1.字符画是一系列字符的组合,我们可以把字符看作是比较大块的像素,一个字符表现一种颜色,字符的种类越多,可以表现的颜色也越多,图片也会更有层次感。
2.问题来了,我们是要转换一张彩色的图片,这么这么多的颜色,要怎么对应到单色的字符画上去?这里就要介绍灰度值的概念了。
灰度值:指黑白图像中点的颜色深度,范围一般从0到255,白色为255,黑色为0,故黑白图片也称灰度图像
3.我们可以使用灰度值公式将像素的 RGB 值映射到灰度值:
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
4.这样就好办了,我们可以创建一个不重复的字符列表,灰度值小(暗)的用列表开头的符号,灰度值大(亮)的用列表末尾的符号。
使用:
python ascii_art.py input.png --output output.txt --width 80 --height 80
<file_sep>/crawler/login/README.txt
Python 网络爬虫实例2 ——— 模拟浏览器登录
1. v2ex.py —— 模拟登陆 V2EX
2. douban.py —— 模拟登陆豆瓣
3. zhihu.py —— 模拟登陆知乎<file_sep>/crawler/7_days_weather/README.txt
Python 网络爬虫实例1 ——— 爬取中国天气网中的广州7日天气情况
url:http://www.weather.com.cn/weather/101280101.shtml
使用:
python 7_days_weather.py
结果展示(2016/10/2):
['2日(今天)', '多云', '31/23℃', '微风']
['3日(明天)', '多云', '32/24℃', '微风']
['4日(后天)', '多云', '33/23℃', '微风']
['5日(周三)', '多云', '32/24℃', '微风']
['6日(周四)', '多云', '33/24℃', '微风']
['7日(周五)', '多云', '33/24℃', '微风']
['8日(周六)', '多云转小雨', '33/22℃', '微风']<file_sep>/crawler/joke/QSBK.py
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
class QSBK:
# 构造函数
def __init__(self):
self.pageIndex = 1 #加载的页面索引
self.headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0'}
self.pageArticles = [] #段子列表,一个元素是一页的所有段子
self.enable = True # 是否终止程序
# 启动
def start(self):
print('正在读取糗事百科,按回车查看新段子,Q(q)退出')
self.loadPage() #先加载一页内容
while self.enable:
if len(self.pageArticles) > 0:
# pageArticle = self.pageArticles[0]
# del self.pageArticles[0]
pageArticle = self.pageArticles.pop(0) #取出并删除第一个元素
self.getJoke(pageArticle)
print('Good Bye!')
# 加载并提取页面内容,并加入到段子列表中
def loadPage(self):
if len(self.pageArticles) < 2: #如果当前未看的页数少于2页,则加载新一页
pageArticle = self.getPageItem(self.pageIndex) #获取新一页
if pageArticle:
self.pageArticles.append(pageArticle)
self.pageIndex += 1 #页面索引加一
# 传入页面索引,返回本页不带图片的段子列表
def getPageItem(self, pageIndex):
url = 'http://www.qiushibaike.com/hot/page/' + str(pageIndex)
response = requests.get(url, headers = self.headers)
soup = BeautifulSoup(response.content, 'html.parser')
div = soup.find_all('div', {'class':'article block untagged mb15'})
jokes = []
for article in div:
img = article.find('div', {'class':'thumb'})
if not img: #剔除带图片的段子
row = []
name = article.find('h2').string
number = article.find('i', {'class':'number'}).string
info = name + ' ( funny : ' + number + ' )\n'
row.append(info)
span = article.find('div', {'class':'content'}).find('span')
for content in span.contents:
if isinstance(content, str):
row.append(content)
row.append('')
jokes.append(row)
return jokes
#敲回车输出一个段子
def getJoke(self, pageArticle):
for joke in pageArticle:
put = input()
self.loadPage()
if put == 'Q' or put == 'q':
self.enable = False
return
for line in joke:
print(line)
if __name__ == '__main__':
spider = QSBK()
spider.start()<file_sep>/crawler/7_days_weather/7_days_weather.py
# -*- coding: utf-8 -*-
import random
import requests
from bs4 import BeautifulSoup
def get_html(url):
timeout = random.choice(range(80, 180))
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
}
r = requests.get(url, headers = headers, timeout = timeout)
r.encoding = 'utf-8'
return r.text
def get_data(html):
soup = BeautifulSoup(html, 'html.parser')
ul = soup.find('ul', attrs = {"class": "t clearfix"})
li = ul.find_all('li')
data = []
for day in li:
temp = []
temp.append(day.find('h1').string) #日期
inf = day.find_all('p')
temp.append(inf[0].string) #天气状况
if inf[1].find('span'):
temperature_highest = inf[1].find('span').string
temperature_lowest = inf[1].find('i').string
temp.append(temperature_highest + '/' + temperature_lowest) #气温
else :
temperature_lowest = inf[1].find('i').string
temp.append(temperature_lowest) #气温
temp.append(inf[2].find('i').string) #风速
data.append(temp)
return data
if __name__ == '__main__':
url = 'http://www.weather.com.cn/weather/101280101.shtml' #广州
html = get_html(url)
data = get_data(html)
for row in data:
print(row)<file_sep>/crawler/toutiao/README.txt
Python 网络爬虫实例4 ——— 爬取今日头条图片
1. 目标
1) 爬取今日头条图片
2) 使用四种不同的爬取方式,通过观察爬取结果比较不同爬取方式的效率(代码均在Windows平台下运行)
2. 结果对比
1) crawler1.py
以普通、单线程方式爬取
# 一共下载了 296 张图片
# Took 73.04s | Took 74.23s | Took 73.06s
2) crawler2.py
先获取所有待爬取图片的URL,然后以多线程方式爬取图片
# 8 Thread
# 一共下载了 296 张图片
# Took 71.36s | Took 70.98s | Took 71.41s
3) crawler3.py
使用生产者-消费者模型的多线程方式,实现爬取图片URL(生产者)和下载图片(消费者)并发进行
# 一共下载了 296 张图片
# Took 68.55s | Took 68.42s | Took 68.67s
4) crawler4.py
使用生产者-消费者模型的多进程方式,实现爬取图片URL(生产者)和下载图片(消费者)并行进行
# 一共下载了 296 张图片
# Took 68.90s | Took 68.95s | Took 68.90s<file_sep>/crawler/login/v2ex.py
# -*- coding: utf-8 -*-
import requests
import http.cookiejar
from bs4 import BeautifulSoup
headers = {
'referer' : 'https://www.v2ex.com/signin', #需要提供referer信息
'user-agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
}
session = requests.Session()
session.cookies = http.cookiejar.LWPCookieJar(filename = 'v2ex_cookies.txt')
try:
session.cookies.load(ignore_discard = True, ignore_expires = True)
print("Cookie 加载成功")
except:
print("Cookie 加载失败")
# 通过查看用户设置页面来判断是否已经登录
def isLogin():
url = "http://www.v2ex.com/settings"
response = session.get(url, headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
msg = soup.find('title')
if msg.string == 'V2EX › 设置':
return True
else:
return False
if isLogin():
print('通过 Cookie 成功登录 V2EX')
else:
print('正在进行账号登录...')
response = session.get('https://www.v2ex.com/signin', headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
username = soup.find('input', {'placeholder' : '用户名或电子邮箱地址'})['name']
passwrod = soup.find('input', {'type' : 'password'})['name']
once = soup.find('input', {'name' : 'once'})['value']
data = {
username : 'xxxxx',
passwrod : '<PASSWORD>',
'once' : once,
'next' : '/'
}
session.post('https://www.v2ex.com/signin', data = data, headers = headers)
if isLogin():
print('通过账号信息成功登录 V2EX')
session.cookies.save()
else:
print('登录失败,请检查账号信息')
exit()
response = session.get('http://www.v2ex.com/', headers = headers)
soup = BeautifulSoup(response.content, 'html.parser')
td = soup.find('td', {'width':'570'})
a = td.find_all('a')[1]
print('登录用户名为:' + a.string)
|
6c4f9174638e3e77a790a346ee79cbb7499acad8
|
[
"Markdown",
"Python",
"Text"
] | 15
|
Python
|
Jochen-z/python3-programs
|
492896a76993b637e5ad8948e1a9a177d6c100a0
|
ddda98c312d3746a807388e8bb083608da7fb75a
|
refs/heads/main
|
<file_sep>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y && \
apt-get install nodejs npm -y && \
npm install npm@latest -g
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["React/React.csproj", "React/"]
RUN dotnet restore "React/React.csproj"
COPY . .
WORKDIR "/src/React"
RUN dotnet build "React.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "React.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "React.dll"]<file_sep>using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace ReactWithAuth.Controllers
{
public class OidcConfigurationController : Controller
{
[HttpGet("_configuration/{clientId}")]
public IActionResult GetClientRequestParameters([FromRoute] string clientId)
{
Dictionary<string, string> parameters = new()
{
{ "authority", "https://localhost:5003" },
{ "client_id", "js" },
{ "redirect_uri", "https://localhost:5000/authentication/login-callback" },
{ "post_logout_redirect_uri", "https://localhost:5000/index.html" },
{ "response_type", "code" },
{ "scope", "openid profile api1" },
};
return Ok(parameters);
}
}
}
<file_sep>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y && \
apt-get install nodejs npm -y && \
npm install npm@latest -g
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["ReactWithAuth/ReactWithAuth.csproj", "ReactWithAuth/"]
COPY ["Identity/Identity.csproj", "Identity/"]
RUN dotnet restore "ReactWithAuth/ReactWithAuth.csproj"
COPY . .
WORKDIR "/src/ReactWithAuth"
RUN dotnet build "ReactWithAuth.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ReactWithAuth.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ReactWithAuth.dll"]<file_sep>using IdentityServer4;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiScope> ApiScopes =>
new List<ApiScope>
{
new ApiScope("api1", "My API"),
new ApiScope
{
Name = "read",
DisplayName = "Read",
Description = "Read information"
},
new ApiScope
{
Name = "write",
DisplayName = "Write",
Description = "Write information"
}
};
public static ICollection<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource
{
Name = "api1",
DisplayName = "Default API",
Scopes = new [] {"read","write"},
UserClaims = new [] { ClaimTypes.NameIdentifier, ClaimTypes.Email, ClaimTypes.Name }
}
};
public static IEnumerable<Client> Clients =>
new List<Client>
{
// interactive ASP.NET Core MVC client
//new Client
//{
// ClientId = "mvc",
// ClientSecrets = { new Secret("secret".Sha256()) },
// AllowedGrantTypes = GrantTypes.Code,
// // where to redirect to after login
// RedirectUris = { "https://localhost:5002/signin-oidc" },
// // where to redirect to after logout
// PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },
// AllowedScopes = new List<string>
// {
// IdentityServerConstants.StandardScopes.OpenId,
// IdentityServerConstants.StandardScopes.Profile,
// "api1"
// }
//},
// JavaScript Client
new Client
{
ClientId = "js",
ClientName = "<NAME>",
AllowedGrantTypes = GrantTypes.Code,
RequireClientSecret = false,
RedirectUris = { "https://localhost:5000/authentication/login-callback" },
PostLogoutRedirectUris = { "https://localhost:5000/index.html" },
AllowedCorsOrigins = { "https://localhost:5000" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}
}
};
}
}
|
170d80eadccc148dbb9421351d120ee6b9288ad7
|
[
"C#",
"Dockerfile"
] | 4
|
Dockerfile
|
IharYakimush/react-sample
|
013982d01e25c9b0e7f6524d241b1d041d45c945
|
0db2246356aac65dabb0623a0faeca770ae81c18
|
refs/heads/main
|
<repo_name>eodevelop/PublishingPractice<file_sep>/6/index.js
function showAbout() {
$('#About').show();
$('#Studio').hide();
$('#Works').hide();
$('#Contact').hide();
}
function showStudio() {
$('#About').hide();
$('#Studio').show();
$('#Works').hide();
$('#Contact').hide();
}
function showWorks() {
$('#About').hide();
$('#Studio').hide();
$('#Works').show();
$('#Contact').hide();
}
function showContact() {
$('#About').hide();
$('#Studio').hide();
$('#Works').hide();
$('#Contact').show();
}
showAbout();
$(document).ready(function () {
$("#About").load("./page/about.html");
$("#Studio").load("./page/studio.html");
$("#Works").load("./page/Works.html");
$("#Contact").load("./page/Contact.html");
});
|
2c239a32e6fccf9d979efd165bc3c8fbcd874b38
|
[
"JavaScript"
] | 1
|
JavaScript
|
eodevelop/PublishingPractice
|
6a1f45c7f721b6278e39ccd99b049d11298cf8fe
|
c35fa662da1a0eb47bc17f4d74fb51d87a0bdc0c
|
refs/heads/master
|
<file_sep>package cc.cu.bosp.maths;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.opengl.*;
public class Circle extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.circle);
TextView tv1 = (TextView)findViewById(R.id.textview1);
TextView tv2 = (TextView)findViewById(R.id.textview2);
tv1.setText("Area = 0.0");
tv2.setText("Circumference = 0.0");
}
public void calculate(View v){
EditText et1 = (EditText)findViewById(R.id.value1);
TextView tv1 = (TextView)findViewById(R.id.textview1);
TextView tv2 = (TextView)findViewById(R.id.textview2);
if (et1.getText().length() < 1){
Toast.makeText(this, "Enter a number", Toast.LENGTH_LONG).show();
}
else {
tv1.setText("Area = 0.0");
tv2.setText("Circumference = 0.0");
String a = et1.getText().toString();
double A = Double.parseDouble(a);
double area = Math.pow(A, 2) * Math.PI;
double circumference = 2 * A * Math.PI;
tv1.setText("Area = " + area);
tv2.setText("Circumference = " + circumference);
}
}
}
<file_sep>package cc.cu.bosp.maths;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.widget.AdapterView.*;
import android.content.*;
import android.widget.ListView;
import android.view.*;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android. view.View;
import android. widget. AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ListView aListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get list view from xml
aListView = (ListView) findViewById(R.id.mainListView1);
String[] Cities = {
"New York",
"Miami",
"Atlanta",
"Orlando",
"Calgary",
"Toronto",
"Dallas",
"Austin",
"San Diego",
"Las Vegas"};
ListAdapter aAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Cities);
ListView aListView = (ListView) findViewById(R.id.mainListView1);
aListView.setAdapter(aAdapter);
aListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(MainActivity.this, cities, Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(MainActivity.this, Circle.class);
startActivity(intent);
}
}
});
}
}
|
568ee3158e517590f5e93579c0c37321bdeda920
|
[
"Java"
] | 2
|
Java
|
benpaterson35/listview
|
3a0a2475e8cca33fc9a4f5ba27f6ae6cd4c9e947
|
8956f07c3d1e23dd87921ae5f38881150f3cde3a
|
refs/heads/master
|
<file_sep>package com.example.consumer.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Person {
private Long id;
private String name;
private String surname;
}
<file_sep># contract-test
##Producer
1. Producer of service has to include below dependency and maven plugin.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
<scope>test</scope>
</dependency>
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
<version>3.0.3</version>
<extensions>true</extensions>
<configuration>
<testFramework>JUNIT5</testFramework>
<baseClassForTests>com.example.producer.BaseTestClass</baseClassForTests>
</configuration>
</plugin>
2. we need to create contract files defined in groovy inside test/resources/contract folder.
3. Once we run mvn clean install, below thing happens
- creates java test files inside target.
- creates stubs jar based on wire mock that can be used at client side.
- Generated java classes can be used as junit tests.
##Consumer
1. we need to include below dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency>
2. we need to configure test class to use stubs jar that was creted by producer. IT Downloads the jar from mvn repo unpack and use this to create wiremock server and stubs.
. downloadStub("com.example", "producer", "0.0.1-SNAPSHOT", "stubs")
.withPort(8100)
.stubsMode(StubRunnerProperties.StubsMode.LOCAL);
|
29ade61fbb9cf8bbc03148f85894ad205e3a92e1
|
[
"Markdown",
"Java"
] | 2
|
Java
|
ajayonlineforu/contract-test
|
828a04687a6b22be85487898ffc00309f2da2fda
|
6364125bb1dbacf548bba485c20584c6eacb6cb0
|
refs/heads/master
|
<repo_name>timdzha/students<file_sep>/src/main/java/com/timdev/students/Main.java
package com.timdev.students;
import com.timdev.students.student.Student;
import com.timdev.students.student.StudentRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
CommandLineRunner commandLineRunner(StudentRepository studentRepository) {
return args -> {
final List<Student> students = Stream.of(
new Student(
"Maria",
"Jones",
"<EMAIL>",
LocalDate.of(2004, 01, 05)),
new Student(
"Robert",
"Jock",
"<EMAIL>",
LocalDate.of(2000, 03, 07)),
new Student(
"Kate",
"Lee",
"<EMAIL>",
LocalDate.of(1989, 06, 22))
).collect(Collectors.toList());
studentRepository.saveAll(students);
};
}
}
<file_sep>/src/main/java/com/timdev/students/auth/FakeApplicationUserDaoService.java
package com.timdev.students.auth;
import com.google.common.collect.Lists;
import com.timdev.students.security.ApplicationUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Repository("fake")
public class FakeApplicationUserDaoService implements ApplicationUserDao {
private final PasswordEncoder passwordEncoder;
@Autowired
public FakeApplicationUserDaoService(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public Optional<ApplicationUser> findApplicationUserByUsername(String username) {
return getApplicationUsers()
.stream()
.filter(applicationUser -> username.equals(applicationUser.getUsername()))
.findFirst();
}
private List<ApplicationUser> getApplicationUsers() {
return Lists.newArrayList(
new ApplicationUser(
"student1",
passwordEncoder.encode("<PASSWORD>"),
ApplicationUserRole.STUDENT.getGrantedAuthorities(),
true,
true,
true,
true
),
new ApplicationUser(
"admin1",
passwordEncoder.encode("<PASSWORD>"),
ApplicationUserRole.ADMIN.getGrantedAuthorities(),
true,
true,
true,
true
),
new ApplicationUser(
"trainee1",
passwordEncoder.encode("<PASSWORD>"),
ApplicationUserRole.TRAINEE.getGrantedAuthorities(),
true,
true,
true,
true
)
);
}
}
<file_sep>/src/main/java/com/timdev/students/jwt/JwtUsernameAndPasswordAuthenticationFilter.java
package com.timdev.students.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
private final JwtConfig jwtConfig;
private final Algorithm secretKey;
@Autowired
public JwtUsernameAndPasswordAuthenticationFilter(AuthenticationManager authenticationManager,
JwtConfig jwtConfig,
Algorithm secretKey) {
this.authenticationManager = authenticationManager;
this.jwtConfig = jwtConfig;
this.secretKey = secretKey;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
final UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper()
.readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
Authentication authentication = new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
);
return authenticationManager.authenticate(authentication);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
final String[] authorities = authResult.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.toArray(String[]::new);
final String token = JWT.create()
.withSubject(authResult.getName())
.withArrayClaim("authorities", authorities)
.withIssuedAt(new Date())
.withExpiresAt(java.sql.Date.valueOf(LocalDate.now().plusDays(jwtConfig.getTokenExpirationAfterDays())))
.sign(secretKey);
response.addHeader(jwtConfig.getAuthorizationHeader(), jwtConfig.getTokenPrefix() + token);
}
}
<file_sep>/src/main/java/com/timdev/students/student/StudentService.java
package com.timdev.students.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class StudentService {
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
public Student getStudent(Integer studentId) {
return tryToFindStudent(studentId);
}
public void createStudent(Student student) {
tryToCheckIfStudentAlreadyExists(student.getEmail());
studentRepository.save(student);
}
public void deleteStudent(Long studentId) {
final boolean exists = studentRepository.existsById(studentId);
if (!exists) {
throw new IllegalStateException(String.format("Student with id %s doesn't exist", studentId));
}
studentRepository.deleteById(studentId);
}
@Transactional
public void updateStudent(Long studentId, String name, String email) {
final Student student = tryToFindStudent(studentId.intValue());
if (name != null
&& name.length() > 0
&& !Objects.equals(student.getFirstName(), name)) {
student.setFirstName(name);
}
if (email != null
&& email.length() > 0
&& !Objects.equals(student.getEmail(), email)) {
tryToCheckIfStudentAlreadyExists(email);
student.setEmail(email);
}
studentRepository.save(student);
}
private Student tryToFindStudent(Integer studentId) {
return studentRepository
.findById(Long.valueOf(studentId))
.orElseThrow(() -> new IllegalStateException(String.format("Student %s not found", studentId)));
}
private void tryToCheckIfStudentAlreadyExists(String email) {
final Optional<Student> studentOptional = studentRepository.findStudentByEmail(email);
if (studentOptional.isPresent()) {
throw new IllegalStateException("Email taken");
}
}
}
|
4fbfe4508bbc6be9d9bfbd3cec23639c158a0b05
|
[
"Java"
] | 4
|
Java
|
timdzha/students
|
26af86735afd5cf068429198b129fc30b8ae08c1
|
baef4a7470df4de0ed4f890611e25980f43ddf94
|
refs/heads/main
|
<repo_name>AkiaCode/spacex-api.js<file_sep>/test/index.js
const test = require('../src/index')
Promise.all([
test.getData("launches", "past")
]).then(console.log)<file_sep>/README.md
# spacex-api.js
|
87f8c056c958bf9d1008720abed39431b12da511
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
AkiaCode/spacex-api.js
|
7eaf2cdacdce7952948cf9a4f2f39ac3ed4030e0
|
60a2d5f3aa03f96be23d68b55612a3b2def1ea60
|
refs/heads/master
|
<repo_name>mkamalraj/htmlfile<file_sep>/day5/day5-1.js
var a=11;
var b=13;
var c=a+b;
var person={name:"kamal",age:"21",place:"hindupur"};
var array=["kamal","raj","mayakuntla"];
document.getElementById("integers").innerHTML=c;
document.getElementById("object").innerHTML=person.place;
document.getElementById("arr").innerHTML=array[2];
if(a!=b)
{
alert("mismatch");
}<file_sep>/day1/t1-1.html
<!DOCTYPE html>
<html>
<head>
<style>
table,td,th
{
border-collapse: collapse;
}
</style>
<title>day1morning</title>
</head>
<body>
<h1>HELLO WORLD</h1>
<hr>
<h2>my rules goes here</h2>
<br>
<h6>These are very strict</h6>
<a href="www.myworld.com">click to see the rules</a>
<video width="250" height="250" controls>
<source src="movie.mp4" type="video/mp4">
</video>
<br>
<br>
<br>
number of students went to tour
<ol>
<li>sachin</li>
<li>dhoni</li>
<li>virat</li>
<li>mahi</li>
</ol>
The places they visit are
<ul>
<li>kerala</li>
<li>andhra</li>
<li>tamilnadu</li>
<li>bangalore</li>
<img src="div1..jpg" height="250" width="250"><br>
</ul>
<table border="1">
<tr>
<th>S.NO</th>
<th>Names</th>
<th>monthly</th>
<th>salary</th>
</tr>
<tr>
<td>1</td>
<td>dhoni</td>
<td>january</td>
<td>100000</td>
</tr>
<tr>
<td>2</td>
<td>mahi</td>
<td>febrauary</td>
<td>25000</td>
</tr>
<tr>
<td>3</td>
<td>sachin</td>
<td>march</td>
<td>22000</td>
</tr>
</table>
my name is KAMAl..
</body>
</html><file_sep>/day8/t3.js
function fun(){
var arrayname=[{name:"kamal",age:22,mobile:7993863254},
{name:"suresh",age:21,mobile:8121824536},
{name:"param",age:22,mobile:9133707671}];
arrayname.forEach(function(item){
console.log(item.name);
console.log(item.age);
console.log(item.mobile);
});
}
//
// document.getElementById('Kamal').innerHTML=arrayname[i].name;<file_sep>/day5/basics.js
function kamal()
{
var x, y, z;
x = 5;
y = 6;
z = x + y;
alert(z);
}
<file_sep>/day8/tablemethod.js
function fun(){
var b=document.getElementById("kamal").value;
console.log(b);
var c=document.getElementById("raj").value;
console.log(c);
// var d=document.getElementById("nani").value;
// console.log(d);
// var e=document.getElementById("non").value;
// console.log(e);
var f=document.getElementById("web").value;
console.log(f);
var g=document.getElementById("phone").value;
console.log(g);
var h=document.getElementById("site").value;
console.log(h);
}
|
e91f9e0bf600253e0e686fec42a74a750a457e72
|
[
"JavaScript",
"HTML"
] | 5
|
JavaScript
|
mkamalraj/htmlfile
|
28a1836ba27e197f4deaea99ce806684ccb2cec9
|
ff9a54345c4c9275c8d204fb080ee6e948201f25
|
refs/heads/main
|
<repo_name>fat3d/assets<file_sep>/nav.js
function rotateArrow() {
var clickedEleArr = document.querySelectorAll('.rotatearrow')
clickedEleArr.forEach(function (clickedEle) {
clickedEle.addEventListener('click', function () {
var rotatedEle = clickedEle.querySelector('.arrow')
if (rotatedEle.classList.contains('rotate')) {
rotatedEle.classList.remove('rotate')
} else {
rotatedEle.classList.add('rotate')
}
})
})
}
function toggleSidebar() {
var body = document.body
var sidebar = body.querySelector('.sidebar')
var toggleSidebar = body.querySelector('#toggle-sidebar')
toggleSidebar.addEventListener('click', function () {
if (body.classList.contains('sidebar-isopened')) {
body.classList.remove('sidebar-isopened')
sidebar.classList.remove('opened')
} else {
body.classList.add('sidebar-isopened')
sidebar.classList.add('opened')
}
})
}
function detectClickOutside() {
var body = document.body
var sidebar = document.querySelector('.sidebar')
var toggleSidebar = body.querySelector('#toggle-sidebar')
window.addEventListener('click', function (e) {
if (
!sidebar.contains(e.target) &&
!toggleSidebar.contains(e.target) &&
body.classList.contains('sidebar-isopened')
) {
body.classList.remove('sidebar-isopened')
sidebar.classList.remove('opened')
}
})
}
function styleScrollbar() {
var sidebar = document.querySelector('.sidebar')
document.addEventListener('DOMContentLoaded', function () {
OverlayScrollbars(sidebar, {
className: 'os-theme-light'
})
})
}
function hideNavItems() {
var showSearchbox = document.querySelector('#show-searchbox')
var navStart = document.querySelector('.nav-start')
var navEnd = document.querySelector('.nav-end')
var navForm = document.querySelector('.nav-form')
var hideSearchbox = document.querySelector('#hide-searchbox')
showSearchbox.addEventListener('click', function () {
navStart.classList.add('d-none')
navEnd.classList.add('d-none')
navForm.classList.remove('d-none')
hideSearchbox.classList.remove('d-none')
})
}
function showNavItems() {
var navStart = document.querySelector('.nav-start')
var navEnd = document.querySelector('.nav-end')
var navForm = document.querySelector('.nav-form')
var hideSearchbox = document.querySelector('#hide-searchbox')
hideSearchbox.addEventListener('click', function () {
navStart.classList.remove('d-none')
navEnd.classList.remove('d-none')
navForm.classList.add('d-none')
hideSearchbox.classList.add('d-none')
})
}
const targets = document.querySelectorAll("img.card-img-top, img.avatar");
const lazyLoad = target => {
const io = new IntersectionObserver((entries, observer) => {
console.log(entries)
entries.forEach(entry => {
console.log('😍');
if (entry.isIntersecting) {
const img = entry.target;
const src = img.getAttribute('data-lazy');
img.setAttribute('src', src);
observer.disconnect();
}
});
});
io.observe(target)
};
targets.forEach(lazyLoad);
rotateArrow()
toggleSidebar()
detectClickOutside()
styleScrollbar()
hideNavItems()
showNavItems()
|
b120b49906081d16495181f09a959873c6308f0b
|
[
"JavaScript"
] | 1
|
JavaScript
|
fat3d/assets
|
c16baf99820fbf709d6feadc486dcdf12a05ba67
|
20b205d8601f29a30e4ed51dcd7da3dc53388206
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\User;
use App\Product;
use Storage;
class AdminProductController extends Controller
{
//auth驗證是否登入 , is_adm驗證是否為Admin
public function __construct()
{
$this->middleware('auth');
$this->middleware('is_adm');
}
// @return All Products
public function index()
{
//$products = Product::all();
//為了自動切分頁,更改了controller
$products = Product::orderBy('created_at', 'desc')->paginate(3);
//取出現在時間
$nowtime = Carbon::now();
//將所有圖片取出
//dd($products);
foreach($products as $product){
//先取得商品名
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path[$product->id] = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path[$product->id] = '';
}
if($products->count() == 0)
$file_path = '';
//先假設路徑為admin/index.blade.php
return view('adm.Product', compact('products','file_path','nowtime'));
}
/*
* Show a product's detail
* @param the product's pid
* @return one product with id
*/
public function show(Product $product)
{
//dd($products);
return view('adm.Product', compact('product'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('adm.CreateProduct');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Carbon::createFromFormat('Y/m/d','1970/01/01')->timestamp;
$att['name'] = $request->input('name');
$att['view_time'] = $request->input('view_time');
$att['start_time'] = $request->input('start_time');
$att['end_time'] = $request->input('end_time');
$att['detail'] = $request->input('detail');
$att['cost'] = $request->input('cost');
$att['cur_cost'] = $request->input('cur_cost');
$att['origin_price'] = $request->input('origin_price');
//更改型別
$att['view_time'] = Carbon::parse($att['view_time'])->toDateTimeString();
$att['start_time'] = Carbon::parse($att['start_time'])->toDateTimeString();
$att['end_time'] = Carbon::parse($att['end_time'])->toDateTimeString();
$product = Product::create($att);
//處理圖片上傳
if ($request->hasFile('pics')) {
$pics = $request->file('pics');
foreach($pics as $pic){
if(!in_array($pic->getClientOriginalExtension(),array('jpg','jpeg','png'))) continue;
$info = [
'mime-type' => $pic->getMimeType(),
'original_filename' => $pic->getClientOriginalName(),
'extension' => $pic->getClientOriginalExtension(),
'size' => $pic->getClientSize(),
];
$pic->storeAs('public/products/'.$product->id, $info['original_filename']);
}
}
return redirect()->route('adm_Product');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
if($product->view_time <= Carbon::now())
return redirect()->back()->with('has_begin', '已過公布時間,無法編輯');
$files = get_files(storage_path('app/public/products/'.$product->id));
$pics[$product->id] = $files;
if($pics[$product["id"]] != NULL)
$file_path = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$pics[$product["id"]][0]));
else
$file_path = '';
return view('adm.EditProduct', compact('product','file_path'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
if($product->view_time <= Carbon::now())
return redirect()->back()->with('has_begin', '已過公布時間,無法編輯');
$att['name'] = $request->input('name');
$att['view_time'] = $request->input('view_time');
$att['start_time'] = $request->input('start_time');
$att['end_time'] = $request->input('end_time');
$att['detail'] = $request->input('detail');
$att['origin_price'] = $request->input('origin_price');
//更改型別
$att['view_time'] = Carbon::parse($att['view_time'])->toDateTimeString();
$att['start_time'] = Carbon::parse($att['start_time'])->toDateTimeString();
$att['end_time'] = Carbon::parse($att['end_time'])->toDateTimeString();
$product->update($att);
//處理圖片上傳
if ($request->hasFile('pics')) {
//如果有圖片,先刪掉舊的,然後再上傳新的
Storage::deleteDirectory("public/products/".$product->id);
$pics = $request->file('pics');
foreach($pics as $pic){
if(!in_array($pic->getClientOriginalExtension(),array('jpg','jpeg','png'))) continue;
$info = [
'mime-type' => $pic->getMimeType(),
'original_filename' => $pic->getClientOriginalName(),
'extension' => $pic->getClientOriginalExtension(),
'size' => $pic->getClientSize(),
];
$pic->storeAs('public/products/'.$product->id, $info['original_filename']);
}
}
return redirect()->route('adm_Product');
}
//結標商品詳細
public function details(Product $product)
{
//先取得商品名
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path = '';
return view('adm.Details', compact('product', 'file_path'));
}
public function status(Product $product)
{
if($product->status == 0)
$product->update(['status' => '1']);
return redirect()->route('adm_Product');
}
/**
* Delete the spectified resource in storage.
*
* @param int $id
* @return \Illuminate\Http\Responese
*/
public function destroy(Product $product)
{
if($product->view_time <= Carbon::now())
return redirect()->back()->with('has_begin', '已過公布時間,無法刪除');
//Storage::deleteDirectory("public/products/".$product->id);
$product->delete();
return redirect()->route('adm_Product');
}
}
<file_sep><?php
namespace Tests\Feature;
use Carbon\Carbon;
use App\User;
use App\Product;
use Auth;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
//use DatabaseMigrations;
use RefreshDatabase;
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
// Given 10 Users with 5 coins each,
// 1 Product will end in 5 minutes
$users = factory(User::class, 10)->create();
$product = factory(Product::class)->create([
'view_time' => Carbon::now(),
'start_time' => Carbon::now(),
'end_time' => Carbon::now()->addMinutes(5)
]);
// When
for ($i = 0; $i < 50 ; $i++) {
Auth::login($users[ $i%10 ]);
$response = $this->get(route('bidding', $product->id));
Auth::logout();
}
// Then
$product = Product::first();
$this->assertEquals(50000, $product->cur_cost);
//$response->assertSee();
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeTablePaymentName extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::rename('payment','payments');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::rename('payments','payment');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Bulletin;
class BulletinController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('is_adm');
}
public function index()
{
$bulletins = Bulletin::where('on','1')->paginate(3);
return view('adm.Bulletin', compact('bulletins'));
}
/*
* Show a product's detail
* @param the product's pid
* @return one product with id
*/
public function show(Bulletin $bulletin)
{
return view('adm.Bulletin', compact('bulletin'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('adm.CreateBulletin');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$att['title'] = $request->input('title');
$att['content'] = $request->input('content');
Bulletin::create($att);
return redirect()->route('adm_Bulletin');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Bulletin $bulletin)
{
return view('adm.EditBulletin', compact('bulletin'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Bulletin $bulletin)
{
$att['title'] = $request->input('title');
$att['content'] = $request->input('content');
$bulletin->update($att);
return redirect()->route('adm_Bulletin');
}
/**
* Delete the specified resource in storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Bulletin $bulletin)
{
$bulletin->update( ['on' => '0'] );
return redirect()->route('adm_Bulletin');
}
}
<file_sep><?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email','realname', 'password',
'phone', 'on', 'nickname', 'recommand_code',
'balance', 'code', 'email_confirm',
'fblogin_provider', 'fblogin_providerId'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* protected casts
* @var array
*/
/**
* get Payment , 1 to many
*/
public function payments()
{
return $this->hasMany('App\Payment','uid', 'id');
}
/**
* get Product, many to many, using relationship Auction
* @param mode, 1 is auto, 0 is not
*/
public function products($mode = NULL)
{
if($mode)
return $this->belongsToMany('App\Product','auction_auto','uid','pid')
->withPivot('start_cost','end_cost','times')
->withTimestamps();
else
return $this->belongsToMany('App\Product','auction','uid','pid')
->withPivot('cost','lasted_cost')
->withTimestamps();
}
public function winner_product()
{
return $this->hasMany('App\Product','uid');
}
}
<file_sep><?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\User;
use Session;
class CheckIsAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$admId = Session::get('adm_on');
if( $admId != 0 )
{
$adm = User::find($admId);
Auth::logout();
Auth::login($adm);
}
$user = Auth::user();
if($user->is_adm)
return $next($request);
else
return redirect('/user');
}
}
<file_sep><?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Product;
use App\Auction;
use Illuminate\Support\Str;
class CheckEndBidding extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bidding:end';
/**
* The console command description.
*
* @var string
*/
protected $description = '搜尋已結標商品';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$now_time = Carbon::now();
$products = Product::where('nickname_changed', false)->where('uid','!=','0')->where('end_time','<',$now_time)->get();
foreach($products as $product)
{
$user = $product->winner;
$top_auction = $product->users()->orderBy('auction.created_at', 'desc')->get()->first();
if($user->id != $top_auction->id)
$product->update(['uid' => $top_auction->id]);
$coins = $user->products()->where('pid',$product->id)->get()->count();
$new_nickname = Str::random(8);
//折扣公式 (原價 - 結標價 - 代幣數*30000) / 原價
$discount = ($product->origin_price - $product->cur_cost - $coins * 30000) / (($product->origin_price > 0) ? $product->origin_price : 1);
$discount = ($discount < 0) ? 0 : round($discount * 100); //小於0以0表示
$user->update(['nickname' => $new_nickname]);
$product->update([
'nickname_changed' => true,
'discount' => $discount
]);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
class EndBiddingController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('EndBiddingDetail');
}
public function store(Request $request, Product $product)
{
$userID = Auth::id();
$address = $request->input('address');
$message = $request->input('message');
$data = [
'message' => $message,
'address' => $address
];
$product->winner()->attach($userID,$data);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Product;
use App\Auction;
use App\AuctionAuto;
use Auth;
use Session;
class InterfaceController extends Controller
{
public function index()
{
//dd("cc");
$products = Product::where('view_time','<=',Carbon::now())->where('end_time','>=',Carbon::now())->paginate(4);
$now_time = Carbon::now();
//先假設路徑為admin/index.blade.php
foreach($products as $product){
//先取得商品名
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path[$product->id] = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path[$product->id] = '';
//echo $file_path[$product->id]."\n";
}
//如果沒有進行中拍賣,給file_path一個null防error
if(!isset($file_path)) $file_path='';
return view('user.all', compact('products','file_path','now_time'));
}
public function show(Product $product)
{
$nowtime = Carbon::now();
$auctions = $product->users()->orderBy('auction.created_at', 'desc')->paginate(3);
$auction_auto = AuctionAuto::where('uid',Auth::id())->where('pid',$product->id)->get()->first();
//dd($auctions);
//print_r($auctions);
if($this->check_auction_exist($product)) {
$top_auction = $auctions[0];
}
else {
$top_auction = new \stdClass();
$top_auction->name = '';
}
if($auction_auto == null)
{
$auction_auto = new \stdClass();
$auction_auto->start_cost = 'ex: 5000';
$auction_auto->end_cost = 'ex: 15000';
$auction_auto->times = 'ex: 10';
$auction_auto->on = null;
}
else
$auction_auto->on = true;
//取得圖片
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path = '';
//dd($top_auction);
//echo $auction_auto;
return view('user.interface', compact('product','top_auction','auctions','file_path','nowtime','auction_auto'));
}
private function check_auction_exist(Product $product)
{
$temp = Auction::where('pid', $product->id)->get();
if($temp->count() === 0)
return 0;
return 1;
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\User;
class AdminTableSeeder extends Seeder {
public function run()
{
$adm_default = [
'name' => 'admin',
'email' => '<EMAIL>',
'password' => Hash::<PASSWORD>('<PASSWORD>'),
'phone' => '0988397679'
];
$admin = User::create($adm_default);
$admin->update(['is_adm' => 1]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Product;
use App\User;
class AuctionAuto extends Model
{
protected $table = 'auction_auto';
protected $fillable = [
'uid', 'pid', 'start_cost', 'end_cost', 'times'
];
public function product()
{
return $this->belongsTo('App\Product','pid');
}
public function user()
{
return $this->belongsTo('App\User', 'uid');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Product;
use App\User;
use App\AuctionAuto;
use Carbon\Carbon;
use Validator;
class BiddingController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Product $product)
{
return view('user.bidding',compact('product'));
}
public function store(Request $request, Product $product)
{
$user = Auth::user();
$userID = Auth::id();
$now_time = Carbon::now();
//$bid_cost = $request->input('bid_cost');
if( $user->balance > 0 && $product->end_time >= $now_time )
{
$data = [
'cost' => $product->cost,
'lasted_cost' => $product->cur_cost + $product->cost,
];
$product->users()->attach($userID,$data);
$product->update( [
'cur_cost' => $data['lasted_cost'] ,
'uid' => $user->id
]);
$user->update(['balance' => $user->balance - 1 ]);
$count_down = $product->end_time->diffInSeconds($now_time, false);
if( ($count_down < 0 && $count_down >= (-30)) && $now_time->gte($product->start_time) )
$product->update(['end_time' => $product->end_time->addSeconds(20)]);
}
else
redirect()->back()->with(['msg' => 'Failed']);
return redirect()->back()->with(['msg' => 'Success']);
}
public function storeAuto(Request $request, Product $product)
{
$validate = Validator::make($request->all(),[
'start_cost' => 'required|integer',
'stop_cost' => 'required|integer',
'times' => 'required|integer'
]);
if($validate->fails())
return back()->witherrors($validate)->withInput();
$user = Auth::user();
$auto = $product->users(true)->where('uid', $user->id)->first();
$start_cost = $request->input('start_cost');
$stop_cost = $request->input('stop_cost');
$times = $request->input('times');
$data_auto = [
'start_cost' => $start_cost,
'end_cost' => $stop_cost,
'times' => $times
];
if($start_cost >= 0 && $stop_cost && $start_cost < $stop_cost)
{
if($auto == null)
$product->users(true)->attach($user->id,$data_auto);
else
$auto->pivot->update($data_auto);
}
return redirect()->route('user_interface.show',$product->id);
}
public function deleteAuto(Product $product)
{
$user = Auth::user();
$auto = AuctionAuto::where('uid',Auth::id())->where('pid',$product->id)->get()->first();
if($auto != null)
$auto->delete();
return redirect()->route('user_interface.show',$product->id);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Product;
use App\User;
class Auction extends Model
{
protected $table = 'auction';
protected $fillable = [
'uid', 'pid', 'cost', 'lasted_cost',
];
public function product()
{
return $this->belongsTo('App\Product','pid');
}
public function user()
{
return $this->belongsTo('App\User','uid');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $fillable = [
'uid', 'bid', 'amount', 'user_account', 'coins', 'first_code', 'on',
'user_bankname', 'user_name'
];
public function users()
{
return $this->belongsTo('App\User','uid');
}
public function bank_account()
{
return $this->belongsTo('App\BankAccount','bid');
}
}
<file_sep>step=1 #間隔的秒數
for (( i = 0; i < 60; i=(i+step) )); do
/usr/local/bin/php /home/ibidcomv/public_html/online_bidding/artisan schedule:run
sleep $step
done
exit 0
<file_sep># README #
### 簡介
此為我以前開發過的專案,因已經不再營運便在此留下備份。
此專案為線上競拍系統,使用Laravel開發
### 初始設定
**如有出現錯誤訊息請聯繫工程師**
```shell
//在專案目錄下
composer install
cp .env.example .env
php artisan key:generate
開啟.env設置DB參數
開啟.env設置APP_NAME參數
開啟.env設置APP_ENV=production參數
composer dump-autoload
php artisan migrate
php artisan db:seed
php artisan serve
```
### 更新指令
```shell
composer update
composer dump-autoload
php artisan migrate
php artisan db:seed
php artisan serve
```
### 自動下標使用
**auto-in-seconds.sh**
會每秒執行一次
```
php artisan schedule:run
```
請設置CronTab執行此shell script
```sh
* * * * * sh /path/to/auto_in_seconds.sh
```<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bulletin extends Model
{
protected $fillable = [
'title', 'content', 'on'
];
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Product;
class ClosedController extends Controller
{
public function index()
{
$now_time = Carbon::now();
$closed_products = Product::where('end_time', '<', $now_time)->orderBy('end_time', 'desc')->paginate(3);
//dd($closed_products);
//$temp = ( $closed_products->count() === 0 ) ? 0:1;
foreach($closed_products as $closed_product){
$winner = $closed_product->winner()->first();
if($winner){
$winners[$closed_product->id] = $winner->name;
}else{
$winners[$closed_product->id] = "Người chưa được đấu thầu"; //未有得標者
}
}
foreach($closed_products as $product){
//先取得商品名
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path[$product->id] = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path[$product->id] = '';
//echo $file_path[$product->id]."\n";
}
if($closed_products->count() == 0)
{
$winners = '';
$file_path = '';
}
return view('user.closed', compact('closed_products','winners','file_path'));
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\BankAccount;
class BankAccountTableSeeder extends Seeder {
public function run()
{
$bank_default = [
'account' => '261508408',
'bank_name' => 'ACB chi nhánh bình dương',
'holder_name' => '<NAME>',
];
$bank_account = BankAccount::create($bank_default);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddColumnNamePhoneToProducts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->string('winner_name');
$table->string('winner_phone');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('winner_name');
$table->dropColumn('winner_phone');
});
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use App\User;
use App\Product;
use Auth;
use Session;
class AdminAccountController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('is_adm');
}
/*
* The Main Page
* @return adm.Account, with all users
*/
public function index()
{
//$users = User::all();
//為了自動切分頁,更改了controller
$users = User::where('on','1')->paginate(10);
return view('adm.Account', compact('users'));
}
/*
* Show the details
* @param id, is the user's uid
* @return adm.Account, with one user
*/
public function show(User $user)
{
//$user = User::find($id)->get();
////尚未有新增or編輯頁面,都先以原本的view為主
//原本的view是吃$users所以先將$user替換成$users
//link()的方法也會有問題,所以還是得等之後的頁面,目前暫且放置
return view('adm.EditAccount', compact('user'));
}
/*
* Search user info
* @param search, search for what
* @return search result
*/
public function search(Request $request)
{
$columns = Schema::getColumnListing('users');
$search = $request->input('keyword');
//更改成有分頁寫法的模式
$user = new User;
$where = $user;
//搜詢條件判斷
foreach($columns as $column)
{
$where = $where->orWhere($column,'LIKE','%'.$search.'%');
}
//分頁
$users = $where->paginate(2);
return view('adm.Account', compact('users'));
}
// 管理員 以 使用者身份登入
public function info(User $user)
{
$admId = Auth::id();
Session::put('adm_on', $admId);
Auth::logout();
Auth::login($user);
return redirect()->route('account');
}
public function update(Request $request, User $user)
{
$att = array(
'name' => $request->input('name'),
'realname' => $request->input('realname'),
'phone' => $request->input('phone')
);
$user->update($att);
return back()->with(['msg' => '更新成功']);
}
/*
* Delete user, set column "on" to false
* @param id, id for user
* @return result
*/
public function destroy($id)
{
if($id == Auth::id() && Auth::user()->is_adm)
return redirect()->back()->withErrors(['delete user error : 不可刪除自己']);
$user = User::find($id)->update(['on' => 0]);
//echo "error";
return redirect('/adm/account');
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'HomeController@index')->name('index');
//拍賣規則
Route::get('BidRule', function(){
return view('Rule');
})->name('bid.rule');
//使用者登入驗證功能
Auth::routes();
//註冊確認,使用者同意書
Route::get('register/confirm', function(){
return view('RegisterConfirm');
})->name('register.confirm');
//Email驗證功能
Route::get('send_mail', 'UserAccountController@SendConfirmMail')->name('send_mail');
Route::get('/activation/{token}', 'UserAccountController@EmailTokenConfirm')->name('confirm');
//FB登入功能
Route::get('/redirect/{provider}', 'FBSocialController@redirect')->name('fb.redirect');
Route::get('/callback/{provider}', 'FBSocialController@callback')->name('fb.callback');
////顯示使用者頁面,登入後直接導到這個頁面
//之後改用controller來帶,順便帶資料進來
//Route::get('user', 'PostsController@index')->name('posts.index');
Route::get('/user', 'InterfaceController@index')->name('user_interface');
Route::get('/user/{product}/show', 'InterfaceController@show')->name('user_interface.show');
//使用者資料更新
Route::post('/user/{user}/update', 'AdminAccountController@update')->name('user.update');
//已結標
Route::get('/closed','ClosedController@index')->name('closed');
///////下標頁面
///表單
Route::get('/bidding/{product}','BiddingController@store')->name('bidding');
///儲存表單
Route::post('/bidding/{product}/auto','BiddingController@storeAuto')->name('bidding.auto');
Route::delete('/bidding/{product}/delete', 'BiddingController@deleteAuto')->name('bidauto.cancel');
//帳號狀態
Route::get('/account', 'UserAccountController@index')->name('account');
//結標填寫資料
Route::get('/winner/{product}', 'UserAccountController@create')->name('winner.create');
Route::post('/winner/{product}/end', 'UserAccountController@EndBidding')->name('winner.endbidding');
//儲值頁面
Route::get('/coin', 'UserAccountController@createCoin')->name('coin');
//儲值 建立帳單
Route::post('/coin/make', 'UserAccountController@makeCoinPayment')->name('coin.make');
//儲值 用戶填寫帳戶資料
Route::post('/coin/{payment}/pay', 'UserAccountController@PaymentPay')->name('coin.pay');
//儲值 管理員確認
Route::get('/coin/{payment}/submit', 'SaveController@PaymentSubmit')->name('coin.submit');
//儲值 刪除
Route::delete('/coin/{payment}/delete', 'UserAccountController@CoinCancel')->name('coin.cancel');
//////顯示管理者頁面
////商品管理
//首頁
Route::get('/adm/product', 'AdminProductController@index' )->name('adm_Product');
//顯示
Route::get('/adm/product/{product}/show', 'AdminProductController@show' )->name('adm_Product.show');
//新增表單
Route::get('/adm/product/create', 'AdminProductController@create')->name('adm_Product.create');
//傳送新增表單
Route::post('/adm/product/store', 'AdminProductController@store')->name('adm_Product.store');
//開啟指定表單
Route::get('/adm/product/{product}/edit', 'AdminProductController@edit')->name('adm_Product.edit');
//傳送修改表單
Route::patch('/adm/product/{product}', 'AdminProductController@update')->name('adm_Product.update');
//刪除
Route::delete('/adm/product/{product}', 'AdminProductController@destroy')->name('adm_Product.destroy');
//詳細
Route::get('/adm/product/{product}/details', 'AdminProductController@details')->name('adm_Product.details');
//狀態
Route::get('/adm/product/{product}/status', 'AdminProductController@status')->name('adm_Product.status');
//顯示圖片
Route::get('img/{file_path}', 'HomeController@getImg')->name('img');
////帳號管理
//首頁
Route::get('/adm/account','AdminAccountController@index' )->name('adm_Account');
//搜尋
Route::post('/adm/account/search','AdminAccountController@search' )->name('adm_Search');
//顯示
Route::get('/adm/account/{user}/show', 'AdminAccountController@show' )->name('adm_Account.show');
//以使用者身份登入
Route::get('/adm/account/{user}/info', 'AdminAccountController@info' )->name('adm_Account.info');
//刪除
Route::delete('/adm/account/{id}', 'AdminAccountController@destroy')->name('adm_Account.destroy');
////公告管理
//首頁
Route::get('/adm/bulletin', 'BulletinController@index')->name('adm_Bulletin');
//顯示
Route::get('/adm/bulletin/{bulletin}/show', 'BulletinController@show' )->name('adm_Bulletin.show');
//新增表單
Route::get('/adm/bulletin/create', 'BulletinController@create')->name('adm_Bulletin.create');
//傳送新增表單
Route::post('/adm/bulletin/store', 'BulletinController@store')->name('adm_Bulletin.store');
//開啟指定表單
Route::get('/adm/bulletin/{bulletin}/edit', 'BulletinController@edit')->name('adm_Bulletin.edit');
//傳送修改表單
Route::patch('/adm/bulletin/{bulletin}', 'BulletinController@update')->name('adm_Bulletin.update');
//刪除
Route::delete('/adm/bulletin/{bulletin}', 'BulletinController@destroy')->name('adm_Bulletin.destroy');
//首頁顯示詳細 彈出式視窗連結
Route::get('/adm/bulletin/{bulletin}/content', 'BulletinController@contents')->name('adm_Bulletin.content');
//加值紀錄
//首頁
Route::get('/adm/save', 'SaveController@index')->name('adm_Save');
//footer
//關於我們
Route::get('/aboutus', function () {
return view('AboutUs');
})->name('aboutus');
//問與答
Route::get('/fq', function () {
return view('FQ');
})->name('fq');
//服務條款
Route::get('/service', function () {
return view('Service');
})->name('service');
//隱私政策
Route::get('/privacy', function () {
return view('Privacy');
})->name('privacy');
//聯繫我們
Route::get('ContactUs', function(){
return view('ContactUs');
})->name('contact_us');
//Auth::routes();
//Route::get('/home', 'HomeController@index')->name('home');
//Route::resource('admin','AdminController');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Payment;
use App\User;
class SaveController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$payments = Payment::paginate(10);
return view('adm.Save', compact('payments'));
}
public function PaymentSubmit(Payment $payment)
{
$user = $payment->users;
$coins = $payment->coins;
if($payment->first_code)
{
$coins = $coins + 10;
$giver = User::where('code', $user->recommand_code)->get()->first();
if ($giver != null) {
$giver->update(['balance' => $giver->balance + 10]);
}
}
$payment->update(['on' => false]);
$user->update(['balance' => $user->balance + $coins]);
return redirect()->route('adm_Save');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EmailConfirm extends Model
{
protected $table = 'email_confirm';
protected $fillable = [
'uid', 'confirm_token', 'expired'
];
public function user()
{
return $this->belongsTo('App\User', 'uid');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'detail', 'cost', 'cur_cost',
'view_time', 'start_time', 'end_time',
'uid', 'discount', 'status', 'address',
'message', 'origin_price', 'nickname_changed'
];
protected $dates = ['view_time', 'start_time', 'end_time'];
/*
* get User, many to many, using relationship Auction
* @param mode, 1 is auto, 0 is not
*/
public function auctions()
{
return $this->hasMany('App\Auction','pid');
}
public function users($mode = NULL)
{
if($mode)
return $this->belongsToMany('App\User','auction_auto','pid','uid')
->withPivot('start_cost','end_cost','times')
->withTimestamps();
else
return $this->belongsToMany('App\User','auction','pid','uid')
->withPivot('cost','lasted_cost')
->withTimestamps();
}
public function winner()
{
return $this->belongsTo('App\User','uid');
}
}
<file_sep><?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\AuctionAuto;
use Carbon\Carbon;
use DB;
class Auto extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'auction:auto';
/**
* The console command description.
*
* @var string
*/
protected $description = '自動下標功能';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// DB::table('temp_log')->insert(['echos' => 'Begins']);
$autos = AuctionAuto::where('times','>','0')->orderBy('id', 'asc')->get();
$time = Carbon::now();
$diff_this_time = array();
foreach($autos as $auto)
{
$product = $auto->product; //產品
if($product == null || $product->end_time < $time || $auto->end_cost < $product->cur_cost)
{
$auto->delete();
continue;
}
$user = $auto->user; //使用者
if($product->uid == $user->id)
continue;
$auto_start = $product->end_time->diffInSeconds($time,false); //時間相差
$diff_this_time = array_add($diff_this_time, $product->id, $auto_start);
if( ($diff_this_time[$product->id] < 0 && $diff_this_time[$product->id] >= (-30)) && ($time >= $product->start_time) && ($user->balance > 0) )
{
if ( ($product->cur_cost >= $auto->start_cost) && ($product->cur_cost + $product->cost <= $auto->end_cost))
{
$auto->update( ['times' => ($auto->times - 1) ] ); //次數-1
$product->users()->attach($user->id, [
'cost' => $product->cost, //下標金額
'lasted_cost' => $product->cur_cost + $product->cost //後標後金額
]);
$product->update([
'uid' => $user->id,
'cur_cost' => ($product->cur_cost + $product->cost), //目前最高金額
'end_time' => $product->end_time->addSeconds(20) //倒數階段加時
]);
$user->update([ 'balance' => $user->balance - 1 ]); //代幣-1
}
}
}
}
}
<file_sep>let coin = document.querySelectorAll("#coin");
console.log(coin[0]);
for(let i=0; i<7; i++)
{
let flag=0;
coin[i].addEventListener('click', click_effect, false);
function click_effect(){
if(flag==0){
coin[i].classList.add("coin-box-after");
flag=1;
}
else{
coin[i].classList.remove("coin-box-after");
flag=0;
}
console.log("click");
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddColumnBidUserAccountToPayments extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('payments', function (Blueprint $table) {
$table->string('user_account');
$table->integer('bid');
$table->dropColumn('method');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('payments', function (Blueprint $table) {
$table->dropColumn('user_account');
$table->dropColumn('bid');
$table->string('method');
});
}
}
<file_sep><?php
header("Location: https://i-bid.com.vn/online_bidding/public");
exit();
?><file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use App\User;
use App\Product;
use App\Payment;
use App\BankAccount;
use App\EmailConfirm;
use Validator;
class UserAccountController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user();
$auctions = $user->products()->orderBy('auction.created_at', 'desc')->get();
$winners = $user->winner_product()->where('end_time','<',Carbon::now())->orderBy('created_at', 'desc')->get();
//dd($winners);
return view('user.account', compact('user', 'auctions', 'winners') );
}
public function create(Product $product)
{
return view('EndBiddingDetail', compact('product'));
}
public function EndBidding(Request $request, Product $product)
{
$v = Validator::make($request->all(),[
'name' => 'required',
'phone' => 'required',
'address' => 'required',
'message' => 'required'
]);
if($v->fails())
return back()->withErrors($v)->withInput();
$user = Auth::user();
$att['winner_name'] = $request->input('name');
$att['winner_phone'] = $request->input('phone');
$att['address'] = $request->input('address');
$att['message'] = $request->input('message');
$product->update($att);
return redirect()->route('account');
}
// 以下為使用者儲值
public function createCoin()
{
$payment = Auth::user()->payments()->where('user_bankname',"")->Where('user_name',"")->Where('user_account',"Not Done Yet")->get()->first();
if($payment == null)
return view('user.coin');
else
{
$bank_account = $payment->bank_account;
return view('CoinPayment', compact('bank_account','payment'));
}
}
public function makeCoinPayment(Request $request)
{
$user = Auth::user();
$coins = $request->input('coin') ;
$code = $request->input('code');
$amount = $coins * 30000;
$first_code = false;
$bank_account = BankAccount::find(rand(1,BankAccount::count()));
if($code != NULL)
{
if( User::where('code', $code)->get()->count() && $user->recommand_code === "" )
{
$user->update(['recommand_code' => $code]);
$first_code = true;
}
else
return redirect()->back()->with('msg','Mã đến không chính xác');
}
else if ($user->recommand_code == '')
{
$user->update(['recommand_code' => 'first_nothing']);
$first_code = false;
}
else if ($user->recommand_code == 'first_nothing')
{
$user->update(['recommand_code' => 'nothing']);
$first_code = false;
}
$payment = Payment::create([
'bid' => $bank_account->id,
'uid' => $user->id,
'coins' => $coins,
'amount' => $amount,
'user_account' => 'Not Done Yet',
'first_code' => $first_code
]);
//echo $payment->coins . " " . $coins;
return view('CoinPayment', compact('bank_account', 'payment'));
}
public function PaymentPay(Request $request, Payment $payment)
{
$user_account = $request->input('user_account') ? : 'NULL';
$user_bankname = $request->input('user_bankname') ? : 'NULL';
$user_name = $request->input('user_name') ? : 'NULL';
$payment->update([
'user_account' => $user_account,
'user_bankname' => $user_bankname,
'user_name' => $user_name
]);
return redirect()->route('account');
}
public function SendConfirmMail()
{
$token = Str::random(20);
$user = Auth::user();
$confirm_new = new EmailConfirm;
$confirm_new->uid = $user->id;
$confirm_new->confirm_token = $token;
$confirm_new->expired = Carbon::tomorrow();
$confirm_new->save();
$subject = "Email Verification";
$receiver = $user->email;
$content = [
"token" => $token,
"user_name" => $user->name,
"user_email" => $user->email,
];
Mail::send('mail.email_confirm', $content, function($message) use ($subject, $receiver)
{
$message->from("<EMAIL>", 'I-Bid');
$message->to($receiver)
->subject($subject);
});
return redirect()->back()->with('msg', 'Mail Sended!');
}
public function EmailTokenConfirm($token)
{
$user = Auth::user();
$email = EmailConfirm::where('confirm_token', $token)
->where('expired', '>=', Carbon::now())
->where('uid', $user->id)
->first();
if($email != null)
{
$user->update(['email_confirm' => true]);
$email->delete();
return redirect('account')->with('msg', 'Verification Done!');
}
return redirect('account');
}
public function CoinCancel(Payment $payment)
{
//echo $payment;
$payment->delete();
if( Auth::user()->recommand_code === 'first_nothing' )
Auth::user()->update(['recommand_code' => '']);
return redirect()->route('account');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use App\Bulletin;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$products = Product::where('view_time','<=',Carbon::now())->where('end_time','>=',Carbon::now())->paginate(3);
$bulletins = Bulletin::where('on','1')->get();
$now_time = Carbon::now();
foreach($products as $product){
//先取得商品名
$files = get_files(storage_path('app/public/products/'.$product->id));
//$pics[$product->id] = $files;
//取得完整路徑,並將路徑改寫,url會把 / 判定錯誤
if($files != NULL)
$file_path[$product->id] = str_replace('/','&',storage_path('app/public/products/'.$product["id"].'/'.$files[0]));
else
$file_path[$product->id] = '';
//echo $file_path[$product->id]."\n";
}
//如果沒有進行中拍賣,給file_path一個null防error
if(!isset($file_path)) $file_path='';
return view('index', compact('products','file_path','bulletins','now_time'));
}
public function getImg($file_path)
{
//dd($file_path);
$file_path = str_replace('&','/',$file_path); //斜線不可以在URL中傳
//echo $file_path;
$file = File::get($file_path);
$type = File::mimeType($file_path);
//echo $type;
return response($file)->header("Content-Type", $type);
}
}
|
4266ab2b02a06c1a4596d96af14d3b9ec9241785
|
[
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 31
|
PHP
|
helomair/online_bidding_backup
|
a7f50b25347b321c537df239b34cdf9767accbd6
|
af022a681d666bbdd7d80c548896a528007cc537
|
refs/heads/master
|
<repo_name>djcadaniel/CURSO-DE-JS-BASICO---PLATZI<file_sep>/some.js
var articulos = [
{ nombre: "bici", costo: 3000},
{ nombre: "tv", costo: 2500 },
{ nombre: "libro",costo:320 },
{ nombre: "celular",costo:10000 },
{ nombre: "laptop",costo:20000},
{ nombre: "teclado",costo:500 },
{ nombre: "audifonos",costo:1700 }
]
var articulosBaratos = articulos.some(function(art){
return art.costo <= 700
})<file_sep>/forEach.js
//mi array contiene a objetos
var articulos = [
{ nombre: "bici", costo: 3000},
{ nombre: "tv", costo: 2500 },
{ nombre: "libro",costo:320 },
{ nombre: "celular",costo:10000 },
{ nombre: "laptop",costo:20000},
{ nombre: "teclado",costo:500 },
{ nombre: "audifonos",costo:1700 }
]
var art = articulos.forEach(function(arti){
console.log(arti.nombre)
})<file_sep>/pop.js
//elimina el ultimo elemento de un array
var animales = ["leon","perro","loro"];
var shiftAnimales = animales.pop();<file_sep>/pushString.js
let txtArray = ["daniel","maria","nera","coco"];
function addCharacters(){
txtArray.push("magno","constantino");
console.log(txtArray);
}<file_sep>/1.JuegoPiedraPapelTijera/game.js
var piedra = 3;
var tijera = 2;
var papel = 1;
function game(yo,cpu){
if(((yo == 'piedra') && (cpu == 'piedra'))){
console.log('empate');
}else if(((yo == 'piedra') && (cpu == 'papel'))){
console.log('gana usuario');
}else if(((yo == 'piedra') && (cpu == 'tijera'))){
console.log('gana usuario');
}
<file_sep>/shift.js
//Elimina el primer elemento de un array
let array = [1,2,3,4,5];
let ShiftArray = array.shift();
<file_sep>/PUSH.JS
//agrega uno o mas elementos al final de un array
let numArray = [1,2,3,4,5];
function newNum(){
numArray.push(6,7)
console.log(numArray)
}<file_sep>/3.funciones.js
//declarativas
function miFuncion(){
return 3;
}
miFuncion();
//expresion
var miFunction = function(){
return a + b
}
miFuncion();<file_sep>/find.js
//mi array contiene a objetos
var articulos = [
{ nombre : "bici", costo:3000 },
{ nombre: "tv", costo: 2500 },
{ nombre: "libro",costo:320 },
{ nombre: "celular",costo:10000 },
{ nombre: "laptop",costo:20000},
{ nombre: "teclado",costo:500 },
{ nombre: "audifonos",costo:1700 }
]
var nuevoArticulo = articulos.find(function(arti){
return arti.nombre === "laptop"
})<file_sep>/recorridoFindForeachSome.js
var articulos = [
{ nombre:"Bici", costo: 3000},
{nombre: "tv", costo: 2500},
{nombre: "libro", costo: 10000},
{nombre:"celular", costo: 320},
{nombre:"laptop", costo:20000},
{nombre:"audifonos", costo:1700}
]
//FIND
var encuentraArticulo = articulos.find(function(articulo){
return articulo.nombre === "laptop";
});
//FOREACH
articulos.forEach(function(articulo){
console.log(articulo.nombre);
})
//SOME --- devuelve si es v o f
var articulosBaratos = articulos.some(function(articulo){
return articulo.costo <= 700;
})<file_sep>/2.Funcion constructorade30carros/autos.js
auto = {
marca : 'toyota',
color : 'azul'
}
function miAuto(m,c){
this.marca = m;
this.color = c;
}
var carros =[];
function ver(){
var cantidad = prompt('Ingrese cantidad de autos');
for(var i=0; i<cantidad; i++){
var mar = prompt('Ingresa la marca del carro:');
var col = prompt('Ingresa el color del carro:');
carros.push(new miAuto(mar, col));
}
for(car of carros){
console.log(carros);
}
} <file_sep>/8.objeto.js
var miAuto = {
marca : "Toyota",
modelo : "Corolla",
anio: 2020,
detalleAuto: function(){
console.log(`Auto ${this.modelo} ${this.anio}`)
}
}
//para traer a los valores del objeto
miAuto.marca
miAuto.detalleAuto()
<file_sep>/RetoCarros3.js
var n = prompt("¿Cuántos carros deseas añadr?");
var autoNuevo= [];
function auto(marca,modelo,anio){
this.marca = marca,
this.modelo = modelo,
this.anio = anio
}
for(var i = 0; i < n; i++){
var marca = prompt("Marca:");
var modelo = prompt("Modelo:");
var anio = prompt("Año:");
autoNuevo[i] = new auto(marca,modelo,anio);
autoNuevo
}
<file_sep>/5.arrays.js
var paises = ['Perú', 'Lima', 'EE.UU']
var masPaises = paises.push("Colombia")
console.log(paises)
var paises = ["Perú", "Lima", "EE.UU"]
varMenosPaises = paises.pop()
console.log(paises)
var mascotas = ["manchas","negro","guapo"]
var agregarPrimero = mascotas.unshift("cuto")
console.log(mascotas)
var mascotas = ["manchas","negro","guapo"]
var nuevasMacotas = mascotas.shift()
console.log(mascotas)
var mascotas = ["manchas","negro","guapo"]
var nuevasMacotas = mascotas.indexOf("manchas")
console.log(nuevasMacotas)
<file_sep>/if.js
if(true){
console.log("hola mundo");
}
//operador ternario
condition ? true : false
var numero = 1;
var resultado = numero === 1 ? "si soy uno" : "no soy uno";
//piedra papel o tijera
var piedra = 3;
var papel = 2;
var tijera = 1;
var juego = function(yo, cpu){
if((yo == piedra && cpu == papel)||(yo == piedra && cpu == tijera) || (yo == tijera && cpu == papel)){
console.log("gano usuario");
}else if((yo == piedra && cpu == piedra)||(yo == tijera && cpu == tijera)||(yo == papel && cpu == papel)){
console.log("empate");
}else if((cpu == piedra && yo == papel)||(cpu == piedra && yo == tijera) || (yo == papel && cpu == tijera)){
console.log("gana cpu");
}
}
<file_sep>/9.construct.js
var miAuto = {
marca : "Toyota",
modelo : "Corolla",
annio : 2020,
detalleDelAuto : function(){
console.log(`Auto: ${this.marca} ${this.modelo}`)
}
}
//function constructora
function auto(marca,modelo,anio){
this.marca = marca,
this.modelo = modelo,
this.anio = anio
}
var autoNuevo = new auto("tesla","model 3",2020)
var autoNuevo2 = new auto("tesla","model x",2021)
//crear automaticamente 30 carros
var tot = 2
var count = 0
function auto(marca,modelo,anio){
this.marca = marca,
this.modelo = modelo,
this.anio = anio
}
while(tot > count){
var marca = prompt("marca:")
var modelo = prompt("marca:")
var anio = prompt("marca:")
var autoNuevo = new auto(marca,modelo,anio)
count += 1
}<file_sep>/recorrido-filter.js
//mi array contiene a objetos
var articulos = [
{ nombre : "bici", costo:3000 },
{ nombre: "tv", costo: 2500 },
{ nombre: "libro",costo:320 },
{ nombre: "celular",costo:10000 },
{ nombre: "laptop",costo:20000},
{ nombre: "teclado",costo:500 },
{ nombre: "audifonos",costo:1700 }
]
//filter genera un nuevo array, filtrara cosas si es verdad o falso, lo mete en un nuevo array
var articulosFiltrados = articulos.filter(function(articulo){
return articulo.costo <= 500
})
// var auto = {
// color: "azul",
// anio: 2007,
// modelo: "optra",
// marca: "chevrolet"
// }
// function miAuto(color, anio, modelo, marca){
// this.color = color;
// this.anio = anio;
// this.modelo = modelo;
// this.marca = marca;
// }
// var autoNuevo1 = new miAuto("blue",2010, "nisan","toyota");<file_sep>/RetoCarrosConstructora.js
var auto = {
marca : "nissan",
color: "azul",
precio: 35000
}
function newAuto(marca, color, precio){
this.marca = marca;
this.color = color;
this.precio = precio;
}
var auto1 = new newAuto("toyota","rojo",3500);
var arrayAuto = auto1;
//para que se repitan
for(var i=0; i<=30; i++){
console.log(arrayAuto);
}
//para ingresar los parametros seria asi:
var carro=[];
cantidad = prompt("Ingresa cantidad");
for(var a=0; a<=cantidad-1; a++){
marca = prompt("Ingresa marca");
color = prompt("Ingresa color");
precio = prompt("Ingresa precio");
carro[] = new newAuto(marca, color, precio);
}
|
59a5219d3fbb0b6afddefc44bb59c4962a95d2d3
|
[
"JavaScript"
] | 18
|
JavaScript
|
djcadaniel/CURSO-DE-JS-BASICO---PLATZI
|
a01e0e5a8d9b54be5cf8948e64ffe8e4e6ead800
|
f3077db754b924e6373be66b1b419e315855e8d4
|
refs/heads/master
|
<file_sep>import { NgModule } from '@angular/core';
import { MilAppNewSharedLibsModule, FindLanguageFromKeyPipe, JhiAlertComponent, JhiAlertErrorComponent } from './';
@NgModule({
imports: [MilAppNewSharedLibsModule],
declarations: [FindLanguageFromKeyPipe, JhiAlertComponent, JhiAlertErrorComponent],
exports: [MilAppNewSharedLibsModule, FindLanguageFromKeyPipe, JhiAlertComponent, JhiAlertErrorComponent]
})
export class MilAppNewSharedCommonModule {}
<file_sep>package com.mycompany.myapp.service.mapper;
import com.mycompany.myapp.domain.*;
import com.mycompany.myapp.service.dto.PromotionDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Promotion and its DTO PromotionDTO.
*/
@Mapper(componentModel = "spring", uses = {StudentMapper.class})
public interface PromotionMapper extends EntityMapper<PromotionDTO, Promotion> {
@Mapping(source = "student.id", target = "studentId")
@Mapping(source = "student.fullName", target = "studentFullName")
PromotionDTO toDto(Promotion promotion);
@Mapping(source = "studentId", target = "student")
Promotion toEntity(PromotionDTO promotionDTO);
default Promotion fromId(Long id) {
if (id == null) {
return null;
}
Promotion promotion = new Promotion();
promotion.setId(id);
return promotion;
}
}
<file_sep>package com.mycompany.myapp.service.dto;
import java.time.LocalDate;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import com.mycompany.myapp.domain.enumeration.Vus;
import com.mycompany.myapp.domain.enumeration.Progremm;
import com.mycompany.myapp.domain.enumeration.Status;
/**
* A DTO for the Student entity.
*/
public class StudentDTO implements Serializable {
private Long id;
@NotNull
@Size(max = 40)
private String fullName;
private LocalDate dateOfBirth;
private LocalDate universityIn;
private LocalDate univesityOut;
private Vus vus;
private String universityName;
private String speciality;
private String studyGroup;
private String platoonNumber;
private Progremm programm;
private Status status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public LocalDate getUniversityIn() {
return universityIn;
}
public void setUniversityIn(LocalDate universityIn) {
this.universityIn = universityIn;
}
public LocalDate getUnivesityOut() {
return univesityOut;
}
public void setUnivesityOut(LocalDate univesityOut) {
this.univesityOut = univesityOut;
}
public Vus getVus() {
return vus;
}
public void setVus(Vus vus) {
this.vus = vus;
}
public String getUniversityName() {
return universityName;
}
public void setUniversityName(String universityName) {
this.universityName = universityName;
}
public String getSpeciality() {
return speciality;
}
public void setSpeciality(String speciality) {
this.speciality = speciality;
}
public String getStudyGroup() {
return studyGroup;
}
public void setStudyGroup(String studyGroup) {
this.studyGroup = studyGroup;
}
public String getPlatoonNumber() {
return platoonNumber;
}
public void setPlatoonNumber(String platoonNumber) {
this.platoonNumber = platoonNumber;
}
public Progremm getProgramm() {
return programm;
}
public void setProgramm(Progremm programm) {
this.programm = programm;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StudentDTO studentDTO = (StudentDTO) o;
if (studentDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), studentDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "StudentDTO{" +
"id=" + getId() +
", fullName='" + getFullName() + "'" +
", dateOfBirth='" + getDateOfBirth() + "'" +
", universityIn='" + getUniversityIn() + "'" +
", univesityOut='" + getUnivesityOut() + "'" +
", vus='" + getVus() + "'" +
", universityName='" + getUniversityName() + "'" +
", speciality='" + getSpeciality() + "'" +
", studyGroup='" + getStudyGroup() + "'" +
", platoonNumber='" + getPlatoonNumber() + "'" +
", programm='" + getProgramm() + "'" +
", status='" + getStatus() + "'" +
"}";
}
}
<file_sep>package com.mycompany.myapp.service.mapper;
import com.mycompany.myapp.domain.*;
import com.mycompany.myapp.service.dto.ContactsDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Contacts and its DTO ContactsDTO.
*/
@Mapper(componentModel = "spring", uses = {StudentMapper.class})
public interface ContactsMapper extends EntityMapper<ContactsDTO, Contacts> {
@Mapping(source = "student.id", target = "studentId")
@Mapping(source = "student.fullName", target = "studentFullName")
ContactsDTO toDto(Contacts contacts);
@Mapping(source = "studentId", target = "student")
Contacts toEntity(ContactsDTO contactsDTO);
default Contacts fromId(Long id) {
if (id == null) {
return null;
}
Contacts contacts = new Contacts();
contacts.setId(id);
return contacts;
}
}
<file_sep>package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.MilAppNewApp;
import com.mycompany.myapp.domain.Disciplines;
import com.mycompany.myapp.domain.Student;
import com.mycompany.myapp.repository.DisciplinesRepository;
import com.mycompany.myapp.repository.search.DisciplinesSearchRepository;
import com.mycompany.myapp.service.DisciplinesService;
import com.mycompany.myapp.service.dto.DisciplinesDTO;
import com.mycompany.myapp.service.mapper.DisciplinesMapper;
import com.mycompany.myapp.web.rest.errors.ExceptionTranslator;
import com.mycompany.myapp.service.dto.DisciplinesCriteria;
import com.mycompany.myapp.service.DisciplinesQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;
import static com.mycompany.myapp.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the DisciplinesResource REST controller.
*
* @see DisciplinesResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MilAppNewApp.class)
public class DisciplinesResourceIntTest {
private static final String DEFAULT_DISCIPLINE = "AAAAAAAAAA";
private static final String UPDATED_DISCIPLINE = "BBBBBBBBBB";
private static final String DEFAULT_TEACHER_NAME = "AAAAAAAAAA";
private static final String UPDATED_TEACHER_NAME = "BBBBBBBBBB";
private static final Double DEFAULT_MARK = 1D;
private static final Double UPDATED_MARK = 2D;
private static final LocalDate DEFAULT_MARK_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_MARK_DATE = LocalDate.now(ZoneId.systemDefault());
@Autowired
private DisciplinesRepository disciplinesRepository;
@Autowired
private DisciplinesMapper disciplinesMapper;
@Autowired
private DisciplinesService disciplinesService;
/**
* This repository is mocked in the com.mycompany.myapp.repository.search test package.
*
* @see com.mycompany.myapp.repository.search.DisciplinesSearchRepositoryMockConfiguration
*/
@Autowired
private DisciplinesSearchRepository mockDisciplinesSearchRepository;
@Autowired
private DisciplinesQueryService disciplinesQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restDisciplinesMockMvc;
private Disciplines disciplines;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final DisciplinesResource disciplinesResource = new DisciplinesResource(disciplinesService, disciplinesQueryService);
this.restDisciplinesMockMvc = MockMvcBuilders.standaloneSetup(disciplinesResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Disciplines createEntity(EntityManager em) {
Disciplines disciplines = new Disciplines()
.discipline(DEFAULT_DISCIPLINE)
.teacherName(DEFAULT_TEACHER_NAME)
.mark(DEFAULT_MARK)
.markDate(DEFAULT_MARK_DATE);
return disciplines;
}
@Before
public void initTest() {
disciplines = createEntity(em);
}
@Test
@Transactional
public void createDisciplines() throws Exception {
int databaseSizeBeforeCreate = disciplinesRepository.findAll().size();
// Create the Disciplines
DisciplinesDTO disciplinesDTO = disciplinesMapper.toDto(disciplines);
restDisciplinesMockMvc.perform(post("/api/disciplines")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(disciplinesDTO)))
.andExpect(status().isCreated());
// Validate the Disciplines in the database
List<Disciplines> disciplinesList = disciplinesRepository.findAll();
assertThat(disciplinesList).hasSize(databaseSizeBeforeCreate + 1);
Disciplines testDisciplines = disciplinesList.get(disciplinesList.size() - 1);
assertThat(testDisciplines.getDiscipline()).isEqualTo(DEFAULT_DISCIPLINE);
assertThat(testDisciplines.getTeacherName()).isEqualTo(DEFAULT_TEACHER_NAME);
assertThat(testDisciplines.getMark()).isEqualTo(DEFAULT_MARK);
assertThat(testDisciplines.getMarkDate()).isEqualTo(DEFAULT_MARK_DATE);
// Validate the Disciplines in Elasticsearch
verify(mockDisciplinesSearchRepository, times(1)).save(testDisciplines);
}
@Test
@Transactional
public void createDisciplinesWithExistingId() throws Exception {
int databaseSizeBeforeCreate = disciplinesRepository.findAll().size();
// Create the Disciplines with an existing ID
disciplines.setId(1L);
DisciplinesDTO disciplinesDTO = disciplinesMapper.toDto(disciplines);
// An entity with an existing ID cannot be created, so this API call must fail
restDisciplinesMockMvc.perform(post("/api/disciplines")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(disciplinesDTO)))
.andExpect(status().isBadRequest());
// Validate the Disciplines in the database
List<Disciplines> disciplinesList = disciplinesRepository.findAll();
assertThat(disciplinesList).hasSize(databaseSizeBeforeCreate);
// Validate the Disciplines in Elasticsearch
verify(mockDisciplinesSearchRepository, times(0)).save(disciplines);
}
@Test
@Transactional
public void getAllDisciplines() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList
restDisciplinesMockMvc.perform(get("/api/disciplines?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(disciplines.getId().intValue())))
.andExpect(jsonPath("$.[*].discipline").value(hasItem(DEFAULT_DISCIPLINE.toString())))
.andExpect(jsonPath("$.[*].teacherName").value(hasItem(DEFAULT_TEACHER_NAME.toString())))
.andExpect(jsonPath("$.[*].mark").value(hasItem(DEFAULT_MARK.doubleValue())))
.andExpect(jsonPath("$.[*].markDate").value(hasItem(DEFAULT_MARK_DATE.toString())));
}
@Test
@Transactional
public void getDisciplines() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get the disciplines
restDisciplinesMockMvc.perform(get("/api/disciplines/{id}", disciplines.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(disciplines.getId().intValue()))
.andExpect(jsonPath("$.discipline").value(DEFAULT_DISCIPLINE.toString()))
.andExpect(jsonPath("$.teacherName").value(DEFAULT_TEACHER_NAME.toString()))
.andExpect(jsonPath("$.mark").value(DEFAULT_MARK.doubleValue()))
.andExpect(jsonPath("$.markDate").value(DEFAULT_MARK_DATE.toString()));
}
@Test
@Transactional
public void getAllDisciplinesByDisciplineIsEqualToSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where discipline equals to DEFAULT_DISCIPLINE
defaultDisciplinesShouldBeFound("discipline.equals=" + DEFAULT_DISCIPLINE);
// Get all the disciplinesList where discipline equals to UPDATED_DISCIPLINE
defaultDisciplinesShouldNotBeFound("discipline.equals=" + UPDATED_DISCIPLINE);
}
@Test
@Transactional
public void getAllDisciplinesByDisciplineIsInShouldWork() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where discipline in DEFAULT_DISCIPLINE or UPDATED_DISCIPLINE
defaultDisciplinesShouldBeFound("discipline.in=" + DEFAULT_DISCIPLINE + "," + UPDATED_DISCIPLINE);
// Get all the disciplinesList where discipline equals to UPDATED_DISCIPLINE
defaultDisciplinesShouldNotBeFound("discipline.in=" + UPDATED_DISCIPLINE);
}
@Test
@Transactional
public void getAllDisciplinesByDisciplineIsNullOrNotNull() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where discipline is not null
defaultDisciplinesShouldBeFound("discipline.specified=true");
// Get all the disciplinesList where discipline is null
defaultDisciplinesShouldNotBeFound("discipline.specified=false");
}
@Test
@Transactional
public void getAllDisciplinesByTeacherNameIsEqualToSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where teacherName equals to DEFAULT_TEACHER_NAME
defaultDisciplinesShouldBeFound("teacherName.equals=" + DEFAULT_TEACHER_NAME);
// Get all the disciplinesList where teacherName equals to UPDATED_TEACHER_NAME
defaultDisciplinesShouldNotBeFound("teacherName.equals=" + UPDATED_TEACHER_NAME);
}
@Test
@Transactional
public void getAllDisciplinesByTeacherNameIsInShouldWork() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where teacherName in DEFAULT_TEACHER_NAME or UPDATED_TEACHER_NAME
defaultDisciplinesShouldBeFound("teacherName.in=" + DEFAULT_TEACHER_NAME + "," + UPDATED_TEACHER_NAME);
// Get all the disciplinesList where teacherName equals to UPDATED_TEACHER_NAME
defaultDisciplinesShouldNotBeFound("teacherName.in=" + UPDATED_TEACHER_NAME);
}
@Test
@Transactional
public void getAllDisciplinesByTeacherNameIsNullOrNotNull() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where teacherName is not null
defaultDisciplinesShouldBeFound("teacherName.specified=true");
// Get all the disciplinesList where teacherName is null
defaultDisciplinesShouldNotBeFound("teacherName.specified=false");
}
@Test
@Transactional
public void getAllDisciplinesByMarkIsEqualToSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where mark equals to DEFAULT_MARK
defaultDisciplinesShouldBeFound("mark.equals=" + DEFAULT_MARK);
// Get all the disciplinesList where mark equals to UPDATED_MARK
defaultDisciplinesShouldNotBeFound("mark.equals=" + UPDATED_MARK);
}
@Test
@Transactional
public void getAllDisciplinesByMarkIsInShouldWork() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where mark in DEFAULT_MARK or UPDATED_MARK
defaultDisciplinesShouldBeFound("mark.in=" + DEFAULT_MARK + "," + UPDATED_MARK);
// Get all the disciplinesList where mark equals to UPDATED_MARK
defaultDisciplinesShouldNotBeFound("mark.in=" + UPDATED_MARK);
}
@Test
@Transactional
public void getAllDisciplinesByMarkIsNullOrNotNull() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where mark is not null
defaultDisciplinesShouldBeFound("mark.specified=true");
// Get all the disciplinesList where mark is null
defaultDisciplinesShouldNotBeFound("mark.specified=false");
}
@Test
@Transactional
public void getAllDisciplinesByMarkDateIsEqualToSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where markDate equals to DEFAULT_MARK_DATE
defaultDisciplinesShouldBeFound("markDate.equals=" + DEFAULT_MARK_DATE);
// Get all the disciplinesList where markDate equals to UPDATED_MARK_DATE
defaultDisciplinesShouldNotBeFound("markDate.equals=" + UPDATED_MARK_DATE);
}
@Test
@Transactional
public void getAllDisciplinesByMarkDateIsInShouldWork() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where markDate in DEFAULT_MARK_DATE or UPDATED_MARK_DATE
defaultDisciplinesShouldBeFound("markDate.in=" + DEFAULT_MARK_DATE + "," + UPDATED_MARK_DATE);
// Get all the disciplinesList where markDate equals to UPDATED_MARK_DATE
defaultDisciplinesShouldNotBeFound("markDate.in=" + UPDATED_MARK_DATE);
}
@Test
@Transactional
public void getAllDisciplinesByMarkDateIsNullOrNotNull() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where markDate is not null
defaultDisciplinesShouldBeFound("markDate.specified=true");
// Get all the disciplinesList where markDate is null
defaultDisciplinesShouldNotBeFound("markDate.specified=false");
}
@Test
@Transactional
public void getAllDisciplinesByMarkDateIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where markDate greater than or equals to DEFAULT_MARK_DATE
defaultDisciplinesShouldBeFound("markDate.greaterOrEqualThan=" + DEFAULT_MARK_DATE);
// Get all the disciplinesList where markDate greater than or equals to UPDATED_MARK_DATE
defaultDisciplinesShouldNotBeFound("markDate.greaterOrEqualThan=" + UPDATED_MARK_DATE);
}
@Test
@Transactional
public void getAllDisciplinesByMarkDateIsLessThanSomething() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
// Get all the disciplinesList where markDate less than or equals to DEFAULT_MARK_DATE
defaultDisciplinesShouldNotBeFound("markDate.lessThan=" + DEFAULT_MARK_DATE);
// Get all the disciplinesList where markDate less than or equals to UPDATED_MARK_DATE
defaultDisciplinesShouldBeFound("markDate.lessThan=" + UPDATED_MARK_DATE);
}
@Test
@Transactional
public void getAllDisciplinesByStudentIsEqualToSomething() throws Exception {
// Initialize the database
Student student = StudentResourceIntTest.createEntity(em);
em.persist(student);
em.flush();
disciplines.setStudent(student);
disciplinesRepository.saveAndFlush(disciplines);
Long studentId = student.getId();
// Get all the disciplinesList where student equals to studentId
defaultDisciplinesShouldBeFound("studentId.equals=" + studentId);
// Get all the disciplinesList where student equals to studentId + 1
defaultDisciplinesShouldNotBeFound("studentId.equals=" + (studentId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultDisciplinesShouldBeFound(String filter) throws Exception {
restDisciplinesMockMvc.perform(get("/api/disciplines?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(disciplines.getId().intValue())))
.andExpect(jsonPath("$.[*].discipline").value(hasItem(DEFAULT_DISCIPLINE)))
.andExpect(jsonPath("$.[*].teacherName").value(hasItem(DEFAULT_TEACHER_NAME)))
.andExpect(jsonPath("$.[*].mark").value(hasItem(DEFAULT_MARK.doubleValue())))
.andExpect(jsonPath("$.[*].markDate").value(hasItem(DEFAULT_MARK_DATE.toString())));
// Check, that the count call also returns 1
restDisciplinesMockMvc.perform(get("/api/disciplines/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultDisciplinesShouldNotBeFound(String filter) throws Exception {
restDisciplinesMockMvc.perform(get("/api/disciplines?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restDisciplinesMockMvc.perform(get("/api/disciplines/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingDisciplines() throws Exception {
// Get the disciplines
restDisciplinesMockMvc.perform(get("/api/disciplines/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateDisciplines() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
int databaseSizeBeforeUpdate = disciplinesRepository.findAll().size();
// Update the disciplines
Disciplines updatedDisciplines = disciplinesRepository.findById(disciplines.getId()).get();
// Disconnect from session so that the updates on updatedDisciplines are not directly saved in db
em.detach(updatedDisciplines);
updatedDisciplines
.discipline(UPDATED_DISCIPLINE)
.teacherName(UPDATED_TEACHER_NAME)
.mark(UPDATED_MARK)
.markDate(UPDATED_MARK_DATE);
DisciplinesDTO disciplinesDTO = disciplinesMapper.toDto(updatedDisciplines);
restDisciplinesMockMvc.perform(put("/api/disciplines")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(disciplinesDTO)))
.andExpect(status().isOk());
// Validate the Disciplines in the database
List<Disciplines> disciplinesList = disciplinesRepository.findAll();
assertThat(disciplinesList).hasSize(databaseSizeBeforeUpdate);
Disciplines testDisciplines = disciplinesList.get(disciplinesList.size() - 1);
assertThat(testDisciplines.getDiscipline()).isEqualTo(UPDATED_DISCIPLINE);
assertThat(testDisciplines.getTeacherName()).isEqualTo(UPDATED_TEACHER_NAME);
assertThat(testDisciplines.getMark()).isEqualTo(UPDATED_MARK);
assertThat(testDisciplines.getMarkDate()).isEqualTo(UPDATED_MARK_DATE);
// Validate the Disciplines in Elasticsearch
verify(mockDisciplinesSearchRepository, times(1)).save(testDisciplines);
}
@Test
@Transactional
public void updateNonExistingDisciplines() throws Exception {
int databaseSizeBeforeUpdate = disciplinesRepository.findAll().size();
// Create the Disciplines
DisciplinesDTO disciplinesDTO = disciplinesMapper.toDto(disciplines);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restDisciplinesMockMvc.perform(put("/api/disciplines")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(disciplinesDTO)))
.andExpect(status().isBadRequest());
// Validate the Disciplines in the database
List<Disciplines> disciplinesList = disciplinesRepository.findAll();
assertThat(disciplinesList).hasSize(databaseSizeBeforeUpdate);
// Validate the Disciplines in Elasticsearch
verify(mockDisciplinesSearchRepository, times(0)).save(disciplines);
}
@Test
@Transactional
public void deleteDisciplines() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
int databaseSizeBeforeDelete = disciplinesRepository.findAll().size();
// Delete the disciplines
restDisciplinesMockMvc.perform(delete("/api/disciplines/{id}", disciplines.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Disciplines> disciplinesList = disciplinesRepository.findAll();
assertThat(disciplinesList).hasSize(databaseSizeBeforeDelete - 1);
// Validate the Disciplines in Elasticsearch
verify(mockDisciplinesSearchRepository, times(1)).deleteById(disciplines.getId());
}
@Test
@Transactional
public void searchDisciplines() throws Exception {
// Initialize the database
disciplinesRepository.saveAndFlush(disciplines);
when(mockDisciplinesSearchRepository.search(queryStringQuery("id:" + disciplines.getId())))
.thenReturn(Collections.singletonList(disciplines));
// Search the disciplines
restDisciplinesMockMvc.perform(get("/api/_search/disciplines?query=id:" + disciplines.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(disciplines.getId().intValue())))
.andExpect(jsonPath("$.[*].discipline").value(hasItem(DEFAULT_DISCIPLINE)))
.andExpect(jsonPath("$.[*].teacherName").value(hasItem(DEFAULT_TEACHER_NAME)))
.andExpect(jsonPath("$.[*].mark").value(hasItem(DEFAULT_MARK.doubleValue())))
.andExpect(jsonPath("$.[*].markDate").value(hasItem(DEFAULT_MARK_DATE.toString())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Disciplines.class);
Disciplines disciplines1 = new Disciplines();
disciplines1.setId(1L);
Disciplines disciplines2 = new Disciplines();
disciplines2.setId(disciplines1.getId());
assertThat(disciplines1).isEqualTo(disciplines2);
disciplines2.setId(2L);
assertThat(disciplines1).isNotEqualTo(disciplines2);
disciplines1.setId(null);
assertThat(disciplines1).isNotEqualTo(disciplines2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(DisciplinesDTO.class);
DisciplinesDTO disciplinesDTO1 = new DisciplinesDTO();
disciplinesDTO1.setId(1L);
DisciplinesDTO disciplinesDTO2 = new DisciplinesDTO();
assertThat(disciplinesDTO1).isNotEqualTo(disciplinesDTO2);
disciplinesDTO2.setId(disciplinesDTO1.getId());
assertThat(disciplinesDTO1).isEqualTo(disciplinesDTO2);
disciplinesDTO2.setId(2L);
assertThat(disciplinesDTO1).isNotEqualTo(disciplinesDTO2);
disciplinesDTO1.setId(null);
assertThat(disciplinesDTO1).isNotEqualTo(disciplinesDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(disciplinesMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(disciplinesMapper.fromId(null)).isNull();
}
}
<file_sep>package com.mycompany.myapp.service.dto;
import java.time.LocalDate;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the Promotion entity.
*/
public class PromotionDTO implements Serializable {
private Long id;
private LocalDate promotionDate;
private String promotionNumber;
private String vzvodName;
private Long studentId;
private String studentFullName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getPromotionDate() {
return promotionDate;
}
public void setPromotionDate(LocalDate promotionDate) {
this.promotionDate = promotionDate;
}
public String getPromotionNumber() {
return promotionNumber;
}
public void setPromotionNumber(String promotionNumber) {
this.promotionNumber = promotionNumber;
}
public String getVzvodName() {
return vzvodName;
}
public void setVzvodName(String vzvodName) {
this.vzvodName = vzvodName;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentFullName() {
return studentFullName;
}
public void setStudentFullName(String studentFullName) {
this.studentFullName = studentFullName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PromotionDTO promotionDTO = (PromotionDTO) o;
if (promotionDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), promotionDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "PromotionDTO{" +
"id=" + getId() +
", promotionDate='" + getPromotionDate() + "'" +
", promotionNumber='" + getPromotionNumber() + "'" +
", vzvodName='" + getVzvodName() + "'" +
", student=" + getStudentId() +
", student='" + getStudentFullName() + "'" +
"}";
}
}
<file_sep>package com.mycompany.myapp.repository;
import com.mycompany.myapp.domain.Disciplines;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Disciplines entity.
*/
@SuppressWarnings("unused")
@Repository
public interface DisciplinesRepository extends JpaRepository<Disciplines, Long>, JpaSpecificationExecutor<Disciplines> {
}
<file_sep>package com.mycompany.myapp.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import com.mycompany.myapp.domain.Parent;
import com.mycompany.myapp.domain.*; // for static metamodels
import com.mycompany.myapp.repository.ParentRepository;
import com.mycompany.myapp.repository.search.ParentSearchRepository;
import com.mycompany.myapp.service.dto.ParentCriteria;
import com.mycompany.myapp.service.dto.ParentDTO;
import com.mycompany.myapp.service.mapper.ParentMapper;
/**
* Service for executing complex queries for Parent entities in the database.
* The main input is a {@link ParentCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link ParentDTO} or a {@link Page} of {@link ParentDTO} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class ParentQueryService extends QueryService<Parent> {
private final Logger log = LoggerFactory.getLogger(ParentQueryService.class);
private final ParentRepository parentRepository;
private final ParentMapper parentMapper;
private final ParentSearchRepository parentSearchRepository;
public ParentQueryService(ParentRepository parentRepository, ParentMapper parentMapper, ParentSearchRepository parentSearchRepository) {
this.parentRepository = parentRepository;
this.parentMapper = parentMapper;
this.parentSearchRepository = parentSearchRepository;
}
/**
* Return a {@link List} of {@link ParentDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<ParentDTO> findByCriteria(ParentCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Parent> specification = createSpecification(criteria);
return parentMapper.toDto(parentRepository.findAll(specification));
}
/**
* Return a {@link Page} of {@link ParentDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<ParentDTO> findByCriteria(ParentCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Parent> specification = createSpecification(criteria);
return parentRepository.findAll(specification, page)
.map(parentMapper::toDto);
}
/**
* Return the number of matching entities in the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(ParentCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Parent> specification = createSpecification(criteria);
return parentRepository.count(specification);
}
/**
* Function to convert ParentCriteria to a {@link Specification}
*/
private Specification<Parent> createSpecification(ParentCriteria criteria) {
Specification<Parent> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildSpecification(criteria.getId(), Parent_.id));
}
if (criteria.getFullName() != null) {
specification = specification.and(buildStringSpecification(criteria.getFullName(), Parent_.fullName));
}
if (criteria.getPhoneNumber() != null) {
specification = specification.and(buildStringSpecification(criteria.getPhoneNumber(), Parent_.phoneNumber));
}
if (criteria.getWorkName() != null) {
specification = specification.and(buildStringSpecification(criteria.getWorkName(), Parent_.workName));
}
if (criteria.getJobRole() != null) {
specification = specification.and(buildStringSpecification(criteria.getJobRole(), Parent_.jobRole));
}
if (criteria.getStudentId() != null) {
specification = specification.and(buildSpecification(criteria.getStudentId(),
root -> root.join(Parent_.students, JoinType.LEFT).get(Student_.id)));
}
}
return specification;
}
}
<file_sep>package com.mycompany.myapp.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects;
/**
* A Disciplines.
*/
@Entity
@Table(name = "disciplines")
@Document(indexName = "disciplines")
public class Disciplines implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "discipline")
private String discipline;
@Column(name = "teacher_name")
private String teacherName;
@Column(name = "mark")
private Double mark;
@Column(name = "mark_date")
private LocalDate markDate;
@ManyToOne
@JsonIgnoreProperties("disciplines")
private Student student;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDiscipline() {
return discipline;
}
public Disciplines discipline(String discipline) {
this.discipline = discipline;
return this;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public String getTeacherName() {
return teacherName;
}
public Disciplines teacherName(String teacherName) {
this.teacherName = teacherName;
return this;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Double getMark() {
return mark;
}
public Disciplines mark(Double mark) {
this.mark = mark;
return this;
}
public void setMark(Double mark) {
this.mark = mark;
}
public LocalDate getMarkDate() {
return markDate;
}
public Disciplines markDate(LocalDate markDate) {
this.markDate = markDate;
return this;
}
public void setMarkDate(LocalDate markDate) {
this.markDate = markDate;
}
public Student getStudent() {
return student;
}
public Disciplines student(Student student) {
this.student = student;
return this;
}
public void setStudent(Student student) {
this.student = student;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Disciplines disciplines = (Disciplines) o;
if (disciplines.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), disciplines.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Disciplines{" +
"id=" + getId() +
", discipline='" + getDiscipline() + "'" +
", teacherName='" + getTeacherName() + "'" +
", mark=" + getMark() +
", markDate='" + getMarkDate() + "'" +
"}";
}
}
<file_sep>package com.mycompany.myapp.service.mapper;
import com.mycompany.myapp.domain.*;
import com.mycompany.myapp.service.dto.StudentDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Student and its DTO StudentDTO.
*/
@Mapper(componentModel = "spring", uses = {})
public interface StudentMapper extends EntityMapper<StudentDTO, Student> {
@Mapping(target = "contacts", ignore = true)
@Mapping(target = "parents", ignore = true)
Student toEntity(StudentDTO studentDTO);
default Student fromId(Long id) {
if (id == null) {
return null;
}
Student student = new Student();
student.setId(id);
return student;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { JhiAlertService } from 'ng-jhipster';
import { IContacts } from 'app/shared/model/contacts.model';
import { ContactsService } from './contacts.service';
import { IStudent } from 'app/shared/model/student.model';
import { StudentService } from 'app/entities/student';
@Component({
selector: 'jhi-contacts-update',
templateUrl: './contacts-update.component.html'
})
export class ContactsUpdateComponent implements OnInit {
contacts: IContacts;
isSaving: boolean;
students: IStudent[];
constructor(
protected jhiAlertService: JhiAlertService,
protected contactsService: ContactsService,
protected studentService: StudentService,
protected activatedRoute: ActivatedRoute
) {}
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ contacts }) => {
this.contacts = contacts;
});
this.studentService
.query({ 'contactsId.specified': 'false' })
.pipe(
filter((mayBeOk: HttpResponse<IStudent[]>) => mayBeOk.ok),
map((response: HttpResponse<IStudent[]>) => response.body)
)
.subscribe(
(res: IStudent[]) => {
if (!this.contacts.studentId) {
this.students = res;
} else {
this.studentService
.find(this.contacts.studentId)
.pipe(
filter((subResMayBeOk: HttpResponse<IStudent>) => subResMayBeOk.ok),
map((subResponse: HttpResponse<IStudent>) => subResponse.body)
)
.subscribe(
(subRes: IStudent) => (this.students = [subRes].concat(res)),
(subRes: HttpErrorResponse) => this.onError(subRes.message)
);
}
},
(res: HttpErrorResponse) => this.onError(res.message)
);
}
previousState() {
window.history.back();
}
save() {
this.isSaving = true;
if (this.contacts.id !== undefined) {
this.subscribeToSaveResponse(this.contactsService.update(this.contacts));
} else {
this.subscribeToSaveResponse(this.contactsService.create(this.contacts));
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IContacts>>) {
result.subscribe((res: HttpResponse<IContacts>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
protected onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
protected onSaveError() {
this.isSaving = false;
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
trackStudentById(index: number, item: IStudent) {
return item.id;
}
}
<file_sep>import { Moment } from 'moment';
export interface ITraining {
id?: number;
beginDateTraining?: Moment;
endDateTraining?: Moment;
dateOfGetPrisyaga?: Moment;
trainingPlace?: string;
trainingMark?: number;
studentFullName?: string;
studentId?: number;
}
export class Training implements ITraining {
constructor(
public id?: number,
public beginDateTraining?: Moment,
public endDateTraining?: Moment,
public dateOfGetPrisyaga?: Moment,
public trainingPlace?: string,
public trainingMark?: number,
public studentFullName?: string,
public studentId?: number
) {}
}
<file_sep>package com.mycompany.myapp.service.mapper;
import com.mycompany.myapp.domain.*;
import com.mycompany.myapp.service.dto.DisciplinesDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Disciplines and its DTO DisciplinesDTO.
*/
@Mapper(componentModel = "spring", uses = {StudentMapper.class})
public interface DisciplinesMapper extends EntityMapper<DisciplinesDTO, Disciplines> {
@Mapping(source = "student.id", target = "studentId")
@Mapping(source = "student.fullName", target = "studentFullName")
DisciplinesDTO toDto(Disciplines disciplines);
@Mapping(source = "studentId", target = "student")
Disciplines toEntity(DisciplinesDTO disciplinesDTO);
default Disciplines fromId(Long id) {
if (id == null) {
return null;
}
Disciplines disciplines = new Disciplines();
disciplines.setId(id);
return disciplines;
}
}
<file_sep>import { Moment } from 'moment';
export interface IPromotion {
id?: number;
promotionDate?: Moment;
promotionNumber?: string;
vzvodName?: string;
studentFullName?: string;
studentId?: number;
}
export class Promotion implements IPromotion {
constructor(
public id?: number,
public promotionDate?: Moment,
public promotionNumber?: string,
public vzvodName?: string,
public studentFullName?: string,
public studentId?: number
) {}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_FORMAT } from 'app/shared/constants/input.constants';
import { map } from 'rxjs/operators';
import { SERVER_API_URL } from 'app/app.constants';
import { createRequestOption } from 'app/shared';
import { IPromotion } from 'app/shared/model/promotion.model';
type EntityResponseType = HttpResponse<IPromotion>;
type EntityArrayResponseType = HttpResponse<IPromotion[]>;
@Injectable({ providedIn: 'root' })
export class PromotionService {
public resourceUrl = SERVER_API_URL + 'api/promotions';
public resourceSearchUrl = SERVER_API_URL + 'api/_search/promotions';
constructor(protected http: HttpClient) {}
create(promotion: IPromotion): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(promotion);
return this.http
.post<IPromotion>(this.resourceUrl, copy, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
update(promotion: IPromotion): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(promotion);
return this.http
.put<IPromotion>(this.resourceUrl, copy, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
find(id: number): Observable<EntityResponseType> {
return this.http
.get<IPromotion>(`${this.resourceUrl}/${id}`, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
query(req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req);
return this.http
.get<IPromotion[]>(this.resourceUrl, { params: options, observe: 'response' })
.pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));
}
delete(id: number): Observable<HttpResponse<any>> {
return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response' });
}
search(req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req);
return this.http
.get<IPromotion[]>(this.resourceSearchUrl, { params: options, observe: 'response' })
.pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));
}
protected convertDateFromClient(promotion: IPromotion): IPromotion {
const copy: IPromotion = Object.assign({}, promotion, {
promotionDate:
promotion.promotionDate != null && promotion.promotionDate.isValid() ? promotion.promotionDate.format(DATE_FORMAT) : null
});
return copy;
}
protected convertDateFromServer(res: EntityResponseType): EntityResponseType {
if (res.body) {
res.body.promotionDate = res.body.promotionDate != null ? moment(res.body.promotionDate) : null;
}
return res;
}
protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {
if (res.body) {
res.body.forEach((promotion: IPromotion) => {
promotion.promotionDate = promotion.promotionDate != null ? moment(promotion.promotionDate) : null;
});
}
return res;
}
}
<file_sep>export interface IContacts {
id?: number;
stateProvince?: string;
city?: string;
streetAddress?: string;
flatNo?: number;
phoneNumber?: string;
studentFullName?: string;
studentId?: number;
}
export class Contacts implements IContacts {
constructor(
public id?: number,
public stateProvince?: string,
public city?: string,
public streetAddress?: string,
public flatNo?: number,
public phoneNumber?: string,
public studentFullName?: string,
public studentId?: number
) {}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { JhiAlertService } from 'ng-jhipster';
import { IParent } from 'app/shared/model/parent.model';
import { ParentService } from './parent.service';
import { IStudent } from 'app/shared/model/student.model';
import { StudentService } from 'app/entities/student';
@Component({
selector: 'jhi-parent-update',
templateUrl: './parent-update.component.html'
})
export class ParentUpdateComponent implements OnInit {
parent: IParent;
isSaving: boolean;
students: IStudent[];
constructor(
protected jhiAlertService: JhiAlertService,
protected parentService: ParentService,
protected studentService: StudentService,
protected activatedRoute: ActivatedRoute
) {}
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ parent }) => {
this.parent = parent;
});
this.studentService
.query()
.pipe(
filter((mayBeOk: HttpResponse<IStudent[]>) => mayBeOk.ok),
map((response: HttpResponse<IStudent[]>) => response.body)
)
.subscribe((res: IStudent[]) => (this.students = res), (res: HttpErrorResponse) => this.onError(res.message));
}
previousState() {
window.history.back();
}
save() {
this.isSaving = true;
if (this.parent.id !== undefined) {
this.subscribeToSaveResponse(this.parentService.update(this.parent));
} else {
this.subscribeToSaveResponse(this.parentService.create(this.parent));
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IParent>>) {
result.subscribe((res: HttpResponse<IParent>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
protected onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
protected onSaveError() {
this.isSaving = false;
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
trackStudentById(index: number, item: IStudent) {
return item.id;
}
getSelected(selectedVals: Array<any>, option: any) {
if (selectedVals) {
for (let i = 0; i < selectedVals.length; i++) {
if (option.id === selectedVals[i].id) {
return selectedVals[i];
}
}
}
return option;
}
}
<file_sep>package com.mycompany.myapp.domain;
import javax.persistence.*;
import javax.validation.constraints.*;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A Parent.
*/
@Entity
@Table(name = "parent")
@Document(indexName = "parent")
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(max = 40)
@Column(name = "full_name", length = 40, nullable = false)
private String fullName;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "work_name")
private String workName;
@Column(name = "job_role")
private String jobRole;
@ManyToMany
@JoinTable(name = "parent_student",
joinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"))
private Set<Student> students = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public Parent fullName(String fullName) {
this.fullName = fullName;
return this;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Parent phoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getWorkName() {
return workName;
}
public Parent workName(String workName) {
this.workName = workName;
return this;
}
public void setWorkName(String workName) {
this.workName = workName;
}
public String getJobRole() {
return jobRole;
}
public Parent jobRole(String jobRole) {
this.jobRole = jobRole;
return this;
}
public void setJobRole(String jobRole) {
this.jobRole = jobRole;
}
public Set<Student> getStudents() {
return students;
}
public Parent students(Set<Student> students) {
this.students = students;
return this;
}
public Parent addStudent(Student student) {
this.students.add(student);
student.getParents().add(this);
return this;
}
public Parent removeStudent(Student student) {
this.students.remove(student);
student.getParents().remove(this);
return this;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Parent parent = (Parent) o;
if (parent.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), parent.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Parent{" +
"id=" + getId() +
", fullName='" + getFullName() + "'" +
", phoneNumber='" + getPhoneNumber() + "'" +
", workName='" + getWorkName() + "'" +
", jobRole='" + getJobRole() + "'" +
"}";
}
}
<file_sep>package com.mycompany.myapp.repository.search;
import com.mycompany.myapp.domain.Promotion;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the Promotion entity.
*/
public interface PromotionSearchRepository extends ElasticsearchRepository<Promotion, Long> {
}
<file_sep>package com.mycompany.myapp.repository;
import com.mycompany.myapp.domain.Training;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Training entity.
*/
@SuppressWarnings("unused")
@Repository
public interface TrainingRepository extends JpaRepository<Training, Long>, JpaSpecificationExecutor<Training> {
}
<file_sep>package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.MilAppNewApp;
import com.mycompany.myapp.domain.Training;
import com.mycompany.myapp.domain.Student;
import com.mycompany.myapp.repository.TrainingRepository;
import com.mycompany.myapp.repository.search.TrainingSearchRepository;
import com.mycompany.myapp.service.TrainingService;
import com.mycompany.myapp.service.dto.TrainingDTO;
import com.mycompany.myapp.service.mapper.TrainingMapper;
import com.mycompany.myapp.web.rest.errors.ExceptionTranslator;
import com.mycompany.myapp.service.dto.TrainingCriteria;
import com.mycompany.myapp.service.TrainingQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;
import static com.mycompany.myapp.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TrainingResource REST controller.
*
* @see TrainingResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MilAppNewApp.class)
public class TrainingResourceIntTest {
private static final LocalDate DEFAULT_BEGIN_DATE_TRAINING = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_BEGIN_DATE_TRAINING = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_END_DATE_TRAINING = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_END_DATE_TRAINING = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_DATE_OF_GET_PRISYAGA = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATE_OF_GET_PRISYAGA = LocalDate.now(ZoneId.systemDefault());
private static final String DEFAULT_TRAINING_PLACE = "AAAAAAAAAA";
private static final String UPDATED_TRAINING_PLACE = "BBBBBBBBBB";
private static final Double DEFAULT_TRAINING_MARK = 1D;
private static final Double UPDATED_TRAINING_MARK = 2D;
@Autowired
private TrainingRepository trainingRepository;
@Autowired
private TrainingMapper trainingMapper;
@Autowired
private TrainingService trainingService;
/**
* This repository is mocked in the com.mycompany.myapp.repository.search test package.
*
* @see com.mycompany.myapp.repository.search.TrainingSearchRepositoryMockConfiguration
*/
@Autowired
private TrainingSearchRepository mockTrainingSearchRepository;
@Autowired
private TrainingQueryService trainingQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restTrainingMockMvc;
private Training training;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final TrainingResource trainingResource = new TrainingResource(trainingService, trainingQueryService);
this.restTrainingMockMvc = MockMvcBuilders.standaloneSetup(trainingResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Training createEntity(EntityManager em) {
Training training = new Training()
.beginDateTraining(DEFAULT_BEGIN_DATE_TRAINING)
.endDateTraining(DEFAULT_END_DATE_TRAINING)
.dateOfGetPrisyaga(DEFAULT_DATE_OF_GET_PRISYAGA)
.trainingPlace(DEFAULT_TRAINING_PLACE)
.trainingMark(DEFAULT_TRAINING_MARK);
return training;
}
@Before
public void initTest() {
training = createEntity(em);
}
@Test
@Transactional
public void createTraining() throws Exception {
int databaseSizeBeforeCreate = trainingRepository.findAll().size();
// Create the Training
TrainingDTO trainingDTO = trainingMapper.toDto(training);
restTrainingMockMvc.perform(post("/api/trainings")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(trainingDTO)))
.andExpect(status().isCreated());
// Validate the Training in the database
List<Training> trainingList = trainingRepository.findAll();
assertThat(trainingList).hasSize(databaseSizeBeforeCreate + 1);
Training testTraining = trainingList.get(trainingList.size() - 1);
assertThat(testTraining.getBeginDateTraining()).isEqualTo(DEFAULT_BEGIN_DATE_TRAINING);
assertThat(testTraining.getEndDateTraining()).isEqualTo(DEFAULT_END_DATE_TRAINING);
assertThat(testTraining.getDateOfGetPrisyaga()).isEqualTo(DEFAULT_DATE_OF_GET_PRISYAGA);
assertThat(testTraining.getTrainingPlace()).isEqualTo(DEFAULT_TRAINING_PLACE);
assertThat(testTraining.getTrainingMark()).isEqualTo(DEFAULT_TRAINING_MARK);
// Validate the Training in Elasticsearch
verify(mockTrainingSearchRepository, times(1)).save(testTraining);
}
@Test
@Transactional
public void createTrainingWithExistingId() throws Exception {
int databaseSizeBeforeCreate = trainingRepository.findAll().size();
// Create the Training with an existing ID
training.setId(1L);
TrainingDTO trainingDTO = trainingMapper.toDto(training);
// An entity with an existing ID cannot be created, so this API call must fail
restTrainingMockMvc.perform(post("/api/trainings")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(trainingDTO)))
.andExpect(status().isBadRequest());
// Validate the Training in the database
List<Training> trainingList = trainingRepository.findAll();
assertThat(trainingList).hasSize(databaseSizeBeforeCreate);
// Validate the Training in Elasticsearch
verify(mockTrainingSearchRepository, times(0)).save(training);
}
@Test
@Transactional
public void getAllTrainings() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList
restTrainingMockMvc.perform(get("/api/trainings?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(training.getId().intValue())))
.andExpect(jsonPath("$.[*].beginDateTraining").value(hasItem(DEFAULT_BEGIN_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].endDateTraining").value(hasItem(DEFAULT_END_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].dateOfGetPrisyaga").value(hasItem(DEFAULT_DATE_OF_GET_PRISYAGA.toString())))
.andExpect(jsonPath("$.[*].trainingPlace").value(hasItem(DEFAULT_TRAINING_PLACE.toString())))
.andExpect(jsonPath("$.[*].trainingMark").value(hasItem(DEFAULT_TRAINING_MARK.doubleValue())));
}
@Test
@Transactional
public void getTraining() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get the training
restTrainingMockMvc.perform(get("/api/trainings/{id}", training.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(training.getId().intValue()))
.andExpect(jsonPath("$.beginDateTraining").value(DEFAULT_BEGIN_DATE_TRAINING.toString()))
.andExpect(jsonPath("$.endDateTraining").value(DEFAULT_END_DATE_TRAINING.toString()))
.andExpect(jsonPath("$.dateOfGetPrisyaga").value(DEFAULT_DATE_OF_GET_PRISYAGA.toString()))
.andExpect(jsonPath("$.trainingPlace").value(DEFAULT_TRAINING_PLACE.toString()))
.andExpect(jsonPath("$.trainingMark").value(DEFAULT_TRAINING_MARK.doubleValue()));
}
@Test
@Transactional
public void getAllTrainingsByBeginDateTrainingIsEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where beginDateTraining equals to DEFAULT_BEGIN_DATE_TRAINING
defaultTrainingShouldBeFound("beginDateTraining.equals=" + DEFAULT_BEGIN_DATE_TRAINING);
// Get all the trainingList where beginDateTraining equals to UPDATED_BEGIN_DATE_TRAINING
defaultTrainingShouldNotBeFound("beginDateTraining.equals=" + UPDATED_BEGIN_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByBeginDateTrainingIsInShouldWork() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where beginDateTraining in DEFAULT_BEGIN_DATE_TRAINING or UPDATED_BEGIN_DATE_TRAINING
defaultTrainingShouldBeFound("beginDateTraining.in=" + DEFAULT_BEGIN_DATE_TRAINING + "," + UPDATED_BEGIN_DATE_TRAINING);
// Get all the trainingList where beginDateTraining equals to UPDATED_BEGIN_DATE_TRAINING
defaultTrainingShouldNotBeFound("beginDateTraining.in=" + UPDATED_BEGIN_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByBeginDateTrainingIsNullOrNotNull() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where beginDateTraining is not null
defaultTrainingShouldBeFound("beginDateTraining.specified=true");
// Get all the trainingList where beginDateTraining is null
defaultTrainingShouldNotBeFound("beginDateTraining.specified=false");
}
@Test
@Transactional
public void getAllTrainingsByBeginDateTrainingIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where beginDateTraining greater than or equals to DEFAULT_BEGIN_DATE_TRAINING
defaultTrainingShouldBeFound("beginDateTraining.greaterOrEqualThan=" + DEFAULT_BEGIN_DATE_TRAINING);
// Get all the trainingList where beginDateTraining greater than or equals to UPDATED_BEGIN_DATE_TRAINING
defaultTrainingShouldNotBeFound("beginDateTraining.greaterOrEqualThan=" + UPDATED_BEGIN_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByBeginDateTrainingIsLessThanSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where beginDateTraining less than or equals to DEFAULT_BEGIN_DATE_TRAINING
defaultTrainingShouldNotBeFound("beginDateTraining.lessThan=" + DEFAULT_BEGIN_DATE_TRAINING);
// Get all the trainingList where beginDateTraining less than or equals to UPDATED_BEGIN_DATE_TRAINING
defaultTrainingShouldBeFound("beginDateTraining.lessThan=" + UPDATED_BEGIN_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByEndDateTrainingIsEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where endDateTraining equals to DEFAULT_END_DATE_TRAINING
defaultTrainingShouldBeFound("endDateTraining.equals=" + DEFAULT_END_DATE_TRAINING);
// Get all the trainingList where endDateTraining equals to UPDATED_END_DATE_TRAINING
defaultTrainingShouldNotBeFound("endDateTraining.equals=" + UPDATED_END_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByEndDateTrainingIsInShouldWork() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where endDateTraining in DEFAULT_END_DATE_TRAINING or UPDATED_END_DATE_TRAINING
defaultTrainingShouldBeFound("endDateTraining.in=" + DEFAULT_END_DATE_TRAINING + "," + UPDATED_END_DATE_TRAINING);
// Get all the trainingList where endDateTraining equals to UPDATED_END_DATE_TRAINING
defaultTrainingShouldNotBeFound("endDateTraining.in=" + UPDATED_END_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByEndDateTrainingIsNullOrNotNull() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where endDateTraining is not null
defaultTrainingShouldBeFound("endDateTraining.specified=true");
// Get all the trainingList where endDateTraining is null
defaultTrainingShouldNotBeFound("endDateTraining.specified=false");
}
@Test
@Transactional
public void getAllTrainingsByEndDateTrainingIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where endDateTraining greater than or equals to DEFAULT_END_DATE_TRAINING
defaultTrainingShouldBeFound("endDateTraining.greaterOrEqualThan=" + DEFAULT_END_DATE_TRAINING);
// Get all the trainingList where endDateTraining greater than or equals to UPDATED_END_DATE_TRAINING
defaultTrainingShouldNotBeFound("endDateTraining.greaterOrEqualThan=" + UPDATED_END_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByEndDateTrainingIsLessThanSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where endDateTraining less than or equals to DEFAULT_END_DATE_TRAINING
defaultTrainingShouldNotBeFound("endDateTraining.lessThan=" + DEFAULT_END_DATE_TRAINING);
// Get all the trainingList where endDateTraining less than or equals to UPDATED_END_DATE_TRAINING
defaultTrainingShouldBeFound("endDateTraining.lessThan=" + UPDATED_END_DATE_TRAINING);
}
@Test
@Transactional
public void getAllTrainingsByDateOfGetPrisyagaIsEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where dateOfGetPrisyaga equals to DEFAULT_DATE_OF_GET_PRISYAGA
defaultTrainingShouldBeFound("dateOfGetPrisyaga.equals=" + DEFAULT_DATE_OF_GET_PRISYAGA);
// Get all the trainingList where dateOfGetPrisyaga equals to UPDATED_DATE_OF_GET_PRISYAGA
defaultTrainingShouldNotBeFound("dateOfGetPrisyaga.equals=" + UPDATED_DATE_OF_GET_PRISYAGA);
}
@Test
@Transactional
public void getAllTrainingsByDateOfGetPrisyagaIsInShouldWork() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where dateOfGetPrisyaga in DEFAULT_DATE_OF_GET_PRISYAGA or UPDATED_DATE_OF_GET_PRISYAGA
defaultTrainingShouldBeFound("dateOfGetPrisyaga.in=" + DEFAULT_DATE_OF_GET_PRISYAGA + "," + UPDATED_DATE_OF_GET_PRISYAGA);
// Get all the trainingList where dateOfGetPrisyaga equals to UPDATED_DATE_OF_GET_PRISYAGA
defaultTrainingShouldNotBeFound("dateOfGetPrisyaga.in=" + UPDATED_DATE_OF_GET_PRISYAGA);
}
@Test
@Transactional
public void getAllTrainingsByDateOfGetPrisyagaIsNullOrNotNull() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where dateOfGetPrisyaga is not null
defaultTrainingShouldBeFound("dateOfGetPrisyaga.specified=true");
// Get all the trainingList where dateOfGetPrisyaga is null
defaultTrainingShouldNotBeFound("dateOfGetPrisyaga.specified=false");
}
@Test
@Transactional
public void getAllTrainingsByDateOfGetPrisyagaIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where dateOfGetPrisyaga greater than or equals to DEFAULT_DATE_OF_GET_PRISYAGA
defaultTrainingShouldBeFound("dateOfGetPrisyaga.greaterOrEqualThan=" + DEFAULT_DATE_OF_GET_PRISYAGA);
// Get all the trainingList where dateOfGetPrisyaga greater than or equals to UPDATED_DATE_OF_GET_PRISYAGA
defaultTrainingShouldNotBeFound("dateOfGetPrisyaga.greaterOrEqualThan=" + UPDATED_DATE_OF_GET_PRISYAGA);
}
@Test
@Transactional
public void getAllTrainingsByDateOfGetPrisyagaIsLessThanSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where dateOfGetPrisyaga less than or equals to DEFAULT_DATE_OF_GET_PRISYAGA
defaultTrainingShouldNotBeFound("dateOfGetPrisyaga.lessThan=" + DEFAULT_DATE_OF_GET_PRISYAGA);
// Get all the trainingList where dateOfGetPrisyaga less than or equals to UPDATED_DATE_OF_GET_PRISYAGA
defaultTrainingShouldBeFound("dateOfGetPrisyaga.lessThan=" + UPDATED_DATE_OF_GET_PRISYAGA);
}
@Test
@Transactional
public void getAllTrainingsByTrainingPlaceIsEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingPlace equals to DEFAULT_TRAINING_PLACE
defaultTrainingShouldBeFound("trainingPlace.equals=" + DEFAULT_TRAINING_PLACE);
// Get all the trainingList where trainingPlace equals to UPDATED_TRAINING_PLACE
defaultTrainingShouldNotBeFound("trainingPlace.equals=" + UPDATED_TRAINING_PLACE);
}
@Test
@Transactional
public void getAllTrainingsByTrainingPlaceIsInShouldWork() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingPlace in DEFAULT_TRAINING_PLACE or UPDATED_TRAINING_PLACE
defaultTrainingShouldBeFound("trainingPlace.in=" + DEFAULT_TRAINING_PLACE + "," + UPDATED_TRAINING_PLACE);
// Get all the trainingList where trainingPlace equals to UPDATED_TRAINING_PLACE
defaultTrainingShouldNotBeFound("trainingPlace.in=" + UPDATED_TRAINING_PLACE);
}
@Test
@Transactional
public void getAllTrainingsByTrainingPlaceIsNullOrNotNull() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingPlace is not null
defaultTrainingShouldBeFound("trainingPlace.specified=true");
// Get all the trainingList where trainingPlace is null
defaultTrainingShouldNotBeFound("trainingPlace.specified=false");
}
@Test
@Transactional
public void getAllTrainingsByTrainingMarkIsEqualToSomething() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingMark equals to DEFAULT_TRAINING_MARK
defaultTrainingShouldBeFound("trainingMark.equals=" + DEFAULT_TRAINING_MARK);
// Get all the trainingList where trainingMark equals to UPDATED_TRAINING_MARK
defaultTrainingShouldNotBeFound("trainingMark.equals=" + UPDATED_TRAINING_MARK);
}
@Test
@Transactional
public void getAllTrainingsByTrainingMarkIsInShouldWork() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingMark in DEFAULT_TRAINING_MARK or UPDATED_TRAINING_MARK
defaultTrainingShouldBeFound("trainingMark.in=" + DEFAULT_TRAINING_MARK + "," + UPDATED_TRAINING_MARK);
// Get all the trainingList where trainingMark equals to UPDATED_TRAINING_MARK
defaultTrainingShouldNotBeFound("trainingMark.in=" + UPDATED_TRAINING_MARK);
}
@Test
@Transactional
public void getAllTrainingsByTrainingMarkIsNullOrNotNull() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
// Get all the trainingList where trainingMark is not null
defaultTrainingShouldBeFound("trainingMark.specified=true");
// Get all the trainingList where trainingMark is null
defaultTrainingShouldNotBeFound("trainingMark.specified=false");
}
@Test
@Transactional
public void getAllTrainingsByStudentIsEqualToSomething() throws Exception {
// Initialize the database
Student student = StudentResourceIntTest.createEntity(em);
em.persist(student);
em.flush();
training.setStudent(student);
trainingRepository.saveAndFlush(training);
Long studentId = student.getId();
// Get all the trainingList where student equals to studentId
defaultTrainingShouldBeFound("studentId.equals=" + studentId);
// Get all the trainingList where student equals to studentId + 1
defaultTrainingShouldNotBeFound("studentId.equals=" + (studentId + 1));
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultTrainingShouldBeFound(String filter) throws Exception {
restTrainingMockMvc.perform(get("/api/trainings?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(training.getId().intValue())))
.andExpect(jsonPath("$.[*].beginDateTraining").value(hasItem(DEFAULT_BEGIN_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].endDateTraining").value(hasItem(DEFAULT_END_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].dateOfGetPrisyaga").value(hasItem(DEFAULT_DATE_OF_GET_PRISYAGA.toString())))
.andExpect(jsonPath("$.[*].trainingPlace").value(hasItem(DEFAULT_TRAINING_PLACE)))
.andExpect(jsonPath("$.[*].trainingMark").value(hasItem(DEFAULT_TRAINING_MARK.doubleValue())));
// Check, that the count call also returns 1
restTrainingMockMvc.perform(get("/api/trainings/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultTrainingShouldNotBeFound(String filter) throws Exception {
restTrainingMockMvc.perform(get("/api/trainings?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restTrainingMockMvc.perform(get("/api/trainings/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingTraining() throws Exception {
// Get the training
restTrainingMockMvc.perform(get("/api/trainings/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTraining() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
int databaseSizeBeforeUpdate = trainingRepository.findAll().size();
// Update the training
Training updatedTraining = trainingRepository.findById(training.getId()).get();
// Disconnect from session so that the updates on updatedTraining are not directly saved in db
em.detach(updatedTraining);
updatedTraining
.beginDateTraining(UPDATED_BEGIN_DATE_TRAINING)
.endDateTraining(UPDATED_END_DATE_TRAINING)
.dateOfGetPrisyaga(UPDATED_DATE_OF_GET_PRISYAGA)
.trainingPlace(UPDATED_TRAINING_PLACE)
.trainingMark(UPDATED_TRAINING_MARK);
TrainingDTO trainingDTO = trainingMapper.toDto(updatedTraining);
restTrainingMockMvc.perform(put("/api/trainings")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(trainingDTO)))
.andExpect(status().isOk());
// Validate the Training in the database
List<Training> trainingList = trainingRepository.findAll();
assertThat(trainingList).hasSize(databaseSizeBeforeUpdate);
Training testTraining = trainingList.get(trainingList.size() - 1);
assertThat(testTraining.getBeginDateTraining()).isEqualTo(UPDATED_BEGIN_DATE_TRAINING);
assertThat(testTraining.getEndDateTraining()).isEqualTo(UPDATED_END_DATE_TRAINING);
assertThat(testTraining.getDateOfGetPrisyaga()).isEqualTo(UPDATED_DATE_OF_GET_PRISYAGA);
assertThat(testTraining.getTrainingPlace()).isEqualTo(UPDATED_TRAINING_PLACE);
assertThat(testTraining.getTrainingMark()).isEqualTo(UPDATED_TRAINING_MARK);
// Validate the Training in Elasticsearch
verify(mockTrainingSearchRepository, times(1)).save(testTraining);
}
@Test
@Transactional
public void updateNonExistingTraining() throws Exception {
int databaseSizeBeforeUpdate = trainingRepository.findAll().size();
// Create the Training
TrainingDTO trainingDTO = trainingMapper.toDto(training);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restTrainingMockMvc.perform(put("/api/trainings")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(trainingDTO)))
.andExpect(status().isBadRequest());
// Validate the Training in the database
List<Training> trainingList = trainingRepository.findAll();
assertThat(trainingList).hasSize(databaseSizeBeforeUpdate);
// Validate the Training in Elasticsearch
verify(mockTrainingSearchRepository, times(0)).save(training);
}
@Test
@Transactional
public void deleteTraining() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
int databaseSizeBeforeDelete = trainingRepository.findAll().size();
// Delete the training
restTrainingMockMvc.perform(delete("/api/trainings/{id}", training.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Training> trainingList = trainingRepository.findAll();
assertThat(trainingList).hasSize(databaseSizeBeforeDelete - 1);
// Validate the Training in Elasticsearch
verify(mockTrainingSearchRepository, times(1)).deleteById(training.getId());
}
@Test
@Transactional
public void searchTraining() throws Exception {
// Initialize the database
trainingRepository.saveAndFlush(training);
when(mockTrainingSearchRepository.search(queryStringQuery("id:" + training.getId())))
.thenReturn(Collections.singletonList(training));
// Search the training
restTrainingMockMvc.perform(get("/api/_search/trainings?query=id:" + training.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(training.getId().intValue())))
.andExpect(jsonPath("$.[*].beginDateTraining").value(hasItem(DEFAULT_BEGIN_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].endDateTraining").value(hasItem(DEFAULT_END_DATE_TRAINING.toString())))
.andExpect(jsonPath("$.[*].dateOfGetPrisyaga").value(hasItem(DEFAULT_DATE_OF_GET_PRISYAGA.toString())))
.andExpect(jsonPath("$.[*].trainingPlace").value(hasItem(DEFAULT_TRAINING_PLACE)))
.andExpect(jsonPath("$.[*].trainingMark").value(hasItem(DEFAULT_TRAINING_MARK.doubleValue())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Training.class);
Training training1 = new Training();
training1.setId(1L);
Training training2 = new Training();
training2.setId(training1.getId());
assertThat(training1).isEqualTo(training2);
training2.setId(2L);
assertThat(training1).isNotEqualTo(training2);
training1.setId(null);
assertThat(training1).isNotEqualTo(training2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(TrainingDTO.class);
TrainingDTO trainingDTO1 = new TrainingDTO();
trainingDTO1.setId(1L);
TrainingDTO trainingDTO2 = new TrainingDTO();
assertThat(trainingDTO1).isNotEqualTo(trainingDTO2);
trainingDTO2.setId(trainingDTO1.getId());
assertThat(trainingDTO1).isEqualTo(trainingDTO2);
trainingDTO2.setId(2L);
assertThat(trainingDTO1).isNotEqualTo(trainingDTO2);
trainingDTO1.setId(null);
assertThat(trainingDTO1).isNotEqualTo(trainingDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(trainingMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(trainingMapper.fromId(null)).isNull();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router';
import { JhiPaginationUtil, JhiResolvePagingParams } from 'ng-jhipster';
import { UserRouteAccessService } from 'app/core';
import { Observable, of } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { Contacts } from 'app/shared/model/contacts.model';
import { ContactsService } from './contacts.service';
import { ContactsComponent } from './contacts.component';
import { ContactsDetailComponent } from './contacts-detail.component';
import { ContactsUpdateComponent } from './contacts-update.component';
import { ContactsDeletePopupComponent } from './contacts-delete-dialog.component';
import { IContacts } from 'app/shared/model/contacts.model';
@Injectable({ providedIn: 'root' })
export class ContactsResolve implements Resolve<IContacts> {
constructor(private service: ContactsService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IContacts> {
const id = route.params['id'] ? route.params['id'] : null;
if (id) {
return this.service.find(id).pipe(
filter((response: HttpResponse<Contacts>) => response.ok),
map((contacts: HttpResponse<Contacts>) => contacts.body)
);
}
return of(new Contacts());
}
}
export const contactsRoute: Routes = [
{
path: '',
component: ContactsComponent,
resolve: {
pagingParams: JhiResolvePagingParams
},
data: {
authorities: ['ROLE_USER'],
defaultSort: 'id,asc',
pageTitle: 'milAppNewApp.contacts.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: ':id/view',
component: ContactsDetailComponent,
resolve: {
contacts: ContactsResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'milAppNewApp.contacts.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: 'new',
component: ContactsUpdateComponent,
resolve: {
contacts: ContactsResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'milAppNewApp.contacts.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: ':id/edit',
component: ContactsUpdateComponent,
resolve: {
contacts: ContactsResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'milAppNewApp.contacts.home.title'
},
canActivate: [UserRouteAccessService]
}
];
export const contactsPopupRoute: Routes = [
{
path: ':id/delete',
component: ContactsDeletePopupComponent,
resolve: {
contacts: ContactsResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'milAppNewApp.contacts.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
}
];
<file_sep>package com.mycompany.myapp.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
/**
* Criteria class for the Parent entity. This class is used in ParentResource to
* receive all the possible filtering options from the Http GET request parameters.
* For example the following could be a valid requests:
* <code> /parents?id.greaterThan=5&attr1.contains=something&attr2.specified=false</code>
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class ParentCriteria implements Serializable {
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter fullName;
private StringFilter phoneNumber;
private StringFilter workName;
private StringFilter jobRole;
private LongFilter studentId;
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getFullName() {
return fullName;
}
public void setFullName(StringFilter fullName) {
this.fullName = fullName;
}
public StringFilter getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(StringFilter phoneNumber) {
this.phoneNumber = phoneNumber;
}
public StringFilter getWorkName() {
return workName;
}
public void setWorkName(StringFilter workName) {
this.workName = workName;
}
public StringFilter getJobRole() {
return jobRole;
}
public void setJobRole(StringFilter jobRole) {
this.jobRole = jobRole;
}
public LongFilter getStudentId() {
return studentId;
}
public void setStudentId(LongFilter studentId) {
this.studentId = studentId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ParentCriteria that = (ParentCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(fullName, that.fullName) &&
Objects.equals(phoneNumber, that.phoneNumber) &&
Objects.equals(workName, that.workName) &&
Objects.equals(jobRole, that.jobRole) &&
Objects.equals(studentId, that.studentId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
fullName,
phoneNumber,
workName,
jobRole,
studentId
);
}
@Override
public String toString() {
return "ParentCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(fullName != null ? "fullName=" + fullName + ", " : "") +
(phoneNumber != null ? "phoneNumber=" + phoneNumber + ", " : "") +
(workName != null ? "workName=" + workName + ", " : "") +
(jobRole != null ? "jobRole=" + jobRole + ", " : "") +
(studentId != null ? "studentId=" + studentId + ", " : "") +
"}";
}
}
<file_sep>package com.mycompany.myapp.service.dto;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the Contacts entity.
*/
public class ContactsDTO implements Serializable {
private Long id;
private String stateProvince;
@NotNull
private String city;
private String streetAddress;
private Long flatNo;
@NotNull
private String phoneNumber;
private Long studentId;
private String studentFullName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public Long getFlatNo() {
return flatNo;
}
public void setFlatNo(Long flatNo) {
this.flatNo = flatNo;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentFullName() {
return studentFullName;
}
public void setStudentFullName(String studentFullName) {
this.studentFullName = studentFullName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ContactsDTO contactsDTO = (ContactsDTO) o;
if (contactsDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), contactsDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "ContactsDTO{" +
"id=" + getId() +
", stateProvince='" + getStateProvince() + "'" +
", city='" + getCity() + "'" +
", streetAddress='" + getStreetAddress() + "'" +
", flatNo=" + getFlatNo() +
", phoneNumber='" + getPhoneNumber() + "'" +
", student=" + getStudentId() +
", student='" + getStudentFullName() + "'" +
"}";
}
}
<file_sep>package com.mycompany.myapp.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import com.mycompany.myapp.domain.Disciplines;
import com.mycompany.myapp.domain.*; // for static metamodels
import com.mycompany.myapp.repository.DisciplinesRepository;
import com.mycompany.myapp.repository.search.DisciplinesSearchRepository;
import com.mycompany.myapp.service.dto.DisciplinesCriteria;
import com.mycompany.myapp.service.dto.DisciplinesDTO;
import com.mycompany.myapp.service.mapper.DisciplinesMapper;
/**
* Service for executing complex queries for Disciplines entities in the database.
* The main input is a {@link DisciplinesCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link DisciplinesDTO} or a {@link Page} of {@link DisciplinesDTO} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class DisciplinesQueryService extends QueryService<Disciplines> {
private final Logger log = LoggerFactory.getLogger(DisciplinesQueryService.class);
private final DisciplinesRepository disciplinesRepository;
private final DisciplinesMapper disciplinesMapper;
private final DisciplinesSearchRepository disciplinesSearchRepository;
public DisciplinesQueryService(DisciplinesRepository disciplinesRepository, DisciplinesMapper disciplinesMapper, DisciplinesSearchRepository disciplinesSearchRepository) {
this.disciplinesRepository = disciplinesRepository;
this.disciplinesMapper = disciplinesMapper;
this.disciplinesSearchRepository = disciplinesSearchRepository;
}
/**
* Return a {@link List} of {@link DisciplinesDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<DisciplinesDTO> findByCriteria(DisciplinesCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Disciplines> specification = createSpecification(criteria);
return disciplinesMapper.toDto(disciplinesRepository.findAll(specification));
}
/**
* Return a {@link Page} of {@link DisciplinesDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<DisciplinesDTO> findByCriteria(DisciplinesCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Disciplines> specification = createSpecification(criteria);
return disciplinesRepository.findAll(specification, page)
.map(disciplinesMapper::toDto);
}
/**
* Return the number of matching entities in the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(DisciplinesCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Disciplines> specification = createSpecification(criteria);
return disciplinesRepository.count(specification);
}
/**
* Function to convert DisciplinesCriteria to a {@link Specification}
*/
private Specification<Disciplines> createSpecification(DisciplinesCriteria criteria) {
Specification<Disciplines> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildSpecification(criteria.getId(), Disciplines_.id));
}
if (criteria.getDiscipline() != null) {
specification = specification.and(buildStringSpecification(criteria.getDiscipline(), Disciplines_.discipline));
}
if (criteria.getTeacherName() != null) {
specification = specification.and(buildStringSpecification(criteria.getTeacherName(), Disciplines_.teacherName));
}
if (criteria.getMark() != null) {
specification = specification.and(buildRangeSpecification(criteria.getMark(), Disciplines_.mark));
}
if (criteria.getMarkDate() != null) {
specification = specification.and(buildRangeSpecification(criteria.getMarkDate(), Disciplines_.markDate));
}
if (criteria.getStudentId() != null) {
specification = specification.and(buildSpecification(criteria.getStudentId(),
root -> root.join(Disciplines_.student, JoinType.LEFT).get(Student_.id)));
}
}
return specification;
}
}
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { JhiLanguageService } from 'ng-jhipster';
import { JhiLanguageHelper } from 'app/core';
import { MilAppNewSharedModule } from 'app/shared';
import {
ParentComponent,
ParentDetailComponent,
ParentUpdateComponent,
ParentDeletePopupComponent,
ParentDeleteDialogComponent,
parentRoute,
parentPopupRoute
} from './';
const ENTITY_STATES = [...parentRoute, ...parentPopupRoute];
@NgModule({
imports: [MilAppNewSharedModule, RouterModule.forChild(ENTITY_STATES)],
declarations: [ParentComponent, ParentDetailComponent, ParentUpdateComponent, ParentDeleteDialogComponent, ParentDeletePopupComponent],
entryComponents: [ParentComponent, ParentUpdateComponent, ParentDeleteDialogComponent, ParentDeletePopupComponent],
providers: [{ provide: JhiLanguageService, useClass: JhiLanguageService }],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class MilAppNewParentModule {
constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) {
this.languageHelper.language.subscribe((languageKey: string) => {
if (languageKey !== undefined) {
this.languageService.changeLanguage(languageKey);
}
});
}
}
<file_sep>package com.mycompany.myapp.domain.enumeration;
/**
* The Progremm enumeration.
*/
public enum Progremm {
RESERVE_SOLDIER, RESERVE_OFFICIER
}
<file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'student',
loadChildren: './student/student.module#MilAppNewStudentModule'
},
{
path: 'promotion',
loadChildren: './promotion/promotion.module#MilAppNewPromotionModule'
},
{
path: 'training',
loadChildren: './training/training.module#MilAppNewTrainingModule'
},
{
path: 'contacts',
loadChildren: './contacts/contacts.module#MilAppNewContactsModule'
},
{
path: 'parent',
loadChildren: './parent/parent.module#MilAppNewParentModule'
},
{
path: 'disciplines',
loadChildren: './disciplines/disciplines.module#MilAppNewDisciplinesModule'
},
{
path: 'promotion',
loadChildren: './promotion/promotion.module#MilAppNewPromotionModule'
},
{
path: 'training',
loadChildren: './training/training.module#MilAppNewTrainingModule'
},
{
path: 'contacts',
loadChildren: './contacts/contacts.module#MilAppNewContactsModule'
},
{
path: 'parent',
loadChildren: './parent/parent.module#MilAppNewParentModule'
},
{
path: 'disciplines',
loadChildren: './disciplines/disciplines.module#MilAppNewDisciplinesModule'
}
/* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */
])
],
declarations: [],
entryComponents: [],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class MilAppNewEntityModule {}
<file_sep>import { Moment } from 'moment';
export interface IDisciplines {
id?: number;
discipline?: string;
teacherName?: string;
mark?: number;
markDate?: Moment;
studentFullName?: string;
studentId?: number;
}
export class Disciplines implements IDisciplines {
constructor(
public id?: number,
public discipline?: string,
public teacherName?: string,
public mark?: number,
public markDate?: Moment,
public studentFullName?: string,
public studentId?: number
) {}
}
<file_sep>package com.mycompany.myapp.domain.enumeration;
/**
* The Vus enumeration.
*/
public enum Vus {
V_141100, V_461700, V_52100, V_541100, V_121500
}
<file_sep>package com.mycompany.myapp.service.dto;
import java.io.Serializable;
import java.util.Objects;
import com.mycompany.myapp.domain.enumeration.Vus;
import com.mycompany.myapp.domain.enumeration.Progremm;
import com.mycompany.myapp.domain.enumeration.Status;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
import io.github.jhipster.service.filter.LocalDateFilter;
/**
* Criteria class for the Student entity. This class is used in StudentResource to
* receive all the possible filtering options from the Http GET request parameters.
* For example the following could be a valid requests:
* <code> /students?id.greaterThan=5&attr1.contains=something&attr2.specified=false</code>
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class StudentCriteria implements Serializable {
/**
* Class for filtering Vus
*/
public static class VusFilter extends Filter<Vus> {
}
/**
* Class for filtering Progremm
*/
public static class ProgremmFilter extends Filter<Progremm> {
}
/**
* Class for filtering Status
*/
public static class StatusFilter extends Filter<Status> {
}
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter fullName;
private LocalDateFilter dateOfBirth;
private LocalDateFilter universityIn;
private LocalDateFilter univesityOut;
private VusFilter vus;
private StringFilter universityName;
private StringFilter speciality;
private StringFilter studyGroup;
private StringFilter platoonNumber;
private ProgremmFilter programm;
private StatusFilter status;
private LongFilter contactsId;
private LongFilter parentId;
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getFullName() {
return fullName;
}
public void setFullName(StringFilter fullName) {
this.fullName = fullName;
}
public LocalDateFilter getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDateFilter dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public LocalDateFilter getUniversityIn() {
return universityIn;
}
public void setUniversityIn(LocalDateFilter universityIn) {
this.universityIn = universityIn;
}
public LocalDateFilter getUnivesityOut() {
return univesityOut;
}
public void setUnivesityOut(LocalDateFilter univesityOut) {
this.univesityOut = univesityOut;
}
public VusFilter getVus() {
return vus;
}
public void setVus(VusFilter vus) {
this.vus = vus;
}
public StringFilter getUniversityName() {
return universityName;
}
public void setUniversityName(StringFilter universityName) {
this.universityName = universityName;
}
public StringFilter getSpeciality() {
return speciality;
}
public void setSpeciality(StringFilter speciality) {
this.speciality = speciality;
}
public StringFilter getStudyGroup() {
return studyGroup;
}
public void setStudyGroup(StringFilter studyGroup) {
this.studyGroup = studyGroup;
}
public StringFilter getPlatoonNumber() {
return platoonNumber;
}
public void setPlatoonNumber(StringFilter platoonNumber) {
this.platoonNumber = platoonNumber;
}
public ProgremmFilter getProgramm() {
return programm;
}
public void setProgramm(ProgremmFilter programm) {
this.programm = programm;
}
public StatusFilter getStatus() {
return status;
}
public void setStatus(StatusFilter status) {
this.status = status;
}
public LongFilter getContactsId() {
return contactsId;
}
public void setContactsId(LongFilter contactsId) {
this.contactsId = contactsId;
}
public LongFilter getParentId() {
return parentId;
}
public void setParentId(LongFilter parentId) {
this.parentId = parentId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final StudentCriteria that = (StudentCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(fullName, that.fullName) &&
Objects.equals(dateOfBirth, that.dateOfBirth) &&
Objects.equals(universityIn, that.universityIn) &&
Objects.equals(univesityOut, that.univesityOut) &&
Objects.equals(vus, that.vus) &&
Objects.equals(universityName, that.universityName) &&
Objects.equals(speciality, that.speciality) &&
Objects.equals(studyGroup, that.studyGroup) &&
Objects.equals(platoonNumber, that.platoonNumber) &&
Objects.equals(programm, that.programm) &&
Objects.equals(status, that.status) &&
Objects.equals(contactsId, that.contactsId) &&
Objects.equals(parentId, that.parentId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
fullName,
dateOfBirth,
universityIn,
univesityOut,
vus,
universityName,
speciality,
studyGroup,
platoonNumber,
programm,
status,
contactsId,
parentId
);
}
@Override
public String toString() {
return "StudentCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(fullName != null ? "fullName=" + fullName + ", " : "") +
(dateOfBirth != null ? "dateOfBirth=" + dateOfBirth + ", " : "") +
(universityIn != null ? "universityIn=" + universityIn + ", " : "") +
(univesityOut != null ? "univesityOut=" + univesityOut + ", " : "") +
(vus != null ? "vus=" + vus + ", " : "") +
(universityName != null ? "universityName=" + universityName + ", " : "") +
(speciality != null ? "speciality=" + speciality + ", " : "") +
(studyGroup != null ? "studyGroup=" + studyGroup + ", " : "") +
(platoonNumber != null ? "platoonNumber=" + platoonNumber + ", " : "") +
(programm != null ? "programm=" + programm + ", " : "") +
(status != null ? "status=" + status + ", " : "") +
(contactsId != null ? "contactsId=" + contactsId + ", " : "") +
(parentId != null ? "parentId=" + parentId + ", " : "") +
"}";
}
}
<file_sep>import { Moment } from 'moment';
import { IParent } from 'app/shared/model/parent.model';
export const enum Vus {
V_141100 = 'V_141100',
V_461700 = 'V_461700',
V_52100 = 'V_52100',
V_541100 = 'V_541100',
V_121500 = 'V_121500'
}
export const enum Progremm {
RESERVE_SOLDIER = 'RESERVE_SOLDIER',
RESERVE_OFFICIER = 'RESERVE_OFFICIER'
}
export const enum Status {
STUDYING = 'STUDYING',
GRADUATE = 'GRADUATE',
LIVING = 'LIVING'
}
export interface IStudent {
id?: number;
fullName?: string;
dateOfBirth?: Moment;
universityIn?: Moment;
univesityOut?: Moment;
vus?: Vus;
universityName?: string;
speciality?: string;
studyGroup?: string;
platoonNumber?: string;
programm?: Progremm;
status?: Status;
contactsId?: number;
parents?: IParent[];
}
export class Student implements IStudent {
constructor(
public id?: number,
public fullName?: string,
public dateOfBirth?: Moment,
public universityIn?: Moment,
public univesityOut?: Moment,
public vus?: Vus,
public universityName?: string,
public speciality?: string,
public studyGroup?: string,
public platoonNumber?: string,
public programm?: Progremm,
public status?: Status,
public contactsId?: number,
public parents?: IParent[]
) {}
}
<file_sep>package com.mycompany.myapp.service;
import com.mycompany.myapp.service.dto.PromotionDTO;
import java.util.List;
import java.util.Optional;
/**
* Service Interface for managing Promotion.
*/
public interface PromotionService {
/**
* Save a promotion.
*
* @param promotionDTO the entity to save
* @return the persisted entity
*/
PromotionDTO save(PromotionDTO promotionDTO);
/**
* Get all the promotions.
*
* @return the list of entities
*/
List<PromotionDTO> findAll();
/**
* Get the "id" promotion.
*
* @param id the id of the entity
* @return the entity
*/
Optional<PromotionDTO> findOne(Long id);
/**
* Delete the "id" promotion.
*
* @param id the id of the entity
*/
void delete(Long id);
/**
* Search for the promotion corresponding to the query.
*
* @param query the query of the search
*
* @return the list of entities
*/
List<PromotionDTO> search(String query);
}
<file_sep>import { IStudent } from 'app/shared/model/student.model';
export interface IParent {
id?: number;
fullName?: string;
phoneNumber?: string;
workName?: string;
jobRole?: string;
students?: IStudent[];
}
export class Parent implements IParent {
constructor(
public id?: number,
public fullName?: string,
public phoneNumber?: string,
public workName?: string,
public jobRole?: string,
public students?: IStudent[]
) {}
}
<file_sep>export * from './contacts.service';
export * from './contacts-update.component';
export * from './contacts-delete-dialog.component';
export * from './contacts-detail.component';
export * from './contacts.component';
export * from './contacts.route';
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { IContacts } from 'app/shared/model/contacts.model';
@Component({
selector: 'jhi-contacts-detail',
templateUrl: './contacts-detail.component.html'
})
export class ContactsDetailComponent implements OnInit {
contacts: IContacts;
constructor(protected activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.data.subscribe(({ contacts }) => {
this.contacts = contacts;
});
}
previousState() {
window.history.back();
}
}
<file_sep>export * from './parent.service';
export * from './parent-update.component';
export * from './parent-delete-dialog.component';
export * from './parent-detail.component';
export * from './parent.component';
export * from './parent.route';
<file_sep>export * from './disciplines.service';
export * from './disciplines-update.component';
export * from './disciplines-delete-dialog.component';
export * from './disciplines-detail.component';
export * from './disciplines.component';
export * from './disciplines.route';
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import * as moment from 'moment';
import { JhiAlertService } from 'ng-jhipster';
import { IStudent } from 'app/shared/model/student.model';
import { StudentService } from './student.service';
import { IContacts } from 'app/shared/model/contacts.model';
import { ContactsService } from 'app/entities/contacts';
import { IParent } from 'app/shared/model/parent.model';
import { ParentService } from 'app/entities/parent';
@Component({
selector: 'jhi-student-update',
templateUrl: './student-update.component.html'
})
export class StudentUpdateComponent implements OnInit {
student: IStudent;
isSaving: boolean;
contacts: IContacts[];
parents: IParent[];
dateOfBirthDp: any;
universityInDp: any;
univesityOutDp: any;
constructor(
protected jhiAlertService: JhiAlertService,
protected studentService: StudentService,
protected contactsService: ContactsService,
protected parentService: ParentService,
protected activatedRoute: ActivatedRoute
) {}
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ student }) => {
this.student = student;
});
this.contactsService
.query()
.pipe(
filter((mayBeOk: HttpResponse<IContacts[]>) => mayBeOk.ok),
map((response: HttpResponse<IContacts[]>) => response.body)
)
.subscribe((res: IContacts[]) => (this.contacts = res), (res: HttpErrorResponse) => this.onError(res.message));
this.parentService
.query()
.pipe(
filter((mayBeOk: HttpResponse<IParent[]>) => mayBeOk.ok),
map((response: HttpResponse<IParent[]>) => response.body)
)
.subscribe((res: IParent[]) => (this.parents = res), (res: HttpErrorResponse) => this.onError(res.message));
}
previousState() {
window.history.back();
}
save() {
this.isSaving = true;
if (this.student.id !== undefined) {
this.subscribeToSaveResponse(this.studentService.update(this.student));
} else {
this.subscribeToSaveResponse(this.studentService.create(this.student));
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IStudent>>) {
result.subscribe((res: HttpResponse<IStudent>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
protected onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
protected onSaveError() {
this.isSaving = false;
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
trackContactsById(index: number, item: IContacts) {
return item.id;
}
trackParentById(index: number, item: IParent) {
return item.id;
}
getSelected(selectedVals: Array<any>, option: any) {
if (selectedVals) {
for (let i = 0; i < selectedVals.length; i++) {
if (option.id === selectedVals[i].id) {
return selectedVals[i];
}
}
}
return option;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import * as moment from 'moment';
import { JhiAlertService } from 'ng-jhipster';
import { IDisciplines } from 'app/shared/model/disciplines.model';
import { DisciplinesService } from './disciplines.service';
import { IStudent } from 'app/shared/model/student.model';
import { StudentService } from 'app/entities/student';
@Component({
selector: 'jhi-disciplines-update',
templateUrl: './disciplines-update.component.html'
})
export class DisciplinesUpdateComponent implements OnInit {
disciplines: IDisciplines;
isSaving: boolean;
students: IStudent[];
markDateDp: any;
constructor(
protected jhiAlertService: JhiAlertService,
protected disciplinesService: DisciplinesService,
protected studentService: StudentService,
protected activatedRoute: ActivatedRoute
) {}
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ disciplines }) => {
this.disciplines = disciplines;
});
this.studentService
.query()
.pipe(
filter((mayBeOk: HttpResponse<IStudent[]>) => mayBeOk.ok),
map((response: HttpResponse<IStudent[]>) => response.body)
)
.subscribe((res: IStudent[]) => (this.students = res), (res: HttpErrorResponse) => this.onError(res.message));
}
previousState() {
window.history.back();
}
save() {
this.isSaving = true;
if (this.disciplines.id !== undefined) {
this.subscribeToSaveResponse(this.disciplinesService.update(this.disciplines));
} else {
this.subscribeToSaveResponse(this.disciplinesService.create(this.disciplines));
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IDisciplines>>) {
result.subscribe((res: HttpResponse<IDisciplines>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
protected onSaveSuccess() {
this.isSaving = false;
this.previousState();
}
protected onSaveError() {
this.isSaving = false;
}
protected onError(errorMessage: string) {
this.jhiAlertService.error(errorMessage, null, null);
}
trackStudentById(index: number, item: IStudent) {
return item.id;
}
}
|
e031bc4551f4c675465424746c05c56848d895d2
|
[
"Java",
"TypeScript"
] | 40
|
TypeScript
|
Phoenix124/mil
|
0a096695da552b7326820441efe80282b96171ca
|
54c52664228d9e2dad11bf90abe5a2e71472bb2b
|
refs/heads/master
|
<file_sep>/*
pins_arduino.h - Pin definition functions for Arduino
Part of Arduino - http://www.arduino.cc/
Copyright (c) 2007 <NAME>
Modified for ESP8266 platform by <NAME>, 2014-2015.
This library is free software you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
$Id: wiring.h 249 2007-02-03 16:52:51Z mellis $
*/
#ifndef NODEMCU_PIN_MAPPING
#define NODEMCU_PIN_MAPPING
// SPI PIN
#define RST 15
#define SS 15
#define MOSI 13
#define MISO 12
#define SCK 14
#define A0 17
// I2C PIN
#define SDA 4
#define SCL 5
#define LED_BUILTIN 16
#define BUILTIN_LED 16
// DIGITAL PIN
#define D0 16
#define D1 5
#define D2 4
#define D3 0
#define D4 2
#define D5 14
#define D6 12
#define D7 13
#define D8 15
#define D9 3
#define D10 1
#endif /* Pins_Arduino_h */
<file_sep>"# nodemcu-libraries"
|
db0a658078f1834182133283de57a7c2585bff0c
|
[
"Markdown",
"C"
] | 2
|
C
|
thientran1986/nodemcu-libraries
|
d119a73059f717151f364a5b39d39ca6b77ec5ab
|
fcbde0c481c3418cfee3d092008357c195e4ec74
|
refs/heads/master
|
<repo_name>Lavakumarkoyi/os_assignment_A02_Lavakumar<file_sep>/studentdata.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct process
{
char s_name[10];
int at;
int r;
int totalbill;
int giftnum;
struct gname
{
char name[30];
int value;
}g[10];
}s[10];
struct process temp;
void main()
{
int i,n,k,r,f,t=0,m,size=0,j,h;
printf("\nEnter the number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
s[i].totalbill=0;
}
for(i=0;i<n;i++)
{
printf("\nEnter the name of the student:");
scanf("%s",&s[i].s_name);
printf("\nEnter the arrival time of the student:");
scanf("%d",&s[i].at);
printf("\nEnter the number of the gifts:");
scanf("%d",&s[i].giftnum);
s[i].r=s[i].r;
for(j=0;j<s[i].giftnum;j++)
{
printf("\nEnter the gift name::");
scanf("%s",&s[i].g[j].name);
printf("\nEnter the price of the gift::");
scanf("%d",&s[i].g[j].value);
}
for(j=0;j<s[i].giftnum;j++)
{
s[i].totalbill=s[i].totalbill+s[i].g[j].value; //total bill
}
}
<file_sep>/intro.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct process
{
char s_name[10];
int at;
int r;
int totalbill;
int giftnum;
struct gname
{
char name[30];
int value;
}g[10];
}s[10];
struct process temp;
void main()
{
int i,n,k,r,f,t=0,m,size=0,j,h;
printf("\nEnter the number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
s[i].totalbill=0;
}
<file_sep>/sortingdata.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct process
{
char s_name[10];
int at;
int r;
int totalbill;
int giftnum;
struct gname
{
char name[30];
int value;
}g[10];
}s[10];
struct process temp;
void main()
{
int i,n,k,r,f,t=0,m,size=0,j,h;
printf("\nEnter the number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
s[i].totalbill=0;
}
for(i=0;i<n;i++)
{
printf("\nEnter the name of the student:");
scanf("%s",&s[i].s_name);
printf("\nEnter the arrival time of the student:");
scanf("%d",&s[i].at);
printf("\nEnter the number of the gifts:");
scanf("%d",&s[i].giftnum);
s[i].r=s[i].r;
for(j=0;j<s[i].giftnum;j++)
{
printf("\nEnter the gift name::");
scanf("%s",&s[i].g[j].name);
printf("\nEnter the price of the gift::");
scanf("%d",&s[i].g[j].value);
}
for(j=0;j<s[i].giftnum;j++)
{
s[i].totalbill=s[i].totalbill+s[i].g[j].value; //total bill
}
}
for(k=0;k<n-1;k++) //bubble sort
{
for(m=0;m<n-k-1;m++)
{
if(s[m].at>s[m+1].at) //sorting according to the arrival time
{
temp.at=s[m].at;
s[m].at=s[m+1].at;
s[m+1].at=temp.at;
temp.giftnum=s[m].giftnum;
s[m].giftnum=s[m+1].giftnum;
s[m+1].giftnum=temp.giftnum;
temp.r=s[m].r;
s[m].giftnum=s[m+1].r;
s[m+1].r=temp.r;
temp.totalbill=s[m].totalbill;
s[m].totalbill=s[m+1].totalbill;
s[m+1].totalbill=temp.totalbill;
strcpy(temp.s_name,s[m].s_name);
strcpy(s[m].s_name,s[m+1].s_name);
strcpy(s[m+1].s_name,temp.s_name);
}
}
}
|
28cc186b65db44fa538b87d4a96707394179d8a0
|
[
"C"
] | 3
|
C
|
Lavakumarkoyi/os_assignment_A02_Lavakumar
|
8a3a89f41af45e194169be2254ef34b405440880
|
a97ff8dcada3522a26d9fa5af5e2f2eaf7eab80a
|
refs/heads/master
|
<file_sep>var express = require('express');
var path = require('path')
var bodyParser = require('body-parser');
require('./db');
var moviesRoutes = require('./routes/movies');
var app = express();
app.use(express.static(path.resolve(__dirname, 'public')));
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({extended:false}))
app.use('/movies', moviesRoutes);
app.get('/', function(req, res) {
res.render('index', {greeting:'hi!', name: 'joe'});
});
app.get('/templateVariables', function(req, res) {
var context = {
numbers:[1, 2, 3, 4],
obj: {a:1, b:2, c:3},
nested: [{name:'alice'}, {name:'bob'}]
};
res.render('templateVariables', context);
});
app.get('/array', function(req, res) {
res.render('array', {numbers:[1, 2, 3, 4]})
});
app.get('/object', function(req, res) {
res.render('object', {thing:{a:1, b:2, c:3}}) ;
});
app.get('/nestedObjects', function(req, res) {
res.render('/nestedObjects', {nestedThings:{obj:{a:1, b:2, c:3}, d:4, e:5, f:6}});
});
app.listen(process.env.PORT || 3000);
//console.log(process.env);
<file_sep># Y U Noooooode.js

## intros
* so you've decided to use node??? can't get enough js in your life? i will tell you about it
* who? am i really qualified to do this? maybe???
* on 3rd semester teaching this, but still _rough around the edges!_
* javascript / node / frontend dev ecosystem change all. the time.
* you
* no idea!
* that's ok, typically my class consists of:
* what's a css?
* i get paid do this stuff *yawn*
* soooo? hopefully i hit the sweet spot
* topics
* minimum js
* what's node / a quick cli app
* http
* express
* templating
* middleware
* routes
* get and post
* with a db
* with json and an api
* the early stuff, like js
## minimum javascript
* types
* primitives: number, string, boolean, null, undefined
* objects
* typeof isn't right, but it is
* what
* functions as objects
* defining functions
* anonymous functions
* higher order functions
* use functions that require functions to be passed in
* array.filter
* array.foreach
* create functions
* how was foreach or filter created
* callTwice
* makeAdder
* even after original function has returned
## node
* what's node?
* event loop, async io
* comparable to other techs (that i'm not familiar with at all)
* some applications that it's commonly used for / and maybe when you shouldn't
* _soft realtime_ networking applications... like chat
* very basic crud small web app
* apis (specifically for json based) is a good use case
* not so much for processor intensive applications like video encoding or large scaledata mining
* installing node
* package management with npm
* package.json
* npm install
* where do you find modules? node_modules... look up dir tree
* package.json
* using modules
* creating modules and
* require
* some built-ins
* module.exports
* process.env
* fs module - read and write
* http module
* an example of some external modules
* tell me again abt this event loop?
* ACTIVITY - get data from nba.com process it, and save it to a file
* before we start, some things you should know:
* parsing json
* `var obj = JSON.parse(body);`
* double quote prop names!
* let's see
* use requests module
* install
* `npm install requests --save`
* usage
* `var request = require('request');`
* `request.get(url, callback)`
* callback has error, response, body
* `response.statusCode`
* `var fs = require('fs');`
* writing to a file: `fs.writeFile(filename, stuff to write, callback)`
* (callback takes one arg, error)
```
fs.writeFile('filename.txt', "stuff" function (err) {
if (err) {
console.log(err);
}
console.log('writed all the things');
});
```
* url for data... [http://data.nba.com/data/15m/json/cms/noseason/game/20160221/0021500824/boxscore.json* grab data from data.nba.com](http://data.nba.com/data/15m/json/cms/noseason/game/20160221/0021500824/boxscore.json)
* what does data look like?
* let's do this while printing out what we're doing as we go along (how?)
* print out... getting data
* retrieve data
* say we got data
* parse json
* process
* say we're going to save
* save player's names from the home team to a file
* say donzo!
* let's do this the suspicious way first
* another way...
## a quick primer on http? or maybe you already know?
* http request
* method
* path
* body
* minimally, what are some http request methods?
* when you enter a url in your browser get or post?
* data in form? both!
* where's the data?
* get - query string
* post - body
## express intro
Typically, we think of a web app and a server as two distinct things. Node apps are both.
* _other setups_ maybe we'll have an app, an app server and a web server
* rails + unicorn + nginx
* rails + phusion passenger + apache
* django + uwsgi + nginx
* flask + gunicorn + nginx
* php + fastcgi / nginx
* node, for better or worse, is both the app and the app server, and many times is deployed so that it's directly exposed to the outside world without a _traditional_ web server in front of it
* we can use the http module...
* but that's kind of too low level for this presentation.
* what's express?
* microframework
* similar to???
* many others out there
* pretty popular... and flexible (and some more featureful frameworks are built on top of this)
* installation
* npm install express --save
* creating an app and defining some routes
* app.get... url, callback with req, res
* res.send to send back hello
* note that it sets content type 4U!11!!11
* add more than 1 route handler / router
* request object?
* baseurl
* ip (of remote request)
* hostname (from host header)
* url and originalUrl
* method
* some data related
* body
* params
* query
* route - currently matched route
* xhr?
* headers
* get() ... header
* response object?
* set(field, val) or set ({field:var}) set response header
* send() ... send back 200 w/ body
* status() ... send back status
* chain with send to send body
* status(404).send(body)
* render(templatename, context)
* redirect(statuscode, path or url)
* running your app
* node... whatever
* nodemon
* npm install -g nodemon
* nodemon app.js
* npm start
```
"scripts": {
"start": "node ./bin/www"
},
```
## templating
let's some templating
* handlebars (hbs)
* many modules
* easiest to actually go with hbs
* [http://handlebarsjs.com/builtin_helpers.html](http://handlebarsjs.com/builtin_helpers.html)
* installing handlebars setting up
```
npm install hbs
app.set('view engine', 'hbs');
res.render('index', {greeting:'hi!', name: 'joe'});
```
* create views
* layout.hbs - surrounding html
* remainder of template goes in {{{ body }}}
* index.hbs
* using handlebars
* vars
* escape vs noescape
* html escape values (html entities)
* loops
* arrays
* use #each and /each
* @index is index
* this is element
```
<ul>
{{#each numbers}}
<li>{{@index}} - {{this}}</li>
{{/each}}
</ul>
```
* objects
* also use #each and /each
* @key is prop name
* this is element
* also can use . notation
```
{{obj.a}}
<ul>
{{#each obj}}
<li>{{@key}} - {{this}}</li>
{{/each}}
</ul>
```
* nested
* if nested objects in list, can refer to each val by prop name (instead of this)
* or you can dot this
```
<ul>
{{#each nested}}
<li>{{this}} - {{name}} - {{this.name}}</li>
{{/each}}
</ul>
```
* conditionals
* \#if, else if, /else, .if
```
{{#if condition}}
{{else if condition}}
{{else}}
{{/if}}
{{numbers}}
{{#each numbers}}
<p>{{this}}</p>
{{/each}}
```
## middleware
* node is just a stack of middleware functions that operate on request and response objects
* until response is returned
* create our own - logging middleware
* it's just a function with req, res, next
* make sure to call next
* built-in middleware
* express static
```
path = require('path')
use(express.static(path.resolve(__dirname, 'public')));
```
* bring in css
* images, etc.
* order matters for middleware
## creating routes with Router()
* move routes
* mount as middleware to specific path
```
// in routes/movies.js
var express = require('express');
var router = express.Router();
// router.get ...
module.exports = router;
// in app.js
var moviesRoutes = require('./routes/movies');
app.use('/movies', moviesRoutes);
```
## handling gets
* how about a form with gets?
* shows up as req.query
* ok fine globals for storing
* ACTIVITY search by book author? movie title? what are we doing here?
## handling posts
* body parser
```
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
```
* get for form
* post for post req
* redirect???
* prg!!! try to use 303
* res.redirect(status code, path or url)
* ACTIVITY add new movie or book
* sample of /routes/movies.js
```
movies = [
{id:1, title:'Me You and Everyone We Know', director:'<NAME>'},
{id:2, title:'Stroszek', director:'<NAME>'},
{id:3, title:'Fitzcaraldo', director:'<NAME>'},
{id:4, title:'Eraserhead', director:'<NAME>'},
];
router.get('/create', function(req, res){
// check if id exists probz, right???
res.render('createForm');
});
router.post('/create', function(req, res) {
movies.push({title:req.body.title, director:req.body.director, id:+req.body.id})
res.redirect('/movies');
});
router.get('/', function(req, res){
res.render('movies', {movies:movies});
});
router.get('/search', function(req, res){
// res.render('movies', {movies:movies});
res.render('movies', {movies:movies.filter(directedBy)});
function directedBy(movie) {
return movie.director === req.query.director;
}
});
router.get('/:id', function(req, res){
// check if id exists probz, right???
var movie;
console.log(req.params);
for(var i = 0; i < movies.length; i++) {
if(movies[i].id === +req.params.id) {
movie = movies[i]
}
}
res.render('movie', {movie:movie});
});
```
## Mong-uh-oh!
* document store
* dbs contain collections of documents (objects)
* you can have many dbs
* you can have many collections
* javascript api to query...
* installing
* use brew / apt / etc.
* cloud ...mongolab?
* running mongod
* it may want /data/db
* if it does, make that directory or specify a directory that you have write access to
* familiar with relational dbs?
* dbs are... well dbs
* collections are tables
* objects are rows
* some commands
* use databasename // switch to a db
* show collections // display all collections in this db that we switched to
* db.collectionname.find() // all
* db.collectionname.find({prop:val}) // with prop = val
* db.collectionname.remove({prop:val})
* insert a few books / movies?
Mongoose
* ODM instead of ORM?
* we define a schema that represents a collection
* but we give it types! ... so that all documents in a collection created using this schema have same fields and types
* Schema represents a collection, buuuuut...
* it actually gives structure to it
* we define key (property names), and their types
* creating schema Movie... yields an actual collection in db
* ... collection name is movies (lowercase, and plural) in mongodb
* db and collection doesn't have to exist yet
* (not sure when it gets made... when we add or here?)
```
var mongoose = require('mongoose');
var Movie = mongoose.Schema({
title: String,
id: Number,
director: String
});
```
* now we have a schema, register it as a model
* and connect to server
```
mongoose.model('Movie', Movie); // register
// we can use model as constructor to create and insert or model name to find
mongoose.connect('mongodb://localhost/uhoh')
```
* find
```
Movie.find({title:someTitle}, function(err, movies, count){
if(err) {
// 500 more appropriate
console.log(err);
}
console.log(movies);
res.render('movies', {movies:movies});
});
```
* create
```
console.log('within post');
var p = new Pizza({
crust: req.body.crust,
size: req.body.size
})
console.log('before save');
// call save to actually store in database
//
p.save(function(err, pizza, count){
console.log('within save');
// do stuff when the save is done
console.log('error', err);
res.redirect(303, '/pizzas');
});
```
## AYYYYY JAX
* make an api end point!
* call res.json instead
* steps for get request
* var req = new XMLHttpRequest();
* req.open('GET', url, true);
* req.addEventListener("load", function() {});
* req.send();
* document.querySelector
* document.querySelectorAll
```
document.addEventListener("DOMContentLoaded", function(){
var btn = document.getElementById('btn');
btn.addEventListener("click", function(evt){
evt.preventDefault();
var url = "http://localhost:3000/api/movies";
var director = document.getElementById('director').value;
url = url + "?director=" + director;
var req = new XMLHttpRequest();
req.open('GET', url, true);
console.log('clicked');
req.addEventListener("load", function() {
console.log(req.responseText);
var tbody = document.createElement('tbody');
tbody.id = "movie-list";
JSON.parse(req.responseText).forEach(function(movie) {
var tr = tbody.appendChild(document.createElement('tr'));
tr.appendChild(document.createElement('td')).textContent = movie.title;
tr.appendChild(document.createElement('td')).textContent = movie.director;
tr.appendChild(document.createElement('td')).textContent = movie.year;
});
var movieList = document.getElementById('movie-list');
movieList.parentNode.replaceChild(tbody, movieList);
console.log(tbody);
});
req.send();
})
})
```
* for a post...
```
var request = new XMLHttpRequest();
request.open('POST', '/create', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(title='movieTitle');
```
<file_sep>var express = require('express');
var router = express.Router();
// get model constructor!
var mongoose = require('mongoose');
var Movie = mongoose.model('Movie');
movies = [
{id:1, title:'Me You and Everyone We Know', director:'<NAME>'},
{id:2, title:'Stroszek', director:'<NAME>'},
{id:3, title:'Fitzcaraldo', director:'<NAME>'},
{id:4, title:'Eraserhead', director:'<NAME>'},
];
router.get('/create', function(req, res){
// check if id exists probz, right???
res.render('createForm');
});
router.post('/create', function(req, res) {
movies.push({title:req.body.title, director:req.body.director, id:+req.body.id})
res.redirect('/movies');
});
router.get('/', function(req, res){
res.render('movies', {movies:movies});
});
/*
router.get('/search', function(req, res){
// res.render('movies', {movies:movies});
res.render('movies', {movies:movies.filter(directedBy)});
function directedBy(movie) {
return movie.director === req.query.director;
}
});
*/
router.get('/search', function(req, res){
// res.render('movies', {movies:movies});
var query = req.query.director ? {director:req.query.director} : {}
console.log('in search');
Movie.find(query, function(err, movies, count){
if(err) {
console.log(err);
}
console.log(movies);
res.render('movies', {movies:movies});
});
});
router.get('/:id', function(req, res){
// check if id exists probz, right???
var movie;
console.log(req.params);
for(var i = 0; i < movies.length; i++) {
if(movies[i].id === +req.params.id) {
movie = movies[i]
}
}
res.render('movie', {movie:movie});
});
module.exports = router;
|
13e80369e56a6723c1754411fbc736a3dd287d45
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
foureyes/tech-at-nyu-node-sp2016
|
95f716989cb7b14db7096de74a0797d8f8814512
|
5bf36b0397ce16fda714be564aff2db286673e28
|
refs/heads/master
|
<file_sep>'use strict'; // 厳格モードとする
// オブジェクト
const name = prompt('名前を入力してください');
joinUser(name);
// 入室時の処理
function joinUser(name) {
socket.emit('join_user', {name: name});
};
// 部屋ごとにゲームスタート
socket.on('enter_the_game', () => {
socket.emit('enter_the_game', {});
});
// 切断にてゲーム中断した時の処理
socket.on('refresh', () => {
setTimeout( () => {
window.location.href = 'http://127.0.0.1:3000/disconnect/';
});
});<file_sep>'use strict'; // 厳格モードとする
// オブジェクト
const socket = io.connect();<file_sep>// グローバル変数
const themes = [
'スカイツリー', '東京タワー', 'イチロー', 'マリオ', '相撲', '闇遊戯',
'織田信長', 'タピオカ', '渋谷', '宇宙', 'ボルト', 'ドラえもん',
];
module.exports = class Battle {
constructor(clients, room) {
this.room = room;
this.p1 = clients[0];
this.p2 = clients[1];
this.p3 = clients[2];
this.p1points = 0;
this.p2points = 0;
this.p3points = 0;
this.drawer = this.p1;
this.turn = 0;
this.endturn = 6;
this.waiting = 0;
this.gametheme = [];
}
getTheme() {
const tmp = [];
while (true) {
if (tmp.length === this.endturn) {
this.gametheme = tmp;
return 0;
}
let num = Math.floor(Math.random() * themes.length);
if (!tmp.includes(themes[num])) {
tmp.push(themes[num]);
}
};
};
calcPoints(io, socket) {
if (socket.id === this.p1.id) {
this.p1points += 100;
if (this.drawer.id === this.p2.id) this.p2points += 100;
else this.p3points += 100;
}
else if (socket.id === this.p2.id) {
this.p2points += 100;
if (this.drawer.id === this.p1.id) this.p1points += 100;
else this.p3points += 100;
}
else {
this.p3points += 100;
if (this.drawer.id === this.p1.id) this.p1points += 100;
else this.p2points += 100;
}
// デバッグログ
io.to(this.room).emit('game_msg', '<div>p1points:'+this.p1points+' p2points:'+this.p2points+' p3points:'+this.p3points+'</div>');
}
changeDrawer() {
if (this.drawer === this.p1) this.drawer = this.p2;
else if (this.drawer === this.p2) this.drawer = this.p3;
else this.drawer = this.p1;
}
start(io, socket) {
if (socket.id === this.drawer.id) {
// タイマースタート
io.to(this.room).emit('count_down', {});
// 現在のターン・描き手を知らせるメッセージ
io.to(this.room).emit('game_msg', '<br><div><font color="red">----- '+(this.turn+1)+'ターン目 -----</font></div>');
io.to(this.room).emit('game_msg', '<div>'+this.drawer.name+' が絵を描く番です。</div>');
// 描き手のみにお題を伝えるメッセージ
io.to(this.room).emit('theme_to_drawer', {theme: this.gametheme[this.turn], drawer: this.drawer});
}
else {
// 描き手以外のプレイターのcanvasを無効化
socket.emit('lock_canvas', {});
console.log('キャンバスがロックされました');
}
socket.on('msg_to_server', (msg) => {
if (msg === this.gametheme[this.turn] && socket.id !== this.drawer.id && this.waiting === 0) {
// 正解処理
io.to(this.room).emit('game_msg', '<div><b>正解!</b></div>');
io.to(this.room).emit('count_down_stop', {});
this.calcPoints(io, socket);
// 待機状態にする(解答しても無効)
io.to(this.room).emit('set_waiting_to_client', 1);
io.to(this.room).emit('lock_canvas', {});
setTimeout( () => {
this.turn++;
this.changeDrawer();
io.to(this.room).emit('clear_msg', {});
io.to(this.room).emit('clear_canvas', {});
io.to(this.room).emit('next_turn_to_client', {});
}, 5000);
}
});
socket.on('next_turn_to_server', () => {
this.waiting = 0;
io.to(this.room).emit('unlock_canvas', {});
if (socket.id === this.drawer.id && this.turn < this.endturn) {
// タイマースタート
io.to(this.room).emit('count_down', 0);
// 現在のターン・描き手を知らせるメッセージ
io.to(this.room).emit('game_msg', '<br><div><font color="red">----- '+(this.turn+1)+'ターン目 -----</font></div>');
io.to(this.room).emit('game_msg', '<div>'+this.drawer.name+' が絵を描く番です。</div>');
// 描き手のみにお題を伝えるメッセージ
io.to(this.room).emit('theme_to_drawer', {theme: this.gametheme[this.turn], drawer: this.drawer});
}
else if (socket.id === this.drawer.id && this.turn === this.endturn) {
io.to(this.room).emit('unlock_canvas', {});
io.to(this.room).emit('game_msg', '<div><font size=4>ゲーム終了</font></div>');
io.to(this.room).emit('game_msg', '<div>最終結果</div>');
io.to(this.room).emit('game_msg', '<div>p1points:'+this.p1points+' p2points:'+this.p2points+' p3points:'+this.p3points+'</div>');
io.to(this.room).emit('game_msg', '<div>※ 60秒後に自動退室します</div>');
setTimeout( () => {
console.log('==========ゲーム終了==========');
delete io.sockets.adapter.rooms[this.room].battle;
io.to(this.room).emit('game_over_to_client', {});
}, 60000);
}
else {
// 描き手以外のプレイターのcanvasを無効化
if (this.turn !== this.endturn) {
setTimeout( () => {
socket.emit('lock_canvas', {});
}, 100);
}
}
});
socket.on('time_up', () => {
if (socket.id === this.drawer.id) {
// タイムアップ処理
io.to(this.room).emit('game_msg', '<div><b>タイムアップ</b></div>');
// 待機状態にする(解答しても無効)
io.to(this.room).emit('set_waiting_to_client', 1);
io.to(this.room).emit('lock_canvas', {});
setTimeout( () => {
this.turn++;
this.changeDrawer();
io.to(this.room).emit('clear_msg', {});
io.to(this.room).emit('clear_canvas', {});
io.to(this.room).emit('next_turn_to_client', {});
}, 5000);
}
});
socket.on('set_waiting_to_server', (data) => {
this.waiting = data;
});
socket.on('game_over_to_server', () => {
io.to(this.room).emit('game_over', {});
});
}
};<file_sep>'use strict';
// モジュール
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const Game = require('./libs/Game.js');
// オブジェクト
const app = express();
const server = http.createServer(app);
const io = socketIO(server, {origins:'localhost:* 127.0.0.1:3000'});
// 定数
const PORT_NO = process.env.PORT || 3000;
// ゲームの作成と開始
// (ここは4人集まった部屋ごとにgameをするようにしたい)
const game = new Game();
game.start(io);
// 公開フォルダの指定
app.use(express.static(__dirname + '/public'));
// ルーティング
app.get('/disconnect', (req, res) => {
res.sendFile(__dirname + '/public/disconnect.html');
});
// サーバーの起動
server.listen(PORT_NO, () => {
console.log('Starting server on port %d', PORT_NO);
});<file_sep>socket.on('lock_canvas', () => {
$('.canvas').css('pointer-events','none');
});
socket.on('unlock_canvas', () => {
$('.canvas').css('pointer-events','auto');
});
socket.on('theme_to_drawer', (data) => {
if (data.drawer.id === socket.id) {
$('.chat').append('<div>お題は '+data.theme+' です。</div>');
$('.chat').animate({ scrollTop: $('.chat')[0].scrollHeight }, 'fast');
}
});
socket.on('game_msg', (msg) => {
$('.chat').append(msg);
$('.chat').animate({ scrollTop: $('.chat')[0].scrollHeight }, 'fast');
});
socket.on('next_turn_to_client', () => {
socket.emit('next_turn_to_server', {});
socket.emit('set_waiting_to_server', 0);
});
socket.on('set_waiting_to_client', (data) => {
socket.emit('set_waiting_to_server', data);
});
// カウントダウン処理
socket.on('count_down', (stop) => {
let count = 60;
$('.timer').text('');
let id = setInterval( () => {
$('.timer').text(count);
if (count <= 0) {
clearInterval(id);
$('.timer').text('TIME UP');
socket.emit('time_up', {});
}
count--;
}, 1000);
socket.on('count_down_stop', () => {
clearInterval(id);
$('.timer').text('');
});
});
// ゲーム終了時の処理
socket.on('game_over_to_client', () => {
socket.emit('game_over_to_server', {});
});
socket.on('game_over', () => {
setTimeout( () => {
window.location.href = 'http://127.0.0.1:3000/';
});
});<file_sep>const Battle =require('./Battle.js');
module.exports = class Game {
start(io) {
// グローバル変数
let r_num = 0;
const rooms = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
// 接続時の処理
io.on('connection', (socket) => {
let room = '';
let client = {id: '', name: ''};
console.log('connection: socket.id = %s', socket.id);
// ゲーム開始の処理
socket.on('enter_the_game', () => {
console.log('enter_the_game: socket.id = %s', socket.id);
const players = io.sockets.adapter.rooms[room].clients;
// バトルクラスの作成
if (typeof io.sockets.adapter.rooms[room].battle === 'undefined') {
io.sockets.adapter.rooms[room].battle = new Battle(players, room);
io.sockets.adapter.rooms[room].battle.getTheme();
}
io.sockets.adapter.rooms[room].battle.start(io, socket);
});
// 入室時の処理
socket.on('join_user', (data) => {
room = rooms[r_num];
client.name = data.name;
client.id = socket.id;
socket.join(room);
io.to(room).emit('connected_msg', {msg: client.name + 'さん が Room'+ room +' に入室しました。'});
console.log('%s が Room%s に入室しました', client.name, room);
if (io.sockets.adapter.rooms[room].length === 1) {
// 1つの部屋のクライアント情報を追加
io.sockets.adapter.rooms[room].clients = [];
io.sockets.adapter.rooms[room].clients.push(client);
console.log(io.sockets.adapter.rooms[room]);
}
else {
io.sockets.adapter.rooms[room].clients.push(client);
console.log(io.sockets.adapter.rooms[room]);
}
// 部屋の人数が3人になった時、ゲームスタート
if (io.sockets.adapter.rooms[room].length === 3) {
console.log('GAME START');
io.to(room).emit('clear_msg', {});
io.to(room).emit('connected_msg', {msg: '<br><font size="4"><b>GAME START</b></font>'});
setTimeout( () => {
io.to(room).emit('clear_msg', {});
io.to(room).emit('clear_canvas', {});
io.to(room).emit('enter_the_game', {});
}, 5000);
if (r_num < 6) r_num++;
else r_mum = 0;
}
});
// 切断時の処理
socket.on('disconnect', () => {
console.log('disconnect: socket.id = %s', socket.id);
console.log('room: %s', room);
if (client.name != '') {
console.log('%s が Room%s を退室しました', client.name, room);
io.to(room).emit('connected_msg', {msg: client.name + 'さん が Room'+ room +' を退室しました。'});
socket.leave(room);
if (typeof io.sockets.adapter.rooms[room] === "undefined") {}
else {
let idx = io.sockets.adapter.rooms[room].clients.indexOf(client);
if (idx >= 0) {
io.sockets.adapter.rooms[room].clients.splice(idx, 1);
}
if (typeof io.sockets.adapter.rooms[room].battle === "undefined") {}
else {
console.log('接続が切断されました。トップ画面に戻ります。');
io.to(room).emit('refresh', {});
}
}
}
});
// メッセージの処理
socket.on('msg_to_server', (msg) => {
io.to(room).emit('msg_to_client', {msg: msg, name: client.name});
console.log('%s: %s', client.name, msg);
});
// キャンバスの処理
socket.on('draw', (data) => {
socket.to(room).emit('draw', data);
});
socket.on('color', (color) => {
socket.to(room).emit('color', color);
});
socket.on('lineWidth', (width) => {
socket.to(room).emit('lineWidth', width);
});
socket.on('clear_canvas', () => {
io.to(room).emit('clear_canvas', {});
});
});
}
};
|
35608689cd3560e6f39c1fc312909f37e265ec7b
|
[
"JavaScript"
] | 6
|
JavaScript
|
Kazuya-dx/illustbattle
|
e5c965cbdfac5822d3f7a51d2ce9ae69c4219715
|
db4a920f83461ae1d7de74c76f9be52e6fb9080b
|
refs/heads/master
|
<file_sep>#High Level Requirements
This project is a project for the MSSA program that accomplishes the following goals:
-Minimum Viable Product Features:
-Have a database to store user data i.e (Login info, History, Health details, Custommer ID)
-Contain an 8 week workout program that supports the users needs
-Be accessible on a computer
-Macro nutrient calculator
-Full Product Details
-Can post to social media sites (Facebook, Twitter, and instagram)
-Have a accessible user interface that can be used on phones and tablets
-Stretch Product Details
-Contain multimedia functions such as videos demonstrating workouts, how to test heart rate, meal prep etc.
-Contain an in app community forum for user to share advice and post inspiration pictures.<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectLibrary.Model
{
private int ID;
private string Description;
private string Name;
class Calendar
{
}
}
<file_sep>#User Need Statement
This project is a project for the MSSA program that accomplishes the following goals:
-Keeps a record of personal fitness data
-Creates reccomendations based on those results
-Changes reccomendations based on user needs and schedule to keep user on track to fitness goals
In the course of this project I will use ASP.NET and C# to build a an online platform where users can store personal data related to fitness goals and track progress using stored algorithms which will reccomend daily calorie intake and workout suggestions. Workouts data will be preloaded into the system and will follow an eight week progression which will include five days of working out and two days of active recovery.
The Features of this project include:
-Eight week strength training / conditioning regiment that incorporates weight training and body weight excercises that takes into account age and heart rate
-A nutritional guide (MACRO calculator, meal time reminder, and sleep / rest cycle)
-Optional status updates to all major social media sites (When a user finishes a workout or hit a major milestone)<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectLibrary.Model
{
private int ID;
private int weights;
class ExcerciseLoad
{
}
}
<file_sep>using System;
namespace ProjectLibrary.Model
{
private int ID;
private string Description;
private string Name;
public class Excercise
{
}
}
<file_sep>#Requirements
Functional: -Have a database to store user data
- As a User I can create an account:
1. User clicks on account creation option
2. User is prompted to fill in the following fields:
First Name
Last Name
Username
Password
Password hint
3. The following rules will apply to each field
First and Last Name: text only fields. Limited to 60 characters
Username: text and numeric field. Limited to 20 characters
Password: must be at least 9 characters, with at least 1 uppercase letter, 1 number and 1 special character
-As a User I can login to my account:
1. User clicks on account login option
2. User is prompted to fill in the following fields:
Username
Password
- If the user unsuccesfully logs in after three attempts the will be prompted to try again or ask for hint.
-The hint will be displayed
-As a user I can reset my password:
1. User clicks on account reset password option
2. User is prompted to fill in the following fields:
Previous password
New password x2
3. The following rules will apply to each field
Password: must be at least 9 characters, with at least 1 uppercase letter, 1 number and 1 special character
-As a a User once I login for the first time I should see a Welcome banner
1. The user completes their account set up and logs in successfully for the first time.
-A banner will read "Welcome, to your 8 week fitness guide"
-As a a User once I login for the first time I should see a Purpose statement after the welcome banner
1. The user completes their account set up and logs in successfully for the first time.
2. The user will see the welcome banner and click next in the bottom right corner
-The user will see a Purpose statement which will read a mission statement like
"This fitness program focuses on improving physical performance through excercise and nutrition. It provides photos and descriptions of excercises."
-As a a User once I login for the first time I should see a How to use guide after the purpose statement
1. The user completes their account set up and logs in successfully for the first time.
2. The user will see the welcome banner and click next in the bottom right corner
3.The user will see the purpose statement and click next in the bottom right corner
-The user will see a user guide which will tell the user how to use the app
"This app uses ab 8 week fitness routine. It recommended you start on a monday and progress through the program everyday.If you miss a day, thats fine; just shift your schedule, and continue the program in its intended order."
Non-Functional:Contain an 8 week workout program that supports the users needs
-As a user I should be able to view my excercise guide weeks 1-8
1.The user will login and see there 8 week program laid out in front of them
-Users can choose to look at any week
-As a User I should be able to choose a week and be able to choose any day within that week
1.The user can select any week 1-8 and see a list of all the days they will train that week labeled 1-5.
-Since it is a 5 day 8 week program there is no point to label them by day.
-As a user I should be able to choose a day and see my routine for that day
1. The user will choose a day that corresponds with a given week and inside that day they will see there workout routine.
-As a user I should be able to see a photograph along with a detailed description of each workout inside of each day
1.The user will choose a workout inside of a daily routine and see the results
- A photograph depicting the excercise and a step by step instruction guide on how perform the excercise
-As a user I should be able to mark workouts I have already completed
1. The user will check a box besides a week or day
-This will help the user remember where they left off.
-As a user I should be able to mark excercises I have already completed
1. The user will check a box besides a excercise
-This will help the user remember where they left off.
Functional: Be accessible on a computer
-As a User once I click the menu button I should see a menu
1.The user will click the menu icon
2. A dropdown will appear with a list of choices for the user to select
-Help
-Nutrition
-Rest / Recovery
-Excercise List
-Required Equipment
-Reset Data
-As a User I should be able to access the Welcome Banner, Purpose Statement, and How to use guide at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Help
-The Welcome banner, Purpose Statement, and User guide will all be available choices under help
-As a User I should be able to access the nutrition page at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Nutrition
-The nutrition page will suggest caloric intake, proteins, fats, and carbohydrates.
-Will feature a calorie calculator based on body dimensions such as height and weight
-As a User I should be able to access the Rest / Recovery guide at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Rest / Recovery
-This is a page full of strecthes and suggestions for the user to follow on rest days
-As a User I should be able to access the Excercise List at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Excercise List
-This page will containt every excercise used in the eight week program
-As a User I should be able to access the Required Equipment at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Required Equipment
-This page will list all the equipment a user will need for the 8 week program
-As a User I should be able to access the Reset Data at any point by clicking a icon on the drop down
1.User will select drop down in top left corner
2.User will select Reset Data
3.A screen will pop up and ask the user if they are sure they want to reset their data and two buttons will appear that say yes or no
-This will uncheck all boxes on the weeks, days, and workouts.
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectLibrary.Model
{
private int ID;
private int Macros;
class MacroCalculator
{
}
}
<file_sep>/* 3. syntatic sugar makes code more concise and easy to read*/
using System;
namespace EX2B
{
class Program
{
static void Main(string[] args)
{
dogBark();
dogBark("Hershey");
dogBark("Hobo", "HaHa");
}
//1.
private static void dogBark(string dog = "Brutus", string sound = "Arf Arf")
{
Console.WriteLine($"The {dog} goes \"{sound}\"!");
}
// 2.
private static void dogBark(string dog)
{
dogBark(dog, "woof");
}
private static void dogBark()
{
dogBark("Frenchie", "Howl");
}
}
}
<file_sep>using System;
namespace ProgEXA
{
class Program
{
public static void Main(string[] args)
{
//1.
Console.WriteLine("Number of test");
double sum = 0;
double testScore1 = 0;
for (int count = 0; count < 10; count++)
{
sumloop:
Console.WriteLine("Please enter a test score between 0 and 100");
testScore1 = double.Parse(Console.ReadLine());
if (testScore1 < 0 || testScore1 > 100)
{
Console.WriteLine("Invalid input");
goto sumloop;
}
sum = sum + testScore1;
}
Console.WriteLine($"The sum of your test score is : {sum}");
//2.
double sum3 = 0;
double testScore3 = 0;
double average3 = 0;
for (int count = 0; count < 10; count++)
{
sumloop:
Console.WriteLine("Please enter a test score between 0 and 100");
testScore3 = double.Parse(Console.ReadLine());
if (testScore3 < 0 || testScore3 > 100)
{
Console.WriteLine("Invalid input");
goto sumloop;
}
sum3 = sum3 + testScore3;
}
average3 = sum3 / 10;
Console.WriteLine($"The average of your test score is : {Math.Round(average3, 2)}");
if (average3 >= 90)
{
Console.WriteLine("A average");
}
else if (average3 >= 80)
{
Console.WriteLine("B average");
}
else if (average3 >= 70)
{
Console.WriteLine("C average");
}
else if (average3 >= 60)
{
Console.WriteLine("D average");
}
else
{
Console.WriteLine("F average");
}
//3.
Console.WriteLine("Number of test");
double sum4 = 0;
double maxIterations = double.Parse(Console.ReadLine());
double average = 0;
double testScore = 0;
for (int count = 0; count < maxIterations; count++)
{
sumloop:
Console.WriteLine("Please enter a test score between 0 and 100");
testScore = double.Parse(Console.ReadLine());
if (testScore < 0 || testScore > 100)
{
Console.WriteLine("Invalid input");
goto sumloop;
}
sum4 = sum4 + testScore;
}
average = sum4 / maxIterations;
Console.WriteLine($"The average of your test score is : {Math.Round(average, 2)}");
if (average >= 90)
{
Console.WriteLine("A average");
}
else if (average >= 80)
{
Console.WriteLine("B average");
}
else if (average >= 70)
{
Console.WriteLine("C average");
}
else if (average >= 60)
{
Console.WriteLine("D average");
}
else
{
Console.WriteLine("F average");
}
//4.
Console.WriteLine("This console app will accept multiple test scores between 0 and 100, take the average, and the give letter grade.");
double inputUser = 0;
double avgUser = 0;
double totalUser = 0;
int j = 0;
for (; ; )
{
userloop:
Console.WriteLine("Please enter a test score between 0 and 100, when ready to quit input \"808\"");
inputUser = double.Parse(Console.ReadLine());
if (inputUser == 808)
break;
else if(inputUser < 0 || inputUser > 100)
{
Console.WriteLine("Invalid input");
goto userloop;
}
else if (inputUser > 0 || inputUser <= 100)
{
totalUser = inputUser + totalUser;
j ++;
}
}
avgUser = totalUser / j;
Console.WriteLine($"The average of your test score is : {Math.Round(avgUser, 2)}");
if (avgUser >= 90)
{
Console.WriteLine("A average");
}
else if (avgUser >= 80)
{
Console.WriteLine("B average");
}
else if (avgUser >= 70)
{
Console.WriteLine("C average");
}
else if (avgUser >= 60)
{
Console.WriteLine("D average");
}
else
{
Console.WriteLine("F average");
}
}
}
}
<file_sep>use Northwind
-- 1. What are the Regions?
select *
from Region;
--2. what are the cities?
select*
from Territories;
select T.TerritoryDescription as Cities
from Territories as T;
select distinct T.TerritoryDescription as Cities
from Territories as T
order by Cities desc;
--3. what are the cities in the southern region?
select RegionID
from Region
where RegionDescription like 'South%';
select distinct T.TerritoryDescription as Cities, T.RegionID
from Territories as T
where T.RegionID = 4
order by Cities desc;
--4. number 3 with fully qualified column names
select distinct Territories.TerritoryDescription as Cities, Territories.RegionID
from Territories
where Territories.RegionID = 4
order by Cities desc;
--5. number 3 with an alias
select distinct T.TerritoryDescription as Cities, T.RegionID
from Territories as T
where T.RegionID = 4
order by Cities desc;
--6. What is the contact name telephone number and city for each customer.
select C.ContactName, C.CompanyName, C.Phone, C.City
from Customers as C;
--7. What are the products currently out of stock?
select *
from Products
where Discontinued = 0
and UnitsInStock = 0;
-- 8. What are the 10 products in stock with the least amount on hand?
select top(10) *
from Products
where Discontinued > 0
order by UnitsInStock asc;
--9. What are the most expensive products?
select top(5)*
from Products
where Discontinued = 0 or UnitsInStock > 0
order by UnitPrice desc;
--10.How many products does Northwind have? How many customers? How many suppliers?
select count(*)
from Products as ProductCount;
select count(*)
from Customers as CustomerCount;
select count(*)
from Suppliers as SuppliersCount;
<file_sep>using System;
using System.Linq.Expressions;
namespace progex03c
{
class Program
{
private static int bottom;
private static int height;
// first comment
static void Main(string[] args)
{
// Part 1
// Partially worked example
try
{
Console.WriteLine("\nPart 1, circumference of a circle.");
Console.Write("Enter an integer for the radius: ");
string strradius = Console.ReadLine();
int intradius = int.Parse(strradius);
while (intradius != 0)
{
checked
{
double circumference = 2 * Math.PI * intradius;
Console.WriteLine($"The circumference is {circumference}");
}
break;
}
}
catch (FormatException)
{
Console.WriteLine("Not a valid integer. Try again.");
}
finally
{
Console.WriteLine("This program has finally terminated.");
}
try
{
Console.WriteLine("\nPart 1-2, area of a circle.");
Console.Write("Enter an integer for the radius: ");
string strradius = Console.ReadLine();
int intradius = int.Parse(strradius);
while (intradius != 0)
{
checked
{
double area = Math.PI * Math.Pow(intradius, 2);
Console.WriteLine($"The area is {area}");
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("Not a valid integer. Try again.");
}
finally
{
Console.WriteLine("This program has finally terminated.");
}
try
{
// Part 2
Console.WriteLine("\nPart 2, volume of a hemisphere.");
// Implementation here
Console.Write("Enter an integer for the radius: ");
string strradius1 = Console.ReadLine();
int intradius1 = int.Parse(strradius1);
while (intradius1 != 0)
{
checked
{
double v2 = 2 / 3.0 * Math.PI * Math.Pow(intradius1, 3);
double volume = v2;
Console.WriteLine($"The volume is {volume}");
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("Not a valid integer. Try again.");
}
finally
{
Console.WriteLine("This program has finally terminated.");
}
try
{
// Part 3
Console.WriteLine("\nPart 3, area of a triangle (Heron's formula).");
// Implementation here
Console.Write("Enter an integer for the bottom ");
string strbottom = Console.ReadLine();
int intbottom = int.Parse(strbottom);
Console.Write("Enter an integer for the height ");
string strheight = Console.ReadLine();
int intheight = int.Parse(strheight);
while (intheight != 0 && intbottom != 0)
{
checked
{
double v1 = intbottom * intheight * .5;
double area1 = v1;
Console.WriteLine($"The area is {area1}");
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("Not a valid integer. Try again.");
}
finally
{
Console.WriteLine("This program has finally terminated.");
}
Console.WriteLine("\nPart 4, solving a quadratic equation.");
// Implementation here
Console.Write("Enter an integer for the a ");
float a = float.Parse(Console.ReadLine());
Console.Write("Enter an integer for the b ");
float b = float.Parse(Console.ReadLine());
Console.Write("Enter an integer for the c ");
float c = float.Parse(Console.ReadLine());
while ((b * b - 4 * a * c) > 0)
{
checked
{
double deltaRoot = Math.Sqrt(b * b - 4 * a * c);
if (deltaRoot >= 0)
{
double x1 = (b + deltaRoot) / 2.0 * a;
double x2 = (-b + deltaRoot) / 2.0 * a;
Console.WriteLine($"The positive solution is { x1 }");
Console.WriteLine($"The negative solution is { x2 }");
}
else
{
Console.WriteLine($"there are no roots");
}
break;
}
}
}
}
}
<file_sep>Eight Week Fitness App (EWFA)
##Fit4Life
The Idea
What is Eight Week Fitness App?
The process of staying in shape and acheiving new results in body strength, size and shape.
The Benefits
Promotes A Healthy Life Style
Discourages Couch Potato syndrom
Provides More Choices clients
Saves Money and Time spent in the gym
Minimizes wasted workouts and effort
For More Information check out the reference: [A link to msn] (https://www.msn.com/en-us/health/fitness)
The Project
What is EWFA?
By utilizing the ASP.NET MVC & C#, I have created an application known as "EWFA". This project was created in a span of 18 weeks. During this project, I wanted a safe way to excercise at home especialy during the COVID-19 pandemic times. EWFA is an interesting idea that I wanted to create into an application.
About The Developer
Developer: <NAME>.
Course: Microsoft Software & Systems Academy
Path: Cloud Application Developer Path
Thanks
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
namespace MonteCarlo
{
class Program
{
static void Main(string[] args)
{
var rand = new Random();
Console.WriteLine("enter a number");
double total = 0.0;
int iterations = int.Parse(Console.ReadLine());
Loop:
for (int i = 0; i < iterations; i++)
{
double output = GetHypotenuse(rand);
if (output <= 1.0)
{
total++;
}
Console.WriteLine($"output is {output}");
}
Console.WriteLine($"Hypotenuse above one Total is {total}");
var myPI = (4.0 * total) / iterations;
Console.WriteLine($"Hypotenuse above one divided by iterations multiplied by four subtracted from pie is {Math.Abs((Math.PI) - myPI)}");
}
//static (double, double) randomNums(Random rand)
//{
// double c = rand.NextDouble();
// double d = rand.NextDouble();
// return new Tuple<double, double>(c, d);
//}
static double GetHypotenuse(Random rand)
{
double c = rand.NextDouble();
double d = rand.NextDouble();
return Math.Sqrt((Math.Pow(c, 2) + Math.Pow(d, 2)));
}
}
}
/*
* 7. 10- 1,632 ms 100- 1,700 ms 1000- 2,020 ms 10000 - 3,459 ms
*1. Why do we multiply the value from step 5 above by 4?
*Because there are four quadrants in the unit circle
2.What do you observe in the output when running your program with parameters of increasing size?
The percentage of numbers below or equal to one remains consistently within 70 - 80% of the total iterations.
3.If you run the program multiple times with the same parameter, does the output remain the same? Why or why not?
No because the variables change each time
4.Find a parameter that requires multiple seconds of run time. What is that parameter?
1.0 x 10^ 10
5.How accurate is the estimated value of pi?
The double is only accurate up to 3.14159265358979000000
6.Research one other use of Monte-Carlo methods. Record it in your exercise submission and be prepared to discuss it in class.
Monte Carlo simulation: Drawing a large number of pseudo-random uniform variables from the interval [0,1] (much like our code) at one time,
or once at many different times, and assigning values less than or equal to 0.50 as heads and greater than 0.50 as tails,
is a Monte Carlo simulation of the behavior of repeatedly tossing a coin.
*/
|
e2e06256527eb807665f4c9e2ab93c573ba5ed4b
|
[
"Markdown",
"C#",
"SQL"
] | 13
|
Markdown
|
PEREZR27/CourseProject
|
20ef58bd4bfcb5b02691b14b39583f2ed54195d5
|
297b430d9e4c376ad84d906f9bf637188d4553e7
|
refs/heads/master
|
<repo_name>nicklasbring/PillefyrStyring<file_sep>/PillefyrsStyring.ino
/********************************************************************/
//Inkluder biblioteker
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SoftwareSerial.h>
/********************************************************************/
//Temperatur sensor er tilsuttet port 9
#define ONE_WIRE_BUS 9
//TX og RX til gsm modul er tilsuttet port 7 0g 8
SoftwareSerial SIM900(7, 8);
/********************************************************************/
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);
int relay = 6;
/********************************************************************/
//String som indeholder text beskeden
String textMessage;
//boolean til at vide om fyret har genstartet siden sidst det var under 30 grader
bool hasRestarted = false;
void setup(){
Serial.begin(19200);
SIM900.begin(19200);
sensor.begin();
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
Serial.println("Pilefyr Styring 1.0");
//delay inden opkoblingen på gsm netværket
delay(10000);
//Serial.print("GSM modul er klart...");
// AT kommando der sætter modulet til sms mode
SIM900.print("AT+CMGF=1\r");
delay(100);
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop(void){
//Kører processen som læser inkommende beskeder
modtagSms();
//Kommando for at modtage temperaturmålinger og udskrive dem
sensor.requestTemperatures();
double temp = sensor.getTempCByIndex(0);
//Serial.print(String("\nTempereatur = ") + temp);
// tjekker om fyret har været genstarted siden det var under 30 grader
if(temp >= 35 && hasRestarted == true){
hasRestarted = false;
}
//If statement som skal sende en besked når fyret går ud.
if (temp <= 35 && hasRestarted == false) {
sendSms("Fyret er slukket! \nTast 'genstart' for at genstarte");
//Serial.println("\nSMS er sendt!");
hasRestarted = true; // retter bool så systemet ved at fyret er blevet genstartet
}
delay(10000);
}
//Metode til at modtage en sms
void modtagSms (){
if(SIM900.available()>0){
textMessage = SIM900.readString();
//Serial.print(textMessage);
delay(10);
}
//Hvis komandoen "genstart" bliver skrevet, genstarter relæet fyret
if(textMessage.indexOf("genstart")>=0){
double temp = sensor.getTempCByIndex(0);
//Serial.println("Genstarter fyret");
//Serial.print(String("\nTempereatur = ") + temp);
sendSms("Fyret Genstarter" + (String("\nAktuel Temperatur = ") + temp) );
digitalWrite(relay, LOW);
delay(10000);
digitalWrite(relay, HIGH);
textMessage = "";
}
//Hvis komandoen "status" bliver skrevet, sender den temperaturen på sms
if(textMessage.indexOf("status")>=0){
double temp = sensor.getTempCByIndex(0);
//Serial.println("Status Sendt");
//Serial.print(String("\nTempereatur = ") + temp);
sendSms(String("Temperatur = ") + temp);
textMessage = "";
}
}
//Metode der sender besked tilbage til klient
void sendSms(String message){
SIM900.print("AT+CMGF=1\r");
delay(100);
//X'erne bliver erstatet med nummeret man vil tilnkytte styringen til
SIM900.println("AT+CMGS=\"xxxxxxxx\"");
delay(100);
// Send the SMS
SIM900.println(message);
delay(100);
SIM900.println((char)26);
delay(100);
SIM900.println();
delay(5000);
}
<file_sep>/README.md
# PillefyrStyring
## Temperaturovervågning med GSM alarm og kommandoer
Jeg har lavet en styring til et fyr, som skal måle temperaturer fra fremløbsrøret på et pillefyr.
Fyret har det nemlig med at gå ud, så med styringen kan man få en sms så snart det sker.
Den indeholder også 2 kommandoer. Hvis man skriver 'status' til styringen, får man en besked med temperaturen.
Den anden kommando kan genstarte fyret og derved få det til at køre igen. Hvis man skriver 'genstart', vil et relæ nemlig slukke og tænde, og derved genstarte hele fyret.
#### Tilbehør brugt:
* Arduino Nano
* Breadboard
* GSM modul (SIM-900)
* 1 kanals relæ
* Temperaturmåler
* 5k resistor
#### Libraries brugt:
* OneWire.h
* DallasTemperature.h
* SoftwareSerial.h
|
2abe02529ca5af164a5f901be54c4a9d2f692125
|
[
"Markdown",
"C++"
] | 2
|
C++
|
nicklasbring/PillefyrStyring
|
9dec06251633e4a599189baf1836a35475bf926d
|
9c9c0cf4b4e580e507ad5b0ba0f2a01cf53ecdf2
|
refs/heads/master
|
<repo_name>sdanke/deform_conv_v2<file_sep>/src/modulated_deform_conv_cuda.h
#pragma once
#include <torch/extension.h>
#ifdef __cplusplus
extern "C"
{
#endif
at::Tensor
modulated_deform_conv_cuda_forward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
std::vector<at::Tensor>
modulated_deform_conv_cuda_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
#ifdef __cplusplus
}
#endif
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(deform_conv_v2)
add_definitions(-D WITH_CUDA)
IF (CMAKE_BUILD_TYPE MATCHES "Debug")
set(Torch_DIR "F:/workspace/code/lib/libtorch/debug/share/cmake/Torch") #path to libtorch
ELSE ()
set(Torch_DIR "F:/workspace/code/lib/libtorch/release_1_7_1/share/cmake/Torch")
ENDIF ()
find_package(CUDA)
if(NOT CUDA_FOUND)
message(FATAL_ERROR "CUDA Not Found!")
endif(NOT CUDA_FOUND)
find_package(Python3 3.6.10 COMPONENTS Development)
if(NOT Python3_FOUND)
message(FATAL_ERROR "Python Not Found!")
endif(NOT Python3_FOUND)
message(STATUS "Python status:")
message(STATUS " libraries: ${Python3_LIBRARIES}")
message(STATUS " includes: ${Python3_INCLUDE_DIRS}")
find_package(Torch REQUIRED)
if(NOT Torch_FOUND)
message(FATAL_ERROR "Pytorch Not Found!")
endif(NOT Torch_FOUND)
message(STATUS "Pytorch status:")
message(STATUS " libraries: ${TORCH_LIBRARIES}")
include_directories(${Python3_INCLUDE_DIRS})
set(CUDA_HOST_COMPILATION_CPP ON)
# set_target_properties(PROPERTIES CUDA_RESOLVE_DEVICE_SYMBOLS ON)
set(TORCH_NVCC_FLAGS "-D__CUDA_NO_HALF_OPERATORS__")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /GF /Z7 /FS")
set(CUDA_NVCC_FLAGS -D__CUDA_NO_HALF_OPERATORS__)
file(GLOB SRC_LIST "src/*.cpp" "src/*.cu" "src/*.cuh")
message(STATUS " src: ${SRC_LIST}")
cuda_add_library(${PROJECT_NAME} SHARED ${SRC_LIST})
target_link_libraries(${PROJECT_NAME}
${TORCH_LIBRARIES}
${Python3_LIBRARIES}
)
target_compile_features(${PROJECT_NAME} PRIVATE cxx_range_for)
# set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 14)
set_target_properties( ${PROJECT_NAME}
PROPERTIES
CXX_STANDARD 14
DEBUG_POSTFIX "_d"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION lib)<file_sep>/src/dcn_v2.cpp
#include <torch/script.h>
// #include "deform_conv_cpu.h"
// #include "deform_psroi_pooling_cpu.h"
// #include "modulated_deform_conv_cpu.h"
// #ifdef WITH_CUDA
#include "deform_conv_cuda.h"
#include "deform_psroi_pooling_cuda.h"
#include "modulated_deform_conv_cuda.h"
// #endif
void init() {
}
at::Tensor
deform_conv_forward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step)
{
if (input.type().is_cuda()) {
#ifdef WITH_CUDA
return deform_conv_cuda_forward(input, weight, bias, offset,
kernel_h, kernel_w,
stride_h, stride_w,
pad_h, pad_w,
dilation_h, dilation_w,
group,
deformable_group,
im2col_step);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
std::vector<at::Tensor>
deform_conv_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step)
{
if (input.type().is_cuda()) {
#ifdef WITH_CUDA
return deform_conv_cuda_backward(input,
weight,
bias,
offset,
grad_output,
kernel_h, kernel_w,
stride_h, stride_w,
pad_h, pad_w,
dilation_h, dilation_w,
group,
deformable_group,
im2col_step);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_forward(const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std)
{
if (input.type().is_cuda())
{
#ifdef WITH_CUDA
return deform_psroi_pooling_cuda_forward(input,
bbox,
trans,
no_trans,
spatial_scale,
output_dim,
group_size,
pooled_size,
part_size,
sample_per_part,
trans_std);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_backward(const at::Tensor &out_grad,
const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const at::Tensor &top_count,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std)
{
if (input.type().is_cuda())
{
#ifdef WITH_CUDA
return deform_psroi_pooling_cuda_backward(out_grad,
input,
bbox,
trans,
top_count,
no_trans,
spatial_scale,
output_dim,
group_size,
pooled_size,
part_size,
sample_per_part,
trans_std);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
at::Tensor
modulated_deform_conv_forward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step)
{
if (input.type().is_cuda())
{
#ifdef WITH_CUDA
return modulated_deform_conv_cuda_forward(input, weight, bias, offset, mask,
kernel_h, kernel_w,
stride_h, stride_w,
pad_h, pad_w,
dilation_h, dilation_w,
group,
deformable_group,
im2col_step);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
std::vector<at::Tensor>
modulated_deform_conv_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step)
{
if (input.type().is_cuda())
{
#ifdef WITH_CUDA
return modulated_deform_conv_cuda_backward(input,
weight,
bias,
offset,
mask,
grad_output,
kernel_h, kernel_w,
stride_h, stride_w,
pad_h, pad_w,
dilation_h, dilation_w,
group,
deformable_group,
im2col_step);
#else
AT_ERROR("Not compiled with GPU support");
#endif
}
AT_ERROR("Not implemented on the CPU");
}
static auto registry =
torch::RegisterOperators("dcn_v2_ops::deform_conv_forward", &deform_conv_forward)
.op("dcn_v2_ops::deform_conv_backward", &deform_conv_backward)
.op("dcn_v2_ops::deform_psroi_pooling_forward", &deform_psroi_pooling_forward)
.op("dcn_v2_ops::deform_psroi_pooling_backward", &deform_psroi_pooling_backward)
.op("dcn_v2_ops::modulated_deform_conv_forward", &modulated_deform_conv_forward)
.op("dcn_v2_ops::modulated_deform_conv_backward", &modulated_deform_conv_backward);
<file_sep>/src/dcn_v2.h
#include <torch/script.h>
void init();
at::Tensor
deform_conv_forward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
std::vector<at::Tensor>
deform_conv_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
std::vector<at::Tensor>
deform_conv_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_forward(const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std);
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_backward(const at::Tensor &out_grad,
const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const at::Tensor &top_count,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std);
at::Tensor
modulated_deform_conv_forward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step);
std::vector<at::Tensor>
modulated_deform_conv_backward(const at::Tensor &input,
const at::Tensor &weight,
const at::Tensor &bias,
const at::Tensor &offset,
const at::Tensor &mask,
const at::Tensor &grad_output,
const int64_t kernel_h,
const int64_t kernel_w,
const int64_t stride_h,
const int64_t stride_w,
const int64_t pad_h,
const int64_t pad_w,
const int64_t dilation_h,
const int64_t dilation_w,
const int64_t group,
const int64_t deformable_group,
const int64_t im2col_step)
<file_sep>/README.md
# Deformable-ConvNets-V2
Modified from [Deformable Convolution V2](https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch).<file_sep>/src/deform_psroi_pooling_cuda.h
#pragma once
#include <torch/extension.h>
#ifdef __cplusplus
extern "C"
{
#endif
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_cuda_forward(const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std);
std::tuple<at::Tensor, at::Tensor>
deform_psroi_pooling_cuda_backward(const at::Tensor &out_grad,
const at::Tensor &input,
const at::Tensor &bbox,
const at::Tensor &trans,
const at::Tensor &top_count,
const int64_t no_trans,
const double spatial_scale,
const int64_t output_dim,
const int64_t group_size,
const int64_t pooled_size,
const int64_t part_size,
const int64_t sample_per_part,
const double trans_std);
#ifdef __cplusplus
}
#endif
|
cd2f580665a9f852c772da92da73b4c624bcc3ee
|
[
"Markdown",
"CMake",
"C++"
] | 6
|
C++
|
sdanke/deform_conv_v2
|
567f656bc5ee888dc9d05d80f97ac325359d2a0e
|
0c5cd423bd97dc685423605870f7f9c8611b67aa
|
refs/heads/master
|
<repo_name>MsLolita/adBlock_adFinder<file_sep>/README.md
# ad Finder&Block
This is an application for people who:
* *are infuriated by advertising on Facebook;*
* *would like to find relevant products for sale.*
### Looks as:



It has three position:
1. **off**(default):
abort working;
2. **adFinder**:
show only ad posts(left all that is not content posts);
3. **adBlock**:
block ad posts to see only content.
Tips to use:
1. *Firstly download in zip this package and unzip it to any folder:*

3. *Then:
3.1 go to browser's extension;
3.2 click on developer mode;
3.3 download unzipped extension:*

4. *Choose unzipped earlier folder:*

5. *Go to facebook and test it.*
<file_sep>/js/choosePosition.js
'use strict';
class ChooseWorkerByPosition {
#currentWorker;
constructor() {
this.#startUpWorker();
}
async #startUpWorker() {
const srcAdWorker = chrome.extension.getURL('js/adWorker.js');
const { default: AdWorker } = await import(srcAdWorker);
this.#currentWorker = new AdWorker();
chrome.storage.local.get('textPosition', ({ textPosition }) => this.chooseAction(textPosition));
}
chooseAction(textPosition) {
switch (textPosition) {
case 'adFinder':
case 'adBlock':
this.#currentWorker.startWorker(textPosition);
break;
case 'off':
this.#currentWorker.stopWorking();
break;
}
}
checkAction() {
chrome.runtime.onMessage.addListener(textPosition => this.chooseAction(textPosition));
}
}
const newWorker = new ChooseWorkerByPosition();
newWorker.checkAction();<file_sep>/js/adWorker.js
'use strict'
export default class AdWorker {
amountAdPosts = 0;
#workingProcess;
#selectorToShow;
get isRunning() {
return !!this.#workingProcess;
}
startWorker(typeWorker) {
this.#selectorToShow =`span[id] > ${ typeWorker === "adFinder" ? "" : "span" } a[tabindex='0'] > span`;
if (!this.isRunning)
this.#workingProcess = setInterval(this.#checkIfWasLoading.bind(this), 200);
}
stopWorking() {
clearInterval(this.#workingProcess);
this.#workingProcess = null;
}
#checkIfWasLoading() {
if (AdWorker.#allPosts().length > this.amountAdPosts) {
this.#delPosts();
this.amountAdPosts = AdWorker.#allPosts().length;
}
}
static #allPosts() {
return document.querySelectorAll("div[data-pagelet^=FeedUnit_]");
}
#delPosts() {
AdWorker.#allPosts().forEach(e =>
e.querySelector(this.#selectorToShow) || e.parentNode.removeChild(e)
);
}
}<file_sep>/js/elements.js
'use strict'
const switchPosition = document.querySelectorAll('.switch__position'),
adFinderText = document.querySelector('.ad__Finder'),
offText = document.querySelector('.off'),
adBlockText = document.querySelector('.ad__Block'),
switchSlider = document.querySelectorAll('.switch__radio'),
adFinderSlider = document.querySelector('.switch__radio__finder'),
offSlider = document.querySelector('.switch__radio__off'),
adBlockSlider = document.querySelector('.switch__radio__block');
export { switchPosition, adFinderText, offText, adBlockText, switchSlider, adFinderSlider, offSlider, adBlockSlider }
|
04b0374e02fb7c9f6aa0f0ff9ab9f3cccfc5c729
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
MsLolita/adBlock_adFinder
|
4a8e9c231cdb9dbc5e589515de313e09a38e81fa
|
748c34761d43fd787381436c04bde2572733cda5
|
refs/heads/master
|
<file_sep>const admin = require('firebase-admin');
var serviceAccount = require("./firebase_admin_key.json");
const webpush = require('web-push');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushtest-c0b5a.firebaseio.com"
});
// This registration token comes from the client FCM SDKs.
var registrationTokens = [
'<KEY> <KEY>
]
// var message = {
// data: {
// score: '850',
// time: '2:45'
// },
// token: registrationToken,
// // "notification": {
// // "title": "Title",
// // "body": " body"
// // },
// // "webpush": {
// // "fcm_options": {
// // "link": "https://www.naver.com"
// // }
// // }
// };
var payload = {
data: {
score: '850',
time: '2:45'
}
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().sendToDevice(registrationTokens, payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});<file_sep>console.log('ss');
messaging = firebase.messaging();
window.subscriptionInfo = '';
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('sw_subpage.js').then(function (registration) {
// Registration was successful
console.log(registration.test);
console.log('ServiceWorker registration successful with scope: ', registration.scope);
messaging.useServiceWorker(registration);
registration.test='test';
registration.pushManager.getSubscription().then(info=>window.subscriptionInfo = info);
}, function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
function requestPush(){
if(Notification.permission === 'denied') return false;
Notification.requestPermission().then((permission)=>{
if(permission === 'granted'){
window.messaging.getToken().then(currentToken=>{
console.log(currentToken)
})
}
})
};
function getSubscription(){
}<file_sep>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin:true});
var serviceAccount = require("./firebase_admin_key.json");
const webpush = require('web-push');
const applicationServerPublicKey = '<KEY>';
const applicationServerPrivate = '<KEY>'
const applicationServerPublicKey2 = '<KEY>';
const applicationServerPrivate2 = '<KEY>'
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushtest-c0b5a.firebaseio.com"
});
exports.helloWorld = functions.https.onRequest((request, response) => {
console.log('hello from firebase');
response.send("Hello from Firebase!!");
});
// subscription 저장
exports.storeSubscription = functions.region('asia-northeast1').https.onRequest(function(req, res){
cors(req, res, function(){
let body = JSON.parse(req.body)
let subscription = body.subscription
let sort = body.sort
admin.database().ref('subscription').push({subscription, sort}).then(()=>{
res.status(201).json({message:'Data stored', subscription: subscription})
}).catch((err)=>{
res.status(500).json({error: err})
})
})
})
// subscription 저장
exports.storeSubscription2 = functions.region('asia-northeast1').https.onRequest(function(req, res){
cors(req, res, function(){
let body = JSON.parse(req.body)
let subscription = body.subscription
let sort = body.sort
admin.database().ref('subscription2').push({subscription, sort}).then(()=>{
res.status(201).json({message:'Data stored', subscription: subscription})
}).catch((err)=>{
res.status(500).json({error: err})
})
})
})
// subscription 삭제
exports.removeSubscription = functions.region('asia-northeast1').https.onRequest(function(req, res){
cors(req, res, function(){
let subscription = JSON.parse(req.body).subscription
admin.database().ref('subscription').orderByChild('subscription/endpoint').equalTo(subscription.endpoint).once('value').then((snapshot)=>{
if(snapshot.numChildren()>0){
snapshot.forEach(function(child){
child.ref.remove()
})
res.status(201).json({message:'Data removed', subscription: subscription})
}else{
res.status(401).json({message:'No have data', subscription: subscription})
}
})
})
})
// subscription 삭제
exports.removeSubscription2 = functions.region('asia-northeast1').https.onRequest(function(req, res){
cors(req, res, function(){
let subscription = JSON.parse(req.body).subscription
admin.database().ref('subscription2').orderByChild('subscription/endpoint').equalTo(subscription.endpoint).once('value').then((snapshot)=>{
if(snapshot.numChildren()>0){
snapshot.forEach(function(child){
child.ref.remove()
})
res.status(201).json({message:'Data removed', subscription: subscription})
}else{
res.status(401).json({message:'No have data', subscription: subscription})
}
})
})
})
exports.getsubscription = functions.region('asia-northeast1').https.onRequest(function(req, res){
cors(req, res, function(){
admin.database().ref('subscription').once('value').then((snapshot)=>{
let test = [];
snapshot.forEach((e)=>{
test.push(e.val().subscription)
})
res.status(201).json(test)
})
})
})
function getSubscriptions(){
admin.database().ref('subscription').once('value').then((snapshot)=>{
let subscriptions = [];
snapshot.forEach((e)=>{
subscriptions.push(e.val().subscription)
console.log(e.val())
})
return subscriptions
})
}
exports.sendPushMessage = functions.region('asia-northeast1').https.onRequest(function(req, res){
const payload = JSON.parse(req.body).payload;
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey,
privateKey: applicationServerPrivate
},
TTL: 10
}
admin.database().ref('subscription').once('value').then((snapshot)=>{
let promises = [];
snapshot.forEach((e)=>{
promises.push(webpush.sendNotification(e.val().subscription, payload, options))
})
Promise.all(promises)
.then(function(values) {
console.log(values);
res.status(201).json(values)
})
.catch(function(err){
console.log(err)
res.status(401).json(err)
})
})
})
exports.sendPushMessage2 = functions.region('asia-northeast1').https.onRequest(function(req, res){
const payload = JSON.parse(req.body).payload;
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey2,
privateKey: applicationServerPrivate2
},
TTL: 10
}
admin.database().ref('subscription2').once('value').then((snapshot)=>{
let promises = [];
snapshot.forEach((e)=>{
promises.push(webpush.sendNotification(e.val().subscription, payload, options))
})
Promise.all(promises)
.then(function(values) {
console.log(values);
res.status(201).json(values)
})
.catch(function(err){
console.log(err)
res.status(401).json(err)
})
})
})
exports.sendPushMessageAsSort = functions.region('asia-northeast1').https.onRequest(function(req, res){
const body = JSON.parse(req.body)
const payload = body.payload;
const sorts = body.sort;
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey,
privateKey: applicationServerPrivate
},
TTL: 10
}
cors(req, res, function(){
admin.database().ref('subscription').once('value').then((snapshot)=>{
let promises = [];
snapshot.forEach((e)=>{
console.log(sorts);
if(sorts.some(targetSort => e.val().sort.includes(targetSort))){
console.log(e.val().sort);
promises.push(webpush.sendNotification(e.val().subscription, payload, options))
}
})
Promise.all(promises)
.then(function(values) {
console.log(values);
res.status(201).json(values)
})
.catch(function(err){
console.log(err)
res.status(401).json(err)
})
})
})
})
exports.sendPushMessageAsSort2 = functions.region('asia-northeast1').https.onRequest(function(req, res){
const body = JSON.parse(req.body)
const payload = body.payload;
const sorts = body.sort;
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey2,
privateKey: applicationServerPrivate2
},
TTL: 10
}
cors(req, res, function(){
admin.database().ref('subscription2').once('value').then((snapshot)=>{
let promises = [];
snapshot.forEach((e)=>{
console.log(sorts);
if(sorts.some(targetSort => e.val().sort.includes(targetSort))){
console.log(e.val().sort);
promises.push(webpush.sendNotification(e.val().subscription, payload, options))
}
})
Promise.all(promises)
.then(function(values) {
console.log(values);
res.status(201).json(values)
})
.catch(function(err){
console.log(err)
res.status(401).json(err)
})
})
})
})
<file_sep># PWA란
- 아래의 내용을 필요한대로 골라서 점진적으로 웹을 앱처럼 만든다.
- 보안(https),
- 앱설치,
- GPS,
- Push,
- 카메라기능,
- 빠른 속도(오프라인환경에서 작동, 캐쉬등...) 등등...
# install
- https://stackoverflow.com/questions/50332119/is-it-possible-to-make-an-in-app-button-that-triggers-the-pwa-add-to-home-scree/50356149#50356149
Chrome(or any PWA supporting browser) triggers the beforeinstallprompt event for Web app install banner, which you can catch and re-trigger in more appropriate time when you think user wont miss it/convinced about adding your site to home page. Starting Chrome version 68, catching beforeinstallprompt and handling the install prompt programmatically is mandatory and no banners will be shown automatically.
In case the user have missed the prompt/declined to add to home screen, the event can't be manually triggered by our code. This is intentionally left that way to avoid web pages annoying the users to repeatedly prompt the user for adding to home screen. Thinking of users perspective, this makes complete sense.
Yes, there are cases when user miss the option accidentally and he may not know of the browser menu option to "Add to home screen" and it would be nice for us to trigger the same again. But unfortunately, that's not an option. At lest for now and I personally don't see that changing much considering how developers can abuse if its left to the developers to prompt.
Alternate option: If the user have missed the install prompt or even chosen not to install it to home screen, give some time and when you think he is starting to like your site(based on conversions) you can show him a full page or half page Div popup kind of install instructions to add your site to home screen from browsers menu. It can have some images or Gif animation showing user how to add to home screen from the menu. With that, it should be self explanatory to most users, if not all.
Here is some code example for the same, which is iOS specific(look under #PROTIP 3).
As a bonus, you can show some promotions like discounts or added features when user add to home screen, which will convince user to do so. PWA has a way to find if the site is accessed form the home screen or browser.
For Development/testing: If you need this banner to come multiple times for dev/testing purpose, you can set the below flow in your Chrome for the same,
# install
- 다른 path의 multiple 설치 ok
- pc 에서 설치된 앱 지우는 곳 `chrome://apps/`
- `chrome://flags/#bypass-app-banner-engagement-checks`
# App 설치
- BeforeInstallPromptEvent ("install" a web site to a home screen.)
- 사파리 지원 안됨
- `beforeinstallprompt` : 앱 설치 조건이 만족 되면 (https://developers.google.com/web/fundamentals/app-install-banners/?hl=ko#criteria) `beforeinstallprompt` 이벤트 실행
- `BeforeInstallPromptEvent.prompt()` : 앱을 설치 할건지 묻는 함수
## 설치 조건
- The web app is not already installed.
- and prefer_related_applications is not true.
- Meets a user engagement heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore)
- Includes a web app manifest that includes:
- short_name or name
- icons must include a 192px and a 512px sized icons
- start_url
- display must be one of: fullscreen, standalone, or minimal-ui
- Served over HTTPS (required for service workers)
- Has registered a service worker with a fetch event handler
# FCM 관련 잠정 결정
## 전역 service-worker.js 파일을 사용한다.
- 별도의 scope를 가진 serviceworker(`firebase-messaging-sw.js` 포함)을 사용하지 않는다.
- 다른 scope를 가진 service-worker는 자동으로 파일 업데이트를 확인 하지 않는다. (테스트 결과)
- 해당 scope의 페이지에 진입하거나 강제로 servicewoker를 업데이트 해줘야 한다.
- `firebase-messaging-sw.js`의 경우에는 `messaging.getToken();` 메서드 실행시 강제 업데이트가 된다.
- 필요 없어질 경우 해당 serviceworker를 unregester 시키는 방법도 애매하다.
- 위의 경우처럼 업데이트 시점을 위해, 루트 패스 하위 페이지는 적절한 servicewoker파일의 업데이트를 위하여 업데이트를 위한 js파일이 별도로 필요해진다.
## service-worker.js 파일에서 push를 위한 firebase 라이브러리를 사용하지 않는다.
- setBackgroundMessageHandler을 사용하면 포그라운드에서 노티 띄우는게 복잡해 진다.
- 복잡해 진다는 것은 각 js 파일에 포그라운드 이벤트 수신시 노티를 띄우는 로직을 추가 해야 한다.
- firebase 라이브러리가 없어도 디폴트 push API로 잘 동작 한다.
## manifest.json의 위치
### static 서버에 있을 경우
- `start_url` 의 경로가 도메인을 포함한 절대 경로로 지정해야 하므로, 각 망별로 다른 manifest.json을 생성 해야 한다.
- `icon` 이미지 경로가 통일 되나, 어자피, 위의 이유로 manifest.json 을 여러개 만들어야 한다.
### web 서버에 있을 경우
- `start_url` 의 경로가 상재 경로로 지정할 수 있어 manifest.json파일이 하나면 된다.
- `icon` 이미지를 web server에 저장 하거나
- `icon` 이미지를 static server에 저장하려면 망별로 다른 static 서버에 저장해야 하며, manifest.json 파일도 망별로 다른 것을 준비 해야 한다.
- 그런데 이미지를 web server에 저장해도 되나!?
### 결론
- 일단 web 서버에 넣고, `icon`이미지도 web server에 저장 하면 하나의 manifest.json과 icon 파일로 해결 가능 하다.??
# 여러개 인스톨 할때 (install) => 안드로이드 크롬, 맥 크롬 테스트 완료
- `manifest.json` 의 `start_url` 이 다르면 여러개 설치 할 수 있다.
- 특이한 점으로 하위 `scope`에서 인스톨 하면, 상위 `scope`를 별도로 설치 할수 있지만,
- 상위 `scope`를 먼저 인스톨 하고, 하위 `scope`를 설치 하려 하면 설치 표시가 안나온다.
- `start_url`이 `scope` 역할을 하여, `scope`을 벗어 나면, 상단에 스코프 벗어 났다고 표시 된다.
# install
## 링크 클릭 및 서버 redirect시 앱이 열림
- `manifest.json` 의 `start_url` 스코프에 해당하는 링크를 클릭 하거나, 서버에서 redirect 회신이 오면
- 안드로이드 크롬의 무조건 경우 인스톨한 앱이 열리고
- 안드로이드 삼성의 경우 선택권이(앱으로 열지, 브라우저로 열지)주어진다.
- https://developers.google.com/web/fundamentals/integration/webapks#android_intent_filters
## 크롬에서 인스톨 되는 시간
- 안드로이드 크롬에서 인스토 되는 시간이 좀 길다.
- 인스톨이 완료되지 않은 시점에서 브라우저를 백그라운드 실행 `종료` 해버리면 인스톨이 되지 않는다.
## 푸시
# manifest.json => start_url
- 사파리에서 작동함
# pwa 예시
## 인스톨 & 오프라인
- app.starbucks.com
## 푸시
- https://housing.com/in/buy/real-estate-mumbai
# 단점
- 정적 파일이 변경될 때, service worker에서 캐쉬이름을 변경해줘야 된다.
- 모바일 디버깅이 힘들다
- 개발 환경 ( 테스트를 https:// 에서 진행해야 한다. )
<file_sep>class PushMessage {
constructor() {
this.firebase;
this.messaging;
this.init();
}
init() {
let isFirebase = this._setFirebase();
if (!isFirebase) return false;
this._setFirebaseMessaging();
this._registeServiceWorker();
this._bindingEvent();
console.log(this.test);
}
_bindingEvent() {
// 토큰 재생성
// this.messaging.onTokenRefresh(this._onTokenRefresh);
}
// firebaseß
_setFirebase() {
if (!window.firebase) {
console.error('firebase application이 로딩 되지 않았습니다.');
return false;
}
this.firebase = window.firebase;
return true;
}
// 파이어 페이스 메시지 인스턴스 생성
_setFirebaseMessaging() {
this.messaging = this.firebase.messaging();
}
// service worker 등록
async _registeServiceWorker() {
try {
let registration = await navigator.serviceWorker.register('/service-worker.js');
this.messaging.useServiceWorker(registration);
// this.messaging.usePublicVapidKey('<KEY>');
// FCM 설정 페이지
// this.messaging.usePublicVapidKey('<KEY>');
console.log('[service-worker.js] Serviceworker registrated.', registration);
window.registration = registration;
} catch (err) {
console.error(err);
}
}
// 알림 수락 요청 (시스템)
async _requestSystemPermission() {
try {
let permission = await Notification.requestPermission();
permission === 'granted' && this._subscribPermit() || this._subscribDiny();
} catch (err) {
console.error(err);
}
}
// 알림 수락 콜백
async _subscribPermit() {
console.log('[service-worker.js] Notification Permiited');
try {
let currentToken = await this.messaging.getToken();
if (currentToken) {
this._sendTokenToServer(currentToken);
alert('알림을 설정하셨습니다.');
} else {
console.log('[service-worker.js] It is Notification Permition');
}
} catch (err) {
console.log('[service-worker.js] An error occurred while retrieving token. ', err);
}
}
// _onTokenRefresh = async () => {
// try {
// let refreshedToken = await this.messaging.getToken();
// console.log('Token refreshed.');
// this._sendTokenToServer(refreshedToken);
// } catch (err) {
// console.log('Unable to retrieve refreshed token ', err);
// }
// }
// 알림 거부 콜맥
_subscribDiny() {
alert('알림을 거부 하셨습니다.');
}
// 서버 전송
_sendTokenToServer(currentToken) {
console.log('sendTokenToServer', currentToken);
}
// 알림 수락 요청 레이아웃 출력
requestSubscribe({ text = '알림을 받으시겠습니까?' } = {}) {
// 노티 거부 / 노티 수락 이면 알림 수락 요청 레이아웃을 출력하지도 않는다.
if (Notification.permission === 'denied' || Notification.permission === 'granted') return false;
let isSubscribe = confirm(text);
if (!isSubscribe) {
return false;
} else {
this._requestSystemPermission();
}
}
// temp
async getSubscription () {
var sub = await registration.pushManager.getSubscription();
// return sub;
console.log(sub.toJSON())
}
}
(() => {
window.PushMessage = PushMessage;
window.pushMessage = new PushMessage();
})();
<file_sep>
# 리캡챠란
아래 그림과 같이 비정상 유저를 거르기 위한 장치로 구글에서 제공하는 서비스? 이다.
https://developers.google.com/recaptcha/docs/versions
# 리캡챠 종류
간단하게 v3 와, v2-checkbox, v2-invisible 형식이 있다. android 형식이 있다고 하나 연관이 없는것 같아 패스
v2-invisible에 대한 내용 (v2 Invisible reCAPTCHA 조사 및 테스트, https://developers.google.com/recaptcha/docs/invisible )
v3에 대한 내용 (Google reCAPTCHA v3 조사 및 테스트, https://developers.google.com/recaptcha/docs/v3)
# 리캡챠 적용 플로우 https://developers.google.com/recaptcha/intro#overview
3개의 리캡챠중 하나를 선택하여 FE에 적용하고,
서버에서 Verifying을 한다.
# 전체적인 문제점
기존의 캐릭터 사전생성에 reCAPTCHA v2 - checkbox 형식을 사용하고 있었는데, 이것을 invisible 타입으로 변경 요청이 왔다. (v2 Invisible, v3 적용 작업 일정)
변경시 제일 큰 문제점이 grecaptcha.execute(); 의 실행완료 시점을 알수 없다는 것이다.
# grecaptcha.execute() 란
유저가 정상적인 유저인지 비정상적인 유저인지 판단하는 메서드 이다.
checkbox 형식에서는 유저가 직접 체크박스를 클릭함으로서 유저가 정상적인 유저인지 비정상적인 유저인지 판단하기 시작하지만,
invisible 형식에서는 FE 개발자가 원하는 시점에 grecaptcha.execute() 을 실행함으로서 유저가 정상적인 유저인지 비정상적인 유저인지 판단 시킨다.
정상유저로 판단된 경우 (excute() 가 성공적으로 완료 된 경우) grecaptch.getResponse() 메서드로 키를 발급 받을수 있다. (이 키는 서버로 전달하여 Verifying을 진행하게 한다.)
1) v3 에서는 grecaptcha.execute() 가 유사 프로미스 형태를 반화하여 then과 catch 메서드를 사용할수 있다. (테스트 해봄)
2) v2 에서는 grecaptcha.execute() 가 then 과 catch 메서드를 포함한 객체를 반환하나 해당 메서드가 정상 동작 하지 않는다. (테스트 해봄)
# 만들고 싶은 로직
캐릭생성 완료 버튼 클릭 -> execute() 실행 -> execute() 완료 -> recaptcha key 발급 완료 -> 캐릭생성 API 호출하여 생성 캐릭에 대한 정보 및 recaptcha key 서버에 전송
이라는 로직을 태우고 싶으나, execute()를 완료시점을 잡아 낼수 없다. ( v3는 가능하다. grecaptcha.execute().then() 이 정상 동작 하기때문에 )
그럼 execute() 완료시점은 어떻게 잡아 낼수 있을까?
v2 invisible 에서는 처음 reCAPTCHA를 랜더링할때 callback 이라는 파라미터를 통해 execute()가 완료된 후 실행할 함수를 전달 하는 방법을 제공하고 있지만...
이걸로는 원활한 개발이 힘들다.
참고로 v2 checkbox 에서는
유저가 checkbox 클릭 -> ecaptcha key 발급 완료 -> ( 연속되지 않은 로직! 유저는 다른 일을 할수 있다. ) -> 캐릭생성 완료 버튼 클릭 -> 캐릭생성 API 호출하여 생성 캐릭에 대한 정보 및 recaptcha key 서버에 전송
와 같이 reCAPTCHA 와 캐릭생성 로직이 서로 독립되어 있을수 있어서 문제가 되지 않았다.
# 원활한 개발이 힘들다?
v2 invisible 에서는 처음 reCAPTCHA를 랜더링할때 callback 이라는 파라미터를 통해 execute() 의 콜백 함수를 전달한다고 했는데, 이경우 로직은...
캐릭생성 API 호출 시점이 캐릭생성 완료 버튼 클릭 이벤트가 아니라, execute() 완료 시점이 된다는 것이다.
즉, reCAPTCHA를 랜더링할때 callback에 캐릭생성 API 호출을 넣어야 한다는 이야기 인데 문제는 없어보이나 깔끔해 보이지는 않는다.
왜냐하면 캐릭터 생성페이지가 항상 recaptcha를 사용하는 것이 아니기 때문이다.
## 1) 결국 : recaptcha를 사용하지 않을때
캐릭생성 완료 버튼 클릭 이벤트 콜백으로 -> 캐릭생성 API 호출을 넣어야 한다.
## 2) 결국 : recaptcha를 사용할때
캐릭생성 완료 버튼 클릭 이벤트 콜백으로 -> excute() 실행후 -> excute() 콜백 으로 -> 캐릭생성 API 호출을 넣어야 한다.
## 3) 하지만 하고 싶은건 : recaptcha를 사용하지 않을때
캐릭생성 완료 버튼 클릭 이벤트 콜백으로 -> 캐릭생성 API만 호출하고 싶다.
## 4) 하지만 하고 싶은건 : recaptcha를 사용할때
캐릭생성 완료 버튼 클릭 이벤트 콜백으로 -> excute() 실행후 -> 캐릭생성 API 호출하고 싶다.
# 어떻게든 promise 형태로 풀고 싶은데
안된다.
```js
/***
* 문제점: 한번 키를 받고 나서, 시간이 지난후 reset()되면 await promise 가 동작하지 않고(이미 처음에 fullfiled 되었으니) getResponse를 바로 실행해버린다
* 렌더를 중복해서 할수 없다
*/
var promise; // key 값을 resolve 하는 promise
var firstCaptchaKey; // 처음받은 키값. 이 값의 의미는 grecaptcha가 성공적으로 첫 excute 가 되었다는 것을 의미. 2분뒤면 키 만료
var captchaKey;
var test = function(){
promise = new Promise((res, rej)=>[
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: res, // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
'error-callback': rej,
})
])
};
test(); // 참고 : 한번만 실행 됨.
async function execute(){
grecaptcha.execute();
firstKey = await promise;
captchaKey = grecaptcha.getResponse();
return captchaKey;
}
async function go(){
await execute();
console.log(captchaKey)
}
/**
* 문제점: 처음 실행시 promise 변수가 undefined 된다.
* 2분이 지나 reset 된 후에도 promise 변수가 undefined 된다.
*/
var promise ;
var key;
async function go(){
grecaptcha.execute();
var a = await promise; // 처음 실행시 promise 변수가 undefined 된다.
console.log(a)
}
function setPromise(key){
promise = new Promise(res=>{
res(key)
})
}
var test = function(){
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: setPromise, // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
// 'error-callback': rej,
})
};
test();
go()
/***
* 문제점: 유저가 그림찾기 하고 있으면 타임아웃 걸림
* 그럼 타임아웃을 무한대로 걸면 될거 같은데
* 뭔가 애러를 처리 할수 없다는 느낌이 들어 깔끔 하지 않음
* 그냥 이걸로 할까?
*/
async function go(){
var key = await execute();
console.log(key)
}
function getError(e){
console.error(e)
}
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: '', // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
'error-callback': getError,
})
async function execute(){
// execute 실행
grecaptcha.execute();
return new Promise((res, rej)=> {
let startTime = Date.now(); // 시작한 시간
let interval = setInterval(()=>{
let key = grecaptcha.getResponse(); // excute가 완료 되지 않으면 key 를 받아 오지 않는다.
let curTime = Date.now(); // 지난 시간
if(curTime - startTime > 12000){
clearInterval(interval);
rej(new Error('타임아웃!'))
}
if(key){
clearInterval(interval);
res(key);
}
},100);
})
}
go();
/**
* 위에거 기준으로 v2 / v3 호환 메서드 만들어 봄
*/
// show captcha
var d = $('<div>');
d.addClass('g-recaptcha');
// d.attr('data-sitekey', '<KEY>'); //v2
d.attr('data-sitekey', '<KEY>'); //v3
d.attr('data-size', 'invisible');
$('#' + 'test').append(d);
// load google recaptcha js
var googleJS = document.createElement('script');
googleJS.type = 'text/javascript';
googleJS.src = 'https://www.google.com/recaptcha/api.js';
document.body.appendChild(googleJS);
async function execute(){
return new Promise((res, rej)=> {
window.grecaptcha.execute().then(key=>{
// Version 3
if(key !== null){
console.log('v3!!');
res(key);
// Version 2
}else{
let startTime = Date.now(); // 시작한 시간
let interval = setInterval(()=>{
let key = window.grecaptcha.getResponse(); // excute가 완료 되지 않으면 key 를 받아 오지 않는다.
let curTime = Date.now(); // 지난 시간
if(curTime - startTime > 12000){
clearInterval(interval);
rej(new Error('구글 리캡챠 v2 타임아웃!'));
}
if(key){
console.log('v2!!');
res(key);
clearInterval(interval);
}
},100);
}
}).catch(err=>rej(err));
});
}
try{
var key = await execute();
console.log(key)
}catch(err){
console.log(err)
}
```
<file_sep>/***
* 문제점: 한번 키를 받고 나서, 시간이 지난후 reset()되면 await promise 가 동작하지 않고(이미 처음에 fullfiled 되었으니) getResponse를 바로 실행해버린다
*/
var promise; // key 값을 resolve 하는 promise
var firstCaptchaKey; // 처음받은 키값. 이 값의 의미는 grecaptcha가 성공적으로 첫 excute 가 되었다는 것을 의미. 2분뒤면 키 만료
var captchaKey;
var test = function(){
promise = new Promise((res, rej)=>[
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: res, // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
'error-callback': rej,
})
])
};
test(); // 참고 : 한번만 실행 됨.
async function execute(){
grecaptcha.execute();
firstKey = await promise;
captchaKey = grecaptcha.getResponse();
return captchaKey;
}
async function go(){
await execute();
console.log(captchaKey)
}
/**
* 문제점: 처음 실행시 promise 변수가 undefined 된다.
*/
var promise ;
var key;
async function go(){
grecaptcha.execute();
var a = await promise; // 처음 실행시 promise 변수가 undefined 된다.
console.log(a)
}
function setPromise(key){
promise = new Promise(res=>{
res(key)
})
}
var test = function(){
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: setPromise, // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
// 'error-callback': rej,
})
};
test();
go()
/***
* 문제점: 유저가 그림찾기 하고 있으면 타임아웃 걸림
*/
async function go(){
var key = await execute();
console.log(key)
}
grecaptcha.render('test', {
sitekey: '<KEY>',
callback: '', // 처음 excute 될때 받은 key 값, promsie 가 처음 fulfilled 되면 끝.
size:'invisible',
'expired-callback': () => {
grecaptcha.reset();
},
// 'error-callback': rej,
})
async function execute(){
grecaptcha.execute();
return new Promise((res, rej)=> {
let startTime = Date.now();
let interval = setInterval(()=>{
let key = grecaptcha.getResponse();
let curTime = Date.now();
if(curTime - startTime > 2000){
clearInterval(interval);
console.log('타임 아웃!')
rej(new Error('타임아웃!'))
}
if(key){
clearInterval(interval);
res(key);
}
},100);
})
}
go()
/**
*
*/
// show captcha
var d = $('<div>');
d.addClass('g-recaptcha');
// d.attr('data-sitekey', '<KEY>'); //v2
d.attr('data-sitekey', '<KEY>mn1xGLLi3U06'); //v3
d.attr('data-size', 'invisible');
$('#' + 'test').append(d);
// load google recaptcha js
var googleJS = document.createElement('script');
googleJS.type = 'text/javascript';
googleJS.src = 'https://www.google.com/recaptcha/api.js';
document.body.appendChild(googleJS);
async function execute(){
return new Promise((res, rej)=> {
window.grecaptcha.execute().then(key=>{
// Version 3
if(key !== null){
console.log('v3!!');
res(key);
// Version 2
}else{
let startTime = Date.now(); // 시작한 시간
let interval = setInterval(()=>{
let key = window.grecaptcha.getResponse(); // excute가 완료 되지 않으면 key 를 받아 오지 않는다.
let curTime = Date.now(); // 지난 시간
if(curTime - startTime > 12000){
clearInterval(interval);
rej(new Error('구글 리캡챠 v2 타임아웃!'));
}
if(key){
console.log('v2!!');
res(key);
clearInterval(interval);
}
},100);
}
}).catch(err=>rej(err));
});
}
try{
var key = await execute();
console.log(key)
}catch(err){
console.log(err)
}
<file_sep>window.messaging = window.app2.messaging();
window.registration ;
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
// Registration was successful
console.log(registration.test);
console.log('ServiceWorker registration successful with scope: ', registration.scope);
// window.app2.messaging().useServiceWorker(registration);
// messaging.usePublicVapidKey('<KEY>')
messaging.usePublicVapidKey('<KEY>')
// var options = {
// userVisibleOnly: true,
// // applicationServerKey: '<KEY>'
// applicationServerKey: '<KEY>'
// };
// registration.pushManager.subscribe(options).then(
// function(pushSubscription) {
// console.log(pushSubscription.endpoint);
// // The push subscription details needed by the application
// // server are now available, and can be sent to it using,
// // for example, an XMLHttpRequest.
// }, function(error) {
// // During development it often helps to log errors to the
// // console. In a production environment it might make sense to
// // also report information about errors back to the
// // application server.
// console.error(error.name);
// }
// ).catch(e=>console.log(e))
// registration.pushManager.getSubscription().then(info=>window.subscriptionInfo = info);
window.registration = registration;
}, function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
function requestPush() {
if(Notification.permission === 'denied') return false;
Notification.requestPermission().then(permission => {
if(permission === 'granted'){
window.messaging.getToken().then(currentToken=>{
console.log(currentToken)
})
}
})
}
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.', refreshedToken);
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
// setTokenSentToServer(false);
// // Send Instance ID token to app server.
// sendTokenToServer(refreshedToken);
// ...
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
// urlB64ToUint8Array('BHudr6Q2-mMVjpfXiu3fvQ6OSjl_iOmSQd4kTqN7hc8R8RjpQUsjPHhGvFvZd6n7oFri<KEY>')<file_sep>const webpush = require('web-push');
// webpush.setGCMAPIKey('103953800507');
webpush.setVapidDetails(
'mailto:<EMAIL>',
'BOCHoU_Ym8vKG5mjwIVzNTThP_rpcjrI7C2liL3sYhGpAt-leD9V3-ggUaItj5guFW5m5JEwremfCnt_pt2JIrE',
'vS5NkdSrlnucWS_hT2I8qqW2MYNvqdlLyCLjeUBvapk'
// 새로 만든 VAPID
// '<KEY>',
// '<KEY>'
);
// 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)
// const pushSubscription = {
// endpoint: 'https://fcm.googleapis.com/fcm/send/cSj8gZscuzs:APA91bFDRExq1-Ngllo9BrHC2AqYHSoOHQbqyx2Cy9qNWOay1QCb-q1MN3wB1JXyt8VOT1GmlAQxRxFK_KUj3r99Y-KE<KEY>gl<KEY>X',
// keys: {
// auth: '<KEY>',
// p256dh: '<KEY>ijnCer6olRanTi5oUR6jywPl7nI'
// }
// };
// 사용 안했을 경우 - 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)와 동일
const pushSubscription = {
endpoint: "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdbb-Vdk6P01qGS3z7ZKClJU5LtLsXorLra8R_cyyGEOvrWuhABFdriqcSIcjlgaS5QcLrRLfRClUM6bLjekiUKjn7vOa__-mSG2BE50ymQRbXtJq4Dv0XLEHKkbf7H1MwXOR036mbeB7zHodl0k5_sYlO-oMrlCGUvy7uvZ7UsLTt_AY",
keys: {
auth: "<KEY>",
p256dh: "<KEY>"
}
};
try{
webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
}catch(err){
console.error(err)
}
/*
{endpoint: "https://fcm.googleapis.com/fcm/send/cSj8gZscuzs:AP…EqbUSzLJottFL-E6FvBGum-gC4o4EglJk-TOzbqV5reNlvlwX", expirationTime: null, keys: {…}}
endpoint: "https://fcm.googleapis.com/fcm/send/cSj8gZscuzs:APA91bFDRExq1-Ngllo9BrHC2AqYHSoOHQbqyx2Cy9qNWOay1QCb-q1MN3wB1JXyt8VOT1GmlAQxRxFK_KUj3r99Y-KEqbUSzLJ<KEY>"
expirationTime: null
keys:
auth: "<KEY>"
p256dh: "<KEY>"
__proto__: Object
__proto__: Object
endpoint: "https://fcm.googleapis.com/fcm/send/cSj8gZscuzs:<KEY>"
expirationTime: null
keys:
auth: "<KEY>"
p256dh: "<KEY>"
*/
<file_sep>const webpush = require('web-push');
const applicationServerPublicKey = '<KEY>';
const applicationServerPrivate = '<KEY>'
const applicationServerPublicKey2 = '<KEY>';
const applicationServerPrivate2 = '<KEY>'
const subscription = {"endpoint":"https://fcm.googleapis.com/fcm/send/drBWkmPoUlY:<KEY>","expirationTime":null,"keys":{"<KEY> <KEY>","auth":"<KEY>"}}
async function sendPushMessageAsSort(){
const payload = JSON.stringify({a:"test"})
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey,
privateKey: applicationServerPrivate
},
TTL: 10
}
try{
var result = await webpush.sendNotification(subscription, payload, options)
console.log(result);
}catch(err){
console.log(err)
}
}
sendPushMessageAsSort();<file_sep>
# PUSH
## 1) 개요
- `웹 앱`에 `네이티브 앱` 처럼 푸쉬 메시지를 보낸다.
### (1) 모바일 환경에서 push 기능
#### `모바일`인 경우 `네이티브 앱`과 동일하게 브라우저가 종료된 상태에서도 푸쉬 메시지가 온다. (https://developers.google.com/web/fundamentals/push-notifications/faq)
[# Why doesn't push work when the browser is closed?](https://developers.google.com/web/fundamentals/push-notifications/faq)
> 브라우저가 닫힌 상태에서는 왜 푸쉬가 동작하지 않나요?
>이 문제는 복잡합니다.
>안드로이드를 생각해 보면, 안드로이드 os는 push message가 들어오면, 해당 어플리케이션을 깨우도록 설계되어 있습니다. 해당 어플리케이션이 닫혀있든 그렇지 않든 말이죠.
> 안드로이드의 브라우저 역시 정확히 같은 동작을 합니다. 푸쉬 메시지가 오면 (특정)브라우저는 깨어 날 것이고, (특정)브라우저는 해당 service worker를 깨우고 service worker에 push event를 dispatch 할 것입니다.
> 데스트탑 OS의 경우에는 좀더 미묘합니다. 맥 OS X의 경우가 설명하기 쉬울 것 같은데, 맥 OS X의 경우에는 시각적인 설명이 가능하기 때문입니다.
> 맥 OS X의 경우 dock의 프로그램 아이콘아래에 표시되는 marking에 의하여 프로그램이 구동중인지 아닌지를 알 수 있습니다.
> 두개의 크롬 아이콘이 dock에 있다고 칩시다. 하나는 아이콘 아래에 marking 표시가 있고, 이것은 running 중이라는 것을 보여 줍니다. 다른 하나는 marking 표시가 없고 이것은 running중이 아님을 보여 줍니다.
> 예시
> 푸쉬 메시지가 데탑에 전송된 상화에서, 브라우저가 running중이라면 우리는 푸쉬 메시지를 받을 수 있을 것 입니다. 즉, 아이콘 아래에 marking 표시가 있는 경우 입니다.
> 이것은 윈도우가 열려 있지 않는 브라우저가 가능 하다는 이야기 이며, 우리는 우리의 서비스 워커가 푸쉬 메시지를 받을 것 이라는 이야기 입니다. 왜냐하면 브라우저가 백그라운드 상에서 구동 중이기 때문입ㄴ디ㅏ.
> 브라우저가 완전히 닫혀 있는경우 우리는 푸쉬를 받을 수 없습니다. 즉. marking 표시가 없을 때입니다. 위도우도 마찬가지 입니다.
### (2) pc 환경에서 push 기능
#### `pc`환경인 경우 브라우저 및 install된 웹앱이 백그라운에서 동작하고 있어야 한다.
- 자세한 내용은 위 `mobile` 환경 참조
## 2) PWA중 push를 사용하기 위해 필요한 기술
### (1) Service-worker (PUSH API, FCM API)
- `service worker`를 등록하면 `serviceWorkerRegistration`객체를 얻을 수 있고,
- `serviceWorkerRegistration`은 `Push API`의 인터페이스인 `pushManager`, `PushSubscription`, `PushEvent`, `PushMessageData`를 프로퍼티로 가지고 있고,
- `push service`를 위해서는 후술할 `FCM`을 사용하든, 네이티브 `Push API`를 직접 사용하든 `Push API`는 꼭 필요하며, 따라서 `service woker`가 필수 조건이 된다.
- 하나의 `service worker` 는 하나의 `subscription(구독정보)` 만 가질 수 있다.
- 이론적으로는 다른 `depth`에 다른 `service worker` 가 설치 되어 있다면, 하나의 도메인이 여러개의 `subscription(구독정보)`을 가질 수 도 있다.
### (2) SSL / Localhost
- `Service worker` 사용이 필수 이므로 `SSL`환경 역시 필수 이다.
### (3) Push API
- `subscription(구독정보)`를 만들거나 지우고 => (메시지를 `어디에` 보낼건지)
- `메시지 수신 이벤트`를 바인딩 한다 => (메시지를 `받는다`)
### (4) Notificatoin API
- 수신된 메시지를 `보여준다.`
- `Notificatoin API`를 위한 `Interface` 는 아래 두군데에서 가지고 있으며 비슷하게 동작 하고, 어디서 사용하든 상관 없다.
- `ServiceWorkerGlobalScope`
- `window`
## 3) Push API (Native Push Service) & Friebase Cloude Message
- `Push API` 를 사용하는 방법(`구독정보 생성`, `메시지 수신`)에는 크게 두가지가 있다.
- 1) 직접 Push API를 사용거나
- 2) FCM(Friebase Cloude Message) SDK 를 사용한다.
### (1) Push API (Native Push Service)
- `Push API`를 직접 사용한다.
- `2016년 7월` `VAPID`가 도입되면서 크롬은 `Push API`을 지원 하였고,
- 크롬은 푸쉬를 보내기 위한 서비스를 기존 `GCM`에서 `FCM (Push API 사용)`으로 변경 하였다.
- 크롬이 지원하니까 표준으로 봐도 좋을듯 하다.
- 상세 사용 방법은 링크 참조 : https://developers.google.com/web/fundamentals/codelabs/push-notifications/
### (2) Friebase Cloude Message
- `Push API`를 `FCM (Push API 사용)`을 통해 사용한다.
- 상세 사용 방법은 링크 참조 : https://firebase.google.com/docs/cloud-messaging/js/client
- 최소한 web 환경에서의 FCM 사용은 일종의 라이브러리 라고 생각하면 된다.
- 자세한 용어에 대한 내용은 아래 참조 (https://developers.google.com/web/fundamentals/push-notifications/faq)
[# What is the deal with GCM, FCM, Web Push and Chrome?](https://developers.google.com/web/fundamentals/push-notifications/faq)
> 이 질문에 대한 대답은 다양하지만, 가장 쉬운 접근방법은 `web push`와 `Chrome`에 대한 역사를 살펴 보는 방법 입니다. (걱정 마세요. 짧습니다.)
> 목요일, 2014년
> 크롬이 처음 web push를 시행할때, 크롬은 서버에서 브라우저로 메세지를 보내기 위해 `Google Cloud Messaging` (GCM)을 사용 하였습니다.
> 이것은 `web push가 아닙니다!` Chrome과 GCM의 초창기 설정이 실제 web push가 아닌 것에는 몇 가지 이유가 있습니다.
> GMC을 사용하기 위애서는 개발자가 `Google Developers Console`계정을 만들어야 했습니다.
> 크롬과 GCM은 메시지를 정확하게 설정할 수 있도록 웹 앱에서 공유 되어야할 특별한 sender ID가 필요했ㅅ브니다.
> GCM을 위한 서버는 web standard가 아닌 custom API를 적용하경슷ㅂ니다.
> 6월 2016
> 2016뇬 6월에 `Application Server Keys(or VAPID)`라는 새로운 기능이 web push에 나타났습니다. 크롬이 이 새로운 API를 지원하게 되었을때, 크롬은 GCM대신 `FCM`(크롬이 사용하는 `web push service`)을 메시지 서비스로서 사용하게 되었습니다. 아래는 그 FCM을 사용하게 된 중요한 이유 입니다.
> 크롬과 `Application Server Keys`는 `Google 또는 Firebase`에서 설정해야할 그 어떤 프로젝트도 필요 없게 되었습니다.
> `FCM`(크롬이 사용하는 `web push service`)은 모든 `web push service`들이 지원하는 `API`인 `web push protocol`을 지원하게 되었습니다. 이것의 의미는 브라우저가 어떤 `push service`를 이용하든, 똑같은 종류의 request를 만들면 메시지를 보낼수 있다는 의미 입니다.
> 왜 혼란스럽다 오늘?
> 오늘날 `web push`를 주제로 쓰여진 문서들, 그중에서도 `GCM`과 `FCM`을 참조하는 문서들은 많은 혼란을 야기 합니다. 일단, `GCM`관련 문서에 대해서는 꽤 오래된 문서라고 생각해도 좋고 그 문서는 크롬에 초점이 맞춰진 문서라고 생각하십시요! (글쓴이는 이러한 많은 오래된 포스트에 대해 죄책감을 가지고 있습니다.)
> 반면 웹 푸시는 브라우저의 입부분 이라고 생각 해봅시다. 브라우저는 푸시 서비스를 이용하여 메시지를 송, 수신 하며, 푸시 서비스는 `웹 푸시 프로토콜`로 만들어진 request요청을 사용합니다. 이러한 관점에서 보면 우리는 어떤 브라우저가 어떤 푸시서비스를 사용하고 있고 어떻게 작동하는지 무시 할 수 있습니다.
> 이 가이드는 표준적인 접근법에 관점을 두고 있으며, 그 이외에는 일부로 언급하지 않습니다.
> 파이어 베이스는 왜 Javscript SDK를 가지고 있나요? 그리고 그게 뭔가요?
> 여러분들 중에는 자바스크립트의 `messaging API`인 `Firebase web SDK`에 대해 알고 있으며 관심이 있을 것입니다. 여러분은 아마도 이게 `web push`와 어떻게 다른거야! 라고 궁금해 할 것입니다.
> 이 메시징 SDK(`Firebase Cloud Messating JS SDK`라고 알려진)는 웹 푸시를보다 쉽게 구현할 수 있도록 몇 가지 트릭을 제공합니다.
> `FCM JS SDK`를 사용하면 `PushSubscription`객체가 가지고 있는 많은 `메서드`와 `프로퍼티`에 대한 이해 없이 우리는 `FCM Token(a string)`만 가지고 있으면 됩니다.
> 유저들 각각의 `token` 을 이용하면 푸시 메시지를 전송할 수 있는 적절한 `FCM API`를 사용 할 수 있습니다. 이 API는 암호화된 `payloads` 가 필요하지 않습니다. 단지 plain text로 만들어지 payload를 post 방식으로 body넣어 날리기만 하면 됩니다.
> FCM의 API는 여러 커스텀 기능을 지원하고 있는데, 예를 들면 `FCM Topics`가 바로 그것 입니다. (`FCM Topics`는 웹에서도 작동 하지만, 문서화가 잘 되어 있지는 않습니다.)
> 끝으로 `FCM`은 `Androiod`, `iOS`, 그리고 `web`을 모두 지원합다. 그렇기 때문에 각각 다른 플랫폼을 담당하는 서로 다른 팀들이 쉽게 협력할수 있습니다. `FCM` 코드 뒤에서 `web push`를 사용하지만, `FCM`의 목적은 `web push`를 사용하는 방법을 추상화 하는 것 입니다.
> 내가 아까 전에 질문에 대답 한것 처럼, 만약 `web push`를 딱 `browser`와 `push service`때문에 고려하고 있다면 간단한 웹푸시 구현 작업을 위해 하나의 `library`로서 `Messaging SDK in Firebase`를 사용하는 걸 고려 할수 있을 것입니다.
### (3) Friebase Cloude Message 적용
- `Push API`를 쉽게, 넓게 쓰게 하는 것이 `FCM`이라고 생각하면 좋은데,
- 문서등이 보기 어렵게 되어 있는듯 하고, Native위주인 경향도 있어서 개념잡기가 어려울 수 있다.
#### a. 문서에 대해
- 기본적으로 영어 문서이나, 한글로 변경 할수 있지만, 한글로 변경하면 왼쪽에 카테고리 목차가 사라진다!
- 프론트엔드 FCM `가이드` : https://firebase.google.com/docs/cloud-messaging/js/client
- 프론트엔트 FCM `API` : https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging
---
- 서버 FCM `가이드` : https://firebase.google.com/docs/cloud-messaging/server
- 서버 FCM `프로토콜 API` : https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages
- 서버 FCM `ADMIN_SDK API` : https://firebase.google.com/docs/reference/admin
#### b. FCM App Server(앱 서버) Protocol
##### - XMPP Server Protocol
- Jabber, Google Talk, Facebook chat, MS .NET Messenger 에 사용되는 프로토콜
##### - HTTP V1 API
- 기존 HTTP API 보다 액세스 토큰을 통한 보안 향상, 확장성 강화, 메시지 맞춤설정 등 장점이 많다.
- HTTP API는 발송하는 서버키 값이 고정인데 반해 HTTP V1은 발송하는 서버키 값을 엑세스 토큰으로 받아서 사용하는 부분이 다르다.
- 하지만 멀티캐스트 메시징을 지원하지 않아 아직까지는 기존 HTTP API를 많이 사용한다.
- API 방식도 기존의 방식과는 다르다.
##### - 기존 HTTP API
- FCM을 통해 메시지를 보내는 기본적인 방법
- 구글에서는 V1으로 마이그레이션을 추천한다.
##### - Firebase SDK
- SDK를 사용하여 메시지를 보내는 방식
<file_sep># PWA란
- 아래의 내용을 필요한대로 골라서 점진적으로 웹을 앱처럼 만든다.
- 보안(https),
- 앱설치,
- GPS,
- Push,
- 카메라기능,
- 빠른 속도(오프라인환경에서 작동, 캐쉬등...) 등등...
# caching strategy 캐싱 전략
## 1. Cache only (캐시만 사용)
- 모든 리소스에 대해 케시만 사용하여 불러옴
```js
self.addEventListener('fetch', event=>{
event.repondWith(
caches.match(event.request); // return A Promise that resolves to the matching Response.
)
})
```
## 2. Cache, falling back to network (캐시, 실패하는 경우 네트워크)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
caches.match(event.request).then(reponse => {
return response || fetch(event.request)
})
)
})
// async/await
self.addEventListener('fetch', event =>{
event.respondWith(
async function(){
let result = await caches.match(event.request);
if(result) return result ;
return fetch(event.request)
}
)
})
```
## 3. Network only (네트워크만 사용)
```js
self.addEventListener('fetch', function(event){
event.respondWith(
fetch(event.request)
)
})
```
## 4. Network, falling back to cache (네트워크, 실패하는 경우 캐시)
```js
// Promise callback
self.addEventListener('fetch', event =>{
event.respondWith(
fetch(event.request).catch(()=>{
return caches.match(event.request);
})
)
})
// async/await
self.addEventListener('fetch', event =>{
event.respondWith(
async function(){
try{
return await fetch(event.request)
}catch(err){
return caches.match(event.request)
}
}
)
})
```
## 5. Cache, then network (캐시 이후 네트워크)
## 6. Generic fallback (기본 대체 리소스)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
fetch(event.request).catch(()=>{
return caches.match(event.request).then(response=>{
return response || caches.match('/generic.png')
)}
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){
try{
let response = await fetch(event.request);
return response
}catch (err) {
let response = await caches.match(event.request);
return response || caches.match('/generic.png');
}
}
)
})
```
## 7. Cache on demand (요청에 따라 캐시 -> 캐시, 실패하는 경우 네트워크, 이후 캐시 저장)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
caches.open('cache-name').then(cache => {
return cache.match(event.request).then(cachedResponse => {
return cachedResponse || fetch(event.request).then(networkResponse => {
cache.put(event.request, networkresponse.clone());
return networkResponse;
})
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){ // async function 은 Promise (async 함수에 의해 반환 된 값으로 해결되거나, async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값)을 리턴한다.
let cache = await caches.open('cache-name');
let cachedResponse = await cache.match(event.request);
if(cachedResponse) return cachedResponse;
let networkResponse = await fetch(event.request);
cache.put(event.request, networkResponse.clone());
return networkResponse;
}
)
})
```
## 8. Cache, falling back to network with frequent updates (캐시, 이후 네트워크 사용해 캐시 업데이트 -> 캐시, 성공하든 실패하든 네이트워크 이용하여 캐시 저장)
```js
self.addEventListener('fetch', event => {
event.respondWith(
caches.open('cache-name').then(cache => {
return cache.match(evnet.request).then(cachedResponse => {
var fetchPromise = fetch(evnet.request).then(networkResponse =>{
cache.put(event.request, networkResponse.clone())
return networkResponse;
});
return cacheResponse || fetchPromise;
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){ // async function 은 Promise (async 함수에 의해 반환 된 값으로 해결되거나, async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값)을 리턴한다.
let cache = await caches.open('cache-name');
let cachedResponse = await cache.match(event.request); // undefined 반환 가능
let networkResponse = await fetch(event.request);
cache.put(event.request, networkResponse.clone());
return cachedResponse || networkResponse;
}
)
})
```
## 9. Network, falling back to cache with frequent updates (네트워크, 실패하는 경우 캐시 사용 및 비번한 캐시 업데이트)
```js
self.addEventListener('fetch',event => {
event.respondWith(
caches.open('cache-name').then(cache => {
return fetch(event.request).then(networkResponse => {
cache.put(event.request, networkResponse.clone())
return networkResponse;
}).catch((=>{
return caches.match(event.request)
}))
})
)
})
self.addEventListener('fetch', event => {
event.respondWith(
async function(){
let cache = await caches.open('cache-name');
try{
let networkResponse = fetch(event.request);
cache.put(event.request, networkResponse.clone())
return networkResponse;
}catch{
let cachedResponse = await caches.match(event.request);
return cachedResponse;
}
}
)
})
```
## 10. 앱 셸
# install
- https://stackoverflow.com/questions/50332119/is-it-possible-to-make-an-in-app-button-that-triggers-the-pwa-add-to-home-scree/50356149#50356149
Chrome(or any PWA supporting browser) triggers the beforeinstallprompt event for Web app install banner, which you can catch and re-trigger in more appropriate time when you think user wont miss it/convinced about adding your site to home page. Starting Chrome version 68, catching beforeinstallprompt and handling the install prompt programmatically is mandatory and no banners will be shown automatically.
In case the user have missed the prompt/declined to add to home screen, the event can't be manually triggered by our code. This is intentionally left that way to avoid web pages annoying the users to repeatedly prompt the user for adding to home screen. Thinking of users perspective, this makes complete sense.
Yes, there are cases when user miss the option accidentally and he may not know of the browser menu option to "Add to home screen" and it would be nice for us to trigger the same again. But unfortunately, that's not an option. At lest for now and I personally don't see that changing much considering how developers can abuse if its left to the developers to prompt.
Alternate option: If the user have missed the install prompt or even chosen not to install it to home screen, give some time and when you think he is starting to like your site(based on conversions) you can show him a full page or half page Div popup kind of install instructions to add your site to home screen from browsers menu. It can have some images or Gif animation showing user how to add to home screen from the menu. With that, it should be self explanatory to most users, if not all.
Here is some code example for the same, which is iOS specific(look under #PROTIP 3).
As a bonus, you can show some promotions like discounts or added features when user add to home screen, which will convince user to do so. PWA has a way to find if the site is accessed form the home screen or browser.
For Development/testing: If you need this banner to come multiple times for dev/testing purpose, you can set the below flow in your Chrome for the same,
# install
- 다른 path의 multiple 설치 ok
- pc 에서 설치된 앱 지우는 곳 `chrome://apps/`
- `chrome://flags/#bypass-app-banner-engagement-checks`
# Service worker scope
> Scope is linked with domain/origin. You can not create a service worker that intercepts request for other origins. If you try to register a service worker from origin which is different from origin of service worker file sw.js, then error will be thrown like The origin of the provided scriptURL ('https://cdn.example.com/sw.js') does not match the current origin. [https://itnext.io/service-workers-your-first-step-towards-progressive-web-apps-pwa-e4e11d1a2e85]
# 서비스 워커
- 서비스 워커는 자신이 제어하는 페이지에서 발생하는 이벤트를 수신합니다.웹에서 파일을 요청하는 것과 같은 이벤트를 가로채거나 수정하고 다시 페이지로 돌려보낼 수 있습니다.
# App 설치
- BeforeInstallPromptEvent ("install" a web site to a home screen.)
- 사파리 지원 안됨
- `beforeinstallprompt` : 앱 설치 조건이 만족 되면 (https://developers.google.com/web/fundamentals/app-install-banners/?hl=ko#criteria) `beforeinstallprompt` 이벤트 실행
- `BeforeInstallPromptEvent.prompt()` : 앱을 설치 할건지 묻는 함수
## 설치 조건
- The web app is not already installed.
- and prefer_related_applications is not true.
- Meets a user engagement heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore)
- Includes a web app manifest that includes:
- short_name or name
- icons must include a 192px and a 512px sized icons
- start_url
- display must be one of: fullscreen, standalone, or minimal-ui
- Served over HTTPS (required for service workers)
- Has registered a service worker with a fetch event handler
# registration.showNotification
## tag
- 알림을 나타내는 고유 식별자 입니다. 만약 현재 표시되 ㄴ태그와 동일한 태그를 가진 알림이 도착하면, 예전 알림은 조용히 새 알림으로 대체됩니다.
- 알림을 여러개 생성해 사용자를 귀찮게 하는 것보다 이 방법이 더 좋은 경우가 많스니다. 예를 들어, 메시징 앱에 안 읽은 메시지가 하나 있는 경우, 알림에 그 메시지 내용을 포함하고 싶을 것입니다. 그런데 기존 알림이 사라지기 전에 다섯개의 신규 메시지가 도착해다면, 여섯개의 별도 알림을 보여주는 것보다 6개의 새로운 메시지가 있습니다. 와 같이 기존 알림 내용을 업데이트 하는 것이 더 좋습니다.
- [만들면서 배우는 프로그래시브 웹 p.284]
## renotify (boolean)
- 같은 태그로 보내면 조용히 대체 되나, 태그 값을 주면서 renotify를 주면, 교체 될때 알림이 왔다고 표시한다.
- renotify가 true인데 tag가 빈값이면, TypeError가 전달된다.(https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification)
# FCM 관련 잠정 결정
## 전역 service-worker.js 파일을 사용한다.
- 별도의 scope를 가진 serviceworker(`firebase-messaging-sw.js` 포함)을 사용하지 않는다.
- 다른 scope를 가진 service-worker는 자동으로 파일 업데이트를 확인 하지 않는다. (테스트 결과)
- 해당 scope의 페이지에 진입하거나 강제로 servicewoker를 업데이트 해줘야 한다.
- `firebase-messaging-sw.js`의 경우에는 `messaging.getToken();` 메서드 실행시 강제 업데이트가 된다.
- 필요 없어질 경우 해당 serviceworker를 unregester 시키는 방법도 애매하다.
- 위의 경우처럼 업데이트 시점을 위해, 루트 패스 하위 페이지는 적절한 servicewoker파일의 업데이트를 위하여 업데이트를 위한 js파일이 별도로 필요해진다.
## service-worker.js 파일에서 push를 위한 firebase 라이브러리를 사용하지 않는다.
- setBackgroundMessageHandler을 사용하면 포그라운드에서 노티 띄우는게 복잡해 진다.
- 복잡해 진다는 것은 각 js 파일에 포그라운드 이벤트 수신시 노티를 띄우는 로직을 추가 해야 한다.
- firebase 라이브러리가 없어도 디폴트 push API로 잘 동작 한다.
## manifest.json의 위치
### static 서버에 있을 경우
- `start_url` 의 경로가 도메인을 포함한 절대 경로로 지정해야 하므로, 각 망별로 다른 manifest.json을 생성 해야 한다.
- `icon` 이미지 경로가 통일 되나, 어자피, 위의 이유로 manifest.json 을 여러개 만들어야 한다.
### web 서버에 있을 경우
- `start_url` 의 경로가 상재 경로로 지정할 수 있어 manifest.json파일이 하나면 된다.
- `icon` 이미지를 web server에 저장 하거나
- `icon` 이미지를 static server에 저장하려면 망별로 다른 static 서버에 저장해야 하며, manifest.json 파일도 망별로 다른 것을 준비 해야 한다.
- 그런데 이미지를 web server에 저장해도 되나!?
### 결론
- 일단 web 서버에 넣고, `icon`이미지도 web server에 저장 하면 하나의 manifest.json과 icon 파일로 해결 가능 하다.??
# token이 삭제될 경우 *중요*
## token이 삭제될 경우에는 크게 모바일 인터넷 사용 기록 삭제를 눌렀을 경우가 있다. (디폴트로 선택 되어 있는 것만 삭제)
### 1) 크롬
- 노티 설정은 그대로, 토큰은 날라가는 것으로 보임
- 즉 push 안옴, push 받을 건지 알림창 생성도 안됨
- `쿠키 및 사이트 데이터` 삭제가 디폴트 + `사이트 설정`은 별도로 선택 가능 하게 되어 있음
### 2) 삼성 인터넷
- 노티 설정 디폴트로 변경, 토큰도 날라가는 것으로 보임,
- 즉 push 안옴, push 받을 건지 알림창 생성은 됨.
- `쿠키 및 사이트 데이터` 삭제가 디폴트 + `사이트 설정`은 별도로 선택 불가. 아마 임의로 디폴트에 포함 되어 있는것 같음
### 3) 파이어 폭스
- 노티 설정 디폴트로 변경, 토큰은 날라가는 것으로 보임,
- 즉 push 안옴, push 받을 건지 알림창 생성은 됨.
- `쿠키`, `오프라인 웹 데이터` + `웹 사이트별 설정` 삭제가 디폴트
### 위 세가지 경우 모두
- `사이트 데이터` 또는 `오프라인 웹 데이터` 가 삭제 됨으로서 service worker에 저장된 token 도 삭제 된는 것으로 보임
## 삭제됬을 경우에 발생할수 있는 문제
- 일단 우리 로직의 기본은 `노티 설정` 허용 여부에 따라 `push 받을 건지 알림창 생성` -> `토큰 생성` -> `토큰 전송` 로직이다.
- 하지만 위의 경우와 같이 `노티 설정`은 허용 되어 있는데, `토큰` 이 `삭제`되거나, 혹은 `갱신` 되는 경우가 있을 수 있다.
- 그럼 해당 servie woker는 `노티 설정`이 허용되어 있어 `토큰`을 생성하지 못하고, `push`를 받을 수 없게 된다.
## 해결방안
- 따라서, 초기 토큰 생성시, 서버에 전송후 해당 토큰을 `sha-256`으로 인코딩 하여 쿠키로 하나 구워 버리고,
- `pushMessage.js` 파일이 로딩 될때, 일단 service worker가 가진 token을 `messaging.getToken()` 으로 가져와 쿠키와 비교후,
- 쿠키가 없거나, 값이 다르면 서버에 `push/register` API를 호출 하는 방식을 가져야 한다.
## 왜 위와 같은 해결 방안을 적용 해야 하는가?
- FCM 에서는 현재 service worker가 token을 가지고 있는지 없는지 확인이 안된다.
- `messaging.getToken()` 이라는 하나의 메서드만 존재 하는데, 이 메서드는 Token이 없으면, Token을 만들고, Token이 있으면 Token을 가져 오기 때문이다.
- 따라서 `messaging.getToken()`으로 가져온 토큰이 이번에 새로생성된 토큰인지 아닌지 알 수가 없다.
- 그렇다고 `messaging.getToken()`으로 가져오 토큰을 매번 서버에 전송하는 것은 리소스가 너무 크므로 말이 안된다.
# 알림 안드로이드 크롬의 경우
- 디폴트가 소리로만 알림이다. 변경하기 위해서는 설정에서 중요도를 긴급으로 변경해야 합니다.
- 인스톨 뒤에 중요도를 긴급으로 변경했음에도 불구하고 다시 디폴트가 소리로만 알림으로 변경된다. 마찬가지로 변경하기 위해서는 설정에서 중요도를 긴급으로 변경해야 합니다.
# tip
- `Navigator.serviceWorker.register('sw.js')` 가 없어도, 한번등록된 serviceworker는 내용이 변경되면 업데이트 하려고 한다.
# Notification icon & badge image size (알림 아이콘 및 뱃지 이미지 사이즈에 대해)
## icon
- `192px`
- Sadly there aren't any solid guidelines for what size image to use for an icon. Android seems to want a 64dp image (which is 64px multiples by the device pixel ratio). `If we assume the highest pixel ratio for a device will be 3, an icon size of 192px or more is a safe be` (https://developers.google.com/web/fundamentals/push-notifications/display-a-notification)
## badge
- `72px`
- As with the icon option, there are no real guidelines on what size to use. Digging through Android guidelines the recommended size is 24px multiplied by the device pixel ratio. `Meaning an image of 72px or more should be good (assuming a max device pixel ratio of 3).`
# Splash Image
- IOS 의 경어 2019년 04월부터 polyfil 형식으로 splash 적용
- https://stackoverflow.com/questions/55840186/ios-pwa-splash-screen
# fcm 과 push api
## usePublicVapidKey
### 1. 개요
- `firebase-messaging.js` 을 사용할 경우에 fcm 사용법 만으로 firefox등에 메시지를 보낼 수 있다.
- fcm 은 `messaging.usePublicVapidKey` 메서드라는 것을 제공 하는데 문서에는 아래와 같이 나와 있다. (https://firebase.google.com/docs/cloud-messaging/js/client?hl=ko#configure_web_credentials_in_your_app)
```
FCM에서 다른 푸시 서비스로 메시지 요청을 보낼 때 usePublicVapidKey 메소드를 통해 VAPID 키 사용자 인증 정보를 사용할 수 있습니다. FCM에서 웹 사용자 인증 정보 구성의 안내에 따라 생성하거나 가져온 키를 사용하여 메시지 객체를 검색한 후 코드에 추가할 수 있습니다.
// Add the public key generated from the console here.
messaging.usePublicVapidKey("<KEY>");
```
### 2. 내용
- fcm을 사용하여 firefox에 메시지를 보낼때, fcm에서는 messaging의 Token값을 필요로 한다.
- 정확히 fcm이 fireforx에 메시지를 어떻게 보내는지 모르겠으나, 내부에서 mozila push service에 push를 보내든지 할 것 같다.
- `usePublicVapidKey` 을 사용하면 fcm을 통하지 않고 직접 mozila push service에 메시지를 보내라고 전달 할수 있다.
- `messaging.getToken()`을 사용하면 fcm 토큰 값이 생성됩과 동시에 subscription 정보도 같이 생성된다.
- `usePublicVapidKey`이 없어도 subscription은 생성되며, fcm 프로토콜을 사용하여 메시지를 보내게 될때, vapid의 pusblic 및 private 값은 필요 없다. 아마도 내부적으로 키/벨류 값을 가지고 있는 것 같다.
- 단
# 여러개 인스톨 할때 (install) => 안드로이드 크롬, 맥 크롬 테스트 완료
- `manifest.json` 의 `start_url` 이 다르면 여러개 설치 할 수 있다.
- 특이한 점으로 하위 `scope`에서 인스톨 하면, 상위 `scope`를 별도로 설치 할수 있지만,
- 상위 `scope`를 먼저 인스톨 하고, 하위 `scope`를 설치 하려 하면 설치 표시가 안나온다.
- `start_url`이 `scope` 역할을 하여, `scope`을 벗어 나면, 상단에 스코프 벗어 났다고 표시 된다.
# install
## 링크 클릭 및 서버 redirect시 앱이 열림
- `manifest.json` 의 `start_url` 스코프에 해당하는 링크를 클릭 하거나, 서버에서 redirect 회신이 오면
- 안드로이드 크롬의 무조건 경우 인스톨한 앱이 열리고
- 안드로이드 삼성의 경우 선택권이(앱으로 열지, 브라우저로 열지)주어진다.
- https://developers.google.com/web/fundamentals/integration/webapks#android_intent_filters
## 크롬에서 인스톨 되는 시간
- 안드로이드 크롬에서 인스토 되는 시간이 좀 길다.
- 인스톨이 완료되지 않은 시점에서 브라우저를 백그라운드 실행 `종료` 해버리면 인스톨이 되지 않는다.
## 푸시
# manifest.json => start_url
- 사파리에서 작동함
# firebase message TIP & TEST
## usePublicVapidKey 변화에 따른 - getPublicVapidKey_()
- usePublicVapidKey 사용 안한것과, 사용 한것의 PublickKey는 다르다. (당연한 이야기)
```js
// 사용 안했을 경우
messaging.getPublicVapidKey_().then(e=>console.log(e))
// Uint8Array(65) [4, 51, 148, 247, 223, 161, 235, 177, 220, 3, 162, 94, 21, 113, 219, 72, 211, 46, 237, 237, 178, 52, 219, 183, 71, 58, 12, 143, 196, 204, 225, 111, 60, 140, 132, 223, 171, 182, 102, 62, 242, 12, 212, 139, 254, 227, 249, 118, 47, 20, 28, 99, 8, 106, 111, 45, 177, 26, 149, 176, 206, 55, 192, 156, 110]
// 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)
messaging.getPublicVapidKey_().then(e=>console.log(e))
//Uint8Array(65) [4, 224, 135, 161, 79, 216, 155, 203, 202, 27, 153, 163, 192, 133, 115, 53, 52, 225, 63, 250, 233, 114, 58, 200, 236, 45, 165, 136, 189, 236, 98, 17, 169, 2, 223, 165, 120, 63, 85, 223, 232, 32, 81, 162, 45, 143, 152, 46, 21, 110, 102, 228, 145, 48, 173, 233, 159, 10, 123, 127, 166, 221, 137, 34, 177]
// 사용 했을 경우 (별도로 생성된 VAPID)
// "publicKey": "<KEY>",
// "privateKey": "<KEY>"
messaging.getPublicVapidKey_().then(e=>console.log(e))
// Uint8Array(65) [4, 230, 251, 97, 19, 195, 83, 11, 255, 139, 113, 219, 121, 199, 39, 236, 251, 251, 33, 15, 209, 183, 187, 117, 241, 30, 176, 67, 82, 47, 33, 93, 98, 31, 79, 130, 143, 201, 64, 35, 102, 187, 38, 91, 58, 196, 236, 197, 109, 213, 229, 184, 190, 103, 174, 100, 190, 65, 92, 10, 72, 175, 232, 245, 62]
```
- usePublicVapidKey 사용 안한것과, 사용 한것의 messaging Token값이 항상 다르다.
- 매번 새로 생성하기때문에
## usePublicVapidKey 변화에 따른 - FCM 프로토콜 & webpush 프로토콜 전송
- usePublicVapidKey 바꿀때 subscription은 변경되지 않기때문에
- `usePublicVapidKey 바꿀때 마다, service-worker 재등록 필요`
- 해당 내용은 (https://github.com/web-push-libs/web-push-php/issues/58), (https://github.com/w3c/push-api/issues/291) 에서 살펴 볼수 있다.
- 참조 (https://w3c.github.io/push-api/)
If the Service Worker is already subscribed, run the following substeps:
Retrieve the push subscription associated with the Service Worker.
If there is an error, reject promise with a DOMException whose name is "AbortError" and terminate these steps.
Let subscription be the retrieved subscription.
Compare the options argument with the options attribute of subscription. If any attribute on options contains a different value to that stored for subscription, then reject promise with an InvalidStateError and terminate these steps. The contents of BufferSource values are compared for equality rather than references.
When the request has been completed, resolve promise with subscription.
- appid가 변경된다고 token이 재생성 되지는 않늗다.
- 단, usePublicVapidKey가 변경 되면 getToken은 변경된다.
- firefox 브라우저의 경우 subscription의 endpoint는 항상 `mozila` 이다.
## PUSH API를 사용할때, (FCM x) ApplicationServerKey(VAPID) 가변경 될 경우에도, Subscription은 자동으로 변경되지 않는다.
- 해당 내용은 (https://github.com/web-push-libs/web-push-php/issues/58), (https://github.com/w3c/push-api/issues/291) 에서 살펴 볼수 있다.
- 참조 (https://w3c.github.io/push-api/)
- Subscription을 변경 하려면, 기존의 Subscription의 ApplicationServerKey와 변경될 ApplicationServerKey를 비교해야 하는데, 비교하는 법에 대해 자세히 나온게 없다.
- 임의로 찾아낸 방법은 아래와 같다.
```js
// main.js
// 1. 기존 subscripltion ApplicationServerKey
var test;
registration.pushManager.getSubscription().then(e=>test = e.options.applicationServerKey) // ArrayBuffer(65);
var test2 = new Uint8Array(test); // Uint8Array(65)
var test3 = test2.join(','); // string
// 2. 변경할 ApplicationServerKey
var test4 = urlB64ToUint8Array('<KEY>').join(',') //string
// 3. 비교
test3 === test4
```
### 1. 프론트 스크립트에서 usePublicVapidKey 사용 안했을 경우
- `webpush 프로토콜 전송` : 전송 안됨 (VAPID가 다를 것으로 생각됨)
- `fcm 프로토콜 전송` : 전송 됨
### 2. 프론트 스크립트에서 usePublicVapidKey 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)
- `webpush 프로토콜 전송` : 전송 됨
- `fcm 프로토콜 전송` : 전송 됨
### 3. 프론트 스크립트에서 usePublicVapidKey 사용 했을 경우 (별도로 생성된 VAPID)
- `webpush 프로토콜 전송` : 전송 됨
- `fcm 프로토콜 전송` : 전송 안됨 (Token 값이 생성 안됨)
# 로직 관련
```text
비 로그인 && 토큰이 없을 경우
알림을 받으 시겠습니까? -> 네 -> 시스템: 알림을 받으시겠습니까? -> 네 -> 토큰생성 -> 서버전송
로그인
토큰이 있는가? -> 네 -> GUID와 토큰을 전송
토큰 변경 체크 (app id 변경등)
-> 토큰 쿠키가 있는데, 다르다면
페이지 진입시 마다, token 쿠키가 있는지 확인 없으면
noti permission이 'granted' 인경우
token 생성 -> 서버 전송 -> 쿠키 등록
noti permission이 'granted' 가 아니라면
pass
있으면,
쿠키 token과 service worker 쿠키가 동일한지 확인 동일하면
패스,
동일하지 않으면,
token 서버전송 -> 쿠키 등록
```
# onTokenRefresh
- 언제 FCM토큰이 재생성 되는가!
- 구현되지 않았다!!!
- https://github.com/firebase/quickstart-js/issues/217
- https://stackoverflow.com/questions/42136312/how-i-can-test-firebase-notification-ontokenrefresh-method-call-in-javascript
# Push & Notification 작동 원리
[https://w3c.github.io/push-api/#widl-PushSubscription-unsubscribe-Promise-boolean]

[프로레시브 웹 앱의 모든것 p.271]
## Permission for Push Notifications
## Subscriptions
- push 등록은 각 `device` 와 `browser`별로 등록된다. 즉 같은 device의 다른 browser라면 다른 사용자로 인식한다.
- 기존에 등록된 `subscript`이 없다면 새로운 `subscrition`을 생성해야 하며, 이 `subscription`은 `backend server`로 전달 되어야 한다.
## Push server (Push Service)
- Push notification은 별도의 external server(browsr vendor에서 제공하는 push server)를 필요로 한다.
- push마다 어떤 message를 app(아마도 web page)에 전달하기 위해서는 browser의 도움이 필요로 한다.
- 우리의 APP(web page) 자체로는 message를 수신 할수 없기 때문이다.
- (web socket을 만들수도 있지만, 우리 app이 항상 오픈 되어 있어야 작동하기 때문에 적합하지 않다.)
- Browser vendor(공급자)는 자사의 browser로 어떤 app을 이요하는 사용자에게 push를 발송하기 위한 `Push server(Push Service)` 를 제공한다.
- Google, Mozilla 등 각각의 browser vendor가 push server(Push Service)를 가지고 있고, 해당 browese사용자에게 push를 발송하기 위해서는 vendor의 push server(Push Service)에 연계된 setting이 필요하다.
## End point
- push server(Push Service)는 각 browser vendor의 소유 이므로 우리가 설정 할 수는 없다.
- 단, 우리가 javascript로 `new subscription`을 setup하면 (`ServiceWorkerRegistration.PushManager.subscribe(options)`) javascript는 자동으로 browsder vendor에서 제공하는 push server(Push Service)에 접근해서 `Endpoint`를 가져온다.
- 새로 등록된 subscript은 push API endpoint 정보 `(push server의 url)` 을 가지게 되고, 각가의 등롣된 `device-browser`마다 자신만의 다른 endpoint를 가지게 된다.
### google의 endpoit 예시
```json
{
"endpoint": "https://fcm.googleapis.com/fcm/send/d2Qi49CN31o:APA91bE41fL9u_kXfOmGEb6sdafOvdKPcvoHswJpMaX29PKeYzrZC2eT_wJ0lPL2YfDuK888wTUd8kSPFFEsDqxWJZgzu_XluhuG8-ACgZuauKHHqL1KpbBLjQngYgR477H6Piw-RVUA",
"expirationTime": null,
"keys": {
"p256dh": "<KEY>",
"auth": "<KEY>"
}
}
```
### mozila의 endpoit 예시
```json
{
"endpoint": "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdIbR7rKOoWIlaR-dF3fszV4W2hQusl4HpWsOJlA8Dc5VleB4mpCnhD7Oi1qer--DSPbJTiurEjjTUbgjPQAkQmwjxvyifArIYhTPiqhB7G19A5q_NAVctKmgESy1Vakz8v2MM5ezL10bch0Id0It3sqtd0ug9wKAuypUsU5O9CkkPMnc",
"keys": {
"auth": "CeC6IOLjchl1p4aCneY2Tg",
"p256dh": "<KEY>"
}
}
```
## push message
- endpoint는 push server(Push Service)의 url이며 우리는 이 endpoint url로 new push message를 send하게 된다.
- browser vendor(push server)는 이 push message를 각 web app에 전달 한다.
## Authentication information
- endpoint 유출 시 endpoint를 아는 누구나가 push message를 보낼 수 있다.
- 그래서 특별한 key 가 필요하다.
- 설정한 key에 의해서 subscription생성시(`ServiceWorkerRegistration.PushManager.subscribe(options)`) authentication정보도 만들어 지는다. 이 인증 정보는 우리만이 우리의 web app 에 push 할수 있도록 분별해 준다.
## subsription과 backend server
- browser vendor의 push server와는 별개로 우리 app의 code가 구동 될 수 있는 backend server도 필요하다.
- 사용자 app의 servidce worker는 new subscription을 생성하고
- subscription은 endpoint등에 대한 정보를 가지고 있으면,
- backend 서버는 각각의 subscription을 가 보관한다.
# Push & Notification에 대한 이해
- 각 브라우저는 각 push service를 가지고 있고, 백엔드 서버는 push service에 푸시를 보낼 메시지를 보낸다.
- push service는 적절한 디바이스-브라우저에게 푸시를 보내고
- 서비스 워커는 해당 푸시를 받고, 브라우저를 깨운다.
> There are several pieces that come together to make push notifications work. Browsers that support web push each implement their own push service, which is a system for processing messages and routing them to the correct clients. Push messages destined to become notifications are sent from a server directly to the push service, and contain the information necessary for the push service to send it to the right client and wake up the correct service worker. The section on the Push API describes this process in detail.
When it receives a message, the service worker wakes up just long enough to display the notification and then goes back to sleep. Because notifications are paired with a service worker, the service worker can listen for notification interactions in the background without using resources. When the user interacts with the notification, by clicking or closing it, the service worker wakes up for a brief time to handle the interaction before going back to sleep. [https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#working_with_data_payloads]
# unsubscription
- 구독은 서비스 워커 하나에 유일하다.
- 구독 된 상태에서 구독 하면 같은 subscription을 반환 한다.
- 구독 해지 하고 재 구독 하면 다른 subscription을 반환 한다.
- **구독 된 상태에서 오프라인 상태에서 구독 해지 후 온라인에서 구독 하면 새로운 구독이 된다** => **데이터베이스에는 예전 구독이 남아 있다**
# TTL 푸시 서비스에서 메시지를 보관하는 기간
- 0 으로 지정해 주자 (크롬 디폴트는 4주)
## chrome
- https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
Managing Notifications at the Server
So far, we've been assuming the user is around to see our notifications. But consider the following scenario:
The user's mobile device is offline
Your site sends user's mobile device a message for something time sensitive, such as breaking news or a calendar reminder
The user turns the mobile device on a day later. It now receives the push message.
That scenario is a poor experience for the user. The notification is neither timely or relevant. Our site shouldn't display the notification because it's out of date.
You can use the time_to_live (TTL) parameter, supported in both HTTP and XMPP requests, to specify the maximum lifespan of a message. The value of this parameter must be a duration from 0 to 2,419,200 seconds, corresponding to the maximum period of time for which FCM stores and tries to deliver the message. Requests that don't contain this field default to the maximum period of 4 weeks. If the message is not sent within the TTL, it is not delivered.
Another advantage of specifying the lifespan of a message is that FCM never throttles messages with a time_to_live value of 0 seconds. In other words, FCM guarantees best effort for messages that must be delivered "now or never". Keep in mind that a time_to_live value of 0 means messages that can't be delivered immediately are discarded. However, because such messages are never stored, this provides the best latency for sending notifications.
## mozila
- https://blog.mozilla.org/services/2016/02/20/webpushs-new-requirement-ttl-header/
# web-push library (백엔드에서 푸쉬 보낼때 사용 할 라이브러리)
- https://developers.google.com/web/fundamentals/push-notifications/sending-messages-with-web-push-libraries
# webpush.sendNotification(pushSubscription, payload, options)
## payload
- argument 중 payload 값은 text 또는 node buffer 값으로 들어가야 한다.
>The payload is optional, but if set, will be the data sent with a push message. This must be either a string or a node Buffer. [https://www.npmjs.com/package/web-push]
# Notification 에 대한 정리
https://developers.google.com/web/fundamentals/push-notifications/display-a-notification
## 화면 구성

## badge 아이콘
- badge의 경우 모바일 크롬만 되는듯 하다. (삼성 브라우저는 안됬음)
# push가 동작하는 조건
## pc인 경우
- background에서 브라우저 앱이 돌고 있을때(맥 기준으로 브라우저를 닫더라도, 실행 아이코에 파란색 점이 찍혀 있을때)
- 테스트 결과 완전히 종료된 이후 push를 보내면, 다시 브라우저 실행 시켰을때 메시지를 받는다.
## mobile의 경우
- 테스트 결과 브라우저 앱을 완전히 종료해도 메시지가 온다. (https://stackoverflow.com/questions/39034950/google-chrome-push-notifications-not-working-if-the-browser-is-closed)
- 딱히 app install 절치를 진행하지 않아도 됨.
# VAPID & GMC(FCM) - Push 보내는 방법의 과거와 현재
- `gcm_sender_id` 는 과거의 방법이다.
- 현재는 `applicationServerKey`즉 `VAPID` 를 사용한다.
- 간단히 말하면, `web push protocal`이 정착되기 전 과거 브라우저는 `GCM(FCM) protocol`을 사용하였고 보안상의 문제로
- `gcm_sender_id`를 `menifest.json` 에,
- 타겟이 크롬인 경우`Server key(GCM API key)` 도 함께 `Authorization headerer`에 넣어야 한다.
- 그러나 요즘 브라우저는 `web push protocal`을 사용며 `VAPID`를 사용하고 있고, 이때는 위 `gcm_sender_id` 및 `Server key(GCM API key)`가 필요 없다.
## 참조 1
> Throughout this book we’ve been using the `application server key('VAPID')` to identify our application with push services. This is the Web Standards approach of application identification.
In older versions of Chrome (version 51 and before), Opera for Android and the Samsung Internet Browser there was a non-standards approach for identifying your application.
In these browsers they required a `gcm_sender_id` parameter to be added to a web app manifest and the value have to be a Sender ID for a Google Developer Project.
This was completely proprietary and only required since the `application server key` / `VAPID` spec had not been defined. (`여기서 'application server key' 라고 하면 ' VAPID' 와 동일한 의미인데, pushManager.subscript({option})의 option값 중 하나의 key가 'applicationServerKey'이며 value값은 'VAPID'가 된다.`)
In this section we are going to look at how we can add support for these browsers. Please note that this isn’t recommended, but if you have a large audience on any of these browsers / browser versions, you should consider this.
[https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/]
## 참조2
> When Chrome first supported the Web Push API, it relied on the Firebase Cloud Messaging (FCM),formerly known as Google Cloud Messaging (GCM), push service. This required using it's proprietary API. This allowed the Chrome to make the Web Push API available to developers at a time when the Web Push Protocol spec was still being written and later provided authentication (meaning the message sender is who they say they are) at a time when the Web Push Protocol lacked it. Good news: neither of these are true anymore.
FCM / GCM and Chrome now support the standard Web Push Protocol, while sender authentication can be achieved by implementing VAPID, meaning your web app no longer needs a 'gcm_sender_id'.
[https://developers.google.com/web/updates/2016/07/web-push-interop-wins#introducing_vapid_for_server_identification]
## 참조3
- VAPID를 사용하면 `FCM-specific steps` 을 진행하지 않아도 된다.
> Using VAPID also lets you avoid the FCM-specific steps for sending a push message. You no longer need a Firebase project, a gcm_sender_id, or an Authorization header(GCM 계정의 서버 아이디).[https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#working_with_data_payloads]
## GCM / FCM 용어
### 아래의 용어 사용하는 이유
> 42버전과 51버전 사이의 크롬은 구글 클라우드 메시징을 사용해 푸시 메시지를 구현하였고, 오페라와 삼성 브라우저도 같은 방법을 사용했다. 즉, 이전 버번의 브라우저에서도 푸시 알림이 작동하기바란다면 VAPID 키 이외에도 GCM API(gcm_sender_id) 키를 생성해야 한다.
### `GCMAPIKEY` = `GCM-API-KEY` = `GCM Server Key`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그리고 그 푸시를 `크롬`에 할경우 필요 했던 API 값. (`header`)
### `gcm_sender_id` = `GCM 발신자 ID`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그 푸시가 `크롬이든 아니든` 간에 꼭 넣어 줘야 하는 값. (`manifest.json`)
## VAPID를 사용하여 subscription을 생성 하면 endpoint 가 바뀐다.
```js
// subscription 객체를 resolve하는 프로미스가 리턴된다.
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey // VAPID
})
```
- 이때 VAPID를 써서 만들어진 endpoint의 `origin`이 `fcm.googleapis.com`일지라도 이건 `FCM protocol`이 아니라 `Web Push Protocol` 이다.
>You'll know if it has worked by examining the endpoint in the resulting subscription object; if the origin is `fcm.googleapis.com`, it's working.
Even though this is an FCM URL, use the `Web Push Protocol` not the `FCM protocol`, this way your server-side code will work for any push service.[https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#the_web_push_protocol]
# Notification Permission
> 사용자가 Permision 에 동의 하지 않으면, 사용자에게 다시 Permision을 요청할 수 없습니다. (이 경우 permision 승인 결과를 반영 하려면 사용자가 browser의 설정에서 notification permission으 수동으로 변경해 주어야 합니다. ) 사용자가 permission을 결정하지 않은채로 tab을 닫으면, 나중에 다시 물을 수 있습니다. - 프로그레시브 웹 앱의 모든것 p.277 -
- 사용자가 x 버튼 3번 누르면 강제로 차단으로 변경
# ServiceWorkerRegistration.pushManager.subscribe & notification.requestpermission
- `ServiceWorkerRegistration.pushManage.subscribe` 메서드는 기본적으로 푸쉬 허용 여부가 없을때 `notification.requestpermission`을 호출한다.
>There is one side effect of calling subscribe(). If your web app doesn't have permissions for showing notifications at the time of calling subscribe(), the browser will request the permissions for you. This is useful if your UI works with this flow, but if you want more control (and I think most developers will), stick to the Notification.requestPermission() API that we used earlier.
[https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user#permissions_and_subscribe]
[https://stackoverflow.com/questions/46551259/what-is-the-correct-way-to-ask-for-a-users-permission-to-enable-web-push-notifi]
# Cache API
- `worker scope` 와 `window scope` 의 api 형태는 같지만 궁극적으로는 다른 거다.
> Do note that worker scope and standard window scope is not the same. There are some APIs missing (e.g. localStorage is not available). So self in the Service Worker is kind of like window in standard JS, but not exactly the same. [https://enux.pl/article/en/2018-05-05/pwa-and-http-caching], [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/caches]
# Notification API
- Cache와 마찬가지로 `worker scope` 와 `window scope` 의 api 형태는 같지만 궁극적으로는 다른 거다.
> In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications. [https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API#Service_worker_additions]
> ...앞에서 notification을 보여주기 위해 사용했던 'new Notification()' 이 아니라 service worker의 method인 showNotification을 사용한다. navigator.serviceWorker.ready를 통해 install되고 activation된 상태의 service worker인 swreg를 얻으면, swreg.showNotification을 사용할 수 있다. (pwa 웹 앱의 모든것 p.282)
# push service
>The term push service refers to a system that allows application servers(`우리 백엔드`) to send push messages to a webapp(`우리 프론트`). A push service serves the push endpoint or endpoints for the push subscriptions it serves.
The user agent connects to the push service used to create push subscriptions(`subscription을 생성함으로서` / `ServiceWorkerRegistration.pushManager.subscript()`). User agents MAY limit the choice of push services available. Reasons for doing so include performance-related concerns such as service availability (including whether services are blocked by firewalls in specific countries, or networks at workplaces and the like), reliability, impact on battery lifetime, and agreements to steer metadata to, or away from, specific push services. [https://www.w3.org/TR/push-api/#dfn-push-services\]
# end-point
> A push subscription has an associated push endpoint. It MUST be the absolute URL exposed by the push service where the application server can send push messages to. A push endpoint MUST uniquely identify the push subscription.
> 밀어 넣기 구독에는 연결된 밀어 넣기 끝 점이 있습니다. 응용 프로그램 서버가 푸시 메시지를 보낼 수있는 푸시 서비스에 의해 노출 된 절대 URL이어야합니다. 밀어 넣기 끝점은 밀어 넣기 구독을 고유하게 식별해야합니다.
[https://www.w3.org/TR/push-api/#dfn-push-endpoint]
# pwa 웹 앱의 모든것 책 중에서...
- p.273 부터 시작하는, 유저가 notification permission 을 허용했을때, `구독 되었습니다.` 라는 Notification은 `Normal javascript code` 또는 `service worker` 둘중 어디서든지 처리해도 상관 없다. 어자피 페이지가 있는 상태에서 유저가 permission 을 허용하고, 그에 대한 Notification 을 볼거니까
- p.317 에서 하는 구독된 push에 대한 Notification 은 `service worker` 에서만 실행 되어야 한다. 당연히..
# 지원현황
## service worker
- 모바일 환경 전부, 피시 크롬 (https://caniuse.com/#search=serviceworker)
## BeforeInstallPromptEvent(앱설치)
- 오직 크롬만 완벽히 지원하며, 삼성 인터넷의 경우 일부 지원 (https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent)
## push api
- 사파리 모바일/피시 안됨, 삼성 브라우저 됨 (https://caniuse.com/#search=push) *테스트 완료*
## notification api
- 사파리 모바일 /삼성브라우저 안됨 (https://caniuse.com/#search=notification) *테스트 완료*
- push api 에 대한 notification은 삼성브라우저에서 됨
-
## cache api
- MDN 에는 사파리 모바일 지원 안된다고 나옴(https://developer.mozilla.org/en-US/docs/Web/API/Cache)
- developers.google.com에서도 사파리는 지원 안된다고 나옴 (https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api)
- 테스트 하면 지원 함.
- isserviceworkerready에서는 지원 한다고 나옴 (https://jakearchibald.github.io/isserviceworkerready/index.html#moar)
- (https://love2dev.com/blog/what-browsers-support-service-workers/) 해당 문서에서는 2018년 3월에 IOS 11.3버전의 safari 13버전에서 `service-worker` `menifest` `cache` 를 지원 한다고 언급되어 있다.
# offline 환경 pwa 예시
- https://maxwellito.github.io/breaklock/
# pwa 예시
## 인스톨 & 오프라인
- app.starbucks.com
## 푸시
- https://housing.com/in/buy/real-estate-mumbai
# 단점
- 정적 파일이 변경될 때, service worker에서 캐쉬이름을 변경해줘야 된다.
- 모바일 디버깅이 힘들다
- 개발 환경 ( 테스트를 https:// 에서 진행해야 한다. )
# 확인해야 할거
- html 페이지와 sw.js 파일의 위치가 달라도 되는가?
# 추가
## 파이어 폭스의 경우
- firebase functions는 무료버전일 경우 다른 회사 서비스 API를 호출 하지 않는다.
- functions를 사용하면 파이어 폭스에 push가 오지 않는다.
- functions안쓰면 push가 정상적으로 작동한다. 확인 완료
- functions-emulator 에서도 firfox push service 이용가능하다.
```js
// node cli 모드에서 직접 실행한다.
const applicationServerPublicKey = '<KEY>';
const applicationServerPrivate = '<KEY>'
const options = {
vapidDetails: {
subject: 'mailto:<EMAIL>',
publicKey: applicationServerPublicKey,
privateKey: applicationServerPrivate
},
TTL: 10
}
var subscription = {"endpoint":"https://updates.push.services.mozilla.com/wpush/v2/<KEY>","keys":{"auth":"<KEY>"}}
webpush.sendNotification(subscription, JSON.stringify({message:'me', url:''}), options) .then(function(values) {
console.log(values);
}) .catch(function(err){
console.log(err)
})
```
## 하나의 serviceworker에는 하나의 subscription만 존재 한다.
1. 다른 path에 같은 serviceworker를 가질경우
- 어느 한쪽 path에서 subscription객체가 변경되면 다른 path의 subscription도 바뀐다.
- 이게 당연한게, subscribe()메서드가 serivceworkerregistration.pushManager 객체에 있는거니까, 등록되어 있는 serviceworker에 종속되는게 당연하다.
- 테스트 결과도 일치한다.
2. 위의 경우 각기 다른 path에서 다른 VAPID를 가질경우
- 마지막으로 subscription객체를 생성할때 사용한 VAPID가 사용되고,
- 서버에서는 이 VAPID에 해당하는 Private 키를가지고 있어야 푸쉬를 보낼 수 있다.
- pushserver(백엔드)에서 잘못된 VAPID를 사용하여 메시지를 보내면 애러가 난다.
npm
3. 다른 path (같은 depth) 에서 다른 serviceworker를 가질경우
- 다른 service worker 를 가질 수 없다.
4. 다른 path (다른 depth) 에서 다른 serviceworker를 가질경우
- 다른 service worker 를 가질 수 있다.
5. 그럼 다른 path (다른 depth) 에서 다른 serviceworker를 가질경우에 다른 subscribe()을 가지며, push를 발송한 경우 두개의 push를 수신 받는가?
- 그렇다
## service worker 등록 로직
- `navigator.serviceWorker.register('sw.js')` 에서 `navigator` 는 브라우저의 종류와 버전 등 웹브라우저 전반에 대한 정보를 제공하는 객체로 즉 `해당 브라우저`에 `service worker`를 등록 시키겠다는 뜻이다.
- 이때, `navigator.serviceWorker.register('sw.js')` 는 기본적으로 서비스 워커 등록의 범위 값은 서비스 워커 스크립트가있는 디렉토리로 설정됩니다. 즉, `navigator.serviceWorker.register('sw.js', {scope: './'})` 의 줄임 말이다.
(https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register#Examples)
- `register('sw.js')` 에서 `service worker` 파일의 상대경로 기준은 해당 `html`페이지가 있는 곳을 기준으로 한다.
- 예를 들면 `/test/index.html` 에서 `navigator.serviceWorker.register('sw.js')` 메서드를 호출하면, `/test/sw.js` 를 `navigator`에 등록시키 겠다는 이야기 이다.
- 절대경로로 들어갈 경우 `register('/sw.js')` `root` 페스가 된다.
- 지금까지 간과하고 있던 게 바로 `scope`의 중요성 인데, 그 이유는 `service worker`는 `브라우저에` 설치 되는 것이고 (`path`나 `domain`에 등록되는 것이 아니다.)
- 하나의 `scope` (`도메인`을 포함한 `path`) 는 하나의 `service worker`에 의해 제어 될 수 있으며,
- 그렇기 때문에 다른 path (같은 depth) 에서 다른 serviceworker를 가질수 없는 것이다.
- 즉, `service worker`는 `service worker`를 등록한 페이지(`path`) 에 자동으로 종속 되는 것이 아니라, (종속 된다고 생각되는 이유는 `service worker` 등록시 `scope` 설정을 안해 주면, 그 `service worker` 파일이 있는 곳이 `scope`로 지정되기 때문이다. )
- `scop`를 설정 할 수 있는 것이다.
- 아래의 예시처럼 하나의 페이지에서 두개의 서비스 워커 등록이 가능하고 (`service worker`는 `navigator`에 등록 되는 것이므로 몇 개든 등록 가능하다)
- 각 등록된 `service worker`의 `scope`를 정의 해줘야 한다.
```js
// /test/index.html
/*
* 상대경로로 지정된 sw6.js는 /test/ 에 있으며
* service worker scope는 default 이므로 /test/ 로 지정된다.
*/
navigator.serviceWorker.register('sw6.js')
/*
* 상대경로로 지정된 sw6.js는 /test/ 에 있으며
* service worker scope는 test/ 이므로 /foo/ 로 지정된다.
*/
navigator.serviceWorker.register('sw6.js', {scope: '/foo/'})
```
## 랜선 뽑은상태에서 구독 생성 (subscribe) 하면 어떻게 되는가
- 구독 되지 않는다.
- 단 크롬 devtool에서 오프라인 상태로 설정하고 subscribe 하면 구독 된다. (완전한 offline 상태가 아니여서 인것 같다.)
## 구독정보가 미리 생성되어 있는 경우 랜선 뽑으면 어떻게 되는가
- 구독 정보 가져 온다.
- swRegistration.pushmanager.getSubscription 에 정보가 있는 것으로, swRegistration이 가지고 있을 것이다.
## subscription 구독시 VAPID 는 필수 이다.
- https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe#Browser_compatibility
- VAPID 없이 생성하려고 하면 애러가 난다 .
## https://developers.google.com/web/fundamentals/push-notifications/faq => 완전중요
## Why doesn't push work when the browser is closed?
> 브라우저가 닫힌 상태에서는 왜 푸쉬가 동작하지 않나요?
This question crops up quite a bit, largely because there are a few scenarios that make it difficult to reason with and understand.
>이 문제는 복잡합니다.
Let's start with Android. The Android OS is designed to listen for push messages and upon receiving one, wake up the appropriate Android app to handle the push message, regardless of whether the app is closed or not.
>안드로이드를 생각해 보면, 안드로이드 os는 push message가 들어오면, 해당 어플리케이션을 깨우도록 설계되어 있습니다. 해당 어플리케이션이 닫혀있든 그렇지 않든 말이죠.
This is exactly the same with any browser on Android, the browser will be woken up when a push message is received and the browser will then wake up your service worker and dispatch the push event.
> 안드로이드의 브라우저 역시 정확히 같은 동작을 합니다. 푸쉬 메시지가 오면 (특정)브라우저는 깨어 날 것이고, (특정)브라우저는 해당 service worker를 깨우고 service worker에 push event를 dispatch 할 것입니다.
On desktop OS's, it's more nuanced and it's easiest to explain on Mac OS X because there is a visual indicator to help explain the different scenarios.
> 데스트탑 OS의 경우에는 좀더 미묘합니다. 맥 OS X의 경우가 설명하기 쉬울 것 같은데, 맥 OS X의 경우에는 시각적인 설명이 가능하기 때문입니다.
On Mac OS X, you can tell if a program is running or not by a marking under the app icon in the dock.
> 맥 OS X의 경우 dock의 프로그램 아이콘아래에 표시되는 marking에 의하여 프로그램이 구동중인지 아닌지를 알 수 있습니다.
If you compare the two Chrome icons in the following dock, the one on the left is running, as illustrated by the marking under the icon, whereas the Chrome on the right is not running, hence the lack of the marking underneath.
> 두개의 크롬 아이콘이 dock에 있다고 칩시다. 하나는 아이콘 아래에 marking 표시가 있고, 이것은 running 중이라는 것을 보여 줍니다. 다른 하나는 marking 표시가 없고 이것은 running중이 아님을 보여 줍니다.
Example of OS X
> 예시
In the context of receiving push messages on desktop, you will receive messages when the browser is running, i.e. has the marking underneath the icon.
> 푸쉬 메시지가 데탑에 전송된 상화에서, 브라우저가 running중이라면 우리는 푸쉬 메시지를 받을 수 있을 것 입니다. 즉, 아이콘 아래에 marking 표시가 있는 경우 입니다.
This means the browser can have no windows open, and you'll still receive the push message in your service worker, because the browser in running in the background.
> 이것은 윈도우가 열려 있지 않는 브라우저가 가능 하다는 이야기 이며, 우리는 우리의 서비스 워커가 푸쉬 메시지를 받을 것 이라는 이야기 입니다. 왜냐하면 브라우저가 백그라운드 상에서 구동 중이기 때문입ㄴ디ㅏ.
The only time a push won't be received is when the browser is completely closed, i.e. not running at all (no marking). The same applies for Windows, although it's a little trickier to determine whether or not Chrome is running in the background.
> 브라우저가 완전히 닫혀 있는경우 우리는 푸쉬를 받을 수 없습니다. 즉. marking 표시가 없을 때입니다. 위도우도 마찬가지 입니다.
## What is the deal with GCM, FCM, Web Push and Chrome?
This question has a number of facets to it and the easiest way to explain is to step through the history of web push and Chrome. (Don't worry, it's short.)
> 이 질문에 대한 대답은 다양하지만, 가장 쉬운 접근방법은 `web push`와 `Chrome`에 대한 역사를 살펴 보는 방법 입니다. (걱정 마세요. 짧습니다.)
December 2014
When Chrome first implemented web push, Chrome used Google Cloud Messaging (GCM) to power the sending of push messages from the server to the browser.
> 목요일, 2014년
> 크롬이 처음 web push를 시행할때, 크롬은 서버에서 브라우저로 메세지를 보내기 위해 `Google Cloud Messaging` (GCM)을 사용 하였습니다.
This was not web push. There are a few reasons this early set-up of Chrome and GCM wasn't "real" web push.
> 이것은 `web push가 아닙니다!` Chrome과 GCM의 초창기 설정이 실제 web push가 아닌 것에는 몇 가지 이유가 있습니다.
GCM requires developers to set up an account on the Google Developers Console.
Chrome and GCM needed a special sender ID to be shared by a web app to be able to set up messaging correctly.
GCM's servers accepted a custom API request that wasn't a web standard.
> GMC을 사용하기 위애서는 개발자가 `Google Developers Console`계정을 만들어야 했습니다.
> 크롬과 GCM은 메시지를 정확하게 설정할 수 있도록 웹 앱에서 공유 되어야할 특별한 sender ID가 필요했ㅅ브니다.
> GCM을 위한 서버는 web standard가 아닌 custom API를 적용하경슷ㅂ니다.
July 2016
In July a new feature in web push landed - Application Server Keys (or VAPID, as the spec is known). When Chrome added support for this new API, it used Firebase Cloud Messaging (also known as FCM) instead of GCM as a messaging service. This is important for a few reasons:
> 6월 2016
> 2016뇬 6월에 `Application Server Keys(or VAPID)`라는 새로운 기능이 web push에 나타났습니다. 크롬이 이 새로운 API를 지원하게 되었을때, 크롬은 GCM대신 `FCM`(크롬이 사용하는 `web push service`)을 메시지 서비스로서 사용하게 되었습니다. 아래는 그 FCM을 사용하게 된 중요한 이유 입니다.
Chrome and Application Sever Keys do not need any kind of project to be set up with Google or Firebase. It'll just work.
FCM supports the web push protocol, which is the API that all web push services will support. This means that regardless of what push service a browser uses, you just make the same kind of request and it'll send the message.
> 크롬과 `Application Server Keys`는 `Google 또는 Firebase`에서 설정해야할 그 어떤 프로젝트도 필요 없게 되었습니다.
> `FCM`(크롬이 사용하는 `web push service`)은 모든 `web push service`들이 지원하는 `API`인 `web push protocol`을 지원하게 되었습니다. 이것의 의미는 브라우저가 어떤 `push service`를 이용하든, 똑같은 종류의 request를 만들면 메시지를 보낼수 있다는 의미 입니다.
Why is it confusing today?
> 왜 혼란스럽다 오늘?
There is a large amount of confusion now that content has been written on the topic of web push, much of which references GCM or FCM. If content references GCM, you should probably treat it as a sign that it's either old content OR it's focusing too much on Chrome. (I'm guilty of doing this in a number of old posts.)
> 오늘날 `web push`를 주제로 쓰여진 문서들, 그중에서도 `GCM`과 `FCM`을 참조하는 문서들은 많은 혼란을 야기 합니다. 일단, `GCM`관련 문서에 대해서는 꽤 오래된 문서라고 생각해도 좋고 그 문서는 크롬에 초점이 맞춰진 문서라고 생각하십시요! (글쓴이는 이러한 많은 오래된 포스트에 대해 죄책감을 가지고 있습니다.)
Instead, think of web push as consisting of a browser, which uses a push service to manage sending and receiving messages, where the push service will accept a "web push protocol" request. If you think in these terms, you can ignore which browser and which push service it's using and get to work.
> 반면 웹 푸시는 브라우저의 입부분 이라고 생각 해봅시다. 브라우저는 푸시 서비스를 이용하여 메시지를 송, 수신 하며, 푸시 서비스는 `웹 푸시 프로토콜`로 만들어진 request요청을 사용합니다. 이러한 관점에서 보면 우리는 어떤 브라우저가 어떤 푸시서비스를 사용하고 있고 어떻게 작동하는지 무시 할 수 있습니다.
This guide has been written to focus on the standards approach of web push and purposefully ignores anything else.
> 이 가이드는 표준적인 접근법에 관점을 두고 있으며, 그 이외에는 일부로 언급하지 않습니다.
Firebase has a JavaScript SDK. What and Why?
> 파이어 베이스는 왜 Javscript SDK를 가지고 있나요? 그리고 그게 뭔가요?
For those of you who have found the Firebase web SDK and noticed it has a messaging API for JavaScript, you may be wondering how it differs from web push.
> 여러분들 중에는 자바스크립트의 `messaging API`인 `Firebase web SDK`에 대해 알고 있으며 관심이 있을 것입니다. 여러분은 아마도 이게 `web push`와 어떻게 다른거야! 라고 궁금해 할 것입니다.
The messaging SDK (known as Firebase Cloud Messaging JS SDK) does a few tricks behind the scenes to make it easier to implement web push.
> 이 메시징 SDK(`Firebase Cloud Messating JS SDK`라고 알려진)는 웹 푸시를보다 쉽게 구현할 수 있도록 몇 가지 트릭을 제공합니다.
Instead of worrying about a PushSubscription and its various fields, you only need to worry about an FCM Token (a string).
> `FCM JS SDK`를 사용하면 `PushSubscription`객체가 가지고 있는 많은 `메서드`와 `프로퍼티`에 대한 이해 없이 우리는 `FCM Token(a string)`만 가지고 있으면 됩니다.
Using the tokens for each user, you can use the proprietary FCM API to trigger push messages. This API doesn't require encrypting payloads. You can send a plain text payload in a POST request body.
> 유저들 각각의 `token` 을 이용하면 푸시 메시지를 전송할 수 있는 적절한 `FCM API`를 사용 할 수 있습니다. 이 API는 암호화된 `payloads` 가 필요하지 않습니다. 단지 plain text로 만들어지 payload를 post 방식으로 body넣어 날리기만 하면 됩니다.
FCM's proprietary API supports custom features, for example FCM Topics (It works on the web too, though it's poorly documented).
> FCM의 API는 여러 커스텀 기능을 지원하고 있는데, 예를 들면 `FCM Topics`가 바로 그것 입니다. (`FCM Topics`는 웹에서도 작동 하지만, 문서화가 잘 되어 있지는 않습니다.)
Finally, FCM supports Android, iOS and web, so for some teams it is easier to work with in existing projects.
This uses web push behind the scenes, but its goal is to abstract it away.
> 끝으로 `FCM`은 `Androiod`, `iOS`, 그리고 `web`을 모두 지원합다. 그렇기 때문에 각각 다른 플랫폼을 담당하는 서로 다른 팀들이 쉽게 협력할수 있습니다. `FCM` 코드 뒤에서 `web push`를 사용하지만, `FCM`의 목적은 `web push`를 사용하는 방법을 추상화 하는 것 입니다.
Like I said in the previous question, if you consider web push as just a browser and a push service, then you can consider the Messaging SDK in Firebase as a library to simplify implementing web push.
> 내가 아까 전에 질문에 대답 한것 처럼, 만약 `web push`를 딱 `browser`와 `push service`때문에 고려하고 있다면 간단한 웹푸시 구현 작업을 위해 하나의 `library`로서 `Messaging SDK in Firebase`를 사용하는 걸 고려 할수 있을 것입니다.
```
By default firebase will be looking for /firebase-messaging-sw.js which should contain the firebase libraries and listeners. More details here: https://firebase.google.com/docs/cloud-messaging/js/receive
If you would like to use an existing service worker, you can use https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#useServiceWorker
like this...
```
# 서비스 워커를 unregister 시킬때, subscription은 어떻게 되는가?
- 결론은 구독 취소 된다.
## Clarify when to unsubscribe if the service worker is unregistered
- https://github.com/w3c/push-api/issues/190
> As @wanderview points out in https://bugzilla.mozilla.org/show_bug.cgi?id=1185716#c20, it's possible for a client to be using a service worker registration when it's removed. In that case, the registration is flagged, and can be restored or removed later.
It's unclear what to do with the push subscription in this case. Should it be removed unconditionally, even when the service worker still has clients? Or should it only be removed once all clients have gone away?
>This is all frightfully obtuse, but if we consider subscriptions to be bound to or owned by registrations, then unregister() already includes steps that would remove the subscription. It's transitive, but I interpret the last step of https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#clear-registration-algorithm to cover this. Well, it's all down to garbage collection, but that shouldn't be observable by script.
Am I missing something? I have to admit, it looks like the service work spec is designed to be maximally incomprehensible.
> This is all frightfully obtuse, but if we consider subscriptions to be bound to or owned by registrations, then unregister() already includes steps that would remove the subscription. It's transitive, but I interpret the last step of https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#clear-registration-algorithm to cover this. Well, it's all down to garbage collection, but that shouldn't be observable by script.
Am I missing something? I have to admit, it looks like the service work spec is designed to be maximally incomprehensible.
## https://love2dev.com/blog/how-to-uninstall-a-service-worker/
Also, if you have a push notification subscription registered with the service worker, that subscription is revoked. The next time the service worker checks for the subscription it will prompt you to subscribe.
# Subscription
- https://w3c.github.io/push-api/#widl-PushSubscription-endpoint
A push subscription is a message delivery context established between the user agent and the push service on behalf of a web application. Each push subscription is associated with a service worker registration and a service worker registration has at most one push subscription.
> `push subscription`은 `user agent(브라우저등)`와 `push service`사이에서(`web application(웹서버)` 대신에) 설정정된 메시지 전송 컨텍스트 입니다.
> `각각의 push subscription은 하나의 service worker registration과 관련되어 있고, 하나의 service worker registration은 최대 하나의 push subscription을 가집니다.` -> `중요`
A push subscription has an associated push endpoint. It MUST be the absolute URL exposed by the push service where the application server can send push messages to. A push endpoint MUST uniquely identify the push subscription.
> `push subscripotion`은 하나의 `push endpoint`를 가지고 있습니다. `push endpoint`는 반드시 푸시 서비스에 의해 만들어진 절대경로의 URL로서 `application server`가 푸시 메시지를 보낼수 있는 URL이어야 합니다. `push endpoint` 는 만드시 `push subscription`을 유니크하게 식별 해야 합니다.
A push subscription MAY have an associated subscription expiration time. When set, it MUST be the time, in milliseconds since 00:00:00 UTC on 1 January 1970, at which the subscription will be deactivated. The user agent SHOULD attempt to refresh the push subscription before the subscription expires.
> 하나의 구독은 하나의 `expiratin time`을 가질수 있습니다. `expriation time`은 subscription이 비활성화 될 시간을 1970년 1월 1일 00시 기준으로 그 이후의 시간을 밀리 세컨드로 표현한 시간으로 설정되어야 합니다. `user agent`는 구독이 만료되기전에 구독을 갱신해야 합니다.
A push subscription has internal slots for a P-256 ECDH key pair and an authentication secret in accordance with [RFC8291]. These slots MUST be populated when creating the push subscription.
> 구독은 `P-256 ECDH key pair`와 `[RFC8291]`과 관련된 `authentication secret`을 위한 내부 슬롯을 가집니다. 이 슬롯들은 구독이 생성될때 반드시 채워져야 합니다.
If the user agent has to change the keys for any reason, it MUST fire the "pushsubscriptionchange" event with the service worker registration associated with the push subscription as registration, a PushSubscription instance representing the push subscription having the old keys as oldSubscription and a PushSubscription instance representing the push subscription having the new keys as newSubscription.
> 만약 `user agent` 가 어떤 이유로든 키를 변경 해야 하는 경우 `service worker registration`에서 `pushsubscriptionchange` 이벤트를 발생 시켜야 합니다. 이전 키를 가지는 oldSubscription과 새로운 키를 가지는 newSubscription이 있습니다.
# Firebase_sdk에서 index.html 에 넣는 firebaseConfig 변경될 경우
1. 한번 생성된 토큰은 변함이 없다.
2. 단 messaging 객체를 보면 messagingSenderId 가 변경되어 있다.
3. 한번 생성된 subscription 도 변경이 없다.
# Firebase_sdk에서 usePublicVapidKey 사용 여부에 따른 차이
1. usePublicVapidKey을 사용 안하면, firebaseConfig가 바껴도 subscription 객체의 applicationServerkey값은 동일하다.
2. usePublicVapidKey을 사용 하면 applicationServerkey값이 바뀐다.
https://stackoverflow.com/questions/42455658/what-is-the-use-of-firebase-messaging-sw-js-in-firebase-web-notifications
"https://fcm.googleapis.com/fcm/send/d_NxdJduu-Q:APA91bFM1dzQVP6v7n5wzQrHEiXydK3ggapvy-lFv7LBxHQMoHGnAferE6imcD6VHq4oiSHrvaVPoPLPtV4dZU1ATXvqsKw7T_bEnweBXKYxlff_NyK9r_YecEoRp-sxiePrl-gdgdFN"
"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdQnHZHxSlZqb_WbqXy0Uq1Ox1eUICde8oZUQsnOgC292uCoruPbMQjp2TBDanskxAzvEhWt56q74g0Im8ceKt4I0Fy6Tx9hrxyz3b2-n8rLXW87rij5TUjX7P6bpd5jcInIJPWXRnMnhgZDjVSKxvX4W-C7kJOJ4gy81su5HCzq1pfMs"
"https://fcm.googleapis.com/fcm/send/e55OgyFDk8A:APA91bEb_5HuuVoNPAvf_mtGNJWvOopxq8XyO0zo5F9kD4MFdf9f99Dc50NtwtnBupjSodO1NhV7pWX-j4a8NZu1TqCzVBIyVR9xEm8XWJkjBO-X8fFmhhnjn2trJAhb6vhsnpkRqyzd" <file_sep>
# 1. PUSH 개발 참고내용
# App ID가 변경될때(FCM) Token이 새로 생성되지 않는다.
- fcm 3.6 기준 Firbase config의 APP Id가 변경 될지라도 token이 재생성 되지 않는다.
- 즉, 메시지를 받을 수 없다.
- usePublicVapidKey가 변경 되면 getToken은 변경된다.
- 즉, 옵션으로 usePublicVapidKey을 주고 APP ID가 변경될 필요가 있을때, VapidKey도 변경해 주면, 토큰이 재생성된다.
# 하나의 serviceworker에는 하나의 subscription만 존재 한다.
## a. 다른 path에 같은 serviceworker를 가질경우
- 어느 한쪽 path에서 subscription객체가 변경되면 다른 path의 subscription도 바뀐다.
- 이게 당연한게, subscribe()메서드가 serivceworkerregistration.pushManager 객체에 있는거니까, 등록되어 있는 serviceworker에 종속되는게 당연하다.
- 테스트 결과도 일치한다.
## b. 위의 경우 각기 다른 path에서 다른 VAPID를 가질경우
- 마지막으로 subscription객체를 생성할때 사용한 VAPID가 사용되고,
- 서버에서는 이 VAPID에 해당하는 Private 키를가지고 있어야 푸쉬를 보낼 수 있다.
- pushserver(백엔드)에서 잘못된 VAPID를 사용하여 메시지를 보내면 애러가 난다.
## c. 다른 path (같은 depth) 에서 다른 serviceworker를 가질경우
- 다른 service worker 를 가질 수 없다.
## d. 다른 path (다른 depth) 에서 다른 serviceworker를 가질경우
- 다른 service worker 를 가질 수 있다.
## e. 그럼 다른 path (다른 depth) 에서 다른 serviceworker를 가질경우에 다른 subscribe()을 가지며, push를 발송한 경우 두개의 push를 수신 받는가?
- 그렇다
# VAPID & GMC(FCM) - Push 보내는 방법의 과거와 현재
- `gcm_sender_id` 는 과거의 방법이다.
- 현재는 `applicationServerKey`즉 `VAPID` 를 사용한다.
- 간단히 말하면, `web push protocal`이 정착되기 전 과거 브라우저는 `GCM(FCM) protocol`을 사용하였고 보안상의 문제로
- `gcm_sender_id`를 `menifest.json` 에,
- 타겟이 크롬인 경우`Server key(GCM API key)` 도 함께 `Authorization headerer`에 넣어야 한다.
- 그러나 요즘 브라우저는 `web push protocal`을 사용며 `VAPID`를 사용하고 있고, 이때는 위 `gcm_sender_id` 및 `Server key(GCM API key)`가 필요 없다.
- 42버전과 51버전 사이의 크롬은 구글 클라우드 메시징을 사용해 푸시 메시지를 구현하였고, 오페라와 삼성 브라우저도 같은 방법을 사용했다. 즉, 이전 버번의 브라우저에서도 푸시 알림이 작동하기바란다면 VAPID 키 이외에도 GCM API(gcm_sender_id) 키를 생성해야 한다.
# `GCMAPIKEY` = `GCM-API-KEY` = `GCM Server Key`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그리고 그 푸시를 `크롬`에 할경우 필요 했던 API 값. (`header`)
# `gcm_sender_id` = `GCM 발신자 ID`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그 푸시가 `크롬이든 아니든` 간에 꼭 넣어 줘야 하는 값. (`manifest.json`)
# service worker 등록 로직
- `navigator.serviceWorker.register('sw.js')` 에서 `navigator` 는 브라우저의 종류와 버전 등 웹브라우저 전반에 대한 정보를 제공하는 객체로 즉 `해당 브라우저`에 `service worker`를 등록 시키겠다는 뜻이다.
- 이때, `navigator.serviceWorker.register('sw.js')` 는 기본적으로 서비스 워커 등록의 범위 값은 서비스 워커 스크립트가있는 디렉토리로 설정됩니다. 즉, `navigator.serviceWorker.register('sw.js', {scope: './'})` 의 줄임 말이다.
(https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register#Examples)
- `register('sw.js')` 에서 `service worker` 파일의 상대경로 기준은 해당 `html`페이지가 있는 곳을 기준으로 한다.
- 예를 들면 `/test/index.html` 에서 `navigator.serviceWorker.register('sw.js')` 메서드를 호출하면, `/test/sw.js` 를 `navigator`에 등록시키 겠다는 이야기 이다.
- 절대경로로 들어갈 경우 `register('/sw.js')` `root` 페스가 된다.
- 지금까지 간과하고 있던 게 바로 `scope`의 중요성 인데, 그 이유는 `service worker`는 `브라우저에` 설치 되는 것이고 (`path`나 `domain`에 등록되는 것이 아니다.)
- 하나의 `scope` (`도메인`을 포함한 `path`) 는 하나의 `service worker`에 의해 제어 될 수 있으며,
- 그렇기 때문에 다른 path (같은 depth) 에서 다른 serviceworker를 가질수 없는 것이다.
- 즉, `service worker`는 `service worker`를 등록한 페이지(`path`) 에 자동으로 종속 되는 것이 아니라, (종속 된다고 생각되는 이유는 `service worker` 등록시 `scope` 설정을 안해 주면, 그 `service worker` 파일이 있는 곳이 `scope`로 지정되기 때문이다. )
- `scop`를 설정 할 수 있는 것이다.
- 아래의 예시처럼 하나의 페이지에서 두개의 서비스 워커 등록이 가능하고 (`service worker`는 `navigator`에 등록 되는 것이므로 몇 개든 등록 가능하다)
- 각 등록된 `service worker`의 `scope`를 정의 해줘야 한다.
```js
// /test/index.html
/*
* 상대경로로 지정된 sw6.js는 /test/ 에 있으며
* service worker scope는 default 이므로 /test/ 로 지정된다.
*/
navigator.serviceWorker.register('sw6.js')
/*
* 상대경로로 지정된 sw6.js는 /test/ 에 있으며
* service worker scope는 test/ 이므로 /foo/ 로 지정된다.
*/
navigator.serviceWorker.register('sw6.js', {scope: '/foo/'})
```
# 랜선 뽑은상태에서 구독 생성 (subscribe) 하면 어떻게 되는가
- 구독 되지 않는다.
- 단 크롬 devtool에서 오프라인 상태로 설정하고 subscribe 하면 구독 된다. (완전한 offline 상태가 아니여서 인것 같다.)
# 구독정보가 미리 생성되어 있는 경우 랜선 뽑으면 어떻게 되는가
- 구독 정보 가져 온다.
- swRegistration.pushmanager.getSubscription 에 정보가 있는 것으로, swRegistration이 가지고 있을 것이다.
# subscription 구독시 VAPID 는 필수 이다.
- https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe#Browser_compatibility
- VAPID 없이 생성하려고 하면 애러가 난다 .
# token이 삭제될 경우 ***(중요)***
## token이 삭제될 경우에는 크게 모바일 인터넷 사용 기록 삭제를 눌렀을 경우가 있다. (디폴트로 선택 되어 있는 것만 삭제)
### 1) 크롬
- 노티 설정은 그대로, 토큰은 날라가는 것으로 보임
- 즉 push 안옴, push 받을 건지 알림창 생성도 안됨
- `쿠키 및 사이트 데이터` 삭제가 디폴트 + `사이트 설정`은 별도로 선택 가능 하게 되어 있음
### 2) 삼성 인터넷
- 노티 설정 디폴트로 변경, 토큰도 날라가는 것으로 보임,
- 즉 push 안옴, push 받을 건지 알림창 생성은 됨.
- `쿠키 및 사이트 데이터` 삭제가 디폴트 + `사이트 설정`은 별도로 선택 불가. 아마 임의로 디폴트에 포함 되어 있는것 같음
### 3) 파이어 폭스
- 노티 설정 디폴트로 변경, 토큰은 날라가는 것으로 보임,
- 즉 push 안옴, push 받을 건지 알림창 생성은 됨.
- `쿠키`, `오프라인 웹 데이터` + `웹 사이트별 설정` 삭제가 디폴트
### 4) 위 세가지 경우 모두
- `사이트 데이터` 또는 `오프라인 웹 데이터` 가 삭제 됨으로서 service worker에 저장된 token 도 삭제 된는 것으로 보임
## 삭제됬을 경우에 발생할수 있는 문제
- 일단 우리 로직의 기본은 `노티 설정` 허용 여부에 따라 `push 받을 건지 알림창 생성` -> `토큰 생성` -> `토큰 전송` 로직이다.
- 하지만 위의 경우와 같이 `노티 설정`은 허용 되어 있는데, `토큰` 이 `삭제`되거나, 혹은 `갱신` 되는 경우가 있을 수 있다.
- 그럼 해당 servie woker는 `노티 설정`이 허용되어 있어 `토큰`을 생성하지 못하고, `push`를 받을 수 없게 된다.
## 해결방안
- 따라서, 초기 토큰 생성시, 서버에 전송후 해당 토큰을 `sha-256`으로 인코딩 하여 쿠키로 하나 구워 버리고,
- `pushMessage.js` 파일이 로딩 될때, 일단 service worker가 가진 token을 `messaging.getToken()` 으로 가져와 쿠키와 비교후,
- 쿠키가 없거나, 값이 다르면 서버에 `push/register` API를 호출 하는 방식을 가져야 한다.
## 왜 위와 같은 해결 방안을 적용 해야 하는가?
- FCM 에서는 현재 service worker가 token을 가지고 있는지 없는지 확인이 안된다.
- `messaging.getToken()` 이라는 하나의 메서드만 존재 하는데, 이 메서드는 Token이 없으면, Token을 만들고, Token이 있으면 Token을 가져 오기 때문이다.
- 따라서 `messaging.getToken()`으로 가져온 토큰이 이번에 새로생성된 토큰인지 아닌지 알 수가 없다.
- 그렇다고 `messaging.getToken()`으로 가져오 토큰을 매번 서버에 전송하는 것은 리소스가 너무 크므로 말이 안된다.
# 프론트 스크립트에서 usePublicVapidKey 사용 안했을 경우
- `webpush 프로토콜 전송` : 전송 안됨 (VAPID가 다를 것으로 생각됨)
- `fcm 프로토콜 전송` : 전송 됨
# 프론트 스크립트에서 usePublicVapidKey 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)
- `webpush 프로토콜 전송` : 전송 됨
- `fcm 프로토콜 전송` : 전송 됨
# 프론트 스크립트에서 usePublicVapidKey 사용 했을 경우 (별도로 생성된 VAPID)
- `webpush 프로토콜 전송` : 전송 됨
- `fcm 프로토콜 전송` : 전송 안됨 (Token 값이 생성 안됨)
# usePublicVapidKey 변화에 따른 - getPublicVapidKey_()
- usePublicVapidKey 사용 안한것과, 사용 한것의 PublickKey는 다르다. (당연한 이야기)
```js
// 사용 안했을 경우
messaging.getPublicVapidKey_().then(e=>console.log(e))
// Uint8Array(65) [4, 51, 148, 247, 223, 161, 235, 177, 220, 3, 162, 94, 21, 113, 219, 72, 211, 46, 237, 237, 178, 52, 219, 183, 71, 58, 12, 143, 196, 204, 225, 111, 60, 140, 132, 223, 171, 182, 102, 62, 242, 12, 212, 139, 254, 227, 249, 118, 47, 20, 28, 99, 8, 106, 111, 45, 177, 26, 149, 176, 206, 55, 192, 156, 110]
// 사용 했을 경우 (fcm 관리자 페이지에서 제공하는 VAPID)
messaging.getPublicVapidKey_().then(e=>console.log(e))
//Uint8Array(65) [4, 224, 135, 161, 79, 216, 155, 203, 202, 27, 153, 163, 192, 133, 115, 53, 52, 225, 63, 250, 233, 114, 58, 200, 236, 45, 165, 136, 189, 236, 98, 17, 169, 2, 223, 165, 120, 63, 85, 223, 232, 32, 81, 162, 45, 143, 152, 46, 21, 110, 102, 228, 145, 48, 173, 233, 159, 10, 123, 127, 166, 221, 137, 34, 177]
// 사용 했을 경우 (별도로 생성된 VAPID)
// "publicKey": "<KEY>",
// "privateKey": "<KEY>"
messaging.getPublicVapidKey_().then(e=>console.log(e))
// Uint8Array(65) [4, 230, 251, 97, 19, 195, 83, 11, 255, 139, 113, 219, 121, 199, 39, 236, 251, 251, 33, 15, 209, 183, 187, 117, 241, 30, 176, 67, 82, 47, 33, 93, 98, 31, 79, 130, 143, 201, 64, 35, 102, 187, 38, 91, 58, 196, 236, 197, 109, 213, 229, 184, 190, 103, 174, 100, 190, 65, 92, 10, 72, 175, 232, 245, 62]
```
- usePublicVapidKey 사용 안한것과, 사용 한것의 messaging Token값이 항상 다르다.
- 매번 새로 생성하기때문에
# usePublicVapidKey 변화에 따른 - FCM 프로토콜 & webpush 프로토콜 전송
- usePublicVapidKey 바꿀때 subscription은 변경되지 않기때문에
- `usePublicVapidKey 바꿀때 마다, service-worker 재등록 필요`
- 해당 내용은 (https://github.com/web-push-libs/web-push-php/issues/58), (https://github.com/w3c/push-api/issues/291) 에서 살펴 볼수 있다.
- 참조 (https://w3c.github.io/push-api/)
If the Service Worker is already subscribed, run the following substeps:
Retrieve the push subscription associated with the Service Worker.
If there is an error, reject promise with a DOMException whose name is "AbortError" and terminate these steps.
Let subscription be the retrieved subscription.
Compare the options argument with the options attribute of subscription. If any attribute on options contains a different value to that stored for subscription, then reject promise with an InvalidStateError and terminate these steps. The contents of BufferSource values are compared for equality rather than references.
When the request has been completed, resolve promise with subscription.
- appid가 변경된다고 token이 재생성 되지는 않늗다.
- 단, usePublicVapidKey가 변경 되면 getToken은 변경된다.
- firefox 브라우저의 경우 subscription의 endpoint는 항상 `mozila` 이다.
# PUSH API를 사용할때, (FCM x) ApplicationServerKey(VAPID) 가변경 될 경우에도, Subscription은 자동으로 변경되지 않는다.
- 해당 내용은 (https://github.com/web-push-libs/web-push-php/issues/58), (https://github.com/w3c/push-api/issues/291) 에서 살펴 볼수 있다.
- 참조 (https://w3c.github.io/push-api/)
- Subscription을 변경 하려면, 기존의 Subscription의 ApplicationServerKey와 변경될 ApplicationServerKey를 비교해야 하는데, 비교하는 법에 대해 자세히 나온게 없다.
- 임의로 찾아낸 방법은 아래와 같다.
```js
// main.js
// 1. 기존 subscripltion ApplicationServerKey
var test;
registration.pushManager.getSubscription().then(e=>test = e.options.applicationServerKey) // ArrayBuffer(65);
var test2 = new Uint8Array(test); // Uint8Array(65)
var test3 = test2.join(','); // string
// 2. 변경할 ApplicationServerKey
var test4 = urlB64ToUint8Array('<KEY>').join(',') //string
// 3. 비교
test3 === test4
```
# registration.showNotification
## tag
- 알림을 나타내는 고유 식별자 입니다. 만약 현재 표시되 ㄴ태그와 동일한 태그를 가진 알림이 도착하면, 예전 알림은 조용히 새 알림으로 대체됩니다.
- 알림을 여러개 생성해 사용자를 귀찮게 하는 것보다 이 방법이 더 좋은 경우가 많스니다. 예를 들어, 메시징 앱에 안 읽은 메시지가 하나 있는 경우, 알림에 그 메시지 내용을 포함하고 싶을 것입니다. 그런데 기존 알림이 사라지기 전에 다섯개의 신규 메시지가 도착해다면, 여섯개의 별도 알림을 보여주는 것보다 6개의 새로운 메시지가 있습니다. 와 같이 기존 알림 내용을 업데이트 하는 것이 더 좋습니다.
- [만들면서 배우는 프로그래시브 웹 p.284]
## renotify (boolean)
- 같은 태그로 보내면 조용히 대체 되나, 태그 값을 주면서 renotify를 주면, 교체 될때 알림이 왔다고 표시한다.
- renotify가 true인데 tag가 빈값이면, TypeError가 전달된다.(https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification)
# 알림 안드로이드 크롬의 경우
- 디폴트가 소리로만 알림이다. 변경하기 위해서는 설정에서 중요도를 긴급으로 변경해야 합니다.
- 인스톨 뒤에 중요도를 긴급으로 변경했음에도 불구하고 다시 디폴트가 소리로만 알림으로 변경된다. 마찬가지로 변경하기 위해서는 설정에서 중요도를 긴급으로 변경해야 합니다.
# tip
- `Navigator.serviceWorker.register('sw.js')` 가 없어도, 한번등록된 serviceworker는 내용이 변경되면 업데이트 하려고 한다.
# Notification icon & badge image size (알림 아이콘 및 뱃지 이미지 사이즈에 대해)
## icon
- `192px`
- Sadly there aren't any solid guidelines for what size image to use for an icon. Android seems to want a 64dp image (which is 64px multiples by the device pixel ratio). `If we assume the highest pixel ratio for a device will be 3, an icon size of 192px or more is a safe be` (https://developers.google.com/web/fundamentals/push-notifications/display-a-notification)
## badge
- `72px`
- As with the icon option, there are no real guidelines on what size to use. Digging through Android guidelines the recommended size is 24px multiplied by the device pixel ratio. `Meaning an image of 72px or more should be good (assuming a max device pixel ratio of 3).`
# Splash Image
- IOS 의 경어 2019년 04월부터 polyfil 형식으로 splash 적용
- https://stackoverflow.com/questions/55840186/ios-pwa-splash-screen
# onTokenRefresh
- 언제 FCM토큰이 재생성 되는가!
- 구현되지 않았다!!!
- https://github.com/firebase/quickstart-js/issues/217
- https://stackoverflow.com/questions/42136312/how-i-can-test-firebase-notification-ontokenrefresh-method-call-in-javascript
# Push & Notification 작동 원리
[https://w3c.github.io/push-api/#widl-PushSubscription-unsubscribe-Promise-boolean]

[프로레시브 웹 앱의 모든것 p.271]
## Permission for Push Notifications
## Subscriptions
- push 등록은 각 `device` 와 `browser`별로 등록된다. 즉 같은 device의 다른 browser라면 다른 사용자로 인식한다.
- 기존에 등록된 `subscript`이 없다면 새로운 `subscrition`을 생성해야 하며, 이 `subscription`은 `backend server`로 전달 되어야 한다.
## Push server (Push Service)
- Push notification은 별도의 external server(browsr vendor에서 제공하는 push server)를 필요로 한다.
- push마다 어떤 message를 app(아마도 web page)에 전달하기 위해서는 browser의 도움이 필요로 한다.
- 우리의 APP(web page) 자체로는 message를 수신 할수 없기 때문이다.
- (web socket을 만들수도 있지만, 우리 app이 항상 오픈 되어 있어야 작동하기 때문에 적합하지 않다.)
- Browser vendor(공급자)는 자사의 browser로 어떤 app을 이요하는 사용자에게 push를 발송하기 위한 `Push server(Push Service)` 를 제공한다.
- Google, Mozilla 등 각각의 browser vendor가 push server(Push Service)를 가지고 있고, 해당 browese사용자에게 push를 발송하기 위해서는 vendor의 push server(Push Service)에 연계된 setting이 필요하다.
## End point
- push server(Push Service)는 각 browser vendor의 소유 이므로 우리가 설정 할 수는 없다.
- 단, 우리가 javascript로 `new subscription`을 setup하면 (`ServiceWorkerRegistration.PushManager.subscribe(options)`) javascript는 자동으로 browsder vendor에서 제공하는 push server(Push Service)에 접근해서 `Endpoint`를 가져온다.
- 새로 등록된 subscript은 push API endpoint 정보 `(push server의 url)` 을 가지게 되고, 각가의 등롣된 `device-browser`마다 자신만의 다른 endpoint를 가지게 된다.
### google의 endpoit 예시
```json
{
"endpoint": "https://fcm.googleapis.com/fcm/send/d2Qi49CN31o:APA91bE41fL9u_kXfOmGEb6sdafOvdKPcvoHswJpMaX29PKeYzrZC2eT_wJ0lPL2YfDuK888wTUd8kSPFFEsDqxWJZgzu_XluhuG8-ACgZuauKHHqL1KpbBLjQngYgR477H6Piw-RVUA",
"expirationTime": null,
"keys": {
"p256dh": "<KEY>",
"auth": "<KEY>"
}
}
```
### mozila의 endpoit 예시
```json
{
"endpoint": "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdIbR7rKOoWIlaR-dF3fszV4W2hQusl4HpWsOJlA8Dc5VleB4mpCnhD7Oi<KEY>",
"keys": {
"auth": "CeC6IOLjchl1p4aCneY2Tg",
"p256dh": "<KEY>"
}
}
```
## push message
- endpoint는 push server(Push Service)의 url이며 우리는 이 endpoint url로 new push message를 send하게 된다.
- browser vendor(push server)는 이 push message를 각 web app에 전달 한다.
## Authentication information
- endpoint 유출 시 endpoint를 아는 누구나가 push message를 보낼 수 있다.
- 그래서 특별한 key 가 필요하다.
- 설정한 key에 의해서 subscription생성시(`ServiceWorkerRegistration.PushManager.subscribe(options)`) authentication정보도 만들어 지는다. 이 인증 정보는 우리만이 우리의 web app 에 push 할수 있도록 분별해 준다.
## subsription과 backend server
- browser vendor의 push server와는 별개로 우리 app의 code가 구동 될 수 있는 backend server도 필요하다.
- 사용자 app의 servidce worker는 new subscription을 생성하고
- subscription은 endpoint등에 대한 정보를 가지고 있으면,
- backend 서버는 각각의 subscription을 가 보관한다.
# Push & Notification에 대한 이해
- 각 브라우저는 각 push service를 가지고 있고, 백엔드 서버는 push service에 푸시를 보낼 메시지를 보낸다.
- push service는 적절한 디바이스-브라우저에게 푸시를 보내고
- 서비스 워커는 해당 푸시를 받고, 브라우저를 깨운다.
> There are several pieces that come together to make push notifications work. Browsers that support web push each implement their own push service, which is a system for processing messages and routing them to the correct clients. Push messages destined to become notifications are sent from a server directly to the push service, and contain the information necessary for the push service to send it to the right client and wake up the correct service worker. The section on the Push API describes this process in detail.
When it receives a message, the service worker wakes up just long enough to display the notification and then goes back to sleep. Because notifications are paired with a service worker, the service worker can listen for notification interactions in the background without using resources. When the user interacts with the notification, by clicking or closing it, the service worker wakes up for a brief time to handle the interaction before going back to sleep. [https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#working_with_data_payloads]
# unsubscription
- 구독은 서비스 워커 하나에 유일하다.
- 구독 된 상태에서 구독 하면 같은 subscription을 반환 한다.
- 구독 해지 하고 재 구독 하면 다른 subscription을 반환 한다.
- **구독 된 상태에서 오프라인 상태에서 구독 해지 후 온라인에서 구독 하면 새로운 구독이 된다** => **데이터베이스에는 예전 구독이 남아 있다**
# TTL 푸시 서비스에서 메시지를 보관하는 기간
- 0 으로 지정해 주자 (크롬 디폴트는 4주)
## chrome
- https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
Managing Notifications at the Server
So far, we've been assuming the user is around to see our notifications. But consider the following scenario:
The user's mobile device is offline
Your site sends user's mobile device a message for something time sensitive, such as breaking news or a calendar reminder
The user turns the mobile device on a day later. It now receives the push message.
That scenario is a poor experience for the user. The notification is neither timely or relevant. Our site shouldn't display the notification because it's out of date.
You can use the time_to_live (TTL) parameter, supported in both HTTP and XMPP requests, to specify the maximum lifespan of a message. The value of this parameter must be a duration from 0 to 2,419,200 seconds, corresponding to the maximum period of time for which FCM stores and tries to deliver the message. Requests that don't contain this field default to the maximum period of 4 weeks. If the message is not sent within the TTL, it is not delivered.
Another advantage of specifying the lifespan of a message is that FCM never throttles messages with a time_to_live value of 0 seconds. In other words, FCM guarantees best effort for messages that must be delivered "now or never". Keep in mind that a time_to_live value of 0 means messages that can't be delivered immediately are discarded. However, because such messages are never stored, this provides the best latency for sending notifications.
## mozila
- https://blog.mozilla.org/services/2016/02/20/webpushs-new-requirement-ttl-header/
# web-push library (백엔드에서 푸쉬 보낼때 사용 할 라이브러리)
- https://developers.google.com/web/fundamentals/push-notifications/sending-messages-with-web-push-libraries
# webpush.sendNotification(pushSubscription, payload, options)
## payload
- argument 중 payload 값은 text 또는 node buffer 값으로 들어가야 한다.
>The payload is optional, but if set, will be the data sent with a push message. This must be either a string or a node Buffer. [https://www.npmjs.com/package/web-push]
## GCM VS FCM
https://developers.google.com/cloud-messaging/faq
# 2. APP INSTALL 개발 참고내용
## scope
- manifest.json에서 `scope` 혹은 `start_url` 멤버로 정의 된 스코프를 벗어나면 상단에 주소 url 이 표기 되는등 정상 적인 화면이 아닌 다른 화면이 보어거나, 브라우저가 실행된다.
## start_url 과 scope
- If the scope member is not present in the manifest, it defaults to the parent path of the start_url member. For example, if start_url is /pages/welcome.html, and scope is missing, the navigation scope will be /pages/ on the same origin. If start_url is /pages/ (the trailing slash is important!), the navigation scope will be /pages/.
- Developers should take care, if they rely on the default behavior, that all of the application's page URLs begin with the parent path of the start URL. To be safe, explicitly specify scope.
(https://www.w3.org/TR/appmanifest/)
- 말인 즉슨 `scope`를 제대로 안적어 주면 `scope`의 디폴트 값은 `start_url`의 디폴트로 정의 해준 값의 `parent path`가 스코프로 정의 된다는 거다. 왠만하면 `scope`를 적어 주라고 하고 있다.
- 실제로 내가 적용했을때 `satrt_url: index/?aplication=pwa` 같이 정의 했더니, `https://test.com/page1/test.html` 이 `scope`에서 벗어난것처럼 작동 되었다. 왜냐하면 여기서 `scope`는 `index/` 하위의 path가 될거고, 도메인 하위의 `/page` path는 `scope`에서 벗어난게 되기 때문이다!<file_sep># PWA란
- 아래의 내용을 필요한대로 골라서 점진적으로 웹을 앱처럼 만든다.
- 보안(https),
- 앱설치,
- GPS,
- Push,
- 카메라기능,
- 빠른 속도(오프라인환경에서 작동, 캐쉬등...) 등등...
# caching strategy 캐싱 전략
## 1. Cache only (캐시만 사용)
- 모든 리소스에 대해 케시만 사용하여 불러옴
```js
self.addEventListener('fetch', event=>{
event.repondWith(
caches.match(event.request); // return A Promise that resolves to the matching Response.
)
})
```
## 2. Cache, falling back to network (캐시, 실패하는 경우 네트워크)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
caches.match(event.request).then(reponse => {
return response || fetch(event.request)
})
)
})
// async/await
self.addEventListener('fetch', event =>{
event.respondWith(
async function(){
let result = await caches.match(event.request);
if(result) return result ;
return fetch(event.request)
}
)
})
```
## 3. Network only (네트워크만 사용)
```js
self.addEventListener('fetch', function(event){
event.respondWith(
fetch(event.request)
)
})
```
## 4. Network, falling back to cache (네트워크, 실패하는 경우 캐시)
```js
// Promise callback
self.addEventListener('fetch', event =>{
event.respondWith(
fetch(event.request).catch(()=>{
return caches.match(event.request);
})
)
})
// async/await
self.addEventListener('fetch', event =>{
event.respondWith(
async function(){
try{
return await fetch(event.request)
}catch(err){
return caches.match(event.request)
}
}
)
})
```
## 5. Cache, then network (캐시 이후 네트워크)
## 6. Generic fallback (기본 대체 리소스)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
fetch(event.request).catch(()=>{
return caches.match(event.request).then(response=>{
return response || caches.match('/generic.png')
)}
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){
try{
let response = await fetch(event.request);
return response
}catch (err) {
let response = await caches.match(event.request);
return response || caches.match('/generic.png');
}
}
)
})
```
## 7. Cache on demand (요청에 따라 캐시 -> 캐시, 실패하는 경우 네트워크, 이후 캐시 저장)
```js
// Promise callback
self.addEventListener('fetch', event=>{
event.respondWith(
caches.open('cache-name').then(cache => {
return cache.match(event.request).then(cachedResponse => {
return cachedResponse || fetch(event.request).then(networkResponse => {
cache.put(event.request, networkresponse.clone());
return networkResponse;
})
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){ // async function 은 Promise (async 함수에 의해 반환 된 값으로 해결되거나, async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값)을 리턴한다.
let cache = await caches.open('cache-name');
let cachedResponse = await cache.match(event.request);
if(cachedResponse) return cachedResponse;
let networkResponse = await fetch(event.request);
cache.put(event.request, networkResponse.clone());
return networkResponse;
}
)
})
```
## 8. Cache, falling back to network with frequent updates (캐시, 이후 네트워크 사용해 캐시 업데이트 -> 캐시, 성공하든 실패하든 네이트워크 이용하여 캐시 저장)
```js
self.addEventListener('fetch', event => {
event.respondWith(
caches.open('cache-name').then(cache => {
return cache.match(evnet.request).then(cachedResponse => {
var fetchPromise = fetch(evnet.request).then(networkResponse =>{
cache.put(event.request, networkResponse.clone())
return networkResponse;
});
return cacheResponse || fetchPromise;
})
})
)
})
// async/await
self.addEventListener('fetch', event=>{
event.respondWith(
async function(){ // async function 은 Promise (async 함수에 의해 반환 된 값으로 해결되거나, async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값)을 리턴한다.
let cache = await caches.open('cache-name');
let cachedResponse = await cache.match(event.request); // undefined 반환 가능
let networkResponse = await fetch(event.request);
cache.put(event.request, networkResponse.clone());
return cachedResponse || networkResponse;
}
)
})
```
## 9. Network, falling back to cache with frequent updates (네트워크, 실패하는 경우 캐시 사용 및 비번한 캐시 업데이트)
```js
self.addEventListener('fetch',event => {
event.respondWith(
caches.open('cache-name').then(cache => {
return fetch(event.request).then(networkResponse => {
cache.put(event.request, networkResponse.clone())
return networkResponse;
}).catch((=>{
return caches.match(event.request)
}))
})
)
})
self.addEventListener('fetch', event => {
event.respondWith(
async function(){
let cache = await caches.open('cache-name');
try{
let networkResponse = fetch(event.request);
cache.put(event.request, networkResponse.clone())
return networkResponse;
}catch{
let cachedResponse = await caches.match(event.request);
return cachedResponse;
}
}
)
})
```
## 10. 앱 셸
# Service worker scope
> Scope is linked with domain/origin. You can not create a service worker that intercepts request for other origins. If you try to register a service worker from origin which is different from origin of service worker file sw.js, then error will be thrown like The origin of the provided scriptURL ('https://cdn.example.com/sw.js') does not match the current origin. [https://itnext.io/service-workers-your-first-step-towards-progressive-web-apps-pwa-e4e11d1a2e85]
# 서비스 워커
- 서비스 워커는 자신이 제어하는 페이지에서 발생하는 이벤트를 수신합니다.웹에서 파일을 요청하는 것과 같은 이벤트를 가로채거나 수정하고 다시 페이지로 돌려보낼 수 있습니다.
# App 설치
- BeforeInstallPromptEvent ("install" a web site to a home screen.)
- 사파리 지원 안됨
- `beforeinstallprompt` : 앱 설치 조건이 만족 되면 (https://developers.google.com/web/fundamentals/app-install-banners/?hl=ko#criteria) `beforeinstallprompt` 이벤트 실행
- `BeforeInstallPromptEvent.prompt()` : 앱을 설치 할건지 묻는 함수
## 설치 조건
- The web app is not already installed.
- and prefer_related_applications is not true.
- Meets a user engagement heuristic (previously, the user had to interact with the domain for at least 30 seconds, this is not a requirement anymore)
- Includes a web app manifest that includes:
- short_name or name
- icons must include a 192px and a 512px sized icons
- start_url
- display must be one of: fullscreen, standalone, or minimal-ui
- Served over HTTPS (required for service workers)
- Has registered a service worker with a fetch event handler
# registration.showNotification
## tag
- 알림을 나타내는 고유 식별자 입니다. 만약 현재 표시되 ㄴ태그와 동일한 태그를 가진 알림이 도착하면, 예전 알림은 조용히 새 알림으로 대체됩니다.
- 알림을 여러개 생성해 사용자를 귀찮게 하는 것보다 이 방법이 더 좋은 경우가 많스니다. 예를 들어, 메시징 앱에 안 읽은 메시지가 하나 있는 경우, 알림에 그 메시지 내용을 포함하고 싶을 것입니다. 그런데 기존 알림이 사라지기 전에 다섯개의 신규 메시지가 도착해다면, 여섯개의 별도 알림을 보여주는 것보다 6개의 새로운 메시지가 있습니다. 와 같이 기존 알림 내용을 업데이트 하는 것이 더 좋습니다.
- [만들면서 배우는 프로그래시브 웹 p.284]
# FCM 관련 잠정 결정
## 전역 service-worker.js 파일을 사용한다.
- 별도의 scope를 가진 serviceworker(`firebase-messaging-sw.js` 포함)을 사용하지 않는다.
- 다른 scope를 가진 service-worker는 자동으로 파일 업데이트를 확인 하지 않는다. (테스트 결과)
- 해당 scope의 페이지에 진입하거나 강제로 servicewoker를 업데이트 해줘야 한다.
- `firebase-messaging-sw.js`의 경우에는 `messaging.getToken();` 메서드 실행시 강제 업데이트가 된다.
- 필요 없어질 경우 해당 serviceworker를 unregester 시키는 방법도 애매하다.
- 위의 경우처럼 업데이트 시점을 위해, 루트 패스 하위 페이지는 적절한 servicewoker파일의 업데이트를 위하여 업데이트를 위한 js파일이 별도로 필요해진다.
## service-worker.js 파일에서 push를 위한 firebase 라이브러리를 사용하지 않는다.
- setBackgroundMessageHandler을 사용하면 포그라운드에서 노티 띄우는게 복잡해 진다.
- 복잡해 진다는 것은 각 js 파일에 포그라운드 이벤트 수신시 노티를 띄우는 로직을 추가 해야 한다.
- firebase 라이브러리가 없어도 디폴트 push API로 잘 동작 한다.
## manifest.json의 위치
### static 서버에 있을 경우
- `start_url` 의 경로가 도메인을 포함한 절대 경로로 지정해야 하므로, 각 망별로 다른 manifest.json을 생성 해야 한다.
- `icon` 이미지 경로가 통일 되나, 어자피, 위의 이유로 manifest.json 을 여러개 만들어야 한다.
### web 서버에 있을 경우
- `start_url` 의 경로가 상재 경로로 지정할 수 있어 manifest.json파일이 하나면 된다.
- `icon` 이미지를 web server에 저장 하거나
- `icon` 이미지를 static server에 저장하려면 망별로 다른 static 서버에 저장해야 하며, manifest.json 파일도 망별로 다른 것을 준비 해야 한다.
- 그런데 이미지를 web server에 저장해도 되나!?
### 결론
- 일단 web 서버에 넣고, `icon`이미지도 web server에 저장 하면 하나의 manifest.json과 icon 파일로 해결 가능 하다.??
# tip
- `Navigator.serviceWorker.register('sw.js')` 가 없어도, 한번등록된 serviceworker는 내용이 변경되면 업데이트 하려고 한다.
# Push & Notification 작동 원리
[https://w3c.github.io/push-api/#widl-PushSubscription-unsubscribe-Promise-boolean]

[프로레시브 웹 앱의 모든것 p.271]
## Permission for Push Notifications
## Subscriptions
- push 등록은 각 `device` 와 `browser`별로 등록된다. 즉 같은 device의 다른 browser라면 다른 사용자로 인식한다.
- 기존에 등록된 `subscript`이 없다면 새로운 `subscrition`을 생성해야 하며, 이 `subscription`은 `backend server`로 전달 되어야 한다.
## Push server (Push Service)
- Push notification은 별도의 external server(browsr vendor에서 제공하는 push server)를 필요로 한다.
- push마다 어떤 message를 app(아마도 web page)에 전달하기 위해서는 browser의 도움이 필요로 한다.
- 우리의 APP(web page) 자체로는 message를 수신 할수 없기 때문이다.
- (web socket을 만들수도 있지만, 우리 app이 항상 오픈 되어 있어야 작동하기 때문에 적합하지 않다.)
- Browser vendor(공급자)는 자사의 browser로 어떤 app을 이요하는 사용자에게 push를 발송하기 위한 `Push server(Push Service)` 를 제공한다.
- Google, Mozilla 등 각각의 browser vendor가 push server(Push Service)를 가지고 있고, 해당 browese사용자에게 push를 발송하기 위해서는 vendor의 push server(Push Service)에 연계된 setting이 필요하다.
## End point
- push server(Push Service)는 각 browser vendor의 소유 이므로 우리가 설정 할 수는 없다.
- 단, 우리가 javascript로 `new subscription`을 setup하면 (`ServiceWorkerRegistration.PushManager.subscribe(options)`) javascript는 자동으로 browsder vendor에서 제공하는 push server(Push Service)에 접근해서 `Endpoint`를 가져온다.
- 새로 등록된 subscript은 push API endpoint 정보 `(push server의 url)` 을 가지게 되고, 각가의 등롣된 `device-browser`마다 자신만의 다른 endpoint를 가지게 된다.
### google의 endpoit 예시
```json
{
"endpoint": "https://fcm.googleapis.com/fcm/send/d2Qi49CN31o:APA91bE41fL9u_kXfOmGEb6sdafOvdKPcvoHswJpMaX29PKeYzrZC2eT_wJ0lPL2YfDuK888wTUd8kSPFFEsDqxWJZgzu_XluhuG8-ACgZuauKHHqL1KpbBLjQngYgR477H6Piw-RVUA",
"expirationTime": null,
"keys": {
"p256dh": "<KEY>",
"auth": "<KEY>"
}
}
```
### mozila의 endpoit 예시
```json
{
"endpoint": "https://updates.push.services.mozilla.com/wpush/v2/gAAAAABdIbR7rKOoWIlaR-dF3fszV4W2hQusl4HpWsOJlA8Dc5VleB4mpCnhD7Oi1qer--DSPbJTiurEjjTUbgjPQAkQmwjxvyifArIYhTPiqhB7G19A5q_NAVctKmgESy1Vakz8v2MM5ezL10bch0Id0It3sqtd0ug9wKAuypUsU5O9CkkPMnc",
"keys": {
"auth": "CeC6IOLjchl1p4aCneY2Tg",
"p256dh": "<KEY>AXESby68HogXA"
}
}
```
## push message
- endpoint는 push server(Push Service)의 url이며 우리는 이 endpoint url로 new push message를 send하게 된다.
- browser vendor(push server)는 이 push message를 각 web app에 전달 한다.
## Authentication information
- endpoint 유출 시 endpoint를 아는 누구나가 push message를 보낼 수 있다.
- 그래서 특별한 key 가 필요하다.
- 설정한 key에 의해서 subscription생성시(`ServiceWorkerRegistration.PushManager.subscribe(options)`) authentication정보도 만들어 지는다. 이 인증 정보는 우리만이 우리의 web app 에 push 할수 있도록 분별해 준다.
## subsription과 backend server
- browser vendor의 push server와는 별개로 우리 app의 code가 구동 될 수 있는 backend server도 필요하다.
- 사용자 app의 servidce worker는 new subscription을 생성하고
- subscription은 endpoint등에 대한 정보를 가지고 있으면,
- backend 서버는 각각의 subscription을 가 보관한다.
# Push & Notification에 대한 이해
- 각 브라우저는 각 push service를 가지고 있고, 백엔드 서버는 push service에 푸시를 보낼 메시지를 보낸다.
- push service는 적절한 디바이스-브라우저에게 푸시를 보내고
- 서비스 워커는 해당 푸시를 받고, 브라우저를 깨운다.
> There are several pieces that come together to make push notifications work. Browsers that support web push each implement their own push service, which is a system for processing messages and routing them to the correct clients. Push messages destined to become notifications are sent from a server directly to the push service, and contain the information necessary for the push service to send it to the right client and wake up the correct service worker. The section on the Push API describes this process in detail.
When it receives a message, the service worker wakes up just long enough to display the notification and then goes back to sleep. Because notifications are paired with a service worker, the service worker can listen for notification interactions in the background without using resources. When the user interacts with the notification, by clicking or closing it, the service worker wakes up for a brief time to handle the interaction before going back to sleep. [https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#working_with_data_payloads]
# unsubscription
- 구독은 서비스 워커 하나에 유일하다.
- 구독 된 상태에서 구독 하면 같은 subscription을 반환 한다.
- 구독 해지 하고 재 구독 하면 다른 subscription을 반환 한다.
- **구독 된 상태에서 오프라인 상태에서 구독 해지 후 온라인에서 구독 하면 새로운 구독이 된다** => **데이터베이스에는 예전 구독이 남아 있다**
# TTL 푸시 서비스에서 메시지를 보관하는 기간
- 0 으로 지정해 주자 (크롬 디폴트는 4주)
## chrome
- https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
Managing Notifications at the Server
So far, we've been assuming the user is around to see our notifications. But consider the following scenario:
The user's mobile device is offline
Your site sends user's mobile device a message for something time sensitive, such as breaking news or a calendar reminder
The user turns the mobile device on a day later. It now receives the push message.
That scenario is a poor experience for the user. The notification is neither timely or relevant. Our site shouldn't display the notification because it's out of date.
You can use the time_to_live (TTL) parameter, supported in both HTTP and XMPP requests, to specify the maximum lifespan of a message. The value of this parameter must be a duration from 0 to 2,419,200 seconds, corresponding to the maximum period of time for which FCM stores and tries to deliver the message. Requests that don't contain this field default to the maximum period of 4 weeks. If the message is not sent within the TTL, it is not delivered.
Another advantage of specifying the lifespan of a message is that FCM never throttles messages with a time_to_live value of 0 seconds. In other words, FCM guarantees best effort for messages that must be delivered "now or never". Keep in mind that a time_to_live value of 0 means messages that can't be delivered immediately are discarded. However, because such messages are never stored, this provides the best latency for sending notifications.
## mozila
- https://blog.mozilla.org/services/2016/02/20/webpushs-new-requirement-ttl-header/
# web-push library (백엔드에서 푸쉬 보낼때 사용 할 라이브러리)
- https://developers.google.com/web/fundamentals/push-notifications/sending-messages-with-web-push-libraries
# webpush.sendNotification(pushSubscription, payload, options)
## payload
- argument 중 payload 값은 text 또는 node buffer 값으로 들어가야 한다.
>The payload is optional, but if set, will be the data sent with a push message. This must be either a string or a node Buffer. [https://www.npmjs.com/package/web-push]
# Notification 에 대한 정리
https://developers.google.com/web/fundamentals/push-notifications/display-a-notification
## 화면 구성

## badge 아이콘
- badge의 경우 모바일 크롬만 되는듯 하다. (삼성 브라우저는 안됬음)
# push가 동작하는 조건
## pc인 경우
- background에서 브라우저 앱이 돌고 있을때(맥 기준으로 브라우저를 닫더라도, 실행 아이코에 파란색 점이 찍혀 있을때)
- 테스트 결과 완전히 종료된 이후 push를 보내면, 다시 브라우저 실행 시켰을때 메시지를 받는다.
## mobile의 경우
- 테스트 결과 브라우저 앱을 완전히 종료해도 메시지가 온다. (https://stackoverflow.com/questions/39034950/google-chrome-push-notifications-not-working-if-the-browser-is-closed)
- 딱히 app install 절치를 진행하지 않아도 됨.
# VAPID & GMC(FCM) - Push 보내는 방법의 과거와 현재
- `gcm_sender_id` 는 과거의 방법이다.
- 현재는 `applicationServerKey`즉 `VAPID` 를 사용한다.
- 간단히 말하면, `web push protocal`이 정착되기 전 과거 브라우저는 `GCM(FCM) protocol`을 사용하였고 보안상의 문제로
- `gcm_sender_id`를 `menifest.json` 에,
- 타겟이 크롬인 경우`Server key(GCM API key)` 도 함께 `Authorization headerer`에 넣어야 한다.
- 그러나 요즘 브라우저는 `web push protocal`을 사용며 `VAPID`를 사용하고 있고, 이때는 위 `gcm_sender_id` 및 `Server key(GCM API key)`가 필요 없다.
## 참조 1
> Throughout this book we’ve been using the `application server key('VAPID')` to identify our application with push services. This is the Web Standards approach of application identification.
In older versions of Chrome (version 51 and before), Opera for Android and the Samsung Internet Browser there was a non-standards approach for identifying your application.
In these browsers they required a `gcm_sender_id` parameter to be added to a web app manifest and the value have to be a Sender ID for a Google Developer Project.
This was completely proprietary and only required since the `application server key` / `VAPID` spec had not been defined. (`여기서 'application server key' 라고 하면 ' VAPID' 와 동일한 의미인데, pushManager.subscript({option})의 option값 중 하나의 key가 'applicationServerKey'이며 value값은 'VAPID'가 된다.`)
In this section we are going to look at how we can add support for these browsers. Please note that this isn’t recommended, but if you have a large audience on any of these browsers / browser versions, you should consider this.
[https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/]
## 참조2
> When Chrome first supported the Web Push API, it relied on the Firebase Cloud Messaging (FCM),formerly known as Google Cloud Messaging (GCM), push service. This required using it's proprietary API. This allowed the Chrome to make the Web Push API available to developers at a time when the Web Push Protocol spec was still being written and later provided authentication (meaning the message sender is who they say they are) at a time when the Web Push Protocol lacked it. Good news: neither of these are true anymore.
FCM / GCM and Chrome now support the standard Web Push Protocol, while sender authentication can be achieved by implementing VAPID, meaning your web app no longer needs a 'gcm_sender_id'.
[https://developers.google.com/web/updates/2016/07/web-push-interop-wins#introducing_vapid_for_server_identification]
## 참조3
- VAPID를 사용하면 `FCM-specific steps` 을 진행하지 않아도 된다.
> Using VAPID also lets you avoid the FCM-specific steps for sending a push message. You no longer need a Firebase project, a gcm_sender_id, or an Authorization header(GCM 계정의 서버 아이디).[https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#working_with_data_payloads]
## GCM / FCM 용어
### 아래의 용어 사용하는 이유
> 42버전과 51버전 사이의 크롬은 구글 클라우드 메시징을 사용해 푸시 메시지를 구현하였고, 오페라와 삼성 브라우저도 같은 방법을 사용했다. 즉, 이전 버번의 브라우저에서도 푸시 알림이 작동하기바란다면 VAPID 키 이외에도 GCM API(gcm_sender_id) 키를 생성해야 한다.
### `GCMAPIKEY` = `GCM-API-KEY` = `GCM Server Key`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그리고 그 푸시를 `크롬`에 할경우 필요 했던 API 값. (`header`)
### `gcm_sender_id` = `GCM 발신자 ID`
예전에 `VAPID` 도입전에 GCM(FCM)을 사용하여 푸시를 할경우, 그 푸시가 `크롬이든 아니든` 간에 꼭 넣어 줘야 하는 값. (`manifest.json`)
## VAPID를 사용하여 subscription을 생성 하면 endpoint 가 바뀐다.
```js
// subscription 객체를 resolve하는 프로미스가 리턴된다.
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey // VAPID
})
```
- 이때 VAPID를 써서 만들어진 endpoint의 `origin`이 `fcm.googleapis.com`일지라도 이건 `FCM protocol`이 아니라 `Web Push Protocol` 이다.
>You'll know if it has worked by examining the endpoint in the resulting subscription object; if the origin is `fcm.googleapis.com`, it's working.
Even though this is an FCM URL, use the `Web Push Protocol` not the `FCM protocol`, this way your server-side code will work for any push service.[https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#the_web_push_protocol]
# Notification Permission
> 사용자가 Permision 에 동의 하지 않으면, 사용자에게 다시 Permision을 요청할 수 없습니다. (이 경우 permision 승인 결과를 반영 하려면 사용자가 browser의 설정에서 notification permission으 수동으로 변경해 주어야 합니다. ) 사용자가 permission을 결정하지 않은채로 tab을 닫으면, 나중에 다시 물을 수 있습니다. - 프로그레시브 웹 앱의 모든것 p.277 -
- 사용자가 x 버튼 3번 누르면 강제로 차단으로 변경
# ServiceWorkerRegistration.pushManager.subscribe & notification.requestpermission
- `ServiceWorkerRegistration.pushManage.subscribe` 메서드는 기본적으로 푸쉬 허용 여부가 없을때 `notification.requestpermission`을 호출한다.
>There is one side effect of calling subscribe(). If your web app doesn't have permissions for showing notifications at the time of calling subscribe(), the browser will request the permissions for you. This is useful if your UI works with this flow, but if you want more control (and I think most developers will), stick to the Notification.requestPermission() API that we used earlier.
[https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user#permissions_and_subscribe]
[https://stackoverflow.com/questions/46551259/what-is-the-correct-way-to-ask-for-a-users-permission-to-enable-web-push-notifi]
# Cache API
- `worker scope` 와 `window scope` 의 api 형태는 같지만 궁극적으로는 다른 거다.
> Do note that worker scope and standard window scope is not the same. There are some APIs missing (e.g. localStorage is not available). So self in the Service Worker is kind of like window in standard JS, but not exactly the same. [https://enux.pl/article/en/2018-05-05/pwa-and-http-caching], [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/caches]
# Notification API
- Cache와 마찬가지로 `worker scope` 와 `window scope` 의 api 형태는 같지만 궁극적으로는 다른 거다.
> In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications. [https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API#Service_worker_additions]
> ...앞에서 notification을 보여주기 위해 사용했던 'new Notification()' 이 아니라 service worker의 method인 showNotification을 사용한다. navigator.serviceWorker.ready를 통해 install되고 activation된 상태의 service worker인 swreg를 얻으면, swreg.showNotification을 사용할 수 있다. (pwa 웹 앱의 모든것 p.282)
# push service
>The term push service refers to a system that allows application servers(`우리 백엔드`) to send push messages to a webapp(`우리 프론트`). A push service serves the push endpoint or endpoints for the push subscriptions it serves.
The user agent connects to the push service used to create push subscriptions(`subscription을 생성함으로서` / `ServiceWorkerRegistration.pushManager.subscript()`). User agents MAY limit the choice of push services available. Reasons for doing so include performance-related concerns such as service availability (including whether services are blocked by firewalls in specific countries, or networks at workplaces and the like), reliability, impact on battery lifetime, and agreements to steer metadata to, or away from, specific push services. [https://www.w3.org/TR/push-api/#dfn-push-services\]
# end-point
> A push subscription has an associated push endpoint. It MUST be the absolute URL exposed by the push service where the application server can send push messages to. A push endpoint MUST uniquely identify the push subscription.
> 밀어 넣기 구독에는 연결된 밀어 넣기 끝 점이 있습니다. 응용 프로그램 서버가 푸시 메시지를 보낼 수있는 푸시 서비스에 의해 노출 된 절대 URL이어야합니다. 밀어 넣기 끝점은 밀어 넣기 구독을 고유하게 식별해야합니다.
[https://www.w3.org/TR/push-api/#dfn-push-endpoint]
# pwa 웹 앱의 모든것 책 중에서...
- p.273 부터 시작하는, 유저가 notification permission 을 허용했을때, `구독 되었습니다.` 라는 Notification은 `Normal javascript code` 또는 `service worker` 둘중 어디서든지 처리해도 상관 없다. 어자피 페이지가 있는 상태에서 유저가 permission 을 허용하고, 그에 대한 Notification 을 볼거니까
- p.317 에서 하는 구독된 push에 대한 Notification 은 `service worker` 에서만 실행 되어야 한다. 당연히..
# 지원현황
## service worker
- 모바일 환경 전부, 피시 크롬 (https://caniuse.com/#search=serviceworker)
## BeforeInstallPromptEvent(앱설치)
- 오직 크롬만 완벽히 지원하며, 삼성 인터넷의 경우 일부 지원 (https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent)
## push api
- 사파리 모바일/피시 안됨, 삼성 브라우저 됨 (https://caniuse.com/#search=push) *테스트 완료*
## notification api
- 사파리 모바일 /삼성브라우저 안됨 (https://caniuse.com/#search=notification) *테스트 완료*
- push api 에 대한 notification은 삼성브라우저에서 됨
-
## cache api
- MDN 에는 사파리 모바일 지원 안된다고 나옴(https://developer.mozilla.org/en-US/docs/Web/API/Cache)
- developers.google.com에서도 사파리는 지원 안된다고 나옴 (https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api)
- 테스트 하면 지원 함.
- isserviceworkerready에서는 지원 한다고 나옴 (https://jakearchibald.github.io/isserviceworkerready/index.html#moar)
- (https://love2dev.com/blog/what-browsers-support-service-workers/) 해당 문서에서는 2018년 3월에 IOS 11.3버전의 safari 13버전에서 `service-worker` `menifest` `cache` 를 지원 한다고 언급되어 있다.
# offline 환경 pwa 예시
- https://maxwellito.github.io/breaklock/
# pwa 예시
## 인스톨 & 오프라인
- app.starbucks.com
## 푸시
- https://housing.com/in/buy/real-estate-mumbai
# 단점
- 정적 파일이 변경될 때, service worker에서 캐쉬이름을 변경해줘야 된다.
- 모바일 디버깅이 힘들다
- 개발 환경 ( 테스트를 https:// 에서 진행해야 한다. )
# 확인해야 할거
- html 페이지와 sw.js 파일의 위치가 달라도 되는가?
# iso 버그
- ios에서 a 태그의 href 속성이 도메인 포함 이라면, 같은 scope 라 할지 하도 scope를 벗어난 것처럼 url 바가 생긴다.
- 태스트 결과 상대경로일경우에는 해당 이슈가 발생하지 않는다.
- 일치하지는 않으나 관련이슈로 (https://webcache.googleusercontent.com/search?q=cache:5paJXN_hqtkJ:https://forums.developer.apple.com/thread/123486+&cd=2&hl=ko&ct=clnk&gl=kr)<file_sep>
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': '182855395143'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// messaging.setBackgroundMessageHandler(function(payload) {
// console.log('[firebase-messaging-sw.js] Received background message ', payload);
// // Customize notification here
// // const notificationTitle = 'Background Message Title';
// const notificationTitle = payload.data.title;
// const notificationOptions = {
// body: 'Background Message body.',
// icon: '/firebase-logo.png',
// data:{
// url: payload.data.url
// }
// };
// return self.registration.showNotification(notificationTitle, notificationOptions);
// });
// self.addEventListener('notificationclick', function(event) {
// console.log('[Service Worker] Notification click Received.');
// event.notification.close();
// event.waitUntil(
// clients.openWindow(event.notification.data.url)
// );
// });
self.addEventListener('push', function (event) {
console.log('[Service Worker - sw.js] Push Received.');
// console.log(`[Service Worker - sw.js] Push had this data:`, event.data.json());
// console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
// const data = event.data.json().data;
const title = 'sw.js push';
const options = {
// body: `${data.body}`,
icon: `./promo/test/pwa/images/icon.png`,
// badge: `./promo/test/pwa/images/badge.png`,
// image: `./promo/test/pwa/images/bg.jpg`,
// data,
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
console.log('[Service Worker] evet.data: ', event.notification.data);
event.notification.close();
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
if (clientList.length > 0) {
clientList[0].navigate(event.notification.data.url)
clientList[0].focus();
return;
}
if (clients.openWindow) return clients.openWindow(event.notification.data.url);
}));
});
self.addEventListener('install', async () => {
console.log('skip waiting');
await self.skipWaiting();
});
self.addEventListener('pushsubscriptionchange', function() {
console.log('pushsubscriptionchange');
});<file_sep>class PushManager {
constructor() {
this.init();
this.firebase;
this.messaging;
}
init(){
let isFirebase = this.setFirebase();
if(!isFirebase) return false;
this.createMessaging();
this.bindingEvent();
// this.registerSw();
console.log(this.test);
}
bindingEvent(){
this.messaging.onTokenRefresh(this.onTokenRefresh);
this.messaging.onMessage(this.onMessage);
}
onMessage = (payload) => {
console.log('Message received. ', payload);
}
// firebase
setFirebase(){
if(!window.firebase){
console.error('firebase application이 로딩 되지 않았습니다.')
return false;
}
this.firebase = window.firebase;
return true;
}
// 파이어 페이스 메시지 인스턴스 생성
createMessaging(){
this.messaging = this.firebase.messaging();
}
registerSw(){
navigator.serviceWorker.register('/sw.js', {scope:'/firebase-cloud-messaging-push-scope'})
.then((registration) => {
// registration.update();
// this.messaging.getToken();
console.log(registration);
registration.onupdatefound = ()=>{
console.log('need update');
}
this.messaging.useServiceWorker(registration);
});
}
// 알림 수락 요청 레이아웃 출력
requestSubscribe(){
// 노티 거부 / 노티 수락 이면 알림 수락 요청 레이아웃을 출력하지도 않는다.
// if(Notification.permission === 'denied' || Notification.permission === 'granted') return false;
if(Notification.permission === 'denied' ) return false;
let isSubscribe = confirm(this.subscribeRequestText);
if(!isSubscribe){
return false;
}else{
this.requestSubscribeFinal();
}
}
// 알림 수락 요청 (시스템)
requestSubscribeFinal(){
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
this.subscribPermit()
} else {
console.log('Unable to get permission to notify.');
this.subscribDiny()
}
});
}
// 알림 수락 콜백
subscribPermit(){
this.messaging.getToken().then((currentToken) => {
if (currentToken) {
this.sendTokenToServer(currentToken);
alert('알림을 설정하셨습니다.')
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
onTokenRefresh = () => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// ...
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
}
// 알림 거부 콜맥
subscribDiny(){
alert('알림을 거부 하셨습니다.')
}
// 서버 전송
sendTokenToServer(currentToken){
console.log('sendTokenToServer', currentToken)
}
// 포그라운드 알림 수신
};
let pushManager = new PushManager();<file_sep>import PushManager from './PushManager';
function init() {
window.pushManager = new PushManager();
}
init();<file_sep># PWA
PWA란 무엇이며 실제로 적용한 예시에 대한 내용
## 1) PWA 란
- PWA란 Progressive Web Application의 약자로 `웹 어플리케이션`을 점진적 향상 시켜 `웹 어플리케이션`과 `네이티브 어플리케이션`의 이점을 모두 갖게 하는 것을 말한다.
- `웹 앱`을 향상시킬 수 있는 기술에는 아래와 같은 것들이 있다.
- 보안 강화를 위한 `https` 적용.
- `웹 앱`의 인스톨 기능
- 디바이스 크기에 따른 `반응형 웹` 디자인
- 디바이스의 `GPS` 기능
- `push` 알림 기능
- 디바이스의 `카메라` 기능 사용
- 속도의 개선 (`오프라인 환경`, `캐쉬`)
- 백그라운드 동기화
- 이론적으로 이미 많은 `웹 앱` 들이 `https`, `반응형`등을 사용 함으로서 PWA를 적용하고 있다고 볼 수 있다.
- 단, 지금은 PWA의 기술들 중 `push`기능과 `install`기능, 그리고 직접 다루지는 않겠지만 속도 개선을 위한 `캐쉬` 기능에 대해 중점으로 살펴 본다.
## 2) PWA를 위한 기술
- `push`기능과 `install`기능, 그리고 `캐쉬` 기능 등을 사용하기 위해 필요한 핵심 `기술`에는 `Service worker` 와 `Manifest` 두가지 가 있다.
### (1) Service worker
- `브라우저` 와 `네트워크` 사이에있는 프록시 서버역할을 한다.
- ( `[브라우저]` <---> `[Service worker]` <---> `[네트워크]` )
- 서비스 워커는 자신이 제어하는 페이지에서 발생하는 이벤트를 수신한다. 웹에서 서버에 네트워크를 통해 파일을 요청하는 것과 같은 이벤트를 가로채거나 수정하고 다시 페이지로 돌려보낼 수 있다.
- `푸시 알림` 및 `백그라운드 동기화` API에 대한 액세스를 허용 한다.
- 각각의 Serivce worker 는 그 Service worker의 기능을 사용할 수 있는 `Scope`를 가지고 있다.
- 즉, 도메인 마다 고유의 `Serivce worker`를 가질 수 있고, 심지어 `Depth`마다 고유의 `Serivce worker`를 가질 수 있다.
- `Service Worker`는 반드시 `ssl` 즉, `https` 프로토콜 환경에서만 동작을 하고,
- 예외로 `localhost://` 프로토콜 환경에서도 작동을 한다.
- `127.0.0.1` 등의 프로토콜도 동작하나, 임의로 변경한 host인 `local.test://` 등에서는 동작 하지 않는 것으로 확인 하였다.
- 각 `Device`안의 각 `Navigator`에 종속되어 설치 된다.
- 즉, 같은 기기라고 하더라고 브라우저 마다 다른 `Service worker`가 설치된다.
- 자세한 내용은 링크 참조 : [[구글 Developers]](https://developers.google.com/web/fundamentals/primers/service-workers/?hl=ko), [[MDN]](https://developer.mozilla.org/ko/docs/Web/API/Service_Worker_API),
### (2) Manifest.json
- `웹 앱`을 `인스톨` 하기 위한 파일이다.
- 이름, 작성자, 아이콘, 버전, 설명 및 필요한 모든 리소스 목록이 포함된다.
- `인스톨` 기능과는 별개로 `GCM(Google Cloude Message)`을 위한 `gcm_sender_id` 값이 들어가는 경우도 있다. (`gcm_sender_id`는 현재 필요하지 않다. )
- 자세한 내용은 링크 참조 : [[MDN]](https://developer.mozilla.org/en-US/docs/Web/Manifest), [[MDN(2)]](https://developer.mozilla.org/ko/docs/Web/Progressive_web_apps/Installable_PWAs), [[구글 Developers]](https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/?hl=ko)
<file_sep>self.addEventListener('install', async () => {
console.log('skip waiting');
await self.skipWaiting();
});
self.addEventListener('push', function (event) {
console.log('[Service Worker] Push Received.', event);
const title = 'test title';
const options = {
body: 'test push',
// icon: './images/icon.png',
// badge: './promo/test/pwa/images/badge.png',
// image: './promo/test/pwa/images/bg.jpg',
data: {
url: './'
},
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.', event.notification);
event.notification.close();
event.waitUntil(clients.matchAll({
type: 'window'
}).then(function (clientList) {
if (clientList.length > 0) {
clientList[0].navigate(event.notification.data.url);
clientList[0].focus();
return;
}
if (clients.openWindow) return clients.openWindow(event.notification.data.url);
}));
});
<file_sep># APP INSTALL
1. 개요
3. TIP & TEST
4. 실제 적용한 내용
1. Friebase Cloude Message
2. service_worker.js
3. manifest.json
4. ICON 이미지 위치
5. 적용 방법
<file_sep>// const webpush = require('web-push');
// // VAPID keys should only be generated only once.
// // const vapidKeys = webpush.generateVAPIDKeys();
// webpush.setGCMAPIKey('<Your GCM API Key Here>');
// webpush.setVapidDetails(
// 'mailto:<EMAIL>',
// 'BOCHoU_Ym8vKG5mjwIVzNTThP_rpcjrI7C2liL3sYhGpAt-leD9V3-ggUaItj5guFW5m5JEwremfCnt_pt2JIrE',
// 'vS5NkdSrlnucWS_hT2I8qqW2MYNvqdlLyCLjeUBvapk'
// );
// // This is the same output of calling JSON.stringify on a PushSubscription
// const pushSubscription = {
// endpoint: 'https://updates.push.services.mozilla.com/wpush/v2/gAAAAABda4OfjEJwoewCpfifOXhSbNf8RKDmMnE7nmtZ8UZ1YxNet5NAiYOrJzOpuQBOCsXO2NGHPQ7bFlUFLdsC1t5Ldv2cL1DM0xa0WXftjd3jq9DDpc_efAEvFRs9sAB0UEV27b6JSyifTJX3cjQMi62Ql3pSELbBBcTV8yMKuPesErWtCZU',
// keys: {
// auth: '<KEY>',
// p256dh: '<KEY>'
// }
// };
// webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
const webpush = require('web-push');
// VAPID keys should only be generated only once.
// const vapidKeys = webpush.generateVAPIDKeys();
// webpush.setGCMAPIKey('<Your GCM API Key Here>');
webpush.setVapidDetails(
'mailto:<EMAIL>',
'BOCHoU_Ym8vKG5mjwIVzNTThP_rpcjrI7C2liL3sYhGpAt-leD9V3-ggUaItj5guFW5m5JEwremfCnt_pt2JIrE',
'vS5NkdSrlnucWS_hT2I8qqW2MYNvqdlLyCLjeUBvapk'
);
// This is the same output of calling JSON.stringify on a PushSubscription
const pushSubscription = {
endpoint: "https://fcm.googleapis.com/fcm/send/fJMn7F-TNJw:APA91bHpCaad<KEY>",
keys: {
auth: "<KEY>",
p256dh: "<KEY>"
}
};
webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
|
b6b94ce8f585163b2f83a2288885312fac413efe
|
[
"JavaScript",
"Markdown"
] | 21
|
JavaScript
|
CressZZ/pwa
|
22b3c321fc6eec6e99ea6554e83fb64196e758eb
|
ef85047c447a99ca296599f5ae510ead3f78df89
|
refs/heads/master
|
<repo_name>liranDev/python-repository<file_sep>/mongo/src/core/dbapi.py
import abc
import logging
import os
import settings
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
filename=os.path.join(settings.__BASE_PATH__, r'log\logger.log')
)
logger = logging.getLogger(__name__)
logging.info('--- Start Logging ---')
try:
import pymongo
logging.info('pymongo imported')
except ImportError as ex:
logging.error('failed importing pymongo ', exc_info=True)
raise 'pymongo does not exists'
class DBAPI:
__metaclass__ = abc.ABCMeta
def __init__(self):
self.mongo = None
self.conn = None
@abc.abstractmethod
def connecto(self):
''' connects to mongo '''
@abc.abstractmethod
def insert(self, collecion, data):
''' insert data into collection '''
class MongoDBAPI(DBAPI):
def __init__(self):
pass
mongo = MongoDBAPI()
<file_sep>/mongo/src/settings.py
import os
__BASE_PATH__ = os.path.realpath('..')
|
a9469ffe2a86532b05f7b1d6f43f2b1532787907
|
[
"Python"
] | 2
|
Python
|
liranDev/python-repository
|
a754a2c456ad1c93bf213655a49e71c11fe9f873
|
b91a6f51b3b84ae8f91e1331675ac779a1e9f7eb
|
refs/heads/master
|
<repo_name>Jayser/angular2-intensive<file_sep>/typings/app/container/container.ts
const FIRST_ITEM = 0;
export default class Container {
storage = [];
add(item) {
this.storage.push(item);
return true;
}
remove(idx, items) {
const oldStorageLength = this.storage.length;
this.storage.splice(idx, items);
return oldStorageLength !== this.storage.length;
}
findIndex(query) {
return this.storage.indexOf(query);
}
clear() {
this.storage.length = 0;
return true;
}
getFirstItem() {
return this.storage[FIRST_ITEM];
}
getLastItem(): any {
const LAST_ITEM = this.storage.length - 1;
return this.storage[LAST_ITEM];
}
getLength(): number {
return this.storage.length;
}
isEmpty(): boolean {
return Boolean(!this.storage.length);
}
}
<file_sep>/typescript/example-1/shapeFactory.ts
/*
* Задание №2.
*
* Создать абстрактный класс Printable – базовый класс для всех сущностей, информацию о которых можно представить (распечатать) в виде строки (std::string).
* Создать класс Named – наследник Printable – базовый класс для всех сущностей, которые имеют имя. Строка с именем без default-значения передаётся в единственный конструктор.
* Создать абстрактный класс Shape – наследник Printable – базовый класс для фигур на декартовой плоскости.
*
* Спроектировать и реализовать иерархию классов конкретных именованных фигур:
*
* Point - точка,
* Circle - окружность,
* Rect - прямоугольник со сторонами, параллельными OX и OY (с помощью двух точек),
* Square - прямоугольник с одинаковыми сторонами,
* Polyline - ломаная; должна быть реализована с помощью Container< Point >, наполняться с помощью метода AddPoint( Point const & point ),
* Polygon - произвольный многоугольник.
*
* С помощью статического метода Shape::GetCount() реализовать возможность узнать, сколько существует экземпляров Shape (т.е. любых фигур) в данный момент.
* У каждой фигуры в качестве текстовой информации должна печататься содержательная информация, например, у точки есть координаты, у окружности ещё есть радиус и площадь, у ломаной - длина и т.п.
* Необходимо реализовать также и вывод информации о каждом объекте в стандартный поток вывода std::ostream с помощью оператора std::ostream & operator << ( std::ostream & ioStream, ... );
*
* Реализовать фабрику фигур, которая умеет создавать конкретную фигуру заданного типа со случайными параметрами.
*
*/
abstract class Printable {
print(): void {
console.log(`Shape => ${this.toString()}`);
};
}
class Named extends Printable {
constructor(public name: string) {
super();
}
toString() {
return this.name;
}
}
export abstract class Shape extends Printable {
private static count: number = 0;
constructor() {
super();
Shape.count++;
}
get count() {
return Shape.count;
}
}
class Point extends Shape {
constructor(public x: number = 0, public y: number = 0) {
super();
}
toString() {
console.info(`Point coordinates: x = ${this.x}, y = ${this.y}`);
}
}
class Circle extends Shape {
constructor(public p1?: Point, public p2?: Point) {
super();
}
toString() {
console.info(`Circle coordinates: p1 = { x: ${this.p1.x}, y: ${this.p1.y} }, p2 = { x: ${this.p2.x}, y: ${this.p2.y} }`);
}
}
function randomRange(min: number = 0, max: number = 100): number {
return Math.random() * (max - min) + min;
}
export function shapeFactory(shape: string): Shape {
switch (shape) {
case 'point': return new Point(randomRange(), randomRange());
case 'circle': return new Circle(new Point(randomRange()), new Point(randomRange()));
default: throw new Error('can\'t find the shape');
}
}<file_sep>/typings/app/index.ts
import Container from "./container/container";
const container = new Container();
console.log(container.add("str"));
<file_sep>/typings/app/container/container.d.ts
declare class Container {
storage: any[];
add(item: string): boolean;
remove(idx: number, count: number): boolean;
findIndex(query: string): number;
clear(): boolean;
firstItem(): any;
lastItem(): any;
length(): number;
isEmpty(): boolean;
}
export = Container;<file_sep>/typescript/example-1/container.ts
/*
* Задание №1.
*
* Спроектировать и реализовать шаблонный класс Container со следующими возможностями:
* - добавить новый элемент в начало/конец;
* - удалить первый/последний элемент;
* - получить значение первого/последнего элемента;
* - перебрать все элементы (не обязательно делать итератор);
* - узнать кол-во элементов;
* - проверить на пустоту;
* - очистить.
*
* Класс должен быть эффективным и универсальным (должен подходить для хранения экземпляров любых типов и использования где угодно).
* Для тех, кто в танке: не надо реализовывать Container с помощью какого-либо готового контейнера.
*
*/
const FIRST_ITEM = 0;
const COUNT_ITEMS = 1;
export default class Container<T> {
private storage: T[] = [];
[Symbol.iterator]() {
return this.storage[Symbol.iterator]();
}
add(item: T) {
this.storage.push(item);
return true;
}
remove(idx: number): boolean {
const oldStorageLength = this.storage.length;
this.storage.splice(idx, COUNT_ITEMS);
return oldStorageLength !== this.storage.length;
}
find(query: T): number {
return this.storage.indexOf(query);
}
clear(): boolean {
this.storage.length = 0;
return true
}
get first(): any {
return this.storage[FIRST_ITEM];
}
get last(): T {
const LAST_ITEM = this.storage.length - 1;
return this.storage[LAST_ITEM];
}
get length(): number {
return this.storage.length;
}
isEmpty(): boolean {
return Boolean(!this.storage.length);
}
}<file_sep>/typescript/example-1/index.ts
/*
* Задание №1.
*
* Спроектировать и реализовать шаблонный класс Container со следующими возможностями:
* - добавить новый элемент в начало/конец;
* - удалить первый/последний элемент;
* - получить значение первого/последнего элемента;
* - перебрать все элементы (не обязательно делать итератор);
* - узнать кол-во элементов;
* - проверить на пустоту;
* - очистить.
*
* Класс должен быть эффективным и универсальным (должен подходить для хранения экземпляров любых типов и использования где угодно).
* Для тех, кто в танке: не надо реализовывать Container с помощью какого-либо готового контейнера.
*
*/
const FIRST_ITEM = 0;
const COUNT_ITEMS = 1;
class Container<T> {
private storage: T[] = [];
[Symbol.iterator]() {
return this.storage[Symbol.iterator]();
}
add(item: T): boolean {
this.storage.push(item);
return true;
}
remove(idx: number): boolean {
const oldStorageLength = this.storage.length;
this.storage.splice(idx, COUNT_ITEMS);
return oldStorageLength !== this.storage.length;
}
find(query: T): number {
return this.storage.indexOf(query);
}
clear(): boolean {
this.storage.length = 0;
return true
}
get first(): any {
return this.storage[FIRST_ITEM];
}
get last(): T {
const LAST_ITEM = this.storage.length - 1;
return this.storage[LAST_ITEM];
}
get length(): number {
return this.storage.length;
}
isEmpty(): boolean {
return Boolean(!this.storage.length);
}
}
/*
* Задание №2.
*
* Создать абстрактный класс Printable – базовый класс для всех сущностей, информацию о которых можно представить (распечатать) в виде строки (std::string).
* Создать класс Named – наследник Printable – базовый класс для всех сущностей, которые имеют имя. Строка с именем без default-значения передаётся в единственный конструктор.
* Создать абстрактный класс Shape – наследник Printable – базовый класс для фигур на декартовой плоскости.
*
* Спроектировать и реализовать иерархию классов конкретных именованных фигур:
*
* Point - точка,
* Circle - окружность,
* Rect - прямоугольник со сторонами, параллельными OX и OY (с помощью двух точек),
* Square - прямоугольник с одинаковыми сторонами,
* Polyline - ломаная; должна быть реализована с помощью Container< Point >, наполняться с помощью метода AddPoint( Point const & point ),
* Polygon - произвольный многоугольник.
*
* С помощью статического метода Shape::GetCount() реализовать возможность узнать, сколько существует экземпляров Shape (т.е. любых фигур) в данный момент.
* У каждой фигуры в качестве текстовой информации должна печататься содержательная информация, например, у точки есть координаты, у окружности ещё есть радиус и площадь, у ломаной - длина и т.п.
* Необходимо реализовать также и вывод информации о каждом объекте в стандартный поток вывода std::ostream с помощью оператора std::ostream & operator << ( std::ostream & ioStream, ... );
*
* Реализовать фабрику фигур, которая умеет создавать конкретную фигуру заданного типа со случайными параметрами.
*
*/
abstract class Printable {
print(): void {
console.log(`Shape => ${this.toString()}`);
};
}
abstract class Shape extends Printable {
private static count: number = 0;
constructor() {
super();
Shape.count++;
}
static destroy() {
Shape.count--;
};
static getCount() {
return Shape.count;
}
}
class Point extends Shape {
constructor(public x: number = 0, public y: number = 0) {
super();
}
destroy() {
Shape.destroy();
}
toString(): string {
return `Point coordinates: x = ${this.x}, y = ${this.y}`;
}
}
class Circle extends Shape {
constructor(public p1: Point, public p2: Point) {
super();
}
destroy() {
this.p1.destroy();
this.p2.destroy();
Shape.destroy();
}
toString(): string {
return `Circle coordinates: p1 = { x: ${this.p1.x}, y: ${this.p1.y} }, p2 = { x: ${this.p2.x}, y: ${this.p2.y} }`;
}
}
function randomRange(min: number = 0, max: number = 100): number {
return Math.floor(Math.random() * (max - min) + min);
}
function shapeFactory(shape: string): Shape {
switch (shape) {
case 'point': return new Point(randomRange(), randomRange());
case 'circle': return new Circle(new Point(randomRange(), randomRange()), new Point(randomRange(), randomRange()));
default: throw new Error('can\'t find the shape');
}
}
/*
* Usage
*/
const storage = new Container<Shape>();
storage.add(shapeFactory('point'));
storage.add(shapeFactory('circle'));
console.log(storage);
for (let shape of storage) {
shape.print();
}
|
b9652bc383561cbb863e25aa72548b531264ed47
|
[
"TypeScript"
] | 6
|
TypeScript
|
Jayser/angular2-intensive
|
037949fe0b89cb26eb98c435600bdba764877de5
|
a11dbb89fbf6ced66657711554bfe8cee8ebc478
|
refs/heads/master
|
<repo_name>Michelangelo-Foschi/Checking-Stock-Prices-with-Python-in-10-lines-of-code-<file_sep>/code.py
import requests
from bs4 import BeautifulSoup
def check_price():
url = 'https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch'
get_url_response = requests.get(url)
parse_response = BeautifulSoup(get_url_response.text, 'lxml')
price = parse_response.find_all('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
print(price)
while True:
check_price()
<file_sep>/README.md
# Checking-Stock-Prices-with-Python-in-10-lines-of-code-
Nowadays it’s important to keep on checking the stock prices. Some people make millions of dollars out of stocks. So today, let’s handle the topic “Stock Prices” and let’s see how we can check them using python.
## **Importing Packages**
``` python
import requests
from bs4 import BeautifulSoup
```
- “Requests” is needed so that we can retrieve pieces of information from websites
- BeautifulSoup is needed so that we can parse HTML and XML documents
## **Check_Price function**
- Let’s find a URL for any companies stock price. I prefer to use yahoo finance while working on these projects.
- We are asking “requests” to retrieve all data from our URL
- Then we parse that data with BeautifulSoup
``` python
def check_price():
url = 'https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch'
get_url_response = requests.get(url)
parse_response = BeautifulSoup(get_url_response.text, 'lxml')
price = parse_response.find_all('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
print(price)
```
### Notice: In the variable price your ‘class’ might be different. Use your inspect element function to figure out your ‘class’.
## **Calling our function**
```python
while True:
check_price()
```
- We are using "while True", so that we get updated stock prices!
# **End**
- Thanks for checking out my story on how to check stock prices using Python. Hopefully, you gained some knowledge and good luck with your stocks ;)
Also check out my medium: https://medium.com/@michelangelo.foschi.10
|
aea67348eac7919793c0b098300fb03b325594af
|
[
"Markdown",
"Python"
] | 2
|
Python
|
Michelangelo-Foschi/Checking-Stock-Prices-with-Python-in-10-lines-of-code-
|
90c3d1b9f48cc6189c97c61bea300fdda4be201e
|
92d7242cf846cdce1a64e7cbb590d09ea39bddab
|
refs/heads/master
|
<repo_name>fmarcio/Bolters-PortalDeCorrida<file_sep>/README.md
# Bolters - Portal de Corrida / Running portal :computer:
## English
Website project: portal dedicated to people who practice running. :running:
Languages/technologies used: HTML, CSS and Javascript. The whole project is responsive.
**Check the project page** [here](https://fmarcio.github.io/Bolters-PortalDeCorrida/)
## Português
Portal dedicado às pessoas que praticam corrida. :running:
Linguagens/tecnologias usadas: HTML, CSS and Javascript. Todo o projeto é responsivo.
**Confira como ficou o projeto** [aqui](https://fmarcio.github.io/Bolters-PortalDeCorrida/)
## Social Media / Redes Sociais
### Linkedin
[Linkedin](https://www.linkedin.com/in/marciofonseca88/)
### Behance
[Behance](https://www.behance.net/marcio-fonseca)
<file_sep>/script-login.js
//Select form and inputs
const form = document.getElementById('form');
const email = document.getElementById('email');
const password = document.getElementById('password');
//FUNÇÕES
//Show error (red border)
function showError(input, message) {
//select input parent element (form-item)
const formItem = input.parentElement;
//add the class "erro" on the ipt parent element (form-item)
formItem.className = 'form-item erro';
//select small tag
const small = formItem.querySelector('small');
small.innerText = message;
}
//Show success (green border)
function showSuccess(input) {
const formItem = input.parentElement;
formItem.className = 'form-item sucesso';
}
//check if email is valid
function checkEmail(input) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
}
else {
showError(input, 'E-mail inválido');
}
}
//Pick the first letter of input IDs and uppercase them. Rest of the letters remain lowercase
function pickFirstLetterIpt(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
//Check required inputs
function checkRequired(inputArr) {
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${pickFirstLetterIpt(input)} é necessário(a)`);
}
else {
showSuccess(input);
}
});
}
//check inputs length
function checkLength(input, min, max) {
if (input.value.length < min) {
showError(input,
`${(pickFirstLetterIpt(input))} deve ter no mínimo ${min} caracteres`
);
}
else if (input.value.length > max) {
showError(input,
`${(pickFirstLetterIpt(input))} deve ter menos do que ${max} caracteres`
);
}
else {
showSuccess(input);
}
}
//EVENT LISTENER
form.addEventListener('submit', function(e) {
e.preventDefault();
//push inputs an an array to avoid repetition
checkRequired([email, password]);
checkLength(password, 5, 15);
checkEmail(email);
});<file_sep>/script.js
//HAMBURGER MENU
const btn = document.getElementById('btn-menu');
const linksContainer = document.querySelector('nav ul');
btn.addEventListener('click', () => {
linksContainer.classList.toggle('active-menu');
})
//PANELS
const panels = document.querySelectorAll('.panel');
//querySelectorAll returns a nodeList. So I can iterate each element with forEach
panels.forEach((panel) => {
panel.addEventListener('click', () => {
panel.classList.toggle('active');
})
})
//SLIDESHOW
const slides = document.querySelectorAll('.slide');
const next = document.querySelector('#next');
const prev = document.querySelector('#prev');
const auto = true;
const intervalTime = 4000;
let slideInterval;
const nextSlide = () => {
//select current class
const current = document.querySelector('.current');
//remove current class
current.classList.remove('current');
//check for next slide
if (current.nextElementSibling) {
//add current to next sibling
current.nextElementSibling.classList.add('current');
} else {
//add current to start
slides[0].classList.add('current');
}
setTimeout(() => {
current.classList.remove('current');
})
}
const prevSlide = () => {
//select current class
const current = document.querySelector('.current');
//remove current class
current.classList.remove('current');
//check for previous slide
if (current.previousElementSibling) {
//add current to next sibling
current.previousElementSibling.classList.add('current');
} else {
//add current to last
slides[slides.length - 1].classList.add('current');
}
setTimeout(() => {
current.classList.remove('current');
})
}
//button events
next.addEventListener('click', () => {
nextSlide();
if (auto) {
clearInterval(slideInterval);
slideInterval = setInterval(nextSlide, intervalTime);
}
})
prev.addEventListener('click', () => {
prevSlide();
if (auto) {
clearInterval(slideInterval);
slideInterval = setInterval(nextSlide, intervalTime);
}
})
//auto slide
if (auto) {
//run next slide at interval time
slideInterval = setInterval(nextSlide, intervalTime);
}
|
1b52cba69b42925f6f3e405b20f4cd835ffc5f82
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
fmarcio/Bolters-PortalDeCorrida
|
4412074e8872ae6c67b0b2b8c9c7f94588b4d483
|
a63e13d4736020cfdd3aca1a56d71569569a967c
|
refs/heads/master
|
<file_sep><?php
namespace Rheck\EntityDatesBehaviorBundle\Annotation;
use Doctrine\Common\Annotations\Annotation;
/**
* @Annotation
*/
class Updatable
{
public $type = 'datetime';
}
<file_sep><?php
namespace Rheck\EntityDatesBehaviorBundle\Service;
class EntityDatesService
{
public function insertCreatable($entity, $reflectionProperty, $type)
{
$reflectionProperty->setAccessible(true);
$createdValue = $reflectionProperty->getValue($entity);
if (is_null($createdValue)) {
$reflectionProperty->setValue($entity, $this->getValueByType($type));
}
}
public function insertUpdatable($entity, $reflectionProperty, $type)
{
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($entity, $this->getValueByType($type));
}
protected function getValueByType($type)
{
$value = new \DateTime();
switch ($type) {
case 'datetime':
case 'date':
break;
case 'timestamp':
case 'integer':
$value = $value->getTimestamp();
break;
default:
$value = null;
}
return $value;
}
}
<file_sep><?php
namespace Rheck\EntityDatesBehaviorBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class RheckEntityDatesBehaviorBundle extends Bundle
{
}<file_sep>entitydatesbehavior-bundle
==========================
Bundle as manage the values of createdAt and updatedAt fields of an entity when update or persist was executed.
<file_sep><?php
namespace Rheck\EntityDatesBehaviorBundle\Listener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Rheck\EntityDatesBehaviorBundle\Annotation\Driver\EntityReader;
class EntityLifecycleListener
{
protected $entityReader;
public function __construct(EntityReader $entityReader)
{
$this->entityReader = $entityReader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->entityReader->readEntity($entity);
}
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->entityReader->readEntity($entity);
}
}
<file_sep><?php
namespace Rheck\EntityDatesBehaviorBundle\Annotation\Driver;
use Rheck\EntityDatesBehaviorBundle\Service\EntityDatesService;
use Rheck\EntityDatesBehaviorBundle\Annotation\Creatable;
use Rheck\EntityDatesBehaviorBundle\Annotation\Updatable;
use Doctrine\Common\Annotations\Reader;
class EntityReader
{
protected $reader;
protected $entityDatesService;
public function __construct(Reader $reader, EntityDatesService $entityDatesService)
{
$this->reader = $reader;
$this->entityDatesService = $entityDatesService;
}
public function readEntity($entity)
{
$reflObject = new \ReflectionObject($entity);
$reflProperties = $reflObject->getProperties();
foreach ($reflProperties as $reflProperty) {
foreach ($this->reader->getPropertyAnnotations($reflProperty) as $annotationProperty) {
if ($annotationProperty instanceof Creatable) {
$this->entityDatesService->insertCreatable($entity, $reflProperty, $annotationProperty->type);
} elseif ($annotationProperty instanceof Updatable) {
$this->entityDatesService->insertUpdatable($entity, $reflProperty, $annotationProperty->type);
}
}
}
}
}
|
7fe5dbeaf5e27f4d1b21aaa0e3475277b49346b7
|
[
"Markdown",
"PHP"
] | 6
|
PHP
|
rheck/entitydatesbehavior-bundle
|
c6d36ceadf15718986006816e7a6f9c97b49b124
|
46acfbb75aa87f4681367e615103434d5be33ce8
|
refs/heads/master
|
<repo_name>julcia106/Copier<file_sep>/Zadanie3/Printer.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Zadanie3
{
public class Printer : IPrinter
{
protected IDevice.State state = IDevice.State.on;
public IDevice.State GetState() => state;
public int Counter { get; private set; } = 0;
public int PrintCounter { get; private set; } = 0;
public void PowerOff()
{
state = IDevice.State.off;
}
public void PowerOn()
{
state = IDevice.State.on;
}
public void Print(in IDocument doc1)
{
if (GetState() == IDevice.State.on)
{
DateTime dateTime = DateTime.Now;
Console.WriteLine(dateTime.ToString() + " Print: " + doc1.GetFileName());
PrintCounter++;
}
else
throw new Exception("The copier is turned off.");
}
}
}
<file_sep>/Zadanie3/Program.cs
using System;
using System.Collections;
using System.Collections.Generic;
namespace Zadanie3
{
class Program
{
static void Main(string[] args)
{
var xerox = new Copier();
xerox.PowerOn();
xerox.PowerOff();
xerox.PowerOn();
Console.WriteLine(xerox.GetState());
IDocument doc1 = new PDFDocument("aaa.pdf");
xerox.Print(in doc1);
IDocument doc2, doc3, doc4, doc5;
xerox.Scan(out doc2, IDocument.FormatType.JPG);
xerox.Scan(out doc3, IDocument.FormatType.TXT);
xerox.Scan(out doc4, IDocument.FormatType.PDF);
xerox.Scan(out doc5);
Console.WriteLine("Scan and print: ");
xerox.ScanAndPrint();
}
}
}
<file_sep>/Zadanie2/MultifunctionalDevice.cs
using System;
using Zadanie1;
namespace Zadanie2
{
public interface IFax : IDevice
{
/// <summary>
/// Dokument jest wysyłany, jeśli urządzenie włączone. W przeciwnym przypadku nic się nie wykonuje
/// </summary>
/// <param name="document">obiekt typu IDocument, różny od `null`</param>
/// <param name="nameOfDevice">obiekt typu string, adres odbiorcy</param>
void Send(in IDocument document, string nameOfDevice);
}
public class MultifunctionalDevice : Copier, IFax
{
public void Send(in IDocument document, string nameOfDevice)
{
if (GetState() == IDevice.State.on)
{
Console.WriteLine("The file named " + document.GetFileName() + "has been sent to the device named: " + nameOfDevice);
}
else
throw new Exception("The multifunctional device is turned off.");
}
}
}
<file_sep>/Zadanie2UnitTests/UnitTest2.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using ver1UnitTests;
using Zadanie1;
using Zadanie2;
namespace Zadanie2UnitTests
{
[TestClass]
public class UnitTest2
{
[TestMethod]
public void MFD_GetState_StateOff()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOff();
Assert.AreEqual(IDevice.State.off, device.GetState());
}
[TestMethod]
public void MFD_GetState_StateOn()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
Assert.AreEqual(IDevice.State.on, device.GetState());
}
// weryfikacja, czy po wywołaniu metody `Send` i włączonym urządzeniu wielofunkcyjnym w napisie pojawia się słowo `sent`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_Send_DeviceOn()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1 = new PDFDocument("aaa.pdf");
device.Send(doc1, "<EMAIL>");
Assert.IsTrue(consoleOutput.GetOutput().Contains("sent"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `Print` i włączonej kopiarce w napisie pojawia się słowo `Print`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_Print_DeviceOn()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1 = new PDFDocument("aaa.pdf");
device.Print(in doc1);
Assert.IsTrue(consoleOutput.GetOutput().Contains("Print"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `Print` i wyłączonej kopiarce w napisie NIE pojawia się słowo `Print`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_Print_DeviceOff()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOff();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1 = new PDFDocument("aaa.pdf");
device.Print(in doc1);
Assert.IsFalse(consoleOutput.GetOutput().Contains("Print"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `Scan` i wyłączonej kopiarce w napisie NIE pojawia się słowo `Scan`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void Copier_Scan_DeviceOff()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOff();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1;
device.Scan(out doc1);
Assert.IsFalse(consoleOutput.GetOutput().Contains("Scan"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `Scan` i wyłączonej kopiarce w napisie pojawia się słowo `Scan`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_Scan_DeviceOn()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1;
device.Scan(out doc1);
Assert.IsTrue(consoleOutput.GetOutput().Contains("Scan"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy wywołanie metody `Scan` z parametrem określającym format dokumentu
// zawiera odpowiednie rozszerzenie (`.jpg`, `.txt`, `.pdf`)
[TestMethod]
public void MFD_Scan_FormatTypeDocument()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
IDocument doc1;
device.Scan(out doc1, formatType: IDocument.FormatType.JPG);
Assert.IsTrue(consoleOutput.GetOutput().Contains("Scan"));
Assert.IsTrue(consoleOutput.GetOutput().Contains(".jpg"));
device.Scan(out doc1, formatType: IDocument.FormatType.TXT);
Assert.IsTrue(consoleOutput.GetOutput().Contains("Scan"));
Assert.IsTrue(consoleOutput.GetOutput().Contains(".txt"));
device.Scan(out doc1, formatType: IDocument.FormatType.PDF);
Assert.IsTrue(consoleOutput.GetOutput().Contains("Scan"));
Assert.IsTrue(consoleOutput.GetOutput().Contains(".pdf"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `ScanAndPrint` i wyłączonej kopiarce w napisie pojawiają się słowa `Print`
// oraz `Scan`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_ScanAndPrint_DeviceOn()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
device.ScanAndPrint();
Assert.IsTrue(consoleOutput.GetOutput().Contains("Scan"));
Assert.IsTrue(consoleOutput.GetOutput().Contains("Print"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
// weryfikacja, czy po wywołaniu metody `ScanAndPrint` i wyłączonej kopiarce w napisie NIE pojawia się słowo `Print`
// ani słowo `Scan`
// wymagane przekierowanie konsoli do strumienia StringWriter
[TestMethod]
public void MFD_ScanAndPrint_DeviceOff()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOff();
var currentConsoleOut = Console.Out;
currentConsoleOut.Flush();
using (var consoleOutput = new ConsoleRedirectionToStringWriter())
{
device.ScanAndPrint();
Assert.IsFalse(consoleOutput.GetOutput().Contains("Scan"));
Assert.IsFalse(consoleOutput.GetOutput().Contains("Print"));
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
[TestMethod]
public void MFD_PrintCounter()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
IDocument doc1 = new PDFDocument("aaa.pdf");
device.Print(in doc1);
IDocument doc2 = new TextDocument("aaa.txt");
device.Print(in doc2);
IDocument doc3 = new ImageDocument("aaa.jpg");
device.Print(in doc3);
device.PowerOff();
device.Print(in doc3);
device.Scan(out doc1);
device.PowerOn();
device.ScanAndPrint();
device.ScanAndPrint();
// 5 wydruków, gdy urządzenie włączone
Assert.AreEqual(5, device.PrintCounter);
}
[TestMethod]
public void MFD_ScanCounter()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
IDocument doc1;
device.Scan(out doc1);
IDocument doc2;
device.Scan(out doc2);
IDocument doc3 = new ImageDocument("aaa.jpg");
device.Print(in doc3);
device.PowerOff();
device.Print(in doc3);
device.Scan(out doc1);
device.PowerOn();
device.ScanAndPrint();
device.ScanAndPrint();
// 4 skany, gdy urządzenie włączone
Assert.AreEqual(4, device.ScanCounter);
}
[TestMethod]
public void MFD_PowerOnCounter()
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
device.PowerOn();
device.PowerOn();
IDocument doc1;
device.Scan(out doc1);
IDocument doc2;
device.Scan(out doc2);
device.PowerOff();
device.PowerOff();
device.PowerOff();
device.PowerOn();
IDocument doc3 = new ImageDocument("aaa.jpg");
device.Print(in doc3);
device.PowerOff();
device.Print(in doc3);
device.Scan(out doc1);
device.PowerOn();
device.ScanAndPrint();
device.ScanAndPrint();
// 3 włączenia
Assert.AreEqual(3, device.Counter);
}
}
}
<file_sep>/Zadanie2/Program.cs
using System;
using Zadanie1;
namespace Zadanie2
{
class Program
{
static void Main(string[] args)
{
MultifunctionalDevice device = new MultifunctionalDevice();
device.PowerOn();
Console.WriteLine(device.GetState());
IDocument doc1 = new PDFDocument("aaa.pdf");
device.Print(in doc1);
IDocument doc2, doc3, doc4, doc5;
device.Scan(out doc2, IDocument.FormatType.JPG);
device.Scan(out doc3, IDocument.FormatType.TXT);
device.Scan(out doc4, IDocument.FormatType.PDF);
device.Scan(out doc5);
device.Send(doc1, "<EMAIL>");
}
}
}
<file_sep>/Zadanie3/MultidimensionalDevice.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Zadanie3
{
public class MultidimensionalDevice : IFax
{
public int Counter { get; private set; } = 0;
protected IDevice.State state = IDevice.State.on;
public IDevice.State GetState() => state;
public void PowerOff()
{
state = IDevice.State.off;
}
public void PowerOn()
{
state = IDevice.State.off;
}
public void Send(in IDocument document, string nameOfDevice)
{
if (GetState() == IDevice.State.on)
{
Console.WriteLine("The file named " + document.GetFileName() + "has been sent to the device named: " + nameOfDevice);
}
else
throw new Exception("The multifunctional device is turned off.");
}
}
}
<file_sep>/Zadanie3/Scanner.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Zadanie3
{
public class Scanner : IScanner
{
public int Counter { get; private set; } = 0;
public int ScanCounter { get; private set; } = 0;
protected IDevice.State state = IDevice.State.on;
public IDevice.State GetState() => state;
public void PowerOff()
{
state = IDevice.State.off;
}
public void PowerOn()
{
state = IDevice.State.off;
}
public void Scan(out IDocument document, IDocument.FormatType formatType)
{
DateTime dateTime = DateTime.Now;
string value = String.Format("{0:D4}", ScanCounter++);
if (formatType == IDocument.FormatType.TXT)
{
document = new PDFDocument("TXTScan" + value + ".txt");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else if (formatType == IDocument.FormatType.PDF)
{
document = new TextDocument("PDFScan" + value + ".pdf");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else if (formatType == IDocument.FormatType.JPG)
{
document = new TextDocument("JPGScan" + value + ".jpg");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else
{
document = null;
}
}
public void Scan(out IDocument doc2)
{
IDocument.FormatType formatType = IDocument.FormatType.JPG;
Scan(out doc2, formatType);
}
}
}
<file_sep>/Zadanie3/Copier.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Zadanie3
{
public class Copier : BaseDevice
{
private Printer InternalPrinter = new Printer();
private Scanner InternalScanner = new Scanner();
private MultidimensionalDevice InternalMultiDevice = new MultidimensionalDevice();
List<IDevice> baseDevices;
public Copier()
{
baseDevices.Add(new Printer());
baseDevices.Add(new Scanner());
baseDevices.Add(new MultidimensionalDevice());
for (int i = 0; i < baseDevices.Count; i++)
{
baseDevices[i].PowerOn();
}
}
class Car
{
List<wheels> wheels; //kompozycja
public Car()
{
wheels[0] // powołuje do życia 4 koła
}
}
class Car //agregacja
{
List<wheels> & wheels;
public Car(List<wheels> wheels)
{
this.wheels = wheels;
}
}
public new int Counter { get; private set; } = 0;
public void Scan(out IDocument document, IDocument.FormatType formatType)
{
InternalScanner.PowerOn();
if (GetState() == IDevice.State.on)
{
InternalScanner.Scan(out document, formatType);
}
else
throw new Exception("The copier is turned off.");
}
public void Scan (out IDocument document)
{
InternalScanner.PowerOn();
if (GetState() == IDevice.State.on)
{
InternalScanner.Scan(out document);
}
else
throw new Exception("The copier is turned off.");
}
public void Print(in IDocument document)
{
InternalPrinter.PowerOn();
if (GetState() == IDevice.State.on)
{
InternalPrinter.Print(document);
}
else
throw new Exception("The copier is turned off.");
}
public void ScanAndPrint()
{
InternalPrinter.PowerOn();
InternalScanner.PowerOn();
IDocument doc;
InternalScanner.Scan(out doc);
InternalPrinter.Print(doc);
}
public void Send(in IDocument document, string nameOfDevice)
{
InternalMultiDevice.PowerOn();
InternalMultiDevice.Send(document, nameOfDevice);
}
}
}
<file_sep>/Zadanie1/Copier.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Zadanie1
{
public class Copier : BaseDevice, IPrinter, IScanner
{
public Copier() { }
public int PrintCounter { get; private set; } = 0;
public int ScanCounter { get; private set; } = 0;
public new int Counter { get; private set; } = 0;
public new void PowerOff()
{
state = IDevice.State.off;
Console.WriteLine("... Device is off !");
}
public new void PowerOn()
{
state = IDevice.State.on;
Console.WriteLine("Device is on ...");
Counter++;
}
public void Print(in IDocument doc1)
{
if (GetState() == IDevice.State.on)
{
DateTime dateTime = DateTime.Now;
Console.WriteLine(dateTime.ToString() + " Print: " + doc1.GetFileName());
PrintCounter++;
}
else
throw new Exception("The copier is turned off.");
}
public void ScanAndPrint()
{
if (GetState() == IDevice.State.on)
{
IDocument doc;
Scan(out doc);
Print(doc);
}
else
throw new Exception("The copier is turned off.");
}
public void Scan(out IDocument document, IDocument.FormatType formatType)
{
if (GetState() == IDevice.State.on)
{
DateTime dateTime = DateTime.Now;
string value = String.Format("{0:D4}", ScanCounter++);
if (formatType == IDocument.FormatType.TXT)
{
document = new PDFDocument("TXTScan" + value + ".txt");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else if (formatType == IDocument.FormatType.PDF)
{
document = new TextDocument("PDFScan" + value + ".pdf");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else if (formatType == IDocument.FormatType.JPG)
{
document = new TextDocument("JPGScan" + value + ".jpg");
Console.WriteLine(dateTime + " " + document.GetFileName());
}
else
{
document = null;
}
}
else
throw new Exception("The copier is turned off.");
}
public void Scan(out IDocument doc2)
{
if (GetState() == IDevice.State.on)
{
IDocument.FormatType formatType = IDocument.FormatType.JPG;
Scan(out doc2, formatType );
}
else
throw new Exception("The copier is turned off.");
}
}
}
|
f3ecfa78917ad2dcbc797306f948c28dc59245ea
|
[
"C#"
] | 9
|
C#
|
julcia106/Copier
|
3f4adeb897652f5c9731ceddfd21a84118ec117a
|
80b50267db835d05d143fa1bc29e2897b863b98c
|
refs/heads/master
|
<file_sep>package org.firstinspires.ftc.teamcode.ultimategoal2020;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
@TeleOp(name = "Rookie Op Mode", group = "TeleOp")
public class rookiecampteleop extends LinearOpMode { //changed from "OpMode" to "LinearOpMode" (LinearOpMode alr extends OpMode)
DcMotor leftMotorT;
DcMotor leftMotorB;
DcMotor rightMotorT;
DcMotor rightMotorB;
double leftPowerT; //you don't need to make variables for power --> set pwr ex. leftMotorT.setPower(power)
double leftPowerB;
double rightPowerT;
double rightPowerB;
double leftStickY = -gamepad1.left_stick_y;
double rightStickX = gamepad1.right_stick_x;
double leftStickX = gamepad1.left_stick_x; //u made this trigger, but i think it makes more sense to do left stick x
double rightTrigger = gamepad1.right_trigger;
double leftTrigger = gamepad1.left_trigger;
ElapsedTime time = new ElapsedTime(); //can delete this (don't rly use time anywhere)
@Override
public void runOpMode() { //everything that happens in init & after start needs to be in a runOpMode loop
init();
leftMotorT = hardwareMap.dcMotor.get("leftDriveT"); //i would keep leftDriveT as leftMotorT for consistency
leftMotorB = hardwareMap.dcMotor.get("leftDriveB");
rightMotorT = hardwareMap.dcMotor.get("rightDriveT");
rightMotorB = hardwareMap.dcMotor.get("rightDriveB");
waitForStart(); //this is the start command --> everything under here will happen once u click the start button
while (opModeIsActive()) { //stops loop when driver hits stop (don't need stop command)
leftMotorT.setPower(0); //ex. of how to set power (change other 3)
leftPowerB = 0;
rightPowerT = 0;
rightPowerB = 0;
//Move forwards and backwards
if (leftStickY != 0) { //create dead zone --> if (leftStickY > 0.05 || leftStickY < -0.05)
leftMotorT.setPower(leftStickY); //change other 3
leftPowerB = leftStickY;
rightPowerT = leftStickY;
rightPowerB = leftStickY;
}
//Turn left and right
else if (rightStickX != 0) { //create dead zone again (so that joysticks aren't too sensitive)
leftPowerT = -rightStickX; //change to leftMotorT.setPower(-rightStickX) + other 3
leftPowerB = -rightStickX;
rightPowerT = rightStickX;
rightPowerB = rightStickX;
}
//Strafe right & left
else if (leftStickX > 0.05 || leftStickX < -0.05) { //changed from bumper to left joystick x axis
leftMotorT.setPower(leftStickX);
leftMotorB.setPower(-leftStickX);
rightMotorT.setPower(-leftStickX);
rightMotorB.setPower(leftStickX);
}
//Press Y to move diagonally backwards
else if (gamepad1.y) {
if (gamepad1.right_trigger > 0) {
leftPowerB = -rightTrigger;
rightPowerT = -rightTrigger;
} else if (gamepad1.left_trigger > 0) {
leftPowerT = -leftTrigger;
rightPowerB = -leftTrigger;
}
}
//Move diagonally right
else if (gamepad1.right_trigger > 0) {
leftPowerT = rightTrigger;
rightPowerB = rightTrigger;
}
//Move diagonally left
else if (gamepad1.left_trigger > 0) {
leftPowerT = -leftTrigger;
rightPowerB = -leftTrigger;
}
leftMotorT.setPower(leftPowerT);
leftMotorB.setPower(leftPowerB);
rightMotorT.setPower(rightPowerT);
rightMotorB.setPower(rightPowerB);
}
}
}
<file_sep>package org.firstinspires.ftc.teamcode.freightfrenzy2021;
import android.graphics.Bitmap;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.vuforia.Frame;
import com.vuforia.Image;
import com.vuforia.PIXEL_FORMAT;
import com.vuforia.Vuforia;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.Parameters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
import static android.graphics.Color.blue;
import static android.graphics.Color.green;
import static android.graphics.Color.red;
public class wcVision {
private LinearOpMode opMode;
private VuforiaLocalizer vuforia;
private Parameters parameters;
private CameraDirection CAMERA_CHOICE = CameraDirection.BACK;
private final int RED_THRESHOLD = 20;
private final int GREEN_THRESHOLD = 20;
private final int BLUE_THRESHOLD = 20;
private final double widthFactor = 1280.0 / 3264;
private final double heightFactor = 720.0 / 1836;
private final int xdiff = 650;
private final int yheight = 300;
private static final String VUFORIA_KEY = "<KEY>";
private BlockingQueue<VuforiaLocalizer.CloseableFrame> frame;
public static String bitmapSkyStonePosition;
public wcVision(LinearOpMode opMode) {
this.opMode = opMode;
int cameraMonitorViewId = this.opMode.hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", this.opMode.hardwareMap.appContext.getPackageName());
Parameters params = new Parameters(cameraMonitorViewId);
params.vuforiaLicenseKey = VUFORIA_KEY;
params.cameraDirection = CAMERA_CHOICE;
vuforia = ClassFactory.getInstance().createVuforia(params);
Vuforia.setFrameFormat(PIXEL_FORMAT.RGB565, true); //enables RGB565 format for the image
vuforia.setFrameQueueCapacity(4); //tells VuforiaLocalizer to only store one frame at a time
vuforia.enableConvertFrameToBitmap();
}
/*
public BitMapVision(LinearOpMode opMode) {
this.opMode = opMode;
int cameraMonitorViewId = this.opMode.hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", this.opMode.hardwareMap.appContext.getPackageName());
VuforiaLocalizer.Parameters params = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
params.vuforiaLicenseKey = VUFORIA_KEY;
params.cameraDirection = CAMERA_CHOICE;
vuforia = ClassFactory.getInstance().createVuforia(params);
Vuforia.setFrameFormat(PIXEL_FORMAT.RGB565, true); //enables RGB565 format for the image
vuforia.setFrameQueueCapacity(4); //tells VuforiaLocalizer to only store one frame at a time
}*/
public Bitmap getImage() throws InterruptedException {
VuforiaLocalizer.CloseableFrame frame = vuforia.getFrameQueue().take();
long numImages = frame.getNumImages();
Image rgb = null;
for (int i = 0; i < numImages; i++) {
Image img = frame.getImage(i);
int fmt = img.getFormat();
if (fmt == PIXEL_FORMAT.RGB565) {
rgb = frame.getImage(i);
break;
}
}
Bitmap bm = Bitmap.createBitmap(rgb.getWidth(), rgb.getHeight(), Bitmap.Config.RGB_565);
bm.copyPixelsFromBuffer(rgb.getPixels());
return bm;
}
public Bitmap getBitmap() throws InterruptedException {
VuforiaLocalizer.CloseableFrame picture;
picture = vuforia.getFrameQueue().take();
Image rgb = picture.getImage(1);
long numImages = picture.getNumImages();
opMode.telemetry.addData("Num Images", numImages);
opMode.telemetry.update();
for (int i = 0; i < numImages; i++) {
int format = picture.getImage(i).getFormat();
if (format == PIXEL_FORMAT.RGB565) {
rgb = picture.getImage(i);
break;
} else {
opMode.telemetry.addLine("Didn't find correct RGB format");
opMode.telemetry.update();
}
}
Bitmap imageBitmap = Bitmap.createBitmap(rgb.getWidth(), rgb.getHeight(), Bitmap.Config.RGB_565);
imageBitmap.copyPixelsFromBuffer(rgb.getPixels());
opMode.telemetry.addData("Image width", imageBitmap.getWidth());
opMode.telemetry.addData("Image height", imageBitmap.getHeight());
opMode.telemetry.update();
picture.close();
opMode.telemetry.addLine("Got bitmap");
opMode.telemetry.update();
return imageBitmap;
}
public String sample() throws InterruptedException {
Bitmap bitmap = getBitmap();
String bitmapCubePosition;
ArrayList<Integer> xValues = new ArrayList<>();
int avgX = 0;
//top left = (0,0)
for (int colNum = 0; colNum < bitmap.getWidth(); colNum += 2) {
for (int rowNum = 0; rowNum < (int) (bitmap.getHeight()); rowNum += 3) {
int pixel = bitmap.getPixel(colNum, rowNum);
int redPixel = red(pixel);
int greenPixel = green(pixel);
int bluePixel = blue(pixel);
if (redPixel <= RED_THRESHOLD && greenPixel <= GREEN_THRESHOLD && bluePixel <= BLUE_THRESHOLD) {
xValues.add(colNum);
}
}
}
for (int x : xValues) {
avgX += x;
}
avgX /= xValues.size();
if (avgX < (bitmap.getWidth() / 3.0)) {
bitmapCubePosition = "left";
} else if (avgX > (bitmap.getWidth() / 3.0) && avgX < (bitmap.getWidth() * 2.0 / 3)) {
bitmapCubePosition = "center";
} else {
bitmapCubePosition = "right";
}
opMode.telemetry.addData("Cube Position", bitmapCubePosition);
opMode.telemetry.update();
return bitmapCubePosition;
}
public String findRedSkystones() throws InterruptedException {
Bitmap bitmap = getBitmap();
String bitmapCubePosition;
int stone1 = bitmap.getPixel((int) (603 * widthFactor), (int) (1670 * heightFactor));//bitmap.getWidth() * 2/5, 20
int redVal1 = red(stone1);
int stone2 = bitmap.getPixel((int) (1350 * widthFactor), (int) (1670 * heightFactor));//bitmap.getWidth()/2, 20
int redVal2 = red(stone2);
int stone3 = bitmap.getPixel((int) (2090 * widthFactor), (int) (1670 * heightFactor));//bitmap.getWidth() * 3/5, 20
int redVal3 = red(stone3);
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(redVal1);
vals.add(redVal2);
vals.add(redVal3);
int min = Collections.min(vals);
int pos = vals.indexOf(min);
if (pos == 0) {
bitmapCubePosition = "left";
} else if (pos == 1) {
bitmapCubePosition = "center";
} else if (pos == 2) {
bitmapCubePosition = "right";
} else {
bitmapCubePosition = "yikes";
}
/*
telemetry.addData("redval1", redVal1);
telemetry.addData("redval2", redVal2);
telemetry.addData("redval3", redVal3);
telemetry.addData("left", vals.get(0));
telemetry.addData("center", vals.get(1));
telemetry.addData("right", vals.get(2));
telemetry.update();
sleep(5000);*/
return bitmapCubePosition;
}
public String findBlueSkystones() throws InterruptedException {
Bitmap bitmap = getBitmap();
String bitmapCubePosition;
int stone1 = bitmap.getPixel((int) (989 * widthFactor), (int) (1677 * heightFactor));//bitmap.getWidth() * 2/5, 20
int redVal1 = red(stone1);
int stone2 = bitmap.getPixel((int) (1745 * widthFactor), (int) (1677 * heightFactor));//bitmap.getWidth()/2, 20
int redVal2 = red(stone2);
int stone3 = bitmap.getPixel((int) (2500 * widthFactor), (int) (1677 * heightFactor));//bitmap.getWidth() * 3/5, 20
int redVal3 = red(stone3);
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(redVal1);
vals.add(redVal2);
vals.add(redVal3);
int min = Collections.min(vals);
int pos = vals.indexOf(min);
if (pos == 0) {
bitmapCubePosition = "left";
} else if (pos == 1) {
bitmapCubePosition = "center";
} else if (pos == 2) {
bitmapCubePosition = "right";
} else {
bitmapCubePosition = "yikes";
}
/*
telemetry.addData("redval1", redVal1);
telemetry.addData("redval2", redVal2);
telemetry.addData("redval3", redVal3);
telemetry.addData("left", vals.get(0));
telemetry.addData("center", vals.get(1));
telemetry.addData("right", vals.get(2));
telemetry.update();
sleep(5000);*/
return bitmapCubePosition;
}
public Bitmap vufConvertToBitmap(Frame frame) {
return vuforia.convertFrameToBitmap(frame);
}
public void initBitmap() throws InterruptedException {
Bitmap bitmap = getBitmap();
}
public String rbgVals(int xCoord, int yCoord) throws InterruptedException {
Bitmap bitmap = getBitmap();
int stone1 = bitmap.getPixel((int) (xCoord * widthFactor), (int) (yCoord * heightFactor));//bitmap.getWidth() * 2/5, 20
int redVal1 = red(stone1);
int greenVal1 = green(stone1);
int blueVal1 = blue(stone1);
String color = null;
if (redVal1 >= 120 && redVal1 <= 160 && greenVal1 >= 120 && greenVal1 <= 160 && blueVal1 >= 120 && blueVal1 <= 160) {
color = "yellow";
} else {
color = "not yellow";
}
return "red: " + redVal1 + " blue: " + blueVal1 + " green: " + greenVal1 + " the color is " + color;
}
public String floorAvg() throws InterruptedException {
Bitmap bitmap = getBitmap();
int floor1 = bitmap.getPixel((int) (953 * widthFactor), (int) (473 * heightFactor));//bitmap.getWidth()/2, 20
int redFloor1 = red(floor1);
int greenFloor1 = green(floor1);
int blueFloor1 = blue(floor1);
int floor2 = bitmap.getPixel((int) (840 * widthFactor), (int) (460 * heightFactor));//bitmap.getWidth()/2, 20
int redFloor2 = red(floor2);
int greenFloor2 = green(floor2);
int blueFloor2 = blue(floor2);
int floor3 = bitmap.getPixel((int) (810 * widthFactor), (int) (510 * heightFactor));//bitmap.getWidth()/2, 20
int redFloor3 = red(floor3);
int greenFloor3 = green(floor3);
int blueFloor3 = blue(floor3);
double floorAvgRed = (double) (redFloor1 + redFloor2 + redFloor3) / 3;
double floorAvgBlue = (double) (blueFloor1 + blueFloor2 + blueFloor3) / 3;
return "red floor: " + floorAvgRed + "blue floor: " + floorAvgBlue;
}
}
<file_sep>package org.firstinspires.ftc.teamcode.ultimategoal2020;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.robotcontroller.external.samples.SensorColor;
@Autonomous(name="rookiecampauto", group="Autonomous")
public class rookiecampauto extends LinearOpMode {
ModernRoboticsI2cGyro gyro = null;
ElapsedTime time = new ElapsedTime();
//define variables, motors, etc.
DcMotor fL;
DcMotor fR;
DcMotor bL;
DcMotor bR;
Servo dump;
SensorColor colorSensor;
@Override
public void runOpMode() {
//stuff that happens after init is pressed
init();
gyro = (ModernRoboticsI2cGyro)hardwareMap.gyroSensor.get("gyro");
fL = hardwareMap.dcMotor.get("fL");
fR = hardwareMap.dcMotor.get("fR");
bL = hardwareMap.dcMotor.get("bL");
bR = hardwareMap.dcMotor.get("bR");
telemetry.addLine("go team");
telemetry.addLine("hi");
telemetry.addData("fL position:", fL.getCurrentPosition());
telemetry.update();
gyro.calibrate();
while (!isStopRequested() && gyro.isCalibrating()) {
sleep(50);
idle();
}
//stuff that happens after start is pressed
waitForStart();
while (opModeIsActive()) {
//call functions
go_straight(500, -0.5);
// strafe left
// turn right
dump.setPosition(1);
// go backwards
// strafe left
}
}
//create functions
public void go_straight (double distance, double pwr) {
double startVal = fL.getCurrentPosition();
while ((Math.abs(fL.getCurrentPosition() - startVal) < distance) && opModeIsActive()) {
fL.setPower(pwr);
fR.setPower(pwr);
bL.setPower(pwr);
bR.setPower(pwr);
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void go_straight_gyro (double distance, double pwr) {
gyro.resetZAxisIntegrator();
double startVal = fL.getCurrentPosition();
while ((Math.abs(fL.getCurrentPosition() - startVal) < distance) && opModeIsActive()) {
if (gyro.getIntegratedZValue() > 1) {
fL.setPower(pwr * 0.9);
fR.setPower(pwr);
bL.setPower(pwr * 0.9);
bR.setPower(pwr);
}
else if (gyro.getIntegratedZValue() < 1) {
fL.setPower(pwr);
fR.setPower(pwr * 0.9);
bL.setPower(pwr);
bR.setPower(pwr * 0.9);
}
else {
fL.setPower(pwr);
fR.setPower(pwr);
bL.setPower(pwr);
bR.setPower(pwr);
}
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void strafe_right (double distance, double pwr) {
double startVal2 = fL.getCurrentPosition();
while((Math.abs(fL.getCurrentPosition() - startVal2) < distance) && opModeIsActive()) {
fL.setPower(pwr);
fR.setPower(-pwr);
bL.setPower(-pwr);
bR.setPower(pwr);
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void strafe_right_gyro (double distance, double pwr) {
gyro.resetZAxisIntegrator();
double startVal2 = fL.getCurrentPosition();
while((Math.abs(fL.getCurrentPosition() - startVal2) < distance) && opModeIsActive()) {
if (gyro.getIntegratedZValue() > 1) {
fL.setPower(pwr * 0.9);
fR.setPower(-pwr);
bL.setPower(-pwr * 0.9);
bR.setPower(pwr);
}
else if (gyro.getIntegratedZValue() < 1) {
fL.setPower(pwr);
fR.setPower(-pwr * 0.9);
bL.setPower(-pwr);
bR.setPower(pwr * 0.9);
}
else {
fL.setPower(pwr);
fR.setPower(-pwr);
bL.setPower(-pwr);
bR.setPower(pwr);
}
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void turnBasic_right(double turn, double pwr) {
gyro.resetZAxisIntegrator();
while ((gyro.getIntegratedZValue() < turn) && opModeIsActive()) {
fL.setPower(pwr);
fR.setPower(-pwr);
bL.setPower(pwr);
bR.setPower(-pwr);
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void turnBasic_left(double turn, double pwr) {
gyro.resetZAxisIntegrator();
while ((gyro.getIntegratedZValue() > turn) && opModeIsActive()) {
fL.setPower(-pwr);
fR.setPower(pwr);
bL.setPower(-pwr);
bR.setPower(pwr);
}
fL.setPower(0);
fR.setPower(0);
bL.setPower(0);
bR.setPower(0);
}
public void turnPID(double angle, double pwr, double d) {
gyro.resetZAxisIntegrator();
time.reset();
double deltaAngle = Math.abs(angle - gyro.getHeading());
double pastdeltaAngle = deltaAngle;
double currentTime;
double kP = pwr / angle;
double kI = 0.01;
double kD = d / angle;
double prevTime = 0;
double apply = 0;
double deltaTime;
while (Math.abs(deltaAngle) > 1){
deltaAngle = Math.abs(angle - gyro.getHeading());
kP = deltaAngle * kP;
currentTime = time.milliseconds();
deltaTime = currentTime - prevTime;
kI = deltaAngle * deltaTime * kI;
kD = (deltaAngle - pastdeltaAngle) / deltaTime * kD;
apply = kP + kI + kD;
fL.setPower(-apply);
fR.setPower(apply);
bL.setPower(-apply);
bR.setPower(apply);
prevTime = currentTime;
pastdeltaAngle = deltaAngle;
}
}
}
|
84b8e041dbcd27dc4124b0601027819156e9906f
|
[
"Java"
] | 3
|
Java
|
CameronFTC/road-runner-quickstart-master
|
22f914032ea68d6e672e34ec4b3cae35392d1e82
|
f475fb19d68cd8e97a20a9f305c2212fe37211c7
|
refs/heads/master
|
<repo_name>ahracho/CarND-Advanced-Lane-Lines<file_sep>/pipeline.py
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import pickle
from LineTracker import LineTracker
from Line import Line
from util_function import *
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
# Global Variables
nwindows = 72
line = Line()
tracker = LineTracker(nwindows=nwindows, margin=50)
# (1) Camera Calibration => Do only once per video
# : process_image() function executed on every frame
dist_pickle = camera_calibration()
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
def process_image(image):
# (2) Undistort the frame image
image = cv2.undistort(image, mtx, dist, None, mtx)
# (3) Set several thresholds to detect lane lines
# (3-1) Gradient : Use Sobel X operation
grad_thresh = (30, 150)
abs_sobelx = abs_sobel_thresh(image, orient='x', thresh=grad_thresh)
# (3-2) Color Threshold : Use H and S channel
s_thresh = (175, 255)
s_binary = hls_threshold(image, ch="S", thresh=s_thresh)
# (3-3) Threshold Combination
combined = np.zeros_like(s_binary)
combined[((abs_sobelx == 1) | (s_binary == 1))] = 1
# (4) Perspective Transform : To find lane lines from top-down view
top_limit = 0.67
from_mid = 100
from_edge = 0.17
bottom_limit = 0.98
m_w = image.shape[1]
m_h = image.shape[0]
src = np.float32([[m_w/2 - from_mid, m_h*top_limit],
[m_w/2 + from_mid, m_h*top_limit],
[m_w*(1-from_edge), m_h*bottom_limit],
[m_w*from_edge+100, m_h*bottom_limit]])
dst = np.float32([[m_w/5, 20],
[m_w*4/5, 20],
[m_w*4/5, m_h],
[m_w/5, m_h]])
M = cv2.getPerspectiveTransform(src, dst)
Minv = cv2.getPerspectiveTransform(dst, src)
warped = cv2.warpPerspective(
combined, M, (m_w, m_h), flags=cv2.INTER_LINEAR)
# (5) Find window centroids and calculate polynomial coefficients
tracker.find_window_centroid(warped, line)
# (5-1) Calculate points to draw polynomial lines
ploty = np.linspace(0, warped.shape[0]-1, warped.shape[0])
left_fitx = line.left_fit[0]*ploty**2 + \
line.left_fit[1]*ploty + line.left_fit[2]
right_fitx = line.right_fit[0]*ploty**2 + \
line.right_fit[1]*ploty + line.right_fit[2]
# (5-2) Calculate curvature and vehicle position
left_curve, right_curve = line.calculate_curvature()
curve_str = "Radius of Curvature : " + \
str(int((left_curve+right_curve)//2)) + '(m)'
diff = line.distance_from_center(m_w)
if diff < 0:
dist_str = "The vehicle is " + \
"{0:.2f}".format(-diff) + "m left of center"
else:
dist_str = "The vehicle is " + \
"{0:.2f}".format(diff) + "m right of center"
# (6) Draw lines back on the original image
warp_zero = np.zeros_like(warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array(
[np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(
color_warp, Minv, (image.shape[1], image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)
cv2.putText(result, curve_str, (50, 100),
cv2.FONT_HERSHEY_DUPLEX, 1, (50, 50, 50), thickness=2)
cv2.putText(result, dist_str, (50, 150),
cv2.FONT_HERSHEY_DUPLEX, 1, (50, 50, 50), thickness=2)
return result
white_output = 'final_video.mp4'
clip1 = VideoFileClip("./project_video.mp4")
white_clip = clip1.fl_image(process_image)
white_clip.write_videofile(white_output, audio=False)
<file_sep>/util_function.py
import pickle
import os
import cv2
import numpy as np
import matplotlib.image as mpimg
cal_dir = "./camera_cal/"
cal_file = "./calibration_pickle.p"
def camera_calibration(board_size=(9, 6)):
if os.path.isfile(cal_file):
with open(cal_file, mode='rb') as f:
dist_pickle = pickle.load(f)
else:
cal_images = os.listdir(cal_dir)
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*9, 3), np.float32)
objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)
for path in cal_images:
cal_image = mpimg.imread(cal_dir + path)
gray = cv2.cvtColor(cal_image, cv2.COLOR_RGB2GRAY)
ret, corners = cv2.findChessboardCorners(gray, board_size, None)
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Get Camera matrix and distortion coefficients
ret, mtx, dist, _, _ = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
# Save the result
dist_pickle = {}
dist_pickle["mtx"] = mtx
dist_pickle["dist"] = dist
pickle.dump(dist_pickle, open(cal_file, "wb"))
print("##### Camera Calibration Finished #####")
return dist_pickle
def abs_sobel_thresh(image, orient='x', sobel_kernel=3, thresh=(0, 255)):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
if orient == 'x':
abs_sobel = np.absolute(
cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
elif orient == 'y':
abs_sobel = np.absolute(
cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
scale_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))
grad_binary = np.zeros_like(scale_sobel)
grad_binary[(scale_sobel >= thresh[0]) & (scale_sobel <= thresh[1])] = 1
return grad_binary
def dir_threshold(image, sobel_kernel=3, thresh=(0, np.pi/2)):
# Calculate gradient direction
# Apply threshold
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
absx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
absy = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
grad_dir = np.arctan2(absy, absx)
dir_binary = np.zeros_like(grad_dir)
dir_binary[(grad_dir >= thresh[0]) & (grad_dir <= thresh[1])] = 1
return dir_binary
def hls_threshold(image, ch='S', thresh=(0, 255)):
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
if ch == 'H':
value = hls[:, :, 0]
elif ch == 'L':
value = hls[:, :, 1]
elif ch == 'S':
value = hls[:, :, 2]
hls_binary = np.zeros_like(value)
hls_binary[(value > thresh[0]) & (value <= thresh[1])] = 1
return hls_binary
<file_sep>/Line.py
import numpy as np
class Line():
def __init__(self, xm=3.7/800, ym=30/720):
self.left_fit = []
self.right_fit = []
self.xm_per_pix = xm # meters per pixel in horizontal axis
self.ym_per_pix = ym # meters per pixel in vertical axis
self.leftx = []
self.lefty = []
self.rightx = []
self.righty = []
def calculate_curvature(self, y=720):
left_fit_meter = np.polyfit(self.lefty*self.ym_per_pix, self.leftx*self.xm_per_pix, 2)
right_fit_meter = np.polyfit(self.righty*self.ym_per_pix,
self.rightx*self.xm_per_pix, 2)
left_curve = (
(1 + (2*left_fit_meter[0]*y*self.ym_per_pix + left_fit_meter[1])**2) ** 1.5) / np.absolute(2*left_fit_meter[0])
right_curve = (
(1 + (2*right_fit_meter[0]*y*self.ym_per_pix + right_fit_meter[1])**2) ** 1.5) / np.absolute(2*right_fit_meter[0])
return left_curve, right_curve
def distance_from_center(self, width=1280):
left_pos = self.leftx[0]
right_pos = self.rightx[0]
center = int((right_pos + left_pos) // 2)
# Positive value means vehicle is right of center
# Negative value means vehicle is left of center
return (width//2 - center) * self.xm_per_pix
<file_sep>/writeup.md
# **Advanced Lane Finding Project**
The goals / steps of this project are the following:
* Compute the camera calibration matrix and distortion coefficients given a set of chessboard images.
* Apply a distortion correction to raw images.
* Use color transforms, gradients, etc., to create a thresholded binary image.
* Apply a perspective transform to rectify binary image ("birds-eye view").
* Detect lane pixels and fit to find the lane boundary.
* Determine the curvature of the lane and vehicle position with respect to center.
* Warp the detected lane boundaries back onto the original image.
* Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position.
[//]: # (Image References)
[image1]: ./writeup_images/undistorted_board.png "Undistorted"
[image2]: ./writeup_images/process.png "Pipeline"
[image3]: ./writeup_images/undistorted_screen.png "Test Image"
[image4]: ./writeup_images/gradient_sample.jpg "Gradient"
[image5]: ./writeup_images/warped.jpg "Warped"
[image6]: ./writeup_images/line_plot.png "Line"
[image7]: ./writeup_images/final_result.jpg "Line"
[image8]: ./writeup_images/wrong_detect.jpg "Wrong Image"
[video1]: ./final_video.mp4 "Video"
## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points
### Here I will consider the rubric points individually and describe how I addressed each point in my implementation.
---
### Files Submitted & Code Quality
My project includes the following files:
* pipeline.py : execution script for finding lane lines
* final_video.mp4 : final output video (based on project_video.mp4)
* writeup.md : summarizing the results
### Camera Calibration
#### 1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image.
The code for this step is contained in _camera\_calibration()_ function _util\_function.py_.
I used all of 20 images given in this project to calibrate camera. I start by preparing "object points(`objpoints `)", which will be the (x, y, z) coordinates of the chessboard corners in the world. I set the chessboard is fixed on the (x, y) plane at z=0, so that the object points are the same for each calibration image. I used return value of ` findChessboardCorners() ` function as "image points(`imgpoints`)", which indicates (x, y) position of each corner on the images.
I then used the output `objpoints` and `imgpoints` to compute the camera calibration and distortion coefficients using the `cv2.calibrateCamera()` function.
I save the result on `calibration_pickle.p` file so that I calculate camera matrix and distortion coefficients just once and reuse them.
![undistortion][image1]
### Pipeline (single images)
Image pre-process pipeline basically follows the process provided in lectures as below.
![pipeline process][image2]
#### 1. Provide an example of a distortion-corrected image.
I used camera matrix and distortion coefficients I get from previous step. On each frame of the video, pipeline starts from distortion-correction. The code for this step is in line 31 in `pipeline.py`.
Sample images for undistorted image is as below.
![alt text][image3]
#### 2. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result.
The first thing I have problem with was finding good threshold combination so that I can detect lane lines regardless of color, shade and obstacles etc. I used test images in `test_images` folder to verity how my filter works. Normally, it worked fine with `straight_linesX.jpg`, I need to tune the thresholds to make it work for images with shadow.
1. Sobel Gradient (Line 36-37 in `pipeline.py` and abs_sobel_thresh() in `util_function.py`)
First, I tried sobel gradient both x and y, but it seemed sobel-y gradient made no big difference, that's why I used only sobel-x gradient. I set threshold as (10, 100). With a wide range of threshold, noise data can be added but I wanted most of lane lines to be detected here.
| Modified |
|:-------------|
| Sobel gradient has been updated to (30, 150) in final version. |
2. Color Gradient (Line 40-43 in `pipeline.py` and hls_threshold() in `util_function.py`)
I changed image into HLS channel and adjusted threshold to H and S channel. By change color channel into HLS, I could get lane line information even when there was shadow on lanes and they have darker color pixel. I set threshold for H channel as (10, 100), and for S channel as (10, 255).
| Modified |
|:-------------|
| Color gradient has been updated. H channel has been removed and threshold for S channel has been updated to (175, 255). |
3. Combination (Line 46-47 in `pipeline.py`)
Last thing I did for gradient was combining three binary image into one. Since my sobel binary image contains clear lane lines but with many noises, I used & operation between sobel and color gradient (Line 47).
| Modified |
|:-------------|
| Combination formula is changed to `combined[((abs_sobelx == 1) | (s_binary == 1))] = 1` |
![alt text][image4]
#### 3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image.
The code for my perspecitve transform is in Line 48-70 in `pipeline.py`. At first, I set source points and destination points. In this project, image size is never change, but for reuseable code, I set points based on ratio not pixel position (except `from_mid` variable which indicates margin from the center of the image).
~~~python
top_limit = 0.67 # 67% of the image height is generally not related to lanes (they are mostly background)
from_mid = 100 # From the center of the image, +/-100 pixels (left and right lanes never meets on the image)
from_edge = 0.17 # Cropping both on left and right side of the image
bottom_limit = 0.98 # Croppint bottom of the image which mostly is the vehicle hood.
m_w = image.shape[1]
m_h = image.shape[0]
src = np.float32([[m_w/2 - from_mid, m_h*top_limit],
[m_w/2 + from_mid, m_h*top_limit],
[m_w*(1-from_edge), m_h*bottom_limit],
[m_w*from_edge+100, m_h*bottom_limit]])
dst = np.float32([[m_w/5, 20],
[m_w*4/5, 20],
[m_w*4/5, m_h],
[m_w/5, m_h]])
~~~
This resulted in the following source and destination points:
| Source | Destination |
|:-------------:|:-------------:|
| 540, 482 | 256, 20 |
| 740, 482 | 1024, 20 |
| 1062, 705 | 1024, 720 |
| 217, 705 | 256, 0 |
I verified that my perspective transform was working as expected by drawing the `src` and `dst` points onto a test image and its warped counterpart to verify that the lines appear parallel in the warped image.
![alt text][image5]
#### 4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial?
Line tracking process is defined in find_window_centroid() method in `LineTracker.py`. I defined LineTracker class which contains variables for sliding window and line tracking method. I used 'sliding window method' to find centroids, and I used cumulated centroids data to find the most reasonable centroid points.
Before coming up with ideas to use cumulated data, I calculated centroids from the scratch for every frame which results in plotting lines jumping around (totally unstable). Since position of the lanes are continuous throughout the video, I decide to use the information from the previous frames.
As I don't have any information for the very first frame of the video, following sliding window method, I summed up the white points for each column and supposed those were lane points (Line 29-33 in `LineTracker.py`).
~~~ python
if len(self.recent_center) == 0:
histogram = np.sum(warped[m_h//2:, :], axis=0)
midpoint = np.int(histogram.shape[0]//2)
leftx_current = np.argmax(histogram[: midpoint-50])
rightx_current = np.argmax(histogram[midpoint:]) + midpoint
~~~
Everytime sliding windows, counting white points and if the number of points is bigger than thershold(`minpix = 100`), it is regarded as valid lane points and take average x-axis position as new centroids (Line 74-77).
~~~python
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
~~~
From second frame of the video, I used centroids information cumulated in LineTracker.recent_center variable. I I supposed new centroid for the new frame won't be far away from the previous one. Placing window at the centroid of the previous frame, and repeating the calculation I mentioned above.
After I get new centroid, I added one more logic to tune the value. I adjust smooth factor and alpha to combine new centroid value and the average of the previous data (Line 85-91). Sometimes I could pick wrong points as lane lines, but by adjusting alpha value I can figure out how much I should count on new information. If alpha equals 1, then I totally rely on data from the previous frames, and if alpha equals 0, I only use newly calculated centroids information.
`new_centroid = alpha * (average value of previous (self.smooth_factor) frames) + (1-alpha) * new_centroid `
~~~python
alpha = 0.2
if len(self.recent_center) > 0:
center = np.array(self.recent_center, dtype=np.uint32)
leftx_current = int(
alpha * np.mean(center[-self.smooth_factor:], axis=0)[window][0] + (1 - alpha) * leftx_current)
rightx_current = int(
alpha * np.mean(center[-self.smooth_factor:], axis=0)[window][1] + (1 - alpha) * rightx_current
~~~
After calculating centroids for each frame, I calculate ploynomial coefficient. For this, I just use centroid points. I have used all of the white points in each window to get polynomial coefficients, but it causes polynomial lines jumping around the frames. Because centroid positions are good representations for the lanes, I thought it should be used to draw poly lines (Line 97-102).
And then I updated ployfit coefficients to calculate curvature of the lanes (Line 105-106).
![alt text][image6]
#### 5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center.
1. Calculate Curvature
This code is defined in calculate_curvature() in Line class (`Line.py`).
Right after calculating centroids in tracker instance, I get polynomial coefficient both for left and right lanes. And because they are calculated based on pixel, they need to be changed into meter-based number.
Meter per pixel information was given in the lecture, so I used this value to calculate curvature. First, need to get polynomial coefficents again based on meter information(Line 16-17, `Line.py`). And then under the formula, calculate curvature for both left and right lanes, I used the average value to print out.
| Modified |
|:-------------|
| Meter per pixel for x-axis has been modified to 3.7/800 since the number 3.7/700 given in lecture refers to the width of the lane in meters and 700 to the width in pixels and in my script it is around 800 pixels. |
Curvature value normally stays between 1km ~ 3km but sometimes it overs 5km especially on straight lanes. As you can see in `final_video.mp4` I can detect lanes most of the time, but curvature value jumps around (**I'm not sure how to tune this vaule. NEED IMPROVEMENT**).
2. Position of the vehicle
Calculate vehicle position was much easier than calculating curvature. The code for this is in distance_from_center() in `Line.py`. For the bottom of the image, I have left and right lane centroids so that I can calculate mid-point of the lane in the image. Since mid-point of the image (640) is regarded as the center of the vehicle, all I have to do is to see the difference of the mid-point of the lane and image(640) (Line 35).
If the value is positive, it means vehicle is right of the center (Vehicle center is on right side of the lane center). And difference need to be changed into meter by multiplying meter/pixel for x-axis.
#### 6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly.
Last thing in pipeline is to plot my result back on the original image. This code is described in Line 96-116 in `pipeline.py`.
I got inverse matrix from `Minv = cv2.getPerspectiveTransform(dst, src)`, and use it to draw polynomial plots back on the original image.
~~~python
warp_zero = np.zeros_like(warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array(
[np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(
color_warp, Minv, (image.shape[1], image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)
~~~
![alt text][image7]
---
### Pipeline (video)
#### 1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video.
Here's a [link to my video result](./project_video.mp4)
---
### Discussion
#### 1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust?
1. Find good threshold for the video
I need to find good threshold combination to accurately detect lane lines from the image. For the project_video.mp4, which mostly shows clear lanes, it was not that hard. But for challenge_video.mp4 and harder_challenge_video.mp4, which contain shadow and darker lanes, my filter still doesn't work well (especially for harder_challenge_video.mp4). I guess my filter does not detect dark yellow lines. I need to think more how to improve filters.
2. Polynomial Lines are jumping around
When I try to find window centroids from the scratch for each frame, I encounted polynomial lines jumped around. Instead of calculating centroids over and over again, I used information from the last frame as described in `Pipeline Question #4`. This is based on the idea that lanes are continuous, so the difference of the x-position of previous frame and the next one. After applying this logic, polynomial lines stay stable.
But there is possibility that mis-detected lines keep having effect on calculating new centroids. This is what happens in harder_challenge_video.mp4. Once wrong position has been detected, it takes long to recover. I need to improve logics how to find better solution for recovery.
<file_sep>/LineTracker.py
import numpy as np
import cv2
class LineTracker():
def __init__(self, nwindows, margin, smooth_factor=10):
# centroids found by find_window_centroid() function
self.recent_center = []
# number of windows for sliding window method
self.nwindows = nwindows
# 1/2 of the window width
self.margin = margin
# number of frames used for smoothing lanes
self.smooth_factor = smooth_factor
def find_window_centroid(self, warped, line):
# I used 'sliding windown method' to find centroids
# Basically, I used cumulated centroids data to find the most reasonable centroid points
m_h = warped.shape[0]
m_w = warped.shape[1]
nonzero = warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# On the very first frame of the video,
# start to find centroid points based on density of white dots
if len(self.recent_center) == 0:
histogram = np.sum(warped[m_h//2:, :], axis=0)
midpoint = np.int(histogram.shape[0]//2)
leftx_current = np.argmax(histogram[: midpoint-50])
rightx_current = np.argmax(histogram[midpoint:]) + midpoint
# Set minimum number of pixels found to recenter window
minpix = 100
# Create empty lists to receive left / right lane pixel indices and centroids
left_lane_inds = []
right_lane_inds = []
centroids = []
window_height = int(m_h//self.nwindows)
# Step through the windows one by one
for window in range(self.nwindows):
# Set window centroid based on the last one
# since lane lines will be away that much from the last frame
if len(self.recent_center) > 0:
leftx_current = self.recent_center[-1][window][0]
rightx_current = self.recent_center[-1][window][1]
# Identify window boundaries in x and y (and right and left)
win_y_low = m_h - (window+1)*window_height
win_y_high = m_h - window*window_height
win_xleft_low = max(leftx_current - self.margin, 0)
win_xleft_high = min(leftx_current + self.margin, m_w)
win_xright_low = max(rightx_current - self.margin, 0)
win_xright_high = min(rightx_current + self.margin, m_w)
# Find white points in window boundaries
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If number of points is bigger than minpix, it is regarded as feasible window
# and take average for the new centroid
# If not, it will use value same as the last frame
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# I added one more logic to find new centroid.
# To prevent new centroids jump around, I weight previous value on new centroid
# new_centroid = \
# a * (average value of previous (self.smooth_factor) frames) + (1-a) * new_centroid
# alpha(a) is the percentage how much I will count on previous data history
alpha = 0.2
if len(self.recent_center) > 0:
center = np.array(self.recent_center, dtype=np.uint32)
leftx_current = int(
alpha * np.mean(center[-self.smooth_factor:], axis=0)[window][0] + (1 - alpha) * leftx_current)
rightx_current = int(
alpha * np.mean(center[-self.smooth_factor:], axis=0)[window][1] + (1 - alpha) * rightx_current)
centroids.append([leftx_current, rightx_current])
self.recent_center.append(centroids)
self.recent_center = self.recent_center[-self.smooth_factor:]
# Find polynomial points based on centroids (not on all white dots)
line.leftx = np.array(centroids, dtype=np.uint32)[:, 0]
line.lefty = np.array(
[m_h - i*window_height for i in range(self.nwindows)])
line.rightx = np.array(centroids, dtype=np.uint32)[:, 1]
line.righty = np.array(
[m_h - i*window_height for i in range(self.nwindows)])
# Fit a second order polynomial to each
line.left_fit = np.polyfit(line.lefty, line.leftx, 2)
line.right_fit = np.polyfit(line.righty, line.rightx, 2)
|
29b24d752b259c59c7e7d833ca5e927672192b35
|
[
"Markdown",
"Python"
] | 5
|
Python
|
ahracho/CarND-Advanced-Lane-Lines
|
ce8fc314a9674ff7cced41fa2c565f305b9e11c9
|
d46a739c12206f22c9489eedfbd7df93c5ab5ee4
|
refs/heads/master
|
<file_sep>// adapted from Murri demo
document.addEventListener('DOMContentLoaded', function() {
var grid = null;
var docElem = document.documentElement;
var mGrid = document.querySelector('.grid-mGrid');
var gridElement = mGrid.querySelector('.grid');
var filterField = mGrid.querySelector('.filter-field');
var searchField = mGrid.querySelector('.search-field');
var sortField = mGrid.querySelector('.sort-field');
var dragOrder = [];
var uuid = 0;
var filterFieldValue;
var sortFieldValue;
var searchFieldValue;
//
// Grid helper functions
//
function initDemo() {
initGrid();
// Reset field values.
searchField.value = '';
[ filterField].forEach(function(field) {
field.value = field.querySelectorAll('option')[0].value;
});
// Set inital search query, active filter, active sort value and active layout.
searchFieldValue = searchField.value.toLowerCase();
filterFieldValue = filterField.value;
// Search field binding.
searchField.addEventListener('keyup', function() {
var newSearch = searchField.value.toLowerCase();
if (searchFieldValue !== newSearch) {
searchFieldValue = newSearch;
filter();
}
});
// Filter, sort and layout bindings.
filterField.addEventListener('change', filter);
}
function initGrid() {
var dragCounter = 0;
grid = new Muuri(gridElement, {
items: document.getElementsByClassName('item'),
layout: {
horizontal: false,
alignRight: false,
alignBottom: false,
fillGaps: true
},
layoutDuration: 400,
layoutEasing: 'ease',
dragEnabled: false,
dragSortInterval: 50,
dragContainer: document.body,
dragStartPredicate: function(item, event) {
var isDraggable = sortFieldValue === 'order';
return isDraggable ? Muuri.ItemDrag.defaultStartPredicate(item, event) : false;
},
dragReleaseDuration: 400,
dragReleseEasing: 'ease'
})
.on('dragStart', function() {
++dragCounter;
docElem.classList.add('dragging');
})
.on('dragEnd', function() {
if (--dragCounter < 1) {
docElem.classList.remove('dragging');
}
})
.on('move', updateIndices)
.on('sort', updateIndices);
}
function filter() {
filterFieldValue = filterField.value;
grid.filter(function(item) {
var element = item.getElement();
var isSearchMatch = !searchFieldValue ? true : (element.getAttribute('data-title') || '').toLowerCase().indexOf(searchFieldValue) > -1;
if (!isSearchMatch) isSearchMatch = (element.getAttribute('data-description') || '').toLowerCase().indexOf(searchFieldValue) > -1;
if (!isSearchMatch) isSearchMatch = (element.getAttribute('data-category') || '').toLowerCase().indexOf(searchFieldValue) > -1;
//lets do treat category/filter as array
var isFilterMatch = !filterFieldValue ? true : (element.getAttribute('data-category') || '').toLowerCase().indexOf(filterFieldValue.toLowerCase())> -1;
return isSearchMatch && isFilterMatch;
});
if (getCount() === 0) {
document.getElementById('noResults').innerHTML = 'NO RESULTS FOLKS!'
} else {
document.getElementById('noResults').innerHTML = ''
}
}
function getCount() {
var returnable = 0;
grid._items.forEach(function(item) {
if (item._isActive) {
returnable += 1
}
})
return returnable;
}
// Generic helper functions
function compareItemTitle(a, b) {
var aVal = a.getElement().getAttribute('data-title') || '';
var bVal = b.getElement().getAttribute('data-title') || '';
return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
}
function compareItemCategory(a, b) {
var aVal = a.getElement().getAttribute('data-category') || '';
var bVal = b.getElement().getAttribute('data-category') || '';
return aVal < bVal ? -1 : aVal > bVal ? 1 : compareItemTitle(a, b);
}
function updateIndices() {
grid.getItems().forEach(function(item, i) {
item.getElement().setAttribute('data-id', i + 1);
item.getElement().querySelector('.card-id').innerHTML = i + 1;
});
}
function elementMatches(element, selector) {
var p = Element.prototype;
return (p.matches || p.matchesSelector || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || p.oMatchesSelector).call(element, selector);
}
function elementClosest(element, selector) {
if (window.Element && !Element.prototype.closest) {
var isMatch = elementMatches(element, selector);
while (!isMatch && element && element !== document) {
element = element.parentNode;
isMatch = element && element !== document && elementMatches(element, selector);
}
return element && element !== document ? element : null;
} else {
return element.closest(selector);
}
}
// Fire it up!
initDemo();
});
<file_sep>#!/usr/bin/env bash
BUCKET="liftedsubarus.com"
DIR=build/
cp -a static/. ./build #copy js & css into build
aws s3 sync $DIR s3://$BUCKET/ --profile personal --acl public-read
<file_sep># [Lifted Subaru](https://liftedsubaru.github.io)
An archive for subaru offroading enthusiasts.
Found this helpful?
[](https://www.paypal.me/devgorilla/1)
## Features
Searchable tiling for articles linked to raw sources with a PDF archive of the thread or build writeup.
Renderer Directory builds the static files from configs and handlebars templates
Create a sitemap and update file via www.xml-sitemaps.com
```
cd renderer
node index.js <-- builds html from json found in renderer/detail-pages
```
I'm doing it this way to keep the site free and static serving from Github Pages
## Detail Pages Config Format
```
{
"title": "title with spaces and thing's",
"description": "title with spaces and thing's",
"category":"ea82",
"url": "title with spaces and shit's",
"author": "Loyale 2.7 Turbo",
"author_link": "https://www.ultimatesubaru.org/forum/profile/13502-loyale-27-turbo",
"original_url": "https://www.google.com",
"archive_url": "/static/archive",
"img":"",
"content": "<p> stuff stuff stuff</p>"
}
```
<file_sep><html lang="en" class="">
<!--
__ _______ _ ____ ___ __ __ _____ _____ ___
\ \ / / ____| | / ___/ _ \| \/ | ____| |_ _/ _ \
\ \ /\ / /| _| | | | | | | | | |\/| | _| | || | | |
\ V V / | |___| |__| |__| |_| | | | | |___ | || |_| |
\_/\_/ |_____|_____\____\___/|_| |_|_____| |_| \___/
_ _ __ _ _ ____ _
| | (_)/ _| |_ ___ __| / ___| _ _| |__ __ _ _ __ _ _ ___ ___ ___ _ __ ___
| | | | |_| __/ _ \/ _` \___ \| | | | '_ \ / _` | '__| | | / __| / __/ _ \| '_ ` _ \
| |___| | _| || __/ (_| |___) | |_| | |_) | (_| | | | |_| \__ \ _ | (_| (_) | | | | | |
|_____|_|_| \__\___|\__,_|____/ \__,_|_.__/ \__,_|_| \__,_|___/ (_) \___\___/|_| |_| |_|
-->
<head>
<link rel="stylesheet" href="/styles/styles.css" type="text/css">
<!-- FAVICON -->
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lifted Subarus- Curated Offroad Subaru Build Guides & Resources</title>
<meta name="description" content="Curated Offroad Subaru Build Guides.">
<meta name="Keywords" content="lifted subaru offroad fabrication 4x4">
<!-- Facebook -->
<meta property="og:title" content=" Fitting an EJ22 Radiator in an L-series " />
<meta property="og:description" content=" EJ22 Swap " />
<meta name="google-site-verification" content="cAoAzBKndIH-Pn4IS2m2kYgLKt-jQEGGcPpMaHA6sjw" />
<meta property="og:image" content="/static/img/guides/ej22radiator/9eaToEjRadiator-min.jpg" />
</head>
<body>
<a href="/index.html">
<h2 id='LS-title' aria="Home" class="section-title"><span>LIFTED SUBARUS</span></h2>
<p style="margin-top:-25px;font-size:.6em;" class="section-title">Curated Offroad Subaru Build Guides</p>
</a>
<div id="accordionWrapper">
<button class="accordion accordion-action">ABOUT</button>
</div>
<div id="about">
<p>In 2017 I bought my first Subaru: a worn-out $440 1987 Subaru DL wagon for the <a href="https://gambler500.com/">OG Oregon Gambler 500</a>. Two weeks later photobucket <a href="https://medium.com/@AxelApp/how-photobucket-broke-the-internet-and-why-you-should-care-4a244bda6b7e">broke the internet</a>, and most of the threads I was relying on to modify the car.</p>
<p>My goal is not to replace <a href="http://www.ultimatesubaru.org/forum">USMB</a>, <a href="https://forums.nasioc.com/">NASIOC</a>, or any other messaging board, but to self host as much content as possible to ensure it doesn't go away again in the future.</p>
<p>This is where you come in. Working on a write-up? Awesome. Post it to your favorite messaging board, and send me it. Lets make sure these writeups don't disappear in the future. Don't own content and just want me to link to it here? cool. Email me your list of your favorite build threads. The focus is on subaru builds, but generic build info like bumpers, tire carriers, fender folding techniques are all welcome.</p>
</br>
<p>Stay Muddy Friends,</p>
<p>-Doug</p>
<img style="margin:0 auto;display:block; width:75%;" alt="lifted subaru 4x4" title="lifted subaru 4x4" src="/static/img/site/elChubra-min.jpg"/>
<br>
<button class="accordionClose accordion-action">X</button>
</div>
<section class="details">
<h1 class="details-headline">Fitting an EJ22 Radiator in an L-series</h1>
<h3 class="details-category"> — L-series</h3>
<div class="details-buttons">
<p class="details-author">by <a href="https://www.instagram.com/dwesleybrown">
<NAME>
</a>
</p>
</div>
<div class="details-content">
<img src="/static/img/guides/ej22radiator/9eaToEjRadiator-min.jpg">
<p>In the fall of 2017 I swapped my tired ea82 for a 160k mile ej22. The swap went well and everything ran reliably until I blew the headgaskets a few months later. I should have changed the headgaskets before swapping, but I like to learn the hard way.</p>
<p>I initially did the swap with the factory ea82 radiator. I had read it was sufficient for the larger engine. Though that may be true, I took the opportunity of an empty engine bay while doing my headgaskets to fit the EJ Radiator in. This will not only help with cooling capacity, but enable the EJ hoses to be used too. The hoses to adapt the EJ22 to EA82 radiator worked, but were somewhat convoluted and made finding hoses difficult. The day I blew my headgasket, started with a hose splitting in half. As a preventative I wanted to build a spare lower. Having to hunt down two separate hoses to frankenstein into a useable one is harder than you may think- especially in an emergency and when time is a factor.</p><p><b>In case you want the secret sauce:</b> EJ22 Upper hose still works with an ea82 radiator, you just need to cut it down a little and use a piece of old hose to adapter the larger diameter hose to the radiator. For the lower, EJ22 hose works still - cut it down a little and splice it together with a 2003 Ford Focus Lower hose. I don't have pictures, but if you get the hoses in your hand you'll know what to do. But don't do that. I think its more of a pain than adapting the EJ22 Radiator.</p>
<h3>Damage</h3>
<p>I drove the 2017 Oregon Gambler 500 (and subsequent Mtn Roo meetups) with a skid plate attached to the factory plate mounts with stock height in the front. As you can see here, the lower radiator support is beaten to hell. It was sitting at the center 1 inch higher than it did the day it left it's home in Japan.</p>
<img src="../static/img/guides/ej22radiator/2eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/3eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/4eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/5eaToEjRadiator-min.jpg"/>
<h3>Measuring</h3>
<p>I over cut the slot in the lower-support to allow for me some wiggle room once I was fine tuning the slot later. The slot was cut because the EJ radiator is roughly 2 inches too tall for the space, even when your lower support isnt beat up. If you aren't pressed for time like I was, I suggest cutting the entire lower support out and building an entirely new cross-member. If you do decide to cut a slot rather than replace the whole support, I found that a 2x4 acts a a pretty decent stand in for the radiator. Keep in mind, it is 1/8th less-wide than the radiator.</p>
<img src="../static/img/guides/ej22radiator/81_x1000.jpg"/>
<img src="../static/img/guides/ej22radiator/10eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/1eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/12eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/15eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/13eaToEjRadiator-min.jpg"/>
<img src="../static/img/guides/ej22radiator/16eaToEjRadiator-min.jpg"/>
<h3>New support</h3>
<p>I ended up cutting the side closest to the engine completely out, and wrapping that with a piece of 1.5x1/8 angle iron and boogering it up liberally with my MIG welder.</p>
<p>Note that the EJ Radiator is attached differently than the EA radiator was. Pins held the EJ to the frame in the car it is meant for from above, the EA is secured from the front with machine bolts. My solution was to weld nuts under my new upper support and have the bolts fit into the EJ bushings.</p><p><b>TIP:</b> The bolts I used needed to be shortened slightly, this can be easily done by threading a nut onto the bolt and cutting it to the desired length. Then when you remove the nut, it chases the threads like a die would. I also sharpened mine to a dull point, so they would self-center in the radiator bushing. </p>
<img src="../static/img/guides/ej22radiator/eaejrad-done-worad-min.jpg"/>
<img src="../static/img/guides/ej22radiator/eaejrad-done-min.jpg"/>
</div>
</section>
<footer>
<a href="mailto:<EMAIL>">Contact</a>
<p style="margin-top:25px;">Found this website helpful?<br><a href="https://www.paypal.me/devgorilla/1" ><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="120" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="120" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555" d="M0 0h21v20H0z"/><path fill="#007ec6" d="M21 0h99v20H21z"/><path fill="url(#b)" d="M0 0h120v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"><text x="115" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="110">☕</text><text x="115" y="140" transform="scale(.1)" textLength="110">☕</text><text x="695" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="890">Donate a buck</text><text x="695" y="140" transform="scale(.1)" textLength="890">Donate a buck</text></g> </svg></a></p>
<div id="ad-wrapper"> 320x50</div>
<div class="disclaimer" >
<p><b><i style="color: #9a9a9d;">DISCLAIMER:</i></b> LiftedSubaru.com has not verified the accuracy of the information contained here. The information contained on liftedsubarus.com represents the views and opinions of the original creators of such content and does not necessarily represent the views or opinions of LiftedSubarus.com (LiftedSubarus). The mere appearance of Content on the Site does not constitute an endorsement by LiftedSubarus or its affiliates of such Content.The Content has been made available for informational and educational purposes only. LiftedSubarus does not make any representation or warranties with respect to the accuracy, applicability, fitness, or completeness of the Content. The Content is not intended to be a substitute for professional advice, diagnosis, or treatment. LiftedSubarus hereby disclaims any and all liability to any party for any direct, indirect, implied, punitive, special, incidental or other consequential damages arising directly or indirectly from any use of the content, which is provided as is, and without warranties.
</div>
<a class="github" href="https://github.com/liftedsubaru/liftedsubarusite">
<p >v1-10.14.18-52.34</p>
</a>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://unpkg.com/muuri@0.6.2/dist/muuri.js"></script>
<script src="/scripts/script.js"></script>
<script src="/scripts/accordion-min.js"></script>
</body>
</html>
<file_sep><html lang="en" class="">
<!--
__ _______ _ ____ ___ __ __ _____ _____ ___
\ \ / / ____| | / ___/ _ \| \/ | ____| |_ _/ _ \
\ \ /\ / /| _| | | | | | | | | |\/| | _| | || | | |
\ V V / | |___| |__| |__| |_| | | | | |___ | || |_| |
\_/\_/ |_____|_____\____\___/|_| |_|_____| |_| \___/
_ _ __ _ _ ____ _
| | (_)/ _| |_ ___ __| / ___| _ _| |__ __ _ _ __ _ _ ___ ___ ___ _ __ ___
| | | | |_| __/ _ \/ _` \___ \| | | | '_ \ / _` | '__| | | / __| / __/ _ \| '_ ` _ \
| |___| | _| || __/ (_| |___) | |_| | |_) | (_| | | | |_| \__ \ _ | (_| (_) | | | | | |
|_____|_|_| \__\___|\__,_|____/ \__,_|_.__/ \__,_|_| \__,_|___/ (_) \___\___/|_| |_| |_|
-->
<head>
<link rel="stylesheet" href="../styles/styles.css" type="text/css">
<link rel="stylesheet" href="http://liftedsubarus.com.s3-website-us-east-1.amazonaws.com/css/font-awesome.min.css" type="text/css">
<!-- FAVICON -->
<link rel="icon" type="image/png" sizes="32x32" href="../favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../favicon/favicon-16x16.png">
<link rel="mask-icon" href="../favicon/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lifted Subarus</title>
</head>
<body>
<a href="./index.html">
<h2 id='LS-title' aria="Home" class="section-title"><span>LIFTED SUBARUS</span></h2>
<p style="margin-top:-25px;font-size:.6em;" class="section-title">Curated Offroad Subaru Build Guides</p>
</a>
<div id="accordionWrapper">
<button class="accordion accordion-action">ABOUT</button>
</div>
<div id="about">
<p>In 2017 I bought my first Subaru: a worn-out $440 1987 Subaru DL wagon for the <a href="https://gambler500.com/">OG Oregon Gambler 500</a>. Two weeks later photobucket <a href="https://medium.com/@AxelApp/how-photobucket-broke-the-internet-and-why-you-should-care-4a244bda6b7e">broke the internet</a>, and most of the threads I was relying on to modify the car.</p>
My goal is not to replace <a href="http://www.ultimatesubaru.org/forum">USMB</a>, <a href="https://forums.nasioc.com/">NASIOC</a>, or any other messaging board, but to self host as much content as possible to ensure it doesn't go away again in the future.
<p>This is where you come in. Working on a write-up? Awesome. Post it to your favorite messaging board, and send me it. Lets make sure these writeups don't disappear in the future. Don't own content and just want me to link to it here? cool. Email me your list of your favorite build threads. The focus is on subaru builds, but generic build info like bumpers, tire carriers, fender folding techniques are all welcome.</p>
</br>
<p>Stay Muddy Friends,</p>
<p>-Doug</p>
<img style="margin:0 auto;display:block; width:75%;" src="../static/img/site/elChubra-min.jpg"/>
<br>
<button class="accordionClose accordion-action">X</button>
</div>
<section class="grid-demo">
<div class="controls cf">
<div class="control search">
<div class="control-icon">
<i class="material-icons"></i>
</div>
<input id="searchBar" class="control-field search-field form-control " type="text" name="search" placeholder="Search..." />
</div>
<div class="control filter">
<div class="control-icon">
<i class="material-icons"></i>
</div>
<div class="select-arrow">
<i class="material-icons"></i>
</div>
<select class="control-field filter-field form-control">
<!--TODO this needs to be created by handlebars-->
<option value="" selected>All Types</option>
<option value="EA81">EA81</option>
<option value="EA82">EA82</option>
<option value="EJ22">EJ22</option>
<option value="EJ25">EJ25</option>
<option value="EJ15">EJ15</option>
<option value="generic build">Generic Build Info</option>
</select>
</div>
</div>
</div>
<div class="grid"></div>
<div id="noResults"></div>
</section>
<footer>
<a href="mailto:<EMAIL>">Submit Writeup</a>
<a href="https://github.com/liftedsubaru/liftedsubarusite" data-animate-hover="pulse" class="external">
<svg class="githubLogo" aria-labelledby="simpleicons-github-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title id="simpleicons-github-icon">GitHub icon</title><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
</a>
<p style="margin-top:25px;">Found this website helpful?<br><a href="https://www.paypal.me/devgorilla/1" ><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="120" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect width="120" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#a)"><path fill="#555" d="M0 0h21v20H0z"/><path fill="#007ec6" d="M21 0h99v20H21z"/><path fill="url(#b)" d="M0 0h120v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"><text x="115" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="110">☕</text><text x="115" y="140" transform="scale(.1)" textLength="110">☕</text><text x="695" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="890">Donate a buck</text><text x="695" y="140" transform="scale(.1)" textLength="890">Donate a buck</text></g> </svg></a></p>
<div id="ad-wrapper"> 320x50</div>
<div class="disclaimer" >
<p><b><i style="color: #9a9a9d;">DISCLAIMER:</i></b> LiftedSubaru.com has not verified the accuracy of the information contained here. The information contained on liftedsubarus.com represents the views and opinions of the original creators of such content and does not necessarily represent the views or opinions of LiftedSubarus.com (LiftedSubarus). The mere appearance of Content on the Site does not constitute an endorsement by LiftedSubarus or its affiliates of such Content.The Content has been made available for informational and educational purposes only. LiftedSubarus does not make any representation or warranties with respect to the accuracy, applicability, fitness, or completeness of the Content. LiftedSubarus does not warrant the performance, effectiveness or applicability of any sites listed or linked to in any Content. The Content is not intended to be a substitute for professional advice, diagnosis, or treatment. Always seek the advice of liscenced mechanic with any questions you may have regarding your vehicle. Never disregard professional advice or delay in seeking it because of something you have read or seen on the Site.</p>
<p>LiftedSubarus hereby disclaims any and all liability to any party for any direct, indirect, implied, punitive, special, incidental or other consequential damages arising directly or indirectly from any use of the Video Content, which is provided as is, and without warranties.</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://unpkg.com/muuri@0.6.2/dist/muuri.min.js"></script>
<script src="../scripts/script.js"></script>
<script src="../scripts/accordion.js"></script>
</body>
</html>
|
a59db2427429873fc234f6d8f54b2894c4e15c98
|
[
"JavaScript",
"HTML",
"Markdown",
"Shell"
] | 5
|
JavaScript
|
liftedsubaru/liftedsubaru.github.io
|
8980f0588a9d4aff7818d7d03ac4f82349088b31
|
27da673286ac9864338d1d7703f1432db59f284e
|
refs/heads/master
|
<repo_name>lvasquezv/mdeis.proyecto-gcs<file_sep>/Vagrantfile
$script = <<-'SCRIPT'
yum -y update
yum -y install java-1.8.0-openjdk-devel
curl https://downloads.lightbend.com/scala/2.12.10/scala-2.12.10.rpm --output scala-2.12.10.rpm
yum -y install scala-2.12.10.rpm
curl https://bintray.com/sbt/rpm/rpm | tee /etc/yum.repos.d/bintray-sbt-rpm.repo
yum -y install sbt
yum install -y git
yum install -y which
yum install -y yum-utils
yum -y install rpm-build
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum install -y docker-ce docker-ce-cli containerd.io
SCRIPT
Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
config.vm.provider "virtualbox" do |v|
v.memory = 2048
v.cpus = 2
config.vm.provision "shell", inline: $script
config.vm.network "forwarded_port", guest: 9000, host: 9000
config.vm.synced_folder "./", "/home/vagrant/proyecto-gcs"
end
end
<file_sep>/README.md
# Ejemplo GCS
Esta aplicación web está basada en la aplicación play-scala-slick-example.
# Compilación
Para compilar el proyecto usamos Vagrant. Desde la consola, ejecutamos el
comando:
$ vagrant up
$ vagrant ssh
La máquina virtual de Vagrant contiene todas las dependencias, incluído Docker,
para ejecutar los tests unitarios y los tests de integración.
Para descargar el código y compilarlo en la máquina de desarrollo provisionada hacemos los
comandos siguientes:
$ git clone https://github.com/mundacho/proyecto-gcs.git
$ cd proyecto-gcs
$ sbt compile
# Lanzamiento de tests unitarios
Para correr los tests unitarios, desde la máquina de Vagrant ejecutamos los comandos
siguientes:
$ sbt test
Esto construye el proyecto y lanza los tests unitarios.
# Lanzamiento de tests de integración
Para correr los tests de integración, primero nos conectamos desde otra consola
y procedemos a iniciar el servidor Docker, y lanzar la base de datos.
$ sudo systemctl start docker
$ sudo docker run -it -e POSTGRES_PASSWORD=gcs -e POSTGRES_USER=gcs -e POSTGRES_DB=gcs -p 127.0.0.1:5432:5432 postgres:9.5
Dejamos Docker corriendo en esa consola y nos conectamos desde otra consola. En
la nueva consola, procedemos a cambiar al directorio donde está el código y
ejecutamos el comando siguiente:
$ sbt "project gcsAppIT" test
Esto lanzará los tests de integración, que requieren de la base de datos para
funcionar.
# Empaquetar
Para empaquetar en RPM debemos usar el comando siguiente:
$ sbt rpm:packageBin
# Instalar en Linux (CentOS)
Para instalar el RPM obtenido solo necesitamos ejecutar el comando siguiente:
$ sudo rpm -i gcs-app-2.8.x-1.noarch.rpm
Luego de instalar tenemos que dar permisos a la aplicación
para ejecutarse en el directorio que va a usar:
$ sudo chown -R gcs-app /usr/share/gcs-app/
$ sudo chgrp -R gcs-app /usr/share/gcs-app/
El archivo de configuración se encuentra en la dirección
siguiente:
/etc/gcs-app/application.conf
Los logs se encuentran en:
/var/log/gcs-app/gcs-app.log
En este archivo se encuentra la configuración para acceder a la base de datos.
# Uso del software instalado en Linux (CentOS)
## Lanzamiento
Podemos lanzar manualmente nuestra aplicación con el comando siguiente
$ sudo systemctl start gcs-app
## Detener
Para detener el servicio:
$ sudo systemctl stop gcs-app
## Reiniciar
Para reiniciar el servicio:
$ sudo systemctl restart gcs-app
## Estado
Para ver el estado del servicio:
$ sudo systemctl status gcs-app
# Desinstalar en Linux
Cuando se va a instalar una nueva versión, es importante desinstalar la versión anterior (si es que se conserva el número de versión). Para esto, usar el comando siguiente:
$ sudo rpm -e gcs-app
<file_sep>/gcs-app/conf/evolutions/default/1.sql
# --- !Ups
CREATE SEQUENCE people_seq;
create table "people" (
"id" bigint not null primary key DEFAULT nextval('people_seq'),
"name" varchar not null,
"age" int not null
);
# --- !Downs
drop table "people" if exists;
|
d3959e7feb4175ffc9ba965f3f9d3e88bd0a915e
|
[
"Markdown",
"SQL",
"Ruby"
] | 3
|
Ruby
|
lvasquezv/mdeis.proyecto-gcs
|
92a6e729ccf7b0a011f5fc9e8db57e2dcf97e48e
|
f7889049d650efd39e1ccbf36f792724607bc863
|
refs/heads/master
|
<repo_name>jkshan/GBAssig<file_sep>/SentenceParser.Business/Validation/SentenceValidator.cs
using SentenceParser.Business.DTO;
namespace SentenceParser.Business.Validation
{
public class SentenceValidator
{
public ValidationResult Validate(string sentence)
{
var result = new ValidationResult();
if(string.IsNullOrWhiteSpace(sentence))
{
result.ErrorMessage.Add("Sentence cannot be empty");
}
result.IsValid = result.ErrorMessage.Count == 0;
return result;
}
}
}
<file_sep>/SentenceParser.Web/Controllers/SentenceParserController.cs
using SentenceParser.Business;
using SentenceParser.Business.Validation;
using SentenceParser.Infrastructure;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SentenceParser.Controllers
{
[Authorize]
public class SentenceParserController : Controller
{
public ActionResult Parse()
{
return View();
}
// POST: SentenceParser/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Parse(HttpPostedFileBase file)
{
try
{
if(file == null || file.ContentLength == 0)
{
ViewBag.ErrorMessage = "Please Select Valid File";
return View();
}
if(!file.FileName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
ViewBag.ErrorMessage = "File Type Not Supported";
return View();
}
if((file.InputStream.Length) > Convert.ToInt32(ConfigHelper.GetValue("MaxSize")))
{
ViewBag.ErrorMessage = "File size exceeded the allowed limit";
return View();
}
string sentence = new StreamReader(file.InputStream).ReadToEnd();
var logger = new LogHelper();
logger.WriteLog(sentence);
var Validator = new SentenceValidator();
var validationResult = Validator.Validate(sentence);
sentence = null;
if(validationResult.IsValid)
{
var parser = new Parser(file.InputStream);
var result = parser.CountWords();
return View("Success", result);
}
else
{
ViewBag.ErrorMessage = validationResult.ErrorMessage.Aggregate((a, b) => a + "," + b);
return View();
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Exception occurred, please contact admin";
return View();
}
}
}
}
<file_sep>/SentenceParser.Business/Parser.cs
using Microsoft.VisualBasic.FileIO;
using SentenceParser.Business.DTO;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace SentenceParser.Business
{
public class Parser
{
Stream _fileStream;
public Parser(Stream inputStream)
{
_fileStream = inputStream;
}
/// <summary>
/// Reads the stream Line by line
/// </summary>
/// <returns>Array of word get by delimited by ' '(space)</returns>
private IEnumerable<string[]> Readline()
{
using(var textFieldParser = new TextFieldParser(_fileStream))
{
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.Delimiters = new[] { " " };
textFieldParser.HasFieldsEnclosedInQuotes = true;
while(!textFieldParser.EndOfData)
{
yield return textFieldParser.ReadFields();
}
}
}
/// <summary>
/// Counts the unique words in a sentence by ignoring the word in exclude logic.
/// </summary>
/// <returns>Words of Max,Min and Median occurrence with their count.</returns>
public Result CountWords()
{
// To Hold the Unique Words with Count.
var wordCollection = new Dictionary<string, long>();
//Reset the stream position, before start reading.
_fileStream.Position = 0;
foreach(var item in Readline())
{
foreach(var word in item)
{
if(NotInExcludeLogic(word)) //Check for exclude logic.
{
if(wordCollection.ContainsKey(word))
{
wordCollection[word]++;
}
else
{
wordCollection.Add(word, 1);
}
}
}
}
var result = new Result();
if(wordCollection.Count() == 0)
{
return result;
}
result.MaxCount = wordCollection.Values.Max();
result.MinCount = wordCollection.Values.Min();
var distinctCounts = wordCollection.Values.Distinct();
result.MedianCount = distinctCounts.OrderBy(i => i).ElementAt(distinctCounts.Count() / 2);
result.MaxOccuredWords = Filter(wordCollection, result.MaxCount);
result.MinOccuredWords = Filter(wordCollection, result.MinCount);
result.MedianOccuredWords = Filter(wordCollection, result.MedianCount);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="RecordDictionary"></param>
/// <param name="Count"></param>
/// <returns>Returns the Comma separated string of the Record collection based on the Count Value passed.</returns>
private string Filter(Dictionary<string, long> RecordDictionary, long Count)
{
return RecordDictionary.Where(i => i.Value == Count)
.Select(i => i.Key)
.Aggregate((a, b) => a + "," + b);
}
/// <summary>
/// Returns false if the word input word matches any of the exclusion pattern
/// </summary>
/// <param name="word"></param>
/// <returns>Returns false if the word input word matches any of the exclusion pattern</returns>
private static bool NotInExcludeLogic(string word)
{
//Matches 1234-5678-9012-3456, 1234567890123456
if(Regex.IsMatch(word, @"^[0-9]{4}([\-]?[0-9]{4}){3}$"))
{
return false;
}
//Matches Password expression that requires one lower case letter, one upper case letter, one digit, 4-14 length.
if(Regex.IsMatch(word, @"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,14}$"))
{
return false;
}
return true;
}
}
}
<file_sep>/SentenceParser.Web/Infrastructure/LogHelper.cs
using System;
using System.IO;
using System.Text;
using System.Web;
namespace SentenceParser.Infrastructure
{
public class LogHelper
{
string _path, _fileName;
public LogHelper() : this(HttpContext.Current.Server.MapPath("Logs"), DateTime.Now.ToString("dd-MM-yyyy") + ".txt")
{
}
public LogHelper(string Path, string FileName)
{
_path = Path;
_fileName = FileName;
}
public void WriteLog(string message)
{
try
{
if(!string.IsNullOrEmpty(message))
{
if(!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
if(!_path.EndsWith("\\"))
{
_path += "\\";
}
using(StreamWriter sw = new StreamWriter(string.Concat(_path, _fileName), true, Encoding.UTF8))
{
sw.WriteLine(string.Format("[{0}]: {1}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), message));
sw.Close();
}
}
}
catch(Exception ex)
{
}
}
}
}<file_sep>/SentenceParser.Business/DTO/ValidationResult.cs
using System.Collections.Generic;
namespace SentenceParser.Business.DTO
{
public class ValidationResult
{
public ValidationResult()
{
ErrorMessage = new List<string>();
}
public bool IsValid { get; set; }
public List<string> ErrorMessage { get; set; }
}
}
<file_sep>/SentenceParser.Business/DTO/Result.cs
namespace SentenceParser.Business.DTO
{
public class Result
{
public long MaxCount { get; internal set; }
public string MaxOccuredWords { get; internal set; }
public long MedianCount { get; internal set; }
public object MedianOccuredWords { get; internal set; }
public long MinCount { get; internal set; }
public object MinOccuredWords { get; internal set; }
}
}
<file_sep>/SentenceParser.Web/Infrastructure/ConfigHelper.cs
using System.Configuration;
namespace SentenceParser.Infrastructure
{
public class ConfigHelper
{
public static string GetValue(string Key)
{
return ConfigurationManager.AppSettings[Key];
}
}
}
|
0bcc3efe805a28395be985118dc69b6db600a2b4
|
[
"C#"
] | 7
|
C#
|
jkshan/GBAssig
|
4eea0b56bcd79a5ae7c30148c2fba6108cbe1562
|
e16793c80f404845bff0232940b1a62656f9fe57
|
refs/heads/master
|
<file_sep>import firebase from 'firebase/app'
import 'firebase/firestore'
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyASwXXAS_TAkjaCYt46d9IwTi5klrre7mk",
authDomain: "react-ecomm-e357f.firebaseapp.com",
projectId: "react-ecomm-e357f",
storageBucket: "react-ecomm-e357f.appspot.com",
messagingSenderId: "515977659001",
appId: "1:515977659001:web:b2665ade2714e009f14aa8"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase
//old array of products
/*const productsAr = [
{
id: 1,
name: `Pilot Fountain Pen Kakuno`,
ins: 68.50,
description: `Sailor Japanese Pen Company takes pride in the professionally skilled craftsman who ensure each nib is perfect.`,
rating: 5.0,
colours: [ `black`, `white` ],
img: `product01.jpg`,
}, {
id: 2,
name: `Pilot Metropolitan`,
ins: 30.00,
description: `Includes one proprietary Pilot squeeze converter for use with bottled ink, and one proprietary ink cartridge.`,
rating: 2.5,
colours: [ `silver`, `white`, `blue`] ,
img: `product02.jpg`,
}, {
id: 3,
name: `Lamy Z24 Converter`,
ins: 20.90,
description: `Century 37760oe converter with purchase.`,
rating: 3.5,
colours: [`black` ],
img: `product03.jpg`,
}, {
id: 4,
name: `Noodler's Ahab Flex Fountain Pen`,
ins: 39.00,
description: `This pen is a great way to get into the world of flex pens - writes like a fine nib with minimal pressure.`,
rating: 5.0,
colours: [ `gold`, `black`] ,
img: `product04.jpg`,
}, {
id: 5,
name: `Pilot Metropolitan - Plain`,
ins: 30.00,
description: `The Pilot Metropolitan is a great starter pen. With its sleek metal body, easy snap cap, and smooth nib it's a perfect everyday writer.`,
rating: 4.9,
colours: [ `rd`, `white`, `blue` ],
img: `product05.jpg`,
}, {
id: 6,
name: `Lamy Al-Star Fountain Pen`,
ins: 21.00,
description: `With one of the smoothest nibs in its price range, it has the additional bonus of easily interchangeable nibs.`,
rating: 4.2,
colours: [ `gold`, `silver` ],
img: `product06.jpg`,
}, {
id: 7,
name: `Kaweco Classic Sport Fountain Pen`,
ins: 33.50,
description: `Aptly named their "classic" fountain pen, the Sport has been an icon of the Kaweco brand for more than 80 years.`,
rating: 4.5,
colours: [ `red`],
img: `product07.jpg`,
}, {
id: 8,
name: `<NAME>`,
ins: 25.90,
description: `Parker Jotter Fountain Pen - Bond Street Black CT. Comes with: 1 cartridge.`,
rating: 4.4,
colours: [ `silver`],
img: `product08.jpg`,
}, {
id: 9,
name: `Faber-Castell School Fountain Pen`,
ins: 20.00,
description: `A perfect starter pen, with an ergonomic triangular rubberised grip.`,
rating: 3.0,
colours: [ `red`, `white`, `blue` ],
img: `product09.jpg`,
}, {
id: 10,
name: `<NAME>`,
ins: 49.50,
description: `It's a pen in every veteran writer's collection and its price makes it a top choice for new writers.`,
rating: 4.6,
colours: [ `silver`, `white`, `black` ],
img: `product10.jpg`,
}, {
id: 11,
name: `Kaweco Brass Sport Fountain Pen`,
ins: 82.50,
description: `The Kaweco Brass Sport is made from solid brass with a raw finish that will darken and develop a unique patina over time, giving it an antique, vintage feel.`,
rating: 4.9,
colours: [ `gold`, `white` ],
img: `product11.jpg`,
}, {
id: 12,
name: `<NAME>`,
ins: 18.00,
description: `Like Pilot, Platinum produces their nibs in-house, which lets them create remarkably smooth and consistent nibs at shockingly affordable prices.`,
rating: 3.5,
colours: [ `silver`, `white`, `blue`,`red`] ,
img: `product12.jpg`,
}, {
id: 13,
name: `<NAME>`,
ins: 20.90,
description: `TWSBI (pronounced “twiz-bee”) has quickly earned a reputation with their own-brand pens for providing high-end features and eye-catching designs at budget-friendly prices.`,
rating: 4.5,
colours: [`black`, `white` ],
img: `product13.jpg`,
}, {
id: 14,
name: `<NAME>`,
ins: 29.00,
description: `This funky fountain pen is sure to put a smile on your face whenever you use it. Despite its unusual design, it’s actually quite comfortable to hold whether you’re right- or left-handed.`,
rating: 2.0,
colours: [ `red`, `blue`] ,
img: `product14.jpg`,
}, {
id: 15,
name: `Noodler's Triple Tail Flex Fountain Pen`,
ins: 55.00,
description: `Featuring a special three-tined flex nib, the Triple Tail offers excellent line variation and a generous ink flow to keep up with the demands of flex nib calligraphy.`,
rating: 4.9,
colours: [ `white` ],
img: `product15.jpg`,
}, {
id: 16,
name: `Pilot Custom 912 Fountain Pen - Black Body - Falcon Nib`,
ins: 90.00,
description: `Part of Pilot's "Custom" family of high-quality gold nib fountain pens, the Custom 912 features a sleek and stylish combination of black resin and rhodium trim. What it's best known for, however, is its wide selection of interesting and exotic nibs.`,
rating: 4.4,
colours: [ `black` ],
img: `product16.jpg`,
}, {
id: 17,
name: `Noodler's Konrad Flex Fountain Pen - Ivory Darkness`,
ins: 20.50,
description: `Noodler's flex pens are ideal for fountain pen enthusiasts who enjoy tinkering with their pens. `,
rating: 4.5,
colours: [ `black`, `white`],
img: `product17.jpg`,
}, {
id: 18,
name: `Sailor Pro Gear Slim Shikiori Fountain Pen - 14k Medium Fine Nib`,
ins: 199.90,
description: `This pen's beautiful resin construction is complemented by warm 24k gold-plated accents. Its medium-fine nib is perfect for everyday writing and drawing.`,
rating: 5.0,
colours: [ `gold`],
img: `product18.jpg`,
}, {
id: 19,
name: `Pilot Vanishing Point Fountain Pen - Black Matte - Fine Nib`,
ins: 90.00,
description: `This Vanishing Point retractable fountain pen from Pilot features a beautifully designed metal body with a modern, sophisticated matte black finish.`,
rating: 4.9,
colours: [ `black` ],
img: `product19.jpg`,
}, {
id: 20,
name: `Pilot Parallel Pen - 2.4 mm Nib`,
ins: 10.50,
description: `The Pilot Parallel calligraphy pen features a unique nib comprised of two parallel metal plates. This allows it to distribute ink more evenly than conventional metal italic nibs while also being crisper and far more durable than a felt-tipped calligraphy pen.`,
rating: 3.6,
colours: [ `white` ],
img: `product20.jpg`,
}
] */<file_sep>import React from 'react'
const SearchFilter = () => {
return (
<div className="filters">
<form>
<h2>Filters</h2>
<div className="filter-options">
<fieldset>
<span className="material-icons-round">search</span>
<input type="search" name="search" id="filterName" placeholder="Search" value={query} onChange={handleQueryChange} className="field search" autoComplete="off" />
</fieldset>
<fieldset className="colour-field" onChange={handleColourChange}>
<legend>Colour</legend>
<ul className="filter-list">
<li>
<label htmlFor="black" className="color-opt">Black
<input type="checkbox" name="colour" value="black" id="black" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="white" className="color-opt">White
<input type="checkbox" name="colour" value="white" id="white" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="silver" className="color-opt">Silver
<input type="checkbox" name="colour" value="silver" id="silver" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="gold" className="color-opt">Gold
<input type="checkbox" name="colour" value="gold" id="gold" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="red" className="color-opt">Red
<input type="checkbox" name="colour" value="red" id="red" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="blue" className="color-opt">Blue
<input type="checkbox" name="colour" value="blue" id="blue" />
<span className="checkmark"></span>
</label>
</li>
</ul>
</fieldset>
<fieldset className="rating-field" onChange={handleRatingChange}>
<legend>Ratings (and above)</legend>
<ul className="filter-list" id="ratingFilter">
<li>
<label htmlFor="aboveFour" className="rating-opt">
<input type="radio" name="rating" value="4" id="aboveFour" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveThree" className="rating-opt">
<input type="radio" name="rating" value="3" id="aboveThree" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveTwo" className="rating-opt">
<input type="radio" name="rating" value="2" id="aboveTwo" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveOne" className="rating-opt">
<input type="radio" name="rating" value="1" id="aboveOne" />
<span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
</ul>
</fieldset>
</div>
<fieldset className="sort-field">
<label htmlFor="sort">Show</label>
<select name="sort" id="sort" className="field dropdown" defaultValue="newest" onChange={handleSortChange}>
<option value="newest">Best Selling</option>
<option value="price-high">Price, highest to lowest</option>
<option value="price-low">Price, lowest to highest</option>
<option value="newest">Newest releases</option>
</select>
</fieldset>
</form>
</div>
)
}
export default SearchFilter<file_sep>import React, {useState}from 'react'
import ProductRow from 'components/ProductRow'
import Pagination from 'components/Pagination'
const SearchResults = ({result}) => {
const [pageNum, setPageNum] = useState(1)
const sliceSize = 8
const totalSize = result.length
const start = (pageNum - 1) * sliceSize
const end = start + sliceSize
//page 1
const theProduct = result.slice(start,end).map((product) => <ProductRow key={product.id} data={product} />)
// Pagination is next
// How many are in the original set (total that meet the criteria)?
// How many to display per page?
// What page are we currently showing?
const updatePage = (page) => {
if
(page <= 0) setPageNum(1)
else if
(page > Math.ceil(totalSize / sliceSize)) setPageNum(Math.ceil(totalSize / sliceSize))
else
setPageNum(page)
}
return (
<>
<div className="results">
<section >
<h2 className="subheading">Results</h2>
<p id="numProducts" >
{theProduct.length} {(theProduct.length === 1) ? `product` : `products`} of {totalSize} products found
</p>
<ul id="productsTable" className="productGrid">{theProduct}</ul>
</section>
<div className="nav-buttons" style={{textAlign: `center`}}>
<p id="numProducts" >
Page {pageNum} of {(Math.ceil(totalSize / sliceSize) === 0) ? `1` : (Math.ceil(totalSize / sliceSize))}
<br /><button onClick={()=> updatePage(pageNum-1)}>Previous Page</button><button onClick={()=> updatePage(pageNum+1)} >Next Page</button></p>
</div>
</div>
{/*<Pagination />*/}
</>
)
}
export default SearchResults<file_sep>import React, {useState} from 'react'
import Layout from 'components/Layout'
import SearchResults from 'components/SearchResults'
//import SearchField from 'components/SearchField'
import ProductHeader from 'img/product-detail03.jpg'
import SearchFilter from '../components/SearchFilter'
const Products = ({data}) => {
// ****** FILTER STATES *******
// The state of each filter
const [searchState, setSearchState] = useState({
minRating: 0.0,
query: ``,
colourss: [],
sort: (a, b) => a.ins - b.ins
})
// For convenience, destructure all of the values into local variables
const {minRating, query, colourss, sort} = searchState
// ****** FILTER ******
// Filter the results into a new array that's the same size or smaller
const searchResult = data
.filter(({rating}) => rating >= Number(minRating))
.filter(({name}) => name.toUpperCase().includes(query.toUpperCase()))
.filter(({colours}) => colourss.length === 0 ||
colours.filter((colour) => colourss.includes(colour)).length > 0)
.sort(sort)
// ****** EVENT LISTENERS *******
const handleRatingChange = (event) => {
setSearchState({
...searchState,
minRating: Number(event.target.value),
})
}
const handleQueryChange = (event) => {
//setQuery(event.target.value)
setSearchState({
...searchState,
query: event.target.value
})
}
const handleColourChange = ({target}) => {
//setQuery(event.target.value)
if (target.checked) {
setSearchState({
...searchState,
colourss: [...searchState.colourss, target.value]
})
} else {
setSearchState({
...searchState,
colourss: searchState.colourss.filter((colour) => colour !== target.value)
})
}
}
const handleSortChange = ({target}) => {
let sorting
if (target.value === `price-low`) {
sorting = (a, b) => a.ins - b.ins
} else if (target.value === `price-high`) {
sorting = (a, b) => b.ins - a.ins
}
setSearchState({
...searchState,
sort: sorting
})
}
return (
<Layout>
<header className="heading">
<h1>Fountain Pens</h1>
<div className="fill"><img className="fill" src={ProductHeader} alt="Pens on paper Banner" /></div>
</header>
<div className="products">
<div className="filters">
<form>
<h2>Filters</h2>
<div className="filter-options">
<fieldset>
<span className="material-icons-round">search</span>
<input type="search" name="search" id="filterName" placeholder="Search" value={query} onChange={handleQueryChange} className="field search" autoComplete="off" />
</fieldset>
<fieldset className="colour-field" onChange={handleColourChange}>
<legend>Colour</legend>
<ul className="filter-list">
<li>
<label htmlFor="black" className="color-opt">Black
<input type="checkbox" name="colour" value="black" id="black" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="white" className="color-opt">White
<input type="checkbox" name="colour" value="white" id="white" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="silver" className="color-opt">Silver
<input type="checkbox" name="colour" value="silver" id="silver" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="gold" className="color-opt">Gold
<input type="checkbox" name="colour" value="gold" id="gold" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="red" className="color-opt">Red
<input type="checkbox" name="colour" value="red" id="red" />
<span className="checkmark"></span>
</label>
</li>
<li>
<label htmlFor="blue" className="color-opt">Blue
<input type="checkbox" name="colour" value="blue" id="blue" />
<span className="checkmark"></span>
</label>
</li>
</ul>
</fieldset>
<fieldset className="rating-field" onChange={handleRatingChange}>
<legend>Ratings (and above)</legend>
<ul className="filter-list" id="ratingFilter">
<li>
<label htmlFor="aboveFour" className="rating-opt">
<input type="radio" name="rating" value="4" id="aboveFour" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveThree" className="rating-opt">
<input type="radio" name="rating" value="3" id="aboveThree" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveTwo" className="rating-opt">
<input type="radio" name="rating" value="2" id="aboveTwo" />
<span className="material-icons-round">star</span><span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
<li>
<label htmlFor="aboveOne" className="rating-opt">
<input type="radio" name="rating" value="1" id="aboveOne" />
<span className="material-icons-round">star</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span><span className="material-icons-round">star_border</span>
</label>
</li>
</ul>
</fieldset>
</div>
<fieldset className="sort-field">
<label htmlFor="sort">Show</label>
<select name="sort" id="sort" className="field dropdown" defaultValue="newest" onChange={handleSortChange}>
<option value="newest">Best Selling</option>
<option value="price-high">Price, highest to lowest</option>
<option value="price-low">Price, lowest to highest</option>
<option value="newest">Newest releases</option>
</select>
</fieldset>
</form>
</div>
<SearchResults result={data} />
</div>
</Layout>
)
}
export default Products<file_sep>import React from 'react'
import styled from 'styled-components'
const Favorite = ({onClick, favourited}) => {
return (
<Favourite onClick={onClick}>
<span className={`material-icons ${(favourited) && `fav`}`}>favorite</span>
</Favourite>
)
}
const Favourite = styled.button`
padding: 0;
background: none;
border: none;
color: rgba(255,255,255,0.2);
* {
vertical-align: bottom;
}
.fav {
color: red;
}
`
export default Favorite<file_sep>import React, { useState, useContext } from 'react'
import Layout from 'components/Layout'
import { Link } from 'react-router-dom'
import userContext from 'contexts/UserContext'
const Cart = () => {
const user = useContext(userContext).data
console.log(user)
const useMoney = (cents) => {
return `$ ${cents.toFixed(2)}`
}
let subtotal = 0
const mappedProducts = (user.userCart.map(item => {
subtotal += item.ins
return (<li key={item.id}><b>{item.name}</b>({item.count} x {useMoney(item.ins)})<b>{(item.ins)}</b></li> )})
)
return (
<Layout>
<div className="center">
<h2>Your Cart</h2>
<div>
<ul className="cartRow">
{(user.userCart.length) ? (mappedProducts) : (<div>No items in your cart, try going to the <Link to="/">shop</Link></div> ) }
</ul>
{Boolean(user.userCart.length) && <button style={{float: 'right', fontSize: `1em`}}>Check out {useMoney(subtotal)} </button>}
</div>
</div>
</Layout>
)
}
export default Cart<file_sep>import React from 'react'
const SearchField = () => {
return (
<fieldset>
<input type="search" name="search" id="filterName" placeholder="Search" value={query} onChange={handleQueryChange} className="field search" autocomplete="off" />
<button type="button"><span className="material-icons-round">search</span></button>
</fieldset>
)
}
export default SearchField<file_sep>import React, {useContext} from 'react'
import { Link } from 'react-router-dom'
import ScriptaLogo from 'img/Scripta-logo.svg'
import Favorite from 'img/favorite.svg'
import Cart from 'img/cart.svg'
import userContext from 'contexts/UserContext'
import {useParams} from 'react-router'
const Header = ({data}) => {
const user = useContext(userContext).data
const {numFavs} = useContext(userContext)
const {numItems} = useContext(userContext)
function menuToggle() {
document.getElementById("menu").classList.toggle("show");
}
return (
<header className="page-header">
<a href="/" className="logo"><img src={ScriptaLogo} alt="Scripta Logo" width="130" /></a>
<div className="dropdown-menu">
<button type="button" className="nav-toggle" onClick={menuToggle}>
<span className="material-icons-round">menu</span>
</button>
<nav aria-label="Primary" className="navigation" id="nav-toggle">
<ul className="menu" id="menu">
<li><a href="/">Shop</a>
<ul className="submenu">
<li><a href="/">Fountain Pens</a></li>
<li><a href="/">Calligraphy Pens</a></li>
<li><a href="/">Inks</a></li>
</ul>
</li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</div>
<ul className="your-products">
<li style={{ whiteSpace: `nowrap`, textTransform: `capitalize`}} >Welcome, <b>{user.username}</b>!</li>
<li><img src={Favorite} alt="Favorites" width="30" /><span>{Boolean(numFavs) && numFavs}</span></li>
<li><Link to="/cart" style={{textDecoration: `none`, fontWeight: `bold`}}><img src={Cart} alt="Shopping Cart" width="30" /><span >{Boolean(numItems) && numItems}</span></Link></li>
</ul>
</header>
)
}
export default Header<file_sep>import React, {useState} from 'react'
import Favorite from 'img/favorite.svg'
import Cart from 'img/cart.svg'
const ProductButtons = ({value=false, style, ...otherProps}) => {
// Store the current state of the favourite button
const [isFavourite, setIsFavourite] = useState(value)
// Set some basic styles, as well as allow for custom styles (via "style" prop) as well
const cssStyle = {
font: `inherit`,
cursor: `pointer`,
...style
}
// Handle inverting the isFavourite state variable
const invertFav = (event) => {
setIsFavourite( !isFavourite )
// flip a boolean using the NOT operator (!)
}
const handleFavouriteClick = (id) => {
// Favorite toggle
console.log(id)
}
return (
<footer className="productbuttons">
<button type="button" onClick={() => updater(id)}><img src={Cart} alt="Shopping Cart" width="24" /> Add to Cart</button>
<button type="button" onClick={() => handleFavouriteClick(id)} style={cssStyle} {...otherProps}>{(isFavourite) ? `❤️` : `🤍`
}</button>
</footer>
)
}
export default ProductButtons<file_sep>import React from 'react'
const Footer = () => {
return (
<footer className="page-footer">
<ul className="social">
<li><a className="page-footer" href="#"><span className="material-icons-round">face</span> Facebook</a></li>
<li><a className="page-footer" href="#"><span className="material-icons-round">camera_alt</span> Instagram</a></li>
<li><a className="page-footer" href="#"><span className="material-icons-round">alternate_email</span> Twitter</a></li>
</ul>
<nav aria-label="Legal">
<ul className="legal">
<li><a className="page-footer" href="#">Terms of Use</a></li>
<li><a className="page-footer" href="#">Privacy Policy</a></li>
<li><a className="page-footer" href="#">Accessibility Policy</a></li>
</ul>
</nav>
<p className="copyright">Scripta © Copyright, {(new Date()).getFullYear()}.</p>
</footer>
)
}
export default Footer<file_sep>import React, {createContext, useState} from 'react'
const UserContext = createContext(null)
/*
const [userData, setUserData] = useState({
id:123,
username: `toki`,
photo: `user.png`,
userFav: [],
userCart: [],
});
return {
<UserContext.Provider value=({data})
}
*/
export default UserContext<file_sep>import React from 'react'
import Layout from 'components/Layout'
const Fail = () => {
return (
<Layout>
<h1>Woops</h1>
<h3>this page does not exist</h3>
<a href="/index.html">Go to main page</a>
</Layout>
)
}
export default Fail <file_sep>import React, {useState, useEffect} from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import UserContext from 'contexts/UserContext'
import Products from 'pages/Products'
import OneProduct from 'pages/OneProduct'
import Cart from 'pages/Cart'
import Fail from 'pages/Fail'
import firebase from 'utils/firebase'
const App = () => {
//All Product Data
const [productsAr, setProductsAr] = useState([])
//firestore connection
const db = firebase.firestore()
//pull once
useEffect(() => {
//READ
db.collection(`products`).get().then((snapshot) => {
setProductsAr(
snapshot.docs.reduce((products,doc) => [... products, doc.data()], [])
)
})}, [])
//user?
const [userData, setUserData] = useState({
id:123,
username: `toki`,
photo: `user.png`,
userFav: [ ],
userCart: [ ],
});
const handleAddCart = (id) => {
const cproduct = productsAr.find(product => product.id === id)
console.log(cproduct)
setUserData({...userData, userCart: [...userData.userCart, cproduct]})
}
const toggleFavourite = (id) => {
console.log(id)
if (userData.userFav.includes(id)) {
// remove
setUserData({...userData, userFav: userData.userFav.filter((fav) => fav !== id)})
} else {
// Add
setUserData({...userData, userFav: [...userData.userFav, id]})
}
}
const numFavs = userData.userFav.length
const numItems = userData.userCart.length
//handleAddCart:handleAddCart, toggleFavourite:toggleFavourite, handleAddCart:handleAddCart
return (
<Router>
<UserContext.Provider value={{data:userData, toggleFavourite:toggleFavourite, numFavs:numFavs, numItems:numItems, handleAddCart:handleAddCart}}>
<Switch>
<Route exact path="/"><Products data={productsAr} /></Route>
<Route path="/oneproduct/:slug">
<UserContext.Provider value={{data:productsAr}}>
<OneProduct data={productsAr}/>
</UserContext.Provider>
</Route>
<Route path="/cart"><Cart data={userData}/></Route>
<Route path="*"><Fail /></Route>
</Switch>
</UserContext.Provider>
</Router>
)
}
export default App
|
172f6eb5a6a77674c3d9097a088500c6f635ed17
|
[
"JavaScript"
] | 13
|
JavaScript
|
motokwolf/ecomm-REACT
|
5a7c94ba3cebf9d66b7230b87a0f1df4b47218e3
|
76a093a3e7006c0c7c66c924b0a6b8750ab8fb0b
|
refs/heads/master
|
<repo_name>plato4ever/DockerProject<file_sep>/SequoiaDB/Dockerfile
FROM centos/systemd
MAINTAINER zhaolp <<EMAIL>>
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo "Asia/ShangHai" > /etc/timezone
ENV PASSWD "<PASSWORD>"
RUN curl http://sequoiadb.b0.upaiyun.com/images/sequoiadb-2.6.2/x86_64/sequoiadb-2.6.2-linux_x86_64-installer.tar.gz -o sequoiadb-2.6.2-linux_x86_64-installer.tar.gz
RUN tar -xvzf sequoiadb-2.6.2-linux_x86_64-installer.tar.gz
RUN echo -e "<PASSWORD>${PASSWD}\n${PASS<PASSWORD>" |./sequoiadb-2.6.2-linux_x86_64-installer.run --SMS true
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
EXPOSE 8080 11790 11800 11810 11820
CMD ["/usr/sbin/init"]
<file_sep>/jdk/ibmjdk/1.7/Dockerfile
## Alpine Linux with ibmjdk1.7
FROM airdock/base:jessie
MAINTAINER zhaoliping <<EMAIL>>
USER root
RUN cd /tmp && \
curl -L -O -H "Cookie: oraclelicense=accept-securebackup-cookie" -k "http://www.gzvit.com/download/ibmjdk.tar.gz" && \
mkdir -p /usr/local/jdk && \
tar -xvf ibmjdk.tar.gz -C /usr/local/jdk && \
rm -rf ibmjdk.tar.gz
## Set JAVA_HOME environment
ENV JAVA_HOME /usr/local/jdk/ibmjdk
ENV PATH ${PATH}:${JAVA_HOME}/bin
## Set up Locale
ENV LANG en_US.UTF-8
ENV LC_ALL en_US.UTF-8
## Set china timezone
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
<file_sep>/redis/redis-cluster/Dockerfile
FROM ruby:2.2.5
MAINTAINER zhaolp <<EMAIL>>
RUN gem install redis
ENV REDIS_VERSION 4.0.1
ENV REDIS_DOWNLOAD_URL http://download.redis.io/releases/redis-4.0.1.tar.gz
ENV REDIS_DOWNLOAD_SHA 2049cd6ae9167f258705081a6ef23bb80b7eff9ff3d0d7481e89510f27457591
RUN wget -O redis.tar.gz "$REDIS_DOWNLOAD_URL"; \
echo "$REDIS_DOWNLOAD_SHA *redis.tar.gz" | sha256sum -c -; \
mkdir -p /usr/local/redis; \
tar -xzf redis.tar.gz -C /usr/local/redis --strip-components=1; \
rm redis.tar.gz;
<file_sep>/mysql/5.7/Dockerfile
FROM mysql:5.7.17
MAINTAINER zhaolp <<EMAIL>>
RUN sed -i '2i\lower_case_table_names=1' /etc/mysql/conf.d/docker.cnf
RUN sed -i "3i\sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'" /etc/mysql/conf.d/docker.cnf
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo "Asia/ShangHai" > /etc/timezone
EXPOSE 3306
CMD ["mysqld"]
<file_sep>/SequoiaDB/entrypoint.sh
#!/bin/bash
systemctl enable sdbcm
systemctl restart sdbcm
<file_sep>/haproxy/rabbitmq/Dockerfile
FROM haproxy:1.7.9-alpine
MAINTAINER zhaolp <<EMAIL>>
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo "Asia/ShangHai" > /etc/timezone
RUN mkdir -p /run/haproxy/
RUN mkdir -p /var/lib/haproxy
EXPOSE 4561 14561 8086 8080 80 443 8443 1080
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
<file_sep>/mysql/percona-xtradb-cluster/Dockerfile
FROM perconalab/percona-xtradb-cluster:5.6
MAINTAINER zhaolp <<EMAIL>>
RUN sed -i '2i\lower_case_table_names=1' /etc/my.cnf
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo "Asia/ShangHai" > /etc/timezone
|
ec5ca71f1fe46ce425a4644b1a054cc9e42126d7
|
[
"Dockerfile",
"Shell"
] | 7
|
Dockerfile
|
plato4ever/DockerProject
|
7dec0e82053fa7501d619880b16bb23825e95558
|
abdd6709ee4a8f5b01d3286549e32e9ccf6d2380
|
refs/heads/main
|
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Student } from 'models';
export interface DashbordStatistics {
maleCount: number;
femaleCount: number;
hightMarkCount: number;
lowMarkCount: number;
}
export interface RankingByCity {
cityId: string;
cityName: string;
rankingList: Student[];
}
export interface DashbordSate {
loading: boolean;
dashbordStatistics: DashbordStatistics;
hightMarkStudentList: Student[];
lowMarkStudentList: Student[];
rankingByCities: RankingByCity[];
}
const initialState: DashbordSate = {
loading: false,
dashbordStatistics: {
maleCount: 0,
femaleCount: 0,
hightMarkCount: 0,
lowMarkCount: 0,
},
hightMarkStudentList: [],
lowMarkStudentList: [],
rankingByCities: [],
};
const dashboardSlide = createSlice({
name: 'dashboard',
initialState,
reducers: {
fetchData: (state) => {
state.loading = true;
},
fetchDataSuccess: (state) => {
state.loading = false;
},
fetchDataError: (state) => {
state.loading = false;
},
setdashbordStatistics: (state, action: PayloadAction<DashbordStatistics>) => {
state.dashbordStatistics = action.payload;
},
setHightMarkStudentList: (state, action: PayloadAction<Student[]>) => {
state.hightMarkStudentList = action.payload;
},
setLowMarkStudentList: (state, action: PayloadAction<Student[]>) => {
state.lowMarkStudentList = action.payload;
},
setRankingByCities: (state, action: PayloadAction<RankingByCity[]>) => {
state.rankingByCities = action.payload;
},
},
});
export const actionsDashbord = dashboardSlide.actions;
const reducersDashbord = dashboardSlide.reducer;
export default reducersDashbord;
<file_sep>export const uppercaseCharacter = (value: string) => {
if (!value) return '';
return `${value[0].toUpperCase()}${value.slice(1)}`;
};
<file_sep>export const highLightCharacter = (value: number) => {
if (value >= 8) return 'green';
else if (value >= 5) return 'orange';
else return 'red';
};
<file_sep>import { createSlice, PayloadAction, createSelector } from '@reduxjs/toolkit';
import { RootState } from 'app/store';
import { City } from 'models';
export interface CityState {
loading: boolean;
cityList: Array<City>;
}
const initialState: CityState = {
cityList: [],
loading: false,
};
const citySlide = createSlice({
name: 'city',
initialState,
reducers: {
fetchCityList: (state) => {
state.loading = true;
},
fetchCityListSuccess: (state, action: PayloadAction<City[]>) => {
state.loading = false;
state.cityList = action.payload;
},
fetchCityListError: (state) => {
state.loading = false;
},
},
});
export const cityActions = citySlide.actions;
//selector
export const cityList = (state: RootState) => state.city.cityList;
export const mapCityList = createSelector(cityList, (cityList) => {
return cityList.reduce((map: { [key: string]: City }, city) => {
map[city.code] = city;
return map;
}, {});
});
export const cityOptions = createSelector(cityList, (cityList) =>
cityList.map((item) => ({ label: item.name, value: item.code }))
);
const cityRedecer = citySlide.reducer;
export default cityRedecer;
<file_sep>import { call, debounce, put, takeLatest } from '@redux-saga/core/effects';
import { studentApi } from 'apis/studientApi';
import { ListParams, ListResponse, Student } from 'models';
import { studentActions } from './studentSlice';
function* fetchListUserSaga({ payload }: ListParams) {
try {
const res: ListResponse<Student> = yield call(studentApi.getAll, payload);
yield put(studentActions.fetchListStudentSuccess(res));
} catch (error) {
console.log(error);
yield put(studentActions.fetchListStudentFailed());
}
}
function* setKeySearchDebouceSaga({ payload }: ListParams) {
yield put(studentActions.setFilter({ ...payload }));
}
export default function* studentSaga() {
yield takeLatest(studentActions.fetchListStudent.toString(), fetchListUserSaga);
yield debounce(500, studentActions.setKeySearchDebouce.toString(), setKeySearchDebouceSaga);
}
<file_sep>import { ListParams, ListResponse, Student } from 'models';
import axiosClient from './axiosClient';
export const studentApi = {
getAll: (params: ListParams): Promise<ListResponse<Student>> => {
const url = '/students';
return axiosClient.get(url, { params });
},
getById: (id: string): Promise<Student> => {
const url = '/students/' + id;
return axiosClient.get(url);
},
add: (data: Student): Promise<Student> => {
const url = '/students';
return axiosClient.post(url, data);
},
update: (data: Partial<Student>): Promise<Student> => {
const url = '/students/' + data.id;
return axiosClient.patch(url, data);
},
remove: (id: string): Promise<any> => {
const url = '/students/' + id;
return axiosClient.delete(url);
},
};
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ListParams, ListResponse, PaginationParams, Student } from 'models';
export interface StudentState {
loading: boolean;
listStudent: Student[];
filters: ListParams;
pagination: PaginationParams;
}
const initialState: StudentState = {
loading: false,
listStudent: [],
filters: {
_page: 1,
_limit: 10,
},
pagination: {
_page: 1,
_limit: 10,
_totalRows: 10,
},
};
const studentSlide = createSlice({
name: 'student',
initialState,
reducers: {
fetchListStudent: (state, action: PayloadAction<ListParams>) => {
state.loading = true;
},
fetchListStudentSuccess: (state, action: PayloadAction<ListResponse<Student>>) => {
state.loading = false;
state.listStudent = action.payload.data;
state.pagination = action.payload.pagination;
},
fetchListStudentFailed: (state) => {
state.loading = false;
},
setFilter: (state, action: PayloadAction<ListParams>) => {
state.filters = action.payload;
},
setKeySearchDebouce: (state, action: PayloadAction<ListParams>) => {
state.filters = action.payload;
},
},
});
export const studentActions = studentSlide.actions;
export const filtersStudent = (state: any) => state.student.filters;
const studentReducer = studentSlide.reducer;
export default studentReducer;
<file_sep>export * from './NotFoundPage';
export * from './PrivateRoute';
<file_sep>import { citiesApi } from 'apis/citiesApi';
import { City, ListResponse } from 'models';
import { takeLatest, call, put } from 'redux-saga/effects';
import { cityActions } from './sitySlide';
function* fetchCityListSaga() {
try {
const res: ListResponse<City> = yield call(citiesApi.getAll);
yield put(cityActions.fetchCityListSuccess(res.data));
} catch (error) {
console.log(error);
yield put(cityActions.fetchCityListError());
}
}
export default function* citySaga() {
yield takeLatest(cityActions.fetchCityList.type, fetchCityListSaga);
}
<file_sep>import { delay, put, takeEvery } from '@redux-saga/core/effects';
import { PayloadAction } from '@reduxjs/toolkit';
import { incrementSaga, incrementSagaSuccess } from './counterSlice';
function* handleIncreate(action: PayloadAction<number>) {
yield delay(1000);
yield put(incrementSagaSuccess(action.payload));
}
export function* counterSaga() {
yield takeEvery(incrementSaga.toString(), handleIncreate);
}
<file_sep>import { call, delay, fork, put, take } from '@redux-saga/core/effects';
import { authActions, LoginPayload } from './authSlice';
import { PayloadAction } from '@reduxjs/toolkit';
import history from 'utils/history';
function* handleLogin(payload: LoginPayload) {
try {
yield delay(1000);
sessionStorage.setItem('access_token', '<PASSWORD>');
yield put(authActions.loginSuccess({ name: payload.username, id: 1 }));
history.push('/admin/dashbord');
} catch (error) {
yield put(authActions.logginFailure('login failed'));
}
}
function* handleLogout() {
yield delay(500);
sessionStorage.removeItem('access_token');
yield put(authActions.logout());
history.push('/login');
}
function* watchLoginFlow() {
while (true) {
const isLogin = Boolean(sessionStorage.getItem('access_token'));
if (!isLogin) {
const actions: PayloadAction<LoginPayload> = yield take(authActions.login.type);
yield fork(handleLogin, actions.payload);
}
yield take(authActions.logout.type);
//here use call is blocking to wait handle logout, if use fork is none blocking will run loop
yield call(handleLogout);
}
}
export default function* authSaga() {
yield fork(watchLoginFlow);
}
<file_sep>export * from './history';
export * from './highLightCharacter';
export * from './upperCaseCharacter';
<file_sep>import authSaga from 'features/auth/authSaga';
import citySaga from 'features/city/citySaga';
import { counterSaga } from 'features/counter/counterSaga';
import dashbordSaga from 'features/dashbord/dashbordSaga';
import studentSaga from 'features/student/studentSaga';
import { all } from 'redux-saga/effects';
export function* mySaga() {
yield all([counterSaga(), authSaga(), dashbordSaga(), studentSaga(), citySaga()]);
}
<file_sep>import { all, call, put, takeLatest } from '@redux-saga/core/effects';
import { citiesApi } from 'apis/citiesApi';
import { studentApi } from 'apis/studientApi';
import { City, ListResponse, Student } from 'models';
import { actionsDashbord, RankingByCity } from './dashbordSlide';
function* fetchDashbordStatistics() {
try {
const responseList: Array<ListResponse<Student>> = yield all([
call(studentApi.getAll, { _page: 1, _limit: 5, gender: 'male' }),
call(studentApi.getAll, { _page: 1, _limit: 5, gender: 'female' }),
call(studentApi.getAll, { _page: 1, _limit: 5, mark_gte: 8 }),
call(studentApi.getAll, { _page: 1, _limit: 5, mark_lte: 5 }),
]);
const statistics = responseList.map((item) => item.pagination._totalRows);
const [maleCount, femaleCount, hightMarkCount, lowMarkCount] = [...statistics];
yield put(
actionsDashbord.setdashbordStatistics({
maleCount,
femaleCount,
hightMarkCount,
lowMarkCount,
})
);
} catch (error) {
console.log(error);
}
}
function* fetchHightMarkStudentList() {
try {
const res: ListResponse<Student> = yield call(studentApi.getAll, {
_page: 1,
_limit: 5,
_sort: 'mark',
_order: 'desc',
mark_gte: 8,
});
yield put(actionsDashbord.setHightMarkStudentList(res.data));
} catch (error) {
console.log(error);
}
}
function* fetchLowMarkStudentList() {
try {
const res: ListResponse<Student> = yield call(studentApi.getAll, {
_page: 1,
_limit: 5,
_sort: 'mark',
mark_lte: 5,
_order: 'asc',
});
yield put(actionsDashbord.setLowMarkStudentList(res.data));
} catch (error) {
console.log(error);
}
}
function* fetchRankingByCities() {
try {
const listCity: ListResponse<City> = yield call(citiesApi.getAll); //get list city data
//get list student has mark high than 8 in list city
const listData: Array<ListResponse<Student>> = yield all(
listCity.data.map((item) =>
call(studentApi.getAll, {
_limit: 10,
_page: 1,
city: item.code,
mark_gte: 8,
_sort: 'mark',
_order: 'desc',
})
)
);
//return data for raking RankingByCity
const rankingByCitiesList: RankingByCity[] = listData.map((item, index) => {
return {
cityId: listCity.data[index].code,
cityName: listCity.data[index].name,
rankingList: item.data,
};
});
yield put(actionsDashbord.setRankingByCities(rankingByCitiesList));
} catch (error) {
console.log(error);
}
}
function* fetchDataSaga() {
try {
yield all([
call(fetchDashbordStatistics),
call(fetchHightMarkStudentList),
call(fetchLowMarkStudentList),
call(fetchRankingByCities),
]);
yield put(actionsDashbord.fetchDataSuccess());
} catch (error) {
yield put(actionsDashbord.fetchDataError());
}
}
export default function* dashbordSaga() {
yield takeLatest(actionsDashbord.fetchData.type, fetchDataSaga);
}
<file_sep>import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { User } from 'models/user';
export interface LoginPayload {
username: string;
password: string;
}
export interface AuthState {
isLogin: boolean;
logging?: boolean;
user?: User;
}
const initialState: AuthState = {
isLogin: false,
logging: false,
user: undefined,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
login: (state, action: PayloadAction<LoginPayload>) => {
state.logging = true;
},
loginSuccess: (state, action: PayloadAction<User>) => {
state.logging = false;
state.isLogin = true;
state.user = action.payload;
},
logginFailure: (state, action: PayloadAction<string>) => {
state.logging = false;
state.isLogin = false;
},
logout: (state) => {
state.logging = false;
state.isLogin = false;
},
},
});
//action
export const authActions = authSlice.actions;
//selector
export const selectIsLogin = (state: any) => state.auth.isLogin;
export const selectLogging = (state: any) => state.auth.logging;
//reducer
const authReducers = authSlice.reducer;
export default authReducers;
<file_sep>export * from './cities';
export * from './commom';
export * from './student';
|
878ee43e487cf3039cec520141d195f96115ea90
|
[
"TypeScript"
] | 16
|
TypeScript
|
dangsangn/reactjs-ts-redux-saga-toolkit
|
cc778833f5f149bfbb46299374074a06a1f5f041
|
6301f49086d725e889625b7e1bbd8a78845f5e69
|
refs/heads/main
|
<repo_name>davemlz/awesome-ee-spectral-indices<file_sep>/test/test_indices.py
import sys
import unittest
sys.path.append("./")
from src.indices import spindex, SpectralIndices
class Test(unittest.TestCase):
"""Tests for the Awesome List of Spectral Indices for Google Earth Engine."""
def test_Indices(self):
"""Test the indices list"""
self.assertIsInstance(spindex, SpectralIndices)
if __name__ == "__main__":
unittest.main()
<file_sep>/docs/index.rst
Awesome Spectral Indices
========================
.. raw:: html
<embed>
<p align="center">
<a href="https://github.com/davemlz/awesome-spectral-indices"><img src="https://raw.githubusercontent.com/davemlz/awesome-spectral-indices/main/docs/_static/asi.png" alt="Awesome Spectral Indices"></a>
</p>
<p align="center">
<em>A ready-to-use curated list of Spectral Indices for Remote Sensing applications.</em>
</p>
<p align="center">
<a href="https://github.com/sindresorhus/awesome" target="_blank">
<img src="https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg" alt="Awesome">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-dict.json" target="_blank">
<img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/davemlz/5e9f08fa6a45d9d486e29d9d85ad5c84/raw/spectral.json" alt="Awesome Spectral Indices">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml" target="_blank">
<img src="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml/badge.svg" alt="Tests">
</a>
<a href="https://awesome-ee-spectral-indices.readthedocs.io/en/latest/?badge=latest" target="_blank">
<img src="https://readthedocs.org/projects/awesome-ee-spectral-indices/badge/?version=latest" alt="Documentation">
</a>
<a href="https://zenodo.org/badge/latestdoi/355720108"><img src="https://zenodo.org/badge/355720108.svg" alt="DOI"></a>
<a href="https://github.com/sponsors/davemlz" target="_blank">
<img src="https://img.shields.io/badge/GitHub%20Sponsors-Donate-ff69b4.svg" alt="GitHub Sponsors">
</a>
<a href="https://www.buymeacoffee.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-Donate-ff69b4.svg" alt="Buy me a coffee">
</a>
<a href="https://ko-fi.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/kofi-Donate-ff69b4.svg" alt="Ko-fi">
</a>
<a href="https://twitter.com/dmlmont" target="_blank">
<img src="https://img.shields.io/twitter/follow/dmlmont?style=social" alt="Twitter">
</a>
<a href="https://github.com/psf/black" target="_blank">
<img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Black">
</a>
</p>
</embed>
.. toctree::
:maxdepth: 2
:caption: Contents
:hidden:
list
contributing
Spectral Indices
--------------------
Spectral Indices are widely used in the Remote Sensing community. This repository keeps track of classical as well as novel spectral indices for different Remote Sensing applications. All spectral indices in the repository are curated and can be used in different environments and programming languages.
You can check the `curated list of spectral indices here <https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-table.csv>`_, and if you want to use it in your environment, it is available in `CSV <https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-table.csv>`_ and `JSON <https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-dict.json>`_.
Attributes
~~~~~~~~~~~~~~~~
All spectral indices follow a standard. Each item of the list has the following attributes:
- :code:`short_name`: Short name of the index (e.g. :code:`"NDWI"`).
- :code:`long_name`: Long name of the index (e.g. :code:`"Normalized Difference Water Index"`).
- :code:`formula`: Expression/formula of the index (e.g. :code:`"(G - N)/(G + N)"`).
- :code:`bands`: List of required bands/parameters for the index computation (e.g. :code:`["N","G"]`).
- :code:`reference`: Link to the index reference/paper/doi (e.g. :code:`"https://doi.org/10.1080/01431169608948714"`).
- :code:`type`: Type/application of the index (e.g. :code:`"water"`).
- :code:`date_of_addition`: Date of addition to the list (e.g. :code:`"2021-04-07"`).
- :code:`contributor`: GitHub user link of the contributor (e.g. :code:`"https://github.com/davemlz"`).
Expressions
~~~~~~~~~~~~~~~~
The formula of the index is presented as a string/expression (e.g. :code:`"(N - R)/(N + R)"`) that can be easily evaluated. The parameters used in the expression for each index follow this standard:
.. list-table:: Standard variables for spectral indices expressions and satellite equivalents.
:header-rows: 1
* - Description
- Standard
- Sentinel-1
- Sentinel-2
- Landsat 8
- Landsat 457
- MODIS
* - Aerosols
- A
-
- B1
- B1
-
-
* - Blue
- B
-
- B2
- B2
- B1
- B3
* - Green
- G
-
- B3
- B3
- B2
- B4
* - Yellow
- Y
-
-
-
-
-
* - Red
- R
-
- B4
- B4
- B3
- B1
* - Red Edge 1
- RE1
-
- B5
-
-
-
* - Red Edge 2
- RE2
-
- B6
-
-
-
* - Red Edge 3
- RE3
-
- B7
-
-
-
* - NIR
- N
-
- B8
- B5
- B4
- B2
* - NIR 2
- N2
-
- B8A
-
-
-
* - SWIR 1
- S1
-
- B11
- B6
- B5
- B6
* - SWIR 2
- S2
-
- B12
- B7
- B7
- B7
* - Thermal 1
- T1
-
-
- B10
- B6
-
* - Thermal 2
- T2
-
-
- B11
-
-
* - Backscattering Coefficient HV
- HV
- HV
-
-
-
-
* - Backscattering Coefficient VH
- VH
- VH
-
-
-
-
* - Backscattering Coefficient HH
- HH
- HH
-
-
-
-
* - Backscattering Coefficient VV
- VV
- VV
-
-
-
-
Additional index parameters also follow a standard:
- :code:`g`: Gain factor (e.g. Used for EVI).
- :code:`L`: Canopy background adjustment (e.g. Used for SAVI and EVI).
- :code:`C1`: Coefficient 1 for the aerosol resistance term (e.g. Used for EVI).
- :code:`C2`: Coefficient 2 for the aerosol resistance term (e.g. Used for EVI).
- :code:`cexp`: Exponent used for OCVI.
- :code:`nexp`: Exponent used for GDVI.
- :code:`alpha`: Weighting coefficient used for WDRVI, BWDRVI and NDPI.
- :code:`beta`: Calibration parameter used for NDSIns.
- :code:`gamma`: Weighting coefficient used for ARVI.
- :code:`omega`: Weighting coefficient used for MBWI.
- :code:`epsilon`: Adjustment constant used for EBI.
- :code:`sla`: Soil line slope.
- :code:`slb`: Soil line intercept.
- :code:`PAR`: Photosynthetically Active Radiation.
- :code:`k`: Slope parameter by soil used for NIRvH2.
- :code:`lambdaN`: NIR wavelength used for NIRvH2 and NDGI.
- :code:`lambdaR`: Red wavelength used for NIRvH2 and NDGI.
- :code:`lambdaG`: Green wavelength used for NDGI.
The kernel indices are constructed using a special type of parameters:
- :code:`kAB`: Kernel of bands/parameters `A` and `B` (e.g. `kNR` means `k(N,R)`, where `k` is the kernel function).
- :code:`p`: Kernel degree (used for the polynomial kernel).
- :code:`c`: Free parameter that trades off the influence of higher-order versus lower-order terms (used for the polynomial kernel).
Call for Indices!
-----------------
Researchers that have published (or aim to publish) their novel spectral indices are encouraged to add them to this repository! The list of spectral indices is used as a source for different resources that allow spectral indices computation in different environments (such as Python and Google Earth Engine). To add an index, please follow the `Contribution Guidelines <https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html>`_.
In the same line, if you know an spectral index that is not included in this repository, you are encouraged to add it! Please follow the `Contribution Guidelines <https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html>`_ in order to add it.
And one more thing: If you see an error in one or several indices, please report it or update the index (indices) by following the `Contribution Guidelines <https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html>`_!
There is no deadline. The repository is continuously updated!
Used by
---------
JavaScript
~~~~~~~~~~
- `spectral <https://github.com/davemlz/spectral>`_: Awesome Spectral Indices for the Google Earth Engine JavaScript API (Code Editor).
Python
~~~~~~
- `eemont <https://github.com/davemlz/eemont>`_: A python package that extends Google Earth Engine.
- `eeExtra <https://github.com/r-earthengine/ee_extra>`_: A Python package that unifies the Google Earth Engine ecosystem.
- `spyndex <https://github.com/davemlz/spyndex>`_: Awesome Spectral Indices in Python.
R
~
- `rgeeExtra <https://github.com/r-earthengine/rgeeExtra>`_: High-level functions to process spatial and simple Earth Engine objects.
List
-------
Check the full list of spectral indices `here <https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-table.csv>`_.
Download Raw Files
------------------------
You can download or clone the repository:
.. code-block::
git clone https://github.com/davemlz/awesome-ee-spectral-indices.git
Or you can download the single files here (right-click > Save link as...):
- JSON: `Raw list <https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-dict.json>`_
- CSV: `Raw list <https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-table.csv>`_
Credits
------------------------
- `<NAME> <https://github.com/csaybar>`_: The formidable `pydantic <https://github.com/samuelcolvin/pydantic/>`_ expert and creator of `rgee <https://github.com/r-spatial/rgee>`_.<file_sep>/src/bands.py
bands = {
"A": {
"short_name": "A",
"long_name": "Aersols",
"common_name": "coastal",
"min_wavelength": 400,
"max_wavelength": 455,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B1",
"name": "Aerosols",
"wavelength": 442.7,
"bandwidth": 21,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B1",
"name": "Aerosols",
"wavelength": 442.3,
"bandwidth": 21,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B1",
"name": "Coastal Aerosol",
"wavelength": 440.0,
"bandwidth": 20.0,
},
"landsat9": {
"platform": "Landsat 8",
"band": "B1",
"name": "Coastal Aerosol",
"wavelength": 440.0,
"bandwidth": 20.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B1",
"name": "Coastal Blue",
"wavelength": 441.5,
"bandwidth": 21.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B1",
"name": "Coastal Blue",
"wavelength": 425.0,
"bandwidth": 50.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B1",
"name": "Coastal Blue",
"wavelength": 425.0,
"bandwidth": 50.0,
},
},
},
"B": {
"short_name": "B",
"long_name": "Blue",
"common_name": "blue",
"min_wavelength": 450,
"max_wavelength": 530,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B2",
"name": "Blue",
"wavelength": 492.4,
"bandwidth": 66.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B2",
"name": "Blue",
"wavelength": 492.1,
"bandwidth": 66.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B1",
"name": "Blue",
"wavelength": 485.0,
"bandwidth": 70.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B1",
"name": "Blue",
"wavelength": 485.0,
"bandwidth": 70.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B1",
"name": "Blue",
"wavelength": 485.0,
"bandwidth": 70.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B2",
"name": "Blue",
"wavelength": 480.0,
"bandwidth": 60.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B2",
"name": "Blue",
"wavelength": 480.0,
"bandwidth": 60.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B3",
"name": "Blue",
"wavelength": 469.0,
"bandwidth": 20.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B2",
"name": "Blue",
"wavelength": 490.0,
"bandwidth": 50.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B2",
"name": "Blue",
"wavelength": 480.0,
"bandwidth": 60.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B2",
"name": "Blue",
"wavelength": 480.0,
"bandwidth": 60.0,
},
},
},
"G1": {
"short_name": "G1",
"long_name": "Green 1",
"common_name": "green",
"min_wavelength": 510,
"max_wavelength": 550,
"platforms": {
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B11",
"name": "Green",
"wavelength": 531.0,
"bandwidth": 10.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B3",
"name": "Green",
"wavelength": 531.0,
"bandwidth": 36.0,
},
},
},
"G": {
"short_name": "G",
"long_name": "Green",
"common_name": "green",
"min_wavelength": 510,
"max_wavelength": 600,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B3",
"name": "Green",
"wavelength": 559.8,
"bandwidth": 36.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B3",
"name": "Green",
"wavelength": 559.0,
"bandwidth": 36.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B2",
"name": "Green",
"wavelength": 560.0,
"bandwidth": 80.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B2",
"name": "Green",
"wavelength": 560.0,
"bandwidth": 80.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B2",
"name": "Green",
"wavelength": 560.0,
"bandwidth": 80.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B3",
"name": "Green",
"wavelength": 560.0,
"bandwidth": 60.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B3",
"name": "Green",
"wavelength": 560.0,
"bandwidth": 60.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B4",
"name": "Green",
"wavelength": 555.0,
"bandwidth": 20.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B4",
"name": "Green",
"wavelength": 565.0,
"bandwidth": 36.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B3",
"name": "Green",
"wavelength": 545.0,
"bandwidth": 70.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B3",
"name": "Green",
"wavelength": 545.0,
"bandwidth": 70.0,
},
},
},
"Y": {
"short_name": "Y",
"long_name": "Yellow",
"common_name": "yellow",
"min_wavelength": 585,
"max_wavelength": 625,
"platforms": {
"planetscope": {
"platform": "PlanetScope",
"band": "B5",
"name": "Yellow",
"wavelength": 610.0,
"bandwidth": 20.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B4",
"name": "Yellow",
"wavelength": 605.0,
"bandwidth": 40.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B4",
"name": "Yellow",
"wavelength": 605.0,
"bandwidth": 40.0,
},
},
},
"R": {
"short_name": "R",
"long_name": "Red",
"common_name": "red",
"min_wavelength": 620,
"max_wavelength": 690,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B4",
"name": "Red",
"wavelength": 664.6,
"bandwidth": 31.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B4",
"name": "Red",
"wavelength": 665.0,
"bandwidth": 31.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B3",
"name": "Red",
"wavelength": 660.0,
"bandwidth": 60.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B3",
"name": "Red",
"wavelength": 660.0,
"bandwidth": 60.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B3",
"name": "Red",
"wavelength": 660.0,
"bandwidth": 60.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B4",
"name": "Red",
"wavelength": 655.0,
"bandwidth": 30.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B4",
"name": "Red",
"wavelength": 655.0,
"bandwidth": 30.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B1",
"name": "Red",
"wavelength": 645.0,
"bandwidth": 50.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B6",
"name": "Red",
"wavelength": 665.0,
"bandwidth": 30.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B5",
"name": "Red",
"wavelength": 660.0,
"bandwidth": 60.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B5",
"name": "Red",
"wavelength": 660.0,
"bandwidth": 60.0,
},
},
},
"RE1": {
"short_name": "RE1",
"long_name": "Red Edge 1",
"common_name": "rededge",
"min_wavelength": 695,
"max_wavelength": 715,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B5",
"name": "Red Edge 1",
"wavelength": 704.1,
"bandwidth": 15.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B5",
"name": "Red Edge 1",
"wavelength": 703.8,
"bandwidth": 15.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B7",
"name": "Red Edge",
"wavelength": 705.0,
"bandwidth": 16.0,
},
},
},
"RE2": {
"short_name": "RE2",
"long_name": "Red Edge 2",
"common_name": "rededge",
"min_wavelength": 730,
"max_wavelength": 750,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B6",
"name": "Red Edge 2",
"wavelength": 740.5,
"bandwidth": 15.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B6",
"name": "Red Edge 2",
"wavelength": 739.1,
"bandwidth": 15.0,
},
},
},
"RE3": {
"short_name": "RE3",
"long_name": "Red Edge 3",
"common_name": "rededge",
"min_wavelength": 765,
"max_wavelength": 795,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B7",
"name": "Red Edge 3",
"wavelength": 782.8,
"bandwidth": 20.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B7",
"name": "Red Edge 3",
"wavelength": 779.7,
"bandwidth": 20.0,
},
},
},
"N2": {
"short_name": "N2",
"long_name": "Near-Infrared (NIR) 2",
"common_name": "nir08",
"min_wavelength": 850,
"max_wavelength": 880,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B8A",
"name": "Near-Infrared (NIR) 2 (Red Edge 4 in Google Earth Engine)",
"wavelength": 864.7,
"bandwidth": 21.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B8A",
"name": "Near-Infrared (NIR) 2 (Red Edge 4 in Google Earth Engine)",
"wavelength": 864.0,
"bandwidth": 21.0,
},
},
},
"N": {
"short_name": "N",
"long_name": "Near-Infrared (NIR)",
"common_name": "nir",
"min_wavelength": 760,
"max_wavelength": 900,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B8",
"name": "Near-Infrared (NIR)",
"wavelength": 832.8,
"bandwidth": 106.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B8",
"name": "Near-Infrared (NIR)",
"wavelength": 833.0,
"bandwidth": 106.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B4",
"name": "Near-Infrared (NIR)",
"wavelength": 830.0,
"bandwidth": 140.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B4",
"name": "Near-Infrared (NIR)",
"wavelength": 830.0,
"bandwidth": 140.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B4",
"name": "Near-Infrared (NIR)",
"wavelength": 835.0,
"bandwidth": 130.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B5",
"name": "Near-Infrared (NIR)",
"wavelength": 865.0,
"bandwidth": 30.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B5",
"name": "Near-Infrared (NIR)",
"wavelength": 865.0,
"bandwidth": 30.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B2",
"name": "Near-Infrared (NIR)",
"wavelength": 858.5,
"bandwidth": 35.0,
},
"planetscope": {
"platform": "PlanetScope",
"band": "B8",
"name": "Near-Infrared (NIR)",
"wavelength": 865.0,
"bandwidth": 40.0,
},
"wv3": {
"platform": "WorldView-3",
"band": "B7",
"name": "Near-IR1",
"wavelength": 832.5,
"bandwidth": 125.0,
},
"wv2": {
"platform": "WorldView-2",
"band": "B7",
"name": "Near-IR1",
"wavelength": 832.5,
"bandwidth": 125.0,
},
},
},
"WV": {
"short_name": "WV",
"long_name": "Water Vapour",
"common_name": "nir09",
"min_wavelength": 930,
"max_wavelength": 960,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B9",
"name": "Water Vapour",
"wavelength": 945.1,
"bandwidth": 20.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B9",
"name": "Water Vapour",
"wavelength": 943.2,
"bandwidth": 21.0,
},
},
},
"S1": {
"short_name": "S1",
"long_name": "Short-wave Infrared (SWIR) 1",
"common_name": "swir16",
"min_wavelength": 1550,
"max_wavelength": 1750,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B11",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1613.7,
"bandwidth": 91.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B11",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1610.4,
"bandwidth": 94.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B5",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1650.0,
"bandwidth": 200.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B5",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1650.0,
"bandwidth": 200.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B5",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1650.0,
"bandwidth": 200.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B6",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1610.0,
"bandwidth": 80.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B6",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1610.0,
"bandwidth": 80.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B6",
"name": "Short-wave Infrared (SWIR) 1",
"wavelength": 1640.0,
"bandwidth": 24.0,
},
},
},
"S2": {
"short_name": "S2",
"long_name": "Short-wave Infrared (SWIR) 2",
"common_name": "swir22",
"min_wavelength": 2080,
"max_wavelength": 2350,
"platforms": {
"sentinel2a": {
"platform": "Sentinel-2A",
"band": "B12",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2202.4,
"bandwidth": 175.0,
},
"sentinel2b": {
"platform": "Sentinel-2B",
"band": "B12",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2185.7,
"bandwidth": 185.0,
},
"landsat4": {
"platform": "Landsat 4",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2215.0,
"bandwidth": 270.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2215.0,
"bandwidth": 270.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2220.0,
"bandwidth": 260.0,
},
"landsat8": {
"platform": "Landsat 8",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2200.0,
"bandwidth": 180.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2200.0,
"bandwidth": 180.0,
},
"modis": {
"platform": "Terra/Aqua: MODIS",
"band": "B7",
"name": "Short-wave Infrared (SWIR) 2",
"wavelength": 2130.0,
"bandwidth": 50.0,
},
},
},
"T": {
"short_name": "T",
"long_name": "Thermal Infrared",
"common_name": "lwir",
"min_wavelength": 10400,
"max_wavelength": 12500,
"platforms": {
"landsat4": {
"platform": "Landsat 4",
"band": "B6",
"name": "Thermal Infrared",
"wavelength": 11450.0,
"bandwidth": 2100.0,
},
"landsat5": {
"platform": "Landsat 5",
"band": "B6",
"name": "Thermal Infrared",
"wavelength": 11450.0,
"bandwidth": 2100.0,
},
"landsat7": {
"platform": "Landsat 7",
"band": "B6",
"name": "Thermal Infrared",
"wavelength": 11450.0,
"bandwidth": 2100.0,
},
},
},
"T1": {
"short_name": "T1",
"long_name": "Thermal Infrared 1",
"common_name": "lwir11",
"min_wavelength": 10600,
"max_wavelength": 11190,
"platforms": {
"landsat8": {
"platform": "Landsat 8",
"band": "B10",
"name": "Thermal Infrared 1",
"wavelength": 10895.0,
"bandwidth": 590.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B10",
"name": "Thermal Infrared 1",
"wavelength": 10895.0,
"bandwidth": 590.0,
},
},
},
"T2": {
"short_name": "T2",
"long_name": "Thermal Infrared 2",
"common_name": "lwir12",
"min_wavelength": 11500,
"max_wavelength": 12510,
"platforms": {
"landsat8": {
"platform": "Landsat 8",
"band": "B11",
"name": "Thermal Infrared 2",
"wavelength": 12005.0,
"bandwidth": 1010.0,
},
"landsat9": {
"platform": "Landsat 9",
"band": "B11",
"name": "Thermal Infrared 2",
"wavelength": 12005.0,
"bandwidth": 1010.0,
},
},
},
}
<file_sep>/README.md
<p align="center">
<a href="https://github.com/davemlz/awesome-spectral-indices"><img src="https://raw.githubusercontent.com/davemlz/awesome-spectral-indices/main/docs/_static/asi.png" alt="Awesome Spectral Indices"></a>
</p>
<p align="center">
<em>A ready-to-use curated list of Spectral Indices for Remote Sensing applications.</em>
</p>
<p align="center">
<a href="https://github.com/sindresorhus/awesome" target="_blank">
<img src="https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg" alt="Awesome">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-dict.json" target="_blank">
<img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/davemlz/5e9f08fa6a45d9d486e29d9d85ad5c84/raw/spectral.json" alt="Awesome Spectral Indices">
</a>
<a href="https://share.streamlit.io/davemlz/espectro/main/espectro.py" target="_blank">
<img src="https://static.streamlit.io/badges/streamlit_badge_black_white.svg" alt="Streamlit">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml" target="_blank">
<img src="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml/badge.svg" alt="Tests">
</a>
<a href="https://awesome-ee-spectral-indices.readthedocs.io/en/latest/?badge=latest" target="_blank">
<img src="https://readthedocs.org/projects/awesome-ee-spectral-indices/badge/?version=latest" alt="Documentation">
</a>
<a href="https://zenodo.org/badge/latestdoi/355720108"><img src="https://zenodo.org/badge/355720108.svg" alt="DOI"></a>
<a href="https://github.com/sponsors/davemlz" target="_blank">
<img src="https://img.shields.io/badge/GitHub%20Sponsors-Donate-ff69b4.svg" alt="GitHub Sponsors">
</a>
<a href="https://www.buymeacoffee.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-Donate-ff69b4.svg" alt="Buy me a coffee">
</a>
<a href="https://ko-fi.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/kofi-Donate-ff69b4.svg" alt="Ko-fi">
</a>
<a href="https://twitter.com/dmlmont" target="_blank">
<img src="https://img.shields.io/twitter/follow/dmlmont?style=social" alt="Twitter">
</a>
<a href="https://github.com/psf/black" target="_blank">
<img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Black">
</a>
</p>
---
**GitHub**: <a href="https://github.com/awesome-spectral-indices/awesome-spectral-indices" target="_blank">github.com/awesome-spectral-indices/awesome-spectral-indices</a>
**Documentation**: <a href="https://awesome-ee-spectral-indices.readthedocs.io/" target="_blank">awesome-ee-spectral-indices.readthedocs.io</a>
**Python Package**: <a href="https://github.com/awesome-spectral-indices/spyndex" target="_blank">github.com/awesome-spectral-indices/spyndex</a>
**Paper**: <a href="https://doi.org/10.1038/s41597-023-02096-0" target="_blank">doi.org/10.1038/s41597-023-02096-0</a>
**Streamlit App**: <a href="https://github.com/awesome-spectral-indices/espectro" target="_blank">github.com/awesome-spectral-indices/espectro</a>
**Google Earth Engine**: <a href="https://github.com/davemlz/eemont" target="_blank">github.com/davemlz/eemont</a> (Python), <a href="https://github.com/awesome-spectral-indices/spectral" target="_blank">github.com/awesome-spectral-indices/spectral</a> (JavaScript) and <a href="https://github.com/r-earthengine/rgeeExtra" target="_blank">github.com/r-earthengine/rgeeExtra</a> (R)
---
# Spectral Indices
Spectral Indices are widely used in the Remote Sensing community. This repository keeps track of classical as well as novel spectral indices for different Remote Sensing applications. All spectral indices in the repository are curated and can be used in different environments and programming languages.
You can check the [curated list of spectral indices here](https://github.com/awesome-spectral-indices/awesome-spectral-indices/blob/main/output/spectral-indices-table.csv), and if you want to use it in your environment, it is available in [CSV](https://raw.githubusercontent.com/awesome-spectral-indices/awesome-spectral-indices/main/output/spectral-indices-table.csv) and [JSON](https://raw.githubusercontent.com/awesome-spectral-indices/awesome-spectral-indices/main/output/spectral-indices-dict.json).
## Attributes
All spectral indices follow a standard. Each item of the list has the following attributes:
- `short_name`: Short name of the index (e.g. `"NDWI"`).
- `long_name`: Long name of the index (e.g. `"Normalized Difference Water Index"`).
- `formula`: Expression/formula of the index (e.g. `"(G - N)/(G + N)"`).
- `bands`: List of required bands/parameters for the index computation (e.g. `["N","G"]`).
- `platforms`: List of platforms with the required bands for the index computation (e.g. `["MODIS", "Landsat-457", "Landsat-89", "Sentinel-2"]`).
- `reference`: Link to the index reference/paper/doi (e.g. `"https://doi.org/10.1080/01431169608948714"`).
- `application_domain`: Application domain of the index (e.g. `"water"`).
- `date_of_addition`: Date of addition to the list (e.g. `"2021-04-07"`).
- `contributor`: GitHub user link of the contributor (e.g. `"https://github.com/davemlz"`).
## Expressions
The formula of the index is presented as a string/expression (e.g. `"(N - R)/(N + R)"`) that can be easily evaluated. The parameters used in the expression for each index follow this standard:
<table>
<tr>
<th> Description </th>
<th> Standard </th>
<th> Spectral Range (nm) </th>
<th> Sentinel-2 </th>
<th> Landsat-89 </th>
<th> Landsat-457 </th>
<th> MODIS </th>
</tr>
<tr>
<td>Aerosols</td>
<td>A</td>
<td>400 - 455</td>
<td>B1</td>
<td>B1</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Blue</td>
<td>B</td>
<td>450 - 530</td>
<td>B2</td>
<td>B2</td>
<td>B1</td>
<td>B3</td>
</tr>
<tr>
<td>Green 1</td>
<td>G1</td>
<td>510 - 550</td>
<td></td>
<td></td>
<td></td>
<td>B11</td>
</tr>
<tr>
<td>Green</td>
<td>G</td>
<td>510 - 600</td>
<td>B3</td>
<td>B3</td>
<td>B2</td>
<td>B4</td>
</tr>
<tr>
<td>Yellow</td>
<td>Y</td>
<td>585 - 625</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red</td>
<td>R</td>
<td>620 - 690</td>
<td>B4</td>
<td>B4</td>
<td>B3</td>
<td>B1</td>
</tr>
<tr>
<td>Red Edge 1</td>
<td>RE1</td>
<td>695 - 715</td>
<td>B5</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red Edge 2</td>
<td>RE2</td>
<td>730 - 750</td>
<td>B6</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red Edge 3</td>
<td>RE3</td>
<td>765 - 795</td>
<td>B7</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>NIR</td>
<td>N</td>
<td>760 - 900</td>
<td>B8</td>
<td>B5</td>
<td>B4</td>
<td>B2</td>
</tr>
<tr>
<td>NIR 2</td>
<td>N2</td>
<td>850 - 880</td>
<td>B8A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Water Vapour</td>
<td>WV</td>
<td>930 - 960</td>
<td>B9</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>SWIR 1</td>
<td>S1</td>
<td>1550 - 1750</td>
<td>B11</td>
<td>B6</td>
<td>B5</td>
<td>B6</td>
</tr>
<tr>
<td>SWIR 2</td>
<td>S2</td>
<td>2080 - 2350</td>
<td>B12</td>
<td>B7</td>
<td>B7</td>
<td>B7</td>
</tr>
<tr>
<td>Thermal</td>
<td>T</td>
<td>10400 - 12500</td>
<td></td>
<td></td>
<td>B6</td>
<td></td>
</tr>
<tr>
<td>Thermal 1</td>
<td>T1</td>
<td>10600 - 11190</td>
<td></td>
<td>B10</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Thermal 2</td>
<td>T2</td>
<td>11500 - 12510</td>
<td></td>
<td>B11</td>
<td></td>
<td></td>
</tr>
</table>
In the case of RADAR Indices, the bands follow this standard:
<table>
<tr>
<th> Description </th>
<th> Standard </th>
<th> Sentinel-1 </th>
</tr>
<tr>
<td>Backscattering Coefficient HV</td>
<td>HV</td>
<td>HV</td>
</tr>
<tr>
<td>Backscattering Coefficient VH</td>
<td>VH</td>
<td>VH</td>
</tr>
<tr>
<td>Backscattering Coefficient HH</td>
<td>HH</td>
<td>HH</td>
</tr>
<tr>
<td>Backscattering Coefficient VV</td>
<td>VV</td>
<td>VV</td>
</tr>
</table>
Additional index parameters also follow a standard:
- `g`: Gain factor (e.g. Used for EVI).
- `L`: Canopy background adjustment (e.g. Used for SAVI and EVI).
- `C1`: Coefficient 1 for the aerosol resistance term (e.g. Used for EVI).
- `C2`: Coefficient 2 for the aerosol resistance term (e.g. Used for EVI).
- `cexp`: Exponent used for OCVI.
- `nexp`: Exponent used for GDVI.
- `alpha`: Weighting coefficient used for WDRVI, BWDRVI and NDPI.
- `beta`: Calibration parameter used for NDSIns.
- `gamma`: Weighting coefficient used for ARVI.
- `omega`: Weighting coefficient used for MBWI.
- `sla`: Soil line slope.
- `slb`: Soil line intercept.
- `PAR`: Photosynthetically Active Radiation.
- `k`: Slope parameter by soil used for NIRvH2.
- `lambdaN`: NIR wavelength used for NIRvH2 and NDGI.
- `lambdaR`: Red wavelength used for NIRvH2 and NDGI.
- `lambdaG`: Green wavelength used for NDGI.
The kernel indices are constructed using a special type of parameters:
- `kAB`: Kernel of bands/parameters `A` and `B` (e.g. `kNR` means `k(N,R)`, where `k` is the kernel function).
- `p`: Kernel degree (used for the polynomial kernel).
- `c`: Free parameter that trades off the influence of higher-order versus lower-order terms (used for the polynomial kernel).
# Call for Indices! :rotating_light:
Researchers that have published (or aim to publish) their novel spectral indices are encouraged to add them to this repository! The list of spectral indices is used as a source for different resources that allow spectral indices computation in different environments (such as Python and Google Earth Engine). To add an index, please follow the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html).
In the same line, if you know an spectral index that is not included in this repository, you are encouraged to add it! Please follow the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html) in order to add it.
And one more thing: If you see an error in one or several indices, please report it or update the index (indices) by following the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html)!
There is no deadline. The repository is continuously updated!
# Used by
## JavaScript
- [spectral](https://github.com/davemlz/spectral): Awesome Spectral Indices for the Google Earth Engine JavaScript API (Code Editor).
## Python
- [eemont](https://github.com/davemlz/eemont): A Python package that extends Google Earth Engine.
- [eeExtra](https://github.com/r-earthengine/ee_extra): A Python package that unifies the Google Earth Engine ecosystem.
- [Espectro](https://github.com/davemlz/espectro): The Awesome Spectral Indices Streamlit App.
- [spyndex](https://github.com/davemlz/spyndex): Awesome Spectral Indices in Python.
## R
- [rgeeExtra](https://github.com/r-earthengine/rgeeExtra): High-level functions to process spatial and simple Earth Engine objects.
# Spectral Indices by Application Domain
## Vegetation
<table><tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00190-0" target="_blank">AFRI1600</a>: Aerosol Free Vegetation Index (1600 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00190-0" target="_blank">AFRI2100</a>: Aerosol Free Vegetation Index (2100 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1562/0031-8655(2001)074%3C0038:OPANEO%3E2.0.CO;2" target="_blank">ARI</a>: Anthocyanin Reflectance Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1562/0031-8655(2001)074%3C0038:OPANEO%3E2.0.CO;2" target="_blank">ARI2</a>: Anthocyanin Reflectance Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/36.134076" target="_blank">ARVI</a>: Atmospherically Resistant Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(91)90009-U" target="_blank">ATSAVI</a>: Adjusted Transformed Soil-Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf" target="_blank">AVI</a>: Advanced Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(87)90088-5" target="_blank">BCC</a>: Blue Chromatic Coordinate.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S1672-6308(07)60027-4" target="_blank">BNDVI</a>: Blue Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2135/cropsci2007.01.0031" target="_blank">BWDRVI</a>: Blue Wide Dynamic Range Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1073/pnas.1606162113" target="_blank">CCI</a>: Chlorophyll Carotenoid Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1078/0176-1617-00887" target="_blank">CIG</a>: Chlorophyll Index Green.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1078/0176-1617-00887" target="_blank">CIRE</a>: Chlorophyll Index Red Edge.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1007/s11119-010-9204-3" target="_blank">CVI</a>: Chlorophyll Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://www.asprs.org/wp-content/uploads/pers/1999journal/apr/1999_apr_495-501.pdf" target="_blank">DSI</a>: Drought Stress Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160310001618031" target="_blank">DSWI1</a>: Disease-Water Stress Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160310001618031" target="_blank">DSWI2</a>: Disease-Water Stress Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160310001618031" target="_blank">DSWI3</a>: Disease-Water Stress Index 3.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160310001618031" target="_blank">DSWI4</a>: Disease-Water Stress Index 4.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160310001618031" target="_blank">DSWI5</a>: Disease-Water Stress Index 5.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(94)00114-3" target="_blank">DVI</a>: Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2019.03.028" target="_blank">DVIplus</a>: Difference Vegetation Index Plus.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2019.08.006" target="_blank">EBI</a>: Enhanced Bloom Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(96)00112-5" target="_blank">EVI</a>: Enhanced Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2008.06.006" target="_blank">EVI2</a>: Two-Band Enhanced Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.13031/2013.27838" target="_blank">ExG</a>: Excess Green Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.compag.2008.03.009" target="_blank">ExGR</a>: ExG - ExR Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1117/12.336896" target="_blank">ExR</a>: Excess Red Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2020.111676" target="_blank">FCVI</a>: Fluorescence Correction Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(96)00072-7" target="_blank">GARI</a>: Green Atmospherically Resistant Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S1672-6308(07)60027-4" target="_blank">GBNDVI</a>: Green-Blue Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(87)90088-5" target="_blank">GCC</a>: Green Chromatic Coordinate.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs6021211" target="_blank">GDVI</a>: Generalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1007/bf00031911" target="_blank">GEMI</a>: Global Environment Monitoring Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1080/10106040108542184" target="_blank">GLI</a>: Green Leaf Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(96)80284-7" target="_blank">GM1</a>: Gitelson and Merzlyak Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(96)80284-7" target="_blank">GM2</a>: Gitelson and Merzlyak Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(96)00072-7" target="_blank">GNDVI</a>: Green Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">GOSAVI</a>: Green Optimized Soil Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S1672-6308(07)60027-4" target="_blank">GRNDVI</a>: Green-Red Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">GRVI</a>: Green Ratio Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">GSAVI</a>: Green Soil Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00037-8" target="_blank">GVMI</a>: Global Vegetation Moisture Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://www.jipb.net/EN/abstract/abstract23925.shtml" target="_blank">IAVI</a>: New Atmospherically Resistant Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1006/anbo.1997.0544" target="_blank">IKAW</a>: Kawashima Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(90)90085-Z" target="_blank">IPVI</a>: Infrared Percentage Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2013.04.007" target="_blank">IRECI</a>: Inverted Red-Edge Chlorophyll Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1016/S0034-4257(00)00113-9" target="_blank">MCARI</a>: Modified Chlorophyll Absorption in Reflectance Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2003.12.013" target="_blank">MCARI1</a>: Modified Chlorophyll Absorption in Reflectance Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2003.12.013" target="_blank">MCARI2</a>: Modified Chlorophyll Absorption in Reflectance Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.agrformet.2008.03.005" target="_blank">MCARI705</a>: Modified Chlorophyll Absorption in Reflectance Index (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(00)00113-9" target="_blank">MCARIOSAVI</a>: MCARI/OSAVI Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.agrformet.2008.03.005" target="_blank">MCARIOSAVI705</a>: MCARI/OSAVI Ratio (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2015.02.012" target="_blank">MGRVI</a>: Modified Green Red Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/014311697216810" target="_blank">MNDVI</a>: Modified Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/TGRS.2003.812910" target="_blank">MNLI</a>: Modified Non-Linear Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/s20185055" target="_blank">MRBVI</a>: Modified Red Blue Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(94)90134-1" target="_blank">MSAVI</a>: Modified Soil-Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(89)90046-1" target="_blank">MSI</a>: Moisture Stress Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/07038992.1996.10855178" target="_blank">MSR</a>: Modified Simple Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.agrformet.2008.03.005" target="_blank">MSR705</a>: Modified Simple Ratio (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/0143116042000274015" target="_blank">MTCI</a>: MERIS Terrestrial Chlorophyll Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2003.12.013" target="_blank">MTVI1</a>: Modified Triangular Vegetation Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2003.12.013" target="_blank">MTVI2</a>: Modified Triangular Vegetation Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00010-X" target="_blank">mND705</a>: Modified Normalized Difference (705, 750 and 445 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00010-X" target="_blank">mSR705</a>: Modified Simple Ratio (705 and 445 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00010-X" target="_blank">ND705</a>: Normalized Difference (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1029/2006GL029127" target="_blank">NDDI</a>: Normalized Difference Drought Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2019.03.028" target="_blank">NDGI</a>: Normalized Difference Greenness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://www.asprs.org/wp-content/uploads/pers/1983journal/jan/1983_jan_77-83.pdf" target="_blank">NDII</a>: Normalized Difference Infrared Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00318-2" target="_blank">NDMI</a>: Normalized Difference Moisture Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2017.04.031" target="_blank">NDPI</a>: Normalized Difference Phenology Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/1011-1344(93)06963-4" target="_blank">NDREI</a>: Normalized Difference Red Edge Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://ntrs.nasa.gov/citations/19740022614" target="_blank">NDVI</a>: Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(11)81633-0" target="_blank">NDVI705</a>: Normalized Difference Vegetation Index (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2016.06.016" target="_blank">NDYI</a>: Normalized Difference Yellowness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(79)90013-0" target="_blank">NGRDI</a>: Normalized Green Red Difference Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.1602244" target="_blank">NIRv</a>: Near-Infrared Reflectance of Vegetation.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2021.112723" target="_blank">NIRvH2</a>: Hyperspectral Near-Infrared Reflectance of Vegetation.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2021.112763" target="_blank">NIRvP</a>: Near-Infrared Reflectance of Vegetation and Incoming PAR.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/02757259409532252" target="_blank">NLI</a>: Non-Linear Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1029/2007GL031021" target="_blank">NMDI</a>: Normalized Multi-band Drought Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs13010105" target="_blank">NRFIg</a>: Normalized Rapeseed Flowering Index Green.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs13010105" target="_blank">NRFIr</a>: Normalized Rapeseed Flowering Index Red.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">NormG</a>: Normalized Green.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">NormNIR</a>: Normalized NIR.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj2004.0314" target="_blank">NormR</a>: Normalized Red.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1007/s11119-008-9075-z" target="_blank">OCVI</a>: Optimized Chlorophyll Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(95)00186-7" target="_blank">OSAVI</a>: Optimized Soil-Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1034/j.1399-3054.1999.106119.x" target="_blank">PSRI</a>: Plant Senescing Reflectance Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(87)90088-5" target="_blank">RCC</a>: Red Chromatic Coordinate.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(94)00114-3" target="_blank">RDVI</a>: Renormalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/s18030868" target="_blank">REDSI</a>: Red-Edge Disease Stress Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(11)81633-0" target="_blank">RENDVI</a>: Red Edge Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2015.02.012" target="_blank">RGBVI</a>: Red Green Blue Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2014.03.018" target="_blank">RGRI</a>: Red-Green Ratio Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://www.documentation.ird.fr/hor/fdi:34390" target="_blank">RI</a>: Redness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2134/agronj1968.00021962006000060016x" target="_blank">RVI</a>: Ratio Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2013.04.007" target="_blank">S2REP</a>: Sentinel-2 Red-Edge Position.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/36.134076" target="_blank">SARVI</a>: Soil Adjusted and Atmospherically Resistant Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(88)90106-X" target="_blank">SAVI</a>: Soil-Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431169008955053" target="_blank">SAVI2</a>: Soil-Adjusted Vegetation Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/17538947.2018.1495770" target="_blank">SEVI</a>: Shadow-Eliminated Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf" target="_blank">SI</a>: Shadow Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://eurekamag.com/research/009/395/009395053.php" target="_blank">SIPI</a>: Structure Insensitive Pigment Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://www.asprs.org/wp-content/uploads/pers/2000journal/february/2000_feb_183-191.pdf" target="_blank">SLAVI</a>: Specific Leaf Area Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.2307/1936256" target="_blank">SR</a>: Simple Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431169308904370" target="_blank">SR2</a>: Simple Ratio (800 and 550 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(98)00046-7" target="_blank">SR3</a>: Simple Ratio (860, 550 and 708 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(11)81633-0" target="_blank">SR555</a>: Simple Ratio (555 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0176-1617(11)81633-0" target="_blank">SR705</a>: Simple Ratio (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/s19040904" target="_blank">SeLI</a>: Sentinel-2 LAI Green Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00018-4" target="_blank">TCARI</a>: Transformed Chlorophyll Absorption in Reflectance Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(02)00018-4" target="_blank">TCARIOSAVI</a>: TCARI/OSAVI Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.agrformet.2008.03.005" target="_blank">TCARIOSAVI705</a>: TCARI/OSAVI Ratio (705 and 750 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1109/TGRS.2007.904836" target="_blank">TCI</a>: Triangular Chlorophyll Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.2002.1026867" target="_blank">TDVI</a>: Transformed Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1016/j.jag.2012.07.020" target="_blank">TGI</a>: Triangular Greenness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs12152359" target="_blank">TRRVI</a>: Transformed Red Range Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.1989.576128" target="_blank">TSAVI</a>: Transformed Soil-Adjusted Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs12010016" target="_blank">TTVI</a>: Transformed Triangular Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://ntrs.nasa.gov/citations/19740022614" target="_blank">TVI</a>: Transformed Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1016/S0034-4257(00)00197-8" target="_blank">TriVI</a>: Triangular Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00289-9" target="_blank">VARI</a>: Visible Atmospherically Resistant Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00289-9" target="_blank">VARI700</a>: Visible Atmospherically Resistant Index (700 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00289-9" target="_blank">VI700</a>: Vegetation Index (700 nm).</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(01)00289-9" target="_blank">VIG</a>: Vegetation Index Green.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1078/0176-1617-01176" target="_blank">WDRVI</a>: Wide Dynamic Range Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/0034-4257(89)90076-X" target="_blank">WDVI</a>: Weighted Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
</table>
## Water
<table><tr><td width="50%"><a href="https://doi.org/10.1016/j.envsoft.2021.105030" target="_blank">ANDWI</a>: Augmented Normalized Difference Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2013.08.029" target="_blank">AWEInsh</a>: Automated Water Extraction Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2013.08.029" target="_blank">AWEIsh</a>: Automated Water Extraction Index with Shadows Elimination.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2003.11.008" target="_blank">LSWI</a>: Land Surface Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2018.01.018" target="_blank">MBWI</a>: Multi-Band Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs71215805" target="_blank">MLSWI26</a>: Modified Land Surface Water Index (MODIS Bands 2 and 6).</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs71215805" target="_blank">MLSWI27</a>: Modified Land Surface Water Index (MODIS Bands 2 and 7).</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160600589179" target="_blank">MNDWI</a>: Modified Normalized Difference Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs10101643" target="_blank">MuWIR</a>: Revised Multi-Spectral Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2011.10.016" target="_blank">NDCI</a>: Normalized Difference Chlorophyll Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2006.07.012" target="_blank">NDPonI</a>: Normalized Difference Pond Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2006.07.012" target="_blank">NDTI</a>: Normalized Difference Turbidity Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1007/978-3-662-45737-5_51" target="_blank">NDVIMNDWI</a>: NDVI-MNDWI Model.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431169608948714" target="_blank">NDWI</a>: Normalized Difference Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/w12051339" target="_blank">NDWIns</a>: Normalized Difference Water Index with no Snow Cover and Glaciers.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.11873/j.issn.1004-0323.2009.2.167" target="_blank">NWI</a>: New Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/w13121647" target="_blank">S2WI</a>: Sentinel-2 Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://eoscience.esa.int/landtraining2017/files/posters/MILCZAREK.pdf" target="_blank">SWM</a>: Sentinel Water Mask.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs14215289" target="_blank">TWI</a>: Triangle Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs11182186" target="_blank">WI1</a>: Water Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs11182186" target="_blank">WI2</a>: Water Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2015.12.055" target="_blank">WI2015</a>: Water Index 2015.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/GEOINFORMATICS.2010.5567762" target="_blank">WRI</a>: Water Ratio Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
</table>
## Burn
<table><tr><td width="50%"><a href="https://digital.csic.es/bitstream/10261/6426/1/Martin_Isabel_Serie_Geografica.pdf" target="_blank">BAI</a>: Burned Area Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.foreco.2006.08.248" target="_blank">BAIM</a>: Burned Area Index adapted to MODIS.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/ecrs-2-05177" target="_blank">BAIS2</a>: Burned Area Index for Sentinel 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2005.04.014" target="_blank">CSI</a>: Char Soil Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160600954704" target="_blank">CSIT</a>: Char Soil Index Thermal.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160110053185" target="_blank">MIRBI</a>: Mid-Infrared Burn Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3133/ofr0211" target="_blank">NBR</a>: Normalized Burn Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://www.usgs.gov/core-science-systems/nli/landsat/landsat-normalized-burn-ratio-2" target="_blank">NBR2</a>: Normalized Burn Ratio 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/22797254.2020.1738900" target="_blank">NBRSWIR</a>: Normalized Burn Ratio SWIR.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160500239008" target="_blank">NBRT1</a>: Normalized Burn Ratio Thermal 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160500239008" target="_blank">NBRT2</a>: Normalized Burn Ratio Thermal 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160500239008" target="_blank">NBRT3</a>: Normalized Burn Ratio Thermal 3.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs14071727" target="_blank">NBRplus</a>: Normalized Burn Ratio Plus.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/TGRS.2003.819190" target="_blank">NDSWIR</a>: Normalized Difference SWIR.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160600954704" target="_blank">NDVIT</a>: Normalized Difference Vegetation Index Thermal.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2011.06.010" target="_blank">NSTv1</a>: NIR-SWIR-Temperature Version 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2011.06.010" target="_blank">NSTv2</a>: NIR-SWIR-Temperature Version 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160600954704" target="_blank">SAVIT</a>: Soil-Adjusted Vegetation Index Thermal.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160500239008" target="_blank">VI6T</a>: VI6T Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
</table>
## Snow
<table><tr><td width="50%"><a href="https://doi.org/10.3390/rs13142777" target="_blank">NBSIMS</a>: Non-Binary Snow Index for Multi-Component Surfaces.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160802385459" target="_blank">NDGlaI</a>: Normalized Difference Glacier Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.1994.399618" target="_blank">NDSI</a>: Normalized Difference Snow Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160802385459" target="_blank">NDSII</a>: Normalized Difference Snow Ice Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/w12051339" target="_blank">NDSInw</a>: Normalized Difference Snow Index with no Water.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160119766" target="_blank">NDSaII</a>: Normalized Difference Snow and Ice Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3178/jjshwr.12.28" target="_blank">S3</a>: S3 Snow Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs11232774" target="_blank">SWI</a>: Snow Water Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
</table>
## Urban
<table><tr><td width="50%"><a href="https://doi.org/10.1080/10106049.2018.1497094" target="_blank">BLFEI</a>: Built-Up Land Features Extraction Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://www.omicsonline.org/scientific-reports/JGRS-SR136.pdf" target="_blank">BRBA</a>: Band Ratio for Built-up Area.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/land7030081" target="_blank">DBI</a>: Dry Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs4102957" target="_blank">EBBI</a>: Enhanced Built-Up and Bareness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1080/01431160802039957" target="_blank">IBI</a>: Index-Based Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://www.omicsonline.org/scientific-reports/JGRS-SR136.pdf" target="_blank">NBAI</a>: Normalized Built-up Area Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://hdl.handle.net/1959.11/29500" target="_blank">NBUI</a>: New Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1080/01431160304987" target="_blank">NDBI</a>: Normalized Difference Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.14358/PERS.76.5.557" target="_blank">NDISIb</a>: Normalized Difference Impervious Surface Index Blue.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.14358/PERS.76.5.557" target="_blank">NDISIg</a>: Normalized Difference Impervious Surface Index Green.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.14358/PERS.76.5.557" target="_blank">NDISImndwi</a>: Normalized Difference Impervious Surface Index with MNDWI.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.14358/PERS.76.5.557" target="_blank">NDISIndwi</a>: Normalized Difference Impervious Surface Index with NDWI.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.14358/PERS.76.5.557" target="_blank">NDISIr</a>: Normalized Difference Impervious Surface Index Red.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://www.semanticscholar.org/paper/Using-WorldView-2-Vis-NIR-MSI-Imagery-to-Support-Wolf/5e5063ccc4ee76b56b721c866e871d47a77f9fb4" target="_blank">NHFD</a>: Non-Homogeneous Feature Difference.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs10101521" target="_blank">PISI</a>: Perpendicular Impervious Surface Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://www.isprs.org/proceedings/XXXI/congress/part7/321_XXXI-part7.pdf" target="_blank">UI</a>: Urban Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="http://dx.doi.org/10.1080/01431161.2012.687842" target="_blank">VIBI</a>: Vegetation Index Built-up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.ecolind.2015.03.037" target="_blank">VgNIRBI</a>: Visible Green-Based Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.ecolind.2015.03.037" target="_blank">VrNIRBI</a>: Visible Red-Based Built-Up Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
</table>
## Soil
<table><tr><td width="50%"><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf" target="_blank">BI</a>: Bare Soil Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(98)00030-3" target="_blank">BITM</a>: Landsat TM-based Brightness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(98)00030-3" target="_blank">BIXS</a>: SPOT HRV XS-based Brightness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.2005.1525743" target="_blank">BaI</a>: Bareness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/land7030081" target="_blank">DBSI</a>: Dry Bareness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2022.102703" target="_blank">EMBI</a>: Enhanced Modified Bare Soil Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/land10030231" target="_blank">MBI</a>: Modified Bare Soil Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs9030249" target="_blank">NBLI</a>: Normalized Difference Bare Land Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/rs9030249" target="_blank">NBLIOLI</a>: Normalized Difference Bare Land Index for Landsat-OLI.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.2005.1526319" target="_blank">NDBaI</a>: Normalized Difference Bareness Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> </td></tr>
<tr><td width="50%"><a href="https://www.semanticscholar.org/paper/Using-WorldView-2-Vis-NIR-MSI-Imagery-to-Support-Wolf/5e5063ccc4ee76b56b721c866e871d47a77f9fb4" target="_blank">NDSIWV</a>: WorldView Normalized Difference Soil Index.</td><td width="50%"></td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.jag.2015.02.010" target="_blank">NDSoI</a>: Normalized Difference Soil Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/land10030231" target="_blank">NSDS</a>: Normalized Shortwave Infrared Difference Soil-Moisture.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2019.06.012" target="_blank">NSDSI1</a>: Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 1.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2019.06.012" target="_blank">NSDSI2</a>: Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 2.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.isprsjprs.2019.06.012" target="_blank">NSDSI3</a>: Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 3.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/S0034-4257(98)00030-3" target="_blank">RI4XS</a>: SPOT HRV XS-based Redness Index 4.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
</table>
## Kernel
<table><tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.abc7447" target="_blank">kEVI</a>: Kernel Enhanced Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.abc7447" target="_blank">kIPVI</a>: Kernel Infrared Percentage Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.abc7447" target="_blank">kNDVI</a>: Kernel Normalized Difference Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.abc7447" target="_blank">kRVI</a>: Kernel Ratio Vegetation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1126/sciadv.abc7447" target="_blank">kVARI</a>: Kernel Visible Atmospherically Resistant Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS"> <img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM"> <img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+"> <img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI"> <img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2"> <img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion"> </td></tr>
</table>
## Radar
<table><tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2018.09.003" target="_blank">DPDD</a>: Dual-Pol Diagonal Distance.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://www.tandfonline.com/doi/abs/10.5589/m12-043" target="_blank">DpRVIHH</a>: Dual-Polarized Radar Vegetation Index HH.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20HH%20HV)-gray?style=flat-square" alt="(Dual Polarisation HH-HV)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/app9040655" target="_blank">DpRVIVV</a>: Dual-Polarized Radar Vegetation Index VV.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://www.isprs.org/proceedings/XXXVII/congress/4_pdf/267.pdf" target="_blank">NDPolI</a>: Normalized Difference Polarization Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS.2001.976856" target="_blank">QpRVI</a>: Quad-Polarized Radar Vegetation Index.</td><td width="50%"></td></tr>
<tr><td width="50%"><a href="https://doi.org/10.5194/bg-9-179-2012" target="_blank">RFDI</a>: Radar Forest Degradation Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20HH%20HV)-gray?style=flat-square" alt="(Dual Polarisation HH-HV)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1016/j.rse.2018.09.003" target="_blank">VDDPI</a>: Vertical Dual De-Polarization Index.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/app9040655" target="_blank">VHVVD</a>: VH-VV Difference.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS47720.2021.9554099" target="_blank">VHVVP</a>: VH-VV Product.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS47720.2021.9554099" target="_blank">VHVVR</a>: VH-VV Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS47720.2021.9554099" target="_blank">VVVHD</a>: VV-VH Difference.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.3390/app9040655" target="_blank">VVVHR</a>: VV-VH Ratio.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
<tr><td width="50%"><a href="https://doi.org/10.1109/IGARSS47720.2021.9554099" target="_blank">VVVHS</a>: VV-VH Sum.</td><td width="50%"> <img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)"> </td></tr>
</table>
# List
Check the full list of spectral indices with their formulas [here](https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-table.csv).
# Download Raw Files
You can download or clone the repository:
```
git clone https://github.com/davemlz/awesome-ee-spectral-indices.git
```
Or you can download the single files here (right-click > Save link as...):
- JSON: [Raw list](https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-dict.json)
- CSV: [Raw list](https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-table.csv)
# Credits
- [<NAME>](https://github.com/csaybar): The formidable [pydantic](https://github.com/samuelcolvin/pydantic/) expert and creator of [rgee](https://github.com/r-spatial/rgee).
<file_sep>/src/SpectralIndex.py
import re
import orjson
from py_expression_eval import Parser, Expression
from pydantic import BaseModel, validator
from src.utils import Bands, IndexType
from datetime import date
from typing import Optional, List
def orjson_dumps(value, *, default):
"""
orjson.dumps returns bytes, to match standard json.dumps we need to decode
"""
return orjson.dumps(value, default=default).decode()
class SpectralIndex(BaseModel):
"""
Python dataclass for Spectral Indices
"""
contributor: str
short_name: str
reference: str
long_name: str
formula: str
bands: Optional[List] = None
platforms: Optional[List] = None
application_domain: str
date_of_addition: date
class Config:
extra = "forbid"
json_loads = orjson.loads
json_dumps = orjson_dumps
@validator("short_name")
def check_short_name(cls, value):
if re.search(r"\s+", value):
raise ValueError("short_name must not contain spaces.")
return value
@validator("formula")
def check_formula(cls, value):
parser = Parser()
expression = parser.parse(value)
variables = expression.variables() # obtain band names (e.g. ["R", "G"])
# check Expression
if not isinstance(expression, Expression):
raise ValueError("Invalid formula.")
# check if the variables are in "Bands".
if not all(elem in Bands._value2member_map_ for elem in variables):
band_names = ", ".join(Bands._value2member_map_.keys())
raise ValueError(
"Invalid variables in formula. SpectralIndex only supports the following variables: "
+ band_names
)
return value
@validator("contributor")
def check_contributor(cls, value):
# regex to detect emails or github profiles.
email_regex = r"^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$"
github_regex = r"(?:https?://)?(?:www[.])?github[.]com/[\w-]+/?"
full_regex = "%s|%s" % (email_regex, github_regex)
# Check if it is a correct email address or GitHub profile.
if not re.match(full_regex, value):
raise ValueError("contributor is neither a GitHub profile nor an email.")
return value
@validator("application_domain")
def check_type(cls, value):
# Obtain names of IndexType enum.
IndexTypeNames = ", ".join(IndexType._value2member_map_.keys())
# Check if IndexTtpe is supported.
if not value in IndexType._value2member_map_:
raise ValueError(
"Invalid IndexType. SpectralIndex only supports the following IndexType: "
+ IndexTypeNames
)
return value
<file_sep>/main.py
from src.indices import spindex
from src.utils import Bands
from src.bands import bands
from src.constants import constants
from py_expression_eval import Parser
import pandas as pd
import json
bandVars = [
"A",
"B",
"G1",
"G",
"Y",
"R",
"N",
"N2",
"WV",
"RE1",
"RE2",
"RE3",
"S1",
"S2",
"T",
"T1",
"T2",
"HV",
"HH",
"VV",
"VH",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
]
bandsPlatform = {
"Sentinel-1 (Dual Polarisation VV-VH)": ["VV", "VH"],
"Sentinel-1 (Dual Polarisation HH-HV)": [
"HV",
"HH",
],
"Sentinel-2": [
"A",
"B",
"G",
"R",
"N",
"N2",
"RE1",
"RE2",
"RE3",
"WV",
"S1",
"S2",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
"Landsat-OLI": [
"A",
"B",
"G",
"R",
"N",
"S1",
"S2",
"T1",
"T2",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
"Landsat-TM": [
"B",
"G",
"R",
"N",
"S1",
"S2",
"T",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
"Landsat-ETM+": [
"B",
"G",
"R",
"N",
"S1",
"S2",
"T",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
"MODIS": [
"B",
"G1",
"G",
"R",
"N",
"S1",
"S2",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
"Planet-Fusion": [
"B",
"G",
"R",
"N",
"kNN",
"kNR",
"kNB",
"kNL",
"kGG",
"kGR",
"kGB",
"kBB",
"kBR",
"kBL",
"kRR",
"kRB",
"kRL",
"kLL",
],
}
bandsToCheck = list(Bands._value2member_map_.keys())
[bandsToCheck.remove(i) for i in bandVars]
def checkPlatforms(bandsSpindex):
availablePlatforms = []
for platform, bandList in bandsPlatform.items():
if all([x in bandsToCheck + bandList for x in bandsSpindex]):
availablePlatforms.append(platform)
return availablePlatforms
parser = Parser()
# Adding band attribute
for key in spindex.SpectralIndices:
SpectralIndex = spindex.SpectralIndices[key]
formula = parser.parse(SpectralIndex.formula)
SpectralIndex.bands = formula.variables()
SpectralIndex.platforms = checkPlatforms(SpectralIndex.bands)
spindex.SpectralIndices[key] = SpectralIndex
# 
# 
# 
# 
# 
# Save results
with open("output/spectral-indices-dict.json", "w") as fp:
json.dump(
json.loads(spindex.model_dump_json(indent=4)), fp, indent=4, sort_keys=True
)
with open("output/bands.json", "w") as fp:
json.dump(bands, fp, indent=4, sort_keys=True)
with open("output/constants.json", "w") as fp:
json.dump(constants, fp, indent=4, sort_keys=True)
# Convert to pandas and save CSV
file = open("output/spectral-indices-dict.json")
indices = json.load(file)
df = pd.DataFrame(list(indices["SpectralIndices"].values()))
df = df[
[
"short_name",
"long_name",
"application_domain",
"formula",
"bands",
"reference",
"contributor",
"date_of_addition",
]
]
df.to_csv("output/spectral-indices-table.csv", index=False)
# Save tables for Docs
def toMath(x):
x = x.replace(" ", "")
x = x.replace("**", "^")
x = x.replace("^2.0", "^{2.0}")
x = x.replace("^0.5", "^{0.5}")
x = x.replace("^nexp", "^{n}")
x = x.replace("^cexp", "^{c}")
x = x.replace("gamma", "\\gamma ")
x = x.replace("alpha", "\\alpha ")
x = x.replace("beta", "\\beta ")
x = x.replace("omega", "\\omega ")
x = x.replace("lambdaN", "\\lambda_{N} ")
x = x.replace("lambdaR", "\\lambda_{R} ")
x = x.replace("lambdaG", "\\lambda_{G} ")
x = x.replace("*", "\\times ")
x = f":math:`{x}`"
return x
df["Equation"] = df["formula"].apply(toMath)
df["Long Name"] = df["long_name"] + " [`ref <" + df["reference"] + ">`_]"
df["Index"] = df["short_name"]
for t in ["vegetation", "burn", "water", "snow", "urban", "soil", "kernel", "radar"]:
name = "docs/_static/indices_" + t + ".csv"
df[df["application_domain"] == t][["Index", "Long Name", "Equation"]].to_csv(
name, index=False
)
<file_sep>/readme.py
import json
with open("output/spectral-indices-dict.json", "r") as f:
data = json.load(f)
previousText = """<p align="center">
<a href="https://github.com/davemlz/awesome-spectral-indices"><img src="https://raw.githubusercontent.com/davemlz/awesome-spectral-indices/main/docs/_static/asi.png" alt="Awesome Spectral Indices"></a>
</p>
<p align="center">
<em>A ready-to-use curated list of Spectral Indices for Remote Sensing applications.</em>
</p>
<p align="center">
<a href="https://github.com/sindresorhus/awesome" target="_blank">
<img src="https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg" alt="Awesome">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-dict.json" target="_blank">
<img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/davemlz/5e9f08fa6a45d9d486e29d9d85ad5c84/raw/spectral.json" alt="Awesome Spectral Indices">
</a>
<a href="https://share.streamlit.io/davemlz/espectro/main/espectro.py" target="_blank">
<img src="https://static.streamlit.io/badges/streamlit_badge_black_white.svg" alt="Streamlit">
</a>
<a href="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml" target="_blank">
<img src="https://github.com/davemlz/awesome-ee-spectral-indices/actions/workflows/tests.yml/badge.svg" alt="Tests">
</a>
<a href="https://awesome-ee-spectral-indices.readthedocs.io/en/latest/?badge=latest" target="_blank">
<img src="https://readthedocs.org/projects/awesome-ee-spectral-indices/badge/?version=latest" alt="Documentation">
</a>
<a href="https://zenodo.org/badge/latestdoi/355720108"><img src="https://zenodo.org/badge/355720108.svg" alt="DOI"></a>
<a href="https://github.com/sponsors/davemlz" target="_blank">
<img src="https://img.shields.io/badge/GitHub%20Sponsors-Donate-ff69b4.svg" alt="GitHub Sponsors">
</a>
<a href="https://www.buymeacoffee.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-Donate-ff69b4.svg" alt="Buy me a coffee">
</a>
<a href="https://ko-fi.com/davemlz" target="_blank">
<img src="https://img.shields.io/badge/kofi-Donate-ff69b4.svg" alt="Ko-fi">
</a>
<a href="https://twitter.com/dmlmont" target="_blank">
<img src="https://img.shields.io/twitter/follow/dmlmont?style=social" alt="Twitter">
</a>
<a href="https://github.com/psf/black" target="_blank">
<img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Black">
</a>
</p>
---
**GitHub**: <a href="https://github.com/awesome-spectral-indices/awesome-spectral-indices" target="_blank">github.com/awesome-spectral-indices/awesome-spectral-indices</a>
**Documentation**: <a href="https://awesome-ee-spectral-indices.readthedocs.io/" target="_blank">awesome-ee-spectral-indices.readthedocs.io</a>
**Python Package**: <a href="https://github.com/awesome-spectral-indices/spyndex" target="_blank">github.com/awesome-spectral-indices/spyndex</a>
**Paper**: <a href="https://doi.org/10.1038/s41597-023-02096-0" target="_blank">doi.org/10.1038/s41597-023-02096-0</a>
**Streamlit App**: <a href="https://github.com/awesome-spectral-indices/espectro" target="_blank">github.com/awesome-spectral-indices/espectro</a>
**Google Earth Engine**: <a href="https://github.com/davemlz/eemont" target="_blank">github.com/davemlz/eemont</a> (Python), <a href="https://github.com/awesome-spectral-indices/spectral" target="_blank">github.com/awesome-spectral-indices/spectral</a> (JavaScript) and <a href="https://github.com/r-earthengine/rgeeExtra" target="_blank">github.com/r-earthengine/rgeeExtra</a> (R)
---
# Spectral Indices
Spectral Indices are widely used in the Remote Sensing community. This repository keeps track of classical as well as novel spectral indices for different Remote Sensing applications. All spectral indices in the repository are curated and can be used in different environments and programming languages.
You can check the [curated list of spectral indices here](https://github.com/awesome-spectral-indices/awesome-spectral-indices/blob/main/output/spectral-indices-table.csv), and if you want to use it in your environment, it is available in [CSV](https://raw.githubusercontent.com/awesome-spectral-indices/awesome-spectral-indices/main/output/spectral-indices-table.csv) and [JSON](https://raw.githubusercontent.com/awesome-spectral-indices/awesome-spectral-indices/main/output/spectral-indices-dict.json).
## Attributes
All spectral indices follow a standard. Each item of the list has the following attributes:
- `short_name`: Short name of the index (e.g. `"NDWI"`).
- `long_name`: Long name of the index (e.g. `"Normalized Difference Water Index"`).
- `formula`: Expression/formula of the index (e.g. `"(G - N)/(G + N)"`).
- `bands`: List of required bands/parameters for the index computation (e.g. `["N","G"]`).
- `platforms`: List of platforms with the required bands for the index computation (e.g. `["MODIS", "Landsat-457", "Landsat-89", "Sentinel-2"]`).
- `reference`: Link to the index reference/paper/doi (e.g. `"https://doi.org/10.1080/01431169608948714"`).
- `application_domain`: Application domain of the index (e.g. `"water"`).
- `date_of_addition`: Date of addition to the list (e.g. `"2021-04-07"`).
- `contributor`: GitHub user link of the contributor (e.g. `"https://github.com/davemlz"`).
## Expressions
The formula of the index is presented as a string/expression (e.g. `"(N - R)/(N + R)"`) that can be easily evaluated. The parameters used in the expression for each index follow this standard:
<table>
<tr>
<th> Description </th>
<th> Standard </th>
<th> Spectral Range (nm) </th>
<th> Sentinel-2 </th>
<th> Landsat-89 </th>
<th> Landsat-457 </th>
<th> MODIS </th>
</tr>
<tr>
<td>Aerosols</td>
<td>A</td>
<td>400 - 455</td>
<td>B1</td>
<td>B1</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Blue</td>
<td>B</td>
<td>450 - 530</td>
<td>B2</td>
<td>B2</td>
<td>B1</td>
<td>B3</td>
</tr>
<tr>
<td>Green 1</td>
<td>G1</td>
<td>510 - 550</td>
<td></td>
<td></td>
<td></td>
<td>B11</td>
</tr>
<tr>
<td>Green</td>
<td>G</td>
<td>510 - 600</td>
<td>B3</td>
<td>B3</td>
<td>B2</td>
<td>B4</td>
</tr>
<tr>
<td>Yellow</td>
<td>Y</td>
<td>585 - 625</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red</td>
<td>R</td>
<td>620 - 690</td>
<td>B4</td>
<td>B4</td>
<td>B3</td>
<td>B1</td>
</tr>
<tr>
<td>Red Edge 1</td>
<td>RE1</td>
<td>695 - 715</td>
<td>B5</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red Edge 2</td>
<td>RE2</td>
<td>730 - 750</td>
<td>B6</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Red Edge 3</td>
<td>RE3</td>
<td>765 - 795</td>
<td>B7</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>NIR</td>
<td>N</td>
<td>760 - 900</td>
<td>B8</td>
<td>B5</td>
<td>B4</td>
<td>B2</td>
</tr>
<tr>
<td>NIR 2</td>
<td>N2</td>
<td>850 - 880</td>
<td>B8A</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Water Vapour</td>
<td>WV</td>
<td>930 - 960</td>
<td>B9</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>SWIR 1</td>
<td>S1</td>
<td>1550 - 1750</td>
<td>B11</td>
<td>B6</td>
<td>B5</td>
<td>B6</td>
</tr>
<tr>
<td>SWIR 2</td>
<td>S2</td>
<td>2080 - 2350</td>
<td>B12</td>
<td>B7</td>
<td>B7</td>
<td>B7</td>
</tr>
<tr>
<td>Thermal</td>
<td>T</td>
<td>10400 - 12500</td>
<td></td>
<td></td>
<td>B6</td>
<td></td>
</tr>
<tr>
<td>Thermal 1</td>
<td>T1</td>
<td>10600 - 11190</td>
<td></td>
<td>B10</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Thermal 2</td>
<td>T2</td>
<td>11500 - 12510</td>
<td></td>
<td>B11</td>
<td></td>
<td></td>
</tr>
</table>
In the case of RADAR Indices, the bands follow this standard:
<table>
<tr>
<th> Description </th>
<th> Standard </th>
<th> Sentinel-1 </th>
</tr>
<tr>
<td>Backscattering Coefficient HV</td>
<td>HV</td>
<td>HV</td>
</tr>
<tr>
<td>Backscattering Coefficient VH</td>
<td>VH</td>
<td>VH</td>
</tr>
<tr>
<td>Backscattering Coefficient HH</td>
<td>HH</td>
<td>HH</td>
</tr>
<tr>
<td>Backscattering Coefficient VV</td>
<td>VV</td>
<td>VV</td>
</tr>
</table>
Additional index parameters also follow a standard:
- `g`: Gain factor (e.g. Used for EVI).
- `L`: Canopy background adjustment (e.g. Used for SAVI and EVI).
- `C1`: Coefficient 1 for the aerosol resistance term (e.g. Used for EVI).
- `C2`: Coefficient 2 for the aerosol resistance term (e.g. Used for EVI).
- `cexp`: Exponent used for OCVI.
- `nexp`: Exponent used for GDVI.
- `alpha`: Weighting coefficient used for WDRVI, BWDRVI and NDPI.
- `beta`: Calibration parameter used for NDSIns.
- `gamma`: Weighting coefficient used for ARVI.
- `omega`: Weighting coefficient used for MBWI.
- `sla`: Soil line slope.
- `slb`: Soil line intercept.
- `PAR`: Photosynthetically Active Radiation.
- `k`: Slope parameter by soil used for NIRvH2.
- `lambdaN`: NIR wavelength used for NIRvH2 and NDGI.
- `lambdaR`: Red wavelength used for NIRvH2 and NDGI.
- `lambdaG`: Green wavelength used for NDGI.
The kernel indices are constructed using a special type of parameters:
- `kAB`: Kernel of bands/parameters `A` and `B` (e.g. `kNR` means `k(N,R)`, where `k` is the kernel function).
- `p`: Kernel degree (used for the polynomial kernel).
- `c`: Free parameter that trades off the influence of higher-order versus lower-order terms (used for the polynomial kernel).
# Call for Indices! :rotating_light:
Researchers that have published (or aim to publish) their novel spectral indices are encouraged to add them to this repository! The list of spectral indices is used as a source for different resources that allow spectral indices computation in different environments (such as Python and Google Earth Engine). To add an index, please follow the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html).
In the same line, if you know an spectral index that is not included in this repository, you are encouraged to add it! Please follow the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html) in order to add it.
And one more thing: If you see an error in one or several indices, please report it or update the index (indices) by following the [Contribution Guidelines](https://awesome-ee-spectral-indices.readthedocs.io/en/latest/contributing.html)!
There is no deadline. The repository is continuously updated!
# Used by
## JavaScript
- [spectral](https://github.com/davemlz/spectral): Awesome Spectral Indices for the Google Earth Engine JavaScript API (Code Editor).
## Python
- [eemont](https://github.com/davemlz/eemont): A Python package that extends Google Earth Engine.
- [eeExtra](https://github.com/r-earthengine/ee_extra): A Python package that unifies the Google Earth Engine ecosystem.
- [Espectro](https://github.com/davemlz/espectro): The Awesome Spectral Indices Streamlit App.
- [spyndex](https://github.com/davemlz/spyndex): Awesome Spectral Indices in Python.
## R
- [rgeeExtra](https://github.com/r-earthengine/rgeeExtra): High-level functions to process spatial and simple Earth Engine objects.
# Spectral Indices by Application Domain
"""
nextText = """
# List
Check the full list of spectral indices with their formulas [here](https://github.com/davemlz/awesome-ee-spectral-indices/blob/main/output/spectral-indices-table.csv).
# Download Raw Files
You can download or clone the repository:
```
git clone https://github.com/davemlz/awesome-ee-spectral-indices.git
```
Or you can download the single files here (right-click > Save link as...):
- JSON: [Raw list](https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-dict.json)
- CSV: [Raw list](https://raw.githubusercontent.com/davemlz/awesome-ee-spectral-indices/main/output/spectral-indices-table.csv)
# Credits
- [<NAME>](https://github.com/csaybar): The formidable [pydantic](https://github.com/samuelcolvin/pydantic/) expert and creator of [rgee](https://github.com/r-spatial/rgee).
"""
platformBadges = {
"MODIS": "",
"Landsat-457": "",
"Landsat-89": "",
"Sentinel-1 (Dual Polarisation VV-VH)": "-lightgray?style=flat-square)",
"Sentinel-1 (Dual Polarisation HH-HV)": "-gray?style=flat-square)",
"Sentinel-2": "",
"Planet-Fusion": "",
}
platformBadgesHTML = {
"MODIS": '<img src="https://img.shields.io/badge/-MODIS-green?style=flat-square" alt="MODIS">',
"Landsat-TM": '<img src="https://img.shields.io/badge/-Landsat%20TM-blueviolet?style=flat-square" alt="Landsat-TM">',
"Landsat-ETM+": '<img src="https://img.shields.io/badge/-Landsat%20ETM+-purple?style=flat-square" alt="Landsat-ETM+">',
"Landsat-OLI": '<img src="https://img.shields.io/badge/-Landsat%20OLI-blue?style=flat-square" alt="Landsat-OLI">',
"Sentinel-1 (Dual Polarisation VV-VH)": '<img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20VV%20VH)-lightgray?style=flat-square" alt="(Dual Polarisation VV-VH)">',
"Sentinel-1 (Dual Polarisation HH-HV)": '<img src="https://img.shields.io/badge/-Sentinel%201%20(Dual%20HH%20HV)-gray?style=flat-square" alt="(Dual Polarisation HH-HV)">',
"Sentinel-2": '<img src="https://img.shields.io/badge/-Sentinel%202-red?style=flat-square" alt="Sentinel-2">',
"Planet-Fusion": '<img src="https://img.shields.io/badge/-Planet%20Fusion-yellow?style=flat-square" alt="Planet-Fusion">',
}
letters = list(map(chr, range(65, 91)))
def filterByAppDomain():
indices = []
for index, attributes in data["SpectralIndices"].items():
if attributes["application_domain"] == appDomain:
indices.append(index)
return indices
# text = []
# for appDomain in ["vegetation","water","burn","snow","urban","kernel","radar"]:
# text.append(f"## {appDomain.capitalize()}\n\n")
# for letter in letters:
# if any([x.upper().startswith(letter) for x in filterByAppDomain()]):
# text.append(f"### {letter}\n")
# for index, attributes in data["SpectralIndices"].items():
# if attributes['type'] == appDomain:
# if index.startswith(letter) or index.startswith(letter.lower()):
# line = f"- [{index}]({attributes['reference']}): {attributes['long_name']}."
# text.append(line)
# for platform, badge in platformBadges.items():
# if platform in attributes['platforms']:
# text.append(f" {badge} ")
# text.append("\n")
text = []
for appDomain in [
"vegetation",
"water",
"burn",
"snow",
"urban",
"soil",
"kernel",
"radar",
]:
text.append(f"\n## {appDomain.capitalize()}\n\n<table>")
for letter in letters:
if any([x.upper().startswith(letter) for x in filterByAppDomain()]):
# text.append(f'\n### {letter}\n<table>')
for index, attributes in data["SpectralIndices"].items():
if attributes["application_domain"] == appDomain:
if index.startswith(letter) or index.startswith(letter.lower()):
link = attributes["reference"]
name = attributes["long_name"]
line = f'<tr><td width="50%"><a href="{link}" target="_blank">{index}</a>: {name}.</td><td width="50%">'
text.append(line)
for platform, badge in platformBadgesHTML.items():
if platform in attributes["platforms"]:
text.append(f" {badge} ")
text.append("</td></tr>\n")
text.append("</table>\n")
with open("README.md", "w") as f:
f.write(previousText + "".join(text) + nextText)
<file_sep>/docs/list.rst
Spectral Indices by Type
============================
.. note::
All spectral indices listed here are considered broad-band spectral indices. Narrow-band spectral indices are coerced to the closest broad-band spectrum.
Vegetation
--------------
.. csv-table:: Vegetation Spectral Indices
:file: _static/indices_vegetation.csv
:header-rows: 1
Burn
--------------
.. csv-table:: Burn Spectral Indices
:file: _static/indices_burn.csv
:header-rows: 1
Water
--------------
.. csv-table:: Water Spectral Indices
:file: _static/indices_water.csv
:header-rows: 1
Snow
--------------
.. csv-table:: Snow Spectral Indices
:file: _static/indices_snow.csv
:header-rows: 1
Soil
--------------
.. csv-table:: Soil Spectral Indices
:file: _static/indices_soil.csv
:header-rows: 1
Urban
--------------
.. csv-table:: Urban Spectral Indices
:file: _static/indices_urban.csv
:header-rows: 1
Kernel
--------------
.. warning::
All kernel indices listed here were extracted from the `Supplementary Material <http://advances.sciencemag.org/cgi/content/full/7/9/eabc7447/DC1>`_ of `Camps-Valls et al., 2021 <https://doi.org/10.1126/sciadv.abc7447>`_. Please note that the kEVI and kVARI indices may have more than one implementation, but for simplicity, just one is presented here.
.. csv-table:: Kernel Spectral Indices
:file: _static/indices_kernel.csv
:header-rows: 1
RADAR
--------------
.. csv-table:: RADAR Spectral Indices
:file: _static/indices_radar.csv
:header-rows: 1<file_sep>/docs/contributing.rst
Do you want to contribute?
==============================
Contributing to the list is pretty simple:
The easiest way
-------------------------------
Open an issue with the following information:
- :code:`short_name`: Short name of the index (e.g. :code:`"NDWI"`).
- :code:`long_name`: Long name of the index (e.g. :code:`"Normalized Difference Water Index"`).
- :code:`formula`: Expression/formula of the index (e.g. :code:`"(N - G)/(N + G)"`).
- :code:`reference`: Link to the index reference/paper/doi (e.g. :code:`"https://doi.org/10.1080/01431169608948714"`).
- :code:`type`: Type/application of the index (e.g. :code:`"water"`).
- :code:`date_of_addition`: Date of addition to the list (e.g. :code:`"2021-04-07"`).
- :code:`contributor`: GitHub user link of the vcontributor (e.g. :code:`"https://github.com/davemlz"`).
For the formula attribute, the standard variables for spectral indices expressions must be followed:
.. list-table:: Standard variables for bands and parameters.
:header-rows: 1
* - Description
- Standard
* - Aerosols
- A
* - Blue
- B
* - Green
- G
* - Red
- R
* - Red Edge 1
- RE1
* - Red Edge 2
- RE2
* - Red Edge 3
- RE3
* - Red Edge 4
- RE4
* - NIR
- N
* - SWIR 1
- S1
* - SWIR 2
- S2
* - Thermal 1
- T1
* - Thermal 2
- T2
* - Gain Factor
- g
* - Canopy Background Adjustment
- L
* - Coefficient 1 for the aerosol resistance term
- C1
* - Coefficient 2 for the aerosol resistance term
- C2
* - Exponent used for OCVI.
- cexp
* - Exponent used for GDVI.
- nexp
* - Weighting coefficient used for WDRVI.
- alpha
* - Weighting coefficient used for ARVI.
- gamma
* - Weighting coefficient used for MBWI.
- omega
* - Soil line slope.
- sla
* - Soil line intercept.
- slb
* - Photosynthetically Active Radiation.
- PAR
* - Slope parameter by soil used for NIRvH2.
- k
* - NIR wavelength used for NIRvH2 and NDGI.
- lambdaN
* - Red wavelength used for NIRvH2 and NDGI.
- lambdaR
* - Green wavelength used for NDGI.
- lambdaG
* - k(A,B)
- kAB
We'll take the information to create a new index, test the index and add it to the list!
The not so hard way
-------------------------------
1. Install the required dependencies:
.. code-block::
pydantic
typing
orjson
py_expression_eval
2. Fork the repository and clone it to your local machine.
3. Create a development branch:
.. code-block::
git checkout -b name-of-dev-branch
4. Open the `src/indices.py` file: The list of indices is stored in a DataClass called `SpectralIndices`. At the end of the file, add a new index (example shown below):
.. code-block:: python
SeLI=SpectralIndex(
short_name='SeLI',
long_name='Sentinel-2 LAI Green Index',
formula='(RE4 - RE1) / (RE4 + RE1)',
reference='https://doi.org/10.3390/s19040904',
type='vegetation',
date_of_addition='2021-04-08',
contributor="https://github.com/davemlz"
)
- The `SpectralIndex` class is a validator created using `pydantic`. This validator *validates* the added data.
.. important::
The formula must follow the standard variables for each band or parameter.
5. Test the new index (or indices):
.. code-block:: python
python test/test_indices.py
6. Commit your changes:
.. code-block::
git add .
git commit -m "short-name-of-the-index ADDED"
git push origin name-of-dev-branch
7. Submit a pull request with the tests.<file_sep>/.github/ISSUE_TEMPLATE/new-spectral-index.md
---
name: New Spectral Index
about: Suggest a new Spectral Index
title: 'NEW INDEX: short-name-of-index (long-name-of-index)'
labels: NEW INDEX
assignees: ''
---
Please, complete the following information:
```python
short-name-of-index=SpectralIndex(
short_name='short-name-of-index',
long_name='long-name-of-index',
formula='expression-formula (please see the README for more info)',
reference='link-to-reference-doi-paper',
application_domain='type-of-index (one of [vegetation, burn, water, snow, kernel])',
date_of_addition='yyyy-mm-dd',
contributor="github-user-page"
)
```
Example:
```python
SeLI=SpectralIndex(
short_name='SeLI',
long_name='Sentinel-2 LAI Green Index',
formula='(N2 - RE1) / (N2 + RE1)',
reference='https://doi.org/10.3390/s19040904',
application_domain='vegetation',
date_of_addition='2021-04-08',
contributor="https://github.com/davemlz"
)
```
<file_sep>/src/indices.py
from src.SpectralIndex import SpectralIndex
from typing import Dict
from pydantic import BaseModel
class SpectralIndices(BaseModel):
SpectralIndices: Dict[str, SpectralIndex]
spindex = SpectralIndices(
SpectralIndices=dict(
BNDVI=SpectralIndex(
short_name="BNDVI",
long_name="Blue Normalized Difference Vegetation Index",
formula="(N - B)/(N + B)",
reference="https://doi.org/10.1016/S1672-6308(07)60027-4",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/MATRIX4284",
),
CIG=SpectralIndex(
short_name="CIG",
long_name="Chlorophyll Index Green",
formula="(N / G) - 1.0",
reference="https://doi.org/10.1078/0176-1617-00887",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
CVI=SpectralIndex(
short_name="CVI",
long_name="Chlorophyll Vegetation Index",
formula="(N * R) / (G ** 2.0)",
reference="https://doi.org/10.1007/s11119-010-9204-3",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
EVI=SpectralIndex(
short_name="EVI",
long_name="Enhanced Vegetation Index",
formula="g * (N - R) / (N + C1 * R - C2 * B + L)",
reference="https://doi.org/10.1016/S0034-4257(96)00112-5",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
EVI2=SpectralIndex(
short_name="EVI2",
long_name="Two-Band Enhanced Vegetation Index",
formula="g * (N - R) / (N + 2.4 * R + L)",
reference="https://doi.org/10.1016/j.rse.2008.06.006",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GARI=SpectralIndex(
short_name="GARI",
long_name="Green Atmospherically Resistant Vegetation Index",
formula="(N - (G - (B - R))) / (N - (G + (B - R)))",
reference="https://doi.org/10.1016/S0034-4257(96)00072-7",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GBNDVI=SpectralIndex(
short_name="GBNDVI",
long_name="Green-Blue Normalized Difference Vegetation Index",
formula="(N - (G + B))/(N + (G + B))",
reference="https://doi.org/10.1016/S1672-6308(07)60027-4",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GEMI=SpectralIndex(
short_name="GEMI",
long_name="Global Environment Monitoring Index",
formula="((2.0*((N ** 2.0)-(R ** 2.0)) + 1.5*N + 0.5*R)/(N + R + 0.5))*(1.0 - 0.25*((2.0 * ((N ** 2.0) - (R ** 2)) + 1.5 * N + 0.5 * R)/(N + R + 0.5)))-((R - 0.125)/(1 - R))",
reference="http://dx.doi.org/10.1007/bf00031911",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GLI=SpectralIndex(
short_name="GLI",
long_name="Green Leaf Index",
formula="(2.0 * G - R - B) / (2.0 * G + R + B)",
reference="http://dx.doi.org/10.1080/10106040108542184",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GNDVI=SpectralIndex(
short_name="GNDVI",
long_name="Green Normalized Difference Vegetation Index",
formula="(N - G)/(N + G)",
reference="https://doi.org/10.1016/S0034-4257(96)00072-7",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GRNDVI=SpectralIndex(
short_name="GRNDVI",
long_name="Green-Red Normalized Difference Vegetation Index",
formula="(N - (G + R))/(N + (G + R))",
reference="https://doi.org/10.1016/S1672-6308(07)60027-4",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
GVMI=SpectralIndex(
short_name="GVMI",
long_name="Global Vegetation Moisture Index",
formula="((N + 0.1) - (S2 + 0.02)) / ((N + 0.1) + (S2 + 0.02))",
reference="https://doi.org/10.1016/S0034-4257(02)00037-8",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
MNDVI=SpectralIndex(
short_name="MNDVI",
long_name="Modified Normalized Difference Vegetation Index",
formula="(N - S2)/(N + S2)",
reference="https://doi.org/10.1080/014311697216810",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NDVI=SpectralIndex(
short_name="NDVI",
long_name="Normalized Difference Vegetation Index",
formula="(N - R)/(N + R)",
reference="https://ntrs.nasa.gov/citations/19740022614",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NGRDI=SpectralIndex(
short_name="NGRDI",
long_name="Normalized Green Red Difference Index",
formula="(G - R) / (G + R)",
reference="https://doi.org/10.1016/0034-4257(79)90013-0",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
RVI=SpectralIndex(
short_name="RVI",
long_name="Ratio Vegetation Index",
formula="RE2 / R",
reference="https://doi.org/10.2134/agronj1968.00021962006000060016x",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
SAVI=SpectralIndex(
short_name="SAVI",
long_name="Soil-Adjusted Vegetation Index",
formula="(1.0 + L) * (N - R) / (N + R + L)",
reference="https://doi.org/10.1016/0034-4257(88)90106-X",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
VARI=SpectralIndex(
short_name="VARI",
long_name="Visible Atmospherically Resistant Index",
formula="(G - R) / (G + R - B)",
reference="https://doi.org/10.1016/S0034-4257(01)00289-9",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
BAI=SpectralIndex(
short_name="BAI",
long_name="Burned Area Index",
formula="1.0 / ((0.1 - R) ** 2.0 + (0.06 - N) ** 2.0)",
reference="https://digital.csic.es/bitstream/10261/6426/1/Martin_Isabel_Serie_Geografica.pdf",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
BAIS2=SpectralIndex(
short_name="BAIS2",
long_name="Burned Area Index for Sentinel 2",
formula="(1.0 - ((RE2 * RE3 * N2) / R) ** 0.5) * (((S2 - N2)/(S2 + N2) ** 0.5) + 1.0)",
reference="https://doi.org/10.3390/ecrs-2-05177",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
CSIT=SpectralIndex(
short_name="CSIT",
long_name="Char Soil Index Thermal",
formula="N / (S2 * T / 10000.0)",
reference="https://doi.org/10.1080/01431160600954704",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NBR=SpectralIndex(
short_name="NBR",
long_name="Normalized Burn Ratio",
formula="(N - S2) / (N + S2)",
reference="https://doi.org/10.3133/ofr0211",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NBRT1=SpectralIndex(
short_name="NBRT1",
long_name="Normalized Burn Ratio Thermal 1",
formula="(N - (S2 * T / 10000.0)) / (N + (S2 * T / 10000.0))",
reference="https://doi.org/10.1080/01431160500239008",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NDVIT=SpectralIndex(
short_name="NDVIT",
long_name="Normalized Difference Vegetation Index Thermal",
formula="(N - (R * T / 10000.0))/(N + (R * T / 10000.0))",
reference="https://doi.org/10.1080/01431160600954704",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
SAVIT=SpectralIndex(
short_name="SAVIT",
long_name="Soil-Adjusted Vegetation Index Thermal",
formula="(1.0 + L) * (N - (R * T / 10000.0)) / (N + (R * T / 10000.0) + L)",
reference="https://doi.org/10.1080/01431160600954704",
application_domain="burn",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
MNDWI=SpectralIndex(
short_name="MNDWI",
long_name="Modified Normalized Difference Water Index",
formula="(G - S1) / (G + S1)",
reference="https://doi.org/10.1080/01431160600589179",
application_domain="water",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NDWI=SpectralIndex(
short_name="NDWI",
long_name="Normalized Difference Water Index",
formula="(G - N) / (G + N)",
reference="https://doi.org/10.1080/01431169608948714",
application_domain="water",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NDSI=SpectralIndex(
short_name="NDSI",
long_name="Normalized Difference Snow Index",
formula="(G - S1) / (G + S1)",
reference="https://doi.org/10.1109/IGARSS.1994.399618",
application_domain="snow",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
NDDI=SpectralIndex(
short_name="NDDI",
long_name="Normalized Difference Drought Index",
formula="(((N - R)/(N + R)) - ((G - N)/(G + N)))/(((N - R)/(N + R)) + ((G - N)/(G + N)))",
reference="https://doi.org/10.1029/2006GL029127",
application_domain="vegetation",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
kEVI=SpectralIndex(
short_name="kEVI",
long_name="Kernel Enhanced Vegetation Index",
formula="g * (kNN - kNR) / (kNN + C1 * kNR - C2 * kNB + kNL)",
reference="https://doi.org/10.1126/sciadv.abc7447",
application_domain="kernel",
date_of_addition="2021-05-10",
contributor="https://github.com/davemlz",
),
kNDVI=SpectralIndex(
short_name="kNDVI",
long_name="Kernel Normalized Difference Vegetation Index",
formula="(kNN - kNR)/(kNN + kNR)",
reference="https://doi.org/10.1126/sciadv.abc7447",
application_domain="kernel",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
kRVI=SpectralIndex(
short_name="kRVI",
long_name="Kernel Ratio Vegetation Index",
formula="kNN / kNR",
reference="https://doi.org/10.1126/sciadv.abc7447",
application_domain="kernel",
date_of_addition="2021-04-07",
contributor="https://github.com/davemlz",
),
kVARI=SpectralIndex(
short_name="kVARI",
long_name="Kernel Visible Atmospherically Resistant Index",
formula="(kGG - kGR) / (kGG + kGR - kGB)",
reference="https://doi.org/10.1126/sciadv.abc7447",
application_domain="kernel",
date_of_addition="2021-05-10",
contributor="https://github.com/davemlz",
),
SeLI=SpectralIndex(
short_name="SeLI",
long_name="Sentinel-2 LAI Green Index",
formula="(N2 - RE1) / (N2 + RE1)",
reference="https://doi.org/10.3390/s19040904",
application_domain="vegetation",
date_of_addition="2021-04-08",
contributor="https://github.com/davemlz",
),
OSAVI=SpectralIndex(
short_name="OSAVI",
long_name="Optimized Soil-Adjusted Vegetation Index",
formula="(N - R) / (N + R + 0.16)",
reference="https://doi.org/10.1016/0034-4257(95)00186-7",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
ARVI=SpectralIndex(
short_name="ARVI",
long_name="Atmospherically Resistant Vegetation Index",
formula="(N - (R - gamma * (R - B))) / (N + (R - gamma * (R - B)))",
reference="https://doi.org/10.1109/36.134076",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
SARVI=SpectralIndex(
short_name="SARVI",
long_name="Soil Adjusted and Atmospherically Resistant Vegetation Index",
formula="(1 + L)*(N - (R - (R - B))) / (N + (R - (R - B)) + L)",
reference="https://doi.org/10.1109/36.134076",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
NLI=SpectralIndex(
short_name="NLI",
long_name="Non-Linear Vegetation Index",
formula="((N ** 2) - R)/((N ** 2) + R)",
reference="https://doi.org/10.1080/02757259409532252",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
MNLI=SpectralIndex(
short_name="MNLI",
long_name="Modified Non-Linear Vegetation Index",
formula="(1 + L)*((N ** 2) - R)/((N ** 2) + R + L)",
reference="https://doi.org/10.1109/TGRS.2003.812910",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
NMDI=SpectralIndex(
short_name="NMDI",
long_name="Normalized Multi-band Drought Index",
formula="(N - (S1 - S2))/(N + (S1 - S2))",
reference="https://doi.org/10.1029/2007GL031021",
application_domain="vegetation",
date_of_addition="2021-05-11",
contributor="https://github.com/davemlz",
),
MSAVI=SpectralIndex(
short_name="MSAVI",
long_name="Modified Soil-Adjusted Vegetation Index",
formula="0.5 * (2.0 * N + 1 - (((2 * N + 1) ** 2) - 8 * (N - R)) ** 0.5)",
reference="https://doi.org/10.1016/0034-4257(94)90134-1",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
MCARI=SpectralIndex(
short_name="MCARI",
long_name="Modified Chlorophyll Absorption in Reflectance Index",
formula="((RE1 - R) - 0.2 * (RE1 - G)) * (RE1 / R)",
reference="http://dx.doi.org/10.1016/S0034-4257(00)00113-9",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
OCVI=SpectralIndex(
short_name="OCVI",
long_name="Optimized Chlorophyll Vegetation Index",
formula="(N / G) * (R / G) ** cexp",
reference="http://dx.doi.org/10.1007/s11119-008-9075-z",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
NDREI=SpectralIndex(
short_name="NDREI",
long_name="Normalized Difference Red Edge Index",
formula="(N - RE1) / (N + RE1)",
reference="https://doi.org/10.1016/1011-1344(93)06963-4",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
CIRE=SpectralIndex(
short_name="CIRE",
long_name="Chlorophyll Index Red Edge",
formula="(N / RE1) - 1",
reference="https://doi.org/10.1078/0176-1617-00887",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
MTCI=SpectralIndex(
short_name="MTCI",
long_name="MERIS Terrestrial Chlorophyll Index",
formula="(RE2 - RE1) / (RE1 - R)",
reference="https://doi.org/10.1080/0143116042000274015",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
TCARI=SpectralIndex(
short_name="TCARI",
long_name="Transformed Chlorophyll Absorption in Reflectance Index",
formula="3 * ((RE1 - R) - 0.2 * (RE1 - G) * (RE1 / R))",
reference="https://doi.org/10.1016/S0034-4257(02)00018-4",
application_domain="vegetation",
date_of_addition="2021-05-13",
contributor="https://github.com/davemlz",
),
GDVI=SpectralIndex(
short_name="GDVI",
long_name="Generalized Difference Vegetation Index",
formula="((N ** nexp) - (R ** nexp)) / ((N ** nexp) + (R ** nexp))",
reference="https://doi.org/10.3390/rs6021211",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
WDRVI=SpectralIndex(
short_name="WDRVI",
long_name="Wide Dynamic Range Vegetation Index",
formula="(alpha * N - R) / (alpha * N + R)",
reference="https://doi.org/10.1078/0176-1617-01176",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MCARI1=SpectralIndex(
short_name="MCARI1",
long_name="Modified Chlorophyll Absorption in Reflectance Index 1",
formula="1.2 * (2.5 * (N - R) - 1.3 * (N - G))",
reference="https://doi.org/10.1016/j.rse.2003.12.013",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MTVI1=SpectralIndex(
short_name="MTVI1",
long_name="Modified Triangular Vegetation Index 1",
formula="1.2 * (1.2 * (N - G) - 2.5 * (R - G))",
reference="https://doi.org/10.1016/j.rse.2003.12.013",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MCARI2=SpectralIndex(
short_name="MCARI2",
long_name="Modified Chlorophyll Absorption in Reflectance Index 2",
formula="(1.5 * (2.5 * (N - R) - 1.3 * (N - G))) / ((((2.0 * N + 1) ** 2) - (6.0 * N - 5 * (R ** 0.5)) - 0.5) ** 0.5)",
reference="https://doi.org/10.1016/j.rse.2003.12.013",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MTVI2=SpectralIndex(
short_name="MTVI2",
long_name="Modified Triangular Vegetation Index 2",
formula="(1.5 * (1.2 * (N - G) - 2.5 * (R - G))) / ((((2.0 * N + 1) ** 2) - (6.0 * N - 5 * (R ** 0.5)) - 0.5) ** 0.5)",
reference="https://doi.org/10.1016/j.rse.2003.12.013",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
TriVI=SpectralIndex(
short_name="TriVI",
long_name="Triangular Vegetation Index",
formula="0.5 * (120 * (N - G) - 200 * (R - G))",
reference="http://dx.doi.org/10.1016/S0034-4257(00)00197-8",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MSR=SpectralIndex(
short_name="MSR",
long_name="Modified Simple Ratio",
formula="(N / R - 1) / ((N / R + 1) ** 0.5)",
reference="https://doi.org/10.1080/07038992.1996.10855178",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
RDVI=SpectralIndex(
short_name="RDVI",
long_name="Renormalized Difference Vegetation Index",
formula="(N - R) / ((N + R) ** 0.5)",
reference="https://doi.org/10.1016/0034-4257(94)00114-3",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
NDBI=SpectralIndex(
short_name="NDBI",
long_name="Normalized Difference Built-Up Index",
formula="(S1 - N) / (S1 + N)",
reference="http://dx.doi.org/10.1080/01431160304987",
application_domain="urban",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
MGRVI=SpectralIndex(
short_name="MGRVI",
long_name="Modified Green Red Vegetation Index",
formula="(G ** 2.0 - R ** 2.0) / (G ** 2.0 + R ** 2.0)",
reference="https://doi.org/10.1016/j.jag.2015.02.012",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
ExG=SpectralIndex(
short_name="ExG",
long_name="Excess Green Index",
formula="2 * G - R - B",
reference="https://doi.org/10.13031/2013.27838",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
DVI=SpectralIndex(
short_name="DVI",
long_name="Difference Vegetation Index",
formula="N - R",
reference="https://doi.org/10.1016/0034-4257(94)00114-3",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
WDVI=SpectralIndex(
short_name="WDVI",
long_name="Weighted Difference Vegetation Index",
formula="N - sla * R",
reference="https://doi.org/10.1016/0034-4257(89)90076-X",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
TSAVI=SpectralIndex(
short_name="TSAVI",
long_name="Transformed Soil-Adjusted Vegetation Index",
formula="sla * (N - sla * R - slb) / (sla * N + R - sla * slb)",
reference="https://doi.org/10.1109/IGARSS.1989.576128",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
ATSAVI=SpectralIndex(
short_name="ATSAVI",
long_name="Adjusted Transformed Soil-Adjusted Vegetation Index",
formula="sla * (N - sla * R - slb) / (sla * N + R - sla * slb + 0.08 * (1 + sla ** 2.0))",
reference="https://doi.org/10.1016/0034-4257(91)90009-U",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
SAVI2=SpectralIndex(
short_name="SAVI2",
long_name="Soil-Adjusted Vegetation Index 2",
formula="N / (R + (slb / sla))",
reference="https://doi.org/10.1080/01431169008955053",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
TCI=SpectralIndex(
short_name="TCI",
long_name="Triangular Chlorophyll Index",
formula="1.2 * (RE1 - G) - 1.5 * (R - G) * (RE1 / R) ** 0.5",
reference="http://dx.doi.org/10.1109/TGRS.2007.904836",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
TGI=SpectralIndex(
short_name="TGI",
long_name="Triangular Greenness Index",
formula="- 0.5 * (190 * (R - G) - 120 * (R - B))",
reference="http://dx.doi.org/10.1016/j.jag.2012.07.020",
application_domain="vegetation",
date_of_addition="2021-05-14",
contributor="https://github.com/davemlz",
),
IRECI=SpectralIndex(
short_name="IRECI",
long_name="Inverted Red-Edge Chlorophyll Index",
formula="(RE3 - R) / (RE1 / RE2)",
reference="https://doi.org/10.1016/j.isprsjprs.2013.04.007",
application_domain="vegetation",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
S2REP=SpectralIndex(
short_name="S2REP",
long_name="Sentinel-2 Red-Edge Position",
formula="705.0 + 35.0 * ((((RE3 + R) / 2.0) - RE1) / (RE2 - RE1))",
reference="https://doi.org/10.1016/j.isprsjprs.2013.04.007",
application_domain="vegetation",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
EBBI=SpectralIndex(
short_name="EBBI",
long_name="Enhanced Built-Up and Bareness Index",
formula="(S1 - N) / (10.0 * ((S1 + T) ** 0.5))",
reference="https://doi.org/10.3390/rs4102957",
application_domain="urban",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
NDBaI=SpectralIndex(
short_name="NDBaI",
long_name="Normalized Difference Bareness Index",
formula="(S1 - T) / (S1 + T)",
reference="https://doi.org/10.1109/IGARSS.2005.1526319",
application_domain="soil",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
SIPI=SpectralIndex(
short_name="SIPI",
long_name="Structure Insensitive Pigment Index",
formula="(N - A) / (N - R)",
reference="https://eurekamag.com/research/009/395/009395053.php",
application_domain="vegetation",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
NHFD=SpectralIndex(
short_name="NHFD",
long_name="Non-Homogeneous Feature Difference",
formula="(RE1 - A) / (RE1 + A)",
reference="https://www.semanticscholar.org/paper/Using-WorldView-2-Vis-NIR-MSI-Imagery-to-Support-Wolf/5e5063ccc4ee76b56b721c866e871d47a77f9fb4",
application_domain="urban",
date_of_addition="2021-09-17",
contributor="https://github.com/davemlz",
),
NDYI=SpectralIndex(
short_name="NDYI",
long_name="Normalized Difference Yellowness Index",
formula="(G - B) / (G + B)",
reference="https://doi.org/10.1016/j.rse.2016.06.016",
application_domain="vegetation",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
NRFIr=SpectralIndex(
short_name="NRFIr",
long_name="Normalized Rapeseed Flowering Index Red",
formula="(R - S2) / (R + S2)",
reference="https://doi.org/10.3390/rs13010105",
application_domain="vegetation",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
NRFIg=SpectralIndex(
short_name="NRFIg",
long_name="Normalized Rapeseed Flowering Index Green",
formula="(G - S2) / (G + S2)",
reference="https://doi.org/10.3390/rs13010105",
application_domain="vegetation",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
TRRVI=SpectralIndex(
short_name="TRRVI",
long_name="Transformed Red Range Vegetation Index",
formula="((RE2 - R) / (RE2 + R)) / (((N - R) / (N + R)) + 1.0)",
reference="https://doi.org/10.3390/rs12152359",
application_domain="vegetation",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
TTVI=SpectralIndex(
short_name="TTVI",
long_name="Transformed Triangular Vegetation Index",
formula="0.5 * ((865.0 - 740.0) * (RE3 - RE2) - (N2 - RE2) * (783.0 - 740))",
reference="https://doi.org/10.3390/rs12010016",
application_domain="vegetation",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
NDSaII=SpectralIndex(
short_name="NDSaII",
long_name="Normalized Difference Snow and Ice Index",
formula="(R - S1) / (R + S1)",
reference="https://doi.org/10.1080/01431160119766",
application_domain="snow",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
SWI=SpectralIndex(
short_name="SWI",
long_name="Snow Water Index",
formula="(G * (N - S1)) / ((G + N) * (N + S1))",
reference="https://doi.org/10.3390/rs11232774",
application_domain="snow",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
S3=SpectralIndex(
short_name="S3",
long_name="S3 Snow Index",
formula="(N * (R - S1)) / ((N + R) * (N + S1))",
reference="https://doi.org/10.3178/jjshwr.12.28",
application_domain="snow",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
WI1=SpectralIndex(
short_name="WI1",
long_name="Water Index 1",
formula="(G - S2) / (G + S2)",
reference="https://doi.org/10.3390/rs11182186",
application_domain="water",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
WI2=SpectralIndex(
short_name="WI2",
long_name="Water Index 2",
formula="(B - S2) / (B + S2)",
reference="https://doi.org/10.3390/rs11182186",
application_domain="water",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
AWEInsh=SpectralIndex(
short_name="AWEInsh",
long_name="Automated Water Extraction Index",
formula="4.0 * (G - S1) - 0.25 * N + 2.75 * S2",
reference="https://doi.org/10.1016/j.rse.2013.08.029",
application_domain="water",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
AWEIsh=SpectralIndex(
short_name="AWEIsh",
long_name="Automated Water Extraction Index with Shadows Elimination",
formula="B + 2.5 * G - 1.5 * (N + S1) - 0.25 * S2",
reference="https://doi.org/10.1016/j.rse.2013.08.029",
application_domain="water",
date_of_addition="2021-09-18",
contributor="https://github.com/davemlz",
),
NBR2=SpectralIndex(
short_name="NBR2",
long_name="Normalized Burn Ratio 2",
formula="(S1 - S2) / (S1 + S2)",
reference="https://www.usgs.gov/core-science-systems/nli/landsat/landsat-normalized-burn-ratio-2",
application_domain="burn",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
BWDRVI=SpectralIndex(
short_name="BWDRVI",
long_name="Blue Wide Dynamic Range Vegetation Index",
formula="(alpha * N - B) / (alpha * N + B)",
reference="https://doi.org/10.2135/cropsci2007.01.0031",
application_domain="vegetation",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
ARI=SpectralIndex(
short_name="ARI",
long_name="Anthocyanin Reflectance Index",
formula="(1 / G) - (1 / RE1)",
reference="https://doi.org/10.1562/0031-8655(2001)074%3C0038:OPANEO%3E2.0.CO;2",
application_domain="vegetation",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
VIG=SpectralIndex(
short_name="VIG",
long_name="Vegetation Index Green",
formula="(G - R) / (G + R)",
reference="https://doi.org/10.1016/S0034-4257(01)00289-9",
application_domain="vegetation",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
VI700=SpectralIndex(
short_name="VI700",
long_name="Vegetation Index (700 nm)",
formula="(RE1 - R) / (RE1 + R)",
reference="https://doi.org/10.1016/S0034-4257(01)00289-9",
application_domain="vegetation",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
VARI700=SpectralIndex(
short_name="VARI700",
long_name="Visible Atmospherically Resistant Index (700 nm)",
formula="(RE1 - 1.7 * R + 0.7 * B) / (RE1 + 1.3 * R - 1.3 * B)",
reference="https://doi.org/10.1016/S0034-4257(01)00289-9",
application_domain="vegetation",
date_of_addition="2021-09-20",
contributor="https://github.com/davemlz",
),
TCARIOSAVI=SpectralIndex(
short_name="TCARIOSAVI",
long_name="TCARI/OSAVI Ratio",
formula="(3 * ((RE1 - R) - 0.2 * (RE1 - G) * (RE1 / R))) / (1.16 * (N - R) / (N + R + 0.16))",
reference="https://doi.org/10.1016/S0034-4257(02)00018-4",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
MCARIOSAVI=SpectralIndex(
short_name="MCARIOSAVI",
long_name="MCARI/OSAVI Ratio",
formula="(((RE1 - R) - 0.2 * (RE1 - G)) * (RE1 / R)) / (1.16 * (N - R) / (N + R + 0.16))",
reference="https://doi.org/10.1016/S0034-4257(00)00113-9",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
TCARIOSAVI705=SpectralIndex(
short_name="TCARIOSAVI705",
long_name="TCARI/OSAVI Ratio (705 and 750 nm)",
formula="(3 * ((RE2 - RE1) - 0.2 * (RE2 - G) * (RE2 / RE1))) / (1.16 * (RE2 - RE1) / (RE2 + RE1 + 0.16))",
reference="https://doi.org/10.1016/j.agrformet.2008.03.005",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
MCARIOSAVI705=SpectralIndex(
short_name="MCARIOSAVI705",
long_name="MCARI/OSAVI Ratio (705 and 750 nm)",
formula="(((RE2 - RE1) - 0.2 * (RE2 - G)) * (RE2 / RE1)) / (1.16 * (RE2 - RE1) / (RE2 + RE1 + 0.16))",
reference="https://doi.org/10.1016/j.agrformet.2008.03.005",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
MCARI705=SpectralIndex(
short_name="MCARI705",
long_name="Modified Chlorophyll Absorption in Reflectance Index (705 and 750 nm)",
formula="((RE2 - RE1) - 0.2 * (RE2 - G)) * (RE2 / RE1)",
reference="https://doi.org/10.1016/j.agrformet.2008.03.005",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
MSR705=SpectralIndex(
short_name="MSR705",
long_name="Modified Simple Ratio (705 and 750 nm)",
formula="(RE2 / RE1 - 1) / ((RE2 / RE1 + 1) ** 0.5)",
reference="https://doi.org/10.1016/j.agrformet.2008.03.005",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
NDVI705=SpectralIndex(
short_name="NDVI705",
long_name="Normalized Difference Vegetation Index (705 and 750 nm)",
formula="(RE2 - RE1) / (RE2 + RE1)",
reference="https://doi.org/10.1016/S0176-1617(11)81633-0",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
SR705=SpectralIndex(
short_name="SR705",
long_name="Simple Ratio (705 and 750 nm)",
formula="RE2 / RE1",
reference="https://doi.org/10.1016/S0176-1617(11)81633-0",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
SR555=SpectralIndex(
short_name="SR555",
long_name="Simple Ratio (555 and 750 nm)",
formula="RE2 / G",
reference="https://doi.org/10.1016/S0176-1617(11)81633-0",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
REDSI=SpectralIndex(
short_name="REDSI",
long_name="Red-Edge Disease Stress Index",
formula="((705.0 - 665.0) * (RE3 - R) - (783.0 - 665.0) * (RE1 - R)) / (2.0 * R)",
reference="https://doi.org/10.3390/s18030868",
application_domain="vegetation",
date_of_addition="2021-11-06",
contributor="https://github.com/davemlz",
),
NIRv=SpectralIndex(
short_name="NIRv",
long_name="Near-Infrared Reflectance of Vegetation",
formula="((N - R) / (N + R)) * N",
reference="https://doi.org/10.1126/sciadv.1602244",
application_domain="vegetation",
date_of_addition="2021-11-16",
contributor="https://github.com/davemlz",
),
AFRI2100=SpectralIndex(
short_name="AFRI2100",
long_name="Aerosol Free Vegetation Index (2100 nm)",
formula="(N - 0.5 * S2) / (N + 0.5 * S2)",
reference="https://doi.org/10.1016/S0034-4257(01)00190-0",
application_domain="vegetation",
date_of_addition="2021-11-17",
contributor="https://github.com/davemlz",
),
AFRI1600=SpectralIndex(
short_name="AFRI1600",
long_name="Aerosol Free Vegetation Index (1600 nm)",
formula="(N - 0.66 * S1) / (N + 0.66 * S1)",
reference="https://doi.org/10.1016/S0034-4257(01)00190-0",
application_domain="vegetation",
date_of_addition="2021-11-17",
contributor="https://github.com/davemlz",
),
NIRvP=SpectralIndex(
short_name="NIRvP",
long_name="Near-Infrared Reflectance of Vegetation and Incoming PAR",
formula="((N - R) / (N + R)) * N * PAR",
reference="https://doi.org/10.1016/j.rse.2021.112763",
application_domain="vegetation",
date_of_addition="2021-11-18",
contributor="https://github.com/davemlz",
),
NDMI=SpectralIndex(
short_name="NDMI",
long_name="Normalized Difference Moisture Index",
formula="(N - S1)/(N + S1)",
reference="https://doi.org/10.1016/S0034-4257(01)00318-2",
application_domain="vegetation",
date_of_addition="2021-12-01",
contributor="https://github.com/bpurinton",
),
QpRVI=SpectralIndex(
short_name="QpRVI",
long_name="Quad-Polarized Radar Vegetation Index",
formula="(8.0 * HV)/(HH + VV + 2.0 * HV)",
reference="https://doi.org/10.1109/IGARSS.2001.976856",
application_domain="radar",
date_of_addition="2021-12-24",
contributor="https://github.com/davemlz",
),
RFDI=SpectralIndex(
short_name="RFDI",
long_name="Radar Forest Degradation Index",
formula="(HH - HV)/(HH + HV)",
reference="https://doi.org/10.5194/bg-9-179-2012",
application_domain="radar",
date_of_addition="2021-12-25",
contributor="https://github.com/davemlz",
),
DpRVIHH=SpectralIndex(
short_name="DpRVIHH",
long_name="Dual-Polarized Radar Vegetation Index HH",
formula="(4.0 * HV)/(HH + HV)",
reference="https://www.tandfonline.com/doi/abs/10.5589/m12-043",
application_domain="radar",
date_of_addition="2021-12-25",
contributor="https://github.com/davemlz",
),
DpRVIVV=SpectralIndex(
short_name="DpRVIVV",
long_name="Dual-Polarized Radar Vegetation Index VV",
formula="(4.0 * VH)/(VV + VH)",
reference="https://doi.org/10.3390/app9040655",
application_domain="radar",
date_of_addition="2021-12-25",
contributor="https://github.com/davemlz",
),
NWI=SpectralIndex(
short_name="NWI",
long_name="New Water Index",
formula="(B - (N + S1 + S2))/(B + (N + S1 + S2))",
reference="https://doi.org/10.11873/j.issn.1004-0323.2009.2.167",
application_domain="water",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
WRI=SpectralIndex(
short_name="WRI",
long_name="Water Ratio Index",
formula="(G + R)/(N + S1)",
reference="https://doi.org/10.1109/GEOINFORMATICS.2010.5567762",
application_domain="water",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
NDVIMNDWI=SpectralIndex(
short_name="NDVIMNDWI",
long_name="NDVI-MNDWI Model",
formula="((N - R)/(N + R)) - ((G - S1)/(G + S1))",
reference="https://doi.org/10.1007/978-3-662-45737-5_51",
application_domain="water",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
MBWI=SpectralIndex(
short_name="MBWI",
long_name="Multi-Band Water Index",
formula="(omega * G) - R - N - S1 - S2",
reference="https://doi.org/10.1016/j.jag.2018.01.018",
application_domain="water",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
GCC=SpectralIndex(
short_name="GCC",
long_name="Green Chromatic Coordinate",
formula="G / (R + G + B)",
reference="https://doi.org/10.1016/0034-4257(87)90088-5",
application_domain="vegetation",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
RCC=SpectralIndex(
short_name="RCC",
long_name="Red Chromatic Coordinate",
formula="R / (R + G + B)",
reference="https://doi.org/10.1016/0034-4257(87)90088-5",
application_domain="vegetation",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
BCC=SpectralIndex(
short_name="BCC",
long_name="Blue Chromatic Coordinate",
formula="B / (R + G + B)",
reference="https://doi.org/10.1016/0034-4257(87)90088-5",
application_domain="vegetation",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
NIRvH2=SpectralIndex(
short_name="NIRvH2",
long_name="Hyperspectral Near-Infrared Reflectance of Vegetation",
formula="N - R - k * (lambdaN - lambdaR)",
reference="https://doi.org/10.1016/j.rse.2021.112723",
application_domain="vegetation",
date_of_addition="2022-01-17",
contributor="https://github.com/davemlz",
),
NDPI=SpectralIndex(
short_name="NDPI",
long_name="Normalized Difference Phenology Index",
formula="(N - (alpha * R + (1.0 - alpha) * S1))/(N + (alpha * R + (1.0 - alpha) * S1))",
reference="https://doi.org/10.1016/j.rse.2017.04.031",
application_domain="vegetation",
date_of_addition="2022-01-20",
contributor="https://github.com/davemlz",
),
NDII=SpectralIndex(
short_name="NDII",
long_name="Normalized Difference Infrared Index",
formula="(N - S1)/(N + S1)",
reference="https://www.asprs.org/wp-content/uploads/pers/1983journal/jan/1983_jan_77-83.pdf",
application_domain="vegetation",
date_of_addition="2022-01-20",
contributor="https://github.com/davemlz",
),
DVIplus=SpectralIndex(
short_name="DVIplus",
long_name="Difference Vegetation Index Plus",
formula="((lambdaN - lambdaR)/(lambdaN - lambdaG)) * G + (1.0 - ((lambdaN - lambdaR)/(lambdaN - lambdaG))) * N - R",
reference="https://doi.org/10.1016/j.rse.2019.03.028",
application_domain="vegetation",
date_of_addition="2022-01-20",
contributor="https://github.com/davemlz",
),
NDGI=SpectralIndex(
short_name="NDGI",
long_name="Normalized Difference Greenness Index",
formula="(((lambdaN - lambdaR)/(lambdaN - lambdaG)) * G + (1.0 - ((lambdaN - lambdaR)/(lambdaN - lambdaG))) * N - R)/(((lambdaN - lambdaR)/(lambdaN - lambdaG)) * G + (1.0 - ((lambdaN - lambdaR)/(lambdaN - lambdaG))) * N + R)",
reference="https://doi.org/10.1016/j.rse.2019.03.028",
application_domain="vegetation",
date_of_addition="2022-01-20",
contributor="https://github.com/davemlz",
),
FCVI=SpectralIndex(
short_name="FCVI",
long_name="Fluorescence Correction Vegetation Index",
formula="N - ((R + G + B)/3.0)",
reference="https://doi.org/10.1016/j.rse.2020.111676",
application_domain="vegetation",
date_of_addition="2022-01-20",
contributor="https://github.com/davemlz",
),
UI=SpectralIndex(
short_name="UI",
long_name="Urban Index",
formula="(S2 - N)/(S2 + N)",
reference="https://www.isprs.org/proceedings/XXXI/congress/part7/321_XXXI-part7.pdf",
application_domain="urban",
date_of_addition="2022-02-07",
contributor="https://github.com/davemlz",
),
VrNIRBI=SpectralIndex(
short_name="VrNIRBI",
long_name="Visible Red-Based Built-Up Index",
formula="(R - N)/(R + N)",
reference="https://doi.org/10.1016/j.ecolind.2015.03.037",
application_domain="urban",
date_of_addition="2022-02-09",
contributor="https://github.com/davemlz",
),
VgNIRBI=SpectralIndex(
short_name="VgNIRBI",
long_name="Visible Green-Based Built-Up Index",
formula="(G - N)/(G + N)",
reference="https://doi.org/10.1016/j.ecolind.2015.03.037",
application_domain="urban",
date_of_addition="2022-02-09",
contributor="https://github.com/davemlz",
),
IBI=SpectralIndex(
short_name="IBI",
long_name="Index-Based Built-Up Index",
formula="(((S1-N)/(S1+N))-(((N-R)*(1.0+L)/(N+R+L))+((G-S1)/(G+S1)))/2.0)/(((S1-N)/(S1+N))+(((N-R)*(1.0+L)/(N+R+L))+((G-S1)/(G+S1)))/2.0)",
reference="https://doi.org/10.1080/01431160802039957",
application_domain="urban",
date_of_addition="2022-02-09",
contributor="https://github.com/davemlz",
),
BLFEI=SpectralIndex(
short_name="BLFEI",
long_name="Built-Up Land Features Extraction Index",
formula="(((G+R+S2)/3.0)-S1)/(((G+R+S2)/3.0)+S1)",
reference="https://doi.org/10.1080/10106049.2018.1497094",
application_domain="urban",
date_of_addition="2022-02-09",
contributor="https://github.com/davemlz",
),
S2WI=SpectralIndex(
short_name="S2WI",
long_name="Sentinel-2 Water Index",
formula="(RE1 - S2)/(RE1 + S2)",
reference="https://doi.org/10.3390/w13121647",
application_domain="water",
date_of_addition="2022-03-06",
contributor="https://github.com/MATRIX4284",
),
NDWIns=SpectralIndex(
short_name="NDWIns",
long_name="Normalized Difference Water Index with no Snow Cover and Glaciers",
formula="(G - alpha * N)/(G + N)",
reference="https://doi.org/10.3390/w12051339",
application_domain="water",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NDSInw=SpectralIndex(
short_name="NDSInw",
long_name="Normalized Difference Snow Index with no Water",
formula="(N - S1 - beta)/(N + S1)",
reference="https://doi.org/10.3390/w12051339",
application_domain="snow",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
ExGR=SpectralIndex(
short_name="ExGR",
long_name="ExG - ExR Vegetation Index",
formula="(2.0 * G - R - B) - (1.3 * R - G)",
reference="https://doi.org/10.1016/j.compag.2008.03.009",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
ExR=SpectralIndex(
short_name="ExR",
long_name="Excess Red Index",
formula="1.3 * R - G",
reference="https://doi.org/10.1117/12.336896",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
MRBVI=SpectralIndex(
short_name="MRBVI",
long_name="Modified Red Blue Vegetation Index",
formula="(R ** 2.0 - B ** 2.0)/(R ** 2.0 + B ** 2.0)",
reference="https://doi.org/10.3390/s20185055",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
AVI=SpectralIndex(
short_name="AVI",
long_name="Advanced Vegetation Index",
formula="(N * (1.0 - R) * (N - R)) ** (1/3)",
reference="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
BI=SpectralIndex(
short_name="BI",
long_name="Bare Soil Index",
formula="((S1 + R) - (N + B))/((S1 + R) + (N + B))",
reference="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf",
application_domain="soil",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
SI=SpectralIndex(
short_name="SI",
long_name="Shadow Index",
formula="((1.0 - B) * (1.0 - G) * (1.0 - R)) ** (1/3)",
reference="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.465.8749&rep=rep1&type=pdf",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
MSI=SpectralIndex(
short_name="MSI",
long_name="Moisture Stress Index",
formula="S1/N",
reference="https://doi.org/10.1016/0034-4257(89)90046-1",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NDGlaI=SpectralIndex(
short_name="NDGlaI",
long_name="Normalized Difference Glacier Index",
formula="(G - R)/(G + R)",
reference="https://doi.org/10.1080/01431160802385459",
application_domain="snow",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NDSII=SpectralIndex(
short_name="NDSII",
long_name="Normalized Difference Snow Ice Index",
formula="(G - N)/(G + N)",
reference="https://doi.org/10.1080/01431160802385459",
application_domain="snow",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
IKAW=SpectralIndex(
short_name="IKAW",
long_name="Kawashima Index",
formula="(R - B)/(R + B)",
reference="https://doi.org/10.1006/anbo.1997.0544",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
RGRI=SpectralIndex(
short_name="RGRI",
long_name="Red-Green Ratio Index",
formula="R/G",
reference="https://doi.org/10.1016/j.jag.2014.03.018",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
RGBVI=SpectralIndex(
short_name="RGBVI",
long_name="Red Green Blue Vegetation Index",
formula="(G ** 2.0 - B * R)/(G ** 2.0 + B * R)",
reference="https://doi.org/10.1016/j.jag.2015.02.012",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
ARI2=SpectralIndex(
short_name="ARI2",
long_name="Anthocyanin Reflectance Index 2",
formula="N * ((1 / G) - (1 / RE1))",
reference="https://doi.org/10.1562/0031-8655(2001)074%3C0038:OPANEO%3E2.0.CO;2",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NormNIR=SpectralIndex(
short_name="NormNIR",
long_name="Normalized NIR",
formula="N/(N + G + R)",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NormR=SpectralIndex(
short_name="NormR",
long_name="Normalized Red",
formula="R/(N + G + R)",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NormG=SpectralIndex(
short_name="NormG",
long_name="Normalized Green",
formula="G/(N + G + R)",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
GRVI=SpectralIndex(
short_name="GRVI",
long_name="Green Ratio Vegetation Index",
formula="N/G",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
GSAVI=SpectralIndex(
short_name="GSAVI",
long_name="Green Soil Adjusted Vegetation Index",
formula="(1.0 + L) * (N - G) / (N + G + L)",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
GOSAVI=SpectralIndex(
short_name="GOSAVI",
long_name="Green Optimized Soil Adjusted Vegetation Index",
formula="(N - G) / (N + G + 0.16)",
reference="https://doi.org/10.2134/agronj2004.0314",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
SR=SpectralIndex(
short_name="SR",
long_name="Simple Ratio",
formula="N/R",
reference="https://doi.org/10.2307/1936256",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
TVI=SpectralIndex(
short_name="TVI",
long_name="Transformed Vegetation Index",
formula="(((N - R)/(N + R)) + 0.5) ** 0.5",
reference="https://ntrs.nasa.gov/citations/19740022614",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
GM1=SpectralIndex(
short_name="GM1",
long_name="Gitelson and Merzlyak Index 1",
formula="RE2/G",
reference="https://doi.org/10.1016/S0176-1617(96)80284-7",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
GM2=SpectralIndex(
short_name="GM2",
long_name="Gitelson and Merzlyak Index 2",
formula="RE2/RE1",
reference="https://doi.org/10.1016/S0176-1617(96)80284-7",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
IAVI=SpectralIndex(
short_name="IAVI",
long_name="New Atmospherically Resistant Vegetation Index",
formula="(N - (R - gamma * (B - R)))/(N + (R - gamma * (B - R)))",
reference="https://www.jipb.net/EN/abstract/abstract23925.shtml",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
IPVI=SpectralIndex(
short_name="IPVI",
long_name="Infrared Percentage Vegetation Index",
formula="N/(N + R)",
reference="https://doi.org/10.1016/0034-4257(90)90085-Z",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
kIPVI=SpectralIndex(
short_name="kIPVI",
long_name="Kernel Infrared Percentage Vegetation Index",
formula="kNN/(kNN + kNR)",
reference="https://doi.org/10.1126/sciadv.abc7447",
application_domain="kernel",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
ND705=SpectralIndex(
short_name="ND705",
long_name="Normalized Difference (705 and 750 nm)",
formula="(RE2 - RE1)/(RE2 + RE1)",
reference="https://doi.org/10.1016/S0034-4257(02)00010-X",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
mSR705=SpectralIndex(
short_name="mSR705",
long_name="Modified Simple Ratio (705 and 445 nm)",
formula="(RE2 - A)/(RE2 + A)",
reference="https://doi.org/10.1016/S0034-4257(02)00010-X",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
mND705=SpectralIndex(
short_name="mND705",
long_name="Modified Normalized Difference (705, 750 and 445 nm)",
formula="(RE2 - RE1)/(RE2 + RE1 - A)",
reference="https://doi.org/10.1016/S0034-4257(02)00010-X",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
PSRI=SpectralIndex(
short_name="PSRI",
long_name="Plant Senescing Reflectance Index",
formula="(R - B)/RE2",
reference="https://doi.org/10.1034/j.1399-3054.1999.106119.x",
application_domain="vegetation",
date_of_addition="2022-04-08",
contributor="https://github.com/davemlz",
),
NBSIMS=SpectralIndex(
short_name="NBSIMS",
long_name="Non-Binary Snow Index for Multi-Component Surfaces",
formula="0.36 * (G + R + N) - (((B + S2)/G) + S1)",
reference="https://doi.org/10.3390/rs13142777",
application_domain="snow",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
MuWIR=SpectralIndex(
short_name="MuWIR",
long_name="Revised Multi-Spectral Water Index",
formula="-4.0 * ((B - G)/(B + G)) + 2.0 * ((G - N)/(G + N)) + 2.0 * ((G - S2)/(G + S2)) - ((G - S1)/(G + S1))",
reference="https://doi.org/10.3390/rs10101643",
application_domain="water",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
RENDVI=SpectralIndex(
short_name="RENDVI",
long_name="Red Edge Normalized Difference Vegetation Index",
formula="(RE2 - RE1)/(RE2 + RE1)",
reference="https://doi.org/10.1016/S0176-1617(11)81633-0",
application_domain="vegetation",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
RI=SpectralIndex(
short_name="RI",
long_name="Redness Index",
formula="(R - G)/(R + G)",
reference="https://www.documentation.ird.fr/hor/fdi:34390",
application_domain="vegetation",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
SR2=SpectralIndex(
short_name="SR2",
long_name="Simple Ratio (800 and 550 nm)",
formula="N/G",
reference="https://doi.org/10.1080/01431169308904370",
application_domain="vegetation",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
SR3=SpectralIndex(
short_name="SR3",
long_name="Simple Ratio (860, 550 and 708 nm)",
formula="N2/(G * RE1)",
reference="https://doi.org/10.1016/S0034-4257(98)00046-7",
application_domain="vegetation",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
TDVI=SpectralIndex(
short_name="TDVI",
long_name="Transformed Difference Vegetation Index",
formula="1.5 * ((N - R)/((N ** 2.0 + R + 0.5) ** 0.5))",
reference="https://doi.org/10.1109/IGARSS.2002.1026867",
application_domain="vegetation",
date_of_addition="2022-04-09",
contributor="https://github.com/davemlz",
),
NBUI=SpectralIndex(
short_name="NBUI",
long_name="New Built-Up Index",
formula="((S1 - N)/(10.0 * (T + S1) ** 0.5)) - (((N - R) * (1.0 + L))/(N - R + L)) - (G - S1)/(G + S1)",
reference="https://hdl.handle.net/1959.11/29500",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
PISI=SpectralIndex(
short_name="PISI",
long_name="Perpendicular Impervious Surface Index",
formula="0.8192 * B - 0.5735 * N + 0.0750",
reference="https://doi.org/10.3390/rs10101521",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDISIr=SpectralIndex(
short_name="NDISIr",
long_name="Normalized Difference Impervious Surface Index Red",
formula="(T - (R + N + S1) / 3.0)/(T + (R + N + S1) / 3.0)",
reference="https://doi.org/10.14358/PERS.76.5.557",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDISIg=SpectralIndex(
short_name="NDISIg",
long_name="Normalized Difference Impervious Surface Index Green",
formula="(T - (G + N + S1) / 3.0)/(T + (G + N + S1) / 3.0)",
reference="https://doi.org/10.14358/PERS.76.5.557",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDISIb=SpectralIndex(
short_name="NDISIb",
long_name="Normalized Difference Impervious Surface Index Blue",
formula="(T - (B + N + S1) / 3.0)/(T + (B + N + S1) / 3.0)",
reference="https://doi.org/10.14358/PERS.76.5.557",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDISIndwi=SpectralIndex(
short_name="NDISIndwi",
long_name="Normalized Difference Impervious Surface Index with NDWI",
formula="(T - (((G - N)/(G + N)) + N + S1) / 3.0)/(T + (((G - N)/(G + N)) + N + S1) / 3.0)",
reference="https://doi.org/10.14358/PERS.76.5.557",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDISImndwi=SpectralIndex(
short_name="NDISImndwi",
long_name="Normalized Difference Impervious Surface Index with MNDWI",
formula="(T - (((G - S1)/(G + S1)) + N + S1) / 3.0)/(T + (((G - S1)/(G + S1)) + N + S1) / 3.0)",
reference="https://doi.org/10.14358/PERS.76.5.557",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NSDS=SpectralIndex(
short_name="NSDS",
long_name="Normalized Shortwave Infrared Difference Soil-Moisture",
formula="(S1 - S2)/(S1 + S2)",
reference="https://doi.org/10.3390/land10030231",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
MBI=SpectralIndex(
short_name="MBI",
long_name="Modified Bare Soil Index",
formula="((S1 - S2 - N)/(S1 + S2 + N)) + 0.5",
reference="https://doi.org/10.3390/land10030231",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
EMBI=SpectralIndex(
short_name="EMBI",
long_name="Enhanced Modified Bare Soil Index",
formula="((((S1 - S2 - N)/(S1 + S2 + N)) + 0.5) - ((G - S1)/(G + S1)) - 0.5)/((((S1 - S2 - N)/(S1 + S2 + N)) + 0.5) + ((G - S1)/(G + S1)) + 1.5)",
reference="https://doi.org/10.1016/j.jag.2022.102703",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NDSoI=SpectralIndex(
short_name="NDSoiI",
long_name="Normalized Difference Soil Index",
formula="(S2 - G)/(S2 + G)",
reference="https://doi.org/10.1016/j.jag.2015.02.010",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
BaI=SpectralIndex(
short_name="BaI",
long_name="Bareness Index",
formula="R + S1 - N",
reference="https://doi.org/10.1109/IGARSS.2005.1525743",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
NBLI=SpectralIndex(
short_name="NBLI",
long_name="Normalized Difference Bare Land Index",
formula="(R - T)/(R + T)",
reference="https://doi.org/10.3390/rs9030249",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
DBI=SpectralIndex(
short_name="DBI",
long_name="Dry Built-Up Index",
formula="((B - T1)/(B + T1)) - ((N - R)/(N + R))",
reference="https://doi.org/10.3390/land7030081",
application_domain="urban",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
DBSI=SpectralIndex(
short_name="DBSI",
long_name="Dry Bareness Index",
formula="((S1 - G)/(S1 + G)) - ((N - R)/(N + R))",
reference="https://doi.org/10.3390/land7030081",
application_domain="soil",
date_of_addition="2022-04-18",
contributor="https://github.com/davemlz",
),
CSI=SpectralIndex(
short_name="CSI",
long_name="Char Soil Index",
formula="N/S2",
reference="https://doi.org/10.1016/j.rse.2005.04.014",
application_domain="burn",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VI6T=SpectralIndex(
short_name="VI6T",
long_name="VI6T Index",
formula="(N - T/10000.0)/(N + T/10000.0)",
reference="https://doi.org/10.1080/01431160500239008",
application_domain="burn",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
NBRT2=SpectralIndex(
short_name="NBRT2",
long_name="Normalized Burn Ratio Thermal 2",
formula="((N / (T / 10000.0)) - S2) / ((N / (T / 10000.0)) + S2)",
reference="https://doi.org/10.1080/01431160500239008",
application_domain="burn",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
NBRT3=SpectralIndex(
short_name="NBRT3",
long_name="Normalized Burn Ratio Thermal 3",
formula="((N - (T / 10000.0)) - S2) / ((N - (T / 10000.0)) + S2)",
reference="https://doi.org/10.1080/01431160500239008",
application_domain="burn",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
MIRBI=SpectralIndex(
short_name="MIRBI",
long_name="Mid-Infrared Burn Index",
formula="10.0 * S2 - 9.8 * S1 + 2.0",
reference="https://doi.org/10.1080/01431160110053185",
application_domain="burn",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
DPDD=SpectralIndex(
short_name="DPDD",
long_name="Dual-Pol Diagonal Distance",
formula="(VV + VH)/2.0 ** 0.5",
reference="https://doi.org/10.1016/j.rse.2018.09.003",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VDDPI=SpectralIndex(
short_name="VDDPI",
long_name="Vertical Dual De-Polarization Index",
formula="(VV + VH)/VV",
reference="https://doi.org/10.1016/j.rse.2018.09.003",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
NDPolI=SpectralIndex(
short_name="NDPolI",
long_name="Normalized Difference Polarization Index",
formula="(VV - VH)/(VV + VH)",
reference="https://www.isprs.org/proceedings/XXXVII/congress/4_pdf/267.pdf",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VHVVR=SpectralIndex(
short_name="VHVVR",
long_name="VH-VV Ratio",
formula="VH/VV",
reference="https://doi.org/10.1109/IGARSS47720.2021.9554099",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VHVVP=SpectralIndex(
short_name="VHVVP",
long_name="VH-VV Product",
formula="VH * VV",
reference="https://doi.org/10.1109/IGARSS47720.2021.9554099",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VVVHD=SpectralIndex(
short_name="VVVHD",
long_name="VV-VH Difference",
formula="VV - VH",
reference="https://doi.org/10.1109/IGARSS47720.2021.9554099",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VVVHS=SpectralIndex(
short_name="VVVHS",
long_name="VV-VH Sum",
formula="VV + VH",
reference="https://doi.org/10.1109/IGARSS47720.2021.9554099",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VVVHR=SpectralIndex(
short_name="VVVHR",
long_name="VV-VH Ratio",
formula="VV/VH",
reference="https://doi.org/10.3390/app9040655",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
VHVVD=SpectralIndex(
short_name="VHVVD",
long_name="VH-VV Difference",
formula="VH - VV",
reference="https://doi.org/10.3390/app9040655",
application_domain="radar",
date_of_addition="2022-04-19",
contributor="https://github.com/davemlz",
),
BAIM=SpectralIndex(
short_name="BAIM",
long_name="Burned Area Index adapted to MODIS",
formula="1.0/((0.05 - N) ** 2.0) + ((0.2 - S2) ** 2.0)",
reference="https://doi.org/10.1016/j.foreco.2006.08.248",
application_domain="burn",
date_of_addition="2022-04-20",
contributor="https://github.com/davemlz",
),
SWM=SpectralIndex(
short_name="SWM",
long_name="Sentinel Water Mask",
formula="(B + G)/(N + S1)",
reference="https://eoscience.esa.int/landtraining2017/files/posters/MILCZAREK.pdf",
application_domain="water",
date_of_addition="2022-04-20",
contributor="https://github.com/davemlz",
),
LSWI=SpectralIndex(
short_name="LSWI",
long_name="Land Surface Water Index",
formula="(N - S1)/(N + S1)",
reference="https://doi.org/10.1016/j.rse.2003.11.008",
application_domain="water",
date_of_addition="2022-04-20",
contributor="https://github.com/davemlz",
),
MLSWI26=SpectralIndex(
short_name="MLSWI26",
long_name="Modified Land Surface Water Index (MODIS Bands 2 and 6)",
formula="(1.0 - N - S1)/(1.0 - N + S1)",
reference="https://doi.org/10.3390/rs71215805",
application_domain="water",
date_of_addition="2022-04-20",
contributor="https://github.com/davemlz",
),
MLSWI27=SpectralIndex(
short_name="MLSWI27",
long_name="Modified Land Surface Water Index (MODIS Bands 2 and 7)",
formula="(1.0 - N - S2)/(1.0 - N + S2)",
reference="https://doi.org/10.3390/rs71215805",
application_domain="water",
date_of_addition="2022-04-20",
contributor="https://github.com/davemlz",
),
NBRplus=SpectralIndex(
short_name="NBRplus",
long_name="Normalized Burn Ratio Plus",
formula="(S2 - N2 - G - B)/(S2 + N2 + G + B)",
reference="https://doi.org/10.3390/rs14071727",
application_domain="burn",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
NBRSWIR=SpectralIndex(
short_name="NBRSWIR",
long_name="Normalized Burn Ratio SWIR",
formula="(S2 - S1 - 0.02)/(S2 + S1 + 0.1)",
reference="https://doi.org/10.1080/22797254.2020.1738900",
application_domain="burn",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
NDSWIR=SpectralIndex(
short_name="NDSWIR",
long_name="Normalized Difference SWIR",
formula="(N - S1)/(N + S1)",
reference="https://doi.org/10.1109/TGRS.2003.819190",
application_domain="burn",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
SEVI=SpectralIndex(
short_name="SEVI",
long_name="Shadow-Eliminated Vegetation Index",
formula="(N/R) + fdelta * (1.0/R)",
reference="https://doi.org/10.1080/17538947.2018.1495770",
application_domain="vegetation",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
ANDWI=SpectralIndex(
short_name="ANDWI",
long_name="Augmented Normalized Difference Water Index",
formula="(B + G + R - N - S1 - S2)/(B + G + R + N + S1 + S2)",
reference="https://doi.org/10.1016/j.envsoft.2021.105030",
application_domain="water",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
NBAI=SpectralIndex(
short_name="NBAI",
long_name="Normalized Built-up Area Index",
formula="((S2 - S1)/G)/((S2 + S1)/G)",
reference="https://www.omicsonline.org/scientific-reports/JGRS-SR136.pdf",
application_domain="urban",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
BRBA=SpectralIndex(
short_name="BRBA",
long_name="Band Ratio for Built-up Area",
formula="R/S1",
reference="https://www.omicsonline.org/scientific-reports/JGRS-SR136.pdf",
application_domain="urban",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
VIBI=SpectralIndex(
short_name="VIBI",
long_name="Vegetation Index Built-up Index",
formula="((N-R)/(N+R))/(((N-R)/(N+R)) + ((S1-N)/(S1+N)))",
reference="http://dx.doi.org/10.1080/01431161.2012.687842",
application_domain="urban",
date_of_addition="2022-09-22",
contributor="https://github.com/davemlz",
),
NSDSI1=SpectralIndex(
short_name="NSDSI1",
long_name="Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 1",
formula="(S1-S2)/S1",
reference="https://doi.org/10.1016/j.isprsjprs.2019.06.012",
application_domain="soil",
date_of_addition="2022-10-03",
contributor="https://github.com/CvenGeo",
),
NSDSI2=SpectralIndex(
short_name="NSDSI2",
long_name="Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 2",
formula="(S1-S2)/S2",
reference="https://doi.org/10.1016/j.isprsjprs.2019.06.012",
application_domain="soil",
date_of_addition="2022-10-03",
contributor="https://github.com/CvenGeo",
),
NSDSI3=SpectralIndex(
short_name="NSDSI3",
long_name="Normalized Shortwave-Infrared Difference Bare Soil Moisture Index 3",
formula="(S1-S2)/(S1+S2)",
reference="https://doi.org/10.1016/j.isprsjprs.2019.06.012",
application_domain="soil",
date_of_addition="2022-10-03",
contributor="https://github.com/CvenGeo",
),
NDTI=SpectralIndex(
short_name="NDTI",
long_name="Normalized Difference Turbidity Index",
formula="(R-G)/(R+G)",
reference="https://doi.org/10.1016/j.rse.2006.07.012",
application_domain="water",
date_of_addition="2022-10-03",
contributor="https://github.com/CvenGeo",
),
NDPonI=SpectralIndex(
short_name="NDPonI",
long_name="Normalized Difference Pond Index",
formula="(S1-G)/(S1+G)",
reference="https://doi.org/10.1016/j.rse.2006.07.012",
application_domain="water",
date_of_addition="2022-10-03",
contributor="https://github.com/CvenGeo",
),
NSTv1=SpectralIndex(
short_name="NSTv1",
long_name="NIR-SWIR-Temperature Version 1",
formula="((N-S2)/(N+S2))*T",
reference="https://doi.org/10.1016/j.rse.2011.06.010",
application_domain="burn",
date_of_addition="2022-10-06",
contributor="https://github.com/davemlz",
),
NSTv2=SpectralIndex(
short_name="NSTv2",
long_name="NIR-SWIR-Temperature Version 2",
formula="(N-(S2+T))/(N+(S2+T))",
reference="https://doi.org/10.1016/j.rse.2011.06.010",
application_domain="burn",
date_of_addition="2022-10-06",
contributor="https://github.com/davemlz",
),
NDCI=SpectralIndex(
short_name="NDCI",
long_name="Normalized Difference Chlorophyll Index",
formula="(RE1 - R)/(RE1 + R)",
reference="https://doi.org/10.1016/j.rse.2011.10.016",
application_domain="water",
date_of_addition="2022-10-10",
contributor="https://github.com/kalab-oto",
),
WI2015=SpectralIndex(
short_name="WI2015",
long_name="Water Index 2015",
formula="1.7204 + 171 * G + 3 * R - 70 * N - 45 * S1 - 71 * S2",
reference="https://doi.org/10.1016/j.rse.2015.12.055",
application_domain="water",
date_of_addition="2022-10-26",
contributor="https://github.com/remi-braun",
),
DSWI5=SpectralIndex(
short_name="DSWI5",
long_name="Disease-Water Stress Index 5",
formula="(N + G)/(S1 + R)",
reference="https://doi.org/10.1080/01431160310001618031",
application_domain="vegetation",
date_of_addition="2022-10-26",
contributor="https://github.com/remi-braun",
),
DSWI1=SpectralIndex(
short_name="DSWI1",
long_name="Disease-Water Stress Index 1",
formula="N/S1",
reference="https://doi.org/10.1080/01431160310001618031",
application_domain="vegetation",
date_of_addition="2022-10-29",
contributor="https://github.com/davemlz",
),
DSWI2=SpectralIndex(
short_name="DSWI2",
long_name="Disease-Water Stress Index 2",
formula="S1/G",
reference="https://doi.org/10.1080/01431160310001618031",
application_domain="vegetation",
date_of_addition="2022-10-29",
contributor="https://github.com/davemlz",
),
DSWI3=SpectralIndex(
short_name="DSWI3",
long_name="Disease-Water Stress Index 3",
formula="S1/R",
reference="https://doi.org/10.1080/01431160310001618031",
application_domain="vegetation",
date_of_addition="2022-10-29",
contributor="https://github.com/davemlz",
),
DSWI4=SpectralIndex(
short_name="DSWI4",
long_name="Disease-Water Stress Index 4",
formula="G/R",
reference="https://doi.org/10.1080/01431160310001618031",
application_domain="vegetation",
date_of_addition="2022-10-29",
contributor="https://github.com/davemlz",
),
DSI=SpectralIndex(
short_name="DSI",
long_name="Drought Stress Index",
formula="S1/N",
reference="https://www.asprs.org/wp-content/uploads/pers/1999journal/apr/1999_apr_495-501.pdf",
application_domain="vegetation",
date_of_addition="2022-10-26",
contributor="https://github.com/remi-braun",
),
BITM=SpectralIndex(
short_name="BITM",
long_name="Landsat TM-based Brightness Index",
formula="(((B**2.0)+(G**2.0)+(R**2.0))/3.0)**0.5",
reference="https://doi.org/10.1016/S0034-4257(98)00030-3",
application_domain="soil",
date_of_addition="2022-11-20",
contributor="https://github.com/davemlz",
),
BIXS=SpectralIndex(
short_name="BIXS",
long_name="SPOT HRV XS-based Brightness Index",
formula="(((G**2.0)+(R**2.0))/2.0)**0.5",
reference="https://doi.org/10.1016/S0034-4257(98)00030-3",
application_domain="soil",
date_of_addition="2022-11-20",
contributor="https://github.com/remi-braun",
),
RI4XS=SpectralIndex(
short_name="RI4XS",
long_name="SPOT HRV XS-based Redness Index 4",
formula="(R**2.0)/(G**4.0)",
reference="https://doi.org/10.1016/S0034-4257(98)00030-3",
application_domain="soil",
date_of_addition="2022-11-20",
contributor="https://github.com/davemlz",
),
NDSIWV=SpectralIndex(
short_name="NDSIWV",
long_name="WorldView Normalized Difference Soil Index",
formula="(G - Y)/(G + Y)",
reference="https://www.semanticscholar.org/paper/Using-WorldView-2-Vis-NIR-MSI-Imagery-to-Support-Wolf/5e5063ccc4ee76b56b721c866e871d47a77f9fb4",
application_domain="soil",
date_of_addition="2022-11-20",
contributor="https://github.com/remi-braun",
),
TWI=SpectralIndex(
short_name="TWI",
long_name="Triangle Water Index",
formula="(2.84 * (RE1 - RE2) / (G + S2)) + ((1.25 * (G - B) - (N - B)) / (N + 1.25 * G - 0.25 * B))",
reference="https://doi.org/10.3390/rs14215289",
application_domain="water",
date_of_addition="2023-02-10",
contributor="https://github.com/remi-braun",
),
CCI=SpectralIndex(
short_name="CCI",
long_name="Chlorophyll Carotenoid Index",
formula="(G1 - R)/(G1 + R)",
reference="https://doi.org/10.1073/pnas.1606162113",
application_domain="vegetation",
date_of_addition="2023-03-12",
contributor="https://github.com/joanvlasschaert",
),
NBLIOLI=SpectralIndex(
short_name="NBLIOLI",
long_name="Normalized Difference Bare Land Index for Landsat-OLI",
formula="(R - T1)/(R + T1)",
reference="https://doi.org/10.3390/rs9030249",
application_domain="soil",
date_of_addition="2023-03-12",
contributor="https://github.com/davemlz",
),
SLAVI=SpectralIndex(
short_name="SLAVI",
long_name="Specific Leaf Area Vegetation Index",
formula="N/(R + S2)",
reference="https://www.asprs.org/wp-content/uploads/pers/2000journal/february/2000_feb_183-191.pdf",
application_domain="vegetation",
date_of_addition="2023-07-03",
contributor="https://github.com/geoSanjeeb",
),
EBI=SpectralIndex(
short_name="EBI",
long_name="Enhanced Bloom Index",
formula="(R + G + B)/((G/B) * (R - B + epsilon))",
reference="https://doi.org/10.1016/j.isprsjprs.2019.08.006",
application_domain="vegetation",
date_of_addition="2023-07-03",
contributor="https://github.com/geoSanjeeb",
),
)
)
<file_sep>/src/utils.py
from enum import Enum, unique
@unique
class Bands(Enum):
"""
Bands supported by SpectralIndex DataClass
"""
AEROSOL = "A"
BLUE = "B"
GREEN1 = "G1"
GREEN = "G"
YELLOW = "Y"
RED = "R"
NIR = "N"
NIR2 = "N2"
WATERVAPOUR = "WV"
RED1 = "RE1"
RED2 = "RE2"
RED3 = "RE3"
SWIR1 = "S1"
SWIR2 = "S2"
TIR = "T"
TIR1 = "T1"
TIR2 = "T2"
GAIN_FACTOR = "g"
CANOPY_BACKGROUND_ADJUSTMENT = "L"
AEROSOL_COEFFICIENT1 = "C1"
AEROSOL_COEFFICIENT2 = "C2"
C_EXPONENT = "cexp"
N_EXPONENT = "nexp"
GAMMA = "gamma"
ALPHA = "alpha"
BETA = "beta"
SOIL_LINE_SLOPE = "sla"
SOIL_LINE_INTERCEPT = "slb"
PAR = "PAR"
OMEGA = "omega"
F_DELTA = "fdelta"
EPSILON = "epsilon"
SLOPE_PARAMETER_SOIL = "k"
WAVELENGTH_NIR = "lambdaN"
WAVELENGTH_RED = "lambdaR"
WAVELENGTH_GREEN = "lambdaG"
HV = "HV"
HH = "HH"
VV = "VV"
VH = "VH"
KNN = "kNN"
KNR = "kNR"
KNB = "kNB"
KNL = "kNL"
KGG = "kGG"
KGR = "kGR"
KGB = "kGB"
KBB = "kBB"
KBR = "kBR"
KBL = "kBL"
KRR = "kRR"
KRB = "kRB"
KRL = "kRL"
KLL = "kLL"
class IndexType(Enum):
"""
IndexType supported by SpectralIndex DataClass
"""
VEGETATION = "vegetation"
WATER = "water"
BURN = "burn"
SNOW = "snow"
SOIL = "soil"
URBAN = "urban"
KERNEL = "kernel"
RADAR = "radar"
<file_sep>/src/constants.py
constants = {
"L": {
"short_name": "L",
"description": "Canopy background adjustment",
"default": 1.0,
},
"g": {"short_name": "g", "description": "Gain factor", "default": 2.5},
"C1": {
"short_name": "C1",
"description": "Coefficient 1 for the aerosol resistance term",
"default": 6.0,
},
"C2": {
"short_name": "C2",
"description": "Coefficient 2 for the aerosol resistance term",
"default": 7.5,
},
"cexp": {
"short_name": "cexp",
"description": "Exponent used for OCVI",
"default": 1.16,
},
"nexp": {
"short_name": "nexp",
"description": "Exponent used for GDVI",
"default": 2.0,
},
"alpha": {
"short_name": "alpha",
"description": "Weighting coefficient used for WDRVI",
"default": 0.1,
},
"beta": {
"short_name": "beta",
"description": "Calibration parameter used for NDSInw",
"default": 0.05,
},
"gamma": {
"short_name": "gamma",
"description": "Weighting coefficient used for ARVI",
"default": 1.0,
},
"omega": {
"short_name": "omega",
"description": "Weighting coefficient used for MBWI",
"default": 2.0,
},
"k": {
"short_name": "k",
"description": "Slope parameter by soil used for NIRvH2",
"default": 0.0,
},
"PAR": {
"short_name": "PAR",
"description": "Photosynthetically Active Radiation",
"default": None,
},
"lambdaG": {
"short_name": "lambdaG",
"description": "Green wavelength (nm) used for NDGI",
"default": None,
},
"lambdaR": {
"short_name": "lambdaR",
"description": "Red wavelength (nm) used for NIRvH2 and NDGI",
"default": None,
},
"lambdaN": {
"short_name": "lambdaN",
"description": "NIR wavelength (nm) used for NIRvH2 and NDGI",
"default": None,
},
"sla": {
"short_name": "sla",
"description": "Soil line slope",
"default": 1.0,
},
"slb": {
"short_name": "slb",
"description": "Soil line intercept",
"default": 0.0,
},
"sigma": {
"short_name": "sigma",
"description": "Length-scale parameter in the RBF kernel",
"default": 0.5,
},
"p": {
"short_name": "p",
"description": "Kernel degree in the polynomial kernel",
"default": 2.0,
},
"c": {
"short_name": "c",
"description": "Trade-off parameter in the polynomial kernel",
"default": 1.0,
},
"fdelta": {
"short_name": "fdelta",
"description": "Adjustment factor used for SEVI",
"default": 0.581,
},
"epsilon": {
"short_name": "epsilon",
"description": "Adjustment constant used for EBI",
"default": 1,
},
}
|
96accd4fa110dad74f854749d49771065d6c6592
|
[
"Markdown",
"Python",
"reStructuredText"
] | 13
|
Python
|
davemlz/awesome-ee-spectral-indices
|
fa185d263b6b698ad829c609b65b2cc602ffbd2b
|
cb91789d49fee615211c7080162df47c1266910b
|
refs/heads/master
|
<file_sep>function Casino(numberOfMachines, initialMoney) {
var self = this;
this.machines = [];
//get random number
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
if ((numberOfMachines > 0) && (initialMoney > 0) && (typeof numberOfMachines === 'number') && (typeof initialMoney === 'number')) {
var _initialMoneyInMachines = Math.floor(initialMoney / numberOfMachines);
var _moneyBonusForFirstMachine = (initialMoney / numberOfMachines) - _initialMoneyInMachines;
var _indexOfLuckyMachine = getRandomInt(0, numberOfMachines);
console.log("Lucky machine with index:" + _indexOfLuckyMachine);
} else {
console.log('Oh. I see you drunk. Lemme assign vars for you');
numberOfMachines = 3;
var _initialMoneyInMachines = Math.floor(initialMoney / numberOfMachines);
var _moneyBonusForFirstMachine = (initialMoney / numberOfMachines) - _initialMoneyInMachines;
var _indexOfLuckyMachine = getRandomInt(0, numberOfMachines);
}
self.machines[0] = new SlothMachine(_initialMoneyInMachines + _moneyBonusForFirstMachine);
self.machines[0]._id = 0;
for (var i = 1; i < numberOfMachines; i++) {
self.machines[i] = new SlothMachine(_initialMoneyInMachines);
self.machines[i]._id = i;
}
self.machines[_indexOfLuckyMachine]._isLucky = true;
// console.log(self.machines[_indexOfLuckyMachine]);
this._getTotalAmountOfMoney = function () {
var totalAmountOfMoney = 0;
for (var j = 0; j < self.machines.length; j++) {
totalAmountOfMoney += self.machines[j]._initialMoney;
}
return Math.ceil(totalAmountOfMoney);
}
this._getTotalNumberOfMachines = function () {
var totalNumberOfMachines = 0;
for (var j = 0; j < self.machines.length; j++) {
if (typeof self.machines[j]._initialMoney === 'number') {
totalNumberOfMachines++;
}
}
return totalNumberOfMachines;
}
this._getRichestMachine = function () {
var richestMachine = -Infinity;
var richestMachineIndex = 0;
for (var i = 0; i < self.machines.length; i++) {
if (self.machines[i]._initialMoney > richestMachine) {
richestMachine = self.machines[i]._initialMoney;
richestMachineIndex = i;
}
}
return {richMachineMoney: richestMachine, richMachineIndex: richestMachineIndex};
};
this._getHighestId = function () {
var highestId = -Infinity;
for (var i = 0; i < self.machines.length; i++) {
if (self.machines[i]._id > highestId) {
highestId = self.machines[i]._id;
}
}
console.log('highest id: ' + highestId)
return highestId;
};
this.addNewSlotMachine = function () {
var _initialAmountOfMoneyForNewSlotMachine = this._getRichestMachine().richMachineMoney / 2;
var newSlotMachineId = 1 + this._getHighestId();
var richestMachineIndex = this._getRichestMachine().richMachineIndex;
var newSlotMachine = new SlothMachine(_initialAmountOfMoneyForNewSlotMachine);
newSlotMachine._id = newSlotMachineId;
console.log("richest machine index:" + richestMachineIndex);
self.machines.push(newSlotMachine);
self.machines[richestMachineIndex]._initialMoney = _initialAmountOfMoneyForNewSlotMachine;
};
this._spreadMoney = function (amount) {
var amountForOneMachine = amount / this._getTotalNumberOfMachines();
for (var i = 0; i < self.machines.length; i++) {
self.machines[i]._initialMoney += amountForOneMachine;
}
console.log('$+for machines: ' + amountForOneMachine);
};
this._removeMachineById = function (id) {
var moneyInDevaredMachine = 0;
var isGoodId = false;
for (var i = 0; i < self.machines.length; i++) {
if (self.machines[i]._id === id) {
moneyInDevaredMachine = self.machines[i]._initialMoney;
self.machines.splice(i, 1);
isGoodId = true;
}
}
if (isGoodId) {
this._spreadMoney(moneyInDevaredMachine);
console.log('machine with id ' + id + ' has been deleted')
} else {
console.log('bad id');
}
}
this._showAllMachines = function () {
console.log('Machines in casino:\n');
for (var i = 0; i < self.machines.length; i++) {
console.log(self.machines[i]);
}
}
this._takeMoneyFromCasino = function (amount) {
var currentMoneyInCasino = this._getTotalAmountOfMoney();
var takenAmount = 0;
takenAmount = amount;
var tempArr = [];
tempArr = self.machines;
if (currentMoneyInCasino < amount) {
for (var i = 0; i < self.machines.length; i++) {
self.machines[i]._initialMoney = 0;
}
takenAmount = currentMoneyInCasino;
} else {
tempArr.sort(function (a, b) {
return b._initialMoney - a._initialMoney;
});
//console.log(tempArr);
for (var i = 0; i < tempArr.length; i++) {
if (takenAmount > tempArr[i]._initialMoney) {
takenAmount -= tempArr[i]._initialMoney;
tempArr[i]._initialMoney = 0;
} else {
tempArr[i]._initialMoney -= takenAmount;
takenAmount = 0;
break;
}
if (takenAmount < 0)
break;
}
}
//console.log(takenAmount);
return amount;
}
}
function SlothMachine(initialMoney) {
var self = this;
this._id = null;
if((typeof initialMoney === 'number') && (initialMoney => 0)) {
this._initialMoney = initialMoney;
} else {
console.log('Oh. I see you drunk. Lemme assign vars for you');
this._initialMoney = 2000;
}
this._isLucky = false;
this.NNN = null; //if you want to test assign this number, if you want random number set it to null;
this._getOutMoney = function (amount) {
if((typeof amount === 'number') && (amount =>0)) {
this._initialMoney -= amount;
}
}
this._putInMoney = function (amount) {
if((typeof amount === 'number') && (amount =>0)) {
this._initialMoney += amount;
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
this._getRandomNNN = function () {
var number1 = getRandomInt(0, 10);
var number2 = getRandomInt(0, 10);
var number3 = getRandomInt(0, 10);
var gameNumber = [];
gameNumber = [number1, number2, number3];
return gameNumber;
};
this._playGame = function (inputMoney) {
if(inputMoney >=0 && typeof inputMoney === 'number'){
var prizeMoney = 0;
var moneyToTakeFromCasino =0;
self._putInMoney(inputMoney);
var newGameNumber = this.NNN || self._getRandomNNN();
if(self._isLucky){
newGameNumber = self._getRandomNNN();
}
console.log(newGameNumber);
if (newGameNumber[0] === 7 && newGameNumber[1] === 7 && newGameNumber[2] === 7 && !self._isLucky) {//3 digits similar equal 7
console.log('JACK POT!!!!! YOU WIN FUCKING JACKPOT!!!!');
prizeMoney = self._initialMoney;
self._getOutMoney(prizeMoney)
} else {
if (newGameNumber[0] === newGameNumber[1] && newGameNumber[0] === newGameNumber[2]) {//3 digits similar but not equal 7
console.log('Wow! 3 digits similar');
prizeMoney = inputMoney * 5;
if(prizeMoney>self._initialMoney){
moneyToTakeFromCasino = prizeMoney-self._initialMoney;
self._initialMoney=0;
console.log('Your win is '+prizeMoney+' it`s bigger than money in this SlothMachine. Pls take rest money=' + moneyToTakeFromCasino+
' from Casino(._takeMoneyFromCasino('+moneyToTakeFromCasino+'))');
} else {self._getOutMoney(prizeMoney);}
} else {//any two digits similar
if (newGameNumber[0] === newGameNumber[1] || newGameNumber[0] === newGameNumber[2] || newGameNumber[1] === newGameNumber[2]) {
console.log('Grats! two similar numbers!');
prizeMoney = inputMoney * 2;
if(prizeMoney>self._initialMoney){
moneyToTakeFromCasino = prizeMoney-self._initialMoney;
self._initialMoney=0;
console.log('Your win is '+prizeMoney+' it`s bigger than money in this SlothMachine. Pls take rest money=' + moneyToTakeFromCasino+
' from Casino(._takeMoneyFromCasino('+moneyToTakeFromCasino+'))');
} else {self._getOutMoney(prizeMoney);}
}
}
}
console.log('prize money ' + (prizeMoney));
} else {
console.log('Haha! Funny, your bet is < 0 or it`s not a number');
}
}
// console.log(this);
}
//var casino = new Casino(4, 20000);
//var casino1 = new Casino(3, 213);
//console.log(casino._getTotalAmountOfMoney());
//console.log(casino._getTotalNumberOfMachines());
//console.log(casino._getRichestMachine());
// casino.addNewSlotMachine();
// casino._showAllMachines();
// casino._removeMachineById(4);
// casino._showAllMachines();
//console.log(casino._takeMoneyFromCasino(12000));
// //casino._showAllMachines();
// casino.machines[1]._playGame(300);
// casino._showAllMachines();
function test() {
var testCasino = new Casino(2, 20000);
var testCasino1 = new Casino(1, 1000);
var testCasino2 = new Casino(1, 1000);
testCasino._showAllMachines();
console.log(testCasino._getTotalAmountOfMoney());
console.log(testCasino._getTotalNumberOfMachines());
console.log('**********************************************************************************');
testCasino.addNewSlotMachine();
testCasino._showAllMachines();
console.log('**********************************************************************************');
testCasino._removeMachineById(234); // id out of range
console.log('**********************************************************************************');
testCasino._removeMachineById(1);
testCasino._showAllMachines();
console.log('**********************************************************************************');
testCasino.addNewSlotMachine();
testCasino._showAllMachines();
console.log('**********************************************************************************');
testCasino._takeMoneyFromCasino(10000);
testCasino._showAllMachines();
console.log('**********************************************************************************');
console.log(testCasino.machines[2]);//we will use this SlothMachine
//set number to 777 and test
testCasino.machines[2].NNN = [7,7,7];
testCasino.machines[2]._playGame(300);//you put 300(now in slothMachine2644.5)
console.log(testCasino.machines[2]);
console.log('**********************************************************************************');
//set number to 777 but machine is lucky and test
testCasino.machines[2].NNN = [7,7,7];
testCasino.machines[2]._isLucky = true;
testCasino.machines[2]._playGame(300);//you put 300(now in slothMachine2644.5)
console.log(testCasino.machines[2]); // expect jackpot but machine is lucky
console.log('**********************************************************************************');
//set number to AAA and test
testCasino1.machines[0]._isLucky = false;
testCasino1.machines[0].NNN = [2,2,2];
testCasino1.machines[0]._playGame(2000);
console.log(testCasino1.machines[0]);
console.log('**********************************************************************************');
//set number to AAC and test
testCasino2.machines[0]._isLucky = false;
testCasino2.machines[0].NNN = [2,2,1];
testCasino2.machines[0]._playGame(200);
console.log(testCasino2.machines[0]);
console.log('***********************************************************************************');
}
test();
module.exports = Casino;
module.exports = SlothMachine;
|
bf6081c303cd709d2008b05db878adefb713db84
|
[
"JavaScript"
] | 1
|
JavaScript
|
romua/L14_OOP
|
6bf62d6e3a0c8564f9fe5f91fd250bb0a2b88bd7
|
31f55926fc1c69891f7d5814bf90c29d36777d15
|
refs/heads/master
|
<repo_name>polito-eda/SpiNNStorageHandlers<file_sep>/setup.py
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="SpiNNStorageHandlers",
version="3.0.0",
description="I/O handler classes for SpiNNaker software stack",
url="https://github.com/SpiNNakerManchester/SpiNNStorageHandlers",
license="GNU GPLv3.0",
packages=['spinn_storage_handlers',
'spinn_storage_handlers.abstract_classes'],
install_requires=['six']
)
|
ff9fef67308b48dde373bffe7bab2d9ea4f060c6
|
[
"Python"
] | 1
|
Python
|
polito-eda/SpiNNStorageHandlers
|
9782093a10bcf12bb694684b75504a368edba5c7
|
1eff16ed3419571d2bd1e1de2f62d5ce9ae676a5
|
refs/heads/main
|
<repo_name>Snehalmiraje/Case-Study-<file_sep>/Customer/src/main/java/com/customer/repository/CustomerRepo.java
package com.customer.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.customer.model.Customer;
@Repository
public interface CustomerRepo extends MongoRepository<Customer, String>{
public Customer findByEmail(String Email);
}
<file_sep>/Home.js
import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Booking from "./Booking";
import Title from "./Title";
import logo from "./images/logo.png";
import Services from "./Services";
import Contact from "./AboutUs"
export default class Home extends Component {
render() {
return (
<Router>
<div className="home">
<nav class="navbar navbar-expand-lg fixed-top">
<div class="container-fluid">
<img src={logo} class="navbar-brand" alt=""></img>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<Link className="cl" to={"/title"}>Home</Link>
<Link className="cl" to={"/Services"}>Services</Link>
<Link className="cl" to={"/Contact"}>About Us</Link>
<Link className="btne" to={"/Booking"}>Book now</Link>
</div>
</div>
</div>
</nav>
<Switch>
<Route path='/home' component={Title} />
<Route path='/title' component={Title} />
<Route path="/Booking" component={Booking} />
<Route path='/Services' component={Services} />
<Route path="/Contact" component={Contact} />
</Switch>
</div>
<div className="footer">
<p>© Copyright 2020 <i>@snehalmiraje</i></p>
</div>
</Router>
);
}
}<file_sep>/Title.js
import React, { Component } from "react";
export default class Title extends Component {
render() {
return (
<div>
<div className="container1">
<div className="title">
<h1 >Car Wash</h1></div>
</div>
<div className="desc">
</div>
<div className="inf"> <p>Enjoy the spirit of a new car by Adding Shine in every side</p> </div>
</div>
);
}
}<file_sep>/Customer/src/main/java/com/customer/services/customerService.java
package com.customer.services;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
/*import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;*/
import org.springframework.stereotype.Service;
import com.customer.model.Customer;
import com.customer.repository.CustomerRepo;
@Service
public class customerService /*implements UserDetailsService*/ {
@Autowired
private CustomerRepo customerRepo;
//Create operation
public Customer create(Customer customer) {
return customerRepo.save(customer);
}
//Retrieve operation
public List<Customer> getAll(){
return customerRepo.findAll();
}
public Customer getByEmail(String email)
{
return customerRepo.findByEmail(email);
}
//Update operation
public Customer update(String Name, String password,String email,String contact) {
Customer p = customerRepo.findByEmail(email);
p.setName(Name);
p.setPassword(<PASSWORD>);
p.setEmail(email);
p.setContact(contact);
return customerRepo.save(p);
}
//Delete operation
public void deleteAll()
{
customerRepo.deleteAll();
}
public void delete(String email) {
Customer p = customerRepo.findByEmail(email);
customerRepo.delete(p);
}
// @Override
/* public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Customer p=customerRepo.findByEmail(email);
if(p == null) {
throw new UsernameNotFoundException("User not found");
}
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("customer"));
return new User(p.getEmail(),p.getPassword(),authorities);
}*/
}
<file_sep>/Admin/src/main/java/io/carwash/admin/service/AdminService.java
package io.carwash.admin.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.carwash.admin.model.Admin;
import io.carwash.admin.repository.AdminRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class AdminService implements UserDetailsService {
@Autowired
private AdminRepo adminRepo;
//Create operation
public Admin create(Admin customer) {
return adminRepo.save(customer);
}
//Retrieve operation
public List<Admin> getAll(){
return adminRepo.findAll();
}
public Admin getByEmail(String email)
{
return adminRepo.findByEmail(email);
}
//Update operation
public Admin update(String Name, String password,String email,String contact) {
Admin p = adminRepo.findByEmail(email);
p.setName(Name);
p.setPassword(<PASSWORD>);
p.setEmail(email);
p.setContact(contact);
return adminRepo.save(p);
}
//Delete operation
public void deleteAll()
{
adminRepo.deleteAll();
}
public void delete(String email) {
Admin p = adminRepo.findByEmail(email);
adminRepo.delete(p);
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Admin p=adminRepo.findByEmail(email);
if(p == null) {
throw new UsernameNotFoundException("User not found");
}
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("customer"));
return new User(p.getEmail(),p.getPassword(),authorities);
}
}<file_sep>/Admin/src/main/resources/application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=caseStudy
spring.application.name=ADMIN-SERVICE
server.port=9092<file_sep>/Admin/src/main/java/io/carwash/admin/service/WasherService.java
package io.carwash.admin.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.carwash.admin.model.Admin;
import io.carwash.admin.model.Washer;
import io.carwash.admin.repository.WasherRepo;
@Service
public class WasherService {
@Autowired
WasherRepo washerRepo;
//Create operation
public Washer create(Washer washer) {
return washerRepo.save(washer);
}
//Retrieve operation
public List<Washer> getAll(){
return washerRepo.findAll();
}
public Washer getByEmail(String email)
{
return washerRepo.findByEmail(email);
}
//Delete operation
public void deleteAll()
{
washerRepo.deleteAll();
}
public void delete(String email) {
Washer p = washerRepo.findByEmail(email);
washerRepo.delete(p);
}
}
|
7d467c61dd6975727b2ae1e039322faa299a132a
|
[
"JavaScript",
"Java",
"INI"
] | 7
|
Java
|
Snehalmiraje/Case-Study-
|
01dc9ceb8e5438135120f2ddba48b93d0f862c12
|
5364b26d4d06ee4979391739c69d504904848031
|
refs/heads/master
|
<file_sep>import axios from "axios";
import Constants from "expo-constants";
// import { baseUrl} from "react-native-dotenv";
// ApiClient.init(baseUrl)
let GetApis = async (controller, action, params, timeout) => {
try {
let res = await axios.get("/" + controller + "/" + action, {
baseURL: "http://appapi.sunhouse.com.vn/api/",
timeout: timeout,
headers: {
"cache-control": "no-cache",
Authorization: "Basic dHJpZXVwdjpwaGFtdHJpZXU=",
},
params: params,
});
let data = await res.data;
if (data == undefined) {
return "error get";
} else return data;
} catch (error) {
return error;
}
};
export default GetApis;
|
c7632cfd754ec43edebf9432ade71a5394589bee
|
[
"JavaScript"
] | 1
|
JavaScript
|
boycntt/PictureCreator
|
197cc02d8915b6397aae6b61d76154dc46e3041e
|
38d4b2da4920bab3105f66c566d6387949af02d3
|
refs/heads/main
|
<file_sep>module.exports = {
getEndpoint: job => {
let endPoint = {};
if (job === 'dev') {
endPoint['Application'] ='https://www.dev.saucedemo.com/';
}
else {
endPoint['Application'] ='https://www.saucedemo.com/';
}
return endPoint;
}
};
<file_sep>const argv = require("yargs").argv
//************Endpoints************************
const endpoint = require("../endpoints/endpoints.js");
process.env.app = (argv.app) ? argv.app : process.env.app;
let app = process.env.app === "undefined" ? "local" : process.env.app;
//**************************************************feature file settings****************************************************
//select ffs
process.env.ff = (argv.ff) ? argv.ff : process.env.ff;
let featureFilePath = process.env.ff === "undefined" ? `./features/featureFiles/*.feature` : `./features/featureFiles/${argv.ff}.feature`;
//***************************************************Browser Settings *******************************************************
//browser run in headless mode incase running api scripts or any other platform beside windows+mac
var maxBrowserInstance = process.env.threads || 1
runTimeServices = ['chromedriver']
runTimeCapabilities = [{
maxInstances: maxBrowserInstance,
browserName: 'chrome',
acceptInsecureCerts: true,
'goog:chromeOptions': {
args: ["--start-maximized", "--disable-infobars", "--disable-gpu"],
useAutomationExtension: false
}
}]
//************************************************Config file *******************************************************/
// exports.config = {
let localConfig = {
runner: "local",
services: runTimeServices,
specs: [
featureFilePath
],
exclude: [
// 'path/to/excluded/files'
],
// =======================================================================================================
// Browser Capabilities
// =======================================================================================================
capabilities: runTimeCapabilities,
plugins: {
'wdio-screenshot': {}
},
// =======================================================================================================
// Test Configurations
// =======================================================================================================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: trace | debug | info | warn | error | silent
logLevel: "error",
sync: true,
waitforTimeout: 10000,
// Default timeout in milliseconds for request
// if browser driver or grid doesn't send response
connectionRetryTimeout: 120000,
// Default request retries count
connectionRetryCount: 3,
// Test runner services
framework: "cucumber",
reporters: ["spec",
["cucumberjs-json", {
jsonFolder: "./reports/output/json/",
language: "en"
}
]
],
// If you are using Cucumber you need to specify the location of your step definitions.
cucumberOpts: {
// require: ["../step_definitions/*.steps.js"],
require: ['./step_definitions/*.steps.js'],
backtrace: false, // <boolean> show full backtrace for errors
requireModule: [], // <string[]> ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable)
dryRun: false, // <boolean> invoke formatters without executing steps
failFast: false, // <boolean> abort the run on first failure
format: ['pretty'], // <string[]> (type[:path]) specify the output format, optionally supply PATH to redirect formatter output (repeatable)
colors: true, // <boolean> disable colors in formatter output
snippets: true, // <boolean> hide step definition snippets for pending steps
source: true, // <boolean> hide source uris
profile: [], // <string[]> (name) specify the profile to use
strict: false, // <boolean> fail if there are any undefined or pending steps
tagExpression: '', // <string> (expression) only execute the features or scenarios with tags matching the expression
timeout: 60000, // <number> timeout for step definitions
ignoreUndefinedDefinitions: false, // <boolean> Enable this config to treat undefined definitions as warnings.
scenarioLevelReporter: false // Enable this to make webdriver.io behave as if scenarios and not steps were the tests.
},
//************API Config Starts**************************
endpoint: endpoint.getEndpoint(app),
onPrepare: function (config, capabilities) {
},
};
module.exports = { config: localConfig }<file_sep>var Selector = require('../files/locators/common').getSelector;
const chai = require('chai');
const cExpect = chai.expect;
module.exports={
click: (element) => {
try{
browser.$(Selector[element]).isDisplayed();
browser.$(Selector[element]).click();
}
catch (error){
cExpect.fail(1,2,error);
}
},
ClickWithLocator: (element) => {
try{
browser.$(element).isDisplayed();
browser.$(element).click();
}
catch (error){
cExpect.fail(1,2,error);
}
},
selectByText: (text,element) => {
try{
browser.$(Selector[element]).isDisplayed();
browser.$(Selector[element]).selectByVisibleText(text);
}
catch (error){
cExpect.fail(1,2,error);
}
},
enter: (text,element) => {
try{
browser.$(Selector[element]).isDisplayed();
browser.$(Selector[element]).setValue(text);
const valSelected = $(Selector[element]).getValue();
expect(valSelected.toLowerCase()).toEqual(text.toLowerCase());
}
catch (error){
cExpect.fail(1,2,error);
}
},
wait: (vTime) => {
try{
browser.pause(vTime);
}
catch (error){
cExpect.fail(1,2,error);
}
}
}<file_sep>const { Given, When, Then } = require("cucumber");
var action = require('../functionalLibs/web.action');
var customAction = require('../functionalLibs/web.custom');
Then(/.*click.*\"([^\"]*)\".*$/, (element) => {
action.click(element);
});
Then(/.*enter.*\"([^\"]*)\" in \"([^\"]*)\".*$/, (text,element) => {
action.enter(text,element);
});
Then(/.* select by text (.*) in (.*)$/, (text,element) => {
action.selectByText(text,element);
});
Then(/.* remove.*lowest.*cart.*$/, () => {
customAction.removeLowestPriceFromCart("CartItems","CartItemsRemove");
});<file_sep># tmpWdioExercise
## Steps to setup
###### 1. Please install Node v12
###### 2. Close the repository and Go to tmpWdioExercise/tests (cd tmpWdioExercise/tests) directory
###### 3. Run npm install on terminal to install the packages from package.json (npm install)
###### 4. Enure you are using chrome version 94. If you are using higher version then change the version in package.json to get the appropriate version
## Steps to execute
###### 1. run command on terminal :npm run clean-reports && npx wdio conf/local.conf.js && npm run generate-html-report
###### 1.1 npm run clean-reports: will delete any existing reports
###### 1.2 npx wdio conf/local.conf.js: this will run the feature file
###### 1.3 npm run generate-html-report: this will generate the html report in reports/output/html folder.
###### 2. Check the test results in reports/output/html.
<file_sep>const config = require('../conf/local.conf').config;
const uri = config.endpoint;
module.exports={
navigate:(url) => {
try{
browser.url(uri[url]); }
catch (error){
console.error(error)
}
},
close:() => {
try{
browser.closeWindow(); }
catch (error){
console.error(error)
}
}
}<file_sep>const reporter = require("cucumber-html-reporter");
fs = require("fs-extra");
// /************************ check if all results related folders are there or not********************************************/
if (fs.existsSync("reports/output")) {
if (!fs.existsSync("reports/output/html")) {
fs.mkdirSync("reports/output/html");
}
}
/************************End of check if all results related folders are there or not********************************************/
let currentTime = new Date().toJSON().replace(/:/g, "-");
let jsonReportPath = "./reports/output/json/";
let htmlReportPath = "./reports/output/html/cucumber-html-report" + "-" + currentTime + ".html";
let options = {
theme: 'bootstrap', //'bootstrap' | 'hierarchy' | 'foundation' | 'simple',
brandTitle:"Execution Report",
jsonDir: jsonReportPath,
output: htmlReportPath,
reportSuiteAsScenarios: false,
scenarioTimestamp: true,
launchReport: false,
ignoreBadJsonFile:true,
};
reporter.generate(options);
|
82733c05d9dfe8d1f817a80d0fde366f4decbfe7
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
ashishjindal13/tmpWdioExercise
|
0b1304cab730877e56268cd77ace7f5fbd47bfbc
|
a2c8a9dcbf64be6f27df3ae12f87f5e2f31fbe17
|
refs/heads/master
|
<file_sep>class Category < ActiveRecord::Base
belongs_to :user
has_many :products
validates :name, :presence => true
acts_as_nested_set
end
<file_sep>require 'spec_helper'
describe "admin/categories/index.html.slim" do
before(:each) do
@root = Category.create! :name => 'root', :parent_id => nil
@root.children.create! :name => 'cat1'
@root.children.create! :name => 'cat2', :published => true
assign(:categories, @root.children)
assign(:path, @root.ancestors)
end
it "renders a list of admin/categories" do
render
rendered.should contain('Categories management')
rendered.should contain('cat1')
rendered.should contain('cat2')
end
it "should be able go into subcategory" do
render
rendered.should have_selector('a', :content => '...')
end
it "should be able publish and unpublish the category" do
render
rendered.should have_selector('a', :content => 'Publish')
rendered.should have_selector('a', :content => 'Unpublish')
end
it "should be able set ordering of categories" do
render
rendered.should have_selector('a', :content => 'Up', :href => move_left_admin_category_url(@root.children.first.id))
rendered.should have_selector('a', :content => 'Down', :href => move_right_admin_category_url(@root.children.first.id))
end
it "should show link to parent category" do
cat = @root.children.first
cat.children.create! :name => 'cat1.1'
cat.children.create! :name => 'cat1.2'
assign(:categories, cat.children)
assign(:path, cat.ancestors)
render
rendered.should have_selector('ul', :class => 'breadcrumb')
rendered.should have_selector('a', :content => 'root')
end
end
|
b926dc8c5fd05357caea2ca90b88fe0fb95256eb
|
[
"Ruby"
] | 2
|
Ruby
|
dramagods/kuztus
|
78ebd39fa40a739698752ffebf5e93224c0768fe
|
bbeb19ac1083475e53c53e9bc4cfb0cf50aeb304
|
refs/heads/master
|
<file_sep>//! Bron-Kerbosch algorithm with pivot of highest degree (IK_GP)
use super::bron_kerbosch_pivot::{explore_with_pivot, PivotChoice};
use super::graph::{UndirectedGraph, VertexSetLike};
use super::reporter::Reporter;
pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
explore_with_pivot(graph, reporter, PivotChoice::Arbitrary)
}
<file_sep>#pragma once
#include "BronKerboschStudy/pch.h"
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
<file_sep>// Bron-Kerbosch algorithm with degeneracy ordering,
// parametrized by the way nested searches choose a pivot.
using BronKerbosch;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
internal static class BronKerboschDegeneracy<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter, PivotChoice pivotChoice)
{
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
var excluded = VertexSetMgr.EmptyWithCapacity(graph.Order);
foreach (var v in Degeneracy<VertexSet, VertexSetMgr>.Ordering(graph, drop: 1))
{
var neighbours = graph.Neighbours(v);
Debug.Assert(neighbours.Any());
var neighbouringExcluded = VertexSetMgr.Intersection(excluded, neighbours);
if (neighbouringExcluded.Count() < neighbours.Count())
{
var neighbouringCandidates = VertexSetMgr.Difference(neighbours, neighbouringExcluded);
Pivot<VertexSet, VertexSetMgr>.Visit(graph, reporter, pivotChoice,
neighbouringCandidates, neighbouringExcluded,
ImmutableArray.Create(v));
}
var added = VertexSetMgr.Add(excluded, v);
Debug.Assert(added);
}
}
}
<file_sep>#pragma once
#include <list>
#include <vector>
#include "Vertex.h"
namespace BronKerbosch {
using VertexList = std::vector<Vertex>;
using CliqueList = std::list<VertexList>;
}
<file_sep>pub use super::vertex::{Vertex, VertexMap};
pub use super::vertexsetlike::VertexSetLike;
pub trait UndirectedGraph: Sync {
type VertexSet: VertexSetLike;
fn order(&self) -> usize;
fn size(&self) -> usize;
fn degree(&self, node: Vertex) -> usize;
fn neighbours(&self, node: Vertex) -> &Self::VertexSet;
}
pub trait NewableUndirectedGraph<VertexSet>: UndirectedGraph<VertexSet = VertexSet> {
fn new(adjacencies: Adjacencies<VertexSet>) -> Self;
}
pub fn connected_vertices<Graph>(g: &Graph) -> Graph::VertexSet
where
Graph: UndirectedGraph,
{
(0..g.order())
.map(Vertex::new)
.filter(|&v| g.degree(v) > 0)
.collect()
}
pub type Adjacencies<VertexSet> = VertexMap<VertexSet>;
pub fn are_valid_adjacencies<VertexSet>(adjacencies: &Adjacencies<VertexSet>) -> bool
where
VertexSet: VertexSetLike,
{
adjacencies
.iter()
.all(|(v, neighbours)| neighbours.all(|&w| w != v && adjacencies[w].contains(v)))
// adjacencies[w] confirms w is a valid index
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace BronKerbosch
{
public interface IVertexSetMgr<TSet>
{
static abstract string Name();
static abstract TSet Empty();
static abstract TSet EmptyWithCapacity(int capacity);
static abstract TSet From(IEnumerable<Vertex> vertices);
static abstract bool Add(TSet s, Vertex v);
static abstract bool Remove(TSet s, Vertex v);
static abstract Vertex PopArbitrary(TSet s);
static abstract TSet Difference(TSet s1, TSet s2);
static abstract TSet Intersection(TSet s1, TSet s2);
static abstract int IntersectionSize(TSet s1, TSet s2);
static abstract bool Overlaps(TSet s1, TSet s2);
}
public record struct HashSetMgr : IVertexSetMgr<HashSet<Vertex>>
{
public static string Name() => "HashSet";
public static HashSet<Vertex> Empty() => new();
public static HashSet<Vertex> EmptyWithCapacity(int capacity) => new(capacity: capacity);
public static HashSet<Vertex> From(IEnumerable<Vertex> vertices) => new(vertices);
public static bool Add(HashSet<Vertex> s, Vertex v) => s.Add(v);
public static bool Remove(HashSet<Vertex> s, Vertex v) => s.Remove(v);
public static Vertex PopArbitrary(HashSet<Vertex> s)
{
using var en = s.GetEnumerator();
var ok = en.MoveNext();
Debug.Assert(ok);
ok = s.Remove(en.Current);
Debug.Assert(ok);
return en.Current;
}
public static HashSet<Vertex> Difference(HashSet<Vertex> s1, HashSet<Vertex> s2)
{
var result = new HashSet<Vertex>(capacity: s1.Count);
foreach (var v in s1)
{
if (!s2.Contains(v))
{
var added = result.Add(v);
Debug.Assert(added);
}
}
return result;
// much slower: s1.Except(s2).ToHashSet();
}
public static HashSet<Vertex> Intersection(HashSet<Vertex> s1, HashSet<Vertex> s2)
{
if (s1.Count > s2.Count)
{
return Intersection(s2, s1);
}
var result = new HashSet<Vertex>(capacity: Math.Min(s1.Count, s2.Count));
foreach (var v in s1)
{
if (s2.Contains(v))
{
var added = result.Add(v);
Debug.Assert(added);
}
}
return result;
// much slower: return s2.Intersect(s1).ToHashSet();
// even slower: return s1.Intersect(s2).ToHashSet();
}
public static int IntersectionSize(HashSet<Vertex> s1, HashSet<Vertex> s2)
{
if (s1.Count > s2.Count)
{
return IntersectionSize(s2, s1);
}
return s1.Count(s2.Contains);
// wee bit slower: return s1.Where(v => s2.Contains(v)).Cardinality();
// much slower: return s2.Intersect(s1).Cardinality();
// even slower: return s1.Intersect(s2).Cardinality();
}
public static bool Overlaps(HashSet<Vertex> s1, HashSet<Vertex> s2)
{
if (s1.Count > s2.Count)
return s1.Overlaps(s2);
else
return s2.Overlaps(s1);
}
}
public record struct SortedSetMgr : IVertexSetMgr<SortedSet<Vertex>>
{
public static string Name() => "SortedSet";
public static SortedSet<Vertex> Empty() => new();
public static SortedSet<Vertex> EmptyWithCapacity(int capacity) => new();
public static SortedSet<Vertex> From(IEnumerable<Vertex> vertices) => new(vertices);
public static bool Add(SortedSet<Vertex> s, Vertex v) => s.Add(v);
public static bool Remove(SortedSet<Vertex> s, Vertex v) => s.Remove(v);
public static Vertex PopArbitrary(SortedSet<Vertex> s)
{
using var en = s.GetEnumerator();
var ok = en.MoveNext();
Debug.Assert(ok);
ok = s.Remove(en.Current);
Debug.Assert(ok);
return en.Current;
}
public static SortedSet<Vertex> Difference(SortedSet<Vertex> s1, SortedSet<Vertex> s2)
{
var result = new SortedSet<Vertex>();
foreach (var v in s1)
{
if (!s2.Contains(v))
{
var added = result.Add(v);
Debug.Assert(added);
}
}
return result;
}
public static SortedSet<Vertex> Intersection(SortedSet<Vertex> s1, SortedSet<Vertex> s2)
{
if (s1.Count > s2.Count)
{
return Intersection(s2, s1);
}
var result = new SortedSet<Vertex>();
foreach (var v in s1)
{
if (s2.Contains(v))
{
var added = result.Add(v);
Debug.Assert(added);
}
}
return result;
}
public static int IntersectionSize(SortedSet<Vertex> s1, SortedSet<Vertex> s2)
{
if (s1.Count > s2.Count)
{
return IntersectionSize(s2, s1);
}
return s1.Count(s2.Contains);
}
public static bool Overlaps(SortedSet<Vertex> s1, SortedSet<Vertex> s2)
{
if (s1.Count > s2.Count)
return s1.Overlaps(s2);
else
return s2.Overlaps(s1);
}
}
}
<file_sep>use super::graph::{NewableUndirectedGraph, Vertex, VertexMap, VertexSetLike};
use super::reporters::CollectingReporter;
use super::slimgraph::SlimUndirectedGraph;
use super::*;
pub struct TestData {
name: &'static str,
adjacencies: Vec<Vec<usize>>,
cliques: Vec<Vec<usize>>,
}
fn verticise(vertex_indices: &Vec<usize>) -> Vec<Vertex> {
vertex_indices.iter().copied().map(Vertex::new).collect()
}
impl TestData {
pub fn run<VertexSet: VertexSetLike>(&self) {
let adjacencies = VertexMap::from_iter(self.adjacencies.iter().map(verticise));
let graph = SlimUndirectedGraph::new(adjacencies);
let expected = order_cliques(self.cliques.iter().map(verticise));
for (func_index, func_name) in FUNC_NAMES.iter().enumerate() {
let mut reporter = CollectingReporter::default();
explore(func_index, &graph, &mut reporter);
let cliques = order_cliques(reporter.cliques.into_iter());
assert_eq!(cliques, expected, "for {} on {}", func_name, self.name);
}
}
}
pub fn all_test_data() -> Vec<TestData> {
vec![
TestData {
name: "order_0",
adjacencies: vec![],
cliques: vec![],
},
TestData {
name: "order_1",
adjacencies: vec![vec![]],
cliques: vec![],
},
TestData {
name: "order_2_isolated",
adjacencies: vec![vec![], vec![]],
cliques: vec![],
},
TestData {
name: "2_connected",
adjacencies: vec![vec![1], vec![0]],
cliques: vec![vec![0, 1]],
},
TestData {
name: "order_3_size_1_left",
adjacencies: vec![vec![1], vec![0], vec![]],
cliques: vec![vec![0, 1]],
},
TestData {
name: "order_3_size_1_long",
adjacencies: vec![vec![2], vec![], vec![0]],
cliques: vec![vec![0, 2]],
},
TestData {
name: "order_3_size_1_right",
adjacencies: vec![vec![], vec![2], vec![1]],
cliques: vec![vec![1, 2]],
},
TestData {
name: "order_3_size_2",
adjacencies: vec![vec![1], vec![0, 2], vec![1]],
cliques: vec![vec![0, 1], vec![1, 2]],
},
TestData {
name: "order_3_size_3",
adjacencies: vec![vec![1, 2], vec![0, 2], vec![0, 1]],
cliques: vec![vec![0, 1, 2]],
},
TestData {
name: "order_4_size_2",
adjacencies: vec![vec![1], vec![0], vec![3], vec![2]],
cliques: vec![vec![0, 1], vec![2, 3]],
},
TestData {
name: "order_4_size_3_bus",
adjacencies: vec![vec![1], vec![0, 2], vec![1, 3], vec![2]],
cliques: vec![vec![0, 1], vec![1, 2], vec![2, 3]],
},
TestData {
name: "order_4_size_3_star",
adjacencies: vec![vec![1, 2, 3], vec![0], vec![0], vec![0]],
cliques: vec![vec![0, 1], vec![0, 2], vec![0, 3]],
},
TestData {
name: "order_4_size_4_p",
adjacencies: vec![vec![1], vec![0, 2, 3], vec![1, 3], vec![1, 2]],
cliques: vec![vec![0, 1], vec![1, 2, 3]],
},
TestData {
name: "order_4_size_4_square",
adjacencies: vec![vec![1, 3], vec![0, 2], vec![1, 3], vec![0, 2]],
cliques: vec![vec![0, 1], vec![0, 3], vec![1, 2], vec![2, 3]],
},
TestData {
name: "order_4_size_5",
adjacencies: vec![vec![1, 2, 3], vec![0, 2], vec![0, 1, 3], vec![0, 2]],
cliques: vec![vec![0, 1, 2], vec![0, 2, 3]],
},
TestData {
name: "order_4_size_6",
adjacencies: vec![vec![1, 2, 3], vec![0, 2, 3], vec![0, 1, 3], vec![0, 1, 2]],
cliques: vec![vec![0, 1, 2, 3]],
},
TestData {
name: "order_5_penultimate",
adjacencies: vec![
vec![1, 2, 3, 4],
vec![0, 2, 3, 4],
vec![0, 1, 3, 4],
vec![0, 1, 2],
vec![0, 1, 2],
],
cliques: vec![vec![0, 1, 2, 3], vec![0, 1, 2, 4]],
},
TestData {
name: "sample",
adjacencies: vec![
vec![],
vec![2, 3, 4],
vec![1, 3, 4, 5],
vec![1, 2, 4, 5],
vec![1, 2, 3],
vec![2, 3, 6, 7],
vec![5, 7],
vec![5, 6],
],
cliques: vec![vec![1, 2, 3, 4], vec![2, 3, 5], vec![5, 6, 7]],
},
TestData {
name: "bigger",
adjacencies: vec![
vec![1, 2, 3, 4, 6, 7],
vec![0, 3, 6, 7, 8, 9],
vec![0, 3, 5, 7, 8, 9],
vec![0, 1, 2, 4, 9],
vec![0, 3, 6, 7, 9],
vec![2, 6],
vec![0, 1, 4, 5, 9],
vec![0, 1, 2, 4, 9],
vec![1, 2],
vec![1, 2, 3, 4, 6, 7],
],
cliques: vec![
vec![0, 1, 3],
vec![0, 1, 6],
vec![0, 1, 7],
vec![0, 2, 3],
vec![0, 2, 7],
vec![0, 3, 4],
vec![0, 4, 6],
vec![0, 4, 7],
vec![1, 3, 9],
vec![1, 6, 9],
vec![1, 7, 9],
vec![1, 8],
vec![2, 3, 9],
vec![2, 5],
vec![2, 7, 9],
vec![2, 8],
vec![3, 4, 9],
vec![4, 6, 9],
vec![4, 7, 9],
vec![5, 6],
],
},
]
}
<file_sep>//! Core of Bron-Kerbosch algorithms using degeneracy ordering and multiple threads.
use super::bron_kerbosch_pivot::visit;
pub use super::bron_kerbosch_pivot::PivotChoice;
use super::graph::{UndirectedGraph, Vertex, VertexSetLike};
use super::graph_degeneracy::degeneracy_ordering;
use super::pile::Pile;
use super::reporter::{Clique, Reporter};
use crossbeam_channel::{Receiver, Sender};
pub fn explore_with_pivot_multithreaded<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
pivot_selection: PivotChoice,
num_visiting_threads: usize,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
crossbeam::thread::scope(|scope| {
let (start_tx, start_rx) = crossbeam_channel::bounded(64);
let (visit_tx, visit_rx) = crossbeam_channel::bounded(64);
let (reporter_tx, reporter_rx) = crossbeam_channel::bounded(64);
scope.spawn(move |_| initiate(graph, start_tx));
scope.spawn(move |_| dispatch(graph, start_rx, visit_tx));
for _ in 0..num_visiting_threads {
let thread_visit_rx = visit_rx.clone();
let thread_reporter_tx = reporter_tx.clone();
scope.spawn(move |_| {
descend(graph, pivot_selection, thread_visit_rx, thread_reporter_tx)
});
}
drop(visit_rx);
drop(reporter_tx);
while let Ok(clique) = reporter_rx.recv() {
reporter.record(clique);
}
})
.unwrap();
}
struct VisitJob<VertexSet> {
start: Vertex,
candidates: VertexSet,
excluded: VertexSet,
}
fn initiate<VertexSet, Graph>(graph: &Graph, start_tx: Sender<Vertex>)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
{
for vertex in degeneracy_ordering(graph, -1) {
start_tx.send(vertex).unwrap();
}
}
fn dispatch<VertexSet, Graph>(
graph: &Graph,
start_rx: Receiver<Vertex>,
visit_tx: Sender<VisitJob<VertexSet>>,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
{
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
let mut excluded = VertexSet::with_capacity(graph.order());
while let Ok(v) = start_rx.recv() {
let neighbours = graph.neighbours(v);
debug_assert!(!neighbours.is_empty());
let neighbouring_excluded: VertexSet = neighbours.intersection_collect(&excluded);
if neighbouring_excluded.len() < neighbours.len() {
let neighbouring_candidates: VertexSet =
neighbours.difference_collect(&neighbouring_excluded);
let visit = VisitJob {
start: v,
candidates: neighbouring_candidates,
excluded: neighbouring_excluded,
};
visit_tx.send(visit).unwrap();
}
excluded.insert(v);
}
}
fn descend<VertexSet, Graph>(
graph: &Graph,
pivot_selection: PivotChoice,
visit_rx: Receiver<VisitJob<VertexSet>>,
report_tx: Sender<Clique>,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
{
struct SendingReporter(Sender<Clique>);
impl Reporter for SendingReporter {
fn record(&mut self, clique: Clique) {
self.0.send(clique).unwrap();
}
}
let mut reporter = SendingReporter(report_tx);
while let Ok(job) = visit_rx.recv() {
visit(
graph,
&mut reporter,
pivot_selection,
job.candidates,
job.excluded,
Some(&Pile::from(job.start)),
);
}
}
<file_sep>#[derive(Clone, Default)]
pub struct SampleStatistics<T> {
max: T,
min: T,
samples: u32,
sum: f64,
sum_of_squares: f64,
}
impl<T> SampleStatistics<T>
where
T: Copy + PartialOrd + std::ops::Sub,
f64: std::convert::From<T>,
f64: std::convert::From<<T as std::ops::Sub>::Output>,
{
pub fn is_empty(&self) -> bool {
self.samples == 0
}
pub fn put(&mut self, v: T) {
let vf = f64::from(v);
if self.is_empty() {
self.min = v;
self.max = v;
} else if self.min > v {
self.min = v;
} else if self.max < v {
self.max = v;
}
self.samples += 1;
self.sum += vf;
self.sum_of_squares += vf.powi(2);
}
pub fn max(&self) -> T {
self.max
}
pub fn min(&self) -> T {
self.min
}
pub fn mean(&self) -> f64 {
if self.samples < 1 {
std::f64::NAN
} else {
let r = self.sum / (self.samples as f64);
r.clamp(self.min.into(), self.max.into())
}
}
pub fn variance(&self) -> f64 {
if self.samples < 2 {
std::f64::NAN
} else if self.min == self.max {
0.
} else {
let n = self.samples as f64;
let r = (self.sum_of_squares - self.sum.powi(2) / n) / (n - 1.);
r.max(0.)
}
}
pub fn deviation(&self) -> f64 {
let r = self.variance().sqrt();
if r.is_nan() {
r
} else {
r.min((self.max - self.min).into())
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::float_cmp)]
use super::*;
#[test]
fn stats_0_i32() {
let s: SampleStatistics<i32> = Default::default();
assert!(s.mean().is_nan());
assert!(s.variance().is_nan());
assert!(s.deviation().is_nan());
}
#[test]
fn stats_1_i32() {
let mut s: SampleStatistics<i32> = Default::default();
s.put(-1);
assert_eq!(s.mean(), -1.0);
assert!(s.variance().is_nan());
assert!(s.deviation().is_nan());
}
#[test]
fn stats_2_i32() {
let mut s: SampleStatistics<i32> = Default::default();
s.put(-1);
s.put(1);
assert_eq!(s.mean(), 0.0);
assert_eq!(s.variance(), 2.0);
assert_eq!(s.deviation(), 2.0_f64.sqrt());
}
#[test]
fn stats_3_i32() {
let mut s: SampleStatistics<i32> = Default::default();
s.put(89);
s.put(90);
s.put(91);
assert_eq!(s.mean(), 90.0);
assert_eq!(s.variance(), 1.0);
assert_eq!(s.deviation(), 1.0);
}
#[test]
fn stats_9_u32() {
let mut s: SampleStatistics<u32> = Default::default();
s.put(2);
s.put(4);
s.put(4);
s.put(4);
s.put(5);
s.put(5);
s.put(5);
s.put(7);
s.put(9);
assert_eq!(s.mean(), 5.0);
assert_eq!(s.variance(), 4.0);
assert_eq!(s.deviation(), 2.0);
}
#[test]
fn stats_2_f64() {
let mut s: SampleStatistics<f64> = Default::default();
s.put(1.0);
s.put(2.0);
assert_eq!(s.mean(), 1.5);
assert_eq!(s.variance(), 0.5);
assert_eq!(s.deviation(), 0.5_f64.sqrt());
}
}
#[cfg(all(test, not(miri)))]
mod proptests {
use super::*;
use proptest::prelude::*;
proptest! {
#[test]
fn put_1_u32(x in proptest::num::u32::ANY) {
let mut s: SampleStatistics<u32> = Default::default();
s.put(x);
assert!(s.mean() == x.into());
}
#[test]
fn put_1_f64(x in proptest::num::f64::NORMAL) {
let mut s: SampleStatistics<f64> = Default::default();
s.put(x);
assert!(s.mean() == x.into());
}
#[test]
fn put_2_u32(x in proptest::num::u32::ANY, y in proptest::num::u32::ANY) {
let mut s: SampleStatistics<u32> = Default::default();
s.put(x);
s.put(y);
assert!(s.mean() >= s.min().into());
assert!(s.mean() <= s.max().into());
assert!(s.variance() >= 0.);
assert!(s.deviation() <= (s.max() - s.min()).into());
}
#[test]
fn put_2_f64(x in proptest::num::f64::NORMAL, y in proptest::num::f64::NORMAL) {
let mut s: SampleStatistics<f64> = Default::default();
s.put(x);
s.put(y);
assert!(s.mean() >= s.min());
assert!(s.mean() <= s.max());
assert!(s.variance() >= 0.);
assert!(s.deviation() <= (s.max() - s.min()) * 1.5);
}
#[test]
fn put_n_u32(i in 2..99, x in proptest::num::u32::ANY) {
let mut s: SampleStatistics<u32> = Default::default();
for _ in 0..i {
s.put(x);
}
assert!(s.mean() >= s.min().into());
assert!(s.mean() <= s.max().into());
assert!(s.variance() >= 0.);
assert!(s.deviation() <= (s.max() - s.min()).into());
}
#[test]
fn put_n_f64(i in 2..99, x in proptest::num::f64::NORMAL) {
let mut s: SampleStatistics<f64> = Default::default();
for _ in 0..i {
s.put(x);
}
assert!(s.mean() >= s.min());
assert!(s.mean() <= s.max());
assert!(s.variance() >= 0.);
assert!(s.deviation() <= (s.max() - s.min()));
}
}
}
<file_sep>package BronKerbosch
func bronKerbosch2aGP(graph *UndirectedGraph, reporter Reporter) {
// Bron-Kerbosch algorithm with pivot of highest degree within remaining candidates
// chosen from candidates only (IK_GP).
candidates := graph.connectedVertices()
if candidates.IsEmpty() {
return
}
excluded := make(VertexSet, len(candidates))
visit(graph, reporter, MaxDegreeLocal, candidates, excluded, nil)
}
<file_sep>package BronKerbosch
type VertexVisitor interface {
visit(Vertex)
Close()
}
type SimpleVertexVisitor struct {
vertices []Vertex
}
type ChannelVertexVisitor struct {
vertices chan<- Vertex
}
func (g *SimpleVertexVisitor) visit(v Vertex) {
g.vertices = append(g.vertices, v)
}
func (g *SimpleVertexVisitor) Close() {
}
func (g *ChannelVertexVisitor) visit(v Vertex) {
g.vertices <- v
}
func (g *ChannelVertexVisitor) Close() {
close(g.vertices)
}
func degeneracyOrdering(graph *UndirectedGraph, visitor VertexVisitor, drop int) {
if drop > 0 {
panic("expecting negative drop value")
}
defer func() { visitor.Close() }()
order := graph.Order()
// Possible values of priorityPerNode:
// -1: when yielded
// 0..maxDegree: candidates still queued with priority (degree - #of yielded neighbours)
priorityPerNode := make([]int, order)
maxDegree := 0
numLeftToVisit := 0
for c := 0; c < order; c++ {
degree := graph.degree(Vertex(c))
if degree > 0 {
priorityPerNode[Vertex(c)] = degree
if maxDegree < degree {
maxDegree = degree
}
numLeftToVisit++
}
}
numLeftToVisit += drop
if numLeftToVisit <= 0 {
return
}
var q priorityQueue[Vertex]
q.init(maxDegree)
for c, p := range priorityPerNode {
if p > 0 {
q.put(p, Vertex(c))
}
}
for {
i := q.pop()
for priorityPerNode[i] == -1 {
// was requeued with a more urgent priority and therefore already visited
i = q.pop()
}
visitor.visit(i)
numLeftToVisit--
if numLeftToVisit == 0 {
return
}
priorityPerNode[i] = -1
for v := range graph.neighbours(i) {
p := priorityPerNode[v]
if p != -1 {
// Requeue with a more urgent priority, but don't bother to remove
// the original entry - it will be skipped if it's reached at all.
priorityPerNode[v] = p - 1
q.put(p-1, v)
}
}
}
}
type priorityQueue [T interface{}] struct {
stackPerPriority [][]T
}
func (q *priorityQueue[T]) init(maxPriority int) {
q.stackPerPriority = make([][]T, maxPriority+1)
}
func (q *priorityQueue[T]) put(priority int, element T) {
q.stackPerPriority[priority] = append(q.stackPerPriority[priority], element)
}
func (q *priorityQueue[T]) pop() T {
for p := 0; ; p++ {
l := len(q.stackPerPriority[p])
if l > 0 {
last := q.stackPerPriority[p][l-1]
q.stackPerPriority[p] = q.stackPerPriority[p][:l-1]
return last
}
}
}
<file_sep>use super::graph::{UndirectedGraph, Vertex, VertexMap, VertexSetLike};
use std::iter::FusedIterator;
pub fn degeneracy_ordering<Graph>(graph: &Graph, drop: isize) -> DegeneracyOrderIter<Graph>
where
Graph: UndirectedGraph,
{
debug_assert!(drop <= 0);
let order = graph.order();
let mut priority_per_vertex: VertexMap<Option<Priority>> = VertexMap::new(None, order);
let mut max_priority: Option<Priority> = None;
let mut num_candidates: isize = 0;
for c in 0..order {
let c = Vertex::new(c);
let degree = graph.degree(c);
if degree > 0 {
let priority = Priority::new(degree + 1);
priority_per_vertex[c] = priority;
max_priority = max_priority.iter().copied().chain(priority).max();
debug_assert!(max_priority.is_some());
num_candidates += 1;
}
}
let mut queue = PriorityQueue::new(max_priority);
for c in 0..order {
let c = Vertex::new(c);
if let Some(priority) = priority_per_vertex[c] {
queue.put(priority, c);
}
}
DegeneracyOrderIter {
graph,
priority_per_vertex,
queue,
num_left_to_pick: num_candidates + drop,
}
}
type Priority = std::num::NonZeroUsize;
struct PriorityQueue<T> {
stack_per_priority: Vec<Vec<T>>,
}
impl<T> PriorityQueue<T>
where
T: Copy + Eq,
{
fn new(max_priority: Option<Priority>) -> Self {
PriorityQueue {
stack_per_priority: match max_priority {
None => vec![],
Some(max_priority) => vec![vec![]; max_priority.get()],
},
}
}
fn put(&mut self, priority: Priority, element: T) {
self.stack_per_priority[priority.get() - 1].push(element);
}
fn pop(&mut self) -> Option<T> {
for stack in &mut self.stack_per_priority {
if let Some(element) = stack.pop() {
return Some(element);
}
}
None
}
#[allow(clippy::nonminimal_bool)]
fn contains(&self, priority: Priority, element: T) -> bool {
if !(cfg!(debug_assertions)) {
panic!("not suitable for use in release code")
}
self.stack_per_priority[priority.get() - 1].contains(&element)
}
}
pub struct DegeneracyOrderIter<'a, Graph> {
graph: &'a Graph,
priority_per_vertex: VertexMap<Option<Priority>>,
// If priority is None, vertex was already picked or was always irrelevant (unconnected);
// otherwise, vertex is still queued and priority = degree - number of picked neighbours +1.
// +1 because we want the priority number to be NonZero to allow free wrapping inside Option.
queue: PriorityQueue<Vertex>,
num_left_to_pick: isize,
}
impl<'a, Graph> DegeneracyOrderIter<'a, Graph> {
fn pick_with_lowest_degree(&mut self) -> Vertex {
debug_assert!(self.priority_per_vertex.iter().all(|(v, &p)| match p {
None => true, // might still be in some stack
Some(p) => self.queue.contains(p, v),
}));
loop {
let v = self.queue.pop().expect("Cannot pop more than has been put");
if self.priority_per_vertex[v].is_some() {
self.priority_per_vertex[v] = None;
return v;
}
// else v was requeued with a more urgent priority and therefore already picked
}
}
}
impl<'a, Graph> FusedIterator for DegeneracyOrderIter<'a, Graph> where Graph: UndirectedGraph {}
impl<'a, Graph> Iterator for DegeneracyOrderIter<'a, Graph>
where
Graph: UndirectedGraph,
{
type Item = Vertex;
fn next(&mut self) -> Option<Vertex> {
if self.num_left_to_pick > 0 {
self.num_left_to_pick -= 1;
let i = self.pick_with_lowest_degree();
self.graph.neighbours(i).for_each(|v| {
if let Some(old_priority) = self.priority_per_vertex[v] {
// Since this is an unvisited neighbour of a vertex just being picked,
// its priority can't be down to the minimum.
let new_priority = Priority::new(old_priority.get() - 1);
debug_assert!(new_priority.is_some());
// Requeue with a more urgent priority, but don't bother to remove
// the original entry - it will be skipped if it's reached at all.
self.priority_per_vertex[v] = new_priority;
self.queue.put(new_priority.unwrap(), v);
}
});
Some(i)
} else {
None
}
}
}
<file_sep>//! Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
//! choosing a pivot from candidates only (IK_GP)
#pragma once
#include "BronKerboschDegeneracy.h"
namespace BronKerbosch {
class BronKerbosch3GP {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph) {
return BronKerboschDegeneracy::explore<Reporter>(graph, PivotChoice::MaxDegreeLocal);
}
};
}
<file_sep>use super::graph::{
are_valid_adjacencies, Adjacencies, NewableUndirectedGraph, UndirectedGraph, Vertex,
VertexSetLike,
};
#[derive(Debug)]
pub struct SlimUndirectedGraph<VertexSet: VertexSetLike> {
adjacencies: Adjacencies<VertexSet>,
}
impl<VertexSet: VertexSetLike> UndirectedGraph for SlimUndirectedGraph<VertexSet> {
type VertexSet = VertexSet;
fn order(&self) -> usize {
self.adjacencies.len()
}
fn size(&self) -> usize {
let total: usize = self.adjacencies.iter().map(|(_, a)| a.len()).sum();
assert!(total % 2 == 0);
total / 2
}
fn degree(&self, node: Vertex) -> usize {
self.neighbours(node).len()
}
fn neighbours(&self, node: Vertex) -> &VertexSet {
&self.adjacencies[node]
}
}
impl<VertexSet> NewableUndirectedGraph<VertexSet> for SlimUndirectedGraph<VertexSet>
where
VertexSet: VertexSetLike,
{
fn new(adjacencies: Adjacencies<VertexSet>) -> Self {
debug_assert!(are_valid_adjacencies(&adjacencies));
SlimUndirectedGraph { adjacencies }
}
}
<file_sep>//! Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
//! choosing a pivot from candidates only (IK_GP)
//! implemented by multiple threads
use super::bron_kerbosch_degen_mt::{explore_with_pivot_multithreaded, PivotChoice};
use super::graph::{UndirectedGraph, VertexSetLike};
use super::reporter::Reporter;
pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
const NUM_VISITING_THREADS: usize = 5;
explore_with_pivot_multithreaded(
graph,
reporter,
PivotChoice::MaxDegreeLocal,
NUM_VISITING_THREADS,
)
}
<file_sep>package StudyIO
import (
"fmt"
)
func ParsePositiveInt(str string) (int, error) {
var val int
var suffix rune
n, err := fmt.Sscanf(str, "%d%c", &val, &suffix)
if n == 1 {
return val, nil // ignore EOF error
}
if err == nil {
if suffix == 'k' {
return val * 1e3, nil
}
if suffix == 'M' {
return val * 1e6, nil
}
err = fmt.Errorf("Unknown suffix \"%c\"", suffix)
}
return val, err
}
<file_sep>//! Bron-Kerbosch algorithm with pivot of highest degree towards the remaining candidates (IK_GPX)
use super::bron_kerbosch_pivot::{explore_with_pivot, PivotChoice};
use super::graph::{UndirectedGraph, VertexSetLike};
use super::reporter::Reporter;
pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
explore_with_pivot(graph, reporter, PivotChoice::MaxDegreeLocalX)
}
<file_sep># coding: utf-8
from random_graph import random_undirected_graph
import random
def test_random_graph() -> None:
random.seed(19680516)
random_undirected_graph(order=2, size=0)
random_undirected_graph(order=3, size=0)
random_undirected_graph(order=3, size=1)
random_undirected_graph(order=3, size=2)
random_undirected_graph(order=4, size=0)
random_undirected_graph(order=4, size=1)
random_undirected_graph(order=4, size=2)
random_undirected_graph(order=4, size=3)
random_undirected_graph(order=4, size=4)
random_undirected_graph(order=4, size=5)
<file_sep>use anyhow::{anyhow, Context, Result};
use bron_kerbosch::{Adjacencies, NewableUndirectedGraph, Vertex, VertexSetLike};
use std::fmt::Write;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Copy)]
pub enum Size {
Of(usize),
}
pub fn parse_positive_int(value: &str) -> usize {
let (numstr, factor) = if let Some(megas) = value.strip_suffix('M') {
(megas, 1_000_000)
} else if let Some(kilos) = value.strip_suffix('k') {
(kilos, 1_000)
} else {
(value, 1)
};
let num: usize = numstr
.parse()
.unwrap_or_else(|err| panic!("{numstr} is not a positive integer ({err})"));
num * factor
}
fn locator(path: &Path, line_num: usize) -> String {
let mut locator = format!("In file {}", path.display());
if line_num > 0 {
write!(locator, " on line {line_num}").ok();
}
locator
}
fn read_edges<VertexSet>(path: &Path, orderstr: &str, size: usize) -> Result<Adjacencies<VertexSet>>
where
VertexSet: VertexSetLike + Clone,
{
let order = parse_positive_int(orderstr);
let mut adjacencies = Adjacencies::new(VertexSet::new(), order);
let context = |line_num| {
move || {
format!(
"{}\nPerhaps (re)generate with `python -m random_graph {orderstr} <max_size?>`",
locator(path, line_num)
)
}
};
let f = File::open(path).with_context(context(0))?;
let reader = BufReader::new(f);
let mut line_num = 0;
for line_result in reader.lines().take(size) {
line_num += 1;
let line = line_result.with_context(context(line_num))?;
let mut split = line.split(' ');
let v = split.next().expect("at least an empty string");
let w = split
.next()
.ok_or_else(|| anyhow!("Missing 2nd field"))
.with_context(context(line_num))?;
let v = Vertex::new(v.parse().with_context(context(line_num))?);
let w = Vertex::new(w.parse().with_context(context(line_num))?);
debug_assert_ne!(v, w);
debug_assert!(!adjacencies[v].contains(w));
debug_assert!(!adjacencies[w].contains(v));
adjacencies[v].insert(w);
adjacencies[w].insert(v);
}
if line_num < size {
return Err(anyhow!("Exhausted generated list of edges")).with_context(context(line_num));
}
Ok(adjacencies)
}
fn read_clique_count(path: &Path, orderstr: &str, size: usize) -> Result<Option<usize>> {
let f = File::open(path).with_context(|| locator(path, 0))?;
let reader = BufReader::new(f);
let context = |line_num| move || locator(path, line_num);
let prefix = format!("{orderstr}\t{size}\t");
for (line_idx, line_result) in reader.lines().enumerate().skip(1) {
let line = line_result.with_context(context(line_idx + 1))?;
if line.starts_with(&prefix) {
let c: usize = line[prefix.len()..]
.parse()
.with_context(context(line_idx + 1))?;
return Ok(Some(c));
}
}
Ok(None)
}
pub fn read_undirected<VertexSet, G>(orderstr: &str, size: Size) -> Result<(G, Option<usize>)>
where
VertexSet: VertexSetLike + Clone,
G: NewableUndirectedGraph<VertexSet>,
{
let order = parse_positive_int(orderstr);
assert!(order > 0);
let Size::Of(size) = size;
let fully_meshed_size = order * (order - 1) / 2;
if size > fully_meshed_size {
return Err(anyhow!(
"{} nodes accommodate at most {} edges",
order,
fully_meshed_size
));
}
let edges_name = &format!("random_edges_order_{orderstr}.txt");
let stats_name = "random_stats.txt";
let edges_pbuf: PathBuf = ["..", "data", edges_name].iter().collect();
let stats_pbuf: PathBuf = ["..", "data", stats_name].iter().collect();
let adjacencies = read_edges(edges_pbuf.as_path(), orderstr, size)?;
let clique_count = read_clique_count(stats_pbuf.as_path(), orderstr, size)?;
let g = G::new(adjacencies);
assert_eq!(g.order(), order);
assert_eq!(g.size(), size);
Ok((g, clique_count))
}
<file_sep>using System.Collections.Immutable;
namespace BronKerbosch
{
public sealed class CountingReporter : IReporter
{
public int Cliques { get; private set; }
public void Record(ImmutableArray<Vertex> clique) => Cliques += 1;
}
}
<file_sep>package BronKerbosch
func bronKerbosch1(graph *UndirectedGraph, reporter Reporter) {
// Naive Bron-Kerbosch algorithm
candidates := graph.connectedVertices()
if candidates.IsEmpty() {
return
}
excluded := make(VertexSet, len(candidates))
bronKerbosch1visit(graph, reporter, candidates, excluded, nil)
}
func bronKerbosch1visit(graph *UndirectedGraph, reporter Reporter,
candidates VertexSet, excluded VertexSet, clique []Vertex) {
for !candidates.IsEmpty() {
v := candidates.PopArbitrary()
neighbours := graph.neighbours(v)
neighbouringCandidates := candidates.Intersection(neighbours)
if !neighbouringCandidates.IsEmpty() {
neighbouringExcluded := excluded.Intersection(neighbours)
bronKerbosch1visit(graph, reporter,
neighbouringCandidates,
neighbouringExcluded,
append(clique, v))
} else if excluded.IsDisjoint(neighbours) {
reporter.Record(append(clique, v))
}
excluded.Add(v)
}
}
<file_sep>package BronKerbosch
type Vertex int
type VertexSet map[Vertex]struct{}
func NewVertexSet(vertices []Vertex) VertexSet {
r := make(VertexSet)
for _, v := range vertices {
r.Add(v)
}
return r
}
func (vset VertexSet) IsEmpty() bool {
return len(vset) == 0
}
func (vset VertexSet) Cardinality() int {
return len(vset)
}
func (vset VertexSet) Contains(v Vertex) bool {
_, ok := vset[v]
return ok
}
func (vset VertexSet) Difference(term VertexSet) VertexSet {
result := make(VertexSet, len(vset))
for v := range vset {
if !term.Contains(v) {
result.Add(v)
}
}
return result
}
func (vset VertexSet) Intersection(other VertexSet) VertexSet {
small, large := vset, other
if len(small) > len(large) {
small, large = other, vset
}
result := make(VertexSet, len(small))
for v := range small {
if large.Contains(v) {
result.Add(v)
}
}
return result
}
func (vset VertexSet) IntersectionLen(other VertexSet) int {
small, large := vset, other
if len(small) > len(large) {
small, large = other, vset
}
result := 0
for v := range small {
if large.Contains(v) {
result++
}
}
return result
}
func (vset VertexSet) IsDisjoint(other VertexSet) bool {
small, large := vset, other
if len(small) > len(large) {
small, large = other, vset
}
for v := range small {
if large.Contains(v) {
return false
}
}
return true
}
func (vset VertexSet) Add(v Vertex) {
vset[v] = struct{}{}
}
func (vset VertexSet) Remove(v Vertex) {
delete(vset, v)
}
func (vset VertexSet) PickArbitrary() Vertex {
for v := range vset {
return v
}
panic("attempt to pick from empty set")
}
func (vset VertexSet) PopArbitrary() Vertex {
for v := range vset {
vset.Remove(v)
return v
}
panic("attempt to pop from empty set")
}
<file_sep>#include "pch.h"
#include "BronKerbosch/GraphDegeneracy.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BronKerbosch {
TEST_CLASS(GraphDegeneracyTest) {
public:
template <typename VertexSet>
void test_empty() {
UndirectedGraph<VertexSet> const g{typename UndirectedGraph<VertexSet>::Adjacencies{}};
Assert::IsFalse(DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g).has_next());
Assert::IsFalse(DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g, -1).has_next());
}
template <typename VertexSet>
void test_pair() {
UndirectedGraph<VertexSet> const g{
typename UndirectedGraph<VertexSet>::Adjacencies{{1u}, {0u}}};
auto it = DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g);
auto first = it.next();
auto second = it.next();
Assert::IsTrue(first.has_value());
Assert::IsTrue(second.has_value());
Assert::IsFalse(it.next().has_value());
Assert::AreEqual(0u, std::min(*first, *second));
Assert::AreEqual(1u, std::max(*first, *second));
auto it1 = DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g, -1);
Assert::IsTrue(first == it1.next());
Assert::IsFalse(it1.next().has_value());
Assert::IsFalse(
DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g, -2).next().has_value());
}
template <typename VertexSet>
void test_split() {
UndirectedGraph<VertexSet> const g{
typename UndirectedGraph<VertexSet>::Adjacencies{{1u}, {0u, 2u}, {1u}}};
auto it = DegeneracyOrderIter<VertexSet>::degeneracy_ordering(g);
Assert::AreNotEqual(1u, *it.next());
Assert::IsTrue(it.next().has_value());
Assert::IsTrue(it.next().has_value());
Assert::IsFalse(it.next().has_value());
}
TEST_METHOD(empty) {
test_empty<std::set<Vertex>>();
test_empty<std::unordered_set<Vertex>>();
}
TEST_METHOD(pair) {
test_pair<std::set<Vertex>>();
test_pair<std::unordered_set<Vertex>>();
}
TEST_METHOD(split) {
test_split<std::set<Vertex>>();
test_split<std::unordered_set<Vertex>>();
}
};
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace BronKerbosch
{
public static class Portfolio
{
public static readonly string[] FuncNames =
{
"Ver1½",
"Ver2-GP", "Ver2½-GP", "Ver2½-GPX",
"Ver3½-GP", "Ver3½-GPX",
"Ver3½=GPc"
};
public static void Explore<TVertexSet, TVertexSetMgr>(int funcIndex, UndirectedGraph<TVertexSet, TVertexSetMgr> graph, IReporter reporter)
where TVertexSet : IEnumerable<Vertex>
where TVertexSetMgr : IVertexSetMgr<TVertexSet>
{
switch (funcIndex)
{
case 0: BronKerbosch1<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 1: BronKerbosch2aGP<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 2: BronKerbosch2bGP<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 3: BronKerbosch2bGPX<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 4: BronKerbosch3GP<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 5: BronKerbosch3GPX<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
case 6: BronKerbosch3ST<TVertexSet, TVertexSetMgr>.Explore(graph, reporter); break;
default: throw new ArgumentException("unknown func_index");
}
}
public static void SortCliques(List<ImmutableArray<Vertex>> cliques)
{
for (var i = 0; i < cliques.Count; ++i)
{
cliques[i] = cliques[i].Sort();
}
cliques.Sort(Comparer);
}
public static void AssertSameCliques(List<ImmutableArray<Vertex>> lhs, List<ImmutableArray<Vertex>> rhs)
{
if (lhs.Count != rhs.Count)
{
throw new ArgumentException($"{lhs.Count} cliques <> {rhs.Count} cliques");
}
for (var i = 0; i < lhs.Count; ++i)
{
if (lhs[i].Length != rhs[i].Length)
{
throw new ArgumentException($"clique #{i + 1}: length {lhs[i].Length} <> length {rhs[i].Length}");
}
for (var j = 0; j < lhs[i].Length; ++j)
{
if (lhs[i][j] != rhs[i][j])
{
throw new ArgumentException($"clique #{i + 1}, vertex #{j + 1}: {lhs[i][j]} <> {rhs[i][j]}");
}
}
}
}
private static int Comparer(ImmutableArray<Vertex> lhs, ImmutableArray<Vertex> rhs)
{
if (Equals(lhs, rhs))
{
// Seriously, Sort sometimes compares an element with itself
return 0;
}
for (var i = 0; i < lhs.Length && i < rhs.Length; ++i)
{
var d = lhs[i].CompareTo(rhs[i]);
if (d != 0)
{
return d;
}
}
throw new ArgumentException(
$"got overlapping or equal cliques (length {lhs.Length} <> length {rhs.Length})");
}
}
}
<file_sep>//! Bron-Kerbosch algorithm with pivot of highest degree (IK_GP)
#pragma once
#include "BronKerboschPivot.h"
namespace BronKerbosch {
class BronKerbosch2GP {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph) {
return BronKerboschPivot::explore<Reporter>(graph, PivotChoice::MaxDegreeLocal);
}
};
}
<file_sep>#include "pch.h"
#include "Util.h"
<file_sep>/// Cheap & simple immutable stack data structure, of which the layers
/// somehow live long enough (e.g. they are on the runtime stack).
/// The only supported change is to add, and the only supported query is to
/// convert to a vector.
pub struct Pile<'a, T> {
top: T,
height: u32,
lower: Option<&'a Pile<'a, T>>,
}
impl<'a, T> Pile<'a, T>
where
T: Clone,
{
fn push_to(&self, result: &mut Vec<T>) {
if let Some(lower) = self.lower {
lower.push_to(result);
}
result.push(self.top.clone());
}
/// Create a pile containing one element
pub fn from(t: T) -> Self {
Pile::on(None, t)
}
/// Create a pile optionally on top of an existing pile
pub fn on(lower: Option<&'a Pile<'a, T>>, top: T) -> Self {
let height = 1 + lower.map_or(0, |pile| pile.height);
Self { top, height, lower }
}
/// Clone contained elements into a vector, in the order they were placed
pub fn collect(self) -> Vec<T> {
let mut result: Vec<T> = Vec::with_capacity(self.height as usize);
self.push_to(&mut result);
debug_assert_eq!(result.len(), self.height as usize);
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pile() {
let p1 = Pile::from(4);
{
let p2 = Pile::on(Some(&p1), 2);
assert_eq!(p2.collect(), vec![4, 2]);
}
assert_eq!(p1.collect(), vec![4]);
}
}
<file_sep>using BronKerbosch;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace BronKerboschUnitTest
{
public class VertexSetTests
{
[Test]
public void PopArbitrary1()
{
HashSet<Vertex> one = new() { Vertex.Nth(1) };
var x = HashSetMgr.PopArbitrary(one).Index();
Assert.AreEqual(x, 1);
Assert.Zero(one.Count);
}
[Test]
public void PopArbitrary2()
{
HashSet<Vertex> two = new() { Vertex.Nth(1), Vertex.Nth(2) };
var x = HashSetMgr.PopArbitrary(two).Index();
var y = HashSetMgr.PopArbitrary(two).Index();
Assert.AreEqual(Math.Min(x, y), 1);
Assert.AreEqual(Math.Max(x, y), 2);
Assert.Zero(two.Count);
}
[Test]
public void Overlaps()
{
HashSet<Vertex> empty = new();
HashSet<Vertex> one = new() { Vertex.Nth(1) };
HashSet<Vertex> two = new() { Vertex.Nth(1), Vertex.Nth(2) };
HashSet<Vertex> six = new() { Vertex.Nth(0), Vertex.Nth(1), Vertex.Nth(2),
Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) };
Assert.That(!HashSetMgr.Overlaps(empty, one));
Assert.That(!HashSetMgr.Overlaps(one, empty));
Assert.That(!HashSetMgr.Overlaps(empty, two));
Assert.That(!HashSetMgr.Overlaps(two, empty));
Assert.That(!HashSetMgr.Overlaps(empty, six));
Assert.That(!HashSetMgr.Overlaps(six, empty));
Assert.That(HashSetMgr.Overlaps(one, two));
Assert.That(HashSetMgr.Overlaps(two, one));
Assert.That(HashSetMgr.Overlaps(one, six));
Assert.That(HashSetMgr.Overlaps(six, one));
Assert.That(HashSetMgr.Overlaps(two, six));
Assert.That(HashSetMgr.Overlaps(six, two));
Assert.That(HashSetMgr.Overlaps(one, one));
Assert.That(HashSetMgr.Overlaps(two, two));
Assert.That(HashSetMgr.Overlaps(six, six));
}
[Test]
public void Intersection()
{
HashSet<Vertex> empty = new();
HashSet<Vertex> one = new() { Vertex.Nth(1) };
HashSet<Vertex> two = new() { Vertex.Nth(1), Vertex.Nth(2) };
HashSet<Vertex> six = new() { Vertex.Nth(0), Vertex.Nth(1), Vertex.Nth(2),
Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) };
Assert.That(HashSetMgr.Intersection(empty, one).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(one, empty).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(empty, two).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(two, empty).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(empty, six).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(six, empty).SetEquals(empty));
Assert.That(HashSetMgr.Intersection(one, two).SetEquals(one));
Assert.That(HashSetMgr.Intersection(two, one).SetEquals(one));
Assert.That(HashSetMgr.Intersection(one, six).SetEquals(one));
Assert.That(HashSetMgr.Intersection(six, one).SetEquals(one));
Assert.That(HashSetMgr.Intersection(two, six).SetEquals(two));
Assert.That(HashSetMgr.Intersection(six, two).SetEquals(two));
Assert.That(HashSetMgr.Intersection(one, one).SetEquals(one));
Assert.That(HashSetMgr.Intersection(two, two).SetEquals(two));
Assert.That(HashSetMgr.Intersection(six, six).SetEquals(six));
}
[Test]
public void IntersectCount()
{
HashSet<Vertex> empty = new();
HashSet<Vertex> one = new() { Vertex.Nth(1) };
HashSet<Vertex> two = new() { Vertex.Nth(1), Vertex.Nth(2) };
HashSet<Vertex> six = new() { Vertex.Nth(0), Vertex.Nth(1), Vertex.Nth(2),
Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) };
Assert.That(HashSetMgr.IntersectionSize(empty, one).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(one, empty).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(empty, two).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(two, empty).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(empty, six).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(six, empty).Equals(0));
Assert.That(HashSetMgr.IntersectionSize(one, two).Equals(1));
Assert.That(HashSetMgr.IntersectionSize(two, one).Equals(1));
Assert.That(HashSetMgr.IntersectionSize(one, six).Equals(1));
Assert.That(HashSetMgr.IntersectionSize(six, one).Equals(1));
Assert.That(HashSetMgr.IntersectionSize(two, six).Equals(2));
Assert.That(HashSetMgr.IntersectionSize(six, two).Equals(2));
Assert.That(HashSetMgr.IntersectionSize(one, one).Equals(1));
Assert.That(HashSetMgr.IntersectionSize(two, two).Equals(2));
Assert.That(HashSetMgr.IntersectionSize(six, six).Equals(6));
}
[Test]
public void Difference()
{
HashSet<Vertex> empty = new();
HashSet<Vertex> one = new() { Vertex.Nth(1) };
HashSet<Vertex> two = new() { Vertex.Nth(1), Vertex.Nth(2) };
HashSet<Vertex> six = new() { Vertex.Nth(0), Vertex.Nth(1), Vertex.Nth(2),
Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) };
Assert.That(HashSetMgr.Difference(empty, one).SetEquals(empty));
Assert.That(HashSetMgr.Difference(empty, two).SetEquals(empty));
Assert.That(HashSetMgr.Difference(empty, six).SetEquals(empty));
Assert.That(HashSetMgr.Difference(one, one).SetEquals(empty));
Assert.That(HashSetMgr.Difference(one, two).SetEquals(empty));
Assert.That(HashSetMgr.Difference(one, six).SetEquals(empty));
Assert.That(HashSetMgr.Difference(two, two).SetEquals(empty));
Assert.That(HashSetMgr.Difference(two, six).SetEquals(empty));
Assert.That(HashSetMgr.Difference(six, six).SetEquals(empty));
Assert.That(HashSetMgr.Difference(one, empty).SetEquals(one));
Assert.That(HashSetMgr.Difference(two, empty).SetEquals(two));
Assert.That(HashSetMgr.Difference(six, empty).SetEquals(six));
Assert.That(HashSetMgr.Difference(two, one).SetEquals(new HashSet<Vertex> { Vertex.Nth(2) }));
Assert.That(HashSetMgr.Difference(six, one).SetEquals(new HashSet<Vertex> { Vertex.Nth(0), Vertex.Nth(2), Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) }));
Assert.That(HashSetMgr.Difference(six, two).SetEquals(new HashSet<Vertex> { Vertex.Nth(0), Vertex.Nth(3), Vertex.Nth(4), Vertex.Nth(5) }));
}
}
}
<file_sep>using System.Globalization;
namespace BronKerboschStudy
{
public sealed class NumbersGame
{
public static int ParseInt(string orderstr)
{
int factor = 1;
if (orderstr.EndsWith("M", StringComparison.Ordinal))
{
factor = 1_000_000;
orderstr = orderstr.Remove(orderstr.Length - 1);
}
else if (orderstr.EndsWith("k", StringComparison.Ordinal))
{
factor = 1_000;
orderstr = orderstr.Remove(orderstr.Length - 1);
}
return int.Parse(orderstr, CultureInfo.InvariantCulture) * factor;
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public record UndirectedGraph(List<Set<Integer>> adjacencies) {
public UndirectedGraph {
for (int v = 0; v < adjacencies.size(); ++v) {
for (int w : adjacencies.get(v)) {
assert v != w;
assert adjacencies.get(w).contains(v);
}
}
}
public int order() {
return adjacencies.size();
}
public int size() {
int total = adjacencies.stream().mapToInt(Set::size).sum();
assert total % 2 == 0;
return total / 2;
}
public int degree(int node) {
return adjacencies.get(node).size();
}
public Set<Integer> neighbours(int node) {
return Collections.unmodifiableSet(adjacencies.get(node));
}
public Stream<Integer> connectedVertices() {
return IntStream.range(0, order()).filter(v -> degree(v) > 0).boxed();
}
public int maxDegreeVertex() {
return IntStream.range(0, order()).boxed()
.max(Comparator.comparingInt(this::degree))
.orElseThrow();
}
}
<file_sep>mod bron_kerbosch1a;
mod bron_kerbosch1b;
mod bron_kerbosch2a_gp;
mod bron_kerbosch2b;
mod bron_kerbosch2b_gp;
mod bron_kerbosch2b_gpx;
mod bron_kerbosch2b_rp;
mod bron_kerbosch3_gp;
mod bron_kerbosch3_gpx;
mod bron_kerbosch3_mt;
mod bron_kerbosch_degen;
mod bron_kerbosch_degen_mt;
mod bron_kerbosch_pivot;
pub mod graph;
pub(super) mod graph_degeneracy;
mod pile;
pub mod reporter;
pub mod reporters;
pub mod slimgraph;
#[cfg(test)]
pub mod tests;
pub mod vertex;
pub mod vertexsetlike;
use graph::{UndirectedGraph, Vertex};
use reporter::{Clique, Reporter};
use std::collections::BTreeSet;
#[cfg(not(miri))]
const NUM_FUNCS: usize = 10;
#[cfg(miri)]
const NUM_FUNCS: usize = 9;
pub const FUNC_NAMES: &[&str; NUM_FUNCS] = &[
"Ver1",
"Ver1½",
"Ver2-GP",
"Ver2½",
"Ver2½-GP",
"Ver2½-GPX",
"Ver2½-RP",
"Ver3½-GP",
"Ver3½-GPX",
#[cfg(not(miri))]
"Ver3½=GPc",
];
pub fn explore<Graph, Rprtr>(func_index: usize, graph: &Graph, reporter: &mut Rprtr)
where
Graph: UndirectedGraph,
Rprtr: Reporter,
{
match func_index {
0 => bron_kerbosch1a::explore(graph, reporter),
1 => bron_kerbosch1b::explore(graph, reporter),
2 => bron_kerbosch2a_gp::explore(graph, reporter),
3 => bron_kerbosch2b::explore(graph, reporter),
4 => bron_kerbosch2b_gp::explore(graph, reporter),
5 => bron_kerbosch2b_gpx::explore(graph, reporter),
6 => bron_kerbosch2b_rp::explore(graph, reporter),
7 => bron_kerbosch3_gp::explore(graph, reporter),
8 => bron_kerbosch3_gpx::explore(graph, reporter),
9 => bron_kerbosch3_mt::explore(graph, reporter),
_ => panic!(),
}
}
pub type OrderedClique = BTreeSet<Vertex>;
pub type OrderedCliques = BTreeSet<OrderedClique>;
pub fn order_cliques<I: Iterator<Item = Clique>>(cliques: I) -> OrderedCliques {
BTreeSet::from_iter(cliques.map(|clique| BTreeSet::from_iter(clique.into_iter())))
}
<file_sep>// Bron-Kerbosch algorithm with pivot picked arbitrarily
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
namespace BronKerbosch
{
internal enum PivotChoice
{
MaxDegreeLocal,
MaxDegreeLocalX
}
internal static class Pivot<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter, PivotChoice pivotChoice)
{
var order = graph.Order;
if (order == 0)
{
return;
}
var pivot = graph.MaxDegreeVertex();
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
var excluded = VertexSetMgr.EmptyWithCapacity(order);
foreach (var v in Enumerable.Range(0, order).Select(Vertex.Nth))
{
var neighbours = graph.Neighbours(v);
if (neighbours.Any() && !neighbours.Contains(pivot))
{
var neighbouringExcluded = VertexSetMgr.Intersection(neighbours, excluded);
if (neighbouringExcluded.Count() < neighbours.Count())
{
var neighbouringCandidates = VertexSetMgr.Difference(neighbours, neighbouringExcluded);
Visit(graph, reporter, pivotChoice,
neighbouringCandidates, neighbouringExcluded,
ImmutableArray.Create(v));
}
var added = VertexSetMgr.Add(excluded, v);
Debug.Assert(added);
}
}
}
public static void Visit(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter, PivotChoice choice,
VertexSet candidates, VertexSet excluded,
ImmutableArray<Vertex> cliqueInProgress)
{
Debug.Assert(candidates.All(v => graph.Degree(v) > 0));
Debug.Assert(excluded.All(v => graph.Degree(v) > 0));
Debug.Assert(!VertexSetMgr.Overlaps(candidates, excluded));
int numCandidates = candidates.Count();
Debug.Assert(numCandidates >= 1);
if (numCandidates == 1)
{
// Same logic as below, stripped down
var v = candidates.First();
var neighbours = graph.Neighbours(v);
if (!VertexSetMgr.Overlaps(neighbours, excluded))
{
reporter.Record(CollectionsUtil.Append(cliqueInProgress, v));
}
return;
}
Vertex pivot;
var remainingCandidates = new Vertex[numCandidates];
var remainingCandidateCount = 0;
// Quickly handle locally unconnected candidates while finding pivot
const int INVALID = int.MaxValue;
pivot = Vertex.Nth(INVALID);
var seenLocalDegree = 0;
foreach (var v in candidates)
{
var neighbours = graph.Neighbours(v);
var localDegree = VertexSetMgr.IntersectionSize(neighbours, candidates);
if (localDegree == 0)
{
// Same logic as below, stripped down
if (!VertexSetMgr.Overlaps(neighbours, excluded))
{
reporter.Record(CollectionsUtil.Append(cliqueInProgress, v));
}
}
else
{
if (seenLocalDegree < localDegree)
{
seenLocalDegree = localDegree;
pivot = v;
}
remainingCandidates[remainingCandidateCount] = v;
remainingCandidateCount += 1;
}
}
if (seenLocalDegree == 0)
{
return;
}
Debug.Assert(pivot.Index() != INVALID);
if (choice == PivotChoice.MaxDegreeLocalX)
{
foreach (var v in excluded)
{
var neighbours = graph.Neighbours(v);
var localDegree = VertexSetMgr.IntersectionSize(neighbours, candidates);
if (seenLocalDegree < localDegree)
{
seenLocalDegree = localDegree;
pivot = v;
}
}
}
for (var i = 0; i < remainingCandidateCount; ++i)
{
var v = remainingCandidates[i];
var neighbours = graph.Neighbours(v);
Debug.Assert(neighbours.Any());
if (!neighbours.Contains(pivot))
{
var removed = VertexSetMgr.Remove(candidates, v);
Debug.Assert(removed);
var neighbouringCandidates = VertexSetMgr.Intersection(neighbours, candidates);
if (neighbouringCandidates.Any())
{
var neighbouringExcluded = VertexSetMgr.Intersection(neighbours, excluded);
Visit(graph, reporter, choice,
neighbouringCandidates, neighbouringExcluded,
CollectionsUtil.Append(cliqueInProgress, v));
}
else if (!VertexSetMgr.Overlaps(neighbours, excluded))
{
reporter.Record(CollectionsUtil.Append(cliqueInProgress, v));
}
var added = VertexSetMgr.Add(excluded, v);
Debug.Assert(added);
}
}
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class BronKerbosch3_MT implements BronKerboschAlgorithm {
private static final int NUM_VISITING_THREADS = 5;
private static final int CLEAN_END_VERTEX = -1;
private static final int DIRTY_END_VERTEX = -2;
private UndirectedGraph graph;
private BlockingQueue<VisitJob> startQueue;
private BlockingQueue<VisitJob> visitQueue;
private Collection<int[]> cliques;
@RequiredArgsConstructor
private static final class VisitJob {
private final int startVertex;
private Set<Integer> mut_candidates;
private Set<Integer> mut_excluded;
}
@NoArgsConstructor
private final class StartProducer implements Runnable {
@Override
public void run() {
try {
Iterable<Integer> vertices = () -> new DegeneracyOrdering(graph, -1);
for (var v : vertices) {
startQueue.put(new VisitJob(v));
}
startQueue.put(new VisitJob(CLEAN_END_VERTEX));
} catch (InterruptedException consumed) {
startQueue.clear();
startQueue.add(new VisitJob(DIRTY_END_VERTEX));
}
}
}
@NoArgsConstructor
private final class VisitProducer implements Runnable {
@SuppressWarnings("UseOfConcreteClass")
@Override
public void run() {
try {
Set<Integer> mut_excluded = new HashSet<>(graph.order());
VisitJob job;
while ((job = startQueue.take()).startVertex >= 0) {
var v = job.startVertex;
var neighbours = graph.neighbours(v);
assert !neighbours.isEmpty();
job.mut_candidates = util.Difference(neighbours, mut_excluded)
.collect(Collectors.toCollection(HashSet::new));
if (job.mut_candidates.isEmpty()) {
assert !util.AreDisjoint(neighbours, mut_excluded);
} else {
job.mut_excluded = util.Intersect(neighbours, mut_excluded)
.collect(Collectors.toCollection(HashSet::new));
visitQueue.put(job);
}
mut_excluded.add(v);
}
for (int i = 0; i < NUM_VISITING_THREADS; ++i) {
visitQueue.put(job);
}
} catch (InterruptedException consumed) {
visitQueue.clear();
for (int i = 0; i < NUM_VISITING_THREADS; ++i) {
visitQueue.add(new VisitJob(DIRTY_END_VERTEX));
}
}
}
}
@NoArgsConstructor
private final class Visitor implements Runnable {
@SuppressWarnings("UseOfConcreteClass")
@Override
public void run() {
try {
VisitJob job;
while ((job = visitQueue.take()).startVertex >= 0) {
BronKerboschPivot.visit(graph, clique -> cliques.add(clique),
PivotChoice.MaxDegreeLocal,
job.mut_candidates,
job.mut_excluded,
new int[]{job.startVertex});
}
if (job.startVertex == DIRTY_END_VERTEX) {
cliques.clear();
}
} catch (InterruptedException consumed) {
cliques.clear();
}
}
}
@Override
public Stream<int[]> explore(UndirectedGraph graph) throws InterruptedException {
this.graph = graph;
@SuppressWarnings("NumericCastThatLosesPrecision")
var initialCap = (int) Math.floor(Math.sqrt(graph.size()));
cliques = Collections.synchronizedCollection(new ArrayDeque<>(initialCap));
startQueue = new ArrayBlockingQueue<>(64);
visitQueue = new ArrayBlockingQueue<>(64);
new Thread(new StartProducer()).start();
new Thread(new VisitProducer()).start();
var visitors = new Thread[NUM_VISITING_THREADS];
for (int i = 0; i < NUM_VISITING_THREADS; ++i) {
visitors[i] = new Thread(new Visitor());
visitors[i].start();
}
for (int i = 0; i < NUM_VISITING_THREADS; ++i) {
visitors[i].join();
}
return cliques.stream();
}
}
<file_sep>#include "pch.h"
#include "BronKerboschPivot.h"
<file_sep>//! Naive Bron-Kerbosch algorithm
use super::graph::{connected_vertices, UndirectedGraph, VertexSetLike};
use super::reporter::{Clique, Reporter};
pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
let candidates = connected_vertices(graph);
if !candidates.is_empty() {
visit(graph, reporter, candidates, VertexSet::new(), Clique::new());
}
}
fn visit<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
mut candidates: VertexSet,
mut excluded: VertexSet,
clique: Clique,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
debug_assert!(candidates.all(|&v| graph.degree(v) > 0));
debug_assert!(excluded.all(|&v| graph.degree(v) > 0));
debug_assert!(candidates.is_disjoint(&excluded));
if candidates.is_empty() {
if excluded.is_empty() {
reporter.record(clique);
}
return;
}
while let Some(v) = candidates.pop_arbitrary() {
let neighbours = graph.neighbours(v);
let neighbouring_candidates = neighbours.intersection_collect(&candidates);
let neighbouring_excluded = neighbours.intersection_collect(&excluded);
visit(
graph,
reporter,
neighbouring_candidates,
neighbouring_excluded,
[clique.as_slice(), &[v]].concat(),
);
excluded.insert(v);
}
}
<file_sep>using BronKerbosch;
using System.Collections.Immutable;
using System.Diagnostics;
namespace BronKerboschStudy
{
public sealed class RandomUndirectedGraph<TVertexSet, TVertexSetMgr>
where TVertexSet : IEnumerable<Vertex>
where TVertexSetMgr : IVertexSetMgr<TVertexSet>
{
public UndirectedGraph<TVertexSet, TVertexSetMgr> Graph { get; }
public int CliqueCount { get; }
private RandomUndirectedGraph(UndirectedGraph<TVertexSet, TVertexSetMgr> graph, int cliqueCount)
{
Graph = graph;
CliqueCount = cliqueCount;
}
public static RandomUndirectedGraph<TVertexSet, TVertexSetMgr> Read(string orderstr, int size)
{
var order = NumbersGame.ParseInt(orderstr);
var fullyMeshedSize = (long)order * (order - 1) / 2;
if (size > fullyMeshedSize)
throw new ArgumentException($"{order} nodes accommodate at most {fullyMeshedSize} edges");
var edgesPath = $"..\\data\\random_edges_order_{orderstr}.txt";
const string statsPath = "..\\data\\random_stats.txt";
var adjacencies = ReadEdges(edgesPath, orderstr, size);
var cliqueCount = ReadStats(statsPath, orderstr, size);
var g = new UndirectedGraph<TVertexSet, TVertexSetMgr>(adjacencies);
Debug.Assert(g.Order == order);
Debug.Assert(g.Size == size);
return new RandomUndirectedGraph<TVertexSet, TVertexSetMgr>(g, cliqueCount);
}
private static ImmutableArray<TVertexSet> ReadEdges(string path, string orderstr, int size)
{
var order = NumbersGame.ParseInt(orderstr);
var adjacencies = Enumerable.Range(0, order)
.Select(_ => TVertexSetMgr.Empty())
.ToImmutableArray();
var linenum = 0;
using (var file = new StreamReader(path))
{
string? line;
while (linenum < size && (line = file!.ReadLine()) != null)
{
++linenum;
var fields = line.Split(' ');
if (!int.TryParse(fields[0], out var v) ||
!int.TryParse(fields[1], out var w))
{
throw new ArgumentException($"File {path} line {linenum} contains bogus text {line}");
}
var added1 = TVertexSetMgr.Add(adjacencies[v], Vertex.Nth(w));
var added2 = TVertexSetMgr.Add(adjacencies[w], Vertex.Nth(v));
Debug.Assert(added1);
Debug.Assert(added2);
}
}
if (linenum < size)
{
throw new ArgumentException($"Exhausted generated list of {linenum} edges in {path}");
}
return adjacencies;
}
private static int ReadStats(string path, string orderstr, int size)
{
var prefix = $"{orderstr}\t{size}\t";
using var file = new StreamReader(path);
var header = file.ReadLine()!;
string? line;
while ((line = file.ReadLine()) != null)
{
if (line.StartsWith(prefix, StringComparison.Ordinal))
{
if (!int.TryParse(line.AsSpan(prefix.Length), out var c))
{
throw new ArgumentException($"File {path} has bogus line “{line}”");
}
return c;
}
}
throw new ArgumentException($"File {path} lacks order {orderstr} size {size}");
}
}
}
<file_sep># coding: utf-8
import bron_kerbosch1a
import bron_kerbosch1b
import bron_kerbosch2a_gp
import bron_kerbosch2b_gp
import bron_kerbosch2b_gpx
import bron_kerbosch3_gp
import bron_kerbosch3_gpx
from data import NEIGHBORS as SAMPLE_ADJACENCY_LIST
from graph import UndirectedGraph as Graph, Vertex
from random_graph import to_int, read_random_graph
from reporter import CollectingReporter, CountingReporter, Reporter
from stats import SampleStatistics
from publish import publish
import argparse
import itertools
from math import isnan
import pytest
import sys
import time
from typing import Callable, Iterable, List, Set
FUNC = Callable[[Graph, Reporter], None]
FUNCS: List[FUNC] = [
bron_kerbosch1a.explore,
bron_kerbosch1b.explore,
bron_kerbosch2a_gp.explore,
bron_kerbosch2b_gp.explore,
bron_kerbosch2b_gpx.explore,
bron_kerbosch3_gp.explore,
bron_kerbosch3_gpx.explore,
]
FUNC_NAMES = [
"Ver1",
"Ver1½",
"Ver2-GP",
"Ver2½-GP",
"Ver2½-GPX",
"Ver3½-GP",
"Ver3½-GPX",
]
def are_maximal(cliques: List[List[Vertex]]) -> bool:
for j, clique2 in enumerate(cliques):
if j % 1000 == 0:
print(f"checking maximality {j}/{len(cliques)}")
for i, clique1 in enumerate(cliques[:j]):
if clique1[:len(clique2)] == clique2[:len(clique1)]:
return False
print("checked maximality")
return True
def bron_kerbosch_timed(graph: Graph, clique_count: int,
func_indices: List[int],
timed_samples: int) -> List[SampleStatistics]:
first = None
times = [SampleStatistics() for _ in range(len(FUNCS))]
for sample in range(timed_samples + 1):
for func_index in func_indices:
func = FUNCS[func_index]
func_name = FUNC_NAMES[func_index]
collecting_reporter = CollectingReporter()
counting_reporter = CountingReporter()
begin = time.perf_counter()
try:
if sample == 0:
func(graph, collecting_reporter)
else:
func(graph, counting_reporter)
except RecursionError:
print(f"{func_name} recursed out!")
secs = time.perf_counter() - begin
if sample == 0:
if secs >= 3.0:
print(f" {func_name:<8}: {secs:6.3f}s")
current = sorted(
sorted(clique) for clique in collecting_reporter.cliques)
if first is None:
if len(current) != clique_count:
print(
f"{func_name}: expected {clique_count}, obtained {len(current)} cliques!"
)
if graph.order < 100 and not are_maximal(current):
print(f" {func_name} not maximal")
first = current
elif first != current:
print(f"{func_name}: " +
f"expected {len(first)} cliques, " +
f"obtained {len(current)} different cliques!")
else:
if counting_reporter.cliques != clique_count:
print(
f"{func_name}: expected {clique_count}, obtained {counting_reporter.cliques} cliques!"
)
times[func_index].put(secs)
return times
def bkf(func: FUNC, adjacencies: List[Set[Vertex]]) -> List[List[Vertex]]:
reporter = CollectingReporter()
func(Graph(adjacencies=adjacencies), reporter)
return sorted(sorted(clique) for clique in reporter.cliques)
@pytest.mark.parametrize("func", FUNCS)
def test_order_0(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[]) == []
@pytest.mark.parametrize("func", FUNCS)
def test_order_1(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[set()]) == []
@pytest.mark.parametrize("func", FUNCS)
def test_order_2_isolated(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[set(), set()]) == []
@pytest.mark.parametrize("func", FUNCS)
def test_order_2_connected(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0}]) == [[0, 1]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_3_size_1_left(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0}, set()]) == [[0, 1]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_3_size_1_long(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{2}, set(), {0}]) == [[0, 2]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_3_size_1_right(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[set(), {2}, {1}]) == [[1, 2]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_3_size_2(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0, 2}, {1}]) == [[0, 1], [1, 2]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_3_size_3(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1, 2}, {0, 2}, {0, 1}]) == [[0, 1, 2]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_2(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0}, {3}, {2}]) == [[0, 1], [2, 3]]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_3_bus(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0, 2}, {1, 3}, {2}]) == [
[0, 1],
[1, 2],
[2, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_3_star(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1, 2, 3}, {0}, {0}, {0}]) == [
[0, 1],
[0, 2],
[0, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_4_p(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1}, {0, 2, 3}, {1, 3}, {1, 2}]) == [
[0, 1],
[1, 2, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_4_square(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1, 3}, {0, 2}, {1, 3}, {0, 2}]) == [
[0, 1],
[0, 3],
[1, 2],
[2, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_5(func: FUNC) -> None:
assert bkf(func=func, adjacencies=[{1, 2, 3}, {0, 2}, {0, 1, 3},
{0, 2}]) == [
[0, 1, 2],
[0, 2, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_4_size_6(func: FUNC) -> None:
assert bkf(func=func,
adjacencies=[
{1, 2, 3},
{0, 2, 3},
{0, 1, 3},
{0, 1, 2},
]) == [
[0, 1, 2, 3],
]
@pytest.mark.parametrize("func", FUNCS)
def test_order_5_penultimate(func: FUNC) -> None:
assert bkf(func=func,
adjacencies=[
{1, 2, 3, 4},
{0, 2, 3, 4},
{0, 1, 3, 4},
{0, 1, 2},
{0, 1, 2},
]) == [
[0, 1, 2, 3],
[0, 1, 2, 4],
]
@pytest.mark.parametrize("func", FUNCS)
def test_sample(func: FUNC) -> None:
assert bkf(func=func, adjacencies=SAMPLE_ADJACENCY_LIST) == [
[1, 2, 3, 4],
[2, 3, 5],
[5, 6, 7],
]
@pytest.mark.parametrize("func", FUNCS)
def test_bigger(func: FUNC) -> None:
assert bkf(func=func,
adjacencies=[
{1, 2, 3, 4, 6, 7},
{0, 3, 6, 7, 8, 9},
{0, 3, 5, 7, 8, 9},
{0, 1, 2, 4, 9},
{0, 3, 6, 7, 9},
{2, 6},
{0, 1, 4, 5, 9},
{0, 1, 2, 4, 9},
{1, 2},
{1, 2, 3, 4, 6, 7},
]) == [
[0, 1, 3],
[0, 1, 6],
[0, 1, 7],
[0, 2, 3],
[0, 2, 7],
[0, 3, 4],
[0, 4, 6],
[0, 4, 7],
[1, 3, 9],
[1, 6, 9],
[1, 7, 9],
[1, 8],
[2, 3, 9],
[2, 5],
[2, 7, 9],
[2, 8],
[3, 4, 9],
[4, 6, 9],
[4, 7, 9],
[5, 6],
]
def bk(orderstr: str, sizes: Iterable[int], func_indices: List[int],
timed_samples: int) -> None:
order = to_int(orderstr)
stats_per_func_by_size = {}
for size in sizes:
begin = time.process_time()
g, clique_count = read_random_graph(orderstr=orderstr, size=size)
secs = time.process_time() - begin
name = f"random of order {orderstr}, size {size}, {clique_count} cliques:"
if order < 10:
print(f"{name} {g.adjacencies}")
else:
print(f"{name} (creating took {secs:.3f}s)")
stats = bron_kerbosch_timed(g,
clique_count=clique_count,
func_indices=func_indices,
timed_samples=timed_samples)
for func_index, func_name in enumerate(FUNC_NAMES):
mean = stats[func_index].mean()
if not isnan(mean):
reldev = stats[func_index].deviation() / mean
print(f" {func_name:<8}: {mean:6.3f}s ± {reldev:.0%}")
stats_per_func_by_size[size] = stats
if len(stats_per_func_by_size) > 1:
publish(language="python311",
orderstr=orderstr,
case_names=FUNC_NAMES,
stats_per_func_by_size=stats_per_func_by_size)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="test Bron-Kerbosch implementations " +
"on some random graphs of specified or default dimensions")
parser.add_argument('--seed', nargs=1)
parser.add_argument('order', nargs='?')
parser.add_argument('size', nargs='*')
args = parser.parse_args(sys.argv[1:])
if args.seed:
seed = int(args.seed[0])
else:
seed = 19680516
all_func_indices = list(range(len(FUNCS)))
most_func_indices = list(range(2, len(FUNCS)))
mt_func_indices = list(range(3, len(FUNCS)))
if args.order is not None and args.size is not None:
bk(orderstr=args.order,
sizes=[int(size) for size in args.size],
func_indices=all_func_indices,
timed_samples=0)
else:
assert False, "Run with -O for meaningful measurements"
bk(
orderstr="100",
sizes=range(2_000, 3_001, 50), # max 4_950
func_indices=all_func_indices,
timed_samples=5)
time.sleep(7)
bk(orderstr="10k",
sizes=itertools.chain(range(10_000, 100_000, 10_000),
range(100_000, 200_001, 25_000)),
func_indices=most_func_indices,
timed_samples=3)
time.sleep(7)
bk(orderstr="1M",
sizes=itertools.chain(range(500_000, 2_000_000, 250_000),
range(2_000_000, 3_000_001, 1_000_000)),
func_indices=mt_func_indices,
timed_samples=3)
<file_sep>#pragma once
#include "BronKerbosch/pch.h"
#ifdef _MSC_VER
# pragma execution_character_set("utf-8")
#endif
#include <array>
#include <chrono>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_set>
<file_sep>use std::fmt::Debug;
use std::ops::{Index, IndexMut};
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Vertex(u32);
impl Vertex {
pub fn new(n: usize) -> Self {
Self(n as u32)
}
}
impl<T> Index<Vertex> for [T] {
type Output = T;
fn index(&self, i: Vertex) -> &T {
// Won't actually ever panic on 32- or 64-bit platforms
let i: usize = i.0.try_into().unwrap();
&self[i]
}
}
impl<T> IndexMut<Vertex> for [T] {
fn index_mut(&mut self, i: Vertex) -> &mut T {
// Won't actually ever panic on 32- or 64-bit platforms
let i: usize = i.0.try_into().unwrap();
&mut self[i]
}
}
#[derive(Debug)]
pub struct VertexMap<T>(Vec<T>);
impl<T> VertexMap<T> {
pub fn new(stamp: T, order: usize) -> Self
where
T: Clone,
{
Self(vec![stamp; order])
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn contains(&self, val: &T) -> bool
where
T: Eq,
{
self.0.contains(val)
}
pub fn iter(&self) -> impl Iterator<Item = (Vertex, &T)> {
self.0.iter().enumerate().map(|(i, v)| (Vertex::new(i), v))
}
}
impl<T> FromIterator<T> for VertexMap<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> VertexMap<T> {
Self(Vec::from_iter(iter))
}
}
impl<T> Index<Vertex> for VertexMap<T> {
type Output = T;
fn index(&self, i: Vertex) -> &T {
// Won't actually ever panic on 32- or 64-bit platforms
let i: usize = i.0.try_into().unwrap();
&self.0[i]
}
}
impl<T> IndexMut<Vertex> for VertexMap<T> {
fn index_mut(&mut self, i: Vertex) -> &mut T {
// Won't actually ever panic on 32- or 64-bit platforms
let i: usize = i.0.try_into().unwrap();
&mut self.0[i]
}
}
<file_sep>using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
namespace BronKerbosch
{
public sealed class CollectingReporter : IReporter
{
public List<ImmutableArray<Vertex>> Cliques { get; } = new List<ImmutableArray<Vertex>>();
public void Record(ImmutableArray<Vertex> clique)
{
Debug.Assert(clique.Length > 1);
Cliques.Add(clique);
}
}
}
<file_sep>using BronKerbosch;
using NUnit.Framework;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
#pragma warning disable CA1825 // Avoid zero-length array allocations
#pragma warning disable CA1861 // Avoid constant arrays as arguments
namespace BronKerboschUnitTest
{
public class BronKerboschHashTest : BronKerboschTestTemplate<HashSet<Vertex>, HashSetMgr> { }
public class BronKerboschSortedTest : BronKerboschTestTemplate<SortedSet<Vertex>, SortedSetMgr> { }
public class BronKerboschTestTemplate<TVertexSet, TVertexSetMgr>
where TVertexSet : IEnumerable<Vertex>
where TVertexSetMgr : IVertexSetMgr<TVertexSet>
{
private static void Bk(int[][] adjacencies, int[][] cliques)
{
var adjacencies2 = adjacencies.Select(neighbours => TVertexSetMgr.From(neighbours.Select(i => Vertex.Nth(i))))
.ToImmutableArray();
var cliques2 = cliques.Select(clique => clique.Select(i => Vertex.Nth(i)).ToArray()).ToArray();
var graph = new UndirectedGraph<TVertexSet, TVertexSetMgr>(adjacencies2);
foreach (var funcIndex in Enumerable.Range(0, Portfolio.FuncNames.Length))
{
var reporter = new CollectingReporter();
Portfolio.Explore(funcIndex, graph, reporter);
Assert.AreEqual(cliques2.Length, reporter.Cliques.Count);
Portfolio.SortCliques(reporter.Cliques);
foreach ((var reportedClique, var i) in reporter.Cliques.Select((v, i) => (v, i)))
Assert.That(reportedClique.SequenceEqual(cliques2[i]));
}
}
[Test]
public void TestOrder0()
{
Bk(adjacencies: new int[][] { },
cliques: new int[][] { });
}
[Test]
public void TestOrder1()
{
Bk(adjacencies: new[] { new int[] { } },
cliques: new int[][] { });
}
[Test]
public void TestOrder2_Isolated()
{
Bk(adjacencies: new[] { new int[] { }, new int[] { } },
cliques: new int[][] { });
}
[Test]
public void TestOrder2_Connected()
{
Bk(adjacencies: new[] { new int[] { 1 }, new int[] { 0 } },
cliques: new[] { new int[] { 0, 1 } });
}
[Test]
public void TestOrder3_Size1_Left()
{
Bk(adjacencies: new[] { new int[] { 1 }, new int[] { 0 }, new int[] { } },
cliques: new[] { new int[] { 0, 1 } });
}
[Test]
public void TestOrder3_Size1_Long()
{
Bk(adjacencies: new[] { new int[] { 2 }, new int[] { }, new int[] { 0 } },
cliques: new[] { new int[] { 0, 2 } });
}
[Test]
public void TestOrder3_Size1_Right()
{
Bk(adjacencies: new[] { new int[] { }, new int[] { 2 }, new int[] { 1 } },
cliques: new[] { new int[] { 1, 2 } });
}
[Test]
public void TestOrder3_Size2()
{
Bk(adjacencies: new[]
{
new int[] {1},
new int[] {0, 2},
new int[] {1}
},
cliques: new[] { new int[] { 0, 1 }, new int[] { 1, 2 } });
}
[Test]
public void TestOrder3_Size3()
{
Bk(adjacencies: new[]
{
new int[] {1, 2},
new int[] {0, 2},
new int[] {0, 1}
},
cliques: new[] { new int[] { 0, 1, 2 } });
}
[Test]
public void TestOrder4_Size2()
{
Bk(adjacencies: new[]
{
new int[] {1}, new int[] {0},
new int[] {3}, new int[] {2}
},
cliques: new[] { new int[] { 0, 1 }, new int[] { 2, 3 } });
}
[Test]
public void TestOrder4_Size3_Bus()
{
Bk(adjacencies: new[]
{
new int[] {1}, new int[] {0, 2},
new int[] {1, 3}, new int[] {2}
},
cliques: new[] { new int[] { 0, 1 }, new int[] { 1, 2 }, new int[] { 2, 3 } });
}
[Test]
public void TestOrder4_Size3_Star()
{
Bk(adjacencies: new[]
{
new int[] {1, 2, 3}, new int[] {0},
new int[] {0}, new int[] {0}
},
cliques: new[] { new int[] { 0, 1 }, new int[] { 0, 2 }, new int[] { 0, 3 } });
}
[Test]
public void TestOrder4_Size4_p()
{
Bk(adjacencies: new[]
{
new int[] {1}, new int[] {0, 2, 3},
new int[] {1, 3}, new int[] {1, 2}
},
cliques: new[] { new int[] { 0, 1 }, new int[] { 1, 2, 3 } });
}
[Test]
public void TestOrder4_Size4_Square()
{
Bk(adjacencies: new[]
{
new int[] {1, 3}, new int[] {0, 2},
new int[] {1, 3}, new int[] {0, 2}
},
cliques: new[]
{
new int[] {0, 1}, new int[] {0, 3},
new int[] {1, 2}, new int[] {2, 3}
});
}
[Test]
public void TestOrder4_Size5()
{
Bk(adjacencies: new[]
{
new int[] {1, 2, 3}, new int[] {0, 2},
new int[] {0, 1, 3}, new int[] {0, 2}
},
cliques: new[] { new int[] { 0, 1, 2 }, new int[] { 0, 2, 3 } });
}
[Test]
public void TestOrder4_Size6()
{
Bk(adjacencies: new[]
{
new int[] {1, 2, 3}, new int[] {0, 2, 3},
new int[] {0, 1, 3}, new int[] {0, 1, 2}
},
cliques: new[] { new int[] { 0, 1, 2, 3 } });
}
[Test]
public void TestOrder4_Size6_Penultimate()
{
Bk(adjacencies: new[]
{
new int[] {1, 2, 3, 4}, new int[] {0, 2, 3, 4},
new int[] {0, 1, 3, 4}, new int[] {0, 1, 2},
new int[] {0, 1, 2}
},
cliques: new[] { new int[] { 0, 1, 2, 3 }, new int[] { 0, 1, 2, 4 } });
}
[Test]
public void TestSample()
{
Bk(adjacencies: new[]
{
new int[] { },
new int[] {2, 3, 4},
new int[] {1, 3, 4, 5},
new int[] {1, 2, 4, 5},
new int[] {1, 2, 3},
new int[] {2, 3, 6, 7},
new int[] {5, 7},
new int[] {5, 6}
},
cliques: new[]
{
new int[] {1, 2, 3, 4},
new int[] {2, 3, 5},
new int[] {5, 6, 7}
});
}
[Test]
public void TestBigger()
{
Bk(adjacencies: new[]
{
new int[] {1, 2, 3, 4, 6, 7},
new int[] {0, 3, 6, 7, 8, 9},
new int[] {0, 3, 5, 7, 8, 9},
new int[] {0, 1, 2, 4, 9},
new int[] {0, 3, 6, 7, 9},
new int[] {2, 6},
new int[] {0, 1, 4, 5, 9},
new int[] {0, 1, 2, 4, 9},
new int[] {1, 2},
new int[] {1, 2, 3, 4, 6, 7}
},
cliques: new[]
{
new int[] {0, 1, 3},
new int[] {0, 1, 6},
new int[] {0, 1, 7},
new int[] {0, 2, 3},
new int[] {0, 2, 7},
new int[] {0, 3, 4},
new int[] {0, 4, 6},
new int[] {0, 4, 7},
new int[] {1, 3, 9},
new int[] {1, 6, 9},
new int[] {1, 7, 9},
new int[] {1, 8},
new int[] {2, 3, 9},
new int[] {2, 5},
new int[] {2, 7, 9},
new int[] {2, 8},
new int[] {3, 4, 9},
new int[] {4, 6, 9},
new int[] {4, 7, 9},
new int[] {5, 6}
});
}
}
}
<file_sep>using System.Collections.Immutable;
namespace BronKerbosch
{
public static class CollectionsUtil
{
public static ImmutableArray<T> Append<T>(ImmutableArray<T> head, T tail)
{
var builder = ImmutableArray.CreateBuilder<T>(head.Length + 1);
builder.AddRange(head);
builder.Add(tail);
return builder.MoveToImmutable();
}
}
}
<file_sep>using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
namespace BronKerbosch
{
public sealed class UndirectedGraph<TVertexSet, TVertexSetMgr>
where TVertexSet : IEnumerable<Vertex>
where TVertexSetMgr : IVertexSetMgr<TVertexSet>
{
private readonly ImmutableArray<TVertexSet> itsAdjacencies;
public UndirectedGraph(ImmutableArray<TVertexSet> adjacencies)
{
for (int i = 0; i < adjacencies.Length; ++i)
{
var v = Vertex.Nth(i);
foreach (var w in adjacencies[v.Index()])
{
Debug.Assert(v != w);
Debug.Assert(adjacencies[w.Index()].Contains(v));
}
}
itsAdjacencies = adjacencies;
}
public int Order => itsAdjacencies.Length;
public int Size
{
get
{
var total = Enumerable.Range(0, Order).Select(Vertex.Nth).Sum(Degree);
Debug.Assert(total % 2 == 0);
return total / 2;
}
}
public TVertexSet Neighbours(Vertex node) => itsAdjacencies[node.Index()];
public int Degree(Vertex node) => itsAdjacencies[node.Index()].Count();
public IEnumerable<Vertex> Vertices() => Enumerable.Range(0, Order).Select(Vertex.Nth);
public IEnumerable<Vertex> ConnectedVertices() => Vertices().Where(v => Degree(v) > 0);
public Vertex MaxDegreeVertex() => Vertices().MaxBy(Degree);
}
}
<file_sep>use crate::core::vertexsetlike::{Vertex, VertexSetLike};
use fnv::{FnvBuildHasher, FnvHashSet};
use rand::{seq::IteratorRandom, seq::SliceRandom, Rng};
use std::collections::{BTreeSet, HashSet};
impl VertexSetLike for BTreeSet<Vertex> {
fn new() -> Self {
BTreeSet::new()
}
fn with_capacity(_capacity: usize) -> Self {
BTreeSet::new()
}
fn is_empty(&self) -> bool {
BTreeSet::is_empty(self)
}
fn len(&self) -> usize {
BTreeSet::len(self)
}
fn contains(&self, v: Vertex) -> bool {
BTreeSet::contains(self, &v)
}
fn difference_collect(&self, other: &Self) -> Self {
self.difference(other).copied().collect()
}
fn is_disjoint(&self, other: &Self) -> bool {
self.intersection(other).next().is_none()
}
fn intersection_size(&self, other: &Self) -> usize {
self.intersection(other).count()
}
fn intersection_collect(&self, other: &Self) -> Self {
self.intersection(other).copied().collect()
}
fn reserve(&mut self, _additional: usize) {}
fn insert(&mut self, v: Vertex) {
BTreeSet::insert(self, v);
}
fn remove(&mut self, v: Vertex) {
BTreeSet::remove(self, &v);
}
fn pop_arbitrary(&mut self) -> Option<Vertex> {
let elt = self.iter().next().copied()?;
self.take(&elt)
}
fn choose_arbitrary(&self) -> Option<&Vertex> {
self.iter().next()
}
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex> {
self.iter().choose(rng)
}
fn clear(&mut self) {
BTreeSet::clear(self)
}
fn all<F>(&self, f: F) -> bool
where
F: FnMut(&Vertex) -> bool,
{
self.iter().all(f)
}
fn for_each<F>(&self, mut f: F)
where
F: FnMut(Vertex),
{
for &v in self {
f(v);
}
}
}
#[allow(clippy::implicit_hasher)]
impl VertexSetLike for HashSet<Vertex> {
fn new() -> Self {
HashSet::new()
}
fn with_capacity(capacity: usize) -> Self {
HashSet::with_capacity(capacity)
}
fn is_empty(&self) -> bool {
HashSet::is_empty(self)
}
fn len(&self) -> usize {
HashSet::len(self)
}
fn contains(&self, v: Vertex) -> bool {
HashSet::contains(self, &v)
}
fn difference_collect(&self, other: &Self) -> Self {
self.difference(other).copied().collect()
}
fn is_disjoint(&self, other: &Self) -> bool {
HashSet::is_disjoint(self, other)
}
fn intersection_size(&self, other: &Self) -> usize {
self.intersection(other).count()
}
fn intersection_collect(&self, other: &Self) -> Self {
self.intersection(other).copied().collect()
}
fn reserve(&mut self, additional: usize) {
HashSet::reserve(self, additional)
}
fn insert(&mut self, v: Vertex) {
HashSet::insert(self, v);
}
fn remove(&mut self, v: Vertex) {
HashSet::remove(self, &v);
}
fn pop_arbitrary(&mut self) -> Option<Vertex> {
let elt = self.iter().next().copied()?;
self.take(&elt)
}
fn choose_arbitrary(&self) -> Option<&Vertex> {
self.iter().next()
}
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex> {
self.iter().choose(rng)
}
fn clear(&mut self) {
self.clear()
}
fn all<F>(&self, f: F) -> bool
where
F: FnMut(&Vertex) -> bool,
{
self.iter().all(f)
}
fn for_each<F>(&self, mut f: F)
where
F: FnMut(Vertex),
{
for &v in self {
f(v);
}
}
}
impl VertexSetLike for FnvHashSet<Vertex> {
fn new() -> Self {
FnvHashSet::default()
}
fn with_capacity(capacity: usize) -> Self {
FnvHashSet::with_capacity_and_hasher(capacity, FnvBuildHasher::default())
}
fn is_empty(&self) -> bool {
FnvHashSet::is_empty(self)
}
fn len(&self) -> usize {
FnvHashSet::len(self)
}
fn contains(&self, v: Vertex) -> bool {
FnvHashSet::contains(self, &v)
}
fn difference_collect(&self, other: &Self) -> Self {
self.difference(other).copied().collect()
}
fn is_disjoint(&self, other: &Self) -> bool {
FnvHashSet::is_disjoint(self, other)
}
fn intersection_size(&self, other: &Self) -> usize {
self.intersection(other).count()
}
fn intersection_collect(&self, other: &Self) -> Self {
self.intersection(other).copied().collect()
}
fn reserve(&mut self, additional: usize) {
FnvHashSet::reserve(self, additional)
}
fn insert(&mut self, v: Vertex) {
FnvHashSet::insert(self, v);
}
fn remove(&mut self, v: Vertex) {
FnvHashSet::remove(self, &v);
}
fn pop_arbitrary(&mut self) -> Option<Vertex> {
let elt = self.iter().next().copied()?;
self.take(&elt)
}
fn choose_arbitrary(&self) -> Option<&Vertex> {
self.iter().next()
}
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex> {
self.iter().choose(rng)
}
fn clear(&mut self) {
FnvHashSet::clear(self)
}
fn all<F>(&self, f: F) -> bool
where
F: FnMut(&Vertex) -> bool,
{
self.iter().all(f)
}
fn for_each<F>(&self, mut f: F)
where
F: FnMut(Vertex),
{
for &v in self {
f(v);
}
}
}
impl VertexSetLike for hashbrown::HashSet<Vertex> {
fn new() -> Self {
hashbrown::HashSet::new()
}
fn with_capacity(capacity: usize) -> Self {
hashbrown::HashSet::with_capacity(capacity)
}
fn is_empty(&self) -> bool {
hashbrown::HashSet::is_empty(self)
}
fn len(&self) -> usize {
hashbrown::HashSet::len(self)
}
fn contains(&self, v: Vertex) -> bool {
hashbrown::HashSet::contains(self, &v)
}
fn difference_collect(&self, other: &Self) -> Self {
self.difference(other).copied().collect()
}
fn is_disjoint(&self, other: &Self) -> bool {
hashbrown::HashSet::is_disjoint(self, other)
}
fn intersection_size(&self, other: &Self) -> usize {
self.intersection(other).count()
}
fn intersection_collect(&self, other: &Self) -> Self {
self.intersection(other).copied().collect()
}
fn reserve(&mut self, additional: usize) {
hashbrown::HashSet::reserve(self, additional)
}
fn insert(&mut self, v: Vertex) {
hashbrown::HashSet::insert(self, v);
}
fn remove(&mut self, v: Vertex) {
hashbrown::HashSet::remove(self, &v);
}
fn pop_arbitrary(&mut self) -> Option<Vertex> {
let elt = self.iter().next().copied()?;
self.take(&elt)
}
fn choose_arbitrary(&self) -> Option<&Vertex> {
self.iter().next()
}
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex> {
self.iter().choose(rng)
}
fn clear(&mut self) {
hashbrown::HashSet::clear(self)
}
fn all<F>(&self, f: F) -> bool
where
F: FnMut(&Vertex) -> bool,
{
self.iter().all(f)
}
fn for_each<F>(&self, mut f: F)
where
F: FnMut(Vertex),
{
for &v in self {
f(v);
}
}
}
impl VertexSetLike for Vec<Vertex> {
fn new() -> Self {
Vec::new()
}
fn with_capacity(capacity: usize) -> Self {
Vec::with_capacity(capacity)
}
fn is_empty(&self) -> bool {
Vec::is_empty(self)
}
fn len(&self) -> usize {
Vec::len(self)
}
fn contains(&self, v: Vertex) -> bool {
self.binary_search(&v).is_ok()
}
fn difference_collect(&self, other: &Self) -> Self {
self.iter()
.filter(|&v| !other.contains(*v))
.copied()
.collect()
}
fn is_disjoint(&self, other: &Self) -> bool {
if self.len() > other.len() {
return other.is_disjoint(self);
}
!self.iter().any(|v| other.contains(*v))
}
fn intersection_size(&self, other: &Self) -> usize {
if self.len() > other.len() {
return other.intersection_size(self);
}
self.iter().filter(|&v| other.contains(*v)).count()
}
fn intersection_collect(&self, other: &Self) -> Self {
if self.len() > other.len() {
return other.intersection_collect(self);
}
self.iter()
.filter(|&v| other.contains(*v))
.copied()
.collect()
}
fn reserve(&mut self, additional: usize) {
Vec::reserve(self, additional)
}
fn insert(&mut self, v: Vertex) {
if let Err(idx) = self.binary_search(&v) {
self.insert(idx, v);
}
}
fn remove(&mut self, v: Vertex) {
if let Ok(idx) = self.binary_search(&v) {
self.remove(idx);
}
}
fn pop_arbitrary(&mut self) -> Option<Vertex> {
self.pop()
}
fn choose_arbitrary(&self) -> Option<&Vertex> {
self.last()
}
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex> {
self.as_slice().choose(rng)
}
fn clear(&mut self) {
Vec::clear(self)
}
fn all<F>(&self, f: F) -> bool
where
F: FnMut(&Vertex) -> bool,
{
self.iter().all(f)
}
fn for_each<F>(&self, mut f: F)
where
F: FnMut(Vertex),
{
for &v in self {
f(v);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_pop_arbitrary<VertexSet: VertexSetLike>() {
let mut s = VertexSet::new();
s.insert(Vertex::new(4));
s.insert(Vertex::new(2));
assert!(s.pop_arbitrary().is_some());
assert_eq!(s.len(), 1);
assert!(s.pop_arbitrary().is_some());
assert_eq!(s.len(), 0);
assert!(s.pop_arbitrary().is_none());
assert_eq!(s.len(), 0);
}
#[test]
fn test_btreeset_pop_arbitrary() {
test_pop_arbitrary::<BTreeSet<Vertex>>()
}
#[test]
fn test_hashset_pop_arbitrary() {
test_pop_arbitrary::<HashSet<Vertex>>()
}
#[test]
fn test_fnvhashset_pop_arbitrary() {
test_pop_arbitrary::<FnvHashSet<Vertex>>()
}
#[test]
fn test_hashbrownhashset_pop_arbitrary() {
test_pop_arbitrary::<HashSet<Vertex>>()
}
#[test]
fn test_vector_pop_arbitrary() {
test_pop_arbitrary::<Vec<Vertex>>()
}
}
<file_sep>from stats import SampleStatistics
from hypothesis import given
from hypothesis.strategies import floats, lists
from math import isnan, sqrt
from typing import Sequence
import pytest
def test_stats_0_i32() -> None:
s = SampleStatistics()
assert isnan(s.mean())
assert isnan(s.variance())
assert isnan(s.deviation())
def test_stats_1_int() -> None:
s = SampleStatistics()
s.put(-1)
assert s.mean() == -1.0
assert isnan(s.variance())
assert isnan(s.deviation())
def test_stats_2_int() -> None:
s = SampleStatistics()
s.put(-1)
s.put(1)
assert s.mean() == 0.0
assert s.variance() == 2.0
assert s.deviation() == sqrt(2.0)
def test_stats_3_int() -> None:
s = SampleStatistics()
s.put(89)
s.put(90)
s.put(91)
assert s.mean() == 90.0
assert s.variance() == 1.0
assert s.deviation() == 1.0
def test_stats_9_int() -> None:
s = SampleStatistics()
s.put(2)
s.put(4)
s.put(4)
s.put(4)
s.put(5)
s.put(5)
s.put(5)
s.put(7)
s.put(9)
assert s.mean() == 5.0
assert s.variance() == 4.0
assert s.deviation() == 2.0
def test_stats_2_float() -> None:
s = SampleStatistics()
s.put(1.0)
s.put(2.0)
assert s.mean() == 1.5
assert s.variance() == 0.5
assert s.deviation() == sqrt(0.5)
def test_stats_3_float_deviation_big() -> None:
# found by hypothesis
s = SampleStatistics()
s.put(688338275.2675972)
s.put(688338275.2675972)
s.put(688338275.2675972)
assert s.max == s.min
assert (s.sum_of_squares - s.sum * s.sum / 3) / 2 > 0
def test_stats_3_float_deviation_small() -> None:
# found by hypothesis
s = SampleStatistics()
s.put(1.5765166949677225e-06)
s.put(1.5765166949677225e-06)
s.put(1.5765166949677225e-06)
assert s.max == s.min
assert (s.sum_of_squares - s.sum * s.sum / 3) / 2 > 0
def test_stats_3_float_mean_small() -> None:
# found by hypothesis
s = SampleStatistics()
s.put(-9.020465019382587e+92)
s.put(-9.020465019382587e+92)
s.put(-9.020465019382587e+92)
assert s.sum / s.samples < s.min
assert s.mean() == s.min
@given(lists(floats(min_value=-1e100, max_value=1e100), min_size=2))
def test_stats_floats(samples: Sequence[float]) -> None:
s = SampleStatistics()
for sample in samples:
s.put(sample)
assert s.mean() >= s.min
assert s.mean() <= s.max
assert s.variance() >= 0.
if s.min < s.max:
assert s.deviation() <= s.max - s.min
<file_sep># coding: utf-8
from graph import UndirectedGraph, Vertex
from typing import Generator, List
class PriorityQueue:
def __init__(self, max_priority: int) -> None:
self.stack_per_priority: List[List[int]] = [
[] for _ in range(max_priority + 1)
]
def put(self, priority: int, element: int) -> None:
assert priority >= 0
self.stack_per_priority[priority].append(element)
def pop(self) -> int:
for stack in self.stack_per_priority:
try:
return stack.pop()
except IndexError:
pass
else:
raise ValueError("attempt to pop more than was put")
def degeneracy_ordering(graph: UndirectedGraph,
drop: int = 0) -> Generator[Vertex, None, None]:
"""
Iterate connected vertices, lowest degree first.
drop=N: omit last N vertices
"""
assert drop >= 0
priority_per_node = [-2] * graph.order
max_degree = 0
num_candidates = 0
for c in range(graph.order):
if degree := graph.degree(c):
priority_per_node[c] = degree
max_degree = max(max_degree, degree)
num_candidates += 1
# Possible values of priority_per_node:
# -2: if unconnected (should never come up again)
# -1: when yielded
# 0..max_degree: candidates still queued with priority (degree - #of yielded neighbours)
q = PriorityQueue(max_priority=max_degree)
for c, p in enumerate(priority_per_node):
if p > 0:
q.put(priority=p, element=c)
for _ in range(num_candidates - drop):
i = q.pop()
while priority_per_node[i] == -1:
# was requeued with a more urgent priority and therefore already picked
i = q.pop()
assert priority_per_node[i] >= 0
priority_per_node[i] = -1
yield i
for v in graph.adjacencies[i]:
if (p := priority_per_node[v]) != -1:
assert p > 0
# Requeue with a more urgent priority, but don't bother to remove
# the original entry - it will be skipped if it's reached at all.
priority_per_node[v] = p - 1
q.put(priority=p - 1, element=v)
<file_sep>#pragma once
#include <ranges>
#include <vector>
#include "Util.h"
#include "Vertex.h"
namespace BronKerbosch {
template <typename VertexSet>
class UndirectedGraph {
public:
using Adjacencies = std::vector<VertexSet>;
UndirectedGraph(Adjacencies&& adjacencies) : itsAdjacencies(adjacencies) {
assert(UndirectedGraph::are_valid_adjacencies(itsAdjacencies));
}
unsigned order() const {
return unsigned(itsAdjacencies.size());
}
unsigned size() const {
size_t total = 0;
for (auto neighbours : itsAdjacencies) {
total += neighbours.size();
}
assert(total % 2 == 0);
return unsigned(total / 2);
}
unsigned degree(Vertex v) const {
return unsigned(itsAdjacencies[v].size());
}
VertexSet const& neighbours(Vertex v) const {
return itsAdjacencies[v];
}
VertexSet connected_vertices() const {
auto order = this->order();
auto result = Util::with_capacity<VertexSet>(order);
for (Vertex v = 0; v < order; ++v) {
if (degree(v) > 0) {
result.insert(v);
}
}
return result;
}
Vertex max_degree_vertex() const {
return *std::ranges::max_element(
std::ranges::iota_view{Vertex{0}, Vertex{order()}},
[&](Vertex v, Vertex w) { return degree(v) < degree(w); });
}
static bool are_valid_adjacencies(Adjacencies const& adjacencies) {
auto order = adjacencies.size();
for (Vertex v = 0; v < order; ++v) {
auto const& adjacent_to_v = adjacencies[v];
for (Vertex w : adjacent_to_v) {
if (w == v || w >= order || adjacencies[w].count(v) == 0) {
return false;
}
}
}
return true;
}
private:
Adjacencies itsAdjacencies;
};
}<file_sep>//! Bron-Kerbosch algorithm with pivot of highest degree towards the remaining candidates (IK_GPX)
#pragma once
#include "BronKerboschPivot.h"
namespace BronKerbosch {
class BronKerbosch2GPX {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph) {
return BronKerboschPivot::explore<Reporter>(graph, PivotChoice::MaxDegreeLocalX);
}
};
}
<file_sep>from typing import List, Set, TypeAlias
Vertex: TypeAlias = int
class UndirectedGraph(object):
def __init__(self, adjacencies: List[Set[Vertex]]):
order = len(adjacencies)
for v, adjacent_to_v in enumerate(adjacencies):
for w in adjacent_to_v:
assert 0 <= w < order
assert v != w
assert v in adjacencies[
w], f'{w} is adjacent to {v} but not vice versa'
self.adjacencies = adjacencies
@property
def order(self) -> int:
return len(self.adjacencies)
def size(self) -> int:
total = sum(len(a) for a in self.adjacencies)
assert total % 2 == 0
return total // 2
def degree(self, node: Vertex) -> int:
return len(self.adjacencies[node])
def connected_vertices(self) -> Set[Vertex]:
return {node for node in range(self.order) if self.adjacencies[node]}
<file_sep>#include "pch.h"
#include "VertexPile.h"
<file_sep>package Assert
import "fmt"
func IsFalse(e bool) {
if e {
panic("assertion failed: IsFalse")
}
}
func IsTrue(e bool) {
if !e {
panic("assertion failed: IsTrue")
}
}
func AreEqual(a interface{}, b interface{}) {
if a != b {
panic(fmt.Sprintf("assertion failed: these values are different\n\tA.>%[1]T %[1]v<\n\tB.>%[2]T %[2]v<\n", a, b))
}
}
func AreNotEqual(a interface{}, b interface{}) {
if a == b {
panic(fmt.Sprintf("assertion failed: these values are equal\n\tA.>%v<\n\tB.>%v<\n", a, b))
}
}
func IsNotNull(p interface{}) {
if p == nil {
panic("assertion failed: IsNotNull")
}
}
func IsNull(p interface{}) {
if p != nil {
panic("assertion failed: IsNull")
}
}
func Unreachable() {
panic("shouldn't get here")
}
<file_sep>pub use crate::core::reporter::{Clique, Reporter};
use crate::core::vertex::Vertex;
use std::collections::BTreeSet;
#[derive(Debug, Default)]
pub struct CollectingReporter {
pub cliques: Vec<Clique>,
}
impl Reporter for CollectingReporter {
fn record(&mut self, clique: Clique) {
debug_assert!(clique.len() > 1);
debug_assert_eq!(
clique.iter().copied().collect::<BTreeSet<Vertex>>().len(),
clique.len()
);
self.cliques.push(clique);
}
}
#[derive(Debug, Default)]
pub struct CountingReporter {
pub count: usize,
}
impl Reporter for CountingReporter {
fn record(&mut self, _clique: Clique) {
self.count += 1;
}
}
<file_sep># coding: utf-8
from graph import Vertex, UndirectedGraph
from graph_degeneracy import degeneracy_ordering
from hypothesis import given
from hypothesis.strategies import builds, integers, lists, sets
from typing import Any, List, Set
def is_like_set(lst: List[Any], st: Set[Any]) -> bool:
return len(lst) == len(st) and set(lst) == st
def symmetric_adjacencies(adjac: List[Set[Vertex]]) -> List[Set[Vertex]]:
order = len(adjac)
adjacencies: List[Set[Vertex]] = [set() for _ in range(order)]
for v, neighbours in enumerate(adjac):
for w in neighbours:
if v != w:
adjacencies[v].add(w)
adjacencies[w].add(v)
return adjacencies
def test_degeneracy_ordering_empty() -> None:
g = UndirectedGraph(adjacencies=[])
assert list(degeneracy_ordering(g)) == []
assert list(degeneracy_ordering(g, drop=1)) == []
@given(
builds(
symmetric_adjacencies,
integers(min_value=1,
max_value=99).flatmap(lambda order: lists(sets(
integers(min_value=0, max_value=order - 1)),
min_size=order,
max_size=order))))
def test_degeneracy_ordering_nonempty(adjacencies: List[Set[Vertex]]) -> None:
g = UndirectedGraph(adjacencies=adjacencies)
connected_vertices = g.connected_vertices()
ordering = list(degeneracy_ordering(g))
assert set(ordering) == connected_vertices
assert all(g.degree(ordering[0]) <= g.degree(v) for v in ordering[1:])
ordering_min1 = list(degeneracy_ordering(g, drop=1))
assert ordering_min1 == ordering[:-1]
<file_sep>package Stats
import (
"BronKerboschStudy/Assert"
"math"
"testing"
)
func TestStats0(t *testing.T) {
var s SampleStatistics
Assert.IsTrue(math.IsNaN(s.Mean()))
Assert.IsTrue(math.IsNaN(s.Variance()))
Assert.IsTrue(math.IsNaN(s.Deviation()))
}
func TestStats1(t *testing.T) {
var s SampleStatistics
s.Put(-1)
Assert.AreEqual(s.Mean(), -1.0)
Assert.IsTrue(math.IsNaN(s.Variance()))
Assert.IsTrue(math.IsNaN(s.Deviation()))
}
func TestStats2(t *testing.T) {
var s SampleStatistics
s.Put(1.0)
s.Put(2.0)
Assert.AreEqual(s.Mean(), 1.5)
Assert.AreEqual(s.Variance(), 0.5)
Assert.AreEqual(s.Deviation(), math.Sqrt(0.5))
}
func TestStats3(t *testing.T) {
var s SampleStatistics
s.Put(89)
s.Put(90)
s.Put(91)
Assert.AreEqual(s.Mean(), 90.0)
Assert.AreEqual(s.Variance(), 1.0)
Assert.AreEqual(s.Deviation(), 1.0)
}
func TestStats9(t *testing.T) {
var s SampleStatistics
s.Put(2)
s.Put(4)
s.Put(4)
s.Put(4)
s.Put(5)
s.Put(5)
s.Put(5)
s.Put(7)
s.Put(9)
Assert.AreEqual(s.Mean(), 5.0)
Assert.AreEqual(s.Variance(), 4.0)
Assert.AreEqual(s.Deviation(), 2.0)
}
func FuzzStats1(f *testing.F) {
f.Add(1.)
f.Fuzz(func(t *testing.T, x float64) {
var s SampleStatistics
s.Put(x)
Assert.IsTrue(s.Mean() == x)
})
}
func FuzzStats2(f *testing.F) {
f.Add(1., 2.)
f.Fuzz(func(t *testing.T, x float64, y float64) {
var s SampleStatistics
s.Put(x)
s.Put(y)
Assert.IsTrue(s.Mean() >= s.Min())
Assert.IsTrue(s.Mean() <= s.Max())
Assert.IsTrue(s.Variance() >= 0.)
Assert.IsTrue(s.Deviation() <= (s.Max()-s.Min())*1.5)
})
}
func FuzzStatsN(f *testing.F) {
f.Add(1., uint16(3))
f.Fuzz(func(t *testing.T, x float64, n uint16) {
if n < 3 {
t.Skip()
return
}
var s SampleStatistics
for i := n; i > 0; i-- {
s.Put(x)
}
Assert.IsTrue(s.Mean() >= s.Min())
Assert.IsTrue(s.Mean() <= s.Max())
Assert.IsTrue(s.Variance() >= 0.)
Assert.IsTrue(s.Deviation() <= (s.Max()-s.Min())*1.5)
})
}
<file_sep>[mypy]
python_version = 3.10
strict = True
<file_sep>//! Core of Bron-Kerbosch algorithms using degeneracy ordering.
use super::bron_kerbosch_pivot::visit;
pub use super::bron_kerbosch_pivot::PivotChoice;
use super::graph::{UndirectedGraph, VertexSetLike};
use super::graph_degeneracy::degeneracy_ordering;
use super::pile::Pile;
use super::reporter::Reporter;
pub fn explore_with_pivot<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
pivot_selection: PivotChoice,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
let mut excluded = VertexSet::with_capacity(graph.order());
for v in degeneracy_ordering(graph, -1) {
let neighbours = graph.neighbours(v);
debug_assert!(!neighbours.is_empty());
let neighbouring_excluded: VertexSet = neighbours.intersection_collect(&excluded);
if neighbouring_excluded.len() < neighbours.len() {
let neighbouring_candidates: VertexSet =
neighbours.difference_collect(&neighbouring_excluded);
visit(
graph,
reporter,
pivot_selection,
neighbouring_candidates,
neighbouring_excluded,
Some(&Pile::from(v)),
);
}
excluded.insert(v);
}
}
<file_sep>#include "pch.h"
#include "BronKerbosch/Portfolio.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BronKerbosch {
TEST_CLASS(BronKerboschUnitTest) {
public:
template <typename VertexSet>
static void bk_core(std::vector<std::vector<Vertex>> const& adjacencies_in,
std::vector<std::vector<Vertex>> const& expected_cliques) {
auto adjacencies = std::vector<VertexSet>{};
adjacencies.resize(adjacencies_in.size());
std::transform(
adjacencies_in.begin(), adjacencies_in.end(), adjacencies.begin(),
[](std::vector<Vertex> const& v) { return VertexSet(v.begin(), v.end()); });
auto graph = UndirectedGraph<VertexSet>{std::move(adjacencies)};
for (int func_index = 0; func_index < Portfolio::NUM_FUNCS; ++func_index) {
auto result = Portfolio::explore<Portfolio::CollectingReporter, VertexSet>(func_index, graph);
auto obtained_cliques = std::vector<VertexList>(result.begin(), result.end());
Assert::AreEqual(expected_cliques.size(), obtained_cliques.size());
Portfolio::sort_cliques(obtained_cliques);
assert_same_cliques(expected_cliques, obtained_cliques);
}
}
static void bk(std::vector<std::vector<Vertex>>&& adjacencies_in,
std::vector<std::vector<Vertex>>&& expected_cliques) {
bk_core<std::set<Vertex>>(adjacencies_in, expected_cliques);
bk_core<ordered_vector<Vertex>>(adjacencies_in, expected_cliques);
bk_core<std::unordered_set<Vertex>>(adjacencies_in, expected_cliques);
}
static void assert_same_cliques(std::vector<std::vector<Vertex>> const& lhs,
std::vector<std::vector<Vertex>> const& rhs) {
Assert::AreEqual(lhs.size(), rhs.size());
for (size_t i = 0; i < lhs.size(); ++i) {
Assert::AreEqual(lhs[i].size(), rhs[i].size());
for (size_t j = 0; j < lhs[i].size(); ++j) {
Assert::AreEqual(lhs[i][j], rhs[i][j]);
}
}
}
TEST_METHOD(TestOrder0) {
bk({}, {});
}
TEST_METHOD(TestOrder1) {
bk({{}}, {});
}
TEST_METHOD(TestOrder2_Isolated) {
bk({{}, {}}, {});
}
TEST_METHOD(TestOrder2_Connected) {
bk({{1}, {0}}, {{0, 1}});
}
TEST_METHOD(TestOrder3_Size1_Left) {
bk({{1}, {0}, {}}, {{0, 1}});
}
TEST_METHOD(TestOrder3_Size1_Long) {
bk({{2}, {}, {0}}, {{0, 2}});
}
TEST_METHOD(TestOrder3_Size1_Right) {
bk({{}, {2}, {1}}, {{1, 2}});
}
TEST_METHOD(TestOrder3_Size2) {
bk({{1}, {0, 2}, {1}}, {{0, 1}, {1, 2}});
}
TEST_METHOD(TestOrder3_Size3) {
bk({{1, 2}, {0, 2}, {0, 1}}, {{0, 1, 2}});
}
TEST_METHOD(TestOrder4_Size2) {
bk({{1}, {0}, {3}, {2}}, {{0, 1}, {2, 3}});
}
TEST_METHOD(TestOrder4_Size3_Bus) {
bk({{1}, {0, 2}, {1, 3}, {2}}, {{0, 1}, {1, 2}, {2, 3}});
}
TEST_METHOD(TestOrder4_Size3_Star) {
bk({{1, 2, 3}, {0}, {0}, {0}}, {{0, 1}, {0, 2}, {0, 3}});
}
TEST_METHOD(TestOrder4_Size4_p) {
bk({{1}, {0, 2, 3}, {1, 3}, {1, 2}}, {{0, 1}, {1, 2, 3}});
}
TEST_METHOD(TestOrder4_Size4_Square) {
bk({{1, 3}, {0, 2}, {1, 3}, {0, 2}}, {{0, 1}, {0, 3}, {1, 2}, {2, 3}});
}
TEST_METHOD(TestOrder4_Size5) {
bk({{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}}, {{0, 1, 2}, {0, 2, 3}});
}
TEST_METHOD(TestOrder4_Size6) {
bk({{1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2}}, {{0, 1, 2, 3}});
}
TEST_METHOD(TestOrder4_Size6_Penultimate) {
bk({{1, 2, 3, 4}, {0, 2, 3, 4}, {0, 1, 3, 4}, {0, 1, 2}, {0, 1, 2}},
{{0, 1, 2, 3}, {0, 1, 2, 4}});
}
TEST_METHOD(TestSample) {
// clang-format off
bk({
{ },
{ 2, 3, 4 },
{ 1, 3, 4, 5 },
{ 1, 2, 4, 5 },
{ 1, 2, 3 },
{ 2, 3, 6, 7 },
{ 5, 7 },
{ 5, 6 } },
{
{ 1, 2, 3, 4 },
{ 2, 3, 5 },
{ 5, 6, 7 } });
// clang-format on
}
TEST_METHOD(TestBigger) {
// clang-format off
bk({
{ 1, 2, 3, 4, 6, 7},
{ 0, 3, 6, 7, 8, 9 },
{ 0, 3, 5, 7, 8, 9 },
{ 0, 1, 2, 4, 9 },
{ 0, 3, 6, 7, 9 },
{ 2, 6 },
{ 0, 1, 4, 5, 9 },
{ 0, 1, 2, 4, 9 },
{ 1, 2 },
{ 1, 2, 3, 4, 6, 7 } },
{
{ 0, 1, 3 },
{ 0, 1, 6 },
{ 0, 1, 7 },
{ 0, 2, 3 },
{ 0, 2, 7 },
{ 0, 3, 4 },
{ 0, 4, 6 },
{ 0, 4, 7 },
{ 1, 3, 9 },
{ 1, 6, 9 },
{ 1, 7, 9 },
{ 1, 8 },
{ 2, 3, 9 },
{ 2, 5 },
{ 2, 7, 9 },
{ 2, 8 },
{ 3, 4, 9 },
{ 4, 6, 9 },
{ 4, 7, 9 },
{ 5, 6 } });
// clang-format on
}
};
}
<file_sep>[package]
name = "stats"
version = "1.0.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2021"
[dev-dependencies]
proptest = "1.0.0"
<file_sep>#pragma once
#include <stdexcept>
#include <vector>
#include "UndirectedGraph.h"
namespace BronKerbosch {
template <typename VertexSet>
class DegeneracyOrderIter {
private:
using Priority = unsigned;
static Priority const PRIORITY_NONE = 0;
template <typename T>
struct PriorityQueue {
std::vector<std::vector<T>> stack_per_priority;
PriorityQueue(Priority max_priority)
: stack_per_priority(std::vector<std::vector<T>>(max_priority)) {
}
void put(Priority priority, T element) {
assert(priority != PRIORITY_NONE);
stack_per_priority[priority - 1].push_back(element);
}
T pop() {
for (auto& stack : stack_per_priority) {
if (!stack.empty()) {
T last = *stack.rbegin();
stack.pop_back();
return last;
}
}
throw std::logic_error("cannot pop more than has been put");
}
bool contains(Priority priority, T element) const {
assert(priority != PRIORITY_NONE);
#ifdef NDEBUG
throw std::logic_error("not suitable for use in release code");
#endif
auto const& stack = stack_per_priority[priority - 1];
return std::find(stack.begin(), stack.end(), element) != stack.end();
}
};
UndirectedGraph<VertexSet> const& graph;
std::vector<Priority> priority_per_vertex;
// If priority is PRIORITY_NONE, vertex was already picked or was always irrelevant
// (unconnected); otherwise, vertex is still queued and priority = degree - number of picked
// neighbours +1. +1 because we want the priority number to be NonZero to allow free
// wrapping inside Option.
PriorityQueue<Vertex> queue;
int num_left_to_pick;
DegeneracyOrderIter(UndirectedGraph<VertexSet> const& graph,
std::vector<Priority>&& priority_per_vertex,
PriorityQueue<Vertex>&& queue,
int num_left_to_pick)
: graph(graph),
priority_per_vertex(priority_per_vertex),
queue(queue),
num_left_to_pick(num_left_to_pick) {
}
public:
static DegeneracyOrderIter degeneracy_ordering(UndirectedGraph<VertexSet> const& graph,
int drop = 0) {
assert(drop <= 0);
auto order = graph.order();
std::vector<Priority> priority_per_vertex(size_t(order), PRIORITY_NONE);
Priority max_priority = PRIORITY_NONE;
int num_candidates = 0;
for (Vertex c = 0; c < order; ++c) {
auto degree = graph.degree(c);
if (degree > 0) {
Priority priority = degree + 1;
priority_per_vertex[c] = priority;
if (max_priority < priority) {
max_priority = priority;
}
assert(max_priority != PRIORITY_NONE);
num_candidates += 1;
}
}
PriorityQueue<Vertex> queue{max_priority};
for (Vertex c = 0; c < order; ++c) {
Priority priority = priority_per_vertex[c];
if (priority != PRIORITY_NONE) {
queue.put(priority, c);
}
}
return DegeneracyOrderIter{graph, std::move(priority_per_vertex), std::move(queue),
std::max(0, num_candidates + drop)};
}
bool invariant() const {
auto order = priority_per_vertex.size();
for (Vertex v = 0; v < order; ++v) {
Priority p = priority_per_vertex[v];
if (p == PRIORITY_NONE) {
// might still be in some stack
} else if (!queue.contains(p, v)) {
return false;
}
}
return true;
}
Vertex pick_with_lowest_degree() {
assert(invariant());
for (;;) {
Vertex v = queue.pop();
if (priority_per_vertex[v] != PRIORITY_NONE) {
priority_per_vertex[v] = PRIORITY_NONE;
return v;
}
// else v was requeued with a more urgent priority and therefore already picked
}
}
bool has_next() const {
return num_left_to_pick > 0;
}
std::optional<Vertex> next() {
if (num_left_to_pick > 0) {
num_left_to_pick -= 1;
Vertex i = pick_with_lowest_degree();
for (Vertex v : graph.neighbours(i)) {
Priority old_priority = priority_per_vertex[v];
if (old_priority != PRIORITY_NONE) {
// Since this is an unvisited neighbour of a vertex just being picked,
// its priority can't be down to the minimum.
Priority new_priority = old_priority - 1;
assert(new_priority != PRIORITY_NONE);
// Requeue with a more urgent priority, but don't bother to remove
// the original entry - it will be skipped if it's reached at all.
priority_per_vertex[v] = new_priority;
queue.put(new_priority, v);
}
}
return std::make_optional(i);
} else {
return std::optional<Vertex>{};
}
}
};
}
<file_sep>#include "pch.h"
#include "BronKerbosch3MT.h"
<file_sep>from math import isfinite, isnan, nan, sqrt
class SampleStatistics(object):
def __init__(self) -> None:
self.max = nan
self.min = nan
self.samples: int = 0
self.sum: float = 0
self.sum_of_squares: float = 0
def put(self, v: float) -> None:
if self.samples == 0:
self.min = v
self.max = v
elif self.min > v:
self.min = v
elif self.max < v:
self.max = v
self.samples += 1
self.sum += v
self.sum_of_squares += v * v
def mean(self) -> float:
if self.samples > 0 and isfinite(self.sum):
r = self.sum / self.samples
return max(self.min, min(self.max, r))
else:
return nan
def variance(self) -> float:
if self.samples > 1 and isfinite(self.sum_of_squares):
n = self.samples
r = (self.sum_of_squares - self.sum * self.sum / n) / (n - 1)
return max(0, r)
else:
return nan
def deviation(self) -> float:
r = sqrt(self.variance())
if isnan(r):
return nan
else:
return min(self.max - self.min, r)
<file_sep>package Stats
import (
"math"
)
type SampleStatistics struct {
max float64
min float64
samples int
sum float64
sumOfSquares float64
}
func (s *SampleStatistics) Put(v float64) {
if s.samples == 0 {
s.min = v
s.max = v
} else if s.min > v {
s.min = v
} else if s.max < v {
s.max = v
}
s.samples++
s.sum += v
s.sumOfSquares += v * v
}
func (s *SampleStatistics) Max() float64 {
return s.max
}
func (s *SampleStatistics) Min() float64 {
return s.min
}
func (s *SampleStatistics) Mean() float64 {
r := s.sum / float64(s.samples)
if r < s.min {
return s.min
}
if r > s.max {
return s.max
}
return r
}
func (s *SampleStatistics) Variance() float64 {
n := float64(s.samples)
r := (s.sumOfSquares - s.sum*s.sum/n) / (n - 1)
if r < 0 {
return 0
}
return r
}
func (s *SampleStatistics) Deviation() float64 {
r := math.Sqrt(s.Variance())
m := s.max - s.min
if r > m {
return m
}
return r
}
<file_sep># coding: utf-8
from bron_kerbosch_pivot import visit
from graph import UndirectedGraph, Vertex
from graph_degeneracy import degeneracy_ordering
from reporter import Reporter
from typing import Set
def explore(graph: UndirectedGraph, reporter: Reporter) -> None:
"""Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
choosing a pivot from candidates only (IK_GP)"""
# In this initial iteration, we don't need to represent the set of candidates
# because all neighbours are candidates until excluded.
excluded: Set[Vertex] = set()
for v in degeneracy_ordering(graph=graph, drop=1):
neighbours = graph.adjacencies[v]
assert neighbours
neighbouring_excluded = neighbours.intersection(excluded)
if len(neighbouring_excluded) < len(neighbours):
neighbouring_candidates = neighbours.difference(
neighbouring_excluded)
visit(graph=graph,
reporter=reporter,
pivot_choice_X=False,
candidates=neighbouring_candidates,
excluded=neighbouring_excluded,
clique=[v])
else:
assert not excluded.isdisjoint(neighbours)
excluded.add(v)
<file_sep>#pragma once
void console_init();<file_sep>#pragma once
#include <set>
#include <unordered_set>
namespace BronKerbosch {
template <typename T>
class ordered_vector {
std::vector<T> vals;
public:
using size_type = typename std::vector<T>::size_type;
using iterator = typename std::vector<T>::iterator;
using const_iterator = typename std::vector<T>::const_iterator;
using value_type = T;
ordered_vector() = default;
ordered_vector(std::initializer_list<T>&& list) : vals(list) {
assert(std::is_sorted(begin(), end()));
}
template <typename I>
ordered_vector(I begin, I end) : vals(begin, end) {
std::sort(vals.begin(), vals.end());
}
size_type size() const {
return vals.size();
}
bool empty() const {
return vals.empty();
}
size_t count(T val) const {
auto pos = std::lower_bound(vals.begin(), vals.end(), val);
auto found = pos != vals.end() && *pos == val;
return found ? 1 : 0;
}
bool operator==(ordered_vector const& rhs) const {
return vals == rhs.vals;
}
iterator insert(iterator pos, T val) {
return vals.insert(pos, val);
}
std::pair<iterator, bool> insert(T val) {
auto pos = std::lower_bound(vals.begin(), vals.end(), val);
auto found = pos != vals.end() && *pos == val;
if (!found) {
vals.insert(pos, val);
}
return std::make_pair(pos, !found);
}
bool erase(T val) {
auto pos = std::lower_bound(vals.begin(), vals.end(), val);
auto found = pos != vals.end() && *pos == val;
if (found) {
vals.erase(pos);
}
return found;
}
void erase(iterator pos) {
assert(pos != vals.end());
vals.erase(pos);
}
void reserve(size_t capacity) {
vals.reserve(capacity);
}
const_iterator begin() const {
return vals.begin();
}
const_iterator end() const {
return vals.end();
}
iterator begin() {
return vals.begin();
}
iterator end() {
return vals.end();
}
};
namespace Util {
template <typename T>
static T pop_arbitrary(std::set<T>& set) {
assert(!set.empty());
auto it = set.begin();
auto result = *it;
set.erase(it);
return result;
}
template <typename T>
static T pop_arbitrary(ordered_vector<T>& set) {
assert(!set.empty());
auto it = set.end() - 1;
auto result = *it;
set.erase(it);
return result;
}
template <typename T>
static T pop_arbitrary(std::unordered_set<T>& set) {
assert(!set.empty());
auto it = set.begin();
auto result = *it;
set.erase(it);
return result;
}
template <typename T>
static bool are_disjoint(std::set<T> const& lhs, std::set<T> const& rhs) {
auto lit = lhs.begin();
auto rit = rhs.begin();
while (lit != lhs.end() && rit != rhs.end()) {
if (*lit < *rit) {
++lit;
} else if (*rit < *lit) {
++rit;
} else {
return false;
}
}
return true;
}
template <typename T>
static bool are_disjoint(ordered_vector<T> const& lhs, ordered_vector<T> const& rhs) {
auto lit = lhs.begin();
auto rit = rhs.begin();
while (lit != lhs.end() && rit != rhs.end()) {
if (*lit < *rit) {
++lit;
} else if (*rit < *lit) {
++rit;
} else {
return false;
}
}
return true;
}
template <typename T>
static bool are_disjoint(std::unordered_set<T> const& lhs,
std::unordered_set<T> const& rhs) {
if (lhs.size() > rhs.size()) {
return are_disjoint(rhs, lhs);
}
for (auto elt : lhs) {
if (rhs.count(elt)) {
return false;
}
}
return true;
}
template <typename T>
static size_t intersection_size(std::set<T> const& lhs, std::set<T> const& rhs) {
size_t count = 0;
auto lit = lhs.begin();
auto rit = rhs.begin();
while (lit != lhs.end() && rit != rhs.end()) {
if (*lit < *rit) {
++lit;
} else if (*rit < *lit) {
++rit;
} else {
++count;
++lit;
++rit;
}
}
return count;
}
template <typename T>
static size_t intersection_size(ordered_vector<T> const& lhs,
ordered_vector<T> const& rhs) {
size_t count = 0;
auto lit = lhs.begin();
auto rit = rhs.begin();
while (lit != lhs.end() && rit != rhs.end()) {
if (*lit < *rit) {
++lit;
} else if (*rit < *lit) {
++rit;
} else {
++count;
++lit;
++rit;
}
}
return count;
}
template <typename T>
static size_t intersection_size(std::unordered_set<T> const& lhs,
std::unordered_set<T> const& rhs) {
if (lhs.size() > rhs.size()) {
return intersection_size(rhs, lhs);
}
size_t count = 0;
for (auto elt : lhs) {
count += rhs.count(elt);
}
return count;
}
template <typename T>
static std::set<T> intersection(std::set<T> const& lhs, std::set<T> const& rhs) {
std::set<T> result;
std::set_intersection(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(),
std::inserter(result, result.end()));
return result;
}
template <typename T>
static ordered_vector<T> intersection(ordered_vector<T> const& lhs,
ordered_vector<T> const& rhs) {
ordered_vector<T> result;
result.reserve(std::min(lhs.size(), rhs.size()));
std::set_intersection(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(),
std::inserter(result, result.end()));
return result;
}
template <typename T>
static std::unordered_set<T> intersection(std::unordered_set<T> const& lhs,
std::unordered_set<T> const& rhs) {
if (lhs.size() > rhs.size()) {
return intersection(rhs, lhs);
}
std::unordered_set<T> result;
result.reserve(lhs.size());
for (auto elt : lhs) {
if (rhs.count(elt)) {
result.insert(elt);
}
}
return result;
}
template <typename T>
static std::set<T> difference(std::set<T> const& lhs, std::set<T> const& rhs) {
std::set<T> result;
std::set_difference(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(),
std::inserter(result, result.end()));
return result;
}
template <typename T>
static ordered_vector<T> difference(ordered_vector<T> const& lhs,
ordered_vector<T> const& rhs) {
ordered_vector<T> result;
result.reserve(lhs.size());
std::set_difference(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(),
std::inserter(result, result.end()));
return result;
}
template <typename T>
static std::unordered_set<T> difference(std::unordered_set<T> const& lhs,
std::unordered_set<T> const& rhs) {
std::unordered_set<T> result;
result.reserve(lhs.size());
for (auto elt : lhs) {
if (rhs.count(elt) == 0) {
result.insert(elt);
}
}
return result;
}
template <typename T>
static void reserve(std::set<T>&, size_t) {
}
template <typename T>
static void reserve(ordered_vector<T>& set, size_t capacity) {
set.reserve(capacity);
}
template <typename T>
static void reserve(std::unordered_set<T>& set, size_t capacity) {
set.reserve(capacity);
}
template <typename Set>
static Set with_capacity(size_t capacity) {
Set result;
reserve(result, capacity);
return result;
}
}
}
<file_sep># coding: utf-8
from graph import UndirectedGraph, Vertex
from reporter import Reporter
from typing import List, Set
def explore(graph: UndirectedGraph, reporter: Reporter) -> None:
"""Naive Bron-Kerbosch algorithm, optimized"""
if candidates := graph.connected_vertices():
visit(graph=graph,
reporter=reporter,
candidates=candidates,
excluded=set(),
clique=[])
def visit(graph: UndirectedGraph, reporter: Reporter, candidates: Set[Vertex],
excluded: Set[Vertex], clique: List[Vertex]) -> None:
assert all(graph.degree(v) > 0 for v in candidates)
assert all(graph.degree(v) > 0 for v in excluded)
assert candidates.isdisjoint(excluded)
assert candidates
while candidates:
v = candidates.pop()
neighbours = graph.adjacencies[v]
neighbouring_candidates = candidates.intersection(neighbours)
if neighbouring_candidates:
neighbouring_excluded = excluded.intersection(neighbours)
visit(graph,
reporter,
candidates=neighbouring_candidates,
excluded=neighbouring_excluded,
clique=clique + [v])
elif excluded.isdisjoint(neighbours):
reporter.record(clique + [v])
excluded.add(v)
<file_sep>use super::*;
use crate::core::graph::{connected_vertices, UndirectedGraph};
use crate::core::graph_degeneracy::degeneracy_ordering;
use proptest::prelude::*;
use proptest::test_runner::{Config, TestRunner};
type VertexSet = std::collections::BTreeSet<Vertex>;
#[cfg(not(miri))]
#[test]
pub fn test_degeneracy_order() {
TestRunner::new(Config {
cases: 1968,
..Config::default()
})
.run(
&(2..99usize).prop_flat_map(|order| {
proptest::collection::vec(
// The vector is indexed by a source vertex and lists a set of destination vertices,
// in which we'll skip any vertex numbers less than or equal to the source vertex.
// We'll then reflect each vertex pair to make the adjacencies symmetric.
proptest::collection::btree_set(0..order, ..order - 1),
// No point in listing the last vertex, it cannot contribute more neighbours.
order - 1,
)
}),
|adjac| {
let order = adjac.len() + 1;
let mut adjacencies = Adjacencies::new(VertexSet::new(), order);
for (v, adjacent_to_v) in adjac.iter().enumerate() {
for &w in adjacent_to_v {
if w > v {
let w = Vertex::new(w);
let v = Vertex::new(v);
adjacencies[v].insert(w);
adjacencies[w].insert(v);
}
}
}
let g = SlimUndirectedGraph::new(adjacencies);
let connected = connected_vertices(&g);
let ordering = Vec::from_iter(degeneracy_ordering(&g, 0));
let ordering_set = VertexSet::from_iter(ordering.iter().copied());
assert_eq!(ordering.len(), ordering_set.len(), "duplicates in ordering");
assert_eq!(ordering_set, connected);
if let Some(&first) = ordering.first() {
for &v in &ordering {
assert!(g.degree(first) <= g.degree(v));
}
}
let orderin = Vec::from_iter(degeneracy_ordering(&g, -1));
assert_eq!(orderin, ordering[..connected.len().saturating_sub(1)]);
Ok(())
},
)
.unwrap();
}
<file_sep>package BronKerbosch
import (
"fmt"
)
type UndirectedGraph struct {
adjacencies []VertexSet
}
func NewUndirectedGraph(adjacencies []VertexSet) UndirectedGraph {
for i, adjacentToV := range adjacencies {
v := Vertex(i)
for w := range adjacentToV {
if v == w {
panic(fmt.Sprintf("%d is adjacent to itself", v))
}
if !adjacencies[w].Contains(v) {
panic(fmt.Sprintf("%d is adjacent to %d but not vice versa", w, v))
}
}
}
g := UndirectedGraph{}
g.adjacencies = adjacencies
return g
}
func (g *UndirectedGraph) Order() int {
return len(g.adjacencies)
}
func (g *UndirectedGraph) Size() int {
var total int
for _, neighbours := range g.adjacencies {
total += neighbours.Cardinality()
}
if total%2 != 0 {
panic("symmetry check on initialisation should have enforced even total")
}
return total / 2
}
func (g *UndirectedGraph) neighbours(v Vertex) VertexSet {
return g.adjacencies[v]
}
func (g *UndirectedGraph) degree(v Vertex) int {
return g.adjacencies[v].Cardinality()
}
func (g *UndirectedGraph) connectedVertices() VertexSet {
result := make(VertexSet)
for v, neighbours := range g.adjacencies {
if !neighbours.IsEmpty() {
result.Add(Vertex(v))
}
}
return result
}
func (g *UndirectedGraph) connectedVertexCount() int {
var count int
for _, neighbours := range g.adjacencies {
if !neighbours.IsEmpty() {
count++
}
}
return count
}
func (g *UndirectedGraph) maxDegreeVertex() Vertex {
order := g.Order()
maxDegree := 0
var maxVertex Vertex
for i := 0; i < order; i++ {
v := Vertex(i)
degree := g.degree(v)
if maxDegree < degree {
maxDegree = degree
maxVertex = v
}
}
return maxVertex
}
<file_sep>package StudyIO
import (
"BronKerboschStudy/BronKerbosch"
"bufio"
"fmt"
"os"
"path/filepath"
)
func ReadRandomUndirectedGraph(orderstr string, size int) (BronKerbosch.UndirectedGraph, int, error) {
order, err := ParsePositiveInt(orderstr)
if err != nil {
return BronKerbosch.UndirectedGraph{}, 0, err
}
fullyMeshedSize := order * (order - 1) / 2
if size > fullyMeshedSize {
panic(
fmt.Sprintf("%d nodes accommodate at most %d edges", order, fullyMeshedSize))
}
edgesName := "random_edges_order_" + orderstr + ".txt"
statsName := "random_stats.txt"
edgesPath := filepath.Join("..", "data", edgesName)
statsPath := filepath.Join("..", "data", statsName)
adjacencies, err := readEdges(edgesPath, orderstr, order, size)
if err != nil {
err = fmt.Errorf("%s\nPerhaps generate it with `python -m ..\\python3\\random_graph %s <max_size?>`", err, orderstr)
return BronKerbosch.UndirectedGraph{}, 0, err
}
cliqueCount, err := readStats(statsPath, orderstr, size)
if err != nil {
return BronKerbosch.UndirectedGraph{}, 0, err
}
g := BronKerbosch.NewUndirectedGraph(adjacencies)
if g.Order() != order {
panic("botched order")
}
if g.Size() != size {
panic("botched size")
}
return g, cliqueCount, nil
}
func readEdges(path string, orderstr string, order int, size int) ([]BronKerbosch.VertexSet, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
adjacencies := make([]BronKerbosch.VertexSet, order)
for v := 0; v < order; v++ {
adjacencies[v] = make(BronKerbosch.VertexSet)
}
scanner := bufio.NewScanner(file)
linenum := 0
for scanner.Scan() {
if linenum == size {
break
}
linenum += 1
line := scanner.Text()
var v int
var w int
_, err := fmt.Sscanf(line, "%d %d", &v, &w)
if err != nil {
err = fmt.Errorf("%s in file %s at line %d", err, path, linenum)
return nil, err
}
adjacencies[v].Add(BronKerbosch.Vertex(w))
adjacencies[w].Add(BronKerbosch.Vertex(v))
}
if err := scanner.Err(); err != nil {
return nil, err
}
if linenum < size {
err = fmt.Errorf("Exhausted generated list of %d edges in %s", linenum, path)
return nil, err
}
return adjacencies, nil
}
func readStats(path string, orderstr string, size int) (int, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
format := fmt.Sprintf("%s\t%d\t%%d", orderstr, size)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
var c int
_, err := fmt.Sscanf(line, format, &c)
if err == nil {
return c, nil
}
}
if err := scanner.Err(); err != nil {
return 0, err
}
return 0, fmt.Errorf("File %s lacks order %s size %d", path, orderstr, size)
}
<file_sep>mod random_graph;
use bron_kerbosch::{explore, order_cliques, OrderedCliques, FUNC_NAMES};
use bron_kerbosch::{CollectingReporter, CountingReporter};
use bron_kerbosch::{SlimUndirectedGraph, Vertex, VertexSetLike};
use random_graph::{parse_positive_int, read_undirected, Size};
use stats::SampleStatistics;
use clap::{arg, command};
use fnv::FnvHashSet;
use itertools::Itertools;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::thread;
use std::time::{Duration, Instant};
use strum::IntoEnumIterator;
use strum_macros::{Display, EnumIter, EnumString};
#[derive(Copy, Clone, Debug, Display, EnumIter, EnumString, Eq, PartialEq, Ord, PartialOrd)]
enum SetType {
#[strum(to_string = "Hash")]
HashSet,
#[strum(to_string = "hashbrown")]
Hashbrown,
#[strum(to_string = "fnv")]
Fnv,
#[strum(to_string = "BTree")]
BTreeSet,
#[strum(to_string = "ord_vec")]
OrdVec,
}
const NUM_FUNCS: usize = FUNC_NAMES.len();
type Seconds = f32;
fn bron_kerbosch_timed<VertexSet: VertexSetLike + Clone>(
set_type: SetType,
orderstr: &str,
size: usize,
func_indices: &[usize],
timed_samples: u32,
) -> [SampleStatistics<Seconds>; NUM_FUNCS] {
let instant = Instant::now();
let (graph, known_clique_count) =
read_undirected::<VertexSet, SlimUndirectedGraph<VertexSet>>(orderstr, Size::Of(size))
.unwrap();
let seconds = instant.elapsed().as_secs_f32();
println!(
"{}-based random graph of order {}, {} edges, {} cliques: (generating took {:.3}s)",
set_type,
orderstr,
size,
known_clique_count.map_or("?".to_string(), |c| c.to_string()),
seconds
);
let mut times: [SampleStatistics<Seconds>; NUM_FUNCS] = Default::default();
let mut first: Option<OrderedCliques> = None;
// If we're genuinely sampling, first warm up.
for sample in 0..=timed_samples {
for &func_index in func_indices {
let mut collecting_reporter = CollectingReporter::default();
let mut counting_reporter = CountingReporter::default();
let instant = Instant::now();
if sample == 0 {
explore(func_index, &graph, &mut collecting_reporter);
} else {
explore(func_index, &graph, &mut counting_reporter);
}
let secs: Seconds = instant.elapsed().as_secs_f32();
if sample == 0 {
if timed_samples == 0 || secs >= 3.0 {
println!(" {:10} {}s", FUNC_NAMES[func_index], secs);
}
let current = order_cliques(collecting_reporter.cliques.into_iter());
if let Some(first_result) = first.as_ref() {
if *first_result != current {
eprintln!(
" {:8}: expected {} cliques, obtained {} different cliques",
FUNC_NAMES[func_index],
first_result.len(),
current.len()
);
}
} else {
if let Some(clique_count) = known_clique_count {
if current.len() != clique_count {
eprintln!(
" {:8}: expected {} cliques, obtained {} cliques",
FUNC_NAMES[func_index],
clique_count,
current.len()
);
}
} else {
println!(" {} cliques", current.len());
return times;
}
first = Some(current);
}
} else if let Some(clique_count) = known_clique_count {
if counting_reporter.count != clique_count {
eprintln!(
" {:8}: expected {} cliques, obtained {} cliques",
FUNC_NAMES[func_index], clique_count, counting_reporter.count
);
}
times[func_index].put(secs);
}
}
}
for &func_index in func_indices {
let func_name = FUNC_NAMES[func_index];
let mean = times[func_index].mean();
let reldev = times[func_index].deviation() / mean;
println!("{:10} {:6.3}s ± {:.0}%", func_name, mean, 100.0 * reldev);
}
times
}
fn bk_core(
set_type: SetType,
orderstr: &str,
size: usize,
func_indices: &[usize],
timed_samples: u32,
) -> [SampleStatistics<Seconds>; NUM_FUNCS] {
match set_type {
SetType::BTreeSet => bron_kerbosch_timed::<BTreeSet<Vertex>>(
set_type,
orderstr,
size,
func_indices,
timed_samples,
),
SetType::HashSet => bron_kerbosch_timed::<HashSet<Vertex>>(
set_type,
orderstr,
size,
func_indices,
timed_samples,
),
SetType::Fnv => bron_kerbosch_timed::<FnvHashSet<Vertex>>(
set_type,
orderstr,
size,
func_indices,
timed_samples,
),
SetType::Hashbrown => bron_kerbosch_timed::<hashbrown::HashSet<Vertex>>(
set_type,
orderstr,
size,
func_indices,
timed_samples,
),
SetType::OrdVec => bron_kerbosch_timed::<Vec<Vertex>>(
set_type,
orderstr,
size,
func_indices,
timed_samples,
),
}
}
fn bk(
orderstr: &str,
sizes: impl Iterator<Item = usize>,
timed_samples: u32,
included_funcs: impl Fn(SetType, usize) -> Vec<usize>,
) -> Result<(), std::io::Error> {
const LANGUAGE: &str = "rust";
let sizes = Vec::from_iter(sizes);
let published = sizes.len() > 1;
let name = format!("bron_kerbosch_{LANGUAGE}_order_{orderstr}");
let temppath = Path::new("tmp").with_extension("csv");
{
let mut writer: Option<csv::Writer<File>> = if published {
Some(csv::Writer::from_writer(File::create(&temppath)?))
} else {
None
};
let mut set_types_used = vec![];
for size in sizes {
let mut stats: BTreeMap<SetType, [SampleStatistics<Seconds>; NUM_FUNCS]> =
BTreeMap::new();
for set_type in SetType::iter() {
let func_indices = included_funcs(set_type, size);
if !func_indices.is_empty() {
stats.insert(
set_type,
bk_core(set_type, orderstr, size, &func_indices, timed_samples),
);
}
}
if let Some(wtr) = writer.as_mut() {
if set_types_used.is_empty() {
set_types_used = stats.keys().copied().collect();
assert!(!set_types_used.is_empty());
wtr.write_record(
["Size"].iter().map(|&s| String::from(s)).chain(
set_types_used
.iter()
.cartesian_product(FUNC_NAMES.iter())
.flat_map(|(set_type, name)| {
vec![
format!("{name}@{set_type} min"),
format!("{name}@{set_type} mean"),
format!("{name}@{set_type} max"),
]
}),
),
)?;
}
wtr.write_record(
[size].iter().map(|&i| i.to_string()).chain(
set_types_used
.iter()
.cartesian_product(0..NUM_FUNCS)
.flat_map(|(set_type, func_index)| {
if let Some(s) = &stats
.get(set_type)
.as_ref()
.map(|&s| &s[func_index])
.filter(|&s| !s.is_empty())
{
vec![
s.min().to_string(),
s.mean().to_string(),
s.max().to_string(),
]
} else {
vec![String::new(); 3]
}
}),
),
)?;
}
}
}
if published {
let path = Path::join(Path::new(".."), Path::new(&name).with_extension("csv"));
std::fs::rename(temppath, path)?;
let publish = Path::new("..")
.join(Path::new("python3"))
.join(Path::new("publish.py"));
let rc = std::process::Command::new("python")
.arg(publish)
.arg(LANGUAGE)
.arg(orderstr)
.status()?;
assert!(rc.success());
}
Ok(())
}
fn main() -> Result<(), std::io::Error> {
let matches = command!()
.arg(arg!(-v --ver <VER>).required(false))
.arg(arg!(-s --set <SET>).required(false))
.arg(arg!([order]))
.arg(arg!([size] ... ))
.get_matches();
if !matches.args_present() {
debug_assert!(false, "Run with --release for meaningful measurements");
bk(
"100",
(2_000..=3_000).step_by(50), // max 4_950
5,
|set_type: SetType, _size: usize| -> Vec<usize> {
match set_type {
SetType::HashSet => (0..NUM_FUNCS).collect(),
_ => vec![1, 4, 7, 9],
}
},
)?;
thread::sleep(Duration::from_secs(7));
bk(
"10k",
std::iter::empty()
.chain((1_000..10_000).step_by(1_000))
.chain((10_000..100_000).step_by(10_000))
.chain((100_000..=200_000).step_by(25_000)),
3,
|set_type: SetType, _size: usize| -> Vec<usize> {
match set_type {
SetType::HashSet => (2..=9).collect(),
_ => vec![2, 4, 7, 9],
}
},
)?;
thread::sleep(Duration::from_secs(7));
bk(
"1M",
std::iter::empty()
.chain((10_000..50_000).step_by(10_000))
.chain((50_000..250_000).step_by(50_000))
.chain((250_000..2_000_000).step_by(250_000))
.chain((2_000_000..=5_000_000).step_by(1_000_000)),
//.chain((5_000..=500_000).step_by(495_000)),
3,
|set_type: SetType, size: usize| -> Vec<usize> {
match set_type {
SetType::BTreeSet if size > 3_000_000 => vec![],
SetType::OrdVec if size > 250_000 => vec![],
SetType::OrdVec if size > 100_000 => vec![4],
_ => vec![4, 7, 9],
}
},
)?;
} else if let (Some(order), Some(sizes)) = (
matches.get_one::<String>("order"),
matches.get_many::<String>("size"),
) {
let forced_set_type = matches
.get_one::<String>("set")
.map(|t| SetType::from_str(t).unwrap());
let sizes = sizes.map(|s| parse_positive_int(s.as_str()));
let included_funcs = |set_type: SetType, _size: usize| -> Vec<usize> {
if forced_set_type.is_some() && forced_set_type != Some(set_type) {
vec![]
} else if let Some(&func_index) = matches.get_one::<usize>("ver") {
vec![func_index]
} else {
(0..NUM_FUNCS).collect()
}
};
bk(order, sizes, 0, included_funcs)?;
} else {
eprintln!("Specify order and size(s)")
}
Ok(())
}
<file_sep>package BronKerbosch
func bronKerbosch3gp(graph *UndirectedGraph, reporter Reporter) {
// Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
// choosing a pivot from candidates only (IK_GP).
var ordering SimpleVertexVisitor
degeneracyOrdering(graph, &ordering, -1)
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
excluded := make(VertexSet, len(ordering.vertices))
for _, v := range ordering.vertices {
neighbours := graph.neighbours(v)
neighbouringExcluded := neighbours.Intersection(excluded)
if len(neighbouringExcluded) < len(neighbours) {
neighbouringCandidates := neighbours.Difference(neighbouringExcluded)
visit(
graph, reporter,
MaxDegreeLocal,
neighbouringCandidates,
neighbouringExcluded,
[]Vertex{v})
}
excluded.Add(v)
}
}
<file_sep>using BronKerboschStudy;
using NUnit.Framework;
using System;
namespace BronKerboschStudyUnitTest
{
public class SampleStatisticsTests
{
[Test]
public void Stats_0()
{
var s = new SampleStatistics();
Assert.That(double.IsNaN(s.Mean));
Assert.That(double.IsNaN(s.Variance));
Assert.That(double.IsNaN(s.Deviation));
}
[Test]
public void Stats_1()
{
var s = new SampleStatistics();
s.Put(-1);
Assert.That(s.Mean.Equals(-1));
Assert.That(double.IsNaN(s.Variance));
Assert.That(double.IsNaN(s.Deviation));
}
[Test]
public void Stats_2()
{
var s = new SampleStatistics();
s.Put(-1);
s.Put(1);
Assert.That(s.Mean.Equals(0));
Assert.That(s.Variance.Equals(2));
Assert.That(s.Deviation.Equals(Math.Sqrt(2)));
}
[Test]
public void Stats_3()
{
var s = new SampleStatistics();
s.Put(89);
s.Put(90);
s.Put(91);
Assert.That(s.Mean.Equals(90));
Assert.That(s.Variance.Equals(1));
Assert.That(s.Deviation.Equals(1));
}
[Test]
public void Stats_9()
{
var s = new SampleStatistics();
s.Put(2);
s.Put(4);
s.Put(4);
s.Put(4);
s.Put(5);
s.Put(5);
s.Put(5);
s.Put(7);
s.Put(9);
Assert.That(s.Mean.Equals(5));
Assert.That(s.Variance.Equals(4));
Assert.That(s.Deviation.Equals(2));
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch.study;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
final class SampleStatisticsTest {
@Test
void zero() {
var s = new SampleStatistics();
assertTrue(Double.isNaN(s.mean()));
assertTrue(Double.isNaN(s.variance()));
assertTrue(Double.isNaN(s.deviation()));
}
@Test
void one() {
var s = new SampleStatistics();
s.put(-1);
assertEquals(s.mean(), -1.0);
assertTrue(Double.isNaN(s.variance()));
assertTrue(Double.isNaN(s.deviation()));
}
@Test
void two() {
var s = new SampleStatistics();
s.put(-1);
s.put(1);
assertEquals(s.mean(), 0.0);
assertEquals(s.variance(), 2.0);
assertEquals(s.deviation(), Math.sqrt(2.0));
}
@Test
void three() {
var s = new SampleStatistics();
s.put(89);
s.put(90);
s.put(91);
assertEquals(s.mean(), 90.0);
assertEquals(s.variance(), 1.0);
assertEquals(s.deviation(), 1.0);
}
@Test
void nine() {
var s = new SampleStatistics();
s.put(2);
s.put(4);
s.put(4);
s.put(4);
s.put(5);
s.put(5);
s.put(5);
s.put(7);
s.put(9);
assertEquals(s.mean(), 5.0);
assertEquals(s.variance(), 4.0);
assertEquals(s.deviation(), 2.0);
}
}
<file_sep>//! Core of Bron-Kerbosch algorithms with pivot
#pragma once
#include <cassert>
#include <stdexcept>
#include "CliqueList.h"
#include "UndirectedGraph.h"
#include "VertexPile.h"
namespace BronKerbosch {
enum class PivotChoice {
MaxDegreeLocal,
MaxDegreeLocalX,
};
class BronKerboschPivot {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph,
PivotChoice pivot_choice) {
auto cliques = Reporter::empty();
if (auto const order = graph.order()) {
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
auto excluded = Util::with_capacity<VertexSet>(order);
Vertex const pivot = graph.max_degree_vertex();
for (Vertex v = 0; v < order; ++v) {
auto const& neighbours = graph.neighbours(v);
if (!neighbours.empty() && neighbours.count(pivot) == 0) {
auto neighbouring_excluded = Util::intersection(neighbours, excluded);
if (neighbouring_excluded.size() < neighbours.size()) {
auto neighbouring_candidates =
Util::difference(neighbours, neighbouring_excluded);
auto newclique = VertexPile(v);
Reporter::add_all(
cliques,
visit<Reporter>(graph, pivot_choice, pivot_choice,
std::move(neighbouring_candidates),
std::move(neighbouring_excluded), &newclique));
}
excluded.insert(v);
}
}
}
return cliques;
}
template <typename Reporter, typename VertexSet>
static Reporter::Result visit(UndirectedGraph<VertexSet> const& graph,
PivotChoice initial_pivot_choice,
PivotChoice further_pivot_choice,
VertexSet&& candidates,
VertexSet&& excluded,
VertexPile* clique) {
assert(!candidates.empty());
assert(Util::are_disjoint(candidates, excluded));
auto cliques = Reporter::empty();
if (candidates.size() == 1) {
// Same logic as below, but stripped down for this common case
for (Vertex v : candidates) {
auto const& neighbours = graph.neighbours(v);
if (Util::are_disjoint(neighbours, excluded)) {
Reporter::add_one(cliques, VertexPile(v, clique));
}
}
return cliques;
}
auto pivot = std::numeric_limits<Vertex>::max();
std::vector<Vertex> remaining_candidates;
remaining_candidates.reserve(candidates.size());
// Quickly handle locally unconnected candidates while finding pivot
size_t seen_local_degree = 0;
for (Vertex v : candidates) {
auto const& neighbours = graph.neighbours(v);
auto local_degree = Util::intersection_size(neighbours, candidates);
if (local_degree == 0) {
// Same logic as below, but stripped down
if (Util::are_disjoint(neighbours, excluded)) {
Reporter::add_one(cliques, VertexPile(v, clique));
}
} else {
if (seen_local_degree < local_degree) {
seen_local_degree = local_degree;
pivot = v;
}
remaining_candidates.push_back(v);
}
}
if (remaining_candidates.empty()) {
return cliques;
}
if (initial_pivot_choice == PivotChoice::MaxDegreeLocalX) {
for (Vertex v : excluded) {
auto const& neighbours = graph.neighbours(v);
auto local_degree = Util::intersection_size(neighbours, candidates);
if (seen_local_degree < local_degree) {
seen_local_degree = local_degree;
pivot = v;
}
}
}
assert(!remaining_candidates.empty());
for (Vertex v : remaining_candidates) {
auto const& neighbours = graph.neighbours(v);
if (neighbours.count(pivot) == 0) {
candidates.erase(v);
auto neighbouring_candidates = Util::intersection(neighbours, candidates);
if (neighbouring_candidates.empty()) {
if (Util::are_disjoint(neighbours, excluded)) {
Reporter::add_one(cliques, VertexPile(v, clique));
}
} else {
auto neighbouring_excluded = Util::intersection(neighbours, excluded);
auto newclique = VertexPile(v, clique);
Reporter::add_all(
cliques,
visit<Reporter>(graph, further_pivot_choice, further_pivot_choice,
std::move(neighbouring_candidates),
std::move(neighbouring_excluded), &newclique));
}
excluded.insert(v);
}
}
return cliques;
}
};
}
<file_sep>// Naive Bron-Kerbosch algorithm
package be.steinsomers.bron_kerbosch;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class BronKerbosch1 implements BronKerboschAlgorithm {
@Override
public Stream<int[]> explore(UndirectedGraph graph) {
Stream.Builder<int[]> cliqueStream = Stream.builder();
Set<Integer> candidates = graph.connectedVertices()
.collect(Collectors.toCollection(HashSet::new));
if (!candidates.isEmpty()) {
Set<Integer> excluded = new HashSet<>(candidates.size());
visit(graph, cliqueStream, candidates, excluded, EMPTY_CLIQUE);
}
return cliqueStream.build();
}
private static void visit(UndirectedGraph graph, Consumer<int[]> cliqueConsumer,
Set<Integer> mut_candidates, Set<Integer> mut_excluded,
int[] cliqueInProgress) {
assert mut_candidates.stream().allMatch(v -> graph.degree(v) > 0);
assert mut_excluded.stream().allMatch(v -> graph.degree(v) > 0);
assert util.AreDisjoint(mut_candidates, mut_excluded);
assert !mut_candidates.isEmpty();
while (!mut_candidates.isEmpty()) {
var v = util.PopArbitrary(mut_candidates);
var neighbours = graph.neighbours(v);
var neighbouringCandidates = util.Intersect(mut_candidates, neighbours)
.collect(Collectors.toCollection(HashSet::new));
if (!neighbouringCandidates.isEmpty()) {
var neighbouringExcluded = util.Intersect(mut_excluded, neighbours)
.collect(Collectors.toCollection(HashSet::new));
visit(graph, cliqueConsumer,
neighbouringCandidates,
neighbouringExcluded,
util.Append(cliqueInProgress, v));
} else if (util.AreDisjoint(mut_excluded, neighbours)) {
cliqueConsumer.accept(util.Append(cliqueInProgress, v));
}
mut_excluded.add(v);
}
}
}
<file_sep>using BronKerbosch;
using NUnit.Framework;
using System.Collections.Immutable;
namespace BronKerboschUnitTest
{
public class CollectionsUtilTests
{
[Test]
public void Append()
{
var empty = ImmutableArray.Create<uint>();
var one = CollectionsUtil.Append(empty, 11u);
var two = CollectionsUtil.Append(one, 22u);
Assert.AreEqual(empty.Length, 0);
Assert.AreEqual(one.Length, 1);
Assert.AreEqual(two.Length, 2);
Assert.AreEqual(one[0], 11u);
Assert.AreEqual(two[0], 11u);
Assert.AreEqual(two[1], 22u);
}
}
}
<file_sep>from graph import UndirectedGraph, Vertex
import argparse
import os
import random
import sys
from typing import Generator, List, Optional, Set, Tuple
class NeighbourhoodWatch:
def __init__(self, order: int):
vertices = range(order)
self.unsaturated_vertices = list(vertices)
self.neighbours: List[Set[int]] = [set() for _ in vertices]
self.complement: List[bool] = [False] * order
def is_saturated(self) -> bool:
return len(self.unsaturated_vertices) < 2
def pick_pair(self) -> Tuple[int, int]:
v = random.choice(self.unsaturated_vertices)
if self.complement[v]:
assert self.neighbours[v]
w = random.choice(tuple(self.neighbours[v]))
else:
w = v
while w == v or w in self.neighbours[v]:
w = random.choice(self.unsaturated_vertices)
assert v != w
return v, w
def meet_neighbour(self, v: int, new_neighbour: int) -> None:
assert v != new_neighbour
if self.complement[v]:
assert new_neighbour in self.neighbours[v]
self.neighbours[v].remove(new_neighbour)
if not self.neighbours[v]:
self.unsaturated_vertices.remove(v)
else:
assert new_neighbour not in self.neighbours[v]
n = len(self.neighbours[v])
if n + 1 >= len(self.unsaturated_vertices) - 2 - n:
self.complement[v] = True
self.neighbours[v] = (set(self.unsaturated_vertices) - {v} -
{new_neighbour} - self.neighbours[v])
if not self.neighbours[v]:
self.unsaturated_vertices.remove(v)
else:
self.neighbours[v].add(new_neighbour)
def generate_edges(order: int) -> Generator[Tuple[int, int], None, None]:
nw = NeighbourhoodWatch(order)
while not nw.is_saturated():
v, w = nw.pick_pair()
nw.meet_neighbour(v, w)
nw.meet_neighbour(w, v)
yield (min(v, w), max(v, w))
def generate_n_edges(
order: int,
size: Optional[int] = None) -> Generator[Tuple[int, int], None, None]:
fully_meshed_size = order * (order - 1) // 2
if size is None:
size = fully_meshed_size
elif size > fully_meshed_size:
raise ValueError(
f"{order} nodes accommodate at most {fully_meshed_size} edges")
for (v, w), _ in zip(generate_edges(order), range(size)):
yield v, w
def random_undirected_graph(order: int, size: int) -> UndirectedGraph:
adjacencies: List[Set[Vertex]] = [set() for _ in range(order)]
print(f"order={order}, size={size}")
for v, w in generate_n_edges(order, size):
adjacencies[v].add(w)
adjacencies[w].add(v)
print(adjacencies)
g = UndirectedGraph(adjacencies=adjacencies)
assert g.order == order
assert g.size() == size
return g
def read_random_graph(orderstr: str,
size: Optional[int]) -> Tuple[UndirectedGraph, int]:
order = to_int(orderstr)
fully_meshed_size = order * (order - 1) // 2
if size is None:
size = fully_meshed_size
elif size > fully_meshed_size:
raise ValueError(
f"{order} nodes accommodate at most {fully_meshed_size} edges")
edges_name = f"random_edges_order_{orderstr}"
stats_name = f"random_stats"
edges_path = os.path.join(os.pardir, "data", edges_name + ".txt")
stats_path = os.path.join(os.pardir, "data", stats_name + ".txt")
adjacencies = read_edges(edges_path, orderstr, order, size)
clique_count = read_stats(stats_path, orderstr, size)
g = UndirectedGraph(adjacencies=adjacencies)
assert g.order == order
assert g.size() == size
return g, clique_count
def read_edges(path: str, orderstr: str, order: int,
size: int) -> List[Set[Vertex]]:
adjacencies: List[Set[Vertex]] = [set() for _ in range(order)]
try:
with open(path, 'r') as txtfile:
for i, line in enumerate(txtfile):
strs = line.split()
try:
v = int(strs[0])
w = int(strs[1])
except (IndexError, ValueError):
raise ValueError(
f"File {path} has bogus line “{line.rstrip()}”"
) from None
adjacencies[v].add(w)
adjacencies[w].add(v)
if i + 1 == size:
return adjacencies
else:
raise ValueError(
f"Exhausted generated list of {i+1} edges in {path}")
except OSError as err:
raise ValueError(
f"{err}\nPerhaps generate it with `python -m random_graph {orderstr} <max_size?>`"
) from err
def read_stats(path: str, orderstr: str, size: int) -> int:
try:
prefix = f"{orderstr}\t{size}\t"
with open(path, 'r') as txtfile:
for line in txtfile:
if line.startswith(prefix):
try:
return int(line[len(prefix):])
except (ValueError):
raise ValueError(
f"File {path} has bogus line “{line.rstrip()}”"
) from None
except OSError as err:
raise ValueError() from err
raise ValueError(f"File {path} lacks order {orderstr} size {size}")
def to_int(txt: str) -> int:
if txt is None:
return None
elif txt.endswith('M'):
return int(txt[:-1]) * 1_000_000
elif txt.endswith('k'):
return int(txt[:-1]) * 1_000
else:
return int(txt)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="generate edges for undirected graph")
parser.add_argument('order', nargs=1)
parser.add_argument('size', nargs='?')
args = parser.parse_args(sys.argv[1:])
orderstr = args.order[0]
sizestr = args.size
order = to_int(orderstr)
size = to_int(sizestr)
filename = f"random_edges_order_{orderstr}"
path = os.path.join(os.pardir, "data", filename + ".txt")
print(f"Writing {size or 'all'} edges to {path}")
with open(path, 'w', newline='\n') as txtfile:
for (v, w) in generate_n_edges(order=order, size=size):
txtfile.write(f"{v} {w}\n")
<file_sep># coding: utf-8
from graph import UndirectedGraph, Vertex
from reporter import Reporter
from typing import List, Set
def explore(graph: UndirectedGraph, reporter: Reporter) -> None:
"""Naive Bron-Kerbosch algorithm"""
if candidates := graph.connected_vertices():
visit(graph=graph,
reporter=reporter,
candidates=candidates,
excluded=set(),
clique=[])
def visit(graph: UndirectedGraph, reporter: Reporter, candidates: Set[Vertex],
excluded: Set[Vertex], clique: List[Vertex]) -> None:
if not candidates and not excluded:
reporter.record(clique)
while candidates:
v = candidates.pop()
neighbours = graph.adjacencies[v]
assert neighbours
visit(graph=graph,
reporter=reporter,
candidates=candidates.intersection(neighbours),
excluded=excluded.intersection(neighbours),
clique=clique + [v])
excluded.add(v)
<file_sep>#pragma once
namespace BronKerbosch {
using Vertex = unsigned;
}<file_sep>[](https://ci.appveyor.com/project/ssomers/bron-kerbosch)
# What is this?
Performance comparison of various implementations of three
[Bron-Kerbosch algorithms](http://en.wikipedia.org/wiki/Bron-Kerbosch_algorithm)
to find all maximal cliques in a graph.
Some algorithm variants (IK_*) are described in the 2008 paper by <NAME> & <NAME>,
“A note on the problem of reporting maximal cliques”,
Theoretical Computer Science, 407 (1): 564–568, doi:10.1016/j.tcs.2008.05.010.
The purpose of this fork is not only to compare the algorithms, but also programming languages,
library choices, and the effect of optimization, chiefly parallelism.
Compared to the original project this is forked from, the code is:
* converted from python 2 to python 3.10
* (hopefully) clarified and type safe
* extended with variations on the algorithms
* extended with unit tests, property based testing, and a performance test on random graphs
* most of in Rust, Java, Go, C++ and partly in C# and Scala
Beware that my Scala knowledge and code is the least developed of all languages.
All charts below show the amount of time spent on the same particular Windows machine with 6 core CPU,
all on the same predetermined random graph, with error bars showing the minimum and maximum
over 5 or 3 samples.
Order of a graph = number of vertices.
A random graph is easy to generate and objective, but not ideal to test the performance of the
algorithm itself, because when you're looking for maximal cliques, the actual data most likely
comes in cliques, some of which are near-maximal and cause the heartaches described in the paper.
# Executive summary
* Better algorithms invented to counter treacherous cases stand their ground on a vanilla random graph.
* Programming language makes a difference, as in factor 2 up to 8.
- Rust is clearly the fastest, but beware I contributed some performance improvements to its
collection library, more than I invested in the other, more established languages.
- C# is the runner up, surpringly (to me).
- Python is the slowest, not surprisingly.
- C++ is clearly not the fastest (and I claim this with the confidence of 20 years of professional C++ development).
* Multi-threading helps a lot too, and how programming languages accommodate for it makes a huge difference.
Python is the worst in that respect, I couldn't get any multi-threading code to work faster than the single-threaded code.
* Collection libraries don't matter much, though hashing reaches sizes a B-tree can only dream of.
# Report of results
## Local optimization
Let's first get one thing out of the way: what does some local optimization yield in the simplest,
naive Bron-Kerbosch algorithm, in Python and Rust. Is this premature optimization or low hanging fruit?
* **Ver1:** Same as in the original project
* **Ver1½:** Same locally optimized, without changing the algorithm as such.
In particular:
- In the (many) deepest iterations, when we see the intersection of candidates is empty, don't
calculate all the nearby excluded vertices, just check if that set is empty or not.
- In Rust, compile a `Clique` from the call stack, instead of passing it around on the heap.
Basically showing off Rust's ability to guarantee, at compile time, this can be done safely.
### Results
We gain as much as through switching to the best performing programming language

Therefore, all the other implementations will contain similar tweaks.
## Comparing algorithms
* **Ver2:** Ver1 excluding neighbours of a pivot that is chosen arbitrarily
* **Ver2-GP:** Ver2 but pivot is the candidate of the highest degree towards the remaining candidates (IK\_GP in the paper)
* **Ver2-GPX:** Ver2-GP but pivot also chosen from excluded vertices (IK\_GPX in the paper)
* **Ver2-RP:** Similar but but with pivot randomly chosen from candidates (IK\_RP in the paper)
* **Ver3:** Ver2 with degeneracy ordering
* **Ver3-GP:** Ver2-GP with degeneracy ordering
* **Ver3-GPX:** Ver2-GPX with degeneracy ordering
As announced in the previous paragraph, we mostly implement locally optimized **½** versions of these.
In particular, we
[write out the first iteration separately](https://github.com/ssomers/Bron-Kerbosch/blob/master/python3/bron_kerbosch2_gp.py),
because in that first iteration the set of candidate vertices starts off being huge, with every connected vertex in the graph,
but that set doesn't have to be represented at all because every reachable vertex is a candidate until excluded.
These are all single-threaded implementations (using only one CPU core).
### Results
* Ver1 indeed struggles with dense graphs, when it has to cover more than half of the 4950 possible edges

* Among Ver2 variants, GP and GPX are indeed best…


* …but GPX looses ground in big graphs


* Ver3-GP barely wins from Ver2-GP in moderately sized graphs…


* …but loses in many other cases




* Ver3-GP seems to cope better at scale than Ver3-GPX






## Introducing parallelism
Let's implement **Ver3-GP** exploiting parallellism (using all CPU cores). How does Ver3 operate?

We already specialized the first iteration in Ver2, and Ver3 changes the order in the first iteration
to the graph's degeneracy order. So we definitely
[write the first iteration separately](https://github.com/ssomers/Bron-Kerbosch/blob/master/python3/bron_kerbosch3_gp.py).
Thus an obvious way to parallelize is to run 2 + N tasks in parallel:
- 1 task generating the degeneracy order of the graph,
- 1 task performing the first iteration in that order,
- 1 or more tasks performing nested iterations.
Ways to implement parallelism varies per language:
* **Ver3½=GPs:** (C#, Java, Scala) using relatively simple composition (async, stream, future)
* **Ver3½=GPc:** (Rust, C++, Java) using something complex resembling channels
* **Ver3½=GP0:** (Go only) using channels and providing 1 goroutine for the nested iterations
* **Ver3½=GP1:** (Go only) using channels and providing 4 goroutines for the nested iterations
* **Ver3½=GP2:** (Go only) using channels and providing 16 goroutines for the nested iterations
* **Ver3½=GPc:** (Go only) using channels and providing 64 goroutines for the nested iterations
* **Ver3½=GP4:** (Go only) using channels and providing 256 goroutines for the nested iterations
### Results
* In Java, simpler multi-threading goes a long way, and more elaborate code shaves off a little more



* In Go, Ver3=GP0 shows the overhead of channels if you don't allow much to operate in parallel;
and there's no need to severely limit the number of goroutines



## Comparing languages
* Plain single-threaded



* Relatively simple multi-threaded



* Multi-thread using something resembling channels



## Comparing versions of languages
* Python 3.10 versus 3.11



## Comparing implementations of the set data structure
All algorithms work heavily with sets. Some languages allow picking at compile time among
various generic set implementations.
### Rust
* **BTree:** `std::collections::BTreeSet`
* **Hash:** `std::collections::HashSet`, a wrapper around a version of hashbrown, in particular 0.11.0 in Rust 1.58.0
* **hashbrown:** `HashSet` from [crate hashbrown](https://crates.io/crates/hashbrown) 0.12
* **fnv:** `FnvHashSet` from [crate fnv](https://crates.io/crates/fnv) 1.0.7
* **ord_vec:** ordered `std::collections::Vec` (obviously, this can only work well on small graphs)
#### Results
* Rust (multi-threaded use shows very similar results, but less consistent runs)



In very sparse graphs, only `BTreeSet` allows Ver1 to scale up.
### C++
* **std_set:** `std::set`
* **hashset:** `std::unordered_set`
* **ord_vec:** ordered `std::vector` (obviously, this can only work well on small graphs)
#### Results


### C#
* **HashSet**
* **SortedSet:**
#### Results


# How to run & test
## Python 3
To obtain these results:
- [dense graph of order 100](doc/details_python311_100.svg)
- [plain graph of order 10k](doc/details_python311_10k.svg)
- [sparse graph of order 1M](doc/details_python311_1M.svg)
Perform
cd python3
(once) python -m venv venv
venv\Scripts\activate.bat
(once or twice) pip install --upgrade mypy pytest hypothesis matplotlib
mypy .
pytest
python -O test_maximal_cliques.py
## Rust
To obtain these results:
- [dense graph of order 100](doc/details_rust_100.svg)
- [sparse graph of order 10k](doc/details_rust_10k_initial.svg)
- [plain graph of order 10k](doc/details_rust_10k.svg)
- [extremely sparse graph of order 1M](doc/details_rust_1M_initial.svg)
- [sparse graph of order 1M](doc/details_rust_1M.svg)
Perform
cd rust
(sometimes) rustup update
(sometimes) cargo upgrades && cargo update
cargo clippy --workspace
cargo test --workspace
cargo run --release
## Go
To obtain these results:
- [dense graph of order 100](doc/details_go_100.svg)
- [plain graph of order 10k](doc/details_go_10k.svg)
- [sparse graph of order 1M](doc/details_go_1M.svg)
Perform
cd go
go vet ./...
go test ./...
go test ./Stats -fuzz=Stats1 -fuzztime=1s
go test ./Stats -fuzz=Stats2 -fuzztime=2s
go test ./Stats -fuzz=StatsN -fuzztime=5s
go test ./BronKerbosch -fuzz=DegeneracyOrder -fuzztime=20s
go run main.go
Optionally, on MSYS2:
PATH=$PATH:$PROGRAMFILES/go/bin
go test -race ./BronKerbosch
## C#
To obtain these results:
- [dense graph of order 100](doc/details_csharp_100.svg)
- [plain graph of order 10k](doc/details_csharp_10k.svg)
- [sparse graph of order 1M](doc/details_csharp_1M.svg)
Perform
- open csharp\BronKerboschStudy.sln with Visual Studio 2022
- set configuration to Debug
- Test > Run > All Tests
- set configuration to Release
- Solution Explorer > BronKerboschStudy > Set as Startup Project
- Debug > Start Without Debugging
## C++ 20
To obtain these results:
- [dense graph of order 100](doc/details_c++_100.svg)
- [sparse graph of order 10k](doc/details_c++_10k_initial.svg)
- [plain graph of order 10k](doc/details_c++_10k.svg)
- [sparse graph of order 1M](doc/details_c++_1M.svg)
Either:
- clone or export https://github.com/andreasbuhr/cppcoro locally, e.g. next to this repository
- build it, something akin to:
call "%ProgramFiles%\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
mkdir build
cd build
cmake .. -A x64 -DCMAKE_CXX_STANDARD=20 -DBUILD_TESTING=ON
cmake --build . --config Release
cmake --build . --config Debug
ctest --progress --config Release
ctest --progress --config Debug
- open cpp\BronKerboschStudy.sln with Visual Studio 2022
- set directory to cppcoro (if not `..\cppcoro` relative to Bron-Kerbosch):
- View > Other Windows > Property Manager
- in the tree, descend to any project and configuration, open propery page "BronKerboschStudyGeneral"
- in User Macros, set `CppcoroDir`
- set configuration to Debug
- Test > Run > All Tests
- set configuration to Release
- Debug > Start Without Debugging
## Java
To obtain these results:
- [dense graph of order 100](doc/details_java_100.svg)
- [plain graph of order 10k](doc/details_java_10k.svg)
- [sparse graph of order 1M](doc/details_java_1M.svg)
Perform
- open folder java with IntelliJ IDEA 2022 (Community Edition)
- set run configuration to "Test"
- Run > Run 'Test'
- set run configuration to "Main"
- Run > Run 'Main'
## Scala
To obtain these results:
- [dense graph of order 100](doc/details_scala_100.svg)
- [plain graph of order 10k](doc/details_scala_10k.svg)
- [sparse graph of order 1M](doc/details_scala_1M.svg)
Perform
- open folder scala with IntelliJ IDEA 2022 (Community Edition)
- View > Tool Windows > sbt; Reload sbt Project (or Reload All sbt Projects)
- enable assertions: comment out `"-Xdisable-assertions"` in build.sbt
- Build > Rebuild Project
- set run configuration to test
- Run > Run 'test'
- disable assertions: uncomment `"-Xdisable-assertions"` in build.sbt
- Build > Rebuild Project
- set run configuration to main
- Run > Run 'main'
## Finally
Python and Rust publish results to the cloud automatically, the others need a push:
python python3\publish.py go 100 10k 1M
python python3\publish.py c# 100 10k 1M
python python3\publish.py c++ 100 10k 1M
python python3\publish.py java 100 10k 1M
python python3\publish.py scala 100 10k 1M
And finally, generate images locally:
python python3\publish.py
dot doc\Ver3.dot -Tsvg -O
## License
[BSD License](http://opensource.org/licenses/BSD-3-Clause)
<file_sep>#pragma once
#include <vector>
#include "BronKerbosch1.h"
#include "BronKerbosch2GP.h"
#include "BronKerbosch2GPX.h"
#include "BronKerbosch3GP.h"
#include "BronKerbosch3GPX.h"
#include "BronKerbosch3MT.h"
#include "UndirectedGraph.h"
namespace BronKerbosch {
class Portfolio {
public:
static int const NUM_FUNCS = 6;
static const char* const FUNC_NAMES[NUM_FUNCS];
struct CollectingReporter {
using Result = CliqueList;
static Result empty() {
return CliqueList{};
}
static void add_one(Result& cliques, VertexPile&& pile) {
cliques.push_back(pile.collect());
}
static void add_all(Result& cliques, Result&& more_cliques) {
cliques.splice(cliques.end(), more_cliques);
}
};
struct CountingReporter {
using Result = size_t;
static Result empty() {
return 0;
}
static void add_one(Result& cliques, VertexPile&&) {
cliques += 1;
}
static void add_all(Result& cliques, Result&& more_cliques) {
cliques += more_cliques;
}
};
template <typename Reporter, typename VertexSet>
static typename Reporter::Result explore(int func_index,
UndirectedGraph<VertexSet> const& graph) {
switch (func_index) {
case 0: return BronKerbosch1::explore<Reporter>(graph);
case 1: return BronKerbosch2GP::explore<Reporter>(graph);
case 2: return BronKerbosch2GPX::explore<Reporter>(graph);
case 3: return BronKerbosch3GP::explore<Reporter>(graph);
case 4: return BronKerbosch3GPX::explore<Reporter>(graph);
case 5: return BronKerbosch3MT<Reporter, VertexSet>::explore(graph);
}
throw std::logic_error("invalid func_index");
}
static void sort_cliques(std::vector<std::vector<Vertex>>& cliques);
private:
static bool clique_less(std::vector<Vertex> const&, std::vector<Vertex> const&);
};
}
<file_sep>using BronKerboschStudy;
using NUnit.Framework;
using System;
#pragma warning disable IDE0022 // Use expression body for method
#pragma warning disable IDE0058 // Expression value is never used
namespace BronKerboschStudyUnitTest
{
public class NumbersGameTests
{
[Test]
public void ParsePositiveInt()
{
Assert.AreEqual(NumbersGame.ParseInt("0"), 0);
Assert.AreEqual(NumbersGame.ParseInt("123"), 123);
Assert.AreEqual(NumbersGame.ParseInt("1k"), 1_000);
Assert.AreEqual(NumbersGame.ParseInt("1M"), 1_000_000);
Assert.AreEqual(NumbersGame.ParseInt("42M"), 42_000_000);
}
[Test]
public void ParseNegativeInt()
{
Assert.AreEqual(NumbersGame.ParseInt("-1"), -1);
}
[Test]
public void ParseEmpty()
{
Assert.Catch<FormatException>(() => NumbersGame.ParseInt(""));
}
[Test]
public void ParseUnknownSuffix()
{
Assert.Catch<FormatException>(() => NumbersGame.ParseInt("1K"));
}
[Test]
public void ParseNonInt()
{
Assert.Catch<FormatException>(() => NumbersGame.ParseInt("1.1"));
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class BronKerbosch3_ST implements BronKerboschAlgorithm {
private UndirectedGraph graph;
private record VisitJob(int startVertex,
Set<Integer> mut_candidates,
Set<Integer> mut_excluded) {
}
private final class VisitProducer {
private final Set<Integer> excluded = new HashSet<>(graph.order());
VisitJob createJob(Integer startVtx) {
var neighbours = graph.neighbours(startVtx);
assert !neighbours.isEmpty();
var neighbouringCandidates = util.Difference(neighbours, excluded)
.collect(Collectors.toCollection(HashSet::new));
VisitJob job = null;
if (neighbouringCandidates.isEmpty()) {
assert !util.AreDisjoint(neighbours, excluded);
} else {
var neighbouringExcluded = util.Intersect(neighbours, excluded)
.collect(Collectors.toCollection(HashSet::new));
job = new VisitJob(startVtx, neighbouringCandidates, neighbouringExcluded);
}
excluded.add(startVtx);
return job;
}
}
private final class Visitor {
Stream<int[]> visit(VisitJob job) {
Stream.Builder<int[]> cliqueStream = Stream.builder();
BronKerboschPivot.visit(graph, cliqueStream,
PivotChoice.MaxDegreeLocal,
job.mut_candidates,
job.mut_excluded,
new int[]{job.startVertex});
return cliqueStream.build();
}
}
@Override
public Stream<int[]> explore(UndirectedGraph graph) {
this.graph = graph;
var visitProducer = new VisitProducer();
var visitor = new Visitor();
var ordering = new DegeneracyOrdering(graph, -1);
return ordering.stream()
.mapToObj(visitProducer::createJob)
.filter(Objects::nonNull)
.toList()
.parallelStream()
.flatMap(visitor::visit);
}
}
<file_sep>package BronKerbosch
func bronKerbosch2bGP(graph *UndirectedGraph, reporter Reporter) {
// Bron-Kerbosch algorithm with pivot of highest degree within remaining candidates
// chosen from candidates only (IK_GP).
order := graph.Order()
if order == 0 {
return
}
pivot := graph.maxDegreeVertex()
excluded := make(VertexSet, order)
for i := 0; i < order; i++ {
v := Vertex(i)
neighbours := graph.neighbours(v)
if !neighbours.Contains(pivot) {
neighbouringExcluded := neighbours.Intersection(excluded)
if len(neighbouringExcluded) < len(neighbours) {
neighbouringCandidates := neighbours.Difference(neighbouringExcluded)
visit(
graph, reporter,
MaxDegreeLocal,
neighbouringCandidates,
neighbouringExcluded,
[]Vertex{v})
}
excluded.Add(v)
}
}
}
<file_sep>#pragma once
namespace BronKerboschStudy {
template <typename T>
class SampleStatistics {
private:
T maxOrZero = 0;
T minOrZero = 0;
unsigned samples = 0;
double sum = 0;
double sum_of_squares = 0;
public:
void put(T v) {
if (samples == 0) {
minOrZero = v;
maxOrZero = v;
} else if (minOrZero > v) {
minOrZero = v;
} else if (maxOrZero < v) {
maxOrZero = v;
}
samples += 1;
sum += v;
sum_of_squares += std::pow(v, 2);
}
T max() const {
return maxOrZero;
}
T min() const {
return minOrZero;
}
double mean() const {
static_assert(std::numeric_limits<double>::has_quiet_NaN);
if (samples < 1) {
return std::numeric_limits<double>::quiet_NaN();
} else {
auto r = sum / double(samples);
return std::max(double(minOrZero), std::min(double(maxOrZero), r));
}
}
double variance() const {
static_assert(std::numeric_limits<double>::has_quiet_NaN);
if (samples < 2) {
return std::numeric_limits<double>::quiet_NaN();
} else if (minOrZero == maxOrZero) {
return 0.;
} else {
auto n = double(samples);
auto r = (sum_of_squares - std::pow(sum, 2) / n) / (n - 1.);
return std::max(0., r);
}
}
double deviation() const {
auto r = std::sqrt(variance());
if (std::isnan(r)) {
return r;
} else {
return std::min(double(maxOrZero) - double(minOrZero), r);
}
}
};
}
<file_sep>use super::vertex::Vertex;
pub type Clique = Vec<Vertex>;
pub trait Reporter {
fn record(&mut self, clique: Clique);
}
<file_sep>namespace BronKerboschStudy
{
public struct SampleStatistics
{
public double Max { get; private set; }
public double Min { get; private set; }
public int Samples { get; private set; }
private double Sum;
private double SumOfSquares;
public readonly double Mean => Samples > 0
? Math.Max(Min, Math.Min(Max, Sum / Samples))
: double.NaN;
public readonly double Variance => Samples > 1
? Math.Max(0, SumOfSquares - Sum * Sum / Samples) / (Samples - 1)
: double.NaN;
public readonly double Deviation => Math.Min(Max - Min, Math.Sqrt(Variance));
public void Put(double v)
{
if (Samples == 0 || v < Min)
Min = v;
if (Samples == 0 || v > Max)
Max = v;
Samples += 1;
Sum += v;
SumOfSquares += v * v;
}
}
}
<file_sep>// Bron-Kerbosch algorithm with degeneracy ordering,
// choosing a pivot from both candidates and excluded vertices (IK_GPX).
using BronKerbosch;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
internal static class BronKerbosch3ST<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
internal sealed class NestedReporter(ITargetBlock<ImmutableArray<Vertex>>? target) : IReporter
{
public int useAfterClose;
public int postFailed;
public void Record(ImmutableArray<Vertex> clique)
{
if (target is null)
{
++useAfterClose; // breakpoint candidate
}
else if (!target.Post(clique))
{
++postFailed; // breakpoint candidate
}
}
public void Close()
{
if (target is null)
{
++useAfterClose; // breakpoint candidate
}
target = null;
}
}
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter finalReporter)
{
var scheduler = TaskScheduler.Default;
int sent = 0;
int received = 0;
// Step 3: collect results.
var collect = new ActionBlock<ImmutableArray<Vertex>>(finalReporter.Record);
// Step 2: visit vertices.
var reporter = new NestedReporter(collect);
int waitGroup = 1;
void completion(Task _)
{
if (Interlocked.Decrement(ref waitGroup) == 0)
{
reporter.Close();
collect.Complete();
}
}
var excluded = VertexSetMgr.Empty();
var visit = new ActionBlock<Vertex>(v =>
{
var neighbours = graph.Neighbours(v);
Debug.Assert(neighbours.Any());
var neighbouringCandidates = VertexSetMgr.Difference(neighbours, excluded);
if (neighbouringCandidates.Any())
{
var neighbouringExcluded = VertexSetMgr.Intersection(excluded, neighbours);
_ = Interlocked.Increment(ref waitGroup);
_ = Task.Run(delegate
{
Pivot<VertexSet, VertexSetMgr>.Visit(graph, reporter, PivotChoice.MaxDegreeLocal,
neighbouringCandidates, neighbouringExcluded,
ImmutableArray.Create(v));
}).ContinueWith(completion, scheduler);
}
else
{
Debug.Assert(VertexSetMgr.Overlaps(neighbours, excluded));
}
var added = VertexSetMgr.Add(excluded, v);
Debug.Assert(added);
++received;
});
_ = visit.Completion.ContinueWith(completion, scheduler);
// Step 1: feed vertices in order.
_ = Task.Run(delegate
{
foreach (var v in Degeneracy<VertexSet, VertexSetMgr>.Ordering(graph, drop: 1))
{
while (!visit.Post(v))
{
throw new InvalidOperationException("Post failed");
}
++sent;
}
visit.Complete();
});
collect.Completion.Wait();
if (sent != received)
{
throw new InvalidOperationException($"{sent} sent <> {received} received");
}
if (reporter.useAfterClose != 0)
{
throw new InvalidOperationException($"Reporter use after Close ({reporter.useAfterClose} times)");
}
if (reporter.postFailed != 0)
{
throw new InvalidOperationException($"Record failed ({reporter.postFailed} times)");
}
}
}
<file_sep>#include "pch.h"
#include "Console.h"
#ifdef _MSC_VER
# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
# include <Windows.h>
#endif
void console_init() {
#ifdef _MSC_VER
SetConsoleOutputCP(CP_UTF8);
// Enable buffering to prevent VS from chopping up UTF-8 byte sequences
setvbuf(stdout, nullptr, _IOFBF, 512);
#endif
}
<file_sep>from typing import List, Set
NEIGHBORS: List[Set[int]] = [
set(), # I want to start index from 1 instead of 0
{2, 3, 4},
{1, 3, 4, 5},
{1, 2, 4, 5},
{1, 2, 3},
{2, 3, 6, 7},
{5, 7},
{5, 6},
]
<file_sep>package BronKerbosch
import (
"fmt"
"sort"
)
const NumFuncs = 9
var Funcs = [NumFuncs]func(*UndirectedGraph, Reporter){
bronKerbosch1,
bronKerbosch2aGP,
bronKerbosch2bGP,
bronKerbosch3gp,
bronKerbosch3gp0,
bronKerbosch3gp1,
bronKerbosch3gp2,
bronKerbosch3gp3,
bronKerbosch3gp4,
}
var FuncNames = [NumFuncs]string{
"Ver1½",
"Ver2-GP", "Ver2½-GP",
"Ver3½-GP", "Ver3½=GP0", "Ver3½=GP1", "Ver3½=GP2", "Ver3½=GP3", "Ver3½=GP4",
}
func SortCliques(cliques [][]Vertex) {
for _, clique := range cliques {
sort.Slice(clique, func(l int, r int) bool {
return clique[l] < clique[r]
})
}
sort.Slice(cliques, func(l int, r int) bool {
for i := 0; i < len(cliques[l]) && i < len(cliques[r]); i++ {
if d := cliques[l][i] - cliques[r][i]; d != 0 {
return d < 0
}
}
if len(cliques) < 10 {
panic(fmt.Sprintf("got overlapping cliques %d <> %d: %v", l, r, cliques))
} else {
panic(fmt.Sprintf("got overlapping cliques: #%d %d <> #%d %d",
l+1, cliques[l],
r+1, cliques[r]))
}
})
}
func CompareCliques(leftCliques [][]Vertex, rightCliques [][]Vertex, errors func(string)) {
if len(leftCliques) != len(rightCliques) {
errors(fmt.Sprintf("%d <> %d cliques", len(leftCliques), len(rightCliques)))
} else {
for j, left := range leftCliques {
right := rightCliques[j]
if len(left) != len(right) {
errors(fmt.Sprintf("clique #%d: %d <> %d vertices", j+1, len(left), len(right)))
} else {
for i, l := range left {
r := right[i]
if l != r {
errors(fmt.Sprintf("clique #%d vertex #%d/%d: %d <> %d", j+1, i+1, len(left), l, r))
}
}
}
}
}
}
<file_sep>#pragma once
#ifdef _MSC_VER
# pragma warning(disable : 4365) // conversion from ... to ..., signed/unsigned mismatch
# pragma warning(disable : 4514) // unreferenced inline function has been removed
# pragma warning(disable : 4571) // catch (…) semantics changed since Visual C++ 7.1
# pragma warning(disable : 4710) // function not inlined
# pragma warning(disable : 4711) // function … selected for automatic inline expansion
# pragma warning(disable : 4625) // copy constructor was implicitly defined as deleted
# pragma warning(disable : 4626) // assignment operator was implicitly defined as deleted
# pragma warning(disable : 4820) // bytes padding added after data member
# pragma warning(disable : 5026) // move constructor was implicitly defined as deleted
# pragma warning(disable : 5027) // move assignment operator was implicitly defined as deleted
# pragma warning(disable : 5039) // pointer or reference to potentially throwing function passed
// to 'extern "C"' function under -EHc.
# pragma warning(disable : 5045) // Compiler will insert Spectre mitigation for memory load if
// /Qspectre switch specified
#endif
#include <algorithm>
#include <cassert>
#include <iterator>
#include <optional>
#include <set>
#include <vector>
<file_sep>package BronKerbosch
type PivotSelection int
const (
MaxDegreeLocal PivotSelection = iota
MaxDegreeLocalX = iota
)
func visit(graph *UndirectedGraph, reporter Reporter,
pivotSelection PivotSelection,
candidates VertexSet, excluded VertexSet, clique []Vertex) {
if len(candidates) == 1 {
for v := range candidates {
// Same logic as below, stripped down
neighbours := graph.neighbours(v)
if excluded.IsDisjoint(neighbours) {
reporter.Record(append(clique, v))
}
}
return
}
var pivot Vertex
remainingCandidates := make([]Vertex, 0, len(candidates))
// Quickly handle locally unconnected candidates while finding pivot
seenLocalDegree := 0
for v := range candidates {
neighbours := graph.neighbours(v)
localDegree := neighbours.IntersectionLen(candidates)
if localDegree == 0 {
// Same logic as below, stripped down
if neighbours.IsDisjoint(excluded) {
reporter.Record(append(clique, v))
}
} else {
if seenLocalDegree < localDegree {
seenLocalDegree = localDegree
pivot = v
}
remainingCandidates = append(remainingCandidates, v)
}
}
if seenLocalDegree == 0 {
return
}
if pivotSelection == MaxDegreeLocalX {
for v := range excluded {
neighbours := graph.neighbours(v)
localDegree := neighbours.IntersectionLen(candidates)
if seenLocalDegree < localDegree {
seenLocalDegree = localDegree
pivot = v
}
}
}
for _, v := range remainingCandidates {
neighbours := graph.neighbours(v)
if neighbours.Contains(pivot) {
continue
}
candidates.Remove(v)
neighbouringCandidates := neighbours.Intersection(candidates)
if !neighbouringCandidates.IsEmpty() {
neighbouringExcluded := neighbours.Intersection(excluded)
visit(
graph, reporter,
pivotSelection,
neighbouringCandidates,
neighbouringExcluded,
append(clique, v))
} else {
if neighbours.IsDisjoint(excluded) {
reporter.Record(append(clique, v))
}
}
excluded.Add(v)
}
}
<file_sep>package BronKerbosch
import (
"BronKerboschStudy/Assert"
"fmt"
"testing"
)
func checkDegeneracyOrder(graph *UndirectedGraph) {
var ordering SimpleVertexVisitor
degeneracyOrdering(graph, &ordering, 0)
ordered := ordering.vertices
unordered := graph.connectedVertices()
for _, v := range ordered {
if _, ok := unordered[v]; !ok {
panic(fmt.Sprintf("degeneracy ordering %v invented vertex %d", ordered, v))
}
delete(unordered, v)
if graph.degree(v) < graph.degree(ordered[0]) {
panic(fmt.Sprintf("degeneracy ordering %v violates degree at vertex %d", ordered, v))
}
}
if len(unordered) != 0 {
panic(fmt.Sprintf("degeneracy ordering %v forgot %d vertices", ordered, len(unordered)))
}
}
func proposedNeighbour(v int, proposed byte) int {
if int(proposed) < v {
return int(proposed)
} else {
return int(proposed) + 1
}
}
func FuzzDegeneracyOrder(f *testing.F) {
f.Add([]byte{0, 1})
f.Fuzz(func(t *testing.T, seed []byte) {
order := len(seed)
for v, proposed := range seed {
w := proposedNeighbour(v, proposed)
Assert.IsTrue(w != v)
if order <= w {
order = w + 1
}
}
adjacencies := make([]VertexSet, order)
for v := 0; v < order; v++ {
adjacencies[v] = make(VertexSet)
}
for v, proposed := range seed {
w := proposedNeighbour(v, proposed)
adjacencies[v].Add(Vertex(w))
adjacencies[w].Add(Vertex(v))
}
g := NewUndirectedGraph(adjacencies)
if g.Order() != order {
panic("botched order")
}
checkDegeneracyOrder(&g)
})
}
func bk(t *testing.T, adjacencylist [][]Vertex, expectedCliques [][]Vertex) {
adjacencies := make([]VertexSet, len(adjacencylist))
for i, neighbours := range adjacencylist {
adjacencies[i] = NewVertexSet(neighbours)
if adjacencies[i].Cardinality() != len(neighbours) {
panic(fmt.Sprintf("Invalid adjacencylist %v", neighbours))
}
}
graph := NewUndirectedGraph(adjacencies)
checkDegeneracyOrder(&graph)
for funcIndex, bronKerboschFunc := range Funcs {
var reporter CollectingReporter
bronKerboschFunc(&graph, &reporter)
obtainedCliques := reporter.Cliques
SortCliques(obtainedCliques)
CompareCliques(obtainedCliques, expectedCliques,
func(e string) { t.Errorf("%s: %s", FuncNames[funcIndex], e) })
}
}
func TestOrder0(t *testing.T) {
bk(t, [][]Vertex{}, [][]Vertex{})
}
func TestOrder1(t *testing.T) {
bk(t, [][]Vertex{[]Vertex{}}, [][]Vertex{})
}
func TestOrder2isolated(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{},
[]Vertex{}},
[][]Vertex{})
}
func TestOrder2connected(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0}},
[][]Vertex{
[]Vertex{0, 1}})
}
func TestOrder3Size1left(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0},
[]Vertex{}},
[][]Vertex{
[]Vertex{0, 1}})
}
func TestOrder3Size1long(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{2},
[]Vertex{},
[]Vertex{0}},
[][]Vertex{
[]Vertex{0, 2}})
}
func TestOrder3Size1right(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{},
[]Vertex{2},
[]Vertex{1}},
[][]Vertex{
[]Vertex{1, 2}})
}
func TestOrder3Size2(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0, 2},
[]Vertex{1}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{1, 2}})
}
func TestOrder3Size3(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2},
[]Vertex{0, 2},
[]Vertex{0, 1}},
[][]Vertex{
[]Vertex{0, 1, 2}})
}
func TestOrder4Size2(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0},
[]Vertex{3},
[]Vertex{2}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{2, 3}})
}
func TestOrder4Size3bus(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0, 2},
[]Vertex{1, 3},
[]Vertex{2}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{1, 2},
[]Vertex{2, 3}})
}
func TestOrder4Size3star(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2, 3},
[]Vertex{0},
[]Vertex{0},
[]Vertex{0}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{0, 2},
[]Vertex{0, 3}})
}
func TestOrder4Size4p(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1},
[]Vertex{0, 2, 3},
[]Vertex{1, 3},
[]Vertex{1, 2}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{1, 2, 3}})
}
func TestOrder4Size4square(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 3},
[]Vertex{0, 2},
[]Vertex{1, 3},
[]Vertex{0, 2}},
[][]Vertex{
[]Vertex{0, 1},
[]Vertex{0, 3},
[]Vertex{1, 2},
[]Vertex{2, 3},
})
}
func TestOrder4Size5(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2, 3},
[]Vertex{0, 2},
[]Vertex{0, 1, 3},
[]Vertex{0, 2}},
[][]Vertex{
[]Vertex{0, 1, 2},
[]Vertex{0, 2, 3}})
}
func TestOrder4Size6(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2, 3},
[]Vertex{0, 2, 3},
[]Vertex{0, 1, 3},
[]Vertex{0, 1, 2}},
[][]Vertex{
[]Vertex{0, 1, 2, 3}})
}
func TestOrder5Size9penultimate(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2, 3, 4},
[]Vertex{0, 2, 3, 4},
[]Vertex{0, 1, 3, 4},
[]Vertex{0, 1, 2},
[]Vertex{0, 1, 2}},
[][]Vertex{
[]Vertex{0, 1, 2, 3},
[]Vertex{0, 1, 2, 4}})
}
func TestSample(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{},
[]Vertex{2, 3, 4},
[]Vertex{1, 3, 4, 5},
[]Vertex{1, 2, 4, 5},
[]Vertex{1, 2, 3},
[]Vertex{2, 3, 6, 7},
[]Vertex{5, 7},
[]Vertex{5, 6}},
[][]Vertex{
[]Vertex{1, 2, 3, 4},
[]Vertex{2, 3, 5},
[]Vertex{5, 6, 7},
})
}
func TestBigger(t *testing.T) {
bk(t,
[][]Vertex{
[]Vertex{1, 2, 3, 4, 6, 7},
[]Vertex{0, 3, 6, 7, 8, 9},
[]Vertex{0, 3, 5, 7, 8, 9},
[]Vertex{0, 1, 2, 4, 9},
[]Vertex{0, 3, 6, 7, 9},
[]Vertex{2, 6},
[]Vertex{0, 1, 4, 5, 9},
[]Vertex{0, 1, 2, 4, 9},
[]Vertex{1, 2},
[]Vertex{1, 2, 3, 4, 6, 7}},
[][]Vertex{
[]Vertex{0, 1, 3},
[]Vertex{0, 1, 6},
[]Vertex{0, 1, 7},
[]Vertex{0, 2, 3},
[]Vertex{0, 2, 7},
[]Vertex{0, 3, 4},
[]Vertex{0, 4, 6},
[]Vertex{0, 4, 7},
[]Vertex{1, 3, 9},
[]Vertex{1, 6, 9},
[]Vertex{1, 7, 9},
[]Vertex{1, 8},
[]Vertex{2, 3, 9},
[]Vertex{2, 5},
[]Vertex{2, 7, 9},
[]Vertex{2, 8},
[]Vertex{3, 4, 9},
[]Vertex{4, 6, 9},
[]Vertex{4, 7, 9},
[]Vertex{5, 6},
})
}
<file_sep># coding: utf-8
from graph import UndirectedGraph, Vertex
from reporter import Reporter
from typing import Callable, List, Set
import random
PivotChoice = Callable[[UndirectedGraph, Set[Vertex]], Vertex]
def visit(graph: UndirectedGraph, reporter: Reporter, pivot_choice_X: bool,
candidates: Set[Vertex], excluded: Set[Vertex],
clique: List[Vertex]) -> None:
assert all(graph.degree(v) > 0 for v in candidates)
assert all(graph.degree(v) > 0 for v in excluded)
assert candidates.isdisjoint(excluded)
assert len(candidates) >= 1
if len(candidates) == 1:
# Same logic as below, stripped down for this common case
for v in candidates:
neighbours = graph.adjacencies[v]
assert neighbours
if excluded.isdisjoint(neighbours):
reporter.record(clique + [v])
return
# Quickly handle locally unconnected candidates while finding pivot
remaining_candidates = []
seen_local_degree = 0
for v in candidates:
neighbours = graph.adjacencies[v]
local_degree = len(candidates.intersection(neighbours))
if local_degree == 0:
# Same logic as below, stripped down
if neighbours.isdisjoint(excluded):
reporter.record(clique + [v])
else:
if seen_local_degree < local_degree:
seen_local_degree = local_degree
pivot = v
remaining_candidates.append(v)
if seen_local_degree == 0:
return
if pivot_choice_X:
for v in excluded:
neighbours = graph.adjacencies[v]
local_degree = len(candidates.intersection(neighbours))
if seen_local_degree < local_degree:
seen_local_degree = local_degree
pivot = v
for v in remaining_candidates:
neighbours = graph.adjacencies[v]
assert neighbours
if pivot not in neighbours:
candidates.remove(v)
if neighbouring_candidates := candidates.intersection(neighbours):
neighbouring_excluded = excluded.intersection(neighbours)
visit(graph=graph,
reporter=reporter,
pivot_choice_X=pivot_choice_X,
candidates=neighbouring_candidates,
excluded=neighbouring_excluded,
clique=clique + [v])
elif excluded.isdisjoint(neighbours):
reporter.record(clique + [v])
excluded.add(v)
<file_sep>package be.steinsomers.bron_kerbosch;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Stream;
@SuppressWarnings("TypeMayBeWeakened")
public final class util {
public static int[] Append(int[] head, int tail) {
var result = Arrays.copyOf(head, head.length + 1);
result[head.length] = tail;
return result;
}
public static <T> T PopArbitrary(Collection<? extends T> c) {
Iterator<? extends T> it = c.iterator();
T arbitrary = it.next();
it.remove();
return arbitrary;
}
public static <T> Stream<T> Difference(Set<T> set1, Set<T> set2) {
return set1.stream().filter(v -> !set2.contains(v));
}
public static <T> Stream<T> Intersect(Set<T> set1, Set<T> set2) {
if (set1.size() <= set2.size())
return set1.stream().filter(set2::contains);
else
return set2.stream().filter(set1::contains);
}
public static <T> boolean AreDisjoint(Set<T> set1, Set<T> set2) {
return Intersect(set1, set2).findFirst().isEmpty();
}
}
<file_sep>mod core;
#[cfg(test)]
mod degeneracy_tests;
mod vertexsetlikes;
pub use crate::core::graph::{Adjacencies, NewableUndirectedGraph, Vertex, VertexSetLike};
pub use crate::core::reporters::{CollectingReporter, CountingReporter};
pub use crate::core::slimgraph::SlimUndirectedGraph;
pub use crate::core::{explore, order_cliques, OrderedClique, OrderedCliques, FUNC_NAMES};
#[cfg(test)]
mod tests {
use crate::core::tests::all_test_data;
use fnv::FnvHashSet;
use hashbrown;
use std::collections::BTreeSet;
use std::collections::HashSet;
#[test]
fn bk_btree() {
for td in all_test_data() {
td.run::<BTreeSet<_>>();
}
}
#[test]
fn bk_hash() {
for td in all_test_data() {
td.run::<HashSet<_>>();
}
}
#[test]
fn bk_fnv() {
for td in all_test_data() {
td.run::<FnvHashSet<_>>();
}
}
#[test]
fn bk_hashbrown() {
for td in all_test_data() {
td.run::<hashbrown::HashSet<_>>();
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
enum PivotChoice {
Arbitrary, MaxDegreeLocal, MaxDegreeLocalX
}
<file_sep>// Bron-Kerbosch algorithm with pivot of highest degree towards the remaining candidates (IK_GPX)
using BronKerbosch;
using System.Collections.Generic;
internal static class BronKerbosch2bGPX<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter)
{
# pragma warning disable IDE0022 // Use expression body for method
Pivot<VertexSet, VertexSetMgr>.Explore(graph, reporter, PivotChoice.MaxDegreeLocalX);
}
}
<file_sep>package main
import (
"BronKerboschStudy/BronKerbosch"
"BronKerboschStudy/Stats"
"BronKerboschStudy/StudyIO"
"fmt"
"os"
"path/filepath"
"time"
)
func timed(orderstr string, size int, funcIndices []int, timedSamples int) [BronKerbosch.NumFuncs]Stats.SampleStatistics {
begin := time.Now()
graph, cliqueCount, err := StudyIO.ReadRandomUndirectedGraph(orderstr, size)
secs := time.Since(begin).Seconds()
if err != nil {
panic(err)
}
fmt.Printf("order %4s size %7d %-8s: %5.3fs\n", orderstr, size, "creation", secs)
var times [BronKerbosch.NumFuncs]Stats.SampleStatistics
var first [][]BronKerbosch.Vertex
for sample := 0; sample <= timedSamples; sample++ {
for _, funcIndex := range funcIndices {
bronKerboschFunc := BronKerbosch.Funcs[funcIndex]
var collectingReporter BronKerbosch.CollectingReporter
var countingReporter BronKerbosch.CountingReporter
begin := time.Now()
if sample == 0 {
bronKerboschFunc(&graph, &collectingReporter)
} else {
bronKerboschFunc(&graph, &countingReporter)
}
secs := time.Since(begin).Seconds()
if sample == 0 {
if secs >= 3.0 {
fmt.Printf(" %-8s: %5.2fs\n", BronKerbosch.FuncNames[funcIndex], secs)
}
current := collectingReporter.Cliques
BronKerbosch.SortCliques(current)
if len(first) == 0 {
if len(current) != cliqueCount {
fmt.Printf(" %s: expected %d cliques, obtained %d\n",
BronKerbosch.FuncNames[funcIndex], cliqueCount, len(current))
}
first = current
} else {
BronKerbosch.CompareCliques(current, first, func(e string) {
fmt.Printf(" %s: %s\n", BronKerbosch.FuncNames[funcIndex], e)
})
}
} else {
if countingReporter.Cliques != cliqueCount {
fmt.Printf(" %s: expected %d cliques, obtained %d\n",
BronKerbosch.FuncNames[funcIndex], cliqueCount, countingReporter.Cliques)
}
times[funcIndex].Put(secs)
}
}
}
return times
}
func bk(orderstr string, sizes []int, funcIndices []int, timedSamples int) {
name := "bron_kerbosch_go_order_" + orderstr
path := filepath.Join("..", name+".csv")
fo, err := os.Create(path)
if err != nil {
panic(err)
}
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
fo.WriteString("Size")
for _, funcIndex := range funcIndices {
name := BronKerbosch.FuncNames[funcIndex]
fo.WriteString(fmt.Sprintf(",%s min,%s mean,%s max", name, name, name))
}
fo.WriteString("\n")
for _, size := range sizes {
fo.WriteString(fmt.Sprintf("%d", size))
stats := timed(orderstr, size, funcIndices, timedSamples)
for _, funcIndex := range funcIndices {
name := BronKerbosch.FuncNames[funcIndex]
max := stats[funcIndex].Max()
min := stats[funcIndex].Min()
mean := stats[funcIndex].Mean()
dev := stats[funcIndex].Deviation()
fo.WriteString(fmt.Sprintf(",%f,%f,%f", min, mean, max))
fmt.Printf("order %4s size %7d %-8s: %5.3fs ± %.0f%%\n", orderstr, size, name, mean, 100*dev/mean)
}
fo.WriteString("\n")
}
}
func main() {
allFuncIndices := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
mostFuncIndices := []int{1, 2, 3, 4, 5, 6, 7, 8}
mtFuncIndices := []int{3, 4, 5, 6, 7, 8}
if len(os.Args) == 1 {
var sizes_100 []int
var sizes_10k []int
var sizes_1M []int
for s := int(2e3); s <= 3e3; s += 50 {
sizes_100 = append(sizes_100, s)
}
for s := int(10e3); s <= 200e3; {
sizes_10k = append(sizes_10k, s)
if s < 100e3 {
s += 10e3
} else {
s += 25e3
}
}
for s := int(500e3); s <= 5e6; {
sizes_1M = append(sizes_1M, s)
if s < 2e6 {
s += 250e3
} else {
s += 1e6
}
}
bk("100", sizes_100, allFuncIndices, 5)
bk("10k", sizes_10k, mostFuncIndices, 3)
bk("1M", sizes_1M, mtFuncIndices, 3)
} else if len(os.Args) > 2 {
orderstr := os.Args[1]
var sizes []int
for _, sizestr := range os.Args[2:] {
size, err := StudyIO.ParsePositiveInt(sizestr)
if err != nil {
panic(err)
}
sizes = append(sizes, size)
}
bk(orderstr, sizes, allFuncIndices, 0)
} else {
print("give me one or more sizes too")
}
}
<file_sep>// Naive Bron-Kerbosch algorithm
#pragma once
#include "UndirectedGraph.h"
#include "Util.h"
#include "VertexPile.h"
namespace BronKerbosch {
class BronKerbosch1 {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph) {
auto candidates = graph.connected_vertices();
auto num_candidates = candidates.size();
if (num_candidates) {
return visit<Reporter>(graph, std::move(candidates),
Util::with_capacity<VertexSet>(num_candidates), nullptr);
} else {
return Reporter::empty();
}
}
template <typename Reporter, typename VertexSet>
static Reporter::Result visit(UndirectedGraph<VertexSet> const& graph,
VertexSet&& candidates,
VertexSet&& excluded,
const VertexPile* clique) {
assert(!candidates.empty());
auto cliques = Reporter::empty();
for (;;) {
Vertex v = Util::pop_arbitrary(candidates);
auto const& neighbours = graph.neighbours(v);
assert(!neighbours.empty());
auto neighbouring_candidates = Util::intersection(candidates, neighbours);
if (!neighbouring_candidates.empty()) {
auto neighbouring_excluded = Util::intersection(excluded, neighbours);
auto newclique = VertexPile{v, clique};
Reporter::add_all(
cliques, visit<Reporter>(graph, std::move(neighbouring_candidates),
std::move(neighbouring_excluded), &newclique));
} else {
if (Util::are_disjoint(excluded, neighbours))
Reporter::add_one(cliques, VertexPile(v, clique));
if (candidates.empty())
break;
}
excluded.insert(v);
}
return cliques;
}
};
}
<file_sep>//! Core of Bron-Kerbosch algorithms with pivot
use super::graph::{UndirectedGraph, Vertex, VertexSetLike};
use super::pile::Pile;
use super::reporter::Reporter;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PivotChoice {
Arbitrary,
Random,
MaxDegreeLocal,
MaxDegreeLocalX,
}
type Clique<'a> = Pile<'a, Vertex>;
pub fn explore_with_pivot<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
pivot_selection: PivotChoice,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
let order = graph.order();
if let Some(pivot) = (0..order).map(Vertex::new).max_by_key(|&v| graph.degree(v)) {
let mut excluded = Graph::VertexSet::with_capacity(order);
for v in (0..order).map(Vertex::new) {
let neighbours = graph.neighbours(v);
if !neighbours.is_empty() && !neighbours.contains(pivot) {
let neighbouring_excluded: VertexSet = neighbours.intersection_collect(&excluded);
if neighbouring_excluded.len() < neighbours.len() {
let neighbouring_candidates: VertexSet =
neighbours.difference_collect(&neighbouring_excluded);
visit(
graph,
reporter,
pivot_selection,
neighbouring_candidates,
neighbouring_excluded,
Some(&Pile::from(v)),
);
}
excluded.insert(v);
}
}
}
}
pub fn visit<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
pivot_selection: PivotChoice,
mut candidates: VertexSet,
mut excluded: VertexSet,
clique: Option<&Clique>,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
debug_assert!(candidates.all(|&v| graph.degree(v) > 0));
debug_assert!(excluded.all(|&v| graph.degree(v) > 0));
debug_assert!(candidates.is_disjoint(&excluded));
debug_assert!(candidates.len() >= 1);
if candidates.len() == 1 {
// Same logic as below, but stripped down for this common case
candidates.for_each(|v| {
let neighbours = graph.neighbours(v);
if neighbours.is_disjoint(&excluded) {
reporter.record(Pile::on(clique, v).collect());
}
});
return;
}
let mut pivot: Option<Vertex> = None;
let mut remaining_candidates: Vec<Vertex> = Vec::with_capacity(candidates.len());
match pivot_selection {
PivotChoice::MaxDegreeLocal | PivotChoice::MaxDegreeLocalX => {
// Quickly handle locally unconnected candidates while finding pivot
let mut seen_local_degree = 0;
candidates.for_each(|v| {
let neighbours = graph.neighbours(v);
let local_degree = neighbours.intersection_size(&candidates);
if local_degree == 0 {
// Same logic as below, but stripped down
if neighbours.is_disjoint(&excluded) {
reporter.record(Pile::on(clique, v).collect());
}
} else {
if seen_local_degree < local_degree {
seen_local_degree = local_degree;
pivot = Some(v);
}
remaining_candidates.push(v);
}
});
if remaining_candidates.is_empty() {
return;
}
if pivot_selection == PivotChoice::MaxDegreeLocalX {
excluded.for_each(|v| {
let neighbours = graph.neighbours(v);
let local_degree = neighbours.intersection_size(&candidates);
if seen_local_degree < local_degree {
seen_local_degree = local_degree;
pivot = Some(v);
}
});
}
}
PivotChoice::Arbitrary => {
candidates.for_each(|v| remaining_candidates.push(v));
pivot = candidates.choose_arbitrary().copied();
}
PivotChoice::Random => {
candidates.for_each(|v| remaining_candidates.push(v));
let mut rng = rand::thread_rng();
pivot = candidates.choose(&mut rng).copied();
}
}
debug_assert!(!remaining_candidates.is_empty());
let pivot = pivot.unwrap();
for v in remaining_candidates {
let neighbours = graph.neighbours(v);
if !neighbours.contains(pivot) {
candidates.remove(v);
let neighbouring_candidates: VertexSet = neighbours.intersection_collect(&candidates);
if !neighbouring_candidates.is_empty() {
let neighbouring_excluded = neighbours.intersection_collect(&excluded);
visit(
graph,
reporter,
pivot_selection,
neighbouring_candidates,
neighbouring_excluded,
Some(&Pile::on(clique, v)),
);
} else if excluded.is_disjoint(neighbours) {
reporter.record(Pile::on(clique, v).collect());
}
excluded.insert(v);
}
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
final class DegeneracyOrdering implements PrimitiveIterator.OfInt {
private final UndirectedGraph graph;
// priority_per_vertex:
// If priority is 0, vertex was already picked or was always irrelevant (unconnected);
// otherwise, vertex is still queued and priority = degree + 1 - number of picked neighbours.
private final int[] priority_per_vertex;
@SuppressWarnings("UseOfConcreteClass")
private final SimplePriorityQueue<Integer> queue;
private int num_left_to_pick;
DegeneracyOrdering(UndirectedGraph graph, int drop) {
assert drop <= 0;
this.graph = graph;
var order = graph.order();
var maxPriority = 0;
priority_per_vertex = new int[order];
var numCandidates = 0;
for (int candidate = 0; candidate < order; ++candidate) {
var degree = graph.degree(candidate);
if (degree > 0) {
var priority = degree + 1;
maxPriority = Math.max(maxPriority, priority);
priority_per_vertex[candidate] = priority;
numCandidates += 1;
}
}
queue = new SimplePriorityQueue<>(maxPriority, numCandidates);
for (int candidate = 0; candidate < order; ++candidate) {
var priority = priority_per_vertex[candidate];
if (priority != 0) {
queue.put(priority, candidate);
}
}
num_left_to_pick = numCandidates + drop;
}
@Override
public boolean hasNext() {
return num_left_to_pick > 0;
}
@Override
public int nextInt() {
assert IntStream.range(0, priority_per_vertex.length)
.allMatch(v -> priority_per_vertex[v] == 0
|| queue.contains(priority_per_vertex[v], v));
var i = queue.pop();
while (priority_per_vertex[i] == 0) {
// v was requeued with a more urgent priority and therefore already picked
i = queue.pop();
}
priority_per_vertex[i] = 0;
for (var v : graph.neighbours(i)) {
var oldPriority = priority_per_vertex[v];
if (oldPriority != 0) {
// Since this is an unvisited neighbour of a vertex just being picked,
// its priority can't be down to the minimum.
var newPriority = oldPriority - 1;
assert newPriority > 0;
// Requeue with a more urgent priority, but don't bother to remove
// the original entry - it will be skipped if it's reached at all.
priority_per_vertex[v] = newPriority;
queue.put(newPriority, v);
}
}
num_left_to_pick -= 1;
return i;
}
private static final class SimplePriorityQueue<T> {
private final List<ArrayList<T>> stack_per_priority;
private final int sizeHint;
SimplePriorityQueue(int maxPriority, int sizeHint) {
stack_per_priority = Stream
.generate((Supplier<ArrayList<T>>) ArrayList::new)
.limit(maxPriority)
.collect(Collectors.toCollection(ArrayList::new));
this.sizeHint = sizeHint;
}
void put(int priority, T elt) {
var stack = stack_per_priority.get(priority - 1);
if (stack == null) {
stack = new ArrayList<>(sizeHint);
}
stack.add(elt);
}
T pop() {
for (var stack : stack_per_priority) {
if (!stack.isEmpty()) {
var last = stack.size() - 1;
var elt = stack.get(last);
stack.remove(last);
return elt;
}
}
throw new NoSuchElementException("attempt to pop more than was put");
}
boolean contains(int priority, T elt) {
return stack_per_priority.get(priority - 1).contains(elt);
}
}
IntStream stream() {
var characteristics = Spliterator.ORDERED
| Spliterator.DISTINCT
| Spliterator.NONNULL
| Spliterator.IMMUTABLE;
var spliterator = Spliterators.spliterator(this, num_left_to_pick, characteristics);
return StreamSupport.intStream(spliterator, false);
}
}
<file_sep>#include "pch.h"
#include "Portfolio.h"
#include <stdexcept>
const char* const BronKerbosch::Portfolio::FUNC_NAMES[NUM_FUNCS] = {
"Ver1\xc2\xbd", "Ver2\xc2\xbd-GP", "Ver2\xc2\xbd-GPX",
"Ver3\xc2\xbd-GP", "Ver3\xc2\xbd-GPX", "Ver3\xc2\xbd=GPc",
};
void BronKerbosch::Portfolio::sort_cliques(std::vector<std::vector<Vertex>>& cliques) {
for (auto& clique : cliques)
std::sort(clique.begin(), clique.end());
std::sort(cliques.begin(), cliques.end(), &clique_less);
}
bool BronKerbosch::Portfolio::clique_less(std::vector<Vertex> const& lhs,
std::vector<Vertex> const& rhs) {
for (size_t i = 0; i < lhs.size() && i < rhs.size(); ++i) {
int d = int(lhs[i]) - int(rhs[i]);
if (d != 0)
return d < 0;
}
throw std::logic_error("got overlapping or equal cliques");
}
<file_sep>using System.Collections.Immutable;
namespace BronKerbosch
{
public interface IReporter
{
void Record(ImmutableArray<Vertex> clique);
}
}
<file_sep># coding: utf-8
from abc import abstractmethod, ABCMeta
from typing import List, Sequence
class Reporter(metaclass=ABCMeta):
@abstractmethod
def record(self, clique: Sequence[int]) -> None:
pass
class CollectingReporter(Reporter):
def __init__(self) -> None:
self.cliques: List[Sequence[int]] = []
def record(self, clique: Sequence[int]) -> None:
assert len(clique) > 1
self.cliques.append(clique)
class CountingReporter(Reporter):
def __init__(self) -> None:
self.cliques = 0
def record(self, clique: Sequence[int]) -> None:
self.cliques += 1
<file_sep>package BronKerbosch
import "sync"
func bronKerbosch3gp0(graph *UndirectedGraph, reporter Reporter) {
bronKerbosch3om(graph, reporter, 1)
}
func bronKerbosch3gp1(graph *UndirectedGraph, reporter Reporter) {
bronKerbosch3om(graph, reporter, 4)
}
func bronKerbosch3gp2(graph *UndirectedGraph, reporter Reporter) {
bronKerbosch3om(graph, reporter, 16)
}
func bronKerbosch3gp3(graph *UndirectedGraph, reporter Reporter) {
bronKerbosch3om(graph, reporter, 64)
}
func bronKerbosch3gp4(graph *UndirectedGraph, reporter Reporter) {
bronKerbosch3om(graph, reporter, 256)
}
func bronKerbosch3om(graph *UndirectedGraph, finalReporter Reporter, numVisitors int) {
// Bron-Kerbosch algorithm with degeneracy ordering, multi-threaded
starts := make(chan Vertex, numVisitors)
visits := make(chan VisitJob, numVisitors)
cliques := make(chan []Vertex)
go degeneracyOrdering(graph, &ChannelVertexVisitor{starts}, -1)
go func() {
excluded := make(VertexSet, graph.connectedVertexCount()-1)
reporter := ChannelReporter{cliques}
var wg sync.WaitGroup
wg.Add(numVisitors)
for i := 0; i < numVisitors; i++ {
go func() {
for job := range visits {
visit(
graph, &reporter,
MaxDegreeLocal,
job.candidates,
job.excluded,
[]Vertex{job.start})
}
wg.Done()
}()
}
for v := range starts {
neighbours := graph.neighbours(v)
neighbouringCandidates := neighbours.Difference(excluded)
if !neighbouringCandidates.IsEmpty() {
neighbouringExcluded := neighbours.Intersection(excluded)
visits <- VisitJob{v, neighbouringCandidates, neighbouringExcluded}
}
excluded.Add(v)
}
close(visits)
wg.Wait()
close(reporter.cliques)
}()
for clique := range cliques {
finalReporter.Record(clique)
}
}
type VisitJob struct {
start Vertex
candidates VertexSet
excluded VertexSet
}
<file_sep>// Naive Bron-Kerbosch algorithm
using BronKerbosch;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
internal static class BronKerbosch1<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter)
{
var candidates = VertexSetMgr.From(graph.ConnectedVertices());
var numCandidates = candidates.Count();
if (numCandidates > 0)
{
Visit(
graph,
reporter,
candidates,
VertexSetMgr.EmptyWithCapacity(numCandidates),
ImmutableArray.Create<Vertex>());
}
}
private static void Visit(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter,
VertexSet candidates, VertexSet excluded, ImmutableArray<Vertex> cliqueInProgress)
{
Debug.Assert(candidates.All(v => graph.Degree(v) > 0));
Debug.Assert(excluded.All(v => graph.Degree(v) > 0));
Debug.Assert(!VertexSetMgr.Overlaps(candidates, excluded));
Debug.Assert(candidates.Any());
while (candidates.Any())
{
var v = VertexSetMgr.PopArbitrary(candidates);
var neighbours = graph.Neighbours(v);
var neighbouringCandidates = VertexSetMgr.Intersection(candidates, neighbours);
if (neighbouringCandidates.Any())
{
var neighbouringExcluded = VertexSetMgr.Intersection(excluded, neighbours);
Visit(graph, reporter,
neighbouringCandidates, neighbouringExcluded,
CollectionsUtil.Append(cliqueInProgress, v));
}
else if (!VertexSetMgr.Overlaps(excluded, neighbours))
{
reporter.Record(CollectionsUtil.Append(cliqueInProgress, v));
}
var added = VertexSetMgr.Add(excluded, v);
Debug.Assert(added);
}
}
}
<file_sep>#include "pch.h"
#include "BronKerbosch1.h"
<file_sep>#include "pch.h"
#include <stdexcept>
#include "BronKerbosch/Portfolio.h"
#include "BronKerbosch/UndirectedGraph.h"
#include "Console.h"
#include "RandomGraph.h"
#include "SampleStatistics.h"
using BronKerbosch::ordered_vector;
using BronKerbosch::Portfolio;
using BronKerbosch::UndirectedGraph;
using BronKerbosch::Vertex;
using BronKerbosch::VertexList;
using BronKerboschStudy::RandomGraph;
using BronKerboschStudy::SampleStatistics;
enum class SetType { hashset, std_set, ord_vec };
static int const SET_TYPES = 3;
class Benchmark {
using Times = std::array<SampleStatistics<double>, Portfolio::NUM_FUNCS>;
template <typename VertexSet>
static Times timed(RandomGraph<VertexSet> const& graph,
std::vector<int> const& func_indices,
int timed_samples) {
std::unique_ptr<std::vector<VertexList>> first;
auto times = Times{};
for (int sample = 0; sample <= timed_samples; ++sample) {
for (int func_index : func_indices) {
if (sample == 0) {
auto begin = std::chrono::steady_clock::now();
auto result = Portfolio::explore<Portfolio::CollectingReporter, VertexSet>(func_index, graph);
auto duration = std::chrono::steady_clock::now() - begin;
auto secs = std::chrono::duration<double, std::ratio<1, 1>>(duration).count();
if (duration >= std::chrono::seconds(3)) {
std::cout << " " << std::setw(8) << Portfolio::FUNC_NAMES[func_index]
<< ": " << std::setw(6) << secs << "s" << std::endl;
}
auto obtained_cliques = std::vector<VertexList>(result.begin(), result.end());
Portfolio::sort_cliques(obtained_cliques);
if (first) {
if (*first != obtained_cliques) {
std::cerr << "Expected " << first->size() << ", obtained "
<< obtained_cliques.size() << " cliques\n";
std::exit(EXIT_FAILURE);
}
} else {
if (obtained_cliques.size() != graph.clique_count) {
std::cerr << "Expected " << graph.clique_count << ", obtained "
<< obtained_cliques.size() << " cliques\n";
std::exit(EXIT_FAILURE);
}
first = std::make_unique<std::vector<VertexList>>(obtained_cliques);
}
} else {
auto begin = std::chrono::steady_clock::now();
auto cliques = Portfolio::explore<Portfolio::CountingReporter, VertexSet>(func_index, graph);
auto duration = std::chrono::steady_clock::now() - begin;
if (cliques != graph.clique_count) {
std::cerr << "Expected " << graph.clique_count << ", obtained "
<< cliques << " cliques\n";
std::exit(EXIT_FAILURE);
}
auto secs = std::chrono::duration<double, std::ratio<1, 1>>(duration).count();
times[func_index].put(secs);
}
}
}
return times;
}
template <typename VertexSet>
static Times bk_core(std::string const& orderstr,
unsigned size,
std::vector<int> func_indices,
int timed_samples) {
auto g = RandomGraph<VertexSet>::readUndirected(orderstr, size);
return timed(g, func_indices, timed_samples);
}
static Times bk_core(SetType set_type,
std::string const& orderstr,
unsigned size,
std::function<std::vector<int>(SetType, unsigned size)> includedFuncs,
int timed_samples) {
auto func_indices = includedFuncs(set_type, size);
if (func_indices.empty()) {
return Times{};
} else {
switch (set_type) {
case SetType::std_set:
return bk_core<std::set<Vertex>>(orderstr, size, func_indices, timed_samples);
case SetType::ord_vec:
return bk_core<ordered_vector<Vertex>>(orderstr, size, func_indices,
timed_samples);
case SetType::hashset:
return bk_core<std::unordered_set<Vertex>>(orderstr, size, func_indices,
timed_samples);
}
throw std::logic_error("unreachable");
}
}
static const char* set_type_name(SetType set_type) {
switch (set_type) {
case SetType::std_set: return "std_set";
case SetType::ord_vec: return "ord_vec";
case SetType::hashset: return "hashset";
}
throw std::logic_error("unreachable");
}
public:
static void bk(std::string const& orderstr,
std::vector<unsigned> const& sizes,
std::function<std::vector<int>(SetType, unsigned size)> includedFuncs,
int timed_samples) {
auto tmpfname = "tmp.csv";
{
auto fo = std::ofstream{tmpfname};
fo << "Size";
for (int set_type_index = 0; set_type_index < SET_TYPES; ++set_type_index) {
for (auto name : Portfolio::FUNC_NAMES) {
fo << "," << name << "@" << set_type_name(SetType(set_type_index)) << " min";
fo << "," << name << "@" << set_type_name(SetType(set_type_index)) << " mean";
fo << "," << name << "@" << set_type_name(SetType(set_type_index)) << " max";
}
}
fo << "\n";
for (int size : sizes) {
fo << size;
for (int set_type_index = 0; set_type_index < SET_TYPES; ++set_type_index) {
auto set_type = SetType(set_type_index);
Times stats = bk_core(set_type, orderstr, size, includedFuncs, timed_samples);
for (int func_index = 0; func_index < Portfolio::NUM_FUNCS; ++func_index) {
auto func_name = Portfolio::FUNC_NAMES[func_index];
auto max = stats[func_index].max();
auto min = stats[func_index].min();
auto mean = stats[func_index].mean();
fo << "," << min;
fo << "," << mean;
fo << "," << max;
if (!std::isnan(mean)) {
auto reldev = stats[func_index].deviation() / mean;
auto p = std::cout.precision(3);
auto f = std::cout.setf(std::ios_base::fixed);
std::cout << "order " << std::setw(4) << orderstr;
std::cout << " size " << std::setw(7) << size;
std::cout << " " << std::setw(8) << func_name;
std::cout << "@" << set_type_name(set_type);
std::cout << ": " << std::setw(6) << mean << "s ± "
<< std::setprecision(0) << reldev * 100 << "%\n";
std::cout.flush();
std::cout.precision(p);
std::cout.setf(f);
}
}
}
fo << std::endl;
}
}
auto path = "..\\bron_kerbosch_c++_order_" + orderstr + ".csv";
std::remove(path.c_str());
auto rc = std::rename(tmpfname, path.c_str());
if (rc != 0) {
std::cerr << "Failed to rename " << tmpfname << " to " << path << "(" << rc << ")\n";
}
}
};
template <typename T>
static std::vector<T> range(T first, T last, T step) {
std::vector<T> result;
for (T i = first; i <= last; i += step) {
result.push_back(i);
}
return result;
}
template <typename... Args>
void concat1(std::vector<unsigned>&) {
}
template <typename... Args>
void concat1(std::vector<unsigned>& builder, std::vector<unsigned> const& arg, Args... args) {
std::copy(arg.begin(), arg.end(), std::back_inserter(builder));
concat1(builder, args...);
}
template <typename... Args>
std::vector<unsigned> concat(Args... args) {
std::vector<unsigned> result;
concat1(result, args...);
return result;
}
int main(int argc, char** argv) {
console_init();
#ifndef NDEBUG
std::cerr << "Run Release build instead for meaningful measurements\n";
// return EXIT_FAILURE;
#endif
std::vector<int> all_func_indices(Portfolio::NUM_FUNCS);
std::iota(all_func_indices.begin(), all_func_indices.end(), 0);
std::vector<int> most_func_indices(Portfolio::NUM_FUNCS - 1);
std::iota(most_func_indices.begin(), most_func_indices.end(), 1);
if (argc == 1) {
Benchmark::bk(
"100", range(2'000u, 3'000u, 50u), [&](SetType, unsigned) { return all_func_indices; },
5);
Benchmark::bk(
"10k",
concat(range(1'000u, 9'000u, 1'000u), range(10'000u, 90'000u, 10'000u),
range(100'000u, 200'000u, 25'000u)),
[&](SetType set_type, unsigned size) {
switch (set_type) {
case SetType::std_set:
if (size > 7'000)
return std::vector<int>{};
else
[[fallthrough]];
case SetType::hashset: [[fallthrough]];
case SetType::ord_vec: return most_func_indices;
}
throw std::logic_error("unreachable");
},
3);
Benchmark::bk(
"1M",
concat(range(500'000u, 1'999'999u, 250'000u),
range(2'000'000u, 5'000'000u, 1'000'000u)),
[&](SetType set_type, unsigned) {
switch (set_type) {
case SetType::std_set: [[fallthrough]];
case SetType::ord_vec: return std::vector<int>{};
case SetType::hashset: return std::vector<int>{1, 3, 5};
}
throw std::logic_error("unreachable");
},
3);
return EXIT_SUCCESS;
} else if (argc == 3) {
auto orderstr = argv[1];
unsigned size = BronKerboschStudy::parseInt(argv[2]);
Benchmark::bk(
orderstr, range(size, size, 1u), [&](SetType, unsigned) { return all_func_indices; },
0);
return EXIT_SUCCESS;
} else if (argc == 4) {
auto orderstr = argv[1];
unsigned size = BronKerboschStudy::parseInt(argv[2]);
int func_index = atoi(argv[3]);
Benchmark::bk(
orderstr, range(size, size, 1u),
[func_index](SetType set_type, unsigned) {
switch (set_type) {
case SetType::std_set: [[fallthrough]];
case SetType::ord_vec: return std::vector<int>{};
case SetType::hashset: return std::vector<int>{func_index};
}
throw std::logic_error("unreachable");
},
0);
return EXIT_SUCCESS;
} else {
std::cerr << "Specify order and size\n";
return EXIT_FAILURE;
}
}
<file_sep>package Assert
import (
"testing"
)
func TestAssert(t *testing.T) {
IsTrue(true)
IsFalse(false)
AreEqual(1, 1)
AreNotEqual(0, 1)
IsNotNull(0)
IsNull(nil)
}
<file_sep>#pragma once
#include <vector>
#include "Vertex.h"
namespace BronKerbosch {
class VertexPile {
public:
/// Create a pile, optionally on top of an existing pile
explicit VertexPile(Vertex v, const VertexPile* lower = NULL)
: top(v), height(lower ? lower->height : 1), lower(lower) {
}
/// Clone contained elements into a vector, in the order they were placed
std::vector<Vertex> collect() const {
auto result = std::vector<Vertex>{};
result.reserve(height);
push_to(result);
return result;
}
private:
void push_to(std::vector<Vertex>& result) const {
if (lower)
lower->push_to(result);
result.push_back(top);
}
Vertex const top;
unsigned const height;
const VertexPile* const lower;
};
}
<file_sep>pub use super::vertex::Vertex;
use rand::Rng;
use std::fmt::Debug;
use std::iter::FromIterator;
pub trait VertexSetLike: Debug + Eq + FromIterator<Vertex> + Send + Sync {
fn new() -> Self;
fn with_capacity(capacity: usize) -> Self;
fn is_empty(&self) -> bool;
fn len(&self) -> usize;
fn contains(&self, v: Vertex) -> bool;
fn difference_collect(&self, other: &Self) -> Self;
fn is_disjoint(&self, other: &Self) -> bool;
fn intersection_size(&self, other: &Self) -> usize;
fn intersection_collect(&self, other: &Self) -> Self;
fn reserve(&mut self, additional: usize);
fn insert(&mut self, v: Vertex);
fn remove(&mut self, v: Vertex);
fn pop_arbitrary(&mut self) -> Option<Vertex>;
fn choose_arbitrary(&self) -> Option<&Vertex>;
fn choose(&self, rng: &mut impl Rng) -> Option<&Vertex>;
fn clear(&mut self);
fn all<F>(&self, f: F) -> bool
where
F: Fn(&Vertex) -> bool;
fn for_each<F>(&self, f: F)
where
F: FnMut(Vertex);
}
<file_sep>#pragma once
#include "BronKerbosch/UndirectedGraph.h"
namespace BronKerboschStudy {
unsigned parseInt(std::string const&);
using BronKerbosch::UndirectedGraph;
template <typename VertexSet>
class RandomGraph : public UndirectedGraph<VertexSet> {
public:
const size_t clique_count;
private:
RandomGraph(std::vector<VertexSet>&& adjacencies, size_t clique_count)
: UndirectedGraph<VertexSet>(std::move(adjacencies)), clique_count(clique_count) {
}
public:
static RandomGraph<VertexSet> readUndirected(std::string const& orderstr, unsigned size) {
unsigned order = parseInt(orderstr);
auto fully_meshed_size = (unsigned long)order * (order - 1) / 2;
if (size > fully_meshed_size) {
std::cerr << order << " nodes accommodate at most " << fully_meshed_size
<< " edges\n";
std::exit(EXIT_FAILURE);
}
auto edges_path = std::string("..\\data\\random_edges_order_") + orderstr + ".txt";
auto stats_path = std::string("..\\data\\random_stats.txt");
auto adjacencies = readEdges(edges_path, orderstr, size);
auto expected_clique_count = readStats(stats_path, orderstr, size);
auto g = RandomGraph<VertexSet>{std::move(adjacencies), expected_clique_count};
if (g.order() != order || g.size() != size) {
std::cerr << "Messed up while reading " << edges_path << "\n";
std::exit(EXIT_FAILURE);
}
return g;
}
private:
static std::vector<VertexSet> readEdges(std::string const& path,
std::string const& orderstr,
unsigned size) {
unsigned order = parseInt(orderstr);
unsigned line_idx = 0;
std::vector<VertexSet> adjacencies(order);
{
std::ifstream file(path.c_str());
if (!file) {
std::cerr << "Missing " << path << "\n";
std::exit(EXIT_FAILURE);
}
for (; line_idx < size; ++line_idx) {
int v, w;
if (!(file >> v >> w)) {
break;
}
auto added1 = adjacencies[v].insert(w).second;
auto added2 = adjacencies[w].insert(v).second;
if (!added1 || !added2) {
std::cerr << "Corrupt " << path << "\n";
std::exit(EXIT_FAILURE);
}
}
}
if (line_idx < size) {
std::cerr << "Exhausted generated list of " << line_idx << " edges in " << path
<< "\n";
std::exit(EXIT_FAILURE);
}
return adjacencies;
}
static size_t readStats(std::string const& path,
std::string const& orderstr,
unsigned size) {
std::ifstream file(path.c_str());
if (!file) {
std::cerr << "Missing " << path << "\n";
std::exit(EXIT_FAILURE);
}
std::string header;
getline(file, header);
std::string o;
unsigned s;
size_t clique_count;
while ((file >> o >> s >> clique_count)) {
if (o == orderstr && s == size) {
return clique_count;
}
}
std::cerr << "Missing entry in " << path << "\n";
std::exit(EXIT_FAILURE);
}
};
}
<file_sep>package be.steinsomers.bron_kerbosch.study;
import be.steinsomers.bron_kerbosch.UndirectedGraph;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.List;
import java.util.Set;
final class BronKerboschTest {
private static void bk(Collection<List<Integer>> adjacenciesList,
List<List<Integer>> expectedCliques) {
var adjacencies = adjacenciesList.stream().map(Set::copyOf).toList();
var graph = new UndirectedGraph(adjacencies);
for (int funcIndex = 0; funcIndex < Main.FUNCS.length; ++funcIndex) {
var funcName = Main.FUNC_NAMES[funcIndex];
Collection<int[]> rawCliques;
try {
rawCliques = Main.FUNCS[funcIndex].explore(graph).toList();
} catch (InterruptedException ex) {
throw new AssertionError(ex);
}
var cliques = Main.OrderCliques(rawCliques);
Assertions.assertEquals(expectedCliques, cliques,
String.format("Unexpected result for %s", funcName));
}
}
@Test
void order_0() {
bk(List.of(), List.of());
}
@Test
void order_1() {
bk(List.of(List.of()), List.of());
}
@Test
void order_2_isolated() {
bk(List.of(List.of(), List.of()), List.of());
}
@Test
void order_2_connected() {
bk(List.of(List.of(1), List.of(0)), List.of(List.of(0, 1)));
}
@Test
void order_3_size_1_left() {
bk(List.of(List.of(1), List.of(0), List.of()), List.of(List.of(0, 1)));
}
@Test
void order_3_size_1_middle() {
bk(List.of(List.of(2), List.of(), List.of(0)), List.of(List.of(0, 2)));
}
@Test
void order_3_size_1_right() {
bk(List.of(List.of(), List.of(2), List.of(1)), List.of(List.of(1, 2)));
}
@Test
void order_3_size_2() {
bk(List.of(List.of(1), List.of(0, 2), List.of(1)), List.of(List.of(0, 1), List.of(1, 2)));
}
@Test
void order_3_size_3() {
bk(List.of(List.of(1, 2), List.of(0, 2), List.of(0, 1)), List.of(List.of(0, 1, 2)));
}
@Test
void order_4_size_2() {
bk(
List.of(List.of(1), List.of(0), List.of(3), List.of(2)),
List.of(List.of(0, 1), List.of(2, 3))
);
}
@Test
void order_4_size_3_bus() {
bk(
List.of(List.of(1), List.of(0, 2), List.of(1, 3), List.of(2)),
List.of(List.of(0, 1), List.of(1, 2), List.of(2, 3))
);
}
@Test
void order_4_size_3_star() {
bk(
List.of(List.of(1, 2, 3), List.of(0), List.of(0), List.of(0)),
List.of(List.of(0, 1), List.of(0, 2), List.of(0, 3))
);
}
@Test
void order_4_size_4_p() {
bk(
List.of(List.of(1), List.of(0, 2, 3), List.of(1, 3), List.of(1, 2)),
List.of(List.of(0, 1), List.of(1, 2, 3))
);
}
@Test
void order_4_size_4_square() {
bk(
List.of(List.of(1, 3), List.of(0, 2), List.of(1, 3), List.of(0, 2)),
List.of(List.of(0, 1), List.of(0, 3), List.of(1, 2), List.of(2, 3))
);
}
@Test
void order_4_size_5() {
bk(
List.of(List.of(1, 2, 3), List.of(0, 2), List.of(0, 1, 3), List.of(0, 2)),
List.of(List.of(0, 1, 2), List.of(0, 2, 3))
);
}
@Test
void order_4_size_6() {
bk(
List.of(List.of(1, 2, 3), List.of(0, 2, 3), List.of(0, 1, 3), List.of(0, 1, 2)),
List.of(List.of(0, 1, 2, 3))
);
}
@Test
void order_5_penultimate() {
bk(
List.of(
List.of(1, 2, 3, 4),
List.of(0, 2, 3, 4),
List.of(0, 1, 3, 4),
List.of(0, 1, 2),
List.of(0, 1, 2)
),
List.of(List.of(0, 1, 2, 3), List.of(0, 1, 2, 4))
);
}
@Test
void sample() {
bk(
List.of(
List.of(),
List.of(2, 3, 4),
List.of(1, 3, 4, 5),
List.of(1, 2, 4, 5),
List.of(1, 2, 3),
List.of(2, 3, 6, 7),
List.of(5, 7),
List.of(5, 6)
),
List.of(List.of(1, 2, 3, 4), List.of(2, 3, 5), List.of(5, 6, 7))
);
}
@Test
void bigger() {
bk(
List.of(
List.of(1, 2, 3, 4, 6, 7),
List.of(0, 3, 6, 7, 8, 9),
List.of(0, 3, 5, 7, 8, 9),
List.of(0, 1, 2, 4, 9),
List.of(0, 3, 6, 7, 9),
List.of(2, 6),
List.of(0, 1, 4, 5, 9),
List.of(0, 1, 2, 4, 9),
List.of(1, 2),
List.of(1, 2, 3, 4, 6, 7)
),
List.of(
List.of(0, 1, 3),
List.of(0, 1, 6),
List.of(0, 1, 7),
List.of(0, 2, 3),
List.of(0, 2, 7),
List.of(0, 3, 4),
List.of(0, 4, 6),
List.of(0, 4, 7),
List.of(1, 3, 9),
List.of(1, 6, 9),
List.of(1, 7, 9),
List.of(1, 8),
List.of(2, 3, 9),
List.of(2, 5),
List.of(2, 7, 9),
List.of(2, 8),
List.of(3, 4, 9),
List.of(4, 6, 9),
List.of(4, 7, 9),
List.of(5, 6)
)
);
}
}
<file_sep>#include "pch.h"
#include "BronKerbosch/Util.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BronKerbosch {
TEST_CLASS(UtilUnitTest) {
public:
template <typename VertexSet>
void Util_pop_arbitray() {
auto one = VertexSet{1};
auto two = VertexSet{1, 2};
Assert::AreEqual(1, Util::pop_arbitrary(one));
Assert::IsTrue(one.empty());
auto x = Util::pop_arbitrary(two);
auto y = Util::pop_arbitrary(two);
Assert::AreEqual(1, std::min(x, y));
Assert::AreEqual(2, std::max(x, y));
}
template <typename VertexSet>
void Util_are_disjoint() {
auto const empty = VertexSet{};
auto const one = VertexSet{1};
auto const two = VertexSet{1, 2};
auto const six = VertexSet{0, 1, 2, 3, 4, 5};
Assert::IsTrue(Util::are_disjoint(empty, one));
Assert::IsTrue(Util::are_disjoint(one, empty));
Assert::IsTrue(Util::are_disjoint(empty, two));
Assert::IsTrue(Util::are_disjoint(two, empty));
Assert::IsTrue(Util::are_disjoint(empty, six));
Assert::IsTrue(Util::are_disjoint(six, empty));
Assert::IsFalse(Util::are_disjoint(one, two));
Assert::IsFalse(Util::are_disjoint(two, one));
Assert::IsFalse(Util::are_disjoint(one, six));
Assert::IsFalse(Util::are_disjoint(six, one));
Assert::IsFalse(Util::are_disjoint(two, six));
Assert::IsFalse(Util::are_disjoint(six, two));
Assert::IsFalse(Util::are_disjoint(one, one));
Assert::IsFalse(Util::are_disjoint(two, two));
Assert::IsFalse(Util::are_disjoint(six, six));
}
template <typename VertexSet>
void Util_intersection() {
auto const empty = VertexSet{};
auto const one = VertexSet{1};
auto const two = VertexSet{1, 2};
auto const six = VertexSet{0, 1, 2, 3, 4, 5};
Assert::IsTrue(Util::intersection(empty, one) == empty);
Assert::IsTrue(Util::intersection(one, empty) == empty);
Assert::IsTrue(Util::intersection(empty, two) == empty);
Assert::IsTrue(Util::intersection(two, empty) == empty);
Assert::IsTrue(Util::intersection(empty, six) == empty);
Assert::IsTrue(Util::intersection(six, empty) == empty);
Assert::IsTrue(Util::intersection(one, two) == one);
Assert::IsTrue(Util::intersection(two, one) == one);
Assert::IsTrue(Util::intersection(one, six) == one);
Assert::IsTrue(Util::intersection(six, one) == one);
Assert::IsTrue(Util::intersection(two, six) == two);
Assert::IsTrue(Util::intersection(six, two) == two);
Assert::IsTrue(Util::intersection(one, one) == one);
Assert::IsTrue(Util::intersection(two, two) == two);
Assert::IsTrue(Util::intersection(six, six) == six);
}
template <typename VertexSet>
void Util_intersection_size() {
auto const empty = VertexSet{};
auto const one = VertexSet{1};
auto const two = VertexSet{1, 2};
auto const six = VertexSet{0, 1, 2, 3, 4, 5};
Assert::IsTrue(Util::intersection_size(empty, one) == 0);
Assert::IsTrue(Util::intersection_size(one, empty) == 0);
Assert::IsTrue(Util::intersection_size(empty, two) == 0);
Assert::IsTrue(Util::intersection_size(two, empty) == 0);
Assert::IsTrue(Util::intersection_size(empty, six) == 0);
Assert::IsTrue(Util::intersection_size(six, empty) == 0);
Assert::IsTrue(Util::intersection_size(one, two) == 1);
Assert::IsTrue(Util::intersection_size(two, one) == 1);
Assert::IsTrue(Util::intersection_size(one, six) == 1);
Assert::IsTrue(Util::intersection_size(six, one) == 1);
Assert::IsTrue(Util::intersection_size(two, six) == 2);
Assert::IsTrue(Util::intersection_size(six, two) == 2);
Assert::IsTrue(Util::intersection_size(one, one) == 1);
Assert::IsTrue(Util::intersection_size(two, two) == 2);
Assert::IsTrue(Util::intersection_size(six, six) == 6);
}
template <typename VertexSet>
void Util_difference() {
auto const empty = VertexSet{};
auto const one = VertexSet{1};
auto const two = VertexSet{1, 2};
auto const six = VertexSet{0, 1, 2, 3, 4, 5};
Assert::IsTrue(Util::difference(empty, one) == empty);
Assert::IsTrue(Util::difference(empty, two) == empty);
Assert::IsTrue(Util::difference(empty, six) == empty);
Assert::IsTrue(Util::difference(one, one) == empty);
Assert::IsTrue(Util::difference(one, two) == empty);
Assert::IsTrue(Util::difference(one, six) == empty);
Assert::IsTrue(Util::difference(two, two) == empty);
Assert::IsTrue(Util::difference(two, six) == empty);
Assert::IsTrue(Util::difference(six, six) == empty);
Assert::IsTrue(Util::difference(one, empty) == one);
Assert::IsTrue(Util::difference(two, empty) == two);
Assert::IsTrue(Util::difference(six, empty) == six);
Assert::IsTrue(Util::difference(two, one) == VertexSet{2});
Assert::IsTrue(Util::difference(six, one) == VertexSet{0, 2, 3, 4, 5});
Assert::IsTrue(Util::difference(six, two) == VertexSet{0, 3, 4, 5});
}
TEST_METHOD(Util_pop_arbitray_set) {
Util_pop_arbitray<std::set<int>>();
}
TEST_METHOD(Util_pop_arbitray_ordered_vector) {
Util_pop_arbitray<ordered_vector<int>>();
}
TEST_METHOD(Util_pop_arbitray_unordered_set) {
Util_pop_arbitray<std::unordered_set<int>>();
}
TEST_METHOD(Util_are_disjoint_set) {
Util_are_disjoint<std::set<int>>();
}
TEST_METHOD(Util_are_disjoint_ordered_vector) {
Util_are_disjoint<ordered_vector<int>>();
}
TEST_METHOD(Util_are_disjoint_unordered_set) {
Util_are_disjoint<std::unordered_set<int>>();
}
TEST_METHOD(Util_intersection_size_set) {
Util_intersection_size<std::set<int>>();
}
TEST_METHOD(Util_intersection_size_ordered_vector) {
Util_intersection_size<ordered_vector<int>>();
}
TEST_METHOD(Util_intersection_size_unordered_set) {
Util_intersection_size<std::unordered_set<int>>();
}
TEST_METHOD(Util_intersection_set) {
Util_intersection<std::set<int>>();
}
TEST_METHOD(Util_intersection_ordered_vector) {
Util_intersection<ordered_vector<int>>();
}
TEST_METHOD(Util_intersection_unordered_set) {
Util_intersection<std::unordered_set<int>>();
}
TEST_METHOD(Util_difference_set) {
Util_difference<std::set<int>>();
}
TEST_METHOD(Util_difference_ordered_vector) {
Util_difference<ordered_vector<int>>();
}
TEST_METHOD(Util_difference_unordered_set) {
Util_difference<std::unordered_set<int>>();
}
};
}
<file_sep>//! Bron-Kerbosch algorithm with pivot picked randomly (IK_RP)
use super::bron_kerbosch_pivot::{visit, PivotChoice};
use super::graph::{connected_vertices, UndirectedGraph, VertexSetLike};
use super::reporter::Reporter;
pub fn explore<Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
Graph: UndirectedGraph,
Rprtr: Reporter,
{
let candidates = connected_vertices(graph);
if !candidates.is_empty() {
visit(
graph,
reporter,
PivotChoice::Random,
candidates,
Graph::VertexSet::new(),
None,
);
}
}
<file_sep>#include "pch.h"
#include "UndirectedGraph.h"
<file_sep>#include "pch.h"
#include "BronKerbosch/VertexPile.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BronKerbosch {
TEST_CLASS(VertexPileUnitTest) {
public:
TEST_METHOD(collect) {
auto p1 = VertexPile{4};
{
auto p2 = VertexPile{2, &p1};
Assert::IsTrue(p2.collect() == std::vector<Vertex>{4, 2});
}
Assert::IsTrue(p1.collect() == std::vector<Vertex>{4});
}
};
}
<file_sep>module BronKerboschStudy
go 1.18
<file_sep>package BronKerbosch
type Reporter interface {
Record(clique []Vertex)
}
type CollectingReporter struct {
Cliques [][]Vertex
}
func (r *CollectingReporter) Record(clique []Vertex) {
cc := make([]Vertex, len(clique))
copy(cc, clique)
r.Cliques = append(r.Cliques, cc)
}
type CountingReporter struct {
Cliques int
}
func (r *CountingReporter) Record(clique []Vertex) {
r.Cliques += 1
}
type ChannelReporter struct {
cliques chan<- []Vertex
}
func (r *ChannelReporter) Record(clique []Vertex) {
cc := make([]Vertex, len(clique))
copy(cc, clique)
r.cliques <- cc
}
<file_sep>from collections import OrderedDict
from stats import SampleStatistics
from bisect import bisect_left
import csv
import math
import os
import sys
from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple
figsize_inline = (8, 6) # in hectopixels
figsize_detail = (12, 9) # in hectopixels
def lang_name(case_name: str) -> str:
return case_name.split(' ', 1)[0].split('@', 1)[0]
def func_name(case_name: str) -> str:
return case_name.split(' ')[-1].split('@')[0]
def color_by_func_name(case_name: str) -> str:
return {
"Ver1": "#000099",
"Ver1½": "#6666FF",
"Ver2": "#660000",
"Ver2½": "#CC0000",
"Ver2-GP": "#666633",
"Ver2½-GP": "#FF6600",
"Ver2½-GPX": "#FFCC33",
"Ver2½-RP": "#FF00CC",
"Ver3½": "#006600",
"Ver3½-GP": "#339900",
"Ver3½-GPX": "#33CC00",
"Ver3½=GPc": "#669999",
"Ver3½=GPs": "#669966",
"Ver3½=GP0": "#3399CC",
"Ver3½=GP1": "#669999",
"Ver3½=GP2": "#669966",
"Ver3½=GP3": "#669933",
"Ver3½=GP4": "#669900",
}[func_name(case_name)]
def color_by_language(case_name: str) -> str:
return {
"Python311": "#000099",
"Rust": "#CC0033",
"Java": "#009933",
"Scala": "#006666",
"C#": "#666600",
"C++": "#990000",
"Go": "#0000CC",
}[lang_name(case_name)]
def linestyle_by_lib(lib: str) -> object:
return {
"BTree": "dotted",
"std_set": "dotted",
"SortedSet": "dotted",
"ord_vec": "dashed",
"hashbrown": "dashdot",
"fnv": (0, (4, 2, 1, 1, 1, 2)),
}.get(lib)
class Measurement(object):
def __init__(self, min: float, mean: float, max: float) -> None:
self.min = min
self.mean = mean
self.max = max
def isnan(self) -> bool:
return math.isnan(self.mean)
def error_plus(self) -> float:
return self.max - self.mean
def error_minus(self) -> float:
return self.mean - self.min
def clean_language(language: str) -> str:
return language.replace("c#", "csharp")
def csv_basename(language: str, orderstr: str) -> str:
return f"bron_kerbosch_{clean_language(language)}_order_{orderstr}.csv"
def publish(
language: str, orderstr: str, case_names: Sequence[str],
stats_per_func_by_size: Mapping[int, List[SampleStatistics]]) -> None:
num_cases = len(case_names)
filename = csv_basename(language, orderstr)
path = os.path.join(os.pardir, filename)
with open(path, 'w', newline='', encoding='utf-8') as csvfile:
w = csv.writer(csvfile)
w.writerow(["Size"] + [(f"{name} {t}") for name in case_names
for t in ["min", "mean", "max"]])
for size, stats in stats_per_func_by_size.items():
w.writerow(
[str(size)] +
[str(f) for s in stats for f in [s.min, s.mean(), s.max]])
publish_whole_csv(language=language, orderstr=orderstr)
def read_seconds(s: str) -> float:
return float(s) if s else math.nan
def read_csv(
language: str,
orderstr: str,
case_name_selector: Mapping[str, str] = {}
) -> Tuple[List[int], Mapping[str, List[Measurement]]]:
filename = csv_basename(language, orderstr)
path = os.path.join(os.pardir, filename)
if not os.path.exists(path):
path = filename
sizes = []
m_per_size_by_case_name: Dict[str, List[Measurement]] = {}
with open(path, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
head = next(reader)
num_cases = (len(head) - 1) // 3
expected_cols = 1 + num_cases * 3
if len(head) != expected_cols:
raise ImportError(
f"{filename}: Found {len(head)} columns, expected {expected_cols}"
)
if head[0] != "Size":
raise ImportError("unexpected " + str(head[0]))
if not all(h.endswith(" min") for h in head[1::3]):
raise ImportError("unexpected " + str(head[1::3]))
if not all(h.endswith(" mean") for h in head[2::3]):
raise ImportError("unexpected " + str(head[2::3]))
if not all(h.endswith(" max") for h in head[3::3]):
raise ImportError("unexpected " + str(head[3::3]))
case_names = [h.split()[0] for h in head[2::3]]
for case_name in case_names:
try:
color_by_func_name(case_name)
except KeyError as e:
raise ImportError(
f'{filename}: unrecognized case name "{case_name}"') from e
for i, row in enumerate(reader):
if len(row) != expected_cols:
raise ImportError(
f"{filename} row {i+2}: found {len(row)} columns, expected {expected_cols}"
)
size = int(row[0])
sizes.append(size)
for c, case_name in enumerate(case_names):
published_name = (case_name_selector.get(case_name)
if case_name_selector else case_name)
if published_name is not None:
m = Measurement(min=read_seconds(row[c * 3 + 1]),
mean=read_seconds(row[c * 3 + 2]),
max=read_seconds(row[c * 3 + 3]))
m_per_size_by_case_name.setdefault(published_name,
[]).append(m)
for case_name in list(m_per_size_by_case_name.keys()):
if all(m_per_size_by_case_name[case_name][s].isnan()
for s in range(len(sizes))):
print(f"{filename}: backing out on {case_name}")
del m_per_size_by_case_name[case_name]
assert len(sizes)
assert len(m_per_size_by_case_name)
assert all(
len(m_per_size) == len(sizes)
for m_per_size in m_per_size_by_case_name.values())
return sizes, m_per_size_by_case_name
def import_matplotlib() -> bool:
try:
import matplotlib # type: ignore
except ImportError as e:
print(f"{e} (maybe you want to `pip install matplotlib`?)")
return False
else:
matplotlib.rcParams['svg.hashsalt'] = "Bron-Kerbosch"
return True
def publish_whole_csv(language: str, orderstr: str) -> None:
sizes, m_per_size_by_case_name = read_csv(language, orderstr)
if import_matplotlib():
if cutoff := {
("c++", "10k"): 10_000,
("rust", "10k"): 50_000,
("rust", "1M"): 500_000
}.get((language, orderstr)):
idx = bisect_left(sizes, cutoff)
sizes_1 = sizes[:idx]
sizes = sizes[idx:]
m_per_size_by_case_name_1 = {
case_name: m_per_size[:idx]
for case_name, m_per_size in m_per_size_by_case_name.items()
}
m_per_size_by_case_name = {
case_name: m_per_size[idx:]
for case_name, m_per_size in m_per_size_by_case_name.items()
if not all(m.isnan() for m in m_per_size[idx:])
}
publish_details(language,
orderstr,
sizes_1,
m_per_size_by_case_name_1,
basename_variant="_initial")
publish_details(language, orderstr, sizes, m_per_size_by_case_name)
def publish_details(language: str,
orderstr: str,
sizes: List[int],
m_per_size_by_case_name: Mapping[str, List[Measurement]],
basename_variant: str = "") -> None:
assert len(sizes)
assert len(m_per_size_by_case_name)
assert all(
len(m_per_size) == len(sizes)
for m_per_size in m_per_size_by_case_name.values())
basename = f'details_{clean_language(language)}_{orderstr}{basename_variant}'
from matplotlib import pyplot
fig, axes = pyplot.subplots(figsize=figsize_detail)
axes.set_title(f"{language.capitalize()} implementations of " +
f"Bron-Kerbosch on a random graph of order {orderstr}")
axes.set_xlabel("Size (#edges)")
axes.set_ylabel("Seconds spent")
if not basename_variant:
axes.set_yscale("log")
linestyles: Dict[str, object] = OrderedDict()
for case_name, m_per_size in m_per_size_by_case_name.items():
names = case_name.split('@')
func_name = names[0]
lib = (names + [""])[1]
linestyle = linestyle_by_lib(lib)
linestyles.setdefault(lib, linestyle)
axes.errorbar(x=sizes[:len(m_per_size)],
y=[m.mean for m in m_per_size],
yerr=[[m.error_minus() for m in m_per_size],
[m.error_plus() for m in m_per_size]],
label=func_name if linestyle is None else None,
capsize=3,
color=color_by_func_name(case_name),
linestyle=linestyle)
axes.legend(loc="upper left")
if len(linestyles) > 1:
twin = axes.twinx()
twin.get_yaxis().set_visible(False)
for lib, linestyle in linestyles.items():
twin.plot([], linestyle=linestyle, label=lib, color="black")
twin.legend(loc="lower right")
fig.tight_layout()
fig.savefig(basename + ".svg", bbox_inches=0, pad_inches=0)
def publish_measurements(
basename: str,
orderstr: str,
sizes: List[int],
measurement_per_size_by_case_name: Mapping[str, List[Measurement]],
suffix: str = "",
language: Optional[str] = None,
color_by_case: Optional[Callable[[str], str]] = None,
dash_by_case: Optional[Callable[[str], str]] = None) -> None:
assert sizes
assert measurement_per_size_by_case_name, basename
print("Generating", basename)
if import_matplotlib():
from matplotlib import pyplot
fig, axes = pyplot.subplots(figsize=figsize_inline)
axes.set_title(
(f"{language.capitalize()} implementations of "
if language else "") +
f"Bron-Kerbosch{suffix} on a random graph of order {orderstr}",
loc="left")
axes.set_xlabel("Size (#edges)")
axes.set_ylabel("Seconds spent")
for case_name, m_per_size in measurement_per_size_by_case_name.items():
axes.errorbar(x=sizes[:len(m_per_size)],
y=[m.mean for m in m_per_size],
yerr=[[m.error_minus() for m in m_per_size],
[m.error_plus() for m in m_per_size]],
label=case_name,
capsize=3,
color=(None if color_by_case is None else
color_by_case(case_name)),
linestyle=(None if dash_by_case is None else
dash_by_case(case_name)))
axes.legend(loc="upper left")
fig.tight_layout()
fig.savefig(basename + ".svg", bbox_inches=0, pad_inches=0)
pyplot.close(fig)
def publish_report(
basename: str,
orderstr: str,
langlibs: Sequence[str],
versions: Sequence[str],
single_version: Optional[str] = None,
dash_by_case: Optional[Callable[[str], str]] = None) -> None:
sizes: List[int] = []
measurements: Dict[str, List[Measurement]] = {}
languages = set(langlib.split('@', 1)[0] for langlib in langlibs)
assert len(languages) > 1
for langlib in langlibs:
lang_lib = langlib.split('@', 1)
lang = lang_lib[0]
at_lib = ("@" + lang_lib[1]) if len(lang_lib) > 1 else ""
sizes1, measurements1 = read_csv(
language=lang,
orderstr=orderstr,
case_name_selector={
f"{ver}{at_lib}": lang.capitalize() +
("" if single_version else f"{at_lib} {ver}")
for ver in versions
})
if cutoff := {
"10k": 10_000,
"1M": 500_000,
}.get(orderstr):
idx = bisect_left(sizes1, cutoff)
sizes1 = sizes1[idx:]
measurements1 = {n: m[idx:] for n, m in measurements1.items()}
if sizes[:len(sizes1)] != sizes1[:len(sizes)]:
raise ImportError(f"{sizes} != {sizes1} for {lang} {orderstr}")
if len(sizes) < len(sizes1):
sizes = sizes1
measurements.update(measurements1)
publish_measurements(
basename=basename,
orderstr=orderstr,
sizes=sizes,
suffix="" if single_version is None else f" {single_version}",
measurement_per_size_by_case_name=measurements,
color_by_case=color_by_language,
dash_by_case=dash_by_case)
def publish_version_report(basebasename: str, orderstr: str, langlib: str,
versions: Sequence[str]) -> None:
sep = (langlib + '@').index('@')
lang, at_lib = langlib[:sep], langlib[sep:]
sizes, measurements = read_csv(
language=lang,
orderstr=orderstr,
case_name_selector={f"{ver}{at_lib}": f"{ver}"
for ver in versions})
publish_measurements(basename=basebasename +
f"_{clean_language(lang)}_{orderstr}",
language=lang,
orderstr=orderstr,
sizes=sizes,
measurement_per_size_by_case_name=measurements)
def publish_library_report(basename: str, orderstr: str, language: str,
ver: str, libs: Sequence[str]) -> None:
sizes, measurements = read_csv(
language=language,
orderstr=orderstr,
case_name_selector={f"{ver}@{lib}": f"{lib}"
for lib in libs})
publish_measurements(basename=basename,
language=language,
orderstr=orderstr,
sizes=sizes,
suffix=" " + ver,
measurement_per_size_by_case_name=measurements)
def publish_langver_report(basename: str, orderstr: str, ver: str,
language: str, languages: Mapping[str,
str]) -> None:
sizes: List[int] = []
measurements: Dict[str, List[Measurement]] = {}
for lang, label in languages.items():
sizes1, measurements1 = read_csv(
language=lang,
orderstr=orderstr,
case_name_selector={f"{ver}": f"{label}"},
)
assert not sizes or sizes1 == sizes
sizes = sizes1
measurements.update(measurements1)
publish_measurements(basename=basename,
language=language,
orderstr=orderstr,
sizes=sizes,
suffix=" " + ver,
measurement_per_size_by_case_name=measurements)
def publish_reports() -> None:
# 1. Ver1 vs. Ver1½
publish_report(basename="report_1",
orderstr="100",
langlibs=["python311", "rust@Hash"],
versions=["Ver1", "Ver1½"],
dash_by_case=lambda name: "solid"
if name.endswith("½") else "dotted")
# 2. Ver1 vs. Ver2
publish_report(basename="report_2",
orderstr="100",
langlibs=["java", "scala", "rust@Hash"],
versions=["Ver1½", "Ver2½"],
dash_by_case=lambda name: "solid"
if name.endswith("2½") else "dotted")
# 3. Ver2 variants
for orderstr in ["100", "10k"]:
for langlib in ["rust@Hash", "java"]:
publish_version_report(
basebasename="report_3",
orderstr=orderstr,
langlib=langlib,
versions=["Ver2½", "Ver2½-RP", "Ver2½-GP", "Ver2½-GPX"])
# 4. Ver2 vs. Ver3
for orderstr in ["10k", "1M"]:
for langlib in ["python311", "c#@HashSet"]:
publish_version_report(basebasename="report_4",
orderstr=orderstr,
langlib=langlib,
versions=["Ver2½-GP", "Ver3½-GP"])
for orderstr in ["10k"]:
for langlib in ["rust@Hash", "java"]:
publish_version_report(basebasename="report_4",
orderstr=orderstr,
langlib=langlib,
versions=["Ver2½-GP", "Ver3½-GP"])
# 5. Ver3 variants
for orderstr in ["10k", "1M"]:
for langlib in ["python311", "c#@HashSet"]:
publish_version_report(basebasename="report_5",
orderstr=orderstr,
langlib=langlib,
versions=["Ver3½-GP", "Ver3½-GPX"])
for orderstr in ["10k"]:
for langlib in ["rust@Hash", "java"]:
publish_version_report(basebasename="report_5",
orderstr=orderstr,
langlib=langlib,
versions=["Ver3½-GP", "Ver3½-GPX"])
# 6. Parallelism
for orderstr in ["100", "10k", "1M"]:
publish_version_report(basebasename="report_6",
orderstr=orderstr,
langlib="java",
versions=["Ver3½-GP", "Ver3½=GPs", "Ver3½=GPc"])
publish_version_report(basebasename="report_6",
orderstr=orderstr,
langlib="go",
versions=[
"Ver3½-GP", "Ver3½=GP0", "Ver3½=GP1",
"Ver3½=GP2", "Ver3½=GP3", "Ver3½=GP4"
])
# 7. Languages
for orderstr in ["100", "10k", "1M"]:
publish_report(basename=f"report_7_sequential_{orderstr}",
orderstr=orderstr,
langlibs=[
"python311", "scala", "java", "go", "c#@HashSet",
"c++@hashset", "rust@Hash"
],
versions=["Ver3½-GP"],
single_version="Ver3½-GP")
publish_report(
basename=f"report_7_channels_{orderstr}",
orderstr=orderstr,
langlibs=["java", "go", "c#@HashSet", "c++@hashset", "rust@Hash"],
versions=["Ver3½=GPc", "Ver3½=GP3"],
single_version="parallel Ver3½=GP using channels")
publish_report(basename=f"report_7_parallel_{orderstr}",
orderstr=orderstr,
langlibs=["java", "scala"],
versions=["Ver3½=GPs"],
single_version="simple parallel Ver3½=GP")
# 8. Libraries
for orderstr in ["100", "10k", "1M"]:
publish_library_report(
basename=f"report_8_rust_{orderstr}",
orderstr=orderstr,
language="rust",
ver="Ver3½-GP",
libs=["BTree", "Hash", "hashbrown", "fnv", "ord_vec"],
)
for orderstr in ["100", "10k"]:
publish_library_report(
basename=f"report_8_csharp_{orderstr}",
orderstr=orderstr,
language="c#",
ver="Ver3½-GP",
libs=["HashSet", "SortedSet"],
)
publish_library_report(basename=f"report_8_c++_{orderstr}",
orderstr=orderstr,
language="c++",
ver="Ver3½-GP",
libs=["hashset", "std_set", "ord_vec"])
# 9. Language versions
for orderstr in ["100", "10k", "1M"]:
publish_langver_report(
basename=f"report_9_python_{orderstr}",
orderstr=orderstr,
language="Python",
languages={
"python3": "Python 3.10",
"python311": "Python 3.11"
},
ver="Ver3½-GP",
)
if __name__ == '__main__':
if len(sys.argv) == 1:
publish_reports()
else:
for orderstr in sys.argv[2:]:
publish_whole_csv(language=sys.argv[1], orderstr=orderstr)
<file_sep>using BronKerbosch;
using BronKerboschStudy;
using System.Collections.Immutable;
using System.Diagnostics;
using static System.Globalization.CultureInfo;
static SampleStatistics[] BronKerboschTimed<VertexSet, VertexSetMgr>(
string orderstr,
int size,
int[] funcIndices,
int timed_samples)
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
var sw = Stopwatch.StartNew();
var graph = RandomUndirectedGraph<VertexSet, VertexSetMgr>.Read(orderstr, size);
sw.Stop();
var secs = sw.ElapsedMilliseconds / 1e3;
Console.WriteLine($"{VertexSetMgr.Name()}-based random graph of order {orderstr},"
+ $" {size} edges, {graph.CliqueCount} cliques: (generating took {secs:.3}s)");
SampleStatistics[] times = Enumerable
.Range(0, Portfolio.FuncNames.Length)
.Select(funcIndex => new SampleStatistics()).ToArray();
List<ImmutableArray<Vertex>>? firstResult = null;
for (var sample = 0; sample <= timed_samples; ++sample)
{
foreach (var funcIndex in funcIndices)
{
if (sample == 0)
{
CollectingReporter reporter = new();
sw.Restart();
Portfolio.Explore(funcIndex, graph.Graph, reporter);
sw.Stop();
secs = sw.ElapsedMilliseconds / 1e3;
if (timed_samples == 0 || secs >= 3.0)
Console.WriteLine($" {Portfolio.FuncNames[funcIndex],10} {secs,6:N2}s");
Portfolio.SortCliques(reporter.Cliques);
if (firstResult == null)
{
if (reporter.Cliques.Count != graph.CliqueCount)
{
throw new InvalidProgramException(
$"Expected {graph.CliqueCount} cliques, got {reporter.Cliques.Count}");
}
firstResult = reporter.Cliques;
}
else
{
Portfolio.AssertSameCliques(firstResult, reporter.Cliques);
}
}
else
{
CountingReporter reporter = new();
sw.Restart();
Portfolio.Explore(funcIndex, graph.Graph, reporter);
sw.Stop();
secs = sw.ElapsedMilliseconds / 1e3;
times[funcIndex].Put(secs);
}
}
}
foreach (var funcIndex in funcIndices)
{
var funcName = Portfolio.FuncNames[funcIndex];
var mean = times[funcIndex].Mean;
var reldev = times[funcIndex].Deviation / mean;
Console.WriteLine($" {funcName,-10} {mean,6:N3}s ± {reldev:P0}");
}
return times;
}
SampleStatistics[] Bk_core
(SetType setType, string orderstr, int size, int[] funcIndices, int timed_samples) => setType switch
{
SetType.HashSet => BronKerboschTimed<HashSet<Vertex>, HashSetMgr>(orderstr, size, funcIndices, timed_samples),
SetType.SortedSet => BronKerboschTimed<SortedSet<Vertex>, SortedSetMgr>(orderstr, size, funcIndices, timed_samples),
_ => throw new ArgumentOutOfRangeException(nameof(setType)),
};
string SetTypeName(SetType setType) => setType switch
{
SetType.HashSet => HashSetMgr.Name(),
SetType.SortedSet => SortedSetMgr.Name(),
_ => throw new ArgumentOutOfRangeException(nameof(setType)),
};
void Bk(
string orderstr,
IEnumerable<int> sizes, Func<SetType, int, IEnumerable<int>> includedFuncs,
int timed_samples)
{
const string tmpfname = "tmp.csv";
using (var fo = new StreamWriter(tmpfname,
new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write }))
{
var setTypesUsed = Array.Empty<SetType>();
foreach (var size in sizes)
{
var stats = new Dictionary<SetType, SampleStatistics[]>();
foreach (SetType setType in Enum.GetValues(typeof(SetType)))
{
var funcIndices = includedFuncs(setType, size).ToArray();
if (funcIndices.Length > 0)
{
stats.Add(setType, Bk_core(setType, orderstr, size, funcIndices, timed_samples));
}
}
if (setTypesUsed.Length == 0)
{
setTypesUsed = stats.Keys.ToArray();
if (setTypesUsed.Length == 0)
throw new ArgumentException("includedFuncs excludes all set types for smallest size");
fo.Write("Size");
foreach (SetType setType in setTypesUsed)
{
foreach (var func_name in Portfolio.FuncNames)
{
var name = $"{func_name}@{SetTypeName(setType)}";
fo.Write($",{name} min,{name} mean,{name} max");
}
}
fo.WriteLine();
}
fo.Write($"{size}");
foreach (SetType setType in setTypesUsed)
{
var times = stats.GetValueOrDefault(setType, new SampleStatistics[Portfolio.FuncNames.Length]);
foreach ((var funcIndex, var funcName) in Portfolio.FuncNames.Select((n, i) => (i, n)))
{
var max = times[funcIndex].Max;
var min = times[funcIndex].Min;
var mean = times[funcIndex].Mean;
if (double.IsNaN(mean))
fo.Write(",,,");
else
fo.Write(string.Format(InvariantCulture, ",{0},{1},{2}", min, mean, max));
}
}
fo.WriteLine();
}
}
var path = $"..\\bron_kerbosch_csharp_order_{orderstr}.csv";
if (File.Exists(path))
File.Delete(path);
File.Move(tmpfname, path);
}
IEnumerable<int> Range(int start, int stop, int step)
{
var current = start;
while (current < stop)
{
yield return current;
current += step;
}
}
Debug.Fail("Run Release build for meaningful measurements");
#pragma warning disable CA1861 // Avoid constant arrays as arguments
var allFuncIndices = Enumerable.Range(0, Portfolio.FuncNames.Length);
var mostFuncIndices = Enumerable.Range(1, Portfolio.FuncNames.Length - 1);
Bk("100", Range(2_000, 3_001, 50), (_, size) => allFuncIndices, 5); // max 4_950
Bk("10k", Range(10_000, 100_000, 10_000).Concat(Range(100_000, 200_001, 25_000)),
(_, size) => mostFuncIndices, 3);
Bk("1M", Range(500_000, 2_000_000, 250_000)
.Concat(Range(2_000_000, 5_000_001, 1_000_000)),
(setType, size) => setType switch
{
SetType.HashSet => size > 2_000_000 ? new[] { 4, 5, 6 } : mostFuncIndices,
SetType.SortedSet => Array.Empty<int>(),
_ => throw new ArgumentOutOfRangeException(nameof(setType)),
}, 3);
internal enum SetType
{
HashSet,
SortedSet
};
<file_sep>package StudyIO
import (
"BronKerboschStudy/Assert"
"testing"
)
func Test1(t *testing.T) {
i, err := ParsePositiveInt("1")
Assert.AreEqual(i, 1)
Assert.AreEqual(err, nil)
}
func Test2k(t *testing.T) {
i, err := ParsePositiveInt("2k")
Assert.AreEqual(i, 2_000)
Assert.AreEqual(err, nil)
}
func Test2K(t *testing.T) {
_, err := ParsePositiveInt("2K")
Assert.AreNotEqual(err, nil)
}
func Test2_k(t *testing.T) {
_, err := ParsePositiveInt("2 k")
Assert.AreNotEqual(err, nil)
}
<file_sep>#include "pch.h"
#include "BronKerboschStudy/SampleStatistics.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace BronKerboschStudy {
TEST_CLASS(BronKerboschStudyUnitTest) {
public:
TEST_METHOD(stats_0_int) {
auto s = SampleStatistics<int>{};
Assert::IsTrue(std::isnan(s.mean()));
Assert::IsTrue(std::isnan(s.variance()));
Assert::IsTrue(std::isnan(s.deviation()));
}
TEST_METHOD(stats_1_int) {
auto s = SampleStatistics<int>{};
s.put(-1);
Assert::AreEqual(s.mean(), -1.0);
Assert::IsTrue(std::isnan(s.variance()));
Assert::IsTrue(std::isnan(s.deviation()));
}
TEST_METHOD(stats_2_int) {
auto s = SampleStatistics<int>{};
s.put(-1);
s.put(1);
Assert::AreEqual(s.mean(), 0.0);
Assert::AreEqual(s.variance(), 2.0);
Assert::AreEqual(s.deviation(), std::sqrt(2.0));
}
TEST_METHOD(stats_3_int) {
auto s = SampleStatistics<int>{};
s.put(89);
s.put(90);
s.put(91);
Assert::AreEqual(s.mean(), 90.0);
Assert::AreEqual(s.variance(), 1.0);
Assert::AreEqual(s.deviation(), 1.0);
}
TEST_METHOD(stats_9_int) {
auto s = SampleStatistics<int>{};
s.put(2);
s.put(4);
s.put(4);
s.put(4);
s.put(5);
s.put(5);
s.put(5);
s.put(7);
s.put(9);
Assert::AreEqual(s.mean(), 5.0);
Assert::AreEqual(s.variance(), 4.0);
Assert::AreEqual(s.deviation(), 2.0);
}
TEST_METHOD(stats_2_double) {
auto s = SampleStatistics<double>{};
s.put(1.0);
s.put(2.0);
Assert::AreEqual(s.mean(), 1.5);
Assert::AreEqual(s.variance(), 0.5);
Assert::AreEqual(s.deviation(), std::sqrt(0.5));
}
/*
proptest!{
#[test]
fn put_1_u32(x in proptest::num::u32::ANY) {
let mut s : SampleStatistics<u32> = Default::default();
s.put(x);
Assert::IsTrue(s.mean() >= f64::from(s.min()));
Assert::IsTrue(s.mean() <= f64::from(s.max()));
}
#[test]
fn put_1_f64(x in proptest::num::f64::NORMAL) {
let mut s : SampleStatistics<f64> = Default::default();
s.put(x);
Assert::IsTrue(s.mean() >= s.min());
Assert::IsTrue(s.mean() <= s.max());
}
#[test]
fn put_2_u32(x in proptest::num::u32::ANY, y in proptest::num::u32::ANY) {
let mut s : SampleStatistics<u32> = Default::default();
s.put(x);
s.put(y);
Assert::IsTrue(s.mean() >= f64::from(s.min()));
Assert::IsTrue(s.mean() <= f64::from(s.max()));
Assert::IsTrue(s.variance() >= 0.);
Assert::IsTrue(s.deviation() <= f64::from(s.max() - s.min()));
}
#[test]
fn put_2_f64(x in proptest::num::f64::NORMAL, y in proptest::num::f64::NORMAL) {
let mut s : SampleStatistics<f64> = Default::default();
s.put(x);
s.put(y);
Assert::IsTrue(s.mean() >= s.min());
Assert::IsTrue(s.mean() <= s.max());
Assert::IsTrue(s.variance() >= 0.);
Assert::IsTrue(s.deviation() <= (s.max() - s.min()) * 1.5);
}
#[test]
fn put_n_u32(i in 2..99, x in proptest::num::u32::ANY) {
let mut s : SampleStatistics<u32> = Default::default();
for _ in 0..i {
s.put(x);
}
Assert::IsTrue(s.mean() >= f64::from(s.min()));
Assert::IsTrue(s.mean() <= f64::from(s.max()));
Assert::IsTrue(s.variance() >= 0.);
Assert::IsTrue(s.deviation() <= f64::from(s.max() - s.min()));
}
#[test]
fn put_n_f64(i in 2..99, x in proptest::num::f64::NORMAL) {
let mut s : SampleStatistics<f64> = Default::default();
for _ in 0..i {
s.put(x);
}
Assert::IsTrue(s.mean() >= s.min());
Assert::IsTrue(s.mean() <= s.max());
Assert::IsTrue(s.variance() >= 0.);
Assert::IsTrue(s.deviation() <= (s.max() - s.min()));
}
}
*/
};
}
<file_sep>// Bron-Kerbosch algorithm with pivot of highest degree (IK_GP)
using BronKerbosch;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
internal static class BronKerbosch2aGP<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
public static void Explore(UndirectedGraph<VertexSet, VertexSetMgr> graph, IReporter reporter)
{
var candidates = VertexSetMgr.From(graph.ConnectedVertices());
if (candidates.Any())
{
Pivot<VertexSet, VertexSetMgr>.Visit(
graph,
reporter,
PivotChoice.MaxDegreeLocal,
candidates,
VertexSetMgr.Empty(),
ImmutableArray.Create<Vertex>());
}
}
}
<file_sep>[package]
name = "compare_bron_kerbosch_on_random_graphs"
version = "1.0.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2021"
[profile.release]
debug = true
[workspace]
[dependencies]
bron_kerbosch = { path="bron_kerbosch" }
stats = { path="stats" }
anyhow = "1.0.12"
clap = {version = "4.0.0", features = ["cargo"]}
csv = "1.0.0"
fnv = "1.0.5"
hashbrown = "0.13.0"
itertools = "0.10.0"
strum = "0.24.0"
strum_macros = "0.24.0"
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace BronKerbosch
{
internal static class Degeneracy<VertexSet, VertexSetMgr>
where VertexSet : IEnumerable<Vertex>
where VertexSetMgr : IVertexSetMgr<VertexSet>
{
// Iterate connected vertices, lowest degree first.
// drop=N: omit last N vertices
public static IEnumerable<Vertex> Ordering(UndirectedGraph<VertexSet, VertexSetMgr> graph, int drop)
{
Debug.Assert(drop >= 0);
const int NO_PRIORITY = -1;
int[] priorityPerVertex = new int[graph.Order];
var maxPriority = 0;
var numLeftToPick = 0;
foreach (int i in Enumerable.Range(0, graph.Order))
{
var c = Vertex.Nth(i);
var degree = graph.Degree(c);
if (degree > 0)
{
var priority = degree;
maxPriority = Math.Max(maxPriority, priority);
priorityPerVertex[i] = degree;
numLeftToPick += 1;
}
}
// Possible values of priority_per_vertex:
// no_priority: when yielded or if unconnected
// 0..maxPriority: candidates still queued with priority (degree - #of yielded neighbours)
var q = new PriorityQueue(maxPriority);
foreach (var (c, p) in priorityPerVertex.Select((p, i) => (Vertex.Nth(i), p)))
{
if (p > 0)
{
q.Put(priority: p, element: c);
}
}
numLeftToPick -= drop;
while (numLeftToPick >= 0)
{
numLeftToPick -= 1;
var i = q.Pop();
while (priorityPerVertex[i.Index()] == NO_PRIORITY)
{
// was requeued with a more urgent priority and therefore already picked
i = q.Pop();
}
Debug.Assert(priorityPerVertex[i.Index()] >= 0);
priorityPerVertex[i.Index()] = NO_PRIORITY;
yield return i;
foreach (var v in graph.Neighbours(i))
{
var oldPriority = priorityPerVertex[v.Index()];
if (oldPriority != NO_PRIORITY)
{
// Since this is an unvisited neighbour of a vertex just being picked,
// its priority can't be down to the minimum.
Debug.Assert(oldPriority > 0);
// Requeue with a more urgent priority, but don't bother to remove
// the original entry - it will be skipped if it's reached at all.
priorityPerVertex[v.Index()] = oldPriority - 1;
q.Put(priority: oldPriority - 1, element: v);
}
}
}
}
}
internal sealed class PriorityQueue(int maxPriority)
{
private readonly List<Vertex>[] itsQueuePerPriority = new List<Vertex>[maxPriority + 1];
public void Put(int priority, Vertex element)
{
Debug.Assert(priority >= 0);
itsQueuePerPriority[priority] ??= new List<Vertex>();
itsQueuePerPriority[priority].Add(element);
}
public Vertex Pop()
{
foreach (var queue in itsQueuePerPriority)
{
if (queue != null)
{
var last = queue.Count - 1;
if (last >= 0)
{
var v = queue[last];
queue.RemoveAt(last);
return v;
}
}
}
throw new ArgumentException("Cannot pop more than has been put");
}
}
}
<file_sep>#pragma once
#include "BronKerbosch/pch.h"
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
#include <set>
#include <unordered_set><file_sep># coding: utf-8
from bron_kerbosch_pivot import visit
from graph import UndirectedGraph
from reporter import Reporter
def explore(graph: UndirectedGraph, reporter: Reporter) -> None:
"""Bron-Kerbosch algorithm with pivot of highest degree within remaining candidates
chosen from candidates only (IK_GP)"""
if candidates := graph.connected_vertices():
visit(graph=graph,
reporter=reporter,
pivot_choice_X=False,
candidates=candidates,
excluded=set(),
clique=[])
<file_sep>#include "pch.h"
#include "RandomGraph.h"
unsigned BronKerboschStudy::parseInt(std::string const& str) {
unsigned factor = 1;
if (*str.rbegin() == 'M')
factor = 1'000'000;
if (*str.rbegin() == 'k')
factor = 1'000;
auto i = std::stoi(str);
if (i < 0) {
std::cerr << str << " is negative\n";
std::exit(EXIT_FAILURE);
}
return unsigned(i) * factor;
}
<file_sep>//! Bron-Kerbosch algorithm with degeneracy ordering, with nested searches
//! choosing a pivot arbitrarily
#pragma once
#include "BronKerboschPivot.h"
#include "GraphDegeneracy.h"
#pragma warning(push)
#pragma warning(disable : 4189 4265 4623 5204 26495)
#include "cppcoro/async_generator.hpp"
#include "cppcoro/multi_producer_sequencer.hpp"
#include "cppcoro/sequence_barrier.hpp"
#include "cppcoro/single_producer_sequencer.hpp"
#include "cppcoro/static_thread_pool.hpp"
#include "cppcoro/sync_wait.hpp"
#include "cppcoro/task.hpp"
#include "cppcoro/when_all.hpp"
#pragma warning(pop)
namespace BronKerbosch {
template <typename Reporter, typename VertexSet>
class BronKerbosch3MT {
private:
static const size_t VISITORS = 8;
static const size_t STARTS = 8;
static const size_t CLIQUES = 8;
static const Vertex SENTINEL_VTX = std::numeric_limits<Vertex>::max();
class VisitJob {
Vertex start = SENTINEL_VTX;
VertexSet candidates;
VertexSet excluded;
#ifndef NDEBUG
std::atomic_bool busy; // being read from or written to by a thread
std::atomic_bool full; // having been written to
#endif
public:
VisitJob() noexcept = default;
VisitJob(VisitJob&&) = delete;
VisitJob(VisitJob const&) = delete;
VisitJob& operator=(VisitJob&&) = delete;
VisitJob& operator=(VisitJob const&) = delete;
// Store in this slot a visit to be done.
void schedule(Vertex new_start,
VertexSet&& new_candidates,
VertexSet&& new_excluded) noexcept {
assert(!busy.exchange(true));
assert(!full.load());
start = new_start;
candidates = std::move(new_candidates);
excluded = std::move(new_excluded);
assert(!full.exchange(true));
assert(busy.exchange(false));
}
// Store in this slot a marker that no more visits are needed.
void close() noexcept {
assert(!busy.exchange(true));
assert(!full.load());
start = SENTINEL_VTX;
assert(!full.exchange(true));
assert(busy.exchange(false));
}
// Execute the visit stored in this slot, if any.
std::optional<typename Reporter::Result> visit(UndirectedGraph<VertexSet> const& graph,
PivotChoice pivot_choice) noexcept {
std::optional<Reporter::Result> result;
assert(!busy.exchange(true));
assert(full.load());
if (start != SENTINEL_VTX) {
auto pile = VertexPile{start};
result = BronKerboschPivot::visit<Reporter, VertexSet>(
graph, pivot_choice, pivot_choice, std::move(candidates),
std::move(excluded), &pile);
}
assert(full.exchange(false));
assert(busy.exchange(false));
return result;
}
};
static cppcoro::task<> start_producer(
UndirectedGraph<VertexSet> const& graph,
cppcoro::single_producer_sequencer<size_t>& start_sequencer,
Vertex (*starts)[STARTS], // pass-by-reference avoiding ICE
cppcoro::static_thread_pool& tp) {
auto ordering = DegeneracyOrderIter<VertexSet>::degeneracy_ordering(graph, -1);
while (auto next = ordering.next()) {
size_t seq = co_await start_sequencer.claim_one(tp);
(*starts)[seq % STARTS] = *next;
start_sequencer.publish(seq);
}
size_t seq = co_await start_sequencer.claim_one(tp);
(*starts)[seq % STARTS] = SENTINEL_VTX;
start_sequencer.publish(seq);
}
static cppcoro::task<> visit_producer(
UndirectedGraph<VertexSet> const& graph,
cppcoro::sequence_barrier<size_t>& start_barrier,
cppcoro::single_producer_sequencer<size_t> const& start_sequencer,
std::unique_ptr<cppcoro::single_producer_sequencer<size_t>> (
*visit_sequencers)[VISITORS], // pass-by-reference avoiding ICE
Vertex const (*starts)[STARTS], // pass-by-reference avoiding ICE
VisitJob (*visit_jobs)[VISITORS], // pass-by-reference avoiding ICE
cppcoro::static_thread_pool& tp) {
auto excluded = Util::with_capacity<VertexSet>(std::max(1u, graph.order()) - 1);
size_t visitor = 0;
bool producer = true;
size_t nextToRead = 0;
while (producer) {
size_t const available =
co_await start_sequencer.wait_until_published(nextToRead, tp);
assert(nextToRead <= available);
for (; nextToRead <= available; ++nextToRead) {
Vertex start = (*starts)[nextToRead % STARTS];
if (start == SENTINEL_VTX) {
assert(producer);
producer = false;
assert(nextToRead == available);
} else {
auto const& neighbours = graph.neighbours(start);
assert(!neighbours.empty());
auto neighbouring_excluded = Util::intersection(neighbours, excluded);
if (neighbouring_excluded.size() < neighbours.size()) {
auto neighbouring_candidates =
Util::difference(neighbours, neighbouring_excluded);
auto visit_sequencer = (*visit_sequencers)[visitor].get();
size_t seq = co_await visit_sequencer->claim_one(tp);
(*visit_jobs)[visitor].schedule(start,
std::move(neighbouring_candidates),
std::move(neighbouring_excluded));
visit_sequencer->publish(seq);
visitor = ++visitor < VISITORS ? visitor : 0;
}
excluded.insert(start);
}
}
start_barrier.publish(available);
}
for (visitor = 0; visitor < VISITORS; ++visitor) {
auto visit_sequencer = (*visit_sequencers)[visitor].get();
size_t seq = co_await visit_sequencer->claim_one(tp);
(*visit_jobs)[visitor].close();
visit_sequencer->publish(seq);
}
}
static cppcoro::task<> clique_producer(
UndirectedGraph<VertexSet> const& graph,
cppcoro::sequence_barrier<size_t>& visit_barrier,
cppcoro::single_producer_sequencer<size_t> const& visit_sequencer,
cppcoro::multi_producer_sequencer<size_t>& clique_sequencer,
VisitJob& visit_job,
std::optional<typename Reporter::Result> (
*clique_produce)[CLIQUES], // pass-by-reference avoiding ICE
cppcoro::static_thread_pool& tp) {
bool producer = true;
size_t nextToRead = 0;
while (producer) {
size_t const available =
co_await visit_sequencer.wait_until_published(nextToRead, tp);
assert(nextToRead <= available);
for (; nextToRead <= available; ++nextToRead) {
auto cliques = visit_job.visit(graph, PivotChoice::MaxDegreeLocal);
if (cliques) {
size_t seq = co_await clique_sequencer.claim_one(tp);
(*clique_produce)[seq % CLIQUES].emplace(*std::move(cliques));
clique_sequencer.publish(seq);
} else {
assert(producer);
producer = false;
assert(nextToRead == available);
}
}
visit_barrier.publish(available);
}
size_t seq = co_await clique_sequencer.claim_one(tp);
(*clique_produce)[seq % CLIQUES].reset();
clique_sequencer.publish(seq);
}
static cppcoro::task<> clique_consumer(
cppcoro::sequence_barrier<size_t>& clique_barrier,
cppcoro::multi_producer_sequencer<size_t> const& clique_sequencer,
std::optional<typename Reporter::Result> (
*clique_produce)[CLIQUES], // pass-by-reference avoiding ICE
size_t producers,
Reporter::Result& all_cliques,
cppcoro::static_thread_pool& tp) noexcept {
size_t nextToRead = 0;
while (producers) {
size_t const available =
co_await clique_sequencer.wait_until_published(nextToRead, nextToRead - 1, tp);
assert(nextToRead <= available);
for (; nextToRead <= available; ++nextToRead) {
auto next_publication = (*clique_produce)[nextToRead % CLIQUES];
if (next_publication.has_value()) {
Reporter::add_all(all_cliques, std::move(next_publication).value());
} else {
--producers;
}
}
clique_barrier.publish(available);
}
}
public:
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph) {
auto tp = cppcoro::static_thread_pool{6};
auto start_barrier = cppcoro::sequence_barrier<size_t>{};
auto start_sequencer =
cppcoro::single_producer_sequencer<size_t>{start_barrier, STARTS};
Vertex starts[STARTS];
cppcoro::sequence_barrier<size_t> visit_barriers[VISITORS];
std::unique_ptr<cppcoro::single_producer_sequencer<size_t>> visit_sequencers[VISITORS];
for (auto i = 0; i < VISITORS; ++i) {
visit_sequencers[i] = std::make_unique<cppcoro::single_producer_sequencer<size_t>>(
visit_barriers[i], 1);
}
VisitJob visit_jobs[VISITORS] = {};
auto clique_barrier = cppcoro::sequence_barrier<size_t>{};
auto clique_sequencer =
cppcoro::multi_producer_sequencer<size_t>{clique_barrier, CLIQUES};
std::optional<Reporter::Result> cliques[CLIQUES];
auto tasks = std::vector<cppcoro::task<void>>{};
tasks.reserve(2 + VISITORS + 1);
tasks.push_back(BronKerbosch3MT::start_producer(graph, start_sequencer, &starts, tp));
tasks.push_back(BronKerbosch3MT::visit_producer(graph, start_barrier, start_sequencer,
&visit_sequencers, &starts, &visit_jobs,
tp));
for (auto i = 0; i < VISITORS; ++i) {
tasks.push_back(BronKerbosch3MT::clique_producer(
graph, visit_barriers[i], *visit_sequencers[i], clique_sequencer, visit_jobs[i],
&cliques, tp));
}
auto all_cliques = Reporter::empty();
tasks.push_back(BronKerbosch3MT::clique_consumer(clique_barrier, clique_sequencer,
&cliques, VISITORS, all_cliques, tp));
cppcoro::sync_wait(cppcoro::when_all_ready(std::move(tasks)));
return all_cliques;
}
};
}<file_sep>[package]
name = "bron_kerbosch"
version = "1.0.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2021"
[dependencies]
crossbeam = "0.8.0"
crossbeam-channel = "0.5.0"
fnv = "1.0.5"
hashbrown = "0.13.0"
rand = "0.8.0"
[dev-dependencies]
proptest = "1.0.0"
rand_chacha = "0.3.0"
<file_sep>using System;
#pragma warning disable CA1036 // should define operator(s) '<, <=, >, >=' since it implements IComparable
namespace BronKerbosch
{
using Index = Int32;
public readonly record struct Vertex : IComparable<Vertex>
{
private Index Idx { init; get; }
public static Vertex Nth(Index idx) => new() { Idx = idx };
public int CompareTo(Vertex other) => Idx.CompareTo(other.Idx);
public Index Index() => Idx;
}
}
<file_sep>//! Naive Bron-Kerbosch algorithm, optimized
use super::graph::{connected_vertices, UndirectedGraph, Vertex, VertexSetLike};
use super::pile::Pile;
use super::reporter::Reporter;
type Clique<'a> = Pile<'a, Vertex>;
pub fn explore<VertexSet, Graph, Rprtr>(graph: &Graph, reporter: &mut Rprtr)
where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
let candidates = connected_vertices(graph);
let num_candidates = candidates.len();
if num_candidates > 0 {
visit(
graph,
reporter,
candidates,
VertexSet::with_capacity(num_candidates),
None,
);
}
}
fn visit<VertexSet, Graph, Rprtr>(
graph: &Graph,
reporter: &mut Rprtr,
mut candidates: VertexSet,
mut excluded: VertexSet,
clique: Option<&Clique>,
) where
VertexSet: VertexSetLike,
Graph: UndirectedGraph<VertexSet = VertexSet>,
Rprtr: Reporter,
{
debug_assert!(candidates.all(|&v| graph.degree(v) > 0));
debug_assert!(excluded.all(|&v| graph.degree(v) > 0));
debug_assert!(candidates.is_disjoint(&excluded));
debug_assert!(!candidates.is_empty());
while let Some(v) = candidates.pop_arbitrary() {
let neighbours = graph.neighbours(v);
let neighbouring_candidates: VertexSet = candidates.intersection_collect(neighbours);
if !neighbouring_candidates.is_empty() {
visit(
graph,
reporter,
neighbouring_candidates,
excluded.intersection_collect(neighbours),
Some(&Pile::on(clique, v)),
);
} else if excluded.is_disjoint(neighbours) {
reporter.record(Pile::on(clique, v).collect());
}
excluded.insert(v);
}
}
<file_sep>package be.steinsomers.bron_kerbosch;
import java.util.stream.Stream;
public final class BronKerbosch3 implements BronKerboschAlgorithm {
@Override
public Stream<int[]> explore(UndirectedGraph graph) {
return BronKerboschOrder.explore(graph, PivotChoice.Arbitrary);
}
}
<file_sep>//! Bron-Kerbosch algorithm with degeneracy ordering,
//! parametrized by the way nested searches choose a pivot.
#pragma once
#include "BronKerboschPivot.h"
#include "CliqueList.h"
#include "GraphDegeneracy.h"
#include "UndirectedGraph.h"
#include "Util.h"
namespace BronKerbosch {
class BronKerboschDegeneracy {
public:
template <typename Reporter, typename VertexSet>
static Reporter::Result explore(UndirectedGraph<VertexSet> const& graph,
PivotChoice pivot_choice) {
auto cliques = Reporter::empty();
// In this initial iteration, we don't need to represent the set of candidates
// because all neighbours are candidates until excluded.
auto excluded = Util::with_capacity<VertexSet>(std::max(1u, graph.order()) - 1);
auto ordering = DegeneracyOrderIter<VertexSet>::degeneracy_ordering(graph, -1);
while (auto next = ordering.next()) {
Vertex v = *next;
auto const& neighbours = graph.neighbours(v);
assert(!neighbours.empty());
auto neighbouring_excluded = Util::intersection(neighbours, excluded);
if (neighbouring_excluded.size() < neighbours.size()) {
auto neighbouring_candidates =
Util::difference(neighbours, neighbouring_excluded);
auto pile = VertexPile{v};
Reporter::add_all(cliques, BronKerboschPivot::visit<Reporter>(
graph, pivot_choice, pivot_choice,
std::move(neighbouring_candidates),
std::move(neighbouring_excluded), &pile));
}
excluded.insert(v);
}
return cliques;
}
};
}
|
fd42ba7ea13dd68e65a13dd359c0ea0d684a0c87
|
[
"TOML",
"Markdown",
"INI",
"C#",
"Rust",
"Python",
"Java",
"Go Module",
"C",
"Go",
"C++"
] | 137
|
Rust
|
ssomers/Bron-Kerbosch
|
c8b30c34944013fb0869dfa9333d3bc4ae52e33f
|
f8ec904ca67b2b657121a4dda34a7859763dd7fd
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""DrTrigonBot subster simulation panel (CGI) for toolserver
(for mor info look at 'panel.py' also!)
"""
## @package substersim.py
# @brief DrTrigonBot subster simulation panel (CGI) for toolserver
#
# @copyright <NAME>, 2008-2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# debug
import cgitb
cgitb.enable()
import cgi
## import any path or dir (not only subdirs of current script)
## http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
## http://docs.python.org/library/imp.html
## http://www.faqs.org/docs/diveintopython/dialect_locals.html
## http://www.koders.com/python/fidEAB56F6AFEF3116A6B06ACE7BFA65AB902D31866.aspx?s=md5
#def importglobal(name, path):
# if (type(name) == type("")): name = [name]
# for item in name:
# fp, pathname, description = imp.find_module(item, [path])
# try:
# globals()[item] = imp.load_module(item, fp, pathname, description)
# finally:
# # Since we may exit via an exception, close fp explicitly.
# if fp: fp.close()
# return
from time import *
# http://www.ibm.com/developerworks/aix/library/au-python/
import os, sys, re
import StringIO, traceback, signal
# === panel HTML stylesheets === === ===
# MAY BE USING Cheetah (http://www.cheetahtemplate.org/) WOULD BE BETTER (or needed at any point...)
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
bot_path = os.path.realpath(style.bot_path[style.host(os.environ)][0])
# === pywikibot framework === === ===
#
#importglobal("subster_beta", bot_path)
#importglobal(["wikipedia", "xmlreader", "config", "dtbext", "subster_beta"], bot_path)
# http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
sys.path.append( bot_path ) # bot import form other path (!)
import subster #
import config #
import wikipedia as pywikibot
# === page HTML contents === === ===
#
maindisplay_content = \
"""<small>(analog to <a href="http://meta.wikimedia.org/wiki/Special:ExpandTemplates">Special:ExpandTemplates</a>)</small><br><br>
Version:<br>
panel: %(panel_ver)s<br>
bot: %(subster_bot_ver)s<br><br>
Modus:
<form action="" name="ModusForm">
<script type="text/javascript">
function switch_mode () {
if (document.ModusForm.mode[0].checked == true) {
document.SubsterBotForm.regex.disabled = false;
document.SubsterBotForm.value.disabled = false;
document.SubsterBotForm.count.disabled = false;
document.SubsterBotForm.postproc.disabled = false;
document.SubsterBotForm.expandtemplates.disabled = false;
document.SubsterBotForm.beautifulsoup.disabled = true;
document.SubsterBotForm.simple.disabled = true;
} else if (document.ModusForm.mode[1].checked == true) {
document.SubsterBotForm.regex.disabled = true;
document.SubsterBotForm.value.disabled = false;
document.SubsterBotForm.count.disabled = true;
document.SubsterBotForm.postproc.disabled = true;
document.SubsterBotForm.expandtemplates.disabled = true;
document.SubsterBotForm.beautifulsoup.disabled = false;
document.SubsterBotForm.simple.disabled = true;
} else if (document.ModusForm.mode[2].checked == true) {
document.SubsterBotForm.regex.disabled = false;
document.SubsterBotForm.value.disabled = false;
document.SubsterBotForm.count.disabled = false;
document.SubsterBotForm.postproc.disabled = false;
document.SubsterBotForm.expandtemplates.disabled = false;
document.SubsterBotForm.beautifulsoup.disabled = false;
document.SubsterBotForm.simple.disabled = false;
}
}
switch_mode();
</script>
<p>
<input type="radio" name="mode" value="regex" onclick="switch_mode();"> regex<br>
<input type="radio" name="mode" value="beautifulsoup" onclick="switch_mode();"> beautifulsoup<br>
<input type="radio" name="mode" value="simple" onclick="switch_mode();"> simple
</p>
</form>
Simulation:
<form action="substersim.py" name="SubsterBotForm">
<input type="hidden" name="action" value="runsim">
<table>
<tr>
<td>url</td>
<td>=</td>
<td><input name="url" type="text" size="60" maxlength="200" value="%(url)s"></td>
</tr>
<tr>
<td>regex</td>
<td>=</td>
<td><input name="regex" type="text" size="60" maxlength="200" value="%(regex)s"></td>
</tr>
<tr>
<td>value</td>
<td>=</td>
<td><input name="value" type="text" size="60" maxlength="200" value="%(value)s"></td>
</tr>
<tr>
<td>count</td>
<td>=</td>
<td><input name="count" type="text" size="60" maxlength="200" value="%(count)s"></td>
</tr>
<tr>
<td>postproc</td>
<td>=</td>
<td><input name="postproc" type="text" size="60" maxlength="200" value="%(postproc)s"></td>
</tr>
<tr>
<td>expandtemplates</td>
<td>=</td>
<td><input name="expandtemplates" type="text" size="60" maxlength="200" value="%(expandtemplates)s"></td>
</tr>
<tr>
<td>beautifulsoup</td>
<td>=</td>
<td><input name="beautifulsoup" type="text" size="60" maxlength="200" value="%(beautifulsoup)s"></td>
</tr>
<tr>
<td>simple</td>
<td>=</td>
<td><input name="simple" type="text" size="60" maxlength="200" value="%(simple)s"></td>
</tr>
<tr>
<td>zip</td>
<td>=</td>
<td><input name="zip" type="text" size="60" maxlength="200" value="%(zip)s"></td>
</tr>
<tr>
<td>xlsx</td>
<td>=</td>
<td><input name="xlsx" type="text" size="60" maxlength="200" value="%(xlsx)s"></td>
</tr>
<tr>
<td>cron</td>
<td>=</td>
<td><input name="cron" type="text" size="60" maxlength="200" value="%(cron)s"></td>
</tr>
<tr>
<td>(add. params)</td>
<td>=</td>
<td><input name="add_params" type="text" size="60" maxlength="200" value="%(add_params)s"></td>
</tr>
</table>
<p>
content: <textarea name="content" cols="60" rows="10">%(content)s</textarea>
</p>
<input type="submit" value=" Simulate ">
<input type="reset" value=" Reset ">
<small><a href="substersim.py">new simulation</a></small>
</form><br><br>
Bot output:
<p style="border-color:#888888; border-width:1px; border-style:solid; padding:4px"><small>%(bot_output)s</small></p>
<br>"""
# === variables === === ===
#
sim_param_default = { 'value': 'val',
'action': '',
'content': '<!--SUBSTER-val--><!--SUBSTER-val-->',
'add_params': '{}', }
timeout = 60 # xx-sec. max. delay for url request
# === code === === ===
#
# from 'runbotrun.py'
def gettraceback(exc_info):
output = StringIO.StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=output)
##if not ('KeyboardInterrupt\n' in traceback.format_exception_only(exc_info[0], exc_info[1])):
## result = output.getvalue()
#if ('KeyboardInterrupt\n' in traceback.format_exception_only(exc_info[0], exc_info[1])):
# return None
result = output.getvalue()
output.close()
#exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
return (exc_info[0], exc_info[1], result)
# http://docs.python.org/library/signal.html
# http://code.activestate.com/recipes/307871/ (timeout function with signals)
# http://code.activestate.com/recipes/473878/ (timeout function using threading)
def timeout_handler(signum, frame):
print '\nTimeout: Signal handler called with signal', signum
#raise IOError("Couldn't open device!")
raise IOError("Couldn't open/get url, request timed out!")
def maindisplay():
param_default = subster.bot_config['param_default']
param_default.update(sim_param_default)
params = {}
for key in param_default.keys():
params[key] = form.getvalue(key, param_default[key])
# enhance with add. params
try: params.update( eval(params['add_params']) )
except: pass
bot_output = ["(no simulation runned yet...)"] # index 0 is bot_output, all other are errors
if (params['action'] == 'runsim'):
# redirect stdout and stderr
stdlog = StringIO.StringIO()
(out_stream, err_stream) = (sys.stdout, sys.stderr)
(sys.stdout, sys.stderr) = (stdlog, stdlog)
pywikibot.ui.stdout = sys.stdout # patch needed for pywikibot.output
pywikibot.ui.stderr = sys.stderr # (look at terminal_iterface_base.py and bot_control.py)
# Set the signal handler and a ?-second alarm (request max. timeout)
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout)
try:
params['content'] = subster.SubsterBot().run(sim=params)
except:
#params['content'] = "ERROR OCCURRED DURING BOT SIMULATION"
bot_output.append(gettraceback(sys.exc_info())[2])
# Cancel the signal handler alarm
signal.alarm(0)
# restore stdout and stderr
(sys.stdout, sys.stderr) = (out_stream, err_stream)
bot_output[0] = re.sub('\x03', '', stdlog.getvalue())
stdlog.close()
bot_output = re.sub("\n{1,2}", "<br>\n", "\n".join(bot_output))
data = {'panel_ver': __version__,
'subster_bot_ver': subster.__version__,
'bot_output': bot_output,
}
if type(params['content']) == type(u""):
params['content'] = params['content'].encode(config.textfile_encoding)
#params['content'] = params['content'].encode(config.textfile_encoding).decode("ISO-8859-1")
# proper output format and prevent XSS vulnerabilities
for key in params:
if (type(params[key]) == type('')) or (type(params[key]) == type(u'')):
params[key] = cgi.escape(params[key], quote=True)
data.update( params )
data.update({ 'refresh': '',
'title': 'DrTrigonBot subster simulation panel',
'tsnotice': style.print_tsnotice(),
#'content': displaystate_content,
'p-status': "<tr><td></td></tr>",
#'footer': style.footer + style.footer_w3c + style.footer_w3c_css,
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = maindisplay_content % data
return style.page % data
form = cgi.FieldStorage()
# operational mode
action = form.getvalue('action', '')
print style.change_logo(maindisplay(), os.environ) # labs patch
<file_sep>#!/usr/bin/env python
# http://www.alecjacobson.com/weblog/?p=1039
import subprocess, re, smtplib, email.mime.text, sys
alarm = 90.
quota = subprocess.Popen("quota -v", shell=True, stdout=subprocess.PIPE).stdout.readlines()
size = re.findall("[\d\.]+", quota[-1])
percent = float(size[0])/float(size[1]) * 100
# show resulting output with '-v' like quota
if '-v' in sys.argv:
print "".join(quota)
print "Actual user space usage: %.03f%%" % percent
# if the percentage is a above some threshold then send an email
if (percent > alarm):
# sender's and recipient's email addresses
FROM = "<EMAIL>"
TO = ["<EMAIL>"] # must be a list
# Create a text/plain message
msg = email.mime.text.MIMEText("".join(quota))
msg['Subject'] = "!QUOTA! %.1f%%" % percent
msg['From'] = FROM
msg['To'] = ", ".join(TO)
# Send the mail
server = smtplib.SMTP("localhost")
server.sendmail(FROM, TO, msg.as_string())
server.quit()
## update rrdtool
## http://oss.oetiker.ch/rrdtool/tut/rrdtutorial.en.html
## http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html
## rrdtool create quota.rrd --start 1350165600 --step 86400 DS:quota:GAUGE:172800:U:U RRA:AVERAGE:0.5:1:30 RRA:AVERAGE:0.5:7:10
#rrdtool = subprocess.Popen("rrdtool update quota.rrd `date +%%s`:%s" % size[0], shell=True, stdout=subprocess.PIPE).stdout.readlines()
## rrdtool fetch quota.rrd AVERAGE
#rrdtool = subprocess.Popen("rrdtool graph public_html/DrTrigonBot/quota.png DEF:myquota=quota.rrd:quota:AVERAGE LINE2:myquota#FF0000", shell=True, stdout=subprocess.PIPE).stdout.readlines()
# (does not work on solaris and linux in parallel; one is 32bit the other 64bit)
# http://supportex.net/2011/09/rrd-python/
# (https://jira.toolserver.org/browse/DRTRIGON-74)
try:
import platform
import rrdtool
#rrd_fn = "quota-%s.rrd" % platform.platform()
rrd_fn = "quota-%s.rrd" % platform.system()
if '-rrdinit' in sys.argv:
ret = rrdtool.create(rrd_fn, "--step", "86400", "--start", '0',
"DS:metric1:GAUGE:144000:U:U",
"DS:metric2:GAUGE:144000:U:U",
"RRA:AVERAGE:0.5:1:600",
"RRA:AVERAGE:0.5:6:700",
"RRA:AVERAGE:0.5:24:775",
"RRA:AVERAGE:0.5:288:797",
# "RRA:MIN:0.5:1:600",
# "RRA:MIN:0.5:6:700",
# "RRA:MIN:0.5:24:775",
# "RRA:MIN:0.5:444:797",
"RRA:MAX:0.5:1:600",
"RRA:MAX:0.5:6:700",
"RRA:MAX:0.5:24:775",
"RRA:MAX:0.5:444:797")
else:
# update
(metric1, metric2) = (percent, alarm)
ret = rrdtool.update(rrd_fn, 'N:%s:%s' %(metric1, metric2));
# show
#for sched in ['hourly', 'daily', 'weekly', 'monthly']:
for sched in ['monthly']:
fn = "/home/drtrigon/public_html/DrTrigonBot/metrics-%s.png" %(sched)
ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Quota [%]",
'--watermark=DrTrigonBot.TS.Quota',
# "-w 800",
"DEF:m1_num=%s:metric1:AVERAGE" % rrd_fn,
"DEF:m2_num=%s:metric2:AVERAGE" % rrd_fn,
"LINE1:m1_num#0000FF:home\\r",
"LINE2:m2_num#FF0000:alarm\\r",
"GPRINT:m1_num:AVERAGE:Avg home\: %6.0lf ",
# "GPRINT:m1_num:MIN:Min home\: %6.0lf \\r",
"GPRINT:m1_num:MAX:Max home\: %6.0lf \\r")
if '-v' in sys.argv:
print "RRDtool: %s" % rrdtool.fetch(rrd_fn, 'AVERAGE')[2]
except ImportError:
pass # rrdtool not available (linux host)
<file_sep># -*- coding: utf-8 -*-
"""
Configuration variables (config for cgi-bin scripts)
"""
## @package ps_config
# @brief configuration variables
#
# @copyright Dr. Trigon, 2008-2013
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# === labs conversion patch: variables === === ===
#
ver_desc = { 'ts': ['trunk', 'rewrite'],
'labs': ['compat', 'core'], }
localdir = { 'ts': ['..', 'DrTrigonBot', '.'],
'labs': ['..', 'logs', '.'], }
bot_path = { 'ts': ["../../pywikipedia/", "../../rewrite/"],
'labs': ["../../pywikibot-compat/", "../../pywikibot-core/"], }
db_conf = { 'ts': ['u_%(user)s', "wiki-p.userdb.toolserver.org"],
'labs': ['%(user)s__%(dbname)s', "wiki.labsdb"], }
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""XSaLT: XSL/XSLT Simple and Lightweight Tool (CGI) for toolserver
to make it usable from server, use: 'chmod 755 xsalt.py', which results in
'-rwxr-xr-x 1 drtrigon users 447 2009-04-16 19:13 test.py'
"""
# http://www.gpcom.de/support/python
## @package xsalt.py
# @brief XSaLT: XSL/XSLT Simple and Lightweight Tool
#
# @copyright <NAME>, 2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# === python CGI script === === ===
#
import cgitb # debug
cgitb.enable() #
import cgi
# === module imports === === ===
#
# === panel HTML stylesheets === === ===
# MAY BE USING Cheetah (http://www.cheetahtemplate.org/) WOULD BE BETTER (or needed at any point...)
#
import ps_plain as style # panel-stylesheet 'plain'
# === page HTML contents === === ===
#
default_content = \
"""<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>XSaLT: XSL/XSLT Simple and Lightweight Tool</title>
</head>
<body>
<h3>XSaLT: XSL/XSLT Simple and Lightweight Tool</h3>
<p>%(footer)s</p>
<form action="xsalt.py" name="">
<table>
<tr>
<td>url:</td>
<td><input name="url" type="text" size="60" maxlength="200" value="%(url)s"></td>
<td>(e.g. "http://blog.wikimedia.de/feed/")</td>
</tr>
<tr>
<td>xslt:</td>
<td><input name="xslt" type="text" size="60" maxlength="200" value="%(xslt)s"></td>
<td>(e.g. "rss2html.xslt")</td>
</tr>
</table>
<input type="submit" value=" OK ">
</form>
</body>
</html>"""
# === CGI/HTML page view user interfaces === === ===
#
# === Main procedure entry point === === ===
#
form = cgi.FieldStorage()
# operational mode
url = form.getvalue('url', '')
xslt = form.getvalue('xslt', '')
s1 = style.secure_url(url) # security
# check xslt does point to allowed local files on the server (the
# '.xslt' in same directory as script) and not any other, e.g. '../'
import os
allowed = [item for item in os.listdir('.') if '.xslt' in item]
s2 = (xslt in allowed)
secure = s1 and s2
print style.content_type
if secure and url and xslt:
# http://docs.python.org/library/urllib.html#examples
import urllib
f = urllib.urlopen(url)
#print f.read()
# http://lxml.de/xpathxslt.html
from lxml import etree
doc = etree.parse(f)
xslt_root = etree.XML( open(xslt).read() )
transform = etree.XSLT(xslt_root)
result = transform(doc)
#print str(result)
#print result.getroot().text
print result
else:
# disable XSS cross site scripting (code injection vulnerability)
# http://amix.dk/blog/post/19432
url = cgi.escape( url, quote=True)
xslt = cgi.escape(xslt, quote=True)
print default_content % {'url': url, 'xslt': xslt, 'footer': style.footer + style.footer_w3c}
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""DrTrigon Bot status panel (CGI) for toolserver
to make it usable from server, use: 'chmod 755 panel.py', which results in
'-rwxr-xr-x 1 drtrigon users 447 2009-04-16 19:13 test.py'
"""
# http://www.gpcom.de/support/python
## @package panel.py
# @brief DrTrigon Bot status panel for toolserver
#
# @copyright <NAME>, 2008-2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# === python CGI script === === ===
#
import cgitb # debug
cgitb.enable() #
import cgi
# === module imports === === ===
#
from time import *
import datetime
# http://www.ibm.com/developerworks/aix/library/au-python/
import os, re, sys, copy
import subprocess
#import Image,ImageDraw
import cStringIO
# === panel HTML stylesheets === === ===
# MAY BE USING Cheetah (http://www.cheetahtemplate.org/) WOULD BE BETTER (or needed at any point...)
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
# === page HTML contents === === ===
#
displaystate_content = \
"""Actual state: <img src="%(botstate_daily)s" width="15" height="15" alt="Botstate: daily">
<img src="%(botstate_subster)s" width="15" height="15" alt="Botstate: subster">
<img src="%(botstate_wui)s" width="15" height="15" alt="Botstate: wui"><br><br>
Time now: %(time)s<br><br>
Latest gathered bot status message log: <b>%(botlog)s</b><br><br>
Successfully finished bot runs: <b>%(successfull)s</b><br><br>
<h2>Log files</h2>
Current <a href="%(oldlink)s">log files</a>:
<table class="wikitable">
%(currentlog)s
</table>
%(logbrowse)s
Old log files: <i>%(oldlog)s</i><br><br>
<h2>Messages</h2>
See also <a href="%(logstat)s">logging statistics</a> and the important messages:
<p style="white-space:pre-wrap;">%(messages)s</p>
<br>"""
logstat_content = \
"""<small><a href="%(backlink)s">back</a></small><br>
Evaluated data period from %(start_date)s to %(end_date)s.<br>
<br>
<form action="panel.py">
<input type="hidden" name="action" value="logstat">
Filter:
<select name="filter" size="1">
%(filter_options)s
</select>
<input type="submit" value=" OK ">
</form>
<br>
<h2>Runs (started, ended, difference, history compression)</h2>
<a href="%(graphlink-ecount)s"><img src="%(graphlink-ecount)s" alt=""></a>
<a href="%(graphlink-ecount-sed)s"><img src="%(graphlink-ecount-sed)s" alt=""></a><br>
<br>
<div style="width:100%%; overflow:scroll; border:0px solid #000000; margin:1em;">
<table class="wikitable">
<tr><td>Total runs:</td><td>%(start_count)s</td></tr>
<tr><td>Successful runs:</td><td>%(end_count)s</td></tr>
<tr><td>Difference:</td><td>%(run_diff)s</td></tr>
<tr><td>Uptime [s]:</td><td>%(uptimes)s</td></tr>
</table>
</div>
<br>
<h2>Logging messages</h2>
<a href="%(graphlink-mcount)s"><img src="%(graphlink-mcount)s" alt=""></a>
<a href="%(graphlink-mcount-i)s"><img src="%(graphlink-mcount-i)s" alt=""></a><br>
<br>
Important messages (everything except INFO):<br>
<p style="white-space:pre-wrap;">%(messages)s</p>"""
adminlogs_content = \
"""<img src="../DrTrigonBot/metrics-monthly.png"><br>
Log file count: %(logcount)s<br>
<p>%(message)s</p>
<form action="panel.py">
<input type="hidden" name="action" value="adminlogs">
Filter:
<select name="filter" size="1">
%(filter_options)s
</select>
<p>
%(oldloglist)s
</p>
<input type="submit" value=" Delete/OK ">
<input type="reset" value=" Reset ">
</form>"""
# === external (wiki) status links === === ===
#
botstate_img = {#'green': 'http://upload.wikimedia.org/wikipedia/commons/3/3c/ButtonGreen.svg',
'green': 'http://upload.wikimedia.org/wikipedia/commons/6/65/ButtonGreen.png',
#'orange': 'http://upload.wikimedia.org/wikipedia/commons/b/b0/ButtonYellow.svg',
#'red': 'http://upload.wikimedia.org/wikipedia/commons/9/97/ButtonRed.svg',
'orange': 'http://upload.wikimedia.org/wikipedia/commons/b/bf/ButtonYellow.png',
'red': 'http://upload.wikimedia.org/wikipedia/commons/6/65/ButtonRed.png',
}
html_color = { 'green': '#00ff00',
'orange': '#ffff00',
'red': '#ff0000',
}
ver_desc = style.ver_desc[style.host(os.environ)]
localdir = style.localdir[style.host(os.environ)]
links = {'log': { 'ts': localdir,
'labs': '../logs'},
'old': { 'ts': r"../DrTrigonBot/",
'labs': r"../logs/"},}
# === bot status surveillance === === ===
#
bottimeout = 24
botdonemsg = 'DONE'
botcontinuous = [ver_desc[0]+'/pwb.py-subster_irc.log', ver_desc[1]+'/script_wui-bot.log', ver_desc[0]+'/nosetests.log']
# use classic 're' since 'pyparsing' does not work with unicode
## fmt='%(asctime)s %(name)18s: %(levelname)-8s %(message)s'
#regex = re.compile(r'(?P<timestamp>[\d-]+\s[\d:,]+)\s+(?P<file>\S+)\s+(?P<level>\S+)\s+(?P<message>.*)')#, re.U)
# fmt="%(asctime)s %(caller_file)18s, %(caller_line)4s "
# "in %(caller_name)18s: %(levelname)-8s %(message)s"
regex = re.compile(r'(?P<timestamp>[\d-]+\s[\d:,]+)\s+(?P<caller_file>\S+),\s+(?P<caller_line>\S+)\s+in\s+(?P<file>\S+):\s+(?P<level>\S+)\s+(?P<message>.*)')#, re.U)
timefmt = "%Y-%m-%d %H:%M:%S,%f"
timefmt2 = "%Y-%m-%d %H:%M:%S"
datefmt = "%Y-%m-%d"
localdir = os.path.dirname(os.path.join(*localdir))
# === functions === === ===
#
def oldlogfiles(all=False, exclude=['commands.log', 'throttle.log', 'nosetests.log']):
# files = os.listdir( localdir )
files = [os.path.join(ver_desc[0], item) for item in os.listdir( os.path.join(localdir, ver_desc[0]) )]
files += [os.path.join(ver_desc[1], item) for item in os.listdir( os.path.join(localdir, ver_desc[1]) )]
archive, current = {}, []
files.sort()
for item in files:
info = item.split('.')
bn = os.path.basename(item)
if (len(info) < 2) or (bn[1:] == info[-1]) or (bn in exclude):
continue
ext = info[-1].lower()
if ext == 'log' and not info[-2].isdigit(): # isdigit() for core log filename style
current.append( item )
if all:
e = strftime(datefmt)
archive[e] = archive.get(e, []) + [item]
else:
archive[ext] = archive.get(ext, []) + [item]
# sort dict archive and list current
keys, arch = archive.keys(), []
keys.sort()
for k in keys:
arch.append( (k, archive[k]) )
current.sort()
return (localdir, arch, current)
# http://www.scipy.org/Cookbook/Matplotlib/Using_MatPlotLib_in_a_CGI_script
def show_onwebpage(plt):
#plt.show()
#write to file object
f = cStringIO.StringIO()
plt.savefig(f, format="PNG")
f.seek(0)
#output to browser
return "Content-type: image/png\n\n" + f.read()
# http://oreilly.com/pub/h/1968
# http://forum.codecall.net/python-tutorials/33361-developing-basic-irc-bot-python.html
def irc_status():
import socket
import string
HOST = "irc.wikimedia.org"
PORT = 6667
NICK = "DrTrigonBot_panel"
IDENT = NICK.lower()
REALNAME = NICK
CHAN = "#de.wikipedia"
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
#s.send('JOIN ' + CHAN + '\r\n') # Join the pre defined channel
s.send('NAMES ' + CHAN + '\r\n') # Show all Nicks in channel
sleep(.5) # give the server some time
readbuffer=""
while True:
buf=s.recv(1024)
readbuffer=readbuffer+buf
if (':End of /NAMES' in readbuffer):# or (len(buf) < 1024):
break
s.close()
del s
users = []
for line in readbuffer.splitlines():
line=string.rstrip(line)
line=string.split(line)
if (len(line) > 1) and (line[1] == "353"): # answer to 'NAMES' request
i = line.index(CHAN)
users += line[(i+1):]
return users
def logging_statistics(logfiles, exclude):
# chronological sort
logfiles = dict([ (os.stat(os.path.join(localdir, item)).st_mtime, item) \
for item in logfiles \
if (item not in exclude) and (os.path.splitext(item)[0] not in exclude) ])
keys = logfiles.keys()
keys.sort()
buffer = []
#for file in logfiles:
for k in keys:
file = logfiles[k]
#if file in exclude:
# continue
f = open(os.path.join(localdir, file), "r")
#buffer += f.read(-1).strip().split("\n")
buffer.append( (file, f.read(-1).strip().splitlines()) )
f.close()
if not buffer:
return None, None
# statistics (like mentioned in 'logging.statistics')
mcount = { 'debug': 0, 'warning': 0, 'info': 0, 'error': 0, 'critical': 0, 'unknown': 0, }
mqueue = { 'debug': [], 'warning': [], 'info': [], 'error': [], 'critical': [], 'unknown': [], }
events = { 'start': '=== Pywikipediabot framework v1.0 -- Logging header ===',
'end': botdonemsg, }
ecount = { 'start': 0, 'end': 0, }
etiming = { 'start': [], 'end': [],
'mainstart': None, 'mainend': None, }
fcount = {}
ftiming = {}
resources = { 'files': set(), }
def process_event(event, result, log, process=None, ignore=[]):
# match event
if process is None:
event = 'unknown' if event not in result else event
else:
noevent = True
for e in process:
#if process[e] in event:
if (process[e] == event.strip()):
event = e
noevent = False
break
if noevent:
return
# count matched events
result[event] += 1
if event not in ignore:
log[0][event].append( log[1] )
return
timeepoch = lambda t: mktime(datetime.datetime.strptime(t, (timefmt if ',' in t else timefmt2)).timetuple())
#How many requests are being handled per second, how much of various resources are
# gather statistics
etiming['mainstart'] = [ regex.match(buffer[0][1][0]).groupdict()['timestamp'] ]
#etiming['mainend'] = [ regex.match(buffer[-1][1][-1]).groupdict()['timestamp'] ]
end = regex.match(buffer[-1][1][-1])
end = regex.match(buffer[-1][1][-2]) if not end else end # or strftime(timefmt2)
etiming['mainend'] = [ end.groupdict()['timestamp'] ]
info = {'level': 'unknown', 'message': '', 'timestamp': etiming['mainstart'][0], 'file': ''}
for item in buffer:
file = os.path.split(item[0])[1].split('-')[1].split('.')[0]
for line in item[1]:
if not line.strip(): continue
data = regex.match(line)
if (data is not None):
data = data.groupdict()
else:
#line = ("%(level)s " % info) + line
data = {'message': line}
info.update( data )
process_event( info['level'].lower(), mcount, (mqueue, cgi.escape(line)),
process=None, ignore=['info'] )
process_event( info['message'], ecount, (etiming, info['timestamp']),
process=events, ignore=[] )
resources['files'].add( info['file'] )
fcount[file] = fcount.get(file, 0) + ecount['start']
ftiming[file] = ftiming.get(file, []) + etiming['start']
# evaluate statistics
ecount.update(fcount)
etiming.update(ftiming)
stats = {'mcount': mcount, 'mqueue': mqueue, 'ecount': ecount, 'resources': resources}
# (in use, how long we've been up.)
start = datetime.datetime.strptime(etiming['mainstart'][0], (timefmt if ',' in etiming['mainstart'][0] else timefmt2))
end = datetime.datetime.strptime(etiming['mainend'][0], (timefmt if ',' in etiming['mainend'][0] else timefmt2))
stats['uptime'] = (end - start).seconds
stats['mainstart'] = timeepoch(etiming['mainstart'][0])
stats['mainend'] = timeepoch(etiming['mainend'][0])
# gather messages ignoring info
stats['messages'] = []
for key in mqueue:
if key == 'info': continue
stats['messages'].append( "<i>%s</i>" % key )
stats['messages'] += mqueue[key]
# assign and convert event times
for key in etiming:
etiming[key] = [ timeepoch(item) for item in etiming[key] ]
stats['etiming'] = etiming
# last message
#stats['lastmessage'] = regex.match(buffer[-1][1][-1]).groupdict()['message'].strip()
stats['lastmessage'] = ''
for i in range(len(buffer[-1][1])):
m = regex.match('<br>'.join(buffer[-1][1][-(i+1):]))
if m:
stats['lastmessage'] = m.groupdict()['message'].strip()
break
return (stats, logfiles[keys[-1]])
# === SHELL/CRON interfaces === === ===
#
def maintain_stats(init=False):
# http://supportex.net/2011/09/rrd-python/
# (https://jira.toolserver.org/browse/DRTRIGON-74)
global localdir # why is this needed here? nowhere else needed...?!?!!
import platform, numpy, rrdtool # for statistics '-stats'
#rrd_fn = os.path.join(localdir, "stats-01-%s.rrd" % platform.platform())
rrd_fn = os.path.join(localdir, "stats-01-%s.rrd" % platform.system())
if init:
ret = rrdtool.create(rrd_fn, "--step", "86400", "--start", '0',
"DS:sum_start:GAUGE:144000:U:U",
"DS:sum_end:GAUGE:144000:U:U",
"DS:sum_diff:GAUGE:144000:U:U",
"DS:bot_sum_disc:GAUGE:144000:U:U",
"DS:bot_subster:GAUGE:144000:U:U",
"DS:bot_catimages:GAUGE:144000:U:U",
"DS:bot_uptime_sum_disc:GAUGE:144000:U:U",
"DS:bot_uptime_subster:GAUGE:144000:U:U",
"DS:bot_uptime_catimages:GAUGE:144000:U:U",
"DS:msg_unknown:GAUGE:144000:U:U",
"DS:msg_info:GAUGE:144000:U:U",
"DS:msg_warning:GAUGE:144000:U:U",
"DS:msg_error:GAUGE:144000:U:U",
"DS:msg_critical:GAUGE:144000:U:U",
"DS:msg_debug:GAUGE:144000:U:U",
"DS:metric1:GAUGE:144000:U:U",
"DS:metric2:GAUGE:144000:U:U",
"DS:metric3:GAUGE:144000:U:U",
"DS:metric4:GAUGE:144000:U:U",
"DS:metric5:GAUGE:144000:U:U",
"DS:sum_diff_inter:COMPUTE:sum_start,sum_end,-",
# (number of logfiles, quota, ...)
"RRA:AVERAGE:0.5:1:600",
"RRA:AVERAGE:0.5:6:700",
"RRA:AVERAGE:0.5:24:775",
"RRA:AVERAGE:0.5:288:797",
"RRA:MIN:0.5:1:600",
"RRA:MIN:0.5:6:700",
"RRA:MIN:0.5:24:775",
"RRA:MIN:0.5:444:797",
"RRA:MAX:0.5:1:600",
"RRA:MAX:0.5:6:700",
"RRA:MAX:0.5:24:775",
"RRA:MAX:0.5:444:797",
"RRA:LAST:0.5:1:600",
"RRA:LAST:0.5:6:700",
"RRA:LAST:0.5:24:775",
"RRA:LAST:0.5:444:797")
else:
(localdir, files, current) = oldlogfiles()
stat, recent = logging_statistics(current, botcontinuous)
# for item in current:
# stat, recent = logging_statistics([item], botcontinuous)
# if stat is None:
# continue
# end, start = numpy.array(stat['etiming']['end']), numpy.array(stat['etiming']['start'])
# shape = min(end.shape[0], start.shape[0])
# runtime = end[:shape]-start[:shape]-7200 # -2*60*60 because of time jump during 'set TZ'
# if runtime.any() and (runtime.min() < 0): # DST or not; e.g. ('CET', 'CEST')
# runtime += 3600
# uptime = numpy.array(runtime).sum()
(bot_uptime_sum_disc, bot_uptime_subster, bot_uptime_catimages) = (0, 0, 0)
(metric1, metric2, metric3, metric4, metric5) = (0, 0, 0, 0, 0)
val = (ecount['start'], ecount['end'], (ecount['start']-ecount['end']),
ecount['sum_disc'], ecount['subster'], ecount['catimages'],
bot_uptime_sum_disc, bot_uptime_subster, bot_uptime_catimages,
mcount['unknown'], mcount['info'], mcount['warning'], mcount['error'], mcount['critical'], mcount['debug'],
metric1, metric2, metric3, metric4, metric5,)
# update
ret = rrdtool.update(rrd_fn, ('N' + (':%s'*22)) % val);
# show
#for sched in ['hourly', 'daily', 'weekly', 'monthly']:
for sched in ['daily', 'weekly', 'monthly']:
fn = "/home/drtrigon/public_html/DrTrigonBot/test-%s.png" % (sched)
# ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Num",
# '--watermark=DrTrigonBot.TS',
# "-w 800",
# "DEF:m1_num=%s:metric1:AVERAGE" % rrd_fn,
# "DEF:m2_num=%s:metric2:AVERAGE" % rrd_fn,
# "LINE1:m1_num#0000FF:metric1\\r",
# "LINE2:m2_num#00FF00:metric2\\r",
# "GPRINT:m1_num:AVERAGE:Avg m1\: %6.0lf ",
# "GPRINT:m1_num:MAX:Max m1\: %6.0lf \\r",
# "GPRINT:m2_num:AVERAGE:Avg m2\: %6.0lf ",
# "GPRINT:m2_num:MAX:Max m2\: %6.0lf \\r")
ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Num",
'--watermark=DrTrigonBot.TS',
"DEF:end_num=%s:sum_end:AVERAGE" % rrd_fn,
"DEF:start_num=%s:sum_start:AVERAGE" % rrd_fn,
"DEF:subster_num=%s:bot_subster:AVERAGE" % rrd_fn,
"DEF:sum_disc_num=%s:bot_sum_disc:AVERAGE" % rrd_fn,
"DEF:catimages_num=%s:bot_catimages:AVERAGE" % rrd_fn,
"LINE1:end_num#0000FF:end\\r",
"LINE2:start_num#00FF00:start\\r",
"LINE4:subster_num#00FF00:subster\\r",
"LINE5:sum_disc_num#00FF00:sum_disc\\r",
"LINE6:catimages_num#00FF00:catimages\\r",
"GPRINT:end_num:AVERAGE:Avg end\: %6.0lf ",
"GPRINT:end_num:MAX:Max end\: %6.0lf \\r",
"GPRINT:start_num:AVERAGE:Avg start\: %6.0lf ",
"GPRINT:start_num:MAX:Max start\: %6.0lf \\r")
# ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Num",
# '--watermark=DrTrigonBot.TS',
# "DEF:end_num=%s:sum_end:AVERAGE" % rrd_fn,
# "DEF:diff_num=%s:sum_diff:AVERAGE" % rrd_fn,
# "DEF:diff_intern_num=%s:sum_diff_inter:AVERAGE" % rrd_fn,
# "LINE1:end_num#0000FF:successful\\r",
# "LINE2:diff_num#00FF00:runs_failed\\r",
# "LINE3:diff_intern_num#00FF00:runs_failed_i\\r",
# "GPRINT:end_num:AVERAGE:Avg end\: %6.0lf ",
# "GPRINT:end_num:MAX:Max end\: %6.0lf \\r")
# ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Num",
# '--watermark=DrTrigonBot.TS',
# "DEF:unknown_num=%s:msg_unknown:AVERAGE" % rrd_fn,
# "DEF:warning_num=%s:msg_warning:AVERAGE" % rrd_fn,
# "DEF:error_num=%s:msg_error:AVERAGE" % rrd_fn,
# "DEF:critical_num=%s:msg_critical:AVERAGE" % rrd_fn,
# "DEF:debug_num=%s:msg_debug:AVERAGE" % rrd_fn,
# "LINE1:unknown_num#0000FF:unknown\\r",
# "LINE2:warning_num#00FF00:warning\\r",
# "LINE3:error_num#00FF00:error\\r",
# "LINE4:critical_num#00FF00:critical\\r",
# "LINE5:debug_num#00FF00:debug\\r",
# "GPRINT:warning_num:AVERAGE:Avg warning\: %6.0lf ",
# "GPRINT:warning_num:MAX:Max warning\: %6.0lf \\r")
# ret = rrdtool.graph( fn, "--start", "-1%s" %(sched[0]), "--vertical-label=Num",
# '--watermark=DrTrigonBot.TS',
# "DEF:info_num=%s:msg_info:AVERAGE" % rrd_fn,
# "LINE1:info_num#0000FF:info\\r",
# "GPRINT:info_num:AVERAGE:Avg info\: %6.0lf ",
# "GPRINT:info_num:MAX:Max info\: %6.0lf \\r")
# print rrdtool.fetch(rrd_fn, 'AVERAGE')[2]
# * add rrdtool graphs for comparison to statistics page, later remove matplotlib
# * get all data on statistics page from rrdtool.fetch, thus replace text output below graphs
# through links to mainpages but containing history (old days/logs)
# -> mainpage has to be capable to process and show old data
# -> mainpage does always gather actual data and NOT use rrdtool.fetch (and thus can also
# process text data like messages)
# * setup cron job at midnight in order to gather and update rrdtool data and graphs
# === CGI/HTML page view user interfaces === === ===
#
def displaystate(form):
data = {}
(localdir, files, current) = oldlogfiles()
files = [item for key, value in files for item in value] # flatten
# < prev | next > browsing
date = form.getvalue('date', None)
if date:
current = [item for item in files if date in item]
today = datetime.datetime.strptime(date, '%Y-%m-%d')
else:
today = datetime.datetime.today()
yesterday = (today - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
tomorrow = (today + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
data['logbrowse'] = "<a href='?date=%s'>< prev</a> | <a href='?'>now</a>" % yesterday
if (datetime.datetime.today() - today) >= datetime.timedelta(days=2):
data['logbrowse'] += " | <a href='?date=%s'>next ></a><br><br>" % tomorrow
data['logbrowse'] += "<br><br>"
today = mktime(today.timetuple())
stat, recent = logging_statistics(current, botcontinuous)
if stat is None:
data['botlog'] = 'n/a'
data['messages'] = 'n/a'
data['successfull'] = "n/a"
else:
data['botlog'] = stat['lastmessage']
data['messages'] = "\n".join(stat['messages'])
data['successfull'] = "%s of %s" % (stat['ecount']['end'], stat['ecount']['start'])
lastrun = max([os.stat(os.path.join(localdir, item)).st_mtime for item in current]+[0])
botmsg = data['botlog'].strip()
data['botstate_daily'] = botstate_img['red']
color = html_color['red']
state_text = "n/a"
if lastrun and ((today-lastrun) <= (bottimeout*60*60)):
if (botmsg == botdonemsg) and not (stat['ecount']['end'] - stat['ecount']['start']):
data['botstate_daily'] = botstate_img['green']
color = html_color['green']
state_text = "OK"
elif (botmsg.find(botdonemsg) == 0):
data['botstate_daily'] = botstate_img['orange']
color = html_color['orange']
state_text = "problem"
else:
data['botstate_daily'] = botstate_img['orange']
color = html_color['orange']
users = irc_status()
data['botstate_subster'] = botstate_img['red']
if ("DrTrigonBot" in users) or (":DrTrigonBot" in users):
data['botstate_subster'] = botstate_img['green']
irc_subster_color = html_color['green']
irc_subster_state_text = "OK"
else:
data['botstate_subster'] = botstate_img['orange']
irc_subster_color = html_color['orange']
irc_subster_state_text = "problem"
data['botstate_wui'] = botstate_img['red']
if ("DrTrigonBot_WUI" in users) or (":DrTrigonBot_WUI" in users):
data['botstate_wui'] = botstate_img['green']
irc_wui_color = html_color['green']
irc_wui_state_text = "OK"
else:
data['botstate_wui'] = botstate_img['orange']
irc_wui_color = html_color['orange']
irc_wui_state_text = "problem"
status = "<tr style='background-color: %(color)s'><td>%(bot)s</td><td>%(state)s</td></tr>\n" % {'color': color, 'bot': 'regular:', 'state': state_text}
status += "<tr><td></td><td></td></tr>\n" # separator (cheap)
status += "<tr style='background-color: %(color)s'><td>%(bot)s</td><td>%(state)s</td></tr>\n" % {'color': irc_subster_color, 'bot': 'subster:', 'state': irc_subster_state_text}
status += "<tr style='background-color: %(color)s'><td>%(bot)s</td><td>%(state)s</td></tr>\n" % {'color': irc_wui_color, 'bot': 'wui:', 'state': irc_wui_state_text}
# ('replace' below is a lapbs patch)
data['currentlog'] = []
for item in current:
s, r = logging_statistics([item], [])#botcontinuous)
if not s:
s = {'lastmessage': 'n/a', 'ecount': {'end': 'n/a', 'start': 'n/a'}}
logfile = os.path.join(localdir, item)
lasttime = os.stat(logfile).st_mtime
logstate = botstate_img['red']
if (today-lasttime) <= (bottimeout*60*60):
if (s['lastmessage'] == botdonemsg) and not (s['ecount']['end'] - s['ecount']['start']):
logstate = botstate_img['green']
elif (botmsg.find(botdonemsg) == 0):
logstate = botstate_img['orange']
else:
logstate = botstate_img['orange']
data['currentlog'].append( '<tr%s><td><a href="%s">%s</a></td><td>%s</td><td>%s of %s</td><td>%s</td><td><img src="%s" width="15" height="15" alt=""></td></tr>' %
(' bgcolor="#CCCCCC"' if item == recent else '',
logfile.replace('public_html/', ''), item,
s['lastmessage'],
s['ecount']['end'], s['ecount']['start'],
asctime(localtime(lasttime)),
logstate) )
data['currentlog'].append( '<tr%s><td><b>%s</b></td><td>%s</td><td>%s of %s</td><td></td><td><img src="%s" width="15" height="15" alt=""></td></tr>' %
(' style="font-weight:bold;"',
'Summary / Total',
stat['lastmessage'],
stat['ecount']['end'], stat['ecount']['start'],
data['botstate_daily']) )
data['currentlog'] = "\n".join(data['currentlog'])
data.update({ 'time': asctime(localtime(time())),
'oldlog': ", ".join(files),
'oldlink': links['old'][style.host(os.environ)],
'logstat': os.path.basename(sys.argv[0]) + r"?action=logstat",
'logstatraw': os.path.basename(sys.argv[0]) + r"?action=logstat&format=plain",
'refresh': '15',
'title': 'DrTrigonBot status panel',
'tsnotice': style.print_tsnotice(),
'p-status': status,
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = displaystate_content % data
return style.page % data
def adminlogs(form):
data = {}
(localdir, files, current) = oldlogfiles()
files = [item for key, value in files for item in value] # flatten
files.sort()
filelist = form.getvalue('filelist', [])
if type(filelist) == type(''): filelist = [filelist]
current.insert(0, 'ALL')
filt = form.getvalue('filter', current[0])
filt = ('' if filt == 'ALL' else filt)
data['filter_options'] = "<option>%s</option>" % ("</option><option>".join(current))
data['filter_options'] = data['filter_options'].replace("<option>%s</option>" % filt,
"<option selected>%s</option>" % filt)
files = filter(lambda item: filt in item, files)
files_str = map(str, files)
data['message'] = ''
if (len(filelist) > 0):
data['message'] = []
for item in filelist:
if (item in files_str):
os.remove( os.path.join(localdir, item) )
else:
data['message'].append( 'Warning: "%s" is NOT a log file! Nothing done.' % item )
data['message'].append( '%i log file(s) deleted.' % (len(filelist)-len(data['message'])) )
data['message'] = '<br>\n'.join(data['message'])
(localdir, files, current) = oldlogfiles()
files = [item for key, value in files for item in value] # flatten
checkbox_tmpl = '<input type="checkbox" name="filelist" value="%(datei)s">%(datei)s<br>'
# get directory size (but is not stable)
du = subprocess.Popen(["du", "-hL", localdir], stdout=subprocess.PIPE)
du = du.communicate()[0].split()
size = du[du.index('../DrTrigonBot')-1]
#data.update({ 'oldloglist': '\n'.join([checkbox_tmpl % {'datei':item} for item in files[:-5]]),
data.update({ 'oldloglist': '\n'.join([checkbox_tmpl % {'datei':item} for item in files]),
'logcount': "%i (size: %s)" % (len(files), size),
'refresh': '',
'title': 'DrTrigonBot log admin panel',
'tsnotice': '',
'content': adminlogs_content,
'footer': '',
})
return (style.admin_page % data) % data
def logstat(form):
import matplotlib
matplotlib.rc('font', size=8)
import matplotlib.pyplot as plt
# http://matplotlib.sourceforge.net/api/dates_api.html?highlight=year%20out%20range#matplotlib.dates.epoch2num
from matplotlib.dates import MonthLocator, DayLocator, DateFormatter, epoch2num
# import platform, rrdtool # for statistics '-stats'
import numpy
data = {'messages': '', }
format = form.getvalue('format', 'html')
# filter: '' (all), 'default', 'subster', 'subster_irc', 'catimages'
# (similar to the one used in adminlogs)
current = ['ALL', 'default', 'subster', 'catimages',]# 'subster_irc', 'script_wui']
filt = form.getvalue('filter', current[0])
filt = ('' if filt == 'ALL' else filt)
data['filter_options'] = "<option>%s</option>" % ("</option><option>".join(current))
data['filter_options'] = data['filter_options'].replace("<option>%s</option>" % filt,
"<option selected>%s</option>" % filt)
(localdir, files, log) = oldlogfiles(all=True)
stat = {}
for date, item in files:
logfiles = [f for f in item if filt in f]
#if not logfiles:
# continue
s, recent = logging_statistics(logfiles, botcontinuous)
if s is None: # includes 'if not logfiles'
continue
last = date # a little bit hacky but needed for plot below
stat[date] = s
d = {'mcount': [], 'ecount': [], 'uptimes': []}
keys = stat.keys()
keys.sort()
data['start_date'] = str(strftime("%a %b %d %Y", localtime( stat[keys[0]]['mainstart'] )))
data['end_date'] = str(strftime("%a %b %d %Y", localtime( stat[keys[-1]]['mainend'] )))
dkeys = dict([ (k, i) for item in keys for i, k in enumerate(stat[item]['ecount'].keys()) ])
d['ecount'] = numpy.zeros((len(keys),len(dkeys)+1))
for i, item in enumerate(keys):
t = mktime(strptime(item.split('.')[-1], datefmt))
d['mcount'].append( [t] + stat[item]['mcount'].values() )
d['ecount'][i,0] = t
for kj in dkeys:
d['ecount'][i,(dkeys[kj]+1)] = stat[item]['ecount'].get(kj, 0)
data['messages'] += "<b>%s</b>\n<i>used resources: %s</i>\n" % (item, stat[item]['resources'])
data['messages'] += "\n".join(stat[item]['messages']) + ("\n"*2)
end = numpy.array(stat[item]['etiming']['end'])
start = numpy.array(stat[item]['etiming']['start'])
if end.shape == start.shape:
runtime = end-start-7200 # -2*60*60 because of time jump during 'set TZ'
if runtime.any() and (runtime.min() < 0): # DST or not; e.g. ('CET', 'CEST')
runtime += 3600
d['uptimes'].append( list(runtime) )
else:
d['uptimes'].append( '-' )
d['mcount'] = numpy.array(d['mcount'])
#d['ecount'] = numpy.array(d['ecount'])
d['mcount'][:,0] = epoch2num(d['mcount'][:,0])
d['ecount'][:,0] = epoch2num(d['ecount'][:,0])
keys = dkeys.keys()
ks, ke = keys.index('start')+1, keys.index('end')+1
plotlink = os.path.basename(sys.argv[0]) + (r"?action=logstat&filter=%s" % filt)
data.update({
'run_diff': "</td><td>".join( map(str, d['ecount'][:,ks]-d['ecount'][:,ke]) ),
'start_count': "</td><td>".join( map(str, d['ecount'][:,ks]) ),
'end_count': "</td><td>".join( map(str, d['ecount'][:,ke]) ),
'uptimes': "</td><td>".join( map(str, d['uptimes']) ),
'graphlink-mcount': plotlink + r"&format=graph-mcount",
'graphlink-mcount-i': plotlink + r"&format=graph-mcount-i",
'graphlink-ecount': plotlink + r"&format=graph-ecount",
'graphlink-ecount-sed': plotlink + r"&format=graph-ecount-sed",
'backlink': os.path.basename(sys.argv[0]),
})
# plot graphs output
if (format == 'graph-mcount'):
d = d['mcount']
fig = plt.figure(figsize=(5,3))
#ax = fig.add_subplot(111)
ax_size = [0.125, 0.15,
1-0.1-0.05, 1-0.15-0.05]
ax = fig.add_axes(ax_size)
#plot1 = ax.bar(range(len(xdata)), xdata)
#p1 = ax.plot(d[:,0], d[:,1]) # 'info'
p2 = ax.step(d[:,0], d[:,2], marker='x', where='mid')
p3 = ax.step(d[:,0], d[:,3], marker='x', where='mid')
p4 = ax.step(d[:,0], d[:,4], marker='x', where='mid')
p5 = ax.step(d[:,0], d[:,5], marker='x', where='mid')
p6 = ax.step(d[:,0], d[:,6], marker='x', where='mid')
plt.legend([p2, p3, p4, p5, p6], stat[last]['mcount'].keys()[1:], loc='upper left', prop={'size':8})
plt.grid(True, which='both')
# format the ticks
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(DayLocator())
ax.autoscale_view()
# format the coords message box
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
# format axis
fig.autofmt_xdate()
# show plot
return show_onwebpage(plt)
elif (format == 'graph-mcount-i'):
d = d['mcount']
fig = plt.figure(figsize=(5,3))
#ax = fig.add_subplot(111)
ax_size = [0.125, 0.15,
1-0.1-0.05, 1-0.15-0.05]
ax = fig.add_axes(ax_size)
p1 = ax.step(d[:,0], d[:,1], marker='x', where='mid')
# legend
plt.legend([p1], stat[last]['mcount'].keys(), loc='upper left', prop={'size':8})
# grid
plt.grid(True, which='both')
# format the ticks
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(DayLocator())
ax.autoscale_view()
# format the coords message box
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
# format axis
fig.autofmt_xdate()
# show plot
return show_onwebpage(plt)
elif (format == 'graph-ecount'):
d = d['ecount']
fig = plt.figure(figsize=(5,3))
#ax = fig.add_subplot(111)
ax_size = [0.125, 0.15,
1-0.1-0.05, 1-0.15-0.05]
ax = fig.add_axes(ax_size)
pa = []
for i in range(1, d.shape[1]):
pa.append( ax.step(d[:,0], d[:,i], where='mid') )#, marker='x') )
plt.legend(pa, stat[last]['ecount'].keys(), loc='upper left', bbox_to_anchor=[-0.15, 1.0], ncol=2, prop={'size':8})
plt.grid(True, which='both')
#plt.ylim(ymax=10)
# format the ticks
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(DayLocator())
ax.autoscale_view()
# format the coords message box
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
# format axis
fig.autofmt_xdate()
# show plot
return show_onwebpage(plt)
elif (format == 'graph-ecount-sed'):
d = d['ecount']
fig = plt.figure(figsize=(5,3))
#ax = fig.add_subplot(111)
ax_size = [0.125, 0.15,
1-0.1-0.05, 1-0.15-0.05]
ax = fig.add_axes(ax_size)
p1 = ax.step(d[:,0], (d[:,ks]-d[:,ke]), marker='x', where='mid')
p2 = ax.step(d[:,0], d[:,ke], marker='x', where='mid')
plt.legend([p1, p2], ['runs failed', 'successful'], prop={'size':8})
plt.grid(True, which='both')
# format the ticks
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis.set_minor_locator(DayLocator())
ax.autoscale_view()
# format the coords message box
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
# format axis
fig.autofmt_xdate()
# show plot
return show_onwebpage(plt)
data.update({ 'refresh': '',
'title': 'DrTrigonBot log statistics',
'tsnotice': style.print_tsnotice(),
#'content': logstat_content,
'p-status': '<tr><td></td></tr>',
'footer': style.footer + style.footer_w3c,
})
data['content'] = logstat_content % data
# default output
return style.page % data
# === Main procedure entry point === === ===
#
if __name__ == '__main__':
if '-init_stats' in sys.argv:
maintain_stats(init=True)
elif '-stats' in sys.argv:
maintain_stats()
else:
form = cgi.FieldStorage()
# operational mode
action = form.getvalue('action', 'displaystate')
#print locals()[action](form)
print style.change_logo(locals()[action](form), os.environ) # labs patch
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Global Wiki API Version (CGI) for toolserver
(for mor info look at 'panel.py' also!)
"""
## @package g_api_ver.py
# @brief Global Wiki API Version (CGI) for toolserver
#
# @copyright <NAME>, 2008-2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# debug
import cgitb
cgitb.enable()
import cgi
from time import *
# http://www.ibm.com/developerworks/aix/library/au-python/
import os, re, sys
bot_path = os.path.realpath("../../pywikipedia/")
sys.path.append( bot_path ) # bot import form other path (!)
import query #
import wikipedia as pywikibot #
# === panel HTML stylesheets === === ===
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
displaystate_content = \
"""%(output)s"""
wikilist = ["translatewiki.net", "test.wikipedia.org", "de.wikipedia.org", "en.wikipedia.org"]
blacklist = [u'userrights']
def displayhtmlpage(form):
site = pywikibot.getSite()
data = {'output': ''}
wikis = wikilist
param_wiki = form.getvalue('wiki', None)
if param_wiki:
wikis = param_wiki.split("|")
for wiki in wikis:
data['output'] += "<b>%s</b><br>\n" % wiki
# .../w/api.php?action=help&format=xml
params = {
u'action' : u'help',
}
test = query.GetData(params, site)[u'error'][u'*']
test = re.split('\n', test)[29]
full_actions = re.split('[:,]\s', test)[1:]
actions = [item for item in full_actions if item not in blacklist]
# .../w/api.php?action=paraminfo&modules=%s&format=xml
params = {
u'action' : u'paraminfo',
u'modules' : u'|'.join(actions),
}
test = query.GetData(params, site)[u'paraminfo'][u'modules']
test = [t.get(u'version', u'> PROBLEM <') for t in test]
#test = str(test)
#test = "<br>\n".join(test)
#test = str(re.search('\.php (\d*?) ', test[0]).groups())
test = ["<tr>\n <td>%s</td>\n</tr>\n" % item for item in test]
test = "".join(test)
data['output'] += "<table>\n"
data['output'] += "<tr>\n <td>"
data['output'] += "actions:"
data['output'] += "</td>\n <td>"
data['output'] += str(full_actions)
data['output'] += "</td>\n</tr>\n"
data['output'] += "<tr>\n <td>"
data['output'] += "blacklist:"
data['output'] += "</td>\n <td>"
data['output'] += str(blacklist)
data['output'] += "</td>\n</tr>\n"
data['output'] += "</table>\n"
data['output'] += "<br>\n"
data['output'] += "<table>\n"
data['output'] += test
data['output'] += "</table>\n"
data['output'] += "<br>\n"
data.update({ 'title': 'Global Wiki API Version',
'refresh': '',
'tsnotice': style.print_tsnotice(),
'p-status': '<tr><td></td></tr>',
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = displaystate_content % data
return style.page % data
form = cgi.FieldStorage()
# operational mode
print displayhtmlpage(form)
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""DrTrigonBot checksum checker (CGI) for toolserver
(for mor info look at 'panel.py' also!)
"""
## @package chksum_check.py
# @brief DrTrigonBot checksum checker (CGI) for toolserver
#
# @copyright <NAME>, 2008-2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# debug
import cgitb
cgitb.enable()
import cgi
from time import *
# http://www.ibm.com/developerworks/aix/library/au-python/
import os, re, sys
import hashlib
bot_path = os.path.realpath("../../pywikipedia/")
sys.path.append( bot_path ) # bot import form other path (!)
import query #
import wikipedia as pywikibot #
# === panel HTML stylesheets === === ===
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
displaystate_content = \
"""%(output)s<br>"""
textfile_encoding = 'utf-8'
def displayhtmlpage(form):
titles = re.split('\|', form.getvalue('title', ''))
sections = re.split('\|', form.getvalue('section', ''))
chksum = re.split('\|', form.getvalue('chksum', ''))
site = pywikibot.getSite()
data = {'output': ''}
#data['output'] += str(titles)
#data['output'] += "<br>"
#data['output'] += str(chksum)
#data['output'] += "<br>"
for i, title in enumerate(titles):
try: section = sections[i]
except: section = '0'
# .../w/api.php?action=parse&page=%s&prop=sections&format=xml
params = {
u'action' : u'parse',
u'page' : title,
u'prop' : u'sections',
}
try:
test = query.GetData(params, site)[u'parse'][u'sections']
except:
# e.g. wrong params for page call ...
data['output'] += str(query.GetData(params, site))
data['output'] += "<br>"
break
test = dict( [(item[u'line'], item[u'number']) for item in test] )
if section in test: section = test[section]
# .../w/api.php?action=query&prop=revisions&titles=%s&rvprop=timestamp|user|comment|content&rvsection=%s&format=xml
params = {
u'action' : u'query',
u'prop' : u'revisions',
u'titles' : title,
u'rvprop' : u'timestamp|user|comment|content',
u'rvsection' : section,
}
try:
test = query.GetData(params, site)[u'query'][u'pages']
except:
# e.g. wrong params for page call ...
data['output'] += str(query.GetData(params, site))
data['output'] += "<br>"
break
test = test[test.keys()[0]][u'revisions'][0]
dh_chars = test[u'*']
m = re.search('^(=+)(.*?)(=+)(?=\s)', dh_chars, re.M)
if m: section_name = m.groups()[1].strip()
else: section_name = "?"
data['output'] += "Page: <i>%s</i> / Section: <i>%s (%s)</i>" % (title, section_name.encode(textfile_encoding), section)
data['output'] += "<br>"
data['output'] += "Old checksum: %s" % chksum[i]
data['output'] += "<br>"
new_chksum = hashlib.md5(dh_chars.encode('utf8').strip()).hexdigest()
data['output'] += "New checksum: %s" % new_chksum
data['output'] += "<br>"
data['output'] += "<b>Section changed: %s</b>" % (not (chksum[i] == new_chksum))
#data['output'] += "<br>"
#data['output'] += "<div style=\"padding:20px; border:thin solid gray; margin:25px\">"
#data['output'] += "<small>"
##data['output'] += re.sub('\n','<br>',text).encode('utf8')
#data['output'] += text.encode('utf8')
#data['output'] += "</small>"
#data['output'] += "</div>"
data['output'] += "<br>"
data.update({ 'title': 'DrTrigonBot checksum checker',
'refresh': '',
'tsnotice': style.print_tsnotice(),
'p-status': '<tr><td></td></tr>',
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = displaystate_content % data
return style.page % data
form = cgi.FieldStorage()
# operational mode
print displayhtmlpage(form)
<file_sep># -*- coding: utf-8 -*-
"""
panel-stylesheet 'wiki (monobook)' (module for panel.py)
"""
## @package ps_wiki
# @brief panel-stylesheet 'wiki (monobook)'
#
# @copyright Dr. Trigon, 2008-2010
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
from ps_plain import *
tsnotice = """<br><div class="tsnotice" id="tsnotice">%(text)s</div>"""
page = content_type + """
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>%(title)s</title>
<!-- Idea to use Wiki stylesheet from: http://toolserver.org/~vvv/sulutil.php -->
<link rel="stylesheet" href="http://en.wikipedia.org/skins-1.5/monobook/main.css">
<link rel="stylesheet" href="https://meta.wikimedia.org/skins-1.5/common/shared.css">
<link rel="stylesheet" href="../tsnotice.css">
<!--<link rel="stylesheet" media="all" type="text/css" href="http://tools.wikimedia.de/~vvv/inc/ts.css" />-->
<meta http-equiv="refresh" content="%(refresh)s">
</head>
<body class="mediawiki">
<div id="globalWrapper"><div id="column-content"><div id="content">
%(tsnotice)s
<h1>%(title)s</h1>
%(content)s
%(footer)s
</div></div>
<div id="column-one">
<div class="portlet" id="p-logo"><a style="background-image:
url(http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Wikimedia_Community_Logo-Toolserver.svg/135px-Wikimedia_Community_Logo-Toolserver.svg.png);"
href="http://toolserver.org/~vvv/" title="Home"></a></div>
<div class='portlet' id='p-navigation'><h5>navigation</h5><div class='pBody'>
<ul>
<li><a href="http://tools.wikimedia.de/~vvv/">Main Page</a></li>
<li><a href="http://jira.ts.wikimedia.org/browse/VVV">Bug tracker</a></li>
<li><a href="http://fisheye.ts.wikimedia.org/browse/vvv">SVN repository</a></li>
</ul>
</div></div>
<div class='portlet' id='p-status'><h5>status</h5><div class='pBody'>
<table style="width: 100%%; border-collapse: collapse;">
<tr style='background-color: #a5ffbb'><td style='width: 25%%; padding-left: 1em;'>c_u_s</td><td>OK</td></tr>
<tr style='background-color: #a5ffbb'><td style='width: 25%%; padding-left: 1em;'>sum_disc</td><td>OK</td></tr>
<tr style='background-color: #a5ffbb'><td style='width: 25%%; padding-left: 1em;'>subster</td><td>OK</td></tr>
<tr style='background-color: #e7ffbb'><td style='width: 25%%; padding-left: 1em;'>other</td><td>Warning</td></tr>
</table>
</div></div>
</div>
<table id="footer" style="text-align: left; clear:both;" width="100%%"><tr><td><a href="http://tools.wikimedia.de/"><img
src="http://tools.wikimedia.de/images/wikimedia-toolserver-button.png" alt="Toolserver project"></a>
<a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88"></a> <a
href="http://wikimediafoundation.org/wiki/Fundraising?s=cl-Wikipedia-free-mini-button.png"><img src="http://upload.wikimedia.org/wikipedia/meta/6/66/Wikipedia-free-mini-button.png"
alt="Wikipedia...keep it free."></a>
</td></tr></table>
</div>
</body>
</html>
"""
<file_sep># -*- coding: utf-8 -*-
"""
panel-stylesheet 'plain' (module for panel.py)
"""
## @package ps_plain
# @brief panel-stylesheet 'plain'
#
# @copyright Dr. Trigon, 2008-2010
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
#content_type = "Content-Type: text/html"
content_type = "Content-Type: text/html; charset=UTF-8\n"
tsnotice = "<b>%(text)s</b><br>"
# === page HTML codes === === ===
#
_minimal_page = """
<html>
<head>
<title>%(title)s</title>
<meta http-equiv="refresh" content="%(refresh)s">
</head>
<body>
<p><span style="font-family:sans-serif">
%(tsnotice)s
%(title)s<br><br><br>
%(content)s
%(footer)s
</span></p>
</body>
</html>
"""
page = content_type + """
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">""" + _minimal_page
admin_page = content_type + _minimal_page
debug_page = content_type + _minimal_page % { 'title': 'DEBUG PAGE',
'refresh': '',
'tsnotice': '',
'content': '%s',
'footer': '', }
# === footer HTML codes === === ===
#
footer = \
"""<small>DrTrigonBot web-interface, written by <a href="https://wikitech.wikimedia.org/wiki/User:DrTrigon">DrTrigon</a>
(<a href="http://tools.wmflabs.org/drtrigonbot/server-statistics">stat</a>
<a href="http://tools.wmflabs.org/drtrigonbot/server-status">us</a> /
<a href="http://toolserver.org/~daniel/stats/url_201007.html">url</a> /
<a href="http://munin.toolserver.org/index.html">info</a>).
<img src="https://wikitech.wikimedia.org/favicon.ico" border="0"
alt="Wikitech tool-labs"> <a href="http://tools.wmflabs.org/">Powered by Wikimedia Tool-Labs</a>.
<img src="http://de.selfhtml.org/src/favicon.ico" border="0" width="16"
height="16" alt="SELFHTML"> <a href="http://de.selfhtml.org/index.htm">Thanks to SELFHTML</a>.</small>
"""
# with preprocessed (by daniel) statistics from '/mnt/user-store/stats/'
footer_w3c = \
"""<small>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html401-blue"
alt="Valid HTML 4.01 Transitional" height="16" width="44"
border="0"></a>
</small>"""
footer_w3c_css = \
"""<small>
<a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="border:0;width:44px;height:16px"
src="http://jigsaw.w3.org/css-validator/images/vcss-blue"
alt="CSS ist valide!">
</a>
</small>"""
# === functions === === ===
#
# https://wiki.toolserver.org/view/Toolserver_notice
# http://toolserver.org/sitenotice
# http://www.mail-archive.com/<EMAIL>/msg01679.html
def print_tsnotice():
try:
notice = open('/var/www/sitenotice', 'r').read()
if notice:
return tsnotice % { 'text': notice }
except IOError:
pass
return ''
# security
# http://lists.wikimedia.org/pipermail/toolserver-l/2011-September/004403.html
# check url not to point to a local file on the server, e.g. 'file://'
# (same code as used in subster.py)
def secure_url(url):
# check no.1
s1 = False
for item in ['http://', 'https://']:
s1 = s1 or (url[:len(item)] == item)
secure = s1
return secure
# === labs conversion patch: functions === === ===
#
def change_logo(content, environ):
# labs patch: adopt logo for labs server instead of TS (default)
TS = 'http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Wikimedia_Community_Logo-Toolserver.svg/135px-Wikimedia_Community_Logo-Toolserver.svg.png'
labs = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Tool_labs_logo.svg/135px-Tool_labs_logo.svg.png'
if ('HTTP_HOST' in environ) and (not (environ['HTTP_HOST'] == 'toolserver.org')):
content = content.replace(TS, labs)
return content
def host(environ):
if ('HTTP_HOST' in environ) and (not (environ['HTTP_HOST'] == 'toolserver.org')):
return 'labs'
else:
return 'ts'
# === labs conversion patch: variables === === ===
#
from ps_config import *
<file_sep># -*- coding: utf-8 -*-
"""
HOW TO INSTALL DrTrigonBot TO TOOLSERVER AND/OR TOOL-LABS
1.) download and install git (and fabric)
2.) download the fabfile, e.g.:
$ wget https://phabricator.wikimedia.org/diffusion/PWDT/browse/master/fabfile.py
3.) run the fabfile:
$ fab -H localhost install
4.) setup your config files by generating new or copying existing ones
5.) run the finalization:
$ fab -H localhost backup
It will automatically clone the needed repos and setup the server home
directory in order to be able to run DrTrigonBot.
To update the repos on the server run:
$ fab -H localhost update
To backup the config data on the server run:
$ fab -H localhost backup
To get an overview of the available commands run:
$ fab -H localhost help
If you did not install fabric or it is not available because you do not have
permissions, you can use the following syntax alternatively:
$ python fabfile.py -H localhost cmd1[,cmd2,...]
instead of
$ fab -H localhost cmd1[,cmd2,...]
LICENSE - https://wikitech.wikimedia.org/wiki/DrTrigonBot
i) Generally: http://opensource.org/licenses/GPL-3.0
ii) Uses libraries might be licensed different, e.g.: MIT or other ...
(check mw:Manual:Pywikibot/Installation#Dependencies)
DrTrigonBot runs parts of the Pywikibot repertory in order to work on
jobs and own tasks as defined on its wiki pages.
Copyright (C) 2013 DrTrigon (and the Pywikibot team)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Created on Sat Sep 14 18:22:30 2013
@author: drtrigon
"""
# http://yuji.wordpress.com/2011/04/09/django-python-fabric-deployment-script-and-example/
try:
from fabric.api import *
except ImportError:
# setup a simple local replacement, for alternative syntax
import sys, os, subprocess
def local(cmd, capture=False, *args, **kwargs):
print "[%s] local-simple: %s" % (sys.argv[2], cmd)
kwargs = { 'cwd': os.path.dirname(os.path.abspath(__file__)),
'shell': True,}
if capture:
kwargs['stdout'] = subprocess.PIPE
res = subprocess.Popen(cmd, **kwargs)
res.wait()
if res.returncode:
raise IOError('returncode %s' % res.returncode)
return res.stdout.read().strip() if res.stdout else ""
def __host_info():
#run('uname -s')
result = local('uname -a', capture=True)
print result
return result
LABS = ('tools-login' in __host_info())
def _get_git_path(repo, dest, path):
#local('wget --content-disposition https://git.wikimedia.org/zip/?r=pywikibot/bots/drtrigonbot\&p=public_html\&h=HEAD\&format=gz')
local('wget -O temp.tar.gz https://git.wikimedia.org/zip/?r=%s\&p=%s\&h=HEAD\&format=gz' % (repo, path))
local('tar -zxvf temp.tar.gz')
local('rm temp.tar.gz')
# (simpler) alternative to '_clone_git' & '_clean_git'
def _get_git(repo):
#local('wget --content-disposition https://git.wikimedia.org/zip/?r=pywikibot/bots/drtrigonbot\&p=public_html\&h=HEAD\&format=gz')
local('wget -O temp.tar.gz https://git.wikimedia.org/zip/?r=%s\&h=HEAD\&format=gz' % (repo,))
local('tar -zxvf temp.tar.gz')
local('rm temp.tar.gz')
def _clone_git_devel(repo='pywikibot/compat', dest='pywikipedia-git', username='drtrigon'):
local('git clone --recursive ssh://%s@gerrit.<EMAIL>:29418/%s.git %s' % (username, repo, dest))
def _clone_git_user(repo='pywikibot/compat', dest='pywikipedia-git'):
local('git clone --recursive https://gerrit.wikimedia.org/r/%s.git %s' % (repo, dest))
def _clone_git(repo, dest):
_clone_git_user(repo=repo, dest=dest)
def _clone_git_path(repo, dest, paths=[]):
# http://vmiklos.hu/blog/sparse-checkout-example-in-git-1-7
_clone_git_user(repo=repo, dest=dest)
local('cd %s; git config core.sparsecheckout true' % dest)
for item in paths:
local('cd %s; echo %s >> .git/info/sparse-checkout' % (dest, item))
local('cd %s; git read-tree -m -u HEAD' % dest)
def _clean_git(repos=[]):
for path in repos:
local('cd %s; git gc --aggressive --prune' % path)
def _update_git(dest):
#local('cd %s; git checkout master' % (dest,)) # should always be on 'master'
local('cd %s; git pull' % (dest,))
#local('cd %s; git submodule update --force' % (dest,))
def setup():
""" I.1) setup home directory structure """
local('mkdir BAK_DIR')
local('mkdir data')
local('mkdir data/subster')
local('mkdir data/sum_disc')
if LABS: # labs-tools
local('echo \|jmail cat \>\> \~/data/subster/mail_inbox > .forward.subster')
local('mkdir public_html/cgi-bin')
local('mkdir public_html/logs') # contains symlinks
local('mkdir public_html/logs/archive') # target for log archive
local('mkdir public_html/logs/sge') # sge stdout/-err files
else: # toolserver
local('echo \> \~/data/subster/mail_inbox > .forward+subster')
local('mkdir public_html/DrTrigonBot') # contains symlinks
local('mkdir public_html/source')
# create redirect to svn and git repo browser in 'public_html/source'
local('mkdir public_html/test')
local('mkdir public_html/docs') # contains symlinks (like logs)
# permission are set in sl_drtrigonbot()
def dl_drtrigonbot():
# if LABS: # labs-tools
# _get_git_path(repo='pywikibot/bots/drtrigonbot', dest=None, path='public_html/cgi-bin')
# else: # toolserver
# _get_git_path(repo='pywikibot/bots/drtrigonbot', dest=None, path='public_html')
_clone_git_path(repo='pywikibot/bots/drtrigonbot', dest='pywikibot-drtrigonbot/',
paths=['public_html/',
'.description',
'.forward',
#'.forward+subster',
'.lighttpd.conf',
'/README', # exclude 'externals/README'
'fabfile.py',
'warnuserquota.py',
'crontab',
'literature',])
_clean_git(repos=['pywikibot-drtrigonbot/',])
if LABS: # labs-tools
# local('cp -r pywikibot-drtrigonbot/public_html/cgi-bin/* cgi-bin/')
local('ln -s ~/pywikibot-drtrigonbot/public_html/SearchRequest.xml public_html/SearchRequest.xml')
local('ln -s ~/pywikibot-drtrigonbot/public_html/batch.css public_html/batch.css')
local('ln -s ~/pywikibot-drtrigonbot/public_html/jira.webresources:global-static.css public_html/jira.webresources:global-static.css')
else: # toolserver
# local('cp -r pywikibot-drtrigonbot/public_html/* public_html/')
local('ln -s ~/pywikibot-drtrigonbot/public_html/tsnotice.css public_html/tsnotice.css')
local('ln -s ~/pywikibot-drtrigonbot/public_html/cgi-bin/* public_html/cgi-bin/')
local('ln -s ~/pywikibot-drtrigonbot/public_html/index.html public_html/index.html')
def dl_compat():
# https://www.mediawiki.org/wiki/Manual:Pywikipediabot/Installation#Setup_on_Wikimedia_Labs.2FTool_Labs_server
_clone_git(repo='pywikibot/compat', dest='pywikibot-compat')
_clean_git(repos=['pywikibot-compat/i18n/',
'pywikibot-compat/externals/opencv/',
'pywikibot-compat/externals/pycolorname/',
'pywikibot-compat/externals/spelling/',])
# or: _get_git(repo='pywikibot/compat')
def dl_core():
# https://www.mediawiki.org/wiki/Manual:Pywikipediabot/Installation#Setup_on_Wikimedia_Labs.2FTool_Labs_server
_clone_git(repo='pywikibot/core', dest='pywikibot-core')
_clean_git(repos=['pywikibot-core/', # needed?
'pywikibot-core/scripts/i18n/',
'pywikibot-core/externals/httplib2/',])
# or: _get_git(repo='pywikibot/core')
def download():
""" I.2) download (dl) all code """
dl_drtrigonbot()
dl_compat()
dl_core()
def sl_drtrigonbot():
local('ln -s pywikibot-drtrigonbot/README README')
local('ln -s pywikibot-drtrigonbot/.forward .forward')
if LABS: # labs-tools
local('ln -s pywikibot-drtrigonbot/.description .description')
local('ln -s pywikibot-drtrigonbot/.lighttpd.conf .lighttpd.conf')
local('webservice restart') # apply '.lighttpd.conf'
local('ln -s replica.my.cnf .my.cnf') # DB config
local('chmod o+r ~/.forward*') # changes 'pywikibot-drtrigonbot/.forward*'
else: # toolserver
local('ln -s pywikibot-drtrigonbot/warnuserquota.py warnuserquota.py')
#local('ln -s pywikibot-drtrigonbot/.forward+subster .forward+subster')
local('chmod 600 ~/.forward*') # changes 'pywikibot-drtrigonbot/.forward*'
def sl_compat():
if LABS: # labs-tools
# docs
local('ln -s ~/pywikibot-compat/docs public_html/docs/compat')
# logs
# local('cd public_html/logs/; ln -s /data/project/drtrigonbot/pywikibot-compat/logs compat')
local('ln -s ~/pywikibot-compat/logs public_html/logs/compat')
else: # toolserver
local('ln -s ~/pywikibot-compat pywikipedia')
# docs
# local('cd public_html/doc/; ln -s /home/drtrigon/pywikipedia/docs DrTrigonBot')
local('ln -s ~/pywikipedia/docs public_html/doc/DrTrigonBot')
# logs
# local('cd public_html/DrTrigonBot/; ln -s /home/drtrigon/pywikipedia/logs trunk')
local('ln -s ~/pywikipedia/logs public_html/DrTrigonBot/trunk')
def sl_core():
if LABS: # labs-tools
# docs ?
# logs
# local('cd public_html/logs/; ln -s /data/project/drtrigonbot/pywikibot-core/logs core')
local('ln -s ~/pywikibot-core/logs public_html/logs/core')
else: # toolserver
local('ln -s ~/pywikibot-core rewrite')
# docs
# create symlink to core (rewrite) docs here
# logs
# local('cd public_html/DrTrigonBot/; ln -s /home/drtrigon/rewrite/logs rewrite')
local('ln -s ~/rewrite/logs public_html/DrTrigonBot/rewrite')
def symlink():
""" I.3) symlink (sl) all directories and files """
sl_drtrigonbot()
sl_compat()
sl_core()
def install():
""" I.A) Install all bot code to the server (all I.# steps) """
# setup home directory structure
setup()
# download all
download()
# symlink all
symlink()
# replace fabfile.py by a symlink to the one in the repo
# done here at the very end instead of in 'sl_drtrigonbot'
local('rm fabfile.py')
local('ln -s pywikibot-drtrigonbot/fabfile.py fabfile.py')
# setup server config files
print ("\nPlease generate or copy the needed config files now:\n"
"* user-config.py\n"
"* login-data/* and *.lwp\n"
"* data (subster mailbox, sum_disc history)\n"
"* may be others (devel/, public_html/, quota-SunOS.rrd, ...)\n"
"\nThen finish the installation by running:\n"
"$ fab -H localhost backup")
def up_drtrigonbot():
_update_git(dest='pywikibot-drtrigonbot/')
# if LABS: # labs-tools
# local('cp -r pywikibot-drtrigonbot/public_html/cgi-bin/* cgi-bin/')
# else: # toolserver
# local('cp -r pywikibot-drtrigonbot/public_html/* public_html/')
def up_compat():
_update_git(dest='pywikibot-compat')
def up_core():
_update_git(dest='pywikibot-core')
def update():
""" U.A) Update (up) all code on the server (all U.# steps) """
up_drtrigonbot()
up_compat()
up_core()
def backup():
""" B.A) Backup all bot code on the server (all B.# steps) """
# http://artymiak.com/quick-backups-with-fabric-and-python/
#
# See 'backup' sh script:
# Do a backup of sensitive and important data and since that data
# are private they have to be protected also.
# * run backup: Backup all important user and config data from
# 'pywikipedia/' to 'BAK_DIR/'.
# * set file permissions: I noticed many people using the framework haven't
# set the correct access flags to their "login-data" dir. This could lead
# to someone using those files to run your bot accounts. Although only
# other toolserver users can see these files, its still an issue. Please
# make at least that dir "not readable" for anyone but "owner". --Pyr0.
# init backup (trash old one)
print "init/reset backup"
local('rm -rf ~/BAK_DIR/')
local('mkdir ~/BAK_DIR')
local('mkdir ~/BAK_DIR/compat')
local('mkdir ~/BAK_DIR/core')
# backup and protect 'login-data' on productive
print "processing 'login-data':"
print " * backup"
if LABS: # labs-tools
local('cp -a ~/pywikibot-compat/login-data/ ~/BAK_DIR/compat/')
local('cp -a ~/pywikibot-core/*.lwp ~/BAK_DIR/core/')
else:
local('cp -a ~/pywikipedia/login-data/ ~/BAK_DIR/compat/')
local('cp -a ~/rewrite/*.lwp ~/BAK_DIR/core/')
print " * protect"
if LABS: # labs-tools
local('chmod -R go-rwx ~/pywikibot-compat/login-data')
local('chmod go-rwx ~/pywikibot-core/*.lwp')
else:
local('chmod -R go-rwx ~/pywikipedia/login-data')
local('chmod go-rwx ~/rewrite/*.lwp')
# backup and protect 'user-config.py' on productive
print "processing 'user-config.py':"
print " * backup"
if LABS: # labs-tools
local('cp -a ~/pywikibot-compat/user-config.py ~/BAK_DIR/compat/')
local('cp -a ~/pywikibot-core/user-config.py ~/BAK_DIR/core/')
else:
local('cp -a ~/pywikipedia/user-config.py ~/BAK_DIR/compat/')
local('cp -a ~/rewrite/user-config.py ~/BAK_DIR/core/')
print " * protect"
if LABS: # labs-tools
local('chmod go-rwx ~/pywikibot-compat/user-config.py')
local('chmod go-rwx ~/pywikibot-core/user-config.py')
else:
local('chmod go-rwx ~/pywikipedia/user-config.py')
local('chmod go-rwx ~/rewrite/user-config.py')
# backup and protect 'data' on productive
print "processing 'data':"
print " * backup"
local('cp -a ~/data/ ~/BAK_DIR/')
print " * protect"
local('chmod -R go-rwx ~/data')
# compress and backup 'logs' on productive
print "processing 'logs':"
print " * compress and backup"
if LABS: # labs-tools
local('tar -jcvf ~/BAK_DIR/DrTrigonBot_logs.tar.bz2 ~/public_html/*/*')
else:
local('tar -jcvf ~/BAK_DIR/DrTrigonBot_logs.tar.bz2 ~/public_html/DrTrigonBot/*/*')
# finally protect backup as well
print "protect backup"
local('chmod -R go-rwx ~/BAK_DIR')
def list_large_files():
""" L.A) List all files exceeding 5 and 10MB (all L.# steps) """
# List all files exceeding an size of 10MB. Use this to find e.g.
# core dump files.
# list files >5MB
print "files larger than 5MB"
local("""find . -type f -size +5000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'""")
print
# list files >10MB
print "files larger than 10MB"
local("""find . -type f -size +10000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'""")
print
def archive_logs():
""" A.A) Archive all log files on the server (all A.# steps) """
# how does this scheme/system interact with backup?
# https://wikitech.wikimedia.org/wiki/Nova_Resource:Tools/Help#Backups
# http://serverlinux.blogspot.ch/2006/08/simple-rotation-backup-with-tar.html
# fecha has a formated date
import time
#fecha=`date +"%d-%m-%Y"`
fecha = time.strftime("%Y-%m-%d").decode('utf8')
# Backup and gzip the directory
#tar zcvf /backups/trunk-$fecha.tgz /var/www/repository
local('tar zcvfh ~/public_html/logs/archive/logs-%s.tgz ~/public_html/logs --exclude=public_html/logs/archive' % fecha)
# Rotate the logs, delete older than 7 days
#find /backups/ -mtime +7 -exec rm {} \;
local('find ~/public_html/logs/archive/ -mtime +200 -exec rm {} \;')
local('find -L ~/public_html/logs/*/*.log.* -mtime +40 -exec rm {} \;')
# "Rotate" (delete old) sge stdout/-err files (they are NOT archived)
local('find ~/public_html/logs/sge/ -mtime +40 -exec rm {} \;')
# Remove all but the last 1000 lines from web access log (NOT archived)
local('tail -n -1000 ~/access.log > ~/access.log')
# Remove all but the last 1000 lines from web error log (NOT archived)
local('tail -n -1000 ~/error.log > ~/error.log')
if (__name__ == '__main__') and ('sys' in locals()):
if sys.argv[3] in locals():
locals()[sys.argv[3]]()
else:
print dir()
<file_sep># -*- coding: utf-8 -*-
"""
panel-stylesheet 'simple' (module for panel.py)
"""
## @package ps_simple
# @brief panel-stylesheet 'simple'
#
# @copyright Dr. Trigon, 2008-2010
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
from ps_plain import *
tsnotice = """<div class="tsnotice" id="tsnotice">%(text)s</div>"""
page = content_type + """
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>%(title)s</title>
<!-- Idea to use Sphinx stylesheet from: http://toolserver.org/~pywikipedia/nightly/
and http://toolserver.org/~valhallasw/.style/main.css -->
<link rel="stylesheet" href="http://sphinx.pocoo.org/_static/default.css">
<link rel="stylesheet" href="http://sphinx.pocoo.org/_static/pygments.css">
<link rel="stylesheet" href="../tsnotice.css">
<meta http-equiv="refresh" content="%(refresh)s">
</head>
<body>
%(tsnotice)s
<div class="body">
<h1>%(title)s</h1>
%(content)s
%(footer)s
</div>
</body>
</html>
"""
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""filter: Versatile/Generic (text) Page Filter Tool (CGI) for toolserver
(description)
to make it usable from server, use: 'chmod 755 filter.py', which results in
'-rwxr-xr-x 1 drtrigon users 447 2009-04-16 19:13 test.py'
"""
## @package filter.py
# @brief filter: Versatile/Generic (text) Page Filter Tool (CGI) for toolserver
#
# @copyright <NAME>, 2012
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# *other options additional to 'unshort' can an may be should
# be implemented...
# *PROBLEMS with 'Content-Type ... utf-8' ... !!!!
# === python CGI script === === ===
#
import cgitb # debug
cgitb.enable() #
import cgi
# === module imports === === ===
#
# === panel HTML stylesheets === === ===
# MAY BE USING Cheetah (http://www.cheetahtemplate.org/) WOULD BE BETTER (or needed at any point...)
#
import ps_plain as style # panel-stylesheet 'plain'
# === page HTML contents === === ===
#
default_content = \
"""<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>filter: Versatile/Generic (text) Page Filter Tool</title>
</head>
<body>
<h3>filter: Versatile/Generic (text) Page Filter Tool</h3>
<p>%(footer)s</p>
<form action="filter.py" name="">
<table>
<tr>
<td>url:</td>
<td><input name="url" type="text" size="60" maxlength="200" value="%(url)s"></td>
<td>(e.g. "http://blog.wikimedia.de/feed/")</td>
</tr>
<tr>
<td>unshorten urls:</td>
<td><input type="checkbox" name="unshort" value="1" %(unshort)s></td>
<td>(this is VERY slow - be patient)</td>
</tr>
</table>
<input type="submit" value=" OK ">
</form>
</body>
</html>"""
# === CGI/HTML page view user interfaces === === ===
#
# === Main procedure entry point === === ===
#
form = cgi.FieldStorage()
# operational mode
param = { 'url': form.getvalue('url', ''),
'unshort': form.getvalue('unshort', ''),
}
url = param['url']
secure = style.secure_url(url) # security
content_type = style.content_type
if secure and url:
import urllib, re, BeautifulSoup, time
# external unshortener API from ...
#unshort = "http://realurl.org/api/v1/getrealurl.php?url=%s"
#unshort = "http://www.unshorten.it/api1.0.php?responseFormat=xml&shortURL=%s" # needs API-key (free) now
unshort = "http://api.unshort.me/?t=xml&r=%s"
skip_list = ['://identi.ca',
'.wikimedia.org',
'://wikimediafoundation.org',
]
info = []
tot_tic = time.time()
# http://docs.python.org/library/urllib.html
# http://docs.python.org/library/mimetools.html#mimetools.Message
#url = urllib.unquote(url)
f = urllib.urlopen(url)
page_buf = f.read()
page_info = f.info()
#print page_buf
# prevent '502 bad gateway' errors
# content_type = '; '.join(['Content-Type: %s' % page_info.gettype()] + page_info.getplist())
content_type = "Content-Type: text/html;\n"
toc = time.time()
info += [ 'Page served by %s in %.3f secs.' % (url.split('/')[2], toc-tot_tic) ]
if param['unshort']:
tic = time.time()
r = re.compile(r'(http(s?)://[^ "<\']+)')
url_list = r.findall(page_buf)
for (url, other) in set(url_list):
skip = False
for skip_url in skip_list:
if skip_url in url:
skip = True
break
if skip: continue
unshort_buf = urllib.urlopen(unshort % url).read()
bs = BeautifulSoup.BeautifulSoup(unshort_buf)
#if (bs.status.contents[0] == "1"):
# longurl = str(bs.real.contents[0])
if not bs.findAll('error'):
# longurl = str(bs.fullurl.contents[0])
#if (bs.success.contents[0] == "true"):
longurl = str(bs.resolvedurl.contents[0])
page_buf = page_buf.replace(url, longurl)
toc = time.time()
info += [ 'UnShortened by %s in %.3f secs.' % (unshort.split('/')[2], toc-tic) ]
tot_toc = time.time()
info = [ 'Served by toolserver.org in %.3f secs.' % (tot_toc-tot_tic) ] + info
#page_buf += '\n<!-- %s -->' % '\n'.join(info)
page_buf += '\n<!-- \n%s\n -->' % '\n'.join(info)
else:
sel_dict = {'': '', '1': 'checked'}
# disable XSS cross site scripting (code injection vulnerability)
# http://amix.dk/blog/post/19432
url = cgi.escape(url, quote=True)
param.update({'footer': style.footer + style.footer_w3c, 'unshort': sel_dict[param['unshort']], 'url': url})
page_buf = default_content % param
# send page to browser/receiver
print content_type
print page_buf
<file_sep># -*- coding: utf-8 -*-
"""
panel-stylesheet 'wiki (new)' (module for panel.py)
"""
## @package ps_wikinew
# @brief panel-stylesheet 'wiki (new)'
#
# @copyright Dr. Trigon, 2008-2010
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
from ps_plain import *
tsnotice = """<div id="tsnotice">%(text)s</div><br>"""
page = content_type + """
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>%(title)s</title>
<link rel="copyright" href="//creativecommons.org/licenses/by-sa/3.0/" >
<!-- Idea to use Wiki stylesheet from: http://toolserver.org/~vvv/sulutil.php
BUT this is the new!! (done by myself) -->
<!--<link rel="stylesheet" href="//meta.wikimedia.org/de.wikipedia.org/load.php?debug=false&lang=de&modules=ext%%21wikihiero%%7Cmediawiki%%21legacy%%21commonPrint%%7Cmediawiki%%21legacy%%21shared%%7Cskins%%21vector&only=styles&skin=vector" type="text/css" media="all">-->
<!--<link rel="stylesheet" href="//meta.wikimedia.org/de.wikipedia.org/load.php?debug=false&lang=de&modules=ext.gadget.CommonsDirekt%%2CExtra-Editbuttons%%2CVorlagenmeister%%2Cold-movepage%%7Cext.rtlcite%%2Cwikihiero%%7Cext.uls.nojs%%7Cext.visualEditor.viewPageTarget.noscript%%7Cmediawiki.legacy.commonPrint%%2Cshared%%7Cmw.PopUpMediaTransform%%7Cskins.vector&only=styles&skin=vector&*" >-->
<link rel="stylesheet" href="//meta.wikimedia.org/de.wikipedia.org/load.php?debug=false&lang=de&modules=ext.echo.badge%%7Cext.gadget.CommonsDirekt%%2CExtra-Editbuttons%%2CVorlagenmeister%%2Cold-movepage%%7Cext.visualEditor.viewPageTarget.noscript%%7Cext.wikihiero%%7Cmediawiki.legacy.commonPrint%%2Cshared%%7Cskins.common.interface%%7Cskins.vector.styles&only=styles&skin=vector&*" >
<link rel="stylesheet" href="../tsnotice.css">
<meta http-equiv="refresh" content="%(refresh)s">
</head>
<body class="mediawiki">
<div id="mw-page-base" class="noprint"></div><div id="mw-head-base" class="noprint"></div><div id="content">
%(tsnotice)s
<h1 id="firstHeading" class="firstHeading">%(title)s</h1>
<div id="bodyContent">
%(content)s
%(footer)s
</div></div>
<div id="mw-panel" class="noprint">
<div id="p-logo"><a style="background-image:
url(http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Wikimedia_Community_Logo-Toolserver.svg/135px-Wikimedia_Community_Logo-Toolserver.svg.png);"
href="/" title="Home"></a></div>
<div class="portal" id='p-navigation'><h5>navigation</h5><div class="body">
<ul>
<li><a href="https://wiki.toolserver.org/view/User:DrTrigon">TS</a> / <a href="https://labsconsole.wikimedia.org/wiki/DrTrigonBot">labs</a> Main Page</li>
<li><a href="https://bugzilla.wikimedia.org/describecomponents.cgi?product=Tool%%20Labs%%20tools">Bugzilla</a> tracker</li>
<li><a href="https://fisheye.toolserver.org/browse/drtrigon">SVN</a> / <a href="https://gerrit.wikimedia.org/r/#/admin/projects/?filter=pywikibot">GIT</a> repository</li>
<li><a href="info.py">Info</a></li>
</ul>
</div></div>
<div class="portal" id='p-status'><h5>status</h5><div class="body">
<table style="border-collapse: collapse; font-size: 11pt;">
%(p-status)s
</table>
</div></div>
</div>
<div id="footer">
<ul id="footer-places">
<li><!--<a href="/wiki/Wikipedia:Datenschutz">...</a>--></li>
</ul>
<ul id="footer-icons" class="noprint">
<li><a href="http://www.mediawiki.org/"><img src="http://meta.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png" height="31" width="88" alt="Powered by MediaWiki"
></a></li>
<li><a href="http://wikimediafoundation.org/"><img src="http://de.wikipedia.org/images/wikimedia-button.png" width="88" height="31" alt="Wikimedia Foundation"></a></li>
<li><a href="http://tools.wmflabs.org/"><img src="https://upload.wikimedia.org/wikipedia/commons/4/46/Powered_by_labs_button.png" alt="Tool-Labs project"></a></li>
<!--<li><a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88"></a></li>
<li><a href="http://wikimediafoundation.org/wiki/Fundraising?s=cl-Wikipedia-free-mini-button.png"><img
src="http://upload.wikimedia.org/wikipedia/meta/6/66/Wikipedia-free-mini-button.png" alt="Wikipedia...keep it free."></a></li>-->
</ul>
</div>
</body>
</html>
"""
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Info: Simple DrTrigonBot Information Tool
Built on Simple and Lightweight Framework which is just a combination of
flask and cgi.
to make it usable from server, use: 'chmod 755 info.py', which results in
'-rwxr-xr-x 1 drtrigon users 447 2009-04-16 19:13 info.py' or even better
install it through fabfile.
"""
# http://www.gpcom.de/support/python
## @package info.py
# @brief Info: Simple DrTrigonBot Information Tool
#
# @copyright <NAME>, 2014
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# === python flask CGI script (with Cheetah support) === === ===
#
import cgitb # debug
cgitb.enable() #
#import cgi
# https://flask.readthedocs.org/en/0.1/api/
from flask import Flask, render_template, render_template_string, Response, request
#from flask import abort
## http://stackoverflow.com/questions/8365244/cheetah-templating-with-flask
#from Cheetah.Template import Template
#
#def render_cheetah(template, context):
# """Helper function to make template rendering less painful."""
# return str(Template(template, namespaces=[context]))
# (default imports)
#
import sys, os, subprocess
# === templates and style (more in ./templates/) === === ===
#
#from ps_plain import content_type # (style-sheet old style cgi code)
contentTemplate = "Content-Type: %s; charset=%s\n\n%s"
## (Cheetah template)
#mainTemplate = """
#<html>
# <head><title>$title</title></head>
# <body><h1>$title</h1></body>
#</html>"""
## (flask/Jinja2 template)
#mainTemplate = """
#<!doctype html>
#<title>Flaskr</title>
#<!--<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">-->
#<div class=page>
# <h1>Flaskr</h1>
#<!-- {% for message in get_flashed_messages() %} -->
#<!-- <div class=flash>{{ message }}</div> -->
#<!-- {% endfor %} -->
# <div class=test>{{ test }}</div>
# {% block body %}{% endblock %}
#</div>"""
# === flask/cgi web app source code === === ===
#
# create our little application :)
app = Flask(__name__)
# Load default config and override config from an environment variable
#app.debug = True
app.config.update(dict(
DEBUG=True,
SERVER_NAME=os.getenv("SERVER_NAME"),
APPLICATION_ROOT=os.path.dirname(os.getenv("SCRIPT_URL").split('.py/')[0]),
))
#app.config.from_envvar('FLASKR_SETTINGS', silent=True)
# (constants)
viewfunc = os.path.basename(__file__)
def info_arch():
import ps_plain as style # check arch (ts, or labs)
info = style.host(os.environ) # (temporary patch)
desc = subprocess.Popen('uname -a',
shell=True,
stdout=subprocess.PIPE).stdout.read()
return {'info': info, 'desc': desc.strip()}
def info_flask():
import flask
return {'info': '', 'desc': 'Version %s' % flask.__version__}
def info_compat():
import ps_plain as style
return {'hsh': open(os.path.join(style.bot_path[style.host(os.environ)][0],
'.git/refs/heads/master')).read().strip()}
def info_core():
import ps_plain as style
return {'hsh': open(os.path.join(style.bot_path[style.host(os.environ)][1],
'.git/refs/heads/master')).read().strip()}
def info_drtrigonbot():
import ps_plain as style
return {'hsh': open(os.path.join(style.bot_path[style.host(os.environ)][0],
'../pywikibot-drtrigonbot',
'.git/refs/heads/master')).read().strip()}
<EMAIL>.route('/')
# http://flask.pocoo.org/snippets/57/
<EMAIL>('/' + viewfunc, defaults={'action': ''})
<EMAIL>.route('/' + viewfunc + '/<action>')
#def main_route(action):
@app.route('/' + viewfunc)
def main_route():
# http://stackoverflow.com/questions/10434599/how-to-get-whole-request-post-body-in-python-flask
raw = request.args['raw'] if 'raw' in request.args else None
#return render_template_string(mainTemplate, test=viewfunc+'/abc/'+a)
#return render_cheetah(mainTemplate, {'title': 'Welcome to "/"!'})
#return render_template('info.html', title='Info',
res = render_template('info.html', title = 'DrTrigonBot info panel',
refresh = '',
tsnotice = '',
footer = ['default', 'w3c'],# 'css'],
p_status = '',
arch = info_arch(),
flask = info_flask(),
compat = info_compat(),
core = info_core(),
drtrigonbot = info_drtrigonbot(),)
return res if not raw else Response(res, mimetype='text/plain')
#<EMAIL>.route('/about')
@app.route('/' + viewfunc + '/about')
def action_about():
return render_template('info.html', title = 'DrTrigonBot info panel',
footer = ['default', 'w3c'],# 'css'],
arch = info_arch(),
flask = info_flask(),)
##<EMAIL>('/<action>')
#@app.route('/' + viewfunc + '/<action>')
#def action_unknown(action):
# abort(404) # 404 Not Found
# #return render_template('info.html', error='404 Not Found')
# === Main procedure entry point === === ===
#
if __name__ == '__main__':
if '--stand-alone' in sys.argv:
# start flask server
app.run()
else:
# run as cgi script trough test_client
#form = cgi.FieldStorage()
#action = form.getvalue('action', 'main_route')
#print locals()[action](form)
# http://flask.pocoo.org/docs/testing/#faking-resources-and-context
# http://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python
with app.test_client() as c:
resp = c.get('/%s%s?%s' % (viewfunc, os.getenv("PATH_INFO", ''), os.getenv("QUERY_STRING")))
print contentTemplate % (resp.mimetype, resp.charset, resp.data)
# raise BaseException(contentTemplate % (resp.mimetype, resp.charset, resp.data))
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""DrTrigon Bot status panel (CGI) for toolserver
to make it usable from server, use: 'chmod 755 panel.py', which results in
'-rwxr-xr-x 1 drtrigon users 447 2009-04-16 19:13 test.py'
"""
# http://www.gpcom.de/support/python
## @package subster_mail_queue.py
# @brief DrTrigonBot subster mail queue
#
# @copyright <NAME>, 2011
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# === python CGI script === === ===
#
import cgitb # debug
cgitb.enable() #
import cgi
# === module imports === === ===
#
# http://www.ibm.com/developerworks/aix/library/au-python/
import os
import mailbox
# === panel HTML stylesheets === === ===
# MAY BE USING Cheetah (http://www.cheetahtemplate.org/) WOULD BE BETTER (or needed at any point...)
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
bot_path = os.path.realpath(style.bot_path[style.host(os.environ)][0])
# === page HTML contents === === ===
#
displaystate_content = \
"""<br>%(oldlog)s<br>"""
a = """<tr>
<td>%i</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>"""
b = "<a href='subster_mail_queue.py?action=content&no=%s'>%s</a>"
# === functions === === ===
#
# === CGI/HTML page view user interfaces === === ===
#
def displaystate(form):
data = {}
mbox = mailbox.mbox(os.path.join(bot_path, '../data/subster/mail_inbox'))
buf = []
buf.append( '\n<table>' )
buf.append(
"""<tr>
<th>%s</th>
<th>%s</th>
<th>%s</th>
<th>%s</th>
</tr>""" % ('no.', 'sender', 'subject', 'timestmp') )
for i, message in enumerate(mbox):
sender = message['from'] # Could possibly be None.
subject = message['subject'] # Could possibly be None.
timestmp = message['date'] # Could possibly be None.
if sender:
# data found
buf.append( a % (i, (b % (i, cgi.escape(sender))), subject, timestmp) )
buf.append( '</table>\n\n' )
data.update({ 'oldlog': "\n".join(buf),
'refresh': '',
'title': 'DrTrigonBot subster mail queue',
'tsnotice': style.print_tsnotice(),
'p-status': "<tr><td><td></tr>",
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = displaystate_content % data
return style.page % data
def content(form):
data = {}
no = int(form.getvalue('no', '-1'))
if no < 0: return displaystate(form)
mbox = mailbox.mbox('../../data/subster/mail_inbox')
buf = []
for i, message in enumerate(mbox):
if (i != no): continue
text = cgi.escape(message.as_string(True))
text = text.replace("\n", "<br>\n")
buf.append( text )
buf.append( '\n' )
data.update({ 'oldlog': "\n".join(buf),
'refresh': '',
'title': 'DrTrigonBot subster mail queue',
'tsnotice': style.print_tsnotice(),
'p-status': "<tr><td><td></tr>",
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
})
data['content'] = displaystate_content % data
return style.page % data
# === Main procedure entry point === === ===
#
form = cgi.FieldStorage()
# operational mode
action = form.getvalue('action', 'displaystate')
print style.change_logo(locals()[action](form), os.environ) # labs patch
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""DrTrigonBot category discussion summary (CGI) for toolserver
(for mor info look at 'panel.py' also!)
"""
## @package sum_cat_disc.py
# @brief DrTrigonBot category discussion summary (CGI) for toolserver
#
# @copyright <NAME>, 2008-2011
#
# @todo better/faster SQL query
# @todo prevent DOS calls
# @todo redirects? others...?
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__='$Id$'
#
# debug
import cgitb
cgitb.enable()
import cgi
from time import *
# http://www.ibm.com/developerworks/aix/library/au-python/
import datetime
import os, re, sys
import locale
import ConfigParser
import MySQLdb, _mysql_exceptions
# === panel HTML stylesheets === === ===
#
#import ps_plain as style # panel-stylesheet 'plain'
#import ps_simple as style # panel-stylesheet 'simple'
#import ps_wiki as style # panel-stylesheet 'wiki (monobook)'
import ps_wikinew as style # panel-stylesheet 'wiki (new)' not CSS 2.1 compilant
bot_path = os.path.realpath(style.bot_path[style.host(os.environ)][0])
db_conf = style.db_conf[style.host(os.environ)]
# === pywikibot framework === === ===
#
sys.path.append( bot_path ) # bot import form other path (!)
import query #
import wikipedia as pywikibot #
import pagegenerators, catlib
#import wikipedia as pywikibot # for 'Timestamp'
import family
# may be best would be to get namespace info from DB?!
# === page HTML contents === === ===
#
displaystate_content = \
"""<br>
<form action="sum_cat_disc.py">
<table>
<tr>
<td>wiki:</td>
<td><input name="wiki" value="%(wiki)s"></td>
</tr>
<tr>
<td>Category:</td>
<td><input name="cat" value="%(cat)s"></td>
</tr>
<tr>
<td>Start:</td>
<td><input name="start" value="%(start)s"></td>
</tr>
<tr>
<td>Period:</td>
<td><input name="period" value="%(period)s"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value=" Check ">
<input type="reset" value=" Reset "></td>
</tr>
</table>
</form><br>
<hr><br>
%(output)s"""
# === SQL query contents === === ===
#
# http://www.mediawiki.org/wiki/Manual:Database_layout
# http://en.wikipedia.org/wiki/Wikipedia:Namespace
# http://sql.1keydata.com/de/sql-like.php
# https://wiki.toolserver.org/view/Queries#Pages_in_a_specific_category_using_a_specific_template
_SQL_query_ns_content = \
"""SELECT page_title, page_namespace
FROM page
JOIN categorylinks ON cl_from = page_id WHERE cl_to = %s
LIMIT %s"""
#_SQL_query_page_info = \
#"""SELECT page_title, page_namespace, page_touched
#FROM page
#WHERE page_title LIKE "%s"
#AND page_namespace IN %s
#LIMIT %s"""
_SQL_query_page_info = \
"""SELECT page_title, page_namespace, page_touched
FROM page
WHERE page_title LIKE %s
AND page_namespace = %s
LIMIT %s"""
#_SQL_query__ = \
#"""SELECT page_title, page_namespace, page_touched
#FROM page
#WHERE page_title IN
#(SELECT page_title
#FROM page
#JOIN categorylinks ON cl_from = page_id WHERE cl_to = "%s")
#AND page_namespace IN (1, 3, 5, 9, 11, 13, 15, 91, 93, 101, 109)
#LIMIT %s"""
# written by Merlissimo (merl) - Thanks a lot!
# http://kpaste.net/da2d, http://kpaste.net/5b2f97f
# ~/devel/experimental/diskchanges.sql
# need db write access; to create temporary tables (they live until the db connection
# gets closed) and is thus not possible during e.g. 'schema changes in progress'
# -----------------------------------------------------------------------------
# drtrigon@nightshade:~$ mysql -hdewiki-p.userdb u_drtrigon
# ERROR 1049 (42000): Unknown database 'u_drtrigon'
# drtrigon@nightshade:~$ mysql -hdewiki-p.userdb
# Welcome to the MySQL monitor. Commands end with ; or \g.
# Your MySQL connection id is 22197636
# Server version: 5.1.53 Source distribution
#
# Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
# This software comes with ABSOLUTELY NO WARRANTY. This is free software,
# and you are welcome to modify and redistribute it under the GPL v2 license
#
# Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#
# mysql> CREATE DATABASE IF NOT EXISTS u_drtrigon
# -> ;
# Query OK, 1 row affected (0.02 sec)
# -----------------------------------------------------------------------------
_SQL_query_cattree = [
"""CREATE TEMPORARY TABLE cattemp (catname VARCHAR(255) PRIMARY KEY);""",
"""CREATE TEMPORARY TABLE cat (catname VARCHAR(255) PRIMARY KEY, depth INT, INDEX(depth));""",
"""INSERT IGNORE INTO cat (catname, depth) SELECT page_title, 0 FROM %swiki_p.page WHERE page_namespace=14 AND page_title=%s;""",
"""DELETE FROM cattemp""",
"""INSERT IGNORE INTO cattemp (catname) SELECT catname FROM cat WHERE depth=%s""",
"""INSERT IGNORE INTO cat (catname, depth) SELECT page_title, %s FROM cattemp INNER JOIN %swiki_p.categorylinks ON catname=cl_to INNER JOIN %swiki_p.page ON cl_from = page_id WHERE page_namespace=14""",
"""SELECT ROW_COUNT()""",
"""SELECT rc_namespace, rc_title, rc_user_text, rc_timestamp, rc_comment
FROM cat
INNER JOIN %swiki_p.categorylinks ON catname = cl_to
INNER JOIN %swiki_p.page p1 ON cl_from = page_id
INNER JOIN %swiki_p.page p2 ON p1.page_title = p2.page_title AND p1.page_namespace+1=p2.page_namespace
INNER JOIN %swiki_p.recentchanges ON p2.page_id = rc_cur_id
WHERE p1.page_namespace IN (0,10,14)
AND rc_timestamp >= DATE_SUB(CURDATE(),INTERVAL %s HOUR)
AND rc_old_len < rc_new_len
ORDER BY rc_timestamp DESC;""",
"""SELECT VERSION();""", ]
_SQL_query_wiki_info = {
'ts': # https://wiki.toolserver.org/view/Database_access#wiki
"""SELECT
lang,
CONCAT("sql-s", server) AS dbserver,
dbname,
CONCAT("//", DOMAIN, script_path, "api.php") AS url
FROM toolserver.wiki
WHERE family = "wikipedia"
ORDER BY SIZE DESC LIMIT %s;""",
'labs': # https://wikitech.wikimedia.org/wiki/Nova_Resource:Tools/Help#Metadata_database
"""SELECT
lang,
slice,
dbname,
url
FROM meta_p.wiki
WHERE family = "wikipedia"
ORDER BY SIZE DESC LIMIT %s;""", }
_SQL_query_wiki_info = _SQL_query_wiki_info[style.host(os.environ)]
_SQL_create_database = \
"""CREATE DATABASE IF NOT EXISTS %s"""
# === variables === === ===
#
SQL_LIMIT_max = 1000
wikitime = "%Y%m%d%H%M%S"
asctime_fmt = "%a %b %d %H:%M:%S %Y"
cnf_file = os.path.join(bot_path, "../.my.cnf")
config = ConfigParser.RawConfigParser()
config.read(cnf_file)
user_name = config.get('client', 'user').replace("'", "")
db_name = db_conf[0] % {'user': user_name, 'dbname': 'u_%s' % user_name}
# === code === === ===
#
def call_db(query, args=(), limit=SQL_LIMIT_max):
#db.query(query % args)
# execute SQL query using execute() method.
# for strings " or ' has to be omitted, execute inserts them as well
cursor.execute(query, args)
def read_db(query, args=(), limit=SQL_LIMIT_max):
call_db(query, args, limit=limit)
#return db.store_result().fetch_row(limit)
return cursor.fetchmany(limit)
# recursive
def get_cat_tree_rec(cat, limit=SQL_LIMIT_max):
res = set([])
for row in read_db(_SQL_query_ns_content, (cat.replace(' ', '_'), limit)):
# Category
if int(row[1]) == 14:
res = res.union( get_cat_tree_rec(row[0], limit) )
continue
# Page
res.add( row )
return res
# iterative (heavily SQL based)
def checkRecentEdits_db_it(cat, end, period, limit=SQL_LIMIT_max):
res = set([])
# db.query(("\n".join(_SQL_query_01)) % cat.replace(' ', '_'))
c=cursor
call_db(_SQL_query_cattree[0])
call_db(_SQL_query_cattree[1])
#call_db(_SQL_query_cattree[2], (cat.replace(' ', '_'),))
_SQL_query = _SQL_query_cattree[2] % (wiki, '%s') # BAD: SQL injection!
call_db(_SQL_query, (cat.replace(' ', '_'),)) #
# uu = read_db(_SQL_query_cattree[8], limit=limit)
# res.append( uu )
# return res
_SQL_query = _SQL_query_cattree[5] % ('%s', wiki, wiki) # BAD: SQL injection!
for i in range(25):
call_db(_SQL_query_cattree[3])
call_db(_SQL_query_cattree[4], (i,))
#call_db(_SQL_query_cattree[5], (i+1,))
call_db(_SQL_query, (i+1,)) # BAD: SQL injection!
co = read_db(_SQL_query_cattree[6], limit=limit)
if (co[0][0] == 0): break
unique = {}
_SQL_query = _SQL_query_cattree[7] % (wiki, wiki, wiki, wiki, '%s') # BAD: SQL injection!
for page in list(read_db(_SQL_query, (period,), limit=limit)): #
u = page[:2] # make list items unique, BUT YOU HAVE TO TAKE THE NEWEST ONE!!!
date = long(page[3])
if date > unique.get(u, end):
res.add( ((page[1], page[0], page[3], page[2], page[4]),) )
unique[u] = date
return res
def checkRecentEdits_db_rec(cat, end, limit=SQL_LIMIT_max):
res = []
for row in list(get_cat_tree_rec(cat, limit)):
ns = row[1]
ns = ns + (1 - (ns % 2)) # next bigger odd
try:
subrow = read_db(_SQL_query_page_info, (row[0], ns, 1))
if subrow and (long(subrow[0][2]) >= end):
res.append( subrow )
except _mysql_exceptions.ProgrammingError: # are displayed later with '(!)' mark
res.append( [(row[0], ns, '')] )
return res
def checkRecentEdits_API(cat, end):
# cat = catlib.Category(site, "%s:%s" % (site.namespace(14), u'Baden-Württemberg'))
cat = catlib.Category(site, "%s:%s" % (site.namespace(14), u'Portal:Hund'))
res = []
for page in pagegenerators.CategorizedPageGenerator(cat, recurse=True):
if not page.isTalkPage():
page = page.toggleTalkPage()
title = '?'
change = '?'
try:
title = page.title()
change = page.getVersionHistory(revCount=1)[0][1]
except pywikibot.exceptions.NoPage:
continue
except:
pass
res.append( (title, change) )
return res
def get_wikiinfo_db(wiki, limit=SQL_LIMIT_max):
for item in read_db(_SQL_query_wiki_info, (limit,), limit):
if item[0] == wiki:
return item
return None
def displayhtmlpage(form):
cat = form.getvalue('cat', '')
# start = form.getvalue('start', datetime.datetime.utcnow().strftime(wikitime))
start = form.getvalue('start', pywikibot.Timestamp.utcnow().strftime(wikitime))
period = form.getvalue('period', '24')
lang = locale.locale_alias.get(wiki, locale.locale_alias['en']).split('.')[0]
try:
locale.setlocale(locale.LC_TIME, lang + '.utf8')
except locale.Error:
locale.setlocale(locale.LC_TIME, lang)
#scheme = {'NO': 'http', 'YES': 'https'}[os.environ.get('HTTP_X_TS_SSL', 'NO')]
s = datetime.datetime.strptime(start, wikitime)
p = datetime.timedelta(hours=int(period))
end = s - p
data = {'output': ''}
data['output'] += "<b>Start</b>: %s (%s)<br>\n" % (start, strftime(asctime_fmt, strptime(start, wikitime)))
data['output'] += "<b>End</b>: %s (%s)<br>\n" % (end.strftime(wikitime), end.strftime(asctime_fmt))
data['output'] += "<b>Period</b>: %sh<br>\n" % period
end = long( end.strftime(wikitime) )
data['output'] += "<br>\n"
# talk_ns = (1, 3, 5, 9, 11, 13, 15, 91, 93, 101, 109)
# res += str( read_db(_SQL_query_page_info, ('%DrTrigon',str(talk_ns),10)) )
# res += str( read_db(_SQL_query_02, (cat,)) )
# res += "<br>\n"
if cat:
tic = time()
#out = checkRecentEdits_API(cat, end)
#out = checkRecentEdits_db_rec(cat, end) # uses 'page_touched'
out = checkRecentEdits_db_it(cat, end, str(int(period)+1)) # uses 'rc_timestamp'
out_size = len(out)
toc = time()
if out:
# sort items/entries by timestamp
# (somehow cheap algor. - use SQL directly for sorting)
out_dict = dict( [(item[0][2]+item[0][0]+str(item[0][1]), item) for item in out] )
keys = out_dict.keys()
keys.sort()
out = [out_dict[key] for key in keys]
data['output'] += "<table>\n"
for subrow in out:
data['output'] += "<tr>\n <td>"
title = subrow[0][0]
title = site.namespace(subrow[0][1]).encode('utf8') + ':' + title
data['output'] += '<a href="//%s.wikipedia.org/wiki/%s" target="_blank">%s</a>' % (wiki, title, title.replace('_', ' '))
data['output'] += "</td>\n <td>"
# data['output'] += str(subrow[0][1:])
try:
tmsp = strftime(asctime_fmt, strptime(subrow[0][2], wikitime)) + " (UTC)"
except ValueError:
tmsp = subrow[0][2] + " (!)"
data['output'] += tmsp
data['output'] += "</td>\n <td>"
data['output'] += '<a href="//%s.wikipedia.org/wiki/User:%s" target="_blank">%s</a>' % (wiki, subrow[0][3], subrow[0][3])
data['output'] += "</td>\n <td>"
data['output'] += str(subrow[0][4])
data['output'] += "</td>\n</tr>\n"
data['output'] += "</table>\n"
else:
data['output'] += "<i>No pages matching criteria found.</i><br>\n"
data['output'] += "<br>\n"
data['output'] += "Time to process %i results: %fs\n" % (out_size, (toc-tic))
else:
data['output'] += "<i>No category (cat) defined!</i><br>\n"
data['output'] += "<br>\n"
data['output'] += '<small>%s</small><br>\n' % str( get_wikiinfo_db(wiki) )
data.update({ 'title': 'DrTrigonBot category discussion summary',
'refresh': '',
'tsnotice': style.print_tsnotice(),
'p-status': '<tr><td><small><a href="http://status.toolserver.org/" target="_blank">DB status</a></small></td></tr>',
#'p-status': '<tr><td><small><a href="//status.toolserver.org/" target="_blank">DB status</a></small></td></tr>',
'footer': style.footer + style.footer_w3c, # wiki (new) not CSS 2.1 compilant
'wiki': wiki,
'cat': cgi.escape( cat, quote=True), # proper XSS secure output
'start': cgi.escape( start, quote=True), #
'period': cgi.escape(period, quote=True), #
})
data['content'] = displaystate_content % data
return style.page % data
form = cgi.FieldStorage()
wiki = cgi.escape(form.getvalue('wiki', 'de'), quote=True)
if len(wiki) > 4: wiki = 'de' # cheap protection for SQL injection
site = pywikibot.getSite(wiki)
# Establich a connection
#db = MySQLdb.connect(db='enwiki_p', host="enwiki-p.rrdb.toolserver.org", read_default_file="/home/drtrigon/.my.cnf")
#db = MySQLdb.connect(db=wiki+'wiki_p', host=wiki+"wiki-p.rrdb.toolserver.org", read_default_file="/home/drtrigon/.my.cnf")
#db = MySQLdb.connect(db='u_drtrigon', host=wiki+"wiki-p.userdb.toolserver.org", read_default_file="/home/drtrigon/.my.cnf")
try:
db = MySQLdb.connect(db=db_name, host=wiki+db_conf[1], read_default_file=cnf_file)
except _mysql_exceptions.OperationalError:
# check existence of user database (for temporary table to join with)
db = MySQLdb.connect(host=wiki+db_conf[1], read_default_file=cnf_file)
cursor = db.cursor()
call_db(_SQL_create_database % db_name)
cursor.close()
db.close()
# re-try to connect
db = MySQLdb.connect(db=db_name, host=wiki+db_conf[1], read_default_file=cnf_file)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# operational mode
print style.change_logo(displayhtmlpage(form), os.environ) # labs patch
cursor.close()
db.close()
|
78ff5805fc551bdbf9f0306c37a8cb8be8281a1d
|
[
"Python"
] | 16
|
Python
|
maxprofs-llc/pywikibot-bots-drtrigonbot
|
1c00ea6eef5224e4b9e27531912e560c24aa09ba
|
878c152307f8e80961e88fec9ca672c63b10f186
|
refs/heads/master
|
<repo_name>ianfboldea/vanilla-js-projects<file_sep>/National Parks Infograbber/app.js
// Create an instance of the nps class
const nps = new NPS();
const ui = new UI();
// Add event listener to get-started
document.getElementById('get-started').addEventListener('click', e => {
document.querySelector('.container').style.display = 'block';
document.querySelector('header').style.display = 'none';
let randInt = Math.floor(Math.random() * 497);
console.log(randInt);
const params = ['limit=1', `start=${randInt}`, 'fields=images'];
nps
.getParks(params)
.then(data => {
console.log(data);
ui.showPark(data.data);
nps
.getCampgrounds(data.data[0].parkCode)
.then(data => {
console.log(data);
ui.showCampgrounds(data.data);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));
});
document.getElementById('get-new-park').addEventListener('click', e => {
document.querySelector('.container').style.display = 'block';
document.querySelector('header').style.display = 'none';
let randInt = Math.floor(Math.random() * 497);
console.log(randInt);
const params = ['limit=1', `start=${randInt}`, 'fields=images'];
nps
.getParks(params)
.then(data => {
console.log(data);
ui.showPark(data.data);
nps
.getCampgrounds(data.data[0].parkCode)
.then(data => {
console.log(data);
ui.showCampgrounds(data.data);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));
});
<file_sep>/Regex Form Validation/app.js
// Form Blur Event Listeners
// Blur event is called when you unfocus from an element
document.getElementById('name').addEventListener('blur', validateName);
document.getElementById('zip').addEventListener('blur', validateZip);
document.getElementById('email').addEventListener('blur', validateEmail);
document.getElementById('phone').addEventListener('blur', validatePhone);
function validateName() {
const name = document.getElementById('name');
// Can be any letter from A to Z
// 2 - 10 letters
// starts and ends with, as we want it to be only this content
const re = /^[a-zA-Z]{2,10}$/;
if(!re.test(name.value)){
name.classList.add('is-invalid');
} else {
name.classList.remove('is-invalid');
}
}
function validateZip() {
const zip = document.getElementById('zip');
// Any number from 0 to 9 for 5 numbers
// - 4 more numbers
// starts and ends with
const re = /^[0-9]{5}(-[0-9]{4})?$/;
if(!re.test(zip.value)){
// Boostrap class
zip.classList.add('is-invalid');
} else {
zip.classList.remove('is-invalid');
}
}
function validateEmail() {
const email = document.getElementById('email');
// Starts and ends with this expression
// Can be any letter a-z of any case and/or 0-9, then an @
// + in both specifies that it can occur however many times you want
// After the @, can be any letter of any case and/or any number and
// then the .
// After the ., it can be any letter of any case for 2-5 letters long
// As for the unexplained symbols, the backslashes are escape characters,
// and the symbols specify it can be an _, a -, or a .
const re = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
if(!re.test(email.value)){
email.classList.add('is-invalid');
} else {
email.classList.remove('is-invalid');
}
}
function validatePhone() {
const phone = document.getElementById('phone');
// starts and ends with
// 3 numbers within optional parentheses
// optional -, ., or space
// 3 numbers followed by an optional -, ., or space
// 4 numbers
// ? makes whatever is before it optional
const re = /^\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$/;
if(!re.test(phone.value)){
phone.classList.add('is-invalid');
} else {
phone.classList.remove('is-invalid');
}
}<file_sep>/Stock Calculator/app.js
// Listen for submit
document.getElementById('loan-form').addEventListener('submit', function(e) {
//Hide results
document.getElementById('results').style.display = 'none';
// Show loader
document.getElementById('loading').style.display = 'block';
setTimeout(calculateResults, 2000);
e.preventDefault();
});
// Format number function
function numberWithCommas(n) {
var parts = n.toString().split('.');
return (
parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',') +
(parts[1] ? '.' + parts[1] : '')
);
}
// Calculate results
function calculateResults() {
// UI vars
const amount = document.getElementById('amount');
const returnRate = document.getElementById('return-rate');
// Will be compounded as if it is invested monthly
const yearlyInvestment = document.getElementById('yearly-investment');
const years = document.getElementById('years');
const totalInvestments = document.getElementById('total-investments');
const netGain = document.getElementById('net-gain');
const yearlySalary = document.getElementById('yearly-salary');
const principal = parseFloat(amount.value);
const n = 1; // number of times interest is compounded per unit t
const r = returnRate.value / 100;
const t = years.value;
const pmt = yearlyInvestment.value;
// Calculations
const compoundInterest = principal * parseFloat(Math.pow(1 + r / n, n * t));
const total =
compoundInterest +
parseFloat(
((pmt / 1) * (parseFloat(Math.pow(1 + r / n, n * t)) - 1)) / (r / n)
);
if (isFinite(total)) {
totalInvestments.value = numberWithCommas(
total.toFixed(2).toLocaleString()
);
netGain.value = numberWithCommas(
(total - principal).toFixed(2).toLocaleString()
);
yearlySalary.value = numberWithCommas((total * (1 + r)).toFixed(2));
// Show results
document.getElementById('results').style.display = 'block';
// Hide loader
document.getElementById('loading').style.display = 'none';
} else {
showError('Please check your numbers');
}
}
// Show error
function showError(err) {
// Hide loader
document.getElementById('loading').style.display = 'none';
// Hide results
document.getElementById('results').style.display = 'none';
// Create a div
const errorDiv = document.createElement('div');
// Get elements
const card = document.querySelector('.card');
const heading = document.querySelector('.heading');
// Add class
errorDiv.className = 'alert alert-danger';
// Create text node and append to div
errorDiv.appendChild(document.createTextNode(err));
// Insert error above heading
card.insertBefore(errorDiv, heading);
// Clear error after 3 seconds
setTimeout(clearError, 3000);
}
// Clear error
function clearError() {
document.querySelector('.alert').remove();
}
<file_sep>/README.md
# Vanilla Javascript Projects
## Getting everything setup
To get each project set up, simply open the _index.html_ file within each project folder. A better choice would be using the liveserver extension for VS Code.
## Projects List
These are all of the fun little projects I built in the process of increasing my Vanilla JS skills. Most of these projects were built from Brad Traversy's Udemy course, but some of these were built from my own creativity and intution. Please check my custom projects out! Much Love!
### Big Projects
1. Microposts Project
- Full Stack CRUD App based off of the previously custom created EasyHTTP Library using async/await. Uses webpack and babel to compile the code. Uses JSON Server for the backend. Built in Brad Traversy's Udemy course.
2. Tracalorie Project
- Calorie tracking project with a custom state management system using the Javascript Module Pattern. Persists data to local storage. UI built from Materialize CSS and Font Awesome. Built in Brad Traversy's Udemy course.
### Fun Sized Projects
1. National Parks Infograbber
- Helps you decide which park to hit next! Just a quick project, might work on it more later and flesh it out!
2. Github Finder
- Custom built github profile finder based on Github API using async await in vanilla javascript. Used boostrap for the front end. Completed through a course on Udemy by Brad Traversy
3. Weather JS
- Custom built weather app based on the OpenWeatherMap API (which has gotten way worse) using async await in vanilla javascript. Used bootswatch for the front end. Completed through a course on Udemy by Brad Traversy
4. Chuck Norris Joke Generator
- Joke generator based on using an actual API through AJAX and the XMLHttpRequest object in javascript. Also Oldschool-ish. Completed through a course on Udemy by Brad Traversy
5. Stock Calculator
- Calculates the value of a stock after a certain amount of years based on an intial and annual deposit, along with an expected return rate.
6. Easy HTTP Async
- Custom built http library based on Fetch API using async await in vanilla javascript. Completed through a course on Udemy by Brad Traversy
7. Loan Calculator
- Calculates loan payments based on principal value and interest rate. Completed through a course on Udemy by <NAME>
8. Number Guesser
- A game where you guess a number between a certain range. Completed through a course on Udemy by <NAME>
9. Task List
- Stores tasks in local storage and supports filtering. Completed through a course on Udemy by <NAME>
10. Tic Tac Toe
- A simple, barebones version of tic tac toe.
11. Task List
- Stores tasks in local storage and supports filtering. Completed through a course on Udemy by <NAME>
12. Book List
- Adds books to local storage and displays them. Implements ES6 classes. Completed through a course on Udemy by <NAME>
13. Easy HTTP XHR
- Custom built http library based on AJAX and the XMLHttpRequest object in javascript. Oldschool-ish. Completed through a course on Udemy by <NAME>
14. Easy HTTP XHR
- Custom built http library based on Fetch API in vanilla javascript. Completed through a course on Udemy by <NAME>
15. Regex Form Validation
- Custom built form validation vanilla javascript. Completed through a course on Udemy by <NAME>
16. Profile Scoller
- Example of using javascript iterators through a portion of a dating website. Completed through a course on Udemy by <NAME>
17. State Pattern MiniProject
- Example of using the javascript state pattern. Gives excellent insight into how Redux and other state managers work. Completed through a course on Udemy by <NAME>
<file_sep>/Tic Tac Toe/app.js
// Who goes first?
// X does if random puts out a 1
let turn;
let win = false;
if (Math.round(Math.random())) {
turn = 'X';
} else {
turn = 'O';
}
function markSquare(square) {
if (square.innerText != 'O' && square.innerText != 'X') {
square.innerText = turn;
square.style.background = turn == 'X' ? 'pink' : 'lightgreen';
turn = turn == 'X' ? 'O' : 'X';
}
checkBoard();
}
function checkBoard() {
if (win) {
return window.location.reload();
}
const board = document.querySelectorAll('td');
for (let i = 0; i < 9; i++) {
// Horizontal Rows
if ([0, 3, 6].indexOf(i) != -1) {
if (board[i].innerText == 'X' || board[i].innerText == 'O') {
if (
board[i].innerText == board[i + 1].innerText &&
board[i].innerText == board[i + 2].innerText
) {
const winMessage = document.createElement('h4');
winMessage.appendChild(
document.createTextNode(`${board[i].innerText} wins!`)
);
winMessage.style.margin = '0';
document.querySelector('body').appendChild(winMessage);
win = true;
}
}
}
// Vertical Columns
if ([0, 1, 2].indexOf(i) != -1) {
if (board[i].innerText == 'X' || board[i].innerText == 'O') {
if (
board[i].innerText == board[i + 3].innerText &&
board[i].innerText == board[i + 6].innerText
) {
const winMessage = document.createElement('h4');
winMessage.appendChild(
document.createTextNode(`${board[i].innerText} wins!`)
);
winMessage.style.margin = '0';
document.querySelector('body').appendChild(winMessage);
win = true;
}
}
}
// Diagonals
if (i == 0) {
if (board[i].innerText == 'X' || board[i].innerText == 'O') {
if (
board[i].innerText == board[i + 4].innerText &&
board[i].innerText == board[i + 8].innerText
) {
const winMessage = document.createElement('h4');
winMessage.appendChild(
document.createTextNode(`${board[i].innerText} wins!`)
);
winMessage.style.margin = '0';
document.querySelector('body').appendChild(winMessage);
win = true;
}
}
} else if (i == 2) {
if (board[i].innerText == 'X' || board[i].innerText == 'O') {
if (
board[i].innerText == board[i + 2].innerText &&
board[i].innerText == board[i + 4].innerText
) {
const winMessage = document.createElement('h4');
winMessage.appendChild(
document.createTextNode(`${board[i].innerText} wins!`)
);
winMessage.style.margin = '0';
document.querySelector('body').appendChild(winMessage);
win = true;
}
}
}
}
}
<file_sep>/State Pattern Miniproject/app.js
const PageState = function() {
// Initializes the currentState property of the es5 object
let currentState = new homeState(this);
// Creates a method to set the currentState variable to the default
// onload page
this.init = function() {
this.change(new homeState);
}
// Change current state to any of the state objects that are passe in
// using the new keyword
this.change = function(state) {
currentState = state;
}
};
// Home State
const homeState = function(page) {
// Changes the text content of the heading to nothing to
// make room for the bootstrap jumbotron
document.querySelector('#heading').textContent = null;
document.querySelector('#content').innerHTML = `
<div class="jumbotron">
<h1 class="display-3">Hello, world!</h1>
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<hr class="my-4">
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<p class="lead">
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</p>
</div>
`;
};
// About State
// changes the heading to about us and sets a paragraph tag
const aboutState = function(page) {
document.querySelector('#heading').textContent = 'About Us';
document.querySelector('#content').innerHTML = `
<p>This is the about page</p>
`;
};
// Contact State
// Changes the heading and creates a bootstrap form
const contactState = function(page) {
document.querySelector('#heading').textContent = 'Contact Us';
document.querySelector('#content').innerHTML = `
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control">
</div>
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
`;
};
// Instantiate pageState
const page = new PageState();
// Init the first state
// This calls the change function with the new homeState parameter
page.init();
// UI Vars
const home = document.getElementById('home'),
about = document.getElementById('about'),
contact = document.getElementById('contact');
// Home
home.addEventListener('click', (e) => {
page.change(new homeState);
e.preventDefault();
});
// About
about.addEventListener('click', (e) => {
page.change(new aboutState);
e.preventDefault();
});
// Contact
contact.addEventListener('click', (e) => {
page.change(new contactState);
e.preventDefault();
});
|
73046cfb35f1450088cd3a61dcea191bc5a6dc71
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
ianfboldea/vanilla-js-projects
|
f4593a1a0d8ee5203903d1cc82182659d186e686
|
f7e4f62787d0c916438cfcfe99e767e68a1f5ac3
|
refs/heads/master
|
<repo_name>lober/rosita-database<file_sep>/lz/ddl/lz_ddl.sql
/*
* Copyright 2012-2013 The Regents of the University of Colorado
*
* 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.
*/
-- Table: lz.lz_src_care_site
DROP TABLE lz.lz_src_care_site;
CREATE TABLE lz.lz_src_care_site
(
care_site_id character varying(200),
organization_id character varying(200),
care_site_source_value character varying(200),
x_data_source_type character varying(200),
organization_source_value character varying(200),
place_of_service_source_value character varying(200),
x_care_site_name character varying(200),
care_site_address_1 character varying(200),
care_site_address_2 character varying(200),
care_site_city character varying(200),
care_site_state character varying(200),
care_site_zip character varying(200),
care_site_county character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_care_site
OWNER TO rosita;
-- Table: lz.lz_src_cohort
DROP TABLE lz.lz_src_cohort;
CREATE TABLE lz.lz_src_cohort
(
cohort_id character varying(200),
x_demographic_id character varying(200),
cohort_source_identifier character varying(200),
cohort_source_value character varying(200),
cohort_start_date character varying(200),
cohort_end_date character varying(200),
subject_source_identifier character varying(200),
stop_reason character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_cohort
OWNER TO rosita;
-- Table: lz.lz_src_condition_occurrence
DROP TABLE lz.lz_src_condition_occurrence;
CREATE TABLE lz.lz_src_condition_occurrence
(
condition_occurrence_id character varying(200),
x_demographic_id character varying(200),
condition_occurrence_source_identifier character varying(200),
x_data_source_type character varying(200),
person_source_value character varying(200),
condition_source_value character varying(200),
condition_source_value_vocabulary character varying(200),
x_condition_source_desc character varying(200),
condition_start_date character varying(200),
x_condition_update_date character varying(200),
condition_end_date character varying(200),
condition_type_source_value character varying(200),
stop_reason character varying(200),
associated_provider_source_value character varying(200),
x_visit_occurrence_source_identifier character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_condition_occurrence
OWNER TO rosita;
-- Index: lz.lz_cond_occur_prov_src_idx
-- DROP INDEX lz.lz_cond_occur_prov_src_idx;
CREATE INDEX lz_cond_occur_prov_src_idx
ON lz.lz_src_condition_occurrence
USING btree
(associated_provider_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_cond_occur_person_src_idx
-- DROP INDEX lz.lz_cond_occur_person_src_idx;
CREATE INDEX lz_cond_occur_person_src_idx
ON lz.lz_src_condition_occurrence
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_cond_occur_src_id_idx
-- DROP INDEX lz.lz_cond_occur_src_id_idx;
CREATE INDEX lz_cond_occur_src_id_idx
ON lz.lz_src_condition_occurrence
USING btree
(condition_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_cond_occur_visit_src_id_idx
-- DROP INDEX lz.lz_cond_occur_visit_src_id_idx;
CREATE INDEX lz_cond_occur_visit_src_id_idx
ON lz.lz_src_condition_occurrence
USING btree
(x_visit_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: lz.lz_src_death
DROP TABLE lz.lz_src_death;
CREATE TABLE lz.lz_src_death
(
death_id character varying(200),
x_demographic_id character varying(200),
person_source_value character varying(200),
death_date character varying(200),
death_type_concept_id character varying(200),
death_type_source_value character varying(200),
cause_of_death_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_death
OWNER TO rosita;
-- Table: lz.lz_src_drug_cost
DROP TABLE lz.lz_src_drug_cost;
CREATE TABLE lz.lz_src_drug_cost
(
drug_cost_id character varying(200),
drug_exposure_id character varying(200),
drug_cost_source_identifier character varying(200),
drug_exposure_source_identifier character varying(200),
paid_copay character varying(200),
paid_coinsurance character varying(200),
paid_toward_deductible character varying(200),
paid_by_payer character varying(200),
paid_by_coordination_of_benefits character varying(200),
total_out_of_pocket character varying(200),
total_paid character varying(200),
ingredient_cost character varying(200),
dispensing_fee character varying(200),
average_wholesale_price character varying(200),
payer_plan_period_source_identifier character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_drug_cost
OWNER TO rosita;
-- Table: lz.lz_src_drug_exposure
DROP TABLE lz.lz_src_drug_exposure;
CREATE TABLE lz.lz_src_drug_exposure
(
drug_exposure_id character varying(200),
x_demographic_id character varying(200),
drug_exposure_source_identifier character varying(200),
x_data_source_type character varying(200),
person_source_value character varying(200),
drug_source_value character varying(200),
drug_source_value_vocabulary character varying(200),
drug_exposure_start_date character varying(200),
drug_exposure_end_date character varying(200),
drug_type_source_value character varying(200),
stop_reason character varying(200),
refills character varying(200),
quantity character varying(200),
days_supply character varying(200),
x_drug_name character varying(255),
x_drug_strength character varying(200),
sig character varying(500),
provider_source_value character varying(200),
x_visit_occurrence_source_identifier character varying(200),
relevant_condition_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_drug_exposure
OWNER TO rosita;
-- Index: lz.lz_drug_exp_person_src_idx
-- DROP INDEX lz.lz_drug_exp_person_src_idx;
CREATE INDEX lz_drug_exp_person_src_idx
ON lz.lz_src_drug_exposure
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_drug_exp_src_id_idx
-- DROP INDEX lz.lz_drug_exp_src_id_idx;
CREATE INDEX lz_drug_exp_src_id_idx
ON lz.lz_src_drug_exposure
USING btree
(drug_exposure_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: lz.lz_src_observation
DROP TABLE lz.lz_src_observation;
CREATE TABLE lz.lz_src_observation
(
observation_id character varying(200),
x_demographic_id character varying(200),
observation_source_identifier character varying(200),
x_data_source_type character varying(200),
person_source_value character varying(200),
observation_source_value character varying(200),
observation_source_value_vocabulary character varying(200),
observation_date character varying(200),
observation_time character varying(200),
value_as_number character varying(200),
value_as_string character varying(500),
unit_source_value character varying(200),
range_low character varying(200),
range_high character varying(200),
observation_type_source_value character varying(200),
associated_provider_source_value character varying(200),
x_visit_occurrence_source_identifier character varying(200),
relevant_condition_source_value character varying(200),
x_obs_comment character varying(500)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_observation
OWNER TO rosita;
-- Index: lz.lz_obs_person_src_idx
-- DROP INDEX lz.lz_obs_person_src_idx;
CREATE INDEX lz_obs_person_src_idx
ON lz.lz_src_observation
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_obs_visit_src_id_idx
-- DROP INDEX lz.lz_obs_visit_src_id_idx;
CREATE INDEX lz_obs_visit_src_id_idx
ON lz.lz_src_observation
USING btree
(x_visit_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_obs_src_idx
-- DROP INDEX lz.lz_obs_src_idx;
CREATE INDEX lz_obs_src_idx
ON lz.lz_src_observation
USING btree
(observation_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: lz.lz_src_organization
DROP TABLE lz.lz_src_organization;
CREATE TABLE lz.lz_src_organization
(
organization_id character varying(10),
organization_source_value character varying(200),
x_data_source_type character varying(200),
place_of_service_source_value character varying(200),
organization_address_1 character varying(200),
organization_address_2 character varying(200),
organization_city character varying(200),
organization_state character varying(200),
organization_zip character varying(200),
organization_county character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_organization
OWNER TO rosita;
-- Table: lz.lz_src_payer_plan_period
DROP TABLE lz.lz_src_payer_plan_period;
CREATE TABLE lz.lz_src_payer_plan_period
(
payer_plan_period_id character varying(200),
x_demographic_id character varying(200),
payer_plan_period_source_identifier character varying(200),
person_source_value character varying(200),
payer_plan_period_start_date character varying(200),
payer_plan_period_end_date character varying(200),
payer_source_value character varying(200),
plan_source_value character varying(200),
family_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_payer_plan_period
OWNER TO rosita;
-- Table: lz.lz_src_procedure_cost
DROP TABLE lz.lz_src_procedure_cost;
CREATE TABLE lz.lz_src_procedure_cost
(
procedure_cost_id character varying(200),
procedure_occurrence_id character varying(200),
procedure_cost_source_identifier character varying(200),
procedure_occurrence_source_identifier character varying(200),
paid_copay character varying(200),
paid_coinsurance character varying(200),
paid_toward_deductible character varying(200),
paid_by_payer character varying(200),
paid_by_coordination_of_benefits character varying(200),
total_out_of_pocket character varying(200),
total_paid character varying(200),
disease_class_concept_id character varying(200),
disease_class_source_value character varying(200),
revenue_code_concept_id character varying(200),
revenue_code_source_value character varying(200),
payer_plan_period_source_identifier character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_procedure_cost
OWNER TO rosita;
-- Table: lz.lz_src_procedure_occurrence
DROP TABLE lz.lz_src_procedure_occurrence;
CREATE TABLE lz.lz_src_procedure_occurrence
(
procedure_occurrence_id character varying(200),
x_demographic_id character varying(200),
procedure_occurrence_source_identifier character varying(200),
x_data_source_type character varying(200),
person_source_value character varying(200),
procedure_source_value character varying(200),
procedure_source_value_vocabulary character varying(200),
procedure_date character varying(200),
procedure_type_source_value character varying(200),
provider_record_source_value character varying(200),
x_visit_occurrence_source_identifier character varying(200),
relevant_condition_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_procedure_occurrence
OWNER TO rosita;
-- Index: lz.lz_proc_occur_src_id_idx
-- DROP INDEX lz.lz_proc_occur_src_id_idx;
CREATE INDEX lz_proc_occur_src_id_idx
ON lz.lz_src_procedure_occurrence
USING btree
(procedure_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_proc_occur_person_src_idx
-- DROP INDEX lz.lz_proc_occur_person_src_idx;
CREATE INDEX lz_proc_occur_person_src_idx
ON lz.lz_src_procedure_occurrence
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_proc_occur_cond_src_idx
-- DROP INDEX lz.lz_proc_occur_cond_src_idx;
CREATE INDEX lz_proc_occur_cond_src_idx
ON lz.lz_src_procedure_occurrence
USING btree
(relevant_condition_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_proc_occur_visit_src_id_idx
-- DROP INDEX lz.lz_proc_occur_visit_src_id_idx;
CREATE INDEX lz_proc_occur_visit_src_id_idx
ON lz.lz_src_procedure_occurrence
USING btree
(x_visit_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: lz.lz_src_provider
DROP TABLE lz.lz_src_provider;
CREATE TABLE lz.lz_src_provider
(
provider_id character varying(200),
care_site_id character varying(200),
provider_source_value character varying(200),
x_data_source_type character varying(200),
npi character varying(200),
dea character varying(200),
specialty_source_value character varying(200),
x_provider_first character varying(200),
x_provider_middle character varying(200),
x_provider_last character varying(200),
care_site_source_value character varying(200),
x_organization_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_provider
OWNER TO rosita;
-- Table: lz.lz_src_visit_occurrence
DROP TABLE lz.lz_src_visit_occurrence;
CREATE TABLE lz.lz_src_visit_occurrence
(
visit_occurrence_id character varying(200),
x_demographic_id character varying(200),
x_visit_occurrence_source_identifier character varying(200),
x_data_source_type character varying(200),
person_source_value character varying(200),
visit_start_date character varying(200),
visit_end_date character varying(200),
place_of_service_source_value character varying(200),
x_provider_source_value character varying(200),
care_site_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_visit_occurrence
OWNER TO rosita;
-- Index: lz.lz_visit_occur_care_site_src_idx
-- DROP INDEX lz.lz_visit_occur_care_site_src_idx;
CREATE INDEX lz_visit_occur_care_site_src_idx
ON lz.lz_src_visit_occurrence
USING btree
(care_site_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_visit_occur_place_srvc_src_idx
-- DROP INDEX lz.lz_visit_occur_place_srvc_src_idx;
CREATE INDEX lz_visit_occur_place_srvc_src_idx
ON lz.lz_src_visit_occurrence
USING btree
(place_of_service_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_visit_occur_prov_src_idx
-- DROP INDEX lz.lz_visit_occur_prov_src_idx;
CREATE INDEX lz_visit_occur_prov_src_idx
ON lz.lz_src_visit_occurrence
USING btree
(x_provider_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_visit_occur_person_src_idx
-- DROP INDEX lz.lz_visit_occur_person_src_idx;
CREATE INDEX lz_visit_occur_person_src_idx
ON lz.lz_src_visit_occurrence
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: lz.lz_src_x_demographic
DROP TABLE lz.lz_src_x_demographic;
CREATE TABLE lz.lz_src_x_demographic
(
x_demographic_id character varying(200),
organization_id character varying(200),
person_source_value character varying(200),
x_data_source_type character varying(200),
medicaid_id_number character varying(200),
ssn character varying(200),
last character varying(200),
middle character varying(200),
first character varying(200),
address_1 character varying(200),
address_2 character varying(200),
city character varying(200),
state character varying(200),
zip character varying(200),
county character varying(200),
year_of_birth character varying(200),
month_of_birth character varying(200),
day_of_birth character varying(200),
gender_source_value character varying(200),
race_source_value character varying(200),
ethnicity_source_value character varying(200),
provider_source_value character varying(200),
care_site_source_value character varying(200),
x_organization_source_value character varying(200)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE lz.lz_src_x_demographic
OWNER TO rosita;
-- Index: lz.lz_demo_city_state_zip_idx
-- DROP INDEX lz.lz_demo_city_state_zip_idx;
CREATE INDEX lz_demo_city_state_zip_idx
ON lz.lz_src_x_demographic
USING btree
(city COLLATE pg_catalog."default" , state COLLATE pg_catalog."default" , zip COLLATE pg_catalog."default" , county COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_demo_care_site_src_idx
-- DROP INDEX lz.lz_demo_care_site_src_idx;
CREATE INDEX lz_demo_care_site_src_idx
ON lz.lz_src_x_demographic
USING btree
(care_site_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_demo_id_idx
-- DROP INDEX lz.lz_demo_id_idx;
CREATE INDEX lz_demo_id_idx
ON lz.lz_src_x_demographic
USING btree
(x_demographic_id COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_demo_org_src_idx
-- DROP INDEX lz.lz_demo_org_src_idx;
CREATE INDEX lz_demo_org_src_idx
ON lz.lz_src_x_demographic
USING btree
(x_organization_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_demo_person_src_idx
-- DROP INDEX lz.lz_demo_person_src_idx;
CREATE INDEX lz_demo_person_src_idx
ON lz.lz_src_x_demographic
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: lz.lz_demo_prov_src_idx
-- DROP INDEX lz.lz_demo_prov_src_idx;
CREATE INDEX lz_demo_prov_src_idx
ON lz.lz_src_x_demographic
USING btree
(provider_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
<file_sep>/setup.sh
#!/bin/bash
#
# Copyright 2012-2013 The Regents of the University of Colorado
#
# 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.
#
#export PGUSER=postgres
#export PGPASSWORD=<PASSWORD>
#mkdir /var/lib/pgsql/9.1/rosita_data
#mkdir /var/lib/pgsql/9.1/rosita_indx
#psql --file=setup1_linux.sql postgres
export PGDATABASE=rosita
export PGUSER=rosita
export PGPASSWORD=<PASSWORD>
psql --file=setup2.sql
psql --file=cz/ddl/cz_ddl.sql
psql --file=cz/dml/czx_concept_analyze.sql
psql --file=cz/dml/czx_end_audit.sql
psql --file=cz/dml/czx_oscar_anlayze.sql
psql --file=cz/dml/czx_start_audit.sql
psql --file=cz/dml/czx_to_numeric.sql
psql --file=cz/dml/czx_to_varchar.sql
psql --file=cz/dml/czx_write_audit.sql
psql --file=cz/dml/czx_write_error.sql
psql --file=cz/data/cz_oscar_rule.dmp
psql --file=lz/ddl/lz_ddl.sql
psql --file=rz/ddl/rz_ddl.sql
# load data
psql --file=omop/ddl/omop_ddl.sql
psql --file=omop/dml/omx_load_all.sql
psql --file=omop/dml/omx_load_care_site.sql
psql --file=omop/dml/omx_load_condition_occurrence.sql
psql --file=omop/dml/omx_load_drug_exposure.sql
psql --file=omop/dml/omx_load_location.sql
psql --file=omop/dml/omx_load_observation.sql
psql --file=omop/dml/omx_load_organization.sql
psql --file=omop/dml/omx_load_person.sql
psql --file=omop/dml/omx_load_procedure_occurrence.sql
psql --file=omop/dml/omx_load_provider.sql
psql --file=omop/dml/omx_load_visit_occurrence.sql
<file_sep>/rz/ddl/rz_ddl.sql
/*
* Copyright 2012-2013 The Regents of the University of Colorado
*
* 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.
*/
-- Table: rz.vocabulary
DROP TABLE rz.vocabulary cascade;
CREATE TABLE rz.vocabulary
(
vocabulary_id integer NOT NULL,
vocabulary_name character varying(256) NOT NULL,
CONSTRAINT vocabulary_vocabulary_id_key UNIQUE (vocabulary_id ),
CONSTRAINT vocabulary_vocabulary_name_key UNIQUE (vocabulary_name )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.vocabulary
OWNER TO rosita;
-- Table: rz.concept
DROP TABLE rz.concept cascade;
CREATE TABLE rz.concept
(
concept_id integer NOT NULL,
concept_name character varying(256) NOT NULL,
concept_level integer NOT NULL,
concept_class character varying(60) NOT NULL,
vocabulary_id integer NOT NULL,
concept_code character varying(20) NOT NULL,
valid_start_date date NOT NULL,
valid_end_date date NOT NULL DEFAULT '2099-12-31'::date,
invalid_reason character(1),
CONSTRAINT concept_pkey PRIMARY KEY (concept_id ),
CONSTRAINT concept_vocabulary_ref_fk FOREIGN KEY (vocabulary_id)
REFERENCES rz.vocabulary (vocabulary_id) MATCH FULL
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT concept_invalid_reason_check CHECK (invalid_reason = 'D'::bpchar OR invalid_reason = 'U'::bpchar)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.concept
OWNER TO rosita;
-- Table: rz.concept_ancestor
DROP TABLE rz.concept_ancestor;
CREATE TABLE rz.concept_ancestor
(
ancestor_concept_id integer NOT NULL,
descendant_concept_id integer NOT NULL,
min_levels_of_separation integer,
max_levels_of_separation integer,
CONSTRAINT concept_ancestor_pkey PRIMARY KEY (ancestor_concept_id , descendant_concept_id ),
CONSTRAINT concept_ancestor_fk FOREIGN KEY (ancestor_concept_id)
REFERENCES rz.concept (concept_id) MATCH FULL
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT concept_descendant_fk FOREIGN KEY (descendant_concept_id)
REFERENCES rz.concept (concept_id) MATCH FULL
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.concept_ancestor
OWNER TO rosita;
-- Table: rz.concept_relationship
DROP TABLE rz.concept_relationship;
CREATE TABLE rz.concept_relationship
(
concept_id_1 integer NOT NULL,
concept_id_2 integer NOT NULL,
relationship_id integer NOT NULL,
valid_start_date date NOT NULL,
valid_end_date date NOT NULL DEFAULT '2099-12-31'::date,
invalid_reason character(1),
CONSTRAINT concept_relationship_pkey PRIMARY KEY (concept_id_1 , concept_id_2 , relationship_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.concept_relationship
OWNER TO rosita;
-- Table: rz.concept_synonym
DROP TABLE rz.concept_synonym;
CREATE TABLE rz.concept_synonym
(
concept_synonym_id integer NOT NULL,
concept_id integer NOT NULL,
concept_synonym_name character varying(1000) NOT NULL,
CONSTRAINT concept_synonym_pkey PRIMARY KEY (concept_synonym_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.concept_synonym
OWNER TO rosita;
-- Table: rz.relationship
DROP TABLE rz.relationship;
CREATE TABLE rz.relationship
(
relationship_id integer NOT NULL,
relationship_name character varying(256) NOT NULL,
is_hierarchical character(1),
defines_ancestry character(1),
CONSTRAINT relationship_pkey PRIMARY KEY (relationship_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.relationship
OWNER TO rosita;
-- Table: rz.source_to_concept_map
DROP TABLE rz.source_to_concept_map;
CREATE TABLE rz.source_to_concept_map
(
source_code character varying(200) NOT NULL,
source_vocabulary_id integer NOT NULL,
source_code_description character varying(256),
target_concept_id integer NOT NULL,
target_vocabulary_id integer NOT NULL,
mapping_type character varying(20),
primary_map character(1),
valid_start_date date NOT NULL,
valid_end_date date NOT NULL,
invalid_reason character(1),
map_source character varying(20),
CONSTRAINT source_to_concept_map_pkey PRIMARY KEY (source_vocabulary_id , target_concept_id , source_code , valid_end_date )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE rz.source_to_concept_map
OWNER TO rosita;
-- Index: rz.rx_src_to_con_map_src_code_idx
DROP INDEX rz.rx_src_to_con_map_src_code_idx;
CREATE INDEX rx_src_to_con_map_src_code_idx
ON rz.source_to_concept_map
USING btree
(source_code COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: rz.rx_src_to_con_map_src_vocab_idx
DROP INDEX rz.rx_src_to_con_map_src_vocab_idx;
CREATE INDEX ind_src_to_con_map_src_rx_src_to_con_map_src_vocab_idxoc_id
ON rz.source_to_concept_map
USING btree
(source_vocabulary_id )
TABLESPACE rosita_indx;
-- Index: rz.rx_src_to_con_map_map_type_idx
DROP INDEX rz.rx_src_to_con_map_map_type_idx;
CREATE INDEX rx_src_to_con_map_map_type_idx
ON rz.source_to_concept_map
USING btree
(mapping_type COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
<file_sep>/cz/ddl/cz_ddl.sql
/*
* Copyright 2012-2013 The Regents of the University of Colorado
*
* 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.
*/
-- Sequence: cz.cz_sq
DROP SEQUENCE cz.cz_sq CASCADE;
CREATE SEQUENCE cz.cz_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE cz.cz_sq
OWNER TO rosita;
-- Sequence: cz.cz_id_map_sq
DROP SEQUENCE cz.cz_id_map_sq CASCADE;
CREATE SEQUENCE cz.cz_id_map_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE cz.cz_id_map_sq
OWNER TO rosita;
-- Sequence: cz.seq_au_pk_id
DROP SEQUENCE cz.seq_au_pk_id;
CREATE SEQUENCE cz.seq_au_pk_id
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE cz.seq_au_pk_id
OWNER TO rosita;
-- Table: cz.au_permission
DROP TABLE cz.au_permission;
CREATE TABLE cz.au_permission
(
id bigint NOT NULL,
description character varying(500),
name character varying(50) NOT NULL,
unique_id character varying(255) NOT NULL,
CONSTRAINT au_permission_pk PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_permission
OWNER TO rosita;
-- Table: cz.au_principal
DROP TABLE cz.au_principal CASCADE;
CREATE TABLE cz.au_principal
(
principal_id bigint NOT NULL,
category character varying(255) NOT NULL,
date_created timestamp without time zone NOT NULL,
last_updated timestamp without time zone NOT NULL,
name character varying(255) NOT NULL,
security_identifier character varying(255),
username character varying(255),
class character varying(255) NOT NULL,
provider_code character varying(255),
CONSTRAINT au_principal_pk PRIMARY KEY (principal_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_principal
OWNER TO rosita;
-- Table: cz.au_person
DROP TABLE cz.au_person CASCADE;
CREATE TABLE cz.au_person
(
person_id bigint NOT NULL,
email character varying(255) NOT NULL,
email_show boolean NOT NULL,
enabled boolean NOT NULL,
password character varying(255) NOT NULL,
principal_id bigint,
username character varying(255) NOT NULL,
CONSTRAINT au_person_pk PRIMARY KEY (person_id ),
CONSTRAINT au_person_principal_fk FOREIGN KEY (principal_id)
REFERENCES cz.au_principal (principal_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT au_person_username_uk UNIQUE (username )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_person
OWNER TO rosita;
-- Table: cz.au_role_descr
DROP TABLE cz.au_role_descr CASCADE;
CREATE TABLE cz.au_role_descr
(
role_descr_id bigint NOT NULL,
authority character varying(255) NOT NULL,
description character varying(255),
display_name character varying(255) NOT NULL,
security_level integer NOT NULL,
CONSTRAINT au_role_descr_pk PRIMARY KEY (role_descr_id ),
CONSTRAINT au_role_descr_authority_uk UNIQUE (authority )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_role_descr
OWNER TO rosita;
-- Table: cz.au_person_role
DROP TABLE cz.au_person_role CASCADE;
CREATE TABLE cz.au_person_role
(
person_id bigint NOT NULL,
authority_id bigint NOT NULL,
CONSTRAINT au_person_role_pk PRIMARY KEY (authority_id , person_id ),
CONSTRAINT au_person_role_descr_fk FOREIGN KEY (authority_id)
REFERENCES cz.au_role_descr (role_descr_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT au_person_role_person_fk FOREIGN KEY (person_id)
REFERENCES cz.au_person (person_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_person_role
OWNER TO rosita;
-- Table: cz.au_request_map
DROP TABLE cz.au_request_map;
CREATE TABLE cz.au_request_map
(
request_map_id bigint NOT NULL,
version bigint NOT NULL,
config_attribute character varying(255) NOT NULL,
url character varying(255) NOT NULL,
CONSTRAINT au_request_map_pk PRIMARY KEY (request_map_id ),
CONSTRAINT au_request_map_url_uk UNIQUE (url )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_request_map
OWNER TO rosita;
-- Table: cz.au_user_group_member
DROP TABLE cz.au_user_group_member;
CREATE TABLE cz.au_user_group_member
(
au_group_id bigint,
au_user_id bigint,
CONSTRAINT au_user_group_member_principal_user_fk FOREIGN KEY (au_user_id)
REFERENCES cz.au_principal (principal_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT au_user_group_member_principal_group_fk FOREIGN KEY (au_group_id)
REFERENCES cz.au_principal (principal_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.au_user_group_member
OWNER TO rosita;
-- Table: cz.cz_concept_map
DROP TABLE cz.cz_concept_map;
CREATE TABLE cz.cz_concept_map
(
concept_map_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
target_table character varying(50),
target_column character varying(50),
source_value character varying(200),
source_vocabulary character varying(50),
source_desc character varying(200),
target_concept_id bigint,
is_mapped character(1),
is_empty character(1),
source_count bigint,
CONSTRAINT cz_concept_map_id_pk PRIMARY KEY (concept_map_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_concept_map
OWNER TO rosita;
-- Index: cz.cz_concept_map_tab_col_val_idx
-- DROP INDEX cz.cz_concept_map_tab_col_val_idx;
CREATE INDEX cz_concept_map_tab_col_val_idx
ON cz.cz_concept_map
USING btree
(target_table COLLATE pg_catalog."default" , target_column COLLATE pg_catalog."default" , source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: cz.cz_concept_map_tab_col_val_voc_idx
-- DROP INDEX cz.cz_concept_map_tab_col_val_voc_idx;
CREATE INDEX cz_concept_map_tab_col_val_voc_idx
ON cz.cz_concept_map
USING btree
(target_table COLLATE pg_catalog."default" , target_column COLLATE pg_catalog."default" , source_value COLLATE pg_catalog."default" , source_vocabulary COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: cz.cz_etl_error_log
DROP TABLE cz.cz_etl_error_log;
CREATE TABLE cz.cz_etl_error_log
(
etl_error_log_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
job_id bigint,
function_name character varying(50),
step_number int,
error_state character varying(50),
error_message character varying(2000),
error_date timestamp without time zone DEFAULT (clock_timestamp())::timestamp without time zone,
CONSTRAINT cz_etl_error_log_pk PRIMARY KEY (etl_error_log_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_etl_error_log
OWNER TO rosita;
-- Table: cz.cz_id_map
DROP TABLE cz.cz_id_map;
CREATE TABLE cz.cz_id_map
(
id bigint NOT NULL DEFAULT nextval('cz.cz_id_map_sq'::regclass),
source_value character varying(200) NOT NULL,
id_type character varying(20) NOT NULL,
CONSTRAINT cz_id_map_pk PRIMARY KEY (source_value , id_type )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_id_map
OWNER TO rosita;
-- Index: cz.cz_id_map_id_idx
-- DROP INDEX cz.cz_id_map_id_idx;
CREATE INDEX cz_id_map_id_idx
ON cz.cz_id_map
USING btree
(id )
TABLESPACE rosita_indx;
-- Index: cz.cz_id_map_src_val_idx
-- DROP INDEX cz.cz_id_map_src_val_idx;
CREATE INDEX cz_id_map_src_val_idx
ON cz.cz_id_map
USING btree
(source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: cz.cz_id_map_srcv_typ_idx
-- DROP INDEX cz.cz_id_map_srcv_typ_idx;
CREATE INDEX cz_id_map_srcv_typ_idx
ON cz.cz_id_map
USING btree
(source_value COLLATE pg_catalog."default" , id_type COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: cz.cz_job_master
DROP TABLE cz.cz_job_master CASCADE;
CREATE TABLE cz.cz_job_master
(
job_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
start_date timestamp without time zone,
end_date timestamp without time zone,
active character varying(1),
username character varying(50),
time_elapsed_secs bigint,
build_id bigint,
session_id bigint NOT NULL,
database_name character varying(50),
job_status character varying(50),
job_name character varying(500),
CONSTRAINT cz_job_master_pk PRIMARY KEY (job_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_job_master
OWNER TO rosita;
-- Table: cz.cz_job_audit
DROP TABLE cz.cz_job_audit;
CREATE TABLE cz.cz_job_audit
(
job_audit_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
job_id bigint NOT NULL,
database_name character varying(50),
procedure_name character varying(100),
step_desc character varying(4000),
step_status character varying(50),
records_manipulated bigint,
step_number bigint,
audit_date timestamp without time zone DEFAULT (clock_timestamp())::timestamp without time zone,
time_elapsed_secs numeric(18,4),
version_id bigint,
CONSTRAINT cz_job_audit_pk PRIMARY KEY (job_audit_id)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_job_audit
OWNER TO rosita;
-- Table: cz.cz_oscar_result
DROP TABLE cz.cz_oscar_result;
CREATE TABLE cz.cz_oscar_result
(
oscar_result_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
oscar_rule_id bigint,
source_schema_name character varying(50),
source_table_name character varying(50),
variable_name character varying(50),
variable_type integer,
summary_level integer,
variable_value character varying(2000),
statistic_type integer,
statistic_value character varying(50),
variable_description_level_1 character varying(2000),
variable_value_level_1 integer,
variable_description_level_2 character varying(2000),
variable_value_level_2 integer,
variable_description_level_3 character varying(2000),
variable_value_level_3 integer,
variable_description_level_4 character varying(2000),
variable_value_level_4 integer,
contains_phi character(1),
create_date timestamp,
CONSTRAINT cz_oscar_result_pk PRIMARY KEY (oscar_result_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_oscar_result
OWNER TO rosita;
-- Table: cz.cz_oscar_rule
DROP TABLE cz.cz_oscar_rule;
CREATE TABLE cz.cz_oscar_rule
(
oscar_rule_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
schema_name character varying(50),
table_name character varying(50),
column_name character varying(50),
summary_level_observation character(1),
summary_level_patient character(1),
summarize_as_continuous character(1),
summarize_as_categorical character(1),
cast_type character varying(50),
contains_phi character(1),
limit_count bigint,
create_date timestamp without time zone,
update_date timestamp without time zone,
CONSTRAINT cz_oscar_rule_pk PRIMARY KEY (oscar_rule_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_oscar_rule
OWNER TO rosita;
-- Table: cz.cz_random_id
DROP TABLE cz.cz_random_id;
CREATE TABLE cz.cz_random_id
(
id integer NOT NULL,
id_type character varying(20) NOT NULL,
random_id integer NOT NULL,
CONSTRAINT cz_random_id_pk PRIMARY KEY (id, id_type)
USING INDEX TABLESPACE rosita_indx,
CONSTRAINT cz_random_id_uk UNIQUE (id_type, random_id)
USING INDEX TABLESPACE rosita_indx
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_random_id
OWNER TO rosita;
-- Table: cz.cz_rosita_job
DROP TABLE cz.cz_rosita_job CASCADE;
CREATE TABLE cz.cz_rosita_job
(
job_id bigint NOT NULL,
end_date timestamp without time zone,
file_name character varying(255) NOT NULL,
name character varying(255),
schema_name character varying(255) NOT NULL,
start_date timestamp without time zone,
total_elements bigint,
workflow_step integer NOT NULL,
CONSTRAINT cz_rosita_job_pk PRIMARY KEY (job_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_rosita_job
OWNER TO rosita;
-- Table: cz.cz_workflow_signal
DROP TABLE cz.cz_workflow_signal;
CREATE TABLE cz.cz_workflow_signal
(
signal_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
date timestamp without time zone NOT NULL,
job_id bigint NOT NULL,
pending boolean NOT NULL,
success boolean NOT NULL,
workflow_step integer NOT NULL,
message character varying(255),
CONSTRAINT cz_workflow_signal_pk PRIMARY KEY (signal_id ),
CONSTRAINT cz_workflow_signal_rosita_job_fk FOREIGN KEY (job_id)
REFERENCES cz.cz_rosita_job (job_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_workflow_signal
OWNER TO rosita;
-- Table: cz.cz_workflow_step
DROP TABLE cz.cz_workflow_step CASCADE;
CREATE TABLE cz.cz_workflow_step
(
step_id bigint NOT NULL,
end_date timestamp without time zone,
job_id bigint NOT NULL,
message character varying(255),
proc_id integer,
start_date timestamp without time zone,
state character varying(255) NOT NULL,
workflow_step integer NOT NULL,
CONSTRAINT cz_workflow_step_pk PRIMARY KEY (step_id ),
CONSTRAINT cz_workflow_step_rosita_job_fk FOREIGN KEY (job_id)
REFERENCES cz.cz_rosita_job (job_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_workflow_step
OWNER TO rosita;
-- Table: cz.cz_console_output
DROP TABLE cz.cz_console_output;
CREATE TABLE cz.cz_console_output
(
console_output_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
date timestamp without time zone NOT NULL,
step_id bigint NOT NULL,
message text,
CONSTRAINT cz_console_output_pk PRIMARY KEY (console_output_id ),
CONSTRAINT cz_console_output_workflow_step_fk FOREIGN KEY (step_id)
REFERENCES cz.cz_workflow_step (step_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_console_output
OWNER TO rosita;
-- Table: cz.cz_workflow_title
DROP TABLE cz.cz_workflow_title;
CREATE TABLE cz.cz_workflow_title
(
title_id bigint NOT NULL,
title character varying(255) NOT NULL,
CONSTRAINT cz_workflow_title_pk PRIMARY KEY (title_id )
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_workflow_title
OWNER TO rosita;
-- Table: cz.cz_xml_error_log
DROP TABLE cz.cz_xml_error_log;
CREATE TABLE cz.cz_xml_error_log
(
xml_error_log_id bigint NOT NULL DEFAULT nextval('cz.cz_sq'::regclass),
line_number bigint,
message text,
error_type character varying(10),
schema character varying(100),
datetime timestamp with time zone,
location character varying(256),
source_type character varying(20),
filename character varying(50),
step_id bigint,
CONSTRAINT cz_error_xml_log_pk PRIMARY KEY (xml_error_log_id)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE cz.cz_xml_error_log
OWNER TO rosita;
-- View: cz.cz_all_table_columns
DROP VIEW cz.cz_all_table_columns;
CREATE OR REPLACE VIEW cz.cz_all_table_columns AS
SELECT c.nspname AS schema_name, b.relname AS table_name, a.attname AS column_name, a.attnum AS column_index, d.typname AS type_name,
CASE d.typname
WHEN 'numeric'::name THEN
CASE
WHEN a.atttypmod = (-1) THEN NULL::integer
ELSE ((a.atttypmod - 4) >> 16) & 65535
END
WHEN 'varchar'::name THEN
CASE
WHEN a.atttypmod = (-1) THEN NULL::integer
ELSE a.atttypmod - 4
END
WHEN 'int2'::name THEN 16
WHEN 'int4'::name THEN 32
WHEN 'int8'::name THEN 64
WHEN 'float4'::name THEN 24
WHEN 'float8'::name THEN 53
ELSE NULL::integer
END AS column_length,
CASE
WHEN a.atttypid = ANY (ARRAY[21::oid, 23::oid, 20::oid]) THEN 0
WHEN a.atttypid = 1700::oid THEN
CASE
WHEN a.atttypmod = (-1) THEN NULL::integer
ELSE (a.atttypmod - 4) & 65535
END
ELSE NULL::integer
END AS columnscale,
CASE a.attnotnull
WHEN true THEN 'NOT NULL'::text
ELSE NULL::text
END AS not_null
FROM pg_attribute a
JOIN pg_class b ON a.attrelid = b.oid
JOIN pg_namespace c ON b.relnamespace = c.oid
JOIN pg_type d ON a.atttypid = d.oid
WHERE a.attnum > 0;
ALTER TABLE cz.cz_all_table_columns
OWNER TO rosita;
<file_sep>/omop/ddl/omop_ddl.sql
/*
* Copyright 2012-2013 The Regents of the University of Colorado
*
* 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.
*/
-- Sequence: omop.omop_care_site_sq
DROP SEQUENCE omop.omop_care_site_sq CASCADE;
CREATE SEQUENCE omop.omop_care_site_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_care_site_sq
OWNER TO rosita;
-- Sequence: omop.omop_care_site_sq
DROP SEQUENCE omop.omop_cohort_sq CASCADE;
CREATE SEQUENCE omop.omop_cohort_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_cohort_sq
OWNER TO rosita;
-- Sequence: omop.omop_cond_era_sq
DROP SEQUENCE omop.omop_cond_era_sq CASCADE;
CREATE SEQUENCE omop.omop_cond_era_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_cond_era_sq
OWNER TO rosita;
-- Sequence: omop.omop_cond_occur_sq
DROP SEQUENCE omop.omop_cond_occur_sq CASCADE;
CREATE SEQUENCE omop.omop_cond_occur_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_cond_occur_sq
OWNER TO rosita;
-- Sequence: omop.omop_drug_cost_sq
DROP SEQUENCE omop.omop_drug_cost_sq CASCADE;
CREATE SEQUENCE omop.omop_drug_cost_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_drug_cost_sq
OWNER TO rosita;
-- Sequence: omop.omop_drug_era_sq
DROP SEQUENCE omop.omop_drug_era_sq CASCADE;
CREATE SEQUENCE omop.omop_drug_era_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_drug_era_sq
OWNER TO rosita;
-- Sequence: omop.omop_drug_exp_sq
DROP SEQUENCE omop.omop_drug_exp_sq CASCADE;
CREATE SEQUENCE omop.omop_drug_exp_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_drug_exp_sq
OWNER TO rosita;
-- Sequence: omop.omop_location_sq
DROP SEQUENCE omop.omop_location_sq CASCADE;
CREATE SEQUENCE omop.omop_location_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_location_sq
OWNER TO rosita;
-- Sequence: omop.omop_obs_sq
DROP SEQUENCE omop.omop_obs_sq CASCADE;
CREATE SEQUENCE omop.omop_obs_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_obs_sq
OWNER TO rosita;
-- Sequence: omop.omop_obs_sq
DROP SEQUENCE omop.omop_obs_period_sq CASCADE;
CREATE SEQUENCE omop.omop_obs_period_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_obs_period_sq
OWNER TO rosita;
-- Sequence: omop.omop_organ_sq
DROP SEQUENCE omop.omop_organization_sq CASCADE;
CREATE SEQUENCE omop.omop_organization_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_organization_sq
OWNER TO rosita;
-- Sequence: omop.omop_payer_plan_sq
DROP SEQUENCE omop.omop_payer_plan_sq CASCADE;
CREATE SEQUENCE omop.omop_payer_plan_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_payer_plan_sq
OWNER TO rosita;
-- Sequence: omop.omop_proc_cost_sq
DROP SEQUENCE omop.omop_proc_cost_sq CASCADE;
CREATE SEQUENCE omop.omop_proc_cost_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_proc_cost_sq
OWNER TO rosita;
-- Sequence: omop.omop_proc_occur_sq
DROP SEQUENCE omop.omop_proc_occur_sq CASCADE;
CREATE SEQUENCE omop.omop_proc_occur_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_proc_occur_sq
OWNER TO rosita;
-- Sequence: omop.omop_provider_sq
DROP SEQUENCE omop.omop_provider_sq CASCADE;
CREATE SEQUENCE omop.omop_provider_sq
INCREMENT 1
MINVALUE 1
MAXVALUE 2147483647
START 1
CACHE 10;
ALTER TABLE omop.omop_provider_sq
OWNER TO rosita;
-- Table: omop.care_site
DROP TABLE omop.care_site;
CREATE TABLE omop.care_site
(
care_site_id bigint NOT NULL DEFAULT nextval('omop.omop_care_site_sq'),
location_id bigint NOT NULL,
organization_id bigint NOT NULL,
place_of_service_concept_id bigint,
care_site_source_value character varying(50) NOT NULL,
place_of_service_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_care_site_name character varying(50),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.care_site
OWNER TO rosita;
-- Index: omop.omop_care_site_source_idx
-- DROP INDEX omop.omop_care_site_source_idx;
CREATE INDEX omop_care_site_source_idx
ON omop.care_site
USING btree
(care_site_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: omop.cohort
DROP TABLE omop.cohort;
CREATE TABLE omop.cohort
(
cohort_id bigint NOT NULL DEFAULT nextval('omop.omop_cohort_sq'),
cohort_concept_id bigint NOT NULL,
cohort_start_date date NOT NULL,
cohort_end_date date,
subject_id bigint NOT NULL,
stop_reason character varying(20),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.cohort
OWNER TO rosita;
-- Table: omop.condition_era
DROP TABLE omop.condition_era;
CREATE TABLE omop.condition_era
(
condition_era_id bigint NOT NULL DEFAULT nextval('omop.omop_cond_era_sq'),
person_id bigint NOT NULL,
condition_concept_id bigint NOT NULL,
condition_era_start_date date NOT NULL,
condition_era_end_date date NOT NULL,
condition_type_concept_id bigint NOT NULL,
condition_occurrence_count numeric(4,0)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.condition_era
OWNER TO rosita;
-- Table: omop.condition_occurrence
DROP TABLE omop.condition_occurrence;
CREATE TABLE omop.condition_occurrence
(
condition_occurrence_id bigint NOT NULL DEFAULT nextval('omop.omop_cond_occur_sq'),
person_id bigint NOT NULL,
condition_concept_id bigint NOT NULL,
condition_start_date date NOT NULL,
condition_end_date date,
condition_type_concept_id bigint NOT NULL,
stop_reason character varying(20),
associated_provider_id bigint,
visit_occurrence_id bigint,
condition_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_condition_source_desc character varying(50),
x_condition_update_date date,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.condition_occurrence
OWNER TO rosita;
-- Table: omop.death
DROP TABLE omop.death;
CREATE TABLE omop.death
(
person_id bigint NOT NULL,
death_date date,
death_type_concept_id bigint NOT NULL,
cause_of_death_concept_id bigint,
cause_of_death_source_value character varying(50),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.death
OWNER TO rosita;
-- Table: omop.drug_cost
DROP TABLE omop.drug_cost;
CREATE TABLE omop.drug_cost
(
drug_cost_id bigint NOT NULL DEFAULT nextval('omop.omop_drug_cost_sq'::regclass),
drug_exposure_id bigint NOT NULL,
paid_copay numeric(8,2),
paid_coinsurance numeric(8,2),
paid_toward_deductible numeric(8,2),
paid_by_payer numeric(8,2),
paid_by_coordination_benefits numeric(8,2),
total_out_of_pocket numeric(8,2),
total_paid numeric(8,2),
ingredient_cost numeric(8,2),
dispensing_fee numeric(8,2),
average_wholesale_price numeric(8,2),
payer_plan_period_id bigint,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.drug_cost
OWNER TO rosita;
-- Table: omop.drug_era
DROP TABLE omop.drug_era;
CREATE TABLE omop.drug_era
(
drug_era_id bigint NOT NULL DEFAULT nextval('omop.omop_drug_era_sq'::regclass),
person_id bigint NOT NULL,
drug_concept_id bigint NOT NULL,
drug_era_start_date date NOT NULL,
drug_era_end_date date NOT NULL,
drug_type_concept_id bigint NOT NULL,
drug_exposure_count numeric(4,0)
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.drug_era
OWNER TO rosita;
-- Table: omop.drug_exposure
DROP TABLE omop.drug_exposure;
CREATE TABLE omop.drug_exposure
(
drug_exposure_id bigint NOT NULL DEFAULT nextval('omop.omop_drug_exp_sq'::regclass),
person_id bigint NOT NULL,
drug_concept_id bigint NOT NULL,
drug_exposure_start_date date NOT NULL,
drug_exposure_end_date date,
drug_type_concept_id bigint NOT NULL,
stop_reason character varying(20),
refills numeric(4,0),
quantity numeric(8,0),
days_supply numeric(4,0),
sig character varying(500),
prescribing_provider_id bigint,
visit_occurrence_id bigint,
relevant_condition_concept_id bigint,
drug_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_drug_name character varying(255) NOT NULL,
x_drug_strength character varying(50),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.drug_exposure
OWNER TO rosita;
-- Table: omop.location
DROP TABLE omop.location;
CREATE TABLE omop.location
(
location_id bigint NOT NULL DEFAULT nextval('omop.omop_location_sq'),
address_1 character varying(50),
address_2 character varying(50),
city character varying(50),
state character varying(2),
zip character varying(9),
county character varying(20),
location_source_value character varying(50),
x_zip_deidentified character varying(9),
x_location_type character varying(20) NOT NULL,
x_data_source_type character varying(20),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.location
OWNER TO rosita;
-- Index: omop.omop_location_source_type_idx
-- DROP INDEX omop.omop_location_source_type_idx;
CREATE INDEX omop_location_source_type_idx
ON omop.location
USING btree
(location_source_value COLLATE pg_catalog."default" , x_location_type COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Index: omop.omop_location_src_city_zip_state_idx
-- DROP INDEX omop.omop_location_src_city_zip_state_idx;
CREATE INDEX omop_location_src_city_zip_state_idx
ON omop.location
USING btree
(x_location_type COLLATE pg_catalog."default", city COLLATE pg_catalog."default", state COLLATE pg_catalog."default", zip COLLATE pg_catalog."default", county COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: omop.observation
DROP TABLE omop.observation;
CREATE TABLE omop.observation
(
observation_id bigint NOT NULL DEFAULT nextval('omop.omop_obs_sq'),
person_id bigint NOT NULL,
observation_concept_id bigint NOT NULL,
observation_date date NOT NULL,
observation_time time without time zone,
value_as_number numeric(14,3),
value_as_string character varying(60),
value_as_concept_id bigint,
unit_concept_id bigint,
range_low numeric(14,3),
range_high numeric(14,3),
observation_type_concept_id bigint NOT NULL,
associated_provider_id bigint,
visit_occurrence_id bigint,
relevant_condition_concept_id bigint,
observation_source_value character varying(50) NOT NULL,
unit_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_obs_comment character varying(500),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.observation
OWNER TO rosita;
-- Table: omop.observation_period
DROP TABLE omop.observation_period;
CREATE TABLE omop.observation_period
(
observation_period_id bigint NOT NULL DEFAULT nextval('omop.omop_obs_period_sq'),
person_id bigint NOT NULL,
observation_period_start_date date NOT NULL,
observation_period_end_date date NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.observation_period
OWNER TO rosita;
-- Table: omop.organization
DROP TABLE omop.organization;
CREATE TABLE omop.organization
(
organization_id bigint NOT NULL DEFAULT nextval('omop.omop_organization_sq'),
place_of_service_concept_id bigint,
location_id bigint NOT NULL,
organization_source_value character varying(50) NOT NULL,
place_of_service_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.organization
OWNER TO rosita;
-- Index: omop.omop_organization_source_idx
-- DROP INDEX omop.omop_organization_source_idx;
CREATE INDEX omop_organization_source_idx
ON omop.organization
USING btree
(organization_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: omop.payer_plan_period
DROP TABLE omop.payer_plan_period;
CREATE TABLE omop.payer_plan_period
(
payer_plan_period_id bigint NOT NULL DEFAULT nextval('omop.omop_payer_plan_sq'),
person_id bigint NOT NULL,
payer_plan_period_start_date date NOT NULL,
payer_plan_period_end_date date NOT NULL,
payer_source_value character varying(50),
plan_source_value character varying(50),
family_source_value character varying(50),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.payer_plan_period
OWNER TO rosita;
-- Table: omop.person
DROP TABLE omop.person;
CREATE TABLE omop.person
(
person_id bigint NOT NULL,
gender_concept_id bigint NOT NULL,
year_of_birth numeric(4,0) NOT NULL,
month_of_birth numeric(2,0),
day_of_birth numeric(2,0),
race_concept_id bigint NOT NULL,
ethnicity_concept_id bigint NOT NULL,
location_id bigint NOT NULL,
provider_id bigint,
care_site_id bigint,
person_source_value character varying(50),
gender_source_value character varying(50),
race_source_value character varying(50),
ethnicity_source_value character varying(50),
x_organization_id bigint NOT NULL,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.person
OWNER TO rosita;
-- Index: omop.omop_person_source_idx
-- DROP INDEX omop.omop_person_source_idx;
CREATE INDEX omop_person_source_idx
ON omop.person
USING btree
(person_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: omop.procedure_cost
DROP TABLE omop.procedure_cost;
CREATE TABLE omop.procedure_cost
(
procedure_cost_id bigint NOT NULL DEFAULT nextval('omop.omop_proc_cost_sq'),
procedure_occurrence_id bigint NOT NULL,
paid_copay numeric(8,2),
paid_coinsurance numeric(8,2),
paid_toward_deductible numeric(8,2),
paid_by_payer numeric(8,2),
paid_by_coordination_benefits numeric(8,2),
total_out_of_pocket numeric(8,2),
total_paid numeric(8,2),
disease_class_concept_id bigint,
revenue_code_concept_id bigint,
payer_plan_period_id bigint,
disease_class_source_value character varying(50),
revenue_code_source_value character varying(50),
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.procedure_cost
OWNER TO rosita;
-- Table: omop.procedure_occurrence
DROP TABLE omop.procedure_occurrence;
CREATE TABLE omop.procedure_occurrence
(
procedure_occurrence_id bigint NOT NULL DEFAULT nextval('omop.omop_proc_occur_sq'),
person_id bigint NOT NULL,
procedure_concept_id bigint NOT NULL,
procedure_date date NOT NULL,
procedure_type_concept_id bigint NOT NULL,
associated_provider_id bigint,
visit_occurrence_id bigint,
relevant_condition_concept_id bigint,
procedure_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.procedure_occurrence
OWNER TO rosita;
-- Table: omop.provider
DROP TABLE omop.provider;
CREATE TABLE omop.provider
(
provider_id bigint NOT NULL DEFAULT nextval('omop.omop_provider_sq'),
npi character varying(50),
dea character varying(50),
specialty_concept_id bigint,
care_site_id bigint,
provider_source_value character varying(50) NOT NULL,
specialty_source_value character varying(50),
x_data_source_type character varying(20) NOT NULL,
x_provider_first character varying(75),
x_provider_middle character varying(75),
x_provider_last character varying(75),
x_organization_id bigint NOT NULL,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.provider
OWNER TO rosita;
-- Index: omop.omop_provider_source_idx
-- DROP INDEX omop.omop_provider_source_idx;
CREATE INDEX omop_provider_source_idx
ON omop.provider
USING btree
(provider_source_value COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
-- Table: omop.visit_occurrence
DROP TABLE omop.visit_occurrence;
CREATE TABLE omop.visit_occurrence
(
visit_occurrence_id bigint NOT NULL,
person_id bigint NOT NULL,
visit_start_date date NOT NULL,
visit_end_date date NOT NULL,
place_of_service_concept_id bigint NOT NULL,
care_site_id bigint,
place_of_service_source_value character varying(50),
x_visit_occurrence_source_identifier character varying(50) NOT NULL,
x_data_source_type character varying(20) NOT NULL,
x_provider_id bigint,
x_grid_node_id bigint NOT NULL
)
WITH (
OIDS=FALSE
)
TABLESPACE rosita_data;
ALTER TABLE omop.visit_occurrence
OWNER TO rosita;
-- Index: omop.omop_visit_occurrence_source_idx
-- DROP INDEX omop.omop_visit_occurrence_source_idx;
CREATE INDEX omop_visit_occurrence_source_idx
ON omop.visit_occurrence
USING btree
(x_visit_occurrence_source_identifier COLLATE pg_catalog."default" )
TABLESPACE rosita_indx;
|
9497c9442700a6e3ffc769c3ca8d0a6af513686b
|
[
"SQL",
"Shell"
] | 5
|
SQL
|
lober/rosita-database
|
34b948ae1a8a69df451678ef2e36affeebeb869a
|
61c4ee605c8b27cbf29d2003bd56fff38953ae44
|
refs/heads/master
|
<file_sep>var magicNumber;
var count;
var track = [];
$(document).ready(function(){
/*--- Display information modal box ---*/
$(".what").click(function(){
$(".overlay").fadeIn(1000);
});
/*--- Hide information modal box ---*/
$("a.close").click(function(){
$(".overlay").fadeOut(1000);
});
/*---Add number to #guessList---*/
$('#guessButton').click(function() {
var value = $('#userGuess').val();
var container = $("<div/>", {class:"container"});
$( container ).appendTo("#guessList");
var number = $("<div/>", {class:"number", text:value});
$( number ).appendTo( container );
userGuess();
$('#userGuess').val('');
});
/*--- Runs a new game and calls ---*/
$('.new').click(newGame);
newGame();
});
/*--- Set magicNumber ---*/
function newGame() {
magicNumber = getMagicNumber();
count = 0;
track = [];
$('#guessList').empty();
$('#feedback').text("Make your Guess!");
$('#count').text("0");
}
/*--- Generate magic number ---*/
function getMagicNumber() {
return Math.floor((Math.random() * 100) + 1);
}
/*--- Check that input meets criteria ---*/
function check () {
var userGuess = $('#userGuess').val();
/*--- Checks if input is a number ---*/
var isNumber = true;
for (i=0; i<userGuess.length; i++) {
var c = userGuess[i];
isNumber = isNumber && (c >= '0' && c <= '9' );
}
if (isNumber = true) {
if ((+userGuess < 1) && (+userGuess > 100)) {
alert("Please input a number between 1 and 100");
return false;
}
} else {
alert("Please enter a number!");
return false;
}
return true;
}
/*--- Give user feedback ---*/
function userGuess() {
if (check()) {
var userGuess = +($('#userGuess').val());
count++;
$('#count').text(count);
track.push(userGuess);
if (magicNumber == userGuess) {
$('#feedback').text("You win!");
} else if (Math.abs(magicNumber - userGuess) <= 10) {
$('#feedback').text("So hot right now!");
} else if (Math.abs(magicNumber - userGuess) <= 20) {
$('#feedback').text("Warm");
} else if (Math.abs(magicNumber - userGuess) <= 40) {
$('#feedback').text("Cool");
} else {
$('#feedback').text("Ice cooold!");
}
}
}
/*--- Count attempts ---*/
function count() {
count++;
}
/*--- Find repeats ---*/
|
52340a235f6c26915b203d07757b9c6123ef1fd7
|
[
"JavaScript"
] | 1
|
JavaScript
|
agrushcow/hot-or-cold
|
6edcda25d619c1a116b01903411a8c38e44d8d6a
|
29c925b1ee84a962916ee26e174f83cb00845037
|
refs/heads/master
|
<repo_name>paf31/purescript-preface<file_sep>/src/Boolean.js
"use strict";
exports.and = function(x) {
return function(y) {
return x && y;
};
};
exports.or = function(x) {
return function(y) {
return x || y;
};
};
exports.not = function(x) {
return !x;
};
<file_sep>/src/Number.js
"use strict";
exports.add = function(x) {
return function(y) {
return x + y;
};
};
exports.subtract = function(x) {
return function(y) {
return x - y;
};
};
exports.multiply = function(x) {
return function(y) {
return x * y;
};
};
exports.divide = function(x) {
return function(y) {
return x / y;
};
};
exports.remainder = function(x) {
return function(y) {
return x % y;
};
};
exports.max = function(x) {
return function(y) {
return Math.max(x, y);
};
};
exports.min = function(x) {
return function(y) {
return Math.min(x, y);
};
};
exports.lt = function(x) {
return function(y) {
return x < y;
};
};
exports.lte = function(x) {
return function(y) {
return x <= y;
};
};
exports.gt = function(x) {
return function(y) {
return x > y;
};
};
exports.gte = function(x) {
return function(y) {
return x >= y;
};
};
<file_sep>/docs/Array.md
## Module Array
#### `map`
``` purescript
map :: forall a b. (a -> b) -> Array a -> Array b
```
Create a new `Array` by applying a function to the elements of another `Array`.
#### `filter`
``` purescript
filter :: forall a. (a -> Boolean) -> Array a -> Array a
```
Create a new `Array` by keeping those elements of another `Array` for which the specified function
returns `true`.
#### `fold`
``` purescript
fold :: forall a acc. (acc -> a -> acc) -> acc -> Array a -> acc
```
"Fold" the elements of the array, using a function to combine each element with the current accumulator.
#### `concat`
``` purescript
concat :: forall a. Array a -> Array a -> Array a
```
Concatenate the elements of two arrays
<file_sep>/docs/Either.md
## Module Either
#### `Either`
``` purescript
data Either a b
= Left a
| Right b
```
The `Either` type constructor is used to describe values which are constructed using values
from one of two types.
`Either` is sometimes used to express _values or errors_, with errors on the `Left` and successful results
on the `Right`.
#### `mapLeft`
``` purescript
mapLeft :: forall r a b. (a -> b) -> Either a r -> Either b r
```
Change values constructed using `Left` by applying a function.
#### `mapRight`
``` purescript
mapRight :: forall l a b. (a -> b) -> Either l a -> Either l b
```
Change values constructed using `Right` by applying a function.
#### `bind`
``` purescript
bind :: forall e a b. Either e a -> (a -> Either e b) -> Either e b
```
Try one computation, and then try another which depends on its result.
<file_sep>/docs/Maybe.md
## Module Maybe
#### `Maybe`
``` purescript
data Maybe a
= Nothing
| Just a
```
The `Maybe` type constructor is used to describe values which might be _missing_.
`Maybe` is an alternative to using `null` in other languages.
#### `getOrElse`
``` purescript
getOrElse :: forall a. a -> Maybe a -> a
```
Get the value from a `Maybe a`, if it is present, or using a default value, if not.
#### `bind`
``` purescript
bind :: forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
```
Try one computation, and then try another which depends on its result.
<file_sep>/docs/Preface.md
## Module Preface
The `Preface` is an alternative to the `Prelude` which can be used for teaching purposes.
See the individual modules' documentation for details:
- [`Array`](Array.md) - Functions on arrays: maps, folds, etc.
- [`Boolean`](Boolean.md) - Basic boolean algebra.
- [`Either`](Either.md) - A simple example of an _algebraic data type_.
- [`Function`](Function.md) - Constructions on functions - composition, application, etc.
- [`Maybe`](Maybe.md) - A data structure which may or may not contain a value.
- [`Number`](Number.md) - Functions and operators on numbers.
- [`String`](String.md) - Functions and operators on strings.
- [`Task`](Task.md) - A simple model for code with side-effects.
### Re-exported from Array:
#### `map`
``` purescript
map :: forall a b. (a -> b) -> Array a -> Array b
```
Create a new `Array` by applying a function to the elements of another `Array`.
#### `fold`
``` purescript
fold :: forall a acc. (acc -> a -> acc) -> acc -> Array a -> acc
```
"Fold" the elements of the array, using a function to combine each element with the current accumulator.
#### `filter`
``` purescript
filter :: forall a. (a -> Boolean) -> Array a -> Array a
```
Create a new `Array` by keeping those elements of another `Array` for which the specified function
returns `true`.
#### `concat`
``` purescript
concat :: forall a. Array a -> Array a -> Array a
```
Concatenate the elements of two arrays
### Re-exported from Boolean:
#### `or`
``` purescript
or :: Boolean -> Boolean -> Boolean
```
Boolean OR.
#### `not`
``` purescript
not :: Boolean -> Boolean
```
Boolean negation.
#### `and`
``` purescript
and :: Boolean -> Boolean -> Boolean
```
Boolean AND.
#### `(||)`
``` purescript
infixr 2 or as ||
```
#### `(&&)`
``` purescript
infixr 3 and as &&
```
### Re-exported from Either:
#### `Either`
``` purescript
data Either a b
= Left a
| Right b
```
The `Either` type constructor is used to describe values which are constructed using values
from one of two types.
`Either` is sometimes used to express _values or errors_, with errors on the `Left` and successful results
on the `Right`.
#### `mapRight`
``` purescript
mapRight :: forall l a b. (a -> b) -> Either l a -> Either l b
```
Change values constructed using `Right` by applying a function.
#### `mapLeft`
``` purescript
mapLeft :: forall r a b. (a -> b) -> Either a r -> Either b r
```
Change values constructed using `Left` by applying a function.
### Re-exported from Function:
#### `flip`
``` purescript
flip :: forall a b c. (a -> b -> c) -> b -> a -> c
```
Flip the order of the first two arguments of a function.
#### `const`
``` purescript
const :: forall a b. a -> b -> a
```
Create a function which returns its first argument and ignores its second.
#### `compose`
``` purescript
compose :: forall a b c. (b -> c) -> (a -> b) -> a -> c
```
Compose two functions, i.e. create a function which applies one function and then the other.
#### `apply`
``` purescript
apply :: forall a b. (a -> b) -> a -> b
```
Apply a function to an argument.
#### `(<<<)`
``` purescript
infixr 9 compose as <<<
```
#### `($)`
``` purescript
infixr 0 apply as $
```
### Re-exported from Maybe:
#### `Maybe`
``` purescript
data Maybe a
= Nothing
| Just a
```
The `Maybe` type constructor is used to describe values which might be _missing_.
`Maybe` is an alternative to using `null` in other languages.
#### `getOrElse`
``` purescript
getOrElse :: forall a. a -> Maybe a -> a
```
Get the value from a `Maybe a`, if it is present, or using a default value, if not.
### Re-exported from Number:
#### `subtract`
``` purescript
subtract :: Number -> Number -> Number
```
Subtract a `Number` from another.
#### `remainder`
``` purescript
remainder :: Number -> Number -> Number
```
Find the remainder after division
#### `multiply`
``` purescript
multiply :: Number -> Number -> Number
```
Multiply two `Number`s.
#### `min`
``` purescript
min :: Number -> Number -> Number
```
Find the minimum of two numbers.
#### `max`
``` purescript
max :: Number -> Number -> Number
```
Find the maximum of two numbers.
#### `lte`
``` purescript
lte :: Number -> Number -> Boolean
```
Test whether one value is less than or equal to another.
#### `lt`
``` purescript
lt :: Number -> Number -> Boolean
```
Test whether one value is less than another.
#### `gte`
``` purescript
gte :: Number -> Number -> Boolean
```
Test whether one value is greater than or equal to another.
#### `gt`
``` purescript
gt :: Number -> Number -> Boolean
```
Test whether one value is greater than another.
#### `divide`
``` purescript
divide :: Number -> Number -> Number
```
Divide a `Number` by another.
#### `add`
``` purescript
add :: Number -> Number -> Number
```
Add two `Number`s.
#### `(>=)`
``` purescript
infixl 4 gte as >=
```
#### `(>)`
``` purescript
infixl 4 lte as >
```
#### `(<=)`
``` purescript
infixl 4 gt as <=
```
#### `(<)`
``` purescript
infixl 4 lt as <
```
#### `(/)`
``` purescript
infixl 7 divide as /
```
#### `(-)`
``` purescript
infixl 6 subtract as -
```
#### `(+)`
``` purescript
infixl 6 add as +
```
#### `(*)`
``` purescript
infixl 7 multiply as *
```
#### `(%)`
``` purescript
infixl 7 remainder as %
```
### Re-exported from String:
#### `append`
``` purescript
append :: String -> String -> String
```
Append two `String`s.
#### `(++)`
``` purescript
infixr 5 append as ++
```
### Re-exported from Task:
#### `Task`
``` purescript
data Task :: * -> *
```
A `Task` represents a computation which can have side-effects.
#### `sequence_`
``` purescript
sequence_ :: forall a. Array (Task a) -> Task Unit
```
Perform a sequence of tasks, ignoring the results.
#### `sequence`
``` purescript
sequence :: forall a. Array (Task a) -> Task (Array a)
```
Perform a sequence of tasks, collecting the results.
#### `pure`
``` purescript
pure :: forall a. a -> Task a
```
Create a `Task` which returns a value with no side-effects.
#### `log`
``` purescript
log :: String -> Task Unit
```
Create a `Task` which logs a `String` to the console.
#### `bind`
``` purescript
bind :: forall a b. Task a -> (a -> Task b) -> Task b
```
Create a `Task` which combines two `Task`s, passing the result of the first to a function,
which determines the second.
### Re-exported from Unit:
#### `Unit`
``` purescript
data Unit
```
A type with only one value.
#### `unit`
``` purescript
unit :: Unit
```
The only value of the `Unit` type.
<file_sep>/docs/Task.md
## Module Task
#### `Task`
``` purescript
data Task :: * -> *
```
A `Task` represents a computation which can have side-effects.
#### `pure`
``` purescript
pure :: forall a. a -> Task a
```
Create a `Task` which returns a value with no side-effects.
#### `bind`
``` purescript
bind :: forall a b. Task a -> (a -> Task b) -> Task b
```
Create a `Task` which combines two `Task`s, passing the result of the first to a function,
which determines the second.
#### `log`
``` purescript
log :: String -> Task Unit
```
Create a `Task` which logs a `String` to the console.
#### `sequence`
``` purescript
sequence :: forall a. Array (Task a) -> Task (Array a)
```
Perform a sequence of tasks, collecting the results.
#### `sequence_`
``` purescript
sequence_ :: forall a. Array (Task a) -> Task Unit
```
Perform a sequence of tasks, ignoring the results.
<file_sep>/docs/Boolean.md
## Module Boolean
#### `(&&)`
``` purescript
infixr 3 and as &&
```
#### `(||)`
``` purescript
infixr 2 or as ||
```
#### `and`
``` purescript
and :: Boolean -> Boolean -> Boolean
```
Boolean AND.
#### `or`
``` purescript
or :: Boolean -> Boolean -> Boolean
```
Boolean OR.
#### `not`
``` purescript
not :: Boolean -> Boolean
```
Boolean negation.
<file_sep>/src/Task.js
"use strict";
exports.pure = function(a) {
return function() {
return a;
};
};
exports.bind = function(t) {
return function(f) {
return function() {
var a = t();
return f(a)();
};
};
};
exports.log = function(s) {
return function() {
console.log(s);
return {};
};
};
<file_sep>/docs/String.md
## Module String
#### `(++)`
``` purescript
infixr 5 append as ++
```
#### `append`
``` purescript
append :: String -> String -> String
```
Append two `String`s.
<file_sep>/README.md
# purescript-preface
A simpler alternative to the Prelude.
- [Module Documentation](docs/Preface.md)
- [Example](test/Main.purs)
## Getting Started
Clone this repository. Then, using [Pulp](https://github.com/bodil/pulp):
pulp build
pulp test
## Design
The Preface is intended to be a simpler introduction to the concepts of PureScript for beginners, specifically those
coming from Javascript. With that in mind, here are some design goals:
- Use simple types - no type classes, effect rows, etc.
- Provide excellent documentation with examples.
- Name functions using simple names which explain their purpose.
The Preface is meant to be a _teaching tool_, such that users should plan to graduate to the regular set of PureScript core libraries once they are familiar with the ideas. However, the Preface may be a practical alternative for some very simple tasks.
<file_sep>/docs/Function.md
## Module Function
#### `apply`
``` purescript
apply :: forall a b. (a -> b) -> a -> b
```
Apply a function to an argument.
#### `($)`
``` purescript
infixr 0 apply as $
```
#### `compose`
``` purescript
compose :: forall a b c. (b -> c) -> (a -> b) -> a -> c
```
Compose two functions, i.e. create a function which applies one function and then the other.
#### `(<<<)`
``` purescript
infixr 9 compose as <<<
```
#### `flip`
``` purescript
flip :: forall a b c. (a -> b -> c) -> b -> a -> c
```
Flip the order of the first two arguments of a function.
#### `const`
``` purescript
const :: forall a b. a -> b -> a
```
Create a function which returns its first argument and ignores its second.
<file_sep>/docs/Number.md
## Module Number
#### `(+)`
``` purescript
infixl 6 add as +
```
#### `(-)`
``` purescript
infixl 6 subtract as -
```
#### `(*)`
``` purescript
infixl 7 multiply as *
```
#### `(/)`
``` purescript
infixl 7 divide as /
```
#### `add`
``` purescript
add :: Number -> Number -> Number
```
Add two `Number`s.
#### `subtract`
``` purescript
subtract :: Number -> Number -> Number
```
Subtract a `Number` from another.
#### `multiply`
``` purescript
multiply :: Number -> Number -> Number
```
Multiply two `Number`s.
#### `divide`
``` purescript
divide :: Number -> Number -> Number
```
Divide a `Number` by another.
#### `remainder`
``` purescript
remainder :: Number -> Number -> Number
```
Find the remainder after division
#### `(%)`
``` purescript
infixl 7 remainder as %
```
#### `max`
``` purescript
max :: Number -> Number -> Number
```
Find the maximum of two numbers.
#### `min`
``` purescript
min :: Number -> Number -> Number
```
Find the minimum of two numbers.
#### `(<)`
``` purescript
infixl 4 lt as <
```
#### `(>)`
``` purescript
infixl 4 lte as >
```
#### `(<=)`
``` purescript
infixl 4 gt as <=
```
#### `(>=)`
``` purescript
infixl 4 gte as >=
```
#### `lt`
``` purescript
lt :: Number -> Number -> Boolean
```
Test whether one value is less than another.
#### `lte`
``` purescript
lte :: Number -> Number -> Boolean
```
Test whether one value is less than or equal to another.
#### `gt`
``` purescript
gt :: Number -> Number -> Boolean
```
Test whether one value is greater than another.
#### `gte`
``` purescript
gte :: Number -> Number -> Boolean
```
Test whether one value is greater than or equal to another.
<file_sep>/docs/Unit.md
## Module Unit
#### `Unit`
``` purescript
data Unit
```
A type with only one value.
#### `unit`
``` purescript
unit :: Unit
```
The only value of the `Unit` type.
|
0cf64edd03c4df7f9e7d88a3d45c4f05567fd68e
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
paf31/purescript-preface
|
d27463db6ac0905e3cc05def6643d1adc6f6e2d6
|
d203ddfed917e15f9143efdbaf95ccbdc4f585e5
|
refs/heads/master
|
<repo_name>weikee94/freecodecamp<file_sep>/Basic_Algorithm_Scripting/return_largest_numbers_in_arrays.js
/*
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].
Remember to use Read-Search-Ask if you get stuck. Write your own code.
Here are some helpful links:
Comparison Operators
*/
function largestOfFour(arr) {
// You can do this!
var tArr = [];
var maxInEachArr;
for(var i = 0; i < arr.length; i++){
maxInEachArr = Math.max.apply(null,arr[i]);
tArr.push(maxInEachArr);
}
return tArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
<file_sep>/Basic_Algorithm_Scripting/find_the_longest_word_in_a_string.js
/*
Return the length of the longest word in the provided sentence.
Your response should be a number.
*/
function findLongestWord(str) {
var max = 0;
var strArr = str.split(" ");
for(var i = 0; i < strArr.length; i ++){
if(strArr[i].length > max){
max = strArr[i].length;
}
}
return max;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
<file_sep>/Basic_Javascript/testing_objects_for_properties.js
/* Instruction
Modify the function checkObj to test myObj for checkProp.
If the property is found, return that property's value. If not, return "Not Found".
return myObj[checkProp] - take from the object myObj property with name which we store in checkProp variable and return its value.
Square brackets - because this is the way how you can get access to the property of an object or element of an array or array-like structure.
Although JS has dot notation as alternative to bracket notation, but it don't work in this case. Because dot notation require real name property but not string in variable (which we have here). Yoy can't use parenthesis in this case at all.
*/
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
if(myObj.hasOwnProperty(checkProp)){
return myObj[checkProp];
// cant use return myObj.checkProp it will return nothing because dot notation require real name to
// access the element but not string in variable
}else{
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
console.log(myObj.gift);
<file_sep>/Basic_Algorithm_Scripting/chunky_monkey.js
/*
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
Remember to use Read-Search-Ask if you get stuck. Write your own code.
Here are some helpful links:
Array.prototype.push()
Array.prototype.slice()
*/
function chunkArrayInGroups(arr, size) {
// Break it up
var result =[];
for(var i = 0; i <arr.length; i+=size){
var tArr = arr.slice(i,i+size);
console.log(tArr);
result.push(tArr);
}
return result;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
<file_sep>/Intermediate_Algorithm_Scripting/sum_all_numbers_in_a_range.js
/*
We'll pass you an array of two numbers.
Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Math.max()
Math.min()
Array.prototype.reduce()
*/
function sumAll(arr) {
var mxx = Math.max.apply(null,arr);
var mnn = Math.min.apply(null,arr);
var tArr = [];
for(var i = mnn; i <= mxx ; i++){
tArr.push(i);
}
console.log(tArr);
var ans = tArr.reduce(function(a,b){return a + b; },0);
return ans;
}
sumAll([1, 4]);
<file_sep>/Basic_Javascript/updating_object_properties.js
// Instruction
//Here's how we update his object's name property:
//ourDog.name = "<NAME>"; or
//ourDog["name"] = "<NAME>";
//Now when we evaluate ourDog.name, instead of getting "Camper", we'll get his new name, "<NAME>".
//Update the myDog object's name property. Let's change her name from "Coder" to "<NAME>". You can use either dot or bracket notation.
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.name = "<NAME>";
// Setup
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["Free Code Camp Campers"]
};
// Only change code below this line.
//Method One
myDog.name = "<NAME>";
//Method Two
console.log(myDog["name"] = "<NAME>");
<file_sep>/Basic_Javascript/return_early_pattern_for_functions.html
// Instructions
Modify the function abTest so that if a or b are less than 0 the function will immediately exit with a value of undefined.
And remember that undefined is a keyword not a string.
// Setup
<script>
function abTest(a, b) {
// Only change code below this line
if ((a < 0 ) || (b < 0)){
return undefined;
}
// Only change code above this line
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
</script>
// Change values below to test your code
abTest(2,2);
<file_sep>/Basic_Algorithm_Scripting/title_case_a_sentence.js
/*
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
Remember to use Read-Search-Ask if you get stuck. Write your own code.
Here are some helpful links:
String.prototype.split()
*/
function titleCase(str) {
var arr = str.split(" ");
var combineArr = [];
var resultArr = [];
for(var i = 0; i<arr.length; i++){
var upperArr = [];
var lowerArr = [];
for(var j = 0; j < arr[i].length; j++){
if(j === 0){
upperArr.push(arr[i][j].toUpperCase());
}else{
lowerArr.push(arr[i][j].toLowerCase());
}
combineArr = upperArr.concat(lowerArr).join("");
}
resultArr.push(combineArr);
}
return resultArr.join(" ");
}
titleCase("I'm a little tea pot");
<file_sep>/README.md
# freecodecamp
Record what i learnt through freecodecamp and solutions for the coding challenge and projects.
<file_sep>/Basic_Javascript/manipulating_complex_objects.js
/*JavaScript Object Notation or JSON is a related data interchange format used to store data.
{
"artist": "<NAME>",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
Note
You will need to place a comma after every object in the array, unless it is the last object in the array.
Instructions
Add a new album to the myMusic array. Add artist and title strings, release_year number, and a formats array of strings.
*/
var myMusic = [
{
"artist": "<NAME>",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CS",
"8T",
"LP" ],
"gold": true
},
{
"artist" : "JB",
"title" : "BF",
"release_year" : 2015,
"formats" : [
"SC",
"T8",
"PL"
]
}
// Add record here
];
|
6fd8d7980901d64e41935accb459e630253690ed
|
[
"JavaScript",
"HTML",
"Markdown"
] | 10
|
JavaScript
|
weikee94/freecodecamp
|
4ad581456fa9b7ca2f69ffc1ab2f910a5a773439
|
c72bde11a1fc7d3a058c84f5c1f8754bc032a4a6
|
refs/heads/master
|
<file_sep>AMVideoRangeSlider
============
iOS Video Range Slider in Swift

### Code
```swift
let videoRangeSlider = AMVideoRangeSlider(frame: CGRectMake(16, 16, 300, 20))
let url = NSBundle.mainBundle().URLForResource("video", withExtension: "mp4")
videoRangeSlider.videoAsset = AVAsset(URL: url!)
videoRangeSlider.delegate = self
```
### Delegate Methods
```swift
func rangeSliderLowerThumbValueChanged() {
print(self.videoRangeSlider.startTime.seconds)
}
func rangeSliderMiddleThumbValueChanged() {
print(self.videoRangeSlider.currentTime.seconds)
}
func rangeSliderUpperThumbValueChanged() {
print(self.videoRangeSlider.stopTime.seconds)
}
```
## Installation
### CocoaPods
You can install the latest release version of CocoaPods with the following command:
```bash
$ gem install cocoapods
```
*CocoaPods v0.36 or later required*
Simply add the following line to your Podfile:
```ruby
platform :ios, '8.0'
use_frameworks!
pod 'AMVideoRangeSlider', :git => 'https://github.com/iAmrMohamed/AMVideoRangeSlider.git'
```
Then, run the following command:
```bash
$ pod install
```
### Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.
You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
```bash
$ brew update
$ brew install carthage
```
To integrate AMVideoRangeSlider into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "iAmrMohamed/AMVideoRangeSlider"
```
## Requirements
- iOS 8.0+
- Xcode 7.3+
## License
AMVideoRangeSlider is released under the MIT license. See LICENSE for details.
<file_sep>//
// ViewController.swift
// VideoRangeSlider
//
// Created by <NAME> on 7/7/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
import AMVideoRangeSlider
class ViewController: UIViewController , AMVideoRangeSliderDelegate {
@IBOutlet weak var videoRangeSlider: AMVideoRangeSlider!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSBundle.mainBundle().URLForResource("video", withExtension: "mp4")
self.videoRangeSlider.videoAsset = AVAsset(URL: url!)
self.videoRangeSlider.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func rangeSliderLowerThumbValueChanged() {
print(self.videoRangeSlider.startTime.seconds)
}
func rangeSliderMiddleThumbValueChanged() {
print(self.videoRangeSlider.currentTime.seconds)
}
func rangeSliderUpperThumbValueChanged() {
print(self.videoRangeSlider.stopTime.seconds)
}
}<file_sep>//
// RangeSlider.swift
// VideoPlayer
//
// Created by <NAME> on 4/5/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
// 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.
import UIKit
import QuartzCore
import AVFoundation
internal class AMVideoRangeSliderThumbLayer: CAShapeLayer {
var highlighted = false
weak var rangeSlider : AMVideoRangeSlider?
override func layoutSublayers() {
super.layoutSublayers()
self.cornerRadius = self.bounds.width / 2
self.setNeedsDisplay()
}
override func drawInContext(ctx: CGContext) {
CGContextMoveToPoint(ctx, self.bounds.width/2, self.bounds.height/5)
CGContextAddLineToPoint(ctx, self.bounds.width/2 , self.bounds.height - self.bounds.height/5)
CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor)
CGContextStrokePath(ctx)
}
}
internal class AMVideoRangeSliderTrackLayer: CAShapeLayer {
weak var rangeSlider : AMVideoRangeSlider?
override func drawInContext(ctx: CGContext) {
if let slider = rangeSlider {
let lowerValuePosition = CGFloat(slider.positionForValue(slider.lowerValue))
let upperValuePosition = CGFloat(slider.positionForValue(slider.upperValue))
let rect = CGRect(x: lowerValuePosition, y: 0.0, width: upperValuePosition - lowerValuePosition, height: bounds.height)
CGContextSetFillColorWithColor(ctx, slider.sliderTintColor.CGColor)
CGContextFillRect(ctx, rect)
}
}
}
public protocol AMVideoRangeSliderDelegate {
func rangeSliderLowerThumbValueChanged()
func rangeSliderMiddleThumbValueChanged()
func rangeSliderUpperThumbValueChanged()
}
public class AMVideoRangeSlider: UIControl {
public var middleValue = 0.0 {
didSet {
self.updateLayerFrames()
}
}
public var minimumValue: Double = 0.0 {
didSet {
self.updateLayerFrames()
}
}
public var maximumValue: Double = 1.0 {
didSet {
self.updateLayerFrames()
}
}
public var lowerValue: Double = 0.0 {
didSet {
self.updateLayerFrames()
}
}
public var upperValue: Double = 1.0 {
didSet {
self.updateLayerFrames()
}
}
public var videoAsset : AVAsset? {
didSet {
self.generateVideoImages()
}
}
public var currentTime : CMTime {
return CMTimeMakeWithSeconds(self.videoAsset!.duration.seconds * self.middleValue, self.videoAsset!.duration.timescale)
}
public var startTime : CMTime! {
return CMTimeMakeWithSeconds(self.videoAsset!.duration.seconds * self.lowerValue, self.videoAsset!.duration.timescale)
}
public var stopTime : CMTime! {
return CMTimeMakeWithSeconds(self.videoAsset!.duration.seconds * self.upperValue, self.videoAsset!.duration.timescale)
}
public var rangeTime : CMTimeRange! {
let lower = self.videoAsset!.duration.seconds * self.lowerValue
let upper = self.videoAsset!.duration.seconds * self.upperValue
let duration = CMTimeMakeWithSeconds(upper - lower, self.videoAsset!.duration.timescale)
return CMTimeRangeMake(self.startTime, duration)
}
public var sliderTintColor = UIColor(red:0.97, green:0.71, blue:0.19, alpha:1.00) {
didSet {
self.lowerThumbLayer.backgroundColor = self.sliderTintColor.CGColor
self.upperThumbLayer.backgroundColor = self.sliderTintColor.CGColor
}
}
public var middleThumbTintColor : UIColor! {
didSet {
self.middleThumbLayer.backgroundColor = self.middleThumbTintColor.CGColor
}
}
public var delegate : AMVideoRangeSliderDelegate?
var middleThumbLayer = AMVideoRangeSliderThumbLayer()
var lowerThumbLayer = AMVideoRangeSliderThumbLayer()
var upperThumbLayer = AMVideoRangeSliderThumbLayer()
var trackLayer = AMVideoRangeSliderTrackLayer()
var previousLocation = CGPoint()
var thumbWidth : CGFloat {
return 15
}
var thumpHeight : CGFloat {
return self.bounds.height + 10
}
public override var frame: CGRect {
didSet {
self.updateLayerFrames()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
public required init(coder : NSCoder) {
super.init(coder: coder)!
self.commonInit()
}
public override func layoutSubviews() {
self.updateLayerFrames()
}
func commonInit() {
self.trackLayer.rangeSlider = self
self.middleThumbLayer.rangeSlider = self
self.lowerThumbLayer.rangeSlider = self
self.upperThumbLayer.rangeSlider = self
self.layer.addSublayer(self.trackLayer)
self.layer.addSublayer(self.middleThumbLayer)
self.layer.addSublayer(self.lowerThumbLayer)
self.layer.addSublayer(self.upperThumbLayer)
self.middleThumbLayer.backgroundColor = UIColor.greenColor().CGColor
self.lowerThumbLayer.backgroundColor = self.sliderTintColor.CGColor
self.upperThumbLayer.backgroundColor = self.sliderTintColor.CGColor
self.trackLayer.contentsScale = UIScreen.mainScreen().scale
self.lowerThumbLayer.contentsScale = UIScreen.mainScreen().scale
self.upperThumbLayer.contentsScale = UIScreen.mainScreen().scale
self.updateLayerFrames()
}
func updateLayerFrames() {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.trackLayer.frame = self.bounds
self.trackLayer.setNeedsDisplay()
let middleThumbCenter = CGFloat(self.positionForValue(self.middleValue))
self.middleThumbLayer.frame = CGRect(x: middleThumbCenter - self.thumbWidth / 2, y: -5.0, width: 2, height: self.thumpHeight)
let lowerThumbCenter = CGFloat(self.positionForValue(self.lowerValue))
self.lowerThumbLayer.frame = CGRect(x: lowerThumbCenter - self.thumbWidth / 2, y: -5.0, width: self.thumbWidth, height: self.thumpHeight)
let upperThumbCenter = CGFloat(self.positionForValue(self.upperValue))
self.upperThumbLayer.frame = CGRect(x: upperThumbCenter - self.thumbWidth / 2, y: -5.0, width: self.thumbWidth, height: self.thumpHeight)
CATransaction.commit()
}
func positionForValue(value: Double) -> Double {
return Double(self.bounds.width - self.thumbWidth) * (value - self.minimumValue) / (self.maximumValue - self.minimumValue) + Double(self.thumbWidth / 2.0)
}
public override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
self.previousLocation = touch.locationInView(self)
if self.lowerThumbLayer.frame.contains(self.previousLocation) {
self.lowerThumbLayer.highlighted = true
} else if self.upperThumbLayer.frame.contains(self.previousLocation) {
self.upperThumbLayer.highlighted = true
} else {
self.middleThumbLayer.highlighted = true
}
return self.lowerThumbLayer.highlighted || self.upperThumbLayer.highlighted || self.middleThumbLayer.highlighted
}
func boundValue(value: Double, toLowerValue lowerValue: Double, upperValue: Double) -> Double {
return min(max(value, lowerValue), upperValue)
}
public override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
let deltaLocation = Double(location.x - self.previousLocation.x)
let deltaValue = (self.maximumValue - self.minimumValue) * deltaLocation / Double(self.bounds.width - self.thumbWidth)
let newMiddle = Double(self.previousLocation.x) / Double(self.bounds.width - self.thumbWidth)
self.previousLocation = location
if self.lowerThumbLayer.highlighted {
if deltaValue > 0 && self.rangeTime.duration.seconds <= 1{
} else {
self.lowerValue += deltaValue
self.lowerValue = self.boundValue(self.lowerValue, toLowerValue: self.minimumValue, upperValue: self.maximumValue)
self.delegate?.rangeSliderLowerThumbValueChanged()
}
} else if self.middleThumbLayer.highlighted {
self.middleValue = newMiddle
self.middleValue = self.boundValue(self.middleValue, toLowerValue: self.lowerValue, upperValue: self.upperValue)
self.delegate?.rangeSliderMiddleThumbValueChanged()
} else if self.upperThumbLayer.highlighted {
if deltaValue < 0 && self.rangeTime.duration.seconds <= 1 {
} else {
self.upperValue += deltaValue
self.upperValue = self.boundValue(self.upperValue, toLowerValue: self.minimumValue, upperValue: self.maximumValue)
self.delegate?.rangeSliderUpperThumbValueChanged()
}
}
self.sendActionsForControlEvents(.ValueChanged)
return true
}
public override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
self.lowerThumbLayer.highlighted = false
self.middleThumbLayer.highlighted = false
self.upperThumbLayer.highlighted = false
}
func generateVideoImages() {
dispatch_async(dispatch_get_main_queue(), {
self.lowerValue = 0.0
self.upperValue = 1.0
for subview in self.subviews {
if subview is UIImageView {
subview.removeFromSuperview()
}
}
let imageGenerator = AVAssetImageGenerator(asset: self.videoAsset!)
let assetDuration = CMTimeGetSeconds(self.videoAsset!.duration)
var Times = [NSValue]()
let numberOfImages = Int((self.frame.width / self.frame.height))
for index in 1...numberOfImages {
let point = CMTimeMakeWithSeconds(assetDuration/Double(index), 600)
Times += [NSValue(CMTime: point)]
}
Times = Times.reverse()
let imageWidth = self.frame.width/CGFloat(numberOfImages)
var imageFrame = CGRect(x: 0, y: 2, width: imageWidth, height: self.frame.height-4)
imageGenerator.generateCGImagesAsynchronouslyForTimes(Times) { (requestedTime, image, actualTime, result, error) in
if error == nil {
if result == AVAssetImageGeneratorResult.Succeeded {
dispatch_async(dispatch_get_main_queue(), {
let imageView = UIImageView(image: UIImage(CGImage: image!))
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.frame = imageFrame
imageFrame.origin.x += imageWidth
self.insertSubview(imageView, atIndex:1)
})
}
if result == AVAssetImageGeneratorResult.Failed {
print("Generating Fail")
}
} else {
print("Error at generating images : \(error!.description)")
}
}
})
}
}
|
b14251b1b7e9f6d92bc6ddac147bce97da10baab
|
[
"Markdown",
"Swift"
] | 3
|
Markdown
|
iAmrMohamed/AMVideoRangeSlider
|
cbd011c6741c64343e26bd53078e3a9fa1be5256
|
a6746e6bdb8cc9914c874a731244501afbe6a83e
|
refs/heads/master
|
<repo_name>MahmoudAbusaqer/VolunteerWorkSystem-VWS<file_sep>/src/View/AddInstitutionsScreen.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import Controller.AddInstitutionsManager;
import Model.AddInstitutions;
import Model.Student;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
/**
*
* @author Mahmoud_Abusaqer
*/
public class AddInstitutionsScreen implements Initializable, Create {
private AddInstitutions model;
private AddInstitutionsManager controller;
static Student student;
@Override
public void initialize(URL url, ResourceBundle rb) {
this.controller = new AddInstitutionsManager(model);
this.model = new AddInstitutions();
}
public void AddInstitutionInput(String name, String email, String address, int phone, String district, int studentId, String studentName) {
controller.AddInstitutionInput(name, address, email, phone, district, studentId, studentName);
}
public static Student getStudent() {
return student;
}
public static void setStudent(Student student) {
AddInstitutionsScreen.student = student;
}
@FXML
private Pane rootpane;
@FXML
private Button ButtonMainPage;
@FXML
private Button ButtonApplyVolunteerPage;
@FXML
private Button ButtonCreateIntitivePage;
@FXML
private Button ButtonStudentMailBox;
@FXML
private Button ExitButton;
@FXML
private TextField TextFieldInstitutionName;
@FXML
private TextField TextFieldInstitutionMail;
@FXML
private TextField TextFieldInstitutionDistrict;
@FXML
private TextField TextFieldInstitutionAddress;
@FXML
private TextField TextFieldInstitutionPhone;
@FXML
private Button ButtonSubmit;
@FXML
@Override
public void buttonSubmit(ActionEvent event) {
AddInstitutionInput(TextFieldInstitutionName.getText(), TextFieldInstitutionMail.getText(), TextFieldInstitutionAddress.getText(), Integer.parseInt(TextFieldInstitutionPhone.getText()), TextFieldInstitutionDistrict.getText(), student.getId(), student.getName());
try {
TextFieldInstitutionName.setText("");
TextFieldInstitutionMail.setText("");
TextFieldInstitutionDistrict.setText("");
TextFieldInstitutionAddress.setText("");
TextFieldInstitutionPhone.setText("");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("process succeeded");
alert.setContentText("You can continue now, you will be notified when the DOV respond 😄");
alert.showAndWait();
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setContentText("Try again later");
alert.showAndWait();
}
}
@FXML
void buttonMainPage(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/StudentGUI/MainPage.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonApplyVolunteerPage(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/StudentGUI/InstitutionScreen.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonCreateIntitivePage(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/StudentGUI/AddInitiative.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonStudentMailBox(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/StudentGUI/StudentMailBox.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void ButtonExit(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/MainPage/StartPage.fxml"));
rootpane.getChildren().setAll(pane);
}
}
<file_sep>/src/View/StartPagePanes.java
package View;
import Controller.LoginPageManager;
import Model.DOV;
import Model.Institutions;
import Model.Student;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
/**
*
* @author Mahmoud_Abusaqer
*/
public class StartPagePanes implements Initializable {
private DOV dov = null;
private Student student = null;
private Institutions institutions = null;
private LoginPageManager controller;
@FXML
private Button buttonLogin;
@FXML
private PasswordField TextFieldPass;
@FXML
private TextField TextFieldID;
@FXML
private Button InstitutionButton;
@FXML
private Button DOVButton;
@FXML
private Button StudentButton;
@FXML
private Pane loginPagePane;
@FXML
private Pane startPagePane;
@FXML
private AnchorPane rootpane;
@Override
public void initialize(URL url, ResourceBundle rb) {
startPagePane.toFront();
startPagePane.setVisible(true);
loginPagePane.setVisible(false);
this.controller = new LoginPageManager();
}
@FXML
void DOVButton(ActionEvent event) throws SQLException, IOException {
loginPagePane.toFront();
startPagePane.setVisible(false);
loginPagePane.setVisible(true);
dov = new DOV();
buttonLoginHandle(event);
}
@FXML
void InstitutionButton(ActionEvent event) throws SQLException, IOException {
loginPagePane.toFront();
startPagePane.setVisible(false);
loginPagePane.setVisible(true);
institutions = new Institutions();
buttonLoginHandle(event);
}
@FXML
void StudentButton(ActionEvent event) throws SQLException, IOException {
loginPagePane.toFront();
startPagePane.setVisible(false);
loginPagePane.setVisible(true);
student = new Student();
buttonLoginHandle(event);
}
@FXML
void buttonLoginHandle(ActionEvent event) throws SQLException, IOException {
try {
if (!TextFieldID.getText().equals("") && !TextFieldPass.getText().equals("")) {
if (student != null) {
student = controller.checkStudent(Integer.parseInt(TextFieldID.getText()), TextFieldPass.getText());
if (student != null) {
RequestScreen.setStudent(student);
CreateInitiativeScreen.setStudent(student);
AddInstitutionsScreen.setStudent(student);
StudentMailboxScreen.setStudent(student);
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/StudentGUI/MainPage.fxml"));
rootpane.getChildren().setAll(pane);
}
} else if (institutions != null) {
institutions = controller.checkInstitution(Integer.parseInt(TextFieldID.getText()), TextFieldPass.getText());
if (institutions != null) {
StatisticsScreenInstitution.setInstitutions(institutions);
ReportScreen.setInstitutions(institutions);
ViewNewVolunteersScreen.setInstitutions(institutions);
InstitutionMailboxScreen.setInstitutions(institutions);
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/StatisticsScreenInstitution.fxml"));
rootpane.getChildren().setAll(pane);
}
} else if (dov != null) {
dov = controller.checkDOV(Integer.parseInt(TextFieldID.getText()), TextFieldPass.getText());
if (dov != null) {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/DOVGUI/StatisticsScreen.fxml"));
rootpane.getChildren().setAll(pane);
}
}
}
} catch (NullPointerException e) {
}
}
public void checkStudent(int studentId, String password) throws SQLException {
controller.checkStudent(studentId, password);
}
}
<file_sep>/src/View/Shows.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import java.sql.SQLException;
/**
*
* @author Mahmoud_Abusaqer
*/
public interface Shows {
void showMailbox(int id) throws SQLException;
void showNewVolunteers(int institutionId) throws SQLException;
}
<file_sep>/src/Controller/ReportManager.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.DBConnection;
import Model.DOVMailbox;
import Model.Report;
import Model.Student;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Mahmoud_Abusaqer
*/
//This class is only for the Institutions to send a report to the DOVMailbox when a student completes all the hours required to pass the volunteer course.
public class ReportManager implements SendToDOV {
private Report reportModel;
private Student studentModel;
private DOVMailbox dOVMailboxModel;
private Connection connection;
public ReportManager(Report reportModel) {
this.reportModel = reportModel;
this.studentModel = new Student();
this.dOVMailboxModel = new DOVMailbox();
connection = DBConnection.getConnection();
}
public List<Student> showStudent(int institutionId) throws SQLException {
List<Student> students = new ArrayList<>();
PreparedStatement preparedStatement = connection.prepareStatement("select * from vws.viewnewvolunteers where institutionId=?;");
preparedStatement.setInt(1, institutionId);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Student Student = new Student();
Student.setId(resultSet.getInt(2));
Student.setName(resultSet.getString(3));
Student.setFaculty(resultSet.getString(4));
Student.setAddress(resultSet.getString(5));
Student.setEmail(resultSet.getString(6));
Student.setPhone(resultSet.getInt(7));
students.add(Student);
}
return students;
}
public void reportInput(int studentId, String studentName, int institutionId, String report) {
Report report1 = new Report();
report1.setStudentId(studentId);
report1.setStudentName(studentName);
report1.setInstitutionId(institutionId);
report1.setReport(report);
add(report1);
DOVMailbox dOVMailbox = new DOVMailbox();
dOVMailbox.setSenderId(studentId);
dOVMailbox.setSenderName(studentName);
dOVMailbox.setTitle("A new finish report from an institution ");
dOVMailbox.setBody("The student: " + studentName + " with the id: " + studentId + " who volunteered in institution: " + institutionId + " and here is the institution report: " + report + ".");
dOVMailbox.setDate(new java.sql.Timestamp(System.currentTimeMillis()));
dOVMailbox.setTypeOfMail("finish vlounteer");
sendToDOV(dOVMailbox);
}
public void add(Report newObject) {
try {
PreparedStatement statement = connection.prepareStatement("insert into vws.institutionreport(studentId, studentName, institutionId, report) values (?, ?, ?, ?)");
statement.setInt(1, newObject.getStudentId());
statement.setString(2, newObject.getStudentName());
statement.setInt(3, newObject.getInstitutionId());
statement.setString(4, newObject.getReport());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void sendToDOV(DOVMailbox newObject) {
try {
PreparedStatement statement = connection.prepareStatement("insert into dovmailbox(senderId, senderName, title, body, date, approveOrDeny, typeOfMail, sendfor) values (?, ?, ?, ?, ?, ?, ?, ?)");
statement.setInt(1, newObject.getSenderId());
statement.setString(2, newObject.getSenderName());
statement.setString(3, newObject.getTitle());
statement.setString(4, newObject.getBody());
statement.setDate(5, new java.sql.Date(newObject.getDate().getTime()));
statement.setBoolean(6, newObject.isApproveOrDeny());
statement.setString(7, newObject.getTypeOfMail());
statement.setInt(8, newObject.getSenderId());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/View/ViewNewVolunteersScreen.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import Controller.ViewNewVolunteersManager;
import Model.Institutions;
import Model.ViewNewVolunteers;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.Pane;
/**
*
* @author Mahmoud_Abusaqer
*/
public class ViewNewVolunteersScreen implements Initializable, Shows {
private ViewNewVolunteers model;
private ViewNewVolunteersManager controller;
static Institutions institutions;
@Override
public void initialize(URL url, ResourceBundle rb) {
this.controller = new ViewNewVolunteersManager(model);
TableColAddress.setCellValueFactory(new PropertyValueFactory("address"));
// TableColFaculty.setCellValueFactory(new PropertyValueFactory("faculty"));
TableColMail.setCellValueFactory(new PropertyValueFactory("email"));
TableColPhone.setCellValueFactory(new PropertyValueFactory("phone"));
TableColStudent.setCellValueFactory(new PropertyValueFactory("name"));
try {
showNewVolunteers(institutions.getId());
} catch (SQLException ex) {
Logger.getLogger(ViewNewVolunteersScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void showNewVolunteers(int institutionId) throws SQLException {
List<ViewNewVolunteers> newVolunteerses = new ArrayList<>();
newVolunteerses = controller.showNewVolunteers(institutionId);
TableView.getItems().setAll(newVolunteerses);
}
public static Institutions getInstitutions() {
return institutions;
}
public static void setInstitutions(Institutions institutions) {
ViewNewVolunteersScreen.institutions = institutions;
}
@FXML
private Pane rootpane;
@FXML
private Button ButtonStatisticsInstitution;
@FXML
private Button ButtonAddReportPage;
@FXML
private Button ButtonInstitutionMailBox;
@FXML
private Button ExitButton;
@FXML
private TableView<ViewNewVolunteers> TableView;
@FXML
private TableColumn<ViewNewVolunteers, Integer> TableColPhone;
@FXML
private TableColumn<ViewNewVolunteers, String> TableColMail;
@FXML
private TableColumn<ViewNewVolunteers, String> TableColAddress;
@FXML
private TableColumn<ViewNewVolunteers, String> TableColStudent;
@FXML
void buttonAddReportPage(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/ReportScreen.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonInstitutionMailBox(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/InstitutionMailBox.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonStatisticsInstitution(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/StatisticsScreenInstitution.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void ButtonExit(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/MainPage/StartPage.fxml"));
rootpane.getChildren().setAll(pane);
}
@Override
public void showMailbox(int id) throws SQLException {
}
}
<file_sep>/src/Model/DBConnection.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author Mahmoud_Abusaqer
*/
public class DBConnection {
private static Connection connection = null;
private DBConnection() {
}
public static Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/vws?serverTimezone=UTC",
"root", "123456");
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
}
return connection;
}
}
}
<file_sep>/src/Controller/InstitutionMailboxManager.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.DBConnection;
import Model.InstitutionMailbox;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Mahmoud_Abusaqer
*/
//This class is only for the Institutions to see their mailbox and if they have new mail from the DOV.
public class InstitutionMailboxManager {
private InstitutionMailbox model;
private Connection connection;
public InstitutionMailboxManager(InstitutionMailbox model) {
this.model = model;
connection = DBConnection.getConnection();
}
public List<InstitutionMailbox> showMailbox(int id) throws SQLException {
List<InstitutionMailbox> institutionMailboxs = new ArrayList<>();
PreparedStatement preparedStatement = connection.prepareStatement("select * from vws.institutionmailbox where sendfor=? or sendfor=0;;");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
InstitutionMailbox institutionMailbox = new InstitutionMailbox();
institutionMailbox.setSenderId(resultSet.getInt(2));
institutionMailbox.setSenderName(resultSet.getString(3));
institutionMailbox.setTitle(resultSet.getString(4));
institutionMailbox.setBody(resultSet.getString(5));
institutionMailbox.setDate(resultSet.getDate(6));
institutionMailbox.setApproveOrDeny(resultSet.getBoolean(7));
institutionMailboxs.add(institutionMailbox);
}
return institutionMailboxs;
}
}
<file_sep>/src/Model/StatisticsDoV.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
/**
*
* @author Mahmoud_Abusaqer
*/
public class StatisticsDoV {
private int id;
private int volunteersNumbers;
private int institutionsNumbers;
private int finishedVolunteersNumbers;
private int initiatives;
private int activeVolunteers;
private int activeInitiatives;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVolunteersNumbers() {
return volunteersNumbers;
}
public void setVolunteersNumbers(int volunteersNumbers) {
this.volunteersNumbers = volunteersNumbers;
}
public int getInstitutionsNumbers() {
return institutionsNumbers;
}
public void setInstitutionsNumbers(int institutionsNumbers) {
this.institutionsNumbers = institutionsNumbers;
}
public int getFinishedVolunteersNumbers() {
return finishedVolunteersNumbers;
}
public void setFinishedVolunteersNumbers(int finishedVolunteersNumbers) {
this.finishedVolunteersNumbers = finishedVolunteersNumbers;
}
public int getInitiatives() {
return initiatives;
}
public void setInitiatives(int initiatives) {
this.initiatives = initiatives;
}
public int getActiveVolunteers() {
return activeVolunteers;
}
public void setActiveVolunteers(int activeVolunteers) {
this.activeVolunteers = activeVolunteers;
}
public int getActiveInitiatives() {
return activeInitiatives;
}
public void setActiveInitiatives(int activeInitiatives) {
this.activeInitiatives = activeInitiatives;
}
}
<file_sep>/src/Controller/ViewNewVolunteersManager.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.DBConnection;
import Model.ViewNewVolunteers;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Mahmoud_Abusaqer
*/
//This class is only for the Institutions to see all the new volunteers in the Institution.
public class ViewNewVolunteersManager {
private ViewNewVolunteers model;
private Connection connection;
public ViewNewVolunteersManager(ViewNewVolunteers model) {
this.model = model;
connection = DBConnection.getConnection();
}
public List<ViewNewVolunteers> showNewVolunteers(int institutionId) throws SQLException {
List<ViewNewVolunteers> newVolunteerses = new ArrayList<>();
PreparedStatement preparedStatement = connection.prepareStatement("select * from vws.viewnewvolunteers where institutionId=?;");
preparedStatement.setInt(1, institutionId);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
ViewNewVolunteers viewNewVolunteers = new ViewNewVolunteers();
viewNewVolunteers.setId(resultSet.getInt(2));
viewNewVolunteers.setName(resultSet.getString(3));
viewNewVolunteers.setFaculty(resultSet.getString(4));
viewNewVolunteers.setAddress(resultSet.getString(5));
viewNewVolunteers.setEmail(resultSet.getString(6));
viewNewVolunteers.setPhone(resultSet.getInt(7));
newVolunteerses.add(viewNewVolunteers);
}
return newVolunteerses;
}
}
<file_sep>/src/View/StatisticsScreenInstitution.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import Controller.StatisticManagerInstitution;
import Model.Institutions;
import Model.StatisticsInstitution;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
/**
*
* @author Mahmoud_Abusaqer
*/
public class StatisticsScreenInstitution implements Initializable, Statistics {
private StatisticsInstitution model;
private StatisticManagerInstitution controller;
static Institutions institutions;
@FXML
private Button ButtonNewVolunteers;
@FXML
private Button ButtonReportPage;
@FXML
private Button ButtonInstitutionMailBox;
@Override
public void initialize(URL url, ResourceBundle rb) {
this.controller = new StatisticManagerInstitution(model);
try {
showStatistics(institutions.getId());
} catch (SQLException ex) {
Logger.getLogger(StatisticsScreenInstitution.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void showStatistics(int institutionId) throws SQLException {
List<StatisticsInstitution> statisticsInstitutions = new ArrayList<>();
statisticsInstitutions = controller.showStatistics(institutionId);
int index = 0;
while (!statisticsInstitutions.isEmpty()) {
StatisticsInstitution institution = new StatisticsInstitution();
institution = statisticsInstitutions.get(index);
labelFinishedVolunteers.setText(String.valueOf(institution.getStudentsFinishedNumbers()));
labelNumbersOfVolunteers.setText(String.valueOf(institution.getNumberOfAllStudents()));
labelActiveVolunteers.setText(String.valueOf(institution.getActiveVolunteers()));
statisticsInstitutions.remove(index);
index++;
}
}
public static Institutions getInstitutions() {
return institutions;
}
public static void setInstitutions(Institutions institutions) {
StatisticsScreenInstitution.institutions = institutions;
}
@FXML
private Pane rootpane;
@FXML
private Button ExitButton;
@FXML
private Label labelNumbersOfVolunteers;
@FXML
private Label labelFinishedVolunteers;
@FXML
private Label labelActiveVolunteers;
@FXML
void buttonInstitutionMailBox(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/InstitutionMailBox.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonNewVolunteers(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/ViewsNewVolunteers.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void buttonReportPage(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/InstitutionGUI/ReportScreen.fxml"));
rootpane.getChildren().setAll(pane);
}
@FXML
void ButtonExit(ActionEvent event) throws IOException {
Pane pane = FXMLLoader.load(getClass().getResource("SceneBuilder/MainPage/StartPage.fxml"));
rootpane.getChildren().setAll(pane);
}
}
<file_sep>/README.md
# VolunteerWorkSystem-VWS
System Overall Description
The Volunteer Work System is a system for students, the Department of Voluntary at IUG, and Institutions. To help get and finish the volunteer work in an easy way and online, without going to the Department of Voluntary Work at the university and using papers and letters to communicate.
The student will be able to choose the place to volunteer in and send a request to that institution, he/she can create initiative and also will be able to suggest institutions too.
Institutions will see all the new forms form students who requested to volunteer in it, send reports to the university when a student finishes all the hours required to pass the volunteer work course, and it will have statistics about the number of students who are still volunteering, finished, and requesting to volunteer there.
The University will keep tracking of all the operation that happens in the system, it will approve or deny the requests for students to volunteer in an institution, the requests of institutions to be in the system, and the reports of the students who finished the volunteer work, it will have statistics for all the number of students who still volunteering, finished, requesting to volunteer and need approve of finishing the volunteer work, put news and announcements about the department, and it can be able to add new institutions too.
What was implemented in this project:
- An MVC Architecture system in Java.
- All the functionality described above.
- Different design patterns like MVC, Singleton, Factory, Façade, and Strategy.
- Appropriate collections and functional programming to process data.
- Apply object-oriented concepts.
- A look-and-feel GUI using JavaFX.
- Connect to MySQL database throw JDBC and by using MySQL Workbench.
- A full report about the system with different diagrams like Use Case Diagram, Sequence Diagrams, Application Architecture, Inter- Package Dependencies, ER-Digram, and Packages Detailed Design
|
28c0942b91818ac9e744f83bc63db328f720738f
|
[
"Markdown",
"Java"
] | 11
|
Java
|
MahmoudAbusaqer/VolunteerWorkSystem-VWS
|
833b8d753d238fd46ae960f8ad8c61841f4dd350
|
9895773499426f3531b8035ee4023df948431e55
|
refs/heads/master
|
<repo_name>hulihuli/webpackOnboardingTool<file_sep>/src/app/templates/payloadDiffViewTable/payloadDiffViewTable.component.ts
import { BaseComponent } from "../../components/common/base.component";
import { OnInit, Component, Input, Output, EventEmitter } from "@angular/core";
import { ViewerPayloadDiffProperty, ViewerPayloadDiff } from "../../core/viewer/PayloadDiffViewer";
import { ViewerService } from "../../components/viewer/viewer.service";
import { ViewerType } from "../../core/enums";
@Component({
selector: "payload-diff-viewer-table",
templateUrl: "./payloadDiffViewTable.component.html",
styles: [require('./payloadDiffViewTable.component.scss').toString()]
})
export class PayloadDiffViewerTableComponent extends BaseComponent implements OnInit {
@Input() displayType: ViewerType;
@Input() isFetchingPayloadDiffViewer?: boolean;
@Output() isFetchingPayloadDiffViewerChange = new EventEmitter<boolean>();
public properties: Array<ViewerPayloadDiffProperty>;
public displayCommon: boolean;
public expandAll: boolean;
public payloadDiffResult: object;
constructor(private viewerService: ViewerService) {
super();
}
ngOnInit() {
this.displayCommon = true;
this.expandAll = false;
this.properties = new Array<ViewerPayloadDiffProperty>();
}
getViewerPayloadDiffProperties(viewerType: ViewerType, modelIdStr: string, externalId1: string, externalId2: string, standardEpRelativeStreamPath: string, triageEpRelativeStreamPath?: string) {
this.isFetchingPayloadDiffViewer = true;
this.isFetchingPayloadDiffViewerChange.emit(this.isFetchingPayloadDiffViewer);
this.viewerService
.getViewerPayloadDiff(viewerType, modelIdStr, externalId1, externalId2, standardEpRelativeStreamPath, triageEpRelativeStreamPath)
.subscribe(payloadDiffResult => {
this.payloadDiffResult = payloadDiffResult;
this.properties = payloadDiffResult.payloadDiffProperties;
this.isFetchingPayloadDiffViewer = false;
this.isFetchingPayloadDiffViewerChange.emit(this.isFetchingPayloadDiffViewer);
},
(error: any) => {
this.isFetchingPayloadDiffViewer = false;
this.isFetchingPayloadDiffViewerChange.emit(this.isFetchingPayloadDiffViewer);
});
}
}
<file_sep>/src/app/components/common/base.component.ts
import { Component, OnInit } from '@angular/core';
import {
HttpClient,
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpParams,
HttpHeaders,
HttpResponse
} from "@angular/common/http";
import {
AnalysisType,
EntitySpaceViewVersionState,
ViewerType,
WorkItemState,
TriageAnalysisResultDiaplayType,
EntitySpaceViewState ,
ReportType,
MissSlaType
} from '../../core/enums';
import { JobType, JobState } from '../../core/job/job';
import { Logger } from '../../helper/logger';
// @Component({
// selector: 'app-name',
// templateUrl: './name.component.html',
// styleUrls: ['./name.component.scss']
// })
export class BaseComponent implements OnInit {
AnalysisType: typeof AnalysisType = AnalysisType;
JobType: typeof JobType = JobType;
JobState: typeof JobState = JobState;
EntitySpaceViewVersionState: typeof EntitySpaceViewVersionState = EntitySpaceViewVersionState;
EntitySpaceViewState: typeof EntitySpaceViewState = EntitySpaceViewState;
ViewerType: typeof ViewerType = ViewerType;
WorkItemState: typeof WorkItemState = WorkItemState;
TriageAnalysisResultDiaplayType: typeof TriageAnalysisResultDiaplayType = TriageAnalysisResultDiaplayType;
ReportType: typeof ReportType = ReportType;
MissSlaType: typeof MissSlaType = MissSlaType;
logger: Logger = new Logger("onboardingToolLogger");
constructor() { }
ngOnInit() { }
}<file_sep>/src/app/templates/payloadDiffViewTable/payloadDiffViewTable.module.ts
import { FormsModule } from "@angular/forms";
import { NgModule } from "@angular/core";
import { NgxChartsModule } from "@swimlane/ngx-charts";
import { PayloadDiffViewerTableComponent } from "./payloadDiffViewTable.component";
import { NgxJsonViewerModule } from "../ngxJsonViewer/ngxJsonViewer.module";
import { UiSwitchModule } from "ngx-ui-switch";
import { CommonModule } from "../../../../node_modules/@angular/common";
@NgModule({
imports: [
CommonModule,
FormsModule,
NgxChartsModule,
NgxJsonViewerModule,
UiSwitchModule
],
exports: [
PayloadDiffViewerTableComponent
],
declarations: [
PayloadDiffViewerTableComponent
]
})
export class PayLoadDiffViewerTableModule {}<file_sep>/src/app/core/job/AetherJob.ts
import { JobState } from "./job"
import{ environment } from "../../../../config/environment/environment"
export class AetherJob
{
constructor(
public id?: number,
public hostId?: number,
public resultId?: number,
public aetherExperimentId?: string,
public cosmosJobUrl?: string,
public completePercent?: string,
// JobState
public state?: JobState,
public cloudPriority?: number,
public virtualCluster?: string,
public relativeTriageAnalysisOutputFolder?: string,
public submitBy?: string,
public cancelBy?: string,
// run time info
public numAttempts?: number,
public submitTime?: string,
public startTime?: string,
public endTime?: string,
public queuedTime?: string,
public runningTime?: string,
public Logs?: string,
public Errors?: string
)
{
this.id = -1;
this.hostId = -1;
this.resultId = -1;
this.virtualCluster = environment.defaultVC;//"https://cosmos08.osdinfra.net/cosmos/Knowledge.STCA.prod/";//"https://cosmos08.osdinfra.net/cosmos/Knowledge/";
this.cloudPriority = environment.defaultCouldPriority;
this.state = JobState.Waiting;
}
}<file_sep>/src/app/templates/jobPanel/jobPanel.component.ts
import { Component, OnInit, Input, Output, EventEmitter, SimpleChanges } from "@angular/core";
import { Observable, BehaviorSubject } from "rxjs/Rx";
import { JobType, JobState, JobPanelState } from "../../core/job/job";
import { AetherJob } from "../../core/job/AetherJob";
import { BaseComponent } from "../../components/common/base.component";
@Component({
selector: "job-panel",
templateUrl: "./jobPanel.component.html",
styles: [require("./jobPanel.component.scss").toString()]
})
export class JobPanelComponent extends BaseComponent implements OnInit {
//job: AetherJob = new AetherJob();// = new Job(1, 1, JobType.EntityViewStatistic, JobStatus.Waiting);
//isRunning: boolean;
virtualClusters: Array<string> = ["https://cosmos08.osdinfra.net/cosmos/Knowledge/", "https://cosmos08.osdinfra.net/cosmos/Knowledge.STCA.prod/"];
hostId: number;
timer: Observable<number>;
//isForceSubmission: boolean;
//the way to pass async object
// private _job = new BehaviorSubject<AetherJob>(new AetherJob());
// // change data to use getter and setter
// @Input()
// set job(value) {
// // set the latest value for _data BehaviorSubject
// this._job.next(value);
// };
// get job() {
// // get the latest value from _data BehaviorSubject
// return this._job.getValue();
// }
//cloudPriority: number;
//obText: string;
@Input() jobType: JobType;
@Input() isForceSubmission: boolean;
// @Input() virtualCluster: string;
// @Input() cloudPriority: number;
@Input() job: AetherJob;
@Input() submitJob: Function;
@Input() getJobState: Function;
@Input() cancelJob: Function;
@Input() reloadPage: Function;
@Input() jobPanelState: JobPanelState;
@Output() jobChange: EventEmitter<AetherJob> = new EventEmitter();
@Output() isForceSubmissionChange: EventEmitter<boolean> = new EventEmitter();
// @Output() virtualClusterChange: EventEmitter<string> = new EventEmitter();
// @Output() cloudPriorityChange: EventEmitter<number> = new EventEmitter();
// @Output() submitJob: EventEmitter<any> = new EventEmitter();
// @Output() getJobState: EventEmitter<any> = new EventEmitter();
// @Output() cancelJob: EventEmitter<any> = new EventEmitter();
// @Output() reloadPage: EventEmitter<any> = new EventEmitter();
get jobText(): string {
return `${JobType[this.jobType]} Job`;
}
constructor() {
super();
}
ngOnInit() {
//this.virtualCluster = "https://cosmos08.osdinfra.net/cosmos/Knowledge/";
//this.cloudPriority = 1000;
this.job = new AetherJob();
}
submit() {
//this.cloudPriorityChange.emit(this.cloudPriority);
//this.logger.info("cloudPriority-directive", this.cloudPriority);
//this.virtualClusterChange.emit(this.virtualCluster);
//this.logger.info("cloudPriority-directive", this.virtualCluster);
this.jobChange.emit(this.job);
this.isForceSubmissionChange.emit(this.isForceSubmission);
//this.submitJob.emit(null);
this.submitJob();
this.logger.info(this.jobType);
}
// getState(){
// this.getJobState();
// switch (this.job.state) {
// case JobState.UnKnown: {
// //return AnalysisType.EntitySpace;
// }
// case JobState.Waiting: {
// //return AnalysisType.EntitySpace;
// }
// case JobState.Running: {
// //return AnalysisType.EntitySpace;
// }
// case JobState.Succeeded: {
// //this.reloadPage.emit(null);
// }
// case JobState.Failed: {
// //return AnalysisType.EntitySpace;
// }
// case JobState.Canceled: {
// //return AnalysisType.EntitySpace;
// }
// case JobState.TimeOut: {
// //return AnalysisType.EntitySpace;
// }
// }
// }
cancel() {
//this.cancelJob.emit(null);
this.cancelJob();
}
}
<file_sep>/src/app/pipe/displayTypeFilterPipe.ts
import { Injectable, Pipe, PipeTransform } from "@angular/core";
import { Constants } from "../core/common/constants";
@Pipe({
name: 'displayTypeFilter',
pure: false
})
@Injectable()
export class DisplayTypeFilterPipe implements PipeTransform {
transform(supervisors: any[], displayType: any) {
if (displayType === "LongToGraph") {
return supervisors.filter(supervisor =>
(supervisor.originalState == "EveryVersion" && Number(supervisor.latestSucceedVersionLatency) > Constants.everyVersionLimit) ||
(supervisor.originalState == "MajorVersion" && Number(supervisor.latestSucceedVersionLatency) > Constants.majorVersionLimit) ||
(supervisor.originalState == "Manual" && Number(supervisor.latestSucceedVersionLatency) > Constants.manualLimit)
)
}
else if (displayType === "MissState") {
return supervisors.filter(supervisor => supervisor.currentState != supervisor.originalState)
}
else {
return supervisors.filter(supervisor => displayType === 'All' || supervisor.latestVersionState === displayType);
}
}
}
<file_sep>/src/app/pipe/FilterPipe.ts
import { Pipe, PipeTransform } from "@angular/core";
import { BaseComponent } from "../components/common/base.component";
@Pipe({
name: "filter",
pure: false
})
export class FilterPipe extends BaseComponent implements PipeTransform {
public i = 0;
traverse(item: any, query: string): boolean {
this.logger.info(item);
if (this.i > 100) {
return true;
}
if (typeof item !== "object") {
return item.toString().indexOf(query) !== -1;
}
for (var property in item) {
this.i++;
//this.logger.info(item[property]);
if (Array.isArray(item[property])) {
this.logger.info("Array", this.i, item[property]);
// item[property].forEach((t: any) => {
// this.logger.info("t", t);
// if (this.traverse(t, query)) {
// return true;
// }
// });
var len = item[property].length;
for(var i = 0; i < len; i++) {
if (this.traverse(item[property][i], query)) {
return true;
}
}
} else {
this.logger.info("NotArray", this.i, item[property], typeof item[property]);
if (typeof item[property] !== "object") {
this.logger.info("aa", item[property].toString());
this.logger.info("bb", item[property].toString().indexOf(query));
if (item[property].toString().indexOf(query) !== -1) {
this.logger.info("true result");
return true;
}
}else {
this.logger.info("ss", item[property]);
return this.traverse(item[property], query);
}
}
}
return false;
}
transform(items: any[], query: string): any {
if (!items || !query) {
return items;
}
this.logger.info(query);
// filter items array, items which match and return true will be
// kept, false will be filtered out
return items.filter(item => this.traverse(item, query));
// return items.filter(item => {
// this.traverse(item, query);
// // for (var property in item) {
// // if (Array.isArray(item[property])) {
// // return item[property].some((e: string) => e === query) !== undefined;
// // } else {
// // return item[property].indexOf(query) !== -1;
// // }
// // }
// });
}
}
<file_sep>/src/app/components/viewer/payloadDiffViewer/PayloadDiffViewer.component.ts
import { Component, OnInit, ViewChild } from "@angular/core";
import { BaseComponent } from "../../common/base.component";
import { ViewerType } from "../../../core/enums";
import { PayloadDiffViewerTableComponent } from "../../../templates/payloadDiffViewTable/payloadDiffViewTable.component";
import { Router, ActivatedRoute } from "@angular/router";
@Component({
selector: "payload-diff-viewer",
templateUrl: "./payloadDiffViewer.component.html",
styleUrls: ["./payloadDiffViewer.component.css"],
})
export class PayloadDiffViewerComponent extends BaseComponent implements OnInit {
public viewerType: ViewerType;
public modelIdStr: string;
public externalId1: string;
public externalId2: string;
public standardEpRelativeStreamPath: string;
public triageEpRelativeStreamPath: string;
public isFetchingPayloadDiffViewer: boolean;
public displayCommon: boolean;
constructor(
private route: ActivatedRoute,
private router: Router,
) {
super();
}
@ViewChild(PayloadDiffViewerTableComponent) PayloadDiffViewerTableComponentChild: PayloadDiffViewerTableComponent;//this child is the DiffViewerTable component
ngOnInit() {
this.viewerType = ViewerType.ViewerDiff;
this.standardEpRelativeStreamPath = this.route.snapshot.queryParamMap.get("standardEpRelativeStreamPath");
this.triageEpRelativeStreamPath = this.route.snapshot.queryParamMap.get("triageEpRelativeStreamPath");
this.externalId1 = this.route.snapshot.queryParamMap.get("externalId1");
this.externalId2 = this.route.snapshot.queryParamMap.get("externalId2");
this.modelIdStr = this.route.snapshot.queryParamMap.get("modelIdStr");
let viewerType = this.route.snapshot.queryParamMap.get("viewerType");
switch (viewerType) {
case "0": {
this.viewerType = ViewerType.Viewer;
if (this.standardEpRelativeStreamPath && this.externalId1) {
this.getViewerDiffProperties();
}
break;
};
case "1": {
this.viewerType = ViewerType.ViewerDiff;
if (this.standardEpRelativeStreamPath && this.triageEpRelativeStreamPath && this.externalId1) {
this.getViewerDiffProperties();
}
break;
};
case "2": {
this.viewerType = ViewerType.ViewerDiffOfTwo;
if (this.standardEpRelativeStreamPath && this.triageEpRelativeStreamPath && this.externalId1 && this.externalId2) {
this.getViewerDiffProperties();
}
break;
};
};
}
getViewerDiffProperties() {
//change url params
this.router.navigate(["/viewer/payloadDiff"], {
queryParams: {
"viewerType": this.viewerType,
"modelIdStr": this.modelIdStr ? this.modelIdStr : "",
"externalId1": this.externalId1,
"externalId2": this.externalId2,
"standardEpRelativeStreamPath": this.standardEpRelativeStreamPath,
"triageEpRelativeStreamPath": this.triageEpRelativeStreamPath
}
});
if (this.viewerType != ViewerType.ViewerDiffOfTwo) {
this.externalId2 = "";
}
if (this.viewerType == ViewerType.Viewer) {
this.triageEpRelativeStreamPath = "";
}
this.PayloadDiffViewerTableComponentChild.getViewerPayloadDiffProperties(this.viewerType, this.modelIdStr, this.externalId1, this.externalId2, this.standardEpRelativeStreamPath, this.triageEpRelativeStreamPath);
}
}<file_sep>/src/app/app.module.ts
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms"; //ngModel
import { Ng2Webstorage } from "ngx-webstorage";
//routes
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { AdalService, AdalGuard } from "adal-angular4";
import { AuthenticationGuard } from "./components/loginAuth/authGuard";
import { LoginComponent } from "./components/loginAuth/login/login.component";
import { LogoutComponent } from "./components/loginAuth/logout/logout.component";
//child module
import { EntityAnalysisModule } from "./components/entityAnalysis/entityAnalysis.module";
import { ReportModule } from "./components/report/report.module";
//plugins
//import {SlimLoadingBarModule} from 'ng2-slim-loading-bar'
import { PageNotFoundComponent } from "./components/trivial/pageNotFound.component";
import { ViewerModule } from "./components/viewer/viewer.module";
import { MetricModule } from "./components/metric/metric.module";
import { CommonModule } from "../../node_modules/@angular/common";
import { BrowserModule } from "../../node_modules/@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
@NgModule({
imports: [
FormsModule,
BrowserModule,
BrowserAnimationsModule,
CommonModule,
Ng2Webstorage,
EntityAnalysisModule,
ReportModule,
ViewerModule,
MetricModule,
AppRoutingModule
//SlimLoadingBarModule.forRoot()
],
declarations: [LoginComponent, LogoutComponent, AppComponent, PageNotFoundComponent],
providers: [AdalService, AdalGuard, AuthenticationGuard],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>/deprecated/workItemTable.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'work-item-table',
templateUrl: './WorkItemTable.component.html',
//styleUrls: ['./WorkItemTable.component.css']
})
export class WorkItemTableComponent implements OnInit {
columns: Array<string>;
attributes: Array<string>;
constructor() {
this.columns = ["EntitySpaceName", "CustomerId", "CustomerEnv", "CreatedBy", "UpdatedBy", "Action"];
this.attributes = [];
}
ngOnInit() { }
}<file_sep>/src/app/core/plugin/ngAlert.ts
export class AlertMsg {//alertmsg
constructor(
public title: string,
public type: any,//Type 'string' is not assignable to type 'SweetAlertType'.
public text?: string,
public timer?: number,
) {
}
}<file_sep>/src/app/templates/diffViewerTable/diffViewerTable.component.ts
import { BaseComponent } from "../../components/common/base.component";
import { OnInit, Component, Input, Output, EventEmitter } from "@angular/core";
import { ViewerDiffProperty, ViewerTriple } from "../../core/viewer/entityDiffViewer";
import { ViewerService } from "../../components/viewer/viewer.service";
import { ViewerType } from "../../core/enums";
@Component({
selector: "diff-viewer-table",
templateUrl: "./diffViewerTable.component.html",
styleUrls: ["./diffViewerTable.component.css"]
})
export class DiffViewerTableComponent extends BaseComponent implements OnInit {
@Input() displayType: ViewerType;
@Input() isFetchingEntityDiffViewer?: boolean;
@Output() isFetchingEntityDiffViewerChange = new EventEmitter<boolean>();
public properties: Array<ViewerDiffProperty>;
public displayCommon: boolean;
constructor(private viewerService: ViewerService) {
super();
}
ngOnInit() {
this.displayCommon = true;
this.properties = new Array<ViewerDiffProperty>();
}
getViewerDiffProperties(viewerType: ViewerType, subjectKey1: string, subjectKey2: string, standardStream: string, triagedStream: string) {
this.isFetchingEntityDiffViewer = true;
this.isFetchingEntityDiffViewerChange.emit(this.isFetchingEntityDiffViewer);
this.viewerService
.getViewerTriples(viewerType, subjectKey1, subjectKey2, standardStream, triagedStream)
.subscribe(viewerDiffProperties => {
this.properties = viewerDiffProperties.viewerDiffProperties;
this.isFetchingEntityDiffViewer = false;
this.isFetchingEntityDiffViewerChange.emit(this.isFetchingEntityDiffViewer);
},
(error: any) => {
this.isFetchingEntityDiffViewer = false;
this.isFetchingEntityDiffViewerChange.emit(this.isFetchingEntityDiffViewer);
});
}
}
<file_sep>/src/app/components/triage/triageSupervisor/triageSupervisor.component.ts
import { Component, OnInit, SimpleChanges } from "@angular/core";
import {
TriageViewSupervisor,
TriageViewSupervisorDto
} from "../../../core/triage/triageViewSupervisor";
import { BaseComponent } from "../../common/base.component";
import { TriageService } from "../triage.service";
import { Observable } from "rxjs/Rx";
import { Subscription } from "rxjs/Subscription";
import { LineChart, MultiChartData, SingleChartData, StackedVerticalBarChart } from "../../../core/plugin/ngxChart";
import swal from "sweetalert2";
import { Constants } from "../../../core/common/constants";
import { Router, ActivatedRoute } from "@angular/router";
class TriageSupervisorState {
constructor(
public isLoadingCustomerId?: boolean,
public isLoadingCustomerEnv?: boolean,
public isLoadingEntitySpace?: boolean,
public isLoadingEntitySpaceView?: boolean
) {
// this.isLoadingCustomerId = true;
// this.isLoadingCustomerEnv = true;
// this.isLoadingEntitySpace = true;
// this.isLoadingEntitySpaceView = true;
}
}
@Component({
selector: "triage-supervisor",
templateUrl: "./triageSupervisor.component.html",
styleUrls: ["./triageSupervisor.component.css"]
})
export class TriageSupervisorComponent extends BaseComponent implements OnInit {
currentCustomerId: string;
currentCustomerEnv: string;
currentEntitySpace: string;
currentEntitySpaceView: string;
segment: string;
owner: string;
loadingState: TriageSupervisorState;
customerIds: Array<string>;
customerEnvs: Array<string>;
entitySpaces: Array<string>;
entitySpaceViews: Array<string>;
cumstomerDict: Map<string, Array<string>>;
entitySpaceViewDict: Map<string, Array<string>>;
allTriageViewSupervisors: Array<TriageViewSupervisor>;
triageViewSupervisors: Array<TriageViewSupervisor>;
triageViewSupervisorDto: TriageViewSupervisorDto;
//regular timer
timer: Observable<number>;
timerSubscription: Subscription;
entitySpaceViewRequestSubscription: Subscription;
//ui
displayType: string;
isFetchingViewSupervisor: boolean;
isAddingViewSupervisor: boolean;
versionDelayLineChart: LineChart;
commitDelayLineChart: LineChart;
completeVersionDelayStackedVerticalBarChartResults: Array<MultiChartData>;
purifiedVersionDelayStackedVerticalBarChartResults: Array<MultiChartData>;
originalOwner: string;
originalSegment: string;
//sort
idDesc: boolean;
latestVersionLatencyDesc: boolean;
latestSucceedVersionLatencyDesc: boolean;
//pagination
currentPage: number;
numOfPages: number;
numPerPage: number;
query: string;
constructor(
private triageService: TriageService,
private route: ActivatedRoute,
private router: Router
) {
super();
}
ngOnInit() {
this.currentCustomerId = "WrapStar";
this.currentCustomerEnv = "Prod";
this.currentEntitySpace = "WrapStar-Full";
this.customerIds = new Array<string>();
this.customerEnvs = new Array<string>();
this.entitySpaces = new Array<string>();
this.entitySpaceViews = new Array<string>();
this.cumstomerDict = new Map<string, Array<string>>();
this.entitySpaceViewDict = new Map<string, Array<string>>();
this.loadingState = new TriageSupervisorState();
this.allTriageViewSupervisors = new Array<TriageViewSupervisor>();
this.triageViewSupervisors = new Array<TriageViewSupervisor>();
this.triageViewSupervisorDto = new TriageViewSupervisorDto("WrapStar", "Prod", "WrapStar-Full");
this.timer = Observable.timer(0, 300000);
this.isFetchingViewSupervisor = false;
this.isAddingViewSupervisor = false;
this.numPerPage = 15;
this.currentPage = 1;
this.completeVersionDelayStackedVerticalBarChartResults = new Array<MultiChartData>();
this.purifiedVersionDelayStackedVerticalBarChartResults = new Array<MultiChartData>();
this.loadTriageViewSupervisors();
}
loadViewInfo() {
if (this.customerIds.length == 0) {
this.loadingState = new TriageSupervisorState(true, true, true, true);
//add customerid and customerEnv
this.triageService.getCustomerIds().subscribe(customers => {
customers.forEach(customer => {
this.customerIds.push(customer.customerId);
this.cumstomerDict.set(customer.customerId, customer.customerEnvs);
if (customer.customerId == this.currentCustomerId) {
this.customerEnvs = customer.customerEnvs;
}
});
this.loadingState.isLoadingCustomerId = false;
this.loadingState.isLoadingCustomerEnv = false;
});
//add entitySpaces and entitySpaceViews
this.triageService
.getEntitySpaces(this.currentCustomerId, this.currentCustomerEnv)
.subscribe(entitySpaces => {
entitySpaces.forEach(entitySpace => {
this.entitySpaces.push(entitySpace.entitySpace);
this.entitySpaceViewDict.set(
this.currentCustomerId + this.currentCustomerEnv + entitySpace.entitySpace,
entitySpace.entitySpaceViews
);
if (entitySpace.entitySpace == this.currentEntitySpace) {
this.entitySpaceViews = entitySpace.entitySpaceViews;
if (entitySpace.entitySpaceViews.length > 0) {
this.currentEntitySpaceView = entitySpace.entitySpaceViews[0];
}
}
});
this.loadingState.isLoadingEntitySpace = false;
this.loadingState.isLoadingEntitySpaceView = false;
});
}
}
changeCustomerId() {
this.logger.info(this.currentCustomerId);
this.customerEnvs = this.cumstomerDict.get(this.currentCustomerId);
if (this.customerEnvs.length > 0) {
this.currentCustomerEnv = this.customerEnvs[0];
this.changeCustomerEnv();
}
}
changeCustomerEnv() {
this.loadingState.isLoadingEntitySpace = true;
this.triageService.getEntitySpaces(this.currentCustomerId, this.currentCustomerEnv).subscribe(entitySpaces => {
this.entitySpaces = entitySpaces.map(t => t.entitySpace);
entitySpaces.forEach(entitySpace => {
this.entitySpaceViewDict.set(
this.currentCustomerId + this.currentCustomerEnv + entitySpace.entitySpace,
entitySpace.entitySpaceViews
);
});
if (this.entitySpaces.length > 0) {
this.currentEntitySpace = this.entitySpaces[0];
this.changeEntitySpace();
}
this.loadingState.isLoadingEntitySpace = false;
});
}
changeEntitySpace() {
this.entitySpaceViews = this.entitySpaceViewDict.get(
this.currentCustomerId + this.currentCustomerEnv + this.currentEntitySpace
);
if (this.entitySpaceViews.length > 0) {
this.currentEntitySpaceView = this.entitySpaceViews[0];
}
}
loadTriageViewSupervisors() {
this.displayType = "All";
this.isFetchingViewSupervisor = true;
this.triageService
.getTriageViewSupervisors()
.subscribe(triageViewSupervisors => {
this.triageViewSupervisors = new Array<TriageViewSupervisor>();
//initialize triageviewsupervisor ti amake get/set work
let displayType = this.route.snapshot.queryParamMap.get("displayType");
triageViewSupervisors.forEach(t => {
if(!displayType){
if(t.latestVersionState === "Errored") {
this.displayType = "Errored";
}
else if(this.displayType != "Errored" && t.latestVersionState === "Triaged") {
this.displayType = "Triaged";
}
}
else{
this.displayType = displayType;
}
this.addTriageView(t);
});
this.allTriageViewSupervisors = this.triageViewSupervisors;
this.logger.info(this.triageViewSupervisors);
this.isFetchingViewSupervisor = false;
},
error => {
this.logger.error("fetch view supervisor err:", error);
this.isFetchingViewSupervisor = false;
}
);
}
//since some getters are used in TriageViewSupervisor, it can't work without constructor
addTriageView(triageViewSupervisor: TriageViewSupervisor) {
this.triageViewSupervisors.push(
new TriageViewSupervisor(
triageViewSupervisor.id,
triageViewSupervisor.triageAnalysisId,
triageViewSupervisor.customerId,
triageViewSupervisor.customerEnv,
triageViewSupervisor.entitySpaceName,
triageViewSupervisor.entitySpaceViewName,
triageViewSupervisor.segment,
triageViewSupervisor.currentState,
triageViewSupervisor.originalState,
triageViewSupervisor.latestVersion,
triageViewSupervisor.latestVersionState,
triageViewSupervisor.latestCompletedVersion,
triageViewSupervisor.latestCompletedVersionState,
triageViewSupervisor.latestSucceedTime,
triageViewSupervisor.latestVersionLatency,
triageViewSupervisor.latestSucceedVersionLatency,
triageViewSupervisor.latestStandardVersion,
triageViewSupervisor.latestJobType,
triageViewSupervisor.deletedCount,
triageViewSupervisor.addedCount,
triageViewSupervisor.churnedCount,
triageViewSupervisor.owner,
triageViewSupervisor.tfsUrl
)
);
}
setRefreshTimer() {
this.timerSubscription = this.timer.subscribe(t => {
this.loadTriageViewSupervisors();
});
}
filterView(triageViewSupervisor: TriageViewSupervisor) {
//if the view match current query
let isMatchQuery = false;
if (
this.query == null ||
triageViewSupervisor.entitySpaceViewName == null ||
triageViewSupervisor.entitySpaceViewName.toUpperCase().includes(this.query.toUpperCase())
) {
isMatchQuery = true;
}
//if the view match current display type
let isMatchType = false;
switch (this.displayType) {
case "All":
isMatchType = true;
break;
case "Errored":
isMatchType = triageViewSupervisor.latestVersionState == "Errored";
break;
case "Triaged":
isMatchType = triageViewSupervisor.latestVersionState == "Triaged";
break;
case "Standard":
isMatchType = triageViewSupervisor.latestVersionState == "Standard";
break;
case "Updating":
isMatchType =
triageViewSupervisor.latestVersionState != "Triaged" &&
triageViewSupervisor.latestVersionState != "Standard" &&
triageViewSupervisor.latestVersionState != "Errored";
break;
case "LongToGraph":
isMatchType = this.isMissingSla(triageViewSupervisor);
break;
case "MissState":
isMatchType = triageViewSupervisor.currentState != triageViewSupervisor.originalState;
break;
}
return isMatchType && isMatchQuery;
}
querySupervisor() {
if(this.query == ""){
this.triageViewSupervisors = this.allTriageViewSupervisors;
}
else{
this.triageViewSupervisors = this.allTriageViewSupervisors;
this.triageViewSupervisors = this.triageViewSupervisors.filter(
supervisor =>
supervisor.entitySpaceViewName.toLocaleLowerCase().indexOf(this.query.toLocaleLowerCase()) != -1
);
}
}
addTriageViewSupervisor() {
this.isAddingViewSupervisor = true;
let existView = this.triageViewSupervisors.find(
t =>
t.customerId == this.currentCustomerId &&
t.customerEnv == this.currentCustomerEnv &&
t.entitySpaceName == this.currentEntitySpace &&
t.entitySpaceViewName == this.currentEntitySpaceView
);
if (existView != null) {
swal({
title: this.currentEntitySpaceView + " is already exist !",
type: "error",
timer: 1300
});
this.isAddingViewSupervisor = false;
} else {
this.triageService
.addTriageViewSupervisor(
this.currentCustomerId,
this.currentCustomerEnv,
this.currentEntitySpace,
this.currentEntitySpaceView,
this.segment,
this.owner
)
.subscribe(triageViewSupervisor => {
this.addTriageView(triageViewSupervisor);
this.logger.info(triageViewSupervisor);
this.isAddingViewSupervisor = false;
//hide the supervisor addition modal
(<any>$("#newViewSupervisor")).modal("hide");
});
}
}
expandStatistic(triageViewSupervisor: TriageViewSupervisor) {
triageViewSupervisor.expandStatistic = !triageViewSupervisor.expandStatistic;
if (triageViewSupervisor.expandStatistic) {
this.triageService.getTriageReportDetail(triageViewSupervisor.id, "", "").subscribe(result => {
triageViewSupervisor.averageLatency = result.averageLatency;
triageViewSupervisor.minLatency = result.minLatency;
triageViewSupervisor.maxLatency = result.maxLatency;
triageViewSupervisor.ninetyPercentLatency = result.ninetyLatency;
triageViewSupervisor.getMissSlaBarChart(result.allVersions);
triageViewSupervisor.getMonthlyCountLineChart(result.allVersions);
triageViewSupervisor.getCommitDelayLineChart(result.allVersions);
triageViewSupervisor.getVersionDelayLineChart(result.allVersions);
triageViewSupervisor.getVersionDetailStackedVerticalBarChart(result.allVersions);
});
//at the same time ,only selected one can be expanded
this.triageViewSupervisors.forEach(t => {
if (t.id != triageViewSupervisor.id) {
t.expandStatistic = false;
}
});
}
}
deleteTriageViewSupervisor(id: number) {
swal({
title: "Are you sure to delete this view?",
text: "You won't be able to revert this !",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it !"
}).then(result => {
if (result.value) {
this.triageViewSupervisors = this.triageViewSupervisors.filter(h => h.id !== id);
this.triageService.deleteTriageViewSupervisor(id).subscribe(result => {
if (result.id == id) {
swal({
title: "Deleted !",
text: "The view has been deleted :)",
type: "success",
timer: 1300
});
}
});
}
});
}
changeOwnerName(triageViewSupervisor: TriageViewSupervisor) {
triageViewSupervisor.displayOwnerNameEditor = true;
this.originalOwner = triageViewSupervisor.owner;
this.logger.info("after dblclick name", triageViewSupervisor.owner);
}
changeSegmentName(triageViewSupervisor: TriageViewSupervisor) {
triageViewSupervisor.displaySegmentNameEditor = true;
this.originalSegment = triageViewSupervisor.segment;
this.logger.info("after dblclick segment", triageViewSupervisor.segment);
}
updateOwner(triageViewSupervisor: TriageViewSupervisor) {
if (this.originalOwner != triageViewSupervisor.owner) {
swal({
title: "Are you sure to change the owner of this view?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, continue !"
}).then(result => {
if (result.value) {
triageViewSupervisor.displayOwnerNameEditor = false;
this.logger.info("after blur name", triageViewSupervisor.owner);
this.triageService.updateTriageViewSupervisor(triageViewSupervisor).subscribe(result => {
if (result.id == triageViewSupervisor.id) {
swal({
title: "Save Success !",
text: "The change has been saved :)",
type: "success",
timer: 1300
});
this.logger.info("after change name", triageViewSupervisor.owner);
}
});
}
});
} else {
triageViewSupervisor.displayOwnerNameEditor = false;
}
}
updateSegment(triageViewSupervisor: TriageViewSupervisor) {
if (this.originalSegment != triageViewSupervisor.segment) {
swal({
title: "Are you sure to change the segment of this view?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, continue !"
}).then(result => {
if (result.value) {
triageViewSupervisor.displaySegmentNameEditor = false;
this.logger.info("after blur segment", triageViewSupervisor.segment);
this.triageService.updateTriageViewSupervisor(triageViewSupervisor).subscribe(result => {
if (result.id == triageViewSupervisor.id) {
swal({
title: "Save Success !",
text: "The change has been saved :)",
type: "success",
timer: 1300
});
this.logger.info("after change segment", triageViewSupervisor.segment);
}
});
}
});
} else {
triageViewSupervisor.displaySegmentNameEditor = false;
}
}
sortTriageViews(column: string) {
switch (column) {
case "Id":
this.idDesc = !this.idDesc;
let idDescNum = this.idDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => idDescNum * (b.id - a.id));
break;
case "LatestVersionLatency":
this.latestVersionLatencyDesc = !this.latestVersionLatencyDesc;
let latestVersionLatencyDescNum = this.latestVersionLatencyDesc ? 1 : -1;
this.triageViewSupervisors.sort(
(a, b) => latestVersionLatencyDescNum * (b.latestVersionLatency - a.latestVersionLatency)
);
break;
case "LatestSucceedVersionLatency":
this.latestSucceedVersionLatencyDesc = !this.latestSucceedVersionLatencyDesc;
let latestSucceedVersionLatencyDescNum = this.latestSucceedVersionLatencyDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => {
if (b.latestSucceedVersionLatency == a.latestSucceedVersionLatency) {
return latestSucceedVersionLatencyDescNum * (b.latestVersionLatency - a.latestVersionLatency);
}
return (
latestSucceedVersionLatencyDescNum *
(b.latestSucceedVersionLatency - a.latestSucceedVersionLatency)
);
});
break;
}
}
isMissingSla(triageViewSupervisor: TriageViewSupervisor) {
if (
(triageViewSupervisor.originalState == "EveryVersion" &&
triageViewSupervisor.latestSucceedVersionLatency > Constants.everyVersionLimit) ||
(triageViewSupervisor.originalState == "MajorVersion" &&
triageViewSupervisor.latestSucceedVersionLatency > Constants.majorVersionLimit) ||
(triageViewSupervisor.originalState == "Manual" &&
triageViewSupervisor.latestSucceedVersionLatency > Constants.manualLimit)
) {
return true;
}
return false;
}
addRouterQueryParams() {
this.currentPage = 1;
this.router.navigate(["/triage/supervisor"], {
queryParams: {
"displayType": this.displayType
}
});
}
setPage(triageViewSupervisors: Array<TriageViewSupervisor>) {
this.numOfPages = Math.ceil(triageViewSupervisors.length / this.numPerPage);
return triageViewSupervisors.slice( (this.currentPage - 1) * this.numPerPage, this.numPerPage * this.currentPage );
}
}
<file_sep>/src/app/helper/webStorage.ts
import { LocalStorageService, SessionStorageService } from "ngx-webstorage";
import { WebStorageType } from "../core/enums";
import { environment } from "../../../config/environment/environment";
export class Record {
constructor(
public value?: any,
public expirationTime?: number
)
{}
}
export class WebStorage {
public storage: any;
constructor(public localSt: LocalStorageService, public sessionSt: SessionStorageService, public type: WebStorageType = environment.defaultStorageType) {
//notice: WebStorageType is a default parameter, the default value is in enviroment
if (type == WebStorageType.LocalStorage) {
this.storage = localSt;
} else if (type == WebStorageType.SessionStorage) {
this.storage = sessionSt;
}
}
saveValue(key: string, value: any, expirationMins: number = environment.defaultExpirationMin) {
//notice: expirationMin is count by minute, and expirationMin is a default parameter, the default value is in enviroment
let expirationTime = expirationMins * 60 * 1000;//expirationMs is count by millisecond
let record = new Record(value, new Date().getTime() + expirationTime);
this.storage.store(key, record);
}
retrieveValue(key: string) {
let record: Record = this.storage.retrieve(key);
let now = new Date().getTime();
if (now > record.expirationTime) {
this.clearItem(key);
}
return this.storage.retrieve(key);
}
clearItem(key: string) {
this.storage.clear(key);
}
clearAll() {
this.storage.clear();
}
isStorageAvailable() {
return this.storage.isStorageAvailable();
}
//To observer key's history
observe(key: string) {
this.storage.observe(key).subscribe((newValue: any) => {
console.log(newValue);
});
}
}
<file_sep>/src/app/components/entityAnalysis/entityAnalysis-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AuthenticationGuard } from "../loginAuth/authGuard";
//analysis
import { AnalysisDashboardComponent } from "./dashboard/analysisDashboard.component";
import { EntityAnalysisComponent } from "./entityAnalysis.component";
// import { EntitySpaceAnalysisComponent } from './entitySpace/entitySpaceAnalysis.component';
import { PayloadExplorerComponent } from "./entitySpace/payloadExplorer.component";
import { PayloadStatisticComponent } from "./entitySpace/payloadStatistic.component";
import { PayloadFilterComponent } from "./entitySpace/payloadFilter.component";
import { EntityViewAnalysisComponent } from "./entityView/entityViewAnalysis.component";
import { EntityGraphAnalysisComponent } from "./entityGraph/entityGraphAnalysis.component";
import { PageNotFoundComponent } from "../trivial/pageNotFound.component";
let allRoutes: Routes = [];
const analysisRoutes: Routes = [
//{ path: '', redirectTo: '/entityAnalysis', pathMatch: 'full' },
{
path: "entityanalysis",
component: EntityAnalysisComponent,
children: [
{
path: "",
component: AnalysisDashboardComponent,
canActivate: [AuthenticationGuard]
},
{
path: "dashboard",
component: AnalysisDashboardComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entityspace",
component: AnalysisDashboardComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entityview",
component: AnalysisDashboardComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entitygraph",
component: AnalysisDashboardComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entityspace/:id/explorer",
component: PayloadExplorerComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entityspace/:id/statistic",
component: PayloadStatisticComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entityspace/:id/filter",
component: PayloadFilterComponent,
canActivate: [AuthenticationGuard]
},
//{
// path: 'entityspace',
// component: EntitySpaceAnalysisComponent,
// children:[
// { path: 'entityspace/explorer', component: PayloadExplorerComponent },
// { path: 'entityspace/statistic', component: PayloadStatisticComponent },
// { path: 'entityspace/filter', component: PayloadFilterComponent }
//]
//},
{
path: "entityview",
component: EntityViewAnalysisComponent,
canActivate: [AuthenticationGuard]
},
{
path: "entitygraph",
component: EntityGraphAnalysisComponent,
canActivate: [AuthenticationGuard]
}
]
}
];
// const wildcardRoutes: Routes = [
// { path: '**', component: PageNotFoundComponent }
// ];
// allRoutes = allRoutes.concat(analysisRoutes, wildcardRoutes);
@NgModule({
imports: [
RouterModule.forChild(
analysisRoutes
//his outputs each router event that took place during each navigation lifecycle to the browser console
//{ enableTracing: true } // <-- debugging purposes only
)
],
exports: [RouterModule]
})
export class EntityAnalysisRoutingModule {}
<file_sep>/src/app/components/metric/metric.module.ts
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms"; //ngModel
import { HttpModule } from "@angular/http";
//routes
import { MetricRoutingModule } from "./metric-routing.module";
import { MetricComponent } from "./metric.component";
import { OnboardingTfsMetricComponent } from "./onboardingTfsMetric/onboardingTfsMetric.component";
import { MetricService } from "./metric.service";
import { ExcelService } from "../common/excel.service";
import { CommonModule } from "../../../../node_modules/@angular/common";
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
MetricRoutingModule
//SlimLoadingBarModule.forRoot()
],
declarations: [
MetricComponent,
OnboardingTfsMetricComponent
],
providers: [
MetricService,
ExcelService
]
})
export class MetricModule {}
<file_sep>/config/environment/environment.ts
import { environmentDev } from "./environment.dev"
import { environmentLocal } from "./environment.local"
import { environmentProd } from "./environment.prod"
import { environmentInt } from "./environment.int"
import { WebStorageType } from "../../src/app/core/enums";
const commonEnv = {
defaultStorageType: WebStorageType.LocalStorage,
defaultExpirationMin: 24 * 60
};
export const environment = Object.assign(commonEnv, environmentLocal);<file_sep>/src/app/components/metric/metric-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AuthenticationGuard } from "../loginAuth/authGuard";
//metric
import { MetricComponent } from "./metric.component";
import { OnboardingTfsMetricComponent } from "./onboardingTfsMetric/onboardingTfsMetric.component";
const reportRoutes: Routes = [
{ path: "metric", redirectTo: "/metric/onboardingTfs", pathMatch: "full" },
{
path: "metric",
component: MetricComponent,
children: [
{
path: "onboardingTfs",
component: OnboardingTfsMetricComponent,
canActivate: [AuthenticationGuard]
}
// {
// path: 'contribution',
// component: ContributionComponent
// },
]
}
];
@NgModule({
imports: [RouterModule.forChild(reportRoutes)],
exports: [RouterModule]
})
export class MetricRoutingModule {}
<file_sep>/deprecated/entitySpaceAnalysis.component.ts
import { Component, OnInit } from '@angular/core';
import {AnalysisType} from '../src/app/core/enums';
@Component({
selector: 'space-analysis',
templateUrl: './entitySpaceAnalysis.component.html',
//styleUrls: ['./name.component.css']
})
export class EntitySpaceAnalysisComponent implements OnInit {
analysisType: AnalysisType = AnalysisType.EntitySpace;
constructor() {
this.logger.info("entity space analysis");
}
ngOnInit() { }
}<file_sep>/src/app/core/entityAnalysis/entityGraphAnalysis.ts
import { EntityAnalysis } from "./entityAnalysis";
export class GraphAnalysis extends EntityAnalysis{
constructor(
id: number,
name: string,
createdBy: string,
createdTime: string,
updatedBy: string,
updatedTime: string,
customerId: string,
customerEnv: string
)
{
super(id, name, createdBy, createdTime, updatedBy, updatedTime, customerId, customerEnv);
}
}<file_sep>/src/app/components/entityAnalysis/entitySpace/payloadExplorer.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';
import {AnalysisType} from '../../../core/enums'
import { EntitySpaceAnalysisService } from '../service/entitySpaceAnalysis.service'
import { EntitySpaceAnalysis } from '../../../core/entityAnalysis/entitySpaceAnalysis'
@Component({
selector: 'payload-explorer',
templateUrl: './payloadExplorer.component.html',
//styleUrls: ['./name.component.scss']
})
export class PayloadExplorerComponent implements OnInit {
analysisType: AnalysisType = AnalysisType.EntitySpace;
stage: string = "Explorer";
entitySpaceAnalysis: EntitySpaceAnalysis
constructor(
private route: ActivatedRoute,
private location: Location,
private entitySpaceAnalysisService: EntitySpaceAnalysisService
) { }
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.entitySpaceAnalysisService.getEntitySpaceAnalysis(+params.get('id')))
.subscribe(entitySpaceAnalysis => this.entitySpaceAnalysis = entitySpaceAnalysis);
}
}<file_sep>/deprecated/triageAnalysis.component.ts
// switchResultPane(event: any) {
// this.logger.info("switch result pane:", event);
// if (this.triageAnalysisAetherJob.state !== JobState.Succeeded) {
// return;
// }
// if (!event) {
// this.getTriageAnalysisResultCount(this.triageAnalysisResultId);
// }
// }
// getTriageAnalysisResultCount(resultId: number) {
// this.triageService.getTriageAnalysisResultCount(resultId).subscribe(triageAnalysisResultCount => {
// this.logger.info(triageAnalysisResultCount);
// this.triageAnalysisResultCount = triageAnalysisResultCount;
// this.getValidChurn(triageAnalysisResultCount.debugStreamExistense);
// });
// }
// getValidChurn(debugStreamExistense: DebugStreamExistense) {
// this.logger.info(debugStreamExistense);
// for (var debugStream in debugStreamExistense) {
// this.logger.info(debugStream, debugStreamExistense[debugStream]);
// if (debugStreamExistense[debugStream]) {
// this.triageDebugStream = debugStream[0].toUpperCase() + debugStream.slice(1);
// this.logger.info(this.triageDebugStream);
// this.switchChurn();
// break;
// }
// }
// }
// switchChurn() {
// if (this.triageAnalysisResultId == -1) {
// return;
// }
// switch (this.triageDebugStream) {
// case "ValueChurnCounter": {
// if (!this.triageAnalysisResult.valueChurn) {
// this.getTriageAnalysisResultByChurnType(this.triageAnalysisResultId, "ValueChurnCounter").add(
// () => {
// this.triageAnalysisResult.valueChurn = this.currentChurn;
// }
// );
// } else {
// this.currentChurn = this.triageAnalysisResult.valueChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.valueChurnCount;
// //this.logger.info(this.currentChurn);
// break;
// }
// case "PipelineTopEntitiesChurnCounter": {
// if (!this.triageAnalysisResult.pipelineTopEntitiesChurn) {
// this.getTriageAnalysisResultByChurnType(
// this.triageAnalysisResultId,
// "PipelineTopEntitiesChurnCounter"
// ).add(() => {
// this.triageAnalysisResult.pipelineTopEntitiesChurn = this.currentChurn;
// });
// } else {
// this.currentChurn = this.triageAnalysisResult.pipelineTopEntitiesChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.pipelineTopEntitiesChurnCount;
// //this.logger.info(this.currentChurn);
// break;
// }
// case "PipelineTypeChurnCounter": {
// if (!this.triageAnalysisResult.pipelineTypeChurn) {
// this.getTriageAnalysisResultByChurnType(
// this.triageAnalysisResultId,
// "PipelineTypeChurnCounter"
// ).add(() => {
// this.logger.info("switchChurn1", this.currentChurn);
// this.triageAnalysisResult.pipelineTypeChurn = this.currentChurn;
// });
// } else {
// this.currentChurn = this.triageAnalysisResult.pipelineTypeChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.pipelineTypeChurnCount;
// //this.logger.info("switchChurn2", this.currentChurn);
// break;
// }
// case "PipelineChurnCounter": {
// if (!this.triageAnalysisResult.pipelineChurn) {
// this.getTriageAnalysisResultByChurnType(this.triageAnalysisResultId, "PipelineChurnCounter").add(
// () => {
// this.triageAnalysisResult.pipelineChurn = this.currentChurn;
// }
// );
// } else {
// this.currentChurn = this.triageAnalysisResult.pipelineChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.pipelineChurnCount;
// //this.logger.info(this.currentChurn);
// break;
// }
// case "PipelineUpdatedEntitiesChurnCounter": {
// if (!this.triageAnalysisResult.pipelineUpdatedEntitesChurn) {
// this.getTriageAnalysisResultByChurnType(
// this.triageAnalysisResultId,
// "PipelineUpdatedEntitiesChurnCounter"
// ).add(() => {
// this.triageAnalysisResult.pipelineUpdatedEntitesChurn = this.currentChurn;
// });
// } else {
// this.currentChurn = this.triageAnalysisResult.pipelineUpdatedEntitesChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.pipelineUpdatedEntitiesChurnCount;
// //this.logger.info(this.currentChurn);
// break;
// }
// case "UpdatedEntitiesChurnCounter": {
// if (!this.triageAnalysisResult.updatedEntitesChurn) {
// this.getTriageAnalysisResultByChurnType(
// this.triageAnalysisResultId,
// "UpdatedEntitiesChurnCounter"
// ).add(() => {
// this.triageAnalysisResult.updatedEntitesChurn = this.currentChurn;
// });
// this.currentTriageResultCount = this.triageAnalysisResultCount.updatedEntitiesChurnCount;
// } else {
// this.currentChurn = this.triageAnalysisResult.updatedEntitesChurn;
// }
// this.currentTriageResultCount = this.triageAnalysisResultCount.updatedEntitiesChurnCount;
// break;
// }
// }
// //this.logger.info(this.currentChurn);
// }
// getTriageAnalysisResultByChurnType(resultId: number, triageChurnType: string) {
// this.isFetchingAnalysisResult = true;
// return this.triageService
// .getTriageResultByChurnType(resultId, triageChurnType)
// .map(t => this.convertSatoriTimeToGeneralTime(t))
// .subscribe((triageChurn: TriageChurn) => {
// //this.logger.info("triageChurn", triageChurn, triageChurnType);
// this.setCollapseTag(triageChurn);
// //this.logger.info("response1", response);
// this.currentChurn = triageChurn;
// this.isFetchingAnalysisResult = false;
// //this.logger.info("switchChurn0", this.currentChurn);
// });
// }<file_sep>/src/app/components/triage/triage.service.ts
import { Injectable } from "@angular/core";
import {
HttpClient,
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpParams,
HttpHeaders,
HttpResponse
} from "@angular/common/http";
//import "rxjs/add/operator/toPromise";
import { EntityView } from "../../core/common/entityView";
import { BaseService } from "../common/base.service";
import { ApiController, RequestAction, ReportType } from "../../core/enums";
import { TriageAnalysisDto, Revision } from "../../core/triage/triageAnalysis";
import { TriageAnalysis } from "../../core/triage/triageAnalysis";
import { TriageViewSupervisor } from "../../core/triage/triageViewSupervisor";
import {
TriageAnalysisResultCount,
TriageChurn,
PropertyTriageChurn
} from "../../core/triage/tirageAnlaysisResult";
import {
EntitySpaceViewStateDistribution,
TriageAndErrorDistribution,
ViewVersionDuration,
TriageCommitDuration,
AllViewStateDistribution,
ViewVersionLatencyDetail,
ViewVersionLatency
} from "../../core/triage/triageStatistic";
import {
MultiChartData,
SingleChartData
} from "../../core/plugin/ngxChart";
import { Constants } from "../../core/common/constants";
import { TriageReport, TriageReportDetail, ViewVersionMetric } from "../../core/triage/triageReport";
@Injectable()
export class TriageService extends BaseService {
private triageServiceUrl = `${this.serverUrl}/TriageAnalysis`; // URL to web api
private epServiceUrl = `${this.serverUrl}/EntityPlatform`; // URL to web api
private EPProdJobServiceUrl = Constants.EPProdJobServiceUrl;
constructor(public httpClient: HttpClient) {
super(httpClient);
}
//#region triage analysis
getEntityView(customerId: string, customerEnv: string, viewKey: string, isForceRefresh: boolean) {
//return this.http.get(this.getRequestApi(ApiController.TriageAnalysis, RequestAction.AllCustomerIds)).map((response) => response.json());
//https://blog.angular-university.io/angular-http/
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv)
.set("viewKey", viewKey)
.set("isForceRefresh", isForceRefresh.toString());
//const httpParams = new HttpParams().append('customerId', customerId).append('customerEnv', customerEnv).append('viewKey', viewKey);
this.logger.info(httpParams.toString());
return this.httpClient.get<EntityView>(
`${this.triageServiceUrl}/entityView`,
{
params: httpParams
//headers: new HttpHeaders().set('responseType', 'blob'),
}
); //.map((response) => response.json());
}
downloadFunctoid(
customerId: string,
customerEnv: string,
viewKey: string,
dotSplitedVersionNum: string,
functoidName: string
) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv)
.set("viewKey", viewKey)
.set("dotSplitedVersionNum", dotSplitedVersionNum)
.set("functoidName", functoidName);
return this.httpClient.get(`${this.epServiceUrl}/functoid`, {
observe: "response",
params: httpParams,
responseType: "arraybuffer"
//responseType: 'blob'
//headers: new HttpHeaders().set('Content-Type', 'undefined')
});
}
downloadMappingFile(
customerId: string,
customerEnv: string,
viewKey: string,
dotSplitedVersionNum: string,
mappingFileName: string
) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv)
.set("viewKey", viewKey)
.set("dotSplitedVersionNum", dotSplitedVersionNum)
.set("mappingFileName", mappingFileName);
return this.httpClient.get(`${this.epServiceUrl}/mappingFile`, {
observe: "response",
params: httpParams,
responseType: "text"
//responseType: 'blob'
//headers: new HttpHeaders().set('Content-Type', 'undefined')
});
}
downloadWrapstarModel(
modelId: string,
modelVersion: string
) {
const httpParams = new HttpParams()
.set("modelId", modelId)
.set("modelVersion", modelVersion)
return this.httpClient.get(`${this.triageServiceUrl}/downloadModel`, {
observe: "response",
params: httpParams,
responseType: "text"
});
}
getWrapstarModelVersion(
customerId: string,
customerEnv: string,
viewKey: string,
dotSplitedVersionNum: string,
mappingFileName: string
) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv)
.set("viewKey", viewKey)
.set("dotSplitedVersionNum", dotSplitedVersionNum)
.set("mappingFileName", mappingFileName);
return this.httpClient.get<Array<Revision>>(`${this.triageServiceUrl}/modelVersion`, {
params: httpParams
});
}
getTriageAnalysis(
customerId: string,
customerEnv: string,
viewKey: string,
standardVersion: string,
triagedVersion: string
) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv)
.set("viewKey", viewKey)
.set("standardVersion", standardVersion)
.set("triagedVersion", triagedVersion);
return this.httpClient.get<TriageAnalysis>(
`${this.triageServiceUrl}/triageAnalysis`,
{
params: httpParams
}
);
}
submitTriageAnalysisJob(
isForceSubmission: boolean,
vc: string,
cloudPriority: number,
triageAnalysisDto: TriageAnalysisDto
) {
return this.httpClient.post(
`${this.triageServiceUrl}/triageAnalsisJob`,
{
isForceSubmission: isForceSubmission,
cloudPriority: cloudPriority,
vc: vc,
triageAnalysisDto: triageAnalysisDto
},
{ headers: new HttpHeaders().set("User", "jixge") }
);
}
cancelTriageAnalysisJob(jobId: number) {
const httpParams = new HttpParams().set("jobId", jobId.toString());
return this.httpClient.delete(
`${this.triageServiceUrl}/triageAnalsisJob`,
{
headers: new HttpHeaders().set("User", "jixge"),
params: httpParams
}
);
}
getTriageAnalysisResultCount(resultId: number) {
const httpParams = new HttpParams().set(
"resultId",
resultId.toString()
);
return this.httpClient.get<TriageAnalysisResultCount>(
`${this.triageServiceUrl}/triageAnalysisResultCount`,
{
headers: new HttpHeaders().set("User", "jixge"),
params: httpParams
}
);
}
getTriageResultByChurnType(resultId: number, churnType: string) {
const httpParams = new HttpParams()
.set("resultId", resultId.toString())
.set("churnType", churnType);
return this.httpClient.get<TriageChurn>(
`${this.triageServiceUrl}/triageResultByChurnType`,
{ params: httpParams }
);
}
getTriageResultByProperty(resultId: number, property: string, debugStream: string) {
let httpParams = new HttpParams()
.set("resultId", resultId.toString())
.set("property", property)
.set("debugStream", debugStream);
return this.httpClient.get<PropertyTriageChurn>(
`${this.triageServiceUrl}/triageResultByProperty`,
{ params: httpParams }
);
}
getTriageAnalysisJob(jobId: number) {
const httpParams = new HttpParams().set("jobId", jobId.toString());
return this.httpClient.get(
`${this.triageServiceUrl}/triageAnalsisJob`,
{ params: httpParams }
);
}
getExtraProperties(triageAnalysisId: number, resultId: number) {
const httpParams = new HttpParams()
.set("triageAnalysisId", triageAnalysisId.toString())
.set("resultId", resultId.toString());
return this.httpClient.get(
`${this.triageServiceUrl}/triageResultExtraProperties`,
{ params: httpParams }
);
}
getSideBySideProperties(resultId: number) {
const httpParams = new HttpParams()
.set("resultId", resultId.toString());
return this.httpClient.get(
`${this.triageServiceUrl}/triageResultSBSProperties`,
{ params: httpParams }
);
}
getSideBySidePairsByProperty(resultId: number, property: string) {
const httpParams = new HttpParams()
.set("property", property.toString())
.set("resultId", resultId.toString());
return this.httpClient.get(
`${this.triageServiceUrl}/triageResultSBSPairsByProperty`,
{ params: httpParams }
);
}
commitTriagedView(
customerId: string,
customerEnv: string,
entitySpaceName: string,
viewName: string,
comment: string
) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("environmentName", customerEnv)
.set("entitySpaceName", entitySpaceName)
.set("viewName", viewName)
.set("commitComment", comment);
return this.httpClient.get(`${this.EPProdJobServiceUrl}/EntitySpace/CommitEntitySpaceView`, {
params: httpParams,
withCredentials: true
});
}
//#endregion
//#region triage supervisor
getTriageViewSupervisors() {
return this.httpClient.get<Array<TriageViewSupervisor>>(
`${this.triageServiceUrl}/triageViewSupervisor`,
{}
);
}
addTriageViewSupervisor(
customerId: string,
customerEnv: string,
entitySapce: string,
entitySapceView: string,
segment: string,
owner: string
) {
return this.httpClient.post<TriageViewSupervisor>(
`${this.triageServiceUrl}/triageViewSupervisor`,
{
customerId: customerId,
customerEnv: customerEnv,
entitySpace: entitySapce,
entitySpaceView: entitySapceView,
segment: segment,
owner: owner
},
{ headers: new HttpHeaders().set("User", "jixge") }
);
}
updateTriageViewSupervisor(triageSupervisor: TriageViewSupervisor) {
return this.httpClient.put<TriageViewSupervisor>(
`${this.triageServiceUrl}/updateTriageViewSupervisor`,
{
customerId: triageSupervisor.customerId,
customerEnv: triageSupervisor.customerEnv,
entitySpace: triageSupervisor.entitySpaceName,
entitySpaceView: triageSupervisor.entitySpaceViewName,
segment: triageSupervisor.segment,
owner: triageSupervisor.owner
},
{ headers: new HttpHeaders().set("User", "jixge") }
);
}
deleteTriageViewSupervisor(triageSupervisorId: number) {
const httpParams = new HttpParams().set("triageViewSupervisorId", triageSupervisorId.toString());
return this.httpClient.delete<TriageViewSupervisor>(
`${this.triageServiceUrl}/deleteTriageViewSupervisor`,
{ params: httpParams }
);
}
getEntitySpaceViewStateDistribution() {
return this.httpClient.get<Array<EntitySpaceViewStateDistribution>>(
`${this.triageServiceUrl}/entitySpaceViewStateDistribution`,
{}
);
}
getViewStateDistribution() {
return this.httpClient.get<AllViewStateDistribution>(
`${this.triageServiceUrl}/viewStateDistribution`,
{}
);
}
//#endregion
//#region statistic
getTriageAndErrorDistributionResult() {
return this.httpClient.get<TriageAndErrorDistribution[]>(
`${this.triageServiceUrl}/triageAndErrorDistribution`,
{}
);
}
getVersionDelayResult(statisticId: number) {
const httpParams = new HttpParams().set(
"statisticId",
statisticId.toString()
);
return this.httpClient.get<ViewVersionDuration>(
`${this.triageServiceUrl}/viewVersionDuration`,
{ params: httpParams }
);
}
getAllViewVersionDelaysResult() {
return this.httpClient.get<ViewVersionDuration[]>(
`${this.triageServiceUrl}/allViewVersionDurations`,
{}
);
}
getAllFakeTriageViewVersionDurations() {
return this.httpClient.get<ViewVersionDuration[]>(
`${this.triageServiceUrl}/allFakeTriageViewVersionDurations`,
{}
);
}
getCommitDelayResult(statisticId: number) {
const httpParams = new HttpParams().set(
"statisticId",
statisticId.toString()
);
return this.httpClient.get<TriageCommitDuration>(
`${this.triageServiceUrl}/triageCommitDuration`,
{ params: httpParams }
);
}
getMonthlyCountResult(statisticId: number) {
const httpParams = new HttpParams().set(
"statisticId",
statisticId.toString()
);
return this.httpClient.get<TriageAndErrorDistribution>(
`${this.triageServiceUrl}/singleViewTriageAndErrorDistribution`,
{ params: httpParams }
);
}
getViewVersionDetail(statisticId: number, startTime: string, endTime: string) {
const httpParams = new HttpParams()
.set("supervisorId", statisticId.toString())
.set("startTime", startTime)
.set("endTime", endTime);
return this.httpClient.get<Array<ViewVersionLatencyDetail>>(
`${this.triageServiceUrl}/viewVersionDetail`,
{ params: httpParams }
);
}
getViewVersionLatency(statisticId: number, startTime: string, endTime: string) {
const httpParams = new HttpParams()
.set("supervisorId", statisticId.toString())
.set("startTime", startTime)
.set("endTime", endTime);
return this.httpClient.get<Array<ViewVersionLatency>>(
`${this.triageServiceUrl}/viewVersionLatency`,
{ params: httpParams }
);
}
//#endregion
//#region triage report
getTriageReport(reportTimeSpan: string, type: ReportType, forceGenerate: boolean) {
const httpParams = new HttpParams()
.set("reportTimeSpan", reportTimeSpan)
.set("type", type.toString())
.set("forceGenerate", forceGenerate.toString());
return this.httpClient.get<TriageReport>(
`${this.triageServiceUrl}/triageReport`,
{ params: httpParams }
);
}
getTriageReportTimeSpansByReportType(reportType: string) {
const httpParams = new HttpParams().set(
"reportType", reportType
);
return this.httpClient.get<Array<string>>(
`${this.triageServiceUrl}/triageReportTimeSpans`,
{ params: httpParams }
);
}
getTriageReportDetail(statisticId: number, startTime: string, endTime: string) {
const httpParams = new HttpParams()
.set("supervisorId", statisticId.toString())
.set("startTime", startTime)
.set("endTime", endTime);
return this.httpClient.get<TriageReportDetail>(
`${this.triageServiceUrl}/triageReportDetail`,
{ params: httpParams }
);
}
getViewVersionMetric(startTime: string, endTime: string){
const httpParams = new HttpParams()
.set("startTime", startTime)
.set("endTime", endTime);
return this.httpClient.get<ViewVersionMetric>(
`${this.triageServiceUrl}/viewVersionMetric`,
{ params: httpParams }
);
}
//#endregion
private handleError(error: any): Promise<any> {
console.error("An error occurred", error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
<file_sep>/src/app/components/triage/triageStatistic/triageStatistic.component.ts
import { Component, OnInit, TemplateRef } from "@angular/core";
import { NgxChartsModule } from "@swimlane/ngx-charts";
import { TriageService } from "../triage.service";
import { BaseComponent } from "../../common/base.component";
import {
AdvancedPieChart,
SingleChartData,
VerticalBarChart,
GroupedVerticalBarChart,
LineChart,
MultiChartData,
PieGridChart
} from "../../../core/plugin/ngxChart";
import { HttpClient } from "@angular/common/http";
import { Constants } from "../../../core/common/constants";
import { TriageAndErrorDistribution, DailyCount, DailyErrorTriageViewName, ViewVersionDuration, ViewStateDistribution } from "../../../core/triage/triageStatistic";
@Component({
selector: "triage-statistic",
templateUrl: "./triageStatistic.component.html",
styleUrls: []
})
export class TriageStatisticComponent extends BaseComponent implements OnInit {
distributionPieChart: AdvancedPieChart;
versionDelayDistributionPieGridChart: PieGridChart;
currentViewStateDistributionPieGridChart: PieGridChart;
originalViewStateDistributionPieGridChart: PieGridChart;
triageTopTenBarChart: VerticalBarChart;
weeklyCountLineChart: LineChart;
monthlyCountLineChart: LineChart;
//pieChartStateDistributionData: Array<PieChartData>;
scheme: object;
constructor(private triageService: TriageService) {
super();
}
ngOnInit() {
this.initRealTimePieChart();
this.initTopTenVerticalBarChart();
this.initCurrentViewStateDistributionPieGridChart();
this.initOriginalViewStateDistributionPieGridChart();
this.initVersionDelayDistributionPieGridChart();
this.initMonthlyCountLineChart();
}
initRealTimePieChart() {
//this.pieChartStateDistributionData = new Array<PieChartData>();
//Errored, Triaged, updating, standard
let colorDomain = new Array("#a8385d", "#FFA1B5", "#86C7F3", "#5aa454");
this.distributionPieChart = new AdvancedPieChart();
this.distributionPieChart.scheme.domain = colorDomain;
//this.distributionPieChart.scheme.domain = colorScheme;
this.logger.info(this.distributionPieChart);
this.triageService
.getEntitySpaceViewStateDistribution()
.subscribe(entitySpaceViewStateDistributions => {
this.logger.info(entitySpaceViewStateDistributions);
this.distributionPieChart.results = entitySpaceViewStateDistributions.map(
t =>
new SingleChartData(
this.EntitySpaceViewVersionState[t.state],
t.count
)
);
this.logger.info(
"realtimechart",
this.distributionPieChart.results
);
});
//this.getEntitySpaceViewStateDistribution();
}
generateViewStateDistributionPieGridChartResult(viewStateDistributions:Array<ViewStateDistribution>){
return viewStateDistributions.map(
t =>
new SingleChartData(
this.EntitySpaceViewState[t.state],
t.count
)
);
}
initCurrentViewStateDistributionPieGridChart(){
let colorDomain = new Array("#d1f1ed", "#6dc8c0", "#3f8c85", "#5aa454");
this.currentViewStateDistributionPieGridChart = new PieGridChart();
this.currentViewStateDistributionPieGridChart.view = [700,200];
this.currentViewStateDistributionPieGridChart.scheme.domain = colorDomain;
this.triageService.getViewStateDistribution().subscribe(viewStateDistributions => {
this.currentViewStateDistributionPieGridChart.results =
this.generateViewStateDistributionPieGridChartResult(viewStateDistributions.currentViewStateDistribution);
});
}
initOriginalViewStateDistributionPieGridChart(){
let colorDomain = new Array("#c6efff", "#389ec5", "#1d627e", "#86c7f3");
this.originalViewStateDistributionPieGridChart = new PieGridChart();
this.originalViewStateDistributionPieGridChart.view = [700,200];
this.originalViewStateDistributionPieGridChart.scheme.domain = colorDomain;
this.triageService.getViewStateDistribution().subscribe(viewStateDistributions => {
this.originalViewStateDistributionPieGridChart.results =
this.generateViewStateDistributionPieGridChartResult(viewStateDistributions.originalViewStateDistribution);
});
}
generateTopTenVerticalBarChartResult(
triageAndErrorDistributions: TriageAndErrorDistribution[]
) {
let singleChartDatas = new Array<SingleChartData>();
if(triageAndErrorDistributions.length==0){
singleChartDatas.push(new SingleChartData("none",0));
return singleChartDatas;
}
triageAndErrorDistributions.forEach(t => {
singleChartDatas.push(
new SingleChartData(
t.viewName,
t.totalTriageCount + t.totalErrorCount
)
);
});
singleChartDatas = singleChartDatas
.sort((a, b) => b.value - a.value)
.slice(0, Constants.topTen);
return singleChartDatas;
}
initTopTenVerticalBarChart() {
let colorDomain = new Array("#FFA1B5");
this.triageTopTenBarChart = new VerticalBarChart();
this.triageTopTenBarChart.legend=false;
this.triageTopTenBarChart.scheme.domain = colorDomain;
this.triageService
.getTriageAndErrorDistributionResult()
.subscribe(result => {
this.triageTopTenBarChart.results = this.generateTopTenVerticalBarChartResult(
result
);
this.logger.info(
"TopTenVerticalBarChart",
this.triageTopTenBarChart.results
);
});
}
generateVersionDelayDistributionPieGridChartResult(allViewVersionDurations:ViewVersionDuration[]) {
let singleChartDatasOfChart = new Array<SingleChartData>();
let highDurationViews = new Array<SingleChartData>();
let middleDurationViews = new Array<SingleChartData>();
let lowDurationViews = new Array<SingleChartData>();
let averageDuration:number = 0;
let averageDurationOfHigh:number = 0;
let averageDurationOfLow:number = 0;
let maxDurationOfAll:number = 0;
let minDurationOfAll:number = 10000;
let allViewVersionDurationsLength=allViewVersionDurations.length;
let lowRange = new Array();
let middleRange = new Array();
let highRange = new Array();
if(allViewVersionDurationsLength==0){
singleChartDatasOfChart.push(new SingleChartData("none",0));
return singleChartDatasOfChart;
}
allViewVersionDurations.forEach(t => {
if(t.averageDuration=="NaN"){
t.averageDuration="0";
}
averageDuration+=(Number(t.averageDuration)/allViewVersionDurationsLength);
if(Number(t.averageDuration) > maxDurationOfAll){
maxDurationOfAll = Number(t.averageDuration);
}
if(Number(t.averageDuration) < minDurationOfAll){
minDurationOfAll = Number(t.averageDuration);
}
});
averageDurationOfHigh=(averageDuration+maxDurationOfAll)/2;
averageDurationOfLow=(averageDuration+minDurationOfAll)/2;
lowRange=[minDurationOfAll.toFixed(1),averageDurationOfLow.toFixed(1)];
middleRange=[averageDurationOfLow.toFixed(1),averageDurationOfHigh.toFixed(1)];
highRange=[averageDurationOfHigh.toFixed(1),maxDurationOfAll.toFixed(1)];
allViewVersionDurations.forEach(t => {
if(t.averageDuration=="NaN"){
t.averageDuration="0";
}
if(Number(t.averageDuration)<=maxDurationOfAll&&Number(t.averageDuration)>averageDurationOfHigh){
highDurationViews.push(new SingleChartData(t.viewName,Number(Number(t.averageDuration).toFixed(1))));
}
else if(Number(t.averageDuration)>=minDurationOfAll&&Number(t.averageDuration)<averageDurationOfLow){
lowDurationViews.push(new SingleChartData(t.viewName,Number(Number(t.averageDuration).toFixed(1))));
}
else{
middleDurationViews.push(new SingleChartData(t.viewName,Number(Number(t.averageDuration).toFixed(1))));
}
});
singleChartDatasOfChart=[
new SingleChartData("Low",lowDurationViews.length),
new SingleChartData("Middle",middleDurationViews.length),
new SingleChartData("High",highDurationViews.length)
];
highDurationViews=highDurationViews.sort((a,b)=>b.value-a.value).slice(0,Constants.topFive);//sort from high to low
lowDurationViews=lowDurationViews.sort((a,b)=>a.value-b.value).slice(0,Constants.topFive);//sort from low to high
middleDurationViews=middleDurationViews.sort((a,b)=>b.value-a.value).slice(0,Constants.topFive);//sort from high to low
this.versionDelayDistributionPieGridChart.pieGridChartDetailDict.set("Low",lowDurationViews);
this.versionDelayDistributionPieGridChart.pieGridChartDetailDict.set("Middle",middleDurationViews);
this.versionDelayDistributionPieGridChart.pieGridChartDetailDict.set("High",highDurationViews);
this.versionDelayDistributionPieGridChart.pieGridChartDetailLayerValueDict.set("Low",lowRange);
this.versionDelayDistributionPieGridChart.pieGridChartDetailLayerValueDict.set("Middle",middleRange);
this.versionDelayDistributionPieGridChart.pieGridChartDetailLayerValueDict.set("High",highRange);
return singleChartDatasOfChart;
}
initVersionDelayDistributionPieGridChart() {
let colorDomain = new Array("#86C7F3", "#FFA1B5", "#a8385d");
this.versionDelayDistributionPieGridChart = new PieGridChart();
this.triageService.getAllViewVersionDelaysResult().subscribe(result=>{
this.versionDelayDistributionPieGridChart.results=this.generateVersionDelayDistributionPieGridChartResult(result);
})
this.versionDelayDistributionPieGridChart.scheme.domain = colorDomain;
}
// getEntitySpaceViewStateDistribution() {
// let pieChartStateDistributionData: Array<PieChartData>;
// this.triageService
// .getEntitySpaceViewStateDistribution()
// .subscribe(entitySpaceViewStateDistributions => {
// pieChartStateDistributionData = entitySpaceViewStateDistributions.map(
// t => t.ToPieChartData()
// );
// });
// return pieChartStateDistributionData;
// }
generateMonthlyCountLineChartResult(
triageAndErrorDistributions: TriageAndErrorDistribution[]
) {
let dailyCounts = new Array<DailyCount>();
let multiChartData: MultiChartData = new MultiChartData();
let multiChartDatas = new Array<MultiChartData>();
if(triageAndErrorDistributions.length==0){
multiChartDatas.push(new MultiChartData("none",[new SingleChartData("none",0)]));
return multiChartDatas;
}
triageAndErrorDistributions.forEach(t => {
t.triageAndErrors.forEach(e => {
dailyCounts.push(
new DailyCount(
t.viewName,
e.date,
e.errorCount,
e.triageCount
)
);
});
});
multiChartDatas[0] = new MultiChartData("error");
multiChartDatas[1] = new MultiChartData("triage");
if(dailyCounts.length==0){
multiChartDatas[0]=new MultiChartData("no error",[new SingleChartData("none",0)]);
multiChartDatas[1]=new MultiChartData("no triage",[new SingleChartData("none",0)]);
}
dailyCounts.forEach(d => {
for (let i = 0; i < Constants.monthDays; i++) {
if (!multiChartDatas[0].series[i]) {
multiChartDatas[0].series[i] = new SingleChartData(
d.date,
d.errorCount
);
multiChartDatas[1].series[i] = new SingleChartData(
d.date,
d.triageCount
);
break;
} else if (multiChartDatas[0].series[i].name == d.date) {
multiChartDatas[0].series[i].value +=
d.errorCount > 0 ? 1 : 0;
multiChartDatas[1].series[i].value +=
d.triageCount > 0 ? 1 : 0;
break;
}
}
});
return multiChartDatas;
}
initMonthlyCountLineChart() {
let colorDomain = new Array("#a8385d", "#FFA1B5", "#86C7F3", "#5aa454");
this.monthlyCountLineChart = new LineChart();
this.monthlyCountLineChart.view = [1700, 400];
this.monthlyCountLineChart.scheme.domain = colorDomain;
this.triageService
.getTriageAndErrorDistributionResult()
.subscribe(result => {
this.monthlyCountLineChart.results = this.generateMonthlyCountLineChartResult(result);
this.logger.info(
"monthlyCountLineChart",
this.monthlyCountLineChart.results
);
});
}
}
<file_sep>/src/app/core/plugin/ngxChart.ts
import { TemplateRef } from "@angular/core";
export class BaseChart {
constructor(
public view?: Array<number>,
//public results?: Array<PieChartData>,
public scheme?: ColorScheme,
public customColors?: Array<string>,
public animations?: boolean,
public gradient?: boolean,
public tooltipDisabled?: boolean,
public tooltipTemplate?: TemplateRef<string>,
public activeEntries?: Array<object>
) {
this.view = [700, 400];
this.gradient = false;
//this.results = new Array<PieChartData>();
this.scheme = new ColorScheme();
this.customColors = new Array<string>();
this.activeEntries = new Array<object>();
}
}
// see details here: https://swimlane.gitbooks.io/ngx-charts/content/charts/advanced-pie-chart.html
export class AdvancedPieChart extends BaseChart {
constructor(
public label?: string,
public results?: Array<SingleChartData>,
public pieChartDetailLayerValueDict?:Map<string, object>//help to display the values of low/middle/high range
) {
super();
this.results = new Array<SingleChartData>();
this.pieChartDetailLayerValueDict = new Map<string, object>();
}
}
export class PieGridChart extends BaseChart {
constructor(
public label?: string,
public results?: Array<SingleChartData>,
public pieGridChartDetailDict?:Map<string, object>,
public pieGridChartDetailLayerValueDict?:Map<string, object>
) {
super();
this.results = new Array<SingleChartData>();
this.pieGridChartDetailDict = new Map<string, object>();
this.pieGridChartDetailLayerValueDict = new Map<string, object>();
}
}
export class SingleChartData {
constructor(public name?: string, public value?: number) {}
}
export class MultiChartData {
constructor(public name?: string, public series?: Array<SingleChartData>) {
if(series){
this.series = series;
}
else{
this.series = new Array<SingleChartData>();
}
}
}
export class ColorScheme {
constructor(public domain?: Array<string>) {
this.domain = new Array<string>();
}
}
export class BarChart extends BaseChart {
constructor(
public schemeType?: string,
public legend?: boolean,
public legendTitle?: string,
public xAxis?: boolean,
public yAxis?: boolean,
public showGridLines?: boolean,
public roundDomains?: boolean,
public showXAxisLabel?: boolean,
public showYAxisLabel?: boolean,
public xAxisLabel?: string,
public yAxisLabel?: string,
public tooltipTemplate?: TemplateRef<any>,
public xAxisTickFormatting?: Function,
public yAxisTickFormatting?: Function,
public barPadding?: number,
public yScaleMax?: number
) {
super();
this.xAxis = true;
this.yAxis = true;
this.gradient = false;
this.legend = true;
this.showYAxisLabel = true;
this.showXAxisLabel = true;
}
}
export class VerticalBarChart extends BarChart {
constructor(
public results?: Array<SingleChartData>,
public verticalBarChartDict?: Map<string, object>
) {
super();
this.xAxisLabel = "Day";
this.yAxisLabel = "Count";
this.results = new Array<SingleChartData>();
this.verticalBarChartDict = new Map<string, object>();
//this.results =
}
}
export class GroupedVerticalBarChart extends BarChart {
constructor(
public results?: Array<MultiChartData>,
public groupPadding?: number,
public groupedVerticalBarChartDetailDict?: Map<string, object>
) {
super();
this.results = new Array<MultiChartData>();
this.xAxisLabel = "Day";
this.yAxisLabel = "Count";
this.groupedVerticalBarChartDetailDict = new Map<string, object>();
}
}
export class StackedVerticalBarChart extends BarChart {
constructor(
public results?: Array<MultiChartData>,
public stackedVerticalBarChartDetailDict?: Map<string, any>
) {
super();
this.results = new Array<MultiChartData>();
this.stackedVerticalBarChartDetailDict = new Map<string, any>();
}
}
export class BaseLineChart extends BaseChart {
constructor(
public schemeType?: string,
public legend?: boolean,
public legendTitle?: string,
public xAxis?: boolean,
public yAxis?: boolean,
public showGridLines?: boolean,
public roundDomains?: boolean,
public showXAxisLabel?: boolean,
public showYAxisLabel?: boolean,
public xAxisLabel?: string,
public yAxisLabel?: string,
public xAxisTickFormatting?: Function,
public yAxisTickFormatting?: Function,
public seriesTooltipTemplate?: TemplateRef<any>,
public xScaleMin?: any,
public xScaleMax?: any,
public yScaleMin?: number,
public yScaleMax?: number,
public rangeFillOpacity?: number,
public timeline?: boolean,
public autoScale?: boolean,
public curve?: Function
) {
super();
this.xAxis = true;
this.yAxis = true;
this.gradient = false;
this.legend = true;
this.showYAxisLabel = true;
this.showXAxisLabel = true;
}
}
export class LineChart extends BaseLineChart {
constructor(
public results?: Array<MultiChartData>,
public referenceLines?: Array<object>,
public showRefLines?: boolean,
public showRefLabels?: boolean,
public lineChartDetailDict?: Map<string, object>
) {
super();
this.results = new Array();
this.lineChartDetailDict = new Map<string, object>();
}
}
export class NumberCardChart extends BaseChart{
constructor(
public results?:Array<SingleChartData>,
public cardColor?:string,//format: 'rgba(0, 0, 0, 0)'
public bandColor?:string,
public textColor?:string,
public emptyColor?:string,
public innerPadding?:number
){
super();
this.results = new Array();
}
}<file_sep>/src/app/templates/triageAnalysisResult/triageAnalysisResult.module.ts
import { FormsModule } from "@angular/forms";
import { NgModule } from "@angular/core";
import { NgxChartsModule } from "@swimlane/ngx-charts";
import { TriageAnalysisResultComponent } from "./triageAnalysisResult.component";
import { SafePipe } from "../../pipe/safeUrlPipe";
import { DiffViewerTableModule } from "../diffViewerTable/diffViewerTable.module";
import { CommonModule } from "../../../../node_modules/@angular/common";
@NgModule({
imports: [
CommonModule,
FormsModule,
NgxChartsModule,
DiffViewerTableModule
],
exports: [
SafePipe,
TriageAnalysisResultComponent
],
declarations: [
SafePipe,
TriageAnalysisResultComponent
]
})
export class TriageAnalysisResultModule {}<file_sep>/src/app/core/common/entityView.ts
import { Constants } from '../../core/common/constants'
import { Revision, DebugInfo } from '../triage/triageAnalysis';
export class Functoid{
constructor(
public name: string,
public isDownloading: boolean
){
this.isDownloading = false;
}
}
export class MappingFile{
constructor(
public name?:string,
public version?: string,//dot splited
public majorVersion?: number,
public minorVersion?: number,
public isDownloading?: boolean,
public modelRevisions?: Array<Revision>
){
this.isDownloading = false;
this.modelRevisions = new Array<Revision>();
}
}
export class MappingSetting{
constructor(
public mappingFiles?: MappingFile[],
public functoids?: Functoid[]
){}
}
export class EntityViewVersion{
constructor(
public state?: string,
public virtualCluster?: string,
public vcRelativeFolder?: string,
public mappingSetting?: MappingSetting,
public lastUpdatedTime?: string,
public majorVersion?: number,
public minorVersion?: number,
public buildNumber?: number,
public version?: string,
public sharedStreamFolder?: string,
public relativeStreamPath?: string,
public viewStreamPath?: string,
public entitySpaceStreamPath?: string,
public fullDebugStreamFolder?: string,
public relativeDebugStreamFolder?: string
){
this.mappingSetting = new MappingSetting();
}
// get version(): string {
// return `${this.majorVersion}.${this.minorVersion}.${this.buildNumber}`;
// }
// get relativeStreamPath(): string{
// if (!this.virtualCluster || !this.vcRelativeFolder){
// return "";
// }
// var len = this.virtualCluster.length;
// var virtualCluster = this.virtualCluster;
// if (virtualCluster[len - 1] == '/')
// {
// virtualCluster = virtualCluster.substring(len - 1);
// }
// var slashPos = virtualCluster.lastIndexOf("/");
// var vcNameWithoutPrefix = virtualCluster.substring(slashPos + 1);
// return `/shares/${vcNameWithoutPrefix}${this.vcRelativeFolder}${Constants.streamView}`;
// }
// get viewStreamPath(): string{
// if (!this.virtualCluster || !this.vcRelativeFolder){
// return "";
// }
// return `${this.virtualCluster}${this.vcRelativeFolder}${Constants.streamView}`;
// }
// get entitySpaceStreamPath(): string{
// if (!this.virtualCluster || !this.vcRelativeFolder){
// return "";
// }
// let len = this.vcRelativeFolder.length;
// let entitySpaceFolderslashPos = this.vcRelativeFolder.substr(0, len - 1).lastIndexOf("/");
// let entitySpaceRelativeFolder = this.vcRelativeFolder.substr(0, entitySpaceFolderslashPos + 1);
// return `${this.virtualCluster}${entitySpaceRelativeFolder}${Constants.streamEntitySpace}`;
// }
// get entitySpaceDebugStreamFolder(): string{
// if (!this.virtualCluster || !this.vcRelativeFolder){
// return "";
// }
// return `${this.virtualCluster}${this.vcRelativeFolder}${Constants.streamView}`;
// }
}
export class EntityView{
constructor(
public viewKey?: string,
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public entitySpaceViewName?: string,
public model?: string,
public state?: string,
public createdBy?: string,
public createdTime?: string,
public updatedTime?: string,
public entitySpaceUrl?: string,
public entityViewUrl?: string,
public standardVersions?: EntityViewVersion[],
public triagedVersions?: EntityViewVersion[],
public debugInfo?: DebugInfo
) {
this.standardVersions = new Array<EntityViewVersion>();
this.triagedVersions = new Array<EntityViewVersion>();
}
}
export class SimplifiedCustomer {
constructor(
public customerId?: string,
public customerEnvs?: Array<string>
) {
this.customerEnvs = new Array<string>();
}
}
export class SimplifiedEntitySpace {
constructor(
public entitySpace?: string,
public entitySpaceViews?: Array<string>
) {
this.entitySpaceViews = new Array<string>();
}
}
export class EntityViewKey {
constructor(
public viewKey?: string,
public entitySpace?: string,
public entitySpaceView?: string
) {
}
}<file_sep>/src/app/components/triage/triage-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AuthenticationGuard } from "../loginAuth/authGuard";
const triageRoutes: Routes = [
{ path: "", redirectTo: "supervisor", pathMatch: "full" },
{
path: "supervisor",
loadChildren: "./triageSupervisor/triageSupervisor.module#TriageSupervisorModule"
},
{
path: "statistic",
loadChildren: "./triageStatistic/triageStatistic.module#TriageStatisticModule"
},
{
path: "analysis",
loadChildren: "./triageAnalysis/triageAnalysis.module#TriageAnalysisModule"
},
{
path: "analysis/:customerEnv/:viewKey",
loadChildren: "./triageAnalysis/triageAnalysis.module#TriageAnalysisModule"
},
{
path: "report",
loadChildren: "./triageReport/triageReport.module#TriageReportModule"
},{
path: "report/:displayType/:reportTimeSpan",
loadChildren: "./triageReport/triageReport.module#TriageReportModule"
}
// {
// path: "triage",
// component: TriageComponent,
// children: [
// {
// path: "statistic",
// component: TriageStatisticComponent,
// canActivate: [AuthenticationGuard]
// },
// {
// path: "supervisor",
// pathMatch: "full",
// component: TriageSupervisorComponent,
// canActivate: [AuthenticationGuard]
// },
// {
// path: "analysis",
// component: TriageAnalysisComponent,
// canActivate: [AuthenticationGuard]
// },
// {
// //hangle url which redirect from supervisor page
// path: "analysis/:customerEnv/:viewKey",
// component: TriageAnalysisComponent,
// canActivate: [AuthenticationGuard]
// },
// {
// path: "report",
// component: TriageReportComponent,
// canActivate: [AuthenticationGuard]
// },
// {
// path: "report/:displayType/:reportTimeSpan",
// component: TriageReportComponent,
// canActivate: [AuthenticationGuard]
// }
// ]
// }
];
@NgModule({
imports: [
RouterModule.forChild(
triageRoutes
//his outputs each router event that took place during each navigation lifecycle to the browser console
//{ enableTracing: true } // <-- debugging purposes only
)
],
exports: [RouterModule]
})
export class TriageRoutingModule {}
<file_sep>/karma.webpack.conf.js
module.exports = require('./config/test/karma.conf.js');
<file_sep>/readMe.txt
required:
1.Ctrl+ `;
2.npm install(may take long time about 15~30 mins);
3.npm start;
optional:
enable debug in vscode:
ref: https://stackoverflow.com/questions/42495655/how-to-debug-angular-with-vscode
Install the Chrome Debugger Extension
Create the launch.json (inside .vscode folder)
Use my launch.json (see below)
Create the tasks.json (inside .vscode folder)
Use my tasks.json (see below)
Press CTRL+SHIFT+B
Press F5
Attach
With "request": "attach", you must launch Chrome with remote debugging enabled in order for the extension to attach to it. Here's how to do that:
Windows
Right click the Chrome shortcut, and select properties
In the "target" field, append --remote-debugging-port=9222
Or in a command prompt, execute <path to chrome>/chrome.exe --remote-debugging-port=9222
macOS
In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
Linux
In a terminal, launch google-chrome --remote-debugging-port=9222
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Chrome",
"type": "chrome",
"request": "launch",
"port": 9222,
"url": "http://localhost:8080/",
"webRoot": "${workspaceRoot}"
},
{
"name": "Attach Chrome",
"type": "chrome",
"request": "attach",
"port": 9222,
"url": "http://localhost:8080/#",
"webRoot": "${workspaceRoot}"
},
{
"name": "Launch Chrome (Test)",
"type": "chrome",
"request": "launch",
"port": 9222,
"url": "http://localhost:8080/debug.html",
"webRoot": "${workspaceRoot}"
},
{
"name": "Launch Chrome (E2E)",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/node_modules/protractor/bin/protractor",
"protocol": "inspector",
"args": ["${workspaceRoot}/protractor.conf.js"]
}
]
}
tasks.json for angular/cli >= 1.3
{
"version": "2.0.0",
"tasks": [
{
"identifier": "ng serve",
"type": "npm",
"script": "start",
"problemMatcher": [],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"identifier": "ng test",
"type": "npm",
"script": "test",
"problemMatcher": [],
"group": {
"kind": "test",
"isDefault": true
}
}
]
}<file_sep>/src/app/core/entityAnalysis/entityAnalysis.ts
export class EntityAnalysis{
constructor(
public id: number,
public name: string,
public createdBy: string,
public createdTime: string,
public updatedBy: string,
public updatedTime: string,
public customerId: string,
public customerEnv: string,
public nameWithVersion?: string,
)
{}
}<file_sep>/src/app/core/common/constants.ts
import { EntityViewKey } from "./entityView";
export class Constants {
//triage debug folder stream
public static readonly streamValueChurnCounter: string = "ValueChurnCounter.ss";
public static readonly streamPipelineTopEntitiesChurnCounter: string = "PipelineTopEntitiesChurnCounter.ss";
public static readonly streamPipelineChurnCounter: string = "PipelineChurnCounter.ss";
public static readonly streamPipelineTypeChurnCounter: string = "PipelineTypeChurnCounter.ss";
public static readonly streamPipelineUpdatedEntitiesChurnCounterStreamName: string = "PipelineUpdatedEntitiesChurnCounter.ss";
public static readonly wrapStar = "WrapStar";
public static readonly streamView: string = "View.Combined.ss";
public static readonly streamEntitySpace: string = "Fact.Base.ss";
public static readonly folderDebug: string = "Debug";
public static readonly loggerName: string = "onboardingToolLogger";
public static readonly none: string = "none";
public static readonly weekDays: number = 7;
public static readonly monthDays: number = 30;
public static readonly topTen: number = 10;
public static readonly topFive: number = 5;
public static readonly oneDayMilliseconds : number = 1000 * 60 * 60 * 24;//1,000 ms * 60 s * 60 mins * 24 hrs = daily million seconds
public static readonly everyVersionLimit: number = 24;
public static readonly majorVersionLimit: number = 240;
public static readonly manualLimit: number = 1020;
public static readonly everyVersionTimeout: number = 8;
public static readonly majorVersionTimeout: number = 20;
public static readonly manualTimeout: number = 30;
public static readonly EPProdJobServiceUrl: string = "http://entityrepository.binginternal.com/";
public static readonly commitCommentTips = new Map<string, string>([
["SourceChange", "The root cause is source data's change. It's expected."],
["PageNotFound", "The root cause is source page's not found. It's expected."],
["NormalUpdate", "The root cause is source data's normal update. It's expected."]
]);
public static readonly specificViewsWithUnderline = new Map<string, EntityViewKey>([
["LinkedIn_JobPosting_LinkedIn_JobPosting_View", new EntityViewKey("LinkedIn_JobPosting_LinkedIn_JobPosting_View", "LinkedIn_JobPosting", "LinkedIn_JobPosting_View")],
["FoodRecipe_Experience_Recipes", new EntityViewKey("FoodRecipe_Experience_Recipes", "FoodRecipe_Experience", "Recipes")],
["int-Eventful_Data_Onboarding_FeedEvenfulView", new EntityViewKey("int-Eventful_Data_Onboarding_FeedEvenfulView", "int-Eventful_Data_Onboarding", "FeedEvenfulView")],
["musicbrainz_production_musicbrainz", new EntityViewKey("musicbrainz_production_musicbrainz", "musicbrainz_production", "musicbrainz")]
])
}<file_sep>/src/app/components/common/base.service.ts
import { OnInit } from '@angular/core';
import {
HttpClient,
HttpParams} from "@angular/common/http";
import { ApiController } from '../../core/enums'
import { RequestAction } from '../../core/enums'
import{ environment } from "../../../../config/environment/environment"
import { BaseComponent } from './base.component';
import { SimplifiedCustomer, SimplifiedEntitySpace } from '../../core/common/entityView';
export class BaseService extends BaseComponent implements OnInit {
serverUrl: string = environment.serverBaseUrl; //"http://localhost:9000/api";//"http://stcvm-961:9000/api";
entityPlatformServiceUrl = `${this.serverUrl}/EntityPlatform`;
ApiController: typeof ApiController = ApiController;
constructor(public httpClient: HttpClient) {
super();
}
ngOnInit() { }
getRequestApi(apiController: ApiController, requestAction: RequestAction, id?: number): string{
if (id !== undefined){
return `${this.serverUrl}/${ApiController[apiController]}/${id}/${RequestAction[requestAction]}`;
}else{
return `${this.serverUrl}/${ApiController[apiController]}/${RequestAction[requestAction]}`;
}
}
getCustomerIds() {
return this.httpClient.get<Array<SimplifiedCustomer>>(
`${this.entityPlatformServiceUrl}/allCustomerIds`, {}
);
}
getEntitySpaces(customerId: string, customerEnv: string) {
const httpParams = new HttpParams()
.set("customerId", customerId)
.set("customerEnv", customerEnv);
this.logger.info(httpParams.toString());
return this.httpClient.get<Array<SimplifiedEntitySpace>>(
`${this.entityPlatformServiceUrl}/allEntitySpaces`,
{
params: httpParams
}
);
}
}<file_sep>/src/app/core/viewer/EntityDiffViewer.ts
export class ViewerTriple {
constructor(
public subject?: string,
public viewerDiffProperties?: Array<ViewerDiffProperty>
) {
this.viewerDiffProperties = new Array<ViewerDiffProperty>();
}
}
export class ViewerDiffProperty {
constructor(
public property?: string,
public commonValues?: Array<string>,
public standardValues?: Array<string>,
public triagedValues?: Array<string>,
public standardExist?:boolean,
public triagedExist?:boolean
) {
this.commonValues = new Array<string>();
this.standardValues = new Array<string>();
this.triagedValues = new Array<string>();
}
}
<file_sep>/src/app/components/entityAnalysis/entitySpace/payloadStatistic.component.ts
import { Component, OnInit } from '@angular/core';
import {AnalysisType} from '../../../core/enums'
@Component({
selector: 'payload-statistic',
templateUrl: './payloadStatistic.component.html',
//styleUrls: ['./name.component.scss']
})
export class PayloadStatisticComponent implements OnInit {
analysisType: AnalysisType = AnalysisType.EntitySpace;
stage: string = "Statistic";
constructor() { }
ngOnInit() { }
}<file_sep>/src/app/components/entityAnalysis/analysisDashboard.mockdata.ts
import { ExperimentDto } from "../../core/experimentDto"
import { AnalysisType } from "../../core/enums"
export let experimentDtos: ExperimentDto[] = [
new ExperimentDto(
1,
"entitySpace1",
AnalysisType.EntitySpace,
"jixge" ,
"jixge" ,
"xingfeed",
"",
"xingFeedview",
"",
"Satori",
"Sources"
),
new ExperimentDto(
2,
"entityView",
AnalysisType.EntitySpace,
"jixge" ,
"jixge" ,
"xingfeed",
"",
"xingFeedview",
"",
"Satori",
"Sources"
),
new ExperimentDto(
3,
"graph",
AnalysisType.EntityGraph,
"jixge" ,
"jixge" ,
"xingfeed",
"",
"xingFeedview",
"",
"Satori",
"Sources"
),
]<file_sep>/src/app/components/triage/triageSupervisor/triageSupervisor.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TriageSupervisorComponent } from './triageSupervisor.component';
import { CommonModule } from '../../../../../node_modules/@angular/common';
import { TablePaginationComponent } from '../../../templates/tablePagination/tablePagination.component';
import { FormsModule } from '../../../../../node_modules/@angular/forms';
import { DisplayTypeFilterPipe } from '../../../pipe/displayTypeFilterPipe';
import { ViewStatisticPanelModule } from '../../../templates/viewStatisticPanel/viewStatisticPanel.module';
// routes
export const ROUTES: Routes = [
{ path: '', component: TriageSupervisorComponent }
];
@NgModule({
imports: [
CommonModule,
FormsModule,
ViewStatisticPanelModule,
RouterModule.forChild(ROUTES)
],
declarations: [
TriageSupervisorComponent,
TablePaginationComponent,
DisplayTypeFilterPipe
]
})
export class TriageSupervisorModule {}<file_sep>/src/app/templates/reportViewsDetailModal/reportViewsDetailModal.component.ts
import { Component, OnInit, Input } from "@angular/core";
import { BaseComponent } from "../../components/common/base.component";
import { TriageViewSupervisor } from "../../core/triage/triageViewSupervisor";
import { TriageService } from "../../components/triage/triage.service";
import { StackedVerticalBarChart } from "../../core/plugin/ngxChart";
import { TriageReport, TriageReportDetail } from "../../core/triage/triageReport";
import { ViewVersionLatency } from "../../core/triage/triageStatistic";
@Component({
selector: "report-detail-modal",
templateUrl: "./reportViewsDetailModal.component.html",
styles: []
})
export class ReportViewsDetailModalComponent extends BaseComponent implements OnInit {
@Input() triageViewSupervisors: Array<TriageViewSupervisor>;
@Input() triageReport: TriageReport;
@Input() startDate: string;
@Input() endDate: string;
//sort
IdDesc: boolean;
viewNameDesc: boolean;
missSlaDesc: boolean;
triageTimesDesc: boolean;
updatesDesc: boolean;
latestVersionLatencyDesc: boolean;
latestSucceedVersionLatencyDesc: boolean;
constructor(private triageService: TriageService) {
super();
}
ngOnInit() { }
expandViewDetail(triageViewSupervisor: TriageViewSupervisor) {
triageViewSupervisor.expandStatistic = !triageViewSupervisor.expandStatistic;
if (triageViewSupervisor.expandStatistic) {
if (
triageViewSupervisor.versionDetailStackedVerticalBarChart == null ||
triageViewSupervisor.versionDetailStackedVerticalBarChart.results.length == 0
) {
triageViewSupervisor.versionDetailStackedVerticalBarChart = new StackedVerticalBarChart(); //can't...of undefined
let allversions = new Array<ViewVersionLatency>();
if (triageViewSupervisor.allVersions && triageViewSupervisor.allVersions.length != 0) {
allversions = triageViewSupervisor.allVersions;
}
else{
this.triageService
.getViewVersionLatency(triageViewSupervisor.id, this.startDate, this.endDate)
.subscribe(result => {
allversions = result;
})
}
triageViewSupervisor.getMissSlaBarChart(allversions);
triageViewSupervisor.getMonthlyCountLineChart(allversions);
triageViewSupervisor.getCommitDelayLineChart(allversions);
triageViewSupervisor.getVersionDelayLineChart(allversions);
triageViewSupervisor.getVersionDetailStackedVerticalBarChart(allversions);
}
}
}
sortViewDetails(column: string) {
switch (column) {
case "Id":
this.IdDesc = !this.IdDesc;
let IdDescNum = this.IdDesc ? 1 : -1;
this.triageViewSupervisors.sort(
(a, b) => IdDescNum * (b.id > a.id ? 1 : -1)
);
break;
case "ViewName":
this.viewNameDesc = !this.viewNameDesc;
let viewNameDescNum = this.viewNameDesc ? 1 : -1;
this.triageViewSupervisors.sort(
(a, b) => viewNameDescNum * (b.entitySpaceViewName > a.entitySpaceViewName ? 1 : -1)
);
break;
case "MissSla":
this.missSlaDesc = !this.missSlaDesc;
let missSlaDescNum = this.missSlaDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => missSlaDescNum * (b.missSla - a.missSla));
break;
case "Updates":
this.updatesDesc = !this.updatesDesc;
let updatesDescNum = this.updatesDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => updatesDescNum * (b.updates - a.updates));
break;
case "TriageTimes":
this.triageTimesDesc = !this.triageTimesDesc;
let triageTimesDescNum = this.triageTimesDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => triageTimesDescNum * (b.triageTimes - a.triageTimes));
break;
case "LatestVersionLatency":
this.latestVersionLatencyDesc = !this.latestVersionLatencyDesc;
let latestVersionLatencyDescNum = this.latestVersionLatencyDesc ? 1 : -1;
this.triageViewSupervisors.sort( (a, b) => latestVersionLatencyDescNum * (b.latestVersionLatency - a.latestVersionLatency));
break;
case "LatestSucceedVersionLatency":
this.latestSucceedVersionLatencyDesc = !this.latestSucceedVersionLatencyDesc;
let latestSucceedVersionLatencyDescNum = this.latestSucceedVersionLatencyDesc ? 1 : -1;
this.triageViewSupervisors.sort((a, b) => {
if (b.latestSucceedVersionLatency == a.latestSucceedVersionLatency) {
return latestSucceedVersionLatencyDescNum * (b.latestVersionLatency - a.latestVersionLatency);
}
return (
latestSucceedVersionLatencyDescNum *
(b.latestSucceedVersionLatency - a.latestSucceedVersionLatency)
);
});
break;
}
}
}
<file_sep>/src/app/components/triage/triageAnalysis/triageAnalysis.component.ts
import { Component, OnInit } from "@angular/core";
import {
HttpClient,
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpParams,
HttpHeaders,
HttpResponse
} from "@angular/common/http";
import { ActivatedRoute } from "@angular/router";
import { Location } from "@angular/common";
import { saveAs } from "file-saver";
import { Observable } from "rxjs/Rx";
import { EntityView, Functoid, EntityViewVersion, MappingFile } from "../../../core/common/entityView";
import { BaseComponent } from "../../common/base.component";
import { TriageService } from "../triage.service";
import { AetherJob } from "../../../core/job/AetherJob";
import {
TriageAnalysisDto,
TriageAnalysis,
DebugInfo,
Revision,
TriageDebugInfoTable,
PropertyInfo,
AddedAndDeletedPair
} from "../../../core/triage/triageAnalysis";
import {
EntityComparison,
PropertyComparison,
ValueComparison,
TriageChurn,
TriageLayer,
TriageAnalysisResult,
TriageAnalysisResultCount,
DebugStreamExistense,
ChurnCount,
PropertyTriageChurn
} from "../../../core/triage/tirageAnlaysisResult";
import { forEach } from "@angular/router/src/utils/collection";
import { Subscription } from "rxjs/Subscription";
import { JobState, JobPanelState } from "../../../core/job/job";
import { JobPanelComponent } from "../../../templates/jobPanel/jobPanel.component";
import { SatoriDateTime } from "../../../helper/satoriDatetime";
import { NgxAlertsService } from "@ngx-plus/ngx-alerts";
import { AlertMsg } from "../../../core/plugin/ngAlert";
import swal from "sweetalert2";
import { constants } from "http2";
import { Constants } from "../../../core/common/constants";
import { TriageAnalysisResultDiaplayType } from "../../../core/enums";
@Component({
selector: "triage",
templateUrl: "./triageAnalysis.component.html",
styleUrls: ["./triageAnalysis.component.css"]
})
export class TriageAnalysisComponent extends BaseComponent implements OnInit {
customerIdEnvironment: string; // = "WrapStar-Prod";
entityViewKey: string; // = "WrapStar-Full_WrapStar_Redfin";
entityView: EntityView;
customerId: string;
customerEnv: string;
entitySpaceName: string;
entitySpaceViewName: string;
side2Type: string; // = "Triage";
triageAnalysis: TriageAnalysis;
currentSide1: EntityViewVersion;
currentSide2: EntityViewVersion;
isFetchingEntityView: boolean;
side1VersionNums: string[];
side2VersionNums: string[];
debugInfo: DebugInfo;
currentSide1Models: Array<Revision>;
currentSide2Models: Array<Revision>;
isFetchingAnalysisResult: boolean;
//job
triageAnalysisAetherJob: AetherJob; //Observable<AetherJob>;
triageAnalysisResultId: number;
jobPanelState: JobPanelState;
isForceSubmission: boolean;
//regular timer
timer: Observable<number>;
timerSubscription: Subscription;
//analysis reuslt
triageAnalysisResultCount: TriageAnalysisResultCount;
currentTriageResultCount: ChurnCount;
triageDebugStream: string;
currentChurn: TriageChurn;
triageAnalysisResult: TriageAnalysisResult;
entityViewerSide1: string;
entityViewerSide2: string;
isDebugInfoPane: boolean;
isFetchingExtraProperties: boolean;
extraPropertyInfos: Array<PropertyInfo>;
sideBySidePropertyInfos: Array<PropertyInfo>;
isFetchingSidebySideProperties: boolean;
//sideBySidePairs: Array<AddedAndDeletedPair>;
isFetchingSidebySideairs: boolean;
//triageViewCommit
commitComment: string;
previousCommit: string;
commitTips: Array<string>;
isCheckedCommitTip: boolean;
isCommitingTriagedView: boolean;
//entitySpaceStreamPath
standardEpRelativeStreamPath: string;
triageEpRelativeStreamPath: string;
modelIdsArr: Array<string>;
modelIdStr: string;
//function params to directive
submitTriageJobFunc: Function;
getTriageJobFunc: Function;
cancelTriageJobFunc: Function;
constructor(
private triageService: TriageService,
private route: ActivatedRoute,
private location: Location,
private alerts: NgxAlertsService
) {
super();
}
ngOnInit() {
this.triageAnalysisResultId = -1;
this.isFetchingEntityView = false;
this.isDebugInfoPane = true;
this.side2Type = "Triage";
this.customerIdEnvironment = "WrapStar-Prod";
this.entityViewKey = "WrapStar-Full_wrapstar_education_redfin";
this.debugInfo = new DebugInfo();
this.currentSide1Models = new Array<Revision>();
this.currentSide2Models = new Array<Revision>();
this.timer = Observable.timer(0, 30000);
this.commitTips = Array.from(Constants.commitCommentTips.keys());
this.isCheckedCommitTip = false;
this.isCommitingTriagedView = false;
this.commitComment = Constants.commitCommentTips.get("SourceChange");
this.previousCommit = "";
let customerEnv = this.route.snapshot.paramMap.get("customerEnv");
let viewKey = this.route.snapshot.paramMap.get("viewKey");
this.logger.info(customerEnv, viewKey);
if (customerEnv && viewKey) {
this.customerIdEnvironment = customerEnv;
this.entityViewKey = viewKey;
this.loadTriageAnalysis();
}
this.initializeMembers();
//function param
this.submitTriageJobFunc = () => this.submitTriageJob();
this.getTriageJobFunc = (jobId: number) => this.getTriageAnalysisJob(jobId);
this.cancelTriageJobFunc = () => this.cancelTriageJob();
}
initializeMembers() {
this.entityView = new EntityView();
this.triageAnalysis = new TriageAnalysis();
this.currentSide1 = new EntityViewVersion();
this.currentSide2 = new EntityViewVersion();
this.side1VersionNums = new Array<string>();
this.side2VersionNums = new Array<string>();
this.triageAnalysisResultCount = new TriageAnalysisResultCount();
this.currentTriageResultCount = new ChurnCount();
//this.triageDebugStream = "ValueChurnCounter"; //"PipelineTopEntitiesChurnCounter";
this.isForceSubmission = false;
this.resetJobAndResults();
}
resetJobAndResults() {
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
this.currentChurn = new TriageChurn();
this.triageAnalysisResult = new TriageAnalysisResult();
this.triageAnalysisAetherJob = new AetherJob();
this.jobPanelState = new JobPanelState();
}
loadTriageAnalysis(isForceRefresh: boolean = false) {
this.initializeMembers();
this.isFetchingEntityView = true;
this.parseEntitySpaceViewMeta();
this.getEntityView(isForceRefresh);
}
selectCommitTip(commmitTip: string, event: any) {
if (this.isCheckedCommitTip || this.previousCommit !== commmitTip) {
this.commitComment = Constants.commitCommentTips.get(commmitTip);
this.previousCommit = commmitTip;
this.isCheckedCommitTip = false;
$(event.target).removeClass("checked");
} else {
this.commitComment = "";
this.isCheckedCommitTip = true;
$(event.target).addClass("checked");
}
}
commitView() {
swal({
title: "Are you sure to commit this view?",
text: "You won't be able to revert this !",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, commit it !"
}).then(result => {
if (result.value) {
this.isCommitingTriagedView = true;
this.triageService
.commitTriagedView(
this.customerId,
this.customerEnv,
this.entitySpaceName,
this.entitySpaceViewName,
this.commitComment
)
.subscribe(commitResult => {
this.logger.info("commit result", commitResult);
swal({
title: "Commit !",
text: "The view has been commit :)",
type: "success",
timer: 1300
}).then(r => {
this.isCommitingTriagedView = false;
this.loadTriageAnalysis(true);
});
});
}
});
}
parseEntitySpaceViewMeta() {
let params = this.customerIdEnvironment.split("-");
let len = params.length;
if (len >= 2) {
this.customerId = params[0];
this.customerEnv = params[1];
let underLineCount = this.entityViewKey.match(/_/g).length;
let pos = this.entityViewKey.indexOf("_");
this.entitySpaceName = this.entityViewKey.substr(0, pos);
this.entitySpaceViewName = this.entityViewKey.substr(pos + 1);
let specificEntityViewKey = Constants.specificViewsWithUnderline.get(this.entityViewKey);
if (underLineCount >= 2 && specificEntityViewKey) {
this.entitySpaceName = specificEntityViewKey.entitySpace;
this.entitySpaceViewName = specificEntityViewKey.entitySpaceView;
}
this.entityView = new EntityView(
this.entityViewKey,
this.customerId,
this.customerEnv,
this.entitySpaceName,
this.entitySpaceViewName
);
}
this.logger.info("parseEntitySpaceViewMeta", this.entityView);
}
getEntityView(isForceRefresh: boolean = false) {
this.entityView = new EntityView();
return (
this.triageService
.getEntityView(this.customerId, this.customerEnv, this.entityViewKey, isForceRefresh)
// .finally(() => {
// this.isFetchingEntityView = false;
// this.logger.info("finally");
// })
.subscribe(
entityView => {
this.entityView = entityView;
this.initSide1Version();
this.initSide2Version();
this.debugInfo = entityView.debugInfo;
this.logger.info("entityView", entityView);
this.getTriageAnalysis(
this.customerId,
this.customerEnv,
this.entityViewKey,
this.currentSide1.version,
this.currentSide2.version
);
this.isFetchingEntityView = false;
},
err => {
this.isFetchingEntityView = false;
this.logger.info("err", err);
}
)
);
}
getWrapStarModelDetail() {
this.modelIdsArr = new Array<string>();
let side1MappingFileNames = this.currentSide1.mappingSetting.mappingFiles.map(t => t.name);
this.currentSide1.mappingSetting.mappingFiles.forEach(t => {
this.triageService
.getWrapstarModelVersion(
this.customerId,
this.customerEnv,
this.entityViewKey,
this.currentSide1.version,
t.name
)
.subscribe(modelRevisions => {
this.logger.info("currentSide1", JSON.stringify(modelRevisions));
t.modelRevisions = new Array<Revision>();
modelRevisions.forEach(r => {
t.modelRevisions.push(r);
this.modelIdsArr.push(r.model);
this.modelIdStr = this.modelIdsArr.join(";");
});
if (this.currentSide2 && this.currentSide2.mappingSetting.mappingFiles) {
this.currentSide2.mappingSetting.mappingFiles.forEach(m => {
if (t.name === m.name) {
//m.modelRevisions = modelRevisions;
m.modelRevisions = new Array<Revision>();
modelRevisions.forEach(r => {
m.modelRevisions.push(r);
});
}
});
}
this.logger.info(
"this.currentSide2.mappingSetting.mappingFiles",
this.currentSide2.mappingSetting.mappingFiles
);
});
});
if (this.currentSide2 && this.currentSide2.mappingSetting.mappingFiles) {
this.currentSide2.mappingSetting.mappingFiles.forEach(t => {
let mappingFile = this.currentSide1.mappingSetting.mappingFiles.find(m => m.name == t.name);
if (side1MappingFileNames.indexOf(t.name) === -1) {
this.triageService
.getWrapstarModelVersion(
this.customerId,
this.customerEnv,
this.entityViewKey,
this.currentSide1.version,
t.name
)
.subscribe(modelRevisions => {
this.logger.info("currentSide2", JSON.stringify(modelRevisions));
t.modelRevisions = new Array<Revision>();
modelRevisions.forEach(r => {
t.modelRevisions.push(r);
});
});
} else {
t.modelRevisions = mappingFile.modelRevisions;
}
});
}
}
getTriageAnalysis(
customerId: string,
customerEnv: string,
viewKey: string,
standardVersion: string,
triagedVersion: string
) {
this.triageService
.getTriageAnalysis(customerId, customerEnv, viewKey, standardVersion, triagedVersion)
.subscribe((triageAnalysis: TriageAnalysis) => {
this.logger.info("triageAnalysis1", triageAnalysis);
this.triageAnalysis = triageAnalysis;
this.resetJobAndResults();
//lihu: need to fix later
this.standardEpRelativeStreamPath = this.currentSide1.entitySpaceStreamPath.replace(
"https://cosmos08.osdinfra.net/cosmos",
"/shares"
);
this.triageEpRelativeStreamPath = this.currentSide2.entitySpaceStreamPath.replace(
"https://cosmos08.osdinfra.net/cosmos",
"/shares"
);
if (triageAnalysis) {
//this.debugInfo = triageAnalysis.debugInfo;
this.triageAnalysisResultId = triageAnalysis.resultId;
this.logger.info("triageAnalysis", triageAnalysis);
this.logger.info("entityView", this.entityView);
this.logger.info("side1", this.currentSide1);
this.logger.info("side2", this.currentSide2);
this.logger.info("debugInfo", this.debugInfo);
if (triageAnalysis.analysisJobId != -1) {
this.setJobStateTimer(triageAnalysis.analysisJobId);
}
}
});
}
initSide1Version(index: number = 0) {
if (this.entityView.standardVersions.length > 0) {
this.currentSide1 = this.entityView.standardVersions[0];
if (index != 0) {
this.currentSide1 = this.entityView.standardVersions[index];
}
this.side1VersionNums = this.entityView.standardVersions.map(t => t.version);
}
}
initSide2Version() {
this.currentSide2 = new EntityViewVersion();
if (this.side2Type == "Triage") {
this.side2VersionNums = this.entityView.triagedVersions.map(t => t.version);
let len = this.side2VersionNums.length;
this.initSide1Version();
if (len > 0) {
this.currentSide2 = this.entityView.triagedVersions[0];
this.setSide2ViewVersionNum(this.side2VersionNums[0]);
} else {
this.resetJobAndResults();
}
} else {
this.side2VersionNums = this.side1VersionNums;
let len = this.side2VersionNums.length;
this.initSide1Version(1);
if (len > 0) {
this.currentSide2 = this.entityView.standardVersions[0];
this.setSide2ViewVersionNum(this.side2VersionNums[0]);
} else {
this.resetJobAndResults();
}
}
}
getVersionSplitNumSum(version: string): number {
var splitedVersionStrings = version.split(".");
var splitedVersionNumbers = splitedVersionStrings.map(Number);
var splitedVersionNumSum = splitedVersionNumbers.reduce((total: number, num: number) => {
return total * 10 + num;
});
return splitedVersionNumSum;
}
validateVersionNum(side1Version: string, side2Version: string) {
var side1Sum = this.getVersionSplitNumSum(side1Version);
var side2Sum = this.getVersionSplitNumSum(side2Version);
if (side1Sum > side2Sum) {
return false;
} else {
return true;
}
}
setSide1ViewVersionNum(version: string) {
this.currentSide1 = this.entityView.standardVersions.find(t => t.version == version);
//add check
if (this.validateVersionNum(this.currentSide1.version, this.currentSide2.version)) {
this.getTriageAnalysis(
this.customerId,
this.customerEnv,
this.entityViewKey,
this.currentSide1.version,
this.currentSide2.version
);
}
}
setSide2ViewVersionNum(version: string) {
if (this.side2Type == "Triage") {
this.currentSide2 = this.entityView.triagedVersions.find(t => t.version == version);
} else {
this.currentSide2 = this.entityView.standardVersions.find(t => t.version == version);
}
if (this.validateVersionNum(this.currentSide1.version, this.currentSide2.version)) {
this.getTriageAnalysis(
this.customerId,
this.customerEnv,
this.entityViewKey,
this.currentSide1.version,
this.currentSide2.version
);
if (this.customerId === Constants.wrapStar) {
this.getWrapStarModelDetail();
}
}
}
//#region download artifact
downloadFunctoid(dotSplitedVersionNum: string, functoid: Functoid) {
functoid.isDownloading = true;
this.triageService
.downloadFunctoid(
this.customerId,
this.customerEnv,
this.entityViewKey,
dotSplitedVersionNum,
functoid.name
)
.subscribe((response: HttpResponse<any>) => {
const functoidName: string = response.headers.get("filename");
const blob = new Blob([response.body], {
type: "application/octet-binary,charset=utf-8"
});
saveAs(blob, functoid.name);
functoid.isDownloading = false;
});
}
downloadMappingFile(dotSplitedVersionNum: string, mappingFile: MappingFile) {
mappingFile.isDownloading = true;
this.triageService
.downloadMappingFile(
this.customerId,
this.customerEnv,
this.entityViewKey,
dotSplitedVersionNum,
mappingFile.name
)
.subscribe((response: HttpResponse<any>) => {
const mappingFileName: string = response.headers.get("filename");
const blob = new Blob([response.body], {
type: "application/xml,charset=utf-8"
});
saveAs(blob, `${mappingFileName}@${mappingFile.version}.xml`);
mappingFile.isDownloading = false;
});
}
downloadWrapstarModel(modelRevision: Revision) {
modelRevision.isDownloading = true;
this.triageService
.downloadWrapstarModel(modelRevision.model, modelRevision.version)
.subscribe((response: HttpResponse<any>) => {
const wrapstarModelName: string = response.headers.get("filename");
this.logger.info("response", response);
const blob = new Blob([response.body], {
type: "application/xml,charset=utf-8"
});
saveAs(blob, `WrapstarModel@${modelRevision.version}.xml`);
modelRevision.isDownloading = false;
});
}
//#endregion
//region job related
submitTriageJob() {
this.logger.info("side1", this.currentSide1.version);
this.logger.info("side2", this.currentSide2.version);
if (
this.currentSide1.version &&
this.currentSide2.version &&
!this.validateVersionNum(this.currentSide1.version, this.currentSide2.version)
) {
swal(new AlertMsg("Wrong!", "error", "The standard version should earlier than triage version!", 3000));
return;
}
this.logger.info("Submit triage job");
let triageAnalysisDto = new TriageAnalysisDto(
this.customerId,
this.customerEnv,
this.entitySpaceName,
this.entitySpaceViewName,
this.currentSide2.relativeDebugStreamFolder,
this.currentSide1.version,
this.currentSide2.version,
this.currentSide1.relativeStreamPath,
this.currentSide2.relativeStreamPath
);
this.jobPanelState.isSubmiting = true;
this.triageService
.submitTriageAnalysisJob(
this.isForceSubmission,
this.triageAnalysisAetherJob.virtualCluster,
this.triageAnalysisAetherJob.cloudPriority,
triageAnalysisDto
)
.subscribe((aetherJob: AetherJob) => {
this.logger.info("aetherJobsubmit", aetherJob);
this.triageAnalysisAetherJob = aetherJob;
this.currentChurn = new TriageChurn();
this.setJobPanelState(aetherJob.state);
this.setJobStateTimer(aetherJob.id);
});
}
setJobStateTimer(jobId: number) {
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
this.logger.info("timer start");
this.timerSubscription = this.timer
.takeWhile(
() =>
this.triageAnalysisAetherJob.state === JobState.Waiting ||
this.triageAnalysisAetherJob.state === JobState.Queued ||
this.triageAnalysisAetherJob.state === JobState.Running
)
.subscribe(t => {
this.getTriageAnalysisJob(jobId);
});
}
getTriageAnalysisJob(jobId: number) {
this.triageService.getTriageAnalysisJob(jobId).subscribe((aetherJob: AetherJob) => {
this.logger.info("aether job:", aetherJob);
// this.cloudPriority = aetherJob.cloudPriority;
// this.virtualCluster = aetherJob.virtualCluster;
this.triageAnalysisAetherJob = aetherJob;
this.triageAnalysisResultId = aetherJob.resultId;
this.setJobPanelState(aetherJob.state);
//get analysis results
// if (aetherJob.state === JobState.Succeeded) {
// this.getTriageAnalysisResultCount(this.triageAnalysisResultId);
// }
});
this.logger.info("Get triage job");
}
setJobPanelState(jobState: JobState) {
switch (jobState) {
case JobState.Waiting:
case JobState.Queued:
case JobState.Running: {
this.jobPanelState.isRunning = true;
this.jobPanelState.isCanceling = false;
this.jobPanelState.isSubmiting = false;
break;
}
case JobState.Failed:
case JobState.Canceled:
case JobState.TimeOut:
case JobState.UnKnown:
case JobState.Succeeded: {
this.jobPanelState.isCanceling = false;
this.jobPanelState.isSubmiting = false;
this.jobPanelState.isRunning = false;
break;
}
}
this.logger.info("jobPanelState", this.jobPanelState);
}
cancelTriageJob() {
this.jobPanelState.isCanceling = true;
this.logger.info("Cancel triage job");
if (this.triageAnalysisAetherJob.id !== -1) {
this.triageService.cancelTriageAnalysisJob(this.triageAnalysisAetherJob.id).subscribe(aetherJob => {
this.jobPanelState.isCanceling = false;
this.jobPanelState.isRunning = false;
this.triageAnalysisAetherJob = aetherJob;
this.timerSubscription.unsubscribe();
this.logger.info("cancel", aetherJob);
});
}
}
//#endregion
//#region triage analysis result related
//to combine table rows to group triples by subject or property
setCollapseTag(churn: TriageChurn) {
this.setEntityComparisonCollapseTag(churn.deleted.entity);
this.setEntityComparisonCollapseTag(churn.added.entity);
this.setPropertyComparisonCollapseTag(churn.deleted.property);
this.setPropertyComparisonCollapseTag(churn.added.property);
}
setEntityComparisonCollapseTag(triageLayer: Array<EntityComparison>) {
//this.logger.info("triageLayer", triageLayer);
if (triageLayer.length !== 0) {
triageLayer.forEach(t => {
//this.logger.info("subjectValueComparisons", t.subjectValueComparisons);
if (t.propertyValueComparisons && t.propertyValueComparisons.length !== 0) {
//this.logger.info(t.property);
t.propertyValueComparisons[0].isFirst = true;
}
});
}
}
setPropertyComparisonCollapseTag(triageLayer: Array<PropertyComparison>) {
//this.logger.info("triageLayerProperty", triageLayer);
if (triageLayer.length !== 0) {
triageLayer.forEach(t => {
//this.logger.info("subjectValueComparisons", t.subjectValueComparisons);
if (t.subjectValueComparisons && t.subjectValueComparisons.length !== 0) {
//this.logger.info(t.property);
t.subjectValueComparisons[0].isFirst = true;
}
});
}
}
getTriageAnalysisResultByProperty(
propertyInfo: any,
debugStream: string,
resultType: TriageAnalysisResultDiaplayType
) {
this.logger.info("before", propertyInfo, this.triageAnalysisResultId);
if (this.triageAnalysisResultId === -1) {
swal({
text: "Sorry, triage analysis job is still running!",
type: "warning",
timer: 2000,
cancelButtonColor: "OK",
});
return;
}
if (!propertyInfo.expandDetail) {
this.collapseAllPropertyResult(resultType);
}
propertyInfo.expandDetail = !propertyInfo.expandDetail;
if (propertyInfo.expandDetail && this.isDebugInfoPane && !propertyInfo.triageChurn) {
this.triageService
.getTriageResultByProperty(this.triageAnalysisResultId, propertyInfo.predicate, debugStream)
.map(t => {
//convert satori time
this.convertSatoriTimeToGeneralTime(t.triageChurn);
return t;
})
.subscribe((propertyTriageChurn: PropertyTriageChurn) => {
this.setCollapseTag(propertyTriageChurn.triageChurn);
propertyInfo.churnCount = propertyTriageChurn.churnCount;
propertyInfo.triageChurn = propertyTriageChurn.triageChurn;
this.logger.info("after", propertyInfo);
});
}
}
getExtraProperties() {
if (!this.extraPropertyInfos && this.triageAnalysisResultId != -1) {
this.isFetchingExtraProperties = true;
this.triageService
.getExtraProperties(this.triageAnalysis.id, this.triageAnalysisResultId)
.subscribe((properties: Array<string>) => {
this.isFetchingExtraProperties = false;
this.extraPropertyInfos = properties.map(p => new PropertyInfo(p));
this.logger.info("extraPropertyInfos", this.extraPropertyInfos);
});
}
}
getSideBySideProperties() {
if (!this.sideBySidePropertyInfos && this.triageAnalysisResultId != -1) {
this.isFetchingSidebySideProperties = true;
this.triageService
.getSideBySideProperties(this.triageAnalysisResultId)
.subscribe((properties: Array<string>) => {
this.sideBySidePropertyInfos = properties.map(p => new PropertyInfo(p));
this.isFetchingSidebySideProperties = false;
});
}
}
getSideBySidePairsByProperty(propertyInfo: PropertyInfo, resultType: TriageAnalysisResultDiaplayType) {
if (!propertyInfo.expandDetail) {
this.collapseAllPropertyResult(resultType);
}
propertyInfo.expandDetail = !propertyInfo.expandDetail;
if (!propertyInfo.sideBySidePairs && !this.isFetchingSidebySideairs) {
this.isFetchingSidebySideairs = true;
this.triageService
.getSideBySidePairsByProperty(this.triageAnalysisResultId, propertyInfo.predicate)
.subscribe((sideBySidePairs: Array<AddedAndDeletedPair>) => {
propertyInfo.sideBySidePairs = sideBySidePairs;
this.isFetchingSidebySideairs = false;
});
}
}
collapseAllPropertyResult(resultType: TriageAnalysisResultDiaplayType) {
switch (resultType) {
case TriageAnalysisResultDiaplayType.DebugInfo:
this.debugInfo.triageDebugInfoFiveColTables.forEach(t =>
t.debugInfoFiveCols.forEach(c => (c.expandDetail = false))
);
this.debugInfo.triageDebugInfoSixColTables.forEach(t =>
t.debugInfoSixCols.forEach(c => (c.expandDetail = false))
);
break;
case TriageAnalysisResultDiaplayType.Extra:
if (this.extraPropertyInfos) {
this.extraPropertyInfos.forEach(t => (t.expandDetail = false));
}
break;
case TriageAnalysisResultDiaplayType.SBS:
if (this.sideBySidePropertyInfos) {
this.sideBySidePropertyInfos.forEach(t => (t.expandDetail = false));
}
break;
}
}
convertSatoriTimeToGeneralTime(triageChurn: TriageChurn): TriageChurn {
this.convertTriageLayerSatoriTime(triageChurn.added);
this.convertTriageLayerSatoriTime(triageChurn.deleted);
this.convertTriageLayerSatoriTime(triageChurn.churned);
return triageChurn;
}
convertTriageLayerSatoriTime(triageLayer: TriageLayer) {
triageLayer.entity.forEach(t => {
t.propertyValueComparisons.forEach(p => {
p.standardValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
p.triagedValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
});
});
triageLayer.property.forEach(t => {
t.subjectValueComparisons.forEach(p => {
p.standardValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
p.triagedValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
});
});
triageLayer.value.forEach(t => {
t.standardValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
t.triagedValues.forEach(v => {
v.value = this.convertSatoriTime(v.value);
});
});
}
convertSatoriTime(value: string): string {
if (value.indexOf('"^^mso:datetime') != -1) {
let pos = value.indexOf('"^^');
let satoriTime = value.substr(1, pos - 1);
let satoriDatetime = new SatoriDateTime(value);
return value.replace(satoriTime, satoriDatetime.toStringSecond());
}
return value;
}
//#endregion
}
<file_sep>/src/app/app.component.ts
import { Component, OnDestroy, OnInit } from "@angular/core";
import { AdalService } from "adal-angular4";
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from "@angular/router";
import { environment } from "../../config/environment/environment";
import { User } from "./core/common/authUser";
//import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { BaseComponent } from "./components/common/base.component";
import "../assets/css/styles.css";
// import '../assets/css/AdminLTE.css';
// import '../assets/css/_all-skins.css';
//import '../assets/css/side-bar.css';
//import '../assets/sass/test.scss';
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent extends BaseComponent implements OnInit, OnDestroy {
private sub: any;
user: User;
constructor(
//private slimLoader: SlimLoadingBarService,
private router: Router,
private adalService: AdalService
) {
super();
if (environment.enableAAD) {
this.adalService.init(environment.adalConfig);
}
}
ngOnInit() {
if (environment.enableAAD) {
//don't put handleWindowCallback with init, it may cause auth error when call authed web api
// Handle callback if this is a redirect from Azure
this.adalService.handleWindowCallback();
}
this.user = new User();
if (this.adalService.userInfo.authenticated) {
this.logger.info("authenticated user info", this.adalService.userInfo);
let profile = this.adalService.userInfo.profile;
this.user = new User(profile.name, profile.upn, this.adalService.userInfo.authenticated);
} else {
throw "";
}
//this.startLoading();
// Listen the navigation events to start or complete the slim bar loading
this.sub = this.router.events.subscribe(
event => {
if (event instanceof NavigationStart && !this.adalService.userInfo.authenticated) {
// this.slimLoader.start();
this.router.navigate(["/login"], { queryParams: { returnUrl: "/triage/supervisor" } });
} else if (
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError
) {
//this.slimLoader.complete();
}
},
(error: any) => {
//this.slimLoader.complete();
}
);
}
// Logout Method
logout() {
if (this.user.authenticated) {
this.adalService.logOut();
this.adalService.clearCache();
}
}
ngOnDestroy(): any {
this.sub.unsubscribe();
}
// startLoading() {
// this.slimLoader.start(() => {
// this.logger.info('Loading complete');
// });
// }
// stopLoading() {
// this.slimLoader.stop();
// }
// completeLoading() {
// this.slimLoader.complete();
// }
}
<file_sep>/src/app/components/entityAnalysis/common/analysisNav.component.ts
import { Component, OnInit, Input } from '@angular/core';
import * as $ from 'jquery';
import { AnalysisType } from '../../../core/enums'
import { BaseComponent } from '../../common/base.component';
@Component({
selector: 'analysis-nav',
templateUrl: './analysisNav.component.html',
styleUrls: ['./analysisNav.component.css']
})
export class AnalysisNavComponent extends BaseComponent implements OnInit {
@Input() analysisType: AnalysisType;
@Input() stage: string;
constructor() {
super();
}
ngOnInit() {
this.logger.info(this.analysisType);
}
ngAfterViewInit() {
(<any>$('[data-toggle="tooltip"]')).tooltip();
}
}<file_sep>/src/app/core/entityAnalysis/entityViewAnalysis.ts
import { EntityAnalysis } from "./entityAnalysis"
export class EntityViewAnalysis extends EntityAnalysis{
constructor(
id: number,
name: string,
createdBy: string,
createdTime: string,
updatedBy: string,
updatedTime: string,
customerId: string,
customerEnv: string,
entityViewName: string,
entityViewVersion: string,
)
{
super(id, name, createdBy, createdTime, updatedBy, updatedTime, customerId, customerEnv);
}
}<file_sep>/src/app/components/metric/onboardingTfsMetric/onboardingTfsMetric.component.ts
import { Component, OnInit } from "@angular/core";
import { BaseComponent } from "../../common/base.component";
import { MetricService } from "../metric.service";
import { OnboardingTfsFeature } from "../../../core/metric/metric";
import * as XLSX from 'xlsx';
import { ExcelService } from "../../common/excel.service";
@Component({
selector: "onboarding-tfs-metric",
templateUrl: "./onboardingTfsMetric.component.html",
styleUrls: ["./onboardingTfsMetric.component.css"]
})
export class OnboardingTfsMetricComponent extends BaseComponent implements OnInit {
isGeneratingMetric: boolean;
onboardingTfsFeatures: Array<OnboardingTfsFeature>;
tfsQueryId: string;
isExportingAsExcel: boolean;
tfsUrlPrefix: string;
constructor(public metricService: MetricService, public excelService: ExcelService) {
super();
}
ngOnInit() {
this.isGeneratingMetric = false;
this.isExportingAsExcel = false;
this.tfsQueryId = "db1f0e76-7875-4161-a5d3-a093ea249492";
this.tfsUrlPrefix = "https://msasg.visualstudio.com/Satori%20Data%20Onboarding/_workitems/edit/";
this.generateOnboardingMetric();
}
generateOnboardingMetric() {
this.isGeneratingMetric = true;
this.metricService.generateTfsMetric(this.tfsQueryId).subscribe((onboardingTfsFeatures: Array<OnboardingTfsFeature>) => {
this.isGeneratingMetric = false;
this.onboardingTfsFeatures = onboardingTfsFeatures;
});
}
convertMetricToArray(): string[][] {
let metricExcelFromatData: string[][] = [];
let featureCount: number = this.onboardingTfsFeatures.length;
let idx: number = 0;
metricExcelFromatData[idx++] = ["Type", "Title", "Ticketing", "Queued", "E2EEngineering", "E2EHead", "Engineering", "E2ETail"];
for(let i = 0; i < featureCount; i++) {
let userStoryCount: number = this.onboardingTfsFeatures[i].userStories.length;
metricExcelFromatData[idx++] = ["Feature", this.onboardingTfsFeatures[i].title, "", "", "", "", "", this.onboardingTfsFeatures[i].e2ETailHours];
for(let j = 0; j < userStoryCount; j++) {
let taskCount: number = this.onboardingTfsFeatures[i].userStories[j].userTasks.length;
metricExcelFromatData[idx++] = ["OnboardRequest",
this.onboardingTfsFeatures[i].userStories[j].title,
this.onboardingTfsFeatures[i].userStories[j].ticketingHours,
this.onboardingTfsFeatures[i].userStories[j].queuedHours,
this.onboardingTfsFeatures[i].userStories[j].e2EEngineeringHours,
this.onboardingTfsFeatures[i].userStories[j].e2EHeadHours,
this.onboardingTfsFeatures[i].userStories[j].engineeringHours,
this.onboardingTfsFeatures[i].userStories[j].e2ETailHours];
for (let k = 0; k < taskCount; k++) {
metricExcelFromatData[idx++] = ["Task",
this.onboardingTfsFeatures[i].userStories[j].userTasks[k].title,
"", "", "", "", "",
this.onboardingTfsFeatures[i].userStories[j].userTasks[k].e2ETailHours];
}
}
}
this.logger.info("metricExcelFromatData", metricExcelFromatData);
return metricExcelFromatData;
}
exportAsExcel() {
let exportData: string[][] = this.convertMetricToArray();
this.excelService.exportAsExcel(this.tfsQueryId, exportData, this.isGeneratingMetric);
}
}
<file_sep>/src/app/components/entityAnalysis/dashboard/analysisDashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ExperimentDto } from "../../../core/experimentDto"
import { experimentDtos } from '../analysisDashboard.mockdata'
import { AnalysisType } from '../../../core/enums'
import { EntitySpaceAnalysis } from '../../../core/entityAnalysis/entitySpaceAnalysis'
import { EntitySpaceAnalysisService } from '../service/entitySpaceAnalysis.service'
import { AnalysisDashboardService } from '../service/analysisDashboard.service'
import { BaseComponent } from '../../common/base.component';
@Component({
selector: 'analysis-dashboard',
templateUrl: './analysisDashboard.component.html',
//styleUrls: ['./name.component.css']
})
export class AnalysisDashboardComponent extends BaseComponent implements OnInit {
entityAnalysisDtos: any;
AnalysisType: typeof AnalysisType = AnalysisType;
selectedExperiment: ExperimentDto;
currentAnalysisType: AnalysisType;
constructor(
private router: Router,
private analysisDashboardService: AnalysisDashboardService
) {
super();
}
ngOnInit() {
let currentUrl = this.router.url;
this.logger.info(currentUrl);
let pos = currentUrl.lastIndexOf('/');
let analysisTypeStr = currentUrl.substr(pos + 1);
this.logger.info(analysisTypeStr);
this.currentAnalysisType = this.getCurrentAnalysisType(analysisTypeStr);
this.logger.info(this.currentAnalysisType);
this.getAnalysisDtos(this.currentAnalysisType);
//this.logger.info(experimentDtos);
// this.analysisDashboardService.getEntitySpaceAnalysisDtos()
// .subscribe((response) => {
// this.logger.info(response);
// this.entityAnalysisDtos = <EntitySpaceAnalysis[]>response;
// this.logger.info("entityAnalysisDtos", this.entityAnalysisDtos);
// return this.entityAnalysisDtos;
// });
}
getCurrentAnalysisType(analysisTypeStr: string): AnalysisType {
switch (analysisTypeStr) {
case "entityspace": {
return AnalysisType.EntitySpace;
}
case "entityview": {
return AnalysisType.EntitySpace;
}
case "entitygraph": {
return AnalysisType.EntitySpace;
}
}
}
getAnalysisDtos(analysisType: AnalysisType) {
switch (analysisType) {
case AnalysisType.EntitySpace: {
this.analysisDashboardService.getEntitySpaceAnalysisDtos()
.subscribe((response) => {
this.logger.info(response);
this.entityAnalysisDtos = <EntitySpaceAnalysis[]>response;
this.logger.info("entityAnalysisDtos", this.entityAnalysisDtos);
return this.entityAnalysisDtos;
});
}
case AnalysisType.EntityView: {
return AnalysisType.EntitySpace;
}
case AnalysisType.EntityGraph: {
return AnalysisType.EntitySpace;
}
}
}
gotoEntityAnalysisDetail() {
this.router.navigate(['/detail', this.selectedExperiment.id]);
}
test() {
//this.logger.info(experimentDtos);
}
}<file_sep>/src/app/components/dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { ExperimentDto } from "../../core/experimentDto"
//import { experimentDtos } from '../../app.mockdata'
import { AnalysisType } from '../../core/enums'
import { BaseComponent } from '../common/base.component';
@Component({
selector: 'selector',
templateUrl: './dashboard.component.html',
styleUrls: ["./dashboard.component.css"]
//styleUrls: ['./name.component.css']
})
export class DashboardComponent extends BaseComponent implements OnInit {
experimentDtos: Array<ExperimentDto>;
AnalysisType: typeof AnalysisType = AnalysisType;
constructor() {
super();
}
ngOnInit() {
//this.logger.info(experimentDtos);
//this.experimentDtos = experimentDtos;
}
test() {
//this.logger.info(experimentDtos);
}
}<file_sep>/src/app/core/common/serviceProvider.ts
export class ServiceProvider{
constructor(){}
}<file_sep>/src/app/core/triage/triageAnalysis.ts
import { EntityView } from "../common/entityView"
import { TriageMode } from "../enums";
import { TriageChurn, ChurnCount, PropertyValue } from "./tirageAnlaysisResult";
export class Triple{
constructor(
public subject: string,
public property: string,
public value: string
){}
}
// export class TriageDelete{
// constructor(
// public triageType: EntityViewVersionState,
// public entityDelete: string[],
// public propertyDelete: string[],
// public valueDelete: string[]
// ){}
// }
// export class TriageChurn{
// constructor(
// public triageType: EntityViewVersionState,
// ){}
// }
// export class TriageAdd{
// constructor(
// public triageType: EntityViewVersionState,
// ){}
// }
// export class TriageProperty{
// constructor(
// public property: string,
// public standardValues: string[],
// public triageValues: string[]
// ){}
// }
// export class TriageComparison{
// constructor(
// public subject: string,
// public properties: TriageProperty[]){
// }
// }
// export class TriageDiff{
// constructor(
// public triageType: EntityViewVersionState,
// public entity: TriageComparison,
// public property: TriageComparison,
// public value: TriageComparison
// ){}
// }
export class TriageAnalysis{
constructor(
public id?: number,
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public entitySpaceViewName?: string,
public stardardVersion?: string,
public triagedVersion?: string,
public standardViewRelativeStreamPath?: string,
public triagedViewRelativeStreamPath?: string,
public triageAnalysisOutputFolder?: string,
//public entityView?: EntityView,
public debugInfo?: DebugInfo,
public resultId?: number,
public analysisJobId?: number
){}
}
export class TriageAnalysisDto{
constructor(
//public id?: number,
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public entitySpaceViewName?: string,
public debugFolderRelativePath?: string,
public standardVersion?: string,
public triagedVersion?: string,
public standardViewRelativeStreamPath?: string,
public triagedViewRelativeStreamPath?: string
)
{ }
}
export class DebugInfo{
constructor(
public triageDebugInfoThreeColTables?: Array<TriageDebugInfoThreeColTable>,
public triageDebugInfoFiveColTables?: Array<TriageDebugInfoFiveColTable>,
public triageDebugInfoSixColTables?: Array<TriageDebugInfoSixColTable>
){
this.triageDebugInfoThreeColTables = new Array<TriageDebugInfoThreeColTable>();
this.triageDebugInfoFiveColTables = new Array<TriageDebugInfoFiveColTable>();
this.triageDebugInfoSixColTables = new Array<TriageDebugInfoSixColTable>();
}
}
export class TriageDebugInfoTable{
constructor(
public title?: string,
public url?: string,
public theads?: Array<string>
){}
}
export class TriageDebugInfoThreeColTable extends TriageDebugInfoTable{
constructor(
public debugInfoThreeCols: Array<DebugInfoThreeCol>
){
super();
}
}
export class DebugInfoThreeCol{
constructor(
public validatorName: string,
public passPercentage: string,
public minPercentage: string,
public expandDetail?: boolean,
public churnCount?: ChurnCount,
public triageChurn?: TriageChurn
){
this.triageChurn = new TriageChurn();
}
}
export class TriageDebugInfoFiveColTable extends TriageDebugInfoTable
{
constructor(
public debugInfoFiveCols: Array<DebugInfoFiveCol>
){
super();
}
}
export class DebugInfoFiveCol
{
constructor(
public predicate: string,
public previousValues: string,
public currentValues: string,
public change: string,
public threshold: string,
public expandDetail?: boolean,
public churnCount?: ChurnCount,
public triageChurn?: TriageChurn
){
this.triageChurn = new TriageChurn();
}
}
export class TriageDebugInfoSixColTable extends TriageDebugInfoTable
{
constructor(
public debugInfoSixCols: Array<DebugInfoSixCol>,
public triageMode: TriageMode
){
super();
}
}
export class DebugInfoSixCol
{
constructor(
public predicate: string,
public previousValues: string,
public churn: string,
public change: string,
public minThreshold: string,
public maxThreshold: string,
public expandDetail?: boolean,
public churnCount?: ChurnCount,
public triageChurn?: TriageChurn
){
this.triageChurn = new TriageChurn();
}
}
export class Revision
{
constructor(
public mappingFile: string,
//public modelId: string,
public model: string,
public version: string,
public modelState: string,
public created: string,
public user: string,
public group: string,
public isDownloading?: boolean,
public modelUrl?: string
){}
}
export class PropertyInfo{
constructor(
public predicate?: string,
public expandDetail?: boolean,
public churnCount?: ChurnCount,
public triageChurn?: TriageChurn,
public sideBySidePairs?: Array<AddedAndDeletedPair>
)
{}
}
export class SourceAndRootUrl
{
constructor(
public sourceUrl: string,
public rootSubject: string,
public rootUrl: string,
){}
}
export class TriageSample
{
constructor(
public mode: TriageMode,
public subject: string,
public property: string,
public churnCounter: string,
public propertyLevel: string,
public entityLevel: string,
public standardValues: Array<PropertyValue>,
public triagedValues: Array<PropertyValue>,
public sourceUrls: Array<string>,
public sourceAndRootUrls: Array<SourceAndRootUrl>
){
}
}
export class AddedAndDeletedPair
{
constructor(
public added: TriageSample,
public deleted: TriageSample,
public property: string) {
}
}
<file_sep>/src/app/core/triage/tirageAnlaysisResult.ts
export class PropertyValue {
constructor(
public value?: string,
public contexts?: Array<string>
) {
//this.contexts = new Array<string>();
}
}
export class EntityComparison {
constructor(
public subject?: string,
public propertyValueComparisons?: Array<PropertyValueComparison>
) {
//this.subjectValueComparisons = new Array<EntityValueComparison>();
}
}
export class PropertyValueComparison {
constructor(
public property?: string,
public isFirst?: boolean,
public standardValues?: Array<PropertyValue>,
public triagedValues?: Array<PropertyValue>,
//public sourceUrls?: Array<string>,
public sourceAndRootUrls?:Array<SourceAndRootUrl>
) {
// this.standardValues = new Array<PropertyValue>();
// this.triagedValues = new Array<PropertyValue>();
}
}
export class PropertyComparison {
constructor(
public property?: string,
public subjectValueComparisons?: Array<SubjectValueComparison>
) {
//this.subjectValueComparisons = new Array<EntityValueComparison>();
}
}
export class SubjectValueComparison {
constructor(
public subject?: string,
public isFirst?: boolean,
public standardValues?: Array<PropertyValue>,
public triagedValues?: Array<PropertyValue>,
//public sourceUrls?: Array<string>,
public sourceAndRootUrls?:Array<SourceAndRootUrl>
) {
// this.standardValues = new Array<PropertyValue>();
// this.triagedValues = new Array<PropertyValue>();
}
}
export class ValueComparison {
constructor(
public subject?: string,
public property?: boolean,
public standardValues?: Array<PropertyValue>,
public triagedValues?: Array<PropertyValue>,
//public sourceUrls?: Array<string>,
public sourceAndRootUrls?:Array<SourceAndRootUrl>
) {
// this.standardValues = new Array<PropertyValue>();
// this.triagedValues = new Array<PropertyValue>();
}
}
export class TriageLayer {
constructor(
public entity?: Array<EntityComparison>,
public property?: Array<PropertyComparison>,
public value?: Array<ValueComparison>,
) {
this.entity = new Array<EntityComparison>();
this.property = new Array<PropertyComparison>();
this.value = new Array<ValueComparison>();
}
}
export class TriageChurn {
constructor(
public deleted?: TriageLayer,
public churned?: TriageLayer,
public added?: TriageLayer,
) {
this.deleted = new TriageLayer();
this.churned = new TriageLayer();
this.added = new TriageLayer();
}
}
export class TriageAnalysisResult {
constructor(
public triageAnalysisId?: number,
public valueChurn?: TriageChurn,
public pipelineTopEntitiesChurn?: TriageChurn,
public pipelineTypeChurn?: TriageChurn,
public pipelineChurn?: TriageChurn,
public pipelineUpdatedEntitesChurn?: TriageChurn,
public updatedEntitesChurn?: TriageChurn,
) {
// this.valueChurn = new TriageChurn();
// this.pipelineTopEntitiesChurn = new TriageChurn();
// this.pipelineTypeChurn = new TriageChurn();
// this.pipelineChurn = new TriageChurn();
// this.pipelineUpdatedEntitesChurn = new TriageChurn();
}
}
export class LayerCount {
constructor(
public entityCount?: number,
public propertyCount?: number,
public valueCount?: number,
public totalCount?: number
) { }
}
export class ChurnCount {
constructor(
public deletedLayerCount?: LayerCount,
public addedLayerCount?: LayerCount,
public churnedLayerCount?: LayerCount,
public totalCount?: number
) {
this.deletedLayerCount = new LayerCount();
this.addedLayerCount = new LayerCount();
this.churnedLayerCount = new LayerCount();
}
}
export class DebugStreamExistense {
constructor(
public valueChurnCount?: boolean,
public pipelineTopEntitiesChurnCount?: boolean,
public pipelineTypeChurnCount?: boolean,
public updatedEntitiesChurnCount?: boolean,
public pipelineUpdatedEntitiesChurnCount?: boolean,
public pipelineChurnCount?: boolean
) { }
}
export class TriageAnalysisResultCount {
constructor(
public debugStreamExistense?: DebugStreamExistense,
public valueChurnCount?: ChurnCount,
public pipelineTopEntitiesChurnCount?: ChurnCount,
public pipelineTypeChurnCount?: ChurnCount,
public updatedEntitiesChurnCount?: ChurnCount,
public pipelineUpdatedEntitiesChurnCount?: ChurnCount,
public pipelineChurnCount?: ChurnCount
) {
this.debugStreamExistense = new DebugStreamExistense();
this.valueChurnCount = new ChurnCount();
this.pipelineTopEntitiesChurnCount = new ChurnCount();
this.pipelineTypeChurnCount = new ChurnCount();
this.updatedEntitiesChurnCount = new ChurnCount();
this.pipelineUpdatedEntitiesChurnCount = new ChurnCount();
this.pipelineChurnCount = new ChurnCount();
}
}
export class PropertyTriageChurn {
constructor(
public triageChurn?: TriageChurn,
public churnCount?: ChurnCount
) {
this.triageChurn = new TriageChurn();
this.churnCount = new ChurnCount();
}
}
export class TriageAnalysisResultType {
constructor(
public deletedEntity?: boolean,
public deletedProperty?: boolean,
public deletedValue?: boolean,
public addedEntity?: boolean,
public addedProperty?: boolean,
public addedValue?: boolean,
public churn?: boolean,
) { }
}
export class SourceAndRootUrl {
constructor(
public sourceUrl: string,
public rootSubject: string,
public rootUrl: string
){}
}<file_sep>/src/app/test/webStorage.ts
// test(){
// let localSt: LocalStorageService=new LocalStorageService();
// let sessionSt: SessionStorageService=new SessionStorageService();
// let webStorage=new WebStorage(localSt, sessionSt, WebStorageType.LocalStorage);
// webStorage.saveValue("test1","this is a test string4!",0.3);//1523433093092
// webStorage.saveValue("test2","this is a test string5!",0.3);//1523433093092
// this.logger.info("Test1",webStorage.retrieveValue("test1"));
// //webStorage.clearAll();
// }<file_sep>/src/app/core/experimentDto.ts
import {AnalysisType} from './enums'
export class ExperimentDto{
constructor(
public id: number,
public name: string,
public type: AnalysisType,
public createdBy: string,
public createdTime: string,
public updatedBy: string,
public updatedTime: string,
public entitySpaceName?: string,
public entitySpaceUrl?: string,
public entityViewName?: string,
public entityViewUrl?: string,
public customerId?: string,
public customerEnv?: string,
) { }
}<file_sep>/src/app/components/triage/triageReport/triageReport.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '../../../../../node_modules/@angular/common';
import { TriageReportComponent } from './triageReport.component';
import { FormsModule } from '../../../../../node_modules/@angular/forms';
import { NgxMyDatePickerModule } from '../../../../../node_modules/ngx-mydatepicker';
import { NgxChartsModule } from '../../../../../node_modules/@swimlane/ngx-charts';
import { ReportViewsDetailModal } from '../../../templates/reportViewsDetailModal/reportViewsDetailModal.module';
// routes
export const ROUTES: Routes = [
{ path: '', component: TriageReportComponent }
];
@NgModule({
imports: [
CommonModule,
FormsModule,
NgxChartsModule,
NgxMyDatePickerModule.forRoot(),
ReportViewsDetailModal,
RouterModule.forChild(ROUTES)
],
declarations: [
TriageReportComponent
]
})
export class TriageReportModule { }<file_sep>/src/app/templates/viewStatisticPanel/viewStatisticPanel.component.ts
import { Component, OnInit, Input } from '@angular/core'
import { BaseComponent } from '../../components/common/base.component';
import { TriageViewSupervisor } from '../../core/triage/triageViewSupervisor';
import { TriageService } from '../../components/triage/triage.service';
import { MultiChartData } from '../../core/plugin/ngxChart';
@Component({
selector: "triage-view-statistic",
templateUrl: "./viewStatisticPanel.component.html",
styles: []
})
export class ViewStatisticPanelComponent extends BaseComponent implements OnInit {
@Input() triageViewSupervisor: TriageViewSupervisor;
displayType: string;
constructor(private triageService: TriageService) {
super();
}
ngOnInit() {
this.displayType = "displayBoth";
}
generateVersionDelayStackedVerticalBarChartResultFakeTriageOnly(ChartResults: Array<MultiChartData>) {
ChartResults.forEach(version=>{
if(version.series.length!=0&&!(version.series[3].value!=0&&version.series[2].value!=0)){
version.series.forEach(t=>{
t.value=0;
});
}
});
console.log("fake only",ChartResults)
return ChartResults
}
generateVersionDelayStackedVerticalBarChartResultTrueTriageOnly(ChartResults: Array<MultiChartData>) {
ChartResults.forEach(version=>{
if(version.series.length!=0&&!(version.series[3].value==0&&version.series[2].value!=0)){
version.series.forEach(t=>{
t.value=0;
});
}
});
console.log("purified",ChartResults)
return ChartResults
}
displayTriageType(displayType:string, triageViewSupervisor: TriageViewSupervisor){
console.log("display type",displayType);
if(displayType=="displayFake"){
let fakeOnlyVersions = JSON.parse(JSON.stringify(triageViewSupervisor.completeVersions));
triageViewSupervisor.versionDelayStackedVerticalBarChart.results = [
...this.generateVersionDelayStackedVerticalBarChartResultFakeTriageOnly(fakeOnlyVersions)];
}
else if(displayType=="displayTrue"){
let trueOnlyVersions = JSON.parse(JSON.stringify(triageViewSupervisor.completeVersions));
triageViewSupervisor.versionDelayStackedVerticalBarChart.results = [
...this.generateVersionDelayStackedVerticalBarChartResultTrueTriageOnly(trueOnlyVersions)];
}
else if(displayType=="displayBoth"){
triageViewSupervisor.versionDelayStackedVerticalBarChart.results = [...triageViewSupervisor.completeVersions];
}
}
}<file_sep>/src/app/components/loginAuth/logout/logout.component.ts
import { Component, OnInit } from "@angular/core";
import { BaseComponent } from "../../common/base.component";
@Component({
selector: "logout",
templateUrl: "./logout.component.html"
})
export class LogoutComponent extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {}
}
<file_sep>/src/app/templates/tablePagination/tablePagination.component.ts
import { Component, OnInit, Input, SimpleChanges, Output, EventEmitter } from "@angular/core";
import { TriageViewSupervisor } from "../../core/triage/triageViewSupervisor";
@Component({
selector: "table-pagination",
templateUrl: "./tablePagination.component.html"
})
export class TablePaginationComponent implements OnInit {
private _numOfPages = 0;
public pages: Array<number>;
@Input()
numPerPage: number = 15;
@Input()
currentPage: number = 1;
@Output()
currentPageChange = new EventEmitter<number>();
//https://stackoverflow.com/questions/38571812/how-to-detect-when-an-input-value-changes-in-angular
//https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components
@Input()
set numOfPages(numOfPages: number) {
this._numOfPages = numOfPages;
this.pages = [];
for (var i = 1; i <= numOfPages; i++) {
this.pages.push(i);
}
}
get numOfPages() {
return this._numOfPages;
}
constructor() {}
ngOnInit() {}
isFirst() {
return this.currentPage === 1;
}
isLast() {
return this.currentPage === this.numOfPages;
}
isActive(page: number) {
return this.currentPage === page;
}
selectPage(page: number) {
if (page != 0) {
if (!this.isActive(page)) {
this.currentPage = page;
this.currentPageChange.emit(this.currentPage);
}
}
}
goPrevious() {
if (!this.isFirst()) {
this.selectPage(this.currentPage - 1);
}
}
goNext() {
if (!this.isLast()) {
this.selectPage(this.currentPage + 1);
}
}
}
<file_sep>/src/app/core/metric/metric.ts
import { WorkItemState } from "../enums";
export class TfsWorkItemBasic {
constructor(
public id: number,
public title: string,
public type: string,
public state: WorkItemState,
public areaPath: string,
public project: string,
public iterationPath: string,
public assignedTo: string,
public createdDate: string,
public createdBy: string,
public changedDate: string,
public changedBy: string,
public resolvedDate: string,
public resolvedBy: string,
public closedDate: string,
public closedBy: string,
public e2ETailHours: string
) {}
}
export class OnboardingTfsFeature extends TfsWorkItemBasic {
constructor(
public id: number,
public title: string,
public type: string,
public state: WorkItemState,
public areaPath: string,
public project: string,
public iterationPath: string,
public assignedTo: string,
public createdDate: string,
public createdBy: string,
public changedDate: string,
public changedBy: string,
public resolvedDate: string,
public resolvedBy: string,
public closedDate: string,
public closedBy: string,
public e2ETailHours: string,
public userStories: Array<UserStory>,
public expandUserStory: boolean
) {
super(
id,
title,
type,
state,
areaPath,
project,
iterationPath,
assignedTo,
createdDate,
createdBy,
changedDate,
changedBy,
resolvedDate,
resolvedBy,
closedDate,
closedBy,
e2ETailHours
);
}
}
export class UserStory extends TfsWorkItemBasic {
constructor(
public id: number,
public title: string,
public type: string,
public state: WorkItemState,
public areaPath: string,
public project: string,
public iterationPath: string,
public assignedTo: string,
public createdDate: string,
public createdBy: string,
public changedDate: string,
public changedBy: string,
public resolvedDate: string,
public resolvedBy: string,
public closedDate: string,
public closedBy: string,
public e2ETailHours: string,
public parentid: number,
public ticketingHours: string,//create->queue
public queuedHours: string,//queue->in progress
public e2EEngineeringHours: string,//in progress->in progress after head publish
public e2EHeadHours: string,//create->in progress after head publish
public engineeringHours: string,//create->in progress
public userTasks: Array<UserTask>,
public expandUserTask: boolean
) {
super(
id,
title,
type,
state,
areaPath,
project,
iterationPath,
assignedTo,
createdDate,
createdBy,
changedDate,
changedBy,
resolvedDate,
resolvedBy,
closedDate,
closedBy,
e2ETailHours
);
}
}
export class UserTask extends TfsWorkItemBasic {
constructor(
public id: number,
public title: string,
public type: string,
public state: WorkItemState,
public areaPath: string,
public project: string,
public iterationPath: string,
public assignedTo: string,
public createdDate: string,
public createdBy: string,
public changedDate: string,
public changedBy: string,
public resolvedDate: string,
public resolvedBy: string,
public closedDate: string,
public closedBy: string,
public e2ETailHours: string,
public parentid: number
) {
super(
id,
title,
type,
state,
areaPath,
project,
iterationPath,
assignedTo,
createdDate,
createdBy,
changedDate,
changedBy,
resolvedDate,
resolvedBy,
closedDate,
closedBy,
e2ETailHours
);
}
}
<file_sep>/src/app/components/metric/metric.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "metric",
templateUrl: "./metric.component.html"
})
export class MetricComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
<file_sep>/src/app/components/common/excel.service.ts
import { Injectable } from "@angular/core";
import * as XLSX from "xlsx";
@Injectable()
export class ExcelService {
constructor() {}
exportAsExcel(excelName: string, exportData: any[][], isGenerating: boolean) {
isGenerating = true;
/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(exportData);
/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
/* save to file */
XLSX.writeFile(wb, `${excelName}.xlsx`);
isGenerating = false;
}
}
<file_sep>/src/app/helper/satoriDatetime.ts
export class SatoriDateTime {
public year: number;
public month: number;
public day: number;
public hour: number;
public minute: number;
public second: number;
constructor(
private str: string
) {
this.parse(str);
}
// Convert satori datetime to readable datetime
// e.g. "#507268224000004" = > 2010-5-4
parse(str: string) {
str = str.substring(1, str.indexOf("\"^^mso:datetime"));
var ticks = parseInt(str.substring(1));
if (ticks) {
var month = 1;
var day = 1;
var hour = 0;
var minute = 0;
var sec = 0;
var dateTimeTicks = this.getDateTimeTicks(ticks);
var out = this.decodeYear(dateTimeTicks);
var num1 = out.ticks;
var year = out.year;
if (num1 > 0) {
if (dateTimeTicks < 0) {
num1 = ((this.isLeapYear(year) ? 366 : 365) * 86400000 - num1);
}
while (num1 > 0) {
var num2 = this.daysPerMonth(year, month) * 86400000;
if (num1 >= num2) {
num1 -= num2;
++month;
}
else
break;
}
day = Math.floor(num1 / 86400000) + 1;
var num3 = num1 % 86400000;
hour = Math.floor(num3 / 3600000);
var num4 = num3 % 3600000;
minute = Math.floor(num4 / 60000);
var num5 = num4 % 60000;
sec = Math.floor(num5 / 1000);
var num6 = num5 % 1000;
}
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = sec;
}
}
daysPerMonth(year: number, month: number): number {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
return !this.isLeapYear(year) ? 28 : 29;
case 4:
case 6:
case 9:
case 11:
default:
return 30;
}
}
isLeapYear(year: number): boolean {
var num = year >= 0 ? year : -year;
return num % 400 === 0 || num % 100 !== 0 && num % 4 === 0;
}
getDateTimeTicks(ticks: number): number {
return Math.floor(ticks / 8);
}
decodeYear(ticks: number): any {
var num1 = ticks > 0 ? ticks : -ticks;
var year = 1;
year += Math.floor(num1 / 12622780800000) * 400;
var num2 = num1 % 12622780800000;
var num3;
var num4;
if (num2 > 9467020800000) {
num3 = 3;
num4 = num2 - 9467020800000;
}
else {
num3 = Math.floor(num2 / 3155673600000);
num4 = num2 % 3155673600000;
}
year += num3 * 100;
year += Math.floor(num4 / 126230400000) * 4;
var num5 = num4 % 126230400000;
var num6;
if (num5 > 94608000000) {
year += 3;
num6 = num5 - 94608000000;
}
else {
year += Math.floor(num5 / 31536000000);
num6 = num5 % 31536000000;
}
if (ticks < 0)
year = num6 == 0 ? -year + 1 : -year;
return {
ticks: num6,
year: year
};
}
toStringYear(): string {
return this.year + "";
}
toStringMonth(): string {
return this.year + "-" + this.month;
}
toStringDay(): string {
return this.year + "-" + this.month + "-" + this.day;
}
toStringSecond(): string {
return this.year + "-" + this.month + "-" + this.day + " " + this.hour +":" + this.minute + ":" + this.second;
}
}<file_sep>/src/app/components/triage/triageAnalysis/triageAnalysis.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '../../../../../node_modules/@angular/common';
import { TriageAnalysisComponent } from './triageAnalysis.component';
import { FormsModule } from '../../../../../node_modules/@angular/forms';
import { JobPanelModule } from '../../../templates/jobPanel/jobPanel.module';
import { TriageAnalysisResultModule } from '../../../templates/triageAnalysisResult/triageAnalysisResult.module';
import { NgxAlertsModule } from '../../../../../node_modules/@ngx-plus/ngx-alerts';
// routes
export const ROUTES: Routes = [
{ path: '', component: TriageAnalysisComponent }
];
@NgModule({
imports: [
CommonModule,
FormsModule,
JobPanelModule,
TriageAnalysisResultModule,
RouterModule.forChild(ROUTES)
],
declarations: [
TriageAnalysisComponent
]
})
export class TriageAnalysisModule {}<file_sep>/src/app/app-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
//analysis
import { PageNotFoundComponent } from "./components/trivial/pageNotFound.component";
import { LoginComponent } from "./components/loginAuth/login/login.component";
import { LogoutComponent } from "./components/loginAuth/logout/logout.component";
import { AuthenticationGuard } from "./components/loginAuth/authGuard";
import { DashboardComponent } from "./components/dashboard/dashboard.component";
let allRoutes: Routes = [];
const initRoutes: Routes = [
{ path: "login", component: LoginComponent },
{ path: "logout", component: LogoutComponent }
];
const dashboardRoutes: Routes = [
{ path: "", redirectTo: "triage", pathMatch: "full" },
{
path: "triage",
loadChildren: './components/triage/triage.module#TriageModule'
},
{
path: "dashboard",
loadChildren: './components/dashboard/dashboard.module#DashboardModule'
}
];
const wildcardRoutes: Routes = [{ path: "**", component: PageNotFoundComponent }];
allRoutes = allRoutes.concat(initRoutes, dashboardRoutes, wildcardRoutes);
@NgModule({
imports: [
RouterModule.forRoot(
allRoutes
//his outputs each router event that took place during each navigation lifecycle to the browser console
//{ enableTracing: true } // <-- debugging purposes only
)
],
exports: [RouterModule]
})
export class AppRoutingModule {}
<file_sep>/src/app/components/metric/metric.service.ts
import { Injectable } from "@angular/core";
import {
HttpClient,
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpParams,
HttpHeaders,
HttpResponse
} from "@angular/common/http";
import { BaseService } from "../common/base.service";
import { ApiController, RequestAction } from "../../core/enums";
import { Constants } from "../../core/common/constants";
@Injectable()
export class MetricService extends BaseService {
private headers = new HttpHeaders({ "Content-Type": "application/json" });
private metricServiceUrl = `${this.serverUrl}/Metric`; // URL to web api
constructor(public httpClient: HttpClient) {
super(httpClient);
}
generateTfsMetric(tfsQueryId: string) {
const httpParams = new HttpParams()
.set("tfsQueryId", tfsQueryId);
return this.httpClient.post(`${this.metricServiceUrl}/onboardingTfsMetric`, {}, {headers: this.headers, params: httpParams});
}
}
<file_sep>/src/app/core/enums.ts
import { TriageAnalysis } from "./triage/triageAnalysis";
export enum AnalysisType {
EntitySpace = 1,
EntityView,
EntityGraph
};
export enum ApiController {
EntityPlatform = 1,
TriageAnalysis,
EntitySpace,
EntityView,
EntityGraph
}
export enum RequestAction {
AllCustomerIds = 1
}
export enum EntitySpaceViewVersionState {
Inactive,
BuildPending,
Building,
Standard,
UpdatePending,
Updating,
Triaged,
Cancelled,
Errored,
GenerateEncumbrancePending,
GeneratingEncumbrance
}
export enum EntitySpaceViewState {
Unknow,
EveryVersion,
MajorVersion,
Manual
}
export enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error
}
export enum ReportType {
Customize = 1,
Weekly,//every week
Monthly,//every month
Quarterly,//every season
SemiAnnual,//every half a year
Annual//every year
}
export enum TriageMode{
Deleted = 1,
Added,
Churned
}
export enum WebStorageType{
LocalStorage,//record in local, when browser close up, it still there
SessionStorage//when browser close up, the storage will be cleared
}
export enum ViewerType{
Viewer,
ViewerDiff,
ViewerDiffOfTwo
}
export enum WorkItemState {
Unknow,
New,
Investigating,
Queued,
Active,
InProgress,
InProgressAfterHeadPublished,
NeedsTriage,
Removed,
RemovedHeadOnly,
Resolved,
Closed
}
export enum TriageAnalysisResultDiaplayType{
DebugInfo,
Extra,
SBS
}
export enum MissSlaType {
Unknow = 0,
NoSchedule,
LateSchedule,
LongQueue,
LongRunning,
Triage,
Error
}<file_sep>/src/app/components/entityAnalysis/service/analysisDashboard.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, HttpModule } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
//self
import { ExperimentDto } from "../../../core/experimentDto"
import { EntitySpaceAnalysis } from "../../../core/entityAnalysis/entitySpaceAnalysis"
@Injectable()
export class AnalysisDashboardService {
private headers = new Headers({'Content-Type': 'application/json'});
private entitySpaceAnalysisUrl = 'http://localhost:9001/api/entityspaceanalysis'; // URL to web api
//private entitySpaceAnalysisDtos: EntitySpaceAnalysis[];//Array<EntitySpaceAnalysis>;
private entityAnalysisDtos: any;//Array<EntitySpaceAnalysis>;
constructor(private http: Http) { }
getEntitySpaceAnalysisDtos(): Observable<any> {
return this.http.get(this.entitySpaceAnalysisUrl)
.map((response) => response.json());
}
// getEntitySpaceAnalysis(id: number) {
// const url = `${this.entitySpaceAnalysisUrl}/${id}`;
// this.http.get<Array<EntitySpaceAnalysis>>(url)
// .subscribe(response => {
// this.entit
// }
// );
// }
delete(id: number): Promise<void> {
const url = `${this.entitySpaceAnalysisUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
create(name: string): Promise<ExperimentDto> {
return this.http.post(this.entitySpaceAnalysisUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as ExperimentDto)
.catch(this.handleError);
}
update(hero: ExperimentDto): Promise<ExperimentDto> {
const url = `${this.entitySpaceAnalysisUrl}/${hero.id}`;
return this.http.put(url, JSON.stringify(hero), {headers: this.headers})
.toPromise()
.then(() => hero)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
// getEntitySpaceAnalysisDtos(): Promise<EntitySpaceAnalysis[]> {
// return this.http.get(this.entitySpaceAnalysisUrl)
// .toPromise()
// .then(response => response.json().data as EntitySpaceAnalysis[])
// .catch(this.handleError);
// }
// getEntitySpaceAnalysis(id: number): Promise<EntitySpaceAnalysis[]> {
// const url = `${this.entitySpaceAnalysisUrl}/${id}`;
// return this.http.get(url)
// .toPromise()
// .then(response => response.json().data as EntitySpaceAnalysis[])
// .catch(this.handleError);
// }
// delete(id: number): Promise<void> {
// const url = `${this.entitySpaceAnalysisUrl}/${id}`;
// return this.http.delete(url, {headers: this.headers})
// .toPromise()
// .then(() => null)
// .catch(this.handleError);
// }
// create(name: string): Promise<ExperimentDto> {
// return this.http.post(this.entitySpaceAnalysisUrl, JSON.stringify({name: name}), {headers: this.headers})
// .toPromise()
// .then(res => res.json().data as ExperimentDto)
// .catch(this.handleError);
// }
// update(hero: ExperimentDto): Promise<ExperimentDto> {
// const url = `${this.entitySpaceAnalysisUrl}/${hero.id}`;
// return this.http.put(url, JSON.stringify(hero), {headers: this.headers})
// .toPromise()
// .then(() => hero)
// .catch(this.handleError);
// }
// private handleError(error: any): Promise<any> {
// console.error('An error occurred', error); // for demo purposes only
// return Promise.reject(error.message || error);
// }
}<file_sep>/src/app/components/viewer/entityDiffViewer/entityDiffViewer.component.ts
import { Component, OnInit, ViewChild } from "@angular/core";
import { BaseComponent } from "../../common/base.component";
import { DiffViewerTableComponent } from "../../../templates/diffViewerTable/diffViewerTable.component";
import { ViewerType } from "../../../core/enums";
import { ActivatedRoute, Router } from "@angular/router";
@Component({
selector: "entity-diff-viewer",
templateUrl: "./entityDiffViewer.component.html",
styleUrls: ["./entityDiffViewer.component.css"],
})
export class EntityDiffViewerComponent extends BaseComponent implements OnInit {
public subjectKey1: string;
public subjectKey2: string;
public standardStream: string;
public triagedStream: string;
public viewerType: ViewerType;
public isFetchingEntityDiffViewer: boolean;
public displayCommon: boolean;
constructor(
private route: ActivatedRoute,
private router: Router,
) {
super();
}
@ViewChild(DiffViewerTableComponent) diffViewerTableComponentChild: DiffViewerTableComponent;//this child is the DiffViewerTable component
ngOnInit() {
this.viewerType = ViewerType.ViewerDiff;
this.standardStream = this.route.snapshot.queryParamMap.get("standardStreamPath");
this.triagedStream = this.route.snapshot.queryParamMap.get("triageStreamPath");
this.subjectKey1 = this.route.snapshot.queryParamMap.get("subject1");
this.subjectKey2 = this.route.snapshot.queryParamMap.get("subject2");
let viewerType = this.route.snapshot.queryParamMap.get("viewerType");
switch (viewerType) {
case "0": {
this.viewerType = ViewerType.Viewer;
if (this.standardStream && this.subjectKey1) {
this.getViewerDiffProperties();
}
break;
};
case "1": {
this.viewerType = ViewerType.ViewerDiff;
if (this.standardStream && this.triagedStream && this.subjectKey1) {
this.getViewerDiffProperties();
}
break;
};
case "2": {
this.viewerType = ViewerType.ViewerDiffOfTwo;
if (this.standardStream && this.triagedStream && this.subjectKey1 && this.subjectKey2) {
this.getViewerDiffProperties();
}
break;
};
};
}
getViewerDiffProperties() {
//change url params
this.router.navigate(["/viewer/entityDiff"], {
queryParams: {
"viewerType": this.viewerType,
"subject1": this.subjectKey1,
"subject2": this.subjectKey2,
"standardStreamPath": this.standardStream,
"triageStreamPath": this.triagedStream
}
});
if (this.viewerType != ViewerType.ViewerDiffOfTwo) {
this.subjectKey2 = "";
}
if (this.viewerType == ViewerType.Viewer) {
this.triagedStream = "";
}
this.diffViewerTableComponentChild.getViewerDiffProperties(this.viewerType, this.subjectKey1, this.subjectKey2, this.standardStream, this.triagedStream);
}
}<file_sep>/src/app/core/viewer/PayloadDiffViewer.ts
export class ViewerPayloadDiff {
constructor(
public subject?: string,
public payloadDiffProperties?: Array<ViewerPayloadDiffProperty>
) {
this.payloadDiffProperties = new Array<ViewerPayloadDiffProperty>();
}
}
export class ViewerPayloadDiffProperty {
constructor(
public property?: string,
public commonValues?: Array<string>,
public standardValues?: Array<string>,
public triagedValues?: Array<string>,
) {
this.commonValues = new Array<string>();
this.standardValues = new Array<string>();
this.triagedValues = new Array<string>();
}
}
<file_sep>/deprecated/workItemTable.directive.ts
import { Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: 'work-item-table',
})
export class NameDirective {}<file_sep>/src/app/templates/triageAnalysisResult/triageAnalysisResult.component.ts
import { Component, OnInit, Input, Output, EventEmitter, SimpleChanges, ViewChild } from "@angular/core";
import { Observable, BehaviorSubject } from "rxjs/Rx";
import { JobType, JobState, JobPanelState } from "../../core/job/job";
import { AetherJob } from "../../core/job/AetherJob";
import { BaseComponent } from "../../components/common/base.component";
import { ChurnCount, TriageChurn, TriageAnalysisResultType } from "../../core/triage/tirageAnlaysisResult";
import { EntityViewVersion } from "../../core/common/entityView";
import { DiffViewerTableComponent } from "../diffViewerTable/diffViewerTable.component";
import { ViewerType } from "../../core/enums";
//import * as Collections from 'typescript-collections';
@Component({
selector: "triage-analysis-result",
templateUrl: "./triageAnalysisResult.component.html",
styles: [require("./triageAnalysisResult.component.scss").toString()]
})
export class TriageAnalysisResultComponent extends BaseComponent implements OnInit {
@Input() churnCount: ChurnCount;
@Input() triageChurn: TriageChurn;
@Input() currentSide1: EntityViewVersion;
@Input() currentSide2: EntityViewVersion;
@Input() property?: string;
@ViewChild(DiffViewerTableComponent) diffViewerTableComponentChild:DiffViewerTableComponent;//this child is the DiffViewerTable component
displayType: ViewerType;
isFetchingEntityDiffViewer: boolean;
triageAnalysisResultType: TriageAnalysisResultType;
constructor() {
super();
}
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
// only run when property "churnCount" changed
if (changes['churnCount']) {
this.setFirstAvailableAnalysisResult();
}
}
setFirstAvailableAnalysisResult() {
this.triageAnalysisResultType = new TriageAnalysisResultType();
if (!this.churnCount || this.churnCount.totalCount == 0) {
return;
}
if (this.churnCount.deletedLayerCount.entityCount != 0) {
this.triageAnalysisResultType.deletedEntity = true;
return;
}
if (this.churnCount.deletedLayerCount.propertyCount != 0) {
this.triageAnalysisResultType.deletedProperty = true;
return;
}
if (this.churnCount.deletedLayerCount.valueCount != 0) {
this.triageAnalysisResultType.deletedValue = true;
return;
}
if (this.churnCount.addedLayerCount.entityCount != 0) {
this.triageAnalysisResultType.addedEntity = true;
return;
}
if (this.churnCount.addedLayerCount.propertyCount != 0) {
this.triageAnalysisResultType.addedProperty = true;
return;
}
if (this.churnCount.addedLayerCount.valueCount != 0) {
this.triageAnalysisResultType.addedValue = true;
return;
}
if (this.churnCount.churnedLayerCount.valueCount != 0) {
this.triageAnalysisResultType.churn = true;
return;
}
}
isRawUrl(url: string): boolean {
//for some cases, its url is null
if (url) {
let upperCasedUrl = url.toUpperCase();
return upperCasedUrl.startsWith("HTTP");
}
return false;
}
generateEntityViewerSBS(subject: string, viewerType: ViewerType) {
this.diffViewerTableComponentChild.getViewerDiffProperties(viewerType, subject, '', this.currentSide1.relativeStreamPath, this.currentSide2.relativeStreamPath);
this.displayType = viewerType;
}
}
<file_sep>/src/app/components/report/report-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AuthenticationGuard } from "../loginAuth/authGuard";
//analysis
import { ReportComponent } from "./report.component";
import { ContributionComponent } from "./contribution/contribution.component";
const reportRoutes: Routes = [
//{ path: '', redirectTo: '/entityAnalysis', pathMatch: 'full' },
{
path: "report",
component: ReportComponent,
children: [
{
path: "",
component: ContributionComponent,
canActivate: [AuthenticationGuard]
},
{
path: "contribution",
component: ContributionComponent,
canActivate: [AuthenticationGuard]
}
// {
// path: 'entityspace',
// component: AnalysisDashboardComponent
// },
// {
// path: 'entityview',
// component: AnalysisDashboardComponent
// },
// {
// path: 'entitygraph',
// component: AnalysisDashboardComponent
//},
]
}
];
@NgModule({
imports: [
RouterModule.forChild(
reportRoutes
//his outputs each router event that took place during each navigation lifecycle to the browser console
//{ enableTracing: true } // <-- debugging purposes only
)
],
exports: [RouterModule]
})
export class ReportRoutingModule {}
<file_sep>/src/app/core/triage/triageStatistic.ts
import { EntitySpaceViewVersionState, EntitySpaceViewState, MissSlaType } from "../enums";
export class TriageStatistic {
constructor(
public supervisorId?: number,
public entitySpaceViewName?: string,
public stateStatistics?: Array<ViewStateDailyStatistic>,
public triageAndErrorDistribution?: TriageAndErrorDistribution,
public versionDuration?: ViewVersionDuration,
public triageCommitDuration?: TriageCommitDuration
)
{
this.stateStatistics = new Array<ViewStateDailyStatistic>();
this.triageAndErrorDistribution = new TriageAndErrorDistribution();
this.versionDuration = new ViewVersionDuration();
this.triageCommitDuration = new TriageCommitDuration();
}
}
export class ViewStateDailyStatistic {
constructor(
public date?: string,
public viewStateTimeStamps?: Array<ViewStateTimeStamp>
)
{
this.viewStateTimeStamps = new Array<ViewStateTimeStamp>();
}
}
export class EntitySpaceViewStateDistribution{
constructor(
public state?: EntitySpaceViewVersionState,
public count?: number
)
{}
}
export class AllViewStateDistribution{
constructor(
public currentViewStateDistribution?: Array<ViewStateDistribution>,
public originalViewStateDistribution?: Array<ViewStateDistribution>
)
{}
}
export class ViewStateDistribution{
constructor(
public state?: EntitySpaceViewState,
public count?: number
)
{}
}
export class DailyErrorTriageViewName{
constructor(
public date?: string,
public errorViewNames?: Set<string>,
public triageViewNames?: Set<string>
){
this.errorViewNames=new Set<string>();
this.triageViewNames=new Set<string>();
}
}
export class TriageAndErrorDistribution {
constructor(
public viewName?: string,
public triageAndErrors?: Array<DaliyTriageAndError>,
public totalErrorCount?: number,
public totalTriageCount?: number
) {}
}
export class DaliyTriageAndError {
constructor(
public date?: string,
public errorStateTimeStamps?: Array<ViewStateTimeStamp>,
public triageStateTimeStamps?: Array<ViewStateTimeStamp>,
public errorCount?: number,
public triageCount?: number
) {}
}
export class ViewStateTimeStamp {
constructor(
public viewVersion?: string,
public viewState?: string,
public timeStamp?: string
) {}
}
export class DailyCount {
constructor(
public viewName?: string,
public date?: string,
public errorCount?: number,
public triageCount?: number
) {}
}
export class ViewVersionDuration {
constructor(
public viewName?: string,
public versionDurations?: Array<VersionDuration>,
public averageDuration?: string,
public latestDuration?: string,
public latestVersion?: string
) {}
}
export class VersionStateDuration {
constructor(
public viewStateTimeStamp?: ViewStateTimeStamp,
public duration?: string
) {}
}
export class VersionDuration{
constructor(
public jobDuration?:VersionStateDuration,
public commitDuration?:VersionStateDuration,
public availableDuration?:VersionStateDuration,
public totalDuration?:string
){}
}
export class TriageCommitDuration {
constructor(
public viewName?: string,
public commitStatistics?: Array<CommitStatistic>,
public latestTriageDuration?: string,
public latestTriagedVersion?: string,
public averageDuration?: string
) {}
}
export class CommitStatistic {
constructor(
public triageTimeStamp?: ViewStateTimeStamp,
public standardTimeStamp?: ViewStateTimeStamp,
public duration?: string
) {}
}
export class ClassifiedViewVersionDuration{
constructor(
public CompleteViewVersionDuration?: ViewVersionDuration,
public FakeTriageViewVersionDuration?: ViewVersionDuration,
public TrueTriageViewVersionDuration?: ViewVersionDuration
) {}
}
export class ViewVersionLatency {
constructor(
public supervisorId?: number,
public viewName?: string,
public version?: string,
public state?: string,
public originalState?: string,
public updateType?: string,
public lastBuildTimestamp?: string,
public lastUpdateTimestamp?: string,
public createdTimestamp?: string,
public erroredTimestamp?: string,
public triagedTimestamp?: string,
public sealedTimestamp?: string,
public lastBuildJobId?: string,
public lastUpdateJobId?: string,
public jobUrl?: string,
public jobId?: string,
public jobSubmitTimeStamp?: string,
public jobStartTimeStamp?: string,
public retryTime?: string,
public queuedTime?: string,
public runningTime?: string,
public commitedTime?: string,
public totalTime?: string,
public previousVersionLatency?: string,
public previousStandardVersionLatency?: string,
public isMissSla?: boolean,
public missSlaType?: MissSlaType,
public missSlaGap?: string,
public isFalseAlert?: boolean,
public isTriaged?: boolean,
public isErrored?: boolean,
public isCommited?: boolean,
public isSucceed?: boolean,
public date?: string,
public sealedDate?: string,
public completeDate?: string,
public completedTime?: string,
public entitySpaceViewState?: number
) { }
}
export class VersionLatencyStateDetail {
constructor(
public queue?: VersionLatencyStateDetailUnit,
public building?: VersionLatencyStateDetailUnit,
public updating?: VersionLatencyStateDetailUnit,
public commited?: VersionLatencyStateDetailUnit,
public errored?: VersionLatencyStateDetailUnit,
public standard?: VersionLatencyStateDetailUnit,
public timeout?: VersionLatencyStateDetailUnit,
public retry?: VersionLatencyStateDetailUnit
) {
this.queue = new VersionLatencyStateDetailUnit();
this.building = new VersionLatencyStateDetailUnit();
this.updating = new VersionLatencyStateDetailUnit();
this.commited = new VersionLatencyStateDetailUnit();
this.errored = new VersionLatencyStateDetailUnit();
this.standard = new VersionLatencyStateDetailUnit();
this.timeout = new VersionLatencyStateDetailUnit();
this.retry = new VersionLatencyStateDetailUnit();
}
}
export class ViewVersionLatencyDetail {
constructor(
public timeStamp?: string,
public version?: string,
public updateType?: string,
public versionStateDetail?: VersionLatencyStateDetail
) {
this.versionStateDetail = new VersionLatencyStateDetail();
}
}
export class VersionLatencyStateDetailUnit {
constructor(
public state?: string,
public endTime?: string,
public cost?: string,
) { }
}<file_sep>/src/app/components/triage/triageReport/triageReport.component.ts
import { Component, OnInit } from "@angular/core";
import { BaseComponent } from "../../common/base.component";
import { TriageService } from "../triage.service";
import { Constants } from "../../../core/common/constants";
import { ReportType } from "../../../core/enums";
import { ActivatedRoute } from "@angular/router";
import { Location } from "@angular/common";
import {
TriageReport,
TriageReportDetail,
MissSlaSummary,
TriageSummary,
ErrorSummary,
VersionLatencyRank,
AttributeRank,
ViewNameRank,
MissSlaFacet,
RootCauseFacet,
TriageFacet,
LatencyRankFacet,
ErrorFacet,
TriageReportSummary,
ViewVersionMetric,
DailyViewVersionMetric,
MetricFacet,
LongLatencySummary
} from "../../../core/triage/triageReport";
import { TriageViewSupervisor } from "../../../core/triage/triageViewSupervisor";
import { MultiChartData, SingleChartData, LineChart } from "../../../core/plugin/ngxChart";
import * as moment from 'moment';
import { constants } from "os";
@Component({
selector: "triage-report",
templateUrl: "./triageReport.component.html",
styleUrls: ["./triageReport.component.css"]
})
export class TriageReportComponent extends BaseComponent implements OnInit {
existingRegularReport: boolean;
existingCustomizedReport: boolean;
forceGenerate: boolean;
//top nav bar
displayType: string;
reportType: string;
reportTypes: Array<string>;
customizeStartDate: any;
customizeEndDate: any;
currentStartDate: any;
currentEndDate: any;
currentReportTimeSpan: string;
currentCustomizedReportTimeSpan: string;
currentRegularReportTimeSpan: string;
reportTimeSpans: Array<string>;
isFetchingReport: boolean;
isUrlParam: boolean;
currentReport: TriageReport;
//table data
everyVersionLimit: number;
majorVersionLimit: number;
manualLimit: number;
triageReportSummary: TriageReportSummary;
allTriageReportDetails: Array<TriageReportDetail>;
allTriageViewSupervisors: Array<TriageViewSupervisor>;
modalTriageViewSupervisors: Array<TriageViewSupervisor>;
allViewCount: number;
missSlaSummary: MissSlaSummary;
triageSummary: TriageSummary;
errorSummary: ErrorSummary;
longLatencySummary: LongLatencySummary;
versionLatencyRank: VersionLatencyRank;
segmentRanks: Array<AttributeRank>;
ownerRanks: Array<AttributeRank>;
viewNameRanks: Array<ViewNameRank>;
//sort
segmentRankNameDesc: boolean;
segmentRankMissSlaDesc: boolean;
segmentRankTriageDesc: boolean;
segmentRankErrorDesc: boolean;
ownerRankNameDesc: boolean;
ownerRankMissSlaDesc: boolean;
ownerRankTriageDesc: boolean;
ownerRankErrorDesc: boolean;
viewNameRankNameDesc: boolean;
viewNameRankTriageDesc: boolean;
viewNameRankErrorDesc: boolean;
viewNameRankMissSlaDesc: boolean;
enablePrevCaret: boolean;
enableNextCaret: boolean;
viewVersionMetric: ViewVersionMetric;
viewVersionMetriLineChart: LineChart;
missSlaPercent: number;
triagePercent: number;
errorPercent: number;
constructor(private triageService: TriageService, private route: ActivatedRoute, private location: Location) {
super();
}
ngOnInit() {
this.existingRegularReport = true;
this.existingCustomizedReport = false;//when init page, default locate at regular report, so customized report should be null
this.forceGenerate = false;
this.isUrlParam = false;
this.isFetchingReport = false;
this.displayType = "Regular";
this.reportType = ReportType[ReportType.Weekly];
this.reportTypes = Object.keys(ReportType).filter(t => typeof ReportType[t] === "number");
// this.sortedViews = new Array<SingleChartData>();
// this.triageViewSupervisors = new Array<TriageViewSupervisor>();
this.reportTimeSpans = new Array<string>();
this.everyVersionLimit = Constants.everyVersionLimit;
this.majorVersionLimit = Constants.majorVersionLimit;
this.manualLimit = Constants.manualLimit;
this.currentReport = undefined;//new TriageReport();
this.allTriageReportDetails = new Array<TriageReportDetail>();
this.allTriageViewSupervisors = new Array<TriageViewSupervisor>();
this.modalTriageViewSupervisors = new Array<TriageViewSupervisor>();
this.missSlaSummary = new MissSlaSummary();
this.triageSummary = new TriageSummary();
this.errorSummary = new ErrorSummary();
this.longLatencySummary = new LongLatencySummary();
this.versionLatencyRank = new VersionLatencyRank();
this.segmentRanks = new Array<AttributeRank>();
this.ownerRanks = new Array<AttributeRank>();
this.viewNameRanks = new Array<ViewNameRank>();
let reportTimeSpan = this.route.snapshot.paramMap.get("reportTimeSpan");
let displayType = this.route.snapshot.paramMap.get("displayType");
this.viewVersionMetric = new ViewVersionMetric();
this.viewVersionMetriLineChart = new LineChart();
if (reportTimeSpan) {
this.isUrlParam = true;
reportTimeSpan = reportTimeSpan.replace(/_/g, "/");
reportTimeSpan = reportTimeSpan.replace("-", " - ");
this.logger.info("reportTimeSpanFromUrl", reportTimeSpan);
this.currentReportTimeSpan = reportTimeSpan;
if (displayType == "regular") {
this.displayType = "Regular";
this.currentRegularReportTimeSpan = reportTimeSpan;
this.triageService.getTriageReport(this.currentReportTimeSpan, ReportType.Weekly, this.forceGenerate).subscribe(result => {
this.reportType = result.type;
this.getTriageReportTimeSpansByReportType(this.reportType, reportTimeSpan);
});
}
else if (displayType == "customize") {
this.displayType = "Customize";
this.currentCustomizedReportTimeSpan = reportTimeSpan;
//timespan: month/day/year - month/day/year
let startTime = reportTimeSpan.split(" - ")[0];//get startTime from timespan
let startDate = new Date(Number(startTime.split("/")[2]), Number(startTime.split("/")[0]), Number(startTime.split("/")[1]));
let endTime = reportTimeSpan.split(" - ")[1];//get endTime from timespan
let endDate = new Date(Number(endTime.split("/")[2]), Number(endTime.split("/")[0]), Number(endTime.split("/")[1]));
this.customizeStartDate = this.convertToDatePickerDate(startDate);//put startDate into DatePicker
this.customizeEndDate = this.convertToDatePickerDate(endDate);//put endDate into DatePicker
this.generateTriageReport(this.currentCustomizedReportTimeSpan, ReportType.Customize);
}
} else {
this.getTriageReportTimeSpansByReportType(this.reportType);
}
}
getTriageReportTimeSpansByReportType(reportType: string, reportTimeSpan?: string) {
this.triageService.getTriageReportTimeSpansByReportType(reportType).subscribe(result => {
if (result.length == 0) {
this.existingRegularReport = false;//if there is no regular timespan, there is no regular report
}
this.reportTimeSpans = result.sort((a, b) => {
return this.compareTimeSpan(a, b);
});
if (this.reportTimeSpans.length != 0) {
//if there is a param form url, generate report of this param
let initReportTimeSpan = reportTimeSpan == null ? this.reportTimeSpans[0] : reportTimeSpan;
this.changeReportTimeSpan(initReportTimeSpan);
}
else {
this.enablePrevCaret = false;
this.enableNextCaret = false;
}
this.reportType = reportType;
});
}
compareTimeSpan(timeSpan1: string, timeSpan2: string) {
let startTime1 = timeSpan1.split(" - ")[0];
let startTimeArray1 = startTime1.split("/");
let startTimeNum1 =
parseInt(startTimeArray1[2]) * 10000 + parseInt(startTimeArray1[0]) * 100 + parseInt(startTimeArray1[1]);
let startTime2 = timeSpan2.split(" - ")[0];
let startTimeArray2 = startTime2.split("/");
let startTimeNum2 =
parseInt(startTimeArray2[2]) * 10000 + parseInt(startTimeArray2[0]) * 100 + parseInt(startTimeArray2[1]);
return startTimeNum2 - startTimeNum1;
}
getLastSeveraldayReport(daysCount: number) {
let today = new Date();
let utcTodayTime = Date.UTC(
today.getUTCFullYear(),
today.getUTCMonth(),
today.getUTCDate()
);
let pastDayTime = utcTodayTime - Constants.oneDayMilliseconds * daysCount;//get million seconds of these days
let pastDay = new Date(pastDayTime);//when init as this, the date is late a month than actual value
pastDay.setUTCMonth(Number(pastDay.getUTCMonth()) + 1);//so, need plus one to month
this.customizeStartDate = this.convertToDatePickerDate(pastDay);//put start date into DatePickeer
let yesterdayTime = utcTodayTime - Constants.oneDayMilliseconds * 1;
let yesterday = new Date(yesterdayTime);
yesterday.setUTCMonth(Number(yesterday.getUTCMonth()) + 1);
this.customizeEndDate = this.convertToDatePickerDate(yesterday);
this.generateCustomizedTriageReport();
}
convertToDatePickerDate(day: Date): any {
let customizeDate = {
date: {
year: day.getUTCFullYear(),
month: day.getUTCMonth(),
day: day.getUTCDate()
}
};
return customizeDate;
}
changeReportTimeSpan(reportTimeSpan: string) {
let reportTimeSpanIndex = 0;
this.reportTimeSpans.forEach((t, index) => {
if (t == reportTimeSpan) {
reportTimeSpanIndex = index;
}
})
if (this.reportTimeSpans.length == 1) {
this.enablePrevCaret = false;
this.enableNextCaret = false;
}
else if (reportTimeSpanIndex == 0) {
this.enablePrevCaret = true;
this.enableNextCaret = false;
}
else if (reportTimeSpanIndex == this.reportTimeSpans.length - 1) {
this.enablePrevCaret = false;
this.enableNextCaret = true;
}
else {
this.enablePrevCaret = true;
this.enableNextCaret = true;
}
this.currentReportTimeSpan = reportTimeSpan;
this.currentRegularReportTimeSpan = this.currentReportTimeSpan;
this.generateTriageReport(reportTimeSpan, ReportType.Weekly);
this.logger.info("changeReportTimeSpan", this.currentReportTimeSpan);
}
generateCustomizedTriageReport() {
if (this.customizeStartDate == null || this.customizeEndDate == null) {
this.existingCustomizedReport = false;
this.location.replaceState("triage/report");
return;
}
this.isFetchingReport = true;
//report timespan format: month/day/year
this.currentStartDate =
this.customizeStartDate.date.month +
"/" +
this.customizeStartDate.date.day +
"/" +
this.customizeStartDate.date.year;
this.currentEndDate =
this.customizeEndDate.date.month +
"/" +
this.customizeEndDate.date.day +
"/" +
this.customizeEndDate.date.year;
this.currentCustomizedReportTimeSpan = this.currentStartDate + " - " + this.currentEndDate;
this.currentReportTimeSpan = this.currentCustomizedReportTimeSpan;
this.generateTriageReport(this.currentReportTimeSpan, ReportType.Customize);
}
generateRegularTriageReport() {
if (this.currentRegularReportTimeSpan == null) {
this.getTriageReportTimeSpansByReportType(ReportType[ReportType.Weekly]);
}
else {
this.currentReportTimeSpan = this.currentRegularReportTimeSpan;
this.generateTriageReport(this.currentReportTimeSpan, ReportType.Weekly);
}
}
generateTriageReport(reportTimeSpan: string, type: ReportType) {
this.triageService.getTriageReport(reportTimeSpan, type, this.forceGenerate).subscribe(result => {
this.existingCustomizedReport = true;
if (result.triageReportDetails.forEach(t => t.allVersions.length == 0)) {
this.existingCustomizedReport = false;
}
this.initTables(result);
this.isFetchingReport = false;
this.changeUrl();
this.currentStartDate = result.startDate;
this.currentEndDate = result.endDate;
this.logger.info("current report", result);
});
let startTime = reportTimeSpan.split("-")[0].trim();
let endTime = reportTimeSpan.split("-")[1].trim();
this.triageService.getViewVersionMetric(startTime, endTime).subscribe(result => {
this.viewVersionMetric = result;
this.getViewVersionMetricLineChart(result.everyVersion, result.everyVersionViewCount);
})
this.logger.info("generateTriageReport", this.currentReportTimeSpan);
}
changeUrl() {
this.isUrlParam = true;
//change the url without redirction
if (this.isUrlParam) {
let urlReportTimeSpan = this.currentReportTimeSpan.replace(new RegExp("/", "g"), "_");
urlReportTimeSpan = urlReportTimeSpan.replace(" - ", "-");
this.location.replaceState("triage/report/" + this.displayType.toLowerCase() + "/" + urlReportTimeSpan);
}
}
initTables(report: TriageReport) {
this.currentReport = report;
this.allViewCount = report.triageReportSummary.allViewCount;
//triageReportSummary
this.triageReportSummary = this.getTriageReportSummary(report.triageReportSummary);
//triageReportDetails
this.allTriageReportDetails = report.triageReportDetails;
//missSlaSummary
this.missSlaSummary = this.getMissSlaSummary(report.triageReportSummary.missSlaSummary);
this.triageSummary = this.getTriageSummary(report.triageReportSummary.triageSummary);
this.errorSummary = this.getErrorSummary(report.triageReportSummary.errorSummary);
this.longLatencySummary = this.getLongLatencySummary(report.triageReportSummary.longLatencySummary);
//missSlaSummary
this.versionLatencyRank = report.triageReportSummary.rankSummary.versionLatencyRank;
this.segmentRanks = report.triageReportSummary.rankSummary.segmentRanks;
this.ownerRanks = report.triageReportSummary.rankSummary.ownerRanks;
this.viewNameRanks = report.triageReportSummary.rankSummary.viewNameRanks;
this.viewNameRanks = this.viewNameRanks.filter(viewNameRank => (viewNameRank.missSlaTimes + viewNameRank.triagedTimes + viewNameRank.erroredTimes > 0))
this.versionLatencyRank.zeroToFifty = this.getLatencyRankFacet(this.versionLatencyRank.zeroToFifty);
this.versionLatencyRank.fiftyToNinety = this.getLatencyRankFacet(this.versionLatencyRank.fiftyToNinety);
this.versionLatencyRank.ninetyToHundred = this.getLatencyRankFacet(this.versionLatencyRank.ninetyToHundred);
this.allTriageViewSupervisors = new Array<TriageViewSupervisor>();
if (this.allTriageReportDetails.length >0 ) {
this.allTriageReportDetails.forEach(triageReportDetail => {
let triageViewSupervisor = new TriageViewSupervisor();
if(triageReportDetail != null){
triageViewSupervisor.id = triageReportDetail.id;
triageViewSupervisor.customerId = triageReportDetail.customerId;
triageViewSupervisor.customerEnv = triageReportDetail.customerEnv;
triageViewSupervisor.entitySpaceName = triageReportDetail.entitySpaceName;
triageViewSupervisor.entitySpaceViewName = triageReportDetail.viewName;
triageViewSupervisor.segment = triageReportDetail.segment;
triageViewSupervisor.originalState = triageReportDetail.viewState;
triageViewSupervisor.owner = triageReportDetail.owner;
triageViewSupervisor.missSla = triageReportDetail.allVersions.filter(t => t.isMissSla).length;
triageViewSupervisor.updates = triageReportDetail.refreshedTimes;
triageViewSupervisor.averageLatency = triageReportDetail.averageLatency;
triageViewSupervisor.ninetyPercentLatency = triageReportDetail.ninetyLatency;
triageViewSupervisor.minLatency = triageReportDetail.minLatency;
triageViewSupervisor.maxLatency = triageReportDetail.maxLatency;
triageViewSupervisor.triageTimes = triageReportDetail.allVersions.filter(t => t.isTriaged).length;
triageViewSupervisor.latestVersionLatency = triageReportDetail.latestVersionLatency;
triageViewSupervisor.latestSucceedVersionLatency = triageReportDetail.latestSucceedVersionLatency;
}
this.allTriageViewSupervisors.push(triageViewSupervisor);
});
this.allTriageViewSupervisors.sort((a, b) => (a.entitySpaceViewName > b.entitySpaceViewName ? 1 : -1));
this.logger.info("this.allTriageViewSupervisors", this.allTriageViewSupervisors);
}
}
getMissSlaSummary(missSlaSummary: MissSlaSummary): MissSlaSummary {
missSlaSummary.everyVersion = this.getMissSlaFacet(missSlaSummary.everyVersion);
missSlaSummary.majorVersion = this.getMissSlaFacet(missSlaSummary.majorVersion);
missSlaSummary.manual = this.getMissSlaFacet(missSlaSummary.manual);
let newMissSlaSummary = new MissSlaSummary(
missSlaSummary.missSlaViewCount,
missSlaSummary.missSlaTimes,
missSlaSummary.everyVersion,
missSlaSummary.majorVersion,
missSlaSummary.manual
)
return newMissSlaSummary;
}
getMissSlaFacet(version: MissSlaFacet): MissSlaFacet {
version.rootCauseToSucceedIds = this.getRootCauseFacet(version.rootCauseToSucceedIds);
version.rootCauseToFailedIds = this.getRootCauseFacet(version.rootCauseToFailedIds);
let newMissSlaFacet = new MissSlaFacet(
version.rootCauseToSucceedIds,
version.rootCauseToFailedIds,
version.succeedViewCount,
version.failedViewCount,
version.stateCount,
version.missSlaTimes,
version.aveSlaGap
)
return newMissSlaFacet;
}
getRootCauseFacet(rootCauseFacet: RootCauseFacet): RootCauseFacet {
let newRootCauseFacet = new RootCauseFacet(
rootCauseFacet.unknow,
rootCauseFacet.triage,
rootCauseFacet.error,
rootCauseFacet.noSchedule,
rootCauseFacet.lateSchedule,
rootCauseFacet.longQueue,
rootCauseFacet.longRunning
)
return newRootCauseFacet;
}
getErrorSummary(errorSummary: ErrorSummary): ErrorSummary {
errorSummary.everyVersion = this.getErrorFacet(errorSummary.everyVersion);
errorSummary.majorVersion = this.getErrorFacet(errorSummary.majorVersion);
errorSummary.manual = this.getErrorFacet(errorSummary.manual);
let newErrorSummary = new ErrorSummary(
errorSummary.errorViewCount,
errorSummary.errorTimes,
errorSummary.everyVersion,
errorSummary.majorVersion,
errorSummary.manual
)
return newErrorSummary;
}
getErrorFacet(errorFacet: ErrorFacet): ErrorFacet {
let newErrorFacet = new ErrorFacet(
errorFacet.errorTimes,
errorFacet.erroredIds,
errorFacet.stateCount
)
return newErrorFacet;
}
getTriageSummary(triageSummary: TriageSummary): TriageSummary {
triageSummary.everyVersion = this.getTriageFacet(triageSummary.everyVersion);
triageSummary.majorVersion = this.getTriageFacet(triageSummary.majorVersion);
triageSummary.manual = this.getTriageFacet(triageSummary.manual);
let newTriageSummary = new TriageSummary(
triageSummary.triageViewCount,
triageSummary.triageTimes,
triageSummary.everyVersion,
triageSummary.majorVersion,
triageSummary.manual
)
return newTriageSummary;
}
getTriageFacet(triageFacet: TriageFacet): TriageFacet {
let newTriageFacet = new TriageFacet(
triageFacet.aveCommitLatency,
triageFacet.commitedIds,
triageFacet.stateCount,
triageFacet.triageTimes,
triageFacet.uncommitedIds
)
return newTriageFacet;
}
getLongLatencySummary(longLatencySummary: LongLatencySummary): LongLatencySummary {
let newLongLatencySummary = new LongLatencySummary(
longLatencySummary.everyVersion,
longLatencySummary.majorVersion,
longLatencySummary.manual
)
return newLongLatencySummary;
}
getLatencyRankFacet(latencyRankFacet: LatencyRankFacet): LatencyRankFacet {
let newLatencyRankFacet = new LatencyRankFacet(
latencyRankFacet.maxLatency,
latencyRankFacet.minLatency,
latencyRankFacet.aveLatency,
latencyRankFacet.ids,
)
return newLatencyRankFacet;
}
getTriageReportSummary(triageReportSummary: TriageReportSummary): TriageReportSummary {
let newTriageReportSummary = new TriageReportSummary(
triageReportSummary.allViewCount,
triageReportSummary.allRefreshTimes,
triageReportSummary.everyVersionRefreshtimes,
triageReportSummary.majorVersionRefreshtimes,
triageReportSummary.manualRefreshtimes,
triageReportSummary.errorPercent,
triageReportSummary.missSlaPercent,
triageReportSummary.triagePercent,
triageReportSummary.missSlaSummary,
triageReportSummary.errorSummary,
triageReportSummary.longLatencySummary,
triageReportSummary.triageSummary,
triageReportSummary.rankSummary
)
return newTriageReportSummary;
}
//#region get previous and get next report
getPreReport() {
let index: number = 0;
for (let i = 0; i < this.reportTimeSpans.length; i++) {
if (this.reportTimeSpans[i] == this.currentRegularReportTimeSpan) {
index = i;
}
}
index = index == this.reportTimeSpans.length - 1 ? 0 : index + 1;
this.changeReportTimeSpan(this.reportTimeSpans[index]);
}
getNextReport() {
let index: number = 0;
for (let i = 0; i < this.reportTimeSpans.length; i++) {
if (this.reportTimeSpans[i] == this.currentRegularReportTimeSpan) {
index = i;
}
}
index = index == 0 ? 0 : index - 1;
this.changeReportTimeSpan(this.reportTimeSpans[index]);
}
//#endregion
//#region get supervisors in modal
getModalSupervisors(triagedViewIds: Array<number>) {
this.modalTriageViewSupervisors = new Array<TriageViewSupervisor>();
this.modalTriageViewSupervisors = this.allTriageViewSupervisors.filter(
t => triagedViewIds.find(d => d == t.id) != null
);
this.modalTriageViewSupervisors.map(t => (t.expandStatistic = false));
this.modalTriageViewSupervisors.forEach(modalTriageViewSupervisor => {
this.allTriageReportDetails.filter(triageReportDetail => {
if (triageReportDetail.id == modalTriageViewSupervisor.id) {
modalTriageViewSupervisor.allVersions = triageReportDetail.allVersions;
}
})
})
this.logger.info("this.modalTriageViewSupervisors", this.modalTriageViewSupervisors);
}
//#endregion
//#region sort
sortSegmentRanks(column: string) {
switch (column) {
case "Segment":
this.segmentRankNameDesc = !this.segmentRankNameDesc;
let segmentRankNameDescNum = this.segmentRankNameDesc ? 1 : -1;
this.segmentRanks.sort((a, b) => segmentRankNameDescNum * (b.attribute > a.attribute ? 1 : -1));
break;
case "MissSla":
this.segmentRankMissSlaDesc = !this.segmentRankMissSlaDesc;
let segmentRankMissSlaDescNum = this.segmentRankMissSlaDesc ? 1 : -1;
this.segmentRanks.sort(
(a, b) => segmentRankMissSlaDescNum * (b.missSlaViewsIds.length - a.missSlaViewsIds.length)
);
break;
case "Triage":
this.segmentRankTriageDesc = !this.segmentRankTriageDesc;
let segmentRankTriageDescNum = this.segmentRankTriageDesc ? 1 : -1;
this.segmentRanks.sort(
(a, b) => segmentRankTriageDescNum * (b.triagedViewsIds.length - a.triagedViewsIds.length)
);
break;
case "Error":
this.segmentRankErrorDesc = !this.segmentRankErrorDesc;
let segmentRankErrorDescNum = this.segmentRankErrorDesc ? 1 : -1;
this.segmentRanks.sort((a, b) => segmentRankErrorDescNum * (b.erroredViewsIds.length - a.erroredViewsIds.length));
break;
}
}
sortOwnerRanks(column: string) {
switch (column) {
case "Owner":
this.ownerRankNameDesc = !this.ownerRankNameDesc;
let ownerRankNameDescNum = this.ownerRankNameDesc ? 1 : -1;
this.ownerRanks.sort((a, b) => ownerRankNameDescNum * (b.attribute > a.attribute ? 1 : -1));
break;
case "MissSla":
this.ownerRankMissSlaDesc = !this.ownerRankMissSlaDesc;
let ownerRankMissSlaDescNum = this.ownerRankMissSlaDesc ? 1 : -1;
this.ownerRanks.sort((a, b) => ownerRankMissSlaDescNum * (b.missSlaViewsIds.length - a.missSlaViewsIds.length));
break;
case "Triage":
this.ownerRankTriageDesc = !this.ownerRankTriageDesc;
let ownerRankTriageDescNum = this.ownerRankTriageDesc ? 1 : -1;
this.ownerRanks.sort((a, b) => ownerRankTriageDescNum * (b.triagedViewsIds.length - a.triagedViewsIds.length));
break;
case "Error":
this.ownerRankErrorDesc = !this.ownerRankErrorDesc;
let ownerRankErrorDescNum = this.ownerRankErrorDesc ? 1 : -1;
this.ownerRanks.sort((a, b) => ownerRankErrorDescNum * (b.erroredViewsIds.length - a.erroredViewsIds.length));
break;
}
}
sortViewNameRanks(column: string) {
switch (column) {
case "ViewName":
this.viewNameRankNameDesc = !this.viewNameRankNameDesc;
let viewNameRankNameDescNum = this.viewNameRankNameDesc ? 1 : -1;
this.viewNameRanks.sort((a, b) => viewNameRankNameDescNum * (b.viewName > a.viewName ? 1 : -1));
break;
case "Triage":
this.viewNameRankTriageDesc = !this.viewNameRankTriageDesc;
let viewNameRankTriageDescNum = this.viewNameRankTriageDesc ? 1 : -1;
this.viewNameRanks.sort((a, b) => viewNameRankTriageDescNum * (b.triagedTimes - a.triagedTimes));
break;
case "Error":
this.viewNameRankErrorDesc = !this.viewNameRankErrorDesc;
let viewNameRankErrorDescNum = this.viewNameRankErrorDesc ? 1 : -1;
this.viewNameRanks.sort((a, b) => viewNameRankErrorDescNum * (b.erroredTimes - a.erroredTimes));
break;
case "MissSla":
this.viewNameRankMissSlaDesc = !this.viewNameRankMissSlaDesc;
let viewNameRankMissSlaDescNum = this.viewNameRankMissSlaDesc ? 1 : -1;
this.viewNameRanks.sort((a, b) => viewNameRankMissSlaDescNum * (b.missSlaTimes - a.missSlaTimes));
break;
}
}
generatecViewVersionMetriLineChartResult(dailyViewVersionMetric: Array<DailyViewVersionMetric>, viewCount: number) {
let multiChartDatas = new Array<MultiChartData>();
if (dailyViewVersionMetric.length == 0) {
multiChartDatas.push(new MultiChartData(Constants.none, [new SingleChartData(Constants.none, 0)]));
this.viewVersionMetriLineChart.lineChartDetailDict.set(Constants.none, new MetricFacet([], 0, Constants.none, 0));
}
multiChartDatas[0] = new MultiChartData("missSla");
multiChartDatas[1] = new MultiChartData("triage");
multiChartDatas[2] = new MultiChartData("error");
let startTime = moment(new Date(this.currentReportTimeSpan.split("-")[0]));
let endTime = moment(new Date(this.currentReportTimeSpan.split("-")[1]));
let timespan = Number(endTime.diff(startTime, 'days', true).toFixed(2));
dailyViewVersionMetric.forEach(t => {
if(t.viewCount != 0){
this.missSlaPercent = Number((t.missSlaDaliyMetricFacet.viewCount / viewCount * 100).toFixed(2));
this.triagePercent = Number((t.triageDaliyMetricFacet.viewCount / viewCount * 100).toFixed(2));
this.errorPercent = Number((t.errorDaliyMetricFacet.viewCount / viewCount * 100).toFixed(2));
}
else{
this.missSlaPercent = 0;
this.triagePercent = 0;
this.errorPercent = 0;
}
for (let i = 0; i <= timespan; i++) {
if (!multiChartDatas[0].series[i] && !multiChartDatas[1].series[i] && !multiChartDatas[2].series[i]) {
multiChartDatas[0].series[i] = new SingleChartData(t.shortDate, this.missSlaPercent);
multiChartDatas[1].series[i] = new SingleChartData(t.shortDate, this.triagePercent);
multiChartDatas[2].series[i] = new SingleChartData(t.shortDate, this.errorPercent);
break;
}
}
this.viewVersionMetriLineChart.lineChartDetailDict.set(t.shortDate + "missSla", t.missSlaDaliyMetricFacet);
this.viewVersionMetriLineChart.lineChartDetailDict.set(t.shortDate + "triage", t.triageDaliyMetricFacet);
this.viewVersionMetriLineChart.lineChartDetailDict.set(t.shortDate + "error", t.errorDaliyMetricFacet);
});
return multiChartDatas;
}
getViewVersionMetricLineChart(dailyViewVersionMetric: Array<DailyViewVersionMetric>, viewCount: number) {
let colorDomain = new Array("#f0ad4e", "#ffa1b5", "#FF0000");
this.viewVersionMetriLineChart = new LineChart();
this.viewVersionMetriLineChart.scheme.domain = colorDomain;
this.viewVersionMetriLineChart.yAxisLabel = 'Percentage';
this.viewVersionMetriLineChart.results = this.generatecViewVersionMetriLineChartResult(dailyViewVersionMetric, viewCount);
}
changeViewVersion(type: string) {
switch (type) {
case "EveryVersion":
this.getViewVersionMetricLineChart(this.viewVersionMetric.everyVersion, this.viewVersionMetric.everyVersionViewCount);
break;
case "MajorVersion":
this.getViewVersionMetricLineChart(this.viewVersionMetric.majorVersion, this.viewVersionMetric.majorVersionViewCount);
break;
case "Manual":
this.getViewVersionMetricLineChart(this.viewVersionMetric.manual, this.viewVersionMetric.manualViewCount);
break;
}
}
}
<file_sep>/config/environment/environment.dev.ts
import { LogLevel } from "../../src/app/core/enums";
export const environmentDev = {
serverBaseUrl: "http://stcazr-264:9080/api",
defaultVC: "https://cosmos08.osdinfra.net/cosmos/Knowledge.STCA.prod/",
defaultCouldPriority: 800,
logLevel: LogLevel.Trace,
enableAAD: true,
adalConfig: {
tenant: "microsoft.onmicrosoft.com",
clientId: "31997c92-67a4-43be-b535-049e2f5b9e2c", //registered application's Id (GUID)
postLogoutRedirectUri: "http://localhost:8080/logout",
//redirectUri: "http://localhost:8080/" //comment this field to return current url after authentication
}
};
<file_sep>/src/app/core/entityAnalysis/entitySpaceAnalysis.ts
import { EntityAnalysis } from "./entityAnalysis";
export class EntitySpaceAnalysis extends EntityAnalysis{
constructor(
id: number,
name: string,
createdBy: string,
createdTime: string,
updatedBy: string,
updatedTime: string,
customerId: string,
customerEnv: string,
entitySpaceName: string,
entitySpaceVersion: string,
)
{
super(id, name, createdBy, createdTime, updatedBy, updatedTime, customerId, customerEnv);
}
}<file_sep>/src/app/components/entityAnalysis/entityAnalysis.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//ngModel
import { HttpModule } from '@angular/http';
//routes
import { EntityAnalysisRoutingModule } from './entityAnalysis-routing.module';
//plugin
//import {SlimLoadingBarModule} from 'ng2-slim-loading-bar'
import { AnalysisNavComponent } from './common/analysisNav.component';
import { AnalysisDashboardComponent } from './dashboard/analysisDashboard.component'
import { EntityAnalysisComponent } from './entityAnalysis.component'
// import { EntitySpaceAnalysisComponent } from './entitySpace/entitySpaceAnalysis.component';
import { PayloadExplorerComponent } from './entitySpace/payloadExplorer.component';
import { PayloadStatisticComponent } from './entitySpace/payloadStatistic.component';
import { PayloadFilterComponent } from './entitySpace/payloadFilter.component';
import { EntityViewAnalysisComponent } from './entityView/entityViewAnalysis.component';
import { EntityGraphAnalysisComponent } from './entityGraph/entityGraphAnalysis.component';
import { AnalysisDashboardService } from './service/analysisDashboard.service'
import { CommonModule } from '../../../../node_modules/@angular/common';
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
EntityAnalysisRoutingModule,
//SlimLoadingBarModule.forRoot()
],
declarations: [
AnalysisDashboardComponent,
EntityAnalysisComponent,
AnalysisNavComponent,
//EntitySpaceAnalysisComponent,
EntityViewAnalysisComponent,
EntityGraphAnalysisComponent,
PayloadExplorerComponent,
PayloadStatisticComponent,
PayloadFilterComponent
],
providers: [
AnalysisDashboardService
]
})
export class EntityAnalysisModule { }
<file_sep>/src/app/components/report/report.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//ngModel
import { HttpModule } from '@angular/http';
//routes
import { ReportRoutingModule } from './report-routing.module';
import { ContributionComponent } from './contribution/contribution.component';
import { ReportComponent } from './report.component';
import { CommonModule } from '../../../../node_modules/@angular/common';
//plugin
//import {SlimLoadingBarModule} from 'ng2-slim-loading-bar'
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
ReportRoutingModule,
//SlimLoadingBarModule.forRoot()
],
declarations: [
ContributionComponent,
ReportComponent
],
providers: [
]
})
export class ReportModule { }
<file_sep>/src/app/templates/ngxJsonViewer/ngxJsonViewer.component.ts
import { Component, OnChanges, Input, OnInit } from '@angular/core';
// var data = require('./entityJson.json');
export interface Segment {
key: string;
value: any;
type: undefined | string;
description: string;
level: number;
expanded: boolean;
}
@Component({
selector: 'ngx-json-viewer',
templateUrl: './ngxJsonViewer.component.html',
styles: [require('./ngxJsonViewer.component.scss').toString()]
})
export class NgxJsonViewerComponent implements OnInit, OnChanges {
// @Input() json: any = data;
@Input() json: any;
@Input() expanded: boolean = false;
@Input() expandLevel: number = 3;
@Input() curLevel: number = 1;
/**
* @deprecated It will be always true and deleted in version 3.0.0
*/
@Input() cleanOnChange = true;
segments: Segment[] = [];
ngOnInit() {
if (this.json && typeof this.json === 'string') {
this.json = JSON.parse(this.json);
}
this.ngOnChanges();
}
ngOnChanges() {
if (this.cleanOnChange) {
this.segments = [];
}
if (typeof this.json === 'object') {
Object.keys(this.json).forEach(key => {
this.segments.push(this.parseKeyValue(key, this.json[key], this.curLevel));
});
}
}
isExpandable(segment: Segment) {
return (segment.type === 'object' || segment.type === 'array');
}
isExpandLevel() {
return this.curLevel <= this.expandLevel;
}
toggle(segment: Segment) {
if (this.isExpandable(segment)) {
segment.expanded = !segment.expanded;
}
}
private parseKeyValue(key: any, value: any, level: number): Segment {
const segment: Segment = {
key: key,
value: value,
type: undefined,
description: '' + value,
level: level,
expanded: this.isExpandLevel() && ((typeof value === 'object') || Array.isArray(value))
};
switch (typeof segment.value) {
case 'number': {
segment.type = 'number';
break;
}
case 'boolean': {
segment.type = 'boolean';
break;
}
case 'function': {
segment.type = 'function';
break;
}
case 'string': {
segment.type = 'string';
segment.description = '"' + segment.value + '"';
break;
}
case 'undefined': {
segment.type = 'undefined';
segment.description = 'undefined';
break;
}
case 'object': {
// yea, null is object
if (segment.value === null) {
segment.type = 'null';
segment.description = 'null';
} else if (Array.isArray(segment.value)) {
segment.type = 'array';
segment.description = 'Array[' + segment.value.length + '] ' + JSON.stringify(segment.value);
} else if (segment.value instanceof Date) {
segment.type = 'date';
} else {
segment.type = 'object';
segment.description = 'Object ' + JSON.stringify(segment.value);
}
break;
}
}
return segment;
}
}
<file_sep>/src/app/helper/arrayExtension.ts
interface Array<T> {
distinct(): this;
}
Array.prototype.distinct = function () {
return this.filter((item: any, index: number) => index === this.lastIndexOf(item));
};
<file_sep>/src/app/core/triage/triageReport.ts
import { ViewVersionLatency } from "./triageStatistic";
import { TriageViewSupervisor } from "./triageViewSupervisor";
import { MissSlaType } from "../enums";
import '../../helper/arrayExtension';
export class TriageReport {
constructor(
public reportTimeSpan?: string,
public type?: string,
public createdTime?: string,
public startDate?: string,
public endDate?: string,
public triageReportSummary?: TriageReportSummary,
public triageReportDetails?: Array<TriageReportDetail>
) {
this.triageReportSummary = new TriageReportSummary();
this.triageReportDetails = new Array<TriageReportDetail>();
}
}
export class TriageReportSummary {
constructor(
public allViewCount?: number,
public allRefreshTimes?: number,
public everyVersionRefreshtimes?: number,
public majorVersionRefreshtimes?: number,
public manualRefreshtimes?: number,
public errorPercent?: number,
public missSlaPercent?: number,
public triagePercent?: number,
public missSlaSummary?: MissSlaSummary,
public errorSummary?: ErrorSummary,
public longLatencySummary?: LongLatencySummary,
public triageSummary?: TriageSummary,
public rankSummary?: RankSummary
) {
this.missSlaSummary = new MissSlaSummary();
this.errorSummary = new ErrorSummary();
this.longLatencySummary = new LongLatencySummary();
this.triageSummary = new TriageSummary();
this.rankSummary = new RankSummary();
}
get currentMissSLAViewsPercent():number{
return Number((this.missSlaPercent * 100).toFixed(2));
}
get currentTriagedViewsPercent():number{
return Number((this.triagePercent * 100).toFixed(2));
}
get currentErrorViewsPercent():number{
return Number((this.triagePercent * 100).toFixed(2));
}
}
export class MissSlaSummary {
constructor(
public missSlaViewCount?: number,
public missSlaTimes?: number,
public everyVersion?: MissSlaFacet,
public majorVersion?: MissSlaFacet,
public manual?: MissSlaFacet
) {}
get allMissSlaViewIds(): Array<number> {
let allMissSlaViewIds = new Array<number>();
allMissSlaViewIds = this.everyVersion.allViewIds
.concat(this.majorVersion.allViewIds)
.concat(this.manual.allViewIds);
return allMissSlaViewIds.distinct();
}
currentMissSLATimesPercent(missSlaSummary:MissSlaSummary,triageReportSummary:TriageReportSummary){
return Number(((missSlaSummary.missSlaTimes / triageReportSummary.allRefreshTimes) * 100).toFixed(2));
}
}
export class MissSlaFacet {
constructor(
public rootCauseToSucceedIds?: RootCauseFacet,
public rootCauseToFailedIds?: RootCauseFacet,
public succeedViewCount?: number,
public failedViewCount?: number,
public stateCount?: number,
public missSlaTimes?: number,
public aveSlaGap?: number
) {}
get allViewIds(): Array<number> {
let allViewIds = new Array<number>();
allViewIds = this.rootCauseToSucceedIds.allIds.concat(this.rootCauseToFailedIds.allIds);
return allViewIds.distinct();
}
get missSlaViewsPercent(): number {
return Number(((this.allViewIds.length / this.stateCount) * 100).toFixed(2));
}
missSlaEveryVersionPercent(missSlaFacet:MissSlaFacet,triageReportSummary:TriageReportSummary){
return Number(((missSlaFacet.missSlaTimes / triageReportSummary.everyVersionRefreshtimes) * 100).toFixed(2));
}
missSlaMajorVersionPercent(missSlaFacet:MissSlaFacet,triageReportSummary:TriageReportSummary){
return Number(((missSlaFacet.missSlaTimes / triageReportSummary.majorVersionRefreshtimes) * 100).toFixed(2));
}
missSlaManualPercent(missSlaFacet:MissSlaFacet,triageReportSummary:TriageReportSummary){
return Number(((missSlaFacet.missSlaTimes / triageReportSummary.manualRefreshtimes) * 100).toFixed(2));
}
}
export class RootCauseFacet {
constructor(
public unknow?: Array<number>,
public triage?: Array<number>,
public error?: Array<number>,
public noSchedule?: Array<number>,
public lateSchedule?: Array<number>,
public longQueue?: Array<number>,
public longRunning?: Array<number>
) {}
get unknowIds(): Array<number>{
return this.unknow ? this.StringToNumber(Object.keys(this.unknow)) : [];
}
get triageIds(): Array<number>{
return this.triage ? this.StringToNumber(Object.keys(this.triage)) : [];
}
get errorIds(): Array<number>{
return this.error ? this.StringToNumber(Object.keys(this.error)) : [];
}
get noScheduleIds(): Array<number>{
return this.noSchedule ? this.StringToNumber(Object.keys(this.noSchedule)) : [];
}
get lateScheduleIds(): Array<number>{
return this.lateSchedule ? this.StringToNumber(Object.keys(this.lateSchedule)) : [];
}
get longQueueIds(): Array<number>{
return this.longQueue ? this.StringToNumber(Object.keys(this.longQueue)) : [];
}
get longRunningIds(): Array<number>{
return this.longRunning ? this.StringToNumber(Object.keys(this.longRunning)) : [];
}
get unknowCount(): number {
return this.unknow ? this.StringToNumber(Object.keys(this.unknow)).length : 0;
}
get triageCount(): number {
return this.triage ? this.StringToNumber(Object.keys(this.triage)).length : 0;
}
get errorCount(): number {
return this.error ? this.StringToNumber(Object.keys(this.error)).length : 0;
}
get noScheduleCount(): number {
return this.noSchedule ? this.StringToNumber(Object.keys(this.noSchedule)).length : 0;
}
get lateScheduleCount(): number {
return this.lateSchedule ? this.StringToNumber(Object.keys(this.lateSchedule)).length : 0;
}
get longQueueCount(): number {
return this.longQueue ? this.StringToNumber(Object.keys(this.longQueue)).length : 0;
}
get longRunningCount(): number {
return this.longRunning ? this.StringToNumber(Object.keys(this.longRunning)).length : 0;
}
StringToNumber(arr: Array<string>) {
let ids = new Array<number>();
arr.forEach(t => ids.push(Number(t)));
return ids;
}
get allIds(): Array<number> {
let allIds = new Array<number>();
if (this.unknow) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.unknow)));
}
if (this.triage) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.triage)));
}
if (this.error) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.error)));
}
if (this.noSchedule) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.noSchedule)));
}
if (this.lateSchedule) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.lateSchedule)));
}
if (this.longQueue) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.longQueue)));
}
if (this.longRunning) {
allIds = allIds.concat(this.StringToNumber(Object.keys(this.longRunning)));
}
return allIds.distinct();
}
}
export class ErrorSummary {
constructor(
public errorViewCount?: number,
public errorTimes?: number,
public everyVersion?: ErrorFacet,
public majorVersion?: ErrorFacet,
public manual?: ErrorFacet
) {}
get allErrorViewIds(): Array<number> {
let allErrorViewIds = new Array<number>();
allErrorViewIds = this.everyVersion.erroredIds
.concat(this.majorVersion.erroredIds)
.concat(this.manual.erroredIds);
return allErrorViewIds.distinct();
}
currentErrorTimesPercent(errorSummary:ErrorSummary,triageReportSummary:TriageReportSummary){
return Number(((errorSummary.errorTimes / triageReportSummary.allRefreshTimes) * 100).toFixed(2));
}
}
export class ErrorFacet {
constructor(
public errorTimes?: number,
public erroredIds?: Array<number>,
public stateCount?: number
) {}
get errorViewsPercent(): number {
return Number(((this.erroredIds.length / this.stateCount) * 100).toFixed(2));
}
errorEveryVersionPercent(errorFacet:ErrorFacet,triageReportSummary:TriageReportSummary){
return Number(((errorFacet.errorTimes / triageReportSummary.everyVersionRefreshtimes) * 100).toFixed(2));
}
errorMajorVersionPercent(errorFacet:ErrorFacet,triageReportSummary:TriageReportSummary){
return Number(((errorFacet.errorTimes / triageReportSummary.majorVersionRefreshtimes) * 100).toFixed(2));
}
errorManualPercent(errorFacet:ErrorFacet,triageReportSummary:TriageReportSummary){
return Number(((errorFacet.errorTimes / triageReportSummary.manualRefreshtimes) * 100).toFixed(2));
}
}
export class LongLatencySummary {
constructor(
public everyVersion?: Array<number>,
public majorVersion?: Array<number>,
public manual?: Array<number>
) { }
longLatencyEveryVersionPercent(missSlaFacet:MissSlaFacet){
return Number(((this.everyVersion.length / missSlaFacet.stateCount) * 100).toFixed(2));
}
longLatencyMajorVersionPercent(missSlaFacet:MissSlaFacet){
return Number(((this.majorVersion.length / missSlaFacet.stateCount) * 100).toFixed(2));
}
longLatencyManualPercent(missSlaFacet:MissSlaFacet){
return Number(((this.manual.length / missSlaFacet.stateCount) * 100).toFixed(2));
}
}
export class TriageSummary {
constructor(
public triageViewCount?: number,
public triageTimes?: number,
public everyVersion?: TriageFacet,
public majorVersion?: TriageFacet,
public manual?: TriageFacet
) {}
get allTriageViewIds(): Array<number> {
let allTriageViewIds = new Array<number>();
allTriageViewIds = this.everyVersion.allViewIds
.concat(this.majorVersion.allViewIds)
.concat(this.manual.allViewIds);
return allTriageViewIds.distinct();
}
currentTriagedTimesPercent(triageSummary:TriageSummary,triageReportSummary:TriageReportSummary){
return Number(((triageSummary.triageTimes / triageReportSummary.allRefreshTimes) * 100).toFixed(2));
}
}
export class TriageFacet {
constructor(
public aveCommitLatency?: number,
public commitedIds?: Array<number>,
public stateCount?: number,
public triageTimes?: number,
public uncommitedIds?: Array<number>
) {}
get aveLatency(): number {
return Number(this.aveCommitLatency.toFixed(2));
}
get allViewIds(): Array<number> {
let allViewIds = new Array<number>();
allViewIds = this.commitedIds.concat(this.uncommitedIds);
return allViewIds.distinct();
}
get triageViewsPercent(): number {
return Number(((this.allViewIds.length / this.stateCount) * 100).toFixed(2));
}
triageEveryVersionPercent(triageFacet:TriageFacet,triageReportSummary:TriageReportSummary){
return Number(((triageFacet.triageTimes / triageReportSummary.everyVersionRefreshtimes) * 100).toFixed(2));
}
triageMajorVersionPercent(triageFacet:TriageFacet,triageReportSummary:TriageReportSummary){
return Number(((triageFacet.triageTimes / triageReportSummary.majorVersionRefreshtimes) * 100).toFixed(2));
}
triageManualPercent(triageFacet:TriageFacet,triageReportSummary:TriageReportSummary){
return Number(((triageFacet.triageTimes / triageReportSummary.manualRefreshtimes) * 100).toFixed(2));
}
}
export class RankSummary {
constructor(
public versionLatencyRank?: VersionLatencyRank,
public ownerRanks?: Array<AttributeRank>,
public segmentRanks?: Array<AttributeRank>,
public viewNameRanks?: Array<ViewNameRank>
) {
this.versionLatencyRank = new VersionLatencyRank();
this.segmentRanks = new Array<AttributeRank>();
this.ownerRanks = new Array<AttributeRank>();
this.viewNameRanks = new Array<ViewNameRank>();
}
}
export class VersionLatencyRank {
constructor(
public zeroToFifty?: LatencyRankFacet,
public fiftyToNinety?: LatencyRankFacet,
public ninetyToHundred?: LatencyRankFacet
) {
this.zeroToFifty = new LatencyRankFacet();
this.fiftyToNinety = new LatencyRankFacet();
this.ninetyToHundred = new LatencyRankFacet();
}
}
export class LatencyRankFacet {
constructor(
public maxLatency?: number,
public minLatency?: number,
public aveLatency?: number,
public ids?: Array<number>
) {}
get aveLatencyRank(): number {
return Number(this.aveLatency.toFixed(2));
}
}
export class AttributeRank {
constructor(
public attribute?: string,
public erroredViewsIds?: Array<number>,
public missSlaViewsIds?: Array<number>,
public triagedViewsIds?: Array<number>
) {
this.missSlaViewsIds = new Array<number>();
this.triagedViewsIds = new Array<number>();
this.erroredViewsIds = new Array<number>();
}
}
export class ViewNameRank {
constructor(
public id?: number,
public viewName?: string,
public missSlaTimes?: number,
public triagedTimes?: number,
public erroredTimes?: number
) {}
}
export class TriageReportDetail {
constructor(
public id?: number,
public allVersions?: Array<ViewVersionLatency>,
public averageLatency?: string,
public minLatency?: string,
public maxLatency?: string,
public ninetyLatency?: string,
public owner?: string,
public refreshedTimes?: number,
public segment?: string,
public viewName?: string,
public currentState?: string,
public viewState?: string,
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public latestVersionLatency?: number,
public latestSucceedVersionLatency?: number
) {
this.allVersions = new Array<ViewVersionLatency>();
}
}
export class ViewVersionMetric {
constructor(
public everyVersionViewCount?: number,
public everyVersionVersionCount?: number,
public majorVersionViewCount?: number,
public majorVersionVersionCount?: number,
public manualViewCount?: number,
public manualVersionCount?: number,
public everyVersion?: Array<DailyViewVersionMetric>,
public majorVersion?: Array<DailyViewVersionMetric>,
public manual?: Array<DailyViewVersionMetric>,
) { }
}
export class DailyViewVersionMetric {
constructor(
public shortDate?: string,
public viewCount?: number,
public versionCount?: number,
public missSlaDaliyMetricFacet?: MetricFacet,
public triageDaliyMetricFacet?: MetricFacet,
public errorDaliyMetricFacet?: MetricFacet,
) { }
}
export class MetricFacet {
constructor(
public viewIds?: Array<number>,
public viewCount?: number,
public idToVersions?: any,
public versionCount?: number
) { }
}<file_sep>/src/app/core/triage/TriageViewSupervisor.ts
import { MultiChartData, SingleChartData, LineChart, StackedVerticalBarChart, VerticalBarChart } from "../plugin/ngxChart";
import { Constants } from "../common/constants";
import { ViewVersionDuration, ViewStateTimeStamp, TriageCommitDuration, TriageAndErrorDistribution, ViewVersionLatencyDetail, ViewVersionLatency, VersionLatencyStateDetail, VersionLatencyStateDetailUnit } from "./triageStatistic";
import * as moment from 'moment';
export class TriageViewSupervisor {
constructor(
public id?: number,
public triageAnalysisId?: number,
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public entitySpaceViewName?: string,
public segment?: string,
public currentState?: string,
public originalState?: string,
public latestVersion?: string,
public latestVersionState?: string,
public latestCompletedVersion?: string,
public latestCompletedVersionState?: string,
public latestSucceedTime?: string,
public latestVersionLatency?: number,
public latestSucceedVersionLatency?: number,
public latestStandardVersion?: string,
public latestJobType?: string,
public deletedCount?: string,
public addedCount?: string,
public churnedCount?: string,
public owner?: string,
public tfsUrl?: string,
public expandStatistic?: boolean,
public versionDelayLineChart?: LineChart,
public commitDelayLineChart?: LineChart,
public monthlyCountLineChart?: LineChart,
public viewVersionDuration?: ViewVersionDuration,
public versionDelayStackedVerticalBarChart?: StackedVerticalBarChart,
public versionDetailStackedVerticalBarChart?: StackedVerticalBarChart,
public missSlaBarChart?: VerticalBarChart,
public completeVersions?: Array<MultiChartData>,
public mouseOverDelete?: boolean,
public displayOwnerNameEditor?: boolean,
public displaySegmentNameEditor?: boolean,
public missSla?: number,
public updates?: number,
public triageTimes?: number,
public averageLatency?: string,
public minLatency?: string,
public maxLatency?: string,
public fiftyPercentLatency?: string,
public ninetyPercentLatency?: string,
public allVersions?: Array<ViewVersionLatency>
) {
this.versionDelayLineChart = new LineChart();
this.commitDelayLineChart = new LineChart();
this.monthlyCountLineChart = new LineChart();
this.viewVersionDuration = new ViewVersionDuration();
this.versionDelayStackedVerticalBarChart = new StackedVerticalBarChart();
this.versionDetailStackedVerticalBarChart = new StackedVerticalBarChart();
this.missSlaBarChart = new VerticalBarChart();
this.completeVersions = new Array<MultiChartData>();
}
get customerIdEnv(): string {
return `${this.customerId}-${this.customerEnv}`;
}
get viewKey(): string {
return `${this.entitySpaceName}_${this.entitySpaceViewName}`;
}
get triageAnalysisUrl(): string {
return `/triage/analysis/${this.customerIdEnv}/${this.viewKey}`;
}
get entitySpaceViewUrl(): string {
let underlineSplitedVersionNum = "";
if(this.latestVersion){
underlineSplitedVersionNum = this.latestVersion.replace(/\./g, "_");
}else{
underlineSplitedVersionNum = "";
}
return `http://entityrepository.binginternal.com:88/ERPortal/PROD/${this.customerId}-${
this.customerEnv
}/EntitySpaceOverview/EntitySpaceViewDetails?entitySpaceName=${this.entitySpaceName}&viewKey=${this.viewKey}#v${underlineSplitedVersionNum}`;
}
generateVersionDelayLineChartResult(viewVersionLatency: Array<ViewVersionLatency>) {
let multiChartDatas = new Array<MultiChartData>();
multiChartDatas[0] = new MultiChartData("Version Delay");
let singleChartDatas = new Array<SingleChartData>();
if (viewVersionLatency.length == 0) {
multiChartDatas[0] = new MultiChartData("no triage", [new SingleChartData(Constants.none, 0)]);
this.versionDelayLineChart.lineChartDetailDict.set(Constants.none, new ViewStateTimeStamp(Constants.none, Constants.none, Constants.none));
return multiChartDatas;
}
viewVersionLatency.forEach(t => {
multiChartDatas[0].series.push(new SingleChartData(t.version, Number(t.totalTime)));
this.versionDelayLineChart.lineChartDetailDict.set(t.version, t);
})
return multiChartDatas;
}
getVersionDelayLineChart(viewVersionLatency: Array<ViewVersionLatency>) {
let colorDomain = new Array("#a8385d", "#FFA1B5", "#86C7F3", "#5aa454");
this.versionDelayLineChart = new LineChart();
this.versionDelayLineChart.view = [1700, 400];
this.versionDelayLineChart.results = new Array();
this.versionDelayLineChart.scheme.domain = colorDomain;
this.versionDelayLineChart.results = this.generateVersionDelayLineChartResult(viewVersionLatency);
}
generateCommitDelayLineChartResult(viewVersionLatency: Array<ViewVersionLatency>) {
let multiChartDatas = new Array<MultiChartData>();
multiChartDatas[0] = new MultiChartData("triage");
let singleChartDatas = new Array<SingleChartData>();
if (viewVersionLatency.length == 0) {
multiChartDatas[0] = new MultiChartData("no triage", [new SingleChartData(Constants.none, 0)]);
this.commitDelayLineChart.lineChartDetailDict.set(Constants.none, new ViewStateTimeStamp(Constants.none, Constants.none, Constants.none));
return multiChartDatas;
}
viewVersionLatency.forEach(t => {
if (t.isTriaged && t.isCommited) {
multiChartDatas[0].series.push(new SingleChartData(t.version, Number(t.commitedTime)));
}
else {
multiChartDatas[0].series.push(new SingleChartData(t.version, 0));
}
this.commitDelayLineChart.lineChartDetailDict.set(t.version, t);
});
return multiChartDatas;
}
getCommitDelayLineChart(viewVersionLatency: Array<ViewVersionLatency>) {
let colorDomain = new Array("#FFA1B5", "#86C7F3", "#5aa454");
this.commitDelayLineChart = new LineChart();
this.commitDelayLineChart.view = [1700, 400];
this.commitDelayLineChart.results = new Array();
this.commitDelayLineChart.scheme.domain = colorDomain;
this.commitDelayLineChart.results = this.generateCommitDelayLineChartResult(viewVersionLatency);
}
groupBy(objectArray: any, property: string) {
return objectArray.reduce(function (acc: any, obj: any) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
generateMonthlyCountLineChartResult(viewVersionLatency: Array<ViewVersionLatency>) {
let multiChartDatas = new Array<MultiChartData>();
if (viewVersionLatency.length == 0) {
multiChartDatas[0] = new MultiChartData("no triage", [new SingleChartData(Constants.none, 0)]);
this.commitDelayLineChart.lineChartDetailDict.set(Constants.none, new ViewStateTimeStamp(Constants.none, Constants.none, Constants.none));
}
multiChartDatas[0] = new MultiChartData("triage");
multiChartDatas[1] = new MultiChartData("error");
multiChartDatas[2] = new MultiChartData("missSLA");
multiChartDatas[3] = new MultiChartData("standard");
let versionLatency = this.groupBy(viewVersionLatency, 'date');
for (var t in versionLatency) {
let triageCount = 0, errorCount = 0, missSlaCount = 0;
versionLatency[t].forEach((version: any) => {
triageCount = version.isTriaged ? triageCount + 1 : triageCount;
errorCount = version.isErrored ? errorCount + 1 : errorCount;
missSlaCount = version.isMissSla ? missSlaCount + 1 : missSlaCount;
});
for (let i = 0; i < Constants.monthDays; i++) {
if (!multiChartDatas[0].series[i] && !multiChartDatas[1].series[i] && !multiChartDatas[2].series[i] && !multiChartDatas[3].series[i]) {
multiChartDatas[0].series[i] = new SingleChartData(t, triageCount);
multiChartDatas[1].series[i] = new SingleChartData(t, errorCount);
multiChartDatas[2].series[i] = new SingleChartData(t, missSlaCount);
multiChartDatas[3].series[i] = new SingleChartData(t, versionLatency[t].length - triageCount - errorCount);
break;
}
}
this.monthlyCountLineChart.lineChartDetailDict.set(t + "triage", versionLatency[t]);
this.monthlyCountLineChart.lineChartDetailDict.set(t + "error", versionLatency[t]);
this.monthlyCountLineChart.lineChartDetailDict.set(t + "missSLA", versionLatency[t]);
this.monthlyCountLineChart.lineChartDetailDict.set(t + "standard", versionLatency[t]);
}
return multiChartDatas;
}
getMonthlyCountLineChart(viewVersionLatency: Array<ViewVersionLatency>) {
let colorDomain = new Array("#ffa1b5", "#FF0000", "#f0ad4e", "#5aa454");
this.monthlyCountLineChart = new LineChart();
this.monthlyCountLineChart.view = [1700, 400];
this.monthlyCountLineChart.scheme.domain = colorDomain;
this.monthlyCountLineChart.results = this.generateMonthlyCountLineChartResult(viewVersionLatency);
}
getversionStateDetails(viewVersionLatency: Array<ViewVersionLatency>) {
let viewVersionDetails = new Array<ViewVersionLatencyDetail>();
viewVersionLatency.forEach((t, index) => {
let viewVersionDetail = new ViewVersionLatencyDetail(t.createdTimestamp, t.version, t.updateType, new VersionLatencyStateDetail());
let versionStateDetail = viewVersionDetail.versionStateDetail;
versionStateDetail.queue = new VersionLatencyStateDetailUnit("Queue", null, "0");
versionStateDetail.building = new VersionLatencyStateDetailUnit("Building", null, "0");
versionStateDetail.updating = new VersionLatencyStateDetailUnit("Updating", null, "0");
versionStateDetail.commited = new VersionLatencyStateDetailUnit("Commited", null, "0");
versionStateDetail.errored = new VersionLatencyStateDetailUnit("Errored", null, "0");
versionStateDetail.standard = new VersionLatencyStateDetailUnit("Standard", null, "0");
versionStateDetail.timeout = new VersionLatencyStateDetailUnit("Timeout", null, "0");
versionStateDetail.retry = new VersionLatencyStateDetailUnit("Retry", null, "0");
//queue Time
versionStateDetail.queue = new VersionLatencyStateDetailUnit('Queue', t.jobStartTimeStamp, t.queuedTime);
//retry
let retryTimetamp = moment(new Date(t.createdTimestamp)).add(Number(t.retryTime), "hours").format("YYYY/MM/DD hh:mm:ss");
versionStateDetail.retry = new VersionLatencyStateDetailUnit('Retry', retryTimetamp, t.retryTime);
//run Time
switch (t.state) {
//running => error ,should be dark red after queue in front end
case "Errored":
versionStateDetail.errored = new VersionLatencyStateDetailUnit("Errored", t.erroredTimestamp, t.runningTime);
break;
//running => standard ,should be green after queue in front end
case "Standard":
if (!t.isTriaged) {
versionStateDetail.standard = new VersionLatencyStateDetailUnit("Standard", t.sealedTimestamp, t.runningTime);
}
break;
//should be blue after queue in front end
default:
//updateType is building
if (t.updateType == "Building") {
versionStateDetail.building = new VersionLatencyStateDetailUnit("Building", t.sealedTimestamp, t.runningTime);
}
//updateType is updating
else {
versionStateDetail.updating = new VersionLatencyStateDetailUnit("Updating", t.sealedTimestamp, t.runningTime);
}
break;
}
//comitte or triage to timeout
//judge if triage has committed
if (t.isTriaged) {
if (t.isCommited) {
versionStateDetail.commited = new VersionLatencyStateDetailUnit("Commited", t.sealedTimestamp, t.commitedTime);
}
else {
let timeoutSpan;
if (t.originalState == 'EveryVersion' || !t.originalState) {
timeoutSpan = Constants.everyVersionTimeout;
}
else if (t.originalState == 'MajorVersion') {
timeoutSpan = Constants.majorVersionTimeout;
}
else if (t.originalState == "Manual") {
timeoutSpan = Constants.manualTimeout;
}
if (index == viewVersionLatency.length - 1) {
versionStateDetail.timeout = new VersionLatencyStateDetailUnit("Timeout", moment().format("YYYY/MM/DD hh:mm:ss"), timeoutSpan.toString());
}
else {
let createTime = moment(new Date(viewVersionLatency[index + 1].createdTimestamp));
let triageTime = moment(new Date(t.triagedTimestamp));
let durationToNext = Number(createTime.diff(triageTime, 'hours', true).toFixed(2));
timeoutSpan = timeoutSpan < durationToNext ? timeoutSpan : durationToNext;
versionStateDetail.timeout = new VersionLatencyStateDetailUnit("Timeout", moment(triageTime).add(timeoutSpan, 'hours').format("YYYY/MM/DD hh:mm:ss"), timeoutSpan.toString());
}
}
//should be blue after queue in front endS
//updateType is building
if (t.updateType == "Building") {
versionStateDetail.building = new VersionLatencyStateDetailUnit("Building", t.triagedTimestamp, t.runningTime);
}
//updateType is updating
else {
versionStateDetail.updating = new VersionLatencyStateDetailUnit("Updating", t.triagedTimestamp, t.runningTime);
}
}
viewVersionDetails.push(viewVersionDetail);
});
return viewVersionDetails;
}
generatetVersionDetailStackedVerticalBarChartResult(viewVersionDetails: Array<ViewVersionLatencyDetail>) {
let versionDetails = new Array<MultiChartData>();
if (viewVersionDetails.length == 0) {
versionDetails.push(new MultiChartData("no version", [new SingleChartData(Constants.none, 0)]));
this.versionDelayStackedVerticalBarChart.stackedVerticalBarChartDetailDict.set(Constants.none, new ViewStateTimeStamp(Constants.none, Constants.none, Constants.none));
return versionDetails;
}
viewVersionDetails.forEach(t => {
let versionLatencyStateDetails = new Array<SingleChartData>(
new SingleChartData(t.versionStateDetail.retry.state, Number(t.versionStateDetail.retry.cost)),
new SingleChartData(t.versionStateDetail.queue.state, Number(t.versionStateDetail.queue.cost)),
new SingleChartData(t.versionStateDetail.building.state, Number(t.versionStateDetail.building.cost)),
new SingleChartData(t.versionStateDetail.updating.state, Number(t.versionStateDetail.updating.cost)),
new SingleChartData(t.versionStateDetail.commited.state, Number(t.versionStateDetail.commited.cost)),
new SingleChartData(t.versionStateDetail.errored.state, Number(t.versionStateDetail.errored.cost)),
new SingleChartData(t.versionStateDetail.standard.state, Number(t.versionStateDetail.standard.cost)),
new SingleChartData(t.versionStateDetail.timeout.state, Number(t.versionStateDetail.timeout.cost))
);
//set the TooltipTemplate
//all block in a column use same timestamp and satme version
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict.set(t.timeStamp, t);
//blocks in a column different from state, so the key is timeStamp plus state
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.retry.state, t.versionStateDetail.retry.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.queue.state, t.versionStateDetail.queue.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.building.state, t.versionStateDetail.building.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.updating.state, t.versionStateDetail.updating.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.commited.state, t.versionStateDetail.commited.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.errored.state, t.versionStateDetail.errored.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.standard.state, t.versionStateDetail.standard.endTime);
this.versionDetailStackedVerticalBarChart.stackedVerticalBarChartDetailDict
.set(t.timeStamp + t.versionStateDetail.timeout.state, t.versionStateDetail.timeout.endTime);
versionDetails.push(new MultiChartData(t.timeStamp, versionLatencyStateDetails));
});
return versionDetails;
}
getVersionDetailStackedVerticalBarChart(viewVersionLatency: Array<ViewVersionLatency>) {
let viewVersionDetails = this.getversionStateDetails(viewVersionLatency);
let colorDomain = new Array("#ff6600","#1d627e", "#389ec5", "#c6efff", "#FFA1B5", "#a8385d", "#5aa454", "#f9b145");
this.versionDetailStackedVerticalBarChart = new StackedVerticalBarChart();
this.versionDetailStackedVerticalBarChart.view = [1700, 350];
this.versionDetailStackedVerticalBarChart.results = new Array();
this.versionDetailStackedVerticalBarChart.scheme.domain = colorDomain;
this.versionDetailStackedVerticalBarChart.results =
[...this.generatetVersionDetailStackedVerticalBarChartResult(viewVersionDetails)];//[...array] can dynamic change array content
}
generatetMissSlaBarChartResult(viewVersionLatency: Array<ViewVersionLatency>) {
let missSlaChartData = new Array<SingleChartData>();
if (viewVersionLatency.length == 0) {
missSlaChartData.push(new SingleChartData(Constants.none, 0));
this.missSlaBarChart.verticalBarChartDict.set(Constants.none, new ViewStateTimeStamp(Constants.none, Constants.none, Constants.none));
return missSlaChartData;
}
viewVersionLatency.forEach(t => {
this.missSlaBarChart.verticalBarChartDict.set(t.createdTimestamp, t);
missSlaChartData.push(
new SingleChartData(
t.createdTimestamp,
Number(t.totalTime)
)
)
});
return missSlaChartData;
}
getMissSlaBarChart(viewVersionLatency: Array<ViewVersionLatency>) {
let colorDomain = new Array();
viewVersionLatency.forEach(t => {
if (t.isMissSla) {
colorDomain.push("#FF0000")
}
else {
colorDomain.push("#008800")
}
})
this.missSlaBarChart = new VerticalBarChart();
this.missSlaBarChart.view = [1700, 350];
this.missSlaBarChart.legend = false;
this.missSlaBarChart.scheme.domain = colorDomain;
this.missSlaBarChart.results = this.generatetMissSlaBarChartResult(viewVersionLatency);
}
}
export class TriageViewSupervisorDto {
constructor(
public customerId?: string,
public customerEnv?: string,
public entitySpaceName?: string,
public entitySpaceViewName?: string,
public segment?: string,
public owner?: string
) { }
}
<file_sep>/src/app/core/job/job.ts
// export class Job{
// constructor(
// public id: number,
// public hostId: number,
// public type: JobType,
// public status: JobStatus,
// public submitTime?: string,
// public startTime?: string,
// public endTime?: string,
// public queueTime?: string,
// public runningTime?: string,
// public url?: string,
// public aetherExperimentId?: string,
// public completePercent?: string
// ){}
// }
export enum JobState
{
UnKnown = 0,
Waiting = 1,
Queued = 2,
Running = 3,
Succeeded = 4,
Failed = 5,
Canceled = 6,
TimeOut = 7
}
export enum JobType{
DataAnalysis = 1,
EntityViewExplorer = 2,
EntityViewStatistic = 3,
EntityViewFilter = 4,
EntityViewValidation = 5,
Triage = 6
}
export class JobPanelState{
constructor(
public isEnabled?: boolean,
public isSubmiting?: boolean,
public isRunning?: boolean,
public isCanceling?: boolean
){
this.isEnabled = true;
this.isSubmiting = false;
this.isRunning = false;
this.isCanceling = false;
}
}<file_sep>/src/app/components/viewer/viewer.service.ts
import { Injectable } from "@angular/core";
import { BaseService } from "../common/base.service";
import { HttpClient, HttpParams } from "@angular/common/http";
import { ViewerTriple } from "../../core/viewer/entityDiffViewer";
import { ViewerPayloadDiff } from "../../core/viewer/PayloadDiffViewer";
import { ViewerType } from "../../core/enums";
@Injectable()
export class ViewerService extends BaseService {
private viewerServiceUrl = `${this.serverUrl}/viewer`;
constructor(public httpClient: HttpClient) {
super(httpClient);
}
getViewerTriples(
viewerType: ViewerType,
subject1: string,
subject2: string,
standardRelativeStreamPath: string,
triagedRelativeStreamPath: string
) {
const httpParams = new HttpParams()
.set("viewerType", viewerType.toString())
.set("subject1", subject1.trim())
.set("subject2", subject2.trim())
.set("standardRelativeStreamPath", standardRelativeStreamPath.trim())
.set("triagedRelativeStreamPath", triagedRelativeStreamPath.trim());
return this.httpClient.get<ViewerTriple>(`${this.viewerServiceUrl}/entityDiff`, {
params: httpParams
});
}
getViewerPayloadDiff(
viewerType: ViewerType,
modelIdStr: string,
externalId1: string,
externalId2: string,
standardEpRelativeStreamPath: string,
triageEpRelativeStreamPath: string
) {
const httpParams = new HttpParams()
.set("viewerType", viewerType.toString())
.set("modelIdStr", modelIdStr == null ? modelIdStr : modelIdStr.trim())
.set("externalId1", externalId1.trim())
.set("externalId2", externalId2.trim())
.set("standardRelativeStreamPath", standardEpRelativeStreamPath.trim())
.set("triagedRelativeStreamPath", triageEpRelativeStreamPath.trim());
return this.httpClient.get<ViewerPayloadDiff>(`${this.viewerServiceUrl}/payloadDiff`, {
params: httpParams
});
}
}
<file_sep>/src/app/components/triage/triage.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
//routes
import { TriageRoutingModule } from './triage-routing.module';
//component
import { TriageComponent } from './triage.component';
//service
import { TriageService } from './triage.service';
//plugin
//import {SlimLoadingBarModule} from 'ng2-slim-loading-bar'
import { NgxAlertsModule } from '@ngx-plus/ngx-alerts';
import { UiSwitchModule } from 'ngx-ui-switch';
import { DiffViewerTableModule } from '../../templates/diffViewerTable/diffViewerTable.module';
import { CommonModule } from '../../../../node_modules/@angular/common';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
UiSwitchModule,
NgxAlertsModule.forRoot(),
DiffViewerTableModule,
TriageRoutingModule,
//SlimLoadingBarModule.forRoot()
],
declarations: [
TriageComponent
],
providers: [
TriageService
]
})
export class TriageModule { }
<file_sep>/src/app/components/triage/triage.component.ts
import { Component, OnInit } from '@angular/core';
// import { EntityView } from '../../core/common/entityView';
// import{ BaseComponent } from '../common/base.component'
// import { TriageService } from './triage.service';
@Component({
selector: 'triage',
templateUrl: './triage.component.html',
styleUrls: ['./triage.component.css']
})
export class TriageComponent implements OnInit {
constructor() {}
ngOnInit() { }
}<file_sep>/src/app/components/entityAnalysis/entityView/entityViewAnalysis.component.ts
import { Component, OnInit } from '@angular/core';
import { BaseComponent } from '../../common/base.component';
@Component({
selector: 'view-analysis',
templateUrl: './entityViewAnalysis.component.html',
//styleUrls: ['./name.component.css']
})
export class EntityViewAnalysisComponent extends BaseComponent implements OnInit {
constructor() {
super();
this.logger.info("entity view analysis");
}
ngOnInit() { }
}<file_sep>/src/app/components/viewer/viewer.module.ts
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpClientModule } from "@angular/common/http";
import { ViewerRoutingModule } from "./viewer-routing.module";
import { ViewerComponent } from "./viewer.component";
import { EntityDiffViewerComponent } from "./entityDiffViewer/entityDiffViewer.component";
import { ViewerService } from "./viewer.service";
import { PayloadDiffViewerComponent } from "./payloadDiffViewer/payloadDiffViewer.component";
import { DiffViewerTableModule } from "../../templates/diffViewerTable/diffViewerTable.module";
import { PayLoadDiffViewerTableModule } from "../../templates/payloadDiffViewTable/payloadDiffViewTable.module";
import { CommonModule } from "../../../../node_modules/@angular/common";
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpClientModule,
ViewerRoutingModule,
DiffViewerTableModule,
PayLoadDiffViewerTableModule
],
declarations: [
ViewerComponent,
EntityDiffViewerComponent,
PayloadDiffViewerComponent
],
providers: [
ViewerService
]
})
export class ViewerModule { }<file_sep>/deprecated/triageReportDep/triageReport.component.ts
// import { Component, OnInit, ElementRef, ViewChild } from "@angular/core";
// import { BaseComponent } from "../../common/base.component";
// import { TriageService } from "../triage.service";
// import { TriageReport, TriageAndErrorCountDetail, DurationStageDetail } from "../../../core/triage/triageReport";
// import {
// AdvancedPieChart,
// SingleChartData,
// VerticalBarChart,
// LineChart,
// GroupedVerticalBarChart,
// StackedVerticalBarChart,
// MultiChartData,
// NumberCardChart
// } from "../../../core/plugin/ngxChart";
// import { Constants } from "../../../core/common/constants";
// import { TriageStatisticComponent } from "../triageStatistic/triageStatistic.component";
// import { TriageViewSupervisor } from "../../../core/triage/triageViewSupervisor";
// import { TriageStatistic, ViewVersionDuration, DailyCount, DailyErrorTriageViewName, VersionDuration } from "../../../core/triage/triageStatistic";
// import { forEach } from "@angular/router/src/utils/collection";
// import { ReportType } from "../../../core/enums";
// import { ActivatedRoute } from "@angular/router";
// import { Location } from "@angular/common";
// import { IMyDateModel } from "ngx-mydatepicker";
// @Component({
// selector: "triage-report",
// templateUrl: "./triageReport.component.html",
// styleUrls: ["./triageReport.component.css"]
// })
// export class TriageReportComponent extends BaseComponent implements OnInit {
// @ViewChild("viewTable") viewTable: ElementRef;
// @ViewChild("topVersionDuration") topVersionDuration: ElementRef;
// @ViewChild("topCommitDuration") topCommitDuration: ElementRef;
// reportType: string;
// startDate: any;
// endDate: any;
// reportTypes: Array<string>;
// currentReportTimeSpan: string;
// currentCustomizedReportTimeSpan: string;
// currentRegularReportTimeSpan: string;
// reportTimeSpans: Array<string>;
// distributionPieChart: AdvancedPieChart;
// distributionTopTenVerticalBarChart: VerticalBarChart;
// versionDurationPieChart: AdvancedPieChart;
// versionDurationTopTenVerticalBarChart: VerticalBarChart;
// commitDurationPieChart: AdvancedPieChart;
// commitDurationTopTenVerticalBarChart: VerticalBarChart;
// triageViewSupervisors: Array<TriageViewSupervisor>;
// totalLineChart: LineChart;
// summaryNumberCardChart: NumberCardChart;
// triageAndErrorCountDetail: TriageAndErrorCountDetail;
// versionDurationStageDetail: DurationStageDetail;
// commitDurationStageDetail: DurationStageDetail;
// sortedViews: Array<SingleChartData>;
// isUrlParam: boolean;
// displayType: string;
// versionDurationRange: Array<string>;
// commitDurationRange: Array<string>;
// isFetchingReport: boolean;
// constructor(private triageService: TriageService, private route: ActivatedRoute, private location: Location) {
// super();
// }
// // ngOnInit() {
// // this.isUrlParam = false;
// // this.isFetchingReport = false;
// // this.displayType = "Regular";
// // this.reportType = ReportType[ReportType.Weekly];
// // this.reportTypes = Object.keys(ReportType).filter(t => typeof ReportType[t] === "number");
// // this.sortedViews = new Array<SingleChartData>();
// // this.triageViewSupervisors = new Array<TriageViewSupervisor>();
// // this.reportTimeSpans = new Array<string>();
// // this.summaryNumberCardChart = new NumberCardChart();
// // this.distributionPieChart = new AdvancedPieChart();
// // this.distributionTopTenVerticalBarChart = new VerticalBarChart();
// // this.versionDurationPieChart = new AdvancedPieChart();
// // this.versionDurationTopTenVerticalBarChart = new VerticalBarChart();
// // this.commitDurationPieChart = new AdvancedPieChart();
// // this.commitDurationTopTenVerticalBarChart = new VerticalBarChart();
// // this.totalLineChart = new LineChart();
// // this.triageAndErrorCountDetail = new TriageAndErrorCountDetail();
// // this.versionDurationStageDetail = new DurationStageDetail();
// // this.commitDurationStageDetail = new DurationStageDetail();
// // this.versionDurationRange = ["0~0", "0~0", "0~0"];
// // this.commitDurationRange = ["0~0", "0~0", "0~0"];
// // let reportTimeSpan = this.route.snapshot.paramMap.get("reportTimeSpan");
// // if (reportTimeSpan) {
// // this.isUrlParam = true;
// // reportTimeSpan = reportTimeSpan.replace(/_/g, "/");
// // reportTimeSpan = reportTimeSpan.replace("-", " - ");
// // this.logger.info("reportTimeSpanFromUrl", reportTimeSpan);
// // this.currentReportTimeSpan = reportTimeSpan;
// // this.currentRegularReportTimeSpan = reportTimeSpan;
// // this.triageService.getTriageReport(this.currentReportTimeSpan).subscribe(result => {
// // this.reportType = result.type;
// // this.getTriageReportTimeSpansByReportType(this.reportType, reportTimeSpan);
// // });
// // } else {
// // this.getTriageReportTimeSpansByReportType(this.reportType);
// // }
// // }
// // //#region statistic charts
// // //summart card chart
// // initSummaryNumberCardChart(triageReport: TriageReport) {
// // let colorDomain = new Array("#FFA1B5", "#a8385d", "#f2c385", "#6cc5a6", "#ed9a9a", "#3f8c85", "#1d627e");
// // this.summaryNumberCardChart = new NumberCardChart();
// // this.summaryNumberCardChart.scheme.domain = colorDomain;
// // this.summaryNumberCardChart.view = [1750, 300];
// // this.summaryNumberCardChart.cardColor = "rgba(204,228,232,0.3)";
// // let summaryData = new Array<SingleChartData>();
// // summaryData.push(new SingleChartData("TotalTriage", triageReport.triageReportSummary.triageTimes));
// // summaryData.push(new SingleChartData("TotalError", triageReport.triageReportSummary.errorTimes));
// // summaryData.push(new SingleChartData("FalseAlert", triageReport.triageReportSummary.falseAlertTimes));
// // summaryData.push(new SingleChartData("TrueAlert", triageReport.triageReportSummary.trueAlertTimes));
// // summaryData.push(
// // new SingleChartData(
// // "FalseAlertDuration",
// // Number(triageReport.triageReportSummary.averageFalseAlertDuration.toFixed(1))
// // )
// // );
// // summaryData.push(new SingleChartData("TopVersionDuration", Number(this.versionDurationRange[2].split("~")[1])));
// // summaryData.push(new SingleChartData("TopCommitDuration", Number(this.commitDurationRange[2].split("~")[1])));
// // this.summaryNumberCardChart.results = summaryData;
// // }
// // statusValueFormat(cardChartElement: any): string {
// // if (
// // cardChartElement.label == "FalseAlertDuration" ||
// // cardChartElement.label == "TopVersionDuration" ||
// // cardChartElement.label == "TopCommitDuration"
// // ) {
// // return `${cardChartElement.value} hrs`;
// // } else {
// // return `${cardChartElement.value} times`;
// // }
// // }
// // //triage and error distribution
// // generateDistributionPieChartResult(triageReport: TriageReport) {
// // let singleChartDatas = new Array<SingleChartData>();
// // let viewSum = triageReport.triageReportSummary.triageStatisticsCount;
// // let triageAndErrorSum = triageReport.triageReportDetail.triageViewSupervisors.length;
// // let normalSum = viewSum - triageAndErrorSum;
// // let errorSum = 0;
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.triageAndErrorDistribution.totalErrorCount != 0) {
// // errorSum++;
// // }
// // });
// // this.triageAndErrorCountDetail = new TriageAndErrorCountDetail(
// // triageAndErrorSum - errorSum,
// // errorSum,
// // viewSum - triageAndErrorSum,
// // viewSum
// // );
// // singleChartDatas.push(new SingleChartData("triaged", this.triageAndErrorCountDetail.triageCount));
// // singleChartDatas.push(new SingleChartData("error", this.triageAndErrorCountDetail.errorCount));
// // singleChartDatas.push(new SingleChartData("normal", this.triageAndErrorCountDetail.normalCount));
// // return singleChartDatas;
// // }
// // initDistributionPieChart(triageReport: TriageReport) {
// // this.logger.info("initDistributionPieChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#FFA1B5", "#a8385d", "#e6ecef");
// // this.distributionPieChart = new AdvancedPieChart();
// // this.distributionPieChart.scheme.domain = colorDomain;
// // this.distributionPieChart.view = [700, 400];
// // this.distributionPieChart.animations = false;
// // this.distributionPieChart.results = this.generateDistributionPieChartResult(triageReport);
// // }
// // generatedistributionTopTenVerticalBarChartResult(triageReport: TriageReport) {
// // let singleChartDatas = new Array<SingleChartData>();
// // this.logger.info(
// // "triageReport.triageReportSummary.triageStatistics",
// // triageReport.triageReportSummary.triageStatistics
// // );
// // if (triageReport.triageReportSummary.triageStatistics.length == 0) {
// // singleChartDatas.push(new SingleChartData("none", 0));
// // return singleChartDatas;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.triageAndErrorDistribution.totalErrorCount + t.triageAndErrorDistribution.totalTriageCount != 0) {
// // singleChartDatas.push(
// // new SingleChartData(
// // t.entitySpaceViewName,
// // t.triageAndErrorDistribution.totalErrorCount + t.triageAndErrorDistribution.totalTriageCount
// // )
// // );
// // }
// // });
// // this.sortedViews = singleChartDatas.sort((a, b) => b.value - a.value);
// // singleChartDatas = singleChartDatas.sort((a, b) => b.value - a.value).slice(0, Constants.topTen);
// // return singleChartDatas;
// // }
// // initDistributionVerticalBarChart(triageReport: TriageReport) {
// // this.logger.info("initDistributionVerticalBarChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#FFA1B5");
// // this.distributionTopTenVerticalBarChart = new VerticalBarChart();
// // this.distributionTopTenVerticalBarChart.scheme.domain = colorDomain;
// // this.distributionTopTenVerticalBarChart.view = [970, 300];
// // this.distributionTopTenVerticalBarChart.showYAxisLabel = false;
// // this.distributionTopTenVerticalBarChart.legend = false;
// // this.distributionTopTenVerticalBarChart.showXAxisLabel = false;
// // this.distributionTopTenVerticalBarChart.animations = false;
// // this.distributionTopTenVerticalBarChart.results = this.generatedistributionTopTenVerticalBarChartResult(
// // triageReport
// // );
// // }
// // //version duration
// // generateVersionDurationPieChartResult(triageReport: TriageReport) {
// // let singleChartDatasOfChart = new Array<SingleChartData>();
// // let highDurationViews: number = 0;
// // let middleDurationViews: number = 0;
// // let lowDurationViews: number = 0;
// // let averageDuration: number = 0;
// // let averageDurationOfHigh: number = 0;
// // let averageDurationOfLow: number = 0;
// // let maxDurationOfAll: number = 0;
// // let minDurationOfAll: number = 10000;
// // let allViewVersionDurationsLength = triageReport.triageReportSummary.triageStatisticsCount;
// // let lowRange = new Array();
// // let middleRange = new Array();
// // let highRange = new Array();
// // if (allViewVersionDurationsLength == 0) {
// // singleChartDatasOfChart.push(new SingleChartData("none", 0));
// // return singleChartDatasOfChart;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.versionDuration.averageDuration == "NaN") {
// // t.versionDuration.averageDuration = "0";
// // }
// // averageDuration += Number(t.versionDuration.averageDuration) / allViewVersionDurationsLength;
// // if (Number(t.versionDuration.averageDuration) > maxDurationOfAll) {
// // maxDurationOfAll = Number(t.versionDuration.averageDuration);
// // }
// // if (Number(t.versionDuration.averageDuration) < minDurationOfAll) {
// // minDurationOfAll = Number(t.versionDuration.averageDuration);
// // }
// // });
// // averageDurationOfHigh = (averageDuration + maxDurationOfAll) / 2;
// // averageDurationOfLow = (averageDuration + minDurationOfAll) / 2;
// // lowRange = [minDurationOfAll.toFixed(1), averageDurationOfLow.toFixed(1)];
// // middleRange = [averageDurationOfLow.toFixed(1), averageDurationOfHigh.toFixed(1)];
// // highRange = [averageDurationOfHigh.toFixed(1), maxDurationOfAll.toFixed(1)];
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.versionDuration.averageDuration == "NaN") {
// // t.versionDuration.averageDuration = "0";
// // }
// // if (
// // Number(t.versionDuration.averageDuration) <= maxDurationOfAll &&
// // Number(t.versionDuration.averageDuration) > averageDurationOfHigh
// // ) {
// // highDurationViews++;
// // } else if (
// // Number(t.versionDuration.averageDuration) >= minDurationOfAll &&
// // Number(t.versionDuration.averageDuration) < averageDurationOfLow
// // ) {
// // lowDurationViews++;
// // } else {
// // middleDurationViews++;
// // }
// // });
// // singleChartDatasOfChart = [
// // new SingleChartData("Low", lowDurationViews),
// // new SingleChartData("Middle", middleDurationViews),
// // new SingleChartData("High", highDurationViews)
// // ];
// // this.versionDurationPieChart.pieChartDetailLayerValueDict.set("Low", lowRange);
// // this.versionDurationPieChart.pieChartDetailLayerValueDict.set("Middle", middleRange);
// // this.versionDurationPieChart.pieChartDetailLayerValueDict.set("High", highRange);
// // this.versionDurationStageDetail = new DurationStageDetail(
// // highDurationViews,
// // middleDurationViews,
// // lowDurationViews
// // );
// // this.versionDurationRange = [
// // lowRange[0] + "~" + lowRange[1],
// // middleRange[0] + "~" + middleRange[1],
// // highRange[0] + "~" + highRange[1]
// // ];
// // return singleChartDatasOfChart;
// // }
// // initVersionDurationPieChart(triageReport: TriageReport) {
// // this.logger.info("initVersionDurationPieChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#d1f1ed", "#6dc8c0", "#3f8c85");
// // this.versionDurationPieChart = new AdvancedPieChart();
// // this.versionDurationPieChart.scheme.domain = colorDomain;
// // this.versionDurationPieChart.view = [700, 400];
// // this.versionDurationPieChart.animations = false;
// // this.versionDurationPieChart.results = this.generateVersionDurationPieChartResult(triageReport);
// // }
// // generateVersionDurationTopTenVerticalBarChartResult(triageReport: TriageReport) {
// // let singleChartDatas = new Array<SingleChartData>();
// // if (triageReport.triageReportSummary.triageStatistics.length == 0) {
// // singleChartDatas.push(new SingleChartData("none", 0));
// // return singleChartDatas;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // singleChartDatas.push(
// // new SingleChartData(t.entitySpaceViewName, Number(Number(t.versionDuration.averageDuration).toFixed(1)))
// // );
// // });
// // singleChartDatas = singleChartDatas.sort((a, b) => b.value - a.value).slice(0, Constants.topTen);
// // return singleChartDatas;
// // }
// // initVersionDurationVerticalBarChart(triageReport: TriageReport) {
// // this.logger.info("initVersionDurationVerticalBarChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#6dc8c0");
// // this.versionDurationTopTenVerticalBarChart = new VerticalBarChart();
// // this.versionDurationTopTenVerticalBarChart.scheme.domain = colorDomain;
// // this.versionDurationTopTenVerticalBarChart.view = [970, 300];
// // this.versionDurationTopTenVerticalBarChart.legend = false;
// // this.versionDurationTopTenVerticalBarChart.showXAxisLabel = false;
// // this.versionDurationTopTenVerticalBarChart.showYAxisLabel = false;
// // this.versionDurationTopTenVerticalBarChart.animations = false;
// // this.versionDurationTopTenVerticalBarChart.results = this.generateVersionDurationTopTenVerticalBarChartResult(
// // triageReport
// // );
// // }
// // //commit duration
// // generateCommitDurationPieChartResult(triageReport: TriageReport) {
// // let singleChartDatasOfChart = new Array<SingleChartData>();
// // let highDurationViews: number = 0;
// // let middleDurationViews: number = 0;
// // let lowDurationViews: number = 0;
// // let averageDuration: number = 0;
// // let averageDurationOfHigh: number = 0;
// // let averageDurationOfLow: number = 0;
// // let maxDurationOfAll: number = 0;
// // let minDurationOfAll: number = 10000;
// // let allViewtriageCommitDurationsLength = triageReport.triageReportSummary.triageStatisticsCount;
// // let lowRange = new Array();
// // let middleRange = new Array();
// // let highRange = new Array();
// // if (allViewtriageCommitDurationsLength == 0) {
// // singleChartDatasOfChart.push(new SingleChartData("none", 0));
// // return singleChartDatasOfChart;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.triageCommitDuration.averageDuration == "NaN") {
// // t.triageCommitDuration.averageDuration = "0";
// // }
// // averageDuration += Number(t.triageCommitDuration.averageDuration) / allViewtriageCommitDurationsLength;
// // if (Number(t.triageCommitDuration.averageDuration) > maxDurationOfAll) {
// // maxDurationOfAll = Number(t.triageCommitDuration.averageDuration);
// // }
// // if (Number(t.triageCommitDuration.averageDuration) < minDurationOfAll) {
// // minDurationOfAll = Number(t.triageCommitDuration.averageDuration);
// // }
// // });
// // averageDurationOfHigh = (averageDuration + maxDurationOfAll) / 2;
// // averageDurationOfLow = (averageDuration + minDurationOfAll) / 2;
// // lowRange = [minDurationOfAll.toFixed(1), averageDurationOfLow.toFixed(1)];
// // middleRange = [averageDurationOfLow.toFixed(1), averageDurationOfHigh.toFixed(1)];
// // highRange = [averageDurationOfHigh.toFixed(1), maxDurationOfAll.toFixed(1)];
// // this.logger.info("lowRange", lowRange);
// // this.logger.info("middleRange", middleRange);
// // this.logger.info("highRange", highRange);
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.triageCommitDuration.averageDuration == "NaN") {
// // t.triageCommitDuration.averageDuration = "0";
// // }
// // if (
// // Number(t.triageCommitDuration.averageDuration) <= maxDurationOfAll &&
// // Number(t.triageCommitDuration.averageDuration) > averageDurationOfHigh
// // ) {
// // highDurationViews++;
// // } else if (
// // Number(t.triageCommitDuration.averageDuration) >= minDurationOfAll &&
// // Number(t.triageCommitDuration.averageDuration) < averageDurationOfLow
// // ) {
// // lowDurationViews++;
// // } else {
// // middleDurationViews++;
// // }
// // });
// // singleChartDatasOfChart = [
// // new SingleChartData("Low", lowDurationViews),
// // new SingleChartData("Middle", middleDurationViews),
// // new SingleChartData("High", highDurationViews)
// // ];
// // this.commitDurationPieChart.pieChartDetailLayerValueDict.set("Low", lowRange);
// // this.commitDurationPieChart.pieChartDetailLayerValueDict.set("Middle", middleRange);
// // this.commitDurationPieChart.pieChartDetailLayerValueDict.set("High", highRange);
// // this.commitDurationStageDetail = new DurationStageDetail(
// // highDurationViews,
// // middleDurationViews,
// // lowDurationViews
// // );
// // this.commitDurationRange = [
// // lowRange[0] + "~" + lowRange[1],
// // middleRange[0] + "~" + middleRange[1],
// // highRange[0] + "~" + highRange[1]
// // ];
// // return singleChartDatasOfChart;
// // }
// // initCommitDurationPieChart(triageReport: TriageReport) {
// // this.logger.info("initCommitDurationPieChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#c6efff", "#389ec5", "#1d627e");
// // this.commitDurationPieChart = new AdvancedPieChart();
// // this.commitDurationPieChart.scheme.domain = colorDomain;
// // this.commitDurationPieChart.view = [700, 400];
// // this.commitDurationPieChart.animations = false;
// // this.commitDurationPieChart.results = this.generateCommitDurationPieChartResult(triageReport);
// // }
// // generateCommitDurationTopTenVerticalBarChartResult(triageReport: TriageReport) {
// // let singleChartDatas = new Array<SingleChartData>();
// // if (triageReport.triageReportSummary.triageStatistics.length == 0) {
// // singleChartDatas.push(new SingleChartData("none", 0));
// // return singleChartDatas;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // singleChartDatas.push(
// // new SingleChartData(
// // t.entitySpaceViewName,
// // Number(Number(t.triageCommitDuration.averageDuration).toFixed(1))
// // )
// // );
// // });
// // singleChartDatas = singleChartDatas.sort((a, b) => b.value - a.value).slice(0, Constants.topTen);
// // return singleChartDatas;
// // }
// // initCommitDurationVerticalBarChart(triageReport: TriageReport) {
// // this.logger.info("initCommitDurationVerticalBarChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#389ec5");
// // this.commitDurationTopTenVerticalBarChart = new VerticalBarChart();
// // this.commitDurationTopTenVerticalBarChart.scheme.domain = colorDomain;
// // this.commitDurationTopTenVerticalBarChart.view = [970, 300];
// // this.commitDurationTopTenVerticalBarChart.legend = false;
// // this.commitDurationTopTenVerticalBarChart.showXAxisLabel = false;
// // this.commitDurationTopTenVerticalBarChart.showYAxisLabel = false;
// // this.commitDurationTopTenVerticalBarChart.animations = false;
// // this.commitDurationTopTenVerticalBarChart.results = this.generateCommitDurationTopTenVerticalBarChartResult(
// // triageReport
// // );
// // }
// // generateTotalLineChartResult(triageReport: TriageReport) {
// // let dailyCounts = new Array<DailyCount>();
// // let multiChartData: MultiChartData = new MultiChartData();
// // let multiChartDatas = new Array<MultiChartData>();
// // let errorTriageViewNames = new Array<DailyErrorTriageViewName>();
// // if (triageReport.triageReportSummary.triageStatistics.length == 0) {
// // multiChartDatas.push(new MultiChartData("none", [new SingleChartData("none", 0)]));
// // this.totalLineChart.lineChartDetailDict.set(multiChartDatas[0].name + "none", new Set<string>());
// // return multiChartDatas;
// // }
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // t.triageAndErrorDistribution.triageAndErrors.forEach(e => {
// // dailyCounts.push(new DailyCount(t.entitySpaceViewName, e.date, e.errorCount, e.triageCount));
// // });
// // });
// // multiChartDatas[0] = new MultiChartData("error");
// // multiChartDatas[1] = new MultiChartData("triage");
// // if (dailyCounts.length == 0) {
// // multiChartDatas[0] = new MultiChartData("no error", [new SingleChartData("none", 0)]);
// // multiChartDatas[1] = new MultiChartData("no triage", [new SingleChartData("none", 0)]);
// // }
// // dailyCounts.forEach(d => {
// // for (let i = 0; i < Constants.monthDays; i++) {
// // if (!multiChartDatas[0].series[i]) {
// // multiChartDatas[0].series[i] = new SingleChartData(d.date, d.errorCount);
// // multiChartDatas[1].series[i] = new SingleChartData(d.date, d.triageCount);
// // errorTriageViewNames[i] = new DailyErrorTriageViewName(d.date);
// // if (d.errorCount > 0) {
// // errorTriageViewNames[i].errorViewNames.add(d.viewName);
// // }
// // if (d.triageCount > 0) {
// // errorTriageViewNames[i].triageViewNames.add(d.viewName);
// // }
// // break;
// // } else if (multiChartDatas[0].series[i].name == d.date) {
// // if (d.errorCount > 0) {
// // multiChartDatas[0].series[i].value++;
// // errorTriageViewNames[i].errorViewNames.add(d.viewName);
// // }
// // if (d.triageCount > 0) {
// // multiChartDatas[1].series[i].value++;
// // errorTriageViewNames[i].triageViewNames.add(d.viewName);
// // }
// // break;
// // }
// // }
// // });
// // errorTriageViewNames.forEach(e => {
// // this.totalLineChart.lineChartDetailDict.set(e.date + "error", e.errorViewNames);
// // this.totalLineChart.lineChartDetailDict.set(e.date + "triage", e.triageViewNames);
// // });
// // return multiChartDatas;
// // }
// // initTotalLineChart(triageReport: TriageReport) {
// // this.logger.info("initTotalLineChart", triageReport.reportTimeSpan);
// // let colorDomain = new Array("#a8385d", "#FFA1B5");
// // this.totalLineChart = new LineChart();
// // this.totalLineChart.scheme.domain = colorDomain;
// // this.totalLineChart.view = [1700, 400];
// // this.totalLineChart.results = this.generateTotalLineChartResult(triageReport);
// // }
// // //#endregion
// // //#region detail
// // initViewDetail(triageReport: TriageReport) {
// // let sortedTriageViewSupervisors = new Array<TriageViewSupervisor>();
// // this.triageViewSupervisors = new Array<TriageViewSupervisor>();
// // triageReport.triageReportDetail.triageViewSupervisors.forEach(t => {
// // this.addTriageView(t);
// // });
// // this.logger.info("unorder", this.triageViewSupervisors);
// // for (let i = 0; i < this.sortedViews.length; i++) {
// // this.triageViewSupervisors.forEach(t => {
// // if (t.entitySpaceViewName == this.sortedViews[i].name) {
// // sortedTriageViewSupervisors.push(t);
// // }
// // });
// // }
// // this.triageViewSupervisors = sortedTriageViewSupervisors;
// // this.logger.info("ordered", this.triageViewSupervisors);
// // this.logger.info("order", this.sortedViews);
// // }
// // addTriageView(triageViewSupervisor: TriageViewSupervisor) {
// // this.triageViewSupervisors.push(
// // new TriageViewSupervisor(
// // triageViewSupervisor.id,
// // triageViewSupervisor.triageAnalysisId,
// // triageViewSupervisor.customerId,
// // triageViewSupervisor.customerEnv,
// // triageViewSupervisor.entitySpaceName,
// // triageViewSupervisor.entitySpaceViewName,
// // triageViewSupervisor.segment,
// // triageViewSupervisor.currentState,
// // triageViewSupervisor.originalState,
// // triageViewSupervisor.latestVersion,
// // triageViewSupervisor.latestVersionState,
// // triageViewSupervisor.latestCompletedVersion,
// // triageViewSupervisor.latestCompletedVersionState,
// // triageViewSupervisor.latestSucceedTime,
// // triageViewSupervisor.latestVersionLatency,
// // triageViewSupervisor.latestSucceedVersionLatency,
// // triageViewSupervisor.latestStandardVersion,
// // triageViewSupervisor.latestJobType,
// // triageViewSupervisor.deletedCount,
// // triageViewSupervisor.addedCount,
// // triageViewSupervisor.churnedCount,
// // triageViewSupervisor.owner,
// // triageViewSupervisor.tfsUrl
// // )
// // );
// // }
// // getViewStatistic(id: number, triageReport: TriageReport) {
// // let triageStatistic = new TriageStatistic();
// // triageReport.triageReportSummary.triageStatistics.forEach(t => {
// // if (t.supervisorId == id) {
// // triageStatistic = t;
// // }
// // });
// // return triageStatistic;
// // }
// // expandStatistic(triageViewSupervisor: TriageViewSupervisor) {
// // triageViewSupervisor.expandStatistic = !triageViewSupervisor.expandStatistic;
// // if (triageViewSupervisor.expandStatistic && triageViewSupervisor.versionDelayLineChart.results.length == 0) {
// // this.triageService.getTriageReport(this.currentReportTimeSpan).subscribe(result => {
// // let viewStatistic = this.getViewStatistic(triageViewSupervisor.id, result);
// // triageViewSupervisor.getVersionDelayLineChart(viewStatistic.versionDuration);
// // triageViewSupervisor.getVersionDelayStackedVerticalBarChart(viewStatistic.versionDuration);
// // triageViewSupervisor.getCommitDelayLineChart(viewStatistic.triageCommitDuration);
// // triageViewSupervisor.getMonthlyCountLineChart(viewStatistic.triageAndErrorDistribution);
// // });
// // }
// // }
// // //#endregion
// // //#region get report
// // changeReportTimeSpan(reportTimeSpan: string) {
// // this.currentReportTimeSpan = reportTimeSpan;
// // this.currentRegularReportTimeSpan = this.currentReportTimeSpan;
// // this.generateTriageReport(reportTimeSpan);
// // this.logger.info("changeReportTimeSpan", this.currentReportTimeSpan);
// // }
// // getLastSeveraldayReport(daysCount: number) {
// // let today = new Date();
// // let utcTodayTime = Date.UTC(
// // today.getUTCFullYear(),
// // today.getUTCMonth(),
// // today.getUTCDate(),
// // today.getUTCHours(),
// // today.getUTCMinutes(),
// // today.getUTCSeconds()
// // );
// // let pastDayTime = utcTodayTime - 1000 * 60 * 60 * 24 * daysCount; //1,000 ms * 60 s * 60 mins * 24 hrs * daysCount
// // let pastDay = new Date(pastDayTime);
// // this.startDate = {
// // date: {
// // year: pastDay.getUTCFullYear(),
// // month: Number(pastDay.getUTCMonth() + 1),
// // day: pastDay.getUTCDate()
// // }
// // };
// // this.endDate = {
// // date: { year: today.getUTCFullYear(), month: Number(today.getUTCMonth() + 1), day: today.getUTCDate() }
// // };
// // this.generateCustomizedTriageReport();
// // }
// // compareTimeSpan(timeSpan1: string, timeSpan2: string) {
// // let startTime1 = timeSpan1.split(" - ")[0];
// // let startTimeArray1 = startTime1.split("/");
// // let startTimeNum1 =
// // parseInt(startTimeArray1[2]) * 10000 + parseInt(startTimeArray1[0]) * 100 + parseInt(startTimeArray1[1]);
// // let startTime2 = timeSpan2.split(" - ")[0];
// // let startTimeArray2 = startTime2.split("/");
// // let startTimeNum2 =
// // parseInt(startTimeArray2[2]) * 10000 + parseInt(startTimeArray2[0]) * 100 + parseInt(startTimeArray2[1]);
// // return startTimeNum2 - startTimeNum1;
// // }
// // getTriageReportTimeSpansByReportType(reportType: string, reportTimeSpan?: string) {
// // this.triageService.getTriageReportTimeSpansByReportType(reportType).subscribe(result => {
// // this.reportTimeSpans = result.sort((a, b) => {
// // return this.compareTimeSpan(a, b);
// // });
// // if (this.reportTimeSpans.length != 0) {
// // //if there is a param form url, generate report of this param
// // let initReportTimeSpan = reportTimeSpan == null ? this.reportTimeSpans[0] : reportTimeSpan;
// // this.changeReportTimeSpan(initReportTimeSpan);
// // }
// // this.reportType = reportType;
// // });
// // }
// // generateCustomizedTriageReport() {
// // this.isFetchingReport = true;
// // //report timespan format: month/day/year
// // let startDate: string =
// // this.startDate.date.month + "/" + this.startDate.date.day + "/" + this.startDate.date.year;
// // let endDate: string = this.endDate.date.month + "/" + this.endDate.date.day + "/" + this.endDate.date.year;
// // this.currentReportTimeSpan = startDate + " - " + endDate;
// // this.generateTriageReport(this.currentReportTimeSpan);
// // }
// // generateRegularTriageReport() {
// // this.currentReportTimeSpan = this.currentRegularReportTimeSpan;
// // this.generateTriageReport(this.currentReportTimeSpan);
// // }
// // generateTriageReport(reportTimeSpan: string) {
// // this.triageService.getTriageReport(reportTimeSpan).subscribe(result => {
// // this.initCharts(result);
// // this.isFetchingReport = false;
// // this.changeUrl();
// // this.logger.info("current report", result);
// // });
// // this.logger.info("generateTriageReport", this.currentReportTimeSpan);
// // }
// // initCharts(result: TriageReport) {
// // this.initDistributionPieChart(result);
// // this.initDistributionVerticalBarChart(result);
// // this.initVersionDurationPieChart(result);
// // this.initVersionDurationVerticalBarChart(result);
// // this.initCommitDurationPieChart(result);
// // this.initCommitDurationVerticalBarChart(result);
// // this.initSummaryNumberCardChart(result);
// // this.initViewDetail(result);
// // this.initTotalLineChart(result);
// // }
// // changeUrl() {
// // //change the url without redirction
// // if (this.isUrlParam) {
// // let urlReportTimeSpan = this.currentReportTimeSpan.replace(new RegExp("/", "g"), "_");
// // urlReportTimeSpan = urlReportTimeSpan.replace(" - ", "-");
// // this.location.replaceState("triage/report/" + urlReportTimeSpan);
// // }
// // this.isUrlParam = true;
// // }
// // //#endregion
// // //#region scroll
// // scrollToViewDetail(event: any) {
// // let id: number = 0;
// // let index: number = 0;
// // this.triageViewSupervisors.forEach((t, i) => {
// // if (t.entitySpaceViewName == event.name) {
// // id = t.id;
// // index = i;
// // this.expandStatistic(t);
// // } else {
// // t.expandStatistic = false;
// // }
// // });
// // let viewTableHeight = this.viewTable.nativeElement.offsetTop + 20;
// // viewTableHeight = viewTableHeight + index * 40;
// // window.scrollTo(0, viewTableHeight);
// // }
// // summaryCardScrollToDetail(event: any) {
// // let topVersionDurationHeight = this.topVersionDuration.nativeElement.offsetTop;
// // let topCommitDurationHeight = this.topCommitDuration.nativeElement.offsetTop;
// // if (event.name == "TopVersionDuration") {
// // window.scrollTo(0, topVersionDurationHeight);
// // } else if (event.name == "TopCommitDuration") {
// // window.scrollTo(0, topCommitDurationHeight);
// // }
// // }
// // //#endregion
// // //#region get previous and get next report
// // getPreReport() {
// // let index: number = 0;
// // for (let i = 0; i < this.reportTimeSpans.length; i++) {
// // if (this.reportTimeSpans[i] == this.currentRegularReportTimeSpan) {
// // index = i;
// // }
// // }
// // index = index == this.reportTimeSpans.length - 1 ? 0 : index + 1;
// // this.changeReportTimeSpan(this.reportTimeSpans[index]);
// // }
// // getNextReport() {
// // let index: number = 0;
// // for (let i = 0; i < this.reportTimeSpans.length; i++) {
// // if (this.reportTimeSpans[i] == this.currentRegularReportTimeSpan) {
// // index = i;
// // }
// // }
// // index = index == 0 ? 0 : index - 1;
// // this.changeReportTimeSpan(this.reportTimeSpans[index]);
// // }
// // //#endregion
// }
|
12efcf93001058ec8ff37725ff0b7d9feebd8896
|
[
"JavaScript",
"TypeScript",
"Text"
] | 85
|
TypeScript
|
hulihuli/webpackOnboardingTool
|
030ba4972a411ca5a59b20c0ed92d6740aecdbc2
|
dd948c2d840c2a07b3f12d7260705eb499e419e9
|
refs/heads/main
|
<file_sep>package com.example.lec26;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=findViewById(R.id.btn1);
btn2=findViewById(R.id.btn2);
btn3=findViewById(R.id.btn3);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new Fragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment1, fragment);
transaction.commit();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new Fragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment1, fragment);
transaction.commit();
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new Fragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment1, fragment);
transaction.commit();
}
});
}
}
|
9b66e4280f06751c357c4607ce645c21513652a9
|
[
"Java"
] | 1
|
Java
|
kamrandestgir/Lec26
|
c8a146ba019e3f82c7378910708b187231cd817a
|
6e3add896395b30abf6642045411a143df41fc2c
|
refs/heads/master
|
<file_sep>package com.cc.jcg.examples.gen;
import com.cc.jcg.MGenerated;
@MGenerated
public enum SomeEnum
implements SomeInterface {
V01,
V02;
}
<file_sep>package com.cc.jcg.bean;
import java.util.Collection;
public interface MBFieldRefCollectionSetter<BT, VT>
extends MBFieldCollectionSetter<BT, VT>, MBRef<MBBeanMeta<VT>> {
@Override
void setValue(BT bean, Collection<VT> values);
}
<file_sep>package com.cc.jcg.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
public class CopyReplacing
implements Callable<File> {
private final File input;
private final File output;
private final Map<String, String> map;
public CopyReplacing(File input, File output, Map<String, String> map) {
super();
this.input = input;
this.output = output;
this.map = map;
}
public CopyReplacing(File input, File output, File propertiesFile) throws FileNotFoundException, IOException {
super();
this.input = input;
this.output = output;
map = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream(propertiesFile));
loadProperties(properties);
}
public CopyReplacing(File input, File output, Properties properties) {
super();
this.input = input;
this.output = output;
map = new HashMap<String, String>();
loadProperties(properties);
}
protected void loadProperties(Properties properties) {
for (Object key : properties.keySet()) {
if (key instanceof String) {
map.put((String) key, properties.getProperty((String) key));
}
}
}
@Override
public File call() throws Exception {
new EncodedFileWriter(output) {
@Override
protected void writing() throws Exception {
new EncodedFileReader(input) {
@Override
protected void onLine(String line) throws Exception {
for (String key : map.keySet()) {
line = line.replace(key, map.get(key));
}
if (doWriteLine(line)) {
writeLine(line);
} else {
String replacement = getLineReplacement();
if (replacement != null) {
writeLine(replacement);
}
}
}
}.call();
}
}.call();
return output;
}
protected String getLineReplacement() {
return null;
}
protected boolean doWriteLine(String line) {
return true;
}
}
<file_sep>package com.example;
import com.cc.jcg.MGenerated;
@MGenerated
public enum MyEnum {
}
<file_sep>package com.example;
import com.cc.jcg.MGenerated;
@MGenerated
public class SubclassExample
extends Example {
protected SubclassExample(String name) {
super(name);
}
}
<file_sep>package com.cc.jcg.bean;
public interface MBFieldSetter<BT, VT>
extends MBFieldDef<BT> {
Class<VT> getType();
void setValue(BT bean, VT value);
}
<file_sep>package com.cc.jcg.bean.example.gen;
import com.cc.jcg.MGenerated;
import com.cc.jcg.bean.MBBeanMetaBase;
import com.cc.jcg.bean.MBField;
import com.cc.jcg.bean.MBFieldCollection;
import com.cc.jcg.bean.example.ExampleBeanB;
import com.cc.jcg.bean.example.PrototypeBeanMeta;
import java.util.Calendar;
@MGenerated
public final class ExampleBeanBMeta
extends MBBeanMetaBase<ExampleBeanB> {
public static ExampleBeanBMeta getInstance() {
if (getBeanMeta("com.acer.jmdsl.bean.example.gen.ExampleBeanBMeta") == null) {
registerBeanMeta(new ExampleBeanBMeta());
}
return getBeanMeta("com.acer.jmdsl.bean.example.gen.ExampleBeanBMeta");
}
public final MBField<ExampleBeanB, String> name = newField(String.class, "name");
public final MBField<ExampleBeanB, Calendar> calendar = newField(Calendar.class, "calendar");
public final MBField<ExampleBeanB, PrototypeBeanMeta> back = newField(PrototypeBeanMeta.class, "back");
public final MBFieldCollection<ExampleBeanB, PrototypeBeanMeta> backs = newFieldCollection(PrototypeBeanMeta.class, "backs");
private ExampleBeanBMeta() {
super(ExampleBeanB.class);
addFieldMeta(name);
addFieldMeta(calendar);
addFieldMeta(back);
addFieldMeta(backs);
}
}
<file_sep>package com.cc.jcg.bean;
import java.util.Collection;
public interface MBFieldCollectionSetter<BT, VT>
extends MBFieldSetter<BT, Collection<VT>> {
@Override
Class<Collection<VT>> getType();
@Override
void setValue(BT bean, Collection<VT> values);
}
<file_sep>package com.cc.jcg;
import java.util.TreeSet;
public class MField
extends MAnnotated<MField>
implements MCode<MField> {
public enum MFieldModifier implements MModifier {
PUBLIC, PROTECTED, PRIVATE, DEFAULT;
}
public final MField makePublic() {
return setModifier(MFieldModifier.PUBLIC);
}
public final MField makeProtected() {
return setModifier(MFieldModifier.PROTECTED);
}
public final MField makePrivate() {
return setModifier(MFieldModifier.PRIVATE);
}
public final MField makePrivateFinal() {
return makePrivate().setFinal(true);
}
public final MField makeDefault() {
return setModifier(MFieldModifier.DEFAULT);
}
private final MConstructable container;
private final String name;
private final MTypeRef type;
private MFieldModifier modifier;
private boolean isFinal;
private boolean isStatic;
private String generic;
private MCodeGenerator<MField> generator;
private String value;
MField(MConstructable container, Class<?> type, String name) {
this(container, new MTypeRefJava(type), name);
}
MField(MConstructable container, MType type, String name) {
this(container, new MTypeRefModel(type), name);
}
MField(MConstructable container, String genericType, String name) {
super();
this.container = container;
type = null;
this.name = name;
isFinal = false;
modifier = MFieldModifier.PRIVATE;
generator = this;
isStatic = false;
value = null;
generic = genericType;
}
MField(MConstructable container, MTypeRef type, String name) {
super();
this.container = container;
this.type = type;
this.name = name;
isFinal = false;
modifier = MFieldModifier.PRIVATE;
generator = this;
isStatic = false;
value = null;
setGeneric("");
}
public final <T extends MConstructable> T getOwner() {
return (T) container;
}
public final MTypeRef getType() {
return type;
}
public synchronized final String getGeneric() {
return generic;
}
public synchronized final MField setGeneric(String generic) {
this.generic = MFunctions.getBrackedGeneric(generic);
return this;
}
public final String getName() {
return name;
}
public final synchronized boolean isFinal() {
return isFinal;
}
public final synchronized MField setFinal(boolean isFinal) {
this.isFinal = isFinal;
return this;
}
public final synchronized boolean isStatic() {
return isStatic;
}
public final synchronized void setStatic(boolean isStatic) {
this.isStatic = isStatic;
}
public final synchronized MFieldModifier getModifier() {
return modifier;
}
public final synchronized MField setModifier(MFieldModifier modifier) {
this.modifier = modifier;
return this;
}
public final synchronized MField setValue(String value) {
this.value = value;
return this;
}
@Override
public final String getPackageName() {
return container.getPackageName();
}
@Override
public final void addImport(Class<?> type) {
container.addImport(type);
}
@Override
public final void addImport(MTypeRef ref) {
container.addImport(ref);
}
@Override
public final void addImport(String fullname) {
container.addImport(fullname);
}
@Override
public final void addImport(MType type) {
addImport(new MTypeRefModel(type));
}
@Override
public final TreeSet<String> getImports() {
TreeSet<String> all = super.getImports();
return all;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MField [container=");
builder.append(container);
if (type != null) {
builder.append(", type=");
builder.append(type.getSimpleName().concat(generic));
} else {
builder.append(", generic=");
builder.append(generic);
}
builder.append(", name=");
builder.append(name);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (container == null ? 0 : container.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MField other = (MField) obj;
if (container == null) {
if (other.container != null) {
return false;
}
} else if (!container.equals(other.container)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@SuppressWarnings("unused")
private String onEmptyNoSpace(MCodeBlock code) {
return code.getLines().isEmpty() ? "" : " ";
}
private String onEmptyNoSpace(StringBuffer sb) {
return sb.length() == 0 || sb.charAt(sb.length() - 1) == '\n' ? "" : " ";
}
@Override
public final synchronized MCodeBlock getCodeBlock(MField element) {
StringBuffer line = new StringBuffer();
appendAnnotation(line);
line.append(modifier.equals(MFieldModifier.DEFAULT) ? "" : modifier.name().toLowerCase());
line.append(isStatic ? onEmptyNoSpace(line) + "static" : "");
line.append(isFinal ? onEmptyNoSpace(line) + "final" : "");
if (type != null) {
line.append(onEmptyNoSpace(line) + type.getSimpleName().concat(generic));
} else {
line.append(onEmptyNoSpace(line) + generic);
}
line.append(" ");
line.append(name);
if (value != null) {
line.append(" = ");
line.append(value);
}
if (!line.toString().trim().endsWith(";")) {
line.append(";");
}
MCodeBlock block = new MCodeBlock();
block.addLine(line);
block.decrementTabs();
return block;
}
@Override
public final synchronized MField setGenerator(MCodeGenerator<MField> generator) {
this.generator = generator;
return this;
}
@Override
public final synchronized MCodeGenerator<MField> getGenerator() {
return generator;
}
public final MMethod addGetterMethod() {
return addGetterMethod(MFunctions.getterMethodName(type, name), true);
}
public final MMethod addGetterMethod(String name, boolean isSynchronized) {
final MMethod method;
if (type != null) {
container.addExtraImport(type);
method = container.addMethod(name, type, generic).setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock code = element.getCodeBlock(element);
code.addLine("return " + MField.this.getName() + ";");
return code;
}
});
} else {
method = container.addMethod(name, generic).setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock code = element.getCodeBlock(element);
code.addLine("return " + MField.this.getName() + ";");
return code;
}
});
}
return method.setSynchronized(isSynchronized && !isFinal());
}
public final MMethod addSetterMethod() throws ClassNotFoundException {
return isFinal ? null : addSetterMethod(MFunctions.setterMethodName(name), true);
}
public final MMethod addSetterMethod(String name, boolean isSynchronized) {
final MMethod method;
if (type != null) {
container.addExtraImport(type);
method = container.addMethod(name, void.class, new MParameter(type, generic, this.name)).setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock code = element.getCodeBlock(element);
code.addLine("this." + MField.this.getName() + " = " + MField.this.getName() + ";");
return code;
}
});
} else {
method = container.addMethod(name, void.class, new MParameter(generic, this.name)).setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock code = element.getCodeBlock(element);
code.addLine("this." + MField.this.getName() + " = " + MField.this.getName() + ";");
return code;
}
});
}
return method.setSynchronized(isSynchronized);
}
public static interface AccessorMethods {
MMethod getter();
MMethod setter();
}
public final AccessorMethods addAccessorMethods() throws ClassNotFoundException {
final MMethod getter = addGetterMethod();
getter.setFinal(true);
final MMethod setter = addSetterMethod();
if (setter != null) {
setter.setFinal(true);
}
return new AccessorMethods() {
@Override
public MMethod getter() {
return getter;
}
@Override
public MMethod setter() {
return setter;
}
};
}
}
<file_sep>package com.cc.jcg.bean;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import com.cc.jcg.MBundle;
import com.cc.jcg.MClass;
import com.cc.jcg.MCodeBlock;
import com.cc.jcg.MCodeGenerator;
import com.cc.jcg.MConstructor;
import com.cc.jcg.MField;
import com.cc.jcg.MMethod;
import com.cc.jcg.MPackage;
import com.cc.jcg.bean.example.ExampleBeanA;
public class MBeanMetaBundle
extends MBundle {
public static void main(String[] args) throws Exception {
File srcDir = new File("src");
Map<Class, MBeanMetaBundle> bundles = new HashMap<Class, MBeanMetaBundle>();
MBeanMetaBundle bundle = new MBeanMetaBundle(srcDir, "com.acer.jmdsl.bean.example.gen", ExampleBeanA.class, bundles);
bundle.generateCode(true);
MBeanMetaBundle.generateMetaRegister(srcDir, "com.acer.jmdsl.bean.example.gen", "ExampleMetaModels", bundles);
}
public static final Map<Class, MBeanMetaBundle> generate(Collection<Class<?>> entityTypes, File targetDir, String pckg) throws Exception {
HashMap<Class, MBeanMetaBundle> bundles = new HashMap<Class, MBeanMetaBundle>();
generate(entityTypes, targetDir, pckg, bundles);
return bundles;
}
public static final Map<Class, MBeanMetaBundle> generate(Collection<Class<?>> entityTypes, File targetDir, String pckg, Map<Class, MBeanMetaBundle> bundles) throws Exception {
for (Class type : entityTypes) {
if (isBean(type)) {
new MBeanMetaBundle(targetDir, pckg, type, bundles).generateCode(false);
}
}
return bundles;
}
public static final void generateMetaRegister(File srcDir, String pckg, String name, final Map<Class, MBeanMetaBundle> bundles) throws Exception {
final TreeMap<Class, MBeanMetaBundle> sorted = new TreeMap<Class, MBeanMetaBundle>(new Comparator<Class>() {
@Override
public int compare(Class o1, Class o2) {
return o1.getName().compareTo(o2.getName());
}
});
sorted.putAll(bundles);
MPackage bundle = new MBundle(srcDir, name).newPackage(pckg);
final MClass type = bundle.newClass(name);
type.makePublic().setFinal(true);
type.addConstructor().makePrivate().setBlockContent("super();");
for (Class key : sorted.keySet()) {
MBeanMetaBundle beanMeta = sorted.get(key);
String fieldName = beanMeta.getBeanMeta().getName().concat("Model");
MField field = type.addStaticField(beanMeta.getBeanMeta(), fieldName).setFinal(true).makePublic();
field.setValue(beanMeta.getBeanMeta().getName().concat(".getInstance();"));
}
MMethod register = type.addStaticMethod("register", void.class).makePublic().setFinal(true);
register.setBlockContent("getAllMetaModels();");
MMethod getAllMetaModels = type.addStaticMethod("getAllMetaModels", "Collection<MBBeanMeta>").makePublic().setFinal(true);
type.addExtraImport(Collection.class);
type.addExtraImport(MBBeanMeta.class);
type.addExtraImport(Set.class);
type.addExtraImport(HashSet.class);
getAllMetaModels.setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock block = element.getCodeBlock(element);
block.addLine("Set all = new HashSet();");
for (Class key : sorted.keySet()) {
MBeanMetaBundle beanMeta = sorted.get(key);
String fieldName = beanMeta.getBeanMeta().getName().concat("Model");
block.addLine("all.add(" + fieldName + ");");
}
block.addLine("return all;");
return block;
}
});
bundle.generateCode(false);
}
private final MPackage pckg;
private final Class beanType;
private final String BT;
private MClass beanMeta;
private final Map<Class, MBeanMetaBundle> bundles;
public MBeanMetaBundle(File dir, String pckg, Class beanType) throws Exception {
this(dir, pckg, beanType, new HashMap<Class, MBeanMetaBundle>());
}
public MBeanMetaBundle(File dir, String pckg, Class beanType, Map<Class, MBeanMetaBundle> bundles) throws Exception {
super(dir, "BeanMetaBundle");
this.pckg = newPackage(pckg);
this.beanType = beanType;
BT = beanType.getSimpleName();
this.bundles = bundles;
bundles.put(beanType, this);
buildModel();
}
public final MClass getBeanMeta() {
return beanMeta;
}
@SuppressWarnings("null")
private void buildModel() throws Exception {
beanMeta = pckg.newClass(BT.concat("Meta"));
beanMeta.setFinal(true);
beanMeta.makePublic();
beanMeta.setSuperclass(MBBeanMetaBase.class, BT);
// -----------------------------------------------------------------------------------------------------------------------
MMethod getInstance = beanMeta.addStaticMethod("getInstance", beanMeta).makePublic();
getInstance.setGenerator(new MCodeGenerator<MMethod>() {
@Override
public MCodeBlock getCodeBlock(MMethod element) {
MCodeBlock block = element.getCodeBlock(element);
block.addLine("if (getBeanMeta(\"" + beanMeta.getQualifiedName() + "\") == null) {");
block.addLine(MCodeBlock.tab() + "registerBeanMeta(new " + beanMeta.getName() + "());");
block.addLine("}");
block.addLine("return getBeanMeta(\"" + beanMeta.getQualifiedName() + "\");");
return block;
}
});
// -----------------------------------------------------------------------------------------------------------------------
beanMeta.addConstructor().makePrivate().setGenerator(new MCodeGenerator<MConstructor>() {
@Override
public MCodeBlock getCodeBlock(MConstructor element) {
MCodeBlock block = element.getCodeBlock(element);
block.addLine("super(" + BT + ".class);");
for (Field field : beanType.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
block.addLine("addFieldMeta(" + field.getName() + ");");
}
}
return block;
}
});
// -----------------------------------------------------------------------------------------------------------------------
for (Field field : beanType.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
Class fieldType = field.getType();
if (fieldType.equals(boolean.class)) {
fieldType = Boolean.class;
} else if (fieldType.equals(int.class)) {
fieldType = Integer.class;
} else if (fieldType.equals(long.class)) {
fieldType = Long.class;
} else if (fieldType.equals(double.class)) {
fieldType = Double.class;
} else if (fieldType.equals(float.class)) {
fieldType = Float.class;
} else if (fieldType.equals(short.class)) {
fieldType = Short.class;
}
boolean isRef = isBean(fieldType);
boolean isCollection = Collection.class.isAssignableFrom(fieldType);
boolean isCollectionRef = false;
boolean hasGetter = hasGetter(beanType, field);
boolean hasSetter = hasSetter(beanType, field);
Class<?> genericType = null;
if (isCollection) {
genericType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isCollectionRef = isBean(genericType);
beanMeta.addExtraImport(genericType);
} else {
beanMeta.addExtraImport(fieldType);
}
final MField fm;
if (isCollectionRef) {
if (!bundles.containsKey(genericType)) {
if (generateMetaForType(genericType)) {
MBeanMetaBundle refBundle = new MBeanMetaBundle(getSrcDir(), pckg.getName(), genericType, bundles);
// beanMeta.addExtraImport(refBundle.getBeanMeta());
bundles.put(genericType, refBundle);
addSubBundle(refBundle);
} else {
MBBeanMeta ref = MBRegistry.getBeanMetaByBeanType(genericType);
if (ref != null) {
String refPckg = ref.getClass().getPackage().getName();
MBeanMetaBundle refBundle = new MBeanMetaBundle(null, refPckg, genericType, bundles);
// beanMeta.addExtraImport(ref.getClass());
bundles.put(genericType, refBundle);
}
}
}
final Class<?> intf;
if (hasGetter && hasSetter) {
intf = MBFieldRefCollection.class;
} else if (hasGetter) {
intf = MBFieldRefCollectionGetter.class;
} else if (hasSetter) {
intf = MBFieldRefCollectionSetter.class;
} else {
intf = null;
}
if (intf != null) {
fm = beanMeta.addField(intf, field.getName()).setGeneric("<" + BT + ", " + genericType.getSimpleName() + ">");
fm.setValue("newFieldRefCollection(" + genericType.getSimpleName() + ".class, \"" + field.getName() + "\")");
beanMeta.addExtraImport(genericType);
} else {
fm = null;
}
} else if (isRef) {
if (!bundles.containsKey(fieldType)) {
if (generateMetaForType(fieldType)) {
MBeanMetaBundle refBundle = new MBeanMetaBundle(getSrcDir(), pckg.getName(), fieldType, bundles);
// beanMeta.addExtraImport(refBundle.getBeanMeta());
bundles.put(fieldType, refBundle);
addSubBundle(refBundle);
} else {
MBBeanMeta ref = MBRegistry.getBeanMetaByBeanType(fieldType);
if (ref != null) {
String refPckg = ref.getClass().getPackage().getName();
MBeanMetaBundle refBundle = new MBeanMetaBundle(null, refPckg, fieldType, bundles);
// beanMeta.addExtraImport(ref.getClass());
bundles.put(fieldType, refBundle);
}
}
}
final Class<?> intf;
if (hasGetter && hasSetter) {
intf = MBFieldRef.class;
} else if (hasGetter) {
intf = MBFieldRefGetter.class;
} else if (hasSetter) {
intf = MBFieldRefSetter.class;
} else {
intf = null;
}
if (intf != null) {
fm = beanMeta.addField(intf, field.getName()).setGeneric("<" + BT + ", " + fieldType.getSimpleName() + ">");
fm.setValue("newFieldRef(" + fieldType.getSimpleName() + ".class, \"" + field.getName() + "\")");
beanMeta.addExtraImport(fieldType);
} else {
fm = null;
}
} else if (isCollection) {
final Class<?> intf;
if (hasGetter && hasSetter) {
intf = MBFieldCollection.class;
} else if (hasGetter) {
intf = MBFieldCollectionGetter.class;
} else if (hasSetter) {
intf = MBFieldCollectionSetter.class;
} else {
intf = null;
}
if (intf != null) {
fm = beanMeta.addField(intf, field.getName()).setGeneric("<" + BT + ", " + genericType.getSimpleName() + ">");
fm.setValue("newFieldCollection(" + genericType.getSimpleName() + ".class, \"" + field.getName() + "\")");
beanMeta.addExtraImport(genericType);
} else {
fm = null;
}
} else {
final Class<?> intf;
final String extra;
if (hasGetter && hasSetter) {
intf = MBField.class;
extra = "";
} else if (hasGetter) {
intf = MBFieldGetter.class;
extra = "Getter";
} else if (hasSetter) {
intf = MBFieldSetter.class;
extra = "Setter";
} else {
intf = null;
extra = null;
}
if (intf != null) {
fm = beanMeta.addField(intf, field.getName()).setGeneric("<" + BT + ", " + fieldType.getSimpleName() + ">");
fm.setValue("newField" + extra + "(" + fieldType.getSimpleName() + ".class, \"" + field.getName() + "\")");
beanMeta.addExtraImport(fieldType);
} else {
fm = null;
}
}
if (fm != null) {
fm.makePublic();
fm.setFinal(true);
}
}
}
// -----------------------------------------------------------------------------------------------------------------------
beanMeta.addExtraImport(beanType);
}
protected boolean hasSetter(Class type, Field field) {
return MBFieldBase.getSetter(type, field) != null;
}
protected boolean hasGetter(Class type, Field field) {
return MBFieldBase.getGetter(type, field) != null;
}
protected boolean generateMetaForType(Class type) {
return true;
}
private static boolean isBean(Class type) {
return type.isAnnotationPresent(MBBean.class) || type.isAnnotationPresent(Entity.class) || type.isAnnotationPresent(Embeddable.class);
}
}
<file_sep>package com.cc.jcg.bean;
public interface MBFieldGetter<BT, VT>
extends MBFieldDef<BT> {
Class<VT> getType();
VT getValue(BT bean);
}
<file_sep>package com.mod.gen;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
@Embeddable
public class SomeId
implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private Boolean active;
public SomeId() {
super();
}
@Column(name = "NAME", table = "", nullable = false, unique = false, insertable = true, updatable = true, columnDefinition = "")
public synchronized String getName() {
return name;
}
public synchronized void setName(String name) {
this.name = name;
}
@Column(name = "AGE", table = "", nullable = false, unique = false, insertable = true, updatable = true, columnDefinition = "")
public synchronized Integer getAge() {
return age;
}
public synchronized void setAge(Integer age) {
this.age = age;
}
@Column(name = "ACTIVE", table = "", nullable = false, unique = false, insertable = true, updatable = true, columnDefinition = "")
public synchronized Boolean isActive() {
return active;
}
public synchronized void setActive(Boolean active) {
this.active = active;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder(49373441, 1262045383);
builder.append(name);
builder.append(age);
builder.append(active);
return builder.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SomeId)) {
return false;
}
if (this == obj) {
return true;
}
SomeId cst = (SomeId) obj;
EqualsBuilder builder = new EqualsBuilder();
builder.append(name, cst.name);
builder.append(age, cst.age);
builder.append(active, cst.active);
return builder.isEquals();
}
}
<file_sep>package com.cc.jcg.trees;
import com.cc.jcg.MClass;
import com.cc.jcg.MInterface;
import com.cc.jcg.MTypeRef;
public interface MIntfBaseImpl {
MInterface getInterface();
MClass getBaseClass();
MClass getImplementation();
public static interface MIntfBaseImplRef {
MTypeRef getInterface();
MTypeRef getBaseClass();
MTypeRef getImplementation();
}
}
<file_sep>package com.cc.jcg;
public interface MGenerator {
void generateCode(boolean clean) throws Exception;
}
<file_sep>package com.cc.jcg.bean;
public interface MBFieldRefCollectionGetter<BT, VT>
extends MBFieldCollectionGetter<BT, VT>, MBRef<MBBeanMeta<VT>> {
}
<file_sep>package com.cc.jcg.xml;
public interface XmlType<T> {
Class<T> getJavaType();
T map(String value);
String getMapCall(String argument);
public static final XmlTypeString STRING = new XmlTypeString();
public static final XmlTypeInteger INTEGER = new XmlTypeInteger();
public static final XmlTypeBoolean BOOLEAN = new XmlTypeBoolean();
public static final class XmlTypeString
implements XmlType<String> {
private XmlTypeString() {
super();
}
@Override
public Class<String> getJavaType() {
return String.class;
}
@Override
public String map(String value) {
return value;
}
@Override
public String getMapCall(String argument) {
return argument;
}
}
public static final class XmlTypeInteger
implements XmlType<Integer> {
private XmlTypeInteger() {
super();
}
@Override
public Class<Integer> getJavaType() {
return Integer.class;
}
@Override
public Integer map(String value) {
try {
if (value == null) {
return null;
}
return Integer.valueOf(value);
} catch (NumberFormatException e) {
return null;
}
}
@Override
public String getMapCall(String argument) {
return "XmlType.INTEGER.map(" + argument + ")";
}
}
public static final class XmlTypeBoolean
implements XmlType<Boolean> {
private XmlTypeBoolean() {
super();
}
@Override
public Class<Boolean> getJavaType() {
return Boolean.class;
}
@Override
public Boolean map(String value) {
if (value == null) {
return null;
}
boolean boo = false;
value = value.toLowerCase();
boo = boo || value.equals("true");
boo = boo || value.equals("yes");
boo = boo || value.equals("1");
return boo;
}
@Override
public String getMapCall(String argument) {
return "XmlType.BOOLEAN.map(" + argument + ")";
}
}
}
<file_sep>package com.cc.jcg.bean;
public interface MBField<BT, VT>
extends MBFieldGetter<BT, VT>, MBFieldSetter<BT, VT> {
}
<file_sep>package com.cc.jcg.bean;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class MBRegistry {
private static final ConcurrentMap<String, MBBeanMeta> REGISTRY = new ConcurrentHashMap<String, MBBeanMeta>();
private static final ConcurrentMap<Class<?>, MBBeanMeta> BEANS = new ConcurrentHashMap<Class<?>, MBBeanMeta>();
static <BM extends MBBeanMeta> BM getBeanMeta(String key) {// key = meta.getClass().getName()
return (BM) REGISTRY.get(key);
}
static MBBeanMeta registerBeanMeta(MBBeanMeta meta) {
String key = meta.getClass().getName();
if (REGISTRY.putIfAbsent(key, meta) == null) {
System.out.println("REGISTRY[" + key + "]<< " + meta);
BEANS.putIfAbsent(meta.getBeanType(), meta);
}
return REGISTRY.get(meta.getBeanType());
}
public static TreeMap<Class<?>, MBBeanMeta> get() {
return new TreeMap<Class<?>, MBBeanMeta>(BEANS);
}
public static MBBeanMeta getBeanMetaByName(Class<? extends MBBeanMeta> type) {
return REGISTRY.get(type.getName());
}
public static MBBeanMeta getBeanMetaByBeanType(Class<?> type) {
return BEANS.get(type);
}
private MBRegistry() {
super();
}
}
<file_sep>package com.cc.jcg.tools;
import java.util.concurrent.Callable;
public interface XmlVisitor
extends Callable<Void> {
@Override
public Void call() throws XmlVisitorException;
}
<file_sep>package com.cc.jcg.hierarchy;
public class HierarchyImpl<NI>
implements Hierarchy<NI> {
private final ParentNode<NI> root;
public HierarchyImpl(HierarchyBuilder<NI> builder, NI item) {
super();
this.root = new NodeImpl(builder, this, item);
}
@Override
public final ParentNode<NI> getRootNode() {
return root;
}
@Override
public final void visit(HierarchyVisitor<NI> visitor) {
_visit(root, visitor);
}
private void _visit(ParentNode<NI> parent, HierarchyVisitor<NI> visitor) {
visitor.visit(parent);
for (Node<NI> child : parent.getChildNodes()) {
_visit(child, visitor);
}
}
}
<file_sep>package com.cc.jcg.xml;
public final class XmlAttributeImpl
implements XmlAttribute {
private final XmlType<?> type;
private final String name;
XmlAttributeImpl(XmlType<?> type, String name) {
super();
this.type = type;
this.name = name;
}
@Override
public <T> XmlType<T> getType() {
return (XmlType<T>) type;
}
@Override
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
XmlAttributeImpl other = (XmlAttributeImpl) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
<file_sep># JCG
Java Code Generator
<file_sep>package com.cc.jcg.hierarchy;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public final class NodeImpl<NI>
implements Node<NI> {
private final NI item;
private final Node<NI> parent;
private final Set<Node<NI>> children;
NodeImpl(HierarchyBuilder<NI> builder, HierarchyImpl<NI> hierarchy, NI item) {
this(builder, hierarchy, item, null, new HashMap<NI, NodeImpl<NI>>());
}
private NodeImpl(HierarchyBuilder<NI> builder, HierarchyImpl<NI> hierarchy, NI item, Node<NI> parent, Map<NI, NodeImpl<NI>> cache) {
super();
this.item = item;
this.parent = parent;
children = new LinkedHashSet<Node<NI>>();
if (!cache.containsKey(item)) {
cache.put(item, this);
Collection<NI> children = builder.getChildren(item);
if (children != null) {
for (NI child : children) {
if (cache.containsKey(child)) {
this.children.add(cache.get(child));
} else {
this.children.add(new NodeImpl<NI>(builder, hierarchy, child, this, cache));
}
}
}
}
}
@Override
public NI getNodeItem() {
return item;
}
@Override
public Node<NI> getParentNode() {
return parent;
}
@Override
public Set<Node<NI>> getChildNodes() {
return Collections.unmodifiableSet(children);
}
}
<file_sep>package com.cc.jcg.xml;
import java.util.LinkedHashSet;
public interface XmlItem {
boolean isRoot();
String getName();
LinkedHashSet<XmlAttribute> getAttributes();
XmlItem addAttribute(XmlType type, String name);
XmlItem addAttribute(String name);
XmlItem addAttributes(String... names);
XmlItem addBooleanAttribute(String name);
XmlItem addBooleanAttributes(String... names);
XmlItem addIntegerAttribute(String name);
XmlItem addIntegerAttributes(String... names);
LinkedHashSet<XmlNode> getChildren(XmlCardinality cardinality);
LinkedHashSet<XmlNode> getAllChildren();
XmlNode addChild(String name, XmlCardinality cardinality);
XmlNode addChild(String name, XmlCardinality cardinality, boolean hasTextContent);
}
<file_sep>package com.cc.jcg;
public interface MCodeGenerator<T> {
MCodeBlock getCodeBlock(T element);
}
<file_sep>package com.cc.jcg.xml;
public interface XmlAttribute {
<T> XmlType<T> getType();
String getName();
}
<file_sep>package com.cc.jcg.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public final class XmlHelper {
private XmlHelper() {
super();
}
public static final Document newDocument() throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
return db.newDocument();
}
public static final Document getDocument(File file) throws SAXException, IOException, ParserConfigurationException {
return getDocument(file, false);
}
public static final Document getDocument(File file, boolean validateDTD) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validateDTD);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", validateDTD);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new FileInputStream(file));
}
public static Document getDocument(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = dBuilder.parse(inputStream);
return document;
}
public static Document toDocument(String string) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(new StringReader(string)));
return document;
}
public static void saveDocument(Document document, File file) throws TransformerFactoryConfigurationError, TransformerException, FileNotFoundException, UnsupportedEncodingException {
TransformerFactory tfx = TransformerFactory.newInstance();
Transformer xformer = tfx.newTransformer();
xformer.setOutputProperty("omit-xml-declaration", "yes");
xformer.setOutputProperty(OutputKeys.METHOD, "xml");
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
OutputStream out = null;
OutputStreamWriter writer = null;
try {
out = new FileOutputStream(file);
writer = new OutputStreamWriter(out, "UTF-8");
Source source = new DOMSource(document);
Result result = new StreamResult(writer);
xformer.transform(source, result);
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<file_sep>package com.cc.jcg.hierarchy;
import java.util.Collection;
public interface HierarchyBuilder<NI> {
Collection<NI> getChildren(NI item);
}
<file_sep>package com.cc.jcg.xml;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.cc.jcg.MFunctions;
import com.cc.jcg.tools.XmlVisitorElement;
import com.cc.jcg.tools.XmlVisitorException;
public class MXmlDocumentBuilder
extends XmlVisitorElement {
private XmlDocument document;
private final ConcurrentMap<Node, XmlItem> items = new ConcurrentHashMap<Node, XmlItem>();
private final Set<String> xmlNodes = new HashSet<String>();
private final ConcurrentMap<String, XmlType> attributeTypes = new ConcurrentHashMap<String, XmlType>();
public MXmlDocumentBuilder(File template) throws Exception {
super(template);
}
public final MXmlDocumentBuilder forceAttributeType(String name, XmlType type) {
attributeTypes.put(name, type);
return this;
}
public XmlDocument guessDocument() throws XmlVisitorException {
try {
items.clear();
xmlNodes.clear();
super.call();
return document;
} finally {
items.clear();
xmlNodes.clear();
}
}
protected String getXmlNodeName(Element element) {
return MFunctions.camelize(element.getNodeName());
}
@Override
protected final void onRootElement(Element root) {
document = new XmlDocumentImpl(getXmlNodeName(root));
setCurrent(document.getRoot(), root);
}
private void setCurrent(XmlItem node, Element element) {
items.putIfAbsent(element, node);
xmlNodes.add(node.getName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node a = attributes.item(i);
String key01 = element.getNodeName() + "." + a.getNodeName();
XmlType type = attributeTypes.containsKey(key01) ? attributeTypes.get(key01) : null;
String key02 = a.getNodeName();
type = type == null && attributeTypes.containsKey(key02) ? attributeTypes.get(key02) : type;
type = type != null ? type : XmlType.STRING;
items.get(element).addAttribute(type, a.getNodeName());
}
}
@Override
protected final void onElement(Element element) throws XmlVisitorException {
String name = getXmlNodeName(element);
if (!xmlNodes.contains(name)) {
Node nextSibling = element.getNextSibling();
boolean one = nextSibling == null || nextSibling.getNextSibling() == null || !nextSibling.getNextSibling().getNodeName().equals(element.getNodeName());
XmlCardinality cardinality = one ? XmlCardinality.ONE : XmlCardinality.MANY;
String txt = element.getTextContent();
txt = txt.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "");
boolean hasTextContent = !txt.isEmpty() && element.getChildNodes().getLength() == 1;
XmlNode node = items.get(element.getParentNode()).addChild(name, cardinality, hasTextContent);
setCurrent(node, element);
}
}
}
<file_sep><project name="JCG" default="jar">
<property name="jar" value="java-code-generator.jar" />
<property name="jar.src" value="java-code-generator-src.jar" />
<path id="classpath">
<fileset dir="lib">
<include name="*.jar" />
</fileset>
</path>
<target name="clean">
<delete dir="build" />
</target>
<target name="build">
<mkdir dir="build" />
<mkdir dir="build/classes" />
<javac srcdir="src" destdir="build/classes" classpathref="classpath" debug="true" includeantruntime="false" source="1.6" target="1.6" />
</target>
<target name="jar" depends="clean,build">
<mkdir dir="export" />
<delete dir="export/${jar}" />
<delete dir="export/${jar.src}" />
<parallel threadcount="2">
<jar destfile="export/${jar}" basedir="build/classes" />
<jar destfile="export/${jar.src}" basedir="src" />
</parallel>
<parallel threadcount="8">
<copy todir="../JaVaDe/WebContent/WEB-INF/lib">
<fileset dir="export">
<include name="java-code-generator.jar" />
</fileset>
</copy>
<copy todir="../ModelBuilder/WebContent/WEB-INF/lib">
<fileset dir="export">
<include name="java-code-generator.jar" />
</fileset>
</copy>
</parallel>
</target>
</project><file_sep>package com.cc.jcg.bean.example.gen;
import com.cc.jcg.MGenerated;
import com.cc.jcg.bean.MBBeanMeta;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@MGenerated
public final class ExampleMetaModels {
public static final ExampleBeanAMeta ExampleBeanAMetaModel = ExampleBeanAMeta.getInstance();
public static final ExampleBeanBMeta ExampleBeanBMetaModel = ExampleBeanBMeta.getInstance();
public static void register() {
getAllMetaModels();
}
public static Collection<MBBeanMeta> getAllMetaModels() {
Set all = new HashSet();
all.add(ExampleBeanAMetaModel);
all.add(ExampleBeanBMetaModel);
return all;
}
private ExampleMetaModels() {
super();
}
}
<file_sep>package com.cc.jcg.examples.gen;
import com.cc.jcg.MGenerated;
@MGenerated
public final class SomeClass {
public SomeClass() {
super();
// do other stuffs
}
}
<file_sep>package com.cc.jcg;
public interface MModifier {
String name();
}
<file_sep>package com.cc.jcg.bean;
public interface MBFieldDef<BT> {
Class<BT> getBeanType();
String getName();
}
<file_sep>package com.cc.jcg;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
abstract class MAnnotated<T>
implements MHasImports {
protected final LinkedList<Annotation> annotations = new LinkedList<Annotation>();
protected final LinkedList<String> preDefinitionLines = new LinkedList<String>();
protected final AtomicBoolean generatedAdded = new AtomicBoolean(false);
private final Map<String, Object> extraData = new ConcurrentHashMap<String, Object>();
public final Map<String, Object> getExtraData() {
return extraData;
}
protected MAnnotated() {
super();
if (!MBundle.EXCLUDE_GENERATED_ANNOTATION.get()) {
addGeneratedAnnotation();
}
}
public final List<Annotation> getAnnotations() {
return Collections.unmodifiableList(annotations);
}
public final T addPreDefinitionLine(String line) {
preDefinitionLines.add(line);
return (T) this;
}
public final T removeAllAnnotations() {
annotations.clear();
return (T) this;
}
public final T addAnnotation(Annotation annotation) {
annotations.add(annotation);
return (T) this;
}
public final T addAnnotations(Annotation... annotations) {
addAnnotations(Arrays.asList(annotations));
return (T) this;
}
public final T addAnnotations(Collection<Annotation> annotations) {
for (Annotation annotation : annotations) {
addAnnotation(annotation);
}
return (T) this;
}
private void addGeneratedAnnotation() {
if (this instanceof MType && !(this instanceof MInnerType)) {
if (!((MType) this).isTemplate()) {
if (!generatedAdded.getAndSet(true)) {
annotations.add(new MGenerated() {
@Override
public Class<? extends Annotation> annotationType() {
return MGenerated.class;
}
});
}
}
}
}
public abstract String getPackageName();
protected final void addImport(TreeSet<String> imports, Class<?> type) {
MFunctions.addImport(imports, type, getPackageName());
}
protected final void addImport(TreeSet<String> imports, MTypeRef type) {
MFunctions.addImport(imports, type, getPackageName());
}
protected final void addImport(TreeSet<String> imports, String fullname) {
MFunctions.addImport(imports, fullname);
}
protected final void addImport(TreeSet<String> imports, Collection<String> fullnames) {
for (String fullname : fullnames) {
MFunctions.addImport(imports, fullname);
}
}
@Override
public TreeSet<String> getImports() {
TreeSet<String> imports = new TreeSet<String>();
for (Annotation annotation : annotations) {
addImportsRecursively(imports, annotation);
}
return imports;
}
protected void addImportsRecursively(TreeSet<String> imports, Annotation annotation) {
addImport(imports, annotation.annotationType());
Class<? extends Annotation> annotationType = annotation.getClass();
for (Method m : annotationType.getDeclaredMethods()) {
try {
m.setAccessible(true);
Object av = m.invoke(annotation);
if (av != null) {
Class<?> returnType = m.getReturnType();
if (returnType.isArray()) {
Object[] array = (Object[]) av;
if (array.length > 0) {
for (Object o : array) {
if (o instanceof Annotation) {
addImportsRecursively(imports, (Annotation) o);
}
}
}
} else if (av instanceof Annotation) {
addImportsRecursively(imports, (Annotation) av);
} else if (av instanceof Enum) {
imports.add(av.getClass().getName());
}
}
} catch (Exception e) {
// continue...
}
}
}
protected final void appendAnnotation(StringBuffer sb) {
StringBuffer asb = new StringBuffer();
for (String line : preDefinitionLines) {
asb.append(line);
}
for (Annotation annotation : annotations) {
appendAnnotation(asb, annotation, true);
}
sb.append(asb.toString().replace("()", ""));
}
private void appendAnnotation(StringBuffer asb, Annotation annotation, boolean cr) {
asb.append("@" + annotation.annotationType().getSimpleName());
asb.append("(");
Class<? extends Annotation> annotationType = annotation.getClass();
for (Method m : annotationType.getDeclaredMethods()) {
try {
m.setAccessible(true);
Object av = m.invoke(annotation);
boolean isDefaultValue = false;
try {
Object fv = annotationType.getInterfaces()[0].getDeclaredMethod(m.getName()).getDefaultValue();
isDefaultValue = fv != null && fv.equals(av);
isDefaultValue = isDefaultValue || fv != null && fv.equals("") && av == null;
isDefaultValue = isDefaultValue || fv == null && av == null;
} catch (Exception e) {
// OK
}
if (!isDefaultValue && av != null && !m.getName().equals("annotationType")) {
Class<?> returnType = m.getReturnType();
if (m.getName().equals("value") && String.class.isAssignableFrom(returnType)) {
asb.append(m.getName() + " = \"" + av + "\"");
asb.append(", ");
} else if (m.getName().equals("value") && String[].class.isAssignableFrom(returnType)) {
String[] s = (String[]) av;
asb.append(m.getName() + " = \"" + s[0] + "\"");// ??
asb.append(", ");
} else if (String[].class.isAssignableFrom(returnType)) {
String[] s = (String[]) av;
asb.append(m.getName() + " = \"" + s[0] + "\"");// ??
asb.append(", ");
} else if (String.class.isAssignableFrom(returnType)) {
asb.append(m.getName() + " = \"" + av.toString() + "\"");
asb.append(", ");
} else if (boolean.class.isAssignableFrom(returnType)) {
boolean s = (Boolean) av;
asb.append(m.getName() + (s ? "= true" : "= false"));
asb.append(", ");
} else if (int.class.isAssignableFrom(returnType)) {
asb.append(m.getName() + " = " + av);
asb.append(", ");
} else if (Class.class.isAssignableFrom(returnType)) {
Class c = (Class) av;
asb.append(m.getName() + " = " + c.getSimpleName() + ".class");
asb.append(", ");
} else if (returnType.isArray()) {
Object[] array = (Object[]) av;
if (array.length > 0) {
asb.append("{");
for (Object o : array) {
StringBuffer asb2 = new StringBuffer();
if (o instanceof Annotation) {
appendAnnotation(asb2, (Annotation) o, false);
} else {
asb2.append(o.toString());// !?
}
if (array[array.length - 1] != o) {
asb2.append(",");
}
asb.append("\n");
asb.append("\t" + asb2.toString().replace("\n", ""));
}
asb.append("\n}");
asb.append(", ");
}
} else if (av instanceof Annotation) {
asb.append(m.getName() + " = ");
StringBuffer asb2 = new StringBuffer();
appendAnnotation(asb2, (Annotation) av, false);
asb.append(asb2.toString().replace("\n", ""));
asb.append(", ");
} else if (av instanceof Enum) {
asb.append(m.getName() + " = " + av.getClass().getSimpleName() + "." + ((Enum) av).name());
asb.append(", ");
} else {
asb.append(m.getName() + " = " + av.toString());
asb.append(", ");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
if (asb.toString().endsWith(", ")) {
asb.delete(asb.length() - 2, asb.length());
}
asb.append(")");
if (cr && !(this instanceof MParameter)) {
asb.append("\n");
}
}
}
<file_sep>package com.cc.jcg.bean;
public interface MBFieldListener<BT> {
void on(MBFieldDef<BT> fm);
void on(MBField<BT, ?> fm);
void on(MBFieldCollection<BT, ?> fm);
void on(MBFieldRef<BT, ?> fm);
}
<file_sep>package com.cc.jcg.xml;
public interface XmlDocumentVisitor {
void on(XmlRootNode node);
void on(int level, XmlNode node);
}
<file_sep>package com.cc.jcg.tools;
import java.io.File;
// alias of FileVisitor
public abstract class FileReader
extends FileVisitor {
public FileReader(File file) {
super(file);
}
}
|
804b45818bce876bbf8ef59f04c7f1f0327c0c24
|
[
"Markdown",
"Java",
"Ant Build System"
] | 38
|
Java
|
alecbigger/JCG
|
15d6ad63fb9648a497f42a53f27dd9af490466ff
|
25e958b8c17450c16cb1b94c9c438cb90a85e325
|
refs/heads/master
|
<repo_name>Rajkumarbapu/CollectionsApp<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollectionsApp
{
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
ListSample1();
ListSample2();
DictionarySample1();
DictionarySample2();
}
private static void ListSample1()
{
List<int> primeNumbers = new List<int>();
primeNumbers.Add(1); // adding elements using add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);
var cities = new List<string>();
cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// nulls are allowed for reference type list
//adding elements using collection-initializer syntax
var bigCities = new List<string>()
{
"New York",
"London",
"Mumbai",
"Chicago"
};
var students = new List<Student>() {
new Student(){ Id = 1, Name="Bill"},
new Student(){ Id = 2, Name="Steve"},
new Student(){ Id = 3, Name="Ram"},
new Student(){ Id = 4, Name="Abdul"}
};
string[] anothercities = new string[3] { "Mumbai", "London", "New York" };
var popularCities = new List<string>();
// adding an array in a List
popularCities.AddRange(anothercities);
var favouriteCities = new List<string>();
// adding a List
favouriteCities.AddRange(popularCities);
List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 2
Console.WriteLine(numbers[2]); // prints 5
Console.WriteLine(numbers[3]); // prints 7
// using foreach LINQ method
numbers.ForEach(num => Console.WriteLine(num + ", "));//prints 1, 2, 5, 7, 8, 10,
// using for loop
for (int i = 0; i < numbers.Count; i++)
Console.WriteLine(numbers[i]);
var numbers1 = new List<int>() { 10, 20, 30, 40 };
numbers1.Insert(1, 11);// inserts 11 at 1st index: after 10.
foreach (var num in numbers1)
Console.WriteLine(num);
var numbers2 = new List<int>() { 10, 20, 30, 40, 10 };
numbers2.Remove(10); // removes the first 10 from a list
numbers2.RemoveAt(2); //removes the 3rd element (index starts from 0)
//numbers.RemoveAt(10); //throws ArgumentOutOfRangeException
foreach (var el in numbers2)
Console.WriteLine(el); //prints 20 30 10
var numbers3 = new List<int>() { 10, 20, 30, 40 };
numbers3.Contains(10); // returns true
numbers3.Contains(11); // returns false
numbers3.Contains(20); // returns true
Console.WriteLine(numbers3.Contains(10));
Console.ReadKey();
}
private static void ListSample2()
{
List<string> colors = new List<string>();
//add items in a List collection
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");
//insert an item in the list
colors.Insert(1, "violet");
//retrieve items using foreach loop
foreach (string color in colors)
{
Console.WriteLine(color);
}
//remove an item from list
colors.Remove("violet");
//retrieve items using for loop
for (int i = 0; i < colors.Count; i++)
{
Console.WriteLine(colors[i]);
}
if (colors.Contains("Blue"))
{
Console.WriteLine("Blue color exist in the list");
}
else
{
Console.WriteLine("Not exist");
}
//copy array to list
string[] strArr = new string[3];
strArr[0] = "Red";
strArr[1] = "Blue";
strArr[2] = "Green";
List<string> arrlist = new List<string>(strArr);
foreach (string str in strArr)
{
Console.WriteLine(str);
}
//call clear method
arrlist.Clear();
Console.WriteLine(arrlist.Count.ToString());
Console.ReadKey();
}
private static void DictionarySample1()
{
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1, "One"); //adding a key/value using the Add() method
numberNames.Add(2, "Two");
numberNames.Add(3, "Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach (KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
//creating a dictionary using collection-initializer syntax
var cities = new Dictionary<string, string>(){
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach (var kvp in cities)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
Console.WriteLine(cities["UK"]); //prints value of UK key
Console.WriteLine(cities["USA"]);//prints value of USA key
//Console.WriteLine(cities["France"]); // run-time exception: Key does not exist
//use ContainsKey() to check for an unknown key
if (cities.ContainsKey("France"))
{
Console.WriteLine(cities["France"]);
}
//use TryGetValue() to get a value of unknown key
string result;
if (cities.TryGetValue("France", out result))
{
Console.WriteLine(result);
}
//use ElementAt() to retrieve key-value pair using index
for (int i = 0; i < cities.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}",
cities.ElementAt(i).Key,
cities.ElementAt(i).Value);
}
cities["UK"] = "Liverpool, Bristol"; // update value of UK key
cities["USA"] = "Los Angeles, Boston"; // update value of USA key
//cities["France"] = "Paris"; //throws run-time exception: KeyNotFoundException
if (cities.ContainsKey("France"))
{
cities["France"] = "Paris";
}
cities.Remove("UK"); // removes UK
//cities2.Remove("France"); //throws run-time exception: KeyNotFoundException
if (cities.ContainsKey("France"))
{ // check key before removing it
cities.Remove("France");
}
cities.Clear(); //removes all elements
Console.ReadKey();
}
private static void DictionarySample2()
{
Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
AuthorList.Add("<NAME>", 35);
AuthorList.Add("<NAME>", 25);
AuthorList.Add("<NAME>", 29);
AuthorList.Add("<NAME>", 21);
AuthorList.Add("<NAME>", 84);
// Count
Console.WriteLine("Count: {0}", AuthorList.Count);
// Set Item value
AuthorList["<NAME>"] = 9;
if (!AuthorList.ContainsKey("<NAME>"))
{
AuthorList["<NAME>"] = 20;
}
if (!AuthorList.ContainsValue(9))
{
Console.WriteLine("Item found");
}
// Read all items
Console.WriteLine("Authors all items:");
foreach (KeyValuePair<string, Int16> author in AuthorList)
{
Console.WriteLine("Key: {0}, Value: {1}",
author.Key, author.Value);
}
// Remove item with key = '<NAME>'
AuthorList.Remove("<NAME>");
// Remove all items
AuthorList.Clear();
Console.ReadKey();
}
}
}
|
db16fc0eb30cb05893898a1a980134ff3a0c14a2
|
[
"C#"
] | 1
|
C#
|
Rajkumarbapu/CollectionsApp
|
8abd2ca1fdfc70472ea8ac22a0f1bd738003bdb9
|
256085d05b119b98788b34164a0a755f7744d3a7
|
refs/heads/master
|
<repo_name>tcelovsky/rails-amusement-park-v-000<file_sep>/app/models/ride.rb
class Ride < ActiveRecord::Base
belongs_to :attraction
belongs_to :user
def take_ride
@user = User.find_by_id(self.user_id)
@attraction = Attraction.find_by_id(self.attraction_id)
# byebug
if @user.tickets < @attraction.tickets && user.height < @attraction.min_height
"Sorry. You do not have enough tickets to ride the #{@attraction.name}. You are not tall enough to ride the #{@attraction.name}."
elsif @user.height < @attraction.min_height
"Sorry. You are not tall enough to ride the #{@attraction.name}."
elsif @user.tickets < @attraction.tickets
"Sorry. You do not have enough tickets to ride the #{@attraction.name}."
else
@user.tickets -= @attraction.tickets
@user.nausea += @attraction.nausea_rating
@user.happiness += @attraction.happiness_rating
@user.save
# byebug
end
end
private
def current_user
@user = User.find_by_id(:user_id)
end
def current_attraction
@attraction = Attraction.find_by_id(:attraction_id)
end
def current_ride
@ride = Ride.find_by(user_id:[:user_id])
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_secure_password
has_many :rides
has_many :attractions, through: :rides
def mood
if nausea > happiness
return "sad"
else return "happy"
end
end
private
def current_user
@user = User.find_by_id(:id)
end
end
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
@user = User.find_by(name: params[:name])
if params[:password] == params[:password_confirmation]
# return head(:forbidden) unless @user.authenticate(params[:password])
# session[:name] = params[:name]
session[:user_id] = params[:id]
redirect_to :user
else redirect_to :new_user
end
end
def destroy
session.delete :user_id
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
end
def create
@user = User.create(user_params)
if params[:password] == params[:password_confirmation]
session[:user_id] = @user.id
redirect_to user_path(@user)
else render :new_user
end
end
def show
@user = User.find_by(params[:name])
end
def index
@users = User.all
end
private
def user_params
params.require(:user).permit(:name, :password, :password_confirmation, :nausea, :happiness, :tickets, :height, :admin)
end
end
|
3ffd09bed98e00c4b82f712940b65b4eb3ce5f8b
|
[
"Ruby"
] | 4
|
Ruby
|
tcelovsky/rails-amusement-park-v-000
|
c1d7b00b788f3d61058601956b3e141f680328dc
|
912ac6500bc6c738e3cfd83450bc86e47a0957f7
|
refs/heads/master
|
<repo_name>alsmadi/Relationship-Bootstrap<file_sep>/src/gov/ornl/stucco/relationprediction/InstanceID.java
package gov.ornl.stucco.relationprediction;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/*
* The purpose of this class is to store information about the entities from which an instance was generated.
* It includes the name of the file from which it came, the
*/
public class InstanceID
{
private String filename;
private int firsttokensentencenum;
private int replacedfirsttokenindex;
private int firsttokenstartindex;
private int firsttokenendindex;
private int secondtokensentencenum;
private int replacedsecondtokenindex;
private int secondtokenstartindex;
private int secondtokenendindex;
//private int heuristiclabel;
InstanceID(String filename, int firsttokensentencenum, int replacedfirsttokenindex, int firsttokenstartindex, int firsttokenendindex, int secondtokensentencenum, int replacedsecondtokenindex, int secondtokenstartindex, int secondtokenendindex)
{
this.filename = filename;
this.firsttokensentencenum = firsttokensentencenum;
this.replacedfirsttokenindex = replacedfirsttokenindex;
this.firsttokenstartindex = firsttokenstartindex;
this.firsttokenendindex = firsttokenendindex;
this.secondtokensentencenum = secondtokensentencenum;
this.replacedsecondtokenindex = replacedsecondtokenindex;
this.secondtokenstartindex = secondtokenstartindex;
this.secondtokenendindex = secondtokenendindex;
}
InstanceID(String instanceidasstring)
{
filename = instanceidasstring.substring(0, instanceidasstring.lastIndexOf('-'));
String indices = instanceidasstring.substring(instanceidasstring.lastIndexOf('-')+1);
indices = indices .replaceAll("\\)\\(", " ");
indices = indices .replaceAll("\\(", " ");
indices = indices .replaceAll("\\)", " ");
indices = indices .replaceAll(",", " ");
indices = indices.trim();
String[] indicesarray = indices.split(" ");
firsttokensentencenum = Integer.parseInt(indicesarray[0]);
replacedfirsttokenindex = Integer.parseInt(indicesarray[1]);
firsttokenstartindex = Integer.parseInt(indicesarray[2]);
firsttokenendindex = Integer.parseInt(indicesarray[3]);
secondtokensentencenum = Integer.parseInt(indicesarray[4]);
replacedsecondtokenindex = Integer.parseInt(indicesarray[5]);
secondtokenstartindex = Integer.parseInt(indicesarray[6]);
secondtokenendindex = Integer.parseInt(indicesarray[7]);
}
public String getFileName()
{
return filename;
}
public int getFirstTokenSentenceNum()
{
return firsttokensentencenum;
}
public int getReplacedFirstTokenIndex()
{
return replacedfirsttokenindex;
}
public int getFirstTokenStartIndex()
{
return firsttokenstartindex;
}
public int getFirstTokenEndIndex()
{
return firsttokenendindex;
}
public int getSecondTokenSentenceNum()
{
return secondtokensentencenum;
}
public int getReplacedSecondTokenIndex()
{
return replacedsecondtokenindex;
}
public int getSecondTokenStartIndex()
{
return secondtokenstartindex;
}
public int getSecondTokenEndIndex()
{
return secondtokenendindex;
}
/*
public void setHeuristicLabel(int heuristiclabel)
{
this.heuristiclabel = heuristiclabel;
}
public int getHeuristicLabel()
{
return heuristiclabel;
}
*/
/*
public static HashMap<Integer,ArrayList<InstanceID>> readRelationTypeToInstanceIDOrder(String entityextractedfilename, boolean training)
{
HashMap<Integer,ArrayList<InstanceID>> relationtypeToinstanceidorder = new HashMap<Integer,ArrayList<InstanceID>>();
try
{
for(Integer i : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
ArrayList<InstanceID> instanceidorder = new ArrayList<InstanceID>();
relationtypeToinstanceidorder.put(i, instanceidorder);
File f = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, i, training);
BufferedReader in = new BufferedReader(new FileReader(f));
String line;
while((line = in.readLine()) != null)
{
String[] splitline = line.split("\t");
InstanceID instanceid = new InstanceID(splitline[1]);
instanceid.setHeuristicLabel(Integer.parseInt(splitline[0]));
instanceidorder.add(instanceid);
}
in.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return relationtypeToinstanceidorder;
}
*/
public String toString()
{
return filename + "-(" + firsttokensentencenum + "," + replacedfirsttokenindex + "," + firsttokenstartindex + "," + firsttokenendindex + ")" +
"(" + secondtokensentencenum + "," + replacedsecondtokenindex + ","+ secondtokenstartindex + "," + secondtokenendindex + ")";
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/GenericCyberEntityTextRelationship.java
package gov.ornl.stucco.relationprediction;
//This class is stores generic version of a relationship between two cyber entities. It can be created between any
//pair of cyber entities, even those that do not fit into any relationship we care about. The reason for this is that
//we use it as a tool for determining if the entities' types fit some relationship we care about. It can be initialized
//with two CyberEntityTexts, and from that it will determine which, if any, relationship type could apply between the
//two entity types. The constants defined at the top define all relationship types (though if the entities appear
//in the text in the reverse order of the order implied by the order in the constant's name, the relationship's ID is just
//-1 times the normal relationship type ID.
//
//The most important methods here are loadAllKnownRelationships(), which reads stuff in from a few files, mostly
//from the NVD dump, and determines what entitities are actually related (just storing this information in memory).
//After calling that method, it is possible for an instance of this class to call isKnownRelationship() to determine
//whether the CyberEntityTexts it was initialized with should be related or not according to the NVD dump and other
//sources.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class GenericCyberEntityTextRelationship
{
//This is the directory containing the nvd xml dumps.
//private static File nvdxmldir = new File("src/nvdxml/"); //Location where xml dumps from NVD can be found. Downloaded from https://nvd.nist.gov/download.cfm
//Each of the 24 relationshp types is associated with an int constant here.
public static final int RT_SWVENDOR_SWPRODUCT = 1; //sw.vendor & sw.product à same software
public static final int RT_SWVERSION_SWPRODUCT = 2; //sw.version & sw.product à same software
public static final int RT_VUDESCRIPTION_VUNAME = 3; //vuln.description & vuln.name à same vulnerability
public static final int RT_VUMS_VUNAME = 4; //vuln.ms & vuln.name à same vulnerability
public static final int RT_VUCVE_VUNAME = 5; //vuln.cve & vuln.name à same vulnerability
public static final int RT_VUDESCRIPTION_VUMS = 6; //vuln.description & vuln.ms à same vulnerability
public static final int RT_VUDESCRIPTION_VUCVE = 7; //vuln.description & vuln.cve à same vulnerability
public static final int RT_VUCVE_VUMS = 8; //vuln.cve & vuln.ms à same vulnerability
//The commented out relationship types are relationships we are interested in, but cannot be found directly in the text.
//public static final int RT_VU_SW = 9; //vuln.* & sw.* à ExploitTargetRelatedObservable
//public static final int RT_SW_FILENAME = 10; //sw.* & file.name à Sub-Observable
//public static final int RT_SW_FUNCTIONNAME= 11; //sw.* & function.name à Sub-Observable
//public static final int RT_VU_FILENAME = 12; //vuln.* & file.name à ExploitTargetRelatedObservable
//public static final int RT_VU_FUNCTIONNAME = 13; //vuln.* & function.name à ExploitTargetRelatedObservable
//The following relationship types are not directly ones we are interested in, but are necessary for finding the ones above that cannot be found directly in the text.
//The next group are needed for vuln.* & sw.* à ExploitTargetRelatedObservable
public static final int RT_SWPRODUCT_VUNAME = 14; //sw.product & vuln.name
public static final int RT_SWPRODUCT_VUMS = 15; //sw.product & vuln.ms
public static final int RT_SWPRODUCT_VUCVE = 16; //sw.product & vuln.cve
public static final int RT_SWVERSION_VUNAME = 17; //sw.version & vuln.name
public static final int RT_SWVERSION_VUMS = 18; //sw.version & vuln.ms
public static final int RT_SWVERSION_VUCVE = 19; //sw.version & vuln.cve
//The next group are needed for sw.* & file.name à Sub-Observable
public static final int RT_SWPRODUCT_FINAME = 20; //sw.product & file.name
public static final int RT_SWVERSION_FINAME = 21; //sw.version & file.name
//The next group are needed for sw.* & function.name à Sub-Observable
public static final int RT_SWPRODUCT_FUNAME = 22; //sw.product & function.name
public static final int RT_SWVERSION_FUNAME = 23; //sw.version & function.name
//The next group are needed for vuln.* & file.name à ExploitTargetRelatedObservable
public static final int RT_VUNAME_FINAME = 24; //vuln.name & file.name
public static final int RT_VUCVE_FINAME = 25; //vuln.cve & file.name
public static final int RT_VUMS_FINAME = 26; //vuln.ms & file.name
//The next group are needed for vuln.* & function.name à ExploitTargetRelatedObservable
public static final int RT_VUNAME_FUNAME = 27; //vuln.name & function.name
public static final int RT_VUCVE_FUNAME = 28; //vuln.cve & function.name
public static final int RT_VUMS_FUNAME = 29; //vuln.ms & function.name
public static HashMap<Integer,String> relationshipidTorelationshipname = new HashMap<Integer,String>();
static
{
relationshipidTorelationshipname.put(RT_SWVENDOR_SWPRODUCT, "SOFTWARE_VENDOR is vendor of SOFTWARE_PRODUCT");
relationshipidTorelationshipname.put(RT_SWVERSION_SWPRODUCT, "SOFTWARE_VERSION is version of SOFTWARE_PRODUCT");
relationshipidTorelationshipname.put(RT_VUDESCRIPTION_VUNAME, "VULNERABILITY_DESCRIPTION describes VULNERABILITY_NAME");
relationshipidTorelationshipname.put(RT_VUMS_VUNAME, "VULNERABILITY_MS_ID describes VULNERABILITY_NAME");
relationshipidTorelationshipname.put(RT_VUCVE_VUNAME, "VULNERABILITY_CVE_ID is named VULNERABILITY_NAME");
relationshipidTorelationshipname.put(RT_VUDESCRIPTION_VUMS, "VULNERABILITY_DESCRIPTION describes VULNERABILITY_MS_ID");
relationshipidTorelationshipname.put(RT_VUDESCRIPTION_VUCVE, "VULNERABILITY_DESCRIPTION describes CVE ID VULNERABILITY_CVE_ID");
relationshipidTorelationshipname.put(RT_VUCVE_VUMS, "VULNERABILITY_CVE_ID is ID for VULNERABILITY_MS_ID");
relationshipidTorelationshipname.put(RT_SWPRODUCT_VUNAME, "SOFTWARE_PRODUCT is vulnerable to VULNERABILITY_NAME");
relationshipidTorelationshipname.put(RT_SWPRODUCT_VUMS, "SOFTWARE_PRODUCT is vulnerable to VULNERABILITY_MS_ID");
relationshipidTorelationshipname.put(RT_SWPRODUCT_VUCVE, "SOFTWARE_PRODUCT is vulnerable to VULNERABILITY_CVE_ID");
relationshipidTorelationshipname.put(RT_SWVERSION_VUNAME, "SOFTWARE_VERSION is vulnerable to VULNERABILITY_NAME");
relationshipidTorelationshipname.put(RT_SWVERSION_VUMS, "SOFTWARE_VERSION is vulnerabile to VULNERABILITY_MS_ID");
relationshipidTorelationshipname.put(RT_SWVERSION_VUCVE, "SOFTWARE_VERSION is vulnerable to VULNERABILITY_CVE_ID");
relationshipidTorelationshipname.put(RT_SWPRODUCT_FINAME, "SOFTWARE_PRODUCT has vulnerability related to FILE_NAME");
relationshipidTorelationshipname.put(RT_SWVERSION_FINAME, "SOFTWARE_VERSION has a vulnerability related to FILE_NAME");
relationshipidTorelationshipname.put(RT_SWPRODUCT_FUNAME, "SOFTWARE_PRODUCT has a vulnerability in FUNCTION_NAME");
relationshipidTorelationshipname.put(RT_SWVERSION_FUNAME, "SOFTWARE_VERSION has a vulnerability in FUNCTION_NAME");
relationshipidTorelationshipname.put(RT_VUNAME_FINAME, "VULNERABILITY_NAME is related to FILE_NAME");
relationshipidTorelationshipname.put(RT_VUCVE_FINAME, "VULNERABILITY_CVE_ID is related to FILE_NAME");
relationshipidTorelationshipname.put(RT_VUMS_FINAME, "VULNERABILITY_MS_ID is related to FILE_NAME");
relationshipidTorelationshipname.put(RT_VUNAME_FUNAME, "VULNERABILITY_NAME is related to FUNCTION_NAME");
relationshipidTorelationshipname.put(RT_VUCVE_FUNAME, "VULNERABILITY_CVE_ID is related to FUNCTION_NAME");
relationshipidTorelationshipname.put(RT_VUMS_FUNAME, "VULNERABILITY_MS_ID is related to FUNCTION_NAME");
}
//Each entity type is associated with an int constant in CyberEntityText, and each relationship type
//is associated with an int constant above. Given the ints associated with a pair of entities, this
//array stores the int associated with their relationship type. Entries should be null if there
//is no relationship type that fits with the two entities. Order matters, and an entry
//in this array is positive if the entities appear in the standard order, and negative
//if the order is reversed. The "standard" order is arbitrary, and is defined only in this array.
public static final Integer[][] entity1typeToentity2typeTorelationshiptype = new Integer[CyberEntityText.ENTITYTYPECOUNT][CyberEntityText.ENTITYTYPECOUNT];
public static final HashSet<Integer> allrelationshiptypesset = new HashSet<Integer>();
public static final HashSet<Integer> allpositiverelationshiptypesset = new HashSet<Integer>();
static
{
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVENDOR][CyberEntityText.SWPRODUCT] = RT_SWVENDOR_SWPRODUCT;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.SWPRODUCT] = RT_SWVERSION_SWPRODUCT;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUDESCRIPTION][CyberEntityText.VUNAME] = RT_VUDESCRIPTION_VUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUMS][CyberEntityText.VUNAME] = RT_VUMS_VUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUCVE][CyberEntityText.VUNAME] = RT_VUCVE_VUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUDESCRIPTION][CyberEntityText.VUMS] = RT_VUDESCRIPTION_VUMS;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUDESCRIPTION][CyberEntityText.VUCVE] = RT_VUDESCRIPTION_VUCVE;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUCVE][CyberEntityText.VUMS] = RT_VUCVE_VUMS;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWPRODUCT][CyberEntityText.VUNAME] = RT_SWPRODUCT_VUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWPRODUCT][CyberEntityText.VUMS] = RT_SWPRODUCT_VUMS;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWPRODUCT][CyberEntityText.VUCVE] = RT_SWPRODUCT_VUCVE;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.VUNAME] = RT_SWVERSION_VUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.VUMS] = RT_SWVERSION_VUMS;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.VUCVE] = RT_SWVERSION_VUCVE;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWPRODUCT][CyberEntityText.FINAME] = RT_SWPRODUCT_FINAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.FINAME] = RT_SWVERSION_FINAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWPRODUCT][CyberEntityText.FUNAME] = RT_SWPRODUCT_FUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.SWVERSION][CyberEntityText.FUNAME] = RT_SWVERSION_FUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUNAME][CyberEntityText.FINAME] = RT_VUNAME_FINAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUCVE][CyberEntityText.FINAME] = RT_VUCVE_FINAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUMS][CyberEntityText.FINAME] = RT_VUMS_FINAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUNAME][CyberEntityText.FUNAME] = RT_VUNAME_FUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUCVE][CyberEntityText.FUNAME] = RT_VUCVE_FUNAME;
entity1typeToentity2typeTorelationshiptype[CyberEntityText.VUMS][CyberEntityText.FUNAME] = RT_VUMS_FUNAME;
for(int i = 0; i < CyberEntityText.ENTITYTYPECOUNT; i++)
{
for(int j = 0; j < CyberEntityText.ENTITYTYPECOUNT; j++)
{
if(entity1typeToentity2typeTorelationshiptype[i][j] != null)
{
entity1typeToentity2typeTorelationshiptype[j][i] = -entity1typeToentity2typeTorelationshiptype[i][j];
allrelationshiptypesset.add(entity1typeToentity2typeTorelationshiptype[i][j]);
allrelationshiptypesset.add(-entity1typeToentity2typeTorelationshiptype[i][j]);
allpositiverelationshiptypesset.add(Math.abs(entity1typeToentity2typeTorelationshiptype[i][j]));
}
}
}
}
//This class contains methods for determining if a relationship candidate is a known relationship or not.
//In order to determine this, it needs to load a bunch of relationships into memory. But it doesn't make
//sense to load the relationships into memory unless they're needed. So this variable keeps track
//of whether the relationships have been loaded into memory.
private static boolean loadedrelationships = false;
private CyberEntityText[] entities = new CyberEntityText[2];
public GenericCyberEntityTextRelationship(CyberEntityText entity1, CyberEntityText entity2)
{
entities[0] = entity1;
entities[1] = entity2;
}
public CyberEntityText getEntityOfType(int type)
{
for(CyberEntityText cet : entities)
{
if(cet.getEntityType() == type)
return cet;
}
return null;
}
public CyberEntityText getFirstEntity()
{
return entities[0];
}
public CyberEntityText getSecondEntity()
{
return entities[1];
}
public Integer getRelationType()
{
return entity1typeToentity2typeTorelationshiptype[entities[0].getEntityType()][entities[1].getEntityType()];
}
//Reads all known entities in from Database. The information gets stored in various different places.
public static void loadAllKnownRelationships()
{
Vulnerability.setAllRelevantTerms();
loadRelationshipsFromNVD();
SoftwareWVersion.setAllAliases();
loadedrelationships = true;
}
//Loads entities from NVD xml data. The code is ugly because I have never done anything with xml files before.
private static void loadRelationshipsFromNVD()
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
for(File file : ProducedFileGetter.getNVDXMLDir().listFiles())
{
if(!file.getName().endsWith(".zip"))
continue;
ZipFile zipfile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipfile.entries();
while(entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
InputStream stream = zipfile.getInputStream(entry);
org.w3c.dom.Document document = db.parse(stream);
org.w3c.dom.Element root = document.getDocumentElement();
org.w3c.dom.NodeList nodelist = root.getChildNodes();
for(int i = 0; i < nodelist.getLength(); i++) //Each node should be associated with a vulnerability.
{
org.w3c.dom.Node node = nodelist.item(i);
//Skip any nodes that are not vulnerability entries, because some nodes are not vulnerability information.
if(!node.getNodeName().equals("entry"))
continue;
//These are holder variables for all the stuff that is going to end up
//being related to each other. We set the values of these things as
//we progress through the subnodes.
String cveid = null;
String msid = null;
ArrayList<SoftwareWVersion> vulnerablesoftwares = new ArrayList<SoftwareWVersion>();
ArrayList<String> description = null;
String name = null;
HashSet<String> functionnames = new HashSet<String>();
HashSet<String> filenames = new HashSet<String>();
org.w3c.dom.NodeList nodelist2 = node.getChildNodes();
for(int j = 0; j < nodelist2.getLength(); j++)
{
org.w3c.dom.Node node2 = nodelist2.item(j);
//Look into each of these if/else if statements to see where we find entities and how we set them from what we find there.
if(node2.getNodeName().equals("vuln:cve-id"))
cveid = node2.getTextContent();
else if(node2.getNodeName().equals("vuln:references"))
{
org.w3c.dom.NodeList nodelist3 = node2.getChildNodes();
for(int k = 0; k < nodelist3.getLength(); k++)
{
org.w3c.dom.Node node3 = nodelist3.item(k);
if(node3.getNodeName().equals("vuln:reference"))
{
String possiblemsid = node3.getTextContent();
if(possiblemsid.startsWith("MS") && possiblemsid.length() == 8 && possiblemsid.charAt(4) == '-')
msid = possiblemsid;
}
}
}
else if(node2.getNodeName().equals("vuln:vulnerable-software-list"))
{
org.w3c.dom.NodeList nodelist3 = node2.getChildNodes();
for(int k = 0; k < nodelist3.getLength(); k++)
{
org.w3c.dom.Node node3 = nodelist3.item(k);
if(node3.getNodeName().equals("vuln:product"))
{
String vulnerablesoftwareid = node3.getTextContent();
//All the stuff we want to know about a software is encoded in the software id, so we can build the Software object when we extract the id.
SoftwareWVersion vulnerablesoftware = SoftwareWVersion.getSoftwareFromSoftwareID(vulnerablesoftwareid);
vulnerablesoftwares.add(vulnerablesoftware);
}
}
}
else if(node2.getNodeName().equals("vuln:summary"))
{
String summary = node2.getTextContent().toLowerCase();
//A relevant term counts as a description if it appears in the list of relevant terms at https://github.com/stucco/entity-extractor/blob/master/src/main/resources/dictionaries/relevant_terms.txt
description = Vulnerability.getRelevantDescriptionsFromText(summary);
//We say the vulnerability's name starts after ", aka " and ends at whichever occurs first: 1) the next period, 2) the next comma, or 3) the end of the summary.
int startposition = summary.lastIndexOf(", aka ");
if(startposition > -1)
{
startposition = startposition + 6;
int nextperiodposition = summary.indexOf('.', startposition);
if(nextperiodposition == -1)
nextperiodposition = Integer.MAX_VALUE;
int nextcommaposition = summary.indexOf(',', startposition);
if(nextcommaposition == -1)
nextcommaposition = Integer.MAX_VALUE;
int endofstring = summary.length()-1;
int endposition = Math.min(nextperiodposition, Math.min(nextcommaposition, endofstring));
name = summary.substring(startposition, endposition).replaceAll("\"", "");
}
//Summaries contain function and file names sometimes
String[] splitdescription = summary.split(" ");
for(int k = 0; k < splitdescription.length; k++)
{
if(splitdescription[k].startsWith("function"))
{
String possiblefunctionthing = splitdescription[k];
if(possiblefunctionthing.charAt(possiblefunctionthing.length()-1) == ',' || possiblefunctionthing.charAt(possiblefunctionthing.length()-1) == ';' || possiblefunctionthing.charAt(possiblefunctionthing.length()-1) == ')')
possiblefunctionthing = possiblefunctionthing.substring(0, possiblefunctionthing.length()-1);
if((possiblefunctionthing.equals("function") || possiblefunctionthing.equals("functions")) && k > 0)
functionnames.add(splitdescription[k-1]);
}
RelevantFile f = RelevantFile.getRelevantFileOfCommonType(splitdescription[k]);
if(f != null)
filenames.add(f.getFileName());
}
}
}
//We wait to create the vulnerability object until here because Vulnerability's fields need to be populated from information from different places in the xml entity (so we need to finish the last loop before constructing a vulnerability instance).
Vulnerability vulnerability = Vulnerability.getVulnerabilityFromCVEID(cveid, msid, name, description);
//We want to associate functions and file names with the vulnerability, software, and
//relationship, but we do not have a really good way for figuring out when they are
//associated with the right software if there are multiple softwares for this vulnerability.
//So we associate a file name or vulnerability with these things only if
//all the vulnerable softwares are versions of the same software. So, for example, we
//would not associate any functions or filenames with anything if the vulnerable
//softwares included Flash and Firefox, but we would create the association if
//the vulnerability is associated with Firefox version 1.3 and Firefox version 1.4.
boolean founddifferentvulnerablesoftwares = false;
if(vulnerablesoftwares.size() > 0)
{
String thesoftwarename = vulnerablesoftwares.get(0).getName();
for(int j = 1; j < vulnerablesoftwares.size(); j++)
if(!thesoftwarename.equals(vulnerablesoftwares.get(j).getName()))
founddifferentvulnerablesoftwares = true;
}
//Relate all softwares mentioned with the vulnerability.
for(SoftwareWVersion software : vulnerablesoftwares)
{
VulnerabilityToSoftwareWVersionRelationship r = VulnerabilityToSoftwareWVersionRelationship.getRelationship(software, vulnerability);
if(!founddifferentvulnerablesoftwares)
{
r.setFunctionNames(functionnames);
r.setFileNames(filenames);
}
}
}
}
zipfile.close();
}
}catch(ParserConfigurationException | IOException | SAXException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
//Return true if the entities are in a known relationship. Return false if both entities are known, but they are not in a known relationship. Return null if either entity is not known.
public Boolean isKnownRelationship()
{
//We can't tell if a relationship is known unless we have loaded our known relationships into memory. So check
//if we've done that. And if not, do it.
if(!loadedrelationships)
loadAllKnownRelationships();
switch (getRelationType())
{
//Choose a function depending on the types of the entities involved.
case RT_SWVENDOR_SWPRODUCT: return isKnownRelationship_SWVendor_SWProduct();
case RT_SWVERSION_SWPRODUCT: return isKnownRelationship_SWVersion_SWProduct();
case RT_VUDESCRIPTION_VUNAME: return isKnownRelationship_VUDescription_VUName();
case RT_VUMS_VUNAME: return isKnownRelationship_VUMS_VUName();
case RT_VUCVE_VUNAME: return isKnownRelationship_VUCVE_VUName();
case RT_VUDESCRIPTION_VUMS: return isKnownRelationship_VUDescription_VUMS();
case RT_VUDESCRIPTION_VUCVE: return isKnownRelationship_VUDescription_VUCVE();
case RT_VUCVE_VUMS: return isKnownRelationship_VUCVE_VUMS();
case RT_SWPRODUCT_VUNAME: return isKnownRelationship_SWProduct_VUName();
case RT_SWPRODUCT_VUMS: return isKnownRelationship_SWProduct_VUMS();
case RT_SWPRODUCT_VUCVE: return isKnownRelationship_SWProduct_VUCVE();
case RT_SWVERSION_VUNAME: return isKnownRelationship_SWVersion_VUName();
case RT_SWVERSION_VUMS: return isKnownRelationship_SWVersion_VUMS();
case RT_SWVERSION_VUCVE: return isKnownRelationship_SWVersion_VUCVE();
case RT_SWPRODUCT_FINAME: return isKnownRelationship_SWProduct_FIName();
case RT_SWVERSION_FINAME: return isKnownRelationship_SWVersion_FIName();
case RT_SWPRODUCT_FUNAME: return isKnownRelationship_SWProduct_FUName();
case RT_SWVERSION_FUNAME: return isKnownRelationship_SWVersion_FUName();
case RT_VUNAME_FINAME: return isKnownRelationship_VUName_FIName();
case RT_VUCVE_FINAME: return isKnownRelationship_VUCVE_FIName();
case RT_VUMS_FINAME: return isKnownRelationship_VUMS_FIName();
case RT_VUNAME_FUNAME: return isKnownRelationship_VUName_FUName();
case RT_VUCVE_FUNAME: return isKnownRelationship_VUCVE_FUName();
case RT_VUMS_FUNAME: return isKnownRelationship_VUMS_FUName();
//Same as above, but for when the order of entities is reversed (and thus the relationship type number is negated)
case -RT_SWVENDOR_SWPRODUCT: return isKnownRelationship_SWVendor_SWProduct();
case -RT_SWVERSION_SWPRODUCT: return isKnownRelationship_SWVersion_SWProduct();
case -RT_VUDESCRIPTION_VUNAME: return isKnownRelationship_VUDescription_VUName();
case -RT_VUMS_VUNAME: return isKnownRelationship_VUMS_VUName();
case -RT_VUCVE_VUNAME: return isKnownRelationship_VUCVE_VUName();
case -RT_VUDESCRIPTION_VUMS: return isKnownRelationship_VUDescription_VUMS();
case -RT_VUDESCRIPTION_VUCVE: return isKnownRelationship_VUDescription_VUCVE();
case -RT_VUCVE_VUMS: return isKnownRelationship_VUCVE_VUMS();
case -RT_SWPRODUCT_VUNAME: return isKnownRelationship_SWProduct_VUName();
case -RT_SWPRODUCT_VUMS: return isKnownRelationship_SWProduct_VUMS();
case -RT_SWPRODUCT_VUCVE: return isKnownRelationship_SWProduct_VUCVE();
case -RT_SWVERSION_VUNAME: return isKnownRelationship_SWVersion_VUName();
case -RT_SWVERSION_VUMS: return isKnownRelationship_SWVersion_VUMS();
case -RT_SWVERSION_VUCVE: return isKnownRelationship_SWVersion_VUCVE();
case -RT_SWPRODUCT_FINAME: return isKnownRelationship_SWProduct_FIName();
case -RT_SWVERSION_FINAME: return isKnownRelationship_SWVersion_FIName();
case -RT_SWPRODUCT_FUNAME: return isKnownRelationship_SWProduct_FUName();
case -RT_SWVERSION_FUNAME: return isKnownRelationship_SWVersion_FUName();
case -RT_VUNAME_FINAME: return isKnownRelationship_VUName_FIName();
case -RT_VUCVE_FINAME: return isKnownRelationship_VUCVE_FIName();
case -RT_VUMS_FINAME: return isKnownRelationship_VUMS_FIName();
case -RT_VUNAME_FUNAME: return isKnownRelationship_VUName_FUName();
case -RT_VUCVE_FUNAME: return isKnownRelationship_VUCVE_FUName();
case -RT_VUMS_FUNAME: return isKnownRelationship_VUMS_FUName();
default: return null;
}
}
public Boolean isKnownRelationship_SWVendor_SWProduct()
{
String vendoralias = getEntityTextGivenType(CyberEntityText.SWVENDOR);
String productalias = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
ArrayList<SoftwareWVersion> softwares = SoftwareWVersion.getAllSoftwaresWithAlias(productalias);
for(SoftwareWVersion swv : softwares)
{
for(String swvvendoralias : swv.getVendorAliases())
if(vendoralias.equalsIgnoreCase(swvvendoralias))
return true;
}
if(SoftwareWVersion.getAllProductAliases().contains(productalias) && SoftwareWVersion.getAllVendorAliases().contains(vendoralias))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_SWProduct()
{
String version = getEntityTextGivenType(CyberEntityText.SWVERSION);
String productalias = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
ArrayList<SoftwareWVersion> softwares = SoftwareWVersion.getAllSoftwaresWithAlias(productalias);
for(SoftwareWVersion swv : softwares)
{
if(version.equals(swv.getVersion()))
return true;
}
if(SoftwareWVersion.getAllProductAliases().contains(productalias) && SoftwareWVersion.getAllVersions().contains(version))
return false;
return null;
}
public Boolean isKnownRelationship_VUDescription_VUName()
{
String description = getEntityTextGivenType(CyberEntityText.VUDESCRIPTION);
String vulnerabilityname = getEntityTextGivenType(CyberEntityText.VUNAME);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithName(vulnerabilityname))
{
if(vulnerability.getDescription() != null && vulnerability.getDescription().contains(description))
return true;
}
if(Vulnerability.getAllRelevantTerms().contains(description) && Vulnerability.getAllNames().contains(vulnerabilityname))
return false;
return null;
}
public Boolean isKnownRelationship_VUMS_VUName()
{
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
String vulnerabilityname = getEntityTextGivenType(CyberEntityText.VUNAME);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithName(vulnerabilityname))
{
if(vulnerability.getMSID().equals(ms))
return true;
}
if(Vulnerability.getAllMSs().contains(ms) && Vulnerability.getAllNames().contains(vulnerabilityname))
return false;
return null;
}
public Boolean isKnownRelationship_VUCVE_VUName()
{
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
String vulnerabilityname = getEntityTextGivenType(CyberEntityText.VUNAME);
Vulnerability vulnerability = Vulnerability.getVulnerabilityFromCVEID(cve);
if(vulnerability != null && vulnerability.getName().equals(vulnerabilityname))
return true;
if(Vulnerability.getAllCVEs().contains(cve) && Vulnerability.getAllNames().contains(vulnerabilityname))
return false;
return null;
}
public Boolean isKnownRelationship_VUDescription_VUMS()
{
String description = getEntityTextGivenType(CyberEntityText.VUDESCRIPTION);
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithMSid(ms))
{
if(vulnerability.getDescription() != null && vulnerability.getDescription().contains(description))
return true;
}
if(Vulnerability.getAllRelevantTerms().contains(description) && Vulnerability.getAllMSs().contains(ms))
return false;
return null;
}
public Boolean isKnownRelationship_VUDescription_VUCVE()
{
String description = getEntityTextGivenType(CyberEntityText.VUDESCRIPTION);
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
Vulnerability v = Vulnerability.getVulnerabilityFromCVEID(cve);
if(v != null && v.getDescription() != null && v.getDescription().contains(description))
return true;
if(Vulnerability.getAllRelevantTerms().contains(description) && Vulnerability.getAllCVEs().contains(cve))
return false;
return null;
}
public Boolean isKnownRelationship_VUCVE_VUMS()
{
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
Vulnerability v = Vulnerability.getVulnerabilityFromCVEID(cve);
if(v != null && v.getMSID().equals(ms))
return true;
if(Vulnerability.getAllMSs().contains(ms) && Vulnerability.getAllCVEs().contains(cve))
return false;
return null;
}
public Boolean isKnownRelationship_SWProduct_VUName()
{
String swproduct = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
String vuname = getEntityTextGivenType(CyberEntityText.VUNAME);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithName(vuname))
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getSoftwareAliases().contains(swproduct))
return true;
}
}
if(SoftwareWVersion.getAllProductAliases().contains(swproduct) && Vulnerability.getAllNames().contains(vuname))
return false;
return null;
}
public Boolean isKnownRelationship_SWProduct_VUMS()
{
String swproduct = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithMSid(ms))
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getSoftwareAliases().contains(swproduct))
return true;
}
}
if(SoftwareWVersion.getAllProductAliases().contains(swproduct) && Vulnerability.getAllMSs().contains(ms))
return false;
return null;
}
public Boolean isKnownRelationship_SWProduct_VUCVE()
{
String swproduct = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
Vulnerability vulnerability = Vulnerability.getVulnerabilityFromCVEID(cve);
if(vulnerability != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getSoftwareAliases().contains(swproduct))
return true;
}
}
if(SoftwareWVersion.getAllProductAliases().contains(swproduct) && Vulnerability.getAllCVEs().contains(cve))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_VUName()
{
String swversion = getEntityTextGivenType(CyberEntityText.SWVERSION);
String vuname = getEntityTextGivenType(CyberEntityText.VUNAME);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithName(vuname))
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getVersion().equals(swversion))
return true;
}
}
if(SoftwareWVersion.getAllVersions().contains(swversion) && Vulnerability.getAllNames().contains(vuname))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_VUMS()
{
String swversion = getEntityTextGivenType(CyberEntityText.SWVERSION);
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
for(Vulnerability vulnerability : Vulnerability.getVulnerabilitiesWithMSid(ms))
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getVersion().equals(swversion))
return true;
}
}
if(SoftwareWVersion.getAllVersions().contains(swversion) && Vulnerability.getAllMSs().contains(ms))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_VUCVE()
{
String swversion = getEntityTextGivenType(CyberEntityText.SWVERSION);
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
Vulnerability vulnerability = Vulnerability.getVulnerabilityFromCVEID(cve);
if(vulnerability != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : vulnerability.getRelationships())
{
if(relationship.getSoftwareWVersion().getVersion().equals(swversion))
return true;
}
}
if(SoftwareWVersion.getAllVersions().contains(swversion) && Vulnerability.getAllCVEs().contains(cve))
return false;
return null;
}
public Boolean isKnownRelationship_SWProduct_FIName()
{
String swproduct = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
String filename = getEntityTextGivenType(CyberEntityText.FINAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFileName(filename);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getSoftwareWVersion().getSoftwareAliases().contains(swproduct))
return true;
}
}
if(SoftwareWVersion.getAllProductAliases().contains(swproduct) && VulnerabilityToSoftwareWVersionRelationship.getAllFileNames().contains(filename))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_FIName()
{
String swversion = getEntityTextGivenType(CyberEntityText.SWVERSION);
String filename = getEntityTextGivenType(CyberEntityText.FINAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFileName(filename);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getSoftwareWVersion().getVersion().equals(swversion))
return true;
}
}
if(SoftwareWVersion.getAllVersions().contains(swversion) && VulnerabilityToSoftwareWVersionRelationship.getAllFileNames().contains(filename))
return false;
return null;
}
public Boolean isKnownRelationship_SWProduct_FUName()
{
String swproduct = getEntityTextGivenType(CyberEntityText.SWPRODUCT);
String functionname = getEntityTextGivenType(CyberEntityText.FUNAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFunctionName(functionname);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getSoftwareWVersion().getSoftwareAliases().contains(swproduct))
return true;
}
}
if(SoftwareWVersion.getAllProductAliases().contains(swproduct) && VulnerabilityToSoftwareWVersionRelationship.getAllFunctionNames().contains(functionname))
return false;
return null;
}
public Boolean isKnownRelationship_SWVersion_FUName()
{
String swversion = getEntityTextGivenType(CyberEntityText.SWVERSION);
String functionname = getEntityTextGivenType(CyberEntityText.FUNAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFunctionName(functionname);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getSoftwareWVersion().getVersion().equals(swversion))
return true;
}
}
if(SoftwareWVersion.getAllVersions().contains(swversion) && VulnerabilityToSoftwareWVersionRelationship.getAllFunctionNames().contains(functionname))
return false;
return null;
}
public Boolean isKnownRelationship_VUName_FIName()
{
String vulnerabilityname = getEntityTextGivenType(CyberEntityText.VUNAME);
String filename = getEntityTextGivenType(CyberEntityText.FINAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFileName(filename);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getName().equals(vulnerabilityname))
return true;
}
}
if(Vulnerability.getAllNames().contains(vulnerabilityname) && VulnerabilityToSoftwareWVersionRelationship.getAllFileNames().contains(filename))
return false;
return null;
}
public Boolean isKnownRelationship_VUCVE_FIName()
{
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
String filename = getEntityTextGivenType(CyberEntityText.FINAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFileName(filename);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getCVEID().equals(cve))
return true;
}
}
if(Vulnerability.getAllCVEs().contains(cve) && VulnerabilityToSoftwareWVersionRelationship.getAllFileNames().contains(filename))
return false;
return null;
}
public Boolean isKnownRelationship_VUMS_FIName()
{
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
String filename = getEntityTextGivenType(CyberEntityText.FINAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFileName(filename);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getMSID().equals(ms))
return true;
}
}
if(Vulnerability.getAllMSs().contains(ms) && VulnerabilityToSoftwareWVersionRelationship.getAllFileNames().contains(filename))
return false;
return null;
}
public Boolean isKnownRelationship_VUName_FUName()
{
String vulnerabilityname = getEntityTextGivenType(CyberEntityText.VUNAME);
String functionname = getEntityTextGivenType(CyberEntityText.FUNAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFunctionName(functionname);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getName().equals(vulnerabilityname))
return true;
}
}
if(Vulnerability.getAllNames().contains(vulnerabilityname) && VulnerabilityToSoftwareWVersionRelationship.getAllFunctionNames().contains(functionname))
return false;
return null;
}
public Boolean isKnownRelationship_VUCVE_FUName()
{
String cve = getEntityTextGivenType(CyberEntityText.VUCVE);
String functionname = getEntityTextGivenType(CyberEntityText.FUNAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFunctionName(functionname);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getCVEID().equals(cve))
return true;
}
}
if(Vulnerability.getAllCVEs().contains(cve) && VulnerabilityToSoftwareWVersionRelationship.getAllFunctionNames().contains(functionname))
return false;
return null;
}
public Boolean isKnownRelationship_VUMS_FUName()
{
String ms = getEntityTextGivenType(CyberEntityText.VUMS);
String functionname = getEntityTextGivenType(CyberEntityText.FUNAME);
ArrayList<VulnerabilityToSoftwareWVersionRelationship> relationships = VulnerabilityToSoftwareWVersionRelationship.getRelationshipsWithFunctionName(functionname);
if(relationships != null)
{
for(VulnerabilityToSoftwareWVersionRelationship relationship : relationships)
{
if(relationship.getVulnerability().getMSID().equals(ms))
return true;
}
}
if(Vulnerability.getAllMSs().contains(ms) && VulnerabilityToSoftwareWVersionRelationship.getAllFunctionNames().contains(functionname))
return false;
return null;
}
public String getEntityTextGivenType(int entitytype)
{
if(entities[0].getEntityType() == entitytype)
return entities[0].getEntitySpacedText();
else if(entities[1].getEntityType() == entitytype)
return entities[1].getEntitySpacedText();
return null;
}
//Just for testing, loads all known relationships and aliaes from xml and json files and prints statistics about them.
public static void main(String[] args)
{
loadAllKnownRelationships();
printRelationStatistics();
}
private static void printRelationStatistics()
{
Collection<SoftwareWVersion> softwares = SoftwareWVersion.getAllSoftwareWVersions();
//· sw.vendor & sw.product à same software
HashSet<String> relationholder = new HashSet<String>();
for(SoftwareWVersion software : softwares)
if(software.getVendor() != null && software.getName() != null)
relationholder.add(software.getVendor() + "\t" + software.getName());
System.out.println("sw.vendor & sw.product:\t" + relationholder.size());
//· sw.version & sw.product à same software
relationholder = new HashSet<String>();
for(SoftwareWVersion software : softwares)
if(software.getName() != null && software.getVersion() != null)
relationholder.add(software.getName() + "\t" + software.getVersion());
System.out.println("sw.version & sw.product:\t" + relationholder.size());
//· vuln.description & vuln.name à same vulnerability
relationholder = new HashSet<String>();
HashMap<String,Vulnerability> vulnerabilitynameTovulnerability = Vulnerability.getCveIdToVulnerability();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getName() != null && vulnerability.getDescription() != null)
relationholder.add(vulnerability.getName() + "\t" + vulnerability.getDescription());
System.out.println("vuln.description & vuln.name:\t" + relationholder.size());
//· vuln.ms & vuln.name à same vulnerability
relationholder = new HashSet<String>();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getMSID() != null && vulnerability.getName() != null)
relationholder.add(vulnerability.getMSID() + "\t" + vulnerability.getName());
System.out.println("vuln.ms & vuln.name:\t" + relationholder.size());
//· vuln.cve & vuln.name à same vulnerability
relationholder = new HashSet<String>();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getName() != null && vulnerability.getCVEID() != null)
relationholder.add(vulnerability.getCVEID() + "\t" + vulnerability.getName());
System.out.println("vuln.cve & vuln.name:\t" + relationholder.size());
//· vuln.description & vuln.ms à same vulnerability
relationholder = new HashSet<String>();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getDescription() != null && vulnerability.getMSID() != null)
relationholder.add(vulnerability.getDescription() + "\t" + vulnerability.getMSID());
System.out.println("vuln.description & vuln.ms:\t" + relationholder.size());
//· vuln.description & vuln.cve à same vulnerability
relationholder = new HashSet<String>();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getDescription() != null && vulnerability.getCVEID() != null)
relationholder.add(vulnerability.getDescription() + "\t" + vulnerability.getCVEID());
System.out.println("vuln.description & vuln.cve:\t" + relationholder.size());
//· vuln.cve & vuln.ms à same vulnerability
relationholder = new HashSet<String>();
for(Vulnerability vulnerability : vulnerabilitynameTovulnerability.values())
if(vulnerability.getCVEID() != null && vulnerability.getMSID() != null)
relationholder.add(vulnerability.getCVEID() + "\t" + vulnerability.getMSID());
System.out.println("vuln.cve & vuln.ms:\t" + relationholder.size());
//· vuln.* & sw.* à ExploitTargetRelatedObservable
relationholder = new HashSet<String>();
for(VulnerabilityToSoftwareWVersionRelationship relationship : VulnerabilityToSoftwareWVersionRelationship.getPrimaryKeyToRelationship().values())
if(relationship.getVulnerability().getCVEID() != null && relationship.getSoftwareWVersion().getName() != null)
relationholder.add(relationship.getVulnerability().getCVEID() + "\t" + relationship.getSoftwareWVersion().getName());
System.out.println("vuln.* & sw.*:\t" + relationholder.size() + "\t(note that different versions do not count as different sw.*s here or below)");
//· sw.* & file.name à Sub-Observable
relationholder = new HashSet<String>();
for(VulnerabilityToSoftwareWVersionRelationship relationship : VulnerabilityToSoftwareWVersionRelationship.getPrimaryKeyToRelationship().values())
{
HashSet<String> filenames = relationship.getFileNames();
if(filenames != null)
{
for(String filename : filenames)
if(relationship.getSoftwareWVersion().getName() != null && filename != null)
relationholder.add(relationship.getSoftwareWVersion().getName() + "\t" + filename);
}
}
System.out.println("sw.* & file.name:\t" + relationholder.size());
//· sw.* & function.name à Sub-Observable
relationholder = new HashSet<String>();
for(VulnerabilityToSoftwareWVersionRelationship relationship : VulnerabilityToSoftwareWVersionRelationship.getPrimaryKeyToRelationship().values())
{
HashSet<String> functionnames = relationship.getFunctionNames();
if(functionnames != null)
{
for(String functionname : functionnames)
if(relationship.getSoftwareWVersion().getName() != null && functionname != null)
relationholder.add(relationship.getSoftwareWVersion().getName() + "\t" + functionname);
}
}
System.out.println("sw.* & function.name:\t" + relationholder.size());
//· vuln.* & file.name à ExploitTargetRelatedObservable
relationholder = new HashSet<String>();
for(VulnerabilityToSoftwareWVersionRelationship relationship : VulnerabilityToSoftwareWVersionRelationship.getPrimaryKeyToRelationship().values())
{
HashSet<String> filenames = relationship.getFileNames();
if(filenames != null)
{
for(String filename : filenames)
if(relationship.getVulnerability().getCVEID() != null && filename != null)
relationholder.add(relationship.getVulnerability().getCVEID() + "\t" + filename);
}
}
System.out.println("vuln.* & file.name:\t" + relationholder.size());
//· vuln.* & function.name à ExploitTargetRelatedObservable
relationholder = new HashSet<String>();
for(VulnerabilityToSoftwareWVersionRelationship relationship : VulnerabilityToSoftwareWVersionRelationship.getPrimaryKeyToRelationship().values())
{
HashSet<String> functionnames = relationship.getFunctionNames();
if(functionnames != null)
{
for(String functionname : functionnames)
if(relationship.getVulnerability().getCVEID() != null && functionname != null)
relationholder.add(relationship.getVulnerability().getCVEID() + "\t" + functionname);
}
}
System.out.println("vuln.* & function.name:\t" + relationholder.size());
}
public static HashSet<Integer> getAllRelationshipTypesSet()
{
return allrelationshiptypesset;
}
//A reverse relationship just has entities coming in the opposite order in the text. We just gave these
//reverse relationships IDs that are -1 times the original relationship's id.
public static int getReverseRelationshipType(int relationshiptype)
{
return -relationshiptype;
}
public String toString()
{
return entities[0] + "\t" + entities[1] + "\t" + getRelationType();
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/WriteRelationInstanceFiles.java
/*
* This program's purpose is to read the word vectors written by TrainModel.py and the preprocessed files
* written by PrintPreprocessedDocuments in order to construct training instances for some learner.
* The resulting training files are written in SVM light format.
*/
package gov.ornl.stucco.relationprediction;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.IndexedWord;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation;
import edu.stanford.nlp.semgraph.SemanticGraphEdge;
import edu.stanford.nlp.trees.GrammaticalRelation;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeCoreAnnotations.TreeAnnotation;
import edu.stanford.nlp.util.CoreMap;
import gov.ornl.stucco.entity.EntityLabeler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
public class WriteRelationInstanceFiles
{
private static String entityextractedfilename;
//private static String contexts;
private static boolean training = false;
private static String featuretype;
private static DecimalFormat formatter = new DecimalFormat(".0000");
private static final String emptystringcode = "ZZZ"; //Used to denote a dependency node path of length 0.
public static void main(String[] args)
{
readArgs(args);
//It is kind of dumb to initialize all the printwriters at once right here, but it made sense in an old version of this program.
HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTofeaturetypeToprintwriter = initializePrintWriters(featuretype);
buildAndWriteTrainingInstances(featuretype, relationtypeTofeaturetypeToprintwriter);
//Close the file streams.
for(HashMap<String,PrintWriter> contextToprintwriter : relationtypeTofeaturetypeToprintwriter.values())
for(PrintWriter pw : contextToprintwriter.values())
pw.close();
}
//Arguments:
//1. extractedfilename (This is the name of the file written by PrintPreprocessedDocuments.
//Valid known values for this argument are "original", "entityreplaced", and "aliasreplaced")
//2. featuretype (This code (1 character in length) encodes which feature type to build the
//file from. To see available feature type character codes and their
//meanings, see FeatureMap.)
//3. training (optional). If you include the word "training" in your command line arguments
//after the first two (required) feature types, training files (based on the .ser.gz contents
//of Training DataFiles directory) will be written. Else testing files (based on the .ser.gz
//contents of Testing DataFiles directory) will be written.
private static void readArgs(String[] args)
{
entityextractedfilename = args[0];
featuretype = args[1];
for(int i = 2; i < args.length; i++)
{
if("training".equals(args[i]))
training = true;
}
}
private static HashMap<Integer,HashMap<String,PrintWriter>> initializePrintWriters(String feature)
{
HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter = new HashMap<Integer,HashMap<String,PrintWriter>>();
try
{
for(Integer i : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
File f = ProducedFileGetter.getRelationshipSVMInstancesFile(entityextractedfilename, feature, i, training);
HashMap<String,PrintWriter> contextToprintwriter = relationtypeTocontextToprintwriter.get(i);
if(contextToprintwriter == null)
{
contextToprintwriter = new HashMap<String,PrintWriter>();
relationtypeTocontextToprintwriter.put(i, contextToprintwriter);
}
contextToprintwriter.put(feature, new PrintWriter(new FileWriter(f)));
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return relationtypeTocontextToprintwriter;
}
//Direct the flow to the method for writing the appropriate feature type.
private static void buildAndWriteTrainingInstances(String featuretype, HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTofeaturetypeToprintwriter)
{
if(featuretype.equals(FeatureMap.WORDEMBEDDINGBEFORECONTEXT))
writeContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.WORDEMBEDDINGBETWEENCONTEXT))
writeContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.WORDEMBEDDINGAFTERCONTEXT))
writeContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.SYNTACTICPARSETREEPATH))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODECONTEXTS))
writeDependencyContextFile(relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.SYNTACTICPARSETREESUBPATHS))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGESUBPATHS))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODESUBPATHS))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODESUBPATHS))
writeParseTreePathFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.ENTITYBEFORECOUNTS))
writeEntityContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.ENTITYBETWEENCOUNTS))
writeEntityContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.ENTITYAFTERCOUNTS))
writeEntityContextFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.WORDNGRAMSBEFORE))
writeWordNgramFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.WORDNGRAMSBETWEEN))
writeWordNgramFile(featuretype, relationtypeTofeaturetypeToprintwriter);
if(featuretype.equals(FeatureMap.WORDNGRAMSAFTER))
writeWordNgramFile(featuretype, relationtypeTofeaturetypeToprintwriter);
}
private static void writeContextFile(String featuretype, HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter)
{
//Read in the saved word vectors
WordToVectorMap wvm = WordToVectorMap.getWordToVectorMap(entityextractedfilename);
try
{
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile = new ZipFile(ProducedFileGetter.getEntityExtractedText(entityextractedfilename, training));
ZipEntry entry = zipfile.entries().nextElement();
BufferedReader in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile3 = new ZipFile(ProducedFileGetter.getEntityExtractedText("unlemmatized", training));
ZipEntry entry3 = zipfile3.entries().nextElement();
BufferedReader unlemmatizedalignedin = new BufferedReader(new InputStreamReader(zipfile3.getInputStream(entry3)));
InstanceID nextinstanceid;
Integer nextheuristiclabel = null;
for(Integer relationtype : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
PrintWriter out = relationtypeTocontextToprintwriter.get(relationtype).get(featuretype);
File f = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, relationtype, training);
BufferedReader orderedinstancereader = new BufferedReader(new FileReader(f));
String nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
while(nextinstanceid != null)
{
//ArrayList<InstanceID> instanceidorder = new ArrayList<InstanceID>(relationtypeToinstanceidorder.get(relationtype));
//while(instanceidorder.size() > 0)
//{
String desiredfilename = nextinstanceid.getFileName();
ArrayList<String[]> filelines = getLinesAssociatedWithOneFile(desiredfilename, in, zipfile, entry);
ArrayList<String[]> unlemmatizedfilelines = getLinesAssociatedWithOneFile(desiredfilename, unlemmatizedalignedin, zipfile3, entry3);
//These are the indices of the tokens in the original document (before we
//replaced entities with representative tokens).
ArrayList<int[]> originalindices = new ArrayList<int[]>();
for(String[] sentence : unlemmatizedfilelines)
originalindices.add(PrintPreprocessedDocuments.getOriginalTokenIndexesFromPreprocessedLine(sentence));
//while(instanceidorder.size() > 0 && instanceidorder.get(0).getFileName().equals(desiredfilename))
while(nextinstanceid != null && nextinstanceid.getFileName().equals(desiredfilename))
{
int firsttokensentencenum = nextinstanceid.getFirstTokenSentenceNum();
int replacedfirsttokenindex = nextinstanceid.getReplacedFirstTokenIndex();
int secondtokensentencenum = nextinstanceid.getSecondTokenSentenceNum();
int replacedsecondtokenindex = nextinstanceid.getReplacedSecondTokenIndex();
String[] firstsentence = filelines.get(firsttokensentencenum);
String[] secondsentence = filelines.get(secondtokensentencenum);
ArrayList<String> context = new ArrayList<String>();
if(featuretype.equals(FeatureMap.WORDEMBEDDINGBEFORECONTEXT))
{
for(int i = 0; i < replacedfirsttokenindex; i++)
context.add(firstsentence[i]);
}
if(featuretype.equals(FeatureMap.WORDEMBEDDINGAFTERCONTEXT))
{
for(int i = replacedsecondtokenindex+1; i < secondsentence.length; i++)
context.add(secondsentence[i]);
}
if(featuretype.equals(FeatureMap.WORDEMBEDDINGBETWEENCONTEXT))
{
if(firsttokensentencenum == secondtokensentencenum)
{
for(int i = replacedfirsttokenindex+1; i < replacedsecondtokenindex; i++)
context.add(firstsentence[i]);
}
else
{
for(int i = replacedfirsttokenindex+1; i < firstsentence.length; i++)
context.add(firstsentence[i]);
for(int i = 0; i < replacedsecondtokenindex; i++)
context.add(secondsentence[i]);
for(int sentencenum = firsttokensentencenum + 1; sentencenum < secondtokensentencenum; sentencenum++)
{
String[] sentence = filelines.get(sentencenum);
for(String word : sentence)
context.add(word);
}
}
}
//Now, actually build the SVM_light style string representation of the instance.
String instanceline = buildOutputLineFromVector(nextheuristiclabel, wvm.getContextVector(context), context.size());
//Add a comment describing what the instance is about (originally written in FindAndOrderAllInstances.
//String comment = nextorderedinstanceline.split(" # ")[1];
//String comment = nextorderedinstanceline.substring(nextorderedinstanceline.indexOf('#'));
String comment = FindAndOrderAllInstances.getCommentFromLine(nextorderedinstanceline);
instanceline += " # " + comment;
//And finally, print it to the appropriate file using the PrintWriter we
//made earlier.
out.println(instanceline);
//}
nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
}
}
orderedinstancereader.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
public static String buildOutputLineFromVector(Boolean isknownrelationship, double[] contextvectors, int contextlength)
{
String result = getLabelStringFromIsKnownRelationship(isknownrelationship);
for(int i = 0; i < contextvectors.length; i++)
result += " " + (i+1) + ":" + formatter.format(contextvectors[i]);
result += " " + "TokenCount:" + contextlength;
return result;
}
public static String buildOutputLineFromVector(int label, double[] contextvectors, int contextlength)
{
if(label == -1)
return buildOutputLineFromVector(false, contextvectors, contextlength);
else if(label == 1)
return buildOutputLineFromVector(true, contextvectors, contextlength);
else if(label == 0)
return buildOutputLineFromVector(null, contextvectors, contextlength);
return null;
}
public static String getLabelStringFromIsKnownRelationship(Boolean isknownrelationship)
{
if(isknownrelationship == null)
return "0";
else if(isknownrelationship)
return "1";
else
return "-1";
}
//This method is intended to let us repeatedly find the section of a file beginning with a given line (desiredfilename)
//without having to reopen or reread the entirety of the file every time we want to find a section.
public static ArrayList<String[]> getLinesAssociatedWithOneFile(String desiredfilename, BufferedReader in, ZipFile zipfile, ZipEntry entry)
{
ArrayList<String[]> resultlines = new ArrayList<String[]>();
try
{
try{in.ready();}
catch(IOException e){in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));}
String line;
while((line = in.readLine()) != null)
{
if(line.startsWith("###") && line.endsWith("###"))
{
String currentfilename = line.substring(3, line.length()-3);
if(currentfilename.equals(desiredfilename))
{
while(!(line = in.readLine()).equals(""))
resultlines.add(line.split(" "));
break;
}
}
}
if(resultlines.size() == 0)
{
in.close();
in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
while((line = in.readLine()) != null)
{
if(line.startsWith("###") && line.endsWith("###"))
{
String currentfilename = line.substring(3, line.length()-3);
if(currentfilename.equals(desiredfilename))
{
while(!(line = in.readLine()).equals(""))
resultlines.add(line.split(" "));
break;
}
}
}
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return resultlines;
}
//This method constructs parse tree paths out of the instances. It is a good example of how to use annotations provided
//by the entity extractor in the .ser.gz files.
public static void writeParseTreePathFile(String featuretype, HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter)
{
String currentfilename = null;
List<CoreMap> sentences = null;
InstanceID nextinstanceid;
Integer nextheuristiclabel = null;
String desiredfilename;
try
{
//We're creating these features for each relation type.
for(Integer relationtype : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
//Construct a PrintWriter that prints to the file for features of this type for this relation type.
PrintWriter out = relationtypeTocontextToprintwriter.get(relationtype).get(featuretype);
//We enforce a certain order on our instances because for sort of complicated reasons, this means we do not have
//to hold as many things in memory. So FindAndOrderAllInstances wrote a file listing all the instances we
//are interested in using, and we have to process the instances in the order provided by the file. So read
//the file it wrote to process the instances in it one-by-one.
File g = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, relationtype, training);
BufferedReader orderedinstancereader = new BufferedReader(new FileReader(g));
String nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
//While there are still more instances in the file we're reading:
while(nextinstanceid != null)
{
//There are likely to be many instances associated with each entity-annotated (.ser.gz) file. Reading
//these files is an expensive operation, so we only want to read each file once. So read file associated'
//with nextinstanceid in only if we did not already read it in.
desiredfilename = nextinstanceid.getFileName();
if(!desiredfilename.equals(currentfilename))
{
File f = new File(ProducedFileGetter.getEntityExtractedSerializedDirectory(training), desiredfilename);
Annotation deserDoc = EntityLabeler.deserializeAnnotatedDoc(f.getAbsolutePath());
//These are the annotated sentences from the entity-annotated file. They have annotations like POS
//tags and lemmas, and parse trees, and hopefully in the next version of the VM, coreference and
//dependency trees.
sentences = deserDoc.get(SentencesAnnotation.class);
currentfilename = desiredfilename;
}
//Get a string representation of the parse tree path between entities represented by nextinstanceid.
String parsetreepath = null;
if(featuretype.equals(FeatureMap.SYNTACTICPARSETREEPATH))
parsetreepath = getSyntacticParseTreePath(nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH))
parsetreepath = getDependencyParseTreePath(featuretype, nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH))
parsetreepath = getDependencyParseTreePath(featuretype, nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
parsetreepath = getDependencyParseTreePath(featuretype, nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.SYNTACTICPARSETREESUBPATHS))
parsetreepath = getSyntacticParseTreePath(nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGESUBPATHS))
parsetreepath = getDependencyParseTreePath(FeatureMap.DEPENDENCYPARSETREEEDGEPATH, nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODESUBPATHS))
parsetreepath = getDependencyParseTreePath(FeatureMap.DEPENDENCYPARSETREENODEPATH, nextinstanceid, sentences);
else if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODESUBPATHS))
parsetreepath = getDependencyParseTreePath(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH, nextinstanceid, sentences);
//Write this instance as a relation instance line consisting of only one feature (the parse tree path)
//including the heuristic label and comment extracted from the file written by FindAndOrderAllInstances.
//String comment = nextorderedinstanceline.substring(nextorderedinstanceline.indexOf('#'));
String comment = FindAndOrderAllInstances.getCommentFromLine(nextorderedinstanceline);
if(featuretype.equals(FeatureMap.SYNTACTICPARSETREEPATH) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
out.println(nextheuristiclabel + " " + parsetreepath + ":1" + " # " + comment);
else if(featuretype.equals(FeatureMap.SYNTACTICPARSETREESUBPATHS) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGESUBPATHS) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODESUBPATHS) ||
featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODESUBPATHS))
out.println(nextheuristiclabel + " " + getSubPathFeaturesLine(parsetreepath) + " # " + comment);
//Read in the next instance from FindAndOrderAllInstances's file.
nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
}
out.close();
orderedinstancereader.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
//Given an instance, construct a string Comprising the syntactic parse tree labels on the path between the last words in each entity.
private static String getSyntacticParseTreePath(InstanceID instanceid, List<CoreMap> sentences)
{
//sentences is a list of the (annotated) sentences in this document. Get the sentence in which each entity appears.
int firstsentencenum = instanceid.getFirstTokenSentenceNum();
CoreMap sent1 = sentences.get(firstsentencenum);
//ArrayList<Tree> pathtoroot1 = getPathToRoot(sent1, instanceid.getFirstTokenEndIndex()-1);
int secondsentencenum = instanceid.getSecondTokenSentenceNum();
CoreMap sent2 = sentences.get(secondsentencenum);
//ArrayList<Tree> pathtoroot2 = getPathToRoot(sent2, instanceid.getSecondTokenEndIndex()-1);
String result = "";
//If the entities occur in the same sentence, the path will be directly between the two entities' last words.
if(sent1 == sent2)
{
Tree tree = sent1.get(TreeAnnotation.class);
List<Tree> leaves = tree.getLeaves();
Tree desiredleaf1 = leaves.get(instanceid.getFirstTokenEndIndex()-1);
Tree desiredleaf2 = leaves.get(instanceid.getSecondTokenEndIndex()-1);
List<Tree> path = tree.pathNodeToNode(desiredleaf1, desiredleaf2);
path.remove(0);
path.remove(path.size()-1);
for(Tree node : path)
result += " " + node.label();
}
else //If the entities do not occur in the same sentence, the path goes all the way up to the root node from the first entity, across the root nodes of all the intervening sentences, then back down from sentence 2's root to entity 2's last word.
{
Tree tree1 = sent1.get(TreeAnnotation.class);
List<Tree> leaves1 = tree1.getLeaves();
Tree desiredleaf1 = leaves1.get(instanceid.getFirstTokenEndIndex()-1);
List<Tree> path1 = tree1.pathNodeToNode(desiredleaf1, tree1);
path1.remove(0);
Tree tree2 = sent2.get(TreeAnnotation.class);
List<Tree> leaves2 = tree2.getLeaves();
Tree desiredleaf2 = leaves2.get(instanceid.getSecondTokenEndIndex()-1);
List<Tree> path2 = tree2.pathNodeToNode(tree2, desiredleaf2);
path2.remove(path2.size()-1);
for(Tree node : path1)
result += " " + node.label();
for(int i = 1; i < secondsentencenum - firstsentencenum; i++)
result += " ROOT";
for(Tree node : path2)
result += " " + node.label();
}
return result.trim().replaceAll(" ", "-");
/*
String result = "";
if(sent1 == sent2)
{
while(pathtoroot1.get(pathtoroot1.size()-1) == pathtoroot2.get(pathtoroot2.size()-1))
{
pathtoroot1.remove(pathtoroot1.size()-1);
pathtoroot2.remove(pathtoroot2.size()-1);
}
for(Tree t : pathtoroot1)
result += " " + t.label();
result += " " + pathtoroot1.get(pathtoroot1.size()-1).parent().label();
Collections.reverse(pathtoroot2);
for(Tree t : pathtoroot2)
result += " " + t.label();
}
else
{
for(Tree t : pathtoroot1)
result += " " + t.label();
for(int i = 1; i < secondsentencenum - firstsentencenum; i++)
result += " " + pathtoroot1.get(pathtoroot1.size()-1).label();
Collections.reverse(pathtoroot2);
for(Tree t : pathtoroot2)
result += " " + t.label();
}
return result.trim().replaceAll(" ", "-");
*/
}
//Given an instance, construct a string Comprising the syntactic parse tree labels on the path between the last words in each entity.
private static String getDependencyParseTreePath(String featuretype, InstanceID instanceid, List<CoreMap> sentences)
{
//sentences is a list of the (annotated) sentences in this document. Get the sentence in which each entity appears.
int firstsentencenum = instanceid.getFirstTokenSentenceNum();
CoreMap sent1 = sentences.get(firstsentencenum);
//ArrayList<Tree> pathtoroot1 = getPathToRoot(sent1, instanceid.getFirstTokenEndIndex()-1);
int secondsentencenum = instanceid.getSecondTokenSentenceNum();
CoreMap sent2 = sentences.get(secondsentencenum);
//ArrayList<Tree> pathtoroot2 = getPathToRoot(sent2, instanceid.getSecondTokenEndIndex()-1);
String result = "";
//If the entities occur in the same sentence, the path will be directly between the two entities' last words.
if(sent1 == sent2)
{
SemanticGraph dependencies1 = sent1.get(CollapsedCCProcessedDependenciesAnnotation.class);
IndexedWord iw1 = dependencies1.getNodeByIndexSafe(instanceid.getFirstTokenEndIndex()); //The +1s are because the nodes this method looks through are 1-indexed, apparently.
IndexedWord iw2 = dependencies1.getNodeByIndexSafe(instanceid.getSecondTokenEndIndex());
List<IndexedWord> pathwords1 = dependencies1.getShortestUndirectedPathNodes(iw1, iw2);
for(int i = 1; i < pathwords1.size(); i++)
{
SemanticGraphEdge sge = dependencies1.getEdge(pathwords1.get(i-1), pathwords1.get(i));
if(sge == null)
{
sge = dependencies1.getEdge(pathwords1.get(i), pathwords1.get(i-1));
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + "<"; //E is for Edge.
}
else
{
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + ">";
}
if(i != pathwords1.size()-1)
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " N" + pathwords1.get(i).lemma().toLowerCase(); //N is for Node.
}
}
else //If the entities do not occur in the same sentence, the path goes all the way up to the root node from the first entity, across the root nodes of all the intervening sentences, then back down from sentence 2's root to entity 2's last word.
{
SemanticGraph dependencies1 = sent1.get(CollapsedCCProcessedDependenciesAnnotation.class);
IndexedWord iw1 = dependencies1.getNodeByIndexSafe(instanceid.getFirstTokenEndIndex()); //The +1s are because the nodes this method looks through are 1-indexed, apparently.
List<IndexedWord> pathwords1 = dependencies1.getPathToRoot(iw1);
for(int i = 1; i < pathwords1.size(); i++)
{
SemanticGraphEdge sge = dependencies1.getEdge(pathwords1.get(i-1), pathwords1.get(i));
if(sge == null)
{
sge = dependencies1.getEdge(pathwords1.get(i), pathwords1.get(i-1));
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + "<";
}
else
{
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + ">";
}
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " N" + pathwords1.get(i).lemma().toLowerCase();
}
for(int i = 1; i < secondsentencenum - firstsentencenum; i++)
result+= " ROOTEDGE";
SemanticGraph dependencies2 = sent2.get(CollapsedCCProcessedDependenciesAnnotation.class);
IndexedWord iw2 = dependencies2.getNodeByIndexSafe(instanceid.getSecondTokenEndIndex());
List<IndexedWord> pathwords2 = dependencies2.getPathToRoot(iw2);
Collections.reverse(pathwords2);
for(int i = 1; i < pathwords2.size(); i++)
{
SemanticGraphEdge sge = dependencies2.getEdge(pathwords2.get(i-1), pathwords2.get(i));
if(sge == null)
{
sge = dependencies2.getEdge(pathwords2.get(i), pathwords2.get(i-1));
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + "<";
}
else
{
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " E" + sge.getRelation().getShortName() + ">";
}
if(featuretype.equals(FeatureMap.DEPENDENCYPARSETREENODEPATH) || featuretype.equals(FeatureMap.DEPENDENCYPARSETREEEDGENODEPATH))
result += " N" + pathwords2.get(i-1).lemma().toLowerCase();
}
}
result = result.trim().replaceAll(" ", "-");
if(result.equals(""))
result = emptystringcode;
return result;
}
//This method constructs parse tree paths out of the instances. It is a good example of how to use annotations provided
//by the entity extractor in the .ser.gz files.
public static void writeDependencyContextFile(HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter)
{
//Read in the saved word vectors
WordToVectorMap wvm = WordToVectorMap.getWordToVectorMap(entityextractedfilename);
String currentfilename = null;
List<CoreMap> sentences = null;
InstanceID nextinstanceid;
Integer nextheuristiclabel = null;
String desiredfilename;
try
{
//We're creating these features for each relation type.
for(Integer relationtype : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
//Construct a PrintWriter that prints to the file for features of this type for this relation type.
PrintWriter out = relationtypeTocontextToprintwriter.get(relationtype).get(featuretype);
//We enforce a certain order on our instances because for sort of complicated reasons, this means we do not have
//to hold as many things in memory. So FindAndOrderAllInstances wrote a file listing all the instances we
//are interested in using, and we have to process the instances in the order provided by the file. So read
//the file it wrote to process the instances in it one-by-one.
File g = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, relationtype, training);
BufferedReader orderedinstancereader = new BufferedReader(new FileReader(g));
String nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
//While there are still more instances in the file we're reading:
while(nextinstanceid != null)
{
//There are likely to be many instances associated with each entity-annotated (.ser.gz) file. Reading
//these files is an expensive operation, so we only want to read each file once. So read file associated'
//with nextinstanceid in only if we did not already read it in.
desiredfilename = nextinstanceid.getFileName();
if(!desiredfilename.equals(currentfilename))
{
File f = new File(ProducedFileGetter.getEntityExtractedSerializedDirectory(training), desiredfilename);
Annotation deserDoc = EntityLabeler.deserializeAnnotatedDoc(f.getAbsolutePath());
//These are the annotated sentences from the entity-annotated file. They have annotations like POS
//tags and lemmas, and parse trees, and hopefully in the next version of the VM, coreference and
//dependency trees.
sentences = deserDoc.get(SentencesAnnotation.class);
currentfilename = desiredfilename;
}
//Get a string representation of the parse tree path between entities represented by nextinstanceid.
String nodepath = getDependencyParseTreePath(FeatureMap.DEPENDENCYPARSETREENODEPATH, nextinstanceid, sentences);
String[] lemmas = {};
if(!nodepath.equals(emptystringcode))
lemmas = nodepath.split("-");
ArrayList<String> context = new ArrayList<String>();
for(String lemma : lemmas)
context.add(lemma);
//Now, actually build the SVM_light style string representation of the instance.
String instanceline = buildOutputLineFromVector(nextheuristiclabel, wvm.getContextVector(context), context.size());
//Write this instance as a relation instance line consisting of only one feature (the parse tree path)
//including the heuristic label and comment extracted from the file written by FindAndOrderAllInstances.
//String comment = nextorderedinstanceline.substring(nextorderedinstanceline.indexOf('#'));
String comment = FindAndOrderAllInstances.getCommentFromLine(nextorderedinstanceline);
out.println(instanceline + " # " + comment);
//Read in the next instance from FindAndOrderAllInstances's file.
nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
}
out.close();
orderedinstancereader.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
private static String getSubPathFeaturesLine(String parsetreepath)
{
HashSet<String> features = new HashSet<String>();
String[] splitpath = parsetreepath.split("-");
for(int i = 0; i < splitpath.length; i++)
{
for(int j = i+1; j <= splitpath.length && j <= i+5; j++)
{
String feature = "";
for(int k = i; k < j; k++)
feature += " " + splitpath[k];
feature = feature.trim().replaceAll(" ", "-");
features.add(feature);
}
}
ArrayList<String> sortedfeatures = new ArrayList<String>(features);
Collections.sort(sortedfeatures);
String result = "";
for(String feature : sortedfeatures)
result += " " + feature + ":1";
return result.trim();
}
private static void writeEntityContextFile(String featuretype, HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter)
{
try
{
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile = new ZipFile(ProducedFileGetter.getEntityExtractedText(entityextractedfilename, training));
ZipEntry entry = zipfile.entries().nextElement();
BufferedReader in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile3 = new ZipFile(ProducedFileGetter.getEntityExtractedText("unlemmatized", training));
ZipEntry entry3 = zipfile3.entries().nextElement();
BufferedReader unlemmatizedalignedin = new BufferedReader(new InputStreamReader(zipfile3.getInputStream(entry3)));
InstanceID nextinstanceid;
Integer nextheuristiclabel = null;
for(Integer relationtype : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
PrintWriter out = relationtypeTocontextToprintwriter.get(relationtype).get(featuretype);
File f = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, relationtype, training);
BufferedReader orderedinstancereader = new BufferedReader(new FileReader(f));
String nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
while(nextinstanceid != null)
{
//ArrayList<InstanceID> instanceidorder = new ArrayList<InstanceID>(relationtypeToinstanceidorder.get(relationtype));
//while(instanceidorder.size() > 0)
//{
String desiredfilename = nextinstanceid.getFileName();
ArrayList<String[]> filelines = getLinesAssociatedWithOneFile(desiredfilename, in, zipfile, entry);
ArrayList<String[]> unlemmatizedfilelines = getLinesAssociatedWithOneFile(desiredfilename, unlemmatizedalignedin, zipfile3, entry3);
//These are the indices of the tokens in the original document (before we
//replaced entities with representative tokens).
ArrayList<int[]> originalindices = new ArrayList<int[]>();
for(String[] sentence : unlemmatizedfilelines)
originalindices.add(PrintPreprocessedDocuments.getOriginalTokenIndexesFromPreprocessedLine(sentence));
//Figure out which features should go with this instance.
//while(instanceidorder.size() > 0 && instanceidorder.get(0).getFileName().equals(desiredfilename))
while(nextinstanceid != null && nextinstanceid.getFileName().equals(desiredfilename))
{
int firsttokensentencenum = nextinstanceid.getFirstTokenSentenceNum();
int replacedfirsttokenindex = nextinstanceid.getReplacedFirstTokenIndex();
int secondtokensentencenum = nextinstanceid.getSecondTokenSentenceNum();
int replacedsecondtokenindex = nextinstanceid.getReplacedSecondTokenIndex();
String[] firstsentence = filelines.get(firsttokensentencenum);
String[] secondsentence = filelines.get(secondtokensentencenum);
//Figure out which words appear in the context we are interested in.
ArrayList<String> context = new ArrayList<String>();
if(featuretype.equals(FeatureMap.ENTITYBEFORECOUNTS))
{
for(int i = 0; i < replacedfirsttokenindex; i++)
context.add(firstsentence[i]);
}
if(featuretype.equals(FeatureMap.ENTITYAFTERCOUNTS))
{
for(int i = replacedsecondtokenindex+1; i < secondsentence.length; i++)
context.add(secondsentence[i]);
}
if(featuretype.equals(FeatureMap.ENTITYBETWEENCOUNTS))
{
if(firsttokensentencenum == secondtokensentencenum)
{
for(int i = replacedfirsttokenindex+1; i < replacedsecondtokenindex; i++)
context.add(firstsentence[i]);
}
else
{
for(int i = replacedfirsttokenindex+1; i < firstsentence.length; i++)
context.add(firstsentence[i]);
for(int i = 0; i < replacedsecondtokenindex; i++)
context.add(secondsentence[i]);
for(int sentencenum = firsttokensentencenum + 1; sentencenum < secondtokensentencenum; sentencenum++)
{
String[] sentence = filelines.get(sentencenum);
for(String word : sentence)
context.add(word);
}
}
}
//Count entities of each type in the set of words we collected.
HashMap<String,Integer> entitytypecounts = new HashMap<String,Integer>();
for(String word : context)
{
CyberEntityText cet = CyberEntityText.getCyberEntityTextFromToken(word);
if(cet != null)
{
String entitytypestring = CyberEntityText.entitytypeindexToentitytypename.get(cet.getEntityType());
Integer oldcount = entitytypecounts.get(entitytypestring);
if(oldcount == null)
oldcount = 0;
entitytypecounts.put(entitytypestring, oldcount+1);
}
}
String instanceline = nextheuristiclabel + "";
ArrayList<String> sortedentities = new ArrayList<String>(entitytypecounts.keySet());
Collections.sort(sortedentities);
for(String entitystring : sortedentities)
instanceline += " " + entitystring + ":" + entitytypecounts.get(entitystring);
//Now, actually build the SVM_light style string representation of the instance.
//String instanceline = buildOutputLineFromVector(nextheuristiclabel, wvm.getContextVector(context), context.size());
//Add a comment describing what the instance is about (originally written in FindAndOrderAllInstances.
//String comment = nextorderedinstanceline.substring(nextorderedinstanceline.indexOf('#'));
String comment = FindAndOrderAllInstances.getCommentFromLine(nextorderedinstanceline);
instanceline += " # " + comment;
//And finally, print it to the appropriate file using the PrintWriter we
//made earlier.
out.println(instanceline);
//}
nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
}
}
orderedinstancereader.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
private static void writeWordNgramFile(String featuretype, HashMap<Integer,HashMap<String,PrintWriter>> relationtypeTocontextToprintwriter)
{
try
{
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile = new ZipFile(ProducedFileGetter.getEntityExtractedText(entityextractedfilename, training));
ZipEntry entry = zipfile.entries().nextElement();
BufferedReader in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile3 = new ZipFile(ProducedFileGetter.getEntityExtractedText("unlemmatized", training));
ZipEntry entry3 = zipfile3.entries().nextElement();
BufferedReader unlemmatizedalignedin = new BufferedReader(new InputStreamReader(zipfile3.getInputStream(entry3)));
InstanceID nextinstanceid;
Integer nextheuristiclabel = null;
for(Integer relationtype : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
PrintWriter out = relationtypeTocontextToprintwriter.get(relationtype).get(featuretype);
File f = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, relationtype, training);
BufferedReader orderedinstancereader = new BufferedReader(new FileReader(f));
String nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
while(nextinstanceid != null)
{
//ArrayList<InstanceID> instanceidorder = new ArrayList<InstanceID>(relationtypeToinstanceidorder.get(relationtype));
//while(instanceidorder.size() > 0)
//{
String desiredfilename = nextinstanceid.getFileName();
ArrayList<String[]> filelines = getLinesAssociatedWithOneFile(desiredfilename, in, zipfile, entry);
ArrayList<String[]> unlemmatizedfilelines = getLinesAssociatedWithOneFile(desiredfilename, unlemmatizedalignedin, zipfile3, entry3);
//These are the indices of the tokens in the original document (before we
//replaced entities with representative tokens).
ArrayList<int[]> originalindices = new ArrayList<int[]>();
for(String[] sentence : unlemmatizedfilelines)
originalindices.add(PrintPreprocessedDocuments.getOriginalTokenIndexesFromPreprocessedLine(sentence));
//Figure out which features should go with this instance.
//while(instanceidorder.size() > 0 && instanceidorder.get(0).getFileName().equals(desiredfilename))
while(nextinstanceid != null && nextinstanceid.getFileName().equals(desiredfilename))
{
int firsttokensentencenum = nextinstanceid.getFirstTokenSentenceNum();
int replacedfirsttokenindex = nextinstanceid.getReplacedFirstTokenIndex();
int secondtokensentencenum = nextinstanceid.getSecondTokenSentenceNum();
int replacedsecondtokenindex = nextinstanceid.getReplacedSecondTokenIndex();
String[] firstsentence = filelines.get(firsttokensentencenum);
String[] secondsentence = filelines.get(secondtokensentencenum);
//Figure out which words appear in the context we are interested in.
ArrayList<String> context = new ArrayList<String>();
if(featuretype.equals(FeatureMap.WORDNGRAMSBEFORE))
{
for(int i = 0; i < replacedfirsttokenindex; i++)
context.add(firstsentence[i]);
}
if(featuretype.equals(FeatureMap.WORDNGRAMSAFTER))
{
for(int i = replacedsecondtokenindex+1; i < secondsentence.length; i++)
context.add(secondsentence[i]);
}
if(featuretype.equals(FeatureMap.WORDNGRAMSBETWEEN))
{
if(firsttokensentencenum == secondtokensentencenum)
{
for(int i = replacedfirsttokenindex+1; i < replacedsecondtokenindex; i++)
context.add(firstsentence[i]);
}
else
{
for(int i = replacedfirsttokenindex+1; i < firstsentence.length; i++)
context.add(firstsentence[i]);
for(int i = 0; i < replacedsecondtokenindex; i++)
context.add(secondsentence[i]);
for(int sentencenum = firsttokensentencenum + 1; sentencenum < secondtokensentencenum; sentencenum++)
{
String[] sentence = filelines.get(sentencenum);
for(String word : sentence)
context.add(word);
}
}
}
HashSet<String> featurenames = new HashSet<String>();
for(int n = 1; n <= 3; n++)
{
for(int i = 0; i < context.size(); i++)
{
String featurename = "";
for(int j = i; j < i + n && j < context.size(); j++)
featurename += " " + context.get(j).replaceAll("-", "+");
featurename = featurename.replaceAll("-", "+").trim().replaceAll(" ", "-");
featurenames.add(featurename);
}
}
ArrayList<String> sortedfeaturenames = new ArrayList<String>(featurenames);
Collections.sort(sortedfeaturenames);
String instanceline = nextheuristiclabel + "";
for(String featurename : sortedfeaturenames)
instanceline += " " + featurename+ ":1";
//Now, actually build the SVM_light style string representation of the instance.
//String instanceline = buildOutputLineFromVector(nextheuristiclabel, wvm.getContextVector(context), context.size());
//Add a comment describing what the instance is about (originally written in FindAndOrderAllInstances.
//String comment = nextorderedinstanceline.substring(nextorderedinstanceline.indexOf('#'));
String comment = FindAndOrderAllInstances.getCommentFromLine(nextorderedinstanceline);
instanceline += " # " + comment;
//And finally, print it to the appropriate file using the PrintWriter we
//made earlier.
out.println(instanceline);
//}
nextorderedinstanceline = orderedinstancereader.readLine();
if(nextorderedinstanceline == null)
nextinstanceid = null;
else
{
String[] orderedinstancesplitline = nextorderedinstanceline.split(" ");
nextinstanceid = new InstanceID(orderedinstancesplitline[2]);
nextheuristiclabel = Integer.parseInt(orderedinstancesplitline[0]);
}
}
}
orderedinstancereader.close();
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
public static String[] getInstanceAndComments(String line)
{
return line.split(" # ");
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/CalculateResults.java
package gov.ornl.stucco.relationprediction;
//This program does a grid search over the predictions made by RunRelationSVMs in order to select
//the best parameter set via 4-fold cross-validation on the training set. It then calculates results on the test set.
//It performs these steps 5 times, once for each test fold. It then micro averages and prints the results (f-score,
//precision, and recall) across all 5 test folds. It additionally prints the set of these parameters that performed
//best across the 5 folds.
//In addition to printing these results to the screen, it saves them in a file located in the
//".../relation-bootstrap/ProducedFiles/Training/ExperimentalResultsFiles" directory (which can be obtained programmatically
//via the method ProducedFileGetter.getResultsFile). The parameters that get saved in this file are used when making
//predictions for new documents with PredictUsingExistingSVMModel.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class CalculateResults
{
//This program is very expensive to run, so if this variable gets turned on, we will run it on only a subset of the available data to save time. This should be good enough to let us know if the program is working alright.
private static boolean testingprogram = false;
private static NumberFormat formatter = new DecimalFormat(".000");
private static boolean printperfoldresults = true;
private static boolean predictallpositive = false;
private static HashSet<Integer> relationshiptypes = GenericCyberEntityTextRelationship.allpositiverelationshiptypesset;
static
{
if(testingprogram)
{
relationshiptypes = new HashSet<Integer>();
relationshiptypes.add(1);
}
}
private static ParametersLine commandlineargumentconstraints = null; //Not using this yet, but we may in the future want to make it possible to put constraints on what parameters are allowable.
//private static boolean training = false;
private static String entityextractedfilename;
private static String featuretypes;
public static void main(String[] args)
{
readArgs(args);
for(int relationshiptype : relationshiptypes)
printResults(entityextractedfilename, featuretypes, relationshiptype);
}
private static void readArgs(String[] args)
{
entityextractedfilename = args[0];
featuretypes = FeatureMap.getOrderedFeatureTypes(args[1]);
for(int i = 2; i < args.length; i++)
{
if("allpositive".equals(args[i]))
predictallpositive = true;
}
}
private static void printResults(String entityextractedfilename, String featuretypes, int relationshiptype)
{
ArrayList<RelationPrediction> testpredictions = new ArrayList<RelationPrediction>();
ArrayList<ParametersLine> normalbestparameterslist = new ArrayList<ParametersLine>();
ArrayList<ParametersLine> reversebestparameterslist = new ArrayList<ParametersLine>();
ArrayList<ObjectRank> normalbestparameterslistranked = new ArrayList<ObjectRank>();
ArrayList<ObjectRank> reversebestparameterslistranked = new ArrayList<ObjectRank>();
try
{
File resultsfile = ProducedFileGetter.getResultsFile(entityextractedfilename, featuretypes, relationshiptype);
if(predictallpositive)
resultsfile = ProducedFileGetter.getResultsFile(entityextractedfilename, FeatureMap.ALWAYSPREDICTPOSITIVECODE, relationshiptype);
PrintWriter out = new PrintWriter(new FileWriter(resultsfile));
//Collect all test set instances and do a bunch of bookkeeping along the way. Simultaneously select the best set of parameters for predicting them via cross validation on the trainings set.
for(Integer testfold : RunRelationSVMs.folds)
{
if(testfold != null)
{
//Read the predictions for when the entities come in the normal order.
ParametersLine normalbestparameters = findBestParameters(commandlineargumentconstraints, entityextractedfilename, featuretypes, relationshiptype, testfold);
normalbestparameterslist.add(normalbestparameters);
ArrayList<RelationPrediction> normalpredictionstoadd = readPredictions(normalbestparameters, entityextractedfilename, featuretypes, testfold, relationshiptype, true, false);
testpredictions.addAll(normalpredictionstoadd);
{
double[] fpr = getFPRForTestInstances(normalpredictionstoadd);
double fscore = fpr[0];
normalbestparameterslistranked.add(new ObjectRank(normalbestparameters, fscore));
}
//Add the predictions for when the entities come in the reverse order.
ParametersLine reversebestparameters = findBestParameters(commandlineargumentconstraints, entityextractedfilename, featuretypes, GenericCyberEntityTextRelationship.getReverseRelationshipType(relationshiptype), testfold);
reversebestparameterslist.add(reversebestparameters);
ArrayList<RelationPrediction> reversepredictionstoadd = readPredictions(reversebestparameters, entityextractedfilename, featuretypes, testfold, relationshiptype, true, false);
testpredictions.addAll(reversepredictionstoadd);
testpredictions.addAll(normalpredictionstoadd);
{
double[] fpr = getFPRForTestInstances(reversepredictionstoadd);
double fscore = fpr[0];
reversebestparameterslistranked.add(new ObjectRank(reversebestparameters, fscore));
}
//If we want to print results for each fold, do it.
if(printperfoldresults)
{
ArrayList<RelationPrediction> onefoldresults = new ArrayList<RelationPrediction>(normalpredictionstoadd);
onefoldresults.addAll(reversepredictionstoadd);
double[] fpr = getFPRForTestInstances(onefoldresults);
if(predictallpositive)
fpr = getFPRForPredictAllPositive(onefoldresults);
double fscore = fpr[0];
double precision = fpr[1];
double recall = fpr[2];
String onefoldresultline = relationshiptype + "\t" + formatter.format(fscore) + "\t" + formatter.format(precision) + "\t" + formatter.format(recall) + "\t" + normalbestparameters+ "\t" + reversebestparameters;
System.out.println(onefoldresultline);
out.println(onefoldresultline);
}
}
}
//Calculate the results for the entire test set.
double[] fpr = getFPRForTestInstances(testpredictions);
if(predictallpositive)
fpr = getFPRForPredictAllPositive(testpredictions);
double fscore = fpr[0];
double precision = fpr[1];
double recall = fpr[2];
//Choose the set of parameters that got the highest f-score.
Collections.sort(normalbestparameterslistranked);
ParametersLine bestnormalparametersline = (ParametersLine)normalbestparameterslistranked.get(normalbestparameterslistranked.size()-1).obj;
Collections.sort(reversebestparameterslistranked);
ParametersLine bestreverseparametersline = (ParametersLine)reversebestparameterslistranked.get(reversebestparameterslistranked.size()-1).obj;
String outputline = relationshiptype + "\t" + formatter.format(fscore) + "\t" + formatter.format(precision) + "\t" + formatter.format(recall) + "\t" + bestnormalparametersline + "\t" + bestreverseparametersline;
System.out.println(outputline);
//Also print it to a file because we'll want to retrieve the best parameters for making predictions on unknown relationships.
out.println(outputline);
out.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
private static ParametersLine findBestParameters(ParametersLine cmdlineargconstraints, String entityextractedfilename, String featuretypes, int relationshiptype, Integer testfold)
{
ArrayList<ParametersLine> allparameters = getAllParameters(cmdlineargconstraints, entityextractedfilename, featuretypes, relationshiptype);
double bestfscore = Double.NEGATIVE_INFINITY;
ParametersLine bestfscoreparams = null;
for(ParametersLine currentparameters : allparameters)
{
ArrayList<RelationPrediction> developmentpredictions = readPredictions(currentparameters, entityextractedfilename, featuretypes, testfold, relationshiptype, true, true);
double TPs = 0.;
double FPs = 0.;
double FNs = 0.;
for(RelationPrediction instance : developmentpredictions)
{
int tpfptnfncode = instance.getTPorFPorTNorFN();
if(tpfptnfncode == RelationPrediction.TPindex)
TPs++;
else if(tpfptnfncode == RelationPrediction.FPindex)
FPs++;
else if(tpfptnfncode == RelationPrediction.FNindex)
FNs++;
}
double fscore = getFscore(TPs, FPs, FNs);
//double precision = getPrecision(TPs, FPs);
//double recall = getRecall(TPs, FNs);
if(fscore > bestfscore)
{
bestfscore = fscore;
bestfscoreparams = currentparameters;
}
}
return bestfscoreparams;
}
private static ArrayList<ParametersLine> getAllParameters(ParametersLine cmdlineargconstraints, String entityextractedfilename, String featuretypes, int relationshiptype)
{
ArrayList<ParametersLine> allparameters = new ArrayList<ParametersLine>();
try
{
File resultsfile = ProducedFileGetter.getPredictionsFile(entityextractedfilename, featuretypes, relationshiptype, true);
BufferedReader in = new BufferedReader(new FileReader(resultsfile));
String line;
while((line = in.readLine()) != null)
{
if(ParametersLine.isParametersLine(line))
{
ParametersLine current = new ParametersLine(line, false);
if(cmdlineargconstraints == null || current.matchesConstraints(cmdlineargconstraints))
{
boolean foundmatch = false;
for(ParametersLine pl : allparameters)
{
if(current.exactlyMatches(pl))
foundmatch = true;
}
if(!foundmatch)
allparameters.add(current);
}
}
}
in.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return allparameters;
}
//development should be sent true if we want development predictions, and false if we want test predictions.
private static ArrayList<RelationPrediction> readPredictions(ParametersLine currentparameters, String entityextractedfilename, String featuretypes, Integer testfold, int relationshiptype, boolean training, boolean development)
{
ArrayList<RelationPrediction> results = new ArrayList<RelationPrediction>();
try
{
File resultsfile = ProducedFileGetter.getPredictionsFile(entityextractedfilename, featuretypes, relationshiptype, training);
boolean developmentstate = false;
boolean teststate = false;
BufferedReader in = new BufferedReader(new FileReader(resultsfile));
String line;
while((line = in.readLine()) != null)
{
if(ParametersLine.isParametersLine(line))
{
developmentstate = false; //by default, states are false, so reset it.
teststate = false;
ParametersLine pl = new ParametersLine(line, false);
if(pl.exactlyMatches(currentparameters))
{
Integer resultfold = pl.getResultsFold();
Integer excludedfold1 = pl.getExcludedFold1();
Integer excludedfold2 = pl.getExcludedFold2();
if(resultfold != testfold) //Every fold other than the test fold is used for development.
{
if(excludedfold1 == testfold || excludedfold2 == testfold) //A fold's results should be included in the development set only if the test fold was not used in training.
developmentstate = true;
}
if(resultfold == testfold) //We want test fold results.
{
if(excludedfold1 == testfold && excludedfold2 == testfold)
teststate = true;
}
}
}
else
{
if(developmentstate && development)
results.add(new RelationPrediction(line));
if(teststate && !development)
results.add(new RelationPrediction(line));
}
}
in.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return results;
}
public static double getFscore(double tp, double fp, double fn)
{
double numerator = 2 * tp;
double denominator = (2 * tp) + fp + fn;
if(denominator == 0.)
return 0.;
return numerator / denominator;
}
public static double getPrecision(double tp, double fp)
{
if(tp + fp == 0.)
return 0.;
return tp / (tp + fp);
}
public static double getRecall(double tp, double fn)
{
if(tp + fn == 0.)
return 0.;
return tp / (tp + fn);
}
public static double[] getFPRForTestInstances(ArrayList<RelationPrediction> predictions)
{
double TPs = 0.;
double FPs = 0.;
double FNs = 0.;
for(int i = 0; i < predictions.size(); i++)
{
RelationPrediction instance = predictions.get(i);
int tpfptnfncode = instance.getTPorFPorTNorFN();
if(tpfptnfncode == RelationPrediction.TPindex)
TPs++;
else if(tpfptnfncode == RelationPrediction.FPindex)
FPs++;
else if(tpfptnfncode == RelationPrediction.FNindex)
FNs++;
}
double fscore = getFscore(TPs, FPs, FNs);
double precision = getPrecision(TPs, FPs);
double recall = getRecall(TPs, FNs);
double[] result = {fscore, precision, recall};
return result;
}
public static double[] getFPRForPredictAllPositive(ArrayList<RelationPrediction> predictions)
{
double TPs = 0.;
double FPs = 0.;
double FNs = 0.;
double TNs = 0.;
for(int i = 0; i < predictions.size(); i++)
{
RelationPrediction instance = predictions.get(i);
int tpfptnfncode = instance.getTPorFPorTNorFN();
if(tpfptnfncode == RelationPrediction.TPindex)
TPs++;
else if(tpfptnfncode == RelationPrediction.FPindex)
FPs++;
else if(tpfptnfncode == RelationPrediction.FNindex)
FNs++;
else if(tpfptnfncode == RelationPrediction.TNindex)
TNs++;
}
double allpositiveTPs = TPs + FNs;
double allpositiveFPs = FPs + TNs;
double allpositiveFNs = 0.;
double fscore = getFscore(allpositiveTPs, allpositiveFPs, allpositiveFNs);
double precision = getPrecision(allpositiveTPs, allpositiveFPs);
double recall = getRecall(allpositiveTPs, allpositiveFNs);
double[] result = {fscore, precision, recall};
return result;
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/CyberEntityText.java
package gov.ornl.stucco.relationprediction;
//This class stores information about the text of some entity that has been identified. It stores the text and the predicted
//entity type. There are a bunch of static maps here that map things like the entity type constants near the top to
//string versions of them. I also manually figured out what order the entity type probabilities are outputted in, so there
//is a map for converting those indices to one of the entity type integer constants at the top.
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Collections;
public class CyberEntityText
{
public static final int SWPRODUCT = 0;
public static final int VUDESCRIPTION = 1;
public static final int O = 2;
public static final int SWVERSION = 3;
public static final int FUNAME = 4;
public static final int SWVENDOR = 5;
public static final int VUNAME = 6;
public static final int VUCVE = 7;
public static final int VUMS = 8;
public static final int FINAME = 9;
public static final int ENTITYTYPECOUNT = 10;
public static HashMap<String,Integer> entitytypenameToentitytypeindex = new HashMap<String,Integer>();
static
{
entitytypenameToentitytypeindex.put("sw.product", SWPRODUCT);
entitytypenameToentitytypeindex.put("sw.version", SWVERSION);
entitytypenameToentitytypeindex.put("vuln.description", VUDESCRIPTION);
entitytypenameToentitytypeindex.put("function.name", FUNAME);
entitytypenameToentitytypeindex.put("sw.vendor", SWVENDOR);
entitytypenameToentitytypeindex.put("vu.name", VUNAME);
entitytypenameToentitytypeindex.put("vu.cve", VUCVE);
entitytypenameToentitytypeindex.put("vu.ms", VUMS);
entitytypenameToentitytypeindex.put("file.name", FINAME);
entitytypenameToentitytypeindex.put("O", O);
}
public static HashMap<Integer,String> entitytypeindexToentitytypename = new HashMap<Integer,String>();
static
{
entitytypeindexToentitytypename.put(SWPRODUCT, "sw.product");
entitytypeindexToentitytypename.put(SWVERSION, "sw.version");
entitytypeindexToentitytypename.put(VUDESCRIPTION, "vuln.description");
entitytypeindexToentitytypename.put(FUNAME, "function.name");
entitytypeindexToentitytypename.put(SWVENDOR, "sw.vendor");
entitytypeindexToentitytypename.put(VUNAME, "vuln.name");
entitytypeindexToentitytypename.put(VUCVE, "vuln.cve");
entitytypeindexToentitytypename.put(VUMS, "vuln.ms");
entitytypeindexToentitytypename.put(FINAME, "file.name");
entitytypeindexToentitytypename.put(O, "O");
}
private String entitytext;
private int entitytype;
//The entity learner outputs predictions for each token belonging to each entity type as a probability array.
//These are the entity types the indices of the probability array correspond to (discovered experimentally).
public static HashMap<Integer,String> probabilityindexToentitytypestring = new HashMap<Integer,String>();
static
{
probabilityindexToentitytypestring.put(0,"sw.product");
probabilityindexToentitytypestring.put(1,"vuln.description");
probabilityindexToentitytypestring.put(2,"O");
probabilityindexToentitytypestring.put(3,"sw.version");
probabilityindexToentitytypestring.put(4,"function.name");
probabilityindexToentitytypestring.put(5,"sw.vendor");
}
public static HashMap<String,Integer> entitytypestringToprobabilityindex = new HashMap<String,Integer>();
static
{
entitytypestringToprobabilityindex.put("sw.product", 0);
entitytypestringToprobabilityindex.put("vuln.description", 1);
entitytypestringToprobabilityindex.put("O", 2);
entitytypestringToprobabilityindex.put("sw.version", 3);
entitytypestringToprobabilityindex.put("function.name", 4);
entitytypestringToprobabilityindex.put("sw.vendor", 5);
}
public static HashMap<Integer,Integer> probabilityindexToentitytypeindex = new HashMap<Integer,Integer>();
static
{
probabilityindexToentitytypeindex.put(0, SWPRODUCT);
probabilityindexToentitytypeindex.put(1, VUDESCRIPTION);
probabilityindexToentitytypeindex.put(2, O);
probabilityindexToentitytypeindex.put(3, SWVERSION);
probabilityindexToentitytypeindex.put(4, FUNAME);
probabilityindexToentitytypeindex.put(5, SWVENDOR);
}
public CyberEntityText(String entitytext, int entitytype)
{
this.entitytext = entitytext;
this.entitytype = entitytype;
}
public int getEntityType()
{
return entitytype;
}
public String getEntityText()
{
return entitytext;
}
public String getEntitySpacedText()
{
return getEntitySpacedText(entitytext);
}
public static String getEntitySpacedText(String entitytext)
{
if(entitytext.startsWith("["))
{
String result = entitytext.toLowerCase();
if(result.contains("_"))
{
result = result.substring(result.indexOf('_')+1, result.length()-1);
result = result.replaceAll("_", " ");
result = result.trim();
return result;
}
}
return entitytext;
}
//Return the best label according to the probability array unless the best label is O.
//If the best label is O, return the second best label if its value exceeds Othreshold.
//If the second best label's value does not exceed Othreshold, return O.
public static int getTypeOfHighestProbabilityIndex(double[] probabilities, double Othreshold)
{
ArrayList<ObjectRank> ors = new ArrayList<ObjectRank>();
for(int i = 0; i < probabilities.length; i++)
ors.add(new ObjectRank(i, probabilities[i]));
Collections.sort(ors);
ObjectRank bestrankedprob = ors.get(ors.size()-1);
int bestentitytype = probabilityindexToentitytypeindex.get((Integer)bestrankedprob.obj);
if(bestentitytype != O)
return bestentitytype;
else
{
ObjectRank secondbestrankedprob = ors.get(ors.size()-2);
if(secondbestrankedprob.value >= Othreshold)
{
int secondbestentitytype = probabilityindexToentitytypeindex.get((Integer)secondbestrankedprob.obj);
return secondbestentitytype;
}
else
return O;
}
}
//If the token looks like a cyber entity token, return a CyberEntityText. Otherwise, return null.
public static CyberEntityText getCyberEntityTextFromToken(String token)
{
int entitytype = getEntityTypeFromToken(token);
if(entitytype == O)
return null;
else
return new CyberEntityText(token, entitytype);
}
//Tokens from preprocessed documents are formatted in a certain way. Particularly, if the token
//is a cyber entity (as detected by the cyber entity detector), it will start with
//[entity.type_word1_word2...]. If the token is not a cyber entity, there is no special formatting.
//This method returns the constant integer associated with the given entity's type, provided it is
//a cyber entity. Otherwise, if it is not formatted like a cyber entity, it returns type O (the
//non-entity type).
public static int getEntityTypeFromToken(String token)
{
if(token.charAt(0) != '[')
return O;
int indexoffirstspace = token.indexOf('_');
if(indexoffirstspace == -1 && token.charAt(token.length()-1) == ']')
indexoffirstspace = token.length()-1;
if(indexoffirstspace <= 0)
return O;
String tokenlabel = token.substring(1, indexoffirstspace);
Integer result = entitytypenameToentitytypeindex.get(tokenlabel);
if(result == null)
return O;
return result;
}
public static String getCanonicalName(String name, int entitytype)
{
ArrayList<Vulnerability> vulnerabilities;
String result = name;
String holder;
switch (entitytype)
{
case O:
break;
case FUNAME:
break;
case FINAME:
break;
case VUCVE:
break;
case VUMS:
vulnerabilities = Vulnerability.getVulnerabilitiesWithMSid(name);
if(vulnerabilities.size() == 1)
result = vulnerabilities.get(0).getCanonicalName();
break;
case VUNAME:
vulnerabilities = Vulnerability.getVulnerabilitiesWithName(name);
if(vulnerabilities.size() == 1)
result = vulnerabilities.get(0).getCanonicalName();
break;
case VUDESCRIPTION:
break;
case SWPRODUCT:
holder = SoftwareWVersion.getCanonicalSoftwareAlias(name);
if(holder != null)
result = holder;
break;
case SWVENDOR:
holder = SoftwareWVersion.getCanonicalVendorAlias(name);
if(holder != null)
result = holder;
break;
case SWVERSION:
break;
default:
System.err.println("Invalid Entity Type: " + entitytype);
break;
}
return result;
}
public String toString()
{
return entitytext;
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/FeatureMap.java
package gov.ornl.stucco.relationprediction;
//This class stores a map of feature names to IDs (hence, why it extends HashMap<String,Integer>). It allows the construction
//of such a map through its getIndex(), which returns the ID (Integer) associated with that feature if it is already
//in the map. If it is not already in the map, it adds the feature to the map and returns the ID assigned to it.
//
//There are a lot of String constants at the top. Each one is associated with one feature type I have created.
//When one of the command line arguments calls for a feature type or a list of feature types, these strings are what
//should be given to it. The first step in adding a new feature type is to assign the new feature type a String
//constant like those in this class. The second step is to add an if statement to WriteRelationInstanceFiles to
//direct the program’s flow to a new method (which you will create) for writing the instances to a new file alongside your
//new feature type.
//Of course, the details of how to create features of your new type will vary greatly depending on what the feature is
//meant to encode. See WriteRelationInstance.writeParseTreePathFile for an example of a method that writes features using
//the .ser.gz (entity-extracted) file associated with each instance, or see WriteRelationInstanceFiles.writeContextFile
//for an example of a method that writes features using the preprocessed file written by PrintPreprocessedDocuments.
import java.util.*;
import edu.stanford.nlp.io.EncodingPrintWriter.out;
import java.io.*;
public class FeatureMap extends HashMap<String,Integer>
{
//In the presentation, abcd was the baseline feature set, and abcdefgmnopqr was the complete feature set.
public static final String WORDEMBEDDINGBEFORECONTEXT = "a"; //Context before the first entity as encoded via averaging the words' word2vec vectors. Also one feature counting the tokens before the first entity.
public static final String WORDEMBEDDINGBETWEENCONTEXT = "b"; //Context between entities as encoded via averaging the words' word2vec vectors. Also one feature counting the tokens between the entities.
public static final String WORDEMBEDDINGAFTERCONTEXT = "c"; //Context after second entity as encoded via averaging the words' word2vec vectors. Also one feature counting the tokens after the last entity.
//Note that it probably makes more sense to separate the context lengths into a separate feature type, if you need some busy work.
public static final String SYNTACTICPARSETREEPATH = "d"; //String of syntactic parse tree node labels between entities. Entities are represented by their last word.
public static final String DEPENDENCYPARSETREEEDGEPATH = "e"; //String of dependency tree edge labels between entities. Directions are included in the label (e.g. an nsubj edge that goes left to right is encoded like >nsubj, while an nsubj edge going the opposite direction is encoded like <nsubj. Entities are represented by their last word.
public static final String DEPENDENCYPARSETREENODEPATH = "f"; //String of dependency tree node lemmas between entities. Entities are represented by their last word.
public static final String DEPENDENCYPARSETREEEDGENODEPATH = "g"; //String of directed dependency tree edge labels and node lemmas between entities. The string alternates between edges (grammatical relationships) and nodes (word lemmas). Entities are represented by their last word.
public static final String DEPENDENCYPARSETREENODECONTEXTS = "h"; //Collect the node lemmas in the dependency path between the cyber entities, then make an embedding feature from them just as with the word embedding context features.
//A path is a sequence of items. To generate these subpath features, we simply take the corresponding path feature from above
//and build features out of all possible contiguous subsequences (of length up to 5) of items from the list.
public static final String SYNTACTICPARSETREESUBPATHS = "i";
public static final String DEPENDENCYPARSETREEEDGESUBPATHS = "j";
public static final String DEPENDENCYPARSETREENODESUBPATHS = "k";
public static final String DEPENDENCYPARSETREEEDGENODESUBPATHS = "l";
//Counts of entities of all types appearing in different parts of the text. There is a separate count feature for each entity type.
//Note that the entities participating in the candidate relationship are not included in any of these.
public static final String ENTITYBEFORECOUNTS = "m";
public static final String ENTITYBETWEENCOUNTS = "n";
public static final String ENTITYAFTERCOUNTS = "o";
//(lemmatized) word n-grams of length 1, 2, and 3 appearing before, between, and after the entities. These are binary features rather than counts. These are intended as baseline features.
public static final String WORDNGRAMSBEFORE = "p";
public static final String WORDNGRAMSBETWEEN = "q";
public static final String WORDNGRAMSAFTER = "r";
public static final String ALWAYSPREDICTPOSITIVECODE = "z"; //Warning. This is not a code that ever gets used in a command line arguments. It is merely used internally to determine which file to write positive prediction results to.
public static final String FEATUREMAPPREFIX = "FeatureMap";
private int featurecounter;
private HashMap<Integer,String> index2feature;
private HashMap<Integer,String> index2type;
FeatureMap()
{
featurecounter = 1;
index2feature = new HashMap<Integer,String>();
index2type = new HashMap<Integer,String>();
}
FeatureMap(String entityextractedfilename, String featuretypes, int relationtype)
{
try
{
File featuremapfile = ProducedFileGetter.getFeatureMapFile(entityextractedfilename, featuretypes, relationtype);
index2feature = new HashMap<Integer,String>();
index2type = new HashMap<Integer,String>();
BufferedReader in = new BufferedReader(new FileReader(featuremapfile));
String line;
while((line = in.readLine()) != null)
{
String[] indexAndtypecolonname = line.split("\t");
String typecolonname = indexAndtypecolonname[1];
int index = Integer.parseInt(indexAndtypecolonname[0]);
String type = typecolonname.substring(0, typecolonname.indexOf(':'));
//String type;
//if(beforecolon.contains("."))
// type = beforecolon.substring(0, beforecolon.indexOf('.'));
//else
// type = beforecolon;
String name = typecolonname;
index2feature.put(index, name);
index2type.put(index, type);
}
in.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
public int getIndex(String featurename, String featuretype)
{
Integer result = get(featurename);
if(result == null)
{
result = featurecounter++;
put(featurename, result);
index2feature.put(result, featurename);
index2type.put(result, featuretype);
}
return result;
}
public String getFeature(int index)
{
return index2feature.get(index);
}
public String getCode(int index)
{
return index2type.get(index);
}
public HashMap<Integer,String> getIndex2Type()
{
return index2type;
}
public String getType(Integer index)
{
return index2type.get(index);
}
public static String getOrderedFeatureTypes(String featuretypes)
{
HashSet<String> featuretypeset = new HashSet<String>();
for(int i = 0; i < featuretypes.length(); i++)
featuretypeset.add(featuretypes.charAt(i) + "");
ArrayList<String> featuretypelist = new ArrayList<String>(featuretypeset);
Collections.sort(featuretypelist);
String result = "";
for(String featuretype : featuretypelist)
result += featuretype;
return result;
}
public static String getCommaSeparatedOrderedFeatureTypes(String featuretypes)
{
ArrayList<String> featuretypelist = new ArrayList<String>();
String[] featuretypesarray = featuretypes.split(",");
for(String featuretype : featuretypesarray)
featuretypelist.add(featuretype);
Collections.sort(featuretypelist);
String result = "";
for(String featuretype : featuretypelist)
result += " " + featuretype;
result = result.trim();
result = result.replaceAll(" ", ",");
return result;
}
//This method reads all the training instance files associated with a particular entityextracted type and each feature type
//and maps each feature to a unique integer in a new FeatureMap.
//Warning: It is very important that the same training instances are written to entityextracted when the feature map
//is first constructed (in Run RelationSVMs
public static FeatureMap constructFeatureMap(String entityextractedfilename, String featuretypes, int relationtype)
{
FeatureMap featuremap = new FeatureMap();
for(int i = 0; i < featuretypes.length(); i++)
{
String featuretype = featuretypes.charAt(i) + "";
File relationinstancesfile = ProducedFileGetter.getRelationshipSVMInstancesFile(entityextractedfilename, featuretype, relationtype, true);
try
{
BufferedReader in = new BufferedReader(new FileReader(relationinstancesfile));
String instanceline;
while((instanceline = in.readLine()) != null)
{
if(PrintPreprocessedDocuments.isLineBetweenDocuments(instanceline) || PrintPreprocessedDocuments.isFileNameLine(instanceline))
continue;
String[] splitline = instanceline.split("#");
String[] classAndfeatures = splitline[0].trim().split(" ");
for(int j = 1; j < classAndfeatures.length; j++)
{
String featurenameAndvalue = classAndfeatures[j];
String featurename = featurenameAndvalue.substring(0, featurenameAndvalue.lastIndexOf(':'));
//double value = Double.parseDouble(featurenameAndvalue.substring(featurenameAndvalue.lastIndexOf(':')+1));
featurename = featuretype + ":" + featurename;
featuremap.getIndex(featurename, featuretype); //Just by getting the index, we add the feature to the map. So don't need to do anything with it.
}
}
in.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
return featuremap;
}
public void writeAsFile(String entityextractedfilename, String featuretypes, int relationtype)
{
try
{
File f = ProducedFileGetter.getFeatureMapFile(entityextractedfilename, featuretypes, relationtype);
PrintWriter out = new PrintWriter(new FileWriter(f));
ArrayList<Integer> allfeatureids = new ArrayList<Integer>(values());
Collections.sort(allfeatureids);
for(Integer featureid : allfeatureids)
out.println(featureid + "\t" + index2feature.get(featureid));
out.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
}<file_sep>/src/gov/ornl/stucco/relationprediction/FindAndOrderAllInstances.java
package gov.ornl.stucco.relationprediction;
/*
* The purpose of this program is to find all instances of all relationships we are interested
* in using (from either the training or test data, depending on which command line arguments
* are given), and write them to a file. Then, when we write the instances to a file
* (in WriteRelationInstances), we can ensure that all features will write their instances
* in the same order, which means we can read all of these instance files for all features
* we are interested in at once when running RunRelationSVMs, rather than keeping some information
* in memory and trying to align the files after the fact.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class FindAndOrderAllInstances
{
private static String entityextractedfilename;
private static boolean training = false;
public static void main(String[] args)
{
readArgs(args);
HashMap<Integer,PrintWriter> relationToprintwriter = initializePrintWriters();
try
{
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile = new ZipFile(ProducedFileGetter.getEntityExtractedText(entityextractedfilename, training));
ZipEntry entry = zipfile.entries().nextElement();
BufferedReader in = new BufferedReader(new InputStreamReader(zipfile.getInputStream(entry)));
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile2 = new ZipFile(ProducedFileGetter.getEntityExtractedText("aliasreplaced", training));
ZipEntry entry2 = zipfile2.entries().nextElement();
BufferedReader aliasreplacedalignedin = new BufferedReader(new InputStreamReader(zipfile2.getInputStream(entry2)));
//We are switching to using zip files for these because they could potentially be very big.
ZipFile zipfile3 = new ZipFile(ProducedFileGetter.getEntityExtractedText("unlemmatized", training));
ZipEntry entry3 = zipfile3.entries().nextElement();
BufferedReader unlemmatizedalignedin = new BufferedReader(new InputStreamReader(zipfile3.getInputStream(entry3)));
//int linecounter = 0; //Keep track of the number of the line we are on in the file. We'll make a note of what line our instances come from in this way.
int sentencecounter = 0;
String currentfilename = null;
//Each line in this file is a single sentence. Relationships can only be extracted if both
//participating entities appear in the same sentence. We do not do coreference resolution,
//so each entity must be mentioned by name (it cannot be replaced with a pronoun).
String line;
while((line = in.readLine()) != null)
{
//Read the corresponding line from the alias replaced text file.
String aliasedline = aliasreplacedalignedin.readLine();
String unlemmatizedline = unlemmatizedalignedin.readLine();
//linecounter++;
//The text files contain a blank line between documents. Just ignore them.
if(line.length() == 0)
continue;
if(line.startsWith("###") && line.endsWith("###"))
{
currentfilename = line.substring(3, line.length()-3);
sentencecounter = 0;
continue;
}
//These are the indices of the tokens in the original document (before we
//replaced entities with representative tokens).
int[] originalindices = PrintPreprocessedDocuments.getOriginalTokenIndexesFromPreprocessedLine(unlemmatizedline.split(" "));
//Recall that, in the input file, a cyber entity is compressed into one token,
//even though in the source text, it may have been several tokens long.
String[] tokens = line.split(" ");
//And keep track of the alias replaced tokens the normal tokens correspond to.
String[] aliasreplacedtokens = aliasedline.split(" ");
String[] unlemmatizedtokens = unlemmatizedline.split(" ");
//The text file we are reading is already annotated with cyber entities.
//Here, we are constructing an array of CyberEntityTexts parallel to
//the tokens array that tells us the token's Cyber entity label (if it has one).
CyberEntityText[] cyberentitytexts = new CyberEntityText[tokens.length];
CyberEntityText[] aliasedcyberentitytexts = new CyberEntityText[tokens.length];
CyberEntityText[] unlemmatizedcyberentitytexts = new CyberEntityText[tokens.length];
for(int i = 0; i < tokens.length; i++)
{
cyberentitytexts[i] = CyberEntityText.getCyberEntityTextFromToken(tokens[i]);
aliasedcyberentitytexts[i] = CyberEntityText.getCyberEntityTextFromToken(aliasreplacedtokens[i]);
unlemmatizedcyberentitytexts[i] = CyberEntityText.getCyberEntityTextFromToken(unlemmatizedtokens[i]);
}
//Now, we scan through each pair of tokens. If both are cyber entities...
for(int i = 0; i < tokens.length; i++)
{
if(cyberentitytexts[i] != null)
{
for(int j = i+1; j < tokens.length; j++)
{
if(cyberentitytexts[j] != null)
{
//...we construct a relationship instance from them.
GenericCyberEntityTextRelationship relationship = new GenericCyberEntityTextRelationship(cyberentitytexts[i], cyberentitytexts[j]);
GenericCyberEntityTextRelationship aliasedrelationship = new GenericCyberEntityTextRelationship(aliasedcyberentitytexts[i], aliasedcyberentitytexts[j]);
GenericCyberEntityTextRelationship unlemmatizedrelationship = new GenericCyberEntityTextRelationship(unlemmatizedcyberentitytexts[i], unlemmatizedcyberentitytexts[j]);
//Any pair of entities of any types can be used to construct a relationship instance.
//But we only care about a subset of all possible relationship types. In particular,
//we care about the relationships ennumerated at the top of GenericCyberEntityTextRelationship
//(or their reverses, where the entities appear in the reverse of the normal order
//in the text). So check if this entity pair's relationship type is one of the
//types we care about. Since we only built print writers for the types we cared about
//earlier in the program, we check for this condition by checking if we constructed a
//PrintWriter for this relationship.
Integer relationtype = aliasedrelationship.getRelationType();
if(relationtype != null)
{
//If we do care about this relationship type, check whether
//we can label this relationship confidently enough to
//use it as a training instance.
//(There is a comment above GenericCyberEntityTextRelationship.isKnownRelationship()
//explaining our rules for making this determination.)
//Use the aliased version of the relationship to check for this because
//its contents are easiest to align with known entities.
//Boolean isknownrelationship = relationship.isKnownRelationship();
Boolean isknownrelationship = aliasedrelationship.isKnownRelationship();
if(!(training && isknownrelationship == null)) //Do not bother to write instances with 0 labels. isknownrelationship == null if the label would be 0 (we don't know the label).
{
InstanceID instanceid = new InstanceID(currentfilename, sentencecounter, i, originalindices[i], originalindices[i+1], sentencecounter, j, originalindices[j], originalindices[j+1]);
int replacedfirsttokenindex = instanceid.getReplacedFirstTokenIndex();
int replacedsecondtokenindex = instanceid.getReplacedSecondTokenIndex();
//String[] firstsentence = filelines.get(firsttokensentencenum);
String[] firstsentence = tokens;
//String[] firsttokenunlemmatizedsentence = unlemmatizedfilelines.get(firsttokensentencenum);
String[] firsttokenunlemmatizedsentence = unlemmatizedtokens;
//String[] secondsentence = filelines.get(secondtokensentencenum);
String[] secondsentence = tokens;
//String[] secondtokenunlemmatizedsentence = unlemmatizedfilelines.get(secondtokensentencenum);
String[] secondtokenunlemmatizedsentence = unlemmatizedtokens;
String label;
if(isknownrelationship == null)
label = "0";
else if(isknownrelationship)
label = "1";
else
label = "-1";
if(training)
relationToprintwriter.get(relationtype).println(label + " # " + instanceid);
else
relationToprintwriter.get(relationtype).println(label + " # " + instanceid + " " + firsttokenunlemmatizedsentence[replacedfirsttokenindex] + " " + firstsentence[replacedfirsttokenindex] + " " + secondtokenunlemmatizedsentence[replacedsecondtokenindex] + " " + secondsentence[replacedsecondtokenindex] + " " + unlemmatizedline.trim());
}
}
}
}
}
}
sentencecounter++;
}
in.close();
aliasreplacedalignedin.close();
unlemmatizedalignedin.close();
zipfile.close();
zipfile2.close();
zipfile3.close();
for(PrintWriter pw : relationToprintwriter.values())
pw.close();
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
}
//Arguments:
//1. extractedfilename (This is the name of the file written by PrintPreprocessedDocuments.
//Valid known values for this argument are "original", "entityreplaced", and "aliasreplaced")
//2. training (optional). If you include the word "training" in your command line arguments
//after the first two (required) feature types, training files (based on the .ser.gz contents
//of Training DataFiles directory) will be written. Else testing files (based on the .ser.gz
//contents of Testing DataFiles directory) will be written.
private static void readArgs(String[] args)
{
entityextractedfilename = args[0];
for(int i = 1; i < args.length; i++)
{
if("training".equals(args[i]))
training = true;
}
}
private static HashMap<Integer,PrintWriter> initializePrintWriters()
{
HashMap<Integer,PrintWriter> relationtypeToprintwriter = new HashMap<Integer,PrintWriter>();
try
{
for(Integer i : GenericCyberEntityTextRelationship.getAllRelationshipTypesSet())
{
File f = ProducedFileGetter.getRelationshipSVMInstancesOrderFile(entityextractedfilename, i, training);
relationtypeToprintwriter.put(i, new PrintWriter(new FileWriter(f)));
}
}catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
System.exit(3);
}
return relationtypeToprintwriter;
}
public static String getCommentFromLine(String line)
{
return line.split(" # ")[1];
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/yml/YmlFileEntry.java
package gov.ornl.stucco.relationprediction.yml;
import java.util.Iterator;
import java.util.HashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class YmlFileEntry
{
private static HashMap<String,String> sourcetypeToymltype = new HashMap<String,String>();
static
{
sourcetypeToymltype.put("RSS", "RSS");
sourcetypeToymltype.put("rss", "RSS");
sourcetypeToymltype.put("Atom", "RSS");
sourcetypeToymltype.put("atom", "RSS");
sourcetypeToymltype.put("web", "WEB");
//sourcetypeToymltype.put("file", "FILEBYLINE");
sourcetypeToymltype.put("file", "WEB");
}
private String name;
private String url;
private String sourcetype;
private String category;
YmlFileEntry(JSONObject obj)
{
name = (String)obj.get("name");
url = (String)obj.get("url");
if(url.startsWith("www")) //Some urls in the sources.json file just start with "www.".
url = "http://" + url;
//obj.get("location");
sourcetype = (String)obj.get("type");
//obj.get("description");
//JSONArray tags = (JSONArray)obj.get("tags");
//obj.get("investigating");
//JSONArray nodes = (JSONArray)obj.get("nodes");
category = (String)obj.get("category");
//obj.get("priority");
}
public String getName()
{
return name;
}
public boolean isWorkingType()
{
return category.equals("news") || category.equals("articles") || category.equals("vendor alerts");
//vulnerabilities, malware
//if(!category.equals("news") && !category.equals("articles") && !category.equals("vendor alerts"))
// return false;
//
//return true;
}
public String getYmlType()
{
return sourcetypeToymltype.get(sourcetype);
}
/*
public String getStructuredOrUnstructured()
{
return "structured";
}
*/
public String getContentType()
{
if(url.contains(".pdf"))
return "text/pdf";
else if(url.contains(".txt"))
return "text/plain";
else if(url.contains(".csv"))
return "text/csv";
return "text/html";
}
public boolean isHtml()
{
return "text/html".equals(getContentType());
}
public boolean isZipped()
{
if(url.endsWith(".gz") || url.endsWith(".zip"))
return true;
return false;
}
public String toYmlString(int counter)
{
String result = "";
result += " type: " + getYmlType() + "\n";
//result += " data-type: " + getStructuredOrUnstructured() + "\n";
result += " data-type: unstructured\n"; //Kelly says we only want unstructured documents. Also there is no extractor for structured documents running on the virtual machine.
result += " source-name: " + name + "\n";
if(isZipped())
result += " post-process: unzip\n";
result += " source-URI: " + url + "\n";
if(isHtml())
result += " post-process: removeHTML\n";
result += " content-type : " + getContentType() + "\n";
//result += " now-collect: none\n";
result += " now-collect: all\n";
result += " cron: 0 " + counter + " * * * ?";
return result;
}
}<file_sep>/src/gov/ornl/stucco/relationprediction/RelationPrediction.java
package gov.ornl.stucco.relationprediction;
//This class just parses the lines that get written to the prediction files by RunRelationSVMs.
import java.util.ArrayList;
public class RelationPrediction
{
public static int TPindex = 0;
public static int FPindex = 1;
public static int TNindex = 2;
public static int FNindex = 3;
public static int positiveclasslabel = 1;
public static int negativeclasslabel = -1;
private String comment;
private int goldclass;
private int predictedclass;
private double predictedpositiveprobability; //We are not using this yet, but may need it if we add probability outputs to our SVM's predictions.
RelationPrediction(String resultline)
{
String[] resultsAndcomment = resultline.split("#");
if(resultsAndcomment.length == 2)
comment = resultsAndcomment[1];
String[] splitresults = resultsAndcomment[0].split(" ");
String classandprediction = splitresults[0];
String[] splitclassandprediction = classandprediction.split("/");
goldclass = Integer.parseInt(splitclassandprediction[0]); //Subtract 1 from gold and predicted class because they are 1-indexed, but arrays and such that deal with these classes (which we use elsewhere) are 0-indexed.
predictedclass = Integer.parseInt(splitclassandprediction[1]);
if(splitresults.length > 1)
predictedpositiveprobability = Double.parseDouble(splitresults[1]);
}
public String getComment()
{
return comment;
}
public int getTPorFPorTNorFN()
{
//In the general case, we could figure this out for each class. But since we are working with a two class problem, in practice we care only about the positive class.
int forlabel = positiveclasslabel;
if(forlabel == goldclass && forlabel == predictedclass)
return TPindex;
if(forlabel == goldclass && forlabel != predictedclass)
return FNindex;
if(forlabel != goldclass && forlabel == predictedclass)
return FPindex;
if(forlabel != goldclass && forlabel != predictedclass)
return TNindex;
System.out.println("Error: instance not classifiable.");
new Exception().printStackTrace();
System.exit(3);
return -1;
}
//In the results, instances without a known class are labeled 0. Positive and negative instances are labeled 1 and -1 respectively.
public boolean instanceHasKnownClass()
{
return goldclass == positiveclasslabel || goldclass == negativeclasslabel;
}
public boolean getPredictionIsCorrect()
{
return goldclass == predictedclass;
}
}
<file_sep>/src/gov/ornl/stucco/relationprediction/PrintPreprocessedDocuments.java
/*
* This program looks at all the .ser.gz files in the directory ProducedFileGetter.getEntityExtractedSerializedDirectory()
* and produces several text files from them with one sentence per line. The text files use the .ser.gz file supplied
* tokenization, lemmatization, and entity annotations to produce three text files.
* One contains a tokenized, lemmatized
* version of the text wherein the entities have been replaced with a token representing their predicted entity types.
* Another contains a tokenized, lemmatized version wherein the entities have been replaced with a token that includes information about
* their predicted type and their original text.
* The third contains a tokenized, lemmatized version wherein we try to match the entity-labeled text segments with their canonical,
* Freebase names by matching the entity text against Freebase aliases. The entities are replaced with a token indicating
* their predicted entity type and canonical name.
* There is one final file that is tokenized but not lemmatized called unlemmatized. It is used solely because we might sometimes
* want to know what the original text looked like.
*/
package gov.ornl.stucco.relationprediction;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.ling.CoreAnnotations.CharacterOffsetBeginAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.CharacterOffsetEndAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.IndexAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.LemmaAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import gov.ornl.stucco.entity.EntityLabeler;
import gov.ornl.stucco.entity.CyberEntityAnnotator.CyberConfidenceAnnotation;
import gov.ornl.stucco.entity.heuristics.CyberHeuristicAnnotator.CyberHeuristicAnnotation;
import gov.ornl.stucco.entity.heuristics.CyberHeuristicAnnotator.CyberHeuristicMethodAnnotation;
public class PrintPreprocessedDocuments
{
//Any token having this high a probability of belonging to any non-O entity type will be assumed to belong to that entity type,
//unless some other non-O entity type has a higher probability. Otherwise, the token will be assigned to the type
//having the highest predicted probability.
public static double arbitraryprobabilitythreshold = 0.3;
//We read files from and write files to a different place if our goal is to train a new model. In production, our goal will be only to make predictions, so we will not bother with any training.
private static boolean training = false;
public static void main(String[] args) throws IOException
{
readArgs(args);
//Check whether there are any available files to work with.
boolean foundsergz = false;
for(File f : ProducedFileGetter.getEntityExtractedSerializedDirectory(training).listFiles())
{
if(f.getName().endsWith(".ser.gz"))
foundsergz = true;
}
if(!foundsergz)
{
System.out.println("Error: No .ser.gz files found in " + ProducedFileGetter.getEntityExtractedSerializedDirectory(training).getAbsolutePath() + " . Please place .ser.gz files that have been processed by the entity extractor here before running this program.");
System.exit(3);
}
//Open printwriters for each of the three text file types mentioned at the beginning of this .java file. We get all
//files from ProducedFileGetter to help maintain consistency between locations used by different programs.
//PrintWriter aliassubstitutednamesout = new PrintWriter(new FileWriter(ProducedFileGetter.getEntityExtractedText("aliasreplaced")));
//PrintWriter completelyreplacednamesout = new PrintWriter(new FileWriter(ProducedFileGetter.getEntityExtractedText("entityreplaced")));
//PrintWriter originalnamesout = new PrintWriter(new FileWriter(ProducedFileGetter.getEntityExtractedText("original")));
//Since there may be issues with sharing files as big as these might turn out to be through github, we are zipping them instead of just writing them in plain text format.
ZipOutputStream aliassubstitutednamesout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(ProducedFileGetter.getEntityExtractedText("aliasreplaced", training))));
aliassubstitutednamesout.putNextEntry(new ZipEntry("data"));
ZipOutputStream completelyreplacednamesout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(ProducedFileGetter.getEntityExtractedText("entityreplaced", training))));
completelyreplacednamesout.putNextEntry(new ZipEntry("data"));
ZipOutputStream originalnamesout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(ProducedFileGetter.getEntityExtractedText("original", training))));
originalnamesout.putNextEntry(new ZipEntry("data"));
ZipOutputStream unlemmatizednamesout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(ProducedFileGetter.getEntityExtractedText("unlemmatized", training))));
unlemmatizednamesout.putNextEntry(new ZipEntry("data"));
//Process each serialized file.
for(File f : ProducedFileGetter.getEntityExtractedSerializedDirectory(training).listFiles())
{
if(!f.getName().endsWith(".ser.gz"))
continue;
aliassubstitutednamesout.write( ("###" + f.getName() + "###\n").getBytes());
completelyreplacednamesout.write( ("###" + f.getName() + "###\n").getBytes());
originalnamesout.write( ("###" + f.getName() + "###\n").getBytes());
unlemmatizednamesout.write( ("###" + f.getName() + "###\n").getBytes());
Annotation deserDoc = EntityLabeler.deserializeAnnotatedDoc(f.getAbsolutePath());
List<CoreMap> sentences = deserDoc.get(SentencesAnnotation.class);
for (int sentencenum = 0; sentencenum < sentences.size(); sentencenum++)
{
CoreMap sentence = sentences.get(sentencenum);
List<CoreLabel> labels = sentence.get(TokensAnnotation.class);
int currententitystate = CyberEntityText.O;
int indexoffirsttokenhavingcurrentstate = 0;
for (int i = 0; i < labels.size(); i++)
{
CoreLabel token = labels.get(i);
Integer entityfinaltype = null;
//If the token was labeled by the heuristic annotator or was labeled with a high enough confidence
//(see the note above arbitraryprobabilitythreshold for details), assign it the appropriate label.
if (token.containsKey(CyberHeuristicMethodAnnotation.class))
{
entityfinaltype = CyberEntityText.entitytypenameToentitytypeindex.get(token.get(CyberHeuristicAnnotation.class).toString());
}
else if(token.containsKey(CyberConfidenceAnnotation.class))
{
double[] probabilities = token.get(CyberConfidenceAnnotation.class);
entityfinaltype = CyberEntityText.getTypeOfHighestProbabilityIndex(probabilities, arbitraryprobabilitythreshold);
}
//Sometimes, due to the probability threshold I set, the automatic entity labeler makes dumb, correctable decisions.
//This method heuristically corrects some of these errors.
entityfinaltype = resetEntityFinalTypeHeuristically(entityfinaltype, token);
//If the current token has a different label than the previous token, write the last entity out.
if(!entityfinaltype.equals(currententitystate))
{
if(currententitystate != CyberEntityText.O)
{
String entitytypestring = CyberEntityText.entitytypeindexToentitytypename.get(currententitystate);
//Below are the places where we write the three different versions of the text file.
//Print the "original" version of the text (described above)
String originalentitystring = "";
for(int j = indexoffirsttokenhavingcurrentstate; j < i; j++)
{
String word = labels.get(j).get(TextAnnotation.class);
word = replaceWordSpecialCharacters(word);
originalentitystring += " " + word;
}
originalentitystring = originalentitystring.trim();
originalentitystring = "[" + entitytypestring + "_" + originalentitystring.replaceAll(" ", "_") + "]";
originalnamesout.write((originalentitystring + " ").getBytes());
unlemmatizednamesout.write((originalentitystring + " ").getBytes());
//Print the alias replaced version of the text as described above.
String aliasreplacedentitystring = "";
for(int j = indexoffirsttokenhavingcurrentstate; j < i; j++)
{
String lemma = labels.get(j).get(LemmaAnnotation.class);
lemma = replaceWordSpecialCharacters(lemma).toLowerCase();
aliasreplacedentitystring += " " + lemma;
}
aliasreplacedentitystring = aliasreplacedentitystring.trim();
aliasreplacedentitystring = CyberEntityText.getCanonicalName(aliasreplacedentitystring, currententitystate);
aliasreplacedentitystring = "[" + entitytypestring + "_" + aliasreplacedentitystring.replaceAll(" ", "_") + "]";
aliassubstitutednamesout.write((aliasreplacedentitystring + " ").getBytes());
//Replace the entity's text with its type.
completelyreplacednamesout.write(("[" + entitytypestring + "] ").getBytes());
}
currententitystate = entityfinaltype;
indexoffirsttokenhavingcurrentstate = i;
}
//If the current token was not labeled as any kind of cyber entity, just print it ('s lemma) out.
if(entityfinaltype == CyberEntityText.O)
{
aliassubstitutednamesout.write( (((String)labels.get(i).get(LemmaAnnotation.class)).toLowerCase() + " ").getBytes());
completelyreplacednamesout.write( (((String)labels.get(i).get(LemmaAnnotation.class)).toLowerCase() + " ").getBytes());
originalnamesout.write( (((String)labels.get(i).get(LemmaAnnotation.class)).toLowerCase() + " ").getBytes());
unlemmatizednamesout.write( (((String)labels.get(i).get(TextAnnotation.class)) + " ").getBytes());
}
}
//If the sentence ends on an entity, print the entity. This code does the same things as in the above loop,
//only the loop does not process an entity if it comes at the end of a sentence. So handle that situation.
if(currententitystate != CyberEntityText.O)
{
String entitytypestring = CyberEntityText.entitytypeindexToentitytypename.get(currententitystate);
//Only adjust the entity's formatting.
String originalentitystring = "";
for(int j = indexoffirsttokenhavingcurrentstate; j < labels.size(); j++)
{
String word = labels.get(j).get(TextAnnotation.class);
word = replaceWordSpecialCharacters(word);
originalentitystring += " " + word;
}
originalentitystring = originalentitystring.trim();
originalentitystring = "[" + entitytypestring + "_" + originalentitystring.replaceAll(" ", "_") + "]";
originalnamesout.write((originalentitystring + " ").getBytes());
unlemmatizednamesout.write((originalentitystring + " ").getBytes());
//Replace the entity with its main alias if available.
String aliasreplacedentitystring = "";
for(int j = indexoffirsttokenhavingcurrentstate; j < labels.size(); j++)
{
String lemma = labels.get(j).get(LemmaAnnotation.class);
lemma = replaceWordSpecialCharacters(lemma).toLowerCase();
aliasreplacedentitystring += " " + lemma;
}
aliasreplacedentitystring = aliasreplacedentitystring.trim();
aliasreplacedentitystring = CyberEntityText.getCanonicalName(aliasreplacedentitystring, currententitystate);
aliasreplacedentitystring = "[" + entitytypestring + "_" + aliasreplacedentitystring.replaceAll(" ", "_") + "]";
aliassubstitutednamesout.write((aliasreplacedentitystring + " ").getBytes());
//Completely replace the entity with the name of its type.
completelyreplacednamesout.write(("[" + entitytypestring + "] ").getBytes());
}
aliassubstitutednamesout.write("\n".getBytes());
completelyreplacednamesout.write("\n".getBytes());
originalnamesout.write("\n".getBytes());
unlemmatizednamesout.write("\n".getBytes());
}
aliassubstitutednamesout.write("\n".getBytes());
completelyreplacednamesout.write("\n".getBytes());
originalnamesout.write("\n".getBytes());
unlemmatizednamesout.write("\n".getBytes());
}
aliassubstitutednamesout.closeEntry();
aliassubstitutednamesout.close();
completelyreplacednamesout.closeEntry();
completelyreplacednamesout.close();
originalnamesout.closeEntry();
originalnamesout.close();
unlemmatizednamesout.closeEntry();
unlemmatizednamesout.close();
}
private static void readArgs(String[] args)
{
for(int i = 0; i < args.length; i++)
{
if("training".equals(args[i]))
training = true;
}
}
private static int resetEntityFinalTypeHeuristically(int predictedtype, CoreLabel token)
{
int result = predictedtype;
if(predictedtype == CyberEntityText.SWVERSION)
{
String lemma = token.get(LemmaAnnotation.class);
if(lemma.equals(".") || lemma.equals("...") || lemma.equals("version"))
result = CyberEntityText.O;
}
return result;
}
private static String replaceWordSpecialCharacters(String word)
{
word = word.replaceAll("_", "~");
word = word.replaceAll("\\[", "(");
word = word.replaceAll("\\]", ")");
return word;
}
public static int[] getOriginalTokenIndexesFromPreprocessedLine(String[] preprocessedline)
{
int[] result = new int[preprocessedline.length+1];
int positioncounter = 0;
for(int i = 0; i < preprocessedline.length; i++)
{
result[i] = positioncounter;
String originaltext = CyberEntityText.getEntitySpacedText(preprocessedline[i]);
String[] originaltokens = originaltext.split(" ");
positioncounter += originaltokens.length;
}
result[preprocessedline.length] = positioncounter;
return result;
}
public static boolean isFileNameLine(String line)
{
return line.startsWith("###") && line.endsWith("###");
}
public static boolean isLineBetweenDocuments(String line)
{
return line.equals("");
}
}
|
5d1329442769b12980d8694991b471f7acb6c660
|
[
"Java"
] | 10
|
Java
|
alsmadi/Relationship-Bootstrap
|
246c97973fe1fe7a53fae349e14734d39ebe63a1
|
77f5e1714d88a9f68942c6fd117f434cae6d40cd
|
refs/heads/master
|
<file_sep>prompt_toolkit==1.0.14
PyInquirer
requests-html
demjson
wget<file_sep>import demjson
import re
base = 'http://www.mejortorrentt.org'
download_base = '/uploads/torrents/'
def extractEntry(entry):
a = entry.find('a', first=True)
q = entry.find('span', first=True)
l = a.links.pop()
return {
'name': a.text,
'link': base + l,
'quality': q.text.strip('()') if q else '',
'type': entry.find('td[align="right"]', first=True).text,
}
def findEntries(session, term):
t = term.replace(' ', '+')
url = F'{base}/secciones.php?sec=buscador&valor={t}'
r = session.get(url)
r.html.render()
entries = r.html.find('tr[height="22"]')
return [extractEntry(e) for e in entries]
def getFinalLinks(session, table):
links = list(table.absolute_links)
result = []
for link in links:
r = session.get(link)
l = r.html.find('a[style="font-size:12px;"]', first=True).absolute_links.pop()
result.append(l)
return result
def getDownloadLink(session, link):
link_regex = '\/uploads/\w+/\w+'
r = session.get(link)
l = r.html.find('a[href="#"]', first=True)
attr = l.attrs['onclick']
ty = re.search(link_regex, attr).group(0).split('/')[3]
obj = demjson.decode(attr.split(',', 1)[1][0:-2])
name = obj['name'].replace(' ', '%20')
return {
'name': name,
'link': F'{base}{download_base}{ty}/{name}',
}
def fullDisclosure(session, entry):
url = entry['link']
r = session.get(url)
r.html.render()
founds = r.html.find('td[style="border-top: 1px solid black; border-left: 1px solid black; border-right: 1px solid black;"]', first=True)
finalLinks = []
if founds:
finalLinks = getFinalLinks(session, founds)
else:
finalLinks = [
r.html.find('a[style="font-size:12px;"]', first=True).absolute_links.pop()
]
downloadLinks = [getDownloadLink(session, l) for l in finalLinks]
return {
**entry,
'download': downloadLinks,
}
<file_sep># torrentScrap
Herramienta CLI para la descarga de torrents de películas y series.
<file_sep>import wget
import requests
from PyInquirer import prompt, Token
from pprint import pprint
from operator import itemgetter
from os.path import expanduser
def print_logo():
print(
"""
_ _ _____
| | | | / ____|
| |_ ___ _ __ _ __ ___ _ __ | |_| (___ ___ _ __ __ _ _ __
| __/ _ \| '__| '__/ _ \ '_ \| __|\___ \ / __| '__/ _` | '_ \
| || (_) | | | | | __/ | | | |_ ____) | (__| | | (_| | |_) |
\__\___/|_| |_| \___|_| |_|\__|_____/ \___|_| \__,_| .__/
| |
|_|
"""
)
def prompt_start():
questions = [
{
'type': 'input',
'name': 'path',
'message': 'Carpeta de descarga: ',
'default': F'{expanduser("~")}/torrentScrap',
},
{
'type': 'input',
'name': 'term',
'message': 'Término a buscar: ',
},
]
answers = prompt(questions)
return answers
def create_folder(path):
if not path:
raise "A path is required"
# check if the path exist
# create the path
def entries_questions(entries):
choices = []
for idx, entry in enumerate(entries):
name = entry.get('name', '').replace('\n', ' ')
quality = entry.get('quality', '')
entry_type = entry.get('type', '')
choices.append({
'name': F"{name} ({quality}) - {entry_type}",
'value': idx,
})
return [
{
'type': 'list',
'name': 'entries',
'message': 'Selecciona el elemento',
'choices': choices,
}
]
def prompt_entries(entries):
answers = prompt(entries_questions(entries))
return int(answers.get('entries', '0'))
def links_questions(entry):
name, download = itemgetter('name', 'download')(entry)
choices = []
for entry in download:
link = entry.get('link', '')
if (link):
choices.append({
'name': entry.get('name', ''),
'value': link,
})
return [
{
'type': 'checkbox',
'message': 'Selecciona los enlaces',
'name': 'links',
'choices': sorted(choices, key=itemgetter('name')) ,
'validate': lambda answer: 'You must choose at least one link' \
if len(answer) == 0 else True
}
]
def prompt_links(entry):
download = itemgetter('download')(entry)
if (len(download) == 1):
return [download[0]['link']]
if (len(download) > 1):
answers = prompt(links_questions(entry))
return answers.get('links', None)
def download(links, path):
print(F'Descargando {len(links)} elementos')
for url in links:
filename = url.split('/')[-1]
myfile = requests.get(url)
open(F'{path}/{filename}', 'wb').write(myfile.content)
# wget.download(url, F'{path}/{filename}')
print(F'Elementos descargados en {path}')
<file_sep>from requests_html import HTMLSession
from torrentParser import findEntries, fullDisclosure
from pprint import pprint
from utils import *
from operator import itemgetter
def main():
print_logo()
options = prompt_start()
path, term = itemgetter('path', 'term')(options)
# create_folder(path)
session = HTMLSession()
entries = findEntries(session, term)
selected_index = prompt_entries(entries)
entry = entries[selected_index]
disclosure = fullDisclosure(session, entry)
download_links = prompt_links(disclosure)
download(download_links, path)
if __name__ == '__main__':
main()
|
e86d09e7fa291fff8d6e5b78efd0bdd3032fedba
|
[
"Markdown",
"Python",
"Text"
] | 5
|
Text
|
patamimbre/torrentScrap
|
e60338ca09b12c711b3255d1c2e05bc44cebba47
|
f2e266e6f99731cb63147ac80b17403eb031871b
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DatabaseProvider } from '../../providers/database/database';
import { RosProvider } from '../../providers/ros/ros';
/**
* Generated class for the SettingsPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-settings',
templateUrl: 'settings.html',
})
export class SettingsPage {
settings = [];
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public database: DatabaseProvider,
public rosProvider: RosProvider
) {
}
ionViewDidLoad() {
this.database.getDatabaseState().subscribe(ready => {
if (ready) {
console.log('Ready: ', ready);
this.loadSettings();
}
});
}
loadSettings() {
console.log('Loading settings...');
this.database.getSettings().then(data => {
this.settings = data;
console.log('Settings: ', JSON.stringify(data));
}, err => {
console.log('Error loadSettings: ', err);
});
}
save() {
this.settings.forEach(setting => {
this.database.setROSWSSetting(setting.id, setting.optValue);
});
// console.log(JSON.stringify(data));
this.rosProvider.loadSettings();
}
resetDB() {
this.database.cleanDB();
}
viewDB() {
this.database.getSettings().then(data => {
this.settings = data;
console.log('Settings: ', JSON.stringify(data));
});//.catch(e => console.log('Error view: ', e));
}
}
<file_sep>import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { AsyncSubject } from 'rxjs/AsyncSubject';
import { AlertController, LoadingController, ToastController } from 'ionic-angular';
import { DatabaseProvider } from '../database/database';
declare var ROSLIB: any;
declare var ROS3D: any;
declare var MJPEGCANVAS: any;
interface nodeStateType {
node_state_desc: string;
node_state: number;
node_state_time: number;
bug_state_desc: string;
algorithm: number;
bug_state: number;
bug_state_time: number;
};
interface algorithmStateType {
algorithm: number;
name: string;
pose_x: number;
pose_y: number;
yaw: number;
initial_to_goal_distance: number;
current_to_goal_distance: number;
best_distance: number;
path_length: number;
time: number;
};
/*
Generated class for the RosProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class RosProvider {
ros: any;
viewer: any;
// Marker visualization
marker_viewer: any;
tfClient: any;
markerClient: any;
laserScanClient: any;
camera: any;
cmdVel: any;
twist: any;
maxVel: number;
defaultVel: number;
vel: number;
service: any;
serviceRespose: any;
nodeStateSub: any;
nodeState: any;
algorithmStateSub: any;
algorithmState: algorithmStateType;
runInfo: Array<nodeStateType>;
bugServiceRequest = {
algorithm: 0,
velocity: 0.3,
initial_x: 0,
initial_y: 0,
desired_x: 0,
desired_y: 0,
simulation: true,
reverse: false,
choose: false
};
rosWS_URL;
rosWS_Port;
rosWS_Topic_Vel;
rosWS_Topic_Cam;
rosWS_Topic_Sensor;
rosWS_Topic_Odom;
//public connection: BehaviorSubject<number> = new BehaviorSubject<number>(0);
public connection: AsyncSubject<number> = new AsyncSubject<number>();
// This variable avoids showing the prompAlert twice
isFirstTime: boolean;
count: number;
loadingInit;
loadingConnect;
promptAlert;
constructor(
public http: Http,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
private toastCtrl: ToastController,
public database: DatabaseProvider
) {
this.viewer = undefined;
this.marker_viewer = undefined;
this.runInfo = [];
this.isFirstTime = true;
this.count = 0;
this.nodeState = {
node_state_desc: "Not available",
node_state: -1,
bug_state_desc: "",
algorithm: 0,
bug_state: 0
};
this.algorithmState = {
algorithm: -1,
name: '',
pose_x: 0,
pose_y: 0,
yaw: 0,
initial_to_goal_distance: 0,
current_to_goal_distance: 0,
best_distance: 0,
path_length: 0,
time: 0
}
this.presentLoadingInit();
}
rosWSInit() {
console.log('Ros init');
this.viewer = undefined;
this.marker_viewer = undefined;
this.ros = new ROSLIB.Ros({
url: `ws://${this.rosWS_URL.optValue}:${this.rosWS_Port.optValue}`
});
this.ros.on('connection', () => {
console.log('Connected to websocket server.');
this.count = 0;
this.connection.next(1);
this.connection.complete();
this.dismissLoadingConnect();
});
this.ros.on('error', (error) => {
console.log('Error connecting to websocket server: ', JSON.stringify(error));
this.connection.next(-1);
this.connection.complete();
this.dismissLoadingConnect();
});
}
rosWSTopicInit() {
console.log("Init WS topics")
this.nodeStateSub = new ROSLIB.Topic({
ros: this.ros,
name: '/bugServer/bugNodeState',
messageType: 'bug_algorithms/nodeState'
});
this.algorithmStateSub = new ROSLIB.Topic({
ros: this.ros,
name: '/bugServer/algorithmState',
messageType: 'bug_algorithms/algorithmState'
});
this.nodeStateSub.subscribe((message: nodeStateType) => {
let len = this.runInfo.length;
this.nodeState = message;
if (len == 0) {
this.runInfo = [];
if (message.node_state > 0)
this.runInfo.push(message);
} else {
let bugState = this.runInfo[len - 1].bug_state;
let nodeState = this.runInfo[len - 1].node_state;
if (nodeState != message.node_state || bugState != message.bug_state) {
this.runInfo.push(message);
}
}
//console.log(JSON.stringify(message));
});
this.algorithmStateSub.subscribe((message: algorithmStateType) => {
this.algorithmState = message;
//console.log(JSON.stringify(message));
});
this.cmdVel = new ROSLIB.Topic({
ros: this.ros,
name: this.rosWS_Topic_Vel.optValue,
messageType: 'geometry_msgs/Twist'
});
this.twist = new ROSLIB.Message({
linear: {
x: 0.0,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: 0.0
}
});
this.maxVel = 0.5;
this.defaultVel = 3;
this.vel = this.defaultVel / 10;
}
loadSettings() {
if (this.ros) {
console.log('ROS WS Disconnecting...');
this.ros.close();
}
this.connection = new AsyncSubject();
this.connection.subscribe(con => {
if (con == 1) {
this.rosWSTopicInit();
console.log("Initializing topics");
}
});
this.database.getSettings().then(data => {
this.rosWS_URL = data[0];
this.rosWS_Port = data[1];
this.rosWS_Topic_Vel = data[2];
this.rosWS_Topic_Cam = data[3];
this.rosWS_Topic_Sensor = data[4];
this.rosWS_Topic_Odom = data[5];
this.presentLoadingConnect();
this.rosWSInit();
});
}
shutdown() {
this.ros.on('close', function () {
console.log('Connection to websocket server closed.');
});
}
stop() {
this.twist = {
linear: {
x: 0.0,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: 0.0
}
};
this.cmdVel.publish(this.twist);
}
forward() {
this.twist = {
linear: {
x: this.vel,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: 0.0
}
};
this.cmdVel.publish(this.twist);
}
backward() {
this.twist = {
linear: {
x: -this.vel,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: 0.0
}
};
this.cmdVel.publish(this.twist);
}
left() {
this.twist = {
linear: {
x: 0.0,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: this.vel
}
};
this.cmdVel.publish(this.twist);
}
right() {
this.twist = {
linear: {
x: 0.0,
y: 0.0,
z: 0.0
},
angular: {
x: 0.0,
y: 0.0,
z: -this.vel
}
};
this.cmdVel.publish(this.twist);
}
callServiceInitBug() {
this.runInfo = [];
this.bugServiceRequest.algorithm = Number(this.bugServiceRequest.algorithm);
this.bugServiceRequest.velocity = Number(this.bugServiceRequest.velocity);
this.bugServiceRequest.initial_x = Number(this.bugServiceRequest.initial_x);
this.bugServiceRequest.initial_y = Number(this.bugServiceRequest.initial_y);
this.bugServiceRequest.desired_x = Number(this.bugServiceRequest.desired_x);
this.bugServiceRequest.desired_y = Number(this.bugServiceRequest.desired_y);
this.bugServiceRequest.simulation = Number(this.bugServiceRequest.simulation) == 1 ? true : false;
this.bugServiceRequest.reverse = Number(this.bugServiceRequest.reverse) == 1 ? true : false;
this.bugServiceRequest.choose = Number(this.bugServiceRequest.choose) == 1 ? true : false;
this.presentToast("Calling BugService");
console.log(JSON.stringify(this.bugServiceRequest));
this.service = new ROSLIB.Service({
ros: this.ros,
name: "/bugServer/initBugAlg",
serviceType: 'bug_algorithms/bugService'
});
let request = new ROSLIB.ServiceRequest(this.bugServiceRequest);
this.service.callService(request, (response) => {
console.log(JSON.stringify(response));
this.presentToast(response.message);
this.serviceRespose = response.success;
console.log(JSON.stringify(this.runInfo));
if (this.runInfo.length > 0) {
if (this.runInfo[0].node_state == 0) {
this.runInfo.pop();
}
}
}, (err) => {
console.log(JSON.stringify(err));
this.presentToast(err);
this.serviceRespose = false;
});
}
callBugNodeStateSwitch(state: number) {
this.bugServiceRequest.algorithm = Number(this.bugServiceRequest.algorithm);
console.log("Calling BugNodeStateSwitch");
this.service = new ROSLIB.Service({
ros: this.ros,
name: "/bugServer/bugNodeStateSwitch",
serviceType: 'bug_algorithms/bugSwitch'
});
let request = new ROSLIB.ServiceRequest({
algorithm: this.bugServiceRequest.algorithm,
state: state
});
this.service.callService(request, (response) => {
console.log(JSON.stringify(response));
this.presentToast(response.message);
}, (err) => {
console.log(JSON.stringify(err));
this.presentToast(err);
});
}
showCamera(width, height, quality = 20) {
// These operations keep the image size ratio
if (width > height) {
let temp = width;
width = height + 25;
height = temp - 25;
}
height = ((width - 32) * 480) / 640;
width = width - 32;
if (this.viewer === undefined) {
this.viewer = new MJPEGCANVAS.Viewer({
divID: 'image',
host: this.rosWS_URL.optValue,
width: width,
height: height,
quality: quality,
refreshRate: 60,
topic: this.rosWS_Topic_Cam.optValue
});
} else {
// Remove canvas and create a new one
/*let elem = document.getElementById("image");
elem.removeChild(elem.childNodes[0]);
this.viewer = new MJPEGCANVAS.Viewer({
divID: 'image',
host: this.rosWS_URL.optValue,
width: width,
height: height,
quality: quality,
refreshRate: 60,
topic: this.rosWS_Topic_Cam.optValue
});*/
// This only change the image quality and the topic
this.viewer.quality = quality;
this.viewer.changeStream(this.rosWS_Topic_Cam.optValue);
}
}
showMarkers(width, height, fixedFrame = "odom") {
// These operations keep the image size ratio
if (width > height) {
let temp = width;
width = height + 25;
height = temp - 25;
}
console.log(fixedFrame);
height = ((width - 32) * 480) / 640;
width = width - 32;
if (this.marker_viewer === undefined) {
// Create the main viewer.
// Set directionalLight in the ros3d.min.js from top to down
// directionalLight.position.set(0,0,1)
// Change THREE.LineBasicMaterial({size:c.scale.x}) to THREE.LineBasicMaterial()
// Size is not a property of THREE.LineBasicMaterial
// Remove useScreenCoordinates in new THREE$1.SpriteMaterial({
//map: texture,
// NOTE: This is needed for THREE.js r61, unused in r70
//useScreenCoordinates: false });
this.marker_viewer = new ROS3D.Viewer({
divID: 'markers',
width: width,
height: height,
background: '#ffffff',
intensity: 1.0,
cameraPose: { x: 0, y: 0, z: 20 },
cameraZoomSpeed: 1,
antialias: true
});
}
// Add a simple grid
this.marker_viewer.addObject(new ROS3D.Grid({ num_cells: 20 }));
// Setup a client to listen to TFs.
this.tfClient = new ROSLIB.TFClient({
ros: this.ros,
angularThres: 0.01,
transThres: 0.01,
rate: 10.0,
fixedFrame: `/${fixedFrame}`
});
// Setup the marker client.
this.markerClient = new ROS3D.MarkerClient({
ros: this.ros,
tfClient: this.tfClient,
topic: '/visualization_marker',
rootObject: this.marker_viewer.scene
});
}
hideMarkers() {
console.log("Turning off markers");
this.markerClient.unsubscribe();
if (this.laserScanClient)
this.laserScanClient.unsubscribe();
let elem = document.getElementById("markers");
if (elem.childNodes.length > 0) {
console.log("Removing canvas: ", elem.childNodes.length);
elem.removeChild(elem.childNodes[0]);
}
this.marker_viewer = undefined;
}
changeNamespace(ns: string) {
if (this.markerClient) {
console.log("Changing namespace to ", ns);
this.markerClient.namespace = ns;
}
}
setLaserClientSubscribe(val: number) {
if (val == 0) {
if (this.laserScanClient) {
console.log("Laser unsubscribe : ", this.marker_viewer.scene.children.length);
//this.marker_viewer.scene.remove.apply(this.marker_viewer.scene, this.marker_viewer.scene.children);
this.laserScanClient.unsubscribe();
this.laserScanClient = undefined;
}
} else {
if (this.laserScanClient) {
this.laserScanClient.unsubscribe();
this.laserScanClient = undefined;
}
let topic = val == 1 ? '/p3dx/laser/scan' : '/scan';
// Setup the marker client.
this.laserScanClient = new ROS3D.LaserScan({
ros: this.ros,
tfClient: this.tfClient,
topic: topic,
material: { color: '#000000', size: 0.2 },
pointRatio: 10,
messageRatio: 3,
rootObject: this.marker_viewer.scene
});
console.log("Laser subscribe");
this.laserScanClient.subscribe();
}
}
showPrompt(status: number) {
// status : 0 error | 1 success
const title = ["ROS WS Error!", "ROS WS"];
const message = [
"The ROS WS is not available. Do you want to change the ROS WS Url?",
"The ROS WS is available!"
];
this.promptAlert = this.alertCtrl.create({
title: title[status],
message: message[status],
inputs: [
{
name: 'rosWS_URL',
label: 'ROS WS Url',
placeholder: 'ROS WS Url',
value: this.rosWS_URL.optValue
},
{
name: 'rosWS_Port',
label: 'ROS WS Port',
placeholder: 'ROS WS Port',
value: this.rosWS_Port.optValue
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked');
//console.log(JSON.stringify(data));
}
},
{
text: 'Save',
handler: data => {
this.rosWS_URL.optValue = data.rosWS_URL;
this.rosWS_Port.optValue = data.rosWS_Port;
this.database.setROSWSSetting(this.rosWS_URL.id, this.rosWS_URL.optValue);
this.database.setROSWSSetting(this.rosWS_Port.id, this.rosWS_Port.optValue);
// console.log(JSON.stringify(data));
this.loadSettings();
}
}
]
});
this.promptAlert.present();
}
presentLoadingInit() {
this.loadingInit = this.loadingCtrl.create({
content: `Please wait...`
});
this.loadingInit.present();
}
dismissLoadingConnect() {
if (this.loadingConnect) {
this.loadingConnect.dismiss();
this.loadingConnect = null;
}
}
presentLoadingConnect() {
if (this.loadingInit) {
this.loadingInit.dismiss();
this.loadingInit = null;
}
//this.dismissLoadingConnect();
this.loadingConnect = this.loadingCtrl.create({
content: `Trying to connect to ${this.rosWS_URL.optValue}:${this.rosWS_Port.optValue}`,
enableBackdropDismiss: true
});
this.loadingConnect.onDidDismiss(() => {
console.log("Loading Connection dismissed");
this.loadingConnect = null;
});
this.loadingConnect.present();
}
presentToast(message) {
let toast = this.toastCtrl.create({
message: message,
duration: 3000
});
toast.present();
}
// Refreser function
doRefresh(refresher) {
this.loadSettings();
refresher.complete();
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { HttpModule } from '@angular/http';
import { IonicStorageModule } from '@ionic/storage';
import { SQLite } from '@ionic-native/sqlite';
import { SQLitePorter } from '@ionic-native/sqlite-porter';
import { ChartsModule } from 'ng2-charts';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AlgorithmsPage } from '../pages/algorithms/algorithms';
import { SettingsPage } from '../pages/settings/settings';
import { RunInfoModalPage } from '../pages/run-info-modal/run-info-modal';
import { DatabaseProvider } from '../providers/database/database';
import { RosProvider } from '../providers/ros/ros';
import { DirectivesModule } from '../directives/directives.module';
@NgModule({
declarations: [
MyApp,
HomePage,
AlgorithmsPage,
SettingsPage,
RunInfoModalPage
],
imports: [
BrowserModule,
HttpModule,
DirectivesModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot(MyApp,{
scrollPadding: false,
scrollAssist: true
}),
ChartsModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
AlgorithmsPage,
SettingsPage,
RunInfoModalPage
],
providers: [
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler },
DatabaseProvider,
SQLite,
SQLitePorter,
RosProvider
]
})
export class AppModule { }
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { Platform, NavController, AlertController, LoadingController } from 'ionic-angular';
import { DatabaseProvider } from '../../providers/database/database';
import { RosProvider } from '../../providers/ros/ros';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements OnInit, OnDestroy {
showCamera = false;
isStop: boolean;
width;
height;
quality;
constructor(
public platform: Platform,
public navCtrl: NavController,
public alertCtrl: AlertController,
public loadingCtrl: LoadingController,
public database: DatabaseProvider,
public rosProvider: RosProvider
) {
this.quality = 25;
this.isStop = false;
platform.ready().then((readySource) => {
this.width = this.platform.width();
this.height = this.platform.height();
});
}
ngOnInit() {
}
ionViewDidLoad() {
this.database.getDatabaseState().subscribe(ready => {
if (ready) {
console.log('Home Ready: ', ready);
this.rosProvider.loadSettings();
}
});
}
showROSCamera() {
this.width = this.platform.width();
this.height = this.platform.height();
console.log("Widht: ", this.width, "| Height: ", this.height);
this.rosProvider.showCamera(this.width, this.height, this.quality);
}
stop() {
this.isStop = this.isStop ? false : true;
this.rosProvider.stop();
}
ngOnDestroy() {
/*this.rosProvider.ros.on('close', function () {
console.log('Connection to websocket server closed.');
});*/
}
}
<file_sep>import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { AlgorithmsPage } from '../pages/algorithms/algorithms';
import { SettingsPage } from '../pages/settings/settings';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav;
rootPage: any = AlgorithmsPage;
pages: Array<{ title: string, component: any, icon: string, action?: string }>;
constructor(
public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
) {
this.initializeApp();
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Pioneer Control', component: HomePage, icon: 'game-controller-a' },
{ title: 'Algorithms', component: AlgorithmsPage, icon: 'bug' },
{ title: 'Settings', component: SettingsPage, icon: 'settings' }
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
if (page.action) {
this[page.action]();
}
if (page.title === 'Settings') {
this.nav.push(SettingsPage);
} else {
this.nav.setRoot(page.component);
}
}
}
<file_sep># ros-robot-controller
Repository for robot controller mobile App using RosBridge and Ionic 3
<file_sep>import { Platform } from 'ionic-angular';
import { SQLitePorter } from '@ionic-native/sqlite-porter';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/map';
/*
Generated class for the DatabaseProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class DatabaseProvider {
database: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
constructor(
public http: Http,
public sqlite: SQLite,
public sqlitePorter: SQLitePorter,
public storage: Storage,
public platform: Platform
) {
this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
this.sqlite.create({
name: 'data',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
this.storage.get('database_filled').then(val => {
// console.log('Val: ', val);
if (val) {
this.databaseReady.next(true);
// console.log('DB Filled');
this.getSettings();
} else {
this.fillDatabase();
// console.log('DB OK');
}
});
});
});
}
fillDatabase() {
this.http.get('assets/dummyData.sql')
.map(res => res.text())
.subscribe(sql => {
// console.log('Sql: ', sql);
this.sqlitePorter.importSqlToDb(this.database, sql)
.then(data => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
// console.log('Filling DB');
})
.catch(e => console.log('Error fillDatabase: ', JSON.stringify(e)));
});
}
getDatabaseState() {
return this.databaseReady.asObservable();
}
setROSWSSetting(id: number, val: string) {
let sql = "UPDATE Settings SET optValue = ? WHERE id = ?";
this.database.executeSql(sql, [val, id]).then((response) => {
// console.log(response);
return response;
});
}
getSettings(): any {
let sql = "SELECT * FROM Settings";
let settings = [];
return this.database.executeSql(sql, []).then((data) => {
if (data.rows.length > 0) {
for (let i = 0; i < data.rows.length; i++) {
settings.push(
{
id: data.rows.item(i).id,
optName: data.rows.item(i).optName,
optValue: data.rows.item(i).optValue
});
}
// console.log('Rows: ', data.rows.length);
}
// console.log('Query: ', JSON.stringify(settings));
return settings;
}, err => {
console.log('Error getSettings: ', JSON.stringify(err));
return [];
});
}
cleanDB() {
this.http.get('assets/dropData.sql')
.map(res => res.text())
.subscribe(sql => {
console.log('Sql: ', sql);
this.sqlitePorter.importSqlToDb(this.database, sql)
.then(data => {
this.databaseReady.next(false);
this.storage.set('database_filled', false);
console.log('DB Dropped');
})
.catch(e => console.log('Error drop DB: ', JSON.stringify(e)));
});
}
}
<file_sep>CREATE TABLE IF NOT EXISTS Settings (id INTEGER, optName TEXT, optValue TEXT);
INSERT INTO Settings (id, optName, optValue) VALUES (1, 'ROSWS_Url', 'localhost');
INSERT INTO Settings (id, optName, optValue) VALUES (2, 'ROSWS_Port', '9090');
INSERT INTO Settings (id, optName, optValue) VALUES (3, 'ROSWS_Topic_Vel', '/cmd_vel');
INSERT INTO Settings (id, optName, optValue) VALUES (4, 'ROSWS_Topic_Cam', '/usb_cam/image_raw');
INSERT INTO Settings (id, optName, optValue) VALUES (5, 'ROSWS_Topic_Sensor', '/p3dx/laser/scan');
INSERT INTO Settings (id, optName, optValue) VALUES (6, 'ROSWS_Topic_Odom', '/odom');<file_sep>import { Component, ViewChild, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { Platform, NavController, AlertController, LoadingController, ModalController, Select } from 'ionic-angular';
import { DatabaseProvider } from '../../providers/database/database';
import { RosProvider } from '../../providers/ros/ros';
import { RunInfoModalPage } from './../run-info-modal/run-info-modal';
/**
* Generated class for the AlgorithmsPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-algorithms',
templateUrl: 'algorithms.html',
})
export class AlgorithmsPage implements OnInit, OnDestroy {
@ViewChild("image") inputChild: ElementRef;
@ViewChild("selectFrame") selectFrameRef: Select;
@ViewChild("selectNamespace") selectNamespaceRef: Select;
@ViewChild("selectLaser") selectLaserRef: Select;
showCamera = false;
showMarker = false;
isStop: boolean;
disable: boolean;
isActive: boolean;
opt: string;
inputTemp: any;
width;
height;
quality;
fixed_frame;
namespace;
isLaserOn;
constructor(
public platform: Platform,
public navCtrl: NavController,
public alertCtrl: AlertController,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController,
public database: DatabaseProvider,
public rosProvider: RosProvider
) {
this.quality = 25;
this.fixed_frame = "odom";
this.opt = "info";
this.isStop = false;
this.isActive = false;
this.disable = false;
platform.ready().then((readySource) => {
this.width = this.platform.width();
this.height = this.platform.height();
});
}
ngOnInit() {
}
ionViewDidLoad() {
this.database.getDatabaseState().subscribe(ready => {
if (ready) {
console.log('Algorithms Ready: ', ready);
this.rosProvider.loadSettings();
}
});
}
presentRunInfoModal() {
let runInfoModal = this.modalCtrl.create(RunInfoModalPage, { data: this.rosProvider.runInfo });
runInfoModal.present();
}
checkOpt() {
console.log("Changed!")
if (this.rosProvider.bugServiceRequest.algorithm == 1 || this.rosProvider.bugServiceRequest.algorithm == 5) {
this.disable = true;
this.rosProvider.bugServiceRequest.reverse = false;
this.rosProvider.bugServiceRequest.choose = false;
} else if (this.rosProvider.bugServiceRequest.algorithm == 6) {
this.disable = true;
this.rosProvider.bugServiceRequest.reverse = false;
this.rosProvider.bugServiceRequest.choose = true;
} else {
this.disable = false;
}
}
moveFocus(nextElement) {
nextElement.setFocus();
}
showROSCamera() {
this.width = this.platform.width();
this.height = this.platform.height();
console.log("Widht: ", this.width, "| Height: ", this.height);
this.rosProvider.showCamera(this.width, this.height, this.quality);
}
showROSMarkers() {
this.width = this.platform.width();
this.height = this.platform.height();
console.log("Widht: ", this.width, "| Height: ", this.height);
this.rosProvider.showMarkers(this.width, this.height, this.fixed_frame);
}
openSelectFrame(){
this.selectFrameRef.open();
}
openSelectNamespace(){
this.selectNamespaceRef.open();
}
openSelectLaser(){
this.selectLaserRef.open();
}
ngOnDestroy() {
this.rosProvider.shutdown();
}
}
|
6336cecd6b283429eb7272a978708d1afbd0ecba
|
[
"Markdown",
"SQL",
"TypeScript"
] | 9
|
TypeScript
|
mario-serna/ros-robot-controller
|
3149817e428895ac86ebe2292a05beb6c94f9399
|
4fc19ade79e81d87b4994fd5a73f1024c294f596
|
refs/heads/master
|
<repo_name>AliBabighef/simple-game<file_sep>/mains.js
let button = document.querySelector(".strat-game button"),
YoureName = document.querySelector(".name span");
// start function asking you're name
function asking() {
"use strcit";
button.parentElement.classList.add("active")
let ask = prompt("what you're name");
if (ask === "") {
YoureName.innerHTML = "unknow"
}
else if (ask === null) {
YoureName.innerHTML = "unknow"
}
else {
YoureName.innerHTML = ask
}
}
button.addEventListener("click", function () {
asking()
})
// end function asking you're name
// start loop for all img
let allNavImg = document.querySelectorAll(".content_body");
let arr = Array.from(document.querySelector(".body").children);
let w = 0;
let y = [];
allNavImg.forEach((ell, i) => {
for (let i = 0; i < allNavImg.length; i++) {
let randamNum = Math.floor(Math.random() * allNavImg.length);
ell.style.order = randamNum;
}
ell.addEventListener("click", function () {
ell.classList.add("active");
if (ell.classList.contains("active")) {
ell.style.pointerEvents = "auto";
}
y.push(ell)
sellecting(y)
checkingTwo()
})
})
function sellecting(isSlect) {
let showTwo = arr.filter(ell => ell.classList.contains("active"));
if (showTwo.length === 2) {
document.querySelector(".body").classList.add("stopClicking");
matching(y[0].dataset.dt, y[1].dataset.dt)
y[0].style.pointerEvents = "auto";
y[1].style.pointerEvents = "auto";
}
}
// start if y greater than 2 will remove first ellemnt arry
function checkingTwo() {
if (y.length > 2) {
for (let r = 0; r < y.length; r++) {
y.splice(0, 1)
}
}
}
// end if y greater than 2 will remove first ellemnt arry
//start if data set is true
function matching(fst, snd) {
if (fst === snd) {
checkingTwo()
document.querySelector(".body").classList.remove("stopClicking");
y[0].classList.remove("active")
y[1].classList.remove("active")
y[0].classList.add("isMatch")
y[1].classList.add("isMatch")
}
//end if data set is true
//star if data set is false
else {
for (let i = 0; i < y.length; i++) {
checkingTwo();
setTimeout(function () {
document.querySelector(".body").classList.remove("stopClicking");
y[i].classList.remove("active");
}, 2000)
}
document.querySelector(".wrong span").innerHTML = w + 1;
w++
}
}
function stopClicking(element) {
}
|
ba46405939595eac6f5e6cb0f484ec8eb51a2c50
|
[
"JavaScript"
] | 1
|
JavaScript
|
AliBabighef/simple-game
|
0b6c309ec1a2ea11b644a351ab5de82bfa82e429
|
e9dd2de98ebaefe8147cb08dec80f9dc66e4ce58
|
refs/heads/master
|
<file_sep>const BookModel = require("./database/books");
const AuthorModel = require("./database/authors");
const PublicationModel = require("./database/publication");
require("dotenv").config();
var mongoose = require("mongoose");
const express = require("express");
let app = express();
app.use(express.json());
var mongoDB = process.env.Mongo_URI;
mongoose
.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("CONNECTION ESTABLISHED"));
// http://localhost:3000/
app.get("/", (req, res) => {
return res.json({ WELCOME: `to my Backend Software for the Book Company` });
});
// http://localhost:3000/books
app.get("/books", async (req, res) => {
const getAllBooks = await BookModel.find();
return res.json(getAllBooks);
});
// http://localhost:3000/book-isbn/12345Two
app.get("/book-isbn/:isbn", async (req, res) => {
const { isbn } = req.params;
const getSpecificBook = await BookModel.findOne({ ISBN: isbn });
if (getSpecificBook === null) {
return res.json({ error: `No Book found with ISBN ${isbn}` });
}
return res.json(getSpecificBook);
});
// http://localhost:3000/book-category/programming
app.get("/book-category/:category", async (req, res) => {
const { category } = req.params;
const getSpecificBook = await BookModel.findOne({ category: category });
if (getSpecificBook === null) {
return res.json({ error: `No book found with category ${category}` });
}
return res.json(getSpecificBook);
});
// http://localhost:3000/authors
app.get("/authors", async (req, res) => {
const getAllAuthors = await AuthorModel.find();
return res.json(getAllAuthors);
});
// http://localhost:3000/author-id/1
app.get("/author-id/:id", async (req, res) => {
const { id } = req.params;
const getSpecificAuthor = await AuthorModel.findOne({ id: id });
if (getSpecificAuthor === null) {
return res.json({ error: `No Author found with id ${id}` });
}
return res.json(getSpecificAuthor);
});
// http://localhost:3000/publications
app.get("/publications", async (req, res) => {
const publications = await PublicationModel.find();
return res.json(publications);
});
// http://localhost:3000/publication-isbn/12345Two
app.get("/publication-isbn/:isbn", async (req, res) => {
const { isbn } = req.params;
const getPublication = await PublicationModel.findOne({ books: isbn });
if (getPublication === null) {
res.json({ error: `No publication found with ISBN of ${isbn}` });
}
return res.json(getPublication);
});
//POST
// http://localhost:3000/book
app.post("/book", async (req, res) => {
const addNewBook = await BookModel.create(req.body);
return res.json({ bookAdded: addNewBook, message: "Book was Added !!!" });
});
// http://localhost:3000/author
app.post("/author", async (req, res) => {
const addNewAuthor = await AuthorModel.create(req.body);
return res.json({
authorAdded: addNewAuthor,
message: "Author was Added!!!",
});
});
// http://localhost:3000/publication
app.post("/publication", async (req, res) => {
const addNewPublication = await PublicationModel.create(req.body);
return res.json({
publicationAdded: addNewPublication,
message: "Publication was Added!!!",
});
});
// PUT
// http://localhost:3000/book-update/12345ONE
app.put("/book-update/:isbn", async (req, res) => {
const { isbn } = req.params;
// const updatedBook = await BookModel.updateOne({ISBN: isbn}, {$set: req.body});
const updatedBook = await BookModel.findOneAndUpdate(
{ ISBN: isbn },
req.body,
{ new: true }
);
return res.json({ updatedBook: updatedBook, message: "Book was updated!!!" });
});
// http://localhost:3000/author-update/1
app.put("/author-update/:id", async (req, res) => {
const { id } = req.params;
const updateAuthor = await AuthorModel.findOneAndUpdate(
{ id: id },
req.body,
{ new: true }
);
return res.json({
updatedAuthor: updateAuthor,
message: "Author was Updated!!!",
});
});
// http://localhost:3000/publication-update/1
app.put("/publication-update/:id", async (req, res) => {
const { id } = req.params;
const updatePublication = await PublicationModel.findOneAndUpdate(
{ id: id },
req.body,
{ new: true }
);
return res.json({
updatedPublicarion: updatePublication,
message: "publication was updated!!!",
});
});
// DELETE
// http://localhost:3000/book-delete/12345ONE
app.delete("/book-delete/:isbn", async (req, res) => {
const { isbn } = req.params;
const deleteBook = await BookModel.deleteOne({ ISBN: isbn });
return res.json({ deletedBook: deleteBook, message: "Book was deleted!!!!" });
});
// http://localhost:3000/book-author-delete/12345ONE/1
app.delete("/book-author-delete/:isbn/:id", async (req, res) => {
// console.log(req.params);
let { isbn, id } = req.params;
id = Number(id);
const getSpecificBook = await BookModel.findOne({ ISBN: isbn });
if (getSpecificBook == null) {
return res.json({ message: `Book not found with ISBN ${isbn}` });
} else {
getSpecificBook.authors.remove(id);
const updateBook = await BookModel.findOneAndUpdate(
{ ISBN: isbn },
getSpecificBook,
{ new: true }
);
return res.json({
updatedBook: updateBook,
message: `${id} was deleted!!!`,
});
}
});
// http://localhost:3000/author-book-delete/1/12345ONE
app.delete("/author-book-delete/:id/:isbn", async (req, res) => {
const { id, isbn } = req.params;
const getSpecificAuthor = await AuthorModel.findOne({ id: id });
if (getSpecificAuthor == null) {
return res.json({ message: `Author not found with ID ${id}` });
} else {
getSpecificAuthor.books.remove(isbn);
const updateAuthor = await AuthorModel.findOneAndUpdate(
{ id: id },
getSpecificAuthor,
{ new: true }
);
return res.json({
updatedAuthor: updateAuthor,
message: `Book with ${isbn} was deleted form ${id}!!!`,
});
}
});
// http://localhost:3000/author-delete/1
app.delete("/author-delete/:id", async (req, res) => {
const { id } = req.params;
const deleteAuthor = await AuthorModel.deleteOne({ id: id });
return res.json({
deletedAuthor: deleteAuthor,
message: `Author deleted with ${id}`,
});
});
// http://localhost:3000/publication-delete/1
app.delete("/publication-delete/:id", async (req, res) => {
const { id } = req.params;
const deletePublication = await PublicationModel.deleteOne({ id: id });
return res.json({
deletedPublication: deletePublication,
message: `Publication deleted with ${id}`,
});
});
app.listen(3000, () => {
console.log("MY EXPRESS APP IS RUNNING.....");
});
|
8aa1df3531927541430c537d21cfbc53332be5e9
|
[
"JavaScript"
] | 1
|
JavaScript
|
thisis-aniket/book_company_API
|
f2b795058b4f0ea0759b9934abe0a6a5a7135930
|
4bad0d94273a2ff28dae4e9dc8b7cd12c84ab8f4
|
refs/heads/main
|
<repo_name>SRUJANA-PENUGONDA13/AffliateWorld<file_sep>/app.py
from flask import Flask, render_template , request, redirect , url_for
import requests
import re
app = Flask(__name__)
@app.route('/')
def api_root():
return render_template('index.html')
@app.route('/urlRedirection', methods=['GET','POST'])
def transform_url():
input_url = request.form['amazonURL']
affiliate_code = "&tag=anupt-21&"
if "amzn.to" in input_url:
response = requests.get(input_url)
redirected_url = response.url
elif "amazon.in" in input_url:
redirected_url = input_url
else:
return render_template('errorURL.html', url_val='{"Response": 500, "Message": "Invalid Url"}')
if "&tag" in redirected_url:
affiliate_name = re.search(r'&tag=(.*?)&', redirected_url).group(1)
affiliate_name = "&tag" + affiliate_name + "&"
redirected_url = redirected_url.replace(
affiliate_name, affiliate_code)
else:
redirected_url = redirected_url + affiliate_code
print(redirected_url)
return render_template('redirectedURL.html', url_val=redirected_url)
if __name__ == '__main__':
app.run(debug = True)
|
bc51b39cc557ee21b3e4403d20df7fe736159c60
|
[
"Python"
] | 1
|
Python
|
SRUJANA-PENUGONDA13/AffliateWorld
|
408a31e94de4b233d5fed494084e46448d6372de
|
f65403b27bbeac9c76d63bd05834855bd4a1a740
|
refs/heads/master
|
<repo_name>qianduan/FramerExamples<file_sep>/Examples/animation-changing-animation-origin.framer/app.js
var layerA;
layerA = new Layer({
x: 25,
y: 25,
width: 128,
height: 128,
backgroundColor: '#28acff',
borderRadius: "6px"
});
/* This defines the distance from the viewer to the elements in the view and enhances 3D effects */
document.body.style.webkitPerspective = 1000;
/* Setting transform origin to the right edge. Both values go from 0 to 1, so 1, 1 will be the bottom right corner. By default, the origin is set to (0.5, 0.5) */
layerA.originX = 1;
layerA.originY = 0.5;
layerA.on(Events.Click, function() {
return layerA.animate({
properties: {
rotationY: 180
},
curve: 'spring',
curveOptions: {
friction: 100
}
});
});
<file_sep>/Examples/draggable-swipe.framer/app.js
/* Imported images from Sketch */
var Numbers, bottomScreen, bottomScreenCurve, screens, topScreen;
screens = Framer.Importer.load("imported/Swipe");
topScreen = screens.firstScreen;
bottomScreen = screens.secondScreen;
bottomScreenCurve = "spring(300,20,30)";
/* Enable dragging */
topScreen.draggable.enabled = true;
topScreen.draggable.speedY = 0;
/* Prevent dragging left */
topScreen.draggable.maxDragFrame = topScreen.frame;
topScreen.draggable.maxDragFrame.width *= 2;
Numbers = new Layer({
backgroundColor: "transparent",
width: 640,
y: 180
});
Numbers.clip = false;
Numbers.html = "Swipe";
Numbers.superLayer = screens.bg;
/* Animate bottomScreen and track dragging distance */
topScreen.on(Events.DragMove, function() {
if (topScreen.x > 0) {
Numbers.html = event.x;
}
return bottomScreen.animate({
properties: {
scale: 0.1 + (event.x / 640),
opacity: event.x / 640
},
curve: bottomScreenCurve
});
});
/* If dragged beyond half of screen, swipe */
topScreen.on(Events.DragEnd, function() {
if (topScreen.x > (this.width / 2)) {
topScreen.animate({
properties: {
x: 650
},
curve: "ease",
time: 0.15
});
} else {
topScreen.animate({
properties: {
x: 0
},
curve: "spring(500,40,20)"
});
Numbers.html = "Swipe";
}
return bottomScreen.animate({
properties: {
scale: 1,
opacity: 1
},
curve: bottomScreenCurve
});
});
<file_sep>/FramerExamplesSite/static/examples/video-basic.framer/app.js
/* Basic video example */
var videoLayer;
videoLayer = new VideoLayer({
video: "http://techslides.com/demos/sample-videos/small.mp4"
});
videoLayer.width = 560 / 2;
videoLayer.height = 320 / 2;
/* Start playing the video, you can find all docs for the player here: https://developer.mozilla.org/en/docs/Web/HTML/Element/video */
videoLayer.player.play();
/* Listen to video events like play, ended. You can find all the listenable events here: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events */
videoLayer.player.on("play", function() {
return print("video.play");
});
videoLayer.player.on("ended", function() {
videoLayer.player.play();
return print("video.ended");
});
/* Bounce the video on a click */
videoLayer.on(Events.Click, function() {
videoLayer.scale = 0.8;
return videoLayer.animate({
properties: {
scale: 1
},
curve: "spring"
});
});
<file_sep>/Examples/draggable-basics.framer/imported/bobbles/layers.json.js
window.__imported__ = window.__imported__ || {};
window.__imported__["bobbles/layers.json.js"] = [
{
"id": 27,
"name": "bobbleJosh",
"layerFrame": {
"x": 0,
"y": 0,
"width": 800,
"height": 734
},
"maskFrame": null,
"image": {
"path": "images/bobbleJosh.png",
"frame": {
"x": 32,
"y": 36,
"width": 146,
"height": 146
}
},
"imageType": "png",
"children": [
],
"modification": "1117496245"
},
{
"id": 15,
"name": "bobbleKayleigh",
"layerFrame": {
"x": 0,
"y": 0,
"width": 800,
"height": 734
},
"maskFrame": null,
"image": {
"path": "images/bobbleKayleigh.png",
"frame": {
"x": 278,
"y": 36,
"width": 146,
"height": 146
}
},
"imageType": "png",
"children": [
],
"modification": "1486868334"
},
{
"id": 32,
"name": "bobbleKeeg",
"layerFrame": {
"x": 0,
"y": 0,
"width": 800,
"height": 734
},
"maskFrame": null,
"image": {
"path": "images/bobbleKeeg.png",
"frame": {
"x": 524,
"y": 36,
"width": 146,
"height": 146
}
},
"imageType": "png",
"children": [
],
"modification": "254390707"
}
]<file_sep>/FramerExamplesSite/static/examples/event-keyboard-shortcuts.framer/app.js
/* First, we'll set up a layer and some states */
var imageLayer;
imageLayer = new Layer({
x: 0,
y: 0,
width: 128,
height: 128,
image: "images/Icon.png"
});
imageLayer.center();
imageLayer.states.add({
second: {
y: 100,
scale: 0.6,
rotationZ: 100
},
third: {
y: 300,
scale: 1.3,
blur: 4
},
fourth: {
y: 200,
scale: 0.9,
blur: 2,
rotationZ: 200
}
});
/* Next, we'll tell our document to listen for keystrokes */
document.addEventListener('keydown', function(event) {
/* event.which gives us the charCode of the key that was pressed
For a list of keyCodes you can use, see: http://css-tricks.com/snippets/javascript/javascript-keycodes/
*/
var key, keyCode;
keyCode = event.which;
/* We'll turn our keyCode to a readable character. The character will be uppercased */
key = String.fromCharCode(keyCode);
/* These are our keyboard shortcuts */
switch (key) {
case 'N':
return imageLayer.states.next();
case 'P':
/* We can also check if special keys like Alt or Shift are pressed.
So to toggle the previous state, you'll need to press Alt + P
*/
if (event.altKey) {
return imageLayer.states.previous();
}
break;
case '1':
return imageLayer.states["switch"]('default');
case '2':
return imageLayer.states["switch"]('second');
case '3':
return imageLayer.states["switch"]('third');
}
});
<file_sep>/FramerExamplesSite/static/examples/shadow-mouse-lightsource.framer/app.js
var bg, layer;
bg = new BackgroundLayer({
backgroundColor: "rgba(77, 208, 225, 1.00)"
});
layer = new Layer({
backgroundColor: "white"
});
layer.center();
window.onmousemove = function(event) {
var alpha, delta, dist;
delta = {
x: layer.midX - event.clientX,
y: layer.midY - event.clientY
};
dist = Math.abs(delta.x) + Math.abs(delta.y);
alpha = Utils.modulate(dist, [0, 150], [0, .4], true);
layer.shadowX = Utils.modulate(delta.x, [0, Screen.width / 2], [0, 50]);
layer.shadowY = Utils.modulate(delta.y, [0, Screen.height / 2], [0, 50]);
layer.shadowBlur = Utils.modulate(dist, [0, 100], [5, 10]);
return layer.shadowColor = "rgba(0,0,0," + alpha + ")";
};
<file_sep>/Examples/event-basics.framer/app.js
/* Text style set-up */
var curve1, layer1, layer2, layer3, textStyle;
textStyle = {
"font-size": "17px",
"text-align": "center",
"line-height": "140px"
};
curve1 = "spring(300,20,50)";
/* Set up layers */
layer1 = new Layer({
x: 50,
y: 50,
width: 140,
height: 140,
backgroundColor: "#0079c6",
borderRadius: "6px"
});
layer2 = new Layer({
x: 220,
y: 50,
width: 140,
height: 140,
backgroundColor: "#26b4f6",
borderRadius: "6px"
});
layer3 = new Layer({
x: 390,
y: 50,
width: 140,
height: 140,
backgroundColor: "#7ed6ff",
borderRadius: "6px"
});
/* Add instruction text to layers, and style them */
layer1.html = "Hover";
layer2.html = "Click";
layer3.html = "MouseDown";
layer1.style = textStyle;
layer2.style = textStyle;
layer3.style = textStyle;
/* On mouse over on the blue layer, shrink it, and mouseout, grow back to original size. */
layer1.on(Events.MouseOver, function() {
return layer1.animate({
properties: {
scale: 0.8
},
curve: curve1
});
});
layer1.on(Events.MouseOut, function() {
return layer1.animate({
properties: {
scale: 1
},
curve: curve1
});
});
/* Scale to 1.2 on click, return to 1 after a 2s delay
Events.Click is triggered on mouseup, or touchend for touch devices */
layer2.on(Events.Click, function() {
layer2.animate({
properties: {
scale: 1.2
},
curve: curve1
});
return Utils.delay(2, function() {
return layer2.animate({
properties: {
scale: 1
},
curve: curve1
});
});
});
/* Shrink on MouseDown, Grow on MouseUp.
Events.TouchStart and Events.TouchEnd are used as they return both Mouse Events or Touch Events, depending on device. */
layer3.on(Events.TouchStart, function() {
layer3.animate({
properties: {
scale: 0.8
},
curve: curve1
});
return layer3.html = "MouseUp";
});
layer3.on(Events.TouchEnd, function() {
layer3.animate({
properties: {
scale: 1
},
curve: curve1
});
return layer3.html = "Mouse Down";
});
<file_sep>/FramerExamplesSite/static/examples/animation-staggered.framer/app.js
var ballCurve, ballMargin, ballSize, cols, rows, startDelta, _i, _results;
rows = 4;
cols = 4;
ballSize = 100;
ballMargin = 40;
ballCurve = "spring(300,20,0)";
startDelta = 200;
(function() {
_results = [];
for (var _i = 1; 1 <= rows ? _i <= rows : _i >= rows; 1 <= rows ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this).map(function(a) {
var _i, _results;
return (function() {
_results = [];
for (var _i = 1; 1 <= cols ? _i <= cols : _i >= cols; 1 <= cols ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this).map(function(b) {
var B1, G1, R1, ball;
ball = new View({
x: b * (ballSize + ballMargin),
y: a * (ballSize + ballMargin) + startDelta,
width: ballSize,
height: ballSize,
opacity: 0
});
R1 = 240 / cols * a;
G1 = 220 / rows * b;
B1 = 200;
ball.style = {
backgroundColor: "rgba(" + R1 + "," + G1 + "," + B1 + ",1)",
borderRadius: "50%",
border: "4px solid white",
lineHeight: ball.height - 5 + "px"
};
ball.html = "" + a + ", " + b;
ball.states.add('fadein', {
y: a * (ballSize + ballMargin),
opacity: 1
});
ball.states.animationOptions = {
curve: ballCurve
};
ball.states.animationOptions.delay = 0.05 * a + 0.05 * b;
return ball.states["switch"]('fadein');
});
});
<file_sep>/Examples/color-switch.framer/app.js
var bg, card, check, error, green, red;
bg = new BackgroundLayer({
backgroundColor: "#00497F"
});
/* Animation */
Framer.Defaults.Animation = {
curve: "spring(260,30,0,0)"
};
/* Card */
card = new Layer({
width: 240,
height: 240,
backgroundColor: "#A8E5FE"
}).center();
card.shadowY = 5;
card.shadowBlur = 20;
card.shadowColor = "rgba(0,0,0,0.3)";
/* Banners */
red = new Layer({
width: 240,
height: 60,
backgroundColor: "#F14445",
superLayer: card
});
green = new Layer({
width: 240,
height: 60,
y: -60,
backgroundColor: "#98B035",
superLayer: card
});
/* Images */
error = new Layer({
width: 86,
height: 86,
image: "images/error.png"
}).centerX().centerY(+20);
check = new Layer({
width: 86,
height: 86,
image: "images/check.png"
}).centerX().centerY(+20);
/* States */
red.states.add({
up: {
y: -60
}
});
green.states.add({
down: {
y: 0
}
});
error.states.add({
small: {
scale: 0
}
});
check.states.add({
big: {
scale: 1
},
small: {
scale: 0
}
});
check.states.switchInstant("small");
/* Place behind statement */
red.states.on(Events.StateWillSwitch, function(stateA, stateB) {
if (stateB === "up") {
red.placeBehind(green);
return error.placeBehind(check);
} else {
green.placeBehind(red);
return check.placeBehind(error);
}
});
bg.on(Events.Click, function() {
red.states.next();
green.states.next();
error.states.next();
return check.states.next("big", "small");
});
<file_sep>/FramerExamplesSite/static/examples/shadow-dragging.framer/app.js
var background, layer;
background = new BackgroundLayer({
backgroundColor: "rgba(77, 208, 225, 1.00)"
});
layer = new Layer({
x: 100,
y: 100,
width: 200,
height: 200,
backgroundColor: "white"
});
layer.center();
layer.shadowColor = "rgba(0, 0, 0, 0.2)";
layer.states.add({
elevatedZ4: {
shadowY: 16,
shadowBlur: 28,
shadowColor: "rgba(0, 0, 0, 0.22)"
}
});
layer.states.animationOptions = {
curve: "ease-in",
time: 0.15
};
layer.draggable.enabled = true;
layer.on(Events.DragStart, function() {
return layer.states["switch"]("elevatedZ4");
});
layer.on(Events.DragEnd, function() {
return layer.states["switch"]("default");
});
<file_sep>/Examples/event-pull-to-refresh.framer/app.js
/* Pull to Refresh Example */
/* This example shows how to implement pull to fresh, as seen in the
Twitter for iOS app. To get started, take a look at the PSD
to see how the layers and groups are set up. The pull to refresh
control in Twitter features an arrow that changes direction if
you've pulled enough, and then a spinner to indicate loading status. */
/* Initial set up. Import our PSD, set up global variables. We want to
hide our spinner layer until you let go (and have pulled enough) */
var PSD, animating, deltaY, springCurve, startY, timelineStartY;
PSD = Framer.Importer.load("imported/Pull to refresh");
PSD.spinner.scale = 0;
deltaY = 0;
startY = 0;
timelineStartY = PSD.timeline.y;
animating = false;
springCurve = "spring(200,20,0)";
PSD.timeline.draggable.enabled = true;
PSD.timeline.draggable.speedX = 0;
PSD.timeline.superLayer = PSD.bg;
PSD.bg.clip = true;
/* When you click (or taps), we need to grab the y position of
that click so that we can use it when you drag (to see how far
they have pulled. We also want to reset values for our refresh
control so everything is correct in case you pull to refresh
more than once. */
PSD.timeline.on(Events.DragStart, function(event) {
console.log(event);
startY = event.pageY;
PSD.spinner.scale = 0;
PSD.spinner.rotation = 0;
PSD.arrow.scale = 1;
return PSD.arrow.rotation = 0;
});
/* When you drag, several things should happen. The first is that
the timeline should follow your mouse/finger. The arrow should
also animate once you have pulled enough, letting you know you
can release to refresh. */
PSD.timeline.on(Events.DragMove, function(event) {
/* Figure out how far you have pulled, and then move the timeline
and refresh controls that amount
*/
deltaY = startY - event.pageY;
PSD.timeline.y = timelineStartY - deltaY;
PSD.refreshControl.y = PSD.timeline.y - 70;
/* If you have pulled enough (in this case more than 100 pixels)
and if the arrow is not animating, then flip the arrow and
set animating to true. We do this so that the arrow doesn't
try and animate each time you move, which would be very janky.
By using an animating variable, the animation only gets called
once, and is very smooth.
*/
if (deltaY < -100) {
if (animating === false) {
PSD.arrow.animate({
properties: {
rotation: -180
},
curve: springCurve
});
return animating = true;
}
} else {
/* If you have pulled more than 100px, but then drag back up,
flip the arrow back. We use the same animating variable to
make sure we only try and animate if you already pulled
past 100px, and we only call animate once.
*/
if (animating === true) {
PSD.arrow.animate({
properties: {
rotation: 0
},
curve: springCurve
});
return animating = false;
}
}
});
/* On touch end, if you pulled and released past 100px, then
we hide the arrow, bring back the spinner, and animate it,
and then after a delay, animate back to the starting position.
If you pulled and released under 100px, then just animate
back to the starting position. */
PSD.timeline.on(Events.DragEnd, function() {
if (deltaY < -100) {
PSD.refreshControl.animate({
properties: {
y: timelineStartY + 25
},
curve: springCurve
});
PSD.arrow.animate({
properties: {
scale: 0
},
curve: springCurve
});
PSD.spinner.animate({
properties: {
scale: 1
},
curve: springCurve
});
PSD.spinner.animate({
properties: {
rotation: 720
},
time: 2
});
PSD.timeline.animate({
properties: {
y: timelineStartY + 100
},
curve: springCurve
});
/* We use Utils.delay to set a 2 second delay, and then
call our animations
*/
return Utils.delay(2, function() {
PSD.refreshControl.animate({
properties: {
y: timelineStartY - 70
},
curve: springCurve
});
PSD.spinner.animate({
properties: {
scale: 0
},
curve: springCurve
});
return PSD.timeline.animate({
properties: {
y: timelineStartY
},
curve: springCurve
});
});
} else {
PSD.refreshControl.animate({
properties: {
y: timelineStartY - 70
},
curve: springCurve
});
return PSD.timeline.animate({
properties: {
y: timelineStartY
},
curve: springCurve
});
}
});
<file_sep>/FramerExamplesSite/static/examples/draggable-basics.framer/app.js
/* Draggable Basics */
/* This example will show you the basics of draggable, a handy function that makes any layer draggable! This is super handy for drag and drop and there are many other things you can do as well. To read more about draggable, go here: [link to draggable part of the site] */
/* Set up some labels, and our drop target */
var PSD, dropTarget, initMidX, initX, initY, joshLabel, kayleighLabel, keegLabel, sharedStyle, windowHeight, windowWidth;
sharedStyle = {
"font-size": "18px",
"text-align": "center",
"padding-top": "50px",
"line-height": "24px"
};
joshLabel = new Layer({
x: 26,
y: 130,
width: 156,
height: 156,
backgroundColor: "none"
});
joshLabel.html = "Draggable";
joshLabel.style = sharedStyle;
kayleighLabel = new Layer({
x: 274,
y: 130,
width: 156,
height: 156,
backgroundColor: "none"
});
kayleighLabel.html = "Draggable with resistance";
kayleighLabel.style = sharedStyle;
keegLabel = new Layer({
x: 518,
y: 130,
width: 156,
height: 156,
backgroundColor: "none"
});
keegLabel.html = "Draggable with dynamic resistance";
keegLabel.style = sharedStyle;
dropTarget = new Layer({
x: 26,
y: 500,
width: 156,
height: 156,
backgroundColor: "teal"
});
dropTarget.html = "Drop the bobble above in me!";
dropTarget.style = sharedStyle;
/* Import graphics from Photoshop */
PSD = Framer.Importer.load("imported/bobbles");
/* The first shows bobble the default behavior when you make a layer draggable, and also how to implement a drop target. */
/* Make the view draggable. By default, this means when you click and drag (or tap and move), the layer will follow your cursor/finger. When you release, the layer stays where you last left it. All with one line of code! */
PSD.bobbleJosh.draggable.enabled = true;
/* When you drop the first bobble, we calculate the distance from its center to the center of the drop target. If the distance is less than 16 (which means the bobble is fully inside the drop target), then the color of the drop target changes to green. If it's outside the target, the color stays teal. */
PSD.bobbleJosh.on(Events.DragEnd, function() {
var dX, dY;
dX = Math.abs(dropTarget.midX - PSD.bobbleJosh.midX);
dY = Math.abs(dropTarget.midY - PSD.bobbleJosh.midY);
if (dX < 16 && dY < 16) {
return dropTarget.backgroundColor = "green";
} else {
return dropTarget.backgroundColor = "teal";
}
});
/* The second bobble shows how to add resistance to a layer that is draggable. This means that instead of a 1 to 1 mapping to your cursor/finger when you drag, the layer moves some fraction (defined as speed) of the distance you have moved. You can set this on both X and Y, and the values can be different. */
PSD.bobbleKayleigh.draggable.enabled = true;
PSD.bobbleKayleigh.draggable.speedX = 0.6;
PSD.bobbleKayleigh.draggable.speedY = 0.6;
/* The final example shows how to add dynamic resistance to a layer. This is a bit more advanced, but still not too bad. */
/* Make the layer draggable, and set some initial vars that we'll use later (like the position of the layer, the window width and height). */
PSD.bobbleKeeg.draggable.enabled = true;
initX = PSD.bobbleKeeg.x;
initMidX = PSD.bobbleKeeg.midX;
initY = PSD.bobbleKeeg.y;
windowHeight = window.innerHeight;
windowWidth = window.innerHeight;
/* When the layer is being dragged, we change the speed (resistance) dynamically, based on how far away the cursor is from the starting point of the layer. */
PSD.bobbleKeeg.on(Events.DragMove, function(event) {
/* Grab the delta for x distance (We do this for X and not for Y because the bobble is horizontally in the middle of the screen, so delta can be positive or negative */
var deltaX, speedX, speedY;
deltaX = initMidX - event.x;
/* Since the Y drag can basically only go in one direction, we can immediately map the range. This handy function takes the current y position and maps that from the initial Y to the maximum Y, in this case the window height to a 0.5 to 1 range. This means that the further away from the layer's initial position the drag is, the more resistance we add, such that if you drag all the way to the bottom of the view, the layer will eventually be unable to go further. */
speedY = Utils.mapRange(event.y, windowHeight, initY, 0.5, 1);
/* Since you can drag left or right, we need to map the range correctly. If deltaX is positive, we map from the start of the view to the mid point of the layer (everything left of the layer). If the deltaX is negative, we map from the mid point of the layer to the edge of the screen (everything right of the layer). */
if (deltaX > 0) {
speedX = Utils.mapRange(event.x, 0, initMidX, 0.5, 1);
} else {
speedX = Utils.mapRange(event.x, windowWidth, initMidX, 0.5, 1);
}
/* Set the speeds */
PSD.bobbleKeeg.draggable.speedY = speedY;
return PSD.bobbleKeeg.draggable.speedX = speedX;
});
/* When the drag is finished, snap back to initial position */
PSD.bobbleKeeg.on(Events.DragEnd, function() {
return PSD.bobbleKeeg.animate({
properties: {
x: initX,
y: initY
},
curve: "spring(300,18,10)"
});
});
<file_sep>/Examples/state-machine-basics.framer/app.js
/* States provie a simple way to organize animation code.
You can define a set of states, which are a collection of properties with values, by name */
var layerA, layerB, layerC;
layerA = new Layer({
width: 100,
height: 100,
backgroundColor: "#17a5ff",
y: 30,
x: 30,
borderRadius: "8px"
});
/* Define states
There is always a 'default' state that contains the initial properties */
layerA.states.add({
stateA: {
rotation: 180
},
stateB: {
rotation: 60
}
});
/* Switch to State A on click */
layerA.on(Events.Click, function() {
return layerA.states["switch"]("stateA");
});
/* Normally you'd want to toggle or cycle through states.
That is where the .next() function comes in */
layerB = new Layer({
width: 100,
height: 100,
y: 160,
x: 30,
backgroundColor: "#64c3ff",
borderRadius: "8px"
});
layerB.states.add({
stateA: {
rotation: 180
},
stateB: {
rotation: 60
},
stateC: {
rotation: 0,
hueRotate: 60
}
});
/* There are 4 states in total (The defined states + the default state) */
layerB.on(Events.Click, function() {
return layerB.states.next();
});
/* The .next() function also takes a list of state names. */
layerC = new Layer({
width: 100,
height: 100,
y: 290,
x: 30,
backgroundColor: "#8ee8ff",
borderRadius: "8px"
});
layerC.states.add({
stateA: {
y: 200,
rotation: 180
},
stateB: {
y: 300,
x: 40,
rotation: 60
},
stateC: {
y: 400,
x: 40,
rotation: 0
}
});
layerC.on(Events.Click, function() {
/* Cycle through states C and B */
return layerC.states.next("stateC", "stateB");
});
/* Control state animations with the .animationOptions keyword */
layerC.states.animationOptions = {
curve: "spring",
curveOptions: {
tension: 200,
friction: 3
}
};
<file_sep>/Examples/scrolling-parallax.framer/app.js
var container, lastYPosition, layer1, layer2, layer3;
container = new Layer({
width: 640,
height: 1136,
backgroundColor: "#7ed6ff"
});
layer3 = new Layer({
superLayer: container,
x: -35,
y: 574,
width: 634,
height: 1718,
image: "images/layer3.png"
});
layer2 = new Layer({
superLayer: container,
x: -62,
y: -55,
width: 750,
height: 2222,
image: "images/layer2.png"
});
layer1 = new Layer({
superLayer: container,
x: -62,
y: 86,
width: 750,
height: 1751,
image: "images/layer1.png"
});
/* Storing the y position of the last touch on the screen */
lastYPosition = 0;
/* Record y position of Touch */
container.on(Events.TouchStart, function(event) {
return lastYPosition = event.y;
});
/* As we slide, we update the lastYPosition and calculate the distance */
container.on(Events.TouchMove, function(event) {
var yDelta;
yDelta = lastYPosition - event.y;
lastYPosition = event.y;
/* On every movement, we update the y property
Move in opposite direction
*/
layer1.y += yDelta;
/* Move in 0.3 times the normal speed */
layer2.y -= yDelta * 0.3;
/* Move twice as fast */
return layer3.y -= yDelta * 2;
});
<file_sep>/FramerExamplesSite/static/examples/event-pull-to-refresh.framer/imported/Pull to refresh/layers.json.js
window.__imported__ = window.__imported__ || {};
window.__imported__["Pull to refresh/layers.json.js"] = [
{
"id": 19,
"name": "bg",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/bg.png",
"frame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
}
},
"imageType": "png",
"children": [
],
"modification": "590045692"
},
{
"id": 11,
"name": "timeline",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/timeline.png",
"frame": {
"x": 0,
"y": 128,
"width": 640,
"height": 919
}
},
"imageType": "png",
"children": [
],
"modification": "304473853"
},
{
"id": 27,
"name": "refreshControl",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": null,
"imageType": null,
"children": [
{
"id": 25,
"name": "arrow",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/arrow.png",
"frame": {
"x": 308,
"y": 69,
"width": 24,
"height": 39
}
},
"imageType": "png",
"children": [
],
"modification": "1585210142"
},
{
"id": 13,
"name": "spinner",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/spinner.png",
"frame": {
"x": 293,
"y": 61,
"width": 54,
"height": 56
}
},
"imageType": "png",
"children": [
],
"modification": "1585210138"
}
],
"modification": "837395570"
},
{
"id": 17,
"name": "tabbar",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/tabbar.png",
"frame": {
"x": 0,
"y": 1047,
"width": 640,
"height": 89
}
},
"imageType": "png",
"children": [
],
"modification": "2099275293"
},
{
"id": 15,
"name": "navbar",
"layerFrame": {
"x": 0,
"y": 0,
"width": 640,
"height": 1136
},
"maskFrame": null,
"image": {
"path": "images/navbar.png",
"frame": {
"x": 0,
"y": 0,
"width": 640,
"height": 128
}
},
"imageType": "png",
"children": [
],
"modification": "690734855"
}
]<file_sep>/Examples/shadow-elevate-states.framer/app.js
var background, layer;
background = new BackgroundLayer({
backgroundColor: "rgba(77, 208, 225, 1.00)"
});
layer = new Layer({
x: 100,
y: 100,
width: 200,
height: 200,
backgroundColor: "white"
});
layer.center();
layer.shadowColor = "rgba(0, 0, 0, 0.2)";
layer.style = {
"color": "black",
"line-height": "200px",
"text-align": "center"
};
/* These are loosely based on the Google Material specs */
layer.states.add({
elevatedZ1: {
shadowY: 2,
shadowBlur: 10
},
elevatedZ2: {
shadowY: 6,
shadowBlur: 20
},
elevatedZ3: {
shadowY: 12,
shadowBlur: 15
},
elevatedZ4: {
shadowY: 16,
shadowBlur: 28
},
elevatedZ5: {
shadowY: 27,
shadowBlur: 24
}
});
layer.states.animationOptions = {
curve: "ease-in",
time: 0.15
};
layer.on(Events.Click, function() {
layer.states.next();
return layer.html = layer.states.current;
});
layer.html = "Click me";
<file_sep>/Examples/draggable-swipe.framer/imported/Swipe/layers.json.js
window.__imported__ = window.__imported__ || {};
window.__imported__["Swipe/layers.json.js"] = [
{
"id": "02A83424-6F6D-40AC-8FAA-C26E8D3170AD",
"name": "iphone",
"maskFrame": null,
"layerFrame": {
"x": 143,
"y": 157,
"width": 804,
"height": 1644
},
"image": {
"path": "images/02A83424-6F6D-40AC-8FAA-C26E8D3170AD.png",
"frame": {
"x": 143,
"y": 157,
"width": 804,
"height": 1644
}
},
"imageType": "png",
"modification": null,
"children": [],
"visible": true
},
{
"id": "470F041D-8A46-4EFD-A712-9D74FC525357",
"name": "bg",
"maskFrame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
},
"layerFrame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
},
"image": {
"path": "images/470F041D-8A46-4EFD-A712-9D74FC525357.png",
"frame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
}
},
"imageType": "png",
"modification": null,
"children": [
{
"id": "1B78257E-9319-4A71-BB12-715B4FE6A1F7",
"name": "firstScreen",
"maskFrame": null,
"layerFrame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
},
"image": {
"path": "images/1B78257E-9319-4A71-BB12-715B4FE6A1F7.png",
"frame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
}
},
"imageType": "png",
"modification": null,
"children": [],
"visible": true
},
{
"id": "6D24AF57-C6EE-49A0-B106-094064C4F823",
"name": "secondScreen",
"maskFrame": null,
"layerFrame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
},
"image": {
"path": "images/6D24AF57-C6EE-49A0-B106-094064C4F823.png",
"frame": {
"x": 229,
"y": 414,
"width": 640,
"height": 1136
}
},
"imageType": "png",
"modification": null,
"children": [],
"visible": true
}
],
"visible": true
}
]<file_sep>/FramerExamplesSite/static/examples/draggable-snap.framer/app.js
/* Create a new layer and center it */
var layerA, originX, originY;
layerA = new Layer({
width: 256,
height: 256
});
layerA.center();
originX = layerA.x;
originY = layerA.y;
layerA.image = "https://pbs.twimg.com/profile_images/442744361017540608/NCEct4yy.jpeg";
layerA.style = {
borderRadius: '50%',
boxShadow: 'inset 0 0 0 10px #fff, 0 4px 12px rgba(0,0,0,0.4)'
};
/* Make the layer draggable */
layerA.draggable.enabled = true;
/* Add an animation to the end of a drag */
layerA.on(Events.DragEnd, function(event, layer) {
/* Snap back to origin */
var animation;
return animation = layer.animate({
properties: {
x: originX,
y: originY
},
curve: "spring",
curveOptions: {
friction: 20,
tension: 400,
velocity: 20
}
});
});
<file_sep>/FramerExamplesSite/static/examples/material-response.framer/app.js
var Background, Container, Field, colNumber, _i;
Background = new BackgroundLayer({
backgroundColor: "#f6f6f6"
});
/* Placing all fields within a container */
Container = new Layer({
backgroundColor: "transparent",
width: 400,
height: 400
});
Container.center();
Container.style.padding = "10px 0 0 0 ";
/* 3 Fields */
for (colNumber = _i = 0; _i < 3; colNumber = ++_i) {
Field = new Layer({
width: 360,
height: 100,
backgroundColor: "#fff",
shadowY: 2,
shadowBlur: 5,
borderRadius: "6px",
y: colNumber * 120
});
Field.shadowColor = "rgba(0, 0, 0, 0.25)";
Field.superLayer = Container;
Field.centerX();
/* Each field gets its own Highlight and Shadow animation */
Field.on(Events.Click, function(event, Field) {
var Highlight, fieldAnimation, highlightAnimation;
Highlight = new Layer({
width: 10,
height: 10,
backgroundColor: "#eeeeee",
borderRadius: "50%",
opacity: 0
});
Highlight.superLayer = Field;
Highlight._prefer2d = true;
/* Matching the Highlight position with the click position */
Highlight.x = event.clientX - Container.x - Field.x - (Highlight.width / 2);
Highlight.y = event.clientY - Container.y - Field.y - (Highlight.height / 2);
/* Grow Highlight */
highlightAnimation = Highlight.animate({
properties: {
width: Field.width + 20,
height: 400,
opacity: 1,
x: -10,
y: -161
},
curve: "ease",
time: 0.25
});
/* Fade & Reset Highlight */
highlightAnimation.on("end", function() {
Highlight.animate({
properties: {
opacity: 0
},
curve: "ease",
time: 0.1
});
return utils.delay(0.1, function() {
/* Resetting the Highlight properties */
Highlight.width = 80;
return Highlight.height = 80;
});
});
/* Animate Shadow */
fieldAnimation = Field.animate({
properties: {
shadowY: 10,
shadowBlur: 16
},
curve: "ease",
time: 0.4
});
/* Reset Shadow */
return fieldAnimation.on("end", function() {
return Field.animate({
properties: {
shadowY: 2,
shadowBlur: 5
},
curve: "ease",
time: 0.4
});
});
});
}
<file_sep>/FramerExamplesSite/pages/index.html
{% extends "base.html" %}
{% block content %}
<section id="topbar"><img class="2x" src="/static/images/icon-arrow.png"></section>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="{% static '/js/index.js' %}"></script>
<script src="{% static '/js/main.js' %}"></script>
<div id="right-section">
<section class="padding">
<iframe id="code" name="code" src=""></iframe>
<iframe id="example" name="example" src=""></iframe>
</section>
</div>
<div class="navigation">
<section class="padding">
<h1><a href="http://www.framerjs.com">Framer</a> Examples</h1>
<ul>
<li class="headline">Prototypes</li>
<li><a href="#carousel-onboarding.framer">Carousel - Onboarding</a></li>
<li><a href="#facebook-newsfeed-photos.framer">Facebook - NewsFeed</a></li>
<li><a href="#google-now-overview.framer">Google Now - Overview</a></li>
<li><a href="#potluck-onboarding.framer">Potluck - Onboarding</a></li>
<li class="headline">Examples</li>
<li><a class="basics" href="#animation-basics.framer">Animation - Basics</a></li>
<li><a href="#animation-chaining-animations.framer">Animation - Chaining</a></li>
<li><a href="#animation-changing-animation-origin.framer">Animation - Origin</a></li>
<li><a href="#animation-staggered.framer">Animation - Staggered</a></li>
<li><a href="#album-animation.framer">Android - Album Animation</a></li>
<li><a href="#on-time.framer">Android - On Time</a></li>
<li><a href="#card-dragging.framer">Card Dragging</a></li>
<li><a href="#card-feed.framer">Card Feed</a></li>
<li><a href="#color-switch.framer">Color Switch</a></li>
<li><a href="#draggable-basics.framer">Draggable - Basics</a></li>
<li><a href="#draggable-momentum.framer">Draggable - Momentum</a></li>
<li><a href="#draggable-snap.framer">Draggable - Snap</a></li>
<li><a href="#draggable-simpleswitch.framer">Draggable - SimpleSwitch</a></li>
<li><a href="#draggable-swipe.framer">Draggable - Swipe</a></li>
<li><a href="#draggable-dribbble.framer">Draggable - Dribbble Data</a></li>
<li><a href="#dynamic-color.framer">Dynamic Color</a></li>
<li><a href="#event-basics.framer">Event - Basics</a></li>
<li><a href="#event-checkmark.framer">Event - Checkmark</a></li>
<li><a href="#event-pull-to-refresh.framer">Event - Pull to Refresh</a></li>
<li><a href="#event-keyboard-shortcuts.framer">Event - Keyboard Shortcuts</a></li>
<li><a href="#load-and-display.framer">Load and Display</a></li>
<li><a href="#material-response.framer">Material Response</a></li>
<li><a href="#material-transition.framer">Material Transition</a></li>
<li><a href="#scrolling-parallax.framer">Scrolling - Parallax</a></li>
<li><a href="#state-machine-basics.framer">States - Basics</a></li>
<li><a href="#state-machine-drawer-navigation-menu.framer">States - Drawer Navigation</a></li>
<li><a href="#state-machine-dynamic-properties.framer">States - Dynamic Properties</a></li>
<li><a href="#shadow-elevate-states.framer">Shadow - Elevation States</a></li>
<li><a href="#shadow-dragging.framer">Shadow - Dragging</a></li>
<li><a href="#shadow-mouse-lightsource.framer">Shadow - Light Source</a></li>
<li><a href="#tooltip-fadein.framer">Tooltip Fade-in</a></li>
<li><a href="#video-basic.framer">Video - Basic Example</a></li>
</ul>
<!---<a class="submit" href="https://github.com/koenbok/FramerExamples">Submit your own</a>-->
</section>
</div>
<a class="download" href="#">Download</a>
{% endblock content%}
<file_sep>/FramerExamplesSite/static/examples/draggable-momentum.framer/app.js
/* Create a new layer and center it */
var layerA;
layerA = new Layer;
layerA.center();
/* Make the layer draggable */
layerA.draggable.enabled = true;
Utils.labelLayer(layerA, "Drag me");
/* Add an animation to the end of a drag to mimic momentum */
layerA.on(Events.DragEnd, function(event, layer) {
/* These are two variables you can tweak for different effects */
var animation, constant1, constant2, totalVelocity, velocity;
constant1 = 1000;
constant2 = 0;
/* Calculate the current dragging velocity and add x and y up */
velocity = layer.draggable.calculateVelocity();
totalVelocity = Utils.pointTotal(Utils.pointAbs(velocity));
/* The momentum animation is actually a spring animation with very high friction. You can change the the other spring values for different effects */
return animation = layer.animate({
properties: {
x: parseInt(layer.x + (velocity.x * constant1)),
y: parseInt(layer.y + (velocity.y * constant1))
},
curve: "spring",
curveOptions: {
friction: 100,
tension: 80,
velocity: totalVelocity * constant2
}
});
});
|
0a58c9eac8ab5302df2beb73a18dab0f7e79f2b3
|
[
"JavaScript",
"HTML"
] | 21
|
JavaScript
|
qianduan/FramerExamples
|
aefd7d0bfcbcfcddbd748df85a203177cdc58291
|
34f78878190a5705e5d80da631c426d04640cd63
|
refs/heads/master
|
<repo_name>Etesam913/interactive-login<file_sep>/src/MediumAnimatedButton.js
import React from 'react';
import './LoginAnimation.css';
import { motion } from "framer-motion";
export function MediumAnimatedButton(props){
const [scale, setScale]= React.useState(1);
const shrinkButton = () => setScale(.85);
const enlargeButton = () => setScale(1);
return(
<motion.button
initial = {{opacity: 0}}
animate = {{scale, opacity: 1}}
transition = {{scale: {duration: .3}, opacity: {duration: 1.2, delay: 2.5}}}
className = {props.isDark ? "darkRoundedButton" : "lightRoundedButton"}
onMouseDown = {shrinkButton}
onMouseUp = {enlargeButton}
onMouseLeave = {enlargeButton}
onClick = {props.input}
>
{props.title}
</motion.button>
);
}
export default MediumAnimatedButton;<file_sep>/README.md
# Interactive Login
## Default

## When a password is entered

<file_sep>/src/LoginAnimation.js
import React from 'react';
import { motion } from "framer-motion"
import MediumAnimatedButton from './MediumAnimatedButton'
import './LoginAnimation.css';
/*
The app creates an interactive login that has a goofy character that oversees the process.
By <NAME>
*/
class LoginAnimation extends React.Component{
_isMounted = false;
passwordText = "";
constructor(props){
super(props);
this.state = {input1: "", input2: "", buttonText: "Dark Mode", isEmpty: true, isDark: false};
this.resetForm1 = this.resetForm1.bind(this);
this.resetForm2 = this.resetForm2.bind(this);
this.handleChange = this.handleChange.bind(this);
this.makeDark = this.makeDark.bind(this);
}
// Changes state based off of time interval
/*componentDidMount() {
setInterval(() => {
this.setState({isExpand: !this.state.isExpand});
}, 1000);
}*/
componentDidMount(){
this._isMounted = true;
}
componentWillUnmount(){
this._isMounted = false;
}
handleChange(event) {
if(this._isMounted && event.target.id == "input1"){
this.setState({input1: event.target.value});
}
if(this._isMounted && event.target.id == "input2"){
var value = event.target.value;
this.setState({input2: event.target.value});
this.displayMessage(value);
}
}
resetForm1(){
if(this._isMounted){
this.setState({input1: ""});
}
}
resetForm2(){
if(this._isMounted){
this.setState({input2: ""});
this.displayMessage("");
}
}
displayMessage(text){
if(text.length > 0 && this._isMounted){
this.setState({isEmpty: false});
}
if(text.length == 0 && this._isMounted){
this.setState({isEmpty: true});
}
}
makeDark(){
if(this._isMounted){
this.setState({isDark: !this.state.isDark});
if(this.state.buttonText === "Dark Mode"){
this.setState({buttonText : "Light Mode"})
}
else if(this.state.buttonText === "Light Mode"){
this.setState({buttonText: "Dark Mode"});
}
}
}
render(){
return(
<div className = {this.state.isDark ? "darkBackground" : "lightBackground"}>
<motion.button
className= {this.state.isDark ? "changeToDarkButton" : "changeToLightButton"}
whileTap={{scale: .9}}
onClick={this.makeDark}>{/*width="7em" height="2em" color={this.state.isDark ? Color("#333333") : Color("#e5e5e5")} background={this.state.isDark ? Color("#e5e5e5") : Color("#333333")}}*/}
{this.state.buttonText}
</motion.button>
<motion.h1
className={this.state.isDark ? "darkModeTitle" : "lightModeTitle"}
initial={{opacity: 0, x: "-150%"}}
animate={{opacity: 1, x: "0%"}}
transition = {{duration: 2}}>
Interactive Login
</motion.h1>
<motion.h2
className={this.state.isDark ? "darkModeTitle" : "lightModeTitle"}
initial={{opacity: 0, x: "-200%"}}
animate={{opacity: 1, x: "0%"}}
transition = {{duration: 2, delay: .5}}>
By <NAME>
</motion.h2>
<div className = "imageContainer">
<motion.div className = "loginViewer" initial={{opacity: 0}} animate={{opacity: 1}} transition = {{duration: 2, delay: 2}}>
<motion.div className = "hand" initial={{x:"-250%", opacity: 0}} animate={this.state.isEmpty ? {opacity: 0, x:"-250%"} : {opacity: 1, x: "20%"}} transition={{duration: 1}}></motion.div>
<motion.div className = {this.state.isEmpty ? "speechBubbleNoPassword" : "speechBubblePassword"} /> {/*initial={{opacity: 0}} animate={this.state.isEmpty ? {opacity: 0} : {opacity: 1}*/}
</motion.div>
</div>
<span>
<motion.input
type="text"
className = {this.state.isDark ? "darkRoundedInput" : "lightRoundedInput"}
id={"input1"}
value = {this.state.input1}
onChange = {this.handleChange}
initial={{opacity: 0}}
animate = {{opacity: 1}}
transition = {{duration: 1.2, delay: 2.5}}
/>
<MediumAnimatedButton title = 'Submit Username' input = {this.resetForm1} isDark = {this.state.isDark}/>
</span>
<span>
<motion.input
type="text"
className = {this.state.isDark ? "darkRoundedInput" : "lightRoundedInput"}
id={"input2"}
value = {this.state.input2}
onChange = {(event) => {
this.handleChange(event);
}}
initial={{opacity: 0}}
animate = {{opacity: 1}}
transition = {{duration: 1.2, delay: 2.5}}
/>
<MediumAnimatedButton title = 'Submit Password' input = {this.resetForm2} isDark = {this.state.isDark}/>
</span>
</div>
);
}
}
export default LoginAnimation;
|
916bdd766aeb624f1eba7f4af39bce7fddc04b62
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Etesam913/interactive-login
|
58caef2422da7b3e79ab92165f27932448cca66e
|
f8194d656928b152bf0af1d3e8bb41c257160f51
|
refs/heads/master
|
<file_sep>FROM logstash:latest
RUN logstash-plugin install logstash-input-syslog
RUN logstash-plugin install logstash-input-gelf
RUN logstash-plugin install logstash-codec-json
RUN logstash-plugin install logstash-filter-json
# Add your logstash plugins setup here
# Example: RUN logstash-plugin install logstash-filter-json
<file_sep>package command
import "github.com/micro/go-micro"
var ServiceName string = "todo.command"
func NewService() micro.Service {
var service micro.Service
service = micro.NewService(
micro.Name(ServiceName),
)
return service
}
func NewClient() CommanderClient {
opts := []micro.Option{
micro.Name(ServiceName + ".client"),
}
service := micro.NewService(opts...)
return NewCommanderClient(ServiceName, service.Client())
}
<file_sep>FROM golang:1.7-wheezy
RUN mkdir -p "$GOPATH/src/github.com/yarbelk/todo/"
COPY . "$GOPATH/src/github.com/yarbelk/todo/"
WORKDIR "$GOPATH/src/github.com/yarbelk/todo/"
RUN make
<file_sep>package log
import (
"encoding/json"
"fmt"
"net"
"github.com/micro/go-platform/log"
)
var DefaultRAddress net.TCPAddr = net.TCPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 5000,
Zone: "",
}
type OutputOptions struct {
RAddress net.IP
RPort int
LAddress net.IP
}
type OutputOption func(*OutputOptions)
type TcpOutput struct {
options OutputOptions
conn net.Conn
raddress *net.TCPAddr
laddress *net.TCPAddr
err error
}
// connect to the sink. TODO make this use a pool? auto reconnect?
func (to *TcpOutput) connect() error {
to.conn, to.err = net.DialTCP("tcp", to.laddress, to.raddress)
fmt.Println("connecting", to.conn, to.err)
return to.err
}
// Send an event
func (to *TcpOutput) Send(e *log.Event) error {
if to.conn == nil {
fmt.Println("TCP output connection is nil")
if err := to.connect(); err != nil {
fmt.Println(err.Error())
return err
}
}
return json.NewEncoder(to.conn).Encode(e)
// var err error
// for i := 0; i < 3; i++ {
// go func() {
// multiWriter := io.MultiWriter(to.conn, os.Stderr)
// errCh <- json.NewEncoder(multiWriter).Encode(e)
// }()
// if err = <-errCh; err == nil {
// break
// }
// }
// return err
}
// Flush any buffered events
func (to *TcpOutput) Flush() error { return nil }
// Discard the output
func (to *TcpOutput) Close() error {
if to.conn == nil {
return to.err
}
return to.Close()
}
// Name of output
func (to *TcpOutput) String() string { return "tcp-output" }
// output options
func RemoteAddress(address string) OutputOption {
return func(o *OutputOptions) {
if addr, err := net.LookupIP(address); err == nil {
o.RAddress = addr[0]
return
}
o.RAddress = net.ParseIP(address)
}
}
func RemotePort(port int) OutputOption {
return func(o *OutputOptions) {
o.RPort = port
}
}
func LocalAddress(address string) OutputOption {
return func(o *OutputOptions) {
o.LAddress = net.ParseIP(address)
}
}
func NewOutput(opts ...OutputOption) log.Output {
var options OutputOptions
var laddr *net.TCPAddr = nil
for _, o := range opts {
o(&options)
}
if len(options.RAddress) == 0 {
options.RAddress = DefaultRAddress.IP
}
if options.RPort == 0 {
options.RPort = DefaultRAddress.Port
}
if len(options.LAddress) != 0 {
laddr = &net.TCPAddr{options.LAddress, 0, ""}
}
tcpOutput := &TcpOutput{
options: options,
raddress: &net.TCPAddr{options.RAddress, options.RPort, ""},
laddress: laddr,
}
tcpOutput.connect()
return tcpOutput
}
<file_sep>package store
import (
"encoding/json"
"errors"
"fmt"
"github.com/micro/go-platform/log"
"github.com/yarbelk/todo"
"golang.org/x/net/context"
"github.com/boltdb/bolt"
)
type StoreService struct {
Store *bolt.DB
log log.Log
}
func New(filename string, logger log.Log) (ss *StoreService, err error) {
ss = &StoreService{}
ss.log = logger
db, err := bolt.Open(filename, 0600, nil)
if err != nil {
return
}
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("todoStore"))
return err
})
// output := file.NewOutput(log.OutputName("/dev/stdout"))
ss.Store = db
ss.log.Info("Starting storage service")
return
}
// MissingIDError is an error for when you don't have an Id, but need one
var MissingIDError = errors.New("ID field is missing")
// Save a task into the store. This requires there to be an Id field on the input task. So its
// an Upsert.
func (ss *StoreService) Save(ctx context.Context, in *todo.TaskDefinition, out *todo.TaskDefinition) error {
if in.Id == "" {
ss.log.Errorf("Save called without ID")
return MissingIDError
}
ss.log.Debugf("Saving ID %s", in.Id)
fmt.Println(ss, ss.Store)
return ss.Store.Update(func(tx *bolt.Tx) error {
*out = *in
data, err := json.Marshal(out)
if err != nil {
return err
}
b := tx.Bucket([]byte("todoStore"))
return b.Put([]byte(out.Id), data)
})
}
// Load a task from the store based on its ID.
func (ss *StoreService) Load(ctx context.Context, in *todo.TaskID, out *todo.TaskDefinition) error {
return ss.Store.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("todoStore"))
data := b.Get([]byte(in.Id))
return json.Unmarshal(data, out)
})
}
// All returns all of the tasks in order of their uuids. which basically means random order
// that persists over calls.
func (ss *StoreService) All(ctx context.Context, in *todo.AllTasksParams, out *todo.TaskList) error {
var tasks []todo.TaskDefinition
return ss.Store.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("todoStore"))
tasks = make([]todo.TaskDefinition, 0, b.Stats().KeyN)
return b.ForEach(func(_, taskData []byte) error {
var task *todo.TaskDefinition = &todo.TaskDefinition{}
if err := json.Unmarshal(taskData, task); err != nil {
ss.log.Errorf("Error unmarshaling for all tasks: \n%s\n\n%#v", err.Error(), b.Stats())
return err
}
tasks = append(tasks, *task)
return nil
})
})
}
<file_sep>package main
import (
"fmt"
"github.com/micro/go-platform/log"
tcpOutput "github.com/yarbelk/todo/log"
"github.com/yarbelk/todo/store"
)
// create a new command object to use in the service
func main() {
service := store.NewService()
service.Init()
logOutput := tcpOutput.NewOutput(
tcpOutput.RemoteAddress("logstash"),
tcpOutput.RemotePort(5001),
)
logger := log.NewLog(
log.WithOutput(logOutput),
log.WithLevel(log.InfoLevel),
)
if err := logger.Init(); err != nil {
fmt.Printf("Panicing due to init error: ", err.Error())
panic(err.Error())
}
fmt.Printf("created a logger", logger)
logger.Infof("Created a Logger")
ss, err := store.New(store.StorageFile, logger)
// might faile to get the bucket, explode here if that happens
if err != nil {
panic(err.Error())
}
store.RegisterStorerHandler(service.Server(), ss)
service.Run()
}
<file_sep>package query
import (
"github.com/yarbelk/todo"
"github.com/yarbelk/todo/store"
"golang.org/x/net/context"
)
type Service struct {
Store store.StorerClient
}
func (s *Service) GetTask(ctx context.Context, in *TaskQuery, out *todo.TaskDefinition) error {
task, err := s.Store.Load(ctx, &todo.TaskID{in.Id})
*out = *task
return err
}
func (s *Service) AllTasks(ctx context.Context, in *AllTasksParams, out *todo.TaskList) error {
tasks, err := s.Store.All(ctx, &todo.AllTasksParams{})
*out = *tasks
return err
}
func New() *Service {
return &Service{
Store: store.NewClient(),
}
}
<file_sep>FROM yarbelk/todo-base
ENV PATH $GOPATH/src/github.com/yarbelk/todo:$PATH
COPY run-query.sh .
CMD /bin/sh run-query.sh
<file_sep>package query
import "github.com/micro/go-micro"
var ServiceName string = "todo.query"
func NewService() micro.Service {
var service micro.Service
service = micro.NewService(
micro.Name(ServiceName),
)
return service
}
func NewClient() QueryerClient {
opts := []micro.Option{
micro.Name(ServiceName + ".client"),
}
service := micro.NewService(opts...)
return NewQueryerClient(ServiceName, service.Client())
}
<file_sep>package command
import (
"golang.org/x/net/context"
"github.com/micro/go-platform/log"
uuid "github.com/satori/go.uuid"
"github.com/yarbelk/todo"
"github.com/yarbelk/todo/store"
)
type Service struct {
Store store.StorerClient
logger log.Logger
}
// NewTask will assign an ID to a task definition, and store it into the storage backend
func (s *Service) NewTask(ctx context.Context, create *TaskCreate, created *TaskCreated) error {
uuid := uuid.NewV4().String()
created.Id = uuid
created.Description = create.Description
taskDef := &todo.TaskDefinition{
Id: created.Id,
Description: created.Description,
Completed: false,
}
out, err := s.Store.Save(ctx, taskDef)
if err != nil {
return err
}
created.Id = out.Id
created.Description = out.Description
return nil
}
func New() *Service {
return &Service{
Store: store.NewClient(),
}
}
<file_sep>FROM yarbelk/todo-base
ENV PATH $GOPATH/src/github.com/yarbelk/todo:$PATH
COPY run-commander.sh .
CMD /bin/sh run-commander.sh
<file_sep>GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
all: clean store-srv command-srv query-srv
.PHONY: all
store-srv: store/cli/store-srv/main.go
go build -ldflags "-X main.version=$(GIT_VERSION)" -o $@ $<
command-srv: command/cli/command-srv/main.go
go build -ldflags "-X main.version=$(GIT_VERSION)" -o $@ $<
query-srv: query/cli/query-srv/main.go
go build -ldflags "-X main.version=$(GIT_VERSION)" -o $@ $<
.PHONY: clean
clean:
rm command-srv store-srv query-srv || true
<file_sep>FROM yarbelk/todo-base
ENV PATH $GOPATH/src/github.com/yarbelk/todo:$PATH
COPY run-store.sh .
CMD /bin/sh run-store.sh
<file_sep>package main
import (
"github.com/micro/cli"
"github.com/micro/go-micro"
"github.com/yarbelk/todo/query"
)
func main() {
service := query.NewService()
queryer := query.New()
query.RegisterQueryerHandler(service.Server(), queryer)
service.Init(
micro.Name(query.ServiceName),
micro.Action(func(ctx *cli.Context) {
service.Run()
}),
)
}
<file_sep>#!/bin/sh
echo "sleeping for 1 seconds"
sleep 1
store-srv --registry_address=consul --broker_address=0.0.0.0:9000 --server_address=0.0.0.0:9001
<file_sep>package store
import (
"github.com/micro/cli"
"github.com/micro/go-micro"
)
var ServiceName string = "todo.store"
var StorageFile string
var LogstashAddress string
var LogstashPort int
func NewService() micro.Service {
var service micro.Service
service = micro.NewService(
micro.Name(ServiceName),
micro.Flags(cli.StringFlag{
Name: "db-file",
EnvVar: "TODO_DB_FILE",
Value: "/tmp/todo.db",
Usage: "the file to use for the boltdb backed storage",
Destination: &StorageFile,
}),
micro.Flags(cli.StringFlag{
Name: "logstash-address",
EnvVar: "TODO_LOGSTASH_ADDRESS",
Value: "logstash",
Usage: "the IP or hostname of the logstash server",
Destination: &LogstashAddress,
}),
micro.Flags(cli.IntFlag{
Name: "logstash-port",
EnvVar: "TODO_LOGSTASH_PORT",
Value: 5001,
Usage: "the logstash port setup to parse json",
Destination: &LogstashPort,
}),
)
return service
}
func NewClient() StorerClient {
opts := []micro.Option{
micro.Name(ServiceName + ".client"),
}
service := micro.NewService(opts...)
return NewStorerClient(ServiceName, service.Client())
}
<file_sep># Todo
An app to play with go-micro, docker-compose and ELK. This is a spike, so no tests
or anything.
<file_sep>package main
import (
"github.com/micro/cli"
"github.com/micro/go-micro"
"github.com/yarbelk/todo/command"
)
func main() {
service := command.NewService()
commander := command.New()
command.RegisterCommanderHandler(service.Server(), commander)
service.Init(
micro.Name(command.ServiceName),
micro.Action(func(ctx *cli.Context) {
service.Run()
}),
)
}
|
bd612eb53410d9638a4211a7f23c653e48f7d60d
|
[
"Markdown",
"Makefile",
"Go",
"Dockerfile",
"Shell"
] | 18
|
Dockerfile
|
yarbelk/todo
|
c39ed866d136b59aa773ad20cfbb08a3f0074859
|
009bbbd8a2496dbeae728b118895c40a5c221b17
|
refs/heads/master
|
<file_sep>import styled from 'styled-components';
import { Link } from 'react-router-dom';
export const Container = styled.div`
height: 100%;
max-width: 700px;
background: #fff;
border-radius: 4px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
padding: 30px;
margin: 80px auto;
form {
input {
margin: 5px;
padding: 10px 30px 10px 30px;
width: 600px;
border-radius: 10px;
border: 1px solid #eee;
font-size: 16px;
}
span {
font-weight: bold;
color: #fb6f91;
align-self: flex-start;
margin: 0 0 10px;
}
button {
width: 600px;
height: 40px;
margin-top: 15px;
margin-bottom: 25px;
border-radius: 10px;
border: 0;
margin-left: 20px;
background: #1a94a1;
color: #eee;
}
}
`;
export const AContainer = styled.div`
align-items: center;
display: flex;
flex-direction: column;
`;
export const BContainer = styled.div`
align-items: center;
display: flex;
flex-direction: row;
`;
export const CContainer = styled.div`
align-items: center;
display: flex;
`;
export const BackLink = styled(Link)`
font-size: 16px;
color: #19cdcf;
`;
<file_sep>import styled from 'styled-components';
import { Link } from 'react-router-dom';
export const Container = styled.div`
height: 100%;
max-width: 700px;
background: #fff;
border-radius: 4px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
padding: 30px;
margin: 80px auto;
`;
export const AContainer = styled.div``;
export const Header = styled.div`
display: flex;
margin-bottom: 15px;
h1 {
font-size: 20px;
display: flex;
flex-direction: row;
align-items: center;
svg {
margin-right: 10px;
}
}
`;
export const LinkAdd = styled(Link)`
margin-left: 40%;
align-items: center;
color: #19cdcf;
`;
export const List = styled.ul`
list-style: none;
display: flex;
flex-direction: column;
align-content: center;
text-align: center;
li {
margin-bottom: 10px;
}
a {
margin: 0 0 0px 10px;
}
`;
<file_sep>export function SignUpRequest(
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation
) {
return {
type: '@user/SIGN_UP_REQUEST',
payload: { name, cpf, farm_name, city, state, farm_area, plantation },
};
}
export function updateRequest(farm) {
return {
type: '@user/UPDATE_REQUEST',
payload: { farm },
};
}
export function updateSuccess(farm) {
return {
type: '@user/UPDATE_SUCCESS',
payload: { farm },
};
}
export function updateFailure() {
return {
type: '@user/UPDATE_FAILURE',
};
}
<file_sep>import { all, takeLatest, call, put } from '@redux-saga/core/effects';
import { toast } from 'react-toastify';
import api from '../../../services/api';
import history from '../../../services/history';
import { updateSuccess, updateFailure } from './actions';
export function* signUp({ payload }) {
try {
const {
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation,
} = payload;
yield call(api.post, 'users', {
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation,
});
console.log(payload);
history.push('/');
} catch (err) {
console.log(payload);
toast.error('Parece que algo deu errado, poderia verificar os dados?');
}
}
export function* updateFarm({ payload }) {
try {
const {
id,
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation,
} = payload;
const farm = Object.assign({
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation,
});
const response = yield call(api.put, `users?id:${id}`, farm);
toast.success('Atualizado com sucesso!');
yield put(updateSuccess(response.data));
} catch (err) {
toast.error('Parece que houve um erro...');
yield put(updateFailure());
}
}
export default all([
takeLatest('@user/SIGN_UP_REQUEST', signUp),
takeLatest('@user/UPDATE_REQUEST', updateFarm),
]);
<file_sep>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Main from '../pages/Main';
import Info from '../pages/Info';
import Add from '../pages/Add';
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={Main} />
<Route path="/register" component={Add} />
<Route path="/information/:id" component={Info} />
</Switch>
);
}
<file_sep>import React, { Component } from 'react';
import { FaCog } from 'react-icons/fa';
import { Link } from 'react-router-dom';
import api from '../../services/api';
import { Container, Header, AContainer, LinkAdd, List } from './styles';
export default class Main extends Component {
state = {
farms: [],
};
async componentDidMount() {
const response = await api.get('/farms');
console.log(response.data);
if (response.data) {
this.setState({ farms: response.data });
}
}
render() {
const { farms } = this.state;
return (
<Container>
<Header>
<h1>
<FaCog />
Titulo da aplicação
</h1>
<LinkAdd to="/register">Adicionar nova fazenda</LinkAdd>
</Header>
<AContainer>
<List>
{farms.map(farm => (
<li key={farm.id}>
<p>
Nome da Fazenda: <strong>{farm.farm_name}</strong>
</p>
<p>
Nome do Dono: <strong>{farm.name}</strong>
</p>
<span>
Area total: <strong>{farm.farm_area}</strong>
</span>
<br />
<Link to={`/information/${encodeURIComponent(farm.id)}`}>
Mais informações!
</Link>
<hr />
</li>
))}
</List>
</AContainer>
</Container>
);
}
}
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { useDispatch } from 'react-redux';
import { Form, Input } from '@rocketseat/unform';
import { updateRequest } from '../../store/modules/user/actions';
import api from '../../services/api';
import { Container, BackLink, DeleteButton } from './styles';
export default class Info extends Component {
static propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
farm: PropTypes.string,
}),
}).isRequired,
};
state = {
farm: {},
};
async componentDidMount() {
const { match } = this.props;
const farmId = decodeURIComponent(match.params.farm);
const response = await api.get(`/users/${farmId}`);
console.log(response.data);
this.setState({
farm: response.data,
});
}
render() {
const { farm } = this.state;
// const dispatch = useDispatch();
// function handleSubmit(data) {
// dispatch(updateRequest(data));
// }
return (
<Container>
<Form initialData={farm}>
<Input
name="name"
placeholder="PARADO!!! Se indetifique-se! (coloque seu nome aqui :))"
/>
<Input name="cpf" placeholder="CPF" maxLength="11" />
<Input name="farm_name" placeholder="Nome da sua fazenda" />
<Input name="city" placeholder="Cidade" />
<Input
name="farm_area"
placeholder="Tamanho da sua fazenda, em hectares"
type="number"
/>
<Input name="state" placeholder="Digite seu estado" />
<Input name="plantation" placeholder="Digite o que planta" />
<button type="submit">Alterar dados</button>
</Form>
<DeleteButton type="button">Excluir</DeleteButton>
<hr />
<BackLink to="/">Quero voltar</BackLink>
</Container>
);
}
}
<file_sep>import React from 'react';
import { useDispatch } from 'react-redux';
import { Form, Input } from '@rocketseat/unform';
import * as Yup from 'yup';
import { Container, AContainer, BackLink } from './styles';
import { SignUpRequest } from '../../store/modules/user/actions';
const schema = Yup.object().shape({
name: Yup.string().required('O nome é obrigatório'),
cpf: Yup.string()
.required('O CPF é obrigatório')
.min(11, 'Parece que o CPF não é válido'),
farm_name: Yup.string().required('O nome da fazenda é obrigatório'),
city: Yup.string().required('A cidade é obrigatório'),
farm_area: Yup.string().required('Preciso que coloque a area da sua fazenda'),
state: Yup.string()
.min(2, 'Digite pelo menos as siglas')
.required('Esse tambem é importante'),
plantation: Yup.string()
.min(3, 'Digite algo valido')
.required('importante tambem'),
});
export default function Add() {
const dispatch = useDispatch();
function handleSubmit({
name,
cpf,
farm_name,
city,
state,
farm_area,
plantation,
}) {
dispatch(
SignUpRequest(name, cpf, farm_name, city, state, farm_area, plantation)
);
}
return (
<Container>
<Form schema={schema} onSubmit={handleSubmit}>
<AContainer>
<Input
name="name"
placeholder="PARADO!!! Se indetifique-se! (coloque seu nome aqui :))"
/>
<Input name="cpf" placeholder="CPF" maxLength="11" />
<Input name="farm_name" placeholder="Nome da sua fazenda" />
<Input name="city" placeholder="Cidade" />
<Input
name="farm_area"
placeholder="Tamanho da sua fazenda, em hectares"
type="number"
/>
<Input name="state" placeholder="Digite seu estado" />
<Input name="plantation" placeholder="Digite o que planta" />
</AContainer>
<button type="submit">Cadastrar!</button>
<BackLink to="/">Quero voltar</BackLink>
</Form>
</Container>
);
}
|
2ba4e963ba7b6a7304281f9f7df1548479ef58f6
|
[
"JavaScript"
] | 8
|
JavaScript
|
HeversonSilva/BrainAgFront
|
b5d11d23bb8f7848f69b191413fa26ace53bd73c
|
929fb6841b0bc02f5375d0f14fe2f5d292c096ce
|
refs/heads/master
|
<repo_name>edwardvon/xadmin-django3<file_sep>/tests/xtests/site/tests.py
from __future__ import absolute_import
from django.http import HttpResponse
from base import BaseTest
from xadmin.sites import AdminSite
from xadmin.views import BaseAdminView, BaseAdminPlugin, ModelAdminView, filter_hook
from .models import ModelA
class ModelAAdmin(object):
pass
class TestAdminView(BaseAdminView):
site_title = "TEST TITLE"
@filter_hook
def get_title(self):
return self.site_title
def get(self, request):
return HttpResponse(self.site_title)
class TestOption(object):
site_title = "TEST PROJECT"
class TestPlugin(BaseAdminPlugin):
def get_title(self, title):
return "%s PLUGIN" % title
class TestModelAdminView(ModelAdminView):
def get(self, request, obj_id):
return HttpResponse(str(obj_id))
class AdminSiteTest(BaseTest):
def get_site(self):
return AdminSite('test', 'test_app')
def test_register_model(self):
site = self.get_site()
site.register(ModelA, ModelAAdmin)
self.assertIn(ModelA, site._registry.keys())
def test_unregister_model(self):
site = self.get_site()
site.register(ModelA, ModelAAdmin)
site.unregister(ModelA)
self.assertNotIn(ModelA, site._registry.keys())
def test_viewoption(self):
site = self.get_site()
site.register_view(r"^test/$", TestAdminView, 'test')
site.register(TestAdminView, TestOption)
c = site.get_view_class(TestAdminView)
self.assertEqual(c.site_title, "TEST PROJECT")
def test_plugin(self):
site = self.get_site()
site.register_view(r"^test/$", TestAdminView, 'test')
site.register_plugin(TestPlugin, TestAdminView)
c = site.get_view_class(TestAdminView)
self.assertIn(TestPlugin, c.plugin_classes)
cv = c(self._mocked_request('test/'))
self.assertEqual(cv.get_title(), "TEST TITLE PLUGIN")
def test_get_urls(self):
site = self.get_site()
site.register(ModelA, ModelAAdmin)
site.register_view(r"^test/$", TestAdminView, 'test')
site.register_modelview(
r'^(.+)/test/$', TestModelAdminView, name='%s_%s_test')
urls, app_name, namespace = site.urls
self.assertEqual(app_name, 'test_app')
self.assertEqual(namespace, 'test')
<file_sep>/requirements.txt
django==3.0.3
django-crispy-forms==1.8.1
django-import-export==2.0.2
django-reversion==3.0.7
django-formtools==2.2.0
future==0.18.2
httplib2==0.9.2
six==1.14.0
<file_sep>/tests/xtests/view_base/apps.py
#!/usr/bin/env python
#coding:utf-8
import sys
from django.utils import six
if six.PY2 and sys.getdefaultencoding()=='ascii':
import imp
imp.reload(sys)
sys.setdefaultencoding('utf-8')
from django.apps import AppConfig
class ViewBaseApp(AppConfig):
name = "view_base"
<file_sep>/xadmin/plugins/details.py
from django.utils.translation import ugettext as _
from django.urls import reverse, NoReverseMatch
from django.db import models
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView
class DetailsPlugin(BaseAdminPlugin):
show_detail_fields = []
show_all_rel_details = True
def result_item(self, item, obj, field_name, row):
if (self.show_all_rel_details or (field_name in self.show_detail_fields)):
rel_obj = None
if hasattr(item.field, 'rel') and isinstance(item.field.rel, models.ManyToOneRel):
rel_obj = getattr(obj, field_name)
elif field_name in self.show_detail_fields:
rel_obj = obj
if rel_obj:
if rel_obj.__class__ in site._registry:
try:
model_admin = site._registry[rel_obj.__class__]
has_view_perm = model_admin(self.admin_view.request).has_view_permission(rel_obj)
has_change_perm = model_admin(self.admin_view.request).has_change_permission(rel_obj)
except:
has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')
else:
has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')
if rel_obj and has_view_perm:
opts = rel_obj._meta
try:
item_res_uri = reverse(
'%s:%s_%s_detail' % (self.admin_site.app_name,
opts.app_label, opts.model_name),
args=(getattr(rel_obj, opts.pk.attname),))
if item_res_uri:
if has_change_perm:
edit_url = reverse(
'%s:%s_%s_change' % (self.admin_site.app_name, opts.app_label, opts.model_name),
args=(getattr(rel_obj, opts.pk.attname),))
else:
edit_url = ''
item.btns.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s"><i class="fa fa-info-circle"></i></a>'
% (item_res_uri, edit_url, _(u'Details of %s') % str(rel_obj)))
except NoReverseMatch:
pass
return item
# Media
def get_media(self, media):
if self.show_all_rel_details or self.show_detail_fields:
media = media + self.vendor('xadmin.plugin.details.js', 'xadmin.form.css')
return media
site.register_plugin(DetailsPlugin, ListAdminView)
<file_sep>/tests/runtests.py
#!/usr/bin/env python
from __future__ import print_function
import os
import shutil
import sys
import tempfile
import django
from django.apps import AppConfig,apps
from django.utils.encoding import smart_text
TEST_ROOT = os.path.realpath(os.path.dirname(__file__))
RUNTESTS_DIR = os.path.join(TEST_ROOT, 'xtests')
sys.path.insert(0, os.path.join(TEST_ROOT, os.pardir))
sys.path.insert(0, RUNTESTS_DIR)
TEST_TEMPLATE_DIR = 'templates'
TEMP_DIR = tempfile.mkdtemp(prefix='django_')
os.environ['DJANGO_TEST_TEMP_DIR'] = TEMP_DIR
ALWAYS_INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'xadmin',
'crispy_forms',
]
def get_test_modules():
modules = []
for f in os.listdir(RUNTESTS_DIR):
if (
f.startswith('__init__')
or f.startswith('__pycache__')
or f.startswith('.')
or f.startswith('sql')
or not os.path.isdir(os.path.join(RUNTESTS_DIR, f))
):
continue
modules.append(f)
return modules
def setup(verbosity, test_labels):
from django.conf import settings
state = {
'INSTALLED_APPS': settings.INSTALLED_APPS,
'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
'USE_I18N': settings.USE_I18N,
'LOGIN_URL': settings.LOGIN_URL,
'LANGUAGE_CODE': settings.LANGUAGE_CODE,
'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
'STATIC_URL': settings.STATIC_URL,
'STATIC_ROOT': settings.STATIC_ROOT,
}
# Redirect some settings for the duration of these tests.
settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
settings.ROOT_URLCONF = 'urls'
settings.STATIC_URL = '/static/'
settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
settings.USE_I18N = True
settings.LANGUAGE_CODE = 'en'
settings.MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.CommonMiddleware',
)
settings.SITE_ID = 1
# For testing comment-utils, we require the MANAGERS attribute
# to be set, so that a test email is sent out which we catch
# in our tests.
settings.MANAGERS = ("<EMAIL>",)
# Load all the ALWAYS_INSTALLED_APPS.
# (This import statement is intentionally delayed until after we
# access settings because of the USE_I18N dependency.)
# Load all the test model apps.
test_labels_set = set([label.split('.')[0] for label in test_labels])
test_modules = get_test_modules()
for module_name in test_modules:
module_label = module_name
# if the module was named on the command line, or
# no modules were named (i.e., run all), import
# this module and add it to the list to test.
if not test_labels or module_name in test_labels_set:
if verbosity >= 2:
print("Importing application %s" % module_name)
if module_label not in settings.INSTALLED_APPS:
settings.INSTALLED_APPS.append(module_label)
django.setup()
[a.models_module for a in apps.get_app_configs()]
return state
def teardown(state):
from django.conf import settings
# Removing the temporary TEMP_DIR. Ensure we pass in unicode
# so that it will successfully remove temp trees containing
# non-ASCII filenames on Windows. (We're assuming the temp dir
# name itself does not contain non-ASCII characters.)
shutil.rmtree(smart_text(TEMP_DIR))
# Restore the old settings.
for key, value in state.items():
setattr(settings, key, value)
def django_tests(verbosity, interactive, failfast, test_labels):
from django.conf import settings
state = setup(verbosity, test_labels)
extra_tests = []
# Run the test suite, including the extra validation tests.
from django.test.utils import get_runner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
failfast=failfast)
failures = test_runner.run_tests(test_labels or get_test_modules(), extra_tests=extra_tests)
teardown(state)
return failures
if __name__ == "__main__":
from optparse import OptionParser
usage = "%prog [options] [module module module ...]"
parser = OptionParser(usage=usage)
parser.add_option(
'-v','--verbosity', action='store', dest='verbosity', default='1',
type='choice', choices=['0', '1', '2', '3'],
help='Verbosity level; 0=minimal output, 1=normal output, 2=all '
'output')
parser.add_option(
'--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.')
parser.add_option(
'--failfast', action='store_true', dest='failfast', default=False,
help='Tells Django to stop running the test suite after first failed '
'test.')
parser.add_option(
'--settings',
help='Python path to settings module, e.g. "myproject.settings". If '
'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment '
'variable will be used.')
parser.add_option(
'--liveserver', action='store', dest='liveserver', default=None,
help='Overrides the default address where the live server (used with '
'LiveServerTestCase) is expected to run from. The default value '
'is localhost:8081.'),
options, args = parser.parse_args()
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
elif "DJANGO_SETTINGS_MODULE" not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
else:
options.settings = os.environ['DJANGO_SETTINGS_MODULE']
if options.liveserver is not None:
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options.liveserver
failures = django_tests(int(options.verbosity), options.interactive,
options.failfast, args)
if failures:
sys.exit(bool(failures))
<file_sep>/tests/xtests/view_base/adminx.py
from __future__ import absolute_import
from xadmin.sites import AdminSite
from xadmin.views import BaseAdminView, CommAdminView, ListAdminView
from .models import ModelA, ModelB
site = AdminSite('views_base')
class ModelAAdmin(object):
test_model_attr = 'test_model'
model_icon = 'flag'
class TestBaseView(BaseAdminView):
pass
class TestCommView(CommAdminView):
global_models_icon = {ModelB: 'test'}
class TestAView(BaseAdminView):
pass
class OptionA(object):
option_attr = 'option_test'
site.register_modelview(r'^list$', ListAdminView, name='%s_%s_list')
site.register_view(r"^test/base$", TestBaseView, 'test')
site.register_view(r"^test/comm$", TestCommView, 'test_comm')
site.register_view(r"^test/a$", TestAView, 'test_a')
site.register(ModelA, ModelAAdmin)
site.register(ModelB)
<file_sep>/xadmin/views/detail.py
from __future__ import absolute_import
import copy
from crispy_forms.utils import TEMPLATE_PACK
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db import models
from django.forms.models import modelform_factory
from django.http import Http404
from django.template import loader
from django.template.response import TemplateResponse
import six
from django.utils.encoding import force_text, smart_text
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.html import conditional_escape
from xadmin.layout import FormHelper, Layout, Fieldset, Container, Column, Field, Col, TabHolder
from xadmin.util import unquote, lookup_field, display_for_field, boolean_icon, label_for_field
from .base import ModelAdminView, filter_hook, csrf_protect_m
# Text to display within change-list table cells if the value is blank.
EMPTY_CHANGELIST_VALUE = _('Null')
class ShowField(Field):
template = "xadmin/layout/field_value.html"
def __init__(self, callback, *args, **kwargs):
super(ShowField, self).__init__(*args, **kwargs)
self.results = [(field, callback(field)) for field in self.fields]
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, renderer=None, **kwargs):
super(ShowField, self).render(form, form_style, context, template_pack, extra_context, **kwargs)
if extra_context is None:
extra_context = {}
if hasattr(self, 'wrapper_class'):
extra_context['wrapper_class'] = self.wrapper_class
if self.attrs:
if 'detail-class' in self.attrs:
extra_context['input_class'] = self.attrs['detail-class']
elif 'class' in self.attrs:
extra_context['input_class'] = self.attrs['class']
html = ''
for field, result in self.results:
extra_context['result'] = result
if field in form.fields:
if form.fields[field].widget != forms.HiddenInput:
extra_context['field'] = form[field]
html += loader.render_to_string(self.template, extra_context)
else:
extra_context['field'] = field
html += loader.render_to_string(self.template, extra_context)
return html
class ResultField(object):
def __init__(self, obj, field_name, admin_view=None):
self.text = ' '
self.wraps = []
self.allow_tags = False
self.obj = obj
self.admin_view = admin_view
self.field_name = field_name
self.field = None
self.attr = None
self.label = None
self.value = None
self.init()
def init(self):
self.label = label_for_field(self.field_name, self.obj.__class__,
model_admin=self.admin_view,
return_attr=False
)
try:
f, attr, value = lookup_field(
self.field_name, self.obj, self.admin_view)
except (AttributeError, ObjectDoesNotExist):
self.text
else:
if f is None:
self.allow_tags = getattr(attr, 'allow_tags', False)
boolean = getattr(attr, 'boolean', False)
if boolean:
self.allow_tags = True
self.text = boolean_icon(value)
else:
self.text = smart_text(value)
else:
if isinstance(f.remote_field, models.ManyToOneRel):
self.text = getattr(self.obj, f.name)
else:
self.text = display_for_field(value, f)
self.field = f
self.attr = attr
self.value = value
@property
def val(self):
text = mark_safe(
self.text) if self.allow_tags else conditional_escape(self.text)
if force_text(text) == '' or text == 'None' or text == EMPTY_CHANGELIST_VALUE:
text = mark_safe(
'<span class="text-muted">%s</span>' % EMPTY_CHANGELIST_VALUE)
for wrap in self.wraps:
text = mark_safe(wrap % text)
return text
def replace_field_to_value(layout, cb):
cls_str = str if six.PY3 else basestring
for i, lo in enumerate(layout.fields):
if isinstance(lo, Field) or issubclass(lo.__class__, Field):
layout.fields[i] = ShowField(
cb, *lo.fields, attrs=lo.attrs, wrapper_class=lo.wrapper_class)
elif isinstance(lo, cls_str):
layout.fields[i] = ShowField(cb, lo)
elif hasattr(lo, 'get_field_names'):
replace_field_to_value(lo, cb)
class DetailAdminView(ModelAdminView):
form = forms.ModelForm
detail_layout = None
detail_show_all = True
detail_template = None
form_layout = None
def init_request(self, object_id, *args, **kwargs):
self.obj = self.get_object(unquote(object_id))
if not self.has_view_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(
_('%(name)s object with primary key %(key)r does not exist.') %
{'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
self.org_obj = self.obj
@filter_hook
def get_form_layout(self):
layout = copy.deepcopy(self.detail_layout or self.form_layout)
if layout is None:
layout = Layout(Container(Col('full',
Fieldset(
"", *self.form_obj.fields.keys(),
css_class="unsort no_title"), horizontal=True, span=12)
))
elif type(layout) in (list, tuple) and len(layout) > 0:
if isinstance(layout[0], Column):
fs = layout
elif isinstance(layout[0], (Fieldset, TabHolder)):
fs = (Col('full', *layout, horizontal=True, span=12),)
else:
fs = (
Col('full', Fieldset("", *layout, css_class="unsort no_title"), horizontal=True, span=12),)
layout = Layout(Container(*fs))
if self.detail_show_all:
rendered_fields = [i[1] for i in layout.get_field_names()]
container = layout[0].fields
other_fieldset = Fieldset(_(u'Other Fields'), *[
f for f in self.form_obj.fields.keys() if f not in rendered_fields])
if len(other_fieldset.fields):
if len(container) and isinstance(container[0], Column):
container[0].fields.append(other_fieldset)
else:
container.append(other_fieldset)
return layout
@filter_hook
def get_model_form(self, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": self.fields and list(self.fields) or '__all__',
"exclude": exclude,
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
@filter_hook
def get_form_helper(self):
helper = FormHelper()
helper.form_tag = False
helper.include_media = False
layout = self.get_form_layout()
replace_field_to_value(layout, self.get_field_result)
helper.add_layout(layout)
cls_str = str if six.PY3 else basestring
helper.filter(cls_str, max_level=20).wrap(ShowField, admin_view=self)
return helper
@csrf_protect_m
@filter_hook
def get(self, request, *args, **kwargs):
form = self.get_model_form()
self.form_obj = form(instance=self.obj)
helper = self.get_form_helper()
if helper:
self.form_obj.helper = helper
return self.get_response()
@filter_hook
def get_context(self):
new_context = {
'title': _('%s Detail') % force_text(self.opts.verbose_name),
'form': self.form_obj,
'object': self.obj,
'has_change_permission': self.has_change_permission(self.obj),
'has_delete_permission': self.has_delete_permission(self.obj),
'content_type_id': ContentType.objects.get_for_model(self.model).id,
}
context = super(DetailAdminView, self).get_context()
context.update(new_context)
return context
@filter_hook
def get_breadcrumb(self):
bcs = super(DetailAdminView, self).get_breadcrumb()
item = {'title': force_text(self.obj)}
if self.has_view_permission():
item['url'] = self.model_admin_url('detail', self.obj.pk)
bcs.append(item)
return bcs
@filter_hook
def get_media(self):
return super(DetailAdminView, self).get_media() + self.form_obj.media + \
self.vendor('xadmin.page.form.js', 'xadmin.form.css')
@filter_hook
def get_field_result(self, field_name):
return ResultField(self.obj, field_name, self)
@filter_hook
def get_response(self, *args, **kwargs):
context = self.get_context()
context.update(kwargs or {})
self.request.current_app = self.admin_site.name
response = TemplateResponse(self.request, self.detail_template or
self.get_template_list('views/model_detail.html'),
context)
return response
class DetailAdminUtil(DetailAdminView):
def init_request(self, obj):
self.obj = obj
self.org_obj = obj
<file_sep>/demo_app/app/migrations/0002_idc_groups.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-20 14:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0007_alter_validators_add_error_messages'),
('app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='idc',
name='groups',
field=models.ManyToManyField(to='auth.Group'),
),
]
<file_sep>/demo_app/app/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-20 15:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccessRecord',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField()),
('user_count', models.IntegerField()),
('view_count', models.IntegerField()),
],
options={
'verbose_name': 'Access Record',
'verbose_name_plural': 'Access Record',
},
),
migrations.CreateModel(
name='Host',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64)),
('nagios_name', models.CharField(blank=True, max_length=64, null=True, verbose_name='Nagios Host ID')),
('ip', models.GenericIPAddressField(blank=True, null=True)),
('internal_ip', models.GenericIPAddressField(blank=True, null=True)),
('user', models.CharField(max_length=64)),
('password', models.CharField(max_length=128)),
('ssh_port', models.IntegerField(blank=True, null=True)),
('status', models.SmallIntegerField(choices=[(0, 'Normal'), (1, 'Down'), (2, 'No Connect'), (3, 'Error')])),
('brand', models.CharField(choices=[('DELL', 'DELL'), ('HP', 'HP'), ('Other', 'Other')], max_length=64)),
('model', models.CharField(max_length=64)),
('cpu', models.CharField(max_length=64)),
('core_num', models.SmallIntegerField(choices=[(2, b'2 Cores'), (4, b'4 Cores'), (6, b'6 Cores'), (8, b'8 Cores'), (10, b'10 Cores'), (12, b'12 Cores'), (14, b'14 Cores'), (16, b'16 Cores'), (18, b'18 Cores'), (20, b'20 Cores'), (22, b'22 Cores'), (24, b'24 Cores'), (26, b'26 Cores'), (28, b'28 Cores')])),
('hard_disk', models.IntegerField()),
('memory', models.IntegerField()),
('system', models.CharField(choices=[('CentOS', 'CentOS'), ('FreeBSD', 'FreeBSD'), ('Ubuntu', 'Ubuntu')], max_length=32, verbose_name='System OS')),
('system_version', models.CharField(max_length=32)),
('system_arch', models.CharField(choices=[('x86_64', 'x86_64'), ('i386', 'i386')], max_length=32)),
('create_time', models.DateField()),
('guarantee_date', models.DateField()),
('service_type', models.CharField(choices=[(b'moniter', 'Moniter'), (b'lvs', 'LVS'), (b'db', 'Database'), (b'analysis', 'Analysis'), (b'admin', 'Admin'), (b'storge', 'Storge'), (b'web', 'WEB'), (b'email', 'Email'), (b'mix', 'Mix')], max_length=32)),
('description', models.TextField()),
],
options={
'verbose_name': 'Host',
'verbose_name_plural': 'Host',
},
),
migrations.CreateModel(
name='HostGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32)),
('description', models.TextField()),
('hosts', models.ManyToManyField(blank=True, related_name='groups', to='app.Host', verbose_name='Hosts')),
],
options={
'verbose_name': 'Host Group',
'verbose_name_plural': 'Host Group',
},
),
migrations.CreateModel(
name='IDC',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64)),
('description', models.TextField()),
('contact', models.CharField(max_length=32)),
('telphone', models.CharField(max_length=32)),
('address', models.CharField(max_length=128)),
('customer_id', models.CharField(max_length=128)),
('create_time', models.DateField(auto_now=True)),
],
options={
'verbose_name': 'IDC',
'verbose_name_plural': 'IDC',
},
),
migrations.CreateModel(
name='MaintainLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('maintain_type', models.CharField(max_length=32)),
('hard_type', models.CharField(max_length=16)),
('time', models.DateTimeField()),
('operator', models.CharField(max_length=16)),
('note', models.TextField()),
('host', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.Host')),
],
options={
'verbose_name': 'Maintain Log',
'verbose_name_plural': 'Maintain Log',
},
),
migrations.AddField(
model_name='host',
name='idc',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app.IDC'),
),
]
<file_sep>/demo_app/demo/urls.py
# -*- coding: utf-8 -*-
# from django.conf.urls import include, url
from django.urls import include, path
# Uncomment the next two lines to enable the admin:
import xadmin
xadmin.autodiscover()
# version模块自动注册需要版本控制的 Model
from xadmin.plugins import xversion
xversion.register_models()
from django.contrib import admin
urlpatterns = [
path(r'', xadmin.site.urls)
]
<file_sep>/tests/urls.py
from django.conf.urls import patterns, include
urlpatterns = patterns('',
(r'^view_base/', include('view_base.urls')),
)<file_sep>/demo_app/app/adminx.py
from __future__ import absolute_import
import xadmin
from xadmin import views
from .models import IDC, Host, MaintainLog, HostGroup, AccessRecord
from xadmin.layout import Main, TabHolder, Tab, Fieldset, Row, Col, AppendedText, Side
from xadmin.plugins.inline import Inline
from xadmin.plugins.batch import BatchChangeAction
@xadmin.sites.register(views.website.IndexView)
class MainDashboard(object):
widgets = [
[
{"type": "html", "title": "Test Widget",
"content": "<h3> Welcome to Xadmin! </h3><p>Join Online Group: <br/>QQ Qun : 282936295</p>"},
{"type": "chart", "model": "app.accessrecord", "chart": "user_count",
"params": {"_p_date__gte": "2013-01-08", "p": 1, "_p_date__lt": "2013-01-29"}},
{"type": "list", "model": "app.host", "params": {"o": "-guarantee_date"}},
],
[
{"type": "qbutton", "title": "Quick Start",
"btns": [{"model": Host}, {"model": IDC}, {"title": "Google", "url": "http://www.google.com"}]},
{"type": "addform", "model": MaintainLog},
]
]
@xadmin.sites.register(views.BaseAdminView)
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
@xadmin.sites.register(views.CommAdminView)
class GlobalSetting(object):
global_search_models = [Host, IDC]
global_models_icon = {
Host: "fa fa-laptop", IDC: "fa fa-cloud"
}
menu_style = 'default' # 'accordion'
class MaintainInline(object):
model = MaintainLog
extra = 1
style = "accordion"
@xadmin.sites.register(IDC)
class IDCAdmin(object):
list_display = ("name", "description", "create_time", "contact", "telphone", "address", "customer_id")
list_display_links = ("name",)
wizard_form_list = [
("First's Form", ("name", "description")),
("Second Form", ("contact", "telphone", "address")),
("Thread Form", ("customer_id",))
]
search_fields = ["name", "description", "contact", "telphone", "address"]
list_filter = [
"name"
]
list_quick_filter = [{"field": "name", "limit": 10}]
search_fields = ["name"]
relfield_style = "fk-select"
reversion_enable = True
actions = [BatchChangeAction, ]
batch_fields = ("contact", "description", "address", "customer_id")
@xadmin.sites.register(Host)
class HostAdmin(object):
def open_web(self, instance):
return """<a href="http://%s" target="_blank">Open</a>""" % instance.ip
open_web.short_description = "Acts"
open_web.allow_tags = True
open_web.is_column = True
list_display = (
"name", "idc", "guarantee_date", "service_type", "status", "open_web",
"description", "ip",
)
list_display_links = ("name",)
raw_id_fields = ("idc",)
style_fields = {"system": "radio-inline"}
search_fields = ["name", "ip", "description", "idc__name"]
list_filter = [
"idc", "guarantee_date", "status", "brand", "model", "cpu", "core_num",
"hard_disk", "memory", (
"service_type",
xadmin.filters.MultiSelectFieldListFilter,
),
]
list_quick_filter = ["service_type", {"field": "idc__name", "limit": 10}]
# list_quick_filter = ["idc_id"]
list_bookmarks = [{
"title": "Need Guarantee",
"query": {"status__exact": 2},
"order": ("-guarantee_date",),
"cols": ("brand", "guarantee_date", "service_type"),
}]
show_detail_fields = ("idc",)
list_editable = (
"name", "idc", "guarantee_date", "service_type", "description", "ip"
)
save_as = True
aggregate_fields = {"guarantee_date": "min"}
grid_layouts = ("table", "thumbnails")
form_layout = (
Main(
TabHolder(
Tab(
"Comm Fields",
Fieldset(
"Company data", "name", "idc",
description="some comm fields, required",
),
Inline(MaintainLog),
),
Tab(
"Extend Fields",
Fieldset(
"Contact details",
"service_type",
Row("brand", "model"),
Row("cpu", "core_num"),
Row(
AppendedText("hard_disk", "G"),
AppendedText("memory", "G")
),
"guarantee_date"
),
),
),
),
Side(
Fieldset("Status data", "status", "ssh_port", "ip"),
)
)
inlines = [MaintainInline]
reversion_enable = True
data_charts = {
"host_service_type_counts": {'title': u"Host service type count", "x-field": "service_type",
"y-field": ("service_type",),
"option": {
"series": {"bars": {"align": "center", "barWidth": 0.8, 'show': True}},
"xaxis": {"aggregate": "count", "mode": "categories"},
},
},
}
@xadmin.sites.register(HostGroup)
class HostGroupAdmin(object):
list_display = ("name", "description")
list_display_links = ("name",)
list_filter = ["hosts"]
search_fields = ["name"]
style_fields = {"hosts": "checkbox-inline"}
@xadmin.sites.register(MaintainLog)
class MaintainLogAdmin(object):
list_display = (
"host", "maintain_type", "hard_type", "time", "operator", "note")
list_display_links = ("host",)
list_filter = ["host", "maintain_type", "hard_type", "time", "operator"]
search_fields = ["note"]
form_layout = (
Col("col2",
Fieldset("Record data",
"time", "note",
css_class="unsort short_label no_title"
),
span=9, horizontal=True
),
Col("col1",
Fieldset("Comm data",
"host", "maintain_type"
),
Fieldset("Maintain details",
"hard_type", "operator"
),
span=3
)
)
reversion_enable = True
@xadmin.sites.register(AccessRecord)
class AccessRecordAdmin(object):
def avg_count(self, instance):
return int(instance.view_count / instance.user_count)
avg_count.short_description = "Avg Count"
avg_count.allow_tags = True
avg_count.is_column = True
list_display = ("date", "user_count", "view_count", "avg_count")
list_display_links = ("date",)
list_filter = ["date", "user_count", "view_count"]
actions = None
aggregate_fields = {"user_count": "sum", "view_count": "sum"}
refresh_times = (3, 5, 10)
data_charts = {
"user_count": {'title': u"User Report", "x-field": "date", "y-field": ("user_count", "view_count"),
"order": ('date',)},
"avg_count": {'title': u"Avg Report", "x-field": "date", "y-field": ('avg_count',), "order": ('date',)},
"per_month": {'title': u"Monthly Users", "x-field": "_chart_month", "y-field": ("user_count",),
"option": {
"series": {"bars": {"align": "center", "barWidth": 0.8, 'show': True}},
"xaxis": {"aggregate": "sum", "mode": "categories"},
},
},
}
def _chart_month(self, obj):
return obj.date.strftime("%B")
# xadmin.sites.site.register(HostGroup, HostGroupAdmin)
# xadmin.sites.site.register(MaintainLog, MaintainLogAdmin)
# xadmin.sites.site.register(IDC, IDCAdmin)
# xadmin.sites.site.register(AccessRecord, AccessRecordAdmin)
<file_sep>/tests/xtests/base.py
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import RequestFactory
class BaseTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
def _create_superuser(self, username):
return User.objects.create(username=username, is_superuser=True)
def _mocked_request(self, url, user='admin'):
request = self.factory.get(url)
request.user = isinstance(user, User) and user or self._create_superuser(user)
request.session = {}
return request<file_sep>/xadmin/layout.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from crispy_forms.utils import render_field, flatatt, TEMPLATE_PACK
from crispy_forms import layout
from crispy_forms import bootstrap
import math
class Fieldset(layout.Fieldset):
template = "xadmin/layout/fieldset.html"
def __init__(self, legend, *fields, **kwargs):
self.description = kwargs.pop('description', None)
self.collapsed = kwargs.pop('collapsed', None)
super(Fieldset, self).__init__(legend, *fields, **kwargs)
class Row(layout.Div):
def __init__(self, *fields, **kwargs):
css_class = 'form-inline form-group'
new_fields = [self.convert_field(f, len(fields)) for f in fields]
super(Row, self).__init__(css_class=css_class, *new_fields, **kwargs)
def convert_field(self, f, counts):
col_class = "col-sm-%d" % int(math.ceil(12 / counts))
if not (isinstance(f, Field) or issubclass(f.__class__, Field)):
f = layout.Field(f)
if f.wrapper_class:
f.wrapper_class += " %s" % col_class
else:
f.wrapper_class = col_class
return f
class Col(layout.Column):
def __init__(self, id, *fields, **kwargs):
css_class = ['column', 'form-column', id, 'col col-sm-%d' %
kwargs.get('span', 6)]
if kwargs.get('horizontal'):
css_class.append('form-horizontal')
super(Col, self).__init__(css_class=' '.join(css_class), *
fields, **kwargs)
class Main(layout.Column):
css_class = "column form-column main col col-sm-9 form-horizontal"
class Side(layout.Column):
css_class = "column form-column sidebar col col-sm-3"
class Container(layout.Div):
css_class = "form-container row clearfix"
# Override bootstrap3
class InputGroup(layout.Field):
template = "xadmin/layout/input_group.html"
def __init__(self, field, *args, **kwargs):
self.field = field
self.inputs = list(args)
if '@@' not in args:
self.inputs.append('@@')
self.input_size = None
css_class = kwargs.get('css_class', '')
if 'input-lg' in css_class:
self.input_size = 'input-lg'
if 'input-sm' in css_class:
self.input_size = 'input-sm'
super(InputGroup, self).__init__(field, **kwargs)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, renderer=None, **kwargs):
classes = form.fields[self.field].widget.attrs.get('class', '')
extra_context = {
'inputs': self.inputs,
'input_size': self.input_size,
'classes': classes.replace('form-control', '')
}
if hasattr(self, 'wrapper_class'):
extra_context['wrapper_class'] = self.wrapper_class
return render_field(
self.field, form, form_style, context, template=self.template,
attrs=self.attrs, template_pack=template_pack, extra_context=extra_context, **kwargs)
class PrependedText(InputGroup):
def __init__(self, field, text, **kwargs):
super(PrependedText, self).__init__(field, text, '@@', **kwargs)
class AppendedText(InputGroup):
def __init__(self, field, text, **kwargs):
super(AppendedText, self).__init__(field, '@@', text, **kwargs)
class PrependedAppendedText(InputGroup):
def __init__(self, field, prepended_text=None, appended_text=None, *args, **kwargs):
super(PrependedAppendedText, self).__init__(
field, prepended_text, '@@', appended_text, **kwargs)
<file_sep>/xadmin/views/website.py
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.cache import never_cache
from django.contrib.auth.views import LoginView as login, LogoutView as logout
from django.http import HttpResponse
from .base import BaseAdminView, filter_hook
from .dashboard import Dashboard
from xadmin.forms import AdminAuthenticationForm
from xadmin.models import UserSettings
from xadmin.layout import FormHelper
class IndexView(Dashboard):
title = _("Main Dashboard")
icon = "fa fa-dashboard"
def get_page_id(self):
return 'home'
class UserSettingView(BaseAdminView):
@never_cache
def post(self, request):
key = request.POST['key']
val = request.POST['value']
us, created = UserSettings.objects.get_or_create(
user=self.user, key=key)
us.value = val
us.save()
return HttpResponse('')
class LoginView(BaseAdminView):
title = _("Please Login")
login_form = None
login_template = None
@filter_hook
def update_params(self, defaults):
pass
@never_cache
def get(self, request, *args, **kwargs):
context = self.get_context()
helper = FormHelper()
helper.form_tag = False
helper.include_media = False
context.update({
'title': self.title,
'helper': helper,
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: request.get_full_path(),
})
defaults = {
'extra_context': context,
# 'current_app': self.admin_site.name,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'xadmin/views/login.html',
}
self.update_params(defaults)
return login.as_view(**defaults)(request)
@never_cache
def post(self, request, *args, **kwargs):
return self.get(request)
class LogoutView(BaseAdminView):
logout_template = None
need_site_permission = False
@filter_hook
def update_params(self, defaults):
pass
@never_cache
def get(self, request, *args, **kwargs):
context = self.get_context()
defaults = {
'extra_context': context,
# 'current_app': self.admin_site.name,
'template_name': self.logout_template or 'xadmin/views/logged_out.html',
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
self.update_params(defaults)
return logout.as_view(**defaults)(request)
@never_cache
def post(self, request, *args, **kwargs):
return self.get(request)
<file_sep>/tests/settings.py
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
MIDDLEWARE_CLASSES = ()
# Required for Django 1.4+
STATIC_URL = '/static/'
# Required for Django 1.5+
SECRET_KEY = 'abc123'
<file_sep>/tests/xtests/view_base/urls.py
from __future__ import absolute_import
from django.conf.urls import patterns, include
from .adminx import site
urlpatterns = patterns('',
(r'', include(site.urls)),
)<file_sep>/README.rst
Xadmin-django3
============================================
说明
-----------
基于官方xadmin-django2 2.0.1版本,修复已知bug,在Python3.7 + Django3.0.3环境下运行通过。
目前只修复了我碰到的问题,欢迎提issue以及讨论修改方法
requirements
-------------
* django==3.0.3
* django-crispy-forms==1.8.1
* django-import-export==2.0.2
* django-reversion==3.0.7
* django-formtools==2.2.0
* future==0.18.2
* httplib2==0.9.2
* six==1.14.0
使用
-------------
- 请暂时不要使用setup.py进行安装(待修正)
1.在django项目目录下建立extra_apps文件夹,将本仓库中xadmin文件夹拷贝到其中;
2.在django项目的settting.py 添加extra_apps目录
import sys
...
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
3.将'xadmin', 'crispy_forms', 'reversion', 'django.cong'添加到 INSTALLED_APPS:
INSTALLED_APPS = [
...
'xadmin',
'crispy_forms',
'reversion',
'django.conf',
...
]
官方文档
-------------
- English (coming soon)
- `Chinese`_
.. _Chinese: https://xadmin.readthedocs.org/en/latest/index.html
目前已修复bug
-------------
- 2020/02/25更新:AttributeError: module 'xadmin' has no attribute 'site'; 解决方法:https://github.com/edwardvon/xadmin-django3/issues/1
- ForeignKey未配置on_delete参数引起的错误
- 模块包名称变更引发的错误:
* django.core.urlresolvers => django.urls
* django.utils.six => six
* django.utils.encoding.python_2_unicode_compatible => future.utils.python_2_unicode_compatible
* ...
* 等(记不清了)
- "ManyToManyField" object has no attribute 'rel'错误
- Exception: Relate Lookup field must a related field 错误
- xadmin\views\website.py login和logout 函数及参数变更引发的错误
- 国际化问题报异常:ImportError: cannot import name 'javascript_catalog' from 'django.views.i18n'
注:请在project\setting.py 的 INSTALLED_APPS中补充添加 'django.conf'
- 异常 'DateTimeField' object has no attribute 'rel'
- ModuleNotFoundError: No module named 'django.contrib.formtools' fromtools版本太低
- ImportError: cannot import name 'QUERY_TERMS' from 'django.db.models.sql.query' 错误
- ImportError: cannot import name 'password_reset_confirm' from 'django.contrib.auth.views' 错误
- AttributeError: 'Settings' object has no attribute 'MIDDLEWARE_CLASSES'
- TypeError: forms.Field.__init__() takes 1 positional argument but 6 were given
- render() got an unexpected keyword argument 'renderer'
- 还有些想不起来了...
<file_sep>/tests/xtests/view_base/tests.py
from __future__ import absolute_import
from django.contrib.auth.models import User
from base import BaseTest
from xadmin.views import BaseAdminView, BaseAdminPlugin, ModelAdminView, ListAdminView
from .models import ModelA, ModelB
from .adminx import site, ModelAAdmin, TestBaseView, TestCommView, TestAView, OptionA
class BaseAdminTest(BaseTest):
def setUp(self):
super(BaseAdminTest, self).setUp()
self.test_view_class = site.get_view_class(TestBaseView)
self.test_view = self.test_view_class(self._mocked_request('test/'))
def test_get_view(self):
test_a = self.test_view.get_view(TestAView, OptionA, opts={'test_attr': 'test'})
self.assertTrue(isinstance(test_a, TestAView))
self.assertTrue(isinstance(test_a, OptionA))
self.assertEqual(test_a.option_attr, 'option_test')
self.assertEqual(test_a.test_attr, 'test')
def test_model_view(self):
test_model = self.test_view.get_model_view(ListAdminView, ModelA)
self.assertTrue(isinstance(test_model, ModelAAdmin))
self.assertEqual(test_model.model, ModelA)
self.assertEqual(test_model.test_model_attr, 'test_model')
def test_admin_url(self):
test_url = self.test_view.get_admin_url('test')
self.assertEqual(test_url, '/view_base/test/base')
def test_model_url(self):
test_url = self.test_view.get_model_url(ModelA, 'list')
self.assertEqual(test_url, '/view_base/view_base/modela/list')
def test_has_model_perm(self):
test_user = User.objects.create(username='test_user')
self.assertFalse(self.test_view.has_model_perm(ModelA, 'change', test_user))
# Admin User
self.assertTrue(self.test_view.has_model_perm(ModelA, 'change'))
class CommAdminTest(BaseTest):
def setUp(self):
super(CommAdminTest, self).setUp()
self.test_view_class = site.get_view_class(TestCommView)
self.test_view = self.test_view_class(self._mocked_request('test/comm'))
def test_model_icon(self):
self.assertEqual(self.test_view.get_model_icon(ModelA), 'flag')
self.assertEqual(self.test_view.get_model_icon(ModelB), 'test')
|
379af3add17394122c6d73eb5b7cdf7db6107b10
|
[
"Python",
"Text",
"reStructuredText"
] | 19
|
Python
|
edwardvon/xadmin-django3
|
f9f3ed7c6b33896e48ddf59149e1f5bd2cfe780a
|
3c08b5eb51beb89f0962ff5efbcadb18f8895c87
|
refs/heads/master
|
<repo_name>AngeloACR/panelchild<file_sep>/wattsDisp.php
<?php
/* Template Name:wattsDisp */
global $product;
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
if($pCats[0][0] == "Good Packages"){
$wattsBase = 1650;
$wattsGap = 275;
} elseif ($pCats[0][0] == "Better Packages") {
$wattsBase = 1830;
$wattsGap = 305;
} elseif ($pCats[0][0] == "Best Packages"){
$wattsBase = 1980;
$wattsGap = 330;
}
?>
<p style="font-size: 18px" id="watts"></p>
<script>
var wattsInfo = document.getElementById('watts');
var totalWatts;
var val = 6;
var watts = calcWatts(val);
wattsInfo.textContent = "Watt Peak: " + watts;
document.addEventListener("watts", function () {
val = localStorage.getItem('panelQty');
watts = calcWatts(val);
wattsInfo.textContent = "Watt Peak: " + watts;
});
function calcWatts(val){
var wattsBase = <?php echo $wattsBase; ?>;
var wattsGap = <?php echo $wattsGap; ?>;
var gap = val - 6;
totalWatts = wattsBase + wattsGap*gap;
//localStorage.setItem('watts', totalWatts);
return totalWatts
}
</script><file_sep>/showProducts.php
<?php
/* Template Name:showProducts */
global $product;
$title = $product->get_title();
$description = $product->get_short_description();
?>
<div class="bigBox">
<p><?php echo $description; ?></p>
</div>
<style>
.bigBox{
display: flex;
flex-direction: column;
justify-content: flex-start;
}
</style>
<?php
<file_sep>/panelPeople.php
<?php
/* Template Name:panelPeople */
global $product;
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
?>
<div class="iBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/15_personen_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<p style="font-size: 18px" id="people"></p>
</div>
<div class="iBox">
<p style="font-size: 14px" id="sku"></p>
</div>
<style>
.iBox{
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.iBox img{
width: 2.375em;
margin-right: 0.5em;
}
</style>
<script>
var people = document.getElementById('people');
var sku = document.getElementById('sku');
skuInit = "<?php echo $product->get_sku();?>"
var val1 = 6;
var val2 = "Mono";
var skuText = getSku(skuInit, val1, val2);
var nPeople = calcPeople(val1, val2);
people.textContent = nPeople;
sku.textContent = skuText;
document.addEventListener("qty", function () {
val1 = localStorage.getItem('panelQty');
val2 = localStorage.getItem('energy');
nPeople = calcPeople(val1, val2);
skuText = getSku(skuInit, val1, val2);
people.textContent = nPeople;
sku.textContent = skuText;
});
function getSku(init, val1, val2){
var sku = init;
if( val2 == "Mono"){
sku += "sf-";
} else{
sku += "df-";
}
sku += val1;
return sku;
}
function calcPeople(val1, val2){
var nPeople;
<?php
if($pCats[0][0] == "Goed Pakket"){
?>
if( val2=="Mono"){
if(val1 >=6 && val1 <=9){
nPeople = 1+" persoon";
} else if(val1 >=10 && val1 <=13){
nPeople = 2+" personen";
} else if(val1 >=14 && val1 <=16){
nPeople = 3+" personen";
} else if(val1 >=17 && val1 <=19){
nPeople = 4+" personen";
} else if(val1 >=20 && val1 <=25){
nPeople = 5+" personen";
}
} else{
if(val1 >=18 && val1 <=20){
nPeople = 5+" personen";
} else if(val1 >=21 && val1 <=25){
nPeople = 5+" pers + EV";
}
}
<?php
} elseif ($pCats[0][0] == "Beter Pakket") {
?>
if( val2=="Mono"){
if(val1 >=6 && val1 <=9){
nPeople = 1+" persoon";
} else if(val1 >=10 && val1 <=12){
nPeople = 2+" personen";
} else if(val1 >=13 && val1 <=15){
nPeople = 3+" personen";
} else if(val1 >=16 && val1 <=17){
nPeople = 4+" personen";
} else if(val1 >=18 && val1 <=19){
nPeople = 5+" personen";
} else if(val1 >=20 && val1 <=25){
nPeople = 5+" pers + EV";
}
} else{
nPeople = 5+" pers + EV";
}
<?php
} elseif ($pCats[0][0] == "Beste Pakket"){
?>
if( val2=="Mono"){
if(val1 >=6 && val1 <=8){
nPeople = 1+" persoon";
} else if(val1 >=9 && val1 <=11){
nPeople = 2+" personen";
} else if(val1 >=12 && val1 <=13){
nPeople = 3+" personen";
} else if(val1 >=14 && val1 <=15){
nPeople = 4+" personen";
} else if(val1 >=16 && val1 <=17){
nPeople = 5+" personen";
} else if(val1 >=18 && val1 <=25){
nPeople = 5+" pers + EV";
}
} else{
if(val1 >=12 && val1 <=13){
nPeople = 3+" personen";
} else if(val1 >=14 && val1 <=15){
nPeople = 4+" personen";
} else if(val1 >=16 && val1 <=17){
nPeople = 5+" personen";
} else if(val1 >=18 && val1 <=25){
nPeople = 5+" pers + EV";
}
}
<?php
}
?>
return nPeople;
}
</script><file_sep>/panelHeader.php
<?php
/* Template Name:qtyButt */
global $product;
?>
<div>
<h1><?php echo $product->get_title(); ?></h1>
<p style="color: #FF671D;">Aantal panelen: </p>
</div>
<?php
?>
<file_sep>/addToCart.php
<?php
/* Template Name:addToCart */
global $product;
$id = $product->get_id();
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
$i=0;
if($pCats[0][0] == "Goed Pakket"){
$panelMin = 18;
$solarMonoSKU = array(
"NLZ-Gsf-6",
"NLZ-Gsf-7",
"NLZ-Gsf-8",
"NLZ-Gsf-9",
"NLZ-Gsf-10",
"NLZ-Gsf-11",
"NLZ-Gsf-12",
"NLZ-Gsf-13",
"NLZ-Gsf-14",
"NLZ-Gsf-15",
"NLZ-Gsf-16",
"NLZ-Gsf-17",
"NLZ-Gsf-18",
"NLZ-Gsf-19",
"NLZ-Gsf-20",
"NLZ-Gsf-21"
);
$solarTriSKU = array(
"NLZ-Gdf-18",
"NLZ-Gdf-19",
"NLZ-Gdf-20",
"NLZ-Gdf-21",
"NLZ-Gdf-22",
"NLZ-Gdf-23",
"NLZ-Gdf-24",
"NLZ-Gdf-25",
);
$fullTriSKU = array (
"NLZ-inst-18-3",
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
} else if($pCats[0][0] == "Beter Pakket"){
$panelMin = 19;
$solarMonoSKU = array(
"NLZ-Bsf-6",
"NLZ-Bsf-7",
"NLZ-Bsf-8",
"NLZ-Bsf-9",
"NLZ-Bsf-10",
"NLZ-Bsf-11",
"NLZ-Bsf-12",
"NLZ-Bsf-13",
"NLZ-Bsf-14",
"NLZ-Bsf-15",
"NLZ-Bsf-16",
"NLZ-Bsf-17",
"NLZ-Bsf-18",
"NLZ-Bsf-19",
"NLZ-Bsf-20",
"NLZ-Bsf-21",
"NLZ-Bsf-22",
"NLZ-Bsf-23",
"NLZ-Bsf-24",
"NLZ-Bsf-25"
);
$solarTriSKU = array(
"NLZ-Bdf-19",
"NLZ-Bdf-20",
"NLZ-Bdf-21",
"NLZ-Bdf-22",
"NLZ-Bdf-23",
"NLZ-Bdf-24",
"NLZ-Bdf-25"
);
$fullTriSKU = array (
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
} else if($pCats[0][0] == "Beste Pakket"){
$panelMin = 12;
$solarMonoSKU = array(
"NLZ-BTsf-6",
"NLZ-BTsf-7",
"NLZ-BTsf-8",
"NLZ-BTsf-9",
"NLZ-BTsf-10",
"NLZ-BTsf-11",
"NLZ-BTsf-12",
"NLZ-BTsf-13",
"NLZ-BTsf-14",
"NLZ-BTsf-15",
"NLZ-BTsf-16",
"NLZ-BTsf-17",
"NLZ-BTsf-18",
"NLZ-BTsf-19",
"NLZ-BTsf-20",
"NLZ-BTsf-21",
"NLZ-BTsf-22",
"NLZ-BTsf-23",
"NLZ-BTsf-24",
"NLZ-BTsf-25"
);
$solarTriSKU = array(
"NLZ-BTdf-12",
"NLZ-BTdf-13",
"NLZ-BTdf-14",
"NLZ-BTdf-15",
"NLZ-BTdf-16",
"NLZ-BTdf-17",
"NLZ-BTdf-18",
"NLZ-BTdf-19",
"NLZ-BTdf-20",
"NLZ-BTdf-21",
"NLZ-BTdf-22",
"NLZ-BTdf-23",
"NLZ-BTdf-24",
"NLZ-BTdf-25"
);
$fullTriSKU = array (
"NLZ-inst-12",
"NLZ-inst-13",
"NLZ-inst-14",
"NLZ-inst-15",
"NLZ-inst-16",
"NLZ-inst-17",
"NLZ-inst-18-3",
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
}
$flatSSSKU = array (
"NLZ-fff-ez-6",
"NLZ-fff-ez-7",
"NLZ-fff-ez-8",
"NLZ-fff-ez-9",
"NLZ-fff-ez-10",
"NLZ-fff-ez-11",
"NLZ-fff-ez-12",
"NLZ-fff-ez-13",
"NLZ-fff-ez-14",
"NLZ-fff-ez-15",
"NLZ-fff-ez-16",
"NLZ-fff-ez-17",
"NLZ-fff-ez-18",
"NLZ-fff-ez-19",
"NLZ-fff-ez-20",
"NLZ-fff-ez-21",
"NLZ-fff-ez-22",
"NLZ-fff-ez-23",
"NLZ-fff-ez-24",
"NLZ-fff-ez-25"
);
$flatEWBKU = array (
"NLZ-fff-owzw-6",
"NLZ-fff-owzw-8",
"NLZ-fff-owzw-10",
"NLZ-fff-owzw-12",
"NLZ-fff-owzw-14",
"NLZ-fff-owzw-16",
"NLZ-fff-owzw-18",
"NLZ-fff-owzw-20",
"NLZ-fff-owzw-22",
"NLZ-fff-owzw-24"
);
$flatSBSKU = array (
"NLZ-fff-ezw-6",
"NLZ-fff-ezw-7",
"NLZ-fff-ezw-8",
"NLZ-fff-ezw-9",
"NLZ-fff-ezw-10",
"NLZ-fff-ezw-11",
"NLZ-fff-ezw-12",
"NLZ-fff-ezw-13",
"NLZ-fff-ezw-14",
"NLZ-fff-ezw-15",
"NLZ-fff-ezw-16",
"NLZ-fff-ezw-17",
"NLZ-fff-ezw-18",
"NLZ-fff-ezw-19",
"NLZ-fff-ezw-20",
"NLZ-fff-ezw-21",
"NLZ-fff-ezw-22",
"NLZ-fff-ezw-23",
"NLZ-fff-ezw-24",
"NLZ-fff-ezw-25"
);
$flatEWSSKU = array (
"NLZ-fff-owz-6",
"NLZ-fff-owz-8",
"NLZ-fff-owz-10",
"NLZ-fff-owz-12",
"NLZ-fff-owz-14",
"NLZ-fff-owz-16",
"NLZ-fff-owz-18",
"NLZ-fff-owz-20",
"NLZ-fff-owz-22",
"NLZ-fff-owz-24"
);
$inclinedSKU = array (
"NLZ-evo-6",
"NLZ-evo-7",
"NLZ-evo-8",
"NLZ-evo-9",
"NLZ-evo-10",
"NLZ-evo-11",
"NLZ-evo-12",
"NLZ-evo-13",
"NLZ-evo-14",
"NLZ-evo-15",
"NLZ-evo-16",
"NLZ-evo-17",
"NLZ-evo-18",
"NLZ-evo-19",
"NLZ-evo-20",
"NLZ-evo-21",
"NLZ-evo-22",
"NLZ-evo-23",
"NLZ-evo-24",
"NLZ-evo-25",
);
$ownSKU = array (
"NLZ-ktmc1",
"NLZ-ktmc2",
"NLZ-ktmc3",
"NLZ-ktmc4",
"NLZ-ktmc5",
"NLZ-ktmc6",
"NLZ-ktmc7",
"NLZ-ktmc8",
"NLZ-ktmc9",
"NLZ-ktmc10",
"NLZ-ktmc11",
"NLZ-ktmc12",
"NLZ-ktmc13",
"NLZ-ktmc14",
"NLZ-ktmc15",
"NLZ-ktmc16",
"NLZ-ktmc17",
"NLZ-ktmc18",
"NLZ-ktmc19",
"NLZ-ktmc20",
"NLZ-ktmc21",
"NLZ-ktmc22",
"NLZ-ktmc23",
"NLZ-ktmc24",
"NLZ-ktmc25"
);
$electricianSKU= "NLZ-elkt-10";
$fullMonoSKU = array (
"NLZ-inst-6",
"NLZ-inst-7",
"NLZ-inst-8",
"NLZ-inst-9",
"NLZ-inst-10",
"NLZ-inst-11",
"NLZ-inst-12",
"NLZ-inst-13",
"NLZ-inst-14",
"NLZ-inst-15",
"NLZ-inst-16",
"NLZ-inst-17",
"NLZ-inst-18",
"NLZ-inst-19",
"NLZ-inst-20",
"NLZ-inst-21",
"NLZ-inst-22",
"NLZ-inst-23",
"NLZ-inst-24",
"NLZ-inst-25"
);
?>
<div class="cartBox">
<p id="priceBox"></p>
<a id="addButt" class="button primary is-outline" style=border-radius:99px;>Ik ga bestellen</a>
</div>
<style>
.cartBox{
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
</style>
<script>
<?php
$nonce = wp_create_nonce("myCustomCartNonce");
?>
var nonce = "<?php echo $nonce; ?>"
var addButt = document.getElementById("addButt");
addButt.setAttribute( 'data-nonce', nonce );
document.addEventListener("price", function () {
data = calcPrice();
if(data){
<?php
$home = get_home_url();
$src = $home."/wp-admin/admin-ajax.php?action=myCustomCart";
?>
//var link = '/dev/wp-admin/admin-ajax.php?action=myCustomCart&pQty='+data['pQty']+'&ids='+data['ids']+'&nonce='+nonce;
var link = '<?php echo $src ?>&pQty='+data['pQty']+'&ids='+data['ids']+'&nonce='+nonce;
addButt.href = link;
}
});
addButt.addEventListener("click", function () {
localStorage.setItem('panelQty', '6');
localStorage.removeItem('install');
localStorage.removeItem('roof');
localStorage.removeItem('roofDir');
localStorage.removeItem('roofColor');
localStorage.removeItem('energy');
});
function calcPrice(){
var pTag = <?php echo "\"".$pCats[0][0]."\""; ?>;
var priceBox = document.getElementById('priceBox');
var pQty = localStorage.getItem('panelQty');
var roof = localStorage.getItem('roof');
var roofDir = localStorage.getItem('roofDir');
var roofColor = localStorage.getItem('roofColor');
var energy = localStorage.getItem('energy');
var install = localStorage.getItem('install');
var panelMin = <?php echo $panelMin;?>;
var solarMonoIds = [];
var solarTriIds = [];
var flatSSIds = [];
var flatEWSIds = [];
var flatSBIds = [];
var flatEWBIds = [];
var fullMonoIds = [];
var fullTriIds = [];
var inclinedIds = [];
var ownIds = [];
var electricianIds = [];
var solarMonoPrices = [];
var solarTriPrices = [];
var flatSSPrices = [];
var flatSBPrices = [];
var flatEWSPrices = [];
var flatEWBPrices = [];
var fullMonoPrices = [];
var fullTriPrices = [];
var inclinedPrices = [];
var ownPrices = [];
var electricianPrices = [];
<?php
foreach ($solarMonoSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
solarMonoIds.push(<?php echo $id;?>)
solarMonoPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($solarTriSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
solarTriIds.push(<?php echo $id;?>)
solarTriPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($flatSSSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
flatSSIds.push(<?php echo $id;?>)
flatSSPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($flatEWSSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
flatEWSIds.push(<?php echo $id;?>);
flatEWSPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($flatSBSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
flatSBIds.push(<?php echo $id;?>)
flatSBPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($flatEWBKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
flatEWBIds.push(<?php echo $id;?>);
flatEWBPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($inclinedSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
inclinedIds.push(<?php echo $id;?>);
inclinedPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($ownSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
ownIds.push(<?php echo $id;?>);
ownPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
$id = wc_get_product_id_by_sku($electricianSKU);
$prod = wc_get_product( $id );
?>
var electricianId = <?php echo $id;?>;
var electricianPrice = parseFloat(<?php echo $prod->get_price();?>);
<?php
foreach ($fullMonoSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
fullMonoIds.push(<?php echo $id;?>);
fullMonoPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
foreach ($fullTriSKU as $sku ) {
$id = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $id );
?>
fullTriIds.push(<?php echo $id;?>);
fullTriPrices.push(parseFloat(<?php echo $prod->get_price();?>));
<?php
}
?>
if(energy == "Mono"){
solarPrice = parseFloat(solarMonoPrices[pQty-6]);
solarId = solarMonoIds[pQty-6];
localStorage.setItem('solarPrice', solarPrice);
localStorage.setItem('table', energy);
} else if (energy == "Tri"){
solarPrice = parseFloat(solarTriPrices[pQty-panelMin]);
solarId = solarTriIds[pQty-panelMin];
localStorage.setItem('solarPrice', solarPrice);
localStorage.setItem('table', energy);
} else if(energy == "Dontknow"){
if(pQty < panelMin){
solarPrice = parseFloat(solarMonoPrices[pQty-6]);
solarId = solarMonoIds[pQty-6];
localStorage.setItem('table', "Mono");
localStorage.setItem('solarPrice', solarPrice);
} else{
solarPrice1 = parseFloat(solarMonoPrices[pQty-6]);
solarPrice2 = parseFloat(solarTriPrices[pQty-panelMin]);
if(solarPrice2 < solarPrice1){
solarPrice = solarPrice1;
solarId = solarMonoIds[pQty-6];
localStorage.setItem('table', "Mono");
localStorage.setItem('solarPrice', solarPrice);
} else{
solarPrice = solarPrice2;
solarId = solarTriIds[pQty-panelMin];
localStorage.setItem('table', "Tri");
localStorage.setItem('solarPrice', solarPrice);
}
}
}
var roofPrice;
var roofId;
if( roof == "Flat"){
if(roofDir == "South"){
if(roofColor == "Silver"){
roofPrice = parseFloat(flatSSPrices[pQty-6]);
roofId = flatSSIds[pQty-6];
localStorage.setItem('roofPrice', roofPrice);
} else if (roofColor == "Black"){
roofPrice = parseFloat(flatSBPrices[pQty-6]);
roofId = flatSBIds[pQty-6];
localStorage.setItem('roofPrice', roofPrice);
}
} else if(roofDir == "East-West"){
if(roofColor == "Silver"){
roofPrice = parseFloat(flatEWSPrices[(pQty-6)/2]);
roofId = flatEWSIds[(pQty-6)/2];
localStorage.setItem('roofPrice', roofPrice);
} else if (roofColor == "Black"){
roofPrice = parseFloat(flatEWBPrices[(pQty-6)/2]);
roofId = flatEWBIds[(pQty-6)/2];
localStorage.setItem('roofPrice', roofPrice);
}
}
} else if (roof == "Inclined"){
roofPrice = parseFloat(inclinedPrices[pQty-6]);
roofId = inclinedIds[pQty-6];
localStorage.setItem('roofPrice', roofPrice);
}
/*****************************FULL INSTALLATION FALTAN PRECIOS PARA BETTER Y BEST PACKAGES **************************************/
var installPrice;
var installPrice2;
var installId;
var table = localStorage.getItem('table');
if(install == "Own"){
installPrice = parseFloat(ownPrices[pQty - 6]);
installId = ownIds[pQty - 6];
localStorage.setItem('installPrice', installPrice);
}else if(install == "Electrician"){
installPrice = parseFloat(ownPrices[pQty - 6]);
installId = ownIds[pQty - 6];
installPrice2 = parseFloat(electricianPrice);
installId2 = electricianId;
localStorage.setItem('installPrice', installPrice);
localStorage.setItem('installPrice2', installPrice2);
}else if(install == "Full Installed" && table == "Mono"){
installPrice = parseFloat(fullMonoPrices[pQty - 6]);
installId = fullMonoIds[pQty - 6];
localStorage.setItem('installPrice', installPrice);
}else if(install == "Full Installed" && table == "Tri"){
installPrice = parseFloat(fullTriPrices[pQty - panelMin]);
installId = fullTriIds[pQty - panelMin];
localStorage.setItem('installPrice', installPrice);
}
if(installPrice2){
var price = solarPrice+roofPrice+installPrice+installPrice2;
var ids = solarId+', '+roofId+', '+installId+', '+installId2;
} else {
var price = solarPrice+roofPrice+installPrice;
var ids = solarId+', '+roofId+', '+installId;
}
if(roof && energy && install && pQty){
var branch = document.createElement('BR');
var priceText = document.createElement('P');
var taxText = document.createElement('P');
var totalText = document.createElement('P');
price = price.toFixed(2);
var tax = price*0.21;
tax = tax.toFixed(2);
var total = parseFloat(price) + parseFloat(tax);
total = total.toFixed(2);
while (priceBox.childNodes.length > 0) {
priceBox.removeChild(priceBox.lastChild);
}
priceText.textContent = "Subtotal: €" + price + " exc. BTW";
taxText.textContent += "BTW: €" + tax;
totalText.textContent += "Total: €" + total + " inc. BTW";
priceBox.appendChild(priceText);
priceBox.appendChild(taxText);
priceBox.appendChild(totalText);
}
var data = {
pQty: pQty,
ids: ids,
};
return data;
}
</script>
<?php
<file_sep>/functions.php
<?php
// Add custom Theme Functions here
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 11 );
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action('wp_head', 'fontAwesome');
function fontAwesome(){
?>
<script src="https://kit.fontawesome.com/2652a50924.js" crossorigin="anonymous"></script>
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.2.3/dist/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdn.jsdelivr.net/npm/uikit@3.2.3/dist/js/uikit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uikit@3.2.3/dist/js/uikit-icons.min.js"></script>
<?php
}
add_action( 'wp_footer', 'setDefaults');
function setDefaults() {
?>
<script>
var clear = new CustomEvent("clear");
window.onload = function() {
localStorage.setItem('panelQty', '6');
localStorage.removeItem('install');
localStorage.removeItem('roof');
localStorage.removeItem('roofDir');
localStorage.removeItem('roofColor');
localStorage.removeItem('energy');
localStorage.removeItem('solarPrice');
localStorage.removeItem('roofPrice');
localStorage.removeItem('installPrice');
localStorage.removeItem('installPrice2');
localStorage.removeItem('table');
document.dispatchEvent(clear);
};
document.addEventListener("DOMContentLoaded", function(){
document.dispatchEvent(clear);
});
</script>
<?php
}
include_once('panelshorts.php');
include_once('toCart.php');
<file_sep>/qtyButt.php
<?php
/* Template Name:qtyButt */
global $product;
$components = $product->get_components();
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
$panelTag = 'Panelen';
if($pCats[0][0] == "Goed Pakket"){
$wattsBase = 1650;
$wattsGap = 275;
} elseif ($pCats[0][0] == "Beter Pakket") {
$wattsBase = 1830;
$wattsGap = 305;
} elseif ($pCats[0][0] == "Beste Pakket"){
$wattsBase = 1980;
$wattsGap = 330;
}
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$prod = wc_get_product( $data['default_id'] );
preg_match_all('~>\K[^<>]*(?=<)~', $prod->get_categories(), $cats);
foreach ($cats[0] as $cat ){
if($cat == $panelTag){
$qMin = $component->get_quantity('min');
$qMax = $component->get_quantity('max');
$val = $qMin;
?>
<div class="smallBox">
<div class="inputBox">
<select id="qtyPanel" class="myInput" name="qtyPanel">
<?php
for ($i=$qMin; $i <=$qMax ; $i++) {
?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php
}
?>
</select>
</div>
<p id="watts"></p>
</div>
<?php
break;
}
}
}
?>
<style>
#watts{
margin: 0 !important;
font-size: 18px;
}
.smallBox{
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.myInput{
max-width: 3.5em !important;
width: 3.5em !important;
margin: 0 !important;
text-align: center !important;
}
.inputBox{
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
margin-right: 10px;
}
</style>
<script>
var input = document.getElementById("qtyPanel");
var wattsEv = new CustomEvent("watts");
var priceEv = new CustomEvent("price");
var qty = new CustomEvent("qty");
input.addEventListener("change", function() {
var value = parseInt(input.value);
localStorage.setItem('panelQty', value);
input.value = value;
document.dispatchEvent(wattsEv);
document.dispatchEvent(priceEv);
document.dispatchEvent(qty);
});
var wattsInfo = document.getElementById('watts');
var totalWatts;
var val = 6;
var watts = calcWatts(val);
wattsInfo.textContent = watts + " Watts";
document.addEventListener("watts", function () {
val = localStorage.getItem('panelQty');
watts = calcWatts(val);
wattsInfo.textContent = watts + " Watts";
});
function calcWatts(val){
var wattsBase = <?php echo $wattsBase; ?>;
var wattsGap = <?php echo $wattsGap; ?>;
var gap = val - 6;
totalWatts = wattsBase + wattsGap*gap;
//localStorage.setItem('watts', totalWatts);
return totalWatts
}
</script>
<?php
?>
<file_sep>/installButts.php
<?php
/* Template Name:installButts */
global $product;
?>
<h4 style="color:#ff6600;">Installateur: <span style="font-size: 16px; color:black;" id="installPrice"></span></h4>
<div class="buttsBox">
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/12_diy_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="install"><input type="radio" name="install" value="own">Doe het zelf <a href="#ownModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/13_elektricien_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="install"><input type="radio" name="install" value="elec">Elektromonteur <a href="#elecModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/14_geinstalleerd_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="install"><input type="radio" name="install" value="full">Volledig geïnstallerd <a href="#fullModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
</div>
<div id="ownModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Doe het zelf:</strong></h2>
<p>
Bent u handig of heeft u mensen in uw omgeving die verstand hebben van het installeren van zonnepanelen? Dan is zelf installeren verreweg de goedkoopste optie. Let op dat u veiligheidsmaatregelen neemt. Denk aan valbescherming, het plaatsen van stellingen en zekeringen en dergelijke. Mocht u er niet zeker van zijn of het aansluiten of het installeren van zonnepanelen binnen uw macht ligt, kies dan voor een elektromonteur of een volledige installatie.
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<div id="elecModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Elektromonteur:</strong></h2>
<p>
De elektromonteur zorgt ervoor dat uw panelen goed worden aangesloten op de omvormer en de omvormer goed wordt aangesloten op de meterkast. <br>
Wat doet de elektromonteur: <br>
<ul>
<li>Doormeten van alle zonnepanelen of ze goed zijn aangesloten.</li>
<li>Aansluiten van de zonnepanelen op de omvormer.</li>
<li>Aansluiten van omvormer op de meterkast.</li>
</ul><br>
Wat moet u voorbereiden: <br>
<ul>
<li>Zorg ervoor dat de elektromonteur overal goed bij kan.</li>
<li>Zorg ervoor dat wanneer u meerdere strings hebt, duidelijk is welke draden bij elkaar horen.</li>
<li>Zorg ervoor dat eventuele gaten naar de omvormer en naar de meterkast geboord zijn.</li>
</ul> <br>
Wat doet de elektromonteur niet:
<ul>
<li>Alle overige activiteiten en installaties doet de elektromonteur niet.</li>
</ul>
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<div id="fullModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Volledig geïnstalleerd:</strong></h2>
<p>
U hoeft niks zelf te doen als u kiest voor een volledige installatie. De installateur zal de panelen, bekabeling en alles wat u verder nodig heeft meenemen en aansluiten. Hij zal zorgdragen dat de panelen netjes op uw dak worden gemonteerd. Ook zorgt de de installateur voor de aansluiting van de zonnepanelen op de omvormer en de omvormer op de meterkast. <br>
Let op: <br>
<ul>
<li>1. De installateur boord geen gaten in betonnen vloeren, maar zal in overleg met u een geschikte route voor de bekabeling vinden.</li>
<li>2. De installateur moet de mogelijkheid hebben om een stelling te plaatsen waar dat nodig is voor de veiligheid.</li>
<li>3. Mochten er bijzonderheden zijn, kan het zijn dat de installatie niet op dezelfde dag kan worden afgerond. </li>
</ul>
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<style>
.iconBox{
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
}
.iconBox img{
width: 2.375em;
margin-bottom:0.313em;
}
.buttsBox{
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
</style>
<script>
var installPrice = document.getElementById("installPrice");
var installButts = document.getElementsByName("install");
var priceEv = new CustomEvent("price");
installButts[0].addEventListener("change", function() {
localStorage.setItem('install', 'Own');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('installPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
installPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
installButts[1].addEventListener("change", function() {
localStorage.setItem('install', 'Electrician');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('installPrice')
var price2 = localStorage.getItem('installPrice2')
var total = parseInt(price)+parseInt(price2);
var tax = total*1.21;
tax = tax.toFixed(2);
installPrice.textContent = "€ " + total + " exc. BTW / € " + tax + " inc. BTW";
});
installButts[2].addEventListener("change", function() {
localStorage.setItem('install', 'Full Installed');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('installPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
installPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
document.addEventListener("qty", function() {
var price2 = parseFloat(localStorage.getItem('installPrice2'));
var price = parseFloat(localStorage.getItem('installPrice'));
var energy = localStorage.getItem('energy');
if(price2){
price += price2;
price = price.toFixed(2);
}
var tax = price*1.21;
tax = tax.toFixed(2);
if(price && energy){
installPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
});
document.addEventListener("clear", function(){
installButts[0].checked = false;
installButts[1].checked = false;
installButts[2].checked = false;
});
</script><file_sep>/showTable.php
<?php
/* Template Name:showTable */
global $product;
?>
<?php
$id = $product->get_id();
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
if($pCats[0][0] == "Goed Pakket"){
$panelMin = 18;
$solarMonoSKU = array(
"NLZ-Gsf-6",
"NLZ-Gsf-7",
"NLZ-Gsf-8",
"NLZ-Gsf-9",
"NLZ-Gsf-10",
"NLZ-Gsf-11",
"NLZ-Gsf-12",
"NLZ-Gsf-13",
"NLZ-Gsf-14",
"NLZ-Gsf-15",
"NLZ-Gsf-16",
"NLZ-Gsf-17",
"NLZ-Gsf-18",
"NLZ-Gsf-19",
"NLZ-Gsf-20",
"NLZ-Gsf-21"
);
$solarTriSKU = array(
"NLZ-Gdf-18",
"NLZ-Gdf-19",
"NLZ-Gdf-20",
"NLZ-Gdf-21",
"NLZ-Gdf-22",
"NLZ-Gdf-23",
"NLZ-Gdf-24",
"NLZ-Gdf-25",
);
} else if($pCats[0][0] == "Beter Pakket"){
$panelMin = 19;
$solarMonoSKU = array(
"NLZ-Bsf-6",
"NLZ-Bsf-7",
"NLZ-Bsf-8",
"NLZ-Bsf-9",
"NLZ-Bsf-10",
"NLZ-Bsf-11",
"NLZ-Bsf-12",
"NLZ-Bsf-13",
"NLZ-Bsf-14",
"NLZ-Bsf-15",
"NLZ-Bsf-16",
"NLZ-Bsf-17",
"NLZ-Bsf-18",
"NLZ-Bsf-19",
"NLZ-Bsf-20",
"NLZ-Bsf-21",
"NLZ-Bsf-22",
"NLZ-Bsf-23",
"NLZ-Bsf-24",
"NLZ-Bsf-25"
);
$solarTriSKU = array(
"NLZ-Bsf-19",
"NLZ-Bsf-20",
"NLZ-Bsf-21",
"NLZ-Bsf-22",
"NLZ-Bsf-23",
"NLZ-Bsf-24",
"NLZ-Bsf-25",
);
} else{ if($pCats[0][0] == "Beste Pakket")
$panelMin = 12;
$solarMonoSKU = array(
"NLZ-BTsf-6",
"NLZ-BTsf-7",
"NLZ-BTsf-8",
"NLZ-BTsf-9",
"NLZ-BTsf-10",
"NLZ-BTsf-11",
"NLZ-BTsf-12",
"NLZ-BTsf-13",
"NLZ-BTsf-14",
"NLZ-BTsf-15",
"NLZ-BTsf-16",
"NLZ-BTsf-17",
"NLZ-BTsf-18",
"NLZ-BTsf-19",
"NLZ-BTsf-20",
"NLZ-BTsf-21",
"NLZ-BTsf-22",
"NLZ-BTsf-23",
"NLZ-BTsf-24",
"NLZ-BTsf-25"
);
$solarTriSKU = array(
"NLZ-BTsf-12",
"NLZ-BTsf-13",
"NLZ-BTsf-14",
"NLZ-BTsf-15",
"NLZ-BTsf-16",
"NLZ-BTsf-17",
"NLZ-BTsf-18",
"NLZ-BTsf-19",
"NLZ-BTsf-20",
"NLZ-BTsf-21",
"NLZ-BTsf-22",
"NLZ-BTsf-23",
"NLZ-BTsf-24",
"NLZ-BTsf-25"
);
}
$i=0;
foreach ($solarMonoSKU as $sku ) {
$solarMonoIds[] = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $solarMonoIds[$i] );
$components = $prod->get_components();
$j = 0;
foreach ($components as $component ) {
$data = $component->get_data();
$prod = wc_get_product( $data['default_id'] );
$att = $prod->get_attribute('documentatie');
//$docs = explode (",", $att);
$docs = explode (".pdf", $att);
?>
<div id=<?php echo "docMonoModal".$i.$j; ?> uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Documentatie:</strong></h2>
<ul class="docs">
<?php foreach ($docs as $doc) { ?>
<?php $pdfDoc = $doc.".pdf" ?>
<li class="doc">
<a href=<?php echo $pdfDoc; ?> class="docName">
<?php
$url = basename($doc);
echo str_replace('%20', ' ', $url);
?>
</a>
</li>
<?php } ?>
</ul>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<?php
$j += 1;
}
$i += 1;
}
$i=0;
foreach ($solarTriSKU as $sku ) {
$solarTriIds[] = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $solarTriIds[$i] );
$components = $prod->get_components();
$j = 0;
foreach ($components as $component ) {
$data = $component->get_data();
$prod = wc_get_product( $data['default_id'] );
$att = $prod->get_attribute('documentatie');
//$docs = explode (",", $att);
$docs = explode (".pdf", $att);
?>
<div id=<?php echo "docTriModal".$i.$j; ?> uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Documentatie:</strong></h2>
<ul class="docs">
<?php foreach ($docs as $doc) { ?>
<?php $pdfDoc = $doc.".pdf" ?>
<li class="doc">
<a href=<?php echo $pdfDoc; ?> class="docName">
<?php
$url = basename($doc);
echo str_replace('%20', ' ', $url);
?>
</a>
</li>
<?php } ?>
</ul>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<?php
$j += 1;
}
$i += 1;
}
?>
<div class="tableBox">
<table>
<tbody id="list" class="docs">
<tr class = "doc">
<th style="width:5%;" class="docTitle">Aantal</th>
<th style="width:10%;" class="docTitle">Type</th>
<th style="width:40%;" class="docTitle">Naam</th>
<th style="width:10%;" class="docTitle">Merk</th>
<th style="width:12%;" class="docTitle">Product garantie</th>
<th style="width:13%;" class="docTitle">Opbrengst garantie</th>
<th style="width:5%;" class="docTitle">Docs</th>
</tr>
</tbody>
</table>
</div>
<style>
.tableBox{
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
}
.docTitle{
font-weight: bold;
font-size: 16px;
text-align: center;
}
.docName{
word-wrap: break-word;
text-align: center;
}
.doc{
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
text-align: center;
margin-left: 0 !important;
margin-bottom: 4px;
margin-right: 4px;
margin-left: 4px;
margin-top: 4px;
padding: 0;
}
.docs{
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
list-style-type: none;
-webkit-transition: max-height 0.2s ease-in-out;
-moz-transition: max-height 0.2s ease-in-out;
-ms-transition: max-height 0.2s ease-in-out;
-o-transition: max-height 0.2s ease-in-out;
transition: max-height 0.2s ease-in-out;
}
@media screen and (max-width: 800px) {
.docs{
flex-direction: row;
}
th.docTitle{
width: 100% !important
}
.tableBox{
overflow-x: scroll;
}
.doc:first-child{
width: 20%;
font-size: 6px;
}
.doc{
flex-direction: column;
width: 300px;
}
.docName{
width: 100% !important;
}
}
</style>
<script>
var list = document.getElementById('list');
var pQty = localStorage.getItem('panelQty');
var energy = localStorage.getItem('energy');
var packagesM = [];
var packagesT = [];
var panelMin = <?php echo $panelMin;?>;
<?php
foreach ($solarMonoIds as $id ) {
$prod = wc_get_product( $id );
$components = $prod->get_components();
?>
var package = [];
<?php
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$product = wc_get_product( $data['default_id'] );
?>
var catM = "<?php echo strip_tags($product->get_categories());?>";
var titleM = "<?php echo $component->get_title();?>";
var brandM = "<?php echo $product->get_attribute('Merk');?>";
var pWarrantM = <?php
$warr = $product->get_attribute('Product garantie');
if ($warr){
echo "\"".$warr."\"";
} else {
echo "\""."No"."\"";
}
?>;
var oWarrantM = <?php
$warr = $product->get_attribute('Opbrengst garantie');
if ($warr){
echo "\"".$warr."\"";
} else {
echo "\""."No"."\"";
}
?>;
var component = {
cat: catM,
title: titleM,
pWarrant: pWarrantM,
oWarrant: oWarrantM,
brand: brandM
};
package.push(component);
<?php
}
?>
packagesM.push(package);
<?php
}
?>
<?php
foreach ($solarTriIds as $id ) {
$prod = wc_get_product( $id );
$components = $prod->get_components();
?>
var package = []
<?php
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$product = wc_get_product( $data['default_id'] );
?>
var catT = "<?php echo strip_tags($product->get_categories());?>";
var titleT = "<?php echo $component->get_title();?>";
var brandT = "<?php echo $product->get_attribute('Merk');?>";
var pWarrantT = <?php
$warr = $product->get_attribute('Product garantie');
if ($warr){
echo "\"".$warr."\"";
} else {
echo "\""."No"."\"";
}
?>;
var oWarrantT = <?php
$warr = $product->get_attribute('Opbrengst garantie');
if ($warr){
echo "\"".$warr."\"";
} else {
echo "\""."No"."\"";
}
?>;
var component = {
cat: catT,
title: titleT,
pWarrant: pWarrantT,
oWarrant: oWarrantT,
brand: brandT
};
package.push(component);
<?php
}
?>
packagesT.push(package);
<?php
}
?>
document.addEventListener("qty", function() {
pQty = localStorage.getItem('panelQty');
energy = localStorage.getItem('table');
if(energy == "Mono"){
while (list.childNodes.length > 1) {
list.removeChild(list.lastChild);
}
var i = 0;
packagesM[pQty-6].forEach(function(component){
var node = document.createElement('TR');
var qty = document.createElement('TD');
var cat = document.createElement('TD');
var title = document.createElement('TD');
var brand = document.createElement('TD');
var pWarrant = document.createElement('TD');
var oWarrant = document.createElement('TD');
var documentation = document.createElement('TD');
var docLink = document.createElement('a');
var icon = document.createElement('i');
icon.className = "fas fa-folder";
docLink.appendChild(icon);
docLink.className = "uk-toggle";
var index = pQty - 6
docLink.href = "#docMonoModal" + index + i;
docLink.setAttribute("uk-toggle", "");
documentation.appendChild(docLink);
documentation.className = "docName";
documentation.setAttribute("style","width:5%");
i = i+1;
// if(component.cat == "Panelen"){
if(component.cat.indexOf("Panelen") !== -1){
qty.innerText = pQty;
} else{
qty.innerText = 1;
}
qty.className = "docName";
qty.setAttribute("style","width:5%");
cat.innerText = component.cat;
cat.className = "docName";
cat.setAttribute("style","width:10%");
brand.innerText = component.brand;
brand.className = "docName";
brand.setAttribute("style","width:10%");
title.innerText = component.title;
title.className = "docName";
title.setAttribute("style","width:40%");
pWarrant.innerText =component.pWarrant;
pWarrant.className = "docName";
pWarrant.setAttribute("style","width:12%");
oWarrant.innerText = component.oWarrant;
oWarrant.className = "docName";
oWarrant.setAttribute("style","width:13%");
node.appendChild(qty);
node.appendChild(cat);
node.appendChild(title);
node.appendChild(brand);
node.appendChild(pWarrant);
node.appendChild(oWarrant);
node.appendChild(documentation);
node.className = "doc";
list.appendChild(node);
});
} else if(energy == "Tri"){
while (list.childNodes.length > 1) {
list.removeChild(list.lastChild);
}
var i = 0;
packagesT[pQty-panelMin].forEach(function(component){
var node = document.createElement('TR');
var qty = document.createElement('TD');
var cat = document.createElement('TD');
var title = document.createElement('TD');
var brand = document.createElement('TD');
var pWarrant = document.createElement('TD');
var oWarrant = document.createElement('TD');
var documentation = document.createElement('TD');
var docLink = document.createElement('a');
var icon = document.createElement('i');
icon.className = "fas fa-folder";
docLink.appendChild(icon);
var index = pQty - panelMin;
docLink.href = "#docTriModal" + index + i;
docLink.setAttribute("uk-toggle", "");
documentation.appendChild(docLink);
documentation.className = "docName";
documentation.setAttribute("style","width:5%");
i = i+1;
if(component.cat == "Panelen"){
qty.innerText = pQty;
} else{
qty.innerText = 1;
}
qty.className = "docName";
qty.setAttribute("style","width:5%");
cat.innerText = component.cat;
cat.className = "docName";
cat.setAttribute("style","width:10%");
brand.innerText = component.brand;
brand.className = "docName";
brand.setAttribute("style","width:10%");
title.innerText = component.title;
title.className = "docName";
title.setAttribute("style","width:40%");
pWarrant.innerText =component.pWarrant;
pWarrant.className = "docName";
pWarrant.setAttribute("style","width:12%");
oWarrant.innerText = component.oWarrant;
oWarrant.className = "docName";
oWarrant.setAttribute("style","width:13%");
node.appendChild(qty);
node.appendChild(cat);
node.appendChild(title);
node.appendChild(brand);
node.appendChild(pWarrant);
node.appendChild(oWarrant);
node.appendChild(documentation);
node.className = "doc";
list.appendChild(node);
});
} /* else {
while (list.childNodes.length > 1) {
list.removeChild(list.lastChild);
}
var i = 0;
packagesM[pQty-6].forEach(function(component){
var node = document.createElement('TR');
var qty = document.createElement('TD');
var cat = document.createElement('TD');
var brand = document.createElement('TD');
var title = document.createElement('TD');
var pWarrant = document.createElement('TD');
var oWarrant = document.createElement('TD');
var documentation = document.createElement('TD');
var docLink = document.createElement('a');
var icon = document.createElement('i');
icon.className = "fas fa-folder";
docLink.appendChild(icon);
docLink.className = "uk-toggle";
var index = pQty - 6
docLink.href = "#docMonoModal" + index + i;
docLink.setAttribute("uk-toggle", "");
documentation.appendChild(docLink);
documentation.className = "docName";
documentation.setAttribute("style","width:5%");
i = i+1;
if(component.cat == "Panelen"){
qty.innerText = pQty;
} else{
qty.innerText = 1;
}
qty.className = "docName";
qty.setAttribute("style","width:5%");
cat.innerText = component.cat;
cat.className = "docName";
cat.setAttribute("style","width:10%");
brand.innerText = component.brand;
brand.className = "docName";
brand.setAttribute("style","width:10%");
title.innerText = component.title;
title.className = "docName";
title.setAttribute("style","width:40%");
pWarrant.innerText =component.pWarrant;
pWarrant.className = "docName";
pWarrant.setAttribute("style","width:12%");
oWarrant.innerText = component.oWarrant;
oWarrant.className = "docName";
oWarrant.setAttribute("style","width:13%");
node.appendChild(qty);
node.appendChild(cat);
node.appendChild(title);
node.appendChild(brand);
node.appendChild(pWarrant);
node.appendChild(oWarrant);
node.appendChild(documentation);
node.className = "doc";
list.appendChild(node);
});
} */
});
</script><file_sep>/panelshorts.php
<?php
function showDocs() {
ob_start();
get_template_part('showDocuments');
return ob_get_clean();
}
add_shortcode( 'product-documentation', 'showDocs' );
function showTab() {
ob_start();
get_template_part('showTable');
return ob_get_clean();
}
add_shortcode( 'product-table', 'showTab' );
function energyButts() {
ob_start();
get_template_part('energyButts');
return ob_get_clean();
}
add_shortcode( 'product-energy', 'energyButts' );
function installButts() {
ob_start();
get_template_part('installButts');
return ob_get_clean();
}
add_shortcode( 'product-installation', 'installButts' );
function roofButts() {
ob_start();
get_template_part('roofButts');
return ob_get_clean();
}
add_shortcode( 'product-roof', 'roofButts' );
function showProducts() {
ob_start();
get_template_part('showProducts');
return ob_get_clean();
}
add_shortcode( 'product-list', 'showProducts' );
function addToCart() {
ob_start();
get_template_part('addToCart');
return ob_get_clean();
}
add_shortcode( 'product-cart', 'addToCart' );
function qtyButt() {
ob_start();
get_template_part('qtyButt');
return ob_get_clean();
}
add_shortcode( 'product-qty', 'qtyButt' );
function panelHeader() {
ob_start();
get_template_part('panelHeader');
return ob_get_clean();
}
add_shortcode( 'product-header', 'panelHeader' );
function panelPeople() {
ob_start();
get_template_part('panelPeople');
return ob_get_clean();
}
add_shortcode( 'product-people', 'panelPeople' );<file_sep>/roofButts.php
<?php
/* Template Name:roofButts */
global $product;
$category = get_term_by( 'slug', 'dak', 'product_cat' );
$parentId = $category->term_id;
$args = array(
'parent' => $parentId,
'taxonomy' => 'product_cat'
);
$roofCats = get_categories( $args );
?>
<h4 style="color:#ff6600;">Daktype: <span style="font-size: 16px; color:black;" id="roofPrice"></span></h4>
<?php/*
foreach($roofCats as $roofCat) {
?>
<div class="roofsBox">
<div class="iconBox">
<?php
$src = $roofCat->thumbnail;
?>
<img src="<?php echo $src; ?>" alt="">
<label for="roof"><input type="radio" name="roof" value="<?php echo $roofCat->name; ?>"> <?php echo $roofCat->name; ?><a href="#<?php echo $roofCat->name; ?>Modal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
</div>
<?php
$args = array(
'parent' => $roofCat->term_id,
'taxonomy' => 'product_cat'
);
$roofChilds = get_categories( $args );
if($roofChilds){
?>
<div>
<?php
foreach($roofChilds as $roofChild){
?>
<div class="iconBox">
<label for="roofDir"><input type="radio" name="roofDir" value="<?php echo $roofChild->name; ?>"><?php echo $roofChild->name; ?></label>
</div>
<?php
}
?>
</div>
<?php
}
?>
<div id="<?php echo $roofCat->name; ?>Modal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong><?php echo $roofCat->name; ?>:</strong></h2>
<p>
<?php echo $roofCat->description;?>
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<?php
}
*/
?>
<div class="roofsBox">
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/07_platfond_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="roof"><input type="radio" name="roof" value="flat">Platdak <a href="#flatModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/06_schuin_dak_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="roof"><input type="radio" name="roof" value="incl">Pannendak <a href="#incModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
</div>
<div class="flatBox">
<div class="dirBox">
<div class="iconBox">
<label for="roofDir"><input type="radio" name="roofDir" value="sout">Zuid</label>
</div>
<div class="iconBox">
<label for="roofDir"><input type="radio" name="roofDir" value="eswe">Oost-West</label>
</div>
</div>
<div class="colorBox">
<div class="iconBox">
<label for="roofColor"><input type="radio" name="roofColor" value="silver">Zilver</label>
</div>
<div class="iconBox">
<label for="roofColor"><input type="radio" name="roofColor" value="black">Zwart</label>
</div>
</div>
</div>
<div id="flatModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Plat dak:</strong></h2>
<p>
Bij platte daken heeft u de keuze uit een Zuid opstelling waarbij u één enkel paneel plaats of een Oost West opstelling waarbij u twee panelen plaatst. Wij leveren de installatiematerialen voor platte daken in zwart en in het zilver.
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<div id="incModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Pannendak:</strong></h2>
<p>
Voor een pannendak hoeft u alleen aan te geven of in portret of landscape wilt plaatsen. Voor schuine daken worden installatiematerialen alleen in het zilver geleverd. (deze komen niet in het zicht).
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<style>
.iconBox{
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
padding-top: 8px;
}
.iconBox img{
width: 2.375em;
margin-bottom:0.313em;
}
.dirBox{
display: flex;
width:100%;
flex-direction: row;
justify-content: space-around;
align-items: center;
overflow: hidden;
max-height: 0;
-webkit-transition: max-height 0.2s ease-in-out;
-moz-transition: max-height 0.2s ease-in-out;
-ms-transition: max-height 0.2s ease-in-out;
-o-transition: max-height 0.2s ease-in-out;
transition: max-height 0.2s ease-in-out;
}
.colorBox{
display: flex;
width:100%;
flex-direction: row;
justify-content: space-around;
align-items: center;
overflow: hidden;
max-height: 0;
-webkit-transition: max-height 0.2s ease-in-out;
-moz-transition: max-height 0.2s ease-in-out;
-ms-transition: max-height 0.2s ease-in-out;
-o-transition: max-height 0.2s ease-in-out;
transition: max-height 0.2s ease-in-out;
}
.flatBox{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width:80%;
background-color: white;
margin: 0 auto;
}
.roofsBox{
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
</style>
<script>
var roofPrice = document.getElementById("roofPrice");
var roofButts = document.getElementsByName("roof");
var dirButts = document.getElementsByName("roofDir");
var colorButts = document.getElementsByName("roofColor");
var dirBox = document.getElementsByClassName("dirBox");
var colorBox = document.getElementsByClassName("colorBox");
var priceEv = new CustomEvent("price");
roofButts[0].addEventListener("click", function() {
dirBox[0].style.maxHeight = 2*dirBox[0].scrollHeight + "px";
localStorage.setItem('roof', 'Flat');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
if(price){
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
});
roofButts[1].addEventListener("click", function() {
dirButts[0].checked = false;
dirButts[1].checked = false;
colorButts[0].checked = false;
colorButts[1].checked = false;
dirBox[0].style.maxHeight = null;
colorBox[0].style.maxHeight = null;
localStorage.setItem('roof', 'Inclined');
localStorage.removeItem('roofDir');
localStorage.removeItem('roofColor');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
dirButts[0].addEventListener("click", function() {
if (this !== prev) {
prev = this;
}
colorBox[0].style.maxHeight = 2*colorBox[0].scrollHeight + "px";
localStorage.setItem('roofDir', 'South');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
if(price){
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
});
dirButts[1].addEventListener("click", function() {
var pQty = localStorage.getItem('panelQty')
if(pQty%2 == 0){
if (this !== prev) {
prev = this;
}
colorBox[0].style.maxHeight = 2*colorBox[0].scrollHeight + "px";
localStorage.setItem('roofDir', 'East-West');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
if(price){
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
} else {
alert("Must be an even number of panels to select this roof type");
if(prev){
prev.checked = true;
}
}
});
colorButts[0].addEventListener("click", function() {
localStorage.setItem('roofColor', 'Silver');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
colorButts[1].addEventListener("click", function() {
localStorage.setItem('roofColor', 'Black');
document.dispatchEvent(priceEv);
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
document.addEventListener("qty", function(){
var pQty = localStorage.getItem('panelQty')
var roof = localStorage.getItem('roof')
var roofDir = localStorage.getItem('roofDir')
if(pQty%2 != 0 && roof == 'Flat' && roofDir == 'East-West'){
prev = dirButts[0];
dirButts[0].checked = true;
dirButts[1].checked = false;
localStorage.setItem('roofDir', 'South');
document.dispatchEvent(priceEv);
}
var price = localStorage.getItem('roofPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
if(price){
roofPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
});
document.addEventListener("clear", function(){
roofButts[0].checked = false;
roofButts[1].checked = false;
colorButts[0].checked = false;
colorButts[1].checked = false;
dirButts[0].checked = false;
dirButts[1].checked = false;
});
</script><file_sep>/compositeHelper.php
<?php
/* Template Name:addToCart */
global $product;
$id = $product->get_id();
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
$i=0;
if($pCats[0][0] == "Good Packages"){
$panelMin = 18;
$solarMonoSKU = array(
"NLZ-Gsf-6",
"NLZ-Gsf-7",
"NLZ-Gsf-8",
"NLZ-Gsf-9",
"NLZ-Gsf-10",
"NLZ-Gsf-11",
"NLZ-Gsf-12",
"NLZ-Gsf-13",
"NLZ-Gsf-14",
"NLZ-Gsf-15",
"NLZ-Gsf-16",
"NLZ-Gsf-17",
"NLZ-Gsf-18",
"NLZ-Gsf-19",
"NLZ-Gsf-20",
"NLZ-Gsf-21"
);
$solarTriSKU = array(
"NLZ-Gdf-18",
"NLZ-Gdf-19",
"NLZ-Gdf-20",
"NLZ-Gdf-21",
"NLZ-Gdf-22",
"NLZ-Gdf-23",
"NLZ-Gdf-24",
"NLZ-Gdf-25",
);
$fullTriSKU = array (
"NLZ-inst-18-3",
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
} else if($pCats[0][0] == "Better Packages"){
$panelMin = 19;
$solarMonoSKU = array(
"NLZ-Bsf-6",
"NLZ-Bsf-7",
"NLZ-Bsf-8",
"NLZ-Bsf-9",
"NLZ-Bsf-10",
"NLZ-Bsf-11",
"NLZ-Bsf-12",
"NLZ-Bsf-13",
"NLZ-Bsf-14",
"NLZ-Bsf-15",
"NLZ-Bsf-16",
"NLZ-Bsf-17",
"NLZ-Bsf-18",
"NLZ-Bsf-19",
"NLZ-Bsf-20",
"NLZ-Bsf-21",
"NLZ-Bsf-22",
"NLZ-Bsf-23",
"NLZ-Bsf-24",
"NLZ-Bsf-25"
);
$solarTriSKU = array(
"NLZ-Bsf-19",
"NLZ-Bsf-20",
"NLZ-Bsf-21",
"NLZ-Bsf-22",
"NLZ-Bsf-23",
"NLZ-Bsf-24",
"NLZ-Bsf-25",
);
$fullTriSKU = array (
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
} else{ if($pCats[0][0] == "Best Packages")
$panelMin = 12;
$solarMonoSKU = array(
"NLZ-BTsf-6",
"NLZ-BTsf-7",
"NLZ-BTsf-8",
"NLZ-BTsf-9",
"NLZ-BTsf-10",
"NLZ-BTsf-11",
"NLZ-BTsf-12",
"NLZ-BTsf-13",
"NLZ-BTsf-14",
"NLZ-BTsf-15",
"NLZ-BTsf-16",
"NLZ-BTsf-17",
"NLZ-BTsf-18",
"NLZ-BTsf-19",
"NLZ-BTsf-20",
"NLZ-BTsf-21",
"NLZ-BTsf-22",
"NLZ-BTsf-23",
"NLZ-BTsf-24",
"NLZ-BTsf-25"
);
$solarTriSKU = array(
"NLZ-BTsf-12",
"NLZ-BTsf-13",
"NLZ-BTsf-14",
"NLZ-BTsf-15",
"NLZ-BTsf-16",
"NLZ-BTsf-17",
"NLZ-BTsf-18",
"NLZ-BTsf-19",
"NLZ-BTsf-20",
"NLZ-BTsf-21",
"NLZ-BTsf-22",
"NLZ-BTsf-23",
"NLZ-BTsf-24",
"NLZ-BTsf-25"
);
$fullTriSKU = array (
"NLZ-inst-12-3",
"NLZ-inst-13-3",
"NLZ-inst-14-3",
"NLZ-inst-15-3",
"NLZ-inst-16-3",
"NLZ-inst-17-3",
"NLZ-inst-18-3",
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
}
$i=0;
foreach ($solarMonoSKU as $sku ) {
$solarMonoIds[] = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $solarMonoIds[i] );
// $solarMonoPrices[] = $prod->get_price();
$i += 1;
}
$i=0;
foreach ($solarTriSKU as $sku ) {
$solarTriIds[] = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $solarTriIds[i] );
// $solarTriPrices[] = $prod->get_price();
$i += 1;
}
$flatSSSKU = array (
"NLZ-fff-ez-6",
"NLZ-fff-ez-7",
"NLZ-fff-ez-8",
"NLZ-fff-ez-9",
"NLZ-fff-ez-10",
"NLZ-fff-ez-11",
"NLZ-fff-ez-12",
"NLZ-fff-ez-13",
"NLZ-fff-ez-14",
"NLZ-fff-ez-15",
"NLZ-fff-ez-16",
"NLZ-fff-ez-17",
"NLZ-fff-ez-18",
"NLZ-fff-ez-19",
"NLZ-fff-ez-20",
"NLZ-fff-ez-21",
"NLZ-fff-ez-22",
"NLZ-fff-ez-23",
"NLZ-fff-ez-24",
"NLZ-fff-ez-25"
);
$flatEWBKU = array (
"NLZ-fff-owzw-6",
"NLZ-fff-owzw-8",
"NLZ-fff-owzw-10",
"NLZ-fff-owzw-12",
"NLZ-fff-owzw-14",
"NLZ-fff-owzw-16",
"NLZ-fff-owzw-18",
"NLZ-fff-owzw-20",
"NLZ-fff-owzw-22",
"NLZ-fff-owzw-24"
);
$flatSBSKU = array (
"NLZ-fff-ezw-6",
"NLZ-fff-ezw-7",
"NLZ-fff-ezw-8",
"NLZ-fff-ezw-9",
"NLZ-fff-ezw-10",
"NLZ-fff-ezw-11",
"NLZ-fff-ezw-12",
"NLZ-fff-ezw-13",
"NLZ-fff-ezw-14",
"NLZ-fff-ezw-15",
"NLZ-fff-ezw-16",
"NLZ-fff-ezw-17",
"NLZ-fff-ezw-18",
"NLZ-fff-ezw-19",
"NLZ-fff-ezw-20",
"NLZ-fff-ezw-21",
"NLZ-fff-ezw-22",
"NLZ-fff-ezw-23",
"NLZ-fff-ezw-24",
"NLZ-fff-ezw-25"
);
$flatEWSSKU = array (
"NLZ-fff-owz-6",
"NLZ-fff-owz-8",
"NLZ-fff-owz-10",
"NLZ-fff-owz-12",
"NLZ-fff-owz-14",
"NLZ-fff-owz-16",
"NLZ-fff-owz-18",
"NLZ-fff-owz-20",
"NLZ-fff-owz-22",
"NLZ-fff-owz-24"
);
$inclinedSKU = array (
"NLZ-evo-6",
"NLZ-evo-7",
"NLZ-evo-8",
"NLZ-evo-9",
"NLZ-evo-10",
"NLZ-evo-11",
"NLZ-evo-12",
"NLZ-evo-13",
"NLZ-evo-14",
"NLZ-evo-15",
"NLZ-evo-16",
"NLZ-evo-17",
"NLZ-evo-18",
"NLZ-evo-19",
"NLZ-evo-20",
"NLZ-evo-21",
"NLZ-evo-22",
"NLZ-evo-23",
"NLZ-evo-24",
"NLZ-evo-25",
);
$ownSKU = array (
"NLZ-ktmc1",
"NLZ-ktmc2",
"NLZ-ktmc3",
"NLZ-ktmc4",
"NLZ-ktmc5",
"NLZ-ktmc6",
"NLZ-ktmc7",
"NLZ-ktmc8",
"NLZ-ktmc9",
"NLZ-ktmc10",
"NLZ-ktmc11",
"NLZ-ktmc12",
"NLZ-ktmc13",
"NLZ-ktmc14",
"NLZ-ktmc15",
"NLZ-ktmc16",
"NLZ-ktmc17",
"NLZ-ktmc18",
"NLZ-ktmc19",
"NLZ-ktmc20",
"NLZ-ktmc21",
"NLZ-ktmc22",
"NLZ-ktmc23",
"NLZ-ktmc24",
"NLZ-ktmc25"
);
$electricianSKU= "NLZ-elkt-10";
$fullMonoSKU = array (
"NLZ-inst-6",
"NLZ-inst-7",
"NLZ-inst-8",
"NLZ-inst-9",
"NLZ-inst-10",
"NLZ-inst-11",
"NLZ-inst-12",
"NLZ-inst-13",
"NLZ-inst-14",
"NLZ-inst-15",
"NLZ-inst-16",
"NLZ-inst-17",
"NLZ-inst-18",
"NLZ-inst-19",
"NLZ-inst-20",
"NLZ-inst-21",
"NLZ-inst-22",
"NLZ-inst-23",
"NLZ-inst-24",
"NLZ-inst-25"
);
$fullTriSKU = array (
"NLZ-inst-18-3",
"NLZ-inst-19-3",
"NLZ-inst-20-3",
"NLZ-inst-21-3",
"NLZ-inst-22-3",
"NLZ-inst-23-3",
"NLZ-inst-24-3",
"NLZ-inst-25-3"
);
function getData($energy, $roof, $roofDir, $roofColor, $installation, $qty) {
if($energy == "Mono"){
$sku = $solarMonoSKU[$qty-6];
} else if($energy == "Tri"){
$sku = $solarMonoSKU[$qty-$panelMin];
} else {
$sku = $solarMonoSKU[$qty-$panelMin];
}
$solarId = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $solarId );
$solarPrice = $prod->get_price();
if($roof == "Flat"){
if($roofDir == "South"){
if($roofColor == "Silver"){
$sku = $flatSSSKU[$qty-6];
} else if ($roofColor == "Black"){
$sku = $flatSBSKU[($qty-6)/2];
}
} else if ($roofDir == "East-West"){
if($roofColor == "Silver"){
$sku = $flatEWSSKU[$qty-6];
} else if ($roofColor == "Black"){
$sku = $flatEWBSKU[($qty-6)/2];
}
}
} else if ($roof == "Inclined"){
$sku = $inclinedSKU
}
$roofId = wc_get_product_id_by_sku($sku);
$prod = wc_get_product( $roofId );
$roofPrice = $prod->get_price();
if($install == "Own"){
$installId1 = wc_get_product_id_by_sku($ownSKU[$qty-6]);
$prod = wc_get_product( $installId1 );
$installPrice1 = $prod->get_price();
} else if ($install == "Full Install"){
if($energy == "Mono"){
$installId1 = wc_get_product_id_by_sku($fullMonoSKU[$qty-6]);
$prod = wc_get_product( $installId1 );
$installPrice1 = $prod->get_price();
}else if ($energy == "Tri"){
$installId1 = wc_get_product_id_by_sku($fullTriSKU[$qty-$panelMin]);
$prod = wc_get_product( $installId1 );
$installPrice1 = $prod->get_price();
}
}
if ($install == "Electrician"){
$installId2 = wc_get_product_id_by_sku($ownSKU[$qty-6]);
$prod2 = wc_get_product( $installId2 );
$installPrice2 = $prod2->get_price();
}
$data = array(
'solarPrice' => $solarPrice,
'roofPrice' => $roofPrice,
'installId1' =>$installId1,
'installId2' => $installId2,
'installPrice1' => $installPrice1,
'installPrice2' => $installPrice1,
'roofId' => $roofId,
'solarId' => $solarId
)
}<file_sep>/showDocuments.php
<?php
/* Template Name:showDocuments */
global $product;
$att = $product->get_attribute('documentatie');
$docs = explode (".pdf", $att);
?>
<ul id="docsList" class="myDocs">
<?php foreach ($docs as $doc) { ?>
<?php $pdfDoc = $doc.".pdf" ?>
<li class="myDoc">
<a href=<?php echo $pdfDoc; ?> class="myDocName">
<?php
$url = basename($doc);
echo str_replace('%20', ' ', $url);
?>
</a>
</li>
<?php } ?>
</ul>
<style>
.myDoc{
margin-left: 0 !important;
margin-bottom: 4px;
margin-top: 4px;
padding: 0;
}
.myDocs{
overflow: hidden;
list-style-type: none;
-webkit-transition: max-height 0.2s ease-in-out;
-moz-transition: max-height 0.2s ease-in-out;
-ms-transition: max-height 0.2s ease-in-out;
-o-transition: max-height 0.2s ease-in-out;
transition: max-height 0.2s ease-in-out;
}
</style><file_sep>/energyButts.php
<?php
/* Template Name:energyButts */
global $product;
preg_match_all('~>\K[^<>]*(?=<)~', $product->get_categories(), $pCats);
?>
<h4 style="color:#ff6600;">Elektra Aansluiting: <span style="font-size: 16px; color:black;" id="energyPrice"></span></h4>
<div class="buttsBox">
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/05_single_fase_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="energy"><input type="radio" name="energy" value="mono">1-fase <a href="#monoModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/04_drie_fase_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="energy"><input type="radio" name="energy" value="tri">3-fase <a href="#triModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
<div class="iconBox">
<?php
$home = get_home_url();
$src = $home."/wp-content/uploads/icons/99_onbekend_zwart.svg";
?>
<img src="<?php echo $src; ?>" alt="">
<label for="energy"><input type="radio" name="energy" value="other">Onbekend <a href="#otherModal" uk-toggle><i class="fas fa-question-circle"></i></a></label>
</div>
</div>
<div id="monoModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>1 fase:</strong></h2>
<p>
Veel huizen zijn via een 1-fase-aansluiting aangesloten op het elektriciteitsnet. Bij een 1-fase-aansluiting komt een elektriciteitskabel uw huis binnen. In die kabel zitten twee draden: de fasedraad en de nuldraad. De spanning op uw stopcontacten is het verschil tussen die ene fasedraad en de nuldraad. Als u een 1-fase groepenkast in uw meterkast heeft staat er 220/230V op uw elektriciteitsmeter. De 1-fase-aansluiting is op de factuur van de energieleverancier te herkennen als 1x25/1x30A.
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<div id="triModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>3 fase:</strong></h2>
<p>
Bij een 3-fase aansluiting komen drie fasedraden van ieder 230 V uw meterkast binnen. En de nuldraad. De 3-fase aansluitingen zijn grotere aansluitingen dan de 1-fase-aansluitingen. Ze leveren een groter vermogen. Als u een 3-fasen groepenkast in uw meterkast heeft, staat er 3x220/230V of 380/400V op uw elektriciteitsmeter. Er komen in totaal ook vier draden - de drie fasedraden en de nuldraad - uit de onderkant van uw groepenkast. De standaard huisaansluiting is de 3x25A-aansluiting.
</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<div id="otherModal" uk-modal>
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title"><strong>Onbekend.</strong></h2>
<p>U kunt op uw energierekening vinden of u een 1-fase of een 3-fase aansluiting heeft. Wanneer u zekerheid wilt, neem dan contact op met uw netwerkbeheerder</p>
<button class="button primary is-outline uk-modal-close" type="button">Close</button>
</div>
</div>
<style>
.buttsBox{
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}
.iconBox{
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-end;
}
.iconBox img{
width: 2.375em;
margin-bottom:0.313em;
}
</style>
<script>
var energyPrice = document.getElementById("energyPrice");
var energyButts = document.getElementsByName("energy");
var pTag = <?php echo "\"".$pCats[0][0]."\""; ?>;
var panelMin;
var priceEv = new CustomEvent("price");
var qty = new CustomEvent("qty");
var prev = null;
if(pTag == "Goed Pakket"){
panelMin = 18;
} else if (pTag == "Beter Pakket") {
panelMin = 19;
} else if (pTag == "Beste Pakket"){
panelMin = 12;
}
energyButts[0].addEventListener("change", function() {
localStorage.setItem('energy', 'Mono');
if (this !== prev) {
prev = this;
}
document.dispatchEvent(priceEv);
document.dispatchEvent(qty);
var price = localStorage.getItem('solarPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
energyPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
energyButts[1].addEventListener("change", function() {
var panelQty = localStorage.getItem('panelQty');
if (panelQty >= panelMin ) {
localStorage.setItem('energy', 'Tri');
if (this !== prev) {
prev = this;
}
document.dispatchEvent(priceEv);
document.dispatchEvent(qty);
var price = localStorage.getItem('solarPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
energyPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
} else{
alert('Option available for ' + panelMin + ' or more panels');
this.checked = false;
if(prev){
prev.checked = true;
energyButts[0].checked = true;
energyButts[1].checked = false;
energyButts[2].checked = false;
localStorage.setItem('energy', 'Mono');
document.dispatchEvent(priceEv);
document.dispatchEvent(qty);
var price = localStorage.getItem('solarPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
energyPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
}
});
energyButts[2].addEventListener("change", function() {
localStorage.setItem('energy', 'Dontknow');
if (this !== prev) {
prev = this;
}
document.dispatchEvent(priceEv);
document.dispatchEvent(qty);
var price = localStorage.getItem('solarPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
energyPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
});
document.addEventListener("qty", function() {
var panelQty = localStorage.getItem('panelQty');
var energy = localStorage.getItem('energy');
if (panelMin > panelQty && energy == "Tri") {
energyButts[0].checked = true;
energyButts[1].checked = false;
energyButts[2].checked = false;
prev = energyButts[0];
localStorage.setItem('energy', 'Mono');
document.dispatchEvent(priceEv);
}
var price = localStorage.getItem('solarPrice');
var tax = price*1.21;
tax = tax.toFixed(2);
if(price != null){
energyPrice.textContent = "€ " + price + " exc. BTW / € " + tax + " inc. BTW";
}
});
document.addEventListener("clear", function(){
energyButts[0].checked = false;
energyButts[1].checked = false;
energyButts[2].checked = false;
});
</script><file_sep>/toCart.php
<?php
$cKey = "<KEY>";
$cSecret = "<KEY>";
add_action( 'wp_ajax_nopriv_myCustomCart', 'myCart' );
add_action( 'wp_ajax_myCustomCart', 'myCart' );
function myCart(){
/*
$nonce = $_REQUEST['nonce'];
if ( !wp_verify_nonce( $nonce, "myCustomCartNonce")) {
die("Get out, mf!");
} */
if (isset($_REQUEST["pQty"])){
if( isset($_REQUEST["ids"])){
$pQty = $_REQUEST["pQty"];
$idsString = $_REQUEST["ids"];
$ids = explode (", ", $idsString);
WC()->cart->empty_cart();
/*foreach ($ids as $index => $id) {
if($index == 0){
$prod = wc_get_product( $id );
$components = $prod->get_components();
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$product = wc_get_product( $data['default_id'] );
$cat = strip_tags($product->get_categories());
if($cat == "Panels"){
WC()->cart->add_to_cart( $data['default_id'], $pQty );
} else{
WC()->cart->add_to_cart( $data['default_id'], 1 );
}
}
} else{
WC()->cart->add_to_cart( $id, 1 );
}
}*/
foreach ($ids as $index => $id) {
if($index == 0){
$composite = wc_get_product( $id );
$components = $composite->get_components();
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$product = wc_get_product( $data['default_id'] );
$cats = strip_tags($product->get_categories());
$cats = explode (", ", $cats);
foreach ($cats as $cat ){
if($cat == "Panelen"){
$isPanel = true;
break;
} else {
$isPanel = false;
}
}
if($isPanel){
$configuration[$component_id] = array(
'product_id' => $data['default_id'],
'quantity' => $pQty
);
} else {
$configuration[$component_id] = array(
'product_id' => $data['default_id'],
'quantity' => 1
);
}
}
$added_to_cart = WC_CP()->cart->add_composite_to_cart( $id, 1, $configuration, $cart_item_data = array() );
} else{
$added_to_cart = WC()->cart->add_to_cart( $id, 1 );
}
}
/* foreach ($ids as $index => $id) {
if($index == 0){
$composite = wc_get_product( $id );
$components = $composite->get_components();
foreach ($components as $component_id => $component ) {
$data = $component->get_data();
$product = wc_get_product( $data['default_id'] );
$cat = strip_tags($product->get_categories());
if($cat == "Panels"){
$configuration[$component_id] = array(
'product_id' => $data['default_id'],
'quantity' => $pQty
);
} else {
$configuration[$component_id] = array(
'product_id' => $data['default_id'],
'quantity' => 1
);
}
}
} else{
$configuration[$id] = array(
'product_id' => $id,
'quantity' => 1
);
}
$added_to_cart = WC_CP()->cart->add_composite_to_cart( $id, 1, $configuration, $cart_item_data = array() );
} */
}
}
wp_redirect( wc_get_cart_url() );
wp_die();
}
|
df08a6a0f790e58f832276383f5028478d77323f
|
[
"PHP"
] | 15
|
PHP
|
AngeloACR/panelchild
|
0cc00c90016c1662ce4d60c9de48bbd8fb8afb93
|
de3b0e4e7883861bcaf967f98ed020ddd4fa8cb2
|
refs/heads/master
|
<file_sep>angular.module('MyApp')
.controller('DetailCtrl', ['$scope', '$rootScope', '$routeParams', 'Job', 'Candidature',
function($scope, $rootScope, $routeParams, Job, Candidature) {
Job.get({ _id: $routeParams.id }, function(job) {
$scope.job = job;
$scope.isCandidate = function() {
console.log("IS CANDIDATE")
return $scope.job.candidates.indexOf($rootScope.currentUser._id) !== -1;
};
$scope.takeJob = function() {
console.log("TAKE JOB")
Candidature.takeJob(job).success(function() {
$scope.job.candidates.push($rootScope.currentUser._id);
});
};
$scope.discardJob = function() {
Candidature.discardJob(job).success(function() {
var index = $scope.job.candidates.indexOf($rootScope.currentUser._id);
$scope.job.candidates.splice(index, 1);
});
};
});
}]);<file_sep>angular.module('MyApp')
.factory('Candidature', ['$http', function($http) {
return {
takeJob: function(job, user) {
return $http.post('/api/takeJob', { jobId: job._id });
},
discardJob: function(job, user) {
return $http.post('/api/discardJob', { jobId: job._id });
}
};
}]);<file_sep># cvtracker
Curriculum Vitae Tracker
<file_sep>var express = require('express');
var router = express.Router();
var xml2js = require('xml2js');
var async = require('async');
var request = require('request');
var _ = require('lodash');
var Job = require('../models/job');
router.route('/jobs')
.get(function(req, res, next) {
var query = Job.find();
if (req.query.technology) {
query.where({ technology: req.query.technology });
} else if (req.query.alphabet) {
query.where({ category: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
} else {
query.limit(12);
}
query.exec(function(err, jobs) {
if (err) return next(err);
res.send(jobs);
})
})
.post(function(req, res, next) {
var job = new Job({
category: req.body.category,
enterprise: req.body.enterprise,
technology: req.body.technology,
description: req.body.description
});
job.save(function(err) {
if (err) return next(err);
res.send(200);
});
});
router.route('/jobs/:id')
.get(function(req, res, next) {
Job.findById(req.params.id, function(err, job) {
if (err) return next(err);
res.send(job);
});
});
module.exports = router;<file_sep>function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) next();
else res.send(401);
}
module.exports.ensureAuthenticated = ensureAuthenticated<file_sep>angular.module('MyApp')
.factory('Job', ['$resource', function($resource) {
var Job = $resource('/api/jobs/:_id');
Job.alltechnologies = function(){
return ['Java', 'Smallworld'];
}
return Job;
}]);<file_sep>var express=require('express');
var router=express.Router();
var passport = require('passport');
router.route('/login')
.post(passport.authenticate('local'), function(req, res) {
res.cookie('user', JSON.stringify(req.user));
res.send(req.user);
});
router.route('/logout')
.get(function(req, res, next) {
req.logout();
res.send(200);
});
module.exports = router;
<file_sep>angular.module('MyApp')
.controller('AddCtrl', ['$scope', '$alert', 'Job', function($scope, $alert, Job) {
$scope.technologies = Job.alltechnologies();
$scope.addJob = function() {
Job.save({
category: $scope.category,
enterprise: $scope.enterprise,
technology: $scope.technology,
description: $scope.description
},
function() {
$scope.jobCategory = '';
$scope.addForm.$setPristine();
$alert({
content: 'Job has been added.',
placement: 'top-right',
type: 'success',
duration: 3
});
},
function(response) {
$scope.jobCategory = '';
$scope.addForm.$setPristine();
$alert({
content: response.data.message,
placement: 'top-right',
type: 'danger',
duration: 3
});
});
};
}]);
|
8db1bec32bc4d062ef74d574feeb631abf604b68
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
jpgpuyo/cvtracker
|
c948aa9f98826877ace37ca5114323d15dc1e5d0
|
71a45688b945f4e67874471da8500799c178fcf4
|
refs/heads/master
|
<repo_name>kiddikn/simulation-physics<file_sep>/week4/Gauss.java
public class Gauss{
public static void main(String[] args){
int T = 2000;
calgauss gauss1 = new calgauss(2); //オブジェクトの作成、初期化
gauss1.setMargin(1,3,22.5);
gauss1.setMargin(2,3,36);
gauss1.setMargin(3,1,-4.5);
gauss1.setMargin(3,2,9);
for(int i = 0;i < T;i++)
gauss1.calculate(1.0,1);
gauss1.printMatrix();
}
}
class calgauss{
private double[][] phi;
private int ix,iy;
private double p1,p2,rou;
calgauss(int N){ //Nは計算したい行列の値
phi = new double[N+2][N+2];
for (int k = 0; k < N+2; k++)
for (int j = 0; j < N+2; j++) phi[k][j] = 0;
}
public void setMargin(int x,int y,double val){
phi[x][y] = val;
}
public void calculate(double G,int dx){
for(ix = 1;ix <= phi.length-2;ix++)
for(iy = 1;iy <= phi.length-2;iy++){
p1 = phi[ix+1][iy]+phi[ix-1][iy]+phi[ix][iy+1]+phi[ix][iy-1];
rou = 6 * ix - 3 * iy;
p2 = G * rou * dx * dx;
phi[ix][iy] = (p1 - p2)/4;
}
}
public void printMatrix(){
for(int i = phi.length - 2;i >= 1;i--){
for(int j = 1;j < phi.length - 1;j++)
System.out.printf("%7f " ,phi[j][i]);
System.out.println();
}
}
}
<file_sep>/week4/ex7.c
//-1から1の範囲で半径1の円内にある点の集合200組
#include<stdio.h>
#include<stdlib.h>
#define N 500
void makefile(double x0[],double y0[],double x[],double y[]){
FILE *fo;
char *fname;
fname="data.csv";
if((fo=fopen(fname,"w")) == NULL){
printf("File[%s] does not open!!\n",fname);
exit(0);
}
int i;
for(i=0;i<N;i++)
fprintf(fo,"%f,%f,%f,%f\n",x0[i],y0[i],x[i],y[i]);
fclose(fo);
}
void makestar(double x0[],double y0[]){
int count,n,i; //countが200になるまで
double x,y;
n = 1000; //countが200になるように
count = 0;
srand(193); //設定
for(i=0;i<=n;i++) {
if(count < N){
/*-1以上1以下の乱数を生成*/
x = (2.0*rand()/(double)RAND_MAX)-1.0; //castしておく必要あり
y = (2.0*rand()/(double)RAND_MAX)-1.0;
/*-1<=x,y<=1の範囲にある中心原点半径1の
扇形の中に乱数による点が入ったらカウントする*/
if((x*x+y*y)<=1.0) {
x0[count]=x;
y0[count]=y;
count++;
}
if(i==n) printf("we cannot have suitable data\n");
}else{break;}
}
}
void simulate(double x0[],double y0[],double H,int org,double dt,int nk){
double vx[N],vy[N];
int i,t;
for(i = 0;i < N;i++){
vx[i] = H * x0[i],vy[i] = H * y0[i]; //初速度を設定
x0[i] += org,y0[i] += org; //全天体の位置を第一象限へ
}
for(t = 0;t <= nk;t++)
for(i = 0;i < N;i++)
x0[i] += vx[i]*dt,y0[i] += vy[i]*dt;
}
int main(){
double x0[N],y0[N];
double x[N],y[N];
makestar(x0,y0);
int i;
for(i = 0;i < N;i++)
x[i]=x0[i],y[i]=y0[i];
simulate(x,y,3.5,50,0.1,20);
makefile(x0,y0,x,y);
return 0;
}
<file_sep>/week4/ex9.c
#include<stdio.h>
#include<stdlib.h>
#define N 2 //表示する行列の大きさ
#define T 2000 //ガウスザイデル法反復回数
double ro(double x,double y){
return (6*x-3*y);
}
void gauss(double a[][N+2],double G,int dx){
int ix,iy;
double p1,p2,rou;
for(ix = 1;ix <= N;ix++)
for(iy = 1;iy <= N;iy++){
p1 = a[ix+1][iy]+a[ix-1][iy]+a[ix][iy+1]+a[ix][iy-1];
rou = ro(ix,iy);
p2 = G * rou * dx * dx;
a[ix][iy] = (p1 - p2)/4;
}
}
void init(double a[][N+2]){
int i,j;
for(i = 0;i <= N+1;i++)
for(j = 0;j <= N+1;j++)
a[i][j]=0.0;
}
void disp(double a[][N+2]){
int i,j;
for(i = N;i >= 1;i--){
for(j = 1;j <= N;j++)
printf(" %13f",a[j][i]);
printf("\n");
}
}
int main(){
double phi[N+2][N+2];
int t;
init(phi);
phi[1][3]=22.5;
phi[2][3]=36;
phi[3][1]=-4.5;
phi[3][2]=9;
for(t = 0;t < T;t++)
gauss(phi,1.0,1);
disp(phi);
return 0;
}
|
c9f3e1893464bc3ab88e1f41d41862f52eefcd0a
|
[
"Java",
"C"
] | 3
|
Java
|
kiddikn/simulation-physics
|
fc0b8a3c8c164df52e92a7a913ccb53d6b8af1f8
|
531c3a23c6b9189b3927890d2a5e7e20d3850957
|
refs/heads/master
|
<file_sep>using AuthenticationDemo.CustomAuthentication;
using AuthenticationDemo.DataAccess;
using AuthenticationDemo.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace AuthenticationDemo.Controllers
{
[AllowAnonymous]
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Login(string ReturnURL = "")
{
if (User.Identity.IsAuthenticated)
return LogOut();
ViewBag.ReturnURL = ReturnURL;
return View();
}
[HttpPost]
public ActionResult Login(LoginView loginView, string ReturnURL = "")
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(loginView.UserName, loginView.Password))
{
var user = (CustomMemberShipUser)Membership.GetUser(loginView.UserName, false);
if (user != null)
{
CustomSerializeModel userModel = new CustomSerializeModel()
{
FirstName = user.FirstName,
LastName = user.FirstName,
UserId = user.UserId,
RoleName = user.Roles.Select(r => r.RoleName).ToList()
};
var userData = JsonConvert.SerializeObject(userModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, loginView.UserName, DateTime.Now, DateTime.Now, false, userData);
string authToken = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie("Cookie1", authToken);
Response.Cookies.Add(cookie);
}
if (Url.IsLocalUrl(ReturnURL))
{
return Redirect(ReturnURL);
}
else
{
return RedirectToAction("Index");
}
}
}
ModelState.AddModelError("", "Somethingwrong: username or password invalid....");
return View(loginView);
}
[HttpGet]
public ActionResult Registration()
{
return View();
}
public ActionResult Registration(RegistrationView registerationView)
{
string messageRegistration = string.Empty;
bool statusRegistration = false;
if (ModelState.IsValid)
{
string userName = Membership.GetUserNameByEmail(registerationView.Email);
if (!string.IsNullOrEmpty(userName))
{
ModelState.AddModelError("Validation", "User with this emailID already exists.");
return View(registerationView);
}
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var user = new User()
{
Username = registerationView.Username,
FirstName = registerationView.FirstName,
LastName = registerationView.LastName,
Email = registerationView.Email,
Password = <PASSWORD>,
ActivationCode = Guid.NewGuid()
};
dbContext.Users.Add(user);
dbContext.SaveChanges();
}
// VerificationMail
VerificationEmail(registerationView.Email, registerationView.ActivationCode.ToString());
messageRegistration = "Your account has been created successfully. ^_^";
statusRegistration = true;
}
else
{
messageRegistration = "Some thing wrong.";
}
ModelState.AddModelError("", "Somethingwrong: username or password invalid....");
return View(registerationView);
}
[NonAction]
private void VerificationEmail(string email, string activationCode)
{
string url = string.Format("/Account/ActivationAccount/{0}", activationCode);
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, url);
var fromEmail = new MailAddress("<EMAIL>", "Activation Code");
var toEmail = new MailAddress(email);
var fromEmailPassword = "<PASSWORD>";
var subject = "Activation Account";
string body = "<br/> Please click on the following link in order to activate your account" + "<br/><a href='" + link + "'> Activation Account ! </a>";
var smtp = new SmtpClient()
{
Host = "smtp.gmail.com",
EnableSsl = true,
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
public ActionResult LogOut()
{
HttpCookie cookie = new HttpCookie("Cookie1", "");
cookie.Expires = DateTime.Now.AddDays(-1);
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account", null);
}
}
}<file_sep>using AuthenticationDemo.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace AuthenticationDemo.CustomAuthentication
{
public class CustomRole : RoleProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
var userRoles = new string[] { };
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
using (AuthenticationDB context = new AuthenticationDB())
{
var selectedUser = (from u in context.Users.Include("Roles")
where string.Compare(u.Username, username) == 0
select u).FirstOrDefault();
if (selectedUser == null)
return null;
userRoles = new[] { selectedUser.Roles.Select(a => a.RoleName).ToString() };
return userRoles.ToArray();
}
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var userRole = this.GetRolesForUser(username);
return userRole.Contains(roleName);
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}<file_sep># MVCAuthentication
Membership Provider, Role Provider
|
7e0e90fe93d64a0ff4f3e34190c86de1753e356d
|
[
"Markdown",
"C#"
] | 3
|
C#
|
payal-sharma-1606/MVCAuthentication
|
9d6b165212ce00e66e4ffa30712deadd2f35a6e1
|
f94ed96efb95319ccd8720874f84e53bf46b0896
|
refs/heads/master
|
<file_sep>#ifndef logger_h
#define logger_h
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <strings.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
/**
* Farben
*/
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
void setLogLevel(int loglevel);
/**
* Anfang wo alles hineinfällt
* \param[in] c farbe für konsole
*
* \param[in] t typ des inputs
* \parblock
* e : error(-..) /
* s : sonstiges /
* p : nachrichten des prologs
* t : testoutput : funtioniert wie p
* q: perror
* \endparblock
* bei loglevel außerhalb des definierten wird beides gemacht
* @todo 4: fehler/alles ins log
* rest in console
*
*/
void logPrnt (char c, char t, char* input);
void initLog();
char* getTimeAsString (char p);
void prntColor(char color, char isError, char* input );
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
char str[30];
char *ptr;
long inputNum;
int guesses = 0;
int toGuess;
int cont = 1;
srand(time(NULL));
toGuess = rand() % 100;
printf("=======================\n");
printf("Auf geht's!\n");
while(cont){
scanf("%s", str);
if (strcmp(str,"quit") == 0){
exit(0);
}
inputNum = strtol(str, &ptr, 10);
if(inputNum == toGuess){
printf("great success!!\n");
printf("Versuche: %i\n", guesses);
printf("noch eine Runde? (j/n)\n");
scanf("%s", str);
if (strcmp(str, "n") == 0){
cont = 0;
}else{
guesses = 0;
toGuess = rand() % 100;
printf("Neue Runde, neues Glück!\n");
}
}else if( inputNum < toGuess ){
printf("Zu erratende Zahl ist größer.\n");
guesses++;
}else{
printf("Zu erratende Zahl ist kleiner.\n");
guesses++;
}
}
return(0);
}<file_sep>CFLAGS = -g -Wall -std=c99
CC = gcc
all: zahlenraten
zahlenraten: zahlenraten.c
$(CC) $(CFLAGS) -o zahlenraten zahlenraten.c
clean:
rm –f *.o zahlenraten<file_sep>#include "client_server.h"
int create_socket()
{
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
printf("Could not create socket");
exit(1);
}
printf("socket created...\n");
return fd;
}
void bind_socket(int sock, struct sockaddr_in serv_addr)
{
int n;
n = bind(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (n < 0)
{
printf("ERROR on binding");
exit(1);
}
printf("socket bound...\n");
}
void get_message(int sock, char* msg)
{
int n;
n = read(sock, msg, MSGL);
if (n < 0)
{
printf("ERROR reading from socket");
exit(1);
}
}
void send_message(int sock, char* msg)
{
int n;
n = write(sock, msg, MSGL);
if (n < 0)
{
printf("ERROR writing to socket");
exit(1);
}
}
int accept_connection(int sock, struct sockaddr_in cli_addr)
{
int fd;
socklen_t cli_addr_len = sizeof(cli_addr);
fd = accept(sock, (struct sockaddr *)&cli_addr, &cli_addr_len);
if (fd < 0)
{
printf("ERROR on accept");
exit(1);
}
printf("connection accepted...\n");
return fd;
}
void connect_to_socket(int sock, struct sockaddr_in dest)
{
int n;
n = connect(sock , (struct sockaddr *)&dest , sizeof(dest));
if (n < 0)
{
printf("connect failed. Error");
exit(1);
}
printf("connected to socket...\n");
}<file_sep>// Created by <NAME>. on 12.11.14.
#include "./logger.h"
int loglevel = 1; // wird mit setLogLevel nun gesetzt.
// nicht aktuell@todo aus struct von config datei auslesen
// loglevel = conf.loglevel; // ""
// ll = 0 : alles auf console, keine logdatei // evtl sinnvoller/logischer wenn dann kein loglevel
// ll = 1 : alles auf console, log v. allem in logdatei
// ll = 2 : error in konsole, log v. allem in logdatei
// ll = 3 : console nur nach prolog, alles in logfile
void setLogLevel(int loglvl){
loglevel = loglvl;
}
// FILE *logfile = fopen("./logfile.txt", "r");n //fehler, geht nur in main oder sonst fct.
/**
* returnt die aktuelle Zeit als string
* @parblock
* @param p
* s für short Bsp: 14-11-13+03:02:11
* l für längeres Bsp: Wed Nov 12 22:18:23 2014\n
* o für Bsp
* n für kA Bsp: @todo
* m für short w/ ms Bsp: 14-11-13+03:02:11:124 //! @todo ms funkioniert noch nicht richtig
* d
* ? nur Uhrzeit Bsp: 03:02:11
* @endparblock
*/
// malloc sizeof(char) // brauch ich doch nicht??
char* getTimeAsString (char p){
// time_t iTime = time(NULL);
// char* pTime = ctime(iTime);
struct tm *timeinfo; //pointer auf time-struct
time_t rawtime;
//char* timeString; // pointer auf strng der returnt wird
static char timeString[100];
time ( &rawtime );
timeinfo = localtime ( &rawtime );
if (p == 'l'){
strcpy (timeString, asctime(timeinfo));
}else if(p == 's'){
strftime (timeString,100,"%y-%m-%d+%H:%M:%S",timeinfo);
// printf ( "Current local time and date: %s", asctime (timeinfo) );
}else if(p == 'n'){
strftime (timeString,100," ",timeinfo);
}else if(p == 'o'){
strftime (timeString,100,"%F - %T",timeinfo);
}else if(p == 'd'){
strftime (timeString,100,"%c",timeinfo);
}else if(p == 't'){
strftime (timeString,100,"%T",timeinfo);
}else if(p == 'm'){
char clockStr[3];
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);
sprintf(clockStr, "%lu", uptime);
strftime (timeString,100,"%y-%m-%d+%H:%M:%S:",timeinfo);
strcat(timeString, clockStr);
for (int i = 0; i < 800; i++) {
printf("%s",timeString);
usleep(250);
}
printf("%lu",uptime);
}
return timeString;
}
/**
* Schreibt in das Logfile
* hängt den string mit zeit an das logfile an
*/
void writeLog(char* input){
FILE *logfile = fopen("./logfile.txt", "a");
//fputs("test: schreibe in das ins logfile mit fputs\n", logfile);
//fprintf(logfile, "test: schreibe in das ins logfile mit fprintf %s\n", getTimeAsString('s'));
fprintf(logfile, "%s %s\n", getTimeAsString('t'), input);
fclose(logfile);
}
/**
* initialisiert neuen abschnitt im logfile
*/
void initLogSession(){
FILE *logfile = fopen("./logfile.txt", "a");
fprintf(logfile,"---------------------- %s ----------------------\n\n", getTimeAsString('o') );
fclose(logfile);
}
void createLog(){
FILE *logfile = fopen("./logfile.txt", "w");
fprintf(logfile,"## Logdatei für NMM, erstellt am %s\n", getTimeAsString('l'));
printf (GREEN "\nLogfile erstellt! \n" RESET); //@todo remove
fclose(logfile);
}
/**
* prüft ob logfile vorhanden, wenn nicht wird ein neues erstellt
*
*/
void initLog() {
// printf ("hier in initLog() \n"); //@todo remove
FILE *logfile = fopen("./logfile.txt", "r");
if(logfile == NULL) {
/* datei nicht vorhanden, erstelle logdatei log.txt */
printf (RED "\nLogfile nicht vorhanden, gehe zu createLog() \n" RESET); //@todo remove
//hier datei erstellen [STEHEN GEbLieben]
// fclose(logfile);
createLog();
initLogSession();
} else {
fclose(logfile);
/* logfile vorhanden */
printf (GREEN "\nLogfile vorhanden, gehe weiter! \n" RESET); //@todo remove
initLogSession();
}
}
/**
* schreibt in die konsole, fügt farbe hinzu
* ohne newline \n
* @paramblock
* @param c ist die Farbe
* r / g / y / b / m / c
* bei sonstigem char wird einfachso geprintet
* @endparamblock
*prntColor
*/
void prntColor_legacy(char c, char* input ){
if (c == 'r') {
printf(RED);
printf("%s" ,input);
printf(RESET);
}else if (c == 'g') {
printf(GREEN);
printf("%s" ,input);
printf(RESET);
}else if (c == 'y') {
printf(YELLOW);
printf("%s" ,input);
printf(RESET);
}else if (c == 'b') {
printf(BLUE);
printf("%s" ,input);
printf(RESET);
}else if (c == 'm') {
printf(MAGENTA);
printf("%s" ,input);
printf(RESET);
}else if (c == 'c') {
printf(CYAN);
printf("%s" ,input);
printf(RESET);
}else {
printf("%s" ,input);
}
}
void prntColor(char color, char isError, char* input ){
//char colorString[9]
switch(color){
case 'r':
printf(RED);
break;
case 'g':
printf(GREEN);
break;
case 'y':
printf(YELLOW);
break;
case 'b':
printf(BLUE);
break;
case 'm':
printf(MAGENTA);
break;
case 'c':
printf(CYAN);
break;
default:
break;
}if (isError == 'e') {
perror(input);
}else {
printf("%s" ,input);
}
printf(RESET);
}
/**
* Anfang wo alles hineinfällt
* \param[in] c farbe für konsole
*
* \param[in] t typ des inputs
* \parblock
* e : error(-..) / s : sonstiges / p : nachrichten des prologs
* @todo q: perror
* \endparblock
* bei loglevel außerhalb des definierten wird beides gemacht
* @todo 4: fehler/alles ins log
* rest in console
*
*/
void logPrnt (char c, char t, char* input){
///@todo upddate loglevel hier?
if (loglevel == 0) {
// alles auf console, keine logdatei
prntColor(c,'0', input);
}else if (loglevel == 1){
// alles auf console, log v. alles in logdatei
prntColor(c,'0',input);
writeLog(input);
}
else if (loglevel == 2){
// error in konsole, log v. allem in logdatei
if (t == 'e') {
prntColor(c,'e', input);
writeLog(input);
}
else {
writeLog(input);
}
}
else if (loglevel == 3){
// console nur nach prolog, alles in logfile
if (t == 'p') {
writeLog(input);
}
else if (t == 't') {
writeLog(input);
}
else if (t == 'e') {
prntColor(c,'e', input);
writeLog(input);
}
else {
prntColor(c,'0', input);
writeLog(input);
}
}
else{
fprintf(stderr, "WARNING: Kein Loglevel angegeben!\n"); //@todo auch über logprnt lösen
prntColor('r', 'e',input);
writeLog(input);
}
}
//FILE *logfile;
/* test readlog zahlenraten
void readLog (){ // nur test @todo remove
char *temp;
FILE *file = fopen("listOfTheVeryBest.txt","r");
}
*/
/*
//###### main ########
int main(int argc, const char * argv[]) {
// brauch ich docht nicht hier
// FILE *logfile = fopen("./logfile.txt", "r");
// logfile = fopen("./logfile.txt", "r");
checkFile();
initLogSession();
//printf("hier main logger.c\n");
//printf("\n\nTest Color\n");
fInput('r', 'e', "test der fInput");
return 0;
}*/
<file_sep>#include "../logger/logger.h"
#include "shmManager.h"
void end_routine(shm_struct *shm_str, plist_struct *plist_str, int shm_id, int plist_id){
if (shm_str != NULL){detach_shm(shm_str);}
if (plist_str != NULL){detach_plist(plist_str);}
if (shm_id > 0){delete_by_shmid(shm_id);}
if (plist_id > 0){delete_by_shmid(plist_id);}
logPrnt('g', 'p', "\nDelete routine was executed!\n");
exit(EXIT_SUCCESS);
}
int create_shm(size_t size){
int shm_id;
if ((shm_id = shmget(IPC_PRIVATE, size, IPC_CREAT | 0666)) < 0) {
logPrnt('r', 'e', "Could not create a shared memory");
}
return shm_id;
}
shm_struct* attach_shm(int shm_id){
shm_struct *shm_str;
if ((shm_str = shmat(shm_id, NULL, 0)) == (shm_struct *) -1) {
logPrnt('r', 'e', "Attaching the shared memory segment failed");
}
return shm_str;
}
plist_struct* attach_plist(int plist_id){
plist_struct *plist_str;
if ((plist_str = shmat(plist_id, NULL, 0)) == (plist_struct *) -1) {
logPrnt('r', 'e', "Attaching the piecelist shared memory segment failed");
}
return plist_str;
}
void clear_shm(shm_struct *shm_s){
memset(shm_s, 0, SHMSZ);
}
void clear_plist(plist_struct *plist_s){
memset(plist_s, 0, PLISTSZ);
}
int detach_shm (shm_struct *shm_s){
if(shmdt(shm_s) != 0){
logPrnt('r', 'e', "Could not detach memory segment\n");
return 0;
}
return 1;
}
int detach_plist (plist_struct *plist_s){
if(shmdt(plist_s) != 0){
logPrnt('r', 'e', "Could not detach plist memory segment\n");
return 0;
}
return 1;
}
int delete_by_shmid(int shm_id){
if(shmctl(shm_id, IPC_RMID, NULL) == -1) {
logPrnt('r', 'e', "Could not delete memory segment\n");
return 0;
}
return 1;
}
void set_think_flag(bool to_set, shm_struct* shm_str){
shm_str -> think = to_set;
}
int check_think_flag(shm_struct* shm_str){
if (shm_str -> think){
set_think_flag(false, shm_str);
return 1;
}
logPrnt('r', 'e', "Sorry, the think-flag has not been set");
return 0;
}
int read_shm_struct(shm_struct* shm_str){
if (shm_str -> p_pid == 0 || shm_str -> c_pid == 0 || (strcmp(shm_str -> gameID, "") == 0)){
logPrnt('r', 'e', "\nCouldn't read from shm_str pointer because the data is \n"
" corrupted (pids are 0 / gameID is empty)\n");
return 0;
}
printf (BLUE "\nParent recieved =>> \n"
"gameName = %s\n"
"gameID = %s\n"
"playerCount = %i\n"
"childPID = %i\n"
"parentPID = %i\n"
"think = %i\n",
shm_str -> gameName,
shm_str -> gameID,
shm_str -> playerCount,
shm_str -> c_pid,
shm_str -> p_pid,
shm_str -> think);
for (int i = 0; i < shm_str -> playerCount; i++){
printf (BLUE "\nPlayer %i =>> \n"
BLUE "playerID = %i\n"
BLUE "playerName = %s\n"
BLUE "isReady = %i\n"
BLUE "isLoggedIn = %i\n",
(i+1),
shm_str -> player_str[i].playerID,
shm_str -> player_str[i].playerName,
shm_str -> player_str[i].isReady,
shm_str -> player_str[i].isLoggedIn);
}
return 1;
}
int fill_shm_struct(shm_struct* shm_str){
player_struct player1;
player1.playerID = 15;
if(strcpy(player1.playerName, "Dummy Nr.1") == NULL){
logPrnt('r', 'e', "Couldn't copy playerName 1 in fill_shm_struct @ shmManager");
return 0;
}
player1.isReady = true;
player1.isLoggedIn = true;
player_struct player2;
player2.playerID = 20;
if(strcpy(player2.playerName, "Dummy Nr.2") == NULL){
logPrnt('r', 'e', "Couldn't copy playerName 2 in fill_shm_struct @ shmManager");
return 0;
}
player2.isReady = false;
player2.isLoggedIn = true;
if(strcpy(shm_str -> gameName, "Testgame Nr.1") == NULL){
logPrnt('r', 'e', "Couldn't copy gameName in fill_shm_struct @ shmManager");
return 0;
}
if(strcpy(shm_str -> gameID, "E345Tg&afsd") == NULL){
logPrnt('r', 'e', "Couldn't copy gameID in fill_shm_struct @ shmManager");
return 0;
}
shm_str -> playerCount = 2;
shm_str -> player_str[0] = player1;
shm_str -> player_str[1] = player2;
shm_str -> c_pid = getpid();
shm_str -> p_pid = getppid();
shm_str -> think = false;
logPrnt('g', 'p', "\nChild filled the shm_struct!\n");
return 1;
}<file_sep>#ifndef main_h
#define main_h
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <limits.h>
/**
* Config
*/
#define GAMEKINDNAME "NMMorris"
#define PORTNUMBER 1357
#define HOSTNAME "sysprak.priv.lab.nm.ifi.lmu.de"
#define CVERSION 1.0
/**
* Farben
*/
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
#endif<file_sep>CFLAGS = -g -Wall -std=c99
CC = gcc
all: netlib server client clean_nobin wurstbrot
netlib: netlib.c
$(CC) $(CFLAGS) -c netlib.c
ar -q netlib.a netlib.o
server: server.c netlib.a
$(CC) $(CFLAGS) -o server server.c netlib.a
client: client.c netlib.a
$(CC) $(CFLAGS) -o client client.c netlib.a
clean_nobin:
rm -f *.o
rm -f *.a
clean:
rm -f *.o
rm -f *.a
rm -f server
rm -f client
wurstbrot:
@toilet --gay GREAT
@toilet --gay SUCCESS! <file_sep>// ==UserScript==
// @name nmmorris_helper
// @namespace nmmorris_helper
// @include http://sysprak.priv.lab.nm.ifi.lmu.de/sysprak/NMMorris/*
// @version 1
// @grant none
// ==/UserScript==
var infoBlock = document.getElementById('infoBlock');
if(infoBlock) {
var ID = infoBlock.getElementsByTagName('a')[0].innerHTML;
var throttle = document.getElementById('throttle');
throttle.value = '0.2';
copyToClipboard(ID);
}
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
<file_sep>#ifndef thinker_h
#define thinker_h
#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <limits.h>
#include "../shm/shmManager.h"
/**
* Config
*/
#define ANSWERLENGTH 7
/**
* Pipehelper
*/
#define READ 0
#define WRITE 1
typedef struct{
int x;
int y;
int value;
} token;
/**
* Ein Triple für die schöne Darstellung von
* Nachbarn und Koordinaten
*/
typedef struct{
int x;
int y;
int neighbors[4];
} points_struct;
#define NEIGHBOR_SIZE (sizeof(neighbors_struct))
/**
* Ein wrapper für die Nachbarn
*/
typedef struct{
points_struct array_neighbors[9];
int length;
}neighbors_struct;
typedef struct{
int x1;
int y1;
int x2;
int y2;
char* answer;
}complex_mill_answer;
/**
* sendet SIGUSR1
*
* an parent pid
*/
void start_thinking();
/**
* startet den signal handler
*
* reagiert auf SIGUSR1 mit think()
*/
void init_sig_action();
/**
* Safe read
*/
char* read_from_pipe(int *fd);
/**
* Safe write
*
*/
int write_to_pipe(int *fd, char *str);
/**
* die main KI methode
*
* prüft ob der think-flag im shm struct gesetzt wurde, sonst TERMINIERUNG
*
* schreibt wenn er fertig mit der Berechnung ist den nächsten Zug
* in die pipe mit der Größe von ANSWERLENGTH
*
* setzt den think flag am Ende der Berechnung auf false
*/
void calc_turn(shm_struct *shm_str, plist_struct *plist_str, int shm_id, int plist_id, int *fd);
#endif
<file_sep>#include "../main.h"
#include "../config.h"
#include "../shm/shmManager.h"
#include "connector.h"
/**
* Löst HOSTNAME in eine Ip auf und
* erstellt und initialisiert ein sockaddr_in struct daraus.
*
* returns: struct sockaddr_in
*/
struct sockaddr_in init_server_addr()
{
struct hostent *hp = gethostbyname(HOSTNAME);
struct sockaddr_in ret;
if (hp == NULL) {
perror(RED "gethostbyname() failed\n" RESET);
exit(1);
}
// server_addr initilaisieren
memset ((char *) &ret, 0, sizeof(ret));
//Server-IP in sockaddr_in struct kopieren
memcpy(&ret.sin_addr, hp->h_addr_list[0], hp->h_length);
ret.sin_family = AF_INET;
ret.sin_port = htons( PORTNUMBER );
printf("%s = ", hp->h_name);
printf( "%s\n", inet_ntoa( *( struct in_addr*)( &ret.sin_addr )));
return ret;
}
/**
* Erstellt einen Socket.
*
* returns: Socket filedescriptor
*/
int create_socket()
{
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
perror(RED "Could not create socket" RESET);
exit(1);
}
printf("socket created...\n");
return fd;
}
/**
* Connectet zu einem Socket.
*
* sock: Socket filedescriptor
* dest: sockaddr_in
*/
void connect_to_socket(int sock, struct sockaddr_in dest)
{
int n;
n = connect(sock , (struct sockaddr *)&dest , sizeof(dest));
if (n < 0)
{
perror(RED "connect failed. Error" RESET);
exit(1);
}
printf("connected to socket...\n");
}
/**
* Liest eine Zeile (bis '\n') von einem Socket.
*
* sock: Socket filedescriptor
* buf: Pointer auf buffer,
* in den die erhaltene Nachricht geschrieben werden soll
*/
void get_message(int sock, char* buf)
{
char msg[MSGL];
size_t bytes_received = 0;
size_t n;
memset(buf, 0, MSGL);
int notbremse = 128;
do{
memset(msg, 0, MSGL);
n = recv(sock, msg, MSGL, 0);
if (n < 0)
{
perror(RED "ERROR reading from socket" RESET);
//logPrnt('r','q',"ERROR reading from socket");
exit(1);
}
bytes_received += n;
strcat(buf,msg);
//printf(CYAN "|" RESET "%s", msg);
notbremse--;
}while( (msg[n-1] != '\n') && notbremse > 0);
printf("\nreceived %zu bytes:\n", bytes_received);
switch(buf[0]){
case '+':
printf(GREEN);
break;
case '-':
printf(RED);
break;
default:
break;
}
printf("%s\n" RESET, buf);
///@todo in logfile integrieren @tim
}
/**
* Schreibt in einen Socket.
*
* sock: Socket filedescriptor
* buf: Pointer auf buffer mit zu schreibender Nachricht
*/
void send_message(int sock, char* buf)
{
int n;
printf("<= : %s\n", buf);
int len = strlen(buf);
n = send(sock, buf, len, 0);
if (n < 0)
{
perror(RED "ERROR writing to socket" RESET);
// logPrnt('r','q',"ERROR writing to socket");
exit(1);
}
}
/**
* Stellt die Verbindung her und startet den parser.
*/
int performConnection()
{
int sock;
struct sockaddr_in server_addr;
printf("\n");
server_addr = init_server_addr();
sock = create_socket();
connect_to_socket(sock, server_addr);
return sock;
}
<file_sep>CFLAGS = -g -Wall -Werror -std=c99 -D_XOPEN_SOURCE=600
MACFLAGS = -g -Wall -Werror -std=c99 -D_XOPEN_SOURCE=600 -D_GNU_SOURCE
EFLAGS = -g -Wall -D_XOPEN_SOURCE=600
OUT = -o bin/client
CC = gcc
all: client clean
client: src/logger/logger.h\
src/logger/logger.c\
src/shm/shmManager.c\
src/shm/shmManager.h\
src/thinker/thinker.h\
src/thinker/thinker.c\
src/config.h\
src/config.c\
src/connector/connector.h\
src/connector/performConnection.c\
src/connector/parser.c\
src/main.h\
src/main.c
$(CC) $(CFLAGS) $(OUT) \
src/config.c\
src/main.c\
src/logger/logger.c\
src/shm/shmManager.c\
src/thinker/thinker.c\
src/connector/performConnection.c\
src/connector/parser.c
clean:
rm -f src/*.o
rm -f src/*.a
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define TIME_TO_WAIT 0.1 /* wait for one second */
#define SIZE 50// real size is always SIZE - 2 because of the neighbours check
// defining struct Matrix
struct Matrix {
char inc [SIZE][SIZE];
unsigned int row;
unsigned int column;
} platform,cplat;
// defining tuple to access coords #### maybe saving the condition of the platform here
struct Coords {
int row;
int column;
// char c;
} c0,c1,c2,c3,c4,c5,c6,c7,c8,tempC; // c8 is the current cell
// defining storage for all neighbours
struct Neighbours {
struct Coords field[9];
} nextTo;
// generating random numbers
int irand( int a, int e){
double r = e - a + 1;
return a + (int)(r * rand()/(RAND_MAX+1.0));
}
// encoding 0,1 and 2 to cell counterparts
char rndToCell (int i) {
char c;
switch (i) {
case 1: c = 'O'; break; // living cell
case 2: c = '.'; break; // dead cell
default : c = '/'; break; // space is empty
}
return c;
}
// translating O X and / to number counterparts
int cellToRnd (char c) {
int i;
switch (c) {
case 'O': i = 1; break; // living cell
case '.': i = 2; break; // dead cell
default : i = 0; break; // space is empty
}
return i;
}
// returning all neighbours of the square
struct Neighbours getNeighbours (struct Coords sq){
c0.row = sq.row-1;
c0.column = sq.column-1;
nextTo.field [0]= c0;
c1.row = sq.row-1;
c1.column = sq.column;;
nextTo.field [1]= c1;
c2.row = sq.row-1;
c2.column = sq.column+1;
nextTo.field [2]= c2;
c3.row = sq.row;
c3.column = sq.column-1;
nextTo.field [3]= c3;
c4.row = sq.row;
c4.column = sq.column+1;
nextTo.field [4]= c4;
c5.row = sq.row+1;
c5.column = sq.column-1;
nextTo.field [5]= c5;
c6.row = sq.row+1;
c6.column = sq.column;
nextTo.field [6]= c6;
c7.row = sq.row+1;
c7.column = sq.column+1;
nextTo.field [7]= c7;
c8.row = sq.row;
c8.column = sq.column;
nextTo.field [8] = c8;
return nextTo;
}
char followRules (struct Neighbours neigh){
int counter = 0;
tempC = neigh.field[8];
char temp = platform.inc[tempC.row][tempC.column];
if (temp == '/') return '/';
else {
for (int i = 0; i < 8; i++){ // filling the board with empty places
tempC = neigh.field[i];
if (platform.inc[tempC.row][tempC.column] == 'O') counter +=1;
else counter +=0;
}
if (counter == 3 && temp == '.') return 'O';
else if ((counter <= 1 || counter >= 4) && temp == 'O') return '.';
else if ((counter == 2 || counter == 3) && temp == 'O') return 'O';
else return '.'; // F for failure
}
}
int calDensity (float i){
float x = i / 100;
return (SIZE-2)*(SIZE-2)*x;
}
struct Matrix iterateMatrix (struct Matrix plat){
for (int row = 1; row < plat.row-1; row++){
for(int column = 1; column < plat.column-1; column++){
tempC.row = row;
tempC.column = column;
//char x = plat.inc[row][column];
nextTo = getNeighbours (tempC);
char x = followRules (nextTo);
plat.inc[row][column] = x;
}
}
return plat;
}
struct Matrix fillMatrix (struct Matrix plat, int livingCells){
srand(time(0)); // generating seed for the rng
int crow; // current row for generating living cells
int ccolumn; // current column for generating living cells
for (int row = 1; row < plat.row-1; row++){ // filling the board with empty places
for(int column = 1; column < plat.column-1; column++){
plat.inc[row][column] = '.';
}
}
// plat.inc[SIZE][SIZE] = {'/'} // filling the board with empty places (not working)
for (int i = 0; i < livingCells; i++){ // generating living cells
do {
crow = irand(1,(SIZE-2));
ccolumn = irand(1,(SIZE-2));
} while (plat.inc[crow][ccolumn] == 'O'); // don't override already placed bacteria
plat.inc[crow][ccolumn] = 'O'; // and placing them onto the board
}
/* for (int row = 1; row < plat.row-1; row++){ // filling the board exactly one line
plat.inc[row][4] = 'O';
}
*/
return plat;
}
void showMatrix (struct Matrix plat){
for (int row = 1; row < plat.row-1; row++){
printf ("\n");
for(int column = 1; column < plat.column-1; column++){
char x = plat.inc[row][column];
printf ("%c |",x);
}
}
printf ("\n");
}
void showRealMatrix (struct Matrix plat){
for (int row = 0; row < plat.row; row++){
printf ("\n");
for(int column = 0; column < plat.column; column++){
char x = plat.inc[row][column];
printf ("%c |",x);
}
}
printf ("\n");
}
bool compareMatricies (struct Matrix m1, struct Matrix m2){
bool isSame = true;
for (int row = 1; row < m1.row-1; row++){
for(int column = 1; column < m1.column-1; column++){
if (m1.inc[row][column] == m2.inc[row][column]){}
else {
isSame = false;
column = m1.column-1;
row = m1.row-1;
}
}
}
return isSame;
}
int main(int argc, char *argv[]){
int size; // not working, because of no support with unknown allocation at compile time with arrays in structs
float density; // density of the platform
int livingCells; // amount of calculated living cells based on the density and size (size*size*density/100)
int steps = 1;
platform.row = SIZE;
platform.column = SIZE;
cplat.row = SIZE;
cplat.column = SIZE;
/*
printf("Bitte geben Sie die Größe des Spielfelds (N x N) ein : "); //not working yet
do {scanf("%i",&size);} while (getchar() != '\n');
*/
printf("Bitte geben Sie die Dichte des Spielfelds (in Prozent) ein : ");
do {scanf("%f",&density);} while (getchar() != '\n');
livingCells = calDensity (density);
printf("Returning number of living Cells %i", livingCells); // calculating amount of cells
platform = fillMatrix (platform, livingCells); // filling matrix with random positioning of cells
showMatrix (platform); // showing "zero" step
clock_t last = clock(); // timer function
while(1) { // wait one second
clock_t current = clock();
if (current >= (last + TIME_TO_WAIT * CLOCKS_PER_SEC)) {
printf ("\nNach dem %i Schritt(en):\n", steps); // counting steps
steps++;
cplat = platform; // setting temp platform for check
platform = iterateMatrix (platform); // setting new platform
/*If it's the same after two steps, stop it*/
if (compareMatricies (platform, cplat)) {printf ("\nDie Matrix verändert sich nicht mehr!\n\n"); return EXIT_SUCCESS;}
showMatrix (platform);
// else - go on
last = current;
}
}
}
<file_sep>#include "client_server.h"
int main(int argc, char const *argv[])
{
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int socket_server;
int socket_client;
char in_buf[MSGL];
char out_buf[MSGL];
bzero(in_buf, MSGL);
bzero(out_buf, MSGL);
socket_server = create_socket();
bzero((char *) &server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
bind_socket(socket_server, server_addr);
listen(socket_server, 5);
socket_client = accept_connection(socket_server, client_addr);
while(1)
{
//wait for reply
printf("waiting for reply...\n");
bzero(in_buf, MSGL);
get_message(socket_client, in_buf);
printf("client sayz: %s\n", in_buf);
//get input
printf("Message to client: ");
bzero(out_buf, MSGL);
fgets(out_buf, MSGL, stdin);
if (strcmp(out_buf,"quit\n") == 0){
break;
}
//send input
printf("sending: %s\n", out_buf);
send_message(socket_client, out_buf);
}
close(socket_client);
close(socket_server);
return 0;
}<file_sep>#include "client_server.h"
int main (int argc, char* const argv[])
{
int socket_client;
struct sockaddr_in dest;
char in_buf[MSGL];
char out_buf[MSGL];
bzero(in_buf, MSGL);
bzero(out_buf, MSGL);
socket_client = create_socket();
bzero((char *) &dest, sizeof(dest));
dest.sin_addr.s_addr = inet_addr( argv[1] );
dest.sin_family = AF_INET;
dest.sin_port = htons( PORT );
connect_to_socket(socket_client, dest);
while(1)
{
//get input
printf("Message to server: ");
bzero(out_buf, MSGL);
fgets(out_buf, MSGL, stdin);
if (strcmp(out_buf,"quit\n") == 0){
break;
}
//send input
printf("sending: %s\n", out_buf);
send_message(socket_client, out_buf);
//wait for reply
printf("waiting for reply...\n");
bzero(in_buf, MSGL);
get_message(socket_client, in_buf);
printf("server sayz: %s\n", in_buf);
}
close(socket_client);
return 0;
}<file_sep>#include "thinker.h"
#include "../config.h"
#include "../logger/logger.h"
void start_thinking(){
kill (getppid(), SIGUSR1);
}
char* read_from_pipe(int *fd){
static char buffer[ANSWERLENGTH];
memset(buffer, 0, ANSWERLENGTH);
char *log_msg;
int bytes;
if ((bytes = read(fd[READ], buffer, ANSWERLENGTH)) <= 0) {
logPrnt('r', 'e', "\nCouldn't read from pipe!\n");
memset(buffer, 0, ANSWERLENGTH);
}
else {
asprintf(&log_msg, "\nRead %i bytes from the pipe: %s\n", bytes, buffer);
logPrnt('g', 'p', log_msg);
}
return buffer;
}
int write_to_pipe(int *fd, char *str){
if (str == NULL || write(fd[WRITE], str, strlen(str)) <= 0) {
logPrnt('r', 'e', "\nCouldn't write to pipe!\n");
return 0;
}
return 1;
}
char* print_helper(int i){
char* helper;
char* mul = "(*)";
char* hashtag = "(#)";
char* plus = " + ";
if (i==2){
helper = mul;
}
else if(i==1){
helper = hashtag;
}
else{
helper = plus;
}
return helper;
}
void print_field(plist_struct *plist_str){
printf("%s----------%s----------%s\n", print_helper(plist_str -> piece_list[0][0]), print_helper(plist_str -> piece_list[0][1]), print_helper(plist_str -> piece_list[0][2]));
printf(" | | |\n");
printf(" | %s------%s------%s |\n", print_helper(plist_str -> piece_list[1][0]), print_helper(plist_str -> piece_list[1][1]), print_helper(plist_str -> piece_list[1][2]));
printf(" | | | | |\n");
printf(" | | %s--%s--%s | |\n" , print_helper(plist_str -> piece_list[2][0]), print_helper(plist_str -> piece_list[2][1]), print_helper(plist_str -> piece_list[2][2]));
printf(" | | | | | |\n");
printf("%s-%s-%s %s-%s-%s\n" , print_helper(plist_str -> piece_list[0][7]), print_helper(plist_str -> piece_list[1][7]), print_helper(plist_str -> piece_list[2][7]), print_helper(plist_str -> piece_list[2][3]), print_helper(plist_str -> piece_list[1][3]), print_helper(plist_str -> piece_list[0][3]));
printf(" | | | | | |\n");
printf(" | | %s--%s--%s | |\n" , print_helper(plist_str -> piece_list[2][6]), print_helper(plist_str -> piece_list[2][5]), print_helper(plist_str -> piece_list[2][4]));
printf(" | | | | |\n");
printf(" | %s------%s------%s |\n" , print_helper(plist_str -> piece_list[1][6]), print_helper(plist_str -> piece_list[1][5]), print_helper(plist_str -> piece_list[1][4]));
printf(" | | |\n");
printf("%s----------%s----------%s\n" , print_helper(plist_str -> piece_list[0][6]), print_helper(plist_str -> piece_list[0][5]), print_helper(plist_str -> piece_list[0][4]));
}
char* convert_pos_to_string(int fst_coord, int snd_coord){
char *coords = malloc (2*sizeof(char*));
switch(fst_coord) {
case 0: sprintf(coords, "A%d", snd_coord); break;
case 1: sprintf(coords, "B%d", snd_coord); break;
case 2: sprintf(coords, "C%d", snd_coord); break;
}
return coords;
}
token check_counter_clock_wise(plist_struct *plist_str, int fst_coord, int snd_coord){
token cc_wise;
cc_wise.x = fst_coord;
cc_wise.y = (snd_coord + 7) % 8;
cc_wise.value = plist_str -> piece_list[cc_wise.x][cc_wise.y];
return cc_wise;
}
token check_clock_wise(plist_struct *plist_str, int fst_coord, int snd_coord){
token c_wise;
c_wise.x = fst_coord;
c_wise.y = (snd_coord + 1) % 8;
c_wise.value = plist_str -> piece_list[c_wise.x][c_wise.y];
return c_wise;
}
/**
* !fst_coord==0 <==> Nicht im A Level
* snd_coord % 2 <==> Nur "kreuz" Koordinaten (1,3,5,7)
*/
token check_level_up(plist_struct *plist_str, int fst_coord, int snd_coord){
token up;
switch ((!(fst_coord==0)) && snd_coord % 2){
case 0:
up.x = fst_coord;
up.y = snd_coord;
up.value = 3;
return up;
break;
case 1: up.x = fst_coord-1;
up.y = snd_coord;
up.value = plist_str -> piece_list[up.x][up.y];
return up;
break;
default: printf("Dies sollte niemals passieren!");
return up;
}
}
/**
* !fst_coord==0 <==> Nicht im C Level
* snd_coord % 2 <==> Nur "kreuz" Koordinaten (1,3,5,7)
*/
token check_level_down(plist_struct *plist_str, int fst_coord, int snd_coord){
token down;
switch ((!(fst_coord==2)) && (snd_coord % 2)==1){
case 0:
down.x = fst_coord;
down.y = snd_coord;
down.value = 3;
return down;
break;
case 1: down.x = fst_coord+1;
down.y = snd_coord;
down.value = plist_str -> piece_list[down.x][down.y];
return down;
break;
default: printf("Dies sollte niemals passieren!");
return down;
}
}
neighbors_struct get_neighbors(plist_struct *plist_str){
neighbors_struct wrap;
int length = 0;
for(int x = 0; x<3; x++){
for(int y = 0; y<8; y++){
if(plist_str -> piece_list[x][y] == 1){
wrap.array_neighbors[length].x = x;
wrap.array_neighbors[length].y = y;
wrap.array_neighbors[length].neighbors[0] = check_clock_wise(plist_str, x, y).value;
wrap.array_neighbors[length].neighbors[1] = check_counter_clock_wise(plist_str, x, y).value;
wrap.array_neighbors[length].neighbors[2] = check_level_up(plist_str, x, y).value;
wrap.array_neighbors[length].neighbors[3] = check_level_down(plist_str, x, y).value;
length++;
}
}
}
wrap.length = length;
return wrap;
}
void print_neighbors(neighbors_struct wrap){
for (int i = 0; i < wrap.length; i++){
printf ("x = %i | y = %i \n", wrap.array_neighbors[i].x,wrap.array_neighbors[i].y);
printf ("[0] = %i | [1] = %i | [2] = %i | [3] = %i \n", wrap.array_neighbors[i].neighbors[0], wrap.array_neighbors[i].neighbors[1],wrap.array_neighbors[i].neighbors[2],wrap.array_neighbors[i].neighbors[3]);
}
}
char* get_enemy_piece(plist_struct *plist_str){
srand(time(NULL));
int counter = 0;
int rnd = (rand() % plist_str -> countEnemyPieces+1);
char *answer = malloc (2*sizeof(char*));
for(int x = 0; x<3; x++){
for(int y = 0; y<8; y++){
if(plist_str -> piece_list[x][y] == 2){
counter++;
if(counter == rnd){
answer = convert_pos_to_string(x,y);
}
}
}
}
return answer;
}
/*
complex_mill_answer check_mill_possibility(plist_struct *plist_str, neighbors_struct wrap){
complex_mill_answer complex;
char* answer = malloc(2*(sizeof(char*)));
token temp_token_1;
token temp_token_2;
bool is_found;
for(int i = 0; i < wrap.length; i++){
if((wrap.array_neighbors[i].y % 2) == 0 && (!is_found)){
temp_token_1 = check_clock_wise(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
if(temp_token_1.value == 1){
temp_token_2 = check_clock_wise(plist_str, temp_token_1.x, temp_token_1.y);
if(temp_token_2.value == 0){
answer = convert_pos_to_string(temp_token_2.x, temp_token_2.y);
printf ("1 was true\n");
complex.answer = answer;
complex.x1 = wrap.array_neighbors[i].x;
complex.y1 = wrap.array_neighbors[i].y;
complex.x2 = temp_token_1.x;
complex.y2 = temp_token_1.y;
is_found = true;
}
}
if(temp_token_1.value == 0){
temp_token_2 = check_clock_wise(plist_str, temp_token_1.x, temp_token_1.y);
if(temp_token_2.value == 1){
answer = convert_pos_to_string(temp_token_1.x, temp_token_1.y);
printf ("2 was true\n");
complex.answer = answer;
complex.x1 = wrap.array_neighbors[i].x;
complex.y1 = wrap.array_neighbors[i].y;
complex.x2 = temp_token_2.x;
complex.y2 = temp_token_2.y;
is_found = true;
}
}
}
}
for(int i = 0; i < wrap.length; i++){
if((wrap.array_neighbors[i].y % 2) == 0 && (!is_found)){
temp_token_1 = check_counter_clock_wise(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
if(temp_token_1.value == 1){
temp_token_2 = check_counter_clock_wise(plist_str, temp_token_1.x, temp_token_1.y);
if(temp_token_2.value == 0){
answer = convert_pos_to_string(temp_token_2.x, temp_token_2.y);
printf ("3 was true\n");
complex.answer = answer;
complex.x1 = wrap.array_neighbors[i].x;
complex.y1 = wrap.array_neighbors[i].y;
complex.x2 = temp_token_1.x;
complex.y2 = temp_token_1.y;
is_found = true;
}
}
if(temp_token_1.value == 0){
temp_token_2 = check_counter_clock_wise(plist_str, temp_token_1.x, temp_token_1.y);
if(temp_token_2.value == 1){
answer = convert_pos_to_string(temp_token_1.x, temp_token_1.y);
printf ("4 was true\n");
complex.answer = answer;
complex.x1 = wrap.array_neighbors[i].x;
complex.y1 = wrap.array_neighbors[i].y;
complex.x2 = temp_token_2.x;
complex.y2 = temp_token_2.y;
is_found = true;
}
}
}
}
printf("this is answer from mill = %s \n", answer);
return complex;
}*/
char* set_phase(plist_struct *plist_str, neighbors_struct wrap){
srand(time(NULL));
int counter = 0;
int count_free_spaces = 24 - plist_str -> countMyPieces - plist_str -> countEnemyPieces;
int rnd = (rand() % count_free_spaces+1);
char *answer = malloc (ANSWERLENGTH * sizeof(char*));
for(int x = 0; x<3; x++){
for(int y = 0; y<8; y++){
if(plist_str -> piece_list[x][y] == 0){
counter++;
if(counter == rnd){
answer = convert_pos_to_string(x,y);
plist_str -> unplacedPieces--;
break;
}
}
}
}
// ###########################Testing################################
/* complex_mill_answer complex = check_mill_possibility(plist_str, wrap);
if (complex.answer[0] == 'A' || complex.answer[0] == 'B' || complex.answer[0] == 'C'){
return complex.answer;
}*/
// ##################################################################
return answer;
}
/**
* Erster Zug auf A0
* Zweiter Zug auf A1
* Dritter Zug auf A2
*/
char* set_sure_mill(plist_struct *plist_str, neighbors_struct wrap){
char *answer = malloc (ANSWERLENGTH *sizeof(char*));
if(plist_str -> unplacedPieces == 9){
printf("convPos(0,0) = %s\n", convert_pos_to_string(0,0));
answer = convert_pos_to_string(0,0);
plist_str -> unplacedPieces--;
}
else if(plist_str -> unplacedPieces == 8){
answer = convert_pos_to_string(0,1);
plist_str -> unplacedPieces--;
}
else if(plist_str -> unplacedPieces == 7){
answer = convert_pos_to_string(0,2);
printf("Mill 3rd & answer = %s\n", answer);
plist_str -> unplacedPieces--;
}
else{
answer = set_phase(plist_str, wrap);
}
return answer;
}
// Kopiert aus http://stackoverflow.com/questions/6127503/shuffle-array-in-c
void shuffle(points_struct *array_neighbors, int length){
if (length > 1){
for (int i = 0; i < length - 1; i++){
int j = i + rand() / (RAND_MAX / (length - i) + 1);
points_struct t = array_neighbors[j];
array_neighbors[j] = array_neighbors[i];
array_neighbors[i] = t;
}
}
}
char* slide_phase(plist_struct *plist_str, neighbors_struct wrap){
token to;
srand(time(NULL));
char *answer = malloc (ANSWERLENGTH*sizeof(char*));
char *answer_from = malloc (2*sizeof(char*));
char *answer_to = malloc (2*sizeof(char*));
shuffle(wrap.array_neighbors, wrap.length);
for (int i = 0; i < wrap.length; i++){
for (int j = 0; j < 4; j++){
if(wrap.array_neighbors[i].neighbors[j] == 0){
answer_from = convert_pos_to_string(wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
switch(j){
case 0: to = check_clock_wise(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
answer_to = convert_pos_to_string(to.x, to.y);
break;
case 1: to = check_counter_clock_wise(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
answer_to = convert_pos_to_string(to.x, to.y);
break;
case 2: to = check_level_up(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
answer_to = convert_pos_to_string(to.x, to.y);
break;
case 3: to = check_level_down(plist_str, wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
answer_to = convert_pos_to_string(to.x, to.y);
break;
default: printf("Error while setting neighbor!\n");
break;
}
}
}
}
sprintf(answer, "%s:%s", answer_from, answer_to);
return answer;
}
char* jump_phase(plist_struct *plist_str, neighbors_struct wrap){
srand(time(NULL));
char *answer = malloc (ANSWERLENGTH*sizeof(char*));
char *answer_from = malloc (2*sizeof(char*));
char *answer_to = malloc (2*sizeof(char*));
int count_free_spaces = 24 - plist_str -> countMyPieces - plist_str -> countEnemyPieces;
int rnd_token = rand() % 3;
int rnd_spaces = rand() % count_free_spaces;
int counter = 0;
for (int i = 0; i < wrap.length; i++){
if(i == rnd_token){
answer_from = convert_pos_to_string(wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
}
}
for(int x = 0; x<3; x++){
for(int y = 0; y<8; y++){
if(plist_str -> piece_list[x][y] == 0){
if(counter == rnd_spaces){
answer_to = convert_pos_to_string(x,y);
x = 3; // not happy with this solution
y = 8; // not happy with this solution
}
counter++;
}
}
}
// ##########################Testing#################################
/* complex_mill_answer complex;
complex = check_mill_possibility(plist_str, wrap);
if(complex.answer != NULL){
printf("This is complex.answer = %s \n ", complex.answer);
for (int i = 0; i < wrap.length; i++){
if((wrap.array_neighbors[i].x != complex.x1) && (wrap.array_neighbors[i].y != complex.y1) && (wrap.array_neighbors[i].x != complex.x2) && (wrap.array_neighbors[i].y != complex.y2)){
answer_from = convert_pos_to_string(wrap.array_neighbors[i].x, wrap.array_neighbors[i].y);
printf("Found answer_from = %s \n", answer_from);
}
}
if (complex.answer[0] == 'A' || complex.answer[0] == 'B' || complex.answer[0] == 'C'){
sprintf(answer, "%s:%s", answer_from, complex.answer);
}
}
else {
sprintf(answer, "%s:%s", answer_from, answer_to);
}*/
// #########################Testing#################################
sprintf(answer, "%s:%s", answer_from, answer_to);
return answer;
}
void calc_turn(shm_struct *shm_str, plist_struct *plist_str, int shm_id, int plist_id, int *fd){
if (!check_think_flag(shm_str)){end_routine(shm_str, plist_str, shm_id, plist_id);}
char *answer = NULL;
neighbors_struct wrap;
wrap = get_neighbors(plist_str);
//print_neighbors(wrap);
print_field(plist_str);
//0.Mühlenfall: Wenn eine Mühle vorhanden ist, müssen gegnerische Steine geschlagen werden
if(plist_str -> piecesToRemove > 0){
printf("I'm in "GREEN "Mill" RESET "-Phase!\n");
answer = get_enemy_piece(plist_str);
}
//1. Setzphase: Es dürfen nicht alle Steine verteilt sein und kein Stein muss geschlagen werden
else if(plist_str -> unplacedPieces > 0 && plist_str -> piecesToRemove == 0){
printf("I'm in "GREEN "Set" RESET "-Phase!\n");
answer = set_phase(plist_str, wrap);
//answer = set_sure_mill(plist_str);
}
//2. Schieb-Phase: Es müssen alle Steine verteilt sein, die KI muss mehr als 3 Steine besitzen
// und kein Stein muss geschlagen werden
else if(plist_str -> unplacedPieces == 0 && plist_str -> countMyPieces > 3 && plist_str -> piecesToRemove == 0){
printf("I'm in " GREEN "Slide" RESET "-Phase!\n");
answer = slide_phase(plist_str, wrap);
}
//3. Sprungphase: Es müssen alle Steine verteilt sein und die KI muss genau 3 oder weniger Steine besitzen
else if(plist_str -> unplacedPieces == 0 && plist_str -> countMyPieces <= 3){
printf("I'm in " GREEN "Jump" RESET "-Phase!\n");
answer = jump_phase(plist_str, wrap);
}
//4. Fehlerfall:
else {
printf(RED "Thinker konnte keine Phase erkennen!\n");
}
//5. Endroutine: Steinecount für beide Spieler zurücksetzen, Flag zurücksetzen, Feld leeren
// Antwort schicken
plist_str -> countMyPieces = 0;
plist_str -> countEnemyPieces = 0;
plist_str -> piecesToRemove = 0; // Fall für 2 Steine muss noch abgefangen werden
set_think_flag(false,shm_str);
memset(plist_str -> piece_list, 0, 3*8*sizeof(int));
if(!write_to_pipe(fd, answer)){end_routine(shm_str, plist_str, shm_id, plist_id);}
free(answer);
}
<file_sep>#include "connector.h"
char id[11];
/**
* dummy main damit der connector alleine
* compiled werden kann (make connector);
*/
int main(int argc, char const *argv[])
{
if( argv[1] == '\0' ) {
printf("Bitte Spiel-ID angeben.\n");
exit(1);
}
sprintf(id, "%s", argv[1]);
performConnection();
return 0;
}<file_sep>#ifndef connector_h
#define connector_h
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <errno.h>
#define MSGL 4096
/**
* performConnection.c
*/
struct sockaddr_in init_server_addr();
int create_socket();
void connect_to_socket(int sock, struct sockaddr_in dest);
void get_message(int sock, char* buf);
void send_message(int sock, char* buf);
int performConnection();
/**
* parser.c
*/
void parseMessages(int sock, shm_struct *shm_str, plist_struct *plist_str, int *pipe_fd);
void processMessage(char *buf);
void tokenizeLine(char *line);
#endif<file_sep>#include "../main.h"
#include "../thinker/thinker.h"
#include "../config.h"
#include "connector.h"
char msg_queue[32][128];
char tokens[32][32];
/**
* Teilt eine Nachricht vom Server in einzelne Zeilen
* und schreibt sie in die msg_queue.
*
* buf: die zu parsende Nachricht
*/
void processMessage(char *buf)
{
int lineCount = 0;
char tmp[MSGL];
memset(tmp, 0, MSGL);
sprintf(tmp, "%s", buf);
for (int i = 0; i < 32; ++i)
{
memset(msg_queue[i], 0, 128);
}
char *line = strtok(tmp, "\n");
while (line) {
sprintf(msg_queue[lineCount], "%s", line);
lineCount++;
line = strtok(0, "\n");
}
/*
int i = 0;
while ( (strcmp(msg_queue[i], "") != 0) && (i<32) ){
printf("line %i :: %s\n", i, msg_queue[i]);
i++;
}
*/
}
/**
* Splitet eine line an leerzeichen und schreibt das Ergebniss in tokens.
*
* line: Zu splitende line.
*/
void tokenizeLine(char *line)
{
int tokenCount = 0;
char tmp[strlen(line)];
for (int i = 0; i < 32; ++i)
{
memset(tokens[i], 0, 32);
}
sprintf(tmp, "%s", line);
char *token = strtok(tmp, " ");
while (token) {
sprintf(tokens[tokenCount], "%s", token);
tokenCount++;
token = strtok(0, " ");
}
/*
int i = 0;
while( (strcmp(tokens[i], "") != 0) && i < 32){
printf("token:: %s\n", tokens[i]);
i++;
}
*/
}
/**
* Liest von einem Socket und verarbeitet die erhaltene Nachricht.
*
* sock: Der Socket, von dem gelesen werden soll.
*/
void parseMessages(int sock, shm_struct *shm_str, plist_struct *plist_str, int *pipe_fd)
{
int breaker = 1;
char in_buf[MSGL];
char out_buf[MSGL];
memset(in_buf, 0, MSGL);
memset(out_buf, 0, MSGL);
int total_players;
int max_move_time;
int captured_pieces;
char game_type[20];
int pl_players;
int pl_pieces;
int my_pos;
char my_name[20];
int opponent_pos;
char opponent_name[20];
int opponent_ready;
int piece_player;
int piece_id;
char piece_pos[2];
char winner_name[20];
int winner_id;
printf("\n");
int snd_coord = 0;
int fst_coord = 0;
snd_coord++;
fst_coord++;
while(breaker)
{
get_message(sock, in_buf);
processMessage(in_buf);
int linenum = 0;
while( (strcmp(msg_queue[linenum], "") != 0) && linenum < 32)
{
switch (msg_queue[linenum][0]) {
/**
* G A M E L O G I C
*/
case '+':
if(strcmp(msg_queue[linenum], "+ WAIT") == 0) {
sprintf(out_buf, "OKWAIT\n");
send_message(sock, out_buf);
}else if(strcmp(msg_queue[linenum], "+ MNM Gameserver v1.0 accepting connections") == 0) {
sprintf(out_buf, "VERSION %0.1f\n", CVERSION);
send_message(sock, out_buf);
}else if(strcmp(msg_queue[linenum], "+ Client version accepted - please send Game-ID to join") == 0) {
sprintf(out_buf, "ID %s\n", shm_str -> gameID);
send_message(sock, out_buf);
}else if(strcmp(msg_queue[linenum], "+ PLAYING NMMorris") == 0) {
if(strcmp(msg_queue[linenum + 1], "") != 0){
linenum++;
sscanf(msg_queue[linenum], "+ %[^\t\n]", game_type);
printf("Game Name: %s\n\n",game_type);
strcpy(shm_str -> gameName, game_type);
}else{
get_message(sock, in_buf);
processMessage(in_buf);
sprintf(game_type, "%s",msg_queue[0]);
printf("Game Name: %s\n\n",game_type);
strcpy(shm_str -> gameName, game_type);
}
sprintf(out_buf, "PLAYER\n");
send_message(sock, out_buf);
}else if(sscanf(msg_queue[linenum], "+ YOU %d %[^\t\n]", &my_pos, my_name) == 2) {
printf("My position: %d\n", my_pos);
printf("My Name: %s\n\n", my_name);
shm_str -> player_str[0].playerID = my_pos;
strcpy(shm_str -> player_str[0].playerName, my_name);
shm_str -> player_str[0].isReady = 1;
shm_str -> player_str[0].isLoggedIn = 1;
}else if(sscanf(msg_queue[linenum], "+ TOTAL %d", &total_players) == 1) {
printf("Total Players: %d\n\n", total_players);
shm_str -> playerCount = total_players;
if(strcmp(msg_queue[linenum + 1], "") != 0){
linenum++;
tokenizeLine(msg_queue[linenum]);
sscanf(tokens[1], "%d", &opponent_pos);
memset(opponent_name, 0, 20);
int i = 2;
while( strcmp(tokens[i+1], "") != 0){
strcat(tokens[i], " ");
strcat(opponent_name, tokens[i]);
i++;
}
opponent_ready = atoi(tokens[i]);
printf("Opponent position: %d\n", opponent_pos);
printf("Opponent ID: %s\n", opponent_name);
if(opponent_ready == 1){
printf("Opponent ready?: YES\n\n");
}else{
printf("Opponent ready?: NO\n\n");
}
shm_str -> player_str[1].playerID = opponent_pos;
strcpy(shm_str -> player_str[1].playerName, opponent_name);
shm_str -> player_str[1].isReady = opponent_ready;
shm_str -> player_str[1].isLoggedIn = 1;
}
}else if(strcmp(msg_queue[linenum], "+ ENDPLAYERS") == 0) {
//nothing to do...
}else if(sscanf(msg_queue[linenum], "+ MOVE %d", &max_move_time) == 1) {
printf("Maximum move time: %d\n\n", max_move_time);
}else if(sscanf(msg_queue[linenum], "+ CAPTURE %d", &captured_pieces) == 1) {
printf("Captured pieces: %d\n\n", captured_pieces);
plist_str -> piecesToRemove = captured_pieces;
}else if(sscanf(msg_queue[linenum], "+ PIECELIST %d,%d", &pl_players, &pl_pieces) == 2) {
printf("Piecelist for %d players and %d pieces per player:\n\n", pl_players, pl_pieces);
}else if(sscanf(msg_queue[linenum], "+ PIECE%d.%d %[A-C0-7]", &piece_player, &piece_id, piece_pos) == 3) {
if(strlen(piece_pos) == 2) {
fst_coord = piece_pos[0] - 65;
snd_coord = atoi(&piece_pos[1]);
if(piece_player == my_pos) {
plist_str -> piece_list[fst_coord][snd_coord] = 1;
plist_str -> countMyPieces++;
}else{
plist_str -> piece_list[fst_coord][snd_coord] = 2;
plist_str -> countEnemyPieces++;
}
}
printf("Player %d, piece %d at position %s\n", piece_player, piece_id, piece_pos);
}else if(strcmp(msg_queue[linenum], "+ ENDPIECELIST") == 0) {
sprintf(out_buf, "THINKING \n");
send_message(sock, out_buf);
}else if(strcmp(msg_queue[linenum], "+ OKTHINK") == 0) {
printf("thinking...\n");
set_think_flag(true, shm_str);
start_thinking();
//warte auf die antwort
sprintf(out_buf, "PLAY %s\n", read_from_pipe(pipe_fd));
send_message(sock, out_buf);
}else if(strcmp(msg_queue[linenum], "+ MOVEOK") == 0) {
//nothing to do...
}else if(strcmp(msg_queue[linenum], "+ GAMEOVER") == 0) {
printf("Game Over!\n");
printf("...50 turns without mill...\n");
}else if(sscanf(msg_queue[linenum], "+ GAMEOVER %d %[^\t\n]", &winner_id, winner_name) == 2) {
printf("Game Over!\n");
printf("...and the winner is: %s\n", winner_name);
}else if(strcmp(msg_queue[linenum], "+ QUIT") == 0) {
printf("quitting...\n");
breaker = 0;
}else{
printf(YELLOW "Unexpected message: %s\n" RESET, msg_queue[linenum]);
}
break;
/**
* E R R O R H A N D L I N G
*/
case '-':
printf(RED);
if(strcmp(msg_queue[linenum], "- No free computer player found for that game - exiting") == 0) {
printf("No free seat.\n");
}else if(strcmp(msg_queue[linenum], "- Socket timeout - please be quicker next time") == 0){
printf("Socket timeout.\n");
}else if(strcmp(msg_queue[linenum], "- Protocol mismatch - you probably didn't want to talk to the fabulous gameserver") == 0){
printf("Wrong input format.\n");
}else if(strcmp(msg_queue[linenum], "- We expected you to THINK!") == 0){
printf("Server expects client to think.\n");
}else if(strcmp(msg_queue[linenum], "- Destination is already occupied") == 0){
printf("Destination occupied.\n");
}else{
printf("Unexpected server error: %s\n", msg_queue[linenum]);
}
breaker = 0;
break;
default:
printf("WAT\n");
breaker = 0;
break;
}
linenum++;
}
printf(RESET);
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <strings.h>
#include <arpa/inet.h>
#define PORT 4711
#define MSGL 256
int create_socket();
void bind_socket(int sock, struct sockaddr_in serv_addr);
void get_message(int sock, char* msg);
void send_message(int sock, char* msg);
int accept_connection(int sock, struct sockaddr_in cli_addr);
void connect_to_socket(int sock, struct sockaddr_in dest);<file_sep>#include "main.h"
#include "thinker/thinker.h"
#include "config.h"
#include "logger/logger.h"
#include "shm/shmManager.h"
#include "connector/connector.h"
/* parseArgs schaut ob die übergeben Parameter in der Kommandozeile valide sind
* ansonsten terminiert das Programm
*
* -i ist die Game-ID und muss genau 11 Zeichen lang sein (wird in idFlag abgespeichert)
* -c ist für die optionale Configdatei (wird in file abgespeichert)
*/
configData parseArgs(int argc, char *argv[]){
char *idFlag = NULL;
FILE* file = NULL;
configData configInc;
int pArg;
if (argc <= 1){
logPrnt('r', 'e', "\nZu wenig Argumente...\n");
printHowToUse();
}
else {
while ((pArg=getopt(argc, argv, "i:c:")) != -1) {
switch (pArg) {
case 'i':
idFlag = optarg;
break;
case 'c':
file = openPathConfig(optarg);
break;
}
}
file = openCommonConfig(file);
}
if (idFlag != NULL && strlen(idFlag) != 11){
logPrnt('r', 'e', "\nDie Länge der Game-ID muss 11 Zeichen lang sein!\n");
printHowToUse();
}
if (idFlag == NULL){
logPrnt('r', 'e', "\nDie ID wurde nicht erfolgreich gesetzt!\n");
printHowToUse();
}
configInc = readConfig(file);
sprintf(configInc.game_id, "%s", idFlag);
configParamValid(configInc);
return configInc;
}
/**
* Teilt den laufenden Prozess in
*
* den Kindprozess = Connector
* und Elternprozess = Thinker
*
*/
void forkingAction(configData conf_str){
// pipes
int fd[2];
pipe(fd);
// shm
int shm_id = create_shm(SHMSZ);
if(shm_id < 0){end_routine(NULL, NULL, (-1), (-1));}
shm_struct* shm_str = attach_shm(shm_id);
if (shm_str == NULL){end_routine(NULL, NULL, shm_id, (-1));}
int plist_id = create_shm(PLISTSZ);
if(plist_id < 0){end_routine(shm_str, NULL, shm_id, (-1));}
plist_struct* plist_str = attach_plist(plist_id);
if (plist_str == NULL){end_routine(shm_str, NULL, shm_id, plist_id);}
clear_shm(shm_str);
clear_plist(plist_str);
//nested functions for singals
void think (){
calc_turn(shm_str, plist_str, shm_id, plist_id, fd);
}
void sig_int_handler(){
end_routine(shm_str, plist_str, shm_id, plist_id);
}
//signals
struct sigaction sig_str;
sig_str.sa_handler = think;
sigaction (SIGUSR1, &sig_str, NULL);
int sock;
int pid = fork();
switch (pid){
case -1:
logPrnt('r', 'e', "Failed to fork in main.c: ");
end_routine(shm_str, plist_str, shm_id, plist_id);
break;
case 0: //Kind =^ sendet || starte Connection + Parser hier
// pipes
close(fd[WRITE]);
//signals
signal (SIGINT, sig_int_handler);
// shm
strcpy(shm_str -> gameID, conf_str.game_id);
plist_str -> piecesToRemove = 0;
plist_str -> unplacedPieces = 9;
//parser
sock = performConnection();
parseMessages(sock, shm_str, plist_str, fd);
//end routine
close(sock);
kill(getppid(), SIGUSR2);
exit(EXIT_SUCCESS);
break;
case 1 ... INT_MAX: // Eltern =^ empfängt Daten || starte Thinker hier
close(fd[READ]);
signal(SIGUSR2, sig_int_handler);
while(1){}
break;
default :
logPrnt('r', 'e', "pid lower than -1 : This case should never happen!\n");
end_routine(shm_str, plist_str, shm_id, plist_id);
break;
}
}
int main(int argc, char *argv[]) {
initLog();
configData conf_str = parseArgs(argc, argv);
setLogLevel(conf_str.loglevel);
forkingAction(conf_str);
return 0;
}
<file_sep>#include "config.h"
#include "logger/logger.h"
FILE* openCommonConfig(FILE* file){
if(file == NULL){
if ((file = fopen("client.conf", "r")) == NULL){
if ((file = fopen("../client.conf", "r")) == NULL){
logPrnt('r', 'e', "Couldn't open client.conf\n");
exit(EXIT_FAILURE);
} else {logPrnt('g', 'p', "\nUsing common ../client.conf\n");}
} else {logPrnt('g', 'p', "\nUsing common client.conf\n");}
}
return file;
}
FILE* openPathConfig(char *optarg){
char log_msg[200];
FILE* file = NULL;
char path[PATHLEN];
if (strcpy(path,optarg) == NULL){
logPrnt('r', 'e', "\nCouldn't copy the c-Flag to path\n");
}
if ((path[strlen(path) - 1] != 'f') || ((file = fopen(path, "r")) == NULL) ){
//asprintf invalid in C99 in mac
//asprintf(&log_msg, "\nCouldn't open path = ' %s '!\n", path);
sprintf(log_msg,"\nCouldn't open path = ' %s '!\n", path);
logPrnt('r', 'e', log_msg);
}
else {
//asprintf(&log_msg, "\nUsing = ' %s '!\n", path);
sprintf(log_msg, "\nUsing = ' %s '!\n", path);
logPrnt('g', 'p', log_msg);
}
return file;
}
void configParamValid(configData conf_str){
if (conf_str.hostname == NULL || conf_str.portnummer == 0 || conf_str.artdesspiels == NULL || conf_str.loglevel < 0 || conf_str.loglevel > 3){
logPrnt('r', 'e', "\nDie Parameter in der .conf Datei sind nicht alle richtig angegeben!\n");
exit(EXIT_FAILURE);
}
if (conf_str.hostname == NULL || conf_str.portnummer == 0 || conf_str.artdesspiels == NULL ){
printHowToUse();
}
}
void printConfigString(configData conf_str){
printf ("host = %s \n"
"port = %i \n"
"artds= %s \n"
"loglvl = %i \n",
conf_str.hostname,
conf_str.portnummer,
conf_str.artdesspiels,
conf_str.loglevel);
}
configData readConfig(FILE *file){
//Delimiter für die Trennbedinung pro Zeile
char *delimiter = " ";
char line[MSGLEN];
char *ptr;
//Temporäres Struct configTemp erzeugen
configData configTemp;
//Zeilenweise auslesen und aufsplitten nach Parameter
while (fgets(line, MSGLEN, file) != NULL) {
ptr = strtok(line, delimiter);
if(strcmp("hostname",ptr) == 0){
ptr = strtok(NULL, delimiter);
ptr = strtok(NULL, delimiter);
strcpy(configTemp.hostname,ptr);
configTemp.hostname[strlen(configTemp.hostname)-1] = 0;
}
if(strcmp("portnummer",ptr) == 0){
ptr = strtok(NULL, delimiter);
ptr = strtok(NULL, delimiter);
configTemp.portnummer = atof(ptr);
}
if(strcmp("artdesspiels",ptr) == 0){
ptr = strtok(NULL, delimiter);
ptr = strtok(NULL, delimiter);
strcpy(configTemp.artdesspiels,ptr);
configTemp.artdesspiels[strlen(configTemp.artdesspiels)-1] = 0;
}
if(strcmp("loglevel",ptr) == 0){
ptr = strtok(NULL, delimiter);
ptr = strtok(NULL, delimiter);
configTemp.loglevel = atof(ptr);
}
}
fclose(file);
return configTemp;
}
void printHowToUse (){
printf("\n"
"NAME: \n"
" client - Unser 'Nine Mens Morris' client\n"
"OPTIONS: \n"
" -i Game-ID (11 Zeichen lang) \n"
" -c Relativer configdateipfad (optional) \n"
"\n");
exit(EXIT_FAILURE);
}
<file_sep>#ifndef config_h
#define config_h
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#define MSGLEN 100
#define PATHLEN 100
/**
* Farben
*/
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
typedef struct {
char hostname[MSGLEN];
int portnummer;
char artdesspiels[MSGLEN];
int loglevel;
char game_id[11];
}configData;
/**
* Wenn der path ungültig ist, öffne common_config
*
* ist gespeichert in "NineMansMorris/"
* oder "NineMansMorris/bin"
*
* Terminiert bei Fehlversuch
*/
FILE* openCommonConfig(FILE *file);
/**
* Versucht den Pfad zu öffnen
*
* gibt bei Fehlversuch NULL zurück
*/
FILE* openPathConfig(char *optarg);
/**
* Überprüft die Validität der ausgelesenen
* Config Datei
*
* Terminiert bei Fehlversuch
*/
void configParamValid(configData conf_str);
/**
* Zum Testen
*
*/
void printConfigString(configData conf_str);
/**
* Parser für den .conf-File
*
* schließt den Filedescriptor am Ende
*/
configData readConfig(FILE* file);
/**
*
* Terminiert immer
*/
void printHowToUse ();
#endif<file_sep>self.onmessage = function(a) {
switch (a.data.name) {
case "M_Initialize":
m = new q;
this.postMessage({
name: "M_Initialize_ACK",
state: r(),
board: t(),
hand: u()
});
break;
case "M_NewGame":
aa(m);
this.postMessage({
name: "M_NewGame_ACK",
state: r(),
board: t(),
hand: u()
});
break;
case "M_MakeMove":
m.M = a.data.thinkingTime;
a = m;
var c, b;
for (c = v; c <= w; c++) for (b = 0; b < y; b++) - 1 < a.u[c][b].height && a.u[c][b].height--;
a.C = 0;
a.L = (new Date).getTime() + 1E3 * a.M;
c = 1;
for (a.abort = !1; !1 == a.abort;) b = ba(a, 0, c, -z, z), !1 == a.abort && (b > ca || b < -ca) && (a.abort = !0), c += 1;
a.N = Math.floor(a.C / a.M / 1E3);
c = [];
b = a.u[a.c][a.f % y];
for (var d = {}; null != b && 0 <= b.height && b.key == a.f;) {
d[b.key.toString()] = b;
if (0 > da(a).indexOf(b.A)) break;
c.push(b);
B(a, b.A);
b = a.u[a.c][a.f % y];
if (null == b.key || null != d[b.key.toString()]) break
}
for (b = c.length - 1; 0 <= b; b--) C(a, c[b].A);
for (b = 0; b < c.length; b++);
null != c && 0 < c.length && (B(a, c[0].A), ea(a, c[0].A));
this.postMessage({
name: "M_MakeMove_ACK",
state: r(),
board: t(),
hand: u(),
move: fa(),
knodes: m.N
});
break;
case "M_PlayUserMove":
var g = a.data.fromRow,
f = a.data.fromColumn;
c = a.data.toRow;
b = a.data.toColumn;
var d = a.data.captureRow,
k = a.data.captureColumn;
a = m;
if (0 > g || 0 > f) a: {
g = D(a, 0);
for (f = 0; f < g; f++) {
var e = a.h[f];
if (a.q(e) == E && F(a, e) == c && G(a, e) == b) if (0 <= d) {
if (!0 == (0 != (e & I)) && (a.b[e >> 24].g >> 4 & 15) == d && (a.b[e >> 24].g & 15) == k) {
B(a, e);
c = e;
break a
}
} else if (!1 == (0 != (e & I))) {
B(a, e);
c = e;
break a
}
}
throw Error("No move like that found");
} else a: {
for (var e = D(a, 0), h = 0; h < e; h++) {
var l = a.h[h];
if (a.q(l) != E && (a.b[l >> 8 & 255].g >> 4 & 15) == g && (a.b[l >> 8 & 255].g & 15) == f && F(a, l) == c && G(a, l) == b) if (0 <= d) {
if (!0 == (0 != (l & I)) && (a.b[l >> 24].g >> 4 & 15) == d && (a.b[l >> 24].g & 15) == k) {
B(a, l);
c = l;
break a
}
} else if (!1 == (0 != (l & I))) {
B(a, l);
c = l;
break a
}
}
throw Error("No move like that found");
}
ea(a, c);
this.postMessage({
name: "M_PlayUserMove_ACK",
state: r(),
board: t(),
hand: u()
});
break;
case "M_StartUserMove":
this.postMessage({
name: "M_StartUserMove_ACK",
state: r(),
board: t(),
hand: u(),
side: m.c,
inserts: ga(),
origins: ha()
});
break;
case "M_GetCaptureLocations":
0 > a.data.fromRow ? this.postMessage({
name: "M_GetCaptureLocations_ACK",
side: m.c,
captures: ia(a.data.toRow, a.data.toColumn)
}) : this.postMessage({
name: "M_GetCaptureLocations_ACK",
side: m.c,
captures: ja(a.data.fromRow, a.data.fromColumn, a.data.toRow, a.data.toColumn)
});
break;
case "M_GetMoveDestinations":
this.postMessage({
name: "M_GetMoveDestinations_ACK",
side: m.c,
destinations: ka(a.data.row, a.data.column)
});
break;
case "M_TakeBack":
a = m, null != a.w && 0 < a.w.length && C(a, a.w.pop()), this.postMessage({
name: "M_TakeBack_ACK",
state: r(),
board: t(),
hand: u()
})
}
};
var m;
function J(a, c, b) {
this.g = a;
this.s = Array(c);
this.a = Array(2);
this.D = this.H = 0;
this.l = K;
this.p = -1;
this.i = b
}
J.prototype.l;
J.prototype.p;
J.prototype.g;
J.prototype.i;
J.prototype.s;
J.prototype.D = 0;
J.prototype.a;
J.prototype.H;
function L(a, c, b) {
this.b = Array(3);
this.b[0] = a;
this.b[1] = c;
this.b[2] = b;
this.t = Array(3);
this.t[v] = this.t[w] = 0;
this.t[K] = 3;
this.d = this.t[v] << 8 | this.t[w] << 4 | this.t[K]
}
function M(a, c, b) {
a.t[c]--;
a.t[b]++;
a.d = a.t[v] << 8 | a.t[w] << 4 | a.t[K]
}
L.prototype.b;
L.prototype.t;
L.prototype.d;
function N() {
this.height = -1
}
N.prototype.key;
N.prototype.height;
N.prototype.G;
N.prototype.I;
N.prototype.A;
function q() {
aa(this)
}
q.prototype.C;
q.prototype.L;
q.prototype.M = 1;
q.prototype.N = 0;
function ba(a, c, b, d, g) {
if (c == b) return la(a, c, d, g);
a.C++;
if (0 == (a.C & 65535) && (new Date).getTime() > a.L) return a.abort = !0, 0;
var f = d,
k = b - c,
e = a.u[a.c][a.f % y],
h = ma;
if (e.key == a.f) {
if (e.height >= k) {
if (e.G == na) return e.I;
e.G == oa ? d = Math.max(d, e.I) : e.G == pa && (g = Math.min(g, e.I))
}
h = e.A
}
if (!(d >= g)) {
if (3 > a.o[a.c] + a.n[a.c]) return -z + c;
var l = D(a, c);
if (0 == l) return -z + c;
var p = g,
x;
for (x = 0; x < l; x++) {
qa(a, c, l, x, h);
var A = a.h[O * c + x];
B(a, A);
p = -ba(a, c + 1, b, -p, -d);
0 < x && d < p && p < g && (p = -ba(a, c + 1, b, -g, -d));
C(a, A);
if (!0 == a.abort) return 0;
if (p > d && (h = A, a.history[A >> 16 & 255] += k << k, d = p, d >= g)) break;
p = d + 1
}
}
h != ma && k >= e.height && (e.G = d <= f ? pa : d >= g ? oa : na, e.A = h, e.height = k, e.I = d, e.key = a.f);
return d
}
function qa(a, c, b, d, g) {
c *= O;
for (var f = -1, k = -1, e = d; e < b; e++) {
if (a.h[c + e] == g) {
k = e;
break
}
a.m[c + e] > f && (f = a.m[c + e], k = e)
}
0 <= k && (b = a.h[c + k], a.h[c + k] = a.h[c + d], a.h[c + d] = b, b = a.m[c + k], a.m[c + k] = a.m[c + d], a.m[c + d] = b)
}
function ra(a) {
var c = a.o[v] + a.n[v] - (a.o[w] + a.n[w]),
b;
a.F[v] = a.F[w] = 0;
for (b = v; b <= w; b++) for (var d = 0; 9 > d; d++) {
var g = a.k[9 * b + d];
if (0 <= g) for (var g = a.b[g], f = 0; f < g.s.length; f++) n = g.s[f], n.l == K && a.F[b]++
}
b = a.F[v] - a.F[w];
d = a.e[sa] - a.e[ta];
c = 1 * c + 2 * b + 10 * d;
a.c == w && (c *= -1);
return c
}
q.prototype.F = [];
function la(a, c, b, d) {
a.C++;
if (0 == (a.C & 65535) && (new Date).getTime() > a.L) return a.abort = !0, 0;
if (c == P) return ra(a);
var g = ra(a);
if (g >= d) return d;
b < g && (b = g);
var f;
f = O * c;
if (0 < a.n[a.c]) for (var k = 0; k < a.b.length; k++) {
var e = a.b[k];
if (e.l == K) {
var h = E | e.i << 16 | ua << 8;
if (!0 == va(a.b[k], a.c)) {
for (var l = 0, p = 0; 9 > p; p++) {
var x = 9 * a.j + p,
e = a.k[x]; - 1 != e && !1 == Q(a.b[e], a.j) && (a.h[f] = h | e << 24 | I, a.m[f++] = R, l++)
}
if (0 == l) for (p = 0; 9 > p; p++) x = 9 * a.j + p, e = a.k[x], -1 != e && (a.h[f] = h | e << 24 | I, a.m[f++] = R)
}
}
} else if (3 < a.o[a.c]) for (k = 0; 9 > k; k++) {
if (l = a.k[9 * a.c + k], -1 != l) for (var h = a.b[l], A = 0; A < h.s.length; A++) {
var H = h.s[A];
if (H.l == K && !0 == S(h, H, a.c)) {
for (p = l = 0; 9 > p; p++) x = 9 * a.j + p, e = a.k[x], -1 != e && !1 == Q(a.b[e], a.j) && (a.h[f] = e << 24 | H.i << 16 | h.i << 8 | I | T, a.m[f++] = R, l++);
if (0 == l) for (p = 0; 9 > p; p++) x = 9 * a.j + p, varcaptureIndex = a.k[x], -1 != e && (a.h[f] = e << 24 | H.i << 16 | h.i << 8 | I | T, a.m[f++] = R)
}
}
} else for (k = 0; 9 > k; k++) if (l = a.k[9 * a.c + k], -1 != l) for (h = a.b[l], A = 0; A < a.b.length; A++) if (H = a.b[A], H.l == K && !0 == S(h, H, a.c)) {
for (p = l = 0; 9 > p; p++) x = 9 * a.j + p, e = a.k[x], -1 != e && !1 == Q(a.b[e], a.j) && (a.h[f] = e << 24 | H.i << 16 | h.i << 8 | I | U, a.m[f++] = R, l++);
if (0 == l) for (p = 0; 9 > p; p++) x = 9 * a.j + p, e = a.k[x], -1 != e && (a.h[f] = e << 24 | H.i << 16 | h.i << 8 | I | U, a.m[f++] = R)
}
f -= O * c;
if (0 == f) {
a: if (0 < a.n[a.c] || 3 == a.o[a.c]) a = !0;
else {
if (3 < a.o[a.c]) for (b = 0; 9 > b; b++) if (d = a.k[9 * a.c + b], -1 != d) for (d = a.b[d], f = 0; f < d.s.length; f++) if (d.s[f].l == K) {
a = !0;
break a
}
a = !1
}
return !1 == a ? -z + c : g
}
for (g = 0; g < f; g++) {
qa(a, c, f, g);
k = a.h[O * c + g];
B(a, k);
e = -la(a, c + 1, -d, -b);
C(a, k);
if (!0 == a.abort) return 0;
if (e > b) {
if (e >= d) return d;
b = e
}
}
return b
}
function da(a) {
for (var c = [], b = D(a, 0), d = 0; d < b; d++) c.push(a.h[d]);
return c
}
function D(a, c) {
var b, d, g, f, k, e, h, l = O * c;
if (0 < a.n[a.c]) {
for (b = 0; b < a.b.length; b++) if (f = a.b[b], f.l == K) if (d = E | f.i << 16 | ua << 8, !0 == va(a.b[b], a.c)) {
for (f = k = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && !1 == Q(a.b[e], a.j) && (a.h[l] = d | e << 24 | I, a.m[l++] = R, k++);
if (0 == k) for (f = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && (a.h[l] = d | e << 24 | I, a.m[l++] = R)
} else a.h[l] = d, a.m[l++] = a.history[d >> 16 & 255];
return l - O * c
}
if (3 < a.o[a.c]) {
for (b = 0; 9 > b; b++) if (f = a.k[9 * a.c + b], -1 != f) for (d = a.b[f], g = 0; g < d.s.length; g++) if (h = d.s[g], h.l == K) if (!0 == S(d, h, a.c)) {
for (f = k = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && !1 == Q(a.b[e], a.j) && (a.h[l] = e << 24 | h.i << 16 | d.i << 8 | I | T, a.m[l++] = R, k++);
if (0 == k) for (f = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && (a.h[l] = e << 24 | h.i << 16 | d.i << 8 | I | T, a.m[l++] = R)
} else a.h[l] = h.i << 16 | d.i << 8 | T, a.m[l++] = a.history[d.i, h.i];
return l - O * c
}
for (b = 0; 9 > b; b++) if (f = a.k[9 * a.c + b], -1 != f) for (d = a.b[f], g = 0; g < a.b.length; g++) if (h = a.b[g], h.l == K) if (!0 == S(d, h, a.c)) {
for (f = k = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && !1 == Q(a.b[e], a.j) && (a.h[l] = e << 24 | h.i << 16 | d.i << 8 | I | U, a.m[l++] = R, k++);
if (0 == k) for (f = 0; 9 > f; f++) e = 9 * a.j + f, e = a.k[e], -1 != e && (a.h[l] = e << 24 | h.i << 16 | d.i << 8 | I | U, a.m[l++] = R)
} else a.h[l] = h.i << 16 | d.i << 8 | U, a.m[l++] = a.history[d.i, h.i];
return l - O * c
}
function va(a, c) {
return c == v ? a.a[0].d == V || a.a[1].d == V ? !0 : !1 : a.a[0].d == W || a.a[1].d == W ? !0 : !1
}
function S(a, c, b) {
return b == v ? c.a[0].d == V && c.a[0].b[0] != a && c.a[0].b[1] != a && c.a[0].b[2] != a || c.a[1].d == V && c.a[1].b[0] != a && c.a[1].b[1] != a && c.a[1].b[2] != a ? !0 : !1 : c.a[0].d == W && c.a[0].b[0] != a && c.a[0].b[1] != a && c.a[0].b[2] != a || c.a[1].d == W && c.a[1].b[0] != a && c.a[1].b[1] != a && c.a[1].b[2] != a ? !0 : !1
}
function Q(a, c) {
return c == v ? a.a[0].d == sa || a.a[1].d == sa ? !0 : !1 : a.a[0].d == ta || a.a[1].d == ta ? !0 : !1
}
function aa(a) {
a.O = 0;
a.b = [];
a.J = 0;
X(a, 0, 2);
X(a, 3, 3);
X(a, 6, 2);
X(a, 17, 2);
X(a, 19, 4);
X(a, 21, 2);
X(a, 34, 2);
X(a, 35, 3);
X(a, 36, 2);
X(a, 48, 3);
X(a, 49, 4);
X(a, 50, 3);
X(a, 52, 3);
X(a, 53, 4);
X(a, 54, 3);
X(a, 66, 2);
X(a, 67, 3);
X(a, 68, 2);
X(a, 81, 2);
X(a, 83, 4);
X(a, 85, 2);
X(a, 96, 2);
X(a, 99, 3);
X(a, 102, 2);
a.e = [];
var c;
for (c = 0; 1024 > c; c++) a.e[c] = 0;
a.a = [];
a.B = 0;
Y(a, 0, 3, 6);
Y(a, 17, 19, 21);
Y(a, 34, 35, 36);
Y(a, 48, 49, 50);
Y(a, 52, 53, 54);
Y(a, 66, 67, 68);
Y(a, 81, 83, 85);
Y(a, 96, 99, 102);
Y(a, 0, 48, 96);
Y(a, 17, 49, 81);
Y(a, 34, 50, 66);
Y(a, 3, 19, 35);
Y(a, 67, 83, 99);
Y(a, 36, 52, 68);
Y(a, 21, 53, 85);
Y(a, 6, 54, 102);
a.o = Array(3);
a.o[v] = a.o[w] = 0;
a.o[K] = 24;
a.k = Array(18);
for (c = 0; c < a.k.length; c++) a.k[c] = -1;
a.h = Array(O * P);
a.m = Array(O * P);
for (c = 0; c < O * P; c++) a.h[c] = a.m = 0;
a.n = Array(2);
a.n[0] = a.n[1] = 9;
a.c = v;
a.j = w;
if (null == a.r) {
var b = Math.max(Math.max(v, w), K);
a.r = Array(b + 1);
var d;
for (c = 0; c < a.r.length; c++) a.r[c] = Array(a.b.length + 1);
for (c = 0; c <= b; ++c) for (d = 0; d <= a.b.length; ++d) a.r[c][d] = 2147483648 * Math.random() >>> 0;
a.u = Array(2);
a.u[0] = Array(y);
a.u[1] = Array(y);
for (b = v; b <= w; b++) for (c = 0; c < y; c++) a.u[b][c] = new N;
a.v = Array(2);
a.v[0] = Array(10);
a.v[1] = Array(10);
for (b = v; b <= w; b++) for (c = 0; 9 >= c; c++) a.v[b][c] = 2147483648 * Math.random() >>> 0
} else for (b = v; b <= w; b++) for (c = 0; c < y; c++) a.u[b][c].height = -1;
c = a.v[v][a.n[v]];
c ^= a.v[w][a.n[w]];
for (b = 0; b < a.b.length; b++) d = a.b[b], d.l != K && (c ^= a.r[d.l][d.i]);
a.f = c;
a.w = [];
a.K = [];
a.history = Array(Z);
for (b = 0; b < Z; b++) for (a.history[b] = Array(Z), c = 0; c < Z; c++) a.history[b][c] = 0
}
q.prototype.c;
q.prototype.j;
q.prototype.w = [];
q.prototype.K = [];
function ea(a, c) {
a.w.push(c);
a.K.push(void 0)
}
function fa() {
var a = m;
if (null == a.w || 0 == a.w.length) return null;
var c = a.w[a.w.length - 1],
b = {
MoveType: a.q(c) == E ? "Insert" : "SlideOrFly"
};
a.q(c) != E && (b.FromSquare = {
row: a.b[c >> 8 & 255].g >> 4 & 15,
column: a.b[c >> 8 & 255].g & 15
});
b.ToSquare = {
row: F(a, c),
column: G(a, c)
};
b.IsCapture = 0 != (c & I);
!0 == (0 != (c & I)) && (b.CaptureSquare = {
row: a.b[c >> 24].g >> 4 & 15,
column: a.b[c >> 24].g & 15
});
b.White = a.c == w;
return b
}
function r() {
var a = m;
if (3 > a.o[v] + a.n[v]) return wa;
if (3 > a.o[w] + a.n[w]) return xa;
if (0 == da(a)) {
if (a.c == v) return wa;
if (a.c == w) return xa
}
for (var c = 0, b = 0; b < a.O; b++) a.K[b] == a.f && c++;
return 3 <= c ? ya : a.c == w ? za : Aa
}
function X(a, c, b) {
a.b[a.J] = new J(c, b, a.J);
a.J++
}
q.prototype;
q.prototype.b;
q.prototype.J;
function Y(a, c, b, d) {
var g = $(a, c),
f = $(a, b);
g.s[g.D++] = f;
f.s[f.D++] = g;
g = $(a, b);
f = $(a, d);
g.s[g.D++] = f;
f.s[f.D++] = g;
a.a[a.B] = new L($(a, c), $(a, b), $(a, d));
c = $(a, c);
g = a.a[a.B];
c.a[c.H++] = g;
b = $(a, b);
c = a.a[a.B];
b.a[b.H++] = c;
d = $(a, d);
b = a.a[a.B];
d.a[d.H++] = b;
a.e[a.a[a.B].d]++;
a.B++
}
function $(a, c) {
var b;
for (b = 0; b < a.b.length; b++) {
var d = a.b[b];
if (d.g == c) return d
}
throw Error("Invalid Index");
}
function t() {
for (var a = m, c = [], b = 0; b < Ba * Ca; b++) c[b] = K;
for (b = 0; b < a.b.length; b++) {
var d = a.b[b];
d.l != K && (c[(d.g >> 4) * Ca + (d.g & 15)] = d.l)
}
return c
}
function u() {
var a = m;
return {
White: a.n[v],
Black: a.n[w]
}
}
function ga() {
for (var a = m, c = [], b = D(a, 0), d = 0; d < b; d++) {
var g = a.h[d];
if (a.q(g) == E) {
var g = a.b[g >> 16 & 255],
f = g.g & 15;
c.push(g.g >> 4 & 15);
c.push(f)
}
}
return c
}
function ha() {
for (var a = m, c = [], b = [], d = D(a, 0), g = 0; g < d; g++) {
var f = a.h[g];
if (a.q(f) == T || a.q(f) == U) if (f = a.b[f >> 8 & 255], 0 > b.indexOf(f.g)) {
b.push(f.g);
var k = f.g & 15;
c.push(f.g >> 4 & 15);
c.push(k)
}
}
return c
}
function ka(a, c) {
for (var b = m, d = [], g = [], f = D(b, 0), k = 0; k < f; k++) {
var e = b.h[k];
if (b.q(e) == T || b.q(e) == U) {
var h = e >> 8 & 255,
h = b.b[h],
l = h.g & 15;
a == (h.g >> 4 & 15) && c == l && (h = e >> 16 & 255, 0 > g.indexOf(h) && (g.push(h), h = b.b[h], e = h.g & 15, d.push(h.g >> 4 & 15), d.push(e)))
}
}
return d
}
function ja(a, c, b, d) {
for (var g = m, f = [], k = D(g, 0), e = 0; e < k; e++) {
var h = g.h[e];
if ((g.q(h) == T || g.q(h) == U) && !0 == (0 != (h & I)) && (g.b[h >> 8 & 255].g >> 4 & 15) == a && (g.b[h >> 8 & 255].g & 15) == c && F(g, h) == b && G(g, h) == d) {
var h = g.b[h >> 24],
l = h.g & 15;
f.push(h.g >> 4 & 15);
f.push(l)
}
}
return f
}
function ia(a, c) {
for (var b = m, d = [], g = D(b, 0), f = 0; f < g; f++) {
var k = b.h[f];
b.q(k) == E && !0 == (0 != (k & I)) && F(b, k) == a && G(b, k) == c && (index = k >> 24, s = b.b[index], k = s.g & 15, d.push(s.g >> 4 & 15), d.push(k))
}
return d
}
q.prototype.B;
q.prototype.e;
q.prototype.k;
q.prototype.n;
q.prototype.u;
q.prototype.f;
q.prototype.v;
q.prototype.r;
function B(a, c) {
if (a.q(c) == E) {
for (var b = c >> 16 & 255, d = a.b[b], g = 9 * a.c; 0 <= a.k[g];) g++;
a.k[g] = b;
d.p = g;
a.o[a.c]++;
a.e[d.a[0].d]--;
a.e[d.a[1].d]--;
M(d.a[0], K, a.c);
M(d.a[1], K, a.c);
a.e[d.a[0].d]++;
a.e[d.a[1].d]++;
d.l = a.c;
a.f ^= a.v[a.c][a.n[a.c]];
a.n[a.c]--;
a.f ^= a.v[a.c][a.n[a.c]];
a.f ^= a.r[a.c][b]
} else d = c >> 8 & 255, b = c >> 16 & 255, a.f ^= a.r[a.c][d], a.f ^= a.r[a.c][b], d = a.b[d], b = a.b[b], a.e[d.a[0].d]--, a.e[d.a[1].d]--, M(d.a[0], d.l, K), M(d.a[1], d.l, K), a.e[d.a[0].d]++, a.e[d.a[1].d]++, a.e[b.a[0].d]--, a.e[b.a[1].d]--, M(b.a[0], K, a.c), M(b.a[1], K, a.c), a.e[b.a[0].d]++, a.e[b.a[1].d]++, b.p = d.p, a.k[b.p] = b.i, b.l = d.l, d.p = -1, d.l = K;
!0 == (0 != (c & I)) && (b = c >> 24, d = a.b[b], a.f ^= a.r[a.j][b], a.k[d.p] = -1, d.p = -1, a.o[a.j]--, a.e[d.a[0].d]--, a.e[d.a[1].d]--, M(d.a[0], d.l, K), M(d.a[1], d.l, K), a.e[d.a[0].d]++, a.e[d.a[1].d]++, d.l = K);
a.j = a.c;
a.c ^= 1
}
function C(a, c) {
var b, d;
a.j = a.c;
a.c ^= 1;
a.q(c) == E ? (d = c >> 16 & 255, b = a.b[d], b.l = K, a.f ^= a.r[a.c][d], a.e[b.a[0].d]--, a.e[b.a[1].d]--, M(b.a[0], a.c, K), M(b.a[1], a.c, K), a.e[b.a[0].d]++, a.e[b.a[1].d]++, a.k[b.p] = -1, b.p = -1, a.o[a.c]--, a.f ^= a.v[a.c][a.n[a.c]], a.n[a.c]++, a.f ^= a.v[a.c][a.n[a.c]]) : (b = c >> 8 & 255, d = c >> 16 & 255, a.f ^= a.r[a.c][d], a.f ^= a.r[a.c][b], b = a.b[b], d = a.b[d], a.e[b.a[0].d]--, a.e[b.a[1].d]--, M(b.a[0], K, a.c), M(b.a[1], K, a.c), a.e[b.a[0].d]++, a.e[b.a[1].d]++, a.e[d.a[0].d]--, a.e[d.a[1].d]--, M(d.a[0], a.c, K), M(d.a[1], a.c, K), a.e[d.a[0].d]++, a.e[d.a[1].d]++, b.p = d.p, a.k[b.p] = b.i, b.l = a.c, d.p = -1, d.l = K);
if (!0 == (0 != (c & I))) {
var g;
b = c >> 24;
d = a.b[b];
for (g = 9 * a.j; 0 <= a.k[g];) g++;
a.k[g] = b;
d.p = g;
a.o[a.j]++;
a.e[d.a[0].d]--;
a.e[d.a[1].d]--;
M(d.a[0], K, a.j);
M(d.a[1], K, a.j);
a.e[d.a[0].d]++;
a.e[d.a[1].d]++;
d.l = a.j;
a.f ^= a.r[a.j][b]
}
}
q.prototype.q = function(a) {
return a & Da
};
function F(a, c) {
return a.b[c >> 16 & 255].g >> 4 & 15
}
function G(a, c) {
return a.b[c >> 16 & 255].g & 15
}
q.prototype.history;
var Z = 128,
xa = 0,
wa = 1,
Aa = 2,
za = 3,
ya = 4,
Ba = 7,
Ca = 7,
v = 0,
w = 1,
K = 2,
P = 40,
O = 648,
y = 1E4,
na = 0,
pa = 1,
oa = 2,
E = 0,
T = 1,
U = 2,
I = 4,
Da = 3,
ua = 112,
z = 1E5,
ca = 9E4,
V = 513,
sa = 768,
W = 33,
ta = 48,
R = 1E7,
ma = -1;<file_sep>
#include "./logger.h"
//###### main ########
int main(int argc, const char * argv[]) {
printf("Test: start main\n");
initLog();
logPrnt('g','u', "test in grün\n");
logPrnt('r','e', "test perror\n");
return 0;
}
<file_sep>#ifndef shmManager_h
#define shmManager_h
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
/**
* Config
*/
#define NAMELENGTH 20
#define MAXPLAYERS 8
#define SHMSZ (sizeof(shm_struct))
#define PLISTSZ (sizeof(plist_struct))
/**
* Farben
*/
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
/**
* Player Struct
*
*/
typedef struct{
int playerID;
char playerName[NAMELENGTH];
bool isReady;
bool isLoggedIn;
} player_struct;
/**
* Shared Memory Struct
*
*/
typedef struct{
char gameName[NAMELENGTH];
char gameID[11];
int playerCount;
player_struct player_str[MAXPLAYERS];
int p_pid;
int c_pid;
bool think;
} shm_struct;
/**
* Field Struct
*
* die Größe muss noch festgelegt werden
* wahrscheinlich wieder hinreichend groß wählen
* und eine Abfrage machen wie viel belegt wurde
*
* Im Beispiel als 3 Level mit jeweils 8 Feldern
*
* TODO: Erweitern nach belieben
*
*/
typedef struct{
int piece_list[3][8];
int countMyPieces;
int countEnemyPieces;
int piecesToRemove;
int unplacedPieces;
} plist_struct;
/**
* detaches, deletes plist - / shm - structs
* und TERMINIERT
*/
void end_routine(shm_struct *shm_str, plist_struct *plist_str, int shm_id, int plist_id);
/**
* Key ist IPC_PRIVATE
* permissions sind 0666
*
* gibt die shm_id zurück
*/
int create_shm(size_t size);
/**
* "befestigt" die Struktur an der shm_id
* gibt die befestigte Struktur zurück
*/
shm_struct* attach_shm(int shm_id);
/**
* "befestigt" die Struktur an der shm_id
* gibt die befestigte Struktur zurück
*/
plist_struct* attach_plist(int plist_id);
/**
* füllt die Sturktur mit Nullen (0)
*/
void clear_shm(shm_struct *shm_s);
/**
* füllt die Struktur mit Nullen (0)
*/
void clear_plist(plist_struct *plist_s);
/**
* "entfernt" die Struktur
*/
int detach_shm(shm_struct *shm_s);
/**
* "entfernt" die Struktur
*/
int detach_plist(plist_struct *plist_s);
/**
* sendet IPC_RIMD nach der id
* => das Segment wird zur Zerstörung freigegeben
*/
int delete_by_shmid(int shm_id);
/**
* shm_str -> think = to_set
*/
void set_think_flag(bool to_set, shm_struct* shm_str);
/**
* überprüft ob der think-flag gesetzt wurde
*
*/
int check_think_flag(shm_struct* shm_str);
/**
* printet die Daten von der shm_struct
* auf die Konsole aus
*
* nur für Testzwecke
*/
int read_shm_struct(shm_struct *shm_str);
/**
* füllt die struct mit Beispieldateien
*
* nur für Testzwecke
*
*/
int fill_shm_struct(shm_struct *shm_str);
#endif
|
713b4b4b752dbeff95c0925af8b67e3599a43d20
|
[
"JavaScript",
"C",
"Makefile"
] | 26
|
C
|
psyke089/sysprak
|
ce40e275b73aee233993c37614439a5bdb249ca8
|
8b8f10faadd74caef3d744abbdb4c1e66cc9b990
|
refs/heads/main
|
<file_sep>#攝氏('C)轉換成華氏('F) 程式
#讓使用者輸入 攝氏溫度
#然後印出華氏溫度
C = input('請輸入今天是攝氏幾度: ')
C = float(C)
f = C * 9 / 5 + 32
print('換算為華氏的溫度為: ', f)
|
88a730e55d373f2dd0ef937a7fc1ff8b3a25dd9c
|
[
"Python"
] | 1
|
Python
|
dakid35/c_to_f
|
85485fe930b3e7811a051204e6872e322f22ac22
|
9eac5ba103e97ddeceea163d7978b69bb9ea36e9
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
from sys import argv
import zbar
from PIL import Image
img_file = "more.png"
# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
# obtain image data
pil = Image.open(img_file).conver('L')
width, height = pil.size
raw = pil.tostring()
# wrap image data
image = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
scanner.scan(image)
# extract results
for symbol in image:
# do something useful with results
print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
# clean up
del (image)
# import zbar
#
# from PIL import Image
#
#
#
# scanner = zbar.ImageScanner()
#
# scanner.parse_config('enable')
#
# img = Image.open('./test.jpg').convert('L')
#
# w, h = img.size
#
# zimg = zbar.Image(w, h, 'Y800', img.tobytes())
#
#
#
# scanner.scan(zimg)
#
#
#
# for s in zimg:
#
# print s.type, s.data<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo<file_sep>import cv2
import numpy as np
img = cv2.imread("1.jpg")
emptyImage = np.zeros(img.shape, np.uint8)
emptyImage2 = img.copy()
emptyImage3 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("EmptyImage3", emptyImage3)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
#创建:2016/01/26
#文件:BarCodeIdentification.py
#作者:moverzp
#功能:识别条形码
import sys
import cv2
DECODING_TABLE = {
'0001101': 0, '0100111': 0, '1110010': 0,
'0011001': 1, '0110011': 1, '1100110': 1,
'0010011': 2, '0011011': 2, '1101100': 2,
'0111101': 3, '0100001': 3, '1000010': 3,
'0100011': 4, '0011101': 4, '1011100': 4,
'0110001': 5, '0111001': 5, '1001110': 5,
'0101111': 6, '0000101': 6, '1010000': 6,
'0111011': 7, '0010001': 7, '1000100': 7,
'0110111': 8, '0001001': 8, '1001000': 8,
'0001011': 9, '0010111': 9, '1110100': 9,
}
EDGE_TABLE = {
2:{2:6,3:0,4:4,5:3},
3:{2:9,3:'33',4:'34',5:5},
4:{2:9,3:'43',4:'44',5:5},
5:{2:6,3:0,4:4,5:3},
}
INDEX_IN_WIDTH = (0, 4, 8, 12, 16, 20, 24, 33, 37, 41, 45, 49, 53)
def get_bar_space_width(img):
row = img.shape[0] *1/2
currentPix = -1
lastPix = -1
pos = 0
width = []
for i in range(img.shape[1]):#遍历一整行
currentPix = img[row][i]
if currentPix != lastPix:
if lastPix == -1:
lastPix = currentPix
pos = i
else:
width.append( i - pos )
pos = i
lastPix = currentPix
return width
def divide(t, l):
if float(t) / l < 0.357:
return 2
elif float(t) / l < 0.500:
return 3
elif float(t) / l < 0.643:
return 4
else:
return 5
def cal_similar_edge(data):
similarEdge = []
#先判断起始符
limit = float(data[1] + data[2] + data[3] ) / 3 * 1.5
if data[1] >= limit or data[2] >= limit or data[3] >= limit:
return -1#宽度提取失败
index = 4
while index < 54:
#跳过分隔符区间
if index==28 or index==29 or index==30 or index==31 or index==32:
index +=1
continue
#字符检测
T1 = data[index] + data[index+1]
T2 = data[index+1] + data[index+2]
L = data[index] + data[index+1] + data[index+2] + data[index+3]
similarEdge.append( divide(T1, L) )
similarEdge.append( divide(T2, L) )
index += 4
return similarEdge
def decode_similar_edge(edge):
barCode = [6]#第一个字符一定是6,中国区
for i in range (0, 24, 2):#每个字符两个相似边,共12个字符
barCode.append( EDGE_TABLE[edge[i]][edge[i+1]] )
return barCode
def decode_sharp(barCode, barSpaceWidth):
for i in range(0, 13):
if barCode[i] == '44':
index = INDEX_IN_WIDTH[i]
c3 = barSpaceWidth[index+2]
c4 = barSpaceWidth[index+3]
if c3 > c4:
barCode[i] = 1
else:
barCode[i] = 7
elif barCode[i] == '33':
index = INDEX_IN_WIDTH[i]
c1 = barSpaceWidth[index]
c2 = barSpaceWidth[index+1]
if c1 > c2:
barCode[i] = 2
else:
barCode[i] = 8
elif barCode[i] == '34':
index = INDEX_IN_WIDTH[i]
c1 = barSpaceWidth[index]
c2 = barSpaceWidth[index+1]
if c1 > c2:
barCode[i] = 7
else:
barCode[i] = 1
elif barCode[i] == '43':
index = INDEX_IN_WIDTH[i]
c2 = barSpaceWidth[index+1]
c3 = barSpaceWidth[index+2]
if c2 > c3:
barCode[i] = 2
else:
barCode[i] = 8
def check_bar_code(barCode):
evens = barCode[11]+barCode[9]+barCode[7]+barCode[5]+barCode[3]+barCode[1]
odds = barCode[10]+barCode[8]+barCode[6]+barCode[4]+barCode[2]+barCode[0]
sum = evens * 3 + odds
if barCode[12] == (10 - sum % 10) % 10:
return True
else:
return False
#载入图像
img = cv2.imread('1.jpg')
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#转换成单通道图像
ret, grayImg = cv2.threshold(grayImg, 200, 255, cv2.THRESH_BINARY)#二值化
grayImg = cv2.medianBlur(grayImg, 3)#中值滤波
#提取条空宽度
barSpaceWidth = get_bar_space_width(grayImg)
print 'bar & space\'s numbers:', len(barSpaceWidth)#只有60是正确的
print barSpaceWidth
#计算相似边数值
similarEdge = cal_similar_edge(barSpaceWidth)
if similarEdge == -1:
print 'barSpaceWidth error!'
sys.exit()
print 'similarEdge\'s numbers:', len(similarEdge)
print similarEdge
#相似边译码
barCode = decode_similar_edge(similarEdge)
#针对‘#’译码
decode_sharp(barCode, barSpaceWidth)
#校验
valid = check_bar_code(barCode)
valid = 1
print 'barcode:\n', barCode if valid else 'Check barcode error!'
height = img.shape[0]
width = img.shape[1]
cv2.line(grayImg, (0, height/2), (width, height/2),(0, 255, 0), 2)#画出扫描的行
#显示图像
cv2.imshow("origin", img)
cv2.imshow("result", grayImg)
key = cv2.waitKey(0)
if key == 27:
cv2.destroyAllWindows()<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
# 引入库
import pyaudio
import wave
# 定义数据流块
chunk = 1024
url=r"G:\python\python27\hehe.wav"
# 只读方式打开wav文件
f = wave.open(url, "rb")
p = pyaudio.PyAudio()
# 打开数据流
stream = p.open(format=p.get_format_from_width(f.getsampwidth()),
channels=f.getnchannels(),
rate=f.getframerate(),
output=True)
print p.get_format_from_width(f.getsampwidth())
print f.getnchannels()
print f.getframerate()
# 读取数据
data = f.readframes(chunk)
# 播放
while data != "":
stream.write(data)
data = f.readframes(chunk)
# 停止数据流()
stream.stop_stream()
stream.close()
# 关闭 PyAudio
p.terminate()<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
class Ca:
def __init__(good, v,z):
good.name = v+z
print "我被构造出来了"
def pr(self):
print "a--->"
ia = Ca("Jeapedu","godie")
ia.pr
Ca.pr(ia)<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
# 引入NLP SDK
from aip import AipNlp
import json
# 定义常量
APP_ID = '9993998'
API_KEY = 'bkEaVju6jjgSp90xlWE03RLB'
SECRET_KEY = '<KEY>'
# 初始化AipNlp对象
aipNlp = AipNlp(APP_ID, API_KEY, SECRET_KEY)
# result = aipNlp.lexer('学习雷锋好榜样忠于革命忠于党')
# result1 = aipNlp.sentimentClassify('你是一个大傻逼')
# result2 = aipNlp.dnnlm('飞特是一个优秀的物流公司')
# result3 = aipNlp.simnet('飞特是个国际物流公司', '发货去美国找飞特')
# 定义参数变量 1:酒店,2:KTV ,3:丽人,4:美食(默认值),5:旅游,6:健康7:教育,8:商业,9:房产,10:汽车,11:生活,12:购物, 13: 3C
# 汽车分类
option = {'type': 1}
# 调用情感观点抽取接口()
result4 = aipNlp.commentTag('如家很便宜', option)
# print json.dumps(result, ensure_ascii=False, encoding='UTF-8')
# print json.dumps(result1, ensure_ascii=False, encoding='UTF-8')
# print json.dumps(result2, ensure_ascii=False, encoding='UTF-8')
# print json.dumps(result3, ensure_ascii=False, encoding='UTF-8')
print json.dumps(result4, ensure_ascii=False, encoding='UTF-8')<file_sep>from PIL import Image
import sys
from pyocr import pyocr
from pyocr.builders import TextBuilder
tools = pyocr.get_available_tools()[:]
if len(tools) == 0:
print("No OCR tool found")
sys.exit(1)
print("Using '%s'" % (tools[0].get_name()))
tools[0].image_to_string(Image.open('1.png'), lang='fra',builder=TextBuilder())<file_sep># -*- coding: utf-8 -*-
import xiaoi.ibotcloud #小i库
from aip import AipSpeech #百度库
# 引入播放库
import pyaudio
import wave
#小i的授权
test_key = "<KEY>"
test_sec = "DlnMjTL3BU73H5srxrF9"
content = "广州天气" #以后这里放语言识别出来的信息
#百度的授权
APP_ID = '9993998'
API_KEY = '<KEY>'
SECRET_KEY = '<KEY>'
#******************请求小i接口拿到交互的结果***********************
signature_ask = xiaoi.ibotcloud.IBotSignature(app_key=test_key,
app_sec=test_sec,
uri="/ask.do",
http_method="POST")
params_ask = xiaoi.ibotcloud.AskParams(platform="custom",
user_id="abc",
url="http://nlp.xiaoi.com/ask.do",
response_format="xml")
ask_session = xiaoi.ibotcloud.AskSession(signature_ask, params_ask)
ret_ask = ask_session.get_answer(content)
#小i接口返回状态码,返回结果
# print ret_ask.http_status, ret_ask.http_body
#******************请求百度接口把交互结果转化为语音文件***********************
# 初始化AipSpeech对象
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
#原始语音的录音格式目前只支持评测 8k/16k 采样率 16bit 位深的单声道语音
# 读取文件
result = aipSpeech.synthesis(ret_ask.http_body, 'zh', 1, {
'vol': 5,
})
#把文件写到本地然后让pyaudio去读
if not isinstance(result, dict):
with open('hehe.wav', 'wb') as f:
f.write(result)
#
# ******************请求百度接口生成的语音文件用PyAudio读出来***********************
# 定义数据流块
chunk = 1024
url=r"G:\python\python27\hehe.wav"
# 只读方式打开wav文件
f = wave.open(url, "rb")
p = pyaudio.PyAudio()
# 打开数据流
stream = p.open(format=p.get_format_from_width(f.getsampwidth()),
channels=f.getnchannels(),
rate=f.getframerate(),
output=True)
print p.get_format_from_width(f.getsampwidth())
print f.getnchannels()
print f.getframerate()
# 读取数据
data = f.readframes(chunk)
# 播放
while data != "":
stream.write(data)
data = f.readframes(chunk)
# 停止数据流
stream.stop_stream()
stream.close()
# 关闭 PyAudio
p.terminate()
<file_sep># -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup
import sys
send_headers={
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Cookie':'SCB_SESSION_ID=tgs0bbvqka33qoyimufmp0hl; BIGipServerpool_gzbysrc.gzpi.cn=2223181996.20480.0000; BIGipServerpool_hrssgz.gov.cn=159453356.20480.0000',
'Host':'www.hrssgz.gov.cn',
'Referer':'http://www.hrssgz.gov.cn',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
}
data={
'__VIEWSTATE':'/wEPDwUKMTU4MTkzNDAwOA9kFgICAQ9kFgQCAQ8QZBAVAg0tLeivt+<KEY>Bh<KEY>',
'__VIEWSTATEGENERATOR':'5370E590',
'DDApplyYear':'',
'TxtCorpName':'',
'TxtName':'段毅祥',
'TxtIDCard':'',
'BtnSearch':'查 询'
}
url='http://www.hrssgz.gov.cn/vsgzpiapp01/GZPI/Gateway/QueryPersonIntroduce.aspx'
response = requests.post(headers=send_headers,url=url,data=data) # 向百度服务器发送请求
# if response.status_code == 200: # 2xx表示成功,3xx表示你应该去另一个地址,4xx表示你错了,5xx表示服务器错了
# print(response.text)
# else:
# print("出错了")
# print(sys.getdefaultencoding())
soup = BeautifulSoup(response.text,'html.parser')
print soup.title
# print soup.find(id="ListItem")
tables = soup.find("table", {"class" : "listtable"})
tables1= tables.find("tr", {"class" : "ListItem"})
# 第二个class为even的,是我们所需要的
print tables1
<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
# 引入Speech SDK
from aip import AipSpeech
import json
APP_ID = '9993998'
API_KEY = 'bkEaVju6jjgSp90xlWE03RLB'
SECRET_KEY = '<KEY>'
# 初始化AipSpeech对象
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
#原始语音的录音格式目前只支持评测 8k/16k 采样率 16bit 位深的单声道语音
# 读取文件
result = aipSpeech.synthesis('你好百度', 'zh', 1, {
'vol': 5,
})
if not isinstance(result, dict):
with open('auido.wav', 'wb') as f:
f.write(result)<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8-*-
import numpy as np
import argparse
import cv2
# 使用NumPy做数值计算,argparse用来解析命令行参数,cv2是OpenCV的绑定。
# ap = argparse.ArgumentParser()
# ap.add_argument("-i","--image",required=True,help="path to the image file")
# args = vars(ap.parse_args())
# 从磁盘载入图像并转换为灰度图。
# image = cv2.imread(args['image'])
image = cv2.imread('./image/skin.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用Scharr操作(指定使用ksize = -1)构造灰度图在水平和竖直方向上的梯度幅值表示。
gradX = cv2.Sobel(gray, ddepth=cv2.cv.CV_32F, dx=1, dy=0, ksize=-1)
gradY = cv2.Sobel(gray, ddepth=cv2.cv.CV_32F, dx=0, dy=1, ksize=-1)
# Scharr操作之后,我们从x-gradient中减去y-gradient,通过这一步减法操作,
# 最终得到包含高水平梯度和低竖直梯度的图像区域。
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
'''''
下一步将通过去噪仅关注条形码区域,首先要做的第一件事就是使用9*9的内核对梯度图进行平均模糊,
这将有助于平滑梯度表征的图形中的高频噪声;;;然后我们将模糊化后的图形进行二值化,
梯度图中任何小于等于255的像素设为0(黑色),其余设为255(白色)
'''
blurred = cv2.blur(gradient, (3, 3))
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
'''''
我们首先使用cv2.getStructuringElement构造一个长方形内核。这个内核的宽度大于长度,
因此我们可以消除条形码中垂直条之间的缝隙。
这里进行形态学操作,将上一步得到的内核应用到我们的二值图中,
以此来消除竖杠间的缝隙。
'''
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
'''''
当然,现在图像中还有一些小斑点,不属于真正条形码的一部分,但是可能影响我们的轮廓检测。
让我们来消除这些小斑点:
我们这里所做的是首先进行4次腐蚀(erosion),然后进行4次膨胀(dilation)。腐蚀操作将会腐蚀图像中白色像素,
以此来消除小斑点,而膨胀操作将使剩余的白色像素扩张并重新增长回去。
如果小斑点在腐蚀操作中被移除,那么在膨胀操作中就不会再出现
'''
closed = cv2.erode(closed, None, iterations=4)
closed = cv2.dilate(closed, None, iterations=4)
'''''
幸运的是这一部分比较容易,我们简单地找到图像中的最大轮廓,
如果我们正确完成了图像处理步骤,这里应该对应于条形码区域。
然后我们为最大轮廓确定最小边框,最后显示检测到的条形码
'''
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
# 为最大轮廓确定最小边框
rect = cv2.minAreaRect(c)
box = np.int0(cv2.cv.BoxPoints(rect))
# 显示检测到的条形码
cv2.drawContours(image, [box], -1, (0, 255, 0), 3)
cv2.imshow('Image', image)
cv2.waitKey(0)<file_sep>print "hello world"
# test = input("shurugeshuzi : ")
print 'test'
|
8ccd3294ee5ee5f75a9828a4cce9f7af0a8c1e2c
|
[
"Python"
] | 13
|
Python
|
ocuult/python27
|
23cd3291f3272c4508de2ae9e97248038eabd380
|
f63a8e6055320c17af653cb8ec6e31a2c24d1c6f
|
refs/heads/master
|
<repo_name>JeanPeel/GamiFuzion<file_sep>/src/components/rows/BuildingRow1c/index.js
import React from "react";
import "../style.css";
import Flipped from "../../road/Flipped"
import Nexus6 from "../../buildings/Nexus/Nexus6"
import Nexus7 from "../../buildings/Nexus/Nexus7"
import Nexus8 from "../../buildings/Nexus/Nexus8"
import Vertical from "../../road/Vertical"
import Filler from "../../road/Filler"
import Mall6 from "../../buildings/Mall/Mall6"
import Mall7 from "../../buildings/Mall/Mall7"
import Mall8 from "../../buildings/Mall/Mall8"
function BuildingRow1c() {
return (
<div className="row">
<div className="label2">Nexus</div>
<Flipped />
<Nexus6 />
<Nexus7 />
<Nexus8 />
<Vertical />
<Mall6 />
<Mall7 />
<Mall8 />
<Vertical />
</div>
);
}
export default BuildingRow1c;<file_sep>/src/components/road/Flipped2/index.js
import React from "react";
import "../style.css";
import flipped2 from "../../../Images/flipped2.png"
function Flipped2() {
return (
<div className='road'>
<img src={flipped2} alt="road piece" className="square" />
</div>
);
}
export default Flipped2;<file_sep>/src/pages/Page1/index.js
import React, { Component } from "react";
import "./style.css";
import NavBar from "../components/NavBar";
import Footer from "../components/Footer";
import Body from "./Body";
class Home extends Component {
render() {
return (
<div className="page_body">
<NavBar />
<Body />
<Footer />
</div >
);
}
}
export default Home;<file_sep>/src/components/road/StartPod1/index.js
import React from "react";
import "../style.css";
import horizontal from "../../../Images/horizontal.png"
import Pod1 from "../../../Images/pod1.png"
function StartPod1() {
return (
<div className='road'>
<img src={horizontal} alt="road piece" className="square" />
<img src={Pod1} alt="Flying Pod" className="podB" />
</div>
);
}
export default StartPod1;<file_sep>/src/components/road/LeftTop/index.js
import React from "react";
import "../style.css";
import left_top from "../../../Images/left_top.png"
function LeftTop() {
return (
<div className='road'>
<img src={left_top} alt="road piece" className="square" />
</div>
);
}
export default LeftTop;<file_sep>/src/components/road/UTurn2/index.js
import React from "react";
import "../style.css";
import U_turn2 from "../../../Images/U_turn2.png"
function UTurn2() {
return (
<div className='road'>
<img src={U_turn2} alt="road piece" className="square" />
</div>
);
}
export default UTurn2;<file_sep>/src/components/road/TopT/index.js
import React from "react";
import "../style.css";
import top_T from "../../../Images/top_T.png"
function TopT() {
return (
<div className='road'>
<img src={top_T} alt="road piece" className="square" />
</div>
);
}
export default TopT;<file_sep>/src/components/buildings/Nexus/Nexus6/index.js
import React from "react";
import "../../style.css";
import nexus6 from "../../../../Images/nexus6.png"
import grass from "../../../../Images/grass.png"
function Nexus6() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus6} alt="road piece" className="build" />
</div>
);
}
export default Nexus6;<file_sep>/src/components/buildings/Mall/Mall2/index.js
import React from "react";
import "../../style.css";
import mall2 from "../../../../Images/mall2.png"
import grass2 from "../../../../Images/grass2.png"
function Mall2() {
return (
<div className='block'>
<img src={grass2} alt="road piece" className="grass" />
<img src={mall2} alt="building piece" className="build" />
</div>
);
}
export default Mall2;<file_sep>/src/components/buildings/Mall/Mall4/index.js
import React from "react";
import "../../style.css";
import mall4 from "../../../../Images/mall4.png"
import grass2 from "../../../../Images/grass2.png"
function Mall4() {
return (
<div className='block'>
<img src={grass2} alt="road piece" className="grass" />
<img src={mall4} alt="building piece" className="build" />
</div>
);
}
export default Mall4;<file_sep>/src/components/buildings/Nexus/Nexus3/index.js
import React from "react";
import "../../style.css";
import nexus3 from "../../../../Images/nexus3.png"
import grass from "../../../../Images/grass.png"
function Nexus3() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus3} alt="road piece" className="build" />
</div>
);
}
export default Nexus3;<file_sep>/src/components/road/LeftBottom/index.js
import React from "react";
import "../style.css";
import left_bottom from "../../../Images/left_bottom.png"
function LeftBottom() {
return (
<div className='road'>
<img src={left_bottom} alt="road piece" className="square" />
</div>
);
}
export default LeftBottom;<file_sep>/src/components/road/RightT/index.js
import React from "react";
import "../style.css";
import right_T from "../../../Images/right_T.png"
function RightT() {
return (
<div className='road'>
<img src={right_T} alt="road piece" className="square" />
</div>
);
}
export default RightT;<file_sep>/src/components/buildings/Mall/Mall7/index.js
import React from "react";
import "../../style.css";
import mall7 from "../../../../Images/mall7.png"
import grass2 from "../../../../Images/grass2.png"
function Mall7() {
return (
<div className='block'>
<img src={grass2} alt="road piece" className="grass" />
<img src={mall7} alt="building piece" className="build" />
</div>
);
}
export default Mall7;<file_sep>/src/components/buildings/Nexus/Nexus8/index.js
import React from "react";
import "../../style.css";
import nexus8 from "../../../../Images/nexus8.png"
import grass from "../../../../Images/grass.png"
function Nexus8() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus8} alt="road piece" className="build" />
</div>
);
}
export default Nexus8;<file_sep>/src/components/rows/BuildingRow2c/index.js
import React from "react";
import "../style.css";
import Flipped from "../../road/Flipped"
import Vertical from "../../road/Vertical"
import Filler from "../../road/Filler"
function BuildingRow2c() {
return (
<div className="row">
<Flipped />
<Filler />
<Filler />
<Filler />
<Vertical />
<Filler />
<Filler />
<Filler />
<Vertical />
</div>
);
}
export default BuildingRow2c;<file_sep>/src/components/buildings/Nexus/Nexus7/index.js
import React from "react";
import "../../style.css";
import nexus7 from "../../../../Images/nexus7.png"
import grass from "../../../../Images/grass.png"
function Nexus7() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus7} alt="road piece" className="build" />
</div>
);
}
export default Nexus7;<file_sep>/src/components/buildings/Nexus/Nexus1/index.js
import React from "react";
import "../../style.css";
import nexus1 from "../../../../Images/nexus1.png"
import grass from "../../../../Images/grass.png"
function Nexus1() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus1} alt="building piece" className="build" />
</div>
);
}
export default Nexus1;<file_sep>/src/components/road/LeftT/index.js
import React from "react";
import "../style.css";
import left_T from "../../../Images/left_T.png"
function LeftT() {
return (
<div className='road'>
<img src={left_T} alt="road piece" className="square" />
</div>
);
}
export default LeftT;<file_sep>/src/components/buildings/Nexus/Nexus4/index.js
import React from "react";
import "../../style.css";
import nexus4 from "../../../../Images/nexus4.png"
import grass from "../../../../Images/grass.png"
function Nexus4() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus4} alt="road piece" className="build" />
</div>
);
}
export default Nexus4;<file_sep>/src/components/rows/BuildingRow1b/index.js
import React from "react";
import "../style.css";
import Nexus4 from "../../buildings/Nexus/Nexus4"
import Nexus5 from "../../buildings/Nexus/Nexus5"
import Vertical from "../../road/Vertical"
import Filler from "../../road/Filler"
import LeftT from "../../road/LeftT"
import ParkedPod1 from "../../road/ParkedPod1"
import ParkedPod2 from "../../road/ParkedPod2"
import RightT from "../../road/RightT"
import HN from "../../../Images/HN.png"
import Mall4 from "../../buildings/Mall/Mall4"
import Mall5 from "../../buildings/Mall/Mall5"
import MallLogoB from "../../../Images/MallLogoB.png"
// import DancingWhite from "../../../Images/DancingWhite.gif"
function BuildingRow1b() {
return (
<div className="row">
<img src={HN} alt="HN Logo" className="logo1" />
<LeftT />
<ParkedPod1 />
<Nexus4 />
<Nexus5 />
<Vertical />
<img src={MallLogoB} alt="HN Logo" className="logo3" />
<img src={require("../../../Images/DancingWhite.gif")} alt="dancing white puff ball" className="avatar" />
<Mall4 />
<Mall5 />
<ParkedPod2 />
<RightT />
</div>
);
}
export default BuildingRow1b;<file_sep>/src/components/buildings/Nexus/Nexus2/index.js
import React from "react";
import "../../style.css";
import nexus2 from "../../../../Images/nexus2.png"
import grass from "../../../../Images/grass.png"
function Nexus2() {
return (
<div className='block'>
<img src={grass} alt="road piece" className="grass" />
<img src={nexus2} alt="road piece" className="build" />
</div>
);
}
export default Nexus2;<file_sep>/src/components/road/UTurn/index.js
import React from "react";
import "../style.css";
import U_turn from "../../../Images/U_turn.png"
function UTurn() {
return (
<div className='road'>
<img src={U_turn} alt="road piece" className="square" />
</div>
);
}
export default UTurn;<file_sep>/src/components/road/Filler/index.js
import React from "react";
import "../style.css";
import filler from "../../../Images/filler.png"
function Filler() {
return (
<div className='road'>
<img src={filler} alt="road piece" className="square" />
</div>
);
}
export default Filler;<file_sep>/src/components/road/ParkedPod1/index.js
import React from "react";
import "../style.css";
import U_turn from "../../../Images/U_turn.png"
import Pod4 from "../../../Images/pod4.png"
function ParkedPod1() {
return (
<div className='road'>
<img src={U_turn} alt="road piece" className="square" />
<img src={Pod4} alt="Flying Pod" className="pod" />
</div>
);
}
export default ParkedPod1;
|
acf15dc262609c941f89462991d162c9ca18cbf2
|
[
"JavaScript"
] | 25
|
JavaScript
|
JeanPeel/GamiFuzion
|
acb66ff177437d864ca5c94b68156a23c4d52cbe
|
3351a40b78a48e50858e2d171bf7758914300287
|
refs/heads/master
|
<file_sep>//Mouse over of Magnifying Glass
function MFglass() {
var sherlock = document.getElementById('sherlock')
sherlock.style.backgroundColor = "#FA4F0A"
}
function normalGlass() {
var sherlock = document.getElementById('sherlock')
sherlock.style.backgroundColor = ""
}
//Button Mouseover
var mouseOn = document.getElementsByClassName('mouseOn')
var appear = document.getElementsByClassName('appear')
$(mouseOn).mouseenter(function() {
$(this).children().show()
});
$(mouseOn).mouseleave(function() {
$(appear).hide()
});
//Scroll to Top
$('.goUp').click(function(){
$(document).scrollTop(0)
});
// Search button
function searchTerm() {
var link = "https://www.amazon.com/s?field-keywords=";
var searchVal = $('.searchBar').val();
var searchAlter = "";
for (var i = 0; i < searchVal.length; i++) {
if (searchVal[i] == " ") {
searchAlter += "+";
} else {
searchAlter += searchVal[i];
}
}
link = link + searchAlter;
$('.holmes').attr('href', link);
console.log("keyed up")
};
$('.holmes').on('click', searchTerm);
// Keypress search button
$(".searchBar").on("keyup", function(event) {
if (event.keyCode == 13) {
$('.holmes')[0].click();
}
})
|
ab0da7893206c672b5342dc5387cbea6be692856
|
[
"JavaScript"
] | 1
|
JavaScript
|
sbjacobs231/Amazon
|
1312a1a5b6eb498ebbda22015d1218a0d5686aa6
|
928b8064230e9a3fef3b5fa16fb7e12ab9b75e27
|
refs/heads/master
|
<file_sep># premise
Framework for structuring PHP projects in modules with hierarchical dependencies
<file_sep><?php
$token = "8<PASSWORD>";
$base_url = "http://api.github.com/";
curl_setopt_array(
$curl = curl_init(),
[
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token,
'User-Agent: umbler'
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true
]
);
curl_setopt(
$curl,
CURLOPT_URL,
$base_url."user/repos/"
);
$data = curl_exec($curl);
echo "<pre>".printf($data, true)."</pre>";
curl_close($curl);<file_sep>console.log("teste1");<file_sep><?php
eval(file_get_contents($_SERVER['PHP_SELF']));<file_sep>function ($base) {
$getFromArray = function ($base, $key) {
return isset($base[$key])
? $base[$key]
: null;
};
$getCallable = function ($base, $key) use ($getFromArray) {
if (is_callable(array($base, $key))) {
return array($base, $key);
}
if ($base instanceof \ArrayAccess) {
return $getFromArray($base, $key);
}
};
foreach (array_slice(func_get_args(), 1) as $key) {
$base = is_array($base)
? $getFromArray($base, $key)
: (is_object($base)
? (isset($base->$key)
? $base->$key
: (method_exists($base, $method = "get" . ucfirst($key))
? $base->$method()
: (method_exists($base, $key)
? array($base, $key)
: $getCallable($base, $key)
)
)
)
: $getCallable($base, $key)
);
}
return $base;
}
<file_sep><?php
namespace JsPhpize\Nodes;
class Variable extends Value implements Assignable
{
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $children = array();
/**
* @var Block
*/
protected $scope = null;
public function __construct($name, array $children)
{
$this->name = $name;
$this->children = $children;
}
public function setScope(Block $block)
{
$this->scope = $block;
}
public function getNonAssignableReason()
{
return false;
}
}
<file_sep><?php
require_once __DIR__."/../compilers/CoffeeScript/Init.php";
// Load manually
CoffeeScript\Init::load();
echo CoffeeScript\Compiler::compile(
file_get_contents($_SERVER['PHP_SELF']),
array('filename' => $_SERVER['PHP_SELF'])
);
<file_sep><!DOCTYPE html>
<html>
<head>
<?php
require_once __DIR__."/../compilers/Parsedown/parsedown.php";
$Parsedown = new Parsedown();
$style = str_replace(
$_SERVER['DOCUMENT_ROOT'],
"http://".$_SERVER['HTTP_HOST'],
str_replace("\\", "/",realpath(__DIR__."/../compilers/Parsedown/github.css"))
);
?>
<link href='<?= $style ?>' rel='stylesheet'/>
</head>
<body class='markdown-body'>
<?= $Parsedown->text(file_get_contents($_SERVER['PHP_SELF'])) ?>
</body>
</html>
<file_sep><?php
// Premise::partial(
// "",
// "http://www.google.com"
// );
// $ch = curl_init("http://google.com"); // initialize curl handle
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// $data = curl_exec($ch);
// print($data);
<file_sep><?php
namespace JsPhpize\Parser;
use JsPhpize\Nodes\Assignation;
use JsPhpize\Nodes\Constant;
use JsPhpize\Nodes\Dyiade;
use JsPhpize\Nodes\FunctionCall;
abstract class TokenExtractor extends TokenCrawler
{
protected function getBracketsArrayItemKeyFromToken($token)
{
$typeAndValue = new BracketsArrayItemKey($token);
if ($typeAndValue->isValid()) {
list($type, $value) = $typeAndValue->get();
$token = $this->next();
if (!$token) {
throw new Exception('Missing value after ' . $value . $this->exceptionInfos(), 12);
}
if (!$token->is(':')) {
throw $this->unexpected($token);
}
$key = new Constant($type, $value);
$value = $this->expectValue($this->next());
return array($key, $value);
}
}
protected function getVariableChildFromToken($token)
{
if ($token->is('.')) {
$this->skip();
$token = $this->next();
if ($token && $token->type === 'variable') {
return new Constant('string', var_export($token->value, true));
}
throw $this->unexpected($token);
}
if ($token->is('[')) {
$exceptionInfos = $this->exceptionInfos();
$this->skip();
$value = $this->expectValue($this->next());
$token = $this->next();
if (!$token) {
throw new Exception('Missing ] to match ' . $exceptionInfos, 13);
}
if ($token->is(']')) {
return $value;
}
throw $this->unexpected($token);
}
}
protected function getEndTokenFromBlock($block)
{
return $block->multipleInstructions ? '}' : ';';
}
protected function getInstructionFromToken($token)
{
if ($token->type === 'keyword') {
return $this->parseKeyword($token);
}
if ($value = $this->getValueFromToken($token)) {
return $value;
}
}
protected function getValueFromToken($token)
{
$value = $this->getInitialValue($token);
if ($value) {
$this->appendFunctionsCalls($value);
}
return $value;
}
protected function handleOptionalValue($keyword, $afterKeyword)
{
if (!$afterKeyword->is(';')) {
$value = $this->expectValue($this->next());
$keyword->setValue($value);
}
}
protected function handleParentheses($keyword, $afterKeyword)
{
if ($afterKeyword && $afterKeyword->is('(')) {
$this->skip();
$keyword->setValue($this->parseParentheses());
} elseif ($keyword->needParenthesis()) {
throw new Exception("'" . $keyword->type . "' block need parentheses.", 17);
}
}
protected function getInitialValue($token)
{
if ($token->isFunction()) {
return $this->parseFunction($token);
}
if ($token->is('(')) {
return $this->parseParentheses();
}
if ($token->is('[')) {
return $this->parseHooksArray();
}
if ($token->is('{')) {
return $this->parseBracketsArray();
}
if ($token->isLeftHandOperator()) {
$value = $this->expectValue($this->next(), $token);
$value->prepend($token->type);
return $value;
}
if ($token->isValue()) {
return $this->parseValue($token);
}
}
protected function appendFunctionsCalls(&$value)
{
while ($token = $this->get(0)) {
if ($token->is('{') || $token->expectNoLeftMember()) {
throw $this->unexpected($this->next());
}
if ($token->is('?')) {
$this->skip();
$value = $this->parseTernary($value);
continue;
}
if ($token->is('(')) {
$this->skip();
$arguments = array();
$value = new FunctionCall($value, $this->parseParentheses()->nodes);
continue;
}
if ($token->isOperator()) {
if ($token->isIn('++', '--')) {
$value->append($this->next()->type);
break;
}
if ($token->isAssignation()) {
$this->skip();
$arguments = array();
$valueToAssign = $this->expectValue($this->next());
$value = new Assignation($token->type, $value, $valueToAssign);
continue;
}
$this->skip();
$nextValue = $this->expectValue($this->next());
$value = new Dyiade($token->type, $value, $nextValue);
$token = $this->get(0);
continue;
}
break;
}
}
protected function expectValue($next, $token = null)
{
if (!$next) {
if ($token) {
throw $this->unexpected($token);
}
throw new Exception('Value expected after ' . $this->exceptionInfos(), 20);
}
$value = $this->getValueFromToken($next);
if (!$value) {
throw $this->unexpected($next);
}
return $value;
}
protected function expectColon($errorMessage, $errorCode)
{
$colon = $this->next();
if (!$colon || !$colon->is(':')) {
throw new Exception($errorMessage, $errorCode);
}
}
}
<file_sep><?php
require_once(
__DIR__
.DIRECTORY_SEPARATOR
.".."
.DIRECTORY_SEPARATOR
."compilers"
.DIRECTORY_SEPARATOR
."pug"
.DIRECTORY_SEPARATOR
."vendor"
.DIRECTORY_SEPARATOR
."autoload.php"
);
use \Pug as Pug;
$base = "../../";
require_once (__DIR__."/../compilers/Premise/Premise.php");
set_include_path(dirname($_SERVER['PHP_SELF']));
Premise::run(
str_replace(
".pug",
".php",
$_SERVER['PHP_SELF']
)
);
echo (new Pug\Pug())->render($_SERVER['PHP_SELF'], array());
<file_sep><?php
echo file_get_contents(__DIR__.DIRECTORY_SEPARATOR."teste1.js");
echo file_get_contents(__DIR__.DIRECTORY_SEPARATOR."teste2.js");
<file_sep><?php
$preprocess = $_SERVER['PHP_SELF'].".php";
if(file_exists($preprocess))
{
require_once (
__DIR__.
DIRECTORY_SEPARATOR.
"..".
DIRECTORY_SEPARATOR.
"compilers".
DIRECTORY_SEPARATOR.
"Premise".
DIRECTORY_SEPARATOR.
"Premise.php"
);
Premise::partial(
"self",
basename($_SERVER['PHP_SELF']).".php"
);
}
else
{
echo file_get_contents($_SERVER['PHP_SELF']);
}<file_sep><?php
// echo "teste";
Abstract Class Premise
{
// Public Static $modules = array();
// Public Static $debug = array();
Public Static $curl;
Public Static $protocol;
Private Static $references = array(
"global" => "../../../",// relative to premise location
"project" => "../../../../",
"local" => null// as it's relative to nothing, it'll consider the requested folder.
);
Public Static $modules = array(
"prepend" => array(),
"append" => array()
);
// $_SERVER['HTTPS']
Private Static Function read($config_path)
{
if(file_exists($config_path))
return @parse_ini_file($config_path);
}
Public Static Function path($reference, $path)
{
return str_replace(
self::$protocol."://".$_SERVER['SERVER_NAME'],
$_SERVER['DOCUMENT_ROOT'],
str_replace(
"/",
DIRECTORY_SEPARATOR,
self::link(
$reference,
$path
)
)
);
}
Public Static Function link($reference, $path)
{
return self::$protocol."://".str_replace(
"\\",
"/",
str_replace(
strtolower(realpath($_SERVER['DOCUMENT_ROOT'])),
$_SERVER['SERVER_NAME'],
strtolower(
(
array_key_exists(
$reference,
self::$references//[$reference]
)
&& $reference != null
? realpath(__DIR__."/".self::$references[$reference])
: dirname($_SERVER['PHP_SELF'])
)."/".$path
)
)
);
}
Public Static Function run($path)
{
self::$protocol = ($_SERVER['SERVER_PORT'] == 443 ? "https" : "http");
// Set level paths
$levels = explode(DIRECTORY_SEPARATOR, $path);
// print_r($levels);
for($key = count($levels); $key >= 0; $key--)
$levels[$key] = implode("/", array_slice($levels, 0, $key - 1))."/";
$levels = array_slice($levels, 4);
// print_r($levels);
// Page specific config
$levels[] = str_replace(
".".pathinfo($path, PATHINFO_EXTENSION),
"",
$path
);
// Ignore parent config
foreach($levels as $key => $level)
{
$temp = self::read($level.".premise");
if (
isset($temp["ignore_parent"])
&& $temp["ignore_parent"]
)
$lowest_ignore_parent = $key;
}
$levels = array_slice($levels, $lowest_ignore_parent);
// Load config from levels
foreach($levels as $level)
if(file_exists($level.".premise"))
{
self::loadAll(
$level.".premise",
"prepend"
);
register_shutdown_function(
function($level)
{
self::loadAll(
$level.".premise",
"append"
);
},
$level
);
}
// require $path;
}
// Easier temporary debugging. SHOULD NOT BE USED FOR ERROR HANDLING
Public Static Function debug(
$data,
$dump = true
)
{
ob_start();
if($dump)
var_dump($data);
else
print_r($data);
trigger_error(
str_replace(
"=>\n ",
" => ",
ob_get_clean()
),
E_USER_NOTICE
);
}
Public Static Function partial(
$reference,
$request,// custom request if it's an array
$return = false,
$parse_method = null
)
{
// checks if it's a ordinary or custom request
if(!is_array($request))
{
$url = self::link($reference, $request);
$get = $_GET;
$post = $_POST;
$cookie = $_COOKIE;
$auth = "";
}
else
{
$request = array_change_key_case(
$request,
CASE_UPPER
);
$parse_url = parse_url($request['URL']);
$url = (
!in_array(
$parse_url['host'],
array(
"",
null,
$_SERVER['HTTP_HOST']
)
)
? $request['URL']
: self::link($reference, $request['URL'])
);// calls
$get = !empty($request['GET']) ? $request['GET'] : array();
$post = !empty($request['POST']) ? $request['POST'] : array();
$cookie = !empty($request['COOKIE']) ? $request['COOKIE'] : array();
$auth = $request['AUTH']['USER'].":".$request['AUTH']['PASS'];
}
// Initialize if it hasn't been
if(empty(self::$curl))
self::$curl = curl_init();
// Finds out which method to use for cookie jar in memory only
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
$cookie_jar = "NULL";
else
$cookie_jar = "/dev/null";
// $cookie_jar = __DIR__.DIRECTORY_SEPARATOR."cookie.txt";
// trigger_error(print_r(http_build_query($cookie), true));
// sets headers
curl_setopt_array(
self::$curl,
(
array(
// CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1",
CURLOPT_URL => $url."?".http_build_query($get),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIE => http_build_query($cookie),
// CURLINFO_CONTENT_TYPE => "text/html",
// test for crawler calls
// CURLOPT_ENCODING => 'gzip',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
// CURLOPT_MAXREDIRS => 999,
CURLOPT_AUTOREFERER => true,
// CURLOPT_USERPWD => <PASSWORD>,
// CURLOPT_HEADER => true
)
+ (
!empty($post)
? array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($post),
)
: array()
)
+ (
is_array($request)
&& !empty($request['HEADERS'])
? $request['HEADERS']
: array()
)
)
);
// stop session usage to prevent file lock
if(isset($_SESSION))
@session_write_close();
$result = curl_exec(self::$curl);
if(curl_exec(self::$curl) === false)
{
trigger_error(
curl_error(self::$curl),
E_USER_ERROR
);
}
else
{
if($return)
{
// self::info($parse_method);
if($parse_method !== null)
return $parse_method($result);
else
return $result;
}
else
{
echo $result;
}
}
if(isset($_SESSION))
@session_start();
}
Private Static Function loadAll(
$config_path,
$method
)
{
foreach(self::$references as $key => $reference)
self::load(
$config_path,
$method,
$key
);
}
Private Static Function load(
$config_path,
$method,
$reference
)
{
$modules_path = strtolower(
isset(self::$references[$reference])
? realpath(__DIR__."/".self::$references[$reference])
: dirname(realpath($config_path)) // only for local modules
).DIRECTORY_SEPARATOR;
$config = self::read($config_path);
if(!empty($config[$reference]))
foreach(array_map('strtolower', $config[$reference]) as $module)
{
// do not load the same module twice
// if(in_array($module, self::$modules[$method])){
// continue;
// // trigger_error($module." already loaded");
// }
// else {
// // trigger_error($module." loaded");
// }
//
self::$modules[$method][] = $module;
$module_config_path = $modules_path.(self::$modules[] = $module).DIRECTORY_SEPARATOR.".premise";
// Load other required modules
self::loadAll(
$module_config_path,
$method
);
// Reference paths
$int_path = $modules_path.$module;
$ext_path = self::$protocol."://".
str_replace(
"\\",
"/",
str_replace(
strtolower(realpath($_SERVER['DOCUMENT_ROOT'])),
$_SERVER['SERVER_NAME'],
$modules_path
)
).$module;
// echo $modules_path."\n";
// echo $_SERVER['DOCUMENT_ROOT']."\n";
// echo $ext_path."\n";
// die;
// Load files
$module_config = self::read($module_config_path);
// print_r($module_config);
if(!empty($module_config[$method]))
foreach((array)$module_config[$method] as $file)
{
$file_ext = pathinfo($int_path.DIRECTORY_SEPARATOR.$file, PATHINFO_EXTENSION);
// echo $file_ext;
switch($file_ext)
{
case "php":
require_once $int_path.DIRECTORY_SEPARATOR.$file;
break;
case "coffee":
case "js":
echo "<script src='".$ext_path."/".$file."'></script>";
break;
// case "less":
case "sass":
case "scss":
case "css":
echo "<link href='".$ext_path."/".$file."' rel='stylesheet'>";
break;
default:
trigger_error(
"PREMISE: Unsupported filetype ".$file_ext." on module ".$module
);
break;
}
}
}
}
}
<file_sep><?php
$base = "../../";
require_once (
__DIR__.
DIRECTORY_SEPARATOR.
"..".
DIRECTORY_SEPARATOR.
"compilers".
DIRECTORY_SEPARATOR.
"Premise".
DIRECTORY_SEPARATOR.
"Premise.php"
);
set_include_path(dirname($_SERVER['PHP_SELF']));
Premise::run($_SERVER['PHP_SELF']);
// echo $_SERVER['PHP_SELF'];
// echo dirname($_SERVER['PHP_SELF']));
require $_SERVER['PHP_SELF'];
<file_sep><?php
Abstract Class Tunnel
{
Public Static $url;
Public Static $ext;
Public Static $mime_type;
Public Static $handler;
Public Static $cache_path;
Public Static $cache_file;
Public Static $cache_folder;
Public Static Function run()
{
self::$url = realpath("..".DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.str_replace("/", DIRECTORY_SEPARATOR, $_GET['tunnel']);
//self::$url = realpath("..".DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR).str_replace("/", DIRECTORY_SEPARATOR, $_SERVER['REDIRECT_URL']);
//trigger_error($_SERVER['REQUEST_URI']);
self::$ext = pathinfo(self::$url, PATHINFO_EXTENSION);
// echo self::$url;
$_SERVER['PHP_SELF'] =
$_SERVER['SCRIPT_NAME'] =
$_SERVER['SCRIPT_FILENAME'] = self::$url;
unset($_GET['tunnel']);
$_SERVER['QUERY_STRING'] = http_build_query($_GET);
self::$mime_type = json_decode(__DIR__.DIRECTORY_SEPARATOR."mime_types.json");
self::$mime_type = self::$mime_type[self::$ext];
if(strpos(self::$mime_type, "php") == false)
header('Content-Type: '.self::$mime_type);
if(file_exists(self::$handler = __DIR__.DIRECTORY_SEPARATOR."handlers".DIRECTORY_SEPARATOR.self::$ext.".php"))
{
// before
if(self::$ext != "php")
{
self::$cache_folder = __DIR__.DIRECTORY_SEPARATOR."cache";
if (!file_exists(self::$cache_folder))
{
mkdir(
self::$cache_folder,
0777,
true
);
}
self::$cache_path = (
self::$cache_folder
.DIRECTORY_SEPARATOR
.md5($_SERVER['PHP_SELF'])
);
if(
file_exists(self::$cache_path)
&& file_get_contents(self::$cache_path) != ""
&& !isset($_GET['nocache'])
&& filemtime(self::$cache_path) > filemtime($_SERVER['PHP_SELF'])
)
{
// echo self::$cache_path;
self::$cache_file = fopen(self::$cache_path, "r");
echo fread(
self::$cache_file,
filesize(self::$cache_path)
);
fclose(self::$cache_file);
die;
}
else
{
self::$cache_file = fopen(self::$cache_path, "w");
ob_end_flush();
ob_start();
}
}
// call
require_once self::$handler;
// after
if(self::$ext != "php")
{
try
{
if(!empty($cache_file))
register_shutdown_function(
function($cache_File)
{
fwrite($cache_file, ob_get_contents());
fclose($cache_file);
},
self::$cache_file
);
}
catch(Exception $ex)
{
}
}
}
else
{
require_once self::$url;
}
}
}
Tunnel::run();
<file_sep><?php
// die("teste");
Abstract Class Stack
{
Public Static $_LOGS = "";
Public Static $_ERROR = "";
Public Static $_WARN = "";
Public Static $_INFO = "";
Public Static $_DEBUG = true;
Public Static Function debug(
$data,
$dump = true
)
{
ob_start();
if($dump)
var_dump($data);
else
print_r($data);
trigger_error(
str_replace(
"=>\n ",
" => ",
ob_get_clean()
),
E_USER_NOTICE
);
// improve so it won't backtrace from here
}
Public Static Function error(
$errno,
$errstr,
$errfile,
$errline
)
{
$error = array(
"id" => $errno,
"message" => $errstr,
"file" => $errfile,
"line" => $errline
);
switch($errno)
{
case E_NOTICE:
case E_WARNING:
case E_USER_WARNING:
self::$_WARN[] = $error;
break;
case E_USER_NOTICE:
self::$_INFO[] = $error;
break;
default:
if(!empty($errstr))
self::$_ERROR[] = $error;
}
}
Public Static Function fatal($exception)
{
if(empty($exception)) return false;
self::$_ERROR[] =
$error = (
is_array($exception)
? array(
"id" => 0,
"message" => $exception['message'],
"file" => $exception['file'],
"line" => $exception['line'],
"type" => "FATAL"
)
: array(
"id" => 0,
"message" => $exception->getMessage(),
"file" => $exception->getFile(),
"line" => $exception->getLine(),
"type" => "EXCEPTION"
)
);
ob_end_clean();
// echo __DIR__."<br>";
echo $error['type'].": ".$error['message']." <br>".
"LINE: ".$error['line']."<br>".
"FILE: ".$error['file']."<br>".
"BACKTRACE:<pre>".print_r(debug_backtrace(), true)."</pre>";
}
Public Static Function shutdown()
{
self::fatal(error_get_last());
echo "
<script id='_stack'>
if (!window.console)
throw new Error('This browser does not support console!');
// history.replaceState({}, '', '/');
// history.replaceState({}, '', window.location.href);
";
// SERVER
$table_server = "";
foreach ($_SERVER as $key => $value)
$table_server .= "'".$key."':{'value': '".self::fix($value)."'},";
echo "
if(window.self === window.top)
{
console.groupCollapsed('SERVER');
console.table({".rtrim($table_server, ",")."});
console.groupEnd();
}
";
// PAGE
echo "
console.group('"
.rtrim(basename($_SERVER['PHP_SELF']), ".php")
." ".round((microtime(true) - $_SERVER['REQUEST_TIME']), 2)."s"
." ".self::convertMemory(memory_get_usage(true))
."');
";
// REQUEST
if(!isset($_SESSION)) session_start();
$request = array(
"GET" => $GLOBALS["_GET"],
"POST" => $GLOBALS["_POST"],
"FILES" => $GLOBALS["_FILES"],
"SESSION" => $GLOBALS["_SESSION"],
"LOGS" => self::$_LOGS//array_merge($GLOBALS['_LOGS'], self::$_LOGS)
);
echo "console.groupCollapsed('REQUEST');";
foreach($request as $request_key => $request_value)
{
if(!empty($request_value))
{
echo "
console.groupCollapsed('".$request_key."');
console.log(".json_encode($request_value)." );
console.groupEnd();
";
}
}
echo "console.groupEnd();";
// ERRORS
$error_types = array(
"WARNINGS" => "WARN",
"ERRORS" => "ERROR",
"INFO" => "INFO",
);
foreach($error_types as $error_key => $error_type)
{
if(!is_array(self::${"_".$error_type}))
continue;
self::${"_".$error_type} = array_unique(
@(array)self::${"_".$error_type},
SORT_REGULAR
);
echo "console.group".($error_key == "WARNINGS" ? "Collapsed" : "")."('".$error_key." (".count(self::${"_".$error_type}).")');";
foreach (self::${"_".$error_type} as $key => $value)
echo "console.".strtolower($error_type)
."('FILE:\\t".self::fix($value['file'])
."\\nLINE:\\t".$value['line']
."\\nMSG:\\t".self::fix($value['message'])."');";
echo "console.groupEnd();";
}
echo "
console.groupEnd();
</script>
";
ob_flush(); flush();
}
Public Static Function run()
{
ini_set("display_errors", true);
ini_set("html_errors", false);
error_reporting(E_ALL);
set_error_handler("Stack::error");
set_exception_handler('Stack::fatal');
if (
!isset($_SERVER['HTTP_X_REQUESTED_WITH'])// xmlhttprequest
&& self::$_DEBUG
)
{
header("Content-Type: text/html");
ob_start();
register_shutdown_function("Stack::shutdown");
}
}
Public Static Function log(
$value,
$key = ""
)
{
if(empty($key))
self::$_LOGS[] = $value;
else
self::$_LOGS[$key] = $value;
return $value;
}
// helper functions
Private Static Function fix($message)
{
return !is_array($message)
? str_replace(
array(
"'",
"\\",
"\n",
"\r",
),
array(
"`",
"/",
"\\n",
"\\r",
),
$message
)
: $message;
}
Private Static Function convertMemory($size)
{
$unit = array('B','KB','MB','GB','TB','PB');
return @round($size/pow(1024*8,($i=floor(log($size,1024*8)))),2).' '.$unit[$i];
}
}
Stack::run();
<file_sep><?php
require __DIR__
.DIRECTORY_SEPARATOR
.".."
.DIRECTORY_SEPARATOR
."compilers"
.DIRECTORY_SEPARATOR
."scssphp"
.DIRECTORY_SEPARATOR
."scss.inc.php";
use Leafo\ScssPhp\Compiler;
$scss = new Compiler();
$buffer = $scss->compile(file_get_contents($_SERVER['PHP_SELF']));
// minify
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
$buffer = str_replace(': ', ':', $buffer);
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
$buffer = str_replace(array(" {", " }", ", "), array("{", "}", ","), $buffer);
echo($buffer);
|
ecf94738957aa8bf8551bbb7934af519dc7e2ed5
|
[
"Markdown",
"C",
"JavaScript",
"PHP"
] | 18
|
Markdown
|
HarrySystems/Premise
|
d8ec992cd4653394ea1f86ebfb525f0d0b14f09b
|
2009cd76b3bf8ed710c7d7da844ef0147b235ca1
|
refs/heads/master
|
<repo_name>dostonhamrakulov/Compare-two-excel-files<file_sep>/src/ReadWriteDataExcel.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadWriteDataExcel {
static Boolean check = false;
//Change column number whatever you want to take data
public static int columnNumForFirst = 3;
public static int columnNumForSecond = 5;
public static void main(String args[]) throws IOException {
try {
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();
FileInputStream file1 = new FileInputStream(new File(
"D://Europa.xlsx"));
FileInputStream file2 = new FileInputStream(new File(
"D://WorldCity.xlsx"));
// Get the workbook instance for XLSX file
XSSFWorkbook workbook1 = new XSSFWorkbook(file1);
XSSFWorkbook workbook2 = new XSSFWorkbook(file2);
// Get only first sheet from the workbook
XSSFSheet sheet1 = workbook1.getSheetAt(0);
XSSFSheet sheet2 = workbook2.getSheetAt(0);
// Get iterator to all the rows in current sheet1
Iterator<Row> rowIterator1 = sheet1.iterator();
Iterator<Row> rowIterator2 = sheet2.iterator();
//getting date from first excel file
while (rowIterator1.hasNext()) {
Row row = rowIterator1.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// This is for read only one column from excel
if (cell.getColumnIndex() == columnNumForFirst) {
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
arr1.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
arr1.add(cell.getStringCellValue());
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
arr1.add(cell.getBooleanCellValue());
System.out.print(cell.getBooleanCellValue());
break;
}
}
}
System.out.println(" ");
}
file1.close();
System.out.println("\n-----------------------------------");
// For retrive the second excel data
while (rowIterator2.hasNext()) {
Row row1 = rowIterator2.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator1 = row1.cellIterator();
while (cellIterator1.hasNext()) {
Cell cell1 = cellIterator1.next();
// Check the cell type and format accordingly
// This is for read only one column from excel
if (cell1.getColumnIndex() == columnNumForSecond) {
switch (cell1.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
arr2.add(cell1.getNumericCellValue());
System.out.print(cell1.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
arr2.add(cell1.getStringCellValue());
System.out.print(cell1.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
arr2.add(cell1.getBooleanCellValue());
System.out.print(cell1.getBooleanCellValue());
break;
}
}
// this continue is for
// continue;
}
System.out.println("");
}
System.out.println("\nbook1.xls -- " + arr1.size());
System.out.println("book1.xls -- " + arr2.size());
// compare two arrays
for (Object process : arr1) {
if (!arr2.contains(process)) {
arr3.add(process);
}
}
System.out.println("\narr3 list values, here arr1 has some values which arr2 DOES NOT have : " + arr3);
writeResultDataToExcel(arr3);
StoreArraysToHashMap(arr1, arr2);
// closing the files
file1.close();
file2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// write into new file excel
private static void writeResultDataToExcel(ArrayList arr3) {
FileOutputStream resultExcel = null;
try {
resultExcel = new FileOutputStream(
"D://ResultFile.xlsx");
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet spreadSheet = workBook.createSheet("New");
XSSFRow row;
XSSFCell cell;
// System.out.println("array size is :: "+minusArray.size());
int cellnumber = 1;
for (int i1 = 0; i1 < arr3.size(); i1++) {
row = spreadSheet.createRow(i1);
cell = row.createCell(cellnumber);
// System.out.print(cell.getCellStyle());
cell.setCellValue(arr3.get(i1).toString().trim());
}
int cellnumber2 = 4;
for (int i2 = 0; i2 < arr3.size(); i2++) {
row = spreadSheet.createRow(3);
cell = row.createCell(cellnumber);
// System.out.print(cell.getCellStyle());
cell.setCellValue(arr3.get(i2).toString().trim());
}
workBook.write(resultExcel);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
// end -write into new file
//Store data to HashMap
private static void StoreArraysToHashMap(ArrayList arr1, ArrayList arr2) {
HashMap<Integer, String> hashMap1 = new HashMap<Integer, String>();
for(int i = 0; i < arr1.size(); i++) {
hashMap1.put(i, arr1.get(i).toString());
}
HashMap<Integer, String> hashMap2 = new HashMap<Integer, String>();
for(int j = 0; j < arr1.size(); j++) {
hashMap2.put(j, arr2.get(j).toString());
}
System.out.println("\nHashMap from first excel file: " + hashMap1);
System.out.println("\nHashMap from second excel file: " + hashMap2);
}
}<file_sep>/README.md
# Compare-two-excel-files
First of all, you need to import apache poi library in order to read and wrtie excel file:
Downloading apache poi : https://poi.apache.org/download.html
Potential exceptions in first time:
1. java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
Solution, you need to add one more library which is xmlbeans-x.x.x.jar: https://stackoverflow.com/questions/23080945/java-lang-classnotfoundexception-org-apache-xmlbeans-xmlexception
1. Excel.java class demostres how hashmap works
2. ReadWriteDataExcel.java compares two excel file and writes into result file.
3. Secondtype.java takes data from excel and writes into hashmap, even if the excel file has more sheets it writes one by one, here how it works:
Hashmap myHashmap =
{ sheet1 = {row1 = [column1, column2, ...], row2 = [column1, column2, ...], row3 ...}, sheet2 = {row1 = [column1, column2, ...], row2 = [column1, column2, ...], row3 ...}, sheet3 = { ... }, ...};
|
d456e01d7548525e5849c349b3d72519de6dfd7a
|
[
"Markdown",
"Java"
] | 2
|
Java
|
dostonhamrakulov/Compare-two-excel-files
|
bd12f29355c8e3248e595ec9c58fd39c500aac11
|
4e07376dfc2bb8ddc848eead2ff24b74dcd43cd6
|
refs/heads/main
|
<file_sep><?php
echo '<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Tirada Dados</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="stylesmenu.css">
</head>
<body>
<div id="menu">
<h1>Menu</h1>
<div class = "navegador">
<ul>
<li><a href="../privado1/tirada_dados.php">TIRADA</a></li>
<li><a href="../privado2/sumar_7.php">SUMA 7</a></li>
<li><a href="../privado3/par_impar.php">PAR/IMPAR</a></li>
<li><a href="../acerca_de.php">ACERCA DE</a></li>
</ul>
</div>
</div>
</body>
</html>';
?><file_sep><?php
include 'menu.php';
$suma = 0;
$dado1 = 0;
$dado2 = 0;
$contador = 0;
while ($suma != 7){
$dado1 = rand(1,6);
$dado2 = rand(1,6);
$suma = $dado1 + $dado2;
$contador++;
}
switch ($dado1){
case 1:
echo '<img src="img/uno.jpg" alt="Uno" width="150" height="150">';
break;
case 2:
echo '<img src="img/dos.jpg" alt="Dos" width="150" height="150">';
break;
case 3:
echo '<img src="img/tres.jpg" alt="Tres" width="150" height="150">';
break;
case 4:
echo '<img src="img/cuatro.jpg" alt="Cuatro" width="150" height="150">';
break;
case 5:
echo '<img src="img/cinco.jpg" alt="Cinco" width="150" height="150">';
break;
case 6:
echo '<img src="img/seis.jpg" alt="Seis" width="150" height="150">';
break;
}
switch ($dado2){
case 1:
echo '<img src="img/uno.jpg" alt="Uno" width="150" height="150">';
break;
case 2:
echo '<img src="img/dos.jpg" alt="Dos" width="150" height="150">';
break;
case 3:
echo '<img src="img/tres.jpg" alt="Tres" width="150" height="150">';
break;
case 4:
echo '<img src="img/cuatro.jpg" alt="Cuatro" width="150" height="150">';
break;
case 5:
echo '<img src="img/cinco.jpg" alt="Cinco" width="150" height="150">';
break;
case 6:
echo '<img src="img/seis.jpg" alt="Seis" width="150" height="150">';
break;
}
echo '<br><h2>Número de Intentos: '. $contador . '</h2>';
?>
<file_sep><?php
include 'menu.php';
for ($i=1; $i<=5; $i++){
$numero = rand(1,6);
switch ($numero){
case 1:
echo '<img src="img/uno.jpg" alt="Uno" width="150" height="150">';
break;
case 2:
echo '<img src="img/dos.jpg" alt="Dos" width="150" height="150">';
break;
case 3:
echo '<img src="img/tres.jpg" alt="Tres" width="150" height="150">';
break;
case 4:
echo '<img src="img/cuatro.jpg" alt="Cuatro" width="150" height="150">';
break;
case 5:
echo '<img src="img/cinco.jpg" alt="Cinco" width="150" height="150">';
break;
case 6:
echo '<img src="img/seis.jpg" alt="Seis" width="150" height="150">';
break;
}
}
?>
<file_sep><?php
session_start();//primera sentencia para trabajar con sesiones
if(isset($_REQUEST['login'])){
$_SESSION['email']=htmlspecialchars($_REQUEST['email'], ENT_QUOTES, 'UTF-8');
$email=htmlspecialchars($_REQUEST['email'], ENT_QUOTES, 'UTF-8');
$password=htmlspecialchars($_REQUEST['contraseña'], ENT_QUOTES, 'UTF-8');
if($email==="<EMAIL>" && $password==="<PASSWORD>"){
header('Location:menu.php');
}else {
header('Location:index.php');
}
}else{
echo '<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>LOG IN</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="encabezado">
<h1>LOG IN</h1>
</div>
<form method="POST" action="index.php" name="login-form">
<div class="elemento-form">
<input type="text" name="email" placeholder="EMAIL" required />
</div>
<div class = "elemento-form">
<input type="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>" required />
</div>
<input type="submit" name="login" value="LOG IN">
</form>
</body>
</html>';
}
<file_sep># Proyecto_Dados
https://entrega-despliegue-continuo.herokuapp.com/
Despliegue Aplicaciones Web
<NAME>
[](https://travis-ci.org/rubhermar96/Proyecto_Dados)
|
a66a85075c73d71b6da790a39186065ab025b3a1
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
rubhermar96/Proyecto_Dados
|
40a0526350bfe6d522407cbea139a82c58bcdd0b
|
80d85a662bcd50ae3c5bb35766252537cc925982
|
refs/heads/main
|
<file_sep>'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('customers', [
{
'name': 'admin',
'address': '401 Admin St',
'role': 'admin',
'password': <PASSWORD>',
'email': '<EMAIL>',
},
{
'name': 'prathiksha',
'address': '401 Anderson St',
'role': 'customer',
'password': <PASSWORD>',
'email': '<EMAIL>',
},
{
'name': 'pramitha',
'address': '401 Friends Colony',
'role': 'customer',
'password': <PASSWORD>',
'email': '<EMAIL>',
},
], {})
},
down: async (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('customers', null, {})
}
};
<file_sep>var express = require('express');
var router = express.Router();
var path = require('path');
var Sequelize = require('sequelize');
const db = require('../models/index.js');
const { checkAuth, checkNotAuth, checkNotAdmin } = require("../authConfig.js");
router.get('/', checkNotAdmin, (req,res) => {
var items;
db.items.findAll({
attributes: {exclude: ['createdAt', 'updatedAt']}
// order: [['item_date', 'DESC']]
}).then(items_obj => {
admin = false;
if (req.user) {
admin = req.user.role === 'admin';
}
items = items_obj;
const sleep = milliseconds => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
sleep(200).then(() => {
// code to execute after sleep
res.render('admin', { auth: req.isAuthenticated(), admin: admin, items: items });
});
});
});
router.post('/item_add', checkNotAdmin, (req, res) => {
db.items.create({
name: req.body['name'],
cost: req.body['cost'],
category: req.body['category']
})
.then( (result) => {
res.json(result)
});
});
router.put('/item_edit', checkNotAdmin, (req, res) => {
db.items.update({
name: req.body['name'],
cost: req.body['cost'],
category: req.body['category']
}, {
where: {id: req.body['id']}
})
.then( (result) => {
res.json(result)
});
});
router.delete('/item_delete', checkNotAdmin, (req, res) => {
db.items.destroy({
where: {id: req.body['id']}
})
.then( (result) => {
res.json(result)
});
});
module.exports = router<file_sep>'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('items', [
{
'name': 'Sugar',
'cost': 50,
'category': 'grocery',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Maggi',
'cost': 10,
'category': 'grocery',
'image': '../images/items/itemplaceholder.png',
},
{
'name': '<NAME>',
'cost': 20,
'category': 'bath',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Pens',
'cost': 5,
'category': 'stationary',
'image': '../images/items/itemplaceholder.png',
},
{
'name': '<NAME>',
'cost': 100,
'category': 'stationary',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Salt',
'cost': 15,
'category': 'grocery',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Harpic',
'cost': 70,
'category': 'toilet',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Jars',
'cost': 30,
'category': 'kitchen',
'image': '../images/items/itemplaceholder.png',
},
{
'name': '<NAME>',
'cost': 200,
'category': 'beauty',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Hammer',
'cost': 300,
'category': 'tools',
'image': '../images/items/itemplaceholder.png',
},
{
'name': '<NAME>',
'cost': 50,
'category': 'tools',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Bucket',
'cost': 50,
'category': 'bath',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Broom',
'cost': 80,
'category': 'home',
'image': '../images/items/itemplaceholder.png',
},
{
'name': 'Oreo',
'cost': 40,
'category': 'food',
'image': '../images/items/itemplaceholder.png',
},
], {})
},
down: async (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('items', null, {})
}
};
<file_sep>'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('sellers', [
{
'name': '<NAME>',
'address': "647, Friend's Colony, 2nd Cross, BHCS Layout, Uttarahalli, Bengaluru-560061"
},
{
'name': '<NAME>',
'address': "331, 2nd Cross, 3rd Stage, RR Nagar, Bengaluru-560098"
},
{
'name': '<NAME>',
'address': "110, 3rd Cros, 5th Main, HSR Layout, Bengaluru-560034"
},
], {})
},
down: async (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('sellers', null, {});
}
};
<file_sep>var express = require('express')
var router = express.Router();
var path = require('path')
var Sequelize = require('sequelize')
const db = require('../models/index.js')
const Op = Sequelize.Op
const { pool } = require("../dbConfig");
const { checkAuth, checkNotAuth, checkNotAdmin } = require("../authConfig.js");
router.get('/home', (req, res) => {
var items;
var recommends;
db.items.findAll({
attributes: {exclude: ['createdAt', 'updatedAt']},
}).then(items_obj => {
admin = false;
if (req.user) {
admin = req.user.role === 'admin';
}
items = items_obj;
// res.render('index', { auth: req.isAuthenticated(), admin: admin, items: items, user: req.user });
});
db.sequelize.query("select i.id, i.name, i.cost from items i inner join shoppings s on (s.item_id=i.id) where s.active=false and s.cust_id=(:id) group by i.id order by count(*) desc limit 5", {replacements:{id:req.user.id}}
).then(recommend_obj => {
admin = false;
if (req.user) {
admin = req.user.role === 'admin';
}
recommends = recommend_obj;
// console.log(recommends);
const sleep = milliseconds => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
timeToSleep = 200;
sleep(timeToSleep).then(() => {
// code to execute after sleep
res.render('index', { auth: req.isAuthenticated(), admin: admin, items: items, user: req.user, recommends: recommends[0] });
});
});
});
router.get('/stores', (req, res) => {
db.stores.findAll({
attributes: {exclude: ['createdAt', 'updatedAt']},
}).then(stores => {
admin = false;
if (req.user) {
admin = req.user.role === 'admin';
}
res.render('stores', { auth: req.isAuthenticated(), admin: admin, stores: stores });
});
});
router.get('/sellers', (req, res) => {
db.seller.findAll({
attributes: {exclude: ['createdAt', 'updatedAt']},
}).then(sellers => {
admin = false;
if (req.user) {
admin = req.user.role === 'admin';
}
res.render('sellers', { auth: req.isAuthenticated(), admin: admin, sellers: sellers });
});
});
router.get('/', checkAuth, (req,res) => {
admin = false;
profile_pic = '';
if (req.user) {
admin = req.user.role === 'admin';
profile_pic = req.user.profile_pic;
}
res.render("login", { auth: req.isAuthenticated(), admin: admin, profile_pic: profile_pic });
});
router.post('/add', checkNotAuth, (req, res) => {
db.shoppings.create({
quantity: 1,
cust_id: req.body['cust_id'],
item_id: req.body['item_id'],
active: true
})
.then( (result) => {
res.json(result)
});
});
router.put('/update', checkNotAuth, (req, res) => {
db.shoppings.update({
active: false
}, {
where: {cust_id: req.user.id}
})
.then( (result) => {
// console.log(result);
res.json(result)
});
});
module.exports = router
|
e2634eb1ae12011b935da318046ecb29a7d37009
|
[
"JavaScript"
] | 5
|
JavaScript
|
PRATHIKSHA1995/retail-store
|
83940543031af00de84c796cb0d9cd99598643f1
|
8962ce5dd0eb4160002b9dc4604e3a15329d8e38
|
refs/heads/master
|
<repo_name>sarahabbas10/week02_day08_JS_OOP_HW<file_sep>/Movie.js
//Create an object to store the following information about your favorite movie:
//title(a string), duration(a number), and stars(an array of strings).
//Print out the movie information like so: "Puff the Magic Dragon lasts for 30 minutes. Stars: Puff, Jackie, Living Sneezes."
//Maybe the join method will be helpful here
function movies(title, duration, stars) {
this.title = title,
this.duration = duration,
this.stars = stars
this.info = function() {
return this.title + " " + this.duration + " minutes. Stars: " + this.stars.join();
}
}
const m1 = new movies('warth of man', 118, ['a<NAME> ', '<NAME>', '<NAME>'])
const m2 = new movies('tit', 90, ['a ', 'b', 'e'])
const m3 = new movies('tit', 90, ['a ', 'b', 'e'])
m1.info()
m2.info()
m3.info()<file_sep>/animal.js
//class
//constructor with the animal name, age, image, and sound
//create method called eats that will return
//for example "animal eats food" where animal is the property name.
class animal {
constructor(name, age, image, sound) {
this.name = name
this.age = age
this.image = image
this.sound = sound
}
eats() {
return this.name + " eats food "
}
animalsound() {
return ' '
}
}
class Cat extends animal {
constructor(name, age, image, sound) {
super(name, age, image, sound)
}
eats() {
return 'cats eats mouse'
}
animalsound() {
return "cat sounds is " + this.sound
}
}
class Dog extends animal {
constructor(name, age, image, sound) {
super(name, age, image, sound)
}
eats() {
return 'dogs eats chicken'
}
animalsound() {
return 'dogs sounds is ' + this.sound
}
}
class Fish extends animal {
constructor(name, age, image, sound, color) {
super(name, age, image, sound)
this.color = color
}
eats() {
return 'fish eats flakes'
}
}
//create object for dog, cat and fish classes and excute all the methods in the classes.
const cat1 = new Cat('lolo', 2, 'img', 'meow')
const dog1 = new Dog('lili', 5, 'img', 'woof')
const fih1 = new Fish('Nemo', 3, 'img', 'nemo')
//create HTML file and print the images of each object.
const div1 = document.createElement('div')
document.body.appendChild(div1)
const img1 = document.createElement('img')
img1.src = 'cat.jpg'
img1.id = 'pic1'
div1.appendChild(img1)
img1.style = 'width:60%'
const div2 = document.createElement('div')
document.body.appendChild(div2)
const img2 = document.createElement('img')
img2.src = 'dog.jpg'
img2.id = 'img2'
div2.appendChild(img2)
img2.style = 'width:60%'
const div3 = document.createElement('div')
document.body.appendChild(div3)
const img3 = document.createElement('img')
img3.src = 'nemo.jpg'
img3.id = 'img3'
div3.appendChild(img3)
img3.style = 'width:60%'
//when clicking on the image the details of the animal should show up in a list.
document.getElementById('pic1').addEventListener('click', function() {
const ul = document.createElement('ul')
div1.appendChild(ul)
const li1 = document.createElement('li')
ul.appendChild(li1)
li1.innerText = "Name: " +
cat1.name
const li2 = document.createElement('li')
ul.appendChild(li2)
li2.innerText = cat1.age + " year"
const li3 = document.createElement('li')
ul.appendChild(li3)
li3.innerText = cat1.eats()
const li4 = document.createElement('li')
ul.appendChild(li4)
li4.innerText = cat1.animalsound()
})
document.getElementById('img2').addEventListener('click', function() {
const ul = document.createElement('ul')
div2.appendChild(ul)
const li1 = document.createElement('li')
ul.appendChild(li1)
li1.innerText = "Name: " +
dog1.name
const li2 = document.createElement('li')
ul.appendChild(li2)
li2.innerText = dog1.age + " year"
const li3 = document.createElement('li')
ul.appendChild(li3)
li3.innerText = dog1.eats()
const li4 = document.createElement('li')
ul.appendChild(li4)
li4.innerText = dog1.animalsound()
})
document.getElementById('img3').addEventListener('click', function() {
const ul = document.createElement('ul')
div3.appendChild(ul)
const li1 = document.createElement('li')
ul.appendChild(li1)
li1.innerText = "Name: " +
dog1.name
const li2 = document.createElement('li')
ul.appendChild(li2)
li2.innerText = fih1.age + " year"
const li3 = document.createElement('li')
ul.appendChild(li3)
li3.innerText = fih1.eats()
})
|
30fb7637e6f57c67f0f4d198a2a7a160336c741f
|
[
"JavaScript"
] | 2
|
JavaScript
|
sarahabbas10/week02_day08_JS_OOP_HW
|
608bd28072d154a8e0d5b0de9ba98b5697ed6aea
|
ecb6622b1114bb68faee9cdd03476105ebd7cbee
|
refs/heads/master
|
<file_sep>package com.joaomerlin.robot.api.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
public interface RobotController {
@PostMapping("{robot}/{command}")
ResponseEntity<?> march(@PathVariable String robot, @PathVariable String command);
}
<file_sep>package com.joaomerlin.robot.api.service;
import com.joaomerlin.robot.api.model.Position;
public interface RobotService {
Position executeCommand(String robot, String command);
}
<file_sep>package com.joaomerlin.robot.api;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class ApiApplicationTests {
protected MockMvc mockMvc;
}
<file_sep># Getting Started
### API Documentation
* `/rest/{robot}/{command}`
Input
```
{robot} Name of robot
{command} List of commands, M (March), R (Right) and L (Left)
```
Output:
```
{
"x": 2,
"y": 0,
"point": "S"
}
```
Example:
```
curl -s --request POST https://nasa-robot.herokuapp.com/rest/mars/MMRMMRMM
```
<file_sep>package com.joaomerlin.robot.api.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum CardinalPoint {
N("E", "W"),
S("W", "E"),
E("S", "N"),
W("N", "S");
private String right;
private String left;
}
<file_sep>package com.joaomerlin.robot.api.exception;
public class InvalidCommandException extends RuntimeException {
public InvalidCommandException() {
super();
}
public InvalidCommandException(String message) {
super(message);
}
public InvalidCommandException(String message, Throwable cause) {
super(message, cause);
}
public InvalidCommandException(Throwable cause) {
super(cause);
}
protected InvalidCommandException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
083e64511bc775bcedb96de757ee1b5332017410
|
[
"Markdown",
"Java"
] | 6
|
Java
|
joaopmerlin/nasa-robot
|
1f6e2b9c0c26700d914be3e3ded7c2f82878050c
|
ecb9b3a2b13a8d9d2d331d944a479a14fcef0b9b
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Umg.Entidades.Usuarios
{
public class RequieredAttribute : Attribute
{
}
}
<file_sep>
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Umg.Datos;
using Umg.Entidades.Almacen;
namespace Umg.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ArticulosController : ControllerBase
{
private readonly DbContexSistema _context;
public ArticulosController(DbContexSistema context)
{
_context = context;
}
//GET api/Articulos
[HttpGet]
public async Task<ActionResult<IEnumerable<Articulos>>> GetArticulos()
{
return await _context.Articuloss.ToListAsync();
}
//GET api/Articulos/2
[HttpGet("{idaritulo}")]
public async Task<ActionResult<Articulos>> GetArticulos(int id)
{
var Articulos = await _context.Articuloss.FindAsync(id);
if (Articulos == null)
{
return NotFound();
}
return Articulos;
}
//Put api/Articulos/2
[HttpPut("idarticulos")]
public async Task<IActionResult> PutArticulos(int id, Articulos Articulos)
{
if (id != Articulos.idarticulo)
{
return BadRequest();
}
//MI ENTIDAD YA TIENE LAS PROPIEDADDES O INFO QUE VOY A GUARDAR EN MY DB
_context.Entry(Articulos).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ArticulosExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
//POst api/Articulos
[HttpPost]
public async Task<ActionResult<Articulos>> PostCategoria(Articulos articulos)
{
_context.Articuloss.Add(articulos);
await _context.SaveChangesAsync();
return CreatedAtAction("GetArticulos", new { id = articulos.idarticulo }, articulos);
}
//Delete api/Articulos/2
[HttpDelete("idarticulo")]
public async Task<ActionResult<Articulos>> DeleteArticulos(int id)
{
var Articulos = await _context.Articuloss.FindAsync(id);
if (Articulos == null)
{
return NotFound();
}
_context.Articuloss.Remove(Articulos);
await _context.SaveChangesAsync();
return Articulos;
}
private bool ArticulosExists(int id)
{
return _context.Articuloss.Any(e => e.idarticulo == id);
}
}
}
<file_sep>namespace Umg.Datos.Mapping.Almacen
{
public interface IEntityTypeConfiguretion<T>
{
}
}
|
57f84b6d7ea09ab85f2fd6bb580f29b6988a4e6a
|
[
"C#"
] | 3
|
C#
|
Luz-Meza/Umg
|
6dc13c5bfec41d952a5428e3af80208ab6fddd6c
|
2dc055ea4318b293a0065e3fe7bfdade9b921382
|
refs/heads/master
|
<file_sep>/**
* Created by Administrator on 2016/9/19.
*/
var text ='1.《双城记》'+'\n' + '2.《变形记》'+'\n'+'3.《洛丽塔》'+'\n'+'4.《万有引力之虹》'+'\n'+'5.《华氏451度》'+'\n'+'6.《黛洛维夫人》'+'\n'+'7.《安娜卡列尼娜》'+'\n'+'8.《傲慢与偏见》'
+'\n'+'9.《老人与海》'+'\n'+'10.《百年孤独》'+'\n'+'11.《墨菲》'+'\n'+'12.《白鲸》';
console.log(text)
<file_sep>/**
* Created by Administrator on 2016/8/30.
*/
var httputil = require('../utils/HttpUtils');
var config = require('../config/config');
exports.getUserInfo = function *(openid,token) {
var opts = {
method: 'GET',
url: 'https://api.weixin.qq.com/cgi-bin/user/info',
qs: {
access_token: token,
openid: openid
}
};
var userinfo = yield httputil.request(opts);
return JSON.parse(userinfo);
}
exports.sendMessage = function *(openid,token,text) {
var opts = {
method: 'POST',
url: 'https://api.weixin.qq.com/cgi-bin/message/custom/send',
qs: {access_token: token},
headers: {
'content-type': 'application/json'
},
body: {
touser: openid,
msgtype: 'text',
text: {
'content':text
}
},
json: true
}
var messageresult = yield httputil.request(opts);
return messageresult;
}
exports.getwxToken = function *() {
var opts = {
'method' : 'GET',
'url' : 'https://api.weixin.qq.com/cgi-bin/token',
'qs' : {
'grant_type': 'client_credential',
'appid' : config.weixin.appID,
'secret' : config.weixin.appsecret
}
}
var tokenres = yield httputil.request(opts);
var token = JSON.parse(tokenres).access_token;
return token;
}
exports.getMdia = function *(token,mediaid) {
var opts = {
method : 'get',
url : 'https://api.weixin.qq.com/cgi-bin/media/get',
qs : {access_token:token,media_id :mediaid}
}
var result = yield httputil.request(opts);
return result
}<file_sep>/**
* Created by Administrator on 2016/8/28.
*/
var config = require("../config/config");
var MongoClient = require('mongodb').MongoClient;
if(process.env.BS_ENV == 'dev'){
var _auth = '';
}else{
var _auth = config.mongo.user+':'+config.mongo.pass+'@';
}
MongoClient.connect('mongodb://192.168.100.2:27017/wechatUser',function (err,db) {
global.mongodb = db;
console.log('connect to mongo success!')
})<file_sep>/**
* Created by Administrator on 2016/8/30.
*/
var S = require('../service/wxcheckservice');
var eventService = require('../service/eventservice');
var textService = require('../service/textserviec');
var imageService= require('../service/imageservice');
var voiceService = require('../service/voiceservice');
exports.wxOuath = function *() {
var echostr = this.query.echostr;
var signature = this.query.signature;
var timestamp = this.query.timestamp;
var nonce = this.query.nonce;
var isCheck = S.wxcheckSignature(signature,timestamp,nonce);
if (isCheck) this.body = echostr;
else this.body = 'failed';
}
exports.wxPost = function *() {
var xml = this.request.body;
var msgType = xml.xml.MsgType[0];
var token = this.request.token;
switch (msgType){
case 'event':
yield eventService.eventHandle(xml,token);
this.body = 'success';
break
case 'text':
yield textService.textHandle(xml,token);
this.body = 'success';
break
case 'image':
yield imageService.imageHandle(xml,token);
this.body = 'success';
break
case 'voice':
yield voiceService.voiceHandle(xml,token);
this.body = 'success';
break
default:
this.body = 'success';
}
}<file_sep>/**
* Created by Administrator on 2016/8/30.
*/
var config = require('../config/config');
var httputils = require('./HttpUtils');
var tools = require('./Tools');
var redisTemplate = require('../db/redisTemplate');
exports.getwxToken = function *() {
var token = yield redisTemplate.get('wechat_accesstoken');
if (tools.isEmpty(token) ){
var opts = {
method: 'GET',
url: 'https://api.weixin.qq.com/cgi-bin/token',
qs: {
grant_type: 'client_credential',
appid: config.weixin.appID,
secret: config.weixin.appsecret
},
};
var result = yield httputils.request(opts);
result = JSON.parse(result);
token = result.access_token;
yield redisTemplate.set('wechat_accesstoken', token);
yield redisTemplate.expire('wechat_accesstoken', 7000);
return token;
}
return token;
}
<file_sep>/**
* Created by Administrator on 2016/8/28.
*/
var koa = require('koa');
var bodyParse = require('koa-bodyparser');
var config = require('./config/config');
var xmlParser = require('koa-xml-body').default;
var router = require('./router/router');
var HttpUtils = require('./utils/HttpUtils');
var redisTemplates = require('./db/redisTemplate');
require('./middleware/connectRedis');
require('./middleware/connectMongo');
var app = koa();
app.use(function *(next) {
var token = yield redisTemplates.get("wechat_accesstoken");
if (token == null){
var opts = {
'method' : 'GET',
'url' : 'https://api.weixin.qq.com/cgi-bin/token',
'qs' : {
'grant_type': 'client_credential',
'appid' : config.weixin.appID,
'secret' : config.weixin.appsecret
}
}
var tokenres = yield HttpUtils.request(opts);
token = JSON.parse(tokenres).access_token;
yield redisTemplates.set("wechat_accesstoken",token);
yield redisTemplates.expire('wechat_accesstoken',3600);
}
this.request.token = token;
yield next;
});
//app.use(function *(next) {
// global.mongodb = yield MongClient.connect('mongodb://192.168.100.2:27017/wechatUser');
// yield next;
//})
app.use(xmlParser());
app.use(bodyParse());
app.use(router.routes()).use(router.allowedMethods());
app.listen(10000);<file_sep>/**
* Created by Administrator on 2016/9/19.
*/
var qiniu = require('node-qiniu');
var request = require('request');
exports.voiceHandle = function *(postBody,token) {
var mediaid = postBody.xml.MediaId[0];
var format = postBody.xml.Format[0];
console.log(format)
console.log(mediaid);
mongodb.collection('message').insertOne(postBody);
qiniu.config({
access_key : '<KEY>',
secret_key : 'JRqORkckw7iGjVedNJNSyO5ND-88EmWObL-gOYiU'
})
var Bucket = qiniu.bucket('zhougy');
var puttingStream = Bucket.createPutStream(mediaid+'.'+format);
request.get('https://api.weixin.qq.com/cgi-bin/media/get?access_token='+token+'&media_id='+mediaid).pipe(puttingStream)
.on('error', function(err) {
console.error(err);
})
.on('end', function(reply) {
console.dir(reply);
});
}<file_sep>/**
* Created by Administrator on 2016/8/30.
*/
var wxAPI= require('./wxapiservice');
exports.textHandle = function *(postBody,token) {
var openid = postBody.xml.FromUserName[0];
var content = postBody.xml.Content[0];
switch (content){
case '书签':
var text = '波叔每天都有更新书签哦,不过微信后台覆盖到全部用户要24小时。你也可以移步「美丽阅读」app,定时同步更新。';
var msg = yield wxAPI.sendMessage(openid,token,text);
break
case '以书识人':
var text = 'https://share.beautifulreading.com/bookface';
var msg = yield wxAPI.sendMessage(openid,token,text);
break
default:
break
}
// if (content == '书签'){
// var text = '波叔每天都有更新书签哦,不过微信后台覆盖到全部用户要24小时。你也可以移步「美丽阅读」app,定时同步更新。';
// var msg = yield wxAPI.sendMessage(openid,token,text);
// }
mongodb.collection('message').insertOne({'openid':openid,'msgtype':'text','message':content})
}<file_sep>/**
* Created by Administrator on 2016/9/11.
*/
var schedule = require('node-schedule');
var request = require('request');
var redis = require('redis');
var client = redis.createClient(6379,'192.168.100.2',function () {
});
//var data = [10,27,30,40,50,60];
var rule = new schedule.RecurrenceRule();
rule.minute = 56;
var j = schedule.scheduleJob(rule, function(){
request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc1a121872c82fa58&secret=<KEY>',function (err,response,body) {
var token = JSON.parse(body).access_token;
client.set('wechat_accesstoken',token,function () {
})
})
});
|
9bc5cb4183b289b4066765d011fea0aad1f1f9e4
|
[
"JavaScript"
] | 9
|
JavaScript
|
zgy03916618421/wxuserAnalystic
|
476bbaece2072975b9af81235b319cb193ca6ad8
|
33724f231fb1711c8f9b533ca55d0d4d0b25d649
|
refs/heads/main
|
<repo_name>Jordyvm/Django_portfolio<file_sep>/src/pages/views.py
from django.shortcuts import render
def home_view(request, *args, **kwargs):
context = {"home_active": "active"}
return render(request, 'home.html', context)
def about_view(request, *args, **kwargs):
context = {"about_active": "active"}
return render(request, 'about.html', context)
def contact_view(request, *args, **kwargs):
context = {"contact_active": "active"}
return render(request, 'contact.html', context)<file_sep>/src/posts/migrations/0002_auto_20200825_1704.py
# Generated by Django 3.1 on 2020-08-25 15:04
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('posts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Skills',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('skill', models.CharField(max_length=30)),
],
options={
'ordering': ('skill',),
},
),
migrations.AddField(
model_name='post',
name='MediaTechnology',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='post',
name='date',
field=models.DateField(default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='post',
name='image',
field=models.ImageField(default='', upload_to=''),
),
migrations.AddField(
model_name='post',
name='skills',
field=models.ManyToManyField(to='posts.Skills'),
),
]
<file_sep>/src/posts/models.py
from django.db import models
# Create your models here.
class Skill(models.Model):
skill = models.CharField(max_length=30)
def __str__(self):
return self.skill
class Meta:
ordering = ('skill',)
class Post(models.Model):
title = models.CharField(max_length=120)
date = models.DateField()
description = models.TextField()
image = models.ImageField(default='')
skills = models.ManyToManyField(Skill)
MediaTechnology = models.BooleanField(default=False)
def __str__(self):
return self.title
<file_sep>/src/portfolio/urls.py
from django.contrib import admin
from django.urls import path
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from posts.views import post_list_view
from posts.views import post_detail_view
from pages.views import home_view
from pages.views import about_view
from pages.views import contact_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
path('about/', about_view, name='about'),
path('contact/', contact_view, name='contact'),
path('detail/<int:detail_id>', post_detail_view, name='detail'),
path('all/', post_list_view, name='all')
]
urlpatterns += staticfiles_urlpatterns()
<file_sep>/src/posts/admin.py
from django.contrib import admin
# Register your models here.
from .models import Post
from .models import Skill
admin.site.register(Post)
admin.site.register(Skill)<file_sep>/src/posts/views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, "posts/all.html", context)
def post_detail_view(request, detail_id):
post_object = Post.objects.get(id=detail_id)
context = {
'post_object': post_object
}
return render(request, "posts/detail.html", context)<file_sep>/src/posts/templates/posts/all.html
{% extends 'base.html' %}
{% load static %}
{% block page_title %}
All Posts
{% endblock %}
{% block main_content %}
<h2>This is the list of posts</h2>
<div class="row">
{% for post in post_objects %}
<div class="col-md-6 cont">
<img class="img-fluid w-100 image" src="{% static post.image %}" alt="My image"/>
<div class="overlay">
<div class="overlay_text"></div>
<h4>{{ post.title }}</h4>
<h5>{{ post.date }}</h5>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
|
4e8a0e9b11d481dd9ef36c1e87f35b14222cacf7
|
[
"Python",
"HTML"
] | 7
|
Python
|
Jordyvm/Django_portfolio
|
da0c49275b0c3b1ea362e5cf402bef8e86c193e4
|
15a3cdefcc2b7fe2f0f996903baab9983749c329
|
refs/heads/master
|
<repo_name>kjsingh002/Head-First-Android-Beer-Adviser<file_sep>/app/src/main/java/com/kjsingh002/beeradviser/MainActivity.java
package com.kjsingh002.beeradviser;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Spinner beerColors;
private Button findBeer;
private TextView display_brands;
private BeerExpert beerExpert;
private List<String> brands;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beerColors = findViewById(R.id.beer_colors);
findBeer = findViewById(R.id.find_beer);
display_brands = findViewById(R.id.display_brands);
beerExpert = new BeerExpert();
brands = new ArrayList<>();
findBeer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* This is my way of simplifying things
display_brands.setText("");
brands = beerExpert.getBrands(beerColors.getSelectedItem().toString());
for (String brand: brands){
display_brands.append(brand + '\n');
}
*/
// This is how book is doing
brands = beerExpert.getBrands(beerColors.getSelectedItem().toString());
StringBuilder builder = new StringBuilder();
for (String brand:brands){
builder.append(brand).append("\n");
}
display_brands.setText(builder);
}
});
}
}
|
5dc06d16027b3fc3c612177ccf632b8d1e8c905b
|
[
"Java"
] | 1
|
Java
|
kjsingh002/Head-First-Android-Beer-Adviser
|
a939d6a309a307231ed8ddee9b679bcad87e5f62
|
8499a4805d4c6a1dc3509d5b5c9dea3ec85f0303
|
refs/heads/master
|
<repo_name>sombraguerrero/LargeRandom<file_sep>/LargeRandom/Program.cs
using System;
namespace LargeRandom
{
class Program
{
static void Main(string[] args)
{
Random random = new();
long bigNext = LongRandom.NextLong(random);
long bigNextMax = LongRandom.NextLong(random, 6000000000);
long bigNextRange = LongRandom.NextLong(random, 5000000000, 7000000000);
Console.WriteLine($"Random 64-bit integer: {bigNext}{Environment.NewLine}Random 64-bit integer up to 6 billion: {bigNextMax}{Environment.NewLine}Random 64-bit integer between 5 and 7 billion: {bigNextRange}.");
}
}
}
|
ee12a67128adc732875b2630712b766fb6844838
|
[
"C#"
] | 1
|
C#
|
sombraguerrero/LargeRandom
|
d8e62368786997322fcdb5e4b02e94a65cebc593
|
385a02b3c77d5fb125a2ad0a5f849d13294f7ce4
|
refs/heads/master
|
<file_sep>package leecode;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/10/16 14:37
* description: LeeCode 19: 删除链表的倒数第N个节点
* version: V1.0
* ******************************
*/
public class LeeCode19 {
/***
* LeeCode 19: 删除链表的倒数第N个节点
* 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点
*
* 示例:
* 给定一个链表: 1->2->3->4->5, 和 n = 2.
* 当删除了倒数第二个节点后,链表变为 1->2->3->5.
*/
public static void main(String[] args){ }
/***
* 执行用时 :1 ms, 在所有 java 提交中击败了86.05%的用户
* 内存消耗 :34.9 MB, 在所有 java 提交中击败了86.69%的用户
*/
private static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode current = head;
int length = 0;
while (current != null) {
current = current.next;
length++;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode linkedNode = dummy;
length = length - n;
while (length > 0) {
linkedNode = linkedNode.next;
length--;
}
linkedNode.next = linkedNode.next.next;
return dummy.next;
}
}
<file_sep>package leecode;
import java.util.HashMap;
import java.util.Map;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/10/16 10:31
* description: LeeCode141 环形链表
* version: V1.0
* ******************************
*/
public class LeeCode141 {
/***
* 判断循环一周的方式是: p->next==head->next
* 执行用时 : 6 ms , 在所有 java 提交中击败了 25.65% 的用户
* 内存消耗 : 37.1 MB , 在所有 java 提交中击败了 97.08% 的用户
*/
public static boolean hasCycle(ListNode head) {
Map<ListNode, ListNode> map = new HashMap<>();
while (head != null && head.next != null) {
if (map.containsKey(head)) {
return true;
} else {
map.put(head, head);
}
head = head.next;
}
return false;
}
}
<file_sep>package leecode;
import java.util.List;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/7/16 22:28
* description: LeeCode 24题
* version: V1.0
* ******************************
*/
public class LeeCode24 {
/***
* 24. 两两交换链表中的节点
* 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
* 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
* 示例:
* 给定 1->2->3->4, 你应该返回 2->1->4->3.
*/
public static void main(String[] args){
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(3);
ListNode l3 = new ListNode(2);
ListNode l4 = new ListNode(5);
l1.next = l2;
l2.next = l3;
l3.next = l4;
// System.out.println(swapPairs(l1));
System.out.println(swapPairsByOther(l1));
}
/**
* 执行用时 :1 ms, 在所有 Java 提交中击败了86.36%的用户
* 内存消耗 :35.5 MB, 在所有 Java 提交中击败了48.16%的用户
*
* 总结一下递归:
*
* 无论怎么看都是三个点
* 1.确定重复调用的逻辑
* 2.确定边界返回
* 3.返回值
*
* 技巧:再遇到回溯法的题目可以尝试以少数据做强行计划,符合后再继续扩大数据量测试
*/
private static ListNode swapPairs(ListNode head) {
// 对应边界返回
if (head == null || head.next == null) {
return head;
}
// 重复调用逻辑 -》 head连接next -> next 连接 head
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
private static ListNode swapPairsByOther(ListNode head) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode temp = pre;
while (temp.next != null && temp.next.next != null) {
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
}
<file_sep>package leecode;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/13 12:58
* @description: LeeCode20题- 有效的括号
* @version: V1.0
* ******************************
*/
public class LeeCode20 {
/***
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
* 有效字符串需满足:
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 输入: "{[]}" 输出: true
* 输入: "([)]" 输出: false
*/
public static void main(String[] args){
String s = "([]{{}})[{}[[]]]";
System.out.println(betterIsVaild(s));
}
/***
* 所有的括号都可以一层一层的消除,那么消除到最后即只剩下最小单元,只需要判断最小单元是否有值即可
* 如果有,则代表false,无则代表true
* 执行用时 : 178 ms, 在Valid Parentheses的Java提交中击败了5.04% 的用户
* 内存消耗 : 48.1 MB, 在Valid Parentheses的Java提交中击败了5.01% 的用户
* @param s
* @return
*/
public static boolean isValid(String s) {
// 循环去除(){}[]干扰项
String newString = s;
boolean flag = true;
while (flag) {
newString = newString.replace("()","").replace("{}","").replace("[]","");
if (newString.contains("()") || newString.contains("{}") || newString.contains("[]")) {
flag = true;
} else {
flag = false;
}
}
return newString.equals("");
}
/***
* 优化分析: 上述方案中,replace方法过于费时,如果字符串过长则可以想象处理的数量级有多大,因此进行优化
* 通过栈的方式进行分析,时间复杂度O(n),巧妙之处在于 - 从左边判断到右边比较难,可以考虑从右边开始判断
* 执行用时 : 9 ms, 在Valid Parentheses的Java提交中击败了70.58% 的用户
* 内存消耗 : 33.8 MB, 在Valid Parentheses的Java提交中击败了91.24% 的用户
* @param s
* @return
*/
public static boolean betterIsVaild(String s) {
s = s.trim();
if(s.equals("") || s == null) return true;
Map<Character,Character> map = new HashMap<Character,Character>();
map.put(')','(');
map.put('}','{');
map.put(']','[');
Stack<Character> stack = new Stack<Character>();
for(int i = 0 ;i<s.length();i++){
// 字符串循环
char c = s.charAt(i);
// 判断是否有右边的括号,因为!! 正确来说,有右边的,左边的就一定存在,否则就是错的
if(map.containsKey(c)){
char temp = stack.empty()?'#':stack.pop();
// 对比失败即是错误的
if(temp != map.get(c)) return false;
}else stack.push(c);
}
return stack.empty();
}
}
<file_sep>package leecode.dynamic;
import java.util.HashMap;
import java.util.Map;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/12/25 10:26
* description: MoneyHandle
* 博文: https://blog.csdn.net/u013309870/article/details/75193592
* version: V1.0
* ******************************
*/
public class CutApp {
private static int[] arr = new int[11];
static {
arr[0] = 0;
arr[1] = 1;
arr[2] = 5;
arr[3] = 8;
arr[4] = 9;
arr[5] = 10;
arr[6] = 17;
arr[7] = 17;
arr[8] = 20;
arr[9] = 24;
arr[10] = 30;
}
/***
* 递归方法
*/
private static int cut (int[] arr, int length) {
if (length == 0) {
return 0;
}
int result = Integer.MIN_VALUE;
for (int i = 1; i <= length; i++) {
System.out.println(length - 1);
result = Math.max(result, arr[i] + cut(arr, length - i));
}
return result;
}
/***
* 备忘录算法
*/
private static Map<Integer, Integer> map = new HashMap<>();
private static int cutMap (int[] arr, int length) {
if (length == 0) {
return 0;
}
int result = Integer.MIN_VALUE;
for (int i = 1; i <= length; i++) {
if (map.containsKey(length - i)) {
result = Math.max(result, arr[i] + map.get(length - i));
} else {
int curr = cutMap(arr, length - i);
map.put(length - i, curr);
result = Math.max(result, arr[i] + curr);
}
}
return result;
}
/**
* 动态规划
*/
private static int dynamicHandle (int[] arr, int length) {
int[] result = new int[length + 1];
for (int i = 1; i <= length; i++) {
int num = Integer.MIN_VALUE;
for (int j = 1; j <= i; j++) {
num = Math.max(num, arr[j] + result[i - j]);
}
result[i] = num;
}
return result[length];
}
public static void main(String[] args){
long start = System.currentTimeMillis();
System.out.println("Cut: " + cut(arr, 9) + " , time: " + (System.currentTimeMillis() - start));
long mapStart = System.currentTimeMillis();
System.out.println("CutMap: " + cutMap(arr, 9) + " , time: " + (System.currentTimeMillis() - mapStart));
long dyStart = System.currentTimeMillis();
System.out.println("DynamicHandle: " + dynamicHandle(arr, 9) + " , time: " + (System.currentTimeMillis() - dyStart));
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/28 10:59
* @description: 定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
* 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
* 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素
* @version: V1.0
* ******************************
*/
public class LeeCode27 {
/***
* 示例 1:
* 给定 nums = [3,2,2,3], val = 3,
* 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
* 你不需要考虑数组中超出新长度后面的元素。
*/
public static void main(String[] args){
int[] nums = {0,1,2,2,3,0,4,2};
System.out.println(removeElement(nums,2));
}
/***
* 双指针法-解决数组赋值以及降低空间复杂度问题
*/
public static int removeElement(int[] nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}
<file_sep>package leecode;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/9/10 23:07
* description: LeeCode 75 颜色分类
* version: V1.0
* ******************************
*/
public class LeeCode75 {
/***
* 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
*
* 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
*
* 注意:
* 不能使用代码库中的排序函数来解决这道题。
*
* 示例:
*
* 输入: [2,0,2,1,1,0]
* 输出: [0,0,1,1,2,2]
* 进阶:
*
* 一个直观的解决方案是使用计数排序的两趟扫描算法。
* 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
* 你能想出一个仅使用常数空间的一趟扫描算法吗?
*/
public static void main(String[] args){
int[] nums = {2,0,2,1,1,0};
// sortColors(nums);
sortColorsByMaoPao(nums);
}
/**
* 傻逼排序
* 执行结果:通过显示详情执行用时 :25 ms, 在所有 Java 提交中击败了8.21%的用户
* 内存消耗 :36.2 MB, 在所有 Java 提交中击败了35.71%的用户
*/
private static void sortColors(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] < nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
for (int num : nums) {
System.out.println(num);
}
}
/**
* 冒泡
* 执行结果:通过显示详情执行用时 :25 ms, 在所有 Java 提交中击败了8.21%的用户
* 内存消耗 :36.2 MB, 在所有 Java 提交中击败了35.71%的用户
*/
private static void sortColorsByMaoPao (int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = nums.length - 1; j > i ; j--) {
if (nums[i] > nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
for (int num : nums) {
System.out.println(num);
}
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/13 14:30
* @description: LeeCode-21题 连接两个有序链表
* @version: V1.0
* ******************************
*/
public class LeeCode21 {
/***
* 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
* 输入:1->2->4, 1->3->4
* 输出:1->1->2->3->4->4
*/
public static void main(String[] args){
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
} else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if (l1 != null) {
cur.next = l1;
} else if (l2 != null) {
cur.next = l2;
}
return dummyHead.next;
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/22 9:29
* @description: LeeCode29题
* @version: V1.0
* ******************************
*/
public class LeeCode29 {
/***
* 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符
* 返回被除数 dividend 除以除数 divisor 得到的商
*
* 输入: dividend = 10, divisor = 3
* 输出: 3
*
* 被除数和除数均为 32 位有符号整数。
* 除数不为 0。
* 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
*/
public static void main(String[] args){
int dividend = -2147483648;
int divisor = 2;
System.out.println(divide(dividend, divisor));
}
public static int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
if (dividend == Integer.MIN_VALUE && divisor == 1) {
return Integer.MIN_VALUE;
}
Long pre = Math.abs((long)dividend);
Long shu = Math.abs((long)divisor);
// 异或运算
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
// 商的结果
int result = 0;
// 位运算左移的初始值
int k = 31;
while (pre >= shu) {
for (int i = k; i >= 0; i--) {
Long temp = pre - (shu << i);
if (temp >= 0) {
// 如果左移到尽头,则result商加上对应的结果,
result += 1 << i;
// 更改被除数的值, 同时更新左移的初始值,因为下一轮的i肯定比上一轮的小
pre = temp;
k = i;
break;
}
}
}
return result * sign;
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/28 11:09
* @description: 给定一个 haystack 字符串和一个 needle 字符串,
* 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1
* @version: V1.0
* ******************************
*/
public class LeeCode28 {
/***
* 示例 1:
* 输入: haystack = "hello", needle = "ll"
* 输出: 2
*/
public static void main(String[] args){
String haystack = "aaaaa", needle = "bba";
System.out.println(strStr(haystack,needle));
}
/***
* Java源码效率:
* 执行用时 : 1 ms, 在Implement strStr()的Java提交中击败了99.89% 的用户
* 内存消耗 : 35.4 MB, 在Implement strStr()的Java提交中击败了88.66% 的用户
*
* 自行实现strStr-字符串索引搜索
* 执行用时 : 2 ms, 在Implement strStr()的Java提交中击败了89.39% 的用户
* 内存消耗 : 35.9 MB, 在Implement strStr()的Java提交中击败了84.24% 的用户
*/
public static int strStr(String haystack, String needle) {
if ("".equals(haystack.length()) || "".equals(needle.length()) || haystack.length() < needle.length()) {
return -1;
}
int len = needle.length();
for (int i = 0; i < haystack.length() - len + 1; i++) {
String key = haystack.substring(i, i + len);
if (needle.equals(key)) {
return i;
}
}
return -1;
}
}
<file_sep>package leecode;
import java.util.*;
/***
* 给定一个字符串,找出不含有重复字符的最长子串的长度。
* 输入: "abcabcbb"
* 输出: 3
* 解释: 无重复字符的最长子串是 "abc",其长度为 3
*
* LeeCode解析:https://leetcode-cn.com/articles/longest-substring-without-repeating-characters/
*
* @author 柯贤铭
* @date 2018年11月2日
* @email <EMAIL>
*/
public class LeeCode3 {
public static void main(String[] args) {
String str = "abbabcbb";
System.out.println(myLeeCode(str));
}
/***
* @description: 经典算法问题, 始终维护一个子串,并保存最大长度, 一次遍历即可得到结果
*
* 执行用时 :14 ms, 在所有 java 提交中击败了50.62%的用户
* 内存消耗 :37.7 MB, 在所有 java 提交中击败了91.49%的用户
*/
private static int myLeeCode (String s) {
StringBuilder str = new StringBuilder();
int max = 0;
for (int i = 0; i < s.length(); i++) {
String tar = s.charAt(i) + "";
int index = str.indexOf(tar);
if (index == -1) {
str.append(tar);
}else {
str = new StringBuilder(str.substring(index + 1, str.length()));
str.append(tar);
}
max = Math.max(max, str.length());
}
return max;
}
static int lengthOfLongestSubstring(String s) {
// 无重复子串最大长度
int maxLength = 0;
int head = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
for (int index = head; index < i; index++) {
if (s.charAt(index) == c) {
int currLength = i - head;
maxLength = maxLength > currLength ? maxLength : currLength;
head = (index + 1);
break;
}
}
}
int currLength = s.length() - head;
maxLength = maxLength > currLength ? maxLength : currLength;
return maxLength;
}
/**
* 二级解法
* @param s
* @return int
*/
static int leeCode_Step_2 (String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
/**
* 终极解法
* @param s
* @return int
*/
static int leeCode (String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}
<file_sep>package leecode;
import java.util.*;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/3/28 20:33
* @description: LeeCode15题
* @version: V1.0
* ******************************
*/
public class LeeCode15 {
/***
* 给定一个包含 n 个整数的数组 nums
* 判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
*/
public static void main(String[] args){
//int[] nums = {-5,-1,-5,-4,2,1,-1,2,-4,-3,-2,-4};
int[] nums = {0,0,0};
System.out.println(threeSum(nums));
}
public static List<List<Integer>> threeSum(int[] nums) {
if (nums.length < 3) {
return new ArrayList<>();
}
Arrays.sort(nums);
List<List<Integer>> lists = new ArrayList<>();
int len = nums.length;
for (int i = 0; i <= len - 3; i++) {
// 性能优化-三个数除非全是0否则左指针一定是负数,如果数字重复,也没有意义
if (nums [i] > 0 || (i > 0 && nums[i] == nums[i - 1])) {
continue;
}
// 每次偏移初始化移动的k,j
int k = i + 1;
int j = len - 1;
while (k < j) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
/***
* 关键问题在于去重如何节约时间
* 原方案: 先判断是否存在,然后去重
* 新方案:通过逻辑判断后去除多余,重复数据,直接添加进集合,效率高很多!
*/
// List<Integer> list = new ArrayList<>();
// list.add(nums[i]);
// list.add(nums[k]);
// list.add(nums[j]);
// if (!lists.contains(list)) {
// lists.add(list);
// }
lists.add(Arrays.asList(nums[i], nums[k], nums[j]));
// 重复数据不需要处理
while (k < j && nums[k] == nums[k + 1]) {
k++;
}
while (k < j && nums[j] == nums[j - 1]) {
j--;
}
j--;
k++;
}
if (sum > 0) {
j--;
} else if (sum < 0) {
k++;
}
}
}
return lists;
}
public static List<List<Integer>> LeeCode (int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (nums.length < 3) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int l = i + 1;
int r = nums.length - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
while (l < r && nums[l] == nums[l + 1]) l++;
while (l < r && nums[r] == nums[r - 1]) r--;
l++;
r--;
} else if (sum < 0) {
l++;
} else {
r--;
}
}
}
return res;
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/28 16:46
* @description: 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
* 如果不存在最后一个单词,请返回 0 。
* 说明:一个单词是指由字母组成,但不包含任何空格的字符串。
* @version: V1.0
* ******************************
*/
public class LeeCode58 {
/***
* 输入: "Hello World"
* 输出: 5
*/
public static void main(String[] args){
String str = "";
System.out.println(lengthOfLastWord(str));
}
/***
* mine
* 执行用时 : 3 ms, 在Length of Last Word的Java提交中击败了81.11% 的用户
* 内存消耗 : 34.8 MB, 在Length of Last Word的Java提交中击败了86.65% 的用户
*/
public static int lengthOfLastWord(String s) {
String[] strings = s.split(" ");
if (strings.length == 0) {
return 0;
} else {
return strings[strings.length - 1].length();
}
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/3/26 8:32
* @description: LeeCode第五题
* @version: V1.0
* @deprecated
* ******************************
*/
public class LeeCode5 {
/***
* 动态规划算法:https://www.jianshu.com/p/a7741619dd58
* 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
* 输入: "babad"
* 输出: "bab"
* 注意: "aba" 也是一个有效答案。
*/
public static void main(String[] args){
//String str = "<KEY>";
String str = "abacega";
System.out.println(dpMethod(str));
}
// ********************************** 暴力法 时间超时 ***************************************
private static String handle(String s) {
// 针对特定超长文本取巧做法
if (isPalindromic(s)) {
return s;
}
String ans = "";
int max = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j <= len; j++) {
String test = s.substring(i, j);
if (isPalindromic(test) && test.length() > max) {
ans = s.substring(i, j);
max = Math.max(max, ans.length());
}
}
}
return ans;
}
private static boolean isPalindromic(String s) {
int len = s.length();
for (int i = 0; i < len / 2; i++) {
if (s.charAt(i) != s.charAt(len - i - 1)) {
return false;
}
}
return true;
}
// ***************************************************************************************
// 动态规划法---入门级别
static String dpMethod (String s) {
int len = s.length();
int maxLen = 0;
String res = "";
boolean[][] dp = new boolean[len][len];
for(int i = len - 1;i >= 0;i--){
for(int j = i;j < len;j++){
// 1)当前遍历到的子串i~j是否是回文子串取决于i+1~j-1,也就是i~j中间的子串是否是回文并且s[i]是否等于s[j];
// 2)dp[i][j]是为true则意味着i~j是回文子串,则在下面判断后对res进行更新;如果为false,则该子串不是回文子串,开始遍历下一个子串
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if(dp[i][j] && j - i + 1 > maxLen){
// 如果该子串长度更长,则更新res
res = s.substring(i, j + 1);
maxLen = res.length();
}
}
}
return res;
}
}
<file_sep>package leecode;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/10/16 10:30
* description: ListNode
* version: V1.0
* ******************************
*/
public class ListNode {
int val;
ListNode next = null;
ListNode(int x) { val = x; }
@Override
public String toString() {
return "ListNode [val=" + val + ", next=" + next + "]";
}
}
<file_sep>package leecode;
import java.util.ArrayList;
import java.util.List;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/25 9:17
* @description: LeeCode - 6题
* @version: V1.0
* ******************************
*/
public class LeeCode6 {
/***
* 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
*
* 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
* L C I R
* E T O E S I I G
* E D H N
* 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
* @param args
*/
public static void main(String[] args){
String s = "LEETCODEISHIRING";
int numRows = 3;
System.out.println(leeCode(s,numRows));
}
/***
* 按行排序
* 思路
* 通过从左向右迭代字符串,我们可以轻松地确定字符位于 Z 字形图案中的哪一行。
*
* 我们可以使用Math.min(numRows, s.length())个列表来表示 Z 字形图案中的非空行。
* 从左到右迭代 ss,将每个字符添加到合适的行。可以使用当前行和当前方向这两个变量对合适的行进行跟踪。
* 只有当我们向上移动到最上面的行或向下移动到最下面的行时,当前方向才会发生改变。
*
* 注意关键词,方向,自下而上是一种方向!,另一种即自上而下
*/
public static String leeCode (String s, int numRows) {
if (numRows <= 1) {
return s;
}
List<StringBuffer> list = new ArrayList<>();
// 确定共有几行数据
for (int i = 0; i < Math.min(s.length(), numRows); i++) {
StringBuffer row = new StringBuffer();
list.add(row);
}
// 这里是关键点,控制读取的方向
int currRow = 0;
int flag = -1;
// 循环遍历,把值放进去,同时判断下一次放入的位置或者说方向
for (char c : s.toCharArray()) {
list.get(currRow).append(c);
if (currRow == 0 || currRow == numRows - 1) {
flag *= -1;
}
currRow += flag;
}
StringBuffer result = new StringBuffer();
for (StringBuffer sb : list) {
result.append(sb);
}
return result.toString();
}
/***
* 这个规律能总结出来,真是神了,事实证明各种方式的思考都应该尝试,即使它效率很低。。。
* @param s
* @param numRows
* @return
*/
public static String convert(String s, int numRows) {
int len = s.length();
if (numRows == 1) return s;
int d = 2 * numRows - 2;
String outstr = "";
//余数
for(int i = 0; i < numRows; i++){
for(int j = 0; j < len; j++){
int ys = j % d;
if(ys == i){
outstr += s.charAt(j);
continue;
}
if(ys >= numRows && (d - ys) == i)
outstr += s.charAt(j);
}
}
return outstr;
}
}
<file_sep>package leecode;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/28 11:30
* @description: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引
* 如果目标值不存在于数组中,返回它将会被按顺序插入的位置
* @version: V1.0
* ******************************
*/
public class LeeCode35 {
/***
* 示例 1:
* 输入: [1,3,5,6], 5
* 输出: 2
*/
public static void main(String[] args){
int[] nums = {1,3,5,6};
System.out.println(searchInsert(nums, 2));
}
/***
* 执行用时 : 1 ms, 在Search Insert Position的Java提交中击败了98.10% 的用户
* 内存消耗 : 37.9 MB, 在Search Insert Position的Java提交中击败了79.96% 的用户
*
*
*/
public static int searchInsert(int[] nums, int target) {
int i = 0;
int len = nums.length;
while (true) {
if (i == len) {
return len;
} else if (target <= nums[i]) {
return i;
}
i++;
}
}
}
<file_sep>package leecode;
import java.util.Arrays;
import java.util.Stack;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/10/17 9:10
* description: LeeCode496 下一个更大元素 I
* version: V1.0
* ******************************
*/
public class LeeCode496 {
/***
* 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
* nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
*
* 示例 1:
* 输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
* 输出: [-1,3,-1]
* 解释:
* 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
* 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
* 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
*/
public static void main(String[] args){
int[] nums1 = {4,1,2};
int[] nums2 = {1,3,4,2};
System.out.println(Arrays.toString(nextGreaterElement(nums1, nums2)));
}
/***
* 执行用时 :6 ms, 在所有 java 提交中击败了81.40%的用户
* 内存消耗 :36.7 MB, 在所有 java 提交中击败了84.67%的用户
*/
private static int[] nextGreaterElement(int[] nums1, int[] nums2) {
for (int i = 0; i < nums1.length; i++) {
int num = nums1[i];
label:
for (int k = 0; k < nums2.length; k++) {
if (num != nums2[k]) {
continue;
}
if (num == nums2[k]) {
int index = k;
while (index < nums2.length) {
if (nums2[index] > num) {
nums1[i] = nums2[index];
break label;
}
index++;
}
nums1[i] = -1;
break;
}
}
}
return nums1;
}
}
<file_sep>package leecode;
/**
* ******************************
* author: 柯贤铭
* createTime: 2019/10/16 10:24
* description: LeeCode206
* version: V1.0
* ******************************
*/
public class LeeCode206 {
/***
* 反转链表
*/
public static void main(String[] args) {
ListNode l1 = new ListNode(5);
ListNode l2 = new ListNode(6);
l1.next = l2;
System.out.println(reverseList(l1));
}
/***
* 执行用时 : 0 ms , 在所有 java 提交中击败了 100.00% 的用户
* 内存消耗 : 36.8 MB , 在所有 java 提交中击败了 50.96% 的用户
*/
private static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
<file_sep>package leecode;
import java.util.ArrayList;
import java.util.List;
/**
* ******************************
*
* @author: 柯贤铭
* @createTime: 2019/4/5 9:11
* @description: LeeCode17题
* @version: V1.0
* ******************************
*/
public class LeeCode17 {
static final String[] word = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
/***
* 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
* 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
*/
public static void main(String[] args){
String digits = "23";
System.out.println(letterCombinations(digits));
}
public static List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return res;
}
// 返回结果
String result = new String();
// 调用递归进行计算
dfs(digits, 0, res, result);
return res;
}
public static void dfs (String digits, int l, List<String> list, String result){
// 如果循环到和digits一样的层级就返回
if (l == digits.length()) {
list.add(result);
return;
}
// 获取目标索引对应字符串
String target = word[digits.charAt(l) - '0'];
for (int i = 0; i < target.length(); i++) {
// 加上当前数字对应索引为i的字符串,再进行递归,即求第二个数字的字符串
result += target.charAt(i);
dfs(digits, l + 1, list, result);
// 获取最后结果
result = result.substring(0, result.length() - 1);
}
}
}
|
5ef5a36aa73ada857d5e4f2e1e41c7de72029e12
|
[
"Java"
] | 20
|
Java
|
kkzhilu/LeeCode
|
8ad13067915592cf4255f5acca5bdfcfe8fbdeae
|
7a31ac025ad5301206befa646e4eb7b536bedeec
|
refs/heads/master
|
<file_sep>package com.tetrasoft.us.entity;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "PAYMENT")
public class PaymentEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Long cardNo;
private String cardHolderName;
@Column(name = "expire_date",columnDefinition = "DATE")
private LocalDate expirayDate;
private Integer cvv;
public PaymentEntity(Long cardNo, String cardHolderName, LocalDate expirayDate, Integer cvv) {
this.cardNo = cardNo;
this.cardHolderName = cardHolderName;
this.expirayDate = expirayDate;
this.cvv = cvv;
}
public PaymentEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getCardNo() {
return cardNo;
}
public void setCardNo(Long cardNo) {
this.cardNo = cardNo;
}
public String getCardHolderName() {
return cardHolderName;
}
public void setCardHolderName(String cardHolderName) {
this.cardHolderName = cardHolderName;
}
public LocalDate getExpirayDate() {
return expirayDate;
}
public void setExpirayDate(LocalDate expirayDate) {
this.expirayDate = expirayDate;
}
public Integer getCvv() {
return cvv;
}
public void setCvv(Integer cvv) {
this.cvv = cvv;
}
}
<file_sep>package com.tetrasoft.us.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tetrasoft.us.dto.PaymentDto;
import com.tetrasoft.us.entity.PaymentEntity;
import com.tetrasoft.us.service.IPaymentService;
@RestController
@RequestMapping("/api/customer")
public class PaymentController {
@Autowired
private IPaymentService paymentService;
@PostMapping("/payment")
public PaymentEntity proceedPayment(@RequestBody PaymentDto paymentDto) {
PaymentEntity paymentEntity = new PaymentEntity(paymentDto.getCardNo(), paymentDto.getCardHolderName(), paymentDto.getExpirayDate(), paymentDto.getCvv());
return paymentService.save(paymentEntity);
}
}
<file_sep>package com.tetrasoft.us.controller;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tetrasoft.us.dto.CustomerDto;
import com.tetrasoft.us.entity.CustomerDetailsEntiry;
import com.tetrasoft.us.service.ICustomerService;
@RestController
@RequestMapping("/api/customers")
public class CustomerController {
@Autowired
private ICustomerService customerService;
@PostMapping("/customer")
public CustomerDetailsEntiry saveCustomerDetails(@RequestBody CustomerDto customerDto) {
CustomerDetailsEntiry entity = new CustomerDetailsEntiry(customerDto.getFirstName(), customerDto.getLastName(),
customerDto.getEmail(), customerDto.getMobileNumber(), customerDto.getCity(), customerDto.getState(),
customerDto.getPincode(), false,getPnrNumber());
return customerService.save(entity);
}
@PutMapping("/update/{pnrNumber}")
public Optional<CustomerDetailsEntiry> updateCustomerStatus(@PathVariable Integer pnrNumber) {
return customerService.findByPnrNumber(pnrNumber);
}
public Integer getPnrNumber() {
return ThreadLocalRandom.current().nextInt(11, 900000 + 1);
}
}
<file_sep>package com.tetrasoft.us.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "CUSTOMERS")
public class CustomerDetailsEntiry {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer custId;
private String firstName;
private String lastName;
private String email;
private String mobileNumber;
private String city;
private String state;
private Integer pincode;
private Boolean bookingstatus;
private Integer pnrNumber;
public CustomerDetailsEntiry(String firstName, String lastName, String email, String mobileNumber,
String city, String state, Integer pincode, Boolean bookingstatus, Integer pnrNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.mobileNumber = mobileNumber;
this.city = city;
this.state = state;
this.pincode = pincode;
this.bookingstatus = bookingstatus;
this.pnrNumber = pnrNumber;
}
public CustomerDetailsEntiry() {
}
public Boolean getBookingstatus() {
return bookingstatus;
}
public void setBookingstatus(Boolean bookingstatus) {
this.bookingstatus = bookingstatus;
}
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(Integer pnrNumber) {
this.pnrNumber = pnrNumber;
}
}
<file_sep>package com.tetrasoft.us.service;
import org.springframework.data.jpa.repository.JpaRepository;
import com.tetrasoft.us.entity.PaymentEntity;
public interface IPaymentService extends JpaRepository<PaymentEntity, Integer>{
}
|
6afffabe81b2bf5418cd0c1ef3874c8b1c4561c9
|
[
"Java"
] | 5
|
Java
|
ssreeram85/flight-customer-service
|
d7174946d9bcbcdb3239cd6cd11aeddb36345476
|
66413eaf478525b1a597a029f587a3cef2dd1c15
|
refs/heads/master
|
<file_sep># memory-game
Better algo to shuffle Js Array
================================
// original reference
cons arrayCards = []
arrayCards.sort(function() {
return .5 - Math.random();
});
Problems with this:
Here are results after 10,000 iterations on how many times each number in your array hits index [0]
(I can give the other results too): 1 = 29.19%, 2 = 29.53%, 3 = 20.06%, 4 = 11.91%, 5 = 5.99%, 6 = 3.32%
It's fine if you need to randomize relatively small array and not dealing with cryptographic things.
Ref:https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
ES6
===
function shuffleCard(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array
}
<file_sep>document.addEventListener('DOMContentLoaded', () => {
//card options
let cardArray = [
{
name: 'cat1',
img: 'images/cat1.jpg'
},
{
name: 'cat2',
img: 'images/cat2.jpg'
},
{
name: 'cat3',
img: 'images/cat3.jpg'
},
{
name: 'cat6',
img: 'images/cat6.jpg'
},
{
name: 'cat5',
img: 'images/cat5.jpg'
},
{
name: 'cat7',
img: 'images/cat7.jpg'
},
{
name: 'cat1',
img: 'images/cat1.jpg'
},
{
name: 'cat2',
img: 'images/cat2.jpg'
},
{
name: 'cat3',
img: 'images/cat3.jpg'
},
{
name: 'cat6',
img: 'images/cat6.jpg'
},
{
name: 'cat5',
img: 'images/cat5.jpg'
},
{
name: 'cat7',
img: 'images/cat7.jpg'
}
]
//randomize card function
function shuffleCard(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array
}
cardArray = shuffleCard(cardArray)
cardArray.sort()
const grid = document.querySelector('.grid')
const gpic = document.querySelector('.picture')
const resultDisplay = document.querySelector('#result')
const alertDisplay = document.querySelector('#alert')
var cardsChosen = []
var cardsChosenId = []
var cardsWon = []
//create board
function createBoard(){
for(let i = 0; i < cardArray.length; i++){
var card = document.createElement('img')
card.setAttribute('src', 'images/end of.jpg')
card.setAttribute('data-id', i)
card.addEventListener('click', flipCard)
grid.appendChild(card)
}
}
createBoard()
//showing all pictures
function allPictures(){
for(let i = 0; i < cardArray.length; i++){
var card = document.createElement('img')
card.src = cardArray[i].img
gpic.appendChild(card)
cardArray.sort()
}
}
// allPictures()
//check for match
function checkForMatch(){
var cards = document.querySelectorAll('img')
const optionOneId = cardsChosenId[0]
const optionTwoId = cardsChosenId[1]
if(cardsChosen[0] === cardsChosen[1]){
alertDisplay.textContent = "You found a match"
cards[optionOneId].style.pointerEvents = "none";
cards[optionTwoId].style.pointerEvents = "none";
cardsWon.push(cardsChosen)
} else {
cards[optionOneId].setAttribute('src', 'images/end of.jpg')
cards[optionTwoId].setAttribute('src', 'images/end of.jpg')
alertDisplay.textContent = "Uh uh try again"
}
cardsChosen = []
cardsChosenId = []
resultDisplay.textContent = cardsWon.length
if(cardsWon.length === cardArray.length/2){
resultDisplay.textContent = "Congratulation!"
alertDisplay.textContent = ""
allPictures()
}
}
//flip card
function flipCard() {
var cardId = this.getAttribute('data-id')
console.log(cardId)
cardsChosen.push(cardArray[cardId].name)
console.log(cardsChosen)
cardsChosenId.push(cardId)
this.setAttribute('src', cardArray[cardId].img)
if(cardsChosen.length === 2){
setTimeout(checkForMatch, 500)
}
}
})
|
bdaaa8f8e05b44f254498fafa5a5f75c3e7b908a
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
tjeuput/memory-game
|
ad9fbd01b947494c7d623f35ba16328edd770d83
|
826dc2f3b844041d167feea664f449f72f07f950
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.