branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># hexchat-scripts
###Scripts for hexchat
Items in brackets are optional
rainbow.py: turns input into rainbow text, add a number to chose how many lines.
Usage: /r text [number of times to repeat]
superslap.py: slap people with various fish and sizes.
Usage: /slap [nick]
cookies.py: hand out cookies really easy with this script
Usage: /cookies [nick]
<file_sep>import hexchat
import random
__module_name__ = "cookies"
__module_author__ = "Glorfindel"
__module_version__ = "0.1"
cookieflavor = ['chocolate chip', 'M&M', 'peanut butter', 'gingersnap', 'plain', 'shortbread']
def cookie(word, word_eol, userdata):
if len(word) < 1:
hexchat.command("me passes out %s cookies" %(random.choice(cookieflavor)))
elif len(word) > 1:
hexchat.command("me hands %s a %s cookie" %(word[1], random.choice(cookieflavor)))
return hexchat.EAT_ALL
hexchat.hook_command("cookies",cookie)
hexchat.prnt("Cookies V0.1 loaded and ready to be eaten!")
<file_sep># Type /slap <nick> to slap some one.
import hexchat
import random
__module_name__ = "Super Slap"
__module_version__ = "1.0"
__module_description__ = "Slap script with random items and sizes"
__author__ = "Glorfindel"
full_name = "{} v{} by {}".format(__module_name__,__module_version__,__author__)
help_hook = "\"/slap [nick]\" will slap a [nick]."
items = ["bass", "trout", "salmon", "bluegill", "goldfish", "catfish", "dogfish", "shark", "piranha", "stingray", "jellyfish", "sink", "showerhead", "table", "television", "laptop", "chair", "lamp", "lead pipe", "copy of DOS", "copy of OSX", "copy of OS/2", "an octothorpe", "a copy of Hexchat", "a copy of ubottu"]
size = ["big", "ginormous", "small", "massively small", "nonexistant"]
def cmd_slap(word, word_eol, userdata):
slapstring = "with a %s %s" %(random.choice(size), random.choice(items))
if len(word) < 2:
hexchat.prnt("Choose a nick please")
return hexchat.EAT_ALL
if len(word) == 2:
hexchat.command("me slaps %s around a bit %s " %(word[1], slapstring))
return hexchat.EAT_ALL
hexchat.hook_command("slap", cmd_slap)
print "Super Slap 1.0 By Glorfindel Loaded"
<file_sep>import xchat, re
import string
__module_name__ = "Rainbow"
__module_version__ = "1.0.0"
__module_description__ = "Generates rainbow colored versions of the text you enter. Post it for the specified line-count"
def Rainbow(text,offset):
colorlist = ["\x034","\x037","\x038","\x039","\x0311","\x0312","\x0313","\x036","\x034"]
rainbowed = ""
for i in xrange(len(text)):
rainbowed += (colorlist[(i+offset)%len(colorlist)] + text[i])
return rainbowed
def rainbowcmd(word,word_eol,userdata):
count = 6
text = ""
if len(word) > 1:
try:
text = word[1]
except ValueError:
text = ""
if len(word) > 2:
try:
count = int(word[2])
except ValueError:
count = 6
for i in xrange(0,count):
(xchat.get_context()).command("say "+Rainbow(text,i))
xchat.hook_command("r",rainbowcmd,help="/r (text) (line count)")
print "Rainbow script by DEElekgolo loaded. use \\r (text) (count) to generate rainbow-ed text"
| 7c7c0ba09c663c1805b0f2019168e0d7bd6a86d0 | [
"Markdown",
"Python"
] | 4 | Markdown | the1glorfindel/hexchat-scripts | 2751d12361805e13e13db46ad1cb3b2399c1ab38 | 8cf6ac5e3beef81379870f7d24f5650e6a60f416 |
refs/heads/master | <repo_name>alaharirchi/alaki<file_sep>/tests.ts
it(`should have as text 'Email'`, async(() => {
expect(comp.text).toEqual('Email');
}));
it(`should not accept invalid email`, async(() => {
comp.signUpForm.controls['email'].setValue('www.john-doe.come');
expect(comp.signUpForm.valid).toBeFalsy();
}));
it(`should accept valid email`, async(() => {
comp.signUpForm.controls['email'].setValue('<EMAIL>');
expect(comp.signUpForm.valid).toBeTruthy();
}));
| a35a038f82a6ab366bfa0849584aa7512bee5ad2 | [
"TypeScript"
] | 1 | TypeScript | alaharirchi/alaki | 75e6cab5ed371a385e106cbf472b4e7d62cccbf1 | 148a4be0cb9aa613b327730219694039ea0cb8ab |
refs/heads/master | <repo_name>Emaren/great_answers<file_sep>/config/routes.rb
Rails.application.routes.draw do
root "welcome#index"
get "/index" => "welcome#index"
get "/home" => "welcome#index", as: :hey
get "/greeting/:name" => "welcome#greeting"
get "/hello" => "welcome#hello"
get "/hello.text" => "welcome#hello"
end
<file_sep>/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
end
def greeting
@name = params[:name]
end
def hello
# render text: "Hello World"
end
end
| 911a623de678c7231f4ad21278c5ecd6a5700407 | [
"Ruby"
] | 2 | Ruby | Emaren/great_answers | c904a2b86b2ff2ef5bf3ecf499eb757472e812a1 | 765b78e24e1daff04c3047662a21eddc1402b70c |
refs/heads/master | <repo_name>FadingDarkness/LabGrouping<file_sep>/Lecture.java
/*
* Programmer: <NAME>
*
* Date: October 14,2013
*
* File Name: Lecture
*
* Class: IT 226
* Instructor: <NAME>
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.DefaultListModel;
/**
* This creates a class that holds an arrayList of students who fill up a specific lecture
* Writes and reads a file, adds students and removes students from the file
*
* @author <NAME>
*
*/
public class Lecture
{
private Student newStu;
private ArrayList<Student> studentList;
private Scanner in;
private String name;
private boolean isMale;
private PrintWriter write;
private File filename;
public Lecture(String fileName)
{
filename = new File(fileName);
studentList = new ArrayList<Student>();
writeFile();
readFile();
}
public void addStu(String stuName, boolean gender)
{
newStu = new Student(stuName, gender);
studentList.add(newStu);
writeFile();
}
public String getStuName(int index)
{
return studentList.get(index).getName();
}
public void remove(String stuName)
{
for(int i = 0; i<studentList.size(); i++)
{
if(studentList.get(i).getName().equals(stuName))
studentList.remove(i);
}
writeFile();
}
private void readFile()
{
int i = 0;
try
{
in = new Scanner(filename);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
while(in.hasNext())
{
name = in.nextLine();
if(in.nextInt() == 0)
isMale = false;
else
isMale = true;
addStu(name, isMale);
int temp = in.nextInt();
studentList.get(i).setPrevGroup(temp);
i++;
}
}
private void writeFile()
{
filename.delete();
try
{
write = new PrintWriter(filename);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
for(int i = 0; i<studentList.size(); i++)
{
write.println(studentList.get(i).getName());
if(studentList.get(i).getGender())
{
write.println(1);
}
else
write.println(0);
write.println(studentList.get(i).getPrevGroup());
}
write.close();
}
public ArrayList<Student> getStudentList()
{
return studentList;
}
}
<file_sep>/GenderSortPanel.java
package edu.ilstu;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class GenderSortPanel extends JPanel
{
final private Color BACKGROUND = new BackgroundColor();
final private Border BORDER_COLOR = BorderFactory.createLineBorder(BACKGROUND);
final private Font FONT = new Font("Arial", Font.BOLD, 12);
JCheckBox checkBox;
public GenderSortPanel()
{
setBackground(BACKGROUND);
checkBox = new JCheckBox("Sort groups by gender?");
checkBox.setBackground(BACKGROUND);
setBorder(BorderFactory.createTitledBorder(
BORDER_COLOR,
"",
TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION,
FONT));
add(checkBox);
}
}
<file_sep>/ClassSelectionPanel.java
package edu.ilstu;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ClassSelectionPanel extends JPanel
{
final private String[] CLASS_NAMES = {"Class 1", "Class 2", "Class 3"};
final private Color BACKGROUND= new BackgroundColor();
private JPanel classPanel;
private JPanel labelPanel;
private Font font;
private JComboBox classNames;
private JLabel label;
public ClassSelectionPanel()
{
setLayout(new FlowLayout());
font = new Font("Arial", 0, 20);
this.setBackground(BACKGROUND);
classPanel = new JPanel();
labelPanel = new JPanel();
classPanel.setBackground(BACKGROUND);
labelPanel.setBackground(BACKGROUND);
label = new JLabel("Choose Your Class: ");
label.setFont(font);
classNames = new JComboBox(CLASS_NAMES);
classNames.setFont(font);
classPanel.add(classNames);
labelPanel.add(label);
add(labelPanel);
add(classPanel);
}
/**
*
* @return the name of the card type
*/
public String getCardType()
{
String cardType;
cardType = (String)classNames.getSelectedItem();
return cardType;
}
}
<file_sep>/Page2.java
package edu.ilstu;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
public class Page2 extends JPanel
{
final private Color BACKGROUND = new BackgroundColor();
private ClassListPanel addRemove;
private GroupSortPanel groupSort;
private int lectureNumber;
private Lecture lecture;
public Page2(Lecture lecture)
{
setLayout(new BorderLayout());
this.lecture = lecture;
this.setBackground(BACKGROUND);
addRemove = new ClassListPanel(lecture);
groupSort = new GroupSortPanel();
add(addRemove, BorderLayout.NORTH);
add(groupSort, BorderLayout.SOUTH);
setVisible(false);
}
public void setLectureNum(int num)
{
this.lectureNumber = num;
}
}
<file_sep>/README.md
LabGrouping
===========
IT 226
| 6b8b80b48981933c4d3be0a3523b9d46163f3ecf | [
"Markdown",
"Java"
] | 5 | Java | FadingDarkness/LabGrouping | 1b088b25bea43859d752c660fbd54e80077f5a41 | bc015d35bd995f50916b94b8308912dc843a4695 |
refs/heads/master | <file_sep>use std::env::current_dir;
use std::fs::File;
use std::path::Path;
pub fn locate_file(raw_input: &str) -> Result<File, std::io::Error> {
if raw_input.starts_with('/') {
return File::open(raw_input);
} else {
let cwd = current_dir()?;
let cwd = cwd.to_str().unwrap();
return File::open(format!("{}/{}", cwd, raw_input));
}
}
pub fn dir_exists(raw_input: &str) -> Result<bool, std::io::Error> {
if raw_input.starts_with('/') {
return Ok(Path::new(raw_input).exists());
} else {
let cwd = current_dir()?;
let cwd = cwd.to_str().unwrap();
return Ok(Path::new(&format!("{}/{}", cwd, raw_input)).exists());
}
}
<file_sep># titel
## subtitel
### heading1
#### Heading2
##### Heading3
Normale tekst.
Dit is een paragraaf. Hier komt een hele hoop tekst te staan. Bla bla bla lorem ipsum etcetera.
Patatjes zijn lekker.
Dit is een zin.
Dit is tekst.
Dit is al het latijn wat ik kan. Dat komt omdat ik een gekkie ben.
[http://patat.nl]<file_sep>use crate::utils;
use quick_xml::events::Event;
use quick_xml::Reader;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::str;
use zip::ZipArchive;
pub struct Doc<'a> {
output_dir: &'a str,
output: String,
}
impl<'a> Doc<'a> {
pub fn new(input_file: &'a str, output_dir: &'a str) -> Result<Doc<'a>, quick_xml::Error> {
// Transform docx to XML
let input_file = utils::locate_file(input_file).expect("The input file was not found.");
let mut input_file =
ZipArchive::new(input_file).expect("Zip archive was corrupted. Failed to read."); // Create zip archive
let mut input_file = input_file
.by_name("word/document.xml")
.expect("Document does not container inner XML representation"); // Search for zip file by name
// Reading contents of unzipped document.xml
let mut input = String::new();
input_file
.read_to_string(&mut input)
.expect("Inner XML document corrupted. Failed to read."); // Read file to String buffer
Ok(Doc {
output_dir: output_dir,
output: Doc::parse(input)?,
})
}
pub fn parse(input: String) -> Result<String, quick_xml::Error> {
// XML vars
let mut xml = Reader::from_reader(input.as_bytes()); // Parse XML file
let mut buf = Vec::new();
// dochero vars
let mut output = String::new();
let mut current_attributes = HashMap::new();
loop {
let event = xml.read_event(&mut buf);
match event {
Ok(Event::Empty(ref e)) => {
// Unpack event and handle tag & attributes
let current_tag = String::from_utf8_lossy(e.name()).to_string();
// If the tag is a style tag, save the attributes to hashmap
if current_tag.as_str() == "w:pStyle" || current_tag.as_str() == "w:rStyle" {
// println!("CURRENT TAG: {}", current_tag);
// Only clear the current attributes after the text is read
for a in e.attributes() {
let attribute = a?;
let key = str::from_utf8(&attribute.key)?;
let r = &attribute.unescaped_value()?;
let val = str::from_utf8(r)?;
current_attributes
.insert(String::from(key.clone()), String::from(val.clone()));
}
}
}
Ok(Event::Text(ref e)) => {
// Text(e) returns the text contained within the node
let line = e.unescape_and_decode(&xml)?;
let line = line.as_str();
if !line.is_empty() {
let md = Doc::transform(&mut current_attributes, line);
if md != None {
output.push_str(md.unwrap().as_str());
}
// After text is pushed, clear current attributes
¤t_attributes.clear();
}
}
Ok(Event::Eof) => break,
Err(err) => return Err(err),
_ => continue,
}
}
// After the output is created, pop the last `\n`
output.pop();
println!("{}", output); // Remove this later
return Ok(output);
}
fn transform(attributes: &mut HashMap<String, String>, value: &str) -> Option<String> {
// Transform can be implemented for different types like: MD, DokuWiki, MediaWiki
// When test is read, push current attributes
let r = attributes.get("w:val");
if r != None {
let style = r.unwrap().as_str();
return match style {
"Title" => Some(format!("# {}\n", value)),
"Subtitle" => Some(format!("## {}\n", value)),
"Heading1" => Some(format!("### {}\n", value)),
"Heading2" => Some(format!("#### {}\n", value)),
"Heading3" => Some(format!("##### {}\n", value)),
"TextBody" => Some(format!("{}\n", value)),
"InternetLink" => Some(format!("[{}]\n", value)),
_ => None,
};
}
None
}
// Getters and setters
// pub fn get_output_dir(&self) -> &str {
// self.output_dir
// }
// pub fn set_output_dir(&mut self, output_dir: &'a str) {
// self.output_dir = output_dir;
// }
// pub fn get_output(&self) -> &String {
// &self.output
// }
// pub fn get_output_mut(&mut self) -> &String {
// &self.output
// }
// pub fn set_output(&mut self, output: String) {
// self.output = output;
// }
// Write the output to the output location held in self
pub fn write_output(&self) -> Result<(), std::io::Error> {
let mut handle = File::create(format!("{}/document.md", self.output_dir).as_str())?;
handle.write_all(self.output.as_bytes())?;
return Ok(());
}
}
<file_sep># DokuHero
Easily convert Word documents to DokuWiki
### Dochero
dochero is a CLI application that takes a `.docx` input file and an output directory.
It reads the document as a zip archive and extracts the content of the `word/document.xml`.
The `quick_xml` parser reads this XML file and returns an iterator of XML objects.
Dochero reads these XML nodes and a formatted output is pushed onto the output buffer.
Lastly the output is written to an output file.
### TODO:
- [X] Create doc_hero project
- [X] Add arg parse functionality
- [X] Add node tree building functionality
- [X] Test with simple samle XML
- [X] Add node parse functionality
- [X] Refactor modules
- [ ] Add web interface/API
- [ ] Create rs lib & mods
- [ ] Use FFI lib call rather than process
<file_sep>extern crate quick_xml;
extern crate zip;
mod doc;
mod utils;
use clap::{App, Arg};
use doc::Doc;
// Example
// dochero -i word.docx -o /home/mathuis/Documents/location
// dochero --input word.docx --output /home/mathuis/Documents/location
fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("Doc Hero")
.about("Doc Hero converts your word document to doku wiki.")
.arg(
Arg::with_name("input")
.short("-i")
.long("--input")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("output")
.short("-o")
.long("--output")
.takes_value(true)
.required(true),
)
.get_matches();
let raw_input_file = matches.value_of("input").expect("Input file is required");
let raw_output_dir = matches
.value_of("output")
.expect("Output directory is required");
if !utils::dir_exists(&raw_output_dir)? {
println!("Directory does not exist.");
}
let doc = Doc::new(raw_input_file, raw_output_dir)?;
doc.write_output()?;
return Ok(());
}
| 6c97a7b65fadbe1a66d84177b2382f1a57fba52c | [
"Markdown",
"Rust"
] | 5 | Rust | Mathuiss/DokuHero | 29a0c0db6669f9318974b4b272237fb04b0a7012 | 4afd7cfe5003f44f7927a52560c21ad20f83077c |
refs/heads/master | <file_sep>package gob.pe.unmsm.becas.alumnos.application.dto;
public class AlumnoDto {
private Long id;
private String firstName;
private String lastName;
private String tipoAlumno;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getTipoAlumno() {
return tipoAlumno;
}
public void setTipoAlumno(String tipoAlumno) {
this.tipoAlumno = tipoAlumno;
}
}
<file_sep>CREATE TABLE alumno (
alumno_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
tipo_alumno VARCHAR(2) NOT NULL,
active BIT NOT NULL,
PRIMARY KEY (alumno_id),
INDEX IX_alumno_last_first_name (last_name, first_name)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;<file_sep>package gob.pe.unmsm.becas.alumnos.domain.repository;
import java.util.Map;
import java.util.Optional;
import gob.pe.unmsm.becas.alumnos.domain.entity.Alumno;
public interface AlumnoDao {
public Alumno create(Alumno Alumno) throws Exception;
public Alumno findById(Long id) throws Exception;
public Map<String, Object> findAll(java.util.Optional<String> pag, java.util.Optional<String> pagLength) throws Exception;
public Map<String, Object> findAllByTipo(Optional<String> tipo, Optional<String> pag, Optional<String> pagLength) throws Exception;
}
<file_sep># examen-final-ads
Examen final de ADS - clean architecture
| 615921130119df3a7745ab81951a19b17b1eb8cb | [
"Markdown",
"Java",
"SQL"
] | 4 | Java | sergioide007/api-becas | 8e62b878ff7624a8e577f978bb4f62ecb74bbc7b | d7654bb5a866be1994471094dea3ab16aa30c50b |
refs/heads/main | <file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
//#region 'Variables'
private loteria = [
[1, 'gallo', './assets/images/cartas/1.png'],
[2, 'diablito', './assets/images/cartas/2.png'],
[3, 'dama', './assets/images/cartas/3.png'],
[4, 'catrin', './assets/images/cartas/4.png'],
[5, 'paraguas', './assets/images/cartas/5.png'],
[6, 'sirena', './assets/images/cartas/6.png'],
[7, 'escalera', './assets/images/cartas/7.png'],
[8, 'botella', './assets/images/cartas/8.png'],
[9, 'barril', './assets/images/cartas/9.png'],
[10, 'arbol', './assets/images/cartas/10.png'],
[11, 'melon', './assets/images/cartas/11.png'],
[12, 'valiente', './assets/images/cartas/12.png'],
[13, 'gorrito', './assets/images/cartas/13.png'],
[14, 'muerte', './assets/images/cartas/14.png'],
[15, 'pera', './assets/images/cartas/15.png'],
[16, 'bandera', './assets/images/cartas/16.png'],
[17, 'bandolon', './assets/images/cartas/17.png'],
[18, 'violoncello', './assets/images/cartas/18.png'],
[19, 'garza', './assets/images/cartas/19.png'],
[20, 'pajaro', './assets/images/cartas/20.png'],
[21, 'mano', './assets/images/cartas/21.png'],
[22, 'bota', './assets/images/cartas/22.png'],
[23, 'luna', './assets/images/cartas/23.png'],
[24, 'cotorro', './assets/images/cartas/24.png'],
[25, 'borracho', './assets/images/cartas/25.png'],
[26, 'negrito', './assets/images/cartas/26.png'],
[27, 'corazon', './assets/images/cartas/27.png'],
[28, 'sandia', './assets/images/cartas/28.png'],
[29, 'tambor', './assets/images/cartas/29.png'],
[30, 'camaron', './assets/images/cartas/30.png'],
[31, 'jaras', './assets/images/cartas/31.png'],
[32, 'musico', './assets/images/cartas/32.png'],
[33, 'arania', './assets/images/cartas/33.png'],
[34, 'soldado', './assets/images/cartas/34.png'],
[35, 'estrella', './assets/images/cartas/35.png'],
[36, 'cazo', './assets/images/cartas/36.png'],
[37, 'mundo', './assets/images/cartas/37.png'],
[38, 'apache', './assets/images/cartas/38.png'],
[39, 'nopal', './assets/images/cartas/39.png'],
[40, 'alacran', './assets/images/cartas/40.png'],
[41, 'rosa', './assets/images/cartas/41.png'],
[42, 'calavera', './assets/images/cartas/42.png'],
[43, 'campana', './assets/images/cartas/43.png'],
[44, 'cantarito', './assets/images/cartas/44.png'],
[45, 'venado', './assets/images/cartas/45.png'],
[46, 'sol', './assets/images/cartas/46.png'],
[47, 'corona', './assets/images/cartas/47.png'],
[48, 'chalupa', './assets/images/cartas/48.png'],
[49, 'pino', './assets/images/cartas/49.png'],
[50, 'pescado', './assets/images/cartas/50.png'],
[51, 'palma', './assets/images/cartas/51.png'],
[52, 'maceta', './assets/images/cartas/52.png'],
[53, 'arpa', './assets/images/cartas/53.png'],
[54, 'rana', './assets/images/cartas/54.png'],
];
private doubles = ['14', '113', '116', '413', '416', '611', '710', '1316'];
public card: any[] = [];
public cards: any[] = [];
public cards_ordered: any[] = [];
public name_top = '';
public dobles = 'true';
public cuantas = '0';
public cantidad = '';
public ubicacion = '666';
public ubicacionDoblesIMG = './assets/images/orden/666.png';
//#endregion 'Variables'
//#region 'Angular LifeCycle'
constructor() {}
ngOnInit() {}
//#endregion 'Angular LifeCycle'
//#region 'General Methods'
public ubicacionDobles(): void {
this.ubicacionDoblesIMG = `./assets/images/orden/${this.ubicacion}.png`;
}
public create_cards() {
this.cards = [];
this.cards_ordered = [];
const CANTIDAD = this.cuantas == '0' ? 54 : Number(this.cantidad);
for (let i = 1; i <= CANTIDAD; i++) {
this.create_card(i);
let cc = this.cloneData(this.card).sort();
while (this.cards_ordered.filter((obj) => obj === cc).length > 0) {
this.create_card(i);
cc = this.cloneData(this.card).sort();
}
this.cards.push(this.cloneData(this.card));
this.cards_ordered.push(cc);
}
this.showData();
}
private create_card(double: number) {
this.card = [];
for (let i = 1; i < 16; i++) {
let random = this.get_random(1, 54, double);
let lote = this.loteria.filter((obj) => obj[0] === random)[0];
if (i < 15) {
this.card.push(lote);
} else {
lote = this.loteria.filter((obj) => obj[0] === double)[0];
this.setDouble(lote);
}
}
}
private get_random(min: number, max: number, double: number) {
let random = Math.floor(Math.random() * (max - min + 1) + min);
let exist = this.card.filter((obj) => obj[0] === random);
while (exist.length > 0 || double == random) {
random = Math.floor(Math.random() * (max - min + 1) + min);
exist = this.card.filter((obj) => obj[0] === random);
}
return random;
}
private setDouble(lote) {
let d1 = 0;
let d2 = 0;
let ran = this.ubicacion;
if (ran == '666') {
ran = this.doubles[Math.floor(Math.random() * 8)];
}
if (ran == '14') {
d1 = 0;
d2 = 3;
}
if (ran == '113') {
d1 = 0;
d2 = 12;
}
if (ran == '116') {
d1 = 0;
d2 = 15;
}
if (ran == '413') {
d1 = 3;
d2 = 12;
}
if (ran == '416') {
d1 = 3;
d2 = 15;
}
if (ran == '611') {
d1 = 5;
d2 = 10;
}
if (ran == '710') {
d1 = 6;
d2 = 9;
}
if (ran == '1316') {
d1 = 12;
d2 = 15;
}
this.card.splice(d1, 0, lote);
this.card.splice(d2, 0, lote);
}
public create_specific_cards() {
this.name_top = '<NAME>';
this.cards = [];
this.cards_ordered = [];
const personal_cards = [
[15, 52, 33, 23, 17, 44, 8, 1, 18, 32, 44, 13, 35, 19, 9, 24],
[25, 11, 13, 48, 41, 37, 53, 16, 7, 37, 36, 47, 49, 50, 54, 20],
[14, 17, 20, 22, 16, 45, 52, 47, 3, 21, 45, 18, 10, 33, 38, 19],
[12, 3, 48, 39, 10, 53, 54, 45, 13, 4, 54, 50, 33, 24, 16, 23],
[8, 46, 7, 29, 22, 35, 23, 21, 31, 26, 35, 16, 17, 41, 47, 52],
[31, 29, 47, 2, 6, 43, 30, 42, 25, 44, 43, 20, 21, 28, 26, 53],
[44, 42, 7, 8, 45, 23, 35, 41, 1, 46, 23, 18, 50, 14, 9, 43],
[27, 10, 29, 28, 31, 11, 15, 12, 26, 49, 11, 34, 17, 51, 52, 32],
];
for (let i = 0; i < personal_cards.length; i++) {
const element = personal_cards[i];
this.card = [];
element.forEach((t) => {
let lote = this.loteria.filter((obj) => obj[0] === t)[0];
this.card.push(lote);
});
this.cards.push(this.cloneData(this.card));
}
}
private showData() {
this.cards.forEach((el) => {
// console.log(
// `${el[0][0].toString().length === 1 ? `0${el[0][0]}` : el[0][0]}-${
// el[1][0].toString().length === 1 ? `0${el[1][0]}` : el[1][0]
// }-${el[2][0].toString().length === 1 ? `0${el[2][0]}` : el[2][0]}-${
// el[3][0].toString().length === 1 ? `0${el[3][0]}` : el[3][0]
// }-${el[4][0].toString().length === 1 ? `0${el[4][0]}` : el[4][0]}-${
// el[5][0].toString().length === 1 ? `0${el[5][0]}` : el[5][0]
// }-${el[6][0].toString().length === 1 ? `0${el[6][0]}` : el[6][0]}-${
// el[7][0].toString().length === 1 ? `0${el[7][0]}` : el[7][0]
// }-${el[8][0].toString().length === 1 ? `0${el[8][0]}` : el[8][0]}-${
// el[9][0].toString().length === 1 ? `0${el[9][0]}` : el[9][0]
// }-${el[10][0].toString().length === 1 ? `0${el[10][0]}` : el[10][0]}-${
// el[11][0].toString().length === 1 ? `0${el[11][0]}` : el[11][0]
// }-${el[12][0].toString().length === 1 ? `0${el[12][0]}` : el[12][0]}-${
// el[13][0].toString().length === 1 ? `0${el[13][0]}` : el[13][0]
// }-${el[14][0].toString().length === 1 ? `0${el[14][0]}` : el[14][0]}-${
// el[15][0].toString().length === 1 ? `0${el[15][0]}` : el[15][0]
// }`
// );
const DATA = [
el[0][0],
el[1][0],
el[2][0],
el[3][0],
el[4][0],
el[5][0],
el[6][0],
el[7][0],
el[8][0],
el[9][0],
el[10][0],
el[11][0],
el[12][0],
el[13][0],
el[14][0],
el[15][0],
].sort();
console.log(DATA);
});
}
private cloneData(data: any): any {
return JSON.parse(JSON.stringify(data));
}
//#endregion 'General Methods'
}
| bff38975ac3800805b5e7722a688838c0eb7d5a1 | [
"TypeScript"
] | 1 | TypeScript | Xiurik/Loteria_Mexicana | 8f9fc6b28c9e170d6594181149f9ba2f48901f9a | 67a6822c5529d603d267f3c4255ed753d11ba886 |
refs/heads/main | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.esales</groupId>
<artifactId>ediparent</artifactId>
<packaging>pom</packaging>
<version>5.0-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot-dependencies.version>2.3.5.RELEASE</spring-boot-dependencies.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
<spring-security-jwt.version>1.1.1.RELEASE</spring-security-jwt.version>
<spring-security-oauth2.version>2.5.0.RELEASE</spring-security-oauth2.version>
<springfox-swagger.version>2.9.2</springfox-swagger.version>
<javers-core.version>5.13.2</javers-core.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${spring-security-jwt.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger.version}</version>
</dependency>
<dependency>
<groupId>org.javers</groupId>
<artifactId>javers-core</artifactId>
<version>${javers-core.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<distributionManagement>
<snapshotRepository>
<id>snapshots</id>
<name>repo-snapshots</name>
<url>http://nexus.esales.com.br:8080/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>releases</id>
<name>repo-releases</name>
<url>http://nexus.esales.com.br:8080/nexus/content/repositories/releases/</url>
</repository>
</distributionManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-dependencies.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<!--<profile>
<id>disable-java8-doclint</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<properties>
<additionalparam>-Xdoclint:none</additionalparam>
</properties>
</profile>-->
</profiles>
<organization>
<name>E-Sales Soluções de Integração</name>
<url>www.esales.com.br</url>
</organization>
</project><file_sep>package br.com.esales.enterprise.repository;
import br.com.esales.enterprise.entity.Product;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
}
<file_sep>package br.com.esales.rest.auth.security.service;
import br.com.esales.enterprise.entity.UserSystem;
//import br.com.esales.enterprise.entity.Usuario;
import br.com.esales.enterprise.repository.UserSystemRepository;
//import br.com.esales.enterprise.repository.UsuarioRepository;
import br.com.esales.rest.auth.security.entity.UserDetailsImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
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
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserSystemRepository userSystemRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
final UserSystem userSystem = userSystemRepository.findByEmail(email);
if(userSystem == null) {
throw new UsernameNotFoundException("User not found!");
}
return new UserDetailsImpl(userSystem);
}
}
<file_sep>package br.com.esales.enterprise.entity;
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "user_system")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@ToString
@Builder
public class UserSystem implements AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", unique = true, nullable = false)
private String name;
@Column(name = "email", unique = true, nullable = false)
private String email;
@Column(name = "password", nullable = false)
@ToString.Exclude
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_system_role", joinColumns = { @JoinColumn(name="id_user_system") }, inverseJoinColumns = { @JoinColumn(name="id_role")})
private List<Role> roles;
}
<file_sep>///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package br.com.esales.enterprise.entity;
//
//import lombok.*;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import javax.persistence.CascadeType;
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.FetchType;
//import javax.persistence.GeneratedValue;
//import javax.persistence.Id;
//import javax.persistence.OneToMany;
//import javax.persistence.Table;
//import javax.persistence.TableGenerator;
//
///**
// * Copyright - Todos os direitos reservados a E-Sales Integration Solutions
// *
// * A cópia integral ou parcial desse código, seja para uso pessoal, profissional
// * ou educacional, é proibida.
// */
//@Entity
//@Table(name = "ORGANIZACAO")
//@Getter
//@Setter
//@NoArgsConstructor
//@AllArgsConstructor
//@EqualsAndHashCode
//@ToString(onlyExplicitlyIncluded = true)
//@Builder
//public class Organizacao implements java.io.Serializable {
//
// @Id
// @GeneratedValue(generator = "InvTaborg")
// @TableGenerator(name = "InvTaborg", table = "ID_GEN",
// pkColumnName = "ID_NAME", valueColumnName = "ID_VAL", allocationSize = 1,
// pkColumnValue = "ORGANIZACAO_ID")
// @Column(name = "ID", nullable = false)
// private Integer id;
//
// @Column(name = "NOME", nullable = false)
// @ToString.Include
// private String nome;
//
// @Column(name = "CNPJ")
// private String cnpj;
//
// @Column(name = "CODIGO")
// private String codigo;
//
// @Column(name = "TITULO")
// private String titulo;
//
// @Column(name = "SUBTITULO")
// private String subtitulo;
//
// @OneToMany(mappedBy = "organizacao", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
// private List<Usuario> usuarios = new ArrayList<>();
//
//}
<file_sep>///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package br.com.esales.enterprise.entity;
//
///*import org.eclipse.persistence.annotations.BatchFetch;
//import org.eclipse.persistence.annotations.BatchFetchType;
//import org.eclipse.persistence.annotations.JoinFetch;
//import org.eclipse.persistence.annotations.JoinFetchType;*/
//
//import lombok.*;
//
//import javax.persistence.*;
//import java.util.*;
//
///**
// * Copyright - Todos os direitos reservados a E-Sales Integration Solutions
// *
// * A cópia integral ou parcial desse código, seja para uso pessoal, profissional
// * ou educacional, é proibida.
// */
//@Entity
//@Table(name = "USUARIO")
//@Getter
//@Setter
//@NoArgsConstructor
//@AllArgsConstructor
///*@EqualsAndHashCode
//@ToString*/
//@Builder
//public class Usuario implements AbstractEntity {
//
// public static enum AUTENTICACAO {
// EDI {
// public String toString() {
// return "Usuário @EDI";
// }
// },
// LDAP {
// public String toString() {
// return "Apenas LDAP";
// }
// },
// SO {
// public String toString() {
// return "Apenas Sistema operacional";
// }
// },
// EDI_SO {
// public String toString() {
// return "Usuário @EDI e Sistema operacional";
// }
// },
// EDI_LDAP {
// public String toString() {
// return "Usuário @EDI e LDAP";
// }
// },
// EDI_SO_LDAP {
// public String toString() {
// return "Usuário @EDI, LDAP e Sistema operacional";
// }
// }
// }
//
// @Id
// @GeneratedValue(generator = "InvTabUser")
// @TableGenerator(name = "InvTabUser", table = "ID_GEN", allocationSize = 1,
// pkColumnName = "ID_NAME", valueColumnName = "ID_VAL",
// pkColumnValue = "USUARIO_ID")
// @Column(name = "ID", nullable = false)
// private Integer id;
//
// @Column(name = "NOME", nullable = false)
// private String nome;
//
// @Column(name = "USERNAME", nullable = false)
// private String username;
//
// @Column(name = "SENHA", insertable = true, updatable = false)
// private String senha;
//
// @Column(name = "SETOR")
// private String setor;
//
// @Column(name = "CARGO")
// private String cargo;
//
// @Column(name = "DOMINIO")
// private String dominio;
//
// @Column(name = "TIPO_AUTENTICACAO", nullable = false)
// @Enumerated(EnumType.STRING)
// private AUTENTICACAO tipoAutenticacao;
//
// /*@BatchFetch(value = BatchFetchType.JOIN)
// @JoinFetch(value = JoinFetchType.OUTER)*/
//// @JoinColumn(name = "ID_EMPRESA", referencedColumnName = "ID")
//// @ManyToOne(fetch = FetchType.EAGER)
//// private Empresa empresa;
//
//// @OneToMany(mappedBy = "usuario",
//// cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval = true)
//// private List<UsuarioEmail> emails = new ArrayList<UsuarioEmail>();
//
// /*@BatchFetch(value = BatchFetchType.JOIN)
// @JoinFetch(value = JoinFetchType.OUTER)*/
//// @JoinColumn(name = "ID_PERFIL", referencedColumnName = "ID")
//// @ManyToOne(fetch = FetchType.EAGER)
//// private Perfil perfil;
//
// @Column(name = "TENTATIVA_RECONEXAO")
// private Integer tentativaReconexao;
//
// @Column(name = "TEMPO_TENTATIVAS")
// private Integer tempoTentativas;
//
// @Column(name = "MAXIMO_CONEXOES")
// private Integer maximoConexoes;
//
// @Column(name = "DIRETORIO_ORIGEM")
// private String diretorioOrigem;
//
// @Column(name = "DIRETORIO_DESTINO")
// private String diretorioDestino;
//
// @Column(name = "MAXIMO_BANDA")
// private Integer maximoBanda;
//
// @Column(name = "TEMPO_LIMPEZA_LOGS_BANCO")
// private Integer tempoLimpezaLogsBanco;
//
// @Column(name = "ULTIMA_LIMPEZA_BANCO")
// @Temporal(TemporalType.DATE)
// private Date ultimaLimpezaBanco;
//
// @Column(name = "DN_LDAP")
// private String dnLdap;
//
// @Column(name = "QT_TENTATIVAS")
// private Integer quantidadeTentativas = 0;
//
// @Column(name = "EXPIRA_SENHA")
// @Temporal(TemporalType.DATE)
// private Date expiraSenha;
//
// @Column(name = "TIMEOUT_USUARIO")
// private Integer timeout;
//
// @Column(name = "CPF")
// private String cpf;
//
// @Column(name = "CERTIFICADO")
// private String certificado;
//
// @Column(name = "VERTICAL")
// private String vertical;
//
// @Column(name = "ULTIMO_ACESSO")
// @Temporal(TemporalType.TIMESTAMP)
// private Date ultimoAcesso;
//
// @Column(name = "TELEFONE")
// private String telefone;
//
// @Column(name = "HASH_VALIDATION")
// private String hashValidation;
//
// @Column(name = "ATIVO")
// private Short ativo;
//
// @Column(name = "SERVICE", nullable = false)
// private Short service;
//
// @Column(name = "ACCESS_TOKEN")
// private String accessToken;
//
// /*@BatchFetch(value = BatchFetchType.JOIN)
// @JoinFetch(value = JoinFetchType.OUTER)*/
//// @JoinColumn(name = "ID_ORGANIZACAO", referencedColumnName = "ID")
//// @ManyToOne(fetch = FetchType.EAGER)
//// private Organizacao organizacao;
//
// @Column(name = "MULTICONEXAO", nullable = false)
// private Short multiconexao;
//
// @Column(name = "IP_CLIENT")
// private String ipClient;
//
// @Column(name = "DIRETORIO_ORIGEM_COPIA")
// private String diretorioOrigemCopia;
//
// @Column(name = "DIRETORIO_DESTINO_COPIA")
// private String diretorioDestinoCopia;
//
// @Column(name = "MASCARA_RENOMEIO")
// private String mascaraRenomeio;
//
// @Column(name = "RENOMEIO_COPIA_ORIGEM")
// private String renomeioCopiaOrigem;
//
// @Column(name = "RENOMEIO_COPIA_DESTINO")
// private String renomeioCopiaDestino;
//
//// @OneToMany(mappedBy = "usuario", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
//// private Set<UsuarioGrupo> usuarioGrupos = new HashSet<UsuarioGrupo>();
//
// @Column(name = "COMPARTILHAR_PASTA_CXA", nullable = false)
// private boolean compartilharPasta;
//
// @Transient
// private String tipoAutenticacaoStr = null;
//
// public Usuario(Integer id) {
// this.id = id;
// }
//
//// public Set<UsuarioGrupo> getUsuarioGrupos() {
//// return usuarioGrupos;
//// }
////
//// public void setUsuarioGrupos(Set<UsuarioGrupo> usuarioGrupos) {
//// this.usuarioGrupos = usuarioGrupos;
//// }
//
//// public Organizacao getOrganizacao() {
//// return organizacao;
//// }
////
//// public void setOrganizacao(Organizacao organizacao) {
//// this.organizacao = organizacao;
//// }
//
//// public List<UsuarioEmail> getEmails() {
//// return emails;
//// }
////
//// public void setEmails(List<UsuarioEmail> emails) {
//// this.emails = emails;
//// }
////
//// public Perfil getPerfil() {
//// if (perfil == null) {
//// this.perfil = new Perfil();
//// }
//// return perfil;
//// }
////
//// public void setPerfil(Perfil perfil) {
//// this.perfil = perfil;
//// }
//
//// public Empresa getEmpresa() {
//// return empresa;
//// }
////
//// public void setEmpresa(Empresa empresa) {
//// this.empresa = empresa;
//// }
//
// public Integer getId() {
// if (this.id == null) {
// this.id = 0;
// }
// return this.id;
// }
//
// public Short getAtivo() {
// if (ativo == null) {
// ativo = 1;
// }
// return ativo;
// }
//
// public Short getMulticonexao() {
// if (multiconexao == null) {
// multiconexao = 0;
// }
// return multiconexao;
// }
//
// public boolean isActive() {
// return this.getAtivo() != null && this.getAtivo().equals((short) 1);
// }
//
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Usuario that = (Usuario) o;
//// if (this.usuarioGrupos != null ? !this.usuarioGrupos.equals(that.usuarioGrupos) : that.usuarioGrupos != null) return false;
// return true;
// }
//
// public int hashCode() {
// return (int) id * nome.hashCode() * username.hashCode();
// }
//
// public String toString() {
// String name = nome;
// if (vertical != null && !vertical.trim().isEmpty()) {
// name = name + " - " + vertical;
// }
// return name;
// }
//
//}<file_sep>//package com.example.rest.auth.hazelcast;
//
//import com.hazelcast.config.SecurityConfig;
//import org.apache.tomcat.util.descriptor.web.SessionConfig;
//import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
//
//public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
//
// SecurityInitializer() {
// super(SecurityConfig.class, SessionConfig.class);
// }
//
//}
<file_sep>///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package br.com.esales.enterprise.entity;
//
//import java.io.Serializable;
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.Id;
//import javax.persistence.JoinColumn;
//import javax.persistence.ManyToOne;
//import javax.persistence.Table;
//
///**
// *
// *
// * Copyright - Todos os direitos reservados a E-Sales Integration Solutions
// *
// * A c�pia integral ou parcial desse c�digo, seja para uso pessoal, profissional ou
// * educacional, � proibida.
// *
// * @author <NAME>
// */
//@Entity
//@Table(name = "USUARIO_EMAIL")
//public class UsuarioEmail implements Serializable {
//
// @Id
// @Column(name = "ID", nullable = false)
// private Integer id;
// @JoinColumn(name = "ID_USUARIO", referencedColumnName = "ID")
// @ManyToOne
// private Usuario usuario;
// @Column(name = "EMAIL")
// private String email;
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public Usuario getUsuario() {
// return usuario;
// }
//
// public void setUsuario(Usuario usuario) {
// this.usuario = usuario;
// }
//
//
//}
<file_sep>//package br.com.esales.enterprise.repository;
//
//import br.com.esales.enterprise.entity.Usuario;
//import org.springframework.data.repository.PagingAndSortingRepository;
//import org.springframework.stereotype.Repository;
//
//@Repository
//public interface UsuarioRepository extends PagingAndSortingRepository<Usuario, Long> {
//
// Usuario findByUsername(String username);
//}
<file_sep>///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package br.com.esales.enterprise.entity;
//
///*import org.eclipse.persistence.annotations.BatchFetch;
//import org.eclipse.persistence.annotations.BatchFetchType;
//import org.eclipse.persistence.annotations.JoinFetch;
//import org.eclipse.persistence.annotations.JoinFetchType;*/
//
//import lombok.*;
//
//import javax.persistence.*;
//import java.util.Set;
//
///**
// * Copyright - Todos os direitos reservados a E-Sales Integration Solutions
// *
// * A cópia integral ou parcial desse código, seja para uso pessoal, profissional
// * ou educacional, é proibida.
// */
//@Entity
//@Table(name = "PERFIL")
//@Getter
//@Setter
//@NoArgsConstructor
//@AllArgsConstructor
//@EqualsAndHashCode
//@ToString
//@Builder
//public class Perfil implements java.io.Serializable {
//
// @Id
// @GeneratedValue(generator = "InvTabPerfil")
// @TableGenerator(name = "InvTabPerfil", table = "ID_GEN", allocationSize = 1,
// pkColumnName = "ID_NAME", valueColumnName = "ID_VAL",
// pkColumnValue = "PERFIL_ID")
// @Column(name = "ID", nullable = false)
// private Integer id;
//
// @Column(name = "NOME", nullable = false)
// private String nome;
//
// @OneToMany(mappedBy = "perfil")
// private Set<Usuario> usuarios;
//
// @JoinTable(name="PERFIL_PERMISSAO",
// joinColumns={ @JoinColumn(name="ID_PERFIL", referencedColumnName="ID") },
// inverseJoinColumns={ @JoinColumn(name="ID_PERMISSAO", referencedColumnName="ID") })
// /*@BatchFetch(value = BatchFetchType.JOIN)
// @JoinFetch(value = JoinFetchType.OUTER)*/
// @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, fetch = FetchType.EAGER)
// private Set<Permissao> permissoes;
//
// /*@OneToMany(mappedBy = "perfil", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
// private Collection<PerfilServidor> servidores;
//
// @OneToMany(mappedBy = "perfil", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
// private Collection<PerfilConta> contas;*/
//
// public boolean isAdmin() {
// return this.nome.toLowerCase() == "admin" || this.id == 1 || this.hasAdminPermission();
// }
//
// private boolean hasAdminPermission() {
// return this.permissoes != null && this.permissoes.stream().anyMatch(p -> p != null && p.getCodigo().equals("ADMUG"));
// }
//}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>br.com.esales</groupId>
<artifactId>ediparent</artifactId>
<version>5.0-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<artifactId>ediapi</artifactId>
<version>5.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ediapi</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.javers</groupId>
<artifactId>javers-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>br.com.esales.api.Propriedades</mainClass>
<addClasspath>true</addClasspath>
<classpathLayoutType>custom</classpathLayoutType>
<customClasspathLayout>${artifact.artifactId}.jar</customClasspathLayout>
</manifest>
<manifestSection>
<name>br/com/esales/api/</name>
<manifestEntries>
<Implementation-Vendor>E-Sales Soluçōes de Integraçāo</Implementation-Vendor>
<Implementation-Title>${project.name}</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
</manifestEntries>
</manifestSection>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
</execution>
</executions>
</plugin>-->
</plugins>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
</build>
<profiles>
<!--<profile>
<id>disable-java8-doclint</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<properties>
<additionalparam>-Xdoclint:none</additionalparam>
</properties>
</profile>-->
</profiles>
</project> | 748985a5ab34d00129e59f1d8e2a6c4877195585 | [
"Java",
"Maven POM"
] | 11 | Maven POM | ronniemikihiro/microservices-pom-parent | 63cde2930ec3c4d6fd19bb2897809aaef18c4040 | 9167315fe73c1a86dbfea742b3abbce83ebd7823 |
refs/heads/master | <file_sep>// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"bytes"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"encoding/json"
"github.com/pressly/chi"
"github.com/pressly/chi/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// playerCmd represents the player command
var playerCmd = &cobra.Command{
Use: "player",
Short: "Launch a patakube player",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: playerRun,
}
func init() {
RootCmd.AddCommand(playerCmd)
playerCmd.PersistentFlags().String("target", "target.patakube.svc.cluster.local", "target to shoot")
if err := viper.BindPFlag("target", playerCmd.PersistentFlags().Lookup("target")); err != nil {
log.Fatal(err)
}
playerCmd.Flags().Bool("patator", false, "Use a patator")
if err := viper.BindPFlag("patator", playerCmd.Flags().Lookup("patator")); err != nil {
log.Fatal(err)
}
playerCmd.Flags().Int("patator-port", 8081, "Port to reach patator")
if err := viper.BindPFlag("patator-port", playerCmd.Flags().Lookup("patator-port")); err != nil {
log.Fatal(err)
}
}
type player struct {
ID string
Namespace string
ClusterURL string
}
func playerRun(cmd *cobra.Command, args []string) {
p := player{ID: os.Getenv("NAME")}
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte(fmt.Sprintf("Player %s \n", p.ID))); err != nil {
http.Error(w, err.Error(), 500)
return
}
})
// Slow handlers/operations.
r.Group(func(r chi.Router) {
// Stop processing after 30 seconds.
r.Use(middleware.Timeout(30 * time.Second))
// Only one request will be processed at a time.
r.Use(middleware.Throttle(1))
r.Post("/potato", func(w http.ResponseWriter, r *http.Request) {
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(p); err != nil {
http.Error(w, err.Error(), 500)
return
}
target := "http://" + viper.GetString("target")
if viper.GetBool("patator") {
target = "http://localhost:" + strconv.Itoa(viper.GetInt("patator-port"))
}
res, err := http.Post(target, "application/json", b)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if res.StatusCode != http.StatusCreated {
http.Error(w, "Missed", 410)
return
}
w.WriteHeader(http.StatusCreated)
if _, err := w.Write([]byte("Hit")); err != nil {
http.Error(w, err.Error(), 500)
return
}
})
})
if err := http.ListenAndServe(":"+strconv.Itoa(viper.GetInt("port")), r); err != nil {
log.Fatal(err)
}
}
<file_sep>// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"log"
"net/http"
"strconv"
"text/template"
"github.com/pressly/chi"
"github.com/pressly/chi/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/rest"
)
var configuratorCmd = &cobra.Command{
Use: "configurator",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: configurator,
}
func init() {
RootCmd.AddCommand(configuratorCmd)
configuratorCmd.Flags().String("cluster-url", "localhost:8080", "Your k8s cluster")
if err := viper.BindPFlag("cluster-url", configuratorCmd.Flags().Lookup("cluster-url")); err != nil {
log.Fatal(err)
}
}
func configurator(cmd *cobra.Command, args []string) {
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, erre := kubernetes.NewForConfig(config)
if erre != nil {
panic(err.Error())
}
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("please provide a player name")); err != nil {
http.Error(w, err.Error(), 500)
return
}
})
r.Get("/:playerID", func(w http.ResponseWriter, r *http.Request) {
playerID := chi.URLParam(r, "playerID")
p := player{
ID: playerID,
Namespace: "player-" + playerID,
ClusterURL: viper.GetString("cluster-url"),
}
ns := v1.Namespace{
ObjectMeta: v1.ObjectMeta{
Name: p.Namespace,
Labels: map[string]string{"player": "true"},
},
}
if _, err := clientset.Core().Namespaces().Create(&ns); err != nil {
http.Error(w, err.Error(), 500)
return
}
t, err := template.ParseFiles("/templates/config.sh")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if err := t.Execute(w, p); err != nil {
http.Error(w, err.Error(), 500)
return
}
})
if err := http.ListenAndServe(":"+strconv.Itoa(viper.GetInt("port")), r); err != nil {
log.Fatal(err)
}
}
<file_sep># User guide
## General
This game oppose you to other player in a potato throwing contest.
## Principle
A _trap_ send you a potato that you have to launch to a target.
Each _hit_ is recorded for final scoring
<file_sep># patakube
[](https://travis-ci.org/guilhem/patakube)
[](https://goreportcard.com/report/github.com/guilhem/patakube)
[](https://microbadger.com/images/guilhem/patakube "Get your own image badge on microbadger.com")
[](https://libraries.io/github/guilhem/patakube)
A simple game to discover kubernetes.
## Status
Under Heavy development. Any advice, contribution is greatly welcome.
## Goal
Who didn't try to explain kubernetes and receive back mutual incomprehension?
_patakube_ try to be a basic use-case to present k8s for technical people.
Pods, services, scaling, secrets... we try to make concepts real.
## Example
[](https://asciinema.org/a/96845?autoplay=1&speed=3)
<file_sep># Patakube for admins
## Requirements
* Kubernetes cluster (even if only 1 node)
* Room with wifi able to reach cluster
You can use a [GKE cluster](https://cloud.google.com/container-engine/) to ease you.
## Before event
- [ ] Ask people to come with a working computer
- [ ] Create number of namespaces
There will be 1 per user who want to play.
`kubectl create namespace player-{NAME I WANT}`
* [ ] spawn _target_, _trap_ and _arbiter_ agent into `patakube` namespace
```
kubectl create namespace patakube
kubectl create --namespace=patakube --filename=config/admin.yaml
```
## During event
TODO
<file_sep># patakube

Patakube is a learning game for [kubernetes](http://kubernetes.io/).
## [For admins](admin.md)
## [For users](user.md)
<file_sep>// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/patrickmn/go-cache"
"github.com/pressly/chi"
"github.com/pressly/chi/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// targetCmd represents the target command
var targetCmd = &cobra.Command{
Use: "target",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: target,
}
var c = cache.New(5*time.Minute, 30*time.Second)
func init() {
RootCmd.AddCommand(targetCmd)
}
func target(cmd *cobra.Command, args []string) {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(c.Items()); err != nil {
http.Error(w, err.Error(), 400)
return
}
})
r.Post("/", postRoot)
if err := http.ListenAndServe(":"+strconv.Itoa(viper.GetInt("port")), r); err != nil {
log.Fatal(err)
}
}
func postRoot(w http.ResponseWriter, r *http.Request) {
var p player
accuracy := 10
velocity := 5
if r.Body == nil {
http.Error(w, "Please send a request body", 412)
return
}
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, err.Error(), 500)
return
}
if r.Header.Get("patator") != "" {
accuracy = 5
w.Header().Set("X-Patator", "YES!")
} else {
w.Header().Set("X-Patator", "no, try `player patator` command")
}
_, found := c.Get(p.ID)
if found {
rand.Seed(time.Now().Unix())
processTime := time.Duration(velocity) * time.Second
select {
case <-r.Context().Done():
return
case <-time.After(processTime):
// The above channel simulates some hard work.
}
if rand.Intn(accuracy) != 0 {
http.Error(w, "Missed", 410)
return
}
if err := c.Increment(p.ID, 1); err != nil {
http.Error(w, err.Error(), 500)
return
}
} else {
c.Set(p.ID, 1, cache.NoExpiration)
}
w.WriteHeader(http.StatusCreated)
if _, err := w.Write([]byte("Hit")); err != nil {
log.Fatal(err)
}
}
<file_sep>#!/bin/bash
set -e
set -u
# = Vars
CLUSTER_NAME=k8s_patakube
CLUSTER_URL={{.ClusterUrl}}
CONTEXT_NAME=patakube
CONTEXT_NAMESPACE={{.Namespace}}
K8S_RELEASE_URL=https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin
# = Setup
#
# == Kubectl
echo '---> Downloading kubectl'
case "$(uname -s)" in
Darwin)
echo 'OS: Mac OS X'
curl -LO ${K8S_RELEASE_URL}/darwin/amd64/kubectl
;;
Linux)
echo 'OS: Linux'
curl -LO ${K8S_RELEASE_URL}/linux/amd64/kubectl
;;
*)
echo 'Unknown OS'
exit 2;
;;
esac
chmod +x ./kubectl
# == Configure
echo '---> Configuring kubectl'
# create kubeconfig entry
./kubectl config set-cluster ${CLUSTER_NAME} \
--server=${CLUSTER_URL}
# create context entry
./kubectl config set-context ${CONTEXT_NAME} \
--cluster=${CLUSTER_NAME} \
--namespace=${CONTEXT_NAMESPACE}
# use the context
./kubectl config use-context ${CONTEXT_NAME}
# = Run
echo '---> Testing kubectl config:'
echo '---> kubectl config view'
./kubectl config view
echo '---> kubectl cluster-info'
./kubectl cluster-info
echo '---> Done'
<file_sep>// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"io/ioutil"
"log"
"net/http"
"strconv"
"github.com/pressly/chi"
"github.com/pressly/chi/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// patatorCmd represents the patator command
var patatorCmd = &cobra.Command{
Use: "patator",
Short: "A potato launcher",
Long: `This tool help you to improve aiming of your shoots.
Be careful, this tool can be quite capricious ;)`,
Run: patator,
}
func init() {
playerCmd.AddCommand(patatorCmd)
}
func patator(cmd *cobra.Command, args []string) {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
http.Error(w, "Please send a request body", 412)
return
}
w.Header().Set("patator", "true")
req, err := http.NewRequest("POST", "http://"+viper.GetString("target"), r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
req.Header.Set("patator", "true")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer func() {
if e := res.Body.Close(); e != nil {
log.Fatal(e)
}
}()
responseBody, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
w.WriteHeader(res.StatusCode)
if _, err := w.Write(responseBody); err != nil {
log.Fatal(err)
}
})
if err := http.ListenAndServe(":"+strconv.Itoa(viper.GetInt("port")), r); err != nil {
log.Fatal(err)
}
}
<file_sep>kubectl run player --image=patakube/player --expose --port=8080 --env=[]
kubectl scale --replicas=3 deployment/player
kubectl apply -f deployment.yaml
| 41be6c7685b960adfea72e54249af32c2a400403 | [
"Markdown",
"Go",
"Shell"
] | 10 | Go | guilhem/patakube | e224a91887254ce31591ae6119b8b47c31e524b1 | a4ad11b1259b7973382c061945ef6898d5b1ee9b |
refs/heads/master | <file_sep>#!/bin/bash
##
## Shell script for creating configuration include files.
##
## Authors:
## <NAME>, <<EMAIL>>
##
##TODO:
## * we need to check if c++ (or other compiler??) is present
dtnow=$(date +'%F %T (%Z)')
logfile="$0.log"
basedir=$1
CC=${CC:=cc}
CXX=${CXX:=c++}
## Declares user-related variables
USR_CPPFLAGS=
USR_CFLAGS=
USR_CXXFLAGS=
USR_LDFLAGS=
## Format a date
function dcs_format_date()
{
echo $(date +'%F %T (%Z)')
}
## Initialize log file
function dcs_log_init()
{
> $logfile
}
## Log an error to the log-file.
function dcs_log_error()
{
date=$(dcs_format_date)
echo "ERROR ($date)>> $1" >> $logfile
}
## Log an error to the log-file.
function dcs_log_info()
{
date=$(dcs_format_date)
echo "INFO ($date)>> $1" >> $logfile
}
## Log an error to the log-file.
function dcs_log_warn()
{
date=$(dcs_format_date)
echo "WARNING ($date)>> $1" >> $logfile
}
## Check if your system has the Boost libraries installed
function dcs_check_boost()
{
src_temp_file=`mktemp tmp.XXXXXXXXXX`
out_temp_file=`mktemp tmp.XXXXXXXXXX`
cat > $src_temp_file <<EOT
#include <boost/version.hpp>
int main(int argc, char* argv[])
{
return 0;
}
EOT
compile_test=(`$CXX $CXXFLAGS -x 'c++' -o $out_temp_file $src_temp_file 2>&1 >/dev/null`)
ret=$?
rm -f $out_temp_file $src_temp_file
if [ $ret == 0 ]; then
echo -n "yes"
else
echo -n "no"
fi
}
## Script starts here
dcs_log_init
dcs_log_info "Starting configuration maker..."
## Control variables
have_boost_bool=
basesrcdir=
## Sanity checks
if [ -z "$basedir" ]; then
basedir=.
fi
if [ -z "$basesrcdir" ]; then
basesrcdir=$basedir/src
fi
## Load user-related variables
if [ -e "$basedir/user-config.sh" ]; then
source "$basedir/user-config.sh"
fi
## Set C/C++ environments
if [ ! -z "$USR_CPPFLAGS" ]; then
CPPFLAGS="$CFLAGS $USR_CPPFLAGS"
fi
if [ ! -z "$USR_CFLAGS" ]; then
CFLAGS="$CFLAGS $USR_CFLAGS"
fi
if [ ! -z "$USR_CXXFLAGS" ]; then
CXXFLAGS="$CXXFLAGS $USR_CXXFLAGS"
fi
if [ ! -z "$USR_LDFLAGS" ]; then
LDFLAGS="$LDFLAGS $USR_LDFLAGS"
fi
## Check for Boost
have_boost=`dcs_check_boost`
if [ "$have_boost" = "yes" ]; then
have_boost_bool='true'
else
have_boost_bool='false'
dcs_log_error "Wanted Boost but Boost not found."
found_errors=yes
fi
## Auto-generation of files.
if [ "$found_errors" = "yes" ]; then
dcs_log_info "Configuration maker has finished."
dcs_log_error "Exit with errors!"
echo "There are some errors. Check the $logfile log-file."
exit 1
fi
# Create base config dir
mkdir -p "$basesrcdir/config"
cat > $basedir/config.mk <<EOT
## \file config.mk
##
## \brief Configurations for the Make build system.
##
## [$dtnow]
## This is an autogenerated file. Do not edit.
##
## \author <NAME>, <mar<EMAIL>>
##
CPPFLAGS_release+=$USR_CPPFLAGS
CFLAGS_release+=$USR_CFLAGS
CXXFLAGS_release+=$USR_CXXFLAGS
LDFLAGS_release+=$USR_LDFLAGS
CPPFLAGS_debug+=$USR_CPPFLAGS
CFLAGS_debug+=$USR_CFLAGS
CXXFLAGS_debug+=$USR_CXXFLAGS
LDFLAGS_debug+=$USR_LDFLAGS
CPPFLAGS_test+=$USR_CPPFLAGS
CFLAGS_test+=$USR_CFLAGS
CXXFLAGS_test+=$USR_CXXFLAGS
LDFLAGS_test+=$USR_LDFLAGS
CPPFLAGS_xmp+=$USR_CPPFLAGS
CFLAGS_xmp+=$USR_CFLAGS
CXXFLAGS_xmp+=$USR_CXXFLAGS
LDFLAGS_xmp+=$USR_LDFLAGS
EOT
dcs_log_info "Configuration maker has finished."
<file_sep>/**
* \file dcs/control/bindings/slicot/detail/slicot.hpp
*
* \brief Declarations of SLICOT Fortran routines.
*
* The subroutine library SLICOT provides Fortran 77 implementations of
* numerical algorithms for computations in systems and control theory. Based on
* numerical linear algebra routines from BLAS and LAPACK libraries, SLICOT
* provides methods for the design and analysis of control systems.
*
* The SLICOT library is Copyright 2002-2012 NICONET e.V.
* For more information, see <a href="http://www.slicot.org>SLICOT web site</a>.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-control (below referred to as "this program").
*
* 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/>.
*/
#ifndef DCS_CONTROL_BINDINGS_SLICOT_DETAIL_SLICOT_HPP
#define DCS_CONTROL_BINDINGS_SLICOT_DETAIL_SLICOT_HPP
#include <dcs/control/bindings/detail/fortran.hpp>
#define DCS_CONTROL_BINDINGS_SLICOT_SB02OD DCS_CONTROL_BINDINGS_FORTRAN_FUNCTION_NAME(sb02od, SB02OD)
#define DCS_CONTROL_BINDINGS_SLICOT_SG02AD DCS_CONTROL_BINDINGS_FORTRAN_FUNCTION_NAME(sg02ad, SG02AD)
extern "C" {
void DCS_CONTROL_BINDINGS_SLICOT_SB02OD(const dcs_control_bindings_fortran_char* dico,
const dcs_control_bindings_fortran_char* jobb,
const dcs_control_bindings_fortran_char* fact,
const dcs_control_bindings_fortran_char* uplo,
const dcs_control_bindings_fortran_char* jobl,
const dcs_control_bindings_fortran_char* sort,
const ::dcs_control_bindings_fortran_int* n,
const ::dcs_control_bindings_fortran_int* m,
const ::dcs_control_bindings_fortran_int* p,
const dcs_control_bindings_fortran_double_real* a,
const ::dcs_control_bindings_fortran_int* lda,
const dcs_control_bindings_fortran_double_real* b,
const ::dcs_control_bindings_fortran_int* ldb,
const dcs_control_bindings_fortran_double_real* q,
const ::dcs_control_bindings_fortran_int* ldq,
const dcs_control_bindings_fortran_double_real* r,
const ::dcs_control_bindings_fortran_int* ldr,
const dcs_control_bindings_fortran_double_real* l,
const ::dcs_control_bindings_fortran_int* ldl,
dcs_control_bindings_fortran_double_real* rcond,
dcs_control_bindings_fortran_double_real* x,
const ::dcs_control_bindings_fortran_int* ldx,
dcs_control_bindings_fortran_double_real* alfar,
dcs_control_bindings_fortran_double_real* alfai,
dcs_control_bindings_fortran_double_real* beta,
dcs_control_bindings_fortran_double_real* s,
const ::dcs_control_bindings_fortran_int* lds,
dcs_control_bindings_fortran_double_real* t,
const ::dcs_control_bindings_fortran_int* ldt,
dcs_control_bindings_fortran_double_real* u,
const ::dcs_control_bindings_fortran_int* ldu,
const dcs_control_bindings_fortran_double_real* tol,
::dcs_control_bindings_fortran_int* iwork,
dcs_control_bindings_fortran_double_real* dwork,
const ::dcs_control_bindings_fortran_int* ldwork,
::dcs_control_bindings_fortran_logical* bwork,
::dcs_control_bindings_fortran_int* info);
void DCS_CONTROL_BINDINGS_SLICOT_SG02AD(const dcs_control_bindings_fortran_char* dico,
const dcs_control_bindings_fortran_char* jobb,
const dcs_control_bindings_fortran_char* fact,
const dcs_control_bindings_fortran_char* uplo,
const dcs_control_bindings_fortran_char* jobl,
const dcs_control_bindings_fortran_char* scal,
const dcs_control_bindings_fortran_char* sort,
const dcs_control_bindings_fortran_char* acc,
const ::dcs_control_bindings_fortran_int* n,
const ::dcs_control_bindings_fortran_int* m,
const ::dcs_control_bindings_fortran_int* p,
const dcs_control_bindings_fortran_double_real* a,
const ::dcs_control_bindings_fortran_int* lda,
const dcs_control_bindings_fortran_double_real* e,
const ::dcs_control_bindings_fortran_int* lde,
const dcs_control_bindings_fortran_double_real* b,
const ::dcs_control_bindings_fortran_int* ldb,
const dcs_control_bindings_fortran_double_real* q,
const ::dcs_control_bindings_fortran_int* ldq,
const dcs_control_bindings_fortran_double_real* r,
const ::dcs_control_bindings_fortran_int* ldr,
const dcs_control_bindings_fortran_double_real* l,
const ::dcs_control_bindings_fortran_int* ldl,
dcs_control_bindings_fortran_double_real* rcond,
dcs_control_bindings_fortran_double_real* x,
const ::dcs_control_bindings_fortran_int* ldx,
dcs_control_bindings_fortran_double_real* alfar,
dcs_control_bindings_fortran_double_real* alfai,
dcs_control_bindings_fortran_double_real* beta,
dcs_control_bindings_fortran_double_real* s,
const ::dcs_control_bindings_fortran_int* lds,
dcs_control_bindings_fortran_double_real* t,
const ::dcs_control_bindings_fortran_int* ldt,
dcs_control_bindings_fortran_double_real* u,
const ::dcs_control_bindings_fortran_int* ldu,
const dcs_control_bindings_fortran_double_real* tol,
::dcs_control_bindings_fortran_int* iwork,
dcs_control_bindings_fortran_double_real* dwork,
const ::dcs_control_bindings_fortran_int* ldwork,
::dcs_control_bindings_fortran_logical* bwork,
::dcs_control_bindings_fortran_int* iwarn,
::dcs_control_bindings_fortran_int* info);
} // extern "C"
#endif // DCS_CONTROL_BINDINGS_SLICOT_DETAIL_SLICOT_HPP
<file_sep>/**
* \file dcs/control/bindings/detail/fortran.hpp
*
* \brief Definitions for interfacing with Fortran routines.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2012 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_BINDINGS_DETAIL_FORTRAN_HPP
#define DCS_CONTROL_BINDINGS_DETAIL_FORTRAN_HPP
#include <complex>
extern "C" {
// "g77" or "gfortran" or mkl_intel_lp64
//#undef DCS_CONTROL_BINDINGS_DETAIL_BIND_FORTRAN_INTEGER_8
// clapack or "gfortran -fdefault-integer-8" or mkl_intel_ilp64
//#define DCS_CONTROL_BINDINGS_DETAIL_BIND_FORTRAN_INTEGER_8
//#ifndef DCS_CONTROL_BINDINGS_DETAIL_BIND_FORTRAN_INTEGER_8
////From BOOST-Numeric_Bindings
//typedef int fortran_int_t;
//typedef unsigned int fortran_bool_t;
////From LAPACK
////typedef int fortran_int_t;
////typedef fortran_int_t fortran_bool_t;
//#else // DCS_CONTROL_BINDINGS_DETAIL_BIND_FORTRAN_INTEGER_8
//typedef std::ptrdiff_t fortran_int_t;
//typedef std::size_t fortran_bool_t;
//#endif // DCS_CONTROL_BINDINGS_DETAIL_BIND_FORTRAN_INTEGER_8
typedef char dcs_control_bindings_fortran_char;
typedef int dcs_control_bindings_fortran_int;
typedef unsigned int dcs_control_bindings_fortran_logical;
typedef float dcs_control_bindings_fortran_single_real;
typedef double dcs_control_bindings_fortran_double_real;
typedef std::complex<float> dcs_control_bindings_fortran_single_complex;
typedef std::complex<double> dcs_control_bindings_fortran_double_complex;
typedef dcs_control_bindings_fortran_logical (*dcs_control_bindings_fortran_function)(...);
} // extern "C"
#define DCS_CONTROL_BINDINGS_FORTRAN_FUNCTION_NAME(id, ID) id##_
#endif // DCS_CONTROL_BINDINGS_DETAIL_FORTRAN_HPP
<file_sep>/**
* \file dcs/control/solver/dare.hpp
*
* \brief Discrete-time Algebraic Riccati Equations solver.
*
* Computes the unique stabilizing solution \f$X\f$ of the discrete-time
* algebraic Riccati equation
* \f[
* A^{T}XA - E^{T}XE - (A^{T}XB+S)(B^{T}XB+R)^{-1}(B^{T}X A+S)^{T} + Q = 0
* \f]
* or, equivalently (if \f$R\f$ is nonsingular):
* \f[
* E^{T}XE = F^{T}XF-F^{T}XB(B^{T}XB+R)^{-1}B^{T}XF + Q - SR^{-1}S^{T}
* \f]
* where \f$F=A-BR^{-1}S^{T}\f$.
*
* Beside the solution \f$X\f$, the solver also computes the \e gain matrix
* \f[ -1
* G = (B^{T}XB + R)^{-1}(B^{T}XA + S^{T})
* \f]
* and the vector \f$L\f$ of <em>closed-loop eigenvalues</em> associated to the
* generalized Schur decomposition of matrix pencil \f$(A-BG,E)\f$.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_SOLVER_DARE_HPP
#define DCS_CONTROL_SOLVER_DARE_HPP
#include <algorithm>
#include <boost/mpl/if.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublasx/container/generalized_diagonal_matrix.hpp>
#include <boost/numeric/ublasx/container/sequence_vector.hpp>
#include <boost/numeric/ublasx/operation/abs.hpp>
#include <boost/numeric/ublasx/operation/any.hpp>
#include <boost/numeric/ublasx/operation/arithmetic_ops.hpp>
#include <boost/numeric/ublasx/operation/balance.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/diag.hpp>
#include <boost/numeric/ublasx/operation/empty.hpp>
#include <boost/numeric/ublasx/operation/find.hpp>
#include <boost/numeric/ublasx/operation/isinf.hpp>
#include <boost/numeric/ublasx/operation/log2.hpp>
#include <boost/numeric/ublasx/operation/lu.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/pow2.hpp>
#include <boost/numeric/ublasx/operation/qr.hpp>
#include <boost/numeric/ublasx/operation/qz.hpp>
#include <boost/numeric/ublasx/operation/rcond.hpp>
#include <boost/numeric/ublasx/operation/relational_ops.hpp>
#include <boost/numeric/ublasx/operation/rep.hpp>
#include <boost/numeric/ublasx/operation/reshape.hpp>
#include <boost/numeric/ublasx/operation/round.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <boost/numeric/ublasx/operation/tril.hpp>
#include <boost/numeric/ublasx/operation/triu.hpp>
#include <boost/type_traits/is_complex.hpp>
#include <cmath>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/math/traits/float.hpp>
#include <functional>
#include <iostream>
#include <stdexcept>
namespace dcs { namespace control {
namespace detail { namespace /*<unnamed>*/ {
/**
* \brief Performs row/column scaling of 2D matrix.
*
* \param A The matrix to be scaled
* \param s The scaling vector
* \param p The permutation vector
* \param full_balance Performs full row/column balancing
* \param permute Enables row/column permutation
* \return The scaled matrix B=T\\A*T together with the scaling S and
* permutation P such that T(:,P)=diag(S).
*/
template <typename MatrixExprT, typename SVectorT, typename PVectorT>
typename ::boost::numeric::ublasx::balance_traits<MatrixExprT>::balanced_matrix_type mat_scale(::boost::numeric::ublas::matrix_expression<MatrixExprT> const& A,
SVectorT& s,
PVectorT& p,
bool full_balance,
bool permute)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublasx::balance_traits<MatrixExprT>::balanced_matrix_type balanced_matrix_type;
typedef typename ublas::matrix_traits<MatrixExprT>::size_type size_type;
typedef typename ublas::matrix_traits<MatrixExprT>::value_type value_type;
balanced_matrix_type B;
// Compute scaling
if (full_balance)
{
B = ublasx::balance(A, s, true, false);
}
else
{
//TODO: see MATLAB mscale.m (use of matscale function)
throw ::std::runtime_error("[dcs::control::detail::mat_scale] Regularized row/column balancing not yet supported.");
}
// Compute permutation
size_type n(ublasx::num_rows(A));
if (ublasx::size(p) != n)
{
p.resize(n, false);
}
if (permute)
{
if (::dcs::math::float_traits<value_type>::essentially_equal(ublas::norm_1(ublasx::tril(A,-2)), 0))
{
// Real upper Hessenberg: no permutation
p = ublasx::sequence_vector<size_type>(0, n);
}
else if (::dcs::math::float_traits<value_type>::essentially_equal(ublas::norm_1(ublasx::triu(A,2)), 0))
{
// Real lower Hessenberg
p = ublasx::sequence_vector<size_type>(n-1, -1, n);
}
else
{
SVectorT tmp_s;
ublasx::balance(A, tmp_s, p, true, true);
}
// Permute rows and columns of B according to p
balanced_matrix_type tmp_B(ublasx::num_rows(B), ublasx::num_columns(B));
for (size_type i = 0; i < n; ++i)
{
size_type k(p[i]);
ublas::row(tmp_B, i) = ublas::row(B, k);
}
for (size_type i = 0; i < n; ++i)
{
size_type k(p[i]);
ublas::column(B, i) = ublas::column(tmp_B, k);
}
}
else
{
// Sequential order
p = ublasx::sequence_vector<size_type>(0, n);
}
return B;
}
/**
* \brief Applies left and right scaling matrices.
*
* Forms Y=diag(L)*X*diag(R).
*/
template <typename AMatrixExprT, typename LVectorExprT, typename RVectorExprT>
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::matrix_traits<AMatrixExprT>::value_type
> left_right_mat_scale(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A,
::boost::numeric::ublas::vector_expression<LVectorExprT> const& l,
::boost::numeric::ublas::vector_expression<RVectorExprT> const& r)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::matrix_traits<AMatrixExprT>::value_type value_type;
typedef typename ublas::matrix_traits<AMatrixExprT>::size_type size_type;
ublas::matrix<value_type> X(A);
size_type nr(ublasx::num_rows(A));
size_type nc(ublasx::num_columns(A));
#if 0 // Slower solution
if (!ublasx::empty(l))
{
// Transforms l into a nr-by-nc matrix L=[l l ... l] and
// computes X=L.*X
X = ublas::element_prod(
ublasx::rep(l, 1, nc),
X
);
}
// else: L=I_{nr,nc} and X=L.*X
if (!ublasx::empty(r))
{
// Transforms r into a nr-by-nc matrix R=[r'; r'; ... r'] and
// computes X=X.*R
X = ublas::element_prod(
X,
ublasx::rep(
ublasx::reshape(r, 1, nc),
nr,
1
)
);
}
// else: R=I_{nr,nc} and X=X.*R
#else // Faster solution (2*nr*nc flops) for small-to-midsize arrays
ublas::matrix<value_type> L;
ublas::matrix<value_type> R;
if (!ublasx::empty(l))
{
// Transforms l into a nr-by-1 matrix L=[l]
L = ublasx::reshape(l, nr, 1);
}
else
{
// Creates L=[1; 1; ... 1]
L = ublas::scalar_matrix<value_type>(nr, 1, 1);
}
if (!ublasx::empty(r))
{
// Transforms r into a 1-by-nc matrix R=[r']
R = ublasx::reshape(r, 1, nc);
}
else
{
// Creates R=[1 1 ... 1]
R = ublas::scalar_matrix<value_type>(1, nc, 1);
}
// Computes X=X.*(L*R)
X = ublas::element_prod(X, ublas::prod(L, R));
#endif
return X;
}
template <typename AMatrixExprT, typename LMatrixExprT, typename RMatrixExprT>
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::matrix_traits<AMatrixExprT>::value_type
> left_right_mat_scale(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A,
::boost::numeric::ublas::matrix_expression<LMatrixExprT> const& L,
::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::matrix_traits<AMatrixExprT>::value_type value_type;
typedef typename ublas::matrix_traits<AMatrixExprT>::size_type size_type;
ublas::matrix<value_type> X(A);
size_type nr(ublasx::num_rows(A));
size_type nc(ublasx::num_columns(A));
#if 0 // Slower solution
if (!ublasx::empty(L))
{
// Transforms L into a nr-by-nc matrix LL=[L L ... L] and
// computes X=LL.*X
X = ublas::element_prod(
ublasx::rep(
ublasx::reshape(L, nr, 1),
1,
nc
),
X
);
}
// else: L=I_{nr,nc} and X=L.*X
if (!ublasx::empty(R))
{
// Transforms R into a nr-by-nc matrix RR=[R'; R'; ... R'] and
// computes X=X.*RR
X = ublas::element_prod(
X,
ublasx::rep(
ublasx::reshape(R, nc, 1),
nr,
1
)
);
}
// else: R=I_{nr,nc} and X=X.*R
#else // Faster solution (2*nr*nc flops) for small-to-midsize arrays
ublas::matrix<value_type> LL;
ublas::matrix<value_type> RR;
if (!ublasx::empty(L))
{
// Transforms L (which we assume is a 1-by-nr matrix) into
// a nr-by-1 matrix LL=L'
LL = ublasx::trans(L);
}
else
{
// Creates L=[1; 1; ... 1]
LL = ublas::scalar_matrix<value_type>(nr, 1, 1);
}
if (!ublasx::empty(R))
{
// Transforms R (which we assume is a nc-by-1 matrix) into
// a 1-by-nc matrix RR=R'
RR = ublasx::trans(R, 1, nc);
}
else
{
// Creates R=[1 1 ... 1]
RR = ublas::scalar_matrix<value_type>(1, nc, 1);
}
// Computes X=X.*(LL*RR)
X = ublas::element_prod(X, ublas::prod(LL, RR));
#endif
return X;
}
template <typename HMatrixT, typename JMatrixT, typename LVectorT, typename X1MatrixT, typename X2MatrixT, typename XMatrixT>
void gdare(HMatrixT& H, JMatrixT& J, ::std::size_t n, ::std::size_t m, LVectorT& l, X1MatrixT& X1, X2MatrixT& X2, XMatrixT& X, bool balance, bool factorize)
{
// - inputs: H, J, n, balance, factorize
// - outputs:
// - X1, X2, sx, L (if 'factorize' == true)
// - X, L (otherwise)
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<HMatrixT>::size_type,
typename ublas::matrix_traits<JMatrixT>::size_type>::promote_type size_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<HMatrixT>::value_type,
typename ublas::matrix_traits<JMatrixT>::value_type>::promote_type value_type;
typedef typename ublas::type_traits<value_type>::real_type real_type;
typedef ublas::matrix<value_type> work_matrix_type;
typedef ublas::vector<value_type> work_vector_type;
size_type n2 = n*2;
size_type n2pm = n2+m;
// size_type n2p1 = n2+1;
// size_type mp1 = m+1;
const real_type eps = ::std::numeric_limits<real_type>::epsilon();
// Scale Symplectic matrix/pencil before compression to preserve
// Symplectic structure (D = state matrix scaling).
ublas::vector<real_type> sx; // scaling vector
ublas::vector<size_type> p; // permutation vector
if (balance)
{
// Computes diagonal scaling: computes a state vector scaling S that
// balances the Hamiltonian/Symplectic matrix or pencil.
// The original state matrix A is transformed to D*A/D where D=diag(S),
// and the solutions X and Y to the original and rescaled equations are
// related by X=D*Y*D.
// Form matrix M to be balanced
work_matrix_type M;
real_type tol_zero(1e2*eps);
if (ublasx::empty(J))
{
M = H;
}
else
{
work_matrix_type Hd;
work_matrix_type Jd;
real_type nh;
real_type nj;
//Hd = H - ublasx::diag(ublasx::diag(H));
Hd = H - ublasx::generalized_diagonal_adaptor<HMatrixT>(H);
nh = ublas::norm_1(
ublas::subrange(Hd, 0, n, 0, n)
)
+
ublasx::norm_1(
ublas::subrange(Hd, n, n2, n, n2)
);
//Jd = J-ublasx::diag(ublasx::diag(J));
Jd = J - ublasx::generalized_diagonal_adaptor<JMatrixT>(J);
nj = ublas::norm_1(
ublas::subrange(Jd, 0, n, 0, n)
)
+
ublasx::norm_1(
ublas::subrange(Jd, n, n2, n, n2)
);
if (nh > 0 && nj > 0)
{
M = nj*ublasx::abs(H) + nh*ublasx::abs(J);
}
else
{
M = ublasx::abs(H) + ublasx::abs(J);
}
}
// Small parasitic entries can trick scaling into making X1 nearly
// singular.
// Zero out such entries in the magnitude matrix M
// Also helps identifying near-triangularizing permutation, e.g.,
// [1 eps;1/eps 1] -> (ignore eps) -> [1 1/eps;eps 1]
if (m == 0)
{
work_matrix_type Mu(n2,2,0);
ublas::column(Mu, 1) = ublasx::abs(ublasx::diag(M));
ublas::column(Mu, 2) = ublas::scalar_vector<real_type>(n2, 1);
Mu = tol_zero * (Mu+ublas::trans(Mu));
size_type nr_M(ublasx::num_rows(M));
size_type nc_M(ublasx::num_columns(M));
for (size_type r = 0; r < nr_M; ++r)
{
for (size_type c = 0; c < nc_M; ++c)
{
if (::dcs::math::float_traits<real_type>::definitely_less(::std::abs(M(r,c)), Mu(r,c)))
{
M(r,c) = real_type/*zero*/();
}
}
}
}
// Rescale magnitude matrix.
// 1. Use two-step approach to acquire permutation
// 2. Acquire permutation making H(p,p) more upper triangular.
// This enhances numerics when H can be permuted to nearly
// upper-triangular (the Schur method may underperform the eigenvalue
// one without this permutation).
// 3. Full balancing needed when F,G<<1, but can hurt when A has small
// entries (roundoff) and F=0 or G=0.
ublas::vector<real_type> s;
ublas::vector<size_type> pp;
detail::mat_scale(M, s, pp, true, true);
pp = ublasx::find(pp, ::std::bind2nd(::std::less<size_type>(), n2));
p.resize(ublasx::size(pp), false);
for (size_type i = 0; i < n2; ++i)
{
p[pp[i]] = i;
}
// unconstrained balancing diag(D1,D2,DR)
s = ublasx::log2(s);
// Impose the constraint that diagonal scalings must be of the form
// diag(D,1./D,DR).
sx = ublasx::round(
(ublas::subrange(s, n, n2)-ublas::subrange(s, 0, n))/real_type(2)
); // D=sqrt(D1/D2)
ublas::subrange(s, 0, n) = ublasx::pow2(sx);
ublas::subrange(s, n, n2) = ublasx::pow2(-sx);
ublas::subrange(s, n2, n2+m) = ublasx::pow2(-ublas::subrange(s, n2, n2+m));
sx = ublas::subrange(s, 0, n); // n-by-1 vector
// Rescale H,J and return diagonal scaling of state matrix
H = detail::left_right_mat_scale(H, s, real_type(1)/s);
if (!ublasx::empty(J))
{
J = detail::left_right_mat_scale(J, s, real_type(1)/s);
}
}
else
{
// No balance
sx = ublas::scalar_vector<value_type>(n, 1);
p = ublasx::sequence_vector<size_type>(0, n);
}
work_matrix_type E;
E = ublas::subrange(J, 0, n, 0, n);
// Compression step on H(:,n2+1:n2+m) = [S1;-S2;R]
if (m > 0)
{
ublasx::qr_decomposition<value_type> qr;
qr.decompose(ublas::subrange(H, 0, n2pm, n2, n2pm));
work_matrix_type tmp_Qt;
tmp_Qt = ublas::trans(
ublas::subrange(qr.Q(), 0, n2pm, m, n2pm)
),
H = ublas::prod(
tmp_Qt,
ublas::subrange(H, 0, n2pm, 0, n2)
);
J = ublas::prod(
tmp_Qt,
ublas::subrange(J, 0, n2pm, 0, n2)
);
}
//XXX DCS_DEBUG_TRACE("After QR");
//XXX DCS_DEBUG_TRACE("H=" << H);
//XXX DCS_DEBUG_TRACE("J=" << J);
// QZ algorithm
//
// NOTE: usual formulation is in term of the pencil (H,J), but
// generalized eigenvalues have a tendency to deflate out in the
// "desired" order, so work with (J.H) instead.
// Specifically, the natural tendency of the QZ algorithm to get
// the largest eigenvalues in the leading part of the matrix pair
// is exploited, by computing the unstable eigenvalues (i.e., the
// ones outside the unit circle) of the permuted matrix pair
// (J,H).
// This is equivalent to take the eigenvalues inside the unit
// circle of the matrix pair (H,J).
size_type n_p(ublasx::size(p));
work_matrix_type HH(n_p,n_p,0);
work_matrix_type JJ(n_p,n_p,0);
// permute H and J
for (size_type r = 0; r < n_p; ++r)
{
for (size_type c = 0; c < n_p; ++c)
{
HH(r,c) = H(p[r],p[c]);
JJ(r,c) = J(p[r],p[c]);
}
}
// QZ decompose
//XXX DCS_DEBUG_TRACE("Before QZ");
//XXX DCS_DEBUG_TRACE("H(perm,perm)=" << HH);
//XXX DCS_DEBUG_TRACE("J(perm,perm)=" << JJ);
ublasx::qz_decomposition<value_type> qz;
qz.decompose(JJ, HH);
//XXX DCS_DEBUG_TRACE("After QZ");
//XXX DCS_DEBUG_TRACE("HH=" << HH);
//XXX DCS_DEBUG_TRACE("JJ=" << JJ);
//XXX DCS_DEBUG_TRACE("q=" << qz.Q());
//XXX DCS_DEBUG_TRACE("z=" << qz.Z());
//XXX DCS_DEBUG_TRACE("S=" << qz.S());
//XXX DCS_DEBUG_TRACE("T=" << qz.T());
// Reorder eigenvalues to push eigenvalues outside the unit circle
// (inside for (H,J)) to the top
qz.reorder(ublasx::udo_qz_eigenvalues);
JJ = qz.S();
HH = qz.T();
//XXX DCS_DEBUG_TRACE("After QZ Reorder");
//XXX DCS_DEBUG_TRACE("HH=" << HH);
//XXX DCS_DEBUG_TRACE("JJ=" << JJ);
work_matrix_type ZZ;
work_matrix_type Z(n_p,n_p,0);
ZZ = qz.Z();
//XXX DCS_DEBUG_TRACE("ZZ=" << ZZ);
//XXX DCS_DEBUG_TRACE("perm=" << p);
for (size_type i = 0; i < n_p; ++i)
{
//ublas::row(Z, i) = ublas::row(ZZ, p[i]);
ublas::row(Z, p[i]) = ublas::row(ZZ, i);
}
ZZ.resize(0, 0, false);
// Compute the n stable closed-loop eigenvalues of the system matrix
// A-BG, where G is the optimal feedback matrix computed based on the
// solution matrix X.
// These eigenvalues correspond to the the trailing n generalized
// eigenvalues of the QZ decomposition
l = qz.eigenvalues();
//XXX DCS_DEBUG_TRACE("L=" << l);
//XXX DCS_DEBUG_TRACE("Z=" << Z);
// if (ublasx::any(ublasx::isinf(l)))
// {
// throw ::std::runtime_error("[dcs::control::dare] [Error] Unable to solve the specified Riccati equation: infinite or undetermined gain.");
// }
// Account for non-identity E matrix and orthonormalize basis
if (E != ublas::identity_matrix<value_type>(n,n))
{
work_matrix_type EZ;
EZ = ublas::prod(E, ublas::subrange(Z, 0, n, 0, n));
EZ.resize(n2, n);
ublas::subrange(EZ, n, n2, 0, n) = ublas::subrange(Z, n, n2, 0, n);
ublasx::qr_decomposition<value_type> qr;
qr.decompose(EZ);
Z = ublas::subrange(qr.Q(), 0, n2, 0, n);
}
// work_matrix_type X1;
// work_matrix_type X2;
X1 = ublas::subrange(Z, 0, n, 0, n);
X2 = ublas::subrange(Z, n, n2, 0, n);
// Check that stable invariant subspace was properly extracted
{
// BEGIN of MATLAB arecheckout
work_matrix_type X12;
X12 = ublas::prod(ublas::trans(X1), X2);
// Solution asymmetry
real_type asym(ublas::norm_1(X12-ublas::trans(X12)));
work_vector_type al(ublasx::abs(l));
// l = ublasx::find(
// ublasx::abs(l),
// ::std::bind2nd(::std::greater<real_type>(), real_type(1))
// );
bool has_abs_le_1;
bool has_abs_gt_1;
// any(!abs(l(1:n)) > 1)
has_abs_le_1 = ublasx::any(
ublas::subrange(al, 0, n),
::std::bind2nd(
::std::less_equal<real_type>(),
real_type(1)
)
);
// any(abs(l((n+1):(2*n))) > 1)
has_abs_gt_1 = ublasx::any(
ublas::subrange(al, n, n2),
::std::bind2nd(
::std::greater<real_type>(),
real_type(1)
)
);
if (has_abs_le_1
|| has_abs_gt_1
|| ::dcs::math::float_traits<real_type>::definitely_greater(asym, ::std::max(1.0e3*eps, 0.1*ublas::norm_1(X12))))
{
// Could not (reliably) isolate stable invariant subspace of
// dimension n
//report = -1;
X1 = X2
= work_matrix_type();
sx = work_vector_type();
throw ::std::runtime_error("[dcs::control::dare] [Error] Unable to solve the specified Riccati equation: the Symplectic spectrum is too near the imaginary axis.");
}
else
{
//report = 0;
if (::dcs::math::float_traits<real_type>::definitely_greater(asym, ::std::sqrt(eps)))
{
::std::clog << "[Warning] Solution may be inaccurate due to poor scaling or eigenvalues near the stability boundary." << ::std::endl;
}
}
// END of MATLAB arecheckout
// Last n eigenvalues are inside the unit circle
//l = ublas::conj(ublas::subrange(l, n, n2));
if (::boost::is_complex<value_type>::value)
{
// eig(H,J)=[t,1/conj(t)], |t|<1 => L = eig(J,H)=[1/t,conj(t)]
// => t = conj(L(n+1:2*n))
l = ublas::conj(ublas::subrange(l, n, n2));
}
else
{
l = ublas::subrange(l, n, n2);
}
}
if (ublasx::any(ublasx::isinf(l)))
{
throw ::std::runtime_error("[dcs::control::dare] [Error] Unable to solve the specified Riccati equation: infinite or undetermined gain.");
}
if (factorize)
{
//TODO
}
else
{
// Compute the Riccati solution X=sx*(X2/X1)*sx
// Solve the system X*X1=X2 (== X1' X = X2')
size_type sing;
sing = ublasx::lu_solve(ublas::trans(X1), ublas::trans(X2), X);
if (sing)
{
// X1 is singular
X = work_matrix_type();
throw ::std::runtime_error("[dcs::control::dare] [Error] The E matrix must be nonsingular.");
}
else
{
// Symmetrize
X = (X+ublas::trans(X))/real_type(2);
// Factor in scaling sx (X -> sx X sx)
X = detail::left_right_mat_scale(X,sx,sx);
}
}
}
}} // Namespace detail::<unnamed>
/**
* \brief Solver for the discrete-time algebraic Ricciati equation (DARE).
*
* Computes the unique stabilizing solution X of the discrete-time algebraic
* Riccati equation
* \f[
* A^{T}XA-E^{T}XE-(A^{T}XB+S)(B^{T}XB+R)^{-1}(B^{T}XA+S)+Q=0
* \f]
* The dare function also returns the gain matrix
* \f[
* G=(B^{T}XB+R)^{-1}(B^{T}XA+S)
* \f]
* and the vector L of closed loop eigenvalues, where
* \f[
* L=\operatorname{eigen}(A-B*G,E)
* \f]
* where \f$S\f$ is the cross-coupling matrix.
* Usually, \f$R\f$, \f$S\f$ and \f$E\f$ are set to the values
* \f{align}{
* R &= I,\\
* S &= 0,\\
* E &= I
* \f}
* resulting in the following Riccati equation form:
* \f[
* A^{T}XA-X-A^{T}XB(B^{T}XB+I)^{-1}B^{T}XA+Q=0
* \f]
*
* \note
* Inspired by the \c dare MATLAB function.
*
* \author <NAME>, <EMAIL>
*/
template <typename ValueT>
class dare_solver
{
public: typedef ValueT value_type;
public: typedef typename ::boost::numeric::ublas::type_traits<value_type>::real_type real_type;
private: typedef ::boost::numeric::ublas::matrix<value_type,::boost::numeric::ublas::column_major> work_matrix_type;
private: typedef ::boost::numeric::ublas::vector<
typename ::boost::mpl::if_<
::boost::is_complex<value_type>,
value_type,
::std::complex<value_type>
>::type
> work_vector_type;
public: typedef work_matrix_type matrix_type;
public: typedef work_vector_type vector_type;
private: typedef typename ::boost::numeric::ublas::matrix_traits<work_matrix_type>::size_type size_type;
// Default constructor
public: dare_solver()
{
// empty
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT
>
dare_solver(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q)
{
solve(A, B, Q);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT
>
dare_solver(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R)
{
solve(A, B, Q, R);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT
>
dare_solver(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R, ::boost::numeric::ublas::matrix_expression<SMatrixExprT> const& S)
{
solve(A, B, Q, R, S);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT
>
dare_solver(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R, ::boost::numeric::ublas::matrix_expression<SMatrixExprT> const& S, ::boost::numeric::ublas::matrix_expression<EMatrixExprT> const& E)
{
solve(A, B, Q, R, S, E);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT
>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B)
{
namespace ublas = ::boost::numeric::ublas;
work_matrix_type Q = ublas::identity_matrix<value_type>(ublas::num_rows(B));
solve(A, B, Q);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT
>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q)
{
namespace ublas = ::boost::numeric::ublas;
work_matrix_type R = ublas::identity_matrix<value_type>(ublas::num_columns(B));
solve(A, B, Q, R);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT
>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R)
{
namespace ublas = ::boost::numeric::ublas;
work_matrix_type S = ublas::zero_matrix<value_type>(ublas::num_rows(B), ublas::num_columns(B));
solve(A, B, Q, R, S);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT
>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R, ::boost::numeric::ublas::matrix_expression<SMatrixExprT> const& S)
{
namespace ublas = ::boost::numeric::ublas;
work_matrix_type E = ublas::identity_matrix<value_type>(ublas::num_rows(B));
solve(A, B, Q, R, S, E);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT
>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R, ::boost::numeric::ublas::matrix_expression<SMatrixExprT> const& S, ::boost::numeric::ublas::matrix_expression<EMatrixExprT> const& E)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
size_type n = ublasx::num_rows(B);
size_type m = ublasx::num_columns(B);
// precondition: n > 0 && m > 0
DCS_ASSERT(
n > 0 && m > 0,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Empty matrix.")
);
// precondition: A is square && num_rows[A] == num_rows[B]
DCS_ASSERT(
ublasx::num_rows(A) == n && ublasx::num_columns(A) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A must be a square matrix and must have the same number of rows of B.")
);
// precondition: Q is square && size[Q] == size[A]
DCS_ASSERT(
ublasx::num_rows(Q) == n && ublasx::num_columns(Q) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: Q is symmetric
DCS_ASSERT(
ublas::norm_1(Q-ublas::trans(Q)) <= 100*eps_*ublas::norm_1(Q),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Q must be symmetric.")
);
// precondition: R is square && num_rows[R] == num_columns[B]
DCS_ASSERT(
ublasx::num_rows(R) == m && ublasx::num_columns(R) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be a square matrix and must have the same number of columns of B.")
);
// precondition: R is symmetric
DCS_ASSERT(
ublas::norm_1(R-ublas::trans(R)) <= 100*eps_*ublas::norm_1(R),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be symmetric.")
);
// precondition: size[S] == size[B]
DCS_ASSERT(
ublasx::num_rows(S) == n && ublasx::num_columns(S) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] B and S must be the same size.")
);
// precondition: E is square && size[E] == size[A]
DCS_ASSERT(
ublasx::num_rows(E) == n && ublasx::num_columns(E) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: E != I_n && E is not singular
DCS_ASSERT(
/*E != ublas::identity_matrix(n) && */ublasx::rcond(E) >= eps_,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be nonsingular.")
);
// reset state
X_.resize(0, 0, false);
l_.resize(0, false);
G_.resize(0, 0, false);
// Set up extended Symplectic pencil (H,J) of the form:
// | A 0 B| |E 0 0|
// H - z J = |-Q E' -S| - z |0 A' 0|
// | S' 0 R| |0 -B' 0|
// of dimension (2N+M)x(2N+M), where N and M are the number of rows and
// of columns of matrix B, respectively.
work_matrix_type H; // (2*n+m,2*n+m)
work_matrix_type J; // (2*n+m,2*n+m)
H = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
ublasx::cat_rows(
A,
ublas::zero_matrix<value_type>(n,n)
),
B
),
ublasx::cat_rows(
ublasx::cat_rows(
-Q,
ublas::trans(E)
),
-S
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::trans(S),
ublas::zero_matrix<value_type>(m,n)
),
R
)
);
J = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
E,
ublas::zero_matrix<value_type>(n,n+m)
),
ublasx::cat_rows(
ublas::zero_matrix<value_type>(n,n),
ublasx::cat_rows(
ublas::trans(A),
ublas::zero_matrix<value_type>(n,m)
)
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::zero_matrix<value_type>(m,n),
-ublas::trans(B)
),
ublas::zero_matrix<value_type>(m)
)
);
work_matrix_type X1;
work_matrix_type X2;
detail::gdare(H, J, n, m, l_, X1, X2, X_, true, false);
// Compute gain matrix G=(B'*X*B+R)\(B'*X*A+S')
work_matrix_type BtX(ublas::prod(ublas::trans(B), X_));
size_type sing;
sing = ublasx::lu_solve(
ublas::prod(BtX, B) + R,
ublas::prod(BtX, A) + ublas::trans(S),
G_
);
if (sing)
{
// Nearly singular matrix
DCS_DEBUG_TRACE("Cannot compute DARE gain matrix: nearly singular matrix.");
throw ::std::runtime_error("[dcs::control::dare_solver::solve] Cannot compute DARE gain matrix: nearly singular matrix.");
}
// // Compute relative residual
// // - T1 = A'*X*A - E'*X*E
// // - T2 = (A'*X*B + S)*G
// work_matrix_type AtX(ublas::prod(ublas::trans(A), X_));
// T1_ = ublas::prod(AtX, A) - ublas::prod(ublas::prod(ublas::trans(E), X), E);
// T2_ = ublas::prod((ublas::prod(AtX, B) + S), G_);
// work_matrix_type Res = T1 - T2 + Q;
// report = ublas::norm_1(Res)/(1+ublas::norm_1(T1_)+ublas::norm_1(T2_)+ublas::norm_1(Q));
}
public: matrix_type solution() const
{
return X_;
}
/// Return the gain matrix: \f$(B^T X B + R)^{-1}( B^T X A + S^T)\f$.
public: matrix_type gain() const
{
return G_;
}
/**
* \brief Return the closed-loop eigenvalues vector.
*
* The closed-loop eigenvalues vector \f$\lambda\f$ is computed as:
* \f[
* \lambda = \operatorname{eig}(A-BG, E)
* \f]
* where \f$G\f$ is the gain matrix.
*/
public: vector_type eigenvalues() const
{
return l_;
}
private: static const real_type eps_;
private: work_matrix_type X_; /// The solution matrix
private: work_matrix_type G_; /// The gain matrix
private: work_vector_type l_; /// The closed-loop eigenvalues vector.
};
template <typename ValueT>
const typename ::boost::numeric::ublas::type_traits<ValueT>::real_type dare_solver<ValueT>::eps_ = ::std::numeric_limits<typename ::boost::numeric::ublas::type_traits<ValueT>::real_type>::epsilon();
/**
* \brief Solve the discrete-time algebraic Ricciati equation (DARE).
*
* Computes the unique stabilizing solution X of the discrete-time algebraic
* Riccati equation
* \f[
* A^{T}XA-E^{T}XE-(A^{T}XB+S)(B^{T}XB+R)^{-1}(B^{T}XA+S)+Q=0
* \f]
* The dare function also returns the gain matrix
* \f[
* G=(B^{T}XB+R)^{-1}(B^{T}XA+S)
* \f]
* and the vector L of closed loop eigenvalues, where
* \f[
* L=\operatorname{eigen}(A-B*G,E)
* \f]
* where \f$S\f$ is the cross-coupling matrix.
* Usually, \f$R\f$, \f$S\f$ and \f$E\f$ are set to the values
* \f{align}{
* R &= I,\\
* S &= 0,\\
* E &= I
* \f}
* resulting in the following Riccati equation form:
* \f[
* A^{T}XA-X-A^{T}XB(B^{T}XB+I)^{-1}B^{T}XA+Q=0
* \f]
*
* \note
* Inspired by the \c dare MATLAB function.
*
* \author <NAME>, <EMAIL>
*/
template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT,
typename XMatrixT
>
void dare(::boost::numeric::ublas::matrix_expression<AMatrixExprT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixExprT> const& B, ::boost::numeric::ublas::matrix_expression<QMatrixExprT> const& Q, ::boost::numeric::ublas::matrix_expression<RMatrixExprT> const& R, ::boost::numeric::ublas::matrix_expression<SMatrixExprT> const& S, ::boost::numeric::ublas::matrix_expression<EMatrixExprT> const& E, XMatrixT& X)
{
namespace ublas = ::boost::numeric::ublas;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<BMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<QMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<RMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<SMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<EMatrixExprT>::value_type,
typename ublas::matrix_traits<XMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
X = solver.solution();
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_SOLVER_DARE_HPP
<file_sep>/**
* \file dcs/control/analysis/observability.hpp
*
* \brief Observability for a state-space system.
*
* A system is said to be observable if any initial state \f$x(k_0)\f$ can be
* estimated from the control sequence \f$u(k)\f$, with
* \f$k=k_0,k_0+1,\ldots,k_f-1\f$, and the measurements \f$y(k)\f$, with
* \f$k=k_0,k_0+1,\ldots,k_f\f$.
*
* More specifically, given a continuous-time state-space system model:
* \f[
* \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t)+\mathbf{B}\mathbf{u}(t)
* \mathbf{y}(t) = \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f]
* or a discrete-time state-space system model:
* \f[
* \mathbf{x}(t) = \mathbf{A}\mathbf{x}(t-1)+\mathbf{B}\mathbf{u}(t-1)
* \mathbf{y}(t) = \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f]
* the following definitions apply [1]:
* - The system is said to be <em>completely observable</em> if every state
* \f$\mathbf{x}(t_0)\f$ can be determined from the observation of the output
* .
* vector \f$\mathbf{y}(t)\f$ over a finite time interval \f$f_0 \le t \le t_1\f$.
* The system is therefore completely observable if every transition of the
* state eventually affects every element of the output vectory.
* The concept of observability is useful in solving the problem of
* reconstructing unmeasurable state variables from measurable variables in the
* minimun possible length of time.
*
* Formally, system observability is defined in terms of the
* <em>observability matrix</em>.
*
* Given a continuous-time state-space system model:
* \f{align*}
* \dot{\mathbf{x}}(t) &= \mathbf{A}\mathbf{x}(t)+\mathbf{B}\mathbf{u}(t),\\
* \mathbf{y}(t) &= \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f}
* or a discrete-time state-space system model:
* \f{align*}
* \mathbf{x}(t) &= \mathbf{A}\mathbf{x}(t-1)+\mathbf{B}\mathbf{u}(t-1),\\
* \mathbf{y}(t) &= \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f}
* where:
* - \f$\mathbf{A}\f$ is a \f$n \times n}\f$ matrix,
* - \f$\mathbf{B}\f$ is a \f$n \times p}\f$ matrix,
* - \f$\mathbf{C}\f$ is a \f$m \times n}\f$ matrix,
* - \f$\mathbf{D}\f$ is a \f$m \times p}\f$ matrix.
* .
* We define the <em>observability matrix</em> as the following
* \f$nm \times n\f$ matrix:
* \f[
* \begin{pmatrix}
* \mathbf{C} \\
* \mathbf{C}\mathbf{A} \\
* \cdots \\
* \mathbf{B}\mathbf{A}^{n-1}
* \end{pmatrix}
* \f]
* Then, we say that a system is <em>complete observable</em> (or simply
* \e observable) if and only if the associated observability matrix is of
* rank \f$n\f$.
*
* A weaker concept of observability is \e detectability (a concept which is
* dual to the one of stabilizability): for a partially observable system, if
* the unobservable modes are stable and the observable modes are unstable, the
* system is said to be detectable.
*
* \note
* Computing the rank of the observability matrix is not recommended for
* observability testing.
* Indeed, the resulting observability matrix will be numerically singular for
* most systems with more than a handful of states.
* This fact is well documented in the control literature.
* For example, see section III in [2].
*
* References:
* -# <NAME>, <em>Modern Control Engineering</em>, 4th edition, Prentice Hall, 2010.
* -# <NAME>, <em>Properties of Numerival Algorithms Related to Computing Controllability</em>, IEEE Transactions on Automatic Control, 26(1), 1981.
* [http://lawww.epfl.ch/webdav/site/la/users/105941/public/NumCompCtrl.pdf]
* .
*
* \todo
* It might be a good idea to add an additional parameter to the function for
* checking observability, representing the tolerance with which estimating
* the rank of the observability matrix. However, this may be a problem if we
* change in the future the way we check for observability. As a matter of
* fact, there are several ways for checking the observability of a system.
* For instance, in Octave, observability is determined by applying Arnoldi
* iteration with complete re-orthogonalization to obtain an orthogonal basis
* of the Krylov subspace.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_ANALYSIS_OBSERVABILITY_HPP
#define DCS_CONTROL_ANALYSIS_OBSERVABILITY_HPP
#include <algorithm>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
namespace dcs { namespace control {
/**
* \brief Type traits for building the type of the observability matrix given
* the type of the state and the input matrices.
*
* \tparam AMatrixT The type of the state matrix for a state-space system model.
* \tparam BMatrixT The type of the input matrix for a state-space system model.
*/
template <
typename AMatrixT,
typename CMatrixT
>
struct observability_matrix_traits
{
/// The type of the observability matrix.
typedef typename ::boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type type;
};
/**
* \brief Compute the observability matrix.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space system
* model.
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \return The observability matrix.
*/
template <
typename AMatrixT,
typename CMatrixT
>
typename observability_matrix_traits<
AMatrixT,
CMatrixT
>::type make_observability_matrix(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename observability_matrix_traits<AMatrixT,CMatrixT>::type matrix_type;
typedef typename ublas::matrix_traits<matrix_type>::value_type value_type;
typedef typename ublas::matrix_traits<matrix_type>::size_type size_type;
size_type m = ublasx::num_rows(C);
size_type n = ublasx::num_columns(C);
// [C C*A C*A^2 ... C*A^{n-1}]
matrix_type O = ublas::zero_matrix<value_type>(n*m, n);
ublas::subrange(O, 0, m, 0, n) = C;
for (size_type k = 1; k < n; ++k)
{
size_type km = k*m;
// O[k*m+1:(k+1)*m,:] = A*O[(k-1)*m+1:k*m,:]
ublas::subrange(O, km, km+m, 0, n) = ublas::prod(ublas::subrange(O, km-m, km, 0, n), A);
}
return O;
}
/**
* \brief Test if a system is complete observable.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam CMatrixT The type of the output matrix for the state-space system
* model.
* \param A The state matrix for the state-space system model.
* \param C The output matrix for the state-space system model.
* \return \c true if the state-space system \f$(\mathbf{A},\mathbf{C})\f$ is
* complete observable; \c false otherwise.
*/
template <
typename AMatrixT,
typename CMatrixT
>
bool is_observable(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C)
{
return ::boost::numeric::ublasx::rank(
make_observability_matrix(A, C)
)
==
::boost::numeric::ublasx::num_columns(C);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_ANALYSIS_OBSERVABILITY_HPP
<file_sep>/**
* \file dcs/control/design/linear_mpc.hpp
*
* \brief Linear Model Predictive Control
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2015 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_DESIGN_LINEAR_MPC_HPP
#define DCS_CONTROL_DESIGN_LINEAR_MPC_HPP
#include <algorithm>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/empty.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/pow.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <cmath>
#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/control/solver/qp.hpp>
#include <dcs/exception.hpp>
#include <dcs/macro.hpp>
#include <stdexcept>
namespace dcs { namespace control {
/**
* \brief Model Predictive Control (MPC) for linear systems (Maciejowski,2000).
*
* The linear Model Predictive Control (MPC) framework can be stated as follows.
* Given a linear time-invariant (LTI) system:
* \f[
* x(k+1) = Ax(k) + Bu(k),\\
* y(k) = Cx(k).
* \f]
* the MPC controller finds the best sequence of control actions \f$u(k|k),\ldots,u(k+H_c-1|k)\f$ by solving the following optimization problem:
* \f{align}
* \text{minimize} \quad J(k) =\sum_{i=1}^{H_p} \lVert y(k+i|k)-y_{\text{ref}}(k+i) \rVert^2_{W_y(i)} + \sum_{i=0}^{H_c-1} \lVert \Delta u(k+i|k) \rVert^2_{W_{\Delta u}(i)},\\
* \text{subject to} \quad y_{\text{min}} \le y \ge y_{\text{max}},\\
* \quad \Delta y_{\text{min}} \ge \Delta y \le \Delta y_{\text{max}},\\
* \quad u_{\text{min}} \le u \ge u_{\text{max}},\\
* \quad \Delta u_{\text{min}} \le \Delta u \ge \Delta u_{\text{max}}.
* \f}
* with initial condition:
* \f[
* u(k-1|k) = u(k-1),\\
* x(k|k) = x(k).
* \f]
* where:
* - The notation \f$\lVert x \rVert^2_Q\f$ represents the quadratic form \f$x^T Q x\f$, where \f$x\f$ is a vector and \f$Q\f$ is a symmetric matrix.
* - \f$H_p\f$ is the prediction horizon
* - \f$H_c\f$ is the control horizon
* - \f$x(k+1|k),u(k+1|k),y(k+i|k)\f$ are the predicted system state, system input and system output at the \f$(k+i)\f$-th prediction horizon step, respectively, which are based on measurements up to time \f$k\f$. Note that \f$u(k-1|k)=u(k-1)\f$.
* Note, we always assume that \f$H_c \le H_p\f$ and that \f$\Delta u(k+i|k)=0\f$ for \f$i \ge H_c\f$, so that \f$u(k+i|k)=u(k+H_c-1|k)\f$ for all \f$i \ge H_c\f$.
*
* \note Soft constraints and manipulated variable tracking are not supported yet.
*
* References
* -# <NAME>. "Predictive Control with Constraints," Prentice-Hall, 2000.
* .
*
* \author <NAME> (<EMAIL>)
*/
template <typename RealT>
class linear_mpc_controller
{
public: typedef RealT real_type;
public: typedef boost::numeric::ublas::matrix<real_type, boost::numeric::ublas::column_major> matrix_type;
public: typedef boost::numeric::ublas::vector<real_type> vector_type;
public: linear_mpc_controller()
{
}
public: template <typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT>
linear_mpc_controller(boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc)
: Wy_(Wy),
Wdu_(Wdu),
ymin_(ymin),
ymax_(ymax),
dymin_(dymin),
dymax_(dymax),
umin_(umin),
umax_(umax),
dumin_(dumin),
dumax_(dumax),
Hp_(Hp),
Hc_(Hc)
{
namespace ublasx = boost::numeric::ublasx;
const std::size_t ny = ublasx::size(ymin);
const std::size_t nu = ublasx::size(umin);
// pre: Hc_ > 0
DCS_ASSERT(Hc_ > 0,
DCS_EXCEPTION_THROW(std::invalid_argument, "Control horizon cannot be zero"));
// pre: Hp_ >= Hc_
DCS_ASSERT(Hp_ >= Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Prediction horizon cannot be less than control horizon"));
// pre: num_rows(Wy_) >= ny
DCS_ASSERT(ublasx::num_rows(Wy_) >= ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for output weight matrix Wy"));
// pre: num_rows(Wy_) <= ny*Hp_
DCS_ASSERT(ublasx::num_rows(Wy_) <= ny*Hp_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many rows for output weight matrix Wy"));
// pre: num_columns(Wy_) >= ny
DCS_ASSERT(ublasx::num_columns(Wy_) >= ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few columns for output weight matrix Wy"));
// pre: num_columns(Wy_) <= ny*Hp_
DCS_ASSERT(ublasx::num_columns(Wy_) <= ny*Hp_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many columns for output weight matrix Wy"));
// pre: num_rows(Wdu_) >= nu_
DCS_ASSERT(ublasx::num_rows(Wdu_) >= nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for manipulated variable weight matrix Wdu"));
// pre: num_rows(Wdu_) <= nu*Hc_
DCS_ASSERT(ublasx::num_rows(Wdu_) <= nu*Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many rows for manipulated variable weight matrix Wdu"));
// pre: num_columns(Wdu_) >= nu
DCS_ASSERT(ublasx::num_columns(Wdu_) >= nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few columns for manipulated variable weight matrix Wdu"));
// pre: num_columns(Wdu_) <= nu*Hc_
DCS_ASSERT(ublasx::num_columns(Wdu_) <= nu*Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many columns for manipulated variable weight matrix Wdu"));
// pre: size(ymin) == size(ymax)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(ymax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and ymax have incompatible size"));
// pre: size(ymin) == size(dymin)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(dymin),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and dymin have incompatible size"));
// pre: size(ymin) == size(dymax)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(dymax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and dymax have incompatible size"));
// pre: size(umin) == size(umax)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(umax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and umax have incompatible size"));
// pre: size(umin) == size(dumin)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(dumin),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and dumin have incompatible size"));
// pre: size(umin) == size(dumax)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(dumax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and dumax have incompatible size"));
}
public: void reset()
{
Wy_.clear();
Wdu_.clear();
ymin_.clear();
ymax_.clear();
dymin_.clear();
dymax_.clear();
umin_.clear();
umax_.clear();
dumin_.clear();
dumax_.clear();
Hp_ = 0;
Hc_ = 0;
A_.clear();
B_.clear();
C_.clear();
Ae_.clear();
Be_.clear();
Ce_.clear();
Iu_.clear();
Ru_.clear();
Rx_.clear();
dRx_.clear();
Rx1_.clear();
umax1_.clear();
umin1_.clear();
dumax1_.clear();
dumin1_.clear();
ymax1_.clear();
ymin1_.clear();
dymax1_.clear();
dymin1_.clear();
H_.clear();
Alpha_.clear();
Xopt_.clear();
Uopt_.clear();
Yopt_.clear();
}
public: template <typename AMatrixT,
typename BMatrixT,
typename CMatrixT>
void solve(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A);
const std::size_t nu = ublasx::num_columns(B);
const std::size_t ny = ublasx::num_rows(C);
// pre: A is a square matrix
DCS_ASSERT(nx == ublasx::num_columns(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A must be square"));
// pre: num_rows(B) == num_rows(A)
DCS_ASSERT(nx == ublasx::num_rows(B),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix B has a wrong number of rows"));
// pre: num_columns(C) == num_rows(A)
DCS_ASSERT(nx == ublasx::num_columns(C),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix C has a wrong number of columns"));
// pre: num_rows(C) == ny
DCS_ASSERT(ny == ublasx::num_rows(C),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix C has a wrong number of rows"));
A_ = A;
B_ = B;
C_ = C;
if (ublasx::empty(Wy_))
{
Wy_ = ublas::identity_matrix<real_type>(ny);
}
if (ublasx::empty(Wdu_))
{
Wdu_= ublas::zero_matrix<real_type>(nu);
}
// if (ublasx::empty(Wdu_))
// {
// Wdu_= ublas::zero_matrix<real_type>(nu);
// }
if (ublasx::empty(umin_))
{
umin_= ublas::scalar_vector<real_type>(nu, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(umax_))
{
umax_= ublas::scalar_vector<real_type>(nu, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dumin_))
{
dumin_= ublas::scalar_vector<real_type>(nu, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dumax_))
{
dumax_= ublas::scalar_vector<real_type>(nu, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(ymin_))
{
ymin_= ublas::scalar_vector<real_type>(ny, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(ymax_))
{
ymax_= ublas::scalar_vector<real_type>(ny, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dymin_))
{
dymin_= ublas::scalar_vector<real_type>(ny, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dymax_))
{
dymax_= ublas::scalar_vector<real_type>(ny, +std::numeric_limits<real_type>::infinity());
}
// Spans the weighting matrices over the horizons
if (ublasx::num_rows(Wdu_) == nu)
{
ublas::matrix<real_type> WduHc = ublas::zero_matrix<real_type>(nu*Hc_);
for (std::size_t i = 0; i < Hc_; ++i)
{
const std::size_t i0 = i*nu;
const std::size_t i1 = i0+nu;
ublas::subrange(WduHc, i0, i1, i0, i1) = Wdu_;
}
Wdu_ = WduHc;
}
if (ublasx::num_rows(Wy_) == ny)
{
ublas::matrix<real_type> WyHp = ublas::zero_matrix<real_type>(ny*Hp_);
for (std::size_t i = 0; i < Hp_; ++i)
{
const std::size_t i0 = i*ny;
const std::size_t i1 = i0+ny;
ublas::subrange(WyHp, i0, i1, i0, i1) = Wy_;
}
Wy_ = WyHp;
}
// Forms the augmented system
Ae_ = ublasx::cat_columns(ublasx::cat_rows(A_, B_),
ublasx::cat_rows(ublas::zero_matrix<real_type>(nu, nx),
ublas::identity_matrix<real_type>(nu)));
Be_ = ublasx::cat_columns(B_, ublas::identity_matrix<real_type>(nu));
Ce_ = ublasx::cat_rows(C_, ublas::zero_matrix<real_type>(ny, nu));
const std::size_t nxe = ublasx::num_rows(Ae_);
const std::size_t nue = ublasx::num_columns(Be_);
const std::size_t nye = ublasx::num_rows(Ce_);
// Auxiliary variables
ublas::matrix<real_type> RRR = ublas::zero_matrix<real_type>(nye*Hp_, nue);
for (std::size_t i = 0; i < Hp_; ++i)
{
const std::size_t r0 = i*nye;
const std::size_t r1 = r0 + nye;
ublas::matrix<real_type> tmp1 = ublas::prod(Ce_, ublasx::pow(Ae_, i));
ublas::subrange(RRR, r0, r1, 0, nue) = ublas::prod(tmp1, Be_);
}
// Constructs the Ru and Rx matrices
Ru_ = ublas::matrix<real_type>(nye*Hp_, nue*Hc_, 0);
for (std::size_t i = 0; i < Hc_; ++i)
{
ublas::matrix<real_type> tmp = ublasx::cat_columns(ublas::zero_matrix<real_type>(i*nye, nue), ublas::subrange(RRR, 0, nye*(Hp_-i), 0, nue));
ublas::subrange(Ru_, 0, nye*Hp_, i*nue, (i+1)*nue) = ublasx::cat_columns(ublas::zero_matrix<real_type>(i*nye, nue), ublas::subrange(RRR, 0, nye*(Hp_-i), 0, nue));
}
Rx_ = ublas::zero_matrix<real_type>(nye*Hp_, nxe);
for (std::size_t i = 0; i < Hp_; ++i)
{
const std::size_t r0 = i*nye;
const std::size_t r1 = r0 + nye;
ublas::subrange(Rx_, r0, r1, 0, nxe) = ublas::prod(Ce_, ublasx::pow(Ae_, i));
}
// Auxiliary matrix
// FIXME: RRR already contains part of info that is computed in the following loop
//RRR = ublas::zero_matrix<real_type>(nye*Hp_, nue);
//for (std::size_t i = 0; i < Hp_; ++i)
//{
// ublas::subrange(RRR, i*nye, i*nye+nye, 0, nue) = ublas::prod(ublas::prod(Ce_, ublasx::pow(Ae_, i)), Be_);
// if (i > 0)
// {
// ublas::subrange(RRR, i*nye, i*nye+nye, 0, nue) -= ublas::prod(ublas::prod(Ce_, ublasx::pow(Ae_, i-1)), Be_);
// }
//}
RRR.resize((Hp_+2)*nye, nue);
for (std::size_t i = 1; i < (Hp_+2); ++i)
{
const std::size_t r0 = i*nye;
const std::size_t r1 = r0 + nye;
if (i >= Hp_)
{
ublas::matrix<real_type> tmp1 = ublas::prod(Ce_, ublasx::pow(Ae_, i));
ublas::subrange(RRR, r0, r1, 0, nue) = ublas::prod(tmp1, Be_);
}
//ublas::subrange(RRR, r0, r1, 0, nue) -= ublas::prod(ublas::prod(Ce_, ublasx::pow(Ae_, i-1)), Be_);
ublas::matrix<real_type> tmp1 = ublas::prod(Ce_, ublasx::pow(Ae_, i-1));
ublas::subrange(RRR, r0, r1, 0, nue) -= ublas::prod(tmp1, Be_);
}
// Constructs the dRu, dRx, dRu1, and dRx1 matrices for delta y constraints
//ublas::matrix<real_type> dRu(ublasx::num_rows(RRR), ublasx::num_columns(RRR)*Hc_);
ublas::matrix<real_type> dRu(ublasx::num_rows(RRR)-2*nye, ublasx::num_columns(RRR)*Hc_);
ublas::subrange(dRu, 0, ublasx::num_rows(dRu), 0, ublasx::num_columns(RRR)) = ublas::subrange(RRR, 2*nye, ublasx::num_rows(RRR), 0, ublasx::num_columns(RRR));
if (Hc_ > 1)
{
const std::size_t r0 = nye;
const std::size_t r1 = ublasx::num_rows(RRR)-nye;
const std::size_t c0 = ublasx::num_columns(RRR);
const std::size_t c1 = c0 + ublasx::num_columns(RRR);
ublas::subrange(dRu, 0, ublasx::num_rows(dRu), c0, c1) = ublas::subrange(RRR, r0, r1, 0, c0);
}
for (std::size_t i = 2; i < Hc_; ++i)
{
//const std::size_t c0 = 2*(i+1)*ublasx::num_columns(RRR);
const std::size_t c0 = i*ublasx::num_columns(RRR);
const std::size_t c1 = c0 + ublasx::num_columns(RRR);
//if (i > 2)
//{
// ublas::subrange(dRu, 0, ublasx::num_rows(dRu), c0, c1) = ublasx::cat_columns(ublas::zero_matrix<real_type>((i-2)*nye, nue), ublas::subrange(RRR, 0, nye*(Hp_+2-i), 0, ublasx::num_columns(RRR)));
//}
//else
//{
// ublas::subrange(dRu, 0, ublasx::num_rows(dRu), c0, c1) = ublas::subrange(RRR, 0, nye*(Hp_+2-i), 0, ublasx::num_columns(RRR));
//}
ublas::subrange(dRu, 0, ublasx::num_rows(dRu), c0, c1) = ublasx::cat_columns(ublas::zero_matrix<real_type>((i-2)*nye, nue), ublas::subrange(RRR, 0, nye*(Hp_+2-i), 0, ublasx::num_columns(RRR)));
}
dRx_ = ublas::matrix<real_type>(nye*Hp_, nxe, 0);
ublas::subrange(dRx_, 0, nye, 0, nxe) = ublas::prod(Ce_, Ae_) - Ce_;
for (std::size_t i = 0; i < (Hp_-1); ++i)
{
const std::size_t r0 = (i+1)*nye;
const std::size_t r1 = r0 + nye;
ublas::subrange(dRx_, r0, r1, 0, nxe) = ublas::prod(Ce_, ublasx::pow(Ae_, i+1)) - ublas::prod(Ce_, ublasx::pow(Ae_, i));
}
ublas::matrix<real_type> Ru1 = ublas::subrange(Ru_, 0, nye, 0, ublasx::num_columns(Ru_));
Rx1_ = ublas::subrange(Rx_, 0, nye, 0, ublasx::num_columns(Rx_));
// $I_u$ matrix
Iu_ = ublas::matrix<real_type>(nue*Hc_, nue, 0);
for (std::size_t i = 0; i < Hc_; ++i)
{
const std::size_t r0 = i*nue;
const std::size_t r1 = r0 + nue;
ublas::subrange(Iu_, r0, r1, 0, nue) = ublas::identity_matrix<real_type>(nue);
}
// $I_{\Delta u}$ matrix
ublas::matrix<real_type> Idu = ublas::zero_matrix<real_type>(nue*Hc_);
for (std::size_t i = 0; i < Hc_; ++i)
{
const std::size_t r0 = i*nue;
const std::size_t r1 = r0 + nue;
for (std::size_t j = 0; j <= i; ++j)
{
const std::size_t c0 = j*nue;
const std::size_t c1 = c0 + nue;
ublas::subrange(Idu, r0, r1, c0, c1) = ublas::identity_matrix<real_type>(nue);
}
}
// Additional variables needed for constraint handling
ublas::matrix<real_type> Hp1 = ublas::scalar_matrix<real_type>(1, Hp_, 1.0);
ublas::matrix<real_type> Hc1 = ublas::scalar_matrix<real_type>(1, Hc_, 1.0);
ublas::matrix<real_type> ImHc = ublas::identity_matrix<real_type>(Hc_*nue);
umax1_ = ublas::vector<real_type>(nu*Hc_);
umin1_ = ublas::vector<real_type>(nu*Hc_);
dumax1_ = ublas::vector<real_type>(nu*Hc_);
dumin1_ = ublas::vector<real_type>(nu*Hc_);
for (std::size_t i = 0; i < Hc_; ++i)
{
const std::size_t i0 = i*nu;
const std::size_t i1 = i0 + nu;
ublas::subrange(umax1_, i0, i1) = umax_;
ublas::subrange(umin1_, i0, i1) = umin_;
ublas::subrange(dumax1_, i0, i1) = dumax_;
ublas::subrange(dumin1_, i0, i1) = dumin_;
}
ymax1_ = ublas::vector<real_type>(ny*Hp_, 0);
ymin1_ = ublas::vector<real_type>(ny*Hp_, 0);
dymax1_ = ublas::vector<real_type>(ny*Hp_, 0);
dymin1_ = ublas::vector<real_type>(ny*Hp_, 0);
for (std::size_t i = 0; i < Hp_; ++i)
{
const std::size_t i0 = i*ny;
const std::size_t i1 = i0 + ny;
ublas::subrange(ymax1_, i0, i1) = ymax_;
ublas::subrange(ymin1_, i0, i1) = ymin_;
ublas::subrange(dymax1_, i0, i1) = dymax_;
ublas::subrange(dymin1_, i0, i1) = dymin_;
}
// $\Alpha$ matrix
Alpha_ = ublas::matrix<real_type>(ublasx::num_rows(Idu)*2 + ublasx::num_rows(ImHc)*2 + ublasx::num_rows(Ru_)*2 + ublasx::num_rows(Ru1)*2 + ublasx::num_rows(dRu)*2, ublasx::num_columns(Idu), 0);
{
std::size_t r0 = 0;
std::size_t r1 = ublasx::num_rows(Idu);
std::size_t c0 = 0;
std::size_t c1 = ublasx::num_columns(Idu);
ublas::subrange(Alpha_, r0, r1, c0, c1) = Idu;
r0 = r1;
r1 = r0 + ublasx::num_rows(Idu);
ublas::subrange(Alpha_, r0, r1, c0, c1) = -Idu;
r0 = r1;
r1 = r0 + ublasx::num_rows(ImHc);
ublas::subrange(Alpha_, r0, r1, c0, c1) = ImHc;
r0 = r1;
r1 = r0 + ublasx::num_rows(ImHc);
ublas::subrange(Alpha_, r0, r1, c0, c1) = -ImHc;
r0 = r1;
r1 = r0 + ublasx::num_rows(Ru_);
ublas::subrange(Alpha_, r0, r1, c0, c1) = Ru_;
r0 = r1;
r1 = r0 + ublasx::num_rows(Ru_);
ublas::subrange(Alpha_, r0, r1, c0, c1) = -Ru_;
r0 = r1;
r1 = r0 + ublasx::num_rows(Ru1);
ublas::subrange(Alpha_, r0, r1, c0, c1) = Ru1;
r0 = r1;
r1 = r0 + ublasx::num_rows(dRu);
ublas::subrange(Alpha_, r0, r1, c0, c1) = dRu;
r0 = r1;
r1 = r0 + ublasx::num_rows(Ru1);
ublas::subrange(Alpha_, r0, r1, c0, c1) = -Ru1;
r0 = r1;
r1 = r0 + ublasx::num_rows(dRu);
ublas::subrange(Alpha_, r0, r1, c0, c1) = -dRu;
}
// $H$ matrix
//ublas::matrix<real_type> H = 2*(ublas::prod(ublas::prod(ublas::trans(Ru), Wy_), Ru) + Wdu_);
{
ublas::matrix<real_type> tmp1 = ublas::prod(ublas::trans(Ru_), Wy_);
H_ = 2*(ublas::prod(tmp1, Ru_) + Wdu_);
}
}
public: template <typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
vector_type control(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A_);
const std::size_t nu = ublasx::num_columns(B_);
const std::size_t ny = ublasx::num_rows(C_);
DCS_ASSERT(ublasx::size(x) == nx,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector x"));
DCS_ASSERT(ublasx::size(u) == nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector u"));
DCS_ASSERT(ublasx::num_columns(Yref) == ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad number of columns for matrix Yref"));
//if (ublasx::num_rows(Yref) < Hp_)
DCS_ASSERT(ublasx::num_rows(Yref) > 0,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for matrix Yref"));
const std::size_t nxe = ublasx::num_rows(Ae_);
const std::size_t nue = ublasx::num_columns(Be_);
ublas::vector<real_type> xe(nxe, 0);
ublas::subrange(xe, 0, nx) = x;
ublas::subrange(xe, nx, nxe) = u;
ublas::vector<real_type> ye = ublas::prod(ublas::prod(Ce_, Ae_), xe);
// Main simulation loop
Uopt_ = ublas::zero_matrix<real_type>(Hp_, nu);
Xopt_ = ublas::zero_matrix<real_type>(Hp_+1, nx);
ublas::row(Xopt_, 0) = x;
Yopt_ = ublas::zero_matrix<real_type>(Hp_+1, ny);
ublas::row(Yopt_, 0) = ublas::prod(C_, x);
ublas::vector<real_type> uu = u;
ublas::vector<real_type> w(ny*Hp_);
for (std::size_t j = 0; j < Hp_; ++j)
{
ublas::subrange(w, j*ny, (j+1)*ny) = ublas::row(Yref(), std::min(j, ublasx::num_rows(Yref)-1));
}
// $\omega$ vector
ublas::vector<real_type> omega(ublasx::size(umax1_)*4+ublasx::size(dymax_)*2+ublasx::size(ymax1_)*4, 0);
{
std::size_t r0 = 0;
std::size_t r1 = ublasx::size(umax1_);
ublas::subrange(omega, r0, r1) = umax1_ - ublas::prod(Iu_, uu);
r0 = r1;
r1 = r0 + ublasx::size(umin1_);
ublas::subrange(omega, r0, r1) = -umin1_ + ublas::prod(Iu_, uu);
r0 = r1;
r1 = r0 + ublasx::size(dumax1_);
ublas::subrange(omega, r0, r1) = dumax1_;
r0 = r1;
r1 = r0 + ublasx::size(dumin1_);
ublas::subrange(omega, r0, r1) = -dumin1_;
r0 = r1;
r1 = r0 + ublasx::size(ymax1_);
ublas::subrange(omega, r0, r1) = ymax1_ - ublas::prod(ublas::prod(Rx_, Ae_), xe);
r0 = r1;
r1 = r0 + ublasx::size(ymin1_);
ublas::subrange(omega, r0, r1) = -ymin1_ + ublas::prod(ublas::prod(Rx_, Ae_), xe);
r0 = r1;
r1 = r0 + ublasx::size(dymax_);
ublas::subrange(omega, r0, r1) = dymax_ - ublas::prod(ublas::prod(Rx1_, Ae_), xe) + ye;
r0 = r1;
r1 = r0 + ublasx::size(dymax1_);
ublas::subrange(omega, r0, r1) = dymax1_ - ublas::prod(ublas::prod(dRx_, Ae_), xe);
r0 = r1;
r1 = r0 + ublasx::size(dymin_);
ublas::subrange(omega, r0, r1) = -dymin_ + ublas::prod(ublas::prod(Rx1_, Ae_), xe) - ye;
r0 = r1;
r1 = r0 + ublasx::size(dymax1_);
ublas::subrange(omega, r0, r1) = -dymin1_ + ublas::prod(ublas::prod(dRx_, Ae_), xe);
}
// $c$ vector
ublas::vector<real_type> c = 2*(ublas::prod(ublas::prod(ublas::trans(Ru_), ublas::trans(Wy_)), ublas::prod(ublas::prod(Rx_, Ae_), xe) - w));
// Computes the control output
//DCS_DEBUG_TRACE("H: " << H_);//XXX
//DCS_DEBUG_TRACE("c: " << c);//XXX
//DCS_DEBUG_TRACE("Alpha: " << Alpha_);//XXX
//DCS_DEBUG_TRACE("Omega: " << omega);//XXX
ublas::vector<real_type> du_opt = qp_solve<real_type>(H_, c, Alpha_, omega);
//DCS_DEBUG_TRACE("dU*: " << du_opt);//XXX
// Integrates u
for (std::size_t k = 0; k < Hp_; ++k)
{
ublas::vector<real_type> du = (k < Hc_) ? ublas::subrange(du_opt, k*nue, (k+1)*nue) : ublas::subrange(du_opt, (Hc_-1)*nue, Hc_*nue);
uu += du;
ublas::row(Uopt_, k) = uu;
xe = ublas::prod(Ae_, xe) + ublas::prod(Be_, du);
ye = ublas::prod(Ce_, xe);
ublas::row(Xopt_, k+1) = ublas::prod(A_, ublas::row(Xopt_,k)) + ublas::prod(B_, uu);
ublas::row(Yopt_, k+1) = ublas::prod(C_, ublas::row(Xopt_,k+1));
}
//DCS_DEBUG_TRACE("CONTROL -- predicted X: " << Xopt_);//XXX
//DCS_DEBUG_TRACE("CONTROL -- optimal U: " << Uopt_);//XXX
//DCS_DEBUG_TRACE("CONTROL -- predicted Y: " << Yopt_);//XXX
return ublas::row(Uopt_, 0);
}
public: template <typename XVectorT,
typename UVectorT,
typename YRefVectorT>
vector_type control(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::vector_expression<YRefVectorT> const& yref)
{
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
matrix_type Yref(Hp_, boost::numeric::ublasx::size(yref));
for (std::size_t i = 0; i < Hp_; ++i)
{
ublas::row(Yref, i) = yref;
}
return this->control(x, u, Yref);
}
// Mimics the MATLAB's sim function
public: template <typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
matrix_type simulate(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A_);
const std::size_t nu = ublasx::num_columns(B_);
const std::size_t ny = ublasx::num_rows(C_);
const std::size_t nsim = ublasx::num_rows(Yref);
if (ublasx::size(x) != nx)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector x");
}
if (ublasx::size(u) != nu)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector u");
}
if (ublasx::num_columns(Yref) != ny)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad number of columns for matrix Yref");
}
//if (ublasx::num_rows(Yref) < Hp_)
//{
// DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for matrix Yref");
//}
ublas::vector<real_type> xx = x;
ublas::vector<real_type> uu = u;
ublas::matrix<real_type> U(nsim, nu, 0);
#ifdef DCS_DEBUG
ublas::matrix<real_type> X(nsim, nx, 0);//XXX
ublas::matrix<real_type> Y(nsim, ny, 0);//XXX
#endif // DCS_DEBUG
for (std::size_t k = 0; k < nsim; ++k)
{
this->control(xx, uu, ublas::row(Yref(), k));
xx = ublas::row(Xopt_, 1);
uu = ublas::row(Uopt_, 0);
ublas::row(U, k) = uu;
#ifdef DCS_DEBUG
//ublas::row(X, k) = xx; //XXX
//ublas::row(Y, k) = ublas::row(Yopt_, 1); //XXX
ublas::row(X, k) = ublas::row(Xopt_, 0); //XXX
ublas::row(Y, k) = ublas::row(Yopt_, 0); //XXX
#endif // DCS_DEBUG
}
//DCS_DEBUG_TRACE("SIMULATION -- Yref: " << Yref);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- X: " << X);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- U: " << U);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- Y: " << Y);//XXX
return U;
}
public: matrix_type Wy() const
{
return Wy_;
}
public: matrix_type Wdu() const
{
return Wdu_;
}
public: vector_type ymin() const
{
return ymin_;
}
public: vector_type ymax() const
{
return ymax_;
}
public: vector_type dymin() const
{
return dymin_;
}
public: vector_type dymax() const
{
return dymax_;
}
public: vector_type umin() const
{
return umin_;
}
public: vector_type umax() const
{
return umax_;
}
public: vector_type dumin() const
{
return dumin_;
}
public: vector_type dumax() const
{
return dumax_;
}
public: std::size_t prediction_horizon() const
{
return Hp_;
}
public: std::size_t control_horizon() const
{
return Hc_;
}
public: matrix_type predicted_states() const
{
return Xopt_;
}
public: matrix_type predicted_outputs() const
{
return Yopt_;
}
public: matrix_type optimal_inputs() const
{
return Uopt_;
}
//TODO: we need to collect the objective values of the QP problem during each iteration in the control method
// private: real_type cost() const
// {
// return J_;
// }
private: matrix_type Wy_; ///< Weight matrix for the output variables
private: matrix_type Wdu_; ///< Weight matrix for the manipulated variable adjustments (moves)
private: vector_type ymin_; ///< Contraint vector definining the lower bounds of the output variables
private: vector_type ymax_; ///< Contraint vector definining the upper bounds of the output variables
private: vector_type dymin_; ///< Contraint vector definining the lower bounds of the manipulated variable adjustments
private: vector_type dymax_; ///< Contraint vector definining the upper bounds of the manipulated variable adjustments
private: vector_type umin_; ///< Contraint vector definining the lower bounds of the manipulated variables
private: vector_type umax_; ///< Contraint vector definining the upper bounds of the manipulated variables
private: vector_type dumin_; ///< Contraint vector definining the lower bounds of the manipulated variable adjustments
private: vector_type dumax_; ///< Contraint vector definining the upper bounds of the manipulated variable adjustments
private: std::size_t Hp_; ///< Prediction horizon
private: std::size_t Hc_; ///< Control horizon
private: matrix_type A_; ///< The state matrix of the linear system
private: matrix_type B_; ///< The input matrix of the linear system
private: matrix_type C_; ///< The output matrix of the linear system
private: matrix_type Ae_; ///< The state matrix of the extended linear system
private: matrix_type Be_; ///< The input matrix of the extended linear system
private: matrix_type Ce_; ///< The output matrix of the extended linear system
private: matrix_type Iu_;
private: matrix_type Ru_;
private: matrix_type Rx_;
private: matrix_type dRx_;
private: matrix_type Rx1_;
private: vector_type umax1_;
private: vector_type umin1_;
private: vector_type dumax1_;
private: vector_type dumin1_;
private: vector_type ymax1_;
private: vector_type ymin1_;
private: vector_type dymax1_;
private: vector_type dymin1_;
private: matrix_type H_;
private: matrix_type Alpha_;
private: matrix_type Xopt_;
private: matrix_type Uopt_;
private: matrix_type Yopt_;
//private: real_type J_;
}; // linear_mpc_controller
template <typename RealT,
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT,
typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
boost::numeric::ublas::vector<RealT> linear_mpc(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc,
boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
linear_mpc_controller<RealT> lmpc(Wy, Wdu, ymin, ymax, dymin, dymax, umin, umax, dumin, dumax, Hp, Hc);
lmpc.solve(A, B, C);
return lmpc.control(x, u, Yref);
}
template <typename RealT,
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT,
typename XVectorT,
typename UVectorT,
typename YRefVectorT>
boost::numeric::ublas::vector<RealT> linear_mpc(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc,
boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::vector_expression<YRefVectorT> const& yref)
{
linear_mpc_controller<RealT> lmpc(Wy, Wdu, ymin, ymax, dymin, dymax, umin, umax, dumin, dumax, Hp, Hc);
lmpc.solve(A, B, C);
return lmpc.control(x, u, yref);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_DESIGN_LINEAR_MPC_HPP
<file_sep>#ifndef DCS_CONTROL_TEST_UTILITY_HPP
#define DCS_CONTROL_TEST_UTILITY_HPP
namespace detail { namespace /*<unnamed>*/ {
template <typename T>
struct complex_cmp
{
bool operator()(::std::complex<T> const& a, ::std::complex<T> const& b) const
{
return a.real() < b.real() || (a.real() == b.real() && a.imag() < b.imag());
}
};
}} // Namespace detail::<unnamed>*/
#endif // DCS_CONTROL_TEST_UTILITY_HPP
<file_sep>/**
* \file test/src/dcs/control/dlqi.cpp
*
* \brief Test suite for DLQI controllers.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-control (below referred to as "this program").
*
* 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/>.
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <complex>
#include <cstddef>
#include <dcs/control/design/dlqi.hpp>
#include <dcs/test.hpp>
#include <iostream>
#include "./utility.hpp"
namespace ublas = boost::numeric::ublas;
namespace dcs_ctrl = dcs::control;
const double tol = 1.0e-5;
DCS_TEST_DEF( matlab_1 )
{
DCS_TEST_CASE("MATLAB #1");
typedef double real_type;
typedef real_type value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t nx(2);
const std::size_t nu(1);
const std::size_t ny(1);
const std::size_t nz(nx+1);
const real_type ts(1);
matrix_type A(nx,nx);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = -20; A(1,1) = -10;
matrix_type B(nx,nu);
B(0,0) = 0;
B(1,0) = 1;
matrix_type C(ny,nx);
C(0,0) = 1; C(0,1) = 0;
matrix_type D(ny,nu);
D(0,0) = 0;
matrix_type Q(ublas::identity_matrix<value_type>(nz,nz));
Q(nx,nx) = 2e+6;
matrix_type R(ublas::identity_matrix<value_type>(nu,nu));
matrix_type N(ublas::zero_matrix<value_type>(nz,nu));
matrix_type expect_K(nu,nz); // state-feedback optimal gain
expect_K(0,0) = -19.000136465758239; expect_K(0,1) = -9.000051490140352; expect_K(0,2) = -0.999853537170799;
matrix_type expect_S(nz,nz); // solution of the associated Riccati equation
expect_S(0,0) = 1e+6* 4.000863944497572; expect_S(0,1) = 1e+6* 2.000472969596359; expect_S(0,2) = 1e+6*-4.000482941768265;
expect_S(1,0) = 1e+6* 2.000472969596359; expect_S(1,1) = 1e+6* 2.000584980049262; expect_S(1,2) = 1e+6*-2.000292968566564;
expect_S(2,0) = 1e+6*-4.000482941768265; expect_S(2,1) = 1e+6*-2.000292968566564; expect_S(2,2) = 1e+6* 6.000502938839015;
vector_type expect_l(nz); // closed-loop eigenvalues
expect_l(0) = complex_value_type( 0.022873738558717,0);
expect_l(1) = complex_value_type(-0.011411124209185, 0.017516871011497);
expect_l(2) = complex_value_type(-0.011411124209185,-0.017516871011497);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqi_controller<value_type> dlqi(Q, R, N);
dlqi.solve(A, B, C, D, ts);
DCS_DEBUG_TRACE("Gain = " << dlqi.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqi.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqi.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqi.gain(), nu, nz, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqi.are_solution(), nz, nz, tol );
vector_type l(dlqi.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, nz, tol );
}
/*
DCS_TEST_DEF( free_func_ill_cond )
{
DCS_TEST_CASE("free function - ill-conditioned problem");
typedef double real_type;
typedef real_type value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<value_type> vector_type;
const std::size_t nx(6);
const std::size_t nu(6);
const std::size_t ny(1);
const real_type ts(896);
matrix_type A(nx,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 0; A(0,3) = 1; A(0,4) = 0; A(0,5) = 0;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0; A(1,3) = 0; A(1,4) = 1; A(1,5) = 0;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 0; A(2,3) = 0; A(2,4) = 0; A(2,5) = 1;
A(3,0) = -2.22045e-16; A(3,1) = -0; A(3,2) = -0; A(3,3) = -0.479283; A(3,4) = -0; A(3,5) = -0;
A(4,0) = -0; A(4,1) = -2.22045e-16; A(4,2) = -0; A(4,3) = -0; A(4,4) = -0.274798; A(4,5) = -0;
A(5,0) = -0; A(5,1) = -0; A(5,2) = -2.22045e-16; A(5,3) = -0; A(5,4) = -0; A(5,5) = 0.993379;
matrix_type B(nx,nu);
B(0,0) = 0; B(0,1) = 0; B(0,2) = 0; B(0,3) = 0; B(0,4) = 0; B(0,5) = 0;
B(1,0) = 0; B(1,1) = 0; B(1,2) = 0; B(1,3) = 0; B(1,4) = 0; B(1,5) = 0;
B(2,0) = 0; B(2,1) = 0; B(2,2) = 0; B(2,3) = 0; B(2,4) = 0; B(2,5) = 0;
B(3,0) = 2.22045e-16; B(3,1) = 2.22045e-16; B(3,2) = 2.22045e-16; B(3,3) = 2.22045e-16; B(3,4) = 2.22045e-16; B(3,5) = 2.22045e-16;
B(4,0) = 2.22045e-16; B(4,1) = 2.22045e-16; B(4,2) = 2.22045e-16; B(4,3) = 2.22045e-16; B(4,4) = 2.22045e-16; B(4,5) = 2.22045e-16;
B(5,0) = 2.22045e-16; B(5,1) = 2.22045e-16; B(5,2) = 2.22045e-16; B(5,3) = 2.22045e-16; B(5,4) = 2.22045e-16; B(5,5) = 2.22045e-16;
matrix_type C(ny,nx);
C(0,0) = 0; C(0,1) = 0; C(0,2) = 0; C(0,3) = 1; C(0,4) = 1; C(0,5) = 1;
matrix_type D(ny,nu);
D(0,0) = 0; D(0,1) = 0; D(0,2) = 0; D(0,3) = 0; D(0,4) = 0; D(0,5) = 0;
matrix_type Q = ublas::identity_matrix<value_type>(nx+1,nx+1);
matrix_type R = ublas::identity_matrix<value_type>(nu,nu);
matrix_type N = ublas::zero_matrix<value_type>(nx+1,nu);
matrix_type expect_K(nu,nx+1); // state-feedback optimal gain
expect_K(0,0) = - 1.0247564929914510514e-17;
expect_K(0,1) = - 1.1891333835485771088e-17;
expect_K(0,2) = - 2.2895406420567840299e-15;
expect_K(0,3) = 0.04615084747885873917;
expect_K(0,4) = 0.05355371134420310042;
expect_K(0,5) = 10.311156036192993923;
expect_K(0,6) = - 0.068270164114244455411;
expect_K(1,0) = 1.0247564929914510514e-17;
expect_K(1,1) = - 1.1891333835485771088e-17;
expect_K(1,2) = - 2.2895406420567840299e-15;
expect_K(1,3) = 0.04615084747885873917;
expect_K(1,4) = 0.05355371134420310042;
expect_K(1,5) = 10.311156036192993923;
expect_K(1,6) = - 0.068270164114244455411;
expect_K(2,0) = 1.0247564929914507432e-17;
expect_K(2,1) = - 1.1891333835485771088e-17;
expect_K(2,2) = - 2.289540642056783241e-15;
expect_K(2,3) = 0.046150847478858725292;
expect_K(2,4) = 0.05355371134420310042;
expect_K(2,5) = 10.311156036192993923;
expect_K(2,6) = - 0.068270164114244455411;
expect_K(3,0) = 1.0247564929914507432e-17;
expect_K(3,1) = - 1.1891333835485771088e-17;
expect_K(3,2) = - 2.289540642056783241e-15;
expect_K(3,3) = 0.046150847478858725292;
expect_K(3,4) = 0.05355371134420310042;
expect_K(3,5) = 10.311156036192993923;
expect_K(3,6) = - 0.068270164114244455411;
expect_K(4,0) = 1.0247564929914507432e-17;
expect_K(4,1) = - 1.1891333835485772629e-17;
expect_K(4,2) = - 2.289540642056783241e-15;
expect_K(4,3) = 0.046150847478858725292;
expect_K(4,4) = 0.05355371134420310042;
expect_K(4,5) = 10.311156036192993923;
expect_K(4,6) = - 0.068270164114244455411;
expect_K(5,0) = 1.0247564929914507432e-17;
expect_K(5,1) = - 1.1891333835485772629e-17;
expect_K(5,2) = - 2.289540642056783241e-15;
expect_K(5,3) = 0.046150847478858725292;
expect_K(5,4) = 0.05355371134420310042;
expect_K(5,5) = 10.311156036192993923;
expect_K(5,6) = - 0.068270164114244455411;
matrix_type K = dcs_ctrl::dlqi_solve(A, B, C, D, ts, Q, R, N);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
DCS_DEBUG_TRACE("Gain = " << K);
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, K, nu, nx+1, tol );
}
*/
int main()
{
// Tests labeled with 'mathematica' keyword are taken from the Wolfram
// Mathematica 8 documentation
// (http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html)
//
// All tests has been validated with MATLAB 2009b
DCS_TEST_SUITE("DCS Control :: DLQI");
DCS_TEST_BEGIN();
DCS_TEST_DO( matlab_1 );
// DCS_TEST_DO( free_func_ill_cond );
DCS_TEST_END();
}
<file_sep>/**
* \file dcs/control/design/matlab_linear_mpc.hpp
*
* \brief Linear Model Predictive Control based on the MATLAB Model Predictive
* Control toolbox.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2015 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_DESIGN_MATLAB_LINEAR_MPC_HPP
#define DCS_CONTROL_DESIGN_MATLAB_LINEAR_MPC_HPP
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublasx/operation/empty.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <cmath>
#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/control/detail/matlab_utility.hpp>
#include <dcs/system/posix_process.hpp>
#include <dcs/exception.hpp>
#include <dcs/macro.hpp>
#include <sstream>
#include <stdexcept>
namespace dcs { namespace control {
namespace matlab_lmpc_detail {
template <typename RealT>
class matlab_output_consumer
{
public: matlab_output_consumer()
: ok_(true)
{
}
public: void operator()(dcs::system::posix_process& matlab_process)
{
ok_ = true;
if (!matlab_process.alive())
{
ok_ = false;
errmsg_ = "MATLAB is not running";
return;
}
std::istream& is = matlab_process.output_stream();
//DCS_DEBUG_TRACE("BEGIN parsing MATLAB output");//XXX
bool parse_line = false;
while (matlab_process.alive() && is.good())
{
//DCS_DEBUG_TRACE("Going to read another line: GOOD: " << is.good() << " - EOF: " << is.eof() << " - FAIL: " << is.fail() << " - BAD: " << is.bad() << " - !(): " << !static_cast<bool>(is) << "");//XXX
std::string line;
std::getline(is, line);
//DCS_DEBUG_TRACE("Read from MATLAB --> " << line);//XXX
if (line.find("???") != std::string::npos
|| line.find("Error:") != std::string::npos)
{
DCS_DEBUG_TRACE("An error is occurred while executing MATLAB: " << line);//XXX
ok_ = false;
errmsg_ = line;
break;
}
if (parse_line)
{
if (line.find("[/dcs::control::matlab_linear_mpc]") != std::string::npos)
{
// The end of parsable lines
parse_line = false;
}
else
{
typename std::string::size_type pos;
if ((pos = line.find("QPCode=")) != std::string::npos)
{
qpcode_ = line.substr(pos+7);
boost::to_lower(qpcode_);
//DCS_DEBUG_TRACE("Parsed as QPCode=" << qpcode_);//XXX
}
else if ((pos = line.find("Iterations=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+11), iterations_);
//DCS_DEBUG_TRACE("Parsed as Iterations=" << iterations_);//XXX
}
else if ((pos = line.find("cost=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+5), cost_);
//DCS_DEBUG_TRACE("Parsed as cost=" << cost_);//XXX
}
else if ((pos = line.find("uopt=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+5), uopt_);
//DCS_DEBUG_TRACE("Parsed as uopt=" << uopt_);//XXX
}
else if ((pos = line.find("Xopt=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+5), Xopt_);
//DCS_DEBUG_TRACE("Parsed as Xopt=" << Xopt_);//XXX
}
else if ((pos = line.find("Uopt=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+5), Uopt_);
//DCS_DEBUG_TRACE("Parsed as Uopt=" << Uopt_);//XXX
}
else if ((pos = line.find("Xopt=")) != std::string::npos)
{
detail::parse_matlab_str(line.substr(pos+5), Yopt_);
//DCS_DEBUG_TRACE("Parsed as Yopt=" << Yopt_);//XXX
}
}
}
else
{
if (line.find("[dcs::control::matlab_linear_mpc]") != std::string::npos)
{
// The beginning of parsable lines
parse_line = true;
}
}
//DCS_DEBUG_TRACE("Looping: GOOD: " << is.good() << " - EOF: " << is.eof() << " - FAIL: " << is.fail() << " - BAD: " << is.bad() << " - !(): " << !static_cast<bool>(is) << "");//XXX
}
//DCS_DEBUG_TRACE("DONE WITH LOOPING");//XXX
//DCS_DEBUG_TRACE("END parsing MATLAB output");//XXX
//DCS_DEBUG_TRACE("IS state: " << is.good() << " - " << is.eof() << " - " << is.fail() << " - " << is.bad());//XXX
}
public: bool ok_;
public: std::string errmsg_;
public: boost::numeric::ublas::vector<RealT> uopt_;
public: boost::numeric::ublas::matrix<RealT> Xopt_;
public: boost::numeric::ublas::matrix<RealT> Uopt_;
public: boost::numeric::ublas::matrix<RealT> Yopt_;
public: std::string qpcode_;
public: std::size_t iterations_;
public: RealT cost_;
}; // matlab_output_consumer
} // Namespace matlab_lmpc_detail
/**
* \brief Model Predictive Control (MPC) for linear systems (Maciejowski,2000).
*
* The linear Model Predictive Control (MPC) framework can be stated as follows.
* Given a linear time-invariant (LTI) system:
* \f[
* x(k+1) = Ax(k) + Bu(k),\\
* y(k) = Cx(k).
* \f]
* the MPC controller finds the best sequence of control actions \f$u(k|k),\ldots,u(k+H_c-1|k)\f$ by solving the following optimization problem:
* \f{align}
* \text{minimize} \quad J(k) =\sum_{i=1}^{H_p} \lVert y(k+i|k)-y_{\text{ref}}(k+i) \rVert^2_{W_y(i)} + \sum_{i=0}^{H_c-1} \lVert \Delta u(k+i|k) \rVert^2_{W_{\Delta u}(i)},\\
* \text{subject to} \quad y_{\text{min}} \le y \ge y_{\text{max}},\\
* \quad \Delta y_{\text{min}} \ge \Delta y \le \Delta y_{\text{max}},\\
* \quad u_{\text{min}} \le u \ge u_{\text{max}},\\
* \quad \Delta u_{\text{min}} \le \Delta u \ge \Delta u_{\text{max}}.
* \f}
* with initial condition:
* \f[
* u(k-1|k) = u(k-1),\\
* x(k|k) = x(k).
* \f]
* where:
* - The notation \f$\lVert x \rVert^2_Q\f$ represents the quadratic form \f$x^T Q x\f$, where \f$x\f$ is a vector and \f$Q\f$ is a symmetric matrix.
* - \f$H_p\f$ is the prediction horizon
* - \f$H_c\f$ is the control horizon
* - \f$x(k+1|k),u(k+1|k),y(k+i|k)\f$ are the predicted system state, system input and system output at the \f$(k+i)\f$-th prediction horizon step, respectively, which are based on measurements up to time \f$k\f$. Note that \f$u(k-1|k)=u(k-1)\f$.
* Note, we always assume that \f$H_c \le H_p\f$ and that \f$\Delta u(k+i|k)=0\f$ for \f$i \ge H_c\f$, so that \f$u(k+i|k)=u(k+H_c-1|k)\f$ for all \f$i \ge H_c\f$.
*
* \note Soft constraints and manipulated variable tracking are not supported yet.
*
* References
* -# <NAME>. "Predictive Control with Constraints," Prentice-Hall, 2000.
* .
*
* \author <NAME> (<EMAIL>)
*/
template <typename RealT>
class matlab_linear_mpc_controller
{
public: typedef RealT real_type;
public: typedef boost::numeric::ublas::matrix<real_type, boost::numeric::ublas::column_major> matrix_type;
public: typedef boost::numeric::ublas::vector<real_type> vector_type;
public: matlab_linear_mpc_controller()
{
}
public: template <typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT>
matlab_linear_mpc_controller(boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc)
: Wy_(Wy),
Wdu_(Wdu),
ymin_(ymin),
ymax_(ymax),
dymin_(dymin),
dymax_(dymax),
umin_(umin),
umax_(umax),
dumin_(dumin),
dumax_(dumax),
Hp_(Hp),
Hc_(Hc)
{
namespace ublasx = boost::numeric::ublasx;
const std::size_t ny = ublasx::size(ymin);
const std::size_t nu = ublasx::size(umin);
// pre: Hc_ > 0
DCS_ASSERT(Hc_ > 0,
DCS_EXCEPTION_THROW(std::invalid_argument, "Control horizon cannot be zero"));
// pre: Hp_ >= Hc_
DCS_ASSERT(Hp_ >= Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Prediction horizon cannot be less than control horizon"));
// pre: num_rows(Wy_) >= ny
DCS_ASSERT(ublasx::num_rows(Wy_) >= ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for output weight matrix Wy"));
// pre: num_rows(Wy_) <= ny*Hp_
DCS_ASSERT(ublasx::num_rows(Wy_) <= ny*Hp_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many rows for output weight matrix Wy"));
// pre: num_columns(Wy_) >= ny
DCS_ASSERT(ublasx::num_columns(Wy_) >= ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few columns for output weight matrix Wy"));
// pre: num_columns(Wy_) <= ny*Hp_
DCS_ASSERT(ublasx::num_columns(Wy_) <= ny*Hp_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many columns for output weight matrix Wy"));
// pre: num_rows(Wdu_) >= nu_
DCS_ASSERT(ublasx::num_rows(Wdu_) >= nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for manipulated variable weight matrix Wdu"));
// pre: num_rows(Wdu_) <= nu*Hc_
DCS_ASSERT(ublasx::num_rows(Wdu_) <= nu*Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many rows for manipulated variable weight matrix Wdu"));
// pre: num_columns(Wdu_) >= nu
DCS_ASSERT(ublasx::num_columns(Wdu_) >= nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few columns for manipulated variable weight matrix Wdu"));
// pre: num_columns(Wdu_) <= nu*Hc_
DCS_ASSERT(ublasx::num_columns(Wdu_) <= nu*Hc_,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too many columns for manipulated variable weight matrix Wdu"));
// pre: size(ymin) == size(ymax)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(ymax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and ymax have incompatible size"));
// pre: size(ymin) == size(dymin)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(dymin),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and dymin have incompatible size"));
// pre: size(ymin) == size(dymax)
DCS_ASSERT(ublasx::size(ymin) == ublasx::size(dymax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors ymin and dymax have incompatible size"));
// pre: size(umin) == size(umax)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(umax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and umax have incompatible size"));
// pre: size(umin) == size(dumin)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(dumin),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and dumin have incompatible size"));
// pre: size(umin) == size(dumax)
DCS_ASSERT(ublasx::size(umin) == ublasx::size(dumax),
DCS_EXCEPTION_THROW(std::invalid_argument, "Vectors umin and dumax have incompatible size"));
}
public: void reset()
{
Wy_.clear();
Wdu_.clear();
ymin_.clear();
ymax_.clear();
dymin_.clear();
dymax_.clear();
umin_.clear();
umax_.clear();
dumin_.clear();
dumax_.clear();
Hp_ = 0;
Hc_ = 0;
A_.clear();
B_.clear();
C_.clear();
Xopt_.clear();
Uopt_.clear();
Yopt_.clear();
//J_ = std::numeric_limits<RealT>::infinity();
}
public: template <typename AMatrixT,
typename BMatrixT,
typename CMatrixT>
void solve(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A);
const std::size_t nu = ublasx::num_columns(B);
const std::size_t ny = ublasx::num_rows(C);
// pre: A is a square matrix
DCS_ASSERT(nx == ublasx::num_columns(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A must be square"));
// pre: num_rows(B) == num_rows(A)
DCS_ASSERT(nx == ublasx::num_rows(B),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix B has a wrong number of rows"));
// pre: num_columns(C) == num_rows(A)
DCS_ASSERT(nx == ublasx::num_columns(C),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix C has a wrong number of columns"));
// pre: num_rows(C) == ny
DCS_ASSERT(ny == ublasx::num_rows(C),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix C has a wrong number of rows"));
A_ = A;
B_ = B;
C_ = C;
if (ublasx::empty(Wy_))
{
Wy_ = ublas::identity_matrix<real_type>(ny);
}
if (ublasx::empty(Wdu_))
{
Wdu_= ublas::zero_matrix<real_type>(nu);
}
// if (ublasx::empty(Wdu_))
// {
// Wdu_= ublas::zero_matrix<real_type>(nu);
// }
if (ublasx::empty(umin_))
{
umin_= ublas::scalar_vector<real_type>(nu, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(umax_))
{
umax_= ublas::scalar_vector<real_type>(nu, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dumin_))
{
dumin_= ublas::scalar_vector<real_type>(nu, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dumax_))
{
dumax_= ublas::scalar_vector<real_type>(nu, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(ymin_))
{
ymin_= ublas::scalar_vector<real_type>(ny, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(ymax_))
{
ymax_= ublas::scalar_vector<real_type>(ny, +std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dymin_))
{
dymin_= ublas::scalar_vector<real_type>(ny, -std::numeric_limits<real_type>::infinity());
}
if (ublasx::empty(dymax_))
{
dymax_= ublas::scalar_vector<real_type>(ny, +std::numeric_limits<real_type>::infinity());
}
// Spans the weighting matrices over the horizons
if (ublasx::num_rows(Wdu_) == nu)
{
ublas::matrix<real_type> WduHc = ublas::zero_matrix<real_type>(nu*Hc_);
for (std::size_t i = 0; i < Hc_; ++i)
{
const std::size_t i0 = i*nu;
const std::size_t i1 = i0+nu;
ublas::subrange(WduHc, i0, i1, i0, i1) = Wdu_;
}
Wdu_ = WduHc;
}
if (ublasx::num_rows(Wy_) == ny)
{
ublas::matrix<real_type> WyHp = ublas::zero_matrix<real_type>(ny*Hp_);
for (std::size_t i = 0; i < Hp_; ++i)
{
const std::size_t i0 = i*ny;
const std::size_t i1 = i0+ny;
ublas::subrange(WyHp, i0, i1, i0, i1) = Wy_;
}
Wy_ = WyHp;
}
}
public: template <typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
vector_type control(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A_);
const std::size_t nu = ublasx::num_columns(B_);
const std::size_t ny = ublasx::num_rows(C_);
DCS_ASSERT(ublasx::size(x) == nx,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector x"));
DCS_ASSERT(ublasx::size(u) == nu,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector u"));
DCS_ASSERT(ublasx::num_columns(Yref) == ny,
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad number of columns for matrix Yref"));
//if (ublasx::num_rows(Yref) < Hp_)
DCS_ASSERT(ublasx::num_rows(Yref) > 0,
DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for matrix Yref"));
//FIXME: in MATLAB it's not possible to set constraints on the output variables rate (variables dymin_ and dymax_)
Xopt_.resize(0, 0, false);
Uopt_.resize(0, 0, false);
Yopt_.resize(0, 0, false);
//J_ = std::numeric_limits<RealT>::infinity();
std::vector<std::string> matlab_args;
matlab_args.push_back("-nodisplay");
//matlab_args.push_back("-nojvm");
matlab_args.push_back("-nodesktop");
std::ostringstream oss;
oss << "-r \""
<< " use_custom_state_est = 1;" //FIXME: this disable the MATLAB's default state estimation (i.e., steady-state kalman filter) in favor of custom state estimation
<< " try"
<< " nu = " << nu << ";"
<< " ny = " << ny << ";"
<< " A = " << detail::to_matlab_str(A_) << ";"
<< " B = " << detail::to_matlab_str(B_) << ";"
<< " C = " << detail::to_matlab_str(C_) << ";"
<< " D = zeros(ny,nu);"
<< " sys = ss(A,B,C,D,1);"
<< " Hp = " << Hp_ << ";"
<< " Hc = " << Hc_ << ";"
<< " ctrl = mpc(sys, sys.Ts, Hp, Hc);"
<< " if use_custom_state_est,"
<< " setEstimator(ctrl,'custom');"
<< " end;"
<< " ctrl.Weights.MVRate = reshape(diag(" << detail::to_matlab_str(Wdu_) << "), nu, Hc)';"
<< " ctrl.Weights.OV = reshape(diag(" << detail::to_matlab_str(Wy_) << "), ny, Hp)';";
for (std::size_t i = 0; i < nu; ++i)
{
oss << " ctrl.MV(" << (i+1) << ").Min = " << umin_(i) << ";"
<< " ctrl.MV(" << (i+1) << ").Max = " << umax_(i) << ";"
<< " ctrl.MV(" << (i+1) << ").RateMin = " << dumin_(i) << ";"
<< " ctrl.MV(" << (i+1) << ").RateMax = " << dumax_(i) << ";";
}
for (std::size_t i = 0; i < ny; ++i)
{
oss << " ctrl.OV(" << (i+1) << ").Min = " << ymin_(i) << ";"
<< " ctrl.OV(" << (i+1) << ").Max = " << ymax_(i) << ";";
}
oss << " x = " << detail::to_matlab_str(x) << ";"
<< " u = " << detail::to_matlab_str(u) << ";"
<< " y = sys.C*x+sys.D*u;"
<< " r = " << detail::to_matlab_str(Yref) << ";"
<< " ctrlstate = mpcstate(ctrl, x, [], [], u);"
<< " if use_custom_state_est,"
<< " ctrlstate.Plant = x;"
<< " end;"
<< " [uopt, info] = mpcmove(ctrl, ctrlstate, y, r);"
<< " format long;"
<< " disp('--- [dcs::control::matlab_linear_mpc] ---');"
<< " disp(['uopt=', mat2str(uopt)]);"
<< " disp(['Uopt=', mat2str(info.Uopt)]);"
<< " disp(['Yopt=', mat2str(info.Yopt)]);"
<< " disp(['Xopt=', mat2str(info.Xopt)]);"
<< " disp(['QPCode=', info.QPCode]);"
<< " disp(['Iterations=', num2str(info.Iterations)]);"
<< " disp(['Cost=', num2str(info.Cost)]);"
<< " disp('--- [/dcs::control::matlab_linear_mpc] ---');"
<< " catch me,"
<< " disp(['??? Error: ', me.message]);"
<< " end;"
<< " quit force;"
<< "\"";
matlab_args.push_back(oss.str());
matlab_lmpc_detail::matlab_output_consumer<RealT> matlab_consumer;
detail::run_matlab("matlab", matlab_args.begin(), matlab_args.end(), matlab_consumer);
if (!matlab_consumer.ok_)
{
DCS_EXCEPTION_THROW(std::runtime_error, matlab_consumer.errmsg_);
}
Xopt_ = matlab_consumer.Xopt_;
Uopt_ = matlab_consumer.Uopt_;
Yopt_ = matlab_consumer.Yopt_;
//J_ = matlab_consumer.cost_;
//DCS_DEBUG_TRACE("CONTROL -- predicted X: " << Xopt_);//XXX
//DCS_DEBUG_TRACE("CONTROL -- optimal U: " << Uopt_);//XXX
//DCS_DEBUG_TRACE("CONTROL -- predicted Y: " << Yopt_);//XXX
return ublas::row(Uopt_, 0);
}
public: template <typename XVectorT,
typename UVectorT,
typename YRefVectorT>
vector_type control(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::vector_expression<YRefVectorT> const& yref)
{
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
matrix_type Yref(Hp_, boost::numeric::ublasx::size(yref));
for (std::size_t i = 0; i < Hp_; ++i)
{
ublas::row(Yref, i) = yref;
}
return this->control(x, u, Yref);
}
// Mimics the MATLAB's sim function
public: template <typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
matrix_type simulate(boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
const std::size_t nx = ublasx::num_rows(A_);
const std::size_t nu = ublasx::num_columns(B_);
const std::size_t ny = ublasx::num_rows(C_);
const std::size_t nsim = ublasx::num_rows(Yref);
if (ublasx::size(x) != nx)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector x");
}
if (ublasx::size(u) != nu)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad size for vector u");
}
if (ublasx::num_columns(Yref) != ny)
{
DCS_EXCEPTION_THROW(std::invalid_argument, "Bad number of columns for matrix Yref");
}
//if (ublasx::num_rows(Yref) < Hp_)
//{
// DCS_EXCEPTION_THROW(std::invalid_argument, "Too few rows for matrix Yref");
//}
ublas::vector<real_type> xx = x;
ublas::vector<real_type> uu = u;
ublas::matrix<real_type> U(nsim, nu, 0);
#ifdef DCS_DEBUG
ublas::matrix<real_type> X(nsim, nx, 0);//XXX
ublas::matrix<real_type> Y(nsim, ny, 0);//XXX
#endif // DCS_DEBUG
for (std::size_t k = 0; k < nsim; ++k)
{
this->control(xx, uu, ublas::row(Yref(), k));
xx = ublas::row(Xopt_, 1);
uu = ublas::row(Uopt_, 0);
ublas::row(U, k) = uu;
#ifdef DCS_DEBUG
//ublas::row(X, k) = xx; //XXX
//ublas::row(Y, k) = ublas::row(Yopt_, 1); //XXX
ublas::row(X, k) = ublas::row(Xopt_, 0); //XXX
ublas::row(Y, k) = ublas::row(Yopt_, 0); //XXX
#endif // DCS_DEBUG
}
//DCS_DEBUG_TRACE("SIMULATION -- Yref: " << Yref);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- X: " << X);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- U: " << U);//XXX
//DCS_DEBUG_TRACE("SIMULATION -- Y: " << Y);//XXX
return U;
}
public: matrix_type Wy() const
{
return Wy_;
}
public: matrix_type Wdu() const
{
return Wdu_;
}
public: vector_type ymin() const
{
return ymin_;
}
public: vector_type ymax() const
{
return ymax_;
}
public: vector_type dymin() const
{
return dymin_;
}
public: vector_type dymax() const
{
return dymax_;
}
public: vector_type umin() const
{
return umin_;
}
public: vector_type umax() const
{
return umax_;
}
public: vector_type dumin() const
{
return dumin_;
}
public: vector_type dumax() const
{
return dumax_;
}
public: std::size_t prediction_horizon() const
{
return Hp_;
}
public: std::size_t control_horizon() const
{
return Hc_;
}
public: matrix_type predicted_states() const
{
return Xopt_;
}
public: matrix_type predicted_outputs() const
{
return Yopt_;
}
public: matrix_type optimal_inputs() const
{
return Uopt_;
}
//TODO: we need to collect the objective values of the QP problem during each iteration in the control method
// private: real_type cost() const
// {
// return J_;
// }
private: matrix_type Wy_; ///< Weight matrix for the output variables
private: matrix_type Wdu_; ///< Weight matrix for the manipulated variable adjustments (moves)
private: vector_type ymin_; ///< Contraint vector definining the lower bounds of the output variables
private: vector_type ymax_; ///< Contraint vector definining the upper bounds of the output variables
private: vector_type dymin_; ///< Contraint vector definining the lower bounds of the manipulated variable adjustments
private: vector_type dymax_; ///< Contraint vector definining the upper bounds of the manipulated variable adjustments
private: vector_type umin_; ///< Contraint vector definining the lower bounds of the manipulated variables
private: vector_type umax_; ///< Contraint vector definining the upper bounds of the manipulated variables
private: vector_type dumin_; ///< Contraint vector definining the lower bounds of the manipulated variable adjustments
private: vector_type dumax_; ///< Contraint vector definining the upper bounds of the manipulated variable adjustments
private: std::size_t Hp_; ///< Prediction horizon
private: std::size_t Hc_; ///< Control horizon
private: matrix_type A_; ///< The state matrix of the linear system
private: matrix_type B_; ///< The input matrix of the linear system
private: matrix_type C_; ///< The output matrix of the linear system
//private: matrix_type Ae_; ///< The state matrix of the extended linear system
//private: matrix_type Be_; ///< The input matrix of the extended linear system
//private: matrix_type Ce_; ///< The output matrix of the extended linear system
//private: matrix_type Iu_;
//private: matrix_type Ru_;
//private: matrix_type Rx_;
//private: matrix_type dRx_;
//private: matrix_type Rx1_;
//private: vector_type umax1_;
//private: vector_type umin1_;
//private: vector_type dumax1_;
//private: vector_type dumin1_;
//private: vector_type ymax1_;
//private: vector_type ymin1_;
//private: vector_type dymax1_;
//private: vector_type dymin1_;
//private: matrix_type H_;
//private: matrix_type Alpha_;
private: matrix_type Xopt_;
private: matrix_type Uopt_;
private: matrix_type Yopt_;
//private: real_type J_;
}; // matlab_linear_mpc_controller
template <typename RealT,
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT,
typename XVectorT,
typename UVectorT,
typename YRefMatrixT>
boost::numeric::ublas::vector<RealT> matlab_linear_mpc(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc,
boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::matrix_expression<YRefMatrixT> const& Yref)
{
matlab_linear_mpc_controller<RealT> lmpc(Wy, Wdu, ymin, ymax, dymin, dymax, umin, umax, dumin, dumax, Hp, Hc);
lmpc.solve(A, B, C);
return lmpc.control(x, u, Yref);
}
template <typename RealT,
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename WyMatrixT,
typename WduMatrixT,
typename YMinVectorT,
typename YMaxVectorT,
typename DeltaYMinVectorT,
typename DeltaYMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename DeltaUMinVectorT,
typename DeltaUMaxVectorT,
typename XVectorT,
typename UVectorT,
typename YRefVectorT>
boost::numeric::ublas::vector<RealT> matlab_linear_mpc(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
boost::numeric::ublas::matrix_expression<WyMatrixT> const& Wy,
boost::numeric::ublas::matrix_expression<WduMatrixT> const& Wdu,
boost::numeric::ublas::vector_expression<YMinVectorT> const& ymin,
boost::numeric::ublas::vector_expression<YMaxVectorT> const& ymax,
boost::numeric::ublas::vector_expression<DeltaYMinVectorT> const& dymin,
boost::numeric::ublas::vector_expression<DeltaYMaxVectorT> const& dymax,
boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
boost::numeric::ublas::vector_expression<DeltaUMinVectorT> const& dumin,
boost::numeric::ublas::vector_expression<DeltaUMaxVectorT> const& dumax,
std::size_t Hp,
std::size_t Hc,
boost::numeric::ublas::vector_expression<XVectorT> const& x,
boost::numeric::ublas::vector_expression<UVectorT> const& u,
boost::numeric::ublas::vector_expression<YRefVectorT> const& yref)
{
matlab_linear_mpc_controller<RealT> lmpc(Wy, Wdu, ymin, ymax, dymin, dymax, umin, umax, dumin, dumax, Hp, Hc);
lmpc.solve(A, B, C);
return lmpc.control(x, u, yref);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_DESIGN_MATLAB_LINEAR_MPC_HPP
<file_sep>/**
* \file dcs/control/bindings/fortran.hpp
*
* \brief Bindings for generic Fortran routines.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2012 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_BINDINGS_FORTRAN_HPP
#define DCS_CONTROL_BINDINGS_FORTRAN_HPP
#include <dcs/control/bindings/detail/fortran.hpp>
namespace dcs { namespace control { namespace bindings {
/// Binding for the Fortran CHARACTER type
typedef dcs_control_bindings_fortran_char fortran_char;
/// Binding for the Fortran COMPLEX double precision type
typedef dcs_control_bindings_fortran_double_complex fortran_double_complex;
/// Binding for the Fortran COMPLEX single precision type
typedef dcs_control_bindings_fortran_single_complex fortran_single_complex;
/// Binding for the Fortran REAL double precision type
typedef dcs_control_bindings_fortran_double_real fortran_double_real;
/// Binding for the Fortran REAL single precision type
typedef dcs_control_bindings_fortran_single_real fortran_single_real;
/// Binding for the Fortran INTEGER type
typedef dcs_control_bindings_fortran_int fortran_int;
/// Binding for the Fortran LOGICAL type
typedef dcs_control_bindings_fortran_logical fortran_logical;
/// Binding for the Fortran external function type
typedef dcs_control_bindings_fortran_function fortran_function;
}}} //Namespace dcs::control::bindings
#endif // DCS_CONTROL_BINDINGS_FORTRAN_HPP
<file_sep>/**
* \file dcs/control/solver/qp.hpp
*
* \brief Quadratic Programming (QP) problem solver
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2015 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_SOLVER_QP_HPP
#define DCS_CONTROL_SOLVER_QP_HPP
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <sstream>
#include <stdexcept>
#if defined(DCS_CONTROL_QP_USE_CPLEX)
# include <ilconcert/iloalg.h>
# include <ilconcert/iloenv.h>
# include <ilconcert/iloexpression.h>
# include <ilconcert/ilomodel.h>
# include <ilcplex/ilocplex.h>
#elif defined(DCS_CONTROL_QP_USE_GUROBI)
# include <gurobi_c++.h>
# include <vector>
#elif defined(DCS_CONTROL_QP_USE_QPOASES)
# include <boost/smart_ptr.hpp>
# include <qpOASES.hpp>
#else
# error Unable to find a suitable QP solver
#endif // DCS_CONTROL_QP_USE_CPLEX
namespace dcs { namespace control {
namespace detail {
#ifdef DCS_CONTROL_QP_USE_CPLEX
template <typename RealT,
typename QMatrixT,
typename CVectorT,
typename AMatrixT,
typename BVectorT>//,
//typename RealT>
boost::numeric::ublas::vector<RealT> qp_solve_by_cplex(const boost::numeric::ublas::matrix_expression<QMatrixT>& Q,
const boost::numeric::ublas::vector_expression<CVectorT>& c,
const boost::numeric::ublas::matrix_expression<AMatrixT>& A,
const boost::numeric::ublas::vector_expression<BVectorT>& b)
{
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
ublas::vector<RealT> sol;
DCS_ASSERT(ublasx::num_rows(Q) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q is not a square matrix"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(b) == ublasx::num_rows(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector b have incompatible dimensions"));
const std::size_t nb = ublasx::size(b);
const std::size_t nx = ublasx::size(c);
try
{
// Initialize the Concert Technology app
IloEnv env;
IloModel model(env);
model.setName("MPC - QP solver");
// Decision variables
// Variable x_{i}
IloNumVarArray x(env, nx);
for (std::size_t i = 0; i < nx; ++i)
{
std::ostringstream oss;
oss << "x[" << i << "]";
x[i] = IloNumVar(env, -IloInfinity, IloInfinity, ILOFLOAT, oss.str().c_str());
model.add(x[i]);
}
// Constraints
std::size_t cc = 0; // Constraint counter
std::size_t csc = 0; // Constraint subcounter
// C1: Ax \le b
++cc;
for (std::size_t i = 0; i < nb; ++i)
{
/*
++csc;
std::ostringstream oss;
oss << "C" << cc << "_{" << csc << "}";
IloExpr lhs(env);
for (std::size_t j = 0; j < nx; ++j)
{
lhs += A()(i,j)*x[j];
}
IloConstraint cons;
if (std::isfinite(b()(i)))
{
cons = (lhs <= b()(i));
}
else
{
if (b()(i) > 0)
{
cons = (lhs <= IloInfinity);
}
else
{
cons = (lhs <= -IloInfinity);
}
}
cons.setName(oss.str().c_str());
model.add(cons);
*/
if (std::isfinite(b()(i)))
{
++csc;
std::ostringstream oss;
oss << "C" << cc << "_{" << csc << "}";
IloExpr lhs(env);
for (std::size_t j = 0; j < nx; ++j)
{
lhs += A()(i,j)*x[j];
}
IloConstraint cons(lhs <= b()(i));
model.add(cons);
}
}
// Objective
IloObjective z;
{
IloExpr expr(env);
for (std::size_t i = 0; i < nx; ++i)
{
// Quadratic term
for (std::size_t j = 0; j < nx; ++j)
{
expr += 0.5*x[i]*Q()(i,j)*x[j];
}
// Linear term
expr += c()(i)*x[i];
}
z = IloMinimize(env, expr);
}
model.add(z);
// Solve the model.
// NOTE: The default solver (i.e., IloCplex::RootAlg parameter set to
// IloCplex::Auto) seems to have troubles maybe due to numerical
// problems.
// The primal simplex algorithm (i.e., IloCplex::IloPrimal) seems to be
// more robust, instead.
IloCplex solver(model);
//solver.setParam(IloCplex::RootAlg, IloCplex::Primal);
#ifndef DCS_DEBUG
solver.setOut(env.getNullStream());
solver.setWarning(env.getNullStream());
#else // DCS_DEBUG
solver.exportModel("cplex-mpc_qp.sav");
#endif // DCS_DEBUG
const bool solved = solver.solve();
IloAlgorithm::Status status = solver.getStatus();
switch (status)
{
case IloAlgorithm::Optimal: // The algorithm found an optimal solution.
case IloAlgorithm::Feasible: // The algorithm found a feasible solution, though it may not necessarily be optimal.
break;
case IloAlgorithm::Infeasible: // The algorithm proved the model infeasible (i.e., it is not possible to find an assignment of values to variables satisfying all the constraints in the model).
case IloAlgorithm::Unbounded: // The algorithm proved the model unbounded.
case IloAlgorithm::InfeasibleOrUnbounded: // The model is infeasible or unbounded.
case IloAlgorithm::Error: // An error occurred and, on platforms that support exceptions, that an exception has been thrown.
case IloAlgorithm::Unknown: // The algorithm has no information about the solution of the model.
{
::std::ostringstream oss;
oss << "Optimization was stopped with status = " << status << " (CPLEX status = " << solver.getCplexStatus() << ", sub-status = " << solver.getCplexSubStatus() << ")";
dcs::log_warn(DCS_LOGGING_AT, oss.str());
}
}
if (solved)
{
#ifdef DCS_DEBUG
DCS_DEBUG_TRACE( "-------------------------------------------------------------------------------[" );
DCS_DEBUG_TRACE( "- Objective value: " << static_cast<RealT>(solver.getObjValue()) );
DCS_DEBUG_TRACE( "- Decision variables: " );
// Output x_{i}
for (std::size_t i = 0; i < nx; ++i)
{
DCS_DEBUG_STREAM << x[i].getName() << " = " << solver.getValue(x[i]) << ::std::endl;
}
DCS_DEBUG_TRACE( "]-------------------------------------------------------------------------------" );
#endif // DCS_DEBUG
sol.resize(nx);
for (std::size_t i = 0; i < nx; ++i)
{
sol[i] = static_cast<RealT>(solver.getValue(x[i]));
}
}
z.end();
x.end();
// Close the Concerty Technology app
env.end();
}
catch (IloException const& e)
{
std::ostringstream oss;
oss << "Got exception from CPLEX: " << e.getMessage();
DCS_EXCEPTION_THROW(std::runtime_error, oss.str());
}
catch (...)
{
DCS_EXCEPTION_THROW(std::runtime_error, "Unexpected error during the optimization");
}
return sol;
}
#endif // DCS_CONTROL_QP_USE_CPLEX
#ifdef DCS_CONTROL_QP_USE_GUROBI
template <typename RealT,
typename QMatrixT,
typename CVectorT,
typename AMatrixT,
typename BVectorT>//,
//typename RealT>
boost::numeric::ublas::vector<RealT> qp_solve_by_gurobi(const boost::numeric::ublas::matrix_expression<QMatrixT>& Q,
const boost::numeric::ublas::vector_expression<CVectorT>& c,
const boost::numeric::ublas::matrix_expression<AMatrixT>& A,
const boost::numeric::ublas::vector_expression<BVectorT>& b)
{
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
ublas::vector<RealT> sol;
DCS_ASSERT(ublasx::num_rows(Q) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q is not a square matrix"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(b) == ublasx::num_rows(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector b have incompatible dimensions"));
const std::size_t nb = ublasx::size(b);
const std::size_t nx = ublasx::size(c);
try
{
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env);
model.set(GRB_StringAttr_ModelName, "MPC - QP solver");
#ifdef DCS_DEBUG
env.set(GRB_IntParam_OutputFlag, 1);
env.set(GRB_IntParam_LogToConsole, 1);
#else
env.set(GRB_IntParam_OutputFlag, 0);
env.set(GRB_IntParam_LogToConsole, 0);
#endif // DCS_DEBUG
// Decision variables
// Variable x_{i}
std::vector<GRBVar> x(nx);
for (std::size_t i = 0; i < nx; ++i)
{
std::ostringstream oss;
oss << "x[" << i << "]";
x[i] = model.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS, oss.str());
}
// Integrate variables into the model
model.update();
// Constraints
std::size_t cc = 0; // Constraint counter
std::size_t csc = 0; // Constraint subcounter
// C1: Ax \le b
++cc;
for (std::size_t i = 0; i < nb; ++i)
{
++csc;
std::ostringstream oss;
oss << "C" << cc << "_{" << csc << "}";
GRBLinExpr lhs;
for (std::size_t j = 0; j < nx; ++j)
{
lhs += A()(i,j)*x[j];
}
if (std::isfinite(b()(i)))
{
model.addConstr(lhs, GRB_LESS_EQUAL, b()(i), oss.str());
}
else
{
if (b()(i) > 0)
{
model.addConstr(lhs, GRB_LESS_EQUAL, GRB_INFINITY, oss.str());
}
else
{
model.addConstr(lhs, GRB_LESS_EQUAL, -GRB_INFINITY, oss.str());
}
}
}
// Objective
GRBQuadExpr obj;
for (std::size_t i = 0; i < nx; ++i)
{
// Quadratic term
for (std::size_t j = 0; j < nx; ++j)
{
obj += 0.5*x[i]*Q()(i,j)*x[j];
}
// Linear term
obj += c()(i)*x[i];
}
model.setObjective(obj, GRB_MINIMIZE);
// Integrate variables into the model
model.update();
#ifdef DCS_DEBUG
model.write("gurobi-mpc_qp.lp");
#endif // DCS_DEBUG
model.optimize();
bool solved = false;
int status = model.get(GRB_IntAttr_Status);
switch (status)
{
case GRB_OPTIMAL: // The algorithm found an optimal solution.
case GRB_SUBOPTIMAL: // The algorithm found a feasible solution, though it may not necessarily be optimal.
solved = true;
break;
default:
{
::std::ostringstream oss;
oss << "Optimization was stopped with status = " << status;
dcs::log_warn(DCS_LOGGING_AT, oss.str());
}
}
if (solved)
{
#ifdef DCS_DEBUG
DCS_DEBUG_TRACE( "-------------------------------------------------------------------------------[" );
DCS_DEBUG_TRACE( "- Objective value: " << static_cast<RealT>(model.get(GRB_DoubleAttr_ObjVal)) );
DCS_DEBUG_TRACE( "- Decision variables: " );
// Output x_{i}
for (std::size_t i = 0; i < nx; ++i)
{
DCS_DEBUG_STREAM << x[i].get(GRB_StringAttr_VarName) << " = " << x[i].get(GRB_DoubleAttr_X) << " (" << static_cast<RealT>(x[i].get(GRB_DoubleAttr_X)) << ")" << ::std::endl;
}
DCS_DEBUG_TRACE( "]-------------------------------------------------------------------------------" );
#endif // DCS_DEBUG
sol.resize(nx);
for (std::size_t i = 0; i < nx; ++i)
{
sol[i] = static_cast<RealT>(x[i].get(GRB_DoubleAttr_X));
}
}
}
catch (GRBException const& e)
{
std::ostringstream oss;
oss << "Got exception from GUROBI: " << e.getMessage() << " (Error code: " << e.getErrorCode() << ")";
DCS_EXCEPTION_THROW(std::runtime_error, oss.str());
}
catch (...)
{
DCS_EXCEPTION_THROW(std::runtime_error, "Unexpected error during the optimization");
}
return sol;
}
#endif // DCS_CONTROL_QP_USE_GUROBI
#ifdef DCS_CONTROL_QP_USE_QPOASES
template <typename RealT,
typename QMatrixT,
typename CVectorT,
typename AMatrixT,
typename BVectorT>//,
//typename RealT>
boost::numeric::ublas::vector<RealT> qp_solve_by_qpoases(const boost::numeric::ublas::matrix_expression<QMatrixT>& Q,
const boost::numeric::ublas::vector_expression<CVectorT>& c,
const boost::numeric::ublas::matrix_expression<AMatrixT>& A,
const boost::numeric::ublas::vector_expression<BVectorT>& b)
{
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
ublas::vector<RealT> sol;
DCS_ASSERT(ublasx::num_rows(Q) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q is not a square matrix"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(Q),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix Q and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(c) == ublasx::num_columns(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector c have incompatible dimensions"));
DCS_ASSERT(ublasx::size(b) == ublasx::num_rows(A),
DCS_EXCEPTION_THROW(std::invalid_argument, "Matrix A and vector b have incompatible dimensions"));
const std::size_t nb = ublasx::size(b);
const std::size_t nx = ublasx::size(c);
try
{
qpOASES::QProblem problem(nx, nb);
qpOASES::Options options;
#ifdef DCS_DEBUG
options.printLevel = qpOASES::PL_DEBUG_ITER;
#else
options.printLevel = qpOASES::PL_NONE;
#endif // DCS_DEBUG
problem.setOptions(options);
boost::scoped_array<qpOASES::real_t> tmp_Q(new qpOASES::real_t[nx*nx]);
for (std::size_t i = 0; i < nx; ++i)
{
const std::size_t offs = i*nx;
for (std::size_t j = 0; j < nx; ++j)
{
tmp_Q[offs+j] = Q()(i,j);
}
}
boost::scoped_array<qpOASES::real_t> tmp_c(new qpOASES::real_t[nx]);
for (std::size_t i = 0; i < nx; ++i)
{
tmp_c[i] = c()(i);
}
boost::scoped_array<qpOASES::real_t> tmp_A(new qpOASES::real_t[nb*nx]);
for (std::size_t i = 0; i < nb; ++i)
{
const std::size_t offs = i*nx;
for (std::size_t j = 0; j < nx; ++j)
{
tmp_A[offs+j] = A()(i,j);
}
}
boost::scoped_array<qpOASES::real_t> tmp_b(new qpOASES::real_t[nb]);
for (std::size_t i = 0; i < nb; ++i)
{
tmp_b[i] = b()(i);
}
boost::scoped_array<qpOASES::real_t> tmp_lbA(new qpOASES::real_t[nb]);
for (std::size_t i = 0; i < nb; ++i)
{
tmp_lbA[i] = -std::numeric_limits<qpOASES::real_t>::infinity();
}
int nWSR = 10;
qpOASES::returnValue ret;
ret = problem.init(tmp_Q.get(),
tmp_c.get(),
tmp_A.get(),
0,
0,
tmp_lbA.get(),
tmp_b.get(),
nWSR);
if (ret != qpOASES::SUCCESSFUL_RETURN)
{
std::ostringstream oss;
oss << "Unable to initialize the qpOASES problem (status: " << ret << ")";
DCS_EXCEPTION_THROW(std::runtime_error, oss.str());
}
boost::scoped_array<qpOASES::real_t> x(new qpOASES::real_t[nx]);
problem.getPrimalSolution(x.get());
#ifdef DCS_DEBUG
DCS_DEBUG_TRACE( "-------------------------------------------------------------------------------[" );
DCS_DEBUG_TRACE( "- Objective value: " << static_cast<RealT>(problem.getObjVal()) );
DCS_DEBUG_TRACE( "- Decision variables: " );
// Output x_{i}
for (std::size_t i = 0; i < nx; ++i)
{
DCS_DEBUG_STREAM << "x[" << i << "]" << " = " << x[i] << " (" << static_cast<RealT>(x[i]) << ")" << ::std::endl;
}
DCS_DEBUG_TRACE( "]-------------------------------------------------------------------------------" );
#endif // DCS_DEBUG
sol.resize(nx);
for (std::size_t i = 0; i < nx; ++i)
{
sol[i] = static_cast<RealT>(x[i]);
}
}
catch (std::exception const& e)
{
std::ostringstream oss;
oss << "Got exception from qpOASES: " << e.what();
DCS_EXCEPTION_THROW(std::runtime_error, oss.str());
}
catch (...)
{
DCS_EXCEPTION_THROW(std::runtime_error, "Unexpected error during the optimization");
}
return sol;
}
#endif // DCS_CONTROL_QP_USE_QPOASES
} // Namespace detail
/**
* Solve a quadratic programming (QP) problem.
*
* Solve the following quadratic programming problem:
* \f{align}
* \text{minimize} &\quad \frac{1}{2} x^T Q x + c^T x,
* \text{subject to} &\quad Ax \le b.
* \f}
*
* \param Q A real symmetric matrix representing the quadratic term in the objective expression
* \param c A real vector representing the linear term in the objective expression
* \param A A real matrix representing the linear coefficients in the constraints \f$Ax \le b\f$
* \param b A real vector representing the constant vector in the constraints \f$Ax \le b\f$
* \return The vector \f$x\f$ that solves the quadratic programming problem.
*
* \note Soft constraints are not supported yet.
*/
template <typename RealT,
typename QMatrixT,
typename CVectorT,
typename AMatrixT,
typename BVectorT>//,
//typename RealT>
boost::numeric::ublas::vector<RealT> qp_solve(const boost::numeric::ublas::matrix_expression<QMatrixT>& Q,
const boost::numeric::ublas::vector_expression<CVectorT>& c,
const boost::numeric::ublas::matrix_expression<AMatrixT>& A,
const boost::numeric::ublas::vector_expression<BVectorT>& b)
{
#if defined(DCS_CONTROL_QP_USE_CPLEX)
return detail::qp_solve_by_cplex<RealT>(Q, c, A, b);
#elif defined(DCS_CONTROL_QP_USE_GUROBI)
return detail::qp_solve_by_gurobi<RealT>(Q, c, A, b);
#elif defined(DCS_CONTROL_QP_USE_QPOASES)
return detail::qp_solve_by_qpoases<RealT>(Q, c, A, b);
#else
# error Unable to find a suitable QP solver
#endif // DCS_CONTROL_QP_USE_...
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_SOLVER_QP_HPP
<file_sep>dcsxx-control
=============
A set of C++ libraries aimed at providing control theoretic functionalities.
Building
--------
### Prerequisites
* A modern C++98 compiler (e.g., GCC v4.8 or newer is fine)
* [Boost](http://boost.org) C++ libraries (v1.54 or newer)
* [Boost.Numeric Bindings](https://svn.boost.org/svn/boost/sandbox/numeric_bindings) library (v2 or newer)
* [Boost.uBLASx](https://github.com/sguazt/boost-ublasx) library (v1 or newer)
* [dcsxx-commons](https://github.com/sguazt/dcsxx-commons) library (v2 or newer)
* [LAPACK](http://www.netlib.org/lapack/) Linear Algebra PACKage (v3.5 or newer)
* [optional] [SLICOT](http://www.slicot.org) Subroutine Library in Systems and Control Theory (v5 or newer)
### Compilation
This is a header-only library and thus it does not need to be compiled.
<file_sep>/**
* \file dcs/control/pid_controller.cpp
*
* \brief Test suite for PID controllers.
*
* Copyright (C) 2009-2010 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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/>.
*
* \author <NAME> (<EMAIL>)
*/
#include <cstddef>
#include <dcs/control/design/pid_controller.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <vector>
DCS_TEST_DEF( test_single_pid_controller )
{
DCS_TEST_CASE("Single-loop PID Controller");
typedef double real_type;
typedef ::std::size_t size_type;
real_type Kp(5);
real_type Ki(10);
real_type Kd(0.25);
real_type ts(1);
dcs::control::pid_controller<real_type> pid(Kp, Ki, Kd, ts);
real_type errors[] = {
-0.08, -0.06, -0.05, 0.04, -0.38, 0.48, 0.34, 0.76,
-0.07, 0.18, -0.07, -0.31, 0.06, 0.69, -0.32, 0.36
};
real_type signals_ok[] = {
-1.20, -1.70, -2.15, -1.28, -7.31, 2.12, 4.57, 14.41,
9.24, 12.56, 10.49, 6.19, 8.79, 18.91, 10.25, 17.67
};
size_type n = sizeof(errors)/sizeof(errors[0]);
for (size_type i = 0; i < n; ++i)
{
real_type e = errors[i];
real_type u_ok = signals_ok[i];
real_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
DCS_TEST_CHECK_CLOSE(u, u_ok, 1e-2);
}
}
DCS_TEST_DEF( test_single_pid_controller_nonunit_step_time )
{
DCS_TEST_CASE("Single-loop PID Controller with non-unit step-time");
typedef double real_type;
typedef ::std::size_t size_type;
real_type Kp(5);
real_type Ki(10);
real_type Kd(0.25);
real_type ts(0.2);
dcs::control::pid_controller<real_type> pid(Kp, Ki, Kd, ts);
real_type errors[] = {
-0.08, -0.06, -0.05, 0.04, -0.38, 0.48, 0.34, 0.76,
-0.07, 0.18, -0.07, -0.31, 0.06, 0.69, -0.32, 0.36
};
real_type signals_ok[] = {
-0.56, -0.56, -0.62, 0.01, -3.49, 3.38, 2.11, 6.43,
0.57, 3.53, 1.52, -0.29, 2.44, 7.30, -0.44, 5.79
};
size_type n = sizeof(errors)/sizeof(errors[0]);
for (size_type i = 0; i < n; ++i)
{
real_type e = errors[i];
real_type u_ok = signals_ok[i];
real_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
DCS_TEST_CHECK_CLOSE(u, u_ok, 1e-2);
}
}
DCS_TEST_DEF( test_multiloop_pid_controller )
{
DCS_TEST_CASE("Multi-loop PID Controller");
typedef double real_type;
typedef ::std::size_t size_type;
typedef ::boost::numeric::ublas::vector<real_type> vector_type;
vector_type Kp(3);
Kp(0) = 4; Kp(1) = 3; Kp(2) = 2;
vector_type Ki(3);
Ki(0) = 0.4; Ki(1) = 0.3; Ki(2) = 0.2;
vector_type Kd(3);
Kd(0) = 0.02; Kd(1) = 0.03; Kd(2) = 0.04;
real_type ts(1);
dcs::control::multiloop_pid_controller<vector_type,real_type> pid(Kp, Ki, Kd, ts);
vector_type v(3);
::std::vector<vector_type> errors;
v(0) = -0.08; v(1) = 0.04; v(2) = -0.01;
errors.push_back(v);
v(0) = -0.06; v(1) = 0.02; v(2) = -0.02;
errors.push_back(v);
v(0) = -0.05; v(1) = -0.02; v(2) = -0.01;
errors.push_back(v);
v(0) = 0.04; v(1) = -0.01; v(2) = 0.04;
errors.push_back(v);
v(0) = -0.38; v(1) = 0.09; v(2) = 0.02;
errors.push_back(v);
v(0) = 0.48; v(1) = 0.12; v(2) = -0.08;
errors.push_back(v);
v(0) = 0.34; v(1) = 0.04; v(2) = 0.05;
errors.push_back(v);
v(0) = 0.76; v(1) = 0.50; v(2) = 0.24;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.33; v(2) = 0.32;
errors.push_back(v);
v(0) = 0.18; v(1) = 0.20; v(2) = 0.55;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.02; v(2) = 0.83;
errors.push_back(v);
v(0) = -0.31; v(1) = -0.04; v(2) = 0.60;
errors.push_back(v);
v(0) = 0.06; v(1) = -0.09; v(2) = 0.35;
errors.push_back(v);
v(0) = 0.69; v(1) = -1.00; v(2) = -0.30;
errors.push_back(v);
v(0) = -0.32; v(1) = -0.02; v(2) = -0.05;
errors.push_back(v);
v(0) = 0.36; v(1) = 0.40; v(2) = -0.45;
errors.push_back(v);
::std::vector<vector_type> signals_ok;
v(0) = -0.35; v(1) = 0.13; v(2) = -0.02;
signals_ok.push_back(v);
v(0) = -0.30; v(1) = 0.08; v(2) = -0.05;
signals_ok.push_back(v);
v(0) = -0.28; v(1) = -0.05; v(2) = -0.03;
signals_ok.push_back(v);
v(0) = 0.10; v(1) = -0.02; v(2) = 0.08;
signals_ok.push_back(v);
v(0) = -1.74; v(1) = 0.31; v(2) = 0.04;
signals_ok.push_back(v);
v(0) = 1.92; v(1) = 0.43; v(2) = -0.18;
signals_ok.push_back(v);
v(0) = 1.47; v(1) = 0.20; v(2) = 0.10;
signals_ok.push_back(v);
v(0) = 3.47; v(1) = 1.75; v(2) = 0.53;
signals_ok.push_back(v);
v(0) = 0.10; v(1) = 1.32; v(2) = 0.75;
signals_ok.push_back(v);
v(0) = 1.19; v(1) = 0.99; v(2) = 1.33;
signals_ok.push_back(v);
v(0) = 0.15; v(1) = 0.45; v(2) = 2.06;
signals_ok.push_back(v);
v(0) = -0.93; v(1) = 0.27; v(2) = 1.70;
signals_ok.push_back(v);
v(0) = 0.58; v(1) = 0.09; v(2) = 1.27;
signals_ok.push_back(v);
v(0) = 3.38; v(1) = -2.97; v(2) = -0.11;
signals_ok.push_back(v);
v(0) = -0.82; v(1) = 0.02; v(2) = 0.42;
signals_ok.push_back(v);
v(0) = 2.08; v(1) = 1.39; v(2) = -0.50;
signals_ok.push_back(v);
size_type nrows = errors.size();
for (size_type r = 0; r < nrows; ++r)
{
vector_type e = errors[r];
vector_type u_ok = signals_ok[r];
vector_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
size_type ncols = errors[r].size();
for (size_type c = 0; c < ncols; ++c)
{
DCS_TEST_CHECK_CLOSE(u[c], u_ok[c], 1e-2);
}
}
}
DCS_TEST_DEF( test_multiloop_pid_controller_nonunit_step_time )
{
DCS_TEST_CASE("Multi-loop PID Controller with non-unit step-time");
typedef double real_type;
typedef ::std::size_t size_type;
typedef ::boost::numeric::ublas::vector<real_type> vector_type;
vector_type Kp(3);
Kp(0) = 4; Kp(1) = 3; Kp(2) = 2;
vector_type Ki(3);
Ki(0) = 0.4; Ki(1) = 0.3; Ki(2) = 0.2;
vector_type Kd(3);
Kd(0) = 0.02; Kd(1) = 0.03; Kd(2) = 0.04;
real_type ts(0.2);
dcs::control::multiloop_pid_controller<vector_type,real_type> pid(Kp, Ki, Kd, ts);
vector_type v(3);
::std::vector<vector_type> errors;
v(0) = -0.08; v(1) = 0.04; v(2) = -0.01;
errors.push_back(v);
v(0) = -0.06; v(1) = 0.02; v(2) = -0.02;
errors.push_back(v);
v(0) = -0.05; v(1) = -0.02; v(2) = -0.01;
errors.push_back(v);
v(0) = 0.04; v(1) = -0.01; v(2) = 0.04;
errors.push_back(v);
v(0) = -0.38; v(1) = 0.09; v(2) = 0.02;
errors.push_back(v);
v(0) = 0.48; v(1) = 0.12; v(2) = -0.08;
errors.push_back(v);
v(0) = 0.34; v(1) = 0.04; v(2) = 0.05;
errors.push_back(v);
v(0) = 0.76; v(1) = 0.50; v(2) = 0.24;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.33; v(2) = 0.32;
errors.push_back(v);
v(0) = 0.18; v(1) = 0.20; v(2) = 0.55;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.02; v(2) = 0.83;
errors.push_back(v);
v(0) = -0.31; v(1) = -0.04; v(2) = 0.60;
errors.push_back(v);
v(0) = 0.06; v(1) = -0.09; v(2) = 0.35;
errors.push_back(v);
v(0) = 0.69; v(1) = -1.00; v(2) = -0.30;
errors.push_back(v);
v(0) = -0.32; v(1) = -0.02; v(2) = -0.05;
errors.push_back(v);
v(0) = 0.36; v(1) = 0.40; v(2) = -0.45;
errors.push_back(v);
::std::vector<vector_type> signals_ok;
v(0) = -0.33; v(1) = 0.12; v(2) = -0.02;
signals_ok.push_back(v);
v(0) = -0.25; v(1) = 0.06; v(2) = -0.04;
signals_ok.push_back(v);
v(0) = -0.21; v(1) = -0.06; v(2) = -0.02;
signals_ok.push_back(v);
v(0) = 0.16; v(1) = -0.03; v(2) = 0.09;
signals_ok.push_back(v);
v(0) = -1.6; v(1) = 0.29; v(2) = 0.04;
signals_ok.push_back(v);
v(0) = 2; v(1) = 0.38; v(2) = -0.18;
signals_ok.push_back(v);
v(0) = 1.37; v(1) = 0.12; v(2) = 0.13;
signals_ok.push_back(v);
v(0) = 3.17; v(1) = 1.62; v(2) = 0.53;
signals_ok.push_back(v);
v(0) = -0.28; v(1) = 1.03; v(2) = 0.68;
signals_ok.push_back(v);
v(0) = 0.84; v(1) = 0.66; v(2) = 1.19;
signals_ok.push_back(v);
v(0) = -0.22; v(1) = 0.11; v(2) = 1.79;
signals_ok.push_back(v);
v(0) = -1.2; v(1) = -0.05; v(2) = 1.26;
signals_ok.push_back(v);
v(0) = 0.34; v(1) = -0.21; v(2) = 0.77;
signals_ok.push_back(v);
v(0) = 2.95; v(1) = -3.12; v(2) = -0.63;
signals_ok.push_back(v);
v(0) = -1.28; v(1) = 0.1; v(2) = 0.05;
signals_ok.push_back(v);
v(0) = 1.63; v(1) = 1.3; v(2) = -0.9;
signals_ok.push_back(v);
size_type nrows = errors.size();
for (size_type r = 0; r < nrows; ++r)
{
vector_type e = errors[r];
vector_type u_ok = signals_ok[r];
vector_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
size_type ncols = errors[r].size();
for (size_type c = 0; c < ncols; ++c)
{
DCS_TEST_CHECK_CLOSE(u[c], u_ok[c], 1e-2);
}
}
}
DCS_TEST_DEF( test_mimo_pid_controller )
{
DCS_TEST_CASE("MIMO PID Controller");
typedef double real_type;
typedef ::std::size_t size_type;
typedef ::boost::numeric::ublas::vector<real_type> vector_type;
typedef ::boost::numeric::ublas::matrix<real_type> matrix_type;
matrix_type Kp(3,3);
Kp(0,0) = 4.0; Kp(0,1) = 3.0; Kp(0,2) = 2.0;
Kp(1,0) = 1.0; Kp(1,1) = 1.3; Kp(1,2) = 0.4;
Kp(2,0) = 2.2; Kp(2,1) = 1.2; Kp(2,2) = 3.8;
matrix_type Ki(3,3);
Ki(0,0) = 0.4; Ki(0,1) = 0.30; Ki(0,2) = 0.2;
Ki(1,0) = 0.9; Ki(1,1) = 0.63; Ki(1,2) = 1.0;
Ki(2,0) = 2.2; Ki(2,1) = 0.90; Ki(2,2) = 0.1;
matrix_type Kd(3,3);
Kd(0,0) = 0.02; Kd(0,1) = 0.03; Kd(0,2) = 0.04;
Kd(1,0) = 0.10; Kd(1,1) = 0.05; Kd(1,2) = 0.02;
Kd(2,0) = 0.40; Kd(2,1) = 0.03; Kd(2,2) = 0.60;
real_type ts(1);
dcs::control::mimo_pid_controller<vector_type,matrix_type,real_type> pid(Kp, Ki, Kd, ts);
vector_type v(3);
::std::vector<vector_type> errors;
v(0) = -0.08; v(1) = 0.04; v(2) = -0.01;
errors.push_back(v);
v(0) = -0.06; v(1) = 0.02; v(2) = -0.02;
errors.push_back(v);
v(0) = -0.05; v(1) = -0.02; v(2) = -0.01;
errors.push_back(v);
v(0) = 0.04; v(1) = -0.01; v(2) = 0.04;
errors.push_back(v);
v(0) = -0.38; v(1) = 0.09; v(2) = 0.02;
errors.push_back(v);
v(0) = 0.48; v(1) = 0.12; v(2) = -0.08;
errors.push_back(v);
v(0) = 0.34; v(1) = 0.04; v(2) = 0.05;
errors.push_back(v);
v(0) = 0.76; v(1) = 0.50; v(2) = 0.24;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.33; v(2) = 0.32;
errors.push_back(v);
v(0) = 0.18; v(1) = 0.20; v(2) = 0.55;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.02; v(2) = 0.83;
errors.push_back(v);
v(0) = -0.31; v(1) = -0.04; v(2) = 0.60;
errors.push_back(v);
v(0) = 0.06; v(1) = -0.09; v(2) = 0.35;
errors.push_back(v);
v(0) = 0.69; v(1) = -1.00; v(2) = -0.30;
errors.push_back(v);
v(0) = -0.32; v(1) = -0.02; v(2) = -0.05;
errors.push_back(v);
v(0) = 0.36; v(1) = 0.40; v(2) = -0.45;
errors.push_back(v);
::std::vector<vector_type> signals_ok;
v(0) = -0.24; v(1) = -0.09; v(2) = -0.31;
signals_ok.push_back(v);
v(0) = -0.26; v(1) = -0.16; v(2) = -0.44;
signals_ok.push_back(v);
v(0) = -0.35; v(1) = -0.27; v(2) = -0.55;
signals_ok.push_back(v);
v(0) = 0.16; v(1) = -0.06; v(2) = -0.01;
signals_ok.push_back(v);
v(0) = -1.39; v(1) = -0.67; v(2) = -1.89;
signals_ok.push_back(v);
v(0) = 2.17; v(1) = 0.74; v(2) = 1.28;
signals_ok.push_back(v);
v(0) = 1.78; v(1) = 0.82; v(2) = 1.89;
signals_ok.push_back(v);
v(0) = 5.75; v(1) = 3.24; v(2) = 6.51;
signals_ok.push_back(v);
v(0) = 2.17; v(1) = 2.53; v(2) = 4.38;
signals_ok.push_back(v);
v(0) = 3.51; v(1) = 3.65; v(2) = 6.8;
signals_ok.push_back(v);
v(0) = 2.66; v(1) = 4.01; v(2) = 6.87;
signals_ok.push_back(v);
v(0) = 1.03; v(1) = 3.89; v(2) = 4.44;
signals_ok.push_back(v);
v(0) = 1.94; v(1) = 4.5; v(2) = 4.57;
signals_ok.push_back(v);
v(0) = 0.31; v(1) = 3.36; v(2) = 2.82;
signals_ok.push_back(v);
v(0) = -0.38; v(1) = 3.32; v(2) = 1.93;
signals_ok.push_back(v);
v(0) = 2.97; v(1) = 4.64; v(2) = 3.79;
signals_ok.push_back(v);
size_type nrows = errors.size();
for (size_type r = 0; r < nrows; ++r)
{
vector_type e = errors[r];
vector_type u_ok = signals_ok[r];
vector_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
size_type ncols = errors[r].size();
for (size_type c = 0; c < ncols; ++c)
{
DCS_TEST_CHECK_CLOSE(u[c], u_ok[c], 1e-2);
}
}
}
DCS_TEST_DEF( test_mimo_pid_controller_nonunit_step_time )
{
DCS_TEST_CASE("MIMO PID Controller with non-unit step-time");
typedef double real_type;
typedef ::std::size_t size_type;
typedef ::boost::numeric::ublas::vector<real_type> vector_type;
typedef ::boost::numeric::ublas::matrix<real_type> matrix_type;
matrix_type Kp(3,3);
Kp(0,0) = 4.0; Kp(0,1) = 3.0; Kp(0,2) = 2.0;
Kp(1,0) = 1.0; Kp(1,1) = 1.3; Kp(1,2) = 0.4;
Kp(2,0) = 2.2; Kp(2,1) = 1.2; Kp(2,2) = 3.8;
matrix_type Ki(3,3);
Ki(0,0) = 0.4; Ki(0,1) = 0.30; Ki(0,2) = 0.2;
Ki(1,0) = 0.9; Ki(1,1) = 0.63; Ki(1,2) = 1.0;
Ki(2,0) = 2.2; Ki(2,1) = 0.90; Ki(2,2) = 0.1;
matrix_type Kd(3,3);
Kd(0,0) = 0.02; Kd(0,1) = 0.03; Kd(0,2) = 0.04;
Kd(1,0) = 0.10; Kd(1,1) = 0.05; Kd(1,2) = 0.02;
Kd(2,0) = 0.40; Kd(2,1) = 0.03; Kd(2,2) = 0.60;
real_type ts(0.2);
dcs::control::mimo_pid_controller<vector_type,matrix_type,real_type> pid(Kp, Ki, Kd, ts);
vector_type v(3);
::std::vector<vector_type> errors;
v(0) = -0.08; v(1) = 0.04; v(2) = -0.01;
errors.push_back(v);
v(0) = -0.06; v(1) = 0.02; v(2) = -0.02;
errors.push_back(v);
v(0) = -0.05; v(1) = -0.02; v(2) = -0.01;
errors.push_back(v);
v(0) = 0.04; v(1) = -0.01; v(2) = 0.04;
errors.push_back(v);
v(0) = -0.38; v(1) = 0.09; v(2) = 0.02;
errors.push_back(v);
v(0) = 0.48; v(1) = 0.12; v(2) = -0.08;
errors.push_back(v);
v(0) = 0.34; v(1) = 0.04; v(2) = 0.05;
errors.push_back(v);
v(0) = 0.76; v(1) = 0.50; v(2) = 0.24;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.33; v(2) = 0.32;
errors.push_back(v);
v(0) = 0.18; v(1) = 0.20; v(2) = 0.55;
errors.push_back(v);
v(0) = -0.07; v(1) = 0.02; v(2) = 0.83;
errors.push_back(v);
v(0) = -0.31; v(1) = -0.04; v(2) = 0.60;
errors.push_back(v);
v(0) = 0.06; v(1) = -0.09; v(2) = 0.35;
errors.push_back(v);
v(0) = 0.69; v(1) = -1.00; v(2) = -0.30;
errors.push_back(v);
v(0) = -0.32; v(1) = -0.02; v(2) = -0.05;
errors.push_back(v);
v(0) = 0.36; v(1) = 0.40; v(2) = -0.45;
errors.push_back(v);
::std::vector<vector_type> signals_ok;
v(0) = -0.22; v(1) = -0.04; v(2) = -0.19;
signals_ok.push_back(v);
v(0) = -0.23; v(1) = -0.06; v(2) = -0.23;
signals_ok.push_back(v);
v(0) = -0.3; v(1) = -0.12; v(2) = -0.21;
signals_ok.push_back(v);
v(0) = 0.22; v(1) = 0.07; v(2) = 0.5;
signals_ok.push_back(v);
v(0) = -1.28; v(1) = -0.52; v(2) = -1.75;
signals_ok.push_back(v);
v(0) = 2.2; v(1) = 1.04; v(2) = 2.34;
signals_ok.push_back(v);
v(0) = 1.62; v(1) = 0.42; v(2) = 1.26;
signals_ok.push_back(v);
v(0) = 5.31; v(1) = 2.18; v(2) = 5.27;
signals_ok.push_back(v);
v(0) = 1.42; v(1) = 0.46; v(2) = 0.65;
signals_ok.push_back(v);
v(0) = 2.69; v(1) = 1.37; v(2) = 4.66;
signals_ok.push_back(v);
v(0) = 1.69; v(1) = 0.9; v(2) = 4.09;
signals_ok.push_back(v);
v(0) = 0; v(1) = 0.53; v(2) = 1;
signals_ok.push_back(v);
v(0) = 0.9; v(1) = 1.11; v(2) = 1.98;
signals_ok.push_back(v);
v(0) = -0.81; v(1) = 0.11; v(2) = -0.89;
signals_ok.push_back(v);
v(0) = -1.14; v(1) = 0.15; v(2) = -1.43;
signals_ok.push_back(v);
v(0) = 2.03; v(1) = 1.88; v(2) = 0.62;
signals_ok.push_back(v);
size_type nrows = errors.size();
for (size_type r = 0; r < nrows; ++r)
{
vector_type e = errors[r];
vector_type u_ok = signals_ok[r];
vector_type u = pid.control(e);
DCS_DEBUG_TRACE("e = " << e << ", u = " << u << " ==> " << u_ok);
size_type ncols = errors[r].size();
for (size_type c = 0; c < ncols; ++c)
{
DCS_TEST_CHECK_CLOSE(u[c], u_ok[c], 1e-2);
}
}
}
int main()
{
DCS_TEST_SUITE("DCS Control :: PID Controller");
DCS_TEST_BEGIN();
DCS_TEST_DO( test_single_pid_controller );
DCS_TEST_DO( test_single_pid_controller_nonunit_step_time );
DCS_TEST_DO( test_multiloop_pid_controller );
DCS_TEST_DO( test_multiloop_pid_controller_nonunit_step_time );
DCS_TEST_DO( test_mimo_pid_controller );
DCS_TEST_DO( test_mimo_pid_controller_nonunit_step_time );
DCS_TEST_END();
}
<file_sep>/**
* \file dcs/control/bindings/slicot/sb02od.hpp
*
* \brief Binding for the SLICOT SB02OD Fortran routine.
*
* The purpose of the SB02OD routine is to solve for \f$X\f$ either the
* continuous-time algebraic Riccati equation
* \f[
* Q + A'X + XA - (L+XB)R^{-1}(L+XB)' = 0
* \f]
* or the discrete-time algebraic Riccati equation
* \f[
* X = A'XA - (L+A'XB)(R + B'XB)^{-1}(L+A'XB)' + Q
* \f]
* where \f$A\f$, \f$B\f$, \f$Q\f$, \f$R\f$, and \f$L\f$ are
* \f$N\f$-by-\f$N\f$, \f$N\f$-by-\f$M\f$, \f$N\f$-by-\f$N\f$,
* \f$M\f$-by-\f$M\f$ and \f$N\f$-by-\f$M\f$ matrices,
* respectively, such that \f$Q = C'C\f$, \f$R = D'D\f$ and \f$L = C'D\f$;
* \f$X\f$ is an \f$N\f$-by-\f$N\f$ symmetric matrix.
*
* The routine also returns the computed values of the closed-loop
* spectrum of the system, i.e., the stable eigenvalues
* \f$\lambda(1),\ldots,\lambda(N)\f$ of the corresponding Hamiltonian or
* symplectic pencil, in the continuous-time case or discrte-time case,
* respectively.
*
* Optionally, matrix \f$G = BR^{-1}B'\f$ may be given instead of \f$B\f$ and
* \f$R\f$.
* Other options include the case with \f$Q\f$ and/or \f$R\f$ given in a
* factored form, \f$Q = C'C\f$, \f$R = D'D\f$, and with L a zero matrix.
*
* The routine uses the method of deflating subspaces, based on
* reordering the eigenvalues in a generalized Schur matrix pair.
* A standard eigenproblem is solved in the continuous-time case if \f$G\f$ is
* given.
*
* The routine uses a variant of the method of deflating subspaces
* proposed by van Dooren [1]. See also [2], [3].
* It is assumed that \f$(A,B)\f$ is stabilizable and \f$(C,A)\f$ is detectable.
* Under these assumptions the algebraic Riccati equation is known to
* have a unique non-negative definite solution.
*
* REFERENCES
* -# <NAME>.
* A Generalized Eigenvalue Approach for Solving Riccati Equations.
* SIAM J. Sci. Stat. Comp., 2, pp. 121-135, 1981.
* -# <NAME>.
* The Autonomous Linear Quadratic Control Problem. Theory and Numerical
* Solution.
* Lecture Notes in Control and Information Sciences, vol. 163,
* Springer-Verlag, Berlin, 1991.
* -# <NAME>.
* Algorithms for Linear-Quadratic Optimization.
* Pure and Applied Mathematics: A Series of Monographs and
* Textbooks, vol. 200, Marcel Dekker, Inc., New York, 1996.
* .
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2012 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_BINDINGS_SLICOT_SB02OD_HPP
#define DCS_CONTROL_BINDINGS_SLICOT_SB02OD_HPP
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/operation/num_columns.hpp>
#include <boost/numeric/ublas/operation/num_rows.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/control/bindings/fortran.hpp>
#include <dcs/control/bindings/slicot/detail/slicot.hpp>
#include <stdexcept>
namespace dcs { namespace control { namespace bindings { namespace slicot {
inline
void sb02od(fortran_char const& dico,
fortran_char const& jobb,
fortran_char const& fact,
fortran_char const& uplo,
fortran_char const& jobl,
fortran_char const& sort,
fortran_int const& n,
fortran_int const& m,
fortran_int const& p,
fortran_double_real const* a,
fortran_int const& lda,
fortran_double_real const* b,
fortran_int const& ldb,
fortran_double_real const* q,
fortran_int const& ldq,
fortran_double_real const* r,
fortran_int const& ldr,
fortran_double_real const* l,
fortran_int const& ldl,
fortran_double_real& rcond,
fortran_double_real* x,
fortran_int const& ldx,
fortran_double_real* alfar,
fortran_double_real* alfai,
fortran_double_real* beta,
fortran_double_real* s,
fortran_int const& lds,
fortran_double_real* t,
fortran_int const& ldt,
fortran_double_real* u,
fortran_int const& ldu,
fortran_double_real const& tol,
fortran_int* iwork,
fortran_double_real* dwork,
fortran_int const& ldwork,
fortran_logical* bwork)
{
fortran_int info(0);
DCS_CONTROL_BINDINGS_SLICOT_SB02OD(&dico,
&jobb,
&fact,
&uplo,
&jobl,
&sort,
&n,
&m,
&p,
a,
&lda,
b,
&ldb,
q,
&ldq,
r,
&ldr,
l,
&ldl,
&rcond,
x,
&ldx,
alfar,
alfai,
beta,
s,
&lds,
t,
&ldt,
u,
&ldu,
&tol,
iwork,
dwork,
&ldwork,
bwork,
&info);
if (info != 0)
{
::std::ostringstream oss;
switch (info)
{
case 1:
oss << "The computed extended matrix pencil is singular, possibly due to rounding errors";
break;
case 2:
oss << "The QZ/QR algorithm failed";
break;
case 3:
oss << "Reordering of the (generalized) eigenvalues failed";
break;
case 4:
oss << "After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the (generalized) Schur form no longer satisfy the stability condition; this could also be caused due to scaling";
break;
case 5:
oss << "The computed dimension of the solution does not equal the number of states";
break;
case 6:
oss << "A singular matrix was encountered during the computation of the solution matrix";
break;
default:
// OK
break;
}
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
}
namespace detail { namespace /*<unnamed>*/ {
template <typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
void sb02od_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
::boost::numeric::ublas::column_major_tag)
{
namespace ublas = ::boost::numeric::ublas;
typedef ublas::matrix<fortran_double_real, ublas::column_major> matrix_type;
typedef ublas::vector<fortran_double_real> real_vector_type;
typedef ublas::vector<fortran_int> int_vector_type;
typedef ublas::vector<fortran_logical> logical_vector_type;
const fortran_char dico(discrete ? 'D' : 'C');
const fortran_char jobb('B');
const fortran_char fact('N');
const fortran_char uplo('U');
const fortran_char jobl((ublas::num_rows(L) > 0 && ublas::num_columns(L) > 0) ? 'N' : 'Z');
const fortran_char sort('S');
const fortran_int n(ublas::num_rows(A)); // Number of states
const fortran_int m(ublas::num_columns(B)); // Number of inputs
const fortran_int p(0); // Number of outputs (not used because FACT == 'N')
const fortran_int lda(::std::max(1, n));
const fortran_int ldb(::std::max(1, n));
const fortran_int ldq(::std::max(1, n));
const fortran_int ldr(::std::max(1, m));
const fortran_int ldl((jobl == 'Z') ? 1 : ::std::max(1, n));
matrix_type tmp_L;
if (jobl == 'Z')
{
tmp_L = matrix_type(ldl,m,0);
}
else
{
tmp_L = L;
tmp_L.resize(ldl, m, false);
}
const fortran_int ldx(::std::max(1, n));
X().resize(ldx, n, false);
const fortran_int n2(2*n);
real_vector_type tmp_alfar(n2,0);
real_vector_type tmp_alfai(n2,0);
real_vector_type tmp_beta(n2, 0);
const fortran_int lds((jobb == 'B') ? ::std::max(1, n2+m) : ::std::max(1,n2));
S().resize(lds, (jobb == 'B') ? (n2+m) : n2, false);
const fortran_int ldt((jobb == 'G') ? ((dico == 'D') ? ::std::max(1,n2) : 1) : ::std::max(1, n2+m));
T().resize(ldt, n2, false);
const fortran_int ldu(::std::max(1, n2));
U().resize(ldu, n2, false);
const fortran_double_real tol(0); // use default value (i.e., eps - the machine precision)
fortran_double_real rcond(0);
const fortran_int liwork((jobb == 'B') ? ::std::max(::std::max(1, m), n2) : ::std::max(1,n2));
int_vector_type iwork(liwork,0);
const fortran_int ldwork((jobb == 'G') ? ((dico == 'C') ? ::std::max(3,6*n) : ::std::max(7*(n2+1)+16,16*n)) : ::std::max(::std::max(::std::max(7*(n2+1)+16, 16*n), n2+m), 3*m));
real_vector_type dwork(ldwork,0);
logical_vector_type bwork(n2,0);
sb02od(dico,
jobb,
fact,
uplo,
jobl,
sort,
n,
m,
p,
A().data().begin(),
lda,
B().data().begin(),
ldb,
Q().data().begin(),
ldq,
R().data().begin(),
ldr,
tmp_L.data().begin(),
ldl,
rcond,
X().data().begin(),
ldx,
tmp_alfar.data().begin(),
tmp_alfai.data().begin(),
tmp_beta.data().begin(),
S().data().begin(),
lds,
T().data().begin(),
ldt,
U().data().begin(),
ldu,
tol,
iwork.data().begin(),
dwork.data().begin(),
ldwork,
bwork.data().begin());
// Fill the lambda vector:
// \lambda(k) = \frac{\alfa_r(k)+j\alfa_i(k)}{\beta(k)}
lambda().resize(n2, false);
typedef typename ublas::vector_traits<LambdaVectorT>::value_type complex_type;
for (fortran_int k = 0; k < n2; ++k)
{
lambda()(k) = complex_type(tmp_alfar(k), tmp_alfai(k))/tmp_beta(k);
}
}
template <typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
inline
void sb02od_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
::boost::numeric::ublas::row_major_tag)
{
namespace ublas = ::boost::numeric::ublas;
typedef ublas::matrix<typename ublas::matrix_traits<AMatrixT>::value_type,ublas::column_major> A_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<BMatrixT>::value_type,ublas::column_major> B_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<QMatrixT>::value_type,ublas::column_major> Q_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<RMatrixT>::value_type,ublas::column_major> R_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<LMatrixT>::value_type,ublas::column_major> L_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<XMatrixT>::value_type,ublas::column_major> X_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<SMatrixT>::value_type,ublas::column_major> S_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<TMatrixT>::value_type,ublas::column_major> T_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<UMatrixT>::value_type,ublas::column_major> U_colmaj_matrix_type;
A_colmaj_matrix_type tmp_A(A);
B_colmaj_matrix_type tmp_B(B);
Q_colmaj_matrix_type tmp_Q(Q);
R_colmaj_matrix_type tmp_R(R);
L_colmaj_matrix_type tmp_L(L);
X_colmaj_matrix_type tmp_X;
S_colmaj_matrix_type tmp_S;
T_colmaj_matrix_type tmp_T;
U_colmaj_matrix_type tmp_U;
sb02od_impl(tmp_A,
tmp_B,
tmp_Q,
tmp_R,
tmp_L,
discrete,
tmp_X,
lambda,
tmp_S,
tmp_T,
tmp_U,
ublas::column_major_tag());
X() = tmp_X;
S() = tmp_S;
T() = tmp_T;
U() = tmp_U;
}
}} // Namespace detail::<unnamed>
template <typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
inline
void sb02od(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U)
{
namespace ublas = ::boost::numeric::ublas;
typedef typename ublas::matrix_traits<AMatrixT>::orientation_category A_orientation_category;
typedef typename ublas::matrix_traits<BMatrixT>::orientation_category B_orientation_category;
typedef typename ublas::matrix_traits<QMatrixT>::orientation_category Q_orientation_category;
typedef typename ublas::matrix_traits<RMatrixT>::orientation_category R_orientation_category;
typedef typename ublas::matrix_traits<LMatrixT>::orientation_category L_orientation_category;
typedef typename ublas::matrix_traits<XMatrixT>::orientation_category X_orientation_category;
typedef typename ublas::matrix_traits<SMatrixT>::orientation_category S_orientation_category;
typedef typename ublas::matrix_traits<TMatrixT>::orientation_category T_orientation_category;
typedef typename ublas::matrix_traits<UMatrixT>::orientation_category U_orientation_category;
// pre: same orientation category
BOOST_STATIC_ASSERT((
::boost::mpl::and_<
::boost::is_same<A_orientation_category,B_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,Q_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,R_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,L_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,X_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,S_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,T_orientation_category>,
::boost::is_same<A_orientation_category,U_orientation_category>
>
>
>
>
>
>
>::value
));
// Dispatch to the right implementation
detail::sb02od_impl(A,
B,
Q,
R,
L,
discrete,
X,
lambda,
S,
T,
U,
A_orientation_category());
}
}}}} // Namespace dcs::control::bindings::slicot
#endif // DCS_CONTROL_BINDINGS_SLICOT_SB02OD_HPP
<file_sep>/**
* \file dcs/control/bindings/slicot.hpp
*
* \brief Header for bindings to all SLICOT Fortran routines.
*
* The subroutine library SLICOT provides Fortran 77 implementations of
* numerical algorithms for computations in systems and control theory. Based on
* numerical linear algebra routines from BLAS and LAPACK libraries, SLICOT
* provides methods for the design and analysis of control systems.
*
* The SLICOT library is Copyright 2002-2012 NICONET e.V.
* For more information, see <a href="http://www.slicot.org>SLICOT web site</a>.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2012 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_BINDINGS_SLICOT_HPP
#define DCS_CONTROL_BINDINGS_SLICOT_HPP
//#include <dcs/control/bindings/slicot/adaptive.hpp>
//#include <dcs/control/bindings/slicot/analysis.hpp>
//#include <dcs/control/bindings/slicot/bench.hpp>
//#include <dcs/control/bindings/slicot/filter.hpp>
//#include <dcs/control/bindings/slicot/ident.hpp>
//#include <dcs/control/bindings/slicot/math.hpp>
//#include <dcs/control/bindings/slicot/nonlinear.hpp>
#include <dcs/control/bindings/slicot/synthesis.hpp>
//#include <dcs/control/bindings/slicot/transform.hpp>
#endif // DCS_CONTROL_BINDINGS_SLICOT_HPP
<file_sep>/**
* \file test/src/dcs/control/dlqr.cpp
*
* \brief Test suite for DLQR controllers.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-control (below referred to as "this program").
*
* 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/>.
*/
#include <algorithm>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <complex>
#include <cstddef>
#include <dcs/control/design/dlqr.hpp>
#include <dcs/test.hpp>
#include <iostream>
#include "./utility.hpp"
namespace ublas = boost::numeric::ublas;
namespace dcs_ctrl = dcs::control;
const double tol = 1.0e-5;
DCS_TEST_DEF( free_func )
{
DCS_TEST_CASE("test_free_func");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<value_type> vector_type;
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = -0.988011751199999956; A(1,1) = 1.98799160895100258;
matrix_type B(n,m);
B(0,0) = 0;
B(1,0) = 1;
matrix_type Q(n,n);
Q(0,0) = 4.04792870679057178e-12; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 0;
matrix_type R(m,m);
R(0,0) = 0.00810385427000000040;
matrix_type N(n,m);
N(0,0) = 0;
N(1,0) = 0;
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -1.0e-3*0.792840452340859; expect_K(0,1) = 1.0e-3*0.802772572963461;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 1.0e-5*0.634804227345193; expect_S(0,1) =-1.0e-5*0.642756176807922;
expect_S(1,0) =-1.0e-5*0.642756176807922; expect_S(1,1) = 1.0e-5*0.650824595759136;
vector_type expect_e(n); // closed-loop eigenvalues
expect_e(0) = 0.996904570704525;
expect_e(1) = 0.990284265674475;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
matrix_type K = dcs_ctrl::dlqr_solve(A, B, Q, R, N);
DCS_DEBUG_TRACE("Gain = " << K);
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, K, m, n, tol );
}
DCS_TEST_DEF( oo )
{
DCS_TEST_CASE("test_oo");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = -0.988011751199999956; A(1,1) = 1.98799160895100258;
matrix_type B(n,m);
B(0,0) = 0;
B(1,0) = 1;
matrix_type Q(n,n);
Q(0,0) = 4.04792870679057178e-12; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 0;
matrix_type R(m,m);
R(0,0) = 0.00810385427000000040;
matrix_type N(n,m);
N(0,0) = 0;
N(1,0) = 0;
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -1.0e-3*0.792840452340859; expect_K(0,1) = 1.0e-3*0.802772572963461;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 1.0e-5*0.634804227345193; expect_S(0,1) =-1.0e-5*0.642756176807922;
expect_S(1,0) =-1.0e-5*0.642756176807922; expect_S(1,1) = 1.0e-5*0.650824595759136;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_value_type(0.996904570704525,0);
expect_l(1) = complex_value_type(0.990284265674475,0);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqr_controller<value_type> dlqr(Q, R, N);
dlqr.solve(A, B);
DCS_DEBUG_TRACE("Gain = " << dlqr.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqr.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqr.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqr.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqr.are_solution(), n, n, tol );
vector_type l(dlqr.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
matrix_type X(16,n);
X( 0,0) = -0.08; X( 0,1) = 0.04;
X( 1,0) = -0.06; X( 1,1) = 0.02;
X( 2,0) = -0.05; X( 2,1) = -0.02;
X( 3,0) = 0.04; X( 3,1) = -0.01;
X( 4,0) = -0.38; X( 4,1) = 0.09;
X( 5,0) = 0.48; X( 5,1) = 0.12;
X( 6,0) = 0.34; X( 6,1) = 0.04;
X( 7,0) = 0.76; X( 7,1) = 0.50;
X( 8,0) = -0.07; X( 8,1) = 0.33;
X( 9,0) = 0.18; X( 9,1) = 0.20;
X(10,0) = -0.07; X(10,1) = 0.02;
X(11,0) = -0.31; X(11,1) = -0.04;
X(12,0) = 0.06; X(12,1) = -0.09;
X(13,0) = 0.69; X(13,1) = -1.00;
X(14,0) = -0.32; X(14,1) = -0.02;
X(15,0) = 0.36; X(15,1) = 0.40;
matrix_type expect_U(m,16);
expect_U(0,0) = -0.000095538139106; expect_U(0,1) = -0.000063625878600; expect_U(0,2) = -0.000023586571158; expect_U(0,3) = 0.000039741343823; expect_U(0,4) = -0.000373528903456; expect_U(0,5) = 0.000284230708368; expect_U(0,6) = 0.000237454850877; expect_U(0,7) = 0.000201172457297; expect_U(0,8) = -0.000320413780742; expect_U(0,9) = -0.000017843233171; expect_U(0,10) = -0.000071554283123; expect_U(0,11) = -0.000213669637307; expect_U(0,12) = 0.000119819958707; expect_U(0,13) = 0.001349832485079; expect_U(0,14) = -0.000237653493290; expect_U(0,15) = -0.000035686466343;
matrix_type U;
U = dlqr.control(X);
DCS_DEBUG_TRACE("Input X = " << X);
DCS_DEBUG_TRACE("Control U = " << U);
DCS_DEBUG_TRACE("Control expect U = " << expect_U);
DCS_TEST_CHECK_MATRIX_CLOSE(U, expect_U, m, 16, tol);
}
DCS_TEST_DEF( mathematica_1 )
{
// This is the first example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html
DCS_TEST_CASE("Mathematica #1");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n = 4;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 0.4725; A(0,1) = 0.2376; A(0,2) = 0.0589; A(0,3) = 0.1971;
A(1,0) = 0.1451; A(1,1) = 0.5669; A(1,2) = 0.2311; A(1,3) = 0.0439;
A(2,0) = 0.0932; A(2,1) = 0.1190; A(2,2) = 0.5752; A(2,3) = 0.2319;
A(3,0) = 0.2628; A(3,1) = 0.0757; A(3,2) = 0.1406; A(3,3) = 0.4465;
matrix_type B(n,m);
B(0,0) = 0.5711;
B(1,0) = -0.3999;
B(2,0) = 0.6899;
B(3,0) = 0.8156;
matrix_type Q(n,n);
Q(0,0) = 0.5; Q(0,1) = 0.0; Q(0,2) = 0; Q(0,3) = 0;
Q(1,0) = 0.0; Q(1,1) = 0.8; Q(1,2) = 0; Q(1,3) = 0;
Q(2,0) = 0.0; Q(2,1) = 0.0; Q(2,2) = 2; Q(2,3) = 0;
Q(3,0) = 0.0; Q(3,1) = 0.0; Q(3,2) = 0; Q(3,3) = 4;
matrix_type R(m,m);
R(0,0) = 1;
matrix_type N(ublas::zero_matrix<value_type>(n,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = 0.258263408785324; expect_K(0,1) = 0.130076037449530; expect_K(0,2) = 0.301712976754135; expect_K(0,3) = 0.393239174520131;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 0.820688030019406; expect_S(0,1) = 0.366157393574175; expect_S(0,2) = 0.142357177991738; expect_S(0,3) = 0.230214495860850;
expect_S(1,0) = 0.366157393574175; expect_S(1,1) = 1.502565253736899; expect_S(1,2) = 0.491675367390775; expect_S(1,3) = 0.233049076800882;
expect_S(2,0) = 0.142357177991738; expect_S(2,1) = 0.491675367390775; expect_S(2,2) = 2.770266171822138; expect_S(2,3) = 0.158115947330550;
expect_S(3,0) = 0.230214495860850; expect_S(3,1) = 0.233049076800882; expect_S(3,2) = 0.158115947330550; expect_S(3,3) = 4.285246483933100;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_value_type(0.715676446034849, 0.000000000000000);
expect_l(1) = complex_value_type(0.460342919154304, 0.000000000000000);
expect_l(2) = complex_value_type(0.130363078014160, 0.048280928782719);
expect_l(3) = complex_value_type(0.130363078014160,-0.048280928782719);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqr_controller<value_type> dlqr(Q, R, N);
dlqr.solve(A, B);
DCS_DEBUG_TRACE("Gain = " << dlqr.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqr.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqr.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqr.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqr.are_solution(), n, n, tol );
vector_type l(dlqr.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( mathematica_2 )
{
// This is the second example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html
DCS_TEST_CASE("Mathematica #2");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n = 3;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1; A(0,2) = -2;
A(1,0) = 0; A(1,1) = 1; A(1,2) = 1;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 1;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 1;
matrix_type Q(ublas::identity_matrix<value_type>(n,n));
matrix_type R(m,m);
R(0,0) = 10;
matrix_type N(ublas::zero_matrix<value_type>(n,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = 0.131575602686720; expect_K(0,1) = 1.015926918639910; expect_K(0,2) = 1.316503115669289;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 1.0e+2*0.077212408523700; expect_S(0,1) = 1.0e+2*0.254481597239685; expect_S(0,2) = -1.0e+2*0.001210476586442;
expect_S(1,0) = 1.0e+2*0.254481597239685; expect_S(1,1) = 1.0e+2*1.182679389650807; expect_S(1,2) = 1.0e+2*0.256345692556058;
expect_S(2,0) = -1.0e+2*0.001210476586442; expect_S(2,1) = 1.0e+2*0.256345692556058; expect_S(2,2) = 1.0e+2*0.402837910468753;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_value_type(0.464520830811466, 0.249314173526600);
expect_l(1) = complex_value_type(0.464520830811466,-0.249314173526600);
expect_l(2) = complex_value_type(0.622879620021054, 0.000000000000000);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqr_controller<value_type> dlqr(Q, R, N);
dlqr.solve(A, B);
DCS_DEBUG_TRACE("Gain = " << dlqr.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqr.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqr.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqr.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqr.are_solution(), n, n, tol );
vector_type l(dlqr.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( mathematica_3 )
{
// This is the third example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html
DCS_TEST_CASE("Mathematica #3");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n = 2;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = 0.951230000000000; A(0,1) = 0.000000000000000;
A(1,0) = 0.000000000000000; A(1,1) = 0.904838000000000;
matrix_type B(n,m);
B(0,0) = 4.900000000000000; B(0,1) = 4.900000000000000;
B(1,0) = -0.019000000000000; B(1,1) = 0.009000000000000;
matrix_type Q(n,n);
Q(0,0) = 1.0e+2*0.000100000000000; Q(0,1) = 1.0e+2*0.000000000000000;
Q(1,0) = 1.0e+2*0.000000000000000; Q(1,1) = 1.0e+2*1.000000000000000;
matrix_type R(m,m);
R(0,0) = 2.000000000000000; R(0,1) = 0.000000000000000;
R(1,0) = 0.000000000000000; R(1,1) = 0.500000000000000;
matrix_type N(ublas::zero_matrix<value_type>(n,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = 0.022043168004973; expect_K(0,1) = -3.296571964433571;
expect_K(1,0) = 0.078004554558866; expect_K(1,1) = 3.751723555757965;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 1.0e+2*0.000178886938538; expect_S(0,1) = -1.0e+2*0.001642946262000;
expect_S(1,0) = -1.0e+2*0.001642946262000; expect_S(1,1) = 1.0e+2*3.736813637743126;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_value_type(0.459187566597895,0);
expect_l(1) = complex_value_type(0.810246213513234,0);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqr_controller<value_type> dlqr(Q, R, N);
dlqr.solve(A, B);
DCS_DEBUG_TRACE("Gain = " << dlqr.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqr.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqr.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqr.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqr.are_solution(), n, n, tol );
vector_type l(dlqr.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( mathematica_4 )
{
// This is the third example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html
DCS_TEST_CASE("Mathematica #4");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n = 3;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = -0.5000; A(0,1) = 0.0000; A(0,2) = 0.0000;
A(1,0) = 0.0000; A(1,1) = 0.9999; A(1,2) = 0.0000;
A(2,0) = 0.0000; A(2,1) = 0.0000; A(2,2) = 0.8187;
matrix_type B(n,m);
B(0,0) = 0.1850; B(0,1) = 0.1974;
B(1,0) = 0.1000; B(1,1) = 0.1390;
B(2,0) = 0.1813; B(2,1) = 0.0000;
matrix_type Q(n,n);
Q(0,0) = 10; Q(0,1) = 0; Q(0,2) = 0;
Q(1,0) = 0; Q(1,1) = 1; Q(1,2) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 1;
matrix_type R(m,m);
R(0,0) = 0.4; R(0,1) = 0.1;
R(1,0) = 0.1; R(1,1) = 0.1;
matrix_type N(n,m);
N(0,0) = 1; N(0,1) = 1;
N(1,0) = 2; N(1,1) = 1;
N(2,0) = 2; N(2,1) = 1;
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -0.10259451927409935; expect_K(0,1) = 1.0550552116729919; expect_K(0,2) = 3.3699401712231705;
expect_K(1,0) = -0.4714396669727725; expect_K(1,1) = 0.4206832287681541; expect_K(1,2) = -1.796589906583708;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 13.104637764024423; expect_S(0,1) = 0.2570942162727292; expect_S(0,2) = 0.18034745994439821;
expect_S(1,0) = 0.25709421627274576; expect_S(1,1) = -2.741491441343835; expect_S(1,2) = -6.024514042762959;
expect_S(2,0) = 0.18034745994441229; expect_S(2,1) = -6.024514042762947; expect_S(2,2) = -4.280531570924603;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_value_type( 0.850245380354058,0);
expect_l(1) = complex_value_type(-0.35398128255121586,0);
expect_l(2) = complex_value_type( 0.15942743551445882,0);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqr_controller<value_type> dlqr(Q, R, N);
dlqr.solve(A, B);
DCS_DEBUG_TRACE("Gain = " << dlqr.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqr.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqr.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqr.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqr.are_solution(), n, n, tol );
vector_type l(dlqr.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
int main()
{
// Tests labeled with 'mathematica' keyword are taken from the Wolfram
// Mathematica 8 documentation
// (http://reference.wolfram.com/mathematica/ref/LQRegulatorGains.html)
//
// All tests has been validated with MATLAB 2009b
DCS_TEST_SUITE("DCS Control :: DLQR");
DCS_TEST_BEGIN();
DCS_TEST_DO( free_func );
DCS_TEST_DO( oo );
DCS_TEST_DO( mathematica_1 );
DCS_TEST_DO( mathematica_2 );
DCS_TEST_DO( mathematica_3 );
DCS_TEST_DO( mathematica_4 );
DCS_TEST_END();
}
<file_sep>/**
* \file test/src/dcs/control/dlqry.cpp
*
* \brief Test suite for the DLQRY controllers.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-control (below referred to as "this program").
*
* 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/>.
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <complex>
#include <cstddef>
#include <dcs/control/design/dlqry.hpp>
#include <dcs/test.hpp>
#include <iostream>
#include "./utility.hpp"
namespace ublas = boost::numeric::ublas;
namespace dcs_ctrl = dcs::control;
const double tol = 1.0e-5;
DCS_TEST_DEF( free_func )
{
DCS_TEST_CASE("free_func");
typedef double value_type;
typedef std::complex<double> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t n = 2; // number of states
const std::size_t m = 1; // number of inputs
const std::size_t p = 2; // number of outputs
matrix_type A(n,n);
A(0,0) = 0.250000000000000000; A(0,1) = 0.80000000000000000;
A(1,0) = -0.988011751199999956; A(1,1) = 1.98799160895100258;
matrix_type B(n,m);
B(0,0) = 0;
B(1,0) = 1;
matrix_type C(p,n);
C(0,0) = 2.011946497e-6; C(0,1) = 0;
C(1,0) = 0.000000000000; C(1,1) = 1;
matrix_type D(p,m);
D(0,0) = 0.5;
D(1,0) = 0.5;
matrix_type Q(n,n);
Q(0,0) = 4.04792870679057178e-12; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 2;
matrix_type R(m,m);
R(0,0) = 0.00810385427000000040;
matrix_type N(ublas::zero_matrix<value_type>(p,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -0.120072092580768; expect_K(0,1) = 1.979799862835259;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
matrix_type K = dcs_ctrl::dlqry_solve(A, B, C, D, Q, R, N);
DCS_DEBUG_TRACE("Gain = " << K);
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, K, m, n, tol );
}
DCS_TEST_DEF( oo )
{
DCS_TEST_CASE("oo");
typedef double value_type;
typedef ::std::complex<value_type> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t n = 2; // number of states
const std::size_t m = 1; // number of inputs
const std::size_t p = 2; // number of outputs
matrix_type A(n,n);
A(0,0) = 0.250000000000000000; A(0,1) = 0.80000000000000000;
A(1,0) = -0.988011751199999956; A(1,1) = 1.98799160895100258;
matrix_type B(n,m);
B(0,0) = 0;
B(1,0) = 1;
matrix_type C(p,n);
C(0,0) = 2.011946497e-6; C(0,1) = 0;
C(1,0) = 0.000000000000; C(1,1) = 1;
matrix_type D(p,m);
D(0,0) = 0.5;
D(1,0) = 0.5;
matrix_type Q(n,n);
Q(0,0) = 4.04792870679057178e-12; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 2;
matrix_type R(m,m);
R(0,0) = 0.00810385427000000040;
matrix_type N(ublas::zero_matrix<value_type>(p,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -0.120072092580768; expect_K(0,1) = 1.979799862835259;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 0.062747695129094; expect_S(0,1) = 0.006690561505124;
expect_S(1,0) = 0.006690561505124; expect_S(1,1) = 0.072218977786870;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_type(0.129095068582370, 0.824459776759475);
expect_l(1) = complex_type(0.129095068582370,-0.824459776759475);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqry_controller<value_type> dlqry(Q, R, N);
dlqry.solve(A, B, C, D);
DCS_DEBUG_TRACE("Gain = " << dlqry.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqry.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqry.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqry.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqry.are_solution(), n, n, tol );
vector_type l(dlqry.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( mathematica_1 )
{
DCS_TEST_CASE("Mathematica #1");
// This is the third example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQOutputRegulatorGains.html
typedef double value_type;
typedef ::std::complex<value_type> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t n = 2; // number of states
const std::size_t m = 1; // number of inputs
const std::size_t p = 2; // number of outputs
matrix_type A(n,n);
A(0,0) = -0.05156; A(0,1) = -0.058770;
A(1,0) = 0.01503; A(1,1) = -0.005887;
matrix_type B(n,m);
B(0,0) = 0.00000;
B(1,0) = -0.03384;
matrix_type C(p,n);
C(0,0) = 1.1; C(0,1) = -0.5;
C(1,0) = -0.7; C(1,1) = 1.0;
matrix_type D(p,m);
D(0,0) = 0.1;
D(1,0) = 0.2;
matrix_type Q(p,p);
Q(0,0) = 10; Q(0,1) = 0.0;
Q(1,0) = 0; Q(1,1) = 0.1;
matrix_type R(m,m);
R(0,0) = 1;
matrix_type N(ublas::zero_matrix<value_type>(p,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = 0.972149539638538; expect_K(0,1) = -0.442347371188903;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 11.141022805252103; expect_S(0,1) = -5.057580732711166;
expect_S(1,0) = - 5.057580732711166; expect_S(1,1) = 2.418501386750889;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_type(-0.036208017520516, 0.050803722152156);
expect_l(1) = complex_type(-0.036208017520516,-0.050803722152156);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqry_controller<value_type> dlqry(Q, R, N);
dlqry.solve(A, B, C, D);
DCS_DEBUG_TRACE("Gain = " << dlqry.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqry.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqry.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqry.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqry.are_solution(), n, n, tol );
vector_type l(dlqry.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( mathematica_2 )
{
DCS_TEST_CASE("Mathematica #2");
// This is the third example for discrete-time systems found in the
// Mathematica 8 doc.
// See:
// http://reference.wolfram.com/mathematica/ref/LQOutputRegulatorGains.html
typedef double value_type;
typedef ::std::complex<value_type> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t n = 4; // number of states
const std::size_t m = 2; // number of inputs
const std::size_t p = 2; // number of outputs
matrix_type A(n,n);
A(0,0) = 0.00; A(0,1) = 0.00; A(0,2) = 1; A(0,3) = 0;
A(1,0) = 0.00; A(1,1) = 0.00; A(1,2) = 0; A(1,3) = 1;
A(2,0) = -0.24; A(2,1) = 0.00; A(2,2) = -1; A(2,3) = 0;
A(3,0) = 0.00; A(3,1) = -0.24; A(3,2) = 0; A(3,3) = -1;
matrix_type B(n,m);
B(0,0) = 0; B(0,1) = 0;
B(1,0) = 0; B(1,1) = 0;
B(2,0) = 1; B(2,1) = 0;
B(3,0) = 0; B(3,1) = 1;
matrix_type C(p,n);
C(0,0) = -0.3; C(0,1) = -0.24; C(0,2) = 1; C(0,3) = -0.4;
C(1,0) = 6.0; C(1,1) = -0.20; C(1,2) = 10; C(1,3) = -0.5;
matrix_type D(p,m);
D(0,0) = 0; D(0,1) = 1;
D(1,0) = 0; D(1,1) = 1;
matrix_type Q(ublas::identity_matrix<value_type>(p,p));
matrix_type R(ublas::identity_matrix<value_type>(m,m));
matrix_type N(ublas::identity_matrix<value_type>(p,m));
matrix_type expect_K(m,n); // state-feedback optimal gain
expect_K(0,0) = -0.5727425667891235; expect_K(0,1) = -0.015333480978689376; expect_K(0,2) = -0.6509281335164934; expect_K(0,3) = -0.005825529959808867;
expect_K(1,0) = 2.4734966016228954; expect_K(1,1) = -0.12406716180484925; expect_K(1,2) = 4.353453877275993; expect_K(1,3) = -0.27783321717671866;
matrix_type expect_S(n,n); // solution of the associated Riccati equation
expect_S(0,0) = 6.450086022615284; expect_S(0,1) = 0.29484190309117786; expect_S(0,2) = 7.92070501731365; expect_S(0,3) = 0.3409790812924333;
expect_S(1,0) = 0.2948419030911792; expect_S(1,1) = 0.013477610610715578; expect_S(1,2) = 0.36206582872544446; expect_S(1,3) = 0.015586601618962546;
expect_S(2,0) = 7.920705017313646; expect_S(2,1) = 0.3620658287254433; expect_S(2,2) = 9.726625001794925; expect_S(2,3) = 0.4187222791327824;
expect_S(3,0) = 0.3409790812924328; expect_S(3,1) = 0.015586601618962477; expect_S(3,2) = 0.41872227913278426; expect_S(3,3) = 0.01802560980913717;
vector_type expect_l(n); // closed-loop eigenvalues
expect_l(0) = complex_type(-0.8240762158433446,0);
expect_l(1) = complex_type(-0.5195595835434045,0);
expect_l(2) = complex_type( 0.27784825088463877,0);
expect_l(3) = complex_type(-0.005451100804677363,0);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqry_controller<value_type> dlqry(Q, R, N);
dlqry.solve(A, B, C, D);
DCS_DEBUG_TRACE("Gain = " << dlqry.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqry.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqry.eigenvalues());
DCS_TEST_CHECK_MATRIX_CLOSE( expect_K, dlqry.gain(), m, n, tol );
DCS_TEST_CHECK_MATRIX_CLOSE( expect_S, dlqry.are_solution(), n, n, tol );
vector_type l(dlqry.eigenvalues());
::std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
::std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE( expect_l, l, n, tol );
}
DCS_TEST_DEF( eesim )
{
DCS_TEST_CASE("Mathematica #2");
typedef double value_type;
typedef ::std::complex<value_type> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t nx = 6; // number of states
const std::size_t nu = 6; // number of inputs
const std::size_t ny = 1; // number of outputs
matrix_type A(nx,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 0; A(0,3) = 1; A(0,4) = 0; A(0,5) = 0;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0; A(1,3) = 0; A(1,4) = 1; A(1,5) = 0;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 0; A(2,3) = 0; A(2,4) = 0; A(2,5) = 1;
A(3,0) = -0.0639186388233641; A(3,1) = -0; A(3,2) = -0; A(3,3) = 0.794311427335589; A(3,4) = -0; A(3,5) = -0;
A(4,0) = -0; A(4,1) = -0.0635751341222181; A(4,2) = -0; A(4,3) = -0; A(4,4) = 0.794589468149401; A(4,5) = -0;
A(5,0) = -0; A(5,1) = -0; A(5,2) = -0.063972851249695; A(5,3) = -0; A(5,4) = -0; A(5,5) = 0.794267523469565;
matrix_type B(nx,nu);
B(0,0) = 0; B(0,1) = 0; B(0,2) = 0; B(0,3) = 0; B(0,4) = 0; B(0,5) = 0;
B(1,0) = 0; B(1,1) = 0; B(1,2) = 0; B(1,3) = 0; B(1,4) = 0; B(1,5) = 0;
B(2,0) = 0; B(2,1) = 0; B(2,2) = 0; B(2,3) = 0; B(2,4) = 0; B(2,5) = 0;
B(3,0) = -0.0187739831892682; B(3,1) = -0.0187739831892682; B(3,2) = -0.0187739831892682; B(3,3) = 0.233302674436667; B(3,4) = 0.233302674436667; B(3,5) = 0.233302674436667;
B(4,0) = -0.018657202160102; B(4,1) = -0.018657202160102; B(4,2) = -0.018657202160102; B(4,3) = 0.233185765885323; B(4,4) = 0.233185765885323; B(4,5) = 0.233185765885323;
B(5,0) = -0.0187924305365045; B(5,1) = -0.0187924305365045; B(5,2) = -0.0187924305365045; B(5,3) = 0.233321119359592; B(5,4) = 0.233321119359592; B(5,5) = 0.233321119359592;
matrix_type C(ny,nx);
C(0,0) = 0; C(0,1) = 0; C(0,2) = 0; C(0,3) = 1; C(0,4) = 1; C(0,5) = 1;
matrix_type D(ny,nu);
D(0,0) = 0; D(0,1) = 0; D(0,2) = 0; D(0,3); D(0,4) = 0; D(0,5) = 0;
matrix_type Q(ublas::identity_matrix<value_type>(ny,ny));
matrix_type R(ublas::identity_matrix<value_type>(nu,nu));
//matrix_type N(ublas::identity_matrix<value_type>(ny,nu));
matrix_type N(ublas::zero_matrix<value_type>(ny,nu));
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqry_controller<value_type> dlqry(Q, R, N);
dlqry.solve(A, B, C, D);
DCS_DEBUG_TRACE("Gain = " << dlqry.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqry.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqry.eigenvalues());
}
DCS_TEST_DEF( xxx )
{
DCS_TEST_CASE("XXX");
typedef double value_type;
typedef ::std::complex<value_type> complex_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_type> vector_type;
const std::size_t nx = 3; // number of states
const std::size_t nu = 1; // number of inputs
const std::size_t ny = 1; // number of outputs
matrix_type A(nx,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
matrix_type B(nx,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
matrix_type C(ny,nx);
C(0,0) = 0; C(0,1) = 0; C(0,2) = 1;
matrix_type D(ny,nu);
D(0,0) = 0;
matrix_type Q(ublas::identity_matrix<value_type>(ny,ny));
matrix_type R(ublas::identity_matrix<value_type>(nu,nu));
//matrix_type N(ublas::identity_matrix<value_type>(ny,nu));
matrix_type N(ublas::zero_matrix<value_type>(ny,nu));
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Q = " << Q);
DCS_DEBUG_TRACE("R = " << R);
DCS_DEBUG_TRACE("N = " << N);
dcs_ctrl::dlqry_controller<value_type> dlqry(Q, R, N);
dlqry.solve(A, B, C, D);
DCS_DEBUG_TRACE("Gain = " << dlqry.gain());
DCS_DEBUG_TRACE("Riccati's Solution = " << dlqry.are_solution());
DCS_DEBUG_TRACE("Closed-loop Eigenvalues = " << dlqry.eigenvalues());
}
int main()
{
// Tests labeled with 'mathematica' keyword are taken from the Wolfram
// Mathematica 8 documentation
// (http://reference.wolfram.com/mathematica/ref/LQOutputRegulatorGains.html)
//
// All tests has been validated with MATLAB 2009b
DCS_TEST_BEGIN();
DCS_TEST_DO( free_func );
DCS_TEST_DO( oo );
DCS_TEST_DO( mathematica_1 );
DCS_TEST_DO( mathematica_2 );
DCS_TEST_DO( eesim );
DCS_TEST_DO( xxx );
DCS_TEST_END();
}
<file_sep>/**
* \file dcs/control/design/dlqry.hpp
*
* \brief Infinite-horizon Discrete Linear Quadratic state-feedback Regulator
* with output weighting.
*
* Given a dicrete time-invariant state-space system model:
* \f{align*}{
* \mathbf{x}(k+1) &= \mathbf{A}\mathbf{x}(k)+\mathbf{B}\mathbf{u}(k) \\
* \mathbf{y}(k+1) &= \mathbf{C}\mathbf{x}(k+1)+\mathbf{D}\mathbf{x}(k+1)
* \f}
* subject to initial conditions:
* \f[
* \mathbf{x}(0) = \mathbf{x}_0
* \f]
* where \f$\mathbf{A} \in \mathbb{R}^{n \times n}\f$,
* \f$\mathbf{B} \in \mathbb{R}^{n \times m}\f$,
* \f$\mathbf{C} \in \mathbb{R}^{p \times n}\f$, and
* \f$\mathbf{D} \in \mathbb{R}^{p \times m}\f$,
* and assuming that \f$(A,B)\f$ is \e stabilizable,
* the <em>Infinite-horizon, Discrete Linear Quadratic (LQ) state-feedback
* Regulator</em> controller problem calculates the optimal \e gain matrix
* \f$\mathbf{K}\f$ such that the state-feedback law:
* \f[
* \mathbf{u}(k) = -K\mathbf{x}(k)
* \f]
* minimizes the following quadratic cost function (<em>performance index</em>):
* \f{align*}
* J(\mathbf{u}) &= \sum_{k=1}^{\infty}{\mathbf{y}^T(k)\mathbf{Q}\mathbf{y}(k) + \mathbf{u}^T(k)\mathbf{R}\mathbf{u}(k) + 2\mathbf{y}^T(k)\mathbf{N}\mathbf{u}(k)} \\
* &= \sum_{k=1}^{\infty}{\begin{pmatrix}\mathbf{y}^T(k) & \mathbf{u}^T(k)\end{pmatrix}\begin{pmatrix}\mathbf{Q} & \mathbf{N} \\ \mathbf{N}^T & \mathbf{R}\end{pmatrix}\begin{pmatrix}\mathbf{y}(k) \\ \mathbf{u}(k)\end{pmatrix}}
* \f}
* where:
* - the <em>error weighting matrix</em>
* \f$\mathbf{Q}\in\mathbb{R}^{n \times n}\f$ is a symmetric positive
* semi-definite real matrix that penalizes the output vector
* \f$\mathbf{y}\f$ in the cost function,
* - the <em>control weighting matrix</em>
* \f$\mathbf{R}\in\mathbb{R}^{m \times m}\f$ is a symmetric positive
* definite real matrix that penalizes the input vector
* \f$\mathbf{u}\f$ in the cost function, and
* - the <em>cross-coupling weighting matrix</em>
* \f$\mathbf{N}\in\mathbb{R}^{n \times m}\f$ is a real matrix that
* penalizes the cross product between input and output vectors, such
* that \f$(\mathbf{Q}-\mathbf{N}\mathbf{R}^{-1}\mathbf{N}^{T})\f$ is
* positive semi-definite.
* .
*
* The optimal gain matrix \f$\mathbf{K}\f$ is derived from:
* \f[
* \mathbf{K} = (\mathbf{B}^{T}\mathbf{X}\mathbf{B}+\mathbf{R})^{-1}(\mathbf{B}^{T}\mathbf{X}\mathbf{A}+\mathbf{N}^{T})
* \f]
* where \f$\mathbf{X}\f$ is the stabilizing infinite-horizon solution of the
* associated Discrete-time Algebraic Riccati Equation:
* \f[
* \mathbf{A}^{T}\mathbf{X}+\mathbf{X}\mathbf{A}-(\mathbf{X}\mathbf{B}+\mathbf{N})\mathbf{R}^{-1}(\mathbf{B}^{T}\mathbf{X}+\mathbf{N}^{T})+\mathbf{Q}=\mathbf{0}
* \f]
*
*
* \note
* -# Matrices \f$\mathbf{Q}\f$ and \f$\mathbf{R}\f$ should be symmetric; if they
* are not, they will be replaced with \f$\mathbf{Q}'\f$ and \f$\mathbf{R}'\f$
* such that:
* \f{align*}
* \mathbf{Q}' &= \frac{\mathbf{Q}+\mathbf{Q}^T}{2}, \\
* \mathbf{R}' &= \frac{\mathbf{R}+\mathbf{R}^T}{2}.
* \f}
* -# Such a Discrete-time LQ regulation problem is equivalent to a Discrete-time
* LQ state-feedback regulation problem with the following weighting matrices:
* \f[
* \begin{pmatrix}\mathbf{\bar{Q}} & \mathbf{\bar{N}} \\ \mathbf{\bar{N}}^{T} & \mathbf{\bar{R}}\end{pmatrix} = \begin{pmatrix}\mathbf{C}^{T} & \mathbf{0} \\ \mathbf{D}^{T} & \mathbf{I}\end{pmatrix} \begin{pmatrix}\mathbf{Q} & \mathbf{N} \\ \mathbf{N}^{T} & \mathbf{R}\end{pmatrix} \begin{pmatrix}\mathbf{C} & \mathbf{D} \\ \mathbf{0} & \mathbf{I}\end{pmatrix}
* \f]
* that is:
* \f{align*}
* \mathbf{\bar{Q}} &= \mathbf{C}^{T}\mathbf{Q}\mathbf{C}, \\
* \mathbf{\bar{R}} &= \mathbf{R}+\mathbf{D}^{T}\mathbf{Q}\mathbf{D}+\mathbf{N}^{T}\mathbf{D}+\mathbf{N}\mathbf{D}^T, \\
* \mathbf{\bar{N}} &= \mathbf{C}^{T}\left(\mathbf{Q}\mathbf{D}+\mathbf{N}\right).
* \f}
* .
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_DLQRY_HPP
#define DCS_CONTROL_DLQRY_HPP
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/traits/layout_type.hpp>
#include <complex>
#include <dcs/assert.hpp>
#include <dcs/control/design/dlqr.hpp>
#include <dcs/debug.hpp>
#include <dcs/macro.hpp>
#include <stdexcept>
namespace dcs { namespace control {
namespace detail { namespace /*<unnamed>*/ {
/// Solve the Infinite-horizon, Discrete-time Linear Quadratic Regulator problem.
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
>
void dlqry2dlqr(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
::boost::numeric::ublas::matrix_expression<QMatrixT>& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT>& R,
::boost::numeric::ublas::matrix_expression<NMatrixT>& N)
{
DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(A);
DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(B);
namespace ublasx = ::boost::numeric::ublasx;
namespace ublas = ::boost::numeric::ublas;
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<RMatrixT>::value_type,
typename ::boost::numeric::ublas::matrix_traits<NMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
typedef typename ublasx::layout_type<AMatrixT>::type layout_type;
typedef ublas::matrix<value_type,layout_type> work_matrix_type;
// Derive parameters of equivalent LQR problem
// ND = N'*D
work_matrix_type ND(ublas::prod(ublas::trans(N), D));
// QQ = C'*Q*C
work_matrix_type QQ(ublas::prod(ublas::trans(C), Q));
QQ = ublas::prod(QQ, C);
// RR = R + D'*Q*D + ND + ND';
work_matrix_type RR(ublas::prod(ublas::trans(D), Q)); // R == D'*Q
RR = ublas::prod(RR, D); // RR == D'*Q*D
RR += R + ND + ublas::trans(ND); // RR == D'*Q*D+R+ND+ND'
// NN = C'*(Q*D + N);
work_matrix_type NN(ublas::prod(Q, D) + N); // NN == Q*D+N
NN = ublas::prod(ublas::trans(C), NN); // NN == C'*(Q*D+N)
Q() = QQ;
R() = RR;
N() = NN;
}
}} // Namespace detail::<unnamed>
/**
* \brief Infinite-horizon Discrete Linear Quadratic controller for
* output-feedback regulation.
*
* \tparam RealT The type for real numbers.
*
* \author <NAME>, <EMAIL>
*/
template <typename RealT>
class dlqry_controller
{
public: typedef RealT real_type;
public: typedef ::std::complex<real_type> complex_type;
public: typedef ::boost::numeric::ublas::matrix<real_type> matrix_type;
public: typedef ::boost::numeric::ublas::vector<complex_type> vector_type;
/// Default constructor
public: dlqry_controller()
{
// empty
}
/// A constructor
public: template <
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
> dlqry_controller(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
: Q_(Q),
R_(R),
N_(N)
{
// Empty
}
/// A constructor
public: template <
typename QMatrixT,
typename RMatrixT
> dlqry_controller(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
: Q_(Q),
R_(R),
N_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(Q),::boost::numeric::ublasx::num_rows(R)))
{
// Empty
}
public: template<typename MatrixT>
void Q(::boost::numeric::ublas::matrix_expression<MatrixT> const& X)
{
Q_ = X;
}
public: matrix_type Q() const
{
return Q_;
}
public: matrix_type& Q()
{
return Q_;
}
public: template<typename MatrixT>
void R(::boost::numeric::ublas::matrix_expression<MatrixT> const& X)
{
R_ = X;
}
public: matrix_type R() const
{
return R_;
}
public: matrix_type& R()
{
return R_;
}
public: template<typename MatrixT>
void N(::boost::numeric::ublas::matrix_expression<MatrixT> const& X)
{
N_ = X;
}
public: matrix_type N() const
{
return N_;
}
public: matrix_type& N()
{
return N_;
}
/**
* \brief Solve the Infinite-horizon Discrete-time Linear Quadratic Regulator
* problem.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space
* system model.
* \tparam CMatrixT The type of the output matrix for the state-space
* system model.
* \tparam DMatrixT The type of the feedforward matrix for the state-space
* system model.
*
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \param C The output matrix for the state-space system model.
* \param D The feedforward matrix for the state-space system model.
*/
public: template <typename AMatrixT, typename BMatrixT, typename CMatrixT, typename DMatrixT>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A, ::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C, ::boost::numeric::ublas::matrix_expression<DMatrixT> const& D)
{
// pre: A must be square
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(A) == ::boost::numeric::ublasx::num_columns(A),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Matrix A must be square.")
);
// pre: num_rows(A) == num_rows(B)
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(A) == ::boost::numeric::ublasx::num_rows(B),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices A and B are not conformant.")
);
// pre: num_rows(A) == num_columns(C)
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(A) == ::boost::numeric::ublasx::num_columns(C),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices A and C are not conformant.")
);
// pre: num_columns(B) == num_columns(D)
DCS_ASSERT(
::boost::numeric::ublasx::num_columns(B) == ::boost::numeric::ublasx::num_columns(D),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices B and D are not conformant.")
);
// pre: num_rows(C) == num_rows(D)
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(C) == ::boost::numeric::ublasx::num_rows(D),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices C and D are not conformant.")
);
// pre: Q must be square
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(Q_) == ::boost::numeric::ublasx::num_columns(Q_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Matrix Q must be square.")
);
// pre: num_rows(C) == num_rows(Q)
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(C) == ::boost::numeric::ublasx::num_rows(Q_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices C and Q are not conformant.")
);
// pre: R must be square
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(R_) == ::boost::numeric::ublasx::num_columns(R_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Matrix R must be square.")
);
// pre: num_columns(D) == num_rows(R)
DCS_ASSERT(
::boost::numeric::ublasx::num_columns(D) == ::boost::numeric::ublasx::num_rows(R_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices D and R are not conformant.")
);
// pre: num_rows(N) == num_rows(Q)
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(N_) == ::boost::numeric::ublasx::num_rows(Q_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices N and Q are not conformant.")
);
// pre: num_rows(N) == num_rows(R)
DCS_ASSERT(
::boost::numeric::ublasx::num_columns(N_) == ::boost::numeric::ublasx::num_rows(R_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller] Size of matrices N and R are not conformant.")
);
matrix_type QQ(Q_);
matrix_type RR(R_);
matrix_type NN(N_);
detail::dlqry2dlqr(A, B, C, D, QQ, RR, NN);
dlqr_controller<real_type> lq(QQ, RR, NN);
lq.solve(A, B);
K_ = lq.gain();
S_ = lq.are_solution();
e_ = lq.eigenvalues();
}
/// Return the optimal state-feedback matrix gain.
public: matrix_type gain() const
{
return K_;
}
/// Return the associated DARE solution.
public: matrix_type are_solution() const
{
return S_;
}
/// Return the closed-loop eigenvalues.
public: vector_type eigenvalues() const
{
return e_;
}
public: template <typename VectorExprT>
vector_type control(::boost::numeric::ublas::vector_expression<VectorExprT> const& x) const
{
// pre: size(x) == num_columns(K_)
DCS_ASSERT(
::boost::numeric::ublasx::size(x) == ::boost::numeric::ublasx::num_columns(K_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller::control] Wrong state dimensiion.")
);
return -::boost::numeric::ublas::prod(K_, x);
}
public: template <typename MatrixExprT>
matrix_type control(::boost::numeric::ublas::matrix_expression<MatrixExprT> const& X) const
{
// pre: num_columns(X) == num_columns(K_)
DCS_ASSERT(
::boost::numeric::ublasx::num_columns(X) == ::boost::numeric::ublasx::num_columns(K_),
throw ::std::invalid_argument("[dcs::control::dlqry_controller::control] Wrong state dimensiion.")
);
return -::boost::numeric::ublas::prod(K_, ::boost::numeric::ublas::trans(X));
}
/// The error weigthed matrix.
private: matrix_type Q_;
/// The control weigthed matrix.
private: matrix_type R_;
/// The cross-coupling weigthed matrix.
private: matrix_type N_;
/// The optimal feedback gain matrix.
private: matrix_type K_;
/// The solution to the associated DARE.
private: matrix_type S_;
/// The closed-loop eigenvalues.
private: vector_type e_;
};
/**
* \brief Infinite-horizon Discrete Linear Quadratic Controller design with
* weighting output.
*
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
* \tparam NMatrixT The type of the cross-coupling weighting matrix.
*
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \param N The cross-coupling weighting matrix.
* \return An object representing an Infinite-horizon Discrete-time Linear
* Quadratic state-feedback Regulator controller.
*/
template <
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
>
inline
dlqry_controller<
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<RMatrixT>::value_type,
typename boost::numeric::ublas::matrix_traits<NMatrixT>::value_type
>::promote_type
>::promote_type
> dlqry(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<RMatrixT>::value_type,
typename boost::numeric::ublas::matrix_traits<NMatrixT>::value_type
>::promote_type
>::promote_type value_type;
return dlqry_controller<value_type>(Q, R, N);
}
/**
* \brief Infinite-horizon Discrete Linear Quadratic Controller design with
* weighting output.
*
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
*
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \return An object representing an Infinite-horizon Discrete-time Linear
* Quadratic state-feedback Regulator controller.
*/
template <
typename QMatrixT,
typename RMatrixT
>
inline
dlqry_controller<
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename boost::numeric::ublas::matrix_traits<RMatrixT>::value_type
>::promote_type
> dlqry(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename boost::numeric::ublas::matrix_traits<RMatrixT>::value_type
>::promote_type value_type;
return dlqry_controller<value_type>(Q, R);
}
/**
* \brief Optimal state-feedback control by Infinite-horizon Discrete Linear
* Quadratic Controller design with weighting output.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam CMatrixT The type of the output matrix for the controlled state-space
* model.
* \tparam DMatrixT The type of the feeforward matrix for the controlled
* state-space model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
* \tparam NMatrixT The type of the cross-coupling weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param C The output matrix for the controlled state-space model.
* \param D The feedforward matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \param N The cross-coupling weighting matrix.
* \return The optimal state-feedback gain matrix \f$\mathbf{K}\f$.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
>
inline
//::boost::numeric::ublas::matrix<double> dlqry_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
//typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type dlqr_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<RMatrixT>::value_type,
typename ::boost::numeric::ublas::matrix_traits<NMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type,
typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type
> dlqry_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<RMatrixT>::value_type,
typename ::boost::numeric::ublas::matrix_traits<NMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
//typedef typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type out_matrix_type; //this doesn't work if A and B have different value types
typedef ::boost::numeric::ublas::matrix<value_type, typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type> out_matrix_type;
out_matrix_type QQ(Q);
out_matrix_type RR(R);
out_matrix_type NN(N);
detail::dlqry2dlqr(A, B, C, D, QQ, RR, NN);
return dlqr_solve(A, B, QQ, RR, NN);
}
/**
* \brief Optimal state-feedback control by Infinite-horizon Discrete Linear
* Quadratic Controller design with weighting output.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam CMatrixT The type of the output matrix for the controlled state-space
* model.
* \tparam DMatrixT The type of the feedforward matrix for the controlled
* state-space model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param C The output matrix for the controlled state-space model.
* \param D The feedforward matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \return The optimal state-feedback gain matrix \f$\mathbf{K}\f$.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename QMatrixT,
typename RMatrixT
>
inline
//typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type dlqr_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::matrix_traits<RMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type,
typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type
> dlqry_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<QMatrixT>::value_type,
typename ::boost::numeric::ublas::matrix_traits<RMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
//typedef typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type out_matrix_type; //this doesn't work if A and B have different value types
typedef ::boost::numeric::ublas::matrix<value_type, typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type> out_matrix_type;
out_matrix_type QQ(Q);
out_matrix_type RR(R);
out_matrix_type NN(
::boost::numeric::ublas::zero_matrix<value_type>(
::boost::numeric::ublasx::num_rows(Q),
::boost::numeric::ublasx::num_rows(R)
)
);
detail::dlqry2dlqr(A, B, C, D, QQ, RR, NN);
return dlqr_solve(A, B, QQ, RR, NN);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_DLQRY_HPP
<file_sep>#!/bin/sh
epacsim_path=$PWD
xmldoc=$1
xmllint --noout --schema $epacsim_path/setup/conf/epacsim_config.xsd $xmldoc
<file_sep>/**
* \file dcs/control/analysis/detectability.hpp
*
* \brief Detectability analysis for linear systems.
*
* A system:
* - continuous-time case: \f$\dot{x}=Ax,\quad y=Cxf$
* - discrete-time case: \f$x(k+1)=Ax(k)\quad y(k)=Cx(k)\f$
* is detectable if all its unobservable modes decay to zero asymptotically.
*
* The detectability test can be performed in different ways:
* - Eigenvector test [1]:
* - The continuous-time LTI system is detectable if and only if every
* eigenvector of A^T corresponding to an eigenvalue with a positive or zero
* real part is not in the kernel of C.
* - The discrete-time LTI system is detectable if and only if every
* eigenvector of A^T corresponding to an eigenvalue with magnitude larger
* or equal to 1 is not in the kernel of C.
* .
* - Popov-Belevitch-Hautus [PBH] test [1,2]:
* - The continuous-time LTI system is detectable if and only if
* \f[
* \operatorname{rank}(\begin{pmatrix}A - \lambda I \\ C\end{pmatrix}) = n, \quad \forall\lambda\in\mathbb{C}: \Re[\lambda] \ge 0
* \f]
* - The discrete-time LTI system is detectable if and only if
* \f[
* \operatorname{rank}(\begin{pmatrix}A - \lambda I \\ C\end{pmatrix}) = n, \quad \forall\lambda\in\mathbb{C}: |\lambda| \ge 1
* \f]
* .
* - Lyapunov test [1]:
* The LTI system (AB-LTI) is detectable if and only if there is a
* positive-definite solution \f$P\f$ to the following Lyapunov matrix
* inequality:
* - Continuous-time case: \f$A^{T}P + PA - C^{T}C < 0\f$
* - Discrete-time case: \f$A^{T}PA - P - C^{T}C < 0\f$
* .
* - Stabilization test [2]:
* The matrix pair \f$(C,A)\f$ is detectable if and only if the dual par \f$(A^T,C^T)\f$ is stabilizable.
* .
*
* \note
* Estimating the rank of a matrix is ill-conditioned; that is, it is very
* sensitive to roundoff errors and errors in the data.
*
* \todo
* Implement other (more numerically robust) tests (e.g., see Octave and SCILAB).
*
*
* References:
* -# <NAME>, "Linear Systems Theory", Princeton University Press, 2009.
* -# <NAME>, "Stability and Stabilization: An Introduction", Princeton University Press, 2009
* .
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2011 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_ANALYSIS_DETECTABILITY_HPP
#define DCS_CONTROL_ANALYSIS_DETECTABILITY_HPP
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublasx/operation/eigen.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <cmath>
#include <complex>
#include <dcs/assert.hpp>
#include <dcs/macro.hpp>
#include <stdexcept>
namespace dcs { namespace control {
template <
typename AMatrixT,
typename CMatrixT,
typename RealT
>
bool is_detectable(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
bool discrete,
RealT tol)
{
DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING( tol );
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
// pre: A must be square
DCS_ASSERT(
ublasx::num_rows(A) == ublasx::num_columns(A),
throw ::std::invalid_argument("[dcs::control::is_detectable] The A matrix must be square.")
);
// pre: num_rows(A) == num_rows(B)
DCS_ASSERT(
ublasx::num_rows(A) == ublasx::num_columns(C),
throw ::std::invalid_argument("[dcs::control::is_detectable] The size of A and C matrices are not conformant.")
);
typedef typename ublas::promote_traits<typename AMatrixT::value_type,
typename CMatrixT::value_type>::promote_type value_type;
typedef typename ublas::promote_traits<typename AMatrixT::size_type,
typename CMatrixT::size_type>::promote_type size_type;
typedef typename ublas::type_traits<value_type>::real_type real_type;
typedef ::std::complex<real_type> complex_type;
// Use the Popov-Belevitch-Hautus [PBH] test for detectability.
// E.g., see Hespanha, "Linear System Theory", 2009, pp.152-153.
ublas::vector<complex_type> v;
ublasx::eigenvalues(A, v);
size_type nv(ublasx::size(v));
size_type na(ublas::num_rows(A));
size_type nc(ublas::num_rows(C));
size_type ns(na+nc);
ublas::matrix<complex_type> cA(A);
ublas::identity_matrix<complex_type> I(na);
for (size_type i = 0; i < nv; ++i)
{
if (discrete)
{
if (::std::abs(v(i)) < 1)
{
continue;
}
}
else
{
if (v(i).real() < 0)
{
continue;
}
}
//ublas::matrix<complex_type> AA(ublas::matrix<complex_type>(A)-v(i)*I);
ublas::matrix<complex_type> S(ns,na,0);
ublas::subrange(S, 0, na, 0, na) = cA-v(i)*I;
ublas::subrange(S, na, ns, 0, na) = C;
if (ublasx::rank(S) != na)
{
return false;
}
}
return true;
}
template <
typename AMatrixT,
typename BMatrixT
>
inline
bool is_detectable(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
bool discrete)
{
return is_detectable(A, B, discrete, 0.0);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_ANALYSIS_DETECTABILITY_HPP
<file_sep>/**
* \file test/src/dcs/control/dare.cpp
*
* \brief Test suite for the DARE solvers.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-control (below referred to as "this program").
*
* 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/>.
*/
#include <algorithm>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <complex>
#include <dcs/control/solver/dare.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <iostream>
#include "./utility.hpp"
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
namespace dcs_control = dcs::control;
const double tol = 1e-5;
DCS_TEST_DEF( test_1 )
{
DCS_TEST_CASE("Test #1");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 0.786939;
A(1,0) = 0; A(1,1) = 0.606531;
matrix_type B(n,m);
B(0,0) = 0.426123;
B(1,0) = 0.786939;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 1;
matrix_type R;
R = ublas::identity_matrix<value_type>(m);
matrix_type S;
S = ublas::zero_matrix<value_type>(n,m);
matrix_type E;
E = ublas::identity_matrix<value_type>(n);
matrix_type X;
matrix_type expect_X(n,n);
expect_X(0,0) = 2.401533210017093; expect_X(0,1) = 1.057915121181177;
expect_X(1,0) = 1.057915121181177; expect_X(1,1) = 2.097053494085709;
dcs_control::dare(A, B, Q, R, S, E, X);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "E = " << E );
DCS_DEBUG_TRACE( "Solution X = " << X );
DCS_TEST_CHECK_MATRIX_CLOSE(X, expect_X, n, n, tol);
}
DCS_TEST_DEF( test_2 )
{
DCS_TEST_CASE("Test #2");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 0.786939;
A(1,0) = 0; A(1,1) = 0.606531;
matrix_type B(n,m);
B(0,0) = 0.426123;
B(1,0) = 0.786939;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 1;
matrix_type R;
R = ublas::identity_matrix<value_type>(m);
matrix_type S;
S = ublas::zero_matrix<value_type>(n,m);
matrix_type E;
E = ublas::identity_matrix<value_type>(n);
matrix_type expect_X(n,n);
expect_X(0,0) = 2.401533210017093; expect_X(0,1) = 1.057915121181177;
expect_X(1,0) = 1.057915121181177; expect_X(1,1) = 2.097053494085709;
// vector_type expect_L(n);
// expect_L(0) = std::complex<value_type>(0.376036021533870, 0.186272944433102);
// expect_L(1) = std::complex<value_type>(0.376036021533870,-0.186272944433102);
matrix_type expect_G(m,n);
expect_G(0,0) = 0.538832818098109; expect_G(0,1) = 0.794025839341854;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "E = " << E );
DCS_DEBUG_TRACE( "Solution X = " << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
}
DCS_TEST_DEF( test_3 )
{
DCS_TEST_CASE("Test #3");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< ::std::complex<value_type> > vector_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 0.4; A(0,1) = 1.7;
A(1,0) = 0.9; A(1,1) = 3.8;
matrix_type B(n,m);
B(0,0) = 0.8;
B(1,0) = 2.1;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = -1;
Q(1,0) = -1; Q(1,1) = 1;
matrix_type R;
R = ublas::scalar_matrix<value_type>(m, m, 3);
matrix_type expect_X(n,n);
expect_X(0,0) = 1.53536988885652; expect_X(0,1) = 1.26226249343861;
expect_X(1,0) = 1.26226249343861; expect_X(1,1) = 10.5595806602029;
vector_type expect_l(n);
expect_l(0) = ::std::complex<value_type>(-0.0022307284532799,0);
expect_l(1) = ::std::complex<value_type>( 0.245448650750199,0);
matrix_type expect_G(m,n);
expect_G(0,0) = 0.409151396044144; expect_G(0,1) = 1.72831474327036;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_4 )
{
DCS_TEST_CASE("Test #4");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< ::std::complex<value_type> > vector_type;
const std::size_t n(3);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
matrix_type Q(n, n, 0);
Q(n-1,n-1) = 1;
matrix_type R(m, m, 1);
matrix_type ok_X(n,n);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
vector_type ok_l(n);
ok_l(0) = std::complex<value_type>( 1.43580766234971e-17,0);
ok_l(1) = std::complex<value_type>( 1.74854855048411e-01,0);
ok_l(2) = std::complex<value_type>(-6.53180872996730e-01,0);
matrix_type ok_G(m,n);
ok_G(0,0) = 0.183674170154323; ok_G(0,1) = -0.425466103638352; ok_G(0,2) = -0.785400393763966;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
vector_type l(solver.eigenvalues());
std::sort(l.begin(), l.end(), detail::complex_cmp<value_type>());
std::sort(ok_l.begin(), ok_l.end(), detail::complex_cmp<value_type>());
//DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), ok_X, n, n, tol);
//DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), ok_G, m, n, tol);
//DCS_TEST_CHECK_VECTOR_CLOSE(l, ok_l, n, tol);
DCS_TEST_CHECK_VECTOR_CLOSE(solver.solution().data().begin(), ok_X.data().begin(), n*n, tol);
DCS_TEST_CHECK_VECTOR_CLOSE(l.data().begin(), ok_l.data().begin(), n, tol);
DCS_TEST_CHECK_VECTOR_CLOSE(solver.gain().data().begin(), ok_G.data().begin(), n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_1 )
{
DCS_TEST_CASE("DAREX Ex. 1.1");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 2; A(0,1) = -1;
A(1,0) = 1; A(1,1) = 0;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 0;
matrix_type Q(n,n);
Q(0,0) = 0; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 1;
matrix_type R(m,m);
R(0,0) = 0;
matrix_type expect_X(n,n);
expect_X(0,0) = 1.0; expect_X(0,1) = 0.0;
expect_X(1,0) = 0.0; expect_X(1,1) = 1.0;
vector_type expect_l(n);
expect_l(0) = 0.0;
expect_l(1) = 0.0;
matrix_type expect_G(m,n);
expect_G(0,0) = 2.0; expect_G(0,1) = -1.0;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_2 )
{
DCS_TEST_CASE("DAREX Ex. 1.2");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(2);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = 0; A(1,1) = -1;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = 0;
B(1,0) = 2; B(1,1) = 1;
matrix_type Q(n,n);
Q(0,0) = -4.0/11.0; Q(0,1) = -4.0/11.0;
Q(1,0) = -4.0/11.0; Q(1,1) = 7.0/11.0;
matrix_type R(m,m);
R(0,0) = 9; R(0,1) = 3;
R(1,0) = 3; R(1,1) = 1;
matrix_type S(n,m);
S(0,0) = 3; S(0,1) = 1;
S(1,0) = -1; S(1,1) = 7;
matrix_type expect_X(n,n);
expect_X(0,0) = -0.014021341244239*1e+2; expect_X(0,1) = 0.130568663991581*1e+2;
expect_X(1,0) = 0.130568663991581*1e+2; expect_X(1,1) = -1.256364927952908*1e+2;
vector_type expect_l(n);
expect_l(0) = -0.217058149756746;
expect_l(1) = 0.687271691663810;
matrix_type expect_G(m,n);
expect_G(0,0) = 0.940453958559404; expect_G(0,1) = -11.009835262327730;
expect_G(1,0) = -1.782864114890681; expect_G(1,1) = 19.609003024189001;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_3 )
{
DCS_TEST_CASE("DAREX Ex. 1.3");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = 0; A(1,1) = 0;
matrix_type B(n,m);
B(0,0) = 0;
B(1,0) = 1;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 2;
Q(1,0) = 2; Q(1,1) = 4;
matrix_type R(m,m);
R(0,0) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 1; expect_X(0,1) = 2;
expect_X(1,0) = 2; expect_X(1,1) = 2+std::sqrt(5);
vector_type expect_l(n);
expect_l(0) = 0.0;
expect_l(1) = -0.381966011250105;
matrix_type expect_G(m,n);
expect_G(0,0) = 0.0; expect_G(0,1) = 0.381966011250105;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_4 )
{
DCS_TEST_CASE("DAREX Ex. 1.4");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(3);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 0.0; A(0,1) = 0.1; A(0,2) = 0.0;
A(1,0) = 0.0; A(1,1) = 0.0; A(1,2) = 0.1;
A(2,0) = 0.0; A(2,1) = 0.0; A(2,2) = 0.0;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = 0;
B(1,0) = 0; B(1,1) = 0;
B(2,0) = 0; B(2,1) = 1;
matrix_type Q(n,n);
Q(0,0) = 1e+5; Q(0,1) = 0; Q(0,2) = 0;
Q(1,0) = 0; Q(1,1) = 1e+3; Q(1,2) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = -10;
matrix_type R(m,m);
R(0,0) = 0; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 1e+5; expect_X(0,1) = 0; expect_X(0,2) = 0;
expect_X(1,0) = 0; expect_X(1,1) = 1e+3; expect_X(1,2) = 0;
expect_X(2,0) = 0; expect_X(2,1) = 0; expect_X(2,2) = 0;
vector_type expect_l(n);
//This is the result we got with MATLAB 2008a
//expect_l(0) = -1.0e-14*0.195676808090185;
//expect_l(1) = 1.0e-14*0.0;
//expect_l(2) = 1.0e-14*0.0;
//Instead, this is the one we got with SLICOT 5.0
expect_l(0) = 0;
expect_l(1) = 0;
expect_l(2) = 0;
matrix_type expect_G(m,n);
expect_G(0,0) = 0.0; expect_G(0,1) = 0.100000000000000; expect_G(0,2) = 0;
expect_G(1,0) = 0.0; expect_G(1,1) = 0.0; expect_G(1,2) = -0.000000000000000;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_5 )
{
DCS_TEST_CASE("DAREX Ex. 1.5");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(4);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 0.998; A(0,1) = 0.067; A(0,2) = 0.000; A(0,3) = 0.000;
A(1,0) = -0.067; A(1,1) = 0.998; A(1,2) = 0.100; A(1,3) = 0.000;
A(2,0) = 0.000; A(2,1) = 0.000; A(2,2) = 0.998; A(2,3) = 0.153;
A(3,0) = 0.000; A(3,1) = 0.000; A(3,2) = -0.153; A(3,3) = 0.998;
matrix_type B(n,m);
B(0,0) = 0.0033; B(0,1) = 0.0200;
B(1,0) = 0.1000; B(1,1) = -0.0007;
B(2,0) = 0.0400; B(2,1) = 0.0073;
B(3,0) = -0.0028; B(3,1) = 0.1000;
matrix_type Q(n,n);
Q(0,0) = 1.870; Q(0,1) = 0.000; Q(0,2) = 0.000; Q(0,3) = -0.244;
Q(1,0) = 0.000; Q(1,1) = 0.744; Q(1,2) = 0.205; Q(1,3) = 0.000;
Q(2,0) = 0.000; Q(2,1) = 0.205; Q(2,2) = 0.589; Q(2,3) = 0.000;
Q(3,0) = -0.244; Q(3,1) = 0.000; Q(3,2) = 0.000; Q(3,3) = 1.048;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 30.707390002658851; expect_X(0,1) = 7.731389771619265; expect_X(0,2) = 3.966329567211186; expect_X(0,3) = - 4.901197596654572;
expect_X(1,0) = 7.731389771619265; expect_X(1,1) = 11.829796382196321; expect_X(1,2) = 5.164569890757084; expect_X(1,3) = 0.278956010969016;
expect_X(2,0) = 3.966329567211186; expect_X(2,1) = 5.164569890757084; expect_X(2,2) = 17.132194857924887; expect_X(2,3) = 1.573172972387152;
expect_X(3,0) = - 4.901197596654572; expect_X(3,1) = 0.278956010969016; expect_X(3,2) = 1.573172972387152; expect_X(3,3) = 14.880017305642824;
vector_type expect_l(n);
expect_l(0) = std::complex<value_type>(0.924483957358999, 0.065175187407696);
expect_l(1) = std::complex<value_type>(0.924483957358999,-0.065175187407696);
expect_l(2) = std::complex<value_type>(0.921554823634630, 0.141844900635441);
expect_l(3) = std::complex<value_type>(0.921554823634630,-0.141844900635441);
matrix_type expect_G(m,n);
expect_G(0,0) = 0.793645328788861; expect_G(0,1) = 1.237433329574766; expect_G(0,2) = 1.123694684785059; expect_G(0,3) = 0.148799363279981;
expect_G(1,0) = 0.093940974504011; expect_G(1,1) = 0.158621967953197; expect_G(1,2) = 0.111849254879984; expect_G(1,3) = 1.264446426229076;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_6 )
{
DCS_TEST_CASE("DAREX Ex. 1.6");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(4);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 1e-3* 984.750; A(0,1) = -1e-3* 79.903; A(0,2) = 1e-3* 0.9054; A(0,3) = -1e-3* 1.0765;
A(1,0) = 1e-3* 41.588; A(1,1) = 1e-3*998.990; A(1,2) = -1e-3* 35.8550; A(1,3) = 1e-3* 12.6840;
A(2,0) = -1e-3* 546.620; A(2,1) = 1e-3* 44.916; A(2,2) = -1e-3*329.9100; A(2,3) = 1e-3*193.1800;
A(3,0) = 1e-3*2662.400; A(3,1) = -1e-3*100.450; A(3,2) = -1e-3*924.5500; A(3,3) = -1e-3*263.2500;
matrix_type B(n,m);
B(0,0) = 1e-4* 37.112; B(0,1) = 1e-4*7.361000;
B(1,0) = -1e-4* 870.510; B(1,1) = 1e-4*0.093411;
B(2,0) = -1e-4*11984.000; B(2,1) = 1e-4*4.137800;
B(3,0) = -1e-4*31927.000; B(3,1) = 1e-4*9.253500;
matrix_type Q(n,n);
Q(0,0) = 0.01; Q(0,1) = 0.00; Q(0,2) = 0.00; Q(0,3) = 0.00;
Q(1,0) = 0.00; Q(1,1) = 0.01; Q(1,2) = 0.00; Q(1,3) = 0.00;
Q(2,0) = 0.00; Q(2,1) = 0.00; Q(2,2) = 0.01; Q(2,3) = 0.00;
Q(3,0) = 0.00; Q(3,1) = 0.00; Q(3,2) = 0.00; Q(3,3) = 0.01;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 1.845979749417746; expect_X(0,1) = -0.056190418825482; expect_X(0,2) = -0.011141163569509; expect_X(0,3) = -0.010550944100757;
expect_X(1,0) = -0.056190418825482; expect_X(1,1) = 2.047915333938012; expect_X(1,2) = -0.059430745710932; expect_X(1,3) = 0.012336403378050;
expect_X(2,0) = -0.011141163569509; expect_X(2,1) = -0.059430745710932; expect_X(2,2) = 0.022799689365452; expect_X(2,3) = 0.000808498679231;
expect_X(3,0) = -0.010550944100757; expect_X(3,1) = 0.012336403378050; expect_X(3,2) = 0.000808498679231; expect_X(3,3) = 0.011514128775705;
vector_type expect_l(n);
expect_l(0) = std::complex<value_type>(-0.265900128787536,+0.397166041362223);
expect_l(1) = std::complex<value_type>(-0.265900128787536,-0.397166041362223);
expect_l(2) = std::complex<value_type>( 0.985894853633392,+0.074733641936961);
expect_l(3) = std::complex<value_type>( 0.985894853633392,-0.074733641936961);
matrix_type expect_G(m,n);
expect_G(0,0) = -0.032648216905453; expect_G(0,1) = -0.127202840052208; expect_G(0,2) = 0.042338962051211; expect_G(0,3) = 0.003014183257250;
expect_G(1,0) = 0.001329925628570; expect_G(1,1) = -0.000143573351369; expect_G(1,2) = -0.000000888234976; expect_G(1,3) = -0.000002486099077;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_7 )
{
DCS_TEST_CASE("DAREX Ex. 1.7");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(4);
const std::size_t m(4);
matrix_type A(n,n);
A(0,0) = -0.6; A(0,1) = -2.2; A(0,2) = -3.6; A(0,3) = -5.400018;
A(1,0) = 1.0; A(1,1) = 0.6; A(1,2) = 0.8; A(1,3) = 3.399982;
A(2,0) = 0.0; A(2,1) = 1.0; A(2,2) = 1.8; A(2,3) = 3.799982;
A(3,0) = 0.0; A(3,1) = 0.0; A(3,2) = 0.0; A(3,3) = -0.999982;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = -1; B(0,2) = -1; B(0,3) = -1;
B(1,0) = 0; B(1,1) = 1; B(1,2) = -1; B(1,3) = -1;
B(2,0) = 0; B(2,1) = 0; B(2,2) = 1; B(2,3) = -1;
B(3,0) = 0; B(3,1) = 0; B(3,2) = 0; B(3,3) = 1;
matrix_type Q(n,n);
Q(0,0) = 2; Q(0,1) = 1; Q(0,2) = 3; Q(0,3) = 6;
Q(1,0) = 1; Q(1,1) = 2; Q(1,2) = 2; Q(1,3) = 5;
Q(2,0) = 3; Q(2,1) = 2; Q(2,2) = 6; Q(2,3) = 11;
Q(3,0) = 6; Q(3,1) = 5; Q(3,2) = 11; Q(3,3) = 22;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0; R(0,2) = 0; R(0,3) = 0;
R(1,0) = 0; R(1,1) = 1; R(1,2) = 0; R(1,3) = 0;
R(2,0) = 0; R(2,1) = 0; R(2,2) = 1; R(2,3) = 0;
R(3,0) = 0; R(3,1) = 0; R(3,2) = 0; R(3,3) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 2.817800285785478; expect_X(0,1) = 2.210160220269767; expect_X(0,2) = 4.997305238829639; expect_X(0,3) = 10.025262087702128;
expect_X(1,0) = 2.210160220269767; expect_X(1,1) = 4.530484712640063; expect_X(1,2) = 6.257605864699351; expect_X(1,3) = 12.998245151137297;
expect_X(2,0) = 4.997305238829639; expect_X(2,1) = 6.257605864699351; expect_X(2,2) = 13.192802180652688; expect_X(2,3) = 24.447703263082389;
expect_X(3,0) = 10.025262087702128; expect_X(3,1) = 12.998245151137297; expect_X(3,2) = 24.447703263082389; expect_X(3,3) = 47.471191943996843;
vector_type expect_l(n);
expect_l(0) = 0.067912325238694;
expect_l(1) = 0.163207174929605;
expect_l(2) = 0.348653414955625;
expect_l(3) = -0.999981999984721;
matrix_type expect_G(m,n);
expect_G(0,0) = 0.250004803979136; expect_G(0,1) = 0.216553352201969; expect_G(0,2) = 0.460193182636258; expect_G(0,3) = 0.926746747874340;
expect_G(1,0) = 0.717798364193832; expect_G(1,1) = 1.123538879388990; expect_G(1,2) = 1.813227965775154; expect_G(1,3) = 3.654563388552431;
expect_G(2,0) = -0.038319084032009; expect_G(2,1) = 0.646201164736901; expect_G(2,2) = 1.172363846404621; expect_G(2,3) = 1.780245030303713;
expect_G(3,0) = -0.000001137431440; expect_G(3,1) = -0.000001872546490; expect_G(3,2) = -0.000003258144388; expect_G(3,3) = -0.000007034919287;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
// NOTE: With a tolerance of 10^{-5} some check on the X matrix fails
// This may be caused by the difference in the algorithms used by
// our library and MATLAB.
// So we decided to lower the precision to 10^{-4}
const double tol2 = 1e-4;
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol2);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_8 )
{
DCS_TEST_CASE("DAREX Ex. 1.8");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(5);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 1e-4*9540.70; A(0,1) = 1e-4* 196.43; A(0,2) = 1e-4* 35.97; A(0,3) = 1e-4* 6.73; A(0,4) = 1e-4* 1.90;
A(1,0) = 1e-4*4084.90; A(1,1) = 1e-4*4131.70; A(1,2) = 1e-4*1608.40; A(1,3) = 1e-4* 446.79; A(1,4) = 1e-4* 119.71;
A(2,0) = 1e-4*1221.70; A(2,1) = 1e-4*2632.60; A(2,2) = 1e-4*3614.90; A(2,3) = 1e-4*1593.00; A(2,4) = 1e-4*1238.30;
A(3,0) = 1e-4* 411.18; A(3,1) = 1e-4*1285.80; A(3,2) = 1e-4*2720.90; A(3,3) = 1e-4*2144.20; A(3,4) = 1e-4*4097.60;
A(4,0) = 1e-4* 13.05; A(4,1) = 1e-4* 58.08; A(4,2) = 1e-4* 187.50; A(4,3) = 1e-4* 361.62; A(4,4) = 1e-4*9428.00;
matrix_type B(n,m);
B(0,0) = 1e-4* 4.34; B(0,1) = -1e-4* 1.22;
B(1,0) = 1e-4*266.06; B(1,1) = -1e-4*104.53;
B(2,0) = 1e-4*375.30; B(2,1) = -1e-4*551.00;
B(3,0) = 1e-4*360.76; B(3,1) = -1e-4*660.00;
B(4,0) = 1e-4* 46.17; B(4,1) = -1e-4* 91.48;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 0; Q(0,2) = 0; Q(0,3) = 0; Q(0,4) = 0;
Q(1,0) = 0; Q(1,1) = 1; Q(1,2) = 0; Q(1,3) = 0; Q(1,4) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 1; Q(2,3) = 0; Q(2,4) = 0;
Q(3,0) = 0; Q(3,1) = 0; Q(3,2) = 0; Q(3,3) = 1; Q(3,4) = 0;
Q(4,0) = 0; Q(4,1) = 0; Q(4,2) = 0; Q(4,3) = 0; Q(4,4) = 1;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type expect_X(n,n);
expect_X(0,0) = 60.456378667853016; expect_X(0,1) = 4.672669320499056; expect_X(0,2) = 3.391010077549930; expect_X(0,3) = 2.183442069546651; expect_X(0,4) = 24.049867925873606;
expect_X(1,0) = 4.672669320499056; expect_X(1,1) = 1.800604768836491; expect_X(1,2) = 0.643306876604517; expect_X(1,3) = 0.368582157291515; expect_X(1,4) = 2.810035381375605;
expect_X(2,0) = 3.391010077549930; expect_X(2,1) = 0.643306876604517; expect_X(2,2) = 1.617206256697997; expect_X(2,3) = 0.373785641698017; expect_X(2,4) = 2.685608599483135;
expect_X(3,0) = 2.183442069546651; expect_X(3,1) = 0.368582157291515; expect_X(3,2) = 0.373785641698017; expect_X(3,3) = 1.246083057616368; expect_X(3,4) = 2.056868888863928;
expect_X(4,0) = 24.049867925873606; expect_X(4,1) = 2.810035381375605; expect_X(4,2) = 2.685608599483135; expect_X(4,3) = 2.056868888863928; expect_X(4,4) = 27.429360377605320;
vector_type expect_l(n);
expect_l(0) = 0.240702660917670;
expect_l(1) = 0.050274226759839;
expect_l(2) = 0.632461076685746;
expect_l(3) = 0.976994439625731;
expect_l(4) = 0.958597232843032;
matrix_type expect_G(m,n);
expect_G(0,0) = 0.488379469793936; expect_G(0,1) = 0.088047339574689; expect_G(0,2) = 0.081945427902266; expect_G(0,3) = 0.050798306322876; expect_G(0,4) = 0.397748565018305;
expect_G(1,0) = -0.624013969453445; expect_G(1,1) = -0.109166256049604; expect_G(1,2) = -0.112656060538442; expect_G(1,3) = -0.073282793503359; expect_G(1,4) = -0.585936198398728;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_9 )
{
DCS_TEST_CASE("DAREX Ex. 1.9");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(6);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1; A(0,2) = 0; A(0,3) = 0; A(0,4) = 0; A(0,5) = 0;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 1; A(1,3) = 0; A(1,4) = 0; A(1,5) = 0;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 0; A(2,3) = 0; A(2,4) = 0; A(2,5) = 0;
A(3,0) = 0; A(3,1) = 0; A(3,2) = 0; A(3,3) = 0; A(3,4) = 1; A(3,5) = 0;
A(4,0) = 0; A(4,1) = 0; A(4,2) = 0; A(4,3) = 0; A(4,4) = 0; A(4,5) = 1;
A(5,0) = 0; A(5,1) = 0; A(5,2) = 0; A(5,3) = 0; A(5,4) = 0; A(5,5) = 0;
matrix_type B(n,m);
B(0,0) = 0; B(0,1) = 0;
B(1,0) = 0; B(1,1) = 0;
B(2,0) = 1; B(2,1) = 0;
B(3,0) = 0; B(3,1) = 0;
B(4,0) = 0; B(4,1) = 0;
B(5,0) = 0; B(5,1) = 1;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 1; Q(0,2) = 0; Q(0,3) = 0; Q(0,4) = 0; Q(0,5) = 0;
Q(1,0) = 1; Q(1,1) = 1; Q(1,2) = 0; Q(1,3) = 0; Q(1,4) = 0; Q(1,5) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 0; Q(2,3) = 0; Q(2,4) = 0; Q(2,5) = 0;
Q(3,0) = 0; Q(3,1) = 0; Q(3,2) = 0; Q(3,3) = 1; Q(3,4) = -1; Q(3,5) = 0;
Q(4,0) = 0; Q(4,1) = 0; Q(4,2) = 0; Q(4,3) = -1; Q(4,4) = 1; Q(4,5) = 0;
Q(5,0) = 0; Q(5,1) = 0; Q(5,2) = 0; Q(5,3) = 0; Q(5,4) = 0; Q(5,5) = 0;
matrix_type R(m,m);
R(0,0) = 3; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type S(n,m);
S(0,0) = 1; S(0,1) = 0;
S(1,0) = 1; S(1,1) = 0;
S(2,0) = 0; S(2,1) = 0;
S(3,0) = 1; S(3,1) = 0;
S(4,0) = -1; S(4,1) = 0;
S(5,0) = 0; S(5,1) = 0;
matrix_type expect_X(n,n);
expect_X(0,0) = 0.776931379296968; expect_X(0,1) = 0.810457127580939; expect_X(0,2) = -0.150367062101950; expect_X(0,3) = -0.223068620703031; expect_X(0,4) = 0.256594368987001; expect_X(0,5) = -0.002115177331576;
expect_X(1,0) = 0.810457127580939; expect_X(1,1) = 1.615873554290608; expect_X(1,2) = 0.682929643886609; expect_X(1,3) = -0.189542872419061; expect_X(1,4) = -0.005040700871270; expect_X(1,5) = 0.254095399301336;
expect_X(2,0) = -0.150367062101950; expect_X(2,1) = 0.682929643886609; expect_X(2,2) = 1.485634705307614; expect_X(2,3) = -0.150367062101950; expect_X(2,4) = -0.016336231909491; expect_X(2,5) = 0.077827181137999;
expect_X(3,0) = -0.223068620703031; expect_X(3,1) = -0.189542872419061; expect_X(3,2) = -0.150367062101950; expect_X(3,3) = 0.776931379296968; expect_X(3,4) = -0.743405631012998; expect_X(3,5) = -0.002115177331577;
expect_X(4,0) = 0.256594368987001; expect_X(4,1) = -0.005040700871270; expect_X(4,2) = -0.016336231909491; expect_X(4,3) = -0.743405631012998; expect_X(4,4) = 1.481770561154726; expect_X(4,5) = -0.741674246035512;
expect_X(5,0) = -0.002115177331576; expect_X(5,1) = 0.254095399301336; expect_X(5,2) = 0.077827181137999; expect_X(5,3) = -0.002115177331577; expect_X(5,4) = -0.741674246035512; expect_X(5,5) = 1.235707250512302;
vector_type expect_l(n);
expect_l(0) = std::complex<value_type>( 0.195825301202028, 0.642361399464209);
expect_l(1) = std::complex<value_type>( 0.195825301202028,-0.642361399464209);
expect_l(2) = std::complex<value_type>( 0.376862701311676, 0.000000000000000);
expect_l(3) = std::complex<value_type>(-0.000000000000001, 0.000000013433172);
expect_l(4) = std::complex<value_type>(-0.000000000000001,-0.000000013433172);
expect_l(5) = std::complex<value_type>(-0.587066411126228, 0.000000000000000);
matrix_type expect_G(m,n);
expect_G(0,0) = 0.223068620703031; expect_G(0,1) = 0.189542872419061; expect_G(0,2) = 0.150367062101950; expect_G(0,3) = 0.223068620703031; expect_G(0,4) = -0.256594368987002; expect_G(0,5) = 0.002115177331576;
expect_G(1,0) = -0.007765239364716; expect_G(1,1) = -0.007544263584996; expect_G(1,2) = 0.108418825705555; expect_G(1,3) = -0.007765239364716; expect_G(1,4) = 0.007986215144435; expect_G(1,5) = -0.331813954691450;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_darex_ex_1_10 )
{
DCS_TEST_CASE("DAREX Ex. 1.10");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector< std::complex<value_type> > vector_type;
const std::size_t n(9);
const std::size_t m(3);
matrix_type A(n,n);
A(0,0) = 1e-2*87.010; A(0,1) = 1e-2* 13.500; A(0,2) = 1e-2* 1.159; A(0,3) = 1e-2* 0.05014; A(0,4) = -1e-2* 3.722; A(0,5) = 1e-2*0.03484; A(0,6) = 1e-2*0.00000; A(0,7) = 1e-2* 0.4242; A(0,8) = 1e-2* 0.7249;
A(1,0) = 1e-2* 7.655; A(1,1) = 1e-2* 89.740; A(1,2) = 1e-2* 1.272; A(1,3) = 1e-2* 0.05504; A(1,4) = -1e-2* 4.016; A(1,5) = 1e-2*0.03743; A(1,6) = 1e-2*0.00000; A(1,7) = 1e-2* 0.4530; A(1,8) = 1e-2* 0.7499;
A(2,0) = -1e-2*12.720; A(2,1) = 1e-2* 35.750; A(2,2) = 1e-2*81.700; A(2,3) = 1e-2* 0.14550; A(2,4) = -1e-2*10.280; A(2,5) = 1e-2*0.09870; A(2,6) = 1e-2*0.00000; A(2,7) = 1e-2* 1.1850; A(2,8) = 1e-2* 1.8720;
A(3,0) = -1e-2*36.350; A(3,1) = 1e-2* 63.390; A(3,2) = 1e-2* 7.491; A(3,3) = 1e-2*79.66000; A(3,4) = -1e-2*27.350; A(3,5) = 1e-2*0.26530; A(3,6) = 1e-2*0.00000; A(3,7) = 1e-2* 3.1720; A(3,8) = 1e-2* 4.8820;
A(4,0) = -1e-2*96.000; A(4,1) = 1e-2*164.590; A(4,2) = -1e-2*12.890; A(4,3) = -1e-2* 0.55970; A(4,4) = 1e-2* 7.142; A(4,5) = 1e-2*0.71080; A(4,6) = 1e-2*0.00000; A(4,7) = 1e-2* 8.4520; A(4,8) = 1e-2*12.5900;
A(5,0) = -1e-2*66.440; A(5,1) = 1e-2* 11.296; A(5,2) = -1e-2* 8.889; A(5,3) = -1e-2* 0.38540; A(5,4) = 1e-2* 8.447; A(5,5) = 1e-2*1.36000; A(5,6) = 1e-2*0.00000; A(5,7) = 1e-2*14.4300; A(5,8) = 1e-2*10.1600;
A(6,0) = 1e-2*41.020; A(6,1) = 1e-2* 69.300; A(6,2) = -1e-2* 5.471; A(6,3) = -1e-2* 0.23710; A(6,4) = 1e-2* 6.649; A(6,5) = 1e-2*1.24900; A(6,6) = 1e-2*0.01063; A(6,7) = 1e-2* 9.9970; A(6,8) = 1e-2* 6.9670;
A(7,0) = -1e-2*17.990; A(7,1) = 1e-2* 30.170; A(7,2) = -1e-2* 2.393; A(7,3) = -1e-2* 0.10350; A(7,4) = 1e-2* 6.059; A(7,5) = 1e-2*2.21600; A(7,6) = 1e-2*0.00000; A(7,7) = 1e-2*21.3900; A(7,8) = 1e-2* 3.5540;
A(8,0) = -1e-2*34.510; A(8,1) = 1e-2* 58.040; A(8,2) = -1e-2* 4.596; A(8,3) = -1e-2* 0.19890; A(8,4) = 1e-2*10.560; A(8,5) = 1e-2*1.98600; A(8,6) = 1e-2*0.00000; A(8,7) = 1e-2*21.9100; A(8,8) = 1e-2*21.5200;
matrix_type B(n,m);
B(0,0) = 1e-4* 4.76000; B(0,1) = -1e-4* 0.57010; B(0,2) = -1e-4*83.68000;
B(1,0) = 1e-4* 0.87900; B(1,1) = -1e-4* 4.77300; B(1,2) = -1e-4* 2.73000;
B(2,0) = 1e-4* 1.48200; B(2,1) = -1e-4*13.12000; B(2,2) = 1e-4* 8.87600;
B(3,0) = 1e-4* 3.89200; B(3,1) = -1e-4*35.13000; B(3,2) = 1e-4*24.80000;
B(4,0) = 1e-4*10.34000; B(4,1) = -1e-4*92.75000; B(4,2) = 1e-4*66.80000;
B(5,0) = 1e-4* 7.20300; B(5,1) = -1e-4*61.59000; B(5,2) = 1e-4*38.34000;
B(6,0) = 1e-4* 4.45400; B(6,1) = -1e-4*36.83000; B(6,2) = 1e-4*20.29000;
B(7,0) = 1e-4* 1.97100; B(7,1) = -1e-4*15.54000; B(7,2) = 1e-4* 6.93700;
B(8,0) = 1e-4* 3.77300; B(8,1) = -1e-4*30.28000; B(8,2) = 1e-4*14.69000;
matrix_type Q(n,n);
Q(0,0) = 50; Q(0,1) = 0; Q(0,2) = 0; Q(0,3) = 0; Q(0,4) = 0; Q(0,5) = 0; Q(0,6) = 0; Q(0,7) = 0; Q(0,8) = 0;
Q(1,0) = 0; Q(1,1) = 0; Q(1,2) = 0; Q(1,3) = 0; Q(1,4) = 0; Q(1,5) = 0; Q(1,6) = 0; Q(1,7) = 0; Q(1,8) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 0; Q(2,3) = 0; Q(2,4) = 0; Q(2,5) = 0; Q(2,6) = 0; Q(2,7) = 0; Q(2,8) = 0;
Q(3,0) = 0; Q(3,1) = 0; Q(3,2) = 0; Q(3,3) = 0; Q(3,4) = 0; Q(3,5) = 0; Q(3,6) = 0; Q(3,7) = 0; Q(3,8) = 0;
Q(4,0) = 0; Q(4,1) = 0; Q(4,2) = 0; Q(4,3) = 0; Q(4,4) = 50; Q(4,5) = 0; Q(4,6) = 0; Q(4,7) = 0; Q(4,8) = 0;
Q(5,0) = 0; Q(5,1) = 0; Q(5,2) = 0; Q(5,3) = 0; Q(5,4) = 0; Q(5,5) = 0; Q(5,6) = 0; Q(5,7) = 0; Q(5,8) = 0;
Q(6,0) = 0; Q(6,1) = 0; Q(6,2) = 0; Q(6,3) = 0; Q(6,4) = 0; Q(6,5) = 0; Q(6,6) = 0; Q(6,7) = 0; Q(6,8) = 0;
Q(7,0) = 0; Q(7,1) = 0; Q(7,2) = 0; Q(7,3) = 0; Q(7,4) = 0; Q(7,5) = 0; Q(7,6) = 0; Q(7,7) = 0; Q(7,8) = 0;
Q(8,0) = 0; Q(8,1) = 0; Q(8,2) = 0; Q(8,3) = 0; Q(8,4) = 0; Q(8,5) = 0; Q(8,6) = 0; Q(8,7) = 0; Q(8,8) = 0;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0; R(0,2) = 0;
R(1,0) = 0; R(1,1) = 1; R(1,2) = 0;
R(2,0) = 0; R(2,1) = 0; R(2,2) = 1;
matrix_type expect_X(n,n);
// Obtained with SLICOT:
// expect_X(0,0) = 1e+2*5.194221256889423; expect_X(0,1) = 1e+2*0.017093107843102; expect_X(0,2) = 1e+2*0.597943238405564; expect_X(0,3) = 1e+2*0.026730739405916; expect_X(0,4) = -1e+2*0.313928655928748; expect_X(0,5) = -1e+2*0.004690645261773; expect_X(0,6) = 1e+2*0; expect_X(0,7) = -1e+2*0.052623035300436; expect_X(0,8) = -1e+2*0.057714706758673;
// expect_X(1,0) = 1e+2*0.017093107843102; expect_X(1,1) = 1e+2*6.062940897213983; expect_X(1,2) = 1e+2*0.026906043422892; expect_X(1,3) = 1e+2*0.001396884300817; expect_X(1,4) = -1e+2*0.163784382994394; expect_X(1,5) = 1e+2*0.012779657048731; expect_X(1,6) = 1e+2*0; expect_X(1,7) = 1e+2*0.143430702460303; expect_X(1,8) = 1e+2*0.164521508295555;
// expect_X(2,0) = 1e+2*0.597943238405564; expect_X(2,1) = 1e+2*0.026906043422892; expect_X(2,2) = 1e+2*0.094662957940239; expect_X(2,3) = 1e+2*0.004250513282368; expect_X(2,4) = -1e+2*0.044326303597952; expect_X(2,5) = -1e+2*0.000662424480368; expect_X(2,6) = 1e+2*0; expect_X(2,7) = -1e+2*0.007428328837057; expect_X(2,8) = -1e+2*0.008137995705764;
// expect_X(3,0) = 1e+2*0.026730739405916; expect_X(3,1) = 1e+2*0.001396884300817; expect_X(3,2) = 1e+2*0.004250513282368; expect_X(3,3) = 1e+2*0.000190925476076; expect_X(3,4) = -1e+2*0.001984142852581; expect_X(3,5) = -1e+2*0.000028773557839; expect_X(3,6) = 1e+2*0; expect_X(3,7) = -1e+2*0.000322384797280; expect_X(3,8) = -1e+2*0.000351053981308;
// expect_X(4,0) = -1e+2*0.313928655928748; expect_X(4,1) = -1e+2*0.163784382994394; expect_X(4,2) = -1e+2*0.044326303597952; expect_X(4,3) = -1e+2*0.001984142852581; expect_X(4,4) = 1e+2*0.527988071584382; expect_X(4,5) = 1e+2*0.000111836392674; expect_X(4,6) = 1e+2*0; expect_X(4,7) = 1e+2*0.001410747036388; expect_X(4,8) = 1e+2*0.002405965955478;
// expect_X(5,0) = -1e+2-0.004690645261773; expect_X(5,1) = 1e+2*0.012779657048731; expect_X(5,2) = -1e+2*0.000662424480368; expect_X(5,3) = -1e+2*0.000028773557839; expect_X(5,4) = 1e+2*0.000111836392674; expect_X(5,5) = 1e+2*0.000041855087295; expect_X(5,6) = 1e+2*0; expect_X(5,7) = 1e+2*0.000476344734388; expect_X(5,8) = 1e+2*0.000583502334040;
// expect_X(6,0) = 1e+2*0.000000000000000; expect_X(6,1) = 1e+2*0.000000000000000; expect_X(6,2) = 1e+2*0.000000000000000; expect_X(6,3) = 1e+2*0.000000000000000; expect_X(6,4) = 1e+2*0.000000000000000; expect_X(6,5) = 1e+2*0.000000000000000; expect_X(6,6) = 1e+2*0; expect_X(6,7) = 1e+2*0.000000000000000; expect_X(6,8) = 1e+2*0.000000000000000;
// expect_X(7,0) = -1e+2*0.052623035300436; expect_X(7,1) = 1e+2*0.143430702460303; expect_X(7,2) = -1e+2*0.007428328837057; expect_X(7,3) = -1e+2*0.000322384797280; expect_X(7,4) = 1e+2*0.001410747036388; expect_X(7,5) = 1e+2*0.000476344734388; expect_X(7,6) = 1e+2*0; expect_X(7,7) = 1e+2*0.005438180536963; expect_X(7,8) = 1e+2*0.006767021988094;
// expect_X(8,0) = -1e+2*0.057714706758673; expect_X(8,1) = 1e+2*0.164521508295555; expect_X(8,2) = -1e+2*0.008137995705764; expect_X(8,3) = -1e+2*0.000351053981308; expect_X(8,4) = 1e+2*0.002405965955478; expect_X(8,5) = 1e+2*0.000583502334040; expect_X(8,6) = 1e+2*0; expect_X(8,7) = 1e+2*0.006767021988094; expect_X(8,8) = 1e+2*0.009074537095327;
// Obtained with OCTAVE 3.6.3
expect_X(0,0) = 495.846638409853; expect_X(0,1) = 566.58467310644; expect_X(0,1) = 21.3182453769891; expect_X(0,1) = 0.940914228675156; expect_X(0,1) = -35.0794989614783; expect_X(0,1) = 1.00768595839933; expect_X(0,1) = -9.78202687278168e-18; expect_X(0,1) = 11.2941480390768; expect_X(0,1) = 13.0244660053976;
expect_X(0,0) = 566.58467310644; expect_X(0,1) = 874.030703535864; expect_X(0,1) = 25.7414453384334; expect_X(0,1) = 1.14060303934333; expect_X(0,1) = -46.9356004669457; expect_X(0,1) = 1.60433278356664; expect_X(0,1) = -1.4492340879616e-17; expect_X(0,1) = 17.9756244598769; expect_X(0,1) = 20.6256929809136;
expect_X(0,0) = 21.3182453769891; expect_X(0,1) = 25.7414453384334; expect_X(0,1) = 10.4544603722017; expect_X(0,1) = 0.467627613507629; expect_X(0,1) = -4.89025951809438; expect_X(0,1) = -0.05857868850231; expect_X(0,1) = -6.63222089817682e-19; expect_X(0,1) = -0.670545173305624; expect_X(0,1) = -0.816779213061608;
expect_X(0,0) = 0.940914228675156; expect_X(0,1) = 1.14060303934333; expect_X(0,1) = 0.467627613507629; expect_X(0,1) = 0.0209286819996061; expect_X(0,1) = -0.216257512554881; expect_X(0,1) = -0.00256878360807131; expect_X(0,1) = -2.89794800397089e-20; expect_X(0,1) = -0.0293729313893332; expect_X(0,1) = -0.0355745669584946;
expect_X(0,0) = -35.0794989614783; expect_X(0,1) = -46.9356004669457; expect_X(0,1) = -4.89025951809438; expect_X(0,1) = -0.216257512554881; expect_X(0,1) = 54.6026901696294; expect_X(0,1) = -0.0295673416723653; expect_X(0,1) = 9.10118236647848e-19; expect_X(0,1) = -0.296096230741024; expect_X(0,1) = -0.142943601662422;
expect_X(0,0) = 1.00768595839933; expect_X(0,1) = 1.60433278356664; expect_X(0,1) = -0.05857868850231; expect_X(0,1) = -0.00256878360807131; expect_X(0,1) = -0.0295673416723653; expect_X(0,1) = 0.00484102459111798; expect_X(0,1) = -2.06031239588945e-20; expect_X(0,1) = 0.0549793147474146; expect_X(0,1) = 0.0669700230013585;
expect_X(0,0) = -9.78202687278168e-18; expect_X(0,1) = -1.4492340879616e-17; expect_X(0,1) = -6.63222089817682e-19; expect_X(0,1) = -2.89794800397089e-20; expect_X(0,1) = 9.10118236647848e-19; expect_X(0,1) = -2.06031239588945e-20; expect_X(0,1) = 0; expect_X(0,1) = -2.23547724169104e-19; expect_X(0,1) = -2.13852247064287e-19;
expect_X(0,0) = 11.2941480390768; expect_X(0,1) = 17.9756244598769; expect_X(0,1) = -0.670545173305624; expect_X(0,1) = -0.0293729313893332; expect_X(0,1) = -0.296096230741024; expect_X(0,1) = 0.0549793147474146; expect_X(0,1) = -2.23547724169104e-19; expect_X(0,1) = 0.625927097523558; expect_X(0,1) = 0.771720988576674;
expect_X(0,0) = 13.0244660053976; expect_X(0,1) = 20.6256929809136; expect_X(0,1) = -0.816779213061608; expect_X(0,1) = -0.0355745669584946; expect_X(0,1) = -0.142943601662422; expect_X(0,1) = 0.0669700230013585; expect_X(0,1) = -2.13852247064287e-19; expect_X(0,1) = 0.771720988576674; expect_X(0,1) = 1.00784365068903;
// Obtained with MATLAB 2012a:
// expect_X(0,0) = 495.846638409846; expect_X(0,1) = 566.584673106431; expect_X(0,2) = 21.3182453769879; expect_X(0,3) = 0.940914228674901; expect_X(0,4) = -35.0794989614771; expect_X(0,5) = 1.00768595839932; expect_X(0,6) = 0; expect_X(0,7) = 11.2941480390767; expect_X(0,8) = 13.0244660053975;
// expect_X(1,0) = 566.584673106431; expect_X(1,1) = 874.03070353585; expect_X(1,2) = 25.7414453384313; expect_X(1,3) = 1.14060303934294; expect_X(1,4) = -46.9356004669439; expect_X(1,5) = 1.60433278356663; expect_X(1,6) = 0; expect_X(1,7) = 17.9756244598768; expect_X(1,8) = 20.6256929809135;
// expect_X(2,0) = 21.3182453769879; expect_X(2,1) = 25.7414453384313; expect_X(2,2) = 10.4544603722013; expect_X(2,3) = 0.467627613507581; expect_X(2,4) = - 4.89025951809416; expect_X(2,5) = -0.0585786885023031; expect_X(2,6) = 0; expect_X(2,7) = - 0.670545173305628; expect_X(2,8) = - 0.816779213061639;
// expect_X(3,0) = 0.940914228674901; expect_X(3,1) = 1.14060303934294; expect_X(3,2) = 0.467627613507581; expect_X(3,3) = 0.020928681999601; expect_X(3,4) = - 0.216257512554839; expect_X(3,5) = -0.00256878360806688; expect_X(3,6) = 0; expect_X(3,7) = - 0.029372931389333; expect_X(3,8) = - 0.0355745669584999;
// expect_X(4,0) = - 35.0794989614771; expect_X(4,1) = - 46.9356004669439; expect_X(4,2) = - 4.89025951809416; expect_X(4,3) = -0.216257512554839; expect_X(4,4) = 54.6026901696292; expect_X(4,5) = -0.0295673416723667; expect_X(4,6) = 0; expect_X(4,7) = - 0.296096230741017; expect_X(4,8) = - 0.142943601662402;
// expect_X(5,0) = 1.00768595839932; expect_X(5,1) = 1.60433278356663; expect_X(5,2) = - 0.0585786885023031; expect_X(5,3) = -0.00256878360806688; expect_X(5,4) = -0.0295673416723667; expect_X(5,5) = 0.00484102459111791; expect_X(5,6) = 0; expect_X(5,7) = 0.0549793147474142; expect_X(5,8) = 0.066970023001358;
// expect_X(6,0) = 0; expect_X(6,1) = 0; expect_X(6,2) = 0; expect_X(6,3) = 0; expect_X(6,4) = 0; expect_X(6,5) = 0; expect_X(6,6) = 0; expect_X(6,7) = 0; expect_X(6,8) = 0;
// expect_X(7,0) = 11.2941480390767; expect_X(7,1) = 17.9756244598768; expect_X(7,2) = - 0.670545173305628; expect_X(7,3) = -0.029372931389333; expect_X(7,4) = -0.296096230741017; expect_X(7,5) = 0.0549793147474142; expect_X(7,6) = 0; expect_X(7,7) = 0.625927097523555; expect_X(7,8) = 0.771720988576672;
// expect_X(8,0) = 13.0244660053975; expect_X(8,1) = 20.6256929809135; expect_X(8,2) = - 0.816779213061639; expect_X(8,3) = -0.0355745669584999; expect_X(8,4) = -0.142943601662402; expect_X(8,5) = 0.066970023001358; expect_X(8,6) = 0; expect_X(8,7) = 0.771720988576672; expect_X(8,8) = 1.00784365068903;
vector_type expect_l(n);
// Obtained with SLICOT:
expect_l(0) = -0.057714706758673;
expect_l(1) = 0.164521508295555;
expect_l(2) = -0.008137995705764;
expect_l(3) = -0.000351053981308;
expect_l(4) = 0.002405965955478;
expect_l(5) = 0.000583502334040;
expect_l(6) = 0.000000000000000;
expect_l(7) = 0.006767021988094;
expect_l(8) = 0.009074537095327;
// Obtained with MATLAB 2012a:
// expect_l(0) = std::complex<value_type>(-0.000142641720816431, 0);
// expect_l(1) = std::complex<value_type>( 0.095448933366983, 0.0248695777873063);
// expect_l(2) = std::complex<value_type>( 0.095448933366983, -0.0248695777873063);
// expect_l(3) = std::complex<value_type>( 0.419715486657864, 0);
// expect_l(4) = std::complex<value_type>( 0.89641256981458, 0);
// expect_l(5) = std::complex<value_type>( 0.770388152116658, 0);
// expect_l(6) = std::complex<value_type>( 0.795645686080788, 0);
// expect_l(7) = std::complex<value_type>( 0.787602190123489, 0);
// expect_l(8) = std::complex<value_type>( 0.0001063, 0);
matrix_type expect_G(m,n);
// Obtained with SLICOT:
expect_G(0,0) = 0.150278082884243; expect_G(0,1) = 0.143143688106951; expect_G(0,2) = 0.018203456199910; expect_G(0,3) = 0.000827154029396; expect_G(0,4) = -0.010056993372684; expect_G(0,5) = 0.000361963320200; expect_G(0,6) = 0; expect_G(0,7) = 0.004381429591722; expect_G(0,8) = 0.007080465330660;
expect_G(1,0) = 0.593621020214211; expect_G(1,1) = -0.948632309320427; expect_G(1,2) = 0.080390245541794; expect_G(1,3) = 0.003513069380213; expect_G(1,4) = -0.036070591820291; expect_G(1,5) = -0.003806125042661; expect_G(1,6) = 0; expect_G(1,7) = -0.044545703037779; expect_G(1,8) = -0.062095480352244;
expect_G(2,0) = -4.304428233551964; expect_G(2,1) = 0.015954154527100; expect_G(2,2) = -0.544493658368384; expect_G(2,3) = -0.024361609342909; expect_G(2,4) = 0.278050871512213; expect_G(2,5) = 0.003861907638793; expect_G(2,6) = 0; expect_G(2,7) = 0.042595101037027; expect_G(2,8) = 0.041926823496933;
// Obtained with MATLAB 2012a:
// expect_G(0,0) = 0.282631498370492; expect_G(0,1) = 0.376083697027103; expect_G(0,2) = 0.00833873358364987; expect_G(0,3) = 0.000370256406442807; expect_G(0,4) = -0.0186935787692258; expect_G(0,5) = 0.000784016255464824; expect_G(0,6) = 0; expect_G(0,7) = 0.00888749509819949; expect_G(0,8) = 0.0108215082970068;
// expect_G(1,0) = -0.535801643344445; expect_G(1,1) = -0.934272914162055; expect_G(1,2) = 0.0746986996823357; expect_G(1,3) = 0.0032561919428259; expect_G(1,4) = -0.0283311587846425; expect_G(1,5) = -0.00388284932318094; expect_G(1,6) = 0; expect_G(1,7) = -0.0454905631646426; expect_G(1,8) = -0.0637611408424757;
// expect_G(2,0) = -3.60334145770696; expect_G(2,1) = -4.19313505104166; expect_G(2,2) = -0.352294163349421; expect_G(2,3) = -0.0154782280166033; expect_G(2,4) = 0.411510684752751; expect_G(2,5) = -0.00348527618228704; expect_G(2,6) = 0; expect_G(2,7) = -0.0355048885458903; expect_G(2,8) = -0.0205119997090879;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "Solution X = " << std::scientific << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << std::scientific << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_mathematica_1 )
{
DCS_TEST_CASE("Mathematica #1");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n(3);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = -1; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 1; A(1,2) = 1;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 1;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = 0;
B(1,0) = 1; B(1,1) = 0;
B(2,0) = 0; B(2,1) = 1;
matrix_type Q(n,n);
Q(0,0) = 10; Q(0,1) = 0; Q(0,2) = 0;
Q(1,0) = 0; Q(1,1) = 1; Q(1,2) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 0.1;
matrix_type R(m,m);
R(0,0) = 10; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 0.1;
matrix_type S;
S = ublas::zero_matrix<value_type>(n,m);
matrix_type E;
E = ublas::identity_matrix<value_type>(n);
matrix_type X;
matrix_type expect_X(n,n);
expect_X(0,0) = 42.2835365723965; expect_X(0,1) = - 68.5246566154061; expect_X(0,2) = - 3.9478276675312;
expect_X(1,0) =-68.5246566154061; expect_X(1,1) = 154.0430907758175; expect_X(1,2) = 16.0017331334676;
expect_X(2,0) =- 3.9478276675312; expect_X(2,1) = 16.0017331334676; expect_X(2,2) = 8.3319663731597;
vector_type expect_l(n);
expect_l(0) = complex_value_type(0.014790878209943,+0.065327030440924);
expect_l(1) = complex_value_type(0.014790878209943,-0.065327030440924);
expect_l(2) = complex_value_type(0.507913088596327,0);
matrix_type expect_G(m,n);
expect_G(0,0) = -0.395758347061307; expect_G(0,1) = 1.599377754500512; expect_G(0,2) = 0.810607779840516;
expect_G(1,0) = 0.097558030819426; expect_G(1,1) = 0.079555884622979; expect_G(1,2) = 1.258885747544583;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "E = " << E );
DCS_DEBUG_TRACE( "Solution X = " << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues l = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_mathematica_2 )
{
DCS_TEST_CASE("Mathematica #2");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n(2);
const std::size_t m(1);
matrix_type A(n,n);
A(0,0) = -1.0; A(0,1) = 0.5;
A(1,0) = -0.5; A(1,1) = -2.0;
matrix_type B(n,m);
B(0,0) = 1.0;
B(1,0) = 0.5;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 0;
Q(1,0) = 0; Q(1,1) = 2;
matrix_type R(m,m);
R(0,0) = 1;
matrix_type S;
S = ublas::zero_matrix<value_type>(n,m);
matrix_type E;
E = ublas::identity_matrix<value_type>(n);
matrix_type X;
matrix_type expect_X(n,n);
expect_X(0,0) = 1.925056693914408; expect_X(0,1) = 2.610775872464338;
expect_X(1,0) = 2.610775872464338; expect_X(1,1) = 31.230349238719803;
vector_type expect_l(n);
expect_l(0) = complex_value_type(-0.384777684926709,+0.143417474092307);
expect_l(1) = complex_value_type(-0.384777684926709,-0.143417474092307);
matrix_type expect_G(m,n);
expect_G(0,0) = -0.925056693914411; expect_G(0,1) = -2.610775872464342;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "E = " << E );
DCS_DEBUG_TRACE( "Solution X = " << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues l = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
DCS_TEST_CHECK_VECTOR_CLOSE(solver.eigenvalues(), expect_l, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
DCS_TEST_DEF( test_mathematica_3 )
{
DCS_TEST_CASE("Mathematica #3");
typedef double value_type;
typedef ::std::complex<value_type> complex_value_type;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<complex_value_type> vector_type;
const std::size_t n(3);
const std::size_t m(2);
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1.000; A(0,2) = 0.0;
A(1,0) = 0; A(1,1) = -0.010; A(1,2) = 0.3;
A(2,0) = 0; A(2,1) = -0.003; A(2,2) = -10.0;
matrix_type B(n,m);
B(0,0) = 0.0; B(0,1) = 0;
B(1,0) = 0.0; B(1,1) = -1;
B(2,0) = 0.1; B(2,1) = 0;
matrix_type Q(n,n);
Q(0,0) = 1; Q(0,1) = 0; Q(0,2) = 0;
Q(1,0) = 0; Q(1,1) = 1; Q(1,2) = 0;
Q(2,0) = 0; Q(2,1) = 0; Q(2,2) = 1;
matrix_type R(m,m);
R(0,0) = 1; R(0,1) = 0;
R(1,0) = 0; R(1,1) = 1;
matrix_type S(n,m);
S(0,0) = 0.10; S(0,1) = 0.0;
S(1,0) = -0.20; S(1,1) = 0.0;
S(2,0) = 0.15; S(2,1) = 0.2;
matrix_type E;
E = ublas::identity_matrix<value_type>(n);
matrix_type X;
matrix_type expect_X(n,n);
expect_X(0,0) = 1.0e+3*0.000999899234593; expect_X(0,1) = 1.0e+3*0.000002166454981; expect_X(0,2) = 1.0e+3*0.009899384711326;
expect_X(1,0) = 1.0e+3*0.000002166454981; expect_X(1,1) = 1.0e+3*0.001981954398444; expect_X(1,2) = -1.0e+3*0.017830763208183;
expect_X(2,0) = 1.0e+3*0.009899384711326; expect_X(2,1) = -1.0e+3*0.017830763208183; expect_X(2,2) = 1.0e+3*9.930660768134448;
vector_type expect_l(n);
expect_l(0) = complex_value_type(-0.004926321073849,+0.012040888479689);
expect_l(1) = complex_value_type(-0.004926321073849,-0.012040888479689);
expect_l(2) = complex_value_type(-0.099826902789823, 0.000000000000000);
matrix_type expect_G(m,n);
expect_G(0,0) = 0.001007654067580; expect_G(0,1) = -0.021664549812126; expect_G(0,2) = -98.993847113263143;
expect_G(1,0) = -0.000602532388965; expect_G(1,1) = 0.000935743736164; expect_G(1,2) = - 0.733959482458431;
dcs_control::dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
DCS_DEBUG_TRACE( "A = " << A );
DCS_DEBUG_TRACE( "B = " << B );
DCS_DEBUG_TRACE( "Q = " << Q );
DCS_DEBUG_TRACE( "R = " << R );
DCS_DEBUG_TRACE( "S = " << S );
DCS_DEBUG_TRACE( "E = " << E );
DCS_DEBUG_TRACE( "Solution X = " << solver.solution() );
DCS_DEBUG_TRACE( "Gain G = " << solver.gain() );
DCS_DEBUG_TRACE( "Closed-loop eigenvalues l = " << std::scientific << solver.eigenvalues() );
DCS_TEST_CHECK_MATRIX_CLOSE(solver.solution(), expect_X, n, n, tol);
DCS_TEST_CHECK_MATRIX_CLOSE(solver.gain(), expect_G, m, n, tol);
vector_type sort_l(solver.eigenvalues());
std::sort(sort_l.begin(), sort_l.end(), detail::complex_cmp<value_type>());
std::sort(expect_l.begin(), expect_l.end(), detail::complex_cmp<value_type>());
DCS_TEST_CHECK_VECTOR_CLOSE(sort_l, expect_l, n, tol);
}
int main()
{
// Tests labeled with 'darex' keyword are taken from:
// 'DAREX -- A Collection of Benchmark Examples for Discrete-Time
// Algebraic Riccati Equations'
// (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.125.6784)
// Tests labeled with 'mathematica' keyword are taken from the Wolfram
// Mathematica 8 documentation
// (http://reference.wolfram.com/mathematica/ref/DiscreteRiccatiSolve.html)
//
// All tests has been validated with MATLAB 2009b
DCS_TEST_SUITE("DCS Control :: DARE");
DCS_TEST_BEGIN();
DCS_TEST_DO( test_1 );
DCS_TEST_DO( test_2 );
DCS_TEST_DO( test_3 );
DCS_TEST_DO( test_4 );
DCS_TEST_DO( test_darex_ex_1_1 );
DCS_TEST_DO( test_darex_ex_1_2 );
DCS_TEST_DO( test_darex_ex_1_3 );
DCS_TEST_DO( test_darex_ex_1_4 );
DCS_TEST_DO( test_darex_ex_1_5 );
DCS_TEST_DO( test_darex_ex_1_6 );
DCS_TEST_DO( test_darex_ex_1_7 );
DCS_TEST_DO( test_darex_ex_1_8 );
DCS_TEST_DO( test_darex_ex_1_9 );
//DCS_TEST_DO( test_darex_ex_1_10 ); //FIXME: don't work!!!
DCS_TEST_DO( test_mathematica_1 );
DCS_TEST_DO( test_mathematica_2 );
DCS_TEST_DO( test_mathematica_3 );
DCS_TEST_END();
}
<file_sep>/**
* \file dcs/control/design/dlqi.hpp
*
* \brief Infinite-horizon Discrete Linear Quadratic Integral state-feedback.
*
* Given a dicrete time-invariant state-space system model:
* \f{align*}{
* \mathbf{x}(k+1) &= \mathbf{A}\mathbf{x}(k)+\mathbf{B}\mathbf{u}(k) \\
* \mathbf{y}(k+1) &= \mathbf{C}\mathbf{x}(k+1)+\mathbf{D}\mathbf{x}(k+1)
* \f}
* subject to initial conditions:
* \f[
* \mathbf{x}(0) = \mathbf{x}_0
* \f]
* where \f$\mathbf{A} \in \mathbb{R}^{n \times n}\f$,
* \f$\mathbf{B} \in \mathbb{R}^{n \times m}\f$,
* \f$\mathbf{C} \in \mathbb{R}^{p \times n}\f$, and
* \f$\mathbf{D} \in \mathbb{R}^{p \times m}\f$,
* and assuming that \f$(A,B)\f$ is \e stabilizable,
* the <em>Infinite-horizon, Discrete Linear-Quadratic (LQ) Integral
* state-feedback</em> controller problem calculates the optimal \e gain matrix
* \f$\mathbf{K}\f$ such that the augmented state-feedback law:
* \f{align}
* \mathbf{u}(k) &= -K\mathbf{z}(k) \\
* &= -K(\mathbf{x}(k) \mathbf{x}_i(k))^T
* \f}
* minimizes the following quadratic cost function (<em>performance index</em>):
* \f{align*}
* J(\mathbf{u}) &= \sum_{k=1}^{\infty}{\mathbf{z}^T(k)\mathbf{Q}\mathbf{z}(k) + \mathbf{u}^T(k)\mathbf{R}\mathbf{u}(k) + 2\mathbf{z}^T(k)\mathbf{N}\mathbf{u}(k)} \\
* &= \sum_{k=1}^{\infty}{\begin{pmatrix}\mathbf{z}^T(k) & \mathbf{u}^T(k)\end{pmatrix}\begin{pmatrix}\mathbf{Q} & \mathbf{N} \\ \mathbf{N}^T & \mathbf{R}\end{pmatrix}\begin{pmatrix}\mathbf{z}(k) \\ \mathbf{u}(k)\end{pmatrix}}
* \f}
* where the <em>error weighting matrix</em>
* \f$\mathbf{Q}\in\mathbb{R}^{n \times n}\f$ is a positive
* semi-definite real matrix,
* the <em>control weighting matrix</em>
* \f$\mathbf{R}\in\mathbb{R}^{m \times m}\f$ is a positive
* definite real matrix, and
* the <em>cross-coupling weighting matrix</em>
* \f$\mathbf{N}\in\mathbb{R}^{n \times m}\f$ is a real matrix.
* Matrices \f$\mathbf{Q}\f$ and \f$\mathbf{R}\f$ should be symmetric; if they
* are not, they are replaced with \f$\mathbf{Q}'\f$ and \f$\mathbf{R}'\f$ such
* that:
* \f{align*}
* \mathbf{Q}' &= \frac{\mathbf{Q}+\mathbf{Q}^T}{2}, \\
* \mathbf{R}' &= \frac{\mathbf{R}+\mathbf{R}^T}{2}.
* \f}
*
* The optimal gain matrix \f$\mathbf{K}\f$ is derived from:
* \f[
* \mathbf{K} = (\mathbf{B}^{T}\mathbf{X}\mathbf{B}+\mathbf{R})^{-1}(\mathbf{B}^{T}\mathbf{X}\mathbf{A}+\mathbf{N}^{T})
* \f]
* where \f$\mathbf{X}\f$ is the stabilizing infinite-horizon solution of the
* associated Discrete-time Algebraic Riccati Equation:
* \f[
* \mathbf{A}^{T}\mathbf{X}+\mathbf{X}\mathbf{A}-(\mathbf{X}\mathbf{B}+\mathbf{N})\mathbf{R}^{-1}(\mathbf{B}^{T}\mathbf{X}+\mathbf{N}^{T})+\mathbf{Q}=\mathbf{0}
* \f]
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_DLQI_HPP
#define DCS_CONTROL_DLQI_HPP
#include <algorithm>
#include <boost/static_assert.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/eigen.hpp>
#include <boost/numeric/ublasx/operation/max.hpp>
#include <boost/numeric/ublasx/operation/min.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/traits/layout_type.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#include <complex>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/control/solver/dare.hpp>
#include <stdexcept>
namespace dcs { namespace control {
namespace detail { namespace /*<unnamed>*/ {
/// Solve the Infinite-horizon, Discrete-time Linear Quadratic Regulator problem.
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename RealT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT,
typename KMatrixT,
typename SMatrixT,
typename EVectorT
>
void dlqi(boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
RealT ts,
boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
boost::numeric::ublas::matrix_expression<NMatrixT> const& N,
bool want_S,
bool want_e,
boost::numeric::ublas::matrix_container<KMatrixT>& K,
boost::numeric::ublas::matrix_container<SMatrixT>& S,
boost::numeric::ublas::vector_container<EVectorT>& e)
{
namespace ublasx = ::boost::numeric::ublasx;
namespace ublas = ::boost::numeric::ublas;
typedef AMatrixT A_matrix_type;
typedef BMatrixT B_matrix_type;
typedef CMatrixT C_matrix_type;
typedef DMatrixT D_matrix_type;
typedef QMatrixT Q_matrix_type;
typedef RMatrixT R_matrix_type;
typedef NMatrixT N_matrix_type;
// typedef typename ublas::promote_traits<
// typename ublas::matrix_traits<A_matrix_type>::value_type,
// typename ublas::promote_traits<
// typename ublas::matrix_traits<B_matrix_type>::value_type,
// typename ublas::promote_traits<
// typename ublas::matrix_traits<Q_matrix_type>::value_type,
// typename ublas::promote_traits<
// typename ublas::matrix_traits<R_matrix_type>::value_type,
// typename ublas::matrix_traits<N_matrix_type>::value_type
// >::promote_type
// >::promote_type
// >::promote_type
// >::promote_type value_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<A_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<B_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<C_matrix_type>::value_type,
typename ublas::matrix_traits<D_matrix_type>::value_type
>::promote_type
>::promote_type
>::promote_type value_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<A_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<B_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<C_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<D_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<Q_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<R_matrix_type>::size_type,
typename ublas::matrix_traits<N_matrix_type>::size_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type size_type;
typedef typename ublas::type_traits<value_type>::real_type real_type;
typedef ::std::complex<real_type> complex_type;
// precondition: Q must be real
BOOST_STATIC_ASSERT(
::boost::is_floating_point<typename ublas::matrix_traits<Q_matrix_type>::value_type>::value
//"dcs_control_lqr_Q_real"
);
// precondition: R must be real
BOOST_STATIC_ASSERT(
::boost::is_floating_point<typename ublas::matrix_traits<R_matrix_type>::value_type>::value
//"dcs_control_lqr_R_real"
);
// precondition: N must be real
BOOST_STATIC_ASSERT(
::boost::is_floating_point<typename ublas::matrix_traits<N_matrix_type>::value_type>::value
//"dcs_control_lqr_N_real"
);
size_type A_nr = ublasx::num_rows(A);
size_type A_nc = ublasx::num_columns(A);
size_type B_nr = ublasx::num_rows(B);
size_type B_nc = ublasx::num_columns(B);
size_type C_nr = ublasx::num_rows(C);
// size_type C_nc = ublasx::num_columns(C);
// size_type D_nr = ublasx::num_rows(D);
// size_type D_nc = ublasx::num_columns(D);
size_type Q_nr = ublasx::num_rows(Q);
size_type Q_nc = ublasx::num_columns(Q);
size_type R_nr = ublasx::num_rows(R);
size_type R_nc = ublasx::num_columns(R);
size_type N_nr = ublasx::num_rows(N);
size_type N_nc = ublasx::num_columns(N);
// pre: A is square
DCS_ASSERT(
A_nr == A_nc,
throw ::std::invalid_argument("[dcs::control::dlqi] State matrix A must be a square matrix.")
);
// pre: num_rows(B) == num_rows(A)
DCS_ASSERT(
B_nr == A_nr,
throw ::std::invalid_argument("[dcs::control::dlqi] The number of rows of the input matrix B must be the same of the state matrix A.")
);
// pre: Q is square
DCS_ASSERT(
Q_nr == Q_nc,
throw ::std::invalid_argument("[dcs::control::dlqi] Error weighting matrix Q must be a square matrix.")
);
// pre: num_rows(Q) == num_rows(A)+num_rows(C)
// The term "num_rows(C)" means that there is one integrator for each output variable
DCS_ASSERT(
Q_nr == (A_nr+C_nr),
throw ::std::invalid_argument("[dcs::control::dlqi] The number of rows of the error weighting matrix Q must be the equal to the sum between the number of rows of the state matrix A and the number of outputs.")
);
// pre: R is square
DCS_ASSERT(
R_nr == R_nc,
throw ::std::invalid_argument("[dcs::control::dlqi] Control weighting matrix Q must be a square matrix.")
);
// pre: num_rows(R) == num_columns(B)
DCS_ASSERT(
R_nr == B_nc,
throw ::std::invalid_argument("[dcs::control::dlqi] The number of columns of the control weighting matrix R must be the same of the input matrix B.")
);
// pre: num_rows(N) == (num_rows(A)+num_rows(C)) && num_columns(N) == num_columns(B)
DCS_ASSERT(
N_nr == (A_nr+C_nr) && N_nc == B_nc,
throw ::std::invalid_argument("[dcs::control::dlqi] The cross-term weighting matrix N must have a number of rows equal to the sum between the number of rows of the state matrix A and the number of outputs, and a number of columns equal to the number of columns of the input matrix B.")
);
const value_type eps = ::std::numeric_limits<real_type>::epsilon();
Q_matrix_type tmp_Q;
R_matrix_type tmp_R;
// Enforce symmetry
tmp_Q = (Q+ublas::trans(Q))/static_cast<real_type>(2);
tmp_R = (R+ublas::trans(R))/static_cast<real_type>(2);
// Check positivity
ublas::vector<complex_type> v_R;
ublasx::eigenvalues(tmp_R, v_R);
ublas::vector<complex_type> v_QNR;
ublasx::eigenvalues(
// [tmp_Q N; N' tmp_R]
ublasx::cat_columns(
ublasx::cat_rows(tmp_Q, N),
ublasx::cat_rows(ublas::trans(N), tmp_R)
),
v_QNR
);
if (::std::real(ublasx::min(v_R)) <= real_type/*zero*/())
{
throw ::std::runtime_error("[dcs::control::detail::dlqi] The control weighting matrix R is not positive definite.");
}
else if (::std::real(ublasx::min(v_QNR)) < (-1.0e+2*eps*::std::max(real_type/*zero*/(), ::std::real(ublasx::max(v_QNR)))))
{
DCS_DEBUG_TRACE("[dcs::control::detail::dlqi] The matrix [Q N;N' R] is not positive semi-definite.");
::std::clog << "[Warning] The matrix [Q N;N' R] is not positive semi-definite." << ::std::endl;
}
// Form the augmented system with an integrator
// xx(k+1) = AAxx(k)+BBu(k)
// where
// AA = [A 0; -C*abs(t_s) I]
// BB = [B; -D*abs(t_s)]
// xx(k) = [x(k); xi(k)]
// t_s = sampling time
// xi = integrator output
// NOTE: integration is based on Forward Euler formula
// xi(k+1) = xi(k)+t_s*(r(k)-y(k))
ts = ::std::abs(ts);
ublas::matrix<value_type> AA;
AA = ublasx::cat_columns(
ublasx::cat_rows(A, ublas::zero_matrix<value_type>(A_nr,C_nr)),
ublasx::cat_rows(-C*ts, ublas::identity_matrix<value_type>(C_nr,C_nr))
);
ublas::matrix<value_type> BB;
BB = ublasx::cat_columns(B, -D*ts);
ublas::matrix<value_type> E = ublas::identity_matrix<value_type>(A_nr+C_nr);
dare_solver<value_type> solver;
solver.solve(AA, BB, Q, R, N, E);
K() = solver.gain();
if (want_S)
{
S() = solver.solution();
}
if (want_e)
{
e() = solver.eigenvalues();
}
}
}} // Namespace detail::<unnamed>
/**
* \brief Infinite-horizon Discrete Linear Quadratic Integral controller for
* state-feedback regulation.
*
* \tparam RealT The type for real numbers.
*
* \note
* Inspired by the \c dlqi MATLAB function.
*
* \author <NAME>, <EMAIL>
*/
template <typename RealT>
class dlqi_controller
{
public: typedef RealT real_type;
public: typedef ::std::complex<real_type> complex_type;
public: typedef ::boost::numeric::ublas::matrix<real_type> matrix_type;
public: typedef ::boost::numeric::ublas::vector<complex_type> vector_type;
/// Default constructor
public: dlqi_controller()
{
// empty
}
/// A constructor
public: template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
> dlqi_controller(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
real_type ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
: Q_(Q),
R_(R),
N_(N)
{
solve(A, B, C, D, ts);
}
/// A constructor
public: template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename QMatrixT,
typename RMatrixT
> dlqi_controller(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
real_type ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
: Q_(Q),
R_(R),
N_(::boost::numeric::ublas::zero_matrix<real_type>(
::boost::numeric::ublasx::num_rows(Q),
::boost::numeric::ublasx::num_rows(R)
)
)
{
solve(A, B, C, D, ts);
}
/// A constructor
public: template <
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
> dlqi_controller(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
: Q_(Q),
R_(R),
N_(N)
{
// Empty
}
/// A constructor
public: template <
typename QMatrixT,
typename RMatrixT
> dlqi_controller(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
: Q_(Q),
R_(R),
N_(::boost::numeric::ublas::zero_matrix<real_type>(
::boost::numeric::ublasx::num_rows(Q),
::boost::numeric::ublasx::num_rows(R)
)
)
{
// Empty
}
/**
* \brief Solve the Infinite-horizon Discrete-time Linear Quadratic Regulator
* problem.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space
* system model.
*
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
*/
public: template <typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
real_type ts)
{
detail::dlqi(A, B, C, D, ts, Q_, R_, N_, true, true, K_, S_, e_);
}
/// Return the optimal state-feedback matrix gain.
public: matrix_type gain() const
{
return K_;
}
/// Return the associated DARE solution.
public: matrix_type are_solution() const
{
return S_;
}
/// Return the closed-loop eigenvalues.
public: vector_type eigenvalues() const
{
return e_;
}
public: template <typename VectorExprT>
vector_type control(::boost::numeric::ublas::vector_expression<VectorExprT> const& x) const
{
// preconditions: size(x) == num_columns(K_)
DCS_ASSERT(
::boost::numeric::ublasx::size(x) == ::boost::numeric::ublasx::num_columns(K_),
throw ::std::invalid_argument("[dcs::control::dlqi_controller::control] Wrong state dimensiion.")
);
return -::boost::numeric::ublas::prod(K_, x);
}
public: template <typename MatrixExprT>
matrix_type control(::boost::numeric::ublas::matrix_expression<MatrixExprT> const& X) const
{
// preconditions: num_columns(X) == num_columns(K_)
DCS_ASSERT(
::boost::numeric::ublasx::num_columns(X) == ::boost::numeric::ublasx::num_columns(K_),
throw ::std::invalid_argument("[dcs::control::dlqi_controller::control] Wrong state dimensiion.")
);
return -::boost::numeric::ublas::prod(K_, ::boost::numeric::ublas::trans(X));
}
/// The error weigthed matrix.
private: matrix_type Q_;
/// The control weigthed matrix.
private: matrix_type R_;
/// The cross-coupling weigthed matrix.
private: matrix_type N_;
/// The optimal feedback gain matrix.
private: matrix_type K_;
/// The solution to the associated DARE.
private: matrix_type S_;
/// The closed-loop eigenvalues which gives the closed-loop poles of \f$A-BK\f$.
private: vector_type e_;
};
/**
* \brief Infinite-horizon Discrete Linear Quadratic Controller design.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
* \tparam NMatrixT The type of the cross-coupling weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \param N The cross-coupling weighting matrix.
* \return An object representing an Infinite-horizon Discrete-time Linear
* Quadratic state-feedback Regulator controller.
*
* \note
* Inspired by the \c dlqi MATLAB function.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename RealT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
>
inline
dlqi_controller<
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type
> dlqi(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
RealT ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
return dlqi_controller<value_type>(A, B, C, D, ts, Q, R, N);
}
/**
* \brief Infinite-horizon Discrete Linear Quadratic Controller design.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \return An object representing an Infinite-horizon Discrete-time Linear
* Quadratic state-feedback Regulator controller.
*
* \note
* Inspired by the \c dlqi MATLAB function.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename RealT,
typename QMatrixT,
typename RMatrixT
>
inline
dlqi_controller<
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type
> dlqi(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
RealT ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
return dlqi_controller<value_type>(A, B, C, D, ts, Q, R);
}
/**
* \brief Optimal state-feedback control by Infinite-horizon Discrete Linear
* Quadratic Controller design.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
* \tparam NMatrixT The type of the cross-coupling weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \param N The cross-coupling weighting matrix.
* \return The optimal state-feedback gain matrix \f$\mathbf{K}\f$.
*
* \note
* Inspired by the \c dlqi MATLAB function.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename RealT,
typename QMatrixT,
typename RMatrixT,
typename NMatrixT
>
inline
//typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type dlqi_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type,
typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type
> dlqi_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
RealT ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<NMatrixT> const& N)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
typedef ::std::complex<typename ::boost::numeric::ublas::type_traits<value_type>::real_type> complex_type;
//typedef typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type out_matrix_type; //this doesn't work if A and B have different value types
typedef ::boost::numeric::ublas::matrix<value_type, typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type> out_matrix_type;
out_matrix_type K;
out_matrix_type dummy_S;
::boost::numeric::ublas::vector<complex_type> dummy_e;
detail::dlqi(
A,
B,
C,
D,
ts,
Q,
R,
N,
false,
false,
K,
dummy_S,
dummy_e
);
return K;
}
/**
* \brief Optimal state-feedback control by Infinite-horizon Discrete Linear
* Quadratic Controller design.
*
* \tparam AMatrixT The type of the state matrix for the controlled state-space
* model.
* \tparam BMatrixT The type of the input matrix for the controlled state-space
* model.
* \tparam QMatrixT The type of the error weighting matrix.
* \tparam RMatrixT The type of the control weighting matrix.
*
* \param A The state matrix for the controlled state-space model.
* \param B The input matrix for the controlled state-space model.
* \param Q The error weighting matrix.
* \param R The control weighting matrix.
* \return The optimal state-feedback gain matrix \f$\mathbf{K}\f$.
*
* \note
* Inspired by the \c dlqi MATLAB function.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT,
typename RealT,
typename QMatrixT,
typename RMatrixT,
typename KMatrixT
>
inline
//typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type dlqi_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix<
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type,
typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type
> dlqi_solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D,
RealT ts,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R)
{
typedef typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<AMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<BMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<CMatrixT>::value_type,
typename ::boost::numeric::ublas::promote_traits<
typename ::boost::numeric::ublas::matrix_traits<DMatrixT>::value_type,
RealT
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
typedef ::std::complex<typename ::boost::numeric::ublas::type_traits<value_type>::real_type> complex_type;
//typedef typename boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type out_matrix_type; //this doesn't work if A and B have different value types
typedef ::boost::numeric::ublas::matrix<value_type, typename ::boost::numeric::ublasx::layout_type<AMatrixT>::type> out_matrix_type;
out_matrix_type K;
out_matrix_type dummy_S;
::boost::numeric::ublas::vector<complex_type> dummy_e;
detail::dlqi(
A,
B,
C,
D,
ts,
Q,
R,
::boost::numeric::ublas::zero_matrix<value_type>(
::boost::numeric::ublasx::num_rows(Q),
::boost::numeric::ublasx::num_columns(R)
),
false,
false,
K,
dummy_S,
dummy_e
);
return K;
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_DLQI_HPP
<file_sep>/**
* \file test/src/dcs/control/controllability.cpp
*
* \brief Test suite for system controllability.
*
* Copyright (C) 2009-2010 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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/>.
*
* \author <NAME> (<EMAIL>)
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <dcs/control/analysis/controllability.hpp>
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
const double tol = 1.0e-5;
DCS_TEST_DEF( state_controllability_matrix )
{
DCS_TEST_CASE("State Controllability Matrix");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = -1; A(1,1) = 2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 2;
matrix_type expect_C(n, n*m);
expect_C(0,0) = 1; expect_C(0,1) = 3;
expect_C(1,0) = 2; expect_C(1,1) = 3;
matrix_type C = dcs::control::make_controllability_matrix(A, B);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("P = [B AB ... A^{" << (n-1) << "}B] = " << C);
DCS_DEBUG_TRACE("Number of uncontrollable states " << (n-ublasx::rank(C)));
DCS_TEST_CHECK_MATRIX_CLOSE(C, expect_C, n, n*m, tol);
}
DCS_TEST_DEF( state_controllability_check )
{
DCS_TEST_CASE("State Controllability Check");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// State controllable system
{
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = -1; A(1,1) = 2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 2;
bool ctrb = dcs::control::is_controllable(A, B);
bool expect_ctrb = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is State Controllable = " << std::boolalpha << ctrb);
DCS_TEST_CHECK(ctrb == expect_ctrb);
}
// Non state controllable system
{
const std::size_t n = 2;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = 4; A(1,1) = -2;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = -1;
B(1,0) = 1; B(1,1) = -1;
bool ctrb = dcs::control::is_controllable(A, B);
bool expect_ctrb = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is State Controllable = " << std::boolalpha << ctrb);
DCS_TEST_CHECK(ctrb == expect_ctrb);
}
}
DCS_TEST_DEF( output_controllability_matrix )
{
DCS_TEST_CASE("Output Controllability Matrix");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
const std::size_t n = 2;
const std::size_t m = 1;
const std::size_t p = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = -1; A(1,1) = 2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 2;
matrix_type C(p,n);
C(0,0) = 1; C(0,1) = -1;
matrix_type D(p,m);
D(0,0) = 1;
matrix_type expect_P(p, (n+1)*m);
expect_P(0,0) = -1; expect_P(0,1) = 0; expect_P(0,2) = 1;
matrix_type P = dcs::control::make_output_controllability_matrix(A, B, C, D);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("P = [CB CAB ... CA^{" << (n-1) << "}B D] = " << P);
DCS_TEST_CHECK_MATRIX_CLOSE(P, expect_P, m, (n+1)*m, tol);
}
DCS_TEST_DEF( output_controllability_check )
{
DCS_TEST_CASE("Output Controllability Check");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// Output controllable system
{
const std::size_t n = 2;
const std::size_t m = 1;
const std::size_t p = 2;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = -1; A(1,1) = 2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 2;
matrix_type C(p,n);
C(0,0) = 1; C(0,1) = -1;
C(1,0) = 2; C(1,1) = -3;
matrix_type D(p,m);
D(0,0) = 1;
D(1,0) = 2;
bool ctrb = dcs::control::is_output_controllable(A, B, C, D);
bool expect_ctrb = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Is Output Controllable = " << std::boolalpha << ctrb);
DCS_TEST_CHECK(ctrb == expect_ctrb);
}
// Non output controllable system
{
const std::size_t n = 2;
const std::size_t m = 1;
const std::size_t p = 2;
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = -1; A(1,1) = -2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = -1;
matrix_type C(p,n);
C(0,0) = 1; C(0,1) = 0;
C(1,0) = 1; C(1,1) = 1;
matrix_type D(p,m);
D(0,0) = 0;
D(1,0) = 0;
bool ctrb = dcs::control::is_output_controllable(A, B, C, D);
bool expect_ctrb = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("D = " << D);
DCS_DEBUG_TRACE("Is Output Controllable = " << std::boolalpha << ctrb);
DCS_TEST_CHECK(ctrb == expect_ctrb);
}
}
DCS_TEST_DEF( controllable_decomposition )
{
DCS_TEST_CASE("Controllable Decomposition");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// Output controllable system
{
// const std::size_t n = 2;
// const std::size_t m = 2;
// const std::size_t p = 2;
const std::size_t n = 3;
const std::size_t m = 2;
const std::size_t p = 2;
matrix_type A(n,n);
// A(0,0) = 1; A(0,1) = 1;
// A(1,0) = 4; A(1,1) = -2;
A(0,0) = 1; A(0,1) = 0; A(0,2) = 0;
A(1,0) = 0; A(1,1) = 2; A(1,2) = 0;
A(2,0) = 0; A(2,1) = 0; A(2,2) = 3;
matrix_type B(n,m);
// B(0,0) = 1; B(0,1) = -1;
// B(1,0) = 1; B(1,1) = -1;
B(0,0) = 0; B(0,1) = 0;
B(1,0) = 4; B(1,1) = 5;
B(2,0) = 0; B(2,1) = 0;
matrix_type C(p,n);
// C(0,0) = 1; C(0,1) = 0;
// C(1,0) = 0; C(1,1) = 1;
C(0,0) = 6; C(0,1) = 0; C(0,2) = 0;
C(1,0) = 0; C(1,1) = 0; C(1,2) = 7;
dcs::control::controllable_decomposition<value_type> ctrbf;
ctrbf.decompose(A, B, 1.7764e-15);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("Ab = " << ctrbf.A_bar());
DCS_DEBUG_TRACE("Bb = " << ctrbf.B_bar());
DCS_DEBUG_TRACE("Cb = " << ctrbf.C_bar(C));
DCS_DEBUG_TRACE("T = " << ctrbf.T());
DCS_DEBUG_TRACE("k = " << ctrbf.k());
// DCS_DEBUG_TRACE("Is Output Controllable = " << std::boolalpha << ctrb);
// DCS_TEST_CHECK(ctrb == expect_ctrb);
}
}
int main()
{
DCS_TEST_SUITE("DCS Control :: Controllability");
DCS_TEST_BEGIN();
DCS_TEST_DO( state_controllability_matrix );
DCS_TEST_DO( state_controllability_check );
DCS_TEST_DO( output_controllability_matrix );
DCS_TEST_DO( output_controllability_check );
DCS_TEST_DO( controllable_decomposition );
DCS_TEST_END();
}
<file_sep>## DCS USER CONFIGURATIONS
##
### dcs general configurations
# Set here you C/C++ preprocessor flags
USR_CPPFLAGS=
# Set here you C compiler flags
USR_CFLAGS=
# Set here you C++ compiler flags
#USR_CXXFLAGS=
USR_CXXFLAGS=
#USR_CXXFLAGS=-I$HOME/tmp/cvs-prj/boost-trunk
# Set here you C/C++ linker flags
USR_LDFLAGS=
export USR_CPPFLAGS USR_CFLAGS USR_CXXFLAGS USR_LDFLAGS
<file_sep>/**
* \file test/src/dcs/control/bindings/slicot.cpp
*
* \brief Test suite for bindings to the SLICOT Fortran library.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright (C) 2012 <NAME> (<EMAIL>)
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of Foobar (below referred to as "this program").
*
* 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/>.
*/
#include <algorithm>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <cstddef>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/math/type/matrix.hpp>
#include <dcs/math/type/matrix_properties.hpp>
#include <dcs/math/type/vector.hpp>
#include <dcs/control/bindings/fortran.hpp>
#include <dcs/control/bindings/slicot.hpp>
#include <dcs/test.hpp>
#include <stdexcept>
namespace /*<unnamed>*/ {
const double tol(1.0e-5);
} // Namespace <unnamed>
DCS_TEST_DEF( sb02od_c_arrays )
{
DCS_TEST_CASE("SB02OD - C Arrays");
namespace math = dcs::math;
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
typedef double real_type;
typedef math::matrix<real_type,math::matrix_properties<math::column_major_storage_layout> > matrix_type;
typedef math::vector<real_type> real_vector_type;
typedef math::vector<bindings::fortran_int> int_vector_type;
typedef math::vector<bindings::fortran_logical> logical_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
const bindings::fortran_int ldl(1);
matrix_type L(ldl,nx,0);
double rcond(0);
const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X(ldx,nx,0);
real_vector_type alfar(2*nx);
real_vector_type alfai(2*nx);
real_vector_type beta(2*nx);
const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S(lds,2*nx+nu,0);
const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T(ldt,2*nx,0);
const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U(ldu,2*nx,0);
const bindings::fortran_int liwork = std::max(std::max(bindings::fortran_int(1),nu),2*nx);
int_vector_type iwork(liwork,0);
const bindings::fortran_int ldwork = std::max(std::max(std::max(7*(2*nx+1)+16,16*nx),2*nx+nu),3*nu);
real_vector_type dwork(ldwork);
logical_vector_type bwork(2*nx, 0);
const char dico('D');
const char jobb('B');
const char fact('N');
const char uplo('U');
const char jobl('Z');
const char sort('S');
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
slicot::sb02od(dico,
jobb,
fact,
uplo,
jobl,
sort,
nx,
nu,
0,
A.begin_data(),
lda,
B.begin_data(),
ldb,
Q.begin_data(),
ldq,
R.begin_data(),
ldr,
L.begin_data(),
ldl,
rcond,
X.begin_data(),
ldx,
alfar.begin_data(),
alfai.begin_data(),
beta.begin_data(),
S.begin_data(),
lds,
T.begin_data(),
ldt,
U.begin_data(),
ldu,
0,
iwork.begin_data(),
dwork.begin_data(),
ldwork,
bwork.begin_data());
DCS_TEST_CHECK_VECTOR_CLOSE(X.begin_data(), ok_X.begin_data(), nx*nx, tol);
}
DCS_TEST_DEF( sb02od_ublas_arrays )
{
DCS_TEST_CASE("SB02OD - Boost.uBLAS Arrays");
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
namespace ublas = boost::numeric::ublas;
typedef double real_type;
typedef ublas::matrix<real_type,ublas::column_major> matrix_type;
typedef ublas::vector<real_type> real_vector_type;
typedef ublas::vector<bindings::fortran_int> int_vector_type;
typedef ublas::vector<bindings::fortran_logical> logical_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
const bindings::fortran_int ldl(1);
matrix_type L(ldl,nx,0);
double rcond(0);
const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X(ldx,nx,0);
real_vector_type alfar(2*nx);
real_vector_type alfai(2*nx);
real_vector_type beta(2*nx);
const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S(lds,2*nx+nu,0);
const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T(ldt,2*nx,0);
const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U(ldu,2*nx,0);
const bindings::fortran_int liwork = std::max(std::max(bindings::fortran_int(1),nu),2*nx);
int_vector_type iwork(liwork,0);
const bindings::fortran_int ldwork = std::max(std::max(std::max(7*(2*nx+1)+16,16*nx),2*nx+nu),3*nu);
real_vector_type dwork(ldwork);
logical_vector_type bwork(2*nx, 0);
const char dico('D');
const char jobb('B');
const char fact('N');
const char uplo('U');
const char jobl('Z');
const char sort('S');
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
slicot::sb02od(dico,
jobb,
fact,
uplo,
jobl,
sort,
nx,
nu,
0,
A.data().begin(),
lda,
B.data().begin(),
ldb,
Q.data().begin(),
ldq,
R.data().begin(),
ldr,
L.data().begin(),
ldl,
rcond,
X.data().begin(),
ldx,
alfar.data().begin(),
alfai.data().begin(),
beta.data().begin(),
S.data().begin(),
lds,
T.data().begin(),
ldt,
U.data().begin(),
ldu,
0,
iwork.data().begin(),
dwork.data().begin(),
ldwork,
bwork.data().begin());
DCS_TEST_CHECK_VECTOR_CLOSE(X.data().begin(), ok_X.data().begin(), nx*nx, tol);
}
DCS_TEST_DEF( sb02od_ublas_arrays_2 )
{
DCS_TEST_CASE("SB02OD - Boost.uBLAS Arrays #2");
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
namespace ublas = boost::numeric::ublas;
typedef double real_type;
typedef ublas::matrix<real_type,ublas::column_major> matrix_type;
typedef ublas::vector<real_type> real_vector_type;
typedef ublas::vector<bindings::fortran_int> int_vector_type;
typedef ublas::vector<bindings::fortran_logical> logical_vector_type;
typedef ublas::vector< std::complex<real_type> > complex_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
matrix_type L;
//const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X;
complex_vector_type lambda;
//const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S;
//const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T;
//const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U;
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
slicot::sb02od(A, B, Q, R, L, true, X, lambda, S, T, U);
//DCS_DEBUG_TRACE("X=" << X);
//DCS_DEBUG_TRACE("lambda=" << lambda);
//DCS_DEBUG_TRACE("S=" << S);
//DCS_DEBUG_TRACE("T=" << T);
//DCS_DEBUG_TRACE("U=" << U);
DCS_TEST_CHECK_VECTOR_CLOSE(X.data().begin(), ok_X.data().begin(), nx*nx, tol);
}
DCS_TEST_DEF( sg02ad_c_arrays )
{
DCS_TEST_CASE("SG02AD - C Arrays");
namespace math = dcs::math;
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
typedef double real_type;
typedef math::matrix<real_type,math::matrix_properties<math::column_major_storage_layout> > matrix_type;
typedef math::vector<real_type> real_vector_type;
typedef math::vector<bindings::fortran_int> int_vector_type;
typedef math::vector<bindings::fortran_logical> logical_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int lde = std::max(bindings::fortran_int(1),nx);
matrix_type E(lde,nx);
E(0,0) = 1; E(0,1) = 0; E(0,2) = 0;
E(1,0) = 0; E(1,1) = 1; E(1,2) = 0;
E(2,0) = 0; E(2,1) = 0; E(2,2) = 1;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
const bindings::fortran_int ldl(1);
matrix_type L(ldl,nx,0);
double rcondu(0);
const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X(ldx,nx,0);
real_vector_type alfar(2*nx);
real_vector_type alfai(2*nx);
real_vector_type beta(2*nx);
const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S(lds,2*nx+nu,0);
const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T(ldt,2*nx,0);
const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U(ldu,2*nx,0);
const bindings::fortran_int liwork = std::max(std::max(bindings::fortran_int(1),nu),2*nx);
int_vector_type iwork(liwork,0);
const bindings::fortran_int ldwork = std::max(std::max(std::max(7*(2*nx+1)+16,16*nx),2*nx+nu),3*nu);
real_vector_type dwork(ldwork);
logical_vector_type bwork(2*nx, 0);
const char dico('D');
const char jobb('B');
const char fact('N');
const char uplo('U');
const char jobl('Z');
const char scal('N');
const char sort('S');
const char acc('N');
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
bindings::fortran_int iwarn(0);
slicot::sg02ad(dico,
jobb,
fact,
uplo,
jobl,
scal,
sort,
acc,
nx,
nu,
0,
A.begin_data(),
lda,
E.begin_data(),
lde,
B.begin_data(),
ldb,
Q.begin_data(),
ldq,
R.begin_data(),
ldr,
L.begin_data(),
ldl,
rcondu,
X.begin_data(),
ldx,
alfar.begin_data(),
alfai.begin_data(),
beta.begin_data(),
S.begin_data(),
lds,
T.begin_data(),
ldt,
U.begin_data(),
ldu,
0,
iwork.begin_data(),
dwork.begin_data(),
ldwork,
bwork.begin_data(),
iwarn);
DCS_TEST_CHECK_VECTOR_CLOSE(X.begin_data(), ok_X.begin_data(), nx*nx, tol);
}
DCS_TEST_DEF( sg02ad_ublas_arrays )
{
DCS_TEST_CASE("SG02AD - Boost.uBLAS Arrays");
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
namespace ublas = boost::numeric::ublas;
typedef double real_type;
typedef ublas::matrix<real_type,ublas::column_major> matrix_type;
typedef ublas::vector<real_type> real_vector_type;
typedef ublas::vector<bindings::fortran_int> int_vector_type;
typedef ublas::vector<bindings::fortran_logical> logical_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int lde = std::max(bindings::fortran_int(1),nx);
matrix_type E(lde,nx);
E(0,0) = 1; E(0,1) = 0; E(0,2) = 0;
E(1,0) = 0; E(1,1) = 1; E(1,2) = 0;
E(2,0) = 0; E(2,1) = 0; E(2,2) = 1;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
const bindings::fortran_int ldl(1);
matrix_type L(ldl,nx,0);
double rcondu(0);
const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X(ldx,nx,0);
real_vector_type alfar(2*nx);
real_vector_type alfai(2*nx);
real_vector_type beta(2*nx);
const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S(lds,2*nx+nu,0);
const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T(ldt,2*nx,0);
const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U(ldu,2*nx,0);
const bindings::fortran_int liwork = std::max(std::max(bindings::fortran_int(1),nu),2*nx);
int_vector_type iwork(liwork,0);
const bindings::fortran_int ldwork = std::max(std::max(std::max(7*(2*nx+1)+16,16*nx),2*nx+nu),3*nu);
real_vector_type dwork(ldwork);
logical_vector_type bwork(2*nx, 0);
const char dico('D');
const char jobb('B');
const char fact('N');
const char uplo('U');
const char jobl('Z');
const char scal('N');
const char sort('S');
const char acc('N');
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
bindings::fortran_int iwarn(0);
slicot::sg02ad(dico,
jobb,
fact,
uplo,
jobl,
scal,
sort,
acc,
nx,
nu,
0,
A.data().begin(),
lda,
E.data().begin(),
lde,
B.data().begin(),
ldb,
Q.data().begin(),
ldq,
R.data().begin(),
ldr,
L.data().begin(),
ldl,
rcondu,
X.data().begin(),
ldx,
alfar.data().begin(),
alfai.data().begin(),
beta.data().begin(),
S.data().begin(),
lds,
T.data().begin(),
ldt,
U.data().begin(),
ldu,
0,
iwork.data().begin(),
dwork.data().begin(),
ldwork,
bwork.data().begin(),
iwarn);
DCS_TEST_CHECK_VECTOR_CLOSE(X.data().begin(), ok_X.data().begin(), nx*nx, tol);
}
DCS_TEST_DEF( sg02ad_ublas_arrays_2 )
{
DCS_TEST_CASE("SG02AD - Boost.uBLAS Arrays #2");
namespace bindings = dcs::control::bindings;
namespace slicot = dcs::control::bindings::slicot;
namespace ublas = boost::numeric::ublas;
typedef double real_type;
typedef ublas::matrix<real_type,ublas::column_major> matrix_type;
typedef ublas::vector<real_type> real_vector_type;
typedef ublas::vector<bindings::fortran_int> int_vector_type;
typedef ublas::vector<bindings::fortran_logical> logical_vector_type;
typedef ublas::vector< std::complex<real_type> > complex_vector_type;
const bindings::fortran_int nx(3);
const bindings::fortran_int nu(1);
const bindings::fortran_int lda = std::max(bindings::fortran_int(1),nx);
matrix_type A(lda,nx);
A(0,0) = 0; A(0,1) = 0; A(0,2) = 1;
A(1,0) = 0; A(1,1) = 0; A(1,2) = 0;
A(2,0) = 0.243365; A(2,1) = -0.563735; A(2,2) = -0.932137;
const bindings::fortran_int lde = std::max(bindings::fortran_int(1),nx);
matrix_type E(lde,nx);
E(0,0) = 1; E(0,1) = 0; E(0,2) = 0;
E(1,0) = 0; E(1,1) = 1; E(1,2) = 0;
E(2,0) = 0; E(2,1) = 0; E(2,2) = 1;
const bindings::fortran_int ldb = std::max(bindings::fortran_int(1),nx);
matrix_type B(ldb,nu);
B(0,0) = 1;
B(1,0) = 0;
B(2,0) = 0.811669;
const bindings::fortran_int ldq = std::max(bindings::fortran_int(1),nx);
matrix_type Q(ldq,nx,0);
Q(nx-1,nx-1) = 1;
const bindings::fortran_int ldr = std::max(bindings::fortran_int(1),nu);
matrix_type R(ldr,nu,1);
matrix_type L;
//const bindings::fortran_int ldx = std::max(bindings::fortran_int(1),nx);
matrix_type X;
complex_vector_type lambda;
//const bindings::fortran_int lds = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type S;
//const bindings::fortran_int ldt = std::max(bindings::fortran_int(1),2*nx+nu);
matrix_type T;
//const bindings::fortran_int ldu = std::max(bindings::fortran_int(1),2*nx);
matrix_type U;
matrix_type ok_X(nx,nx);
ok_X(0,0) = 0.0671891998477877; ok_X(0,1) = -0.1556382535540959; ok_X(0,2) = -0.2977628887069395;
ok_X(1,0) = -0.1556382535540959; ok_X(1,1) = 0.3605232094480238; ok_X(1,2) = 0.6897432336827665;
ok_X(2,0) = -0.2977628887069395; ok_X(2,1) = 0.6897432336827665; ok_X(2,2) = 2.3481878868207247;
slicot::sg02ad(A, E, B, Q, R, L, true, X, lambda, S, T, U);
//DCS_DEBUG_TRACE("X=" << X);
//DCS_DEBUG_TRACE("lambda=" << lambda);
//DCS_DEBUG_TRACE("S=" << S);
//DCS_DEBUG_TRACE("T=" << T);
//DCS_DEBUG_TRACE("U=" << U);
DCS_TEST_CHECK_VECTOR_CLOSE(X.data().begin(), ok_X.data().begin(), nx*nx, tol);
}
int main()
{
DCS_TEST_SUITE("DCS Control SLICOT C++ Interface");
DCS_TEST_BEGIN();
DCS_TEST_DO( sb02od_c_arrays );
DCS_TEST_DO( sb02od_ublas_arrays );
DCS_TEST_DO( sb02od_ublas_arrays_2 );
DCS_TEST_DO( sg02ad_c_arrays );
DCS_TEST_DO( sg02ad_ublas_arrays );
DCS_TEST_DO( sg02ad_ublas_arrays_2 );
DCS_TEST_END();
}
<file_sep>/**
* \file dcs/control/analysis/controllability.hpp
*
* \brief Controllability for a state-space system.
*
* A system with internal state vector \f$\mathbf{x}\f$ is called
* \e controllable if and only if the system states can be changed by changing
* the system input.
* Equivalently, a system is said to be controllable if for any initial state
* \f$x(k_0)\f$ there exists a control sequence \f$u(k)\f$, with
* \f$k=k_0,k_0+1,\ldots,k_f-1\f$, such that an arbitrary final state
* \f$x(k_f)\f$ can be reached in finite time \f$k_f\f$.
*
* More specifically, given a continuous-time state-space system model:
* \f[
* \dot{\mathbf{x}}(t) = \mathbf{A}\mathbf{x}(t)+\mathbf{B}\mathbf{u}(t)
* \mathbf{y}(t) = \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f]
* or a discrete-time state-space system model:
* \f[
* \mathbf{x}(t) = \mathbf{A}\mathbf{x}(t-1)+\mathbf{B}\mathbf{u}(t-1)
* \mathbf{y}(t) = \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f]
* the following definitions apply [1]:
* - The system is called <em>state controllable</em> at time \f$t_0\f$ if
* it there exists an unconstrained input signal \f$\mathbf{u}(t)\f$ that
* willl transfer an initial state to any final state in a finite time
* interval \f$t_0 \le t \le t_1\f$.
* - The system is called <em>complete state controllable</em> (or simply
* \e controllable) at time \f$t_0\f$ if every state \f$x_0\f$ in the
* state-space model is controllable.
* - The system is called <em>complete output controllable</em> if there exists
* an unconstrained input signal \f$\mathbf{u}(t)\f$ that will transfer any
* given initial output \f$\mathbf{y}(t_0)\f$ to any final output
* \f$\mathbf{y}(t_1)\f$ in a finite time interval \f$t_0 \le t \le t_1\f$.
* .
*
* Formally, system controllability is defined in terms of the
* <em>controllability matrix</em>.
*
* Given a continuous-time state-space system model:
* \f{align*}
* \dot{\mathbf{x}}(t) &= \mathbf{A}\mathbf{x}(t)+\mathbf{B}\mathbf{u}(t),\\
* \mathbf{y}(t) &= \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f}
* or a discrete-time state-space system model:
* \f{align*}
* \mathbf{x}(t) &= \mathbf{A}\mathbf{x}(t-1)+\mathbf{B}\mathbf{u}(t-1),\\
* \mathbf{y}(t) &= \mathbf{C}\mathbf{x}(t)+\mathbf{D}\mathbf{u}(t)
* \f}
* where:
* - \f$\mathbf{A}\f$ is a \f$n \times n}\f$ matrix,
* - \f$\mathbf{B}\f$ is a \f$n \times m}\f$ matrix,
* - \f$\mathbf{C}\f$ is a \f$p \times n}\f$ matrix,
* - \f$\mathbf{D}\f$ is a \f$p \times m}\f$ matrix.
* .
* We define:
* - the <em>(state) controllability matrix</em> as the following
* \f$n \times nm\f$ matrix:
* \f[
* \begin{pmatrix}
* \mathbf{B} & \mathbf{A}\mathbf{B} & \cdots & \mathbf{A}^{n-1}\mathbf{B}
* \end{pmatrix}
* \f]
* - the <em>output controllability matrix</em> as the following
* \f$p \times (n+1)m\f$ matrix:
* \f[
* \begin{pmatrix}
* \mathbf{C}\mathbf{B} & \mathbf{C}\mathbf{A}\mathbf{B} & \cdots & \mathbf{C}\mathbf{A}^{n-1}\mathbf{B} & \mathbf{D}
* \end{pmatrix}
* \f]
* .
* Then, we say that:
* - A system is <em>complete state controllable</em> (or simply
* \e controllable) if and only if the associated controllability matrix is of
* rank \f$n\f$.
* - A system is <em>complete output controllable</em> (or simply
* \e output controllable) if and only if the associated output
* controllability matrix is of rank \f$p\f$.
* .
*
* \note
* Estimating the rank of the controllability matrix is ill-conditioned; that
* is, it is very sensitive to roundoff errors and errors in the data.
*
* References:
* -# <NAME>, <em>Modern Control Engineering</em>, 3rd edition, Prentice Hall, 2002.
* .
*
* \todo
* It might be a good idea to add an additional parameter to the function for
* checking controllability, representing the tolerance with which estimating
* the rank of the controllability matrix. However, this may be a problem if we
* change in the future the way we check for controllability. As a matter of
* fact, there are several ways for checking the controllability of a system.
* For instance, in Octave, controllability is determined by applying Arnoldi
* iteration with complete re-orthogonalization to obtain an orthogonal basis
* of the Krylov subspace.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_ANALYSIS_CONTROLLABILITY_HPP
#define DCS_CONTROL_ANALYSIS_CONTROLLABILITY_HPP
#include <algorithm>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/eps.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <boost/numeric/ublasx/operation/rot90.hpp>
#include <boost/numeric/ublasx/operation/sum.hpp>
#include <boost/numeric/ublasx/operation/svd.hpp>
#include <limits>
namespace dcs { namespace control {
/**
* \brief Type traits for building the type of the controllability matrix given
* the type of the state and the input matrices.
*
* \tparam AMatrixT The type of the state matrix for a state-space system model.
* \tparam BMatrixT The type of the input matrix for a state-space system model.
*/
template <
typename AMatrixT,
typename BMatrixT
>
struct controllability_matrix_traits
{
/// The type of the controllability matrix.
typedef typename ::boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type type;
};
/**
* \brief Type traits for building the type of the output controllability matrix
* given the type of the state, the input, the output, and the direct
* transmission matrices.
*
* \tparam AMatrixT The type of the state matrix for a state-space system model.
* \tparam BMatrixT The type of the input matrix for a state-space system model.
* \tparam CMatrixT The type of the control matrix for a state-space system
* model.
* \tparam DMatrixT The type of the direct transmission matrix for a state-space
* system model.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT
>
struct output_controllability_matrix_traits
{
/// The type of the output controllability matrix.
typedef typename ::boost::numeric::ublas::matrix_temporary_traits<AMatrixT>::type type;
};
/**
* \brief Compute the (state) controllability matrix.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space system
* model.
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \return The state controllability matrix.
*/
template <
typename AMatrixT,
typename BMatrixT
>
typename controllability_matrix_traits<
AMatrixT,
BMatrixT
>::type make_controllability_matrix(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename controllability_matrix_traits<AMatrixT,BMatrixT>::type matrix_type;
typedef typename ublas::matrix_traits<matrix_type>::value_type value_type;
typedef typename ublas::matrix_traits<matrix_type>::size_type size_type;
size_type n = ublasx::num_rows(B);
size_type m = ublasx::num_columns(B);
// [B AB A^2*B ... A^{n-1}*B]
matrix_type C = ublas::zero_matrix<value_type>(n, n*m);
ublas::subrange(C, 0, n, 0, m) = B;
for (size_type k = 1; k < n; ++k)
{
size_type km = k*m;
// C[:,k*m+1:(k+1)*m] = A*C[:,(k-1)*m+1:k*m]
ublas::subrange(C, 0, n, km, km+m) = ublas::prod(A, ublas::subrange(C, 0, n, km-m, km));
}
return C;
}
/**
* \brief Compute the output controllability matrix.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space system
* model.
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \return The state controllability matrix.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT
>
typename output_controllability_matrix_traits<
AMatrixT,
BMatrixT,
CMatrixT,
DMatrixT
>::type make_output_controllability_matrix(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename output_controllability_matrix_traits<AMatrixT,BMatrixT,CMatrixT,DMatrixT>::type matrix_type;
typedef typename ublas::matrix_traits<matrix_type>::size_type size_type;
size_type n = ublasx::num_rows(B);
size_type m = ublasx::num_columns(B);
size_type p = ublasx::num_rows(C);
size_type nr = p;
size_type nc = (n+1)*m;
// [C*B C*A*B C*A^2*B ... C*A^{n-1}*B D]
// Compute: [B A*B A^2*B ... A^{n-1}*B]
matrix_type P = make_controllability_matrix(A, B);
size_type xnr = ublasx::num_rows(P);
size_type xnc = ublasx::num_columns(P);
// Make enough space for the output controllability matrix
P.resize(::std::max(nr, xnr), nc, true);
// Compute: C*[B A*B A^2*B ... A^{n-1}*B] == [C*B C*A*B C*A^{2}*B C*A^{n-1}*B]
ublas::subrange(P, 0, nr, 0, xnc) = ublas::prod(C, ublas::subrange(P, 0, xnr, 0, xnc));
// Add D to the last m columns
ublas::subrange(P, 0, nr, xnc, nc) = D;
// Make P of the right size
P.resize(nr, nc, true);
return P;
}
/**
* \brief Test if a system is complete state controllable.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space system
* model.
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \return \c true if the state-space system \f$(\mathbf{A},\mathbf{B})\f$ is
* complete state controllable; \c false otherwise.
*/
template <
typename AMatrixT,
typename BMatrixT
>
bool is_controllable(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
return ::boost::numeric::ublasx::rank(
make_controllability_matrix(A, B)
)
==
::boost::numeric::ublasx::num_rows(B);
}
/**
* \brief Test if a system is complete output controllable.
*
* \tparam AMatrixT The type of the state matrix for the state-space system
* model.
* \tparam BMatrixT The type of the input matrix for the state-space system
* model.
* \tparam CMatrixT The type of the output matrix for the state-space system
* model.
* \tparam DMatrixT The type of the direct transmission matrix for the
* state-space system model.
* \param A The state matrix for the state-space system model.
* \param B The input matrix for the state-space system model.
* \param C The output matrix for the state-space system model.
* \param D The direct transmission matrix for the state-space system model.
* \return \c true if the state-space system \f$(\mathbf{A},\mathbf{B},
* \mathbf{C},\mathbf{D})\f$ is complete output controllable; \c false
* otherwise.
*/
template <
typename AMatrixT,
typename BMatrixT,
typename CMatrixT,
typename DMatrixT
>
bool is_output_controllable(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
::boost::numeric::ublas::matrix_expression<DMatrixT> const& D)
{
return ::boost::numeric::ublasx::rank(
make_output_controllability_matrix(A, B, C, D)
)
==
::boost::numeric::ublasx::num_rows(C);
}
template <typename ValueT>
class controllable_decomposition
{
public: typedef ValueT value_type;
public: typedef ::std::size_t size_type;
public: typedef ::boost::numeric::ublas::matrix<value_type> matrix_type;
public: typedef ::boost::numeric::ublas::vector<size_type> vector_type;
public: controllable_decomposition()
{
}
public: template <
typename AMatrixT,
typename BMatrixT
>
controllable_decomposition(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
decompose(A, B);
}
public: template <
typename AMatrixT,
typename BMatrixT,
typename RealT
>
controllable_decomposition(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
RealT tol)
{
decompose(A, B, tol);
}
public: template <
typename AMatrixT,
typename BMatrixT
>
void decompose(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
//decompose(A, B, ublasx::num_rows(A)*ublas::norm_1(A)*::std::numeric_limits<value_type>::epsilon());,
//decompose(A, B, ::std::max(ublasx::num_rows(A), ublasx::num_columns(A))*ublasx::eps(ublas::norm_2(A)));//FIXME: this is right
decompose(A, B, ::std::max(ublasx::num_rows(A), ublasx::num_columns(A))*ublasx::eps(value_type(ublas::norm_1(A))));//FIXME: this is wrong
}
public: template <
typename AMatrixT,
typename BMatrixT,
typename RealT
>
void decompose(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
RealT tol)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::promote_traits<
typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixT>::size_type,
typename ublas::matrix_traits<BMatrixT>::size_type
>::promote_type,
size_type
>::promote_type work_size_type;
// typedef typename ublas::promote_traits<
// typename ublas::matrix_traits<AMatrixT>::value_type,
// typename ublas::promote_traits<
// typename ublas::matrix_traits<BMatrixT>::value_type,
// typename ublas::promote_traits<
// RealT,
// value_type
// >::promote_type
// >::promote_type
// >::promote_type work_value_type;
size_type A_nr(ublasx::num_rows(A));
// size_type A_nc(ublasx::num_columns(A));
// size_type B_nr(ublasx::num_rows(B));
// size_type B_nc(ublasx::num_columns(B));
// Initialization
k_ = ublas::zero_vector<size_type>(A_nr);
matrix_type PTj(ublas::identity_matrix<value_type>(A_nr, A_nr));
matrix_type Aj(A);
matrix_type Bj(B);
// size_type rojn1 = B_nc;
size_type deltaj = 0;
// size_type sigmaj(A_nr);
// Body loop
for (work_size_type j = 0; j < A_nr; ++j)
{
ublasx::svd_decomposition<value_type> svd;
svd.decompose(Bj);
matrix_type Uj(svd.U());
matrix_type Sj(svd.S());
// matrix_type Vj(svd.V());
size_type Sj_nr(ublasx::num_rows(Sj));
// size_type Sj_nc(ublasx::num_columns(Sj));
matrix_type P(ublasx::rot90(ublas::identity_matrix<value_type>(Sj_nr, Sj_nr), 1));
//ublasx::rot90(ublas::identity_matrix<value_type>(Sj_nr, Sj_nr));
//matrix_type P;
Uj = ublas::prod(Uj, P);
matrix_type BB(ublas::prod(ublas::trans(Uj), Bj));
size_type BB_nr(ublasx::num_rows(BB));
// size_type BB_nc(ublasx::num_columns(BB));
size_type roj(ublasx::rank(BB, tol));
size_type sigmaj(BB_nr-roj);
k_(j) = roj;
if (roj == 0 || sigmaj == 0)
{
break;
}
//matrix_type UAU = ublas::prod(ublas::prod(ublas::trans(Uj), Aj), Uj);
matrix_type UAU(ublas::prod(ublas::trans(Uj), Aj));
UAU = ublas::prod(UAU, Uj);
Aj = ublas::subrange(UAU, 0, sigmaj, 0, sigmaj);
Bj = ublas::subrange(UAU, 0, sigmaj, sigmaj, sigmaj+roj);
size_type Uj_nr(ublasx::num_rows(Uj));
size_type Uj_nc(ublasx::num_columns(Uj));
PTj = ublas::prod(
PTj,
ublasx::cat_columns(
ublasx::cat_rows(Uj, ublas::zero_matrix<value_type>(Uj_nr, deltaj)),
ublasx::cat_rows(ublas::zero_matrix<value_type>(deltaj, Uj_nc), ublas::identity_matrix<value_type>(deltaj, deltaj))
)
);
deltaj += roj;
}
// Finalization
T_ = ublas::trans(PTj);
//Ab_ = ublas::prod(ublas::prod(T_, A), PTj);
Ab_ = ublas::prod(T_, A);
Ab_ = ublas::prod(Ab_, PTj);
Bb_ = ublas::prod(T_, B);
}
/// Return the similarity transformation matrix T such that A_bar=TAT' and B_bar=TB.
public: matrix_type const& T() const
{
return T_;
}
/// Return the vector containing the number of controllable states at each iteration
public: vector_type const& k() const
{
return k_;
}
public: size_type num_controllable_states() const
{
return ::boost::numeric::ublasx::sum(k_);
}
/// Return the transformed A matrix.
public: matrix_type const& A_bar() const
{
return Ab_;
}
/// Return the transformed B matrix.
public: matrix_type const& B_bar() const
{
return Bb_;
}
public: template <typename MatrixT>
matrix_type C_bar(::boost::numeric::ublas::matrix_expression<MatrixT> const& C) const
{
namespace ublas = ::boost::numeric::ublas;
return ublas::prod(C, ublas::trans(T_));
}
private: matrix_type T_;
private: vector_type k_;
private: matrix_type Ab_;
private: matrix_type Bb_;
};
/*
template <
typename AMatrixT,
typename BMatrixT
>
controllable_decomposition(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixT>::value_type,
typename ublas::matrix_traits<BMatrixT>::value_type
>::promote_type value_type;
return controllable_decomposition(A, B, ublasx::num_rows(A)*ublas::norm_1(A)*::std::numeric_limits<value_type>::epsilon());,
}
template <
typename AMatrixT,
typename BMatrixT,
typename RealT
>
controllable_decomposition(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<CMatrixT> const& C,
RealT tol)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixT>::size_type,
typename ublas::matrix_traits<BMatrixT>::size_type
>::promote_type size_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<BMatrixT>::value_type,
RealT
>::promote_type
>::promote_type value_type;
typedef ublas::matrix<value_type> work_matrix_type;
typedef ublas::vector<value_type> work_vector_type;
size_type A_nr(ublasx::num_rows(A));
size_type A_nc(ublasx::num_columns(A));
size_type B_nr(ublasx::num_rows(B));
// size_type B_nc(ublasx::num_columns(B));
// Initialization
work_matrix_type PTj(ublas::identity_matrix<value_type>(A_nr, A_nr));
work_matrix_type Aj(A);
work_matrix_type Bj(B);
// size_type rojn1 = B_nc;
size_type deltaj = 0;
// size_type sigmaj(A_nr);
work_vector_type k(ublas::zero_vector<value_type>(A_nr));
// Body loop
for (size_type j = 0; j < A_nr; ++j)
{
ublasx::svd_decomposition<value_type> svd;
svd.decompose(Bj);
work_matrix_type Uj(svd.U());
work_matrix_type Sj(svd.S());
work_matrix_type Vj(svd.V());
size_type S_nr(ublasx::num_rows(S));
size_type S_nc(ublasx::num_columns(S));
work_matrix_type P(ublasx::rot90(ublas::identity_matrix<value_type>(S_nr, S_nr)));
Uj = ublas::prod(Uj, P);
work_matrix_type BB(ublas::prod(ublas::trans(Uj), Bj));
BB_nr = ublasx::num_rows(BB);
BB_nc = ublasx::num_columns(BB);
size_type roj(ublasx::rank(BB, tol));
size_type sigmaj(BB_nr-roj);
k(jj) = roj;
if (roj == 0 || sigmaj == 0)
{
break;
}
abxy = ublas::prod(ublas::prod(ublas::trans(Uj), Aj), Uj);
Aj = ublas::subrange(abxy, 0, sigmaj, 0, sigmaj);
Bj = ublas::subrange(abxy, 0, sigmaj, sigmaj, sigmaj+roj);
size_type Uj_nr(ublasx::num_rows(Uj));
size_type Uj_nc(ublasx::num_columns(Uj));
PTj = ublas::prod(
PTj,
ublasx::cat_columns(
ublasx::cat_rows(U, ublas::zero_matrix<value_type>(Uj_nr, deltaj)),
ublasx::cat_rows(ublas::zero_matrix<value_type>(deltaj, Uj_nc, ublas::identity_matrix<value_type>(deltaj, deltaj)))
)
);
deltaj += roj;
}
// Finalization
T = ublas::trans(PTj);
//A_bar = ublas::prod(ublas::prod(T, a), ublas::trans(T));
A_bar = ublas::prod(ublas::prod(t, a), PTj);
B_bar = ublas::prod(T, b);
//cbar = ublas::prod(c, ublas::trans(T));
C_bar = ublas::prod(c, PTj);
}
*/
}} // Namespace dcs::control
#endif // DCS_CONTROL_ANALYSIS_CONTROLLABILITY_HPP
<file_sep>/**
* \file dcs/control/design/pid_controller.hpp
*
* \brief PID controller.
*
* A Proportial-Integral-Derivative (PID) controller attempts to correct the
* error between a measured process variable and a desired setpoint by
* calculating and then outputting a corrective action that can adjust the
* process accordingly and rapidly, to keep the error minimal.
*
* The control law is defined as:
* \f{align*}{
* u(t) &= u_P(t)+u_I(t)+u_D(t) \\
* &= K_P e(t) + K_I \int_0^t{q(e(t)) e(\tau)}\,{d\tau} +
* K_D\frac{de}{dt}(t),
* \quad q(e(t)) = \begin{cases}
* 1,& |e(t)|\le E\\
* 0,& \text{otherwise}
* \end{cases}
* \f}
* where:
* - \f$u_P(t)\f$ is the proportional term, which determines the reaction to the
* current error;
* - \f$u_I(t)\f$ is the integral term, which determines the reaction based on
* the sum of recent errors;
* - \f$u_D(t)\f$ is the derivative term, which determines the reaction based on
* the rate at which the error has been changing.
* - \f$K_P\f$ is the proportional gain: larger values typically mean faster
* response since the larger the error, the larger the proportional term
* compensation; however, an excessively large proportional gain will lead to
* system instability and oscillation.
* - \f$K_I\f$ is the integral gain: larger values imply steady state errors are
* eliminated more quickly; however, the trade-off is larger overshoot, since
* any negative error integrated during transient response must be integrated
* away by positive error before we reach steady state.
* - \f$K_D\f$ is the derivative gain: larger values decrease overshoot, but
* slows down transient response and may lead to instability due to signal
* noise amplification in the differentiation of the error.
* - \f$q(\cdot)\f$ is a function used for turning on or off the integration
* when the amplitude (i.e., the absolute value) of the error signal is above
* a cutoff level \f$E\f$; its purpose is to mitigate the integrator
* windup (also called reset windup) problem, resulting whenever actuator
* saturation occurs, that is when integrating a large error signal during
* periods when the actuator is unable to respond fully to its commanded
* behavior; the problem is that the integrated error term can reach a very
* large value during these periods, which results in significant overshoot in
* the system response; oscillation is also a possibility, with the actuator
* banging from one end of its range of motion to the other.
* .
*
* \note
* Actually, this implementation is based on the discretized version of the
* above control law, that is:
* \f[
* u(t+\Delta\,t) = K_P e(t+\Delta\,t) + K_I \Delta\,t \sum_{i=0}^{t+\Delta\,t}{e(t+i\Delta\,t)} + K_D\frac{e(t+\Delta\,t)-e(t)}{\Delta\,t}
* \f]
* where \f$\Delta\,t\f$ is the sampling time</em> (also known as <em>control
* time</em> or <em>step time</em>).
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_PID_CONTROLLER_HPP
#define DCS_CONTROL_PID_CONTROLLER_HPP
#include <cmath>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <functional>
#include <limits>
#include <stdexcept>
namespace dcs { namespace control {
/**
* \brief Class for single-loop PID controllers.
*
* A single-loop PID controller can be used to control Single-Input Single-Output
* (SISO) systems.
*
* The control law is thus given by:
* \f[
* u(k) = K_Pe(k)+K_I\sum_{i=0}^k{e(k)}+K_D(e(k)-e(k-1))
* \f]
* where:
* - \f$u_j(k)\f$ is the <em>control signal</em> at time \f$k\f$,
* - \f$e_j(k)\f$ is the <em>control error</em> at time \f$k\f$,
* - \f$K_{P,j}\f$ is the <em>proportional gain</em>,
* - \f$K_{I,j}\f$ is the <em>integral gain</em>,
* - \f$K_{D,j}\f$ is the <em>derivative gain</em>.
* .
*
* \author <NAME>, <<EMAIL>>
*/
template <typename RealT = double>
class pid_controller
{
public: typedef RealT real_type;
/**
* \brief A constructor.
*
* \param kp The proportional gain.
* \param ki The integral gain.
* \param kd The derivative gain.
* \param step_time The control time.
* \param err_thresh The error cutoff level used for mitigating the
* integrator windup problem; set to \f$\infty\f$ for not using it.
*/
public: pid_controller(real_type kp, real_type ki, real_type kd, real_type step_time, real_type err_thresh = ::std::numeric_limits<real_type>::infinity())
: kp_(kp),
ki_(ki),
kd_(kd),
ts_(step_time),
err_thresh_(err_thresh),
prev_err_(0),
integral_(0),
started_(false)
{
// Empty
}
public: real_type sampling_time() const
{
return ts_;
}
public: real_type proportional_gain() const
{
return kp_;
}
public: real_type integral_gain() const
{
return ki_;
}
public: real_type derivative_gain() const
{
return kd_;
}
/**
* \brief Update the control signal according to the given control error.
* \param error The current control error.
* \return The new control signal.
*
* \note
* This version uses the positional algorithm:
* \f{align*}{
* u(k) &= u_P(k) + u_I(k) + u_D(k) \\
* &= K_P e(k) + K_I \sum_{i=0}^{k} e(i) + K_D (e(k)-e(k-1))
* \f}
*/
public: real_type control(real_type error)
{
// Update if the error magnitude is below the threshold.
if (
err_thresh_ == ::std::numeric_limits<real_type>::infinity()
|| ::std::abs(error) < err_thresh_
) {
// Update the error integral according to the forward difference
// equation:
// (u_I(k+h) - u_I(k))h = K_I ==> u_I(k+h) = u_I(k) + h*e(k+h)*K_I
integral_ += ts_*error;
}
// Compute the error derivative according to the backward difference
// equation:
// K_D*(u_D(k)-u_D(k-1))/h+u_D(k) = -K_D*e(k)/h
real_type deriv(0);
if (started_)
{
deriv = (error - prev_err_) / ts_;
}
prev_err_ = error;
if (!started_)
{
started_ = true;
}
// Return the PID controller actuator command
return kp_*error + ki_*integral_ + kd_*deriv;
}
// Use the incremental algorithm (aka velocity algorithm)
// u(t_k)=u(t_{k-1})+K_p\left[\left(1+\dfrac{\Delta t}{T_i}+\dfrac{T_d}{\Delta t}\right)e(t_k)+\left(-1-\dfrac{2T_d}{\Delta t}\right)e(t_{k-1})+\dfrac{T_d}{\Delta t}e(t_{k-2})\right]
//real_type control(real_type error);
/// Proportional gain.
private: real_type kp_;
/// Integral gain.
private: real_type ki_;
/// Differential gain.
private: real_type kd_;
/// Controller step time.
private: real_type ts_;
/// Error cutoff level for preventing the integrator windup problem.
private: real_type err_thresh_;
/// The control error at the previous control interval.
private: real_type prev_err_;
/// Integrator state.
private: real_type integral_;
/// Tell if the controller is started.
private: bool started_;
};
/**
* \brief Class for multi-loop PID controllers.
*
* A multi-loop PID controller can be used to control Multi-Input Multi-Output
* (MIMO) systems.
* In a multi-loop PID controller, control is performed by considering each
* single-loop PID controller independently.
*
* The control law is thus given by:
* \f[
* u_j(k) = K_{P,j}e_j(k)+K_{I,j}\sum_{i=0}^k{e_j(k)}+K_{D,j}(e_j(k)-e_j(k-1))
* \f]
* for \f$j=1,\ldots,n_u\f$, where:
* - \f$u_j(k)\f$ is the <em>control signal</em> at time \f$k\f$ for the
* \f$j\f$-th single-loop PID controller,
* - \f$e_j(k)\f$ is the <em>control error</em> at time \f$k\f$ for the
* \f$j\f$-th single-loop PID controller,
* - \f$K_{P,j}\f$ is the <em>proportional gain</em> for the \f$j\f$-th
* single-loop PID controller,
* - \f$K_{I,j}\f$ is the <em>integral gain</em> for the \f$j\f$-th single-loop
* PID controller,
* - \f$K_{D,j}\f$ is the <em>derivative gain</em> for the \f$j\f$-th
* single-loop PID controller.
* .
*
* \author <NAME>, <<EMAIL>>
*/
template <typename VectorT, typename RealT = double>
class multiloop_pid_controller
{
public: typedef VectorT vector_type;
public: typedef RealT real_type;
/**
* \brief A constructor.
*
* \param kp The proportional gain matrix.
* \param ki The integral gain matrix.
* \param kd The derivative gain matrix.
* \param step_time The control (step) time.
* \param err_thresh The error cutoff level used for mitigating the
* integrator windup problem; set to \f$\infty\f$ for not using it.
*/
public: multiloop_pid_controller(vector_type kp, vector_type ki, vector_type kd, real_type step_time, vector_type err_thresh = vector_type(1, ::std::numeric_limits<real_type>::infinity()))
: kp_(kp),
ki_(ki),
kd_(kd),
ts_(step_time),
err_thresh_(err_thresh),
prev_err_(::boost::numeric::ublasx::size(kp), 0),
integral_(::boost::numeric::ublasx::size(ki), 0),
started_(false)
{
// preconditions
DCS_ASSERT(
::boost::numeric::ublasx::size(kp) == ::boost::numeric::ublasx::size(ki)
&&
::boost::numeric::ublasx::size(kp) == ::boost::numeric::ublasx::size(kd),
throw ::std::invalid_argument("Non conformant dimensions for K_P, K_I and K_D gains.")
);
// Make sure the error threshold vector has a compliant size.
typedef typename ::boost::numeric::ublas::vector_traits<vector_type>::size_type size_type;
size_type n = ::boost::numeric::ublasx::size(kp);
size_type m = ::boost::numeric::ublasx::size(err_thresh_);
if (m < n)
{
err_thresh_.resize(n, true);
real_type val = (m > 0) ? err_thresh_(m-1) : ::std::numeric_limits<real_type>::infinity();
while (m < n)
{
err_thresh_[m++] = val;
}
}
}
public: real_type sampling_time() const
{
return ts_;
}
public: vector_type proportional_gain() const
{
return kp_;
}
public: vector_type integral_gain() const
{
return ki_;
}
public: vector_type derivative_gain() const
{
return kd_;
}
/**
* \brief Compute the control signal according to the given control error.
* \param error The current control error.
* \return The new control signal.
*
* \note
* This version uses the positional algorithm:
* \f{align*}{
* u(k) &= u_P(k) + u_I(k) + u_D(k) \\
* &= K_P e(k) + K_I \sum_{i=0}^{k} e(i) + K_D (e(k)-e(k-1))
* \f}
*/
public: vector_type control(vector_type error)
{
// preconditions
DCS_ASSERT(
::boost::numeric::ublasx::size(error) == ::boost::numeric::ublasx::size(err_thresh_),
throw ::std::invalid_argument("Wrong length of error vector.")
);
typedef typename vector_type::size_type size_type;
// Update if the error magnitude is below the threshold.
size_type err_len = ::boost::numeric::ublasx::size(error);
for (size_type i = 0; i < err_len; ++i)
{
if (
(err_thresh_(i) == ::std::numeric_limits<real_type>::infinity())
||
(::std::abs(error(i)) < err_thresh_(i))
) {
// Update the error integral according to the forward difference
// equation:
// (u_I(k+h) - u_I(k))/h = K_I ==> u_I(k+h) = u_I(k) + h*e(k+h)*K_I
integral_(i) += ts_*error(i);
}
}
// Compute the error derivative according to the backward difference
// equation:
// K_D*(u_D(k)-u_D(k-h))/h+u_D(k) = -K_D*e(k)/h
vector_type deriv(err_len, 0);
if (started_)
{
deriv = (error - prev_err_) / ts_;
}
prev_err_ = error;
if (!started_)
{
started_ = true;
}
// Return the PID controller actuator command
return ::boost::numeric::ublas::element_prod(kp_, error)
+ ::boost::numeric::ublas::element_prod(ki_, integral_)
+ ::boost::numeric::ublas::element_prod(kd_, deriv);
}
// Use the incremental algorithm (aka velocity algorithm)
// u(k) = u(k-1) + K_P \left[\left(1+\frac{\Delta t}{T_I}+\frac{T_D}{\Delta t}\right)e(k)+\left(-1-\frac{2T_D}{\Delta t}e(k-1)+\frac{T_D}{\Delta t}e(k-2)\right)\right]
//vector_type control(vector_type error);
/// Proportional gain.
private: vector_type kp_;
/// Integral gain.
private: vector_type ki_;
/// Differential gain.
private: vector_type kd_;
/// Control (step) time.
private: real_type ts_;
/// Error cutoff level for preventing the integrator windup problem.
private: vector_type err_thresh_;
/// The control error at the previous control interval.
private: vector_type prev_err_;
/// Integrator state.
private: vector_type integral_;
/// Tell if the controller is started.
private: bool started_;
};
/**
* \brief Class for Multi-Input Multi-Output (MIMO) PID controllers.
*
* A MIMO PID controller can be used to control MIMO systems.
* A MIMO PID controller differs from a multi-loop PID controller since it takes
* care of possible interactions between control signals.
* The control law is thus given by:
* \f[
* \mathbf{u}(k) = \mathbf{K}_P \mathbf{e}(k) + \mathbf{K}_I \sum_{i=0}^k{\mathbf{e}(k)} + \mathbf{K}_D(\mathbf{e}(k)-\mathbf{e}(k-1))
* \f]
* where:
* - \f$\mathbf{u}(k)\f$ is the <em>control signal vector</em> at time \f$k\f$,
* - \f$\mathbf{e}(k)\f$ is the <em>control error vector</em> at time \f$k\f$,
* - \f$\mathbf{K}_P\f$ is the <em>proportional gain matrix</em>,
* - \f$\mathbf{K}_I\f$ is the <em>integral gain matrix</em>,
* - \f$\mathbf{K}_D\f$ is the <em>derivative gain matrix</em>.
* .
*
* \author <NAME>, <<EMAIL>>
*/
template <typename VectorT, typename MatrixT, typename RealT = double>
class mimo_pid_controller
{
public: typedef VectorT vector_type;
public: typedef MatrixT matrix_type;
public: typedef RealT real_type;
/**
* \brief A constructor.
*
* \param kp The proportional gain matrix.
* \param ki The integral gain matrix.
* \param kd The derivative gain matrix.
* \param step_time The control (step) time.
* \param err_thresh The error cutoff level used for mitigating the
* integrator windup problem; set to \f$\infty\f$ for not using it.
*/
public: mimo_pid_controller(matrix_type kp, matrix_type ki, matrix_type kd, real_type step_time, vector_type err_thresh = vector_type(::std::numeric_limits<real_type>::infinity()))
: kp_(kp),
ki_(ki),
kd_(kd),
ts_(step_time),
err_thresh_(err_thresh),
prev_err_(::boost::numeric::ublasx::num_rows(kp), 0),
integral_(::boost::numeric::ublasx::num_rows(ki), 0),
started_(false)
{
// preconditions
DCS_ASSERT(
::boost::numeric::ublasx::num_rows(kp) == ::boost::numeric::ublasx::num_rows(ki)
&&
::boost::numeric::ublasx::num_columns(kp) == ::boost::numeric::ublasx::num_columns(ki)
&&
::boost::numeric::ublasx::num_rows(kp) == ::boost::numeric::ublasx::num_rows(kd)
&&
::boost::numeric::ublasx::num_columns(kp) == ::boost::numeric::ublasx::num_columns(kd),
throw ::std::invalid_argument("Non conformant dimensions for K_P, K_I and K_D gains.")
);
// Make sure the error threshold vector has a compliant size.
typedef typename ::boost::numeric::ublas::vector_traits<vector_type>::size_type size_type;
size_type n = ::boost::numeric::ublasx::num_rows(kp);
size_type m = ::boost::numeric::ublasx::size(err_thresh_);
if (m < n)
{
err_thresh_.resize(n, true);
real_type val = (m > 0) ? err_thresh_(m-1) : ::std::numeric_limits<real_type>::infinity();
while (m < n)
{
err_thresh_[m++] = val;
}
}
}
public: real_type sampling_time() const
{
return ts_;
}
public: matrix_type proportional_gain() const
{
return kp_;
}
public: matrix_type integral_gain() const
{
return ki_;
}
public: matrix_type derivative_gain() const
{
return kd_;
}
/**
* \brief Update the control signal according to the given control error.
* \param error The current control error.
* \return The new control signal.
*
* \note
* This version uses the positional algorithm:
* \f{align*}{
* u(k) &= u_P(k) + u_I(k) + u_D(k) \\
* &= K_P e(k) + K_I \sum_{i=0}^{k} e(i) + K_D (e(k)-e(k-1))
* \f}
*/
public: vector_type control(vector_type error)
{
// preconditions
DCS_ASSERT(
::boost::numeric::ublasx::size(error) == ::boost::numeric::ublasx::size(err_thresh_),
throw ::std::invalid_argument("Wrong length of error vector.")
);
typedef typename vector_type::size_type size_type;
// Update if the error magnitude is below the threshold.
size_type err_len = ::boost::numeric::ublasx::size(error);
for (size_type i = 0; i < err_len; ++i)
{
if (
(err_thresh_(i) == ::std::numeric_limits<real_type>::infinity())
||
(::std::abs(error(i)) < err_thresh_(i))
) {
// Update the error integral according to the forward difference
// equation:
// (u_I(k+h) - u_I(k))/h = K_I ==> u_I(k+h) = u_I(k) + h*e(k+h)*K_I
integral_(i) += ts_*error(i);
}
}
// Compute the error derivative according to the backward difference
// equation:
// K_D*(u_D(k)-u_D(k-h))/h+u_D(k) = -K_D*e(k)/h
vector_type deriv(err_len, 0);
if (started_)
{
deriv = (error - prev_err_) / ts_;
}
prev_err_ = error;
if (!started_)
{
started_ = true;
}
// Return the PID controller actuator command
return ::boost::numeric::ublas::prod(kp_, error)
+ ::boost::numeric::ublas::prod(ki_, integral_)
+ ::boost::numeric::ublas::prod(kd_, deriv);
}
// Use the incremental algorithm (aka velocity algorithm)
// u(k) = u(k-1) + K_P \left[\left(1+\frac{\Delta t}{T_I}+\frac{T_D}{\Delta t}\right)e(k)+\left(-1-\frac{2T_D}{\Delta t}e(k-1)+\frac{T_D}{\Delta t}e(k-2)\right)\right]
//vector_type control(vector_type error);
/// Proportional gain.
private: matrix_type kp_;
/// Integral gain.
private: matrix_type ki_;
/// Differential gain.
private: matrix_type kd_;
/// Control (step) time.
private: real_type ts_;
/// Error cutoff level for preventing the integrator windup problem.
private: vector_type err_thresh_;
/// The control error at the previous control interval.
private: vector_type prev_err_;
/// Integrator state.
private: vector_type integral_;
/// Tell if the controller is started.
private: bool started_;
};
/**
* \brief PID controller in standard form.
*
* A single-loop PID controller can be used to control Single-Input Single-Output
* (SISO) systems.
*
* The control law is thus given by:
* \f[
* u(k) = K_P\left(e(k)+\frac{1}{T_I}\sum_{i=0}^k{e(i)}+T_D(e(k)-e(k-1)\right))
* \f]
* where:
* - \f$u_j(k)\f$ is the <em>control signal</em> at time \f$k\f$,
* - \f$e_j(k)\f$ is the <em>control error</em> at time \f$k\f$,
* - \f$K_{P,j}\f$ is the <em>proportional gain</em>,
* - \f$T_I\f$ is the <em>integral time</em>,
* - \f$T_D\f$ is the <em>derivative time</em>.
* .
*
* The ideal and standard PID controller are related by:
* \f{align*}{
* K_P &= K_P \\
* K_I &= \frac{K_P}{T_I} \\
* K_D &= K_P T_D
* \f}
*
* \author <NAME>, <<EMAIL>>
*/
template <typename RealT = double>
class std_pid_controller
{
public: typedef RealT real_type;
public: std_pid_controller(real_type kp, real_type int_time, real_type deriv_time, real_type step_time, real_type err_thresh = ::std::numeric_limits<real_type>::infinity())
: pid_(kp, kp/int_time, kp*deriv_time, err_thresh)
{
// Empty
}
public: real_type sampling_time() const
{
return pid_.sampling_time();
}
public: real_type proportional_gain() const
{
return pid_.proportional_gain();
}
public: real_type integral_time() const
{
return pid_.proportional_gain()/pid_.integral_gain();
}
public: real_type derivative_time() const
{
return pid_.derivative_gain()/pid_.proportional_gain();
}
public: real_type control(real_type error)
{
return pid_.control(error);
}
private: pid_controller<real_type> pid_;
};
}} // dcs::control
#endif // DCS_CONTROL_PID_CONTROLLER_HPP
<file_sep>/**
* \file src/dcs/control/solver/dare_slicot5.hpp
*
* \brief Discrete-time Algebraic Riccati Equations solver.
*
* Computes the unique stabilizing solution \f$X\f$ of the discrete-time
* algebraic Riccati equation
* \f[
* A^{T}XA - E^{T}XE - (A^{T}XB+S)(B^{T}XB+R)^{-1}(B^{T}X A+S)^{T} + Q = 0
* \f]
* or, equivalently (if \f$R\f$ is nonsingular):
* \f[
* E^{T}XE = F^{T}XF-F^{T}XB(B^{T}XB+R)^{-1}B^{T}XF + Q - SR^{-1}S^{T}
* \f]
* where \f$F=A-BR^{-1}S^{T}\f$.
*
* Beside the solution \f$X\f$, the solver also computes the \e gain matrix
* \f[ -1
* G = (B^{T}XB + R)^{-1}(B^{T}XA + S^{T})
* \f]
* and the vector \f$L\f$ of <em>closed-loop eigenvalues</em> associated to the
* generalized Schur decomposition of matrix pencil \f$(A-BG,E)\f$.
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_SOLVER_DARE_SLICOT5_HPP
#define DCS_CONTROL_SOLVER_DARE_SLICOT5_HPP
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublasx/container/generalized_diagonal_matrix.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/diag.hpp>
#include <boost/numeric/ublasx/operation/lu.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/ql.hpp>
#include <boost/numeric/ublasx/operation/qz.hpp>
#include <boost/numeric/ublasx/operation/rcond.hpp>
#include <boost/numeric/ublasx/operation/seq.hpp>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
#include <stdexcept>
namespace dcs { namespace control {
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
template <typename ValueT>
class dare_solver
{
public: typedef ValueT value_type;
public: typedef typename ublas::type_traits<value_type>::real_type real_type;
private: typedef ublas::matrix<value_type,ublas::column_major> work_matrix_type;
private: typedef ublas::vector< ::std::complex<value_type> > work_vector_type;
public: typedef work_matrix_type matrix_type;
public: typedef work_vector_type vector_type;
private: typedef typename ublas::matrix_traits<work_matrix_type>::size_type size_type;
// Default constructor
public: dare_solver()
{
// empty
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT
>
dare_solver(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q)
{
solve(A, B, Q);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT
>
dare_solver(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R)
{
solve(A, B, Q, R);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT
>
dare_solver(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R, ublas::matrix_expression<SMatrixExprT> const& S)
{
solve(A, B, Q, R, S);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT
>
dare_solver(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R, ublas::matrix_expression<SMatrixExprT> const& S, ublas::matrix_expression<EMatrixExprT> const& E)
{
solve(A, B, Q, R, S, E);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT
>
void solve(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q)
{
work_matrix_type R = ublas::identity_matrix<value_type>(ublas::num_columns(B));
solve(A, B, Q, R);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT
>
void solve(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R)
{
work_matrix_type S = ublas::zero_matrix<value_type>(ublas::num_rows(B), ublas::num_columns(B));
solve(A, B, Q, R, S);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT
>
void solve(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R, ublas::matrix_expression<SMatrixExprT> const& S)
{
work_matrix_type E = ublas::identity_matrix<value_type>(ublas::num_rows(B));
solve(A, B, Q, R, S, E);
}
public: template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT
>
void solve(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R, ublas::matrix_expression<SMatrixExprT> const& S, ublas::matrix_expression<EMatrixExprT> const& E)
{
size_type n = ublasx::num_rows(B);
size_type m = ublasx::num_columns(B);
// precondition: n > 0 && m > 0
DCS_ASSERT(
n > 0 && m > 0,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Empty matrix.")
);
// precondition: A is square && num_rows[A] == num_rows[B]
DCS_ASSERT(
ublasx::num_rows(A) == n && ublasx::num_columns(A) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A must be a square matrix and must have the same number of rows of B.")
);
// precondition: Q is square && size[Q] == size[A]
DCS_ASSERT(
ublasx::num_rows(Q) == n && ublasx::num_columns(Q) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: Q is symmetric
DCS_ASSERT(
ublas::norm_1(Q-ublas::trans(Q)) <= 100*eps*ublas::norm_1(Q),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Q must be symmetric.")
);
// precondition: R is square && num_rows[R] == num_columns[B]
DCS_ASSERT(
ublasx::num_rows(R) == m && ublasx::num_columns(R) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be a square matrix and must have the same number of columns of B.")
);
// precondition: R is symmetric
DCS_ASSERT(
ublas::norm_1(R-ublas::trans(R)) <= 100*eps*ublas::norm_1(R),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be symmetric.")
);
// precondition: size[S] == size[B]
DCS_ASSERT(
ublasx::num_rows(S) == n && ublasx::num_columns(S) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] B and S must be the same size.")
);
// precondition: E is square && size[E] == size[A]
DCS_ASSERT(
ublasx::num_rows(E) == n && ublasx::num_columns(E) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: E != I_n && E is not singular
DCS_ASSERT(
/*E != ublas::identity_matrix(n) && */ublasx::rcond(E) >= eps,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be nonsingular.")
);
// reset state
X_.resize(0, 0, false);
G_.resize(0, 0, false);
// Create temporary copies of Q, R, S matrices and make sure that Q and R
// are symmetric matrices.
work_matrix_type work_Q((Q + ublas::trans(Q))/real_type(2));
work_matrix_type work_R((R + ublas::trans(R))/real_type(2));
work_matrix_type work_S(S);
// Scale Q,R,S so that norm_1(Q)+norm_1(R)+norm_1(S) = 1
real_type scale_factor(0);
scale_factor += ublas::norm_1(work_Q)+ublas::norm_1(work_R)+ublas::norm_1(S);
// Chek if the scaling factor is too near to zero.
if (scale_factor <= eps)
{
scale_factor = real_type(1);
}
work_Q /= scale_factor;
work_R /= scale_factor;
work_S /= scale_factor;
// Set up extended Symplectic pencil (H,J) of the form:
// |A 0 B| |E 0 0|
// H - z J = |Q -E' S| - z |0 -A' 0|
// |S' 0 R| |0 -B' 0|
// of dimension (2N+M)x(2N+M), where N and M are the number of rows and of
// of columns of matrix B, respectively.
work_matrix_type H; // (2*n+m,2*n+m)
work_matrix_type J; // (2*n+m,2*n+m)
H = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
ublasx::cat_rows(
A,
ublas::zero_matrix<value_type>(n,n)
),
B
),
ublasx::cat_rows(
ublasx::cat_rows(
work_Q,
-ublas::trans(E)
),
work_S
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::trans(work_S),
ublas::zero_matrix<value_type>(m, n)
),
work_R
)
);
J = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
E,
ublas::zero_matrix<value_type>(n, n+m)
),
ublasx::cat_rows(
ublas::zero_matrix<value_type>(n, n),
ublasx::cat_rows(
-ublas::trans(A),
ublas::zero_matrix<value_type>(n, m)
)
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::zero_matrix<value_type>(m, n),
-ublas::trans(B)
),
ublas::zero_matrix<value_type>(m)
)
);
// Undo scaling of the data matrices.
//work_Q *= scale_factor;
//work_R *= scale_factor;
//work_S *= scale_factor;
// Temporary copies of Q, R, and S not needed any more.
work_Q.resize(0, 0, false);
work_R.resize(0, 0, false);
work_S.resize(0, 0, false);
// Compress the pencils using QL factorization.
// The compressed form is (see [1]):
// \lambda H - J
// where H and J are 2n-by-2n matrices.
// [1] <NAME>.
// A Generalized Eigenvalue Approach for Solving Riccati Equations.
// SIAM J. Sci. Stat. Comp., 2, pp. 121-135, 1981.
//
size_type n2 = n*2;
size_type n2pm = n2 + m;
ublasx::ql_decomposition<value_type> ql(ublas::subrange(H, 0, n2pm, n2, n2pm));
work_matrix_type tmp_HJ;
tmp_HJ = ublas::subrange(H, 0, n2pm, 0, n2);
H = ublas::subrange(ql.tlprod(tmp_HJ), 0, n2, 0, n2);
tmp_HJ = ublas::subrange(J, 0, n2pm, 0, n2);
J = ublas::subrange(ql.tlprod(tmp_HJ), 0, n2, 0, n2);
// Check the singularity of the L factor in the QL factorization:
// if singular, then the extended matrix pencil is also singular.
if (ublasx::rcond(ql.L()) <= eps)
{
DCS_DEBUG_TRACE("The extended matrix pencil is singular");
throw ::std::runtime_error("[dcs::control::dare_solver::solve] Cannot compute DARE solution: the extended matrix pencil is singular.");
}
// The natural tendency of the QZ algorithm to get the largest
// eigenvalues in the leading part of the matrix pair is
// exploited, by computing the unstable eigenvalues (i.e., the ones
// outside the unit circle) of the permuted matrix pair (J,H).
// This is equivalent to take the eigenvalues inside the unit circle of
// the matrix pair (H,J).
//ublasx::qz_decomposition<work_matrix_type,work_matrix_type> qz;
//qz.decompose(H, J, ublasx::udi_qz_eigenvalues);
work_matrix_type Z;
//ublasx::qz_decompose_inplace(J, H, qzQ, qzZ, ublasx::udo_qz_eigenvalues);//FIXME:test me
//TODO: clear qzQ since it seems it is not used
ublasx::qz_decomposition<value_type> qz;
qz.decompose(J, H);
qz.reorder(ublasx::udo_qz_eigenvalues);
Z = qz.Z();
// Compute the n stable closed-loop eigenvalues of the system matrix
// A-BG, where G is the optimal feedback matrix computed based on the
// solution matrix X.
// These eigenvalues correspond to the the trailing n generalized
// eigenvalues of the QZ decomposition
l_ = ublas::subrange(qz.eigenvalues(), n, n2);
// Select submatrices X1 and X2 out of the matrix Z which define the
// solution X = X2 * inv(X1).
// Since X = X' we may obtain X as the solution of the system of
// linear equations X1' X = X2', where
// X1 = Z(1:n, 1:n),
// X2 = Z(n+1:2n, 1:n).
work_matrix_type X1 = ublas::subrange(Z, 0, n, 0, n);
work_matrix_type X2 = ublas::subrange(Z, n, n2, 0, n);
// Z is not needed any more
Z.resize(0, 0, false);
//// Check if X1 is singular
//X1_norm = ublas::norm_1(X1);
// Solve the system X1' X = X2'
//work_matrix_type X;
size_type sing;
sing = ublasx::lu_solve(ublas::trans(X1), ublas::trans(X2), X_);
// ublas::permutation_matrix<size_type> P(n);
// X1 = ublas::trans(X1);
// ublasx::lu_decompose_inplace(X1, P);
// if (ublasx::rcond(X1) < eps)
// {
// // Nearly singular matrix
// //FIXME: what to do?
// }
// X = ublasx::lu_apply(X1, P, ublas::trans(X2));
if (sing)
{
// Nearly singular matrix
DCS_DEBUG_TRACE("Cannot compute DARE solution: nearly singular matrix.");
throw ::std::runtime_error("[dcs::control::dare_solver::solve] Cannot compute DARE solution: nearly singular matrix.");
}
// Make sure the solution X is symmetrix
X_ = scale_factor * (X_ + ublas::trans(X_))/real_type(2);
// Compute the Gain matrix G = (B'*X*B+R)\(B'*X*A+S');
work_matrix_type BTX(ublas::prod(ublas::trans(B), X_));
sing = ublasx::lu_solve(
ublas::prod(BTX, B) + R,
ublas::prod(BTX, A) + ublas::trans(S),
G_
);
if (sing)
{
// Nearly singular matrix
DCS_DEBUG_TRACE("Cannot compute DARE gain matrix: nearly singular matrix.");
throw ::std::runtime_error("[dcs::control::dare_solver::solve] Cannot compute DARE gain matrix: nearly singular matrix.");
}
}
public: matrix_type solution() const
{
return X_;
}
/// Return the gain matrix: \f$(B^T X B + R)^{-1}( B^T X A + S^T)\f$.
public: matrix_type gain() const
{
return G_;
}
/**
* \brief Return the closed-loop eigenvalues vector.
*
* The closed-loop eigenvalues vector \f$\lambda\f$ is computed as:
* \f[
* \lambda = \operatorname{eig}(A-BG, E)
* \f]
* where \f$G\f$ is the gain matrix.
*/
public: vector_type eigenvalues() const
{
return l_;
}
private: static const real_type eps;
private: work_matrix_type X_; /// The solution matrix
private: work_matrix_type G_; /// The gain matrix
private: work_vector_type l_; /// The closed-loop eigenvalues vector.
};
template <typename ValueT>
const typename ublas::type_traits<ValueT>::real_type dare_solver<ValueT>::eps = ::std::numeric_limits<typename ublas::type_traits<ValueT>::real_type>::epsilon();
/**
* \brief Solve the discrete-time algebraic Ricciati equation (DARE).
*
* Computes the unique stabilizing solution X of the discrete-time algebraic
* Riccati equation
* \f[
* A^{T}XA-E^{T}XE-(A^{T}XB+S)(B^{T}XB+R)^{-1}(B^{T}XA+S)+Q=0
* \f]
* The dare function also returns the gain matrix
* \f[
* G=(B^{T}XB+R)^{-1}(B^{T}XA+S)
* \f]
* and the vector L of closed loop eigenvalues, where
* \f[
* L=\operatorname{eigen}(A-B*G,E)
* \f]
*
* \author <NAME>, <EMAIL>
*/
template <
typename AMatrixExprT,
typename BMatrixExprT,
typename QMatrixExprT,
typename RMatrixExprT,
typename SMatrixExprT,
typename EMatrixExprT,
typename XMatrixT
>
void dare(ublas::matrix_expression<AMatrixExprT> const& A, ublas::matrix_expression<BMatrixExprT> const& B, ublas::matrix_expression<QMatrixExprT> const& Q, ublas::matrix_expression<RMatrixExprT> const& R, ublas::matrix_expression<SMatrixExprT> const& S, ublas::matrix_expression<EMatrixExprT> const& E, XMatrixT& X)
{
#if 0
typedef AMatrixExprT A_matrix_type;
typedef BMatrixExprT B_matrix_type;
typedef QMatrixExprT Q_matrix_type;
typedef RMatrixExprT R_matrix_type;
typedef SMatrixExprT S_matrix_type;
typedef EMatrixExprT E_matrix_type;
typedef XMatrixT X_matrix_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<A_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<B_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<Q_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<R_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<S_matrix_type>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<E_matrix_type>::value_type,
typename ublas::matrix_traits<X_matrix_type>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<A_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<B_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<Q_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<R_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<S_matrix_type>::size_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<E_matrix_type>::size_type,
typename ublas::matrix_traits<X_matrix_type>::size_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type size_type;
typedef typename ublas::type_traits<value_type>::real_type real_type;
typedef ublas::matrix<value_type> work_matrix_type; //FIXME: adjust orientation?
size_type n = ublasx::num_rows(B);
size_type m = ublasx::num_columns(B);
const double eps = ::std::numeric_limits<double>::epsilon();
// precondition: n > 0 && m > 0
DCS_ASSERT(
n > 0 && m > 0,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Empty matrix.")
);
// precondition: A is square && num_rows[A] == num_rows[B]
DCS_ASSERT(
ublasx::num_rows(A) == n && ublasx::num_columns(A) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A must be a square matrix and must have the same number of rows of B.")
);
// precondition: Q is square && size[Q] == size[A]
DCS_ASSERT(
ublasx::num_rows(Q) == n && ublasx::num_columns(Q) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: Q is symmetric
DCS_ASSERT(
ublas::norm_1(Q-ublas::trans(Q)) <= 100*eps*ublas::norm_1(Q),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] Q must be symmetric.")
);
// precondition: R is square && num_rows[R] == num_columns[B]
DCS_ASSERT(
ublasx::num_rows(R) == m && ublasx::num_columns(R) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be a square matrix and must have the same number of columns of B.")
);
// precondition: R is symmetric
DCS_ASSERT(
ublas::norm_1(R-ublas::trans(R)) <= 100*eps*ublas::norm_1(R),
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be symmetric.")
);
// precondition: size[S] == size[B]
DCS_ASSERT(
ublasx::num_rows(S) == n && ublasx::num_columns(S) == m,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] B and S must be the same size.")
);
// precondition: E is square && size[E] == size[A]
DCS_ASSERT(
ublasx::num_rows(E) == n && ublasx::num_columns(E) == n,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] A and Q must be the same size.")
);
// precondition: E != I_n && E is not singular
DCS_ASSERT(
/*E != ublas::identity_matrix(n) && */ublasx::rcond(E) >= eps,
throw ::std::invalid_argument("[dcsxx::control::operation::dare] R must be nonsingular.")
);
// Create temporary copies of Q, R, S matrices and make sure that Q and R
// are symmetric matrices.
work_matrix_type work_Q((Q + ublas::trans(Q))/real_type(2));
work_matrix_type work_R((R + ublas::trans(R))/real_type(2));
work_matrix_type work_S(S);
// Scale Q,R,S so that norm_1(Q)+norm_1(R)+norm_1(S) = 1
real_type scale_factor(0);
scale_factor += ublas::norm_1(work_Q)+ublas::norm_1(work_R)+ublas::norm_1(S);
// Chek if the scaling factor is too near to zero.
if (scale_factor <= eps)
{
scale_factor = real_type(1);
}
work_Q /= scale_factor;
work_R /= scale_factor;
work_S /= scale_factor;
// Set up extended Symplectic pencil (H,J) of the form:
// |A 0 B| |E 0 0|
// H - z J = |Q -E' S| - z |0 -A' 0|
// |S' 0 R| |0 -B' 0|
// of dimension (2N+M)x(2N+M), where N and M are the number of rows and of
// of columns of matrix B, respectively.
work_matrix_type H; // (2*n+m,2*n+m)
work_matrix_type J; // (2*n+m,2*n+m)
H = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
ublasx::cat_rows(
A,
ublas::zero_matrix<value_type>(n,n)
),
B
),
ublasx::cat_rows(
ublasx::cat_rows(
work_Q,
-ublas::trans(E)
),
work_S
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::trans(work_S),
ublas::zero_matrix<value_type>(m, n)
),
work_R
)
);
J = ublasx::cat_columns(
ublasx::cat_columns(
ublasx::cat_rows(
E,
ublas::zero_matrix<value_type>(n, n+m)
),
ublasx::cat_rows(
ublas::zero_matrix<value_type>(n, n),
ublasx::cat_rows(
-ublas::trans(A),
ublas::zero_matrix<value_type>(n, m)
)
)
),
ublasx::cat_rows(
ublasx::cat_rows(
ublas::zero_matrix<value_type>(m, n),
-ublas::trans(B)
),
ublas::zero_matrix<value_type>(m)
)
);
// Undo scaling of the data matrices.
//work_Q *= scale_factor;
//work_R *= scale_factor;
//work_S *= scale_factor;
// Temporary copies of Q, R, and S not needed any more.
work_Q.resize(0, 0, false);
work_R.resize(0, 0, false);
work_S.resize(0, 0, false);
// Compress the pencils using QL factorization.
// The compressed form is (see [1]):
// \lambda H - J
// where H and J are 2n-by-2n matrices.
// [1] <NAME>.
// A Generalized Eigenvalue Approach for Solving Riccati Equations.
// SIAM J. Sci. Stat. Comp., 2, pp. 121-135, 1981.
//
size_type n2 = n*2;
size_type n2pm = n2 + m;
ublasx::ql_decomposition<value_type> ql(ublas::subrange(H, 0, n2pm, n2, n2pm));
work_matrix_type tmp_HJ;
tmp_HJ = ublas::subrange(H, 0, n2pm, 0, n2);
H = ublas::subrange(ql.tlprod(tmp_HJ), 0, n2, 0, n2);
tmp_HJ = ublas::subrange(J, 0, n2pm, 0, n2);
J = ublas::subrange(ql.tlprod(tmp_HJ), 0, n2, 0, n2);
// Check the singularity of the L factor in the QL factorization:
// if singular, then the extended matrix pencil is also singular.
if (ublasx::rcond(ql.L()) <= eps)
{
DCS_DEBUG_TRACE("The extended matrix pencil is singular");
throw ::std::runtime_error("[dcs::control::dare] Cannot compute DARE solution: the extended matrix pencil is singular.");
}
// The natural tendency of the QZ algorithm to get the largest
// eigenvalues in the leading part of the matrix pair is
// exploited, by computing the unstable eigenvalues (i.e., the ones
// outside the unit circle) of the permuted matrix pair (J,H).
// This is equivalent to take the eigenvalues inside the unit circle of
// the matrix pair (H,J).
//ublasx::qz_decomposition<work_matrix_type,work_matrix_type> qz;
//qz.decompose(H, J, ublasx::udi_qz_eigenvalues);
work_matrix_type Z;
//ublasx::qz_decompose_inplace(J, H, qzQ, qzZ, ublasx::udo_qz_eigenvalues);//FIXME:test me
//TODO: clear qzQ since it seems it is not used
ublasx::qz_decomposition<value_type> qz;
qz.decompose(J, H);
qz.reorder(ublasx::udo_qz_eigenvalues);
Z = qz.Z();
// Select submatrices X1 and X2 out of the matrix Z which define the
// solution X = X2 * inv(X1).
// Since X = X' we may obtain X as the solution of the system of
// linear equations X1' X = X2', where
// X1 = Z(1:n, 1:n),
// X2 = Z(n+1:2n, 1:n).
work_matrix_type X1 = ublas::subrange(Z, 0, n, 0, n);
work_matrix_type X2 = ublas::subrange(Z, n, n2, 0, n);
// Z is not needed any more
Z.resize(0, 0, false);
//// Check if X1 is singular
//X1_norm = ublas::norm_1(X1);
// Solve the system X1' X = X2'
work_matrix_type X;
size_type sing;
sing = ublasx::lu_solve(ublas::trans(X1), ublas::trans(X2), X);
// ublas::permutation_matrix<size_type> P(n);
// X1 = ublas::trans(X1);
// ublasx::lu_decompose_inplace(X1, P);
// if (ublasx::rcond(X1) < eps)
// {
// // Nearly singular matrix
// //FIXME: what to do?
// }
// X = ublasx::lu_apply(X1, P, ublas::trans(X2));
if (sing)
{
// Nearly singular matrix
DCS_DEBUG_TRACE("Cannot compute DARE solution: nearly singular matrix.");
throw ::std::runtime_error("[dcs::control::dare] Cannot compute DARE solution: nearly singular matrix.");
}
// Make sure the solution X is symmetrix
X = scale_factor * (X + ublas::trans(X))/real_type(2);
#endif
typedef typename ublas::promote_traits<
typename ublas::matrix_traits<AMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<BMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<QMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<RMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<SMatrixExprT>::value_type,
typename ublas::promote_traits<
typename ublas::matrix_traits<EMatrixExprT>::value_type,
typename ublas::matrix_traits<XMatrixT>::value_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type
>::promote_type value_type;
dare_solver<value_type> solver;
solver.solve(A, B, Q, R, S, E);
X = solver.solution();
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_SOLVER_DARE_SLICOT5_HPP
<file_sep>/**
* \file dcs/control/design/fmpc.hpp
*
* \brief Fast Model Predictive Control using Online Optimization.
*
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2009 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_FMPC_HPP
#define DCS_CONTROL_FMPC_HPP
#include <algorithm>
#include <boost/static_assert.hpp>
#include <boost/numeric/bindings/blas.hpp>
#include <boost/numeric/bindings/lapack.hpp>
#include <boost/numeric/bindings/ublas.hpp>
#include <boost/numeric/bindings/views.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublasx/operation/cat.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <boost/numeric/ublasx/traits/layout_type.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#include <cmath>
#include <complex>
#include <dcs/assert.hpp>
#include <dcs/debug.hpp>
//#include <dcs/control/detail/blas.hpp>
//#include <dcs/control/detail/lapack.hpp>
#include <dcs/macro.hpp>
#include <stdexcept>
namespace dcs { namespace control {
namespace detail { namespace /*<unnamed>*/ {
const int ione = 1;
const int itwo = 2;
const int ithree = 3;
const int iseven = 7;
const double fone = 1;
const double ftwo = 2;
const double fzero = 0;
const double fmone = -1;
const int quiet = 0;
///@{ Prototypes
template <typename RealT, typename SizeT>
void dnudz(RealT* A, RealT* B, RealT* At, RealT* Bt, RealT* eyen, RealT* eyem, RealT* Q, RealT* R, RealT* Qf, RealT* hp, RealT* rd, RealT* rp, SizeT T, SizeT n, SizeT m, SizeT nz, RealT kappa, RealT* dnu, RealT* dz);
template <typename RealT, typename SizeT>
void rdrp(RealT* A, RealT* B, RealT* z, RealT* nu, RealT* gf, RealT* gp, RealT* b, SizeT T, SizeT n, SizeT m, SizeT nz, RealT kappa, RealT* rd, RealT* rp, RealT* Ctnu);
template <typename RealT, typename SizeT>
void gfgphp(RealT* Q, RealT* R, RealT* Qf, RealT* zmax, RealT* zmin, RealT* z, SizeT T, SizeT n, SizeT m, SizeT nz, RealT* gf, RealT* gp, RealT* hp);
template <typename RealT, typename SizeT>
void resdresp(RealT* rd, RealT* rp, SizeT T, SizeT n, SizeT nz, RealT* resd, RealT* resp, RealT* res);
template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename QfMatrixT,
typename ZMinVectorT,
typename ZMaxVectorT,
typename XVectorT,
typename Z0VectorT,
typename SizeT,
typename RealT
>
void fmpc_solve_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
::boost::numeric::ublas::vector_expression<ZMinVectorT> const& zmin,
::boost::numeric::ublas::vector_expression<ZMaxVectorT> const& zmax,
::boost::numeric::ublas::vector_expression<XVectorT> const& x,
::boost::numeric::ublas::vector_container<Z0VectorT>& z0,
SizeT T,
SizeT niters,
RealT kappa);
template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename XMinVectorT,
typename XMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename QfMatrixT,
typename SizeT,
typename RealT,
typename X0MatrixT,
typename U0MatrixT,
typename X0VectorT,
typename XMatrixT,
typename UMatrixT,
typename XVectorT,
typename KMatrixT
>
void fmpc_step(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::vector_expression<XMinVectorT> const& xmin,
::boost::numeric::ublas::vector_expression<XMaxVectorT> const& xmax,
::boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
::boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
SizeT T,
SizeT niters,
RealT kappa,
::boost::numeric::ublas::matrix_expression<X0MatrixT> const& X0,
::boost::numeric::ublas::matrix_expression<U0MatrixT> const& U0,
::boost::numeric::ublas::vector_expression<X0VectorT> const& x0,
bool want_X,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
bool want_U,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
bool want_x,
::boost::numeric::ublas::vector_container<XVectorT>& x,
bool want_K,
::boost::numeric::ublas::matrix_container<KMatrixT>& K);
///@} Prototypes
#if 0
void printmat(double *A, int m, int n)
{
double *dptr;
int j, i;
dptr = A;
::std::cerr.precision(4);
for (j = 0; j < m; j++)
{
for (i = 0; i < n; i++)
{
/*printf("%5.4f\t", *(dptr+m*i+j));*/
::std::cerr << ::std::fixed << *(dptr+m*i+j) << "\t";
}
/*printf("\n");*/
::std::cerr << ::std::endl;
}
return;
}
#endif // 0
/* computes the search directions dz and dnu */
template <typename RealT, typename SizeT>
void dnudz(RealT* A, RealT* B, RealT* At, RealT* Bt, RealT* eyen, RealT* eyem, RealT* Q, RealT* R, RealT* Qf, RealT* hp, RealT* rd, RealT* rp, SizeT T, SizeT n, SizeT m, SizeT nz, RealT kappa, RealT* dnu, RealT* dz)
{
namespace ublas = ::boost::numeric::ublas;
namespace bindings = ::boost::numeric::bindings;
typedef RealT real_type;
typedef SizeT size_type;
#if 0
typedef ublas::array_adaptor<real_type> array_type;
typedef ublas::matrix<real_type,ublas::column_major,array_type> matrix_type;
typedef ublas::vector<real_type,array_type> vector_type;
#endif // 0
size_type info;
real_type* dptr(0);
real_type* dptr1(0);
real_type* dptr2(0);
real_type* dptr3(0);
size_type nT = n*T;
size_type nn = n*n;
size_type mm = m*m;
size_type nnT = nn*T;
size_type nnTm1 = nn*(T-1);
size_type mmT = mm*T;
size_type nm = n*m;
size_type nmT = nm*T;
/* allocate memory */
real_type* PhiQ = new real_type[nnT];
real_type* PhiR = new real_type[mmT];
real_type* PhiinvQAt = new real_type[nnT];
real_type* PhiinvRBt = new real_type[nmT];
real_type* PhiinvQeye = new real_type[nnT];
real_type* PhiinvReye = new real_type[mmT];
real_type* CPhiinvrd = new real_type[nT];
real_type* Yd = new real_type[nnT];
real_type* Yud = new real_type[nnTm1];
real_type* Ld = new real_type[nnT];
real_type* Lld = new real_type[nnTm1];
real_type* gam = new real_type[nT];
real_type* v = new real_type[nT];
real_type* be = new real_type[nT];
real_type* temp = new real_type[n];
real_type* tempmatn = new real_type[nn];
real_type* tempmatm = new real_type[mm];
real_type* Ctdnu = new real_type[nz];
real_type* rdmCtdnu = new real_type[nz];
// auxiliary matrices and vectors
#if 0
matrix_type A1;
matrix_type A2;
matrix_type A3;
vector_type v1;
vector_type v2;
#endif // 0
/* form PhiQ and PhiR */
for (size_type i = 0; i < T-1; ++i)
{
dptr = PhiQ+nn*i; dptr1 = Q;
for (size_type j = 0; j < nn; ++j)
{
*dptr = 2*(*dptr1);
++dptr; ++dptr1;
}
dptr = PhiQ+nn*i; dptr1 = hp+m*(i+1)+n*i;
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr+kappa*(*dptr1);
dptr = dptr+n+1; ++dptr1;
}
dptr = PhiR+mm*i; dptr1 = R;
for (size_type j = 0; j < mm; ++j)
{
*dptr = 2*(*dptr1);
++dptr; ++dptr1;
}
dptr = PhiR+m*m*i; dptr1 = hp+i*(n+m);
for (size_type j = 0; j < m; ++j)
{
*dptr = *dptr+kappa*(*dptr1);
dptr = dptr+m+1; ++dptr1;
}
}
dptr = PhiR+mm*(T-1); dptr1 = R;
for (size_type j = 0; j < mm; ++j)
{
*dptr = 2*(*dptr1);
++dptr; ++dptr1;
}
dptr = PhiR+mm*(T-1); dptr1 = hp+(T-1)*(n+m);
for (size_type j = 0; j < m; ++j)
{
*dptr = *dptr+kappa*(*dptr1);
dptr = dptr+m+1; ++dptr1;
}
dptr = PhiQ+nn*(T-1); dptr1 = Qf;
for (size_type j = 0; j < nn; ++j)
{
*dptr = 2*(*dptr1);
++dptr; ++dptr1;
}
dptr = PhiQ+nn*(T-1); dptr1 = hp+m*T+n*(T-1);
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr+kappa*(*dptr1);
dptr = dptr+n+1; ++dptr1;
}
/* compute PhiinvQAt, PhiinvRBt, PhiinvQeye, PhiinvReye */
for (size_type i = 0; i < T; ++i)
{
dptr = PhiinvQAt+nn*i; dptr1 = At;
for (size_type j = 0; j < nn; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-nn; dptr1 = PhiQ+nn*i;
// F77_CALL(dposv)("l",&n,&n,dptr1,&n,dptr,&n,&info);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr1));
A2 = matrix_type(n, n, array_type(nn, dptr));
bindings::lapack::posv(bindings::lower(A1), A2);
::std::copy(A1.data().begin(), A1.data().end(), dptr1);
::std::copy(A2.data().begin(), A2.data().end(), dptr);
#else
LAPACK_DPOSV("l",&n,&n,dptr1,&n,dptr,&n, &info);
#endif // 0
dptr = PhiinvQeye+nn*i; dptr1 = eyen;
for (size_type j = 0; j < nn; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-nn; dptr1 = PhiQ+nn*i;
// F77_CALL(dtrtrs)("l","n","n",&n,&n,dptr1,&n,dptr,&n,&info);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr1));
A2 = matrix_type(n, n, array_type(nn, dptr));
bindings::lapack::trtrs(bindings::lower(A1), A2);
::std::copy(A2.data().begin(), A2.data().end(), dptr);
#else
LAPACK_DTRTRS("l","n","n",&n,&n,dptr1,&n,dptr,&n,&info);
#endif // 0
// F77_CALL(dtrtrs)("l","t","n",&n,&n,dptr1,&n,dptr,&n,&info);
#if 0
bindings::lapack::trtrs(bindings::trans(bindings::lower(A1)), A2);
::std::copy(A2.data().begin(), A2.data().end(), dptr);
#else
LAPACK_DTRTRS("l","t","n",&n,&n,dptr1,&n,dptr,&n,&info);
#endif // 0
}
for (size_type i = 0; i < T; ++i)
{
dptr = PhiinvRBt+nm*i; dptr1 = Bt;
for (size_type j = 0; j < nm; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-nm; dptr1 = PhiR+mm*i;
// F77_CALL(dposv)("l",&m,&n,dptr1,&m,dptr,&m,&info);
#if 0
A1 = matrix_type(m, m, array_type(mm, dptr1));
A2 = matrix_type(m, n, array_type(nm, dptr));
bindings::lapack::posv(bindings::lower(A1), A2);
::std::copy(A1.data().begin(), A1.data().end(), dptr1);
::std::copy(A2.data().begin(), A2.data().end(), dptr);
#else
LAPACK_DPOSV("l",&m,&n,dptr1,&m,dptr,&m,&info);
#endif // 0
dptr = PhiinvReye+mm*i; dptr1 = eyem;
for (size_type j = 0; j < mm; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-mm; dptr1 = PhiR+mm*i;
// F77_CALL(dtrtrs)("l","n","n",&m,&m,dptr1,&m,dptr,&m,&info);
#if 0
A1 = matrix_type(m, m, array_type(mm, dptr1));
A2 = matrix_type(m, m, array_type(mm, dptr));
bindings::lapack::trtrs(bindings::lower(A1), A2);
#else
LAPACK_DTRTRS("l","n","n",&m,&m,dptr1,&m,dptr,&m,&info);
#endif // 0
// F77_CALL(dtrtrs)("l","t","n",&m,&m,dptr1,&m,dptr,&m,&info);
#if 0
bindings::lapack::trtrs(bindings::trans(bindings::lower(A1)), A2);
::std::copy(A2.data().begin(), A2.data().end(), dptr);
#else
LAPACK_DTRTRS("l","t","n",&m,&m,dptr1,&m,dptr,&m,&info);
#endif // 0
}
/* form Yd and Yud */
dptr = Yud; dptr1 = PhiinvQAt;
for (size_type i = 0; i < nnTm1; ++i)
{
*dptr = -(*dptr1);
++dptr; ++dptr1;
}
dptr2 = Yd; dptr3 = PhiinvQeye;
for (size_type i = 0; i < nn; ++i)
{
*dptr2 = *dptr3;
++dptr2; ++dptr3;
}
dptr2 = dptr2-nn;
// F77_CALL(dgemm)("n","n",&n,&n,&m,&fone,B,&n,PhiinvRBt,&m,&fone,dptr2,&n);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
A2 = matrix_type(m, n, array_type(nm, PhiinvRBt));
A3 = matrix_type(n, n, array_type(nn, dptr2));
bindings::blas::gemm(fone, A1, A2, fone, A3);
::std::copy(A3.data().begin(), A3.data().end(), dptr2);
#else
BLAS_DGEMM("n","n",&n,&n,&m,&fone,B,&n,PhiinvRBt,&m,&fone,dptr2,&n);
#endif // 0
for (size_type i = 1; i < T; ++i)
{
dptr = Yd+nn*i; dptr1 = PhiinvQeye+nn*i;
for (size_type j = 0; j < nn; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr1 = PhiinvRBt+nm*i; dptr = dptr-nn;
// F77_CALL(dgemm)("n","n",&n,&n,&m,&fone,B,&n,dptr1,&m,&fone,dptr,&n);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
A2 = matrix_type(m, n, array_type(nm, dptr1));
A3 = matrix_type(n, n, array_type(nn, dptr));
bindings::blas::gemm(fone, A1, A2, fone, A3);
::std::copy(A3.data().begin(), A3.data().end(), dptr);
#else
BLAS_DGEMM("n","n",&n,&n,&m,&fone,B,&n,dptr1,&m,&fone,dptr,&n);
#endif // 0
dptr1 = PhiinvQAt+nn*(i-1);
// F77_CALL(dgemm)("n","n",&n,&n,&n,&fone,A,&n,dptr1,&n,&fone,dptr,&n);
#if 0
A1 = matrix_type(n, n, array_type(nn, A));
A2 = matrix_type(n, n, array_type(nn, dptr1));
A3 = matrix_type(n, n, array_type(nn, dptr));
bindings::blas::gemm(fone, A1, A2, fone, A3);
::std::copy(A3.data().begin(), A3.data().end(), dptr);
#else
BLAS_DGEMM("n","n",&n,&n,&n,&fone,A,&n,dptr1,&n,&fone,dptr,&n);
#endif // 0
}
/* compute Lii */
dptr = Ld; dptr1 = Yd;
for (size_type i = 0; i < nn; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-nn;
// F77_CALL(dposv)("l",&n,&ione,dptr,&n,temp,&n,&info);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr));
A2 = matrix_type(n, ione, array_type(n, temp));
bindings::lapack::posv(bindings::lower(A1), A2);
::std::copy(A1.data().begin(), A1.data().end(), dptr);
::std::copy(A2.data().begin(), A2.data().end(), temp);
#else
LAPACK_DPOSV("l",&n,&ione,dptr,&n,temp,&n,&info);
#endif // 0
for (size_type i = 1; i < T; ++i)
{
dptr = Ld+nn*(i-1); dptr1 = Yud+nn*(i-1); dptr2 = Lld+nn*(i-1);
for (size_type j = 0; j < nn; ++j)
{
*dptr2 = *dptr1;
++dptr2; ++dptr1;
}
dptr2 = dptr2-nn;
// F77_CALL(dtrtrs)("l","n","n",&n,&n,dptr,&n,dptr2,&n,&info);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr));
A2 = matrix_type(n, n, array_type(nn, dptr2));
bindings::lapack::trtrs(bindings::lower(A1), A2);
::std::copy(A2.data().begin(), A2.data().end(), dptr2);
#else
LAPACK_DTRTRS("l","n","n",&n,&n,dptr,&n,dptr2,&n,&info);
#endif // 0
dptr1 = tempmatn;
for (size_type j = 0; j < nn; ++j)
{
*dptr1 = *dptr2;
++dptr1; ++dptr2;
}
dptr1 = dptr1-nn; dptr2 = dptr2-nn;
// F77_CALL(dgemm)("t","n",&n,&n,&n,&fone,dptr1,&n,eyen,&n,&fzero,dptr2,&n);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr1));
A2 = matrix_type(n, n, array_type(nn, eyen));
A3 = matrix_type(n, n, array_type(nn, dptr2));
bindings::blas::gemm(fone, bindings::trans(A1), A2, fzero, A3);
::std::copy(A3.data().begin(), A3.data().end(), dptr2);
#else
BLAS_DGEMM("t","n",&n,&n,&n,&fone,dptr1,&n,eyen,&n,&fzero,dptr2,&n);
#endif // 0
dptr = Ld+nn*i; dptr1 = Yd+nn*i;
for (size_type j = 0; j < nn; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-nn;
// F77_CALL(dgemm)("n","t",&n,&n,&n,&fmone,dptr2,&n,dptr2,&n,&fone,dptr,&n);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr2));
A2 = matrix_type(n, n, array_type(nn, dptr2));
A3 = matrix_type(n, n, array_type(nn, dptr));
bindings::blas::gemm(fmone, A1, bindings::trans(A2), fone, A3);
::std::copy(A3.data().begin(), A3.data().end(), dptr);
#else
BLAS_DGEMM("n","t",&n,&n,&n,&fmone,dptr2,&n,dptr2,&n,&fone,dptr,&n);
#endif // 0
// F77_CALL(dposv)("l",&n,&ione,dptr,&n,temp,&n,&info);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr));
A2 = matrix_type(n, ione, array_type(n, temp));
bindings::lapack::posv(bindings::lower(A1), A2);
::std::copy(A1.data().begin(), A1.data().end(), dptr);
::std::copy(A2.data().begin(), A2.data().end(), temp);
#else
LAPACK_DPOSV("l",&n,&ione,dptr,&n,temp,&n,&info);
#endif // 0
}
/* compute CPhiinvrd */
dptr = CPhiinvrd; dptr1 = rd+m;
for (size_type i = 0; i < n; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-n;
// F77_CALL(dtrsv)("l","n","n",&n,PhiQ,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, PhiQ));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::lower(A1), v1);
#else
BLAS_DTRSV("l","n","n",&n,PhiQ,&n,dptr,&ione);
#endif // 0
// F77_CALL(dtrsv)("l","t","n",&n,PhiQ,&n,dptr,&ione);
#if 0
// A1 = matrix_type(n, n, array_type(nn, PhiQ));
// v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","t","n",&n,PhiQ,&n,dptr,&ione);
#endif // 0
dptr2 = temp; dptr1 = rd;
for (size_type i = 0; i < m; ++i)
{
*dptr2 = *dptr1;
++dptr2; ++dptr1;
}
dptr2 = dptr2-m;
// F77_CALL(dtrsv)("l","n","n",&m,PhiR,&m,dptr2,&ione);
#if 0
A1 = matrix_type(m, m, array_type(mm, PhiR));
v1 = vector_type(m, array_type(m, dptr2));
bindings::blas::trsv(bindings::lower(A1), v1);
#else
BLAS_DTRSV("l","n","n",&m,PhiR,&m,dptr2,&ione);
#endif // 0
// F77_CALL(dtrsv)("l","t","n",&m,PhiR,&m,dptr2,&ione);
#if 0
// A1 = matrix_type(m, m, array_type(mm, PhiR));
// v1 = vector_type(m, array_type(m, dptr2));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr2);
#else
BLAS_DTRSV("l","t","n",&m,PhiR,&m,dptr2,&ione);
#endif // 0
// F77_CALL(dgemv)("n",&n,&m,&fmone,B,&n,temp,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(m, array_type(m, temp));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&m,&fmone,B,&n,temp,&ione,&fone,dptr,&ione);
#endif // 0
for (size_type i = 1; i < T; ++i)
{
dptr = CPhiinvrd+n*i; dptr1 = rd+m+i*(n+m);
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-n; dptr3 = PhiQ+nn*i;
// F77_CALL(dtrsv)("l","n","n",&n,dptr3,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::lower(A1), v1);
#else
BLAS_DTRSV("l","n","n",&n,dptr3,&n,dptr,&ione);
#endif // 0
// F77_CALL(dtrsv)("l","t","n",&n,dptr3,&n,dptr,&ione);
#if 0
// A1 = matrix_type(n, n, array_type(nn, dptr3));
// v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","t","n",&n,dptr3,&n,dptr,&ione);
#endif // 0
dptr2 = temp; dptr1 = rd+i*(m+n);
for (size_type j = 0; j < m; ++j)
{
*dptr2 = *dptr1;
++dptr2; ++dptr1;
}
dptr3 = PhiR+mm*i; dptr2 = dptr2-m;
// F77_CALL(dtrsv)("l","n","n",&m,dptr3,&m,dptr2,&ione);
#if 0
A1 = matrix_type(m, m, array_type(mm, dptr3));
v1 = vector_type(m, array_type(m, dptr2));
bindings::blas::trsv(bindings::lower(A1), v1);
#else
BLAS_DTRSV("l","n","n",&m,dptr3,&m,dptr2,&ione);
#endif // 0
// F77_CALL(dtrsv)("l","t","n",&m,dptr3,&m,dptr2,&ione);
#if 0
// A1 = matrix_type(m, m, array_type(mm, dptr3));
// v1 = vector_type(m, array_type(m, dptr2));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr2);
#else
BLAS_DTRSV("l","t","n",&m,dptr3,&m,dptr2,&ione);
#endif // 0
// F77_CALL(dgemv)("n",&n,&m,&fmone,B,&n,temp,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(m, array_type(m, temp));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&m,&fmone,B,&n,temp,&ione,&fone,dptr,&ione);
#endif // 0
dptr2 = temp; dptr1 = rd+(i-1)*(n+m)+m;
for (size_type j = 0; j < n; ++j)
{
*dptr2 = *dptr1;
++dptr2; ++dptr1;
}
dptr3 = PhiQ+nn*(i-1); dptr2 = dptr2-n;
// F77_CALL(dtrsv)("l","n","n",&n,dptr3,&n,dptr2,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr2));
bindings::blas::trsv(bindings::lower(A1), v1);
#else
BLAS_DTRSV("l","n","n",&n,dptr3,&n,dptr2,&ione);
#endif // 0
// F77_CALL(dtrsv)("l","t","n",&n,dptr3,&n,dptr2,&ione);
#if 0
// A1 = matrix_type(n, n, array_type(nn, dptr3));
// v1 = vector_type(n, array_type(n, dptr2));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr2);
#else
BLAS_DTRSV("l","t","n",&n,dptr3,&n,dptr2,&ione);
#endif // 0
// F77_CALL(dgemv)("n",&n,&n,&fmone,A,&n,temp,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, A));
v1 = vector_type(n, array_type(n, temp));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&fmone,A,&n,temp,&ione,&fone,dptr,&ione);
#endif // 0
}
/* form be */
dptr = be; dptr1 = rp; dptr2 = CPhiinvrd;
for (size_type i = 0; i < nT; ++i)
{
*dptr = (*dptr2)-(*dptr1);
++dptr; ++dptr1; ++dptr2;
}
/* solve for dnu */
dptr = v; dptr1 = be;
for (size_type i = 0; i < n; ++i)
{
*dptr = -(*dptr1);
++dptr; ++dptr1;
}
dptr = dptr-n;
// F77_CALL(dtrsv)("l","n","n",&n,Ld,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, Ld));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::lower(A1), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","n","n",&n,Ld,&n,dptr,&ione);
#endif // 0
for (size_type i = 1; i < T; ++i)
{
dptr = v+i*n; dptr1 = v+(i-1)*n; dptr2 = be+i*n;
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr2;
++dptr; ++dptr2;
}
dptr = dptr-n; dptr3 = Lld+nn*(i-1);
// F77_CALL(dgemv)("n",&n,&n,&fmone,dptr3,&n,dptr1,&ione,&fmone,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fmone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&fmone,dptr3,&n,dptr1,&ione,&fmone,dptr,&ione);
#endif // 0
dptr3 = Ld+nn*i;
// F77_CALL(dtrsv)("l","n","n",&n,dptr3,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::lower(A1), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","n","n",&n,dptr3,&n,dptr,&ione);
#endif // 0
}
dptr = dnu+n*(T-1); dptr1 = v+n*(T-1);
for (size_type i = 0; i < n; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-n; dptr3 = Ld+nn*(T-1);
// F77_CALL(dtrsv)("l","t","n",&n,dptr3,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","t","n",&n,dptr3,&n,dptr,&ione);
#endif // 0
for (size_type i = T-1; i > 0; --i)
{
dptr = dnu+n*(i-1); dptr1 = dnu+n*i; dptr2 = v+n*(i-1);
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr2;
++dptr; ++dptr2;
}
dptr = dptr-n; dptr3 = Lld+nn*(i-1);
// F77_CALL(dgemv)("t",&n,&n,&fmone,dptr3,&n,dptr1,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("t",&n,&n,&fmone,dptr3,&n,dptr1,&ione,&fone,dptr,&ione);
#endif // 0
dptr3 = Ld+nn*(i-1);
// F77_CALL(dtrsv)("l","t","n",&n,dptr3,&n,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr3));
v1 = vector_type(n, array_type(n, dptr));
bindings::blas::trsv(bindings::trans(bindings::lower(A1)), v1);
::std::copy(v1.data().begin(), v1.data().end(), dptr);
#else
BLAS_DTRSV("l","t","n",&n,dptr3,&n,dptr,&ione);
#endif // 0
}
/* form Ctdnu */
for (size_type i = 0; i < T-1; ++i)
{
dptr = Ctdnu+i*(n+m); dptr1 = dnu+i*n;
// F77_CALL(dgemv)("n",&m,&n,&fmone,Bt,&m,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(m, n, array_type(nm, Bt));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(fmone, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&m,&n,&fmone,Bt,&m,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = Ctdnu+i*(n+m)+m; dptr2 = dnu+(i+1)*n;
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = dptr-n;
// F77_CALL(dgemv)("n",&n,&n,&fmone,At,&n,dptr2,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, At));
v1 = vector_type(n, array_type(n, dptr2));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&fmone,At,&n,dptr2,&ione,&fone,dptr,&ione);
#endif // 0
}
dptr = Ctdnu+(T-1)*(n+m); dptr1 = dnu+(T-1)*n;
// F77_CALL(dgemv)("n",&m,&n,&fmone,Bt,&m,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(m, n, array_type(nm, Bt));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(fmone, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&m,&n,&fmone,Bt,&m,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = dptr+m;
for (size_type i = 0; i < n; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = rdmCtdnu; dptr1 = Ctdnu; dptr2 = rd;
for (size_type i = 0; i < nz; ++i)
{
*dptr = -(*dptr1)-(*dptr2);
++dptr; ++dptr1; ++dptr2;
}
/* solve for dz */
for (size_type i = 0; i < T; ++i)
{
dptr = dz+(i+1)*m+i*n; dptr1 = rdmCtdnu+(i+1)*m+i*n;
dptr2 = PhiinvQeye+nn*i;
// F77_CALL(dgemv)("n",&n,&n,&fone,dptr2,&n,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, dptr2));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fone, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&fone,dptr2,&n,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
}
for (size_type i = 0; i < T; ++i)
{
dptr = dz+i*(m+n); dptr1 = rdmCtdnu+i*(m+n);
dptr2 = PhiinvReye+mm*i;
// F77_CALL(dgemv)("n",&m,&m,&fone,dptr2,&m,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(m, m, array_type(mm, dptr2));
v1 = vector_type(m, array_type(m, dptr1));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(fone, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&m,&m,&fone,dptr2,&m,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
}
delete[] PhiQ;
delete[] PhiR;
delete[] PhiinvQAt;
delete[] PhiinvRBt;
delete[] PhiinvQeye;
delete[] PhiinvReye;
delete[] CPhiinvrd;
delete[] Yd;
delete[] Yud;
delete[] Ld;
delete[] Lld;
delete[] gam;
delete[] v;
delete[] be;
delete[] temp;
delete[] tempmatn;
delete[] tempmatm;
delete[] Ctdnu;
delete[] rdmCtdnu;
}
/* computes rd and rp */
template <typename RealT, typename SizeT>
void rdrp(RealT* A, RealT* B, RealT* z, RealT* nu, RealT* gf, RealT* gp, RealT* b, SizeT T, SizeT n, SizeT m, SizeT nz, RealT kappa, RealT* rd, RealT* rp, RealT* Ctnu)
{
namespace ublas = ::boost::numeric::ublas;
namespace bindings = ::boost::numeric::bindings;
typedef RealT real_type;
typedef SizeT size_type;
#if 0
typedef ublas::array_adaptor<real_type> array_type;
typedef ublas::matrix<real_type,ublas::column_major,array_type> matrix_type;
typedef ublas::vector<real_type,array_type> vector_type;
#endif // 0
real_type* dptr(0);
real_type* dptr1(0);
real_type* dptr2(0);
size_type nT = n*T;
#if 0
size_type nn = n*n;
size_type nm = n*m;
// auxiliary matrices and vectors
matrix_type A1;
vector_type v1;
vector_type v2;
#endif // 0
real_type* Cz = new real_type[nT];
/* compute Cz */
dptr = Cz; dptr1 = z+m;
for (size_type i = 0; i < n; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
// F77_CALL(dgemv)("n",&n,&m,&fmone,B,&n,z,&ione,&fone,Cz,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(m, array_type(m, z));
v2 = vector_type(n, array_type(n, Cz));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), Cz);
#else
BLAS_DGEMV("n",&n,&m,&fmone,B,&n,z,&ione,&fone,Cz,&ione);
#endif // 0
for (size_type i = 2; i <= T; ++i)
{
dptr = Cz+(i-1)*n; dptr1 = z+m+(i-2)*(n+m);
dptr2 = z+m+(i-1)*(m+n);
for (size_type j = 0; j < n; ++j)
{
*dptr = *dptr2;
++dptr; ++dptr2;
}
dptr = dptr-n;
// F77_CALL(dgemv)("n",&n,&n,&fmone,A,&n,dptr1,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, A));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&fmone,A,&n,dptr1,&ione,&fone,dptr,&ione);
#endif // 0
dptr1 = dptr1+n;
// F77_CALL(dgemv)("n",&n,&m,&fmone,B,&n,dptr1,&ione,&fone,dptr,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(m, array_type(m, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(fmone, A1, v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&m,&fmone,B,&n,dptr1,&ione,&fone,dptr,&ione);
#endif // 0
}
/*
dptr = Cz+(T-1)*n; dptr1 = z+m+(T-2)*(n+m);
F77_CALL(dgemv)("n",&n,&n,&fmone,A,&n,dptr1,&ione,&fzero,dptr,&ione);
dptr1 = dptr1+n;
F77_CALL(dgemv)("n",&n,&m,&fmone,B,&n,dptr1,&ione,&fone,dptr,&ione);
dptr1 = z+nz-n;
for (i = 0; i < n; i++)
{
*dptr = *dptr+*dptr1;
dptr++; dptr1++;
}
*/
/* compute Ctnu */
dptr = Ctnu; dptr1 = Ctnu+m; dptr2 = nu;
for (size_type i = 1; i <= T-1; ++i)
{
// F77_CALL(dgemv)("t",&n,&m,&fmone,B,&n,dptr2,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(n, array_type(n, dptr2));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(fmone, bindings::trans(A1), v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("t",&n,&m,&fmone,B,&n,dptr2,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = dptr+n+m;
for (size_type j = 0; j < n; ++j)
{
*dptr1 = *dptr2;
++dptr1; ++dptr2;
}
dptr1 = Ctnu+m+(i-1)*(n+m);
// F77_CALL(dgemv)("t",&n,&n,&fmone,A,&n,dptr2,&ione,&fone,dptr1,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, A));
v1 = vector_type(n, array_type(n, dptr2));
v2 = vector_type(n, array_type(n, dptr1));
bindings::blas::gemv(fmone, bindings::trans(A1), v1, fone, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr1);
#else
BLAS_DGEMV("t",&n,&n,&fmone,A,&n,dptr2,&ione,&fone,dptr1,&ione);
#endif // 0
dptr1 = dptr1+n+m;
}
// F77_CALL(dgemv)("t",&n,&m,&fmone,B,&n,dptr2,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(n, m, array_type(nm, B));
v1 = vector_type(n, array_type(n, dptr2));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(fmone, bindings::trans(A1), v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("t",&n,&m,&fmone,B,&n,dptr2,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = Ctnu+nz-n; dptr1 = nu+(T-1)*n;
for (size_type i = 0; i < n; ++i)
{
*dptr = *dptr1;
++dptr; ++dptr1;
}
dptr = rp; dptr1 = Cz; dptr2 = b;
for (size_type i = 0; i < nT; ++i)
{
*dptr = *dptr1-*dptr2;
++dptr; ++dptr1; ++dptr2;
}
dptr = rd; dptr1 = Ctnu; dptr2 = gf;
for (size_type i = 0; i < nz; ++i)
{
*dptr = *dptr1+*dptr2;
++dptr; ++dptr1; ++dptr2;
}
// F77_CALL(daxpy)(&nz,&kappa,gp,&ione,rd,&ione);
#if 0
v1 = vector_type(nz, array_type(nz, gp));
v2 = vector_type(nz, array_type(nz, rd));
bindings::blas::axpy(kappa, v1, v2);
::std::copy(v2.data().begin(), v2.data().end(), rd);
#else
BLAS_DAXPY(&nz,&kappa,gp,&ione,rd,&ione);
#endif // 0
delete[] Cz;
}
/* computes gf, gp and hp */
template <typename RealT, typename SizeT>
void gfgphp(RealT* Q, RealT* R, RealT* Qf, RealT* zmax, RealT* zmin, RealT* z, SizeT T, SizeT n, SizeT m, SizeT nz, RealT* gf, RealT* gp, RealT* hp)
{
namespace ublas = ::boost::numeric::ublas;
namespace bindings = ::boost::numeric::bindings;
typedef RealT real_type;
typedef SizeT size_type;
#if 0
typedef ublas::array_adaptor<real_type> array_type;
typedef ublas::matrix<real_type,ublas::column_major,array_type> matrix_type;
typedef ublas::vector<real_type,array_type> vector_type;
#endif // 0
#if 0
size_type nn = n*n;
size_type mm = m*m;
// auxiliary matrices and vectors
matrix_type A1;
vector_type v1;
vector_type v2;
#endif // 0
real_type* gp1 = new real_type[nz];
real_type* gp2 = new real_type[nz];
real_type* dptr(0);
real_type* dptr1(0);
real_type* dptr2(0);
dptr = gp1; dptr1 = zmax; dptr2 = z;
for (size_type i = 0; i < nz; ++i)
{
*dptr = 1.0/(*dptr1-*dptr2);
++dptr; ++dptr1; ++dptr2;
}
dptr = gp2; dptr1 = zmin; dptr2 = z;
for (size_type i = 0; i < nz; ++i)
{
*dptr = 1.0/(*dptr2-*dptr1);
++dptr; ++dptr1; ++dptr2;
}
dptr = hp; dptr1 = gp1; dptr2 = gp2;
for (size_type i = 0; i < nz; ++i)
{
*dptr = (*dptr1)*(*dptr1) + (*dptr2)*(*dptr2);
++dptr; ++dptr1; ++dptr2;
}
dptr = gp; dptr1 = gp1; dptr2 = gp2;
for (size_type i = 0; i < nz; ++i)
{
*dptr = *dptr1-*dptr2;
++dptr; ++dptr1; ++dptr2;
}
dptr = gf; dptr1 = z;
size_type Tm1 = T-1;
for (size_type i = 0; i < Tm1; ++i)
{
// F77_CALL(dgemv)("n",&m,&m,&ftwo,R,&m,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(m, m, array_type(mm, R));
v1 = vector_type(m, array_type(n, dptr1));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(ftwo, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&m,&m,&ftwo,R,&m,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = dptr+m; dptr1 = dptr1+m;
// F77_CALL(dgemv)("n",&n,&n,&ftwo,Q,&n,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, Q));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(ftwo, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&ftwo,Q,&n,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = dptr+n; dptr1 = dptr1+n;
}
// F77_CALL(dgemv)("n",&m,&m,&ftwo,R,&m,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(m, m, array_type(mm, R));
v1 = vector_type(m, array_type(m, dptr1));
v2 = vector_type(m, array_type(m, dptr));
bindings::blas::gemv(ftwo, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&m,&m,&ftwo,R,&m,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
dptr = dptr+m; dptr1 = dptr1+m;
// F77_CALL(dgemv)("n",&n,&n,&ftwo,Qf,&n,dptr1,&ione,&fzero,dptr,&ione);
#if 0
A1 = matrix_type(n, n, array_type(nn, Qf));
v1 = vector_type(n, array_type(n, dptr1));
v2 = vector_type(n, array_type(n, dptr));
bindings::blas::gemv(ftwo, A1, v1, fzero, v2);
::std::copy(v2.data().begin(), v2.data().end(), dptr);
#else
BLAS_DGEMV("n",&n,&n,&ftwo,Qf,&n,dptr1,&ione,&fzero,dptr,&ione);
#endif // 0
delete[] gp1;
delete[] gp2;
}
/* computes resd, resp, and res */
template <typename RealT, typename SizeT>
void resdresp(RealT* rd, RealT* rp, SizeT T, SizeT n, SizeT nz, RealT* resd, RealT* resp, RealT* res)
{
namespace ublas = ::boost::numeric::ublas;
namespace bindings = ::boost::numeric::bindings;
typedef RealT real_type;
typedef SizeT size_type;
#if 0
typedef ublas::array_adaptor<real_type> array_type;
typedef ublas::vector<real_type,array_type> vector_type;
#endif // 0
size_type nnu = T*n;
#if 0
// auxiliary vector
vector_type v;
#endif // 0
// *resp = F77_CALL(dnrm2)(&nnu,rp,&ione);
#if 0
v = vector_type(nnu, array_type(nnu, rp));
*resp = bindings::blas::nrm2(v);
#else
*resp = BLAS_DNRM2(&nnu,rp,&ione);
#endif // 0
// *resd = F77_CALL(dnrm2)(&nz,rd,&ione);
#if 0
v = vector_type(nz, array_type(nz, rd));
*resd = bindings::blas::nrm2(v);
#else
*resd = BLAS_DNRM2(&nz,rd,&ione);
#endif // 0
*res = ::std::sqrt((*resp)*(*resp)+(*resd)*(*resd));
}
template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename QfMatrixT,
typename ZMinVectorT,
typename ZMaxVectorT,
typename XVectorT,
typename Z0VectorT,
typename SizeT,
typename RealT
>
void fmpc_solve_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
::boost::numeric::ublas::vector_expression<ZMinVectorT> const& zmin,
::boost::numeric::ublas::vector_expression<ZMaxVectorT> const& zmax,
::boost::numeric::ublas::vector_expression<XVectorT> const& x,
::boost::numeric::ublas::vector_container<Z0VectorT>& z0,
SizeT T,
SizeT niters,
RealT kappa)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
typedef AMatrixT A_matrix_type;
typedef BMatrixT B_matrix_type;
typedef QMatrixT Q_matrix_type;
typedef RMatrixT R_matrix_type;
typedef QfMatrixT Qf_matrix_type;
typedef ZMinVectorT zmin_vector_type;
typedef ZMaxVectorT zmax_vector_type;
typedef XVectorT x_vector_type;
typedef Z0VectorT z0_vector_type;
typedef SizeT size_type;
typedef RealT real_type;
//TODO: type promotion among all matrices for the real_type
typedef ublas::vector<real_type> work_vector_type;
typedef ublas::matrix<real_type, ublas::column_major> work_matrix_type;
typedef typename work_matrix_type::array_type matrix_array_type;
typedef typename work_vector_type::array_type vector_array_type;
size_type n(ublasx::num_columns(A));
size_type m(ublasx::num_columns(B));
size_type nz(ublasx::size(z0));
// size_type maxiter(niters);
real_type alpha(0.01);
real_type beta(0.9);
real_type tol(0.1);
size_type Tn(T*n);
work_vector_type nu(n*T, 0);
work_vector_type b(Tn, 0);
ublas::subrange(b, 0, n) = ublas::prod(A, x);
work_vector_type z(z0); // (nz x 1)
work_matrix_type At(ublas::trans(A));
work_matrix_type Bt(ublas::trans(B));
work_matrix_type eyen(ublas::identity_matrix<real_type>(n, n));
work_matrix_type eyem(ublas::identity_matrix<real_type>(m, m));
DCS_DEBUG_TRACE(std::endl << "iteration \t step \t\t rd \t\t\t rp");
for (size_type k = 0; k < niters; ++k)
{
work_vector_type gf(nz);
work_vector_type gp(nz);
work_vector_type hp(nz);
work_vector_type rd(nz);
work_vector_type rp(Tn);
work_vector_type Ctnu(nz);
real_type resd;
real_type resp;
real_type res;
gfgphp(const_cast<matrix_array_type&>(Q().data()).begin(),
const_cast<matrix_array_type&>(R().data()).begin(),
const_cast<matrix_array_type&>(Qf().data()).begin(),
const_cast<vector_array_type&>(zmax().data()).begin(),
const_cast<vector_array_type&>(zmin().data()).begin(),
z.data().begin(),
T,
n,
m,
nz,
gf.data().begin(),
gp.data().begin(),
hp.data().begin());
rdrp(const_cast<matrix_array_type&>(A().data()).begin(),
const_cast<matrix_array_type&>(B().data()).begin(),
// const_cast<matrix_array_type&>(Q().data()).begin(),
// const_cast<matrix_array_type&>(R().data()).begin(),
// const_cast<matrix_array_type&>(Qf().data()).begin(),
z.data().begin(),
nu.data().begin(),
gf.data().begin(),
gp.data().begin(),
b.data().begin(),
T,
n,
m,
nz,
kappa,
rd.data().begin(),
rp.data().begin(),
Ctnu.data().begin());
resdresp(rd.data().begin(),
rp.data().begin(),
T,
n,
nz,
&resd,
&resp,
&res);
if (res < tol) break;
work_vector_type dz(nz);
work_vector_type dnu(Tn);
dnudz(const_cast<matrix_array_type&>(A().data()).begin(),
const_cast<matrix_array_type&>(B().data()).begin(),
At.data().begin(),
Bt.data().begin(),
eyen.data().begin(),
eyem.data().begin(),
const_cast<matrix_array_type&>(Q().data()).begin(),
const_cast<matrix_array_type&>(R().data()).begin(),
const_cast<matrix_array_type&>(Qf().data()).begin(),
hp.data().begin(),
rd.data().begin(),
rp.data().begin(),
T,
n,
m,
nz,
kappa,
dnu.data().begin(),
dz.data().begin());
real_type s(1);
/* feasibility search */
while (1)
{
bool cont(false);
for (size_type i = 0; i < nz && !cont; ++i)
{
if (z(i)+s*dz(i) >= zmax()(i)
||
z(i)+s*dz(i) <= zmin()(i)
)
{
cont = true;
}
}
if (cont)
{
s *= beta;
continue;
}
else
{
break;
}
}
work_vector_type newnu(nu+s*dnu);
work_vector_type newz(z+s*dz);
real_type newresd;
real_type newresp;
real_type newres;
/* insert backtracking line search */
while (1)
{
work_vector_type newgf(nz);
work_vector_type newgp(nz);
work_vector_type newhp(nz);
work_vector_type newrd(nz);
work_vector_type newrp(Tn);
work_vector_type newCtnu(nz);
gfgphp(const_cast<matrix_array_type&>(Q().data()).begin(),
const_cast<matrix_array_type&>(R().data()).begin(),
const_cast<matrix_array_type&>(Qf().data()).begin(),
const_cast<vector_array_type&>(zmax().data()).begin(),
const_cast<vector_array_type&>(zmin().data()).begin(),
newz.data().begin(),
T,
n,
m,
nz,
newgf.data().begin(),
newgp.data().begin(),
newhp.data().begin());
rdrp(const_cast<matrix_array_type&>(A().data()).begin(),
const_cast<matrix_array_type&>(B().data()).begin(),
// const_cast<matrix_array_type&>(Q().data()).begin(),
// const_cast<matrix_array_type&>(R().data()).begin(),
// const_cast<matrix_array_type&>(Qf().data()).begin(),
newz.data().begin(),
newnu.data().begin(),
newgf.data().begin(),
newgp.data().begin(),
b.data().begin(),
T,
n,
m,
nz,
kappa,
newrd.data().begin(),
newrp.data().begin(),
newCtnu.data().begin());
resdresp(newrd.data().begin(),
newrp.data().begin(),
T,
n,
nz,
&newresd,
&newresp,
&newres);
if (newres <= (1-alpha*s)*res) break;
s *= beta;
newnu = nu+s*dnu;
newz = z+s*dz;
}
nu = newnu;
z = newz;
DCS_DEBUG_TRACE(" " << k << " \t\t " << s << " \t " << newresd << " \t\t " << newresp);
}
z0() = z;
}
template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename XMinVectorT,
typename XMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename QfMatrixT,
typename SizeT,
typename RealT,
typename X0MatrixT,
typename U0MatrixT,
typename X0VectorT,
typename XMatrixT,
typename UMatrixT,
typename XVectorT,
typename KMatrixT
>
void fmpc_step(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::vector_expression<XMinVectorT> const& xmin,
::boost::numeric::ublas::vector_expression<XMaxVectorT> const& xmax,
::boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
::boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
SizeT T,
SizeT niters,
RealT kappa,
::boost::numeric::ublas::matrix_expression<X0MatrixT> const& X0,
::boost::numeric::ublas::matrix_expression<U0MatrixT> const& U0,
::boost::numeric::ublas::vector_expression<X0VectorT> const& x0,
bool want_X,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
bool want_U,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
bool want_x,
::boost::numeric::ublas::vector_container<XVectorT>& x,
bool want_K,
::boost::numeric::ublas::matrix_container<KMatrixT>& K)
{
DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(want_x);
namespace ublas = ::boost::numeric::ublas;
namespace bindings = ::boost::numeric::bindings;
#if 0
typedef SizeT size_type;
//typedef typename ublas::promote_traits<SizeT,fortran_int_t>::promote_type size_type; //TODO: type promotion
#else
typedef fortran_int_t size_type;
#endif
typedef RealT real_type; //TODO: type promotion
typedef ublas::matrix<real_type, ublas::column_major> work_matrix_type;
typedef ublas::vector<real_type> work_vector_type;
#if 0
#else
size_type TT(T);
size_type nn(niters);
#endif // 0
size_type nx(ublas::num_columns(A));
size_type nu(ublas::num_columns(B));
size_type nz(T*(nx+nu));
work_vector_type z(nz, 0);
for (size_type i = 0; i < TT; ++i)
{
size_type i1(i*(nu+nx));
size_type i2(i1+nu);
size_type i3(i2+nx);
ublas::subrange(z, i1, i2) = ublas::column(U0(), i);
ublas::subrange(z, i2, i3) = ublas::column(X0(), i);
}
work_vector_type zmin(nz, 0);
work_vector_type zmax(nz, 0);
for (size_type i = 0; i < TT; ++i)
{
size_type i1(i*(nu+nx));
size_type i2(i1+nu);
size_type i3(i2+nx);
ublas::subrange(zmin, i1, i2) = umin;
ublas::subrange(zmin, i2, i3) = xmin;
ublas::subrange(zmax, i1, i2) = umax;
ublas::subrange(zmax, i2, i3) = xmax;
}
work_vector_type zrang(zmax-zmin);
work_vector_type zminp(zmin+0.01*zrang);
work_vector_type zmaxp(zmax-0.01*zrang);
/* project z */
for (size_type i = 0; i < nz; ++i) z(i) = z(i) > zmaxp(i) ? zmaxp(i) : z(i);
for (size_type i = 0; i < nz; ++i) z(i) = z(i) < zminp(i) ? zminp(i) : z(i);
x() = x0;
#if 0
fmpc_solve_impl(A, B, Q, R, Qf, zmin, zmax, x, z, T, niters, kappa);
#else
fmpc_solve_impl(A, B, Q, R, Qf, zmin, zmax, x, z, TT, nn, kappa);
#endif // 0
if (want_X || want_U)
{
for (size_type i = 0; i < TT; ++i)
{
size_type i1(i*(nu+nx));
size_type i2(i1+nu);
size_type i3(i2+nx);
if (want_U)
{
ublas::column(U(), i) = ublas::subrange(z, i1, i2);
}
if (want_X)
{
ublas::column(X(), i) = ublas::subrange(z, i2, i3);
}
}
}
// Compute the terminal control gain K = (R+B'Q_fB)^{-1}B'Q_fA
if (want_K)
{
// int info;
work_matrix_type BtQf(ublas::prod(ublas::trans(B), Qf)); // B'Q_f
K() = ublas::prod(BtQf, A); // B'Q_fA
BtQf = ublas::prod(BtQf, B) + R; // B'Q_fB+R
// F77_CALL(dposv)("l",&nu,&nx,BtQf.data().begin(),&nu,K().data().begin(),&nu,&info); // Find K s.t. (B'Q_fB+R)K=B'Q_fA
bindings::lapack::posv(bindings::lower(BtQf), K());
}
}
}} // Namespace detail::<unnamed>
template <typename RealT, typename SizeT>
class fmpc_controller
{
public: typedef RealT real_type;
public: typedef SizeT size_type;
public: typedef ::boost::numeric::ublas::matrix<real_type, ::boost::numeric::ublas::column_major> matrix_type;
public: typedef ::boost::numeric::ublas::vector<real_type> vector_type;
public: fmpc_controller()
{
}
public: template <
typename QMatrixT,
typename RMatrixT,
typename QfMatrixT,
typename XMinVectorT,
typename XMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT>
fmpc_controller(::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
::boost::numeric::ublas::vector_expression<XMinVectorT> const& xmin,
::boost::numeric::ublas::vector_expression<XMaxVectorT> const& xmax,
::boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
::boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
size_type horiz,
real_type barrier,
size_type niters)
: Q_(Q),
R_(R),
Qf_(Qf),
xmin_(xmin),
xmax_(xmax),
umin_(umin),
umax_(umax),
T_(horiz),
kappa_(barrier),
niters_(niters),
X_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(Q), horiz)),
U_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(R), horiz)),
K_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(R), ::boost::numeric::ublasx::num_rows(Q))),
J_(0)
{
}
public: template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename XMinVectorT,
typename XMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename QfMatrixT,
typename X0MatrixT,
typename U0MatrixT>
fmpc_controller(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
::boost::numeric::ublas::vector_expression<XMinVectorT> const& xmin,
::boost::numeric::ublas::vector_expression<XMaxVectorT> const& xmax,
::boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
::boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
size_type horiz,
real_type barrier,
size_type niters,
::boost::numeric::ublas::matrix_expression<X0MatrixT> const& X0,
::boost::numeric::ublas::matrix_expression<U0MatrixT> const& U0)
: Q_(Q),
R_(R),
Qf_(Qf),
xmin_(xmin),
xmax_(xmax),
umin_(umin),
umax_(umax),
T_(horiz),
kappa_(barrier),
niters_(niters),
X_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(Q), horiz)),
U_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(R), horiz)),
K_(::boost::numeric::ublas::zero_matrix<real_type>(::boost::numeric::ublasx::num_rows(R), ::boost::numeric::ublasx::num_rows(Q))),
J_(0)
{
solve(A, B, X0, U0/*, x0*/);
}
public: template <
typename AMatrixT,
typename BMatrixT,
typename X0MatrixT,
typename U0MatrixT>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<X0MatrixT> const& X0,
::boost::numeric::ublas::matrix_expression<U0MatrixT> const& U0)
{
A_ = A;
B_ = B;
X_ = X0;
U_ = U0;
// x_ = x0;
}
public: template <
typename AMatrixT,
typename BMatrixT>
void solve(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B)
{
A_ = A;
B_ = B;
}
public: template <typename XVectorT>
vector_type control(::boost::numeric::ublas::vector_expression<XVectorT> const& x)
{
namespace ublas = ::boost::numeric::ublas;
namespace ublasx = ::boost::numeric::ublasx;
vector_type dummy_x;
detail::fmpc_step(A_, B_, Q_, R_, xmin_, xmax_, umin_, umax_, Qf_, T_, niters_, kappa_, X_, U_, x, true, X_, true, U_, false, dummy_x, true, K_);
// Get the next optimal action
vector_type u(ublas::column(U_, 0));
// compute stage cost
vector_type xtQ(ublas::prod(x, Q_));
vector_type utR(ublas::prod(u, R_));
J_ = ublas::inner_prod(xtQ, x) + ublas::inner_prod(utR, u);
// shift previous state and input trajectories
// for warm start in next step
X_ = ublasx::cat_rows(ublas::subrange(X_, 0, ublasx::size(x), 1, T_), ublas::zero_matrix<real_type>(ublasx::size(x), 1));
U_ = ublasx::cat_rows(ublas::subrange(U_, 0, ublasx::size(u), 1, T_), ublas::zero_matrix<real_type>(ublasx::size(u), 1));
return u;
}
public: matrix_type Q() const
{
return Q_;
}
public: matrix_type R() const
{
return R_;
}
public: matrix_type Qf() const
{
return Qf_;
}
public: vector_type xmin() const
{
return xmin_;
}
public: vector_type xmax() const
{
return xmax_;
}
public: vector_type umin() const
{
return umin_;
}
public: vector_type umax() const
{
return umax_;
}
public: size_type horizon() const
{
return T_;
}
public: size_type max_num_iterations() const
{
return niters_;
}
public: real_type barrier() const
{
return kappa_;
}
public: matrix_type predicted_states() const
{
return X_;
}
public: matrix_type optimal_inputs() const
{
return U_;
}
public: matrix_type gain() const
{
return K_;
}
private: real_type cost() const
{
return J_;
}
private: matrix_type Q_;
private: matrix_type R_;
private: matrix_type Qf_;
private: vector_type xmin_;
private: vector_type xmax_;
private: vector_type umin_;
private: vector_type umax_;
private: size_type T_;
private: real_type kappa_;
private: size_type niters_;
private: matrix_type A_;
private: matrix_type B_;
private: matrix_type X_;
private: matrix_type U_;
// private: matrix_type x_;
private: matrix_type K_;
private: real_type J_;
}; // fmpc_controller
template <
typename AMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename XMinVectorT,
typename XMaxVectorT,
typename UMinVectorT,
typename UMaxVectorT,
typename QfMatrixT,
typename SizeT,
typename RealT,
typename X0MatrixT,
typename U0MatrixT,
typename X0VectorT
>
inline
::boost::numeric::ublas::vector<RealT> fmpc_step(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<QfMatrixT> const& Qf,
::boost::numeric::ublas::vector_expression<XMinVectorT> const& xmin,
::boost::numeric::ublas::vector_expression<XMaxVectorT> const& xmax,
::boost::numeric::ublas::vector_expression<UMinVectorT> const& umin,
::boost::numeric::ublas::vector_expression<UMaxVectorT> const& umax,
SizeT T,
RealT kappa,
SizeT niters,
::boost::numeric::ublas::matrix_container<X0MatrixT>& X0,
::boost::numeric::ublas::matrix_container<U0MatrixT>& U0,
::boost::numeric::ublas::vector_container<X0VectorT>& x0)
{
namespace ublas = ::boost::numeric::ublas;
typedef RealT real_type;
typedef SizeT size_type;
typedef ublas::matrix<real_type, ublas::column_major> work_matrix_type;
typedef ublas::vector<real_type, ublas::column_major> work_vector_type;
work_matrix_type dummyK;
detail::fmpc_step(A, B, Q, R, xmin, xmax, umin, umax, Qf, T, niters, kappa, X0, U0, x0, true, X0, true, U0, true, x0, false, dummyK);
return ublas::column(U0(), 0);
}
}} // Namespace dcs::control
#endif // DCS_CONTROL_FMPC_HPP
<file_sep>/**
* \file dcs/control/bindings/slicot/sg02ad.hpp
*
* \brief Binding for the SLICOT SG02AD Fortran routine.
*
* The purpose of the SG02AD routine is to solve for \f$X\f$ either the
* continuous-time algebraic Riccati equation
* \f[
* Q + A'XE + E'XA - (L+E'XB)R^{-1}(L+E'XB)' = 0
* \f]
* or the discrete-time algebraic Riccati equation
* \f[
* E'XE = A'XA - (L+A'XB)(R + B'XB)^{-1}(L+A'XB)' + Q
* \f]
* where \f$A\f$, \f$E\f$, \f$B\f$, \f$Q\f$, \f$R\f$, and \f$L\f$ are
* \f$N\f$-by-\f$N\f$, \f$N\f$-by-\f$N\f$, \f$N\f$-by-\f$M\f$,
* \f$N\f$-by-\f$N\f$, \f$M\f$-by-\f$M\f$ and \f$N\f$-by-\f$M\f$ matrices,
* respectively, such that \f$Q = C'C\f$, \f$R = D'D\f$ and \f$L = C'D\f$;
* \f$X\f$ is an \f$N\f$-by-\f$N\f$ symmetric matrix.
*
* The routine also returns the computed values of the closed-loop
* spectrum of the system, i.e., the stable eigenvalues
* \f$\lambda(1),\ldots,\lambda(N)\f$ of the pencil \f$(A-BF,E)\f$, where
* \f$F\f$ is the optimal gain matrix,
* \f[
* F = R^{-1}(L+E'XB)' ,\quad\text{for continuous-time case}
* \f]
* and
* \f[
* F = (R+B'XB)^{-1}(L+A'XB)' ,\quad\text{for discrete-time case}
* \f]
* Optionally, matrix \f$G = BR^{-1}B'\f$ may be given instead of \f$B\f$ and
* \f$R\f$.
* Other options include the case with \f$Q\f$ and/or \f$R\f$ given in a
* factored form, \f$Q = C'C\f$, \f$R = D'D\f$, and with L a zero matrix.
*
* The routine uses the method of deflating subspaces, based on
* reordering the eigenvalues in a generalized Schur matrix pair.
*
* It is assumed that \f$E\f$ is nonsingular, but this condition is not
* checked. Note that the definition of the continuous-time
* algebraic Riccati equation, and the formula for the corresponding
* optimal gain matrix, require \f$R\f$ to be nonsingular, but the
* associated linear quadratic optimal problem could have a unique
* solution even when matrix \f$R\f$ is singular, under mild assumptions
*
* The routine uses a variant of the method of deflating subspaces
* proposed by <NAME> [1]. See also [2], [3], [4].
* It is assumed that E is nonsingular, the triple (E,A,B) is
* strongly stabilizable and detectable (see [3]); if, in addition,
* \f{equation}
* - [ Q L ]
* \bar{R} = \begin{pmatrix}
* Q & L \\
* L' & R
* \end{pmatrix> \ge 0
* \f}
* then the pencils
* \f{equation}
* \begin{pmatrix}
* A & 0 & B \\
* Q & -E' & L \\
* L' & 0 & R
* \end{pmatrix} - z \begin{pmatrix}
* E & 0 & 0 \\
* 0 & -A' & 0 \\
* 0 & -B' & 0
* \end{pmatrix}
* \f}
* for discrete-time case, and
* \f{equation}
* \begin{pmatrix}
* A & 0 & B \\
* Q & A' & L \\
* L' & B' & R
* \end{pmatrix} - s \begin{pmatrix}
* E & 0 & 0 \\
* 0 & -E' & 0 \\
* 0 & 0 & 0
* \end{pmatrix}
* \f}
* for continuous-time case, are dichotomic, i.e., they have no eigenvalues on
* the boundary of the stability domain. The above conditions are sufficient for
* regularity of these pencils. A necessary condition is that
* \f$rank([ B' L' R']') = m\f$.
*
* Under these assumptions the algebraic Riccati equation is known to
* have a unique non-negative definite solution.
*
* REFERENCES
* -# <NAME>.
* A Generalized Eigenvalue Approach for Solving Riccati Equations.
* SIAM J. Sci. Stat. Comp., 2, pp. 121-135, 1981.
* -# <NAME>, W.F. and <NAME>.
* Generalized Eigenproblem Algorithms and Software for Algebraic Riccati
* Equations.
* Proc. IEEE, 72, 1746-1754, 1984.
* -# <NAME>.
* The Autonomous Linear Quadratic Control Problem. Theory and Numerical
* Solution.
* Lecture Notes in Control and Information Sciences, vol. 163,
* Springer-Verlag, Berlin, 1991.
* -# <NAME>.
* Algorithms for Linear-Quadratic Optimization.
* Pure and Applied Mathematics: A Series of Monographs and
* Textbooks, vol. 200, Marcel Dekker, Inc., New York, 1996.
* .
*
* \author <NAME> (<EMAIL>)
*
* <hr/>
*
* Copyright 2012 <NAME> (<EMAIL>)
*
* 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.
*/
#ifndef DCS_CONTROL_BINDINGS_SLICOT_SG02AD_HPP
#define DCS_CONTROL_BINDINGS_SLICOT_SG02AD_HPP
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/operation/num_columns.hpp>
#include <boost/numeric/ublas/operation/num_rows.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <dcs/control/bindings/fortran.hpp>
#include <dcs/control/bindings/slicot/detail/slicot.hpp>
#include <stdexcept>
namespace dcs { namespace control { namespace bindings { namespace slicot {
inline
void sg02ad(fortran_char const& dico,
fortran_char const& jobb,
fortran_char const& fact,
fortran_char const& uplo,
fortran_char const& jobl,
fortran_char const& scal,
fortran_char const& sort,
fortran_char const& acc,
fortran_int const& n,
fortran_int const& m,
fortran_int const& p,
fortran_double_real const* a,
fortran_int const& lda,
fortran_double_real const* e,
fortran_int const& lde,
fortran_double_real const* b,
fortran_int const& ldb,
fortran_double_real const* q,
fortran_int const& ldq,
fortran_double_real const* r,
fortran_int const& ldr,
fortran_double_real const* l,
fortran_int const& ldl,
fortran_double_real& rcondu,
fortran_double_real* x,
fortran_int const& ldx,
fortran_double_real* alfar,
fortran_double_real* alfai,
fortran_double_real* beta,
fortran_double_real* s,
fortran_int const& lds,
fortran_double_real* t,
fortran_int const& ldt,
fortran_double_real* u,
fortran_int const& ldu,
fortran_double_real const& tol,
fortran_int* iwork,
fortran_double_real* dwork,
fortran_int const& ldwork,
fortran_logical* bwork,
fortran_int& iwarn)
{
fortran_int info(0);
DCS_CONTROL_BINDINGS_SLICOT_SG02AD(&dico,
&jobb,
&fact,
&uplo,
&jobl,
&scal,
&sort,
&acc,
&n,
&m,
&p,
a,
&lda,
e,
&lde,
b,
&ldb,
q,
&ldq,
r,
&ldr,
l,
&ldl,
&rcondu,
x,
&ldx,
alfar,
alfai,
beta,
s,
&lds,
t,
&ldt,
u,
&ldu,
&tol,
iwork,
dwork,
&ldwork,
bwork,
&iwarn,
&info);
if (info != 0)
{
::std::ostringstream oss;
switch (info)
{
case 1:
oss << "The computed extended matrix pencil is singular, possibly due to rounding errors";
break;
case 2:
oss << "The QZ/QR algorithm failed";
break;
case 3:
oss << "Reordering of the (generalized) eigenvalues failed";
break;
case 4:
oss << "After reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the (generalized) Schur form no longer satisfy the stability condition; this could also be caused due to scaling";
break;
case 5:
oss << "The computed dimension of the solution does not equal the number of states";
break;
case 6:
oss << "A singular matrix was encountered during the computation of the solution matrix";
break;
default:
oss << "Unknown error";
break;
}
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
else if (iwarn != 0)
{
::std::ostringstream oss;
switch (iwarn)
{
case 1:
oss << "The solution may be inaccurate due to poor scaling or eigenvalues too close to the boundary of the stability domain (the imaginary axis, if continuous-time case, or the unit circle, if discrete-time case)";;
break;
default:
oss << "Unknown warning";
break;
}
dcs::log_warn(DCS_LOGGING_AT, oss.str());
}
}
namespace detail { namespace /*<unnamed>*/ {
template <typename AMatrixT,
typename EMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
void sg02ad_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<EMatrixT> const& E,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
::boost::numeric::ublas::column_major_tag)
{
namespace ublas = ::boost::numeric::ublas;
typedef ublas::matrix<fortran_double_real, ublas::column_major> matrix_type;
typedef ublas::vector<fortran_double_real> real_vector_type;
typedef ublas::vector<fortran_int> int_vector_type;
typedef ublas::vector<fortran_logical> logical_vector_type;
const fortran_char dico(discrete ? 'D' : 'C');
const fortran_char jobb('B');
const fortran_char fact('N');
const fortran_char uplo('U');
const fortran_char jobl((ublas::num_rows(L) > 0 && ublas::num_columns(L) > 0) ? 'N' : 'Z');
const fortran_char scal('N');
const fortran_char sort('S');
const fortran_char acc('N');
const fortran_int n(ublas::num_rows(A)); // Number of states
const fortran_int m(ublas::num_columns(B)); // Number of inputs
const fortran_int p(0); // Number of outputs (not used because FACT == 'N')
const fortran_int lda(::std::max(1, n));
const fortran_int lde(::std::max(1, n));
const fortran_int ldb(::std::max(1, n));
const fortran_int ldq(::std::max(1, n));
const fortran_int ldr(::std::max(1, m));
const fortran_int ldl((jobl == 'Z') ? 1 : ::std::max(1, n));
matrix_type tmp_L;
if (jobl == 'Z')
{
tmp_L = matrix_type(ldl, m, 0);
}
else
{
tmp_L = L;
tmp_L.resize(ldl, m, false);
}
const fortran_int ldx(::std::max(1, n));
X().resize(ldx, n, false);
const fortran_int n2(2*n);
real_vector_type tmp_alfar(n2,0);
real_vector_type tmp_alfai(n2,0);
real_vector_type tmp_beta(n2, 0);
const fortran_int lds((jobb == 'B') ? ::std::max(1, n2+m) : ::std::max(1,n2));
S().resize(lds, (jobb == 'B') ? (n2+m) : n2, false);
const fortran_int ldt((jobb == 'G') ? ((dico == 'D') ? ::std::max(1,n2) : 1) : ::std::max(1, n2+m));
T().resize(ldt, n2, false);
const fortran_int ldu(::std::max(1, n2));
U().resize(ldu, n2, false);
const fortran_double_real tol(0); // use default value (i.e., eps - the machine precision)
fortran_double_real rcondu(0);
const fortran_int liwork((jobb == 'B') ? ::std::max(::std::max(1, m), n2) : ::std::max(1,n2));
int_vector_type iwork(liwork,0);
const fortran_int ldwork((jobb == 'G') ? ((dico == 'C') ? ::std::max(3,6*n) : ::std::max(7*(n2+1)+16,16*n)) : ::std::max(::std::max(::std::max(7*(n2+1)+16, 16*n), n2+m), 3*m));
real_vector_type dwork(ldwork,0);
logical_vector_type bwork(n2,0);
fortran_int iwarn(0);
sg02ad(dico,
jobb,
fact,
uplo,
jobl,
scal,
sort,
acc,
n,
m,
p,
A().data().begin(),
lda,
E().data().begin(),
lde,
B().data().begin(),
ldb,
Q().data().begin(),
ldq,
R().data().begin(),
ldr,
tmp_L.data().begin(),
ldl,
rcondu,
X().data().begin(),
ldx,
tmp_alfar.data().begin(),
tmp_alfai.data().begin(),
tmp_beta.data().begin(),
S().data().begin(),
lds,
T().data().begin(),
ldt,
U().data().begin(),
ldu,
tol,
iwork.data().begin(),
dwork.data().begin(),
ldwork,
bwork.data().begin(),
iwarn);
// Fill the lambda vector:
// \lambda(k) = \frac{\alfa_r(k)+j\alfa_i(k)}{\beta(k)}
lambda().resize(n2, false);
typedef typename ublas::vector_traits<LambdaVectorT>::value_type complex_type;
for (fortran_int k = 0; k < n2; ++k)
{
lambda()(k) = complex_type(tmp_alfar(k), tmp_alfai(k))/tmp_beta(k);
}
}
template <typename AMatrixT,
typename EMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
inline
void sg02ad_impl(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<EMatrixT> const& E,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U,
::boost::numeric::ublas::row_major_tag)
{
namespace ublas = ::boost::numeric::ublas;
typedef ublas::matrix<typename ublas::matrix_traits<AMatrixT>::value_type,ublas::column_major> A_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<EMatrixT>::value_type,ublas::column_major> E_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<BMatrixT>::value_type,ublas::column_major> B_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<QMatrixT>::value_type,ublas::column_major> Q_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<RMatrixT>::value_type,ublas::column_major> R_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<LMatrixT>::value_type,ublas::column_major> L_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<XMatrixT>::value_type,ublas::column_major> X_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<SMatrixT>::value_type,ublas::column_major> S_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<TMatrixT>::value_type,ublas::column_major> T_colmaj_matrix_type;
typedef ublas::matrix<typename ublas::matrix_traits<UMatrixT>::value_type,ublas::column_major> U_colmaj_matrix_type;
A_colmaj_matrix_type tmp_A(A);
E_colmaj_matrix_type tmp_E(E);
B_colmaj_matrix_type tmp_B(B);
Q_colmaj_matrix_type tmp_Q(Q);
R_colmaj_matrix_type tmp_R(R);
L_colmaj_matrix_type tmp_L(L);
X_colmaj_matrix_type tmp_X;
S_colmaj_matrix_type tmp_S;
T_colmaj_matrix_type tmp_T;
U_colmaj_matrix_type tmp_U;
sg02ad_impl(tmp_A,
tmp_E,
tmp_B,
tmp_Q,
tmp_R,
tmp_L,
discrete,
tmp_X,
lambda,
tmp_S,
tmp_T,
tmp_U,
ublas::column_major_tag());
X() = tmp_X;
S() = tmp_S;
T() = tmp_T;
U() = tmp_U;
}
}} // Namespace detail::<unnamed>
template <typename AMatrixT,
typename EMatrixT,
typename BMatrixT,
typename QMatrixT,
typename RMatrixT,
typename LMatrixT,
typename XMatrixT,
typename LambdaVectorT,
typename SMatrixT,
typename TMatrixT,
typename UMatrixT>
inline
void sg02ad(::boost::numeric::ublas::matrix_expression<AMatrixT> const& A,
::boost::numeric::ublas::matrix_expression<EMatrixT> const& E,
::boost::numeric::ublas::matrix_expression<BMatrixT> const& B,
::boost::numeric::ublas::matrix_expression<QMatrixT> const& Q,
::boost::numeric::ublas::matrix_expression<RMatrixT> const& R,
::boost::numeric::ublas::matrix_expression<LMatrixT> const& L,
bool discrete,
::boost::numeric::ublas::matrix_container<XMatrixT>& X,
::boost::numeric::ublas::vector_container<LambdaVectorT>& lambda,
::boost::numeric::ublas::matrix_container<SMatrixT>& S,
::boost::numeric::ublas::matrix_container<TMatrixT>& T,
::boost::numeric::ublas::matrix_container<UMatrixT>& U)
{
namespace ublas = ::boost::numeric::ublas;
typedef typename ublas::matrix_traits<AMatrixT>::orientation_category A_orientation_category;
typedef typename ublas::matrix_traits<EMatrixT>::orientation_category E_orientation_category;
typedef typename ublas::matrix_traits<BMatrixT>::orientation_category B_orientation_category;
typedef typename ublas::matrix_traits<QMatrixT>::orientation_category Q_orientation_category;
typedef typename ublas::matrix_traits<RMatrixT>::orientation_category R_orientation_category;
typedef typename ublas::matrix_traits<LMatrixT>::orientation_category L_orientation_category;
typedef typename ublas::matrix_traits<XMatrixT>::orientation_category X_orientation_category;
typedef typename ublas::matrix_traits<SMatrixT>::orientation_category S_orientation_category;
typedef typename ublas::matrix_traits<TMatrixT>::orientation_category T_orientation_category;
typedef typename ublas::matrix_traits<UMatrixT>::orientation_category U_orientation_category;
// pre: same orientation category
BOOST_STATIC_ASSERT((
::boost::mpl::and_<
::boost::is_same<A_orientation_category,E_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,B_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,Q_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,R_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,L_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,X_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,S_orientation_category>,
::boost::mpl::and_<
::boost::is_same<A_orientation_category,T_orientation_category>,
::boost::is_same<A_orientation_category,U_orientation_category>
>
>
>
>
>
>
>
>::value
));
// Dispatch to the right implementation
detail::sg02ad_impl(A,
E,
B,
Q,
R,
L,
discrete,
X,
lambda,
S,
T,
U,
A_orientation_category());
}
}}}} // Namespace dcs::control::bindings::slicot
#endif // DCS_CONTROL_BINDINGS_SLICOT_SG02AD_HPP
<file_sep>/**
* \file test/src/dcs/control/stabilizability.cpp
*
* \brief Test suite for system stabilizability.
*
* Copyright (C) 2009-2010 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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/>.
*
* \author <NAME> (<EMAIL>)
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <dcs/control/analysis/stabilizability.hpp>
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
const double tol = 1.0e-5;
DCS_TEST_DEF( stabilizability_check )
{
DCS_TEST_CASE("Stabilizability Check");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// Stabilizable and controllable system
{
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = -1; A(1,1) = 2;
matrix_type B(n,m);
B(0,0) = 1;
B(1,0) = 2;
bool stbl = dcs::control::is_stabilizable(A, B, true);
bool expect_stbl = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is Stabilizable = " << std::boolalpha << stbl);
DCS_TEST_CHECK(stbl == expect_stbl);
}
// Stabilizable but not controllable system
{
const std::size_t n = 3;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = -1; A(0,1) = 3; A(0,2) = 0;
A(1,0) = 0; A(1,1) = 1; A(1,2) = 1;
A(1,0) = 0; A(1,1) = 2; A(1,2) = 0;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = 2.0/3.0;
B(1,0) = 0; B(1,1) = 1.0/3.0;
B(2,0) = 0; B(2,1) = 1.0/3.0;
bool stbl = dcs::control::is_stabilizable(A, B, true);
bool expect_stbl = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is Stabilizable = " << std::boolalpha << stbl);
DCS_TEST_CHECK(stbl == expect_stbl);
}
// Non stabilizable system
{
const std::size_t n = 2;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = 4; A(1,1) = -2;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = -1;
B(1,0) = 1; B(1,1) = -1;
bool stbl = dcs::control::is_stabilizable(A, B, true);
bool expect_stbl = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is Stabilizable = " << std::boolalpha << stbl);
DCS_TEST_CHECK(stbl == expect_stbl);
}
}
int main()
{
DCS_TEST_SUITE("DCS Control :: Stabilizability");
DCS_TEST_BEGIN();
DCS_TEST_DO( stabilizability_check );
DCS_TEST_END();
}
<file_sep>#!/bin/sh
base_path=.
test_src_path="$base_path/test/src/dcs/control"
test_bin_path="$base_path/build/test/dcs/control"
test_files=$(ls $test_src_path/*.cpp)
for f in $test_files; do
f=$(basename $f .cpp)
t="$test_bin_path/$f"
if [ -x $t ]; then
echo -n "--- $f ==> "
out=$($t 2>&1 | grep -i 'failed test')
echo $out
fi
done
<file_sep><?php
$xmlFile="./test/data/test-conf_1.xml";
$doc = new DOMDocument();
$doc->preserveWhiteSpace=false;
$doc->formatOutput = true;
$doc->load($xmlFile);
$Valid=$doc->schemaValidate("./setup/epacsim_config.xsd"); // $doc is your xml loaded file, and "client_test.xsd" your xml schema definition file
echo $Valid; // Returns 1 (if valid)
?>
<file_sep>/**
* \file test/src/dcs/control/detectability.cpp
*
* \brief Test suite for system detectability.
*
* Copyright (C) 2009-2010 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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/>.
*
* \author <NAME> (<EMAIL>)
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <dcs/control/analysis/detectability.hpp>
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
const double tol = 1.0e-5;
DCS_TEST_DEF( detectability_check )
{
DCS_TEST_CASE("Detectability Check");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// Detectable and observable system
{
const std::size_t n = 2;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 0; A(0,1) = 1;
A(1,0) = 1; A(1,1) = 0;
matrix_type C(m,n);
C(0,0) = 1; C(0,1) = 0;
bool dtbl = dcs::control::is_detectable(A, C, true);
bool expect_dtbl = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("Is Detectable = " << std::boolalpha << dtbl);
DCS_TEST_CHECK(dtbl == expect_dtbl);
}
/*
// Detectable but not observable system
{
const std::size_t n = 2;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = 1;
A(1,0) = 4; A(1,1) = -2;
matrix_type B(n,m);
B(0,0) = 1; B(0,1) = -1;
B(1,0) = 1; B(1,1) = -1;
bool dtbl = dcs::control::is_detectable(A, B, true);
bool expect_dtbl = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("B = " << B);
DCS_DEBUG_TRACE("Is Detectable = " << std::boolalpha << dtbl);
DCS_TEST_CHECK(dtbl == expect_dtbl);
}
*/
// Non detectable system
{
const std::size_t n = 3;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = -0.4; A(0,1) = 0; A(0,2) = 0;
A(1,0) = 0.0; A(1,1) = 3; A(1,2) = 0;
A(2,0) = 0.0; A(2,1) = 0; A(2,2) = -2;
matrix_type C(m,n);
C(0,0) = 1; C(0,1) = 1; C(0,2) = 0;
bool dtbl = dcs::control::is_detectable(A, C, true);
bool expect_dtbl = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("Is Detectable = " << std::boolalpha << dtbl);
DCS_TEST_CHECK(dtbl == expect_dtbl);
}
}
int main()
{
DCS_TEST_SUITE("DCS Control :: Detectability");
DCS_TEST_BEGIN();
DCS_TEST_DO( detectability_check );
DCS_TEST_END();
}
<file_sep>/**
* \file test/src/dcs/control/observability.cpp
*
* \brief Test suite for system observability.
*
* Copyright (C) 2009-2011 Distributed Computing System (DCS) Group, Computer
* Science Department - University of Piemonte Orientale, Alessandria (Italy).
*
* 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/>.
*
* \author <NAME> (<EMAIL>)
*/
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublasx/operation/rank.hpp>
#include <dcs/debug.hpp>
#include <dcs/test.hpp>
#include <dcs/control/analysis/observability.hpp>
namespace ublas = boost::numeric::ublas;
namespace ublasx = boost::numeric::ublasx;
const double tol = 1.0e-5;
DCS_TEST_DEF( observability_matrix )
{
DCS_TEST_CASE("Observability Matrix");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
const std::size_t n = 3;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = -1; A(0,1) = 2; A(0,2) = -1;
A(1,0) = -1; A(1,1) = -2; A(1,2) = 0;
A(2,0) = -3; A(2,1) = -3; A(2,2) = 2;
matrix_type C(m,n);
C(0,0) = 1; C(0,1) = 0; C(0,2) = 0;
matrix_type expect_O(n*m, n);
expect_O(0,0) = 1; expect_O(0,1) = 0; expect_O(0,2) = 0;
expect_O(1,0) = -1; expect_O(1,1) = 2; expect_O(1,2) = -1;
expect_O(2,0) = 2; expect_O(2,1) = -3; expect_O(2,2) = -1;
matrix_type O = dcs::control::make_observability_matrix(A, C);
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("O = [C CA ... CA^{" << (n-1) << "}] = " << O);
DCS_DEBUG_TRACE("Number of unobservable states: " << (n-ublasx::rank(O)) );
DCS_TEST_CHECK_MATRIX_CLOSE(O, expect_O, n*m, n, tol);
}
DCS_TEST_DEF( observability_check )
{
DCS_TEST_CASE("Observability Check");
typedef double value_type;
typedef ublas::matrix<value_type> matrix_type;
// observable system
{
const std::size_t n = 3;
const std::size_t m = 1;
matrix_type A(n,n);
A(0,0) = 1; A(0,1) = -3; A(0,2) = -1;
A(1,0) = -1; A(1,1) = -2; A(1,2) = 2;
A(1,0) = -1; A(1,1) = 2; A(1,2) = -2;
matrix_type C(m,n);
C(0,0) = 1; C(0,1) = 1; C(0,2) = 0;
bool obsv = dcs::control::is_observable(A, C);
bool expect_obsv = true;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("Is Observable = " << std::boolalpha << obsv);
DCS_TEST_CHECK(obsv == expect_obsv);
}
// Non observable system
{
const std::size_t n = 3;
const std::size_t m = 2;
matrix_type A(n,n);
A(0,0) = -3; A(0,1) = 1; A(0,2) = 0;
A(1,0) = 0; A(1,1) = -3; A(1,2) = 1;
A(2,0) = 0; A(2,1) = 0; A(2,2) = -3;
matrix_type C(m,n);
C(0,0) = 0; C(0,1) = 1; C(0,2) = 1;
C(1,0) = 0; C(1,1) = 2; C(1,2) = -1;
bool obsv = dcs::control::is_observable(A, C);
bool expect_obsv = false;
DCS_DEBUG_TRACE("A = " << A);
DCS_DEBUG_TRACE("C = " << C);
DCS_DEBUG_TRACE("Is Observable = " << std::boolalpha << obsv);
DCS_TEST_CHECK(obsv == expect_obsv);
}
}
int main()
{
DCS_TEST_SUITE("DCS Control :: Observability");
DCS_TEST_BEGIN();
DCS_TEST_DO( observability_matrix );
DCS_TEST_DO( observability_check );
DCS_TEST_END();
}
| dbaf8ee32868612e1cb8681ceb7886ea681a717f | [
"Markdown",
"C++",
"PHP",
"Shell"
] | 35 | Shell | cyy1991/dcsxx-control | af60dadcdb2b55f4e9b47578b7944dfa9cea3e92 | 6b0bf92f4f2abab8eba5c0562157fc3e71a3ed83 |
refs/heads/master | <repo_name>yalin001/springcloudANDdocker<file_sep>/pd-order-consumer/src/main/java/com/pd/OrderConsumer.java
package com.pd;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.pd.pojo.PdOrder;
import com.pd.service.OrderService;
import com.rabbitmq.client.Channel;
@Component
public class OrderConsumer {
//收到订单数据后,会调用订单的业务代码,把订单保存到数据库
@Autowired
private OrderService orderService;
//添加该注解后,会从指定的orderQueue接收消息,
//并把数据转为 PdOrder 实例传递到此方法
@RabbitListener(queues="orderQueue")
public void save(PdOrder pdOrder, Channel channel, Message message)
{
System.out.println("消费者");
System.out.println(pdOrder.toString());
try {
orderService.saveOrder(pdOrder);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
e.printStackTrace();
}
}
}<file_sep>/rabbitmq/src/main/java/testBlockingQueue/BlockingQueue.java
package testBlockingQueue;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
public class BlockingQueue {
static ArrayBlockingQueue<String> q = new ArrayBlockingQueue<String>(5);
public static void main(String[] args) {
new Thread() {
public void run() {
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
q.offer(s);
};
}.start();
new Thread() {
public void run() {
String s;
try {
s=q.take();//阻塞等待队列中的数据
System.out.println("输出:"+s);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
}
| b7c8d9f2251055cd1bb98865b993212f3aa3157f | [
"Java"
] | 2 | Java | yalin001/springcloudANDdocker | 8c0ff40220251795eb8ee9a1f2173cf85c876553 | f47549c8570e9d048bb4e0952ac674f10bf3ddb5 |
refs/heads/master | <file_sep>package casinoData;
import java.io.*;
import java.util.Scanner;
//TODO: when a player registers check if pass or user name has ','
public class Data {
public static void save(Player p) throws IOException {
String path = new File("."). getCanonicalPath() +"\\users\\" + p.getUserName()+".txt";
BufferedWriter writer = new BufferedWriter(new FileWriter(path,false));
writer.write(p.getPassword());
writer.newLine();
writer.write(p.getName());
writer.newLine();
writer.write(String.valueOf(p.getBalance()));
writer.close();
}
public static Player load(String userName) throws IOException{
String path = new File("."). getCanonicalPath() +"\\users\\" +userName+".txt";
BufferedReader reader = new BufferedReader(new FileReader(path));
String password = <PASSWORD>();
String name = reader.readLine();
int balance = Integer.parseInt(reader.readLine());
return new Player(name, balance, userName, password);
}
public static Player openGame() throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Are you registered?(y/n)");
String answer = in.next();
if (answer.equals("y")){
System.out.println("Enter user name:");
String user = in.next();
System.out.println("Enter password:");
String pass = in.next();
return Login.logIn(user,pass);
}
else {
return load(Registraition.register());
}
}
}
<file_sep>package casinoData;
public class CasinoExceptions {
public static class outOfMoney extends Exception{
@Override
public String getMessage() {
return "Out of money";
}
}
public static class yesOrNo extends Exception{
@Override
public String getMessage() {
return "Please enter y or n";
}
}
}
<file_sep>package card;
public class CardType {
public static String cardTypes[] = {"Club","Diamond","Heart","Spade"};
private int type;
CardType(String type) throws Exception {
//Check if type is legal
for(int i = 0; i < cardTypes.length; i++)
if(type == cardTypes[i]){
this.type = i;
return;
}
throw new CardException.badInput();
}
CardType(int type) throws Exception {
if (0<=type && type < cardTypes.length)
this.type = type;
else
throw new CardException.badInput();
}
public int getType(){
return type;
}
}<file_sep>package games.BlackJack;
class Const {
static int BLACK_JACK = 21;
static int ROYAL_VALUE = 10;
static int HIGH_ACE = 11;
static int LOW_ACE = 1;
static int AI_DRAW = 16;
//AI will draw if hand value >= AI_DRAW
static int START_HAND = 2;
}
| 16e9b776fe3095cd3a1fbfd97f0a8f3806ebcd03 | [
"Java"
] | 4 | Java | jonathanjosef91/casino | a742cfb9280e86a1b5280b06bc9e3e20a330b38f | 45f836535089fedac8d996de07374828d7ac95dc |
refs/heads/master | <file_sep>import falcon
import json
import boto3
from datetime import datetime
import random
import calendar
class QuoteResource:
def on_get(self, req, resp):
"""Handles GET requests"""
quote = {
'quote': 'I\'ve always been more interested in the future than in the past.',
'author': '<NAME>'
}
resp.body = json.dumps(quote)
def on_post(self, req, resp):
"""Handles GET requests"""
class EventResource:
def on_post(self, req, resp):
"""Handles POST requests"""
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName='axis-node-event-queue')
queue.send_message(MessageBody='boto3', MessageAttributes={
'Author': {
'StringValue': 'Daniel',
'DataType': 'String'
}
})
resp.status = falcon.HTTP_200
class KinesisEventResource:
thing_id = 'aa-bb'
stream_name = 'axis-node-event-stream'
def on_get(self, req, resp):
"""Handles GET requests"""
kinesis_client = boto3.client('kinesis')
response = kinesis_client.describe_stream(StreamName=KinesisEventResource.stream_name)
my_shard_id = response['StreamDescription']['Shards'][0]['ShardId']
shard_iterator = kinesis_client.get_shard_iterator(StreamName=KinesisEventResource.stream_name,
ShardId=my_shard_id,
ShardIteratorType='LATEST')
my_shard_iterator = shard_iterator['ShardIterator']
record_response = kinesis_client.get_records(ShardIterator=my_shard_iterator,
Limit=2)
record_response = kinesis_client.get_records(ShardIterator=record_response['NextShardIterator'],
Limit=2)
# resp.body = json.dumps(quote)
def on_post(self, req, resp):
"""Handles POST requests"""
kinesis_client = boto3.client('kinesis')
payload = {
'prop': str(random.randint(40, 120)),
'timestamp': str(calendar.timegm(datetime.utcnow().timetuple())),
'thing_id': KinesisEventResource.thing_id
}
put_response = kinesis_client.put_record(
StreamName=KinesisEventResource.stream_name,
Data=json.dumps(payload),
PartitionKey=KinesisEventResource.thing_id)
resp.body = put_response
resp.status = falcon.HTTP_200
api = falcon.API()
api.add_route('/api/quote', QuoteResource())
api.add_route('/api/event', EventResource())
api.add_route('/api/kinesis', KinesisEventResource()) | 96912b579531a41d3e79498b568abdd07fa79ee3 | [
"Python"
] | 1 | Python | benmyob/kinesis-sqs-poc | 2d41d165072ea42ce8f7199ac9f9560d713a5b2a | 2d4027802351699f9593ec660e4bd6f9520b0d8c |
refs/heads/master | <repo_name>linkcheckerfw/linkcheckerfw.github.io<file_sep>/releases/linkchecker.meta.js
// ==UserScript==
// @name Verificador de uploads [FW]
// @version 1.0.1
// @description User script para facilitar a verificação de uploads na FW
// @author XOR
// @namespace 4971e63b909612f5598edd6d90012dae
// @match *://*.filewarez.tv/*
// @grant GM_xmlhttpRequest
// @grant GM.xmlhttpRequest
// @grant GM.setValue
// @grant GM_setValue
// @grant GM.getValue
// @grant GM_getValue
// @grant GM_addStyle
// @grant GM.addStyle
// @grant unsafeWindow
// @run-at document-start
// @connect *
// @noframes
// ==/UserScript==
| 9e86751b8aad8a7965c6cf81d478d06f3abf0c45 | [
"JavaScript"
] | 1 | JavaScript | linkcheckerfw/linkcheckerfw.github.io | b59c7d1e4ec67d2101bdf17fbbdc356354f4b4cc | 18f54c4785a1a781c6533f1a7188f0c523660f28 |
refs/heads/master | <file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'challenge/(?P<challenge_pk>[0-9]+)/team/count$',
views.get_participant_team_count, name='get_participant_team_count'),
url(r'challenge/(?P<challenge_pk>[0-9]+)/participant/count$',
views.get_participant_count, name='get_participant_count'),
url(r'challenge/(?P<challenge_pk>[0-9]+)/submission/(?P<duration>[A-Za-z]+)/count$',
views.get_submission_count, name='get_submission_count'),
]
<file_sep>from datetime import timedelta
from django.utils import timezone
from rest_framework import permissions, status
from rest_framework.decorators import (api_view,
authentication_classes,
permission_classes,
throttle_classes,)
from rest_framework.response import Response
from rest_framework_expiring_authtoken.authentication import (ExpiringTokenAuthentication,)
from rest_framework.throttling import UserRateThrottle
from accounts.permissions import HasVerifiedEmail
from challenges.permissions import IsChallengeCreator
from challenges.utils import get_challenge_model
from jobs.models import Submission
from jobs.serializers import (SubmissionCount,
SubmissionCountSerializer,
)
from participants.models import Participant
from participants.serializers import (ParticipantCount,
ParticipantCountSerializer,
ParticipantTeamCount,
ParticipantTeamCountSerializer,
)
@throttle_classes([UserRateThrottle])
@api_view(['GET', ])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail, IsChallengeCreator))
@authentication_classes((ExpiringTokenAuthentication,))
def get_participant_team_count(request, challenge_pk):
challenge = get_challenge_model(challenge_pk)
participant_team_count = challenge.participant_teams.count()
participant_team_count = ParticipantTeamCount(participant_team_count)
serializer = ParticipantTeamCountSerializer(participant_team_count)
return Response(serializer.data, status=status.HTTP_200_OK)
@throttle_classes([UserRateThrottle])
@api_view(['GET', ])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail, IsChallengeCreator))
@authentication_classes((ExpiringTokenAuthentication,))
def get_participant_count(request, challenge_pk):
challenge = get_challenge_model(challenge_pk)
participant_teams = challenge.participant_teams.all()
participant_count = Participant.objects.filter(team__in=participant_teams).count()
participant_count = ParticipantCount(participant_count)
serializer = ParticipantCountSerializer(participant_count)
return Response(serializer.data, status=status.HTTP_200_OK)
@throttle_classes([UserRateThrottle])
@api_view(['GET', ])
@permission_classes((permissions.IsAuthenticated, HasVerifiedEmail, IsChallengeCreator))
@authentication_classes((ExpiringTokenAuthentication,))
def get_submission_count(request, challenge_pk, duration):
'''
Returns submission count for a challenge according to the duration
Valid values for duration are all, daily, weekly and monthly.
'''
# make sure that a valid url is requested.
if duration.lower() not in ('all', 'daily', 'weekly', 'monthly'):
response_data = {'error': 'Wrong URL pattern!'}
return Response(response_data, status=status.HTTP_406_NOT_ACCEPTABLE)
challenge = get_challenge_model(challenge_pk)
challenge_phase_ids = challenge.challengephase_set.all().values_list('id', flat=True)
q_params = {'challenge_phase__id__in': challenge_phase_ids}
since_date = None
if duration.lower() == 'daily':
since_date = timezone.now().date()
elif duration.lower() == 'weekly':
since_date = (timezone.now() - timedelta(days=7)).date()
elif duration.lower() == 'monthly':
since_date = (timezone.now() - timedelta(days=30)).date()
# for `all` we dont need any condition in `q_params`
if since_date:
q_params['submitted_at__gte'] = since_date
submission_count = Submission.objects.filter(**q_params).count()
submission_count = SubmissionCount(submission_count)
serializer = SubmissionCountSerializer(submission_count)
return Response(serializer.data, status=status.HTTP_200_OK)
| 99e667495fd029b30411ecfc5143f8570cc21023 | [
"Python"
] | 2 | Python | TroJan/EvalAI | e378c5d6fd6a2f5d1ec020198eeae5d17793952f | 4bcbe8570b93011c7f1c80a271bc37c9c40eba36 |
refs/heads/master | <file_sep># Copyright (c) 2013-2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Resource verification business logic.
"""
from barbican.common import utils
LOG = utils.getLogger(__name__)
def verify(verification):
"""Verifies if a resource is 'valid' for an action or not.
Based on the target resource information in the supplied verification
entity this function determines if it is valid to use for the specified
action. The supplied entity is then updated with the processing result.
:param verification: A Verification entity
"""
if 'image' == verification.resource_type:
#TODO(jfwood) Add rules or else consider a plugin approach similar to
# barbican/crypto/plugin.py.
verification.is_verified = True
<file_sep>#!/bin/bash
CONFIG_DIR=/etc/barbican
DB_DIR=/var/lib/barbican
# VIRTUAL_ENV is set by virtualenv on activate. If VIRTUAL_ENV is not,
# available, it attempts to fallback on pyenv for the python environment path.
VENV_DIR=${VIRTUAL_ENV:-`pyenv prefix`}
LOCAL_CONFIG_DIR=./etc/barbican
if [ ! -d $LOCAL_CONFIG_DIR ];
then
LOCAL_CONFIG_DIR=../etc/barbican
fi
LOCAL_CONFIG=$LOCAL_CONFIG_DIR/barbican-api.conf
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo 'DIR: '$DIR
start_barbican()
{
# Start barbican server up.
# Note: Add ' --stats :9314' to run a stats server on port 9314
echo "Starting barbican..."
uwsgi --master --emperor $CONFIG_DIR/vassals -H $VENV_DIR
}
stop_barbican()
{
echo "Stopping barbican..."
killall -KILL uwsgi
}
install_barbican()
{
# Copy conf file to home directory so oslo.config can find it
cp $LOCAL_CONFIG ~
# Copy the other config files to the /etc location
if [ ! -d $CONFIG_DIR ];
then
sudo mkdir -p $CONFIG_DIR
sudo chown $USER $CONFIG_DIR
fi
cp -rf $LOCAL_CONFIG_DIR/* $CONFIG_DIR/
# Create a SQLite db location.
if [ ! -d $DB_DIR ];
then
sudo mkdir -p $DB_DIR
sudo chown $USER $DB_DIR
fi
# Install Python dependencies
pip install -r requirements.txt
pip install -r test-requirements.txt
# Install uWSGI
pip install uwsgi
# Install source code into the Python path as if packaged.
pip install -e .
# If using pyenv, rehash now.
hash pyenv &> /dev/null
if [ $? -eq 0 ]; then
pyenv rehash
fi
# Run unit tests
nosetests
start_barbican
}
case "$1" in
install)
install_barbican
;;
start)
start_barbican
;;
stop)
stop_barbican
;;
restart)
stop_barbican
sleep 5
start_barbican
;;
*)
echo "Usage: barbican.sh {install|start|stop|restart}"
exit 1
esac
| e576c75c02275ee1b2c5b19d7adfe08b47508c37 | [
"Python",
"Shell"
] | 2 | Python | andersonvom/barbican | e3d7b43cda0fdcab38facbb3b7e0492c06f74253 | c7725d05453228b4f9bc805ea7495efb9ef42483 |
refs/heads/master | <file_sep>const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
var prefix = ayarlar.prefix;
exports.run = (client, message, params) => {
const embedyardim = new Discord.RichEmbed()
.setTitle("Komutlar")
.setDescription('')
.setColor(0x00ffff)
.addField("**» Eğlence Komutları**", `a!atatürk = Rastgele Atatürkün Fotoğraflarını Gösterir. \na!starwars = StarWars (Pixel Formatında) Filmini Gösterir. \na!banned = Dene ve Gör! \na!kahkaha = Kahkaha Atarsınız \na!herkesebendençay = Herkese Çay Alırsınız. \na!koş = Koşarsınız.\na!çayiç = Çay İçersiniz. \na!çekiç = İstediğiniz Kişiye Çekiç Atarsınız. \na!çayaşekerat = Çaya Şeker Atarsınız. \na!yumruk-at = Yumruk Atarsınız. \na!şanslısayım = Bot Sizin Şanslı Sayınızı Söyler.`)
.addField("**» Kullanıcı Komutları**", `a!report = İstediğiniz Kullanıcıyı Reportlarsınız. \na!kısalt = İstediğiniz Linki Kısaltarak Özelleştire Bilirsiniz. \na!yaz = Bota İsediğinizi Yazdırırsınız. \na!sunucubilgi = Bulunduğunuz Sunucu Hakkında Bilgi Verir. \na!sunucuresmi = Bulunduğunuz Sunucunun Resmin Gösterir. \na!kullanıcıbilgim = Sizin Hakkınızda Bilgi Verir. \na!avatarım = Avatarınınızı Gösterir. `)
.addField("**» Oyun Komutları**", `a!fortnite = İstediğiniz Kullanıcının İstatistiklerine Bakarsınız.`)
.addField("**» Sunucu Yetkilisi Komutları**", `a!ban = İstediğiniz Kişiyi Sunucudan Banlar. \na!kick = İstediğiniz Kişiyi Sunucudan Atar. \na!unban = İstediğiniz Kişinin Yasağını Açar. \na!sustur = İstediğiniz Kişiyi Susturur. \na!sil = Belirtilen Miktarda Mesajı Silir. (MAX 100) \na!oylama = Oylama Açar. \na!duyuru = Güzel Bir Duyuru Görünümü Sağlar.`)
.addField("**» Botun Ana Komutları**", "a!yardım = BOT Komutlarını Atar. \na!bilgi = BOT Kendisi Hakkında Bilgi Verir. \na!ping = BOT Gecikme Süresini Söyler. \na!davet = BOT Davet Linkini Atar. \na!istatistik = BOT İstatistiklerini Gösterir.")
.setFooter('AnatoliaBot Güncel Sürüm [ BETA v0.1.0 ]')
if (!params[0]) {
const commandNames = Array.from(client.commands.keys());
const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
message.channel.send(embedyardim);
} else {
let command = params[0];
if (client.commands.has(command)) {
command = client.commands.get(command);
message.author.send('', `= ${command.help.name} = \n${command.help.description}\nDoğru kullanım: ` + prefix + `${command.help.usage}`);
}
}
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['h', 'halp', 'help', 'y'],
permLevel: 0
};
exports.help = {
name: 'yardım',
description: 'Tüm komutları gösterir.',
usage: 'yardım [komut]'
};
| 3123b90c679c97b447296cf67c353af68fb4a571 | [
"JavaScript"
] | 1 | JavaScript | ahmetwinner/dcbot1 | a1fdb7cea129f362a7b9287770cbd19711f57ba0 | cea64f422c150bbe07ae31a636728377b1f0d307 |
refs/heads/main | <repo_name>settur1409/JourneyWithDataScience<file_sep>/market_basket_Analysis/groceries_association_rules_streamlit.py
import pandas as pd
import streamlit as st
rulesData = pd.read_csv("rules.csv")
rawData = pd.read_csv("Groceries_dataset.csv")
recommendedItems = pd.DataFrame()
product_choose = st.selectbox(label="select product to choose the recommendation", key="chooseFromDropDown", options=pd.unique(rulesData['antecedents']))
if product_choose is not None:
filteredData = rulesData[rulesData['antecedents'] == product_choose]
recommendedItems = filteredData.sort_values(by=['consequent support'])['consequents']
recommendedItems = recommendedItems.iloc[:5].reset_index()
# itemsToDisplay = recommendedItems['consequents'].tolist()
st.table(recommendedItems['consequents'].values)
| 3199558aac6ee83a99e702d101ec9ba61f629a61 | [
"Python"
] | 1 | Python | settur1409/JourneyWithDataScience | 4cce23b5760490c79d9079e9b594485760aafeb0 | 435570526074442ce8c00e1bb1718d8fc6ad3eeb |
refs/heads/master | <file_sep>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "./../lib/crc16.cc"
using namespace std;
TEST_CASE("CRC16 sum are computed")
{
uint8_t stream[] = {
0xa5, 0xd2, 0xdd, 0x70, 0x96, 0x35, 0xd7, 0xf0, 0x12, 0x0b,
0x07, 0x7d, 0x60, 0xbe, 0x3f, 0x59, 0x1a, 0x59, 0x9f, 0x71,
0x2f, 0x89, 0x11, 0x73,
0x96, 0xce};
SECTION("Checksum can return an sum array")
{
uint8_t sum[2];
CRC16CheckSum(stream, 24, sum);
REQUIRE(sum[0] == 0x96);
REQUIRE(sum[1] == 0xce);
}
SECTION("Checksum can return an string by char*")
{
char *s = CRC16CheckSum(stream, 24);
string sum(s);
REQUIRE(sum == "96ce");
}
SECTION("Checksum can return an unsigned short number")
{
uint16_t sum;
CRC16CheckSum(stream, 24, &sum);
REQUIRE(sum == 38606);
}
SECTION("Verifysum should be passed")
{
bool isValid = CRC16VerifySum(stream, 26);
REQUIRE(isValid == true);
}
}
<file_sep>all: clean build-node
build-node:
node-gyp rebuild
build-xcode-project:
node-gyp configure -- -f xcode
test-node:
npm test
test-cpp:
clang++ -Wc++11-extensions -std=c++11 -o ./test_cpp/crc16_test.out ./test_cpp/crc16_test.cc
./test_cpp/crc16_test.out
test: test-cpp
benchmark.js:
npm run benchmark
nanobench:
npm run nanobench
.PHONY: clean
clean:
rm -fr build
rm -fr **/*.dSYM
rm -f **/*.out
rm -fr .nyc_output
rm -fr coverage
<file_sep># node-crc16
_A native node addon to calcalate CRC16 values, adopted by MODBUS agreement._
## Bug Fixes
- fix a param check bug
([de764db8](https://github.com/imnemo/crc16/commit/de764db8e5ae9e250a10006e4a0fd7f97440c33a))
- fix:Buffer factory bug when node version is less than v5.10.0
([6fc831e1](https://github.com/imnemo/crc16/commit/6fc831e1841ee8045085853cc8c3c07f1a20d9e0))
## Features
- feat:Add node native addon implement and the main entry
([3bc81ad0](https://github.com/imnemo/crc16/commit/3bc81ad0a2720130d7b4523e57d8cada46959a61))
## Release
- release:v1.0.0
([c2975ebd](https://github.com/imnemo/crc16/commit/c2975ebdc7953bb67493e4ff23b4031c3f6e9246))
- release:v1.0.0-beta
([f2931f20](https://github.com/imnemo/crc16/commit/f2931f2091d224de117437786a8559cbee4ea3d6))
## Documentation
- doc:Add Runkit example code
([b344adc6](https://github.com/imnemo/crc16/commit/b344adc69acf251902e46ca4aad53d6d0c3f8f24))
- doc:Add some badges
([d1821c77](https://github.com/imnemo/crc16/commit/d1821c77a7f986446ad2b2fb79b806cd446bde7c))
- doc:Add readme in English
([339e538e](https://github.com/imnemo/crc16/commit/339e538ee189b6a944ade0dde40d21ee226a79b8))
- doc:Add readme in Chinese
([468fd09a](https://github.com/imnemo/crc16/commit/468fd09ab2c6e23594387b462d7e451df951b978))
## Refactor
- refactor:Remove bufferfactory util
([c91c3488](https://github.com/imnemo/crc16/commit/c91c348870b002b4f04d6635ce4de82d57e302a3))
- refactor:deprecate option.getArry and turn it to option.retType
([8af05e59](https://github.com/imnemo/crc16/commit/8af05e59a13a5b070cd80a70eb21de7a19ba74cf))
- refactor:c++ implementation
([c65f543d](https://github.com/imnemo/crc16/commit/c65f543da1997c923e4001ea231fbdf47ccb17c1))
## Test
- test:Add unit test about option.retType
([a31f11e1](https://github.com/imnemo/crc16/commit/a31f11e166ac030d86a19f8624c6d4ee20efd0d0))
- test:Add the exception test branch
([7f3e383e](https://github.com/imnemo/crc16/commit/7f3e383ec820cdd03cb78985ad69e877a0c14050))
- test:Integrating with Coveralls
([a6707fca](https://github.com/imnemo/crc16/commit/a6707fca4b657ffa947d5d10c0dc8f8560575c94))
- test:Add C++ Unit Test using Catch
([9882e526](https://github.com/imnemo/crc16/commit/9882e526ff9149dff486257d936977828e078d6a))
- test:Add supported node version
([8234e473](https://github.com/imnemo/crc16/commit/8234e473335a1a9ec723dbed2dea33110e0abd32))
- test:Add CI using tranvis
([45e0ec77](https://github.com/imnemo/crc16/commit/45e0ec7713ffd671a24daff3b4c7f1d70746c0d2))
- test:Add code coverage using istanbul
([c1b747ba](https://github.com/imnemo/crc16/commit/c1b747ba1cd424ced7157a72e0417d9fb2d732a1))
- test:increase the test case to 10000
([3f49576d](https://github.com/imnemo/crc16/commit/3f49576d777f56792671f8dea811762957bd9f1c))
- test:Add unit test
([5ea90c4d](https://github.com/imnemo/crc16/commit/5ea90c4d1677408561a5a661f4fcf9584ebc395f))
- test:Add c++ code test and makefile
([7d65cc38](https://github.com/imnemo/crc16/commit/7d65cc38cee8cffb7652d4e61bab68510df264ec))
## Benchmark
- benchmark:Add benchmark using nanobench
([ca4156cf](https://github.com/imnemo/crc16/commit/ca4156cfb1c3fea5c1a7cdccf8e07b34a676c032))
- benchmark:Add benchmark using benchmark.js
([06453f52](https://github.com/imnemo/crc16/commit/06453f52b3d823f8ba5c2f6d96348f73b0eeeeb6))
## Chore
- chore:remove debug dependency
([108a5d80](https://github.com/imnemo/crc16/commit/108a5d8022e68a0cae678219c2d43c512eae44d4))
- chore:update .changelogrc to make a whole versions changelog
([21b16ae0](https://github.com/imnemo/crc16/commit/21b16ae0fafe3d5a8371c581d5ee1d7692b8818e))
- chore:Add .npmignore
([61e8968e](https://github.com/imnemo/crc16/commit/61e8968e40e9fa460e16ae8f502e5bc92facbc77))
- chore:Add changelog
([fc096515](https://github.com/imnemo/crc16/commit/fc0965155ae4724e5fc43cd595798a401a43b2f8))
- chore:Add core algorithm c++ implementation
([d5042c74](https://github.com/imnemo/crc16/commit/d5042c7470cff63567525e4c108d20cf044bb21a))
---
<sub><sup>*Generated with [git-changelog](https://github.com/rafinskipg/git-changelog). If you have any problems or suggestions, create an issue.* :) **Thanks** </sub></sup>
<file_sep>[](https://travis-ci.org/imnemo/crc16)
[](https://coveralls.io/github/imnemo/crc16?branch=master)
<a href="https://www.npmjs.com/package/node-crc16" alt="NPM latest version"><img src="https://img.shields.io/npm/v/node-crc16.svg"></a>
<a href="https://www.npmjs.com/package/node-crc16" alt="NPM total downloads"><img src="https://img.shields.io/npm/dt/node-crc16.svg"></a>
<a href="https://github.com/imnemo/crc16" alt="Github stars"><img src="https://img.shields.io/github/stars/imnemo/crc16.svg?style=social&label=Star"></a>
<a href="https://github.com/imnemo/crc16" alt="Github forks"><img src="https://img.shields.io/github/forks/imnemo/crc16.svg?style=social&label=Fork"></a>
<a href="https://npms.io/search?q=node-crc16" alt="NPM latest version"><img src="https://badges.npms.io/node-crc16.svg"></a>
<a href="https://npm.runkit.com/node-crc16"><img src="https://badge.runkitcdn.com/node-crc16.svg" alt="Try node-crc16 on RunKit"/></a>
<a href="https://deepscan.io/dashboard/#view=project&pid=1291&bid=3472"><img src="https://deepscan.io/api/projects/1291/branches/3472/badge/grade.svg" alt="DeepScan Grade"></a>
<a href="https://github.com/imnemo/crc16" alt="Github contributors"><img src="https://img.shields.io/github/contributors/imnemo/crc16.svg"></a>
<a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fimnemo%2Fcrc16?ref=badge_shield" alt="FOSSA Status"><img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimnemo%2Fcrc16.svg?type=shield"/></a>
# Node CRC16 - ([中文版README](./README-zh.md))
[MODBUS][1] is an application-layer messaging protocol, positioned at level 7 of the OSI model. It provides client/server communication between devices connected on different types of buses or networks.The `CRC`(Cyclic Redundancy Check) part in protocol, such as [MODBUS over serial line][2](Page 42), and [Modbus-RTU][3](Page 75), adopt the same one algorithm.
`node-crc16` implement the c++ version of this algorithm by table look-up, and also provide a node native addon and a nodejs version wrapper.
*This module has been well unit tested and documented.*
## Versions
If your version of node.js is lower than `v8.x.x`, please use the latest `v1.x.x` of this module, or you should select `v2.x.x`, which uses `NAPI` to implement native addon gracefully and compatibly.
## Usage
Tips: the most intuitive decription about this module is the comment in [src](./index.js) and the code in [unit test](./test) :).
### Install
`npm install node-crc16`
### generate a sum by `crc16.checkSum`
`checkSum`accept three params, the first two params `(input, [encoding])` construct a `Buffer`
```javascript
crc16.checkSum('utf8 string', 'utf8')
```
default `encoding` is `hex`
```javascript
var sum = crc16.checkSum('a031ffb7');
sum.should.equal('726d');
```
the third param is `option`,which type is `Object`
+ `option.retType` set the format of the returned sum
* default is `hex`,two bytes BigEndian hex string, `726d`
* `array`, two unsigned char number of the returned sum,`[114, 109]`
* `int`,one unsigned short number of the returned sum,`29293`
* `buffer`,Buffer type of the returned sum,`<Buffer 72 6d>`
```javascript
var sum = crc16.checkSum('a031ffb7', {retType: 'array'});
sum.should.eql([114, 109]);
```
### verify a sum by `crc16.verifySum`
Params of `verifySum` is same as `checkSum`, the first two params are used to constructe a `Buffer` which contains the `sum` to be verified.
```javascript
var stream = 'a031ffb7',
sum = '726d';
var isValid = crc16.verifySum(stream + sum);
isValid.should.equal(true);
```
## Contribution
### get source code
```sh
# fork and clone the code to your local env
git clone <EMAIL>:imnemo/crc16.git
cd crc16
```
### code structure
```
├── lib //CRC16 algorithm implemention in c++
├── util //Util functions
├── src //Node Native Addon
├── test //JS unit testing
├── test_cpp //C++ unit testing
├── index.js //Main entry of NodeJS module
```
### install dependencies
`npm install`
### C++ unit testing
The implemention of `CRC16` checking and verifing algorithm in c++ is standalone in `./lib/crc16.cc`. If you want to modify it, please write suitable unittest cases. You can reference [Catch](https://github.com/philsquared/Catch), and then run:
```bash
make test
```
> Make sure all the unit testing case is passed after you modify.
### JS unit testing
`npm test` or `./node_modules/.bin/mocha --reporter spec`
### Benchmark
#### use benchmark.js
```bash
>>> npm run benchmark
> node-crc16@1.0.0 benchmark /Users/nemo/code/imnemo/crc16
> node benchmark/benchmark.js
CEC16#checkSum x 905,071 ops/sec ±2.00% (83 runs sampled)
CRC16#verifySum x 1,540,940 ops/sec ±19.92% (65 runs sampled)
Fastest is CRC16#verifySum
```
#### use nanobench
```bash
>>> npm run nanobench
> node-crc16@1.0.0 nanobench /Users/nemo/code/imnemo/crc16
> node benchmark/nanobench.js
NANOBENCH version 2
> /Users/nemo/.nvm/versions/node/v8.1.2/bin/node benchmark/nanobench.js
# CRC16#checkSum 2,000,000 times
ok ~3.17 s (3 s + 166422442 ns)
# CRC16#verifySum 2,000,000 times
ok ~2.85 s (2 s + 848059820 ns)
all benchmarks completed
ok ~6.01 s (6 s + 14482262 ns)
```
### pull request
You can pull a request when you complete all steps above.
## TODO
- [x] Add JS code lint
- [x] Add changelog
- [x] Add JS unit test
- [x] Add JS unit test code covarage
- [x] Add C++ unit test
- [x] Add CI
- [x] Add performance test
- [x] Refactor node native addon part with NAPI
- [x] Add `index.js.d`
- [ ] Add global module supported to provide a cli tool
- [ ] Add donate entry
---
<p align="center">
twitter: <a href="https://twitter.com/imoncoding" alt="@imoncoding">@imoncoding</a>
</p>
<p align="center">
<img width="430" height="430" src="http://cdn-qiniu.algovis.fun/imnemo/qrcode_for_mp_oncoding.jpg" alt="qrcode_mp_oncoding">
</p>
<p align="center">Welcome to subscribe my wechat!</p>
[1]: http://modbus.org/specs.php
[2]: https://www.honeywellprocess.com/library/support/Public/Documents/51-52-25-66.pdf
[3]: http://modbus.org/docs/Modbus_over_serial_line_V1_02.pdf
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fimnemo%2Fcrc16?ref=badge_large)
<file_sep>#include <napi.h>
#include <string>
#include "./../lib/crc16.cc"
uint8_t *BufferData(Napi::Buffer<uint8_t> buf_val)
{
return (uint8_t *)buf_val.Data();
}
size_t BufferLength(Napi::Buffer<uint8_t> buf_val)
{
return buf_val.Length();
}
Napi::Value NODECRC16CheckSum(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (!info[0].IsBuffer())
{
Napi::TypeError::New(env, "Input stream requires a Buffer!").ThrowAsJavaScriptException();
return env.Null();
}
Napi::Buffer<uint8_t> stream = info[0].As<Napi::Buffer<uint8_t>>();
Napi::Object option;
if (info[1].IsNull() || info[1].IsEmpty() || !info[1].IsObject())
{
option = Napi::Object::New(env);
}
else
{
option = info[1].As<Napi::Object>();
}
uint8_t *bytes = BufferData(stream);
size_t len = BufferLength(stream);
if (len <= 0)
{
Napi::TypeError::New(env, "Stream buffer can't be empty!").ThrowAsJavaScriptException();
return env.Null();
}
std::string retType = "hex";
std::string retTypeKey = "retType";
if (option.Has(retTypeKey) && option.Get(retTypeKey).IsString())
{
retType = option.Get(retTypeKey).ToString();
}
if (retType == "array")
{
uint8_t sumArry[2];
CRC16CheckSum(bytes, len, sumArry);
Napi::Array sumForReturn = Napi::Array::New(env);
sumForReturn[0U] = sumArry[0];
sumForReturn[1] = sumArry[1];
return sumForReturn;
}
else if (retType == "buffer")
{
uint8_t sumArry[2];
CRC16CheckSum(bytes, len, sumArry);
Napi::Buffer<uint8_t> sumBufferForReturn = Napi::Buffer<uint8_t>::New(env, 2);
sumBufferForReturn.Data()[0U] = sumArry[0];
sumBufferForReturn.Data()[1] = sumArry[1];
return sumBufferForReturn;
}
else if (retType == "int")
{
uint16_t sum;
CRC16CheckSum(bytes, len, &sum);
return Napi::Number::New(env, sum);
}
else
{
char *sumStr = CRC16CheckSum(bytes, len);
return Napi::String::New(env, sumStr);
}
}
Napi::Boolean NODECRC16VerifySum(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (!info[0].IsBuffer())
{
Napi::TypeError::New(env, "Input stream requires a Buffer!").ThrowAsJavaScriptException();
return Napi::Boolean::New(env, false);
}
Napi::Buffer<uint8_t> stream = info[0].As<Napi::Buffer<uint8_t>>();
uint8_t *bytes = BufferData(stream);
size_t len = BufferLength(stream);
if (len <= 0)
{
Napi::TypeError::New(env, "Stream buffer can't be empty!").ThrowAsJavaScriptException();
return Napi::Boolean::New(env, false);
}
bool isValid = false;
isValid = CRC16VerifySum(bytes, len);
return Napi::Boolean::New(env, isValid);
}
Napi::Object Init(Napi::Env env, Napi::Object exports)
{
exports.Set(Napi::String::New(env, "checkSum"), Napi::Function::New(env, NODECRC16CheckSum));
exports.Set(Napi::String::New(env, "verifySum"), Napi::Function::New(env, NODECRC16VerifySum));
return exports;
}
NODE_API_MODULE(crc16, Init)
<file_sep>[](https://travis-ci.org/imnemo/crc16)
[](https://coveralls.io/github/imnemo/crc16?branch=master)
<a href="https://www.npmjs.com/package/node-crc16" alt="NPM latest version"><img src="https://img.shields.io/npm/v/node-crc16.svg"></a>
<a href="https://www.npmjs.com/package/node-crc16" alt="NPM total downloads"><img src="https://img.shields.io/npm/dt/node-crc16.svg"></a>
<a href="https://github.com/imnemo/crc16" alt="Github stars"><img src="https://img.shields.io/github/stars/imnemo/crc16.svg?style=social&label=Star"></a>
<a href="https://github.com/imnemo/crc16" alt="Github forks"><img src="https://img.shields.io/github/forks/imnemo/crc16.svg?style=social&label=Fork"></a>
<a href="https://npms.io/search?q=node-crc16" alt="NPM latest version"><img src="https://badges.npms.io/node-crc16.svg"></a>
<a href="https://npm.runkit.com/node-crc16"><img src="https://badge.runkitcdn.com/node-crc16.svg" alt="Try node-crc16 on RunKit"/></a>
<a href="https://deepscan.io/dashboard/#view=project&pid=1291&bid=3472"><img src="https://deepscan.io/api/projects/1291/branches/3472/badge/grade.svg" alt="DeepScan Grade"></a>
<a href="https://github.com/imnemo/crc16" alt="Github contributors"><img src="https://img.shields.io/github/contributors/imnemo/crc16.svg"></a>
<a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fimnemo%2Fcrc16?ref=badge_shield" alt="FOSSA Status"><img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimnemo%2Fcrc16.svg?type=shield"/></a>
# Node CRC16 - ([README in English](./README.md))
[MODBUS][1]是一种应用层消息通讯协议, 使得用各种不同类型的总线或网络连接的设备支持C/S通信,被广泛应用于嵌入式应用通讯开发。协议中通信数据包的“CRC循环冗余校验和”的生成与校验, 如[MODBUS串行线通信][2](第42页),[Modbus-RTU通信][3](第75页),都采用了同一种算法。
本模块实现了该算法的 _查表法_ C++代码实现, Node原生模块的封装, 以及NodeJS模块的封装。
*本模块有充分的单元测试和完善的使用文档。*
## 版本选择
如果你的`Node`版本小于`v8.x.x`,请使用本模块的`v1.x.x`版本,否则请使用`v2.x.x`。 在本模块`v2.x.x`中,引入了`NAPI`来实现原生模块,有更好的兼容性。
## 使用
温馨提示: 其实最好的方法使用说明, 在[源码](./index.js)的注释与[单元测试](./test)的代码里面 :)
### 安装
`npm install node-crc16`
### 生成校验和`crc16.checkSum`
`checkSum`接收三个参数,前两个参数 `(input, [encoding])` 其实是为了生成一个`Buffer`
```javascript
crc16.checkSum('一个utf8字符串', 'utf8')
```
`encoding`默认值为`hex`
```javascript
var sum = crc16.checkSum('a031ffb7');
sum.should.equal('726d');
```
第三个参数`option`,是对象类型。
+ `option.retType`,返回校验和的格式,取值:
* 默认值`hex`,2字节大端字节序hex编码,如`726d`
* `array`, 校验和单字节数组,如`[114, 109]`
* `int`,校验和16字节整型,如`29293`
* `buffer`,校验和以`Buffer`类型返回,如`<Buffer 72 6d>`
```javascript
var sum = crc16.checkSum('a031ffb7', {retType: 'array'});
sum.should.eql([114, 109]);
```
### 验证校验和`crc16.verifySum`
`verifySum`传参与`checkSum`一致,前两个参数都是为了生成一个`Buffer`,且`Buffer`包含校验和
```javascript
var stream = 'a031ffb7',
sum = '726d';
var isValid = crc16.verifySum(stream + sum);
isValid.should.equal(true);
```
## 贡献代码
### 获取源码
```sh
# fork 源码,然后克隆到本地
git clone <EMAIL>:imnemo/crc16.git
cd crc16
```
### 目录结构
```
├── lib //CRC16算法的C++实现
├── util //工具方法
├── src //Node原生模块的实现
├── test //JS单元测试代码
├── test_cpp //C++单元测试代码
├── index.js //Node模块入口文件
```
### 安装依赖
`npm install`
### C++单元测试
CRC16生成与校验算法的C++实现是独立的,如有修改该文件,完成后请编写相应的单元测试代码。
C++单元测试请参考的[Catch](https://github.com/philsquared/Catch),完成后请执行:
```bash
make test
```
保证全部测试用例通过。
### JS单元测试
`npm test` 或者 `./node_modules/.bin/mocha --reporter spec`
### 性能基准测试
#### 使用benchmark.js
```bash
>>> npm run benchmark
> node-crc16@1.0.0 benchmark /Users/nemo/code/imnemo/crc16
> node benchmark/benchmark.js
CEC16#checkSum x 905,071 ops/sec ±2.00% (83 runs sampled)
CRC16#verifySum x 1,540,940 ops/sec ±19.92% (65 runs sampled)
Fastest is CRC16#verifySum
```
#### 使用nanobench
```bash
>>> npm run nanobench
> node-crc16@1.0.0 nanobench /Users/nemo/code/imnemo/crc16
> node benchmark/nanobench.js
NANOBENCH version 2
> /Users/nemo/.nvm/versions/node/v8.1.2/bin/node benchmark/nanobench.js
# CRC16#checkSum 2,000,000 times
ok ~3.17 s (3 s + 166422442 ns)
# CRC16#verifySum 2,000,000 times
ok ~2.85 s (2 s + 848059820 ns)
all benchmarks completed
ok ~6.01 s (6 s + 14482262 ns)
```
### 提交
所有单元测试通过后,您就可以Pull一个Request了 :)
## TODO
- [x] 增加JS代码lint
- [x] 增加变更日志
- [x] 增加JS代码单元测试
- [x] 增加JS代码测试覆盖率
- [x] 增加C++代码单元测试
- [x] 增加持续集成
- [x] 增加性能测试
- [x] 用NAPI重构Node原生模块部分
- [x] 添加 `index.js.d` 文件
- [ ] 支持全局模块,提供CLI
- [ ] 增加打赏入口
---
<p align="center">
twitter: <a href="https://twitter.com/imoncoding" alt="@imoncoding">@imoncoding</a>
</p>
<p align="center">
<img width="430" height="430" src="http://cdn-qiniu.algovis.fun/imnemo/qrcode_for_mp_oncoding.jpg" alt="qrcode_mp_oncoding">
</p>
<p align="center">一个追求专业、规范、极简, 关注技术本质,笃信万物相通的公众号!</p>
[1]: http://modbus.org/specs.php
[2]: https://www.honeywellprocess.com/library/support/Public/Documents/51-52-25-66.pdf
[3]: http://modbus.org/docs/Modbus_over_serial_line_V1_02.pdf
<file_sep>var bufferFactory = require('buffer-factory');
// eslint-disable-next-line import/no-unresolved
var crc16Native = require('./build/Release/crc16.node');
var parseParam = function (input, encoding, option) {
encoding = encoding || 'hex';
if (typeof encoding === 'object') {
option = encoding;
encoding = 'hex';
}
option = option || {};
var buf = (function () {
if (typeof input === 'string') {
try {
input = bufferFactory.create(input, encoding);
} catch (e) {
console.trace(e);
return null;
}
}
if (Buffer.isBuffer(input) && input.length > 0 && input.byteLength > 0) {
return input;
}
return null;
}());
if (buf === null) {
throw new TypeError(`crc16.${arguments.callee.caller.name} input param invalid!`);
}
return { buf, option };
};
var crc16 = {
/**
* checkSum
* @param input string | buffer
* @param encoding string 'hex' default
* @param option object
* @example checkSum('301a', 'hex')
* @example checkSum('301a')
* @example checkSum(Buffer.from('301a', 'hex'))
* @example checkSum('301a', {retType: 'int'}) default retType is hex
* @return
* hex string when option.retType == 'hex'
* array when option.retType == 'array'
* unsigned short int when option.retType == 'int'
* Buffer when option.retType == 'buffer'
*/
checkSum(input, encoding, option) {
var param = parseParam(input, encoding, option);
var sum = crc16Native.checkSum(param.buf, param.option);
return sum;
},
/**
* verifySum
* @param input string | buffer
* @param encoding string 'hex' default
* @param option object
* @example verifySum('301a947b', 'hex')
* @example verifySum('301a947b')
* @example checkSum(Buffer.from('301a947b', 'hex'))
* @return return bool true | false
*/
verifySum(input, encoding, option) {
var param = parseParam(input, encoding, option);
return crc16Native.verifySum(param.buf, param.option);
},
};
module.exports = crc16;
<file_sep>var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var crc16 = require('../index');
var util = require('./../util/util');
var stream = '3a16070a00000000001a0000';
var streamBuf = util.bufferFactory(stream, 'hex');
var sumShouldStr = '98af';
var streamWithSumBuf = util.bufferFactory(stream + sumShouldStr, 'hex');
suite
.add('CEC16#checkSum', function() {
crc16.checkSum(streamBuf);
})
.add('CRC16#verifySum', function(){
crc16.verifySum(streamWithSumBuf);
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });
<file_sep>{
"targets": [{
"target_name": "crc16",
"sources": ["./src/crc16_node.cc"],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}]
, "cflags": ["-Wall", "-O3", "-std=c++11", "-fno-exceptions"]
, "cflags_cc": ["-Wall", "-O3", "-std=c++11", "-fno-exceptions"]
, "xcode_settings": {
'OTHER_CFLAGS': ['-std=c++11'],
}
, "msvs_settings": {
'VCCLCompilerTool': {
'ExceptionHandling': 1 # /EHsc
}
}
, 'configurations': {
'Release': {
'msvs_settings': {
'VCCLCompilerTool': {
'ExceptionHandling': 1,
}
}
}
}
, "conditions": [[
'OS=="mac"', {
"xcode_settings": {
'MACOSX_DEPLOYMENT_TARGET': '10.5'
}
}
]]
}
<file_sep>/**
* For simplicity, there is no params validation check,
* becuase this util function is only used here .
* Also, I suppose that versionA and versionB are valid semver string .
*/
function isLargerOrEqual(versionA, versionB) {
if (versionA === versionB)
return true;
var ver1 = versionA.substr(1).split('.');
var ver2 = versionB.substr(1).split('.');
var len = ver1.length;
for (var i = 0; i < len; i++) {
var v1 = parseInt(ver1[i]);
var v2 = parseInt(ver2[i]);
if (v1 > v2)
return true;
if (v1 < v2)
return false;
}
}
if (!isLargerOrEqual(process.version, 'v8.0.0')) {
console.error('\033[1;31m' + `
now your node version is lower than v8.0.0,
please use node-crc16@1.x.x instead.
`
);
process.exit(1);
} else {
process.exit(0);
}<file_sep>var bench = require('nanobench');
var crc16 = require('../index');
var util = require('./../util/util');
var stream = '3a16070a00000000001a0000';
var streamBuf = util.bufferFactory(stream, 'hex');
var sumShouldStr = '98af';
var streamWithSumBuf = util.bufferFactory(stream + sumShouldStr, 'hex');
var times = 2 * 1000 * 1000;
bench('CRC16#checkSum 2,000,000 times', function (b) {
b.start()
for (var i = 0; i < times; i++) {
crc16.checkSum(streamBuf);
}
b.end()
})
bench('CRC16#verifySum 2,000,000 times', function (b) {
b.start()
for (var i = 0; i < times; i++) {
crc16.verifySum(streamWithSumBuf);
}
b.end()
})
<file_sep>var should = require('chai').should();
var bufferFactory = require('buffer-factory');
var crc16 = require('../index');
var stream = '3a16070a00000000001a0000';
var sumShouldStr = '98af';
var sumShouldBuf = bufferFactory(sumShouldStr, 'hex');
var sumShouldInt = sumShouldBuf.readUInt16BE();
var sumShouldArry = [152, 175];
describe('Syntax to call the apis', () => {
describe('CheckSum', () => {
// exception
it('Should throw an exception when input stream is null', () => {
(function () {
crc16.checkSum(null);
}).should.throw();
});
it('Should throw an exception when input stream is invalid', () => {
(function () {
crc16.checkSum('qweewq', 'hex');
}).should.throw();
});
// params about input
it('Stream input should be a hex string and return a string sum by default', () => {
var sum = crc16.checkSum(stream);
sum.should.equal(sumShouldStr);
});
it('Stream input with encoding', () => {
var sum = crc16.checkSum(stream, 'hex');
sum.should.equal(sumShouldStr);
});
it('Stream input can be a buffer', () => {
var sum = crc16.checkSum(bufferFactory(stream, 'hex'));
sum.should.equal(sumShouldStr);
});
// params about output
it('Returned sum can be an unsigned short int', () => {
var sum = crc16.checkSum(stream, { retType: 'int' });
sum.should.eql(sumShouldInt);
});
it('Returned sum can be a buffer', () => {
var sum = crc16.checkSum(stream, { retType: 'buffer' });
Buffer.isBuffer(sum).should.equal(true);
sum.compare(sumShouldBuf).should.eql(0);
});
it('Returned sum can be a decimal numbers array', () => {
var sum = crc16.checkSum(stream, { retType: 'array' });
sum.should.eql(sumShouldArry);
});
it('Returned sum should be a hex string when option.retType is anything else string', () => {
var sum = crc16.checkSum(stream, { retType: 'anything else' });
sum.should.eql(sumShouldStr);
});
it('Returned sum should be a hex string when option.retType is not a string', () => {
var sum = crc16.checkSum(stream, { retType: { foo: 'bar' } });
sum.should.eql(sumShouldStr);
});
});
describe('verifySum', () => {
it('Should throw an exception when input stream is null', () => {
(function () {
crc16.verifySum(null);
}).should.throw();
});
it('Should throw an exception when input stream is invalid', () => {
(function () {
crc16.verifySum('qweewq', 'hex');
}).should.throw();
});
it('Stream input should be a hex string by default', () => {
var isValid = crc16.verifySum(stream + sumShouldStr);
isValid.should.equal(true);
});
it('Stream input with encoding', () => {
var isValid = crc16.verifySum(stream + sumShouldStr, 'hex');
isValid.should.equal(true);
});
it('Stream input can be a buffer', () => {
var isValid = crc16.verifySum(bufferFactory(stream + sumShouldStr, 'hex'));
isValid.should.equal(true);
});
it('Should return false when the sum is not matched the stream input', () => {
var isValid = crc16.verifySum(`${stream}7878`);
isValid.should.equal(false);
});
});
});
<file_sep>type RetType = 'hex' | 'array' | 'int' | 'buffer';
type CheckSumOption = {
retType?: RetType
} & {
(key?: string): any
};
// export function checkSum(input: string, encoding?: string | CheckSumOption, option?: CheckSumOption): string | number | [] | Buffer;
export function checkSum(input: string, option: {retType: 'hex'}): string;
export function checkSum(input: string, option: {retType: 'array'}): [];
export function checkSum(input: string, option: {retType: 'int'}): number;
export function checkSum(input: string, option: {retType: 'buffer'}): Buffer;
export function checkSum(input: string, option?: {retType: any}): string;
export function checkSum(input: string, encoding: BufferEncoding, option: {retType: 'hex'}): string;
export function checkSum(input: string, encoding: BufferEncoding, option: {retType: 'array'}): [];
export function checkSum(input: string, encoding: BufferEncoding, option: {retType: 'int'}): number;
export function checkSum(input: string, encoding: BufferEncoding, option: {retType: 'buffer'}): Buffer;
export function checkSum(input: string, encoding: BufferEncoding, option?: {retType: any}): string;
export function checkSum(input: Buffer, option: {retType: 'hex'}): string;
export function checkSum(input: Buffer, option: {retType: 'array'}): [];
export function checkSum(input: Buffer, option: {retType: 'int'}): number;
export function checkSum(input: Buffer, option: {retType: 'buffer'}): Buffer;
export function checkSum(input: Buffer, option?: {retType: any}): string;
export function verifySum(input: string, encoding?: string): boolean;
export function verifySum(input: Buffer): boolean;
<file_sep>var crc16 = require('node-crc16');
var stream = '3a16070a00000000001a0000';
var sumShouldStr = '98af';
//check sum
var sum = crc16.checkSum(stream);
console.log('check stream ' + stream + ', result: ' + sum);
//verify sum
var isValid = crc16.verifySum(stream + sumShouldStr);
console.log('verify sum result: ' + isValid);
<file_sep><% if(logo) { %><img width="300px" src="<%= logo %>" /><%= '\n\n' %><% } %># <%= title %>
<% if(intro) { %><%= '\n' %>_<%= intro %>_<%= '\n' %><% } %>
<% if(version && (version.name || version.number)) { %>##<% if(version.name){%> <%= version.name %><% } %> <%= version.number %> <% if(version.date){ %>( <%= version.date %> )<% } %><%= '\n' %><% } %>
<% _.forEach(sections, function(section){
if(section.commitsCount > 0) { %>
## <%= section.title %>
<% _.forEach(section.commits, function(commit){ %> - <%= printCommit(commit, true) %><% }) %>
<% _.forEach(section.components, function(component){ %> - **<%= component.name %>**
<% _.forEach(component.commits, function(commit){ %> - <%= printCommit(commit, true) %><% }) %>
<% }) %>
<% } %>
<% }) %>
---
<sub><sup>*Generated with [git-changelog](https://github.com/rafinskipg/git-changelog). If you have any problems or suggestions, create an issue.* :) **Thanks** </sub></sup>
<file_sep>/**
* @author imnemo
* @email <EMAIL>
* @create date 2017-04-10 10:20:19
* @modify date 2017-07-25 04:52:22
*/
#include <stdint.h>
#include <iostream>
static uint8_t const CRCHighTbl[256] = {
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40};
static uint8_t const CRCLowTbl[256] = {
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40};
/**
* place where magic truely works
**/
void checkSum(uint8_t *pDataIn, size_t len, uint8_t *sumHigh, uint8_t *sumLow)
{
uint8_t tableIndex = 0;
//采用len控制for循环结束,更灵活
//这样可以对input的一部分做计算
size_t i = 0;
if ((0 != len) && (NULL != pDataIn))
{
for (i = len; i > 0; i--)
{
tableIndex = *sumHigh ^ (*pDataIn++);
*sumHigh = *sumLow ^ CRCHighTbl[tableIndex];
*sumLow = CRCLowTbl[tableIndex];
}
}
}
/**
* check crc16 sum by table look-up
* @param [point] *pDataIn data to be checked
* @param [int] len data length
* @return [char*] result sum, hex code string
**/
char *CRC16CheckSum(uint8_t *pDataIn, size_t len)
{
uint8_t sumHigh = 0xFF;
uint8_t sumLow = 0xFF;
checkSum(pDataIn, len, &sumHigh, &sumLow);
char *sum = new char[5];
sprintf(sum, "%02x%02x", sumHigh, sumLow);
return sum;
}
/**
* check crc16 sum by table look-up
* @param [unsigned char*] *pDataIn data to be checked
* @param [int] len data length
* @param [unsigned char* array] sum result, BigEndian
* @return void
**/
void CRC16CheckSum(uint8_t *pDataIn, size_t len, uint8_t *sum)
{
uint8_t sumHigh = 0xFF;
uint8_t sumLow = 0xFF;
checkSum(pDataIn, len, &sumHigh, &sumLow);
*sum++ = sumHigh;
*sum = sumLow;
}
/**
* check crc16 sum by table look-up
* @param [unsigned char*] *pDataIn data to be checked
* @param [int] len data length
* @param [unsigned short* number] sum result
* @return void
**/
void CRC16CheckSum(uint8_t *pDataIn, size_t len, uint16_t *sum)
{
uint8_t sumHigh = 0xFF;
uint8_t sumLow = 0xFF;
checkSum(pDataIn, len, &sumHigh, &sumLow);
*sum = (sumHigh << 8 | sumLow);
}
/**
* verify crc16 sum by table look-up
* @param [unsigned char*] *pDataIn data to be checked
* @param [int] len data length
* @return bool
**/
bool CRC16VerifySum(uint8_t *pDataIn, size_t len)
{
uint8_t tableIndex = 0;
uint8_t sumHigh = 0xFF;
uint8_t sumLow = 0xFF;
if ((0 == len) || (NULL == pDataIn))
{
return false;
}
size_t i = 0;
for (i = len; i > 0; i--)
{
tableIndex = sumHigh ^ (*pDataIn++);
sumHigh = sumLow ^ CRCHighTbl[tableIndex];
sumLow = CRCLowTbl[tableIndex];
}
if ((sumHigh | sumLow) != 0)
{
return false;
}
return true;
}
| f148330c89012bee33be6219e9f8f67b125b1b56 | [
"Markdown",
"JavaScript",
"Makefile",
"Python",
"TypeScript",
"C++"
] | 16 | C++ | imnemo/crc16 | 7985dbcbfd71a87a25bd127aebed5952be88092d | 2cabc997c80203f3d31da0f46cc6a13d11de02bd |
refs/heads/master | <file_sep>#!/usr/bin/python
import socket
import time
import sys
# if false disable debug lines
debug = False
if len(sys.argv) >= 2 and sys.argv[1] == "debug":
print "entering debug mode."
debug = True
# method to get current time in millisecond
current_milli_time = lambda: int(round(time.time() * 1000))
while True:
host = raw_input("Please enter host ip or exit to exit.\n")
print "you entered", host
if host == "exit":
exit(0)
# connect to server
s = socket.socket()
port = 8000
# get current time
t1 = current_milli_time()
if debug:
print "t1 is", t1
# connect and send message to server
s.settimeout(10)
try:
s.connect((host, port))
s.settimeout(None)
s.send("All human beings are in truth akin")
s.recv(1024)
except socket.timeout:
print "timeout exception.\ncan't find route to host."
# get current time
t2 = current_milli_time()
if debug:
print "t2 is", t2
# show delay time
print "delay is: ", t2 - t1
s.close()
# to test multi thread
if debug:
time.sleep(1)
<file_sep>Run client with : python client.py debug to show debug log
Run server with : python server.py debug to show debug log
<file_sep>#!/usr/bin/python
import socket
import threading
import sys
from time import sleep
# if false disable debug lines
debug = False
if len(sys.argv) >= 2 and sys.argv[1] == "debug":
print "entering debug mode."
debug = True
# set up server
s = socket.socket()
host = '0.0.0.0'
port = 8000
s.bind((host, port))
s.listen(5) # up to 5 concurrent connections
def secretary():
c, addr = s.accept() # Establish connection with client.
if debug:
print 'Got connection from', addr
while True:
print c.recv(1024)
# c.send('Bah Bah')
#c.close()
return
# threads = []
def parse_of_header( s ):
if len(s) < 8:
return 8
length = (ord(s[3]) + ord(s[2])*2**8)
if debug:
print ( "version: %s" % ord(s[0]) )
print ( "type: %s" % ord(s[1]) )
print ( "length: %s" % length )
print ( "xid: %s" % (ord(s[7]) + ord(s[6])*2**8 + ord(s[5])*2**16 + ord(s[4])*2**24 ))
return length
def read_of_header(c):
cur = c.recv(8)
return parse_of_header(cur) - 8, cur
def feature_req():
return "%s%s%s%s%s%s%s%s"%(chr(1),chr(5),chr(0),chr(8),chr(0),chr(0),chr(1),chr(240))
def connect_to_floodlight():
s = socket.socket()
port = 6653
host = '127.0.0.1'
s.connect((host, port))
return s
while True:
#t = threading.Thread(target=secretary)
#threads.append(t)
#t.start()
c, addr = s.accept() # Establish connection with client.
if debug:
print 'Got connection from', addr
#sleep(5)
payload_size , cur = read_of_header(c)
print ( "start floodlight part.")
f = connect_to_floodlight()
f.send(cur)
payload_size , cur = read_of_header(f)
c.send(cur)
print ( "done floodlight part.")
payload_size , cur = read_of_header(f)
c.send(feature_req())
payload_size , cur = read_of_header(c)
c.recv(payload_size)
for i in range(0,4):
payload_size , cur = read_of_header(c)
c.recv(payload_size)
| 4dc6bcd2d6d2804977cac8abf1e8d7e5ddf74686 | [
"Markdown",
"Python"
] | 3 | Python | soreana/bastar-gostar-py | cc4af6d753c9f50d59376a637076073410f68f72 | a2231872e21f94f1b9e98ce8d5597eced979e3b1 |
refs/heads/master | <repo_name>RobBlanchard/SortingVisualizer<file_sep>/sorting-visualizer/src/SortingVisualizer/Rectangle.jsx
import React from 'react';
export default class Rectangle extends React.Component{
render() {
var styleChild = {
position : "absolute",
backgroundColor : this.props.color,
width : "100%",
height : this.props.height.toString()+"%",
top : (100-this.props.height).toString()+"%",
};
var styleParent = {
position: "relative",
width : this.props.width.toString()+"%",
height : "100%",
marginLeft: this.props.array_size<100 ? "1px" : "0px",
marginRight: this.props.array_size<100 ? "1px" : "0px"
};
return (
<div className="rectangle" style={styleParent}>
<div style={styleChild}>
{this.props.value}
</div>
</div>
)
}
}<file_sep>/sorting-visualizer/src/SortingVisualizer/MergeSort.js
export function merge_sort(arr, start, end, animations){
if (end <= start){
return arr;
} else {
var p = Math.floor((start+end)/2) + 1*((start+end)%2!=0);
merge_sort(arr, start, p-1, animations);
merge_sort(arr, p, end, animations);
_merge_lists(arr, start, end, p, animations);
}
return arr;
}
function _merge_lists(arr, start, end, p, animations){
var i = start;
var j = p;
var tmp;
while (i<j && j<=end){
if (arr[j]<arr[i]){
animations.push([i,j,1]);
tmp = arr[j];
arr.splice(j, 1);
arr.splice(i, 0, tmp);
i++
j++;
} else {
animations.push([i,j,0]);
i++;
}
}
}<file_sep>/python/lib/merge_sort.py
def merge_sort(L):
n=len(L)
if n<2:
return L
else:
p=n//2
return merge_lists(merge_sort(L[:p]), merge_sort(L[p:]))
def merge_lists(K,L):
R=[]
while len(K)>0 and len(L)>0:
if K[0]<L[0]:
R.append(K.pop(0))
else:
R.append(L.pop(0))
if len(K)==0:
R.extend(L)
else:
R.extend(K)
return R<file_sep>/README.md
# Sorting Visualizer
## Demo
You can find a demo of my visualizer here : https://robblanchard.github.io/SortingVisualizer/
## Objectives
This repository has two objectives:
* First, implement various sorting algorithms in Python and create an executable (this part of the project has been dropped).
* Second, create a sorting visualizer in ReactJS
This project has been started to implement my own version from scratch of **Clément Mihailescu**'s Sorting Visualizer which you can find here: https://github.com/clementmihailescu/Sorting-Visualizer.
I made this project to get my hands on React programming.
### TO DO
Python :
- [ ] Optimize sorting algorithms
- [ ] Create an exectutable
React :
- [x] Deploy GitHub page
- [x] Merge Sort
- [X] Lomuto Quick Sort
- [X] Customizable array sizes and sorting speed
- [ ] History feature : go back in time
- [ ] More sorting algorithms
- [ ] Swapping animation (FLIP) <file_sep>/sorting-visualizer/src/SortingVisualizer/QuickSortLomuto.js
export function quick_sort_lomuto(arr, start, end, animations){
if (start<end){
var p;
[p, arr] = _partition(arr, start, end, animations);
arr = quick_sort_lomuto(arr, start, p-1, animations);
arr = quick_sort_lomuto(arr, p+1, end, animations);
return arr
} else {
return arr;
}
}
function _partition(arr, start, end, animations){
var p = end;
var p_val = arr[p];
var i = start;
for (var j=start; j<end; j++){
if (arr[j]<p_val){
arr = _swap_values(arr,i,j);
animations.push([p, i, j, 1]);
i++;
} else {
animations.push([p, i, j, 0]);
}
}
if (arr[i]!=arr[end]){
arr = _swap_values(arr,i, end);
animations.push([p, i, end, 1]);
} else {
animations.push([p, i, end, 0]);
}
return [i,arr];
}
function _swap_values(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr
}<file_sep>/python/lib/bubble_sort.py
def bubble_sort(L):
n = len(L)
for k in range(n-1,-1, -1):
is_sorted = True
for i in range(k):
if L[i]>L[i+1]:
is_sorted=False
L[i],L[i+1] = L[i+1],L[i]
if is_sorted:
break
return L
<file_sep>/python/lib/insertion_sort.py
def insertion_sort(L):
for i, fixed_elt in enumerate(L):
min_value = fixed_elt
min_idx = i
for j, moving_elt in enumerate(L[i+1:]):
if moving_elt < min_value:
min_value = moving_elt
min_idx = i+1+j
if min_idx!=i:
L[i],L[min_idx] = L[min_idx],L[i]
return L
<file_sep>/python/lib/quick_sort.py
def quick_sort(L):
n=len(L)
if n<2:
return L
else:
p = L[n//2]
inf = [x for x in L if x<p]
eq = [x for x in L if x==p]
sup = [x for x in L if x>p]
return quick_sort(inf)+eq+quick_sort(sup)<file_sep>/sorting-visualizer/src/SortingVisualizer/InsertionSort.js
export function get_animations_insertion_sort(arr){
var animations=[];
for (var i=0; i<arr.length; i++){
var fixed_val = arr[i];
var min_val = fixed_val;
var min_idx = i;
for (var j=i+1; j<=arr.length; j++){
var moving_val = arr[j];
if (moving_val < min_val){
min_val = moving_val;
min_idx = j;
animations.push([i, min_idx, j, 0]);
} else {
animations.push([i, min_idx, j, 0]);
}
}
arr = _swap_values(arr, i , min_idx);
animations.push([i, min_idx, min_idx, 1]);
}
return animations;
}
function _swap_values(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr
}<file_sep>/sorting-visualizer/src/SortingVisualizer/BubbleSort.js
export function get_animations_bubble_sort(arr){
var animations=[];
for (var k=arr.length-1; k>=0; k--){
var is_sorted=true;
for (var i=0; i<k; i++){
if (arr[i]>arr[i+1]){
is_sorted=false;
_swap_values(arr, i, i+1);
animations.push([i,i+1,1])
} else {animations.push([i,i+1,0])}
}
if (is_sorted){break;}
}
return animations;
}
function _swap_values(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr
}<file_sep>/python/test/test_sorts.py
import pytest
import random
from lib.insertion_sort import insertion_sort
from lib.quick_sort import quick_sort
from lib.merge_sort import merge_sort
from lib.bubble_sort import bubble_sort
random.seed(30)
testdata = [[random.randint(-1000,1000) for i in range(1000)] for i in range(10)]
testdata += [[random.randint(-1000,1000)/1000 for i in range(1000)] for i in range(10)]
@pytest.mark.parametrize("L",testdata)
def test__insertion_sort(L):
assert insertion_sort(L)==sorted(L)
@pytest.mark.parametrize("L",testdata)
def test__quick_sort(L):
assert quick_sort(L)==sorted(L)
@pytest.mark.parametrize("L",testdata)
def test__merge_sort(L):
assert merge_sort(L)==sorted(L)
@pytest.mark.parametrize("L",testdata)
def test__bubble_sort(L):
assert bubble_sort(L)==sorted(L)<file_sep>/sorting-visualizer/src/SortingVisualizer/QuickSortHoare.js
export function quick_sort_hoare(arr, start, end, animations){
if (_unique_number(arr,start,end)){
return [arr, animations];
} else {
var p;
[arr, p] = _quick_sort_partition(arr, start, end, animations);
quick_sort_hoare(arr, start, p, animations);
quick_sort_hoare(arr, p+1, end, animations);
return [arr, animations];
}
}
function _quick_sort_partition(arr, start, end, animations){
var p = Math.floor((start+end)/2)
var p_val = arr[p];
var i = start;
var j = end;
while (true){
while (arr[i]<p_val){
animations.push([p, i, j, 0]);
i++;
}
while (arr[j]>p_val){
animations.push([p, i, j, 0]);
j--;
}
if (i>=j){
return [arr, j];
}
arr = _swap_values(arr,i,j);
//in case p was changed
if (p==j){p=i;} else if(p==i){p=j;}
animations.push([p, i, j, 1]);
i++;
j--;
}
}
function _swap_values(arr, i, j){
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
return arr
}
function _unique_number(arr, start, end){
if (start==end) {return true;}
else {
var a = arr[start]
for (var i=1;i<=end;i++){
if (arr[i]!=a){
return false;
}
}
return true;
}
} | 3157093eb8e104149660cee8376b967b52e37783 | [
"JavaScript",
"Python",
"Markdown"
] | 12 | JavaScript | RobBlanchard/SortingVisualizer | a626daad67d6c87e9530221673e3fe3d447fde3b | 0ffa39e1fc4312ad6918a61fb0cc325bde0bbbc5 |
refs/heads/master | <file_sep>#Blur, dilation, and erosion
import numpy as np
import cv2
image = cv2.imread("thresh.jpg")
cv2.imshow("Original",image)
#Gaussian Blur (blurs image)
blur = cv2.GaussianBlur(image, (5,55), 0) #blur 5 of x axis and 55 on y axis
cv2.imshow("Blur",blur)
#Moves around the pixels
kernel = np.ones((5,5), 'uint8')
#Dilate the image (turns black pixels/background to white)
dilate = cv2.dilate(image,kernel,iterations=1)
#Erode the image (turns white pixels/foreground to black)
erode = cv2.erode(image,kernel,iterations=1)
cv2.imshow("Dilate",dilate)
cv2.imshow("Erode",erode)
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>#Displaying images from pixel values
import numpy as np
import cv2
black = np.zeros([150, 250, 1], 'uint8') #150px tall 200px wide, 1 channel, 0-255 range (2^8)
cv2.imshow("Black", black)
print(black[0,0,:])
ones = np.ones([150,200,3], 'uint8')
cv2.imshow("Ones", ones)
print(ones[0,0,:])
white = np.ones([150,200,3], 'uint16')
white *= (2**16-1)
cv2.imshow("White",white)
print(white[0,0,:])
color = ones.copy()
color[:,:] = (255,0,0)
cv2.imshow("Blue", color)
print(color[0,0,:])
cv2.waitKey(0)
cv2.destroyAllWindows()
| 8a9e3c0ccf85e5051d020076dc08193549b8de72 | [
"Python"
] | 2 | Python | vanessaland/image-processing-exercises | 63a677338d94d1f396270fa30787b50f46dd0fa4 | 76561ee84af2ede0f5a76e0704616a4abe31867d |
refs/heads/master | <repo_name>santilobato/hello_world<file_sep>/chat.php
<html>
<head>
<title>ChatTerra</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1><center><font color="891E1E">Meeting</font></center></h1>
<hr>
<br>
<center><font size=+1>
<table cellpadding="10" bgcolor="B9D3EE">
<form action="calcula.php" method="post">
<tr>
<td>Mensaje:<input type="text" name="numA" placeholder="..." value"<?php echo $a;?>/></td>
</tr>
</table>
<p> <input type="submit" value="+" name="mas"/>
<input type="submit" value="-" name="menos"/>
<input type="submit" value="*" name="multi"/>
<input type="submit" value="/" name="divi"/>
<input type="submit" value="%" name="porce"/></p>
</form>
</body>
</html>
<?php
$a = $_POST['numA'];
$b = $_POST['numB'];
if($_POST['mas']) {
$simb = "+";
$resultado = $a + $b;
echo "$a"."$simb"."$b"."="."$resultado" ;
if($resultado>0){
for($i=0;$i<$resultado;$i++){
echo " *";
}
}
else if($resultado<0){
for($i=0;$i>$resultado;$i--){
echo "<font color='#E21010'> *</font>";
}
}
}
| 79e815b5bd96d46df9f14e226e9af5f696e1e261 | [
"PHP"
] | 1 | PHP | santilobato/hello_world | 71c1182869f117bc1a3e116ba6cad7197ea2c776 | 60dc1f2011ab0e61ad8e46f166bfdcd111012992 |
refs/heads/master | <repo_name>mtalham/react-web-component<file_sep>/concatBuiltJs.js
#!/usr/bin/env node
const { readFile } = require("fs").promises;
const concat = require("concat");
(async function build() {
try {
const assetManifestPath = "./build/asset-manifest.json";
const { entrypoints } = JSON.parse(
await readFile(assetManifestPath, "utf8")
);
const filePaths = entrypoints
.filter((path) => /\.js$/.test(path))
.map((path) => `./build/${path}`);
const outFile = "./build/main.js";
await concat(filePaths, outFile);
console.log(
`Concatinated the following files into ${outFile}\n\n${filePaths.join("\n")}`
);
} catch (error) {
console.error(error);
}
})();
<file_sep>/src/App.js
import React from 'react';
import PropTypes from 'prop-types';
import {List, ListItem, ListItemText, makeStyles, Paper, Divider} from "@material-ui/core";
const fallbackData = ['name1', 'name2', 'name3', 'name4', 'name5'];
const useStyles = makeStyles((theme) => ({
container: {
paddingTop: "1.5rem",
},
}));
export default function App({data}) {
const input = data ? data : fallbackData;
const {container} = useStyles();
return (
<div className={container}>
<Paper elevation={3}>
<List>
{input.map((name, index) =>
(<div key={index}>
<ListItem>
<ListItemText primary={name} />
</ListItem>
{index !== (input.length - 1) && (<Divider/>)}
</div>)
)}
</List>
</Paper>
</div>
)
}
App.propTypes = {
data: PropTypes.arrayOf(PropTypes.string).isRequired
}
<file_sep>/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import reactToWebComponent from "react-to-webcomponent";
import App from "./App";
const app = reactToWebComponent(App, React, ReactDOM);
customElements.define("app-webcomponent", app);
| 29d07ade89e7aa502c131d9cf19cf3a7f4163490 | [
"JavaScript"
] | 3 | JavaScript | mtalham/react-web-component | f44aa1f889c228703f678dbe2cec44caf1e61694 | e6e1231011f5c6663af39585730521e1acd73a25 |
refs/heads/master | <file_sep>/**
****************************************************************************************
*
* @file app_sys.h
*
* @brief Application System Functioins
*
* Copyright(C) 2015 NXP Semiconductors N.V.
* All rights reserved.
*
* $Rev: 1.0 $
*
****************************************************************************************
*/
#ifndef _APP_SYS_H_
#define _APP_SYS_H_
/*
* INCLUDE FILES
****************************************************************************************
*/
#if (QN_DEMO_MENU || QN_EACI)
#if (QN_DEMO_MENU)
#define QN_UART_RX_LEN 0x10
/// Application UART environment context structure
struct app_uart_env_tag
{
uint8_t len;
uint8_t buf_rx[QN_UART_RX_LEN];
};
#endif
/// Message of UART data request send to application
struct app_uart_data_req
{
uint8_t len;
uint8_t data[1];
};
/// Application handle message of UART received data
struct app_uart_data_ind
{
uint8_t len;
uint8_t data[1];
};
#endif
#if QN_DBG_PRINT
/*
****************************************************************************************
* @brief Uart initialization.
*
****************************************************************************************
*/
void app_uart_init(void);
#endif
#define DATA_BUF_LEN 1000
struct app_pass_env_tag
{
uint8_t head;
uint8_t len_H;
uint8_t len_L;
uint8_t uart_flag;
uint16_t length; //uart rx left data
uint16_t length_backup; //ble tx left data
uint16_t ble_tx_pack_max;
uint16_t ble_tx_pack_ct;
uint8_t *p_uart_rx; // uart rx data pointer
uint8_t *p_ble_send; // ble tx data pointer
uint8_t buf_rx[DATA_BUF_LEN];
};
#endif // _APP_SYS_H_
<file_sep>
#include "app_pt.h"
#include "uart.h"
#include "timer.h"
#include "lib.h"
struct pt_env_tag pt_env;
struct PT_FIFO pt_data_fifo; //data fifo
void pt_rx_raw_done(void);
uint8_t pt_fifo_get(uint8_t *pBuf);
uint8_t pt_fifo_put(uint8_t *pPutDat, uint8_t PutLen);
void pt_fifo_init(void);
void ble_data_tx(void);
void pt_init(void);
void pt_rx_raw_frame_hdl(void);
void pt_enable(void);
void pt_disable(void);
void pt_init()
{
if(KE_EVENT_OK != ke_evt_callback_set(PT_RX_RAW_FRAME_EVENT_ID,
pt_rx_raw_frame_hdl))
ASSERT_ERR(0);
}
void pt_enable(void)
{
pt_rx_raw_start();
}
void pt_disable(void)
{
uart_rx_int_enable(QN_UART0, MASK_DISABLE);
}
uint32_t timer3_CT = 0;
void timer3_callback(void)
{
timer3_CT++;
//receive one frame data,disable uart and timer.
// uart_rx_int_enable(QN_UART0, MASK_DISABLE);
timer_enable(QN_TIMER3, MASK_DISABLE);
timer_timer_ClrIntFlag(QN_TIMER3, TIMER_MASK_TOVF|TIMER_MASK_OCF|TIMER_MASK_ICF);
if(pt_data_fifo.elemt[pt_data_fifo.in].len)
{
pt_data_fifo.in++; //in this place should pt_data_fifo.in >= pt_data_fifo.out
if(pt_data_fifo.in >= PT_FIFO_X_SIZE)
{
pt_data_fifo.in = 0;
}
if(pt_data_fifo.in == pt_data_fifo.out)
{
pt_data_fifo.full_ct++;
pt_data_fifo.state = PT_FIFO_FULL;
}
else
{
pt_data_fifo.state = PT_FIFO_NOFU;
}
pt_data_fifo.elemt[pt_data_fifo.in].len = 0;
if((pt_env.ble_tx_state != BLE_TX_GOING)&&(pt_data_fifo.state != PT_FIFO_EMPT))
{
ke_evt_set(1UL << PT_RX_RAW_FRAME_EVENT_ID); //don't send ble data in uart interrupt, set an env to kernel
pt_env.ble_tx_state = BLE_TX_GOING;
}
}
if(pt_env.uart_rx_state != UART_RX_STOP)
uart_read(PT_UART_PORT, pt_data_fifo.elemt[pt_data_fifo.in].buf+pt_data_fifo.elemt[pt_data_fifo.in].len, 1, pt_rx_raw_done);
}
void pt_fifo_init(void)
{
pt_data_fifo.elemt[0].len = 0;
pt_data_fifo.in = 0;
pt_data_fifo.out = 0;
pt_data_fifo.state = PT_FIFO_EMPT;
}
void pt_rx_raw_start(void)
{
pt_fifo_init();
pt_env.ble_tx_state = BLE_TX_STOP;
pt_env.uart_rx_state = UART_RX_GOING;
pt_env.state = PT_CONN_EMPTY;
uart_uart_GetRXD(QN_UART0);//before read start,clear fifo data.
uart_uart_ClrIntFlag(QN_UART0, 0x0000003d);//before read start,clear all the interrupt flag
uart_read(PT_UART_PORT, pt_data_fifo.elemt[0].buf, 1, pt_rx_raw_done);
uart_rx_int_enable(PT_UART_PORT, MASK_ENABLE);
// Rx timer config
timer_config(QN_TIMER3, TIMER_PSCAL_DIV, TIMER_COUNT_MS(/*pt_env.user_param.raw_frame_timer*/5 , TIMER_PSCAL_DIV));
timer_init(QN_TIMER3, timer3_callback);
}
/*
* note: when UART baud rade is 115200, UART speed is higher than ble.
* baud rade is 2400, 9600, 38400, BLE speed is higher than UART.
* data fifo should deal with it
*/
void pt_rx_raw_done(void)
{
pt_data_fifo.elemt[pt_data_fifo.in].len++;
if(pt_data_fifo.elemt[pt_data_fifo.in].len >= PT_FIFO_Y_SIZE)
{
pt_data_fifo.in++; //in this place should pt_data_fifo.in >= pt_data_fifo.out
if(pt_data_fifo.in >= PT_FIFO_X_SIZE)
{
pt_data_fifo.in = 0;
}
if(pt_data_fifo.in == pt_data_fifo.out)
{
pt_data_fifo.full_ct++;
pt_data_fifo.state = PT_FIFO_FULL;
pt_env.uart_rx_state = UART_RX_STOP;
}
else
{
pt_data_fifo.state = PT_FIFO_NOFU;
}
pt_data_fifo.elemt[pt_data_fifo.in].len = 0;
if((pt_env.ble_tx_state != BLE_TX_GOING)&&(pt_data_fifo.state != PT_FIFO_EMPT))
{
ke_evt_set(1UL << PT_RX_RAW_FRAME_EVENT_ID); //don't send ble data in uart interrupt, set an env to kernel
pt_env.ble_tx_state = BLE_TX_GOING;
}
}
if(pt_env.uart_rx_state != UART_RX_STOP)
{
//stop timer, prepare next byte
do{timer_timer_SetCRWithMask(QN_TIMER3, TIMER_MASK_TEN, MASK_DISABLE);}
while((UART_RX_TIMER->CR & 0x00000001) == 1);
uart_read(PT_UART_PORT, pt_data_fifo.elemt[pt_data_fifo.in].buf+pt_data_fifo.elemt[pt_data_fifo.in].len, 1, pt_rx_raw_done);
//start timer
do{timer_enable(QN_TIMER3, MASK_ENABLE);}
while((UART_RX_TIMER->CR & 0x00000001) == 0);
}
}
void pt_rx_raw_frame_hdl(void)
{
ke_evt_clear(1UL << PT_RX_RAW_FRAME_EVENT_ID);
ble_data_tx();
}
void ble_data_tx()
{
app_qpps_env->tx_buffer_available--;
app_qpps_data_send(app_qpps_env->conhdl, 0, pt_data_fifo.elemt[pt_data_fifo.out].len, pt_data_fifo.elemt[pt_data_fifo.out].buf);
pt_data_fifo.out ++;
if(pt_data_fifo.out == PT_FIFO_X_SIZE)
{
pt_data_fifo.out = 0;
}
if(pt_data_fifo.out == pt_data_fifo.in)
{
pt_data_fifo.state = PT_FIFO_EMPT;
pt_data_fifo.empty_ct++;
if(pt_env.uart_rx_state == UART_RX_STOP)
{
pt_rx_raw_start();
}
}
}
<file_sep>/**
****************************************************************************************
*
* @file app_eaci_uart.h
*
* @brief UART transport module functions for Easy Application Controller Interface.
*
* Copyright (C) Quintic 2012-2013
*
* $Rev: 1.0 $
*
****************************************************************************************
*/
#ifndef APP_PT_H_
#define APP_PT_H_
#include "app_env.h"
#define UART_RX_TIMER QN_TIMER3
#define PT_UART_PORT QN_UART0
#define PT_FIFO_X_SIZE 200//50
#define PT_FIFO_Y_SIZE 20
#define FIFO_SIZE 1000
#define PT_RX_RAW_FRAME_EVENT_ID 4
enum pt_st
{
PT_DEEPSLEEP = 0,
PT_ADV = 1,
PT_CONN_EMPTY = 2,
PT_CONN_FULL = 3,
};
enum ble_tx_st
{
BLE_TX_STOP = 0,
BLE_TX_DELAY = 1,
BLE_TX_GOING = 2,
BLE_TX_NOBUF = 4,
};
enum uart_rx_st
{
UART_RX_STOP = 0,
// UART_RX_DELAY = 1,
UART_RX_GOING = 2,
// UART_RX_NOBUF = 4,
};
enum pt_fifo_st
{
PT_FIFO_EMPT = 0, // empty
PT_FIFO_NOFU = 1, // not full
PT_FIFO_FULL = 2, // FIFO full
// PT_FIFO_SUCC = 3, // operation success
// PT_FIFO_FAIL = 4, // operation fail
};
struct woke_param
{
uint16_t adv_intv_min; //adv_interval
uint16_t adv_intv_max;
uint16_t conn_intv_min; //conn_interval
uint16_t conn_intv_max;
uint8_t ble_name_len;
uint8_t ble_name[17];
uint8_t baudrate;
uint8_t wakeup_exmcu_timer;
uint16_t raw_frame_timer;
uint8_t adv_user_data_len;
uint8_t adv_user_data[30];
};
struct PT_FIFO_ELEMENT
{
uint8_t len; ///UART RX Raw data
uint8_t buf[PT_FIFO_Y_SIZE]; ///UART RX Raw data
};
struct PT_FIFO
{
uint8_t in; ///UART RX Raw data paramete
uint8_t out;
uint8_t state; // fifo state: empty, not full, full
uint8_t full_ct; // debug information
uint8_t empty_ct; // debug information
struct PT_FIFO_ELEMENT elemt[PT_FIFO_X_SIZE];
};
struct pt_env_tag
{
uint8_t state; //deepsleep, advertising, connect full, connect empty
uint8_t ble_tx_state; //stop, tx delay, tx going
uint8_t uart_rx_state; //stop, tx delay, tx going
struct woke_param user_param;
// uint8_t rx_raw_len;
// uint8_t rx_raw_buf[PT_FIFO_Y_SIZE]; ///UART RX Raw data parameter
};
extern uint8_t pt_fifo_get(uint8_t *pBuf);
extern uint8_t pt_fifo_put(uint8_t *pPutDat, uint8_t PutLen);
extern void pt_fifo_init(void);
extern void pt_rx_raw_start(void);
extern void ble_data_tx(void);
extern void pt_init(void);
extern void pt_enable(void);
extern void pt_disable(void);
extern void pt_rx_raw_done(void);
extern struct pt_env_tag pt_env;
extern struct PT_FIFO pt_data_fifo; //data fifo
#endif
| 07bc7237106c07cb9e8ab143be0ed9bc755dbfa3 | [
"C"
] | 3 | C | Wangwenxue/Ninebot-BLE-Module | cf17ae7db975976ec6601cb4fce40e33c4e50295 | 90e6ed5596e95342548801aaf246844aaa7ded9b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat3
{
class FigureMatrixCheckEmpty : IMatrixCheckEmpty<GeomFigure>
{
public GeomFigure getEmptyElement()
{
return null;
}
public bool checkEmptyElement(GeomFigure element)
{
bool Result = false;
if (element == null)
{
Result = true;
}
return Result;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat2
{
interface IComparable
{
int CompareTo();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat6._1
{
delegate double GeomOrArithm(string str,int i1,int i2);
class Program
{
static double GeomMean(string str, int i1, int i2)
{
Console.WriteLine(str);
return Math.Sqrt(Math.Abs(i1 * i2));
}
static double ArithmMean(string str, int i1, int i2)
{
Console.WriteLine(str);
return ((i1 + i2) / 2);
}
static void ArithmMean1(string str, int i1, int i2)
{
Console.WriteLine("Среднее арифметическое: ");
double Result = ((i1 + i2) / 2);
Console.WriteLine(Result.ToString());
}
static void PrintGA(string str, int i1, int i2, GeomOrArithm func)
{
Console.WriteLine("i1 = " + i1.ToString() + ", i2 = " + i2.ToString());
Console.WriteLine("Ответ:" + (func(str, i1, i2)).ToString());
}
static void PrintAction(string str, int i1, int i2, Action<string, int, int> GAparam)
{
Console.WriteLine("i1 = " + i1.ToString() + ", i2 = " + i2.ToString());
GAparam(str, i1, i2);
}
static void Main(string[] args)
{
int i1 = 3;
int i2 = 5;
Console.WriteLine("Создание экземпляра делегата на основе метода: ");
PrintGA("Среднее геометрическое: ",i1,i2, GeomMean);
Console.WriteLine("\nСоздание экземпляра делегата на лямбда-выражения: ");
PrintGA("Среднее арифметическое: ", i1, i2,
(str, x, y) =>
{
Console.Write(str);
return ((x + y) / 2);
}
);
Console.WriteLine("\n\nИспользование обощенного делегата Action<>");
Console.WriteLine("\nСоздание экземпляра делегата на основе метода: ");
PrintAction("Ответ:",i1, i2, ArithmMean1);
Console.WriteLine("\nСоздание экземпляра делегата на лямбда-выражения: ");
PrintAction("Cреднее геометрическое: ", i1, i2,
(string str, int x, int y) =>
{
Console.WriteLine(str + Math.Sqrt(Math.Abs(i1 * i2)).ToString());
}
);
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat2
{
class Program
{
static void Main(string[] args)
{
Circle obj1 = new Circle(3);
Console.WriteLine(obj1.Area());
obj1.Print();
Rectangle obj2 = new Rectangle(5, 10);
Console.WriteLine(obj2.Area());
obj2.Print();
Square obj3 = new Square(5);
Console.WriteLine(obj3.Area());
obj3.Print();
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat2
{
class Rectangle : GeomFigure, IPrint
{
double height;
double width;
public Rectangle(double a, double b)
{
this.height = a;
this.width = b;
this.Type = "Прямоугольник";
}
public override double Area()
{
double S = this.width * this.height;
return S;
}
public override string ToString()
{
return (Type.ToString() + ": ширина = " + width + ", высота = " + height + ", площадь = " + Area());
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Laborat5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> list = new List<string>();
private void ReadFile_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "текстовые файлы|*.txt";
if (fd.ShowDialog() == DialogResult.OK)
{
Stopwatch timer1 = new Stopwatch();
timer1.Start();
string text = File.ReadAllText(fd.FileName, Encoding.GetEncoding(1251));
char[] separators = new char[] { ' ', '.', ',', '!', '?', '/', '\t', '\n' };
string[] textArray = text.Split(separators);
foreach (string strTemp in textArray)
{
string str = strTemp.Trim();
if (!list.Contains(str)) list.Add(str);
}
timer1.Stop();
this.LoadTime.Text = timer1.Elapsed.ToString();
MessageBox.Show("Чтение файла завершено.");
}
else
{
MessageBox.Show("Необходимо выбрать файл!");
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
string word = this.SearchText.Text.Trim();
if (!string.IsNullOrWhiteSpace(word) && list.Count > 0)
{
int maxDist;
if (!int.TryParse(this.MaxDist.Text.Trim(), out maxDist))
{
MessageBox.Show("Необходимо указать максимальное расстояние");
return;
}
if (maxDist < 1 || maxDist > 5)
{
MessageBox.Show("Максимальное расстояние должно быть в диапазоне от 1 до 5");
return;
}
//Слово для поиска в верхнем регистре
string wordUpper = word.ToUpper();
//Временные результаты поиска
List<Tuple<string, int>> tempList = new List<Tuple<string, int>>();
Stopwatch t = new Stopwatch();
t.Start();
foreach (string str in list)
{
//Вычисление расстояния Дамерау-Левенштейна
int dist = DamerauLevenshtein.Distance(str.ToUpper(), wordUpper);
//Если расстояние меньше порогового, то слово добавляется в результат
if (dist <= maxDist)
{
tempList.Add(new Tuple<string, int>(str, dist));
}
}
t.Stop();
this.SearchTime.Text = t.Elapsed.ToString();
this.ListSearch.BeginUpdate();
//Очистка списка
this.ListSearch.Items.Clear();
//Вывод результатов поиска
foreach (var x in tempList)
{
string temp = x.Item1 + "(расстояние=" + x.Item2.ToString() + ")";
this.ListSearch.Items.Add(temp);
}
this.ListSearch.EndUpdate();
}
else
MessageBox.Show("Необходимо выбрать файл и ввести слово для поиска");
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat3
{
class Matrix3<T>
{
Dictionary<string, T> matr = new Dictionary<string, T>();
int maxX;
int maxY;
int maxZ;
IMatrixCheckEmpty<T> сheckEmpty;
public Matrix3(int x, int y, int z, IMatrixCheckEmpty<T> сheckEmptyParam)
{
this.maxX = x;
this.maxY = y;
this.maxZ = z;
this.сheckEmpty = сheckEmptyParam;
}
public T this[int x, int y, int z]
{
get
{
CheckBounds(x, y, z);
string key = DictKey(x, y, z);
if (this.matr.ContainsKey(key)) { return this.matr[key]; }
else { return this.сheckEmpty.getEmptyElement(); }
}
set
{
CheckBounds(x, y, z);
string key = DictKey(x, y, z);
this.matr.Add(key, value);
}
}
void CheckBounds(int x, int y, int z)
{
if ((x < 0) || (x > this.maxX)) throw new Exception("x=" + x + "выходит за границы матрицы");
if ((y < 0) || (y > this.maxY)) throw new Exception("y=" + y + "выходит за границы матрицы");
if ((z < 0) || (z > this.maxZ)) throw new Exception("z=" + z + "выходит за границы матрицы");
}
string DictKey(int x, int y, int z) { return x.ToString() + "_" + y.ToString() + "_" + z.ToString(); }
public override string ToString()
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < this.maxZ; i++)
{
for (int j = 0; j < this.maxY; j++)
{
b.Append("[");
for (int k = 0; k < this.maxX; k++)
{
if (k > 0) { b.Append("\t"); }
if (!this.сheckEmpty.checkEmptyElement(this[i, j, k])) { b.Append(this[i, j, k].ToString()); }
else { b.Append(" - "); }
}
b.Append("]\n");
}
b.Append("\n\n\n");
}
return b.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laboratorn1
{
class Program
{
static void WriteColor(string st, int color)
{
if (color == 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(st);
Console.ResetColor();
}
if (color == 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(st);
Console.ResetColor();
}
}
static void QEquat(double a, double b, double c)
{
if ((a == 0) & (b == 0))
{
WriteColor("Корней нет", 1);
}
if ((a == 0) & (b != 0))
{
double x = -c / b;
if (x<0) WriteColor("Корней нет", 1);
else WriteColor("R1=" + Math.Sqrt(x)+ ", R2=" + (-1)*Math.Sqrt(x), 0);
}
if ((b == 0) & (a != 0))
{
if ((-c / a) < 0) WriteColor("Корней нет", 1);
else
{
double x1 = Math.Sqrt(Math.Abs(-c / a));
WriteColor("R1=" + Math.Sqrt(x1) + ", R2=" + (-1)*Math.Sqrt(x1), 0);
}
}
if ((a != 0) & (b != 0))
{
double D = b * b - 4 * a * c;
if (D == 0)
{
double R = -b / (2 * a);
if (R < 0) WriteColor("Корней нет", 1);
else WriteColor("R1=" + Math.Sqrt(R) + ", R2=" + (-1)*Math.Sqrt(R)+ ", D=" + D, 0);
}
else if (D > 0)
{
double R1 = (-b + Math.Sqrt(D)) / (2 * a);
double R2 = (-b - Math.Sqrt(D)) / (2 * a);
if ((R1 < 0)&(R2 < 0)) WriteColor("Корней нет", 1);
else
if (R2 < 0) WriteColor("R1=" + Math.Sqrt(R1) + ", R2=" + (-1)*Math.Sqrt(R1) + ", D=" + D, 0);
else if (R1 < 0) WriteColor("R1=" + Math.Sqrt(R2) + ", R2=" + (-1) * Math.Sqrt(R2) + ", D=" + D, 0);
else WriteColor("R1=" + Math.Sqrt(R1) + ", R2=" + (-1) * Math.Sqrt(R1) + ", R3=" + Math.Sqrt(R2) + ", R4=" + (-1) * Math.Sqrt(R2)+", D=" + D, 0);
}
else if (D < 0)
{
WriteColor("Корней нет, D = 0", 1);
}
}
}
static void Main(string[] args)
{
Console.Title="Павловская Анастасия ИУ5-31Б";
Console.WriteLine("Ax^4+Bx^2+C=0");
string k = "y";
do
{
double a = 0, b = 0, c = 0;
Console.WriteLine("Введите коэффициенты A, B, C");
if (args.Length == 0)
{
bool e = true;
do
{
Console.Write("A = ");
e = double.TryParse(Console.ReadLine(), out a);
//ф = double.Parse(args[0]); - для командной строки
if (!e) WriteColor("Ошибка!Введите число", 1);
}
while (!e);
do
{
Console.Write("B = ");
e = double.TryParse(Console.ReadLine(), out b);
if (!e) WriteColor("Ошибка!Введите число", 1);
}
while (!e);
do
{
Console.Write("C = ");
e = double.TryParse(Console.ReadLine(), out c);
if (!e) WriteColor("Ошибка!Введите число", 1);
}
while (!e);
}
else if (args.Length != 0)
{
bool e1 = true;
bool e = true;
do
{
Console.Write("A = ");
if (e1)
e = double.TryParse(args[0], out a);
else e = double.TryParse(Console.ReadLine(), out a);
if (!e) { WriteColor("Ошибка!Введите число", 1); e1 = false; }
}
while (!e);
e1 = true;
do
{
Console.Write("B = ");
if (e1)
e = double.TryParse(args[1], out b);
else e = double.TryParse(Console.ReadLine(), out b);
if (!e) { WriteColor("Ошибка!Введите число", 1); e1 = false; }
}
while (!e);
e1 = true;
do
{
Console.Write("C = ");
if (e1)
e = double.TryParse(args[2], out c);
else e = double.TryParse(Console.ReadLine(), out c);
if (!e) { WriteColor("Ошибка!Введите число", 1); e1 = false; }
}
while (!e);
}
Program.QEquat(a, b, c);
Console.WriteLine("Продолжить?(y/n)");
k = Console.ReadLine();
} while (k == "y");
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat3
{
abstract class GeomFigure: IComparable
{
public string Type
{
get
{
return this._Type;
}
protected set
{
this._Type = value;
}
}
string _Type;
public int CompareTo(object obj)
{
GeomFigure p = (GeomFigure)obj;
if (this.Area() < p.Area()) return -1;
else if (this.Area() == p.Area()) return 0;
else return 1;
}
public abstract double Area();
public override string ToString()
{
return Type.ToString()+"";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Laborat3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Сортировка геометрических фигур ");
Circle obj1 = new Circle(3);
Rectangle obj2 = new Rectangle(5, 10);
Square obj3 = new Square(5);
Console.WriteLine("\n\nПример работы класса ArrayList");
ArrayList arr = new ArrayList();
arr.Add(obj1);
arr.Add(obj2);
arr.Add(obj3);
Console.WriteLine("\nДо сортировки:");
foreach (GeomFigure f in arr) Console.WriteLine(f);
arr.Sort();
Console.WriteLine("\nПосле сортировки:");
foreach (GeomFigure f in arr) Console.WriteLine(f);
Console.WriteLine("\n\nПример работы класса List<T>");
List<GeomFigure> LF = new List<GeomFigure>();
LF.Add(obj1);
LF.Add(obj2);
LF.Add(obj3);
Console.WriteLine("\nПеред сортировкой:");
foreach (var x in LF) Console.WriteLine(x);
LF.Sort();
Console.WriteLine("\nПосле сортировки:");
foreach (var x in LF) Console.WriteLine(x);
Console.WriteLine("\n\nПример работы класса SimpleList");
SimpleList<GeomFigure> list = new SimpleList<GeomFigure>();
list.Add(obj1); list.Add(obj2); list.Add(obj3);
Console.WriteLine("\nПеред сортировкой:");
foreach (var x in list)
Console.WriteLine(x); //сортировка
list.Sort();
Console.WriteLine("\nПосле сортировки:");
foreach (var x in list)
Console.WriteLine(x);
Console.WriteLine("\n\nПример работы класса SimpleStack ");
SimpleStack<GeomFigure> stack = new SimpleStack<GeomFigure>();
//добавление данных в стек
stack.Push(obj1); stack.Push(obj2); stack.Push(obj3);
//чтение данных из стека
while (stack.Count > 0)
{
GeomFigure f = stack.Pop();
Console.WriteLine(f);
}
Console.WriteLine("\n\nПример работы класса Matrix3");
Matrix3<GeomFigure> matrix = new Matrix3<GeomFigure>(3, 3, 3, new FigureMatrixCheckEmpty());
matrix[0, 0, 0] = obj1;
matrix[1, 1, 1] = obj2;
matrix[2, 2, 2] = obj3;
Console.WriteLine(matrix.ToString());
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Laborat2
{
class Circle : GeomFigure, IPrint
{
double R;
public Circle(double a)
{
this.R = a;
this.Type = "Круг";
}
public override double Area()
{
double S = Math.PI * this.R * this.R;
return S;
}
public override string ToString()
{
return (Type.ToString() + ": радиус = " + R + ", площадь = " + Area());
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
} | e40985f95cf3aaeb100ea49f58c6deb21d81bfe6 | [
"C#"
] | 11 | C# | PavlAA79/Labs1 | 6f78f145fb7465067891d85d62208ad1c66c662c | 0a1bb38eba53352feb5894f3a3d3b51ace783946 |
refs/heads/master | <file_sep>#' Title
#'
#' @param tab
#'
#' @return
#' @export
#'
#' @examples
extractDiseaseCode = function(tab){
listCode = list()
for(i in 1:nrow(tab)){
listCode[[as.character(tab[i,1])]] = list("icd7"=giveCauseCode(tab$ICD7[i]),"icd8"=giveCauseCode(tab$ICD8[i]),"icd9"=giveCauseCode(tab$ICD9[i]),"icd10"=giveCauseCode(tab$ICD10[i]))#"icd7"=giveCauseCode(tab$ICD7[i]),
}
return(listCode)
}
<file_sep>#' Title
#'
#' @param string
#'
#' @return
#' @export
#'
#' @examples
giveRange = function(string){
vect = c()
# print(string)
if(grepl("-",string)){
string_split = unlist(strsplit(string,"-"))
le = max(nchar(string_split[1]),nchar(string_split[2]))
# print(le)
nb1 = as.numeric(substr(string_split[1],2,le))
# print(nb1)
nb2 = as.numeric(substr(string_split[2],2,le))
# print(nb2)
car1 = substr(string_split[1],1,1)
nb_range = nb1:nb2
if(nchar(nb1)!=(le-1) | nchar(nb2)!=(le-1)){
for(i in 1:length(nb_range)){
nb_range[i] = paste(paste(rep(0,(le-1-nchar(nb_range[i]))),collapse=""),nb_range[i],sep="")
}
}
vect = paste(car1,nb_range,sep="")
}else{
vect = string
}
return(vect)
}
<file_sep>#' Title
#'
#' @param UNcode
#' @param WHO_UN
#'
#' @return
#' @export
#'
#' @examples
UNtoWHO = function(UNcode,WHO_UN){
WHOcode = c()
for(code in UNcode){
newCode = ifelse(code==-1,-1,WHO_UN[which(WHO_UN$un==code),"who"])
WHOcode = c(WHOcode,newCode)
}
return(WHOcode)
}
<file_sep>#' Title
#'
#' @param vect_cause
#'
#' @return
#' @export
#'
#' @examples
giveCauseCode = function(vect_cause){
cause = c()
# print(nchar(vect_cause))
if(!is.na(vect_cause) & vect_cause!=""){
string_split = unlist(strsplit(as.character(vect_cause),";"))
# print(string_split)
for(j in 1:length(string_split)){
cause = c(cause,giveRange(string_split[j]))
}
}
return(cause)
}
<file_sep>#' Title
#'
#' @param WHOcode
#' @param WHO_UN
#'
#' @return
#' @export
#'
#' @examples
WHOtoUN = function(WHOcode,WHO_UN){
UNcode = c()
for(code in WHOcode){
# if(length(WHO_UN[which(WHO_UN$who==code),"un"])==0){print(code)}
# else if(WHO_UN[which(WHO_UN$who==code),"un"]==-1 | is.na(WHO_UN[which(WHO_UN$who==code),"un"])){print(code)}
UNcode = c(UNcode,WHO_UN[which(WHO_UN$who==code),"un"])
}
return(UNcode)
}
| c98a51dcde7fd07c196d2b8e2c6b81c47be1cdfb | [
"R"
] | 5 | R | Cecile-P/MTA | c37f56369b32760ff75a2bc6259c33c251900f35 | 506185653297622f9f85b3cb4662cc5d38d35e32 |
refs/heads/master | <repo_name>codetronaut/doc_tag_test<file_sep>/src/commandF.sh
#File and Folder placement:::
# BASE FOLDER PWD MUST contain files "commandF.sh", "html_report.py",
#"README.md", "PDF-to-txt.py", "make_report.py"
# All PDFs to be searched are in a folder of PWD called "PDFs"
counterPDF=1
counterTXT=1
counterDEL=1
STR=""
STR_noES=""
emptyspace=" "
pdfname=""
for file in $PWD/PDFs/*.pdf
do
path=$PWD/
pdfname="${file##*/}"
echo "converting file "$pdfname
extension=.txt
outfile=$path$pdfname$extension
python pdf2txt.py "$file" >> "$outfile"
counterPDF=$((counterPDF+1))
done
for file in $PWD/*.txt
do
pdfname="${file##*/}"
echo "searching through "$pdfname
name="$pdfname"
STR_noES="$STR$name"
STR="$STR_noES$emptyspace"
counterTXT=$((counterTXT+1))
done
echo $STR_noES
python convert.py $STR_noES
python make_report.py
#rm *.txt
<file_sep>/readme.md
# Doc-Tag
## Description
This tool basically searches the given word within pdf files in a specific location or directory. This program searches one or more keywords and generates an html report of it ,i.e what sort of information is found.
### How To Run This Project
> Since the project use python-2.7 I recommend you to run it with repl for py2.7
#### Run the Application
```bash
# Install Python 2.7
$ sudo apt install python2
$ python2 --version
# Clone into YOUR local drive
$ git clone https://github.com/codetronaut/doc_tag_test.git
#move to project
$ cd doc_tag_test
# Run
$ python2 Doc_Tag.py
```
`Note: you can also change your directory(in which your are going to search) right now i have hard coded it to the PDFs directory.`
### Tools Used:
It is coded in fully python with the help of crucial modules i.e [PDFminer](https://github.com/pdfminer/pdfminer.six) and [markdown](https://python-markdown.github.io).
### Contribution:
willing to contribute let's get started.
The main issues to be resolved are:
* Shipping this current version(i.e python-2.7) to python-3.x.
* Enabling back support for some modules which are deprecated(for python-2.7).
* Refactor the code and write more comments for easy understanding to those who are new.
* Shoot any other your ideas to me if any :)
Peace!
| 7e598baf762fd46e7be5aae5efe89db18caaeae8 | [
"Markdown",
"Shell"
] | 2 | Shell | codetronaut/doc_tag_test | 3003bd27914302e28596bf3c2ea48d59fc212f2a | 2a5cd835f5e59cf7735c9aa120ac992615b0a2f5 |
refs/heads/master | <file_sep>window.onload = function () {
fetch("/pokemon")
.then(function (response) {
return response.json();
})
.then(function (content) {
console.log(content)
})
}<file_sep>//Requirements
const express = require("express");
const fs = require("fs");
const app = express();
const port = 3000;
//View Engine
app.set("view engine", "pug");
app.use(express.static("public"));
//Read JSON file
const content = fs.readFileSync("public/pokemon.json", "utf8");
//console.log(content)
//const foo = require("/public/pokemon.json");
//console.log(foo)
//console.log(content)
//const pokemon = JSON.parse(content)
//console.log(pokemon)
//app.locals.SampleData = require('public/pokemon.json');
//Pages
app.get("/", (req,res) => {
res.render("index", {});
});
app.get("/pokemon", (req,res) => {
res.render("pokemon")
res.json(content)
});
app.get("/pokemon.json", (req,res) =>{
res.send(JSON.stringify(content))
console.log(content)
});
//app.get('/pokemon.json', function (req, res) {
// res.header("Content-Type", 'application/json');
// res.send(JSON.stringify(data));
//})
//Listening Port
app.listen(port, () => {
console.log(`Server running on port ${port}`);
}); | 4a3a1d1197f93b0e944a65dfb5cc178e1a569d95 | [
"JavaScript"
] | 2 | JavaScript | pklapwyk/pokedex | fb49d85f435b92e2d8f99a6d25adcfc48e48c82b | 1ef7aea7d35e400a8f5540c77d3955139b8043a4 |
refs/heads/master | <file_sep>using SnakeOnlineClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snake
{
public class Model
{
const string _url = "http://safeboard.northeurope.cloudapp.azure.com";
string _name = "<NAME>";
const string _token = "r_-<PASSWORD>";
Client _client;
public string Name
{
get {
return _name;
}
set
{
_name = value;
}
}
public Model()
{
_client = new Client(_url);
}
public async Task GetNameAsync(string token)
{
await _client.GetNameAsync(_token).ContinueWith((antecedent) =>
{
Name = antecedent.Result.Name;
});
}
public async Task<GameStateResponse> GetGameStateResponseAsync()
{
return await _client.GetGameStateResponseAsync();
}
public async Task SendDirectionRequestAsync(string direction)
{
await _client.SendDirectionRequestAsync(direction, _token);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
namespace Snake
{
class SendNameRequest : ICommand
{
private Model _model;
public event EventHandler CanExecuteChanged;
public SendNameRequest(Model model)
{
_model = model;
}
public bool CanExecute(object parameter)
{
return true;
}
public async void Execute(object parameter)
{
await _model.GetNameAsync((string)parameter);
}
}
public class LoginParameterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.Clone();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Snake
{
public sealed class SendDirectionRequest : ICommand
{
Model _model;
public SendDirectionRequest(Model model)
{
_model = model;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public async void Execute(object parameter)
{
await _model.SendDirectionRequestAsync((string)parameter);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.ComponentModel;
using SnakeOnlineClient;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Input;
namespace Snake
{
class ObservableRectangle : Rectangle
{
public Brush Color { get; set; }
}
class MainWindowViewModel : INotifyPropertyChanged
{
const int width = 800;
const int height = 550;
int _step = 0;
int _roundNumber = 0;
ObservableCollection<ObservableRectangle> _rectangles;
ObservableCollection<ObservableRectangle> _wallsRectangles;
Model _model = new Model();
public event PropertyChangedEventHandler PropertyChanged;
public ICommand DirectionCommand { get; set; }
public ICommand ShowLoginWindow { get; set; }
public ObservableCollection<ObservableRectangle> Rectangles
{
get
{
return _rectangles;
}
set
{
_rectangles = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Rectangles)));
}
}
public MainWindowViewModel()
{
_rectangles = new ObservableCollection<ObservableRectangle>();
DirectionCommand = new SendDirectionRequest(_model);
ShowLoginWindow = new ShowLoginWindow();
ThreadPool.QueueUserWorkItem(RefreshStateLoop);
}
public void RefreshStateLoop(object state)
{
while (true)
{
GetGameState();
Thread.Sleep(100);
}
}
private void GetGameState()
{
var gameStateResponse = _model.GetGameStateResponseAsync();
var gameState = gameStateResponse.Result;
if (gameState.RoundNumber != _roundNumber)
{
_wallsRectangles = new ObservableCollection<ObservableRectangle>();
var widthSteps = gameState.GameBoardSize.Width + 2;
var heightSteps = gameState.GameBoardSize.Height + 2;
_step = Math.Min(width / widthSteps, height / heightSteps);
var brush = Brushes.SteelBlue;
_wallsRectangles.Add(new ObservableRectangle
{
Width = _step,
Height = heightSteps * _step,
X = 0,
Y = 0,
Color = brush
});
_wallsRectangles.Add(new ObservableRectangle
{
Width = widthSteps * _step,
Height = _step,
X = 0,
Y = 0,
Color = brush
});
_wallsRectangles.Add(new ObservableRectangle
{
Width = _step,
Height = heightSteps * _step,
X = (widthSteps - 1) * _step,
Y = 0,
Color = brush
});
_wallsRectangles.Add(new ObservableRectangle
{
Width = widthSteps * _step,
Height = _step,
X = 0,
Y = (heightSteps - 1) * _step,
Color = brush
});
foreach (var wall in gameState.Walls)
{
_wallsRectangles.Add(new ObservableRectangle
{
Width = wall.Width * _step,
Height = wall.Height * _step,
X = (wall.X + 1) * _step,
Y = (wall.Y + 1) * _step,
Color = brush
});
}
}
var r = new ObservableCollection<ObservableRectangle>(_wallsRectangles);
foreach (PlayerState player in gameState.Players)
{
foreach (var block in player.Snake ?? new List<Point>())
{
var brush = Brushes.Red;
if (player.IsSpawnProtected)
brush = Brushes.White;
if (player.Name == _model.Name)
brush = Brushes.Aqua;
r.Add(new ObservableRectangle
{
Width = _step,
Height = _step,
X = (block.X + 1) * _step,
Y = (block.Y + 1) * _step,
Color = brush
});
}
}
foreach (var food in gameState.Food)
{
r.Add(new ObservableRectangle
{
Width = _step,
Height = _step,
X = (food.X + 1) * _step,
Y = (food.Y + 1) * _step,
Color = Brushes.Chocolate
});
}
Rectangles = r;
return;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace SnakeOnlineClient
{
public sealed class Client
{
private readonly RestClient _httpClient;
public Client(string uri)
{
_httpClient = new RestClient(uri);
}
public string GetName(string token)
{
var request = new RestRequest("api/Player/name");
request.AddQueryParameter("token", token);
var response = _httpClient.Execute<NameResponse>(request);
if (!response.IsSuccessful)
return null;
return response.Data.Name;
}
public async Task<NameResponse> GetNameAsync(string token)
{
var request = new RestRequest("api/Player/name");
request.AddQueryParameter("token", token);
var response = await _httpClient.ExecuteGetTaskAsync<NameResponse>(request);
return response.Data;
}
public async Task<GameStateResponse> GetGameStateResponseAsync()
{
var request = new RestRequest("api/Player/gameboard");
var response = await _httpClient.ExecuteGetTaskAsync<GameStateResponse>(request);
return response.Data;
}
public GameStateResponse GetGameStateResponse()
{
var request = new RestRequest("api/Player/gameboard");
var response = _httpClient.Execute<GameStateResponse>(request);
return response.Data;
}
public HttpStatusCode SendDirectionRequest(string direction, string token)
{
var request = new RestRequest("api/Player/direction")
{
Method = Method.POST
};
request.AddJsonBody(new DirectionRequest { Direction = direction, Token = token });
var response = _httpClient.Execute(request);
return response.StatusCode;
}
public async Task<HttpStatusCode> SendDirectionRequestAsync(string direction, string token)
{
var request = new RestRequest("api/Player/direction");
request.Method = Method.POST;
request.AddJsonBody(new DirectionRequest { Direction = direction, Token = token });
var response = await _httpClient.ExecuteTaskAsync(request);
return response.StatusCode;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnakeOnlineClient
{
public sealed class NameResponse
{
public string Name { get; set; }
}
public sealed class DirectionRequest
{
public string Direction { get; set; }
public string Token { get; set; }
}
public sealed class Point
{
public int X { get; set; }
public int Y { get; set; }
}
public sealed class Size
{
public int Width { get; set; }
public int Height { get; set; }
}
public class Rectangle
{
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public sealed class PlayerState
{
public string Name { get; set; }
public bool IsSpawnProtected { get; set; }
public List<Point> Snake { get; set; }
}
public sealed class GameStateResponse
{
public bool IsStarted { get; set; }
public bool IsPaused { get; set; }
public int RoundNumber { get; set; }
public int TurnNumber { get; set; }
public int TurnTimeMilliseconds { get; set; }
public int TimeUntilNextTurnMilliseconds { get; set; }
public Size GameBoardSize { get; set; }
public int MaxFood { get; set; }
public List<PlayerState> Players { get; set; }
public List<Point> Food { get; set; }
public List<Rectangle> Walls { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Snake
{
class ShowLoginWindow : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var loginWindow = new Login();
loginWindow.ShowDialog();
}
}
}
<file_sep># Snake
Online Client for snake game
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Snake
{
class LoginWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ICommand SendNameRequest { get; set; }
Model _model;
public LoginWindowViewModel()
{
_model = new Model();
SendNameRequest = new SendNameRequest(_model);
}
}
}
| dcef5b71efd5bfaa729c5656c94875f34a3db5a9 | [
"Markdown",
"C#"
] | 9 | C# | ISChetverikov/Snake | 5e38e40f532acd2e7ba3e0e7c773fa560e00870f | b1318b915f73634250866a6c41e477453dbb58db |
refs/heads/master | <file_sep>package com.booking.hotel.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
@Entity
@Table(name = "customer", schema = "shivam",
uniqueConstraints = @UniqueConstraint(columnNames= {"email"}))
public class CustomerEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6517403645560177106L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "firstname", nullable=false)
private String firstName;
@Column(name = "lastname", nullable=false)
private String lastName;
@Column(name = "dob", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date dob;
@Email
@Column(name = "email", unique = true, nullable=false)
private String email;
@Size(min = 8, max = 10)
@Min(8)
@Max(10)
@Column(name = "password", nullable=false, length=10)
private String password;
public CustomerEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
<file_sep>package com.booking.hotel.error;
public class UsernameAlreadyExists extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 3507138578683736837L;
public UsernameAlreadyExists(String s) {
super(s);
}
}
<file_sep>package com.booking.hotel.mapper;
import java.util.Date;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import com.booking.hotel.entity.CustomerEntity;
public class EntityToModelTest {
@InjectMocks
EntityToModel etom;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testmapModel() {
etom.mapModel(buildEntity().get());
}
private Optional<CustomerEntity> buildEntity() {
CustomerEntity entity = new CustomerEntity();
entity.setId(1L);
entity.setFirstName("shivam");
entity.setLastName("gaba");
entity.setDob(new Date());
entity.setEmail("<EMAIL>");
entity.setPassword("<PASSWORD>");
return Optional.of(entity);
}
}
<file_sep>package com.booking.hotel.model;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({"id", "firstname", "lastname", "dob", "email", "password"})
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Customer implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5212396240256621441L;
@JsonProperty(value="id")
private Long id;
@JsonProperty(value="firstname")
private String firstName;
@JsonProperty(value="lastname")
private String lastName;
@JsonProperty(value="dob")
private Date dob;
@JsonProperty(value="email")
private String email;
@JsonProperty(value="<PASSWORD>")
private String password;
private Customer() {}
private Customer(CustomerBuilder customerBuilder) {
this.id = customerBuilder.id;
this.firstName = customerBuilder.firstName;
this.lastName = customerBuilder.lastName;
this.dob = customerBuilder.dob;
this.email = customerBuilder.email;
this.password = <PASSWORD>.password;
}
public Long getId() { return id; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public Date getDob() { return dob; }
public String getEmail() { return email; }
public String getPassword() { return password; }
public static class CustomerBuilder {
@JsonProperty(value="id")
private Long id;
@JsonProperty(value="firstname")
private String firstName;
@JsonProperty(value="lastname")
private String lastName;
@JsonProperty(value="dob")
private Date dob;
@JsonProperty(value="email")
private String email;
@JsonProperty(value="password")
private String password;
public CustomerBuilder() {}
public CustomerBuilder setId(Long id) {
this.id = id;
return this;
}
public CustomerBuilder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public CustomerBuilder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public CustomerBuilder setDob(Date dob) {
this.dob = dob;
return this;
}
public CustomerBuilder setEmail(String email) {
this.email = email;
return this;
}
public CustomerBuilder setPassword(String password) {
this.password = <PASSWORD>;
return this;
}
public Customer build() {
return new Customer(this);
}
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(final Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
<file_sep>package com.booking.hotel.mapper;
import java.util.Optional;
import com.booking.hotel.entity.CustomerEntity;
import com.booking.hotel.model.Customer;
import com.booking.hotel.model.Customer.CustomerBuilder;
public class EntityToModel {
public Customer mapModel(CustomerEntity entity) {
Customer.CustomerBuilder builder = new CustomerBuilder();
Optional.ofNullable(entity).map(CustomerEntity::getId).ifPresent(builder::setId);
Optional.ofNullable(entity).map(CustomerEntity::getFirstName).ifPresent(builder::setFirstName);
Optional.ofNullable(entity).map(CustomerEntity::getLastName).ifPresent(builder::setLastName);
Optional.ofNullable(entity).map(CustomerEntity::getDob).ifPresent(builder::setDob);
Optional.ofNullable(entity).map(CustomerEntity::getEmail).ifPresent(builder::setEmail);
Optional.ofNullable(entity).map(CustomerEntity::getPassword).ifPresent(builder::setPassword);
return builder.build();
}
}
<file_sep>package com.booking.hotel.controller;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.booking.hotel.model.Customer;
import com.booking.hotel.model.Customer.CustomerBuilder;
import com.booking.hotel.service.CustomerService;
public class CustomerControllerTest {
@InjectMocks
CustomerController customerController;
@Mock
private CustomerService service;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
//customerController = new CustomerController(service);
//this.service = Mockito.mock(CustomerService.class);
}
@Test
public void testSaveCustomer() {
customerController.saveCustomer(buildCustomer());
}
@Test
public void testGetCustomerById() {
Mockito.when(service.getById(Mockito.anyLong())).thenReturn(buildCustomer());
customerController.getCustomerById(1L);
}
private Customer buildCustomer() {
Customer.CustomerBuilder builder = new CustomerBuilder();
builder.setFirstName("shivam").setLastName("gaba").setId(1L).setDob(new Date()).setEmail("<EMAIL>")
.setPassword("<PASSWORD>");
return builder.build();
}
}
<file_sep>package com.booking.hotel.mapper;
import java.util.Optional;
import org.springframework.util.Assert;
import com.booking.hotel.entity.CustomerEntity;
import com.booking.hotel.model.Customer;
public class ModelToEntity {
public CustomerEntity mapEntity(Customer customer) {
Assert.notNull(customer, "customer object can not be empty");
CustomerEntity customerEntity = new CustomerEntity();
Optional.ofNullable(customer).map(Customer::getFirstName).ifPresent(customerEntity::setFirstName);
Optional.ofNullable(customer).map(Customer::getLastName).ifPresent(customerEntity::setLastName);
Optional.ofNullable(customer).map(Customer::getDob).ifPresent(customerEntity::setDob);
Optional.ofNullable(customer).map(Customer::getEmail).ifPresent(customerEntity::setEmail);
Optional.ofNullable(customer).map(Customer::getPassword).ifPresent(customerEntity::setPassword);
return customerEntity;
}
}
<file_sep>package com.booking.hotel.error;
public class UserNotFoundException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 2113997953414754308L;
public UserNotFoundException(String s) {
super(s);
}
}
<file_sep>package com.booking.hotel.service;
import java.util.Date;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.booking.hotel.entity.CustomerEntity;
import com.booking.hotel.error.PasswordConstraintException;
import com.booking.hotel.error.UserNotFoundException;
import com.booking.hotel.error.UsernameAlreadyExists;
import com.booking.hotel.model.Customer;
import com.booking.hotel.model.Customer.CustomerBuilder;
import com.booking.hotel.repository.CustomerRepository;
public class CustomerServiceImplTest {
@InjectMocks
CustomerServiceImpl customerServiceImpl;
@Mock
private CustomerRepository repo;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSave() {
customerServiceImpl.save(buildCustomer());
}
@Test
public void testSaveInvalidEmail() {
Mockito.when(repo.findByEmail(Mockito.anyString())).thenReturn(buildEntity());
exception.expect(UsernameAlreadyExists.class);
customerServiceImpl.save(buildCustomer());
}
@Test
public void testSaveWithInvaildPasswordLengthLessThen8() {
Customer.CustomerBuilder builder = new CustomerBuilder();
builder.setPassword("sgh");
exception.expect(PasswordConstraintException.class);
customerServiceImpl.save(builder.build());
}
@Test
public void testSaveWithInvaildPasswordLengthMoreThen10() {
Customer.CustomerBuilder builder = new CustomerBuilder();
builder.setPassword("<PASSWORD>");
exception.expect(PasswordConstraintException.class);
customerServiceImpl.save(builder.build());
}
@Test
public void testGetById() {
Mockito.when(repo.findById(Mockito.anyLong())).thenReturn(buildEntity());
customerServiceImpl.getById(1L);
}
@Test
public void testIdNotFoundException() {
exception.expect(UserNotFoundException.class);
customerServiceImpl.getById(1L);
}
private Customer buildCustomer() {
Customer.CustomerBuilder builder = new CustomerBuilder();
builder.setFirstName("shivam").setLastName("gaba").setId(1L).setDob(new Date()).setEmail("<EMAIL>")
.setPassword("<PASSWORD>");
return builder.build();
}
private Optional<CustomerEntity> buildEntity() {
CustomerEntity entity = new CustomerEntity();
entity.setId(1L);
entity.setFirstName("shivam");
entity.setLastName("gaba");
entity.setDob(new Date());
entity.setEmail("<EMAIL>");
entity.setPassword("<PASSWORD>");
return Optional.of(entity);
}
}
<file_sep>package com.booking.hotel.mapper;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import com.booking.hotel.model.Customer;
import com.booking.hotel.model.Customer.CustomerBuilder;
public class ModelToEntityTest {
@InjectMocks
ModelToEntity mtoe;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testMapEntity() {
mtoe.mapEntity(buildCustomer());
}
private Customer buildCustomer() {
Customer.CustomerBuilder builder = new CustomerBuilder();
builder.setFirstName("shivam").setLastName("gaba").setId(1L).setDob(new Date()).setEmail("<EMAIL>")
.setPassword("<PASSWORD>");
return builder.build();
}
}
| 93a5de6ff1831e383c06a9ea0e40bb48caaf1111 | [
"Java"
] | 10 | Java | shivamgaba/roombookingmgmasystem | cb010bfd6e8e1e895dbc24028eb347337079f0ea | ab28bba03193e687fc748fd1ef66f1227629806b |
refs/heads/master | <file_sep>//
/*
MIT License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
@IBDesignable
open class OPLGaugeView: UIView {
private lazy var gauge: OPLGaugeLayer = {
let _gauge = OPLGaugeLayer()
_gauge.drawsAsynchronously = true
_gauge.disableSpringAnimation = true
return _gauge
}()
@IBInspectable open var enableSpring: Bool {
set {
gauge.disableSpringAnimation = newValue
}
get {
return gauge.disableSpringAnimation
}
}
@IBInspectable open var displayMarkers: Bool = true {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var displayNumbers: Bool = true {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var gaugeColor: UIColor = UIColor.orange {
didSet {
gauge.fillColor = gaugeColor.cgColor
setNeedsDisplay()
}
}
@IBInspectable open var markers: Int = 5 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var minSpeed: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var maxSpeed: CGFloat = 25 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var textFont: UIFont = UIFont.boldSystemFont(ofSize: 24) {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var textColor: UIColor = UIColor.black {
didSet {
setNeedsDisplay()
}
}
@IBInspectable open var startingSpeed: CGFloat = 0 {
didSet {
if startingSpeed > maxSpeed {
startingSpeed = maxSpeed
}
if startingSpeed < minSpeed {
startingSpeed = minSpeed
}
setNeedsDisplay()
}
}
private let lineWidth: CGFloat = 6
open override func draw(_ rect: CGRect) {
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let radius = min(bounds.width, bounds.height) / 2
let startAngle: CGFloat = 0.75 * CGFloat(Double.pi)
let endAngle: CGFloat = 0.25 * CGFloat(Double.pi)
let outlinePath = UIBezierPath(arcCenter: center, radius: radius - (lineWidth / 2), startAngle: startAngle, endAngle: endAngle, clockwise: true)
outlinePath.lineWidth = lineWidth
gaugeColor.setStroke()
outlinePath.stroke()
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
gaugeColor.setFill()
let angleDifference: CGFloat = 2 * .pi - startAngle + endAngle
let arcLengthPerMark: CGFloat = angleDifference / CGFloat(markers)
let multiplePerMark: CGFloat = (maxSpeed - minSpeed) / CGFloat(markers)
let markerWidth: CGFloat = lineWidth - 1
let markerSize: CGFloat = markerWidth * 2
let markerPath = UIBezierPath(rect: CGRect(x: -markerWidth / 2, y: 0, width: markerWidth, height: markerSize).integral)
context.translateBy(x: rect.width / 2, y: rect.height / 2)
for i in 0...markers {
context.saveGState()
let angle = arcLengthPerMark * CGFloat(i) + startAngle - .pi / 2
context.rotate(by: angle)
context.translateBy(x: 0, y: rect.height / 2 - markerSize)
if displayMarkers {
markerPath.fill()
}
context.rotate(by: CGFloat(Double.pi))
let label = round(value: multiplePerMark * CGFloat(i) + minSpeed)
let labelWidth = label.width(font: textFont)
let textPos = CGPoint(x: -labelWidth / 2, y: 0)
if displayNumbers {
label.draw(at: textPos, withAttributes: [NSAttributedString.Key.font: textFont, NSAttributedString.Key.foregroundColor: textColor])
}
context.restoreGState()
}
context.restoreGState()
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
gauge.fillColor = gaugeColor.cgColor
layer.addSublayer(gauge)
let anchorPoint = CGPoint(x: 0.5, y: 1.0)
let newPoint = CGPoint(x: gauge.bounds.size.width * anchorPoint.x, y: gauge.bounds.size.height * anchorPoint.y)
let oldPoint = CGPoint(x: gauge.bounds.size.width * gauge.anchorPoint.x, y: gauge.bounds.size.height * gauge.anchorPoint.y)
var position = gauge.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
gauge.position = position
gauge.anchorPoint = anchorPoint
rotateGauge(newSpeed: startingSpeed)
}
open override func layoutSubviews() {
super.layoutSubviews()
let viewWidth = frame.width
let halfViewWidth = viewWidth / 2
let viewHeight = frame.height
let gaugeYPos: CGFloat = viewHeight * 0.05
let gaugeHeight: CGFloat = viewHeight * 0.45
let gaugeWidth: CGFloat = gaugeHeight * 0.16
let gaugeFrame = CGRect(x: halfViewWidth - (gaugeWidth / 2), y: gaugeYPos, width: gaugeWidth, height: gaugeHeight).integral
gauge.bounds.size = gaugeFrame.size
gauge.position.x = gaugeFrame.origin.x + (gaugeFrame.width / 2)
gauge.position.y = gaugeFrame.origin.y + gaugeFrame.height
let gaugePath = UIBezierPath()
gaugePath.move(to: CGPoint(x: gaugeWidth / 2, y: 0))
gaugePath.addLine(to: CGPoint(x: gaugeWidth, y: gaugeHeight))
gaugePath.addLine(to: CGPoint(x: 0, y: gaugeHeight))
gaugePath.close()
gauge.path = gaugePath.cgPath
}
func rotateGauge(newSpeed: CGFloat) {
var speed = newSpeed
if speed > maxSpeed {
speed = maxSpeed
}
if speed < minSpeed {
speed = minSpeed
}
let fractalSpeed = (speed - minSpeed) / (maxSpeed - minSpeed)
let newAngle = 0.75 * CGFloat(Double.pi) * (2 * fractalSpeed - 1)
gauge.transform = CATransform3DMakeRotation(newAngle, 0, 0, 1)
}
private func round(value: CGFloat) -> String {
let divisor = pow(10, Double(1))
let roundedNumber = (Double(value) * divisor).rounded() / divisor
if roundedNumber.isZero {
return "0"
}
let intRoundedNumber = Int(roundedNumber)
if Double(intRoundedNumber) == roundedNumber {
return "\(intRoundedNumber)"
}
return "\(roundedNumber)"
}
}
fileprivate extension String {
func width(font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: CGFloat(220))
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.width)
}
}
| 4825e4e19edab8e02b0d464e02dba83867b7e069 | [
"Swift"
] | 1 | Swift | jesusjimenezdev/OPLGaugeViewExample | daf27a1b4c1e42d04ddf2edd183064bc0d878b92 | 404757dd41de5b31d0e59dfc1a2c18be8f701483 |
refs/heads/master | <file_sep>var tests = {
"list": [{
"test1": {
"title": "我需要向人表示關懷",
"type": "F"
},
"test2": {
"title": "我選擇與人保持距離",
"type": "H"
}
}, {
"test1": {
"title": "一般而言,我頗容易被激怒",
"type": "B"
},
"test2": {
"title": "一般而言,我絕不容易被激怒",
"type": "A"
}
}, {
"test1": {
"title": "我是一個浪漫兼且想像能力豐富的人",
"type": "E"
},
"test2": {
"title": "我是一個實事求是、腳踏實地的人",
"type": "B"
}
}, {
"test1": {
"title": "我既倔強又疑心大",
"type": "B"
},
"test2": {
"title": "我既心軟又感情用事",
"type": "F"
}
}, {
"test1": {
"title": "我經常憂慮自己流失了重要的機會",
"type": "I"
},
"test2": {
"title": "我憂慮當我不設防的時候,人家會乘機而入",
"type": "G"
}
}, {
"test1": {
"title": "一般而言,我是個外向的人",
"type": "I"
},
"test2": {
"title": "我是個殷實而自律的人",
"type": "D"
}
}, {
"test1": {
"title": "我努力地令人喜歡及接受我",
"type": "C"
},
"test2": {
"title": "我並不重視人家是否喜歡或接受我",
"type": "D"
}
}, {
"test1": {
"title": "我生命中重要的價值包括責任及工作",
"type": "B"
},
"test2": {
"title": "我生命中重要的價值包括和諧與被接受",
"type": "A"
}
}, {
"test1": {
"title": "遭遇困擾的時候,我會獨自沉思",
"type": "E"
},
"test2": {
"title": "遭遇問題的時候,我會盡量看開一點",
"type": "I"
}
}, {
"test1": {
"title": "我不能停止考慮各種可能性而去採取單一行動",
"type": "H"
},
"test2": {
"title": "我不能處之泰然及變得更有彈性",
"type": "D"
}
}, {
"test1": {
"title": "我是一個實事求是的求存者",
"type": "G"
},
"test2": {
"title": "我是一個志向高的理想主義者",
"type": "D"
}
}, {
"test1": {
"title": "我經常可以不理會感受,先把工作完成",
"type": "C"
},
"test2": {
"title": "一般而言,我要擺平自己的感受,才能採取行動",
"type": "E"
}
}, {
"test1": {
"title": "一般而言,我做事謹慎及有系統",
"type": "B"
},
"test2": {
"title": "一般而言,我喜愛及甘於冒險",
"type": "I"
}
}, {
"test1": {
"title": "我時常不能堅持己見,而容許別人操縱我",
"type": "A"
},
"test2": {
"title": "我不肯妥協及對人要求過高",
"type": "D"
}
}, {
"test1": {
"title": "許多時候我之所以成功是因為我有本事在人心目中留下好印象",
"type": "C"
},
"test2": {
"title": "雖然我沒有興趣拓展自己的人際溝通技巧,我仍然能夠成功",
"type": "H"
}
}, {
"test1": {
"title": "基本而言,我是個平易近人、容易相處的人",
"type": "A"
},
"test2": {
"title": "基本上,我盡力衛護本身的利益",
"type": "G"
}
}, {
"test1": {
"title": "一直而來,我屬於自我肯定,並且推動自己成功",
"type": "C"
},
"test2": {
"title": "我為人謙遜,並且用自己的步伐做事",
"type": "A"
}
}, {
"test1": {
"title": "我對自己太過認真及嚴謹",
"type": "D"
},
"test2": {
"title": "我對自己太過縱容及任意妄為",
"type": "I"
}
}, {
"test1": {
"title": "組織資源及實踐計劃是我的強項",
"type": "G"
},
"test2": {
"title": "產生嶄新意念及令身邊的人對這些意念感覺興奮是我的強項",
"type": "I"
}
}, {
"test1": {
"title": "我引自己的清晰度及客觀態度為傲",
"type": "H"
},
"test2": {
"title": "我引自己的可信度及承諾感為傲",
"type": "B"
}
}, {
"test1": {
"title": "我一生人大部份時間都是大起大落",
"type": "I"
},
"test2": {
"title": "我一生人大部份時間都是一個細水長流、平平穩穩的人",
"type": "A"
}
}, {
"test1": {
"title": "我入睡有困難",
"type": "H"
},
"test2": {
"title": "我很容易入睡",
"type": "A"
}
}, {
"test1": {
"title": "當我感覺憤怒的時候,我典型的反應就是破口大罵",
"type": "G"
},
"test2": {
"title": "當我感覺憤怒的時候,我典型的反應就是自我抽離",
"type": "C"
}
}, {
"test1": {
"title": "我經常設法與人拉近距離",
"type": "F"
},
"test2": {
"title": "我經常設法知道別人想從我那裡得到什麼好處",
"type": "B"
}
}, {
"test1": {
"title": "一般而言,我為人太過開放及天真",
"type": "A"
},
"test2": {
"title": "一般而言,我的防衛性太強",
"type": "B"
}
}, {
"test1": {
"title": "我頭腦清醒活力充沛",
"type": "I"
},
"test2": {
"title": "我忠於朋友及對人真心關懷",
"type": "F"
}
}, {
"test1": {
"title": "我覺得自己感情過份脆弱",
"type": "E"
},
"test2": {
"title": "我經常覺得別人對我的犧牲習以為常",
"type": "F"
}
}, {
"test1": {
"title": "一般而言,我缺乏自律",
"type": "I"
},
"test2": {
"title": "一般而言,我與人缺乏連繫",
"type": "H"
}
}, {
"test1": {
"title": "別人信任我,因為我充滿自信及能替他們的利益著想",
"type": "G"
},
"test2": {
"title": "別人信任我,因為我公正及會做「對」的事情",
"type": "D"
}
}, {
"test1": {
"title": "我經常因自己的神經質、缺乏安全感及自我懷疑感到困擾",
"type": "B"
},
"test2": {
"title": "我經常因自己的憤怒感、追求完美及缺乏耐性感到困擾",
"type": "D"
}
}, {
"test1": {
"title": "我太願意幫助別人,個人健康及處境因此受損",
"type": "F"
},
"test2": {
"title": "我太過注重個人的需求,人際關係因此受損",
"type": "E"
}
}, {
"test1": {
"title": "我傾情於令我激情的環境",
"type": "E"
},
"test2": {
"title": "我喜歡令我感覺平和的情境",
"type": "A"
}
}, {
"test1": {
"title": "我為人甚為圓滿、有魅力及有野心",
"type": "C"
},
"test2": {
"title": "我為人直接、循規蹈矩及有理想",
"type": "D"
}
}, {
"test1": {
"title": "當面對嶄新經驗的時候,我問自己這經驗對我的實用價值何在",
"type": "C"
},
"test2": {
"title": "當面對嶄新經驗的時候,我問自己是否會享受這經驗",
"type": "I"
}
}, {
"test1": {
"title": "當遭遇困難的時候,我能夠視而不見",
"type": "A"
},
"test2": {
"title": "當遭遇困難的時候,我會做一些令我自己開心的事情",
"type": "I"
}
}, {
"test1": {
"title": "我信賴我的朋友,而他們也知能夠信賴我",
"type": "B"
},
"test2": {
"title": "我從來沒有信賴別人,我習慣事事靠自己",
"type": "C"
}
}, {
"test1": {
"title": "我難以放下過去承諾,因此在生命中不能作出重要的轉變",
"type": "B"
},
"test2": {
"title": "我難以作出長期的承諾,因此可以在生命中輕易作出重大的轉變",
"type": "C"
}
}, {
"test1": {
"title": "當我與朋友辯論時,我一定強調自己的立場",
"type": "H"
},
"test2": {
"title": "當我與朋友辯駁時,我會得過且過以免傷和氣",
"type": "A"
}
}, {
"test1": {
"title": "我為人謹慎,經常替未發生的問題作好準備",
"type": "B"
},
"test2": {
"title": "我為人即興,選擇臨場發揮",
"type": "I"
}
}, {
"test1": {
"title": "當別人未能欣賞我為他們所做的事情,我會覺得憤怒",
"type": "F"
},
"test2": {
"title": "當別人不聽從我的意見時,我會覺得憤怒",
"type": "D"
}
}, {
"test1": {
"title": "我需要明白自己的感受,因此我經常內省",
"type": "E"
},
"test2": {
"title": "我必須做到要做的事情,因此很少內省",
"type": "G"
}
}, {
"test1": {
"title": "我傾向於向最壞的地方去想",
"type": "B"
},
"test2": {
"title": "我傾向於認為一切都會有最好的安排",
"type": "A"
}
}, {
"test1": {
"title": "我堅持所有事情都要做得正確,而這種態度有時令人不安",
"type": "D"
},
"test2": {
"title": "我不喜歡別人向我施壓,因此也不喜歡向人施壓",
"type": "A"
}
}, {
"test1": {
"title": "一般而言,我喜歡放開懷抱,「去到盡」",
"type": "I"
},
"test2": {
"title": "一般而言,我不喜歡失控",
"type": "D"
}
}, {
"test1": {
"title": "我引以為傲的是我在別人生命中所佔的重要地位",
"type": "F"
},
"test2": {
"title": "我引以為傲的是我對新事物的開放態度",
"type": "I"
}
}, {
"test1": {
"title": "我在人際關係方面的問題源自我過度敏感及事事個人化",
"type": "E"
},
"test2": {
"title": "我在人際關係方面的問題源自我不太尊重社會規條",
"type": "H"
}
}, {
"test1": {
"title": "我太過在意自己的表現是否較別人出色",
"type": "D"
},
"test2": {
"title": "我太過在意替別人將事情辦妥",
"type": "C"
}
}, {
"test1": {
"title": "能夠自給自足對我而言是非常重要的",
"type": "G"
},
"test2": {
"title": "被人珍惜及仰慕對我而言是非常重要的",
"type": "C"
}
}, {
"test1": {
"title": "我對所愛的人有強烈的佔有慾",
"type": "F"
},
"test2": {
"title": "我經常試探所愛的人,看看他們是否願意為我付出",
"type": "B"
}
}, {
"test1": {
"title": "我引以為傲的是自己的堅持力",
"type": "B"
},
"test2": {
"title": "我引以為傲的是我的原創力",
"type": "E"
}
}, {
"test1": {
"title": "很多人都欣賞我「打不死」的精神及幽默感",
"type": "I"
},
"test2": {
"title": "很多人都欣賞我默默無言的幹勁及對人的慷慨",
"type": "F"
}
}, {
"test1": {
"title": "太多時候我將焦點放在自己的身上",
"type": "E"
},
"test2": {
"title": "太多時候我將集中點放在別人的身上",
"type": "A"
}
}, {
"test1": {
"title": "我著重人際關係多於達到目標",
"type": "F"
},
"test2": {
"title": "我著重達到目標多於人際關係",
"type": "C"
}
}, {
"test1": {
"title": "我喜歡與人相處,又樂於支援別人",
"type": "F"
},
"test2": {
"title": "我為人含蓄及認真,喜歡與人討論時事",
"type": "D"
}
}, {
"test1": {
"title": "我很注重我自己的感受,不輕易放下過去",
"type": "E"
},
"test2": {
"title": "我不太留意自己的感受",
"type": "H"
}
}, {
"test1": {
"title": "我經常對自己要求過高",
"type": "D"
},
"test2": {
"title": "我經常感情用事又缺乏自律",
"type": "E"
}
}, {
"test1": {
"title": "我有時會逼人太甚",
"type": "F"
},
"test2": {
"title": "我有時與人相處時,立場不夠堅定",
"type": "A"
}
}, {
"test1": {
"title": "我寧願活在自己的小天地中",
"type": "H"
},
"test2": {
"title": "我需要這個世界知道我的存在",
"type": "G"
}
}, {
"test1": {
"title": "很多時,我太過投入自己的事情而導致自我孤立",
"type": "H"
},
"test2": {
"title": "很多時,我太過投入別人的世界而忽略了自己的事情",
"type": "F"
}
}, {
"test1": {
"title": "有多時候我缺乏自信",
"type": "B"
},
"test2": {
"title": "有多時候我祗是對自己有信心",
"type": "G"
}
}, {
"test1": {
"title": "需要與人對抗時,我經常會表現得過份直接及硬朗",
"type": "G"
},
"test2": {
"title": "需要與人對抗時,我經常會轉彎抹角、辭不達意",
"type": "C"
}
}, {
"test1": {
"title": "過去,我可能與朋友之間的關係過度親密",
"type": "F"
},
"test2": {
"title": "過去,我可能與朋友之間的距離太遠",
"type": "C"
}
}, {
"test1": {
"title": "我覺得許多人都侵略我的私人空間及對我有過多的要求",
"type": "H"
},
"test2": {
"title": "我覺得許多人都缺乏組織能力及沒有責任感",
"type": "D"
}
}, {
"test1": {
"title": "太多時候,我的自我懷疑令我裹足不前",
"type": "E"
},
"test2": {
"title": "我很少容許我的自我懷疑阻上我前進",
"type": "C"
}
}, {
"test1": {
"title": "我憂慮我沒有足夠的資源去完成份內的職責",
"type": "G"
},
"test2": {
"title": "我憂慮我沒有足夠的自律性去追求心目中的目標",
"type": "I"
}
}, {
"test1": {
"title": "一直以來我是個態度開放敢於嘗新的人",
"type": "H"
},
"test2": {
"title": "我不會自我掩飾,而且願意與人分享我的感受",
"type": "E"
}
}, {
"test1": {
"title": "我是一個直覺能力強的個人主義者",
"type": "E"
},
"test2": {
"title": "我是一個組織能力強、極有責任感的人",
"type": "D"
}
}, {
"test1": {
"title": "我時時都確保自己「後退有路」",
"type": "B"
},
"test2": {
"title": "我盡其量不去依賴別人",
"type": "H"
}
}, {
"test1": {
"title": "我通常都跟隨我的良知及理性做人",
"type": "D"
},
"test2": {
"title": "我通常跟隨我的感受及直覺倣人",
"type": "I"
}
}, {
"test1": {
"title": "我盡量不讓人覺得我是一個自私的人",
"type": "F"
},
"test2": {
"title": "我盡量不讓人覺得我是一個沉悶的人",
"type": "I"
}
}, {
"test1": {
"title": "為了不被別人的需求所掩蓋,我盡量避免與人親密",
"type": "H"
},
"test2": {
"title": "為了不想令人失望,我盡量避免與人親密",
"type": "C"
}
}, {
"test1": {
"title": "我的成就強差人意因為我沒有乘勢起飛",
"type": "E"
},
"test2": {
"title": "我的成就強差人意因為我「周身刀冇張利」",
"type": "I"
}
}, {
"test1": {
"title": "我經常難以作出抉擇",
"type": "B"
},
"test2": {
"title": "我絕少有困難作出抉擇",
"type": "G"
}
}, {
"test1": {
"title": "我經常強調我與朋友之間大不同之處",
"type": "E"
},
"test2": {
"title": "我經常強調我與朋友之間相同之處",
"type": "A"
}
}, {
"test1": {
"title": "我很少表露感情",
"type": "H"
},
"test2": {
"title": "我經常表露感情",
"type": "F"
}
}, {
"test1": {
"title": "我是一個充滿善意的支援者",
"type": "F"
},
"test2": {
"title": "我充滿衝勁,取得我應得的",
"type": "C"
}
}, {
"test1": {
"title": "就算我的朋友做錯了事,我對他們也不離不棄",
"type": "B"
},
"test2": {
"title": "我不會為了友情而放棄原則",
"type": "D"
}
}, {
"test1": {
"title": "我通常絕對不會炫耀我的才幹",
"type": "A"
},
"test2": {
"title": "我通常會令朋友清楚我的才幹",
"type": "C"
}
}, {
"test1": {
"title": "我傾向於遲疑不決及有拖延的壞習慣",
"type": "B"
},
"test2": {
"title": "我是一個大膽及專橫的人",
"type": "G"
}
}, {
"test1": {
"title": "別人時常覺得我舉棋不定",
"type": "B"
},
"test2": {
"title": "別人時常覺得我過份自信",
"type": "D"
}
}, {
"test1": {
"title": "我是一個好客兼且喜歡結交新朋友的人",
"type": "F"
},
"test2": {
"title": "我重視私人空間,不太喜歡與人相處",
"type": "E"
}
}, {
"test1": {
"title": "我盡量結識朋友,建立人際網絡",
"type": "C"
},
"test2": {
"title": "我很少結識朋友,也沒有刻意建立人際網絡",
"type": "E"
}
}, {
"test1": {
"title": "我看見別人犯錯時,不會作聲",
"type": "E"
},
"test2": {
"title": "我經常協助別人看到他們所犯的錯誤",
"type": "D"
}
}, {
"test1": {
"title": "我時常憂慮不被別人邀請參予活動",
"type": "F"
},
"test2": {
"title": "我時常憂慮參予別人的活動會令我分心",
"type": "D"
}
}, {
"test1": {
"title": "當我不喜歡某人時,我會客氣地與對方保持距離",
"type": "C"
},
"test2": {
"title": "當我不喜歡某人時,我會想盡方法讓對方知道",
"type": "B"
}
}, {
"test1": {
"title": "我通常說話謹慎、直接、不會轉彎抹角",
"type": "G"
},
"test2": {
"title": "我說話機靈、快速、生動",
"type": "I"
}
}, {
"test1": {
"title": "結識新朋友的時候,我會較為含蓄",
"type": "C"
},
"test2": {
"title": "我容易與人一見如故",
"type": "I"
}
}, {
"test1": {
"title": "我通常要等一段長時間才採取行動",
"type": "H"
},
"test2": {
"title": "我通常很快便能採取行動",
"type": "D"
}
}, {
"test1": {
"title": "我參予的事務均有潛能替我增進財富及知名度",
"type": "C"
},
"test2": {
"title": "為了做自己有興趣的工作,我寧願放棄名利",
"type": "H"
}
}, {
"test1": {
"title": "在大部份情況底下,我選擇做領袖",
"type": "G"
},
"test2": {
"title": "在大部份情況底下,我選擇讓別人做領袖",
"type": "A"
}
}, {
"test1": {
"title": "我盡量加快自己生命的步伐,活得精彩",
"type": "I"
},
"test2": {
"title": "我盡量令自己的生命穩定及安寧",
"type": "A"
}
}, {
"test1": {
"title": "我對生命具有強烈的信念,也有清晰的方向感",
"type": "D"
},
"test2": {
"title": "我對生命充滿疑慮,也經常懷疑所選擇的路向",
"type": "H"
}
}, {
"test1": {
"title": "我經常用大計劃及大承諾去推動身邊的人",
"type": "G"
},
"test2": {
"title": "我經常向人指出不跟隨我的意見之後果,以推動他們走正確的路",
"type": "D"
}
}, {
"test1": {
"title": "當與人發生磨擦的時候,我傾向於退縮",
"type": "E"
},
"test2": {
"title": "當與人發生磨擦的時候,我絕少退縮",
"type": "G"
}
}, {
"test1": {
"title": "被人施壓時,我會退縮",
"type": "H"
},
"test2": {
"title": "被人施壓時,我的侵略感會大增",
"type": "I"
}
}, {
"test1": {
"title": "我經常覺得需要表現得堅強",
"type": "G"
},
"test2": {
"title": "我經常覺得事事都要做得完美",
"type": "C"
}
}, {
"test1": {
"title": "我喜歡挑戰別人,令他們不再安於現狀",
"type": "G"
},
"test2": {
"title": "我是一個積極及有自律的人",
"type": "F"
}
}, {
"test1": {
"title": "我時常問艱深的問題,及保持獨立性",
"type": "H"
},
"test2": {
"title": "我時常希望保持穩定及心緒平靜",
"type": "A"
}
}, {
"test1": {
"title": "我的不投入態度令我產生許多人際問題",
"type": "A"
},
"test2": {
"title": "我急切令人依賴我的態度令我產生許多人際問題",
"type": "F"
}
}, {
"test1": {
"title": "我不畏懼與人對抗",
"type": "G"
},
"test2": {
"title": "我盡量避免與人對抗",
"type": "A"
}
}, {
"test1": {
"title": "我的思維傾向於探討性,充滿好奇及幻想",
"type": "H"
},
"test2": {
"title": "我的思想實際,集中於解決目前的問題",
"type": "B"
}
}, {
"test1": {
"title": "我經常做我需要做的事情",
"type": "B"
},
"test2": {
"title": "我經常做我想做的事情",
"type": "E"
}
}, {
"test1": {
"title": "我擅長於主宰環境",
"type": "G"
},
"test2": {
"title": "我擅長於敘述我內在的感受",
"type": "E"
}
}, {
"test1": {
"title": "我傾向於直接介入向人伸出援手",
"type": "F"
},
"test2": {
"title": "我傾向於教人如何自救",
"type": "G"
}
}, {
"test1": {
"title": "我的個人風格傾向於嚴肅及簡約",
"type": "H"
},
"test2": {
"title": "我的個人風格傾向於誇大",
"type": "I"
}
}, {
"test1": {
"title": "我重視追求我的興趣多於得到實際的成績",
"type": "H"
},
"test2": {
"title": "我為人實事求是,同時期望我的努力會產生實在的成果",
"type": "G"
}
}, {
"test1": {
"title": "我的好戰性格有時令人卻步",
"type": "G"
},
"test2": {
"title": "我的嚴肅態度有時令人卻步",
"type": "D"
}
}, {
"test1": {
"title": "能夠替人服務及照顧別人的需求對我而言是非常重要的",
"type": "F"
},
"test2": {
"title": "對我來說,能夠以不同的方式做事及看這個世界是很重要的",
"type": "H"
}
}, {
"test1": {
"title": "如果要在新與舊之間作出抉擇,我多數會揀新的那樣",
"type": "I"
},
"test2": {
"title": "我多數會選擇自己熟悉的東西,因為我不想冒險嘗新,揀了自己不喜歡的東西",
"type": "B"
}
}, {
"test1": {
"title": "我經常想起過往的事情",
"type": "E"
},
"test2": {
"title": "我經常思考我將會做的事情",
"type": "I"
}
}, {
"test1": {
"title": "當我缺乏安全感的時候,我會變得囂張及不理睬別人",
"type": "C"
},
"test2": {
"title": "當我缺乏安全感的時候,我的防衛性會增強,同時變得喜歡辯駁",
"type": "B"
}
}, {
"test1": {
"title": "在別人的心目中,我是一個大方得體、值得仰慕的人",
"type": "C"
},
"test2": {
"title": "在別人的心目中,我是一個古怪甚至冷漠的人",
"type": "H"
}
}, {
"test1": {
"title": "當我不知所措的時候,我會要求別人給我意見",
"type": "B"
},
"test2": {
"title": "當我不知所措的時候,我會嘗試用不同的方式解決問題",
"type": "I"
}
}, {
"test1": {
"title": "一般而言,我是個悲觀的人",
"type": "E"
},
"test2": {
"title": "一般而言,我是個樂觀的人",
"type": "A"
}
}, {
"test1": {
"title": "我明白很多時候我對人太過熱情",
"type": "F"
},
"test2": {
"title": "我明白我很多時候對人太過冷漠",
"type": "C"
}
}, {
"test1": {
"title": "對我來說,達到社會的既定制約是很重要的",
"type": "E"
},
"test2": {
"title": "對我來說,達到社會的既定制約沒有什麼重要性",
"type": "B"
}
}, {
"test1": {
"title": "過去幾年以來,我的價值觀及生活方式經歷多次的轉變",
"type": "C"
},
"test2": {
"title": "過去幾年以來,我的價值觀及生活方式都保持不變",
"type": "D"
}
}, {
"test1": {
"title": "我覺得自己充滿陽光氣息,隨遇而安",
"type": "A"
},
"test2": {
"title": "我覺得自己是個認真及有尊嚴的人",
"type": "D"
}
}, {
"test1": {
"title": "我給予許多人關懷及照顧",
"type": "F"
},
"test2": {
"title": "我給予許多人鼓勵及方向感",
"type": "G"
}
}, {
"test1": {
"title": "成為眾人焦點所在對我而言是自然不過的現象",
"type": "C"
},
"test2": {
"title": "成為眾人焦點所在令我覺得不自然",
"type": "E"
}
}, {
"test1": {
"title": "我不善於處理細節",
"type": "I"
},
"test2": {
"title": "我善於處理細節",
"type": "C"
}
}, {
"test1": {
"title": "過求悲觀及經常投訴令我產生很多人際之間的問題",
"type": "B"
},
"test2": {
"title": "過度的操控及專制令我產生很多人際之間的問題",
"type": "G"
}
}, {
"test1": {
"title": "在危急的情況底下,我傾向於做「塘邊鶴」",
"type": "H"
},
"test2": {
"title": "在危急的情況底下,我多數會置身事中",
"type": "G"
}
}, {
"test1": {
"title": "我傾向於信任我的感受並依據之行事,然後隨遇而安",
"type": "F"
},
"test2": {
"title": "我很少依據我的感受行事,因為我害怕這樣做會製造更多的問題",
"type": "A"
}
}, {
"test1": {
"title": "別人對我產生興趣因為我為人外向,而且對人有興趣",
"type": "F"
},
"test2": {
"title": "別人對我產生興趣因為我為人含蓄、安靜及有深度",
"type": "E"
}
}, {
"test1": {
"title": "我需要做別人心目中的強者,因此我沒有時間去處理自己的感受及恐懼",
"type": "G"
},
"test2": {
"title": "我不懂得處理自己的感受及恐懼,因此無法成為人別人心目中的強者",
"type": "E"
}
}, {
"test1": {
"title": "我對人太過干預,因此製造了許多人際問題",
"type": "F"
},
"test2": {
"title": "我慣性逃避人際溝通,因此製這了許多人際問題",
"type": "B"
}
}, {
"test1": {
"title": "我在人面前表現得較實際堅強",
"type": "G"
},
"test2": {
"title": "我在人面前表現得較實際更關懷別人",
"type": "F"
}
}, {
"test1": {
"title": "吸引到我的課題可能會別人感覺恐懼或不安",
"type": "H"
},
"test2": {
"title": "我選擇不去花費時間研究令我感覺恐懼或不安的課題",
"type": "A"
}
}, {
"test1": {
"title": "時不與我的逆境令我更堅強",
"type": "C"
},
"test2": {
"title": "時不與我的逆境令我洩氣及退縮",
"type": "A"
}
}, {
"test1": {
"title": "很可能我屬於過份被動及不投入",
"type": "A"
},
"test2": {
"title": "很可能我傾向於過度操控別人",
"type": "F"
}
}, {
"test1": {
"title": "一般而言,我的情緒屬於穩定",
"type": "C"
},
"test2": {
"title": "一般而言,我的情緒波動頗大",
"type": "I"
}
}, {
"test1": {
"title": "我喜歡在高壓甚至困難的環境中運作",
"type": "G"
},
"test2": {
"title": "我討厭在高壓及困難的環境中運作",
"type": "A"
}
}, {
"test1": {
"title": "我運用身體的接觸去令人感受我對他們的關懷",
"type": "F"
},
"test2": {
"title": "我認為真正的關懷並不需要用身體的接觸去表達",
"type": "D"
}
}, {
"test1": {
"title": "我主要的挑戰之一是克服惰性",
"type": "A"
},
"test2": {
"title": "我主要的挑戰之一是令自己慢下來",
"type": "I"
}
}, {
"test1": {
"title": "我需要有強烈的歸屬感",
"type": "B"
},
"test2": {
"title": "我需要有強烈的平衡感",
"type": "D"
}
}, {
"test1": {
"title": "我對自己能夠彈性處理事情引以為傲,因為目前看來重要或適宜的選擇都會改變",
"type": "C"
},
"test2": {
"title": "我對自己能夠堅持立場引以為傲,因為我深信自己所代表的一切",
"type": "D"
}
}, {
"test1": {
"title": "追求個人興趣比較個人舒適及安全感重要",
"type": "H"
},
"test2": {
"title": "擁有個人舒適及安全感比較追求個人興趣更重要",
"type": "B"
}
}, {
"test1": {
"title": "我傾向於做人積極及有焦點",
"type": "H"
},
"test2": {
"title": "我傾向於做人即興及有趣味",
"type": "I"
}
}, {
"test1": {
"title": "我不是一個敢言的人",
"type": "E"
},
"test2": {
"title": "我絕對敢言,經常說出別人不敢講的說話",
"type": "I"
}
}, {
"test1": {
"title": "我傾向於抽離及時常若有所思",
"type": "H"
},
"test2": {
"title": "我傾向於情緒化及自我中心",
"type": "E"
}
}, {
"test1": {
"title": "別人相信我的知識及洞悉力",
"type": "H"
},
"test2": {
"title": "別人信賴我的決斷與個人力量",
"type": "G"
}
}, {
"test1": {
"title": "我的抽離態度不時觸怒別人",
"type": "E"
},
"test2": {
"title": "我慣性教人如何做事的態度不時觸怒別人",
"type": "D"
}
}, {
"test1": {
"title": "生命那麼美好,我不明白為何有些人祗集中去看負面的一邊",
"type": "A"
},
"test2": {
"title": "生命那麼糟糕,我不明白為何有些人還是那麼開心",
"type": "D"
}
}]
};<file_sep>enneagram
======
九型人格测试 Windows 版,使用 node-webkit 技术开发
<file_sep>////////////////////////////////////////////////////////////////////////////////
// 名称: 主程序
// 作者: Steven
// 说明: Require jQuery
// 更新: 2014-8-1
////////////////////////////////////////////////////////////////////////////////
// Main
(function($) {
// Helpers
var isIE6 = !!window.ActiveXObject && !window.XMLHttpRequest;
function isString(val) {
return Object.prototype.toString.call(val) === '[object String]';
}
function $id(id) {
// return 'string' === typeof id ? document.getElementById(id) : id;
// return $.type('test') === 'string' ? document.getElementById(id) : id;
return isString(id) ? document.getElementById(id) : id;
}
// 文档加载完执行
$(function() {
// 通用变量
var $html = $('html');
// var $header = $('header');
var $username = $('#username');
var $swiper = $('#swiper-responsive');
var $counter = $('#js-counter');
var animationend = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
// Mobilebone
Mobilebone.callback = function(pagein, pageout) {
if (pagein.id === 'page-tests') {
$swiper.data('swiper').reInit();
$swiper.data('swiper').swipeTo(0);
}
if (pagein.id === 'page-home') {
$html.addClass('home');
} else {
$html.removeClass('home');
}
};
// 输入名字
$username.on('keyup', function() {
var $btn = $(this).next('a');
var val = $.trim(this.value);
$btn[val ? 'removeClass' : 'addClass']('disabled');
// 按钮显示效果
if (val) {
// $btn.addClass('animated bounceInDown').one(animationend, function() {
// $(this).removeClass('animated bounceInDown');
// });
$btn.removeClass('bounceOutUp').addClass('animated bounceInDown');
} else {
$btn.removeClass('bounceInDown').addClass('animated bounceOutUp');
}
}).on('blur', function() {
this.value = $.trim(this.value);
}).trigger('keyup');
// 如果没有输入姓名,开始按钮默认不可用
$('#page-home').on('click', 'a.disabled', function() {
return false;
});
// 初始化 Swiper
// tests.list = tests.list.splice(-5);
$swiper[0].innerHTML = template('tests', tests);
$swiper.swiper({
// pagination: '.pagination',
// paginationClickable: true,
// noSwiping: true,
simulateTouch: false,
onFirstInit: function(swiper) {
var total = swiper.slides.length;
var index = swiper.activeIndex + 1;
var left = total - index;
$counter.children('.current').html(index);
$counter.children('.left').html(left);
$counter.children('.total').html(total);
$(swiper.container).removeClass('fn-vh');
},
onSlideChangeEnd: function(swiper) {
var index = swiper.activeIndex + 1;
var left = swiper.slides.length - index;
$counter.children('.current').html(index);
$counter.children('.left').html(left);
}
}).on('click', '.swiper-nav a', function(e) {
// console.log($(this))
$(e.delegateTarget).data('swiper').swipeNext();
}).on('change', 'label', function(e) { // 这里有一个坑,用 click 事件,input 会冒泡,会导致触发两次
var $this = $(this);
var $slide = $this.parents('.swiper-slide');
var swiper = $swiper.data('swiper');
if (swiper.activeIndex === swiper.slides.length - 1) {
var $checked = $swiper.find('input:checked');
window.location.hash = '#&page-chart';
// 初始化图表
var ichart = echarts.init(document.getElementById('chart'));
var username = $username.val();
var testData = {};
var tags = ['D', 'F', 'C', 'E', 'H', 'B', 'I', 'J', 'A'];
$.each(tags, function(i, v) {
testData[v] = $checked.filter('[value=' + v + ']').length || 0;
});
// console.log(testData);
// 为图表对象加载数据
ichart.setOption({
title: {
text: username + '的九型人格测试图表',
// subtext: '纯属虚构',
x: 'center'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
x: 'left',
data: [
'1号: ' + testData[tags[0]],
'2号: ' + testData[tags[1]],
'3号: ' + testData[tags[2]],
'4号: ' + testData[tags[3]],
'5号: ' + testData[tags[4]],
'6号: ' + testData[tags[5]],
'7号: ' + testData[tags[6]],
'8号: ' + testData[tags[7]],
'9号: ' + testData[tags[8]]
]
},
toolbox: {
show: true,
feature: {
mark: {
show: false
},
dataView: {
show: true,
readOnly: false
},
magicType: {
show: true,
type: ['pie', 'funnel'],
option: {
funnel: {
x: '25%',
width: '50%',
funnelAlign: 'left',
max: 1548
}
}
},
restore: {
show: true
},
saveAsImage: {
show: false
}
}
},
// calculable: true,
series: [{
name: '详细测试结果',
type: 'pie',
radius: '55%',
center: ['50%', '50%'],
data: [{
value: testData[tags[0]],
label: 'xx',
name: '1号: ' + testData[tags[0]]
}, {
value: testData[tags[1]],
label: 'label',
name: '2号: ' + testData[tags[1]]
}, {
value: testData[tags[2]],
label: 'label',
name: '3号: ' + testData[tags[2]]
}, {
value: testData[tags[3]],
label: 'label',
name: '4号: ' + testData[tags[3]]
}, {
value: testData[tags[4]],
label: 'label',
name: '5号: ' + testData[tags[4]]
}, {
value: testData[tags[5]],
label: 'label',
name: '6号: ' + testData[tags[5]]
}, {
value: testData[tags[6]],
label: 'label',
name: '7号: ' + testData[tags[6]]
}, {
value: testData[tags[7]],
label: 'label',
name: '8号: ' + testData[tags[7]]
}, {
value: testData[tags[8]],
label: 'label',
name: '9号: ' + testData[tags[8]]
}]
}]
});
// var pieData = [{
// value: $checked.filter('[value=D]').length,
// color: '#E87C25',
// highlight: '#EEA366',
// // label: 'D'
// label: '1号'
// }, {
// value: $checked.filter('[value=F]').length,
// color: '#FE8463',
// highlight: '#FEA891',
// // label: 'F'
// label: '2号'
// }, {
// value: $checked.filter('[value=C]').length,
// color: '#FCCE10',
// highlight: '#FCDC57',
// // label: 'C'
// label: '3号'
// }, {
// value: $checked.filter('[value=E]').length,
// color: '#27727B',
// highlight: '#679CA2',
// // label: 'E'
// label: '4号'
// }, {
// value: $checked.filter('[value=H]').length,
// color: '#F3A43B',
// highlight: '#F6BF75',
// // label: 'H'
// label: '5号'
// }, {
// value: $checked.filter('[value=B]').length,
// color: '#B5C334',
// highlight: '#CBD570',
// // label: 'B'
// label: '6号'
// }, {
// value: $checked.filter('[value=I]').length,
// color: '#60C0DD',
// highlight: '#8FD2E7',
// // label: 'I'
// label: '7号'
// }, {
// value: $checked.filter('[value=G]').length,
// color: '#28A428',
// highlight: '#68BF68',
// // label: 'G'
// label: '8号'
// }, {
// value: $checked.filter('[value=A]').length,
// color: '#C1232B',
// highlight: '#D3656A',
// // label: 'A'
// label: '9号'
// }];
// var ctx = $('<canvas width="300" height="300"/>').appendTo($('#chart').empty())[0].getContext('2d');
// // var ctx = $id('chart').getContext('2d');
// // var chart = $id('chart');
// // var ctx = chart.getContext('2d');
// // ctx.clearRect(0, 0, chart.width, chart.height)
// new Chart(ctx).Pie(pieData);
return;
}
$this.parent().animate({
'right': '-50px'
}, 500, function() {
$(this).css('right', 'auto');
swiper.swipeNext();
// $(this).animate({'right': 0}, 0, function() {
// swiper.swipeNext();
// });
});
// setTimeout(function() {
// $swiper.data('swiper').swipeNext();
// }, 300);
});
// 重置测试
$('#page-chart').on('click', '.content > a', function() {
$swiper.find(':radio').prop('checked', false);
// window.location.reload();
});
});
})(jQuery);<file_sep>#! sh
app_name="system-info"
# 创建app.nw文件
rm -rf output
cd ../ && rm -rf output && mkdir output
cp -r $app_name/* output
rm -rf output/Info.plist output/build.sh output/app.icns
cd output/
find . -type d -name ".svn" | xargs rm -rf
zip -r ../app.nw * > /dev/null;
rm -rf * && cd ../ && mv app.nw output/
mv output $app_name/ && cd $app_name
echo "create nw file success!"
#下载基础包
svn co svn://localhost/node-webkit-base output > /dev/null
#创建mac版本app
cd output
unzip mac-os-x.zip -d mac-os-x > /dev/null
rm -rf mac-os-x.zip mac-os-x/nwsnapshot
if [ -f ../Info.plist ];then
cp ../Info.plist mac-os-x/node-webkit.app/Contents/
fi
cp app.nw mac-os-x/node-webkit.app/Contents/Resources/
if [ -f ../app.icns ];then
cp ../app.icns mac-os-x/node-webkit.app/Contents/Resources/
fi
mv mac-os-x/node-webkit.app mac-os-x/$app_name.app
echo "create mac os app success!"
#创建windows版本app
unzip win-32.zip -d win-32 > /dev/null
rm -rf win-32.zip win-32/nwsnapshot
cp app.nw win-32/ && cd win-32
cat nw.exe app.nw > $app_name.exe
rm -rf nw.exe nwsnapshot.exe
cd ..
echo "create windows app success!"
#删除app.nw
rm -f app.nw<file_sep>// 引入 gulp
var gulp = require('gulp');
// 引入组件
var nib = require('nib');
// var btStylus = require('bootstrap-stylus');
var stylus = require('gulp-stylus');
// var cssmin = require('gulp-cssmin');
// var seajs = require('gulp-seajs');
// var CMDTrans = require('gulp-cmd-transport');
var coffee = require('gulp-coffee');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var jshint = require('gulp-jshint');
// var concat = require('gulp-concat');
// var clean = require('gulp-clean');
// var clean = require('gulp-rimraf');
var del = require('del');
var copy = require('gulp-copy');
var zip = require('gulp-zip');
// var imagemin = require('gulp-imagemin');
// var changed = require('gulp-changed');
// var watch = require('gulp-watch');
// var livereload = require('gulp-livereload');
var app = {
src: './**',
destfiles: [
'./*.htm?',
'./package.json',
// './app.png',
'./css/**',
'./js/**',
'./img/**',
'!./**/*-debug.*',
'!./**/*.styl',
'!./**/*.coffee',
'!./**/*.psd',
'!./**/bower_components/**',
'!./**/spm_modules/**',
'!./**/bak/**',
'!./**/*-bak.*'
],
zipfiles: ['./dist/**'],
dest: 'dist',
watch: ['./**/*.php', './**/*.htm', './**/*.html', './**/*.css', './**/*.js', './img/**/*'],
stylus: {
src: 'css/main.styl',
dest: 'css',
watch: 'css/*.styl'
},
coffee: {
src: 'js/*.coffee',
dest: 'js',
watch: 'js/*.coffee'
},
js: {
debug: 'js/*-debug.js',
src: 'js/*.js',
dest: 'js',
watch: 'js/*-debug.js'
},
img: {
src: 'img/**/*',
dest: 'img',
watch: 'img/**/*'
}
};
// 删除目标文件夹
gulp.task('clean', function(cb) {
// return gulp.src(app.dest, {read: false})
// .pipe(clean());
del(app.dest, cb);
});
// 复制文件到目标文件夹
// gulp.task('copy', ['clean'], function() {
// return gulp.src(app.destfiles)
// .pipe(gulp.dest(app.dest));
// });
gulp.task('copy', ['clean'], function() {
return gulp.src(app.destfiles)
.pipe(copy(app.dest));
});
// 压缩目标文件夹中的文件
gulp.task('zip', ['copy'], function() {
gulp.src(app.zipfiles)
.pipe(zip('app.nw'))
.pipe(gulp.dest(app.dest));
});
// 创建 stylus 任务
gulp.task('stylus', function() {
gulp.src(app.stylus.src)
.pipe(stylus({
compress: true,
use: [nib()]
}))
// .pipe(cssmin())
.pipe(gulp.dest(app.stylus.dest));
// .pipe(livereload());
});
// 创建 coffee 任务
gulp.task('coffee', function() {
return gulp.src(app.coffee.src)
.pipe(coffee())
.pipe(uglify())
.pipe(gulp.dest(app.coffee.dest));
});
// 合并压缩 JS
gulp.task('jsmin', function() {
gulp.src(app.js.debug)
// .pipe(watch())
// .pipe(concat('all.js'))
// .pipe(rename({suffix: '-min'}))
.pipe(rename(function(path) {
path.basename = path.basename.replace(/-debug$/, '');
}))
.pipe(uglify())
.pipe(gulp.dest(app.js.dest));
});
// 检查脚本
gulp.task('jshint', function() {
gulp.src(app.js.debug)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Copy all static images
// gulp.task('img', function() {
// return gulp.src(app.img.src)
// .pipe(imagemin({
// optimizationLevel: 5
// }))
// .pipe(gulp.dest('build/img'));
// });
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(app.stylus.watch, ['stylus']);
// gulp.watch(app.coffee.watch, ['coffee']);
gulp.watch(app.js.watch, ['jshint', 'jsmin']);
// gulp.watch(app.img.src, ['img']);
});
// livereload task
// gulp.task('livereload', function() {
// livereload.lissten();
// ['copy'], gulp.watch(app.watch).on('change', livereload.changed);
// })files;
// The default task (called when you run `gulp` from cli)
// gulp.task('default', ['stylus', 'coffee', 'jsmin', 'watch']);
gulp.task('default', ['stylus', 'jshint', 'jsmin', 'watch']);
// 打包文件到目录
gulp.task('build', ['clean', 'copy', 'zip']); | 7335a6802677372e56bd3d90580e98e0991cd410 | [
"JavaScript",
"Markdown",
"Shell"
] | 5 | JavaScript | wangwen1220/enneagram | e47d638cc602c85b2bcae2eeabead896c28241f3 | 04b5a38730ade19dc3b71d0b16ce3045b7c0b186 |
refs/heads/master | <file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class communityCategoryPage extends BasePage {
public communityCategoryPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//title[text()='Softvision - Community Archives']"));
System.out.println("------------------------");
System.out.println("Community category page was found.");
System.out.println("------------------------");
}
}
<file_sep>package softvisionProject.testcases.ServicesPageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.productDesignPage;
import softvisionProject.POM.ServicesPage;
import softvisionProject.testcases.BaseTest;
public class openProductDesignPage extends BaseTest {
@Test
public void clickDeJ() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("Services");
ServicesPage services = new ServicesPage(driver);
services.defineUserJourneys();
productDesignPage product = new productDesignPage(driver);
}
}
<file_sep>package softvisionProject.testcases.ContactPageTestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.lang.String;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.*;
import softvisionProject.POM.BasePage;
import softvisionProject.POM.ContactPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class openSoftVisionContactPage extends BaseTest {
//open contact page from softvision.com
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
titleAssert("Softvision, your Technology Partner for Digital Innovation");
home.acceptCookieMethod();
openMenuPage("Contact");
ContactPage contactAssert = new ContactPage(driver);
urlAssert("contact");
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class xamarinCategoryPage extends BasePage {
public xamarinCategoryPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//span[text()='Xamarin']"));
System.out.println("-----------------------");
System.out.println("Xamarin category page was found.");
System.out.println("-----------------------");
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.GuildsPage;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.softwareTechnologyCategoryPage;
import softvisionProject.testcases.BaseTest;
public class GuildsPageSoftTechHashtagTestCase extends BaseTest {
// Test Case
// open the software&technology hashtag from the guilds page on softvision.com, hashtag related to article:
// Getting started with Xamarin.
//
@Test
public void software_technology() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Guilds");
GuildsPage guilds = new GuildsPage(driver);
softwareTechnologyCategoryPage soft = guilds.softTech();
}
}
<file_sep>package softvisionProject.testcases.NewsPage;
import org.testng.annotations.Test;
import softvisionProject.POM.companyNewsCategoryPage;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.NewsPage;
import softvisionProject.testcases.BaseTest;
public class NewsElementCompanyNews extends BaseTest {
// Test Case:
// on news page from softvision.com click the company news hashtag from the second article:
// Top Drupal Developers Attend DrupalCon Seattle.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("News");
NewsPage news = new NewsPage(driver);
news.clickCompanyNewsBtn();
companyNewsCategoryPage company = new companyNewsCategoryPage(driver);
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class NewsPage extends BasePage {
public NewsPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//title[text()='Softvision - News']"));
System.out.println("------------------------");
System.out.println("News page was found.");
System.out.println("------------------------");
}
// Page Factory
@FindBy(xpath = "//*[@id=\"post-25057\"]/div[1]/a")
WebElement article1;
@FindBy(xpath = "//article[@id='post-25057']//a[text()='Design thinking']")
WebElement designThinking;
@FindBy(xpath = "//article[@id='post-25030']//a[text()='Company news']")
WebElement companyNews;
@FindBy(xpath = "//article[@id='post-25202']//a[text()='Community']")
WebElement community;
@FindBy(xpath = "/html/body/div[2]/div/div/div/div[2]/div/div[1]/div[1]/ul/li[3]/a")
WebElement eventsTab;
@FindBy(xpath = "//article[@id='post-24938']//a[text()='Technical Agility Conference 2019']")
WebElement eventsTabArticle1;
//
// Methods
public void article1() {
article1.click();
}
public void designThinking() {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(designThinking));
if (designThinking.isDisplayed()) {
System.out.println("- design thinking btn display: pass");
designThinking.click();
} else {
System.out.println("- design thinking btn display: fail");
}
}
public void clickCompanyNewsBtn() {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(companyNews));
checkIfElemIsDisplayedAndClickOnIt(companyNews);
}
public void clickCommunityBtn() {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(community));
checkIfElemIsDisplayedAndClickOnIt(community);
}
public void eventsTab() {
if (eventsTab.isDisplayed()) {
System.out.println("- events tab display: pass");
eventsTab.click();
} else {
System.out.println("- events tab display: fail");
}
}
public void eventsTabArticle1() {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='loading' and @style='position: absolute; width: 100%; height: 100%; background: rgba(250, 250, 250, 0.8); z-index: 10001; text-align: center; display: initial; left: 0px; top: 0px;']")));
wait.until(ExpectedConditions.elementToBeClickable(eventsTabArticle1));
if(eventsTabArticle1.isDisplayed()) {
System.out.println("- article nr.1 display: pass");
eventsTabArticle1.click();
} else {
System.out.println("- article nr.1 display: fail");
}
}
//
}
<file_sep>package softvisionProject.testcases.HomePageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.WindowsServerPage;
import softvisionProject.testcases.BaseTest;
public class clickHomePageGetinTouchBtn extends BaseTest {
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.getInTouchBtn();
WindowsServerPage win = new WindowsServerPage(driver);
}
}
<file_sep>package softvisionProject.testcases.HomePageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class clickSolutionsTab extends BaseTest {
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.solutionsPage();
}
}
<file_sep>package softvisionProject.testcases;
import com.beust.jcommander.Parameter;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import org.testng.annotations.*;
import java.lang.String;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class BaseTest {
public static WebDriver driver;
public BaseTest() {}
public BaseTest(WebDriver driver) {
this.driver = driver;
}
// JS Executor
JavascriptExecutor js = (JavascriptExecutor) driver;
//
// Methods
public void goToSoftVision() {
driver.navigate().to("https://softvision.com");
}
// open any page
public void openMenuPage(String pageName) {
String desiredPage = "//span[text()='" + pageName + "']";
WebElement menuPage = driver.findElement(By.xpath(desiredPage));
menuPage.click();
}
public void openSecondaryPage(String subPageName) {
String desiredPage = "//span[text()='" + subPageName + "']";
WebElement subPage = driver.findElement(By.xpath(desiredPage));
subPage.click();
}
// assertions url and title.
public void urlAssert(String pageName) {
String expectedPageUrl = "https://www.softvision.com/" + pageName + "/";
Assert.assertEquals(driver.getCurrentUrl(), expectedPageUrl);
System.out.println("- " + pageName + " url: pass");
}
/* public void mainPageAssert() {
String expectedMainUrl = "https://www.softvision.com/";
Assert.assertEquals(driver.getCurrentUrl(), expectedMainUrl);
System.out.println("Main assert done");
} */
public void titleAssert(String titleName) {
String expectedTitle = titleName;
Assert.assertEquals(driver.getTitle(), expectedTitle);
System.out.println("- title: pass");
}
//
@Parameters({"browserName"})
@BeforeClass
public void initializeBrowser(String browserName) {
driver = chooseBrowser(browserName);
}
@AfterClass
public void e_stop() {
driver.quit();
}
}
<file_sep>package softvisionProject.testcases.HomePageTestCases;
import softvisionProject.POM.BasePage;
import softvisionProject.POM.HomePage;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.*;
import softvisionProject.testcases.BaseTest;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class openSoftVisionHP extends BaseTest {
//open home page from softvision.com
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
titleAssert("Softvision, your Technology Partner for Digital Innovation");
}
}
<file_sep>package softvisionProject.testcases.ContactPageTestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.lang.String;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.*;
import softvisionProject.POM.BasePage;
import softvisionProject.POM.ContactPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class inputSoftVisionContactPageContactUsForm extends BaseTest {
// open softvision.com contact page and manipulate the contact form.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage homeAssert = new HomePage(driver);
titleAssert("Softvision, your Technology Partner for Digital Innovation");
homeAssert.acceptCookieMethod();
openMenuPage("Contact");
ContactPage contactUsForm = new ContactPage(driver);
urlAssert("contact");
contactUsForm.InputNamePlease("Bogdan");
contactUsForm.InputEmailPlease("<EMAIL>");
//contactUsForm.OpenDropDownList("Press");
contactUsForm.clickRegardingList("Press");
contactUsForm.InputMessagePlease("Please check my request");
/* DropDownList choices:
General
Work With Us
Business
Press
Microsoft
*/
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class AustinStudioPage extends BasePage {
public AustinStudioPage (WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//*[@id=\"gradient-background\"]/div/div/div/div/div/div/div/div/div/div/div/div/h1"));
System.out.println("------------------------");
System.out.println("Austin studio page was found.");
System.out.println("------------------------");
}
}
<file_sep>package Steps.ContactPage;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import softvisionProject.POM.ContactPage;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.ServicesPage;
import softvisionProject.testcases.BaseTest;
public class ServicesPageSteps extends BaseTest {
public HomePage home;
public ServicesPage service;
private void initializeServicesPage() {
if(service == null) {
service = new ServicesPage(driver);
}
}
// Scenario I
@When("^Services: SoftVision and cookie accepted$")
public void onSoftVisionAndCookieAccepted() {
home = new HomePage(driver);
home.acceptCookieMethod();
}
@Then("^Open ServicesPage$")
public void openServicesPage() {
openMenuPage("Services");
initializeServicesPage();
}
// Scenario II
@And("^Click Define User Journeys WebElement$")
public void clickDefineUserJourneysWebElement() {
service.defineUserJourneys();
}
@And("^Click Play on YT video$")
public void clickPlayOnYTVideo() {
service.playWeArePeopleVideo();
}
@And("^Check list item presence$")
public void checkListItemPresence() {
service.listItem();
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.*;
import softvisionProject.POM.*;
import softvisionProject.framework.helperClass;
import softvisionProject.testcases.BaseTest;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class openSoftVisionApproachPages extends BaseTest {
//open all of the approach pages on softvision.com
//
@Test (priority = 1)
public void openHomePage() {
goToSoftVision();
HomePage homeAssert = new HomePage(driver);
homeAssert.acceptCookieMethod();
openMenuPage("Contact");
ContactPage contactAssert = new ContactPage(driver);
contactAssert.hoverApproachBtn();
}
@Test (priority = 2)
public void openEcoSystemPage() {
openMenuPage("Our Ecosystem");
EcoSystemPage systemAssert = new EcoSystemPage(driver);
systemAssert.hoverApproachBtn();
}
@Test (priority = 3)
public void openGuildsPage() {
openMenuPage("Guilds");
GuildsPage guildsAssert = new GuildsPage(driver);
guildsAssert.hoverApproachBtn();
}
@Test (priority = 4)
public void openPodsPage() {
openMenuPage("Pods");
PodsPage podsAssert = new PodsPage(driver);
podsAssert.hoverApproachBtn();
}
@Test (priority = 5)
public void openAlliancesPage() {
openMenuPage("Alliances");
AlliancesPage alliancesAssert = new AlliancesPage(driver);
}
}
<file_sep>package softvisionProject.testcases.ContactPageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.AustinStudioPage;
import softvisionProject.POM.ContactPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class openAustinStudio extends BaseTest {
// open contact/austinstudio from softvision.com.
//
@Test
public void openContactPage() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("Contact");
ContactPage contact = new ContactPage(driver);
contact.austinStudio();
AustinStudioPage austin = new AustinStudioPage(driver);
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class PodsPage extends BasePage {
public PodsPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//title[text()='Softvision - Pods']"));
System.out.println("------------------------");
System.out.println("Pods page was found.");
System.out.println("------------------------");
}
// Page Factory
@FindBy(xpath = "//*[@id=\"slider_with_content\"]/div[1]/div[2]/div/div[1]/div/div[1]/div/a/img")
WebElement podMitosis;
@FindBy(xpath = "//*[@id=\"slider_with_content\"]/div[1]/div[2]/div/div[1]/div/div[2]/div/a/img")
WebElement framework;
@FindBy(xpath = "//*[@id=\"slider_with_content\"]/div[1]/div[2]/div/div[1]/div/div[3]/div/a/div")
WebElement gameOfPods;
@FindBy(xpath = "//*[@id=\"static_content\"]/div/div/div[1]/img")
WebElement podPng;
@FindBy(xpath = "//*[@id=\"static_image_video\"]/div/div/div[2]/div/p[1]")
WebElement innovationP1;
//
// Methods
public void clickPodMitosis() {
if (podMitosis.isDisplayed()) {
System.out.println("- pod mitosis: pass");
podMitosis.click();
}
else{
System.out.println("- pod mitosis: fail");
}
}
public void clickFramework() {
if (framework.isDisplayed()) {
System.out.println("- framework: pass");
framework.click();
} else {
System.out.println("- framework: fail");
}
}
public void clickGameOfPods() {
if (gameOfPods.isDisplayed()) {
System.out.println("- game of pods: pass");
gameOfPods.click();
} else {
System.out.println("- game of pods: fail");
}
}
public void checkPodPng() {
if (podPng.isDisplayed()) {
System.out.println("- pod chart display: pass");
} else{
System.out.println("- pod chart display: fail");
}
}
public void checkInnovationFirstParagraph(){
if (innovationP1.isDisplayed()) {
System.out.println("- first paragraph found: pass");
} else{
System.out.println("- first paragraph found: fail");
}
}
//
}
<file_sep>package Steps.ContactPage;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.PodsPage;
import softvisionProject.testcases.BaseTest;
public class PodsPageSteps extends BaseTest {
public HomePage home;
public PodsPage pod;
private void initializePodsPage() {
if(pod == null) {
pod = new PodsPage(driver);
}
}
// Scenario I
@When("^Pods on SoftVision and cookie accepted$")
public void podsOnSoftVisionAndCookieAccepted() {
home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
}
@Then("^Open PodsPage$")
public void openPodsPage() {
openMenuPage("Pods");
initializePodsPage();
}
// Scenario II
@And("^Click pod mitosis$")
public void clickPodMitosis() {
pod.clickPodMitosis();
}
@And("^Click framework$")
public void clickFramework() {
pod.clickFramework();
}
@And("^Click game of pods$")
public void clickGameOfPods() {
pod.clickGameOfPods();
}
// Scenario III
@And("^Check paragraph$")
public void checkParagraphs() {
pod.checkInnovationFirstParagraph();
}
@And("^Check PNG$")
public void checkPNG() {
pod.checkPodPng();
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import softvisionProject.framework.JavaMap;
import java.util.HashMap;
import java.util.Set;
import static softvisionProject.framework.JavaMap.getNameEmail;
public class CareersPage extends BasePage {
public CareersPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//title[text()='Technology Jobs and Careers – Softvision']"));
System.out.println("------------------------");
System.out.println("Careers page was found.");
System.out.println("------------------------");
}
// Page Factory
@FindBy(xpath = "//span[text()='Location / Studios']")
WebElement locationz;
@FindBy(xpath = "//span[text()='Expertise / Guilds']")
WebElement expertisez;
@FindBy(xpath = "//*[@id=\"careers-search-job\"]/div[3]/input")
WebElement searchField;
@FindBy(xpath = "//span[text()='Search']")
WebElement searchBtn;
@FindBy(xpath = "//*[@id=\"first-section\"]/div/div/div[2]/h3")
WebElement searchTitle;
//
// HashMap methods - get the LOCATION / STUDIOS drop down list items
public void selectLocations(String name) {
if (locationz.isDisplayed()) {
System.out.println("- location displayed");
locationz.click();
System.out.println("location display clicked");
JavaMap test = new JavaMap();
HashMap <String, WebElement> dropDownList = test.getDropList(driver);
for (String location: dropDownList.keySet()) {
if (location.contains(name)) {
System.out.println("location by name found");
System.out.println("Name taken " + name);
dropDownList.get(location).click();
break;
} else {
System.out.println("The desired location " + name + " cannot be found in this list");
}
}
} else {
System.out.println("- location not displayed");
}
}
// HashMap methods - get the EXPERTISE / GUILDS drop down list items
public void selectExpertise(String name) {
if (expertisez.isDisplayed()) {
System.out.println("- expertise displayed");
expertisez.click();
System.out.println("- expertise display clicked");
JavaMap test = new JavaMap();
HashMap<String, WebElement> expertiseList = test.getExpertiseList(driver);
for (String expertise : expertiseList.keySet()) {
if (expertise.contains(name)) {
System.out.println("Expertise found : " + name);
expertiseList.get(expertise).click();
break;
} else {
System.out.println("The desired expertise " + name + " cannot be found in this list");
}
}
} else {
System.out.println("- expertise not displayed");
}
}
//
// Methods
public void clickLocation(String selectLocation) {
if (locationz.isDisplayed()) {
System.out.println("- location displayed");
locationz.click();
String dropDownElements = "//span[contains(text(),'" + selectLocation + "')]";
WebElement eNew42 = driver.findElement(By.xpath(dropDownElements));
eNew42.click();
} else {
System.out.println("- location not displayed");
}
/* Locations available for selection:
atlanta-ga
austin-tx
baia-mare
bangalore
boston-ma
*/
}
public void clickExpertise(String selectExpertise) {
if (expertisez.isDisplayed()) {
System.out.println("- expertise displayed");
expertisez.click();
String dropDownElements = "//span[contains(text(),'" + selectExpertise + "')]";
WebElement eNew42 = driver.findElement(By.xpath(dropDownElements));
eNew42.click();
} else {
System.out.println("- expertise not displayed");
}
}
public void searchField(String input) {
if(searchField.isDisplayed()) {
System.out.println("- search field display: pass");
searchField.sendKeys(input);
} else {
System.out.println("- search field display: fail");
}
}
public void searchButton() {
if(searchBtn.isDisplayed()) {
System.out.println("- search btn display: pass");
searchBtn.click();
} else {
System.out.println("- search btn display: fail");
}
}
public void title() {
if(searchTitle.isDisplayed()) {
System.out.println("- search title display: pass");
}
else {
System.out.println("- search title display: fail");
}
}
//
}
<file_sep>package softvisionProject.testcases.InsightsPageTestCases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.InsightsPage;
import softvisionProject.testcases.BaseTest;
public class checkInsightsArrowSwipeBtn extends BaseTest {
//Open article "Vancouver Studio Design Team Retreat 2019" from Insights page
// after selecting industry and guilds and check if the swipe arrow from the bottom of the page works.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("Insights");
InsightsPage insights = new InsightsPage(driver);
urlAssert("insights");
insights.clickIndustries("Agriculture");
insights.clickGuilds("Design & UX");
insights.clickShowMore();
insights.removeOverlay();
insights.articleDesignJam();
openMenuPage("Insights");
insights.openMatiBaldiArticle();
insights.clickRightArrow();
goToSoftVision();
HomePage homeback = new HomePage(driver);
}
}
<file_sep>package Steps.ContactPage;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.InnovationPage;
import softvisionProject.POM.ServicesPage;
import softvisionProject.testcases.BaseTest;
public class InnovationPageSteps extends BaseTest {
public HomePage home;
public InnovationPage innovate;
private void initializeInnovationPage() {
if(innovate == null) {
innovate = new InnovationPage(driver);
}
}
// Scenario I
@When("^Innovation on softvision and cookie accepted$")
public void acceptCookie() {
home = new HomePage(driver);
home.acceptCookieMethod();
}
@Then("^Open InnovationPage$")
public void openInnovation() {
openMenuPage("Innovation");
initializeInnovationPage();
}
// Scenario II
@And("^Open Burst BlogPage$")
public void openBurstBlogPage() {
innovate.innovateBurst();
}
// Scenario III
@And("^Click Identify$")
public void clickIdentify() {
innovate.identify();
}
@And("^Click Prototype$")
public void clickPrototype() {
innovate.prototype();
}
@And("^Click Partner$")
public void clickPartner() {
innovate.partner();
}
@And("^Click Roadmap$")
public void clickRoadmap() {
innovate.roadmap();
}
}
<file_sep>package softvisionProject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.lang.String;
import org.testng.Assert;
import org.testng.annotations.*;
import softvisionProject.testcases.BaseTest;
import static softvisionProject.framework.helperClass.chooseBrowser;
public class contactPage extends BaseTest {
public void openHomeUrl() {
// open SoftVision and assert
driver.navigate().to("https://softvision.com");
// Assert proper 'Home' page has been opened
String expectedHomeUrl = "https://www.softvision.com/";
Assert.assertEquals(driver.getCurrentUrl(), expectedHomeUrl);
System.out.println("Assertion successful: Current Home Url = Expected Home Url");
}
public void acceptCookie() {
// accept Cookie
String iD = "hs-eu-confirmation-button";
driver.findElement(By.id(iD)).click();
}
public void openContactUrl() {
// find 'Contact' and click WebElement
String xpath = "//span[text()='Contact']";
WebElement element = driver.findElement(By.xpath(xpath));
element.click();
// Assert 'Tab Title' after opening 'Contact' page
String expectedTitle = "Softvision - Contact";
Assert.assertEquals(driver.getTitle(), expectedTitle);
System.out.println("Assertion successful: Current Title = Expected Title");
// Assert proper 'Contact' page has been opened
String expectedContactUrl = "https://www.softvision.com/contact/";
Assert.assertEquals(driver.getCurrentUrl(), expectedContactUrl);
System.out.println("Assertion successful: Current Contact Url = Expected Url");
}
@BeforeTest
public void runBrowser() {
System.out.println("It works so far");
driver = chooseBrowser("Chrome");
}
@Test
public void openContactPage() {
openHomeUrl();
acceptCookie();
openContactUrl();
}
@AfterTest
public void stopBrowser() {
driver.close();
driver.quit();
}
}<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.GuildsPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class GuildsGetInTouchBtnTestCase extends BaseTest {
// Test Case
// open approach/guilds from softvision.com and click on the button from bottom page:
// "GET IN TOUCH TO FIND OUT MORE".
@Test
public void getInTouchBtn() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Guilds");
GuildsPage guilds = new GuildsPage(driver);
guilds.findOutMore();
guilds.closeOverlayForm();
}
}
<file_sep>package softvisionProject.testcases.NewsPage;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.NewsPage;
import softvisionProject.POM.designThinkingCategoryPage;
import softvisionProject.testcases.BaseTest;
public class NewsElementDesignThinking extends BaseTest {
// Test Case:
// open news page on softvision.com and click on the hashtag: "Design Thinking" from the article:
// Cognizant Softvision Holds Design Thinking Workshops.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("News");
NewsPage news = new NewsPage(driver);
news.designThinking();
designThinkingCategoryPage design = new designThinkingCategoryPage(driver);
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.blogGettingStartedWithXamarinPage;
import softvisionProject.POM.GuildsPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class GuildsPageReadMoreBtnTestCase extends BaseTest {
// Test Case
// open approach/guilds page from softvision.com and click on Read More Button from the bottom of the page.
//
@Test
public void clickReadMore() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Guilds");
GuildsPage guilds = new GuildsPage(driver);
guilds.readMore();
blogGettingStartedWithXamarinPage xamarinBlog = new blogGettingStartedWithXamarinPage(driver);
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class RPAPage extends BasePage {
public RPAPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//a[contains(text(),'RPA')]"));
System.out.println("------------------------");
System.out.println("Robotic Process automation page was found.");
System.out.println("------------------------");
}
}
<file_sep>package softvisionProject.testcases.InnovationPageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.InnovationPage;
import softvisionProject.POM.blogSystematicallyInnovateorBurst;
import softvisionProject.testcases.BaseTest;
public class InnovationArticleInnovation extends BaseTest {
// Test Case:
// on softvision.com open innovation page and click on the article Systematically innovate or bust
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("Innovation");
InnovationPage innovation = new InnovationPage(driver);
innovation.innovateBurst();
blogSystematicallyInnovateorBurst blog = new blogSystematicallyInnovateorBurst(driver);
}
}<file_sep>package softvisionProject.testcases.ChatBot;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import softvisionProject.POM.BasePage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class personaltaskopenSoftVisionHomePageChatBot extends BaseTest {
//open and close the chatbot situated on the home page.
//
@Test
public void openSoftVision () {
goToSoftVision();
HomePage homeAssert = new HomePage(driver);
homeAssert.acceptCookieMethod();
homeAssert.switchToFrame(By.xpath("//*[@id=\"hubspot-messages-iframe-container\"]/iframe"));
homeAssert.openChatBot();
homeAssert.closeChatBot();
homeAssert.switchToMainFrame();
}
}
<file_sep>package softvisionProject.testcases.WorkWithUsPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.TrainingsPage;
import softvisionProject.testcases.BaseTest;
public class openTrainingsPage extends BaseTest {
@Test
public void searchFields() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverWorkWithUsBtn();
openMenuPage("Trainings");
TrainingsPage trainings = new TrainingsPage(driver);
}
}
<file_sep>package softvisionProject.testcases.HomePageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class personaltaskmuteUnmuteSound extends BaseTest {
@Test (priority = 1)
public void openSoftVision() {
goToSoftVision();
HomePage homeAssert = new HomePage(driver);
homeAssert.acceptCookieMethod();
}
@Test (priority = 2)
public void muteUnmuteSound() {
HomePage sound = new HomePage(driver);
sound.muteUnmuteSound();
sound.muteUnmuteSound();
}
}
<file_sep>package softvisionProject.testcases.WorkWithUsPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.TrainingsPage;
import softvisionProject.testcases.BaseTest;
public class checkTitleParagraphAndIndiaBtn extends BaseTest {
// open work with us/trainings page from softvision.com and check the presence of TOJ and Pre-emp training titles
// and of their text bodies also, check if India btn is clickable.
//
@Test
public void checkTitlesAndParagraphs() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverWorkWithUsBtn();
openMenuPage("Trainings");
TrainingsPage trainings = new TrainingsPage(driver);
trainings.verifyTojTitle();
trainings.verifyTojBody();
trainings.verifyPreEmpTitle();
trainings.verifyPreEmpBody();
trainings.verifyIndiaBtn();
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.EcoSystemPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class EcoSystemfindText extends BaseTest {
// Test Case:
// on approach/ecosystem page from softvision.com check if "The Softvision model is proven" is present.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Our Ecosystem");
EcoSystemPage eco = new EcoSystemPage(driver);
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.EcoSystemPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class EcoSystemselectAllElementsfromDeliver extends BaseTest {
// Test Case:
// on approach/ecosystem page from softvision.com select every element from "How we deliver".
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Our Ecosystem");
EcoSystemPage eco = new EcoSystemPage(driver);
eco.removeBot();
eco.guilds();
eco.pods();
eco.studios();
eco.transform();
eco.labs();
eco.rightArrow();
eco.alliances();
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class AlliancesPage extends BasePage {
public AlliancesPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//title[text()='Softvision - Alliances']"));
System.out.println("------------------------");
System.out.println("Alliances page was found.");
System.out.println("------------------------");
}
// Page Factory
@FindBy(xpath = "//*[@id=\"customers_content\"]/div/div[1]/div[1]/img")
WebElement acquiaPng;
@FindBy(xpath = "//*[@id=\"customers_content\"]/div/div[1]/div[2]/div[1]")
WebElement acquiaTitle;
@FindBy(xpath = "//*[@id=\"customers_content\"]/div/div[2]/div[1]/img")
WebElement adobePng;
@FindBy(xpath = "//*[@id=\"customers_content\"]/div/div[2]/div[2]/div[1]")
WebElement adobeTitle;
@FindBy(xpath = "//div[@class='text']/p[contains(text(),'The goals of our Alliance program')]")
WebElement innerText;
//
// Methods
public void acquia () {
acquiaPng.isDisplayed();
acquiaTitle.isDisplayed();
System.out.println("- acquia logo: pass");
System.out.println("- acquia title: pass");
}
public void adobe() {
adobePng.isDisplayed();
adobeTitle.isDisplayed();
System.out.println("- adobe logo: pass");
System.out.println("- adobe title: pass");
}
public void text() {
innerText.isDisplayed();
System.out.println("- selected text is displayed: pass");
}
//
}
<file_sep>package softvisionProject.framework;
import com.google.errorprone.annotations.Var;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.HashMap;
import java.util.List;
public class JavaMap {
public static HashMap<String, String> getNameEmail() {
HashMap<String, String> nameEmail = new HashMap<String, String>();
nameEmail.put("first", "<EMAIL>");
nameEmail.put("Second", "<EMAIL>");
nameEmail.put("Three", "<EMAIL>");
return nameEmail;
}
public HashMap<String, WebElement> getDropList(WebDriver driver) {
List<WebElement> locations = driver.findElements(By.xpath("//div[@class='btn-group bootstrap-select locationselect dropup open']//div[@class='dropdown-menu open' and @role='combobox']/ul/li/a/span[@class='text']"));
// System.out.println(locations.size()); prints the number of selections the xpath generates
HashMap<String, WebElement> dropList = new HashMap<String, WebElement>();
for (WebElement item : locations) {
dropList.put(item.getAttribute("innerHTML"), item);
//System.out.println(item.getAttribute("innerHTML").trim()); // prints the name of the selection
}
return dropList;
}
public HashMap<String, WebElement> getExpertiseList(WebDriver driver) {
List<WebElement> expertises = driver.findElements(By.xpath("//div[@class='btn-group bootstrap-select guildselect dropup open']//div[@class='dropdown-menu open']/ul/li/a/span[@class='text']"));
HashMap<String, WebElement> expertiseList = new HashMap<String, WebElement>();
for (WebElement item : expertises) {
expertiseList.put(item.getAttribute("innerHTML"), item);
}
return expertiseList;
}
public HashMap<String, WebElement> getRegardingList(WebDriver driver) {
List<WebElement> regarding = driver.findElements(By.xpath("//div[@class='btn-group bootstrap-select hs-input dropup open']//div[@class='dropdown-menu open']/ul/li/a/span[@class='text']"));
HashMap<String, WebElement> regardingList = new HashMap<String, WebElement>();
for (WebElement item : regarding) {
regardingList.put(item.getAttribute("innerHTML"), item);
}
return regardingList;
}
}
<file_sep>package Steps.ContactPage;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import softvisionProject.POM.AlliancesPage;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.TrainingsPage;
import softvisionProject.testcases.BaseTest;
public class TrainingsPageSteps extends BaseTest {
public HomePage home;
public TrainingsPage training;
private void initializeTrainingsPage() {
if(training == null) {
training = new TrainingsPage(driver);
}
}
// Scenario I
@When("^Trainings on SoftVision and cookie accepted$")
public void contactOnSoftVisionAndCookieAccepted() {
home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
}
@Then("^Open TrainingsPage$")
public void openContactPage() {
openMenuPage("Trainings");
initializeTrainingsPage();
}
// Scenario II
@And("^Verify elements: title, body, preEmp title, preEmp body, IndiaBtn$")
public void verifyElements() {
training.verifyTojTitle();
training.verifyTojBody();
training.verifyPreEmpTitle();
training.verifyPreEmpBody();
training.verifyIndiaBtn();
}
}
<file_sep>package softvisionProject.testcases.ApproachPagesTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.AlliancesPage;
import softvisionProject.POM.HomePage;
import softvisionProject.testcases.BaseTest;
public class AlliancesPageCheckBrandsTestCase extends BaseTest {
// Test Case:
// open approach/alliances page from softvision.com and check if brand elements(logo and title)
// acquia and adobe are present in the webpage.
@Test
public void brands () {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
home.hoverApproachBtn();
openMenuPage("Alliances");
AlliancesPage alliances = new AlliancesPage(driver);
alliances.acquia();
alliances.adobe();
}
}
<file_sep>package softvisionProject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.lang.String;
import org.testng.Assert;
import static softvisionProject.framework.helperClass.runChromeDriver;
public class openSV {
public static void main(String[] args) {
// use runDriver from helperClass
WebDriver driver = runChromeDriver();
// open SoftVision
driver.navigate().to("https://softvision.com");
// Assert proper 'Home' page has been opened
String expectedHomeUrl = "https://www.softvision.com/";
Assert.assertEquals(driver.getCurrentUrl(), expectedHomeUrl);
System.out.println("Assertion successful: Current Home Url = Expected Home Url");
// accept Cookie
String iD = "hs-eu-confirmation-button";
driver.findElement(By.id(iD)).click();
// find 'Contact' and click WebElement
String xpath = "//span[text()='Contact']";
WebElement element = driver.findElement(By.xpath(xpath));
element.click();
// Assert 'Tab Title' after opening 'Contact' page
String expectedTitle = "Softvision - Contact";
Assert.assertEquals(driver.getTitle(), expectedTitle);
System.out.println("Assertion successful: Current Title = Expected Title");
// Assert proper 'Contact' page has been opened
String expectedContactUrl = "https://www.softvision.com/contact/";
Assert.assertEquals(driver.getCurrentUrl(), expectedContactUrl);
System.out.println("Assertion successful: Current Contact Url = Expected Url");
// stop driver
driver.close();
}
}
*/
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class productDesignPage extends BasePage {
public productDesignPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//*[@id=\"page-title\"]/div/h1"));
System.out.println("------------------------");
System.out.println("Product Design page found.");
System.out.println("------------------------");
}
// Page Factory
@FindBy(xpath = "//span[contains(text(),'full case')]")
WebElement readTheFullCaseStudy;
//
// Methods
public void clickFullCaseStudy() {
readTheFullCaseStudy.click();
}
//
}
<file_sep>package softvisionProject.testcases.InsightsPageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.InsightsPage;
import softvisionProject.testcases.BaseTest;
public class openInsightsPageMatiBaldiArticle extends BaseTest {
@Test(priority = 1)
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
home.acceptCookieMethod();
openMenuPage("Insights");
InsightsPage insights = new InsightsPage(driver);
insights.removeOverlay();
insights.openMatiBaldiArticle();
}
}
<file_sep>package Steps.ContactPage;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import softvisionProject.POM.ClujNapocaStudioPage;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.RPAPage;
import softvisionProject.testcases.BaseTest;
public class HomePageSteps extends BaseTest {
public HomePage home;
public HomePageSteps() {
this.home = new HomePage(driver);
}
// Use constructor from above or use method from below
/* private void initializeHomePage() {
if(home == null) {
home = new HomePage(driver);
}
}
*/
@When("^On SoftVision site$")
public void onSoftVisionSite() {
home.acceptCookieMethod();
}
@Then("^Click Solutions Tab$")
public void clickSolutionsTab() {
home.solutionsPage();
}
@Then("^Click RPA hashtag button$")
public void clickRPAHashtagButton() {
home.rpaBtn();
RPAPage rpa = new RPAPage(driver);
}
@Then("^Click get in touch button$")
public void clickGetInTouchBtn() {
home.getInTouchBtn();
}
@Then("^Open Cluj dot$")
public void openClujDot() {
home.mapDotCluj();
}
@And("^Click View Studio button$")
public void clickViewStudioButton() {
home.inDotViewStudioBtn();
ClujNapocaStudioPage cluj = new ClujNapocaStudioPage(driver);
}
}
<file_sep>package softvisionProject.POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class companyNewsCategoryPage extends BasePage {
public companyNewsCategoryPage(WebDriver driver) {
super(driver);
driver.findElement(By.xpath("//div[@class='row']/@href | //a[@class='selected']"));
System.out.println("------------------------");
System.out.println("Company News category page was found.");
System.out.println("------------------------");
}
}
<file_sep>package softvisionProject.testcases.InsightsPageTestCases;
import org.testng.annotations.Test;
import softvisionProject.POM.HomePage;
import softvisionProject.POM.InsightsPage;
import softvisionProject.testcases.BaseTest;
public class openInsightsReadMorePage extends BaseTest {
// Open insights page from softvision.com and click on ReadMore btn.
//
@Test
public void openSoftVision() {
goToSoftVision();
HomePage home = new HomePage(driver);
titleAssert("Softvision, your Technology Partner for Digital Innovation");
home.acceptCookieMethod();
openMenuPage("Insights");
InsightsPage insights = new InsightsPage(driver);
urlAssert("insights");
insights.clickReadMore();
}
}
| 3954f7484181f0874cdb5848999cfb84d5d43970 | [
"Java"
] | 43 | Java | projectImplementer/My-practice | c9c25c9d74178ccb26045c92194d9694c799ba87 | 2cd7e36df86ab4792bd2a367b93690ab3608ecae |
refs/heads/master | <repo_name>atomicjuice/ruby-oo-relationships-practice-art-gallery-exercise-london-web-120919<file_sep>/app/models/artist.rb
class Artist
attr_reader :name, :years_experience
def initialize(name:, years_experience:)
@name = name
@years_experience = years_experience
@@all << self
end
@@all = []
def self.all
@@all
end
def paintings
Painting.all.select{|paintings|paintings.artist == self}
end
def galleries
paintings.map{|paintings|paintings.gallery}.uniq
end
def cities
galleries.map{|paintings|paintings.city}
end
def self.total_experience
all.map{|artists|artists.years_experience}.reduce(:+)
end
def self.most_prolific
self.all.max_by{|artist|artist.paintings.count / artist.years_experience.to_f}
end
def create_painting(title:, price:, gallery:)
Painting.new(title: title, price: price, artist:self, gallery: gallery)
end
end
<file_sep>/tools/console.rb
require_relative '../config/environment.rb'
a1 = Artist.new(name: "Monet", years_experience: 20)
a2 = Artist.new(name: "Manet", years_experience: 30)
a3 = Artist.new(name: "Picasso", years_experience: 25)
a4 = Artist.new(name: "<NAME>", years_experience: 32)
a5 = Artist.new(name: "Rembrandt", years_experience: 15)
a6 = Artist.new(name: "<NAME>", years_experience: 55)
g1 = Gallery.new(name: "National Portrait Gallery", city: "London")
g2 = Gallery.new(name: "Louvre", city: "Paris")
g3 = Gallery.new(name: "Tate Modern", city: "London")
g4 = Gallery.new(name: "The Met", city: "NYC")
p1 = Painting.new(title: "deck", price: rand(1000000), artist: (Artist.all.sample), gallery: (Gallery.all.sample) )
p2 = Painting.new(title: "the", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p3 = Painting.new(title: "halls", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p4 = Painting.new(title: "with", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p5 = Painting.new(title: "boughs", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p6 = Painting.new(title: "of holly", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p7 = Painting.new(title: "falalalalala", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p8 = Painting.new(title: "lalalala", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p9 = Painting.new(title: "tis the season", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
p10 = Painting.new(title: "to be jolly", price: rand(1000000), artist: Artist.all.sample, gallery: Gallery.all.sample )
binding.pry
puts "<NAME> rules."
| 9f3029c27f164eed820f3a90a68f6e5df2880968 | [
"Ruby"
] | 2 | Ruby | atomicjuice/ruby-oo-relationships-practice-art-gallery-exercise-london-web-120919 | 8780453e968ba93c15cd191fc78cdb49f542067d | ec83dfee21e5eab6b18a61b90933c973c701bc18 |
refs/heads/master | <file_sep># Troubleshooting
### If `asdf` is upgraded, ASDF_DIR may be incorrect
```shell
printf "'%s'\n" "$ASDF_DIR"
unset ASDF_DIR
```
<file_sep>#
# <NAME>: https://github.com/gehrigkeane
#
# References:
# https://github.com/zdharma/zinit
# https://esham.io/2018/02/zsh-profiling
# Patch ZSH word boundaries per https://stackoverflow.com/a/1438523
autoload -U select-word-style
select-word-style bash
#
# Env
#
# . /usr/local/opt/asdf/asdf.sh
export TERM="xterm-256color"
export LESS=-JMQRiFX
# Long running commands should print timing information
# https://github.com/unixorn/zsh-quickstart-kit/blob/master/zsh/.zshrc
REPORTTIME=10
TIMEFMT="%U user %S system %P cpu %*Es total"
#
# Plugins
#
# Brew completions
# ref: https://docs.brew.sh/Shell-Completion#configuring-completions-in-zsh
FPATH=/usr/local/share/zsh/site-functions:$FPATH
### Added by Zinit's installer
if [[ ! -f $HOME/.local/share/zinit/zinit.git/zinit.zsh ]]; then
print -P "%F{33} %F{220}Installing %F{33}ZDHARMA-CONTINUUM%F{220} Initiative Plugin Manager (%F{33}zdharma-continuum/zinit%F{220})…%f"
command mkdir -p "$HOME/.local/share/zinit" && command chmod g-rwX "$HOME/.local/share/zinit"
command git clone https://github.com/zdharma-continuum/zinit "$HOME/.local/share/zinit/zinit.git" && \
print -P "%F{33} %F{34}Installation successful.%f%b" || \
print -P "%F{160} The clone has failed.%f%b"
fi
source "$HOME/.local/share/zinit/zinit.git/zinit.zsh"
autoload -Uz _zinit
(( ${+_comps} )) && _comps[zinit]=_zinit
# Load a few important annexes, without Turbo
# (this is currently required for annexes)
zinit light-mode for \
zdharma-continuum/zinit-annex-as-monitor \
zdharma-continuum/zinit-annex-bin-gem-node \
zdharma-continuum/zinit-annex-patch-dl \
zdharma-continuum/zinit-annex-rust
### End of Zinit's installer chunk
# zinit ice wait atinit"zpcompinit; zpcdreplay" # https://github.com/zdharma-continuum/fast-syntax-highlighting
zinit light zdharma-continuum/fast-syntax-highlighting
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=8' # https://github.com/zsh-users/zsh-autosuggestions
# zinit ice wait atload"_zsh_autosuggest_start"
zinit light zsh-users/zsh-autosuggestions
zinit light djui/alias-tips # https://github.com/djui/alias-tips
#zinit light mattbangert/kubectl-zsh-plugin
zinit snippet https://github.com/gehrigkeane/zsh_plugins/blob/master/kubectl.zsh.plugin
# Regenerate kubectl completion via `kubectl completion zsh > _kubectl`
zinit ice as"completion"
zinit snippet https://github.com/gehrigkeane/zsh_plugins/blob/master/_kubectl
#
# Oh My Zsh Plugins (via zinit)
#
# https://python-poetry.org/docs/#enable-tab-completion-for-bash-fish-or-zsh
# poetry completions zsh > ~/.zfunc/_poetry
fpath+=~/.zfunc
# completions are failing somewhere
# https://github.com/eddiezane/lunchy/issues/57#issuecomment-121173592
autoload bashcompinit
bashcompinit
zinit snippet OMZ::lib/key-bindings.zsh
zinit snippet OMZ::lib/history.zsh
zinit snippet OMZ::lib/git.zsh
zinit snippet OMZ::plugins/brew/brew.plugin.zsh # https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/brew
# https://github.com/zdharma/zinit/issues/382#issuecomment-660521300
# https://github.com/zdharma/zinit/issues/367
zinit lucid has'docker' for \
as'completion' is-snippet \
'https://github.com/docker/cli/blob/master/contrib/completion/zsh/_docker' \
\
as'completion' is-snippet \
'https://github.com/docker/compose/blob/master/contrib/completion/zsh/_docker-compose'
zinit snippet OMZ::plugins/git/git.plugin.zsh # https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/git
#
# Themes
#
# Spaceship Theme
# zplug denysdovhan/spaceship-prompt, use:spaceship.zsh, from:github, as:theme
# Powerlevel 9k
# https://github.com/bhilburn/powerlevel9k#customizing-prompt-segments
# https://github.com/bhilburn/powerlevel9k/wiki/Stylizing-Your-Prompt
# POWERLEVEL9K_MODE='awesome-patched'
POWERLEVEL9K_SHORTEN_DIR_LENGTH=2
POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=0
POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=3
POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND='black'
POWERLEVEL9K_COMMAND_EXECUTION_TIME_BACKGROUND='072'
POWERLEVEL9K_EXECUTION_TIME_ICON='Δ'
POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false
POWERLEVEL9K_BACKGROUND_JOBS_BACKGROUND=none
POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_COLOR=002
POWERLEVEL9K_BACKGROUND_JOBS_ICON='⇶'
POWERLEVEL9K_VCS_INCOMING_CHANGES_ICON='⇣'
POWERLEVEL9K_VCS_OUTGOING_CHANGES_ICON='⇡'
POWERLEVEL9K_SHOW_CHANGESET=true
POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(dir dir_writable vcs)
POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status command_execution_time background_jobs history time)
zinit ice depth=1; zinit light romkatv/powerlevel10k
#
# En fin
#
setopt hist_expire_dups_first
setopt hist_ignore_all_dups
setopt hist_ignore_dups
setopt hist_ignore_space
setopt hist_reduce_blanks
setopt hist_save_no_dups
setopt hist_verify
# Patch ZSH key bindings per https://stackoverflow.com/a/29403520
bindkey "^U" backward-kill-line
bindkey "^X\\x7f" backward-kill-line
bindkey "^X^_" redo
#
# Source `.shell*` configuration
#
source ~/.profile
. /usr/local/opt/asdf/asdf.sh
# In the event of weird up and down behavior try these:
# bindkey '^[[A' up-line-or-search
# bindkey '^[[B' down-line-or-search
# FZF
# Note: the following is stems from the `/usr/local/opt/fzf/install` executable
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
<file_sep>Hi guys!
# Q/A
## Why ZSH?
Often, after mentioning I'm a ZSH user, people ask what the differences are compared to BASH. Well:
- Interoperability, scripts with `#!/bin/bash` still run in bash (this may or may not be obvious)
- *Extensive* plugin (eco)system
- Z Shell has an army of MacOS hipsters, who develope and maintain awesome plugins
- Advanced tab completion/navigation system
- Automatic cd
- Inline wildcard expansion
- Recursive path expansion
## Why not csh, fish, or ksh?
Again, an army of hipsters. Seriously, I haven't attempted to daily-drive `fish`, the only comperable alternative, largely because I too am an MacOS hipster... :sadparrot: Also, it's my understanding that the primary quality-of-life features `fish` offers are available to `zsh` as plugins.
### Why Oh My Zsh?
Ok, ZSH sounds neat, so what's [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) and why should you use a ZSH plugin framework?
Succinctly, read through this list of [awesome-zsh-plugins](https://github.com/unixorn/awesome-zsh-plugins).
Plugin frameworks provide the lion-share... lion's share? :shrug: of user friendliness `zsh` has to offer.
Recently, I've migrated from [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh) to [zplug](https://github.com/zplug/zplug) which offers everything and more compared to [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh).
Though, there are a plethora of `zsh` framework'esque tools. I recommend you take the time to poke around the ecosystem at some point and make a decision for yourself.
Powerlevel9k https://github.com/bhilburn/powerlevel9k/wiki/Install-Instructions#option-5-install-for-zplug
## References
- https://www.reddit.com/r/programming/comments/bwjny2/zsh_is_now_the_default_shell_for_macos/
- [Powerlevel9k](https://github.com/bhilburn/powerlevel9k/wiki/Install-Instructions#option-5-install-for-zplug)
## EDT (every day tools)
- [bat](https://github.com/sharkdp/bat) Alternative to `cat` with syntax highlighting
- [exa](https://the.exa.website) Modern replacement for 'ls'
- [fzf](https://github.com/junegunn/fzf) A command-line fuzzy finder
- [httpie](https://github.com/jkbrzt/httpie) Modern CURL + features (see https://github.com/eliangcs/http-prompt)
- [jq](https://stedolan.github.io/jq/) Awesome JSON command line utility
- [ncdu](https://dev.yorhel.nl/ncdu) NCurses Disk Usage
- [ripgrep](https://github.com/BurntSushi/ripgrep) Search tool like grep and The Silver Searcher
- [tig](https://jonas.github.io/tig/) Text interface for Git repositories
- [tldr](https://tldr.sh/) Simplified and community-driven man pages
- [cjbassi/gotop/gotop](https://github.com/cjbassi/gotop) A terminal based graphical activity monitor inspired by gtop and vtop
## Hipster Cool Tools
- [tmux](https://tmux.github.io/) Terminal multiplexer
- [vim](https://www.vim.org/) Up-to-date vim replacement
## Casks (MacOS Apps)
### Favs
- [bartender](https://www.macbartender.com/)
- [flycut](https://github.com/TermiT/Flycut) Clean and simple clipboard manager for developers
- [istat-menus](https://bjango.com/mac/istatmenus/)
- [spectacle](https://www.spectacleapp.com/) Window control with simple keyboard shortcuts
### Quick Look Extensions
- [qlcolorcode](https://github.com/anthonygelibert/QLColorCode) QuickLook for code
- [qlimagesize](https://github.com/Nyx0uf/qlImageSize) QuickLook image info
- [qlmarkdown](https://github.com/toland/qlmarkdown) QuickLook generator for Markdown files
- [qlprettypatch](https://github.com/atnan/QLPrettyPatch) QuickLook generator for patch files
- [qlstephen](https://whomwah.github.io/qlstephen/) QuickLook plugin for plain text files sans file extension
- [quicklook-csv](https://github.com/p2/quicklook-csv)
- [quicklook-json](http://www.sagtau.com/quicklookjson.html)
- [webpquicklook](https://github.com/emin/WebPQuickLook) QuickLook plugin for WebP image files
### Honorable Mentions
- [karabiner-elements](https://pqrs.org/osx/karabiner/) A powerful and stable keyboard customizer for macOS
- [the-unarchiver](https://theunarchiver.com/) Nice file archive GUI
- [aerial](https://github.com/JohnCoates/Aerial) Pretty screen-savers
| c49ce1be0b0876c6353516e75c325206e865a791 | [
"Markdown",
"Shell"
] | 3 | Markdown | gehrigkeane/dotfiles | 4da53efaf26127c6afd7028ec484b3eab15a31bd | cfb13ee086f28262bd88a03dd75ea3487298fabb |
refs/heads/master | <repo_name>Erloch/liri-node-app<file_sep>/README.md
# liri-node-app
This is a node.js app that searches 3 different api's for information about; your favorite bands concert information, your favorite movies information, as well as the information on your favorite song. You can use the spotify api by adding spotify-this to the call and adding your favorite song you get info on that song as in the artist and a link to spotify to take a listen.
When looking for a good movie add movie-this to the end of your call and add an interesting movie to get information about that movie, like the actors as well as the year it was released. If bands are your thing use concert-this after the call with the name of your favorite band and find information on the next concert they are playing as well as the location in case you are looking to travel for that band.
Links to video:
https://drive.google.com/file/d/13Gvf1tfhNcMutynMZhsPhaI2VgN0AlG-/view
https://drive.google.com/file/d/1QlpEN0Rp1nJcp3vBasMaLSLhXaDqQzWY/view
<file_sep>/liri.js
var fs = require("fs");
var Spotify = require("node-spotify-api");
require("dotenv").config();
var keys = require("./keys.js");
var moment = require("moment");
var axios = require("axios");
var spotify = new Spotify(keys.spotify);
var action = process.argv[2];
// var divider = "\n------------------------------------------------------------\n\n";
// console.log(response.data[0]);
// liri needs to take these in
//=================================
switch (action) {
case "concert-this":
var bands = process.argv.slice(3).join(" ");
concertThis();
break;
// write();
case "spotify-this-song":
var song = process.argv.slice(3).join(" ");
// console.log(song)
spotifyThisSong()
// write();
// axios.get(search).then(
// function (response) {
// console.log(response.data);
// });
// * The album that the song is from
// * If no song is provided then your program will default to "The Sign" by Ace of Base.
break;
case "movie-this":
// var type = process.argv[3];
var movieName = process.argv.slice(3).join("+");
movieThis();
// write();
break;
case "do-what-it-says":
fs.readFile("random.txt", "utf8", function (error, data) {
// If the code experiences any errors it will log the error to the console.
if (error) {
return console.log(error);
}
// We will then print the contents of data
// console.log(data);
// Then split it by commas (to make it more readable)
var dataArr = data.split(",");
if (dataArr[0] === "spotify-this-song") {
action = dataArr[0];
song = dataArr[1];
spotifyThisSong();
}
if (dataArr[2] === "movie-this") {
action = dataArr[2];
movieName = dataArr[3];
movieThis();
}
if (dataArr[4] === "concert-this") {
action = dataArr[4];
bands = dataArr[5];
movieThis();
}
// We will then re-display the content as an array for later use.
// console.log(dataArr);
});
break;
default: "its here";
};
function spotifyThisSong() {
if (song) {
spotify
.search({ type: 'track', query: song, limit: 1 })
.then(function (response) {
// console.log(response)
// * The song's name
console.log("\n\n\n\nSong Name: " + response.tracks.items[0].name + "\n\nArtist: " + response.tracks.items[0].artists[0].name + "\n\nAlbum: " + response.tracks.items[0].album.name + "\n\nSpotify Link: " + response.tracks.items[0].external_urls.spotify + "\n\n\n\n");
// * Artist(s)
// console.log("\nArtist: " + response.tracks.items[0].artists[0].name + "\n");
// // * The album that the song is from
// console.log("\nAlbum: " + response.tracks.items[0].album.name + "\n");
// // * A preview link of the song from Spotify
// console.log("\nSpotify Link: " + response.tracks.items[0].external_urls.spotify + "\n\n\n\n");
}).catch(function (err) {
console.log(err);
});
} else {
spotify
.search({ type: 'track', query: "The Sign", limit: 7 })
.then(function (response) {
// console.log(response.tracks.items[5])
// * The song's name
console.log("\n\n\n\nSong Name: " + response.tracks.items[5].name + "\n\nArtist: " + response.tracks.items[5].artists[0].name + "\n\nAlbum: " + response.tracks.items[5].album.name + "\n\nSpotify Link: " + response.tracks.items[5].external_urls.spotify + "\n\n\n\n");
// // * Artist(s)
// console.log();
// // * The album that the song is from
// console.log("\nAlbum: " + response.tracks.items[5].album.name + "\n");
// // * A preview link of the song from Spotify
// console.log(");
fs.appendFile("log.txt", "\n\n\n\nSong Name: " + response.tracks.items[5].name + "\n\nArtist: " + response.tracks.items[5].artists[0].name + "\n\nAlbum: " + response.tracks.items[5].album.name + "\n\nSpotify Link: " + response.tracks.items[5].external_urls.spotify + "\n\n\n\n", function(err) {
// If an error was experienced we will log it.
if (err) {
console.log(err);
}
// If no error is experienced, we'll log the phrase "Content Added" to our node console.
else {
console.log("Content Added!");
}
});
}).catch(function (err) {
console.log(err);
});
}
};
function movieThis() {
if (movieName) {
var query = "http://www.omdbapi.com/?t=" + movieName + "&y=&plot=short&apikey=trilogy";
axios.get(query).then(
function (response) {
// console.log(response.data)
// * Title of the movie.
console.log("\n\n\nMovie Info:\n\nTitle: " + response.data.Title + "\n\nDate Released: " + response.data.Released + "\n\nIMDB Rating: " + response.data.Ratings[0].Value + "\n\nRoten Tomato Rating: " + response.data.Ratings[1].Value + "\n\nCountry of production: " + response.data.Country + "\n\nLanguage of movie: " + response.data.Language + "\n\nPolt: " + response.data.Plot + "\n\nActors: " + response.data.Actors + "\n\n\n\n\n");
fs.appendFile("log.txt", "\n\nMovie Info:\n\nTitle: " + response.data.Title + "\n\nDate Released: " + response.data.Released + "\n\nIMDB Rating: " + response.data.Ratings[0].Value + "\n\nRoten Tomato Rating: " + response.data.Ratings[1].Value + "\n\nCountry of production: " + response.data.Country + "\n\nLanguage of movie: " + response.data.Language + "\n\nPolt: " + response.data.Plot + "\n\nActors: " + response.data.Actors + "\n\n\n\n\n", function(err) {
// If an error was experienced we will log it.
if (err) {
console.log(err);
}
// If no error is experienced, we'll log the phrase "Content Added" to our node console.
else {
console.log("Content Added!");
}
});
});
} else {
var query = "http://www.omdbapi.com/?t=Mr+Nobody&y=&plot=short&apikey=trilogy";
axios.get(query).then(
function (response) {
// console.log(response.data)
// * Title of the movie.
console.log("\n\n\nMovie Info:\n\nTitle: " + response.data.Title + "\n\nDate Released: " + response.data.Released + "\n\nIMDB Rating: " + response.data.Ratings[0].Value + "\n\nRoten Tomato Rating: " + response.data.Ratings[1].Value + "\n\nCountry of production: " + response.data.Country + "\n\nLanguage of movie: " + response.data.Language + "\n\nPolt: " + response.data.Plot + "\n\nActors: " + response.data.Actors + "\n\n\n\n\n");
fs.appendFile("log.txt", "\n\n\nMovie Info:\n\nTitle: " + response.data.Title + "\n\nDate Released: " + response.data.Released + "\n\nIMDB Rating: " + response.data.Ratings[0].Value + "\n\nRoten Tomato Rating: " + response.data.Ratings[1].Value + "\n\nCountry of production: " + response.data.Country + "\n\nLanguage of movie: " + response.data.Language + "\n\nPolt: " + response.data.Plot + "\n\nActors: " + response.data.Actors + "\n\n\n\n\n", function(err) {
// If an error was experienced we will log it.
if (err) {
console.log(err);
}
// If no error is experienced, we'll log the phrase "Content Added" to our node console.
else {
console.log("Content Added!");
}
});
});
}
};
function concertThis(){
var search = "https://rest.bandsintown.com/artists/" + bands + "/events?app_id=codingbootcamp";
axios.get(search).then(
function (response) {
console.log("\n\n\nConcert Info:\n\nVenue: " + response.data[0].venue.name + "\n\nLocation: " + response.data[0].venue.city + ", " + response.data[0].venue.country + "\n\nDate: " + moment(response.data[0].datetime).format('MM DD YYYY') + "\n\n\n\n\n");
fs.appendFile("log.txt", "Concert Info:\n\nVenue: " + response.data[0].venue.name + "\n\nLocation: " + response.data[0].venue.city + ", " + response.data[0].venue.country + "\n\nDate: " + moment(response.data[0].datetime).format('MM DD YYYY') + "\n\n\n\n\n", function(err) {
// If an error was experienced we will log it.
if (err) {
console.log(err);
}
// If no error is experienced, we'll log the phrase "Content Added" to our node console.
else {
console.log("Content Added!");
}
});
});
}
// function write(){
// fs.appendFile("log.txt", devider + , function(err) {
// // If an error was experienced we will log it.
// if (err) {
// console.log(err);
// }
// // If no error is experienced, we'll log the phrase "Content Added" to our node console.
// else {
// console.log("Content Added!");
// }
// });
// }
//========================= | a9bb307bd7b6be22b69c1e606438305926d9db9a | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Erloch/liri-node-app | 22cecd735badb0db727908334eb0cad01d257687 | 1b26364e7210bc9d881628833293f29b6a4ee988 |
refs/heads/master | <file_sep>package com.store.services.product;
import com.store.model.ProductModel;
import com.store.persistence.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
ProductRepository productRepository;
@Override
public ProductModel getProduct(Long id) {
ProductModel productModel = productRepository.getById(id);
return productModel;
}
@Override
public ProductModel createProduct(ProductModel productModel) {
return productRepository.save(productModel);
}
}
<file_sep>spring.datasource.url=jdbc:postgresql://localhost:5432/store
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults= false
management.server.port=9001
management.server.address=127.0.0.1
management.endpoints.web.exposure.include=*
spring.liquibase.enabled=true
spring.liquibase.change-log=classpath:/db/changelog/master.xml
<file_sep>package com.store.persistence.repository;
import com.store.model.CategoryModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<CategoryModel,Long> {
}
<file_sep>package com.store.app;
import com.store.model.ProductModel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.store.persistence"})
@EntityScan(basePackages = {"com.store.model"})
@ComponentScan(basePackages = {"com.store.web.*","com.store.admin.*", "com.store.services"})
public class StoreApplication {
public static void main(String[] args) {
SpringApplication.run(StoreApplication.class);
}
}
<file_sep>package com.store.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping("/get")
public String getProduct(){
return "Hello";
}
}
| 4dfd0fc4d2246e98c5a0b7ea426517044c07237e | [
"Java",
"INI"
] | 5 | Java | suleimen/store-app | 7138edc5cfb612d0d2272069472fba8cf8044b20 | 1c1cd76525fc013f87b47982cb9d10b82774c3a8 |
refs/heads/master | <repo_name>Soreasan/C-Sharp-Minesweeper-with-Methods<file_sep>/Assignment1Minesweeper/Assignment1Minesweeper/Program.cs
/*
* <NAME>
* www.cslearner.com
* This was an assignment for my C# class. We were asked to make a simple program that randomly generated "bombs"
* and blank spaces for a minesweeper map. I'm not the best programmer but I know how to use methods so I figured
* out I could make a basic minesweeper game including player input and win conditions with nothing but lots and lots
* of methods. This program/game is the result. It's messy but it works! I'm actually very proud of myself, this is
* my first game I've ever made.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment1Minesweeper
{
class Program
{
//EmptyMapGenerator() is a method that generators an 2D array with dashes in each spot
public static char[,] EmptyMapGenerator()
{
// Arrays are flipped in C# so it's [y, x]
// y = 5
// x = 10
char[,] array = new char[5, 10];
//This first loop is looping through the ROWS (y value), 5 rows
for (int y = 0; y < 5; y++)
{
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
//This is generating an empty map
array[y, x] = '-';
}
}
return array;
}
//This method randomly generates bomgbs in our matrix
public static char[,] BombFiller(char[,] EmptyMap){
//r becomes a random number generator
var r = new Random();
//This loop creates randomized bombs
for (int i = 0; i < 10; i++)
{ //places random bombs on our grid
EmptyMap[r.Next(5), r.Next(10)] = 'X';
}
return EmptyMap;
}
//This method displays any map we put into it onto the console
public static char[,] MapDisplay(char[,] Map)
{
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9");
for (int y = 0; y < 5; y++)
{
Console.Write(y + " ");
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
//This is generating an empty map
Console.Write(Map[y,x] + " ");
}
Console.WriteLine();
}
return Map;
}
//This method will be called by another method.
//This one checks a single square to see if it has an X or not
public static int CheckSpecificBox(char[,] map, int x, int y){
if (x < 0 || x > 9 || y < 0 || y > 4)
{
return 0;
}
else if (map[y, x] == 'X')
{
return 1;
}
else
{
return 0;
}
}
//This method will use CheckSpecificBox many times to check the 8 boxes around a box to determine a square number
//This method will be called by another method to update the entire map
public static void CheckEightBoxes(char[,] map, int x, int y)
{
//If this space IS a bomb, do nothing and move on
if (map[y, x] == 'X')
{
return;
}
else
{
//Check 9 squares including itself for nearby bombs
//The reason we have the square check itself is for simplicity of the loops
//Since the above IF statement catches if it's a bomb we don't have to worry
//Counter tracks how many bombs are around the square
int counter = 0;
//Goes through each Y value nearby
for (int yy = y - 1; yy < y + 2; yy++)
{
//Goes through each X value nearby
for (int xx = x - 1; xx < x + 2; xx++)
{
//If there is a bomb at the specific counter we increment the counter
if (CheckSpecificBox(map, xx, yy) == 1)
{
counter++;
}
//counter = counter + CheckSpecificBox(map, xx, yy);
}
}
//Once it has counted between 0 and 8 bombs we update the square to reflect how many bombs are nearby
if (counter > 0)
{
if (counter == 1)
{
map[y, x] = '1';
}
else if (counter == 2)
{
map[y, x] = '2';
}
else if (counter == 3)
{
map[y, x] = '3';
}
else if (counter == 4)
{
map[y, x] = '4';
}
else if (counter == 5)
{
map[y, x] = '5';
}
else if (counter == 6)
{
map[y, x] = '6';
}
else if (counter == 7)
{
map[y, x] = '7';
}
else
{
map[y, x] = '8';
}
}
}
}
//This class checks the entire map and updates the number values to reflect how many bombs there are
public static char[,] UpdateMapWithNumbers(char[,] map)
{
//This first loop is looping through all the ROWS (y value), 5 rows
for (int y = 0; y < 5; y++)
{
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
CheckEightBoxes(map, x, y);
}
}
return map;
}
//This generates the computer's map that we play against
public static char[,] ComputerMap()
{
char[,] map = EmptyMapGenerator();
map = BombFiller(map);
map = UpdateMapWithNumbers(map);
return map;
}
//This is the map the player will see
public static char[,] EmptyDisplayMapGenerator()
{
// Arrays are flipped in C# so it's [y, x]
// y = 5
// x = 10
char[,] array = new char[5, 10];
//This first loop is looping through the ROWS (y value), 5 rows
for (int y = 0; y < 5; y++)
{
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
//This is generating an empty map
array[y, x] = ' ';
}
}
return array;
}
public static void CheckAllNearbySafeSquares(char[,] ComputerMap, char[,] PlayerMap, int x, int y)
{
//Goes through each Y value nearby
for (int yy = y - 1; yy < y + 2; yy++)
{
//Goes through each X value nearby
for (int xx = x - 1; xx < x + 2; xx++)
{
if (xx < 0 || xx > 9 || yy < 0 || yy > 4)
{
//Do nothing since this square doesn't exist
}
//If the square is empty, reveal it
//Make sure to check that the player map is empty or the program will trigger
// an infinite recursive loop
else if (PlayerMap[yy, xx] == ' ' && ComputerMap[yy, xx] == '-')
{
//If the square is empty reveal it and then recursively check all nearby squares
PlayerMap[yy,xx] = ComputerMap[yy,xx];
CheckAllNearbySafeSquares(ComputerMap, PlayerMap, xx, yy);
}
else if (ComputerMap[yy, xx] == 'X')
{
//Do nothing if that square is a bomb
}
else
{
//If the square is a number reveal it but don't recursively check that one.
PlayerMap[yy, xx] = ComputerMap[yy, xx];
}
}
}
}
//This allows a user to designate a spot as a bomb, same as a "right-click"
public static void DeclareBomb(char[,] PlayerMap, int x, int y)
{
PlayerMap[y, x] = 'X';
}
public static void Lose()
{
Console.WriteLine("Sorry you lose!");
Console.ReadLine();
Environment.Exit(0);
}
public static void Win()
{
Console.WriteLine("Congrats you win!");
Console.ReadLine();
Environment.Exit(0);
}
public static void CheckWinCondition(char[,] ComputerMap, char[,] PlayerMap)
{
//This first loop is looping through the ROWS (y value), 5 rows
for (int y = 0; y < 5; y++)
{
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
//If they are both equal, keep going and see if we win
if (ComputerMap[y, x] == PlayerMap[y, x])
{
//Do nothing, but keep looping and see if we win
}
else
{
return;
}
}
}
//If every square in the player matrix and the NPC matrix are the same you win
Win();
}
//This is the same as a left-click, means the user thinks the spot is safe
public static void Reveal(char[,] ComputerMap, char[,] PlayerMap, int x, int y)
{
//If the user clicks on a bomb they die.
if (ComputerMap[y, x] == 'X')
{
Lose();
}
//If the user clicked on an empty square it reveals nearby squares
else if (ComputerMap[y, x] == '-')
{
CheckAllNearbySafeSquares(ComputerMap, PlayerMap, x, y);
}
else
{
//If the user just clicked on a number, just reveal the number;
PlayerMap[y, x] = ComputerMap[y, x];
}
}
//If the player enters cheatcode lowercase they win
public static void CheatCode(char[,] ComputerMap, char[,] PlayerMap)
{
//This first loop is looping through the ROWS (y value), 5 rows
for (int y = 0; y < 5; y++)
{
//This second loop is looping through the COLUMNS (x value), 10 columns
for (int x = 0; x < 10; x++)
{
//Updates the map so that the player map is equal to the computer's map
PlayerMap[y, x] = ComputerMap[y, x];
}
}
}
public static void PlayerInput(char[,] ComputerMap, char[,] PlayerMap)
{
//This clears the console so all they see is the map and options to pick
Console.Clear();
//Variables we need for the user input
String UserInput, UserInputX, UserInputY;
int x, y;
//These lines are the output that pront the user what they should do
Console.WriteLine(" Minesweeper map: ");
MapDisplay(PlayerMap);
Console.WriteLine("Would you like to designate a square as safe or designate a square as a bomb?");
Console.WriteLine("Enter 1 to designate a square as safe or 2 to designate a square as a bomb.");
Console.WriteLine("Enter 'cheatcode' to win automatically or 'displaymap' to display the computer's map including bombs");
Console.WriteLine("(Enter 3 to quit.)");
//This line accepts the user input and puts it into "UserInput"
UserInput = Console.ReadLine();
//If the user says they want to designate a square as safe, do this:
if(UserInput=="1"){
Console.WriteLine("Designating a square as safe: ");
Console.WriteLine("Please enter the X coordinate: ");
UserInputX = Console.ReadLine();
if(UserInputX == "0" || UserInputX == "1" || UserInputX == "2" || UserInputX == "3" || UserInputX == "4" || UserInputX == "5" || UserInputX == "6" || UserInputX == "7" || UserInputX == "8" || UserInputX == "9"){
x = int.Parse(UserInputX);
}else{return;}
Console.WriteLine("Please enter the Y coordinate: ");
UserInputY = Console.ReadLine();
if(UserInputY == "0" || UserInputY == "1" || UserInputY == "2" || UserInputY == "3" || UserInputY == "4"){
y = int.Parse(UserInputY);
}else{return;}
Reveal(ComputerMap, PlayerMap, x, y);
}
//If the user says they want to designate a square as a bomb, do this:
else if(UserInput=="2"){
//Prompts the user for an X coordinate
Console.WriteLine("Designating a square as a bomb: ");
Console.WriteLine("Please enter the X coordinate: ");
//This takes the user input as a string initially
UserInputX = Console.ReadLine();
//This checks to make sure the user input is a number
if(UserInputX == "0" || UserInputX == "1" || UserInputX == "2" || UserInputX == "3" || UserInputX == "4" || UserInputX == "5" || UserInputX == "6" || UserInputX == "7" || UserInputX == "8" || UserInputX == "9"){
//If the user input is a number then cast it into an int
x = int.Parse(UserInputX);
//If the user input is not a number then restart the loop
}else{return;}
//This asks the user for a Y coordinate
Console.WriteLine("Please enter the Y coordinate: ");
//This takes the input as a string initially
UserInputY = Console.ReadLine();
//This checks to ensure the user input is a valid number
if (UserInputY == "0" || UserInputY == "1" || UserInputY == "2" || UserInputY == "3" || UserInputY == "4")
{
//If the user input an integer then we cast the string as an integer
y = int.Parse(UserInputY);
//If the user input is not a number then restart the loop
}else {return; }
//This method "DeclareBomb" just designates a square as a bomb on the player's map.
DeclareBomb(PlayerMap, x, y);
}
//If the user says they want to quit do this:
else if(UserInput=="3"){
Console.WriteLine("Thank you for playing!");
Console.ReadLine();
Environment.Exit(0);
}
else if (UserInput == "cheatcode")
{
Console.WriteLine();
CheatCode(ComputerMap, PlayerMap);
Console.WriteLine();
MapDisplay(PlayerMap);
Console.WriteLine();
}
else if (UserInput == "displaymap")
{
Console.WriteLine();
MapDisplay(ComputerMap);
Console.WriteLine();
Console.ReadLine();
}
//If the user enters invalid input then just restart the loop.
else
{
return;
}
CheckWinCondition(ComputerMap, PlayerMap);
}
//This is the MAIN, it just calls our methods to play the game
static void Main(string[] args)
{
char[,] NPCMap = ComputerMap();
char[,] PlayerMap = EmptyDisplayMapGenerator();
while (true)
{
PlayerInput(NPCMap, PlayerMap);
}
}
}
} | 91e3b1fa078f0c2aae8239811aa17c26e28eaa48 | [
"C#"
] | 1 | C# | Soreasan/C-Sharp-Minesweeper-with-Methods | 161d167a66270a1e5c8481ff51f530f3d36964fc | cc8fefb1b5209e9548b0bc74a658b044d3d94a76 |
refs/heads/master | <repo_name>tsekeres/Heist<file_sep>/Heist/Program.cs
using Heist.Team_Members;
using System;
using System.Collections.Generic;
namespace Heist
{
class Program
{
static void Main(string[] args)
{
List<CrewMember> crew = new List<CrewMember>();
Console.WriteLine("Plan Your Heist!");
Console.WriteLine("First pick a bank difficulty level from 50(easy) to 100(difficult).");
var enteredBankDifficultyLevel = Console.ReadLine();
var bankDifficultyLevel = Convert.ToInt32(enteredBankDifficultyLevel);
Console.WriteLine("Enter a crew member's name:");
var name = Console.ReadLine();
Console.WriteLine($"Enter a Skill Level for {name}. Should be a positive whole number between 1 - 40.");
var skillLevel = int.Parse(Console.ReadLine());
Console.WriteLine($"Enter {name}'s Courage Factor. Should be a decimal between 0.0 to 2.0.");
var courageFactor = decimal.Parse(Console.ReadLine());
var newMember = new CrewMember(name, skillLevel, courageFactor);
crew.Add(newMember);
Console.WriteLine($"Your crew has {crew.Count} members.");
while (name != "")
{
Console.WriteLine("Enter another crew member's name. Or hit enter to stop adding crew members.");
name = Console.ReadLine();
if (name != "")
{
Console.WriteLine($"Enter a Skill Level for {name}. Should still be a positive whole number between 1 - 40.");
skillLevel = int.Parse(Console.ReadLine());
Console.WriteLine($"Enter {name}'s Courage Factor. Should be a decimal between 0.0 to 2.0.");
courageFactor = decimal.Parse(Console.ReadLine());
newMember = new CrewMember(name, skillLevel, courageFactor);
crew.Add(newMember);
Console.WriteLine($"Your crew has {crew.Count} members.");
} else
{
break;
}
}
var crewSkillLevel = 0;
foreach (var member in crew)
{
crewSkillLevel += member.SkillLevel;
}
Console.WriteLine($"Your crew has {crew.Count} members with a skill level total of {crewSkillLevel}");
Console.WriteLine("------------------------");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Enter the number of trial runs you want to see for your heist plan (from 1 to 10):");
var enteredTrialRuns = Console.ReadLine();
var trialRuns = Convert.ToInt32(enteredTrialRuns);
Console.WriteLine($"Your crew will attempt {trialRuns} trial runs.");
var rnd = new Random();
var successfulRuns = 0;
var failedRuns = 0;
for (var i = 0; i < trialRuns; i++)
{
var difficultyLevel = bankDifficultyLevel;
var luckValue = rnd.Next(-10, 10);
difficultyLevel += luckValue;
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"This bank has a difficulty level of {difficultyLevel}.");
if ( difficultyLevel <= crewSkillLevel)
{
Console.WriteLine("Yee Haw! Ya'll done got away with it! Heist successful.");
successfulRuns++;
} else
{
Console.WriteLine("Ya'll are goin away for a long time. Heist failed.");
failedRuns++;
}
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Your crew of {crew.Count} ran through {trialRuns} attempts.");
Console.WriteLine($"With a crew skill level of {crewSkillLevel} you had {successfulRuns} successful attempts.");
Console.WriteLine($"Your crew had {failedRuns} failed attempts.");
if (successfulRuns < failedRuns)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("I wouldn't try this bank.");
} else if (successfulRuns == failedRuns)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("This is touch and go. Go with your gut on this one.");
} else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Go for it. Your crew has got this licked.");
}
}
}
}
<file_sep>/Heist/Team Members/TeamMember.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Heist.Team_Members
{
class CrewMember
{
public string Name { get; set; }
public int SkillLevel { get; set; }
public decimal CourageFactor { get; set; }
public CrewMember(string name, int skillLevel, decimal courageFactor)
{
Name = name;
SkillLevel = skillLevel;
CourageFactor = courageFactor;
}
public void CrewMemberInfo()
{
Console.WriteLine($"Crew Member: {Name}, Skill Level: {SkillLevel}, Courage Factor: {CourageFactor}");
}
}
}
| 24314148636af6c991c9f8adedb23c3902ee5226 | [
"C#"
] | 2 | C# | tsekeres/Heist | 649fa7248f8cee493455957c78361dd594dd2fea | c4da6d9d069df6d6120a8072e86bdecd2c0679d3 |
refs/heads/master | <repo_name>ZippoZeng/UILib<file_sep>/lib/src/main/java/com/github/zippo/uilib/CommonToolbar.java
package com.github.zippo.uilib;
import android.content.Context;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.TintTypedArray;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.github.zippo.lib.R;
/**
* Created by Zippo on 2018/2/23.
* Date: 2018/2/23
* Time: 11:00:49
*/
public class CommonToolbar extends Toolbar {
private static final String TAG = "CommonToolbar";
private TextView mTitleTextView;
private CharSequence mTitleText;
private int mTitleTextColor;
private int mTitleTextAppearance;
private ImageButton mNavButtonView;
public CommonToolbar(Context context) {
super(context);
resolveAttribute(context, null, R.attr.toolbarStyle);
}
public CommonToolbar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
resolveAttribute(context, attrs, R.attr.toolbarStyle);
}
public CommonToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
resolveAttribute(context, attrs, defStyleAttr);
}
private void resolveAttribute(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
// Need to use getContext() here so that we use the themed context
context = getContext();
final TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs,
R.styleable.Toolbar, defStyleAttr, 0);
final int titleTextAppearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0);
if (titleTextAppearance != 0) {
setTitleTextAppearance(context, titleTextAppearance);
}
if (mTitleTextColor != 0) {
setTitleTextColor(mTitleTextColor);
}
a.recycle();
post(new Runnable() {
@Override
public void run() {
if (getLayoutParams() instanceof Toolbar.LayoutParams) {
Log.v(TAG, "is Toolbar.LayoutParams");
((LayoutParams) getLayoutParams()).gravity = Gravity.CENTER;
}
}
});
}
@Override
public CharSequence getTitle() {
return mTitleText;
}
public ImageButton getNavButtonView() {
return mNavButtonView;
}
@Override
public void setTitle(CharSequence title) {
if (!TextUtils.isEmpty(title)) {
if (mTitleTextView == null) {
final Context context = getContext();
mTitleTextView = new TextView(context);
mTitleTextView.setSingleLine();
mTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
if (mTitleTextAppearance != 0) {
mTitleTextView.setTextAppearance(context, mTitleTextAppearance);
}
if (mTitleTextColor != 0) {
mTitleTextView.setTextColor(mTitleTextColor);
}
}
if (mTitleTextView.getParent() != this) {
addCenterView(mTitleTextView);
}
} else if (mTitleTextView != null && mTitleTextView.getParent() == this) {//
// 当title为空时,remove
removeView(mTitleTextView);
}
if (mTitleTextView != null) {
mTitleTextView.setText(title);
}
mTitleText = title;
}
private void addCenterView(View v) {
final ViewGroup.LayoutParams vlp = v.getLayoutParams();
final LayoutParams lp;
if (vlp == null) {
lp = generateDefaultLayoutParams();
} else if (!checkLayoutParams(vlp)) {
lp = generateLayoutParams(vlp);
} else {
lp = (LayoutParams) vlp;
}
addView(v, lp);
}
@Override
public Toolbar.LayoutParams generateLayoutParams(AttributeSet attrs) {
Toolbar.LayoutParams lp = new Toolbar.LayoutParams(getContext(), attrs);
lp.gravity = Gravity.CENTER;
return lp;
}
@Override
protected Toolbar.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
Toolbar.LayoutParams lp;
if (p instanceof Toolbar.LayoutParams) {
lp = new Toolbar.LayoutParams((Toolbar.LayoutParams) p);
} else if (p instanceof ActionBar.LayoutParams) {
lp = new Toolbar.LayoutParams((ActionBar.LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
lp = new Toolbar.LayoutParams((MarginLayoutParams) p);
} else {
lp = new Toolbar.LayoutParams(p);
}
lp.gravity = Gravity.CENTER;
return lp;
}
@Override
protected Toolbar.LayoutParams generateDefaultLayoutParams() {
Toolbar.LayoutParams lp = new Toolbar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
return lp;
}
@Override
public void setTitleTextAppearance(Context context, @StyleRes int resId) {
mTitleTextAppearance = resId;
if (mTitleTextView != null) {
mTitleTextView.setTextAppearance(context, resId);
}
}
@Override
public void setTitleTextColor(@ColorInt int color) {
mTitleTextColor = color;
if (mTitleTextView != null) {
mTitleTextView.setTextColor(color);
}
}
}
<file_sep>/app/src/main/java/com/github/zippo/uilib/entity/BaseModel.java
package com.github.zippo.uilib.entity;
import org.json.JSONObject;
/**
* Created by Zippo on 2018/2/23.
* Date: 2018/2/23
* Time: 11:16:26
*/
public abstract class BaseModel implements IParse {
@Override
public abstract void decode(JSONObject object);
@Override
public abstract JSONObject encode(Object o);
@Override
public void release() {
}
}
<file_sep>/app/src/main/java/com/github/zippo/uilib/app/BaseApplication.java
package com.github.zippo.uilib.app;
import android.app.Application;
/**
* Created by Zippo on 2018/2/23.
* Date: 2018/2/23
* Time: 11:21:46
*/
public class BaseApplication extends Application {
}
| 24a6e58f4caa8347a9ca709f1442918ced03acb2 | [
"Java"
] | 3 | Java | ZippoZeng/UILib | 5c5cbf700832d33c03e28ce655fd55706bfdbee3 | 293b819e5f1a7f6f2c4ea524925a88d528914a21 |
refs/heads/master | <file_sep>package com.imook.client.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class home {
@Value("${server.port}")
private String port;
@RequestMapping("/hello")
@ResponseBody
public String home(){
return "hello"+port;
}
}
| 64222ae0f87635c6f5cf946ee78928ba43f696cc | [
"Java"
] | 1 | Java | RockyYao/eureka | 8fb5a76d10e9d48b5b50ada89401ce309139aa1a | e3779b354edb527e7e14fc51a62cfdcab325d7b6 |
refs/heads/master | <repo_name>JoeyW1991/docker-cpptrade<file_sep>/Dockerfile
FROM ubuntu:18.04 as base
COPY sources.list /etc/apt/sources.list
RUN set -o errexit -o nounset \
&& apt-get update \
&& apt-get install -y --no-install-recommends libevent-dev libssl-dev uuid-dev libonig-dev librocksdb-dev libunivalue-dev \
&& rm -rf /var/lib/apt/lists
FROM base as builder
RUN set -o errexit -o nounset \
&& apt-get update \
&& apt-get install -y --no-install-recommends libtool autoconf automake make gcc unzip wget g++ cmake
RUN set -o errexit -o nounset \
&& echo "Install evhtp" \
&& wget --no-check-certificate https://github.com/criticalstack/libevhtp/archive/1.2.16.tar.gz -O /tmp/evhtp.tar.gz \
&& cd /tmp && tar zxvf evhtp.tar.gz && cd /tmp/libevhtp-1.2.16/build \
&& cmake .. && make && make install
RUN set -o errexit -o nounset \
&& echo "Install cpptrade" \
&& wget --no-check-certificate https://codeload.github.com/bloq/cpptrade/zip/master -O /tmp/cpptrade.zip \
&& cd /tmp && unzip cpptrade.zip && rm cpptrade.zip
COPY Makefile.am /tmp/cpptrade-master/Makefile.am
RUN set -o errexit -o nounset \
&& cd /tmp/cpptrade-master/\
&& ./autogen.sh && ./configure && make
FROM base
COPY --from=builder /usr/local/lib/libevhtp.a /usr/local/lib/
COPY --from=builder /usr/local/include/evhtp/ /usr/local/include/evhtp.h /usr/local/include/
COPY --from=builder /usr/local/lib/pkgconfig/evhtp.pc /usr/local/lib/pkgconfig/
COPY --from=builder /tmp/cpptrade-master/obdb /tmp/cpptrade-master/obsrv /usr/local/sbin/
ADD start.sh /start
RUN mkdir -p /etc/cpptrde/ \
&& echo "{}" > /etc/cpptrde/config-obsrv.json \
&& chmod +x /start
EXPOSE 7979
CMD ["/start"]
<file_sep>/start.sh
#!/bin/bash
PID_FN="/run/obsrv.pid"
CFG_FN="/etc/cpptrde/config-obsrv.json"
if [ -f $PID_FN ];then
if [ `ps aux | grep -c obsrv | grep -v grep` -eq 0 ];then
rm $PID_FN
else
echo Daemon PID file already exists.
exit 1
fi
fi
# Start daemon
obsrv -c $CFG_FN -p $PID_FN
| cfede51ebc32726bc491a4cb4f09cb50eb570af1 | [
"Dockerfile",
"Shell"
] | 2 | Dockerfile | JoeyW1991/docker-cpptrade | 078e162aa2beb4507c46cfb1d4369a6e747f309d | 927f264968741b717af3c8b5f8e26ff20aa3b3d0 |
refs/heads/master | <file_sep>from cvat.settings.production import *
# add custom apps here
import ldap
from django_auth_ldap.config import LDAPSearch, PosixGroupType
DJANGO_AUTH_TYPE = 'LDAP'
AUTH_LOGIN_NOTE = '''<p>
Please use your LDAP login credentials (the ones you use to login system-wide).
</p>'''
# Baseline configuration.
AUTH_LDAP_SERVER_URI = "ldap://192.168.2.128:389"
# Credentials for LDAP server
AUTH_LDAP_BIND_DN = "cn=admin,dc=jonas,dc=host"
AUTH_LDAP_BIND_PASSWORD = "<PASSWORD>"
# Set up basic user search
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=jonas,dc=host",
ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=jonas,dc=host",
ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)")
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
# Populate the Django user from the LDAP directory.
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
AUTH_LDAP_ALWAYS_UPDATE_USER = True
# Cache group memberships for an hour to minimize LDAP traffic
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
AUTH_LDAP_AUTHORIZE_ALL_USERS = True
#AUTH_LDAP_FIND_GROUP_PERMS = True
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS += ['django_auth_ldap.backend.LDAPBackend']
AUTH_LDAP_ADMIN_GROUPS = [
'cn=admin,dc=jonas,dc=host',
]
AUTH_LDAP_ANNOTATOR_GROUPS = [
'cn=user,dc=jonas,dc=host',
]
AUTH_LDAP_USER_GROUPS = [
'cn=user,dc=jonas,dc=host',
]
AUTH_LDAP_OBSERVER_GROUPS = [
'cn=user,dc=jonas,dc=host',
]
<file_sep># Fork of Computer Vision Annotation Tool (CVAT)
This is my fork of the [CVAT](https://github.com/opencv/cvat/tree/develop) which has been modified to support our system's user directory structure, LDAP authentication, and requirements for loading NITF files.
Command to start docker containers:
```sudo docker-compose -f docker-compose.yml -f docker-compose.override.yml up -d --build```
| 02c7c52dc223277476479dd7ff99e46c10317e8f | [
"Markdown",
"Python"
] | 2 | Python | bryanjonas/cvat | c28fa4001efa23c700be226f7f99873cfcf9cff6 | 3cc8428af10cf8ffbf6b4e931ac9fbe064cfae46 |
refs/heads/master | <repo_name>pyed/tailer<file_sep>/linereader.go
// Copyright 2016-2017 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tailer
import (
"bytes"
"fmt"
"io"
)
type bufferedLineReader struct {
remainingBytesFromLastRead []byte
}
func NewBufferedLineReader() *bufferedLineReader {
return &bufferedLineReader{
remainingBytesFromLastRead: []byte{},
}
}
func (r *bufferedLineReader) ReadAvailableLines(file io.Reader) ([]string, error) {
var lines []string
newBytes, err := read2EOF(file)
if err != nil {
return nil, err
}
lines, r.remainingBytesFromLastRead = splitLines(append(r.remainingBytesFromLastRead, newBytes...))
return lines, nil
}
func (r *bufferedLineReader) Clear() {
r.remainingBytesFromLastRead = []byte{}
}
func read2EOF(file io.Reader) ([]byte, error) {
result := make([]byte, 0)
buf := make([]byte, 512)
for {
n, err := file.Read(buf)
if n > 0 {
// Callers should always process the n > 0 bytes returned before considering the error err.
result = append(result, buf[0:n]...)
}
if err != nil {
if err == io.EOF {
return result, nil
} else {
return nil, fmt.Errorf("read error: %v", err.Error())
}
}
}
}
func splitLines(data []byte) (lines []string, remainingBytes []byte) {
newline := []byte("\n")
lines = make([]string, 0)
remainingBytes = make([]byte, 0)
for _, line := range bytes.SplitAfter(data, newline) {
if bytes.HasSuffix(line, newline) {
line = bytes.TrimSuffix(line, newline)
line = bytes.TrimSuffix(line, []byte("\r")) // Needed for CRLF line endings?
lines = append(lines, string(line))
} else {
// This is the last (incomplete) line returned by SplitAfter(). We will exit the for loop here.
remainingBytes = line
}
}
return lines, remainingBytes
}
<file_sep>/fileTailer_windows.go
// Copyright 2016-2017 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tailer
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"golang.org/x/exp/winfsnotify"
)
func initWatcher(abspath string, _ *autoClosingFile) (*winfsnotify.Watcher, error) {
watcher, err := winfsnotify.NewWatcher()
if err != nil {
return nil, err
}
err = watcher.Watch(filepath.Dir(abspath))
if err != nil {
watcher.Close()
return nil, err
}
return watcher, nil
}
type eventLoop struct {
watcher *winfsnotify.Watcher
}
func startEventLoop(watcher *winfsnotify.Watcher) *eventLoop {
return &eventLoop{
watcher: watcher,
}
}
func (l *eventLoop) Close() error {
// watcher.Close() may be called twice, once for the eventLoop and once for the watcher. This should be fine.
return l.watcher.Close()
}
func (l *eventLoop) Errors() chan error {
return l.watcher.Error
}
func (l *eventLoop) Events() chan *winfsnotify.Event {
return l.watcher.Event
}
func processEvents(event *winfsnotify.Event, _ *winfsnotify.Watcher, fileBefore *autoClosingFile, reader *bufferedLineReader, abspath string, logger simpleLogger) (file *autoClosingFile, lines []string, err error) {
file = fileBefore
lines = []string{}
var truncated bool
logger.Debug("File system watcher received %v.\n", event.String())
// WRITE or TRUNCATE
if file != nil && norm(event.Name) == norm(abspath) && event.Mask&winfsnotify.FS_MODIFY == winfsnotify.FS_MODIFY {
truncated, err = checkTruncated(file)
if err != nil {
return
}
if truncated {
_, err = file.Seek(0, io.SeekStart)
if err != nil {
return
}
}
var freshLines []string
freshLines, err = reader.ReadAvailableLines(file)
if err != nil {
return
}
lines = append(lines, freshLines...)
}
// MOVE or DELETE
if file != nil && norm(event.Name) == norm(abspath) && (event.Mask&winfsnotify.FS_MOVED_FROM == winfsnotify.FS_MOVED_FROM || event.Mask&winfsnotify.FS_DELETE == winfsnotify.FS_DELETE) {
file = nil
reader.Clear()
}
// CREATE
if file == nil && norm(event.Name) == norm(abspath) && event.Mask&winfsnotify.FS_CREATE == winfsnotify.FS_CREATE {
file, err = open(abspath)
if err != nil {
return
}
reader.Clear()
var freshLines []string
freshLines, err = reader.ReadAvailableLines(file)
if err != nil {
return
}
lines = append(lines, freshLines...)
}
return
}
// winfsnotify uses "/" instead of "\" when constructing the path in the event name.
func norm(path string) string {
path = strings.Replace(path, "/", "\\", -1)
path = strings.Replace(path, "\\\\", "\\", -1)
return path
}
// On Windows, logrotate will not be able to delete or move the logfile if grok_exporter keeps the file open.
// The AutoClosingFile has an API similar to os.File, but the underlying file is closed after each operation.
type autoClosingFile struct {
path string
currentPos int64
}
func open(path string) (*autoClosingFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return &autoClosingFile{
path: path,
currentPos: 0,
}, nil
}
func (f *autoClosingFile) Seek(offset int64, whence int) (int64, error) {
file, err := os.Open(f.path)
if err != nil {
return 0, err
}
defer file.Close()
result, resultErr := file.Seek(offset, whence)
f.currentPos, err = file.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
return result, resultErr
}
func (f *autoClosingFile) Read(b []byte) (int, error) {
file, err := os.Open(f.path)
if err != nil {
return 0, err
}
defer file.Close()
_, err = file.Seek(f.currentPos, io.SeekStart)
if err != nil {
return 0, err
}
result, resultErr := file.Read(b)
f.currentPos, err = file.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
return result, resultErr
}
func (f *autoClosingFile) Name() string {
return f.path
}
func (f *autoClosingFile) Close() error {
// nothing to do
return nil
}
func checkTruncated(f *autoClosingFile) (bool, error) {
file, err := os.Open(f.path)
if err != nil {
return false, err
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
return false, fmt.Errorf("%v: Stat() failed: %v", file.Name(), err.Error())
}
return f.currentPos > fileInfo.Size(), nil
}
<file_sep>/linereader_test.go
// Copyright 2016-2017 The grok_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tailer
import (
"io"
"testing"
)
type mockFile struct {
bytes []string
pos int
eof bool
}
func NewMockFile(lines ...string) *mockFile {
return &mockFile{
bytes: lines,
pos: 0,
eof: false,
}
}
func (f *mockFile) Read(p []byte) (int, error) {
if f.eof {
f.eof = false
return 0, io.EOF
} else {
f.eof = true
copy(p, []byte(f.bytes[f.pos])) // In this test the buffer p will alwasy be large enough.
f.pos++
return len(f.bytes[f.pos-1]), nil
}
}
func TestLineReader(t *testing.T) {
file := NewMockFile("This is l", "ine 1\n", "This is line two\nThis is line three\n", "This ", "is ", "line 4", "\n", "\n")
reader := NewBufferedLineReader()
lines, err := reader.ReadAvailableLines(file)
expectEmpty(t, lines, err)
lines, err = reader.ReadAvailableLines(file)
expectLines(t, lines, err, "This is line 1")
lines, err = reader.ReadAvailableLines(file)
expectLines(t, lines, err, "This is line two", "This is line three")
lines, err = reader.ReadAvailableLines(file) // This
expectEmpty(t, lines, err)
lines, err = reader.ReadAvailableLines(file) // is
expectEmpty(t, lines, err)
lines, err = reader.ReadAvailableLines(file) // line 4
expectEmpty(t, lines, err)
lines, err = reader.ReadAvailableLines(file) // \n
expectLines(t, lines, err, "This is line 4")
lines, err = reader.ReadAvailableLines(file) // \n
expectLines(t, lines, err, "")
}
func expectEmpty(t *testing.T, lines []string, err error) {
if err != nil {
t.Error(err)
}
if lines == nil {
t.Error("expected empty slice, but got nil")
}
if len(lines) > 0 {
t.Errorf("expected empty slice, but got len = %v", len(lines))
}
}
func expectLines(t *testing.T, lines []string, err error, expectedLines ...string) {
if err != nil {
t.Error(err)
}
if lines == nil {
t.Error("slice is nil")
}
if len(lines) != len(expectedLines) {
t.Errorf("expected slice with len = %v, but got len = %v", len(expectedLines), len(lines))
}
for i, expectedLine := range expectedLines {
if lines[i] != expectedLine {
t.Errorf("Expected line '%v', but got '%v'.", expectedLine, lines[i])
}
}
}
<file_sep>/README.md
# tailer
from: https://github.com/fstab/grok_exporter/tree/master/tailer
| 50dde0135d3449d1ac59b472e2a914910d39c2a8 | [
"Markdown",
"Go"
] | 4 | Go | pyed/tailer | 376cd2db7eb601bfeb6de212741627624fe993a2 | 98a427eb0985a7ffd881cd94ae1dae62a9630cb9 |
refs/heads/master | <repo_name>navonf/chatalyze-frontend<file_sep>/src/Components/Chat.js
import React, { Component } from 'react'
import {Row, Col, Card, CardBody, CardTitle, CardFooter, InputGroup, InputGroupAddon, Button, Input} from 'reactstrap';
import{Redirect} from 'react-router-dom';
import io from 'socket.io-client';
const empty_string = '';
class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
messages: [],
user_joined: [],
user_disconnected: [],
chat_key: '',
redirect: false
}
this.socket = io('https://api-chatalyze.herokuapp.com');
this.socket.emit('SEND_USERNAME', this.props.location.state.username);
this.socket.on('USER_ADDED', (data) => {
var users = this.state.user_joined
users.push(data);
this.setState({
user_joined: users
});
})
this.socket.on('RECIEVE_MESSAGE', (data) => {
addMessage(data);
});
this.socket.on('CHAT_KEY', (data) => {
this.setState({
chat_key: data
}, () => console.log('key '+ this.state.chat_key));
});
// this.socket.on('WHO_DISCONNECTED', () => {
// this.socket.emit('THIS_PERSON', this.props.location.state.username);
// })
// this.socket.on('PERSON_DISCONNECTED', data => {
// var users_disc = this.state.user_disconnected;
// users_disc.push(data);
// this.setState({
// user_disconnected: users_disc
// })
// })
this.sendMessage = (e) => {
e.preventDefault();
this.socket.emit('SEND_MESSAGE', {
author: this.props.location.state.username,
message: this.state.message
})
this.sendTranscript();
const q = document.getElementById('input_message');
q.value = '';
}
const addMessage = (data) => {
this.setState({
messages: [
...this.state.messages,
data
]
});
}
this.onDisconnect = () => {
var arr = this.state.user_disconnected;
arr.push(this.props.location.state.username);
this.setState({
user_disconnected: arr
});
console.log(this.state.user_disconnected);
this.socket.emit('USER_LEAVING', this.props.location.state.username);
this.setState({
redirect: true
})
}
}
redirectTo(){
if(this.state.redirect){
return(
<Redirect to='/' />
)
}
}
keyPress = (e) => {
if(e.key === 'Enter'){
document.getElementById('send-btn').click()
}
}
sendTranscript() {
var obj = {
key: this.state.chat_key,
user: this.props.location.state.username,
message: this.state.message
}
fetch('https://api-chatalyze.herokuapp.com/conversation/update_transcript', {
method: 'POST',
body: JSON.stringify(obj),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => console.log(res.status));
}
grabInput = (e) => {
this.setState({
message: e.target.value
})
}
render() {
return (
<div style={{overflow: "hidden"}}>
<Row>
<Col>
<Card>
<CardBody>
<CardTitle>
<div>
Hello, {this.props.location.state.username}
<span className="float-right">
<Button outline color="danger" size="sm" onClick={this.onDisconnect}>Logout</Button>
{this.redirectTo()}
</span>
</div>
</CardTitle>
<hr />
<div className="messages">
{
this.state.user_joined.map((user, index) => {
return(
<div key={index} style={{color:'#ED1137'}}>
{user}{' '}has entered the chat.
</div>
)
})
}
{
this.state.user_disconnected.map((user, index) => {
return(
<div key={index} style={{color:'#ED1137'}}>
{user}{' '}has left the chat.
</div>
)
})
}
{
this.state.messages.map((message, index) => {
var back_color = '';
var text_color = ''
{
index % 2 === 0 ? back_color = '#1387FD' : back_color = '#E5E5EB'
}
{
index % 2 === 0 ? text_color = 'white' : text_color = 'black'
}
return(
<div key={index}>
<span style={{fontSize:"1.5rem"}}>{message.author}</span>:{' '}
<span class="rounded-pill px-2 pb-1" style={{backgroundColor:`${back_color}`, color:`${text_color}`, fontSize:"1.5rem"}}>{message.message}</span>
</div>
)
})
}
</div>
</CardBody>
</Card>
</Col>
</Row>
<div class="navbar fixed-bottom mb-2">
<InputGroup>
<Input placeholder="What's your message?" id="input_message" onChange={(e) => this.grabInput(e)} onKeyDown={this.keyPress} />
<InputGroupAddon addonType="append">
<Button outline color="primary" id="send-btn" onClick={this.sendMessage}>Send</Button>
</InputGroupAddon>
</InputGroup>
</div>
</div>
)
}
}
export default Chat;
<file_sep>/src/Components/Login.js
import React, { Component } from 'react';
import { Modal, ModalHeader, ModalFooter, ModalBody } from 'reactstrap';
class Login extends Component {
constructor(props){
super(props);
this.state = {
modal: true,
login: false,
register: false
}
}
render() {
return (
<div style={{backgroundColor: "#2c3030b8", height:"100vh"}}>
<Modal style={{top: "20%"}} isOpen={this.state.modal}>
<ModalHeader>
<span style={{fontSize: "45px", color: "black"}}>
chatalyze
</span>
</ModalHeader>
<ModalBody>
yeet
</ModalBody>
<ModalFooter>
<a href="/" className="btn btn-outline-primary mr-2" role="button">
Login
</a>
<a href="/">
Create an Account
</a>
</ModalFooter>
</Modal>
</div>
)
}
}
export default Login;
<file_sep>/src/Components/Landing.js
import React, { Component } from 'react';
import { DialogContainer, TextField, Button } from 'react-md';
import {Row, Col, Alert} from 'reactstrap';
import ReactTyped from 'react-typed';
import { MdRemoveRedEye } from 'react-icons/md';
import { Redirect } from 'react-router-dom';
import '../styles.css';
class Landing extends Component {
constructor(props){
super(props);
this.state = {
visible: false,
login: false,
register: false,
username: '',
password: '',
verified: false,
redirect: false,
invalid: false
}
}
sendInfo(param) {
const userObj = {
username: this.state.username,
password: <PASSWORD>
}
fetch('https://api-chatalyze.herokuapp.com/user/add_user', {
method: 'POST',
body: JSON.stringify(userObj),
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(resJSON => console.log(resJSON))
.catch(error => console.error('Error:', error));
this.setState({
[param]: false
});
}
show = () => {
this.setState({
visible: true
});
};
hide = () => {
this.setState({
visible: false,
register: false,
register: false
});
};
toggleLogin = () => {
this.setState({
login: true,
register: false
})
}
toggleRegister = () => {
this.setState({
login: false,
register: true
})
}
redirectTo() {
if(this.state.redirect){
return(
<Redirect to={{
pathname: '/chat',
state: {username: this.state.username}
}}/>
)
}
}
verifyLogin() {
const userObj = {
username: this.state.username,
password: <PASSWORD>
}
fetch('https://api-chatalyze.herokuapp.com/user/login', {
method: 'POST',
body: JSON.stringify(userObj),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if(res.status){
this.setState({
verified: true,
redirect: true
});
}
})
}
setInput = (param, e) => {
this.setState({
[param]: e
})
}
render() {
const { visible } = this.state;
const actions = [{
onClick: this.toggleLogin,
primary: true,
children: 'Login',
style: {margin: "auto"}
},
{
onClick: this.toggleRegister,
primary: true,
children: 'Register',
style: {margin: "auto"}
},{
onClick: this.hide,
primary: false,
secondary: true,
children: 'Cancel',
style: {margin: "auto"}
}];
return (
<div style={{backgroundColor: "#202424", height:"100vh"}}>
<DialogContainer
id={1}
visible={visible}
title="Think before you speak."
onHide={this.hide}
modal
actions={actions}
className="login-font"
>
{
this.state.login ?
<p>
<TextField
id="floating-center-title"
label="Username"
lineDirection="center"
placeholder="i.e. JohnSmith123"
className="md-cell md-cell--12"
onChange={(e) => this.setInput("username", e)}
/>
<TextField
id="floating-password"
label="Password"
lineDirection="center"
placeholder="i.e. johnsmith123"
className="md-cell md-cell--12"
type="password"
passwordIcon={<MdRemoveRedEye />}
onChange={(e) => this.setInput("password", e)}
/>
<div className="center-screen">
<Button raised primary onClick={() => this.verifyLogin()}>Submit</Button>
</div>
</p> : null
}
{
this.state.register ?
<p>
<Row form>
<Col md={6}>
<TextField
id="floating-center-title"
label="First"
lineDirection="center"
placeholder="i.e. John"
className="md-cell md-cell--12"
/>
</Col>
<Col md={6}>
<TextField
id="floating-center-title"
label="Last"
lineDirection="center"
placeholder="i.e. Smith"
className="md-cell md-cell--12"
/>
</Col>
</Row>
<Row form>
<TextField
id="floating-center-title"
label="Email"
lineDirection="center"
placeholder="i.e. <EMAIL>"
className="md-cell md-cell--12"
/>
</Row>
<Row form>
<TextField
id="floating-center-title"
label="Username"
lineDirection="center"
placeholder="i.e. JohnSmith123"
className="md-cell md-cell--12"
onChange={(e) => this.setInput("username", e)}
/>
</Row>
<Row form>
<TextField
id="floating-password"
label="Password"
lineDirection="center"
placeholder="i.e. johnsmith123"
className="md-cell md-cell--12"
type="password"
passwordIcon={<MdRemoveRedEye />}
onChange={(e) => this.setInput("password", e)}
/>
</Row>
<div className="center-screen">
<Button raised primary onClick={() => this.sendInfo("register")}>Submit</Button>
</div>
</p> : null
}
{
this.state.invalid ?
<Alert color="danger">
INCORRECT PASSWORD
</Alert> : null
}
{this.redirectTo()}
</DialogContainer>
<div className="mx-auto text-center landing" onClick={this.show}>
<h1 className="mx-auto mb-0 landing-font">chatalyze
<span><img src="chat.png" height="90"/></span>
</h1>
<div className="mx-auto text-center landing-text">
<ReactTyped
strings={["an app to prevent bullying", "an app to prevent abuse", "an app to prevent violence", "an app to prevent harassment", "an app to create a better workplace."]}
typeSpeed={60}
backSpeed={90}
backDelay={1}
smartBackspace={true}
className="typedjs-font"
/>
</div>
</div>
</div>
)
}
}
export default Landing;
| 20385dd51c383283e4e6d00e59676ac3dcc8408e | [
"JavaScript"
] | 3 | JavaScript | navonf/chatalyze-frontend | c7b4f7ded4a7f494a62f17cfb91de78a03efae27 | 3b27d59de40c4de4079b845d7dc2f04f2aa0d628 |
refs/heads/master | <file_sep>'use strict';
var auth = require('./tmp/auth');
var commits = require('./');
commits('breakdance/breakdance', auth)
.then(function(res) {
console.log(res);
})
.catch(console.error)
<file_sep>## Usage
See [github-base][] for documentation for all options and authentication choices.
```js
var commits = require('{%= name %}');
var auth = {
username: 'YOUR_USERNAME',
password: '<PASSWORD>'
};
commits('breakdance/breakdance', auth)
.then(function(res) {
console.log(res);
})
```
| 7a95b573a40592249550d65472aca49acd90ac7b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | jonschlinkert/commits | 69c7fd9b9d68922e3b2f5082244aa59d738491d7 | bfc02085f4936b57c3f92407ec51daba28b90005 |
refs/heads/master | <repo_name>apache1011/Quarto<file_sep>/js/game/AI.js
Node = function(bases, pieces){
var competeTimes = 0;
var curBases = bases;
var curPieces = pieces;
};
var AI = {
enable : false,
difficulty : 0,
playerNum : 2,
// AI put real piece
put: function(i, j){
//move the piece to the selected base
var base = QUARTO.board.getBase(i, j);
GAME_STATES.SET_ON_BOARD = false;
GAME_STATES.PICK_FOR_PLAYER = true;
selectedMesh.putOnBoard(base, function() {
if (selectedMesh != null) {
selectedMesh.setSelected(false);
selectedMesh = null;
var winTest = QUARTO.board.isWin();
if (winTest.finish) {
goFinish(winTest.bases, winTest.draw);
} else {
// display next action
GUI.setCurrentAction(QUARTO.currentPlayer, GUI.PICK_ACTION);
}
}
});
},
// AI
pick(mesh){
// Unselect all pieces
QUARTO.pieces.forEach(function(p) {
p.setSelected(false);
});
// Set this mesh as selected
mesh.setSelected(true, QUARTO.scene.getMaterialByID("sp"));
// Keep in memory the selected one
selectedMesh = mesh;
// Switch player
switchPlayer();
},
getAvailablePos: function(bases){
var empty = []
for(var i = 0; i < Gameboard.LINE; ++i){
for(var j = 0; j < Gameboard.COL; ++j){
if(!bases[i][j].piece){
empty.push([i,j]);
}
}
}
return empty;
},
getAvailablePiece: function(pieces){
var available = [];
pieces.forEach(p => {
if(!p.isOnBoard && !p.isSelected){
available.push(p);
}
});
return available;
},
getAvailablePiece2: function(pieces){
var available = [];
pieces.forEach(p => {
if(!p.isSelected){
available.push(p);
}
});
return available;
},
randomPut: function(bases){
var empty = this.getAvailablePos(bases)
var pos = empty[Math.floor(Math.random()*empty.length)];
return pos;
},
randomPick: function(pieces){
var available = this.getAvailablePiece(pieces);
var mesh = available[Math.floor(Math.random()*available.length)];
return mesh;
},
resetOnPointDown: function(){
QUARTO.scene.onPointerDown = function (evt, pickResult) {
if (GAME_STATES.GAME_STARTED) {
if (pickResult.hit && !GAME_STATES.IS_FINISHED) {
var mesh = pickResult.pickedMesh;
// IF the player choose a piece for the other player
if (GAME_STATES.PICK_FOR_PLAYER && mesh instanceof Piece && !mesh.isOnBoard) {
// Unselect all pieces
QUARTO.pieces.forEach(function(p) {
p.setSelected(false);
});
// Set this mesh as selected
mesh.setSelected(true, QUARTO.scene.getMaterialByID("sp"));
// Keep in memory the selected one
selectedMesh = mesh;
// Switch player
switchPlayer();
// disable onPointerDown listener
if(QUARTO.model == "robot"){
QUARTO.scene.onPointerDown = null;
}
} else if (GAME_STATES.SET_ON_BOARD && mesh instanceof Base) {
// If the base does not contain a piece already
if (!mesh.piece) {
//move the piece to the selected base
var base = QUARTO.board.getBase(mesh.line, mesh.col);
GAME_STATES.SET_ON_BOARD = false;
GAME_STATES.PICK_FOR_PLAYER = true;
selectedMesh.putOnBoard(base, function() {
if (selectedMesh != null) {
selectedMesh.setSelected(false);
selectedMesh = null;
var winTest = QUARTO.board.isWin();
console.log(winTest);
if (winTest.finish) {
goFinish(winTest.bases, winTest.draw);
} else {
// display next action
GUI.setCurrentAction(QUARTO.currentPlayer, GUI.PICK_ACTION);
}
}
});
}
}
}
}
}
},
exNode: function(test_num){
var real_pos = this.getAvailablePos(QUARTO.board.bases);
var real_piece = this.getAvailablePiece(QUARTO.pieces);
var pos_len = real_pos.length;
var piece_len = real_piece.length;
var maxValue = -10000;
var maxPos = null;
var maxPiece = null;
for(var i = 0; i < pos_len; ++i){
for(var j = 0; j < piece_len; ++j){
var value = 0;
for(var t = 0; t < test_num; ++t){
var v = new VirtualGame(1);
var virtual_pos = this.getAvailablePos(v.bases);
var virtual_piece = this.getAvailablePiece(v.pieces);
v.put(virtual_pos[i]);
v.pick(virtual_piece[j]);
var winTest = v.isWin();
if(winTest.finish){
console.log("finishCase");
return {pos: real_pos[i], piece: real_piece[j]};
}
var res = v.runGame();
switch(res){
case 1:
value--;
break;
case 2:
value++;
break;
default:
break;
}
}
if(value > maxValue){
maxValue = value;
maxPos = i;
maxPiece = j;
}
}
}
console.log(value);
return {pos: real_pos[maxPos], piece: real_piece[maxPiece]};
}
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Object.defineProperty(QUARTO, 'currentPlayer', {
get: function() {
return currentPlayer;
},
set: async function(value){
currentPlayer = value;
if(currentPlayer == AI.playerNum && AI.enable){
switch(AI.difficulty){
case 0:
await sleep(500);
var pos = AI.randomPut(QUARTO.board.bases);
AI.put(pos[0], pos[1]);
await sleep(1000);
var mesh = AI.randomPick(QUARTO.pieces);
AI.pick(mesh);
AI.resetOnPointDown();
break;
case 1:
await sleep(50);
var decision = AI.exNode(300);
AI.put(decision.pos[0], decision.pos[1]);
await sleep(1000);
AI.pick(decision.piece);
AI.resetOnPointDown();
console.log(selectedMesh.isSelected);
break;
case 2:
await sleep(50);
var decision = AI.exNode(1500);
AI.put(decision.pos[0], decision.pos[1]);
await sleep(1000);
AI.pick(decision.piece);
AI.resetOnPointDown();
console.log(selectedMesh.isSelected);
break;
}
}
}
})<file_sep>/js/game/Index.js
var humanModel = function(){
QUARTO.model = "human";
GUI._removePage(GUI._get("indexWrapper"));
}
var robotModel = function(){
QUARTO.model = "robot";
GUI._removePage(GUI._get("indexWrapper"));
GUI._removePage(GUI._get("loginWrapper"));
}
var setDifficulty = function(difficulty = 0){
// Create players
var name1 = "YOU";
var name2 = "ROBOT";
QUARTO.players = [
new Player(name1, BABYLON.Color3.Green()),
new Player(name2, BABYLON.Color3.Red())
];
// Display loader
GUI.displayLoader();
// Display names
GUI.displayNames(name1, name2);
// Hide the login screen when the scene is ready
QUARTO.scene.executeWhenReady(function() {
GUI._removePage(GUI._get("levelChooseWrapper"))
GUI.displayStartingTutorial();
});
AI.enable = true;
AI.difficulty = difficulty;
}
var setSkyBox = function(){
}<file_sep>/README.md
# Quarto
运行方式:部署到wamp服务器上运行或访问http://172.16.17.32/quarto/
运行环境:ES6
#### 说明:
QUARTO的游戏规则在游戏中有详细教程
游戏分为双人对战模式和人机对战模式
人机对战有三种难度的AI可供选择
菜鸡难度为随机算法,AI随机选择位置和棋子
另外两种难度使用蒙特卡洛树搜索算法构建游戏的决策树,AI将选择胜率最大的节点走下去
普通难度模拟次数为300次
大佬难度模拟次数为1500次 | 9254d3587ef9d82945d3c0ab29c7ee4e59817646 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | apache1011/Quarto | 1cce715a63ba88e5f9d218904000530de00a135c | f2947019c1b88e97d5265b4dee3e094287e9cb1b |
refs/heads/master | <repo_name>n-azemachi/Rails_blog<file_sep>/app/models/article.rb
class Article < ApplicationRecord
belongs_to :user
validates :title, :body, presence: true
attachment :image
end
<file_sep>/README.md
# README
* Name Rails Blog
this use only portfolio
Overview
This is a simple blog service.
You can post articles, upload photos, and change your profile.
| fd911b065fe47a0ddd39d4775edbc2debfc482f9 | [
"Markdown",
"Ruby"
] | 2 | Ruby | n-azemachi/Rails_blog | 19c7981ba8b5f26f1f07b8fdaf655f6586053c18 | 67fe459bd446145a0e96197ee2bc4c4cc400f659 |
refs/heads/master | <repo_name>Aziiiz/aws_ec2_reboot<file_sep>/README.md
# aws_ec2_reboot
reboting ec2 instance
<file_sep>/aws-reboot.go
package goAws
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
t "github.com/tom"
)
c := make(chan error)
type config struct {
Aws struct {
AcKeyID string
SecKeyID string
}
}
func (cfg *config) Default() {
cfg.Aws.AcKeyID = ""
cfg.Aws.SecKeyID = ""
}
var gConfig config
func Init() error {
gConfig.Default()
err := t.LoadConfig("collection.json", &gConfig)
if nil != err {
t.Log(t.Error, err)
}
return err
}
// StopInstance ???
func StopInstance(svc ec2iface.EC2API, instanceID *string, stsInput ec2.DescribeInstancesInput) error {
// snippet-start:[ec2.go.start_stop_instances.stop]
input := &ec2.StopInstancesInput{
InstanceIds: []*string{
instanceID,
},
DryRun: aws.Bool(true),
}
_, err := svc.StopInstances(input)
awsErr, ok := err.(awserr.Error)
if ok && awsErr.Code() == "DryRunOperation" {
input.DryRun = aws.Bool(false)
_, err = svc.StopInstances(input)
// snippet-end:[ec2.go.start_stop_instances.stop]
if err != nil {
return err
}
err = svc.WaitUntilInstanceStopped(&stsInput)
return nil
}
return err
}
// StartInstance ???
func StartInstance(svc ec2iface.EC2API, instanceID *string, stsInput ec2.DescribeInstancesInput) (string, error) {
// snippet-start:[ec2.go.start_stop_instances.start]
// var waitGroup sync.WaitGroup
input := &ec2.StartInstancesInput{
InstanceIds: []*string{
instanceID,
},
DryRun: aws.Bool(true),
}
_, err := svc.StartInstances(input)
awsErr, ok := err.(awserr.Error)
if ok && awsErr.Code() == "DryRunOperation" {
// Set DryRun to be false to enable starting the instances
input.DryRun = aws.Bool(false)
_, err := svc.StartInstances(input)
// snippet-end:[ec2.go.start_stop_instances.start]
if err != nil {
return "", err
}
err = svc.WaitUntilInstanceRunning(&stsInput)
description, err := svc.DescribeInstances(&stsInput)
publicIp := description.Reservations[0].Instances[0].PublicIpAddress
publicIP := *publicIp
return publicIP, nil
}
return "", err
}
func RestartEc2(insID, accessKey, secretKey, region string) (string, error) {
var publicIp string
var err error
instanceID := flag.String("i", insID, "the id of instance to reboot")
flag.Parse()
if *instanceID == "" {
fmt.Println("(-s START | STOP -i INSTANCE-ID")
return "", nil
}
// setting configs
//access key, secret key token key(optional)
sess := session.Must(session.NewSessionWithOptions(session.Options{
Config: aws.Config{
CredentialsChainVerboseErrors: aws.Bool(true),
Credentials: credentials.NewStaticCredentials(accessKey, secretKey, ""),
Region: aws.String(region),
},
}))
svc := ec2.New(sess)
// snippet-end:[ec2.go.start_stop_instances.session]
statusInput := ec2.DescribeInstancesInput{
InstanceIds: []*string{
instanceID,
},
}
if err = StopInstance(svc, instanceID, statusInput); nil == err {
if publicIp, err = StartInstance(svc, instanceID, statusInput); nil == err {
return publicIp, err
}
}
return "", err
}
| 885fe2a78e7a0f04b19f20771d6e09f82596f074 | [
"Markdown",
"Go"
] | 2 | Markdown | Aziiiz/aws_ec2_reboot | e4863cb54a4c1dc41ae7720363c943660eef97c7 | fc5abe801d8422c834e0d90390adcd9aed1f9148 |
refs/heads/master | <repo_name>Sgarcia10/leal<file_sep>/src/client/app/containers/user/user.module.ts
import { NgModule } from '@angular/core';
import { UserComponent } from './user.component';
import { HeaderComponent } from '../../components/header/header.component';
import { SharedModule } from '../../shared/shared.module';
import { ProfileComponent } from '../../components/profile/profile.component';
import { TransactionFeedComponent } from '../../components/transaction-feed/transaction-feed.component';
import { TransactionComponent } from '../../components/transaction/transaction.component';
import { DialogTransactionDetailComponent } from '../../components/dialog-transaction-detail/dialog-transaction-detail.component';
import { DateFilterComponent } from '../../components/date-filter/date-filter.component';
@NgModule({
declarations: [
UserComponent,
HeaderComponent,
ProfileComponent,
TransactionFeedComponent,
TransactionComponent,
DialogTransactionDetailComponent,
DateFilterComponent
],
imports: [SharedModule],
entryComponents: [DialogTransactionDetailComponent]
})
export class UserModule {}
<file_sep>/src/client/app/core/models/transactionsDTO.ts
import { Transaction } from './transaction';
export interface TransactionsDTO {
userId: string;
data: Transaction[];
}
<file_sep>/src/client/app/core/models/userDTO.ts
import { User } from './user';
export interface UserDTO {
code: number;
token: string;
user: User;
}
<file_sep>/src/client/app/core/guards/auth.guard.spec.ts
import { TestBed, async, inject } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
import { Store, StoreModule } from '@ngrx/store';
import { reducers } from '../../store';
import { Router } from '@angular/router';
describe('AuthGuard', () => {
let routerStub: Partial<Router>;
beforeEach(() => {
routerStub = {
navigate: () => null
};
TestBed.configureTestingModule({
providers: [AuthGuard, { provide: Router, useValue: routerStub }, Store],
imports: [StoreModule.forRoot(reducers)]
});
});
it('should ...', inject([AuthGuard], (guard: AuthGuard) => {
expect(guard).toBeTruthy();
}));
});
<file_sep>/src/client/app/components/date-filter/date-filter.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as moment from 'moment';
@Component({
selector: 'app-date-filter',
templateUrl: './date-filter.component.html',
styleUrls: ['./date-filter.component.scss']
})
export class DateFilterComponent implements OnInit {
@Output() filter$ = new EventEmitter<{ fromDate: string; toDate: string }>();
fromDate: FormControl;
toDate: FormControl;
moment = moment;
constructor() {}
ngOnInit() {
this.fromDate = new FormControl('', Validators.required);
this.toDate = new FormControl({ value: '', disabled: true }, Validators.required);
this.fromDate.valueChanges.subscribe(value => {
if (this.fromDate.valid) this.toDate.enable();
else this.toDate.disable();
});
}
filter() {
const momentFromDate: moment.Moment = this.fromDate.value;
const momentToDate: moment.Moment = this.toDate.value;
const startDate = momentFromDate.format('YYYY-MM-DD');
const endDate = momentToDate.format('YYYY-MM-DD');
this.filter$.emit({ fromDate: startDate, toDate: endDate });
}
display(): boolean {
return true;
}
}
<file_sep>/src/client/app/store/auth/auth.effects.ts
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { switchMap, map, catchError, tap } from 'rxjs/operators';
import { of } from 'rxjs/';
import { AuthActions } from './auth.actions';
import { AuthService } from '../../core/services/auth/auth.service';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable()
export class AuthEffects {
constructor(private actions: Actions, private service: AuthService) {}
@Effect()
login = this.actions.pipe(
ofType<AuthActions.Login>(AuthActions.Type.LOGIN),
switchMap(auth =>
this.service.login(auth.payload).pipe(
map(res => new AuthActions.LoginSuccess(res)),
catchError((err: HttpErrorResponse) => of(new AuthActions.LoginFailed(err.error)))
)
)
);
@Effect({ dispatch: false })
logout = this.actions.pipe(
ofType<AuthActions.Logout>(AuthActions.Type.LOGOUT),
tap(auth => this.service.logout())
);
}
<file_sep>/src/client/app/core/services/utils/dialog.service.ts
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Injectable } from '@angular/core';
import { ComponentType } from '@angular/cdk/typings/portal';
@Injectable()
export class DialogService {
private dialogRef: MatDialogRef<any>;
constructor(private dialog: MatDialog) {}
openDialogTransactionDetail(component: ComponentType<any>, options?: any) {
this.dialogRef = this.dialog.open(component, {
disableClose: false,
width: '450px',
panelClass: 'app-dialog-transaction-detail',
data: options !== undefined ? options.data : {}
});
return this.dialogRef;
}
close(dialogResult?: any): void {
this.dialogRef.close(dialogResult);
}
}
<file_sep>/src/client/app/core/services/transaction/transaction.service.spec.ts
import { TestBed, inject, async } from '@angular/core/testing';
import { TransactionService } from './transaction.service';
import { HttpClient } from '@angular/common/http';
describe('TransactionService', () => {
let httpServiceStub: Partial<HttpClient>;
let http: HttpClient;
let service: TransactionService;
beforeEach(() => {
httpServiceStub = {
post: () => null
};
TestBed.configureTestingModule({
providers: [TransactionService, { provide: HttpClient, useValue: httpServiceStub }]
}).compileComponents();
http = TestBed.get(HttpClient);
service = TestBed.get(TransactionService);
});
it('should be created', async(() => {
expect(service).toBeTruthy();
}));
});
<file_sep>/src/client/app/core/models/custom-action.ts
import { Action } from '@ngrx/store';
export interface CustomAction<T = {}> extends Action {
readonly payload?: T;
}
<file_sep>/src/client/app/components/transaction-feed/transaction-feed.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import * as moment from 'moment';
import { isNullOrUndefined } from 'util';
@Component({
selector: 'app-transaction-feed',
templateUrl: './transaction-feed.component.html',
styleUrls: ['./transaction-feed.component.scss']
})
export class TransactionFeedComponent implements OnInit {
_transactionFeed: { _id: string; position: number; createdDate: string }[];
displayedColumns: string[] = ['position', 'createdDate', 'actions'];
@Input() loading: boolean;
@Output() viewDetail$ = new EventEmitter<string>();
constructor() {}
ngOnInit() {}
/**
*
*
* @memberof TransactionFeedComponent
*/
@Input()
set transactionFeed(
transactions: { _id: string; position: number; createdDate: string }[]
) {
this._transactionFeed =
transactions.map((t, i) => {
return {
_id: t._id,
position: i + 1,
createdDate: moment(t.createdDate).format('YYYY-MM-DD')
};
}) || [];
}
/**
* Get transaction feed
*
* @readonly
* @type {{ _id: string; position: number; createdDate: string }[]}
* @memberof TransactionFeedComponent
*/
get transactionFeed(): { _id: string; position: number; createdDate: string }[] {
return this._transactionFeed;
}
/**
*
*
* @returns {boolean}
* @memberof TransactionFeedComponent
*/
isLoadingResults(): boolean {
if (!isNullOrUndefined(this._transactionFeed)) return false;
else return true;
}
/**
* Emit event to view transaction detail
*
* @param {string} _id
* @memberof TransactionFeedComponent
*/
viewDetail(_id: string) {
this.viewDetail$.emit(_id);
}
}
<file_sep>/src/client/app/app.routing.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserComponent } from './containers/user/user.component';
import { LoginComponent } from './containers/login/login.component';
import { AuthGuard } from './core/guards/auth.guard';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'user', component: UserComponent, canActivate: [AuthGuard] }, // <-- delete this line
{ path: '**', redirectTo: '/user', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: false } // <-- debugging purposes only
)
],
exports: [RouterModule]
})
export class AppRoutingModule {}
<file_sep>/src/client/app/store/auth/auth.actions.ts
import { Action } from '@ngrx/store';
import { User } from '../../core/models/user';
import { ErrorLogin } from '../../core/models/errorLogin';
import { LoginDTO } from '../../core/models/loginDTO';
import { CustomAction } from '../../core/models/custom-action';
export namespace AuthActions {
export enum Type {
LOGIN = '[AUTH] LOGIN',
LOGIN_SUCCESS = '[AUTH] LOGIN_SUCCESS',
LOGIN_FAILED = '[AUTH] LOGIN_FAILED',
LOGOUT = '[AUTH] LOGOUT'
}
export type ClassType = Login | LoginSuccess | LoginFailed | Logout;
export class Login implements CustomAction {
readonly type = Type.LOGIN;
constructor(readonly payload: LoginDTO) {}
}
export class LoginSuccess implements CustomAction {
readonly type = Type.LOGIN_SUCCESS;
constructor(readonly payload: User) {}
}
export class LoginFailed implements CustomAction {
readonly type = Type.LOGIN_FAILED;
constructor(readonly payload: ErrorLogin) {}
}
export class Logout implements CustomAction {
readonly type = Type.LOGOUT;
constructor() {}
}
}
<file_sep>/src/client/app/store/auth/auth.state.ts
import { User } from '../../core/models/user';
import { ErrorLogin } from '../../core/models/errorLogin';
import { UserDTO } from '../../core/models/userDTO';
import { isNullOrUndefined } from 'util';
export interface AuthState {
user: User;
error: ErrorLogin;
authenticating: boolean;
}
const getDefaultUser: () => User = () => {
const currentUser: UserDTO = JSON.parse(localStorage.getItem('currentUser'));
if (isNullOrUndefined(currentUser)) return null;
return currentUser.user;
};
export const defaultAuthState: AuthState = {
user: getDefaultUser(),
error: null,
authenticating: false
};
<file_sep>/src/client/app/core/services/transaction/transaction.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TransactionsDTO } from '../../models/transactionsDTO';
import { map, delay } from 'rxjs/operators';
import { Transaction } from '../../models/transaction';
@Injectable({
providedIn: 'root'
})
export class TransactionService {
/**
*Creates an instance of TransactionService.
* @param {HttpClient} http
* @memberof TransactionService
*/
constructor(private http: HttpClient) {}
/**
* Get all transactions
*
* @returns {Observable<TransactionsDTO>}
* @memberof TransactionService
*/
getAll(): Observable<Transaction[]> {
return this.http
.get<TransactionsDTO>('/api/user/my/transactions')
.pipe(map(transactionsDTO => transactionsDTO.data));
}
/**
* Get transactions by creation dates
*
* @returns {Observable<Transaction[]>}
* @memberof TransactionService
*/
getByDates(fromDate: string, toDate: string): Observable<Transaction[]> {
const params = new HttpParams()
.append('startDate', fromDate)
.append('endDate', toDate);
return this.http
.get<TransactionsDTO>('/api/user/my/transactions', {
params: params
})
.pipe(
delay(500),
map(transactionsDTO => transactionsDTO.data)
);
}
}
<file_sep>/src/client/app/core/guards/auth.guard.ts
import { Injectable } from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthState } from '../../store/auth';
import { Store, select } from '@ngrx/store';
import { selectAuth } from '../../store';
import { isNullOrUndefined } from 'util';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
authState$: Observable<AuthState>;
isLogged: boolean;
/**
*Creates an instance of LoginComponent.
* @param {AuthService} authService
* @param {Router} router
* @memberof LoginComponent
*/
constructor(private store: Store<AuthState>, private router: Router) {
this.isLogged = false;
this.authState$ = this.store.pipe(select(selectAuth));
this.authState$.subscribe(state => {
if (state && !isNullOrUndefined(state.user)) {
this.isLogged = true;
}
});
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.checkLogin();
}
checkLogin(): boolean {
if (this.isLogged) {
return true;
}
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
<file_sep>/src/client/app/core/helpers/jwt.helper.ts
import { LoginDTO } from '../models/loginDTO';
import { UserDTO } from '../models/userDTO';
export class JwtHelper {
public static addJwt(): { [Authorization: string]: string } {
// ensure request options and headers are not null
// add authorization header with jwt token
let jwtHeader: { [Authorization: string]: string } = {};
const currentUser: UserDTO = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
jwtHeader = { Authorization: `Bearer ${currentUser.token}` };
}
return jwtHeader;
}
}
<file_sep>/README.md
<p align="center">
<h1><NAME></h1>
</p>
## Description
Angular 6 Project
## Installation
```bash
$ npm install
```
## Running the client
```bash
# Development (watch mode)
$ npm run client:dev
# Production build
$ npm run client:build
```
## Test
```bash
# unit tests
$ npm run test or $ npm t
# unit tests watch
$ npm run test:watch
# test coverage
$ npm run test:cov
```
## License
Nest is [MIT licensed](LICENSE).
<file_sep>/src/client/app/components/date-filter/date-filter.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DateFilterComponent } from './date-filter.component';
import { SharedModule } from '../../shared/shared.module';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material';
import {
MomentDateAdapter,
MAT_MOMENT_DATE_FORMATS
} from '@angular/material-moment-adapter';
import * as moment from 'moment';
const providers = [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
];
describe('DateFilterComponent', () => {
let component: DateFilterComponent;
let fixture: ComponentFixture<DateFilterComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DateFilterComponent],
imports: [SharedModule],
providers: [...providers, moment]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DateFilterComponent);
component = fixture.componentInstance;
jest.spyOn(component, 'display').mockReturnValue(false);
fixture.detectChanges();
});
it('should create', () => {
component.ngOnInit();
expect(component).toBeTruthy();
});
});
<file_sep>/src/client/app/core/services/auth/auth.service.spec.ts
import { TestBed, inject, async } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClient } from '@angular/common/http';
import { of, Observable } from 'rxjs';
import { User } from '../../models/user';
import { LoginDTO } from '../../models/loginDTO';
import { UserComponent } from 'src/client/app/containers/user/user.component';
import { UserDTO } from '../../models/userDTO';
describe('AuthService', () => {
let httpServiceStub: Partial<HttpClient>;
let http: HttpClient;
let service: AuthService;
beforeEach(() => {
httpServiceStub = {
post: () => null
};
TestBed.configureTestingModule({
providers: [AuthService, { provide: HttpClient, useValue: httpServiceStub }]
}).compileComponents();
http = TestBed.get(HttpClient);
service = TestBed.get(AuthService);
});
it('should be created', async(() => {
expect(service).toBeTruthy();
}));
it('should be created', async(() => {
const mockUser: User = {
_id: 'sdasd',
firstName: 'san',
lastName: 'gar',
email: 'garsan@gm'
};
const mockUserDTO: Observable<UserDTO> = of({
code: 210,
token: '<PASSWORD>',
user: mockUser
});
jest.spyOn(http, 'post').mockReturnValue(mockUserDTO);
let user: User;
service.login({} as LoginDTO).subscribe(data => (user = data));
expect(user._id).toBe(mockUser._id);
}));
});
<file_sep>/src/client/app/components/transaction-feed/transaction-feed.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TransactionFeedComponent } from './transaction-feed.component';
import { SharedModule } from '../../shared/shared.module';
describe('TransactionFeedComponent', () => {
let component: TransactionFeedComponent;
let fixture: ComponentFixture<TransactionFeedComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TransactionFeedComponent],
imports: [SharedModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TransactionFeedComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/client/app/shared/shared.module.ts
import { NgModule, Provider } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
MatInputModule,
MatFormFieldModule,
MatButtonModule,
MatSnackBarModule,
MatIconModule,
MatCardModule,
MatTableModule,
MatProgressSpinnerModule,
MatDialogModule,
MatChipsModule,
MatDatepickerModule,
MatExpansionModule
} from '@angular/material';
import {
MAT_MOMENT_DATE_FORMATS,
MomentDateAdapter,
MatMomentDateModule
} from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
const modules = [
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
MatFormFieldModule,
MatButtonModule,
MatSnackBarModule,
MatIconModule,
MatCardModule,
MatTableModule,
MatProgressSpinnerModule,
MatDialogModule,
MatChipsModule,
MatDatepickerModule,
MatExpansionModule,
MatMomentDateModule
];
const providers = [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
];
@NgModule({
imports: [...modules],
providers: [...providers],
exports: [...modules]
})
export class SharedModule {
static get providers(): Provider[] {
return providers;
}
}
<file_sep>/src/client/app/containers/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginDTO } from '../../core/models/loginDTO';
import { AuthState, AuthActions } from '../../store/auth';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { selectAuth } from '../../store';
import { isNullOrUndefined } from 'util';
import { MatSnackBar } from '@angular/material';
import { delay, tap } from 'rxjs/operators';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
authState$: Observable<AuthState>;
/**
*Creates an instance of LoginComponent.
* @param {Store<AuthState>} store
* @param {Router} router
* @param {MatSnackBar} snackBar
* @memberof LoginComponent
*/
constructor(
private store: Store<AuthState>,
private router: Router,
public snackBar: MatSnackBar
) {
this.authState$ = this.store.pipe(select(selectAuth));
this.authState$.subscribe(state => {
if (state && !isNullOrUndefined(state.error)) {
this.snackBar.open(state.error.message, undefined, {
duration: 3000
});
} else if (state && !isNullOrUndefined(state.user)) {
this.router.navigate(['/user']);
}
});
}
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required])
});
}
/**
* Dispatch login action
*
* @memberof LoginComponent
*/
login() {
if (this.loginForm.valid) {
const loginDTO = {
email: this.emailFormControl.value,
password: this.passwordFormControl.value
};
this.store.dispatch(new AuthActions.Login(loginDTO));
}
}
/**
*Get Email Form Control
*
* @readonly
* @memberof LoginComponent
*/
get emailFormControl() {
return this.loginForm.get('email');
}
/**
*Get Password Form Control
*
* @readonly
* @memberof LoginComponent
*/
get passwordFormControl() {
return this.loginForm.get('password');
}
}
<file_sep>/src/client/app/store/index.ts
import { environment } from '../../environments/environment';
import {
ActionReducer,
ActionReducerMap,
MetaReducer,
createFeatureSelector
} from '@ngrx/store';
import { AuthState, AuthReducer } from './auth';
export interface AppAction {
authState: AuthState;
}
export const reducers: ActionReducerMap<AppAction> = {
authState: AuthReducer
};
export function actionsLogger(reducer: ActionReducer<AppAction>) {
return function(state, action) {
const type = `Action ${action.type}`;
console.groupCollapsed(type);
if (action.payload) {
console.log('Action payload', action.payload);
}
console.log('Previous state', state);
const nextState = reducer(state, action);
console.log('Next state', nextState);
console.groupEnd();
return nextState;
};
}
export const metaReducers: MetaReducer<AppAction>[] = [];
if (!environment.production) {
metaReducers.push(actionsLogger);
}
export const selectAuth = createFeatureSelector<AuthState>('authState');
<file_sep>/src/client/app/core/models/__mocks__/transaction.mock.ts
import { Transaction } from '../transaction';
const getDefaults = (): Transaction => ({
_id: 'mock id',
createdDate: new Date('2018-12-05'),
points: 10,
type: 'mock type',
userId: 'mock user id',
value: 10000
});
export const getTransactionMock = (p?: Partial<Transaction>): Transaction => ({
...getDefaults(),
...p
});
<file_sep>/src/client/app/components/header/header.component.ts
import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
/**
*
*
* @export
* @class HeaderComponent
* @implements {OnInit}
*/
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
@Output() logout$ = new EventEmitter<{}>();
@Input('name') name: string;
/**
* Creates an instance of HeaderComponent.
* @memberof HeaderComponent
*/
constructor() {}
ngOnInit() {}
/**
* Emit logout event
* @memberof HeaderComponent
*/
public logout(): void {
this.logout$.emit({});
}
}
<file_sep>/src/client/app/containers/user/user.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthState, AuthActions } from '../../store/auth';
import { selectAuth } from '../../store';
import { select, Store } from '@ngrx/store';
import { isNullOrUndefined } from 'util';
import { Router } from '@angular/router';
import { User } from '../../core/models/user';
import { TransactionsDTO } from '../../core/models/transactionsDTO';
import { TransactionService } from '../../core/services/transaction/transaction.service';
import { Transaction } from '../../core/models/transaction';
import { DialogService } from '../../core/services/utils/dialog.service';
import { DialogTransactionDetailComponent } from '../../components/dialog-transaction-detail/dialog-transaction-detail.component';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
authState$: Observable<AuthState>;
currentUser: User;
transactions: Transaction[];
loadingTransactions: boolean;
/**
*Creates an instance of UserComponent.
* @param {Store<AuthState>} store
* @memberof UserComponent
*/
constructor(
private store: Store<AuthState>,
private router: Router,
private transactionService: TransactionService,
private dialogService: DialogService
) {
this.currentUser = null;
this.authState$ = this.store.pipe(select(selectAuth));
this.authState$.subscribe(state => {
if (state && isNullOrUndefined(state.user)) {
this.currentUser = null;
this.router.navigate(['/login']);
} else {
this.currentUser = state.user;
}
});
}
ngOnInit() {
this.loadingTransactions = true;
this.transactionService.getAll().subscribe(data => {
this.transactions = data;
this.loadingTransactions = false;
});
}
/**
* Dispatch logout action
*
* @memberof UserComponent
*/
logout(): void {
this.store.dispatch(new AuthActions.Logout());
}
/**
*
*
* @readonly
* @type {string}
* @memberof UserComponent
*/
get fullName(): string {
if (!isNullOrUndefined(this.currentUser)) {
return `${this.currentUser.firstName} ${this.currentUser.lastName}`;
}
return '';
}
get email(): string {
if (!isNullOrUndefined(this.currentUser)) {
return `${this.currentUser.email}`;
}
return '';
}
get transactionFeed(): { _id: string; position: number; createdDate: Date }[] {
if (!isNullOrUndefined(this.transactions)) {
return this.transactions.map((transaction, i) => {
return {
_id: transaction._id,
position: i + 1,
createdDate: transaction.createdDate
};
});
}
return [];
}
viewDetail(_id: string) {
const currentTransaction = this.transactions.find(
transaction => transaction._id === _id
);
this.dialogService.openDialogTransactionDetail(DialogTransactionDetailComponent, {
data: currentTransaction
});
}
filterByDate($event: { fromDate: string; toDate: string }) {
this.loadingTransactions = true;
this.transactionService.getByDates($event.fromDate, $event.toDate).subscribe(data => {
this.loadingTransactions = false;
this.transactions = data;
});
}
}
<file_sep>/src/client/app/store/auth/auth.reducer.ts
import { AuthActions } from './auth.actions';
import { defaultAuthState, AuthState } from './auth.state';
export function AuthReducer(state: AuthState, action: AuthActions.ClassType): AuthState {
switch (action.type) {
case AuthActions.Type.LOGIN:
return { ...state, user: null, error: null, authenticating: true };
case AuthActions.Type.LOGIN_SUCCESS:
return { ...state, user: action.payload, error: null, authenticating: false };
case AuthActions.Type.LOGIN_FAILED:
return { ...state, user: null, error: action.payload, authenticating: false };
case AuthActions.Type.LOGOUT:
return { ...state, user: null, error: null, authenticating: false };
default: {
return defaultAuthState;
}
}
}
<file_sep>/src/client/app/core/services/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { LoginDTO } from '../../models/loginDTO';
import { HttpClient } from '@angular/common/http';
import { User } from '../../models/user';
import { map, tap } from 'rxjs/operators';
import { UserDTO } from '../../models/userDTO';
import { isNullOrUndefined } from 'util';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {}
login(loginDTO: LoginDTO): Observable<User> {
return this.http.post<UserDTO>('/api/user/login', loginDTO).pipe(
tap(userDto => {
if (userDto && userDto.token) {
localStorage.setItem('currentUser', JSON.stringify(userDto));
}
}),
map(userDto => userDto.user)
);
}
logout(): void {
localStorage.removeItem('currentUser');
}
isLoggedIn(): boolean {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (isNullOrUndefined(currentUser)) return false;
else return true;
}
}
<file_sep>/src/client/app/core/models/__mocks__/user.mock.ts
import { User } from 'src/client/app/core/models/user';
const getDefaults = (): User => ({
_id: 'mock id',
email: 'mock email',
firstName: 'mock first name',
lastName: 'mock last name'
});
export const getUserMock = (p?: Partial<User>): User => ({
...getDefaults(),
...p
});
<file_sep>/src/client/app/containers/user/user.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component } from '@angular/core';
import { UserComponent } from './user.component';
import { NO_ERRORS_SCHEMA } from '@angular/compiler/src/core';
import { Store, StoreModule } from '@ngrx/store';
import { reducers } from '../../store';
import { Router } from '@angular/router';
import { TransactionService } from '../../core/services/transaction/transaction.service';
import { DialogService } from '../../core/services/utils/dialog.service';
import { of } from 'rxjs';
import { AuthState, AuthActions } from '../../store/auth';
import { getUserMock } from '../../core/models/__mocks__/user.mock';
import { getTransactionMock } from '../../core/models/__mocks__/transaction.mock';
import { Transaction } from '../../core/models/transaction';
@Component({ selector: 'app-header', template: '' })
class HeaderStubComponent {}
@Component({ selector: 'app-profile', template: '' })
class ProfileStubComponent {}
@Component({ selector: 'app-date-filter', template: '' })
class DateFilterStubComponent {}
@Component({ selector: 'app-transaction-feed', template: '' })
class TransactionFeedStubComponent {}
describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
let routerStub: Partial<Router>;
let transactionServiceStub: Partial<TransactionService>;
let dialogServiceStub: Partial<DialogService>;
let transactionservice: TransactionService;
let store: Store<AuthState>;
beforeEach(async(() => {
routerStub = {
navigate: () => null
};
transactionServiceStub = {
getAll: () => of([]),
getByDates: () => of([])
};
dialogServiceStub = {
openDialogTransactionDetail: () => null
};
TestBed.configureTestingModule({
declarations: [
UserComponent,
HeaderStubComponent,
ProfileStubComponent,
DateFilterStubComponent,
TransactionFeedStubComponent
],
providers: [
Store,
{ provide: Router, useValue: routerStub },
{ provide: TransactionService, useValue: transactionServiceStub },
{ provide: DialogService, useValue: dialogServiceStub }
],
imports: [StoreModule.forRoot(reducers)],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
transactionservice = TestBed.get(TransactionService);
store = TestBed.get(Store);
component = fixture.componentInstance;
spyOn(store, 'dispatch').and.callThrough();
jest.spyOn(transactionservice, 'getAll').mockClear();
fixture.detectChanges();
});
it('should create', () => {
jest.spyOn(transactionservice, 'getAll').mockReturnValue(of([]));
expect(component).toBeTruthy();
});
it('should logout user', () => {
let state: AuthState;
expect(state).toBeUndefined();
component.authState$.subscribe(data => {
state = data;
});
store.dispatch(new AuthActions.Logout());
expect(state.user).toBeNull();
expect(component.currentUser).toBeNull();
store.dispatch(new AuthActions.LoginSuccess(getUserMock({ firstName: 'carlos' })));
expect(state.user.firstName).toBe('carlos');
store.dispatch(new AuthActions.Logout());
expect(state.user).toBeNull();
});
it('should login user', () => {
let state: AuthState;
expect(state).toBeUndefined();
component.authState$.subscribe(data => {
state = data;
});
expect(state.user).toBeNull();
store.dispatch(new AuthActions.LoginSuccess(getUserMock({ firstName: 'carlos' })));
expect(state.user.firstName).toBe('carlos');
expect(component.currentUser.firstName).toBe('carlos');
});
it('should get full name', () => {
const user = getUserMock({ firstName: 'carlos', lastName: 'gonzales' });
let state: AuthState;
expect(state).toBeUndefined();
component.authState$.subscribe(data => {
state = data;
});
expect(state.user).toBeNull();
store.dispatch(new AuthActions.LoginSuccess(user));
expect(component.fullName).toBe('<NAME>');
});
it('should get email', () => {
const user = getUserMock({ email: '<EMAIL>' });
let state: AuthState;
expect(state).toBeUndefined();
component.authState$.subscribe(data => {
state = data;
});
expect(state.user).toBeNull();
store.dispatch(new AuthActions.LoginSuccess(user));
expect(component.email).toBe('<EMAIL>');
});
it('should set transaction feed on init', () => {
const transactions: Transaction[] = Array.apply(null, Array(5)).map(function() {});
transactions.forEach((element, i) => {
transactions[i] = getTransactionMock({ _id: `${i}` });
});
jest.spyOn(transactionservice, 'getAll').mockReturnValue(of(transactions));
component.ngOnInit();
expect(component.transactions).toHaveLength(5);
component.transactions.forEach((element, i) => {
expect(element._id).toBe(`${i}`);
});
});
});
<file_sep>/src/client/app/core/models/loginDTO.ts
import { User } from './user';
export interface LoginDTO {
email: string;
password: string;
}
<file_sep>/src/client/app/core/models/transaction.ts
export interface Transaction {
userId: string;
value: number;
points: number;
type: string;
createdDate: Date;
_id: string;
}
| fe8cba6897aa2bd2ca1a76ba0acf74b5ff024a7c | [
"Markdown",
"TypeScript"
] | 32 | TypeScript | Sgarcia10/leal | ae51fe5ef38fa716cfa5634f5590374b352a4425 | d23d88c14ed6ed9381e8b54d694ead6fab753dde |
refs/heads/master | <file_sep>package com.misakamikoto.springboot.api.aspect.pointcut;
import org.aspectj.lang.annotation.Pointcut;
public class RestExceptionPointcut {
@Pointcut("execution(* com.misakamikoto.springboot.api..*(..))")
public void exception() {}
}
<file_sep>app.controller('detailController', ['$scope', '$location', '$cookies', function ($scope, $location, $cookies) {
if($cookies.get('memberId') === undefined) {
disconnect();
} else {
var bookmark = new Bookmarks();
let bookmarkPromise = bookmark.getListToIsbn($cookies.get('memberId'), $scope.detail.isbn.trim());
bookmarkPromise.then((response) => {
if(response.length > 0) {
if (response[0].isbn == $scope.detail.isbn.trim()) {
$('#bookmarking').attr('class', 'btn btn-primary disabled');
$('#bookmarking').html("이 책은 이미 북마킹 되었습니다.");
angular.element($('#bookmarking')).unbind('click');
}
}
}, (error) => {
console.error('Failed!', error);
});
$scope.bookmarking = () => {
if (confirm("이 책을 북마킹 하겠습니까?") == true) {
let bookmarkPromise = bookmark.add($cookies.get('memberId'));
bookmarkPromise.then((response) => {
if (response.title) {
alert(response.title + " 책이 북마킹에 추가되었습니다.");
$('#ok').trigger('click');
} else {
alert("북마킹에 실패하였습니다.");
}
}, (error) => {
console.error('Failed!', error);
});
};
};
}
function disconnect() {
if($cookies.get('memberId') !== undefined && $cookies.get('memberName') !== undefined) {
$cookies.remove('memberId');
$cookies.remove('memberName');
}
alert('세션이 종료되었습니다. 로그인 페이지로 돌아갑니다.');
$location.path('/');
}
}]);<file_sep>package com.misakamikoto.springboot.api.services.book.repository;
import com.misakamikoto.springboot.api.services.book.dto.History;
import org.springframework.data.repository.CrudRepository;
public interface BookHistoryRepository extends CrudRepository<History, Long> {
}
<file_sep>class Book {
constructor() {
this._booksJSON = '';
}
set booksJSON(booksJSON) {
this._booksJSON = booksJSON;
}
searchKakaoAPI(query, pageIndex, memberId) {
let sendQuery = query;
let sendSort = $("#sort option:selected").val();
let sendSize = Number($("#size option:selected").val());
let sendPage = Number(pageIndex);
let commonRequestPromise = new CommonRequestPromise();
return commonRequestPromise.get('/v1/book/search/books?query=' + sendQuery + "&page=" + sendPage + "&sort=" + sendSort + "&size=" + sendSize + "&memberId=" + memberId)
.then((response) => {
let parseJSON = JSON.parse(response);
if(parseJSON.status !== undefined) {
return parseJSON
} else {
this.booksJSON = parseJSON.books;
$('#totalCount').html('총 ' + parseJSON.pagination.pageableCount + ' 건');
return parseJSON;
}
}, function(error) {
console.error('Failed!', error);
});
}
showDetail(index) {
let book = this._booksJSON[index - 1];
return this.paserDetailToViewData(book);
}
paserDetailToViewData(book) {
let authors = book.authors;
if (book !== undefined && book.length > 0) {
book.authors = authors.toString();
}
let translators = book.translators;
if (translators !== undefined && translators.length > 0) {
book.translators = translators.toString();
}
let saleYn = book.saleYn;
if (saleYn == 'Y') {
book.saleYn = "판매 가능";
} else {
book.saleYn = "판매 불가능";
}
return book;
}
validSearch() {
if($('#query').val().trim().length == "") {
alert("검색어를 입력해 주세요.");
return false;
} else if($( "#size option:selected" ).val() == "0") {
alert("페이지당 검색 개수를 선택해 주세요.");
return false;
} else if($( "#sort option:selected" ).val() == "none") {
alert("검색의 정렬 조건을 선택해 주세요.");
return false;
} else {
return true;
}
}
}<file_sep>app.controller('bookmarkController', ['$scope', '$location', '$cookies', function ($scope, $location, $cookies) {
if($cookies.get('memberId') === undefined) {
disconnect();
} else {
bindSelectChange();
var bookmark = new Bookmarks();
let bookmarkPromise = bookmark.getListOrderId($cookies.get('memberId'));
bookmarkPromise.then((response) => {
if (response instanceof Array) {
$scope.searchBookmarks = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
$scope.back = () => {
$location.path('/search');
};
}
function bindSelectChange() {
$('#sort').on('change', (element) => {
let sort = element.target.value;
if('title' == sort) {
let searchBookmarkPromise = bookmark.getListOrderTitle($cookies.get('memberId'));
searchBookmarkPromise.then((response) => {
if(response instanceof Array) {
$scope.searchBookmarks = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else if('status' == sort) {
let searchBookmarkPromise = bookmark.getListOrderStatus($cookies.get('memberId'));
searchBookmarkPromise.then((response) => {
if (response instanceof Array) {
$scope.searchBookmarks = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else if('salePrice' == sort) {
let searchBookmarkPromise = bookmark.getListOrderSalePrice($cookies.get('memberId'));
searchBookmarkPromise.then((response) => {
if (response instanceof Array) {
$scope.searchBookmarks = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else {
// another case..
;
}
});
}
$scope.delete = () => {
if (confirm("선택한 북마크를 삭제하시겠습니까?") == true) {
if(bookmark.validateDeleteList()) {
let searchBookmarkPromise = bookmark.deleteList($cookies.get('memberId'));
searchBookmarkPromise.then((response) => {
if (response instanceof Array) {
$scope.searchBookmarks = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else {
alert("선택한 북마크가 없습니다.");
}
} else {
return;
}
};
function disconnect() {
if($cookies.get('memberId') !== undefined && $cookies.get('memberName') !== undefined) {
$cookies.remove('memberId');
$cookies.remove('memberName');
}
alert('세션이 종료되었습니다. 로그인 페이지로 돌아갑니다.');
$location.path('/');
}
}]);<file_sep>package com.misakamikoto.springboot.api.config.character;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.Filter;
import java.nio.charset.Charset;
@Configuration
public class CharacterConfig {
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public Filter characterEncodingFilter() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return characterEncodingFilter;
}
}
<file_sep>app.controller('loginController', ['$scope', '$location', '$cookies', function ($scope, $location, $cookies) {
var login = new Login();
if(checkCookies()) {
$location.path('/search');
}
$scope.login = () => {
if(login.validLogin()) {
let loginPromise = login.findUser($scope.id, $scope.password);
loginPromise.then((response) => {
if (response.status) {
$cookies.put('memberId', response.memberId);
$cookies.put('memberName', response.memberName);
alert(response.message + ' 환영합니다. ' + response.memberName + ' 님');
$location.path('/search');
$scope.$apply();
} else {
alert(response.message);
}
}, (error) => {
console.error('Failed!', error);
});
}
};
$scope.signin = () => {
$location.path('/signin');
};
$scope.modify = () => {
$location.path('/modify');
};
function checkCookies() {
if($cookies.get('memberId') !== undefined) {
return true;
} else {
return false;
}
}
}]);<file_sep>package com.misakamikoto.springboot.api.common.rest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Map;
public class RestHttpGet {
private static String USER_AGENT = "Mozilla/5.0";
public String call(String url, Map<String, String> headerMap) throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
request.addHeader("Content-Type", "application/json;charset=UTF-8");
for(String key : headerMap.keySet()) {
request.addHeader(key, headerMap.get(key));
}
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
String result = "";
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity,"UTF-8");
}
return result;
}
}
<file_sep>buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.1.0'
}
}
plugins { id "io.spring.dependency-management" version "1.0.4.RELEASE" }
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'org.junit.platform.gradle.plugin'
apply plugin: 'war'
group = 'com.misakamikoto.springboot.api'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
configurations {
providedRuntime
}
junitPlatform {
platformVersion '1.1.0' // optional, defaults to plugin version
reportsDir file('build/test-results/junit-platform') // this is the default
// enableStandardTestTask true
// selectors (optional)
// filters (optional)
// logManager (optional)
// logManager 'org.apache.logging.log4j.jul.LogManager'
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compileOnly('org.projectlombok:lombok')
compile('org.springframework.boot:spring-boot-starter-tomcat')
testCompile('org.springframework.boot:spring-boot-starter-test')
// JUnit Jupiter API for writing tests and extensions.
testCompile("org.junit.jupiter:junit-jupiter-api:5.1.0")
// JUnit Jupiter test engine implementation, only required at runtime.
testRuntime("org.junit.jupiter:junit-jupiter-engine:5.1.0")
// Support for parameterized tests in JUnit Jupiter.
testCompile("org.junit.jupiter:junit-jupiter-params:5.1.0")
// Runner for executing tests and test suites on the JUnit Platform in a JUnit 4 environment.
// JUnit 4 환경에서 JUnit 플랫폼의 테스트 및 테스트 스위트 실행을위한 러너
// See Using JUnit 4 to run the JUnit Platform for details.
// JUnitPlatform.class
testCompile("org.junit.platform:junit-platform-runner:1.1.0")
testCompile('name.falgout.jeffrey.testing.junit5:mockito-extension:1.0.0')
// https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jdbc
compile group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: '8.0.30'
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
// https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
compile('org.springframework.boot:spring-boot-starter-aop')
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'
// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
// https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto
compile group: 'org.springframework.security', name: 'spring-security-crypto', version: '3.1.0.RELEASE'
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")
compile "org.springframework.boot:spring-boot-configuration-processor"
}
<file_sep>class Login {
constructor() {}
findUser(id, password) {
let params = {
id: id,
password: <PASSWORD>
};
let commonRequestPromise = new CommonRequestPromise();
return commonRequestPromise.post('/v1/account/login', params).then((response) => {
return JSON.parse(response);
}, function(error) {
console.error("Failed!", error);
});
}
validLogin() {
if($('#id').val().trim().length == "") {
alert("아이디를 입력해 주세요.");
return false;
} else if($('#password' ).val() == "") {
alert("암호를 입력해 주세요.");
return false;
} else {
return true;
}
}
}<file_sep>package com.misakamikoto.springboot.api.services.account.dto;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class Member {
public Member(){}
@Id
private String id;
@Column
private String password;
@Column
private String name;
@Column
private String modifyPassword;
}
<file_sep>app.controller('bookHistoryController', ['$scope', '$location', '$cookies', function ($scope, $location, $cookies) {
if($cookies.get('memberId') === undefined) {
disconnect();
} else {
bindSelectChange();
var bookHistory = new BookHistory();
let searchBookHistoryPromise = bookHistory.getListOrderId($cookies.get('memberId'));
searchBookHistoryPromise.then((response) => {
if(response instanceof Array) {
$scope.searchHistories = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
$scope.delete = () => {
if (confirm("선택한 검색 히스토리를 삭제하시겠습니까?") == true) {
if(bookHistory.validateDeleteList()) {
let searchBookHistoryPromise = bookHistory.deleteList($cookies.get('memberId'));
searchBookHistoryPromise.then((response) => {
if (response instanceof Array) {
$scope.searchHistories = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else {
alert("선택된 검색 히스토리가 없습니다.")
}
} else {
return;
}
};
$scope.back = () => {
$location.path('/search');
};
}
function bindSelectChange() {
$('#sort').on('change', (element) => {
let sort = element.target.value;
if('query' == sort) {
let searchBookHistoryPromise = bookHistory.getListOrderQuery($cookies.get('memberId'));
searchBookHistoryPromise.then((response) => {
if(response instanceof Array) {
$scope.searchHistories = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else if('datetime' == sort) {
let searchBookHistoryPromise = bookHistory.getListOrderDatetime($cookies.get('memberId'));
searchBookHistoryPromise.then((response) => {
if(response instanceof Array) {
$scope.searchHistories = response;
$scope.$apply();
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
} else {
// another case..
;
}
});
}
function disconnect() {
if($cookies.get('memberId') !== undefined && $cookies.get('memberName') !== undefined) {
$cookies.remove('memberId');
$cookies.remove('memberName');
}
alert('세션이 종료되었습니다. 로그인 페이지로 돌아갑니다.');
$location.path('/');
}
}]);<file_sep>class Modify {
checkPassword(params) {
let commonRequestPromise = new CommonRequestPromise();
return commonRequestPromise.put('/v1/account/modify', params).then((response) => {
return JSON.parse(response);
}, function(error) {
console.error("Failed!", error);
});
}
validateModify() {
if($('#id').val().length == "") {
alert("아이디를 입력해 주세요.");
return false;
} else if($('#password' ).val() == "") {
alert("암호를 입력해 주세요.");
return false;
} else if($('#modifyPassword' ).val() == "") {
alert("수정할 암호를 입력해 주세요.");
return false;
} else if($('#password' ).val() == $('#modifyPassword' ).val()) {
alert("기존의 암호와 수정할 암호는 같을 수 없습니다.");
return false;
} else {
return true;
}
}
}<file_sep># SpringBoot-API
- Install & Execute Guide
- JDK 1.8 Install
- http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
- Download Guide
- Download - https://github.com/MisakaMikoto/SpringBoot-API -> clone or download -> zip download
- extracting zip file
- cmd or terminal open. move to the extracting file(zip) root folder path (ex: c:/document/springBoot-API/)
- build : gradlew build (build + jUnit test)
- run : gradlew bootRun
- Clone Guide
- Checkout - https://github.com/MisakaMikoto/SpringBoot-API.git
- cmd or terminal open. move to the checkout file root folder path (ex: c:/document/springBoot-API/)
- build : gradlew build (build + jUnit test)
- run : gradlew bootRun
- Execute Browser
- Chrome
- Additional Implementations
- Login Session
- Login Session redirect
- Login Session Interceptor
- Logging AOP (Pointcut)
- Swagger ui (/swagger-ui.html)
- Login Information Modfy
- JPA
- SPA
- Used OpenSource in Backend
- Gradle
- SpringBoot
- SpringBoot-tomcat-starter
- SpringBoot-test-starter
- SpringBoot-aop-starter
- SpringBoot-jpa-starter
- h2Database
- spring-security-crypto 3.1.0
- Google gson 2.8.0
- Apache httpclient 4.5.2
- logback-classic 1.2.3
- springfox swagger 2.7.0
- springfox swagger-ui 2.7.0
- jUnit5 (jupiter) 5.1.0
- mocktio-extension 1.0.0
- tomcat-jdbc 8.0.30
- Used OpenSource in Frontend
- angular 1.6.4
- angular-route 1.2.0rc1
- angular-cookies 1.7.2
- jQuery 1.12.0
- jQuery-ui 1.11.4
- bootstrap 3.3.7
- bootstrap-ui 2.5.0
- bootstrap-ui-tpls 2.5.0
<file_sep>package com.misakamikoto.springboot.api.services.book.dto;
import lombok.Data;
@Data
public class Pagination {
int totalCount;
int pageableCount;
boolean isEnd;
// is default
int pageCount = 10;
}
<file_sep>package com.misakamikoto.springboot.api.services.account;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.misakamikoto.springboot.api.ApiApplication;
import com.misakamikoto.springboot.api.services.account.controller.LoginController;
import com.misakamikoto.springboot.api.services.account.dto.Login;
import com.misakamikoto.springboot.api.services.account.dto.Member;
import name.falgout.jeffrey.testing.junit5.MockitoExtension;
import org.junit.FixMethodOrder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(JUnitPlatform.class)
@ExtendWith({SpringExtension.class, MockitoExtension.class})
@SpringBootTest(classes={ApiApplication.class})
@AutoConfigureMockMvc
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoginControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
LoginController loginController;
// ***** TEST CASE *****
// test1 -> id, name password 가 aa 인 유저 생성
// test2 -> aa 유저 로그인
// test3 -> aa 유저의 암호를 aaa 로 수정
// test4 -> 로그 아웃
@Test
public void test1( ) throws Exception {
String json = createDummyMember("aa", "aa", "aa", "aa");
this.mockMvc.perform(post("/v1/account/signin")
.content(json).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test2( ) throws Exception {
String json = createDummyMember("aa", "aa", "aa", "aa");
this.mockMvc.perform(post("/v1/account/login")
.content(json).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test3( ) throws Exception {
String json = createDummyMember("aa", "aa", "aa", "aaa");
this.mockMvc.perform(put("/v1/account/modify")
.content(json).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test4( ) throws Exception {
this.mockMvc.perform(get("/v1/account/logout"))
.andDo(print())
.andExpect(status().isOk());
}
public static String createDummyMember(String id, String name, String password, String modifyPassword) {
Gson gson = new GsonBuilder().create();
Member member = new Member();
member.setId(id);
member.setName(name);
member.setPassword(<PASSWORD>);
member.setModifyPassword(<PASSWORD>);
return gson.toJson(member);
}
public static Login createDummyLogin() {
Login login = new Login();
login.setMemberId("aa");
login.setMemberName("aa");
login.setMessage("로그인에 성공하였습니다.");
login.setStatus(true);
return login;
}
}
<file_sep>app.controller('bookController', ['$scope', '$location', '$cookies', '$uibModal', function ($scope, $location, $cookies, $uibModal) {
if($cookies.get('memberId') === undefined) {
disconnect();
} else {
setUserName();
var pagination = new Pagination();
var book = new Book();
$scope.search = () => {
searchForKakao(1, false);
};
$scope.showDetail = (index) => {
$scope.detail = book.showDetail(index);
createModal();
};
$scope.goHistories = () => {
$location.path('/history');
};
$scope.goBookmarks = () => {
$location.path('/bookmark');
};
$scope.logout = () => {
logout();
};
}
function setUserName() {
let memberName = $cookies.get('memberName') + " 님 ";
$('#memberName').html(memberName);
}
function createModal() {
$uibModal.open({
templateUrl: '/component/detail.html',
scope: $scope,
backdrop: true,
controller: function ($scope, $uibModalInstance) {
$scope.ok = function () {
$uibModalInstance.close();
};
}
});
}
function searchForKakao(pageIndex, isPageCall) {
$scope.books = [];
if(book.validSearch()) {
let searchPromise = book.searchKakaoAPI($scope.query, pageIndex, $cookies.get('memberId'));
searchPromise.then((response) => {
if (response.books !== undefined) {
$('.table').show();
$scope.books = response.books;
$scope.$apply();
if(!isPageCall) {
$('#pagination').empty();
createPagination(response.pagination);
}
} else {
disconnect();
$scope.$apply();
}
}, (error) => {
console.error('Failed!', error);
});
}
}
function createPagination(responsePagination) {
pagination.lastPageNumber = Number(responsePagination.pageableCount / Number($("#size option:selected").val()));
pagination.pageCount = Number(responsePagination.pageCount);
pagination.createPage(searchPage);
}
function searchPage (pageIndex) {
searchForKakao(pageIndex, true);
}
function logout() {
$cookies.remove('memberId');
$cookies.remove('memberName');
alert('로그인 페이지로 돌아갑니다.');
$location.path('/');
}
function disconnect() {
if($cookies.get('memberId') !== undefined && $cookies.get('memberName') !== undefined) {
$cookies.remove('memberId');
$cookies.remove('memberName');
}
alert('세션이 종료되었습니다. 로그인 페이지로 돌아갑니다.');
$location.path('/');
}
}]);<file_sep>app.controller("signinController", ['$scope', '$location', function ($scope, $location) {
var signin = new Signin();
$scope.create = () => {
if(signin.validSignin()) {
let params = {
id: $scope.id,
password: <PASSWORD>,
name: $scope.name
};
let signinPromise = signin.createAccount(params);
signinPromise.then((response) => {
if (response.status) {
alert(response.message);
$location.path("/");
$scope.$apply();
} else {
alert(response.message);
}
}, (error) => {
console.error('Failed!', error);
});
}
};
$scope.cancel = () => {
$location.path("/");
};
}]);<file_sep>app.controller('modifyController', ['$scope', '$location', '$cookies', function ($scope, $location, $cookies) {
var modify = new Modify();
$scope.modify = () => {
if(modify.validateModify()) {
let params = {
id: $scope.id,
password: <PASSWORD>,
modifyPassword: $<PASSWORD>
};
let loginPromise = modify.checkPassword(params);
loginPromise.then((response) => {
if (response.status) {
alert(response.message);
$location.path("/");
$scope.$apply();
} else {
alert(response.message);
}
}, (error) => {
console.error('Failed!', error);
});
}
};
$scope.cancel = () => {
$location.path("/");
};
}]);<file_sep>package com.misakamikoto.springboot.api.services.book.dto;
import lombok.Data;
import java.util.List;
@Data
public class Book {
String title;
String contents;
String url;
String isbn;
String datetime;
List<String> authors;
String publisher;
List<String> translators;
String price;
String salePrice;
String saleYn;
String category;
String thumbnail;
String barcode;
String ebookBarcode;
String status;
}
<file_sep>package com.misakamikoto.springboot.api.config.interceptor;
import com.misakamikoto.springboot.api.interceptor.SessionInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class SessionInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SessionInterceptor())
.addPathPatterns("/v1/book/**", "/v1/history/**", "/v1/bookmark/**");
}
}
<file_sep>package com.misakamikoto.springboot.api.config.mvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".html");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/WEB-INF/**", "/js/**", "/css/**", "/component/**")
.addResourceLocations("/WEB-INF/", "/js/", "/css/", "/component/");
}
}
<file_sep>package com.misakamikoto.springboot.api.index.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping(value={"/", "/modify", "/signin", "/search", "/history", "/bookmark"})
public String main() {
return "index";
}
}
<file_sep>package com.misakamikoto.springboot.api.services.book.controller;
import com.misakamikoto.springboot.api.services.book.dto.Search;
import com.misakamikoto.springboot.api.services.book.service.BookHistoryService;
import com.misakamikoto.springboot.api.services.book.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
@Controller
public class BookController {
@Autowired
BookService bookService;
@Autowired
BookHistoryService bookHistoryService;
@GetMapping("/v1/book/search/books")
public ResponseEntity search(
@RequestParam("query") String query,
@RequestParam("sort") String sort,
@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam("memberId") String memberId) throws IOException {
this.bookHistoryService.save(query, memberId);
Search search = bookService.getBooks(query, sort, page, size);
return new ResponseEntity<>(search, HttpStatus.OK);
}
}
<file_sep>package com.misakamikoto.springboot.api.services.account.controller;
import com.misakamikoto.springboot.api.services.account.dto.Login;
import com.misakamikoto.springboot.api.services.account.dto.Member;
import com.misakamikoto.springboot.api.services.account.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
@RestController
public class LoginController {
@Autowired
LoginService loginService;
@PostMapping(path = "/v1/account/signin")
public ResponseEntity signIn(@RequestBody Member member) {
Login login = this.loginService.signIn(member);
return new ResponseEntity<>(login, HttpStatus.OK);
}
@PostMapping(path = "/v1/account/login")
public ResponseEntity login(@RequestBody Member member, HttpSession httpSession) {
Login login = this.loginService.logIn(member);
httpSession.setAttribute("login", login);
return new ResponseEntity<>(login, HttpStatus.OK);
}
@PutMapping(path = "/v1/account/modify")
public ResponseEntity modify(@RequestBody Member member) {
Login login = this.loginService.modify(member);
return new ResponseEntity<>(login, HttpStatus.OK);
}
@GetMapping(path = "/v1/account/logout")
public ResponseEntity logout() {
Login login = new Login();
return new ResponseEntity<>(login, HttpStatus.OK);
}
}
<file_sep>package com.misakamikoto.springboot.api.services.account.dto;
import lombok.Data;
@Data
public class Login {
boolean status;
String message;
String memberId;
String memberName;
}
<file_sep>/**
* Created by MisakaMikoto on 2017-08-23.
*/
var app = angular.module('app', ['ngRoute', 'ngCookies', 'ui.bootstrap']).
config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/', {templateUrl: '/component/login.html'})
.when('/modify', {templateUrl: '/component/modify.html'})
.when('/signin', {templateUrl: '/component/signin.html'})
.when('/search', {templateUrl: '/component/book.html'})
.when('/history', {templateUrl: '/component/bookhistory.html'})
.when('/bookmark', {templateUrl: '/component/bookmark.html'})
});<file_sep>package com.misakamikoto.springboot.api.services.book;
import com.misakamikoto.springboot.api.ApiApplication;
import com.misakamikoto.springboot.api.services.account.LoginControllerTest;
import com.misakamikoto.springboot.api.services.account.dto.Login;
import com.misakamikoto.springboot.api.services.book.controller.BookHistoryController;
import com.misakamikoto.springboot.api.services.book.service.BookHistoryService;
import name.falgout.jeffrey.testing.junit5.MockitoExtension;
import org.junit.FixMethodOrder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(JUnitPlatform.class)
@ExtendWith({SpringExtension.class, MockitoExtension.class})
@SpringBootTest(classes={ApiApplication.class})
@AutoConfigureMockMvc
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BookHistoryControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
BookHistoryController bookHistoryController;
@Autowired
BookHistoryService bookHistoryService;
// ***** TEST CASE *****
// 히스토리 기능은 로그인 세션이 없으면 동작하지 않는다. 때문에 세션이 있는 경우, 없는 경우 두 가지 테스트를 한다.
// test1NoSession -> java 책 검색 (정확도, 1페이지, 20개) : Expected redirect logout
// test2NoSession -> javascript 책 검색 (정확도, 1페이지, 20개) : Expected redirect logout
// test3NoSession -> 히스토리 id 정렬 조회 : Expected redirect logout
// test4NoSession -> 히스토리 query 정렬 조회 : Expected redirect logout
// test5NoSession -> 히스토리 datetime 정렬 조회 : Expected redirect logout
// test6NoSession -> 히스토리 2건을 세이브 후 히스토리 id가 1인 히스토리 삭제 : Expected redirect logout
// test1Session -> java 책 검색 (정확도, 1페이지, 20개) : Expected isOK
// test2Session -> javascript 책 검색 (정확도, 1페이지, 20개) : Expected isOK
// test3Session -> 히스토리 id 정렬 조회 : Expected isOK
// test4Session -> 히스토리 query 정렬 조회 : Expected isOK
// test5Session -> 히스토리 datetime 정렬 조회 : Expected isOK
// test6Session -> 히스토리 2건을 세이브 후 히스토리 id가 1인 히스토리 삭제 : Expected isOK
@Test
public void test1NoSession() throws Exception {
this.mockMvc.perform(get("/v1/book/search/books?query=java&sort=accuracy&page=1&size=20&memberId=aa")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test2NoSession() throws Exception {
this.mockMvc.perform(get("/v1/book/search/books?query=javascript&sort=accuracy&page=1&size=20&memberId=aa")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test3NoSession() throws Exception {
this.mockMvc.perform(get("/v1/history/aa/order/id")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test4NoSession() throws Exception {
this.mockMvc.perform(get("/v1/history/aa/order/query")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test5NoSession() throws Exception {
this.mockMvc.perform(get("/v1/history/aa/order/datetime")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test6NoSession() throws Exception {
this.mockMvc.perform(delete("/v1/history/aa?ids=1")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(redirectedUrl("/v1/account/logout"));
}
@Test
public void test1Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(get("/v1/book/search/books?query=java&sort=accuracy&page=1&size=20&memberId=aa")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test2Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(get("/v1/book/search/books?query=javascript&sort=accuracy&page=1&size=20&memberId=aa")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test3Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(get("/v1/history/aa/order/id")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test4Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(get("/v1/history/aa/order/query")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test5Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(get("/v1/history/aa/order/datetime")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void test6Session() throws Exception {
Login login = LoginControllerTest.createDummyLogin();
this.mockMvc.perform(delete("/v1/history/aa?ids=1")
.accept(MediaType.APPLICATION_JSON).sessionAttr("login", login))
.andDo(print())
.andExpect(status().isOk());
}
}
| 605f3d8037ccbeff734d4a359bb7bd9fa537eded | [
"JavaScript",
"Java",
"Markdown",
"Gradle"
] | 28 | Java | MisakaMikoto/SpringBoot-API | e48f05ede47aac26cb8cd08cff9a38e467bddf26 | 3b31a6395901b6755822999f72c7b74dabe0a038 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmUpdateEmployees : Form
{
List<Employee> EmpList;
List<Group> GroupList;
Employee SelectedEmployee;
DataClasses1DataContext DContext;
public frmUpdateEmployees()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SaveSelectedEmployee();
SaveChangesToDB();
this.Close();
}
public void StartThing(List<Employee> EList)
{
EmpList = new List<Employee>();
foreach (Employee E in EList)
EmpList.Add(E);
DContext = DBCommands.DContext;
InitializeGroupBox();
hScrollBar1.Minimum = 1;
hScrollBar1.Maximum = EmpList.Count + (hScrollBar1.LargeChange - 1);
label1.Text = "1 of " + EmpList.Count.ToString();
if (EmpList.Count > 0)
LoadEmployee(EmpList[0]);
}
private void frmUpdateEmployees_Load(object sender, EventArgs e)
{
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
SaveSelectedEmployee();
label1.Text = hScrollBar1.Value.ToString() + " of " + EmpList.Count.ToString();
LoadEmployee(EmpList[hScrollBar1.Value - 1]);
}
private void SaveSelectedEmployee()
{
if (SelectedEmployee != null)
{
SelectedEmployee.PreferredName = PrefNameBox.Text;
if (GroupNoBox.SelectedItem != null && GroupNoBox.SelectedItem is Group)
{
SelectedEmployee.GroupID = ((Group)GroupNoBox.SelectedItem).GroupID;
}
SelectedEmployee.PrideEligible = PrideEligibleBox.Checked;
SelectedEmployee.Active = ActiveBox.Checked;
SelectedEmployee.OldAwardCount = Decimal.ToInt32(OldAwdCountBox.Value);
}
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
}
private void LoadEmployee(Employee Emp)
{
SelectedEmployee = Emp;
EmpNameBox.Text = SelectedEmployee.LastName + ", " + SelectedEmployee.FirstName;
if (SelectedEmployee.MiddleInitial != null)
EmpNameBox.Text += " " + SelectedEmployee.MiddleInitial.ToString();
EmpIDBox.Text = SelectedEmployee.EmployeeID;
EmpDeptBox.Text = DBCommands.GetDepartment(SelectedEmployee.DeptID).DeptName;
EmpTitleBox.Text = SelectedEmployee.Title;
if (SelectedEmployee.HR_FTE != null)
EmpFTEBox.Text = ((double)SelectedEmployee.HR_FTE).ToString("0.00");
else
EmpFTEBox.Text = "";
if (SelectedEmployee.HireDate != null)
EmpHireDateBox.Text = ((DateTime)SelectedEmployee.HireDate).ToShortDateString();
else
EmpHireDateBox.Text = "";
EmpStatusBox.Text = SelectedEmployee.HR_Status;
PrefNameBox.Text = SelectedEmployee.PreferredName;
int GrpInd = GetGroupIndex(SelectedEmployee.GroupID);
if (GrpInd >= 0)
GroupNoBox.SelectedIndex = GrpInd;
else
GroupNoBox.SelectedIndex = -1;
if (SelectedEmployee.PrideEligible != null)
PrideEligibleBox.Checked = (bool)SelectedEmployee.PrideEligible;
else
PrideEligibleBox.Checked = false;
if (SelectedEmployee.Active != null)
ActiveBox.Checked = (bool)SelectedEmployee.Active;
else
ActiveBox.Checked = false;
if (SelectedEmployee.OldAwardCount != null)
OldAwdCountBox.Value = (decimal)SelectedEmployee.OldAwardCount;
else
OldAwdCountBox.Value = 0;
}
private int GetGroupIndex(string GroupID)
{
int C1, Result;
Result = -1;
for (C1 = 0; C1 < GroupList.Count; C1++)
if (GroupList[C1].GroupID.Equals(GroupID, StringComparison.CurrentCultureIgnoreCase))
Result = C1;
return Result;
}
private void SaveChangesToDB()
{
foreach (Employee E in EmpList)
{
DBCommands.SaveEmployee(E);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace GUI_Design_Mockup
{
public partial class frmMainMenu : Form
{
List<Group> GroupList;
List<Department> DeptList;
List<Employee> EmpList;
List<Employee> EmpListA;
List<Type_Of_Award> ToAList;
DataClasses1DataContext DContext;
public frmMainMenu()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
LaunchForm(new frmEmployees());
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
frm.Location = this.Location;
this.Hide();
}
private void button6_Click(object sender, EventArgs e)
{
LaunchForm(new frmNewAward());
}
private void frmMainMenu_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'pRIDE_beDataSet.Employee' table. You can move, or remove it, as needed.
try
{
this.employeeTableAdapter.Fill(this.pRIDE_beDataSet.Employee);
}
catch (Exception E)
{
}
DBCommands.DContext = new DataClasses1DataContext();
DContext = DBCommands.DContext;
InitializeGroupBox();
InitializeDeptBox();
InitializeEmpBox();
InitializeAwdBox();
if (DateTime.Now > new DateTime(2014, 1, 1))
button12.Visible = false;
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
Group AllGroup;
AllGroup = new Group();
AllGroup.GroupID = "GRP0000000";
AllGroup.GroupNum = "All Groups";
AllGroup.DayOfPride = 'X';
GroupList.Add(AllGroup);
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
}
private void InitializeDeptBox()
{
var DeptListRaw = from D in DBCommands.DContext.Departments
orderby D.DeptName ascending
select D;
DeptList = new List<Department>();
Department AllDepartment;
AllDepartment = new Department();
AllDepartment.DeptID = "DPT0000000";
AllDepartment.DeptName = "All Departments";
DeptList.Add(AllDepartment);
foreach (Department D in DeptListRaw)
{
DeptList.Add(D);
}
DepartmentBox.DataSource = DeptList;
}
private void InitializeEmpBox()
{
var EmpListRaw = from E in DBCommands.DContext.Employees
orderby E.LastName ascending
select E;
EmpList = new List<Employee>();
EmpListA = new List<Employee>();
Employee AllEmployee;
AllEmployee = new Employee();
AllEmployee.EmployeeID = "EMP0000000";
EmpList.Add(AllEmployee);
EmpListA.Add(AllEmployee);
foreach (Employee E in EmpListRaw)
{
EmpList .Add(E);
EmpListA.Add(E);
}
NominatorBox.DataSource = EmpList ;
RecipientBox.DataSource = EmpListA;
}
private void InitializeAwdBox()
{
var AwdListRaw = from A in DBCommands.DContext.Type_Of_Awards
orderby A.AwardTypeName ascending
select A;
ToAList = new List<Type_Of_Award >();
Type_Of_Award AllAward;
AllAward = new Type_Of_Award();
AllAward.AwardTypeName = "All Awards";
ToAList.Add(AllAward);
foreach (Type_Of_Award ToA in AwdListRaw)
{
ToAList.Add(ToA);
}
AwardTypeBox.DataSource = ToAList;
}
private void button12_Click(object sender, EventArgs e)
{
LaunchForm(new frmUpdateFromAccess());
}
private void ReviewOTSButton_Click(object sender, EventArgs e)
{
frmReviewOnTheSpot form = new frmReviewOnTheSpot();
List<Award> AwdList = new List<Award>();
string AwdID = DBCommands.GetAwardID("On The Spot");
var AwdListRawA = from N in DContext.Awards
where N.AwardTypeID == AwdID && System.Data.Linq.SqlClient.SqlMethods.Like(N.RecipientID,"EMP%")
orderby N.RecipientID
select N;
Group GrpVal =(Group) GroupNoBox.SelectedItem;
if (GrpVal != null && !GrpVal.GroupID.Equals("GRP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
join Emp in DContext.Employees on N.RecipientID equals Emp.EmployeeID
where Emp.GroupID == GrpVal.GroupID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Department DptVal = (Department)DepartmentBox.SelectedItem;
if (DptVal != null && !DptVal.DeptID.Equals("DPT0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
join Emp in DContext.Employees on N.RecipientID equals Emp.EmployeeID
where Emp.DeptID==DptVal.DeptID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Employee RecEmp = (Employee)RecipientBox.SelectedItem;
if (RecEmp != null && !RecEmp.EmployeeID.Equals("EMP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
where N.RecipientID == RecEmp.EmployeeID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Employee NomEmp = (Employee)NominatorBox.SelectedItem;
if (NomEmp != null && !NomEmp.EmployeeID.Equals("EMP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
where N.NominatorID == NomEmp.EmployeeID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
if (checkBox1.Checked)
{
var AwdListRawB = from N in AwdListRawA
where N.AwardDate >= StartDateBox.Value
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
if (checkBox2.Checked)
{
var AwdListRawB = from N in AwdListRawA
where N.AwardDate <= EndDateBox.Value
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
foreach (Award A in AwdListRawA)
AwdList.Add(A);
form.StartThing(AwdList);
LaunchForm(form);
}
private void StartDateBox_ValueChanged(object sender, EventArgs e)
{
checkBox1.Checked = true;
}
private void EndDateBox_ValueChanged(object sender, EventArgs e)
{
checkBox2.Checked = true;
}
private void YSPButton_Click(object sender, EventArgs e)
{
LaunchForm(new frmYouShowedPRIDE());
}
private void DWPButton_Click(object sender, EventArgs e)
{
LaunchForm(new frmYouShowedPRIDE("Dinner With PRIDE"));
}
private void DOPButton_Click(object sender, EventArgs e)
{
LaunchForm(new frmDayOfPRIDE());
}
private void PAAButton_Click(object sender, EventArgs e)
{
LaunchForm(new frmPRIDEAwards());
}
private void MonthStatRptButton_Click(object sender, EventArgs e)
{
DateTime StartDate = checkBox1.Checked ? StartDateBox.Value : new DateTime(1, 1, 2000);
DateTime EndDate = checkBox2.Checked ? EndDateBox.Value : DateTime.Now;
LaunchForm(new frmMonthlyStats(StartDate, EndDate));
}
private void button1_Click(object sender, EventArgs e)
{
frmReviewOnTheSpot form;// = new frmReviewOnTheSpot("All Awards");
List<Award> AwdList = new List<Award>();
var AwdListRawA = from N in DContext.Awards
where System.Data.Linq.SqlClient.SqlMethods.Like(N.RecipientID, "EMP%")
orderby N.RecipientID
select N;
Type_Of_Award ToA = (Type_Of_Award)AwardTypeBox.SelectedItem;
if (ToA != null && !ToA.AwardTypeName.Equals("All Awards", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
where N.AwardTypeID == ToA.AwardTypeID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
form = new frmReviewOnTheSpot(ToA.AwardTypeName );
}
else
form = new frmReviewOnTheSpot("All Awards");
Group GrpVal = (Group)GroupNoBox.SelectedItem;
if (GrpVal != null && !GrpVal.GroupID.Equals("GRP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
join Emp in DContext.Employees on N.RecipientID equals Emp.EmployeeID
where Emp.GroupID == GrpVal.GroupID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Department DptVal = (Department)DepartmentBox.SelectedItem;
if (DptVal != null && !DptVal.DeptID.Equals("DPT0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
join Emp in DContext.Employees on N.RecipientID equals Emp.EmployeeID
where Emp.DeptID == DptVal.DeptID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Employee RecEmp = (Employee)RecipientBox.SelectedItem;
if (RecEmp != null && !RecEmp.EmployeeID.Equals("EMP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
where N.RecipientID == RecEmp.EmployeeID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
Employee NomEmp = (Employee)NominatorBox.SelectedItem;
if (NomEmp != null && !NomEmp.EmployeeID.Equals("EMP0000000", StringComparison.CurrentCultureIgnoreCase))
{
var AwdListRawB = from N in AwdListRawA
where N.NominatorID == NomEmp.EmployeeID
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
if (checkBox1.Checked)
{
var AwdListRawB = from N in AwdListRawA
where N.AwardDate >= StartDateBox.Value
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
if (checkBox2.Checked)
{
var AwdListRawB = from N in AwdListRawA
where N.AwardDate <= EndDateBox.Value
orderby N.RecipientID
select N;
AwdListRawA = (System.Linq.IOrderedQueryable<Award>)AwdListRawB;
}
foreach (Award A in AwdListRawA)
AwdList.Add(A);
form.StartThing(AwdList);
LaunchForm(form);
}
private void DeptGrpRptButton_Click(object sender, EventArgs e)
{
LaunchForm(new frmDepartmentGroup());
}
private void BlankOTSButton_Click(object sender, EventArgs e)
{
string FileLoc = Application.StartupPath +@"\Blank Award Document.docx";
DBCommands.PrintBlankDocument(FileLoc);
}
private void EmpAwdSumButton_Click(object sender, EventArgs e)
{
String GroupID, Department, Recipient, Nominator, AwardType;
Group g = (Group)GroupNoBox.SelectedValue;
if (g.GroupID == "GRP0000000" || g == null)
{
GroupID = "";
}
else
{
GroupID = g.GroupID;
}
Department d = (Department)DepartmentBox.SelectedValue;
if (d.DeptID == "DPT0000000" || d == null)
{
Department = "";
}
else
{
Department = d.DeptID;
}
Employee r = (Employee)RecipientBox.SelectedValue;
if (r.EmployeeID == "EMP0000000" || r == null)
{
Recipient = "";
}
else
{
Recipient = r.EmployeeID;
}
Employee n = (Employee)NominatorBox.SelectedValue;
if (n.EmployeeID == "EMP0000000" || n == null)
{
Nominator = "";
}
else
{
Nominator = n.EmployeeID;
}
Type_Of_Award t = (Type_Of_Award)AwardTypeBox.SelectedValue;
if (t.AwardTypeName == "All Awards" || t == null)
{
AwardType = "";
}
else
{
AwardType = t.AwardTypeID;
}
MessageBox.Show(Recipient + " - " + r.FirstName + " " + r.LastName);
DateTime OldestAward;
var award = from s in DContext.Awards
orderby s.AwardDate ascending
select s;
OldestAward = (DateTime)award.First().AwardDate;
DateTime StartDate = checkBox1.Checked ? StartDateBox.Value : OldestAward;
DateTime EndDate = checkBox2.Checked ? EndDateBox.Value : DateTime.Now;
LaunchForm(new frmAwardsSummaryReport(StartDate, EndDate, GroupID, Department, Recipient, Nominator, AwardType));
// string FileLoc = /*Application.StartupPath*/@"C:\Users\Stephan\Google Drive\Digital USB\PRIDE Beta" + @"\Blank Award Template.dotx";
// DBCommands.BuildAwardPrintout(FileLoc, new Award());
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GUI_Design_Mockup
{
class classDepartmentGroupReport
{
public String DayOfPride { get; set; }
public String GroupNum { get; set; }
public String Department { get; set; }
public float FTE { get; set; }
public int EmployeeCount { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
namespace GUI_Design_Mockup
{
class DBCommands
{
public static int MaxTeamCount = 6;
public static DataClasses1DataContext DContext;
public static Employee GetEmployee(string EmpID)
{
Employee result = null;
var TempEmp = DContext.GetTable<Employee>().SingleOrDefault(p => p.EmployeeID == EmpID);
if (TempEmp != null)
result = TempEmp;
return result;
}
public static Employee GetEmployee(string First, char? Middle, string Last)
{
Employee result = null;
Employee TempEmp;
if (Middle != null)
{
TempEmp = (from Emp in DContext.Employees
where Emp.FirstName == First && Emp.MiddleInitial == Middle && Emp.LastName == Last
select Emp).First<Employee>();
}
else
{
TempEmp = (from Emp in DContext.Employees
where Emp.FirstName == First && Emp.LastName == Last
select Emp).First<Employee>();
}
if (TempEmp != null)
result = TempEmp;
return result;
}
public static Department GetDepartment(string DeptID)
{
Department result = null;
var TempEmp = DContext.GetTable<Department>().SingleOrDefault(p => p.DeptID == DeptID);
if (TempEmp != null)
result = TempEmp;
return result;
}
/*public static string GetAwardNominationID(string AwardName)
{
string result = "";
var AwdNomination = DContext.GetTable<Type_Of_Award>().SingleOrDefault(p => p.AwardTypeName == AwardName);
if (AwdNomination != null)
result = AwdNomination.AwardTypeID;
return result;
}*/
public static string GetDeptID(string DeptName)
{
string result = "";
var DptVar = DContext.GetTable<Department>().SingleOrDefault(p => p.DeptName == DeptName);
if (DptVar != null)
result = DptVar.DeptID;
return result;
}
public static string GetOrCreateDeptID(string DeptName)
{
string result = GetDeptID(DeptName);
if (result == "")
{
Department NewDept = new Department();
NewDept.DeptName = DeptName;
NewDept.DeptID = NextID("Department");
result = NewDept.DeptID;
DContext.Departments.InsertOnSubmit(NewDept);
DContext.SubmitChanges();
}
return result;
}
public static string GetGroupID(string GroupName)
{
string result = "";
var DptVar = DContext.GetTable<Group>().SingleOrDefault(p => p.GroupNum == GroupName);
if (DptVar != null)
result = DptVar.GroupID;
return result;
}
public static string GetAwardID(string AwardName)
{
string result = "";
var AwdVar = DContext.GetTable<Type_Of_Award>().SingleOrDefault(p => p.AwardTypeName == AwardName);
if (AwdVar != null)
result = AwdVar.AwardTypeID;
return result;
}
public static Type_Of_Award GetTypeOfAward(string AwardID)
{
var AwdVar = DContext.GetTable<Type_Of_Award>().SingleOrDefault(p => p.AwardTypeID == AwardID);
if (AwdVar != null)
return AwdVar;
else
return null;
}
public static Type_Of_Award GetAwardFromNomination(string NominationID)
{
var AwdVar = DContext.GetTable<Type_Of_Award>().SingleOrDefault(p => p.AwardNominationID == NominationID);
if (AwdVar != null)
return AwdVar;
else
return null;
}
public static bool GetAwardExists(string AwardID)
{
var AwdVar = DContext.GetTable<Award>().SingleOrDefault(p => p.AwardID == AwardID);
return AwdVar != null;
}
public static bool GetEmployeeExists(string FirstName, char? MiddleInitial, string LastName)
{
if (MiddleInitial != null)
{
var TempEmp = DContext.GetTable<Employee>().FirstOrDefault(p => p.FirstName == FirstName && p.MiddleInitial == MiddleInitial && p.LastName == LastName);
return TempEmp != null;
}
else
{
var TempEmp = DContext.GetTable<Employee>().FirstOrDefault(p => p.FirstName == FirstName && p.LastName == LastName);
return TempEmp != null;
}
}
public static string GetEmployeeID(string PreferredName, string LastName)
{
string result = "";
var EmpVar = DContext.GetTable<Employee>().SingleOrDefault(p => p.PreferredName == PreferredName && p.LastName == LastName);
if (EmpVar != null)
result = EmpVar.EmployeeID;
return result;
}
public static string NextID(string TableName)
{
var NextId = DBCommands.DContext.GetTable<NextID>().SingleOrDefault(p => p.TableName == TableName);
int result = (int)NextId.NextNum;
NextId.NextNum++;
DBCommands.DContext.SubmitChanges();
string ResultStr = NextId.Prefix + result.ToString("0000000");
return ResultStr;
}
public static List<Employee> GetNewEmployeesList()
{
List<Employee> EmpList = new List<Employee>();
var EmpListRaw = from E in DContext.Employees
where E.GroupID==""
select E;
foreach(Employee E in EmpListRaw)
EmpList.Add(E);
return EmpList;
}
public static void SaveEmployee(Employee Emp)
{
var EmpVal = DContext.GetTable<Employee>().SingleOrDefault(p => p.EmployeeID == Emp.EmployeeID );
if (EmpVal != null)
{
EmpVal.PreferredName = Emp.PreferredName;
EmpVal.GroupID = Emp.GroupID;
EmpVal.PrideEligible = Emp.PrideEligible;
EmpVal.Active = Emp.Active;
EmpVal.OldAwardCount = Emp.OldAwardCount;
DContext.SubmitChanges();
}
}
public static void SaveEmployeeB(Employee Emp)
{
var EmpVal = DContext.GetTable<Employee>().SingleOrDefault(p => p.EmployeeID == Emp.EmployeeID);
if (EmpVal != null)
{
EmpVal.DeptID = Emp.DeptID;
EmpVal.GroupID = Emp.GroupID;
EmpVal.HR_Status= Emp.HR_Status ;
EmpVal.HR_FTE = Emp.HR_FTE ;
EmpVal.Title = Emp.Title ;
DContext.SubmitChanges();
}
}
public static void DeactivateEmployee(Employee Emp)
{
var EmpVal = DContext.GetTable<Employee>().SingleOrDefault(p => p.EmployeeID == Emp.EmployeeID);
if (EmpVal != null)
{
EmpVal.Active = false;
DContext.SubmitChanges();
}
}
public static List<Employee> BuildEmployeeListFromExcel()
{
List<Employee> ExcelEmpList = new List<Employee>();
List<Employee> NewEmpList = new List<Employee>();
OpenFileDialog OFD = new OpenFileDialog();
OFD.DefaultExt = "*.xls";
if (OFD.ShowDialog() == DialogResult.OK)
{
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Open(OFD.FileName);
Excel.Worksheet oSheet = oWB.ActiveSheet;
Excel.Range rng;
int C1 = 2;
Employee tempEmp;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
for (C1 = 2; C1 <= lastUsedRow; C1++)
{
tempEmp = new Employee();
rng = oSheet.Cells[C1, 1] as Excel.Range;
tempEmp.DeptID = DBCommands.GetOrCreateDeptID(rng.Value2.ToString());
rng = oSheet.Cells[C1, 2] as Excel.Range;
tempEmp.Title = rng.Value2.ToString();
rng = oSheet.Cells[C1, 3] as Excel.Range;
tempEmp.HR_Status = rng.Value2.ToString();
rng = oSheet.Cells[C1, 4] as Excel.Range;
tempEmp.LastName = rng.Value2;
rng = oSheet.Cells[C1, 5] as Excel.Range;
tempEmp.FirstName = rng.Value2;
rng = oSheet.Cells[C1, 6] as Excel.Range;
if (rng.Value2.ToString().Length > 0)
tempEmp.MiddleInitial = rng.Value2.ToString()[0];
rng = oSheet.Cells[C1, 7] as Excel.Range;
tempEmp.HireDate = (DateTime)rng.get_Value();
rng = oSheet.Cells[C1, 8] as Excel.Range;
tempEmp.HR_FTE = (double)rng.get_Value();
rng = oSheet.Cells[C1, 9] as Excel.Range;
tempEmp.EmployeeStatusCode = rng.Value2.ToString();
ExcelEmpList.Add(tempEmp);
}
}
return ExcelEmpList;
}
public static void PrintBlankDocument(string FileLocation)
{
object copies = "1";
object pages = "";
object range = Word.WdPrintOutRange.wdPrintAllDocument;
object items = Word.WdPrintOutItem.wdPrintDocumentContent;
object pageType = Word.WdPrintOutPages.wdPrintAllPages;
object oTrue = true;
object oFalse = false;
Word.Application wApp = new Word.Application();
wApp.Visible = false;
string FileLoc = FileLocation;
Word.Document wDoc = wApp.Documents.Open(FileLoc);
//object missing = Type.Missing;
object nullobj = System.Reflection.Missing.Value;
wDoc.Activate();
wApp.Visible = true;
int dialogResult = wApp.Dialogs[Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint].Show(ref nullobj);
wDoc.Close();
wApp.Visible = false;
wApp.Quit();
wApp = null;
GC.Collect();
}
public static void LoadNewEmployees()
{
List<Employee> ExcelEmpList = new List<Employee>();
List<Employee> NewEmpList = new List<Employee>();
OpenFileDialog OFD = new OpenFileDialog();
OFD.DefaultExt = "*.xls";
if (OFD.ShowDialog() == DialogResult.OK)
{
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Open(OFD.FileName);
Excel.Worksheet oSheet = oWB.ActiveSheet;
Excel.Range rng;
int C1 = 2;
Employee tempEmp;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
for (C1 = 2; C1 <= lastUsedRow; C1++)
{
tempEmp = new Employee();
rng = oSheet.Cells[C1, 1] as Excel.Range;
tempEmp.DeptID = DBCommands.GetOrCreateDeptID(rng.Value2.ToString());
rng = oSheet.Cells[C1, 2] as Excel.Range;
tempEmp.Title = rng.Value2.ToString();
rng = oSheet.Cells[C1, 3] as Excel.Range;
tempEmp.HR_Status = rng.Value2.ToString();
rng = oSheet.Cells[C1, 4] as Excel.Range;
tempEmp.LastName = rng.Value2;
rng = oSheet.Cells[C1, 5] as Excel.Range;
tempEmp.FirstName = rng.Value2;
rng = oSheet.Cells[C1, 6] as Excel.Range;
if (rng.Value2.ToString().Length > 0)
tempEmp.MiddleInitial = rng.Value2.ToString()[0];
rng = oSheet.Cells[C1, 7] as Excel.Range;
tempEmp.HireDate = (DateTime)rng.get_Value();
rng = oSheet.Cells[C1, 8] as Excel.Range;
tempEmp.HR_FTE = (double)rng.get_Value();
rng = oSheet.Cells[C1, 9] as Excel.Range;
tempEmp.EmployeeStatusCode = rng.Value2.ToString();
ExcelEmpList.Add(tempEmp);
}
oWB.Close();
oXL.Quit();
foreach (Employee E in ExcelEmpList)
if (!DBCommands.GetEmployeeExists(E.FirstName, E.MiddleInitial, E.LastName))
{
E.EmployeeID = NextID("Employee");
NewEmpList.Add(E);
}
foreach (Employee E in NewEmpList)
{
DContext.Employees.InsertOnSubmit(E);
}
DBCommands.DContext.SubmitChanges();
}
}
public static bool EmployeeNeedsUpdating(Employee Emp, out Employee OldEmp)
{
bool result = false;
OldEmp = GetEmployee(Emp.FirstName,Emp.MiddleInitial,Emp.LastName);
if (OldEmp != null)
{
if(OldEmp.DeptID != Emp.DeptID || OldEmp.Title !=Emp.Title || OldEmp.HR_FTE !=Emp.HR_FTE || OldEmp.HR_Status!=Emp.HR_Status)
{
result = true;
}
}
return result;
}
public static List<Employee> GetAllEmployeeList(bool RequireActive, bool RequireEligible= false)
{
var EmpListRaw = from E in DContext.Employees
orderby E.LastName ascending
select E;
if (RequireActive)
{
EmpListRaw = EmpListRaw.Where(p => (bool)p.Active).OrderBy(p => p.LastName);
}
if (RequireEligible )
{
EmpListRaw = EmpListRaw.Where(p => (bool)p.PrideEligible).OrderBy(p=>p.LastName);
}
List<Employee> EmpList = new List<Employee>();
Employee AllEmployee;
AllEmployee = new Employee();
AllEmployee.EmployeeID = "EMP-000001";
EmpList.Add(AllEmployee);
foreach (Employee E in EmpListRaw)
{
EmpList.Add(E);
}
return EmpList;
}
public static List<Type_Of_Award> GetAllTypeOfAwardList(string DefaultAwardType, out Type_Of_Award DefaultResult)
{
var ToAListRaw = from A in DContext.Type_Of_Awards
where A.IsNomination == true || A.AwardTypeName == "On The Spot"
orderby A.AwardTypeName ascending
select A;
List<Type_Of_Award> AwardTypeList = new List<Type_Of_Award>();
DefaultResult = null;
foreach (Type_Of_Award T in ToAListRaw)
{
AwardTypeList.Add(T);
if (T.AwardTypeName.Equals(DefaultAwardType, StringComparison.CurrentCultureIgnoreCase))
DefaultResult = T;
}
return AwardTypeList;
}
public static List<Department> GetAllDepartmentList()
{
var DeptListRaw = from D in DContext.Departments
orderby D.DeptName ascending
select D;
List<Department> DeptList = new List<Department>();
Department AllDepartment;
AllDepartment = new Department();
AllDepartment.DeptID = "DPT0000000";
AllDepartment.DeptName = "All Departments";
DeptList.Add(AllDepartment);
foreach (Department D in DeptListRaw)
{
DeptList.Add(D);
}
return DeptList;
}
public static string BuildTeam(params string[] EmployeeIDs)
{
string TeamId = NextID("Team");
int C1;
Team temp;
for (C1 = 0; C1 < EmployeeIDs.Length; C1++)
{
string nextID = NextID("Row");
temp = new Team();
temp.TeamID = TeamId;
temp.EmployeeID = EmployeeIDs[C1];
temp.RowID = nextID;
DContext.Teams.InsertOnSubmit(temp);
}
DContext.SubmitChanges();
return TeamId;
}
public static List<string> GetEmployeeIDsForTeam(string TeamID)
{
List<string> IDList = new List<String>();
var TeamListRaw = from T in DContext.Teams
where T.TeamID == TeamID
select T;
foreach (Team T in TeamListRaw)
IDList.Add(T.EmployeeID );
return IDList;
}
public static List<Employee> GetEmployeesForTeam(string TeamID)
{
List<Employee> EmpList = new List<Employee>();
var TeamListRaw = from T in DContext.Teams
where T.TeamID == TeamID
select T;
foreach (Team T in TeamListRaw)
{
EmpList.Add(GetEmployee(T.EmployeeID));
}
return EmpList;
}
public static void BuildAwardPrintout(string FileLoc, Award Awd)
{
Employee Nominator = GetEmployee(Awd.NominatorID);
Employee Recipient = GetEmployee(Awd.RecipientID);
Department Dpt = GetDepartment(Recipient.DeptID);
Type_Of_Award ToA = GetTypeOfAward(Awd.AwardTypeID);
object copies = "1";
object pages = "";
object range = Word.WdPrintOutRange.wdPrintAllDocument;
object items = Word.WdPrintOutItem.wdPrintDocumentContent;
object pageType = Word.WdPrintOutPages.wdPrintAllPages;
object oTrue = true;
object oFalse = false;
try
{
Word.Application wApp = new Word.Application();
wApp.Visible = false;
Word.Document wDoc = wApp.Documents.Open(FileLoc);
//object missing = Type.Missing;
object nullobj = System.Reflection.Missing.Value;
wDoc.Activate();
var CCList = wDoc.SelectContentControlsByTitle("RecipientBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = Recipient.PreferredName+" "+Recipient.LastName ;
CCList = wDoc.SelectContentControlsByTitle("NominatorBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = Nominator.PreferredName +" "+Nominator.LastName ;
CCList = wDoc.SelectContentControlsByTitle("DepartmentBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = Dpt.DeptName ;
CCList = wDoc.SelectContentControlsByTitle("AwardTypeBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = ToA.AwardTypeName ;
CCList = wDoc.SelectContentControlsByTitle("DateBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = ((DateTime)Awd.AwardDate).ToString("MM/dd/yyyy");
CCList = wDoc.SelectContentControlsByTitle("NotesBox");
foreach (Word.ContentControl CC in CCList)
CC.Range.Text = Awd.Notes;
//wApp.Dialogs[Word.WdWordDialog.wdDialogFileSaveAs].Show(ref nullobj);
string SaveLocation= Application.StartupPath+@"\Awards\"+Nominator.PreferredName+" "+Nominator.LastName+" "+Awd.AwardID+".docx";
wDoc.SaveAs2(SaveLocation);
nullobj = System.Reflection.Missing.Value;
wApp.Visible = true;
int dialogResult = wApp.Dialogs[Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint].Show(ref nullobj);
try
{
wDoc.Close();
}
catch
{
}
wApp.Visible = false;
try
{
wApp.Quit();
}
catch
{
}
wApp = null;
GC.Collect();
}
catch
{
MessageBox.Show("Something went wrong while trying to generate an Award. Try closing word and trying again");
}
}
}
//Let's build some ToString() functions, shall we?
partial class Employee
{
public override string ToString()
{
if (EmployeeID == "EMP0000000")
{
return "All Employees";
}
else if(EmployeeID=="EMP-000001")
{
return "Choose an Employee";
}
else
return PreferredName+" " + LastName ;
}
}
partial class Department
{
public override string ToString()
{
if (DeptID == "DPT0000000")
return "All Departments";
else
return DeptName;
}
}
partial class Group
{
public override string ToString()
{
if (GroupID == "GRP0000000")
return "All Groups";
else
return GroupNum;
}
}
partial class Type_Of_Award
{
public override string ToString()
{
if (AwardTypeID == "TOA0000000")
return "All Award Types";
else
return AwardTypeName;
}
}
}
<file_sep>using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmDepartmentGroup : Form
{
public frmDepartmentGroup()
{
InitializeComponent();
}
private void frmDepartmentGroup_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
//Clear the defaults from the report
reportViewer1.Reset();
reportViewer1.LocalReport.DataSources.Clear();
//Tell the viewer which report we're using
reportViewer1.LocalReport.ReportEmbeddedResource = "GUI_Design_Mockup.DepartmentGroupReport.rdlc";
//Get the DataContext for queries
DataClasses1DataContext dc = DBCommands.DContext;
var DayOfPrideList = from s in dc.Groups
orderby s.DayOfPride
select s.DayOfPride;
DayOfPrideList = DayOfPrideList.Distinct();
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("DayOfPride");
foreach (var q in DayOfPrideList)
{
Object x = q;
data.Tables["A"].Rows.Add(x);
}
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DepartmentGroupSet", data.Tables["A"]));
this.reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
reportViewer1.RefreshReport();
}
void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
{
DataClasses1DataContext dc = DBCommands.DContext;
if (e.ReportPath == "DayOfPrideGroupSubreport")
{
DataSet nds = new DataSet("DayOfPrideSet");
nds.Tables.Add("A");
nds.Tables["A"].Columns.Add("GroupNum");
nds.Tables["A"].Columns.Add("FTE");
nds.Tables["A"].Columns.Add("EmployeeCount");
var GroupList = from s in dc.Groups
where s.DayOfPride.ToString() == e.Parameters.First().Values.First()
orderby s.GroupID
select s;
object[] row = new object[3];
foreach (var p in GroupList)
{
float FTE = 0;
int count = 0;
var EmpsInGroup = from s in dc.Employees
where (bool)s.Active && s.GroupID == p.GroupID
select s;
var DeptIDs = from s in EmpsInGroup
select s.DeptID;
DeptIDs = DeptIDs.Distinct();
//Get the departments in the group by comparing department IDs
var DeptsInGroup = from s in dc.Departments
where DeptIDs.Contains(s.DeptID)
orderby s.DeptID
select s;
//Everything through this line returns proper data
//MessageBox.Show("Department: " + DeptsInGroup.Count().ToString());
foreach (var q in DeptsInGroup)
{
var EmpsInDept = from s in EmpsInGroup
where s.DeptID == q.DeptID && s.GroupID == p.GroupID
select s;
count += EmpsInDept.Count();
//MessageBox.Show(q.DeptName + ": " + count.ToString());
//int i = 0;
foreach (var r in EmpsInDept)
{
if (r.HR_FTE == null) FTE += 0;
else FTE += (float)r.HR_FTE;
}
}
row[0] = p.GroupNum;
row[1] = FTE;
row[2] = count;
nds.Tables["A"].Rows.Add(row);
}
ReportDataSource rds = new ReportDataSource();
rds.Name = "DayOfPrideSet";
rds.Value = nds.Tables["A"];
e.DataSources.Add(rds);
}
if (e.ReportPath == "DGroupSubreport")
{
DataSet nds = new DataSet("DGroupSet");
nds.Tables.Add("A");
nds.Tables["A"].Columns.Add("Department");
nds.Tables["A"].Columns.Add("FTE");
nds.Tables["A"].Columns.Add("EmployeeCount");
Object[] row = new Object[3];
String GroupID = (from s in dc.Groups
where s.GroupNum == e.Parameters.First().Values.First()
select s.GroupID).First();
var EmpsInGroup = from s in dc.Employees
where (bool)s.Active && s.GroupID == GroupID
select s;
var DeptIDs = from s in EmpsInGroup
select s.DeptID;
DeptIDs = DeptIDs.Distinct();
//Get the departments in the group by comparing department IDs
var DeptsInGroup = from s in dc.Departments
where DeptIDs.Contains(s.DeptID)
orderby s.DeptID
select s;
//Everything through this line returns proper data
//MessageBox.Show("Department: " + DeptsInGroup.Count().ToString());
foreach (var q in DeptsInGroup)
{
float FTE = 0;
int count = 0;
var EmpsInDept = from s in EmpsInGroup
where s.DeptID == q.DeptID && s.GroupID == GroupID
select s;
count = EmpsInDept.Count();
//MessageBox.Show(q.DeptName + ": " + count.ToString());
//int i = 0;
foreach (var r in EmpsInDept)
{
if (r.HR_FTE == null) FTE += 0;
else FTE += (float)r.HR_FTE;
}
row[0] = q.DeptName;
row[1] = FTE;
row[2] = count;
nds.Tables["A"].Rows.Add(row);
}
//foreach (var p in DeptsInGroup)
//{
// float FTE = 0;
// int count = 0;
// var EmpsInDept = from s in EmpsInGroup
// where s.DeptID == p.DeptID && s.GroupID == GroupID
// select s;
// //MessageBox.Show(p.DeptID + " " + EmpsInDept.Count().ToString());
// foreach (var q in EmpsInDept)
// {
// count++;
// FTE += (float)q.HR_FTE;
// }
// //MessageBox.Show("Department: " + p.DeptName + "NumEmployees : " + EmpsInDept.Count().ToString() + "\r\nFTE: " + FTE.ToString() + " Count: " + count.ToString());
// row[0] = p.DeptName;
// row[1] = FTE;
// row[2] = count;
// //MessageBox.Show(row[0].ToString() + "\r\n" + row[1].ToString() + "\r\n" + row[2].ToString() + "\r\n");
// nds.Tables["A"].Rows.Add(row);
//}
ReportDataSource rds = new ReportDataSource();
rds.Name = "DGroupSet";
rds.Value = nds.Tables["A"];
e.DataSources.Add(rds);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmReviewOnTheSpot : Form
{
List<Award> AwdList;
/*List<Department> DeptList;
List<Employee> EmpList;
List<Employee> EmpListA;*/
DataClasses1DataContext DContext;
Award SelectedAward;
public frmReviewOnTheSpot(string AwardName = "On The Spot")
{
InitializeComponent();
DContext = DBCommands.DContext;
AwdList = new List<Award>();
panel2.Enabled = true;
textBox3.Text = AwardName;
if(AwardName.Equals("All Awards",StringComparison.CurrentCultureIgnoreCase))
{
label1.Text = "All Awards";
Text="Review All Awards";
}
else if (!AwardName.Contains("Nomination"))
{
label1.Text = AwardName + " Award";
Text = "Review " + AwardName + " Awards";
}
else
{
label1.Text = AwardName;
Text = "Review " + AwardName + "s";
}
label1.Location = new Point(((this.Size.Width / 2) - label1.Size.Width / 2), label1.Location.Y);
}
private void frmReviewOnTheSpot_Load(object sender, EventArgs e)
{
}
public void StartThing(List<Award> AwdListB)
{
foreach (Award A in AwdListB)
AwdList.Add(A);
hScrollBar1.Maximum = AwdList.Count + (hScrollBar1.LargeChange-1);
hScrollBar1.Minimum = 1;
XofYLabel.Text = hScrollBar1.Value.ToString() + " of " + AwdList.Count;
if(AwdList.Count>0)
LoadDataForAward(0);
}
public void LoadDataForAward(int Index)
{
SelectedAward = AwdList[Index];
NoteBox.Text = SelectedAward.Notes;
Employee NomEmp = DBCommands.GetEmployee(SelectedAward.NominatorID);
Employee RecEmp = DBCommands.GetEmployee(SelectedAward.RecipientID);
Type_Of_Award ToA = DBCommands.GetTypeOfAward(SelectedAward.AwardTypeID);
Department NomDept;
if (NomEmp != null)
{
NominatorBox.Text = NomEmp.ToString();
}
if (RecEmp != null)
{
RecipientBox.Text = RecEmp.ToString();
NomDept = DBCommands.GetDepartment(RecEmp.DeptID);
if (NomDept != null)
DepartmentBox.Text = NomDept.ToString();
}
if (ToA != null)
textBox3.Text = ToA.AwardTypeName;
dateTimePicker1.Value = (DateTime)SelectedAward.AwardDate;
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int SelectedIndex = hScrollBar1.Value;
if (SelectedIndex > -1 && SelectedIndex<= AwdList.Count)
{
XofYLabel.Text = SelectedIndex.ToString() + " of " + AwdList.Count.ToString();
LoadDataForAward(SelectedIndex - 1);
}
}
private void button3_Click(object sender, EventArgs e)
{
NoteBox.Text = SelectedAward.Notes;
dateTimePicker1.Value = (DateTime)SelectedAward.AwardDate;
}
private void button2_Click(object sender, EventArgs e)
{
var Awd = DContext.Awards.Single(x => x.AwardID == SelectedAward.AwardID);
Awd.Notes = NoteBox.Text;
Awd.AwardDate = dateTimePicker1.Value;
DContext.SubmitChanges();
MessageBox.Show("Changes saved");
/*using (var ctx = new FooContext())
{
var obj = ctx.Bars.Single(x => x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}*/
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GUI_Design_Mockup
{
class classStatsReport
{
public int groupNum { get; set; }
public String Department { get; set; }
public int numEmployees { get; set; }
public int numAwardsReceived { get; set; }
public int numEmployeesReceived { get; set; }
public int numAwardsGiven { get; set; }
public int numEmployeesGiven { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmYouShowedPRIDE : Form
{
List<Group> GroupList;
//List<Award> AwardList;
DataClasses1DataContext DContext;
string AwardTypeName;
public frmYouShowedPRIDE(string AwardTypeName = "You Showed PRIDE")
{
InitializeComponent();
DContext = DBCommands.DContext;
this.AwardTypeName = AwardTypeName;
ElibilityReportButton.Text = AwardTypeName + " Eligibility Report";
EmailReportButton.Text = "Email " + AwardTypeName + " Eligibility Report";
WinnerReportButton.Text = AwardTypeName + " Award Winners";
TopLabel.Text = AwardTypeName + " Nominations and Awards";
TopLabel.Location = new Point(((this.Size.Width / 2) - TopLabel.Size.Width / 2), TopLabel.Location.Y);
}
private void frmYouShowedPRIDE_Load(object sender, EventArgs e)
{
/*int C1;
for (C1 = 0; 2004 + C1 <= DateTime.Now.Year; C1++)
YearBox.Items.Add((2004 + C1).ToString());
YearBox.Text = DateTime.Now.Year.ToString();
MonthBox.SelectedIndex = DateTime.Now.Month - 1;*/
InitializeGroupBox();
}
private void GroupBox_SelectedValueChanged(object sender, EventArgs e)
{
Group grp = (Group)GroupNoBox.SelectedItem;
string GroupNum = "";
if (grp != null)
GroupNum = grp.GroupNum;
//string Month = "";
//if (MonthBox.SelectedItem != null)
// Month = MonthBox.SelectedItem.ToString();
label7.Text = "Select winner(s) for Group " + GroupNum + " from "+StartDateBox.Value.ToShortDateString()+" to "+EndDateBox.Value.ToShortDateString()+",\n\r then click the Winner button.";
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
}
private void button4_Click(object sender, EventArgs e)
{
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, MonthValue, 1);
DateTime FirstDayThisYear = new DateTime(DateTime.Now.Year, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, MonthValue, DateTime.DaysInMonth(YearValue, MonthValue));
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID(AwardTypeName );
string AwdNomID = DBCommands.GetTypeOfAward(AwdID).AwardNominationID;
List<Award> AwdList = new List<Award>();
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdNomID
select Awd;
var AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDayThisYear && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
var AwardListRawD = (from A in AwdListRawC
join Emp in DContext.Employees on A.RecipientID equals Emp.EmployeeID
join D in DContext.Departments on Emp.DeptID equals D.DeptID
join G in DContext.Groups on Emp.GroupID equals G.GroupID
where A.AwardDate >= FirstDay && A.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID
select new { Emp.PreferredName, Emp.LastName, D.DeptName, G.GroupNum, Emp.EmployeeID }).Distinct();
dataGridView1.DataSource = AwardListRawD;
dataGridView1.Columns[0].HeaderText = "Preferred Name";
dataGridView1.Columns[1].HeaderText = "Last Name";
dataGridView1.Columns[2].HeaderText = "Department Name";
dataGridView1.Columns[3].HeaderText = "Group Number";
dataGridView1.Columns[4].HeaderText = "Employee ID";
dataGridView1.Columns[4].Visible = false;
}
}
private void StartDateBox_ValueChanged(object sender, EventArgs e)
{
}
private void EndDateBox_ValueChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
DateTime FirstDay = StartDateBox.Value;
DateTime LastDay = EndDateBox.Value;
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID(AwardTypeName );
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
List<Award> AwdList = new List<Award>();
foreach (Award Awd in AwdListRaw)
AwdList.Add(Awd);
frmReviewOnTheSpot OTSpot = new frmReviewOnTheSpot(AwardTypeName);
OTSpot.StartThing(AwdList);
LaunchForm(OTSpot);
}
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
frm.Location = this.Location;
this.Hide();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
WinnerButton.Enabled = dataGridView1.SelectedRows.Count == 1;
}
private void button6_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
Award Awd = new Award();
DataGridViewRow theRow = dataGridView1.SelectedRows[0];
string AwdRecID = theRow.Cells[4].Value.ToString();
LaunchForm(new frmNewAward("You Showed PRIDE", AwdRecID));
/*Awd.RecipientID = theRow.Cells[4].Value.ToString();
Awd.NominatorID = "EMP0000000";
Awd.AwardTypeID = DBCommands.GetAwardID(AwardTypeName );
Awd.AwardID = DBCommands.NextID("Award");
Awd.AwardDate = DateTime.Now;
DContext.Awards.InsertOnSubmit(Awd);
DContext.SubmitChanges();
MessageBox.Show(theRow.Cells[0].Value.ToString() + " " + theRow.Cells[1].Value.ToString() + " has been selected as a winner!");*/
button4_Click(sender, e);
}
}
private void ElibilityReportButton_Click(object sender, EventArgs e)
{
Group g = (Group)GroupNoBox.SelectedItem;
if (g == null) return;
MessageBox.Show(AwardTypeName);
LaunchForm(new frmEligibilityReport(AwardTypeName, StartDateBox.Value, EndDateBox.Value, g));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GUI_Design_Mockup
{
class classEligibilityReport
{
public string Nominee { get; set; }
public string NomineeDepartment { get; set; }
public string NominationType { get; set; }
public DateTime NominationDate { get; set; }
public string Nominator { get; set; }
public string NominationInfo { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
// NOTE: THIS CODE NOW COMPLETELY OBSOLETE. FUNCTIONALITY HANDLED BY frmYouShowedPRIDE
public partial class frmDinnerWithPRIDE : Form
{
List<Group> GroupList;
DataClasses1DataContext DContext;
public frmDinnerWithPRIDE()
{
InitializeComponent();
DContext = DBCommands.DContext;
}
private void frmDinnerWithPRIDE_Load(object sender, EventArgs e)
{
/*int C1;
for (C1 = 0; 2004 + C1 <= DateTime.Now.Year; C1++)
YearBox.Items.Add((2004 + C1).ToString());
YearBox.Text = DateTime.Now.Year.ToString();
QuarterBox.SelectedIndex = ((DateTime.Now.Month - 1) / 3);*/
InitializeGroupBox();
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
private void YearBox_SelectedValueChanged(object sender, EventArgs e)
{
Group grp = (Group)GroupNoBox.SelectedItem;
string GroupNum = "";
if (grp != null)
GroupNum = grp.GroupNum;
/*string Year = "", Quarter = "";
if (YearBox.SelectedItem != null)
Year = YearBox.SelectedItem.ToString();
if (QuarterBox.SelectedItem != null)
Quarter = QuarterBox.SelectedItem.ToString();*/
label7.Text = "Select winner(s) for Group " + GroupNum + " from " + StartDateBox.Value.ToShortDateString() + " to " + EndDateBox.Value.ToShortDateString() + ",\n\r then click the Winner button.";
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
GroupNoBox.SelectedIndex = 0;
}
private void button4_Click(object sender, EventArgs e)
{
//int QuarterValue = QuarterBox.SelectedIndex;
//int YearValue = int.Parse(YearBox.SelectedItem.ToString());
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, 3 * QuarterValue + 1, 1);
DateTime FirstDayThisYear = new DateTime(DateTime.Now.Year, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, 3 + 3 * QuarterValue, DateTime.DaysInMonth(YearValue, 3 + 3 * QuarterValue));
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID("Dinner With PRIDE");
string AwdNomID = DBCommands.GetTypeOfAward(AwdID).AwardNominationID;
List<Award> AwdList = new List<Award>();
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdNomID
select Awd;
var AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDayThisYear && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
var AwdListRawD = (from A in AwdListRawC
join Emp in DContext.Employees on A.RecipientID equals Emp.EmployeeID
join D in DContext.Departments on Emp.DeptID equals D.DeptID
join G in DContext.Groups on Emp.GroupID equals G.GroupID
where A.AwardDate >= FirstDay && A.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID
select new { Emp.PreferredName, Emp.LastName, D.DeptName, G.GroupNum }).Distinct();
dataGridView1.DataSource = AwdListRawD;
dataGridView1.Columns[0].HeaderText = "Preferred Name";
dataGridView1.Columns[1].HeaderText = "Last Name";
dataGridView1.Columns[2].HeaderText = "Department Name";
dataGridView1.Columns[3].HeaderText = "Group Number";
}
}
private void StartDateBox_ValueChanged(object sender, EventArgs e)
{
if (StartDateBox.Value > EndDateBox.Value)
EndDateBox.Value = StartDateBox.Value;
}
private void EndDateBox_ValueChanged(object sender, EventArgs e)
{
if (EndDateBox.Value < StartDateBox.Value)
StartDateBox.Value = EndDateBox.Value;
}
private void button3_Click(object sender, EventArgs e)
{
DateTime FirstDay = StartDateBox.Value;
DateTime LastDay = EndDateBox.Value;
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID("Dinner With PRIDE");
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
List<Award> AwdList = new List<Award>();
foreach (Award Awd in AwdListRaw)
AwdList.Add(Awd);
frmReviewOnTheSpot OTSpot = new frmReviewOnTheSpot("Dinner With PRIDE");
OTSpot.StartThing(AwdList);
LaunchForm(OTSpot);
}
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
frm.Location = this.Location;
this.Hide();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmEmployees : Form
{
List<Group> GroupList;
List<Employee> EmpList;
DataClasses1DataContext DContext;
public frmEmployees()
{
DContext = DBCommands.DContext;
InitializeComponent();
InitializeEmpBox();
InitializeGroupBox();
}
private void button2_Click(object sender, EventArgs e)
{
frmUpdateEmployees frm = new frmUpdateEmployees();
frm.StartThing(DBCommands.GetNewEmployeesList());
LaunchForm(frm);
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
Cursor OldCurs = this.Cursor;
this.Cursor = Cursors.WaitCursor;
DBCommands.LoadNewEmployees();
this.Cursor = OldCurs;
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
Group AllGroup;
AllGroup = new Group();
AllGroup.GroupID = "GRP0000000";
AllGroup.GroupNum = "All Groups";
AllGroup.DayOfPride = 'X';
GroupList.Add(AllGroup);
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
}
private void InitializeEmpBox()
{
var EmpListRaw = from E in DBCommands.DContext.Employees
orderby E.LastName ascending
select E;
EmpList = new List<Employee>();
Employee AllEmployee;
AllEmployee = new Employee();
AllEmployee.EmployeeID = "EMP-000001";
EmpList.Add(AllEmployee);
foreach (Employee E in EmpListRaw)
{
EmpList.Add(E);
}
EmpBox.DataSource = EmpList;
}
private void button5_Click(object sender, EventArgs e)
{
var NewEmpListRaw = from E in DContext.Employees
select E;
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null && Grp.GroupID != "GRP0000000")
{
var NewEmpListRawB = from E in NewEmpListRaw
where E.GroupID == Grp.GroupID
select E;
NewEmpListRaw = NewEmpListRawB;
}
if (!checkBox1.Checked)
{
var NewEmpListRawB = from E in NewEmpListRaw
where E.Active == true // Yes, that's necessary. Not quite sure why, but it is
select E;
NewEmpListRaw = NewEmpListRawB;
}
List<Employee> NewEmpList = new List<Employee>();
foreach (Employee E in NewEmpListRaw)
NewEmpList.Add(E);
frmUpdateEmployees frm = new frmUpdateEmployees();
frm.StartThing(NewEmpList);
LaunchForm(frm);
}
private void button4_Click(object sender, EventArgs e)
{
Employee SelectedEmp = (Employee)EmpBox.SelectedItem;
if (SelectedEmp != null && SelectedEmp.EmployeeID != "EMP-000001")
{
List<Employee> ShortList = new List<Employee>();
ShortList.Add(SelectedEmp);
frmUpdateEmployees frm = new frmUpdateEmployees();
frm.StartThing(ShortList);
LaunchForm(frm);
}
}
private void EmpBox_SelectedValueChanged(object sender, EventArgs e)
{
if (EmpBox.SelectedItem != null)
{
Employee SelectedEmp = (Employee)EmpBox.SelectedItem;
button4.Enabled = SelectedEmp.EmployeeID != "EMP-000001";
}
else
button4.Enabled = false;
}
private void button6_Click(object sender, EventArgs e)
{
List<Employee> TempEmpList = DBCommands.BuildEmployeeListFromExcel();
var FullEmpListRaw = from E in DContext.Employees
select E;
List<Employee> FullEmpList = new List<Employee>();
foreach (Employee E in FullEmpListRaw)
FullEmpList.Add(E);
List<Employee> InactiveEmployeeList = new List<Employee>();
foreach (Employee E in FullEmpList)
{
if (E.MiddleInitial != null)
if (TempEmpList.Count(p => p.FirstName == E.FirstName && p.LastName == E.LastName && p.MiddleInitial == E.MiddleInitial) == 0)
if (E.Active !=null && (bool)E.Active)
InactiveEmployeeList.Add(E);
else
if (TempEmpList.Count(p => p.FirstName == E.FirstName && p.LastName == E.LastName) == 0)
if (E.Active != null && (bool)E.Active)
InactiveEmployeeList.Add(E);
}
foreach (Employee E in InactiveEmployeeList)
DBCommands.DeactivateEmployee(E);
}
private void button3_Click(object sender, EventArgs e)
{
LaunchForm(new frmUpdateFromExcel());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmUpdateFromAccess : Form
{
DataClasses1DataContext DContext;
DataTable AwardDataTable, EmployeeDataTable, EmployeeAwardDataTable, GroupDataTable;
public frmUpdateFromAccess()
{
InitializeComponent();
DContext = DBCommands.DContext;
AwardDataTable = pRIDE_beDataSet.TypeOfAward;
EmployeeDataTable = pRIDE_beDataSet.Employee;
EmployeeAwardDataTable = pRIDE_beDataSet.EmployeeAward;
GroupDataTable = pRIDE_beDataSet.Groups;
}
private void frmUpdateFromAccess_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'pRIDE_beDataSet.TypeOfAward' table. You can move, or remove it, as needed.
this.typeOfAwardTableAdapter.Fill(this.pRIDE_beDataSet.TypeOfAward);
// TODO: This line of code loads data into the 'pRIDE_beDataSet.Groups' table. You can move, or remove it, as needed.
this.groupsTableAdapter.Fill(this.pRIDE_beDataSet.Groups);
// TODO: This line of code loads data into the 'pRIDE_beDataSet.EmployeeAward' table. You can move, or remove it, as needed.
this.employeeAwardTableAdapter.Fill(this.pRIDE_beDataSet.EmployeeAward);
// TODO: This line of code loads data into the 'pRIDE_beDataSet.Employee' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.pRIDE_beDataSet.Employee);
}
private void button1_Click(object sender, EventArgs e)
{
ImportIDs();
ImportGroups();
ImportAwardTypes();
//LoadAllEmployees();
//LoadAllAwards();
MessageBox.Show("Done doing whatever this button does today!");
}
private void button2_Click(object sender, EventArgs e)
{
LoadAllDeptNames();
LoadAllEmployees();
LoadAllAwards();
//LoadAllDeptNames();
MessageBox.Show("Done doing whatever this button does today!");
}
private void button3_Click(object sender, EventArgs e)
{
//LoadAllEmployees();
ExtractAllNextIDs();
ExtractAllGroups();
ExtractAllAwardTypes();
MessageBox.Show("Done doing whatever this button does today!");
}
private void ImportIDs()
{
string Temp;
NextID ID;
List<NextID> NIds = new List<NextID>();
string[] Pieces;
System.IO.StreamReader SRead = new System.IO.StreamReader("IDTypes.txt");
while (!SRead.EndOfStream)
{
Temp = SRead.ReadLine();
ID = new NextID();
Pieces = Temp.Split(',');
if (Pieces.Length == 3)
{
ID.TableName = Pieces[0];
ID.NextNum = int.Parse(Pieces[1]);
ID.Prefix = Pieces[2];
NIds.Add(ID);
}
}
foreach (NextID NID in NIds)
{
DContext.NextIDs.InsertOnSubmit(NID);
}
DContext.SubmitChanges();
}
private void ImportGroups()
{
string Temp;
Group G;
List<Group> Groups = new List<Group>();
string[] Pieces;
System.IO.StreamReader SRead = new System.IO.StreamReader("Groups.txt");
while (!SRead.EndOfStream)
{
Temp = SRead.ReadLine();
G = new Group();
Pieces = Temp.Split(',');
if (Pieces.Length == 3)
{
G.GroupID= Pieces[0];
G.GroupNum = Pieces[1];
G.DayOfPride = Pieces[2][0];
Groups.Add(G);
}
}
foreach (Group Gr in Groups)
{
DContext.Groups.InsertOnSubmit(Gr);
}
DContext.SubmitChanges();
}
private void ImportAwardTypes()
{
string Temp;
Type_Of_Award TOA;
List<Type_Of_Award > TOAs= new List<Type_Of_Award>();
string[] Pieces;
System.IO.StreamReader SRead = new System.IO.StreamReader("AwardTypes.txt");
while (!SRead.EndOfStream)
{
Temp = SRead.ReadLine();
TOA = new Type_Of_Award();
Pieces = Temp.Split(',');
if (Pieces.Length == 5)
{
TOA.AwardTypeID = Pieces[0];
TOA.AwardTypeName= Pieces[1];
TOA.IsNomination = bool.Parse(Pieces[2]);
TOA.Frequency = Pieces[3];
TOA.AwardNominationID = Pieces[4];
TOAs.Add(TOA);
}
}
foreach (Type_Of_Award A in TOAs)
{
DContext.Type_Of_Awards.InsertOnSubmit(A);
}
DContext.SubmitChanges();
}
private void ExtractAllNextIDs()
{
var IDs = from ID in DContext.NextIDs
select ID;
System.IO.StreamWriter SWrite = new System.IO.StreamWriter("IDTypes.txt");
foreach (NextID ID in IDs)
{
SWrite.WriteLine(ID.TableName+","+ID.NextNum.ToString()+","+ID.Prefix );
}
SWrite.Close();
}
private void ExtractAllAwardTypes()
{
//NOTE: Do not use, built for pulling data to give to Scott
var Stuff = from TOA in DContext.Type_Of_Awards
select TOA;
System.IO.StreamWriter SWrite = new System.IO.StreamWriter("AwardTypes.txt");
foreach (Type_Of_Award TOA in Stuff)
{
SWrite.WriteLine(TOA.AwardTypeID + "," + TOA.AwardTypeName + "," + TOA.IsNomination.ToString() + "," + TOA.Frequency.ToArray() + "," + TOA.AwardNominationID);
}
SWrite.Close();
}
private void ExtractAllGroups()
{
//NOTE: Do not use, built for pulling data to give to Scott
var Stuff = from TOA in DContext.Groups
select TOA;
System.IO.StreamWriter SWrite = new System.IO.StreamWriter("Groups.txt");
foreach (Group G in Stuff)
{
SWrite.WriteLine(G.GroupID+","+G.GroupNum+","+G.DayOfPride.ToString());
}
SWrite.Close();
}
private List<DataRow> GetAwards(string AwType)
{
var NominationRowsRaw = from N in AwardDataTable.AsEnumerable()
where N.Field<string>(2).Equals(AwType, StringComparison.CurrentCultureIgnoreCase)
select N;
List<DataRow> NominationRows = new List<DataRow>();
foreach (DataRow DR in NominationRowsRaw)
NominationRows.Add(DR);
return NominationRows;
}
private void LoadAllNominationTypes()
{
List<DataRow> NominationRows = GetAwards("Nomination");
int C1;//, NextNum;
Type_Of_Award ToA;
List<Type_Of_Award> ToAList = new List<Type_Of_Award>();
for (C1 = 0; C1 < NominationRows.Count; C1++)
{
ToA = new Type_Of_Award();
ToA.AwardTypeID = DBCommands.NextID("Type_Of_Award");
ToA.AwardTypeName = NominationRows[C1][0].ToString();
if (DBCommands.GetAwardID(ToA.AwardTypeName).Equals(""))
{
ToA.IsNomination = true;
ToA.Frequency = NominationRows[C1][3].ToString();
ToAList.Add(ToA);
}
}
foreach (Type_Of_Award TA in ToAList)
{
DContext.Type_Of_Awards.InsertOnSubmit(TA);
}
try
{
MessageBox.Show(DContext.GetChangeSet().Updates.Count.ToString());
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
private void LoadAllAwardTypes()
{
List<DataRow> NominationRows = GetAwards("Award");
int C1;
Type_Of_Award ToA;
List<Type_Of_Award> ToAList = new List<Type_Of_Award>();
for (C1 = 0; C1 < NominationRows.Count; C1++)
{
ToA = new Type_Of_Award();
ToA.AwardTypeID = DBCommands.NextID("Type_Of_Award");
ToA.AwardTypeName = NominationRows[C1][0].ToString();
if (DBCommands.GetAwardID(ToA.AwardTypeName).Equals(""))
{
ToA.IsNomination = false;
ToA.Frequency = NominationRows[C1][3].ToString();
ToA.AwardNominationID = DBCommands.GetAwardID(NominationRows[C1][4].ToString());
ToAList.Add(ToA);
}
}
foreach (Type_Of_Award TA in ToAList)
{
DContext.Type_Of_Awards.InsertOnSubmit(TA);
}
try
{
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
private void LoadAllDeptNames()
{
var StringListRaw = (from S in EmployeeDataTable.AsEnumerable()
where S.Field<string>(8)!=null
select S.Field<string>(8).ToUpper()).Distinct<string>();
List<String> StringList = new List<String>();
List<Department> DeptList = new List<Department>();
Department dept = new Department();
foreach (string S in StringListRaw)
{
StringList.Add(S);
dept = new Department();
if (DBCommands.GetDeptID(S) == "")
{
dept.DeptName = S;
dept.DeptID = DBCommands.NextID("Department");
DeptList.Add(dept);
}
}
foreach (Department D in DeptList)
DContext.Departments.InsertOnSubmit(D);
try
{
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
private void LoadAllDeptNamesB()
{
var StringListRaw = (from S in EmployeeAwardDataTable.AsEnumerable()
where S.Field<string>(15) != null
select S.Field<string>(15).ToUpper()).Distinct<string>();
List<String> StringList = new List<String>();
List<Department> DeptList = new List<Department>();
Department dept = new Department();
foreach (string S in StringListRaw)
{
StringList.Add(S);
dept = new Department();
if (DBCommands.GetDeptID(S) == "")
{
dept.DeptName = S;
dept.DeptID= DBCommands.NextID("Department");
DeptList.Add(dept);
}
}
foreach (Department D in DeptList)
DContext.Departments.InsertOnSubmit(D);
try
{
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
private void LoadAllEmployees()
{
int C1;
List<Employee> EmployeeList = new List<Employee>();
Employee TempEmp;
int NextNum;
DataRow DR;
for (C1 = 0; C1 < EmployeeDataTable.Rows.Count; C1++)
{
DR = EmployeeDataTable.Rows[C1];
TempEmp = new Employee();
NextNum = (int)DR[0];
TempEmp.EmployeeID = "EMP" + NextNum.ToString("0000000");
TempEmp.FirstName = DR[1].ToString();
TempEmp.LastName = DR[2].ToString();
if (DR[3].ToString().Length > 0)
TempEmp.MiddleInitial = DR[3].ToString()[0];
TempEmp.Title = DR[4].ToString();
TempEmp.GroupID = DBCommands.GetGroupID(DR[5].ToString());
if (DR[6].ToString().Length > 0)
TempEmp.HR_FTE = double.Parse(DR[6].ToString());
TempEmp.IsDirector = DR[7].ToString().Equals("x", StringComparison.CurrentCultureIgnoreCase);
TempEmp.DeptID = DBCommands.GetDeptID(DR[8].ToString());
if (DR[9].ToString().Length > 0)
TempEmp.HireDate = DateTime.Parse(DR[9].ToString());
TempEmp.HR_Status = DR[10].ToString();
TempEmp.EmployeeStatusCode = DR[11].ToString();
TempEmp.PreferredName = DR[12].ToString();
TempEmp.Active = (bool)DR[13];
TempEmp.PrideEligible = (bool)DR[14];
if (DR[15].ToString().Length > 0)
TempEmp.OldAwardCount = (int)(double)DR[15];
TempEmp.DeptRecord = (bool)DR[16];
TempEmp.DateLastUpdated = DateTime.Today;
if (DBCommands.GetEmployeeID(TempEmp.PreferredName, TempEmp.LastName).Equals(""))
EmployeeList.Add(TempEmp);
}
foreach (Employee Emp in EmployeeList)
DContext.Employees.InsertOnSubmit(Emp);
try
{
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
private void LoadAllAwards()
{
int C1;
List<Award> AwardList = new List<Award>();
Award TempAwd;
int NextNum;
DataRow DR;
for (C1 = 0; C1 < EmployeeAwardDataTable.Rows.Count; C1++)
{
DR = EmployeeAwardDataTable.Rows[C1];
TempAwd = new Award();
NextNum = (int)DR[0];
TempAwd.AwardID = "AWD" + NextNum.ToString("0000000");
if (!DBCommands.GetAwardExists(TempAwd.AwardID))
{
TempAwd.AwardDate = (DateTime)DR[1];
TempAwd.AwardTypeID = DBCommands.GetAwardID(DR[2].ToString());
NextNum = (int)DR[3];
TempAwd.RecipientID = "EMP" + NextNum.ToString("0000000");
NextNum = (int)DR[8];
TempAwd.NominatorID = "EMP" + NextNum.ToString("0000000");
TempAwd.Notes = DR[13].ToString();
AwardList.Add(TempAwd);
}
}
foreach (Award Awd in AwardList)
DContext.Awards.InsertOnSubmit(Awd);
try
{
MessageBox.Show(DContext.GetChangeSet().Inserts.Count.ToString());
DContext.SubmitChanges();
}
catch (Exception E)
{
MessageBox.Show(E.Message);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmUpdateFromExcel : Form
{
List<Employee[]> EmpPairs;
int SelectedIndex;
public frmUpdateFromExcel()
{
InitializeComponent();
}
private void frmUpdateFromExcel_Load(object sender, EventArgs e)
{
List<Employee> EmpList = DBCommands.BuildEmployeeListFromExcel();
EmpPairs = new List<Employee[]>();
int C1;
for (C1 = 0; C1 < EmpList.Count; C1++)
{
Employee OldEmp;
if (DBCommands.EmployeeNeedsUpdating(EmpList[C1], out OldEmp))
{
EmpPairs.Add(new Employee[2] { OldEmp,EmpList[C1]});
}
}
hScrollBar1.Maximum = EmpPairs.Count + (hScrollBar1.LargeChange - 1);
hScrollBar1.Minimum = 1;
XofYLabel.Text = hScrollBar1.Value.ToString() + " of " + EmpPairs.Count.ToString();
SelectedIndex = -1;
if (EmpPairs.Count > 0)
UpdateDataFromEmpPair(0);
}
private void label8_Click(object sender, EventArgs e)
{
}
public void UpdateDataFromEmpPair(int Index)
{
UpdateDataFromEmpPair(EmpPairs[Index]);
SelectedIndex = Index;
}
public void UpdateDataFromEmpPair(Employee[] EmpPair)
{
IDBox.Text = EmpPair[0].EmployeeID;
NameBox.Text = EmpPair[0].ToString();
string DeptName1 = DBCommands.GetDepartment(EmpPair[0].DeptID).DeptName;
string DeptName2 = DBCommands.GetDepartment(EmpPair[1].DeptID).DeptName;
DeptBoxOld.Text = DeptName1;
DeptBoxNew.Text = DeptName2;
TitleBoxOld.Text = EmpPair[0].Title;
TitleBoxNew.Text = EmpPair[1].Title;
FTEBoxOld.Text = EmpPair[0].HR_FTE.ToString();
FTEBoxNew.Value = (decimal)EmpPair[1].HR_FTE;
StatusBoxOld.Text = EmpPair[0].HR_Status;
StatusBoxNew.Text = EmpPair[1].HR_Status;
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
if (SelectedIndex >= 0)
{
EmpPairs[SelectedIndex][1].Title = TitleBoxNew.Text;
EmpPairs[SelectedIndex][1].HR_FTE = (double)FTEBoxNew.Value;
EmpPairs[SelectedIndex][1].HR_Status = StatusBoxNew.Text;
}
XofYLabel.Text = hScrollBar1.Value.ToString() + " of " + EmpPairs.Count.ToString();
UpdateDataFromEmpPair(hScrollBar1.Value-1);
}
private void button1_Click(object sender, EventArgs e)
{
int C1;
for (C1 = 0; C1 < EmpPairs.Count; C1++)
{
if (EmpPairs[C1][0].DeptID != EmpPairs[C1][1].DeptID||EmpPairs[C1][0].Title!=EmpPairs[C1][1].Title)
{
EmpPairs[C1][0].GroupID = "";
}
EmpPairs[C1][0].DeptID = EmpPairs[C1][1].DeptID;
EmpPairs[C1][0].Title = EmpPairs[C1][1].Title;
EmpPairs[C1][0].HR_FTE = EmpPairs[C1][1].HR_FTE;
EmpPairs[C1][0].HR_Status = EmpPairs[C1][1].HR_Status;
DBCommands.SaveEmployeeB(EmpPairs[C1][0]);
}
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmNewAward : Form
{
DataClasses1DataContext DContext;
List<ComboBox> CBoxes;
ComboBox RecipientBox;
bool IsNomination;
public frmNewAward(string AwardName = "On The Spot", string EmployeeID = "")
{
InitializeComponent();
DContext = DBCommands.DContext;
InitializeEmpBox();
InitializeTypeOfAwardBox(AwardName);
Text = "New " + AwardName + " Award";
label1.Text = AwardName + " Award";
button2.Text = "Save " + AwardName +" Award";
CBoxes = new List<ComboBox>();
RecipientBox = BuildNextNomineeBox();
RecipientBox.SelectedIndexChanged += RecipientBox_SelectedIndexChanged;
CBoxes.Add(RecipientBox);
int C1;
if (EmployeeID != "")
{
for (C1 = 0; C1 < RecipientBox.Items.Count;C1++ )
{
if (((Employee)RecipientBox.Items[C1]).EmployeeID == EmployeeID)
RecipientBox.SelectedIndex = C1;
}
}
IsNomination = AwardName.Contains("Nomination") || AwardName.Equals("On The Spot", StringComparison.CurrentCultureIgnoreCase);
if (!IsNomination )
{
AwdTypeBox.Visible = true;
AwdTypeBox.Text = AwardName;
AwdTypeBox.Enabled = false;
comboBox1.Visible = false;
}
if(!AwardName.Equals("On The Spot", StringComparison.CurrentCultureIgnoreCase))
{
AddButton.Visible=false;
RemoveButton.Visible=false;
NewHireButton.Visible = false;
}
/*if (!AwardName.Equals("On The Spot", StringComparison.CurrentCultureIgnoreCase))
{
button3.Visible = false;
button1.Visible = false;
label7.Visible = false;
button2.Text = "Submit " + AwardName;
comboBox1.Location = new Point(251,137);
comboBox1.Size = new Size(187, 21);
}*/
}
private ComboBox BuildNextNomineeBox()
{
ComboBox CBox = new ComboBox();
CBox.DataSource = DBCommands.GetAllEmployeeList(true,true);
CBox.Size = new Size(278, 21);
CBox.Location = new Point(160, 55 + (27 * CBoxes.Count));
CBox.FormattingEnabled = true;
CBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
CBox.AutoCompleteSource = AutoCompleteSource.ListItems;
this.Controls.Add(CBox);
return CBox;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void InitializeEmpBox()
{
NominatorBox.DataSource = DBCommands.GetAllEmployeeList(true);
}
private void InitializeTypeOfAwardBox(string DefaultAwardType)
{
Type_Of_Award temp;
comboBox1.DataSource = DBCommands.GetAllTypeOfAwardList(DefaultAwardType, out temp);
if (temp != null)
comboBox1.SelectedIndex = ((List<Type_Of_Award>)comboBox1.DataSource).IndexOf(temp);
}
private void RecipientBox_SelectedIndexChanged(object sender, EventArgs e)
{
Employee SelectedEmployee = (Employee)RecipientBox.Items[RecipientBox.SelectedIndex];
if (SelectedEmployee != null && !SelectedEmployee.EmployeeID.Equals("EMP-000001"))
{
Department tempDept = DBCommands.GetDepartment(SelectedEmployee.DeptID);
if (tempDept != null)
DepartmentBox.Text = tempDept.DeptName;
else
DepartmentBox.Text = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
Award NewAward = new Award();
NewAward.AwardID = DBCommands.NextID("Award");
Employee EmpA, EmpB;
bool Flag = false;
if (CBoxes.Count == 1)
{
EmpA = (Employee)NominatorBox.SelectedItem;
EmpB = (Employee)RecipientBox.SelectedItem;
if (EmpA.EmployeeID != "EMP-000001" && EmpB.EmployeeID != "EMP-000001")
{
NewAward.NominatorID = EmpA.EmployeeID;
NewAward.RecipientID = EmpB.EmployeeID;
NewAward.Notes = NoteBox.Text;
NewAward.AwardDate = dateTimePicker1.Value;
if(IsNomination)
NewAward.AwardTypeID = ((Type_Of_Award)comboBox1.SelectedItem).AwardTypeID;
else
NewAward.AwardTypeID = DBCommands.GetAwardID(AwdTypeBox.Text);
DContext.Awards.InsertOnSubmit(NewAward);
Flag = true;
DContext.SubmitChanges();
this.Close();
}
else
{
MessageBox.Show("You must select both a nominator and a recipient for the award");
}
}
else
{
List<Employee> SelectedEmployees = new List<Employee>();
int C1;
for (C1 = 0; C1 < CBoxes.Count; C1++)
{
EmpA = (Employee)CBoxes[C1].SelectedItem;
if (EmpA.EmployeeID != "EMP-000001" && !SelectedEmployees.Contains(EmpA))
{
SelectedEmployees.Add(EmpA);
}
}
EmpB = (Employee)RecipientBox.SelectedItem;
if (SelectedEmployees.Count > 0 && EmpB.EmployeeID != "EMP-000001")
{
Award TempAwd;
string AwdNotes = NoteBox.Text;
string AwdTypeID = ((Type_Of_Award)comboBox1.SelectedItem).AwardTypeID;
string NominatorID = EmpB.EmployeeID;
DateTime AwdDate = dateTimePicker1.Value;
string[] EmpIDlist = new string[SelectedEmployees.Count];
for (C1 = 0; C1 < SelectedEmployees.Count; C1++)
{
EmpIDlist[C1] = SelectedEmployees[C1].EmployeeID;
TempAwd = new Award();
TempAwd.AwardDate = AwdDate;
TempAwd.AwardTypeID = AwdTypeID;
TempAwd.Notes = AwdNotes;
TempAwd.AwardID = DBCommands.NextID("Award");
TempAwd.RecipientID = SelectedEmployees[C1].EmployeeID;
TempAwd.NominatorID = NominatorID;
DContext.Awards.InsertOnSubmit(TempAwd);
}
string TeamID = DBCommands.BuildTeam(EmpIDlist);
NewAward.RecipientID = TeamID;
NewAward.NominatorID = NominatorID;
NewAward.Notes = AwdNotes;
NewAward.AwardDate = AwdDate ;
NewAward.AwardTypeID = AwdTypeID ;
DContext.Awards.InsertOnSubmit(NewAward);
Flag = true;
DContext.SubmitChanges();
this.Close();
}
else
MessageBox.Show("You must select a nominator and at least one recipient for the award");
}
if (Flag)
{
string FileLoc = Application.StartupPath+ @"\Blank Award Template.dotx";
DBCommands.BuildAwardPrintout(FileLoc, NewAward);
}
}
private void button3_Click(object sender, EventArgs e)
{
Award NewAward = new Award();
NewAward.AwardID = DBCommands.NextID("Award");
Employee EmpA, EmpB;
EmpA = (Employee)NominatorBox.SelectedItem;
EmpB = (Employee)RecipientBox.SelectedItem;
if (EmpA.EmployeeID != "DPT-000001" && EmpB.EmployeeID != "DPT-000001")
{
NewAward.NominatorID = EmpA.EmployeeID;
NewAward.RecipientID = EmpB.EmployeeID;
NewAward.Notes = NoteBox.Text;
NewAward.AwardDate = dateTimePicker1.Value;
NewAward.AwardTypeID = "TOA0000029";
DContext.Awards.InsertOnSubmit(NewAward);
DContext.SubmitChanges();
RecipientBox.Text = "";
MessageBox.Show("Award added.");
}
else
{
MessageBox.Show("You must select both a nominator and a recipient for the award");
}
}
private void frmNewAward_Load(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void AddButton_Click(object sender, EventArgs e)
{
if (CBoxes.Count == 1)
{
DepartmentBox.Visible = false;
label3.Visible = false;
RemoveButton.Enabled = true;
}
else
this.Size = new Size(this.Size.Width, this.Size.Height + 27);
CBoxes.Add(BuildNextNomineeBox());
if (CBoxes.Count >= DBCommands.MaxTeamCount)
AddButton.Enabled = false;
}
private void RemoveButton_Click(object sender, EventArgs e)
{
ComboBox LastBox = CBoxes.Last<ComboBox>();
this.Controls.Remove(LastBox);
CBoxes.Remove(LastBox);
if (CBoxes.Count == 1)
{
RemoveButton.Enabled = false;
DepartmentBox.Visible = true;
label3.Visible = true;
}
else
this.Size = new Size(this.Size.Width, this.Size.Height - 27);
if (CBoxes.Count < DBCommands.MaxTeamCount)
AddButton.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
NoteBox.Text = "Welcome to the City of Allen! We wanted to be one of the first to give you an On the Spot Award! We hope that your career here will be fulfilling, and that you receive many On the Spot Awards in the future!";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmDayOfPRIDE : Form
{
List<Group> GroupList;
DataClasses1DataContext DContext;
string AwardName = "Day of Pride";
public frmDayOfPRIDE()
{
InitializeComponent();
DContext = DBCommands.DContext;
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmDayOfPRIDE_Load(object sender, EventArgs e)
{
/*int C1;
for (C1 = 0; 2004 + C1 <= DateTime.Now.Year; C1++)
YearBox.Items.Add((2004 + C1).ToString());
YearBox.Text = DateTime.Now.Year.ToString();
HalfBox.SelectedIndex = ((DateTime.Now.Month - 1) / 6);*/
InitializeGroupBox();
}
private void InitializeGroupBox()
{
var GroupListRaw = from G in DBCommands.DContext.Groups
orderby G.GroupID ascending
select G;
GroupList = new List<Group>();
Group AllGroup;
AllGroup = new Group();
AllGroup.GroupID = "GRP0000000";
AllGroup.GroupNum = "All Groups";
AllGroup.DayOfPride = 'X';
GroupList.Add(AllGroup);
foreach (Group G in GroupListRaw)
{
GroupList.Add(G);
}
GroupNoBox.DataSource = GroupList;
GroupNoBox.SelectedIndex = 0;
}
private void GroupNoBox_SelectedValueChanged(object sender, EventArgs e)
{
Group grp = (Group)GroupNoBox.SelectedItem;
string GroupNum = "";
if (grp != null)
GroupNum = grp.GroupNum;
/*string Year = "", Half = "";
if (YearBox.SelectedItem != null)
Year = YearBox.SelectedItem.ToString();
if (HalfBox.SelectedItem != null)
Half = HalfBox.SelectedItem.ToString();*/
if(GroupNum=="GRP0000000")
label7.Text = "Select winner(s) for " + GroupNum;
else
label7.Text = "Select winner(s) for Group " + GroupNum;
label7.Text+=" from " + StartDateBox.Value.ToShortDateString() + " to " + EndDateBox.Value.ToShortDateString() + ",\n\r then click the Winner button.";
}
private void button9_Click(object sender, EventArgs e)
{
LaunchForm(new frmNewAward("Day of PRIDE Nomination"));
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
this.Hide();
}
private void button4_Click(object sender, EventArgs e)
{
//int HalfValue = HalfBox.SelectedIndex;
//int YearValue = int.Parse(YearBox.SelectedItem.ToString());
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, 6 * HalfValue + 1, 1);
DateTime FirstDayThisYear = new DateTime(DateTime.Now.Year, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, 6 + 6 * HalfValue, DateTime.DaysInMonth(YearValue, 6 + 6 * HalfValue));
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID("Day of PRIDE");
string AwdNomID = DBCommands.GetTypeOfAward(AwdID).AwardNominationID;
List<Award> AwdList = new List<Award>();
IQueryable<Award> AwdListRaw;
IQueryable<Award> AwdListRawB;
if (!Grp.GroupID.Equals("GRP0000000"))
{
AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdNomID
select Awd;
AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDayThisYear && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
}
else
{
AwdListRaw = from Awd in DContext.Awards
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdNomID
select Awd;
AwdListRawB = from Awd in DContext.Awards
where Awd.AwardDate >= FirstDayThisYear && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdID
select Awd;
}
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
var AwdListRawD = (from A in AwdListRawC
join Emp in DContext.Employees on A.RecipientID equals Emp.EmployeeID
join D in DContext.Departments on Emp.DeptID equals D.DeptID
join G in DContext.Groups on Emp.GroupID equals G.GroupID
where A.AwardDate >= FirstDay && A.AwardDate <= LastDay
select new { Emp.PreferredName, Emp.LastName, D.DeptName, G.GroupNum, Emp.EmployeeID }).Distinct();
dataGridView1.DataSource = AwdListRawD;
dataGridView1.Columns[0].HeaderText = "Preferred Name";
dataGridView1.Columns[1].HeaderText = "Last Name";
dataGridView1.Columns[2].HeaderText = "Department Name";
dataGridView1.Columns[3].HeaderText = "Group Number";
dataGridView1.Columns[4].Visible = false;
}
}
private void StartDateBox_ValueChanged(object sender, EventArgs e)
{
}
private void EndDateBox_ValueChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
DateTime FirstDay = StartDateBox.Value;
DateTime LastDay = EndDateBox.Value;
Group Grp = (Group)GroupNoBox.SelectedItem;
if (Grp != null)
{
string AwdID = DBCommands.GetAwardID("Day of PRIDE");
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Emp.GroupID == Grp.GroupID && Awd.AwardTypeID == AwdID
select Awd;
List<Award> AwdList = new List<Award>();
foreach (Award Awd in AwdListRaw)
AwdList.Add(Awd);
frmReviewOnTheSpot OTSpot = new frmReviewOnTheSpot("Day of PRIDE");
OTSpot.StartThing(AwdList);
LaunchForm(OTSpot);
}
}
private void button10_Click(object sender, EventArgs e)
{
Type_Of_Award SelectedAwd = (Type_Of_Award)DBCommands.GetTypeOfAward(DBCommands.GetAwardID("Day of PRIDE Nomination"));
//int YearValue = int.Parse(YearBox.SelectedItem.ToString());
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, 12, DateTime.DaysInMonth(YearValue, 12));
if (SelectedAwd != null)
{
string AwdID = DBCommands.GetAwardFromNomination(SelectedAwd.AwardTypeID).AwardTypeID;
string AwdNomID = SelectedAwd.AwardTypeID;
List<Award> AwdList = new List<Award>();
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdNomID
select Awd;
var AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdID
select Awd;
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
foreach (Award A in AwdListRawC)
AwdList.Add(A);
frmReviewOnTheSpot frm = new frmReviewOnTheSpot(SelectedAwd.AwardTypeName);
frm.StartThing(AwdList);
LaunchForm(frm);
}
}
private void button6_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
DataGridViewRow theRow = dataGridView1.SelectedRows[0];
string AwdRecID = theRow.Cells[4].Value.ToString();
LaunchForm(new frmNewAward("Day of PRIDE", AwdRecID));
/*Award Awd = new Award();
DataGridViewRow theRow = dataGridView1.SelectedRows[0];
Awd.RecipientID = theRow.Cells[4].Value.ToString();
Awd.NominatorID = "EMP0000000";
Awd.AwardTypeID = DBCommands.GetAwardID("Day Of PRIDE");
Awd.AwardID = DBCommands.NextID("Award");
Awd.AwardDate = DateTime.Now;
DContext.Awards.InsertOnSubmit(Awd);
DContext.SubmitChanges();
MessageBox.Show(theRow.Cells[0].Value.ToString() + " " + theRow.Cells[1].Value.ToString() + " has been selected as a winner!");*/
button4_Click(sender, e);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
WinnerButton.Enabled = (dataGridView1.SelectedRows.Count == 1);
}
private void button1_Click(object sender, EventArgs e)
{
Group g = (Group)GroupNoBox.SelectedItem;
if (g == null) return;
LaunchForm(new frmEligibilityReport("Day of PRIDE", StartDateBox.Value, EndDateBox.Value, g));
}
private void GroupNoBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmAwardsSummaryReport : Form
{
List<Type_Of_Award> AwardTypes;
DateTime StartDate, EndDate;
String GroupID, Department, Recipient, Nominator, AwardType;
public frmAwardsSummaryReport(DateTime Start, DateTime End, String GroupID, String Department, String Recipient, String Nominator, String AwardType)
{
InitializeComponent();
StartDate = Start;
EndDate = End;
this.GroupID = GroupID;
this.Department = Department;
this.Recipient = Recipient;
this.Nominator = Nominator;
this.AwardType = AwardType;
DataClasses1DataContext dc = DBCommands.DContext;
AwardTypes = new List<Type_Of_Award>();
if (AwardType.Length > 0) //If only a single award type, get it and fill the list
{
Type_Of_Award toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == AwardType
select s).First();
AwardTypes.Add(toa);
}
else
{ //Otherwise, fill the list with every award type
Type_Of_Award toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "On The Spot"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "You Showed PRIDE"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "Dinner With PRIDE"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "Day Of PRIDE"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "P"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "R"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "I"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "D"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "E"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "Heart of Gold"
select s).First();
AwardTypes.Add(toa);
toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == "Unsung Hero"
select s).First();
AwardTypes.Add(toa);
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
//Clear the defaults from the report
reportViewer1.Reset();
reportViewer1.LocalReport.DataSources.Clear();
//Tell the viewer which report we're using
reportViewer1.LocalReport.ReportEmbeddedResource = "GUI_Design_Mockup.AwardsSummaryReport.rdlc";
//Get the DataContext for queries
DataClasses1DataContext dc = DBCommands.DContext;
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("AwardType");
foreach (var q in AwardTypes)
{
Object x = q.AwardTypeName;
data.Tables["A"].Rows.Add(x);
}
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("SummarySet", data.Tables["A"]));
this.reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
reportViewer1.RefreshReport();
}
void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
{
DataClasses1DataContext dc = DBCommands.DContext;
if (e.ReportPath == "SingleAwardByYearSubreport")
{
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("Year");
DateTime Year = new DateTime(StartDate.Year, 1, 1);
while (Year < EndDate)
{
Object x = Year.Year;
data.Tables["A"].Rows.Add(x);
Year = new DateTime(Year.Year + 1, 1, 1);
}
ReportDataSource rds = new ReportDataSource();
rds.Name = "SummarySet";
rds.Value = data.Tables["A"];
e.DataSources.Add(rds);
}
if (e.ReportPath == "SingleAwardByWinnerSubreport")
{
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("Winner");
data.Tables["A"].Columns.Add("WinnerGroup");
data.Tables["A"].Columns.Add("WinnerDayOfPride");
data.Tables["A"].Columns.Add("AwardType");
data.Tables["A"].Columns.Add("AwardDate");
data.Tables["A"].Columns.Add("Nominator");
data.Tables["A"].Columns.Add("AwardInfo");
String AwardType = e.Parameters[1].Values.First();
DateTime YearStart = new DateTime(Int32.Parse(e.Parameters[0].Values.First()), 1, 1);
DateTime YearEnd = new DateTime(Int32.Parse(e.Parameters[0].Values.First()), 12, 31);
if (YearEnd >= EndDate) YearEnd = EndDate;
if (YearStart.Year == StartDate.Year) YearStart = StartDate;
Type_Of_Award toa = (from s in dc.Type_Of_Awards
where s.AwardTypeName == AwardType
select s).First();
//MessageBox.Show(toa.AwardTypeID + " - " + toa.AwardTypeName);
var AwardList = from s in dc.Awards
join emp in dc.Employees on s.RecipientID equals emp.EmployeeID
where s.AwardDate >= YearStart && s.AwardDate <= YearEnd && s.AwardTypeID == toa.AwardTypeID
select new { s.AwardID, s.AwardDate, s.RecipientID, s.NominatorID, s.Notes, s.AwardTypeID, emp.GroupID, emp.DeptID };
if (GroupID.Length > 0)
{
AwardList = AwardList.Where(s => s.GroupID == GroupID);
}
if (Department.Length > 0)
{
AwardList = AwardList.Where(s => s.DeptID == Department);
}
if (Nominator.Length > 0)
{
AwardList = AwardList.Where(s => s.NominatorID == Nominator);
}
if (Recipient.Length > 0)
{
AwardList = AwardList.Where(s => s.RecipientID == Recipient);
}
object[] row = new object[7];
if (AwardList.Count() <= 0)
{
row[0] = "No Winners for Award " + AwardType + " In this span of time";
data.Tables["A"].Rows.Add(row);
}
else if (AwardList.Count() > 0)
{
foreach (var q in AwardList)
{
String WinnerName;
var Winner = from s in dc.Employees
where s.EmployeeID == q.RecipientID
select s;
if(Winner.Count() <= 0)
{
continue;
}
WinnerName = Winner.First().PreferredName + " " + Winner.First().LastName;
row[0] = WinnerName;
var WinnerGroup = from s in dc.Groups
where s.GroupID == Winner.First().GroupID
select s;
if (WinnerGroup.Count() > 0)
{
row[1] = "Group " + WinnerGroup.First().GroupNum;
row[2] = "Day of PRIDE Group " + WinnerGroup.First().DayOfPride;
}
row[3] = AwardType;
row[4] = q.AwardDate.Value.ToShortDateString();
var Nominators = from s in dc.Employees
where s.EmployeeID == q.NominatorID
select s;
String NominatorName;
if (Nominators.Count() > 0)
{
NominatorName = Nominators.First().PreferredName + " " + Nominators.First().LastName;
}
else
{
NominatorName = "";
}
row[5] = NominatorName.Length > 0 ? "Nominated by: " + NominatorName : "";
row[6] = q.Notes;
data.Tables["A"].Rows.Add(row);
}
}
ReportDataSource rds = new ReportDataSource();
rds.Name = "SummarySet";
rds.Value = data.Tables["A"];
e.DataSources.Add(rds);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GUI_Design_Mockup
{
class classAwardsSummaryReport
{
public int Year { get; set; }
public string Winner { get; set; }
public string WinnerGroup { get; set; }
public string WinnerDayOfPride { get; set; }
public string AwardType { get; set; }
public DateTime AwardDate { get; set; }
public string Nominator { get; set; }
public string AwardInfo { get; set; }
}
}
<file_sep>using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmEligibilityReport : Form
{
String AwardName;
String SubAwardName;
DateTime StartDate, EndDate;
Group theGroup;
public frmEligibilityReport()
{
InitializeComponent();
}
public frmEligibilityReport(String Award, DateTime Start, DateTime End, Group g)
{
AwardName = Award;
EndDate = End;
StartDate = Start;
theGroup = g;
switch (AwardName)
{
case "You Showed PRIDE": SubAwardName = "On The Spot"; break;
case "Dinner With PRIDE": SubAwardName = "On The Spot"; break;
case "Day of PRIDE": SubAwardName = "Day of PRIDE Nomination"; break;
}
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
//Clear the defaults from the report
reportViewer1.Reset();
reportViewer1.LocalReport.DataSources.Clear();
//Tell the viewer which report we're using
reportViewer1.LocalReport.ReportEmbeddedResource = "GUI_Design_Mockup.AwardEligibilityReport.rdlc";
//Get the DataContext for queries
DataClasses1DataContext dc = DBCommands.DContext;
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("NominationInfo");
Object x = "Award";
data.Tables["A"].Rows.Add(x);
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("EligibilitySet", data.Tables["A"]));
this.reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
reportViewer1.RefreshReport();
}
void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
{
DataClasses1DataContext dc = DBCommands.DContext;
String SubID = DBCommands.GetAwardID(SubAwardName);
String AwardID = DBCommands.GetAwardID(AwardName);
DataSet nds = new DataSet();
DateTime yearStart = new DateTime(EndDate.Year, 1, 1);
DateTime yearEnd = new DateTime(EndDate.Year, 12, 31);
nds.Tables.Add("A");
nds.Tables["A"].Columns.Add("Nominee");
nds.Tables["A"].Columns.Add("NomineeDepartment");
nds.Tables["A"].Columns.Add("Nominator");
nds.Tables["A"].Columns.Add("NominationDate");
nds.Tables["A"].Columns.Add("NominationType");
nds.Tables["A"].Columns.Add("NominationInfo");
//Get the list of everybody who won the lower level award in the given year
var SubAwardList = from s in dc.Awards
join Emp in dc.Employees on s.RecipientID equals Emp.EmployeeID
where s.AwardDate >= StartDate && s.AwardDate <= EndDate && Emp.GroupID == theGroup.GroupID && s.AwardTypeID == SubID
select s;
var OldAwards = from s in dc.Awards
join Emp in dc.Employees on s.RecipientID equals Emp.EmployeeID
where s.AwardDate >= yearStart && s.AwardDate <= yearEnd && Emp.GroupID == theGroup.GroupID && s.AwardTypeID == AwardID
select s;
var EligibleList = SubAwardList;
if (e.ReportPath == "EligibleSubreport")
{
EligibleList = from s in SubAwardList
where !OldAwards.Select(t => t.RecipientID).Contains(s.RecipientID)
select s;
}
else if (e.ReportPath == "IneligibleSubreport")
{
EligibleList = from s in SubAwardList
where OldAwards.Select(t => t.RecipientID).Contains(s.RecipientID)
select s;
}
object[] data = new object[6];
try
{
foreach (var q in EligibleList)
{
var nominee = from s in dc.Employees
where q.RecipientID == s.EmployeeID
select s;
string NomineeName = nominee.First().FirstName + " " + nominee.First().LastName;
var dept = from s in dc.Departments
where s.DeptID == nominee.First().DeptID
select s;
string NomineeDept = dept.First().DeptName;
var nominator = from s in dc.Employees
where q.NominatorID == s.EmployeeID
select s;
string NominatorName;
if (nominator.Count() == 0)
{
NominatorName = "";
}
else
{
NominatorName = nominator.First().FirstName + " " + nominator.First().LastName;
}
data[0] = NomineeName;
data[1] = NomineeDept;
data[2] = NominatorName.Length > 0 ? "Nominated by: " + NominatorName : "";
data[3] = q.AwardDate.Value.ToShortDateString();
data[4] = SubAwardName;
data[5] = q.Notes;
nds.Tables["A"].Rows.Add(data);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception " + ex.ToString());
}
ReportDataSource rds = new ReportDataSource();
rds.Name = "EligibilitySet";
rds.Value = nds.Tables["A"];
e.DataSources.Add(rds);
}
}
}
<file_sep>using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmAnnualAwardsReport : Form
{
Type_Of_Award AwardType;
DateTime StartDate, EndDate;
public frmAnnualAwardsReport(Type_Of_Award awdType, DateTime Start, DateTime End)
{
InitializeComponent();
AwardType = awdType;
StartDate = Start;
EndDate = End;
}
private void Form1_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
//Clear the defaults from the report
reportViewer1.Reset();
reportViewer1.LocalReport.DataSources.Clear();
//Tell the viewer which report we're using
reportViewer1.LocalReport.ReportEmbeddedResource = "GUI_Design_Mockup.AnnualAwardReport.rdlc";
//Get the DataContext for queries
DataClasses1DataContext dc = DBCommands.DContext;
String AwardID = AwardType.AwardTypeID;
String AwardName = AwardType.AwardTypeName;
DataSet nds = new DataSet();
DateTime yearStart = new DateTime(EndDate.Year, 1, 1);
DateTime yearEnd = new DateTime(EndDate.Year, 12, 31);
nds.Tables.Add("A");
nds.Tables["A"].Columns.Add("Nominee");
nds.Tables["A"].Columns.Add("NomineeDepartment");
nds.Tables["A"].Columns.Add("Nominator");
nds.Tables["A"].Columns.Add("NominationDate");
nds.Tables["A"].Columns.Add("NominationType");
nds.Tables["A"].Columns.Add("NominationInfo");
//Get the list of everybody who won the lower level award in the given year
//MessageBox.Show(StartDate.ToShortDateString() + " - " + EndDate.ToShortDateString());
var NomineeList = from s in dc.Awards
where s.AwardDate >= StartDate && s.AwardDate <= EndDate && s.AwardTypeID == AwardID
select s;
//MessageBox.Show(NomineeList.Count().ToString());
object[] data = new object[6];
foreach (var q in NomineeList)
{
var nominee = from s in dc.Employees
where q.RecipientID == s.EmployeeID
select s;
string NomineeName = nominee.First().FirstName + " " + nominee.First().LastName;
var dept = from s in dc.Departments
where s.DeptID == nominee.First().DeptID
select s;
string NomineeDept = dept.First().DeptName;
var nominator = from s in dc.Employees
where q.NominatorID == s.EmployeeID
select s;
string NominatorName;
if (nominator.Count() == 0)
{
NominatorName = "";
}
else
{
NominatorName = nominator.First().FirstName + " " + nominator.First().LastName;
}
data[0] = NomineeName;
data[1] = NomineeDept;
data[2] = NominatorName.Length > 0 ? "Nominated by: " + NominatorName : "";
data[3] = q.AwardDate.Value.ToShortDateString();
data[4] = AwardName;
data[5] = q.Notes;
nds.Tables["A"].Rows.Add(data);
//MessageBox.Show(TypeOfAward + " " + NomineeName);
}
ReportDataSource rds = new ReportDataSource();
rds.Name = "AnnualSet";
rds.Value = nds.Tables["A"];
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("AnnualSet", nds.Tables["A"]));
reportViewer1.RefreshReport();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmPRIDEAwards : Form
{
List<Type_Of_Award> AwardList;
DataClasses1DataContext DContext;
public frmPRIDEAwards()
{
InitializeComponent();
DContext = DBCommands.DContext;
}
private void frmPRIDEAwards_Load(object sender, EventArgs e)
{
//int C1;
//for (C1 = 0; 2004 + C1 <= DateTime.Now.Year; C1++)
// YearBox.Items.Add((2004 + C1).ToString());
//YearBox.Text = DateTime.Now.Year.ToString();
InitializeAwardBox();
SaneLabelName.Text = "";
}
private void InitializeAwardBox()
{
var TypeOfAwardListRaw = from TOA in DBCommands.DContext.Type_Of_Awards
where TOA.IsNomination == true
orderby TOA.AwardTypeID ascending
select TOA;
AwardList = new List<Type_Of_Award>();
foreach (Type_Of_Award TOA in TypeOfAwardListRaw)
{
AwardList.Add(TOA);
}
AwardBox.DataSource = AwardList;
AwardBox.SelectedIndex = 0;
}
private void button4_Click(object sender, EventArgs e)
{
Type_Of_Award SelectedAwd = (Type_Of_Award)AwardBox.SelectedItem;
//int YearValue = int.Parse(YearBox.SelectedItem.ToString());
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, 1, 1);
DateTime FirstDayThisYear = new DateTime(DateTime.Now.Year, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, 12, DateTime.DaysInMonth(YearValue, 12));
if (SelectedAwd!= null)
{
string AwdID = DBCommands.GetAwardFromNomination(SelectedAwd.AwardTypeID).AwardTypeID;
string AwdNomID = SelectedAwd.AwardTypeID;
List<Award> AwdList = new List<Award>();
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdNomID
select Awd;
var AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDayThisYear && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdID
select Awd;
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
var AwardListRawD = (from A in AwdListRawC
join Emp in DContext.Employees on A.RecipientID equals Emp.EmployeeID
join D in DContext.Departments on Emp.DeptID equals D.DeptID
join G in DContext.Groups on Emp.GroupID equals G.GroupID
where A.AwardDate >= FirstDay && A.AwardDate <= LastDay
orderby G.DayOfPride
select new { Emp.PreferredName, Emp.LastName, D.DeptName, G.DayOfPride , Emp.EmployeeID }).Distinct();
dataGridView1.DataSource = AwardListRawD;
dataGridView1.Columns[0].HeaderText = "Preferred Name";
dataGridView1.Columns[1].HeaderText = "Last Name";
dataGridView1.Columns[2].HeaderText = "Department Name";
dataGridView1.Columns[3].HeaderText = "Group Number";
dataGridView1.Columns[4].Visible = false;
}
}
private void StartDateBox_ValueChanged(object sender, EventArgs e)
{
if (StartDateBox.Value > EndDateBox.Value)
EndDateBox.Value = StartDateBox.Value;
}
private void EndDateBox_ValueChanged(object sender, EventArgs e)
{
if (EndDateBox.Value < StartDateBox.Value)
StartDateBox.Value = EndDateBox.Value;
}
private void button2_Click(object sender, EventArgs e)
{
DateTime FirstDay = StartDateBox.Value;
DateTime LastDay = EndDateBox.Value;
Type_Of_Award ToA = (Type_Of_Award)AwardBox.SelectedItem;
if (ToA != null)
{
Type_Of_Award ParentAward = DBCommands.GetAwardFromNomination(ToA.AwardTypeID);
var AwdListRaw = from Awd in DContext.Awards
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == ParentAward.AwardTypeID
select Awd;
List<Award> AwdList = new List<Award>();
foreach (Award Awd in AwdListRaw)
AwdList.Add(Awd);
frmReviewOnTheSpot form = new frmReviewOnTheSpot(ParentAward.AwardTypeName);
form.StartThing(AwdList);
LaunchForm(form);
}
}
private void button9_Click(object sender, EventArgs e)
{
Type_Of_Award ToA = (Type_Of_Award)AwardBox.SelectedItem;
if(ToA!=null)
LaunchForm(new frmNewAward(ToA.AwardTypeName ));
}
private void OnSubFormClose(object sender, FormClosedEventArgs e)
{
this.Show();
}
public void LaunchForm(Form frm)
{
frm.FormClosed += OnSubFormClose;
frm.Show();
this.Hide();
}
private void button10_Click(object sender, EventArgs e)
{
Type_Of_Award SelectedAwd = (Type_Of_Award)AwardBox.SelectedItem;
//int YearValue = int.Parse(YearBox.SelectedItem.ToString());
DateTime FirstDay = StartDateBox.Value;// new DateTime(YearValue, 1, 1);
DateTime LastDay = EndDateBox.Value;// new DateTime(YearValue, 12, DateTime.DaysInMonth(YearValue, 12));
if (SelectedAwd != null)
{
string AwdID = DBCommands.GetAwardFromNomination(SelectedAwd.AwardTypeID).AwardTypeID;
string AwdNomID = SelectedAwd.AwardTypeID;
List<Award> AwdList = new List<Award>();
var AwdListRaw = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdNomID
select Awd;
var AwdListRawB = from Awd in DContext.Awards
join Emp in DContext.Employees on Awd.RecipientID equals Emp.EmployeeID
where Awd.AwardDate >= FirstDay && Awd.AwardDate <= LastDay && Awd.AwardTypeID == AwdID
select Awd;
var AwdListRawC = from Awd in AwdListRaw
where !AwdListRawB.Select(s => s.RecipientID).Contains(Awd.RecipientID)
select Awd;
foreach (Award A in AwdListRawC)
AwdList.Add(A);
frmReviewOnTheSpot frm = new frmReviewOnTheSpot(SelectedAwd.AwardTypeName);
frm.StartThing(AwdList);
LaunchForm(frm);
}
}
private void button5_Click(object sender, EventArgs e)
{
this.Close();
}
private void WinnerButton_Click(object sender, EventArgs e)
{
Type_Of_Award SelectedAwd = (Type_Of_Award)AwardBox.SelectedItem;
if (dataGridView1.SelectedRows.Count == 1 && SelectedAwd != null)
{
Award Awd = new Award();
DataGridViewRow theRow = dataGridView1.SelectedRows[0];
string AwdRecID = theRow.Cells[4].Value.ToString();
LaunchForm(new frmNewAward(DBCommands.GetAwardFromNomination(SelectedAwd.AwardTypeID).AwardTypeName , AwdRecID));
/*Awd.RecipientID = theRow.Cells[4].Value.ToString();
Awd.NominatorID = "EMP0000000";
Awd.AwardTypeID = DBCommands.GetAwardFromNomination(SelectedAwd.AwardTypeID).AwardTypeID ;
Awd.AwardID = DBCommands.NextID("Award");
Awd.AwardDate = DateTime.Now;
DContext.Awards.InsertOnSubmit(Awd);
DContext.SubmitChanges();
MessageBox.Show(theRow.Cells[0].Value.ToString() + " " + theRow.Cells[1].Value.ToString() + " has been selected as a winner!");*/
button4_Click(sender, e);
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
WinnerButton.Enabled = dataGridView1.SelectedRows.Count == 1;
}
private void AwardBox_SelectedValueChanged(object sender, EventArgs e)
{
Type_Of_Award TOA = (Type_Of_Award)AwardBox.SelectedItem;
if (TOA != null)
{
SaneLabelName.Text = "Select " + TOA.AwardTypeName + " winner\n\r";
SaneLabelName.Text += "from " + StartDateBox.Value.ToShortDateString() + " to " + EndDateBox.Value.ToShortDateString() + ", then click the Winner button.";
}
}
private void button1_Click(object sender, EventArgs e)
{
Type_Of_Award toa = (Type_Of_Award)AwardBox.SelectedValue;
LaunchForm(new frmAnnualAwardsReport(toa, StartDateBox.Value, EndDateBox.Value));
}
}
}
<file_sep>using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Design_Mockup
{
public partial class frmMonthlyStats : Form
{
DataSet ds;
DateTime StartDate, EndDate;
public frmMonthlyStats()
{
InitializeComponent();
}
public frmMonthlyStats(DateTime Start, DateTime End)
{
StartDate = Start;
EndDate = End;
InitializeComponent();
}
private void frmMonthlyStats_Load(object sender, EventArgs e)
{
this.reportViewer1.RefreshReport();
}
/*
* The general process for creating a report is as follows (Assuming the report is like a table):
* Identify each column
* Create a data-member only class (no functions), one member for each column in the table
* Create a Data Source from that object (Data Sources -> Add New -> From Object -> Your Class)
* I'm using classStatsReport.cs for this
* Create a DataSet object
* Fill the DataSet object with the necessary data
* Create your rdlc report
* Associate the Data Source you previously created with it (In the reportviewer_Load function/Event Handler)
* Create a ReportDataSource object from your DataSet object (It can only use one of the DataSet's tables)
* Add the ReportDataSource to your report
* Use the GUI designer to lay out your report. It's fairly intuitive.
* Subreports complicate things slightly.
*/
private void reportViewer1_Load(object sender, EventArgs e)
{
//Clear the defaults from the report
reportViewer1.Reset();
reportViewer1.LocalReport.DataSources.Clear();
//Tell the viewer which report we're using
reportViewer1.LocalReport.ReportEmbeddedResource = "GUI_Design_Mockup.MonthlyStatsReport.rdlc";
//Generate a DataSet
//ds = generateDataSet();
DataClasses1DataContext dc = DBCommands.DContext;
var GroupList = from s in dc.Groups
orderby s.GroupID
select s;
DateTime Start = StartDate;
DateTime End = EndDate;
DataSet data = new DataSet();
data.Tables.Add("A");
data.Tables["A"].Columns.Add("groupNum");
data.Tables["A"].Columns.Add("numEmployees");
data.Tables["A"].Columns.Add("numAwardsReceived");
data.Tables["A"].Columns.Add("numEmployeesReceived");
data.Tables["A"].Columns.Add("numAwardsGiven");
data.Tables["A"].Columns.Add("numEmployeesGiven");
var DeptList = from s in dc.Departments
select s;
foreach (var q in GroupList)
{
int totalEmployees = 0;
int totalAwardsReceived = 0;
int totalEmployeesReceived = 0;
int totalAwardsGiven = 0;
int totalEmployeesGiven = 0;
Object[] row = new Object[6];
var EmpsInGroup = from s in dc.Employees
where s.GroupID == q.GroupID
select s;
var DeptIDs = from s in dc.Employees
where s.GroupID == q.GroupID
select s.DeptID;
//Get the departments in the group by comparing department IDs
var DeptsInGroup = from s in dc.Departments
where DeptIDs.Contains(s.DeptID)
select s;
foreach (var p in DeptsInGroup)
{
var EmpsInDept = from s in dc.Employees //Select all employees in department that are in the group
where s.DeptID == p.DeptID && s.Active == true && s.GroupID == q.GroupID
select s; //There are some departments that are split iirc, this accounts for that
int numEmployees = EmpsInDept.Count(); //Count = # of Employees
if (numEmployees < 1) continue;
totalEmployees += numEmployees;
var EmpIDs = from s in EmpsInDept //Get the list of Employee IDs within the department
select s.EmployeeID;
var AwardsReceived = from s in dc.Awards //Find all awards received by an employee in this department
where EmpIDs.Contains(s.RecipientID) && (s.AwardDate >= (DateTime?)Start) && (s.AwardDate <= (DateTime?)End)
select s.RecipientID; //Select just this so we can Distinct them easily
totalAwardsReceived += AwardsReceived.Count(); //Number of awards received by this department
totalEmployeesReceived += AwardsReceived.Distinct().Count(); //Number of distinct employees receiving awards
var AwardsGiven = from s in dc.Awards //Find all awards given by an employee in this department
where EmpIDs.Contains(s.NominatorID) && (s.AwardDate >= (DateTime?)StartDate) && (s.AwardDate <= (DateTime?)EndDate)
select s.NominatorID;
totalAwardsGiven += AwardsGiven.Count(); //Same as awards received
totalEmployeesGiven += AwardsGiven.Distinct().Count();
}
row[0] = q.GroupNum;
row[1] = totalEmployees;
row[2] = totalAwardsReceived;
row[3] = totalEmployeesReceived;
row[4] = totalAwardsGiven;
row[5] = totalEmployeesGiven;
data.Tables["A"].Rows.Add(row);
}
//Process the subreport. I'm pretty sure the loop above is necessary rather than the line below
//But I just can't make it work
//This line is irrelevant and just so the larger report has a dataset (Which may or may not be necessary)
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("GroupSet", data.Tables["A"]));
this.reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
reportViewer1.RefreshReport();
}
void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
{
ReportDataSource rds = new ReportDataSource();
DataSet nds = new DataSet("StatsReportDataSet");
nds.Tables.Add("A");
nds.Tables["A"].Columns.Add("groupNum");
nds.Tables["A"].Columns.Add("Department");
nds.Tables["A"].Columns.Add("numEmployees");
nds.Tables["A"].Columns.Add("numAwardsReceived");
nds.Tables["A"].Columns.Add("numEmployeesReceived");
nds.Tables["A"].Columns.Add("numAwardsGiven");
nds.Tables["A"].Columns.Add("numEmployeesGiven");
Object[] data = new Object[7]; //Stores a row of data
DateTime Start = StartDate;
DateTime End = EndDate;
DataClasses1DataContext dc = DBCommands.DContext;
//Get the group and department list
var GroupList = from s in dc.Groups
orderby s.GroupNum
select s;
var DeptList = from s in dc.Departments
select s;
GroupList = (IOrderedQueryable<GUI_Design_Mockup.Group>)GroupList.Where(s => s.GroupNum == e.Parameters.First().Values.First());
foreach (var q in GroupList)
{
var EmpsInGroup = from s in dc.Employees
where s.GroupID == q.GroupID
select s;
var DeptIDs = from s in dc.Employees
where s.GroupID == q.GroupID
select s.DeptID;
//Get the departments in the group by comparing department IDs
var DeptsInGroup = from s in dc.Departments
where DeptIDs.Contains(s.DeptID)
select s;
foreach (var p in DeptsInGroup)
{
data[0] = q.GroupNum;
data[1] = p.DeptName;
var EmpsInDept = from s in dc.Employees //Select all employees in department that are in the group
where s.DeptID == p.DeptID && s.Active == true && s.GroupID == q.GroupID
select s; //There are some departments that are split iirc, this accounts for that
data[2] = EmpsInDept.Count(); //Count = # of Employees
if ((int)data[2] < 1) continue;
var EmpIDs = from s in EmpsInDept //Get the list of Employee IDs within the department
select s.EmployeeID;
var AwardsReceived = from s in dc.Awards //Find all awards received by an employee in this department
where EmpIDs.Contains(s.RecipientID) && (s.AwardDate >= (DateTime?)Start) && (s.AwardDate <= (DateTime?)End)
select s.RecipientID; //Select just this so we can Distinct them easily
data[3] = AwardsReceived.Count(); //Number of awards received by this department
data[4] = AwardsReceived.Distinct().Count(); //Number of distinct employees receiving awards
var AwardsGiven = from s in dc.Awards //Find all awards given by an employee in this department
where EmpIDs.Contains(s.NominatorID) && (s.AwardDate >= (DateTime?)StartDate) && (s.AwardDate <= (DateTime?)EndDate)
select s.NominatorID;
data[5] = AwardsGiven.Count(); //Same as awards received
data[6] = AwardsGiven.Distinct().Count();
nds.Tables["A"].Rows.Add(data); //Add the object vector to the table.
}
}
rds.Name = "StatsReportDataSet"; //Must exactly match the Dataset name in the actual report
rds.Value = nds.Tables["A"];
e.DataSources.Add(rds);
//Set the datasource to the appropriate table.
//Using the groupNum int to choose which group table to grab
//rds.Value = ds.Tables[groupNum];
//groupNum++;
//foreach (var q in ds.Tables)
//{
// rds.Value = ds;
// e.DataSources.Add(rds);
//}
}
DataSet generateDataSet()
{
DataSet ds = new DataSet("StatsReportDataSet");
ds.Tables.Add("A");
ds.Tables["A"].Columns.Add("groupNum");
ds.Tables["A"].Columns.Add("Department");
ds.Tables["A"].Columns.Add("numEmployees");
ds.Tables["A"].Columns.Add("numAwardsReceived");
ds.Tables["A"].Columns.Add("numEmployeesReceived");
ds.Tables["A"].Columns.Add("numAwardsGiven");
ds.Tables["A"].Columns.Add("numEmployeesGiven");
DateTime StartDate = DateTime.Parse("2/1/2013"); //Should adjust these to parameters based on
DateTime EndDate = DateTime.Parse("2/28/2013"); //The date pickers on the main menu
Object[] data = new Object[7]; //Stores a row of data
DataClasses1DataContext dc = DBCommands.DContext;
//Get the group and department list
var GroupList = from s in dc.Groups
orderby s.GroupNum
select s;
var DeptList = from s in dc.Departments
select s;
GroupList = GroupList.OrderBy(s => s.GroupID);
foreach (var q in GroupList)
{
//Add a table to the dataset for this group
//ds.Tables.Add(q.GroupNum);
//ds.Tables[q.GroupNum].Columns.Add("groupNum");
//ds.Tables[q.GroupNum].Columns.Add("Department");
//ds.Tables[q.GroupNum].Columns.Add("numEmployees");
//ds.Tables[q.GroupNum].Columns.Add("numAwardsReceived");
//ds.Tables[q.GroupNum].Columns.Add("numEmployeesReceived");
//ds.Tables[q.GroupNum].Columns.Add("numAwardsGiven");
//ds.Tables[q.GroupNum].Columns.Add("numEmployeesGiven");
var EmpsInGroup = from s in dc.Employees
where s.GroupID == q.GroupID
select s;
var DeptIDs = from s in dc.Employees
where s.GroupID == q.GroupID
select s.DeptID;
//Get the departments in the group by comparing department IDs
var DeptsInGroup = from s in dc.Departments
where DeptIDs.Contains(s.DeptID)
select s;
foreach (var p in DeptsInGroup)
{
data[0] = q.GroupNum;
data[1] = p.DeptName;
var EmpsInDept = from s in dc.Employees //Select all employees in department that are in the group
where s.DeptID == p.DeptID && s.Active == true && s.GroupID == q.GroupID
select s; //There are some departments that are split iirc, this accounts for that
data[2] = EmpsInDept.Count(); //Count = # of Employees
if ((int)data[2] < 1) continue;
var EmpIDs = from s in EmpsInDept //Get the list of Employee IDs within the department
select s.EmployeeID;
var AwardsReceived = from s in dc.Awards //Find all awards received by an employee in this department
where EmpIDs.Contains(s.RecipientID) && (s.AwardDate >= (DateTime?)StartDate) && (s.AwardDate <= (DateTime?)EndDate)
select s.RecipientID; //Select just this so we can Distinct them easily
data[3] = AwardsReceived.Count(); //Number of awards received by this department
data[4] = AwardsReceived.Distinct().Count(); //Number of distinct employees receiving awards
var AwardsGiven = from s in dc.Awards //Find all awards given by an employee in this department
where EmpIDs.Contains(s.NominatorID) && (s.AwardDate >= (DateTime?)StartDate) && (s.AwardDate <= (DateTime?)EndDate)
select s.NominatorID;
data[5] = AwardsGiven.Count(); //Same as awards received
data[6] = AwardsGiven.Distinct().Count();
ds.Tables["A"].Rows.Add(data); //Add the object vector to the table.
}
}
return ds;
}
}
}
| bf4e025273fb6b4ba1618a9c9916aee129110a04 | [
"C#"
] | 21 | C# | Falterfire/AllenPRIDE | cd4dcd4639950f6c57c750c9ba8f5e30215f9d00 | 8155c75d11e77cd1d6c851817094f54a7ca1360e |
refs/heads/master | <repo_name>ugurbagci/DBFirstExample2<file_sep>/DBFirstExample2/Form1.cs
using System;
using DBFirstExample2.Model;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity.SqlServer;
namespace DBFirstExample2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
NorthwindEntities db = new NorthwindEntities();
private void btnToList_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = db.Categories.ToList();
}
private void btnContains_Click(object sender, EventArgs e)
{
//Contains ()=> T-SQL
dataGridView1.DataSource = db.Products.Where(x => x.ProductName.Contains("a")).ToList();
}
private void btnStarAndWith_Click(object sender, EventArgs e)
{
//StartWith ()- EndWith() => Like sorgusundaki başlayan "c" ile biten
dataGridView1.DataSource = db.Products.Where(x => x.ProductName.StartsWith("c")).ToList();
dataGridView1.DataSource = db.Products.Where(x => x.ProductName.EndsWith("a")).ToList();
}
private void btnAny_Click(object sender, EventArgs e)
{
/* Any() => iki farklı kullanıma sahip olan Any methodu ilk kullanımı
*
*
* */
// Kategoriler tablosunda Becearges isimli bir kategori var mı yok mu?
bool sonuc = db.Categories.Any(x => x.CategoryName == "Becearges");
MessageBox.Show(sonuc.ToString());
// Kategoriler tablosunda adı B ile başlayan bir kategori var mı yok mu
bool sonuc2 = db.Categories.Any(x => x.CategoryName.StartsWith("Be"));
MessageBox.Show(sonuc2.ToString());
}
// AGGREGATE FUNCTION //
private void btnCount_Click(object sender, EventArgs e)
{
/* Count ()=> T-SQL ' den hatırlayacağınız gibi Count () methodu sorgu sonucunda dçnen result'un satırlarını saymaktadır.
*/
int IsciSayisi = db.Employees.Count();
MessageBox.Show(IsciSayisi.ToString());
}
private void btnSum_Click(object sender, EventArgs e)
{
// SUM()=> T-SQL'de kullanılan SUÖ methodu ile aynı görevi üstlenir. Dönen result içerisinde belirlediğiniz kolonların değerlerinin toplanmasını sağlar.
/* tüm ürünler dahil olmak üzere dahil olmak üzere stoğumda kaç adet ürün var ? (not: her ürünün stok değerlerini toplam istiyoruz
*
* */
int? StokSonuc = db.Products.Sum(x => x.UnitsInStock);
MessageBox.Show(StokSonuc.ToString());
}
private void btnMinMax_Click(object sender, EventArgs e)
{
// en pahalı ürün
decimal? SonucFiyat = db.Products.Max(x => x.UnitPrice);
MessageBox.Show(SonucFiyat.ToString());
// en ucuz ürün
decimal? SonucFiyat2 = db.Products.Min(x => x.UnitPrice);
MessageBox.Show(SonucFiyat2.ToString());
}
private void btnDistinct_Click(object sender, EventArgs e)
{
// T-SQL 'deki gibi tekrar eden değerleri egale etmek için kullanılır.
// hangi ülkelerle iş yapıyoruz?
List<string> liste = db.Orders.Select(x => x.ShipCountry).Distinct().ToList();
foreach (string item in liste)
{
listBox1.Items.Add(item);
}
}
private void btnSelect_Click(object sender, EventArgs e)
{
// Select() => Select metodu sorgularınızı çekerken istediğiniz kolonları almanıza
// müşterilerin müşteri adı, yetkilisi, telefonu ve adresini farklı kolon isimleriyle getiren soruyu yazınız.
dataGridView1.DataSource = db.Customers.Select(x => new
{ MusteriSirketi = x.CompanyName,
Yetkili = x.ContactName,
Telefon = x.Phone,
Adres = x.Address
}).ToList();
}
private void btnGroupBy_Click(object sender, EventArgs e)
{
// GroupBy() => Sorgularımızdan dönen sonuçları
// Hnagi kategoride kaç adet ürünüm var
dataGridView1.DataSource = db.Products.GroupBy(x => x.Category.CategoryName).Select(y => new
{
KategoriAdi = y.Key,
ToplamStok = y.Sum(x => x.UnitsInStock)
}).ToList();
}
private void btnJoin_Click(object sender, EventArgs e)
{
// ürünlerin ürün adını, fiyatını, stok miktarını, kategori adını ve tedarikçi adını getiren sorguyu yazınız.
dataGridView1.DataSource = db.Products.Select(x => new
{
UrunAdi = x.ProductName,
Fiyat = x.UnitPrice,
Stok = x.UnitsInStock,
Kategori = x.Category.CategoryID,
Tedarikci = x.Supplier.SupplierID,
}).ToList();
}
private void btnFunction_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = db.Employees.Select(x=> new
{
Adi = x.FirstName,
Soyadi = x.LastName,
DogumTarihi = x.BirthDate,
Yasi = SqlFunctions.DateDiff("Year",x.BirthDate)
})
}
}
}
| 4762b3f2757c995f5f76aeff1fd2a312793a2279 | [
"C#"
] | 1 | C# | ugurbagci/DBFirstExample2 | e85e71ff2495a519ddfe9d75bccd06ddaade7baa | bbbc3f603670ae285c88cf30aa0adf7a7c48dd07 |
refs/heads/master | <file_sep>def consolidate_cart(cart)
# code here
new_cart = {}
cart.each do |piece|
piece.each do |item, attr_hash|
new_cart[item] ||= attr_hash
new_cart[item][:count] ||= 0
new_cart[item][:count] += 1
end
end
new_cart
end
def apply_coupons(cart, coupons= {})
# code here
new_prices = {}
cart.each do |grocery_item, item_details|
discounted_item = grocery_item.dup + " W/COUPON"
discounted_details = {:price => nil, :clearance => nil, :count =>nil}
coupons.each do |coupon|
if coupon[:item] == grocery_item && item_details[:count] >= coupon[:num]
discounted_details[:price] = (coupon[:cost] / coupon[:num])
discounted_details[:count] ||= 0
discounted_details[:count] += coupon[:num]
discounted_details[:clearance] = item_details[:clearance].dup
item_details[:count] -= coupon[:num]
new_prices[grocery_item] = item_details
new_prices[discounted_item] = discounted_details
end
end
new_prices[grocery_item] ||= item_details
end
new_prices
end
def apply_clearance(cart)
# code here
updated_cart = {}
cart.each do |item, details|
if details[:clearance]
details[:price] = (details[:price] * 0.8).round(2)
updated_cart[item] = details
else
updated_cart[item] = details
end
end
updated_cart
end
def checkout(cart, coupons = {})
new_cart = consolidate_cart(cart)
new_cart = apply_coupons(new_cart,coupons)
new_cart = apply_clearance(new_cart)
new_cost = 0
new_cart.each do |item, details|
new_cost += (details[:count] * details[:price])
end
if new_cost > 100
new_cost -= (new_cost * 0.1)
end
new_cart
new_cost
end
puts checkout(
[{"AVOCADO" => {:price => 3.00, :clearance => true }},{"AVOCADO" => {:price => 3.00, :clearance => true }},
{"AVOCADO" => {:price => 3.00, :clearance => true }},
{"KALE" => {:price => 3.00, :clearance => false}}
],[{:item => "AVOCADO", :num => 2, :cost => 5.00},{:item => "BEER", :num => 2, :cost => 20.00}, {:item => "CHEESE", :num => 3, :cost => 15.00}])
| 1ea82f627de180ea81b91b059077d545ad372518 | [
"Ruby"
] | 1 | Ruby | LizLaffitte/ruby-enumerables-hash-practice-green-grocer-lab-online-web-prework | aca9b54c207f2638a980c8645b116aaf445c2578 | f42340c76652ae3390478e8fabf832f0688d7a22 |
refs/heads/master | <repo_name>Lamx/Cours-Ruby<file_sep>/boucles.rb
utilisateurs = [
"Alice", "Bob", "John", "Hector"
]
utilisateurs.each do |utilisateur|
puts utilisateur
end
<file_sep>/tp.rb
class Utilisateur
attr_accessor :prenom, :nom, :amis
def nom_complet
prenom + " " + nom
end
def est_ami_avec(valeur)
amis.each do |ami|
ami = "#{ami}"
if valeur == ami
"Oui :)"
else
"Non :("
end
end
end
end
alice = Utilisateur.new
alice.prenom = "Alice"
alice.nom = "Fillot"
bob = Utilisateur.new
bob.prenom = "Bob"
bob.nom = "Lennon"
ted = Utilisateur.new
ted.prenom = "Ted"
ted.nom = "Mosby"
alice.amis = ["Léo", "Manon", "Roxanne"]
bob.amis = ["John", "Paul", "George", "Ringo"]
ted.amis = ["Marshall", "Barney"]
puts alice.amis.length
puts "Est-ce que " + alice.nom_complet + " est amie avec Léo ?\n" + alice.est_ami_avec("Manon")
<file_sep>/manip.rb
class Utilisateur
attr_accessor :prenom, :amis
def initialize(prenom)
@prenom = prenom
end
def est_ami_avec?(prenom)
amis.each do |ami|
return true if ami.prenom == prenom
end
return false
end
end
alice = Utilisateur.new("Alice")
bob = Utilisateur.new
bob.prenom = "Bob"
jane = Utilisateur.new
jane.prenom = "Jane"
alice.amis = [bob, jane]
puts alice.amis.size
puts alice.est_ami_avec?("Bob")<file_sep>/conditions.rb
animaux = [["chien", "chat", "oiseau"]]<file_sep>/classes.rb
class Utilisateur
attr_accessor :prenom
end
mon_utilisateur = Utilisateur.new
mon_utilisateur.prenom = "Bob"
puts mon_utilisateur.prenom
<file_sep>/methodes.rb
class Utilisateur
attr_accessor :prenom, :nom, :pays
def nom_complet
prenom + " " + nom
end
def habite_en(valeur)
valeur == pays
end
end
bob = Utilisateur.new
bob.prenom = "Bob"
bob.nom = "Lennon"
bob.pays = "France"
puts "Est-ce que Bob habite en France ?"
puts bob.habite_en("France")<file_sep>/README.md
# Cours-Ruby
| 2ff04f4238397e0c7d1199a88c5ce0e87eae610d | [
"Markdown",
"Ruby"
] | 7 | Ruby | Lamx/Cours-Ruby | a2e710fefb99e955fefc2dac420ef78c30530489 | f723eee212127e0f2a656d15f41720f37554c879 |
refs/heads/master | <file_sep>package com.theironyard.charlotte;
import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// write your code here
}
// The number 6 is a truly great number. Given two int values, a and b, return true if either one is 6.
// Or if their sum or difference is 6. Note: the function Math.abs(num) computes the absolute value of a number.
public static boolean love6(int a, int b) {
if (a == 6 || b == 6) {
return true;
} else if ((a + b) == 6 || (a -b) == 6) {
return true;
}
else {
return false;
}
}
// Return true if the given non-negative number is 1 or 2 more than a multiple of 20.
public static boolean more20(int n) {
if (n >= 20 && (n % 20 == 1 || n % 20 == 2)) {
return true;
}
return false;
}
// Given a non-negative number "num", return true if num is within 2 of a multiple of 10.
public static boolean nearTen(int num) {
int r = num % 10;
if (r <= 2) {
return true;
}
return false;
}
// Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
public static String firstHalf(String input) {
int subStringLength = (input.length() / 2);
String answer = input.substring(0, subStringLength);
return answer;
}
// Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1.
public static String nonStart(String a, String b) {
String firstWord = a.substring(1, a.length());
String secondWord = b.substring(1, b.length());
return firstWord + secondWord;
}
// Given a string, return a string length 1 from its front, unless front is false,
// in which case return a string length 1 from its back. The string will be non-empty.
//
// theEnd("Hello", true) → "H"
// theEnd("Hello", false) → "o"
// theEnd("oh", true) → "o"
public static String theEnd(String input, boolean front) {
if (front == true) {
return input.substring(0, 1);
}
return input.substring(input.length() - 1, input.length());
}
// Given a string, return true if it ends in "ly".
public static boolean endsLy(String input) {
String lastTwo = input.substring(input.length() - 2, input.length());
if (lastTwo.equalsIgnoreCase("ly")) {
return true;
}
return false;
}
// Given a string of odd length, return the string length 3 from its middle, so "Candy" yields "and".
// The string length will be at least 3.
public static String middleThree(String input) {
int middle = input.length() / 2;
String middleLetters = input.substring(middle - 1, middle +2);
return middleLetters;
}
// Given 2 strings, a and b, return a new string made of the first char of a and the last char of b, so "yo" and "java"
// yields "ya". If either string is length 0, use '@' for its missing char.
public static String lastChars(String a, String b) {
String firstChar = a.substring(0, 1);
String lastChar = b.substring(b.length() - 1, b.length());
String mashup = firstChar + lastChar;
return mashup;
}
// Given a string, if the string begins with "red" or "blue" return that color string,
// otherwise return the empty string.
public static String seeColor(String input) {
String red = "red";
String blue = "blue";
String zippy = "";
if (input.startsWith("red")) {
return red;
}
else if (input.startsWith("blue")) {
return blue;
}
else {
return zippy;
}
}
// Given three ints, a b c, return true if two or more of them have the same rightmost digit.
// The ints are non-negative
public static boolean lastDigit(int a, int b, int c) {
int lastA = Math.abs(a % 10);
int lastB = Math.abs(b % 10);
int lastC = Math.abs(c % 10);
if (lastA == lastB || lastA == lastC || lastB == lastC) {
return true;
}
return false;
}
// Given two int values, return whichever value is larger.
// However if the two values have the same remainder when divided by 5, then the return the smaller value.
// However, in all cases, if the two values are the same, return 0
public static int maxMod5(int a, int b) {
if (a == b) {
return 0;
} else if (a % 5 == b % 5) {
return Integer.min(a, b);
}
else {
return Integer.max(a, b);
}
}
// This starts med diff
// We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each)
// and big bricks (5 inches each). Return true if it is possible to make the goal by choosing from the given bricks.
// This is a little harder than it looks and can be done without any loops.
public static boolean makeBricks(int small, int big, int goal) {
int bigBrick = 5;
int firstStep = goal % (big * bigBrick);
if (firstStep <= small) {
return true;
}
else {
return false;
}
}
// Given 2 int values greater than 0, return whichever value is nearest to 21 without going over.
// Return 0 if they both go over.
public static int blackjack(int a, int b) {
int highNumber = Integer.max(a, b);
if (a > 21 && b > 21) {
return 0;
}
else if (highNumber > 21) {
return Integer.min(a, b);
}
return highNumber;
}
// Given 3 int values, a b c, return their sum.
// However, if one of the values is the same as another of the values, it does not count towards the sum.
public static int loneSum(int a, int b, int c) {
if (a == b && b == c) {
return 0;
}
else if (a == b) {
return c;
}
else if (b == c) {
return a;
}
else if (a == c) {
return b;
}
else {
return a + b + c;
}
}
// For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more,
// so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is
// less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values.
// To avoid code repetition, write a separate helper "public int round10(int num) {" and call it 3 times.
// Write the helper entirely below and at the same indent level as roundSum().
public static int roundTen(int num) {
double decimal = (double)num/10;
double rounded = Math.round(decimal);
int finalValue = (int)rounded * 10;
return finalValue;
}
public static int roundSum(int a, int b, int c) {
int answer = (roundTen(a) + roundTen(b) + roundTen(c));
return answer;
}
// Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19
// inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper
// "public int fixTeen(int n) {"that takes in an int value and returns that value fixed for the teen rule.
// In this way, you avoid repeating the teen code 3 times (i.e. "decomposition").
// Define the helper below and at the same indent level as the main noTeenSum().
public static int fixTeen(int n) {
if ((n == 13 || n == 14) || (n>= 17 && n <= 19)) {
n = 0;
return Integer.valueOf(n);
}
else {
return Integer.valueOf(n);
}
}
public static int noTeenSum(int a, int b, int c) {
int answer = (fixTeen(a) + fixTeen(b) + fixTeen(c));
return answer;
}
//
// Given three ints, a b c, one of them is small, one is medium and one is large. Return true if the three values are
// evenly spaced, so the difference between small and medium is the same as the difference between medium and large
public static boolean evenlySpaced(int a, int b, int c) {
int[] spaced = {a, b, c};
Arrays.sort(spaced, 0, 3);
int firstDiff = spaced[1] - spaced [0];
int secondDiff = spaced[2] - spaced [1];
if (firstDiff == secondDiff) {
return true;
}
return false;
}
// Given 3 int values, a b c, return their sum. However, if one of the values is 13
// then it does not count towards the sum and values to its right do not count. So for example,
// if b is 13, then both b and c do not count.
public static int luckySum(int a, int b, int c) {
if (a == 13) {
return 0;
}
else if (b == 13) {
return a;
}
else if (c == 13) {
return a + b;
}
else {
return a + b + c;
}
}
// Given three ints, a b c, return true if one of b or c is "close" (differing from a by at most 1), while the other
// is "far", differing from both other values by 2 or more. Note: Math.abs(num) computes the absolute value of a number.
public static boolean closeFar(int a, int b, int c) {
int first = Math.abs(a - b);
int second = Math.abs(a - c);
if ((first == 1 || second == 1) && (first > 2 || second > 2)) {
return true;
}
return false;
}
// We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each).
// Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.
public static int makeChocolate(int small, int big, int goal) {
int remainder = goal - (5 * big);
if (remainder > small) {
return -1;
}
return remainder;
}
// Return the number of times that the string "code" appears anywhere in the given string,
// except we'll accept any letter for the 'd', so "cope" and "cooe" count.
public static int countCode(String input) {
int count = 0;
for (int i = 0; i < input.length() - 3; i++)
if (input.substring(i, (i + 2)).equals("co") && input.charAt(i + 3) == 'e') {
count++;
}
return count;
}
}
| 0a65ce7ba646e762cd7eda024e6f8f48fac82b0d | [
"Java"
] | 1 | Java | mfahrner/PracticeProbs | 70837b0fa0c6c9eaf6cc2993f92925d7f374ed72 | 9be37030ba9f0445fafc169a24867377e03912de |
refs/heads/master | <repo_name>lqiz/BarrageDemo<file_sep>/BarrageDemo/src/com/example/testdanmu/MainActivity.java
package com.example.testdanmu;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private DanMuView mDanMuLayout;
private DanMuClient danMuClient;
private SharedPreferences sharedPreferences;
private String mUserName;
private String mTitle;
private Button mBtnSwitch;
public static final String BUNDLE_USER_NAME = "userName";
public static final String BUNDLE_TITLE = "title";
public static final String KEY_DANMU_STATUS = "switch_dan_mu"; // 弹幕
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = null;
try {
bundle = getIntent().getExtras();
} catch (Exception e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
mDanMuLayout = (DanMuView) this
.findViewById(R.id.view_danmu);
mBtnSwitch = (Button) findViewById(R.id.dan_mu_switch);
// Demo, change it to your need.
mTitle = "342679617";
mUserName = "qq";
if (bundle != null) {
mUserName = bundle.getString(BUNDLE_USER_NAME);
mTitle = bundle.getString(BUNDLE_TITLE);
}
sharedPreferences = getSharedPreferences("danmu_demo",
Context.MODE_PRIVATE); // 私有数据
// Change to your own switch
mBtnSwitch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean danmuStatus = sharedPreferences.getBoolean(
KEY_DANMU_STATUS, true);
if (danmuStatus) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(KEY_DANMU_STATUS, false);
editor.commit();
danMuClient.stopDanMu();
mDanMuLayout.setVisibility(View.GONE);
} else {
Editor editor = sharedPreferences.edit();
editor.putBoolean(KEY_DANMU_STATUS, true);
editor.commit();
danMuClient.startDanMu();
mDanMuLayout.setVisibility(View.VISIBLE);
}
}
});
}
@Override
protected void onResume() {
super.onResume();
boolean danmuStatus = sharedPreferences.getBoolean(KEY_DANMU_STATUS,
true);
MyHandler myHandler = new MyHandler();
danMuClient = new DanMuClient(this, myHandler);
mDanMuLayout.setDanMuClient(danMuClient, mUserName, mTitle);
android.util.Log.e("danmuStatus", "danmuStatus: " + danmuStatus);
if (danmuStatus) {
danMuClient.startDanMu();
} else {
mDanMuLayout.setVisibility(View.GONE);
}
}
/*
* {@"msg":msg,@"book":book,@"user":username}
*/
private class MyHandler extends Handler {
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
String KEY_CONTENT = "content";
String content = (String) bundle.get(KEY_CONTENT);
mDanMuLayout.createDanMuText(content);
}
}
public void onStop() {
danMuClient.stopDanMu();
super.onStop();
}
@Override
public void finish() {
super.finish();
danMuClient.stopDanMu();
}
}
<file_sep>/README.md
# BarrageDemo
A useful barrage demo, using WebSocket
这里有个嵌入到商业工程里的应用:打开一本书的时候,可以发送弹幕。弹幕体验: http://fir.im/danmu
| 935aa9dff2da154bc3505bf223b7b367f6a68d09 | [
"Markdown",
"Java"
] | 2 | Java | lqiz/BarrageDemo | f990445ab2e1a88213ac5d59724aa96d146ca6c1 | d3f9ba0c3f9f5a39aa928a2747a5cb146c7a631d |
refs/heads/master | <repo_name>DeanTang/HealthVision<file_sep>/gui.py
import requests
import json
from tkinter import *
import time
import datetime
import serial
window = Tk()
toggle = IntVar()
window.title("HealthVision")
light_text = ""
def checkToggle():
try:
if toggle.get():
led_url = "https://api.particle.io/v1/devices/3b003b000847373336323230/led"
data ={
'access_token': '86928f56a4820739bd1ed711fe46d84dfb90451d',
'args':'ON'}
r2 = requests.post(led_url, data)
print(r2.text)
else:
led_url = "https://api.particle.io/v1/devices/3b003b000847373336323230/led"
data ={
'access_token': '86928f56a4820739bd1ed711fe46d84dfb90451d',
'args':'OFF'}
r2 = requests.post(led_url, data)
print(r2.text)
except:
print("Error: Could not post to the particle api for the LED function!")
def getTime():
try:
global time1
time2 = time.strftime('%H:%M:%S')
if time2 != time1:
time1 = time2
window.after(100, tick)
return time1;
except:
return "Error"
def getLight():
try:
light_url = "https://api.particle.io/v1/devices/3b003b000847373336323230/light?access_token=86928f56a4820739bd1ed711fe46d84dfb90451d"
r = requests.get(light_url)
json_light = r.json()
return json_light['result']
except:
print("Could not fetch light data!!!")
return "N/A"
def getPulse():
try:
ser = serial.Serial('/dev/ttyACM0', 9600)
line = re.sub("[^0-9]", "", str(ser.readline()))
##Change value to 150 or above for possible alerts
if int(line)>10:
led_url = "https://api.particle.io/v1/devices/3b003b000847373336323230/led"
data ={
'access_token': '8<PASSWORD>',
'args':'<PASSWORD>'}
r2 = requests.post(led_url, data)
print(r2.text)
return str(line)
except:
print("Could not listen to the pulse sensor reading!!!")
return "N/A"
while True:
Logo = Label(window, text="HealthVision", font=("Arial Bold", 24))
Logo.grid(column=0, row=0)
Time = Label(window, text=datetime.datetime.now().strftime('%H:%M:%S'), font=("Arial Bold", 24))
Time.grid(column=0, row=1)
lightcheck = Checkbutton(text='Light', variable=toggle, command=checkToggle)
lightcheck.grid(column=0, row=2)
lightlbl = Label(window, text="Light: "+getLight())
lightlbl.grid(column=0, row=3)
pulselbl = Label(window,text="Pulse: "+getPulse())
pulselbl.grid(column=0, row=4)
window.update()
window.protocol("WM_DELETE_WINDOW",window.destroy())
window.mainloop()
<file_sep>/particlecode.ino
int photosensor = A0;//light sensor connected to A0
// Declaring variables
int analogvalue;
char light[30];
void setup() {
Serial.begin();
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
//Particle.variable("AnalogData", analogvalue);
Particle.variable("light", light);
Particle.subscribe("hook-response/light", myHandler, MY_DEVICES);
Particle.function("led", led);
}
void myHandler(const char *event, const char *data) {
}
int led(String arg)
{
if (arg == "ON")
{
digitalWrite(D6, HIGH);
digitalWrite(D7, HIGH);
}
if (arg== "OFF")
{
digitalWrite(D6, LOW);
digitalWrite(D7, LOW);
}
if (arg=="blink")
{
digitalWrite(D6, HIGH);
digitalWrite(D7, HIGH);
delay(5000);
digitalWrite(D6, LOW);
digitalWrite(D7, LOW);
}
return 0;
}
void loop() {
//Reading light value
analogvalue = analogRead(photosensor);
//Converting light value into string for particle.publish()
sprintf(light,"%d", analogvalue);
//Publishing to thinkspeak
Particle.publish("light", light, PRIVATE);
delay(2000);
}
| ea48267cb5ea658b37d803633b0e80af5c62bb62 | [
"Python",
"C++"
] | 2 | Python | DeanTang/HealthVision | 1338ffec6d29219d2e16d021ddbcad9ff8c37c31 | 8d3b440a947d2fa2c0740cccc0f49bb6bba37b78 |
refs/heads/master | <file_sep>/**
* History.js YUI Adapter [NOT WORKING]
* @author <NAME> <<EMAIL>>
* @copyright 2010-2011 <NAME> <<EMAIL>>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/// Closure
(function(a,b){var c=a.History=a.History||{},d=a.YUI;if(typeof c.Adapter!="undefined")throw new Error("History.js Adapter has already been loaded...");c.Adapter={bind:function(a,b,c){d().use("node-base",function(d){d.one(a).on(b,c)})},trigger:function(a,b){d().use("node-event-simulate",function(c){c.one(a).simulate(b)})},onDomLoad:function(a){d().use("event",function(b){b.on("domready",a)})}},typeof c.init!="undefined"&&c.init()})(window)<file_sep><?php
# Base URL
$relative_url = $_SERVER['REQUEST_URI'];
$relative_url = substr($relative_url,0,strpos($relative_url,'/history.js')).'/history.js/';
$base_url = 'http://'.$_SERVER['HTTP_HOST'].$relative_url;
$tests_url = $base_url.'tests/';
# Dirs
$dirs = array('compressed','uncompressed');
# Support
$supports = array('html5','html4');
# Adapter
$adapters = array('jquery','mootools','prototype','zepto');
<file_sep><?php
# Header
require_once(dirname(__FILE__).'/_header.php');
?><!DOCTYPE html>
<html>
<head>
<title>History.js Test Suite</title>
<style type="text/css">
body,html,iframe {
padding:0;
margin:0;
outline:none;
border:none;
}
.dir {
padding-top:1em;
}
.support {
padding-top:1em;
}
</style>
</head>
<body>
<h1>History.js Test Suite</h1>
<p>HTML5 Browsers - should pass the HTML4 and HTML5 tests</p>
<p>HTML4 Browsers - should pass the HTML4 tests and fail the HTML5 tests</p>
<?php
foreach ( $dirs as $dir ) :
echo '<div class="dir">';
foreach ( $supports as $support ) :
echo '<div class="support">';
foreach ( $adapters as $adapter ) :
echo '<div class="adapter">';
# Url
$tests_full_url = $tests_url."${dir}/${support}/${adapter}";
# Titles
$Support = strtoupper($support);
$Adapter = ucwords($adapter);
$Dir = ucwords($dir);
$title = "History.js ${Dir} ${Support} ${Adapter} Test Suite";
# Render
?><a href="<?=$tests_full_url?>"><?=$title?></a><?php
echo '</div>';
endforeach;
echo '</div>';
endforeach;
echo '</div>';
endforeach;
?>
</body>
</html>
<file_sep><?php
# Header
require_once(dirname(__FILE__).'/_header.php');
# Support
$support = isset($_GET['support']) ? $_GET['support'] : null;
if ( !in_array($support,$supports) ) {
throw new Exception('Unknown support ['.$support.']');
}
# Adapter
$adapter = isset($_GET['adapter']) ? $_GET['adapter'] : null;
if ( !in_array($adapter,$adapters) ) {
throw new Exception('Unknown adapter ['.$adapter.']');
}
# Dir
$dir = isset($_GET['dir']) ? $_GET['dir'] : null;
if ( !in_array($dir,$dirs) ) {
throw new Exception('Unknown dir ['.$dirs.']');
}
# Url
$tests_full_url = $tests_url."${dir}/${support}/${adapter}/";
# Titles
$Support = strtoupper($support);
$Adapter = ucwords($adapter);
$Dir = ucwords($dir);
$title = "History.js ${Dir} ${Support} ${Adapter} Test Suite";
# No Chache
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Expires" CONTENT="Mon, 06 Jan 1990 00:00:01 GMT" />
<meta http-equiv="PRAGMA" CONTENT="NO-CACHE" />
<meta http-equiv="CACHE-CONTROL" CONTENT="NO-CACHE" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title><?=$title?></title>
<base href="<?=$tests_url?>" />
<!-- Check -->
<script>
if ( window.document.location.href !== "<?=$tests_full_url?>" ) {
window.document.location.href = "<?=$tests_full_url?>";
}
</script>
<!-- Framework -->
<script src="../vendor/<?=$adapter?>.js"></script>
<!-- QUnit -->
<link rel="stylesheet" href="../vendor/qunit/qunit/qunit.css" type="text/css" media="screen">
<script src="../vendor/qunit/qunit/qunit.js"></script>
</head>
<body>
<!-- Elements -->
<h1 id="qunit-header"><?=$title?></h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup</div>
<button onclick="history.back()">back</button><button onclick="history.forward()">forward</button>
<textarea id="log" style="width:100%;height:400px"></textarea>
<!-- FireBug Lite -->
<script>if ( typeof window.console === 'undefined' ) { document.write('<script src=".../vendor/firebug-lite.js"><\/script>'); }</script>
<!-- JSON -->
<script>if ( typeof window.JSON === 'undefined' ) { document.write('<script src="../scripts/<?=$dir?>/json2.js"><\/script>'); }</script>
<!-- History.js -->
<script src="../scripts/<?=$dir?>/history.adapter.<?=$adapter?>.js"></script>
<script src="../scripts/<?=$dir?>/history.js"></script>
<?php if ( $support === 'html4' ) : ?>
<script src="../scripts/<?=$dir?>/history.html4.js"></script>
<?php endif; ?>
<!-- Tests -->
<script src="tests.js"></script>
</body>
</html>
| 249791bc540d6b5026af8d6ef4c9fe47080097f8 | [
"JavaScript",
"PHP"
] | 4 | JavaScript | dlarsson/history.js | 910f8ff8bfb3b9317b5d7f80d83fa310a2dad788 | 480d3081cdacecf902de5c9caa8381243afa53f5 |
refs/heads/master | <repo_name>aQuanPig/shop-mall<file_sep>/src/store/actions.js
export default {
addCart({state,commit},payload){
const old_payload = state.cartList.find(item =>{
return item.iid === payload.iid
})
if (old_payload){
commit('incrementCount',old_payload)
}else {
commit('pushCart',payload)
}
}
}
<file_sep>/src/store/getters.js
export default {
getCartLength(state){
return state.cartList.length
},
getCartCountPrice(state){
return state.cartList.filter(item=>{
return item.isCheck === true
}).reduce((preValue,nowValue)=>{
return preValue + nowValue.price * nowValue.count
},0)
}
}
<file_sep>/src/vant/index.js
import Vue from 'vue'
import { Swipe, SwipeItem, GoodsAction, GoodsActionIcon, GoodsActionButton, Checkbox, CheckboxGroup,Toast, Icon , Image as VanImage} from 'vant';
Vue.use(VanImage);
Vue.use(Icon)
Vue.use(Toast);
Vue.use(Swipe);
Vue.use(SwipeItem);
Vue.use(GoodsAction);
Vue.use(GoodsActionButton);
Vue.use(GoodsActionIcon);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
| 6b943129b2418b6bba7def4012507791fd6d4916 | [
"JavaScript"
] | 3 | JavaScript | aQuanPig/shop-mall | cf57a1002ed46b91c2ce5908d41f5f37e9a28e95 | 053bf104f1a2f3cfa87adb8880eef043ddc0db2d |
refs/heads/master | <repo_name>wbma/front-end-5-routes-login-MikKarl<file_sep>/src/app/services/media.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MediaService {
username: string;
password: string;
constructor() { }
login() {
console.log('uname: ' + this.username);
console.log('pwd: ' + this.password);
}
}
| 9f69ff9532b8534c9601382e90521b3a5b9036b1 | [
"TypeScript"
] | 1 | TypeScript | wbma/front-end-5-routes-login-MikKarl | 9f518939c4ffc47720e67b51c61a44d8cf9237d8 | 5176ab9df5cb9b9305a954d15014be4b7e4a5416 |
refs/heads/master | <file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libmill.h>
#include "server.h"
const int URI_MAXIMUM_LENGTH = 256;
const int QUERY_ARG_MAXIMUM_LENGTH = 2083 - URI_MAXIMUM_LENGTH;
const char* HTTP_PROTOCOL = "HTTP/1.1";
void parseRequestBody(tcpsock socket, Request *request) {
// TODO: read content length
// TODO: read content into request body
}
void parseRequestMethod(Request *request, char *value) {
if (!strncmp(value, "GET", 3)) {
request->HTTPMethod = HTTP_GET;
} else if (!strncmp(value, "POST", 4)) {
request->HTTPMethod = HTTP_POST;
} else if (!strncmp(value, "PUT", 3)) {
request->HTTPMethod = HTTP_PUT;
} else if (!strncmp(value, "DELETE", 6)) {
request->HTTPMethod = HTTP_DELETE;
} else if (!strncmp(value, "OPTIONS", 7)) {
request->HTTPMethod = HTTP_OPTIONS;
} else {
request->error = HTTP_INVALID_HTTP_METHOD;
}
}
void parseQueryArgs(Request *request, char *input) {
char *currentLine, *currentLineEnd, *keyValueEnd;
QueryArg *currentArg, *lastArg = NULL;
request->queryArg = NULL;
currentLine = strtok_r(input, "&", ¤tLineEnd);
while (currentLine != NULL) {
char * key, * value;
key = strtok_r(currentLine, "=", &keyValueEnd);
value = strtok_r(NULL, "=", &keyValueEnd);
if (key != NULL && value != NULL) {
currentArg = malloc(sizeof(QueryArg));
currentArg->key = calloc(strlen(key) + 1, sizeof(char));
currentArg->value = calloc(strlen(value) + 1, sizeof(char));
request->queryArgsCount = request->queryArgsCount + 1;
strcpy(currentArg->key, key);
strcpy(currentArg->value, value);
currentArg->next = NULL;
// if this is the first queryArg, then the request struct needs a pointer to the current queryArg
if (request->queryArg == NULL) {
request->queryArg = currentArg;
} else {
lastArg->next = currentArg;
}
lastArg = currentArg;
}
currentLine = strtok_r(NULL, "&", ¤tLineEnd);
}
}
Request * getRequest(tcpsock socket) {
char method[8], uri[URI_MAXIMUM_LENGTH];
Request * request = malloc(sizeof(Request));
size_t size = tcprecvuntil(socket, method, 8, " ", 1, -1);
if (errno) {
request->error = errno;
return request;
}
parseRequestMethod(request, method);
if (request->error) {
return request;
}
size = tcprecvuntil(socket, uri, URI_MAXIMUM_LENGTH, " ?", 2, -1);
if (errno) {
request->error = errno;
return request;
} else if (uri[size - 1] == '?') {
// seek the queryArgs from the socket
char queryArgs[QUERY_ARG_MAXIMUM_LENGTH];
size = tcprecvuntil(socket, queryArgs, QUERY_ARG_MAXIMUM_LENGTH, " ", 1, -1);
// parse the args into the request object
parseQueryArgs(request, queryArgs);
}
char protocol[8];
size = tcprecvuntil(socket, protocol, 8, "\r\n\r\n", 1, -1);
if (errno) {
request->error = errno;
return request;
}
request->isHTTP = !(strncmp(protocol, HTTP_PROTOCOL,5));
return request;
}
Request* parseRequest(tcpsock socket) {
Request * request = getRequest(socket);
QueryArg * current = request->queryArg;
if (request->error) {
return request;
}
if (request->HTTPMethod == HTTP_POST || request->HTTPMethod == HTTP_PUT) {
parseRequestBody(socket, request);
}
// parse other headers
return request;
}
void writeResponse(tcpsock socket, Response* r) {
char response[256];
int responseCharacters = snprintf(response, sizeof(response), "Hello World");
tcpsend(socket, response, responseCharacters, -1);
tcpflush(socket, -1);
tcpclose(socket);
}
void socketHandler(tcpsock socket, Server *server) {
Request *request = parseRequest(socket);
Response *response = NULL;
// ensure that there were no problems parsing the raw request
if (request->error) {
printf("%d\n", request->error);
response = server->errorHandler(request);
writeResponse(socket, response);
return;
}
response = server->routeHandler(request);
if (request->error) {
response = server->errorHandler(request);
}
writeResponse(socket, response);
}
void startServer(Server *server) {
int port = 5555;
char *hostAddress = NULL;
ipaddr address = iplocal(hostAddress, port, 0);
tcpsock listeningSocket = tcplisten(address);
if (!listeningSocket) {
return;
}
// accept socket connections, spawn a worker process request and call handler
while(1) {
tcpsock acceptedSocket = tcpaccept(listeningSocket, -1);
if (!acceptedSocket) {
continue;
}
go(socketHandler(acceptedSocket, server));
}
}
<file_sep>#include <libmill.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void handler(tcpsock accepted_socket, chan channel) {
// request name from connected client
tcpsend(accepted_socket, "What's your name?\r\n", 19, -1);
tcpflush(accepted_socket, -1);
// send a message to the communication channel, signifying this connection
chs(channel, int, 1);
// capture the name, and create a response message
char inbuf[256], outbuf[256];
size_t size = tcprecvuntil(accepted_socket, inbuf, sizeof(inbuf), "\r", 1, -1);
inbuf[size-1] = 0;
int rc = snprintf(outbuf, sizeof(outbuf), "Hello, %s!\r\n", inbuf);
// flush the message to the server
tcpsend(accepted_socket, outbuf, rc, -1);
cleanup:
tcpflush(accepted_socket, -1);
tcpclose(accepted_socket);
}
int test = 0;
void channel_handler(chan channel) {
while(1) {
int received_value = chr(channel, int);
test = test + 1;
}
}
int main(int argc, char *argv[]) {
int port = 5555;
if (argc > 1) {
port = atoi(argv[1]);
}
// create a communication channel
chan channel = chmake(int, 0);
go(channel_handler(channel));
// create server that listens and routes traffic to handler function
ipaddr addr = iplocal(NULL, port, 0);
tcpsock ls = tcplisten(addr);
if (!ls) {
perror("Can't open listening socket");
return 1;
}
while(1) {
tcpsock accepted_socket = tcpaccept(ls, -1);
if (!accepted_socket) {
continue;
} else {
go(handler(accepted_socket, channel));
}
// temporary stop gap :)
if (test == 3) {
break;
}
}
return 0;
}
<file_sep>#ifndef KIMAGELY_SERVER_INCLUDED
#define KIMAGELY_SERVER_INCLUDED
extern const int URI_MAXIMUM_LENGTH;
extern const int QUERY_ARG_MAXIMUM_LENGTH;
extern const char* HTTP_PROTOCOL;
typedef enum {
UNABLE_TO_LISTEN,
UNABLE_TO_ACCEPT,
HTTP_INVALID_PROTOCOL,
HTTP_INVALID_ROUTE,
HTTP_URL_TOO_LONG,
HTTP_INVALID_HTTP_METHOD,
} SERVER_ERRORS;
// create an enum + array of const char
typedef enum {
HTTP_GET,
HTTP_POST,
HTTP_PUT,
HTTP_DELETE,
HTTP_OPTIONS,
} HTTP_METHODS;
typedef struct QueryArg QueryArg;
struct QueryArg {
char * key;
char * value;
QueryArg *next;
};
typedef struct {
int length;
char ** data;
} Response;
typedef struct {
int HTTPMethod;
_Bool isHTTP;
int queryArgsCount;
QueryArg * queryArg;
int error;
//Response* (*handler)(Request *);
} Request;
typedef struct {
// logChannel
// routeTable
Response * (*errorHandler)(Request *);
Response * (*routeHandler)(Request *);
} Server;
void startServer(Server *);
#endif
<file_sep>Vagrant.configure("2") do |config|
config.vm.box = 'hashicorp/precise64'
config.vm.hostname = 'k-imagely.com'
config.vm.provider 'virtualbox' do |v|
v.memory = 512
v.cpus = 1
v.auto_nat_dns_proxy = false
v.customize ['modifyvm', :id, '--natdnsproxy1', 'off']
v.customize ['modifyvm', :id, '--natdnshostresolver1', 'off']
end
config.vm.provision :shell, inline: 'sudo apt-get update'
config.vm.synced_folder '.', '/opt/k-imagely'
config.vm.provision :docker do |d|
d.pull_images 'ubuntu'
end
end
<file_sep>CC=gcc
LIBS=-lmill
OUTPUT_DIR=.
OUTPUT=kimagely
SRC_FILES=main.c server.c router.c handlers.c
HEADER_FILES=server.h router.h handlers.h
install: $(HEADER_FILES) $(SRC_FILES)
$(CC) $(LIBS) -o $(OUTPUT_DIR)/$(OUTPUT) $(SRC_FILES)
clean:
@if [ -a $(OUTPUT_DIR)/$(OUTPUT) ] ; \
then \
rm $(OUTPUT_DIR)/$(OUTPUT); \
fi;
.PHONY: install clean
<file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libmill.h>
#include "handlers.h"
#include "server.h"
Response* errorHandler(Request * request) {
// TODO: implement error handler
printf("%s\n", "error handler goes here");
return NULL;
}
Response* routeHandler(Request * request) {
// TODO: implement router
// TODO: implement middleware here if its needed - IE: json parser?
printf("%s\n", "router");
return NULL;
}
<file_sep># K-Imagely
A microservice for comparing and contrasting images using k-means clustering.
<file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// for sleep definition
#include <unistd.h>
#include <libmill.h>
void worker(int count, const char *text) {
int i;
for (i = 0; i != count; ++i) {
printf("%s\n", text);
msleep(10);
}
}
int main(int argc, char *argv[]) {
go(worker(5, "a"));
go(worker(2, "b"));
go(worker(3, "c"));
msleep(10000000000);
return 0;
}
<file_sep>FROM debian:wheezy
MAINTAINER <NAME>
RUN apt-get update && \
apt-get install -y curl gcc make git dh-autoreconf && \
rm -rf /var/lib/apt/lists/*
# fetch, build install libmill
RUN git clone https://github.com/sustrik/libmill.git /opt/libmill && \
cd /opt/libmill && \
./autogen.sh && \
./configure && \
make && \
make check && \
make install && \
rm -rf /opt/libmill
ADD . /opt/k-imagely
RUN cd /opt/k-imagely && \
make clean && \
make install OUTPUT_DIR=/usr/local/bin
CMD ['kimagely']
<file_sep>#ifndef KIMAGELY_APP_INCLUDED
#define KIMAGELY_APP_INCLUDED
#include "server.h"
Response * errorHandler(Request*);
Response * routeHandler(Request *);
#endif
<file_sep>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libmill.h>
#include "server.h"
#include "router.h"
#include "handlers.h"
typedef enum {
INVALID_PORT,
} ERRORS;
struct Config {
char *unparsedPort;
int port;
};
// global config object
struct Config config = {
.unparsedPort = "8000",
.port = 8000,
};
int parseConfig(int argc, char **argv) {
char ** configItem = NULL;
for (int i=0; i < argc; ++i) {
char *option = argv[i];
if (configItem) {
*configItem = option;
configItem = NULL;
continue;
}
if (strncmp(option, "--port", 5) == 0) {
configItem = &config.unparsedPort;
}
}
// check validity of port
int parsedPort = atoi(config.unparsedPort);
if (parsedPort) {
config.port = parsedPort;
} else {
return INVALID_PORT;
}
return 0;
}
int main(int argc, char *argv[]) {
int err;
err = parseConfig(argc, argv);
if (err) {
return err;
}
Server server = {
.errorHandler = errorHandler,
.routeHandler = routeHandler,
};
startServer(&server);
return 0;
}
<file_sep>#ifndef KIMAGELY_ROUTER
#define KIMAGELY_ROUTER
// TODO expand this in the future to hammer out details of response ...
typedef int (*RequestHandler)();
#endif
| 052137f2debaa1d286ba0fd04d7f3be2db42dbd0 | [
"Ruby",
"Markdown",
"Makefile",
"C",
"Dockerfile"
] | 12 | C | jonmorehouse/k-imagely | 223ad8ec5e7a58aa955dbd0d8831e3a3d232c3bf | dadd7da1f124b061ef1a558a0ff2b6ed58f4551a |
refs/heads/master | <file_sep>var five = require("johnny-five");
var board = new five.Board();
board.on("ready", function() {
var buttons = {
rock: new five.Button(2),
paper: new five.Button(3),
scissors: new five.Button(4)
};
var lcd = new five.LCD({
pins: [ 7, 8, 9, 10, 11, 12 ]
});
var gameOverLED = new five.Led( 13 );
var losers = {
rock: "scissors",
paper: "rock",
scissors: "paper"
};
var choices = Object.keys( losers );
var waiting = false;
var computerPoints = 0;
var playerPoints = 0;
var totalTurns = 5;
var isGameOver = false;
var points = {};
choices.forEach(function( buttonName ) {
var button = buttons[ buttonName ];
button.on( "up", function() {
turn( buttonName );
});
});
reset();
function computerChoice() {
return choices[ Math.floor( Math.random() * choices.length ) ];
}
function reset() {
points = {
player: 0,
computer: 0
};
isGameOver = false;
}
function turn( player ) {
if ( waiting ) { return; }
gameOverLED.off();
waiting = true;
var computer = computerChoice();
if ( player !== computer ) {
points[ playerIsWinner( player, computer ) ? "player" : "computer" ]++;
}
updateScoreboard( player, computer );
waiting = false;
if ( points.player > 3 || points.computer > 3 ) {
gameOver();
}
}
function playerIsWinner( playerChoice, computerChoice ) {
return losers[ computerChoice ] !== playerChoice;
}
function updateScoreboard( playerChoice, computerChoice ) {
lcd.clear();
lcd.print( "Robot : " + points.computer + " : " +
computerChoice.substr(0, 1).toUpperCase() );
lcd.setCursor( 0, 1 );
lcd.print( "Human : " + points.player + " : " +
playerChoice.substr(0, 1).toUpperCase() );
}
function gameOver() {
lcd.clear();
lcd.print(
points.computer > points.player ?
'ROBOT WINS' :
'HUMAN WINS'
);
gameOverLED.on();
reset();
}
board.repl.inject({
buttons: buttons,
lcd: lcd,
gameOverLED: gameOverLED
})
});<file_sep>johnny-five-projects
====================<file_sep>var five = require("johnny-five");
var board = new five.Board();
board.on("ready", function() {
var joystick = new five.Joystick({
// Joystick pins are an array of pins
// Pin orders:
// [ up, down, left, right ]
// [ ud, lr ]
pins: [ "A0", "A1" ],
freq: 500
});
var lc = new five.LedControl({
pins: {
data: 2,
clock: 3,
cs: 4
},
devices: 1,
isMatrix: true
});
lc.on( 0 );
lc.brightness( 0, 50 );
lc.clear( 0 );
var currentRow = 0;
var currentCol = 0;
var maxRow = 7;
var maxCol = 7;
setDot();
joystick.on( "axismove", function() {
var x = this.fixed.x;
var y = this.fixed.y;
if ( x > 0.6 ) {
currentCol = currentCol === 7 ? 0 : ( currentCol + 1 );
}
if ( x < 0.4 ) {
currentCol = currentCol === 0 ? 7 : ( currentCol - 1 );
}
if ( y > 0.6 ) {
currentRow = currentRow === 0 ? 7 : ( currentRow - 1 );
}
if ( y < 0.4 ) {
currentRow = currentRow === 7 ? 0 : ( currentRow + 1 );
}
setDot();
});
function setDot() {
var val;
lc.clear( 0 );
for ( var row = 0; row <= maxRow; row++ ) {
if ( row === currentRow ) {
val = 1 << ( maxCol - currentCol );
} else {
val = 0;
lc.row( 0, row, 0 );
}
process.nextTick(function() { lc.row( 0, row, val ); });
}
}
board.repl.inject({
lc: lc
});
}); | 49c6cc04c410761d02e6b506f76650c9c1b9dcf2 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | rmurphey/johnny-five-projects | 2151c27e5b20731ebc5490f4e127256eded14297 | b60f9e5030777ac20d2822aea7dce0a80b56bff7 |
refs/heads/master | <repo_name>cluntraru/computer-networks<file_sep>/tema3/src/arp_poison.py
import argparse
import scapy.all as scp
import os
#import netifaces
import signal
import sys
import threading
import time
#ARP Poison parameters
packet_count = 1000
#Given an IP, get the MAC. Broadcast ARP Request for a IP Address. Should recieve
#an ARP reply with MAC Address
def get_mac(ip_address):
#ARP request is constructed. sr function is used to send/ receive a layer 3 packet
resp, unans = scp.srp(scp.Ether(dst="ff:ff:ff:ff:ff:ff")/scp.ARP(pdst=ip_address), timeout = 2)
# resp, unans = sr(ARP(op=1, hwdst="ff:ff:ff:ff:ff:ff", pdst=ip_address), retry=2, timeout=10)
for s,r in resp:
return r[scp.ARP].hwsrc
return None
#Keep sending false ARP replies to put our machine in the middle to intercept packets
#This will use our interface MAC address as the hwsrc for the ARP reply
def arp_poison(gateway_ip, gateway_mac, target_ip, target_mac):
while True:
arp_gateway = scp.ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip)
scp.send(arp_gateway)
arp_target = scp.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip)
scp.send(arp_target)
arp_gateway_mac = scp.ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, hwsrc="FB:65:DD:8E:34:90")
arp_gateway_mac.display()
scp.send(arp_gateway_mac)
arp_target_mac = scp.ARP(op=2, pdst=target_ip, hwdst=target_mac, hwsrc="FB:65:DD:8E:34:90")
arp_target_mac.display()
scp.send(arp_target_mac)
time.sleep(2)
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target-ip", dest = "target_ip")
parser.add_argument("-g", "--gateway-ip", dest = "gateway_ip")
args = parser.parse_args()
#gateway_ip = netifaces.gateways()['default'][netifaces.AF_INET][0]
target_ip = args.target_ip
gateway_ip = args.gateway_ip
#Start the script
print("[*] Starting script: arp_poison.py")
print("[*] Enabling IP forwarding")
#Enable IP Forwarding on a mac
os.system("sysctl -w net.ipv4.ip_forward=1")
print(f"[*] Gateway IP address: {gateway_ip}")
print(f"[*] Target IP address: {target_ip}")
gateway_mac = get_mac(gateway_ip)
if gateway_mac is None:
print("[!] Unable to get gateway MAC address. Exiting..")
sys.exit(0)
else:
print(f"[*] Gateway MAC address: {gateway_mac}")
target_mac = get_mac(target_ip)
if target_mac is None:
print("[!] Unable to get target MAC address. Exiting..")
sys.exit(0)
else:
print(f"[*] Target MAC address: {target_mac}")
arp_poison(gateway_ip, gateway_mac, target_ip, target_mac)
<file_sep>/tema3/src/tcp_client.py
# TCP client
import socket
import logging
import time
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--server', dest = 'server_addr')
args = parser.parse_args()
logging.basicConfig(format = u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.NOTSET)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 10000
server_address = (args.server_addr, port)
mesaj = sys.argv[0]
try:
logging.info('Handshake cu %s', str(server_address))
sock.connect(server_address)
time.sleep(15)
sock.send("Client - OK")
data = sock.recv(1024)
logging.info('Content primit: "%s"', data)
finally:
logging.info('closing socket')
sock.close()
<file_sep>/tema3/src/arp.py
import scapy.all as scp
import socket
#socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM),
# 35099, struct.pack('256s', iface))[20:24])
eth = scp.Ether(dst = "ff:ff:ff:ff:ff:ff")
arp = scp.ARP(pdst = "172.16.17.32/16")
ans, unans = scp.srp(eth / arp, timeout = 2)
print(" IP -- MAC")
for send, recv in ans:
print recv.sprintf(r"%ARP.psrc% -- %Ether.src%")
<file_sep>/script.py
import sys
import logging
def afiseaza(ceva = 'salut'):
for it, elem in enumerate(ceva):
if it % 2 == 1:
print elem
# logging.basicConfig(format = u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',
# level = logging.NOTSET)
# logging.info("Mesaj de informare")
# logging.warn("Mesaj de warning")
# logging.error("Mesaj de eroare")
def main():
afiseaza(sys.argv[1])
if __name__ == '__main__':
main()
<file_sep>/client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = 10000
address = 'localhost'
server_address = (address, port)
s.sendto('hi', server_address)
data, from_address = s.recvfrom(4)
print data
print from_address
s.close()
<file_sep>/server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = 10000
address = 'localhost'
server_address = (address, port)
s.bind(server_address)
data, from_address = s.recvfrom(2)
print data
print from_address
sent_bytes = s.sendto('receipt done', from_address)
print sent_bytes
s.close()
| e16edcdd645171ed9b2559e5c203b9ef89deea48 | [
"Python"
] | 6 | Python | cluntraru/computer-networks | 8eb14c1460f8c95c385dafc38265cd4ddbf65479 | 7aa87529fc1e70985650919b967967b72b07de50 |
refs/heads/master | <repo_name>AhmetFurkanDEMIR/COVID-19-Detection-Classification<file_sep>/README.md




# COVID-19 Detection-Classification
* Bu projemizde 1270 Bilgisayarlı tomografi verisi (Akciğer) ile COVID-19 tespiti yapan model geliştirdik.
* Verilerin tüm telif hakları medRxiv ve bioRxiv'e aittir.
# Eğitim ve Doğrulama Başarımı

# Eğitim ve Doğrulama Kaybı

# Testler






<file_sep>/Test/test_network.py
from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import argparse
import imutils
import cv2
import os
"""
python test_network.py --model asd.h5 \
--image resima_di.png
"""
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True,
help="path to trained model model")
ap.add_argument("-i", "--image", required=True,
help="path to input image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
orig = image.copy()
# pre-process the image for classification
image = cv2.resize(image, (150, 150))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
print("[INFO] loading network...")
model = load_model(args["model"])
if model.predict(image) >=0.5:
label = "COVID-19"
a = 100 * model.predict(image)[0][0]
else:
label = "HEALTY"
a = (1-model.predict(image)[0][0]) * 100
os.system("clear")
proba = model.predict(image)
label = "{}: {:.2f}%".format(label, a)
output = imutils.resize(orig, width=400)
cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0, 255, 0), 2)
cv2.imshow("Output", output)
cv2.waitKey(0)
<file_sep>/main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# veri çeşitlendirme
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
# eniyileme
from keras import optimizers
# CNN katmanları
from keras.layers import Conv2D
# model tanımlamak
from keras.models import Sequential
# enbüyükleri biriktirme
from keras.layers import MaxPooling2D
# çıktı boyutunu düzenleme
from keras.layers import Flatten
# tamamen bağlı katman
from keras.layers import Dense
# iletim sönümü
from keras.layers import Dropout
# kayıpları ve başarımı görselleştirme
import matplotlib.pyplot as plt
from time import sleep as sl
# matris işlemleri
import numpy as np
# klasör ve işletim sistemi
import os, shutil
# --- modeli GPU üzerinden eğitiyoruz --- #
# tensrflow ve kerasın GPU versiyonu gerekli
# Nvdia GPU
# CUDA
# cuDNN
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# cpu üzerinden eğitimi gerçekleştirmek isterseni "-1" yapın
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
# ----------- veri ön işleme (veri klasör yollarını kodda tanımlama) ----------- #
# Test veri seti klasörü
train_dir = os.path.join("Train")
# Doğrulama veri seti klasörü
validation_dir = os.path.join("Validation")
# Test veri seti klasörü
test_dir = os.path.join("Test")
# Eğitim veri setinde sağlıklı veriler
train_healthy_dir = os.path.join(train_dir,"healthy")
# Eğitim veri setinde covid-19 veriler
train_infected_dir = os.path.join(train_dir,"infected")
# Doğrulama veri setinde sağlıklı veriler
validation_healthy_dir = os.path.join(validation_dir,"healthy")
# Doğrulama veri setinde covid-19 veriler
validation_infected_dir = os.path.join(validation_dir,"infected")
# Test veri setinde sağlıklı veriler
test_healthy_dir = os.path.join(test_dir,"healthy")
# Test veri setinde covid-19 veriler
test_infected_dir = os.path.join(test_dir,"infected")
os.system("clear")
# --- Veri seti çeşitlendirme --- #
# veri çeşitlendirme
train_datagen = ImageDataGenerator(
# resim pixellerini 0,1 arasına sıkıştırma
rescale=1./255,
# derece cinsinden (0-180) resimlerin rastgele döndürülme açısı
rotation_range=40,
# resimlerin yatayda ve dikeyde kaydırılma oranları
width_shift_range=0.2,
# resimlerin yatayda ve dikeyde kaydırılma oranları
height_shift_range=0.2,
# burkma işlemi
shear_range=0.2,
# yakınlaştırma işlemi
zoom_range=0.2,
# dikeyde resim döndürme
horizontal_flip=True,
# işlemlerden sonra ortaya çıkan fazla
# görüntü noktalarının nasıl doldurulacağını belirler
fill_mode='nearest')
# test resimlerinde çeşitlendirme yapmıyoruz.
test_datagen = ImageDataGenerator(rescale=1./255)
# çeşitlendirilmiş verileri kullanmak (eğitim)
train_generator = train_datagen.flow_from_directory(
# hedef dizin
train_dir,
# tüm resimler (150x150) olarak boyutlandırılacak
target_size=(150, 150),
# yığın boyutu
batch_size=20,
# binary_crossentropy kullandığımız için
# ikili etiketler gerekiyor.
class_mode='binary')
# verileri kullanmak (doğrulama)
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
sl(5)
# --- Modelimiz ve sinir ağlarımız --- #
# modelimizi tanımladık
model = Sequential()
# evrişimli sinir ağı,
# alacağı resim boyutu = (150,150,3)
# filitreler 3x3 boyutuna sahip
# 32 boyutlı CNN
model.add(Conv2D(32, (3,3), activation="elu", input_shape=(150,150,3)))
# en büyükleri biriktirmek.
# her MaxPooling katmanından sonra nitelik haritalarının boyutu yarıya düşer.
# girdi nitelik haritasından pencereler çıkarıp her kanalın en büyük değerini almaktır.
model.add(MaxPooling2D(2,2))
# evrişimli sinir ağı
model.add(Conv2D(64, (3,3), activation="elu"))
# en büyükleri biriktirme
model.add(MaxPooling2D(2,2))
# evrişimli sinir ağı
model.add(Conv2D(128, (3,3), activation="elu"))
# en büyükleri biriktirme
model.add(MaxPooling2D(2,2))
# evrişimli sinir ağı
model.add(Conv2D(256, (3,3), activation="elu"))
# en büyükleri biriktirme
model.add(MaxPooling2D(2,2))
# evrişimli sinir ağı
model.add(Conv2D(256, (3,3), activation="elu"))
# en büyükleri biriktirme
model.add(MaxPooling2D(2,2))
# 3B çıktıları 1B vektörlere düzenler
model.add(Flatten())
# tamamen bağlı katmanlar
model.add(Dense(512, activation="elu"))
# iletim sönümü :
# modelin aşırı uydurma yapmasını engeller.
# Sinir ağlarının düzleştirilmesinde kullanılır.
# verdiğimiz orana göre elemanları sıfırlar.
model.add(Dropout(0.6))
# fonksiyonu sigmoid olarak kullanarak çıkan değeri [0,1] arasına sıkıştırdık
# çünki ikili sınıflandırma var (hasta, sağlıklı)
model.add(Dense(1,activation="sigmoid"))
# --- modeli derleme ve eğitme --- #
# modeli derleme aşaması
model.compile(loss='binary_crossentropy', # kayıp fonksiyonu
# eniyileme:
# ağımızın girdisi olan veri ile oluşturduğu kaybı göz önünde
# bulundurarak kendisini güncelleme mekanizması
optimizer=optimizers.RMSprop(lr=2e-5),
# eğitim ve test süresince takip edilecek metrikler.
metrics=['acc'])
# modeli eğitme aşaması
history = model.fit_generator( # acc, loss, val_acc, val_loss değerlerini history adlı değişkenden alacağız.
# eğitim verileri
train_generator,
# döngü bitene kadar geçeceği örnek sayısı (alınacak yığın)
steps_per_epoch=175,
# döngü sayısı
epochs=150,
# doğrulama verisi
validation_data=validation_generator,
# doğrulama için yığın sayısı
validation_steps=75,
verbose=2)
# modelimizi test için kaydettik.
model.save('asd.h5')
# --- sonuçları görselleştirme --- #
# Eğitim başarım skoru
acc = history.history["acc"]
# doğrulama başarım skoru
val_acc = history.history["val_acc"]
# eğitim kayıp skoru
loss = history.history["loss"]
# doğrulama kayıp skoru
val_loss = history.history["val_loss"]
# epochs sayısına göre grafik çizdireceğiz.
epochs = range(1, len(acc) + 1)
# eğitim başarımını kendine özel çizdirdik.
plt.plot(epochs, acc, "bo", label="Eğitim başarımı")
# doğrulama başarımını kendine özel çizdirdik.
plt.plot(epochs, val_acc, "b", label="Doğrulama başarımı")
# çizdirmemizin başlığı
plt.title("Eğitim ve doğrulama başarımı")
plt.legend()
plt.figure()
# eğitim kaybını kendine özel çizdirdik.
plt.plot(epochs, loss, "bo", label="Eğitim kaybı")
# doğrulama kaybını kendine özel çizdirdik.
plt.plot(epochs, val_loss, "b", label="Doğrulama kaybı")
# çizdirmemizin başlığı
plt.title("Eğitim ve doğrulama kaybı")
plt.legend()
# ekrana çıkartma
plt.show()
| 6d3e2488f674e25649796c8d35e445e4f4920362 | [
"Markdown",
"Python"
] | 3 | Markdown | AhmetFurkanDEMIR/COVID-19-Detection-Classification | f4380c1df725cb98d1bdc6f5262be4ff64b99a99 | c0c188f7a2e6f33fcf1b21da4d102e7ca91bea08 |
refs/heads/master | <file_sep>#define PACKAGE_GPC_TOOL 1
#ifdef PACKAGE_GPC_TOOL
#include <stdio.h>
#include <fc/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <fc/exception/exception.hpp>
#include <string>
#include <iostream>
#include <fstream>
#include <uvm/uvm_api.h>
#include <fc/io/json.hpp>
#include <fc/io/varint.hpp>
#include <boost/uuid/sha1.hpp>
#include <vector>
#include <map>
using namespace std;
struct CodeInfo {
std::vector<std::string> api;
std::vector<std::string> offline_api;
std::vector<std::string> event;
std::map<std::string, uint32_t> storage_properties_types;
std::map<std::string, std::vector<uint32_t>> api_args_types;
};
UvmModuleByteStream::UvmModuleByteStream()
{
is_bytes = false;
contract_level = CONTRACT_LEVEL_TEMP;
contract_state = CONTRACT_STATE_VALID;
}
UvmModuleByteStream::~UvmModuleByteStream()
{
contract_apis.clear();
offline_apis.clear();
contract_emit_events.clear();
}
//FC_REFLECT(::CodeInfo,
//(api)
//(offline_api)
//(event)
//(storage_properties_types)
//(api_args_types)
//)
struct GpcBuffer
{
std::vector<unsigned char> data;
size_t pos = 0;
bool eof() const { return pos >= data.size(); }
size_t size() const { return data.size(); }
};
int gpcread(void* ptr, size_t element_size, size_t count, GpcBuffer* gpc_buffer)
{
if (!ptr)
return 0;
if (gpc_buffer->eof() || ((gpc_buffer->data.size() - gpc_buffer->pos) < element_size))
return 0;
if (element_size*count <= (gpc_buffer->data.size() - gpc_buffer->pos))
{
memcpy(ptr, gpc_buffer->data.data() + gpc_buffer->pos, element_size*count);
gpc_buffer->pos += element_size*count;
return count;
}
size_t available_count = (gpc_buffer->data.size() - gpc_buffer->pos) / element_size;
memcpy(ptr, gpc_buffer->data.data() + gpc_buffer->pos, element_size * available_count);
gpc_buffer->pos += element_size * available_count;
return available_count;
}
int gpcwrite(const void* ptr, size_t element_size, size_t count, GpcBuffer* gpc_buffer)
{
if (!ptr)
return 0;
if (element_size * count > (gpc_buffer->data.size() - gpc_buffer->pos))
{
gpc_buffer->data.resize(gpc_buffer->pos + element_size * count);
}
memcpy(gpc_buffer->data.data() + gpc_buffer->pos, ptr, element_size*count);
gpc_buffer->pos += element_size * count;
return count;
}
int common_fread_int(GpcBuffer* fp, int* dst_int)
{
int ret;
unsigned char uc4, uc3, uc2, uc1;
ret = (int)gpcread(&uc4, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcread(&uc3, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcread(&uc2, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcread(&uc1, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
*dst_int = (uc4 << 24) + (uc3 << 16) + (uc2 << 8) + uc1;
return 1;
}
int common_fread_octets(GpcBuffer* fp, void* dst_stream, int len)
{
return (int)gpcread(dst_stream, len, 1, fp);
}
int common_fwrite_stream(GpcBuffer* fp, const void* src_stream, int len)
{
return (int)gpcwrite(src_stream, len, 1, fp);
}
int common_fwrite_int(GpcBuffer* fp, const int* src_int)
{
int ret;
unsigned char uc4, uc3, uc2, uc1;
uc4 = ((*src_int) & 0xFF000000) >> 24;
uc3 = ((*src_int) & 0x00FF0000) >> 16;
uc2 = ((*src_int) & 0x0000FF00) >> 8;
uc1 = (*src_int) & 0x000000FF;
ret = (int)gpcwrite(&uc4, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcwrite(&uc3, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcwrite(&uc2, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
ret = (int)gpcwrite(&uc1, sizeof(unsigned char), 1, fp);
if (ret != 1)
return ret;
return 1;
}
int save_code_to_file(const std::string& name, UvmModuleByteStream *stream, char* err_msg)
{
boost::uuids::detail::sha1 sha;
unsigned int digest[5];
UvmModuleByteStream* p_new_stream = new UvmModuleByteStream();
if (nullptr == p_new_stream)
{
strcpy(err_msg, "malloc UvmModuleByteStream fail");
return -1;
}
p_new_stream->is_bytes = stream->is_bytes;
p_new_stream->buff = stream->buff;
for (int i = 0; i < stream->contract_apis.size(); ++i)
{
int new_flag = 1;
for (int j = 0; j < stream->offline_apis.size(); ++j)
{
if (stream->contract_apis[i] == stream->offline_apis[j])
{
new_flag = 0;
continue;
}
}
if (new_flag)
{
p_new_stream->contract_apis.push_back(stream->contract_apis[i]);
}
}
p_new_stream->offline_apis = stream->offline_apis;
p_new_stream->contract_emit_events = stream->contract_emit_events;
p_new_stream->contract_storage_properties = stream->contract_storage_properties;
p_new_stream->contract_id = stream->contract_id;
p_new_stream->contract_name = stream->contract_name;
p_new_stream->contract_level = stream->contract_level;
p_new_stream->contract_state = stream->contract_state;
FILE *f = fopen(name.c_str(), "wb");
if (nullptr == f)
{
delete (p_new_stream);
strcpy(err_msg, strerror(errno));
return -1;
}
GpcBuffer gpc_buffer;
gpc_buffer.pos = 0;
sha.process_bytes(p_new_stream->buff.data(), p_new_stream->buff.size());
sha.get_digest(digest);
for (int i = 0; i < 5; ++i)
common_fwrite_int(&gpc_buffer, (int*)&digest[i]);
int p_new_stream_buf_size = (int)p_new_stream->buff.size();
common_fwrite_int(&gpc_buffer, &p_new_stream_buf_size);
p_new_stream->buff.resize(p_new_stream_buf_size);
common_fwrite_stream(&gpc_buffer, p_new_stream->buff.data(), p_new_stream->buff.size());
int contract_apis_count = (int)p_new_stream->contract_apis.size();
common_fwrite_int(&gpc_buffer, &contract_apis_count);
for (int i = 0; i < contract_apis_count; ++i)
{
int api_len = p_new_stream->contract_apis[i].length();
common_fwrite_int(&gpc_buffer, &api_len);
common_fwrite_stream(&gpc_buffer, p_new_stream->contract_apis[i].c_str(), api_len);
}
int offline_apis_count = (int)p_new_stream->offline_apis.size();
common_fwrite_int(&gpc_buffer, &offline_apis_count);
for (int i = 0; i < offline_apis_count; ++i)
{
int offline_api_len = p_new_stream->offline_apis[i].length();
common_fwrite_int(&gpc_buffer, &offline_api_len);
common_fwrite_stream(&gpc_buffer, p_new_stream->offline_apis[i].c_str(), offline_api_len);
}
int contract_emit_events_count = p_new_stream->contract_emit_events.size();
common_fwrite_int(&gpc_buffer, &contract_emit_events_count);
for (int i = 0; i < contract_emit_events_count; ++i)
{
int event_len = p_new_stream->contract_emit_events[i].length();
common_fwrite_int(&gpc_buffer, &event_len);
common_fwrite_stream(&gpc_buffer, p_new_stream->contract_emit_events[i].c_str(), event_len);
}
int contract_storage_properties_count = p_new_stream->contract_storage_properties.size();
common_fwrite_int(&gpc_buffer, &contract_storage_properties_count);
for (const auto& storage_info : p_new_stream->contract_storage_properties)
{
int storage_len = storage_info.first.length();
common_fwrite_int(&gpc_buffer, &storage_len);
common_fwrite_stream(&gpc_buffer, storage_info.first.c_str(), storage_len);
int storage_type = storage_info.second;
common_fwrite_int(&gpc_buffer, &storage_type);
}
fwrite(gpc_buffer.data.data(), gpc_buffer.pos, 1, f);
fclose(f);
delete (p_new_stream);
return 0;
}
int main(int argc,char** argv)
{
try{
if (argc < 3)
{
perror("No enough params\n");
return 0;
}
boost::filesystem::path code_file(argv[1]);
boost::filesystem::path codeinfo_file(argv[2]);
if (!boost::filesystem::exists(code_file) || !boost::filesystem::exists(codeinfo_file)) {
perror("the file not exist!\n");
return 1;
}
string out_filename = code_file.string();
size_t pos;
pos = code_file.string().find_last_of('.');
if ((pos != string::npos))
{
out_filename = code_file.string().substr(0, pos) + ".gpc";
}
else
{
perror("contract source file name should end with .lua or .uvm\n");
return 1;
}
std::ifstream file(code_file.string().c_str(), std::ifstream::binary);
file.seekg(0, file.end);
auto length = file.tellg();
UvmModuleByteStream* p_new_stream = new UvmModuleByteStream();
if (p_new_stream == nullptr)
{
perror("Create UvmModuleByteStream Failed\n");
return 1;
}
p_new_stream->buff.resize(length);
file.seekg(0, file.beg);
file.read(p_new_stream->buff.data(), length);
file.close();
std::ifstream meta_file(codeinfo_file.string().c_str(), std::ifstream::binary);
meta_file.seekg(0, meta_file.end);
auto metafile_length = meta_file.tellg();
std::vector<char> metafile_chars(metafile_length);
meta_file.seekg(0, meta_file.beg);
meta_file.read(metafile_chars.data(), metafile_length);
meta_file.close();
auto metajson = fc::json::from_string(std::string(metafile_chars.begin(), metafile_chars.end()), fc::json::legacy_parser).as<fc::mutable_variant_object>();
const auto& info_apis = metajson["api"].as<fc::variants>();
for (size_t i = 0; i < info_apis.size(); i++)
{
p_new_stream->contract_apis.push_back(info_apis[i].as_string());
}
const auto& info_events = metajson["event"].as<fc::variants>();
for (size_t i = 0; i < info_events.size(); i++)
{
p_new_stream->contract_emit_events.push_back(info_events[i].as_string());
}
const auto& info_offline_apis = metajson["offline_api"].as<fc::variants>();
for (size_t i = 0; i < info_offline_apis.size(); i++)
{
p_new_stream->offline_apis.push_back(info_offline_apis[i].as_string());
}
const auto& info_api_args_types = metajson["api_args_types"].as<fc::variants>();
for (auto it = info_api_args_types.begin(); it != info_api_args_types.end();it++)
{
const auto& items = it->as<fc::variants>();
const auto& item_values = items[1].as<fc::variants>();
vector<UvmTypeInfoEnum> vec;
for (auto it2 = item_values.begin(); it2 != item_values.end(); it2++) {
fc::unsigned_int type_it = it2->as_int64();
vec.push_back((UvmTypeInfoEnum)type_it);
}
p_new_stream->contract_api_arg_types.insert(std::make_pair(items[0].as_string(), vec));
}
const auto& info_storage_properties = metajson["storage_properties_types"].as<fc::variants>();
for (auto it = info_storage_properties.begin(); it != info_storage_properties.end(); it++)
{
const auto& items = it->as<fc::variants>();
auto value = items[1].as_int64();
p_new_stream->contract_storage_properties[items[0].as_string()] = (fc::unsigned_int) value;
}
if (save_code_to_file(out_filename, p_new_stream, nullptr) < 0)
{
delete p_new_stream;
p_new_stream = nullptr;
perror("save bytecode to gpcfile failed");
return 1;
}
if (p_new_stream)
delete p_new_stream;
printf("%s\n", out_filename.c_str()) ;
return 0;
}
catch (std::exception &e)
{
printf(e.what());
printf("Unknown Error\n");
}
}
#endif<file_sep>cmake_minimum_required(VERSION 3.5)
project(package_gpc)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES
pack_gpc.cpp
)
include_directories(./uvm/include ../jsondiff/jsondiff-cpp/include ../fc/include /usr/local/lib/boost/include)
link_directories(../fc /usr/local/lib/boost/lib)
link_libraries(fc boost_system boost_system boost_chrono boost_date_time boost_coroutine boost_context boost_thread boost_filesystem pthread)
add_executable(package_gpc ${SOURCE_FILES})
<file_sep>uvm_package_gpc
===================
tool to package uvm bytecode and contract metadata to one file
# Dependencies
* boost 1.55
* https://github.com/cryptonomex/fc
* https://github.com/BlockLink/jsondiff-cpp
* `git submodule update --init --recursive`
# Usage
* `cmake .` and `make` to build
* package_gpc path-to-uvm-bytecode-file path-to-contract-metadata-file
| 2a69517b516b9aee822bf1a8497eda629abe4fe2 | [
"Markdown",
"CMake",
"C++"
] | 3 | C++ | Whitecoin-XWC/uvm_package_gpc | 20097ba052bd1e501fe0d7e87c6a4bc174d819d9 | 1798042d41f011c8c388892675f9b36b9e6d5826 |
refs/heads/master | <file_sep>var SwissArmyKnife = (function() {
'use strict';
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
var retina;
var baseURL = "assets/reg/";
var browserType = "";
function determineScreenDPI()
{
retina = window.devicePixelRatio > 1 ? true : false;
//alert( retina )
if( retina == true )
{
baseURL = "assets/retina/";
}
}
function getBaseURL()
{
return baseURL;
}
function doesDeviceSupportTouch() {
return !!('ontouchstart' in window);
}
// wrappers for events diff between ie and every other browser.
function addEvent( evnt , elem , func)
{
evnt = evnt.replace('on','');
if(func)
{
if(elem.addEventListener)
{
elem.addEventListener(evnt,func,false);
}
else if(elem.attachEvent)
{
elem.attachEvent("on"+evnt,func);
}
}
}
function removeEvent( evnt , elem , func )
{
evnt = evnt.replace('on','');
if(func)
{
if(elem.addEventListener)
{
elem.removeEventListener(evnt,func,false);
}
else if(elem.attachEvent)
{
elem.detachEvent("on"+evnt,func);
}
}
}
function isIE()
{
var isIe = !!window.ActiveXObject;
//alert( isIe + "is IE boolean ")
return isIe;
}
function setBackground( displayItem , imageURL )
{
displayItem.style.background ='url(' + imageURL + ')';
}
function browserWidth()
{
return window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
}
function browserHeight()
{
return window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
}
function init()
{
determineScreenDPI();
isIE();
}
init();
// Because I don't have public variables, I can just return an object instead
// of an object api var. Whether you return an object api var or just return
// an object, it's the same thing and a matter of preference.
return {
// public functions
getBaseURL: getBaseURL,
doesDeviceSupportTouch: doesDeviceSupportTouch,
addEvent: addEvent,
removeEvent: removeEvent,
browserWidth: browserWidth,
browserHeight: browserHeight,
isIE: isIE,
setBackground: setBackground,
// public vars
retina: retina
};
})();<file_sep>var MyClass = function () {
'use strict';
var scope = this;
var publicVar = 'Public for tracing sakes';
var privateVar = 'Private';
function publicMethodFoo()
{
console.log('publicMethodFoo() has been called');
console.log('publicVar : ' + publicVar );
};
//
function privateMethod()
{
console.log('privateVar: ' + privateVar);
publicMethodFoo();
}
function setPrivateVar( string )
{
privateVar = string
}
function setPublicVar( string )
{
publicVar = string
}
return {
// return getter and setter methods, no varibales, variables are accessible through getter and setter funtion listed in the return object ONLY!
privateMethod: privateMethod,
setPrivateVar: setPrivateVar,
setPublicVar: setPublicVar,
};
}
<file_sep>function MyClass() {
// Reference to "this" classes. This will be used internally only when
// attempting to reference any public methods or properties.
var scope = this;
// This is public because I'm attaching it to 'this' class.
this.publicVar = 'Public';
// This is private because I'm not attaching it to "this" class.
var privateVar = 'Private';
// This is public because I'm attaching it to 'this' class.
this.publicMethod = function() {
console.log('publicMethod() has been called');
privateMethod();
};
// This is public because I'm attaching it to 'this' class.
this.publicMethodFoo = function() {
console.log('publicMethodFoo() has been called');
};
// This is private because I'm not attaching it to "this" class.
function privateMethod() {
// I want to call the public method. I could just do this.publicMethodFoo()
// but using "this" could cause some scoping issues. It's cleaner to
// call with "scope" instead of "this". That ensures me I'm always
// using the right context/scope.
scope.publicMethodFoo();
// I can call my public vars the same way I did with the public methods
// using the "scope".
console.log('publicVar: ', scope.publicVar);
console.log('privateVar: ', privateVar);
}
}
var myclass = new MyClass();
myclass.publicMethod();<file_sep>var HeroView = function () {
'use strict';
var scope = this;
var isOpen = false;
var isLoaded = false;
var isAllLoaded = false;
var map = {};
var pointerArr = [];
var loadedArr = [];
var dotBtnArr = [];
var rotateView;
var jsView;
var dotBtnShell;
var preload;
var loader;
var manifest;
var manifestReversed;
var w = 238; // Item width
var h = 170; // Item height
var preloadid = 0;
var manifestLength = ""
var pid = 0;
var curId = 0;
// signal pointers for events
var ourviceLoaded;
var ourviceOpened;
var ourviceClosed;
var _transformOrigin = "left bottom";
var _xpos = -1000;
var _skewY = 180;
var _transformOriginCLOSE = "left bottom";
var _skewYCLOSE = 180
var _xposCLOSE = -1000;
var delays = [ 0 , .025 , .05 , .075 , .1 , .125, .15 , .175 , .2 ];
var dragStageWidth = 0;
var dragStageHeight= 0;
var stageWidth;
var stageHeight;
var isTimerRunning = false;
var timer;
function openView()
{
if( isOpen == false && isLoaded == true )
{
curId = 0;
addEventListeners();
//console.log('public openView() has been called');
isOpen = true;
//var has3d = ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix())
//alert( has3d )
var item = pointerArr[ curId ]
TweenLite.killTweensOf( item);
TweenLite.to( item , .5 , { css:{ autoAlpha: 1 } , delay:0 , onComplete:openCompleteHandler} );
item.style.zIndex = 1;
dotBtnArr[0].style.visibility = 'visible';
setSelect( 0 );
}
}
function closeView() {
if( isOpen == true )
{
isOpen = false;
removeEventListeners();
//console.log('public closeView() has been called');
stopTimer();
var item = pointerArr[ curId ]
TweenLite.killTweensOf( item);
TweenLite.to( item , .5 , { css:{ autoAlpha: 0} , delay:0 , onComplete:closeCompleteHandler } );
}
}
function startTimer()
{
if( isTimerRunning == false )
{
//console.log( "startTimer");
isTimerRunning = true;
timer = setTimeout( nextClickSlideHandler , 8000);
}
}
function stopTimer()
{
if( isTimerRunning == true )
{
isTimerRunning = false;
//console.log( "stopTimer");
clearTimeout(timer);
}
}
function killOpenTweens()
{
var i;
for (i=0; i<manifestLength ; i++)
{
var node = pointerArr[i];
TweenLite.killTweensOf( node );
}
}
function addEventListeners()
{
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.addEvent( 'mousedown' , jsView , nextClickHandler );
}else{
SwissArmyKnife.addEvent( 'touchstart', jsView , nextClickHandler );
}
initDotBtns();
}
function removeEventListeners()
{
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.removeEvent( 'mousedown' , jsView , nextClickHandler );
}else{
SwissArmyKnife.removeEvent( 'touchstart', jsView , nextClickHandler );
}
killDotBtns();
}
function openCompleteHandler()
{
ourviceOpened.dispatch( "ourviceOpenCompleteEvent" );
startTimer();
}
function closeCompleteHandler()
{
ourviceClosed.dispatch( "ourviceCloseCompleteEvent" , pid );
}
function getIsOpen()
{
return isOpen;
}
function getIsLoaded()
{
return isLoaded;
}
function resizeEvent( w , h )
{
stageHeight = h;
stageWidth = w;
if( isOpen == true && isLoaded == true )
{
}
}
function dragEvent( valX , valY )
{
/*
if( isOpen == true && isLoaded == true )
{
var i;
var tempManifestArr = manifest;
var stageWidth = dragStageWidth;// SwissArmyKnife.browserWidth();
var stageHeight = dragStageHeight; //SwissArmyKnife.browserHeight();
for (i=0; i<manifestLength ; i++)
{
var centerX = stageWidth/2 - (manifest[i].width/2) + manifest[i].xoffset + valX + "px";
var centerY = stageHeight/2 - (manifest[i].height/2) + manifest[i].yoffset + valY + "px";
var node = pointerArr[i];
TweenLite.to( node , .2 , {css:{ left:centerX , top:centerY } , delay: delays[i] } );
}
}
*/
}
// Reset everything
function init( id ) {
pid = id;
// If there is an open preload queue, close it.
if (preload != null) { preload.close(); }
jsView = document.getElementById( "js-heroContainer" ); //$("#js-view");
dotBtnShell = document.getElementById( "js-dotBtnShell" );
// $("#mainProgress .progress").width(0);
ourviceLoaded = new signals.Signal();
ourviceOpened = new signals.Signal();
ourviceClosed = new signals.Signal();
// get mafifest from DataModelLunchBox datamodel.
manifest = DataModelLunchBox.getHeroDataById( id );
manifestReversed = cloneObject( manifest );// DataModelLunchBox.getDataById( id );
manifestReversed.reverse();
manifestLength = manifest.length;
// Create a preloader. There is no manfest added to it up-front, we will add items on-demand.
preload = new PreloadJS();
preload.onFileLoad = handleFileLoad;
preload.onProgress = handleOverallProgress;
//preload.onFileProgress = handleFileProgress;
preload.onError = handleFileError;
preload.setMaxConnections(1);
}
function initDotBtns()
{
dotBtnArr = [];
var i;
var width = 0;
var incW = 32;
for ( i=0; i<manifestLength ; i++)
{
var node = document.getElementById( "js-cbtn" + i );
dotBtnArr[i] = node;
width = width + incW;
if( isAllLoaded == true )
{
node.style.visibility = 'visible';
}
node.btnId = i;
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.addEvent( 'mousedown' , node , btnDotClickHandler );
}else
{
SwissArmyKnife.addEvent( 'touchstart' , node , btnDotClickHandler );
}
}
dotBtnShell.style.width = width+"px";
}
function killDotBtns()
{
var i;
for ( i=0; i< manifestLength ; i++)
{
var node = dotBtnArr[i];
node.style.visibility = 'hidden';
var item = pointerArr[ i ]
if( loadedArr[i] == true )
{
item.style.zIndex = (String(( pid + i ))+1)*-1;
}
// console.log( item.style.zIndex + " poop ");
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.removeEvent( 'mousedown' , node , btnDotClickHandler );
}else
{
SwissArmyKnife.removeEvent( 'touchstart' , node , btnDotClickHandler );
}
}
dotBtnShell.style.width = 0+"px";
}
function btnDotClickHandler( e )
{
if (!e) var e = window.event;
var target = (e.currentTarget) ? e.currentTarget : e.srcElement;
var id = target.btnId ;
openById( id )
setSelect( id );
}
function cloneObject(source) {
var i;
var array = []
for (i in source) {
if (typeof source[i] == 'source') {
array[i] = new cloneObject(source[i]);
}
else{
array[i] = source[i];
}
}
return array;
}
function stop() {
if (preload != null) { preload.close(); }
}
function loadAll()
{
preloadid = 0;
var i;
for (i=0; i < manifestLength ; i++)
{
loadAnother( i );
}
}
function loadAnother( id ) {
// Get the next manifest item, and load it
var item = manifest[id].image;
preload.loadFile(item);
}
// File complete handler
function handleFileLoad(event) {
// Get a reference to the loaded image (<img/>)
var img = event.result;
var div = img;
//div.addClass("completeLeft");
div.className = "heroLoaded";
div.id = "js" + preloadid+ "item" + pid ;
div.draggable = false;
//div.attr("id", "js" + preloadid+ "item" + pid );
div.style.zIndex = (String(( pid + preloadid ))+1)*-1;
//console.log( jsView.style.zIndex + " style.zIndex" )
// console.log( div.style.zIndex+ " div.style.zIndex " )
jsView.appendChild(div);
pointerArr[ preloadid ] = div; //document.getElementById( "js" + preloadid +"item" + pid );
loadedArr[ preloadid ] = true;
preloadid = preloadid +1;
// Add it to the DOM
if( preloadid == 1 )
{
isLoaded = true;
ourviceLoaded.dispatch('ourviceLoadCompleteEvent');
// dispatch evetn up to ProjectManagerView
}else{
if( isOpen == true )
{
dotBtnArr[preloadid -1].style.visibility = 'visible';
}
}
if( preloadid == manifestLength )
{
isAllLoaded = true;
}
}
function openById( id )
{
curId = id;
var item = pointerArr[ id ]
// TweenLite.killTweensOf( item );
stopTimer();
setOpacity( item , 0 );
item.style.zIndex = 1;
var i;
for ( i=0; i<manifestLength ; i++)
{
if( i != id )
{
if( loadedArr[ i ] == true )
{
var node = pointerArr[i];
TweenLite.killTweensOf( node );
node.style.zIndex = (( pid + i )+1)*-1;
node.style.visibility = "hidden";
}
}
}
TweenLite.killTweensOf( item );
TweenLite.to( item , .5 , { css:{ autoAlpha: 1 } , delay:0 , onComplete:doneTweeningHandler } );
}
function setSelect( id )
{
var i;
for ( i=0; i<manifestLength ; i++)
{
var node = dotBtnArr[i];
if( i != id )
{
node.style.backgroundPosition = "0 -31px";
}else{
node.style.backgroundPosition = "0 0px";
}
}
}
function setOpacity( testObj , value)
{
testObj.style.opacity = value;
testObj.style.filter = 'alpha(opacity=' + value + ')';
}
function doneTweeningHandler()
{
startTimer();
/// console.log( " donetweening " );
}
function nextClickHandler()
{
if( MenuView.getIsOpen() == true )
{
MenuView.closeView();
}else
{
var nextId = curId + 1;
if( nextId < manifestLength && loadedArr[ nextId ] == true)
{
openById( nextId );
setSelect( nextId );
}else if ( loadedArr[ 0 ] == true )
{
nextId = 0;
openById( nextId );
setSelect( nextId );
}
}
}
function nextClickSlideHandler()
{
var nextId = curId + 1;
if( nextId < manifestLength && loadedArr[ nextId ] == true)
{
openById( nextId );
setSelect( nextId );
}else if ( loadedArr[ 0 ] == true )
{
nextId = 0;
openById( nextId );
setSelect( nextId );
}
}
function getOurviceLoaded()
{
return ourviceLoaded;
}
function getOurviceOpened()
{
return ourviceOpened;
}
function getOurviceClosed()
{
return ourviceClosed;
}
// File progress handler
function handleFileProgress(event) {
}
// Overall progress handler
function handleOverallProgress(event) {
// FullScreenLoader.upDateProgressBar( ( preload.progress *100 ) + '%' );
}
// An error happened on a file
function handleFileError(event) {
}
function getPID()
{
return pid;
}
return {
// return getter and setter methods, no varibales, variables are accessible through getter and setter funtion listed in the return object ONLY!
openView: openView,
closeView: closeView,
resizeEvent: resizeEvent,
loadAll: loadAll,
init: init,
getIsLoaded: getIsLoaded,
getPID: getPID,
killOpenTweens: killOpenTweens,
getOurviceLoaded: getOurviceLoaded,
getOurviceOpened: getOurviceOpened,
getOurviceClosed: getOurviceClosed
};
}
<file_sep>var MenuView = (function() {
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
'use strict';
var isOpen = false;
var isTabOpen = false;
var slideContainer ;
var menuButton;
var menuOpenBtn;
var isSwipeEnabled = false;
var startDragX = 0;
var startDragY = 0;
var distanceX = 0;
var distanceY = 0;
var openWidth = 0;
var baseheight = 450;
var variableWidth = 350;
var preload;
var loader;
var manifest;
var preloadid = 0;
var isLoaded = false;
var manifestLength = 0;
var jsLogo;
var menuBtnArr = [];
var menuNameData = [];
var arrow;
function openView()
{
if( isOpen == false )
{
isOpen = true;
addEventListeners();
openWidth = ( baseheight );
// console.log( baseheight + " baseheight" )
resizeEvent( ProjectManagerView.stageWidth , ProjectManagerView.stageHeight );
TweenLite.killTweensOf( slideContainer );
//TweenLite.killTweensOf( ProjectManagerView.mainView );
TweenLite.to( slideContainer , .5 , {css:{ top:openWidth + "px" } , delay:0 } );
TweenLite.killTweensOf( arrow );
setOpacity( arrow , 0)
TweenLite.to( arrow , .2 , {css:{ opacity : 1 } , delay:.2 } );
arrow.style.backgroundPosition = "0 -39px";
}
}
function closeView()
{
if( isOpen == true )
{
isOpen = false;
removeEventListeners();
TweenLite.killTweensOf( slideContainer );
// TweenLite.killTweensOf( ProjectManagerView.mainView );
TweenLite.to( slideContainer , .5 , {css:{ top:"0px" } , delay:0 } );
TweenLite.killTweensOf( arrow );
setOpacity( arrow , 0)
TweenLite.to( arrow , .2, {css:{ opacity : 1 } , delay:.2 } );
arrow.style.backgroundPosition = "0 0px";
}
}
function addEventListeners()
{
// enableSwipeEvents();
//SwissArmyKnife.addEvent( 'mousedown' , prevBtn , prevClickHandler );
for ( var i=1; i< menuBtnArr.length ; i++)
{
var btn = menuBtnArr[ i ];
btn.pid = i;
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.addEvent( 'mousedown' , btn , btnMenuClickHandler );
}else
{
SwissArmyKnife.addEvent( 'touchstart' , btn , btnMenuClickHandler );
}
}
}
function btnMenuClickHandler( e )
{
if (!e) var e = window.event;
var target = (e.currentTarget) ? e.currentTarget : e.srcElement;
var id = target.pid ;
ProjectManagerView.updateById( id )
}
function removeEventListeners()
{
var btn = menuBtnArr[ i ];
for ( var i=0; i< menuBtnArr.length ; i++)
{
var btn = menuBtnArr[ i ];
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.removeEvent( 'mousedown' , btn , btnMenuClickHandler );
}else
{
SwissArmyKnife.removeEvent( 'touchstart' , btn , btnMenuClickHandler );
}
}
}
function setSelect( id )
{
var i;
jsLogo.innerHTML = "<font id='testWidths' ><font>WINDWARD FLUTES " + "<font id='js-menuTextFade' color='#5a5a5a' > " + DataModelLunchBox.getMenuTitleById( id ) + "</font></font> "
var tempWidth = document.getElementById('testWidths').offsetWidth
var fadeText = document.getElementById('js-menuTextFade' );
TweenLite.killTweensOf( fadeText );
setOpacity( fadeText , 0)
TweenLite.to( fadeText , .1 , {css:{ opacity : 1 } , delay:.1 } );
TweenLite.killTweensOf( arrow );
setOpacity( arrow , 0)
TweenLite.to( arrow , .1 , {css:{ opacity : 1 } , delay:.2 } );
arrow.style.left = tempWidth+ 30 +"px";
arrow.style.display = "block";
// console.log( tempWidth + " widthsss" )
for ( i=1; i< menuBtnArr.length; i++)
{
var node = menuBtnArr[ i ];
//console.log( i )
if( i != id )
{
node.style.color = "#333333";
}else{
node.style.color = "#e22a0c";
}
}
setOpacity( document.getElementById('js-menuBarWhiteBox') , DataModelLunchBox.getMenuAlphasById( id ) );
}
function setOpacity( testObj , value)
{
testObj.style.opacity = value;
testObj.style.filter = 'alpha(opacity=' + value + ')';
}
function enableSwipeEvents()
{
}
function disableSwipeEvents()
{
}
function resizeEvent( w, h )
{
if( isOpen == true )
{
var stageWidth = w;
var stageHeight = h;
}
}
function init()
{
// SwissArmyKnife.addEvent( 'mousedown', menuButton , toggleOpenViewHandler );
if( ProjectManagerView.isTouchDevice == false )
{
SwissArmyKnife.addEvent( 'mousedown' , menuOpenBtn , menuOpenClickHandler );
}else{
SwissArmyKnife.addEvent( 'touchstart', menuOpenBtn , menuOpenClickHandler );
}
}
function menuOpenClickHandler()
{
if( isOpen == false )
{
openView() ;
}else{
closeView() ;
}
}
function getIsOpen()
{
return isOpen;
}
function initDomPointers()
{
var menuDiv = document.getElementById( "js-menuBox" ).offsetHeight;
arrow = document.getElementById('js-arrow');
setOpacity( arrow , 0 )
slideContainer = document.getElementById( "js-slideShell" );
menuOpenBtn = document.getElementById( "js-menuBar" );
var shells = document.getElementById( "js-menuShell" );
shells.style.zIndex = 999;
var bar = document.getElementById( "js-heroBar" );
bar.style.zIndex = 990;
var dotMenu = document.getElementById( "js-dotBtnShell" );
dotMenu.style.zIndex = 980;
menuBtnArr = []
menuNameData = DataModelLunchBox.getMenuBtnNames();
var len = menuNameData.length;
var col0 = document.getElementById( "js-menuCol0" );
var col1 = document.getElementById( "js-menuCol1" );
var col2 = document.getElementById( "js-menuCol2" );
menuBtnArr = [ "" ];
for( var i = 0 ; i < len ; i ++ )
{
var menugroup = menuNameData[i].menugroup;
var btnDiv = document.createElement('div');
btnDiv.className = "menuTextItem";
btnDiv.id = "js-mid" + i;
btnDiv.innerHTML = menuNameData[i].btnName;
if( menugroup == "flutes" )
{
col0.appendChild( btnDiv );
}else if( menugroup == "about" )
{
col1.appendChild( btnDiv );
}else if( menugroup == "contact" )
{
col2.appendChild( btnDiv );
}
menuBtnArr.push ( btnDiv )
}
var h = document.getElementById( "js-menuBox" ).offsetHeight;
// console.log(h+ ' menuDiv');
baseheight = h+140;
jsLogo = document.getElementById( "js-logo" )
//reload();
}
function changeColor( colorObj )
{
//viewContainer.style.backgroundColor = colorObj.color0;
}
// loads stuffs
/*
// Reset everything
function reload()
{
// If there is an open preload queue, close it.
if (preload != null) { preload.close(); }
// Reset the UI
preloadid = 0;
// Push each item into our manifest
manifest = DataModelLunchBox.getMenuImageArray();
manifestLength = manifest.length;
// Create a preloader. There is no manfest added to it up-front, we will add items on-demand.
preload = new PreloadJS();
preload.onFileLoad = handleFileLoad;
preload.onProgress = handleOverallProgress;
preload.onFileProgress = handleFileProgress;
preload.onError = handleFileError;
preload.setMaxConnections(1);
loadAll()
}
function stop() {
if (preload != null) { preload.close(); }
}
function loadAll()
{
preloadid = 0;
var i;
for (i=0; i < manifestLength ; i++)
{
loadAnother( i );
}
}
function loadAnother( id ) {
// Get the next manifest item, and load it
var item = manifest[id].imageMenu;
preload.loadFile(item);
}
// File complete handler
function handleFileLoad(event) {
var div = event.result;
//div.addClass("completeLeft");
//div.className = "scroller ";
div.id = "js" + preloadid+ "menuItem" ;
//div.attr("id", "js" + preloadid+ "item" + pid );
listView.appendChild(div);
preloadid = preloadid +1;
if( preloadid == manifestLength )
{
isLoaded = true;
console.log( " menu is loaded " );
init();
}
//TweenLite.to( view , 0 , {css:{ scale:0 } , delay: 0 } );
}
// File progress handler
function handleFileProgress(event) {
//var div = map[event.src]; // Lookup the related item
//div.children("DIV").width(event.progress*div.width()); // Set the width the progress.
}
// Overall progress handler
function handleOverallProgress(event) { //http://ourvice.com/clients/ourvice/html5/assets/reg/backs.jpg
}
// An error happened on a file
function handleFileError(event) {
//alert( event );
}
*/
initDomPointers();
return {
// public functions
init: init,
resizeEvent: resizeEvent,
openView: openView,
closeView: closeView,
setSelect:setSelect,
getIsOpen:getIsOpen
// public vars
};
})();<file_sep>var MyClass = (function() {
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
console.log(this);
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
function foo() {
console.log('foo() has been called');
}
function poo() {
console.log('poo() has been called');
}
// Because I don't have public variables, I can just return an object instead
// of an object api var. Whether you return an object api var or just return
// an object, it's the same thing and a matter of preference.
return {
foo: foo,
poo: poo
};
})();
var MyClass = (function() {
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
console.log(this);
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// Everything public gets attached to the public api object.
var api = {};
// I need public variables so I have to attach to the public api.
api.name = 'Destin';
api.last = 'Young';
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
function foo() {
console.log('foo() has been called');
}
function poo() {
console.log('poo() has been called');
console.log('name: ' + api.name);
console.log('last: ' + api.last);
}
// I'm attaching my foo() and poo() methods to the api because I want them
// to be public. If I don't want them to be public I can just remove from
// the api without modifying the entire code base.
api.foo = foo;
api.poo = poo;
// Just like above I have to return an object with the methods/properties
// I want to be exposed publicly. I'm using an api object so I can return
// that. All properties and methods that have been attached are now public
// to the outside world.
return api;
})();<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Windward Flutes | Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<style type="text/css">
body {
padding-top: 0px;
padding-bottom: 40px;
}
</style>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="../assets/js/html5shiv.js"></script>
<![endif]-->
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="navbar transparent navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="index.html">Windward Flutes / <small>Contact</small></a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li><a href="index.html">Home</a></li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">Flutes <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li><a href="pratten.html">The Windward Pratten</a></li>
<li><a href="keylesspratten.html"> Keyless Pratten</a></li>
<li><a href="combo.html"> Windward Combo</a></li>
<li><a href="keyedpratten.html"> Keyed Pratten</a></li>
<li class="divider"></li>
<li><a href="windwardc.html">Windward C Flute</a></li>
</ul>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">About <b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li><a href="makers.html">The Makers</a></li>
<li><a href="design.html">Design</a></li>
<li><a href="craftsmanship.html">Craftsmanship</a></li>
<li><a href="restoration.html">Restoration & Repairs</a></li>
<li><a href="wood.html">Wood and Materials</a></li>
<li><a href="faq.html">FAQ</a></li>
</ul>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown">Contact<b class="caret"></b></a>
<ul class="dropdown-menu" role="menu">
<li class="active"><a href="contact.html">Contact Us</a></li>
<li><a href="order.html">Order & Info</a></li>
<li><a href="links.html">Links & Events</a></li>
<li><a href="credits.html">Credits</a></li>
</ul>
</li>
<li><a data-iconcolor="#3b5998" href="https://www.facebook.com/FlutesbyWindward" target="_blank"><i class="icon-facebook"></i></a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="row">
<ul class="rslides">
<li><img src="img/assets/contact/01.jpg" alt="" /></li>
<li><img src="img/assets/contact/02.jpg" alt="" /></li>
<li><img src="img/assets/contact/03.jpg" alt="" /></li>
<li><img src="img/assets/contact/04.jpg" alt="" /></li>
<li><img src="img/assets/contact/05.jpg" alt="" /></li>
<li><img src="img/assets/contact/06.jpg" alt="" /></li>
<li><img src="img/assets/contact/07.jpg" alt="" /></li>
<li><img src="img/assets/contact/08.jpg" alt="" /></li>
<li><img src="img/assets/contact/09.jpg" alt="" /></li>
<li><img src="img/assets/contact/10.jpg" alt="" /></li>
<li><img src="img/assets/contact/11.jpg" alt="" /></li>
<li><img src="img/assets/contact/12.jpg" alt="" /></li>
<li><img src="img/assets/contact/13.jpg" alt="" /></li>
</ul>
</div>
<div class="container">
<div class="header"><hr><h2>Contact Us</h2></div>
<div class="row">
<div class="span6">
<p class="lead">Thank you for visiting our website. We welcome your comments and feedback, and we will respond to any inquiries.</p><p>If you would like to buy a Windward instrument, we will try to assist you in the choice of flute that best fulfills your expectations. We care about our customers as we do our flutes, and like any good matchmaker, we want the player and the flute to have a long and happy relationship!</p><p>Feel free to <a href="mailto:<EMAIL>">contact us</a> about the available options.
</div>
<div class="well span4 offset1">
<?php
// check for a successful form post
if (isset($_GET['s'])) echo "<div class=\"alert alert-success\">".$_GET['s']."</div>";
// check for a form error
elseif (isset($_GET['e'])) echo "<div class=\"alert alert-error\">".$_GET['e']."</div>";
?>
<form method="POST" action="contact-form-submission.php" class="form-inline">
<div class="control-group">
<label class="control-label" for="input1">Name</label>
<div class="controls">
<input type="text" name="contact_name" id="input1" placeholder="Your name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="input2">Email Address</label>
<div class="controls">
<input type="text" name="contact_email" id="input2" placeholder="Your email address">
</div>
</div>
<div class="control-group">
<label class="control-label" for="input3">Message</label>
<div class="controls">
<textarea name="contact_message" id="input3" rows="8" class="span4" placeholder="The message you want to send to me."></textarea>
</div>
</div>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn">Send</button>
</div>
</form>
</div>
<br><br>
</div>
</div><br><br>
<footer>
<div class="container">
<div class="span3">
<p>CONTACT:<br><ul class="unstyled inline">
<h3>
<li>
<a href="http://www.youtube.com/user/flutesbywindward">
<i class="icon-youtube"></i>
</a>
</li>
<li>
<a href="https://www.facebook.com/FlutesbyWindward">
<i class="icon-facebook"></i>
</a>
</li>
<li>
<a href="mailto:<EMAIL>?Subject=Hello">
<i class="icon-envelope"></i>
</a>
</li>
</ul></h3>
<address>
phone: 902-875-3207<br>
<a href=mailto:<EMAIL>?Subject=Hello><EMAIL></a>
</address>
<address>
11 Charlotte Lane<br>
Box 1777<br>
Shelburne Nova Scotia<br>
B0T 1W0, Canada</p>
</address>
</div>
</footer>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery.min.js"></script>
<script src="js/min/bootstrap.min.js"></script>
<script src="js/min/responsiveslides.min.js"></script>
<script>
$(function() {
$(".rslides").responsiveSlides();
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-28515852-1']);
_gaq.push(['_setDomainName', 'windwardflutes.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
<file_sep>var ProjectManagerView = (function() {
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
'use strict';
var isOpen = false;
var curId = 0;
var lastId = -1;
var classArray = [];
var subClassArray = [];
var currentViewPointer = "";
var currentSubViewPointer = "";
var direction = 1; // positive means forward, negative means backwards, used to let the app know if it was a next event or previsous event
var dragElement;
var isSwipeEnabled = false;
var startDragX = 0;
var startDragY = 0;
var distanceX = 0;
var distanceY = 0;
var swipeDistance = 100;
var stageWidth;
var stageHeight;
var isTouchDown = false;
var isTouchDevice;
var mainView; // used to move block
function openView()
{
if( isOpen == false )
{
isOpen = true;
addEventListeners();
stageWidth = SwissArmyKnife.browserWidth();
stageHeight = SwissArmyKnife.browserHeight();
}
}
function closeView() {
if( isOpen == true )
{
isOpen = false;
removeEventListeners();
}
}
function addEventListeners()
{
// SwissArmyKnife.addEvent( 'touchmove', document , documentMoveTouchHandler );
// document.addEventListener("touchmove", documentMoveTouchHandler, false);
}
function removeEventListeners()
{
}
// used to stop stage dragging in crapple ios safri
function documentMoveTouchHandler()
{
//event.preventDefault();
}
function resizeEvent( w, h )
{
if( isOpen == true )
{
//console.log( " ProjectManagerView : resizeEvent" );
stageWidth = w;
stageHeight = h;
// InfoView.resizeEvent( w, h );
if( currentViewPointer != 'undefined' )
{
// currentViewPointer.resizeEvent( w, h );
}
}
}
function setDirection( val )
{
direction = val;
}
function updateById( id )
{
//console.log( convertToDeeplinkByID( id ) + " ::::::: function updateById( id )" )
SWFAddress.setValue( convertToDeeplinkByID( id ) );
// loadById( convertToDeeplinkByID( id ) );
}
function changeColorById( id )
{
/*
var color = DataModelLunchBox.getColorById( id );
MenuView.changeColor( color );
//InfoView.changeColor( color );
FullScreenLoader.changeColor( color );
NextPrev.changeColor( color );
*/
}
function loadById( id )
{
//disableSwipeEvents();
curId = id;
MenuView.setSelect( id );
MenuView.closeView();
YtPlayerView.closeView();
// MenuView.closeTabBtn();
// console.log( curId + " curId from function loadById( id ) " );
//changeColorById( id )
if( currentViewPointer != "" )
{
currentViewPointer.closeView();
currentSubViewPointer.closeView();
}else{
}
// NextPrev.closeView();
currentViewPointer = classArray[id];
currentSubViewPointer = subClassArray[id];
currentViewPointer.getOurviceLoaded().add( onLoadedEventHandler );
currentViewPointer.getOurviceOpened().add( onOpenCompleteEventHandler );
currentViewPointer.getOurviceClosed().add( onCloseCompleteEventHandler );
if( currentViewPointer.getIsLoaded() == false )
{
// FullScreenLoader.openView();
currentViewPointer.loadAll();
currentSubViewPointer.loadAll();
}else{
currentViewPointer.openView();
currentSubViewPointer.openView();
}
lastId = curId
}
// Reset everything
function init() {
// If there is an open preload queue, close it.
var len = DataModelLunchBox.getHeroDataLength()
for( var i = 0 ; i < len ; i ++ )
{
var heroModule = new HeroView();
heroModule.init( i );
classArray[i] = heroModule;
var mySub3ColView = new Sub3ColView();
mySub3ColView.init(i , DataModelLunchBox.getContentSubDataById( i ).rowCount );
subClassArray[i] = mySub3ColView;
}
}
function changeAddressHandler( event )
{
// closeMenu()
// closeInfoView();
// console.log( SWFAddress.getValue() + " function changeAddressHandler( event ) function changeAddressHandler( event ) function changeAddressHandler( event ) function changeAddressHandler( event ) function changeAddressHandler( event ) " );
if( SWFAddress.getValue() == "/" )
{
loadById( convertDeepLink( SWFAddress.getValue() ) );
}else{
loadById( convertDeepLink( SWFAddress.getValue() ) );
}
}
function convertToDeeplinkByID( id )
{
var sectionArray = DataModelLunchBox.getDeepLinkData();
return sectionArray[id];
}
function convertDeepLink( deepLink )
{
var i = 0;
var sectionArray = DataModelLunchBox.getDeepLinkData();
var result = "";
for (i=0; i< sectionArray.length ; i++)
{
if ( deepLink == sectionArray[i] )
{
result = i;
}
}
//console.log( result + " function convertDeepLink( deepLink )" )
return result;
}
function initSwfAddress()
{
SWFAddress.addEventListener( "change" , changeAddressHandler );
}
function onOpenCompleteEventHandler( string )
{
// console.log( string );
// NextPrev.openView();
// MenuView.openTabBtn();
// enableSwipeEvents();
//console.log( string + " onOpenCompleteEventHandler" )
if( curId == 0 )
{
// loadById( 1 )
}
}
function onCloseCompleteEventHandler( string , pid )
{
//console.log( string + " " + pid );
var ref = classArray[ pid ];
// console.log( ref + " has event listener?" );
/*
ref.getOurviceLoaded().remove( onLoadedEventHandler );
ref.getOurviceOpened().remove( onOpenCompleteEventHandler );
ref.getOurviceClosed().remove( onCloseCompleteEventHandler );
*/
}
function onLoadedEventHandler( string )
{
// console.log( string + " " + currentViewPointer.getPID() + " " + curId );
// FullScreenLoader.closeView();
stageWidth = SwissArmyKnife.browserWidth();
stageHeight = SwissArmyKnife.browserHeight();
if( currentViewPointer.getPID() == curId )
{
currentViewPointer.openView() ;
currentSubViewPointer.openView();
}
}
function getCurId()
{
return curId;
}
function getDirection()
{
return direction;
}
function initDomPointers()
{
mainView = document.getElementById( "js-viewItem" );
isTouchDevice = SwissArmyKnife.doesDeviceSupportTouch();
}
initDomPointers();
// Because I don't have public variables, I can just return an object instead
// of an object api var. Whether you return an object api var or just return
// an object, it's the same thing and a matter of preference.
return {
// public functions
openView: openView,
closeView: closeView,
resizeEvent: resizeEvent,
init: init,
updateById: updateById,
getCurId: getCurId,
initSwfAddress: initSwfAddress,
// public vars
isOpen: isOpen,
curId: curId,
stageWidth : stageWidth,
stageHeight: stageHeight,
mainView : mainView,
direction: direction,
isTouchDevice: isTouchDevice
};
})();<file_sep>var BackgroundResize = (function() {
// Just so you can see what "this" refers to. It's the global window object.
// Never attach anything to "this" because then it's a global var/method
// and you start polluting the global namespace.
// This pattern gives you closure privacy. This is self executing which
// means you don't have to use the new operator but this is a static/singleton
// class. Only one instance is created.
// All methods are private. You don't have to worry about scoping or using
// "this". If you were to trace out "this", you would get an instance of
// the global window object. Never use "this" within the module pattern.
'use strict';
var map = {};
var preload;
var loader;
var manifest;
var preloadid = 0;
var isOpen = "false";
var isLoaded = "false";
var initW = 0;
var initH = 0;
function openView()
{
if( isOpen == "false" )
{
isOpen = "true";
loadAll();
}
}
// Reset everything
function reload() {
// If there is an open preload queue, close it.
if (preload != null) { preload.close(); }
// Reset the UI
// Push each item into our manifest
var model = DataModelLunchBox.getThemeDataById(0)
var temps = model.backgroundImage;
manifest = [ temps ];
// Create a preloader. There is no manfest added to it up-front, we will add items on-demand.
preload = new PreloadJS();
preload.onFileLoad = handleFileLoad;
preload.onProgress = handleOverallProgress;
preload.onFileProgress = handleFileProgress;
preload.onError = handleFileError;
preload.setMaxConnections(1);
preloadid = 0;
}
function stop() {
if (preload != null) { preload.close(); }
}
function loadAll() {
while (manifest.length > 0) {
loadAnother();
}
}
function loadAnother() {
// Get the next manifest item, and load it
var item = manifest.shift();
preload.loadFile(item);
// Create a new loader display item
}
// File complete handler
function handleFileLoad(event) {
var div = document.getElementById("js-background");
//console.log ( div )
preloadid = preloadid +1;
// Get a reference to the loaded image (<img/>)
div.style.opacity = 0;
var img = event.result;
img.setAttribute('id', 'js-backgroundIMG');
div.appendChild(img); // Add it to the DOM
var divb = document.getElementById("js-backgroundIMG");
initW = divb.offsetWidth;
initH = divb.offsetHeight;
if( preloadid == 1 )
{
isLoaded = "true";
resizeEvent( SwissArmyKnife.browserWidth() , SwissArmyKnife.browserHeight() );
}
TweenLite.to( div , 1 , {css:{ opacity:1 } } );
}
// File progress handler
function handleFileProgress(event) {
//var div = map[event.src]; // Lookup the related item
//div.children("DIV").width(event.progress*div.width()); // Set the width the progress.
}
// Overall progress handler
function handleOverallProgress(event) { //http://ourvice.com/clients/ourvice/html5/assets/reg/backs.jpg
}
// An error happened on a file
function handleFileError(event) {
//alert( event );
}
function touchScale()
{
var divCont = document.getElementById("js-backgroundIMG");
TweenLite.to( divCont , .5 , {css:{ scale: .95 } , delay:0 , ease:Power2.easeOut } );
}
function touchScaleDone()
{
var divCont = document.getElementById("js-backgroundIMG");
TweenLite.to( divCont , .5 , {css:{ scale: 1 } , delay:0 , ease:Power2.easeOut } );
}
function resizeEvent( w, h )
{
if( isLoaded == "true" )
{
var div = document.getElementById("js-backgroundIMG");
var divCont = document.getElementById("js-background");
var stageWidth = w;
var stageHeight = h;
// Calculate new height and width
var offsetBleed = 0;
var ratio = initH / initW;
var imgWidth = stageWidth + offsetBleed;
var imgHeight = imgWidth * ratio;
var myX = 0;
var myY = 0;
div.style.width = imgWidth + 'px';
div.style.height = imgHeight + 'px';
if( imgHeight < stageHeight )
{
var ratio = initW /initH ;
imgHeight = stageHeight + offsetBleed;
imgWidth = ( imgHeight + offsetBleed )* ratio;
div.style.width = imgWidth + 'px';
div.style.height = imgHeight + 'px';
myY = ( offsetBleed/2)*-1;
divCont.style.top = myY + "px" ;
}else{
myY = -( imgHeight - stageHeight )/2;
divCont.style.top = myY + "px" ;
}
if ( imgWidth < stageWidth ) {
myX = 0;
divCont.style.left = myX + "px" ;
}else{
myX = ( stageWidth - imgWidth )/2;
divCont.style.left = myX + "px" ;
}
}
}
reload();
// Because I don't have public variables, I can just return an object instead
// of an object api var. Whether you return an object api var or just return
// an object, it's the same thing and a matter of preference.
return {
// public functions
resizeEvent: resizeEvent,
touchScale: touchScale,
touchScaleDone: touchScaleDone,
openView: openView
// public vars
//retina: retina
};
})(); | caada124d8343d4343c73ba1a4ec72a6ba517ad1 | [
"JavaScript",
"PHP"
] | 9 | JavaScript | sohier/wwfsite | 61d18fdf860fc629e53b01831006918470a5b906 | 5bfbccc239ad78299e305233e64cab32f529aaf9 |
refs/heads/master | <file_sep>
<?php echo $__env->make('blog::blog.partial.header', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<section class="grid">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="sidebar">
<div class="widget search">
<form action="">
<input type="text" class="form-control" placeholder="Keywords.." name="search[tags]" required="">
<button class="btn btn-primary" type="submit"><i class="ti-search"></i></button>
</form>
</div>
<div class="widget category">
<ul class="mt-20">
<?php echo $__env->make('blog::blog.partial.aside', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</ul>
</div>
</div>
</div>
<div class="col-md-9">
<div class="main-area parent-border">
<div class="row mb30">
<?php $__currentLoopData = $blogs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $blog): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="col-sm-6">
<div class="newest-item border">
<div class="feature">
<a href="<?php echo e(trans_url('blog')); ?>/<?php echo e(@$blog['slug']); ?>">
<img src="<?php echo e(url($blog->defaultImage('images','sm'))); ?>" class="img-responsive center-block" alt="" >
</a>
</div>
<div class="content">
<h4><a href="<?php echo e(trans_url('blog')); ?>/<?php echo e($blog['slug']); ?>"><?php echo e(@$blog->title); ?></a></h4>
<div class="metas mt20">
<div class="tag pull-left">
<a href="<?php echo e(trans_url('blogs/category')); ?>/<?php echo e(@$blog->category->slug); ?>" class=""><?php echo e(@$blog->category->name); ?></a>
</div>
<div class="date-time pull-right">
<span><i class="fa fa-comments"></i><?php echo e($blog->comments->count()); ?></span>
<span><i class="fa fa-calendar"></i><?php echo e(format_date($blog['created_at'])); ?></span>
</div>
</div>
<div class="divider"></div>
<div class="author">
<div class="avatar pull-left">
<img class="img-circle" src="img/blogs/author-04.jpg" alt="">
</div>
<p>by <span class="text-primary">
<a href="" class="">
<?php echo e((@$blog->user->name)); ?></a></span></p>
</div>
</div>
</div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
</div>
<div class="pagination text-center">
<?php echo e($blogs->links()); ?>
</div>
</div>
</div>
</div>
</section><file_sep><!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<i class="fa fa-flag-o"></i> <?php echo trans('task::task.name'); ?> <small> <?php echo trans('app.manage'); ?> <?php echo trans('task::task.names'); ?></small>
</h1>
<ol class="breadcrumb">
<li><a href="<?php echo trans_url('admin'); ?>"><i class="fa fa-dashboard"></i> <?php echo trans('app.home'); ?> </a></li>
<li class="active"><?php echo trans('task::task.names'); ?></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-lg-4">
<div class="ibox box box-warning">
<div class="ibox-content">
<h3>To-do</h3>
<p class="small"><i class="fa fa-hand-o-up"></i> Drag task between list</p>
<?php echo Form::vertical_open()
->id('create-task')
->method('POST')
->files('true')
->enctype('multipart/form-data')
->action(guard_url('task/task')); ?>
<?php echo Form::token(); ?>
<div class="input-group">
<input type="hidden" name="new-status" value="to_do" placeholder="Add new task." class="input input-sm form-control">
<input type="text" name="new-task" placeholder="Add new task." class="input input-sm form-control" required="required">
<span class="input-group-btn">
<button type="button" class="btn btn-primary btn-sm task-button" data-action='CREATE' data-form='#create-task' data-load-to='#to_do_list'>Add Task</button>
</span>
</div>
<?php echo Form::close(); ?>
<div id="to_do_list">
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="ibox box box-primary">
<div class="ibox-content">
<h3>In Progress</h3>
<p class="small"><i class="fa fa-hand-o-up"></i> Drag task between list</p>
<div id="in_progress_list">
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="ibox box box-success">
<div class="ibox-content">
<h3>Completed</h3>
<p class="small"><i class="fa fa-hand-o-up"></i> Drag task between list</p>
<div id="completed_list">
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modal-task">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
</section>
</div>
<script>
$(document).ready(function(){
$("#to_do_list").load('<?php echo e(trans_url('admin/task/task/status?search[status]=to_do')); ?>');
$("#in_progress_list").load('<?php echo e(trans_url('admin/task/task/status?search[status]=in_progress')); ?>');
$("#completed_list").load('<?php echo e(trans_url('admin/task/task/status?search[status]=completed')); ?>');
});
</script>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title><?php echo e(Theme::getMetaTitle()); ?> - <?php echo e(__('app.name')); ?></title>
<meta name="keyword" content="<?php echo e(Theme::getMetaKeyword()); ?>">
<meta name="description" content="<?php echo e(Theme::getMetaDescription()); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="<?php echo e(asset('apple-touch-icon.png')); ?>">
<?php echo Theme::asset()->styles(); ?>
<?php echo Theme::asset()->scripts(); ?>
</head>
<body>
<div class="page">
<?php echo Theme::partial('login'); ?>
<?php echo Theme::partial('header'); ?>
<?php echo Theme::content(); ?>
<?php echo Theme::partial('footer'); ?>
</div>
<?php echo Theme::asset()->container('footer')->scripts(); ?>
<?php echo Theme::asset()->container('extra')->scripts(); ?>
</body>
</html>
<file_sep> <header class="main-header">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" onclick="toggleNav()" id="nav_btn" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</button>
<a class="navbar-brand" href="<?php echo e(trans_url('/')); ?>"><img src="<?php echo e(theme_asset('img/logo/logo.svg')); ?>" alt=""></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<?php echo Menu::menu('main'); ?>
</ul>
<ul class="nav navbar-nav navbar-right hidden-sm hidden-xs">
<li><a href="https://twitter.com/lavalitecms" target="_blank" class="social-icons"><i class="fab fa-twitter"></i></a></li>
<li><a href="https://www.facebook.com/lavalite" target="_blank" class="social-icons"><i class="fab fa-facebook"></i></a></li>
<li><a href="https://github.com/lavalite/cms" target="_blank" class="social-icons"><i class="fab fa-github"></i></a></li>
<?php if(!auth('client.web')->check()): ?>
<li><a href="#" data-toggle="modal" data-target="#loginModal" class="btn">Login</a></li>
<?php else: ?>
<li><a href="<?php echo e(trans_url('client')); ?>" class="btn"><?php echo e(users('name', 'client.web')); ?></a></li>
<li><a href="<?php echo e(trans_url('client/logout')); ?>" class="btn">Logout</a></li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>
<?php if(!auth('client.web')->check()): ?>
<a href="<?php echo e(trans_url('client/login')); ?>" class="login_btn btn hidden-md hidden-lg">Login</a>
<?php else: ?>
<a href="<?php echo e(trans_url('client')); ?>" class="login_btn btn hidden-md hidden-lg"><?php echo e(users('name', 'client.web')); ?></a>
<?php endif; ?>
<a href="https://github.com/lavalite/cms" target="_blank" class="github_btn hidden-md hidden-lg"><i class="fab fa-github"></i></a>
</header>
<file_sep><?php return array (
'barryvdh/laravel-debugbar' =>
array (
'providers' =>
array (
0 => 'Barryvdh\\Debugbar\\ServiceProvider',
),
'aliases' =>
array (
'Debugbar' => 'Barryvdh\\Debugbar\\Facade',
),
),
'lavalite/framework' =>
array (
'dont-discover' =>
array (
0 => 'rachidlaasri/laravel-installer',
1 => 'intervention/imagecache',
2 => 'spatie/laravel-backup',
),
),
'litecms/block' =>
array (
'providers' =>
array (
0 => 'Litecms\\Block\\BlockServiceProvider',
),
'aliases' =>
array (
'Block' => 'Litecms\\Block\\Facades\\Block',
),
),
'litecms/blog' =>
array (
'providers' =>
array (
0 => 'Litecms\\Blog\\Providers\\BlogServiceProvider',
),
'aliases' =>
array (
'Blog' => 'Litecms\\Blog\\Facades\\Blog',
),
),
'litecms/contact' =>
array (
'providers' =>
array (
0 => 'Litecms\\Contact\\ContactServiceProvider',
),
'aliases' =>
array (
'Contact' => 'Litecms\\Contact\\Facades\\Contact',
),
),
'litecms/page' =>
array (
'providers' =>
array (
0 => 'Litecms\\Page\\PageServiceProvider',
),
'aliases' =>
array (
'Page' => 'Litecms\\Page\\Facades\\Page',
),
),
'litecms/slider' =>
array (
'providers' =>
array (
0 => 'Litecms\\Slider\\Providers\\SliderServiceProvider',
),
'aliases' =>
array (
'Slider' => 'Litecms\\Slider\\Facades\\Slider',
),
),
'mpociot/teamwork' =>
array (
'providers' =>
array (
0 => 'Mpociot\\Teamwork\\TeamworkServiceProvider',
),
),
'nesbot/carbon' =>
array (
'providers' =>
array (
0 => 'Carbon\\Laravel\\ServiceProvider',
),
),
);<file_sep><section class="title">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center">
<h1><?php echo trans('slider::slider.name'); ?></h1>
<p>We are a creative studio focusing on culture, luxury, editorial & art.</p>
</div>
</div>
</div>
</section><file_sep>
<div class="nav-tabs-custom">
<!-- Nav tabs -->
<ul class="nav nav-tabs primary">
<li role="presentation" class="active"><a href="#details" area-controls="details" role="tab" data-toggle="tab">Blog</a></li>
<li role="presentation"><a href="#image" area-controls="image" role="tab" data-toggle="tab">Image & Meta</a></li>
<div class="box-tools pull-right">
<button type="button" class="btn btn-primary btn-sm" data-action='CREATE' data-form='#blog-blog-create' data-load-to='#blog-blog-entry' data-datatable='#blog-blog-list'><i class="fa fa-floppy-o"></i> <?php echo e(trans('app.save')); ?></button>
<button type="button" class="btn btn-default btn-sm" data-action='CLOSE' data-load-to='#blog-blog-entry' data-href='<?php echo e(guard_url('blog/blog/0')); ?>'><i class="fa fa-times-circle"></i> <?php echo e(trans('app.close')); ?></button>
</div>
</ul>
<div class="tab-content clearfix">
<?php echo Form::vertical_open()
->id('blog-blog-create')
->method('POST')
->files('true')
->action(guard_url('blog/blog')); ?>
<div class="tab-pane active" id="details">
<div class="tab-pan-title"> <?php echo e(trans('app.new')); ?> [<?php echo trans('blog::blog.name'); ?>] </div>
<?php echo $__env->make('blog::admin.blog.partial.entry', ['mode' => 'create'], \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</div>
<?php echo Form::close(); ?>
</div>
</div><file_sep> <?php echo $__env->make('slider::public.slider.partial.header', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<section class="grid">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="main-area parent-border list-item">
<?php $__currentLoopData = $sliders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $slider): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<?php echo Slider::getSlider($slider->slug); ?>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
<div class="pagination text-center">
<?php echo e($sliders->links()); ?>
</div>
</div>
</div>
</div>
</section> <file_sep>
<div class="no-padding">
<div id="calendar"></div>
</div>
<?php $__env->startPush('scripts'); ?>
<script src="/example.js"></script>
<?php $__env->stopPush(); ?>
<?php $__env->startSection('script'); ?>
<script type="text/javascript">
$(function () {
$('#calendar').fullCalendar({
contentHeight: 635,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
//Random default events
eventSources: [
// your event source
{
url: '<?php echo guard_url('calendar/calendar/ajax/list'); ?>', // use the `url` property
}
],
editable: false,
droppable: false, // this allows things to be dropped onto the calendar !!!
resizable: false,
eventLimit: true,
});
});
</script>
<?php echo $__env->yieldSection(); ?>
<?php $__env->startSection('style'); ?>
<style type="text/css">
.external-event{
color: #fff;
}
.fc-time{
display : none;
}
.fc-state-active,.fc-state-disabled,.fc-state-hover{
color: #000 !important;
}
.fc-state-default {
background-color: #12d6cc;
color: #fff;
border: none;
}
</style>
<?php echo $__env->yieldSection(); ?>
<file_sep><ul class="dropdown-menu notification">
<li class="header"> You have <?php echo Message::count('Inbox', null, 1); ?> messages</li>
<li>
<!-- inner menu: contains the actual data -->
<div class="slimScrollDiv" >
<ul class="menu" >
<div class="slim-scroll">
<?php $__empty_1 = true; $__currentLoopData = Message::list('Inbox', null, 1); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
<li>
<a href="<?php echo guard_url('message/message'); ?>">
<div class="pull-left">
<img src="<?php echo @$value['user']->picture; ?>" class="img-circle img-responsive" alt="User Image" />
</div>
<h4>
<?php echo @$value->user->name; ?>
<br>
<small class="">
<i class="fa fa-clock-o">
</i>
<time class="timeago" datetime="<?php echo @$value['created_at']; ?>"></time>
<p class=""><?php echo @$value['subject']; ?></p>
</small>
</h4>
</a>
</li>
<!-- end message -->
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<?php endif; ?>
</div>
</ul>
</div>
</li>
<li class="footer"><a href="<?php echo e(guard_url('message/message')); ?>">See All Messages</a></li>
</ul>
<file_sep><div class="full-height landing">
<div class="route-landing">
<div id="wrap" class="no-overflow">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-well">
<h1>Bootstrapper for Laravel</h1>
<h3>Content Management System.</h3>
<a class="btn btn-default btn-round" href="http://www.lavalite.org/packages" target="_blank">
<i class="fas fa-box"></i> Build Packages
</a>
<a class="btn btn-default btn-round" href="http://lavalite.org/docs" target="_blank">
<i class="fas fa-book"></i> Documentation
</a>
<a class="btn btn-default btn-round" href="http://lavalite.org/marketplace" target="_blank">
<i class="fas fa-shapes"></i> Market Place
</a>
</div>
</div>
</div>
</div>
<div class="container">
<img src="<?php echo e(theme_asset('img/ui-screen.png')); ?>" alt="" class="img-responsive center-block" style="margin-top: 95px;" />
</div>
</div>
</div>
<div class="stripes-wraper">
<div class="stripes">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
</div>
<div class="inner-pages">
<section class="features">
<div class="container">
<?php echo Block::display('features'); ?>
</div>
</section>
</div>
<file_sep> <div class="nav-tabs-custom">
<!-- Nav tabs -->
<ul class="nav nav-tabs primary">
<li class="active"><a href="#slider" data-toggle="tab"><?php echo trans('slider::slider.tab.name'); ?></a></li>
<div class="box-tools pull-right">
<button type="button" class="btn btn-primary btn-sm" data-action='UPDATE' data-form='#slider-slider-edit' data-load-to='#slider-slider-entry' data-datatable='#slider-slider-list'><i class="fa fa-floppy-o"></i> <?php echo e(trans('app.save')); ?></button>
<button type="button" class="btn btn-default btn-sm" data-action='CANCEL' data-load-to='#slider-slider-entry' data-href='<?php echo e(guard_url('slider/slider')); ?>/<?php echo e($slider->getRouteKey()); ?>'><i class="fa fa-times-circle"></i> <?php echo e(trans('app.cancel')); ?></button>
</div>
</ul>
<?php echo Form::vertical_open()
->id('slider-slider-edit')
->method('PUT')
->enctype('multipart/form-data')
->action(guard_url('slider/slider/'. $slider->getRouteKey())); ?>
<div class="tab-content clearfix">
<div class="tab-pane active" id="slider">
<div class="tab-pan-title"> <?php echo e(trans('app.edit')); ?> <?php echo trans('slider::slider.name'); ?> [<?php echo $slider->name; ?>] </div>
<?php echo $__env->make('slider::admin.slider.partial.entry', ['mode' => 'edit'], \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</div>
</div>
<?php echo Form::close(); ?>
</div><file_sep><!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<i class="fa fa-file-text-o"></i> <?php echo trans('settings::setting.name'); ?> <small> <?php echo trans('app.manage'); ?> <?php echo trans('settings::setting.names'); ?></small>
</h1>
<ol class="breadcrumb">
<li><a href="<?php echo guard_url('/'); ?>"><i class="fa fa-dashboard"></i> <?php echo trans('app.home'); ?> </a></li>
<li class="active"><?php echo trans('settings::setting.names'); ?></li>
</ol>
</section>
<section class="content">
<!-- Main content -->
<?php echo Form::vertical_open()
->id('settings-setting-create')
->method('POST')
->files('true')
->action(URL::to('admin/settings/setting')); ?>
<div class="nav-tabs-custom">
<!-- Nav tabs -->
<ul class="nav nav-tabs primary">
<li class="active"><a href="#main" data-toggle="tab">Main</a></li>
<li><a href="#user" data-toggle="tab">User</a></li>
<div class="box-tools pull-right">
<button type="button" class="btn btn-primary btn-sm" data-action='CREATE' data-form='#settings-setting-create' data-load-to='#settings-setting-entry' data-datatable='#settings-setting-list'><i class="fa fa-floppy-o"></i> <?php echo e(trans('app.save')); ?></button>
<button type="reset" class="btn btn-default btn-sm"><i class="fa fa-times-circle"></i> <?php echo e(trans('app.close')); ?></button>
</div>
</ul>
<div class="tab-content clearfix">
<div class="tab-pane active" id="main">
<?php echo $__env->make('settings::admin.setting.partial.main', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</div>
<div class="tab-pane" id="user">
<?php echo $__env->make('settings::admin.setting.partial.user', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
</div>
</div>
</div>
<?php echo Form::close(); ?>
</section>
</div><file_sep> <div class='row'>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('main[main.name]')
-> label(trans('settings::setting.label.main.name'))
-> value(setting('main.name'))
-> placeholder(trans('settings::setting.placeholder.main.name')); ?>
</div>
</div><file_sep><div class="section-header">
<h2><?php echo $category->title; ?></h2>
<p> <?php echo $category->details; ?> </p>
</div>
<?php $__currentLoopData = $blocks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $block): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="col-sm-4 content-center text-center">
<div class="list-view-item">
<i class="<?php echo $block->icon; ?>"></i>
<h5><?php echo $block->name; ?></h5>
<p><?php echo $block->description; ?> </p>
</div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><file_sep><div class="sidebar">
<div class="widget">
<!-- <a href="<?php echo e(trans_url('blog/create')); ?>" class="btn btn-primary"><?php echo e(trans('app.create')); ?> Blog</a> -->
</div>
<div class="widget category">
<h3 class="border-bottom">Category</h3>
<ul class="mt-20">
<li class="menu-title uppercase"><a href="<?php echo e(trans_url('blogs')); ?>"><i style="color: #4BCC88;" class="fa fa-circle-o"></i> All</a></li>
<?php $__empty_1 = true; $__currentLoopData = Blog::selectCategories(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
<li class="menu-title uppercase"><a href="<?php echo e(trans_url('blogs/category')); ?>/<?php echo e(@$key); ?>"><i style="color: #4BCC88;" class="fa fa-circle-o"></i> <?php echo @$category; ?></a></li>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<?php endif; ?>
</ul>
</div>
<div class="widget tags">
<h3>Tag</h3>
<ul class="mt-20">
<?php $__empty_1 = true; $__currentLoopData = Blog::selectTags(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $tag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
<li><a href="<?php echo e(trans_url('blogs/tag')); ?>/<?php echo e(@$tag); ?>"><?php echo @$tag; ?></a></li>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<?php endif; ?>
</ul>
</div>
</div>
<file_sep> <section class="inner-page-title about-header">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center">
<h1><?php echo e(Page::getPage('contact')->heading); ?></h1>
<p><?php echo e(Page::getPage('contact')->meta_description); ?></p>
</div>
</div>
</div>
</section><file_sep>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<?php $__currentLoopData = $slider->getImages('images','lg'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key=> $image): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="item active">
<img src="<?php echo url($slider->defaultImage('images' ,'original',$key)); ?>" alt="...">
<div class="carousel-caption">
<h5><?php echo e($slider->images[$key]['title']); ?></h5>
<p><?php echo e($slider->images[$key]['caption']); ?></p>
</div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div><file_sep><div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="details">
<div class='row'>
<div class='col-md-12 col-sm-6'>
<?php echo Form::text('title')
-> label(trans('blog::blog.label.title'))
-> placeholder(trans('blog::blog.placeholder.title')); ?>
</div>
<div class='col-md-4 col-sm-6'>
<?php echo Form::select('category_id')
->options(Blog::selectadminCategories())
-> label(trans('blog::blog.label.category_id'))
-> placeholder(trans('blog::blog.placeholder.category_id')); ?>
</div>
<div class='col-md-8 col-sm-6'>
<?php echo Form::text('tags')
-> label(trans('blog::blog.label.tags'))
-> placeholder(trans('blog::blog.placeholder.tags')); ?>
</div>
<div class='col-md-12'>
<?php echo Form::textarea('description')
-> label(trans('blog::blog.label.description'))
-> dataUpload(trans_url($blog->getUploadURL('description')))
-> addClass('html-editor')
-> placeholder(trans('blog::blog.placeholder.description')); ?>
</div>
<?php if(@$blog['published'] == 'yes'): ?>
<div class='col-md-4 col-sm-6'>
<?php echo Form::numeric('viewcount')
-> label(trans('blog::blog.label.viewcount'))
-> placeholder(trans('blog::blog.placeholder.viewcount')); ?>
</div>
<?php endif; ?>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="image">
<div class='row'>
<div class="col-md-6">
<div class='col-md-12 col-sm-6'>
<?php echo Form::text('meta_title')
-> label(trans('blog::blog.label.meta_title'))
-> placeholder(trans('blog::blog.placeholder.meta_title')); ?>
</div>
<div class='col-md-12 col-sm-6'>
<?php echo Form::textarea('meta_description')
-> label(trans('blog::blog.label.meta_description'))
-> placeholder(trans('blog::blog.placeholder.meta_description')); ?>
</div>
<div class='col-md-12 col-sm-6'>
<?php echo Form::text('meta_keyword')
-> label(trans('blog::blog.label.meta_keyword'))
-> placeholder(trans('blog::blog.placeholder.meta_keyword')); ?>
</div>
</div>
<div class="col-md-6">
<div class='col-md-12 col-sm-12'>
<div class="form-group">
<label for="images" class="control-label col-lg-12 col-sm-12 text-left">
<?php echo e(trans('blog::blog.label.images')); ?>
</label>
<div class='col-lg-12 col-sm-12'>
<?php echo $blog->files('images', 10)
->mime(config('filer.image_extensions'))
->url($blog->getUploadUrl('images'))
->dropzone(); ?>
</div>
<div class='col-lg-7 col-sm-12'>
<?php echo $blog->files('images')
->editor(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('#tags').selectize({
delimiter: ',',
persist: false,
valueField: 'tag',
labelField: 'tag',
searchField: 'tag',
options: tags,
create: function(input) {
return {
tag: input
}
}
});
});
</script>
<script>
var tags = [
<?php $__empty_1 = true; $__currentLoopData = Blog::selectTags(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $tag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
{tag: "<?php echo e($tag); ?>" },
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<?php endif; ?>
];
</script><file_sep><?php echo $__env->make('contact::public.contact.header', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<section class="contact">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="sidebar">
<div class="widget clearfix">
<div class="title">
<h3>
Address
</h3>
<div class="separator">
<span>
</span>
<span>
</span>
<span>
</span>
</div>
</div>
<div class="icon">
<i class="ti-location-pin">
</i>
</div>
<div class="content">
<p>
<?php echo $contact['details']; ?>
</p>
</div>
</div>
<div class="widget clearfix">
<div class="title">
<h3>
Phone
</h3>
<div class="separator">
<span>
</span>
<span>
</span>
<span>
</span>
</div>
</div>
<div class="icon">
<i class="ti-mobile">
</i>
</div>
<div class="content">
<p>
<br/>
<?php echo $contact['phone']; ?>
</p>
</div>
</div>
<div class="widget clearfix">
<div class="title">
<h3>
Email
</h3>
<div class="separator">
<span>
</span>
<span>
</span>
<span>
</span>
</div>
</div>
<div class="icon">
<i class="ti-email">
</i>
</div>
<div class="content">
<p>
<br/>
<?php echo $contact['email']; ?>
</p>
</div>
</div>
</div>
</div>
<div class="col-md-7 col-md-offset-1">
<div class="form mb30">
<div class="title">
<h3>
Get In Touch
</h3>
<div class="separator">
<span>
</span>
<span>
</span>
<span>
</span>
</div>
</div>
<div class="mb30" id="success">
</div>
<?php echo Form::vertical_open()
->id('send-message')
->method('POST')
->action(guard_url('contact/sendmail')); ?>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<?php echo Form::text('name')
->placeholder('Name')
->raw(); ?>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<?php echo Form::email('email')
->placeholder('Email')
->raw(); ?>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<?php echo Form::text('phone')
->placeholder('Phone')
->raw(); ?>
</div>
</div>
<div class="col-md-12 mb20">
<div class="form-group">
<?php echo Form::textarea('message')
->placeholder('Message')->rows(6)
->raw(); ?>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-primary btn-round" id="contact-submit" type="submit">
Send Message
</button>
</div>
</div>
<?php echo Form::close(); ?>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="map">
<div id="map" class="ui-map"></div>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(function(){
$("#send-message" ).submit(function(event) {
event.preventDefault();
app.sendmail(this);
});
var map, myLatlng;
<?php if(!empty($contact->lat) && !empty($contact->lng)): ?>
myLatlng = new google.maps.LatLng(<?php echo @$contact->lat; ?>,<?php echo @$contact->lng; ?>);
<?php else: ?>
myLatlng = new google.maps.LatLng(9.929789275194516,76.27235919804684);
<?php endif; ?>
var mapOptions = {
zoom: 14,
draggable: false,
center: myLatlng,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{
"featureType": "water",
"elementType": "geometry",
"stylers": [{
"color": "#e9e9e9"
}, {
"lightness": 17
}]
}, {
"featureType": "landscape",
"elementType": "geometry",
"stylers": [{
"color": "#f5f5f5"
}, {
"lightness": 20
}]
}, {
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ffffff"
}, {
"lightness": 17
}]
}, {
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#ffffff"
}, {
"lightness": 29
}, {
"weight": 0.2
}]
}, {
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [{
"color": "#ffffff"
}, {
"lightness": 18
}]
}, {
"featureType": "road.local",
"elementType": "geometry",
"stylers": [{
"color": "#ffffff"
}, {
"lightness": 16
}]
}, {
"featureType": "poi",
"elementType": "geometry",
"stylers": [{
"color": "#f5f5f5"
}, {
"lightness": 21
}]
}, {
"featureType": "poi.park",
"elementType": "geometry",
"stylers": [{
"color": "#dedede"
}, {
"lightness": 21
}]
}, {
"elementType": "labels.text.stroke",
"stylers": [{
"visibility": "on"
}, {
"color": "#ffffff"
}, {
"lightness": 16
}]
}, {
"elementType": "labels.text.fill",
"stylers": [{
"saturation": 36
}, {
"color": "#333333"
}, {
"lightness": 40
}]
}, {
"elementType": "labels.icon",
"stylers": [{
"visibility": "off"
}]
}, {
"featureType": "transit",
"elementType": "geometry",
"stylers": [{
"color": "#f2f2f2"
}, {
"lightness": 19
}]
}, {
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [{
"color": "#fefefe"
}, {
"lightness": 20
}]
}, {
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#fefefe"
}, {
"lightness": 17
}, {
"weight": 1.2
}]
}]
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
draggable: false,
position: myLatlng,
map: map,
title: "<?php echo e($contact['city']); ?>"
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<div id="bodyContent">'+
'<p><b><?php echo e($contact->name); ?></b></p>'+
'<p><?php echo e($contact->address_line1); ?></p>'+
'<p><a href="mailto:<?php echo e($contact["email"]); ?>">'+
'<?php echo e($contact["email"]); ?></a> '+
'</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
})
</script><file_sep><?php $__empty_1 = true; $__currentLoopData = $tasks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
<div class="media discussion-widget-block">
<div class="media-left media-middle">
<a href="#">
<img class="media-object img-circle" src="<?php echo url($value->user->picture); ?>" style="width:60px;height:60px;">
</a>
</div>
<div class="media-body">
<p><?php echo @$value->task; ?></p>
<p class="text-muted"><small><i class="ion ion-android-person"></i> <?php echo @$value->user->name; ?> at <?php echo format_date($value->created_at); ?></small></p>
</div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<div class="discussion-widget-block">
<p>No Discussions</p>
</div>
<?php endif; ?>
<file_sep> <div class='row'>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('name')
-> label(trans('slider::slider.label.name'))
-> placeholder(trans('slider::slider.placeholder.name')); ?>
</div>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('slug')
-> label(trans('slider::slider.label.slug'))
-> placeholder(trans('slider::slider.placeholder.slug')); ?>
</div>
</div>
<div class='row'>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('heading')
-> label(trans('slider::slider.label.heading'))
-> placeholder(trans('slider::slider.placeholder.heading')); ?>
</div>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('subheading')
-> label(trans('slider::slider.label.subheading'))
-> placeholder(trans('slider::slider.placeholder.subheading')); ?>
</div>
<div class='col-md-4 col-sm-6'>
<?php echo Form::select('status')
-> options(trans('slider::slider.options.status'))
-> placeholder(trans('slider::slider.placeholder.status')); ?>
</div>
<div class='col-md-12 col-sm-12'>
<div class="form-group">
<label for="images" class="control-label col-lg-12 col-sm-12 text-left">
<?php echo e(trans('slider::slider.label.images')); ?>
</label>
<div class='col-lg-12 col-sm-12'>
<?php echo $slider->files('images', 10)
->mime(config('filer.image_extensions'))
->url($slider->getUploadUrl('images'))
->dropzone(); ?>
</div>
<div class='col-lg-7 col-sm-12'>
<?php echo $slider->files('images')
->editor(); ?>
</div>
</div>
</div>
</div><file_sep> <footer class="main-footer">
<div class="container-fluid">
<div class="row logo">
<div class="col-md-12 text-center">
<img src="<?php echo e(theme_asset('img/logo/footer.svg')); ?>" alt="">
</div>
</div>
<div class="row links">
<div class="col-sm-4 social-links">
<?php echo Menu::menu('social'); ?>
</div>
<div class="col-sm-4 copyright">
<p><?php echo __('app.rights'); ?></p>
</div>
<div class="col-sm-4 navs">
<?php echo Menu::menu('footer'); ?>
</div>
</div>
</div>
</footer>
<file_sep><ul class="sortable-list connectList agile-list ui-sortable" id="<?php echo $status; ?>">
<?php $__empty_1 = true; $__currentLoopData = $tasks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
<li class="<?php echo @$value['priority']; ?> <?php echo @$value['status']; ?>" id="<?php echo @$value->getRouteKey(); ?>">
<?php echo @$value['task']; ?>
<div class="task-link-btn">
<button class="task-edit m-r-5 btn-xs btn-primary" data-toggle="modal" data-target="#modal-task">
<i class="fa fa-pencil"></i>
</button>
<button class="task-delete btn-xs btn-danger" data-action="DELETE" data-load-to='#<?php echo $value["status"]; ?>_list' data-href='<?php echo e(trans_url('/admin/task/task')); ?>/<?php echo e($value->getRouteKey()); ?>' ><i class="fa fa-trash"></i></button>
</div>
<div class="agile-detail">
<i class="fa fa-clock-o"></i> <?php echo format_date(@$value['created_at']); ?>
</div>
</li>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
<?php endif; ?>
</ul>
<script type="text/javascript">
$(".task-edit").click(function(){
var id = $(this).parent().parent().attr('id');
$('#modal-task .modal-content').load('<?php echo e(trans_url('admin/task/task')); ?>'+ '/' + id + '/' + 'edit');
$('#modal-task').show();
});
$(".task-trash").click(function(){
location.reload();
});
$(".sortable-list").sortable({
connectWith: ".connectList"
}).disableSelection();
$( ".sortable-list" ).on( "sortreceive", function( event, ui ) {
var status = $(this).attr('id');
var id = ui.item.attr('id');
var formURL = "<?php echo e(guard_url('task/task')); ?>"+"/"+id;
$.ajax( {
url: formURL,
type: 'PUT',
data: {'status': status},
success:function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
});
</script>
<style>
.task-link-btn {
position: absolute;
right: -40px;
top: 5px;
z-index: 9;
transition: 0.5s all ease;
}
.task-link-btn .btn-xs {
display: block;
margin-bottom: 5px;
}
.task-link-btn .btn-xs:last-child {
margin-bottom: 0;
}
.sortable-list li {
position: relative;
overflow: hidden;
}
.sortable-list li:hover .task-link-btn {
right: 0;
}
</style><file_sep> <footer class="main-footer">
<strong><?php echo trans('app.all.rights'); ?>
</footer><file_sep><section class="title">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center">
<h1><?php echo trans('blog::blog.name'); ?></h1>
<form action="#" class="search search-full">
<input type="text" name="search[title]" class="form-control" placeholder="Search existing blogs">
<button class="btn btn-primary" type="submit"><i class="ti-search"></i></button>
</form>
</div>
</div>
</div>
</section><file_sep><?php
namespace Litecms;
use DB;
use Illuminate\Database\Seeder;
class SliderTableSeeder extends Seeder
{
public function run()
{
DB::table(config('litecms.slider.slider.model.table'))->insert([
[
'id' => '1',
'user_id' => '1',
'user_type' => 'App\\User',
'name' => 'Music & Arts',
'heading' => 'Music Bands',
'subheading' => 'Music Bands',
'slug' => 'music-arts',
'images' => '[{"title":"Chicago","caption":"Thank you, Chicago!","url":"Chicago","desc":null,"folder":"2018\\/10\\/16\\/075556818\\/images","time":"2018-10-16 07:56:25","path":"slider\\/slider\\/2018\\/10\\/16\\/075556818\\/images\\/chicago.jpg","file":"chicago.jpg"},{"title":"Los Angeles","caption":"LA is always so much fun!","url":"La","desc":null,"folder":"2018\\/10\\/16\\/075556818\\/images","time":"2018-10-16 07:56:25","path":"slider\\/slider\\/2018\\/10\\/16\\/075556818\\/images\\/la.jpg","file":"la.jpg"},{"title":"New York","caption":"We love the Big Apple!","url":"Ny","desc":null,"folder":"2018\\/10\\/16\\/075556818\\/images","time":"2018-10-16 07:56:25","path":"slider\\/slider\\/2018\\/10\\/16\\/075556818\\/images\\/ny.jpg","file":"ny.jpg"}]',
'status' => 'Show',
'upload_folder' => null,
'deleted_at' => null,
'created_at' => '2018-10-16 07:56:28',
'updated_at' => '2018-10-16 08:55:18',
],
]);
DB::table('permissions')->insert([
[
'slug' => 'slider.slider.view',
'name' => 'View Slider',
],
[
'slug' => 'slider.slider.create',
'name' => 'Create Slider',
],
[
'slug' => 'slider.slider.edit',
'name' => 'Update Slider',
],
[
'slug' => 'slider.slider.delete',
'name' => 'Delete Slider',
],
]);
DB::table('menus')->insert([
[
'parent_id' => 1,
'key' => null,
'url' => 'admin/slider/slider',
'name' => 'Slider',
'description' => null,
'icon' => 'fa fa-newspaper-o',
'target' => null,
'order' => 190,
'status' => 1,
],
[
'parent_id' => 4,
'key' => null,
'url' => 'sliders',
'name' => 'Slider',
'description' => null,
'icon' => null,
'target' => null,
'order' => 190,
'status' => 1,
],
[
'parent_id' => 5,
'key' => null,
'url' => 'sliders',
'name' => 'Slider',
'description' => null,
'icon' => null,
'target' => null,
'order' => 190,
'status' => 1,
],
]);
DB::table('settings')->insert([
// Uncomment and edit this section for entering value to settings table.
/*
[
'pacakge' => 'Slider',
'module' => 'Slider',
'user_type' => null,
'user_id' => null,
'key' => 'slider.slider.key',
'name' => 'Some name',
'value' => 'Some value',
'type' => 'Default',
'control' => 'text',
],
*/
]);
}
}
<file_sep> <div class='row'>
<div class='col-md-4 col-sm-6'>
<?php echo Form::text('user[user.name]')
-> label(trans('settings::setting.label.user.name'))
-> value(setting()->user('user.name'))
-> placeholder(trans('settings::setting.placeholder.user.name')); ?>
</div>
</div> | 045dea9de7368a28a58600c56183353aed696a38 | [
"PHP"
] | 28 | PHP | Mo7ammedFtta7/smrc | 4d67174bbd413a706955a6f274202afd43f16a4a | 3bd9a9016a2ea219ff60e05d58c30af38ce1573c |
refs/heads/master | <repo_name>pramttl/github_track_repo<file_sep>/main/models.py
from django.db import models
class Project(models.Model):
repo_owner = models.CharField()
repo_name = models.CharField()
class DataPoint(models.Model):
P = models.ForeignKey(Project)
created = models.DateTimeField(auto_add_now=True)
size = models.IntegerField(default=0)
stargazers_count = models.IntegerField(default=0)
forks_count = models.IntegerField(default=0)
open_issues_count = models.IntegerField(default=0)
fork = models.IntegerField(default=0)
###################### Apscheduler Stuff #######################
#XXX: Not sure if this is the right place to start the scheduler
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
scheduler.start()
import requests
def fetch_repo_stats(rep):
api_repo_url = 'https://api.github.com/repos/' + repo_owner + '/' + repo_name
r = requests.get(api_repo_url)
data = r.json()
#XXX Extract stats from data and create a datapoint for them
################# Triggers and Callbacks ###################
############################################################
from django.db.models.signals import post_save, post_delete
@receiver(post_save, sender=Project)
def update_userlimitedcredits(sender, instance, **kwargs):
"""
To update value of net limitedcredits for MUser when a new LimitedCreditPack
is added for him.
"""
if kwargs['created']:
project = instance
#XXX: Add a job that fetches repo stats from api to the scheduler
# Store the repo stats
else:
pass
<file_sep>/README.md
Track your Github project statistics with time
----------------------------------------------
**Warning**: Not ready yet! I'll remove this message when this code is ready to use.
`github_track_repo` is a simple web applicaiton that allows you to follow your favourite github project and see how it is doing over time.
Project
-------
The github project you are tracking. Each project object has the following attribute(s):
```
repo_url = <repo_url>
```
DataPoint
---------
Each datapoint corresponds to a particular project P and a time instant T. It is a collection of the following statistics for a given P and T.
```
P = <reference_to_project>
T = <datetime>
size
stargazers_count
forks_count
open_issues_count
fork
```
The parameter names are self explainatory. Infact since the data is pulled from the Github API itself the terminology and names of these parameters are exactly same as those specified in Github API v3 (Repos)
https://developer.github.com/v3/repos/
Installation
------------
<file_sep>/main/views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse
import json
import requests
from .models import *
import random
from django.views.decorators.csrf import csrf_exempt
def index(request):
"""
Select project from dropdown
"""
pass
def track(request):
"""
Add a project to track
"""
pass
<file_sep>/requirements.txt
APScheduler==3.0.2
Django==1.8
futures==2.2.0
pytz==2015.2
requests==2.6.0
six==1.9.0
tzlocal==1.1.3
wsgiref==0.1.2
| 9c929b01790f314ba14ae7c28c1013cd0829ead8 | [
"Markdown",
"Python",
"Text"
] | 4 | Python | pramttl/github_track_repo | ea81ce2e4c5654324ea342ace285efef3e31f31c | 5fe4c80ced3f198cfd21026abb0f164d91a1866b |
refs/heads/master | <repo_name>coquito77/R_functions<file_sep>/funggcast.R
funggcast<-function(dn,fcast){
# fuction is from here
# http://davenportspatialanalytics.squarespace.com/blog/2012/3/14/plotting-forecast-objects-in-ggplot-part-1-extracting-the-da.html
require(zoo) #needed for the 'as.yearmon()' function
en<-max(time(fcast$mean)) #extract the max date used in the forecast
#Extract Source and Training Data
ds<-as.data.frame(window(dn,end=en))
names(ds)<-'observed'
ds$date<-as.Date(time(window(dn,end=en)))
#Extract the Fitted Values (need to figure out how to grab confidence intervals)
dfit<-as.data.frame(fcast$fitted)
dfit$date<-as.Date(time(fcast$fitted))
names(dfit)[1]<-'fitted'
ds<-merge(ds,dfit,all.x=T) #Merge fitted values with source and training data
#Exract the Forecast values and confidence intervals
dfcastn<-as.data.frame(fcast)
dfcastn$date<-as.Date(as.yearmon(row.names(dfcastn)))
names(dfcastn)<-c('forecast','lo80','hi80','lo95','hi95','date')
pd<-merge(ds,dfcastn,all.x=T) #final data.frame for use in ggplot
return(pd)
}<file_sep>/abbFileName.R
abbFileName <- function(x) {
FileName <- x %>% gsub("[^[:alnum:]]", " ", .) %>%
tolower %>% gsub("\\b(\\w)", "\\U\\1", ., perl=TRUE)
FileNameList <- FileName %>% strsplit(" ") %>% unlist()
for (i in 1:length(FileNameList)) {
#print(FileNameList[i])
newval <- abbreviate(FileNameList[i])
#print(newval)
x <- sub(FileNameList[i], newval, FileName)
FileName <- gsub("[^[:alnum:]]", "", x)
}
print(FileName)
}
# e.g abbFileName("Data Show Differences Between Urban and Rural Populations")
<file_sep>/facetAdjust.R
library(grid)
# script is from here
# http://stackoverflow.com/questions/13297155/add-floating-axis-labels-in-facet-wrap-plot/13316126#13316126
# pos - where to add new labels
# newpage, vp - see ?print.ggplot
facetAdjust <- function(x, pos = c("up", "down"),
newpage = is.null(vp), vp = NULL)
{
# part of print.ggplot
ggplot2:::set_last_plot(x)
if(newpage)
grid.newpage()
pos <- match.arg(pos)
p <- ggplot_build(x)
gtable <- ggplot_gtable(p)
# finding dimensions
dims <- apply(p$panel$layout[2:3], 2, max)
nrow <- dims[1]
ncol <- dims[2]
# number of panels in the plot
panels <- sum(grepl("panel", names(gtable$grobs)))
space <- ncol * nrow
# missing panels
n <- space - panels
# checking whether modifications are needed
if(panels != space){
# indices of panels to fix
idx <- (space - ncol - n + 1):(space - ncol)
# copying x-axis of the last existing panel to the chosen panels
# in the row above
gtable$grobs[paste0("axis_b",idx)] <- list(gtable$grobs[[paste0("axis_b",panels)]])
if(pos == "down"){
# if pos == down then shifting labels down to the same level as
# the x-axis of last panel
rows <- grep(paste0("axis_b\\-[", idx[1], "-", idx[n], "]"),
gtable$layout$name)
lastAxis <- grep(paste0("axis_b\\-", panels), gtable$layout$name)
gtable$layout[rows, c("t","b")] <- gtable$layout[lastAxis, c("t")]
}
}
# again part of print.ggplot, plotting adjusted version
if(is.null(vp)){
grid.draw(gtable)
}
else{
if (is.character(vp))
seekViewport(vp)
else pushViewport(vp)
grid.draw(gtable)
upViewport()
}
invisible(p)
}<file_sep>/README.md
# R_functions
r functions
R fuctions that come handy when analyzing data
use the lines below to extract the fuction
library(httr);
set_config(config(ssl_verifypeer = 0L));
devtools::source_url("https://raw.githubusercontent.com/coquito77/R_functions/master/abbFileName.R")
| 785f78d289e688fa24eb2f1b14581501b80c52af | [
"Markdown",
"R"
] | 4 | R | coquito77/R_functions | 9f8893e2ce87683ee23a64c87ec1523b8f6f038e | c74448a90732281fe91c9b6d09cd197b1a22fd0f |
refs/heads/master | <repo_name>lemosbor/Vora<file_sep>/Вора.py
import speech_recognition as sr
import pyttsx3
import webbrowser
from pydub import AudioSegment
from pydub.playback import play # подключаем библиотеку для воспроизведения mp3
import requests
import json
text = 'какой-нибудь текст'
tts = pyttsx3.init()
rate = tts.getProperty('rate') #Скорость произношения
tts.setProperty('rate', rate-57)
volume = tts.getProperty('volume') #Громкость голоса
tts.setProperty('volume', volume+0.9)
voices = tts.getProperty('voices')
# Задать голос по умолчанию
tts.setProperty('voice', 'ru')
# Попробовать установить предпочтительный голос
for voice in voices:
if voice.name == 'Anna':
tts.setProperty('voice', voice.id)
def record_volume():
r = sr.Recognizer()
with sr.Microphone(device_index = 1) as source:
print('Настраиваюсь.')
r.adjust_for_ambient_noise(source, duration=0.5) #настройка посторонних шумов
print('Слушаю...')
audio = r.listen(source)
print('Услышала.')
try:
query = r.recognize_google(audio, language = 'ru-RU')
text = query.lower()
print(f'Вы сказали: {query.lower()}')
if text == "привет":
tts.say("Добрый вечер, <NAME>")
tts.runAndWait()
if text == "как дела":
tts.say("Всё замечательно.")
tts.runAndWait()
if text == "терпсихора":
tts.say("Слушаю и повинуюсь")
tts.runAndWait()
if text == "кто такой":
tts.say("Ми")
tts.runAndWait()
if text == "она хорошая":
tts.say("проанализированные мною данные позволяют с уверенностью сказать, что Инесса хорошая на 134 процента")
tts.runAndWait()
if text == "обновить музыку":
tts.say("Начинаю обновление музыки")
tts.runAndWait()
import Парсер
if text == "как зовут мою девушку":
tts.say("Я хотела бы быть вашей девушкой, но это пока невозможно. Вашу девушку зовут Инесса.")
tts.runAndWait()
if text == "какая сейчас погода":
url = "https://api.openweathermap.org/data/2.5/onecall?lat=%s&lon=%s&appid=%s&units=metric&lang=ru" % ("55.669952", "37.610324", "2d3ba9a0a3d3d4d9c8f605d44b60bb15")
температура = json.loads(requests.get(url).text)["current"]["temp"]
осадки = json.loads(requests.get(url).text)["current"]["weather"][0]["description"]
tts.say((round(температура), "градусов.", осадки))
print(round(температура), "градусов", осадки)
tts.runAndWait()
if text == "включи новую песню":
tts.say("Включаю. Но скоро я сама научусь петь")
tts.runAndWait()
song = AudioSegment.from_mp3("01.mp3")
play(song)
if text == "покажи погоду":
tts.say("С вами всегда тепло и солнечно, создатель. Загружаю погоду.")
tts.runAndWait()
webbrowser.open("https://yandex.ru/pogoda/moscow/maps/nowcast?via=mmapw")
if text == "баста":
global и
и = 1
except:
print('Error')
и = 0
while и == 0:
record_volume() | 330ce7d976e1a8e37f727618984641ae46419e19 | [
"Python"
] | 1 | Python | lemosbor/Vora | e4b0e73fcf8a92cfa06c1321353353972db4df9f | d89a6d92ed12148b9fc3e5d51ea0e96ac9f65c3e |
refs/heads/master | <file_sep>0.3 (2017-10-15)
----------------
- Make use of ii-django-package-settings
0.2 (2017-10-14)
----------------
- Manifest fix
0.1 (2017-10-14)
----------------
- Project creation
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from io import open
from setuptools import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
def get_packages(package):
"""
Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
version = get_version('ii_django_backup')
setup(
name='ii_django_backup',
version=version,
description='ideallical django backup',
url='https://github.com/ideallical/ii-django-backup',
download_url=('https://github.com/ideallical/ii-django-backup/archive/'
'{}.tar.gz'.format(version)),
author='ideallical',
author_email='<EMAIL>',
keywords=['django', 'backup', 'dropbox'],
license='BSD',
install_requires=[
'dropbox>=7.1.1',
'ii-django-package-settings>=0.1'
],
packages=get_packages('ii_django_backup'),
package_data=get_package_data('ii_django_backup'),
zip_safe=False
)
<file_sep>import datetime
import os
import subprocess # nosec
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import dropbox
from dropbox.exceptions import AuthError
from ii_django_backup.settings import backup_settings as bs
class Command(BaseCommand):
help = 'Make backup of Django database'
def check(self):
"""
Check if ii-django-backup is configured properly.
:return: None
:raises CommandError: if ii-django-backup is not configured correctly
"""
backup_dir = bs.DIR
dropbox_dir = bs.DROPBOX_DIR
dropbox_access_token = bs.DROPBOX_ACCESS_TOKEN
use_dropbox = (dropbox_dir is not None) or (
dropbox_access_token is not None)
if backup_dir is None:
raise CommandError(
'Please declare II_DJANGO_BACKUP[\'DIR\'], as the default '
'backup dir is based on settings.BASE_DIR, and your settings '
'don\'t define a BASE_DIR.')
if use_dropbox and (dropbox_dir is None):
raise CommandError(
'Please declare II_DJANGO_BACKUP[\'DROPBOX_DIR\'] or disable '
'using dropbox by setting II_DJANGO_BACKUP[\'DROPBOX_ACCESS_'
'TOKEN\'] to None')
if use_dropbox and (dropbox_access_token is None):
raise CommandError(
'Please declare II_DJANGO_BACKUP[\'DROPBOX_ACCESS_TOKEN\'] or '
'disable using dropbox by setting II_DJANGO_BACKUP[\'DROPBOX_D'
'IR\'] to None')
def get_backup_command(self, db_dict, backup_path):
"""
Return backup shell command for given database dict and path.
:param dict db_dict: used database information
:param str backup_path: used path to export backup to
:return: the backup command string
:rtype: str
:raises CommandError: if the db_dict['ENGINE'] is unknown
"""
db_type = db_dict['ENGINE']
# set default HOST
if db_dict['HOST'] in ['', None]:
db_dict['HOST'] = 'localhost'
if db_type in ['django.db.backends.postgresql_psycopg2',
'django.contrib.gis.db.backends.postgis']:
# set default Postgres PORT
if db_dict['PORT'] in ['', None]:
db_dict['PORT'] = 5432
cmd = ('pg_dump -U {USER} -h {HOST} -p {PORT} -Fc {NAME}'
' --no-owner').format(**db_dict)
elif db_type == 'django.db.backends.mysql':
# set default MySQL PORT
if db_dict['PORT'] in ['', None]:
db_dict['PORT'] = 3306
cmd = (
'mysqldump --opt -Q -h {HOST} -P {PORT} -u {USER} '
'{NAME}').format(**db_dict)
else:
raise CommandError(
'No backup command is implemented for {}'.format(db_type))
if bs.USE_GZIP:
return '{cdm} | gzip > {backup_path}'.format(
cdm=cmd, backup_path=backup_path)
return '{cdm} > {backup_path}'.format(cdm=cmd, backup_path=backup_path)
def handle(self, *args, **options):
"""
Creates backup for Django's default database connection.
If configured, it will also upload this backup to the given dropbox
folder.
:return: None
:raises CommandError: if ii-django-backup is not configured correctly
:raises CommandError: if the db_dict['ENGINE'] is unknown
:raises CommandError: if script couldn't connect to Dropbox
"""
self.check()
# gather configuration variables
db_dict = settings.DATABASES['default']
# create an unique backup filename
filename = bs.NAME_GENERATOR_FUNC(db_dict=db_dict,
dt=datetime.datetime.now())
# when using GZIP, add .gz extension to the filename
if bs.USE_GZIP:
filename = '{}.gz'.format(filename)
backup_dir = bs.DIR
backup_path = os.path.join(backup_dir, filename)
# create backup-dir if it doesn't exists yet
if not os.path.isdir(backup_dir):
os.mkdir(backup_dir)
# backup locally
cmd = self.get_backup_command(db_dict, backup_path)
subprocess.call(cmd, shell=True) # nosec
# backup to dropbox if needed
if bs.DROPBOX_ACCESS_TOKEN is not None:
try:
dbx = dropbox.Dropbox(bs.DROPBOX_ACCESS_TOKEN)
with open(backup_path, 'rb') as f:
data = f.read()
dbx.files_upload(data, '{}{}'.format(
bs.DROPBOX_DIR, filename))
except AuthError:
raise CommandError(
'Could not connect to Dropbox. Please check II_DJANGO_BAC'
'KUP[\'DROPBOX_TOKEN\'].')
<file_sep>__title__ = 'ideallical Django backup'
__version__ = '0.3'
__author__ = 'ideallical'
__license__ = 'BSD'
__copyright__ = 'Copyright 2017 ideallical'
# Version synonym
VERSION = __version__
<file_sep># ideallical django backup
[![pypi-version]][pypi]
## Requirements
* Python (3.5)
## Installation
Install using `pip`...
```shell
$ pip install ii-django-backup
```
## Running
```shell
$ python manage.py backup_database
```
## Configuration
Configure ii-django-backup in your Django settings:
```python
INSTALLED_APPS = {
[..],
'ii_django_backup',
[..],
}
II_DJANGO_BACKUP = {
'DIR': '/var/backups/',
'DROPBOX_ACCESS_TOKEN': '**********',
'DROPBOX_DIR': '/websitename/staging/',
'USE_GZIP': True,
}
```
Setting `II_DJANGO_BACKUP['DIR']` to `'/var/backups/'` let's ii-django-backup
know where to store your backups locally.
By default this is set to `os.path.join(settings.BASE_DIR, 'backups')`; this
requires `BASE_DIR` being defined in your Django settings.
Setting `II_DJANGO_BACKUP['DROPBOX_ACCESS_TOKEN']` to `**********`, enables
backup to Dropbox using this access token. By default this is set to `None`.
Setting `II_DJANGO_BACKUP['DROPBOX_DIR']` to `/websitename/staging/` let's
ii-django-backup know where to store your backups at Dropbox.
By default this is set to `None`.
Setting `II_DJANGO_BACKUP['USE_GZIP']` to `True` enables Gzipping the backup
file. By default this is set to `True`.
# Trouble shooting
Note that passwords are NOT sent over the commandline (for security reasons).
Therefor you need to make sure the mysqldump and pgdump commands know your
database's password to do backups without password prompt.
For Postgres:
either create a `.pgpass` file in your home-directory and chmod it 600.
The content could look like this:
```t
localhost:5432:database_name:username:secretPassword
```
or set an ENV named PGPASSWORD with your Postgres database password. For Heroku you would be able to do this like so:
```shell
$ heroku config:set PGPASSWORD=<PASSWORD>
```
For MySQL:
Create a `.my.cnf` file in your home-directory and chmod it 600.
The content could look like this:
```t
[mysqldump]
user=username
password=<PASSWORD>
[client]
user=username
password=<PASSWORD>
```
[pypi-version]: https://img.shields.io/pypi/v/ii-django-backup.svg
[pypi]: https://pypi.python.org/pypi/ii-django-backup
<file_sep>def default(db_dict, dt):
db_name = db_dict['NAME']
engine = db_dict['ENGINE']
if engine in ['django.db.backends.postgresql_psycopg2',
'django.contrib.gis.db.backends.postgis']:
extension = '.backup'
else:
extension = '.sql'
return '{time}_db_backup-{db_name}{extension}'.format(
time=dt.strftime('%Y.%m.%d.%H.%M.%S'),
db_name=db_name,
extension=extension
)
<file_sep>"""
Settings for ideallical django backup are all namespaced in the
II_DJANGO_BACKUP setting.
For example your project's `settings.py` file might look like this:
II_DJANGO_BACKUP = {
'DIR': '/var/backups/',
'DROPBOX_ACCESS_TOKEN': '**********',
'DROPBOX_DIR': '/websitename/staging/',
'USE_GZIP': True,
}
This module provides the `backup_setting` object, that is used to access
ideallical Django backup settings, checking for user settings first, then
falling back to the defaults.
"""
from __future__ import unicode_literals
import os
from django.conf import settings
from ii_django_package_settings.settings import PackageSettings
try:
backup_dir = os.path.join(settings.BASE_DIR, 'backups')
except AttributeError:
backup_dir = None
class BackupSettings(PackageSettings):
NAME = 'II_DJANGO_BACKUP'
DOC = 'https://github.com/ideallical/ii-django-package-settings/'
DEFAULTS = {
'DIR': backup_dir,
'NAME_GENERATOR_FUNC': 'ii_django_backup.name_generators.default',
'DROPBOX_ACCESS_TOKEN': None,
'DROPBOX_DIR': None,
'USE_GZIP': True,
}
IMPORT_STRINGS = ('NAME_GENERATOR_FUNC', )
backup_settings = BackupSettings(None)
| 5fad2bd3559b88e5fd9660736f6d1e5f21f9e2f6 | [
"Markdown",
"Python"
] | 7 | Markdown | ideallical/ii-django-backup | db8d4219d865ea2d10fad9757d8b7d8a3808cbe0 | 4e24e6ce699e569bd70fc320021e95d2ff13e7ed |
refs/heads/master | <file_sep>package com.mrpowergamerbr.protocolsupportswordblocking;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers.Hand;
import com.comphenix.protocol.wrappers.WrappedWatchableObject;
import com.mrpowergamerbr.protocolsupportswordblocking.packetwrapper.WrapperPlayClientBlockPlace;
import com.mrpowergamerbr.protocolsupportswordblocking.packetwrapper.WrapperPlayServerEntityMetadata;
import protocolsupport.api.ProtocolSupportAPI;
import protocolsupport.api.ProtocolVersion;
public class ProtocolSupportSwordBlocking extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
// Block Place (sword blocking)
// We don't need to process block dig because it seems that's unaffected (yay!)
protocolManager.addPacketListener(new PacketAdapter(this,
ListenerPriority.HIGHEST,
new PacketType[] { PacketType.Play.Client.BLOCK_PLACE, PacketType.Play.Server.ENTITY_METADATA }) {
@Override
public void onPacketReceiving(PacketEvent event) {
if (ProtocolSupportAPI.getProtocolVersion(event.getPlayer()).isBefore(ProtocolVersion.MINECRAFT_1_9)) { // If it is a client before MC 1.9...
if (event.getPacketType() == PacketType.Play.Client.BLOCK_PLACE) { // and it is a block place packet
event.setCancelled(true); // We are going to cancel this packet...
WrapperPlayClientBlockPlace wrappedPacket = new WrapperPlayClientBlockPlace(event.getPacket().shallowClone()); // Clone the packet!
wrappedPacket.setHand(Hand.OFF_HAND); // Change the held item to off hand
try {
ProtocolLibrary.getProtocolManager().recieveClientPacket(event.getPlayer(), event.getPacket(), false); // Now we are going to resend the original packet...
ProtocolLibrary.getProtocolManager().recieveClientPacket(event.getPlayer(), wrappedPacket.getHandle(), false); // ...and simulate a receive client packet
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onPacketSending(PacketEvent event) {
if (ProtocolSupportAPI.getProtocolVersion(event.getPlayer()).isBefore(ProtocolVersion.MINECRAFT_1_9)) { // check if below 1.9
if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
WrapperPlayServerEntityMetadata wrappedPacket = new WrapperPlayServerEntityMetadata(event.getPacket().deepClone()); // Clone the packet!
for (WrappedWatchableObject packet : wrappedPacket.getMetadata()) {
if (packet.getIndex() == 6) { //shield
if (packet.getHandle() instanceof Byte && (byte) packet.getValue() == 3) {
packet.setValue((byte) 1);
}
}
}
event.setPacket(wrappedPacket.getHandle());
}
}
}
});
getLogger().info("Successfully Loaded.");
}
}
<file_sep># ProtocolSupport1.8Combat
Allows blocking/sheilds to be seen on other clients when using OldCombatMecanics and ProtocolSupport
Updated Fork of MrPowerGamerBR's Sword Blocking Plugin
> Currently only supports versions 1.13-1.16.5, 1.12 and below support coming soon!
### Dependencies
- [ProtocolLib](https://www.spigotmc.org/resources/protocollib.1997/)
- [ProtoclSupport(duh)](https://protocol.support/)
- [OldCombatMechanics](https://www.spigotmc.org/resources/oldcombatmechanics-disable-1-9-hit-cooldown.19510/)
### Installation
1. Go to the [releases page](https://github.com/codergautam/ProtocolSupport1.8Combat/releases)
2. Download the latest release jar file
3. Drag it into your plugins folder on the server
4. Make sure you got all dependencies installed
5. Start the server and Enjoy!
### Support
If you get any issues with the plugin, please create a new issue from the [issues page](https://github.com/codergautam/ProtocolSupport1.8Combat/issues)
| e7ad4158a0b64b2830d287bb1c72eaabd2ab2c05 | [
"Markdown",
"Java"
] | 2 | Java | codergautam/ProtocolSupport1.8Combat | fb9dbbbf29e03085dd385a8696fdd2c9b4b0f568 | 335c503c34a8bfdb58b53308aa2f7eb2ec398185 |
refs/heads/main | <repo_name>Caronte-Aqueronte/Unidad6ProgramacionModular<file_sep>/src/Ejercicio1.java
package src;
import java.util.Scanner;
public class Ejercicio1 {
public static void main(String[] args) {
Ejercicio1 ej = new Ejercicio1();
}
int[] arreglo = new int[5];
public Ejercicio1() {
llenarArreglo();
mostrarArreglo();
}
public void llenarArreglo() {
Scanner scanner = new Scanner(System.in);
for (int x = 0; x < arreglo.length; x++) {
System.out.println("Ingrese un numero");
arreglo[x] = scanner.nextInt();
}
}
public void mostrarArreglo() {
for (int x = 0; x < arreglo.length; x++) {
System.out.println("Elemento en la posicion " + x + " es " + arreglo[x]);
}
}
}<file_sep>/src/Ejercicio3.java
package src;
import java.util.Scanner;
public class Ejercicio3 {
public static void main(String[] args) {
Ejercicio3 ejercicio3 = new Ejercicio3();
}
int[] arreglo = new int[8];
Scanner scanner = new Scanner(System.in);
public Ejercicio3() {
int num;
llenarArreglo();
System.out.println("Ingrese numero a buscar");
num = scanner.nextInt();
String confirmacion = buscarEnArreglo(num);
System.out.println(confirmacion);
}
public void llenarArreglo() {
int random;
for (int x = 0; x < arreglo.length; x++) {
random = (int) (Math.random() * (100 - 1) + 1);
arreglo[x] = random;
System.out.println("Elemento en la posicion " + (x + 1) + " = " + arreglo[x]);
}
}
public String buscarEnArreglo(int num) {
for (int item : arreglo) {
if (num == item) {
return "Encontrado";
}
}
return "No encontrado";
}
}<file_sep>/src/Ejercicio2.java
package src;
public class Ejercicio2 {
public static void main(String[] args) {
Ejercicio2 ejercicio2 = new Ejercicio2();
}
int[] arreglo = new int[10];
int mayor;
public Ejercicio2() {
llenarArreglo();
imprimirDatos();
}
public void llenarArreglo() {
int random;
for (int x = 0; x < arreglo.length; x++) {
random = (int) (Math.random() * (99 - 0) + 0);
compararMayor(random);
arreglo[x] = random;
}
}
public void compararMayor(int num) {
if (num > mayor) {
mayor = num;
}
}
public int contarRepeticiones() {
int contador = 0;
for (int item : arreglo) {
if (item == mayor) {
contador++;
}
}
return contador;
}
public void imprimirDatos() {
for (int x = 0; x < arreglo.length; x++) {
System.out.println("Elemento en la posicion " + (x + 1) + " = " + arreglo[x]);
}
System.out.println("El numero mayor es " + mayor);
System.out.println("El numero mayor se repite " + contarRepeticiones() + " veces");
}
}<file_sep>/src/Ejercicio8.java
package src;
import java.util.Scanner;
public class Ejercicio8 {
public static void main(String[] args) {
Ejercicio8 ejercicio = new Ejercicio8();
}
String[] arreglo = new String[5];
String[] arreglo2 = new String[5];
public Ejercicio8() {
llenarArreglo(arreglo);
llenarArreglo(arreglo2);
compararPalabras();
}
public void llenarArreglo(String[] arreglo) {
Scanner scanner = new Scanner(System.in);
String palabra;
for (int x = 0; x < arreglo.length; x++) {
System.out.println("Ingrese valor en la posicion " + (x + 1) + " del arreglo");
palabra = scanner.nextLine();
arreglo[x] = palabra;
}
}
public void compararPalabras() {
System.out.println("Palabra del primer arreglo en la primera posicion es " + arreglo[0] + " tiene " + arreglo[0].length() + " letras");
System.out.println("Palabra del segundo arreglo en la primera posicion es " + arreglo2[0] + " tiene " + arreglo2[0].length() + " letras");
if (arreglo[0].length() == arreglo2[0].length()) {
System.out.println("Tienen la misma cantidad de letras");
} else {
System.out.println("No tienen la misma cantidad de letras");
}
}
}<file_sep>/src/Ejercicio5.java
package src;
import java.util.Arrays;
import java.util.Scanner;
public class Ejercicio5 {
public static void main(String[] args) {
Ejercicio5 ejercicio = new Ejercicio5();
}
int[] arreglo = new int[101];
Scanner scanner = new Scanner(System.in);
public Ejercicio5() {
String decision;
do {
for (int x = 0; x < arreglo.length; x++) {
arreglo[x] = 0;
}
llenarArreglo();
System.out.println("Pusle cualquier tecla para ingresar otra clase, pulse S para salir");
decision = scanner.next();
} while (!decision.equals("S"));
}
public void llenarArreglo() {
int num;
int contador = 0;
int x = 0;
String decision = "S";
do {
System.out.println("Ingrese nota nueva");
num = scanner.nextInt();
while (num < 0 || num > 10) {
System.out.println("Ingrese nota valida entre 0 y 10");
num = scanner.nextInt();
}
contador++;
arreglo[x] = num;
arreglo[x + 1] = -51;
System.out.println("Notas: " + Arrays.toString(arreglo));
System.out.println("Promedio de notas: " + calcularPromedio(contador));
System.out.println("Desea agregar mas notas, Si.cualquier tecla No.S");
decision = scanner.next();
x++;
} while (x < 100 & !decision.equals("S"));
if (!decision.equals("S")) {
System.out.println("100 alumnos registrado, no hay mas cupo");
}
}
public double calcularPromedio(int contador) {
int x = 0;
int suma = 0;
while (arreglo[x] != -51) {
suma += arreglo[x];
x++;
}
return ((double) suma / contador);
}
}<file_sep>/src/Ejercicio9.java
package src;
import java.util.Scanner;
public class Ejercicio9 {
public static void main(String[] args) {
Ejercicio9 ejercicio = new Ejercicio9();
}
int[][] arreglo;
int[][] arreglo2;
int[][] suma;
public Ejercicio9() {
definirEspacio();
llenarMatriz(arreglo);
llenarMatriz(arreglo2);
mostrarMatriz(arreglo, 1);
mostrarMatriz(arreglo2, 2);
sumarMatrices();
mostrarMatriz(suma, 3);
}
public void definirEspacio() {
Scanner scanner = new Scanner(System.in);
int posx1;
int posy1;
int posx2;
int posy2;
System.out.println("Ingrese el espacio de la primera matriz primero filas luego columnas");
posx1 = scanner.nextInt();
posy1 = scanner.nextInt();
System.out.println("Ingrese el espacio de la segunda matriz primero filas luego columnas");
posx2 = scanner.nextInt();
posy2 = scanner.nextInt();
if (posx1 == posx2 && posy1 == posy2) {
arreglo = new int[posx1][posy1];
arreglo2 = new int[posx2][posy2];
suma = new int[posx2][posy2];
} else {
System.exit(0);
}
}
public void llenarMatriz(int[][] matriz) {
int random;
for (int x = 0; x < matriz.length; x++) {
for (int y = 0; y < matriz[x].length; y++) {
random = (int) (Math.random() * (10 - 1) + 1);
matriz[x][y] = random;
}
}
}
public void mostrarMatriz(int[][] matriz, int numero) {
System.out.println("Matriz " + numero);
for (int x = 0; x < matriz.length; x++) {
System.out.print("*");
for (int y = 0; y < matriz[x].length; y++) {
System.out.print(matriz[x][y] + " ");
}
System.out.println("*");
}
}
public void sumarMatrices() {
for (int x = 0; x < suma.length; x++) {
for (int y = 0; y < suma[x].length; y++) {
suma[x][y] = (arreglo[x][y] + arreglo2[x][y]);
}
}
}
} | 669f02dd7fef1ef615f7a1a03999e4ff80cdd45c | [
"Java"
] | 6 | Java | Caronte-Aqueronte/Unidad6ProgramacionModular | 019188bd0e007f2a1507f819cf738e62ff1aed5a | b74e4dd2d0ed059aff15133284afded075167da9 |
refs/heads/master | <file_sep>/**
* External dependencies
*/
import { expect } from 'chai';
/**
* Internal dependencies
*/
import { parse, attr, prop, html, text, query } from '../src';
describe( 'hpq', () => {
// Markup
const markup = '<blockquote><p>…</p><p>…</p><cite class="large"><em>—</em> Andrew</cite></blockquote>';
// Element
let element;
before( () => {
const { JSDOM } = require( 'jsdom' );
global.window = new JSDOM( '' ).window;
global.document = window.document;
global.navigator = window.navigator;
element = document.createElement( 'div' );
element.innerHTML = markup;
element = element.firstChild;
} );
after( () => {
delete global.document;
delete global.window;
delete global.navigator;
} );
describe( 'parse()', () => {
it( 'should return undefined if passed no matchers', () => {
const result = parse( markup );
expect( result ).to.be.undefined;
} );
it( 'should accept a string of markup as source', () => {
const result = parse( markup, text( 'cite' ) );
expect( result ).to.equal( '— Andrew' );
} );
it( 'should return matcher value if passed function matcher', () => {
const result = parse( element, text( 'cite' ) );
expect( result ).to.equal( '— Andrew' );
} );
it( 'should return undefiend if passed matchers other than object, function', () => {
const result = parse( element, 2 );
expect( result ).to.be.undefined;
} );
it( 'should return parsed matches in shape of matcher object', () => {
const result = parse( element, {
author: text( 'cite' ),
} );
expect( result ).to.eql( {
author: '— Andrew',
} );
} );
} );
describe( 'prop()', () => {
it( 'should return a matcher function', () => {
const matcher = prop();
expect( matcher ).to.be.a( 'function' );
} );
it( 'should return property of current top node if undefined selector', () => {
const result = parse( element, prop( undefined, 'nodeName' ) );
expect( result ).to.equal( 'BLOCKQUOTE' );
} );
it( 'should return property of current top node if omitted selector', () => {
const result = parse( element, prop( 'nodeName' ) );
expect( result ).to.equal( 'BLOCKQUOTE' );
} );
it( 'should return undefined if selector does not match', () => {
const result = parse( element, prop( 'strong', 'nodeName' ) );
expect( result ).to.be.undefined;
} );
it( 'should return property of selector match by property', () => {
const result = parse( element, prop( 'cite', 'nodeName' ) );
expect( result ).to.equal( 'CITE' );
} );
} );
describe( 'attr()', () => {
it( 'should return a matcher function', () => {
const matcher = attr();
expect( matcher ).to.be.a( 'function' );
} );
it( 'should return attribute of current top node if undefined selector', () => {
const result = parse( element, query( 'cite', attr( undefined, 'class' ) ) );
expect( result ).to.eql( [ 'large' ] );
} );
it( 'should return attribute of current top node if omitted selector', () => {
const result = parse( element, query( 'cite', attr( 'class' ) ) );
expect( result ).to.eql( [ 'large' ] );
} );
it( 'should return undefined if selector does not match', () => {
const result = parse( element, attr( 'strong', 'class' ) );
expect( result ).to.be.undefined;
} );
it( 'should return undefined if match does not have attribute', () => {
const result = parse( element, attr( 'cite', 'data-unknown' ) );
expect( result ).to.be.undefined;
} );
it( 'should return attribute value of match', () => {
const result = parse( element, attr( 'cite', 'class' ) );
expect( result ).to.equal( 'large' );
} );
} );
describe( 'html()', () => {
it( 'should return a matcher function', () => {
const matcher = html();
expect( matcher ).to.be.a( 'function' );
} );
it( 'should return inner HTML of top node if no selector', () => {
const result = parse( element, html() );
expect( result ).to.match( /^<p>/ );
} );
it( 'should return inner HTML of selector match', () => {
const result = parse( element, html( 'cite' ) );
expect( result ).to.equal( '<em>—</em> Andrew' );
} );
} );
describe( 'text()', () => {
it( 'should return a matcher function', () => {
const matcher = text();
expect( matcher ).to.be.a( 'function' );
} );
it( 'should return text content of top node if no selector', () => {
const result = parse( element, text() );
expect( result ).to.match( /^…/ );
} );
it( 'should return text content of selector match', () => {
const result = parse( element, text( 'cite' ) );
expect( result ).to.equal( '— Andrew' );
} );
} );
describe( 'query()', () => {
it( 'should return a matcher function', () => {
const matcher = query();
expect( matcher ).to.be.a( 'function' );
} );
it( 'should return array of parse on matched nodes', () => {
const result = parse( element, { text: query( 'p', text() ) } );
expect( result ).to.eql( {
text: [ '…', '…' ],
} );
} );
} );
} );
<file_sep>/**
* External dependencies
*/
import { expect } from 'chai';
/**
* Internal dependencies
*/
import getPath from '../src/get-path';
describe( 'getPath()', () => {
it( 'should return simple path value', () => {
const value = getPath( { a: 1 }, 'a' );
expect( value ).to.equal( 1 );
} );
it( 'should return deep value', () => {
const value = getPath( { a: { b: 1 } }, 'a.b' );
expect( value ).to.equal( 1 );
} );
it( 'should return undefined on missing simple path value', () => {
const value = getPath( {}, 'a' );
expect( value ).to.be.undefined;
} );
it( 'should return undefined on missing deep path value', () => {
const value = getPath( {}, 'a.b' );
expect( value ).to.be.undefined;
} );
it( 'should allow retrieving by prototype', () => {
const value = getPath( {}, 'valueOf' );
expect( value ).to.be.a( 'function' );
} );
it( 'should allow deep retrieving by prototype', () => {
const value = getPath( { a: {} }, 'a.valueOf' );
expect( value ).to.be.a( 'function' );
} );
} );
| 1ac80485dab4f8d8c9d387858f906a9fac51e1a2 | [
"JavaScript"
] | 2 | JavaScript | gziolo/hpq | c9704368e06be8cfc3d71696dee44d93f7e9dd87 | be190d177ff3f14ec76aceb9c942c686d2a423c8 |
refs/heads/master | <repo_name>paulz/OutputTo<file_sep>/README.md
# OutputTo
[](https://travis-ci.org/paulz/OutputTo)
[](http://cocoapods.org/pods/OutputTo)
[](http://cocoapods.org/pods/OutputTo)
[](http://cocoapods.org/pods/OutputTo)
## Usage
[Kiwi](https://github.com/kiwi-bdd/Kiwi) Spec example to verify NSLog() output
```objc
[[[PZOutputTo log:^{
[subject doSomething];
}] should] containString:@"something has been done successfully"];
```
See more Kiwi Spec examples in [PZOutputToSpec.m](Example/Tests/PZOutputToSpec.m)
To run the example project, clone the repo, open [Example/OutputTo.xcworkspace](Example/OutputTo.xcworkspace) and run tests.
## Requirements
NSLog, printf or compatible to standard output stream loggers
## Installation
OutputTo is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod 'OutputTo'
```
## Author
<NAME>, http://github.com/paulz
## License
OutputTo is available under the MIT license. See the [LICENSE](LICENSE) file for more info.
<file_sep>/Example/Podfile
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
inhibit_all_warnings! # KWHaveValueMatcher.m:45:47: warning: 'isEqualOrMatches:' is deprecated
target 'Tests', :exclusive => true do
pod "OutputTo", :path => "../"
pod 'Kiwi'
end
<file_sep>/OutputTo.podspec
Pod::Spec.new do |s|
s.name = "OutputTo"
s.version = "0.3.1"
s.summary = "Capture NSLog or printf output"
s.description = <<-DESC
Returns string containing output captured during execution of a block.
Typical use to assert log output made by code under the test.
Could be used in production code.
Works with printf(), NSLog() and other loggers.
Can capture output to stdout or stderr streams.
DESC
s.homepage = "https://github.com/paulz/OutputTo"
s.license = 'MIT'
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/paulz/OutputTo.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/iospaulz'
s.ios.deployment_target = '7.0'
s.macos.deployment_target = '10.12'
s.requires_arc = true
s.source_files = 'Pod/Classes'
s.frameworks = 'Foundation'
end
| 3130ff5c05c8f0129b3a46402d63b6aff6a3e656 | [
"Markdown",
"Ruby"
] | 3 | Markdown | paulz/OutputTo | 965f013429ef050f4a6e7748ca61f29bf4488901 | 4ae3de0da00ff7c93c01cd6934362a6bf0ede93b |
refs/heads/master | <file_sep>#!/usr/bin/env python3
import math
import sys
def gcd(a,b):
a = abs(a)
b = abs(b)
if a < b:
a, b = b, a
if b == 0:
return a
return gcd(b, a%b)
def pow(a,b,m):
"""
calculate a^b % m
where a, b, m are integers and
a >= 0, b >= 0, m > 0
"""
assert type(a) == int
assert type(b) == int
assert type(m) == int
assert a >= 0
assert b >= 0
assert m > 0
def __pow(a,b):
if b == 0:
return 1 % m
if b == 1:
return a % m
r = __pow(a,b//2)
r = r * r % m
if b % 2 == 1:
r = r * a % m
return r
def __pow_no_recursive(a,b):
l = 0
while (1<<l) <= b:
l += 1
r = 1 % m
for i in reversed(range(l)):
r = r * r % m
if (1<<i) & b:
r = r * a % m
#assert r == __pow(a,b)
return r
return __pow_no_recursive(a,b)
def isprime(n):
"""
determine whether n is a prime
where n is an integer
Reference:
http://home.sandiego.edu/~dhoffoss/teaching/cryptography/10-Rabin-Miller.pdf
"""
assert type(n) == int
if n <= 1:
return False
# now n > 1
small_primes = [2,3,5,7,11,13,17,19,23]
phi = [2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 341550071728321, 3825123056546413051]
# n < phi[i] -> use small_primes [0..i] is enough
# phi -> Smallest odd number for which Miller-Rabin primality test on bases <= n-th prime does not reveal compositeness.
# see OEIS A014233
for i in range(len(phi)):
if n < phi[i]:
small_primes = small_primes[:i+1]
break
if n in small_primes:
return True
if n <= max(small_primes):
return False
# now n > max(small_primes)
def isprime_fermat(n,b):
# n is a fermat psudoprime with base b ?
return pow(b,n-1,n) == 1
def isprime_rabin_miller(n,b):
# rabin-miller prime test with base b
# fermat test first
if not isprime_fermat(n,b):
return False
# let n - 1 = 2^s * m, m is odd, s >= 1
m = n - 1
s = 0
while m % 2 == 0:
m = m // 2
s = s + 1
#
r = pow(b,m,n)
if r == 1 or r == n - 1:
return True
while s > 0:
r = pow(r,2,n)
if r == 1:
return False
if r == n - 1:
return True
s -= 1
return False
for p in small_primes:
if not isprime_rabin_miller(n,p):
return False
return True
class Prime:
def __init__(self, upper):
self.n = 2
self.upper = upper
def __init__(self, lower, upper):
self.n = lower
while not isprime(self.n):
self.n = self.n + 1
self.upper = upper
def __iter__(self):
return self
def __next__(self):
if self.n >= self.upper:
raise StopIteration
n = self.n
self.n = self.n + 1
while self.n < self.upper and not isprime(self.n):
self.n = self.n + 1
return n
def next(self):
return self.__next__()
def main():
# test
u = 2048
print('Primes in range [2,%d) :'%(u),list(Prime(u)))
if __name__ == '__main__':
main()
<file_sep>#include <iostream>
using namespace std;
typedef unsigned int uint;
int main(){
uint upper = 1U << 30;
uint count = 0;
#pragma omp parallel for
for ( uint n = 1; n <= upper; n++ ){
if ( n ^ (2*n) ^ (3*n) )
;
else{
#pragma omp atomic
count += 1;
}
}
cout << count << endl;
return 0;
}
<file_sep>/*
Compiling:
g++ -Ofast -fopenmp
Machine:
Debian, GCC 4.8.2 @ Xeon E5-2630 V2 * 2
Running time:
2m28s
*/
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
typedef long long ll;
ll pow_mod( ll a, int b, ll mod ){
if ( b == 0 ) return 1 % mod;
if ( b == 1 ) return a % mod;
ll r = pow_mod(a,b/2,mod);
r = r * r % mod;
if ( b % 2 ) r = r * a % mod;
return r;
}
const ll mod = 10000000000000000LL + 61;
const int maxn = 1000000 + 10;
const int maxr = 100000 + 10;
const int max_len_x_bin = 30;
int m;
int r;
ll g[2][maxr];
ll g_curr, g_next;
int x_bin[max_len_x_bin];
int len_x_bin;
ll cgs[max_len_x_bin][maxr];
void get_ng( int p, int x ){
g_next = 1 ^ g_curr;
memset(g[g_next],0,sizeof(g[g_next]));
int i = 0;
len_x_bin = 0;
while ( true ){
if ( (1<<i) > x )
break;
x_bin[len_x_bin++] = ( 1 << i ) & x;
i += 1;
}
memset(cgs,0,sizeof(cgs[0])*len_x_bin);
memcpy(cgs[0],g[g_curr],sizeof(g[g_curr]));
ll _p = p;
for ( int i = 0; i < len_x_bin - 1; i++ ){
//#pragma omp parallel
{
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
if ( cgs[i][v] != 0 ){
cgs[i+1][v] += cgs[i][v];
cgs[i+1][v] %= mod;
}
}
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
if ( cgs[i][v] != 0 ){
int pos = v * _p%r;
#pragma omp atomic
cgs[i+1][pos] += cgs[i][v];
}
}
#pragma omp parallel for
for ( int v = 0; v < r; v++ )
if ( cgs[i][v] != 0 ){
cgs[i+1][v] %= mod;
}
}
_p = _p * _p % r;
}
ll shift_p;
shift_p = pow_mod(p, x, r);
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
#pragma omp atomic
g[g_next][v*shift_p%r] += cgs[0][v];
}
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
g[g_next][v] %= mod;
}
for ( int i = 0; i < len_x_bin; i++ )
if ( x_bin[i] ){
x_bin[i] = 0;
x -= 1 << i;
shift_p = pow_mod(p, x, r);
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
#pragma omp atomic
g[g_next][v*shift_p%r] += cgs[i][v];
}
#pragma omp parallel for
for ( int v = 0; v < r; v++ ){
g[g_next][v] %= mod;
}
}
g_curr = g_next;
}
bool isprime[maxn];
ll solve( int n, int d ){
m = 0;
while ( (ll)(pow(10,m)) < d )
m += 1;
r = (ll)(pow(10,m));
g_curr = 0;
g_next = 1;
memset(g,0,sizeof(g));
g[g_curr][1] = 1;
memset(isprime,true,sizeof(isprime));
isprime[0] = isprime[1] = false;
for( int p = 2; p <= n; p++ )
if ( isprime[p] )
for ( int q = p + p; q <= n; q += p )
isprime[q] = false;
for ( int p = 2; p <= n; p++ )
if ( isprime[p] ){
int x = 0;
ll _p = p;
while ( _p <= n ){
x += n/_p;
_p *= p;
}
get_ng( p , x );
}
return g[g_curr][d];
}
int main(){
ll answer = solve(1000000,65432);
cout << answer << endl;
return 0;
}<file_sep>#!/usr/bin/env python3
def main():
l = 50
f = [0.0] * (l+1)
while True:
g = [0.0] * (l+1)
for d in range(1,l+1):
pt = [1.0/6.0,4.0/6.0,1.0/6.0]
mt = [-1,0,1]
for i in range(3):
for j in range(3):
p = pt[i]*pt[j]
m = mt[j] - mt[i]
nd = d + m
if nd > l:
nd = l-(nd-l)
if nd < 0:
nd = -nd
g[d] += (f[nd] + 1) * p
max_diff = max([ abs(fv-gv) for fv,gv in zip(f,g) ])
f = g
if max_diff < 1e-15:
break
#print(max_diff)
print(f[l])
main()
<file_sep>project-euler
=============
My works on ProjectEuler
<file_sep>#!/usr/bin/env python3
# Python version is too slow
# Consider the cpp version for the same problem
from libmath import numberthy
def get_ng(g, p, x, mod):
r = len(g)
ng = [0] * r
#print('get_ng','p =',p,'x =',x)
assert x > 0
# x_bin : x's binary representation
x_bin = []
i = 0
while True:
if (1 << i) > x:
break
x_bin.append( (1 << i) & x )
i += 1
print(x_bin)
def get_cgs():
cgs = [ [0] * r for i in range(len(x_bin)) ]
cgs[0] = g
_p = p
for i in range(len(x_bin)-1):
for v in range(r):
if cgs[i][v] != 0:
cgs[i+1][v] += cgs[i][v]
cgs[i+1][v] %= mod
cgs[i+1][v*_p%r] += cgs[i][v]
cgs[i+1][v*_p%r] %= mod
_p = _p * _p % r
#print('cgs size',len(cgs),len(cgs[0]))
return cgs
cgs = get_cgs()
ng = [0] * r
cg = cgs[0]
shift_p = numberthy.pow(p, x, r)
for v in range(r):
ng[v*shift_p%r] += cg[v]
ng[v*shift_p%r] %= mod
for i in range(len(x_bin)):
if x_bin[i]:
x_bin[i] = 0
x -= 1<<i
cg = cgs[i]
shift_p = numberthy.pow(p, x, r)
for v in range(r):
ng[v*shift_p%r] += cg[v]
ng[v*shift_p%r] %= mod
return ng
def f(n,d,mod):
"""
f(n,d) = F(n!,d) in the problem statement
"""
# last m digit(s)
m = 0
while 10**m <= d:
m = m + 1
# r = 10^m
# range is [0,r)
r = 10**m
print('m =',m)
print('r =',r)
# g[v], v in [0,r)
# count
g = [0] * r
g[1] = 1
for p in numberthy.Prime(2,n+1):
# there are p^x in n!
# get x
x = 0
_p = p
while _p <= n:
x += n // _p
_p *= p
print('p =',p,'x =',x)
# ng is next_g
ng = get_ng(g, p, x, mod)
#print(ng)
#print()
g = ng
print(g[d])
#print(g)
return g[d]
#for p in numberthy.Prime(10**6+1):
# print(p)
ans = f(12, 12, 10**16)
print('ans =',ans)
print()
"""
ans = f(50, 123, 10**16)
print('ans =',ans)
print()
ans = f(10**6, 65432, 10**16+61)
print('ans =',ans)
"""
| c840eaabf2518e82581ba74d3a2507107bee3673 | [
"Markdown",
"Python",
"C++"
] | 6 | Python | alantian/project-euler | bc0d73b1023d22441f104272ee2ef624cb683baf | bb138473f734959827cf5bf173f9b16fe3d3d507 |
refs/heads/master | <file_sep>package br.com.thiagojose.simulalogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText edtUsuario;
private EditText edtSenha;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUsuario = findViewById(R.id.edtUsuario);
edtSenha = findViewById(R.id.edtSenha);
findViewById(R.id.btnEntrar).setOnClickListener(login());
}
private View.OnClickListener login() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
String usuario = edtUsuario.getText().toString();
String senha = edtSenha.getText().toString();
if ("senac".equals(usuario) && "123".equals(senha)) {
mostrarMensagem(getString(R.string.login_sucesso));
} else {
mostrarMensagem(getString(R.string.login_error));
}
}
};
}
private void mostrarMensagem(String msg){
Toast.makeText(this,msg, Toast.LENGTH_LONG).show();
}
}
| bac76ffdad155c7b05d90db63ceda4a3763181a1 | [
"Java"
] | 1 | Java | ThiagoJFreitas/login | f150f6e0726ee7ec59d35062fb51c93f665cdd46 | 45b2c96b4b4feca6a714027fc234a91c2b21e79b |
refs/heads/master | <repo_name>hanahboles/bubble_game<file_sep>/index.js
const startButton = document.querySelector('start');
const gameArea = document.querySelector('.game');
const scoreSpan = document.querySelector('.score');
let score = 0;
// Initializations for dots when first created
// size --- maybe a data attribute for value?
// color/image
// position on x axis
function init() {
var height = randomSize() + "px";
var position = randomPosition() + "px";
var obj = document.createElement("div");
obj.style.left = position;
obj.style.height = height;
obj.style.width = height;
obj.classList.add("dot");
//obj.setAttribute('data-point', '1');
gameArea.appendChild(obj);
obj.addEventListener("click", updateScore);
obj.addEventListener("click", () => obj.remove());
return obj;
}
function randomSize() {
return (Math.floor(Math.random() * 11) * 10);
}
function randomPosition() {
return (Math.floor(Math.random() * 11) * 100);
}
function start() {
setInterval(createDot, 5000);
}
function createDot() {
var dot = init();
//const dot = document.querySelector('.dot');
setInterval(fall, 50);
function fall() {
var pos = parsePosition(dot.style.top) + 10;
if (pos < 500) {
dot.style.top = pos + "px";
} else {
clearInterval();
dot.remove();
}
}
}
function parsePosition(pos) {
if (pos === '') {
pos = 0;
}
return parseInt(pos);
}
function updateScore() {
score = score + 1;
scoreSpan.innerHTML = score;
}
// Bugs
// ground level varies per size of dot
// the drop level changes when the dots come down too quickly
| f44d43febccbf5dd3ca7e519a9286fb48dda6ca0 | [
"JavaScript"
] | 1 | JavaScript | hanahboles/bubble_game | b538312cf91f2454a56ddc829fe8157e5b4798ac | edced868ab8889ede625d2d0dba9f3700d4a4631 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<p>
<p><button class="btn"name="account" onclick="window.location.href='vote.php'"> Back</button>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
</p>
<p><p><button class="btn"name="account" onclick="window.location.href='results.php'"> Voters</button>
<button class="btn"name="account" onclick="window.location.href='candidates.php'"> Candidates</button>
<button class="btn"name="account" onclick="window.location.href='votes.php'">Votes</button>
</p>
</section>
<div id="main2">
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/ussd/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM candidates");
echo " <table cellpadding='10' cellspacing='0' border='3'>
<caption='top'> registered CANDIDATES </caption>
<tr>
<td ></td> <td >NO.</td> <td >NAMES</td> <td>REG NO.</td> <td>CANDIDATE ID</td> <td>PARTY</td> <td>POST</td>
</tr>";
$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> <input type='checkbox' name='edit' value='{$row['NAMES']}' />
</td> <td> $i . </td> <td>{$row['NAMES']} </td> <td>{$row['REGNO']} </td> <td>{$row['CAND_ID']} </td> <td>{$row['PARTY']} </td> <td>{$row['POST']}</td> </tr>";
}
$i++;
echo '</table>';
}
?>
</div>
<div id="footer">
<p>Copyrights @Kisii university</p>
</div>
</div>
</body>
</html><file_sep># codeWiz
voting Ussd app
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
<script type ="text/javascript">
function PrintTable(){
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=1000, height=700, left=100, top=25";
var content_vlue = document.getElementById("print_content").innerHTML;
var docprint=window.open("","",disp_setting);
docprint.document.open();
docprint.document.write('<html><head><title>Clearance Power System</title>');
docprint.document.write('<link rel="stylesheet" href="layout/styles/layout.css" type="text/css" />');
docprint.document.write('</head><body onLoad="self.print()" style="width: 94%; font-size:9px; font-family:Times New Roman;">');
docprint.document.write(content_vlue);
docprint.document.write('</body></html>');
docprint.document.close();
docprint.focus();
}
</script>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<p>
<p><button class="btn"name="account" onclick="window.location.href='vote.php'"> Back</button>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
</p>
<p><p><button class="btn"name="account" onclick="window.location.href='results.php'"> Voters</button>
<button class="btn"name="account" onclick="window.location.href='candidates.php'"> Candidates</button>
<button class="btn"name="account" onclick="window.location.href='votes.php'">Votes</button>
</p>
</section>
<div id="main">
<table border='1' cellpadding='5' cellspacing='10'><tr><td>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM voter");
echo "<table cellpadding='10' cellspacing='0' border='3'>
<caption='top'> registered voters </caption>
<tr>
<td cellpadding='5'>NO.</td>
<td cellspacing='5'>Registration No.</td>
<td cellspacing='5'>phone no.</td>
</tr>";
//$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<=$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> $i . </td> <td>{$row['REGNO']} </td> <td>{$row['phone']}</td> </tr>";
}
$i++;
}
echo '</table>';
?>
</td>
<td>
<table>
<caption ='top'><h2>Voters' turn up</h2></caption>
<tr><td> Registered voters </td><td> <?php $root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT count(ID) FROM voter");
while($row = mysql_fetch_array($query, MYSQL_ASSOC) ){
$vts= "{$row['count(ID)']}";
echo "<h3>".$vts."<h3>";
}
?> </td></tr>
<tr><td> Student voted </td><td> <?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT sum(status) FROM voter where status = '1'");
while($row = mysql_fetch_array($query, MYSQL_ASSOC) ){
$vt= "{$row['sum(status)']}";
echo "<h3>".$vt."<h3>";
}
?> </td></tr>
<tr><td> Percentage turn-Up </td><td> <?php $resul = $vt/$vts;
echo $resul. "%";
?></td></tr>
</table>
</td></tr>
</table>
<input type='button' onclick='PrintTable()' value='Print'/>
</div>
<div id="footer">
<p>Copyrights @Kisii university</p>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<p><button class="btn"name="account" onclick="window.location.href='vote.php'"> Voter</button>
<button class="btn"name="account" onclick="window.location.href='candi.php'"> Candidate</button>
<button class="btn"name="account" onclick="window.location.href='results.php'">Result Reports</button>
</p>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
<a href="vote.php">Register voter</a>
</section>
<SCRIPT TYPE="text/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false();
}else{
return true;
}
</SCRIPT>
<div id="main">
<form action='#' method='post'>
<table cellspacing='5' cellpadding='10'align='center'>
<caption position ='top'> REGISTER VOTER </caption>
<tr><td>National_ID No:</td><td><input type='text' name='nat'/></td></tr>
<tr><td>REG No:</td><td><input type='text' name='Reg'/></td></tr>
<tr><td>Phone No:</td> <td> <input name="someid" type="number" onkeypress=" return isNumberKey(event)" /> </td> </tr>
<tr><td></td><td><input type='submit' name='Submit' value='Submit'/></td>
<td><input type='Reset' name='Reset' value='Reset' onclick='reset()'/></td></tr>
<script type= 'text/javascript'>
function reset(){
nat.setText("");
}
</script>
</table>
</form>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
if(isset($_POST['Submit'])) {
$pin= randal();
$reg=$_POST['Reg'];
$nato= $_POST['nat'];
$phonee = $_POST['someid'];
//check there is some entry.
if($phonee!='' && $reg!=''&& $nato !=''){
//fetch data from database and check if the registration exist in student table. if not dont register
$query = mysql_query ("select * from students where national_id='$nato'") or die(mysql_error());
$row = mysql_fetch_array($query, MYSQL_ASSOC);
if ($nato = "{$row['national_id']}"&& $reg = "{$row['RegNo']}"){
// sms code.
require_once('sms/AfricasTalkingGateway.php');
$username = "trey";
$apikey = "<KEY>";
$recipients = $phonee;
$message = $pin;
$gateway = new AfricasTalkingGateway($username, $apikey);
try
{
$results = $gateway->sendMessage($recipients, $message);
foreach($results as $result) {
echo " Number: " .$result->number;
echo '</br>';
echo " Status: " .$result->status;
echo '</br>';
echo " MessageId: " .$result->messageId;
echo '</br>';
echo " Cost: " .$result->cost."\n";
}
}
catch ( AfricasTalkingGatewayException $e )
{
echo "Encountered an error while sending: ".$e->getMessage();
}
if (!@AfricasTalkingGatewayException){
$query= mysql_query("insert into voter ( REGNO, phone, PASSWORD)
values('$reg','$phonee','$pin')") or die(mysql_error());
echo 'ONE RECORD ADDED!';
}
}
else{
echo 'You are not our student';
}
}
else{
echo 'Please fill the fields';
}
}
?>
<?php
//generate random no.
function randal($length=4){
$passwrd="";
$possible="0123456789";
$maxlength= strlen($possible);
if($length > $maxlength){
$length = $maxlength;
}
$i=0;
while($i<$length){
$char = substr($possible,mt_rand(1,$maxlength-1),1);
if(!strstr($passwrd,$char)){
$passwrd.=$char;
$i++;
}
}
return $passwrd;
}
?>
</div>
<div id="footer">
Copyrights @Kisii university
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<p> </p>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
<p> </p>
</section>
<div id="main">
<table cellspacing='5' align='center'>
<caption position ='top'> <img src="12.png" width='220px' height= '150px' ></caption>
<tr><td>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='uname'/></td></tr>
<tr><td>Password:</td><td><input type='password' name='upwd'/></td></tr>
<tr><td></td><td><button class="btn"name="submit" onclick="window.location.href='vote.php'"> Login</button>
</td></tr>
<tr><td> <a style="font-weight:bold;" href="pass.php">forgot password <span style="background:#ffffff;color:#ff4800">»</span></a></td></tr>
</table>
</form>
</td></tr></table>
<?php
session_start();
if(isset($_POST['submit']))
{
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/ussd/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$name=$_POST['uname'];
$pwd=$_POST['<PASSWORD>'];
if($name!=''&&$pwd!='')
{
$query=mysql_query("select * from admin where USERNAME='".$name."' and
PASSWORD='".$pwd."'")
or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
$_SESSION['name']=$name;
header('location:vote.php');
}
else
{
echo'You entered wrong username or password';
}
}
else
{
echo'Enter both username and password';
}
}
?>
</div>
<div id="footer">
<p>Copyrights @Kisii university</p>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a><p>
</div>
<p><button class="btn"name="account" onclick="window.location.href='vote.php'"> Voter</button>
<button class="btn"name="account" onclick="window.location.href='candi.php'"> Candidate</button>
<button class="btn"name="account" onclick="window.location.href='results.php'">Result Reports</button>
<h4>Time:<input type='text' name ='time' value ='tyme'></h4>
</section>
<div id="main1">
<table border='1' cellpadding='5' cellspacing='10'><tr><td>
<?php
//presidential results
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM votes WHERE post='President'");
echo " <table cellpadding='10' cellspacing='0' border='0'>
<caption='top'> Presidential results </caption>
<tr>
<td cellpadding='5'>NO.</td>
<td cellspacing='5'>Candidate Name</td>
<td cellspacing='5'>Candidate ID</td>
<td cellspacing='5'>votes</td>
</tr>";
$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> $i . </td> <td>{$row['CANDI_ID']} </td> <td>{$row['CANDI_ID']} </td> <td>{$row['Vote']}</td> </tr>";
}
$i++;
echo '</table>';
}
?>
</td>
<td>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM votes WHERE post='Director_Academic'");
echo " <table cellpadding='10' cellspacing='0' border='0'>
<caption='top'> Director Academic results </caption>
<tr>
<td cellpadding='5'>NO.</td>
<td cellspacing='5'>Candidate Name</td>
<td cellspacing='5'>Candidate ID</td>
<td cellspacing='5'>votes</td>
</tr>";
$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> $i . </td> <td>{$row['CANDI_ID']} </td> <td>{$row['CANDI_ID']} </td> <td>{$row['Vote']}</td> </tr>";
}
$i++;
echo '</table>';
}
?>
</td>
</tr>
<tr>
<td>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM votes WHERE post='Finance_Secretary'");
echo " <table cellpadding='10' cellspacing='0' border='0'>
<caption='top'> Finance Secretary results </caption>
<tr>
<td cellpadding='5'>NO.</td>
<td cellspacing='5'>Candidate Name</td>
<td cellspacing='5'>Candidate ID</td>
<td cellspacing='5'>votes</td>
</tr>";
$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> $i . </td> <td>{$row['CANDI_ID']} </td> <td>{$row['CANDI_ID']} </td> <td>{$row['Vote']}</td> </tr>";
}
$i++;
echo '</table>';
}
?>
</td>
<td>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$query= mysql_query("SELECT * FROM votes WHERE post='Gender_social_welfar'");
echo " <table cellpadding='10' cellspacing='0' border='0'>
<caption='top'> Gender social welfare results </caption>
<tr>
<td cellpadding='5'>NO.</td>
<td cellspacing='5'>Candidate Name</td>
<td cellspacing='5'>Candidate ID</td>
<td cellspacing='5'>votes</td>
</tr>";
$i=1;
while($row = mysql_fetch_array($query, MYSQL_ASSOC) )
{
for($i=1;$i<$row = mysql_fetch_array($query,MYSQL_ASSOC);$i++){
echo " <tr>
<td> $i . </td> <td>{$row['CANDI_ID']} </td> <td>{$row['CANDI_ID']} </td> <td>{$row['Vote']}</td> </tr>";
}
$i++;
echo '</table>';
}
?>
</td>
</tr>
</table>
</div>
<div id="footer">
Copyrights @Kisii university
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<hr>
<p><button class="btn"name="account" onclick="window.location.href='vote.php'"> Voter</button>
<button class="btn"name="account" onclick="window.location.href='candi.php'"> Candidate</button>
<button class="btn"name="account" onclick="window.location.href='results.php'">Result Reports</button></p>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
<a href="candi.php">Register Candidate</a>
</section>
<div id="main">
<form action='#' method='post'>
<table cellspacing='5' cellpadding='10'align='center'>
<caption position ='top'> REGISTER CANDIDATE </caption>
<tr><td>Name:</td><td><input type='text' name='Cname'/></td></tr>
<tr><td>REG No:</td><td><input type='text' name='REGNO'/></td></tr>
<tr><td>Candidate ID:</td><td><input type='text' name='CAND_ID'/></td></tr>
<tr><td>Post:</td><td> <select name='pst'>
<option value=''>Select Post </option>
<option value='President'>President </option>
<option value='Finance_Secretary'>Finance_Secretary </option>
<option value='Sec_general'>Sec_general </option>
<option value='Special_needs'>Special_needs </option>
<option value='Sports'>Sports </option>
<option value='Director_Academic'>Director_Academic </option>
<option value='Gender_social_welfare'>Gender_social_welfare </option>
</select> </td></tr>
<tr><td>Party:</td><td><select name= 'part'>
<option value=''>Select Party </option>
<option value='FREEDOM'>FREEDOM</option>
<option value='REBLICAN'>REBLICAN</option>
<option value='DEMOCRATIC'>DEMOCRATIC</option>
</select> </td></tr>
<tr><td></td><td><input type='submit' name='Register' value='Register'/></td></tr>
</table>
</form>
<?php
if(isset($_POST['Register'])) {
session_start();
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$name=$_POST['Cname'];
$Reg= $_POST['REGNO'];
$party=$_POST['part'];
$CAN_ID=$_POST['CAND_ID'];
$post=$_POST['pst'];
if($name!='' && $Reg!='' && $party!='' && $CAN_ID!='' &&$post!=''){
$query=mysql_query("insert into votes ( CANDI_ID,post)
values('$CAN_ID','$post')")
or die(mysql_error());
$query =mysql_query("insert into candidates ( NAMES,REGNO,CAND_ID,PARTY,POST)
values('$name','$Reg','$CAN_ID','$party','$post')") or die(mysql_error());
echo "1 record added";
}
else {
echo 'Please fill in all the fields';
}
}
else {
}
?>
</div>
<div id="footer">
Copyrights @Kisii university
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="favicon.ico">
<title> kisii university</title>
<link href="main1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="header"><img src="logo.png" alt="--" >
</div>
<section>
<p> </p>
<div id ="logs">
<a style="font-weight:bold;" href="logout.php">Logout <span style="background:#ffffff;color:#ff4800">»</span></a>
</div>
<p> </p>
</section>
<div id="main">
<table cellspacing='5' align='center'>
<form action='#' method='post'>
<table cellspacing='5' align='center'>
<tr><td>User name:</td><td><input type='text' name='uname'/></td></tr>
<tr><td>Phone No:</td> <td> <input name="someid" type="number" onkeypress=" return isNumberKey(event)" /></td></tr>
<tr><td></td><td><button class="btn"name="submit" onclick="window.location.href='check.php'"> Submit</button>
</td></tr>
</table>
</form>
</td></tr></table>
<SCRIPT TYPE="text/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false();
}else{
return true;
}
</SCRIPT>
<?php
session_start();
if(isset($_POST['submit']))
{
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include ("$root/Configuration.php");
$parameters=new Parameters();
$hostname=$parameters->getHost();
$user_name=$parameters->getUserName();
$PSW=$parameters->getPassword();
$data_base=$parameters->getDatabase();
$dbhandle = mysql_connect($hostname, $user_name, $PSW) ;
mysql_select_db($data_base);
$name=$_POST['uname'];
$pwd=$_POST['<PASSWORD>'];
if($name!=''&&$pwd!='')
{
$query=mysql_query("select * from admin where USERNAME='".$name."' and
TELEPHONE='".$pwd."'")or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
//sms sending
require_once('sms/AfricasTalkingGateway.php');
$username = "trey";
$apikey = "<KEY>";
$recipients = $pwd;
$message = $pin;
$gateway = new AfricasTalkingGateway($username, $apikey);
try
{
$results = $gateway->sendMessage($recipients, $message);
foreach($results as $result) {
echo " Number: " .$result->number;
echo '</br>';
echo " Status: " .$result->status;
echo '</br>';
echo " MessageId: " .$result->messageId;
echo '</br>';
echo " Cost: " .$result->cost."\n";
}
}
catch ( AfricasTalkingGatewayException $e )
{
echo "Encountered an error while sending: ".$e->getMessage();
}
if (!@AfricasTalkingGatewayException){
header('location:check.php');
}
}
else
{
echo'You entered wrong username or phone no.';
}
}
else
{
echo'Enter both username and phone no.';
}
}
?>
</div>
<div id="footer">
<p>Copyrights @Kisii university</p>
</div>
</div>
</body>
</html> | 6c5e5b9b34489cbde095b08fbd6532756ae6f410 | [
"Markdown",
"PHP"
] | 8 | PHP | winniegakuru/codeWiz | 2510fc80c6f2f1da91e1cb1381aa86919cffe1a4 | b4c85a5b34b4f3f69db6002190a0f6b5b25425a7 |
refs/heads/main | <file_sep>using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Homer.Api.Domain.Entities.Imoveis
{
[Table("ImovelImagem")]
public partial class ImovelImagem
{
[Key]
public int Id { get; set; }
public int ImovelId { get; set; }
public string Descricao { get; set; }
public byte[] Imagem { get; set; }
}
}
<file_sep>package com.homer.imovel.app
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.homer.imovel.app.network.ImageRequester
import com.homer.imovel.app.network.ImovelEntry
class ImovelCardViewAdapter internal constructor(private val imovelList: List<ImovelEntry>) : RecyclerView.Adapter<ImovelCardViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImovelCardViewHolder {
val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.hmr_imovel_card, parent, false)
return ImovelCardViewHolder(layoutView)
}
override fun onBindViewHolder(holder: ImovelCardViewHolder, position: Int) {
try {
if (position < imovelList.size) {
val imovel = imovelList[position]
holder.imovelTitulo.text = imovel.titulo
holder.imovelLocal.text = imovel.local
ImageRequester.setImageFromStrB64(holder.imovelImage, imovel.imagemBinStr)
}
} catch (e: Exception) {
println("**** Ocorreu um erro:")
println(e.message)
}
}
override fun getItemCount(): Int {
return imovelList.size
}
}<file_sep>package com.homer.imovel.app.controllers
import com.homer.imovel.app.models.RequestResult
import retrofit2.Call
import retrofit2.http.POST
public interface EndPoints {
@POST("api/Imoveis/ListaDosImoveis")
fun getListaDosImoveis() : Call<RequestResult>
@POST("api/Imoveis/ObterTodos")
fun getTodosOsImoveis() : Call<RequestResult>
}<file_sep>package com.homer.imovel.app.network
import android.content.Context
import android.graphics.Bitmap
import android.util.LruCache
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley
import com.homer.imovel.app.application.HmrViewerApp
import android.graphics.BitmapFactory
import android.util.Base64
import android.widget.ImageView
object ImageRequester {
private val requestQueue: RequestQueue
private val imageLoader: ImageLoader
private val maxByteSize: Int
init {
val context = HmrViewerApp.instance
this.requestQueue = Volley.newRequestQueue(context)
this.requestQueue.start()
this.maxByteSize = calculateMaxByteSize(context)
this.imageLoader = ImageLoader(
requestQueue,
object : ImageLoader.ImageCache {
private val lruCache = object : LruCache<String, Bitmap>(maxByteSize) {
override fun sizeOf(url: String, bitmap: Bitmap): Int {
return bitmap.byteCount
}
}
@Synchronized
override fun getBitmap(url: String): Bitmap? {
return lruCache.get(url)
}
@Synchronized
override fun putBitmap(url: String, bitmap: Bitmap) {
lruCache.put(url, bitmap)
}
})
}
fun setImageFromStrB64(networkImageView: ImageView, strImageB64: String) {
val bm = convertString64ToImage(strImageB64)
networkImageView.setImageBitmap(bm);
}
fun convertString64ToImage(base64String: String): Bitmap {
val decodedString = Base64.decode(base64String, Base64.DEFAULT)
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
}
private fun calculateMaxByteSize(context: Context): Int {
val displayMetrics = context.resources.displayMetrics
val screenBytes = displayMetrics.widthPixels * displayMetrics.heightPixels * 4
return screenBytes * 3
}
}<file_sep>using Homer.Api.Domain.Service.Sistema;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;
namespace Homer.Api.App.Controllers
{
public class BaseController : ControllerBase
{
ILogSistemaService _iLogSistemaService;
public BaseController(IHttpContextAccessor httpContextAccessor, ILogSistemaService iLogSistemaService)
{
_iLogSistemaService = iLogSistemaService;
}
public ObjectResult RetornarErroInterno(Exception ex, string metodo)
{
string mensagemErro = ex.Message;
_iLogSistemaService.GravarLogErro(ex);
return StatusCode((int)HttpStatusCode.InternalServerError, mensagemErro);
}
}
}
<file_sep>package com.homer.imovel.app.Helpers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class RestUtils {
companion object {
private const val apiUrl: String = "http://10.0.2.2:7001"
fun getRestClient() : Retrofit {
val httpClient: OkHttpClient.Builder = OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
val client: OkHttpClient = httpClient.build()
return Retrofit.Builder()
.baseUrl(this.apiUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
}
}
}<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.CrossCutting.IOC
{
public class ConfigureRepository
{
public static void ConfigureDependeciesRepository(IServiceCollection serviceCollaction)
{
serviceCollaction.AddScoped(typeof(Homer.Api.Domain.Interface.Repository.Imoveis.IImovelRepository),
typeof(Homer.Api.Data.Repository.Imoveis.ImovelRepository));
serviceCollaction.AddScoped(typeof(Homer.Api.Domain.Interface.Repository.Sistema.ILogSistemaRepository),
typeof(Homer.Api.Data.Repository.Sistema.LogSistemaRepository));
}
}
}
<file_sep>using Homer.Api.Domain.Entities.Imoveis;
using Homer.Api.Domain.Entities.Sistema;
using Homer.Api.Domain.Service.Imoveis;
using Homer.Api.Domain.Service.Sistema;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Homer.Api.App.Controllers
{
[EnableCors("PolicyCORS")]
[Route("api/[controller]")]
[ApiController]
public class ImoveisController : BaseController
{
private readonly ILogSistemaService _iLogSistemaService;
private readonly IImovelService _ImovelService;
private ResponseResult<Imovel> _response = new ResponseResult<Imovel>();
public ImoveisController(IHttpContextAccessor iHttpContextAccessor, ILogSistemaService iLogSistemaService, IImovelService ImovelService)
: base(iHttpContextAccessor, iLogSistemaService)
{
_ImovelService = ImovelService;
_iLogSistemaService = iLogSistemaService;
}
[HttpPost("ListaDosImoveis")]
public async Task<IActionResult> ListaDosImoveis()
{
try
{
var retorno = await _ImovelService.ListaDeImoveis();
_response.ListEntities = retorno;
_response.Success = true;
}
catch (Exception ex)
{
_response.Success = false;
_response.Message = "Não foi possível obter a lista dos imoveis, devido a um erro interno do servidor. Contate o suporte p/maiores informações.";
}
return Ok(_response);
}
[HttpPost("ObterTodos")]
public async Task<IActionResult> ObterTodos()
{
try
{
var retorno = await _ImovelService.ObterTodos();
_response.ListEntities = retorno;
_response.Success = true;
}
catch (Exception ex)
{
_response.Success = false;
_response.Message = "Não foi possível obter todos os imoveis, devido a um erro interno do servidor. Contate o suporte p/maiores informações.";
}
return Ok(_response);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.Domain.Helpers
{
public class BaseContextHelpers
{
private static string _ConnStr = "";
public static string GetConnectionStr() => _ConnStr;
public static string SetConnectionStr(string value) => _ConnStr = value;
}
}
<file_sep>package com.homer.imovel.app.models
import com.google.gson.annotations.SerializedName
import java.util.*
data class RequestResult (
@SerializedName("entity")
var Entity : Any,
@SerializedName("listEntities")
var ListEntities : Array<Object>,
@SerializedName("success")
var Success : Boolean,
@SerializedName("message")
var Message : String
)
<file_sep>using Homer.Api.Data.Context;
using Homer.Api.Domain.Interface.Repository.Sistema;
using Microsoft.AspNetCore.Http;
using System;
namespace Homer.Api.Data.Repository.Sistema
{
public class LogSistemaRepository : BaseContext, ILogSistemaRepository
{
public LogSistemaRepository(IHttpContextAccessor iHttpContextAccessor) : base(iHttpContextAccessor) { }
public void GravarLogErro(Exception errorModel)
{
//implemente aqui log de erros
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.Domain.Interface.Repository.Sistema
{
public interface ILogSistemaRepository
{
void GravarLogErro(Exception errorModel);
}
}
<file_sep>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
using Homer.Api.Data.Context;
using Homer.Api.CrossCutting.IOC;
using Microsoft.EntityFrameworkCore;
using System;
using Homer.Api.Domain.Helpers;
namespace Homer.Api.App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMemoryCache();
services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
services.AddResponseCompression(option => { option.Providers.Add<GzipCompressionProvider>(); });
ConfigureService.ConfigureDependeciesService(services);
ConfigureRepository.ConfigureDependeciesRepository(services);
string conStr = Configuration.GetConnectionString("DefaultConnection");
BaseContextHelpers.SetConnectionStr(conStr);
var serverVersion = new MySqlServerVersion(new Version(5, 7, 17));
services.AddDbContextPool<BaseContext>(
dbContextOptions => dbContextOptions
.UseMySql(conStr, serverVersion)
.EnableDetailedErrors()
);
var ver = ServerVersion.AutoDetect(conStr);
services.AddDbContext<BaseContext>(options => options.UseMySql(conStr, ver));
//CORS
string[] hostPermitido = new string[] { "*", "http://localhost:3000", "http://localhost:3001" };
services.AddCors(options =>
{
options.AddPolicy("PolicyCORS", builder => builder
.WithOrigins(hostPermitido)
.AllowAnyMethod()
.AllowAnyHeader()
);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("PolicyCORS");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>package com.homer.imovel.app
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
class ImovelCardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imovelCard: MaterialCardView = itemView.findViewById(R.id.imovel_card)
var imovelImage: ImageView = itemView.findViewById(R.id.imovel_image)
var imovelTitulo: TextView = itemView.findViewById(R.id.imovel_titulo)
var imovelLocal: TextView = itemView.findViewById(R.id.imovel_local)
}<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Homer.Api.Domain.Entities.Imoveis;
namespace Homer.Api.Domain.Interface.Repository.Imoveis
{
public interface IImovelRepository
{
Task<IEnumerable<Imovel>> ListaDeImoveis();
Task<IEnumerable<Imovel>> ObterTodos();
}
}
<file_sep> <NAME>vel Viewer
===================
Esse projeto é um exemplo de uma Aplicação formada por Fronend Mobile e Backend API
- FRONTEND: foi desenvolvido todo em usando linguagem Kotlin e usando IDE IntelliJ IDEA Community Edition
* Usando acesso a API através RESTFull client HTTP Retrofit e OkHttp ambos da SquareUp
* Unsado também a lib Material Design para android
- BACKEND: responsável por fornecer API que alimenta o front. Foi desenvolvido em DotNet Core 5.0
* Utilizada IDE Visual Studio 2019 Community
* Arquitura uma simples DDD (Domain Driven Design) para persistir os dados.
* Banco de dados utilizado é o MySQL;
Obs.
===
* Para rodar:
- Altere no Backend a connectionString do arquivo appsettings.json de acordo com suas configurações;
- Altere no Frontend no arquivo RestUtils.kt a constante "apiUrl" de acordo com a sua necessidade;
- Criar o banco de dados com base no script mencionado aqui;
Script do Banco de Dados MySQL
==============================
* No arquivo "homerdb.sql" tem os script para criar e insert´s para dados fictícios nas tabelas
* Na connectionString da API (backend) precisa informar o usuário e senha de conexão com o banco de dados mysql
* Se preferir também pode ser utilizado o "MariaDB" como motor de banco de dados que também funciona;
<file_sep>package com.homer.imovel.app.models
import com.google.gson.annotations.SerializedName
data class Imovel (
@SerializedName("id")
var id : Int,
@SerializedName("descricao")
var Descricao : String,
@SerializedName("localizacao")
var Localizacao : String,
@SerializedName("imagemCapa")
var ImagemCapa : String,
@SerializedName("imagens")
var Imagens : MutableList<ImovelImagens> = TODO()
)<file_sep>using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.CrossCutting.IOC
{
public class ConfigureService
{
public static void ConfigureDependeciesService(IServiceCollection serviceCollaction)
{
serviceCollaction.AddTransient<Homer.Api.Domain.Service.Imoveis.IImovelService,
Homer.Api.Service.Imoveis.ImovelService>();
serviceCollaction.AddTransient< Homer.Api.Domain.Service.Sistema.ILogSistemaService,
Homer.Api.Service.Sistema.LogSistemaService>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Homer.Api.Domain.Service.Imoveis;
using Homer.Api.Domain.Interface.Repository.Imoveis;
using Homer.Api.Domain.Entities.Imoveis;
namespace Homer.Api.Service.Imoveis
{
public class ImovelService: IImovelService
{
private IImovelRepository _imovelRepository;
public ImovelService(IImovelRepository imovelRepository)
{
_imovelRepository = imovelRepository;
}
public async Task<IEnumerable<Imovel>> ListaDeImoveis() =>
await _imovelRepository.ListaDeImoveis();
public async Task<IEnumerable<Imovel>> ObterTodos() =>
await _imovelRepository.ObterTodos();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.Domain.Service.Sistema
{
public interface ILogSistemaService
{
void GravarLogErro(Exception errorModel);
}
}
<file_sep>using System;
using Homer.Api.Domain.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using MySql.Data.MySqlClient;
namespace Homer.Api.Data.Context
{
public class BaseContext : DbContext
{
private readonly IHttpContextAccessor _iHttpContextAccessor;
public string _connString {
get => BaseContextHelpers.GetConnectionStr();
set {
BaseContextHelpers.SetConnectionStr(value);
}
}
public BaseContext(IHttpContextAccessor iHttpContextAccessor)
{
_iHttpContextAccessor = iHttpContextAccessor;
}
public string getConnectionString() => _connString;
public BaseContext(string conn) : base()
{
_connString = conn;
}
public BaseContext(DbContextOptions<BaseContext> options) : base(options)
{
}
protected MySqlConnection OpenConnection()
{
try
{
var connectionString = getConnectionString();
var conn = new MySqlConnection(connectionString);
conn.Open();
return conn;
}
catch (Exception)
{
throw;
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var serverVersion = new MySqlServerVersion(new Version(5, 7, 17));
if (!string.IsNullOrWhiteSpace(_connString))
optionsBuilder.UseMySql(_connString, serverVersion);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Homer.Api.Domain.Entities.Sistema
{
public class ResponseResult<TEntity> where TEntity : class
{
public TEntity Entity { get; set; }
public IEnumerable<TEntity> ListEntities { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public ResponseResult()
{
this.ListEntities = new List<TEntity>();
Success = true;
}
}
}
<file_sep>package com.homer.imovel.app
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.homer.imovel.app.Helpers.RestUtils
import com.homer.imovel.app.controllers.EndPoints
import com.homer.imovel.app.models.Imovel
import com.homer.imovel.app.models.RequestResult
import com.homer.imovel.app.network.ImovelEntry
import kotlinx.android.synthetic.main.hmr_login_fragment.*
import kotlinx.android.synthetic.main.hmr_login_fragment.view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class LoginFragment : Fragment() {
var listaDados: MutableList<ImovelEntry> = mutableListOf()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.hmr_login_fragment, container, false)
view.next_button.setOnClickListener {
if (!isPasswordValid(password_edit_text.text)) {
password_text_input.error = getString(R.string.hmr_error_senha)
} else {
password_text_input.error = null
getImveis(view)
}
}
view.password_edit_text.setOnKeyListener { _, _, _ ->
if (isPasswordValid(password_edit_text.text)) {
password_text_input.error = null
}
false
}
return view
}
private fun isPasswordValid(text: Editable?): Boolean {
return text != null && text.length >= 8
}
fun setEsperaVisible(visivel: Boolean){
if (visivel){
espera_circle.visibility = View.VISIBLE;
edUsuario.visibility = View.INVISIBLE;
password_text_input.visibility = View.INVISIBLE;
btnLayout.visibility = View.INVISIBLE;
}
else{
espera_circle.visibility = View.INVISIBLE;
btnLayout.visibility = View.VISIBLE;
edUsuario.visibility = View.VISIBLE;
password_text_input.visibility = View.VISIBLE;
}
}
fun getImveis(view: View){
val restClient = RestUtils.getRestClient()
setEsperaVisible(true)
val endpoint = restClient.create(EndPoints::class.java)
val callback = endpoint.getTodosOsImoveis()
callback.enqueue(object : Callback<RequestResult> {
override fun onFailure(call: Call<RequestResult>, t: Throwable) {
setEsperaVisible(false)
password_text_input.error = "Houve uma instabilidade na comunicação com o servidor, tente mais tarde!"
}
override fun onResponse(call: Call<RequestResult>, response: Response<RequestResult>) {
password_text_input.error = null
if (response.body()?.Success == true) {
val listaImovel = response.body()?.ListEntities
val gson = Gson()
val jsonArray: String = gson.toJson(listaImovel)
println(jsonArray)
val listImoveisType = object : TypeToken<List<Imovel>>() {}.type
val listaImoveis: List<Imovel> = gson.fromJson(jsonArray, listImoveisType)
listaImoveis.forEach {
val imovel: ImovelEntry = ImovelEntry(it.Descricao,it.ImagemCapa, it.Localizacao)
listaDados.add(imovel)
}
(activity as NavigationHost).navigateTo(ImovelGridFragment(listaDados), false)
setEsperaVisible(false)
}
}
})
}
}
<file_sep>using Homer.Api.Data.Context;
using Homer.Api.Domain.Entities.Imoveis;
using Homer.Api.Domain.Interface.Repository.Imoveis;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
using Dapper;
namespace Homer.Api.Data.Repository.Imoveis
{
public class ImovelRepository : BaseContext, IImovelRepository
{
public ImovelRepository(IHttpContextAccessor iHttpContextAccessor) : base(iHttpContextAccessor) { }
public async Task<IEnumerable<Imovel>> ListaDeImoveis()
{
try
{
using (var conn = OpenConnection())
{
var ret = await conn.GetAllAsync<Imovel>();
return ret;
};
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
return null;
}
public async Task<IEnumerable<Imovel>> ObterTodos()
{
IEnumerable<Imovel> Retorno = null;
try
{
using (var db = OpenConnection())
{
string sql = @"select * from Imovel i
left join ImovelImagem ii
on (i.Id = ii.ImovelId)";
var imovelDic = new Dictionary<int, Imovel>();
Retorno = (await db.QueryAsync<Imovel, ImovelImagem, Imovel>(sql,
(_I, _Ii) =>
{
Imovel imovel;
if (!imovelDic.TryGetValue(_I.Id, out imovel))
{
imovel = _I;
imovel.Imagens = new List<ImovelImagem>();
imovelDic.Add(imovel.Id, imovel);
}
imovel.Imagens.Add(_Ii);
return imovel;
}, new { }, splitOn: "Id")).Distinct().ToList();
}
}
catch (Exception e)
{
Console.WriteLine("Erro: {0}", e.Message);
}
return Retorno;
}
}
}
<file_sep>package com.homer.imovel.app.network
class ImovelEntry(
val titulo: String, val imagemBinStr: String, val local: String) {
}<file_sep>package com.homer.imovel.app.models
import com.google.gson.annotations.SerializedName
data class ImovelImagens (
@SerializedName("id")
var id : Int,
@SerializedName("imovelid")
var imovelId : Int,
@SerializedName("descricao")
var Descricao : String,
@SerializedName("imagem")
var Imagem : String
)<file_sep>include ':app'
rootProject.name = "Homer Imoveis Viewer App"<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Homer.Api.Domain.Entities.Imoveis
{
[Table("Imovel")]
public partial class Imovel
{
[Key]
public int Id { get; set; }
public string Descricao { get; set; }
public string Localizacao { get; set; }
public byte[] ImagemCapa { get; set; }
public List<ImovelImagem> Imagens { get; set; }
}
}
<file_sep>package com.homer.imovel.app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.homer.imovel.app.network.ImovelEntry
import kotlinx.android.synthetic.main.hmr_imovel_grid_fragment.view.*
class ImovelGridFragment(val listaImoveis: List<ImovelEntry>) : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.hmr_imovel_grid_fragment, container, false)
(activity as AppCompatActivity).setSupportActionBar(view.app_bar)
view.recycler_view.setHasFixedSize(true)
view.recycler_view.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false)
val adapter = ImovelCardViewAdapter(listaImoveis)
view.recycler_view.adapter = adapter
val largePadding = resources.getDimensionPixelSize(R.dimen.hmr_imoveis_grid_spacing)
val smallPadding = resources.getDimensionPixelSize(R.dimen.hmr_imoveis_grid_spacing_small)
view.recycler_view.addItemDecoration(ImovelGridItemDecor(largePadding, smallPadding))
return view;
}
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.hmr_toolbar_menu, menu)
super.onCreateOptionsMenu(menu, menuInflater)
}
}<file_sep>using Homer.Api.Domain.Interface.Repository.Sistema;
using Homer.Api.Domain.Service.Sistema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homer.Api.Service.Sistema
{
public class LogSistemaService : ILogSistemaService
{
private readonly ILogSistemaRepository _iLogSistemaRepository;
public LogSistemaService(ILogSistemaRepository iLogSistemaRepository)
{
_iLogSistemaRepository = iLogSistemaRepository;
}
public void GravarLogErro(Exception errorModel)
{
_iLogSistemaRepository.GravarLogErro(errorModel);
}
}
}
<file_sep>using Homer.Api.Domain.Entities.Imoveis;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Homer.Api.Domain.Service.Imoveis
{
public interface IImovelService
{
Task<IEnumerable<Imovel>> ListaDeImoveis();
Task<IEnumerable<Imovel>> ObterTodos();
}
}
| 298ab114e08514c5b52739699406ded21369411b | [
"Markdown",
"C#",
"Kotlin",
"Gradle"
] | 31 | C# | enavadev/homer | e82fcb6416370a779c206daa504d0d8393c00484 | d1e6e0425ba6e0ae572e4097a692fa97635c4412 |
refs/heads/master | <file_sep># Plan: Display antlet dependencies
# API:
## Primary features
zfs_dependencies - Print entire tree to screen in human readable format
zfs_dependencies -j, --json - Print entire tree to screen in json format
## Secondary features
zfs_dependencies antlet_name - Print children tree for this zfs name, to screen in human readable format
zfs_dependencies -j antlet_name - Print children tree for this zfs name, to screen in json format
zfs_dependencies -p antlet_name - Print parent tree for this zfs name, to screen in human readable format
zfs_dependencies -jp antlet_name - Print parent tree for this zfs name, to screen in json format
zfs_dependencies zfs_name - Print children tree for this zfs name, to screen in human readable format
zfs_dependencies -j zfs_name - Print children tree for this zfs name, to screen in json format
zfs_dependencies -p zfs_name - Print parent tree for this zfs name, to screen in human readable format
zfs_dependencies -jp zfs_name - Print parent tree for this zfs name, to screen in json format
# Ideal functioins
## Primary features
create_parser()
get_zfs_name_origin_list()
create_dependency_list(name_origin_list)
show_tree(dependency_list)
show_jtree(dependency_list)
## Secondary features
show_childen_tree(antlet_name, dependency_list)
show_parent_tree(antlet_name, dependency_list)
<file_sep>#!/usr/bin/python3
import unittest
from zfs_dependencies import *
class TestAntletDependencies(unittest.TestCase):
def setUp(self):
self.zfs_nolist = [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/_templates/ubuntu-xenial\t-',
'antlets/_templates/ubuntu-xenial@snap\t-',
'antlets/win1\tantlets/_templates/Win10@snap',
'antlets/win2\tantlets/_templates/Win10@snap',
'antlets/ubu1\tantlets/_templates/ubuntu-xenial@snap',
'antlets/ubu2\tantlets/_templates/ubuntu-xenial@snap',
'antlets/_tmp\t-'
]
self.long_zfs_dlist = [ { 'name': 'antlets',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates/Win10',
'parent': None,
'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap',
'parent': 'antlets/_templates/Win10',
'children': ['antlets/win1', 'antlets/win2']},
{ 'name': 'antlets/_templates/ubuntu-xenial',
'parent': None,
'children': ['antlets/_templates/ubuntu-xenial@snap']},
{ 'name': 'antlets/_templates/ubuntu-xenial@snap',
'parent': 'antlets/_templates/ubuntu-xenial',
'children': ['antlets/ubu1', 'antlets/ubu2']},
{ 'name': 'antlets/win1',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/win2',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/ubu1',
'parent': 'antlets/_templates/ubuntu-xenial@snap',
'children': []},
{ 'name': 'antlets/ubu2',
'parent': 'antlets/_templates/ubuntu-xenial@snap',
'children': []},
{ 'name': 'antlets/_tmp',
'parent': None,
'children': []}
]
def test_create_dependency_list_returns_a_list(self):
result = create_dependency_list(self.zfs_nolist)
self.assertIsInstance(result, list)
def test_create_dependency_list_returns_a_list_of_dicts(self):
result = create_dependency_list(self.zfs_nolist)
for item in result:
self.assertIsInstance(item, dict)
def test_create_dependency_list_each_dict_has_3_keys(self):
result = create_dependency_list(self.zfs_nolist)
for item in result:
self.assertEqual(len(item), 3)
def test_create_dependency_list_each_dict_children_key_is_a_list(self):
result = create_dependency_list(self.zfs_nolist)
for item in result:
self.assertIsInstance(item['children'], list)
def test_create_dependency_list(self):
result = create_dependency_list(self.zfs_nolist)
self.assertEqual(result, self.long_zfs_dlist)
def test_create_json_list_returns_a_list(self):
dlist = create_dependency_list(self.zfs_nolist)
result = create_json_list(dlist)
self.assertIsInstance(result, list)
def test_create_json_list_each_item_is_a_dict(self):
dlist = create_dependency_list(self.zfs_nolist)
result = create_json_list(dlist)
for item in result:
self.assertIsInstance(item, dict)
def test_create_json_list_each_dict_has_2_keys(self):
dlist = create_dependency_list(self.zfs_nolist)
result = create_json_list(dlist)
for item in result:
self.assertEqual(len(item), 2)
if __name__ == '__main__':
unittest.main()
<file_sep># No templates No antlets:
def nolist0():
return [ 'antlets\t-', 'antlets/_templates\t-', 'antlets/_tmp\t-' ]
def dlist0():
return [{ 'name': 'antlets', 'parent': None, 'children': []},
{ 'name': 'antlets/_templates', 'parent': None, 'children': []},
{ 'name': 'antlets/_tmp', 'parent': None, 'children': []}
]
def jlist0():
return [ { 'name': 'antlets', 'children': []},
{ 'name': 'antlets/_templates', 'children': []},
{ 'name': 'antlets/_tmp', 'children': []}
]
# No antlets 1 templates:
def nolist1():
return [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/_tmp\t-'
]
def dlist1():
return [ { 'name': 'antlets', 'parent': None, 'children': []},
{ 'name': 'antlets/_templates', 'parent': None, 'children': []},
{ 'name': 'antlets/_templates/Win10', 'parent': None, 'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap', 'parent': 'antlets/_templates/Win10', 'children': []},
{ 'name': 'antlets/_tmp', 'parent': None, 'children': []}
]
def jlist1():
return [ { 'name': 'antlets',
'children': []
},
{ 'name': 'antlets/_templates',
'children': []
},
{ 'name': 'antlets/_templates/Win10',
'children': [
{ 'name': 'antlets/_templates/Win10@snap',
'children': []
}
]
},
{ 'name': 'antlets/_tmp',
'children': []
}
]
# No antlets 2 templates:
def nolist2():
return [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/_templates/ubuntu-xenial\t-',
'antlets/_templates/ubuntu-xenial@snap\t-',
'antlets/_tmp\t-'
]
def dlist2():
return [ { 'name': 'antlets', 'parent': None, 'children': []},
{ 'name': 'antlets/_templates', 'parent': None, 'children': []},
{ 'name': 'antlets/_templates/Win10', 'parent': None, 'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap', 'parent': 'antlets/_templates/Win10', 'children': []},
{ 'name': 'antlets/_templates/ubuntu-xenial', 'parent': None, 'children': ['antlets/_templates/ubuntu-xenial@snap']},
{ 'name': 'antlets/_templates/ubuntu-xenial@snap', 'parent': 'antlets/_templates/ubuntu-xenial', 'children': []},
{ 'name': 'antlets/_tmp', 'parent': None, 'children': []}
]
def jlist2():
return [ { 'name': 'antlets',
'children': []
},
{ 'name': 'antlets/_templates',
'children': []
},
{ 'name': 'antlets/_templates/Win10',
'children': [
{ 'name': 'antlets/_templates/Win10@snap',
'children': []
}
]
},
{ 'name': 'antlets/_templates/ubuntu-xenial',
'children': [
{ 'name': 'antlets/_templates/ubuntu-xenial@snap',
'children': []
}
]
},
{ 'name': 'antlets/_tmp',
'children': []
}
]
# 1 templates 1 antlet:
def nolist11():
return [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/win1\tantlets/_templates/Win10@snap',
'antlets/_tmp\t-'
]
def dlist11():
return [ { 'name': 'antlets',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates/Win10',
'parent': None,
'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap',
'parent': 'antlets/_templates/Win10',
'children': ['antlets/win1', 'antlets/win2']},
{ 'name': 'antlets/win1',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/_tmp',
'parent': None,
'children': []}
]
def jlist11():
return [ { 'name': 'antlets',
'children': []},
{ 'name': 'antlets/_templates',
'children': []},
{ 'name': 'antlets/_templates/Win10',
'children': [
{ 'name': 'antlets/_templates/Win10@snap',
'children': [
{ 'name': 'antlets/win1',
'children': []}
]}
]},
{ 'name': 'antlets/_tmp',
'children': []}
]
# 1 templates 2 antlet:
def nolist12():
return [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/win1\tantlets/_templates/Win10@snap',
'antlets/win2\tantlets/_templates/Win10@snap',
'antlets/_tmp\t-'
]
def dlist12():
return [ { 'name': 'antlets',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates/Win10',
'parent': None,
'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap',
'parent': 'antlets/_templates/Win10',
'children': ['antlets/win1', 'antlets/win2']},
{ 'name': 'antlets/win1',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/win2',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/_tmp',
'parent': None,
'children': []}
]
def jlist12():
return [ { 'name': 'antlets',
'children': []},
{ 'name': 'antlets/_templates',
'children': []},
{ 'name': 'antlets/_templates/Win10',
'children': [
{ 'name': 'antlets/_templates/Win10@snap',
'children': [
{ 'name': 'antlets/win1',
'children': []},
{ 'name': 'antlets/win2',
'children': []}
]}
]},
{ 'name': 'antlets/_tmp',
'children': []}
]
# 2 templates 4 antlets:
def nolist24():
return [ 'antlets\t-',
'antlets/_templates\t-',
'antlets/_templates/Win10\t-',
'antlets/_templates/Win10@snap\t-',
'antlets/_templates/ubuntu-xenial\t-',
'antlets/_templates/ubuntu-xenial@snap\t-',
'antlets/win1\tantlets/_templates/Win10@snap',
'antlets/win2\tantlets/_templates/Win10@snap',
'antlets/ubu1\tantlets/_templates/ubuntu-xenial@snap',
'antlets/ubu2\tantlets/_templates/ubuntu-xenial@snap',
'antlets/_tmp\t-'
]
def dlist24():
return [ { 'name': 'antlets',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates',
'parent': None,
'children': []},
{ 'name': 'antlets/_templates/Win10',
'parent': None,
'children': ['antlets/_templates/Win10@snap']},
{ 'name': 'antlets/_templates/Win10@snap',
'parent': 'antlets/_templates/Win10',
'children': ['antlets/win1', 'antlets/win2']},
{ 'name': 'antlets/_templates/ubuntu-xenial',
'parent': None,
'children': ['antlets/_templates/ubuntu-xenial@snap']},
{ 'name': 'antlets/_templates/ubuntu-xenial@snap',
'parent': 'antlets/_templates/ubuntu-xenial',
'children': ['antlets/ubu1', 'antlets/ubu2']},
{ 'name': 'antlets/win1',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/win2',
'parent': 'antlets/_templates/Win10@snap',
'children': []},
{ 'name': 'antlets/ubu1',
'parent': 'antlets/_templates/ubuntu-xenial@snap',
'children': []},
{ 'name': 'antlets/ubu2',
'parent': 'antlets/_templates/ubuntu-xenial@snap',
'children': []},
{ 'name': 'antlets/_tmp',
'parent': None,
'children': []}
]
def jlist24():
return [ { 'name': 'antlets',
'children': []},
{ 'name': 'antlets/_templates',
'children': []},
{ 'name': 'antlets/_templates/Win10',
'children': [
{ 'name': 'antlets/_templates/Win10@snap',
'children': [
{ 'name': 'antlets/win1',
'children': []},
{ 'name': 'antlets/win2',
'children': []}
]}
]},
{ 'name': 'antlets/_templates/ubuntu-xenial',
'children': [
{ 'name': 'antlets/_templates/ubuntu-xenial@snap',
'children': [
{ 'name': 'antlets/ubu1',
'children': []},
{ 'name': 'antlets/ubu2',
'children': []}
]}
]},
{ 'name': 'antlets/_tmp',
'children': []}
]
<file_sep>#!/usr/bin/env python3
'''Get antlet dependencies'''
from subprocess import Popen, PIPE
from argparse import ArgumentParser
from pprint import pprint as pp
from sample_data import *
dependency_list = []
def create_parser():
parser = ArgumentParser(description='Returns a zfs dependency tree.\nIf no arguments are given the tree is printed in an easily readable format.')
parser.add_argument('-j', '--json',
help='return a json string',
action='store_true')
parser.add_argument('--version',
action='version',
version='%(prog)s 0.1.0')
parser.add_argument('-t', help="use sample data", choices=[0,1,2,11,24], type=int)
return parser
def get_zfs_name_origin_list():
'''Gets a list of strings, each containing the zfs name and origin - incluedes snapshots'''
zfs_name_origin_list = []
# get zfs list with snapshots and origins
with Popen(["zfs list -H -t filesystem,snapshot -o name,origin | grep -v antlets/_docker"],
shell=True, stdout=PIPE) as lister:
for bytes in lister.stdout:
line = bytes.decode().strip()
zfs_name_origin_list.append(line)
return zfs_name_origin_list
def create_dependency_list(zfs_name_origin_list):
'''Creates a dependency list from the 'name origin' list.
This is a list of dict's, one for each zfs name.
Keys are:
'name': String - zfs name
'parent' String - parent zfs name
'children' List of Strings - zfs names of dependent children'''
dependency_list = []
# convert each name,origin string into a dict
for item in zfs_name_origin_list:
name, _, origin = item.partition('\t')
dependency_list.append({'name':name, 'parent': origin})
# populate empty 'parent' values
for item in dependency_list:
if item['parent'] != '-':
continue
elif '@' in item['name']:
parent_name = item['name'].partition('@')[0]
item['parent'] = parent_name
else:
item['parent'] = None
# populate 'children' values
'''Does the current zfs name == another item 'parent' name'''
for parent_item in dependency_list:
children = []
for item in dependency_list:
if parent_item['name'] == item['parent']:
children.append(item['name'])
parent_item = parent_item.update({'children': children})
return dependency_list
def create_json_list(dependency_list):
def insert_children(zobj):
for item in dependency_list:
if zobj['name'] == item['name']:
for child in item['children']:
new_zobj = {'name': child, 'children': []}
zobj['children'].append(new_zobj)
insert_children(new_zobj)
jlist = []
# Create list of top level zfs (zfs with no parents)
for item in dependency_list:
if not item['parent']:
jlist.append({'name': item['name'], 'children': []})
# add chidren recursively
for jitem in jlist:
insert_children(jitem)
return jlist
def get_parent_list(zfs_name):
def get_zfs_item(zfs_name):
for item in dependency_list:
if item['name'] == zfs_name:
return item
parent_list = []
parent = get_zfs_item(zfs_name)['parent']
count = 0 # protect against infinit loop
while parent != None and count < 20:
parent_list.append(parent)
parent = get_zfs_item(parent)['parent']
count += 1
parent_list.reverse()
return parent_list
def show_parents(zfs_name):
parent_list = get_parent_list(zfs_name)
parent_list.append(zfs_name)
indent = " " * 4
next_level = "\u2514\u2500\u2500 "
count = -1
for item in parent_list:
if count < 0:
prefix = ""
else:
prefix = "{}{}".format(indent * count, next_level)
print(prefix + item)
count += 1
def show_children(zfs_name):
global dependency_list
print(zfs_name)
def _show_child_tree(zfs_name, depth=0):
indent = " " * 3
next_level = "\u2514\u2500 "
for item in dependency_list:
if zfs_name == item['name']:
for i in item['children']:
prefix = "{}{}".format((indent * (depth-1)), next_level)
print("{}{}".format(prefix, i))
_show_child_tree(i, depth+1)
_show_child_tree(zfs_name, 1)
def get_top_level_parent_list(dependency_list):
top_level_parent_list = []
for item in dependency_list:
if not item['parent']:
top_level_parent_list.append(item['name'])
return top_level_parent_list
def main():
parser = create_parser()
args = parser.parse_args()
global dependency_list
global json_list
if args.t == 0:
zfs_name_origin_list = nolist0()
elif args.t == 1:
zfs_name_origin_list = nolist1()
elif args.t == 2:
zfs_name_origin_list = nolist2()
elif args.t == 11:
zfs_name_origin_list = nolist11()
elif args.t == 12:
zfs_name_origin_list = nolist12()
elif args.t == 24:
zfs_name_origin_list = nolist24()
else:
zfs_name_origin_list = get_zfs_name_origin_list()
#pp(zfs_name_origin_list)
dependency_list = create_dependency_list(zfs_name_origin_list)
#pp(dependency_list)
if args.json:
json_list = create_json_list(dependency_list)
print("** json list:")
pp(json_list)
print()
else:
for top_level_item in get_top_level_parent_list(dependency_list):
show_children(top_level_item)
print()
if __name__ == '__main__':
main()
| c70b102d6cf3b4099742bebdc1b57f78ba32e912 | [
"Markdown",
"Python"
] | 4 | Markdown | Shortrope/zfs-dependency-tree | 46ed96a4971188dbfbab2650d7093d44889338c0 | e8fed6dfa00ae955fd6872842977fc10a9a53df7 |
refs/heads/master | <file_sep>import React from 'react';
import './Header.css';
const Header = props => {
return(
<div>
<header id="header">
<div className='container'>
<div id='logo' class='pull-left'>
<h1><a href='#body' class='scrollto'>Real<span>Valor</span></a></h1>
{/*<!-- Uncomment below if you prefer to use an image logo -->
<!-- <a href="#body"><img src="img/logo.png" alt="" title="" /></a>-->*/}
</div>
<nav id="nav-menu-container">
<ul className="nav-menu">
<li className="menu-active"><a href="#body">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#team">Team</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</div>
</header>
</div>
)
}
export default Header;<file_sep># realvalorteste
Real Valor Teste
| 5b53a23b1894d72c5c093116df3a0ca0e7df6813 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | agnaldom/realvalorteste | ca65a1aac1bd92915bc510cb4957f44a74513d15 | e26096374b0f2a4ef8526dd5508f029d4c98915d |
refs/heads/master | <repo_name>EnriqueOrtiz95/LADM_U1.-Pr-ctica-2.-Archivos-Memoria-Interna-y-Externa.<file_sep>/app/src/main/java/mx/edu/ladm_u1_p2_ortizloraenrique/MainActivity.kt
package mx.edu.ladm_u1_p2_ortizloraenrique
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
class MainActivity : AppCompatActivity() {
//private static final String FILE_NAME = null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Guardar.setOnClickListener {
if (radInt.isChecked) {
guardarArchivoInterno() }
if (radSD.isChecked) {
guardarArchivoSD() }
}
Abrir.setOnClickListener {
if (radInt.isChecked){
leerArchivoInterno() }
if (radInt.isChecked){
leerArchivoSD() }
}
}
private fun guardarArchivoInterno() {
try {
var flujoSalida =
OutputStreamWriter(openFileOutput(txtFile.text.toString(), Context.MODE_PRIVATE))
var data = txtFrase.text.toString()
flujoSalida.write(data)
flujoSalida.flush()
flujoSalida.close()
mensaje("Archivo interno almacenado")
asignarText("")
} catch (error: IOException) {
mensaje(error.message.toString())
}
}
fun leerArchivoInterno() {
try {
var flujoEnntrada = BufferedReader(InputStreamReader(openFileInput(
txtFile.text.toString())))
var data = flujoEnntrada.readLine()
var vector = data.split("&")
asignarText(vector[0])
} catch (error: IOException) {
mensaje(error.message.toString())
}finally {
mensaje("Proceso terminado")
}
}
fun leerArchivoSD() {
if (noSD()) {
return
}
try {
var rutaSD = Environment.getExternalStorageDirectory()
var datosArchivo = File(rutaSD.absolutePath, txtFile.text.toString())
var flujoEnntrada = BufferedReader(InputStreamReader(FileInputStream(datosArchivo)))
var data = flujoEnntrada.readLine()
var vector = data.split("&")
asignarText(vector[0])
} catch (error: IOException) {
mensaje(error.message.toString())
}finally {
mensaje("Proceso terminado")
}
}
fun guardarArchivoSD() {
if (noSD()) {
mensaje("No tienes archivos en memoria")
return
}
try {
var rutaSD = Environment.getExternalStorageDirectory()
var datosArchivo = File(rutaSD.absolutePath, txtFile.text.toString())
var flujoSalida = OutputStreamWriter(FileOutputStream(datosArchivo))
var data = txtFrase.text.toString()
flujoSalida.write(data)
flujoSalida.flush()
flujoSalida.close()
mensaje("Archivo almacenado")
asignarText("")
} catch (error: IOException) {
mensaje(error.message.toString())
}
}
fun mensaje(msg: String) {
AlertDialog.Builder(this).setTitle("ATENCION").setMessage(msg)
.setPositiveButton("OK") { d, i ->
}.show()
}
fun noSD(): Boolean {
var estado = Environment.getExternalStorageState()
if (estado != Environment.MEDIA_MOUNTED) {
return true }
else{
return false }}
fun asignarText(t1: String) {
txtFrase.setText(t1)
}
}
<file_sep>/settings.gradle
include ':app'
rootProject.name='LADM_U1_P2_OrtizLoraEnrique'
| d4a33c8190a00cfb92a8ab63e26765ddf5b89f88 | [
"Kotlin",
"Gradle"
] | 2 | Kotlin | EnriqueOrtiz95/LADM_U1.-Pr-ctica-2.-Archivos-Memoria-Interna-y-Externa. | 282c0d3cd8576e8ad5317fb6a61e28f931a1058a | 5ea13cc0ef3da110211aee57cf0a21cf93c61243 |
refs/heads/master | <file_sep>'use strict';
// Fallback for desktop testings
var Camera = Camera || {
PictureSourceType: {
PHOTOLIBRARY: 0,
CAMERA: 1,
SAVEDPHOTOALBUM: 2
},
DestinationType: {
DATA_URL: 0,
FILE_URI: 1,
NATIVE_URI: 2
},
EncodingType: {
JPEG: 0,
PNG: 1
},
MediaType: {
PICTURE: 0,
VIDEO: 1,
ALLMEDIA: 2
},
Direction: {
BACK: 0,
FRONT: 1
}
};
angular.module('starter.services', [])
.factory('Camera', function($q, $window) {
return {
getPicture: function() {
var deferred = $q.defer();
$window.navigator.camera.getPicture(
//OnSuccess
function(image) {
deferred.resolve(image);
}, function(error) {
deferred.reject(error);
},
{
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
quality: 20
}
);
return deferred.promise;
},
cleanup: function(onSuccess, onError) {
$window.navigator.camera.cleanup(onSuccess, onError);
},
PictureSourceType: Camera.PictureSourceType,
DestinationType: Camera.DestinationType,
EncodingType: Camera.EncodingType,
MediaType: Camera.MediaType,
Direction: Camera.Direction
};
})
.factory('Recognition', function($q, $http) {
return {
upload: function(image) {
var deferred = $q.defer();
$http({
url: 'http://olympic-insa.fr.nf:8083/recognition/api/upload',
method: "POST",
data: "{\"name\": \"Name\",\"description\": \"metadata string\",\"content\": \"" + image + "\",\"contentType\": \"image/jpeg\"}"
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
},
recognize: function(url) {
var deferred = $q.defer();
$http.get("http://lynxlabs.fr.nf:8083/recognition/api/recognize?url=" + url)
.success(function(response) {
deferred.resolve(response);
})
.error(function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
})
.factory('Athlete', function() {
var Athlete = {};
return {
getAthlete: function() {
return Athlete;
},
setAthlete: function(athlete) {
Athlete = athlete;
return;
}
};
})
.factory('Athletes', function() {
var Athletes = {};
return {
getAthletes: function() {
return Athletes;
},
setAthletes: function(athletes) {
Athletes = athletes;
return;
}
};
})
.factory('Reader', function($rootScope) {
function gotFS(fileSystem) {
fileSystem.root.getFile("history.json", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file) {
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
$rootScope.history = JSON.parse(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
alert("Fail " + evt.target.error.code);
}
return {
getJSON: function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
return;
}
};
})
.factory('Writer', function() {
var JsonToWrite = "{[]}";
function gotFS(fileSystem) {
fileSystem.root.getFile("history.json", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.write(JsonToWrite);
}
function fail(error) {
alert("Can't write " + error.code);
}
return {
writeJSON: function(jsonToWrite) {
JsonToWrite = JSON.stringify(jsonToWrite);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
return;
}
};
})
.factory('Favorite', function($rootScope) {
var JsonToWrite = "{[]}";
function gotFSread(fileSystem) {
fileSystem.root.getFile("favorites.json", {create: true, exclusive: false}, gotFileEntryread, fail);
}
function gotFileEntryread(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file) {
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
$rootScope.favorites = JSON.parse(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
alert("Fail " + evt.target.error.code);
}
function gotFSwrite(fileSystem) {
fileSystem.root.getFile("favorites.json", {create: true, exclusive: false}, gotFileEntrywrite, fail);
}
function gotFileEntrywrite(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.write(JsonToWrite);
}
return {
checkFavorite: function(id) {
var lengthFavorites = $rootScope.favorites.length;
for (var i = 0; i < lengthFavorites; i++) {
if ($rootScope.favorites[i].id == id) {
return true;
}
}
},
getJSON: function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSread, fail);
return;
},
writeJSON: function(jsonToWrite) {
JsonToWrite = JSON.stringify(jsonToWrite);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSwrite, fail);
return;
}
};
}
)
.factory('Geolocation', function($rootScope) {
return {
/**
* Plugin Get from https://github.com/xelita/angular-cordova-geolocation
*
* Check the geolocation plugin availability.
* @returns {boolean}
*/
checkGeolocationAvailability: function() {
//$log.debug('starter.services.Geolocation.checkGeolocationAvailability.');
if (!navigator.geolocation) {
//$log.warn('Geolocation API is not available.');
return false;
}
return true;
},
/**
* Returns the device's current position to the geolocationSuccess callback with a Position object as the parameter.
* For more information: https://github.com/apache/cordova-plugin-geolocation/blob/master/doc/index.md#navigatorgeolocationgetcurrentposition
*/
getCurrentPosition: function(successCallback, errorCallback, options) {
//$log.debug('starter.services.Geolocation.getCurrentPosition.');
// Checking API availability
if (!this.checkGeolocationAvailability()) {
return;
}
// API call
navigator.geolocation.getCurrentPosition(
function(position) {
$rootScope.$apply(successCallback(position));
},
function(error) {
$rootScope.$apply(errorCallback(error));
},
options
);
},
/**
* Returns the device's current position when a change in position is detected.
* For more information: https://github.com/apache/cordova-plugin-geolocation/blob/master/doc/index.md#navigatorgeolocationwatchposition
*/
watchPosition: function(successCallback, errorCallback, options) {
//$log.debug('cordovaGeolocationService.watchPosition.');
// Checking API availability
if (!this.checkGeolocationAvailability()) {
return;
}
// API call
return navigator.geolocation.watchPosition(
function(position) {
$rootScope.$apply(successCallback(position));
},
function(error) {
$rootScope.$apply(errorCallback(error));
},
options
);
},
/**
* Stop watching for changes to the device's location referenced by the watchID parameter.
* For more information: https://github.com/apache/cordova-plugin-geolocation/blob/master/doc/index.md#navigatorgeolocationclearwatch
*/
clearWatch: function(watchID) {
//$log.debug('cordovaGeolocationService.clearWatch.');
// Checking API availability
if (!this.checkGeolocationAvailability()) {
return;
}
// API call
navigator.geolocation.clearWatch(watchID);
}
};
});<file_sep>// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
'use strict';
angular.module('starter', ['ionic', 'starter.services', 'starter.controllers', 'starter.directives', 'starter.filters'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('menu', {
url: "/menu",
abstract: true,
templateUrl: "templates/menu.html"
})
// setup an abstract state for the tabs directive
.state('menu.tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
// History tab
.state('menu.tab.history', {
url: '/history',
views: {
'history-tab': {
templateUrl: 'templates/history.html',
controller: 'HistoryCtrl'
}
}
})
// RioHome tab
.state('menu.tab.home', {
url: '/riohome',
views: {
'home-tab': {
templateUrl: 'templates/riohome.html',
controller: 'RioHomeCtrl'
}
}
})
// Picture tab
.state('menu.tab.recognize', {
url: '/picturesrecognizer',
views: {
'recognize-tab': {
templateUrl: 'templates/picturesrecognizer.html',
controller: 'PicturesRecognizeCtrl'
}
}
})
.state('menu.favorite', {
url: '/favorite',
templateUrl: 'templates/favorite.html',
controller: 'FavoriteCtrl'
})
.state('menu.about', {
url: '/about',
templateUrl: 'templates/about.html',
controller: 'AboutCtrl'
})
.state('menu.athletes-index', {
url: '/athletes',
templateUrl: 'templates/athlete-index.html',
controller: 'AthleteIndexCtrl'
})
.state('menu.parameters', {
url: '/parameters',
templateUrl: 'templates/parameters.html',
controller: 'ParametersCtrl'
})
.state('menu.questionrecognize', {
url: '/questionrecognize',
templateUrl: 'templates/questionsrecognizer.html',
controller: 'QuestionsCtrl'
})
.state('menu.athlete-detail', {
url: '/athlete/:athleteId',
templateUrl: 'templates/athlete-detail.html',
controller: 'AthleteDetailCtrl'
})
.state('menu.athletes-result', {
url: '/athletesresult',
templateUrl: 'templates/athletesresult.html',
controller: 'AthletesResultCtrl'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/menu/tab/riohome');
});
<file_sep>angular.module('starter.directives', [])
.directive('adjustimg', function() {
return function(scope, element, attrs) {
element.on('load', function() {
//alert("here");
var height = element[0].clientHeight;
var width = element[0].clientWidth;
//alert("height :"+height+" width : "+width);
if (height / width > 1) {
//alert(width);
var top = (height - width) / 2;
var bottom = top + width;
element.css("clip", "rect(" + top + "px," + width + "px," + bottom + "px,0px)");
element.css("overflow", "hidden");
element.css("position", "absolute");
element.css("top", "-" + (top-5) + "px");
element.parent().css("height",width+"px");
} else if (height / width < 1) {
var left = (width - height) / 2;
var rigth = right + width;
element.css("clip", "rect(0px," + rigth + "px,"+height+"px," + left + "px)");
element.css("overflow", "hidden");
element.css("position", "absolute");
element.css("left", "-" + left + "px");
element.parent().css("width",heigth+"px");
}else{
//alert("image is already squared or problem with height and width");
}
});
};
}); | 6be5dda236b218ea79471ca985b746de61b9d452 | [
"JavaScript"
] | 3 | JavaScript | Olympic-insa/riocognized-mobile | a65fbe4510dfcbd5f6ca2aaa5fcc96ff843fa649 | 9df127194bfbb7b7d9e46f7b53deefb1aa2a12f6 |
refs/heads/master | <file_sep>
$(function(){
$('#main-menu > li').mouseover(
function(){
$(this)
.find(".depth2")
.addClass('show');
},
function(){
$(this)
.find(".depth2")
.removeClass('show');
}
)
});
$(function(){
$('#indicator a').click(function(){
// 기본 이벤트 취소
return false
});
var img_num = 0; // 이미지 배열 번호
var img_width = 1200; // 이미지 크기
var duration = 1000; // 재생시간
var play_slider = setInterval(function(){
if(img_num >= 3){img_num = 0;}
// image_width * image_number
$(".sliders").css('margin-left', -(img_width * img_num) + 'px')
img_num++;
}, duration)
});
| 4436c787b03385a63829814fafd1da0b277a0ac6 | [
"JavaScript"
] | 1 | JavaScript | KKongrrr326/test7 | b6799176f185fc7e42ad661eeb27635a8af8c1f9 | d336f75e310e9c24d26467730f1d3fc9e2d81734 |
refs/heads/master | <file_sep>import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class Staff extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Staff frame = new Staff();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Staff() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 593, 433);
JMenuBar menuBar = new JMenuBar();
menuBar.setBorderPainted(false);
setJMenuBar(menuBar);
JMenu menu = new JMenu("");
menuBar.add(menu);
JMenu mnBilling = new JMenu("Billing");
menuBar.add(mnBilling);
JMenuItem mntmCreateBill = new JMenuItem("Create Bill");
mntmCreateBill.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<100; i++){
System.out.println();
}
try{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "mysql");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from inventory;");
System.out.println("ITEMID " + "ITEMNAME " + "PRICE "+ "QUANTITY");
while(myRs.next()){
System.out.println(myRs.getString("item_id")+"\t"+ myRs.getString("item_name") +"\t" + myRs.getString("price")+"\t"+ myRs.getString("quantity"));
}
}
catch (Exception exc){
exc.printStackTrace();
}
System.out.println();
System.out.println("ITEMID " + "ITEMNAME " + "PRICE "+ "QUANTITY");
System.out.println();
Bill bl=new Bill();
bl.setVisible(true);
}
});
mnBilling.add(mntmCreateBill);
JMenuItem mntmChangePassword = new JMenuItem("Change Password");
menuBar.add(mntmChangePassword);
mntmChangePassword.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Changepwd cpwd=new Changepwd();
cpwd.setVisible(true);
}
});
JMenuBar menuBar_1 = new JMenuBar();
menuBar.add(menuBar_1);
}
}
<file_sep>#Sat Mar 25 13:57:26 IST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.2.v20161124-1400
<file_sep>import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import javax.swing.JButton;
public class Admin extends JFrame {
private JPanel contentPane;
private JFrame admin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Admin frame = new Admin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Admin() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 826, 628);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewUser = new JMenu("New User");
menuBar.add(mnNewUser);
JMenuItem mntmAddUser = new JMenuItem("Add user");
mntmAddUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Adduser adduser=new Adduser();
adduser.setVisible(true);
}
});
mnNewUser.add(mntmAddUser);
JMenuItem mntmRemoveUser = new JMenuItem("Remove User");
mntmRemoveUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<100; i++){
System.out.println();
}
Removeuser removeuser=new Removeuser();
removeuser.setVisible(true);
}
});
mnNewUser.add(mntmRemoveUser);
JMenu mnManagebills = new JMenu("Manage Bills");
menuBar.add(mnManagebills);
JMenuItem mntmManagebills = new JMenuItem("Managebills");
mntmManagebills.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
for(int i=0; i<10; i++)
System.out.println();
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "mysql");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from bill");
System.out.println("NO." + "\t" + "NAME"+ "\t" +"DATE"+ "\t\t\t" +"AMT");
System.out.println();
while(myRs.next()){
System.out.println(myRs.getString("bill_no")+"\t"+ myRs.getString("username")+"\t"+ myRs.getString("date")+"\t"+"\t"+ myRs.getString("amount"));
}
}
catch (Exception exc){
exc.printStackTrace();
}
// Managebills managebills=new Managebills();
// managebills.setVisible(true);
}
});
mnManagebills.add(mntmManagebills);
JMenu mnInventory = new JMenu("Inventory");
menuBar.add(mnInventory);
JMenuItem mntmAddItem = new JMenuItem("Add item");
mntmAddItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Inventory invntry=new Inventory();
invntry.setVisible(true);
}
});
mnInventory.add(mntmAddItem);
JMenuItem mntmUpdateQuantity = new JMenuItem("Update quantity");
mntmUpdateQuantity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
UpdateQuantity upqnty =new UpdateQuantity();
upqnty.setVisible(true);
}
});
mnInventory.add(mntmUpdateQuantity);
JMenu mnSalesReport = new JMenu("Sales Report");
menuBar.add(mnSalesReport);
JMenuItem mntmCheckReport = new JMenuItem("Check Report");
mntmCheckReport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Salesreport salesreport =new Salesreport();
salesreport.setVisible(true);
}
});
mnSalesReport.add(mntmCheckReport);
JMenu mnTax = new JMenu("TAX");
menuBar.add(mnTax);
JMenuItem mntmChangeTax = new JMenuItem("Change Tax");
mntmChangeTax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tax tax=new Tax();
tax.setVisible(true);
}
});
mnTax.add(mntmChangeTax);
contentPane = new JPanel();
contentPane.setForeground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
| 9a19beab6c1d9a0d4b6137844adced6eead61e49 | [
"Java",
"INI"
] | 3 | Java | tusharkadam008/OOBill | ba7fd59dfcb343216dfa73c77b0d945002e552d8 | 2d0af5473df1a040618d9c22b32e690719b0a098 |
refs/heads/master | <file_sep>/*
Question #1: Correctness
In TypeScript, write a function called "scriptAt". Prove that it's correct by providing a set of test cases.
The function will do as follows.
Given a string as an input, find the index of the string "Script" within the input string.
You can use Google to look up the method calls.
Questions:
1) How to ensure that the input is a string at compile time?
2) What did you learn from this exercise?
*/
function scriptAt(text: string): number {
return text.indexOf('Script');
}
console.log(scriptAt('TypeScript'));
/** เรียนรุ้การประกาศ type */ | 8d4b8fd3a339c16ccc00afc24a30decebbc99009 | [
"TypeScript"
] | 1 | TypeScript | nong3cha11/compiler-is-your-friend | 6a906fd6d94a05e8de2936c0d52cb48f9c73666e | cfda4c7f2db1c1994fa46c226d272a95762dd3b5 |
refs/heads/main | <file_sep>package frc.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
public class HwJoystick {
// //tank drive controlls for driver
// public final Joystick leftJoystick = new Joystick(1);
// public final Joystick rightJoystick = new Joystick(0);
//xbox controller for operator
public final XboxController xbox = new XboxController(2);
public final XboxController xboxDriver = new XboxController(3);
}
| faa41d45f3f3f041b195f5ffefd0c497f265acfe | [
"Java"
] | 1 | Java | EthanCubed/Robot-Code-Attempt | ee1e2dfc8a4ad52420204235e3df0e48a45f7260 | e8bcfb840ae60e224876ebdcf523744ac2142a8b |
refs/heads/main | <repo_name>Adhityarahman/Github<file_sep>/ArifiDatabase/help.js
const help = (pushname, prefix, getLevelingLevel, getLevelingXp, premi, sender, reqXp, _registered, uangku) => {
return `
*Selamat ${ucapan.data.result} I'm ${NamaBot}*
╔════□ *Info Developer* □
║╔▸
║╠➤ *Nama* : ManikGanz
║╠➤ *Nomer* : wa.me/62895342978510
║╠➤ *Github* : Cari Sendiri!?
║╠➤ *Tag Owner* : @${62895342978510}
║╠➤ *Yutub* : 「 ᴍᴀɴɪᴋ ᴏғғɪᴄɪᴀʟツ 」
║╠➤ *Ig* : gk punya
║╠➤ *Ulang Tahun Owner:V*
║╠➤ *${ultah.data.result}*
║╚▸
╠════□ *Info User* □
║╔▸
║╠➤ *Nama* : ${pushname}
║╠➤ *Nomer* : @${sender.split("@")[0]}
║╠➤ *Uang mu* : Rp${uangku}
║╠➤ *Premium* : ${premi}
║╠➤ *XP* : ${getLevelingXp(sender)}/${reqXp}
║╠➤ *Level* : ${getLevelingLevel(sender)}
║╠➤ *User register* : ${_registered.length}
║╚▸
╠════□ *Info ${NamaNot}* □
║╔▸
║╠➤ *Name* : ${NamaBot}
║╠➤ *Prefix* : ${prefix}
║╠➤ *Speed* : ${process.uptime()}
║╠➤ *Runtime* : ${kyun(uptime)}
║╠➤ *Baterai :* ${battre}%
║╠➤ *🕰Jam* : ${jam}:${menit}:${detik} ${ampm}
║╠➤ *🗓️Tanggal* : ${day} - ${myMonths[bulan]} - ${year}
║╠➤ *Versi Whatsapp* : ${manik.user.phone.wa_version}
║╠➤ *Group Chat* : ${good.length}
║╠➤ *Personal Chat*: ${totalchat.length - good.length}
║╠➤ *Total Chat* : ${totalchat.length}
║╚▸
╠════□ *Other* □
║╔▸
║╠➤ *Grup Wa : ${prefix}manikgroup*
║╠➤ *Sewabot? : ${prefix}sewabot*
║╠➤ *Bug? : ${prefix}bugreport*
║╠➤ *Req? : ${prefix}request*
║╠➤ *Surat? : ${prefix}suratto <628xxx|Surat>*
║╚▸
╠════□ *Menu ${NamaBot}* □
║╔▸ *◪ OWNER MENU ◪*
║╠❏ ${prefix}antidelete aktif/mati(Group)
║╠❏ ${prefix}antidelete ctaktif/ctmati (Cp)
║╠❏ ${prefix}antidelete banct (Cp)
║╠❏ ${prefix}attack gc (BugGc)
║╠❏ ${prefix}addlimit
║╠❏ ${prefix}setlimit
║╠❏ ${prefix}setmemlimit
║╠❏ ${prefix}addbadword
║╠❏ ${prefix}dellbadword
║╠❏ ${prefix}clearall
║╠❏ ${prefix}setprefix
║╠❏ ${prefix}bc
║╠❏ ${prefix}event 1/0
║╠❏ ${prefix}block
║╠❏ ${prefix}unblock
║╠❏ ${prefix}ban
║╠❏ ${prefix}unban
║╠❏ ${prefix}upswtext
║╠❏ ${prefix}upswimg
║╠❏ ${prefix}upswvid
║╠❏ ${prefix}sendkontak
║╠❏ ${prefix}sendkontag
║╠❏ ${prefix}spamchat
║╠❏ ${prefix}term
║╠❏ ${prefix}setname
║╠❏ ${prefix}setbio
║╠❏ ${prefix}fdeface
║╠❏ ${prefix}spam
║╠❏ ${prefix}imgtag
║╠❏ ${prefix}stctag
║╠❏ ${prefix}toimg
║╠❏ ${prefix}togif
║╠❏ ${prefix}tovideo
║╠❏ ${prefix}grouplist
║╠❏ ${prefix}autosticker (1/0)
║╠❏ ${prefix}ncheck (1/0)
║╠❏ ${prefix}fordward
║╠❏ ${prefix}wame
║╠❏ ${prefix}nobg
┏━━□ *ANIME* □━━━┓
┣□ *${prefix}anime*
┣□ *${prefix}bokunh*
┣□ *${prefix}sao*
┣□ *${prefix}lovelive*
┣□ *${prefix}animesaran/animesaran2*
┣□ *${prefix}loli*
┣□ *${prefix}hsdxd*
┣□ *${prefix}husbu*
┣□ *${prefix}waifu*
┣□ *${prefix}neko*
┣□ *${prefix}chika*
┣□ *${prefix}kurumi*
┣□ *${prefix}kaneki*
┣□ *${prefix}touka*
┣□ *${prefix}aot*
┣□ *${prefix}naruto*
┣□ *${prefix}minato*
┣□ *${prefix}sagiri*
┣□ *${prefix}tokyoghoul*
┗━━━━━━━━━━━━━━━━
┏━━□ *CREATOR* □━━━┓
┣□ *${prefix}comunism*
┣□ *${prefix}trigger*
┣□ *${prefix}rotate*
┣□ *${prefix}delete*
┣□ *${prefix}thuglife*
┣□ *${prefix}tobecontinue*
┣□ *${prefix}smoke* <teks>
┣□ *${prefix}camuflage* <teks>
┣□ *${prefix}stars* <teks>
┣□ *${prefix}3dglowing* <teks>
┣□ *${prefix}underwaterocean* <teks>
┣□ *${prefix}wolfmetal* <teks>
┣□ *${prefix}rainbowshine* <teks>
┣□ *${prefix}gtavposter*
┣□ *${prefix}pencil*
┣□ *${prefix}pencildrawing*
┣□ *${prefix}burneffect*
┣□ *${prefix}crossgun*
┣□ *${prefix}customwp*
┣□ *${prefix}nightbeach*
┣□ *${prefix}raindrop*
┣□ *${prefix}3dlinephoto*
┣□ *${prefix}stiker/sticker*
┣□ *${prefix}tahta* <teks>
┣□ *${prefix}woodblock* <text>
┣□ *${prefix}darkneon* <text>
┣□ *${prefix}tlight* <text>
┣□ *${prefix}paper* <text>
┣□ *${prefix}matrix* <teks>
┣□ *${prefix}text3dbox* <teks>
┣□ *${prefix}breakwall* <text>
┣□ *${prefix}didin* <text|text>
┣□ *${prefix}gtext* <text|text>
┣□ *${prefix}pornhub* <text|text>
┣□ *${prefix}bneon* <text>
┣□ *${prefix}coffee* <text>
┣□ *${prefix}logobp* <text>
┣□ *${prefix}leavest* <text>
┣□ *${prefix}shadowt* <text>
┣□ *${prefix}nulis* <text>
┣□ *${prefix}attp* <text>
┣□ *${prefix}ppcouple*
┣□ *${prefix}porncomen* <text>
┣□ *${prefix}tts* <kode bahasa> <text>
┗━━━━━━━━━━━━━━━━
┏━━□ *FUN* □━━━┓
┣□ *${prefix}memeindo*
┣□ *${prefix}darkjoke*
┣□ *${prefix}asupan*
┣□ *${prefix}pantun*
┣□ *${prefix}quotes*
┣□ *${prefix}cerhor*
┣□ *${prefix}gombal*
┣□ *${prefix}bucin*
┣□ *${prefix}jadian*
┣□ *${prefix}watak* <nama>
┣□ *${prefix}kapankah* <teks>
┣□ *${prefix}bisakah* <teks>
┣□ *${prefix}terpintar*
┣□ *${prefix}terganteng*
┣□ *${prefix}tercantik*
┣□ *${prefix}tebakkata*
┣□ *${prefix}family100*
┣□ *${prefix}caklontong*
┣□ *${prefix}tebakgambar*
┗━━━━━━━━━━━━━━━━
┏━━□ *ISLAM* □━━━┓
┣□ *${prefix}sedekah*
┣□ *${prefix}qmuslim*
┣□ *${prefix}rdoadl*
┣□ *${prefix}listsurah*
┣□ *${prefix}quranaudio*
┣□ *${prefix}kisahnabi* <nama nabi>
┗━━━━━━━━━━━━━━━━
┏━━□ *ANBOT-D* □━━━┓
┣□ *${prefix}dompet*
┣□ *${prefix}buylimit*
┣□ *${prefix}transfer*
┣□ *${prefix}limit*
┣□ *${prefix}level*
┣□ *${prefix}bahasa*
┣□ *${prefix}qrcode*
┗━━━━━━━━━━━━━━━━
┏━━□ *ALL* □━━━┓
┣□ *${prefix}namajawa*
┣□ *${prefix}pinte* <text>
┣□ *${prefix}lb/leaderboard*
┣□ *${prefix}aesthetic*
┣□ *${prefix}listsound*
┣□ *${prefix}cecen*
┣□ *${prefix}cogan*
┣□ *${prefix}tumur* <nama>
┣□ *${prefix}mutual*
┣□ *${prefix}spamcall* <nomor>
┣□ *${prefix}spamsms* <nomor>
┣□ *${prefix}spamgmail* <gmail/email>
┣□ *${prefix}artinama* <nama>
┣□ *${prefix}brainly* <pertanyaan>
┣□ *${prefix}next*
┣□ *${prefix}mimpi* <nama mimpi>
┣□ *${prefix}tomp3* <merubah video menjadi audio>
┣□ *${prefix}toimg* <merubah stiker menjadi gambar>
┣□ *${prefix}rate* <text>
┣□ *${prefix}addbucin* <text>
┣□ *${prefix}gantengcek* <nana>
┣□ *${prefix}cantikcek* <nama>
┣□ *${prefix}kucing*
┣□ *${prefix}listbadword*
┣□ *${prefix}lizard*
┣□ *${prefix}lirik* <text>
┣□ *${prefix}igstalk* <username>
┣□ *${prefix}tiktokstalk* <username>
┗━━━━━━━━━━━━━━━━
┏━━□ *PREMIUM* □━━━┓
┣□ *${prefix}ytmp3* <link video yt>
┣□ *${prefix}ytmp4* <link video yt>
┣□ *${prefix}ytplaymp3/ytplaymp4* <judul>
┣□ *${prefix}joox* <judul lagu>
┗━━━━━━━━━━━━━━━━
┏━━□ *INFO* □━━━┓
┣□ *${prefix}info*
┣□ *${prefix}premiumlist*
┣□ *${prefix}owner*
┗━━━━━━━━━━━━━━━━
┏━━□ *GROUP* □━━━┓
┣□ *${prefix}demote*
┣□ *${prefix}promote*
┣□ *${prefix}kick*
┣□ *${prefix}listadmin*
┣□ *${prefix}add*
┣□ *${prefix}tagall*
┣□ *${prefix}linkgc*
┣□ *${prefix}delete*
┣□ *${prefix}setdesc*
┣□ *${prefix}setname*
┗━━━━━━━━━━━━━━━━
┏━━□ *OWNER* □━━━┓
┣□ *${prefix}setppbot*
┣□ *${prefix}unblock*
┣□ *${prefix}addbadword*
┣□ *${prefix}block*
┣□ *${prefix}addprem*
┣□ *${prefix}dellprem*
┣□ *${prefix}leave*
┣□ *${prefix}clearall*
┗━━━━━━━━━━━━━━━━
┏━━□ *ON/OFF* □━━━┓
┣□ *${prefix}antilink* [1/0]
┣□ *${prefix}antivirtex* [1/0]
┣□ *${prefix}leveling* [enable/disable]
┣□ *${prefix}nsfw* <1/0>
┣□ *${prefix}nobadword* <enable/disable>
┣□ *${prefix}welcome* [1/0]
┣□ *${prefix}event* <1/0>
┗━━━━━━━━━━━━━━━━
║▌│█║▌│ █║▌│█│║▌║
║▌│█║▌│ █║▌│█│║▌║
*「 OREKI BOT 」*`
}
exports.help = help
<file_sep>/ArifiSrc/rules.js
const rules = (prefix) => {
return `
*RULES BAGI PENGGUNA ANBOT-D*
━━━━━━━━━(PENTING)━━━━━━━━━
🦏 JANGAN SPAM BOT
🦏 JANGAN CALL/VC BOT JIKA TIDAK INGIN DI BLOCK
🦏 JANGAN LUPA UNTUK SELALU TERSENYUM
🦏 SAYA TIDAK PERNAH MEMAKSA ANDA BERDONASI, JIKA INGIN BERDONASI CHAT OWMER
🦏 JANGAN LUPA UNTUK SELALU BERIBADAH, DAN INGATLAH SELALU TERSENYUM
━━━━━━━━━━━━━━━━━━━━━━━━
ketik ${prefix}menu
untuk melihat menu ANBOT-D
║▌│█║▌│ █║▌│█│║▌║
║▌│█║▌│ █║▌│█│║▌║
*「 ANBOT-D 」*`
}
exports.rules = rules
| ece7309767f5b0183c3d3317240340ce511aa866 | [
"JavaScript"
] | 2 | JavaScript | Adhityarahman/Github | d1fd5898a10640b11985fe7e599a1f35ca60e20b | 6a9d84b10e2644904deb0d90ad66c5eb46ce6ab2 |
refs/heads/master | <repo_name>Arctic1337/Test-tasks-<file_sep>/README.md
# In this repository I will download completed tasks which were given to me by different employers as test tasks
<file_sep>/News feed/forTask2.php
<?php
function PageByNumber($result, $pageNumber) {
for ($i=0; $i < 5 ; $i++) {
global $MyTitle, $MyAnnounce, $MyDate, $MyId, $MyContent;
if (!is_object($result)) {
return NULL;
}
$result->data_seek($i+($pageNumber)*5-5);
$row = $result->fetch_array(MYSQLI_ASSOC);
$MyTitle[$i] = $row['title'];
$MyAnnounce[$i] = $row['announce'];
$MyId[$i] = $row['id'];
$MyDate[$i] = date('d.m.Y', $row['idate']);
}
}
function NewsById($result, $id) {
for ($i=0; $i < 5 ; $i++) {
global $MyTitle, $MyContent;
if (!is_object($result)) {
return NULL;
}
$result->data_seek($_GET["id"] - 1);
$row = $result->fetch_array(MYSQLI_ASSOC);
$MyTitle = $row['title'];
$MyContent= $row['content'];
}
}
require_once 'login.php';
$conn = new mysqli ($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$conn->query('SET NAMES utf8');
$query = "SELECT * FROM news ORDER BY idate DESC";
$result = $conn->query($query);
if (!$result) die ($conn->error);
$NumberOfRows = $result->num_rows;
$NumberOfRef = ceil($NumberOfRows/5);
$CreateListItems = "";
$MyTitle= array();
$MyAnnounce= array();
$MyDate= array();
$MyId = array();
$MyContent;
if (!empty($_GET["n"])) {
PageByNumber($result, $_GET["n"]);
for ($i=2; $i < $NumberOfRef+1; $i++) {
$CreateListItems .= "<li><a href='forTask2.php?n=" . $i . "'>" . $i . "</a></li>\n";
}
echo <<<_END
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>The Task</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<header>
<h1>Новости</h1>
</header>
<main>
<div>
<div class="date-and-announce">
<span>$MyDate[0]</span>
<a href="forTask2.php?id=$MyId[0]">$MyTitle[0]</a>
</div>
<p>$MyAnnounce[0]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[1]</span>
<a href="forTask2.php?id=$MyId[1]">$MyTitle[1]</a>
</div>
<p>$MyAnnounce[1]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[2]</span>
<a href="forTask2.php?id=$MyId[2]">$MyTitle[2]</a>
</div>
<p>$MyAnnounce[2]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[3]</span>
<a href="forTask2.php?id=$MyId[3]">$MyTitle[3]</a>
</div>
<p>$MyAnnounce[3]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[4]</span>
<a href="forTask2.php?id=$MyId[4]">$MyTitle[4]</a>
</div>
<p>$MyAnnounce[4]</p>
</div>
</main>
<footer>
<h2>Страницы:</h2>
<ul id="selectBackground">
<li><a href="forTask2.php">1</a></li>
$CreateListItems
</ul>
</footer>
</div>
</body>
</html>
_END;
}
elseif (!empty($_GET["id"])) {
NewsById($result, $_GET["id"]);
echo <<<_END
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>The Task</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<header>
<h1>$MyTitle</h1>
</header>
<main>
$MyContent
</main>
<footer>
<a href="forTask2.php">Все новости >></a>
</footer>
</div>
</body>
</html>
_END;
}
elseif(empty($_GET["n"]) || empty($_GET["id"])){
for ($i=0; $i < 5; $i++) {
$result->data_seek($i);
$row = $result->fetch_array(MYSQLI_ASSOC);
$MyTitle[$i] = $row['title'];
$MyAnnounce[$i] = $row['announce'];
$MyDate[$i] = $row['idate'];
$MyDate[$i] = date('d.m.Y', $row['idate']);
$MyId[$i] = $row['id'];
}
for ($i=2; $i < $NumberOfRef+1; $i++) {
$CreateListItems .= "<li><a href='forTask2.php?n=" . $i . "'>" . $i . "</a></li>\n";
}
echo <<<_END
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>The Task</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<header>
<h1>Новости</h1>
</header>
<main>
<div>
<div class="date-and-announce">
<span>$MyDate[0]</span>
<a href="forTask2.php?id=$MyId[0]">$MyTitle[0]</a>
</div>
<p>$MyAnnounce[0]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[1]</span>
<a href="forTask2.php?id=$MyId[1]">$MyTitle[1]</a>
</div>
<p>$MyAnnounce[1]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[2]</span>
<a href="forTask2.php?id=$MyId[2]">$MyTitle[2]</a>
</div>
<p>$MyAnnounce[2]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[3]</span>
<a href="forTask2.php?id=$MyId[3]">$MyTitle[3]</a>
</div>
<p>$MyAnnounce[3]</p>
</div>
<div>
<div class="date-and-announce">
<span>$MyDate[4]</span>
<a href="forTask2.php?id=$MyId[4]">$MyTitle[4]</a>
</div>
<p>$MyAnnounce[4]</p>
</div>
</main>
<footer>
<h2>Страницы:</h2>
<ul id="selectBackground">
<li><a href="forTask2.php">1</a></li>
$CreateListItems
</ul>
</footer>
</div>
</body>
</html>
_END;
}
?>
| 382c0c2ef4ee10fb7abcc241764c7d4994a691b7 | [
"Markdown",
"PHP"
] | 2 | Markdown | Arctic1337/Test-tasks- | f7fa29031f46d21820d73fc8b807a3b8346b80ce | e868cf9cad72f632c51f426f487f26263eceb984 |
refs/heads/main | <file_sep># graph-node-embedding-algorithms
Implementation of graph node embedding algorithms
<file_sep>import os.path as osp
import torch
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from sklearn.manifold import TSNE
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import Node2Vec
from torch_geometric.data import DataLoader
output_path = '../graph_data/'
result_path = 'results/'
print('load data')
dataset = Planetoid(root=output_path+'Cora', name='Cora')
data = dataset[0]
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('create model')
model = Node2Vec(data.edge_index, embedding_dim=20, walk_length=10, context_size=2, walks_per_node=5, num_negative_samples=1, p=1, q=1, sparse=True).to(device)
loader = model.loader(batch_size=32, shuffle=True, num_workers=0)
optimizer = torch.optim.SparseAdam(list(model.parameters()), lr=0.01)
def train():
model.train()
total_loss = 0
for pos_rw, neg_rw in loader:
optimizer.zero_grad()
loss = model.loss(pos_rw.to(device), neg_rw.to(device))
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss/len(loader)
@torch.no_grad()
def test():
model.eval()
z = model()
acc = model.test(z[data.train_mask], data.y[data.train_mask], z[data.test_mask], data.y[data.test_mask], max_iter=50)
return acc
print('train model')
loss_list = []
acc_list = []
epoch_num = 100
for epoch in range(epoch_num):
loss = train()
acc = test()
loss_list.append(loss)
acc_list.append(acc)
print('epoch %s, loss %.2f, acc %.2f'%(epoch, loss, acc))
@torch.no_grad()
def plot_points(colors):
model.eval()
z = model(torch.arange(data.num_nodes, device=device))
z = TSNE(n_components=2).fit_transform(z.cpu().numpy())
y = data.y.cpu().numpy()
plt.figure(figsize=(6,4))
for i in range(dataset.num_classes):
plt.scatter(z[y== i, 0], z[y==i, 1], s=20, color=colors[i])
plt.axis('off')
plt.show()
# colors = ['#ffc0cb', '#bada55', '#008080', '#420420', '#7fe5f0', '#065535', '#ffd700']
# plot_points(colors)
plt.figure(figsize=(6,4))
plt.plot(loss_list)
plt.xlabel('Epoch', fontsize=12)
plt.ylabel('Loss', fontsize=12)
plt.tight_layout()
plt.savefig(result_path+'node2vec_loss'+'.png', dpi=100)
plt.show()
plt.figure(figsize=(6,4))
plt.plot(acc_list)
plt.xlabel('Epoch', fontsize=12)
plt.ylabel('Accuracy', fontsize=12)
plt.tight_layout()
plt.savefig(result_path+'node2vec_acc'+'.png', dpi=100)
plt.show()
<file_sep>import os.path as osp
import torch
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from sklearn.manifold import TSNE
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import Node2Vec, GCNConv, GATConv
from torch_geometric.data import DataLoader
import torch.nn.functional as F
import torch_geometric.transforms as T
output_path = '../graph_data/'
result_path = 'results/'
dataset = Planetoid(root=output_path+'Cora', name='Cora', transform=T.NormalizeFeatures())
data = dataset[0]
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = GATConv(dataset.num_features, 8, heads=1, dropout=0.2)
self.conv2 = GATConv(8*1, dataset.num_classes, heads=1, concat=False, dropout=0.2)
def forward(self):
x = F.dropout(data.x, p=0.6, training=self.training)
x = self.conv1(x, data.edge_index)
x = F.relu(x)
x = F.dropout(x, p=0.6, training=self.training)
x = self.conv2(x, data.edge_index)
return F.log_softmax(x, dim=1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = Net()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
def train():
model.train()
optimizer.zero_grad()
out = model()
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
return loss.item()
@torch.no_grad()
def test():
model.eval()
out = model().max(1)[1]
acc = out[data.test_mask].eq(data.y[data.test_mask]).sum().item()/data.test_mask.sum().item()
return acc
epoch_num = 100
loss_list = []
acc_list = []
for epoch in range(epoch_num):
loss = train()
acc = test()
loss_list.append(loss)
acc_list.append(acc)
print('epoch %s, loss %.2f, acc %.2f'%(epoch, loss, acc))
plt.figure(figsize=(6,4))
plt.plot(loss_list)
plt.xlabel('epoch', fontsize=12)
plt.ylabel('loss', fontsize=12)
plt.tight_layout()
plt.savefig(result_path+'gat_loss'+'.png', dpi=100)
plt.show()
plt.figure(figsize=(6,4))
plt.plot(acc_list)
plt.xlabel('epoch', fontsize=12)
plt.ylabel('acc', fontsize=12)
plt.tight_layout()
plt.savefig(result_path+'gat_acc'+'.png', dpi=100)
plt.show()
| fab46a44e0c76ffd67a766d9459bc45ff2bd0990 | [
"Markdown",
"Python"
] | 3 | Markdown | yang0110/Graph-Node-Embedding-Algorithms | d9dae488d518015bac97e92fdb80aa036295b617 | d68f36252886ea89565d9677a6d26775d7bbc53c |
refs/heads/main | <file_sep><?php
// Set variables
$host = "localhost";
$port = 1234;
// No timeout
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
$socket_binded = socket_bind($socket, $host, $port) or die("Could not bind socket to port\n");
$socket_listened = socket_listen($socket, SOMAXCONN) or die("Could not set up socket listener\n");
$socket_accepted = socket_accept($socket) or die("Could not accept socket\n");
do{
$input = socket_read($socket_accepted, 1024) or die("Could not read socket input\n");
$input = trim($input);
echo "Client message: ", $input, PHP_EOL;
socket_write($socket_accepted, $input, strlen($input)) or die("Could not write socket input\n");
}while(true);
socket_close($socket_accepted);
socket_close($socket);
?><file_sep># echoServerPHP
Echo server made with sockets in a TCP connection
<file_sep><?php
// Set variables
$host = "localhost";
$port = 1234;
// No timeout
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_connect($socket, $host, $port) or die("Could not connect to socket\n");
do{
$message = readline("Enter a message: ");
socket_write($socket, $message, strlen($message)) or die("Could not write message input\n");
$output = socket_read($socket, 1024) or die("Could not read socket message from server\n");
echo "Reply from server: ", $output, PHP_EOL;
}while(true);
socket_close($socket);
?> | 943a6853f9c060c7e12c2307b187495532d9be6d | [
"Markdown",
"PHP"
] | 3 | PHP | arielangeles/echoServerPHP | 97ad2a426ede990d2f2b5a4ec2b280cf0984217d | cc847bdbbc20456db32231e1692c2c02c24fef4e |
refs/heads/main | <repo_name>Code-Sydney-Related-Work/FCC--Project_5<file_sep>/cash_register.js
function checkCashRegister(price, cash, cid)
{
let changeOwed = cash - price;
let cashInBox = 0;
let accArray = [];
for(let m = 0; m < cid.length; m++){accArray[m]=cid[cid.length - 1 - m];} //console.log(accArray);
XXXXXXXXXXXXXXXXX PORTION OF CODE DELETED TO PROTECT INTELLECTUAL PROPERTY XXXXXXXXXXXXXXXX
for(let i=0; i < cid.length; i++)
{cashInBox += cid[i][1];}
if (cashInBox === changeOwed)
{ outputObj.status = "CLOSED";
outputObj.change = cid;
return outputObj;}
if (cashInBox < changeOwed)
{ outputObj.status = "INSUFFICIENT_FUNDS";
return outputObj;}
let tempcashcount = cashInBox;
let allocatedcurr = 0;
XXXXXXXXXXXXXXXXXXXXXX PORTION OF CODE DELETED TO PROTECT INTELLECTUAL PROPERTY XXXXXXXXXXXXXXXX
if(outputArray.length < 1 || changeOwed > 0){
outputObj.status = "INSUFFICIENT_FUNDS";
return outputObj;
}
outputObj.status = "OPEN";
outputObj.change = outputArray;
return outputObj;
}
module.exports = checkCashRegister;
<file_sep>/cash_register.test.js
const { TestScheduler } = require('jest');
const checkCashRegister = require('./cash_register');
describe('checkCashRegister', ()=>{
test('calculate the currencies to be dispensed', () => {
expect(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1],
["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])).toMatchObject({status: "OPEN", change: [["TWENTY", 60],
["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]});
});
}); | a82fe47b229cd4e6d4bf501849a7c9814c086483 | [
"JavaScript"
] | 2 | JavaScript | Code-Sydney-Related-Work/FCC--Project_5 | eee5c2a7e9110f7846cf93ee971d142397529265 | 0540a23f04fffea6eb14f58408535e29b460b78e |
refs/heads/main | <repo_name>vigacv/arquitecturabdoracle<file_sep>/index.js
var dicc = {
"PGA": {
"title": "Program Global Area",
"desc": "Es la porción de memoria que ocupa un server process (uno por server process) y es privada para cada server process. Comienza con 3 MB, aproximadamente, pero su tamaño varía conforme a la carga. Puede usar memoria swap/virtual en caso lo requiera (ORA-04030)."
},
"SGA":{
"title": "System Global Area",
"desc": "Es memoria compartida entre todos los server process. La distribución usual es 40% Buffer Cache y 40% Shared Pool. Cuando llega un query este primero pasa por el library cache, luego una vez se tiene el plan de ejecución, primero se consulta si los registros están en buffer cache, en cuyo caso se leen de ahí (logical read) y si no, se busca en disco (physical read). El Buffer Cache y el Shared Pool usan el algoritmo LRU (Least Recently Used) para organizar su espacio."
},
"Data Block": {
"title": "Data Block",
"desc": "Es la unidad mínima con la que se compone una base de datos, es decir son registros. Puede ser de varios tamaños: 2, 4, 8, 16 o 32 Kb. En Oracle se llama Data Block, en SQL Server se conoce como página. Sugerencia de tamaños: 2 - 4 Kb para bases de datos altamente transaccionales, 8 Kb Mixta (Transaccional + Reporteria (DW)), 16 - 32 Kb DW."
},
"Parameter File":{
"title": "Parameter File",
"desc": "Define como se configura la instancia. Guarda parametros de la base de datos. En oracle hay alrededor de 300 parametros. 2 modos: PFILE O SPFILE. <ul><li>PFILE(initPRDSID.ora): Archivo plano. Se puede editar de manera directa pero requiere reinicio.</li><li>SPFILE(spfilePRDSID.ora): Es un archivo binario y solo se puede editar con comandos SQL (alter system). 2/3 de los parametros son cambiantes sin reinicio.</li></ul>"
},
"LGWR":{
"title": "Log Writter",
"desc": "Escribe el log. Lee lo que está en memoria en el Redo Log Buffer y lo manda a los Redo Log Files. Ocurre: <ul><li>Cada 3 segundos</li><li>Cada commit</li><li>Cada 1MB de updates</li></ul>"
},
"DBWR":{
"title": "Database writter",
"desc": "Baja la información que está en el buffer cache y la guarda para su persistencia. Las operaciones de update, insert y delete ocurren en el buffer cache, pero se requieren bajar a la capa física para que persistan. Se ejecuta: <ul><li>Cuando el buffer cache esta lleno</li><li>Cuando se hace alguna operacion de DROP.</li><li>Cuando hay demasiado dirty blocks (registros cambiados que aun no son guardados en disco).</li></ul>"
},
"CKPT":{
"title": "Checkpoint Process",
"desc": "De por sí no hace nada, es un coordinador. 'Mi base de datos todo el tiempo es inconsistente', se dice esto porque la información que está en memoria no es exactamente igual a la que está en capa física, existe una desincronización normal. El Checkpoint Process tiene como objetivo dejar la base de datos consistente, lo cual logra cuando se ejecuta, pero la siguiente fracción de segundo vuelve a estar inconsistente. Le ordena a los otros bg processes ejecutarse. Ocurre: <ul><li>Cada 1800 segundos (se pude modificar)</li><li>Cuando se detiene la bd de manera limpia</li><li>Switch de redo logs.</li></ul>"
},
"SMON":{
"title": "System MONitor",
"desc": "Tiene dos principales funciones: <ol><li>Instance Recovery: El SCN (Sequence Changed Number) es un id incremental que la bd genera por cada transaccion y que también tienen los datafiles en sus cabeceras, el cual se sincroniza con el CKPT. Cuando la bd no baja bien y el SCN no es consistente, se inicia el Instance Recovery.</li><li>Limpieza de temporales (tempfiles)</li></ol>"
}
};
var diccComponents = {
"UI":{
"titleComp": "User Information",
"desc": "Guarda información mínima del usuario, como nombre de usuario, hostname del cliente, ejecutable, etc."
},
"PSQL":{
"titleComp": "Private SQL Area",
"desc": "Guarda variables de PL/SQL. *Nota: Un cursor es todo un PSQL Area a parte."
},
"WKArea":{
"titleComp": "Work Area",
"desc": "Guarda operaciones de ordenamiento, como order by, group by, distinct, indices, join."
},
"Shared Pool":{
"titleComp": "Shared Pool",
"desc": "Cuando se hace una consulta, Oracle buscará el hash de dicha consulta aquí, en particular en el Library Cache y lanza el plan de ejecución (soft parse). De no encontrarlo lo guarda (hard parse)."
},
"Library Cache":{
"titleComp": "Library Cache",
"desc": "Aqui se guarda los hash de las consultas (case sensitive). Además lanza el plan de ejecución, el cual optimiza los queries."
},
"Data Dictionary":{
"titleComp": "Data Dictionary",
"desc": "Guarda información de las vistas que no tienen persistencia (ejemplo: v$instance)"
},
"Result Cache":{
"titleComp": "Result Cache",
"desc": "Creado en la versión 11g. Guarda resultados. Por ejemplo de un sum."
},
"ASH":{
"titleComp": "Active Session History",
"desc": "Creado en la versión 10g. Guarda cada segundo todo lo que se está haciendo en la base de datos (sentencias SQL + user id)"
},
"Large Pool":{
"titleComp": "Active Session History",
"desc": "Creado en la versión 9i para asumir ciertas responsabilidades que antes el Shared Pool hacía, como son: Backup/Restore (rman), paralelismo, Transacciones XA (aplicaciones que interactúa con múltiples bds)."
},
"Java Pool":{
"titleComp": "Java Pool",
"desc": "Introducido en la versión 8i. Espacio en memoria RAM donde se almacenan objetos Java instanciados. Requiere la JVM."
},
"Stream Pool":{
"titleComp": "Java Pool",
"desc": "Desde 9i. Guarda colas AQ (Advanced Queue). Replicación"
},
"Redo":{
"titleComp": "Redo Log Buffer",
"desc": "Sirve para recuperación. Guarda todas las sintaxis de sentencias DML, DDL, DCL. Es una especie de caja negra."
},
"PFILE":{
"titleComp": "Parameter File",
"desc": "(initPRDSID.ora) Archivo plano. Se puede editar de manera directa pero requiere reinicio."
},
"SPFILE":{
"titleComp": "Redo Log Buffer",
"desc": "(spfilePRDSID.ora) Es un archivo binario y solo se puede editar con comandos SQL (alter system). 2/3 de los parametros son cambiantes sin reinicio."
},
"Control File":{
"titleComp": "Control File",
"desc": "Metadata de la base de datos. Guarda el SCN"
},
"Background processes":{
"titleComp": "Background processes",
"desc": "Se encargan de hacer convivir lo de arriba (instancia) con lo de abajo (capa física). Conocidos como demonios/daemons porque están ejecutandose todo el tiempo."
},
"PMON":{
"titleComp": "Process MONitor",
"desc": "Se encarga de la recuperación de recursos cuando una sesión no se cierra correctamente. Hace rollback para liberar las tablas que podrían estar bloqueadas."
},
"LREG":{
"titleComp": "Listener Registration",
"desc": "Desde 12c. Sus tareas eran antes realizadas por el PMON. Agarra los servicios de la bd y busca un listener por default (puerto 1521/tcp) y registrará los servicios ahí para habilitar la conexión."
},
"MMAN":{
"titleComp": "Memory Manager",
"desc": "Desde 10g. Reparte la memoria asignada al SGA entre sus componentes."
},
"MMNL":{
"titleComp": "MMON Lite",
"desc": "Desde 10g. Descarga la información del ASH y lo graba en los datafiles, en particular en unas tablas que sirven para afinamiento. Hace muestras de cada 10 segundos."
},
"MMON":{
"titleComp": "Manageability Monitor",
"desc": "Desde 10g. Toma fotos a la estructura de la BD (como esta el PGA, cuanta memoria ocupa, como estan los discos, etc.) y lo encapsula en snapshots. Ocurre cada hora y permanece por 8 dias por default. Tambien se encarga de borrar los archivos trace."
},
"RECO":{
"titleComp": "Recoverer",
"desc": "Se usa en dblink, para confirmar transacciones entre bases de datos remotas, y cancelarlas si es necesario."
},
"SMCO":{
"titleComp": "Space Management Coordinator",
"desc": "Responsable de asegurar que haya espacio en los tablespaces."
}
}
var activarToolTips = function(){
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
}
var activarPopOvers = function(){
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
}
var llenarInfoOffCanvas = function(e){
var info = dicc[e.target.innerHTML];
document.querySelector("#offcanvasBottomLabel").innerHTML = info.title;
document.querySelector("#offCanvasBotomText").innerHTML = info.desc;
}
var asignarFuncionInfoOffC = function(){
for(var title of document.getElementsByClassName("infoOffCanvas")){
title.addEventListener("click", llenarInfoOffCanvas)
}
}
var llenarInfoPopOver = function(e){
console.log(e);
console.log(e.innerHTML);
var componentInfo = diccComponents[e.innerHTML];
var currentComponent = e;
console.log(componentInfo["desc"]);
currentComponent.setAttribute("title", componentInfo["titleComp"]);
currentComponent.setAttribute("data-bs-content", componentInfo["desc"]);
}
var asignarFuncionPopOvers = function(){
for(let comp of document.getElementsByClassName("bdcomponent")){
llenarInfoPopOver(comp);
}
}
window.addEventListener("load", function(){
activarToolTips();
activarPopOvers();
asignarFuncionInfoOffC();
asignarFuncionPopOvers();
}) | 09757cb1095f18d9dd37c431c5132795377aa753 | [
"JavaScript"
] | 1 | JavaScript | vigacv/arquitecturabdoracle | 2f9e173d13eef1c827e623debae32b5f077e7a17 | 01950d46b41d7277084a69e6b37e20d25648e813 |
refs/heads/master | <repo_name>guojiangtv/overseas-webpack<file_sep>/README.md
### eslint对vue组件的监视及自动修改设置
在vscode的setting.json文件中添加以下内容
```
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",{
"language": "vue",
"autoFix": true
},
"html",
"vue"
],
```
### 海外版前端自动化编译构建工具使用说明
此工具仅适用于海外前后端分离项目,之前的php项目仍就采用之前的gulp编译并手动发布
此项目采用非覆盖式编译,公共js文件打包成一个dll.js,common.js采用ES6 Module形式,项目中用到哪个方法直接import 引入该方法即可
```js
import {showLoading} from 'common'
```
项目中已引入typescript编译,可参考累充活动cumulativeRecharge
git clone此项目后
yarn install安装必要的项目依赖和开发依赖包
主项目文件在海外gitlab上,需要配置host 172.16.17.32 gitlab.cblive.tv
访问地址https://gitlab.cblive.tv
git clone git@gitlab.cblive.tv:root/national-overseas.git
主项目文件下载完后 先建立自己的开发分支 feature/*** 在自己的分支上开发
发测试和线上同国内项目相同
### 注意点
在ejs文件中直接引入图片时,需用require形式
```
<img src='${require("../../../../src/v2/mobile/img/recharge/index/Telkomsel.png")}' alt="">
```
建议在overseas-webpack文件夹下建立trunk文件夹并拉取已下svn地址 ,用于查看提交文件列表
html文件夹 https://10.0.0.15/svn/develop/website/trunk/cblive/web/html
static_cblive https://10.0.0.15/svn/develop/website/trunk/static_cblive
#### mobile端编译命令
yarn dll 打包公共文件生成dll.js
yarn watch 开发编译,监测文件变化
yarn build 打包
yarn deploy 压缩打包
#### 越南版mobile端编译命令 都加上vn_前缀
yarn vn_dll
#### 中东版mobile端编译命令 都加上arb_前缀
yarn arb_dll
#### pc端编译命令 都加上pc_前缀
yarn pc_dll
#### yeoman工具使用方法
yeoman已集成到项目脚手架中
执行`yarn new`命令可启动yeoman,填写英文名称,项目名称,项目标题,选择项目模板pc或mobile,即可自动生成相应的文件
#### 海外项目中mockjs使用方法
在前后端分离开发模式下,为了方便前端自己模拟数据,引入mockjs库,目前已在项目脚手架中安装。
#### mockjs使用方法
* 在mock文件夹中新建js文件,文件中需引入mockjs
* 编辑文件
```js
import Mock from 'mockjs';
Mock.mock('/worldcup/userrank', {
'errno': 0,
'msg': '',
'data|10':[
{
'uid|+1' : 123,
'nickname' : 'ruby',
'headPic' : 'http://fpoimg.com/200x200',
'rank' : 1, //用户排名
'points|+1' : 1000, //用户积分
'isFollow|0-1' : 1 //0:未关注 1:已关注
}
]
});
```
Mock能自动拦截页面js中发出的ajax请求,并将模拟的数据作为请求结果返回
至于如何模拟自己想要的数据可参考[语法规范](https://github.com/nuysoft/Mock/wiki/Syntax-Specification)
* 在项目js文件中引入自己模拟的数据文件
```js
//mock数据
import '../../../../../mock/worldcup.js';
```
当本地开发完要发测试时需在项目js文件中注释掉引入的模拟数据文件
<file_sep>/mock/worldcup.js
import Mock from 'mockjs';
Mock.mock('/worldCup/userinfo', {
'errno': 0,
'msg': '',
'data': {
'uid': 123,
'nickname': 'ruby',
'headPic': 'http://fpoimg.com/200x200',
'gifts': {
'67': 99, //用户送出的 大力神杯 礼物个数
'68': 120 //用户送出的 T-shirt 礼物个数
},
'winCoins': 100, //用户抽奖收到的金币数
'chance': 10 //用户拥有的抽奖次数
}
});
Mock.mock('/worldCup/lottery', {
'errno': 0,
'msg': '',
'data':{
'result':{
'level' : 1, //奖品等级
'prize' : 10 //奖励的金币数
}
}
});
Mock.mock('/worldCup/modrank', {
'errno': 0,
'msg': '',
'data|10':[
{
'uid|+1' : 123,
'nickname' : 'ruby',
'headPic' : 'http://fpoimg.com/200x200',
'rank' : 1, //用户排名
'points|+1' : 1000, //用户积分
'isPlay' : 1, //1:直播中 0:没有直播
'isVip' : 1, //0:非VIP 1:VIP用户
'isFollow' : 1 //0:未关注 1:已关注
}
]
});
Mock.mock('/worldCup/userrank', {
'errno': 0,
'msg': '',
'data|10':[
{
'uid|+1' : 123,
'nickname' : 'ruby',
'headPic' : 'http://fpoimg.com/200x200',
'rank' : 1, //用户排名
'points|+1' : 1000, //用户积分
'isFollow|0-1' : 1 //0:未关注 1:已关注
}
]
});
Mock.mock('/worldCup/love?mid=123', {
'errno': 0,
'msg': '',
'data':{}
});
<file_sep>/.eslintrc.js
module.exports = {
root: true,
env: {
//浏览器环境中的全局变量
browser: true,
//CommonJS 全局变量和 CommonJS 作用域
commonjs: true,
// 启用除了 modules 以外的所有 ECMAScript 6 特性(该选项会自动设置 ecmaVersion 解析器选项为 6)
es6: true
},
//定义全局变量
globals: {
window:true,//用于定义方法便于app调用
_czc: true, //用于统计
recharge:true,//安卓js对象
gBridge:true//ios android js对象
},
extends: [
"eslint:recommended",
"plugin:vue/recommended",
"plugin:import/errors",
"plugin:import/warnings",
//https://standardjs.com/rules-zhcn.html#javascript-standard-style
"standard"
],
parserOptions: {
parser: "babel-eslint",
sourceType: "module"
},
//此项是用来提供插件的,插件名称省略了eslint-plugin-
plugins: ["vue"],
rules: {
"import/no-unresolved": ["error", { commonjs: true, amd: true }],
"import/namespace": "error",
"import/default": "error",
"import/export": "error",
"indent": ["error", 4],
//取消强制使用一致的换行风格
"linebreak-style": "off",
"no-console": "off",
//函数需要jsDoc注释 ctrl+alt+D
// "require-jsdoc": [
// "error",
// {
// require: {
// FunctionDeclaration: true,
// MethodDefinition: true,
// ClassDeclaration: false,
// ArrowFunctionExpression: false,
// FunctionExpression: false
// }
// }
// ],
"strict": "error",
//new实例可以不赋值给变量,new Vue()
"no-new": "off",
// 是否禁止无用的表达式
"no-unused-expressions": "off",
// 取消禁止扩展原生对象
"no-extend-native": "off",
//不限制每行的属性数量
"vue/max-attributes-per-line": "off",
// 组件的属性必须为一定的顺序
'vue/order-in-components': 'off'
},
settings: {
/**
* 这里传入webpack并不是import插件能识别webpack,而且通过npm安装了「eslint-import-resolver-webpack」,
* 「import」插件通过「eslint-import-resolver-」+「webpack」找到该插件并使用,就能解析webpack配置项。使用里面的参数。
* 主要是使用以下这些参数,共享给import规则,让其正确识别import路径
* extensions: ['.js', '.vue', '.json'],
* alias: {
* 'vue$': 'vue/dist/vue.esm.js',
* '@': resolve('src'),
* 'static': resolve('static')
* }
*/
"import/resolver": "webpack"
}
};
<file_sep>/generators/activity/config.yo.js
module.exports = {
/* Base Path */
outputHtmlDir: '/guojiang/overseas-webpack/national-overseas/html/src', // html输出路径
outputStaticDir: '/guojiang/overseas-webpack/national-overseas/src/v2', // 静态文件相关输出路径
/* Templates Relative Path */
outputHtmlPCDir: 'pc/',
outputHtmlMobileDir: 'mobile/',
/* Static Resource Relative Path */
outputStaticPCDirForJS: 'pc/js/',
outputStaticPCDirForStyles: 'pc/css/',
outputStaticPCDirForImgs: 'pc/img/',
outputStaticMobileDirForJS: 'mobile/js/',
outputStaticMobileDirForStyles: 'mobile/css/',
outputStaticMobileDirForImgs: 'mobile/img/'
};
<file_sep>/generators/activity/templates/mobile/scripts/main.ts
/*
* @Author: <%= youName %>
* @Date: <%= Date %>
*/
import '<%= stylePath %>'
import Vue from 'vue'
import axios from 'axios'
import {goPersonalPage} from '../../js/common/common'
new Vue({
el: '#app',
data: {},
created () {
},
mounted () {
},
methods: {
// 点击头像,进入个人主页
goPersonalPage (id:number) {
goPersonalPage(id)
},
// 点击关注按钮,关注主播
attention (uid:number, index:number) {
axios.get('***', {
params: {
mid: uid
}
})
.then(res => {
let _data = res.data
if (typeof _data === 'string') {
_data = JSON.parse(_data)
}
if (_data.errno === 0) {
// this.rankList[index].isFollow = true
} else {
console.log(_data.msg)
}
})
.catch(err => {
console.log(err)
})
}
}
})
<file_sep>/gulpfile.js
//引入插件
var gulp = require('gulp'),
cleanCss = require('gulp-clean-css'),
uglify = require('gulp-uglify'),
less = require('gulp-less'),
plumber = require('gulp-plumber'), // less报错时不退出watch
fs = require('fs'), //获取真实路径
runSequence = require('run-sequence'),
rev = require('gulp-rev-params'),
revCollector = require('gulp-rev-collector-params'),
gulpif = require('gulp-if'),
changed = require('gulp-changed'),
debug = require('gulp-debug'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
sourcemaps = require('gulp-sourcemaps');
// 任务处理的文件路径配置
var m_src = {
js: fs.realpathSync('./national-overseas/src/mobile/js') + '/**/*.js',
css: fs.realpathSync('./national-overseas/src/mobile/css') + '/**/*',
img: './national-overseas/src/mobile/img/**',
base: './national-overseas/src/mobile/'
},
m_dist = {
jscss: [
fs.realpathSync('./national-overseas/dist/mobile/js') + '/**/*.js',
fs.realpathSync('./national-overseas/dist/mobile/css') + '/**/*.css'
]
},
m_output = './national-overseas/dist/mobile';
//定义句柄状态为未发布
var isRelease = false;
/******************************** mobile ****************************/
//清除dist目录中的js和css文件 不常用
gulp.task('clean', function() {
return gulp.src(m_dist.jscss, { read: false })
.pipe(clean({ force: true }));
})
//处理js 压缩 混淆 添加版本号
gulp.task('scripts', function() {
return gulp.src(m_src.js, { base: m_src.base })
.pipe(gulpif(!isRelease, changed(m_output)))
.pipe(gulpif(isRelease, sourcemaps.init()))
.pipe(gulpif(isRelease, uglify()))
.on('error', errorHandler)
.pipe(gulpif(isRelease, rev()))
.pipe(debug({ title: 'js:' }))
.pipe(gulpif(isRelease, sourcemaps.write('./maps')))
.pipe(gulp.dest(m_output))
.pipe(gulpif(isRelease, rev.manifest()))
.pipe(gulpif(isRelease, gulp.dest('./rev/mobile/js/')));
});
gulp.task('less', function() {
return gulp.src(m_src.css, { base: m_src.base })
.pipe(gulpif(!isRelease, changed(m_output, {extension: '.css'})))
.pipe(sourcemaps.init())
.pipe(less()).on('error', errorHandler)
.pipe(sourcemaps.write())
.pipe(plumber())
.pipe(postcss([autoprefixer()]))
.pipe(gulpif(isRelease, cleanCss()))
.pipe(gulpif(isRelease, rev()))
.pipe(debug({ title: 'css:' }))
.pipe(gulp.dest(m_output))
.pipe(gulpif(isRelease, rev.manifest()))
.pipe(gulpif(isRelease, gulp.dest('./rev/mobile/css/')));
});
gulp.task('images', function() {
return gulp.src(m_src.img, { base: m_src.base })
.pipe(gulpif(!isRelease, changed(m_output)))
.pipe(gulpif(isRelease, rev()))
.pipe(gulp.dest(m_output))
.pipe(gulpif(isRelease, rev.manifest()))
.pipe(gulpif(isRelease,gulp.dest('./rev/mobile/img/')));
});
gulp.task('rev', function() {
//为php模板添加版本号
gulp.src(['./rev/mobile/**/*.json', 'z:/cblive/web/protected/modules/mobile/views/**/*.php'])
.pipe(revCollector({replaceReved: true}))
.pipe(gulp.dest(fs.realpathSync('z:/cblive/web/protected/modules/mobile/views/')));
//为css中图片添加版本号
gulp.src(['./rev/mobile/img/*.json', './national-overseas/dist/mobile/css/*'])
.pipe(revCollector({replaceReved: true}))
.pipe(gulp.dest(fs.realpathSync('./national-overseas/dist/mobile/css/')));
//为js中图片添加版本号
gulp.src(['./rev/mobile/img/*.json', './national-overseas/dist/mobile/js/*'])
.pipe(revCollector({replaceReved: true}))
.pipe(gulp.dest(fs.realpathSync('./national-overseas/dist/mobile/js/')));
});
// 测试以及线上环境 ,每次发布的时候会对所有的文件添加新版本号
gulp.task('release', function() {
//更改句柄为发布状态
isRelease = true;
return runSequence(
['images', 'less', 'scripts'], ['rev']
);
});
//本地开发环境
gulp.task('dev', function() {
return runSequence(
['images', 'less', 'scripts'],
function() {
var less_watcher = gulp.watch(m_src.css, ['less']);
less_watcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
})
var js_watcher = gulp.watch(m_src.js, ['scripts']);
js_watcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
})
}
);
});
//默认执行gulp dev命令
gulp.task('default', ['dev'])
/*错误处理*/
function errorHandler(error) {
console.log(error.toString());
this.emit('end');
}
<file_sep>/generators/activity/templates/pc/scripts/main.js
'use strict';
import Vue from 'vue';
import axios from 'axios';
import user from 'user';
// import layer from 'layer'; // desc: 弹出层插件
import '<%= stylePath %>'
new Vue({
el: '#app',
data: {},
methods: {
//适配机型重定向
adaptation() {
let href = window.location;
if (/Android|webOS|iPhone|iPod|iPad|BlackBerry|Windows Phone|SymbianOS/i.test(navigator.userAgent)) {
if (href.host.indexOf('www') >= 0) {
window.location.href = '//m.kuaishouvideo.com/dist' + href.pathname;
}
} else {
if (href.host.indexOf('www') < 0) {
window.location.href = '//www.kuaishouvideo.com' + href.pathname.replace('/dist', '');
}
}
},
},
mounted: function() {
// pc / mobile 重定向
this.adaptation();
}
});
<file_sep>/webpack-dll.config.js
const path = require('path');
const webpack = require('webpack');
const chalk = require('chalk')
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //抽离css
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const HashedChunkIdsPlugin = require('./config/hashedChunkIdsPlugin.js')
const CleanWebpackPlugin = require('clean-webpack-plugin')
//是否是生产环境
const prod = process.env.NODE_ENV === 'production' ? true : false;
//是否是pc编译
const isPc = process.env.PLATFORM == 'pc' ? true : false;
//是否是越南版编译
let isVn = process.env.COUNTRY == 'vietnam' ? true : false;
//是否是中东版编译
let isArb = process.env.COUNTRY == 'arb' ? true : false;
//webpack配置
const postcssConfigDir = './config/postcss.config.js';
const resolveConfigDir = './config/resolve.config.js';
let baseEntryDir,outputDir,outputPublicDir,entries,dll_manifest_name,entryDir;
if(isPc){
//PC目录配置
baseEntryDir = './national-overseas/src/v2/pc/';
entryDir = baseEntryDir + '**/*.js';
outputDir = path.resolve(__dirname, './national-overseas/dist/v2/pc/');
outputPublicDir = '//static.cblive.tv/dist/v2/pc/';
entries = ['vue','axios','layer','jquery'];
dll_manifest_name = 'dll_pc_manifest';
}else if(isVn){
baseEntryDir = './national-overseas/src/vietnam/mobile/';
entryDir = baseEntryDir + '**/*.js';
outputDir = path.resolve(__dirname, './national-overseas/dist/vietnam/mobile/');
outputPublicDir = '//static.cblive.tv/dist/v2/vietnam/mobile/';
entries = ['vue', 'axios', 'layer'];
dll_manifest_name = 'dll_vn_manifest';
}else if(isArb){
baseEntryDir = './national-overseas/src/arb/mobile/';
entryDir = baseEntryDir + '**/*.js';
outputDir = path.resolve(__dirname, './national-overseas/dist/arb/mobile/');
outputPublicDir = '//static.cblive.tv/dist/v2/arb/mobile/';
entries = ['vue', 'axios', 'layer'];
dll_manifest_name = 'dll_arb_manifest';
}else{
baseEntryDir = './national-overseas/src/v2/mobile/';
entryDir = baseEntryDir + '**/*.*';
outputDir = path.resolve(__dirname, './national-overseas/dist/v2/mobile/');
outputPublicDir = '//static.cblive.tv/dist/v2/mobile/';
entries = ['vue', 'axios', 'layer'];
dll_manifest_name = 'dll_manifest';
}
module.exports = {
/* 输入文件 */
resolve: require(resolveConfigDir),
entry: {
dll: entries
},
output: {
path: outputDir,
publicPath: outputPublicDir,
filename: 'js/lib/[name].[chunkhash:8].js',
library: '[name]_library',
/*libraryTarget: 'umd'*/
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
postcss: [require( postcssConfigDir )]
}
},
{
test: /\.js$/,
enforce: 'pre',
loader: 'eslint-loader',
include: path.resolve(__dirname, entryDir),
exclude: [baseEntryDir + 'js/lib', baseEntryDir + 'js/component'],
options: {
fix: true
}
},
{
test: /\.js$/,
loader: 'babel-loader?cacheDirectory=true',
exclude: ['node_modules', baseEntryDir + 'js/lib', baseEntryDir + 'js/component']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader'],
exclude: [baseEntryDir + 'css/lib']
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract(['css-loader','postcss-loader','less-loader']),
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader',
options: {
limit: 512,
name: function(p){
let tem_path
if (p.indexOf('/') != -1) {
// linux
tem_path = p.split(/\/img\//)[1]
} else {
// win
tem_path = p.split(/\\img\\/)[1]
}
tem_path = tem_path.replace(/\\/g, '/')
return 'img/' + tem_path + '?v=[hash:8]'
}
}
}
]
},
plugins: [
// 清除lib内旧版本的库文件,防止后面插入html时错乱
// 服务器时间的更改会导致文件创建时间不准确
new CleanWebpackPlugin([
'css/lib/dll.*.css',
'css/lib/dll.*.css.map',
'js/lib/dll.*.js',
'js/lib/dll.*.js.map'
], {
root: outputDir
}),
//keep module.id stable when vender modules does not change
new HashedChunkIdsPlugin(),
new webpack.HashedModuleIdsPlugin(),
new webpack.DllPlugin({
// 本Dll文件中各模块的索引,供DllReferencePlugin读取使用
path: './manifest/'+ dll_manifest_name + '.json',
//当前Dll的所有内容都会存放在这个参数指定变量名的一个全局变量下,注意与参数output.library保持一致
name: '[name]_library',
// 指定一个路径作为上下文环境,需要与DllReferencePlugin的context参数保持一致,建议统一设置为项目根目录
context: __dirname,
}),
new ExtractTextPlugin('css/lib/[name].[contenthash:8].css'),
new webpack.LoaderOptionsPlugin({
options: {
postcss: require(postcssConfigDir)
},
})
]
};
/***** 区分开发环境和生产环境 *****/
if (prod) {
console.log(chalk.red('当前编译环境:production'));
module.exports.plugins = module.exports.plugins.concat([
// 压缩css代码
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css\.*(?!.*map)/g, // 注意不要写成 /\.css$/g
cssProcessor: require('cssnano'),
cssProcessorOptions: {
discardComments: {removeAll: true },
// 避免 cssnano 重新计算 z-index
safe: true,
// cssnano通过移除注释、空白、重复规则、过时的浏览器前缀以及做出其他的优化来工作,一般能减少至少 50% 的大小
// cssnano 集成了autoprefixer的功能。会使用到autoprefixer进行无关前缀的清理。默认不兼容ios8,会去掉部分webkit前缀,比如flex
// 所以这里选择关闭,使用postcss的autoprefixer功能
autoprefixer: false
},
canPrint: true
}),
//压缩JS代码
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
ie8: false,
output: {
comments: false,
beautify: false,
},
compress: true,
warnings: false
}
}),
]);
} else {
console.log(chalk.red('当前编译环境:dev'));
module.exports.devtool = 'cheap-module-source-map';
}
| 5a4450b850a5985d94f830175692daf6804e8080 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 8 | Markdown | guojiangtv/overseas-webpack | 3e95ff6131ea276b2a693f41d95a6efe42b6831b | 0b88b949c77cffbd4f7e1f23ba4a78438626152c |
refs/heads/master | <repo_name>heinrich10/pos<file_sep>/src/main/java/com/app/erp/controller/MaintenanceController.java
package com.app.erp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/maintenance")
public class MaintenanceController {
@RequestMapping(value = "/")
public String mainPage(){
return "maintenance";
}
}
<file_sep>/src/main/java/com/app/erp/service/IngredientService.java
package com.app.erp.service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import com.app.erp.mapper.IngredientMapper;
import com.app.erp.model.IngredientCodeList;
import com.app.erp.model.IngredientLink;
public class IngredientService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5761957303785995228L;
@Inject
private transient IngredientMapper ingredientMapper;
public IngredientCodeList loadIngredientCode(){
return new IngredientCodeList(ingredientMapper.loadIngredientCode());
}
public IngredientLink loadIngredientLink(String codeIngredient){
IngredientLink ingredientLink = ingredientMapper.loadIngredientLink(codeIngredient);
if(ingredientLink == null){
ingredientLink = new IngredientLink();
//ingredientLink.setLink1(0);
//ingredientLink.setLink2(0);
}
ingredientLink.setCodeIngredient(codeIngredient);
return ingredientLink;
}
public void validate(IngredientLink ingredientLink) throws Exception{
long itemNumber1 = ingredientLink.getLink1();
long itemNumber2 = ingredientLink.getLink2();
if(itemNumber1 == 0 && itemNumber2 == 0){
}else if(itemNumber1 == itemNumber2){
throw new Exception();
}
}
public void saveIngredientLink(IngredientLink ingredientLink){
ingredientMapper.saveIngredientLink(ingredientLink);
}
}
<file_sep>/src/main/java/com/app/erp/model/Discount.java
package com.app.erp.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Range;
public class Discount {
@Size(min=1, max=10)
private String codeDiscount;
@Size(min=1, max=45)
private String name;
@Range(min=0, max=1)
private double discountFactor;
private boolean indVatable = true;
public Discount(){
}
public Discount(String codeDiscount, String name, double discountFactor, boolean indVatable){
this.codeDiscount = codeDiscount;
this.name = name;
this.discountFactor = discountFactor;
this.indVatable = indVatable;
}
public String getCodeDiscount() {
return codeDiscount;
}
public void setCodeDiscount(String codeDiscount){
this.codeDiscount = codeDiscount;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public double getDiscountFactor(){
return discountFactor;
}
public void setDiscountFactor(double discountFactor){
this.discountFactor = discountFactor;
}
public boolean getIndVatable(){
return indVatable;
}
public void setIndVatable(boolean indVatable){
this.indVatable = indVatable;
}
}
<file_sep>/src/main/java/com/app/erp/mapper/MenuItemMapper.java
package com.app.erp.mapper;
import java.util.List;
import com.app.erp.model.MenuItem;
import com.app.erp.model.MenuItemType;
public interface MenuItemMapper {
List<MenuItem> loadMenuItem();
List<MenuItem> loadMenuItem(String[] codeMenuItem);
void updateMenuItem(MenuItem menuItem);
List<MenuItemType> loadMenuItemType();
MenuItemType loadMenuItemType(String code);
void saveMenuItemType(MenuItemType menuItemType);
void updateMenuItemType(MenuItemType menuItemType);
int allowDeletion(String code);
void deleteMenuItemType(String[] code);
}
<file_sep>/src/main/java/com/app/erp/controller/SystemController.java
package com.app.erp.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.app.erp.util.MyUserInfo;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
@Controller
@RequestMapping(value="/system")
public class SystemController {
@RequestMapping(value="/", method=RequestMethod.GET)
public String home(){
return "system";
}
@RequestMapping(value="/shutdown", method=RequestMethod.GET)
public ModelAndView shutdown(Map<String, Object> myModel){
myModel.put("option", "shutdown");
return new ModelAndView("system", myModel);
}
@RequestMapping(value="/shutdown", method=RequestMethod.POST)
public void submitShutdown(JSch jsch){
String user = "rick";
String host = "192.168.159.10";
String password = "<PASSWORD>";
InputStream in = null;
Session session;
try {
session = jsch.getSession(user, host, 22);
session.setPassword(<PASSWORD>);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("sudo -S -p '' sudo shutdown -h now");
in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((password + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping(value="/parameters", method=RequestMethod.GET)
public ModelAndView loadParameters(Map<String, Object> myModel){
return new ModelAndView();
}
}
<file_sep>/src/main/java/com/app/erp/model/MenuItem.java
package com.app.erp.model;
import java.io.Serializable;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
public class MenuItem implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7976731707644029073L;
private String code;
private String type;
@Size(min=1, max=25)
private String name;
@Size(min=1, max=100)
private String description;
@Min(0)
private double price;
private String typeCode;
private double recipePrice;
public void setCode(String code){
this.code = code;
}
public String getCode(){
return code;
}
public void setType(String type){
this.type = type;
}
public String getType(){
return type;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return description;
}
public void setPrice(double price){
this.price = price;
}
public double getPrice(){
return price;
}
public void setTypeCode(String typeCode){
this.typeCode = typeCode;
}
public String getTypeCode(){
return typeCode;
}
public void setRecipePrice(double recipePrice){
this.recipePrice = recipePrice;
}
public double getRecipePrice(){
return recipePrice;
}
}
<file_sep>/src/main/java/com/app/erp/model/OrderList.java
package com.app.erp.model;
import java.io.Serializable;
import java.util.List;
public class OrderList implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4244742121633006674L;
private List<TranOrder> tranOrderList;
public OrderList(){
}
public OrderList(List<TranOrder> tranOrderList){
this.tranOrderList = tranOrderList;
}
public List<TranOrder> getTranOrderList(){
return tranOrderList;
}
public void setTranOrderList(List<TranOrder> tranOrderList){
this.tranOrderList = tranOrderList;
}
}
<file_sep>/src/main/java/com/app/erp/model/InventoryActive.java
package com.app.erp.model;
import java.io.Serializable;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class InventoryActive extends Inventory implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1057367550230251747L;
private Date stockDate;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date roastDate;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date expDate;
private String comment;
public InventoryActive(){
}
public InventoryActive(Inventory inventory){
super(inventory);
}
public java.sql.Date getStockDate(){
if(stockDate == null){
return null;
} else {
return new java.sql.Date(stockDate.getTime());
}
}
public void setStockDate(Date stockDate){
this.stockDate = stockDate;
}
public java.sql.Date getRoastDate(){
if(roastDate == null){
return null;
} else {
return new java.sql.Date(roastDate.getTime());
}
}
public void setRoastDate(Date roastDate){
this.roastDate = roastDate;
}
public java.sql.Date getExpDate(){
if(expDate == null){
return null;
} else {
return new java.sql.Date(expDate.getTime());
}
}
public void setExpDate(Date expDate){
this.expDate = expDate;
}
public String getComment(){
return comment;
}
public void setComment(String comment){
this.comment = comment;
}
}
<file_sep>/src/main/java/com/app/erp/mapper/InventoryMapper.java
package com.app.erp.mapper;
import java.util.List;
import com.app.erp.model.Inventory;
import com.app.erp.model.InventoryActive;
import com.app.erp.model.InventoryHist;
import com.app.erp.model.InventoryPending;
import com.app.erp.model.MonthYear;
public interface InventoryMapper {
List<InventoryActive> loadInventoryActive(String codeIngredient);
List<InventoryActive> loadInventoryActive();
void updateInventoryActive(InventoryActive inventoryActive);
List<InventoryPending> loadInventoryPending();
List<InventoryPending> loadInventoryPendingList(long[] itemNumber);
List<InventoryHist> loadInventoryHist(MonthYear monthYear);
void saveInventoryPending(Inventory inventory);
void deleteInventoryPending(long[] itemNumber);
void deleteInventory(long itemNumber);
void saveToInventory(List<InventoryActive> arrInventoryActive);
void addPendingHist(List<InventoryPending> arrInventoryPending);
//void updateInventory(long itemNumber, int quantity);
}
<file_sep>/src/main/java/com/app/erp/service/InventoryService.java
package com.app.erp.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.springframework.transaction.annotation.Transactional;
import com.app.erp.mapper.InventoryMapper;
import com.app.erp.mapper.UnitMapper;
import com.app.erp.model.InventoryActive;
import com.app.erp.model.InventoryActiveList;
import com.app.erp.model.InventoryPending;
import com.app.erp.model.InventoryPendingList;
import com.app.erp.model.UnitAndPostUnit;
public class InventoryService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 965620516500933416L;
@Inject
private transient InventoryMapper inventoryMapper;
@Inject
private transient UnitMapper unitMapper;
public InventoryService(){
}
public InventoryPendingList loadInventoryPending(){
return new InventoryPendingList(inventoryMapper.loadInventoryPending());
}
public InventoryActiveList forDelivery(long[] itemNumber){
List<InventoryPending> inventoryPendingList = inventoryMapper.loadInventoryPendingList(itemNumber);
List<InventoryActive> arrInventoryActive = new ArrayList<InventoryActive>();
for(InventoryPending inventoryPending: inventoryPendingList){
arrInventoryActive.add(new InventoryActive(inventoryPending));
}
return new InventoryActiveList(arrInventoryActive);
}
@Transactional
public void delivered(InventoryActiveList inventoryActiveList, long[] itemNumber){
List<InventoryActive> arrInventoryActive = inventoryActiveList.getInventoryList();
List<InventoryPending> arrInventoryPending = inventoryMapper.loadInventoryPendingList(itemNumber);
for(int i = 0; i < arrInventoryPending.size(); i++){
InventoryActive inventoryActive = arrInventoryActive.get(i);
inventoryActive.setInventory(arrInventoryPending.get(i));
UnitAndPostUnit unitAndPostUnit = unitMapper.loadUnitAndPostUnit(inventoryActive.getUnitCode());
String codePostUnit = unitAndPostUnit.getCodePostUnit();
if(!codePostUnit.isEmpty()){
inventoryActive.setUnitCode(codePostUnit);
int quantity = (int) (inventoryActive.getQuantity() * unitAndPostUnit.getConversionFactor());
inventoryActive.setQuantity(quantity);
double unitPrice = inventoryActive.getUnitPrice() / unitAndPostUnit.getConversionFactor();
inventoryActive.setUnitPrice(unitPrice);
}
}
inventoryMapper.addPendingHist(arrInventoryPending);
inventoryMapper.saveToInventory(arrInventoryActive);
inventoryMapper.deleteInventoryPending(itemNumber);
}
public InventoryActiveList loadInventory(){
return new InventoryActiveList(inventoryMapper.loadInventoryActive());
}
public InventoryActiveList loadInventory(String code){
return new InventoryActiveList(inventoryMapper.loadInventoryActive(code));
}
@Transactional
public void consolidateInventory(InventoryActiveList inventoryActiveList){
for(InventoryActive inventoryActive: inventoryActiveList.getInventoryList()){
if(inventoryActive.getQuantity() == 0){
inventoryMapper.deleteInventory(inventoryActive.getItemNumber());
}
inventoryMapper.updateInventoryActive(inventoryActive);
}
}
}
<file_sep>/src/main/java/com/app/erp/mapper/TranMapper.java
package com.app.erp.mapper;
import java.util.List;
import com.app.erp.model.Tran;
import com.app.erp.model.TranOrder;
public interface TranMapper {
List<Tran> loadTransaction(String startDate, String endDate);
List<TranOrder> loadTransactionOrder(long code);
}
<file_sep>/src/main/java/com/app/erp/util/InventoryHelper.java
package com.app.erp.util;
import java.util.ArrayList;
import com.app.erp.model.InventoryActive;
public class InventoryHelper {
public static ArrayList<InventoryActive> convertUnitToPostUnit(ArrayList<InventoryActive> arrInventryActive){
return arrInventryActive;
}
}
<file_sep>/src/main/java/com/app/erp/controller/InventoryController.java
package com.app.erp.controller;
import java.sql.Date;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.app.erp.mapper.IngredientMapper;
import com.app.erp.mapper.InventoryMapper;
import com.app.erp.mapper.UnitMapper;
import com.app.erp.model.MonthYear;
import com.app.erp.model.IngredientCode;
import com.app.erp.model.Inventory;
import com.app.erp.model.InventoryActive;
import com.app.erp.model.InventoryActiveList;
import com.app.erp.model.InventoryHist;
import com.app.erp.model.InventoryPending;
import com.app.erp.model.Unit;
import com.app.erp.model.UnitAndPostUnit;
import com.app.erp.util.DateUtilities;
import com.app.erp.validator.InventoryValidator;
@Controller
@RequestMapping("/inventory")
@Transactional(propagation=Propagation.SUPPORTS, isolation=Isolation.READ_UNCOMMITTED)
public class InventoryController {
@Inject
private InventoryMapper inventoryMapper;
@Inject
private InventoryValidator inventoryValidator;
@Inject
private IngredientMapper ingredientMapper;
@Inject
private UnitMapper unitMapper;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(){
return "inventory";
}
@RequestMapping(value = "/active", method = RequestMethod.GET)
@Transactional(readOnly=true)
public ModelAndView getInventory() {
List<InventoryActive> arrInventoryActive;
arrInventoryActive = inventoryMapper.loadInventoryActive();
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("inventory", arrInventoryActive);
myModel.put("tabletype", "active");
return new ModelAndView("inventory", "model", myModel);
}
@RequestMapping(value = "/pending", method = RequestMethod.GET)
@Transactional(readOnly=true)
public ModelAndView getInventoryPending() {
List<InventoryPending> arrInventory;
arrInventory = inventoryMapper.loadInventoryPending();
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("inventory", arrInventory);
myModel.put("tabletype", "pending");
return new ModelAndView("inventory", "model", myModel);
}
@RequestMapping(value = "/hist", method = RequestMethod.GET)
@Transactional(readOnly=true)
public ModelAndView getInventoryHist(
@ModelAttribute("dateYear") MonthYear monthYear){
List<InventoryHist> arrInventoryHist;
if(monthYear.getMonth() == 0 && monthYear.getYear() == 0){
Calendar cal = Calendar.getInstance();
monthYear.setMonth(cal.get(Calendar.MONTH)+1);
monthYear.setYear(cal.get(Calendar.YEAR));
}
arrInventoryHist = inventoryMapper.loadInventoryHist(monthYear);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("tabletype", "history");
myModel.put("inventory", arrInventoryHist);
myModel.put("monthYear", monthYear);
myModel.put("month", DateUtilities.getMonthMap());
myModel.put("year", DateUtilities.getYear());
return new ModelAndView("inventory", myModel);
}
@RequestMapping(value = "/pending/add", method = RequestMethod.GET)
public ModelAndView addInventoryPending(Map<String, Object> myModel, Inventory inventory){
return addPendingInventoryWithValidation(myModel, inventory);
}
@RequestMapping(value = "/pending/add", method = RequestMethod.POST)
public ModelAndView submitInventoryPending(
@ModelAttribute("inventory") @Valid Inventory inventory,
BindingResult result,
SessionStatus status){
if(result.hasErrors()){
return addPendingInventoryWithValidation(new HashMap<String, Object>(), inventory);
} else {
inventory.setTotalPrice(inventory.getUnitPrice()*inventory.getQuantity());
inventoryMapper.saveInventoryPending(inventory);
return new ModelAndView("redirect:/inventory/pending");
}
}
private ModelAndView addPendingInventoryWithValidation(
Map<String, Object> myModel, Inventory inventory){
List<IngredientCode> arrIngredientCode;
List<Unit> arrUnit;
arrIngredientCode = ingredientMapper.loadIngredientCode();
arrUnit = unitMapper.loadUnit();
myModel.put("inventory", inventory);
myModel.put("ingredientCode", arrIngredientCode);
myModel.put("unit", arrUnit);
myModel.put("editType", "inventory");
return new ModelAndView("edit", myModel);
}
@RequestMapping(value = "/pending/delete", method = RequestMethod.POST)
public String deleteInventoryPending(
@RequestParam("itemNumber") long[] itemNumber
){
inventoryMapper.deleteInventoryPending(itemNumber);
return "redirect:/inventory/pending";
}
@RequestMapping(value ="/pending/delivered", method = RequestMethod.GET)
public ModelAndView moveToInventory(
@RequestParam("itemNumber") long[] itemNumber,
Map<String, Object> myModel
){
List<InventoryPending> arrInventory = inventoryMapper.loadInventoryPendingList(itemNumber);
List<InventoryActive> arrInventoryActive = new ArrayList<InventoryActive>();
for(int i = 0; i < arrInventory.size(); i++){
arrInventoryActive.add(new InventoryActive(arrInventory.get(i)));
}
myModel.put("tabletype", "deliver");
myModel.put("inventory", new InventoryActiveList(arrInventoryActive));
//myModel.put("inventory", arrInventoryActive);
//ArrayList<InventoryPending> arrInventoryPedning = inventoryMapper.loadInventoryPending(itemNumber);
//inventoryMapper.addPendingHist(arrInventoryPending);
//inventoryMapper.saveToInventory(inventory);
//inventoryMapper.deleteInventoryPending(itemNumber);
return new ModelAndView("inventory", myModel);
}
@RequestMapping(value ="/pending/delivered", method = RequestMethod.POST)
@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.READ_COMMITTED, rollbackFor=Exception.class)
public String submitMoveToInventory(
@ModelAttribute("inventory") InventoryActiveList inventoryActiveList,
@RequestParam("itemNumber") long[] itemNumber
){
List<InventoryActive> arrInventoryActive = (ArrayList<InventoryActive>) inventoryActiveList.getInventoryList();
List<InventoryPending> arrInventoryPending = inventoryMapper.loadInventoryPendingList(itemNumber);
for(int i = 0; i < arrInventoryPending.size(); i++){
InventoryActive inventoryActive = arrInventoryActive.get(i);
inventoryActive.setInventory(arrInventoryPending.get(i));
UnitAndPostUnit unitAndPostUnit = unitMapper.loadUnitAndPostUnit(inventoryActive.getUnitCode());
inventoryActive.setUnitCode(unitAndPostUnit.getCodePostUnit());
int quantity = (int) (inventoryActive.getQuantity() * unitAndPostUnit.getConversionFactor());
inventoryActive.setQuantity(quantity);
}
inventoryMapper.addPendingHist(arrInventoryPending);
inventoryMapper.saveToInventory(arrInventoryActive);
inventoryMapper.deleteInventoryPending(itemNumber);
return "redirect:/inventory/active";
}
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
<file_sep>/src/main/java/com/app/erp/model/Recipe.java
package com.app.erp.model;
import java.io.Serializable;
import java.util.List;
public class Recipe implements Serializable{
/**
*
*/
private static final long serialVersionUID = 9199123488689936218L;
private List<Ingredient> ingredientList;
public Recipe(){
}
public Recipe(List<Ingredient> ingredientList){
this.ingredientList = ingredientList;
}
public void addIngredient(Ingredient ingredient){
ingredientList.add(ingredient);
}
public void removeIngredient(Ingredient ingredient){
ingredientList.remove(ingredient);
}
public Ingredient removeIngredient(int index){
return ingredientList.remove(index);
}
public Ingredient getIngredient(int index){
return ingredientList.get(index);
}
public int size(){
return ingredientList.size();
}
public void replace(int index, Ingredient ingredient){
ingredientList.set(index, ingredient);
}
public List<Ingredient> getIngredientList(){
return ingredientList;
}
}
<file_sep>/src/main/java/com/app/erp/controller/ParametersController.java
package com.app.erp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/system/parameters")
public class ParametersController {
@RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView viewParameters(){
return new ModelAndView("parameters");
}
}
<file_sep>/src/main/java/com/app/erp/exception/PatternException.java
package com.app.erp.exception;
public class PatternException extends Exception {
/**
*
*/
private static final long serialVersionUID = -4100657227250500002L;
public PatternException(){
System.out.println("Input does not comply with the pattern required");
}
}
<file_sep>/src/main/java/com/app/erp/controller/AjaxController.java
package com.app.erp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/ajax")
public class AjaxController {
}
<file_sep>/src/main/java/com/app/erp/util/ErrorMessageUtil.java
package com.app.erp.util;
public class ErrorMessageUtil {
public static final String DEL_UNIT_ERROR =
"Selected unit for deletion is in use; Cannot delete";
public static final String DEL_MI_ERROR =
"Selected menu item for deletion is in use; Cannot delete";
public static final String DEL_ING_ERROR =
"Selected ingredient Code for deletion is in use; Cannot delete";
public static final String DEL_ING_TYPE_ERROR =
"Selected ingredient type for deletion is in use; Cannot delete";
}
<file_sep>/src/main/resources/messages.properties
typeMismatch.inventory.quantity = Quantity should be a number
Min.inventory.quantity = Quantity must not be 0
typeMismatch.inventory.unitPrice = Price must be a number
Size.unitAndPostUnit.codeUnit = Unit code should be composed of only 1 to 10 characters
Size.unitAndPostUnit.name = Name should be composed of only 1 to 45 characters
Min.unitAndPostUnit.conversionFactor = Conversion Factor should be positive
Size.menuItem.name = Menu item name should be composed of only 1 to 25 characters
Size.menuItem.description = Menu item description should be composed of only 1 to 100 characters
Min.menuItem.price = Price should be positive
Size.menuItemList.menuItemList.name = Menu item name should be composed of only 1 to 10 characters
Size.menuItemList.menuItemList.description = Menu item description should be composed of only 1 to 100 characters
Min.menuItemList.menuItemList.price = Menu item price should be positive
Size.menuItemType.code = Menu item type code should be composed of only 1 to 10 characters
Size.menuItemType.name = Menu item type name should be composed of only 1 to 45 characters
Size.discount.codeDiscount = Discount code should be composed of only 1 to 10 characters
Size.discount.name = Discount name should be composed of only 1 to 45 characters
Size.ingredientCode.code = Ingredient code should be composed of only 1 to 10 characters
Size.ingredientCode.brand = Ingredient brand should be composed of only 1 to 45 characters
Size.ingredientCode.name = Ingredient name should be composed of only 1 to 45 characters
Size.ingredientType.code = Ingredient type code should be composed of only 1 to 10 characters
Size.ingredientType.name = Ingredient type name should be composed of only 1 to 45 characters
<file_sep>/src/main/java/com/app/erp/controller/MenuItemController.java
package com.app.erp.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.app.erp.mapper.MenuItemMapper;
import com.app.erp.model.MenuItem;
import com.app.erp.model.MenuItemList;
import com.app.erp.model.MenuItemType;
import com.app.erp.util.ErrorMessageUtil;
@Controller
@RequestMapping("/maintenance")
public class MenuItemController {
@Inject
private MenuItemMapper menuItemMapper;
@RequestMapping(value = "/mi", method = RequestMethod.GET)
public ModelAndView viewMenuItem(Map<String, Object> myModel){
MenuItemList menuItemList = new MenuItemList(menuItemMapper.loadMenuItem());
List<MenuItemType> arrMenuItemType = menuItemMapper.loadMenuItemType();
myModel.put("tabletype", "menuItem");
myModel.put("menuItem", menuItemList);
myModel.put("mitype", arrMenuItemType);
return new ModelAndView("maintenance", myModel);
}
@RequestMapping(value = "/mi/edit", method=RequestMethod.GET)
public ModelAndView editMenuItem(
@RequestParam("code") String[] code,
Map<String, Object> myModel,
MenuItemList menuItemList
){
menuItemList.setMenuItemList(menuItemMapper.loadMenuItem(code));
return editMenuItemWithValidation(myModel, menuItemList);
}
@RequestMapping(value= "/mi/edit", method=RequestMethod.POST)
public ModelAndView updateMenuItem(
@ModelAttribute("menuItemList") @Valid MenuItemList menuItemList,
BindingResult result
){
if(result.hasErrors()){
return editMenuItemWithValidation(new HashMap<String, Object>(), menuItemList);
} else {
for(MenuItem mi:menuItemList.getMenuItemList()){
menuItemMapper.updateMenuItem(mi);
}
return new ModelAndView("redirect:/maintenance/mi");
}
}
private ModelAndView editMenuItemWithValidation(Map<String, Object> myModel, MenuItemList menuItemList){
List<MenuItemType> arrMenuItemType = menuItemMapper.loadMenuItemType();
myModel.put("menuItemList", menuItemList);
myModel.put("menuItemType", arrMenuItemType);
myModel.put("tabletype", "menuItemEdit");
return new ModelAndView("maintenance", myModel);
}
@RequestMapping(value = "/mi/type", method=RequestMethod.GET)
public ModelAndView viewMenuItemType(Map<String, Object> myModel){
return viewMenuItemTypeWithValidation(myModel);
}
@RequestMapping(value = "/mi/type/add", method=RequestMethod.GET)
public ModelAndView addMenuItemType(Map<String, Object> myModel,
MenuItemType menuItemType){
return addMenuItemTypeWithValidation(myModel, menuItemType);
}
@RequestMapping(value = "/mi/type/add", method=RequestMethod.POST)
public ModelAndView saveMenuItemType(
@ModelAttribute("menuItemType") @Valid MenuItemType menuItemType,
BindingResult result,
SessionStatus status
){
if(result.hasErrors()){
return addMenuItemTypeWithValidation(new HashMap<String, Object>(), menuItemType);
} else {
menuItemMapper.saveMenuItemType(menuItemType);
return new ModelAndView("redirect:/maintenance/mi/type");
}
}
private ModelAndView addMenuItemTypeWithValidation(
Map<String, Object> myModel, MenuItemType menuItemType){
myModel.put("editType", "miType");
myModel.put("menuItemType", menuItemType);
return new ModelAndView("edit", myModel);
}
@RequestMapping(value = "/mi/type/delete", method=RequestMethod.POST)
public ModelAndView deleteMenuItemType(
@RequestParam("code") String[] code
){
for(int i=0; i < code.length; i++){
if(menuItemMapper.allowDeletion(code[i]) > 0){
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("errorMsg", ErrorMessageUtil.DEL_MI_ERROR);
return viewMenuItemTypeWithValidation(myModel);
}
}
menuItemMapper.deleteMenuItemType(code);
return new ModelAndView("redirect:/maintenance/mi/type");
}
private ModelAndView viewMenuItemTypeWithValidation(Map<String, Object> myModel ){
List<MenuItemType> arrMenuItemType = menuItemMapper.loadMenuItemType();
myModel.put("object", arrMenuItemType);
myModel.put("tabletype", "mitype");
return new ModelAndView("maintenance", "model", myModel);
}
}
<file_sep>/src/main/java/com/app/erp/controller/TranController.java
package com.app.erp.controller;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.app.erp.mapper.TranMapper;
import com.app.erp.model.OrderList;
import com.app.erp.model.Tran;
@Controller
@RequestMapping("/accounting/transaction")
public class TranController {
@Inject
TranMapper tranMapper;
@RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView viewTran(Map<String, Object> myModel){
/**
List<Tran> tranList = tranMapper.loadTransaction(Date.valueOf("2013-05-09"));
for(Tran tran:tranList){
OrderList orderList = new OrderList(tranMapper.loadTransactionOrder(tran.getCodeTransaction()));
tran.setOrderList(orderList);
}
myModel.put("tabletype", "transaction");
myModel.put("tran", tranList);
return new ModelAndView("accounting", myModel);
**/
return null;
}
}
<file_sep>/src/main/java/com/app/erp/model/UnitAndPostUnit.java
package com.app.erp.model;
import javax.validation.constraints.Min;
public class UnitAndPostUnit extends Unit {
/**
*
*/
private static final long serialVersionUID = -4691842932753831766L;
private String codePostUnit;
private String namePostUnit;
@Min(0)
private double conversionFactor;
public void setCodePostUnit(String codePostUnit){
this.codePostUnit = codePostUnit;
}
public String getCodePostUnit(){
return codePostUnit;
}
public void setNamePostUnit(String namePostUnit){
this.namePostUnit = namePostUnit;
}
public String getNamePostUnit(){
return namePostUnit;
}
public void setConversionFactor(double conversionFactor){
this.conversionFactor = conversionFactor;
}
public double getConversionFactor(){
return conversionFactor;
}
}
<file_sep>/src/main/java/com/app/erp/service/TranService.java
package com.app.erp.service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.app.erp.mapper.TranMapper;
import com.app.erp.model.OrderList;
import com.app.erp.model.Tran;
import com.app.erp.model.TranList;
import com.app.erp.model.TranOrder;
public class TranService implements Serializable {
/**
*
*/
private static final long serialVersionUID = 455224890463372687L;
@Inject
private transient TranMapper tranMapper;
public TranList loadTran(String startDate, String endDate){
List<Tran> tranList = tranMapper.loadTransaction(startDate, endDate);
for(Tran tran:tranList){
OrderList orderList = new OrderList(tranMapper.loadTransactionOrder(tran.getCodeTransaction()));
tran.setOrderList(orderList);
}
return new TranList(tranList);
}
public void printTran(TranList tranList){
String fileName = "D:\\Magnum Opus\\test.xls";
Workbook wb = new HSSFWorkbook();
int rowCounter = 0;
int colLength;
String[] col = {"Time", "Transaction Number", "Dine in", "Item Ordered", "Price", "Total Amount"};
Sheet sheet = wb.createSheet("test");
Row row = sheet.createRow(rowCounter++);
colLength = col.length;
for(int i = 0; i < col.length; i++){
Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING);
cell.setCellValue(col[i]);
}
for(Tran tran:tranList.getTranList()){
row = sheet.createRow(rowCounter++);
Cell cell = row.createCell(0, Cell.CELL_TYPE_STRING);
cell.setCellValue(tran.getTimeStamp().toString());
CellStyle cs = cell.getCellStyle();
Cell cell1 = row.createCell(1, Cell.CELL_TYPE_NUMERIC);
cell1.setCellValue(tran.getCodeTransaction());
Cell cell2 = row.createCell(2, Cell.CELL_TYPE_STRING);
if(tran.getIndDineIn()){
cell2.setCellValue("Yes");
} else {
cell2.setCellValue("No");
}
int rowOrder = rowCounter;
Row innerRow = row;
boolean status = false;
for(TranOrder tranOrder:tran.getOrderList().getTranOrderList()){
if(status){
innerRow = sheet.createRow(rowOrder++);
}
Cell cell3 = innerRow.createCell(3, Cell.CELL_TYPE_STRING);
cell3.setCellValue(tranOrder.getMenuItemName());
Cell cell4 = innerRow.createCell(4, Cell.CELL_TYPE_NUMERIC);
cell4.setCellValue(tranOrder.getMenuItemPrice());
status = true;
}
Cell cell5 = row.createCell(5, Cell.CELL_TYPE_NUMERIC);
cell5.setCellValue(tran.getTotalAmount());
rowCounter = rowOrder;
}
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName);
wb.write(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 32a05608b1824837cbb3de00467a83e271d85d2c | [
"Java",
"INI"
] | 23 | Java | heinrich10/pos | b17200b36f879a7d987065523f2263dbb511267b | e3155a3853a56a96376a81401af63f42d36a874f |
refs/heads/master | <repo_name>tyler-patton44/cSharpBankAccount<file_sep>/Models/transactions.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace testBank.Models
{
public class transactions
{
[Key]
public int transactionId{get;set;}
[Required(ErrorMessage = "This field is required")]
[Display(Name = "Amount:")]
[Range(0, float.PositiveInfinity, ErrorMessage = "Must be greater than 0")]
public decimal amount{get;set;}
public DateTime createdAt{get;set;}
public int userId{get;set;}
public users users{get;set;}
public transactions(){
createdAt = DateTime.Now;
}
}
} | 9f04c70f4e8e1a299403429ef9c84d7542c70732 | [
"C#"
] | 1 | C# | tyler-patton44/cSharpBankAccount | 54e391618c7bae0c9b0f51ad21326fe8bde50110 | e11e00f0380beb7501c8c9aa5080f1496bab8328 |
refs/heads/master | <repo_name>pepabo/takosan<file_sep>/README.md
# Takosan
[](http://badge.fury.io/rb/takosan)
[](https://travis-ci.org/pepabo/takosan)
Ruby wrapper of [Takosan](https://github.com/kentaro/takosan)
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'takosan'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install takosan
## Usage
```ruby
Takosan.url = "http://irc.example.com:4649"
Takosan.channel = "#example"
Takosan.privmsg 'awesome comment'
Takosan.privmsg 'awesome comment and title with link', color: '#000', title: 'black title', title_link: 'http://example.com'
```
You can change Takosan's icon and name like the following:
```ruby
Takosan.icon = ":angel:"
Takosan.name = "ikasan"
```
## Contributing
1. Fork it ( https://github.com/pepabo/takosan/fork )
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. Create a new Pull Request
<file_sep>/test/test_helper.rb
require 'test/unit'
require 'mocha/setup'
require 'logger'
require 'tempfile'
module Rails
module_function
def logger
@@_logger ||= Logger.new(STDOUT)
end
end
<file_sep>/lib/takosan.rb
# -*- coding: utf-8 -*-
require 'net/http'
require 'uri'
require 'pathname'
require 'active_support/all'
module Takosan
mattr_accessor :url, :channel, :name, :icon
module_function
def privmsg(message, **options)
request('/privmsg', options.merge({ 'channel' => @@channel, 'message' => message, 'name' => @@name, 'icon' => @@icon }))
end
def uri_for(path = nil)
uri = URI.parse("#{@@url}/#{path}")
uri.path = Pathname.new(uri.path).cleanpath.to_s
uri
end
def request(path, params)
begin
uri = uri_for(path)
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = http.read_timeout = 10
req = Net::HTTP::Post.new(uri.path)
req.form_data = params
http.request(req)
rescue StandardError, TimeoutError => e
logger.warn("#{e.class} #{e.message}")
end
end
def logger
@@_logger ||=
if defined?(Rails.logger)
Rails.logger
else
Logger.new($stderr)
end
end
end
<file_sep>/test/takosan_test.rb
# -*- coding: utf-8 -*-
require 'test_helper'
require_relative '../lib/takosan'
class TakosanTest < Test::Unit::TestCase
def setup
Takosan.url = "http://irc.example.com:4649"
Takosan.channel = "#example"
end
def test_privmsg
http = mock('http')
http.stub_everything
http.expects(:request)
Net::HTTP.expects(:new).with('irc.example.com', 4649).returns(http)
req = mock('req')
req.stub_everything
req.expects(:form_data=).with do |params|
(params['channel'] == '#example') && (params['message'] == 'foo bar buzz')
end
Net::HTTP::Post.expects(:new).with('/privmsg').returns(req)
Takosan.privmsg('foo bar buzz')
end
def test_privmsg_with_message_attachments
http = mock('http')
http.stub_everything
http.expects(:request)
Net::HTTP.expects(:new).with('irc.example.com', 4649).returns(http)
req = mock('req')
req.stub_everything
req.expects(:form_data=).with do |params|
(params['channel'] == '#example') && (params['message'] == 'foo bar buzz')
end
Net::HTTP::Post.expects(:new).with('/privmsg').returns(req)
Takosan.privmsg('foo bar buzz', title: 'black', color: '#000')
end
def test_rescue_timeout_error
http = stub('http')
http.stub_everything
http.stubs(:request).raises(Timeout::Error, 'timeout error!')
Net::HTTP.expects(:new).with('irc.example.com', 4649).returns(http)
req = stub('req')
req.stub_everything
Net::HTTP::Post.expects(:new).with('/privmsg').returns(req)
assert_nothing_raised do
Takosan.privmsg('foo bar buzz')
end
end
def test_rescue_socket_error
http = stub('http')
http.stub_everything
http.stubs(:request).raises(SocketError, 'connection error!')
Net::HTTP.expects(:new).with('irc.example.com', 4649).returns(http)
req = stub('req')
req.stub_everything
Net::HTTP::Post.expects(:new).with('/privmsg').returns(req)
assert_nothing_raised do
Takosan.privmsg('foo bar buzz')
end
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
# Specify your gem's dependencies in takosan.gemspec
gemspec
if Gem::Version.create(RUBY_VERSION) < Gem::Version.create("2.2.2")
gem "activesupport", ">= 4.0.0", "< 5.0.0"
end
| e3bae54407c7a07da6d28b9c925c661154a0b51d | [
"Markdown",
"Ruby"
] | 5 | Markdown | pepabo/takosan | 597b41238c55b1a51d01bb330e9de49852c7c131 | f405bd144e64dbc4041c82f4e059c3e70612f38a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.