branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>nnduyquang/thinhphat<file_sep>/local/app/Repositories/Menu/MenuRepositoryInterface.php
<?php
namespace App\Repositories\Menu;
interface MenuRepositoryInterface
{
public function getAllMenu();
public function showCategoryDropDown($dd_categories, $parent_id = 0, &$newArray);
}<file_sep>/local/app/Http/ViewComposers/ConfigComposer.php
<?php
namespace App\Http\ViewComposers;
use App\Repositories\Frontend\FrontendRepository;
use Illuminate\View\View;
class ConfigComposer
{
public $dataConfig=[];
/**
* Create a movie composer.
*
* @return void
*/
public function __construct(FrontendRepository $home)
{
$this->dataConfig = $home->getDataConfig();
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('dataConfig', $this->dataConfig);
}
}<file_sep>/local/app/Http/Controllers/feCategoryController.php
<?php
namespace App\Http\Controllers;
use App\CategoryItem;
use App\Post;
use App\Product;
use Illuminate\Http\Request;
class feCategoryController extends Controller
{
public function getDetailCategory($pathCategory){
$category=CategoryItem::where('path','=',$pathCategory)->first();
$sub_Category=CategoryItem::where('parent_id','=',$category->id)->get();
$list_product=[];
self::getAllProductByCategory($category, $list_product);
return view('frontend.category.category', compact('category','sub_Category','list_product'));
}
public function getAllProductByCategory($category, &$list_product)
{
$list = Product::where('category_product_id', '=', $category->id)->orderBy('created_at')->get();
foreach ($list as $key2 => $data2) {
$data2->path='/san-pham/'.$category->path.'/'.$data2->path;
$data2->price=number_format($data2->price, 0, ',', '.');
$data2->final_price=number_format($data2->final_price, 0, ',', '.');
array_push($list_product, $data2);
}
$sub = CategoryItem::where('parent_id', '=', $category->id)->get();
foreach ($sub as $key => $data) {
self::getAllProductByCategory($data, $list_product);
}
}
public function showCategoryDropDown($dd_categories, $parent_id = 0, &$newArray)
{
foreach ($dd_categories as $key => $data) {
if ($data->parent_id == $parent_id) {
array_push($newArray, $data);
$dd_categories->forget($key);
self::showCategoryDropDown($dd_categories, $data->id, $newArray);
}
}
}
}
<file_sep>/local/resources/assets/js/scripts.js
var plugins = {
menu: $('.sidebar'),
slider: $('#slider'),
owlCarouselHPListProduct: $('.h-p-owl'),
owlCarouselPDOrderProduct:$('.p-d-owl'),
fixMenuOnScroll: $('#menu-list')
};
$(document).ready(function () {
function runOwlCarouselHPListProduct() {
plugins.owlCarouselHPListProduct.owlCarousel({
dots: false,
nav: true,
autoplay: true,
navContainer: '.nav-arrow',
loop: true,
navText: ["<i class='fas fa-angle-left'></i>", "<i class='fas fa-angle-right'></i>"],
responsive: {
0: {
items: 1
},
600: {
items: 4
},
1000: {
items:7
}
}
});
}
function runOwlCarouselPDOrderProduct(){
plugins.owlCarouselPDOrderProduct.owlCarousel({
dots: false,
nav: true,
autoplay: true,
navContainer: '.nav-arrow',
loop: true,
navText: ["<i class='fas fa-angle-left'></i>", "<i class='fas fa-angle-right'></i>"],
responsive: {
0: {
items: 1
},
600: {
items: 4
},
1000: {
items: 4
}
}
});
}
function sidebar() {
var trigger = $('#trigger,#close');
trigger.on('click', function () {
$(this).toggleClass('active');
plugins.menu.toggleClass('closed');
$('#blurrMe').toggleClass('blurred')
})
$('#wrap-container').on('click', function () {
if ($('#blurrMe').hasClass('blurred')) {
$('#blurrMe').toggleClass('blurred')
plugins.menu.toggleClass('closed');
}
})
}
sidebar();
function runSlider() {
plugins.slider.nivoSlider({
effect: 'fade',
animSpeed: 500,
pauseTime: 3000,
pauseOnHover: true,
controlNav: false,
});
}
function runFixMenuOnScroll(){
$(window).on("scroll", function (e) {
if ($(this).scrollTop() > 64) {
plugins.fixMenuOnScroll.addClass('fixed-top');
}
else{
plugins.fixMenuOnScroll.removeClass('fixed-top');
}
});
}
if (plugins.slider.length) {
runSlider();
}
if (plugins.owlCarouselHPListProduct.length) {
runOwlCarouselHPListProduct();
}
if(plugins.owlCarouselPDOrderProduct.length){
runOwlCarouselPDOrderProduct();
}
if(plugins.fixMenuOnScroll.length){
runFixMenuOnScroll()
}
});<file_sep>/local/app/Repositories/Menu/MenuRepository.php
<?php
namespace App\Repositories\Menu;
use App\Menu;
use App\CategoryItem;
use App\Post;
use App\Repositories\EloquentRepository;
class MenuRepository extends EloquentRepository implements MenuRepositoryInterface
{
public function getModel()
{
return Menu::class;
}
public function getAllMenu()
{
$list_sidebar = CategoryItem::select('id', 'name','image', 'level', 'parent_id','path')->where(function($query){
$query->where('level', '=', 0)->orWhere('level', '=', 1);
})->where('isActive','=',1)->orderBy('order')->get();
$menu_sidebar = [];
self::showCategoryDropDown($list_sidebar, 0, $menu_sidebar);
$menu_horizon= CategoryItem::where('level', '=', 0)->orderBy('order')->get();
$catalogues=Post::where('post_type','=',2)->where('isActive','=',1)->get();
$data['menu_sidebar']=$menu_sidebar;
$data['menu_horizon']=$menu_horizon;
$data['catalogues']=$catalogues;
return $data;
}
public function showCategoryDropDown($dd_categories, $parent_id = 0, &$newArray)
{
foreach ($dd_categories as $key => $data) {
if ($data->parent_id == $parent_id) {
array_push($newArray, $data);
$dd_categories->forget($key);
self::showCategoryDropDown($dd_categories, $data->id, $newArray);
}
}
}
}<file_sep>/local/app/Http/Controllers/HomepageController.php
<?php
namespace App\Http\Controllers;
use App\CategoryItem;
use App\Post;
use App\Product;
use Illuminate\Http\Request;
class HomepageController extends Controller
{
public function showHomepage()
{
$list_sidebar2 = CategoryItem::where('level', '=', 0)->where('isActive','=',1)->orderBy('order')->get();
$list_product = [];
$final_array = [];
foreach ($list_sidebar2 as $key => $data) {
self::getAllProductByCategory($data, $list_product);
$list_subMenu=CategoryItem::where('parent_id','=',$data->id)->get();
array_push($final_array, array(["category" => $data, "list_product" => collect($list_product)->sortByDESC('created_at')->take(8),"list_subMenu"=>$list_subMenu]));
$list_product = [];
}
$bestSaleProduct=Product::where('is_best_sale',1)->where('isActive',ACTIVE)->orderBy('updated_at','DESC')->take(8)->get();
foreach ($bestSaleProduct as $key=>$data){
$data->price=chuyen_thap_phan($data->price);
$data->final_price=chuyen_thap_phan($data->final_price);
}
return view('frontend.homepage.index', compact('final_array','bestSaleProduct'));
}
public function showCategoryDropDown($dd_categories, $parent_id = 0, &$newArray)
{
foreach ($dd_categories as $key => $data) {
if ($data->parent_id == $parent_id) {
array_push($newArray, $data);
$dd_categories->forget($key);
self::showCategoryDropDown($dd_categories, $data->id, $newArray);
}
}
}
public function getAllProductByCategory($category, &$list_product)
{
$list = Product::where('category_product_id', '=', $category->id)->orderBy('created_at')->get();
foreach ($list as $key2 => $data2) {
$data2->path='/san-pham/'.$category->path.'/'.$data2->path;
$data2->price=number_format($data2->price, 0, ',', '.');
$data2->final_price=number_format($data2->final_price, 0, ',', '.');
array_push($list_product, $data2);
}
$sub = CategoryItem::where('parent_id', '=', $category->id)->get();
foreach ($sub as $key => $data) {
self::getAllProductByCategory($data, $list_product);
}
}
public function getFrontendContentCategory()
{
$list_sidebar2 = CategoryItem::where('level', '=', 0)->where('isActive','=',1)->orderBy('order')->get();
$final_array = [];
foreach ($list_sidebar2 as $key => $data) {
$list_subMenu=CategoryItem::where('parent_id','=',$data->id)->get();
array_push($final_array, array(["category" => $data,"list_subMenu"=>$list_subMenu]));
}
return view('frontend.common.menu.m-category', compact('final_array'));
}
public function getDetailCatalogue($pathCatalogue){
$catalogue=Post::where('post_type','=',2)->where('path','=',$pathCatalogue)->first();
return view('frontend.catalogue.catalogue', compact('catalogue'));
}
public function getPage($type)
{
if($type==2){
$configs = Config::whereIn('name', ['config-introduce'])->first();
$data['content']=$configs->content;
}
$data['type'] = $type;
return view('frontend.page.index', compact('data'));
}
}
<file_sep>/thinhphat.sql
-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Máy chủ: 127.0.0.1
-- Thời gian đã tạo: Th6 29, 2018 lúc 10:08 AM
-- Phiên bản máy phục vụ: 10.1.31-MariaDB
-- Phiên bản PHP: 7.0.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Cơ sở dữ liệu: `thinhphat`
--
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `category_items`
--
CREATE TABLE `category_items` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`image_mobile` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` text COLLATE utf8mb4_unicode_ci,
`path` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`seo_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_description` text COLLATE utf8mb4_unicode_ci,
`seo_keywords` longtext COLLATE utf8mb4_unicode_ci,
`isActive` tinyint(1) NOT NULL DEFAULT '0',
`order` int(11) NOT NULL DEFAULT '1',
`level` tinyint(1) UNSIGNED NOT NULL DEFAULT '0',
`parent_id` int(10) UNSIGNED DEFAULT NULL,
`type` tinyint(4) NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `category_items`
--
INSERT INTO `category_items` (`id`, `name`, `image`, `image_mobile`, `description`, `path`, `seo_title`, `seo_description`, `seo_keywords`, `isActive`, `order`, `level`, `parent_id`, `type`, `created_at`, `updated_at`) VALUES
(1, 'Đèn Trang Trí - Đèn Chiếu Sáng', 'images/uploads/images/danhmuc/den_trnag_tri.jpg', NULL, '<p>Đèn Trang Trí - Đèn Chiếu Sáng</p>', 'den-trang-tri-den-chieu-sang', 'Đèn Trang Trí - Đèn Chiếu Sáng', '<p>Đèn Trang Trí - Đèn Chiếu Sáng</p>', NULL, 1, 1, 0, 0, 1, '2017-12-26 13:03:40', '2018-01-03 03:41:48'),
(2, 'Thiết Bị Điện', 'images/uploads/images/danhmuc/temp_list_category_banne_phongngu.jpg', NULL, '<p>Thiết Bị Điện</p>', 'thiet-bi-dien', 'Thiết Bị Điện', '<p>Thiết Bị Điện</p>', NULL, 1, 2, 0, 0, 1, '2017-12-26 13:04:17', '2018-01-01 03:04:37'),
(3, 'Thiết Bị Nước - Thiết Bị Vệ Sinh', 'images/uploads/images/danhmuc/temp_list_category_banne_gianbep.jpg', NULL, '<p>Thiết Bị Nước - Thiết Bị Vệ Sinh</p>', 'thiet-bi-nuoc-thiet-bi-ve-sinh', 'Thiết Bị Nước - Thiết Bị Vệ Sinh', '<p>Thiết Bị Nước - Thiết Bị Vệ Sinh</p>', NULL, 1, 3, 0, 0, 1, '2017-12-26 13:04:42', '2018-01-01 03:05:20'),
(4, 'Thiết Bị Nhà Bếp', 'images/uploads/images/danhmuc/temp_list_category_banne_hanhlang.jpg', NULL, '<p>Thiết Bị Nhà Bếp</p>', 'thiet-bi-nha-bep', 'Thiết Bị Nhà Bếp', '<p>Thiết Bị Nhà Bếp</p>', NULL, 1, 4, 0, 0, 1, '2017-12-26 13:05:04', '2018-01-01 03:06:05'),
(5, 'Thiết Kế Thi Công', 'images/uploads/images/danhmuc/temp_list_category_banne_showroom.jpg', NULL, '<p>Thiết Kế Thi Công</p>', 'thiet-ke-thi-cong', 'Thiết Kế Thi Công', '<p>Thiết Kế Thi Công</p>', NULL, 0, 5, 0, 0, 1, '2017-12-26 13:05:29', '2018-01-01 03:31:11'),
(6, 'Đèn Treo', 'images/uploads/images/danhmuc/dentreo.jpg', 'http://localhost:8080/thinhphat/http://localhost:8080/thinhpha', '<p>\r\n Đèn Treo\r\n</p>', 'den-treo', 'Đèn Treo', 'Đèn Treo', NULL, 1, 1, 1, 1, 1, '2017-12-26 13:05:59', '2018-06-29 06:48:33'),
(7, '<NAME>', 'images/uploads/images/danhmuc/denphale.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Pha Lê\r\n</p>', 'den-pha-le', 'Đèn Pha Lê', '<p>Đèn Pha Lê</p>', NULL, 1, 2, 1, 1, 1, '2017-12-26 13:06:19', '2018-06-29 06:53:07'),
(8, 'Đèn Chùm Hiện Đại', 'images/uploads/images/danhmuc/denchumhiendai.jpg', 'http://localhost:8080/thinhphat/http://localhost:8080/thinhpha', '<p>\r\n Đèn Chùm Hiện Đại\r\n</p>', 'den-chum-hien-dai', 'Đèn Chùm Hiện Đại', 'Đèn Chùm Hiện Đại', 'Đèn Chùm Hiện Đại', 1, 3, 1, 1, 1, '2017-12-26 13:06:40', '2018-06-29 06:54:10'),
(9, 'Đ<NAME> Tân Cổ Điển', 'images/uploads/images/danhmuc/denchumtancodien.jpg', 'http://localhost:8080/thinhphat/http://localhost:8080/thinhpha', '<p>\r\n Đèn Chùm Tân Cổ Điển\r\n</p>', 'den-chum-tan-co-dien', 'Đèn Chùm Tân Cổ Điển', 'Đèn Chùm Tân Cổ Điển', 'Đèn Chùm Tân Cổ Điển', 1, 4, 1, 1, 1, '2018-01-01 03:08:50', '2018-06-29 06:55:04'),
(10, 'Đèn Ốp Trần', 'images/uploads/images/danhmuc/denoptran.png', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Ốp Trần\r\n</p>', 'den-op-tran', 'Đèn Ốp Trần', '<p>Đèn Ốp Trần</p>', NULL, 1, 5, 1, 1, 1, '2018-01-01 03:09:21', '2018-06-29 06:55:43'),
(11, 'Đèn Quạt - Quạt Trần', 'images/uploads/images/danhmuc/denquattran.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Quạt - Quạt Trần\r\n</p>', 'den-quat-quat-tran', 'Đèn Quạt - Quạt Trần', '<p>Đèn Quạt - Quạt Trần</p>', NULL, 1, 6, 1, 1, 1, '2018-01-01 03:10:00', '2018-06-29 06:56:41'),
(12, 'Đèn Downlight', 'images/uploads/images/danhmuc/dendownlight.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Downlight\r\n</p>', 'den-downlight', 'Đèn Downlight', '<p>Đèn Downlight</p>', NULL, 1, 7, 1, 1, 1, '2018-01-01 03:10:33', '2018-06-29 06:57:45'),
(13, 'Đèn Ốp Tường', 'images/uploads/images/danhmuc/denoptuong.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Ốp Tường\r\n</p>', 'den-op-tuong', 'Đèn Ốp Tường', '<p>Đèn Ốp Tường</p>', NULL, 1, 8, 1, 1, 1, '2018-01-01 03:11:12', '2018-06-29 06:59:07'),
(14, 'Đèn Soi Tranh', 'images/uploads/images/danhmuc/densoitranh.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Soi Tranh\r\n</p>', 'den-soi-tranh', 'Đèn Soi Tranh', '<p>Đèn Soi Tranh</p>', NULL, 1, 9, 1, 1, 1, '2018-01-01 03:11:40', '2018-06-29 07:00:13'),
(15, 'Đèn Bàn', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'images/uploads/images/danhmuc/denban.jpg', '<p>\r\n Đèn Bàn\r\n</p>', 'den-ban', 'Đèn Bàn', '<p>Đèn Bàn</p>', NULL, 1, 10, 1, 1, 1, '2018-01-01 03:12:14', '2018-06-29 07:01:04'),
(16, 'Đèn Sân Vườn - Ngoại Thất', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'images/uploads/images/danhmuc/densanvuon.png', '<p>\r\n Đèn Sân Vườn - Ngoại Thất\r\n</p>', 'den-san-vuon-ngoai-that', 'Đèn Sân Vườn - Ngoại Thất', '<p>Đèn Sân Vườn - Ngoại Thất</p>', NULL, 1, 11, 1, 1, 1, '2018-01-01 03:12:39', '2018-06-29 07:02:20'),
(17, 'Đèn Nghệ Thuật', 'images/uploads/images/danhmuc/dennghethuat.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Đèn Nghệ Thuật\r\n</p>', 'den-nghe-thuat', 'Đèn Nghệ Thuật', '<p>Đèn Nghệ Thuật</p>', NULL, 1, 12, 1, 1, 1, '2018-01-01 03:12:59', '2018-06-29 07:03:13'),
(18, 'Đèn Cho Bé', 'images/uploads/images/danhmuc/denchobe.jpg', 'images/uploads/images/danhmuc/denchobe.jpg', '<p>\r\n Đèn Cho Bé\r\n</p>', 'den-cho-be', 'Đèn Cho Bé', '<p>Đèn Cho Bé</p>', NULL, 1, 13, 1, 1, 1, '2018-01-01 03:14:02', '2018-06-29 07:28:08'),
(19, 'Các Loại Đèn Khác', 'images/uploads/images/danhmuc/denkhac.png', 'images/uploads/images/danhmuc/denkhac.png', '<p>\r\n Các Loại Đèn Khác\r\n</p>', 'cac-loai-den-khac', 'Các Loại Đèn Khác', '<p>Các Loại Đèn Khác</p>', NULL, 1, 14, 1, 1, 1, '2018-01-01 03:14:38', '2018-06-29 07:28:29'),
(20, 'Thiết Bị Điện Panaonic', 'images/uploads/images/danhmuc/dienpanasonic.png', 'images/uploads/images/danhmuc/dienpanasonic.png', '<p>\r\n Thiết Bị Điện Panaonic\r\n</p>', 'thiet-bi-dien-panaonic', 'Thiết Bị Điện Panaonic', '<p>Thiết Bị Điện Panaonic</p>', NULL, 1, 1, 1, 2, 1, '2018-01-01 03:19:06', '2018-06-29 07:15:53'),
(21, '<NAME> Schneider', 'images/uploads/images/danhmuc/dienschneider.jpg', 'images/uploads/images/danhmuc/dienschneider.jpg', '<p>\r\n Thiết Bị Điện Schneider\r\n</p>', 'thiet-bi-dien-schneider', 'Thiết Bị Điện Schneider', '<p>Thiết Bị Điện Schneider</p>', NULL, 1, 2, 1, 2, 1, '2018-01-01 03:19:36', '2018-06-29 07:16:06'),
(22, 'Thiết bị điện MPE', 'images/uploads/images/danhmuc/dienmpe.jpg', 'images/uploads/images/danhmuc/dienmpe.jpg', '<p>\r\n Thiết bị điện MPE\r\n</p>', 'thiet-bi-dien-mpe', 'Thiết bị điện MPE', '<p>Thiết bị điện MPE</p>', NULL, 1, 3, 1, 2, 1, '2018-01-01 03:19:52', '2018-06-29 07:16:20'),
(23, 'Thiết bị điện Sino', 'images/uploads/images/danhmuc/diensino.jpg', 'images/uploads/images/danhmuc/diensino.jpg', '<p>\r\n Thiết bị điện Sino\r\n</p>', 'thiet-bi-dien-sino', 'Thiết bị điện Sino', '<p>Thiết bị điện Sino</p>', NULL, 1, 4, 1, 2, 1, '2018-01-01 03:20:48', '2018-06-29 07:16:33'),
(24, 'Ống Nước & Phụ Kiện', 'images/uploads/images/danhmuc/ongnuocvaphukien.jpg', 'images/uploads/images/danhmuc/ongnuocvaphukien.jpg', '<p>\r\n Ống Nước & Phụ Kiện\r\n</p>', 'ong-nuoc-phu-kien', 'Ống Nước & Phụ Kiện', '<p>Ống Nước & Phụ Kiện</p>', NULL, 1, 1, 1, 3, 1, '2018-01-01 03:21:57', '2018-06-29 07:16:51'),
(25, 'Bồn Cầu', 'images/uploads/images/danhmuc/boncau.jpg', 'images/uploads/images/danhmuc/boncau.jpg', '<p>\r\n Bồn Cầu\r\n</p>', 'bon-cau', 'Bồn Cầu', '<p>Bồn Cầu</p>', NULL, 1, 2, 1, 3, 1, '2018-01-01 03:22:19', '2018-06-29 07:17:03'),
(26, 'Lavabo', 'images/uploads/images/danhmuc/lavabo.jpg', 'images/uploads/images/danhmuc/lavabo.jpg', '<p>\r\n Lavabo\r\n</p>', 'lavabo', 'Lavabo', '<p>Lavabo</p>', NULL, 1, 3, 1, 3, 1, '2018-01-01 03:23:07', '2018-06-29 07:17:17'),
(27, '<NAME>', 'images/uploads/images/danhmuc/voisen.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Vòi Sen\r\n</p>', 'voi-sen', 'V<NAME>', '<p>Vòi Sen</p>', NULL, 1, 4, 1, 3, 1, '2018-01-01 03:23:30', '2018-06-29 07:18:29'),
(28, '<NAME>', 'images/uploads/images/danhmuc/voibep.png', 'http://localhost:8080/thinhphat', '<p>\r\n Vòi Bếp\r\n</p>', 'voi-bep', 'Vòi Bếp', '<p>Vòi Bếp</p>', NULL, 1, 5, 1, 3, 1, '2018-01-01 03:23:54', '2018-06-29 07:19:04'),
(29, 'Chậu Rửa Inox - Chậu Rửa Đá', 'images/uploads/images/danhmuc/chauruainox.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Chậu Rửa Inox - Chậu Rửa Đá\r\n</p>', 'chau-rua-inox-chau-rua-da', 'Chậu Rửa Inox - Chậu Rửa Đá', '<p>Chậu Rửa Inox - Chậu Rửa Đá</p>', NULL, 1, 6, 1, 3, 1, '2018-01-01 03:24:34', '2018-06-29 07:20:56'),
(30, 'Bồn Nước Inox', 'images/uploads/images/danhmuc/bonruainox.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Bồn Nước Inox\r\n</p>', 'bon-nuoc-inox', 'Bồn Nước Inox', '<p>Bồn Nước Inox</p>', NULL, 1, 7, 1, 3, 1, '2018-01-01 03:25:09', '2018-06-29 07:21:51'),
(31, 'Năng Lượng Mặt Trời', 'images/uploads/images/danhmuc/nangluongmattroi.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Năng Lượng Mặt Trời\r\n</p>', 'nang-luong-mat-troi', 'Năng Lượng Mặt Trời', '<p>Năng Lượng Mặt Trời</p>', NULL, 1, 8, 1, 3, 1, '2018-01-01 03:25:33', '2018-06-29 07:22:52'),
(32, 'Máy Lọc Nước', 'images/uploads/images/danhmuc/maylocnuoc.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Máy Lọc Nước\r\n</p>', 'may-loc-nuoc', 'Máy Lọc Nước', '<p>Máy Lọc Nước</p>', NULL, 1, 9, 1, 3, 1, '2018-01-01 03:26:06', '2018-06-29 07:23:32'),
(33, 'Bình Nóng Lạnh', 'images/uploads/images/danhmuc/binhnonglanh.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Bình Nóng Lạnh\r\n</p>', 'binh-nong-lanh', 'Bình Nóng Lạnh', '<p>Bình Nóng Lạnh</p>', NULL, 1, 10, 1, 3, 1, '2018-01-01 03:27:08', '2018-06-29 07:24:12'),
(34, 'Phụ Kiện Phòng Tắm', 'images/uploads/images/danhmuc/phukienphongtam.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Phụ Kiện Phòng Tắm\r\n</p>', 'phu-kien-phong-tam', 'Phụ Kiện Phòng Tắm', '<p>Phụ Kiện Phòng Tắm</p>', NULL, 1, 11, 1, 3, 1, '2018-01-01 03:27:38', '2018-06-29 07:25:09'),
(35, 'Lò Nướng', 'images/uploads/images/danhmuc/lonuong.png', 'http://localhost:8080/thinhphat', '<p>\r\n Lò Nướng\r\n</p>', 'lo-nuong', 'Lò Nướng', '<p>Lò Nướng</p>', NULL, 1, 1, 1, 4, 1, '2018-01-01 03:28:19', '2018-06-29 07:25:50'),
(36, 'Bếp Từ', 'images/uploads/images/danhmuc/beptu.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Bếp Từ\r\n</p>', 'bep-tu', 'Bếp Từ', '<p>Bếp Từ</p>', NULL, 1, 2, 1, 4, 1, '2018-01-01 03:28:39', '2018-06-29 07:26:25'),
(37, 'Quạt Hút', 'images/uploads/images/danhmuc/quathut.jpg', 'http://localhost:8080/thinhphat', '<p>\r\n Quạt Hút\r\n</p>', 'quat-hut', 'Quạt Hút', '<p>Quạt Hút</p>', NULL, 1, 3, 1, 4, 1, '2018-01-01 03:29:02', '2018-06-29 07:27:16'),
(38, 'Thiết Kế Kiến Trúc', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', NULL, '<p>Thiết Kế Kiến Trúc</p>', 'thiet-ke-kien-truc', 'Thiết Kế Kiến Trúc', '<p>Thiết Kế Kiến Trúc</p>', NULL, 1, 1, 1, 5, 1, '2018-01-01 03:29:48', '2018-01-01 03:29:48');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `category_permissions`
--
CREATE TABLE `category_permissions` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `category_permissions`
--
INSERT INTO `category_permissions` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'Role', '2017-12-23 13:04:28', '2017-12-23 13:04:28'),
(2, 'User', '2017-12-23 13:04:28', '2017-12-23 13:04:28'),
(3, 'Loại Sản Phẩm', '2017-12-24 02:03:30', '2017-12-24 02:03:30'),
(4, 'Sản Phẩm', '2017-12-26 08:57:53', '2017-12-26 08:57:53'),
(5, 'Page', '2017-12-30 12:21:43', '2017-12-30 12:21:43'),
(6, 'Post', '2017-12-30 12:21:44', '2017-12-30 12:21:44'),
(7, 'Catalogue', '2018-01-01 04:06:39', '2018-01-01 04:06:39');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `configs`
--
CREATE TABLE `configs` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`content` longtext COLLATE utf8mb4_unicode_ci,
`description` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`order` int(11) DEFAULT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `configs`
--
INSERT INTO `configs` (`id`, `name`, `content`, `description`, `order`, `user_id`, `created_at`, `updated_at`) VALUES
(1, 'config-contact', '<p>\r\n <strong><em><span style=\"background-color:#f1c40f;\">Hotline đặt hàng</span>:</em></strong><em> <strong>097.388.9336 - 0914.675.777</strong></em>\r\n</p>\r\n\r\n<p>\r\n <strong><em>Hotline hỗ trợ tư vấn và phản hồi ý kiến</em></strong><em>: <strong>097.388.9336</strong></em>\r\n</p>\r\n\r\n<p>\r\n <strong><em>Hân hạnh được phục vụ quý khách hàng.!</em></strong>\r\n</p>\r\n\r\n<p>\r\n <strong><em>Thông tin liên hệ với chúng tôi:</em></strong>\r\n</p>\r\n\r\n<p>\r\n <strong>CÔNG TY TNHH THƯƠNG MẠI DỊCH VỤ THÉP KHÁNH NAM</strong>\r\n</p>\r\n\r\n<p>\r\n <strong>TRỤ SỞ CHÍNH:</strong> <em>201 Bình Thành, KP 4, <NAME>, <NAME>, thành phố Hồ Chí Minh</em>\r\n</p>\r\n\r\n<p>\r\n <strong>Di động:</strong><em> 097.388.9336 - 0914.675.777</em>\r\n</p>', NULL, NULL, 1, NULL, '2018-03-30 09:07:51');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2017_12_23_195635_create_entrust_setup_tables', 2),
(4, '2017_12_24_085328_create_categories_table', 3),
(5, '2017_12_26_140629_create_products_table', 4);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `permissions`
--
CREATE TABLE `permissions` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`display_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`category_permission_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `permissions`
--
INSERT INTO `permissions` (`id`, `name`, `display_name`, `description`, `category_permission_id`, `created_at`, `updated_at`) VALUES
(1, 'role-list', 'Xem Danh Sách Quyền', 'Được Xem Danh Sách Quyền', 1, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(2, 'role-create', 'Tạo Quyền Mới', 'Được Tạo Quyền Mới', 1, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(3, 'role-edit', 'Cập Nhật Quyền', 'Được Cập Nhật Quyền', 1, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(4, 'role-delete', 'Xóa Quyền', 'Được Xóa Quyền', 1, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(5, 'user-list', 'Xem Danh Sách Users', 'Được Xem Danh Sách Users', 2, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(6, 'user-create', 'Tạo User', 'Được Tạo User Mới', 2, '2017-12-23 13:06:50', '2017-12-23 13:06:50'),
(7, 'user-edit', 'Cập Nhật User', 'Được Cập Nhật User', 2, '2017-12-23 13:06:51', '2017-12-23 13:06:51'),
(8, 'user-delete', 'Xóa user', 'Được Xóa User', 2, '2017-12-23 13:06:51', '2017-12-23 13:06:51'),
(9, 'category-list', 'Xem Toàn Bộ Loại Sản Phẩm', 'Được Xem Toàn Bộ Loại Sản Phẩm', 3, '2017-12-24 02:04:45', '2017-12-24 02:04:45'),
(10, 'category-create', 'Tạo Loại Sản Phẩm Mới', 'Được Tạo Loại Sản Phẩm Mới', 3, '2017-12-24 02:04:45', '2017-12-24 02:04:45'),
(11, 'category-edit', 'Cập Nhật Loại Sản Phẩm', 'Được Cập Nhật Loại Sản Phẩm', 3, '2017-12-24 02:04:45', '2017-12-24 02:04:45'),
(12, 'category-delete', 'Xóa Loại Sản Phẩm', 'Được Xóa Loại Sản Phẩm', 3, '2017-12-24 02:04:45', '2017-12-24 02:04:45'),
(13, 'product-list', 'Xem Toàn Bộ Sản Phẩm', 'Được Xem Toàn Bộ Sản Phẩm', 4, '2017-12-26 08:58:57', '2017-12-26 08:58:57'),
(14, 'product-create', 'Tạo Sản Phẩm Mới', 'Được Tạo Sản Phẩm Mới', 4, '2017-12-26 08:58:57', '2017-12-26 08:58:57'),
(15, 'product-edit', 'Cập Nhật Sản Phẩm', 'Được Cập Nhật Sản Phẩm', 4, '2017-12-26 08:58:57', '2017-12-26 08:58:57'),
(16, 'product-delete', 'Xóa Sản Phẩm', 'Được Xóa Sản Phẩm', 4, '2017-12-26 08:58:57', '2017-12-26 08:58:57'),
(17, 'page-list', 'Xem Toàn Bộ Trang', 'Được Xem Toàn Bộ Trang', 5, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(18, 'page-create', 'Tạo Trang Mới', 'Được Tạo Trang Mới', 5, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(19, 'page-edit', 'Cập Nhật Trang', 'Được Cập Nhật Trang', 5, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(20, 'page-delete', 'Xóa Trang', 'Được Xóa Trang', 5, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(21, 'post-list', 'Xem Toàn Bộ Bài Viết', 'Được Xem Toàn Bộ Bài Viết', 6, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(22, 'post-create', 'Tạo Bài Viết Mới', 'Được Tạo Bài Viết Mới', 6, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(23, 'post-edit', 'Cập Nhật Bài Viết', 'Được Cập Nhật Bài Viết', 6, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(24, 'post-delete', 'Xóa Bài Viết', 'Được Xóa Bài Viết', 6, '2017-12-30 12:24:39', '2017-12-30 12:24:39'),
(26, 'catalogue-list', 'Xem Toàn Bộ Catalogue', 'Được Xem Toàn Bộ Catalogue', 7, '2018-01-01 04:08:33', '2018-01-01 04:08:33'),
(27, 'catalogue-create', 'Tạo Catalogue Mới', 'Được Tạo Catalogue Mới', 7, '2018-01-01 04:08:33', '2018-01-01 04:08:33'),
(28, 'catalogue-edit', 'Cập Nhật Catalogue', 'Được Cập Nhật Catalogue', 7, '2018-01-01 04:08:33', '2018-01-01 04:08:33'),
(29, 'catalogue-delete', 'Xóa Catalogue', 'Được Xóa Catalogue', 7, '2018-01-01 04:08:33', '2018-01-01 04:08:33');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `permission_role`
--
CREATE TABLE `permission_role` (
`permission_id` int(10) UNSIGNED NOT NULL,
`role_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `permission_role`
--
INSERT INTO `permission_role` (`permission_id`, `role_id`) VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 1),
(5, 1),
(6, 1),
(7, 1),
(8, 1),
(9, 1),
(10, 1),
(11, 1),
(12, 1),
(13, 1),
(14, 1),
(15, 1),
(16, 1),
(17, 1),
(18, 1),
(19, 1),
(20, 1),
(21, 1),
(22, 1),
(23, 1),
(24, 1),
(26, 1),
(27, 1),
(28, 1),
(29, 1);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `posts`
--
CREATE TABLE `posts` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`path` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`content` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_description` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_keywords` longtext COLLATE utf8mb4_unicode_ci,
`post_type` tinyint(3) UNSIGNED NOT NULL DEFAULT '0',
`isActive` tinyint(1) NOT NULL DEFAULT '1',
`category_item_id` int(11) NOT NULL,
`user_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `posts`
--
INSERT INTO `posts` (`id`, `title`, `path`, `description`, `content`, `image`, `seo_title`, `seo_description`, `seo_keywords`, `post_type`, `isActive`, `category_item_id`, `user_id`, `created_at`, `updated_at`) VALUES
(1, '<NAME>', 'gioi-thieu', '<p>123</p>', '<p>123</p>', '0', '123', '<p>123</p>', NULL, 0, 1, 0, 1, '2018-01-01 02:22:24', '2018-01-01 02:22:24'),
(2, 'Catalogue Đèn Trang Trí', 'catalogue-den-trang-tri', '<p>Catalogue Đèn Trang Trí</p>', '<p>Catalogue Đèn Trang Trí</p>', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'Catalogue Đèn Trang Trí', '<p>Catalogue Đèn Trang Trí</p>', NULL, 2, 1, 0, 1, '2018-01-01 04:16:07', '2018-01-01 04:16:07'),
(3, 'Catalogue Thiết Bị Điện', 'catalogue-thiet-bi-dien', '<p>Catalogue Thiết Bị Điện</p>', '<p>Catalogue Thiết Bị Điện</p>', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'Catalogue Thiết Bị Điện', '<p>Catalogue Thiết Bị Điện</p>', NULL, 2, 1, 0, 1, '2018-01-01 04:16:40', '2018-01-01 04:16:40'),
(4, 'Catalogue Thiết Bị Nước - WC', 'catalogue-thiet-bi-nuoc-wc', '<p>Catalogue Thiết Bị Nước - WC</p>', '<p>Catalogue Thiết Bị Nước - WC</p>', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'Catalogue Thiết Bị Nước - WC', '<p>Catalogue Thiết Bị Nước - WC</p>', NULL, 2, 1, 0, 1, '2018-01-01 04:17:04', '2018-01-01 04:17:04'),
(5, 'Catalogue Thiết Bị Nhà Bếp', 'catalogue-thiet-bi-nha-bep', '<p>Catalogue Thiết Bị Nhà Bếp</p>', '<p>Catalogue Thiết Bị Nhà Bếp</p>', 'images/uploads/images/danhmuc/temp_list_category_banne_dotrangtri.jpg', 'Catalogue Thiết Bị Nhà Bếp', '<p>Catalogue Thiết Bị Nhà Bếp</p>', NULL, 2, 1, 0, 1, '2018-01-01 04:17:31', '2018-01-01 04:17:31');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `products`
--
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`path` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`isActive` tinyint(1) NOT NULL DEFAULT '0',
`is_best_sale` tinyint(4) DEFAULT '0',
`image` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci,
`content` longtext COLLATE utf8mb4_unicode_ci,
`code` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`seo_description` text COLLATE utf8mb4_unicode_ci,
`seo_keywords` longtext COLLATE utf8mb4_unicode_ci,
`price` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT '0',
`sale` int(11) NOT NULL DEFAULT '0',
`final_price` int(11) DEFAULT '0',
`order` int(11) NOT NULL DEFAULT '1',
`user_id` int(10) UNSIGNED NOT NULL,
`category_product_id` int(10) UNSIGNED NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `products`
--
INSERT INTO `products` (`id`, `name`, `path`, `isActive`, `is_best_sale`, `image`, `description`, `content`, `code`, `seo_title`, `seo_description`, `seo_keywords`, `price`, `sale`, `final_price`, `order`, `user_id`, `category_product_id`, `created_at`, `updated_at`) VALUES
(1, 'HL0171806 L', 'hl0171806-l', 1, 1, 'images/uploads/images/sanpham/denchumhiendai/HL0171806_L.jpg', '<p>\r\n HL0171806 L\r\n</p>', '<p>\r\n HL0171806 L\r\n</p>', 'HL0171806', 'HL0171806 L', 'HL0171806 L', 'HL0171806 L', '12400000', 30, 8680000, 1, 1, 8, '2017-12-26 13:58:02', '2018-06-29 08:07:51'),
(2, 'HL0171806 M', 'hl0171806-m', 1, 0, 'images/uploads/images/sanpham/denchumhiendai/HL0171806_M.jpg', '<p>\r\n HL0171806 M\r\n</p>', '<p>\r\n HL0171806\r\n</p>', 'HL0171806', 'HL0171806 M', 'HL0171806', 'HL0171806', '8910000', 30, 6237000, 2, 1, 8, '2017-12-26 14:00:09', '2018-06-29 08:05:14'),
(3, 'HL0151042', 'hl0151042', 1, 0, 'images/uploads/images/sanpham/denchumhiendai/HL0151042.jpg', '<p>\r\n HL0151042\r\n</p>', '<p>\r\n HL0151042\r\n</p>', 'HL0151042', 'HL0151042', 'HL0151042', 'HL0151042', '8360000', 30, 5852000, 2, 1, 8, '2017-12-26 14:02:31', '2018-06-29 08:04:09'),
(4, 'HL120072', 'hl120072', 1, 1, 'images/uploads/images/sanpham/denchumtancodien/HL120072.jpg', '<p>\r\n HL120072\r\n</p>', '<p>\r\n HL120072\r\n</p>', 'HL120072', 'HL120072', 'HL120072', 'HL120072', '10750000', 30, 7525000, 4, 1, 9, '2017-12-26 14:16:57', '2018-06-29 08:01:36'),
(5, 'HL018018-10+5', 'hl018018-105', 1, 0, 'images/uploads/images/sanpham/denchumtancodien/HL018018_10_5.jpg', '<p>\r\n HL018018-10+5\r\n</p>', '<p>\r\n HL018018\r\n</p>', 'HL018018', 'HL018018-10+5', 'HL018018-10+5', 'HL018018-10+5', '12000000', 30, 8400000, 6, 1, 9, '2017-12-26 14:18:22', '2018-06-29 07:55:11'),
(6, 'HL088070-10+5', 'hl088070-105', 1, 0, 'images/uploads/images/sanpham/denchumtancodien/HL088070_10_5.jpg', '<p>\r\n HL088070-10+5\r\n</p>', '<p>\r\n HL088070\r\n</p>', 'HL088070', 'HL088070-10+5', 'HL088070', 'HL088070', '15600000', 30, 10920000, 7, 1, 9, '2017-12-26 14:20:02', '2018-06-29 07:53:47'),
(7, 'HL088006-10+5', 'hl088006-105', 1, 0, 'images/uploads/images/sanpham/denchumtancodien/HL088006_10_5.jpg', '<p>\r\n HL088006-10+5\r\n</p>', '<p>\r\n HL088006-10+5\r\n</p>', NULL, 'HL088006-10+5', 'HL088006-10+5', 'HL088006-10+5', '15000000', 30, 10500000, 1, 1, 9, '2017-12-26 14:21:38', '2018-06-29 07:52:29'),
(8, 'HL0121056 L', 'hl0121056-l', 1, 1, 'images/uploads/images/sanpham/denchumhiendai/HL0121056_L.jpg', '<p>\r\n HL0121056 L\r\n</p>', NULL, NULL, 'HL0121056 L', '<p>HL0121056 L</p>', NULL, '7300000', 30, 5110000, 1, 1, 8, '2017-12-26 14:24:02', '2018-06-29 07:51:08'),
(9, 'HL0121056 M', 'hl0121056-m', 1, 1, 'images/uploads/images/sanpham/denchumhiendai/HL0121056_M.jpg', '<p>\r\n HL0121056 M\r\n</p>', NULL, NULL, 'HL0121056 M', '<p>HL0121056 M</p>', NULL, '5860000', 30, 4102000, 1, 1, 8, '2017-12-26 14:24:47', '2018-06-29 07:49:41'),
(10, 'HL1086048-H2', 'hl1086048-h2', 1, 0, 'images/uploads/images/sanpham/dentreo/HL1086048-H2.jpg', '<p>\r\n HL1086048-H2\r\n</p>', '<p>\r\n HL1086048-H2\r\n</p>', NULL, 'HL1086048-H2', 'HL1086048-H2', 'HL1086048-H2', '4750000', 30, 3325000, 1, 1, 6, '2017-12-26 14:32:32', '2018-06-29 07:47:51'),
(11, 'HL093333-7-61191', 'hl093333-7-61191', 1, 0, 'images/uploads/images/sanpham/denban/HL093333-7-61191.jpg', '<p>\r\n HL093333-7-61191\r\n</p>', '<p>\r\n HL093333\r\n</p>', 'HL093333', 'HL093333-7-61191', 'HL093333-7-61191', NULL, '3450000', 30, 2415000, 1, 1, 15, '2017-12-26 14:40:18', '2018-06-29 07:44:52'),
(12, 'HL093333-7-61174', 'hl093333-7-61174', 1, 1, 'images/uploads/images/sanpham/denban/HL093333.jpg', '<p>\r\n HL093333-7-61174\r\n</p>', NULL, NULL, 'HL093333-7-61174', 'HL093333-7-61174', NULL, '4000000', 30, 2800000, 1, 1, 15, '2017-12-26 14:42:30', '2018-06-29 07:43:28'),
(13, 'HL04116', 'hl04116', 1, 1, 'images/uploads/images/sanpham/dentreo/HL1086048.jpg', '<p>\r\n HL04116\r\n</p>', NULL, NULL, 'HL04116', '<p>HL04116</p>', NULL, '3250000', 30, 2275000, 1, 1, 6, '2017-12-27 03:06:01', '2018-06-29 07:40:57');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `roles`
--
CREATE TABLE `roles` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`display_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `roles`
--
INSERT INTO `roles` (`id`, `name`, `display_name`, `description`, `created_at`, `updated_at`) VALUES
(1, 'admin', 'admin', '<p>administer the website and manage users</p>', '2017-12-23 13:01:45', '2017-12-26 12:27:57');
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `role_user`
--
CREATE TABLE `role_user` (
`user_id` int(10) UNSIGNED NOT NULL,
`role_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `role_user`
--
INSERT INTO `role_user` (`user_id`, `role_id`) VALUES
(1, 1);
-- --------------------------------------------------------
--
-- Cấu trúc bảng cho bảng `users`
--
CREATE TABLE `users` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Đang đổ dữ liệu cho bảng `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'nnduyquang', '<EMAIL>', <PASSWORD>', NULL, '2017-12-23 11:59:19', NULL);
--
-- Chỉ mục cho các bảng đã đổ
--
--
-- Chỉ mục cho bảng `category_items`
--
ALTER TABLE `category_items`
ADD PRIMARY KEY (`id`);
--
-- Chỉ mục cho bảng `category_permissions`
--
ALTER TABLE `category_permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `category_permissions_name_unique` (`name`);
--
-- Chỉ mục cho bảng `configs`
--
ALTER TABLE `configs`
ADD PRIMARY KEY (`id`),
ADD KEY `configs_user_id_foreign` (`user_id`);
--
-- Chỉ mục cho bảng `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Chỉ mục cho bảng `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Chỉ mục cho bảng `permissions`
--
ALTER TABLE `permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `permissions_name_unique` (`name`),
ADD KEY `permissions_category_permission_id_foreign` (`category_permission_id`);
--
-- Chỉ mục cho bảng `permission_role`
--
ALTER TABLE `permission_role`
ADD PRIMARY KEY (`permission_id`,`role_id`),
ADD KEY `permission_role_role_id_foreign` (`role_id`);
--
-- Chỉ mục cho bảng `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`id`),
ADD KEY `posts_user_id_foreign` (`user_id`);
--
-- Chỉ mục cho bảng `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`),
ADD KEY `products_user_id_foreign` (`user_id`),
ADD KEY `products_category_id_foreign` (`category_product_id`);
--
-- Chỉ mục cho bảng `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `roles_name_unique` (`name`);
--
-- Chỉ mục cho bảng `role_user`
--
ALTER TABLE `role_user`
ADD PRIMARY KEY (`user_id`,`role_id`),
ADD KEY `role_user_role_id_foreign` (`role_id`);
--
-- Chỉ mục cho bảng `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT cho các bảng đã đổ
--
--
-- AUTO_INCREMENT cho bảng `category_items`
--
ALTER TABLE `category_items`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39;
--
-- AUTO_INCREMENT cho bảng `category_permissions`
--
ALTER TABLE `category_permissions`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT cho bảng `configs`
--
ALTER TABLE `configs`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT cho bảng `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT cho bảng `permissions`
--
ALTER TABLE `permissions`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30;
--
-- AUTO_INCREMENT cho bảng `posts`
--
ALTER TABLE `posts`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT cho bảng `products`
--
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT cho bảng `roles`
--
ALTER TABLE `roles`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT cho bảng `users`
--
ALTER TABLE `users`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- Các ràng buộc cho các bảng đã đổ
--
--
-- Các ràng buộc cho bảng `configs`
--
ALTER TABLE `configs`
ADD CONSTRAINT `configs_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `permissions`
--
ALTER TABLE `permissions`
ADD CONSTRAINT `permissions_category_permission_id_foreign` FOREIGN KEY (`category_permission_id`) REFERENCES `category_permissions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `permission_role`
--
ALTER TABLE `permission_role`
ADD CONSTRAINT `permission_role_permission_id_foreign` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `permission_role_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `posts`
--
ALTER TABLE `posts`
ADD CONSTRAINT `posts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `products`
--
ALTER TABLE `products`
ADD CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_product_id`) REFERENCES `category_items` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `products_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Các ràng buộc cho bảng `role_user`
--
ALTER TABLE `role_user`
ADD CONSTRAINT `role_user_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `role_user_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/local/app/Repositories/Frontend/FrontendRepository.php
<?php
namespace App\Repositories\Frontend;
use App\Config;
class FrontendRepository implements FrontendRepositoryInterface
{
public function getDataConfig()
{
$data = [];
$configs = Config::whereIn('name', ['config-phone', 'config-email', 'config-address','config-contact'])->orderBy('order')->get();
foreach ($configs as $key => $item) {
if ($item->name == 'config-phone'){
$data['config-phone'] = $item->content;
$data['config-phone-2'] = str_replace('.','',$item->content);
}
if ($item->name == 'config-email')
$data['config-email'] = $item->content;
if ($item->name == 'config-address')
$data['config-address'] = $item->content;
if ($item->name == 'config-contact')
$data['config-contact'] = $item->content;
}
return $data;
}
}<file_sep>/local/app/Repositories/Frontend/FrontendRepositoryInterface.php
<?php
namespace App\Repositories\Frontend;
interface FrontendRepositoryInterface
{
public function getDataConfig();
}<file_sep>/local/database/seeds/PermissionTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Permission;
class PermissionTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$permission = [
// KHỞI TẠO BAN ĐẦU
// [
// 'name' => 'role-list',
// 'display_name' => 'Xem Danh Sách Quyền',
// 'description' => 'Được Xem Danh Sách Quyền',
// 'category_permission_id' => 1
// ],
// [
// 'name' => 'role-create',
// 'display_name' => '<NAME>',
// 'description' => 'Được Tạo Quyền Mới',
// 'category_permission_id' => 1
// ],
// [
// 'name' => 'role-edit',
// 'display_name' => '<NAME>',
// 'description' => 'Được Cập Nhật Quyền',
// 'category_permission_id' => 1
// ],
// [
// 'name' => 'role-delete',
// 'display_name' => '<NAME>',
// 'description' => 'Được Xóa Quyền',
// 'category_permission_id' => 1
// ]
// ,
// [
// 'name' => 'user-list',
// 'display_name' => 'Xem Danh Sách Users',
// 'description' => 'Được Xem Danh Sách Users',
// 'category_permission_id' => 2
// ],
// [
// 'name' => 'user-create',
// 'display_name' => 'Tạo User',
// 'description' => 'Được Tạo User Mới',
// 'category_permission_id' => 2
// ],
// [
// 'name' => 'user-edit',
// 'display_name' => '<NAME>',
// 'description' => 'Được Cập Nhật User',
// 'category_permission_id' => 2
// ],
// [
// 'name' => 'user-delete',
// 'display_name' => '<NAME>',
// 'description' => 'Được Xóa User',
// 'category_permission_id' => 2
// ],
// [
// 'name' => 'news-list',
// 'display_name' => '<NAME>̀<NAME>',
// 'description' => 'Được Xem Toàn Bộ Tin Tức',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'news-create',
// 'display_name' => '<NAME>́<NAME>́i',
// 'description' => 'Được Tạo Tin Tức Mới',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'news-edit',
// 'display_name' => '<NAME>',
// 'description' => 'Được Cập Nhật Tin Tức',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'news-delete',
// 'display_name' => '<NAME>́c',
// 'description' => 'Được Xóa Tin Tức',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'config-list',
// 'display_name' => 'Toàn Quyền Cấu Hình',
// 'description' => 'Được Toàn Quyền Cấu Hình',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'config-create',
// 'display_name' => 'Thêm Mới Cấu Hình',
// 'description' => 'Được Thêm Mới Cấu Hình',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'config-edit',
// 'display_name' => 'Cập Nhật Cấu Hình',
// 'description' => 'Được Cập Nhật Cấu Hình',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'config-delete',
// 'display_name' => '<NAME>',
// 'description' => 'Được Xóa Cấu Hình',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'category-list',
// 'display_name' => 'Xem Toàn Bộ Loại Sản Phẩm',
// 'description' => 'Được Xem Toàn Bộ Loại Sản Phẩm',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'category-create',
// 'display_name' => 'Tạo Loại Sản Phẩm Mới',
// 'description' => 'Được Tạo Loại Sản Phẩm Mới',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'category-edit',
// 'display_name' => 'Cập Nhật Loại Sản Phẩm',
// 'description' => 'Được Cập Nhật Loại Sản Phẩm',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'category-delete',
// 'display_name' => 'Xóa Loại Sản Phẩm',
// 'description' => 'Được Xóa Loại Sản Phẩm',
// 'category_permission_id'=>3
// ],
// [
// 'name' => 'product-list',
// 'display_name' => 'Xem Toàn Bộ Sản Phẩm',
// 'description' => 'Được Xem Toàn Bộ Sản Phẩm',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'product-create',
// 'display_name' => 'Tạo Sản Phẩm Mới',
// 'description' => 'Được Tạo Sản Phẩm Mới',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'product-edit',
// 'display_name' => 'Cập Nhật Sản Phẩm',
// 'description' => 'Được Cập Nhật Sản Phẩm',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'product-delete',
// 'display_name' => 'Xóa Sản Phẩm',
// 'description' => 'Được Xóa Sản Phẩm',
// 'category_permission_id'=>4
// ],
// [
// 'name' => 'page-list',
// 'display_name' => 'Xem Toàn Bộ Trang',
// 'description' => 'Được Xem Toàn Bộ Trang',
// 'category_permission_id'=>5
// ],
// [
// 'name' => 'page-create',
// 'display_name' => 'Tạo Trang Mới',
// 'description' => 'Được Tạo Trang Mới',
// 'category_permission_id'=>5
// ],
// [
// 'name' => 'page-edit',
// 'display_name' => 'Cập Nhật Trang',
// 'description' => 'Được Cập Nhật Trang',
// 'category_permission_id'=>5
// ],
// [
// 'name' => 'page-delete',
// 'display_name' => 'Xóa Trang',
// 'description' => 'Được Xóa Trang',
// 'category_permission_id'=>5
// ],
// [
// 'name' => 'post-list',
// 'display_name' => 'Xem Toàn Bộ Bài Viết',
// 'description' => 'Được Xem Toàn Bộ Bài Viết',
// 'category_permission_id'=>6
// ],
// [
// 'name' => 'post-create',
// 'display_name' => 'Tạo Bài Viết Mới',
// 'description' => 'Được Tạo Bài Viết Mới',
// 'category_permission_id'=>6
// ],
// [
// 'name' => 'post-edit',
// 'display_name' => 'Cập Nhật Bài Viết',
// 'description' => 'Được Cập Nhật Bài Viết',
// 'category_permission_id'=>6
// ],
// [
// 'name' => 'post-delete',
// 'display_name' => 'Xóa Bài Viết',
// 'description' => 'Được Xóa Bài Viết',
// 'category_permission_id'=>6
// ],
[
'name' => 'catalogue-list',
'display_name' => 'Xem Toàn Bộ Catalogue',
'description' => 'Được Xem Toàn Bộ Catalogue',
'category_permission_id'=>7
],
[
'name' => 'catalogue-create',
'display_name' => 'Tạo Catalogue Mới',
'description' => 'Được Tạo Catalogue Mới',
'category_permission_id'=>7
],
[
'name' => 'catalogue-edit',
'display_name' => 'Cập Nhật Catalogue',
'description' => 'Được Cập Nhật Catalogue',
'category_permission_id'=>7
],
[
'name' => 'catalogue-delete',
'display_name' => 'Xóa Catalogue',
'description' => 'Được Xóa Catalogue',
'category_permission_id'=>7
],
];
foreach ($permission as $key => $value) {
Permission::create($value);
}
}
}
<file_sep>/local/app/Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'id','name','image','description','path','seo_title','seo_description', 'isActive','order','level','parent_id','user_id','created_at','updated_at'
];
public function users()
{
return $this->belongsTo('App\User', 'user_id');
}
public function products(){
return $this->hasMany('App\Product','category_id');
}
}
<file_sep>/local/app/Http/Controllers/feProductController.php
<?php
namespace App\Http\Controllers;
use App\CategoryItem;
use App\Post;
use App\Product;
use Illuminate\Http\Request;
class feProductController extends Controller
{
public function getDetailProduct($pathCategory, $pathProduct)
{
$product = Product::where('path', '=', $pathProduct)->first();
$product->price=number_format($product->price, 0, ',', '.');
$product->final_price=number_format($product->final_price, 0, ',', '.');
$list_sidebar = CategoryItem::select('id', 'name', 'level', 'parent_id','path')->where('level', '=', 0)->orWhere('level', '=', 1)->orderBy('order')->get();
$menu_horizon= CategoryItem::where('level', '=', 0)->orderBy('order')->get();
$menu_sidebar = [];
$order_product = [];
self::showCategoryDropDown($list_sidebar, 0, $menu_sidebar);
$category = CategoryItem::where('path', '=', $pathCategory)->first();
self::getAllProductByCategory($category, $order_product);
foreach ($order_product as $key => $data) {
if ($data->id == $product->id) {
unset($order_product[$key]);
break;
}
}
// $order_product = collect($order_product)->sortByDESC('created_at')->take(4);
$catalogues=Post::where('post_type','=',2)->where('isActive','=',1)->get();
return view('frontend.detail.detail', compact('product', 'menu_sidebar', 'order_product','menu_horizon','catalogues'));
}
public function showCategoryDropDown($dd_categories, $parent_id = 0, &$newArray)
{
foreach ($dd_categories as $key => $data) {
if ($data->parent_id == $parent_id) {
array_push($newArray, $data);
$dd_categories->forget($key);
self::showCategoryDropDown($dd_categories, $data->id, $newArray);
}
}
}
public function getAllProductByCategory($category, &$list_product)
{
$list = Product::where('category_product_id', '=', $category->id)->orderBy('created_at')->get();
foreach ($list as $key2 => $data2) {
$data2->path = '/san-pham/'.$category->path . '/' . $data2->path;
$data2->price=number_format($data2->price, 0, ',', '.');
$data2->final_price=number_format($data2->final_price, 0, ',', '.');
array_push($list_product, $data2);
}
$sub = CategoryItem::where('parent_id', '=', $category->id)->get();
foreach ($sub as $key => $data) {
self::getAllProductByCategory($data, $list_product);
}
}
}
|
6acf17a497e9a3e32d93b156690dac664e3ac011
|
[
"JavaScript",
"SQL",
"PHP"
] | 12
|
PHP
|
nnduyquang/thinhphat
|
d2ba559326d0a2d536825e5736c7d5f04875b933
|
3e92c84e8f01737d3ef4124f327b139a9eb42f7a
|
refs/heads/master
|
<file_sep>/**
* Created by admin on 12-01-2015.
*/
public class USDollar extends Currency {
@Override
public double convert(Currency other, Double convertRatio) {
return 0;
}
USDollar()
{
super("USDollar","USD");
}
}
<file_sep>/**
* Created by admin on 12-01-2015.
*/
public class Pound extends Currency{
Pound(String currencyName, String currencySymbol) {
super("Pound", "P");
}
public double convert(Currency otherCurrency,Double convertRatio)
{
return 0.0;
}
}
|
c416f687ae22586f62b5408c87096a47fbb7d75f
|
[
"Java"
] | 2
|
Java
|
rohanwce/Currency
|
f25551d3e308d6b856fc62938ee2417f3a628f37
|
d3c5a78f3ff5053534e8f7f1e38758f9bc425a49
|
refs/heads/master
|
<file_sep>package xyz.patzj.alterator.algorithm;
import xyz.patzj.alterator.algorithm.KeyExpander;
/**
* @author patzj
*/
public abstract class BlockKeyExpander extends KeyExpander {
private int subKey[][][] = new int[11][4][4]; // round 0 to 10 of 128-bit block
/**
* Returns the subkey of the specified round.
* @param round Current encryption or decryption round.
* @return Subkey for specific encryption or decryption round.
* @throws IndexOutOfBoundsException
*/
public int[][] getSubKey(int round) throws IndexOutOfBoundsException {
return subKey[round];
}
}
<file_sep>package xyz.patzj.alterator.algorithm;
import xyz.patzj.alterator.algorithm.SymmetricCipher;
import java.security.Key;
/**
* @author patzj
*/
public abstract class BlockSymmetricCipher extends SymmetricCipher {
private int[][] stateMatrix;
private KeyExpander keyExpander;
/**
* Returns the n-bit state matrix of data.
* @return Two-dimensional array of bytes.
*/
public int[][] getStateMatrix() {
return stateMatrix;
}
/**
* Sets the n-bits state matrix of data.
* @param stateMatrix n-bit Two-dimentional array of bytes.
*/
public void setStateMatrix(int[][] stateMatrix) {
this.stateMatrix = stateMatrix;
}
public KeyExpander getKeyExpander() {
return keyExpander;
}
public void setKeyExpander(KeyExpander keyExpander) {
this.keyExpander = keyExpander;
}
}
<file_sep>package xyz.patzj.alterator.algorithm;
/**
* Cipher interface.
* @author patzj
*/
public interface Cipher {
void encrypt();
void decrypt();
}
<file_sep>package xyz.patzj.alterator;
/**
* @author patzj
*/
public class AlgorithmNotFoundException extends Exception {
public AlgorithmNotFoundException() {
super("No algorithm implementation found.");
}
}
|
27833d29254c41cf1235df3807cfb57c9b7204a1
|
[
"Java"
] | 4
|
Java
|
patzj/alterator
|
fee0f181b6458e2c4e6e9c292e23ab8431886919
|
39daad6485d33fab66b61c8146dd0e5787a59ab0
|
refs/heads/master
|
<file_sep>package main
import (
"os"
"fmt"
"flag"
"time"
"bytes"
"strings"
"net/http"
"encoding/json"
"github.com/stianeikeland/go-rpio"
)
var (
DEBUG bool
VERBOSE bool
ENDPOINT string
)
type State int
const (
LOCKED State = iota
UNLOCKED
UNKNOWN
)
type stateChange struct {
State string `json:"state"`
}
var httpClient = &http.Client{Timeout: 30 * time.Second}
func main() {
cmdline := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
fRefresh := cmdline.Duration ("refresh", time.Millisecond * 50, "GPIO pin refresh rate.")
fEndpoint := cmdline.String ("endpoint", "", "The endpoint to send lock state updates to. If omitted, updates are local only.")
fDebug := cmdline.Bool ("debug", strToBool(os.Getenv("DEBUG")), "Enable debugging mode.")
fVerbose := cmdline.Bool ("verbose", strToBool(os.Getenv("VERBOSE")), "Enable verbose debugging mode.")
cmdline.Parse(os.Args[1:])
fmt.Println(">>> Starting.")
DEBUG = *fDebug
VERBOSE = *fVerbose
ENDPOINT = *fEndpoint
refresh := *fRefresh
if refresh < time.Millisecond {
refresh = time.Millisecond
}
updateLockState(UNKNOWN)
err := rpio.Open()
if err != nil {
panic(fmt.Errorf("Could not open GPIO: %v", err))
}
defer rpio.Close()
indOpen := rpio.Pin(4)
indOpen.Output()
indLock := rpio.Pin(27)
indLock.Output()
indInput := rpio.Pin(17)
indInput.Output()
lock := rpio.Pin(9)
lock.Input()
button := rpio.Pin(11)
button.Input()
buzzer := rpio.Pin(18)
buzzer.Output()
indOpen.High()
indLock.High()
indInput.High()
for i := 0; i < 20; i++ {
if i % 3 == 0 {
indOpen.Toggle()
}else if i % 3 == 1 {
indLock.Toggle()
}else{
indInput.Toggle()
}
<-time.After(time.Millisecond * 75)
}
indOpen.Low()
indLock.Low()
indInput.Low()
go handleReset(button, indInput, indOpen, indLock, refresh)
go handleLockUnlock(lock, indOpen, indLock, refresh)
fmt.Println(">>> Ready.")
<-make(chan struct{})
}
func handleReset(button, indInput, indOpen, indLock rpio.Pin, refresh time.Duration) {
state := rpio.Low
for {
button.PullDown()
res := button.Read()
if state != res {
state = res
switch state {
case rpio.High:
if DEBUG || VERBOSE {
fmt.Println(">>> BUTTON DOWN")
}
indOpen.Low()
indLock.Low()
indInput.Low()
updateLockState(UNKNOWN)
case rpio.Low:
if DEBUG || VERBOSE {
fmt.Println(">>> BUTTON UP")
}
}
}
<-time.After(refresh)
}
}
func handleLockUnlock(lock, indOpen, indLock rpio.Pin, refresh time.Duration) {
state := rpio.Low
indOpen.High()
for {
lock.PullDown()
res := lock.Read()
if state != res {
state = res
switch state {
case rpio.High:
if DEBUG || VERBOSE {
fmt.Println(">>> LOCK DOWN")
}
indOpen.Low()
indLock.High()
case rpio.Low:
if DEBUG || VERBOSE {
fmt.Println(">>> LOCK UP")
}
indOpen.High()
indLock.Low()
}
var update State
switch state {
case rpio.High:
update = LOCKED
case rpio.Low:
update = UNLOCKED
default:
update = UNKNOWN
}
err := updateLockState(update)
if err != nil {
fmt.Errorf(">>> Could not update lock state: %v", err)
}
}
<-time.After(refresh)
}
}
func updateLockState(s State) error {
if VERBOSE || DEBUG {
fmt.Printf(">>> Updating state: %v\n", s)
}
var dest string
switch s {
case LOCKED:
dest = "occupied"
case UNLOCKED:
dest = "available"
default:
dest = "unknown"
}
change := &stateChange{
State: dest,
}
data, err := json.Marshal(change)
if err != nil {
return fmt.Errorf("Could not marshal state change: %v", err)
}
req, err := http.NewRequest("POST", ENDPOINT, bytes.NewBuffer(data))
if err != nil {
return fmt.Errorf("Could not create update request: %v", err)
}
rsp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("Could not perform update request: %v", err)
}
if rsp.StatusCode != http.StatusOK {
return fmt.Errorf("Invalid status code from service: %v", rsp.Status)
}
return nil
}
func strToBool(s string) bool {
return strings.EqualFold(s, "t") || strings.EqualFold(s, "true") || strings.EqualFold(s, "y") || strings.EqualFold(s, "yes")
}<file_sep>
GOPATH := $(PWD)
PRODUCT := $(PWD)/bin/occupi
SRC := $(shell find src -name \*.go -print)
all: build
build: $(PRODUCT)
$(PRODUCT): $(SRC)
mkdir -p $(PWD)/bin && go build -o $(PRODUCT) occupi/main
<file_sep># The Occu-pi Door Controller
This is the controller software for the Occu-pi, a totally awesome bathroom door sensor. If you use it as the basis for your own Occu-pi you may need to make adjustments to use the GPIO pins to which you've wired your sensors and LEDs.
If you have no idea what I'm talking about, [read about the Occu-pi](https://medium.com/@bww/occu-pi-the-bathroom-of-the-future-ed69b84e21d5).
|
a5735fbc25cfa0455776d854721c0ac12543f965
|
[
"Makefile",
"Go",
"Markdown"
] | 3
|
Go
|
zackkitzmiller/occu-pi
|
fe5713ca70dd1a5f7f4e9bf334e8fbbaca718189
|
3f98bc9f0cd909cd4d9227dcf9fea85d430fe658
|
refs/heads/master
|
<repo_name>craigwardman/ChunkingRedisClient<file_sep>/src/Client/Reader/IRedisReader.cs
using System;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Reader
{
public interface IRedisReader<in TKey, TItem>
{
Task<TItem> ReadAsync(IDatabaseAsync redisDatabase, TKey key, TimeSpan? resetExpiry);
}
}<file_sep>/src/Client/Deleter/StandardDeleter.cs
using System;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Deleter
{
public class StandardDeleter<TKey, TItem> : IRedisDeleter<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
public StandardDeleter(IKeygen<TKey> keygen)
{
_keygen = keygen ?? throw new ArgumentNullException(nameof(keygen));
}
public Task<bool> DeleteAsync(IDatabaseAsync redisDatabase, TKey key)
{
return redisDatabase.KeyDeleteAsync(_keygen.GetKey(key));
}
}
}<file_sep>/src/Keys/GuidKeygen.cs
using System;
using StackExchange.Redis;
namespace ChunkingRedisClient.Keys
{
public class GuidKeygen : IKeygen<Guid>
{
public RedisKey GetKey(Guid input, string suffix = null)
{
return $"{input}:{suffix}";
}
}
}<file_sep>/src/Locking/IRedisLockFactory.cs
using StackExchange.Redis;
namespace ChunkingRedisClient.Locking
{
public interface IRedisLockFactory
{
IRedisLock GetLockInstance(RedisKey key);
void Use<T>() where T : IRedisLock;
}
}<file_sep>/tests/ChunkingRedisClient.IntegrationTests/TestObjects/TestDataGenerator.cs
using System.Collections.Generic;
namespace ChunkingRedisClient.Tests.TestObjects
{
public class TestDataGenerator
{
public static IReadOnlyCollection<Product> Generate(int numberOfItems)
{
List<Product> products = new List<Product>();
for (int i = 0; i < numberOfItems; i++)
{
products.Add(new Product
{
ProductId = (i + 1) * 10
});
}
return products;
}
}
}<file_sep>/README.md
# Chunking Redis Client
A C#/.NET Core library which wraps the StackExchange.Redis client, specifically using JSON serialisation, and adds functionality such as chunked reading/writing and sliding expiration.
To install without the source, use the NuGet package:
https://www.nuget.org/packages/ChunkingRedisClient/
The purpose of this library is to create a re-usable library of code for wrapping the StackExchange.RedisClient and solving the issues I usually need to solve.
Those being:
* IoC wrappers/abstractions<br/>
- Just take your dependency on `IRedisClient<TKey, TItem>`<br/>
- By default you should configure your DI container to inject the provided RedisClient<TKey, TItem><br/>
- Since IoC is used throughout you also need to configure:<br/>
~ `IRedisWriter<TKey, Item>` -> JsonRedisWriter or ChunkedJsonRedisWriter<br/>
~ `IRedisReader<TKey, Item>` -> JsonRedisReader or ChunkedJsonRedisReader<br/>
~ `IRedisWriter<TKey, Item>` -> JsonRedisDeleter or ChunkedJsonRedisDeleter<br/>
(note: for one combination of TKey, TItem - ensure the decision to chunk or not is consistent)<br/>
~ `IKeygen<TKey>` to an object specific implementation, like GuidKeygen<br/>
~ For chunking, locking is required:<br/>
IRedisLockFactory -> RedisLockFactory<br/>
To override the default of InMemoryRedisLock, call `RedisLockFactory.Use<IRedisLock>() <-- your class here`<br/>
* Strongly typed access to the cache<br/>
- Use any C# object as your TKey and TItem, given that:<br/>
~ You can implement your own Keygen for TKey<br/>
~ Your TItem is serialisable by Newtonsoft.Json<br/>
* Implementing the StackExchange Connection Multiplexer<br/>
- This is handled by the RedisDatabaseFactory<br/>
- Not using the usual `Lazy<ConnectionMulitplexer>` approach, as I want to support one multiplexer per connection string (if your app is dealing with more than 1 cache)<br/>
- The multiplexers are stored in a concurrent dictionary where the connection string is the key<br/>
- The multiplexer begins connecting asynchronously on first use<br/>
* Sliding expiration of cache keys<br/>
- Pass in the optional timespan to read methods if you want to use sliding expiration<br/>
- This updates the expiry when you read the item, so that keys which are still in use for read purposes live longer<br/>
* Chunked JSON data<br/>
- This solves a performance issue whereby Redis does not perform well with large payloads.<br/>
- Sometimes you may also have had errors from the server when the queue is full.<br/>
- The default chunk size is 10KB which can be configured in the ChunkedJsonRedisWriter<br/>
- The JSON data is streamed from Newtonsoft into a buffer. Every time the buffer is full it is written to Redis under the main cache key with a suffix of "chunkIndex"<br/>
- The main cache key is then written to contain the count of chunks, which is used by the reader and deleter.<br/>
* Generating keys for objects<br/>
- I don't like using bytes for keys as they are not human readable, so I like to generate unique strings<br/>
- There is no none-intrusive way of providing a type agnostic generic keygen, therefore you must write your own. If you write something for a CLR type, considering contributing it to the project!
- Since we know Guids are unique, I have demonstrated the ability to create custom keygens.<br/>
The code can be extended to support other serialisation types (TODO), distributed locks (TODO), different ways of generating keys or whatever you need it to do.
<file_sep>/src/Client/Reader/ChunkedJsonRedisReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using ChunkingRedisClient.Locking;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Reader
{
public class ChunkedJsonRedisReader<TKey, TItem> : IRedisReader<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
private readonly IRedisLockFactory _lockFactory;
public ChunkedJsonRedisReader(IKeygen<TKey> keygen, IRedisLockFactory lockFactory)
{
_keygen = keygen ?? throw new ArgumentNullException(nameof(keygen));
_lockFactory = lockFactory ?? throw new ArgumentNullException(nameof(lockFactory));
}
public async Task<TItem> ReadAsync(IDatabaseAsync redisDatabase, TKey key, TimeSpan? resetExpiry)
{
var headerKey = _keygen.GetKey(key);
var chunkGets = new List<Task<RedisValue>>();
using (var redisLock = _lockFactory.GetLockInstance(headerKey))
{
await redisLock.AcquireAsync().ConfigureAwait(false);
var header = await GetAndUpdateExpiry(redisDatabase, headerKey, resetExpiry).ConfigureAwait(false);
if (header.IsNullOrEmpty)
{
return default(TItem);
}
var totalChunks = (int)header;
for (var chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++)
{
var chunkKey = _keygen.GetKey(key, chunkIndex.ToString());
chunkGets.Add(GetAndUpdateExpiry(redisDatabase, chunkKey, resetExpiry));
}
await Task.WhenAll(chunkGets).ConfigureAwait(false);
}
var jsonData = string.Join("", chunkGets.Select(cg => cg.Result));
return string.IsNullOrEmpty(jsonData) ? default(TItem) : JsonConvert.DeserializeObject<TItem>(jsonData);
}
private static async Task<RedisValue> GetAndUpdateExpiry(IDatabaseAsync connection, RedisKey key, TimeSpan? resetExpiry)
{
if (resetExpiry.HasValue)
{
await connection.KeyExpireAsync(key, resetExpiry.Value, CommandFlags.FireAndForget).ConfigureAwait(false);
}
return await connection.StringGetAsync(key).ConfigureAwait(false);
}
}
}<file_sep>/tests/ChunkingRedisClient.IntegrationTests/TestObjects/Product.cs
namespace ChunkingRedisClient.Tests.TestObjects
{
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public ProductType ProductType { get; set; }
public int BrandId { get; set; }
public ProductGroup ProductGroup { get; set; }
public decimal CurrentPurchasePrice { get; set; }
}
public class ProductType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ProductGroup
{
public int Id { get; set; }
public string Name { get; set; }
}
}<file_sep>/src/Client/RedisClient.cs
using System;
using System.Threading.Tasks;
using ChunkingRedisClient.Client.Deleter;
using ChunkingRedisClient.Client.Reader;
using ChunkingRedisClient.Client.Writer;
using ChunkingRedisClient.Database;
using StackExchange.Redis;
using StackExchange.Redis.KeyspaceIsolation;
namespace ChunkingRedisClient.Client
{
public class RedisClient<TKey, TItem> : IRedisClient<TKey, TItem>
{
private readonly string _connectionString;
private readonly IRedisWriter<TKey, TItem> _redisWriter;
private readonly IRedisReader<TKey, TItem> _redisReader;
private readonly IRedisDeleter<TKey, TItem> _redisDeleter;
private readonly string _keyPrefix;
private IDatabase _prefixedDatabase;
public RedisClient(
RedisClientConfig config,
IRedisWriter<TKey, TItem> redisWriter,
IRedisReader<TKey, TItem> redisReader,
IRedisDeleter<TKey, TItem> redisDeleter)
{
_connectionString = string.IsNullOrEmpty(config?.ConnectionString) ? throw new ArgumentNullException(nameof(config.ConnectionString)) : config.ConnectionString;
_redisWriter = redisWriter ?? throw new ArgumentNullException(nameof(redisWriter));
_redisReader = redisReader ?? throw new ArgumentNullException(nameof(redisReader));
_redisDeleter = redisDeleter ?? throw new ArgumentNullException(nameof(redisDeleter));
_keyPrefix = $"{typeof(TItem).Namespace}.{typeof(TItem).Name}::";
}
public Task<bool> SetAsync(TKey key, TItem item, TimeSpan? expiryTimeSpan = null)
{
if (key == null) throw new ArgumentNullException(nameof(key));
if (item == null) throw new ArgumentNullException(nameof(item));
return SetAsyncInternal(key, item, expiryTimeSpan);
}
public Task<TItem> GetAsync(TKey key, TimeSpan? resetExpiryTimeSpan = null)
{
if (key == null) throw new ArgumentNullException(nameof(key));
return GetAsyncInternal(key, resetExpiryTimeSpan);
}
public Task<bool> DeleteAsync(TKey key)
{
if (key == null) throw new ArgumentNullException(nameof(key));
return DeleteAsyncInternal(key);
}
private async Task<bool> DeleteAsyncInternal(TKey key)
{
var connection = await GetKeyspacedDatabaseAsync().ConfigureAwait(false);
return await _redisDeleter.DeleteAsync(connection, key).ConfigureAwait(false);
}
private async Task<TItem> GetAsyncInternal(TKey key, TimeSpan? resetExpiryTimeSpan)
{
var connection = await GetKeyspacedDatabaseAsync().ConfigureAwait(false);
return await _redisReader.ReadAsync(connection, key, resetExpiryTimeSpan).ConfigureAwait(false);
}
private async Task<bool> SetAsyncInternal(TKey key, TItem item, TimeSpan? expiryTimeSpan)
{
var connection = await GetKeyspacedDatabaseAsync().ConfigureAwait(false);
return await _redisWriter.WriteAsync(connection, key, item, expiryTimeSpan).ConfigureAwait(false);
}
private async Task<IDatabase> GetKeyspacedDatabaseAsync()
{
if (_prefixedDatabase == null)
{
_prefixedDatabase = (await RedisDatabaseFactory
.GetRedisDatabaseAsync(_connectionString)
.ConfigureAwait(false))
.WithKeyPrefix(_keyPrefix);
}
return _prefixedDatabase;
}
}
}<file_sep>/src/Locking/IRedisLock.cs
using System;
using System.Threading.Tasks;
namespace ChunkingRedisClient.Locking
{
public interface IRedisLock : IDisposable
{
Task AcquireAsync();
void Release();
}
}<file_sep>/src/Client/IRedisClient.cs
using System;
using System.Threading.Tasks;
namespace ChunkingRedisClient.Client
{
public interface IRedisClient<in TKey, TItem>
{
Task<bool> DeleteAsync(TKey key);
Task<TItem> GetAsync(TKey key, TimeSpan? resetExpiryTimeSpan = null);
Task<bool> SetAsync(TKey key, TItem item, TimeSpan? expiryTimeSpan = null);
}
}<file_sep>/src/Client/Deleter/ChunkedDeleter.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using ChunkingRedisClient.Locking;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Deleter
{
public class ChunkedDeleter<TKey, TItem> : IRedisDeleter<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
private readonly IRedisLockFactory _lockFactory;
public ChunkedDeleter(IKeygen<TKey> keygen, IRedisLockFactory lockFactory)
{
_keygen = keygen ?? throw new ArgumentNullException(nameof(keygen));
_lockFactory = lockFactory ?? throw new ArgumentNullException(nameof(lockFactory));
}
public async Task<bool> DeleteAsync(IDatabaseAsync redisDatabase, TKey key)
{
var headerKey = _keygen.GetKey(key);
var chunkDeletes = new List<Task<bool>>();
using (var redisLock = _lockFactory.GetLockInstance(headerKey))
{
await redisLock.AcquireAsync().ConfigureAwait(false);
var header = await redisDatabase.StringGetAsync(headerKey).ConfigureAwait(false);
if (header.IsNullOrEmpty)
{
return false;
}
var chunkCount = (int)header;
for (var chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++)
{
var chunkKey = _keygen.GetKey(key, chunkIndex.ToString());
chunkDeletes.Add(redisDatabase.KeyDeleteAsync(chunkKey));
}
await Task.WhenAll(chunkDeletes).ConfigureAwait(false);
return await redisDatabase.KeyDeleteAsync(headerKey).ConfigureAwait(false);
}
}
}
}<file_sep>/src/Locking/RedisLockFactory.cs
using System;
using System.Linq.Expressions;
using System.Reflection;
using StackExchange.Redis;
namespace ChunkingRedisClient.Locking
{
public class RedisLockFactory : IRedisLockFactory
{
private ConstructorInfo _lockTypeCtor;
public RedisLockFactory()
{
Use<InMemoryRedisLock>();
}
public void Use<T>() where T : IRedisLock
{
foreach (var ctor in typeof(T).GetConstructors())
{
var ctorParams = ctor.GetParameters();
if (ctorParams.Length == 1 && ctorParams[0].ParameterType == typeof(RedisKey))
{
_lockTypeCtor = ctor;
return;
}
}
throw new InvalidOperationException($"Cannot use type {typeof(T)} in RedisLockFactory. The type must inherit IRedisLock and have a public constructor taking a single argument of type RedisKey.");
}
public IRedisLock GetLockInstance(RedisKey key)
{
LambdaExpression lambda =
Expression.Lambda<Func<IRedisLock>>(Expression.New(_lockTypeCtor, Expression.Constant(key)));
return ((Func<IRedisLock>)lambda.Compile())();
}
}
}<file_sep>/src/Database/RedisDatabaseFactory.cs
using System.Collections.Concurrent;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace ChunkingRedisClient.Database
{
internal static class RedisDatabaseFactory
{
private static readonly ConcurrentDictionary<string, Task<ConnectionMultiplexer>> ConnectionMultiplexers = new ConcurrentDictionary<string, Task<ConnectionMultiplexer>>();
public static async Task<IDatabase> GetRedisDatabaseAsync(string connectionString)
{
var connectionMultiplexer = ConnectionMultiplexers.GetOrAdd(connectionString, GetConnectionMuliplexerAsync);
return (await connectionMultiplexer.ConfigureAwait(false)).GetDatabase();
}
private static Task<ConnectionMultiplexer> GetConnectionMuliplexerAsync(string connectionString)
{
return ConnectionMultiplexer.ConnectAsync(connectionString);
}
}
}<file_sep>/src/Client/Deleter/IRedisDeleter.cs
using System.Threading.Tasks;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Deleter
{
public interface IRedisDeleter<in TKey, TItem>
{
Task<bool> DeleteAsync(IDatabaseAsync redisDatabase, TKey key);
}
}<file_sep>/src/Client/Writer/BufferedTextWriter.cs
using System;
using System.IO;
using System.Text;
namespace ChunkingRedisClient.Client.Writer
{
public class BufferedTextWriter : TextWriter
{
private readonly int _bufferSize;
public BufferedTextWriter(int bufferSize)
{
_bufferSize = bufferSize;
Buffer = new StringBuilder(_bufferSize);
}
public event EventHandler<BufferFullEventArgs> BufferFull;
public override Encoding Encoding => Encoding.UTF8;
public StringBuilder Buffer { get; }
public override void Write(char value)
{
if (Buffer.Length == _bufferSize)
{
throw new InvalidOperationException("Buffer is full!");
}
Buffer.Append(value);
if (Buffer.Length == _bufferSize)
{
OnBufferFull(new BufferFullEventArgs(Buffer));
}
}
protected virtual void OnBufferFull(BufferFullEventArgs e)
{
BufferFull?.Invoke(this, e);
}
public class BufferFullEventArgs : EventArgs
{
public BufferFullEventArgs(StringBuilder buffer)
{
Buffer = buffer;
}
public StringBuilder Buffer { get; }
}
}
}<file_sep>/src/Keys/IKeygen.cs
using StackExchange.Redis;
namespace ChunkingRedisClient.Keys
{
public interface IKeygen<in TInput>
{
RedisKey GetKey(TInput input, string suffix = null);
}
}<file_sep>/src/Client/Writer/BufferFullEventArgs.cs
using System;
using System.Text;
namespace ChunkingRedisClient.Client.Writer
{
public class BufferFullEventArgs : EventArgs
{
public BufferFullEventArgs(StringBuilder buffer)
{
Buffer = buffer;
}
public StringBuilder Buffer { get; }
}
}<file_sep>/src/Locking/InMemoryRedisLock.cs
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace ChunkingRedisClient.Locking
{
internal class InMemoryRedisLock : IRedisLock
{
private static readonly ConcurrentDictionary<RedisKey, SemaphoreSlim> KeyLocks = new ConcurrentDictionary<RedisKey, SemaphoreSlim>();
private readonly SemaphoreSlim _mySemaphoreSlim;
private bool _isLockAcquired;
public InMemoryRedisLock(RedisKey key)
{
_mySemaphoreSlim = KeyLocks.GetOrAdd(key, redisKey => new SemaphoreSlim(1, 1));
}
public async Task AcquireAsync()
{
if (!_isLockAcquired)
{
await _mySemaphoreSlim.WaitAsync().ConfigureAwait(false);
_isLockAcquired = true;
}
}
public void Release()
{
if (_isLockAcquired)
{
_mySemaphoreSlim.Release();
_isLockAcquired = false;
}
}
public void Dispose()
{
Release();
}
}
}<file_sep>/src/Client/Reader/JsonRedisReader.cs
using System;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Reader
{
public class JsonRedisReader<TKey, TItem> : IRedisReader<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
public JsonRedisReader(IKeygen<TKey> keygen)
{
_keygen = keygen;
}
public async Task<TItem> ReadAsync(IDatabaseAsync redisDatabase, TKey key, TimeSpan? resetExpiry)
{
var redisKey = _keygen.GetKey(key);
var item = await redisDatabase.StringGetAsync(redisKey).ConfigureAwait(false);
if (resetExpiry.HasValue)
{
await redisDatabase.KeyExpireAsync(redisKey, resetExpiry.Value, CommandFlags.FireAndForget).ConfigureAwait(false);
}
return string.IsNullOrEmpty(item) ? default(TItem) : JsonConvert.DeserializeObject<TItem>(item);
}
}
}<file_sep>/src/MicrosoftDiExtensions.cs
using System;
using ChunkingRedisClient.Client;
using ChunkingRedisClient.Client.Deleter;
using ChunkingRedisClient.Client.Reader;
using ChunkingRedisClient.Client.Writer;
using ChunkingRedisClient.Keys;
using ChunkingRedisClient.Locking;
using Microsoft.Extensions.DependencyInjection;
namespace ChunkingRedisClient
{
public static class MicrosoftDiExtensions
{
public static void AddRedisClient<TKey, TItem>(this IServiceCollection serviceCollection, int? chunkSize)
{
serviceCollection.AddSingleton<IKeygen<Guid>, GuidKeygen>(); // user to manually register any other keygen classes
serviceCollection.AddSingleton<IRedisLockFactory, RedisLockFactory>();
if (chunkSize.GetValueOrDefault(0) is int chunk && chunk > 0)
{
serviceCollection.AddScoped<IRedisReader<TKey, TItem>, ChunkedJsonRedisReader<TKey, TItem>>();
serviceCollection.AddScoped<IRedisDeleter<TKey, TItem>, ChunkedDeleter<TKey, TItem>>();
serviceCollection.AddScoped(provider => new ChunkedJsonRedisWriter<TKey, TItem>(
provider.GetRequiredService<IKeygen<TKey>>(),
provider.GetRequiredService<IRedisLockFactory>(),
chunk));
}
else
{
serviceCollection.AddScoped<IRedisReader<TKey, TItem>, JsonRedisReader<TKey, TItem>>();
serviceCollection.AddScoped<IRedisDeleter<TKey, TItem>, StandardDeleter<TKey, TItem>>();
serviceCollection.AddScoped<IRedisWriter<TKey, TItem>, JsonRedisWriter<TKey, TItem>>();
}
serviceCollection.AddScoped<IRedisClient<TKey, TItem>, RedisClient<TKey, TItem>>(); // user to define IRedisClientConfig impl.
}
}
}<file_sep>/src/Client/Writer/ChunkedJsonRedisWriter.cs
using System;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using ChunkingRedisClient.Locking;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Writer
{
public class ChunkedJsonRedisWriter<TKey, TItem> : IRedisWriter<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
private readonly IRedisLockFactory _lockFactory;
private readonly int _chunkSize;
public ChunkedJsonRedisWriter(IKeygen<TKey> keygen, IRedisLockFactory lockFactory, int chunkSize)
{
_keygen = keygen ?? throw new ArgumentNullException(nameof(keygen));
_lockFactory = lockFactory ?? throw new ArgumentNullException(nameof(lockFactory));
_chunkSize = chunkSize > 0 ? chunkSize : 10240;
}
public async Task<bool> WriteAsync(IDatabaseAsync redisDatabase, TKey key, TItem item, TimeSpan? expiry)
{
var headerKey = _keygen.GetKey(key);
var chunkIndex = 0;
Task<bool> previousWriteTask = null;
using (var redisLock = _lockFactory.GetLockInstance(headerKey))
{
await redisLock.AcquireAsync().ConfigureAwait(false);
using (var bufferedWriter = new BufferedTextWriter(_chunkSize))
{
bufferedWriter.BufferFull += async (s, e) =>
{
var bufferContent = e.Buffer.ToString();
var myChunkIndex = chunkIndex++;
e.Buffer.Clear();
if (previousWriteTask != null)
{
await previousWriteTask.ConfigureAwait(false);
}
previousWriteTask = WriteToRedisAsync(redisDatabase, key, expiry, bufferContent, myChunkIndex);
};
JsonSerializer.CreateDefault().Serialize(bufferedWriter, item);
if (bufferedWriter.Buffer.Length > 0)
{
if (previousWriteTask != null)
{
await previousWriteTask.ConfigureAwait(false);
previousWriteTask = null;
}
await WriteToRedisAsync(redisDatabase, key, expiry, bufferedWriter.Buffer.ToString(), chunkIndex++).ConfigureAwait(false);
}
}
return await redisDatabase.StringSetAsync(headerKey, chunkIndex, expiry).ConfigureAwait(false);
}
}
private Task<bool> WriteToRedisAsync(IDatabaseAsync redisDatabase, TKey key, TimeSpan? expiry, string bufferContent, int chunkIndex)
{
return redisDatabase.StringSetAsync(
_keygen.GetKey(key, chunkIndex.ToString()),
bufferContent,
expiry);
}
}
}<file_sep>/src/Client/Writer/JsonRedisWriter.cs
using System;
using System.Threading.Tasks;
using ChunkingRedisClient.Keys;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Writer
{
public class JsonRedisWriter<TKey, TItem> : IRedisWriter<TKey, TItem>
{
private readonly IKeygen<TKey> _keygen;
public JsonRedisWriter(IKeygen<TKey> keygen)
{
_keygen = keygen;
}
public Task<bool> WriteAsync(IDatabaseAsync redisDatabase, TKey key, TItem item, TimeSpan? expiry)
{
var redisValue = JsonConvert.SerializeObject(item);
return redisDatabase.StringSetAsync(_keygen.GetKey(key), redisValue, expiry);
}
}
}<file_sep>/tests/ChunkingRedisClient.IntegrationTests/WhenDoingSequentialReadsAndWrites.cs
using ChunkingRedisClient.Client;
using ChunkingRedisClient.Client.Deleter;
using ChunkingRedisClient.Client.Reader;
using ChunkingRedisClient.Client.Writer;
using ChunkingRedisClient.Keys;
using ChunkingRedisClient.Locking;
using ChunkingRedisClient.Tests.TestObjects;
using FluentAssertions;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace ChunkingRedisClient.Tests
{
public class WhenDoingSequentialReadsAndWrites
{
[Fact]
public async Task CanWriteAndReadOneItem()
{
var keyGen = new GuidKeygen();
var redisClient =
new RedisClient<Guid, Product>(
new RedisClientConfig
{
ConnectionString = "my-redis:6379"
},
new ChunkedJsonRedisWriter<Guid, Product>(
keyGen, new RedisLockFactory(), 0),
new ChunkedJsonRedisReader<Guid, Product>(
keyGen, new RedisLockFactory()),
new ChunkedDeleter<Guid, Product>(
keyGen, new RedisLockFactory()));
var product = TestDataGenerator.Generate(1).First();
var guid = Guid.NewGuid();
await redisClient.SetAsync(guid, product);
var item = await redisClient.GetAsync(guid);
item.Should().NotBeNull();
}
}
}<file_sep>/src/Client/Writer/IRedisWriter.cs
using System;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace ChunkingRedisClient.Client.Writer
{
public interface IRedisWriter<in TKey, in TItem>
{
Task<bool> WriteAsync(IDatabaseAsync redisDatabase, TKey key, TItem item, TimeSpan? expiry);
}
}<file_sep>/src/Client/RedisClientConfig.cs
namespace ChunkingRedisClient.Client
{
public sealed class RedisClientConfig
{
public string ConnectionString { get; set; }
}
}
|
63e7e55f3953999f1a2bc9621b1a719762d31a37
|
[
"Markdown",
"C#"
] | 26
|
C#
|
craigwardman/ChunkingRedisClient
|
fb108903027e62cb4e79360f08e36a503c57984e
|
a00dac21a7276f2df0c761c7d0c6184226179b86
|
refs/heads/master
|
<file_sep>/* eslint-disable global-require */
module.exports = {
// base color scheme def
base: {
...require('./base/light.js'),
name: '<NAME> (LinkedData)',
variables: {
root: 'hsl(199, 56%, 51%)',
scape: 'hsl(344, 81%, 65%)',
flare: 'hsl(42, 98%, 66%)',
echo: 'hsl(175, 58%, 53%)',
chip: 'hsl(250, 48%, 69%)',
root_boost: 'hsl(199, 85%, 53%)',
scape_boost: 'hsl(344, 94%, 65%)',
flare_boost: 'hsl(42, 100%, 61%)',
echo_boost: 'hsl(175, 85%, 53%)',
chip_boost: 'hsl(250, 83%, 67%)',
},
},
// extra rules to append
rules: [
// registered prefixes
{
scope: 'meta.prefix-declaration.either.registered',
background: 'hsla(220, 63%, 89%, 0.61)',
},
// inverse path
{
scope: 'meta.path.inverse',
background: 'hsla(226, 94%, 62%, 0.12)',
font_style: 'italic',
},
// inverse path
{
scope: 'meta.path.negated',
background: 'hsla(290, 84%, 10%, 0.38)',
},
// plus quantifier
{
scope: 'keyword.operator.path.quantifier.one-or-more',
font_style: 'bold',
},
// storage modifier
{
scope: 'storage.modifier',
font_style: 'italic',
},
// comments
{
scope: 'comment',
foreground: 'hsla(0, 0%, 11%, 0.6)',
},
],
// blends
blends: {
root: {
// `@` as in `@prefix`
'punctuation.definition.storage storage.type': -25,
// prefix / base
'storage.type': -20,
// distinct / reduced
'storage.modifier': -8,
// all 'other' keywords (namely modifiers)
'keyword.operator': 15,
// `graph`
'keyword.control': -15,
},
root_boost: {
// qualifier keywords
'keyword.operator.word.qualifier': -10,
// where clause brace
'punctuation.section, meta.clause.where': 10,
// built-ins
'support.function': 0,
'punctuation.definition.expression': -15,
'punctuation.definition.arguments': 25,
// `as`
'storage.type.variable': -15,
'keyword.operator.path': 0,
'punctuation.section.group': -20,
'punctuation.section.block': -15,
'meta.path.negated punctuation.section.group': -10,
'meta.path.inverse punctuation.section.group': -10,
// constants `true` and `false`
'constant.language': -5,
},
scape: {
// prefixes
'variable.other.readwrite.prefixed-name.namespace': -25,
'punctuation.separator.prefixed-name': -10,
'variable.other.member.prefixed-name.local': 0,
'constant.character.escape.prefixed-name': -5,
// `a`
'support.constant.predicate.a': -50,
},
scape_boost: {
},
flare: {
// datatype symbol `^^`
'punctuation.separator.datatype.symbol': -60,
// prefixed-names
'meta.datatype variable.other.readwrite.prefixed-name.namespace': -50,
'meta.datatype variable.other.member.prefixed-name.local': -35,
'meta.datatype punctuation.separator.prefixed-name': -50,
// iri datatypes
'meta.datatype string.unquoted.iri': -25,
'meta.datatype constant.character.escape.iri': -40,
'meta.datatype punctuation.definition.iri': -50,
// blank node property list
'punctuation.definition.blank-node-property-list': -30,
'punctuation.definition.anonymous-blank-node': -45,
// terminators and separators
'punctuation.separator.object': -40,
'punctuation.separator.pair': -20,
'punctuation.separator.predicate-object-list': -40,
'punctuation.terminator.triple': -100,
'punctuation.terminator.graph-pattern': -60,
'punctuation.terminator.prefix-declaration': -60,
},
flare_boost: {
// variables
'variable.other.readwrite.var': -15,
},
echo: {
// literasls
'string.quoted.double.literal, string.quoted.single.literal': -15,
'punctuation.definition.string': -35,
'constant.character.escape.literal': -40,
// language-tags
'string.unquoted.language-tag': -5,
'punctuation.separator.language-tag.symbol': -35,
// numerics
'keyword.operator.arithmetic': -0,
'constant.numeric': -15,
'meta.numeric.exponent': -40,
},
echo_boost: {
'support.constant': -15,
},
chip: {
// iris
'string.unquoted.iri': -20,
'constant.character.escape.iri': -40,
'punctuation.definition.iri': -55,
// collection punctuation
'punctuation.definition.collection': 20,
// blank nodes
'variable.other.readwrite.blank-node.underscore': -45,
'variable.other.member.blank-node.label': -10,
},
chip_boost: {
'meta.directive': -45,
},
},
};
<file_sep>const fs = require('fs');
const path = require('path');
const syntax = require('../class/syntax.js');
let i_phrase = 0;
const unique_phrase = () => Buffer.from((i_phrase++)+'').toString('base64').replace(/=+$/, '');
const H_CASES = {
upper: s => s.toUpperCase(),
lower: s => s.toLowerCase(),
proper: s => s[0].toUpperCase()+s.slice(1).toLowerCase(),
mixed: s => `(?i)${s}`,
};
const H_CASES_EXTENDED = {
camel: s => s,
pascal: s => s[0].toUpperCase()+s.slice(1),
};
const normalize_insert_spec = (g_spec, a_stack=[]) => {
let b_pop = false;
if(g_spec.pop) {
b_pop = true;
}
else if(g_spec.set) {
b_pop = true;
a_stack.unshift(...(Array.isArray(g_spec.set)? g_spec.set: [g_spec.set]));
}
else if(g_spec.push) {
a_stack.unshift(...(Array.isArray(g_spec.push)? g_spec.push: [g_spec.push]));
}
return {
...g_spec,
pop: b_pop,
stack: a_stack,
action: (b_pop
? (a_stack.length
? {set:a_stack}
: {pop:true})
: {push:a_stack}),
};
};
const insert_prefixed_name = (h_env, k_context, i_rule, g_spec) => {
let {
scope: s_scope_frag,
action: h_stack_action,
} = normalize_insert_spec(g_spec, ['prefixedName']);
// prefix name
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{prefixedNameNamespace_LOOKAHEAD}}'`.slice(1, -1),
...h_stack_action,
});
return i_rule;
};
const insert_iri_ref = (h_env, k_context, i_rule, g_spec) => {
let {
scope: s_scope_frag,
action: h_stack_action,
} = normalize_insert_spec(g_spec, ['iriRef']);
// iri
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{iriRef_LOOKAHEAD}}'`.slice(1, -1),
...h_stack_action,
});
return i_rule;
};
const insert_blank_node = (h_env, k_context, i_rule, g_spec) => {
let {
scope: s_scope_frag,
stack: a_stack,
action: h_stack_action,
} = normalize_insert_spec(g_spec);
// make new context name
let si_context_blank_node_begin = `${syntax.scope_to_context(s_scope_frag)}_AFTER_BLANK_NODE_BEGIN`;
// // push to stack
// a_stack.push(si_context_blank_node_begin);
// blank node
k_context.insert(i_rule++, {
match: '_:',
scope: `variable.other.readwrite.blank-node.underscore.${s_scope_frag}.${h_env.syntax}`,
set: si_context_blank_node_begin,
});
// new context
let k_context_new = k_context.def.append(si_context_blank_node_begin, [
{meta_include_prototype:false},
{
match: /* syntax: sublime-syntax.regex */ `'{{BLANK_NODE_LABEL}}'`.slice(1, -1),
scope: `variable.other.member.blank-node.label.${s_scope_frag}.${h_env.syntax}`,
...h_stack_action,
},
// {include:'other_illegal_pop'},
{
match: /* syntax: sublime-syntax.regex */ `'{{MAT_word_or_any_one_char}}'`.slice(1, -1),
scope: `invalid.illegal.token.expected.${k_context.id}.${h_env.syntax}`,
pop: true,
},
]);
// throw pop
H_MODIFIERS._throw(h_env, k_context_new, 2, true);
};
const insert_cases = (h_env, k_context, i_rule, k_rule, s_word, h_cases) => {
let g_source = k_rule.source;
// lookahead
let s_lookahead = '{{KEYWORD_BOUNDARY}}';
if(g_source.lookahead) {
s_lookahead = g_source.lookahead;
delete g_source.lookahead;
}
// type
let s_type = 'modifier';
if(g_source.type) {
s_type = g_source.type;
delete g_source.type;
}
// each predefined case
for(let [s_case, f_case] of Object.entries(h_cases)) {
// insert permutation to rule
k_context.insert(i_rule++, {
match: `${f_case(syntax.string_to_regex(s_word))}(?=${s_lookahead})`,
...k_rule.clone(i_rule)
.scopes(s_scope => s_scope
.replace(/\.CASE\./, `.${s_case}.`)
.replace(/\.WORD\./, `.${s_word}.`))
.mod(g_source_sub => ({
...g_source_sub,
scope: `${g_source.scope || `keyword.operator.word.${s_type}.${s_word}.${h_env.syntax}`} `
+`meta.case.${s_case}.${h_env.syntax}`,
}))
.export(),
});
}
return i_rule;
};
const punctuation = (s_type, s_name, s_match_begin, s_match_end) => ({
[`_open_${s_name}`]: (h_env, k_context, k_rule, s_scope_frag) => {
Object.assign(k_rule.source, {
match: s_match_begin,
scope: `punctuation.${s_scope_frag}.begin.${h_env.syntax}`,
});
},
[`_close_${s_name}`]: (h_env, k_context, k_rule, s_scope_frag) => {
Object.assign(k_rule.source, {
match: s_match_end,
scope: `punctuation.${s_scope_frag}.end.${h_env.syntax}`,
});
},
});
const H_MODIFIERS = {
// apply capitalization permutations of the given word in the appearing context
_case: (h_env, k_context, k_rule, s_word) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
return insert_cases(h_env, k_context, i_rule, k_rule, s_word, H_CASES);
},
// array-style of above
_cases: (h_env, k_context, k_rule, a_words) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// each keyword
for(let s_word of a_words) {
i_rule = insert_cases(h_env, k_context, i_rule, k_rule, s_word, H_CASES);
}
return i_rule;
},
_case_camel: (h_env, k_context, k_rule, s_word) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
return insert_cases(h_env, k_context, i_rule, k_rule, s_word, H_CASES_EXTENDED);
},
// array-style of above
_cases_camel: (h_env, k_context, k_rule, a_words) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// each keyword
for(let s_word of a_words) {
i_rule = insert_cases(h_env, k_context, i_rule, k_rule, s_word, H_CASES_EXTENDED);
}
return i_rule;
},
// insert all registered prefixe declaration productions in the appearing context
_registeredPrefixDeclarations: (h_env, k_context, k_rule, s_version) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// each prefix in environment
for(let [si_prefix, p_prefix_iri] of Object.entries(h_env.prefixes)) {
// create new rule for prefix mapping
k_context.insert(i_rule++, {
match: `(((${syntax.string_to_regex(si_prefix)})(:))\\s*(<)(${syntax.string_to_regex(p_prefix_iri)})(>))`,
captures: [
`meta.prefix-declaration.either.registered.${h_env.syntax}`,
`meta.prefix-declaration.${s_version}.namespace.${h_env.syntax}`,
`variable.other.readwrite.prefixed-name.namespace.prefix-declaration.${h_env.syntax}`,
`punctuation.separator.prefixed-name.prefix-declaration.${h_env.syntax}`,
// `meta.prefix-declaration.${s_version}.iri.${h_env.syntax}`,
`punctuation.definition.iri.begin.prefix-declaration.${h_env.syntax}`,
`string.unquoted.iri.prefix-declaration.${h_env.syntax}`,
`punctuation.definition.iri.end.prefix-declaration.${h_env.syntax}`,
],
pop: true,
});
}
return i_rule;
},
_prefixedName: (h_env, k_context, k_rule, w_spec) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert iri ref rules; update rule index
return insert_prefixed_name(h_env, k_context, i_rule, w_spec);
},
_iriRef: (h_env, k_context, k_rule, w_spec) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert iri ref rules; update rule index
return insert_iri_ref(h_env, k_context, i_rule, w_spec);
},
_blankNode: (h_env, k_context, k_rule, w_spec) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert blank node rules; return rule index
return insert_blank_node(h_env, k_context, i_rule, w_spec);
},
_namedNode: (h_env, k_context, k_rule, w_spec) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert iri ref rules; update rule index
i_rule = insert_iri_ref(h_env, k_context, i_rule, w_spec);
// insert prefixed name rules; update rule index
return insert_prefixed_name(h_env, k_context, i_rule, w_spec);
},
_node: (h_env, k_context, k_rule, w_spec) => {
// remove source rule from context
let i_rule = H_MODIFIERS._namedNode(h_env, k_context, k_rule, w_spec);
// insert blank node rules; return rule index
return insert_blank_node(h_env, k_context, i_rule, w_spec);
},
_throw: (h_env, k_context, k_rule, b_pop) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert other illegal pop
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{MAT_word_or_any_one_char}}'`.slice(1, -1),
scope: `invalid.illegal.token.expected.${k_context.id}.${h_env.syntax}`,
...(b_pop? {pop:b_pop}: {}),
});
return i_rule;
},
_throw_meta: (h_env, k_context, k_rule, s_meta_scope) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert other illegal pop
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{MAT_word_or_any_one_char}}'`.slice(1, -1),
scope: `meta.${s_meta_scope}.${h_env.syntax} invalid.illegal.token.expected.${k_context.id}.${h_env.syntax}`,
pop: true,
});
return i_rule;
},
_goto: (h_env, k_context, k_rule, w_context_goto) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// insert jump
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{PLA_anything}}'`.slice(1, -1),
set: w_context_goto,
});
return i_rule;
},
_meta: (h_env, k_context, k_rule, s_meta_scope) => {
let g_source = k_rule.source;
// push a meta content scope to back of stack
if(g_source.set) {
// coerce to array
if(!Array.isArray(g_source.set)) g_source.set = [g_source.set];
let s_context_meta = `${k_context.id}_META`;
// create new context
k_context.def.append(s_context_meta, [
{meta_include_prototype:false},
{meta_content_scope:s_meta_scope},
{
match: /* syntax: sublime-syntax.regex */ `'{{PLA_anything}}'`.slice(1, -1),
pop: true,
},
]);
// push to 'bottom' of stack
g_source.set.unshift(s_context_meta);
}
else {
throw new Error(`'_meta' used on ${k_context.id} context but no stack in rule`);
}
},
...punctuation('section', 'brace', '\\{', '\\}'),
...punctuation('definition', 'bracket', '\\[', '\\]'),
...punctuation('section', 'paren', '\\(', '\\)'),
_switch: (h_env, k_context, k_rule, a_cases) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// each case
for(let z_case of a_cases) {
// string
if('string' === typeof z_case) {
// cast to string
let s_case = z_case;
// insert rule
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{${s_case}_LOOKAHEAD}}'`.slice(1, -1),
set: s_case,
});
}
// object
else if('object' === typeof z_case) {
// cast to object
let h_case = z_case;
// 0th key
let s_token = Object.keys(h_case)[0];
// insert rule
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{${s_token}_LOOKAHEAD}}'`.slice(1, -1),
set: h_case[s_token],
});
}
// other?
else {
throw new TypeError(`unexpected type for _switch case: ${z_case}`);
}
}
return i_rule;
},
_switch_push: (h_env, k_context, k_rule, a_cases) => {
// remove source rule from context
let i_rule = k_context.drop(k_rule);
// each case
for(let z_case of a_cases) {
// string
if('string' === typeof z_case) {
// cast to string
let s_case = z_case;
// insert rule
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{${s_case}_LOOKAHEAD}}'`.slice(1, -1),
push: s_case,
});
}
// object
else if('object' === typeof z_case) {
// cast to object
let h_case = z_case;
// 0th key
let s_token = Object.keys(h_case)[0];
// insert rule
k_context.insert(i_rule++, {
match: /* syntax: sublime-syntax.regex */ `'{{${s_token}_LOOKAHEAD}}'`.slice(1, -1),
push: h_case[s_token],
});
}
// other?
else {
throw new TypeError(`unexpected type for _switch case: ${z_case}`);
}
}
return i_rule;
},
};
//
const load_syntax_source = (p_yaml) => {
// syntax def
let s_def_contents = fs.readFileSync(p_yaml);
let k_syntax = syntax.def.from_yaml_contents(s_def_contents, p_yaml);
// extends super source
if(k_syntax.other._extends) {
// resolve path
let p_super = path.resolve(path.dirname(p_yaml), k_syntax.other._extends);
// load super syntax
let k_syntax_super = load_syntax_source(p_super);
// extend this
k_syntax.extends(k_syntax_super);
// remove property
delete k_syntax.other._extends;
}
return k_syntax;
};
const H_MAGICS = {
pop(h_env, k_syntax, s_state) {
k_syntax.append(`${s_state}.POP`, [
{
include: s_state,
},
{
include: 'else_pop',
},
]);
},
star(h_env, k_syntax, s_state) {
k_syntax.append(`${s_state}.STAR`, [
{
match: `${s_state}_LOOKAHEAD`,
push: s_state,
},
{
include: 'else_pop',
},
]);
},
plus(h_env, k_syntax, s_state) {
k_syntax.append(`${s_state}.PLUS`, [
{
match: `${s_state}_LOOKAHEAD`,
set: [
`${s_state}.STAR`,
s_state,
],
},
{
match: /* syntax: sublime-syntax.regex */ `'{{MAT_word_or_any_one_char}}'`.slice(1, -1),
scope: `invalid.illegal.token.expected.${s_state}.STAR.${h_env.syntax}`,
...(b_pop? {pop:b_pop}: {}),
},
]);
if(!(`${s_state}.STAR` in k_syntax.contexts)) {
H_MAGICS.star(h_env, k_syntax, s_state);
}
},
};
//
const build_syntax = (h_env) => {
// syntax source
let k_syntax = load_syntax_source(process.argv[2]);
// set env syntax
let s_syntax = h_env.syntax = /\.([^.]+)$/.exec(k_syntax.other.scope)[1];
// each rule in syntax
let a_rules = [...k_syntax.rules()];
for(let [k_rule, k_context] of a_rules) {
// ref rule source
let g_source = k_rule.source;
// each modifier
for(let s_modifier in H_MODIFIERS) {
// rule source has modifier
if('object' === typeof g_source && s_modifier in g_source) {
// fetch value from source
let w_value = g_source[s_modifier];
// delete from object in case it is cloned for rule
delete g_source[s_modifier];
// apply transform
H_MODIFIERS[s_modifier](h_env, k_context, k_rule, w_value);
}
}
}
// magic states
{
let as_magic_states = new Set();
// each subrule in context
for(let [k_rule] of k_syntax.rules()) {
// each state
for(let s_state of k_rule.states()) {
// state name includes dot
if(s_state.includes('.')) {
as_magic_states.add(s_state);
}
}
}
// each magic state
for(let s_state_magic of as_magic_states) {
let [, s_state_src, s_magic] = /^(.+)\.(.+)$/.exec(s_state_magic);
// apply magic
H_MAGICS[s_magic.toLowerCase()](h_env, k_syntax, s_state_src);
}
}
// each rule (again)
a_rules = [...k_syntax.rules()];
for(let [k_rule] of a_rules) {
// replace placeholders
k_rule.scopes(s_scope => s_scope.replace(/\.SYNTAX/g, `.${s_syntax}`));
}
// validate
k_syntax.validate();
// return
return k_syntax;
};
module.exports = {
build() {
return new Promise((fk_resolve) => {
// consume prefix context from stdin
let s_prefixes_jsonld = '';
process.stdin.setEncoding('utf8');
process.stdin
.on('data', (s_chunk) => {
s_prefixes_jsonld += s_chunk;
})
.on('end', () => {
let g_jsonld = JSON.parse(s_prefixes_jsonld);
let h_prefixes = g_jsonld['@context'];
// build syntax
fk_resolve(build_syntax({
prefixes: h_prefixes,
}));
});
});
},
};
|
88e71e050111b8a452e2a4c848a9a3df451aeaa4
|
[
"JavaScript"
] | 2
|
JavaScript
|
sparql-generate/sublime-editor
|
05621d04fd2947d983f5cca952e683cfe5037d67
|
e749930e2607b83b012036c2215e7f2d03709eba
|
refs/heads/master
|
<file_sep>// Javascript for the Gallery page
// var fs = require('fs');
// var gallery = JSON.parse(fs.readFileSync('gallery.json'));
// var jQuery = require('jQuery');
var title = document.getElementById('gallery-title');
var images = document.getElementsByClassName("smallPic");
console.log(images);
title.onclick = function(e) {
e.preventDefault();
var form = document.getElementById('gallery-title-edit');
if (form.style.display == 'block') {
form.style.display = 'none';
}
else {
form.style.display = 'block';
}
};
function showImage(i) {
document.getElementById('largeImg').src = images[i].getAttribute("src");
document.getElementById('imgTitle').innerHTML = "<h2>" + images[i].getAttribute("data-title") + "</h2>";
document.getElementById('imgDesc').innerHTML = images[i].getAttribute("data-desc");
showLargeImagePanel();
unselectAll();
}
function showLargeImagePanel() {
document.getElementById('largeImgPanel').style.visibility = 'visible';
}
function unselectAll() {
if(document.selection) document.selection.empty();
if(window.getSelection) window.getSelection().removeAllRanges();
}
function hideMe(obj) {
obj.style.visibility = 'hidden';
}
|
304146492973224e449e8b82deef1cf83fb62f0a
|
[
"JavaScript"
] | 1
|
JavaScript
|
S17cis526/gallery-part-1-plexabyte
|
5a72de51c377c086b7386126fbb588be756ceea7
|
0fa3365d63755b0d755c1db3d38c594906e6d212
|
refs/heads/master
|
<file_sep># Sena-docとは(Overview)
Senaアプリケーションのドキュメント管理です。
## ライセンス(License)
Copyright 2016 yellow-man.yokohama
This software is licensed under the Apache 2 license, quoted below.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project 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.
<file_sep>-- MySQL Script generated by MySQL Workbench
-- 06/15/16 09:39:54
-- Model: New Model Version: 1.0
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema sena_db
-- -----------------------------------------------------
-- マスタ関連
-- -----------------------------------------------------
-- Schema sena_secure_db
-- -----------------------------------------------------
-- ユーザー関連
CREATE SCHEMA IF NOT EXISTS `sena_secure_db` ;
USE `sena_secure_db` ;
-- -----------------------------------------------------
-- Table `sena_secure_db`.`users`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_secure_db`.`users` ;
CREATE TABLE IF NOT EXISTS `sena_secure_db`.`users` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'ユーザーID',
`account_id` VARCHAR(20) BINARY NOT NULL COMMENT 'アカウントID',
`password` VARCHAR(45) BINARY NOT NULL COMMENT 'パスワード(暗号化)',
`nickname` VARCHAR(20) NOT NULL COMMENT 'ニックネーム',
`access_token` VARCHAR(128) BINARY NOT NULL COMMENT 'アクセストークン',
`use_datetime` DATETIME NOT NULL COMMENT '利用日時',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = 'ユーザー';
CREATE INDEX `i_users1` ON `sena_secure_db`.`users` (`delete_flg` ASC, `access_token` ASC);
CREATE INDEX `i_users2` ON `sena_secure_db`.`users` (`delete_flg` ASC, `account_id` ASC, `password` ASC);
CREATE INDEX `i_users3` ON `sena_secure_db`.`users` (`delete_flg` ASC, `account_id` ASC);
-- -----------------------------------------------------
-- Table `sena_secure_db`.`account_stocks`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_secure_db`.`account_stocks` ;
CREATE TABLE IF NOT EXISTS `sena_secure_db`.`account_stocks` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '口座銘柄ID',
`users_id` BIGINT NOT NULL COMMENT 'ユーザーID',
`acquisition_datetime` DATETIME NOT NULL COMMENT '取得日時',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`type` INT NOT NULL COMMENT '取引種別(1..国内株式、2..金額・株数指定取引、3..信用建玉(買建)、4..信用建玉(売建))',
`closing_date` DATE NULL COMMENT '大引けを表す日付(null..取引中、日付..取引終了(終値)、PTS夜間取引は考慮しない)',
`closing_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '大引けを表すフラグ(1:大引け、0:取引中)',
`amount` DECIMAL(25,10) NOT NULL COMMENT '保有株数(整数部:15桁、小数部:10桁)',
`average_cost` DECIMAL(25,10) NOT NULL COMMENT '平均取得単価(整数部:15桁、小数部:10桁)',
`current_value` DECIMAL(20,5) NOT NULL COMMENT '現在値(整数部:15桁、小数部:5桁)',
`market_value` DECIMAL(25,10) NOT NULL COMMENT '時価評価額(「保有株数 * 現在値」で算出された値、整数部:15桁、小数部:10桁)',
`profit_loss` DECIMAL(25,10) NOT NULL COMMENT '評価損益(「(保有株数 * 現在値) - (保有株数 * 平均取得単価)」で算出された値、整数部:15桁、小数部:10桁)',
`profit_loss_rate` DECIMAL(10,2) NOT NULL COMMENT '損益率(「(評価損益 / (保有株数 * 現在値)) * 100」で算出された値、整数部:8桁、小数部:2桁)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`, `users_id`))
ENGINE = InnoDB
COMMENT = '口座銘柄';
CREATE INDEX `fk_account_stocks_users_idx` ON `sena_secure_db`.`account_stocks` (`users_id` ASC);
CREATE INDEX `fk_account_stocks_stocks1_idx` ON `sena_secure_db`.`account_stocks` (`stock_code` ASC);
CREATE INDEX `i_account_stocks1` ON `sena_secure_db`.`account_stocks` (`delete_flg` ASC, `users_id` ASC, `closing_flg` ASC);
-- -----------------------------------------------------
-- Table `sena_secure_db`.`account_summaries`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_secure_db`.`account_summaries` ;
CREATE TABLE IF NOT EXISTS `sena_secure_db`.`account_summaries` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '口座サマリーID',
`users_id` BIGINT NOT NULL COMMENT 'ユーザーID',
`acquisition_datetime` DATETIME NOT NULL COMMENT '取得日時',
`closing_date` DATE NULL COMMENT '大引けを表す日付(null..取引中、日付..取引終了(終値)、PTS夜間取引は考慮しない)',
`closing_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '大引けを表すフラグ(1:大引け、0:取引中)',
`free_margin` INT NULL COMMENT '信用建余力',
`stock_purchased` INT NULL COMMENT '現引可能額',
`initial_margin_cache` INT NULL COMMENT '委託保証金現金',
`initial_margin_value` INT NULL COMMENT '代用有価証券評価額合計',
`payment_expenses_total` INT NULL COMMENT '評価損・決済損益・支払諸経費等合計',
`initial_margin` INT NULL COMMENT '実質保証金',
`open_interest` INT NULL COMMENT '建代金合計',
`maintenance_requirement` DECIMAL(10,2) NULL COMMENT '委託保証金率',
`ref_maintenance_requirement` DECIMAL(10,2) NULL COMMENT '参考委託保証金率',
`free_cache` INT NOT NULL COMMENT '買付余力',
`free_cache_etc` INT NOT NULL COMMENT '現金残高等',
`asset_value` DECIMAL(20,5) NOT NULL COMMENT '株式',
`margin_profit_loss` INT NOT NULL COMMENT '建玉評価損益額',
`account_balance` DECIMAL(20,5) NOT NULL COMMENT '計',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`, `users_id`))
ENGINE = InnoDB
COMMENT = '口座サマリー';
CREATE INDEX `fk_account_summaries_users1_idx` ON `sena_secure_db`.`account_summaries` (`users_id` ASC);
CREATE INDEX `i_account_summaries1` ON `sena_secure_db`.`account_summaries` (`delete_flg` ASC, `users_id` ASC, `closing_flg` ASC);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>-- MySQL Script generated by MySQL Workbench
-- 06/15/16 09:39:35
-- Model: New Model Version: 1.0
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema sena_db
-- -----------------------------------------------------
-- マスタ関連
CREATE SCHEMA IF NOT EXISTS `sena_db` DEFAULT CHARACTER SET utf8mb4 ;
-- -----------------------------------------------------
-- Schema sena_secure_db
-- -----------------------------------------------------
-- ユーザー関連
USE `sena_db` ;
-- -----------------------------------------------------
-- Table `sena_db`.`stocks`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_db`.`stocks` ;
CREATE TABLE IF NOT EXISTS `sena_db`.`stocks` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '銘柄ID',
`date` DATE NOT NULL COMMENT '取得日',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`stock_name` VARCHAR(128) NOT NULL COMMENT '銘柄名',
`market` VARCHAR(64) NULL COMMENT '市場名',
`topix_sector` VARCHAR(64) NULL COMMENT '業種分類',
`share_unit` INT NULL COMMENT '単元株数(単元制度なし:-1)',
`nikkei225_flg` TINYINT(1) NULL DEFAULT 0 COMMENT '日経225採用銘柄フラグ(1:採用銘柄、0:未採用銘柄)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = '銘柄';
CREATE INDEX `i_stocks1` ON `sena_db`.`stocks` (`delete_flg` ASC, `date` ASC, `stock_code` ASC);
-- -----------------------------------------------------
-- Table `sena_db`.`company_schedules`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_db`.`company_schedules` ;
CREATE TABLE IF NOT EXISTS `sena_db`.`company_schedules` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '企業スケジュールID',
`settlement_date` DATE NOT NULL COMMENT '決算発表日',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`settlement` VARCHAR(64) NOT NULL COMMENT '決算期(サンプル:4月期、12月期)',
`settlement_types_id` INT NOT NULL COMMENT '決算種別(サンプル:1..第1、2..第2、3..第3、4..本)',
`reg_calendar_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'カレンダー登録済みフラグ(1:登録済み、0:未登録)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = '企業スケジュール';
CREATE INDEX `fk_company_schedules_stocks_idx` ON `sena_db`.`company_schedules` (`stock_code` ASC);
CREATE UNIQUE INDEX `uk_company_schedules` ON `sena_db`.`company_schedules` (`settlement_date` ASC, `stock_code` ASC);
CREATE INDEX `i_company_schedules1` ON `sena_db`.`company_schedules` (`delete_flg` ASC, `settlement_date` ASC, `stock_code` ASC);
CREATE INDEX `i_company_schedules2` ON `sena_db`.`company_schedules` (`delete_flg` ASC, `stock_code` ASC, `settlement_date` ASC);
CREATE INDEX `i_company_schedules3` ON `sena_db`.`company_schedules` (`delete_flg` ASC, `reg_calendar_flg` ASC);
-- -----------------------------------------------------
-- Table `sena_db`.`debit_balances`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_db`.`debit_balances` ;
CREATE TABLE IF NOT EXISTS `sena_db`.`debit_balances` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '信用残ID',
`release_date` DATE NOT NULL COMMENT '公表日',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`margin_selling_balance` INT NOT NULL COMMENT '信用売残(ハイフン等、数値に変換できない場合:-1)',
`margin_debt_balance` INT NOT NULL COMMENT '信用買残(ハイフン等、数値に変換できない場合:-1)',
`ratio_margin_balance` DECIMAL(10,2) NOT NULL COMMENT '信用倍率(整数部:8桁、小数部:2桁、ハイフン等、数値に変換できない場合:-1)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = '信用残';
CREATE INDEX `fk_debit_balances_stocks1_idx` ON `sena_db`.`debit_balances` (`stock_code` ASC);
CREATE UNIQUE INDEX `uk_debit_balances` ON `sena_db`.`debit_balances` (`release_date` ASC, `stock_code` ASC);
CREATE INDEX `i_debit_balances1` ON `sena_db`.`debit_balances` (`delete_flg` ASC, `release_date` ASC, `stock_code` ASC);
CREATE INDEX `i_debit_balances2` ON `sena_db`.`debit_balances` (`delete_flg` ASC, `stock_code` ASC, `release_date` ASC);
-- -----------------------------------------------------
-- Table `sena_db`.`indicators`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_db`.`indicators` ;
CREATE TABLE IF NOT EXISTS `sena_db`.`indicators` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '指標ID',
`date` DATE NOT NULL COMMENT '取得日',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`dividend_yield` DECIMAL(10,2) NULL COMMENT '配当利回り(整数部:8桁、小数部:2桁)',
`price_earnings_ratio` DECIMAL(10,2) NULL COMMENT '株価収益率(PER、整数部:8桁、小数部:2桁)',
`price_book_value_ratio` DECIMAL(10,2) NULL COMMENT '株価純資産倍率(PBR、整数部:8桁、小数部:2桁)',
`earnings_per_share` DECIMAL(10,2) NULL COMMENT '1株利益(EPS、整数部:8桁、小数部:2桁)',
`book_value_per_share` DECIMAL(10,2) NULL COMMENT '1株当たり純資産(BPS、整数部:8桁、小数部:2桁)',
`return_on_equity` DECIMAL(25,20) NULL COMMENT '株主資本利益率(ROE、整数部:5桁、小数部:20桁)',
`capital_ratio` DECIMAL(10,2) NULL COMMENT '自己資本比率(整数部:8桁、小数部:2桁)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = '指標';
CREATE INDEX `fk_debit_balances_copy1_stocks1_idx` ON `sena_db`.`indicators` (`stock_code` ASC);
CREATE UNIQUE INDEX `uk_indicators` ON `sena_db`.`indicators` (`date` ASC, `stock_code` ASC);
CREATE INDEX `i_indicators1` ON `sena_db`.`indicators` (`delete_flg` ASC, `date` ASC, `stock_code` ASC);
-- -----------------------------------------------------
-- Table `sena_db`.`finances`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `sena_db`.`finances` ;
CREATE TABLE IF NOT EXISTS `sena_db`.`finances` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '財務ID',
`year` INT NOT NULL COMMENT '決算年',
`settlement_types_id` INT NOT NULL COMMENT '決算種別(サンプル:1..第1、2..第2、3..第3、4..本)',
`stock_code` INT NOT NULL COMMENT '銘柄コード',
`sales` INT NULL COMMENT '売上高',
`operating_profit` INT NULL COMMENT '営業益',
`net_profit` INT NULL COMMENT '純利益',
`sales_rate` DECIMAL(30,20) NULL COMMENT '売上高(前年比、整数部:10桁、小数部:20桁)',
`operating_profit_rate` DECIMAL(30,20) NULL COMMENT '営業益(前年比、整数部:10桁、小数部:20桁)',
`net_profit_rate` DECIMAL(30,20) NULL COMMENT '純利益(前年比、整数部:10桁、小数部:20桁)',
`created` DATETIME NOT NULL COMMENT '作成日時',
`modified` DATETIME NOT NULL COMMENT '更新日時',
`delete_flg` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '削除フラグ(1:削除、0:未削除)',
PRIMARY KEY (`id`))
ENGINE = InnoDB
COMMENT = '財務';
CREATE INDEX `fk_finances_stocks1_idx` ON `sena_db`.`finances` (`stock_code` ASC);
CREATE UNIQUE INDEX `uk_finances` ON `sena_db`.`finances` (`year` ASC, `settlement_types_id` ASC, `stock_code` ASC);
CREATE INDEX `i_finances1` ON `sena_db`.`finances` (`delete_flg` ASC, `year` ASC, `settlement_types_id` ASC, `stock_code` ASC);
CREATE INDEX `i_finances2` ON `sena_db`.`finances` (`delete_flg` ASC, `stock_code` ASC, `year` ASC, `settlement_types_id` ASC);
CREATE INDEX `i_finances3` ON `sena_db`.`finances` (`delete_flg` ASC, `stock_code` ASC, `settlement_types_id` ASC);
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ja">
<head>
<!-- Generated by javadoc (1.8.0_73) on Sat Feb 04 16:43:01 JST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>直列化された形式 (Sena-core(1.0.0) アプリケーション API仕様)</title>
<meta name="date" content="2017-02-04">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="\u76F4\u5217\u5316\u3055\u308C\u305F\u5F62\u5F0F (Sena-core\uFF081.0.0\uFF09 \u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3 API\u4ED5\u69D8)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>ブラウザのJavaScriptが無効になっています。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="ナビゲーション・リンクをスキップ">ナビゲーション・リンクをスキップ</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="ナビゲーション">
<li><a href="overview-summary.html">概要</a></li>
<li>パッケージ</li>
<li>クラス</li>
<li><a href="overview-tree.html">階層ツリー</a></li>
<li><a href="deprecated-list.html">非推奨</a></li>
<li><a href="index-all.html">索引</a></li>
<li><a href="help-doc.html">ヘルプ</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>前</li>
<li>次</li>
</ul>
<ul class="navList">
<li><a href="index.html?serialized-form.html" target="_top">フレーム</a></li>
<li><a href="serialized-form.html" target="_top">フレームなし</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">すべてのクラス</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="直列化された形式" class="title">直列化された形式</h1>
</div>
<div class="serializedFormContainer">
<ul class="blockList">
<li class="blockList">
<h2 title="パッケージ">パッケージ yokohama.yellow_man.sena.core.components.google</h2>
<ul class="blockList">
<li class="blockList"><a name="yokohama.yellow_man.sena.core.components.google.GoogleApiException">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/components/google/GoogleApiException.html" title="yokohama.yellow_man.sena.core.components.google内のクラス">yokohama.yellow_man.sena.core.components.google.GoogleApiException</a> extends java.lang.Exception implements Serializable</h3>
</li>
</ul>
</li>
<li class="blockList">
<h2 title="パッケージ">パッケージ yokohama.yellow_man.sena.core.models</h2>
<ul class="blockList">
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.AppModel">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.AppModel</a> extends play.db.ebean.Model implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>id</h4>
<pre>java.lang.Long id</pre>
<div class="block">プライマリーキー</div>
</li>
<li class="blockList">
<h4>deleteFlg</h4>
<pre>java.lang.Boolean deleteFlg</pre>
<div class="block">削除フラグ</div>
</li>
<li class="blockList">
<h4>created</h4>
<pre>java.util.Date created</pre>
<div class="block">作成日時</div>
</li>
<li class="blockListLast">
<h4>modified</h4>
<pre>java.util.Date modified</pre>
<div class="block">更新日時</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.CompanySchedules">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/CompanySchedules.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.CompanySchedules</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>settlementDate</h4>
<pre>java.util.Date settlementDate</pre>
<div class="block">決算発表日</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>settlement</h4>
<pre>java.lang.String settlement</pre>
<div class="block">決算期(サンプル:4月期、12月期)</div>
</li>
<li class="blockList">
<h4>settlementTypesId</h4>
<pre>java.lang.Integer settlementTypesId</pre>
<div class="block">決算種別(サンプル:1..第1、2..第2、3..第3、4..本)</div>
</li>
<li class="blockListLast">
<h4>regCalendarFlg</h4>
<pre>java.lang.Boolean regCalendarFlg</pre>
<div class="block">カレンダー登録済みフラグ(1:登録済み、0:未登録)</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.DebitBalances">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/DebitBalances.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.DebitBalances</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>releaseDate</h4>
<pre>java.util.Date releaseDate</pre>
<div class="block">公表日</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>marginSellingBalance</h4>
<pre>java.lang.Integer marginSellingBalance</pre>
<div class="block">信用売残(ハイフン等、数値に変換できない場合:-1)</div>
</li>
<li class="blockList">
<h4>marginDebtBalance</h4>
<pre>java.lang.Integer marginDebtBalance</pre>
<div class="block">信用買残(ハイフン等、数値に変換できない場合:-1)</div>
</li>
<li class="blockListLast">
<h4>ratioMarginBalance</h4>
<pre>java.math.BigDecimal ratioMarginBalance</pre>
<div class="block">信用倍率(整数部:8桁、小数部:2桁、ハイフン等、数値に変換できない場合:-1)</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.Finances">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/Finances.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.Finances</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>year</h4>
<pre>java.lang.Integer year</pre>
<div class="block">決算年</div>
</li>
<li class="blockList">
<h4>settlementTypesId</h4>
<pre>java.lang.Integer settlementTypesId</pre>
<div class="block">決算種別(サンプル:1..第1、2..第2、3..第3、4..本)</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>sales</h4>
<pre>java.lang.Integer sales</pre>
<div class="block">売上高</div>
</li>
<li class="blockList">
<h4>operatingProfit</h4>
<pre>java.lang.Integer operatingProfit</pre>
<div class="block">営業益</div>
</li>
<li class="blockList">
<h4>netProfit</h4>
<pre>java.lang.Integer netProfit</pre>
<div class="block">純利益</div>
</li>
<li class="blockList">
<h4>salesRate</h4>
<pre>java.math.BigDecimal salesRate</pre>
<div class="block">売上高(前年比、整数部:10桁、小数部:20桁)</div>
</li>
<li class="blockList">
<h4>operatingProfitRate</h4>
<pre>java.math.BigDecimal operatingProfitRate</pre>
<div class="block">営業益(前年比、整数部:10桁、小数部:20桁)</div>
</li>
<li class="blockListLast">
<h4>netProfitRate</h4>
<pre>java.math.BigDecimal netProfitRate</pre>
<div class="block">純利益(前年比、整数部:10桁、小数部:20桁)</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.Indicators">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/Indicators.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.Indicators</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>date</h4>
<pre>java.util.Date date</pre>
<div class="block">取得日</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>dividendYield</h4>
<pre>java.math.BigDecimal dividendYield</pre>
<div class="block">配当利回り(整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>priceEarningsRatio</h4>
<pre>java.math.BigDecimal priceEarningsRatio</pre>
<div class="block">株価収益率(PER、整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>priceBookValueRatio</h4>
<pre>java.math.BigDecimal priceBookValueRatio</pre>
<div class="block">株価純資産倍率(PBR、整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>earningsPerShare</h4>
<pre>java.math.BigDecimal earningsPerShare</pre>
<div class="block">1株利益(EPS、整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>bookValuePerShare</h4>
<pre>java.math.BigDecimal bookValuePerShare</pre>
<div class="block">1株当たり純資産(BPS、整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>returnOnEquity</h4>
<pre>java.math.BigDecimal returnOnEquity</pre>
<div class="block">株主資本利益率(ROE、整数部:5桁、小数部:20桁)</div>
</li>
<li class="blockListLast">
<h4>capitalRatio</h4>
<pre>java.math.BigDecimal capitalRatio</pre>
<div class="block">自己資本比率(整数部:8桁、小数部:2桁)</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.Stocks">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/Stocks.html" title="yokohama.yellow_man.sena.core.models内のクラス">yokohama.yellow_man.sena.core.models.Stocks</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>date</h4>
<pre>java.util.Date date</pre>
<div class="block">取得日</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>stockName</h4>
<pre>java.lang.String stockName</pre>
<div class="block">銘柄名</div>
</li>
<li class="blockList">
<h4>market</h4>
<pre>java.lang.String market</pre>
<div class="block">市場名</div>
</li>
<li class="blockList">
<h4>topixSector</h4>
<pre>java.lang.String topixSector</pre>
<div class="block">業種分類</div>
</li>
<li class="blockList">
<h4>shareUnit</h4>
<pre>java.lang.Integer shareUnit</pre>
<div class="block">単元株数</div>
</li>
<li class="blockListLast">
<h4>nikkei225Flg</h4>
<pre>java.lang.Boolean nikkei225Flg</pre>
<div class="block">日経225採用銘柄フラグ(1:採用銘柄、0:未採用銘柄)</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList">
<h2 title="パッケージ">パッケージ yokohama.yellow_man.sena.core.models.ext</h2>
<ul class="blockList">
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.ext.CompanySchedulesWithStocks">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/ext/CompanySchedulesWithStocks.html" title="yokohama.yellow_man.sena.core.models.ext内のクラス">yokohama.yellow_man.sena.core.models.ext.CompanySchedulesWithStocks</a> extends <a href="yokohama/yellow_man/sena/core/models/CompanySchedules.html" title="yokohama.yellow_man.sena.core.models内のクラス">CompanySchedules</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockListLast">
<h4>stocks</h4>
<pre><a href="yokohama/yellow_man/sena/core/models/Stocks.html" title="yokohama.yellow_man.sena.core.models内のクラス">Stocks</a> stocks</pre>
<div class="block">銘柄(stocks)モデル</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList">
<h2 title="パッケージ">パッケージ yokohama.yellow_man.sena.core.models.secure</h2>
<ul class="blockList">
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.secure.AccountStocks">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/secure/AccountStocks.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">yokohama.yellow_man.sena.core.models.secure.AccountStocks</a> extends <a href="yokohama/yellow_man/sena/core/models/secure/AppSecureModel.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">AppSecureModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>usersId</h4>
<pre>java.lang.Long usersId</pre>
<div class="block">ユーザーID</div>
</li>
<li class="blockList">
<h4>acquisitionDatetime</h4>
<pre>java.util.Date acquisitionDatetime</pre>
<div class="block">取得日時</div>
</li>
<li class="blockList">
<h4>stockCode</h4>
<pre>java.lang.Integer stockCode</pre>
<div class="block">銘柄コード</div>
</li>
<li class="blockList">
<h4>type</h4>
<pre>java.lang.Integer type</pre>
<div class="block">取引種別(1..国内株式、2..金額・株数指定取引、3..信用建玉(買建)、4..信用建玉(売建))</div>
</li>
<li class="blockList">
<h4>closingDate</h4>
<pre>java.util.Date closingDate</pre>
<div class="block">大引けを表す日付(null..取引中、日付..取引終了(終値)、PTS夜間取引は考慮しない)</div>
</li>
<li class="blockList">
<h4>closingFlg</h4>
<pre>java.lang.Boolean closingFlg</pre>
<div class="block">大引けを表すフラグ(1:大引け、0:取引中)</div>
</li>
<li class="blockList">
<h4>amount</h4>
<pre>java.math.BigDecimal amount</pre>
<div class="block">保有株数(整数部:15桁、小数部:10桁)</div>
</li>
<li class="blockList">
<h4>averageCost</h4>
<pre>java.math.BigDecimal averageCost</pre>
<div class="block">平均取得単価(整数部:15桁、小数部:10桁)</div>
</li>
<li class="blockList">
<h4>currentValue</h4>
<pre>java.math.BigDecimal currentValue</pre>
<div class="block">現在値(整数部:15桁、小数部:5桁)</div>
</li>
<li class="blockList">
<h4>marketValue</h4>
<pre>java.math.BigDecimal marketValue</pre>
<div class="block">時価評価額(「保有株数 * 現在値」で算出された値、整数部:15桁、小数部:10桁)</div>
</li>
<li class="blockList">
<h4>profitLoss</h4>
<pre>java.math.BigDecimal profitLoss</pre>
<div class="block">評価損益(「(保有株数 * 現在値) - (保有株数 * 平均取得単価)」で算出された値、整数部:15桁、小数部:10桁)</div>
</li>
<li class="blockListLast">
<h4>profitLossRate</h4>
<pre>java.math.BigDecimal profitLossRate</pre>
<div class="block">損益率(「(評価損益 / (保有株数 * 現在値)) * 100」で算出された値、整数部:8桁、小数部:2桁)</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.secure.AccountSummaries">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/secure/AccountSummaries.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">yokohama.yellow_man.sena.core.models.secure.AccountSummaries</a> extends <a href="yokohama/yellow_man/sena/core/models/secure/AppSecureModel.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">AppSecureModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>usersId</h4>
<pre>java.lang.Long usersId</pre>
<div class="block">ユーザーID</div>
</li>
<li class="blockList">
<h4>acquisitionDatetime</h4>
<pre>java.util.Date acquisitionDatetime</pre>
<div class="block">取得日時</div>
</li>
<li class="blockList">
<h4>closingDate</h4>
<pre>java.util.Date closingDate</pre>
<div class="block">大引けを表す日付(null..取引中、日付..取引終了(終値)、PTS夜間取引は考慮しない)</div>
</li>
<li class="blockList">
<h4>closingFlg</h4>
<pre>java.lang.Boolean closingFlg</pre>
<div class="block">大引けを表すフラグ(1:大引け、0:取引中)</div>
</li>
<li class="blockList">
<h4>freeMargin</h4>
<pre>java.lang.Long freeMargin</pre>
<div class="block">信用建余力</div>
</li>
<li class="blockList">
<h4>stockPurchased</h4>
<pre>java.lang.Long stockPurchased</pre>
<div class="block">現引可能額</div>
</li>
<li class="blockList">
<h4>initialMarginCache</h4>
<pre>java.lang.Long initialMarginCache</pre>
<div class="block">委託保証金現金</div>
</li>
<li class="blockList">
<h4>initialMarginValue</h4>
<pre>java.lang.Long initialMarginValue</pre>
<div class="block">代用有価証券評価額合計</div>
</li>
<li class="blockList">
<h4>paymentExpensesTotal</h4>
<pre>java.lang.Long paymentExpensesTotal</pre>
<div class="block">評価損・決済損益・支払諸経費等合計</div>
</li>
<li class="blockList">
<h4>initialMargin</h4>
<pre>java.lang.Long initialMargin</pre>
<div class="block">実質保証金</div>
</li>
<li class="blockList">
<h4>openInterest</h4>
<pre>java.lang.Long openInterest</pre>
<div class="block">建代金合計</div>
</li>
<li class="blockList">
<h4>maintenanceRequirement</h4>
<pre>java.math.BigDecimal maintenanceRequirement</pre>
<div class="block">委託保証金率(整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>refMaintenanceRequirement</h4>
<pre>java.math.BigDecimal refMaintenanceRequirement</pre>
<div class="block">参考委託保証金率(整数部:8桁、小数部:2桁)</div>
</li>
<li class="blockList">
<h4>freeCache</h4>
<pre>java.lang.Long freeCache</pre>
<div class="block">買付余力</div>
</li>
<li class="blockList">
<h4>freeCacheEtc</h4>
<pre>java.lang.Long freeCacheEtc</pre>
<div class="block">現金残高等</div>
</li>
<li class="blockList">
<h4>assetValue</h4>
<pre>java.lang.Long assetValue</pre>
<div class="block">株式</div>
</li>
<li class="blockList">
<h4>marginProfitLoss</h4>
<pre>java.lang.Long marginProfitLoss</pre>
<div class="block">建玉評価損益額</div>
</li>
<li class="blockListLast">
<h4>accountBalance</h4>
<pre>java.lang.Long accountBalance</pre>
<div class="block">計</div>
</li>
</ul>
</li>
</ul>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.secure.AppSecureModel">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/secure/AppSecureModel.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">yokohama.yellow_man.sena.core.models.secure.AppSecureModel</a> extends <a href="yokohama/yellow_man/sena/core/models/AppModel.html" title="yokohama.yellow_man.sena.core.models内のクラス">AppModel</a> implements Serializable</h3>
</li>
<li class="blockList"><a name="yokohama.yellow_man.sena.core.models.secure.Users">
<!-- -->
</a>
<h3>Class <a href="yokohama/yellow_man/sena/core/models/secure/Users.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">yokohama.yellow_man.sena.core.models.secure.Users</a> extends <a href="yokohama/yellow_man/sena/core/models/secure/AppSecureModel.html" title="yokohama.yellow_man.sena.core.models.secure内のクラス">AppSecureModel</a> implements Serializable</h3>
<ul class="blockList">
<li class="blockList">
<h3>直列化されたフィールド</h3>
<ul class="blockList">
<li class="blockList">
<h4>accountId</h4>
<pre>java.lang.String accountId</pre>
<div class="block">アカウントID</div>
</li>
<li class="blockList">
<h4>password</h4>
<pre>java.lang.String password</pre>
<div class="block">パスワード</div>
</li>
<li class="blockList">
<h4>nickname</h4>
<pre>java.lang.String nickname</pre>
<div class="block">ニックネーム</div>
</li>
<li class="blockList">
<h4>accessToken</h4>
<pre>java.lang.String accessToken</pre>
<div class="block">アクセストークン</div>
</li>
<li class="blockListLast">
<h4>useDatetime</h4>
<pre>java.util.Date useDatetime</pre>
<div class="block">利用日時</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="ナビゲーション・リンクをスキップ">ナビゲーション・リンクをスキップ</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="ナビゲーション">
<li><a href="overview-summary.html">概要</a></li>
<li>パッケージ</li>
<li>クラス</li>
<li><a href="overview-tree.html">階層ツリー</a></li>
<li><a href="deprecated-list.html">非推奨</a></li>
<li><a href="index-all.html">索引</a></li>
<li><a href="help-doc.html">ヘルプ</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>前</li>
<li>次</li>
</ul>
<ul class="navList">
<li><a href="index.html?serialized-form.html" target="_top">フレーム</a></li>
<li><a href="serialized-form.html" target="_top">フレームなし</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">すべてのクラス</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>-- Creation a database.
CREATE DATABASE `sena_secure_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
-- Creation an user.for the database.
GRANT ALL PRIVILEGES ON `sena_secure_db`.* TO username@localhost IDENTIFIED BY '<PASSWORD>';
GRANT ALL PRIVILEGES ON `sena_secure_db`.* TO username@'%' IDENTIFIED BY '<PASSWORD>';
-- Reflects the all privileges as above
FLUSH PRIVILEGES;
|
38afe30ee6cdb7935cc85650438b8888fbac3554
|
[
"Markdown",
"SQL",
"HTML"
] | 5
|
Markdown
|
yellow-man/sena-doc
|
27d675adf61fabdf331eb3981ff6c61684be60db
|
4a284652b3688ad6b590055b3a0ebcd01c5561e9
|
refs/heads/master
|
<repo_name>biswajeet163/Face-Detector<file_sep>/Taking_only_small_face.py
import numpy
import cv2
import os
path='E:\\p3\\CODING P#\\PROJECTS\\face\\data\\';
"""
print ("Enter Person Name:")
x=raw_input()
"""
camera=cv2.VideoCapture(0);
#camera=cv2.VideoCapture(r'C:\\Users\\Bishu\\Desktop\\FM\\me.mp4')
#os.mkdir('C:/Users/Bishu/Desktop/FM/images/'+x);
f_cascade=cv2.CascadeClassifier('C://Users//Bishu//Desktop//FM//cascades//data//haarcascade_frontalface_alt.xml')
j=1000
while(1):
ret , frame = camera.read()
gray=cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
faces = f_cascade.detectMultiScale(gray , scaleFactor=1.4 ,minNeighbors=1)
for(x,y,w,h) in faces:
print (x,y,w,h)
start_h =x + h
end_w =y +w
color=(255 , 0 , 0)
stroke=2
cv2.rectangle(frame , ( x , y ) , ( start_h , end_w ) , color , stroke )
region_of_interest_gray=gray[y+20 : y+h-10 , x+10 : x+w-10]
img_cap="Biswa_"+str(j)+".jpg"
j=j+1
#region_of_interest_gray = cv2.blur(region_of_interest_gray,(5,5))
cv2.imwrite(path+img_cap , region_of_interest_gray )
cv2.imshow('f',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break;
camera.release();
cv2.destroyAllWindows();
<file_sep>/only_face_baki_blur_1.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 7 15:10:12 2019
@author: Bishu
"""
import numpy
import cv2
import os
path='E:\\p3\\CODING P#\\PROJECTS\\face\\data\\';
camera=cv2.VideoCapture(0);
#camera=cv2.VideoCapture(r'C:\\Users\\Bishu\\Desktop\\FM\\me.mp4')
#os.mkdir('C:/Users/Bishu/Desktop/FM/images/'+x);
f_cascade=cv2.CascadeClassifier('C://Users//Bishu//Desktop//FM//cascades//data//haarcascade_frontalface_alt.xml')
j=1
while(1):
ret , frame = camera.read()
gray=cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
#faces = f_cascade.detectMultiScale(gray , scaleFactor=1.4 ,minNeighbors=1)
m , n =gray.shape;
print(str(m)+" "+str(n));
"""
for(x,y,w,h) in faces:
print (x,y,w,h)
region_of_interest_gray=gray[y+20 : y+h-10 , x+10 : x+w-10]
start_h =x + h
end_w =y +w
color=(255 , 0 , 0)
stroke=2
cv2.rectangle(frame , ( x , y ) , ( start_h , end_w ) , color , stroke )
for i in range(m):
for j in range(n):
if(i<y and i>y+h and j<x and j>x+w):
gray[i:j]=0;
#region_of_interest_gray=gray[y+20 : y+h-10 , x+10 : x+w-10]
img_cap="Biswa_"+str(j)+".jpg"
j=j+1
cv2.imwrite(path+img_cap , gray )
"""
#cv2.imshow('f',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break;
camera.release();
cv2.destroyAllWindows();
<file_sep>/only_face_baki_blur.py
import numpy
import cv2
import os
path='E:\\p3\\CODING P#\\PROJECTS\\face\\data\\';
camera=cv2.VideoCapture(0);
#camera=cv2.VideoCapture(r'C:\\Users\\Bishu\\Desktop\\FM\\me.mp4')
#os.mkdir('C:/Users/Bishu/Desktop/FM/images/'+x);
f_cascade=cv2.CascadeClassifier('C://Users//Bishu//Desktop//FM//cascades//data//haarcascade_frontalface_alt.xml')
jj=100
while(1):
ret , frame = camera.read()
gray=cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
faces = f_cascade.detectMultiScale(gray , scaleFactor=1.4 ,minNeighbors=1)
m ,n =gray.shape;
print(str(m)+" "+str(n));
for(x,y,w,h) in faces:
#print (x,y,w,h)
#region_of_interest_gray=gray[y+20 : y+h-10 , x+10 : x+w-10]
start_h =x + h
end_w =y +w
color=(255 , 0 , 0)
stroke=2
cv2.rectangle(frame , ( x , y ) , ( start_h , end_w ) , color , stroke )
blr_1,blr_2 = 20,20;
blr_11,blr_22 = 15,15;
gray[0:y , :] = cv2.blur(gray[0:y , :] ,(blr_1,blr_2))
gray[y+h: , :] = cv2.blur(gray[y+h: m, :] ,(blr_1,blr_2))
gray[ : , 0:x] = cv2.blur(gray[ : , 0:x] ,(blr_11,blr_22))
gray[:, x+w:n] = cv2.blur(gray[:, x+w:n] ,(blr_11,blr_22))
#image[y:y+h, x:x+w] = cv2.blur(image[y:y+h, x:x+w] ,(23,23))
#gray = cv2.blur(gray[y:y+h, x:x+w] ,(23,23),4000)
img_cap="Biswa_"+str(jj)+".jpg"
jj=jj+1
cv2.imwrite(path+img_cap , gray )
cv2.imshow('f',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break;
camera.release();
cv2.destroyAllWindows();
<file_sep>/click.py
import numpy
import cv2
import os
path='E:\\p3\\CODING P#\\PROJECTS\\face\\data\\';
camera=cv2.VideoCapture(0);
#camera=cv2.VideoCapture(r'C:\\Users\\Bishu\\Desktop\\FM\\me.mp4')
#os.mkdir('C:/Users/Bishu/Desktop/FM/images/'+x);
j=1
while(1):
ret , frame = camera.read()
#path = 'C:/Users/Bishu/Desktop/FM/images/'+x ;
img_cap=str(j)+".jpg"
j=j+1
cv2.imwrite(os.path.join(path , img_cap), frame)
cv2.imshow('BISWAJEET',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):file:///E:/p3/CODING P%23/PROJECTS/face/New folder/eye_detect1.py
file:///E:/p3/CODING P%23/PROJECTS/face/New folder/eyeBlink.py
file:///E:/p3/CODING P%23/PROJECTS/face/New folder/faceDetect_dlib.py
break;
camera.release();
cv2.destroyAllWindows();
print ("Hello Lord");
print ("Images Captured %d"%j);
<file_sep>/README.md
# Face-Detector using opencv python dlib library
<file_sep>/face.py
import numpy
import cv2
import os
"""
print ("Enter Person Name:")
x=raw_input()
"""
camera=cv2.VideoCapture(0);
#camera=cv2.VideoCapture(r'C:\\Users\\Bishu\\Desktop\\FM\\me.mp4')
#os.mkdir('C:/Users/Bishu/Desktop/FM/images/'+x);
f_cascade=cv2.CascadeClassifier('C://Users//Bishu//Desktop//FM//cascades//data//haarcascade_frontalface_alt.xml')
j=1
while(1):
ret , frame = camera.read()
gray=cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
faces = f_cascade.detectMultiScale(gray , scaleFactor=1.4 ,minNeighbors=1)
for(x,y,w,h) in faces:
print (x,y,w,h)
start_h =x + h
end_w =y +w
color=(255 , 0 , 0)
stroke=2
cv2.rectangle(frame , ( x , y ) , ( start_h , end_w ) , color , stroke )
cv2.imshow('f',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break;
camera.release();
cv2.destroyAllWindows();
|
8005017faa75314059b6229756ab61614244dfcb
|
[
"Markdown",
"Python"
] | 6
|
Python
|
biswajeet163/Face-Detector
|
b9fff48279159e8e18deea6d2e84d58c09cec667
|
2fb71d7ba6a0c580864d0fcd51636eef02b5b5ea
|
refs/heads/master
|
<repo_name>zhangyingwei/okcsv<file_sep>/src/test/java/com/zhangyingwei/okcsv/csv/impl/DefalutCsvExporterTest.java
package com.zhangyingwei.okcsv.csv.impl;
import com.zhangyingwei.okcsv.config.CsvConfig;
import com.zhangyingwei.okcsv.handler.DefaultHandler;
import com.zhangyingwei.okcsv.handler.SqlHandler;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author: <EMAIL>
* @date: 2017/1/10
* @time: 11:42
* @desc:
*/
public class DefalutCsvExporterTest {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
CsvExporter exporter = new CsvExporter(new CsvConfig()
.setSpliter(",")
.setPageSize(20)
);
List<String[]> items = new ArrayList<String[]>();
for(int i = 0;i<185;i++){
items.add(new String[]{"a","a","a","a","a","a","a","a"});
}
exporter.export(new DefaultHandler(items));
}
}<file_sep>/README.md
# okcsv
一个导出数据库内容为csv的工具
<file_sep>/src/main/java/com/zhangyingwei/okcsv/csv/impl/FileExporter.java
package com.zhangyingwei.okcsv.csv.impl;
import com.zhangyingwei.okcsv.config.CsvConfig;
import com.zhangyingwei.okcsv.csv.Exporter;
import com.zhangyingwei.okcsv.entity.CsvEntity;
import com.zhangyingwei.okcsv.handler.Handler;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author: <EMAIL>
* @date: 2017/1/9
* @time: 23:08
* @desc: 文件导出
*/
public class FileExporter implements Exporter {
public void export(Handler handler, String path) throws IOException {
CsvConfig config = handler.getConfig();
List<CsvEntity> entitys = handler.resultList();
System.out.println("total-size:"+entitys.size());
if (this.validPath(path)) {
BufferedWriter writer = null;
try {
for (int i = 0;i<entitys.size();i++) {
writer = this.getBufferReader(writer,handler, path, i);
writer.write(entitys.get(i).toLine(config));
this.newLine(handler, writer, entitys, i);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer!=null){
writer.close();
}
}
}
}
private void newLine(Handler handler, BufferedWriter writer,List<CsvEntity> entitys, int index) throws IOException {
if(handler.getConfig().getPageSize()==-1){
if(index+1<entitys.size()){
writer.newLine();
}
}else{
if(index+1 < entitys.size() && (index%handler.getConfig().getPageSize()+1)<handler.getConfig().getPageSize()){
writer.newLine();
}
}
}
private boolean validPath(String path) {
return path != null;
}
/**
* 获取一个文件输出流
*
* @param handler
* @param path
* @return
* @throws IOException
*/
public BufferedWriter getBufferReader(BufferedWriter writer,Handler handler, String path,int index) throws IOException {
path = this.getPath(handler,path);
if(handler.getConfig().getPageSize()==-1 && index == 0){
System.out.println("new File["+path+"]");
writer = new BufferedWriter(new FileWriter(path));
}else if(handler.getConfig().getPageSize() != -1){
if((index%handler.getConfig().getPageSize()) == 0){
if(writer!=null){
writer.close();
}
System.out.println("new File["+path+"]");
writer = new BufferedWriter(new FileWriter(path));
}
}
return writer;
}
private String getPath(Handler handler , String path) {
if(handler.getConfig().getPageSize() != -1){
path = path.replace(handler.getConfig().getFileSuffix(), "-"+ UUID.randomUUID() + handler.getConfig().getFileSuffix());
}
return path;
}
}
<file_sep>/src/main/java/com/zhangyingwei/okcsv/csv/Exporter.java
package com.zhangyingwei.okcsv.csv;
import com.zhangyingwei.okcsv.entity.CsvEntity;
import com.zhangyingwei.okcsv.handler.Handler;
import java.io.IOException;
import java.util.List;
/**
* @author: <EMAIL>
* @date: 2017/1/9
* @time: 22:25
* @desc: 数据导出接口
*/
public interface Exporter {
void export(final Handler handler, final String path) throws IOException;
}
|
ab088a91ec8797e2090ad24d5ae573685c8622ca
|
[
"Markdown",
"Java"
] | 4
|
Java
|
zhangyingwei/okcsv
|
397bac7826828c5e995deffe91404ee2062cd759
|
dd396a9cc1807da79e01caffa4c01d47cf4fc033
|
refs/heads/main
|
<file_sep>#include<stdio.h>
int main()
{
int age;
printf("enter your age\n");
scanf("%d", &age);
switch(age)
{
case 3:
printf("the age is 3\n");
// break;
case 13:
printf(" the age is 13\n");
break;
case 26:
printf("the age is 26\n");
break;
default:
printf("the age is not 3, 13, 26\n");
}
return 0;
}
<file_sep>#include<stdio.h>
#include<conio.h>
#include<math.h>
float fun(float x)
{
return ((cos(x)+1)/3); //+1.
}
int main()
{
float a,b,x,d;
int n;
printf("enter the number of iteration");
scanf("%d",&n);
printf("\n n x i(c)");
for(int j=0;j<n;j++)
{
printf("\n\n%d %10.6f %10.6f ",j+1,x,fun(x));
x=fun(x);
}
getch();
}
<file_sep>#include<stdio.h>
#include<conio.h>
#include<math.h>
float fun(float x)
{
return(cos(x)-3*x+1); //+1.
}
int main()
{
float a,b,c,d,t;
int n,x=0;
printf("enter the number of iteration");
scanf("%d",&n);
while(1)
{
if((fun(x)*fun(x+1))<0){ break; }
else printf("no root found\n");
x++;
}
a=x;
b=x+1;
printf("\nthe initial aprrox limit are\n");
printf("%f%f",a,b);
printf("\n\n a b c f(c)");
for(int j=0;j<n;j++)
{
c=(a+b)/2;
printf("\n\n %10.6f %10.6f %10.6f %10.6f",a,b,c,fun(c));
if(fun(c)*fun(a)<0)
{ b=c;}
else
{a=c;}
}
getch();
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class sample
{
int a,b;
public:
void setvalue(int,int);
friend float mean(sample s);
};
float mean(sample s)
{
return float((s.a+s.b)/2.0);
}
int main()
{
sample s;
s.setvalue(26,24);
cout <<"mean is" << mean(s);
return 0;
}
<file_sep>#include<stdio.h>
int main()
{
char ch;
printf("enter any character\n");
scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("character is an alphabet\n");
}
else{
printf("otherwise character is not an alphabet\n");
}
return 0;
}
|
c557469f14dec5c6d2cba0ea09c1eb909b64980d
|
[
"C",
"C++"
] | 5
|
C
|
sumitkain27/Informationsecurity
|
75f24fe85dce748f854bf39ef28cb96940dee697
|
1bbf10f785a896c61788d6cbf91dc10ce5409149
|
refs/heads/master
|
<repo_name>y4izus/testing-react360<file_sep>/service/map.js
import { playSound } from "../utils";
import { translate } from "./position";
import { WIDTH, HEIGHT } from '../constants'
import map from '../static_assets/maps/easy.json'
export const drawSound = cell =>
playSound('finger-snap', translate(cell.value))
export const hasReachExit = coordinate => {
const [x, y] = coordinate
return (x > WIDTH || x < -WIDTH) || (y > HEIGHT || y < -HEIGHT)
}
const getAxis = direction => direction.includes(['up', 'down']) ? 0 : 1
const getOppositveAxis = direction => direction.includes(['up', 'down']) ? 1 : 0
const getCellsInSameDirection = (direction, position, map) => {
const axis = getOppositveAxis(direction)
return map.filter(cell => !cell.emptyOn.includes(direction)).filter(cell => {
return cell.value[axis] === position[axis]
})
}
const getClosestCellOnAxis = (axis, cellsInSameDirection) => {
return cellsInSameDirection.reduce((minDistanceCell, cell) => cell.value[axis] < minDistanceCell.value[axis] ? cell : minDistanceCell, cellsInSameDirection[0])
}
export const calculateExitPosition = (position, direction) => {
switch (direction) {
case 'up':
return [position[0], HEIGHT, 0]
case 'down':
return [position[0], 0, 0]
case 'left':
return [0, position[1], 0]
case 'right':
return [WIDTH, position[1], 0]
}
return position
}
export const minDistanceColide = (direction, position) => {
const axis = getAxis(direction)
const cellsInSameDirection = getCellsInSameDirection(direction, position, map.cells)
return getClosestCellOnAxis(axis, cellsInSameDirection)
}<file_sep>/index.js
import React from 'react';
import {
AppRegistry,
View,
} from 'react-360';
import styles from './styles'
import { handleInput } from './service/inputs'
export default class Hello360 extends React.Component {
handleInput(e) {
const event = e.nativeEvent
const inputEvent = event.inputEvent
handleInput(inputEvent)
}
render() {
return (
<View style={styles.panel} onInput={this.handleInput} />
);
}
};
AppRegistry.registerComponent('Hello360', () => Hello360);
|
711e946da606e7cb49b971beaa091933a20e60df
|
[
"JavaScript"
] | 2
|
JavaScript
|
y4izus/testing-react360
|
f2287696b03e4b7d629eeb1c401574a252042cfd
|
f36fc5c74d8555e5c9e572dd956c7702dd84aee1
|
refs/heads/master
|
<repo_name>NLDPhat/Demo_Blog<file_sep>/app/models/blog.rb
class Blog < ApplicationRecord
belongs_to :user
has_many :comments, :dependent => :destroy
validates :Title, presence: true,
length: { maximum: 200}
validates :post, presence: true
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :blogs do
resources :comments
end
resources :users
get 'blog' => "blogs#index"
get 'about' => "pages#about", as: :about
get 'contact' => "pages#contact", as: :contact
get 'register' => "users#new", as: :register
root 'welcome#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
f9b4610e4294c58e80e5f4446ba8280550a7f4b7
|
[
"Ruby"
] | 2
|
Ruby
|
NLDPhat/Demo_Blog
|
1095d3eb58e5631f1994b60dfa288c07de0f2037
|
be67de029838fc1d5a4c61322a4a3669adac005f
|
refs/heads/master
|
<repo_name>adachi0919/resources_app<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
User.create(user_params)
redirect_to :action => "search"
end
def search
user_search = UserSearch.new(params_user_search)
@users = user_search.execute
end
def edit
@user = User.find(params[:id])
end
def update
user = User.find(params[:id])
user.update(user_params)
redirect_to :action => "search"
end
def destroy
user = User.find(params[:id])
user.delete
redirect_to :action => "search"
end
private
def params_user_search
params.permit(:search_name, :search_age)
end
def user_params
params.require(:user).permit(:name, :age)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root to: 'users#search'
get '/users/search', to: 'users#search'
get 'users/new', to: 'users#new'
post 'users/create', to: 'users#create'
get '/users/:id/edit', to: 'users#edit'
patch '/users/:id', to: 'users#update'
delete '/users/:id', to: 'users#destroy'
end
|
d53ab4a028729bc9cb3c9827bb4691e1efe1a661
|
[
"Ruby"
] | 2
|
Ruby
|
adachi0919/resources_app
|
f10a6b42a4486fcf507add13a2bd86e76e2f9afb
|
55ed3bef64d32c0e65c2b1bd0deaaa7bdc5fe2c7
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamFactoryD.Model
{
public class QualityControl
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Employee { get; set; }
public string Variant { get; set; }
public string TimeCheck { get; set; }
public List<QualityActivity> ActivityList { get; set; }
public QualityControl(int id, string name, string description, string employee, string variant, string timeCheck, List<QualityActivity> activityList)
{
this.ActivityList = activityList;
this.ID = id;
this.Name = name;
this.Description = description;
this.Employee = employee;
this.Variant = variant;
this.TimeCheck = timeCheck;
}
public QualityControl(int id, string name, string description, string employee, string variant, string timeCheck)
{
ActivityList = new List<QualityActivity>();
this.ID = id;
this.Name = name;
this.Description = description;
this.Employee = employee;
this.Variant = variant;
this.TimeCheck = timeCheck;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Controller for group A
namespace JamFactory.Controller {
class IngredientController {
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JamFactoryD.Model;
using JamFactory.Model;
using JamFactoryD.Controller.Facades;
using JamFactory.View.Group_D;
namespace JamFactoryD.Controller
{
static class QualityControlController
{
static int ProductID;
public static List<QualityControl> ControlList = new List<QualityControl>();
public static void GetQualityInsurence()
{
ControlList = QualityInsurenceFacade.GetControlByProductID(2);
}
public static void SetProductID(Recipe recipe)
{
ProductID = QualityInsurenceFacade.GetProductsFromRecipe(recipe);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using JamFactory.Model;
using JamFactoryD.Controller.Facades;
// Controller for group D
namespace JamFactoryD.Controller {
class ProductController {
List<Recipe> recipes;
public Recipe selectedRecipe;
/// <summary>
/// Fetches recipes and ingredients from database
/// </summary>
/// <returns>List of recipes with ingredients in a string format</returns>
public List<string> GetRecipes() {
recipes = RecipeFacade.GetRecipes();
List<string> recipesString = new List<string>();
// Adding ingredients to recipes
foreach (Recipe recipe in recipes) {
List<string> ingredients = new List<string>();
recipe.Ingredients = IngredientFacade.GetIngredientsFromRecipe(recipe);
foreach (IngredientLine ingredient in recipe.Ingredients) {
ingredients.Add(ingredient.Ingredient.Name);
}
recipesString.Add(recipe.Name + " | " + string.Join(", ", ingredients));
}
return recipesString;
}
/// <summary>
/// Opens the details window for recipe
/// </summary>
/// <param name="index">The index for a recipe in recipes list</param>
internal void ShowDetailsForRecipe(int index) {
try {
// Sets the clicked recipe to selected to use when the window is opened
selectedRecipe = recipes[index];
}
catch (Exception e) {
System.Windows.MessageBox.Show(e.Message);
}
// Making the view and showing it
View.Group_D.RecipeDetailsWindow view = new View.Group_D.RecipeDetailsWindow();
view.Show();
// Binds this controller to the view so it can fetch selected recipe later
view.SetController(this);
}
/// <summary>
/// Recipes basic information
/// </summary>
/// <returns>Dictonary with recipe info</returns>
internal Dictionary<string, string> GetSelectedRecipe() {
Dictionary<string,string> recipe = new Dictionary<string,string>();
recipe.Add("Name", selectedRecipe.Name);
recipe.Add("Documentation", selectedRecipe.Documentation);
recipe.Add("Correspondence", selectedRecipe.Correspondence);
return recipe;
}
/// <summary>
/// Fetches products from database by recipe
/// </summary>
/// <returns>Dictionary with Variant and Size from each product</returns>
internal Dictionary<string, int> GetProducts() {
Dictionary<string, int> productList = new Dictionary<string, int>();
List<Product> products = RecipeFacade.GetProductsFromRecipe(selectedRecipe);
foreach (Product product in products) {
productList.Add(product.Variant, product.Size);
}
return productList;
}
public List<string> GetRecipeByType(List<string> parameters) {
List<string> recipesString = new List<string>();
recipes.Clear();
recipes = RecipeFacade.GetRecipeByType(parameters);
// Adding ingredients to recipes
foreach (Recipe recipe in recipes) {
List<string> ingredients = new List<string>();
recipe.Ingredients = IngredientFacade.GetIngredientsFromRecipe(recipe);
foreach (IngredientLine ingredient in recipe.Ingredients) {
ingredients.Add(ingredient.Ingredient.Name);
}
string stringRecipe = recipe.Name + " | " + string.Join(", ", ingredients);
recipesString.Add(stringRecipe);
// Removes Dups
//if (!recipesString.Contains(stringRecipe)) {
// recipesString.Add(stringRecipe);
//}
}
return recipesString;
}
public List<string> GetIngredient()
{
List<Ingredient> ingredients = IngredientFacade.GetIngredient(selectedRecipe.ID);
List<string> ingredientsString = new List<string>();
foreach (Ingredient ingredient in ingredients)
{
ingredientsString.Add(ingredient.Name);
}
return ingredientsString;
}
public void SetTestVariant()
{
RecipeFacade.SetTestVariant(selectedRecipe.ID);
}
public bool CheckTestVariant(){
return RecipeFacade.CheckTestVariant(selectedRecipe.ID);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using JamFactory.Model;
namespace JamFactoryD.Controller.Facades {
class IngredientFacade {
private static string _connect = "Server=ealdb1.eal.local;" + "Database=EJL20_DB;" + "User Id=ejl20_usr;" + "Password=<PASSWORD>";
/// <summary>
/// Fetches ingredientLines with ingredient from database
/// </summary>
/// <param name="recipe">The recipe you want the ingredients from</param>
/// <returns>A List of ingredientLines with recipes</returns>
internal static List<IngredientLine> GetIngredientsFromRecipe(Recipe recipe) {
List<IngredientLine> ingredients = new List<IngredientLine>();
SqlConnection connect = new SqlConnection(_connect);
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetIngredientsAmountFromRecipeID", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", recipe.ID));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
Ingredient ingredient = new Ingredient((string)reader["Name"], Convert.ToDouble(reader["Price"]));
ingredients.Add(new IngredientLine((int)reader["Amount"], recipe, ingredient));
}
}
catch (Exception e) {
throw e;
}
finally {
connect.Close();
connect.Dispose();
}
return ingredients;
}
public static List<Ingredient> GetIngredient(int RecipeID)
{
SqlConnection connect = new SqlConnection(_connect);
List<Ingredient> ingredients = new List<Ingredient>();
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetRecipeResources", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", RecipeID));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
ingredients.Add(new Ingredient((string)reader["Name"], Convert.ToDouble(reader["Amount"]), Convert.ToInt32(reader["Price"])));
}
}
catch (Exception e) {
throw e;
}
finally {
connect.Close();
connect.Dispose();
}
return ingredients;
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DatabaseFacadeTest
{
[TestClass]
public class UnitTest1
{
//Test for GetQualityInsurence
[TestMethod]
public void GetQualityInsurenceTest()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using JamFactoryD.Controller;
namespace JamFactoryD.View.Group_D
{
/// <summary>
/// Interaction logic for RecipeDetailsWindow.xaml
/// </summary>
public partial class RecipeDetailsWindow : Window
{
ProductController _controller;
public RecipeDetailsWindow()
{
InitializeComponent();
}
private void ProductTypeListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
/// <summary>
/// Sets the controller to the currently used controller to be able to fetch the selected recipe
/// </summary>
/// <param name="productController"></param>
internal void SetController(ProductController productController)
{
_controller = productController;
PrintRecipe();
PrintProducts();
ShowIngredient();
TestVariant_Load();
}
/// <summary>
/// Prints the selected recipes information
/// </summary>
private void PrintRecipe()
{
Dictionary<string, string> recipe = _controller.GetSelectedRecipe();
RecipeNameLabel.Content = recipe["Name"];
DocumentationTextBox.Text = recipe["Documentation"];
CorrespondanceTextBox.Text = recipe["Correspondence"];
}
/// <summary>
/// Prints product for selected recipe
/// </summary>
private void PrintProducts()
{
Dictionary<string, int> products = _controller.GetProducts();
foreach (KeyValuePair<string, int> product in products)
{
ProductNames.Text += product.Key + "\n";
ProductAmounts.Text += product.Value + "g\n";
}
}
/// <summary>
/// Closes the window
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BackButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Kvalitetssikring_btn_Click(object sender, RoutedEventArgs e)
{
KvalityInsurence kval = new KvalityInsurence();
kval.Show();
}
private void ShowIngredient()
{
foreach (string items in _controller.GetIngredient())
{
Ingredient.Items.Add(items);
}
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
_controller.SetTestVariant();
if (TestVariant.IsChecked != true)
{
DocumentationTextBox.Clear();
}
}
private void TestVariant_Load()
{
if (_controller.CheckTestVariant() == true)
{
TestVariant.IsChecked = true;
}
else
{
TestVariant.IsChecked = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using JamFactoryD.Controller;
namespace JamFactory.View.Group_D {
// Interaction logic for Start.xaml
public partial class Start : Window {
ProductController _controller;
List<string> parameters = new List<string>();
public Start() {
InitializeComponent();
_controller = new ProductController();
PrintRecipes();
parameters.Add("Luksus");
parameters.Add("Hverdags");
parameters.Add("Discount");
}
// Adds all the recipes to ListView
private void PrintRecipes() {
// Adding recipes to ListView
RecipeList.ItemsSource = _controller.GetRecipes();
}
private void PrintSortedRecipeByType() {
RecipeList.ItemsSource = null;
RecipeList.Items.Clear();
RecipeList.ItemsSource = _controller.GetRecipeByType(parameters);
}
// Opens a new window with recipe details
private void RecipeList_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
_controller.ShowDetailsForRecipe(RecipeList.SelectedIndex);
QualityControlController.SetProductID(_controller.selectedRecipe);
}
//public void SortParameters(string parameter) {
// // Removes parameter from parameterlist
// for (int i = 0; i < parameters.Count; i++){
// if (parameters[i] == parameter) {
// parameters.RemoveAt(i);
// }
// }
//}
private void luksus_Click(object sender, RoutedEventArgs e) {
// unchecked
if (luksus.IsChecked != true) {
parameters[0] = "null";
}
// checked
else {
parameters[0] = "Luksus";
}
PrintSortedRecipeByType();
}
private void weekday_Click(object sender, RoutedEventArgs e) {
// unchecked
if (weekday.IsChecked != true) {
parameters[1] = "null";
}
// checked
else {
parameters[1] = "Hverdags";
}
PrintSortedRecipeByType();
}
private void discount_Click(object sender, RoutedEventArgs e) {
// unchecked
if (discount.IsChecked != true) {
parameters[2] = "null";
}
// checked
else {
parameters[2] = "Discount";
}
PrintSortedRecipeByType();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using JamFactory.Model;
namespace JamFactoryD.Controller.Facades
{
public static class QualityInsurenceFacade
{
private static string _connect = "Server=ealdb1.eal.local;" + "Database=EJL20_DB;" + "User Id=ejl20_usr;" + "Password=<PASSWORD>";
/// <summary>
/// Fetches Control and Activities from database
/// </summary>
///
internal static List<Model.QualityControl> GetControlByProductID(int productID)
{
List<Model.QualityControl> ControlList = new List<Model.QualityControl>();
//List<Model.QualityControl> NoDublicateList = new List<Model.QualityControl>();
SqlConnection connect = new SqlConnection(_connect);
try
{
connect.Open();
SqlCommand sqlCmd = new SqlCommand("3_GetControl", connect);
sqlCmd.Parameters.Add(new SqlParameter("@C_ProductID", productID));
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read() && reader.HasRows )
{
ControlList.Add(new Model.QualityControl(
Convert.ToInt32(reader["ID"]),
Convert.ToString(reader["C_Name"]),
Convert.ToString(reader["Description"]),
Convert.ToString(reader["Name"]),
Convert.ToString(reader["Variant"]),
Convert.ToString(reader["TimeCheck"]),
GetAcitivtyByControl(Convert.ToInt32(reader["ID"]))
));
}
}
catch (Exception e)
{
throw e;
}
finally
{
connect.Close();
connect.Dispose();
}
return ControlList;
}
internal static List<Model.QualityActivity> GetAcitivtyByControl(int controlID)
{
List<Model.QualityActivity> ActivityList = new List<Model.QualityActivity>();
SqlConnection connect = new SqlConnection(_connect);
try
{
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetActivityByControl", connect);
sqlCmd.Parameters.Add(new SqlParameter("@AL_C_ID", controlID));
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read() && reader.HasRows)
{
ActivityList.Add(new Model.QualityActivity(Convert.ToString(reader["AL_Title"]), Convert.ToString(reader["AL_Description"]), Convert.ToString(reader["AL_Details"]), Convert.ToDateTime(reader["AL_Time"]), Convert.ToString(reader["AL_ExpectedResult"]), Convert.ToString(reader["AL_ActualResult"])));
}
}
catch (Exception e)
{
throw e;
}
finally
{
connect.Close();
connect.Dispose();
}
return ActivityList;
}
internal static int GetProductsFromRecipe(Recipe recipe)
{
int productID = 0;
SqlConnection connect = new SqlConnection(_connect);
try
{
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetProductsFromRecipeID", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", recipe.ID));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
productID = (int)reader["ID"];
}
}
catch (Exception e)
{
throw e;
}
finally
{
connect.Close();
connect.Dispose();
}
return productID;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using JamFactory.Model;
namespace JamFactoryD.Controller.Facades {
static class RecipeFacade {
private static string _connect = "Server=ealdb1.eal.local;" + "Database=EJL20_DB;" + "User Id=ejl20_usr;" + "Password=<PASSWORD>";
/// <summary>
/// Fetches all recipes form database
/// </summary>
/// <returns>A list of recipes</returns>
internal static List<Recipe> GetRecipes() {
List<Recipe> recipes = new List<Recipe>();
SqlConnection connect = new SqlConnection(_connect);
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetRecipes", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
recipes.Add(new Recipe((int)reader["ID"], reader["Name"].ToString(), reader["Documentation"].ToString(), reader["Correspondence"].ToString()));
}
}
catch (Exception e) {
throw e;
}
finally {
connect.Close();
connect.Dispose();
}
return recipes;
}
/// <summary>
/// Fetches products from database
/// </summary>
/// <param name="recipe">The recipe the products belongs to</param>
/// <returns>A List of products</returns>
internal static List<Product> GetProductsFromRecipe(Recipe recipe) {
List<Product> products = new List<Product>();
SqlConnection connect = new SqlConnection(_connect);
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetProductsFromRecipeID", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", recipe.ID));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
products.Add(new Product((int)reader["ID"], (string)reader["Variant"], (int)reader["Size"], (int)reader["FruitContent"], Convert.ToDouble(reader["Price"])));
}
}
catch (Exception e) {
throw e;
}
finally {
connect.Close();
connect.Dispose();
}
return products;
}
internal static List<Recipe> GetRecipeByType(List<string> variants) {
List<Recipe> recipes = new List<Recipe>();
List<Recipe> NoDupRecipes = new List<Recipe>();
SqlConnection connect = new SqlConnection(_connect);
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetRecipeByType", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@Variant1", variants[0]));
sqlCmd.Parameters.Add(new SqlParameter("@Variant2", variants[1]));
sqlCmd.Parameters.Add(new SqlParameter("@Variant3", variants[2]));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
Recipe _recipe = new Recipe((int)reader["ID"], reader["Name"].ToString(), reader["Documentation"].ToString(), reader["Correspondence"].ToString());
recipes.Add(_recipe);
}
Dictionary<string, int> dups = new Dictionary<string, int>();
for (int i = 0; i < recipes.Count; i++){
if(!dups.ContainsKey(recipes[i].Name)){
dups.Add(recipes[i].Name, i);
}
}
for (int i = 0; i < recipes.Count; i++) {
if (dups.ContainsValue(i)) {
NoDupRecipes.Add(recipes[i]);
}
}
//for (int i = 0; i < recipes.Count; i++) {
// if (!dups.ContainsValue(i)) {
// recipes.RemoveAt(i);
// }
//}
}
catch (Exception e) {
System.Windows.MessageBox.Show(e.Message);
}
finally {
connect.Close();
connect.Dispose();
}
return NoDupRecipes;
}
public static void SetTestVariant(int RecipeID)
{
SqlConnection connect = new SqlConnection(_connect);
try {
connect.Open();
SqlCommand sqlCmd = new SqlCommand("MoveRecipeFromDevelopment", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", RecipeID));
sqlCmd.ExecuteNonQuery();
}
catch (Exception e) {
System.Windows.MessageBox.Show(e.Message);
}
finally {
connect.Close();
connect.Dispose();
}
}
public static bool CheckTestVariant(int RecipeID)
{
SqlConnection connect = new SqlConnection(_connect);
bool testVariant = new bool();
try
{
connect.Open();
SqlCommand sqlCmd = new SqlCommand("4_GetTestVariantFromRecipeID", connect);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@RecipeID", RecipeID));
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
testVariant = Convert.ToBoolean(reader["TestVariant"]);
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
}
finally
{
connect.Close();
connect.Dispose();
}
return testVariant;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using JamFactoryD.Controller;
namespace JamFactoryD.View.Group_D
{
/// <summary>
/// Interaction logic for KvalitetsSikring.xaml
/// </summary>
public partial class KvalityInsurence : Window
{
public KvalityInsurence()
{
InitializeComponent();
Activity_Combo.IsEnabled = false;
ActivityDescription_Box.IsEnabled = false;
Details_Box.IsEnabled = false;
Time_Box.IsEnabled = false;
QualityControlController.GetQualityInsurence();
for (int i = 0; i < QualityControlController.ControlList.Count; i++)
{
if (!Control_Combo.Items.Contains(QualityControlController.ControlList[i].Name)) {
Control_Combo.Items.Add(QualityControlController.ControlList[i].Name);
}
}
}
private void Back_btn_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Control_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ActivityDescription_Box.Clear();
Details_Box.Clear();
Time_Box.Clear();
Activity_Combo.Items.Clear();
for (int k = 0; k < QualityControlController.ControlList[Control_Combo.SelectedIndex].ActivityList.Count; k++)
{
Activity_Combo.Items.Add(QualityControlController.ControlList[Control_Combo.SelectedIndex].ActivityList[k].Name);
}
ControlDescription_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].Description;
TimeCheck_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].TimeCheck;
Product_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].Variant;
Employee_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].Employee;
Activity_Combo.IsEnabled = true;
ActivityDescription_Box.IsEnabled = true;
Details_Box.IsEnabled = true;
Time_Box.IsEnabled = true;
}
private void Activity_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
ActivityDescription_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].ActivityList[Activity_Combo.SelectedIndex].Description;
Details_Box.Text = QualityControlController.ControlList[Control_Combo.SelectedIndex].ActivityList[Activity_Combo.SelectedIndex].Details;
Time_Box.Text = Convert.ToString(QualityControlController.ControlList[Control_Combo.SelectedIndex].ActivityList[Activity_Combo.SelectedIndex].Time);
}
catch (Exception)
{
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamFactoryD.Model
{
public class QualityActivity
{
public string Name { get; set; }
public string Description { get; set; }
public string Details { get; set; }
public DateTime Time { get; set; }
public string ExpectedResult { get; set; }
public string ActualResult { get; set; }
public QualityActivity(string name, string description, string details, DateTime time, string expectedResult, string actualResult)
{
this.Name = name;
this.Description = description;
this.Details = details;
this.Time = time;
this.ExpectedResult = expectedResult;
this.ActualResult = actualResult;
}
}
}
|
a6b625e92dea7e2a770fab29feaaf8ddcdbb39a2
|
[
"C#"
] | 12
|
C#
|
nickosv/JamFactoryD
|
e8cb86cefbc1eb58c076429e583bfb8d81161698
|
5926c7925bd27afba705ee279515646e99754d80
|
refs/heads/master
|
<file_sep># # encoding: utf-8
# Inspec test for recipe tomcat::default
# The Inspec reference, with examples and extensive documentation, can be
# found at http://inspec.io/docs/reference/resources/
#unless os.windows?
# This is an example test, replace with your own test.
# describe user('root'), :skip do
# it { should exist }
# end
#end
# This is an example test, replace it with your own test.
#describe port(8080), do
# it { should_not be_listening }
#end
describe command('curl localhost:8080') do
its('stdout') { should match (/Tomcat/) }
end
describe package ('java-1.7.0-openjdk-devel') do
it { should be_installed }
end
describe file ('/opt/tomcat') do
it {should be_directory}
it { should be_owned_by 'tomcat'}
end
describe user ('tomcat') do
it {should exist}
its ('group') {should eq 'tomcat'}
its ('home') {should eq '/opt/tomcat'}
its ('shell') {should eq '/bin/nologin'}
end
describe group('tomcat') do
it {should exist}
end
describe service('tomcat') do
it {should be_installed}
it {should be_enabled}
it {should be_running}
end<file_sep>#
# Cookbook:: tomcat
# Recipe:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
package 'java-1.7.0-openjdk-devel'
group 'tomcat'
user 'tomcat' do
manage_home false
shell '/bin/nologin'
group 'tomcat'
home '/opt/tomcat'
end
remote_file 'apache-tomcat-8.0.43.tar.gz' do
source 'http://mirror.fibergrid.in/apache/tomcat/tomcat-8/v8.0.43/bin/apache-tomcat-8.0.43.tar.gz'
action :create
end
directory '/opt/tomcat' do
action :create
owner 'tomcat'
group 'tomcat'
mode '0755'
end
execute 'tar -xvzf apache-tomcat-8.0.43.tar.gz -C /opt/tomcat --strip-components=1'
%w[/opt/tomcat/conf/ /opt/tomcat/webapps/ /opt/tomcat/work/ /opt/tomcat/logs/ /opt/tomcat/temp/].each do |path|
directory path do
owner 'tomcat'
group 'tomcat'
mode '0755'
end
end
execute 'chmod -Rf 755 /opt/tomcat'
template '/etc/systemd/system/tomcat.service' do
source 'tomcat.service.erb'
mode '0755'
end
execute 'deamon-reload' do
command 'systemctl daemon-reload'
action :nothing
end
service 'tomcat' do
action [:enable, :start]
end
|
a05f300d9aeae16a5b4fc5ee8e2c56281ab2346a
|
[
"Ruby"
] | 2
|
Ruby
|
saurau01/Chef-repo
|
33f7824642b5e9b14b0ca1326dad7d165d6bac44
|
9ff9a7adbb3e632f4acee6afff7eaa78d110ca69
|
refs/heads/master
|
<repo_name>mathieu-rohon/scripts<file_sep>/create-vm.sh
#!/bin/bash
#VM1=$1
#VM2=$2
if [ -z "$OS_TENANT_NAME" ]; then
echo "openstack environ variables is not set"
exit
fi
TENANT_ID=$(keystone --os-tenant-name admin --os-username admin --os-password password tenant-list | grep " $OS_TENANT_NAME " | awk '{print $2}')
#PRINET="${OS_TENANT_NAME}"
# create private network
#NET_ID=$(quantum net-list | awk "/ private / { print \$2 }")
#echo "NET=$NET_ID"
NET_GRE=$(neutron --os-tenant-name admin --os-username admin --os-password password net-create --tenant_id $TENANT_ID net-gre100 --provider:network_type gre --provider:segmentation_id 100 | awk '/ id /{print $4}')
neutron subnet-create --gateway 10.0.0.254 net-gre100 10.0.0.0/24
NET_VXLAN=$(neutron --os-tenant-name admin --os-username admin --os-password password net-create --tenant_id $TENANT_ID net-vxlan100 --provider:network_type vxlan --provider:segmentation_id 100 | awk '/ id /{print $4}')
neutron subnet-create --gateway 10.0.0.254 net-vxlan100 10.0.0.0/24
#
# boot instance
#
#if [ ! -z "$VM1" ]; then
# IMAGE_ID=$(glance add name=Ubuntu-12.04 is_public=true container_format=ovf disk_format=qcow2 < ./precise-server-cloudimg-amd64-disk1.img | awk '{print $6}')
IMAGE_ID=$(glance image-list | grep ami | head -n 1 | awk '{print $2}')
echo "IMAGE=$IMAGE_ID"
for i in 1 2
do
VM_VXLAN=$(nova boot --image=$IMAGE_ID --flavor=1 --nic net-id=$NET_VXLAN vm$i-vxlan | awk '/ id /{print $4}')
nova show $VM_VXLAN
SERVER=$(nova-manage vm list | grep vm$i-vxlan | awk '{print $2}')
echo "host for vm$i-vxlan : $SERVER"
done
for i in 1 2
do
VM_GRE=$(nova boot --image=$IMAGE_ID --flavor=1 --nic net-id=$NET_GRE vm$i-gre | awk '/ id /{print $4}')
nova show $VM_GRE
SERVER=$(nova-manage vm list | grep vm$i-gre | awk '{print $2}')
echo "host for vm$i-gre : $SERVER"
done
|
a28c874d946f5b8597dd8391a4a0bc4e71369557
|
[
"Shell"
] | 1
|
Shell
|
mathieu-rohon/scripts
|
8ae26661b31b33c6f2bb88daaf3c545f33a01627
|
9ca98daf59a3e799c5ff833d32aacc9fb0797765
|
refs/heads/main
|
<file_sep>import { CfnOutput, Fn, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { AuthorizationType, Cors, MethodOptions, ResourceOptions, RestApi } from 'aws-cdk-lib/lib/aws-apigateway'
import { GenericTable } from './GenericTable';
import { AuthorizerWrapper } from './auth/AuthorizerWrapper';
import { Bucket, HttpMethods } from 'aws-cdk-lib/lib/aws-s3';
import { WebAppDeployment } from './WebAppDeployment';
import { Policies } from './Policies';
export class SpaceStack extends Stack {
private api = new RestApi(this, 'SpaceApi');
private authorizer: AuthorizerWrapper;
private suffix: string;
private spacesPhotosBucket: Bucket;
private profilePhotosBucket: Bucket;
private policies: Policies;
private spacesTable = new GenericTable(this, {
tableName: 'SpacesTable',
primaryKey: 'spaceId',
createLambdaPath: 'Create',
readLambdaPath: 'Read',
updateLambdaPath: 'Update',
deleteLambdaPath: 'Delete',
secondaryIndexes: ['location']
})
private reservationsTable = new GenericTable(this, {
tableName: 'ReservationsTable',
primaryKey: 'reservationId',
createLambdaPath: 'Create',
readLambdaPath: 'Read',
updateLambdaPath: 'Update',
deleteLambdaPath: 'Delete',
secondaryIndexes: ['user']
})
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props)
this.initializeSuffix();
this.initializeSpacesPhotosBucket();
this.initializeProfilePhotosBucket();
this.policies = new Policies(this.spacesPhotosBucket, this.profilePhotosBucket);
this.authorizer = new AuthorizerWrapper(
this,
this.api,
this.policies);
new WebAppDeployment(this, this.suffix);
const optionsWithAuthorizer: MethodOptions = {
authorizationType: AuthorizationType.COGNITO,
authorizer: {
authorizerId: this.authorizer.authorizer.authorizerId
}
}
const optionsWithCors:ResourceOptions = {
defaultCorsPreflightOptions : {
allowOrigins: Cors.ALL_ORIGINS,
allowMethods: Cors.ALL_METHODS
}
}
//Spaces API integrations:
const spaceResource = this.api.root.addResource('spaces', optionsWithCors);
spaceResource.addMethod('POST', this.spacesTable.createLambdaIntegration, optionsWithAuthorizer);
spaceResource.addMethod('GET', this.spacesTable.readLambdaIntegration, optionsWithAuthorizer);
spaceResource.addMethod('PUT', this.spacesTable.updateLambdaIntegration, optionsWithAuthorizer);
spaceResource.addMethod('DELETE', this.spacesTable.deleteLambdaIntegration, optionsWithAuthorizer);
//Reservations API integrations:
const reservationResource = this.api.root.addResource('reservations', optionsWithCors);
reservationResource.addMethod('POST', this.reservationsTable.createLambdaIntegration, optionsWithAuthorizer);
reservationResource.addMethod('GET', this.reservationsTable.readLambdaIntegration, optionsWithAuthorizer);
reservationResource.addMethod('PUT', this.reservationsTable.updateLambdaIntegration, optionsWithAuthorizer);
reservationResource.addMethod('DELETE', this.reservationsTable.deleteLambdaIntegration, optionsWithAuthorizer);
}
private initializeSuffix() {
const shortStackId = Fn.select(2, Fn.split('/', this.stackId));
const Suffix = Fn.select(4, Fn.split('-', shortStackId));
this.suffix = Suffix;
}
private initializeSpacesPhotosBucket() {
this.spacesPhotosBucket = new Bucket(this, 'spaces-photos', {
bucketName: 'spaces-photos-' + this.suffix,
cors: [{
allowedMethods: [
HttpMethods.HEAD,
HttpMethods.GET,
HttpMethods.PUT
],
allowedOrigins: ['*'],
allowedHeaders: ['*']
}]
});
new CfnOutput(this, 'spaces-photos-bucket-name', {
value: this.spacesPhotosBucket.bucketName
})
}
private initializeProfilePhotosBucket() {
this.profilePhotosBucket = new Bucket(this, 'profile-photos', {
bucketName: 'profile-photos-' + this.suffix,
cors: [{
allowedMethods: [
HttpMethods.HEAD,
HttpMethods.GET,
HttpMethods.PUT
],
allowedOrigins: ['*'],
allowedHeaders: ['*']
}]
});
new CfnOutput(this, 'profile-photos-bucket-name', {
value: this.profilePhotosBucket.bucketName
})
}
}<file_sep>
export const config = {
REGION: 'eu-west-1',
USER_POOL_ID: 'eu-west-1_gRIUoOdLx',
APP_CLIENT_ID: '335vma5jmludo42mn2895cu5bh',
IDENTITY_POOL_ID: 'eu-west-1:c1490135-4dd2-4a82-9959-880f77fef599',
TEST_USER_NAME: 'barosanu2',
TEST_USER_PASSWORD: '<PASSWORD>&'
}
|
5792b54ce7e74773e6cc5eca60b75f919bd7db12
|
[
"TypeScript"
] | 2
|
TypeScript
|
sandeepsharmaster/space-finder-backend
|
1e9e99ad0ff0b9f64300b6623a06915c87cd8a3f
|
4e84b5720e6f8cdd84c29be8f579ed6377f3bdb0
|
refs/heads/master
|
<repo_name>FilipOlofsson/SFML-Networking<file_sep>/server/main.cpp
#include <SFML/Network.hpp>
#include <string.h>
#include <iostream>
using namespace sf;
int main()
{
IpAddress target = "127.0.0.1";
UdpSocket socket;
std::string toSend;
while(true) {
char data[1000];
for(int i = 0; i < 1000; i++) {
data[i] = '@';
}
std::getline(std::cin, toSend);
strcpy(data, toSend.c_str());
if(socket.send(data, 1000, target, 54000) != sf::Socket::Done) {
printf("Error sending data.");
}
}
}<file_sep>/client/main.cpp
#include <SFML/Network.hpp>
#include <iostream>
int main()
{
sf::UdpSocket socket;
std::size_t received;
if(socket.bind(54000) != sf::Socket::Done) {
printf("Error binding to the socket.");
}
sf::IpAddress IP;
unsigned short port;
while(true) {
char data[1000];
if(socket.receive(data, 1000, received, IP, port) != sf::Socket::Done) {
printf("Error receiving data.");
}
for(int i = 0; i < 1000; i++) {
if(data[i] != '@') {
std::cout << data[i];
}
}
std::cout << std::endl;
}
}
|
76aecc4dd5d31535f5ea749cd3a92e67a5b66c1a
|
[
"C++"
] | 2
|
C++
|
FilipOlofsson/SFML-Networking
|
22bd5cd481f41271b8dba1c38986257b6a4db190
|
af7ba09dbf36c1db5f9793d9be656035fffdcf35
|
refs/heads/master
|
<repo_name>awilk46/projektkino<file_sep>/navbar.php
<link rel="stylesheet" href="media/css/navbar.css">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand"><NAME></div>
</div>
<ul class="nav navbar-nav">
<li><a href="index.php">Strona Glowna</a></li>
<li><a href="bilety.php">Bilety</a></li>
<?php
if (isset($_SESSION['zalogowany']) && $_SESSION['rola'] == 'user') {
?>
<li><a href="mojeRezerwacje.php">Moje rezerwacje</a></li>
<?php
} ?>
<?php
if (isset($_SESSION['zalogowany']) && $_SESSION['rola'] == 'admin') {
?>
<li><a href="administrator.php">Panel Administratora</a></li>
<?php
} ?>
<li><a href="kontakt.php">Kontakt</a></li>
</ul>
<?php
if (isset($_SESSION['zalogowany'])) {
?>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="wylogowanie.php" style="padding-top: 0;padding-bottom: 0;" >
<button type="button" class="btn btn-danger btn-sm przyciskZarejestruj">
<span class="glyphicon glyphicon-log-out"></span> Wyloguj
</button>
</a>
</li>
</ul>
<?php
} else {
?>
<form method="post" action="logowanie.php">
<ul class="nav navbar-nav navbar-right">
<li><input type="text" class="form-control login" name="login" placeholder="login"></li>
<li><input type="password" class="form-control haslo" name="haslo" placeholder="<PASSWORD>"></li>
<li>
<button type="submit" class="btn btn-success przyciskZaloguj">Zaloguj</button>
</li>
<li>
<a href="rejestracja.php" class="przyciskZarejestruj" style="padding-top: 0;padding-bottom: 0;">
<button type="button" class="btn btn-info">Rejestruj</button>
</a>
</li>
</ul>
</form>
<div style="clear:both;"></div>
<?php
}
?>
</div>
</nav><file_sep>/rejestracja.php
<?php
session_start();
if (isset($_POST['email'])) {
$is_validated = true;
$login = $_POST['login'];
if ((strlen($login) < 3) || (strlen($login) > 20)) {
$is_validated = false;
$_SESSION['e_login'] = "login musi posiadac od 3 do 20 znakow";
}
if (!ctype_alnum($login)) {
$is_validated = false;
$_SESSION['e_login'] = "Login musi skladac sie tylko z liter oraz cyfr";
}
$imieINazwisko = $_POST['imieINazwisko'];
if ((strlen($imieINazwisko) < 3) || (strlen($imieINazwisko) > 20)) {
$is_validated = false;
$_SESSION['e_imieINazwisko'] = "Imie I Nazwisko musi posiadac od 3 do 20 znakow";
}
$email = $_POST['email'];
$emailPrzefiltrowany = filter_var($email, FILTER_SANITIZE_EMAIL);
if ((filter_var($emailPrzefiltrowany, FILTER_VALIDATE_EMAIL) == false) || ($emailPrzefiltrowany != $email)) {
$is_validated = false;
$_SESSION['e_email'] = "Musi byc poprawny adres email";
}
$password1 = $_POST['<PASSWORD>1'];
$password2 = $_POST['<PASSWORD>2'];
if (strlen($password1) < 8 || strlen($password1) > 25) {
$is_validated = false;
$_SESSION['e_password'] = "Haslo musi zawierac od 8 do 25 znakow";
}
if ($password1 != $password2) {
$is_validated = false;
$_SESSION['e_password'] = "<PASSWORD>";
}
$password_hash = password_hash($password1, PASSWORD_DEFAULT);
if (!isset($_POST['regulamin'])) {
$is_validated = false;
$_SESSION['e_regulamin'] = "Potwierdz regulamin";
}
$_SESSION['fr_login'] = $login;
$_SESSION['fr_imieINazwisko'] = $imieINazwisko;
$_SESSION['fr_email'] = $email;
$_SESSION['fr_password1'] = $<PASSWORD>;
$_SESSION['fr_password2'] = $<PASSWORD>;
if (isset($_POST['regulamin'])) $_SESSION['fr_regulamin'] = true;
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $db_user, $db_password, $db_name);
$connection->set_charset("utf8");
if ($connection->connect_errno != 0) {
throw new Exception(mysqli_connect_errno());
} else {
$result = $connection->query("SELECT id FROM uzytkownicy WHERE email = '$email'");
if (!$result) throw new Exception($connection->error);
if ($result->num_rows > 0) {
$is_validated = false;
$_SESSION['e_email'] = "Istnieje juz konto przypisane do tego adresu email!";
}
$result = $connection->query("SELECT id FROM uzytkownicy WHERE login = '$login'");
if (!$result) throw new Exception($connection->error);
if ($result->num_rows > 0) {
$is_validated = false;
$_SESSION['e_login'] = "Istnieje juz konto o takim loginie!";
}
if ($is_validated) {
if ($connection->query("INSERT INTO uzytkownicy VALUES (NULL, '$login','$password_hash','$email','$imieINazwisko','user')")) {
$_SESSION['succesful_register'] = true;
header('Location: index.php');
} else {
throw new Exception($connection->error);
}
}
$connection->close();
}
} catch (Exception $e) {
echo '<span style="color:red;">Blad serwera!</span>';
echo $e->getMessage();
}
}
?>
<!DOCTYPE HTML>
<html lang="pl">
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link rel="stylesheet" href="media/css/rejestracja.css">
</head>
<body>
<form method="post" class="row">
<div>
<h2>Rejestracja</h2>
</div>
<div class="myContainer">
<input type="text" name="login" placeholder="Login" value="<?php
if (isset($_SESSION['fr_login'])) {
echo $_SESSION['fr_login'];
unset($_SESSION['fr_login']);
}
?>" autofocus class="login"/>
<?php
if (isset($_SESSION['e_login'])) {
echo '<div class="error">' . $_SESSION['e_login'] . '</div>';
unset($_SESSION['e_login']);
}
?>
<br/>
<input type="text" name="imieINazwisko" placeholder="<NAME>" value="<?php
if (isset($_SESSION['fr_imieINazwisko'])) {
echo $_SESSION['fr_imieINazwisko'];
unset($_SESSION['fr_imieINazwisko']);
}
?>" class="nazwa"/>
<?php
if (isset($_SESSION['e_imieINazwisko'])) {
echo '<div class="error">' . $_SESSION['e_imieINazwisko'] . '</div>';
unset($_SESSION['e_imieINazwisko']);
}
?>
<br/>
<input type="text" name="email" placeholder="e-mail" value="<?php
if (isset($_SESSION['fr_email'])) {
echo $_SESSION['fr_email'];
unset($_SESSION['fr_email']);
}
?>" class="email"/>
<?php
if (isset($_SESSION['e_email'])) {
echo '<div class="error">' . $_SESSION['e_email'] . '</div>';
unset($_SESSION['e_email']);
}
?>
<br/>
<input type="password" name="password1" placeholder="<PASSWORD>" value="<?php
if (isset($_SESSION['fr_password1'])) {
echo $_SESSION['fr_password1'];
unset($_SESSION['fr_password1']);
}
?>" class="haslo1"/>
<?php
if (isset($_SESSION['e_password'])) {
echo '<div class="error">' . $_SESSION['e_password'] . '</div>';
unset($_SESSION['e_password']);
}
?>
<br/>
<input type="<PASSWORD>" name="password2" placeholder="Pow<NAME>" value="<?php
if (isset($_SESSION['fr_password2'])) {
echo $_SESSION['fr_password2'];
unset($_SESSION['fr_password2']);
}
?>" class="haslo2"/>
<br/>
<br/>
<label class="regulamin">
<input type="checkbox" name="regulamin" <?php
if (isset($_SESSION['fr_regulamin'])) {
echo "checked";
unset($_SESSION['fr_regulamin']);
}
?>/>Akceptuje Regulamin</label>
<br/>
<?php
if (isset($_SESSION['e_regulamin'])) {
echo '<div class="error">' . $_SESSION['e_regulamin'] . '</div>';
unset($_SESSION['e_regulamin']);
}
?>
<br/>
<input type="submit" class="wyslij">
<br/>
</div>
</form>
</body>
</html><file_sep>/kontakt.php
<?php
session_start();
?>
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link rel="stylesheet" href="media/css/bilety.css">
<script src="media/js/jquery-3.2.1.min.js"></script>
<script src="media/js/bootstrap.min.js"></script>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container">
<div style="margin-top: 10%">
<div style="float: left; padding-left: 10%;margin-right: 10%;">
<h2 style="text-align: center;margin-bottom: 50px">Kontakt:</h2>
<h3><NAME>:</h3>
<h4>Rzeszow, ul. Sezamkowa 12</h4>
<h4><NAME> 12aa</h4>
<br/>
<h4>Rzeszow, ul. Landrynkowa 33b</h4>
<h4>Milenium Hall 12aa</h4>
<br/>
<h4>Rzeszow, ul. Czekoladowa 6</h4>
<h4>Amfiteatr 12aa</h4>
</div>
<div style="float: left">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d10251.167874979841!2d22.005947384191906!3d50.03399381163639!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1spl!2spl!4v1516591904654"
width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
</div>
<?php include 'stopka.php'; ?>
</body>
</html><file_sep>/index.php
<?php
session_start();
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $db_user, $db_password, $db_name);
$connection->set_charset("utf8");
if ($connection->connect_errno != 0) {
throw new Exception(mysqli_connect_errno());
} else {
$resultSet = $connection->query("SELECT * FROM filmy ORDER BY RAND() LIMIT 16");
if (!$resultSet) throw new Exception($connection->error);
$randomoweFilmy = $resultSet->fetch_all(MYSQLI_NUM);
if (isset($_POST['rezerwuj'])) {
$resultToAdd = $connection->query('INSERT INTO rezerwacje VALUES (' . $_SESSION['user_id'] . ',' . $_POST['rezerwuj'] . ')');
if (!$resultToAdd) throw new Exception($connection->error);
unset($_POST['rezerwuj']);
}
$connection->close();
}
} catch (Exception $e) {
echo '<span style="color:red;">Blad serwera.</span>';
echo '<br/>Informacja developerska:' . $e;
}
?>
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link rel="stylesheet" href="media/css/index.css">
<script src="media/js/jquery-3.2.1.min.js"></script>
<script src="media/js/bootstrap.min.js"></script>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container">
<h2>Nowosci w styczniu:</h2>
<form class="row" method="post">
<?php
foreach ($randomoweFilmy
as $film) {
?>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 plakat">
<img src="<?php echo $film[5] ?>">
<h6><?php echo $film[1] ?></h6>
</div>
<?php
}
?>
</form>
</div>
<?php include 'stopka.php'; ?>
</body>
</html><file_sep>/projektkino.sql
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 1172.16.58.3
-- Czas generowania: 22 Sty 2018, 05:17
-- Wersja serwera: 10.1.28-MariaDB
-- Wersja PHP: 7.1.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Baza danych: `projektkino`
--
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `filmy`
--
CREATE TABLE `filmy` (
`id` int(11) DEFAULT NULL,
`nazwa` text COLLATE utf16_polish_ci NOT NULL,
`opis` text COLLATE utf16_polish_ci NOT NULL,
`cena` int(11) NOT NULL,
`kategoria` text COLLATE utf16_polish_ci NOT NULL,
`plakat` text COLLATE utf16_polish_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf16 COLLATE=utf16_polish_ci;
--
-- Zrzut danych tabeli `filmy`
--
INSERT INTO `filmy` (`id`, `nazwa`, `opis`, `cena`, `kategoria`, `plakat`) VALUES
(1, 'Atak paniki', 'Radiowiec, kelner, panna młoda, pisarka, mąż i żona oraz behawiorysta zwierząt dostają ataku paniki.', 17, 'baśń', 'http://1.fwcdn.pl/po/28/05/772805/7807260.6.jpg'),
(2, '<NAME>', 'Auggie od urodzenia ma zdeformowaną twarz. W nowej szkole chłopiec chce udowodnić rówieśnikom, że piękno to więcej niż wygląd.', 17, 'akcja', 'http://1.fwcdn.pl/po/63/87/776387/7822508.6.jpg'),
(4, 'DJ', 'Maja to piękna oraz ambitna dziewczyna, utalentowana muzycznie. Przyjmuje pseudonim DJ Mini i wchodzi w świat muzyki klubowej. ', 17, 'horror', 'http://1.fwcdn.pl/po/57/60/795760/7819757.6.jpg'),
(5, '<NAME>', '<NAME>, spragniony miłości i ciepła, ucieka w świat baśni <NAME>.', 19, 'baśń', 'http://1.fwcdn.pl/po/79/33/767933/7816448.6.jpg'),
(6, 'Wszystkie pieniądze świata', 'Szesnastoletni wnuk najbogatszego człowieka świata zostaje uprowadzony. Jego oddana matka stara się przekonać nieustępliwego miliardera do zapłacenia okupu porywaczom.', 17, 'akcja', 'http://1.fwcdn.pl/po/20/92/782092/7822490.6.jpg'),
(7, 'Czas mroku', '<NAME> zostaje premierem Wielkiej Brytanii. Jego pierwszym zadaniem jest zjednoczenie narodu w obliczu groźby inwazji nazistowskich Niemiec.', 17, 'komedia ', 'http://1.fwcdn.pl/po/20/92/782092/7822490.6.jpg'),
(8, 'Więzień labiryntu: Lek na śmierć', 'Thomas wyrusza na misję w celu znalezienia lekarstwa zwalczającego śmiertelną chorobę.', 14, 'horror', 'http://1.fwcdn.pl/po/04/44/740444/7819035.6.jpg'),
(9, 'Tedi i mapa skarbów', '<NAME> wyjeżdża do Los Angeles, gdzie poznaje archeolożkę <NAME>. Niedługo potem zostaje porwana, a Tedi wyrusza jej na ratunek.', 17, 'baśń', 'http://1.fwcdn.pl/po/90/74/739074/7819193.6.jpg'),
(10, 'Dusza i ciało', 'Mária jest nowo przyjętą pracownicą działu kontroli mięsa w rzeźni, a Endre jej dyrektorem. Przypadkowo dowiadują się, że śnią identyczny sen, w którym są jeleniami. ', 19, 'akcja', 'http://1.fwcdn.pl/po/92/55/779255/7813488.6.jpg'),
(11, 'Atak paniki', 'Radiowiec, kelner, panna młoda, pisarka, mąż i żona oraz behawiorysta zwierząt dostają ataku paniki.', 17, 'baśń', 'http://1.fwcdn.pl/po/28/05/772805/7807260.6.jpg'),
(12, '<NAME>', 'Auggie od urodzenia ma zdeformowaną twarz. W nowej szkole chłopiec chce udowodnić rówieśnikom, że piękno to więcej niż wygląd.', 17, 'akcja', 'http://1.fwcdn.pl/po/63/87/776387/7822508.6.jpg'),
(14, 'DJ', 'Maja to piękna oraz ambitna dziewczyna, utalentowana muzycznie. Przyjmuje pseudonim DJ Mini i wchodzi w świat muzyki klubowej. ', 17, 'horror', 'http://1.fwcdn.pl/po/57/60/795760/7819757.6.jpg'),
(15, '<NAME>', 'Sześcio<NAME>, spragniony miłości i ciepła, ucieka w świat baśni <NAME>.', 19, 'baśń', 'http://1.fwcdn.pl/po/79/33/767933/7816448.6.jpg'),
(16, 'Wszystkie pieniądze świata', 'Szesnastoletni wnuk najbogatszego człowieka świata zostaje uprowadzony. Jego oddana matka stara się przekonać nieustępliwego miliardera do zapłacenia okupu porywaczom.', 17, 'akcja', 'http://1.fwcdn.pl/po/20/92/782092/7822490.6.jpg'),
(17, '<NAME>', '<NAME> zostaje premierem Wielkiej Brytanii. Jego pierwszym zadaniem jest zjednoczenie narodu w obliczu groźby inwazji nazistowskich Niemiec.', 17, 'komedia ', 'http://1.fwcdn.pl/po/20/92/782092/7822490.6.jpg'),
(18, 'Więzień labiryntu: Lek na śmierć', 'Thomas wyrusza na misję w celu znalezienia lekarstwa zwalczającego śmiertelną chorobę.', 14, 'horror', 'http://1.fwcdn.pl/po/04/44/740444/7819035.6.jpg'),
(19, 'Tedi i mapa skarbów', '<NAME> wyjeżdża do Los Angeles, gdzie poznaje archeolożkę <NAME>. Niedługo potem zostaje porwana, a Tedi wyrusza jej na ratunek.', 17, 'baśń', 'http://1.fwcdn.pl/po/90/74/739074/7819193.6.jpg'),
(20, 'Dusza i ciało', 'Mária jest nowo przyjętą pracownicą działu kontroli mięsa w rzeźni, a Endre jej dyrektorem. Przypadkowo dowiadują się, że śnią identyczny sen, w którym są jeleniami. ', 19, 'akcja', 'http://1.fwcdn.pl/po/92/55/779255/7813488.6.jpg');
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `rezerwacje`
--
CREATE TABLE `rezerwacje` (
`id_uzytkownik` int(15) NOT NULL,
`id_film` int(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Zrzut danych tabeli `rezerwacje`
--
INSERT INTO `rezerwacje` (`id_uzytkownik`, `id_film`) VALUES
(2, 2),
(2, 11),
(2, 19);
-- --------------------------------------------------------
--
-- Struktura tabeli dla tabeli `uzytkownicy`
--
CREATE TABLE `uzytkownicy` (
`id` int(11) NOT NULL,
`login` text COLLATE utf8_polish_ci NOT NULL,
`haslo` text COLLATE utf8_polish_ci NOT NULL,
`email` text COLLATE utf8_polish_ci NOT NULL,
`imieINazwisko` text COLLATE utf8_polish_ci NOT NULL,
`rola` text COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
--
-- Zrzut danych tabeli `uzytkownicy`
--
INSERT INTO `uzytkownicy` (`id`, `login`, `haslo`, `email`, `imieINazwisko`, `rola`) VALUES
(1, 'admin', '$2y$10$MBHG7EEDiKFVMdrhY4gkLuBiXn7qLgVpGgjF4osY9sP9VeYWAl5SC', '<EMAIL>', 'admin', 'admin'),
(2, 'user', '$2y$10$MBHG7EEDiKFVMdrhY4gkLuBiXn7qLgVpGgjF4osY9sP9VeYWAl5SC', '<EMAIL>', 'user', 'user');
--
-- Indeksy dla zrzutów tabel
--
--
-- Indexes for table `filmy`
--
ALTER TABLE `filmy`
ADD UNIQUE KEY `id` (`id`);
--
-- Indexes for table `uzytkownicy`
--
ALTER TABLE `uzytkownicy`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `id` (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT dla tabeli `uzytkownicy`
--
ALTER TABLE `uzytkownicy`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/bilety.php
<?php
session_start();
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $db_user, $db_password, $db_name);
$connection->set_charset("utf8");
if ($connection->connect_errno != 0) {
throw new Exception(mysqli_connect_errno());
} else {
$resultSet = $connection->query("SELECT * FROM filmy ORDER BY RAND() LIMIT 10");
if (!$resultSet) throw new Exception($connection->error);
$randomoweFilmy = $resultSet->fetch_all(MYSQLI_NUM);
if (isset($_POST['rezerwuj'])) {
$resultToAdd = $connection->query('INSERT INTO rezerwacje VALUES (' . $_SESSION['user_id'] . ',' . $_POST['rezerwuj'] . ')');
if (!$resultToAdd) throw new Exception($connection->error);
unset($_POST['rezerwuj']);
}
$connection->close();
}
} catch (Exception $e) {
echo '<span style="color:red;">Blad serwera.</span>';
echo '<br/>Informacja developerska:' . $e;
}
?>
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link rel="stylesheet" href="media/css/bilety.css">
<script src="media/js/jquery-3.2.1.min.js"></script>
<script src="media/js/bootstrap.min.js"></script>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container">
<h2>Przeglad Filmow w Styczniu:</h2>
<form method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>nazwa</th>
<th>opis</th>
<th>cena</th>
<th>kategoria</th>
</tr>
</thead>
<tbody>
<?php
foreach ($randomoweFilmy
as $film) {
?>
<tr>
<td><img src="<?php echo $film[5] ?>"/></td>
<td><?php echo $film[1] ?></td>
<td><?php echo $film[2] ?></td>
<td><?php echo $film[3] ?> zl</td>
<td><?php echo $film[4] ?></td>
<?php
if (isset($_SESSION['zalogowany']) && $_SESSION['rola'] == 'user') {
echo '<td>';
echo '<button type="submit" name="rezerwuj" value="' . $film[0] . '" class="btn btn-warning delete">Rezerwuj</button>';
echo '</td>';
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
</form>
</div>
<?php include 'stopka.php'; ?>
</body>
</html><file_sep>/administrator.php
<?php
session_start();
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
if (!isset($_SESSION['rola']) || $_SESSION['rola'] != 'admin') {
header('Location: index.php');
exit();
}
try {
$connection = new mysqli($host, $db_user, $db_password, $db_name);
$connection->set_charset("utf8");
if ($connection->connect_errno != 0) {
throw new Exception(mysqli_connect_errno());
} else {
if (isset($_POST['usunUzytkownika'])) {
$result = $connection->query('DELETE FROM uzytkownicy WHERE uzytkownicy.id = ' . $_POST['usunUzytkownika']);
if (!$result) throw new Exception($connection->error);
unset($_POST['usunUzytkownika']);
}
if (isset($_POST['usunFilm'])) {
$result = $connection->query('DELETE FROM filmy WHERE filmy.id = ' . $_POST['usunFilm']);
if (!$result) throw new Exception($connection->error);
unset($_POST['usunFilm']);
}
$resultSet = $connection->query("SELECT * FROM filmy");
if (!$resultSet) throw new Exception($connection->error);
$randomoweFilmy = $resultSet->fetch_all(MYSQLI_NUM);
$resultSet = $connection->query("SELECT * FROM uzytkownicy");
if (!$resultSet) throw new Exception($connection->error);
$uzytkownicy = $resultSet->fetch_all(MYSQLI_NUM);
$connection->close();
}
} catch (Exception $e) {
echo '<span style="color:red;">Blad serwera.</span>';
echo '<br/>Informacja developerska:' . $e;
}
?>
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="media/css/bootstrap.min.css">
<link rel="stylesheet" href="media/css/bilety.css">
<script src="media/js/jquery-3.2.1.min.js"></script>
<script src="media/js/bootstrap.min.js"></script>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container">
<h2>Filmy</h2>
<form method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>nazwa</th>
<th>opis</th>
<th>cena</th>
<th>kategoria</th>
<th>akcja</th>
</tr>
</thead>
<tbody>
<?php
foreach ($randomoweFilmy
as $film) {
?>
<tr>
<td><?php echo $film[0] ?></td>
<td><?php echo $film[1] ?></td>
<td><?php echo $film[2] ?></td>
<td><?php echo $film[3] ?></td>
<td><?php echo $film[4] ?></td>
<?php
echo '<td>';
echo '<button type="submit" name="usunFilm" value="' . $film[0] . '" class="btn btn-danger delete">usun</button>';
echo '</td>';
?>
</tr>
<?php
}
?>
</tbody>
</table>
</form>
</div>
<div class="container">
<h2>Uzytkownicy</h2>
<form method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>login</th>
<th>email</th>
<th>imie i nazwisko</th>
<th>rola</th>
<th>akcja</th>
</tr>
</thead>
<tbody>
<?php
foreach ($uzytkownicy
as $uzytkownik) {
?>
<tr>
<td><?php echo $uzytkownik[0] ?></td>
<td><?php echo $uzytkownik[1] ?></td>
<td><?php echo $uzytkownik[3] ?></td>
<td><?php echo $uzytkownik[4] ?></td>
<td><?php echo $uzytkownik[5] ?></td>
<?php
echo '<td>';
echo '<button type="submit" name="usunUzytkownika" value="' . $uzytkownik[0] . '" class="btn btn-danger delete">usun</button>';
echo '</td>';
?>
</tr>
<?php
}
?>
</tbody>
</table>
</form>
</div>
<?php include 'stopka.php'; ?>
</body>
</html><file_sep>/logowanie.php
<?php
session_start();
if ((!isset($_POST['login'])) || (!isset($_POST['haslo']))) {
header('Location: index.php');
exit();
}
require_once "connect.php";
$connection = @new mysqli($host, $db_user, $db_password, $db_name);
$connection->set_charset("utf8");
if ($connection->connect_errno != 0) {
echo "Blad: " . $connection->connect_errno;
} else {
$login = $_POST['login'];
$haslo = $_POST['haslo'];
$login = htmlentities($login, ENT_QUOTES, "UTF-8");
$haslo = htmlentities($haslo, ENT_QUOTES, "UTF-8");
if ($resultSet = @$connection->query(
sprintf("SELECT * FROM uzytkownicy WHERE login='%s'",
mysqli_real_escape_string($connection, $login)))) {
$chosenResult = $resultSet->num_rows;
if ($chosenResult > 0) {
$row = $resultSet->fetch_assoc();
if (password_verify($haslo, $row['haslo'])) {
$_SESSION['zalogowany'] = true;
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_login'] = $row['login'];
$_SESSION['user_imieINazwisko'] = $row['imieINazwisko'];
$_SESSION['email'] = $row['email'];
$_SESSION['rola'] = $row['rola'];
unset($_SESSION['login_error']);
$resultSet->free_result();
header('Location: index.php');
} else {
$_SESSION['login_error'] = 'blad logowania';
header('Location: index.php');
}
} else {
$_SESSION['login_error'] = 'blad logowania';
header('Location: index.php');
}
}
$connection->close();
}
?>
|
1ec4bf8a88d4a630e958a49b75bf9ae7671c465a
|
[
"SQL",
"PHP"
] | 8
|
PHP
|
awilk46/projektkino
|
42c3bfa831f723ac4cafd22f9b04c199cc3771f7
|
50051c6ef87b14f1a5eda92d525b8430b5745efa
|
refs/heads/master
|
<file_sep>package seleniumwd;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class MultipleFrames {
public static void main(String[] args) throws Exception {
File pathBinary=new File("C:\\Users\\ext-sdasari\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver(new FirefoxBinary(pathBinary), new FirefoxProfile());
driver.get("https://docs.oracle.com/javase/7/docs/api/");
driver.manage().window().maximize();
WebElement[] framee = {driver.findElement(By.name("packageFrame")),driver.findElement(By.name("packageListFrame"))};
System.out.println(driver.switchTo().frame(framee[0]).findElements(By.tagName("a")).size());
driver.switchTo().parentFrame();
System.out.println(driver.switchTo().frame(framee[1]).findElements(By.tagName("a")).size());
driver.close();
}
}
<file_sep>package package001;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello Sneha, Welcome to Java programing world");
}
}
<file_sep>package junitpackage;
import java.io.File;
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.PageFactory;
public class HomePage
{
File pathBinary = new File("C:\\Users\\ext-sdasari\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver(new FirefoxBinary(pathBinary), new FirefoxProfile());
@Before
public void launchApp(){
driver.get("https://easy.techmahindra.com");
driver.manage().window().maximize();
}
@After
public void closeApp()
{
driver.close();
}
@Test
public void LoginFunctionality() throws Exception
{
HomePOM hpom=PageFactory.initElements(driver, HomePOM.class);
//HomeRM homeRM = new HomeRM();
FileInputStream f = new FileInputStream("D:\\Sneha\\Selenium\\TestData\\LoginTestData.xls");
Workbook workbook= Workbook.getWorkbook(f);
Sheet sheet = workbook.getSheet(0);
hpom.Uid.sendKeys(sheet.getCell(0, 0).getContents());
System.out.println(sheet.getCell(0, 0).getContents());
}
}
<file_sep>package package002;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SeleniumWebD {
public static void main(String[] args)
{
File pathBinary = new File("C:\\Users\\ext-sdasari\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile);
driver.get("https://hydowa.techmahindra.com");
driver.manage().window().maximize();
driver.findElement(By.id("txtLanId")).sendKeys("SD00477954");
driver.findElement(By.id("txtPassword")).sendKeys("<PASSWORD>");
driver.findElement(By.id("btnlogin")).click();
driver.findElement(By.id("TimesheetEntrylinkNew")).click();
//driver.findElement(By.id("btnsearchTask_11")).click();
}
}
<file_sep>package seleniumwd;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class RediffHomePage
{
By SignInLink = By.xpath(".//*[@id='signin_info']/a[1]");
@FindBy(xpath=".//*[@id='signin_info']/a[2]") WebElement RegistrationLink;
}
<file_sep>package junitpackage;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class HomePOM
{
@FindBy(xpath=".//*[@id='txtLanId']") WebElement Uid;
@FindBy(xpath=".//*[@id='txtPassword']") WebElement Pass;
}
<file_sep>package seleniumwd;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Excel_ReadWrite {
public static void main(String[] args) throws Exception
{
FileInputStream f = new FileInputStream("D:\\Sneha\\Selenium\\IFS.xls");
Workbook wb = Workbook.getWorkbook(f);
Sheet s=wb.getSheet("Business Interface");
String s1=s.getCell(7,8).getContents();
s=wb.getSheet("Business Interface");
s1+=s.getCell(5,5).getContents();
FileOutputStream fo = new FileOutputStream("D:\\Sneha\\Selenium\\Output.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("Result Sheet", 1);
Label l=new Label(0,0,s1);
ws.addCell(l);
wwb.write();
wwb.close();
}
}
<file_sep>package takedasites;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestSite {
public static void main(String[] args) {
File pathBinary=new File("C:\\Users\\ext-sdasari\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver(new FirefoxBinary(pathBinary),new FirefoxProfile());
driver.get("https://mytakeda.sharepoint.com/sites/myTakeda-Dev/rohittest/SitePages/Home.aspx");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement uid=wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("i0116")));
uid.sendKeys("<EMAIL>");
WebElement next=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='idSIButton9']")));
next.click();
WebElement pwd=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='i0118']")));
pwd.sendKeys("<PASSWORD>");
driver.findElement(By.xpath(".//*[@id='idSIButton9']")).click();
driver.findElement(By.xpath(".//*[@id='KmsiCheckboxField']")).click();
driver.findElement(By.xpath(".//*[@id='idSIButton9']")).click();
System.out.println(driver.getTitle());
driver.findElement(By.xpath(".//*[@id='zz14_RootAspMenu']/li[6]/a")).click();
driver.findElement(By.xpath(".//*[@id='appRoot']/div/div[3]/div/div[2]/div[2]/div/div[2]/div[1]/div/div/a")).click();
driver.findElement(By.xpath(".//*[@id='idHomePageNewItem']/span[2]")).click();
driver.findElement(By.xpath(".//*[@id='Gender_25642945-b2c5-483e-b301-3b921f87edb5_$RadioButtonChoiceField0']")).click();
System.out.println(driver.findElement(By.xpath(".//*[@id='Gender_25642945-b2c5-483e-b301-3b921f87edb5_$RadioButtonChoiceField0']")).getAttribute("value"));
/*Select dropdown = new Select(driver.findElement(By.xpath(".//*[@id='Designation_3f975d33-dc4e-4690-8f74-0751d6b4a1f7_$DropDownChoice']")));
dropdown.selectByIndex(2);
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.SECONDS);
dropdown.selectByValue("Software Engineer");
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.SECONDS);
dropdown.selectByVisibleText("Assosciate Software Engineer");*/
//driver.quit();
}
}
<file_sep>package seleniumwd;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class RediffRegistrationPage {
@FindBy(xpath=".//*[@id='tblcrtac']/tbody/tr[3]/td[3]/input") WebElement Uid;
By pass=By.xpath(".//*[@id='tblcrtac']/tbody/tr[7]/td[3]/input[1]");
}
<file_sep>package seleniumwd;
import java.io.File;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class HandlingAlerts {
public static void main(String[] args) throws Exception{
File pathBinary = new File("C:\\Users\\ext-sdasari\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxbinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxprofile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(firefoxbinary,firefoxprofile);
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
WebElement button = driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/div[1]/div/form/div/div[6]/div[1]/input"));
button.click();
Thread.sleep(3000);
Alert a=driver.switchTo().alert();
System.out.println(a.getText());
a.dismiss();
driver.close();
}
}
|
5251016a1d6f3f6a7b2deaae5d350d96742a480a
|
[
"Java"
] | 10
|
Java
|
sdasari96/FreeCRMTest
|
7a2ac627df274e81a1d075042b389ea11c5ecf4b
|
4fb046f97d58bfef0f998e9b1736d817f37da7fe
|
refs/heads/master
|
<repo_name>wangbj/detnet<file_sep>/Cargo.toml
[package]
name = "detnet"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
nix = "0.12"
combine = "3.6"
libc = "0.2"
<file_sep>/src/lib.rs
use combine::{many1, none_of, Parser, sep_by, sep_end_by, choice, attempt};
use combine::char::*;
use std::result::*;
use combine::error::*;
use std::string::*;
use std::fs::File;
use std::io::prelude::*;
use std::io::Error;
use std::io::ErrorKind;
#[derive(Debug)]
#[derive(Clone)]
struct Group {
name: String,
password: String,
gid: u32,
users: Vec<String>,
}
fn parse_fields(fields: Vec<String>) -> Result<Group, StringStreamError> {
let userp = many1(none_of(",".chars()));
let mut parser = sep_by(userp, char(',')).map(|words: Vec<String> | words);
let ret = match fields.as_slice() {
[username, password, gidstring, users_fields] => {
let gid = gidstring.parse::<u32>().expect("gid must be an positive integer");
parser.parse(users_fields.as_str()).map(|x| Group {name: username.clone(), password: <PASSWORD>.clone(), gid: gid, users: x.0})
},
[username, password, gidstring] => {
let gid = gidstring.parse::<u32>().expect("gid must be an positive integer");
Ok(Group {name: username.clone(), password: <PASSWORD>.clone(), gid: gid, users: Vec::new() })
},
_ => Err(StringStreamError::UnexpectedParse)
};
ret
}
fn parse_group_entry (line: &str) -> Result<Group, StringStreamError> {
let word = many1(none_of(":".chars()));
let grp_with_users = sep_by(word.clone(), char(':')).map(|words: Vec<String> | words);
let grp_without_users = sep_end_by(word.clone(), char(':')).map(|words: Vec<String> | words);
let mut p = choice((attempt(grp_with_users), grp_without_users));
p.parse(line).map(|x| x.0).map(|x| parse_fields(x)).and_then(|x| x)
}
pub fn from_group(desired: &str) -> Result<u32, std::io::Error> {
let mut f = File::open("/etc/group")?;
let mut contents = String::new();
f.read_to_string(&mut contents)?;
let all_groups :Result<Vec<Group>, StringStreamError> = contents.lines().map(|e| parse_group_entry(e)).collect();
let groups: Vec<u32> = all_groups.expect("failed to parse /etc/group").iter().filter(|x| x.name == desired).map(|x|x.gid).collect();
match groups[..] {
[found] => Ok(found),
_ => {
let errmsg = String::from("cannot find group: ");
Err(Error::new(ErrorKind::Other, errmsg + desired))
},
}
}
<file_sep>/src/main.rs
#![allow(unused_imports)]
#![allow(dead_code)]
extern crate nix;
extern crate combine;
extern crate libc;
use std::thread;
use std::fs;
use std::fs::File;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::MetadataExt;
use std::io::prelude::*;
use std::io::Error;
use std::io::ErrorKind;
use std::os::unix::net::{UnixStream, UnixListener};
use nix::unistd::*;
use libc::{uid_t, gid_t};
use detnet;
fn handle_client(mut stream: UnixStream) {
let mut message = String::new();
stream.read_to_string(&mut message).unwrap();
println!("{}", message);
}
fn check_user_root() -> std::io::Result<()> {
unsafe { let euid = libc::geteuid() as u32;
match euid {
0 => Ok(()),
_ => Err(Error::new(ErrorKind::PermissionDenied, "must run as root")),
}
}
}
fn detnet_main() {
check_user_root().unwrap();
let dettrace_group = detnet::from_group("dettrace").expect("dettrace group not found");
let unp = "/var/run/dettrace.sock";
fs::remove_file(unp).ok();
let listener = UnixListener::bind(unp).unwrap();
let mut perms = fs::metadata(unp).unwrap().permissions();
perms.set_mode(0o660);
fs::set_permissions(unp, perms).expect(&format!("change {} permission to 0660", unp));
let uid = nix::unistd::Uid::from_raw(0);
let gid = nix::unistd::Gid::from_raw(dettrace_group as gid_t);
nix::unistd::chown(unp, Some(uid), Some(gid)).expect(&format!("failed to chown {}", unp));
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(||handle_client(stream));
}
Err(_err) => {
break;
}
}
}
}
fn main() {
detnet_main();
}
#[cfg(test)]
mod tests {
#[test]
fn root_group_exists() {
assert_eq!(detnet::from_group("root").unwrap_or(65535), 0);
}
#[test]
fn nonexist_group() {
assert_eq!(detnet::from_group("doesnotExist").unwrap_or(65535), 65535);
}
}
|
b7fc7c1fa5759b84142e952c5ad992698c861a62
|
[
"TOML",
"Rust"
] | 3
|
TOML
|
wangbj/detnet
|
4810182ec4cca677a88db1247c0548636914d747
|
dcd2b506990f114b1dd7916975aea40ff6dc8bd9
|
refs/heads/master
|
<file_sep>package hu.uniobuda.nik.androgamers.main_menu;
import android.content.Context;
public interface IServerConnected {
public void ServerConnected(Context context);
}
<file_sep>SkillGame
=========
Semester project for the BIR Android course.
In summary, SkillGame is a multiplayer game that can be played by two players over Wi-Fi.
The players compete with each other solving and go through the mini games in time.
The game can be exciting for all the members of the family.
<file_sep>package hu.uniobuda.nik.androgamers.game_files;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import hu.uniobuda.nik.androgamers.R;
public class SzinvalasztoActivity extends Activity implements INextGame {
private static Handler handler;
//Következő játék indítása új Activityben
public void NextGame() {
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SzinvalasztoActivity.this, RajzolgatoActivity.class);
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_szinvalaszto);
GameAbstract.init();
handler = new Handler(Looper.getMainLooper());
SzinvalasztoView.setNext_game(this);
Toast.makeText(this, GameAbstract.SZINVALASZTO_TEXT, Toast.LENGTH_LONG).show();
}
}
<file_sep>package hu.uniobuda.nik.androgamers.main_menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import hu.uniobuda.nik.androgamers.R;
public class MainActivity extends Activity {
private Button startButton;
private Button profileButton;
private Button infoButton;
private Button helpButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Játék kezdése
startButton = (Button) findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent connectActivity = new Intent(MainActivity.this, ConnectActivity.class);
startActivity(connectActivity);
}
});
//Profil
profileButton = (Button) findViewById(R.id.profil_button);
profileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent profileActivity = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileActivity);
}
});
//Információ
infoButton = (Button) findViewById(R.id.info_button);
infoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title)
.setCancelable(false)
.setPositiveButton("OK", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
//Leírás
helpButton = (Button) findViewById(R.id.help_button);
helpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent helpActivity = new Intent(MainActivity.this, HelpActivity.class);
startActivity(helpActivity);
}
});
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
}
<file_sep>package hu.uniobuda.nik.androgamers.main_menu;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseAR {
DataBaseHandler db;
public DataBaseAR(Context context) {
db = new DataBaseHandler(context);
}
public long insertHighScore(int score) {
ContentValues contentValues = new ContentValues();
contentValues.put(DataBaseHandler.SCORE, score);
SQLiteDatabase sqLiteDatabase = db.getWritableDatabase();
long id = sqLiteDatabase.insert(DataBaseHandler.TABLE_NAME, null, contentValues);
db.close();
return id;
}
public Cursor loadHighScores() {
SQLiteDatabase sqLiteDatabase = db.getReadableDatabase();
Cursor c = sqLiteDatabase.query(DataBaseHandler.TABLE_NAME, null, null, null, null, null, DataBaseHandler.SCORE + " DESC", "10");
c.moveToFirst();
db.close();
return c;
}
class DataBaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "SkillGame.db";
private static final String TABLE_NAME = "highscore";
private static final String UID = "_id";
private static final String SCORE = "score";
private static final int DATABASE_VERSION = 1;
private Context context;
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SCORE + " INTEGER);");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
onCreate(sqLiteDatabase);
}
}
}<file_sep>package hu.uniobuda.nik.androgamers.main_menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import hu.uniobuda.nik.androgamers.R;
import hu.uniobuda.nik.androgamers.Result;
import hu.uniobuda.nik.androgamers.ResultAdapter;
public class ProfileActivity extends Activity {
private final static String usernameFilePath = "User";
private final int CAMERA_REQUEST = 1;
private final int SELECT_PICTURE = 2;
private ImageView userpic;
private ImageView camera;
private ImageView gallery;
private ListView listview;
private List<Result> results;
private ResultAdapter adapter;
private TextView nameLabel;
private EditText txtUserName;
//Kép betöltése belső tárolóból
public static Bitmap loadImage(Context context) {
StringBuilder builder = new StringBuilder();
int charsRead;
char[] buffer = new char[4096];
String FILENAME = "UserPic";
try {
FileInputStream fis = context.openFileInput(FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while ((charsRead = reader.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
builder.append(message);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] img_bytes = builder.toString().getBytes();
byte[] base_decoded = Base64.decode(img_bytes, 0); //Base64
return BitmapFactory.decodeByteArray(base_decoded, 0, base_decoded.length); //jpeg dekódolás
}
//read username from file
public static String getUsername(Context context) {
String text = "DefaultUser";
try {
//create if not exist
File file = new File(String.valueOf(context.getApplicationContext().getFileStreamPath(usernameFilePath)));
if (!file.exists()) {
setUsername(context, text);
}
//read
FileInputStream fis = context.openFileInput(usernameFilePath);
byte[] buffer = new byte[1024];
int len;
text = "";
while ((len = fis.read(buffer)) > 0) {
text += new String(buffer, 0, len);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
//save username to file
public static void setUsername(Context context, String username) {
try {
//save
FileOutputStream fos = context.openFileOutput(usernameFilePath, MODE_PRIVATE);
fos.write(username.getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//load username
nameLabel = (TextView) findViewById(R.id.name_label);
nameLabel.setText(getUsername(this));
nameLabel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txtUserName = new EditText(ProfileActivity.this);
txtUserName.setHint("Anonymus");
txtUserName.setMaxWidth(200);
txtUserName.setMaxLines(1);
new AlertDialog.Builder(ProfileActivity.this)
.setTitle("Felhasználónév")
.setMessage("Add meg az új felhasználóneved:")
.setView(txtUserName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name = txtUserName.getText().toString().trim();
if (name.matches("")) return;
setUsername(ProfileActivity.this, name);
nameLabel.setText(name);
}
})
.setNegativeButton("Mégse", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
});
userpic = (ImageView) findViewById(R.id.userpic);
Bitmap image = loadImage(ProfileActivity.this); //Betöltjük a felhasználó képét
if (image == null) //Lementjük a default képet, hogy a felhasználó képe ne legyen null
saveImage(((BitmapDrawable) userpic.getDrawable()).getBitmap());
else
userpic.setImageBitmap(image);
camera = (ImageView) findViewById(R.id.camera);
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
gallery = (ImageView) findViewById(R.id.gallery);
gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
});
// -------------- DB local highscore
DataBaseAR dbAR = new DataBaseAR(this);
results = new ArrayList<Result>();
Cursor c = dbAR.loadHighScores();
while (!c.isAfterLast()) {
String score = c.getString(c.getColumnIndex("score"));
results.add(new Result(Integer.valueOf(score)));
c.moveToNext();
}
//---------------------------------------------
adapter = new ResultAdapter(results);
listview = (ListView) findViewById(R.id.list_results);
listview.setAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap photo;
Bitmap scaled_photo = null;
//kép készítése kamerával
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
if (photo == null)
return;
scaled_photo = Bitmap.createScaledBitmap(photo, 200, 200, false);
userpic.setImageBitmap(scaled_photo);
}
//Kép betöltése galériából
else if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//első kép betöltése -> a válaszott fájl
photo = BitmapFactory.decodeFile(picturePath);
if (photo == null)
return;
scaled_photo = Bitmap.createScaledBitmap(photo, 200, 200, false);
userpic.setImageBitmap(scaled_photo);
}
if (scaled_photo == null)
return;
saveImage(scaled_photo);
}
//Kép mentése belső tárolóra: jpeg és base64 kódolás
private void saveImage(Bitmap photo) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 85, stream);
byte[] byteArray = stream.toByteArray();
byte[] img_bytes = Base64.encode(byteArray, 0);
String FILENAME = "UserPic";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(img_bytes);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package hu.uniobuda.nik.androgamers.game_files;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
//Következő játék megjelenítése
interface INextGame {
void NextGame();
}
public abstract class GameAbstract extends View {
public static final String SZINVALASZTO_NAME = "APP1";
public static final String RAJZOLGATO_NAME = "APP2";
public static final String PARBAJOZO_NAME = "APP3";
public static final String SZAMOLGATO_NAME = "APP4";
public static final String SZINVALASZTO_TEXT = "Koppints, ha a felirat szövege és színe megegyezik!";
public static final String RAJZOLGATO_TEXT = "Rajzold meg a legkisebb befoglaló téglalapot!";
public static final String PARBAJOZO_TEXT = "Te légy a gyorsabb párbajozó!";
public static final String SZAMOLGATO_TEXT = "Oldd meg az egyenletet!";
protected static final int GAME_COUNT = 5; //Játszmák száma
protected static int[] game_points = new int[4]; //Az egyes játékok végső pontszámai
private static boolean game_finished = false;
protected final long GAME_MILLIS = 2500; //Játszma ideje
protected long old_time = 0; //Játszma időméréshez a régebben mért idő
protected Thread time_thread; //Játszma méréshez háttérszál
protected int current_game = 0;
protected int view_size_width = 1000;
protected int view_size_height = 500;
public GameAbstract(Context context, AttributeSet attrs) {
super(context, attrs);
}
//getter
public static boolean isGame_finished() {
return game_finished;
}
//setter
public static void setGame_finished(boolean _game_finished) {
game_finished = _game_finished;
}
//Új játék esetén beállítja a megfelelő kezdő értékeket
public static void init() {
for (int i = 0; i < game_points.length; i++) {
game_points[i] = 0;
}
game_finished = false;
}
//Az összpontszám lekérdezése
public static int getFinalPoint() {
int sum = 0;
for (int point : game_points) {
sum += point;
}
return sum;
}
public abstract void GetResult(); //Végső pontszám kiszámítása
public abstract void Init(); //Kezdeti inicializálás
protected abstract void GameInit(); //Játszma inicializálás
}
|
e35b6f184cf029323929d5782380aef1000a7bdf
|
[
"Markdown",
"Java"
] | 7
|
Java
|
p4farkas/SkillGame
|
9621872020e7d11685c0bbefe7e6ca04b6170a1e
|
d9365e4d98a7e8c277ba0513098b856b10dc3541
|
refs/heads/master
|
<repo_name>yanzixiang/YZX.TIA<file_sep>/YZX.TIA/Proxies/PLBlockEditorControlElementProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YZX.Tia.Proxies
{
class PLBlockEditorControlElementProxy
{
}
}
<file_sep>/YZX.TIA/Proxies/DebugDeviceProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonServices;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.PlcLanguages.TisServer;
using Reflection;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
public class DebugDeviceProxy
{
public DebugDevice DebugDevice;
public DebugDeviceProxy(DebugDevice dd)
{
DebugDevice = dd;
}
public ILegitimationService LegitimationService
{
get
{
return Reflector.GetInstanceFieldByName(DebugDevice, "m_LegitimationService", ReflectionWays.SystemReflection)
as ILegitimationService;
}
set
{
Reflector.SetInstanceFieldByName(DebugDevice, "m_LegitimationService", value, ReflectionWays.SystemReflection);
}
}
public List<DebugJob> JobList
{
get
{
return DebugDevice.JobList;
}
}
public ICoreObject Controller
{
get
{
return (ICoreObject)Reflector.GetInstanceFieldByName(
DebugDevice,
"m_Controller",
ReflectionWays.SystemReflection);
}
}
public IConnection Connection
{
get
{
return DebugDevice.Connection;
}
set
{
Reflector.SetInstanceFieldByName(
DebugDevice,
"m_Connection",
value,
ReflectionWays.SystemReflection);
}
}
public ConnectionState ConnectionState
{
get
{
return (ConnectionState)Reflector.GetInstanceFieldByName(
DebugDevice,
"m_ConnectionState",
ReflectionWays.SystemReflection);
}
set
{
Reflector.SetInstanceFieldByName(
DebugDevice,
"m_ConnectionState",
value,
ReflectionWays.SystemReflection);
}
}
public IOnlineService OnlineService
{
get
{
return Reflector.GetInstanceFieldByName(DebugDevice,
"m_OnlineService",
ReflectionWays.SystemReflection)
as IOnlineService;
}
}
public ConnectionServiceProvider ConnectionService
{
get
{
IConnectionService ics = Reflector.GetInstanceFieldByName(DebugDevice,
"m_ConnectionService",
ReflectionWays.SystemReflection)
as IConnectionService;
return ics.ToConnectionServiceProvider();
}
}
public DebugService DebugService
{
get
{
return DebugDevice.DebugService;
}
}
private void OnConnectionStateChange(
OamCallbackMessage message,
int Flags,
int referenceCount,
byte[] buffer,
DateTime timeStamp,
TimeSpan elapsedTime,
object oamSource,
object ClientSource)
{
Reflector.RunInstanceMethodByName(DebugDevice, "OnConnectionStateChange",
ReflectionWays.SystemReflection,
message,
Flags,
referenceCount,
buffer,
timeStamp,
elapsedTime,
oamSource,
ClientSource);
}
public bool IsPlusDevice
{
get
{
return DebugDevice.IsPlusDevice;
}
}
public event AfterConnectedHandler AfterConnected;
public int NumberOfClients
{
get
{
return (int)Reflector.GetInstanceFieldByName(DebugDevice, "m_NumberOfClients", ReflectionWays.SystemReflection);
}
set
{
Reflector.SetInstanceFieldByName(DebugDevice, "m_NumberOfClients", value, ReflectionWays.SystemReflection);
}
}
public void FireAfterConnected(IAsyncResult ar)
{
AsyncConnectRequest arc = ar as AsyncConnectRequest;
AfterConnectedEventArgs args = new AfterConnectedEventArgs();
args.AsyncConnectRequest = arc;
AfterConnected(this, args);
}
public void OnConnectToOnline(IAsyncResult iar)
{
Reflector.RunInstanceMethodByName(
DebugDevice,
"OnConnectToOnline",
ReflectionWays.SystemReflection,
iar);
ConnectionState = ConnectionState.Online;
FireAfterConnected(iar);
}
public delegate void AfterConnectedHandler(object sender, AfterConnectedEventArgs args);
public class AfterConnectedEventArgs : EventArgs
{
public AsyncConnectRequest AsyncConnectRequest;
}
public ITisDevice TisDevice
{
get
{
object o = Reflector.GetInstanceFieldByName(DebugDevice, "m_TisDevice", ReflectionWays.SystemReflection);
ITisDevice itd = o as ITisDevice;
return itd;
}
set
{
Reflector.SetInstanceFieldByName(DebugDevice, "m_TisDevice", value, ReflectionWays.SystemReflection);
}
}
public IDebugDeviceOnlinePermission DebugDeviceOnlinePermission
{
get
{
return DebugDevice as IDebugDeviceOnlinePermission;
}
}
public IMessageCell GetPermissionForOnlineSession(JobType jobType)
{
return DebugDeviceOnlinePermission.GetPermissionForOnlineSession(jobType);
}
public static bool AllowStatusForLivelist
{
get
{
return DebugDevice.AllowStatusForLivelist;
}
set
{
DebugDevice.AllowStatusForLivelist = value;
}
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.GoOnlineCommands.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Automation.DomainServices.UI.GoOnline;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
namespace YZX.Tia
{
partial class TiaStarter
{
GoOnlineCommands m_GoOnlineCommands = null;
public GoOnlineCommands GoOnlineCommands
{
get
{
if(m_GoOnlineCommands == null)
{
m_GoOnlineCommands = new GoOnlineCommands();
IDlc dlc_GoOnlineCommands = m_GoOnlineCommands as IDlc;
dlc_GoOnlineCommands.Attach(m_BusinessLogicApplicationContext);
}
return m_GoOnlineCommands;
}
}
public CommandResult GoOnlineCommands_Excute(ICommand command)
{
ICommandTarget ict = GoOnlineCommands as ICommandTarget;
return ict.Execute(command);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.FormInvoke.cs
using System;
using System.Windows.Forms;
namespace YZX.Tia
{
partial class TiaStarter
{
public static void TIAInvokeAction(Action action,int timeout = 1000)
{
if(m_MainApplicationForm != null)
{
m_MainApplicationForm.Invoke(action);
}
}
public static object TIAInvokeFunc(Func<object> func, int timeout = 1000)
{
if (m_MainApplicationForm != null)
{
return m_MainApplicationForm.Invoke(func);
}
else
{
return null;
}
}
public static void SetForm(Form f)
{
m_MainApplicationForm = f;
}
}
}<file_sep>/YZX.TIA/Extensions/ILifelistServiceExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainModel;
namespace YZX.Tia.Extensions
{
public static class ILifelistServiceExtensions
{
public static ICoreObject GetLocalInterfaceCardByBoardConfiguration(this ILifelistService lifelist,
IOamConfiguration physicalConfiguration)
{
ICoreObjectCollection localInterfaceCards = lifelist.GetLocalInterfaceCards(true);
ICoreObject coreBoard = LifelistNavigator.FindCoreBoard(localInterfaceCards, physicalConfiguration.Board);
return coreBoard;
}
public static IConnectionService GetIConnectionService(this ILifelistService lifelist)
{
LifelistServiceProvider lsp = lifelist as LifelistServiceProvider;
if (lsp != null)
{
return lsp.ConnectionService;
}
else
{
return null;
}
}
public static ConnectionServiceProvider GetOnlineServiceProvider(this ILifelistService lifelist)
{
IConnectionService connectionService = lifelist.GetIConnectionService();
ConnectionServiceProvider csp = connectionService.ToConnectionServiceProvider();
return csp;
}
public static ICoreObject GetInterfaceCardByName(this ILifelistService lifelist,
string InterfaceCardName,
bool forceScan=true)
{
ICoreObjectCollection interfaces = lifelist.GetLocalInterfaceCards(forceScan);
foreach(ICoreObject card in interfaces){
string name = card.GetObjectName();
if (name == InterfaceCardName)
{
return card;
}
}
return null;
}
public static ICoreObject GetBoardConfigurationByName(this ILifelistService lifelist,
string ConfigurationName,
bool forceScan = true)
{
ICoreObjectCollection boards = lifelist.GetLocalInterfaceCards(forceScan);
foreach (ICoreObject localBoard in boards)
{
ICoreObjectCollection configurations = lifelist.GetAllBoardConfigurations(localBoard);
foreach (ICoreObject config in configurations)
{
IOamIdentification attributes = CoreObjectExtension.GetAttributes<IOamIdentification>(config);
if (attributes != null && attributes.OamName == ConfigurationName)
{
return config;
}
}
}
return null;
}
public static ICoreObject GetBoardConfigurationByName(this ILifelistService lifelist,
ICoreObject localBoard,
string ConfigurationName)
{
ICoreObjectCollection configurations = lifelist.GetAllBoardConfigurations(localBoard);
foreach(ICoreObject config in configurations)
{
IOamIdentification attributes = CoreObjectExtension.GetAttributes<IOamIdentification>(config);
if (attributes != null && attributes.OamName == ConfigurationName)
{
return config;
}
}
return null;
}
}
}
<file_sep>/YZX.TIA/Extensions/FLGViewExtensions.cs
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.Accessibility;
using YZX.Tia.Proxies.Ladder;
namespace YZX.Tia.Extensions
{
public static class FLGViewExtensions
{
public static GraphicManager GetGraphicManager(this FLGView flgView)
{
return flgView.GraphicManager;
}
public static FLGViewAccessibleObjectProxy GetCorrectAccessibilityObject(this FLGView flgView)
{
IFLGAccessibleObject IFLGAccessibleObject = flgView.GetCorrectAccessibilityObject();
return new FLGViewAccessibleObjectProxy(IFLGAccessibleObject);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/GlobalLibraryNavigationViewProxy.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
namespace YZX.Tia.Proxies.FrameApplication
{
public class GlobalLibraryNavigationViewProxy
{
internal GlobalLibraryNavigationView GlobalLibraryNavigationView;
public GlobalLibraryNavigationViewProxy(IDlc dlc)
{
GlobalLibraryNavigationView = dlc as GlobalLibraryNavigationView;
}
}
}<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Extensions/OnlineInterface/OMSPlusConnectionServiceExtensions.cs
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.SystemDiagnosis.Comm.OMSPlusService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions
{
public static class OMSPlusConnectionServiceExtensions
{
public static void SetConnection(this OMSPlusConnectionService service,
IOMSConnection connection)
{
Reflector.SetInstanceFieldByName(service,
"m_Connection", connection, ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Automation.FileIO.Test/Proxies/FileIO/MetaPackageImplementationProxy.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Archiving;
using Siemens.Automation.FileIO.Private;
using Siemens.Automation.FileIO.Private.MetaPackage;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FileIO
{
public class MetaPackageImplementationProxy
{
IMetaPackageAccess IMetaPackageAccess;
MetaPackageImplementation MetaPackageImplementation;
internal MetaPackageImplementationProxy(IMetaPackageAccess metaPackageAccess)
{
IMetaPackageAccess = metaPackageAccess;
MetaPackageImplementation = metaPackageAccess as MetaPackageImplementation;
}
public void Add(string fileName, Stream stream)
{
IMetaPackageAccess.Add(fileName, stream);
}
public IDirectory Package
{
get
{
var package = Reflector.GetInstanceFieldByName(
IMetaPackageAccess,
"m_Package",
ReflectionWays.SystemReflection)
as IDirectory;
return package;
}
}
}
}
<file_sep>/ShowModuleState/ShowModuleStateForm.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
using Console = Colorful.Console;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
using YZX.Tia;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.Dlc;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Extensions.FrameApplication;
using YZX.Tia.Extensions.ProjectManager;
using YZX.Tia.Proxies.ProjectManager;
using YZX.Tia.Extensions.Diagnostic;
using YZX.Tia.Dlc;
using OpenTelemetry;
using OpenTelemetry.Trace;
namespace ShowModuleState
{
public partial class ShowModuleStateForm : Form
{
public ShowModuleStateForm()
{
address = "Sps7;Rack=0;Slot=2;RSA=TCP_192.168.8.111_SM_255.255.255.0_SubnetId_4C-AA-00-00-00-01;ResourceId=1;";
//address = "Sps7;Rack=0;Slot=2;RSA=TCP_192.168.1.111_SM_255.255.255.0_SubnetId_8F-21-00-00-00-02;ResourceId=1;";
address = "OMS;TSelector=SIMATIC-ROOT-ES;RSA=TCP_192.168.1.34_SM_255.255.255.0_SubnetId_11-5F-00-00-00-01;ResourceId=6;";
path = @"E:\gitt\VPLC\1500VPLCTIA\1500VPLCTIA.ap14";
boardName = "PLCSIM";
TiaStarter.SetForm(this);
InitializeComponent();
Load += Form1_Load;
SizeChanged += Form1_SizeChanged;
//AfterSychronizer();
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
}
TiaProjectProxy projectProxy;
PrimaryProjectManagerProxy PrimaryProjectManagerProxy;
PrimaryProjectUiWorkingContextManagerProxy PrimaryProjectUiWorkingContextManagerProxy;
public void OpenProject()
{
Console.WriteLine("OpenProject");
PrimaryProjectUiWorkingContextManagerProxy = TiaStarter.m_ViewApplicationContext.GetPrimaryProjectUiWorkingContextManagerProxy();
PrimaryProjectManagerProxy =
PrimaryProjectUiWorkingContextManagerProxy.PrimaryProjectManager;
PrimaryProjectManagerProxy.ProjectOpened += PrimaryProjectManagerProxy_ProjectOpened;
var proxy = TiaStarter.m_BusinessLogicApplicationContext.GetTiaProjectManagerProxy();
object project = null;
//proxy.OpenProjectReadWrite(path, out project);
try
{
PrimaryProjectManagerProxy.OpenProjectReadWrite(path, out project);
}catch(Exception ex)
{
Console.WriteLine(ex);
}
}
private void PrimaryProjectManagerProxy_ProjectOpened(object sender, EventArgs e)
{
projectProxy = PrimaryProjectManagerProxy.PrimaryProject;
var project_WorkingContext_Proxy = new WorkingContextProxy(projectProxy.WorkingContext);
var project_WorkingContext_PlatformServiceContainer = project_WorkingContext_Proxy.PlatformServiceContainer;
if (project_WorkingContext_PlatformServiceContainer != null)
{
project_WorkingContext_PlatformServiceContainer.ConstructServiceEvent += Project_WorkingContext_PlatformServiceContainer_ConstructServiceEvent;
project_WorkingContext_PlatformServiceContainer.ServiceLoadedEvent += Project_WorkingContext_PlatformServiceContainer_ServiceLoadedEvent;
project_WorkingContext_PlatformServiceContainer.ServiceAddedEvent += Project_WorkingContext_PlatformServiceContainer_ServiceAddedEvent;
project_WorkingContext_PlatformServiceContainer.ServiceRemovedEvent += Project_WorkingContext_PlatformServiceContainer_ServiceRemovedEvent;
}
projectProxy.WorkingContext.AutoLoadDlcs();
ShowModuleState();
}
private void Project_WorkingContext_PlatformServiceContainer_ServiceRemovedEvent(
object sender,
ServiceChangedEventArgs e)
{
Console.WriteLine(string.Format("ServiceRemoved {0}",e.ServiceType.Name));
}
private void Project_WorkingContext_PlatformServiceContainer_ServiceAddedEvent(
object sender,
ServiceChangedEventArgs e)
{
Console.WriteLine(string.Format("ServiceAdded {0}",e.ServiceType.Name));
}
private void Project_WorkingContext_PlatformServiceContainer_ServiceLoadedEvent(
object sender,
ServiceChangedEventArgs e)
{
Console.WriteLine(string.Format("ServiceLoaded {0}",e.ServiceType.Name));
}
private void Project_WorkingContext_PlatformServiceContainer_ConstructServiceEvent(
object sender,
ConstructServiceEventArgs e)
{
Console.WriteLine(string.Format("ConstructService {0}",e.ServiceCreatorType.Name));
}
Control ModuleState;
public void ShowModuleState()
{
if (projectProxy != null)
{
cpu = projectProxy.FindCPU("VPLC1");
ModuleState = cpu.ShowModuleState();
Controls.Add(ModuleState);
var metainfos1 = TiaStarter.m_ViewApplicationContext.GetGlobalSingletonCache_MetaInfo();
var metainfos2 = TiaStarter.m_ViewApplicationContext.GetSingletonCache_MetaInfo();
var metainfos3 = TiaStarter.m_ViewApplicationContext.GetNonSingletonCache_MetaInfo();
var metainfos4 = TiaStarter.m_BusinessLogicApplicationContext.GetGlobalSingletonCache_MetaInfo();
var metainfos5 = TiaStarter.m_BusinessLogicApplicationContext.GetSingletonCache_MetaInfo();
var metainfos6 = TiaStarter.m_BusinessLogicApplicationContext.GetNonSingletonCache_MetaInfo();
Console.WriteLine("O");
}
}
string address;
string path;
string boardName = "Intel(R) Dual Band Wireless-AC 7265";
int boardNumber = 1;
int configIndex = 1;
public void BeforeStartSynchronizer()
{
OpenProject();
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Form1_Load");
TestTraceManager();
BeforeStartSynchronizer();
Resize += Form1_Resize;
}
private static readonly ActivitySource MyActivitySource = new ActivitySource(
"MyCompany.MyProduct.MyLibrary");
OpenTelemetry.Trace.TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetSampler(new AlwaysOnSampler())
.AddSource("MyCompany.MyProduct.MyLibrary")
.AddConsoleExporter()
.Build();
public void TestTraceManager()
{
var trace = TraceManagerExtensions.GetTrace("Siemens.Automation.TraceIntegrationDotNet",
"Siemens.Automation.CommonTrace.TraceIntegrationDotNet.TraceManager");
trace.DebugMessageSent += Trace_DebugMessageSent;
trace.InformationMessageSent += Trace_InformationMessageSent;
trace.WarningMessageSent += Trace_WarningMessageSent;
trace.ErrorMessageSent += Trace_ErrorMessageSent;
}
private void Trace_ErrorMessageSent(object sender, TraceEventArgs e)
{
try
{
Console.WriteLine(string.Format("{0} Error", e.ClassName), Color.Red);
//Console.WriteLine(e, Color.Red);
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity.SetTag("e", e);
}
}
catch(Exception ex)
{
}
}
private void Trace_WarningMessageSent(object sender, TraceEventArgs e)
{
try
{
Console.WriteLine(string.Format("{0} Warning", e.ClassName), Color.Yellow);
//Console.WriteLine(e, Color.Yellow);
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity.SetTag("e", e);
}
}
catch(Exception ex)
{
}
}
private void Trace_InformationMessageSent(object sender, TraceEventArgs e)
{
try
{
Console.WriteLine(string.Format("{0} Information", e.ClassName), Color.Green);
//Console.WriteLine(e, Color.Green);
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity.SetTag("e", e);
}
if (e.MethodName == "#### DlcManager #####: DlcCreated")
{
Console.WriteLine(e, Color.Gold);
}
}catch(Exception ex) { }
}
private void Trace_DebugMessageSent(object sender, TraceEventArgs e)
{
try
{
Console.WriteLine(string.Format("{0} Debug",e.ClassName));
//Console.WriteLine(e);
using (var activity = MyActivitySource.StartActivity("SayHello"))
{
activity.SetTag("e", e);
}
}
catch(Exception ex)
{
}
}
private void Form1_Resize(object sender, EventArgs e)
{
}
static ICoreObject cpu;
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/LoadCommandsProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.LoadService.Download;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class LoadCommandsProxy
{
LoadCommands LoadCommands;
public ILoad Load
{
get
{
return LoadCommands as ILoad;
}
}
public IDlc Dlc
{
get
{
return LoadCommands as IDlc;
}
}
public ICompileLoadAttributes CompileLoadAttributes
{
get
{
return LoadCommands as ICompileLoadAttributes;
}
}
public LoadCommandsProxy(ILoadCommandExtension loadCommand)
{
LoadCommands = loadCommand as LoadCommands;
}
public IOnlineService OnlineService
{
get
{
return Reflector.GetInstancePropertyByName(LoadCommands, "OnlineService",
ReflectionWays.SystemReflection) as IOnlineService;
}
}
public DownloadServiceProxy DownloadServiceProxy
{
get
{
DownloadService downloadService = Reflector.GetInstancePropertyByName(LoadCommands,
"DownloadSerice", ReflectionWays.SystemReflection) as DownloadService;
return new DownloadServiceProxy(downloadService);
}
}
public DownloadCommandServiceProxy DownloadCommandServiceProxy
{
get
{
DownloadCommandService downloadCommandService = Reflector.GetInstancePropertyByName(LoadCommands,
"DownloadCommandService", ReflectionWays.SystemReflection) as DownloadCommandService;
return new DownloadCommandServiceProxy(downloadCommandService);
}
}
public MainUploadServiceProxy MainUploadServiceProxy
{
get
{
MainUploadService mainUploadService = Reflector.GetInstancePropertyByName(LoadCommands,
"MainUploadService", ReflectionWays.SystemReflection) as MainUploadService;
return new MainUploadServiceProxy(mainUploadService);
}
}
public UploadServiceProxy UploadServiceProxy
{
get
{
UploadService uploadervice = Reflector.GetInstancePropertyByName(LoadCommands,
"UploadService", ReflectionWays.SystemReflection) as UploadService;
return new UploadServiceProxy(uploadervice);
}
}
public UploadCommandServiceProxy UploadCommandServiceProxy
{
get
{
UploadCommandService uploadCommandService = Reflector.GetInstancePropertyByName(LoadCommands,
"UploadCommandService", ReflectionWays.SystemReflection) as UploadCommandService;
return new UploadCommandServiceProxy(uploadCommandService);
}
}
public LoadState LoadState
{
get
{
return Load.LoadState;
}
}
public IWorkingContext WorkingContext
{
get
{
return Dlc.WorkingContext;
}
}
public event DownloadEventHandler DownloadStarted
{
add
{
LoadCommands.DownloadStarted += value;
}
remove
{
LoadCommands.DownloadStarted -= value;
}
}
public event DownloadEventHandler DownloadFinished
{
add
{
LoadCommands.DownloadFinished += value;
}
remove
{
LoadCommands.DownloadFinished -= value;
}
}
public MemoryStream GetBinaryDataStream(ICoreObject backupFile)
{
return Reflector.RunInstanceMethodByName(LoadCommands, "GetBinaryDataStream",
ReflectionWays.SystemReflection,
backupFile)
as MemoryStream;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/CommonProjectHandlingProxy.cs
using Siemens.Automation.Basics;
using System;
using System.Collections.Generic;
using Siemens.Automation.FrameApplication.ProjectWizard;
namespace YZX.Tia.Proxies.FrameApplication
{
public class CommonProjectHandlingProxy
{
public static List<IStarterFileInfo> LastRecentProjects(IWorkingContext workingContext,
out int maxRecentlyUsedProjectsToShow)
{
return CommonProjectHandling.LastRecentProjects(workingContext, out maxRecentlyUsedProjectsToShow);
}
public static List<IStarterFileInfo> LastRecentProjects(IWorkingContext workingContext)
{
return CommonProjectHandling.LastRecentProjects(workingContext);
}
public static void DeleteProjectFromRecentList(IWorkingContext workingContext, string project)
{
CommonProjectHandling.DeleteProjectFromRecentList(workingContext, project);
}
public static string OpenProjectDialog(string path,
out bool openReadonly,
IWorkingContext workingContext,
bool showReadOnlyBox=true,
bool defaultReadOnlyBoxState=true)
{
var handling = new CommonProjectHandling();
return handling.OpenProjectDialog(path, showReadOnlyBox, defaultReadOnlyBoxState,
out openReadonly, workingContext);
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/ViewMetaReaderProxy.cs
using System.Collections.Generic;
using Siemens.Automation.FrameApplication.ViewManager;
using Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ViewMetaReaderProxy
{
private static ViewMetaReaderProxy s_This;
public static ViewMetaReaderProxy Singleton
{
get
{
if(s_This == null)
{
s_This = new ViewMetaReaderProxy(ViewMetaReader.Singleton);
}
return s_This;
}
}
ViewMetaReader ViewMetaReader;
internal ViewMetaReaderProxy(ViewMetaReader reader)
{
ViewMetaReader = reader;
}
public ViewServiceDataProxy this[string viewID]
{
get
{
ViewServiceData vd = ViewMetaReader[viewID];
ViewServiceDataProxy proxy = new ViewServiceDataProxy(vd);
return proxy;
}
}
public Dictionary<string, ViewServiceDataProxy> ViewDictionary
{
get
{
Dictionary<string, ViewServiceData> vd = Reflector.GetInstanceFieldByName(ViewMetaReader,
"m_ViewDictionary",
ReflectionWays.SystemReflection) as Dictionary<string, ViewServiceData>;
Dictionary<string, ViewServiceDataProxy> vdp = new Dictionary<string, ViewServiceDataProxy>();
foreach(string key in vd.Keys)
{
ViewServiceData data = vd[key];
ViewServiceDataProxy proxy = new ViewServiceDataProxy(data);
vdp[key] = proxy;
}
return vdp;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/OpenProjectViewDlcProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Portal.Views;
namespace YZX.Tia.Proxies.FrameApplication
{
public class OpenProjectViewDlcProxy
{
internal OpenProjectViewDlc OpenProjectViewDlc;
public IView IView
{
get
{
return OpenProjectViewDlc as IView;
}
}
internal OpenProjectViewDlcProxy(OpenProjectViewDlc dlc)
{
OpenProjectViewDlc = dlc;
}
public IViewFrame ViewFrame
{
get
{
return IView.ViewFrame;
}
}
public event EventHandler<PortalViewNotificationEventArgs> Notify
{
add
{
OpenProjectViewDlc.Notify += value;
}
remove
{
OpenProjectViewDlc.Notify -= value;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/StepProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.Model.GraphElements;
namespace YZX.Tia.Proxies.Graph
{
public class StepProxy:LogicalElementProxy
{
Step Step;
internal StepProxy(Step step):base(step)
{
Step = step;
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/ConnectorBaseProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Reflection;
namespace YZX.Tia.Proxies.OnlineService
{
public class ConnectorBaseProxy
{
ConnectorBase ConnectorBase;
public ConnectorBaseProxy(object connectorBase)
{
ConnectorBase = connectorBase as ConnectorBase;
}
public virtual IConnection CreateDirectOamConnection(INode node, bool shareConnection)
{
return Reflector.RunInstanceMethodByName(ConnectorBase,
"CreateDirectOamConnection", ReflectionWays.SystemReflection,
node,
shareConnection) as IConnection;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/ViewLoaderExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
namespace YZX.Tia.Extensions.FrameApplication
{
public static class ViewLoaderExtensions
{
public static IView LoadViewFromDLCManager(this IWorkingContext workingContext,string viewID)
{
return ViewLoader.LoadViewFromDLCManager(viewID, workingContext);
}
public static IViewDomainLogic LoadViewDomainLogicFromDLCManager(this IWorkingContext workingContext, string domainLogicID)
{
return ViewLoader.LoadViewDomainLogicFromDLCManager(domainLogicID, workingContext);
}
}
}
<file_sep>/Siemens.Automation.CommonServices.ProjectManager.Test/Proxies/ProjectManager/TiaProjectProxy.Debug.cs
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
namespace YZX.Tia.Proxies.ProjectManager
{
public partial class TiaProjectProxy
{
private DebugService m_DebugService = null;
public DebugService DebugService
{
get
{
if (m_DebugService == null)
{
m_DebugService = new DebugService();
IDlc dlc_DebugService = m_DebugService;
dlc_DebugService.PreDetach();
dlc_DebugService.Attach(ProjectWorkingContext);
dlc_DebugService.PostAttach();
}
return m_DebugService;
}
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamPlcSimCtlProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OnlineAccess.S7SDDnet;
using Siemens.Automation.OnlineAccess.S7DosWrapper;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public class OamPlcSimCtlProxy
{
OamPlcSimCtl SimCtl;
public OamPlcSimCtlProxy(IOamPlcSimCtl simCtl)
{
SimCtl = simCtl as OamPlcSimCtl;
}
public S7Simulation S7Simulation
{
get
{
return Reflector.GetInstanceFieldByName(SimCtl,
"m_PlcsimCtl",
ReflectionWays.SystemReflection)
as S7Simulation;
}
}
public S7DWSimulation S7DWSimulation
{
get
{
return Reflector.GetInstanceFieldByName(S7Simulation,
"m_S7DWSimulation",
ReflectionWays.SystemReflection)
as S7DWSimulation;
}
}
public int RequestId
{
get
{
return (int)Reflector.GetInstanceFieldByName(SimCtl,
"m_RequestId",
ReflectionWays.SystemReflection);
}
}
public static int GetNextReferenceCount()
{
return (int)Reflector.RunStaticMethodByName(typeof(OamPlcSimCtl),
"GetNextReferenceCount",
ReflectionWays.SystemReflection);
}
public int ReferenceCount
{
get
{
return (int)Reflector.GetInstanceFieldByName(SimCtl,
"s_referenceCount",
ReflectionWays.SystemReflection);
}
}
public bool PlcRedirection
{
get
{
return SimCtl.PlcRedirection;
}
}
public event OamChangeDelegate<object, IOamClientInfoEventArgs> PlcRedirectionChanged
{
add {
SimCtl.PlcRedirectionChanged += value;
}
remove {
SimCtl.PlcRedirectionChanged -= value;
}
}
public int StartSimulationRedirection()
{
return SimCtl.StartSimulationRedirection();
}
public int StopSimulationRedirection()
{
return SimCtl.StopSimulationRedirection();
}
public void Dispose()
{
SimCtl.Dispose();
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameApplicationExtensions.ProjectManagment.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Portal.Views;
using Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.FrameApplication
{
partial class FrameApplicationExtensions
{
public static OpenProjectViewDlcProxy GetOpenProjectViewDlc(this IWorkingContext workingContext)
{
var dlc = workingContext.GetRequiredDlc<OpenProjectViewDlc>("Siemens.Automation.FrameApplication.Portal.Views.OpenProjectViewDlc");
return new OpenProjectViewDlcProxy(dlc);
}
public static PrimaryProjectUiWorkingContextManagerProxy GetPrimaryProjectUiWorkingContextManagerProxy(this IWorkingContext workingContext)
{
var dlc = workingContext.GetPrimaryProjectUiWorkingContextManagerDlc()
as PrimaryProjectUiWorkingContextManagerDlc;
var manager = Reflector.GetInstancePropertyByName(dlc, "Forwardee", ReflectionWays.SystemReflection)
as PrimaryProjectUiWorkingContextManager;
if (PrimaryProjectUiWorkingContextManagerProxy.Instance == null)
{
var proxy = new PrimaryProjectUiWorkingContextManagerProxy(manager);
return proxy;
}
else
{
return PrimaryProjectUiWorkingContextManagerProxy.Instance;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.CoreContext.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static ICoreContextHandler GetCoreContextHandler([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ICoreContextHandler>("Siemens.Automation.CommonServices.CoreContextHandler");
}
public static ICoreContext GetCoreContext([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetCoreContextHandler().CoreContext;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Proxies/WorkingContextProxy.cs
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public class WorkingContextProxy
{
WorkingContext WC;
public WorkingContextProxy(IWorkingContext wc)
{
WC = wc as WorkingContext;
}
public List<WorkingContext> ChildWorkingContexts
{
get
{
return Reflector.GetInstanceFieldByName(WC,
"m_ChildWorkingContexts",
ReflectionWays.SystemReflection) as List<WorkingContext>;
}
}
public IWorkingContext SiblingInBusinessLogicForUnload
{
get
{
return Reflector.GetInstanceFieldByName(WC,
"m_SiblingInBusinessLogicForUnload",
ReflectionWays.SystemReflection) as IWorkingContext;
}
}
public IWorkingContext SiblingInViewContext
{
get
{
return Reflector.GetInstanceFieldByName(WC,
"m_SiblingInViewContext",
ReflectionWays.SystemReflection) as IWorkingContext;
}
}
public PlatformServiceContainer PlatformServiceContainer
{
get
{
return Reflector.GetInstanceFieldByName(WC,
"m_PlatformServiceContainer",
ReflectionWays.SystemReflection) as PlatformServiceContainer;
}
}
public static ITrace GetTrace()
{
return Reflector.GetStaticFieldByName(typeof(WorkingContext),"s_MyTrace") as ITrace;
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BackupPlusCheckBeforeUploadProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies
{
public class BackupPlusCheckBeforeUploadProxy
{
BackupPlusCheckBeforeUpload BackupPlusCheckBeforeUpload;
public BackupPlusCheckBeforeUploadProxy(object upload)
{
BackupPlusCheckBeforeUpload = upload as BackupPlusCheckBeforeUpload;
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/ProjectNavigatorLoaderProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ProjectNavigatorLoaderProxy
{
internal ProjectNavigatorLoader ProjectNavigatorLoader;
internal ProjectNavigatorLoaderProxy(ProjectNavigatorLoader loader)
{
ProjectNavigatorLoader = loader;
}
public IFrameGroup PnvPlaceHolderGroup
{
get
{
FrameGroup m_PnvPlaceHolderGroup = Reflector.GetInstanceFieldByName(ProjectNavigatorLoader,
"m_PnvPlaceHolderGroup",
ReflectionWays.SystemReflection) as FrameGroup;
return m_PnvPlaceHolderGroup;
}
}
public IViewFrame ProjectNavigatorViewFrame
{
get
{
IViewFrame m_ProjectNavigatorViewFrame = Reflector.GetInstanceFieldByName(ProjectNavigatorLoader,
"m_ProjectNavigatorViewFrame",
ReflectionWays.SystemReflection) as IViewFrame;
return m_ProjectNavigatorViewFrame;
}
}
public ProjectNavigationViewProxy NavigationView
{
get
{
ProjectNavigationView NavigationView = Reflector.GetInstancePropertyByName(ProjectNavigatorLoader,
"NavigationView",
ReflectionWays.SystemReflection) as ProjectNavigationView;
ProjectNavigationViewProxy proxy = new ProjectNavigationViewProxy(NavigationView);
return proxy;
}
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameApplicationExtensions.Library.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.FrameApplication
{
partial class FrameApplicationExtensions
{
public static GlobalLibraryNavigationViewProxy GetGlobalLibraryNavigationView(this IWorkingContext workingContext)
{
GlobalLibraryNavigationView dlc = workingContext.GetRequiredDlc<GlobalLibraryNavigationView>("Siemens.Automation.FrameApplication.Portal.Views.OpenProjectViewDlc");
return new GlobalLibraryNavigationViewProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamConnectionProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamConnectionProxy
{
OamConnection OamConnection;
public OamConnectionProxy(OamConnectionBase connection)
{
OamConnection = connection as OamConnection;
}
public int LastResult
{
get
{
return OamConnection.LastResult;
}
set
{
OamConnection.LastResult = value;
}
}
public OamConnectionType ConnType
{
get
{
return OamConnection.ConnType;
}
set
{
OamConnection.ConnType = value;
}
}
OamConnectionStatemachine StateMachine
{
get
{
return OamConnection.StateMachine;
}
}
OamSharedConnectionServer ShareServer
{
get
{
return OamConnection.ShareServer;
}
}
public int NoUserCallbackCounter
{
get
{
return OamConnection.NoUserCallbackCounter;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObjectExtensions.LogicView.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.PLInterface;
using YZX.Tia.Proxies;
using Reflection;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static BlockEditorControlBase GetPLView(this ICoreObject block,
BlockEditorLogicBase logic,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
PLBlockEditorControlElement pl = new PLBlockEditorControlElement();
if (ViewWorkingContext == null)
{
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
}
else
{
pl.Attach(ViewWorkingContext);
}
EditorPayload ep = new EditorPayload(block, ViewWorkingContext, serviceContainer);
pl.SetPayload(ep);
pl.SetDomainLogic(logic);
logic.SetView(pl);
logic.InitializationFinished();
return pl;
}) as BlockEditorControlBase;
}
public static BlockEditorControlBase GetGraphView(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
GraphBlockEditorControl pl = new GraphBlockEditorControl();
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
BlockEditorLogicBase logic = block.GetGraphBlockEditorLogic();
pl.SetDomainLogic(logic);
pl.SetPayload(block);
pl.InitializationFinished();
pl.CreateVisuals();
return pl;
}) as BlockEditorControlBase;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/OnlineFunctionServerProxy.cs
using System.Collections;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.DataSetServices.Server;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Server;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public class OnlineFunctionServerProxy
{
public OnlineFunctionServer OnlineFunctionServer;
public OnlineFunctionServerProxy(OnlineFunctionServer ofs)
{
OnlineFunctionServer = ofs;
}
public IOnlineObjectService DiagOnlObjService
{
get
{
return Reflector.GetInstancePropertyByName(OnlineFunctionServer,
"DiagOnlObjService",
ReflectionWays.SystemReflection) as IOnlineObjectService;
}
}
public IDataSetService DataSetService
{
get
{
return OnlineFunctionServer as IDataSetService;
}
}
public IOfctHighLevelDataSetAccess HighLevelDataSetAccess
{
get
{
return DataSetService.HighLevelDataSetAccess;
}
}
public IOfctClientLevelDataSetAccess ClientLevelDataSetAccess
{
get
{
return DataSetService.ClientLevelDataSetAccess;
}
}
public IEnumerable GetFunctionProviderAcfs(ICoreObject onlineTarget)
{
return Reflector.RunInstanceMethodByName(OnlineFunctionServer,
"GetFunctionProviderAcfs",
ReflectionWays.SystemReflection,
onlineTarget) as IEnumerable;
}
}
}
<file_sep>/YZX.TIA/Proxies/OamNodeBaseProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamNodeBaseProxy
{
OamNodeBase OamNodeBase;
public OamNodeBaseProxy(INode node)
{
OamNodeBase = node as OamNodeBase;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/ConnectionService/ConnectorBaseExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.ConnectionService;
namespace YZX.Tia.Extensions.OnlineService
{
class ConnectorBaseExtensions
{
internal ConnectorBase GetConnector(
ConnectionServiceProvider csp,
string connectionType)
{
return csp.GetConnector(connectionType);
}
}
}
<file_sep>/Siemens.Automation.CommonServices.ProjectManager.Test/Proxies/ProjectManager/TiaProjectProxy.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ProjectManager;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ProjectManager.Impl.Tia;
#if Tia
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
#endif
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Dlc;
using YZX.Tia.Proxies.BlockLogic;
namespace YZX.Tia.Proxies.ProjectManager
{
public partial class TiaProjectProxy
{
TiaProject tp;
ITiaProject TiaProject
{
get
{
return tp as ITiaProject;
}
}
ITiaProjectInternal TiaProjectInternal
{
get
{
return tp as ITiaProjectInternal;
}
}
public TiaProjectProxy(object o)
{
tp = o as TiaProject;
}
public IWorkingContext WorkingContext
{
get
{
return TiaProject.WorkingContext;
}
}
public IWorkingContext ProjectWorkingContext
{
get
{
ICoreContext projectContext = WorkingContext.GetCoreContext();
return ((IDlc)projectContext).WorkingContext;
}
}
public void UnlockStarterFile()
{
TiaProjectInternal.UnlockStarterFile();
}
public string DirectoryPath
{
get
{
return (string)Reflector.GetInstancePropertyByName(tp,
"DirectoryPath",
ReflectionWays.SystemReflection);
}
}
public string StarterFilePath
{
get
{
return (string)Reflector.GetInstancePropertyByName(tp,
"StarterFilePath",
ReflectionWays.SystemReflection);
}
}
public event EventHandler MainWorkingContextIsClosing
{
add
{
tp.MainWorkingContextIsClosing += value;
}
remove
{
tp.MainWorkingContextIsClosing -= value;
}
}
public event EventHandler IsModifiedChanged
{
add
{
tp.IsModifiedChanged += value;
}
remove
{
tp.IsModifiedChanged -= value;
}
}
#if Tia
public QueryBasedControllerTargetLookupProxy QueryBasedControllerTargetLookup
{
get
{
var coreContext = WorkingContext.GetCoreContext();
var QueryBasedControllerTargetLookupProxy =
new QueryBasedControllerTargetLookupProxy(coreContext);
return QueryBasedControllerTargetLookupProxy;
}
}
public ICoreObject FindCPU(string name)
{
return QueryBasedControllerTargetLookup.FindControllerTargetByName(name);
}
public ILibraryVersionService LibraryVersionService
{
get
{
return ProjectWorkingContext.DlcManager.Load("Siemens.Simatic.PlcLanguages.BlockLogic.LibraryVersionService") as ILibraryVersionService;
}
}
#endif
public void Close(bool Silent = true)
{
var cpp = new CloseProjectParams();
cpp.Silent = Silent;
TiaProject.Close(cpp);
}
public TiaProjectState State {
get
{
return TiaProject.State;
}
}
}
}
<file_sep>/LadderViewer/Program.cs
using System;
using System.Windows.Forms;
using YZX.Tia;
namespace VatViewer
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static int Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
app = new TiaStarter();
//Application.Run(new Form1());
app.StartUpPowerManagementThread();
app.Run(new Form1());
return 0;
}
public static TiaStarter app=null;
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BackupPlusUploadProxy.cs
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Reflection;
namespace YZX.Tia.Proxies
{
public class BackupPlusUploadProxy
{
BackupPlusUpload BackupPlusUpload;
public BackupPlusUploadProxy(object upload)
{
BackupPlusUpload = upload as BackupPlusUpload;
}
public ICoreContext CoreContext
{
get
{
return Reflector.GetInstanceFieldByName(BackupPlusUpload,
"m_CoreContext", ReflectionWays.SystemReflection) as ICoreContext;
}
}
public ILoadConnection LoadConnection
{
get
{
return Reflector.GetInstanceFieldByName(BackupPlusUpload,
"m_LoadConnection", ReflectionWays.SystemReflection) as ILoadConnection;
}
}
public ILoadData LoadData
{
get
{
return Reflector.GetInstanceFieldByName(BackupPlusUpload,
"m_LoadData", ReflectionWays.SystemReflection) as ILoadData;
}
}
}
}<file_sep>/YZX.TIA/Extensions/IOnlineServiceExtensions.cs
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class IOnlineServiceExtensions
{
public static OnlineServiceProvider ToOnlineServiceProvider(this IOnlineService ios)
{
OnlineServiceProxy osp = ios as OnlineServiceProxy;
IOnlineService rios = Reflector.GetInstanceFieldByName(ios, "m_RealOnlineService", ReflectionWays.SystemReflection) as IOnlineService;
OnlineServiceProvider real = rios as OnlineServiceProvider;
return real;
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/LifelistDetailsQueueProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.OnlineService;
namespace YZX.Tia.Proxies.OnlineService
{
public class LifelistDetailsQueueProxy
{
internal LifelistDetailsQueue LifelistDetailsQueue;
internal LifelistDetailsQueueProxy(LifelistDetailsQueue queue)
{
LifelistDetailsQueue = queue;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.ProjectManager.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using YZX.Tia.Proxies.ProjectManager;
using YZX.Tia.Extensions.ProjectManager;
namespace YZX.Tia
{
partial class TiaStarter
{
//static CmdHandlerHelper CHH;
public static ICoreContextHandler cch;
IProjectManager m_ProjectManager;
public IProjectManager ProjectManager
{
get
{
if (m_ProjectManager == null)
{
m_ProjectManager = m_ViewApplicationContext.GetProjectManager();
}
return m_ProjectManager;
}
set
{
m_ProjectManager = value;
}
}
private TiaProjectManagerLegacyHandlerProxy m_ProjectManagerProxy;
public TiaProjectManagerLegacyHandlerProxy ProjectManagerProxy
{
get
{
if(m_ProjectManagerProxy == null)
{
m_ProjectManagerProxy = new TiaProjectManagerLegacyHandlerProxy(ProjectManager);
}
return m_ProjectManagerProxy;
}
}
#region projectWorkingContext Event
private void ProjectWorkingContext_ServiceLoadedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("ProjectWorkingContext_ServiceLoadedEvent {0}", e.ServiceCreatorType, e.ServiceType);
}
private void ProjectWorkingContext_ServiceAddedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("ProjectWorkingContext_ServiceAddedEvent {0}", e.ServiceCreatorType, e.ServiceType);
}
private void ProjectWorkingContext_WorkingContextChildCreatedEvent(object sender, ChildCreatedEventArgs e)
{
Console.WriteLine("ProjectWorkingContext_WorkingContextChildCreatedEvent {0}", e.ChildContext);
}
#endregion
#region projectWorkingContext Event
private void ProjectViewWorkingContext_WorkingContextChildCreatedEvent(object sender, ChildCreatedEventArgs e)
{
Console.WriteLine("ProjectViewWorkingContext_WorkingContextChildCreatedEvent {0}", e.ChildContext);
}
private void ProjectViewWorkingContext_ServiceLoadedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("ProjectViewWorkingContext_ServiceLoadedEvent {0}", e.ServiceCreatorType, e.ServiceType);
}
private void ProjectViewWorkingContext_ServiceAddedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("ProjectViewWorkingContext_ServiceAddedEvent {0}", e.ServiceCreatorType, e.ServiceType);
}
#endregion
}
}
<file_sep>/YZX.TIA/Proxies/Graph/AbstractGraphViewProxy.cs
using System;
using Siemens.Automation.UI.Controls;
using Siemens.Simatic.PlcLanguages.GraphEditor;
using Siemens.Simatic.PlcLanguages.GraphEditor.View;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.Overlays;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class AbstractGraphViewProxy
{
internal AbstractGraphView currentView;
public AbstractGraphViewProxy(UserControl currentView)
{
this.currentView = currentView as AbstractGraphView;
}
internal OverlayManagerBase OverlayManager
{
get
{
return currentView.OverlayManager;
}
}
public GraphDrawSettingsProxy DrawSettingsProxy
{
get
{
var settings = Reflector.GetInstanceFieldByName(currentView, "m_DrawSettings",
ReflectionWays.SystemReflection) as GraphDrawSettings;
return new GraphDrawSettingsProxy(settings);
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameApplication-NavigationViews.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static ProjectNavigationViewProxy ProjectNavigationView([NotNull] this IWorkingContext workingContext)
{
ProjectNavigationView dlc = workingContext.GetRequiredDlc<ProjectNavigationView>("Siemens.Automation.FrameApplication.ProjectNavigatorView");
return new ProjectNavigationViewProxy(dlc);
}
}
}
<file_sep>/MpkExtractor/MpkExtractorForm.cs
using System;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;
using Siemens.Automation.FileIO;
using YZX.Tia.Proxies.Archiving;
using YZX.Tia.Proxies.FileIO;
namespace MpkExtractor
{
public partial class MpkExtractorForm : Form
{
public MpkExtractorForm()
{
InitializeComponent();
InitNlogViewer();
Load += Form1_Load;
}
#region NlogViewer
NlogViewer.NlogViewer nlogViewer;
NLog.Logger log;
private void InitNlogViewer()
{
nlogViewer = new NlogViewer.NlogViewer();
nlogViewer.MessageWidth = 400;
LogHost.Child = nlogViewer;
log = NLog.LogManager.GetLogger("YZX");
}
#endregion
private void Form1_Load(object sender, EventArgs e)
{
log.Info(string.Format("加载Dlc成功"));
log.Info(string.Format("程序加载成功"));
LoadExclusionList();
}
const string ExclusionListFile = "MpkExtractorExclusionList.json";
private void LoadExclusionList()
{
try
{
var s = File.ReadAllText(ExclusionListFile);
ExclusionList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(s);
log.Info(string.Format("排除列表加载成功"));
}
catch(Exception e)
{
log.Info(string.Format("排除列表加载失败"));
}
}
PackagingImplementationBaseProxy proxy;
IList<string> FileNames;
string FilePath;
string LastDirectory;
List<string> ExclusionList;
IFileService FileService =
FileServiceFacade.FileService;
#region 按钮
private void OpenProjectButton_Click(object sender, EventArgs e)
{
using (var openFileDialog = new OpenFileDialog())
{
if(LastDirectory == null)
{
LastDirectory = "c:\\";
}
openFileDialog.InitialDirectory = LastDirectory;
openFileDialog.Filter = "TIA 配置文件包(*.mpk)|*.mpk";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
FilePath = openFileDialog.FileName;
proxy = new PackagingImplementationBaseProxy(FilePath);
if(FileNames != null)
{
FileNames = null;
}
FileNames = proxy.GetFiles();
foreach(var file in FileNames)
{
log.Info(file);
}
log.Info(string.Format("{0}打开完成", FilePath));
LastDirectory = Path.GetDirectoryName(FilePath);
}
}
}
private void ExportButton_Click(object sender, EventArgs e)
{
var folderBrowserDialog1 = new FolderBrowserDialog();
folderBrowserDialog1.SelectedPath = LastDirectory;
folderBrowserDialog1.ShowNewFolderButton = true;
var result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
var SaveDirectory = folderBrowserDialog1.SelectedPath;
LastDirectory = Path.GetDirectoryName(SaveDirectory);
proxy.Unpack(SaveDirectory,ExclusionList);
log.Info(string.Format("{0}导出完成",FilePath));
}
}
private void CloseMpk()
{
if (proxy != null)
{
proxy.Dispose();
proxy = null;
if (FileNames != null)
{
FileNames = null;
}
log.Info(string.Format("{0}关闭完成", FilePath));
LastDirectory = Path.GetDirectoryName(FilePath);
}
}
private void CloseProjectButton_Click(object sender, EventArgs e)
{
CloseMpk();
}
private void ExitButton_Click(object sender, EventArgs e)
{
try
{
log.Info(string.Format("开始关闭程序"));
}catch(Exception ex)
{
}
finally
{
Close();
Application.Exit();
}
}
private void AddFileButton_Click(object sender, EventArgs e)
{
if(proxy == null)
{
log.Info(string.Format("未打开Mpk"));
return;
}
using (var openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "TIA 配置文件(*.xml)|*.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
FilePath = openFileDialog.FileName;
var FileName = Path.GetFileName(FilePath);
var package = FileService.CreatePackageForWrite(VirtualFileSystem.Installation, "YZX", "AL02.mpk");
//package => WriteableMpkDirectory
var packageProxy = new WriteableMpkDirectoryProxy(package);
var MetaPackageProxy = packageProxy.GetMetaPackageImplementationProxy();
MetaPackageProxy.Add(FileName, File.Open(FilePath, FileMode.Open));
var arch = MetaPackageProxy.Package;
var writer = arch as Siemens.Automation.Archiving.IWriteableDirectory;
var zipProxy = new ZipCreatorProxy(writer);
zipProxy.CloseCurrentFile();
log.Info(string.Format("添加{0}完成", FilePath));
}
}
}
private void SaveMpkButton_Click(object sender, EventArgs e)
{
if (proxy == null)
{
log.Info(string.Format("未打开Mpk"));
return;
}
using (var openFileDialog = new SaveFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "TIA 配置文件包(*.mpk)|*.mpk";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
FilePath = openFileDialog.FileName;
proxy.Save(FilePath);
FileNames = proxy.GetFiles();
foreach (var file in FileNames)
{
log.Info(file);
}
log.Info(string.Format("{0}保存完成", FilePath));
}
}
}
#endregion
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.cs
using System;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Threading;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Bootstrapper;
using Siemens.Automation.FrameApplication.ShortcutManager;
using Siemens.Automation.Basics.SynchronizationContext;
using Siemens.Automation.CommonServices.ApplicationLifeCycle.PowerManagement;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
public partial class TiaStarter
{
private IWindowManagerInternal m_WindowManager;
private IApplicationFrame m_MainApplicationFrame;
private void StartFileStorageServer()
{
ICoreFrame m_CoreFrame = m_ViewApplicationContext.DlcManager.Load("Siemens.Automation.ObjectFrame.CoreFrame")
as ICoreFrame;
m_CoreFrame.TryStartServer();
}
public static Form m_MainApplicationForm;
public string AppId = "TiaTest";
public string username = "YZX";
private void CreateStartupPreloadedContext()
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
new Thread(new ParameterizedThreadStart(this.CreateStartupPreloadedContextThread)).Start(autoResetEvent);
autoResetEvent.WaitOne();
}
private void CreateStartupPreloadedContextThread(object autoResetEvent)
{
try
{
WorkingContext workingContext = new WorkingContext(false,
WorkingContextEnvironment.Application,
AppId,
username)
{
Scope = "DlcStartupPreload"
};
((EventWaitHandle)autoResetEvent).Set();
((IDlcAutoloader)workingContext.DlcManager).AutoloadByScope();
}
finally
{
((EventWaitHandle)autoResetEvent).Set();
}
}
public void StartUpHibernateThread()
{
using (AutoResetEvent autoResetEvent = new AutoResetEvent(false))
{
new Thread(new ParameterizedThreadStart(StartUpHibernateThread))
{
IsBackground = true,
Name = "PowerManagementThread",
Priority = ThreadPriority.Normal
}.Start(autoResetEvent);
autoResetEvent.WaitOne();
}
}
private static void StartUpHibernateThread(object o)
{
HibernateServiceFactory.CreateAndInit((AutoResetEvent)o);
}
public void StartUpPowerManagementThread()
{
using (AutoResetEvent autoResetEvent = new AutoResetEvent(false))
{
new Thread(new ParameterizedThreadStart(StartUpHibernateThread))
{
IsBackground = true,
Name = "PowerManagementThread",
Priority = ThreadPriority.Normal
}.Start(autoResetEvent);
autoResetEvent.WaitOne();
}
}
public static void ForceEarlyCreationOfBroadcastEventWindow()
{
SystemEvents.InvokeOnEventsThread((Action)(() => { }));
}
private bool StartShouldBeInterrupted()
{
return false;
}
public TiaStarter(bool showView=false)
{
this.CreateWorkingContextHierarchy();
if (showView)
{
//WindowManager.InitializationCompleted += WindowManager_InitializationCompleted;
}
this.CreateStartupPreloadedContext();
}
private void WindowManager_InitializationCompleted(object sender, EventArgs e)
{
//m_ViewApplicationContext.DlcManager.Load("Siemens.Automation.Portal.ComServer.Application", true);
this.m_WindowManager.InitializationCompleted -= new EventHandler(this.WindowManager_InitializationCompleted);
bool flag = false;
//if (this.InitializationCompletedCallback != null)
// flag = this.InitializationCompletedCallback();
if (flag)
{
m_MainApplicationForm.Close();
}
else
{
this.StartFileStorageServer();
string startupCompletedCallback = "";
if (string.IsNullOrEmpty(startupCompletedCallback))
startupCompletedCallback = "Siemens.Automation.FrameApplication.Bootstrapper.DefaultStartupCompletedCallbackDlc";
new StartupCompletedCallbackDlcCommandLineHandler(m_ViewApplicationContext, startupCompletedCallback).Start(null);
}
//m_MainApplicationForm.Hide();
}
public void CreateForm()
{
//this.WindowManager.InitializationCompleted += new EventHandler(this.WindowManager_InitializationCompleted);
//this.m_MainApplicationFrame = this.WindowManager.CreateMainApplication() as IApplicationFrame;
if (this.m_MainApplicationFrame == null)
throw new FrameApplicationException("Calling IWindowManager.CreateMainApplication was not successful: It has returned null.");
m_MainApplicationForm = (Form)this.m_MainApplicationFrame.FrameControl;
if (m_MainApplicationForm == null)
throw new FrameApplicationException("The FrameControl of the ApplicationFrame must be of type 'System.Windows.Forms.Form'.");
m_MainApplicationForm.FormClosed += new FormClosedEventHandler(this.MainApplicationForm_FormClosed);
}
public void Run(Form f = null)
{
Console.WriteLine("AppLoader.Run", "Bootstrapper enters IStarter.Run method.");
if (this.StartShouldBeInterrupted())
return;
ForceEarlyCreationOfBroadcastEventWindow();
Application.EnableVisualStyles();
//this.CreateStartupPreloadedContext();
IWorkingContextExtensions.GetRequiredDlc<IShortcutManager>(m_ViewApplicationContext, "Siemens.Automation.FrameApplication.ShortcutManager");
m_ViewApplicationContext.DlcManager.Load("Siemens.Automation.FrameApplication.Services.RegisterServices");
m_ViewApplicationContext.SiblingInBusinessLogicContext.AutoLoadDlcs();
m_ViewApplicationContext.AutoLoadDlcs();
if (f == null)
{
CreateForm();
}
else
{
m_MainApplicationForm = f;
}
SynchronizationContext current = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(new NonPumpingSynchronizationContext(current));
ISynchronizer sychronizer = Synchronizer;
if (sychronizer != null)
{
Console.WriteLine("AppLoader.Run", "Bootstrapper starts running ThreadSynchronizer.");
sychronizer.Run(m_MainApplicationForm);
Console.WriteLine("AppLoader.Run", "Bootstrapper finished running ThreadSynchronizer.");
}
else
{
Application.Run(m_MainApplicationForm);
}
}
finally
{
SynchronizationContext.SetSynchronizationContext(current);
}
}
private void MainApplicationForm_FormClosed(object sender, FormClosedEventArgs e)
{
m_MainApplicationForm.FormClosed -= new FormClosedEventHandler(this.MainApplicationForm_FormClosed);
this.Uninitialize();
}
public void Uninitialize()
{
lock (this)
{
if (m_ViewApplicationContext != null)
m_ViewApplicationContext.Close();
m_MainApplicationForm = null;
this.m_WindowManager = null;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Hwcn/DoeViewAccessProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
namespace YZX.Tia.Proxies.Hwcn
{
public class DoeViewAccessProxy
{
internal DoeViewAccess DoeViewAccess;
public DoeViewAccessProxy(IDoeViewAccess viewAccess)
{
DoeViewAccess = viewAccess as DoeViewAccess;
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Proxies/NetworkEditorFrame/LanguagePaletteElementProxy.cs
namespace YZX.Tia.Proxies.NetworkEditorFrame
{
public class LanguagePaletteElementProxy
{
}
}<file_sep>/YZX.TIA/Extensions/Tis/S7AnyExtensions.cs
using System.Collections.Generic;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.TisServer;
namespace YZX.Tia.Extensions
{
public static class S7AnyExtensions
{
public static byte[] CreateRequestBuffer(this List<S7Any> s7anyList, ITisServer TisServer)
{
ITisEndianBuffer endianBuffer1 = TisServer.CreateEndianBuffer(false);
foreach (S7Any anyPointer in s7anyList)
{
endianBuffer1.WriteUInt8(18);
endianBuffer1.WriteUInt8(10);
byte[] numArray = new byte[10]
{
anyPointer.syntax_id,
anyPointer.datatyp,
(byte)((uint) anyPointer.count >> 8),
(byte)anyPointer.count,
(byte)((uint) anyPointer.pointer_val.DbNumber >> 8),
(byte)anyPointer.pointer_val.DbNumber,
(byte)(anyPointer.pointer_val.Ptr >> 24),
(byte)(anyPointer.pointer_val.Ptr >> 16),
(byte)(anyPointer.pointer_val.Ptr >> 8),
(byte)anyPointer.pointer_val.Ptr
};
endianBuffer1.WriteByteArray(numArray);
}
return endianBuffer1.Buffer;
}
}
}
<file_sep>/YZX.TIA/Proxies/ITraceProxy.cs
using System.Collections.Generic;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
namespace YZX.Tia.Proxies
{
public class ITraceProxy
{
Tracer Tracer;
public ITraceObserver TraceObserver
{
get
{
return Tracer as ITraceObserver;
}
}
public ITraceProxy(ITrace trace)
{
Tracer = trace as Tracer;
}
public event TraceEventHandler ErrorMessageSent
{
add
{
if (TraceObserver != null)
{
TraceObserver.ErrorMessageSent += value;
}
}
remove
{
if (TraceObserver != null)
{
TraceObserver.ErrorMessageSent -= value;
}
}
}
public event TraceEventHandler WarningMessageSent
{
add
{
if (TraceObserver != null)
{
TraceObserver.WarningMessageSent += value;
}
}
remove
{
if (TraceObserver != null)
{
TraceObserver.WarningMessageSent -= value;
}
}
}
public event TraceEventHandler InformationMessageSent
{
add
{
if (TraceObserver != null)
{
TraceObserver.InformationMessageSent += value;
}
}
remove
{
if (TraceObserver != null)
{
TraceObserver.InformationMessageSent -= value;
}
}
}
public event TraceEventHandler DebugMessageSent
{
add
{
if (TraceObserver != null)
{
TraceObserver.DebugMessageSent += value;
}
}
remove
{
if (TraceObserver != null)
{
TraceObserver.DebugMessageSent -= value;
}
}
}
}
}
<file_sep>/YZX.TIA/Proxies/LifeListDialogProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
namespace YZX.Tia.Proxies
{
public class LifeListDialogProxy
{
internal LifeListDialog LifeListDialog;
internal LifeListDialogProxy(LifeListDialog dialog)
{
LifeListDialog = dialog;
}
public event EventHandler<EventArgs> AllCommonControlsShown
{
add
{
LifeListDialog.AllCommonControlsShown += value;
}
remove
{
LifeListDialog.AllCommonControlsShown -= value;
}
}
internal event EventHandler<OnlineCommonDialogButtonsEventArgs> DialogButtonEvent;
public void AllSubControlsVisible()
{
LifeListDialog.AllSubControlsVisible();
}
public void InitializeDialogbuttons()
{
LifeListDialog.InitializeDialogbuttons();
}
public void Close()
{
LifeListDialog.Close();
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.DiagOnlineObjectService.cs
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
namespace YZX.Tia
{
partial class TiaStarter
{
IOnlineObjectService m_DiagOnlineObjectService;
public IOnlineObjectService DiagOnlineObjectService
{
get
{
if (this.m_DiagOnlineObjectService == null)
{
this.m_DiagOnlineObjectService = projectWorkingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineObjectService") as IOnlineObjectService;
IOnlineObjectService onlineObjectService = this.m_DiagOnlineObjectService;
}
return this.m_DiagOnlineObjectService;
}
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/WindowManagerExtensions.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Dlc;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions.FrameApplication
{
public static class WindowManagerExtensions
{
public static IViewContent GetNavigationView(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.ProjectNavigatorView") as ProjectNavigationView;
}
internal static ISlideManager GetSlideManager(this IWorkingContext workingContext)
{
return (ISlideManager)workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.WindowManager.SlidingManager", true);
}
internal static SlidingManagerProxy GetSlideManagerProxy(this IWorkingContext workingContext)
{
SlidingManager sm = workingContext.GetSlideManager() as SlidingManager;
return new SlidingManagerProxy(sm);
}
internal static IWindowManagerInternal GetWindowManager(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<IWindowManagerInternal>("Siemens.Automation.FrameApplication.WindowManager");
}
internal static WindowManagerProxy GetWindowManagerProxy(this IWorkingContext workingContext)
{
return new WindowManagerProxy(workingContext.GetWindowManager());
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Extensions/BlockLogic/ICodeBlockExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Simatic.PlcLanguages.Online;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions
{
public static class ICodeBlockExtensions
{
public static IOfflineOnlineStatus GetOnlineStatusByExplicitExplore(this ICodeBlock codeBlock)
{
return Reflector.RunStaticMethodByName(typeof(OnlineManagerBase),
"GetOnlineStatusByExplicitExplore",
ReflectionWays.SystemReflection,
codeBlock) as IOfflineOnlineStatus;
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Proxies/BlockLogic/OmsPlusBlockUtilitiesProxy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus;
namespace Siemens.Simatic.Lang.BlockLogic.Test.Proxies.BlockLogic
{
public static class OmsPlusBlockUtilitiesProxy
{
public static T GetAttribute<T>(this Siemens.Automation.OMSPlus.Managed.Object currentObject,
GlobalAID id,
Value reusedValueStorage = null)
{
return OmsPlusBlockUtilities.GetAttribute<T>(currentObject, id, reusedValueStorage);
}
public static Siemens.Automation.OMSPlus.Managed.Error SetAttribute(
ref Siemens.Automation.OMSPlus.Managed.Object omsObject,
int iAID, object iValue)
{
return OmsPlusBlockUtilities.SetAttribute(ref omsObject, iAID, iValue);
}
public static uint GetBlockTypeObjectRID(BlockType blockType)
{
return OmsPlusBlockUtilities.GetBlockTypeObjectRID(blockType);
}
public static BlockType GetBlockTypeFromClassRid(uint classRid)
{
return OmsPlusBlockUtilities.GetBlockTypeFromClassRid(classRid);
}
public static BlockType GetClassRIDBlockType(uint classRID)
{
return OmsPlusBlockUtilities.GetClassRIDBlockType(classRID);
}
public static uint[] GetRelationIDs(uint classRID)
{
return OmsPlusBlockUtilities.GetRelationIDs(classRID);
}
public static Siemens.Automation.OMSPlus.Managed.Error GetAsSwEvent(
ClientSession clientSession,
Siemens.Automation.OMSPlus.Managed.Object asObject,
uint[] aids,
ref Siemens.Automation.OMSPlus.Managed.Object asSwEvent)
{
return OmsPlusBlockUtilities.GetAsSwEvent(clientSession, asObject, aids, ref asSwEvent);
}
public static Rid GetDBConfiguredTypeRid(Siemens.Automation.OMSPlus.Managed.Object block)
{
return OmsPlusBlockUtilities.GetDBConfiguredTypeRid(block);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.ProjectManager.cs
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ProjectManager.Impl.Tia;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static TiaProjectManagerLegacyHandlerProxy GetProjectManagerProxy(this IWorkingContext workingContext)
{
return new TiaProjectManagerLegacyHandlerProxy(GetProjectManager(workingContext));
}
public static IProjectManager GetProjectManager([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<IProjectManager>("Siemens.Automation.CommonServices.ProjectManager");
}
internal static TiaProjectManager GetTiaProjectManager(this IWorkingContext workingContext)
{
ITiaProjectActionerFactory requiredDlc = GetRequiredDlc<ITiaProjectActionerFactory>(workingContext,
"Siemens.Automation.ProjectManager.Impl.Tia.TiaProjectActionerFactory");
return new TiaProjectManager(workingContext, requiredDlc);
}
public static TiaProjectManagerProxy GetTiaProjectManagerProxy(this IWorkingContext workingContext)
{
TiaProjectManager tiaProjectManager = workingContext.GetTiaProjectManager();
TiaProjectManagerProxy tiaProjectManagerProxy = new TiaProjectManagerProxy(tiaProjectManager);
return tiaProjectManagerProxy;
}
}
}
<file_sep>/YZX.TIA/Extensions/Vat/VatDeviceExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.VATViewer;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.VatService.Businesslogic;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class VatDeviceExtensions
{
public static IDebugDevice GetDebugDevice(this IVatDevice vd)
{
return Reflector.GetInstanceFieldByName(vd, "m_DebugDevice",
ReflectionWays.SystemReflection)
as IDebugDevice;
}
public static void SetDebugDevice(this IVatDevice vd,IDebugDevice DebugDevice)
{
Reflector.SetInstanceFieldByName(vd, "m_DebugDevice",
DebugDevice,
ReflectionWays.SystemReflection);
}
/// <summary>
/// 加载 DebugDevice
/// </summary>
public static void LoadDebugDevice(this IVatDevice vd,bool force = false)
{
IDebugDevice m_DebugDevice = vd.GetDebugDevice();
if (!force)
{
if (vd.ControllerTarget == null || vd.GetDebugDevice() != null)
return;
}
m_DebugDevice = vd.Service.DebugService.GetDevice(vd.ControllerTarget);
vd.SetDebugDevice(m_DebugDevice);
//DeviceResultHandler m_ConnectionStateChangedCallback =
// Reflector.GetInstanceFieldByName(vd, "m_ConnectionStateChangedCallback")
// as DeviceResultHandler;
//m_DebugDevice.ConnectionStateChanged += m_ConnectionStateChangedCallback;
if (ConnectionState.Online != m_DebugDevice.ConnectionState)
return;
//Reflector.RunInstanceMethodByName(vd, "StartReadingStatusInformation");
//Reflector.RunInstanceMethodByName(vd, "StartMarkJob");
Reflector.RunInstanceMethodByName(vd, "FireClientNotificationConnectionStateChange", new DeviceResultArgs()
{
ConnectionState = ConnectionState.Online
});
}
}
}
<file_sep>/Siemens.Automation.CommonServices.ProjectManager.Test/Extensions/ProjectManager/ProjectManagerExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ProjectManager.Impl.Tia;
using YZX.Tia.Proxies.ProjectManager;
namespace YZX.Tia.Extensions.ProjectManager
{
public static class ProjectManagerExtensions
{
public static TiaProjectManagerLegacyHandlerProxy GetProjectManagerProxy(this IWorkingContext workingContext)
{
return new TiaProjectManagerLegacyHandlerProxy(GetProjectManager(workingContext));
}
public static IProjectManager GetProjectManager(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<IProjectManager>("Siemens.Automation.CommonServices.ProjectManager");
}
internal static TiaProjectManager GetTiaProjectManager(this IWorkingContext workingContext)
{
ITiaProjectActionerFactory requiredDlc = workingContext.GetRequiredDlc<ITiaProjectActionerFactory>(
"Siemens.Automation.ProjectManager.Impl.Tia.TiaProjectActionerFactory");
return new TiaProjectManager(workingContext, requiredDlc);
}
public static TiaProjectManagerProxy GetTiaProjectManagerProxy(this IWorkingContext workingContext)
{
TiaProjectManager tiaProjectManager = workingContext.GetTiaProjectManager();
TiaProjectManagerProxy tiaProjectManagerProxy = new TiaProjectManagerProxy(tiaProjectManager);
return tiaProjectManagerProxy;
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameApplication-Library.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static GlobalLibraryNavigationViewProxy GetGlobalLibraryNavigationView([NotNull] this IWorkingContext workingContext)
{
GlobalLibraryNavigationView dlc = workingContext.GetRequiredDlc<GlobalLibraryNavigationView>("Siemens.Automation.FrameApplication.Portal.Views.OpenProjectViewDlc");
return new GlobalLibraryNavigationViewProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BackupClassicCheckBeforeUploadProxy.cs
using Siemens.Automation.DomainServices.LoadService;
using Reflection;
namespace YZX.Tia
{
public class BackupClassicCheckBeforeUploadProxy
{
BackupClassicCheckBeforeUpload BackupClassicCheckBeforeUpload;
public BackupClassicCheckBeforeUploadProxy(object upload)
{
BackupClassicCheckBeforeUpload = upload as BackupClassicCheckBeforeUpload;
}
}
}<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectExtensions.Folder.cs
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.TagService;
using Siemens.Simatic.PlcLanguages.VatService.FolderSnapIn;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static partial class ICoreObjectExtensions
{
public static VatFolderSnapInFactory GetStandardFolderBLObjectFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
VatFolderSnapInFactory VatFolderSnapInFactory = idlcManager.Load("Siemens.Automation.DomainServices.FolderService.StandardFolderBLObjectFactory")
as VatFolderSnapInFactory;
return VatFolderSnapInFactory;
}
public static VatFolderSnapInFactory GetVatFolderSnapInFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
VatFolderSnapInFactory VatFolderSnapInFactory = idlcManager.Load("PlcLanguages.VatService.FolderSnapIn.VatFolderSnapInFactory")
as VatFolderSnapInFactory;
return VatFolderSnapInFactory;
}
public static ControllerTagsFolderBLObjectFactory GetControllerTagsFolderBLObjectFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
ControllerTagsFolderBLObjectFactory ControllerTagsFolderBLObjectFactory = idlcManager.Load("Siemens.Automation.DomainServices.TagService.ControllerTagsFolderBL")
as ControllerTagsFolderBLObjectFactory;
return ControllerTagsFolderBLObjectFactory;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableTextLabelProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableTextLabelProxy:DrawableBoxElementProxy
{
internal DrawableTextLabel DrawableTextLabel;
internal DrawableTextLabelProxy(DrawableTextLabel label):base(label)
{
DrawableTextLabel = label;
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/HierarchyFrameProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class HierarchyFrameProxy:FrameBaseProxy
{
HierarchyFrame HierarchyFrame;
IHierarchyFrame IHierarchyFrame
{
get
{
return HierarchyFrame as IHierarchyFrame;
}
}
public new static HierarchyFrameProxy ToProxy(IFrame frame)
{
if (frame is ApplicationFrame)
{
return new ApplicationFrameProxy(frame);
}
if (frame is EditorMainFrame)
{
return new EditorMainFrameProxy(frame);
}
if (frame is EditorFrame)
{
return new EditorFrameProxy(frame);
}
return new HierarchyFrameProxy(frame);
}
public HierarchyFrameProxy(IFrame frame) : base(frame)
{
HierarchyFrame = frame as HierarchyFrame;
}
public List<FrameBaseProxy> ChildFramesCompleteList
{
get
{
List<FrameBase> frames = new List<FrameBase>(HierarchyFrame.ChildFramesCompleteList);
return frames.ConvertAll(new Converter<FrameBase, FrameBaseProxy>(ToProxy));
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/LanguagePaletteElementProxy.cs
namespace YZX.Tia.Proxies.Ladder
{
public class LanguagePaletteElementProxy
{
}
}<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphNetElementProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphNetElementProxy
{
internal GraphNetElement GraphNetElement;
internal GraphNetElementProxy(GraphNetElement element)
{
GraphNetElement = element;
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamObjectCreatorProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public static class OamObjectCreatorProxy
{
public static int CreateAddress(string addressString, out IOamAddress address)
{
return OamObjectCreator.CreateAddress(addressString, out address);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/EditorMainFrameProxy.cs
using System.Collections.Generic;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class EditorMainFrameProxy:HierarchyFrameProxy
{
EditorMainFrame EditorMainFrame;
IEditorMainFrame IEditorMainFrame
{
get
{
return EditorMainFrame as IEditorMainFrame;
}
}
public EditorMainFrameProxy(IFrame frame) : base(frame)
{
EditorMainFrame = frame as EditorMainFrame;
}
EditorSplitManager EditorSplitManager
{
get
{
return EditorMainFrame.EditorSplitManager as EditorSplitManager;
}
}
public IFrame DockedEditor
{
get
{
return EditorMainFrame.DockedEditor;
}
}
public bool IsMaximized
{
get
{
return EditorMainFrame.IsMaximized;
}
}
public IEditorFrame FolderPortalFrame
{
get
{
return EditorMainFrame.FolderPortalFrame;
}
}
public IEnumerable<IEditorFrame> AllEditors
{
get
{
return EditorMainFrame.AllEditors;
}
}
public bool CheckEditorWithInstanceNameExists(string editorInstanceId)
{
return EditorMainFrame.CheckEditorWithInstanceNameExists(editorInstanceId);
}
public bool CheckEditorIsFloating(string editorInstanceId)
{
return EditorMainFrame.CheckEditorIsFloating(editorInstanceId);
}
public void EditorFullScreen(IEditorFrame editorFrame, bool fullSizeState)
{
IEditorMainFrame.EditorFullScreen(editorFrame, fullSizeState);
}
public void CloseEditor(IEditorFrame editorFrame)
{
IEditorMainFrame.CloseEditor(editorFrame);
}
public void Minimize(IEditorFrame frameToMinimize, bool minimize)
{
IEditorMainFrame.Minimize(frameToMinimize, minimize);
}
}
}
<file_sep>/YZX.TIA/Extensions/IConnectionServiceExtensions.cs
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainModel;
using Reflection;
using YZX.Tia.Proxies.OnlineService;
namespace YZX.Tia.Extensions
{
public static class IConnectionServiceExtensions
{
public static ConnectionServiceProvider ToConnectionServiceProvider(this IConnectionService ics)
{
if(ics is ConnectionServiceProvider)
{
return ics as ConnectionServiceProvider;
}
ConnectionServiceProxy csproxy = ics as ConnectionServiceProxy;
ConnectionServiceProvider csprovider = Reflector.GetInstanceFieldByName(csproxy, "m_RealConnectionService", ReflectionWays.SystemReflection) as ConnectionServiceProvider;
return csprovider;
}
public static ConnectionServiceProviderProxy ToProxy(this IConnectionService ics)
{
ConnectionServiceProvider csp = ics.ToConnectionServiceProvider();
var proxy = new ConnectionServiceProviderProxy(csp);
return proxy;
}
public static ICoreObject GetSimConnectionConfig(this IConnectionService ics)
{
var provider = ics.ToConnectionServiceProvider();
var boardConfigurations = provider.GetUsableConfigurations("OMS");
string str = "PLCSIM.TCPIP.1";
foreach (ICoreObject o in boardConfigurations)
{
IOamIdentification attributes = CoreObjectExtension.GetAttributes<IOamIdentification>(o);
if (attributes != null && attributes.OamName == str)
return o;
}
return null;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectCollectionExtensions.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static class ICoreObjectCollectionExtensions
{
public static List<string> GetNames(this ICoreObjectCollection oc)
{
List<string> names = new List<string>();
foreach(ICoreObject o in oc)
{
string name = o.GetObjectName();
names.Add(name);
}
return names;
}
public static ICoreObject GetCoreObjectByName(this ICoreObjectCollection oc,string name)
{
foreach (ICoreObject o in oc)
{
if(o.GetObjectName() == name)
{
return o;
}
}
return null;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectExtensions.SettingsService.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonServices.SettingsService;
using Siemens.Simatic.HwConfiguration.Basics.Basics;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static partial class ICoreObjectExtensions
{
public static ISettingsService GetSettingsService(ICoreObject device)
{
ISettingsService settingsService = null;
if (device != null)
{
IDlc dlc = device.Context as IDlc;
IHwcnBasicsFacade hwcnBasicsFacade = null;
if (dlc != null && dlc.WorkingContext != null)
hwcnBasicsFacade = dlc.WorkingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.Basics.HwcnBasicsFacade") as IHwcnBasicsFacade;
settingsService = hwcnBasicsFacade != null ? hwcnBasicsFacade.SettingsServiceV11 : (ISettingsService)null;
}
return settingsService;
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/NetworkElementProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Controls.TagComments;
namespace YZX.Tia.Proxies.Ladder
{
public class NetworkElementProxy : LanguagePaletteElementProxy
{
internal NetworkElement ne;
public LanguagePaletteBaseElement LanguagePaletteBaseElement
{
get
{
return ne;
}
}
internal NetworkElementProxy(NetworkElement ne)
{
this.ne = ne;
children = LanguagePaletteBaseElement.GetChildUIControls();
}
private List<IUIControl> children;
public CommandTextBoxElement CommandTextBoxElement
{
get
{
return children[0] as CommandTextBoxElement;
}
}
internal LanguageUIElementContainer LanguageUIElementContainer
{
get
{
UIControlWindowlessWrapper wrapper = children[1] as UIControlWindowlessWrapper;
return wrapper.Instance as LanguageUIElementContainer;
}
}
public CollapsableTextBoxElement CommentElement
{
get
{
return LanguageUIElementContainer.ChildControls[0] as CollapsableTextBoxElement;
}
}
public TagCommentElement NetworkTagCommentElement
{
get
{
return LanguageUIElementContainer.ChildControls[1] as TagCommentElement;
}
}
public SimaticFLGraphicEditor SimaticFLGraphicEditor
{
get
{
return LanguageUIElementContainer.ChildControls[2] as SimaticFLGraphicEditor;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/OMS/OmsSessionProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.DirectoryMappingService;
namespace YZX.Tia.Proxies
{
public class OmsSessionProxy
{
OmsSession OmsSession;
public OmsSessionProxy(IDisposable omsSession)
{
OmsSession = OmsSession as OmsSession;
}
}
}
<file_sep>/YZX.TIA/Extensions/DlcManagerExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.Utilities;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class DlcManagerExtensions
{
//internal static void AddLoadedDlcsToList(
// IEnumerable<IWorkingContext> workingContexts,
// IList<DlcMetaInfo> dlcMetaInfoList,
// List<IDlc> loadedDlcs)
//{
// Reflector.RunStaticMethodByName(typeof(DlcManager),
// "",
// ReflectionWays.SystemReflection,
// workingContexts, dlcMetaInfoList, loadedDlcs);
//}
public static ILibraryVersionService GetLibraryVersionService(this IDlcManager dlcManager)
{
return DlcIdExtensions.LoadByDlcId(dlcManager, DlcIds.Iecpl.BlockLogic.LibraryVersionService);
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamSimaticScannerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamSimaticScannerProxy
{
OamSimaticScanner OamSimaticScanner;
public OamSimaticScannerProxy(IOamScanner<IOamLocalBoard> scanner)
{
OamSimaticScanner = scanner as OamSimaticScanner;
}
public IEnumerable<IOamLocalBoard> Scan()
{
return OamSimaticScanner.Scan();
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/RootObjectHostServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
namespace YZX.Tia.Proxies.FrameApplication
{
public class RootObjectHostServiceProxy
{
internal RootObjectHostService RootObjectHostService;
internal RootObjectHostServiceProxy(RootObjectHostService service)
{
RootObjectHostService = service;
}
public RootCollectionHolderProxy RootCollectionHolder
{
get
{
return new RootCollectionHolderProxy(RootObjectHostService.RootCollectionHolder);
}
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Graph.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Reflection;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
private delegate BlockEditorLogicBase GetGraphBlockEditorLogicDelegate(
ICoreObject block,
IWorkingContext ViewWorkingContext = null,
ISynchronizeInvoke synchronizer = null);
public static BlockEditorLogicBase GetGraphBlockEditorLogic(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
if (UsingSynchronizer.InvokeRequired)
return UnifiedSynchronizerAccess.Invoke(UsingSynchronizer,
new GetGraphBlockEditorLogicDelegate(GetGraphBlockEditorLogic), new object[3]
{
block,
ViewWorkingContext,
synchronizer
}).InvokeResult as BlockEditorLogicBase;
GraphBlockEditorLogic pl = new GraphBlockEditorLogic();
if (ViewWorkingContext == null)
{
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
}
else
{
pl.Attach(ViewWorkingContext);
}
pl.PostAttach();
try
{
pl.SetPayload(block);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return pl;
}
private delegate BlockEditorControlBase GetGraphViewDelegate(
ICoreObject block,
IWorkingContext ViewWorkingContext = null,
ISynchronizeInvoke synchronizer = null);
public static BlockEditorControlBase GetGraphView(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
if (UsingSynchronizer.InvokeRequired)
return UnifiedSynchronizerAccess.Invoke(UsingSynchronizer,
new GetGraphViewDelegate(GetGraphView), new object[3]
{
block,
ViewWorkingContext,
synchronizer
}).InvokeResult as BlockEditorControlBase;
GraphBlockEditorControl pl = new GraphBlockEditorControl();
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
BlockEditorLogicBase logic = block.GetGraphBlockEditorLogic();
pl.SetDomainLogic(logic);
pl.SetPayload(block);
pl.InitializationFinished();
pl.CreateVisuals();
return pl;
}
}
}<file_sep>/MpkExtractor/Program.cs
using System;
using System.Windows.Forms;
namespace MpkExtractor
{
static class Program
{
[STAThread]
static int Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MpkExtractorForm());
return 0;
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamBlockCollectionProxy.cs
using Siemens.Automation.OnlineAccess;
namespace YZX.Tia.Proxies
{
public class OamBlockCollectionProxy
{
OamBlockCollection OamBlockCollection;
public OamBlockCollectionProxy(OamBlockCollection blocks)
{
OamBlockCollection = blocks;
}
}
}
<file_sep>/YZX.TIA/Proxies/ItemAccessStrategyProxy.cs
using Siemens.Automation.DomainServices.TagService;
using Reflection;
namespace YZX.Tia.Proxies
{
public class ItemAccessStrategyProxy
{
ItemAccessStrategy IItemAccessStrategy;
public ItemAccessStrategyProxy(object ias)
{
IItemAccessStrategy = ias as ItemAccessStrategy;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectExtensions.cs
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainModel;
using Siemens.Simatic.AlarmServices.Interfaces.Alarms;
using Siemens.Simatic.AlarmServices.Helper;
using Siemens.Automation.ObjectFrame.BusinessLogic;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static partial class ICoreObjectExtensions
{
public static int GetPnoIdent(ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier;
return 0;
}
public static int GetProfinetVendorId(this ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier >> 16;
return 0;
}
public static int GetProfinetDeviceId(this ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier & ushort.MaxValue;
return 0;
}
public static IControllerAlarm GetControllerAlarm(this ICoreObject coreObject)
{
IControllerAlarm alarm =
BusinessLogicConnectorHelper.GetBusinessLogic<IControllerAlarm>(
coreObject,
"Siemens.Simatic.AlarmServices.AlarmBusinessLogicFactory");
return alarm;
}
public static T GetAttributes<T>(this ICoreObject o) where T : class
{
return (o != null ? o.GetAttributeSet(typeof(T)) : null) as T;
}
public static T GetBl<T>(this ICoreObject coreObject, string serviceId)
{
return (T)((IBusinessLogicConnector)coreObject).GetBusinessLogic(serviceId);
}
public static IBusinessLogicObject Connect(this ICoreObject coreObject, int cookie, IBusinessLogicObject bl)
{
((IBusinessLogicConnector)coreObject).SetBusinessLogic(cookie, bl);
return bl;
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphConnectionProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphConnectionProxy
{
internal GraphConnection GraphConnection;
internal GraphConnectionProxy(GraphConnection connection)
{
GraphConnection = connection;
}
}
}
<file_sep>/YZX.TIA/TiaStarter.ViewManager.cs
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ObjectFrame;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
}
}
public void OpenVatTable(ICoreObject vatTable)
{
ViewManager.Show("Siemens.Simatic.PlcLanguages.VATViewer.VATViewerView", vatTable);
}
}
}<file_sep>/YZX.TIA/Extensions/TraceManagerExtensions.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
using Reflection;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions
{
public static class TraceManagerExtensions
{
public static List<string> GetTracerNames()
{
List<string> names = new List<string>();
TraceManager tm = TraceManager.Instance as TraceManager;
if (tm != null)
{
Dictionary<string, IComponentTrace> m_TracerStore =
Reflector.GetInstanceFieldByName(tm, "m_TracerStore", ReflectionWays.SystemReflection)
as Dictionary<string, IComponentTrace>;
foreach (var kct in m_TracerStore)
{
names.Add(kct.Key);
}
}
return names;
}
public static ITraceProxy GetTracer(string traceName)
{
ITraceManager tm = TraceManager.Instance as ITraceManager;
ITrace trace = tm.CreateTracer(traceName);
ITraceProxy traceProxy = new ITraceProxy(trace);
return traceProxy;
}
public static List<ITraceProxy> GetTracers()
{
List<ITraceProxy> tracers = new List<ITraceProxy>();
List<string> names = GetTracerNames();
foreach(string name in names)
{
ITraceProxy proxy = GetTracer(name);
tracers.Add(proxy);
}
return tracers;
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamVariableControlProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamVariableControlProxy
{
OamVariableControl OamVariableControl;
public OamVariableControlProxy(IOamVariableControl control)
{
OamVariableControl = control as OamVariableControl;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/DialogFrameMetaProxy.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class DialogFrameMetaProxy:HierarchyFrameMetaProxy
{
DialogFrameMeta DialogFrameMeta;
internal DialogFrameMetaProxy(DialogFrameMeta meta) : base(meta)
{
DialogFrameMeta = meta;
}
public bool IsModal
{
get
{
return DialogFrameMeta.IsModal;
}
}
public MultiLanguageString CheckBoxTitle
{
get
{
return DialogFrameMeta.CheckBoxTitle;
}
}
public int HelpId
{
get
{
return DialogFrameMeta.HelpId;
}
}
public string HelpFile
{
get
{
return DialogFrameMeta.HelpFile;
}
}
}
}
<file_sep>/Siemens.Automation.FileIO.Test/Proxies/FileIO/WriteableMpkDirectoryProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FileIO;
using Siemens.Automation.FileIO.Private;
using Siemens.Automation.FileIO.Private.MetaPackage;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FileIO
{
public class WriteableMpkDirectoryProxy
{
WriteableMpkDirectory WriteableMpkDirectory;
public WriteableMpkDirectoryProxy(IWriteableDirectory directory)
{
WriteableMpkDirectory = directory as WriteableMpkDirectory;
}
public MetaPackageImplementationProxy GetMetaPackageImplementationProxy()
{
var IMetaPackageAccess = Reflector.GetInstanceFieldByName(
WriteableMpkDirectory,
"m_MetaPackage",
ReflectionWays.SystemReflection)
as IMetaPackageAccess;
var MetaPackageImplementation = IMetaPackageAccess as MetaPackageImplementation;
var proxy = new MetaPackageImplementationProxy(IMetaPackageAccess);
return proxy;
}
}
}
<file_sep>/YZX.TIA/Proxies/OEM/UIOemCustomizationServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices.Internal.OemCustomization;
using Reflection;
namespace YZX.Tia.Proxies.OEM
{
public class UIOemCustomizationServiceProxy
{
internal UIOemCustomizationServiceDlc UIOemCustomizationServiceDlc;
internal UIOemCustomizationService UIOemCustomizationService;
public UIOemCustomizationServiceProxy(IDlc dlc)
{
UIOemCustomizationServiceDlc = dlc as UIOemCustomizationServiceDlc;
if(UIOemCustomizationServiceDlc != null)
{
UIOemCustomizationService = Reflector.GetInstanceFieldByName(UIOemCustomizationServiceDlc,
"m_UiOemCustomizationService",
ReflectionWays.SystemReflection) as UIOemCustomizationService;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/Tis/S7Extensions.cs
using System;
using Siemens.Simatic.PlcLanguages.PLInterface;
namespace YZX.Tia.Extensions
{
public static class S7Extensions
{
public static byte[] GetBytes(this S7Any val)
{
byte[] arr = new byte[10];
arr[0] = val.syntax_id;
arr[1] = val.datatyp;
CopyFrom(arr, 2, GetBytes(val.count));
CopyFrom(arr, 4, GetBytes(val.pointer_val.DbNumber));
CopyFrom(arr, 6, GetBytes(val.pointer_val.Ptr));
return arr;
}
public static S7Any ToS7Any(this byte[] bytes)
{
if (bytes == null)
throw new ArgumentException("Expect array of 10 bytes");
if (bytes.Length != 10)
throw new ArgumentException("Expect array of 10 bytes");
return new S7Any()
{
syntax_id = bytes[0],
datatyp = bytes[1],
count = ToUInt16(bytes, 2),
pointer_val = {
DbNumber = ToUInt16(bytes, 4),
Ptr = ToUInt32(bytes, 6)
}
};
}
public static byte[] GetBytes(this S7Pointer val)
{
byte[] arr = new byte[6];
CopyFrom(arr, 0, GetBytes(val.DbNumber));
CopyFrom(arr, 2, GetBytes(val.Ptr));
return arr;
}
public static S7Pointer ToS7Pointer(this byte[] bytes)
{
if (bytes == null)
throw new ArgumentException("Expect array of 6 bytes");
if (bytes.Length != 6)
throw new ArgumentException("Expect array of 6 bytes");
return new S7Pointer()
{
DbNumber = ToUInt16(bytes, 0),
Ptr = ToUInt32(bytes, 2)
};
}
public static byte[] GetBytes(this S7DateLTime val)
{
byte[] arr = new byte[12];
CopyFrom(arr, 0, GetBytes(val.year));
arr[2] = val.month;
arr[3] = val.day;
arr[4] = val.weekday;
arr[5] = val.hours;
arr[6] = val.minutes;
arr[7] = val.seconds;
CopyFrom(arr, 8, GetBytes(val.nanoseconds));
return arr;
}
public static S7DateLTime ToS7DateLTime(this byte[] bytes)
{
if (bytes == null)
throw new ArgumentException("Expect array of 12 bytes");
if (bytes.Length != 12)
throw new ArgumentException("Expect array of 12 bytes");
return new S7DateLTime()
{
year = ToUInt16(bytes, 0),
month = bytes[2],
day = bytes[3],
weekday = bytes[4],
hours = bytes[5],
minutes = bytes[6],
seconds = bytes[7],
nanoseconds = ToUInt32(bytes, 8)
};
}
public static DateTime ToDateTime(this S7DateLTime s7datetime)
{
DateTime dt = new DateTime(s7datetime.year, s7datetime.month, s7datetime.day,
s7datetime.hours, s7datetime.minutes, s7datetime.seconds);
return dt;
}
public static byte[] GetBytes(this S7DateTime val)
{
return new byte[8]
{
val.year,
val.month,
val.day,
val.hours,
val.minutes,
val.seconds,
val.msecs,
val.ms_wd
};
}
public static S7DateTime ToS7DateTime(this byte[] bytes)
{
if (bytes == null)
throw new ArgumentException("Expect array of 8 bytes");
if (bytes.Length != 8)
throw new ArgumentException("Expect array of 8 bytes");
return new S7DateTime()
{
year = bytes[0],
month = bytes[1],
day = bytes[2],
hours = bytes[3],
minutes = bytes[4],
seconds = bytes[5],
msecs = bytes[6],
ms_wd = bytes[7]
};
}
private static byte[] GetBytes(this ushort val)
{
return BitConverter.GetBytes(val);
}
private static byte[] GetBytes(this uint val)
{
return BitConverter.GetBytes(val);
}
private static byte[] Revert(this byte[] arr)
{
Array.Reverse(arr);
return arr;
}
private static byte[] CopyFrom(this byte[] arr, int pos, byte[] src)
{
Array.Copy(src, 0, arr, pos, src.Length);
return arr;
}
private static ushort ToUInt16(this byte[] arr, int startIndex)
{
return BitConverter.ToUInt16(arr, startIndex);
}
private static uint ToUInt32(this byte[] arr, int startIndex)
{
return BitConverter.ToUInt32(arr, startIndex);
}
private static byte[] SubArray(this byte[] arr, int startIndex, int len)
{
byte[] numArray = new byte[len];
Array.Copy(arr, startIndex, numArray, 0, numArray.Length);
return numArray;
}
}
}
<file_sep>/YZX.TIA/Proxies/S7JobProxy.cs
using Siemens.Automation.OnlineAccess.S7SDDnet;
namespace YZX.Tia.Proxies
{
public class S7JobProxy
{
internal S7Job S7Job { get; private set; }
internal S7JobProxy(S7Job job)
{
S7Job = job;
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/S7DOSConnectionProxy.cs
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class S7DOSConnectionProxy : OamConnectionProxy
{
S7DOSConnection S7DOSConnection;
public S7DOSConnectionProxy(OamConnectionBase connection)
: base(connection)
{
{
S7DOSConnection = connection as S7DOSConnection;
}
}
List<OamAsynchronousCommand> ActiveAsynchronousComands
{
get
{
return S7DOSConnection.ActiveAsynchronousComands;
}
}
public bool DisconnectByBackgroundControl
{
get
{
return S7DOSConnection.DisconnectByBackgroundControl;
}
}
public IOamAddress Address
{
get
{
return S7DOSConnection.Address;
}
}
public OamJobControl JobControlInt
{
get
{
return S7DOSConnection.JobControlInt;
}
}
public string LogDevice
{
get
{
return S7DOSConnection.LogDevice;
}
}
public OamConnectionOpenModes Openmode
{
get
{
return S7DOSConnection.Openmode;
}
set
{
S7DOSConnection.Openmode = value;
}
}
public bool SynchronousDisconnected
{
get
{
return S7DOSConnection.SynchronousDisconnected;
}
set
{
S7DOSConnection.SynchronousDisconnected = value;
}
}
public bool AreAllJobsStoppedForThisConnection
{
get
{
return S7DOSConnection.AreAllJobsStoppedForThisConnection;
}
set
{
S7DOSConnection.AreAllJobsStoppedForThisConnection = value;
}
}
public bool IsConnectionEstablishedByJob
{
get
{
return S7DOSConnection.IsConnectionEstablishedByJob;
}
set
{
S7DOSConnection.IsConnectionEstablishedByJob = value;
}
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Extensions/Diagnostic/DoeInstanceAccessExtensions.cs
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.Diagnostic
{
public static class DoeInstanceAccessExtensions
{
public static IDoeViewAccess GetDoeViewAccess(this IDoeInstanceAccess iaccess)
{
DoeInstanceAccess access = iaccess as DoeInstanceAccess;
if (access != null)
{
return Reflector.GetInstanceFieldByName(access, "m_DoeViewAccess", ReflectionWays.SystemReflection)
as IDoeViewAccess;
}
else
{
return null;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.WindowManager.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IViewContent GetNavigationView([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.ProjectNavigatorView") as ProjectNavigationView;
}
internal static ISlideManager GetSlideManager([NotNull] this IWorkingContext workingContext)
{
return (ISlideManager)workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.WindowManager.SlidingManager", true);
}
public static SlidingManagerProxy GetSlideManagerProxy([NotNull] this IWorkingContext workingContext)
{
SlidingManager sm = workingContext.GetSlideManager() as SlidingManager;
return new SlidingManagerProxy(sm);
}
internal static IWindowManagerInternal GetWindowManager([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<IWindowManagerInternal>("Siemens.Automation.FrameApplication.WindowManager");
}
public static WindowManagerProxy GetWindowManagerProxy([NotNull] this IWorkingContext workingContext)
{
return new WindowManagerProxy(workingContext.GetWindowManager());
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamThreadPoolProxy.cs
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Reflection;
namespace YZX.Tia.Proxies
{
public class OamThreadPoolProxy
{
OamThreadPool OamThreadPool;
public static OamThreadPoolProxy Default
{
get
{
return new OamThreadPoolProxy(OamThreadPool.Default);
}
}
private OamThreadPoolProxy(OamThreadPool pool)
{
OamThreadPool = pool;
}
//public Dictionary<int, object> ThreadList
//{
// get
// {
// }
//}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamLocalBoardBaseProxy.cs
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamLocalBoardBaseProxy
{
OamLocalBoardBase OamLocalBoardBase;
public OamLocalBoardBaseProxy(IOamLocalBoard localBoardBase)
{
OamLocalBoardBase = localBoardBase as OamLocalBoardBase;
}
public bool BoardPlcRedirected
{
get
{
return OamLocalBoardBase.BoardPlcRedirected;
}
}
public bool HasOpenConnections()
{
return OamLocalBoardBase.HasOpenConnections();
}
public OamNetType NetType
{
get
{
return OamLocalBoardBase.NetType;
}
}
public IEnumerable<OamNetType> SupportedNetTypes
{
get
{
return OamLocalBoardBase.SupportedNetTypes;
}
}
public string BoardType
{
get
{
return OamLocalBoardBase.BoardType;
}
}
public OamLocalBoardState State
{
get
{
return OamLocalBoardBase.State;
}
}
public void ChangeSimulated(bool simulated, bool plcsim)
{
OamLocalBoardBase.ChangeSimulated(simulated, plcsim);
}
public void UpdateBoardState()
{
OamLocalBoardBase.UpdateBoardState();
}
public IEnumerable<IOamConfiguration> SearchActiveConfigurations()
{
return OamLocalBoardBase.SearchActiveConfigurations();
}
public int CanSaveParameters()
{
return OamLocalBoardBase.CanSaveParameters();
}
public int StartParamServer()
{
return OamLocalBoardBase.StartParamServer();
}
public int StopParamServer()
{
return OamLocalBoardBase.StopParamServer();
}
public override string ToString()
{
return OamLocalBoardBase.ToString() + "-" + State;
}
}
}
<file_sep>/YZX.TIA/Proxies/ThreadSynchronizerPerformanceMeasurementProxy.cs
using System.ComponentModel;
using Siemens.Automation.Basics.Synchronizer;
namespace YZX.Tia.Proxies
{
public class ThreadSynchronizerPerformanceMeasurementProxy
{
private ThreadSynchronizerPerformanceMeasurement tspm;
public ThreadSynchronizerPerformanceMeasurementProxy(ThreadSynchronizerProxy tsp)
:this(tsp.Synchronize as ISynchronizeInvoke)
{
}
public ThreadSynchronizerPerformanceMeasurementProxy(ISynchronizeInvoke isi)
{
ThreadSynchronizer ts = isi as ThreadSynchronizer;
tspm = new ThreadSynchronizerPerformanceMeasurement(ts, ts);
}
public void DumpStatistics()
{
tspm.DumpStatistics();
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Proxies/BlockLogic/QueryBasedControllerTargetLookupProxy.cs
using System;
using Siemens.Simatic.PlcLanguages.BlockLogic.OpenBlockHandling;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.Filter;
using Siemens.Automation.ObjectFrame.Meta;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.BlockLogic
{
public class QueryBasedControllerTargetLookupProxy
{
IControllerTargetLookup lookup;
private IAttributeSetInfo m_CoreAttributeSetInfo;
public IAttributeSetInfo CoreAttributeSetInfo {
get
{
if (m_CoreAttributeSetInfo == null)
{
m_CoreAttributeSetInfo = Reflector.GetInstanceFieldByName(lookup,
"m_CoreAttributeSetInfo", ReflectionWays.SystemReflection)
as IAttributeSetInfo;
}
return m_CoreAttributeSetInfo;
}
}
public ICoreContext m_CoreContext;
public ICoreContext CoreContext
{
get
{
if (m_CoreContext == null)
{
m_CoreContext = Reflector.GetInstanceFieldByName(lookup,
"m_CoreContext", ReflectionWays.SystemReflection)
as ICoreContext;
}
return m_CoreContext;
}
}
public IObjectTypeInfo m_ControllerTargetTypeInfo;
public IObjectTypeInfo ControllerTargetTypeInfo
{
get
{
if (m_ControllerTargetTypeInfo == null)
{
m_ControllerTargetTypeInfo = Reflector.GetInstanceFieldByName(lookup,
"m_ControllerTargetTypeInfo", ReflectionWays.SystemReflection)
as IObjectTypeInfo;
}
return m_ControllerTargetTypeInfo;
}
}
public QueryBasedControllerTargetLookupProxy(ICoreContext coreContext)
{
lookup = new QueryBasedControllerTargetLookup(coreContext);
}
public ICoreObject FindControllerTargetByName(string name)
{
return lookup.FindControllerTargetByName(name);
}
public ICoreObjectCollection ListAllControllerTarget()
{
try
{
var typeIterator = new TypeIterator(ControllerTargetTypeInfo, true, false);
var selectClause = new ObjectReferenceExpression(typeIterator, CoreAttributeSetInfo);
var name =
new NotEqualExpression(
new AttributeReferenceExpression(CoreContext, typeof(ICoreAttributes), "Name", typeIterator),
new ConstantExpression(string.Empty)
);
var whereClause = new FilterCondition(CoreContext, name);
var query = CoreContext.CreateObjectQuery(selectClause, typeIterator,
whereClause,
SortCondition.Empty);
var objectCollection =
CoreContext.GetCoreObjectCollection(query, CollectionFlag.SnapShot);
return objectCollection;
} catch (Exception ex)
{
return null;
}
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameApplicationExtensions.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Menu;
using Siemens.Automation.FrameApplication.StatusBar;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.FrameApplication
{
public static partial class FrameApplicationExtensions
{
public static StatusBarProxy GetStatusBar(this IWorkingContext workingContext)
{
StatusBarDlc dlc = workingContext.GetRequiredDlc<StatusBarDlc>("Siemens.Automation.FrameApplication.StatusBar");
return new StatusBarProxy(dlc);
}
public static MenuServiceImplementationProxy GetMenuService(this IWorkingContext workingContext)
{
MenuService dlc = workingContext.GetRequiredDlc<MenuService>("Siemens.Automation.FrameApplication.Menu.MenuService");
return new MenuServiceImplementationProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/SlidingManagerProxy.cs
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class SlidingManagerProxy
{
SlidingManager SlidingManager;
internal SlidingManagerProxy(SlidingManager sm)
{
SlidingManager = sm;
}
}
}
<file_sep>/YZX.TIA/FakeProjectManager.cs
using System;
using System.ComponentModel;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia
{
public class FakeProjectManager : IProjectManager
{
private IProjectManager projectManager;
public FakeProjectManager(IProjectManager projectManager)
{
this.projectManager = projectManager;
}
public ICoreContextHandler CurrentCoreContextHandler
{
get
{
return projectManager.CurrentCoreContextHandler;
}
}
public ICorePersistence CurrentProject
{
get
{
throw new NotImplementedException();
}
}
public string CurrentProjectPath
{
get
{
return projectManager.CurrentProjectPath;
}
}
public string ProjectExtension
{
get
{
return projectManager.ProjectExtension;
}
}
public event EventHandler Closed;
public event EventHandler Closing;
public event EventHandler Opened;
public event CancelEventHandler PreOpening;
public event EventHandler Saved;
public event CancelEventHandler Saving;
public bool AreProjectVersionsCompatible(Version version1, Version version2)
{
throw new NotImplementedException();
}
public void DeleteProject(string path)
{
throw new NotImplementedException();
}
public string GetArchiveDirectory()
{
throw new NotImplementedException();
}
public Version GetStarterFileVersion(string directoryOrStarterFilePath)
{
throw new NotImplementedException();
}
public string[] GetSupportedGlobalLibraryExtensions()
{
throw new NotImplementedException();
}
public string[] GetSupportedLibraryZipExtensions()
{
throw new NotImplementedException();
}
public string[] GetSupportedLocalSessionExtensions()
{
throw new NotImplementedException();
}
public string[] GetSupportedProjectExtensions()
{
throw new NotImplementedException();
}
public string[] GetSupportedSystemLibraryExtensions()
{
throw new NotImplementedException();
}
public string[] GetSupportedZipExtensions()
{
throw new NotImplementedException();
}
public void RenameProject(string oldDirectory, string newDirectory)
{
throw new NotImplementedException();
}
public void SaveProject(ICorePersistence persistence)
{
throw new NotImplementedException();
}
public void SaveProjectAs(ICorePersistence project, string path)
{
throw new NotImplementedException();
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/ProjectNavigatorStateManagerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication.WindowManager;
using Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ProjectNavigatorStateManagerProxy
{
ProjectNavigatorStateManager ProjectNavigatorStateManager;
internal ProjectNavigatorStateManagerProxy(ProjectNavigatorStateManager manager)
{
manager = ProjectNavigatorStateManager = manager as ProjectNavigatorStateManager;
}
public void ToggleCurrent()
{
ProjectNavigatorStateManager.ToggleCurrent();
}
public void ChangeState()
{
ProjectNavigatorStateManager.ChangeState();
}
public void ShowSlide()
{
ProjectNavigatorStateManager.ShowSlide();
}
public void UpdateSlideWidth(int newSlideWidth)
{
ProjectNavigatorStateManager.UpdateSlideWidth(newSlideWidth);
}
public void EmbedAsCollapsedFromSliding()
{
ProjectNavigatorStateManager.EmbedAsCollapsedFromSliding();
}
public void SlideWithoutShow()
{
ProjectNavigatorStateManager.SlideWithoutShow();
}
public void HideSlideIfShown()
{
ProjectNavigatorStateManager.HideSlideIfShown();
}
}
}
<file_sep>/YZX.TIA/Extensions/OMS/IOMSConnectionExtensions.cs
using System;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.HwConfiguration.Basics.Utilities;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OMSPlus.Managed;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class IOMSConnectionExtensions
{
public static SecurePassword GetSaltedPassword(this IOMSConnection conn,
SecurePassword plain)
{
byte[] bytes = Encoding.UTF8.GetBytes(plain.GetPlain());
SecurePassword securePassword = plain;
byte[] buffer = conn.UploadSalt();
if (buffer == null)
return securePassword;
PcIdent pcIdent = new PcIdent(buffer);
if (pcIdent.IsValid())
{
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(bytes, pcIdent.Salt, pcIdent.Rounds))
securePassword = SecurePassword.Create(Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(pcIdent.DerivedBytesLen)));
}
return securePassword;
}
public static byte[] UploadSalt(this IOMSConnection conn)
{
byte[] data = null;
Rid rid = new Rid(37U);
Aid aid = new Aid(2449U);
Value obj = null;
int requestID = -1;
Error error = conn.ClientSession.GetVariableRemote(rid, aid, ref obj, ref requestID);
if (error.Failed)
return null;
using (obj)
{
Blob blob = null;
error = obj.GetValue(ref blob);
if (error.Succeeded)
{
if (blob != null)
{
error = blob.GetData(ref data);
blob.Dispose();
}
}
}
if (!error.Failed)
return data;
return null;
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/LifelistAsyncScannerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.CommonServices;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
namespace YZX.Tia.Proxies.Oam
{
public class LifelistAsyncScannerProxy
{
LifelistAsyncScanner scanner;
public LifelistAsyncScannerProxy(ILifelistService lifeListService,
IFeedbackService feedbackService,
IJobbasedSynchronizeInvoke synchronizer)
{
scanner = new LifelistAsyncScanner(lifeListService, feedbackService, synchronizer);
}
}
}
<file_sep>/YZX.TIA/Extensions/PythonSynAccess.cs
using System;
using System.ComponentModel;
using Siemens.Automation.DomainServices;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
namespace YZX.Tia.Extensions
{
public static class PythonSynAccess
{
public static void InvokeAction(ISynchronizeInvoke synchronizer,
PythonFunction method)
{
Action action = () => {
PythonCalls.Call(method);
};
UnifiedSynchronizerAccess.Invoke(synchronizer, action,null);
}
public static UnifiedInvokeResult InvokeFunc<T> (ISynchronizeInvoke synchronizer,
PythonFunction method)
{
Func<T> func = () => {
return (T)PythonCalls.Call(method);
};
return UnifiedSynchronizerAccess.Invoke(synchronizer, func,null);
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.LifelistService.cs
using Siemens.Automation.DomainServices;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public ILifelistService LifelistService
{
get
{
return m_BusinessLogicApplicationContext.GetLifelist();
}
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/OnlineCommonLifeListFacadeProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using Siemens.Automation.DomainServices.UI.OnlineCommon.DataBinding;
using Reflection;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies.OnlineService
{
public class OnlineCommonLifeListFacadeProxy
{
internal OnlineCommonLifeListFacade OnlineCommonLifeListFacade;
internal OnlineCommonLifeListFacadeProxy(OnlineCommonLifeListFacade facade)
{
OnlineCommonLifeListFacade = facade;
}
public List<OnlineCommonNodeProxy> UserAddressesLifelistNodes
{
get
{
var nodes = Reflector.GetInstancePropertyByName(OnlineCommonLifeListFacade,
"UserAddressesLifelistNodes", ReflectionWays.SystemReflection)
as List<OnlineCommonNode>;
return nodes.ConvertAll(new Converter<OnlineCommonNode, OnlineCommonNodeProxy>(
OnlineServiceConverters.OnlineCommonNodeProxy));
}
}
public OnlineCommonHelperProxy Helper
{
get
{
return new OnlineCommonHelperProxy(OnlineCommonLifeListFacade.Helper);
}
}
public OamProtocolType ProtocolType
{
get
{
return OnlineCommonLifeListFacade.ProtocolType;
}
}
public OnlineCommonNodeProxy SelectedNode
{
get
{
var node = Reflector.GetInstancePropertyByName(OnlineCommonLifeListFacade,
"SelectedNode", ReflectionWays.SystemReflection)
as OnlineCommonNode;
return new OnlineCommonNodeProxy(node);
}
set
{
Reflector.SetInstancePropertyByName(OnlineCommonLifeListFacade,
"SelectedNode", value.OnlineCommonNode,
ReflectionWays.SystemReflection);
}
}
public SortedList<string, string> PresentMacToIPAddresses
{
get
{
return OnlineCommonLifeListFacade.PresentMacToIPAddresses;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.LibraryService.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.LibraryService;
using Siemens.Simatic.PlcLanguages.LibraryService.Meta;
using Siemens.Simatic.PlcLanguages.LibraryService.Tree;
using Siemens.Simatic.Lang.PLInternal.BlockInterface;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static ILibBaseService GetBaseService(this IWorkingContext workingContext)
{
return LibraryServices.GetBaseService(workingContext);
}
public static ILibMetaService GetMetaService(this IWorkingContext workingContext)
{
return LibraryServices.GetMetaService(workingContext);
}
public static ILibTreeService GetTreeService(this IWorkingContext workingContext)
{
return LibraryServices.GetTreeService(workingContext);
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/OmsSessionConfiguratorProxy.cs
using System;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public static class OmsSessionConfiguratorProxy
{
public static IOmsModelLoader OmsLoadHelper
{
get
{
return OmsSessionConfigurator.OmsLoadHelper;
}
}
public static string DefaultLocationPaom
{
get
{
Type t = typeof(OmsSessionConfigurator);
return (string)Reflector.GetStaticPropertyByName(t,
"DefaultLocationPaom",
ReflectionWays.SystemReflection);
}
}
public static string DefaultLocationPaim
{
get
{
Type t = typeof(OmsSessionConfigurator);
return (string)Reflector.GetStaticPropertyByName(t,
"DefaultLocationPaim",
ReflectionWays.SystemReflection);
}
}
public static IASModelDescription ResolveASModelLocation(ICoreObject target)
{
return OmsSessionConfigurator.ResolveASModelLocation(target);
}
public static IASModelDescription ResolveASModelLocation(ICoreObject cardReaderSlot,
uint paomVersionID,
string paomVersionIdString)
{
return OmsSessionConfigurator.ResolveASModelLocation(cardReaderSlot, paomVersionID, paomVersionIdString);
}
public static void ResolvePublicKey(ICoreObject target, out PublicKeyInfo publicKeyInfo)
{
OmsSessionConfigurator.ResolvePublicKey(target, out publicKeyInfo);
}
public static void ResolvePublicKey(ICoreObject cardReaderSlot,
uint paomVersionID,
string paomVersionIdString,
out PublicKeyInfo publicKeyInfo)
{
OmsSessionConfigurator.ResolvePublicKey(cardReaderSlot,
paomVersionID, paomVersionIdString, out publicKeyInfo);
}
public static int LoadSpecificAsModel(ClientSession omsSession, ICoreObject target)
{
return OmsSessionConfigurator.LoadSpecificAsModel(omsSession, target);
}
public static int LoadSpecificPublicKey(ClientSession omsSession, ICoreObject target)
{
return OmsSessionConfigurator.LoadSpecificPublicKey(omsSession, target);
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamVariableContainerProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamVariableContainerProxy
{
OamVariableContainer OamVariableContainer;
public OamVariableContainerProxy(IOamVariableContainer container)
{
OamVariableContainer = container as OamVariableContainer;
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Block.cs
using System.Net;
using Siemens.Automation.DomainServices;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.BusinessLogic;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.HwConfiguration.Diagnostic.Common;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static IBlock GetBlock(this ICoreObject coreObject)
{
IBlock block = IecplUtilities.GetBusinessLogicBlock(coreObject) as IBlock;
return block;
}
public static ICodeBlock GetCodeBlock(this ICoreObject coreObject)
{
return (ICodeBlock)((IBusinessLogicConnector)coreObject).GetBusinessLogic("PlcLanguages.BlockLogic.BlockService");
}
private static void SetIpAddress(this ICoreObject onlineCore,
DiagServiceProvider DiagServiceProvider,
int addressType,
byte[] ipAddress,
byte[] subnetMask,
byte[] router){
IEthernetDiscoverNode ethernetDiscoverNode = DiagServiceProvider.PELifelistService.GetOamNode(onlineCore.GetParent().GetParent()) as IEthernetDiscoverNode;
if (ethernetDiscoverNode == null)
return;
IPAddress ipAddress1 = new IPAddress(ethernetDiscoverNode.IpStationParams.LocalIpParam.InternetProtocolAddress.GetAddressBytes());
IPAddress ipAddress2 = new IPAddress(ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalIpv4SubnetMask.GetAddressBytes());
IPAddress ipAddress3 = new IPAddress(ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalDefaultRouter.GetAddressBytes());
if (ethernetDiscoverNode.Configuration.ProtocolType != OamProtocolType.Ethernet && ethernetDiscoverNode.Configuration.ProtocolType != OamProtocolType.InternetProtocol && ethernetDiscoverNode.Configuration.ProtocolType != OamProtocolType.Auto)
throw new OnlineException(4, 240);
if (ipAddress == null)
throw new OnlineException(7, 240);
IPAddress ipAddress4 = new IPAddress(ipAddress);
ethernetDiscoverNode.IpStationParams.LocalIpParam.InternetProtocolAddress = ipAddress4;
if (subnetMask != null)
ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalIpv4SubnetMask = new IPAddress(subnetMask);
if (router != null)
{
if (1 == addressType)
{
IPAddress ipAddress5 = new IPAddress(router);
ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalDefaultRouter = ipAddress5;
}
else
ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalDefaultRouter = ipAddress4;
}
ethernetDiscoverNode.IpStationParams.LocalIpParam.IpActive = 1;
ethernetDiscoverNode.IpStationParams.PermanentStorage = true;
int errorCode = ethernetDiscoverNode.IpStationParams.Write();
if (errorCode != 0)
{
int serviceId = DiagServiceProvider.OnlineSessionDlc.OnlineAccess.ErrorHandler.ServiceId;
ethernetDiscoverNode.IpStationParams.LocalIpParam.InternetProtocolAddress = ipAddress1;
ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalIpv4SubnetMask = ipAddress2;
ethernetDiscoverNode.IpStationParams.LocalIpParam.LocalDefaultRouter = ipAddress3;
ethernetDiscoverNode.IpStationParams.Write();
throw new OnlineException(errorCode, serviceId, string.Empty);
}
}
internal static IOnlinePlusBlockAccess GetBlockAccess(ICoreObject target, ClientSession clientSession)
{
return OnlineBlockAccess.GetBlockAccess(target, clientSession);
}
}
}
<file_sep>/YZX.TIA/Extensions/BlockEditor/GraphicManagerExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.UserInteraction;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.Selection;
using YZX.Tia.Proxies.Ladder;
namespace YZX.Tia.Extensions.Ladder
{
public static class GraphicManagerExtensions
{
public static void SetNullInteractor(this GraphicManager manager)
{
DefaultUserInteractor oldInteractor = manager.UserInteractor;
NullUserInteractor newInteractor = new NullUserInteractor(oldInteractor);
manager.SetUserInteractor(newInteractor);
}
public static void SetNullSelectionManager(this GraphicManager manager)
{
DefaultSelectionManager oldManager = manager.SelectionManager as DefaultSelectionManager;
NullSelectionManager newManager = new NullSelectionManager(manager.FLGView,manager);
manager.SetSelectionManager(newManager);
}
public static List<GraphicObjectProxy> ToGraphicObjectProxyList(this GraphicManager manager)
{
List<GraphicObjectProxy> list = new List<GraphicObjectProxy>();
foreach(var go in manager)
{
GraphicObjectProxy proxy = new GraphicObjectProxy(go);
list.Add(proxy);
}
return list;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.JobbasedSynchronizeInvoke.cs
using System.Threading;
using Siemens.Automation.Basics.Synchronizer;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public IJobbasedSynchronizeInvoke JobbasedSynchronizeInvoke
{
get
{
return m_ViewApplicationContext.GetRequiredDlc<IJobbasedSynchronizeInvoke>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer");
}
}
}
}
<file_sep>/YZX.TIA/Proxies/PlusBlockConsistencyServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus.Upload;
using Reflection;
namespace YZX.Tia.Proxies
{
public class PlusBlockConsistencyServiceProxy
{
PlusBlockConsistencyService PlusBlockConsistencyService;
public PlusBlockConsistencyServiceProxy(IUpload upload)
{
PlusBlockConsistencyService = upload as PlusBlockConsistencyService;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/ViewManagerExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions.FrameApplication
{
public static class ViewManagerExtensions
{
public static IViewManager GetViewManager(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.ViewManager") as IViewManager;
}
public static ViewManagerProxy GetViewManagerProxy(this IWorkingContext workingContext)
{
ViewManagerDlc dlc = workingContext.GetViewManager() as ViewManagerDlc;
ViewManagerFacade facade = Reflector.GetInstanceFieldByName(dlc,
"m_ViewManagerFacade",
ReflectionWays.SystemReflection) as ViewManagerFacade;
IViewManager manager = Reflector.GetInstanceFieldByName(facade,
"m_ViewManager",
ReflectionWays.SystemReflection) as IViewManager;
ViewManagerProxy proxy = new ViewManagerProxy(manager);
return proxy;
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.Lifelist.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using Siemens.Automation.DomainServices.OnlineService;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static LifelistActivator GetLifelistActivator([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.LifelistActivator") as LifelistActivator;
}
public static ILifelistService GetLifelist([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.LifelistService") as ILifelistService;
}
public static LifeListView GetLifeListView([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.UI.OnlineCommon.LifeListView") as LifeListView;
}
public static LifeListEmbeddedPortalView GetLifeListEmbeddedPortalView([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.UI.OnlineCommon.LifeListEmbeddedPortalView") as LifeListEmbeddedPortalView;
}
public static LifelistBrowserExtension GetLifelistBrowserExtension([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<LifelistBrowserExtension>("Siemens.Automation.DomainServices.LifelistBrowserExtension");
}
public static LifelistPNVBrowserExtension GetLifelistPNVBrowserExtension([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<LifelistPNVBrowserExtension>("Siemens.Automation.DomainServices.LifelistPNVBrowserExtension");
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphSequenceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphSequenceProxy
{
GraphSequence GraphSequence;
internal GraphSequenceProxy(GraphSequence sequence)
{
GraphSequence = sequence;
}
public string Title
{
get
{
return GraphSequence.Title;
}
set
{
GraphSequence.Title = value;
}
}
public string Comment
{
get
{
return GraphSequence.Comment;
}
set
{
GraphSequence.Comment = value;
}
}
public List<GraphTransitionProxy> Transitions
{
get
{
return GraphSequence.Transitions.ConvertAll(new Converter<GraphTransition, GraphTransitionProxy>(
GraphBlockLogicConverters.GraphTransitionProxy));
}
}
public List<GraphStepProxy> Steps
{
get
{
return GraphSequence.Steps.ConvertAll(new Converter<GraphStep, GraphStepProxy>(
GraphBlockLogicConverters.GraphStepProxy));
}
}
public List<GraphBranchProxy> Branches
{
get
{
return GraphSequence.Branches.ConvertAll(new Converter<GraphBranch, GraphBranchProxy>(
GraphBlockLogicConverters.GraphBranchProxy));
}
}
public List<GraphActionProxy> OnActions
{
get
{
return GraphSequence.OnActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphActionProxy> OffActions
{
get
{
return GraphSequence.OffActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphActionProxy> OffAllActions
{
get
{
return GraphSequence.OffAllActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphSequencePartProxy> SequenceParts
{
get
{
return GraphSequence.SequenceParts.ConvertAll(new Converter<GraphSequencePart, GraphSequencePartProxy>(
GraphBlockLogicConverters.GraphSequencePartProxy));
}
}
public List<GraphSequencePartProxy> RelevantSequenceParts
{
get
{
return GraphSequence.RelevantSequenceParts.ConvertAll(new Converter<GraphSequencePart, GraphSequencePartProxy>(
GraphBlockLogicConverters.GraphSequencePartProxy));
}
}
public List<GraphConnectionProxy> Connections
{
get
{
return GraphSequence.Connections.ConvertAll(new Converter<GraphConnection, GraphConnectionProxy>(
GraphBlockLogicConverters.GraphConnectionProxy));
}
}
public GraphStepProxy FindStepByNumber(int number)
{
GraphStep step = GraphSequence.FindStepByNumber(number);
return new GraphStepProxy(step);
}
public GraphTransitionProxy FindTransitionByNumber(int number)
{
GraphTransition transition = GraphSequence.FindTransitionByNumber(number);
return new GraphTransitionProxy(transition);
}
public GraphBranchProxy FindBranchByNumber(int number)
{
GraphBranch branch = GraphSequence.FindBranchByNumber(number);
return new GraphBranchProxy(branch);
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/GraphicObjectProxy.cs
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.Logic;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.UserInteraction;
namespace YZX.Tia.Proxies.Ladder
{
public class GraphicObjectProxy
{
internal GraphicObject graphicObject;
public GraphicObjectProxy(object graphicObject)
{
this.graphicObject = graphicObject as GraphicObject;
}
public Element LogicalObject
{
get
{
return graphicObject.LogicalObject;
}
}
public bool SupportEdit
{
get
{
IEditFieldProvider provider = graphicObject as IEditFieldProvider;
return provider != null;
}
}
public IFLGEditBoxHandler EditBoxHandler {
get
{
if (SupportEdit)
{
IEditFieldProvider provider = graphicObject as IEditFieldProvider;
return provider.EditBoxHandler;
}
return null;
}
}
}
}<file_sep>/YZX.TIA/Proxies/Graph/GraphBlockEditorControlProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
namespace YZX.Tia.Proxies.Graph
{
public class GraphBlockEditorControlProxy
{
internal GraphBlockEditorControl GraphBlockEditorControl;
public GraphBlockEditorControlProxy(BlockEditorControlBase element)
{
GraphBlockEditorControl = element as GraphBlockEditorControl;
}
public BlockEditorLogicBase GraphBlockEditorLogic
{
get
{
return GraphBlockEditorControl.GraphBlockEditorLogic;
}
}
public GraphBlockEditorLogicProxy GraphBlockEditorLogicProxy
{
get
{
return new GraphBlockEditorLogicProxy(GraphBlockEditorLogic);
}
}
public MainControlContainerProxy MainControlContainer
{
get
{
return new MainControlContainerProxy(GraphBlockEditorControl.MainControlContainer);
}
}
public NavigationViewControlProxy NavigationViewControl
{
get
{
return new NavigationViewControlProxy(GraphBlockEditorControl.NavigationViewControl);
}
}
public GraphModelProxy ModelProxy
{
get
{
return new GraphModelProxy(GraphBlockEditorControl.Model);
}
}
public GraphDrawSettingsProxy BasicDrawSettings
{
get
{
var settings = GraphBlockEditorControl.BasicDrawSettings;
var proxy = new GraphDrawSettingsProxy(settings);
return proxy;
}
}
public List<IUIControl> GetChildUIControls()
{
return GraphBlockEditorControl.GetChildUIControls();
}
public void ShowAlarmMainCtrl(bool focus, bool speedySplitterHandling = false)
{
GraphBlockEditorControl.ShowAlarmMainCtrl(focus, speedySplitterHandling);
}
public void ShowSingleStepMainCtrl(bool focus, bool speedySplitterHandling = false)
{
GraphBlockEditorControl.ShowSingleStepMainCtrl(focus, speedySplitterHandling);
}
public void DisableGraphBlockInput()
{
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BackupClassicUploadProxy.cs
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia
{
public class BackupClassicUploadProxy
{
BackupClassicUpload BackupClassicUpload;
public BackupClassicUploadProxy(object upload)
{
BackupClassicUpload = upload as BackupClassicUpload;
}
}
}<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphModelProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphModelProxy
{
internal GraphModel GraphModel;
internal GraphModelProxy(GraphModel model)
{
GraphModel = model;
}
public List<GraphActionsProxy> Actions
{
get
{
return GraphModel.Actions.ConvertAll(new Converter<GraphActions, GraphActionsProxy>(
GraphBlockLogicConverters.GraphActionsProxy));
}
}
public List<GraphStepProxy> InitialSteps
{
get
{
return GraphModel.InitialSteps.ConvertAll(new Converter<GraphStep, GraphStepProxy>(
GraphBlockLogicConverters.GraphStepProxy));
}
}
public List<GraphSequenceProxy> Sequences
{
get
{
return GraphModel.Sequences.ConvertAll(new Converter<GraphSequence, GraphSequenceProxy>(
GraphBlockLogicConverters.GraphSequenceProxy));
}
}
public List<GraphActionProxy> OnActions
{
get
{
return GraphModel.OnActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphActionProxy> OffActions
{
get
{
return GraphModel.OffActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
#region Step
public GraphStepProxy FindStepByNumber(int number)
{
GraphStep step = GraphModel.FindStepByNumber(number);
GraphStepProxy proxy = new GraphStepProxy(step);
return proxy;
}
public GraphStepProxy FindStepByName(string name)
{
GraphStep step = GraphModel.FindStepByName(name);
GraphStepProxy proxy = new GraphStepProxy(step);
return proxy;
}
public GraphStepProxy GetStep(int id)
{
GraphStep step = GraphModel.GetStep(id);
GraphStepProxy proxy = new GraphStepProxy(step);
return proxy;
}
#endregion Step
#region Transition
public GraphTransitionProxy FindTransitionByNumber(int number)
{
GraphTransition transition = GraphModel.FindTransitionByNumber(number);
GraphTransitionProxy proxy = new GraphTransitionProxy(transition);
return proxy;
}
internal GraphTransitionProxy FindTransitionByName(string name)
{
GraphTransition transition = GraphModel.FindTransitionByName(name);
GraphTransitionProxy proxy = new GraphTransitionProxy(transition);
return proxy;
}
public GraphTransitionProxy GetTransition(int id)
{
GraphTransition transition = GraphModel.GetTransition(id);
GraphTransitionProxy proxy = new GraphTransitionProxy(transition);
return proxy;
}
#endregion Transition
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphJumpProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphJumpProxy
{
internal GraphJump GraphJump;
internal GraphJumpProxy(GraphJump jump)
{
GraphJump = jump;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/LogicalElementProxy.cs
using Siemens.Simatic.PlcLanguages.GraphEditor.Model.GraphElements;
namespace YZX.Tia.Proxies.Graph
{
public class LogicalElementProxy
{
internal LogicalElement le;
internal LogicalElementProxy(LogicalElement le)
{
this.le = le;
}
}
}<file_sep>/YZX.TIA/Proxies/DebugJobProxy.cs
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.PlcLanguages.TisServer;
namespace YZX.Tia.Proxies
{
public class DebugJobProxy
{
public DebugJob DebugJob;
public DebugJobProxy(DebugJob dj)
{
DebugJob = dj;
}
public ITisJob TisJob
{
get
{
return DebugJob.TisJob;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BLS7PlusBackupProxy.cs
using Siemens.Automation.DomainServices.LoadService;
using Reflection;
namespace YZX.Tia.Proxies
{
public class BLS7PlusBackupProxy
{
BLS7PlusBackup BLS7PlusBackup;
public BLS7PlusBackupProxy(object bl)
{
BLS7PlusBackup = bl as BLS7PlusBackup;
}
public BackupPlusCheckBeforeUploadProxy CreateInstanceCheckBeforeUpload()
{
BackupPlusCheckBeforeUpload upload = Reflector.RunInstanceMethodByName(BLS7PlusBackup,
"CreateInstanceCheckBeforeUpload", ReflectionWays.SystemReflection) as BackupPlusCheckBeforeUpload;
return new BackupPlusCheckBeforeUploadProxy(upload);
}
protected BackupPlusUploadProxy CreateInstanceUpload()
{
BackupPlusUpload upload = Reflector.RunInstanceMethodByName(BLS7PlusBackup,
"CreateInstanceUpload", ReflectionWays.SystemReflection) as BackupPlusUpload;
return new BackupPlusUploadProxy(upload);
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/SelectableUIElementWrapperProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class SelectableUIElementWrapperProxy:UIElementWrapperProxy
{
internal SelectableUIElementWrapper SelectableUIElementWrapper;
internal SelectableUIElementWrapperProxy(SelectableUIElementWrapper wrapper)
:base(wrapper)
{
SelectableUIElementWrapper = wrapper as SelectableUIElementWrapper;
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/BLS7ClassicBackupProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
using Reflection;
namespace YZX.Tia
{
public class BLS7ClassicBackupProxy
{
BLS7ClassicBackup BLS7ClassicBackup;
public BLS7ClassicBackupProxy(object bl)
{
BLS7ClassicBackup = bl as BLS7ClassicBackup;
}
public BackupClassicCheckBeforeUploadProxy CreateInstanceCheckBeforeUpload()
{
BackupClassicCheckBeforeUpload upload = Reflector.RunInstanceMethodByName(BLS7ClassicBackup,
"CreateInstanceCheckBeforeUpload", ReflectionWays.SystemReflection) as BackupClassicCheckBeforeUpload;
return new BackupClassicCheckBeforeUploadProxy(upload);
}
public BackupClassicUploadProxy CreateInstanceUpload()
{
BackupClassicUpload upload = Reflector.RunInstanceMethodByName(BLS7ClassicBackup,
"CreateInstanceUpload", ReflectionWays.SystemReflection) as BackupClassicUpload;
return new BackupClassicUploadProxy(upload);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/PrimaryProjectManagerProxy.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.ProjectManager;
using Siemens.Automation.UserProjectManagement.BL.PrimaryProject;
using Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject;
using YZX.Tia.Proxies.ProjectManager;
namespace YZX.Tia.Proxies
{
public class PrimaryProjectManagerProxy
{
internal IPrimaryProjectManager m_PrimaryProjectManager;
internal IPrimaryProjectUiWorkingContextManager IPrimaryProjectUiWorkingContextManager
{
get
{
return m_PrimaryProjectManager as IPrimaryProjectUiWorkingContextManager;
}
}
public PrimaryProjectManagerProxy Instance { get; private set; }
internal PrimaryProjectManagerProxy(IPrimaryProjectManager m_PrimaryProjectManager)
{
this.m_PrimaryProjectManager = m_PrimaryProjectManager;
m_PrimaryProjectManager.ProjectOpened += M_PrimaryProjectManager_ProjectOpened;
Instance = this;
}
private void M_PrimaryProjectManager_ProjectOpened(object sender, TiaPrimaryProjectOpenedEventArgs e)
{
this.ProjectOpened?.Invoke(sender,e);
}
public TiaProjectProxy PrimaryProject
{
get
{
return new TiaProjectProxy(m_PrimaryProjectManager.PrimaryProject);
}
}
public IWorkingContext UiPersistenceWorkingContext
{
get
{
return IPrimaryProjectUiWorkingContextManager.UiPersistenceWorkingContext;
}
}
public event EventHandler<EventArgs> ProjectOpened;
public bool OpenProjectReadOnly(string path, out object projectO, bool silent = false)
{
OpenProjectParams parameters = new OpenProjectParams(path);
parameters.Access = TiaProjectAccess.ReadOnly;
parameters.Silent = silent;
ITiaProject project;
bool returnB = m_PrimaryProjectManager.OpenProject(parameters, out project);
if (project != null)
{
projectO = new TiaProjectProxy(project);
}
else
{
projectO = null;
}
return returnB;
}
public bool OpenProjectReadWrite(string path, out object projectO,bool silent = false)
{
OpenProjectParams parameters = new OpenProjectParams(path);
parameters.Access = TiaProjectAccess.ReadWrite;
parameters.Silent = silent;
ITiaProject project;
bool returnB;
try
{
returnB = m_PrimaryProjectManager.OpenProject(parameters, out project);
if (project != null)
{
projectO = new TiaProjectProxy(project);
}
else
{
projectO = null;
}
return returnB;
}
catch(Exception ex)
{
Console.WriteLine(ex);
projectO = null;
return false;
}
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamSinecRegistryAccessX64Proxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess.Sinec;
namespace YZX.Tia.Proxies
{
public class OamSinecRegistryAccessX64Proxy
{
public static OamSinecRegistryAccessX64Proxy GetInstanceX64()
{
OamSinecRegistryAccess access = OamSinecRegistryAccessX64.GetInstanceX64();
return new OamSinecRegistryAccessX64Proxy(access);
}
OamSinecRegistryAccess OamSinecRegistryAccess;
public OamSinecRegistryAccessX64Proxy(IServiceProvider access)
{
OamSinecRegistryAccess = access as OamSinecRegistryAccess;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.Hwcn.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using YZX.Tia.Proxies;
using YZX.Tia.Extensions;
using YZX.Tia.Extensions.Hwcn;
namespace YZX.Tia
{
partial class TiaStarter
{
public Control ShowModuleState(ICoreObject cpu)
{
UIContextHolder = PrimaryProjectUiWorkingContextManagerProxy.IUIContextHolder;
ProjectUIContext = UIContextHolder.ProjectUIContext;
IWorkingContext workingContext = cpu.GetWorkingContext();
FrameGroupManager manager = ProjectUIContext.GetHwcnFrameGroupManager();
ICommandProcessor processor = workingContext.GetCommandProcessor();
ICommand command = processor.CreateCommand("Hwcn.Diagnostic.ShowModuleState", new object[1]
{
cpu
}, new NameObjectCollection());
command.Arguments.Add("DoeStartCategory", "DiagCategoryEventLog");
CommandResult result = manager.Execute(command);
if(result.ReturnCode == CommandReturnCodes.Handled)
{
object resultObject = result.ReturnValue;
List<IDoeInstanceAccess> does = manager.GetDoeInstances();
foreach(IDoeInstanceAccess doe in does)
{
DoeInstanceAccess DoeInstanceAccess = doe as DoeInstanceAccess;
DoeViewAccess viewAccess = DoeInstanceAccess.GetDoeViewAccess() as DoeViewAccess;
ICoreObject viewObject = doe.ViewObject;
IEditorFrame frame = doe.EditorFrame;
if(viewObject == cpu)
{
return frame.FrameControl;
}
}
}
return null;
}
public Control ShowLifelistNodeModuleState(ICoreObject cpu)
{
IWorkingContext LifelistNodeUIContext = cpu.GetUIWorkingContext();
IWorkingContext workingContext = cpu.GetWorkingContext();
FrameGroupManager manager = LifelistNodeUIContext.GetHwcnFrameGroupManager();
ICommandProcessor processor = workingContext.GetCommandProcessor();
ICommand command = processor.CreateCommand("Hwcn.Diagnostic.ShowModuleState", new object[1]
{
cpu
}, new NameObjectCollection());
command.Arguments.Add("DoeStartCategory", "DiagCategoryEventLog");
CommandResult result = manager.Execute(command);
if (result.ReturnCode == CommandReturnCodes.Handled)
{
object resultObject = result.ReturnValue;
List<IDoeInstanceAccess> does = manager.GetDoeInstances();
foreach (IDoeInstanceAccess doe in does)
{
DoeInstanceAccess DoeInstanceAccess = doe as DoeInstanceAccess;
DoeViewAccess viewAccess = DoeInstanceAccess.GetDoeViewAccess() as DoeViewAccess;
ICoreObject viewObject = doe.ViewObject;
IEditorFrame frame = doe.EditorFrame;
if (viewObject == cpu)
{
return frame.FrameControl;
}
}
}
return null;
}
}
}
<file_sep>/YZX.TIA/Proxies/CoreContextProxy.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.Private;
using Reflection;
namespace YZX.Tia.Proxies
{
public class CoreContextProxy
{
CoreContext CoreContext;
ICoreContext ICoreContext
{
get
{
return CoreContext;
}
}
IDlc IDlc
{
get
{
return CoreContext;
}
}
public CoreContextProxy(ICoreContext coreContext)
{
CoreContext = coreContext as CoreContext;
}
public CultureInfo DefaultLanguage
{
get
{
return ICoreContext.DefaultLanguage;
}
}
public ICorePersistence Persistence
{
get
{
return ICoreContext.Persistence;
}
}
public IWorkingContext WorkingContext
{
get
{
return IDlc.WorkingContext;
}
}
internal IList<ICoreObjectInternal> AllEnvironmentRootObjects
{
get
{
return Reflector.GetInstancePropertyByName(CoreContext,
"AllEnvironmentRootObjects",
ReflectionWays.SystemReflection)
as IList<ICoreObjectInternal>;
}
}
public DateTime GetTimestamp()
{
return ICoreContext.GetTimestamp();
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableStepProxy.cs
using Siemens.Automation.UI.Controls.WindowlessFramework;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
using Siemens.Simatic.PlcLanguages.GraphEditor.ActionList.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableStepProxy:DrawableBoxElementProxy
{
internal DrawableStep step;
internal DrawableStepProxy(DrawableStep step)
:base(step)
{
this.step = step;
}
public ActionListControl GetActionListControl()
{
if(step.ElementList.Count > 0)
{
DrawableLangModTogglerDSV dsv = step.ElementList[2] as DrawableLangModTogglerDSV;
if (dsv.ElementList.Count > 0)
{
UIElementWrapperForUIContainer container = dsv.ElementList[0] as UIElementWrapperForUIContainer;
UIElementWrapperForPalettes palettes = container.ElementList[0] as UIElementWrapperForPalettes;
UIElementWrapperForPalettesProxy palettesProxy = new UIElementWrapperForPalettesProxy(palettes);
LanguagePaletteBaseElement palette = palettesProxy.Palette;
UIControlWindowlessWrapper wrapper = palette.ChildControls[1] as UIControlWindowlessWrapper;
ActionListControl alc = wrapper.ChildControls[0] as ActionListControl;
return alc;
}
}
return null;
}
}
}<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.cs
using System;
using System.ComponentModel;
using System.Threading;
using System.Collections.Generic;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.FrameApplication.MetaData;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PLCMessaging;
using Reflection;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions
{
public static partial class IWorkingContextExtensions
{
public static ISynchronizeInvoke GetSynchronizeInvoke([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ISynchronizer>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer")
as ISynchronizeInvoke;
}
public static ISynchronizer GetSynchronizer([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ISynchronizer>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer");
}
public static Thread GetMainThread([NotNull] this IWorkingContext workingContext)
{
ISynchronizer syn = workingContext.GetSynchronizer();
return syn.MainThread;
}
internal static IMetaDataManager GetMetaDataManager([NotNull] this IWorkingContext workingContext)
{
return GetRequiredDlc<IMetaDataManager>(workingContext, "Siemens.Automation.FrameApplication.MetaData.MetaDataManager");
}
public static IEnumerable<WorkingContext> GetTopWorkingContexts()
{
return Reflector.RunStaticMethodByName(typeof(WorkingContext),
"GetTopWorkingContexts",
ReflectionWays.SystemReflection) as IEnumerable<WorkingContext>;
}
public static IWorkingContext GetRootWorkingContext(this IWorkingContext currentContext)
{
for (IWorkingContext parentWorkingContext = currentContext.ParentWorkingContext; parentWorkingContext != null; parentWorkingContext = currentContext.ParentWorkingContext)
currentContext = parentWorkingContext;
return currentContext;
}
public static IWorkingContext GetCommonWorkingContext(
this IWorkingContext workingContext1,
IWorkingContext workingContext2)
{
return Reflector.RunStaticMethodByName(typeof(WorkingContext),
"GetCommonWorkingContext",
ReflectionWays.SystemReflection,
workingContext1,
workingContext2) as IWorkingContext;
}
public static ConnectionServiceProvider GetConnectionService([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.ConnectionService") as ConnectionServiceProvider;
}
public static OnlineServiceProvider GetOnlineService([NotNull] this IWorkingContext workingContext)
{
IOnlineService ios = workingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService") as IOnlineService;
return ios.ToOnlineServiceProvider();
}
public static IOnlineCommandInvoke GetOnlineCommandInvoke([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService.OnlineCommandInvoke") as IOnlineCommandInvoke;
}
public static IIconService GetIconService([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetService("Siemens.Automation.CommonServices.IconService") as IIconService;
}
}
}<file_sep>/YZX.TIA/Extensions/Vat/VATViewerViewExtensions.cs
using Siemens.Automation.DomainServices.DomainGrid;
using Siemens.Simatic.PlcLanguages.VATViewer;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class VATViewerViewExtensions
{
public static DomainGrid GetDomainGrid(this VATViewerView vatViewerView)
{
return Reflector.GetInstanceFieldByName(vatViewerView, "m_DomainGrid",
ReflectionWays.SystemReflection)
as DomainGrid;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DetailedSequenceViewProxy.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using Siemens.Automation.UI.Controls.WindowlessFramework;
using Siemens.Automation.CommonServices.TextEditor;
using Siemens.Automation.CommonServices.TextEditor.View;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.GraphEditor;
using Siemens.Simatic.PlcLanguages.GraphEditor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.Overlays;
using Siemens.Simatic.PlcLanguages.GraphEditor.ActionList.View;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.Selection;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class DetailedSequenceViewProxy:AbstractGraphViewProxy
{
internal DetailedSequenceView view;
internal DetailedSequenceViewProxy(DetailedSequenceView view)
:base(view)
{
this.view = view;
}
public SequenceUIElementProxy SequenceUIElement
{
get
{
return new SequenceUIElementProxy(view.SequenceUIElement);
}
}
public HostElement HostElement
{
get
{
return Reflector.GetInstancePropertyByName(view, "HostElement",
ReflectionWays.SystemReflection) as HostElement;
}
}
public void TrackStep(int stepNumber, bool firstCallOfTrackActiveStep)
{
view.TrackStep(stepNumber, firstCallOfTrackActiveStep);
}
public List<IDebugBlock> GetVisibleSubControls()
{
return Reflector.RunInstanceMethodByName(view, "GetVisibleSubControls",
ReflectionWays.SystemReflection) as List<IDebugBlock>;
}
public void DisableGraphBlockInput()
{
view.SelectionManager.DelayedSelectionChanged += SelectionManager_DelayedSelectionChanged;
}
private void SelectionManager_DelayedSelectionChanged(object sender, EventArgs e)
{
DefaultSelectionManager manager = sender as DefaultSelectionManager;
var selectedItems = manager.SelectedItems;
if(selectedItems.Count > 0)
{
foreach(var item in selectedItems)
{
}
}
DisableGraphBlockInputInternal();
}
public void DisableGraphBlockInputInternal()
{
SequenceUIElement.SequenceUIElement.BackColor = Color.Yellow;
UIElementCollection children = HostElement.ChildUIElements;
List<OverlayBaseProxy> seqOverlayList = GetSequenceOverlay();
foreach (var overlay in seqOverlayList)
{
var steps = overlay.GetSteps();
foreach (var step in steps)
{
ActionListControl actions = step.GetActionListControl();
if (actions != null)
{
actions.BackColor = Color.Red;
actions.Enabled = false;
CmdDispatcher CmdDispatcher = actions.CmdDispatcher;
CmdDispatcher.MainCmdContainer.ClearCmdHandler();
var ActionListOverlays = actions.ActionListOverlays;
actions.ContextMenuProvider = null;
EditOverlay edit = actions.EditOverlay;
edit.BackColor = Color.Blue;
}
}
var transitions = overlay.GetTransitions();
foreach(var transition in transitions)
{
GraphFLGraphicEditor editor = transition.GetGraphFLGraphicEditor();
if(editor != null)
{
editor.Enabled = false;
editor.BackColor = Color.Yellow;
}
}
}
List<IDebugBlock> blocks = GetVisibleSubControls();
foreach (var child in view.Controls)
{
}
}
public List<OverlayBaseProxy> GetSequenceOverlay()
{
List<OverlayBaseProxy> list = new List<OverlayBaseProxy>();
if(OverlayManager == null)
{
return list;
}
foreach (var overlay in OverlayManager.OverlayList)
{
if (overlay.OverlayType == GraphEditorDefinitions.OverlayType.Sequence)
{
var proxy = new OverlayBaseProxy(overlay);
list.Add(proxy);
}
}
return list;
}
}
}<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/ConnectionParamsProxy.cs
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class ConnectionParamsProxy
{
internal ConnectionParams CP;
public ConnectionParamsProxy()
{
CP = new ConnectionParams();
}
public ICoreObject OnlineTarget
{
get
{
return CP.OnlineTarget;
}
set
{
CP.OnlineTarget = value;
}
}
public ICoreObject OfflineTarget
{
get
{
return CP.OfflineTarget;
}
set
{
CP.OfflineTarget = value;
}
}
public string ConnectionType
{
get
{
return CP.ConnectionType;
}
set
{
CP.ConnectionType = value;
}
}
public OnlineConnectionModes ConnectionMode
{
get
{
return CP.ConnectionMode;
}
set
{
CP.ConnectionMode = value;
}
}
public object ConfigurationData
{
get
{
return CP.ConfigurationData;
}
set
{
CP.ConfigurationData = value;
}
}
public object ConnectSpecificData
{
get
{
return CP.ConnectSpecificData;
}
set
{
CP.ConnectSpecificData = value;
}
}
public bool ThrowOnError
{
get
{
return CP.ThrowOnError;
}
set
{
CP.ThrowOnError = value;
}
}
public bool IsLifelistNode
{
get
{
return CP.IsLifelistNode;
}
set
{
CP.IsLifelistNode = value;
}
}
public int GeneralErrorCode
{
get
{
return CP.GeneralErrorCode;
}
set
{
CP.GeneralErrorCode = value;
}
}
public int FeedbackErrorService
{
get
{
return CP.FeedbackErrorService;
}
set
{
CP.FeedbackErrorService = value;
}
}
public int FeedbackErrorNumber
{
get
{
return CP.FeedbackErrorNumber;
}
set
{
CP.FeedbackErrorNumber = value;
}
}
public IOamAddress OnlineAddress
{
get
{
return CP.OnlineAddress;
}
set
{
CP.OnlineAddress = value;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableLanguageModuleProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements.DrawableLanguageModules;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableLanguageModuleProxy : UIElementWrapperProxy
{
internal DrawableLanguageModule DrawableLanguageModule;
internal DrawableLanguageModuleProxy(DrawableLanguageModule wrapper)
: base(wrapper)
{
DrawableLanguageModule = wrapper as DrawableLanguageModule;
}
}
}
<file_sep>/YZX.TIA/TiaStarter.AsyncOpenProject.cs
using Microsoft.Practices.Unity;
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public void AsyncOpenProject(string path)
{
SynchronizeInvoke.Invoke((Action)(() => this.OpenProjectSynchronized(path)), null);
}
private void OpenProjectSynchronized(string projectLocation)
{
try
{
ICommandProcessor commandProcessor = IDlcManagerExtension.Get<ICommandProcessor>(UnityContainerExtensions.Resolve<IDlcManager>(Ioc.Container, Array.Empty<ResolverOverride>()), null);
string id = "ProjectHandler.OpenProject";
ICommand command = commandProcessor.CreateCommand(id);
command.Arguments["ProjectPath"] = projectLocation;
ICommand cmd = command;
commandProcessor.Execute(cmd);
}
catch (Exception ex)
{
//this.Log.Exception(ex, "OpenProjectSynchronized");
throw;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.WorkingContext.cs
using System.ComponentModel;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Reflection;
namespace YZX.Tia.Extensions
{
public static partial class ICoreObjectExtensions
{
public static WorkingContext FindWorkingContext(this ICoreObject ico)
{
List<ICoreObject> icoL = new List<ICoreObject>() { ico };
return WorkingContext.FindWorkingContextForGivenObjects(icoL) as WorkingContext;
}
}
}
<file_sep>/YZX.TIA/Proxies/PrimaryProjectUiWorkingContextManagerProxy.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject;
using Siemens.Automation.UserProjectManagement.BL.PrimaryProject;
using Reflection;
namespace YZX.Tia.Proxies
{
public class PrimaryProjectUiWorkingContextManagerProxy
{
internal PrimaryProjectUiWorkingContextManager manager;
internal IPrimaryProjectUiWorkingContextManager IManager
{
get
{
return manager as IPrimaryProjectUiWorkingContextManager;
}
}
public PrimaryProjectManagerProxy PrimaryProjectManager
{
get
{
IPrimaryProjectManager m_PrimaryProjectManager =
Reflector.GetInstanceFieldByName(manager, "m_PrimaryProjectManager",
ReflectionWays.SystemReflection)
as IPrimaryProjectManager;
return new PrimaryProjectManagerProxy(m_PrimaryProjectManager);
}
}
public IUIContextHolder IUIContextHolder
{
get
{
return Reflector.GetInstanceFieldByName(manager,
"m_PrimaryProjectUiContextHolder",
ReflectionWays.SystemReflection)
as IUIContextHolder;
}
}
internal PrimaryProjectUiWorkingContextManagerProxy(PrimaryProjectUiWorkingContextManager manager)
{
this.manager = manager;
}
public IWorkingContext UiPersistenceWorkingContext
{
get
{
return IManager.UiPersistenceWorkingContext;
}
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Extensions/Diagnostic/FrameGroupManagerExtensions.cs
using System.Collections.Generic;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
namespace YZX.Tia.Extensions.Diagnostic
{
public static class FrameGroupManagerExtensions
{
public static List<IDoeInstanceAccess> GetDoeInstances(this FrameGroupManager manager)
{
return Reflector.GetInstanceFieldByName(manager, "m_DoeInstances", ReflectionWays.SystemReflection)
as List<IDoeInstanceAccess>;
}
public static string GetViewId(this FrameGroupManager manager)
{
return Reflector.GetInstanceFieldByName(manager, "m_ViewId", ReflectionWays.SystemReflection)
as string;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.CommandProcessor.cs
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.UI.GoOnline;
namespace YZX.Tia
{
partial class TiaStarter
{
public ICommandProcessor CommandProcessor
{
get
{
return m_BusinessLogicApplicationContext.DlcManager.Load("Siemens.Automation.CommonServices.CommandProcessor") as ICommandProcessor;
}
}
public ICommand CreateCommand(string id)
{
ICommand command = CommandProcessor.CreateCommand(id);
//command.WorkingContext = m_BusinessLogicApplicationContext;
command.WorkingContext = projectViewWorkingContext;
return command;
}
#region ExtendedGoOnline
public CommandResult ExtendedGoOnline(ICoreObject cpu)
{
GoOnlineCommands GoOnlineCommands = new GoOnlineCommands();
IDlc dlc_GoOnlineCommands = GoOnlineCommands as IDlc;
dlc_GoOnlineCommands.Attach(PersistenceWorkingContext);
ICommandTarget ict_GoOnlineCommands = GoOnlineCommands as ICommandTarget;
ICommand command = CommandProcessor.CreateCommand("Application.ExtendedGoOnline", new object[1]
{
cpu
}, new NameObjectCollection());
command.WorkingContext = projectWorkingContext;
return ict_GoOnlineCommands.Execute(command);
}
#endregion
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Proxies/Diagnostic/DoeViewAccessProxy.cs
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
namespace YZX.Tia.Proxies.Diagnostic
{
public class DoeViewAccessProxy
{
internal DoeViewAccess DoeViewAccess;
public DoeViewAccessProxy(IDoeViewAccess viewAccess)
{
DoeViewAccess = viewAccess as DoeViewAccess;
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Extensions/Diagnostic/NotificationServiceExtensions.cs
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.Diagnostic
{
public static class NotificationServiceExtensions
{
public static Dictionary<ICoreObject, IDiagNotification> GetDeviceHostObserverManagers(this NotificationService service)
{
return Reflector.GetInstanceFieldByName(service,
"m_DeviceHostObserverManagers",
ReflectionWays.SystemReflection) as Dictionary<ICoreObject, IDiagNotification>;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/MenuServiceImplementationProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Menu;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class MenuServiceImplementationProxy
{
internal MenuService MenuService;
internal MenuServiceImplementation MenuServiceImplementation;
public MenuServiceImplementationProxy(IDlc dlc)
{
MenuService = dlc as MenuService;
if(MenuService != null)
{
MenuServiceImplementation = Reflector.GetInstanceFieldByName(MenuService,
"m_MenuServiceImplementation",
ReflectionWays.SystemReflection)
as MenuServiceImplementation;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/OnlineService/OnlineSessionExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OMSPlus.Managed;
using Reflection;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions.OnlineService
{
public static class OnlineSessionExtensions
{
/// <summary>
/// 切换仿真状态
/// from OamPlcSimCtl
/// </summary>
/// <param name="simulated"></param>
public static void SwitchBoardsToSimulationState(this OnlineSession session,bool simulated)
{
List<IOamLocalBoard> boards = session.Boards;
foreach (IOamLocalBoard oamLocalBoard1 in boards)
{
OamLocalBoardBase oamLocalBoardBase = oamLocalBoard1 as OamLocalBoardBase;
if (oamLocalBoardBase != null)
{
OamLocalBoard oamLocalBoard2 = oamLocalBoard1 as OamLocalBoard;
if (oamLocalBoard2 != null)
{
bool isPlcSimulation = oamLocalBoard2.IsPlcSimulation();
oamLocalBoardBase.ChangeSimulated(simulated, isPlcSimulation);
}
else
{
oamLocalBoardBase.ChangeSimulated(simulated, false);
}
}
}
}
public static ClientSessions GetClientSessions(this OnlineSession session)
{
return session.SessionContainer;
}
public static OamPlcSimCtlProxy GetPlcSimController(this OnlineSession session)
{
OamPlcSimCtl simCtl = session.PlcSimController as OamPlcSimCtl;
return new OamPlcSimCtlProxy(simCtl);
}
public static List<OamLocalBoardBaseProxy> GetBoardProxies(this OnlineSession session)
{
IList<IOamLocalBoard> boards = session.Boards;
List<OamLocalBoardBaseProxy> boardproxies = new List<OamLocalBoardBaseProxy>();
foreach (IOamLocalBoard board in boards)
{
if (board.IsOamComBoard())
{
OamComBoardProxy proxy = new OamComBoardProxy(board);
boardproxies.Add(proxy);
}
if (board.IsOamCustomBoard())
{
}
if (board.IsOamLocalBoard())
{
OamLocalBoardProxy proxy = new OamLocalBoardProxy(board);
boardproxies.Add(proxy);
}
}
return boardproxies;
}
public static OamDeviceWatcherProxy GetOamDeviceWatcherProxy(this OnlineSession session)
{
OamDeviceWatcher watcher = Reflector.GetInstanceFieldByName(session,
"OamDeviceWatcher",
ReflectionWays.SystemReflection)
as OamDeviceWatcher;
OamDeviceWatcherProxy proxy = new OamDeviceWatcherProxy(watcher);
return proxy;
}
public static OamEthernetConnectionsWatcherProxy GetOamEthernetConnectionsWatcherProxy(this OnlineSession session)
{
OamEthernetConnectionsWatcher watcher = Reflector.GetInstanceFieldByName(session,
"m_Ethwatch",
ReflectionWays.SystemReflection)
as OamEthernetConnectionsWatcher;
OamEthernetConnectionsWatcherProxy proxy = new OamEthernetConnectionsWatcherProxy(watcher);
return proxy;
}
}
}
<file_sep>/YZX.TIA/Extensions/Vat/VarTableViewExtensions.cs
using JetBrains.Annotations;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.VatService.Exceptions;
using Siemens.Simatic.PlcLanguages.VatService.Views;
namespace YZX.Tia.Extensions
{
public static class VarTableViewExtensions
{
internal static IWorkingContext GetViewContextTest([NotNull] this VarTableView IvarTableView)
{
VarTableView varTableView = IvarTableView as VarTableView;
if (varTableView.DomainGrid == null)
throw new VatServiceInvalidOperationException("The project view context is not available for the given view instance.");
IWorkingContext workingContext = varTableView.DomainGrid.ViewFrame.WorkingContext;
if (workingContext.WorkingContextEnvironment != WorkingContextEnvironment.Project || !workingContext.IsViewContext || !(workingContext.Scope == "Project"))
workingContext = varTableView.DomainGrid.GetService(typeof(IWorkingContext)) as IWorkingContext;
if (workingContext.WorkingContextEnvironment != WorkingContextEnvironment.Project || !workingContext.IsViewContext || !(workingContext.Scope == "Project"))
throw new VatServiceInvalidOperationException("The project view context is not available for the given view instance.");
return workingContext;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.Sychronizer.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.DomainServices;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public ISynchronizer Synchronizer
{
get
{
return m_ViewApplicationContext.GetRequiredDlc<ISynchronizer>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer");
}
}
public ISynchronizeInvoke SynchronizeInvoke
{
get
{
return Synchronizer as ISynchronizeInvoke;
}
}
public static object RunInSynchronizer(ISynchronizeInvoke Synchronizer, Delegate method, params object[] args)
{
return UnifiedSynchronizerAccess.Invoke(Synchronizer, method, args).InvokeResult;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/LoadAttributesProxy.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Automation.CommonServices.SettingsService;
namespace YZX.Tia.Proxies.LoadService
{
public static class LoadAttributesProxy
{
public static void SetAddressChanged(IWorkingContext workingContext, ISettingsService settingsService, ICoreObject device)
{
LoadAttributes.SetAddressChanged(workingContext, settingsService, device);
}
public static void SetDisplayDeviceAsStation(ICoreObject device, bool displayDeviceAsStation)
{
LoadAttributes.SetDisplayDeviceAsStation(device, displayDeviceAsStation);
}
public static bool GetDisplayDeviceAsStation(ICoreObject device)
{
return LoadAttributes.GetDisplayDeviceAsStation(device);
}
public static void SetLoadPosition(ICoreObject deviceOrTarget, int position)
{
LoadAttributes.SetLoadPosition(deviceOrTarget, position);
}
public static int GetLoadPosition(ICoreObject deviceOrTarget)
{
return LoadAttributes.GetLoadPosition(deviceOrTarget);
}
public static void SetHwSwDownloadRequired(ICoreObject target)
{
LoadAttributes.SetHwSwDownloadRequired(target);
}
public static void SetHwDownloadRequired(ICoreObject target)
{
LoadAttributes.SetHwDownloadRequired(target);
}
public static void SetSwDownloadRequired(ICoreObject target)
{
LoadAttributes.SetSwDownloadRequired(target);
}
public static void ResetAllAttributesHwAndOrSwDownloadRequired(ICoreObject target)
{
LoadAttributes.ResetAllAttributesHwAndOrSwDownloadRequired(target);
}
public static bool IsAttributeSetHwSwDownloadRequired(ICoreObject target)
{
return LoadAttributes.IsAttributeSetHwSwDownloadRequired(target);
}
public static bool IsAttributeSetHwDownloadRequired(ICoreObject target)
{
return LoadAttributes.IsAttributeSetHwDownloadRequired(target);
}
public static bool IsAttributeSetSwDownloadRequired(ICoreObject target)
{
return LoadAttributes.IsAttributeSetSwDownloadRequired(target);
}
public static bool SetDisplaySubHeadlineForDownloadTarget(ICoreObject device)
{
return LoadAttributes.SetDisplaySubHeadlineForDownloadTarget(device);
}
public static bool ResetDisplaySubHeadlineForDownloadTarget(ICoreObject device)
{
return LoadAttributes.ResetDisplaySubHeadlineForDownloadTarget(device);
}
public static bool DisplaySubHeadlineForDownloadTarget(ICoreObject device)
{
return LoadAttributes.DisplaySubHeadlineForDownloadTarget(device);
}
public static bool SetPrimaryDownloadTarget(ICoreObject target)
{
return LoadAttributes.SetPrimaryDownloadTarget(target);
}
public static bool ResetPrimaryDownloadTarget(ICoreObject target)
{
return LoadAttributes.ResetPrimaryDownloadTarget(target);
}
public static bool IsPrimaryDownloadTarget(ICoreObject target)
{
return LoadAttributes.IsPrimaryDownloadTarget(target);
}
public static bool SetCreateSnapshotOnCompile(ICoreObject target)
{
return LoadAttributes.IsSetCreateSnapshotOnCompile(target);
}
public static bool ResetCreateSnapshotOnCompile(ICoreObject target)
{
return LoadAttributes.ResetCreateSnapshotOnCompile(target);
}
public static bool IsSetCreateSnapshotOnCompile(ICoreObject target)
{
return LoadAttributes.IsSetCreateSnapshotOnCompile(target);
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/MainControlContainerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.UI.Controls;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Siemens.Simatic.PlcLanguages.GraphEditor.View;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class MainControlContainerProxy
{
internal MainControlContainer mainControlContainer;
public MainControlContainerProxy(UserControl mainControlContainer)
{
this.mainControlContainer = mainControlContainer as MainControlContainer;
}
public AbstractGraphViewProxy CurrentView
{
get
{
return new AbstractGraphViewProxy(mainControlContainer.CurrentView);
}
}
public GraphBlockEditorControlProxy GraphBlockEditorControl
{
get
{
GraphBlockEditorControl control = Reflector.GetInstancePropertyByName(mainControlContainer,
"GraphBlockEditorControl",
ReflectionWays.SystemReflection) as GraphBlockEditorControl;
return new GraphBlockEditorControlProxy(control);
}
}
public List<IUIControl> GetChildUIControls()
{
return mainControlContainer.GetChildUIControls();
}
public List<DetailedSequenceViewProxy> GetDetailedSequenceView()
{
List<DetailedSequenceViewProxy> list = new List<DetailedSequenceViewProxy>();
foreach (var child in mainControlContainer.Controls)
{
if(child is DetailedSequenceView)
{
DetailedSequenceView view = child as DetailedSequenceView;
DetailedSequenceViewProxy proxy = new DetailedSequenceViewProxy(view);
list.Add(proxy);
}
}
return list;
}
}
}
<file_sep>/YZX.TIA/Extensions/Tis/TisPlusServerExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.TisPlusServer;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class TisPlusServerExtensions
{
public static void ReplaceTracer(this Server server)
{
ConsoleTrace ct = new ConsoleTrace();
TisLogger tl = new TisLogger(ct);
Reflector.SetInstanceFieldByName(server, "m_tisTracer",
tl, ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/FrameBaseProxy.cs
using System.Windows.Forms;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class FrameBaseProxy
{
FrameBase FrameBase;
public IFrame Frame
{
get
{
return FrameBase;
}
}
IFrameInternal IFrameInternal
{
get
{
return FrameBase as IFrameInternal;
}
}
public static FrameBaseProxy ToProxy(IFrame frame)
{
if(frame is HierarchyFrame)
{
return HierarchyFrameProxy.ToProxy(frame);
}
if(frame is ViewFrame)
{
return ViewFrameProxy.ToProxy(frame);
}
return new FrameBaseProxy(frame);
}
public FrameBaseProxy(IFrame frame)
{
FrameBase = frame as FrameBase;
}
public bool IsClosing
{
get
{
return FrameBase.IsClosing;
}
}
public FrameBackground Background
{
get
{
return FrameBase.Background;
}
}
public DockStyle Dock
{
get
{
return IFrameInternal.Dock;
}
set
{
IFrameInternal.Dock = value;
}
}
public WindowManagerProxy WindowManagerProxy
{
get
{
var manager = Reflector.GetInstancePropertyByName(FrameBase,
"",
ReflectionWays.SystemReflection)
as IWindowManagerInternal;
WindowManagerProxy proxy = new WindowManagerProxy(manager);
return proxy;
}
}
public override string ToString()
{
return string.Format("{0} : {1}", FrameBase.GetType(), FrameBase.InstanceName);
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Proxies/Archiving/PackagingImplementationBaseProxy.cs
using System;
using System.IO;
using System.Collections.Generic;
using Siemens.Automation.Basics.PackagingService;
using Siemens.Automation.Utilities.PackagingService;
using Siemens.Automation.Archiving;
using Siemens.Automation.Utilities.IO;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.Archiving
{
public class PackagingImplementationBaseProxy: IDisposable
{
public PackagingImplementationBase PackagingImplementationBase;
public PackagingImplementationBaseProxy(string path,bool ForWriting= false)
{
var parameter = new PackagingParameterBase();
if (ForWriting)
{
parameter.ForWriting = true;
PackagingImplementationBase = new PackagingImplementationBase(path, parameter, null);
}
else
{
PackagingImplementationBase = new PackagingImplementationBase(path, parameter, null);
}
}
public string PackageFilePath
{
get
{
return PackagingImplementationBase.PackageFilePath;
}
}
public string PackageFileDirectory
{
get
{
return Path.GetDirectoryName(PackageFilePath);
}
}
public IDirectory Package
{
get
{
return Reflector.GetInstanceFieldByName(PackagingImplementationBase, "m_Package",
ReflectionWays.SystemReflection)
as IDirectory;
}
}
private ZipExtractorProxy zipExtractor;
public ZipExtractorProxy ZipExtractor
{
get
{
if(zipExtractor == null)
{
zipExtractor = new ZipExtractorProxy(Package);
}
return zipExtractor;
}
}
public bool Disposed
{
get
{
return (bool)Reflector.GetInstanceFieldByName(PackagingImplementationBase, "m_Disposed",
ReflectionWays.SystemReflection);
}
}
IDictionary<string, object> GetFilesWithFileInfo()
{
if (Disposed)
throw new InvalidOperationException("MetaPackageReader is closed");
var fileInfos = ZipExtractor.GetFileInfos();
return fileInfos;
}
public IList<string> GetFiles()
{
return PackagingImplementationBase.GetFiles();
}
public UtilityStream OpenStreamReferencePackageWithPosition(string entryName, object FileInfo)
{
return Reflector.RunInstanceMethodByName(PackagingImplementationBase,
"OpenStreamReferencePackageWithPosition",
ReflectionWays.SystemReflection,
entryName,FileInfo
) as UtilityStream;
}
public bool InExclusionList(
string filename,
List<string> ExclusionList = null)
{
if(ExclusionList == null)
{
return false;
}
string name = Path.GetFileNameWithoutExtension(filename);
foreach(var Exclusion in ExclusionList)
{
if (name.EndsWith(Exclusion))
{
return true;
}
}
return false;
}
public void Unpack(
string SaveDirectory = "",
List<string> ExclusionList = null )
{
var fileinfos = GetFilesWithFileInfo();
var filesNames = GetFiles();
var files = ZipExtractor.GetFiles();
foreach(var f in filesNames)
{
var fileinfo = fileinfos[f];
var us = OpenStreamReferencePackageWithPosition(f, fileinfo);
string path;
if (SaveDirectory == "")
{
path = Path.Combine(PackageFileDirectory, f);
}
else
{
path = Path.Combine(SaveDirectory, f);
}
var Excluded = InExclusionList(f, ExclusionList);
if (Excluded)
{
Console.WriteLine("{0} InExclusionList",f);
}
else
{
Console.WriteLine(f);
StreamWriter sw = new StreamWriter(path);
us.CopyTo(sw.BaseStream);
sw.Flush();
sw.Close();
}
}
}
public void AddFile(string filename, Stream stream)
{
PackagingImplementationBase.AddFile(filename, stream);
}
public void Save(string newFilePath)
{
var StreamBasedArchiveInfo = CreateArchiveInfo();
StreamWriter sw = new StreamWriter(newFilePath);
var us = StreamBasedArchiveInfo.Stream;
us.Seek(0,SeekOrigin.Begin);
us.CopyTo(sw.BaseStream);
sw.Flush();
sw.Close();
}
public StreamBasedArchiveInfo CreateArchiveInfo()
{
var ArchiveInfo = Reflector.RunInstanceMethodByName(PackagingImplementationBase,
"CreateArchiveInfo",
ReflectionWays.SystemReflection
) as ArchiveInfo;
return ArchiveInfo as StreamBasedArchiveInfo;
}
#region IDisposable Support
private bool disposedValue = false; // 要检测冗余调用
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: 释放托管状态(托管对象)。
}
// TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// TODO: 将大型字段设置为 null。
disposedValue = true;
}
}
// TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
// ~PackagingImplementationBaseProxy()
// {
// // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
// Dispose(false);
// }
// 添加此代码以正确实现可处置模式。
public void Dispose()
{
((IDisposable)PackagingImplementationBase).Dispose();
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
// GC.SuppressFinalize(this);
}
#endregion
}
}
<file_sep>/LadderViewer/PLForm.cs
using System;
using System.Drawing;
using System.Threading;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Windows.Threading;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.UI.Controls.WindowlessFramework;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Controls.TagComments;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Reflection;
using YZX.Tia;
using YZX.Tia.Extensions;
using YZX.Tia.Extensions.Ladder;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.Ladder;
using YZX.Tia.Forms;
using YZX.Tia.Proxies.Graph;
namespace VatViewer
{
public partial class Form1 : TiaForm
{
string path;
public Form1()
{
path = @"S:\216889\216889-1500-1113\216889-1500-1113.ap14";
TiaStarter.SetForm(this);
Thread = Thread.CurrentThread;
InitializeComponent();
Load += Form1_Load;
SizeChanged += Form1_SizeChanged;
//AfterSychronizer();
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
if(gbec != null)
{
gbec.Size = new Size(Size.Width - 20, Size.Height - 40);
}
if(ModuleState != null)
{
ModuleState.Size = new Size(Size.Width - 20, Size.Height - 40);
}
}
TiaProjectProxy projectProxy;
public void OpenProject()
{
Program.app.PrimaryProjectManagerProxy.ProjectOpened += PrimaryProjectManagerProxy_ProjectOpened;
var proxy = Program.app.TiaProjectManagerProxy;
object project = null;
//proxy.OpenProjectReadWrite(path, out project);
Program.app.PrimaryProjectManagerProxy.OpenProjectReadWrite(path, out project);
}
private void PrimaryProjectManagerProxy_ProjectOpened(object sender, EventArgs e)
{
projectProxy = Program.app.PrimaryProjectManagerProxy.PrimaryProject;
projectProxy.WorkingContext.AutoLoadDlcs();
LoadOB1();
//TestDiagBufferDialog();
//OpenGraph();
OpenLadder();
}
private void OpenLadder()
{
this.gbec = Program.app.GetBlockEditor(pl) ;
pLBlockEditorControlElementProxy =
new PLBlockEditorControlElementProxy(this.gbec);
OnlineManagerBase plOnlineManager = pLBlockEditorControlElementProxy.PLBlockEditorLogic.OnlineManager;
plOnlineManager.GoOnline();
plOnlineManager.StartProgramStatus();
Controls.Add(this.gbec);
this.gbec.DisablePLBlockInput();
}
private void OpenGraph()
{
this.gbec = Program.app.GetBlockEditor(graph);
GraphBlockEditorControlProxy pLBlockEditorControlElementProxy =
new GraphBlockEditorControlProxy(this.gbec);
//pLBlockEditorControlElementProxy.BasicDrawSettings.StepBackground = Brushes.DarkBlue;
//Font stepNameFont = new Font("Consolas", pLBlockEditorControlElementProxy.BasicDrawSettings.StepNameFont.Size);
//pLBlockEditorControlElementProxy.BasicDrawSettings.StepNameFont = stepNameFont;
OnlineManagerBase plOnlineManager = pLBlockEditorControlElementProxy.GraphBlockEditorLogic.OnlineManager;
plOnlineManager.GoOnline();
plOnlineManager.StartProgramStatus();
List<IUIControl> children = pLBlockEditorControlElementProxy.GetChildUIControls();
Controls.Add(this.gbec);
var cs = this.gbec.Controls;
this.gbec.DisableGraphBlockInput();
}
Control ModuleState;
public void TestDiagBufferDialog()
{
ModuleState = Program.app.ShowModuleState(cpu);
Controls.Add(ModuleState);
}
PLBlockEditorControlElementProxy pLBlockEditorControlElementProxy;
public void LoadOB1()
{
cpu = projectProxy.FindCPU("216889CPU");
pl = projectProxy.BlockServiceProxy.FindBlockByAddress(cpu, BlockType.FC, 2012)[0];
graph = projectProxy.BlockServiceProxy.FindBlockByAddress(cpu, BlockType.FB, 2010)[0];
}
ICoreObject pl;
ICoreObject graph;
public void BeforeStartSynchronizer()
{
OpenProject();
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Form1_Load");
//TestWindowManager();
BeforeStartSynchronizer();
}
Thread Thread;
Dispatcher Dispatcher;
static ICoreObject cpu;
private void WorkingContext_ServiceAddedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("GBEC WorkingContext_ServiceAddedEvent {0} {1}", e.ServiceType, e.ServiceCreatorType);
}
}
}
<file_sep>/YZX.TIA/Proxies/LoadService/Upload/MainUploadServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class MainUploadServiceProxy
{
MainUploadService MainUploadService;
public MainUploadServiceProxy(IWorkingContext workingContext)
{
MainUploadService = new MainUploadService(workingContext);
}
public MainUploadServiceProxy(object mus)
{
MainUploadService = mus as MainUploadService;
}
public ILoadConnection LoadConnection
{
get
{
return MainUploadService.LoadConnection;
}
}
public int ErrorCount
{
get
{
return MainUploadService.ErrorCount;
}
}
public int WarningCount
{
get
{
return MainUploadService.WarningCount;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/SequenceUIElementProxy.cs
using Siemens.Automation.UI.Controls.WindowlessFramework;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.UIElements;
namespace YZX.Tia.Proxies.Graph
{
public class SequenceUIElementProxy
{
internal SequenceUIElement SequenceUIElement;
public SequenceUIElementProxy(UIElement sequenceUIElement)
{
this.SequenceUIElement = sequenceUIElement as SequenceUIElement;
}
}
}<file_sep>/YZX.TIA/Proxies/Graph/DrawableBoxElementProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableBoxElementProxy : DrawableElementProxy
{
internal DrawableBoxElement box;
internal DrawableBoxElementProxy(DrawableBoxElement box)
:base(box)
{
this.box = box;
}
}
}
<file_sep>/YZX.TIA/Extensions/IDlcExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Simatic.HwConfiguration.Basics.Basics;
namespace YZX.Tia.Extensions
{
public static class IDlcExtensions
{
public static ConnectionServiceProvider GetConnectionService([NotNull] this IDlcManager manager)
{
return manager.Load("Siemens.Automation.DomainServices.ConnectionService") as ConnectionServiceProvider;
}
}
}
<file_sep>/YZX.TIA/Proxies/EthernetDiscoverNodeHelperProxy.cs
using System;
using System.Net;
using Siemens.Automation.DomainServices;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public static class EthernetDiscoverNodeHelperProxy
{
public static bool GetVendorAndDeviceFromOam(INode oamNode, out int vendor, out int deviceID)
{
return EthernetDiscoverNodeHelper.GetVendorAndDeviceFromOam(oamNode, out vendor, out deviceID);
}
public static bool GetOemVendorAndDeviceFromOam(INode oamNode, out int vendor, out int deviceID)
{
return EthernetDiscoverNodeHelper.GetOemVendorAndDeviceFromOam(oamNode, out vendor, out deviceID);
}
public static bool SupportsIpAddress(INode oamNode)
{
return EthernetDiscoverNodeHelper.SupportsIpAddress(oamNode);
}
public static IPAddress GetIpAddress(INode oamNode)
{
return EthernetDiscoverNodeHelper.GetIpAddress(oamNode);
}
public static IPAddress GetSubnetMask(INode oamNode)
{
return EthernetDiscoverNodeHelper.GetSubnetMask(oamNode);
}
public static DhcpParameter GetDhcpParameter(INode oamNode)
{
return EthernetDiscoverNodeHelper.GetDhcpParameter(oamNode);
}
public static int UpdateStationParams(INode oamNode, bool forceRead)
{
return EthernetDiscoverNodeHelper.UpdateStationParams(oamNode, forceRead);
}
public static IOamMacAddress GetMacAddressFromEthernetDiscoverNode(INode oamNode)
{
return EthernetDiscoverNodeHelper.GetMacAddressFromEthernetDiscoverNode(oamNode);
}
public static DhcpParameter FillDhcpParameter(DhcpParameter dhcpParameter, IOamDhcpAddress dhcpAddress)
{
if ((int)dhcpAddress.OptionCode1 != 61)
return null;
if (dhcpAddress.OptionValues.Length == 1)
{
switch (dhcpAddress.OptionValues[0])
{
case 0:
dhcpParameter.DhcpMode = DhcpOption.DhcpUseNameOfStation;
break;
case 1:
dhcpParameter.DhcpMode = DhcpOption.DhcpUseMacAddress;
break;
default:
dhcpParameter = null;
break;
}
}
else if (dhcpAddress.OptionValues.Length > 1)
{
if (dhcpAddress.OptionValues[0] != 0)
{
dhcpParameter = null;
}
else
{
dhcpParameter.DhcpMode = DhcpOption.DhcpUserDefinedClientId;
int length = dhcpAddress.OptionValues.Length - 1;
byte[] numArray = new byte[length];
Array.Copy(dhcpAddress.OptionValues, 1, numArray, 0, length);
dhcpParameter.UserClientId = numArray;
}
}
else
dhcpParameter = null;
return dhcpParameter;
}
public static void GetStandardVendorAndDevice(IEthernetDiscoverNode discoverNode, out int vendor, out int deviceID)
{
vendor = discoverNode.DetailedTypeOfStationData[0] << 8 | discoverNode.DetailedTypeOfStationData[1];
deviceID = discoverNode.DetailedTypeOfStationData[2] << 8 | discoverNode.DetailedTypeOfStationData[3];
}
private static bool GetOemVendorAndDevice(IEthernetDiscoverNode discoverNode, out int vendor, out int deviceID)
{
return ReadOemValues(GetOemDeviceIdDataSet(discoverNode), out vendor, out deviceID);
}
public static IOamIeDataset GetOemDeviceIdDataSet(IEthernetDiscoverNode discoverNode)
{
byte[] buffer = new byte[32];
IOamMacAddress macAddress = GetMacAddress(discoverNode);
return (discoverNode.Configuration.Network as IOamNetworkIe).Dataset.Create(2, 8, macAddress, buffer, true);
}
public static IOamMacAddress GetMacAddress(IEthernetDiscoverNode discoverNode)
{
return (discoverNode.Address as IEthernetDiscoverAddress).RemoteStationAddress;
}
public static bool ReadOemValues(IOamIeDataset oemDataset, out int vendor, out int deviceID)
{
vendor = 0;
deviceID = 0;
if (oemDataset.Read() != 0 || oemDataset.ReadBytes < 3L)
return false;
byte[] record = oemDataset.Record;
vendor = (record[0] << 8) + record[1];
deviceID = (record[2] << 8) + record[3];
return true;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/ProjectNavigatorFrameProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Automation.FrameApplication;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ProjectNavigatorFrameProxy
{
ProjectNavigatorFrame ProjectNavigatorFrame;
public ProjectNavigatorFrameProxy(IFrame frame)
{
ProjectNavigatorFrame = frame as ProjectNavigatorFrame;
}
public bool Sliding
{
get
{
return ProjectNavigatorFrame.Sliding;
}
set
{
ProjectNavigatorFrame.Sliding = value;
}
}
internal ProjectNavigatorStateManager GetProjectNavigatorStateManager()
{
return ProjectNavigatorFrame.GetService(typeof(ProjectNavigatorStateManager)) as ProjectNavigatorStateManager;
}
public ProjectNavigatorStateManagerProxy GetProjectNavigatorStateManagerProxy()
{
var manager = GetProjectNavigatorStateManager();
var proxy = new ProjectNavigatorStateManagerProxy(manager);
return proxy;
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Extensions/OnlineInterface/IOamLocalBoardExtensions.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Extensions.OnlineInterface
{
public static class IOamLocalBoardExtensions
{
public static bool IsOamLocalBoard(this IOamLocalBoard board)
{
OamLocalBoard oamLocalBoard = board as OamLocalBoard;
return oamLocalBoard != null;
}
public static bool IsOamComBoard(this IOamLocalBoard board)
{
OamComBoard oamComBoard = board as OamComBoard;
return oamComBoard != null;
}
public static bool IsOamCustomBoard(this IOamLocalBoard board)
{
OamCustomBoard oamCustomBoard = board as OamCustomBoard;
return oamCustomBoard != null;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/OnlineService/IOnlineServiceExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.OnlineService
{
public static class IOnlineServiceExtensions
{
public static OnlineServiceProvider ToOnlineServiceProvider(this IOnlineService ios)
{
IOnlineService rios = Reflector.GetInstanceFieldByName(ios, "m_RealOnlineService", ReflectionWays.SystemReflection) as IOnlineService;
OnlineServiceProvider real = rios as OnlineServiceProvider;
return real;
}
public static OnlineServiceProvider GetOnlineService(this IWorkingContext workingContext)
{
IOnlineService ios = workingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService") as IOnlineService;
return ios.ToOnlineServiceProvider();
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/StatusBarProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.UI.Controls;
using Siemens.Automation.FrameApplication.StatusBar;
using Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class StatusBarProxy
{
internal StatusBarDlc StatusBarDlc;
internal StatusBarControl StatusBarControl;
public UserControl UserControl
{
get
{
return StatusBarControl;
}
}
public StatusBarProxy(IDlc dlc)
{
StatusBarDlc = dlc as StatusBarDlc;
if(StatusBarDlc != null)
{
StatusBarControl = Reflector.GetInstanceFieldByName(StatusBarDlc,
"m_StatusBarControl",
ReflectionWays.SystemReflection) as StatusBarControl;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/RemoteFileAccessExtensions.cs
using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Collections.Generic;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.DomainServices.DirectoryMappingService;
using Siemens.Automation.DomainServices.DirectoryMappingService.Internal;
namespace YZX.Tia.Extensions
{
public static class RemoteFileAccessExtensions
{
public static List<string> GetFileNames(this RemoteFileAccess remoteFileAccess, string path="")
{
List<string> peList = new List<string>();
uint handle = 0U;
remoteFileAccess.OpenDir(FormatPath(path), ref handle);
Value entries = null;
remoteFileAccess.ReadDir(handle, ref entries, 100U, RemoteFileAccess.DirEntryFilter.FindFilesOnly);
if (entries != null)
{
for (uint key = 0U; key < entries.ElementCount; ++key)
{
Value obj = new Value();
entries.GetValue(key, ref obj);
string str = string.Empty;
obj.GetValue(ref str);
if (!str.Equals(".") && !str.Equals("..") && !peList.Contains(str))
peList.Add(str);
obj.Dispose();
}
entries.Dispose();
}
remoteFileAccess.CloseDir(handle);
return peList;
}
internal static IConfigFile ReadConfigFile(this RemoteFileAccess remoteFileAccess,
IMetaService m_metaService,
string configFileName)
{
IConfigFile configFile = null;
uint handle = 0U;
string path = configFileName;
remoteFileAccess.OpenFile(path, RemoteFileAccess.FileAccessMode.ReadAccess, ref handle);
Siemens.Automation.OMSPlus.Managed.FileInfo info = new Siemens.Automation.OMSPlus.Managed.FileInfo();
remoteFileAccess.GetFileInfo(configFileName, ref info);
uint bytes_to_read = (uint)info.size;
byte[] buffer = new byte[(int)bytes_to_read];
uint read = 0U;
remoteFileAccess.ReadFile(handle, ref buffer, bytes_to_read, RemoteFileAccess.CurrentPosition, ref read);
byte[] bytes = new byte[(int)read];
for (uint index = 0U; index < read; ++index)
bytes[(int)index] = buffer[(int)index];
string @string = new UTF8Encoding().GetString(bytes);
remoteFileAccess.CloseFile(handle);
XDocument innerDocument = m_metaService.ParseConfigFile(@string);
if (innerDocument != null)
{
string fileName = Path.GetFileName(configFileName);
ConfigFileParameters configFileParameters = GetConfigFileParameters(innerDocument, fileName);
if (configFileParameters != null)
configFile = new ConfigFile(configFileParameters);
}
return configFile;
}
private static ConfigFileParameters GetConfigFileParameters(XDocument innerDocument, string fileName)
{
if (innerDocument == null)
return null;
string unformattedPath;
string type;
try
{
unformattedPath = Enumerable.First(Enumerable.Where(innerDocument.Descendants(), x => x.Name.LocalName == Constants.DirectoryPath)).Value;
type = Enumerable.First(Enumerable.Where(innerDocument.Descendants(), x => x.Name.LocalName == Constants.Type)).Value;
}
catch (InvalidOperationException ex)
{
return null;
}
return new ConfigFileParameters(fileName, FormatPath(unformattedPath), type, false);
}
public static string FormatPath(string unformattedPath)
{
return unformattedPath.Replace("\\", "/");
}
}
}
<file_sep>/Siemens.Automation.Archiving.Test/Extensions/Archiving/IDirectoryExtensions.cs
using Siemens.Automation.Archiving;
using YZX.Tia.Proxies.Archiving;
namespace YZX.Tia.Extensions.Archiving
{
public static class IDirectoryExtensions
{
public static ZipExtractorProxy ToZipExtractorProxy(IDirectory directory)
{
return new ZipExtractorProxy(directory);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.CommandProcessor.cs
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Simatic.PlcLanguages.Utilities;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static ICommandProcessor GetCommandProcessor([NotNull] this IWorkingContext workingContext)
{
ICommandProcessor commandProcessor = DlcIdExtensions.LoadByDlcId(workingContext.DlcManager, DlcIds.Platform.CommonServices.CommandProcessor);
return commandProcessor;
}
}
}
<file_sep>/YZX.TIA/Proxies/SimaticStructureTargetProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.StructureProviderSupport;
namespace YZX.Tia.Proxies
{
public class SimaticStructureTargetProxy
{
SimaticStructureTarget SimaticStructureTarget;
public SimaticStructureTargetProxy()
{
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Tags.cs
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Siemens.Simatic.PlcLanguages.TagTableViewer;
using Siemens.Automation.ObjectFrame.Meta;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.FolderService;
using Siemens.Automation.ObjectFrame.BusinessLogic;
using YZX.Tia.Proxies;
using Reflection;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
/// <summary>
/// 取得变量表文件夹
/// </summary>
/// <param name="cpu">控制器</param>
public static ICoreObject GetTagsFolder(this ICoreObject cpu,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(c) =>
{
IFolderService folderService = cpu.GetFolderService();
IObjectTypeInfo tagTableType = GetTagTableType(cpu);
return folderService.GetAppropriateFolder(cpu, tagTableType, false);
}, cpu) as ICoreObject;
}
public static readonly Type XLSXImporterType = typeof(XLSXImporter);
public static ICoreObject GetTagTableByName(this ICoreObject tagsFolder,
string Name,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = tagsFolder.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(p_tagsFolder, p_Name) =>
{
IDictionary<string, ICoreObject> tables = GetTagTables(tagsFolder, UsingSynchronizer);
ICoreObject table;
tables.TryGetValue(p_Name, out table);
return table;
}, tagsFolder, Name) as ICoreObject;
}
/// <summary>
/// 取得指定文件夹下所有变量表
/// </summary>
public static IDictionary<string, ICoreObject> GetTagTables(this ICoreObject tagsFolder,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = tagsFolder.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(folder) =>
{
return Reflector.RunStaticMethodByName(
XLSXImporterType,
"GetTagTables",
ReflectionWays.SystemReflection,
tagsFolder) as IDictionary<string, ICoreObject>;
}, tagsFolder) as IDictionary<string, ICoreObject>;
}
/// <summary>
/// 取得默认变量表
/// </summary>
public static ICoreObject GetDefaultTagTable(this ICoreObject cpu,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
ICoreObject tagFolder = cpu.GetTagsFolder();
IDictionary<string, ICoreObject> tagTables = tagFolder.GetTagTables();
ICoreObject defaultTagTable = null;
tagTables.TryGetValue("默认变量表", out defaultTagTable);
return defaultTagTable;
}
public static IObjectTypeInfo GetTagTableType(this ICoreObject tagTable)
{
return tagTable.Context.Meta.GetObjectType("Siemens.Automation.DomainModel.EAMTZTagTableData");
}
public static IObjectTypeInfo GetTagType(this ICoreObject tagTable)
{
return tagTable.Context.Meta.GetObjectType("Siemens.Automation.DomainModel.EAMTZTagData");
}
public static IObjectTypeInfo GetConstantType(this ICoreObject tagTable)
{
return tagTable.Context.Meta.GetObjectType("Siemens.Automation.DomainModel.SimaticConstantTagData");
}
/// <summary>
/// 按名称查找变量
/// </summary>
/// <param name="cpu">控制器</param>
/// <param name="tagName">变量名称</param>
public static IBLTag FindRootTagByName(
this ICoreObject cpu,
string tagName,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(p_cpu, p_tagName) =>
{
ITagService tagService = cpu.GetTagService();
return tagService.FindRootTagByName(p_tagName, p_cpu, "InverseTarget", true);
}, cpu, tagName) as IBLTag;
}
/// <summary>
/// 按地址查找变量
/// </summary>
/// <param name="cpu">控制器</param>
/// <param name="address">地址</param>
public static IBLTag FindRootTagByAddress(this ICoreObject cpu,
string address,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(p_cpu, p_address, p_synchronizer) =>
{
ITagService tagService = p_cpu.GetTagService();
RootTagCollectionProxy rtcp = p_cpu.FindRootTags(p_synchronizer);
List<IBLTag> tags = rtcp.Tags;
foreach (IBLTag tag in tags)
{
if (tag.LogicalAddress == p_address)
{
return tag;
}
}
return null;
}, cpu, address, UsingSynchronizer) as IBLTag;
}
/// <summary>
/// 取得控制器所有变量
/// </summary>
public static RootTagCollectionProxy FindRootTags(this ICoreObject cpu,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(p_cpu) =>
{
ITagService tagService = cpu.GetTagService();
IList list = tagService.FindRootTags(p_cpu, cpu.GetTagType(), "InverseTarget", true);
RootTagCollectionProxy rtcp = new RootTagCollectionProxy(list, UsingSynchronizer);
return rtcp;
}, cpu) as RootTagCollectionProxy;
}
/// <summary>
/// 创建变量
/// </summary>
/// <param name="cpu">控制器</param>
/// <param name="tagTable">变量表</param>
/// <param name="properties">变量数据</param>
/// <param name="isConstant">是否静态变量</param>
public static IBLTag CreateRootTagInTagTable(
this ICoreObject cpu,
ICoreObject tagTable,
Dictionary<string, string> properties,
bool isConstant = false,
ISynchronizeInvoke synchronizer = null
)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
IObjectTypeInfo iot = null;
if (isConstant)
{
iot = tagTable.GetConstantType();
}
else
{
iot = tagTable.GetTagType();
}
ITagService tagService = cpu.GetTagService();
using (new ObjectFrameBulkOperationMode(tagTable))
{
return tagService.CreateRootTag(
cpu,
iot,
Enumerable.ToDictionary(properties,
kvp => kvp.Key, (Func<KeyValuePair<string, string>, object>)(kvp => kvp.Value))) as IBLTag;
}
}) as IBLTag;
}
/// <summary>
/// 更新变量
/// </summary>
/// <param name="tagTable">变量表</param>
/// <param name="tag">变量</param>
/// <param name="properties">变量数据</param>
/// <param name="isConstant">是否静态变量</param>
public static bool UpdateTagReal(
this ICoreObject tagTable,
IBLTag tag,
Dictionary<string, string> properties,
bool isConstant = false)
{
if (tag == null)
throw new ArgumentNullException("tag");
if (properties == null)
throw new ArgumentNullException("properties");
string str = null;
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.DataTypeNameStructureRef", out str)
&& !tag.IsAttributeReadOnly("DataTypeNameStructureRef"))
tag.SetStringAttribute("DataTypeNameStructureRef", str);
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.LogicalAddress", out str)
&& !tag.IsAttributeReadOnly("LogicalAddress"))
tag.LogicalAddress = str;
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.Comment", out str)
&& !tag.IsAttributeReadOnly("Comment"))
tag.Comment = str;
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.HmiStructureTypeRelevant", out str))
{
bool result;
if (!bool.TryParse(str, out result))
return false;
if (!tag.IsAttributeReadOnly("HmiStructureTypeRelevant"))
tag.HmiStructureTypeRelevant = result;
}
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.HmiVisible", out str))
{
bool result;
if (!bool.TryParse(str, out result))
return false;
if (!tag.IsAttributeReadOnly("HmiVisible"))
tag.HmiVisible = result;
}
if (properties.TryGetValue("Siemens.Automation.DomainServices.IBLTag.Value", out str) && !tag.IsAttributeReadOnly("Value"))
tag.Value = str;
if (!tag.IsAttributeReadOnly("TagTable"))
{
tag.TagTable = tagTable;
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新变量
/// </summary>
/// <param name="tagTable">变量表</param>
/// <param name="tag">变量</param>
/// <param name="properties">变量数据</param>
/// <param name="isConstant">是否静态变量</param>
//public static IBLTag UpdateTag(
// this ICoreObject tagTable,
// IBLTag tag,
// Dictionary<string, string> properties,
// bool isConstant = false,
// ISynchronizeInvoke synchronizer = null)
//{
// ISynchronizeInvoke UsingSynchronizer;
// if (synchronizer == null)
// {
// UsingSynchronizer = tagTable.GetSynchronizer();
// }
// else
// {
// UsingSynchronizer = synchronizer;
// }
// return TiaStarter.RunFuncInSynchronizer(UsingSynchronizer,
// () =>
// {
// bool result = UpdateTagReal(tagTable, tag, properties, isConstant);
// return FindRootTagByName(tagTable.GetParent(), tag.Name);
// }) as IBLTag;
//}
public static IBLTag ToBLTag(this ICoreObject tagRef,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = tagRef.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunFuncInSynchronizer(UsingSynchronizer,
(p_tag) =>
{
if (p_tag == null)
{
return null;
}
IBusinessLogicConnector businessLogicConnector = tagRef as IBusinessLogicConnector;
if (businessLogicConnector == null)
{
return null;
}
return businessLogicConnector.GetBusinessLogic("Siemens.Automation.DomainServices.TagService") as IBLTag;
}, tagRef) as IBLTag;
}
public static readonly string[] TagPropertyNames = new string[]{
"Siemens.Automation.DomainServices.IBLTag.Name",
"Path",
"Siemens.Automation.DomainServices.IBLTag.DataTypeNameStructureRef",
"Siemens.Automation.DomainServices.IBLTag.LogicalAddress",
"Siemens.Automation.DomainServices.IBLTag.Comment",
"Siemens.Automation.DomainServices.IBLTag.HmiVisible",
"Siemens.Automation.DomainServices.IBLTag.HmiStructureTypeRelevant"
};
public static Dictionary<string, string> CreateTagProperties(string[] propertyValues)
{
return Reflector.RunStaticMethodByName(typeof(XLSXImporter),
"CreateProperties", ReflectionWays.SystemReflection, TagPropertyNames, propertyValues)
as Dictionary<string, string>;
}
public static ICoreObject CreateTagTable(this ICoreObject folder,
string Name,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = folder.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunFuncInSynchronizer(UsingSynchronizer, (Func<ICoreObject>)
(() => {
ITagService tagService = folder.GetTagService();
TagServiceProxy tsp = new TagServiceProxy(tagService);
return tsp.CreateTagTable(folder, folder.GetTagTableType(), false, Name);
})) as ICoreObject;
}
/// <summary>
/// 取得或创建变量表
/// </summary>
/// <param name="cpu">控制器</param>
/// <param name="Path">变量表路径</param>
public static ICoreObject GetOrCreateTagTable(
this ICoreObject cpu,
string Path,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = cpu.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer, (Func<ICoreObject>)
(() => {
ICoreObject tagFolder = cpu.GetTagsFolder();
ICoreObject table = GetTagTableByName(tagFolder, Path);
if (table == null)
{
table = CreateTagTable(tagFolder, Path);
}
return table;
})) as ICoreObject;
}
//public static IBLTag UpdateOrCreateTag(
// this ICoreObject cpu,
// string Name,
// string Path,
// string DataType,
// string address,
// string Comment,
// bool isConstant = false,
// ISynchronizeInvoke synchronizer = null)
//{
// ISynchronizeInvoke UsingSynchronizer;
// if (synchronizer == null)
// {
// UsingSynchronizer = cpu.GetSynchronizer();
// }
// else
// {
// UsingSynchronizer = synchronizer;
// }
// return TiaStarter.RunInSynchronizer(UsingSynchronizer,
// (Func<ICoreObject, string, string, string, string, string, bool, IBLTag>)
// ((p_cpu, p_Name, p_Path, p_DataType, p_address, p_Comment, p_isConstant) =>
// {
// string[] values = new string[]{
// p_Name,p_Path,p_DataType,p_address,p_Comment,"True","True"
// };
// Dictionary<string, string> properties = CreateTagProperties(values);
// IBLTag findTag = FindRootTagByName(p_cpu, p_Name, UsingSynchronizer);
// ICoreObject tagTable = GetOrCreateTagTable(p_cpu, p_Path, UsingSynchronizer);
// IBLTag newTag = null;
// if (findTag == null)
// {
// newTag = CreateRootTagInTagTable(p_cpu, tagTable, properties, isConstant);
// }
// else
// {
// newTag = UpdateTag(tagTable, findTag, properties, isConstant, UsingSynchronizer);
// }
// return newTag;
// }), cpu, Name, Path, DataType, address, Comment, isConstant) as IBLTag;
//}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Diag.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Diagnostic.Common;
using Siemens.Simatic.HwConfiguration.Diagnostic.ToolWindows.DeviceInfoTable.Service;
using Siemens.Simatic.HwConfiguration.Diagnostic.ToolWindows.DeviceInfoTable.Controller;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static IDiagServiceProvider GetDiagServiceProvider(this ICoreObject coreObj)
{
return DiagServiceProviderAdminImpl.Instance.GetDiagServiceProviderFromCoreObject(coreObj);
}
public static DeviceInfoTableService GetDeviceInfoTableService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
DeviceInfoTableService DeviceInfoTableService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.DeviceInfoTableService")
as DeviceInfoTableService;
return DeviceInfoTableService;
}
public static DeviceInfoTableController GetDeviceInfoTableController(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
DeviceInfoTableController DeviceInfoTableController = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.DeviceInfoTableController")
as DeviceInfoTableController;
return DeviceInfoTableController;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/OnlineService/IConnectionServiceExtensions.cs
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.OnlineService
{
public static class IConnectionServiceExtensions
{
public static ConnectionServiceProvider ToConnectionServiceProvider(this IConnectionService ics)
{
if(ics is ConnectionServiceProvider)
{
return ics as ConnectionServiceProvider;
}
ConnectionServiceProvider csprovider = Reflector.GetInstanceFieldByName(ics, "m_RealConnectionService", ReflectionWays.SystemReflection) as ConnectionServiceProvider;
return csprovider;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DebugManagerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.Model.DebugSupport;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
namespace YZX.Tia.Proxies.Graph
{
public class DebugManagerProxy
{
internal DebugManager DebugManager;
internal DebugManagerProxy(DebugManager manager)
{
DebugManager = manager as DebugManager;
}
public GraphOperatingModeEnum GetOperatingMode()
{
return DebugManager.GetOperatingMode();
}
public bool GetGraphStatusData(string statusDataString, out IGraphStatusData graphStatusData)
{
return DebugManager.GetGraphStatusData(statusDataString, out graphStatusData);
}
public GraphOnlineService GraphOnlineService
{
get
{
return DebugManager.GraphOnlineService as GraphOnlineService;
}
}
public AppendJobResult DeactivateStep(int stepNumber)
{
return GraphOnlineService.DeactivateStep(stepNumber);
}
public AppendJobResult ActivateStep(int stepNumber)
{
return GraphOnlineService.ActivateStep(stepNumber);
}
public AppendJobResult InitializeSequencer()
{
return GraphOnlineService.InitializeSequencer();
}
public AppendJobResult SwitchOffSequencer()
{
return GraphOnlineService.SwitchOffSequencer();
}
public AppendJobResult SwitchMode(GraphOperatingModeEnum newMode)
{
return GraphOnlineService.SwitchMode(newMode);
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Extensions/OnlineInterface/ConnectionExtensions.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Extensions.OnlineInterface
{
public static class ConnectionExtensions
{
public static IOamConfiguration GetConfigurationByName(
string configName
)
{
IOnlineSession onlineSession = OnlineSession.GetOnlineSession();
List<IOamLocalBoard> Boards = onlineSession.Boards;
foreach(var board in Boards)
{
OamConfigurationScanner OCS = new OamConfigurationScanner();
OCS.Board = board;
IEnumerable<IOamConfiguration> configs = OCS.Scan();
List<IOamConfiguration> configList = new List<IOamConfiguration>(configs);
foreach (var config in configList)
{
if (config.Name == configName)
{
return config;
}
}
}
return null;
}
public static IOamConfiguration GetConfigurationByIndex(
string boardName,
int boardNumber,
int configIndex
)
{
IOnlineSession onlineSession = OnlineSession.GetOnlineSession();
List<IOamLocalBoard> boards = onlineSession.Boards;
IOamLocalBoard board = onlineSession.GetBoard(boardName, boardNumber);
OamConfigurationScanner OCS = new OamConfigurationScanner();
OCS.Board = board;
IEnumerable<IOamConfiguration> configs = OCS.Scan();
List<IOamConfiguration> configList = new List<IOamConfiguration>(configs);
IOamConfiguration config = configList[configIndex];
return config;
}
public static INode CreateNode(IOamConfiguration ioc,string addressString)
{
OamConfigurationBase ocb = ioc as OamConfigurationBase;
IOamAddress address;
int createResult = OamObjectCreator.CreateAddress(addressString,out address);
INode node = ocb.CreateNode(address);
return node;
}
public static Tuple<IConnection, IConnection> CreateConnectionFromAddress(
IOamConfiguration config,
OamConnectionType connectionType,
string addressString
)
{
IOamAddress address;
int createResult = OamObjectCreator.CreateAddress(addressString, out address);
OamNodeBase node = OamObjectCreator.CreateNode(config, address);
IConnection connectionMaster = OamObjectCreator.CreateConnection(
connectionType,
node,
true,
OamConnection.OamConnectionRole.SharedMaster);
IConnection connectionProxy = OamObjectCreator.CreateConnection(
connectionType,
node,
true,
OamConnection.OamConnectionRole.SharedProxy);
Tuple<IConnection, IConnection> result =
new Tuple<IConnection, IConnection>(connectionMaster, connectionProxy);
return result;
}
public static Tuple<IConnection,IConnection> CreateConnectionFromAddress(
string boardName,
int boardNumber,
int configIndex,
OamConnectionType connectionType,
string addressString
)
{
IOamConfiguration config = GetConfigurationByIndex(boardName, boardNumber, configIndex);
IOamAddress address;
int createResult = OamObjectCreator.CreateAddress(addressString,out address);
OamNodeBase node = OamObjectCreator.CreateNode(config, address);
IConnection connectionMaster = OamObjectCreator.CreateConnection(
connectionType,
node,
true,
OamConnection.OamConnectionRole.SharedMaster);
IConnection connectionProxy = OamObjectCreator.CreateConnection(
connectionType,
node,
true,
OamConnection.OamConnectionRole.SharedProxy);
Tuple<IConnection, IConnection> result =
new Tuple<IConnection, IConnection>(connectionMaster,connectionProxy);
return result;
}
}
}
<file_sep>/YZX.TIA/Proxies/PackagingImplementationBaseProxy.cs
using System;
using System.IO;
using System.Collections.Generic;
using Siemens.Automation.Utilities.PackagingService;
using Siemens.Automation.Archiving;
using Siemens.Automation.Archiving.Private;
using Siemens.Automation.Utilities.IO;
using Common;
using Reflection;
using Extensions;
namespace YZX.Tia.Proxies
{
public class PackagingImplementationBaseProxy
{
public PackagingImplementationBase PackagingImplementationBase;
public PackagingImplementationBaseProxy(string path)
{
PackagingImplementationBase = new PackagingImplementationBase(path, null, null);
}
public string PackageFilePath
{
get
{
return PackagingImplementationBase.PackageFilePath;
}
}
public string PackageFileDirectory
{
get
{
return FileSystem.PathGetDirectoryName(PackageFilePath);
}
}
public IDirectory Package
{
get
{
return Reflector.GetInstanceFieldByName(PackagingImplementationBase, "m_Package",
ReflectionWays.SystemReflection)
as IDirectory;
}
}
public bool Disposed
{
get
{
return (bool)Reflector.GetInstanceFieldByName(PackagingImplementationBase, "m_Disposed",
ReflectionWays.SystemReflection);
}
}
public Dictionary<string, object> GetFilesWithPositions()
{
if (Disposed)
throw new InvalidOperationException("MetaPackageReader is closed");
IDictionary<string, ZipArchivedFileInfo> fileInfos = ((ZipExtractor)Package).GetFileInfos();
Dictionary<string, object> filepositions = new Dictionary<string, object>();
foreach(string key in fileInfos.Keys)
{
filepositions[key] = fileInfos[key];
}
return filepositions;
}
IDictionary<string, ZipArchivedFileInfo> GetFilesWithFileInfo()
{
if (Disposed)
throw new InvalidOperationException("MetaPackageReader is closed");
IDictionary<string, ZipArchivedFileInfo> fileInfos = ((ZipExtractor)Package).GetFileInfos();
return fileInfos;
}
public IList<string> GetFiles()
{
return PackagingImplementationBase.GetFiles();
}
public UtilityStream OpenStreamReferencePackageWithPosition(string entryName, object ZipArchivedFileInfo)
{
return PackagingImplementationBase.OpenStreamReferencePackageWithPosition(entryName, (ZipArchivedFileInfo)ZipArchivedFileInfo);
}
public void Unpack()
{
IDictionary <string, ZipArchivedFileInfo> fileinfos = GetFilesWithFileInfo();
IList<string> files = GetFiles();
foreach(string f in files)
{
Console.WriteLine(f);
ZipArchivedFileInfo fileinfo = fileinfos[f];
UtilityStream us = OpenStreamReferencePackageWithPosition(f, fileinfo);
us.WriteToFile(Path.Combine(PackageFileDirectory,f));
}
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlinePlusReadThroughCacheProxy.cs
using System;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
namespace YZX.Tia.Proxies
{
public class OnlinePlusReadThroughCacheProxy
{
OnlinePlusReadThroughCache cache;
internal OnlinePlusReadThroughCacheProxy(OnlinePlusReadThroughCache cache)
{
this.cache = cache;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.LibraryService.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.LibraryService;
using Siemens.Simatic.PlcLanguages.LibraryService.Meta;
using Siemens.Simatic.PlcLanguages.LibraryService.Tree;
#if TIAV13
#else
using Siemens.Simatic.Lang.PLInternal.BlockInterface;
#endif
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
#if TIAV13
#else
public static ILibBaseService GetBaseService(this IWorkingContext workingContext)
{
return LibraryServices.GetBaseService(workingContext);
}
#endif
public static ILibMetaService GetMetaService(this IWorkingContext workingContext)
{
return LibraryServices.GetMetaService(workingContext);
}
public static ILibTreeService GetTreeService(this IWorkingContext workingContext)
{
return LibraryServices.GetTreeService(workingContext);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.UiWorkingContext.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject;
using Reflection;
using YZX.Tia.Proxies;
using Siemens.Automation.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IDlc GetPrimaryProjectUiWorkingContextManagerDlc([NotNull] this IWorkingContext workingContext)
{
PrimaryProjectUiWorkingContextManagerDlc EditorController =
workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject.PrimaryProjectUiWorkingContextManager")
as PrimaryProjectUiWorkingContextManagerDlc;
return EditorController;
}
public static PrimaryProjectUiWorkingContextManagerProxy GetPrimaryProjectUiWorkingContextManagerProxy([NotNull] this IWorkingContext workingContext)
{
PrimaryProjectUiWorkingContextManagerDlc dlc = workingContext.GetPrimaryProjectUiWorkingContextManagerDlc()
as PrimaryProjectUiWorkingContextManagerDlc;
PrimaryProjectUiWorkingContextManager manager = Reflector.GetInstancePropertyByName(dlc, "Forwardee", ReflectionWays.SystemReflection)
as PrimaryProjectUiWorkingContextManager;
PrimaryProjectUiWorkingContextManagerProxy proxy = new PrimaryProjectUiWorkingContextManagerProxy(manager);
return proxy;
}
public static IUIContextHolder GetUIContextHolder([NotNull] this IWorkingContext workingContext)
{
PrimaryProjectUiWorkingContextManagerDlc dlc = workingContext.GetPrimaryProjectUiWorkingContextManagerDlc()
as PrimaryProjectUiWorkingContextManagerDlc;
PrimaryProjectUiWorkingContextManager manager = Reflector.GetInstancePropertyByName(dlc, "Forwardee", ReflectionWays.SystemReflection)
as PrimaryProjectUiWorkingContextManager;
PrimaryProjectUiWorkingContextManagerProxy proxy = new PrimaryProjectUiWorkingContextManagerProxy(manager);
return proxy.IUIContextHolder;
}
}
}
<file_sep>/YZX.TIA/Extensions/Oam/IEthernetDiscoverNodeExtensions.cs
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Extensions
{
public static class IEthernetDiscoverNodeExtensions
{
public static int GetProfinetDeviceId(this IEthernetDiscoverNode ethDiscoverNode)
{
int num = 0;
if (ethDiscoverNode != null && ethDiscoverNode.DetailedTypeOfStation != 0)
num = ethDiscoverNode.DetailedTypeOfStationData[2] << 8 | ethDiscoverNode.DetailedTypeOfStationData[3];
return num;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.TiaProjectManager.cs
using System;
using Siemens.Automation.ProjectManager.Impl.Tia;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.ProjectManager;
namespace YZX.Tia
{
partial class TiaStarter
{
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameLocatorExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Undo;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions.FrameApplication
{
public static partial class FrameLocatorExtensions
{
public static IViewFrame ProjectTreeViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.ProjectLibraryTreeViewFrame(workingContext);
}
public static IViewFrame FolderPortalViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.FolderPortalViewFrame(workingContext);
}
public static IViewFrame DetailsViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.DetailsViewFrame(workingContext);
}
public static IViewFrame ProjectLibraryTreeViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.ProjectLibraryTreeViewFrame(workingContext);
}
public static IViewFrame GlobalLibraryTreeViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.GlobalLibraryTreeViewFrame(workingContext);
}
public static IFrame ElementsFrame(this IWorkingContext workingContext)
{
return FrameLocator.ElementsFrame(workingContext);
}
public static IViewFrame PartsViewFrame(this IWorkingContext workingContext)
{
return FrameLocator.PartsViewFrame(workingContext);
}
public static bool IsWithinPortalViewFrameHierarchy(IFrame frame)
{
return FrameLocator.IsWithinPortalViewFrameHierarchy(frame);
}
public static bool IsPropertyViewFrame(IViewFrame viewFrame)
{
return FrameLocator.IsPropertyViewFrame(viewFrame);
}
public static IFrame GetFrame(this IWorkingContext workingContext, string frameId)
{
return FrameLocator.GetFrame(workingContext, frameId);
}
public static IFrame GetEditorMainFrame(this IWorkingContext workingContext)
{
return workingContext.GetFrame("EditorMainFrame");
}
public static EditorMainFrameProxy GetEditorMainFrameProxy(this IWorkingContext workingContext)
{
IFrame frame = workingContext.GetEditorMainFrame();
var proxy = new EditorMainFrameProxy(frame);
return proxy;
}
public static IFrame ActiveFrame(this IWorkingContext workingContext)
{
return FrameLocator.ActiveFrame(workingContext);
}
public static IEditorFrame ActiveEditor(this IWorkingContext workingContext)
{
return FrameLocator.ActiveEditor(workingContext);
}
public static IEditorPageFrame GetActiveEditorPageFrame(this IWorkingContext workingContext)
{
return FrameLocator.GetActiveEditorPageFrame(workingContext);
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/NullUserInteractor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Siemens.Automation.UI.Controls.Utils;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.UserInteraction;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.Selection;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.Logic;
namespace YZX.Tia.Proxies.Ladder
{
internal class NullUserInteractor: DefaultUserInteractor
{
private DefaultUserInteractor oldManager;
public NullUserInteractor(DefaultUserInteractor oldManager)
:base(oldManager.FLGView,oldManager.Navigator,oldManager.SelectionManager)
{
this.oldManager = oldManager;
}
protected override DragImage CreateAndSetDragImage(IGraphicObject graphicObject,
List<Element> data,
IDataObject dataObject)
{
return null;
}
protected override void HandleHover(IGraphicObject graphicObject) { }
protected override void HandleSelection(IGraphicObject graphicObject) { }
protected override void OnViewLostFocus(object sender, EventArgs e) { }
protected override void OnEditBoxLostFocus(object sender, EventArgs e) { }
protected override void OnViewMouseDoubleClick(object sender, MouseEventArgs e) {
}
protected override void OnViewMouseDown(object sender, MouseEventArgs e) { }
protected override void OnViewMouseUp(object sender, MouseEventArgs e) { }
protected override void OnViewMouseMove(object sender, MouseEventArgs e) { }
protected override void OnViewMouseLeave(object sender, EventArgs e) { }
protected override void OnViewKeyDown(object sender, KeyEventArgs e) {
FLGComboBox.Hide();
FLGEditBox.Hide();
}
protected override void OnViewKeyPress(object sender, KeyPressEventArgs e) {
FLGComboBox.Hide();
FLGEditBox.Hide();
}
protected override void OnEditBoxKeyDown(object sender, KeyEventArgs e) {
FLGComboBox.Hide();
FLGEditBox.Hide();
}
protected override void OnViewDragEnter(object sender, DragEventArgs e) { }
protected override void OnViewDragOver(object sender, DragEventArgs e) { }
protected override void OnViewDragDrop(object sender, DragEventArgs dragEventArgs) { }
protected override void OnViewDragLeave(object sender, EventArgs e) { }
public new IFLGEditField EditObject(IGraphicObject objectToEdit,
EditObjectActivationMode activationMode)
{
return null;
}
public new void BeginAction(IUserAction action)
{
}
public new void EndAction(IUserAction action, bool bCommit)
{
}
internal new IFLGTextBox FLGEditBox
{
get
{
return null;
}
}
public new bool IsEditing
{
get
{
return false;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.Hwcn-Application-DlcConfigAccess.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
using Siemens.Simatic.HwConfiguration.Application.UserInterface.Basics.Controller;
using YZX.Tia.Proxies.Hwcn;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static PersistentDataStorageServiceProxy GetPersistentDataStorageService([NotNull] this IWorkingContext workingContext)
{
PersistentDataStorageService dlc = workingContext.GetRequiredDlc<PersistentDataStorageService>("Siemens.Simatic.HwConfiguration.Application.UserInterface.Basics.Controller.PersistentDataStorageService");
return new PersistentDataStorageServiceProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Proxies/OMSNodeProxy.cs
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OMSNodeProxy:OamNodeProxy
{
OMSNode OMSNode;
public OMSNodeProxy(INode node) : base(node)
{
OMSNode = node as OMSNode;
}
public IConnection CreateConnection(OamConnectionType connectionType, bool useExisting)
{
return OMSNode.CreateConnection(connectionType, useExisting);
}
public IConnection CreateConnection(OamConnectionType connectionType, OmsSessionType sessionType)
{
return OMSNode.CreateConnection(connectionType, sessionType);
}
public ClientSession CreateOmsSession(OmsSessionType sessionType)
{
return OMSNode.CreateOmsSession(sessionType);
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Proxies/BlockLogic/DebugServiceProxy.cs
using System.ComponentModel;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
namespace YZX.Tia.Proxies
{
public class DebugServiceProxy
{
public DebugService DebugService;
public DebugServiceProxy(DebugService ds)
{
DebugService = ds;
}
public IDebugSynchronizeInvoke Synchronizer
{
get
{
return DebugService.Synchronizer;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/OnlineBlockServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online;
namespace YZX.Tia.Proxies
{
public class OnlineBlockServiceProxy
{
OnlineBlockService OnlineBlockService;
public OnlineBlockServiceProxy(IOnlineBlockService IOnlineBlockService)
{
OnlineBlockService = IOnlineBlockService as OnlineBlockService;
}
internal TargetCache GetTargetCacheForTarget(ICoreObject target)
{
return OnlineBlockService.GetTargetCacheForTarget(target);
}
}
}
<file_sep>/YZX.TIA/Proxies/FileManagerProxy.cs
using System;
using System.Xml;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.TagTableViewer;
using Siemens.Automation.DomainServices;
using Siemens.Automation.ObjectFrame;
using Reflection;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
class FileManagerProxy
{
FileManager FM;
ISynchronizeInvoke UsingSynchronizer;
public FileManagerProxy(IWorkingContext wc, ISynchronizeInvoke synchronizer = null)
:this(new FileManager(wc),synchronizer)
{
}
public FileManagerProxy(FileManager fm, ISynchronizeInvoke synchronizer = null)
{
FM = fm;
UsingSynchronizer = synchronizer;
}
public bool ImportXML(ICoreObject controller, string path)
{
XmlReader xmlReader = XmlReader.Create(path);
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
return (bool)Reflector.RunInstanceMethodByName(FM,
"ImportXML",
ReflectionWays.SystemReflection,
controller, xmlReader);
});
}
private void AddTag2TagTable(ICoreObject parent,
string tagName,
string tagDataType,
string tagAddr,
string tagRemark,
string hmiAccessible = "True",
string hmiVisible = "True",
string retain = "",
ITagService tagService = null)
{
TiaStarter.RunActionInSynchronizer(UsingSynchronizer,
() =>
{
Reflector.RunInstanceMethodByName(FM,
"ImportXML",
ReflectionWays.SystemReflection,
tagName,
tagDataType,
tagAddr,
tagRemark,
hmiAccessible,
hmiVisible,
retain,
tagService);
});
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamOnlineBlockDirectoryProxy.cs
using System;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.SPS7;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamOnlineBlockDirectoryProxy
{
OamOnlineBlockDirectory OamOnlineBlockDirectory;
public OamOnlineBlockDirectoryProxy(IOamOnlineBlockDirectory dir)
{
OamOnlineBlockDirectory = dir as OamOnlineBlockDirectory;
}
}
}
<file_sep>/YZX.TIA/UnpackAllMpk.py
# -*- coding: utf-8 -*-
import clr
from System import *
from System.IO import *
from System.Collections.Generic import *
from System.Diagnostics import *
NetHome = "C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\Framework\\.NETFramework\\v4.0\\"
TiaHome = "D:\\Program Files\\Siemens\\Automation\\Portal V14\\Bin\\"
TiaHome32 = "D:\\Program Files\\Siemens\\Automation\\Portal V14\\Win32\\Bin\\"
Debugger.Launch()
clr.AddReferenceToFileAndPath(TiaHome32 + "siemens.automation.utilities.dll")
clr.AddReferenceToFileAndPath(TiaHome + "YZX.Tia.dll")
from YZX.Tia.Proxies import *
from YZX.Tia.Extensions import *
mpks = {}
BasePath = "D:\\Program Files\\Siemens\\Automation\\Portal V14\\Meta\\"
BasePath = "D:\Program Files\Siemens\Automation\Portal V14\Data\IECPL"
BasePath = "D:\Program Files\Siemens\Automation\Portal V14\Data\IPI"
BasePath = "D:\Program Files\Siemens\Automation\Portal V14\Data\Hwcn"
def EnumerateFiles():
print Directory
files = Directory.EnumerateFiles(BasePath,"*.mpk",SearchOption.AllDirectories)
for f in files:
print f
pib = PackagingImplementationBaseProxy(f)
pib.Unpack()
fi = FileInfo(f)
try:
fi.Delete()
except:
print "删除" + f + "失败"
def RunOneTime():
EnumerateFiles()
RunOneTime()<file_sep>/Siemens.Automation.CommonServices.ProjectManager.Test/Proxies/ProjectManager/TiaProjectManagerProxy.cs
using Siemens.Automation.ProjectManager;
using Siemens.Automation.ProjectManager.Impl.Tia;
namespace YZX.Tia.Proxies.ProjectManager
{
public class TiaProjectManagerProxy
{
public object TiaProjectManagerObject
{
get
{
return TiaProjectManager;
}
}
ITiaProjectManager TiaProjectManager;
internal TiaProjectManagerProxy(TiaProjectManager tpm)
{
TiaProjectManager = tpm;
}
public bool OpenProjectReadWrite(string path,
out object projectO,
bool silent=false)
{
OpenProjectParams parameters = new OpenProjectParams(path);
parameters.Access = TiaProjectAccess.ReadWrite;
parameters.Silent = silent;
//parameters.OpenCallback = new UpgradeCurrentOpenCallback(new OpenProjectCommandData.CachingOpenFeedbackHandler());
ITiaProject project;
bool returnB = TiaProjectManager.OpenProject(parameters, out project);
if(project != null)
{
projectO = new TiaProjectProxy(project);
}
else
{
projectO = null;
}
return returnB;
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphStepProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphStepProxy
{
internal GraphStep GraphStep;
internal GraphStepProxy(GraphStep step)
{
GraphStep = step;
}
public GraphActionsProxy StepActions
{
get
{
return new GraphActionsProxy(GraphStep.StepActions);
}
}
public int Id
{
get
{
return GraphStep.Id;
}
set
{
GraphStep.Id = value;
}
}
public int Number
{
get
{
return GraphStep.Number;
}
set
{
GraphStep.Number = value;
}
}
public string Name
{
get
{
return GraphStep.Name;
}
set
{
GraphStep.Name = value;
}
}
public GraphSequenceProxy Parent
{
get
{
return new GraphSequenceProxy(GraphStep.Parent) ;
}
}
public List<GraphActionProxy> OnActions
{
get
{
return GraphStep.OnActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphActionProxy> OffActions
{
get
{
return GraphStep.OffActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public List<GraphActionProxy> OffAllActions
{
get
{
return GraphStep.OffAllActions.ConvertAll(new Converter<GraphAction, GraphActionProxy>(
GraphBlockLogicConverters.GraphActionProxy));
}
}
public GraphConnectionProxy InConnection
{
get
{
return new GraphConnectionProxy(GraphStep.InConnection);
}
set
{
GraphStep.InConnection = value.GraphConnection;
}
}
public GraphConnectionProxy OutConnection
{
get
{
return new GraphConnectionProxy(GraphStep.OutConnection);
}
set
{
GraphStep.OutConnection = value.GraphConnection;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/RootCollectionHolderProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.Basics.Browsing;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.FrameApplication
{
public class RootCollectionHolderProxy
{
internal RootCollectionHolder RootCollectionHolder;
internal IRootObjectHostService IRootObjectHostService
{
get
{
return RootCollectionHolder as IRootObjectHostService;
}
}
internal RootCollectionHolderProxy(RootCollectionHolder holder)
{
RootCollectionHolder = holder;
}
public IBrowsableCollection RootObjectCollection
{
get
{
return RootCollectionHolder.RootObjectCollection;
}
}
public IWorkingContext CollectionWorkingContext
{
get
{
return RootCollectionHolder.CollectionWorkingContext;
}
}
public IDictionary<int, BrowsableCollection> CollectionPositionList
{
get
{
return RootCollectionHolder.CollectionPositionList;
}
}
public IBrowsableCollection GetRootObjectCollection(IWorkingContext workingContext)
{
return IRootObjectHostService.GetRootObjectCollection(workingContext);
}
public IBrowsableCollection GetLowestPrioRootObjectCollection(IWorkingContext workingContext)
{
return IRootObjectHostService.GetLowestPrioRootObjectCollection(workingContext);
}
}
}
<file_sep>/YZX.TIA/Extensions/ClientSessionExtensions.cs
using System.Collections.Generic;
using System.Linq;
using Siemens.Automation.DomainModel;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.Lang.Model.Blocks;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions
{
public static class ClientSessionExtensions
{
public static string GetSerialNumberRemote(this ClientSession clientSession)
{
return OmsPlusBlockUtilities.GetSerialNumberRemote(clientSession, "");
}
public static int GetOperatingState(this ClientSession clientSession)
{
return OmsPlusBlockUtilities.GetOperatingState(clientSession);
}
public static OnlinePlusReadThroughCacheProxy GetBlockAccess(this ClientSession clientSession, ICoreObject target)
{
OnlinePlusReadThroughCache cache = new OnlinePlusReadThroughCache(target, clientSession);
OnlinePlusReadThroughCacheProxy proxy = new OnlinePlusReadThroughCacheProxy(cache);
return proxy;
}
public static Object CreateASRoot(this ClientSession clientSession)
{
Object @object = new Object();
Composition composition = new Composition();
Error childObject = clientSession.ProxyObjectRoot.CreateChildObject(new Rid(2478U), ref @object, composition, new ObjectPlacement()
{
NewPosition = PlacementHint.PlacementAddDontCare
}, new Rid(1U));
composition.Dispose();
if (childObject.Succeeded || clientSession.ProxyObjectRoot.GetObjectFromID(1U, ref @object).Succeeded)
return @object;
return null;
}
public static void TestStart(this ClientSession clientSession)
{
Rid rid = new Rid(52U);
Value obj = new Value(3);
Aid aid = new Aid(2167U);
int requestID = 0;
Error error = clientSession.SetVariableRemote(rid, aid, obj, 1, ref requestID);
}
public static void TestStop(this ClientSession clientSession)
{
Rid rid = new Rid(52U);
Value obj = new Value(1);
Aid aid = new Aid(2167U);
int requestID = 0;
Error error = clientSession.SetVariableRemote(rid, aid, obj, 1, ref requestID);
}
public static OnlineProtectionLevel EffectiveProtectionFromPlcOrHashSet(this ClientSession session)
{
OnlineProtectionLevel onlineProtectionLevel = OnlineProtectionLevel.Unknown;
Value obj = new Value();
int requestID = -1;
Error variableRemote = session.GetVariableRemote(session.ServerSessionRID, new Aid(1842U), ref obj, ref requestID);
if (variableRemote.Succeeded)
{
uint num = 1000U;
variableRemote = obj.GetValue(ref num);
if (variableRemote.Succeeded)
{
switch (num)
{
case 0U:
onlineProtectionLevel = OnlineProtectionLevel.NoProtection;
break;
case 1U:
onlineProtectionLevel = OnlineProtectionLevel.ProtectFailSafeAccess;
break;
case 2U:
onlineProtectionLevel = OnlineProtectionLevel.ProtectWrite;
break;
case 3U:
onlineProtectionLevel = OnlineProtectionLevel.ProtectReadWrite;
break;
case 4U:
onlineProtectionLevel = OnlineProtectionLevel.ProtectIdentificationAccess;
break;
case 5U:
onlineProtectionLevel = OnlineProtectionLevel.NoProtection;
break;
}
}
if (obj != null)
obj.Dispose();
}
return onlineProtectionLevel;
}
public static uint GetProtectionLevelOnline(this ClientSession session)
{
uint m_OnlineProtectionLevel = 0;
Rid rid = new Rid(50U);
Aid aid = new Aid(3451U);
Value obj = new Value();
int requestID = -1;
if (session.GetVariableRemote(rid, aid, ref obj, ref requestID).Succeeded)
obj.GetValue(ref m_OnlineProtectionLevel);
return m_OnlineProtectionLevel;
}
public static ulong GetMMCFreeSpaceRemote(this ClientSession session)
{
ulong num1 = 0UL;
ulong num2 = 0UL;
uint num3 = 0U;
int requestID = -1;
AnyVariableValue[] anyValueList = new AnyVariableValue[2]
{
new AnyVariableValue()
{
ObjectRID = new Rid(201U),
AddressList = new uint[1]
{
399U
}
},
new AnyVariableValue()
{
ObjectRID = new Rid(51U),
AddressList = new uint[1]
{
2117U
}
}
};
if (session.GetVariablesRemote(anyValueList, ref requestID).Succeeded)
{
anyValueList[0].VariableValue.GetValue(ref num2);
anyValueList[1].VariableValue.GetValue(ref num3);
num1 = ((int)num3 & -1073741824) != -1073741824 ? num2 - (num3 & 1073741823U) * (((int)num3 & int.MinValue) != 0 ? 4096UL : (((int)num3 & 1073741824) != 0 ? 512UL : 1UL)) : 0UL;
}
anyValueList[0].VariableValue.Dispose();
anyValueList[1].VariableValue.Dispose();
return num1;
}
public static Error WriteValuesRemote(this ClientSession session,
AnyVariableValue[] anyValueArray)
{
Error error = new Error();
foreach (AnyVariableValue anyVariableValue in anyValueArray)
{
Blob blob = null;
error = anyVariableValue.VariableValue.GetValue(ref blob);
using (blob)
{
if (error.Failed)
return error;
error = session.SetBlobRemote(anyVariableValue.ObjectRID.RID, anyVariableValue.AddressList, blob);
if (error.Failed)
return error;
}
}
return error;
}
public static bool ReadPlusDbValuesRemote(this ClientSession session,
ICoreObject onlineTarget, ICoreObject blockDb, out OnlineBinary binaryToRead, uint dbValuesAid)
{
if (onlineTarget == null || blockDb == null)
throw new BlockLogicException("onlineTarget, blockDb is null");
if (!IecplUtilities.IsPlusPLC(blockDb) || !onlineTarget.GetObjectType().IsTypeOf(OnlineControllerTargetData.FullName))
throw new BlockLogicException("Target is no Plus- or Online target");
IGeneralBlockSourceData generalBlockSourceData = blockDb.GetAttributeSet(typeof(IGeneralBlockSourceData), false) as IGeneralBlockSourceData;
if (generalBlockSourceData == null || generalBlockSourceData.BlockType != BlockType.DB)
throw new BlockLogicException("block is no data block!");
if ((int)dbValuesAid != 2550 && (int)dbValuesAid != 2548)
throw new System.NotSupportedException("Only ValueActual_Aid and ValueInitial_Aid are supported");
uint blockRid = RidService.GetRidService(onlineTarget, true).GetBlockRid(blockDb);
Error error = new Error();
ulong ticks = 0UL;
Dictionary<uint, byte[]> dictionary = new Dictionary<uint, byte[]>()
{
{
3U,
new byte[0]
},
{
4U,
new byte[0]
},
{
5U,
new byte[0]
}
};
binaryToRead = new OnlineBinary(dictionary[4U], dictionary[5U], dictionary[3U], new System.DateTime());
try
{
int requestID = -1;
Value obj1 = new Value();
Value obj2 = null;
foreach (uint index in Enumerable.ToList(dictionary.Keys))
{
Blob blob = new Blob();
Error blobRemote = session.GetBlobRemote(blockRid, new uint[2]
{
dbValuesAid,
index
}, ref blob);
using (blob)
{
if (blobRemote.Failed)
{
return false;
}
byte[] data = new byte[0];
blob.GetData(ref data);
dictionary[index] = data;
}
}
Error variableSubrangeRemote = session.GetVariableSubrangeRemote(new Rid(blockRid), new uint[2]
{
dbValuesAid,
6U
}, ref obj2, ref requestID);
using (obj2)
{
if (variableSubrangeRemote.Failed)
{
return false;
}
obj2.GetValue(ref ticks);
}
binaryToRead = new OnlineBinary(dictionary[4U], dictionary[5U], dictionary[3U], DateTimeExtensions.ConvertPLCToESTime(ticks));
}
finally
{
}
return true;
}
public static bool ReadPlusMcDbValuesRemote(this ClientSession session,
ICoreObject onlineTarget, ICoreObject blockDb, out OnlineBinary binaryToRead, uint dbValuesAid)
{
if (onlineTarget == null || blockDb == null)
throw new BlockLogicException("onlineTarget, blockDb is null");
if (!IecplUtilities.IsPlusPLC(blockDb) || !onlineTarget.GetObjectType().IsTypeOf(OnlineControllerTargetData.FullName))
throw new BlockLogicException("Target is no Plus- or Online target");
IGeneralBlockSourceData generalBlockSourceData = blockDb.GetAttributeSet(typeof(IGeneralBlockSourceData), false) as IGeneralBlockSourceData;
if (generalBlockSourceData == null || generalBlockSourceData.BlockType != BlockType.DB)
throw new BlockLogicException("block is no data block!");
if ((int)dbValuesAid != 2550 && (int)dbValuesAid != 2548)
throw new System.NotSupportedException("Only ValueActual_Aid and ValueInitial_Aid are supported");
uint blockRid = RidService.GetRidService(onlineTarget, true).GetBlockRid(blockDb);
Error error = new Error();
ulong ticks = 0UL;
Dictionary<uint, byte[]> dictionary = new Dictionary<uint, byte[]>()
{
{
3U,
new byte[0]
},
{
4U,
new byte[0]
},
{
5U,
new byte[0]
}
};
binaryToRead = new OnlineBinary(dictionary[4U], dictionary[5U], dictionary[3U], new System.DateTime());
try
{
int requestID = -1;
Value obj1 = new Value();
Value obj2 = null;
Error variableRemote = session.GetVariableRemote(new Rid(blockRid), new Aid(dbValuesAid), ref obj1, ref requestID);
using (obj1)
{
if (variableRemote.Failed)
{
return false;
}
foreach (uint key in Enumerable.ToList(dictionary.Keys))
{
Error errorState = obj1.GetValue(key, ref obj2);
using (obj2)
{
if (errorState.Failed)
{
return false;
}
byte[] numArray = new byte[0];
obj2.GetValue(ref numArray);
dictionary[key] = numArray;
}
}
Error errorState1 = obj1.GetValue(6U, ref obj2);
using (obj2)
{
if (errorState1.Failed)
{
return false;
}
obj2.GetValue(ref ticks);
}
binaryToRead = new OnlineBinary(dictionary[4U], dictionary[5U], dictionary[3U], DateTimeExtensions.ConvertPLCToESTime(ticks));
}
}
finally
{
}
return true;
}
public static string GetAOM_Version(this ClientSession session)
{
Value obj1 = new Value();
int requestID = -1;
if (session.GetVariableRemote(new Rid(1U), new Aid(2460U), ref obj1, ref requestID).Failed)
{
obj1.Dispose();
return string.Empty;
}
string str = null;
if (obj1.GetValue(ref str).Failed)
{
obj1.Dispose();
return string.Empty;
}
obj1.Dispose();
return str;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectExtensions.WorkingContext.cs
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Basics.SystemData;
using Siemens.Simatic.HwConfiguration.Connections.Block.Base;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static partial class ICoreObjectExtensions
{
public static WorkingContext FindWorkingContext(this ICoreObject ico)
{
List<ICoreObject> icoL = new List<ICoreObject>() { ico };
return WorkingContext.FindWorkingContextForGivenObjects(icoL) as WorkingContext;
}
public static ConnService GetConnService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
ConnService ConnService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Connections.Block.Base.ConnectionService")
as ConnService;
return ConnService;
}
public static SystemDataBlockFactory GetSystemDataBlockFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
SystemDataBlockFactory SystemDataBlockFactory = idlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.SystemData.SystemDataBlockFactory")
as SystemDataBlockFactory;
return SystemDataBlockFactory;
}
public static S7PlusDataUpload GetS7PlusDataUpload(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
S7PlusDataUpload S7PlusDataUpload = idlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.SystemData.S7PlusDataUpload")
as S7PlusDataUpload;
return S7PlusDataUpload;
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.PLCMessaging.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PLCMessaging;
using Siemens.Simatic.PLCMessaging.GUI;
using Siemens.Simatic.PLCMessaging.UI;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static PLCMsgConnector GetPlcmService([NotNull] this IWorkingContext workingContext)
{
ICoreContext coreContext = workingContext.GetCoreContext();
return coreContext.GetPlcmService();
}
public static PLCMessagingWindow GetPLCMessagingWindow([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<PLCMessagingWindow>("Siemens.Simatic.PLCMessaging.GUI.PLCMessagingWindow");
}
public static ArchiveGridService GetArchiveGridService([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ArchiveGridService>("Siemens.Simatic.PLCMessaging.GUI.ArchiveGridService");
}
public static AlarmGridService GetAlarmGridService([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<AlarmGridService>("Siemens.Simatic.PLCMessaging.GUI.AlarmGridService");
}
public static PlcMessagingView GetPlcMessagingView([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<PlcMessagingView>("Siemens.Simatic.PLCMessaging.GUI.PlcMessagingView");
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/ConnectionServiceProviderProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainServices.ConnectionService.Private;
using Reflection;
namespace YZX.Tia.Proxies.OnlineService
{
public class ConnectionServiceProviderProxy
{
public ConnectionServiceProvider ConnectionServiceProvider;
public IOnlineConfiguration IOnlineConfiguration
{
get
{
return ConnectionServiceProvider;
}
}
public ConnectionServiceProviderProxy(ConnectionServiceProvider csp)
{
ConnectionServiceProvider = csp;
}
public IAsyncResult BeginConnectToTarget(
ConnectionParamsProxy connectParameter,
AsyncCallback callback,
object state)
{
IAsyncResult iar = Reflector.RunInstanceMethodByName(
ConnectionServiceProvider,
"BeginConnectToTarget",
ReflectionWays.SystemReflection,
connectParameter.CP,
callback,
state
) as IAsyncResult;
return iar;
}
public event ConnectionOpenedEventHandler ConnectionOpened
{
add
{
IOnlineConfiguration.ConnectionOpened += value;
}
remove
{
IOnlineConfiguration.ConnectionOpened -= value;
}
}
public ConnectionServiceClassFactoryProxy ClassFactory
{
get
{
IConnectionServiceClassFactory ClassFactory = Reflector.GetInstancePropertyByName(ConnectionServiceProvider,
"ClassFactory", ReflectionWays.SystemReflection) as IConnectionServiceClassFactory;
return new ConnectionServiceClassFactoryProxy(ClassFactory);
}
}
public IOnlineService OnlineService
{
get
{
return Reflector.GetInstancePropertyByName(ConnectionServiceProvider,
"OnlineService", ReflectionWays.SystemReflection) as IOnlineService;
}
}
public List<ConnectorBaseProxy> ExistingConnectors
{
get
{
List<ConnectorBaseProxy> connectorList = new List<ConnectorBaseProxy>();
IEnumerable<ConnectorBase> ecx = Reflector.GetInstancePropertyByName(ConnectionServiceProvider,
"ExistingConnectors", ReflectionWays.SystemReflection) as IEnumerable<ConnectorBase>;
foreach(ConnectorBase cb in ecx)
{
ConnectorBaseProxy cbp = new ConnectorBaseProxy(cb);
connectorList.Add(cbp);
}
return connectorList;
}
}
public ConnectorBaseProxy GetConnector(string connectionType)
{
ConnectorBase connectorBase = ConnectionServiceProvider.GetConnector(connectionType);
return new ConnectorBaseProxy(connectorBase);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/ProjectNavigationViewProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics.Browsing;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ProjectNavigationViewProxy
{
internal ProjectNavigationView ProjectNavigationView;
internal ProjectNavigationViewProxy(ProjectNavigationView view)
{
ProjectNavigationView = view;
}
public IBrowsableCollection RootObjects
{
get
{
return ProjectNavigationView.RootObjects;
}
}
#region NavigationTreeView
internal INavigationTreeView NavigationTreeView
{
get
{
return ProjectNavigationView as INavigationTreeView;
}
}
public bool IsViewVisible
{
get
{
return NavigationTreeView.IsViewVisible;
}
}
public void ChangeViewScopes(string[] viewScopes)
{
NavigationTreeView.ChangeViewScopes(viewScopes);
}
public string ShowBrowsableInView(IBrowsable browsable)
{
var result = NavigationTreeView.ShowBrowsableInView(browsable);
return result.ToString();
}
public string ShowParentOfBrowsableInView(IBrowsable browsable, out IBrowsable[] path)
{
var result = NavigationTreeView.ShowParentOfBrowsableInView(browsable, out path);
return result.ToString();
}
public bool ContainsBrowsable(IBrowsable browsable)
{
return NavigationTreeView.ContainsBrowsable(browsable);
}
#endregion
public string[] GetGenericBrowserScopes()
{
return ProjectNavigationView.GetGenericBrowserScopes();
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Proxies/NetworkEditorFrame/PLBlockEditorLogicProxy.cs
using System;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
namespace YZX.Tia.Proxies.NetworkEditorFrame
{
public class PLBlockEditorLogicProxy
{
PLBlockEditorLogic PLBlockEditorLogic;
public PLBlockEditorLogicProxy(BlockEditorLogicBase logic)
{
PLBlockEditorLogic = logic as PLBlockEditorLogic;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/OnlineService/LegitimationServiceObjectFactoryExtensions.cs
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace Siemens.Automation.DomainServices.Online.Test.Extensions
{
public static class LegitimationServiceObjectFactoryExtensions
{
public static void ChangeLegitimationServiceObjectFactoryConnectionService(
LegitimationServiceProvider lsp,
ConnectionServiceProvider csp)
{
LegitimationServiceObjectFactory lsof = lsp.LegitimationServiceObjectFactory as LegitimationServiceObjectFactory;
Reflector.SetInstanceFieldByName(
lsof,
"m_ConnectionService",
csp,
ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Extensions/NetworkEditorFrame/PLBlockEditorLogicExtensions.cs
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.NetworkEditorFrame
{
public static class PLBlockEditorLogicExtensions
{
public static void SetMenuService(this BlockEditorLogicBase PLlogic,
IMenuService menuService)
{
Reflector.SetInstanceFieldByName(PLlogic, "m_MenuService", menuService, ReflectionWays.SystemReflection); ;
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Extensions/Diagnostic/CycleTimeDialogExtensions.cs
using Siemens.Simatic.HwConfiguration.Diagnostic.Viewer;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.Diagnostic
{
public static class CycleTimeDialogExtensions
{
public static void InitializeUI(this CycleTimeDialog CycleTimeDialog)
{
Reflector.RunInstanceMethodByName(CycleTimeDialog,
"InitializeUI", ReflectionWays.SystemReflection);
}
public static void SetEnabledState(this CycleTimeDialog CycleTimeDialog,
bool enabled=true)
{
Reflector.RunInstanceMethodByName(CycleTimeDialog,
"SetEnabledState", ReflectionWays.SystemReflection,enabled);
}
public static void DisplayCycleTime(this CycleTimeDialog CycleTimeDialog)
{
Reflector.RunInstanceMethodByName(CycleTimeDialog,
"DisplayCycleTime", ReflectionWays.SystemReflection);
}
public static void SetCycleTimeProj(this CycleTimeDialog CycleTimeDialog,
int Proj)
{
Reflector.SetInstanceFieldByName(CycleTimeDialog,
"m_CycleTimeProj", ReflectionWays.SystemReflection);
}
public static void SetCycleTimeProjMin(this CycleTimeDialog CycleTimeDialog,
float ProjMin)
{
Reflector.SetInstanceFieldByName(CycleTimeDialog,
"m_CycleTimeProjMin", ProjMin,ReflectionWays.SystemReflection);
}
public static void SetCycleTimeOnlineMin(this CycleTimeDialog CycleTimeDialog,
float OnlineMin)
{
Reflector.SetInstanceFieldByName(CycleTimeDialog,
"m_CycleTimeOnlineMin", OnlineMin,ReflectionWays.SystemReflection);
}
public static void SetCycleTimeOnlineAkt(this CycleTimeDialog CycleTimeDialog,
float OnlineAkt)
{
Reflector.SetInstanceFieldByName(CycleTimeDialog,
"m_CycleTimeOnlineAkt",OnlineAkt, ReflectionWays.SystemReflection);
}
public static void SetCycleTimeOnlineMax(this CycleTimeDialog CycleTimeDialog,
float OnlineMax)
{
Reflector.SetInstanceFieldByName(CycleTimeDialog,
"m_CycleTimeOnlineMax", OnlineMax,ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/DPSlaveConnectionProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class DPSlaveConnectionProxy:S7DOSConnectionProxy
{
DPSlaveConnection DPSlaveConnection;
public DPSlaveConnectionProxy(OamConnectionBase connection):
base(connection)
{
DPSlaveConnection = connection as DPSlaveConnection;
}
}
}
<file_sep>/YZX.TIA/Extensions/Vat/VarTableInfoExtensions.cs
using System.Collections.Generic;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.VatService.Navigator;
using Siemens.Simatic.HwConfiguration.BusinessLogic.Acf.Devices;
namespace YZX.Tia.Extensions
{
public static class VarTableInfoExtensions
{
public static List<S7Any> GetS7AnyList(this IVarTableInfo vti)
{
List<S7Any> s7anyList = new List<S7Any>();
foreach(VarLineInfo vli in vti.Lines)
{
//byte[] cap = vli.ClassicAnyPointer;
//if (cap != null)
//{
// if (cap.Length == 10)
// {
// S7Any s7any = cap.ToS7Any();
// s7anyList.Add(s7any);
// }
//}
S7Any? s7any = null;
// s7any = vli.S7Any;
if(s7any.HasValue)
{
s7anyList.Add(s7any.Value);
}
}
return s7anyList;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.HwConfiguration.cs
using Siemens.Automation.Basics;
using Siemens.Simatic.HwConfiguration.Basics.Basics;
using Siemens.Simatic.HwConfiguration.Basics.Meta;
using Siemens.Simatic.HwConfiguration.Basics.SystemData;
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static TargetValidation GetTargetValidation(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<TargetValidation>("Siemens.Simatic.HwConfiguration.Basics.SystemData.TargetValidation");
}
public static HwcnBasicsFacade GetHwcnBasicsFacade(this IWorkingContext workingContext)
{
var hwcnBasicsFacade = workingContext.GetRequiredDlc<HwcnBasicsFacade>("Siemens.Simatic.HwConfiguration.Basics.Basics.HwcnBasicsFacade");
return hwcnBasicsFacade;
}
public static IHwcnFileProvider GetHwcnFileProvider(this IWorkingContext workingContext)
{
var IHwcnFileProvider = workingContext.GetRequiredDlc<IHwcnFileProvider>("Siemens.Simatic.HwConfiguration.Basics.Meta.HwcnFileProvider");
return IHwcnFileProvider;
}
public static IHwcnMetaService GetIHwcnMetaService(this IWorkingContext workingContext)
{
var IHwcnFileProvider = workingContext.GetRequiredDlc<IHwcnMetaService>("Siemens.Simatic.HwConfiguration.Basics.Meta.HwcnMetaService");
return IHwcnFileProvider;
}
}
}
<file_sep>/YZX.TIA/Converter/OamConverters.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Converter
{
public static class OamConverters
{
internal static IOamAsyncResult ConnectAsyncResult2IOamAsyncResult(ConnectAsyncResult car)
{
return car;
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/WindowManagerProxy.Frames.cs
using Siemens.Automation.FrameApplication;
namespace YZX.Tia.Proxies.FrameApplication
{
partial class WindowManagerProxy
{
public const string ProjectNavigatorFrameID = "Siemens.Automation.FrameApplication.ApplicationNavigationContainer";
public ProjectNavigatorFrameProxy GetProjectNavigatorFrameProxy()
{
IFrame frame = GetSingletonFrame(ProjectNavigatorFrameID);
ProjectNavigatorFrameProxy proxy = new ProjectNavigatorFrameProxy(frame);
return proxy;
}
}
}<file_sep>/YZX.TIA/Extensions/OnlineImageCacheExtensions.cs
using System.Collections.Generic;
using Siemens.Simatic.HwConfiguration.Application.ViewDescription;
using Siemens.Simatic.HwConfiguration.Application.UserInterface.Basics.Common.ImageCache;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class OnlineImageCacheExtensions
{
public static Dictionary<string, IHwcnImage> GetImages (OnlineImageCache cache)
{
return Reflector.GetInstanceFieldByName(cache,
"m_Images",
ReflectionWays.SystemReflection) as Dictionary<string, IHwcnImage>;
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphSequencePartProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphSequencePartProxy
{
internal GraphSequencePart GraphSequencePart;
internal GraphSequencePartProxy(GraphSequencePart part)
{
GraphSequencePart = part;
}
}
}
<file_sep>/YZX.TIA/Proxies/ProjectManager/TiaProjectManagerLegacyHandlerProxy.cs
using System;
using System.ComponentModel;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
#if Tia
using Siemens.Simatic.PlcLanguages.BlockLogic.OpenBlockHandling;
#endif
using Siemens.Automation.ProjectManager;
using Siemens.Automation.ProjectManager.Legacy;
using Siemens.Automation.ProjectManager.Impl.UI;
using Siemens.Automation.ProjectManager.Impl.Tia;
using Reflection;
namespace YZX.Tia.Proxies
{
public class TiaProjectManagerLegacyHandlerProxy:IProjectManager
{
internal TiaProjectManagerLegacyHandler TPMLH;
public IProjectManager ProjectManager
{
get
{
return TPMLH as IProjectManager;
}
}
internal TiaProjectManager TiaProjectManager
{
get
{
return Reflector.GetInstancePropertyByName(TPMLH,
"ProjectManager",
ReflectionWays.SystemReflection)
as TiaProjectManager;
}
}
TiaProjectManagerProxy m_TiaProjectManagerProxy;
public event CancelEventHandler PreOpening;
public event EventHandler Opened;
public event CancelEventHandler Saving;
public event EventHandler Saved;
public event EventHandler Closing;
public event EventHandler Closed;
public TiaProjectManagerProxy TiaProjectManagerProxy
{
get
{
if(m_TiaProjectManagerProxy == null)
{
m_TiaProjectManagerProxy = new TiaProjectManagerProxy(TiaProjectManager);
}
return m_TiaProjectManagerProxy;
}
}
public TiaProjectManagerLegacyHandlerProxy(IProjectManager tpmlh)
{
TPMLH = tpmlh as TiaProjectManagerLegacyHandler;
CurrentProject = ProjectManager.CurrentProject;
}
public void SetCurrentProject(ICorePersistence persistence)
{
CurrentProject = persistence;
}
public void ResetCurrentProject()
{
CurrentProject = ProjectManager.CurrentProject;
}
public ICorePersistence CurrentProject { get; private set; }
public string CurrentProjectPath
{
get
{
return ProjectManager.CurrentProjectPath;
}
}
public ICoreContextHandler CurrentCoreContextHandler
{
get
{
return ProjectManager.CurrentCoreContextHandler;
}
}
public string ProjectExtension
{
get
{
return ProjectManager.ProjectExtension;
}
}
public string[] GetSupportedProjectExtensions()
{
return ProjectManager.GetSupportedProjectExtensions();
}
public string[] GetSupportedLocalSessionExtensions()
{
return ProjectManager.GetSupportedLocalSessionExtensions();
}
public string[] GetSupportedGlobalLibraryExtensions()
{
return ProjectManager.GetSupportedGlobalLibraryExtensions();
}
public string[] GetSupportedSystemLibraryExtensions()
{
return ProjectManager.GetSupportedSystemLibraryExtensions();
}
public string[] GetSupportedZipExtensions()
{
return ProjectManager.GetSupportedZipExtensions();
}
public string[] GetSupportedLibraryZipExtensions()
{
return ProjectManager.GetSupportedLibraryZipExtensions();
}
public void RenameProject(string oldDirectory, string newDirectory)
{
ProjectManager.RenameProject(oldDirectory, newDirectory);
}
public void SaveProject(ICorePersistence persistence)
{
ProjectManager.SaveProject(persistence);
}
public void SaveProjectAs(ICorePersistence project, string path)
{
ProjectManager.SaveProjectAs(project, path);
}
public void DeleteProject(string path)
{
ProjectManager.DeleteProject(path);
}
public Version GetStarterFileVersion(string directoryOrStarterFilePath)
{
return ProjectManager.GetStarterFileVersion(directoryOrStarterFilePath);
}
public bool AreProjectVersionsCompatible(Version version1, Version version2)
{
return ProjectManager.AreProjectVersionsCompatible(version1, version2);
}
public string GetArchiveDirectory()
{
return ProjectManager.GetArchiveDirectory();
}
#if Tia
public ICoreObject FindCPU(string name)
{
IControllerTargetLookup QBCTL = new QueryBasedControllerTargetLookup(CurrentCoreContextHandler.CoreContext);
ICoreObject cpu = QBCTL.FindControllerTargetByName(name);
return cpu;
}
#endif
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.BusinessLogic.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.BusinessLogic;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.Lang.Model.Blocks;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Reflection;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static IBusinessLogicObject CreateBusinessLogicObject(this ICoreObject coreObject)
{
return Siemens.Automation.ObjectFrame.Private.BusinessLogicHelper.CreateBusinessLogicObject(coreObject);
}
public static void GetBlockTypeAndLanguage(this ICoreObject coreObject,
out BlockType blockType,
out ProgrammingLanguage blockLanguage)
{
blockType = BlockType.Undef;
blockLanguage = ProgrammingLanguage.Undef;
Reflector.RunStaticMethodByName(typeof(EditorStarterFacade),
"GetBlockTypeAndLanguage",
ReflectionWays.SystemReflection,
coreObject, blockType, blockLanguage);
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/OnlineService/LifelistPNVBrowserExtensionExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.Basics.Browsing;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.Lifelist
{
public static class LifelistPNVBrowserExtensionExtensions
{
public static IBrowsableCollection GetNodesFromBoard(this LifelistPNVBrowserExtension browser,
ICoreObject board)
{
IBrowsableCollection collection = Reflector.RunInstanceMethodByName(browser, "GetNodesFromBoard",
ReflectionWays.SystemReflection,
board,
"LifelistNodes"
) as IBrowsableCollection;
return collection;
}
public static ICoreContext GetLifelistProject(this LifelistPNVBrowserExtension browser)
{
ICoreContext context = Reflector.GetInstancePropertyByName(browser, "LifelistProject",
ReflectionWays.SystemReflection) as ICoreContext;
return context;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/Download/DownloadServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Download
{
public class DownloadServiceProxy
{
DownloadService DownloadService;
public DownloadServiceProxy(object downloadService)
{
DownloadService = downloadService as DownloadService;
}
}
}
<file_sep>/YZX.TIA/TiaStarter.event.cs
using System;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia
{
partial class TiaStarter
{
#region IWindowManagerInternal
internal event EventHandler<ApplicationViewModeChangedEventArgs> ApplicationViewModeChanged {
add {
this.WindowManager.ApplicationViewModeChanged += value;
}
remove {
this.WindowManager.ApplicationViewModeChanged -= value;
}
}
public event EventHandler<FrameAddEventArgs> FrameAdded {
add {
this.WindowManager.FrameAdded += value;
}
remove {
this.WindowManager.FrameAdded -= value;
}
}
public event EventHandler<FrameEventArgs> FrameClosed {
add {
this.WindowManager.FrameClosed += value;
}
remove {
this.WindowManager.FrameClosed -= value;
}
}
public event EventHandler<CancelFrameEventArgs> FrameClosing {
add {
this.WindowManager.FrameClosing += value;
}
remove {
this.WindowManager.FrameClosing -= value;
}
}
public event EventHandler<AdditionalFramesEventArgs> FrameCreated
{
add {
this.WindowManager.FrameCreated += value;
}
remove {
this.WindowManager.FrameCreated -= value;
}
}
public event EventHandler<FrameCreatingEventArgs> FrameCreating
{
add {
this.WindowManager.FrameCreating += value;
}
remove {
this.WindowManager.FrameCreating -= value;
}
}
public event EventHandler InitializationCompleted
{
add {
this.WindowManager.InitializationCompleted += value;
}
remove {
this.WindowManager.InitializationCompleted -= value;
}
}
#endregion
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphTransitionProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphTransitionProxy
{
internal GraphTransition GraphTransition;
internal GraphTransitionProxy(GraphTransition transition)
{
GraphTransition = transition;
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/EditorFrameGroupProxy.cs
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class EditorFrameGroupProxy:FrameGroupBaseProxy
{
EditorFrameGroup EditorFrameGroup;
public EditorFrameGroupProxy(IEditorFrameGroup group):base(group)
{
EditorFrameGroup = group as EditorFrameGroup;
}
}
}
<file_sep>/Siemens.Automation.FileIO.Test/Proxies/FileIO/InstallationFileServiceImplProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FileIO;
using Siemens.Automation.FileIO.Private;
namespace YZX.Tia.Proxies.FileIO
{
public class InstallationFileServiceImplProxy
{
InstallationFileServiceImpl InstallationFileServiceImpl;
public InstallationFileServiceImplProxy(IFileService fileService)
{
InstallationFileServiceImpl = fileService as InstallationFileServiceImpl;
}
}
}
<file_sep>/YZX.TIA/Proxies/OMS/EthernetDiscoverConnectionProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class EthernetDiscoverConnectionProxy:S7DOSConnectionProxy
{
EthernetDiscoverConnection EthernetDiscoverConnection;
public EthernetDiscoverConnectionProxy(OamConnectionBase connection)
:base(connection)
{
EthernetDiscoverConnection = connection as EthernetDiscoverConnection;
}
public int DeletePgIpAdresses()
{
return EthernetDiscoverConnection.DeletePgIpAdresses();
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameApplication.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Menu;
using Siemens.Automation.FrameApplication.StatusBar;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static StatusBarProxy GetStatusBar([NotNull] this IWorkingContext workingContext)
{
StatusBarDlc dlc = workingContext.GetRequiredDlc<StatusBarDlc>("Siemens.Automation.FrameApplication.StatusBar");
return new StatusBarProxy(dlc);
}
public static MenuServiceImplementationProxy GetMenuService([NotNull] this IWorkingContext workingContext)
{
MenuService dlc = workingContext.GetRequiredDlc<MenuService>("Siemens.Automation.FrameApplication.Menu.MenuService");
return new MenuServiceImplementationProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Proxies/Backup/OmsBackupHelperProxy.cs
using System;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.Backup
{
public class OmsBackupHelperProxy
{
OmsBackupHelper OmsBackupHelper;
public OmsBackupHelperProxy(ClientSession clientSession, Func<string, bool> logDiagnosticsInformation)
{
OmsBackupHelper = new OmsBackupHelper(clientSession, logDiagnosticsInformation);
}
public bool ContinueReadNextBackupBinaryData
{
get
{
return OmsBackupHelper.ContinueReadNextBackupBinaryData;
}
}
public static bool CheckIfOmsModelSupportsBackupObject(ClientSession clientSession)
{
return OmsBackupHelper.CheckIfOmsModelSupportsBackupObject(clientSession);
}
public UploadResult CreateOmsBackupObject()
{
BackupPlusUpload.UploadResult result = OmsBackupHelper.CreateOmsBackupObject();
return (UploadResult)result;
}
public UploadResult DownloadOmsBackupObject()
{
BackupPlusUpload.UploadResult result = OmsBackupHelper.DownloadOmsBackupObject();
return (UploadResult)result;
}
public byte[] ReadNextBackupBinaryData()
{
return OmsBackupHelper.ReadNextBackupBinaryData();
}
public enum UploadResult
{
None,
NotSupportedByOfflineOmsModel,
NotSupportedByOnlineOmsModel,
WrongInterface,
UploadOnlineBackupFailed,
Canceled,
Success,
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreContextExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PLCMessaging;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static class ICoreContextExtensions
{
public static ICoreObject CreateTempControllerTarget(this ICoreContext projectContext,
string configObjectTypeName, string plcName)
{
return Reflector.RunStaticMethodByName(typeof(BLBlockProcessor),
"CreateTempControllerTarget",
ReflectionWays.SystemReflection,
projectContext, configObjectTypeName, plcName) as ICoreObject;
}
public static PLCMsgConnector GetPlcmService(this ICoreContext coreContext)
{
return ((IDlc)coreContext).WorkingContext.DlcManager.Load("Siemens.Simatic.PLCMessaging.PLCMsgConnector") as PLCMsgConnector;
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OmsNodeControlProxy.cs
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OmsNodeControlProxy
{
private IOmsNodeControl NodeControl;
public OmsNodeControlProxy(IOmsNodeControl nodeControl)
{
NodeControl = nodeControl;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.DlcContainer.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Dlc
{
public static partial class IWorkingContextExtensions
{
internal static IDlcCache GetGlobalSingletonCache(this IWorkingContext workingContext)
{
var manager = workingContext.DlcManager.GetDlcLifetimeManager();
var cache = Reflector.GetInstanceFieldByName(manager, "m_GlobalSingletonCache") as IDlcCache;
return cache;
}
internal static IDlcCache GetSingletonCache(this IWorkingContext workingContext)
{
var manager = workingContext.DlcManager.GetDlcLifetimeManager();
var cache = Reflector.GetInstanceFieldByName(manager, "m_SingletonCache") as IDlcCache;
return cache;
}
internal static IDlcCache GetNonSingletonCache(this IWorkingContext workingContext)
{
var manager = workingContext.DlcManager.GetDlcLifetimeManager();
var cache = Reflector.GetInstanceFieldByName(manager, "m_NonSingletonCache") as IDlcCache;
return cache;
}
public static List<IDlcMetaInfo> GetGlobalSingletonCache_MetaInfo(this IWorkingContext workingContext)
{
var metainfos = new List<IDlcMetaInfo>();
var cache = workingContext.GetGlobalSingletonCache();
var dlcs = cache.Dlcs;
foreach(var dlc in dlcs)
{
var meta = cache.FindDlcMetaInfo(dlc);
metainfos.Add(meta);
}
return metainfos;
}
public static List<IDlcMetaInfo> GetSingletonCache_MetaInfo(this IWorkingContext workingContext)
{
var metainfos = new List<IDlcMetaInfo>();
var cache = workingContext.GetSingletonCache();
var dlcs = cache.Dlcs;
foreach (var dlc in dlcs)
{
var meta = cache.FindDlcMetaInfo(dlc);
metainfos.Add(meta);
}
return metainfos;
}
public static List<IDlcMetaInfo> GetNonSingletonCache_MetaInfo(this IWorkingContext workingContext)
{
var metainfos = new List<IDlcMetaInfo>();
var cache = workingContext.GetNonSingletonCache();
var dlcs = cache.Dlcs;
foreach (var dlc in dlcs)
{
var meta = cache.FindDlcMetaInfo(dlc);
metainfos.Add(meta);
}
return metainfos;
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamClientInfoEventArgsProxy.cs
using System;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamClientInfoEventArgsProxy: IOamClientInfoEventArgs
{
public IOamClientInfoEventArgs Args;
public byte[] Buffer;
public object OamSource;
public object ClientSource;
public OamClientInfoEventArgsProxy(IOamClientInfoEventArgs args)
{
Args = args;
}
public override TimeSpan ElapsedTime
{
get
{
return Args.ElapsedTime;
}
}
public override int Flags
{
get
{
return Args.Flags;
}
}
public override OamCallbackMessage Message
{
get
{
return Args.Message;
}
}
public override int ReferenceCount
{
get
{
return Args.ReferenceCount;
}
}
public override DateTime TimeStamp
{
get
{
return Args.TimeStamp;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObjectExtensions.Logic.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.Lang.Model.Blocks;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.Utilities.Toolbox;
using YZX.Tia.Proxies;
using Reflection;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static BlockEditorLogicBase GetPLBlockEditorLogic(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
PLBlockEditorLogic pl = new PLBlockEditorLogic();
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
pl.PostAttach();
EditorPayload ep = new EditorPayload(block, ViewWorkingContext, serviceContainer);
pl.SetPayload(ep);
OnlineManagerBase OnlineManager = pl.OnlineManager;
return pl;
}) as BlockEditorLogicBase;
}
public static BlockEditorLogicBase GetGraphBlockEditorLogic(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
GraphBlockEditorLogic pl = new GraphBlockEditorLogic();
if (ViewWorkingContext == null)
{
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
}
else
{
pl.Attach(ViewWorkingContext);
}
pl.PostAttach();
try
{
pl.SetPayload(block);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return pl;
}) as BlockEditorLogicBase;
}
public static void GetBlockTypeAndLanguage(this ICoreObject coreObject,
out BlockType blockType,
out ProgrammingLanguage blockLanguage)
{
blockType = BlockType.Undef;
blockLanguage = ProgrammingLanguage.Undef;
Reflector.RunStaticMethodByName(typeof(EditorStarterFacade),
"GetBlockTypeAndLanguage",
ReflectionWays.SystemReflection,
coreObject, blockType, blockLanguage);
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/ViewManagerProxy.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
using Siemens.Automation.FrameApplication.WindowManager;
using Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ViewManagerProxy
{
ViewManager ViewManager;
public IViewManager IViewManager
{
get
{
return ViewManager as IViewManager;
}
}
IViewManagerInternal IViewManagerInternal
{
get
{
return ViewManager as IViewManagerInternal;
}
}
public IFrameCreator IFrameCreator
{
get
{
return ViewManager as IFrameCreator;
}
}
IViewManagerTestSupport ViewManagerTestSupport
{
get
{
return ViewManager as IViewManagerTestSupport;
}
}
public IWorkingContext WorkingContext
{
get
{
return Reflector.GetInstanceFieldByName(ViewManager,
"m_WorkingContext",
ReflectionWays.SystemReflection) as IWorkingContext;
}
}
public ViewManagerProxy(IViewManager manager)
{
ViewManager = manager as ViewManager;
}
public IFrame Show(string viewId, object payload=null)
{
return IFrameCreator.Show(viewId, payload);
}
public IFrameGroup CreateFrameGroup(IFrame commonParent)
{
return new FrameGroup(WorkingContext, commonParent);
}
public bool CanCreateEditorFrameGroup()
{
return IViewManager.CanCreateEditorFrameGroup();
}
public IEditorFrameGroup CreateEditorFrameGroup()
{
return IViewManager.CreateEditorFrameGroup();
}
public IView CreateView(string viewId, object payload=null)
{
return IViewManager.CreateView(viewId, payload);
}
public bool IsAvailableViewId(string viewId)
{
return IViewManagerInternal.IsAvailableViewId(viewId);
}
public string GetViewFrameId(string viewId)
{
return IViewManagerInternal.GetViewFrameId(viewId);
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Proxies/ThreadSynchronizerProxy.cs
using System;
using System.Threading;
using System.ComponentModel;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.UI.Controls;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public class ThreadSynchronizerProxy
{
ThreadSynchronizer TS;
public ISynchronizer Synchronize
{
get
{
return TS as ISynchronizer;
}
}
public ThreadSynchronizerProxy(ISynchronizeInvoke isi)
{
ThreadSynchronizer ts = isi as ThreadSynchronizer;
TS = ts;
}
public void SetMainThread(Thread thread)
{
Reflector.RunInstanceMethodByName(
TS,
"SetMainThread",
ReflectionWays.SystemReflection,
thread);
}
public event EventHandler Runed;
public void Run(Form f= null)
{
if(Synchronize == null)
{
return;
}
if (Synchronize.IsOperational)
{
}
else
{
if(f == null)
{
Synchronize.Run();
}
else
{
Synchronize.Run(f);
}
Runed(this, null);
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/GraphDrawSettingsProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Controls;
using Siemens.Simatic.PlcLanguages.GraphEditor;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class GraphDrawSettingsProxy
{
internal GraphDrawSettings GraphDrawSettings;
internal GraphDrawSettingsProxy(GraphDrawSettings settings)
{
GraphDrawSettings = settings;
}
public Font DefaultFont
{
get
{
return GraphDrawSettings.DefaultFont;
}
}
public Pen ConnectionPenThin
{
get
{
return GraphDrawSettings.ConnectionPenThin;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPenThin", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectionPenSelectedThin
{
get
{
return GraphDrawSettings.ConnectionPenSelectedThin;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPenSelectedThin", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectionPenSelectionThin
{
get
{
return GraphDrawSettings.ConnectionPenSelectionThin;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPenSelectionThinInactive", value,
ReflectionWays.SystemReflection);
}
}
public Brush ConnectionBrush
{
get
{
return GraphDrawSettings.ConnectionBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush ConnectionBrushSelection
{
get
{
return GraphDrawSettings.ConnectionBrushSelection;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionBrushSelectionInactive", value,
ReflectionWays.SystemReflection);
}
}
public Brush ConnectionBrushSelected
{
get
{
return GraphDrawSettings.ConnectionBrushSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionBrushSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush PseudoDeletedBrush
{
get
{
return GraphDrawSettings.PseudoDeletedBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_PseudoDeletedBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen PseudoDeletedPen
{
get
{
return GraphDrawSettings.PseudoDeletedPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_PseudoDeletedPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen SequenceFocusPen
{
get
{
return GraphDrawSettings.SequenceFocusPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InactiveFocusPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen FocusBackgroundPen
{
get
{
return GraphDrawSettings.FocusBackgroundPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InactiveFocusBackgroundPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen InactiveFocusBackgroundPen
{
get
{
return GraphDrawSettings.InactiveFocusBackgroundPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InactiveFocusBackgroundPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen InactiveFocusPen
{
get
{
return GraphDrawSettings.InactiveFocusPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InactiveFocusPen", value,
ReflectionWays.SystemReflection);
}
}
public Brush SeqPaletteBrushSelected
{
get
{
return GraphDrawSettings.SeqPaletteBrushSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SeqPaletteBrushSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush SeqPaletteBrush
{
get
{
return GraphDrawSettings.SeqPaletteBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SeqPaletteBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen SeqPaletteBorderPen
{
get
{
return GraphDrawSettings.SeqPaletteBorderPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SeqPaletteBorderPen", value,
ReflectionWays.SystemReflection);
}
}
public Font PaletteHeaderFont
{
get
{
return GraphDrawSettings.PaletteHeaderFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_PaletteHeaderFont", value,
ReflectionWays.SystemReflection);
}
}
public Color CommentForeColor
{
get
{
return GraphDrawSettings.CommentForeColor;
}
}
public Brush CommentForeBrush
{
get
{
return GraphDrawSettings.CommentForeBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_CommentForeBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectionPen
{
get
{
return GraphDrawSettings.ConnectionPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectionPenSelected
{
get
{
return GraphDrawSettings.ConnectionPenSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPenSelected", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectionPenSelection
{
get
{
return GraphDrawSettings.ConnectionPenSelection;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ConnectionPenSelectionInactive", value,
ReflectionWays.SystemReflection);
}
}
public Brush JumpTargetArrowBrush
{
get
{
return GraphDrawSettings.JumpTargetArrowBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_JumpTargetArrowBrush", value,
ReflectionWays.SystemReflection);
}
}
public Font TransitionNumberFont
{
get
{
return GraphDrawSettings.TransitionNumberFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TransitionNumberFontPrint", value,
ReflectionWays.SystemReflection);
}
}
public Font TransitionNameFont
{
get
{
return GraphDrawSettings.TransitionNameFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TransitionNameFont", value,
ReflectionWays.SystemReflection);
}
}
public Font TransitionNumberFontBig
{
get
{
return GraphDrawSettings.TransitionNumberFontBig;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TransitionNumberFontBig", value,
ReflectionWays.SystemReflection);
}
}
public Font TransitionNameFontBig
{
get
{
return GraphDrawSettings.TransitionNameFontBig;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TransitionNameFontBig", value,
ReflectionWays.SystemReflection);
}
}
public Pen SimultaneousBranchPenSelected
{
get
{
return GraphDrawSettings.SimultaneousBranchPenSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SimultaneousBranchPenSelected", value,
ReflectionWays.SystemReflection);
}
}
public Pen SimultaneousBranchPenSelection
{
get
{
return GraphDrawSettings.SimultaneousBranchPenSelection;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SimultaneousBranchPenSelectionInactive", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepBackground
{
get
{
return GraphDrawSettings.StepBackground;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackground", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepBackgroundSelected
{
get
{
return GraphDrawSettings.StepBackgroundSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackgroundSelectedInactive", value,
ReflectionWays.SystemReflection);
}
}
public Pen StepMiddleLinePen
{
get
{
return GraphDrawSettings.StepMiddleLinePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepMiddleLinePen", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepForeBrushSelected
{
get
{
return GraphDrawSettings.StepForeBrushSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepForeBrushSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepForeBrushSymbolic
{
get
{
return GraphDrawSettings.StepForeBrushSymbolic;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepForeBrushSymbolic", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepForeBrushAbsolute
{
get
{
return GraphDrawSettings.StepForeBrushAbsolute;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepForeBrushAbsolute", value,
ReflectionWays.SystemReflection);
}
}
public StringFormat StepStringFormatLeftAligned
{
get
{
return GraphDrawSettings.StepStringFormatLeftAligned;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepStringFormatLeftAligned", value,
ReflectionWays.SystemReflection);
}
}
public StringFormat StepStringFormatCenterAligned
{
get
{
return GraphDrawSettings.StepStringFormatCenterAligned;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepStringFormatCenterAligned", value,
ReflectionWays.SystemReflection);
}
}
public Font StepNumberFont
{
get
{
return GraphDrawSettings.StepNumberFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNumberFont", value,
ReflectionWays.SystemReflection);
}
}
public Font StepNameFont
{
get
{
return GraphDrawSettings.StepNameFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNameFont", value,
ReflectionWays.SystemReflection);
}
}
public Font StepNumberFontBig
{
get
{
return GraphDrawSettings.StepNumberFontBig;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNumberFontBig", value,
ReflectionWays.SystemReflection);
}
}
public Font StepNameFontBig
{
get
{
return GraphDrawSettings.StepNameFontBig;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNameFontBig", value,
ReflectionWays.SystemReflection);
}
}
public StringFormat TransitionStringFormat
{
get
{
return GraphDrawSettings.TransitionStringFormat;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TransitionStringFormat", value,
ReflectionWays.SystemReflection);
}
}
public Color HighlightColor
{
get
{
return GraphDrawSettings.HighlightColor;
}
}
public Brush HighlightBrush
{
get
{
return GraphDrawSettings.HighlightBrush;
}
}
public Pen HighlightPen
{
get
{
return GraphDrawSettings.HighlightPen;
}
}
public Brush HighlightIndicatorBrush
{
get
{
return GraphDrawSettings.HighlightIndicatorBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_MarkHighlightBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush HighlightFrameBrush
{
get
{
return GraphDrawSettings.HighlightFrameBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightFrameBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush MarkBrush
{
get
{
return GraphDrawSettings.MarkBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_MarkBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush MarkFrameBrush
{
get
{
return GraphDrawSettings.MarkFrameBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_MarkFrameBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush JumpHighlightBrush
{
get
{
return GraphDrawSettings.JumpHighlightBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_JumpHighlightBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen HighlightAreaFramePen
{
get
{
return GraphDrawSettings.HighlightAreaFramePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightAreaFramePen", value,
ReflectionWays.SystemReflection);
}
}
public Pen HighlightAreaFramePenInactive
{
get
{
return GraphDrawSettings.HighlightAreaFramePenInactive;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightAreaFramePenInactive", value,
ReflectionWays.SystemReflection);
}
}
public Color HighlightAreaFrameColor
{
get
{
return GraphDrawSettings.HighlightAreaFrameColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightAreaFrameColor", value,
ReflectionWays.SystemReflection);
}
}
public Color HighlightAreaFrameColorInactive
{
get
{
return GraphDrawSettings.HighlightAreaFrameColorInactive;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightAreaFrameColorInactive", value,
ReflectionWays.SystemReflection);
}
}
public Pen MovingWirePen
{
get
{
return GraphDrawSettings.MovingWirePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_MovingWirePen", value,
ReflectionWays.SystemReflection);
}
}
public Pen HighlightMovingWirePen
{
get
{
return GraphDrawSettings.HighlightMovingWirePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightMovingWirePen", value,
ReflectionWays.SystemReflection);
}
}
public Pen HighlightMovingWirePenSim
{
get
{
return GraphDrawSettings.HighlightMovingWirePenSim;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightMovingWirePenSim", value,
ReflectionWays.SystemReflection);
}
}
public AdjustableArrowCap HighlightMovingWireArrowCap
{
get
{
return GraphDrawSettings.HighlightMovingWireArrowCap;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_HighlightMovingWireArrowCap", value,
ReflectionWays.SystemReflection);
}
}
public Pen SetJumpTargetPenValid
{
get
{
return GraphDrawSettings.SetJumpTargetPenValid;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SetJumpTargetPenValid", value,
ReflectionWays.SystemReflection);
}
}
public Pen SetJumpTargetPenInvalid
{
get
{
return GraphDrawSettings.SetJumpTargetPenInvalid;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SetJumpTargetPenInvalid", value,
ReflectionWays.SystemReflection);
}
}
public Pen AlarmViewForePen
{
get
{
return GraphDrawSettings.AlarmViewForePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmViewPen", value,
ReflectionWays.SystemReflection);
}
}
public Brush AlarmViewForeBrush
{
get
{
return GraphDrawSettings.AlarmViewForeBrush;
}
}
public Font AlarmViewFont
{
get
{
return GraphDrawSettings.AlarmViewFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmViewFont", value,
ReflectionWays.SystemReflection);
}
}
public Font AlarmTextFont
{
get
{
return GraphDrawSettings.AlarmTextFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmViewTextBoxFont", value,
ReflectionWays.SystemReflection);
}
}
public Font NavAlarmViewFont
{
get
{
return GraphDrawSettings.NavAlarmViewFont;
}
}
public Color NavAlarmViewBackColor
{
get
{
return GraphDrawSettings.NavAlarmViewBackColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NavAlarmViewBackColor", value,
ReflectionWays.SystemReflection);
}
}
public Brush NavAlarmViewBackBrush
{
get
{
return GraphDrawSettings.NavAlarmViewBackBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NavAlarmViewBackBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush AlarmTextBackBrush
{
get
{
return GraphDrawSettings.AlarmTextBackBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmTextBackBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush AlarmTextDisabledBrush
{
get
{
return GraphDrawSettings.AlarmTextDisabledBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmTextDisabledBrush", value,
ReflectionWays.SystemReflection);
}
}
public Color AlarmTextBackColor
{
get
{
return GraphDrawSettings.AlarmTextBackColor ;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_AlarmTextBackColor", value,
ReflectionWays.SystemReflection);
}
}
public Color AlarmViewBackColor
{
get
{
return GraphDrawSettings.AlarmViewBackColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ViewBackColor", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineActiveBrush
{
get
{
return GraphDrawSettings.OnlineActiveBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineActiveBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineDisturbedBrush
{
get
{
return GraphDrawSettings.OnlineDisturbedBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineDisturbedBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineWarningBrush
{
get
{
return GraphDrawSettings.OnlineWarningBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineWarningBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineSyncProposalBrush
{
get
{
return GraphDrawSettings.OnlineSyncProposalBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineSyncProposalBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen OnlineActivePen
{
get
{
return GraphDrawSettings.OnlineActivePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineActivePen", value,
ReflectionWays.SystemReflection);
}
}
public Pen OnlineActivePenThin
{
get
{
return GraphDrawSettings.OnlineActivePenThin;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineActivePenThin", value,
ReflectionWays.SystemReflection);
}
}
public Pen OnlineActivePenSimBranchSelected
{
get
{
return GraphDrawSettings.OnlineActivePenSimBranchSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineActivePenSimBranchSelected", value,
ReflectionWays.SystemReflection);
}
}
public Pen OnlineDisturbedPenWarning
{
get
{
return GraphDrawSettings.OnlineDisturbedPenWarning;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineDisturbedPenWarning", value,
ReflectionWays.SystemReflection);
}
}
public Pen OnlineDisturbedPenError
{
get
{
return GraphDrawSettings.OnlineDisturbedPenError;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineDisturbedPenError", value,
ReflectionWays.SystemReflection);
}
}
public Font OnlineStepTimeFont
{
get
{
return GraphDrawSettings.OnlineStepTimeFont;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineStepTimeFont", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepTimeBrush
{
get
{
return GraphDrawSettings.OnlineStepTimeBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineStepTimeBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineNotMonitoredBrush
{
get
{
return GraphDrawSettings.OnlineNotMonitoredBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnlineNotMonitoredBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepForeBrushSelectedActive
{
get
{
return GraphDrawSettings.OnlineStepForeBrushSelectedActive;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackgroundSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepForeBrushSelectedWarning
{
get
{
return this.OnlineStepForeBrushSelectedActive;
}
}
public Brush OnlineStepForeBrushSelectedError
{
get
{
return GraphDrawSettings.OnlineStepForeBrushSelectedError;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepForeBrushSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepBackBrushSelectedActive
{
get
{
return GraphDrawSettings.OnlineStepBackBrushSelectedActive;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackgroundSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepBackBrushSelectedWarning
{
get
{
return GraphDrawSettings.OnlineStepBackBrushSelectedWarning;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackgroundSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush OnlineStepBackBrushSelectedError
{
get
{
return GraphDrawSettings.OnlineStepBackBrushSelectedError;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepBackgroundSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepNotCompared
{
get
{
return GraphDrawSettings.StepNotCompared;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNotComparedBackground", value,
ReflectionWays.SystemReflection);
}
}
public Pen StepNotComparedMiddleLinePen
{
get
{
return GraphDrawSettings.StepNotComparedMiddleLinePen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepNotComparedMiddleLinePen", value,
ReflectionWays.SystemReflection);
}
}
public Pen NotComparedConnectionPen
{
get
{
return GraphDrawSettings.NotComparedConnectionPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NotComparedConnectionPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen NotComparedConnectionPenThin
{
get
{
return GraphDrawSettings.NotComparedConnectionPenThin;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NotComparedConnectionPenThin", value,
ReflectionWays.SystemReflection);
}
}
public Brush NotComparedConnectionBrush
{
get
{
return GraphDrawSettings.NotComparedConnectionBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NotComparedConnectionBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush NotComparedForeBrushAbsolute
{
get
{
return GraphDrawSettings.NotComparedForeBrushAbsolute;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NotComparedForeBrushAbsolute", value,
ReflectionWays.SystemReflection);
}
}
public Brush NotComparedFontBrush
{
get
{
return GraphDrawSettings.NotComparedFontBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NotComparedFontBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen SimultaneousBranchComparePenSelected
{
get
{
return GraphDrawSettings.SimultaneousBranchComparePenSelected;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SimultaneousBranchComparePenSelected", value,
ReflectionWays.SystemReflection);
}
}
public Brush StepTransNumberDifferenceBrush
{
get
{
return GraphDrawSettings.StepTransNumberDifferenceBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_StepTransNumberDifferenceBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush JumpDifferenceLilaBrush
{
get
{
return GraphDrawSettings.JumpDifferenceLilaBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_JumpDifferenceLilaBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush JumpDifferencePinkBrush
{
get
{
return GraphDrawSettings.JumpDifferencePinkBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_JumpDifferencePinkBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush CompareSelectionModeBrush
{
get
{
return GraphDrawSettings.CompareSelectionModeBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_CompareSelectionModeBrush", value,
ReflectionWays.SystemReflection);
}
}
public Pen JumpTargetPen
{
get
{
return GraphDrawSettings.JumpTargetPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_JumpTargetPen", value,
ReflectionWays.SystemReflection);
}
}
public Color ForeColor
{
get
{
return GraphDrawSettings.ForeColor;
}
}
public Color InactiveSelectionColor
{
get
{
return GraphDrawSettings.InactiveSelectionColor;
}
}
public Color InactiveBackColor
{
get
{
return GraphDrawSettings.InactiveBackColor;
}
}
public Color SelectionColor
{
get
{
return GraphDrawSettings.SelectionColor;
}
}
public Color SelectionFrontColor
{
get
{
return GraphDrawSettings.SelectionFrontColor;
}
}
public Color SelectionBoxFrameColor
{
get
{
return GraphDrawSettings.SelectionBoxFrameColor;
}
}
public Color SelectionBoxInsideColor
{
get
{
return GraphDrawSettings.SelectionBoxInsideColor;
}
}
public Color JumpLineColor
{
get
{
return GraphDrawSettings.JumpLineColor;
}
}
public Color FocusColor
{
get
{
return GraphDrawSettings.FocusColor;
}
}
public Color BackColor
{
get
{
return GraphDrawSettings.BackColor;
}
}
public Color NavigationViewBackColor
{
get
{
return GraphDrawSettings.NavigationViewBackColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ViewBackColor", value,
ReflectionWays.SystemReflection);
}
}
public Color NavigationViewActiveColor
{
get
{
return GraphDrawSettings.NavigationViewActiveColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NavigationViewActiveColor", value,
ReflectionWays.SystemReflection);
}
}
public Color ConnectableBranchColor
{
get
{
return GraphDrawSettings.ConnectableBranchColor;
}
}
public Color NotConnectableBranchColor
{
get
{
return GraphDrawSettings.NotConnectableBranchColor;
}
}
public Color ReadOnlyColor
{
get
{
return GraphDrawSettings.ReadOnlyColor;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_ReadOnlyColor", value,
ReflectionWays.SystemReflection);
}
}
public Brush FocusBrush
{
get
{
return GraphDrawSettings.FocusBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TreeFocusBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush ForeBrush
{
get
{
return GraphDrawSettings.ForeBrush;
}
}
public Brush SelectionBrush
{
get
{
return GraphDrawSettings.SelectionBrush;
}
}
public Brush SelectionFrontBrush
{
get
{
return GraphDrawSettings.SelectionFrontBrush;
}
}
public Brush SelectionBoxInsideBrush
{
get
{
return GraphDrawSettings.SelectionBoxInsideBrush;
}
}
public Brush HoverBrush
{
get
{
return GraphDrawSettings.HoverBrush;
}
}
public Brush NavigationViewActiveBrush
{
get
{
return GraphDrawSettings.NavigationViewActiveBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_NavigationViewActiveBrush", value,
ReflectionWays.SystemReflection);
}
}
public Brush NavigationViewBackBrush
{
get
{
return GraphDrawSettings.NavigationViewBackBrush;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InactiveFocusBackgroundPen", value,
ReflectionWays.SystemReflection);
}
}
public Brush SelectedTextBackgroundBrush
{
get
{
return GraphDrawSettings.SelectedTextBackgroundBrush;
}
}
public Brush SelectedTextForegroundBrush
{
get
{
return GraphDrawSettings.SelectedTextForegroundBrush;
}
}
public Pen ForePen
{
get
{
return GraphDrawSettings.ForePen;
}
}
public Pen SelectionPen
{
get
{
return GraphDrawSettings.SelectionPen;
}
}
public Pen NavigationViewPermOpSelectionPen
{
get
{
return GraphDrawSettings.NavigationViewPermOpSelectionPen;
}
}
public Pen SelectionFrontPen
{
get
{
return GraphDrawSettings.SelectionFrontPen;
}
}
public Pen SelectionBoxFramePen
{
get
{
return GraphDrawSettings.SelectionBoxFramePen;
}
}
public Pen JumpLinePen
{
get
{
return GraphDrawSettings.JumpLinePen;
}
}
public Pen FocusPen
{
get
{
return GraphDrawSettings.FocusPen;
}
}
public Pen FocusPenForTreeItems
{
get
{
return GraphDrawSettings.FocusPenForTreeItems;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_TreeFocusPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen ConnectableBranchPen
{
get
{
return GraphDrawSettings.ConnectableBranchPen;
}
}
public Pen NotConnectableBranchPen
{
get
{
return GraphDrawSettings.NotConnectableBranchPen;
}
}
public Pen DottedLineTransitionPen
{
get
{
return GraphDrawSettings.DottedLineTransitionPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_DottedLineTransitionPen", value,
ReflectionWays.SystemReflection);
}
}
public Pen DottedLineTogglerPen
{
get
{
return GraphDrawSettings.DottedLineTogglerPen;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_DottedLineTogglerPen", value,
ReflectionWays.SystemReflection);
}
}
#region ICON
public AccessibleIcon SupervisionErrorIcon
{
get
{
return GraphDrawSettings.SupervisionErrorIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_SupervisionErrorIcon", value,
ReflectionWays.SystemReflection);
}
}
public AccessibleIcon InterlockWarningIcon
{
get
{
return GraphDrawSettings.InterlockWarningIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_InterlockWarningIcon", value,
ReflectionWays.SystemReflection);
}
}
public AccessibleIcon OnEqualIcon
{
get
{
return GraphDrawSettings.OnEqualIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnEqualIcon", value,
ReflectionWays.SystemReflection);
}
}
public AccessibleIcon OnUnEqualIcon
{
get
{
return GraphDrawSettings.OnUnEqualIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OnUnEqualIcon", value,
ReflectionWays.SystemReflection);
}
}
public AccessibleIcon OffUnequalIcon
{
get
{
return GraphDrawSettings.OffUnequalIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_OffUnequalIcon", value,
ReflectionWays.SystemReflection);
}
}
public AccessibleIcon EmptyIcon
{
get
{
return GraphDrawSettings.EmptyIcon;
}
set
{
Reflector.SetInstanceFieldByName(GraphDrawSettings, "m_MarkHighlightBrush", value,
ReflectionWays.SystemReflection);
}
}
#endregion ICON
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/Upload/UploadOnlineAccessBaseProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class UploadOnlineAccessBaseProxy
{
UploadOnlineAccessBase UploadOnlineAccessBase;
internal UploadOnlineAccessBaseProxy(UploadOnlineAccessBase access)
{
UploadOnlineAccessBase = access;
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/OnlineCommonHelperProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using OCH = Siemens.Automation.DomainServices.UI.OnlineCommon.OnlineCommonHelper;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies.OnlineService
{
public class OnlineCommonHelperProxy
{
internal OCH och;
internal OnlineCommonHelperProxy(OCH helper)
{
och = helper;
}
public OnlineCommonHelperProxy(OnlineCommonParameter parameter,
string dialogmode)
{
OnlineCommonDialogType ocdt = OnlineCommonDialogType.Undefined;
switch (dialogmode)
{
case "Undefined":
break;
case "GoOnline":
ocdt = OnlineCommonDialogType.GoOnline;
break;
case "ExtendedDownload":
ocdt = OnlineCommonDialogType.ExtendedDownload;
break;
case "LifeList":
ocdt = OnlineCommonDialogType.LifeList;
break;
case "HardwareDetection":
ocdt = OnlineCommonDialogType.HardwareDetection;
break;
case "SelectTarget":
ocdt = OnlineCommonDialogType.SelectTarget;
break;
case "ShowHideInterfaces":
ocdt = OnlineCommonDialogType.ShowHideInterfaces;
break;
case "GlobalConnectionSettings":
ocdt = OnlineCommonDialogType.GlobalConnectionSettings;
break;
}
och = new OCH(parameter, ocdt);
}
public List<OnlineCommonNodeProxy> GetUsableProjectNodes()
{
var nodes = och.GetUsableProjectNodes();
return nodes.ConvertAll(new Converter<OnlineCommonNode, OnlineCommonNodeProxy>(
OnlineServiceConverters.OnlineCommonNodeProxy));
}
}
}
<file_sep>/ShowModuleState/Program.cs
using System;
using System.Windows.Forms;
using YZX.Tia;
namespace ShowModuleState
{
static class Program
{
[STAThread]
static int Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
app = new TiaStarter();
app.StartUpPowerManagementThread();
app.Run(new ShowModuleStateForm());
return 0;
}
private static void CurrentDomain_AssemblyLoad(
object sender,
AssemblyLoadEventArgs args)
{
var s_dir = @"D:\Program Files\Siemens\Automation\Portal V14\Bin";
var d_dir = @"E:\Github\yanzixiang\Published\YZX.TIA\ShowModuleState\ShowModuleStateV14\Bin";
if (args.LoadedAssembly.GlobalAssemblyCache)
{
}
else
{
var filename = System.IO.Path.GetFileName(args.LoadedAssembly.CodeBase);
string s_path, d_path;
if (filename.EndsWith("resources.DLL")) {
s_path = System.IO.Path.Combine(s_dir, "en",filename);
d_path = System.IO.Path.Combine(d_dir, "en",filename);
} else
{
s_path = System.IO.Path.Combine(s_dir, filename);
d_path = System.IO.Path.Combine(d_dir, filename);
}
if (System.IO.File.Exists(s_path))
{
if (!System.IO.File.Exists(d_path))
{
System.IO.File.Copy(s_path, d_path);
}
}
else
{
Console.WriteLine(string.Format("{0} Not exists", s_path));
}
}
}
public static TiaStarter app = null;
}
}
<file_sep>/YZX.TIA/Extensions/DebugDeviceExtender.cs
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
namespace YZX.Tia.Extensions
{
public static class DebugDeviceExtender
{
private const int s_PduSize300Plc = 240;
private const int s_PduSize400Plc = 480;
public static bool Is300Plc(this IDebugDevice debugDevice)
{
return debugDevice.TisCapabilities.iPduSize == 240;
}
public static bool Is400Plc(this IDebugDevice debugDevice)
{
return debugDevice.TisCapabilities.iPduSize == 480;
}
public static bool IsInHalt(this IDebugDevice debugDevice)
{
return debugDevice.GetCondition() == Condition.Halt;
}
public static bool IsOnline(this IDebugDevice debugDevice)
{
return debugDevice.ConnectionState == ConnectionState.Online;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.Context.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using YZX.Tia.Proxies;
using YZX.Tia.Extensions;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Extensions.FrameApplication;
using YZX.Tia.Proxies.Dlc;
namespace YZX.Tia
{
partial class TiaStarter
{
public static WorkingContext m_BusinessLogicApplicationContext;
public static WorkingContext m_ViewApplicationContext;
public static WorkingContext PersistenceWorkingContext;
public IWorkingContext projectWorkingContext;
public IWorkingContext projectViewWorkingContext;
public IWorkingContext projectPersistenceWorkingContext;
public PrimaryProjectUiWorkingContextManagerProxy PrimaryProjectUiWorkingContextManagerProxy;
public PrimaryProjectManagerProxy PrimaryProjectManagerProxy;
public IUIContextHolder UIContextHolder;
public IWorkingContext ProjectUIContext;
private void CreateWorkingContextHierarchy()
{
m_BusinessLogicApplicationContext = new WorkingContext(false,
WorkingContextEnvironment.Application,
AppId,
"Project"
);
m_BusinessLogicApplicationContext.ConstructServiceEvent += m_BusinessLogicApplicationContext_ConstructServiceEvent;
m_BusinessLogicApplicationContext.ServiceLoadedEvent += m_BusinessLogicApplicationContext_ServiceLoadedEvent;
m_BusinessLogicApplicationContext.ServiceAddedEvent += m_BusinessLogicApplicationContext_ServiceAddedEvent;
m_BusinessLogicApplicationContext.WorkingContextChildCreatedEvent += M_BusinessLogicApplicationContext_WorkingContextChildCreatedEvent;
m_BusinessLogicApplicationContext.AutoLoadDlcs();
WorkingContextProxy wcp = new WorkingContextProxy(m_BusinessLogicApplicationContext);
PlatformServiceContainer psc = wcp.PlatformServiceContainer;
m_ViewApplicationContext = new WorkingContext(true,
WorkingContextEnvironment.Application,
AppId,
"Project"
);
m_ViewApplicationContext.SiblingInBusinessLogicContext = m_BusinessLogicApplicationContext;
m_ViewApplicationContext.ConstructServiceEvent += M_ViewApplicationContext_ConstructServiceEvent;
m_ViewApplicationContext.ServiceLoadedEvent += M_ViewApplicationContext_ServiceLoadedEvent;
m_ViewApplicationContext.ServiceAddedEvent += M_ViewApplicationContext_ServiceAddedEvent;
m_ViewApplicationContext.AutoLoadDlcs();
PersistenceWorkingContext = new WorkingContext(m_ViewApplicationContext,
WorkingContextEnvironment.Persistence);
PrimaryProjectUiWorkingContextManagerProxy = m_ViewApplicationContext.GetPrimaryProjectUiWorkingContextManagerProxy();
PrimaryProjectManagerProxy =
PrimaryProjectUiWorkingContextManagerProxy.PrimaryProjectManager;
}
#region m_ViewApplicationContext Event
private void M_ViewApplicationContext_ServiceAddedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("M_ViewApplicationContext_ServiceAddedEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceType);
}
private void M_ViewApplicationContext_ConstructServiceEvent(object sender, ConstructServiceEventArgs e)
{
Console.WriteLine("M_ViewApplicationContext_ConstructServiceEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceInstance);
}
private void M_ViewApplicationContext_ServiceLoadedEvent(object sender,
ServiceChangedEventArgs e)
{
Console.WriteLine("M_ViewApplicationContext_ServiceLoadedEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceType);
}
#endregion
#region m_BusinessLogicApplicationContext Event
private void m_BusinessLogicApplicationContext_ServiceAddedEvent(object sender, ServiceChangedEventArgs e)
{
Console.WriteLine("m_BusinessLogicApplicationContext_ServiceAddedEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceType);
}
private void m_BusinessLogicApplicationContext_ConstructServiceEvent(object sender, ConstructServiceEventArgs e)
{
Console.WriteLine("m_BusinessLogicApplicationContext_ConstructServiceEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceInstance);
}
private void m_BusinessLogicApplicationContext_ServiceLoadedEvent(object sender,
ServiceChangedEventArgs e)
{
Console.WriteLine("m_BusinessLogicApplicationContext_ServiceLoadedEvent {0} -> {1}", e.ServiceCreatorType, e.ServiceType);
}
private void M_BusinessLogicApplicationContext_WorkingContextChildCreatedEvent(object sender, ChildCreatedEventArgs e)
{
Console.WriteLine("M_BusinessLogicApplicationContext_WorkingContextChildCreatedEvent {0}", e.ChildContext);
}
#endregion
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.OnlineServiceManager.cs
using System;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Threading;
using Siemens.Automation.ObjectFrame.Meta;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
namespace YZX.Tia
{
partial class TiaStarter
{
IOnlineServiceManager OnlineServiceManager
{
get
{
return OnlineMetaManagerFactory.GetServiceManager(projectWorkingContext);
}
}
#region OnlineServiceManager
public IOnlineFunctionProvider GetOnlineProvider(IObjectTypeInfo targetType, string onlineFunction)
{
return OnlineServiceManager.GetOnlineProvider(targetType, onlineFunction);
}
#endregion
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.WindowManager.cs
using Siemens.Automation.FrameApplication;
using YZX.Tia.Extensions;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia
{
partial class TiaStarter
{
public IWindowManager WindowManager
{
get
{
return m_ViewApplicationContext.GetWindowManager() as IWindowManager;
}
}
public WindowManagerProxy WindowManagerProxy
{
get
{
return m_ViewApplicationContext.GetWindowManagerProxy();
}
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.BlockEditor.cs
using System.Windows.Forms;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using YZX.Tia.Extensions.NetworkEditorFrame;
namespace YZX.Tia
{
partial class TiaStarter
{
public BlockEditorControlBase GetBlockEditor(ICoreObject pl)
{
UIContextHolder = PrimaryProjectUiWorkingContextManagerProxy.IUIContextHolder;
ProjectUIContext = UIContextHolder.ProjectUIContext;
IEditorStarter starter = ProjectUIContext.GetEditorStarterFacadeDlc();
OpenEditorContext openEditorContext = new OpenEditorContext(pl, ProjectUIContext);
OpenEditorResult result = starter.OpenEditor(openEditorContext);
if (result.HasEditor)
{
var ieditor = result.Editor;
var editor = ieditor as Editor;
var IEditorViewFrameProvider = editor as IEditorViewFrameProvider;
var control = IEditorViewFrameProvider.MainViewFrame.View.Control;
return control as BlockEditorControlBase;
}
else
{
return null;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Dlc/DlcObserverProxy.cs
using System;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.Dlc
{
public class DlcObserverProxy : IDlcObserver
{
public event EventHandler<DlcAttachedEventArgs> DlcAttachedEvent;
public void DlcAttached(IWorkingContext workingContext,
IDlcMetaInfo dlcMetaInfo, IDlc dlc)
{
DlcAttachedEvent?.Invoke(this,
new DlcAttachedEventArgs(workingContext,dlcMetaInfo,dlc));
}
public event EventHandler<DlcEventArgs> DlcDetachedEvent;
public void DlcDetached(IDlc dlc)
{
DlcDetachedEvent?.Invoke(this, new DlcEventArgs(dlc));
}
public event EventHandler<DlcInstanceClonedEventArgs> DlcInstanceClonedEvent;
public void DlcInstanceCloned(IWorkingContext workingContext,
IDlcMetaInfo dlcMetaInfo, IDlc dlcForCloning, IDlc clonedDlc)
{
DlcInstanceClonedEvent?.Invoke(this,
new DlcInstanceClonedEventArgs(workingContext, dlcMetaInfo, dlcForCloning, clonedDlc));
}
public event EventHandler<DlcInstanceCreatedEventArgs> DlcInstanceCreatedEvent;
public void DlcInstanceCreated(IDlcMetaInfo dlcMetaInfo, IDlc dlc)
{
DlcInstanceCreatedEvent?.Invoke(this,
new DlcInstanceCreatedEventArgs(dlcMetaInfo, dlc));
}
public event EventHandler<DlcEventArgs> DlcPostAttachedEvent;
public void DlcPostAttached(IDlc dlc)
{
DlcPostAttachedEvent?.Invoke(this, new DlcEventArgs(dlc));
}
public event EventHandler<DlcEventArgs> DlcPredetachedEvent;
public void DlcPredetached(IDlc dlc)
{
DlcPredetachedEvent?.Invoke(this, new DlcEventArgs(dlc));
}
public event EventHandler<WorkingContextEventArgs> WorkingContextClosedEvent;
public void WorkingContextClosed(IWorkingContext workingContext)
{
WorkingContextClosedEvent?.Invoke(this, new WorkingContextEventArgs(workingContext));
}
public event EventHandler<WorkingContextEventArgs> WorkingContextCreatedEvent;
public void WorkingContextCreated(IWorkingContext workingContext)
{
WorkingContextCreatedEvent?.Invoke(this, new WorkingContextEventArgs(workingContext));
}
public event EventHandler<ChildWorkingContextEventArgs> ChildWorkingContextCreatedEvent;
public void WorkingContextCreated(IWorkingContext parentWorkingContext,
IWorkingContext newWorkingContext)
{
ChildWorkingContextCreatedEvent?.Invoke(this,
new ChildWorkingContextEventArgs(parentWorkingContext, newWorkingContext));
}
}
public class ChildWorkingContextEventArgs
{
public IWorkingContext parentWorkingContext;
public IWorkingContext newWorkingContext;
public ChildWorkingContextEventArgs(IWorkingContext parentWorkingContext, IWorkingContext newWorkingContext)
{
this.parentWorkingContext = parentWorkingContext;
this.newWorkingContext = newWorkingContext;
}
}
public class WorkingContextEventArgs
{
public IWorkingContext workingContext;
public WorkingContextEventArgs(IWorkingContext workingContext)
{
this.workingContext = workingContext;
}
}
public class DlcInstanceClonedEventArgs
{
public IWorkingContext workingContext;
public IDlcMetaInfo dlcMetaInfo;
public IDlc dlcForCloning;
public IDlc clonedDlc;
public DlcInstanceClonedEventArgs(IWorkingContext workingContext,
IDlcMetaInfo dlcMetaInfo, IDlc dlcForCloning, IDlc clonedDlc)
{
this.workingContext = workingContext;
this.dlcMetaInfo = dlcMetaInfo;
this.dlcForCloning = dlcForCloning;
this.clonedDlc = clonedDlc;
}
}
public class DlcInstanceCreatedEventArgs:DlcEventArgs
{
public IDlcMetaInfo dlcMetaInfo;
public DlcInstanceCreatedEventArgs(IDlcMetaInfo dlcMetaInfo, IDlc dlc):base(dlc)
{
this.dlcMetaInfo = dlcMetaInfo;
}
}
public class DlcEventArgs
{
public IDlc dlc;
public DlcEventArgs(IDlc dlc)
{
this.dlc = dlc;
}
}
public class DlcAttachedEventArgs:DlcEventArgs
{
public IWorkingContext workingContext;
public IDlcMetaInfo dlcMetaInfo;
public DlcAttachedEventArgs(IWorkingContext workingContext, IDlcMetaInfo dlcMetaInfo, IDlc dlc):base(dlc)
{
this.workingContext = workingContext;
this.dlcMetaInfo = dlcMetaInfo;
}
}
}
<file_sep>/YZX.TIA/Proxies/QueryBasedControllerTargetLookupProxy.cs
using Siemens.Simatic.PlcLanguages.BlockLogic.OpenBlockHandling;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Proxies
{
public class QueryBasedControllerTargetLookupProxy
{
IControllerTargetLookup lookup;
public QueryBasedControllerTargetLookupProxy(ICoreContext coreContext)
{
lookup = new QueryBasedControllerTargetLookup(coreContext);
}
public ICoreObject FindControllerTargetByName(string name)
{
return lookup.FindControllerTargetByName(name);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/TiaStarter/TiaStarter.OnlineCommandInvoke.cs
using Siemens.Automation.DomainServices;
namespace YZX.Tia
{
partial class TiaStarter
{
public IOnlineCommandInvoke OnlineCommandInvoke
{
get
{
return projectWorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService.OnlineCommandInvoke") as IOnlineCommandInvoke;
}
}
}
}
<file_sep>/Siemens.Automation.Archiving.Test/Proxies/Archiving/ZipExtractorProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Archiving;
using Siemens.Automation.Archiving.Private;
namespace YZX.Tia.Proxies.Archiving
{
public class ZipExtractorProxy
{
ZipExtractor extractor;
public ZipExtractorProxy(IDirectory directory)
{
extractor = directory as ZipExtractor;
}
public Dictionary<string, object> GetFileInfos()
{
var infos = extractor.GetFileInfos();
var infodic = new Dictionary<string, object>();
foreach(var info in infos)
{
infodic[info.Key] = info.Value;
}
return infodic;
}
public IFile GetFile(object fileInfo)
{
ZipArchivedFileInfo info = fileInfo as ZipArchivedFileInfo;
return extractor.GetFile(info);
}
public IEnumerable<IFile> GetFiles()
{
return extractor.GetFiles();
}
public string GetPasswordString()
{
return extractor.GetPasswordString();
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.Project.cs
using Siemens.Automation.Basics;
using Siemens.Simatic.FPlus.FEngine.Interface.Utilities;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IWorkingContext GetProjectWorkingContext(this IWorkingContext inputWorkingContext)
{
return WorkingContextFinder.GetProjectWorkingContext(inputWorkingContext);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.Hwcn.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Simatic.HwConfiguration.Basics.Basics;
using Siemens.Simatic.HwConfiguration.Diagnostic.Basics;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.DataSetServices.Server;
using Siemens.Simatic.HwConfiguration.EditorSupport.EditorSupport.Editor;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using Siemens.Simatic.HwConfiguration.Basics.Basics.Actions;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static EditorController GetHwcnEditorController([NotNull] this IWorkingContext workingContext)
{
EditorController EditorController = workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.EditorSupport.EditorController")
as EditorController;
return EditorController;
}
public static FunctionProvider GetOnlineFunctionProvider([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.FunctionProvider") as FunctionProvider;
}
public static OnlineObjectService GetOnlineObjectService([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineObjectService") as OnlineObjectService;
}
public static OnlineFunctionServer GetOnlineFunctionServer([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Server.OnlineFunctionServer") as OnlineFunctionServer;
}
public static IIconServer GetIconServer([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.IconServer") as IIconServer;
}
public static HwcnBasicsFacade GetHwcnBasicFacade([NotNull] this IWorkingContext workingContext)
{
IHwcnBasicsFacade facade = workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.Basics.HwcnBasicsFacade") as IHwcnBasicsFacade;
return facade as HwcnBasicsFacade;
}
public static IModuleDetection GetModuleDetection([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Services.ModuleDetection") as IModuleDetection;
}
public static OnlineHostObserverProxy GetOnlineHostObserverProxy([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineHostObserver") as OnlineHostObserverProxy;
}
public static NotificationService GetNotificationService([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.NotificationService") as NotificationService;
}
public static OnlineScope GetOnlineScope(this IWorkingContext wc)
{
return Siemens.Simatic.HwConfiguration.Diagnostic.Common.Helper.GetOnlineScope(wc);
}
public static IOnlineObjectService GetDiagOnlineObjectService(IWorkingContext wc)
{
if (wc == null)
throw new ArgumentNullException("wc");
return wc.DlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineObjectService") as IOnlineObjectService;
}
public static FrameGroupManager GetHwcnFrameGroupManager([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<FrameGroupManager>("Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics.FrameGroupManager");
}
public static IUserControlFactory GetHwcnUserControlFactory([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<IUserControlFactory>("Siemens.Simatic.HwConfiguration.Diagnostic.Viewer.DoeUserControlFactory");
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.OEM.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices.Internal.OemCustomization;
using YZX.Tia.Proxies.OEM;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
internal static UIOemCustomizationServiceProxy GetUIOemCustomizationServiceDlcProxy([NotNull] this IWorkingContext workingContext)
{
UIOemCustomizationServiceDlc dlc = workingContext.GetRequiredDlc<UIOemCustomizationServiceDlc>("Siemens.Automation.CommonServices.UIOemCustomizationService");
return new UIOemCustomizationServiceProxy(dlc);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/ViewServiceDataProxy.cs
using System.Collections;
using System.Drawing;
using Siemens.Automation.FrameApplication.ViewManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ViewServiceDataProxy
{
ViewServiceData ViewServiceData;
internal ViewServiceDataProxy(ViewServiceData data)
{
ViewServiceData = data;
}
public string ViewId
{
get
{
return ViewServiceData.ViewId;
}
}
public string ViewFrame
{
get
{
return ViewServiceData.ViewFrame;
}
}
public string ViewDlc
{
get
{
return ViewServiceData.ViewDlc;
}
}
public string DomainLogicDlc
{
get
{
return ViewServiceData.DomainLogicDlc;
}
}
public string LoadInfo
{
get
{
return ViewServiceData.LoadInfo;
}
}
public bool IsEditor
{
get
{
return ViewServiceData.IsEditor;
}
}
public bool IsActive
{
get
{
return ViewServiceData.IsActive;
}
}
public ArrayList SelectionSource
{
get
{
return ViewServiceData.SelectionSource;
}
}
public ArrayList SelectionTarget
{
get
{
return ViewServiceData.SelectionTarget;
}
}
public Size MinSize
{
get
{
return ViewServiceData.MinSize;
}
}
public Size MaxSize
{
get
{
return ViewServiceData.MaxSize;
}
}
public string ToolbarID
{
get
{
return ViewServiceData.ToolbarID;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/ProjectNavigationViewProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics.Browsing;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ProjectNavigationViewProxy
{
internal ProjectNavigationView ProjectNavigationView;
internal ProjectNavigationViewProxy(ProjectNavigationView view)
{
ProjectNavigationView = view;
}
public IBrowsableCollection RootObjects
{
get
{
return ProjectNavigationView.RootObjects;
}
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamInfoEventProxy.cs
using System;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamInfoEventProxy
{
public OamInfoCallback oic;
public OamInfoEventProxy()
{
oic = new OamInfoCallback(OnOamInfoCallback);
}
public event OamJobInfoHandler OnCallback;
public void OnOamInfoCallback(
OamCallbackMessage message,
int Flags,
int referenceCount,
byte[] buffer,
DateTime timeStamp,
TimeSpan elapsedTime,
object oamSource,
object ClientSource)
{
//Console.WriteLine($"OamInfoEventProxy.OnOamInfoCallback() {message} {Flags} {referenceCount} {timeStamp} {elapsedTime}");
if(OnCallback != null)
{
OamClientInfoEventArgs args = new OamClientInfoEventArgs(message, Flags, referenceCount, buffer, timeStamp, elapsedTime);
OamClientInfoEventArgsProxy argsProxy = new OamClientInfoEventArgsProxy(args);
argsProxy.Buffer = buffer;
argsProxy.OamSource = oamSource;
argsProxy.ClientSource = ClientSource;
OnCallback(this,argsProxy);
}
}
}
}
<file_sep>/YZX.TIA/Proxies/BlockEditorLogicBaseProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
namespace YZX.Tia.Proxies
{
public class BlockEditorLogicBaseProxy
{
BlockEditorLogicBase BELB;
public BlockEditorLogicBaseProxy(BlockEditorLogicBase belb)
{
BELB = belb;
}
public void SkipPrintingTest()
{
}
}
}
<file_sep>/YZX.TIA/ConsoleTrace.cs
using System;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
namespace YZX.Tia
{
public class ConsoleTrace: ITrace, IComponentTrace
{
public bool IsErrorAllowed
{
get
{
return false;
}
}
public bool IsWarningAllowed
{
get
{
return false;
}
}
public bool IsInfoAllowed
{
get
{
return false;
}
}
public bool IsDebugAllowed
{
get
{
return false;
}
}
public string AssemblyName
{
get
{
return "Siemens.Automation.CommonTrace.IntegrationDotNet";
}
}
public string ComponentName
{
get
{
return "Siemens.Automation.CommonTrace.IntegrationDotNet.TraceMockup";
}
}
public string AssemblyInfo
{
get
{
return null;
}
set
{
}
}
public string ClassName
{
get
{
return null;
}
set
{
}
}
public event TraceEventHandler ErrorMessageSent;
public event TraceEventHandler WarningMessageSent;
public event TraceEventHandler InformationMessageSent;
public event TraceEventHandler DebugMessageSent;
public void Error(string sourceMethod, string message)
{
Console.WriteLine(String.Format("{0},{1}", sourceMethod, message));
}
public void Error(string sourceMethod, string format, object arg1)
{
String formattedString = String.Format(format, arg1);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Error(string sourceMethod, string format, object arg1, object arg2)
{
String formattedString = String.Format(format, arg1, arg2);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Error(string sourceMethod, string format, object arg1, object arg2, object arg3)
{
String formattedString = String.Format(format, arg1, arg2, arg3);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Error(string sourceMethod, string format, params object[] args)
{
String formattedString = String.Format(format, args);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Warning(string sourceMethod, string message)
{
Console.WriteLine(String.Format("{0},{1}", sourceMethod, message));
}
public void Warning(string sourceMethod, string format, object arg1)
{
String formattedString = String.Format(format, arg1);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Warning(string sourceMethod, string format, object arg1, object arg2)
{
String formattedString = String.Format(format, arg1, arg2);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Warning(string sourceMethod, string format, object arg1, object arg2, object arg3)
{
String formattedString = String.Format(format, arg1, arg2, arg3);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Warning(string sourceMethod, string format, params object[] args)
{
String formattedString = String.Format(format, args);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Info(string sourceMethod, string message)
{
Console.WriteLine(String.Format("{0},{1}", sourceMethod, message));
}
public void Info(string sourceMethod, string format, object arg1)
{
String formattedString = String.Format(format, arg1);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Info(string sourceMethod, string format, object arg1, object arg2)
{
String formattedString = String.Format(format, arg1, arg2);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Info(string sourceMethod, string format, object arg1, object arg2, object arg3)
{
String formattedString = String.Format(format, arg1, arg2, arg3);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Info(string sourceMethod, string format, params object[] args)
{
String formattedString = String.Format(format, args);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Debug(string sourceMethod, string message)
{
Console.WriteLine(String.Format("{0},{1}", sourceMethod, message));
}
public void Debug(string sourceMethod, string format, object arg1)
{
String formattedString = String.Format(format, arg1);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Debug(string sourceMethod, string format, object arg1, object arg2)
{
String formattedString = String.Format(format, arg1, arg2);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Debug(string sourceMethod, string format, object arg1, object arg2, object arg3)
{
String formattedString = String.Format(format, arg1,arg2,arg3);
Console.WriteLine(String.Format("{0},{1}", sourceMethod, formattedString));
}
public void Debug(string sourceMethod, string format, params object[] args)
{
String formattedString = String.Format(format, args);
Console.WriteLine(String.Format("{0},{1}", sourceMethod,formattedString));
}
ITrace IComponentTrace.GetTracerForClass(HierarchyName hierarchyName)
{
return new ConsoleTrace();
}
public bool IsTraceAllowed(int traceLevel)
{
return true;
}
public void PerformTracing(string className, string sourceMethod, int traceLevel, long traceTime, string format, params object[] args)
{
}
}
}
<file_sep>/YZX.TIA/Proxies/OMS/OMSConnectionProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Reflection;
namespace YZX.Tia.Proxies
{
public class OMSConnectionProxy
{
OMSConnection OMSConnection;
IOMSConnection IOMSConnection
{
get
{
return OMSConnection;
}
}
public OMSConnectionProxy(IOMSConnection connection)
{
OMSConnection = connection as OMSConnection;
}
internal OamTrace Trace
{
get
{
return Reflector.GetInstanceFieldByName(OMSConnection,
"m_Trace", ReflectionWays.SystemReflection) as OamTrace;
}
}
public OamConnectionState State
{
get
{
return (OamConnectionState)Reflector.GetInstanceFieldByName(OMSConnection,
"m_State",
ReflectionWays.SystemReflection);
}
}
public IOmsNodeControl NodeControl
{
get
{
return OMSConnection.NodeControl;
}
}
public OmsNodeControlProxy NodeControlProxy
{
get
{
return new OmsNodeControlProxy(NodeControl);
}
}
public int RegisterWatchdogHandler()
{
return OMSConnection.RegisterWatchdogHandler();
}
public void ConnectInternal()
{
Reflector.RunInstanceMethodByName(OMSConnection,
"ConnectInternal", ReflectionWays.SystemReflection);
}
public void CreateStartWorkerThread()
{
Reflector.RunInstanceMethodByName(OMSConnection,
"CreateStartWorkerThread", ReflectionWays.SystemReflection);
}
public void StopWorkerThread()
{
Reflector.RunInstanceMethodByName(OMSConnection,
"StopWorkerThread", ReflectionWays.SystemReflection);
}
}
}
<file_sep>/README.md
# 目的
1.TIA 中有很多控件我想要将它们用到自己开发的软件中去,比如监控某一个流程图(graph)实例的状态,监控某一段梯型图(ladder)的状态,比如监控某一个变量表中的变量的当前值。
2.给 TIA 添加一些我想要的功能。
# Openness 和 OpennessScripter
OpennessScripter 只是一个 Openness 的一种应用而已。Openness 只是给用户提供一种操作 TIA 的方式,提供一种从 TIA 向外导出数据和向 TIA 导入数据的方式。
# 当前状态
1. [Open Graph Editor](https://github.com/yanzixiang/YZX.TIA/wiki/Open-Graph-Editor)</br>
打开顺序流程图编辑器
2. [Open Ladder Editor](https://github.com/yanzixiang/YZX.TIA/wiki/Open-Ladder-Editor)</br>
打开梯型图编辑器
3. [Change the splash image](https://github.com/yanzixiang/YZX.TIA/wiki/Change-the-splash-image)</br>
更换启动画面
4. [Add some menu in the Portal view](https://github.com/yanzixiang/YZX.TIA/wiki/Add-some-menu-in-the-Portal-view)</br>
在Portal视图中添加菜单
5. [Add IronPython Console for controls in Wincc Design Editor](https://github.com/yanzixiang/YZX.TIA/wiki/Add-IronPython-Console-for-controls-in-Wincc-Design-Editor)</br>
在Wincc设计画面中为每个控件添加IronPython控制台
6. [Unpack mpk files](https://github.com/yanzixiang/YZX.TIA/tree/master/MpkExtractor)</br>
解包TIA专用配置文件MPK<file_sep>/YZX.TIA/Proxies/Oam/OamUserProgramProxy.cs
using System;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OnlineAccess.SPS7;
namespace YZX.Tia.Proxies
{
public class OamUserProgramProxy
{
OamUserProgram OamUserProgram;
public OamUserProgramProxy(IOamUserProgram program)
{
OamUserProgram = program as OamUserProgram;
}
}
}
<file_sep>/YZX.TIA/Proxies/Dlc/DlcMetaInfoRepositoryProxy.cs
using System.Collections.Generic;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.Dlc
{
public class DlcMetaInfoRepositoryProxy
{
public static IEnumerable<IDlcMetaInfo> Singleton
{
get
{
return DlcMetaInfoRepository.Singleton;
}
}
private static List<IDlcMetaInfo> m_DlcMetaInfoList;
public static List<IDlcMetaInfo> SingletonList
{
get
{
if (m_DlcMetaInfoList == null)
{
m_DlcMetaInfoList = new List<IDlcMetaInfo>(Singleton);
}
return m_DlcMetaInfoList;
}
}
public static void UpdateList()
{
m_DlcMetaInfoList = new List<IDlcMetaInfo>(Singleton);
}
}
}
<file_sep>/YZX.TIA/Extensions/OMS/OMSNodeExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YZX.Tia.Extensions
{
public class OMSNodeExtensions
{
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableLangModTogglerDSVProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableLangModTogglerDSVProxy:DrawableBoxElementProxy
{
internal DrawableLangModTogglerDSV DrawableLangModTogglerDSV;
internal DrawableLangModTogglerDSVProxy(DrawableLangModTogglerDSV dsv)
:base(dsv)
{
DrawableLangModTogglerDSV = dsv as DrawableLangModTogglerDSV;
}
}
}
<file_sep>/YZX.TIA/Proxies/EAMTZTagTableViewLogicProxy.cs
using System;
using System.ComponentModel;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.Meta;
using Siemens.Automation.CommonServices;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.Utilities;
using Siemens.Simatic.PlcLanguages.TagTableViewer;
using Reflection;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
public class EAMTZTagTableViewLogicProxy
{
TagsTableViewLogic TagsTableViewLogic;
ISynchronizeInvoke UsingSynchronizer;
public EAMTZTagTableViewLogicProxy(TagsTableViewLogic ttvl, ISynchronizeInvoke synchronizer = null)
{
TagsTableViewLogic = ttvl;
UsingSynchronizer = synchronizer;
}
public CommandReturnCodes PrepareImport(ICoreObject parentObject, string sourceFile)
{
return (CommandReturnCodes)TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<CommandReturnCodes>)(() =>
{
return (CommandReturnCodes)Reflector.RunInstanceMethodByName(
TagsTableViewLogic,
"PrepareImport",
ReflectionWays.SystemReflection,
parentObject,
sourceFile);
}));
}
public bool ImportFile(ITagService TagService,string file, ICoreObject parentObject)
{
return (bool)TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<bool>)(() =>
{
TagService.SuspendCollectionEvents();
using (OnDispose.Invoke(() => TagService.ResumeCollectionEvents()))
{
using (new ObjectFrameBulkOperationMode(parentObject))
{
return (bool)Reflector.RunInstanceMethodByName(
TagsTableViewLogic,
"ImportFile",
ReflectionWays.SystemReflection,
file,
parentObject);
}
}
}));
}
public CommandReturnCodes PrepareExport(ICoreObject parentObject, string sourceFile)
{
return (CommandReturnCodes)TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<CommandReturnCodes>)(() =>
{
return (CommandReturnCodes)Reflector.RunInstanceMethodByName(
TagsTableViewLogic,
"PrepareExport",
ReflectionWays.SystemReflection,
parentObject,
sourceFile);
}));
}
public bool ExportFile(string file, ICoreObject parentObject)
{
return (bool)TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<bool>)(() =>
{
return (bool)Reflector.RunInstanceMethodByName(
TagsTableViewLogic,
"ExportFile",
ReflectionWays.SystemReflection,
file,
parentObject);
}));
}
}
}
<file_sep>/YZX.TIA/Proxies/OEM/BLOemCustomizationServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices.Internal.OemCustomization;
using Reflection;
namespace YZX.Tia.Proxies.OEM
{
public class BLOemCustomizationServiceProxy
{
internal BLOemCustomizationServiceDlc BLOemCustomizationServiceDlc;
internal BLOemCustomizationService BLOemCustomizationService;
public BLOemCustomizationServiceProxy(IDlc dlc)
{
BLOemCustomizationServiceDlc = dlc as BLOemCustomizationServiceDlc;
if(BLOemCustomizationServiceDlc != null)
{
BLOemCustomizationService = Reflector.GetInstanceFieldByName(BLOemCustomizationServiceDlc,
"m_BlOemCustomizationService",
ReflectionWays.SystemReflection) as BLOemCustomizationService;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/OnlineCommonNodeProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using Siemens.Automation.DomainServices.UI.OnlineCommon.DataBinding;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies.OnlineService
{
public class OnlineCommonNodeProxy
{
internal OnlineCommonNode OnlineCommonNode;
internal OnlineCommonNodeProxy(OnlineCommonNode node)
{
OnlineCommonNode = node;
}
public bool IsLifelistOfflineSibling
{
get
{
return OnlineCommonNode.IsLifelistOfflineSibling;
}
set
{
OnlineCommonNode.IsLifelistOfflineSibling = value;
}
}
public bool LifelistSiblingInfoUpdatesTriggered
{
get
{
return OnlineCommonNode.LifelistSiblingInfoUpdatesTriggered;
}
set
{
OnlineCommonNode.LifelistSiblingInfoUpdatesTriggered = value;
}
}
public bool InfoUpdatesTriggered
{
get
{
return OnlineCommonNode.InfoUpdatesTriggered;
}
set
{
OnlineCommonNode.InfoUpdatesTriggered = value;
}
}
public string IPAddressString
{
get
{
return OnlineCommonNode.IPAddressString;
}
set
{
OnlineCommonNode.IPAddressString = value;
}
}
public string MACAddressString
{
get
{
return OnlineCommonNode.MACAddressString;
}
set
{
OnlineCommonNode.MACAddressString = value;
}
}
public string IPAddressStringWithProtocol
{
get
{
return OnlineCommonNode.IPAddressStringWithProtocol;
}
}
public string MACAddressStringWithProtocol
{
get
{
return OnlineCommonNode.MACAddressStringWithProtocol;
}
}
public bool HasIPAddress
{
get
{
return OnlineCommonNode.HasIPAddress;
}
}
public string ProtocolString
{
get
{
return OnlineCommonNode.ProtocolString;
}
set
{
OnlineCommonNode.ProtocolString = value;
}
}
public string AddressStringWithProtocol
{
get
{
return OnlineCommonNode.AddressStringWithProtocol;
}
}
public ICoreObject DeviceNode
{
get
{
return OnlineCommonNode.DeviceNode;
}
}
public ICoreObject OnlineDeviceNode
{
get
{
return OnlineCommonNode.OnlineDeviceNode;
}
}
public ICoreObject TargetNode
{
get
{
return OnlineCommonNode.TargetNode;
}
}
public bool ConnectionPossible
{
get
{
return OnlineCommonNode.ConnectionPossible;
}
}
public string DeviceName
{
get
{
return OnlineCommonNode.DeviceName;
}
set
{
OnlineCommonNode.DeviceName = value;
}
}
public string DeviceTypeName
{
get
{
return OnlineCommonNode.DeviceTypeName;
}
set
{
OnlineCommonNode.DeviceTypeName = value;
}
}
public ICoreObject OnlineDeviceTarget
{
get
{
return OnlineCommonNode.OnlineDeviceTarget;
}
}
public string TargetName
{
get
{
return OnlineCommonNode.TargetName;
}
set
{
OnlineCommonNode.TargetName = value;
}
}
public void SetDeviceOrTargetInfoUpdateReady()
{
OnlineCommonNode.SetDeviceOrTargetInfoUpdateReady();
}
internal static OnlineCommonNode Create(OnlineCommonLifeListFacade lifeListFacade,
ICoreObject accessibleNode,
OnlineCommonHelper helper)
{
return OnlineCommonNode.Create(lifeListFacade, accessibleNode, helper);
}
internal static OnlineCommonNode CreateExtendedDownloadNode(OnlineCommonLifeListFacade lifeListFacade,
string address,
IOamAddress defaultAddress,
OnlineCommonHelper helper,
OnlineCommonNodeClass nodeClass,
bool isReachable)
{
return OnlineCommonNode.CreateExtendedDownloadNode(lifeListFacade,
address, defaultAddress, helper, nodeClass, isReachable);
}
internal static OnlineCommonNode CreateWithAddressAsLifelistNode(OnlineCommonLifeListFacade lifeListFacade,
IOamAddress address,
OnlineCommonHelper helper,
bool isReachable)
{
return OnlineCommonNode.CreateWithAddressAsLifelistNode(lifeListFacade, address, helper, isReachable);
}
internal static OnlineCommonNode CreateWithOfflineTarget(OnlineCommonLifeListFacade lifeListFacade,
IOamAddress address,
OnlineCommonHelper helper,
bool isReachable)
{
return OnlineCommonNode.CreateWithOfflineTarget(lifeListFacade, address, helper, isReachable);
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/SPS7ConnectionProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OnlineAccess.SPS7;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Converter;
namespace YZX.Tia.Proxies
{
public class SPS7ConnectionProxy:S7DOSConnectionProxy
{
SPS7Connection SPS7Connection;
public SPS7ConnectionProxy(OamConnectionBase connection)
:base(connection)
{
SPS7Connection = connection as SPS7Connection;
}
public List<IOamAsyncResult> SuspendedConnectRequests
{
get
{
List<ConnectAsyncResult> result =
Reflector.GetInstanceFieldByName(SPS7Connection,
"",
ReflectionWays.SystemReflection) as List<ConnectAsyncResult>;
return result.ConvertAll(new Converter<ConnectAsyncResult, IOamAsyncResult>(
OamConverters.ConnectAsyncResult2IOamAsyncResult));
}
}
public IOamSystemNotifier NotifyWatchdogHandler
{
get
{
return SPS7Connection.NotifyWatchdogHandler;
}
}
public OamOnlineBlockDirectoryProxy BlocksProxy
{
get
{
return new OamOnlineBlockDirectoryProxy(SPS7Connection.Blocks);
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Dlc/WorkingContextFallbackStrategyProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Reflection;
namespace YZX.Tia.Proxies.Dlc
{
public class WorkingContextFallbackStrategyProxy
{
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Hwcn.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Basics.SystemData;
using Siemens.Simatic.HwConfiguration.Connections.Block.Base;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static SystemDataBlockFactory GetSystemDataBlockFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
SystemDataBlockFactory SystemDataBlockFactory = idlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.SystemData.SystemDataBlockFactory")
as SystemDataBlockFactory;
return SystemDataBlockFactory;
}
public static S7PlusDataUpload GetS7PlusDataUpload(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
S7PlusDataUpload S7PlusDataUpload = idlcManager.Load("Siemens.Simatic.HwConfiguration.Basics.SystemData.S7PlusDataUpload")
as S7PlusDataUpload;
return S7PlusDataUpload;
}
public static ConnService GetConnService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
ConnService ConnService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Connections.Block.Base.ConnectionService")
as ConnService;
return ConnService;
}
}
}
<file_sep>/YZX.TIA/YZXLegitimationService.cs
using System;
using Siemens.Automation.DomainServices;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia
{
public class YZXLegitimationService : ILegitimationService
{
public event EventHandler<TargetConnectionsPreDelegitimationEventArgs> TargetConnectionsPreDelegitimationEvent;
public void Delegitimate(ClientSession drive)
{
}
public void Delegitimate(IOamEpromDrive drive)
{
}
public void Delegitimate(IConnection connection)
{
}
public bool IsProtected(IOamEpromDrive drive)
{
return false;
}
public bool IsProtected(ClientSession drive)
{
return false;
}
public bool IsProtected(IConnection connection)
{
return false;
}
public bool Legitimate(IOamEpromDrive drive, NeededProtectionLevel desiredLevel, bool requestPasswordFromUser)
{
return true;
}
public bool Legitimate(ClientSession drive, NeededProtectionLevel desiredLevel, bool requestPasswordFromUser)
{
return true;
}
public bool Legitimate(IConnection connection, NeededProtectionLevel desiredLevel, bool requestPasswordFromUser)
{
return true;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/CompileService/CompileCommandsProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Automation.DomainServices.CompileService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.LoadService.Download;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class CompileCommandsProxy
{
CompileCommands CompileCommands;
public ILoad Load
{
get
{
return CompileCommands as ILoad;
}
}
public IDlc Dlc
{
get
{
return CompileCommands as IDlc;
}
}
public ICompileLoadAttributes CompileLoadAttributes
{
get
{
return CompileCommands as ICompileLoadAttributes;
}
}
public CompileCommandsProxy(ICompileCommandExtension compileCommands)
{
CompileCommands = compileCommands as CompileCommands;
}
public IOnlineService OnlineService
{
get
{
return Reflector.GetInstancePropertyByName(CompileCommands, "OnlineService",
ReflectionWays.SystemReflection) as IOnlineService;
}
}
public DownloadServiceProxy DownloadServiceProxy
{
get
{
DownloadService downloadService = Reflector.GetInstancePropertyByName(CompileCommands,
"DownloadSerice", ReflectionWays.SystemReflection) as DownloadService;
return new DownloadServiceProxy(downloadService);
}
}
public DownloadCommandServiceProxy DownloadCommandServiceProxy
{
get
{
DownloadCommandService downloadCommandService = Reflector.GetInstancePropertyByName(CompileCommands,
"DownloadCommandService", ReflectionWays.SystemReflection) as DownloadCommandService;
return new DownloadCommandServiceProxy(downloadCommandService);
}
}
public MainUploadServiceProxy MainUploadServiceProxy
{
get
{
MainUploadService mainUploadService = Reflector.GetInstancePropertyByName(CompileCommands,
"MainUploadService", ReflectionWays.SystemReflection) as MainUploadService;
return new MainUploadServiceProxy(mainUploadService);
}
}
public UploadServiceProxy UploadServiceProxy
{
get
{
UploadService uploadervice = Reflector.GetInstancePropertyByName(CompileCommands,
"UploadService", ReflectionWays.SystemReflection) as UploadService;
return new UploadServiceProxy(uploadervice);
}
}
public UploadCommandServiceProxy UploadCommandServiceProxy
{
get
{
UploadCommandService uploadCommandService = Reflector.GetInstancePropertyByName(CompileCommands,
"UploadCommandService", ReflectionWays.SystemReflection) as UploadCommandService;
return new UploadCommandServiceProxy(uploadCommandService);
}
}
public LoadState LoadState
{
get
{
return Load.LoadState;
}
}
public IWorkingContext WorkingContext
{
get
{
return Dlc.WorkingContext;
}
}
}
}
<file_sep>/YZX.TIA/TiaProcess.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Simatic.PlcLanguages.BlockLogic.OpenBlockHandling;
using Siemens.Automation.CommonServices;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonServices.ProjectManagement.Private.Interfaces;
using Siemens.Automation.CommonServices.ProjectControl.UI;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.HwConfiguration.BusinessLogic.Acf.Devices;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.VatService.Navigator;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Automation.DomainServices.FolderService;
using Siemens.Simatic.PlcLanguages.Model;
using Siemens.Automation.ObjectFrame.Private;
using Siemens.Automation.ObjectFrame.BusinessLogic;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.DomainServices.UI.GoOnline;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
using Siemens.Simatic.PlcLanguages.VatService.Businesslogic;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.ObjectFrame.Meta;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Commands;
using Siemens.Automation.DomainServices.UI.LoadService;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
public class TiaProcess
{
#region internal
static CmdHandlerHelper CHH;
IControllerTargetLookup QBCTL;
OnlineServiceHelper onlineServiceHelper;
IBlockLookup blockLookup;
#endregion
public static ICoreContextHandler cch;
static TiaProcess(){
CHH = new CmdHandlerHelper(App.ProjectManager);
}
public OnlineErrorState Connect(ICoreObject onlineTarget,
NeededProtectionLevel protectionLevel,
string connectionType,
bool showDialog)
{
if(onlineServiceHelper == null)
{
return OnlineErrorState.Error;
}
return onlineServiceHelper.Connect(onlineTarget, protectionLevel, connectionType, showDialog);
}
public object GetOnlineReader(ICoreObject cpu)
{
return OnlineReaderFactory.GetOnlineReader(cpu);
}
}
}
<file_sep>/YZX.TIA/Proxies/LoadService/Upload/UploadOnlineAccessLifelistNodeProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class UploadOnlineAccessLifelistNodeProxy:UploadOnlineAccessBaseProxy
{
UploadOnlineAccessLifelistNode UploadOnlineAccessLifelistNode;
internal UploadOnlineAccessLifelistNodeProxy(UploadOnlineAccessLifelistNode node)
: base(node)
{
UploadOnlineAccessLifelistNode = node;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/ConnectionService/ICoreObjectExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.OnlineService;
namespace YZX.Tia.Extensions
{
public static class ICoreObjectExtensions
{
public static ConnectionServiceProvider GetConnectionServiceProvider(this ICoreObject coreObject)
{
ConnectionServiceProvider connectionService = null;
if (!coreObject.IsDeleted || !coreObject.IsDeleting)
{
IConnectionService ics = ((IDlc)coreObject.Context).WorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.ConnectionService")
as IConnectionService;
ConnectionServiceProxy csp = ics as ConnectionServiceProxy;
connectionService = Reflector.GetInstancePropertyByName(csp, "RealConnectionService", ReflectionWays.SystemReflection) as ConnectionServiceProvider;
}
return connectionService;
}
public static object GetNodeDetails(this ICoreObject node)
{
return LifelistNodeDetailsFactory.GetNodeDetails(node);
}
public static ICoreObject GetOnlineDeviceNode(this ICoreObject lifelistNode)
{
var detail = lifelistNode.GetNodeDetails();
LifelistNodeDetailsProxy detailsProxy = new LifelistNodeDetailsProxy(detail);
var onlineDevice = detailsProxy.OnlineDeviceNode;
return onlineDevice;
}
}
}
<file_sep>/YZX.TIA/Proxies/LoadService/LoadCommandsUIProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Automation.DomainServices.UI.LoadService;
namespace YZX.Tia.Proxies.LoadService
{
public class LoadCommandsUIProxy
{
internal LoadCommandsUI LoadCommandsUI;
public LoadCommandsUIProxy(IDlc dlc)
{
LoadCommandsUI = dlc as LoadCommandsUI;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/OnlineService/OnlineNavigatorProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.OnlineService;
namespace YZX.Tia.Proxies.OnlineService
{
public class OnlineNavigatorProxy
{
OnlineNavigator OnlineNavigator;
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.TisPlusServer.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Simatic.PlcLanguages.TisPlusServer;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia
{
partial class TiaStarter
{
private Server m_TisPlusServer;
public Server TisPlusServer
{
get
{
if (this.m_TisPlusServer == null)
this.m_TisPlusServer = m_BusinessLogicApplicationContext.DlcManager.Load("Siemens.Simatic.PlcLanguages.TisPlusServer") as Server;
return this.m_TisPlusServer;
}
}
public Device CreateTisPlusDevice(IConnection pConnection)
{
return TisPlusServer.CreateDevice(pConnection) as Device;
}
public DataAddress CreateTisPlusDataAddress()
{
return TisPlusServer.CreateDataAddress() as DataAddress;
}
public Value CreateTisPlusValue()
{
return TisPlusServer.CreateTisValue() as Value;
}
}
}
<file_sep>/YZX.TIA/Extensions/PLBlockEditorLogicExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Automation.FrameApplication;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class PLBlockEditorLogicExtensions
{
public static void SetMenuService(this BlockEditorLogicBase PLlogic,
IMenuService menuService)
{
Reflector.SetInstanceFieldByName(PLlogic, "m_MenuService", menuService, ReflectionWays.SystemReflection); ;
}
}
}
<file_sep>/YZX.TIA/Proxies/PLCMsgConnectorProxy.cs
using Siemens.Simatic.PLCMessaging;
using Reflection;
namespace YZX.Tia.Proxies
{
public class PLCMsgConnectorProxy
{
PLCMsgConnector PLCMsgConnector;
public PLCMsgConnectorProxy(PLCMsgConnector connector)
{
PLCMsgConnector = connector;
}
}
}
<file_sep>/YZX.TIA/mpk.cs
using System.Collections.Generic;
using Siemens.Automation.Utilities.PackagingService;
using Siemens.Automation.Archiving.Private;
using Siemens.Automation.FrameApplication.Releasemanagement;
using Siemens.Automation.FrameApplication.ContextNavigator;
namespace YZX.Tia
{
public class mpk
{
public static IList<string> GetNames(string path)
{
PackagingImplementationBase pib = new PackagingImplementationBase(path, null, null);
return pib.GetFiles();
}
public static void unpack(string path)
{
PackagingImplementationBase pib = new PackagingImplementationBase(path, null, null);
IList<string> files = pib.GetFiles();
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/WindowManagerProxy.Events.cs
using System;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
partial class WindowManagerProxy
{
public event EventHandler<AdditionalFramesEventArgs> FrameCreated
{
add
{
WindowManager.FrameCreated += value;
}
remove
{
WindowManager.FrameCreated -= value;
}
}
public event EventHandler<FrameAddEventArgs> FrameAdding
{
add
{
WindowManager.FrameAdding += value;
}
remove
{
WindowManager.FrameAdding -= value;
}
}
public event EventHandler<FrameAddEventArgs> FrameAdded
{
add
{
WindowManager.FrameAdded += value;
}
remove {
WindowManager.FrameAdded -= value;
}
}
public event EventHandler<CancelFrameEventArgs> FrameClosing
{
add
{
WindowManager.FrameClosing += value;
}
remove
{
WindowManager.FrameClosing -= value;
}
}
public event EventHandler<FrameEventArgs> FrameClosed
{
add
{
WindowManager.FrameClosed += value;
}
remove
{
WindowManager.FrameClosed -= value;
}
}
public event EventHandler InitializationCompleted
{
add
{
WindowManager.InitializationCompleted += value;
}
remove
{
WindowManager.InitializationCompleted -= value;
}
}
public event EventHandler<FrameCreatingEventArgs> FrameCreating
{
add
{
WindowManager.FrameCreating += value;
}
remove
{
WindowManager.FrameCreating -= value;
}
}
}
}<file_sep>/YZX.TIA/Proxies/OnlineService/PGAddressHelperProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
namespace YZX.Tia.Proxies.OnlineService
{
public class PGAddressHelperProxy
{
internal PGAddressHelper PGAddressHelper;
public PGAddressHelperProxy(object helper)
{
PGAddressHelper = helper as PGAddressHelper;
}
public bool AddPGAddressWithDialogNotCheckingProjectIP(bool allowSetTemporaryAddress)
{
return PGAddressHelper.AddPGAddressWithDialogNotCheckingProjectIP(allowSetTemporaryAddress);
}
internal bool AddPGAddressWithDialogNotCheckingProjectIP(bool allowSetTemporaryAddress,
List<OnlineCommonNode> nodes)
{
return PGAddressHelper.AddPGAddressWithDialogNotCheckingProjectIP(allowSetTemporaryAddress, nodes);
}
internal bool RequiresNewPGAddress(ICoreObject boardConfiguration,
OnlineCommonNode node,
bool allowTemporaryTargetAddress)
{
return PGAddressHelper.RequiresNewPGAddress(boardConfiguration, node, allowTemporaryTargetAddress);
}
internal bool SetNewPGAddressOfflineRequired(List<OnlineCommonNode> projectNodes,
ICoreObject boardConfiguration)
{
return PGAddressHelper.SetNewPGAddressOfflineRequired(projectNodes, boardConfiguration);
}
internal bool AddPGAddressWithDialogIncludeCheckingProjectIP(OnlineCommonNode node,
List<OnlineCommonNode> projectNodes,
ICoreObject boardConfiguration)
{
return PGAddressHelper.AddPGAddressWithDialogIncludeCheckingProjectIP(node, projectNodes, boardConfiguration);
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamNetworkProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamNetworkProxy
{
OamNetwork OamNetwork;
public OamNetworkProxy(IOamNetwork network)
{
OamNetwork = network as OamNetwork;
}
OamNodeCollection Nodes
{
get
{
return OamNetwork.Nodes;
}
}
List<OamScan> WaitingScans
{
get
{
return OamNetwork.WaitingScans;
}
}
public static bool IsOpenTcpConnectionsActivated
{
get
{
return OamNetwork.IsOpenTcpConnectionsActivated;
}
}
public int GetCountOfOnlineNodes()
{
return OamNetwork.GetCountOfOnlineNodes();
}
public void ClearOnlineNode()
{
OamNetwork.ClearOnlineNode();
}
public INode LookupOnlineNode(string searchedAddress)
{
return OamNetwork.LookupOnlineNode(searchedAddress);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/UiWorkingContextExtensions.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions.FrameApplication
{
public static class UiWorkingContextExtensions
{
public static IDlc GetPrimaryProjectUiWorkingContextManagerDlc(this IWorkingContext workingContext)
{
PrimaryProjectUiWorkingContextManagerDlc EditorController =
workingContext.DlcManager.Load("Siemens.Automation.FrameApplication.ProjectHandling.PrimaryProject.PrimaryProjectUiWorkingContextManager")
as PrimaryProjectUiWorkingContextManagerDlc;
return EditorController;
}
public static IUIContextHolder GetUIContextHolder(this IWorkingContext workingContext)
{
PrimaryProjectUiWorkingContextManagerDlc dlc = workingContext.GetPrimaryProjectUiWorkingContextManagerDlc()
as PrimaryProjectUiWorkingContextManagerDlc;
PrimaryProjectUiWorkingContextManager manager = Reflector.GetInstancePropertyByName(dlc, "Forwardee", ReflectionWays.SystemReflection)
as PrimaryProjectUiWorkingContextManager;
var proxy = new PrimaryProjectUiWorkingContextManagerProxy(manager);
return proxy.IUIContextHolder;
}
}
}
<file_sep>/Siemens.Automation.CommonServices.ProjectManager.Test/Proxies/ProjectManager/TiaProjectProxy.Block.cs
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.Lang.Model.Idents;
namespace YZX.Tia.Proxies.ProjectManager
{
partial class TiaProjectProxy
{
public BlockServiceProxy BlockServiceProxy
{
get
{
IBlockService bs =
ProjectWorkingContext.DlcManager.Load("PlcLanguages.BlockLogic.BlockService") as IBlockService;
return new BlockServiceProxy(bs);
}
}
public ICoreObject[] FindBlockByAddress(ICoreObject parent, BlockType type, int number)
{
return BlockServiceProxy.FindBlockByAddress(parent, type, number);
}
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamCustomBoardProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamCustomBoardProxy : OamLocalBoardBaseProxy
{
OamCustomBoard OamLocalBoard;
public OamCustomBoardProxy(IOamLocalBoard localBoard):base(localBoard)
{
OamLocalBoard = localBoard as OamCustomBoard;
}
}
}
<file_sep>/YZX.TIA/Extensions/OamTraceExtensions.cs
using System.Configuration;
using System.Reflection;
namespace YZX.Tia.Extensions
{
public static class OamTraceExtensions
{
public static int ReadTraceLevelFromCfg()
{
int result = 0;
Configuration configuration = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
if (configuration.HasFile && configuration.AppSettings.Settings.Count > 0)
{
KeyValueConfigurationElement configurationElement = configuration.AppSettings.Settings["OamTraceLevel"];
if (configurationElement != null && !int.TryParse(configurationElement.Value, out result))
result = 0;
}
return result;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Proxies/AssemblyFinderProxy.cs
using System.Collections.Generic;
using System.Reflection;
using Siemens.Automation.Basics;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies
{
public class AssemblyFinderProxy
{
public static IDictionary<string, Assembly> GetLoadedAssemblyList()
{
return Reflector.GetStaticFieldByName(typeof(AssemblyFinder),
"s_LoadedAssemblyList",
ReflectionWays.SystemReflection) as IDictionary<string, Assembly>;
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Proxies/BlockLogic/PlusBlockConsistencyServiceProxy.cs
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus.Upload;
namespace YZX.Tia.Proxies
{
public class PlusBlockConsistencyServiceProxy
{
PlusBlockConsistencyService PlusBlockConsistencyService;
public PlusBlockConsistencyServiceProxy(IUpload upload)
{
PlusBlockConsistencyService = upload as PlusBlockConsistencyService;
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Proxies/BlockLogic/ICoreObjectExtensionProxy.cs
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockLogic.Compiler.Util.Extensions;
namespace YZX.Tia.Proxies.BlockLogic
{
public static class ICoreObjectExtensionProxy
{
public static bool IsLittle(this ICoreObject m_target)
{
return ICoreObjectExtension.IsLittle(m_target);
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Online.cs
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Diagnostic.Common;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static string GetObjectIdentification(this ICoreObject source)
{
return Siemens.Simatic.HwConfiguration.Diagnostic.Common.Helper.GetObjectIdentification(source);
}
internal static IOnlineReader GetOnlineReader(this ICoreObject onlineTarget)
{
return OnlineReaderFactory.GetOnlineReader(onlineTarget);
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Extensions/NetworkEditorFrame/ICoreObjectExtensions.Ladder.cs
using System;
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.Utilities.Toolbox;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.Lang.Model.Blocks;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
using YZX.Tia.Extensions.ObjectFrame;
namespace YZX.Tia.Extensions.NetworkEditorFrame
{
public static partial class ICoreObjectExtensions
{
private delegate BlockEditorLogicBase GetPLBlockEditorLogicDelegate(
ICoreObject block,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null
);
public static BlockEditorLogicBase GetPLBlockEditorLogic(this ICoreObject block,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
if (UsingSynchronizer.InvokeRequired)
return UnifiedSynchronizerAccess.Invoke(UsingSynchronizer,
new GetPLBlockEditorLogicDelegate(GetPLBlockEditorLogic), new object[4]
{
block,
ViewWorkingContext,
serviceContainer,
synchronizer
}).InvokeResult as BlockEditorLogicBase;
PLBlockEditorLogic pl = new PLBlockEditorLogic(EditorMode.Normal);
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
//pl.Attach(ViewWorkingContext);
pl.PostAttach();
EditorPayload ep = new EditorPayload(block, ViewWorkingContext, serviceContainer);
pl.SetPayload(ep);
//Reflector.RunInstanceMethodByName(pl, "CreateOnlineManager");
OnlineManagerBase OnlineManager = pl.OnlineManager;
return pl;
}
private delegate BlockEditorControlBase GetPLViewDelegate(
ICoreObject block,
BlockEditorLogicBase logic,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null);
public static BlockEditorControlBase GetPLView(this ICoreObject block,
BlockEditorLogicBase logic,
IWorkingContext ViewWorkingContext = null,
LanguageServiceContainer serviceContainer = null,
ISynchronizeInvoke synchronizer = null)
{
ISynchronizeInvoke UsingSynchronizer;
if (synchronizer == null)
{
UsingSynchronizer = block.GetSynchronizer();
}
else
{
UsingSynchronizer = synchronizer;
}
if (UsingSynchronizer.InvokeRequired)
return UnifiedSynchronizerAccess.Invoke(UsingSynchronizer,
new GetPLViewDelegate(GetPLView), new object[4]
{
block,
ViewWorkingContext,
serviceContainer,
synchronizer
}).InvokeResult as BlockEditorControlBase;
PLBlockEditorControlElement pl = new PLBlockEditorControlElement();
if (ViewWorkingContext == null)
{
IWorkingContext iwc = block.GetWorkingContext();
pl.Attach(iwc);
}
else
{
pl.Attach(ViewWorkingContext);
}
EditorPayload ep = new EditorPayload(block, ViewWorkingContext, serviceContainer);
pl.SetPayload(ep);
pl.SetDomainLogic(logic);
logic.SetView(pl);
logic.InitializationFinished();
return pl;
}
public static void GetBlockTypeAndLanguage(this ICoreObject coreObject,
out BlockType blockType,
out ProgrammingLanguage blockLanguage)
{
blockType = BlockType.Undef;
blockLanguage = ProgrammingLanguage.Undef;
Reflector.RunStaticMethodByName(typeof(EditorStarterFacade),
"GetBlockTypeAndLanguage",
ReflectionWays.SystemReflection,
coreObject, blockType, blockLanguage);
}
}
}<file_sep>/YZX.TIA/Proxies/OnlineService/LifelistNodeDetailsFactoryProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.OnlineService;
using Reflection;
namespace YZX.Tia.Proxies.OnlineService
{
public class LifelistNodeDetailsFactoryProxy
{
public static LifelistNodeDetailsProxy GetNodeDetails(ICoreObject node)
{
LifelistNodeDetails details = LifelistNodeDetailsFactory.GetNodeDetails(node);
return new LifelistNodeDetailsProxy(details);
}
public static LifelistDetailsQueueProxy GetDetailsQueue(ICoreObject node)
{
var queue = Reflector.RunStaticMethodByName(typeof(LifelistNodeDetailsFactory),
"GetDetailsQueue",
ReflectionWays.SystemReflection,
node) as LifelistDetailsQueue;
return new LifelistDetailsQueueProxy(queue);
}
}
}
<file_sep>/YZX.TIA/Extensions/Hwcn/DoeInstanceAccessExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using Reflection;
namespace YZX.Tia.Extensions.Hwcn
{
public static class DoeInstanceAccessExtensions
{
public static IDoeViewAccess GetDoeViewAccess(this IDoeInstanceAccess iaccess)
{
DoeInstanceAccess access = iaccess as DoeInstanceAccess;
if (access != null)
{
return Reflector.GetInstanceFieldByName(access, "m_DoeViewAccess", ReflectionWays.SystemReflection)
as IDoeViewAccess;
}
else
{
return null;
}
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/DlcManagerExtensions.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Dlc
{
public static class DlcManagerExtensions
{
public static IDlcLifetimeManager GetDlcLifetimeManager(this IDlcManager manager)
{
var lifetimeManager = Reflector.GetInstanceFieldByName(manager, "m_DlcLifetimeManager")
as IDlcLifetimeManager;
return lifetimeManager;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/StaticMethodsProxy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.CommonServices.ClipboardService;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.LoadService;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Proxies.LoadService
{
public static class StaticMethodsProxy
{
public static ICoreObject GetCommandCoreObject(object commandObject)
{
return StaticMethods.GetCommandCoreObject(commandObject);
}
public static List<ICoreObject> GetTargetClipboardObjects(IFormatterCache formatterCache)
{
return StaticMethods.GetTargetClipboardObjects(formatterCache);
}
public static bool CheckClipboardConditions(IFormatterCache formatterCache)
{
return StaticMethods.CheckClipboardConditions(formatterCache);
}
public static ICoreObject FindOfflineDevice(ICoreObject startObject,
IOnlineService onlineService)
{
return StaticMethods.FindOfflineDevice(startObject, onlineService);
}
public static void GetOfflineTargets(ICoreObject baseObject, List<ICoreObject> targets)
{
StaticMethods.GetOfflineTargets(baseObject, targets);
}
public static void GetSubOfflineTargets(ICoreObject baseObject,
List<ICoreObject> involvedOfflineTargets)
{
StaticMethods.GetSubOfflineTargets(baseObject, involvedOfflineTargets);
}
public static IList ExpandGlobalFolderToDevice(IList commandObjects)
{
return StaticMethods.ExpandGlobalFolderToDevice(commandObjects);
}
public static string GetObjectTypeAndSubType(ICoreObject selectedObject)
{
return StaticMethods.GetObjectTypeAndSubType(selectedObject);
}
public static string GetBrowsableName(ICoreObject selectedObject)
{
return StaticMethods.GetBrowsableName(selectedObject);
}
public static string GetName(ICoreObject selectedObject)
{
return StaticMethods.GetName(selectedObject);
}
public static string HwcnModuleName(ILoadConnection loadConnection)
{
return StaticMethods.HwcnModuleName(loadConnection);
}
public static ICoreObject SearchAncestor(ICoreObject descendantObject,
Type ancestorType)
{
return StaticMethods.SearchAncestor(descendantObject, ancestorType);
}
public static void SearchMinorFolderLoadObjects(ICoreObject minorFolderObject,
IList<ICoreObject> loadObjects)
{
StaticMethods.SearchMinorFolderLoadObjects(minorFolderObject, loadObjects);
}
public static string ChangeListToCommaSeparatedText(IList<string> stringList)
{
return StaticMethods.ChangeListToCommaSeparatedText(stringList);
}
public static List<string> ChangeCommaSeparatedTextToList(string commaSeparatedText)
{
return StaticMethods.ChangeCommaSeparatedTextToList(commaSeparatedText);
}
public static string LogFilePathName()
{
return StaticMethods.LogFilePathName();
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/NullSelectionManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.Selection;
namespace YZX.Tia.Proxies.Ladder
{
internal class NullSelectionManager: DefaultSelectionManager
{
internal NullSelectionManager(FLGView flgView, GraphicManager grManager)
:base(flgView,grManager)
{
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/WindowManagerProxy.cs
using System.Collections.Generic;
using System.Collections;
using System.Windows.Forms;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public partial class WindowManagerProxy
{
IWindowManagerInternal WindowManager;
public IWindowManager IWindowManager
{
get
{
return WindowManager as IWindowManager;
}
}
DlcWindowManager DlcWindowManager
{
get
{
return WindowManager as DlcWindowManager;
}
}
internal WindowManagerProxy(IWindowManagerInternal manager)
{
WindowManager = manager;
}
public Control ApplicationFrameWindow
{
get
{
return IWindowManager.ApplicationFrameWindow;
}
}
public IApplicationFrame ApplicationFrame
{
get
{
return WindowManager.ApplicationFrame;
}
}
public ApplicationFrameProxy ApplicationFrameProxy
{
get
{
return new ApplicationFrameProxy(ApplicationFrame);
}
}
public void ShowViewMode(ApplicationViewMode mode)
{
WindowManager.ShowViewMode(mode);
}
public void ShowViewMode(string mode)
{
switch (mode)
{
case "Compact":
WindowManager.ShowViewMode(ApplicationViewMode.Compact);
break;
case "Portal":
WindowManager.ShowViewMode(ApplicationViewMode.Portal);
break;
case "Project":
WindowManager.ShowViewMode(ApplicationViewMode.Project);
break;
case "Library":
WindowManager.ShowViewMode(ApplicationViewMode.Library);
break;
}
}
internal IApplicationViewModeManager ApplicationViewModeManager
{
get
{
return WindowManager.ApplicationViewModeManager;
}
}
public List<IFrame> Frames
{
get
{
return Reflector.GetInstanceFieldByName(WindowManager,
"m_FrameInstanceList",
ReflectionWays.SystemReflection)
as List<IFrame>;
}
}
public List<FrameBaseProxy> SingletonFrames
{
get
{
Hashtable hashTable = Reflector.GetInstanceFieldByName(WindowManager,
"m_SingletonFrames",
ReflectionWays.SystemReflection)
as Hashtable;
List<FrameBaseProxy> frames = new List<FrameBaseProxy>();
foreach(IFrame frame in hashTable.Values)
{
FrameBaseProxy proxy = FrameBaseProxy.ToProxy(frame);
frames.Add(proxy);
}
return frames;
}
}
public bool CompactMode
{
get
{
return ApplicationViewModeManager.CurrentView == ApplicationViewMode.Compact;
}
}
public IFrame Show(IView view, string viewFrameId, IFrameGroup existingFrames)
{
return WindowManager.Show(view, viewFrameId, existingFrames);
}
public IFrame Show(string frameId, IFrameGroup existingFrames)
{
return WindowManager.Show(frameId, existingFrames);
}
public IFrame GetSingletonFrame(string frameId)
{
return WindowManager.GetSingletonFrame(frameId);
}
public IFrame GetFrame(string frameId)
{
return WindowManager.GetFrame(frameId);
}
public IFrame GetFrame(string frameId, IFrameGroup frameGroup)
{
return WindowManager.GetFrame(frameId, frameGroup);
}
public IFrame CreateFrame(string frameId, IWorkingContext workingContext)
{
return DlcWindowManager.CreateFrame(frameId, workingContext);
}
FrameBaseMeta GetMetaData(string frameId)
{
return WindowManager.GetMetaData(frameId);
}
public FrameBaseMetaProxy GetMetaDataProxy(string frameId)
{
FrameBaseMeta meta = WindowManager.GetMetaData(frameId);
var proxy = FrameBaseMetaProxy.ToProxy(meta);
return proxy;
}
}
}
<file_sep>/YZX.TIA/Proxies/Hwcn/OnlineDeviceServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.HwConfiguration.Application.UserInterface.Basics.Controller;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
namespace YZX.Tia.Proxies.Hwcn
{
public class OnlineDeviceServiceProxy
{
internal OnlineDeviceService OnlineDeviceService;
internal OnlineDeviceServiceProxy(OnlineDeviceService service)
{
OnlineDeviceService = service;
}
public ICollection<ICoreObject> OnlineDevices
{
get
{
return OnlineDeviceService.OnlineDevices;
}
}
public IOnlineObjectService OnlineObjectService
{
get
{
return OnlineDeviceService.OnlineObjectService;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.GraphBlockLogic.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static GraphOnlineService GetGraphOnlineService([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<GraphOnlineService>("GraphBlockLogic.GraphOnlineService<");
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Sync.cs
using System.ComponentModel;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.Utilities;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static ISynchronizeInvoke GetSynchronizer(this ICoreObject coreObject)
{
return ((IDlc)coreObject.Context).WorkingContext.DlcManager.LoadByDlcId(DlcIds.Platform.Basics.SynchronizerService);
}
}
}
<file_sep>/YZX.TIA/Extensions/Oam/IOamAddressExtensions.cs
using System.Net;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.HwConfiguration.Diagnostic.OnlineFunctions.Common;
namespace YZX.Tia.Extensions
{
public static class IOamAddressExtensions
{
public static IPAddress ExtractIpAddress(this IOamAddress address)
{
return Helper.ExtractIpAddress(address);
}
}
}
<file_sep>/Siemens.Simatic.Lang.BlockLogic.Test/Extensions/BlockLogic/ICoreObjectExtensions.cs
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.OnlineReader;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus.Upload;
namespace YZX.Tia.Extensions
{
public static class ICoreObjectExtensions
{
internal static IOnlinePlusBlockAccess GetBlockAccess(ICoreObject target, ClientSession clientSession)
{
return OnlineBlockAccess.GetBlockAccess(target, clientSession);
}
internal static IOnlineReader GetOnlineReader(this ICoreObject onlineTarget)
{
return OnlineReaderFactory.GetOnlineReader(onlineTarget);
}
public static IUpload GetPlusBlockConsistencyService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
PlusBlockConsistencyService PlusBlockConsistencyService = idlcManager.Load("BlockLogic.PlusBlockConsistencyService")
as PlusBlockConsistencyService;
return PlusBlockConsistencyService;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/ViewFrameProxy.cs
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ViewFrameProxy:FrameBaseProxy
{
ViewFrame ViewFrame;
public new static ViewFrameProxy ToProxy(IFrame frame)
{
return new ViewFrameProxy(frame);
}
public ViewFrameProxy(IFrame viewFrame):base(viewFrame)
{
ViewFrame = viewFrame as ViewFrame;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameApplicationExtensions.NavigationViews.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Navigation.Library.GlobalLibrary;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.FrameApplication
{
partial class FrameApplicationExtensions
{
public static ProjectNavigationViewProxy ProjectNavigationView(this IWorkingContext workingContext)
{
ProjectNavigationView dlc = workingContext.GetRequiredDlc<ProjectNavigationView>("Siemens.Automation.FrameApplication.ProjectNavigatorView");
return new ProjectNavigationViewProxy(dlc);
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.CommandProcessor.cs
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Simatic.PlcLanguages.Utilities;
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static ICommandProcessor GetCommandProcessor(this IWorkingContext workingContext)
{
ICommandProcessor commandProcessor = DlcIdExtensions.LoadByDlcId(workingContext.DlcManager, DlcIds.Platform.CommonServices.CommandProcessor);
return commandProcessor;
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamDeviceWatcherProxy.cs
using System;
using Siemens.Automation.OnlineAccess;
namespace YZX.Tia.Proxies
{
public class OamDeviceWatcherProxy
{
OamDeviceWatcher OamDeviceWatcher;
public OamDeviceWatcherProxy(IDisposable d)
{
OamDeviceWatcher = d as OamDeviceWatcher;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableElementProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
using YZX.Tia.Extensions.Graph;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableElementProxy
{
internal DrawableElement DrawableElement;
internal DrawableElementProxy(DrawableElement element)
{
this.DrawableElement = element;
}
public List<DrawableElementProxy> ElementList
{
get
{
List<DrawableElementProxy> list = new List<DrawableElementProxy>();
foreach(var element in DrawableElement.ElementList)
{
var proxy = element.ToProxy();
list.Add(proxy);
}
return list;
}
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.OnlineService.cs
using System;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.ObjectFrame;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
private OnlineServiceProvider m_OnlineService;
public OnlineServiceProvider OnlineService
{
get
{
if (m_OnlineService == null)
{
IOnlineService ios = projectWorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService") as IOnlineService;
m_OnlineService = ios.ToOnlineServiceProvider();
}
return m_OnlineService;
}
}
internal OnlineNavigator OnlineNavigator
{
get
{
return OnlineService.Navigator;
}
}
public bool DoOperationFlash(ICoreObject target, out int errorCode, out int errorServiceID, IDiagFlashJob job)
{
bool flag = false;
errorCode = 0;
errorServiceID = 0;
if (target != null)
{
IOnlineItemAccess onlineItemProxy = OnlineService.FindOnlineItemProxy(target);
if (onlineItemProxy != null)
{
try
{
onlineItemProxy.DoOperation("Flash", job);
flag = true;
}
catch (OnlineException ex)
{
errorCode = ex.ErrorCode;
errorServiceID = ex.ErrorServiceID;
}
catch (NotSupportedException ex)
{
errorCode = 0;
errorServiceID = 241;
}
}
}
return flag;
}
public ICoreObject GetOnlineObject(
ICoreObject offlineObject,
bool initializeState,
OnlineCreateMode mode)
{
ICoreObject ico = OnlineService.GetOnlineObject(offlineObject, initializeState, mode);
return ico;
}
public void GoOnline(ICoreObject offlineTarget)
{
OnlineService.GoOnline(offlineTarget);
}
public void GoOffline()
{
OnlineService.GoOffline();
}
}
}
<file_sep>/YZX.TIA/Proxies/BlockServiceProxy.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.Lang.Model.Blocks;
namespace YZX.Tia.Proxies
{
public class BlockServiceProxy
{
IBlockService BlockService;
public BlockServiceProxy(IBlockService bs)
{
BlockService = bs;
}
public ICoreObject FindBlockByName(ICoreObject parent, BlockType type, string name)
{
return BlockService.FindBlockByName(parent, type, name);
}
public ICoreObject[] FindBlockByAddress(ICoreObject parent, BlockType type, int number)
{
return BlockService.FindBlockByAddress(parent, type, number);
}
public ICoreObject[] FindBlockByAddress(ICoreObject parent, string absoluteName)
{
return BlockService.FindBlockByAddress(parent, absoluteName);
}
public ICoreObject[] FindBlockByRID(ICoreObject parent, uint rid)
{
return BlockService.FindBlockByRID(parent, rid);
}
public string GetViewPath(ICoreObject leafObject)
{
return BlockService.GetViewPath(leafObject);
}
public List<ICoreObject> GetBlocksByTypeAndLanguage(ICoreObject parent, BlockType type, ProgrammingLanguage language)
{
List<ICoreObject> blockList = new List<ICoreObject>();
IList blocks = BlockService.GetBlocksByTypeAndLanguage(parent, type, language);
for (int i = 0; i < blocks.Count; i++)
{
blockList.Add(blocks[i] as ICoreObject);
}
return blockList;
}
public List<ICoreObject> GetBlocksByTypeAndSubtype(ICoreObject parent, BlockType type, string subtype)
{
List<ICoreObject> blockList = new List<ICoreObject>();
IList blocks = BlockService.GetBlocksByTypeAndSubtype(parent, type, subtype);
for (int i = 0; i < blocks.Count; i++)
{
blockList.Add(blocks[i] as ICoreObject);
}
return blockList;
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameApplication-ProjectNavigator.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static RootObjectHostServiceProxy GetRootObjectHostService([NotNull] this IWorkingContext workingContext)
{
RootObjectHostService dlc = workingContext.GetRequiredDlc<RootObjectHostService>("Siemens.Automation.FrameApplication.RootObjectHostService");
return new RootObjectHostServiceProxy(dlc);
}
public static ProjectNavigatorLoaderProxy GetProjectNavigatorLoader([NotNull] this IWorkingContext workingContext)
{
ProjectNavigatorLoader dlc = workingContext.GetRequiredDlc<ProjectNavigatorLoader>("Siemens.Automation.FrameApplication.ProjectNavigatorLoader");
return new ProjectNavigatorLoaderProxy(dlc);
}
}
}
<file_sep>/YZX.TIA/Extensions/IProjectManagerExtensions.cs
using Siemens.Automation.CommonServices;
using YZX.Tia.Proxies;
namespace YZX.Tia.Extensions
{
public static class IProjectManagerExtensions
{
public static TiaProjectManagerProxy GetTiaProjectManagerProxy(this IProjectManager manager)
{
TiaProjectManagerLegacyHandlerProxy proxy = new TiaProjectManagerLegacyHandlerProxy(manager);
return proxy.TiaProjectManagerProxy;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.LegitimationService.cs
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.DomainServices.ConnectionService;
using Reflection;
namespace YZX.Tia
{
partial class TiaStarter
{
private LegitimationServiceProvider m_LegitimationService;
public LegitimationServiceProvider LegitimationService
{
get
{
if (m_LegitimationService == null)
{
ILegitimationService ils = projectWorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.LegitimationService") as ILegitimationService;
m_LegitimationService = ils as LegitimationServiceProvider;
}
return m_LegitimationService;
}
}
public LegitimationServiceProvider GetLegitimationService(ICoreObject coreObject)
{
ILegitimationService legitimationService = null;
if (!coreObject.IsDeleted || !coreObject.IsDeleting)
legitimationService = ((IDlc)coreObject.Context).WorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.LegitimationService") as ILegitimationService;
return legitimationService as LegitimationServiceProvider;
}
public void ChangeLegitimationServiceObjectFactoryConnectionService(
LegitimationServiceProvider lsp,
ConnectionServiceProvider csp)
{
LegitimationServiceObjectFactory lsof = lsp.LegitimationServiceObjectFactory as LegitimationServiceObjectFactory;
Reflector.SetInstanceFieldByName(
lsof,
"m_ConnectionService",
csp,
ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Extensions/NetworkEditorFrame/IWorkingContextExtensions.Editor.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.NetworkEditorFrame
{
public static class IWorkingContextExtensions
{
public static IEditorStarter GetEditorStarterFacadeDlc(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<EditorStarterFacadeDlc>("Siemens.Simatic.PlcLanguages.BlockEditorFrame.EditorStarterFacade");
}
}
}
<file_sep>/YZX.TIA/Proxies/OnlineService/LifelistNodeDetailsProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Proxies.OnlineService
{
public class LifelistNodeDetailsProxy
{
LifelistNodeDetails LifelistNodeDetails;
public LifelistNodeDetailsProxy(object detail)
{
LifelistNodeDetails = detail as LifelistNodeDetails;
}
public ICoreObject Node
{
get
{
return LifelistNodeDetails.Node;
}
}
public bool OnlineInfoUpdated
{
get
{
return LifelistNodeDetails.OnlineInfoUpdated;
}
}
public ICoreObject OnlineDeviceNode
{
get
{
return LifelistNodeDetails.OnlineDeviceNode;
}
}
public string DeviceFamily
{
get
{
return LifelistNodeDetails.DeviceFamily;
}
}
public string DeviceName
{
get
{
return LifelistNodeDetails.DeviceName;
}
}
public string Address
{
get
{
return LifelistNodeDetails.Address;
}
}
public string DeviceTypeName
{
get
{
return LifelistNodeDetails.DeviceTypeName;
}
}
public string MLFB
{
get
{
return LifelistNodeDetails.MLFB;
}
}
public string TIAPortalConfigured
{
get
{
return LifelistNodeDetails.TIAPortalConfigured;
}
}
public string Firmware
{
get
{
return LifelistNodeDetails.Firmware;
}
}
public event EventHandler<EventArgs> UpdateEvent
{
add
{
LifelistNodeDetails.UpdateEvent += value;
}
remove
{
LifelistNodeDetails.UpdateEvent -= value;
}
}
public void UpdateOnlineInfo()
{
LifelistNodeDetails.UpdateOnlineInfo();
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/OpenProjectViewDlcProxy.cs
using System;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Portal.Views;
namespace YZX.Tia.Proxies.FrameApplication
{
public class OpenProjectViewDlcProxy
{
internal OpenProjectViewDlc OpenProjectViewDlc;
public IView IView
{
get
{
return OpenProjectViewDlc as IView;
}
}
internal OpenProjectViewDlcProxy(OpenProjectViewDlc dlc)
{
OpenProjectViewDlc = dlc;
}
public IViewFrame ViewFrame
{
get
{
return IView.ViewFrame;
}
}
public event EventHandler<PortalViewNotificationEventArgs> Notify
{
add
{
OpenProjectViewDlc.Notify += value;
}
remove
{
OpenProjectViewDlc.Notify -= value;
}
}
}
}
<file_sep>/GraphViewer/GraphForm.cs
using System;
using System.Collections;
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Forms;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonServices;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainServices.ConnectionService.Private;
using Siemens.Automation.DomainServices.DomainGrid;
using Siemens.Automation.CommonServices.AccessControl;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.Lang.Model.Idents;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.OnlineAccess;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Online;
using Reflection;
using YZXLogicEngine;
using YZX.Tia;
using YZX.Tia.Extensions;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.Graph;
using YZX.Tia.Forms;
using YZX.Tia.Proxies.Ladder;
namespace VatViewer
{
public partial class Form1 : TiaForm
{
public Form1()
{
address = "Sps7;Rack=0;Slot=2;RSA=TCP_192.168.8.111_SM_255.255.255.0_SubnetId_4C-AA-00-00-00-01;ResourceId=1;";
//address = "Sps7;Rack=0;Slot=2;RSA=TCP_192.168.1.111_SM_255.255.255.0_SubnetId_8F-21-00-00-00-02;ResourceId=1;";
address = "OMS;TSelector=SIMATIC-ROOT-ES;RSA=TCP_192.168.1.34_SM_255.255.255.0_SubnetId_11-5F-00-00-00-01;ResourceId=6;";
path = @"S:\216321\216321江森HTA\216321-315\216321-315.ap14";
path = @"S:\216889\216889-1500-1113\216889-1500-1113.ap14";
boardName = "PLCSIM";
TiaStarter.SetForm(this);
InitializeComponent();
Load += Form1_Load;
SizeChanged += Form1_SizeChanged;
//AfterSychronizer();
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
gbec.Size = Size;
}
TiaProjectProxy projectProxy;
PrimaryProjectManagerProxy PrimaryProjectManagerProxy;
PrimaryProjectUiWorkingContextManagerProxy PrimaryProjectUiWorkingContextManagerProxy;
IUIContextHolder UIContextHolder;
IWorkingContext ProjectUIContext;
public void OpenProject()
{
PrimaryProjectUiWorkingContextManagerProxy = TiaStarter.m_ViewApplicationContext.GetPrimaryProjectUiWorkingContextManagerProxy();
PrimaryProjectManagerProxy =
PrimaryProjectUiWorkingContextManagerProxy.PrimaryProjectManager;
PrimaryProjectManagerProxy.ProjectOpened += PrimaryProjectManagerProxy_ProjectOpened;
var proxy = Program.app.TiaProjectManagerProxy;
object project = null;
//proxy.OpenProjectReadWrite(path, out project);
PrimaryProjectManagerProxy.OpenProjectReadWrite(path, out project);
}
private void PrimaryProjectManagerProxy_ProjectOpened(object sender, EventArgs e)
{
UIContextHolder = PrimaryProjectUiWorkingContextManagerProxy.IUIContextHolder;
ProjectUIContext = UIContextHolder.ProjectUIContext;
projectProxy = PrimaryProjectManagerProxy.PrimaryProject;
projectProxy.WorkingContext.AutoLoadDlcs();
LoadVatTable();
TestGetLadderEditor();
}
private void TestGetLadderEditor()
{
this.gbec = Program.app.GetBlockEditor(graph);
GraphBlockEditorControlProxy pLBlockEditorControlElementProxy =
new GraphBlockEditorControlProxy(this.gbec);
OnlineManagerBase plOnlineManager = pLBlockEditorControlElementProxy.GraphBlockEditorLogic.OnlineManager;
plOnlineManager.GoOnline();
plOnlineManager.StartProgramStatus();
List<IUIControl> children = pLBlockEditorControlElementProxy.GetChildUIControls();
Controls.Add(this.gbec);
}
public void LoadVatTable()
{
cpu = projectProxy.FindCPU("216889CPU");
graph = projectProxy.BlockServiceProxy.FindBlockByAddress(cpu, BlockType.FB, 2010)[0];
}
ICoreObject graph;
string address;
string path;
string boardName = "Intel(R) Dual Band Wireless-AC 7265";
int boardNumber = 1;
int configIndex = 1;
DebugDevice dd;
DebugDeviceProxy ddp;
ConnectionServiceProvider ssp;
ThreadSynchronizerProxy tsp;
public void BeforeStartSynchronizer()
{
OpenProject();
LoadVatTable();
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Form1_Load");
BeforeStartSynchronizer();
OpenIronPythonConsole();
Resize += Form1_Resize;
}
private void Form1_Resize(object sender, EventArgs e)
{
this.gbec.Size = this.Size;
}
public void OpenIronPythonConsole()
{
IronPythonConsoleForm IPCF = new IronPythonConsoleForm();
//VarTableViewModifyExtension VTVME = ConfigVTVME();
//IPCF.PCV.SetVariable("VTVME", VTVME);
IPCF.PCV.SetVariable("app", Program.app);
IPCF.PCV.SetVariable("gbec", this.gbec);
IPCF.InitFile = "IronPython/VAT.py";
IPCF.Show();
IPCF.FormClosed += IPCF_FormClosed;
}
private void IPCF_FormClosed(object sender, FormClosedEventArgs e)
{
IronPythonConsoleForm ipcf = sender as IronPythonConsoleForm;
ipcf.Dispose();
}
static ICoreObject cpu;
}
}
<file_sep>/YZX.TIA/Proxies/Dlc/WorkingContextAccessProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.Dlc
{
public static class WorkingContextAccessProxy
{
public static IWorkingContext GetWorkingContext(this ICoreContext coreContext)
{
return WorkingContextAccess.GetWorkingContext(coreContext);
}
public static IWorkingContext GetWorkingContext(this ICorePersistence corePersistence)
{
return WorkingContextAccess.GetWorkingContext(corePersistence);
}
}
}
<file_sep>/YZX.TIA/Extensions/Graph/DrawableElementExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements.DrawableLanguageModules;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.Graph;
namespace YZX.Tia.Extensions.Graph
{
public static class DrawableElementExtensions
{
internal static DrawableElementProxy ToProxy(this DrawableElement element)
{
if(element is DrawableStep)
{
DrawableStep step = element as DrawableStep;
return new DrawableStepProxy(step);
}
if(element is DrawableLangModTogglerDSV)
{
DrawableLangModTogglerDSV dsv = element as DrawableLangModTogglerDSV;
return new DrawableLangModTogglerDSVProxy(dsv);
}
if(element is ActionListDrawLangMod)
{
ActionListDrawLangMod mod = element as ActionListDrawLangMod;
return new DrawableElementProxy(mod);
}
if(element is UIElementWrapperForUIContainer)
{
UIElementWrapperForUIContainer container = element as UIElementWrapperForUIContainer;
return new UIElementWrapperForUIContainerProxy(container);
}
if(element is DrawableTransition)
{
DrawableTransition transition = element as DrawableTransition;
return new DrawableTransitionProxy(transition);
}
return new DrawableElementProxy(element);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameApplication-ProjectManagment.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.Portal.Views;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static OpenProjectViewDlcProxy GetOpenProjectViewDlc([NotNull] this IWorkingContext workingContext)
{
OpenProjectViewDlc dlc = workingContext.GetRequiredDlc<OpenProjectViewDlc>("Siemens.Automation.FrameApplication.Portal.Views.OpenProjectViewDlc");
return new OpenProjectViewDlcProxy(dlc);
}
}
}
<file_sep>/Siemens.Simatic.Lang.NetworkEditorFrame.Test/Proxies/NetworkEditorFrame/PLBlockEditorControlElementProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.UI.Controls.WindowlessFramework;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Taskcards.Instruction;
namespace YZX.Tia.Proxies.NetworkEditorFrame
{
public class PLBlockEditorControlElementProxy
{
internal PLBlockEditorControlElement PLBlockEditorControlElement;
public PLBlockEditorControlElementProxy(BlockEditorControlBase element)
{
PLBlockEditorControlElement = element as PLBlockEditorControlElement;
}
public BlockEditorLogicBase PLBlockEditorLogic
{
get
{
return PLBlockEditorControlElement.PLBlockEditorLogic;
}
}
public PLBlockEditorLogicProxy PLBlockEditorLogicProxy
{
get
{
return new PLBlockEditorLogicProxy(PLBlockEditorLogic);
}
}
public FavouritesControl FavouritsToolBar
{
get
{
return PLBlockEditorControlElement.FavouritsToolBar;
}
}
public BlockHeaderPaletteElement BlockHeaderPalette
{
get
{
return PLBlockEditorControlElement.BlockHeaderPalette as BlockHeaderPaletteElement;
}
}
public List<NetworkElementProxy> GetNetworks()
{
UIElementCollection networks = PLBlockEditorControlElement.NetworksContainer.GetNetworks();
List<NetworkElementProxy> proxies = new List<NetworkElementProxy>();
foreach(UIElement network in networks)
{
if(network is NetworkElement)
{
NetworkElement ne = network as NetworkElement;
NetworkElementProxy proxy = new NetworkElementProxy(ne);
proxies.Add(proxy);
}
}
return proxies;
}
}
}
<file_sep>/YZX.TIA/Converter/OnlineServiceConverters.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using YZX.Tia.Proxies.OnlineService;
namespace YZX.Tia.Converter
{
public static class OnlineServiceConverters
{
internal static OnlineCommonNodeProxy OnlineCommonNodeProxy(OnlineCommonNode node)
{
return new OnlineCommonNodeProxy(node);
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphAction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphActionProxy
{
internal GraphAction GraphActions;
internal GraphActionProxy(GraphAction actions)
{
GraphActions = actions;
}
public bool IsOnAction
{
get
{
return GraphActions.IsOnAction;
}
}
public bool IsOffAction
{
get
{
return GraphActions.IsOffAction;
}
}
public bool IsOffAllAction
{
get
{
return GraphActions.IsOffAllAction;
}
}
public bool IsEmptyAction
{
get
{
return GraphActions.IsEmptyAction;
}
}
public int Id
{
get
{
return GraphActions.Id;
}
set
{
GraphActions.Id = value;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphActionsProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphActionsProxy:GraphNetElementProxy
{
internal GraphActions GraphActions;
internal GraphActionsProxy(GraphActions actions):base(actions)
{
GraphActions = actions;
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/MetaDataReaderProxy.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class MetaDataReaderProxy
{
public static Hashtable NameToMetaDataMapping
{
get
{
return MetaDataReader.NameToMetaDataMapping;
}
}
public static Dictionary<string,FrameBaseMetaProxy> NameToMetaDataProxy
{
get
{
Dictionary<string, FrameBaseMetaProxy> map = new Dictionary<string, FrameBaseMetaProxy>();
foreach(string key in NameToMetaDataMapping.Keys)
{
FrameBaseMeta meta = NameToMetaDataMapping[key] as FrameBaseMeta;
FrameBaseMetaProxy proxy = FrameBaseMetaProxy.ToProxy(meta);
map[key] = proxy;
}
return map;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.FrameLocator.cs
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Undo;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IViewFrame ProjectTreeViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.ProjectLibraryTreeViewFrame(workingContext);
}
public static IViewFrame FolderPortalViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.FolderPortalViewFrame(workingContext);
}
public static IViewFrame DetailsViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.DetailsViewFrame(workingContext);
}
public static IViewFrame ProjectLibraryTreeViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.ProjectLibraryTreeViewFrame(workingContext);
}
public static IViewFrame GlobalLibraryTreeViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.GlobalLibraryTreeViewFrame(workingContext);
}
public static IFrame ElementsFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.ElementsFrame(workingContext);
}
public static IViewFrame PartsViewFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.PartsViewFrame(workingContext);
}
public static bool IsWithinPortalViewFrameHierarchy(IFrame frame)
{
return FrameLocator.IsWithinPortalViewFrameHierarchy(frame);
}
public static bool IsPropertyViewFrame(IViewFrame viewFrame)
{
return FrameLocator.IsPropertyViewFrame(viewFrame);
}
public static IFrame GetFrame([NotNull] this IWorkingContext workingContext, string frameId)
{
return FrameLocator.GetFrame(workingContext, frameId);
}
public static IFrame GetEditorMainFrame([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetFrame("EditorMainFrame");
}
public static EditorMainFrameProxy GetEditorMainFrameProxy([NotNull] this IWorkingContext workingContext)
{
IFrame frame = workingContext.GetEditorMainFrame();
var proxy = new EditorMainFrameProxy(frame);
return proxy;
}
public static IFrame ActiveFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.ActiveFrame(workingContext);
}
public static IEditorFrame ActiveEditor([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.ActiveEditor(workingContext);
}
public static IEditorPageFrame GetActiveEditorPageFrame([NotNull] this IWorkingContext workingContext)
{
return FrameLocator.GetActiveEditorPageFrame(workingContext);
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.Dlc.cs
using System;
using Siemens.Automation.Basics;
namespace YZX.Tia.Dlc
{
public static partial class IWorkingContextExtensions
{
public static T GetOptionalDlc<T>(this IWorkingContext workingContext,
string serviceId)
where T : class
{
return GetDlcInternal<T>(workingContext, serviceId, false);
}
public static T GetRequiredDlc<T>(this IWorkingContext workingContext,
string serviceId)
where T : class
{
return GetDlcInternal<T>(workingContext, serviceId, true);
}
public static T GetDlcInternal<T>(this IWorkingContext workingContext,
string serviceId,
bool throwExceptionOnFailure)
where T : class
{
if (workingContext == null)
throw new ArgumentNullException("workingContext");
if (string.IsNullOrEmpty(serviceId))
throw new ArgumentNullException("serviceId");
object obj1 = workingContext.DlcManager.Load(serviceId, throwExceptionOnFailure);
if (obj1 == null && throwExceptionOnFailure)
throw new DlcManagerException(string.Format("Could not load Dlc with service id '{0}'.", serviceId));
T obj2 = ServiceProviderHelper.AccessService<T>(obj1);
if (obj2 == null && throwExceptionOnFailure)
throw new DlcManagerException(string.Format("Dlc with service id '{0}' does not implement '{1}'.", serviceId, typeof(T).FullName));
return obj2;
}
}
}
<file_sep>/Siemens.Automation.Archiving.Test/Extensions/TIAzlib128.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Archiving.Private;
namespace YZX.Tia.Extensions.Archiving
{
public static class ZlibExtensions
{
[DllImport("zlib128-tia.dll", EntryPoint = "unzCloseCurrentFile", CallingConvention = CallingConvention.Cdecl)]
internal static extern int UnzCloseCurrentFile(IntPtr handle);
[DllImport("zlib128-tia.dll", EntryPoint = "unzClose", CallingConvention = CallingConvention.Cdecl)]
internal static extern int UnzClose(IntPtr handle);
[DllImport("zlib128-tia.dll", EntryPoint = "unzGoToFirstFile", CallingConvention = CallingConvention.Cdecl)]
internal static extern int UnzGoToFirstFile(IntPtr handle);
[DllImport("zlib128-tia.dll", EntryPoint = "unzGoToNextFile", CallingConvention = CallingConvention.Cdecl)]
internal static extern int UnzGoToNextFile(IntPtr handle);
[DllImport("zlib128-tia.dll", EntryPoint = "unzGetCurrentFileInfo64", CallingConvention = CallingConvention.Cdecl)]
internal static extern int UnzGetCurrentFileInfo(IntPtr handle, out ZlibDllWrapper.UnzipFileInfo fileInfo, byte[] fileNameArray, uint fileNameBufferSize, IntPtr extraField, uint extraFieldBufferSize, IntPtr comment, uint commentBufferSize);
}
}
<file_sep>/Siemens.Automation.OnlineAccess.Test.Basics/Proxies/OnlineInterface/OamEthernetConnectionsWatcherProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamEthernetConnectionsWatcherProxy
{
private static OamEthernetConnectionsWatcherProxy s_Instance;
public static OamEthernetConnectionsWatcherProxy Instance
{
get
{
if(s_Instance == null)
{
s_Instance = new OamEthernetConnectionsWatcherProxy(OamEthernetConnectionsWatcher.Instance);
}
return s_Instance;
}
}
OamEthernetConnectionsWatcher OamEthernetConnectionsWatcher;
internal OamEthernetConnectionsWatcherProxy(OamEthernetConnectionsWatcher watcher)
{
OamEthernetConnectionsWatcher = watcher;
}
public static OamEthernetConnectionsWatcherProxy Initialize()
{
return new OamEthernetConnectionsWatcherProxy(OamEthernetConnectionsWatcher.Initialize());
}
public int AddConnection(IEthernetDiscoverConnection edConnection)
{
return OamEthernetConnectionsWatcher.AddConnection(edConnection);
}
public void RemoveConnection(IEthernetDiscoverConnection edConnection)
{
OamEthernetConnectionsWatcher.RemoveConnection(edConnection);
}
public int PingEthernetNode(IEthernetDiscoverConnection connection)
{
EthernetDiscoverConnection edc = connection as EthernetDiscoverConnection;
return OamEthernetConnectionsWatcher.PingEthernetNode(edc);
}
}
}
<file_sep>/YZX.TIA/Proxies/CommonProjectHandlingProxy.cs
using Siemens.Automation.Basics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication.ProjectWizard;
namespace YZX.Tia.Proxies
{
public class CommonProjectHandlingProxy
{
public static List<IStarterFileInfo> LastRecentProjects(IWorkingContext workingContext,
out int maxRecentlyUsedProjectsToShow)
{
return CommonProjectHandling.LastRecentProjects(workingContext, out maxRecentlyUsedProjectsToShow);
}
public static List<IStarterFileInfo> LastRecentProjects(IWorkingContext workingContext)
{
return CommonProjectHandling.LastRecentProjects(workingContext);
}
public static void DeleteProjectFromRecentList(IWorkingContext workingContext, string project)
{
CommonProjectHandling.DeleteProjectFromRecentList(workingContext, project);
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/UIElementWrapperForPalettesProxy.cs
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.UIElements;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class UIElementWrapperForPalettesProxy:SelectableUIElementWrapperProxy
{
internal UIElementWrapperForPalettes palettes;
internal UIElementWrapperForPalettesProxy(UIElementWrapperForPalettes palettes)
:base(palettes)
{
this.palettes = palettes;
}
internal LanguagePaletteBaseElement Palette
{
get
{
return Reflector.GetInstancePropertyByName(palettes, "Palette",
ReflectionWays.SystemReflection) as LanguagePaletteBaseElement;
}
}
}
}<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/TaskCardServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.UI.Controls;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.StatusBar;
using Siemens.Automation.FrameApplication.TaskCards;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class TaskCardServiceProxy
{
internal TaskCardService TaskCardService;
public TaskCardServiceProxy(ITaskCardService dlc)
{
TaskCardService = dlc as TaskCardService;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.TiaProjectManager.cs
using System;
using Siemens.Automation.ProjectManager.Impl.Tia;
using YZX.Tia.Proxies;
using Reflection;
namespace YZX.Tia
{
partial class TiaStarter
{
TiaProjectManager TiaProjectManager
{
get
{
Type type = typeof(TiaProjectManagerDlc);
TiaProjectManager TiaProjectManager =
Reflector.RunStaticMethodByName(type, "CreateProjectManager", m_BusinessLogicApplicationContext)
as TiaProjectManager;
return TiaProjectManager;
}
}
public TiaProjectManagerProxy TiaProjectManagerProxy
{
get
{
TiaProjectManagerProxy proxy = new TiaProjectManagerProxy(TiaProjectManager);
return proxy;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/GraphModelProxy.cs
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.Model;
using Siemens.Simatic.PlcLanguages.GraphEditor.Model.GraphElements;
using Reflection;
namespace YZX.Tia.Proxies.Graph
{
public class GraphModelProxy
{
internal GraphModel model;
public GraphModelProxy(Component model)
{
this.model = model as GraphModel;
}
public DebugManagerProxy DebugManagerProxy
{
get
{
return new DebugManagerProxy(model.DebugManager);
}
}
public bool ReadOnly
{
get
{
return model.ReadOnly;
}
set
{
Reflector.SetInstancePropertyByName(model, "ReadOnly", value,
ReflectionWays.SystemReflection);
}
}
public int GetMaximumActiveStepCount()
{
return model.GetMaximumActiveStepCount();
}
public List<SequenceProxy> SequenceProxies
{
get
{
List<SequenceProxy> list = new List<SequenceProxy>();
foreach (Sequence seq in model.Sequences)
{
SequenceProxy proxy = new SequenceProxy(seq);
list.Add(proxy);
}
return list;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/LifelistNodeProxyExtensions.cs
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Automation.DomainServices.OnlineService;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class LifelistNodeProxyExtensions
{
public static INode GetPhysicalLifelistNode(this LifelistNodeProxy proxy)
{
return Reflector.RunInstanceMethodByName(proxy, "GetPhysicalLifelistNode",
ReflectionWays.SystemReflection) as INode;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.Lifelist.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using Siemens.Automation.DomainServices.OnlineService;
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static LifelistActivator GetLifelistActivator(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.LifelistActivator") as LifelistActivator;
}
public static ILifelistService GetLifelist(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.LifelistService") as ILifelistService;
}
public static LifeListView GetLifeListView(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.UI.OnlineCommon.LifeListView") as LifeListView;
}
public static LifeListEmbeddedPortalView GetLifeListEmbeddedPortalView(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.UI.OnlineCommon.LifeListEmbeddedPortalView") as LifeListEmbeddedPortalView;
}
public static LifelistBrowserExtension GetLifelistBrowserExtension(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<LifelistBrowserExtension>("Siemens.Automation.DomainServices.LifelistBrowserExtension");
}
public static LifelistPNVBrowserExtension GetLifelistPNVBrowserExtension(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<LifelistPNVBrowserExtension>("Siemens.Automation.DomainServices.LifelistPNVBrowserExtension");
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.BlockEditor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using YZX.Tia.Proxies;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public BlockEditorControlBase GetBlockEditor(ICoreObject pl)
{
UIContextHolder = PrimaryProjectUiWorkingContextManagerProxy.IUIContextHolder;
ProjectUIContext = UIContextHolder.ProjectUIContext;
IEditorStarter starter = ProjectUIContext.GetEditorStarterFacadeDlc();
OpenEditorContext openEditorContext = new OpenEditorContext(pl, ProjectUIContext);
OpenEditorResult result = starter.OpenEditor(openEditorContext);
if (result.HasEditor)
{
IEditor ieditor = result.Editor;
Editor editor = ieditor as Editor;
IEditorViewFrameProvider IEditorViewFrameProvider = editor;
Control control = IEditorViewFrameProvider.MainViewFrame.View.Control;
return control as BlockEditorControlBase;
}
else
{
return null;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/TagServiceProxy.cs
using System;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.TagService;
using Siemens.Simatic.PlcLanguages.TagTableViewer;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.Meta;
using Reflection;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
public class TagServiceProxy
{
internal TagService TagService;
private TagServiceCore core;
internal TagServiceCore TSC
{
get
{
if(core == null)
{
core = TagService.GetTagServiceCore();
}
return core;
}
}
public TagServiceProxy(ITagService ts)
{
TagService = ts as TagService;
}
public object GetStrategyForItem(ICoreObject coreObject, bool throwOnError)
{
return Reflector.RunInstanceMethodByName(
TSC,
"GetStrategyForItem",
ReflectionWays.SystemReflection,
coreObject,
throwOnError);
}
public ICoreObject CreateTagTable(
ICoreObject folder,
IObjectTypeInfo tagTableType,
bool defaultTagTable = false,
string name = "")
{
using (new ObjectFrameBulkOperationMode(folder))
{
return Reflector.RunInstanceMethodByName(
TSC,
"CreateTagTable",
ReflectionWays.SystemReflection,
folder,
tagTableType,
defaultTagTable,
name) as ICoreObject;
}
}
}
}
<file_sep>/Siemens.Automation.CommonTrace.IntegrationDotNet.Test/Extensions/TraceManagerExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.CommonTrace.TraceIntegrationDotNet;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia
{
public class TraceManagerExtensions
{
public static ITraceObserver GetTrace(string componentName, string className)
{
var manager = TraceManager.Instance;
var TracerStore = Reflector.GetInstanceFieldByName(TraceManager.Instance,"m_TracerStore")
as Dictionary<string, IComponentTrace>;
foreach(var k in TracerStore.Keys)
{
if(k== componentName)
{
HierarchyName hierarchyName = new HierarchyName(componentName, className, null);
var componentTrace = TracerStore[k];
var trace = componentTrace.GetTracerForClass(hierarchyName);
return trace as ITraceObserver;
}
}
return null;
}
}
}
<file_sep>/YZX.TIA/Extensions/Vat/VatServiceExtensions.cs
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
using Siemens.Simatic.PlcLanguages.VatService;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class VatServiceExtensions
{
public static void SetDebugService(this VatService vs,DebugService ds)
{
Reflector.SetInstanceFieldByName(vs, "m_DebugService", ds,ReflectionWays.SystemReflection);
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/GraphBlockEditorLogicProxy.cs
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
namespace YZX.Tia.Proxies.Graph
{
public class GraphBlockEditorLogicProxy
{
private BlockEditorLogicBase graphBlockEditorLogic;
public GraphBlockEditorLogicProxy(BlockEditorLogicBase graphBlockEditorLogic)
{
this.graphBlockEditorLogic = graphBlockEditorLogic;
}
}
}<file_sep>/YZX.TIA/Proxies/InternalCoreObjectCollectionProxy.cs
using System.ComponentModel;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Proxies
{
public class InternalCoreObjectCollectionProxy
{
InternalCoreObjectCollection ICOC;
public ISynchronizeInvoke UsingSynchronizer;
public InternalCoreObjectCollectionProxy(ICoreObjectCollection icoc, ISynchronizeInvoke synchronizer = null)
{
ICOC = icoc as InternalCoreObjectCollection;
UsingSynchronizer = synchronizer;
}
public ICoreObject this[int index]
{
get
{
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
() =>
{
if (index <= ICOC.Count - 1)
{
return ICOC[index] as ICoreObject;
}
else
{
return null;
}
}) as ICoreObject;
}
}
public int Count
{
get
{
return ICOC.Count;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/RootTagCollectionProxy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.TagService;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
public class RootTagCollectionProxy
{
RootTagCollection RTC;
public ISynchronizeInvoke UsingSynchronizer;
public RootTagCollectionProxy(IList rtc, ISynchronizeInvoke synchronizer = null)
{
RTC = rtc as RootTagCollection;
UsingSynchronizer = synchronizer;
}
public InternalCoreObjectCollectionProxy CoreObjectCollection
{
get
{
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<InternalCoreObjectCollectionProxy>)(() =>
{
InternalCoreObjectCollectionProxy icocp =
new InternalCoreObjectCollectionProxy(RTC.CoreObjectCollection,UsingSynchronizer);
return icocp;
})) as InternalCoreObjectCollectionProxy;
}
}
public List<IBLTag> Tags
{
get
{
return TiaStarter.RunInSynchronizer(UsingSynchronizer,
(Func<List<IBLTag>>)(() =>
{
List<IBLTag> tags = new List<IBLTag>();
for(int i = 0;i < CoreObjectCollection.Count; i++)
{
ICoreObject coreObject = CoreObjectCollection[i];
IBLTag tag = coreObject.ToBLTag();
tags.Add(tag);
}
return tags;
})) as List<IBLTag>;
}
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/Upload/UploadOnlineAccessProjectProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class UploadOnlineAccessProjectProxy:UploadOnlineAccessBaseProxy
{
UploadOnlineAccessProject UploadOnlineAccessProject;
internal UploadOnlineAccessProjectProxy(UploadOnlineAccessProject project)
:base(project)
{
UploadOnlineAccessProject = project;
}
}
}
<file_sep>/YZX.TIA/S7DOS.cs
using System.ServiceProcess;
namespace YZX.Tia
{
public class S7DOS
{
/// <summary>
/// Returns the Service name of the S7DOS-Service correspondig to operating system.
/// s7oiehsx on 32 Bit an s7oiehsx64 on 64 Bit
/// </summary>
/// <returns>The Service name of the S7DOS-Service, or Empty if could not be determined.</returns>
public static string GetS7DOSHelperServiceName()
{
string machineName = "."; // local
ServiceController[] services = null;
try
{
services = ServiceController.GetServices(machineName);
}
catch
{
return string.Empty;
}
for (int i = 0; i < services.Length; i++)
{
if (services[i].ServiceName == "s7oiehsx")
{
return services[i].ServiceName;
}
else if (services[i].ServiceName == "s7oiehsx64")
{
return services[i].ServiceName;
}
}
return string.Empty;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/BrowsableGridUtilitiesProxy.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using Siemens.Automation.Basics.Browsing;
using Siemens.Automation.FrameApplication.BrowsableGridSupport.Logics;
using Siemens.Automation.FrameApplication.BrowsableGridSupport.StatesHandling;
using Siemens.Automation.FrameApplication.SessionMemory;
using Siemens.Automation.FrameApplication.Utilities;
using Siemens.Automation.UI.Controls.Grid;
using Siemens.Automation.FrameApplication.BrowsableGridSupport;
namespace YZX.Tia.Proxies.FrameApplication
{
public static class BrowsableGridUtilitiesProxy
{
public static void EnsureBrowsableGrid(Grid grid)
{
BrowsableGridUtilities.EnsureBrowsableGrid(grid);
}
}
}
<file_sep>/YZX.TIA/Proxies/OamNodeProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamNodeProxy:OamNodeBaseProxy
{
OamNode OamNode;
public OamNodeProxy(INode node):base(node)
{
OamNode = node as OamNode;
}
internal List<OamSharedConnectionServer> SharedServers { get; }
public List<INode> Parent
{
get
{
OamNodeCollection nodes = OamNode.Parent as OamNodeCollection;
List<INode> nodeList = new List<INode>(nodes.Count);
foreach(OamNode node in nodes)
{
nodeList.Add(node);
}
return nodeList;
}
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Proxies/Dlc/DlcManagerProxy.cs
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.Dlc
{
public class DlcManagerProxy
{
DlcManager Manager;
public DlcManagerProxy(IDlcManager manager)
{
Manager = manager as DlcManager;
}
}
}
<file_sep>/YZX.TIA/Proxies/Ladder/FLGViewAccessibleObjectProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View.Accessibility;
namespace YZX.Tia.Proxies.Ladder
{
public class FLGViewAccessibleObjectProxy
{
internal IFLGAccessibleObject iFLGAccessibleObject;
internal FLGViewAccessibleObjectProxy(IFLGAccessibleObject iFLGAccessibleObject)
{
this.iFLGAccessibleObject = iFLGAccessibleObject;
}
internal System.Windows.Forms.AccessibleObject GetAccessibleChildObject(IGraphicObject graphicObject)
{
return iFLGAccessibleObject.GetAccessibleChildObject(graphicObject);
}
public System.Windows.Forms.AccessibleObject GetAccessibleChildObject(GraphicObjectProxy graphicObject)
{
return GetAccessibleChildObject(graphicObject.graphicObject);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/ApplicationFrameProxy.cs
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class ApplicationFrameProxy:HierarchyFrameProxy
{
ApplicationFrame ApplicationFrame;
IApplicationFrameInternal IApplicationFrameInternal
{
get
{
return ApplicationFrame;
}
}
public ApplicationFrameProxy(IFrame frame) : base(frame)
{
ApplicationFrame = frame as ApplicationFrame;
}
public void ShowMenu()
{
IApplicationFrameInternal.ShowMenu();
}
public void HideMenu()
{
IApplicationFrameInternal.HideMenu();
}
public void ShowToolBar()
{
IApplicationFrameInternal.ShowToolBar();
}
public void HideToolBar()
{
IApplicationFrameInternal.HideToolBar();
}
public void SetBargeSign(bool activate)
{
ApplicationFrame.SetBargeSign(activate);
}
}
}
<file_sep>/YZX.TIA/Extensions/OMS/OMSPlusConnectionServiceExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.SystemDiagnosis.Comm.OMSPlusService;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class OMSPlusConnectionServiceExtensions
{
public static void SetConnection(this OMSPlusConnectionService service,
IOMSConnection connection)
{
Reflector.SetInstanceFieldByName(service,
"m_Connection", connection, ReflectionWays.SystemReflection);
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.BlockEditor.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.PLInterface;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static BlockEditorStarter GetBlockEditorStarter([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<BlockEditorStarter>("Siemens.Simatic.PlcLanguages.PLInterface.BlockEditorStarter");
}
public static CodeBlockEditorStarterDlcBase GetNetworkEditorStarterDlc([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<CodeBlockEditorStarterDlcBase>("Siemens.Simatic.PlcLanguages.NetworkEditorFrame.EditorStarter");
}
public static object GetBlockEditorController([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.PlcLanguages.BlockEditorFrame.EditorController");
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.TagService.cs
using System;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Threading;
using Siemens.Automation.DomainServices;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.Utilities;
using Siemens.Automation.Basics;
using System.ComponentModel;
namespace YZX.Tia
{
partial class TiaStarter
{
public ITagService TagService
{
get
{
return projectWorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.TagService") as ITagService;
}
}
internal static bool RunInSynchronizer(ISynchronizeInvoke usingSynchronizer, Func<bool> p)
{
return true;
}
internal static void RunActionInSynchronizer(ISynchronizeInvoke usingSynchronizer, Action action)
{
}
internal static IBLTag RunFuncInSynchronizer(ISynchronizeInvoke usingSynchronizer, Func<ICoreObject, IBLTag> func, ICoreObject tagRef)
{
throw new NotImplementedException();
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/EditorFrameProxy.cs
using System;
using System.Collections.Generic;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.WindowManager;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class EditorFrameProxy:HierarchyFrameProxy
{
EditorFrame EditorFrame;
public IEditorFrame IEditorFrame
{
get
{
return EditorFrame;
}
}
IEditorFrameInternal IEditorFrameInternal
{
get
{
return EditorFrame;
}
}
public EditorFrameProxy(IFrame frame) : base(frame)
{
EditorFrame = frame as EditorFrame;
}
public bool HideTabHeader
{
get
{
return IEditorFrame.HideTabHeader;
}
}
public EditorTitle Title
{
get
{
return IEditorFrame.Title;
}
}
public bool IsPinned
{
get
{
return IEditorFrameInternal.IsPinned;
}
}
public ApplicationViewMode ViewModeAttachedTo
{
get
{
return IEditorFrameInternal.ViewModeAttachedTo;
}
}
public IEditorStateService EditorStateService
{
get
{
return IEditorFrameInternal.EditorStateService;
}
}
public bool IsFloating
{
get
{
return IEditorFrameInternal.IsFloating;
}
}
public bool IsMinimized
{
get
{
return IEditorFrameInternal.IsMinimized;
}
}
public void IndicateStatus(string function, bool state)
{
Type t = typeof(ControlBoxFunction);
ControlBoxFunction f = (ControlBoxFunction)Enum.Parse(t, function);
EditorFrame.IndicateStatus(f, state);
}
public object EditorViewModeProvider
{
get
{
return Reflector.GetInstanceFieldByName(EditorFrame,
"m_EditorViewModeProvider",
ReflectionWays.SystemReflection);
}
}
internal IEditorWorkedOnObjectService EditorWorkedOnObjectService
{
get
{
return Reflector.GetInstanceFieldByName(EditorFrame,
"m_EditorWorkedOnObjectService",
ReflectionWays.SystemReflection)
as IEditorWorkedOnObjectService;
}
}
public object WorkedOnObject
{
get
{
return EditorWorkedOnObjectService.WorkedOnObject;
}
set
{
EditorWorkedOnObjectService.WorkedOnObject = value;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/FrameApplication/LifeListViewExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.UI.OnlineCommon;
using Reflection;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.FrameApplication;
namespace YZX.Tia.Extensions.FrameApplication
{
public static class LifeListViewExtensions
{
public static LifeListDialogProxy GetLifeListDialogProxy(this LifeListView lifeListView)
{
LifeListDialog dialog = lifeListView.LifeListControl;
var proxy = new LifeListDialogProxy(dialog);
return proxy;
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreContextExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainModel;
using Siemens.Simatic.PLCMessaging;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.AlarmServices.Interfaces.Alarms;
using Siemens.Simatic.AlarmServices.Helper;
using Siemens.Simatic.AlarmServices.Gui.ControllerAlarmView;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class ICoreContextExtensions
{
public static string GetObjectName(this ICoreObject element)
{
ICoreAttributes coreAttributes = element.GetAttributeSet(typeof(ICoreAttributes)) as ICoreAttributes;
if (coreAttributes == null)
return "";
return coreAttributes.Name;
}
public static ICoreObject CreateTempControllerTarget(this ICoreContext projectContext,
string configObjectTypeName, string plcName)
{
return Reflector.RunStaticMethodByName(typeof(BLBlockProcessor),
"CreateTempControllerTarget",
ReflectionWays.SystemReflection,
projectContext, configObjectTypeName, plcName) as ICoreObject;
}
public static PLCMsgConnector GetPlcmService(this ICoreContext coreContext)
{
return ((IDlc)coreContext).WorkingContext.DlcManager.Load("Siemens.Simatic.PLCMessaging.PLCMsgConnector") as PLCMsgConnector;
}
public static int GetPnoIdent(ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier;
return 0;
}
public static int GetProfinetVendorId(this ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier >> 16;
return 0;
}
public static int GetProfinetDeviceId(this ICoreObject lifelistNode)
{
ILifelistNodeInfo lifelistNodeInfo = lifelistNode.GetAttributeSet(typeof(ILifelistNodeInfo)) as ILifelistNodeInfo;
if (lifelistNodeInfo != null)
return lifelistNodeInfo.PnoIdentifier & ushort.MaxValue;
return 0;
}
public static IControllerAlarm GetControllerAlarm(this ICoreObject coreObject)
{
IControllerAlarm alarm =
BusinessLogicConnectorHelper.GetBusinessLogic<IControllerAlarm>(
coreObject,
"Siemens.Simatic.AlarmServices.AlarmBusinessLogicFactory");
return alarm;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Extensions/OnlineService/LifelistActivatorExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Extensions.Lifelist
{
public static class LifelistActivatorExtensions
{
public static LifeListRootObjectWrapper GetLifeListRootObjectWrapper(this LifelistActivator activator)
{
return Reflector.GetInstanceFieldByName(activator, "m_RootObjectWrapper",
ReflectionWays.SystemReflection) as LifeListRootObjectWrapper;
}
public static IWorkingContext GetPersistanceViewContext(this LifelistActivator activator)
{
return Reflector.GetInstanceFieldByName(activator, "m_PersistanceViewContext",
ReflectionWays.SystemReflection) as IWorkingContext;
}
public static IWorkingContext GetProjectViewContext(this LifelistActivator activator)
{
return Reflector.GetInstanceFieldByName(activator, "m_ProjectViewContext",
ReflectionWays.SystemReflection) as IWorkingContext;
}
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.Editor.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Services.Starter;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IEditorStarter GetEditorStarterFacadeDlc([NotNull] this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<EditorStarterFacadeDlc>("Siemens.Simatic.PlcLanguages.BlockEditorFrame.EditorStarterFacade");
}
}
}
<file_sep>/YZX.TIA/Forms/TiaForm.cs
using System;
using Siemens.Automation.UI.Controls;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.StatusBar;
namespace YZX.Tia.Forms
{
public class TiaForm: Form
{
public TiaForm()
{
//Load += TiaForm_Load;
}
StatusBarControl StatusBarControl;
private void TiaForm_Load(object sender, EventArgs e)
{
StatusBarControl = new StatusBarControl(TiaStarter.m_ViewApplicationContext);
Controls.Add(StatusBarControl);
SizeChanged += TiaForm_SizeChanged;
}
private void TiaForm_SizeChanged(object sender, EventArgs e)
{
StatusBarControl.Width = Width;
StatusBarControl.Height = 50;
}
protected override void Dispose(bool disposing)
{
try
{
base.Dispose(disposing);
}catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/Download/DownloadCommandServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Download
{
public class DownloadCommandServiceProxy
{
DownloadCommandService DownloadCommandService;
public DownloadCommandServiceProxy(object downloadCommandService)
{
DownloadCommandService = downloadCommandService as DownloadCommandService;
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamComBoardProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamComBoardProxy:OamLocalBoardBaseProxy
{
OamComBoard OamLocalBoard;
public OamComBoardProxy(IOamLocalBoard localBoard):base(localBoard)
{
OamLocalBoard = localBoard as OamComBoard;
}
}
}
<file_sep>/YZX.TIA/README.md
# YZX.TIA.PUBLIC
use TIA as an software platform</br>
将博图作为软件平台使用</br>
1. [Add some menu in the Portal view](https://github.com/yanzixiang/YZX.TIA.PUBLIC/wiki/Add-some-menu-in-the-Portal-view)</br>
在Portal视图中添加菜单
2. [Add IronPython Console for controls in Wincc Design Editor](https://github.com/yanzixiang/YZX.TIA.PUBLIC/wiki/Add-IronPython-Console-for-controls-in-Wincc-Design-Editor)</br>
在Wincc设计画面中为每个控件添加IronPython控制台
3. [Change the splash image](https://github.com/yanzixiang/YZX.TIA.PUBLIC/wiki/Change-the-splash-image)</br>
更换启动画面
4. [Open Graph Editor](https://github.com/yanzixiang/YZX.TIA.PUBLIC/wiki/Open-Graph-Editor)</br>
打开顺序流程图编辑器
5. [Open Ladder Editor](https://github.com/yanzixiang/YZX.TIA.PUBLIC/wiki/Open-Ladder-Editor)</br>
打开梯型图编辑器<file_sep>/YZX.TIA/Proxies/LoadConnectionOnlineProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies
{
public class LoadConnectionOnlineProxy
{
LoadConnectionOnline LoadConnectionOnline;
public LoadConnectionOnlineProxy(ILoadConnection connection)
{
LoadConnectionOnline = connection as LoadConnectionOnline;
}
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/LoadService/Upload/UploadServiceProxy.cs
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices.LoadService;
namespace YZX.Tia.Proxies.LoadService.Upload
{
public class UploadServiceProxy
{
UploadService UploadService;
public UploadServiceProxy(object us)
{
UploadService = us as UploadService;
}
public UploadServiceProxy(IWorkingContext workingContext)
{
UploadService = new UploadService(workingContext);
}
}
}
<file_sep>/YZX.TIA/Proxies/Oam/OamLocalBoardProxy.cs
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class OamLocalBoardProxy:OamLocalBoardBaseProxy
{
OamLocalBoard OamLocalBoard;
public OamLocalBoardProxy(IOamLocalBoard localBoard):base(localBoard)
{
OamLocalBoard = localBoard as OamLocalBoard;
}
public string HardwareID
{
get
{
return OamLocalBoard.HardwareID;
}
}
public string Unit
{
get
{
return OamLocalBoard.Unit;
}
}
public string HwInstanceId
{
get
{
return OamLocalBoard.HwInstanceId;
}
}
public string NdisLinkage
{
get
{
return OamLocalBoard.NdisLinkage;
}
set
{
OamLocalBoard.NdisLinkage = value;
}
}
public string ServiceInstance
{
get
{
return OamLocalBoard.ServiceInstance;
}
}
public void SetStatus(OamLocalBoardState state)
{
OamLocalBoard.SetStatus(state);
}
public void SetInitialState()
{
OamLocalBoard.SetInitialState();
}
}
}
<file_sep>/YZX.TIA/Proxies/FrameApplication/CommonProjectHandlingProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.FrameApplication.ProjectWizard;
namespace YZX.Tia.Proxies.FrameApplication
{
public class CommonProjectHandlingProxy
{
CommonProjectHandling CommonProjectHandling;
}
}
<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.MonitorLoop.cs
using System;
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IDlc GetMonitorLoop([NotNull] this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.Lang.Code.MonitorLoopFactory");
}
}
}
<file_sep>/YZX.TIA/Proxies/Hwcn/PersistentDataStorageServiceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.HwConfiguration.Application.UserInterface.Basics.Controller;
using Reflection;
namespace YZX.Tia.Proxies.Hwcn
{
public class PersistentDataStorageServiceProxy
{
internal PersistentDataStorageService PersistentDataStorageService;
internal PersistentDataStorageServiceProxy(PersistentDataStorageService dlc)
{
this.PersistentDataStorageService = dlc;
}
public OnlineDeviceServiceProxy OnlineDeviceService
{
get
{
var service = Reflector.GetInstanceFieldByName(PersistentDataStorageService,
"m_OnlineDeviceService", ReflectionWays.SystemReflection)
as OnlineDeviceService;
return new OnlineDeviceServiceProxy(service);
}
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/NavigationViewControlProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.UI.Controls;
using Siemens.Simatic.PlcLanguages.GraphEditor.Frame;
namespace YZX.Tia.Proxies.Graph
{
public class NavigationViewControlProxy
{
private NavigationViewControl navigationViewControl;
public NavigationViewControlProxy(UserControl navigationViewControl)
{
this.navigationViewControl = navigationViewControl as NavigationViewControl;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Extensions/FrameApplication/FrameApplicationExtensions.ProjectNavigator.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.Navigation.Project.Main;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Dlc;
namespace YZX.Tia.Extensions.FrameApplication
{
partial class FrameApplicationExtensions
{
public static RootObjectHostServiceProxy GetRootObjectHostService(this IWorkingContext workingContext)
{
RootObjectHostService dlc = workingContext.GetRequiredDlc<RootObjectHostService>("Siemens.Automation.FrameApplication.RootObjectHostService");
return new RootObjectHostServiceProxy(dlc);
}
public static ProjectNavigatorLoaderProxy GetProjectNavigatorLoader(this IWorkingContext workingContext)
{
ProjectNavigatorLoader dlc = workingContext.GetRequiredDlc<ProjectNavigatorLoader>("Siemens.Automation.FrameApplication.ProjectNavigatorLoader");
return new ProjectNavigatorLoaderProxy(dlc);
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.cs
using System;
using System.ComponentModel;
using System.Threading;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.Basics.Synchronizer;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.DomainServices;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Dlc
{
public static partial class IWorkingContextExtensions
{
public static ISynchronizeInvoke GetSynchronizeInvoke(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ISynchronizer>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer")
as ISynchronizeInvoke;
}
public static ISynchronizer GetSynchronizer(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ISynchronizer>("Siemens.Automation.Basics.Synchronizer.ThreadSynchronizer");
}
public static Thread GetMainThread(this IWorkingContext workingContext)
{
ISynchronizer syn = workingContext.GetSynchronizer();
return syn.MainThread;
}
public static IEnumerable<WorkingContext> GetTopWorkingContexts()
{
return Reflector.RunStaticMethodByName(typeof(WorkingContext),
"GetTopWorkingContexts",
ReflectionWays.SystemReflection) as IEnumerable<WorkingContext>;
}
public static IWorkingContext GetRootWorkingContext(this IWorkingContext currentContext)
{
for (IWorkingContext parentWorkingContext = currentContext.ParentWorkingContext; parentWorkingContext != null; parentWorkingContext = currentContext.ParentWorkingContext)
currentContext = parentWorkingContext;
return currentContext;
}
public static IWorkingContext GetCommonWorkingContext(
this IWorkingContext workingContext1,
IWorkingContext workingContext2)
{
return Reflector.RunStaticMethodByName(typeof(WorkingContext),
"GetCommonWorkingContext",
ReflectionWays.SystemReflection,
workingContext1,
workingContext2) as IWorkingContext;
}
public static ConnectionServiceProvider GetConnectionService(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.ConnectionService") as ConnectionServiceProvider;
}
public static IOnlineCommandInvoke GetOnlineCommandInvoke(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Automation.DomainServices.OnlineService.OnlineCommandInvoke") as IOnlineCommandInvoke;
}
public static IIconService GetIconService(this IWorkingContext workingContext)
{
return workingContext.GetService("Siemens.Automation.CommonServices.IconService") as IIconService;
}
}
}<file_sep>/YZX.TIA/Proxies/Graph/SequenceProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.GraphEditor.Model.GraphElements;
namespace YZX.Tia.Proxies.Graph
{
public class SequenceProxy
{
Sequence Sequence;
internal SequenceProxy(Sequence sequence)
{
Sequence = sequence;
}
public StepProxy GetFirstStep()
{
Step step = Sequence.GetFirstStep();
return new StepProxy(step);
}
public string GetTitle()
{
return Sequence.GetTitle();
}
public MultiLanguageString GetDefaultTitle()
{
return Sequence.GetDefaultTitle();
}
public List<LogicalElementProxy> GetAllContainedElements()
{
List<LogicalElement> list = Sequence.GetAllContainedElements();
List<LogicalElementProxy> proxies = new List<LogicalElementProxy>();
foreach(LogicalElement le in list)
{
LogicalElementProxy proxy = new LogicalElementProxy(le);
proxies.Add(proxy);
}
return proxies;
}
}
}
<file_sep>/YZX.TIA/Extensions/Oam/IOamLocalBoardExtensions.cs
using Microsoft.Scripting.Runtime;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Extensions
{
public static class IOamLocalBoardExtensions
{
public static bool IsOamLocalBoard([NotNull] this IOamLocalBoard board)
{
OamLocalBoard oamLocalBoard = board as OamLocalBoard;
return oamLocalBoard != null;
}
public static bool IsOamComBoard([NotNull] this IOamLocalBoard board)
{
OamComBoard oamComBoard = board as OamComBoard;
return oamComBoard != null;
}
public static bool IsOamCustomBoard([NotNull] this IOamLocalBoard board)
{
OamCustomBoard oamCustomBoard = board as OamCustomBoard;
return oamCustomBoard != null;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/HierarchyFrameMetaProxy.cs
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class HierarchyFrameMetaProxy:FrameBaseMetaProxy
{
HierarchyFrameMeta HierarchyFrameMeta;
internal static HierarchyFrameMetaProxy ToProxy(HierarchyFrameMeta meta)
{
return new HierarchyFrameMetaProxy(meta);
}
internal HierarchyFrameMetaProxy(HierarchyFrameMeta meta):base(meta)
{
HierarchyFrameMeta = meta;
}
public bool Singleton
{
get
{
return HierarchyFrameMeta.Singleton;
}
}
public LayoutBehavior Layout
{
get
{
return HierarchyFrameMeta.Layout;
}
}
public bool UserClose
{
get
{
return HierarchyFrameMeta.UserClose;
}
}
public bool ShowCaption
{
get
{
return HierarchyFrameMeta.ShowCaption;
}
}
}
}
<file_sep>/YZX.TIA/Proxies/XLSXImporterProxy.cs
using System.ComponentModel;
using System.Collections.Generic;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.TagTableViewer;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DataExchange.MassDataHandler;
using YZX.Tia.Extensions;
using Reflection;
namespace YZX.Tia.Proxies
{
public class XLSXImporterProxy
{
public ICoreObject CPU;
XLSXImporter XLSXImporter;
public ISynchronizeInvoke Synchronizer;
public XLSXImporterProxy(object importer)
{
XLSXImporter = importer as XLSXImporter;
}
public XLSXImporterProxy(
ICoreObject cpu,
ISynchronizeInvoke synchronizer = null)
{
if (synchronizer == null)
{
Synchronizer = cpu.GetSynchronizer();
}
else
{
Synchronizer = synchronizer;
}
TiaStarter.RunInSynchronizer(Synchronizer, () =>
{
XLSXImporter = new XLSXImporter(cpu.GetTagService(),
MassDataHandler.CreateWorkbook(null),
cpu.GetDefaultTagTable(Synchronizer),
XLSXImportExportOptions.IncludeTags | XLSXImportExportOptions.IncludeConstants,
cpu.GetFolderService(),
cpu.GetCommandProcessor(),
null,
null,
cpu.GetNameService(),
cpu.GetRangeCheck());
});
}
public ICoreObject ResolveTagTableFromProperties(IDictionary<string, string> properties)
{
return TiaStarter.RunInSynchronizer(Synchronizer,
(p_properties) =>
{
return Reflector.RunInstanceMethodByName(XLSXImporter,
"ResolveTagTableFromProperties",
ReflectionWays.SystemReflection,
p_properties) as ICoreObject;
}, properties) as ICoreObject;
}
public bool UpdateTag(IBLTag tag, Dictionary<string, string> properties, bool isConstant, int rowNumber)
{
return (bool)TiaStarter.RunInSynchronizer(Synchronizer,
(p_tag, p_properties, p_isConstant) =>
{
return Reflector.RunInstanceMethodByName(XLSXImporter,
"UpdateTag",
ReflectionWays.SystemReflection,
p_tag,
p_properties,
p_isConstant);
}, tag, properties, isConstant);
}
/// <summary>
/// 取得或创建变量表
/// </summary>
public ICoreObject GetOrCreateTagTable(string tagTablePath)
{
return TiaStarter.RunInSynchronizer(Synchronizer,
(p_tagTablePath) =>
{
ICoreObject tagTable = Reflector.RunInstanceMethodByName(XLSXImporter,
"GetOrCreateTagTable",
ReflectionWays.SystemReflection,
p_tagTablePath) as ICoreObject;
return tagTable;
}, tagTablePath) as ICoreObject;
}
public void AddUpdateTagOrConstant2TagTable(
string[] propertyValues,
string[] propertyNames,
int typeIndex,
bool isConstant
)
{
TiaStarter.RunInSynchronizer(Synchronizer,
() =>
{
Reflector.RunInstanceMethodByName(XLSXImporter,
"AddUpdateTagOrConstant2TagTable",
ReflectionWays.SystemReflection,
propertyValues, propertyNames, typeIndex, isConstant, 0);
});
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.ConnectionService.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Reflection;
using YZX.Tia.Extensions;
using YZX.Tia.Proxies;
namespace YZX.Tia
{
partial class TiaStarter
{
private ConnectionServiceProvider m_ConnectionService;
public ConnectionServiceProvider ConnectionService
{
get
{
if (this.m_ConnectionService == null)
{
IConnectionService ics = projectViewWorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.ConnectionService") as IConnectionService;
m_ConnectionService = ics.ToConnectionServiceProvider();
}
return this.m_ConnectionService;
}
}
public IAsyncResult BeginConnectToTarget(
ConnectionServiceProvider ssp,
ConnectionParamsProxy connectParameter,
AsyncCallback callback,
object state)
{
return Reflector.RunInstanceMethodByName(
ssp,
"BeginConnectToTarget",
ReflectionWays.SystemReflection,
connectParameter.CP,
callback,
state) as IAsyncResult;
}
internal ConnectorBase GetConnector(
ConnectionServiceProvider csp,
string connectionType)
{
return csp.GetConnector(connectionType);
}
public bool PrepareConnection(
ConnectionServiceProvider csp,
ICoreObject target,
string connectionType)
{
return csp.PrepareConnection(target, connectionType);
}
}
}
<file_sep>/YZX.TIA/Proxies/EthernetDiscoverNodeProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.OnlineAccess;
using Siemens.Automation.OnlineAccess.OnlineInterface;
namespace YZX.Tia.Proxies
{
public class EthernetDiscoverNodeProxy:OamNodeProxy
{
EthernetDiscoverNode EthernetDiscoverNode;
public EthernetDiscoverNodeProxy(INode node) : base(node)
{
EthernetDiscoverNode = node as EthernetDiscoverNode;
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Dlc.cs
using System.ComponentModel;
using Siemens.Automation.Basics;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.BusinessLogic;
using Siemens.Automation.CommonServices;
using Siemens.Automation.DomainServices.FolderService;
using Siemens.Automation.ObjectFrame.NameService;
using Siemens.Automation.DomainModel;
using Siemens.Simatic.SystemDiagnosis.Sdal.SdalPE;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common.Lifelist;
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.PLInterface.PLDebug;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.Utilities;
using Siemens.Simatic.PlcLanguages.TisPlusServer;
using Siemens.Simatic.HwConfiguration.Application;
using Siemens.Simatic.HwConfiguration.Diagnostic;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
using Siemens.Simatic.HwConfiguration.Diagnostic.Common;
using Siemens.Simatic.PLCMessaging;
using Siemens.Simatic.SystemDiagnosis.Comm.AlarmService;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus.Upload;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common.OnlineHostService;
using Siemens.Simatic.PlcLanguages.VatService.FolderSnapIn;
using Siemens.Automation.DomainServices.TagService;
#if TIA
using Siemens.Simatic.PlcLanguages.VatService.Businesslogic;
#endif
using Reflection;
namespace YZX.Tia.Extensions
{
public static partial class ICoreObjectExtensions
{
#if TIA
public static IVarTable ToIVarTable(this ICoreObject ico)
{
IBusinessLogicConnector iblc = ico as IBusinessLogicConnector;
IBusinessLogicObject iblo = iblc.GetBusinessLogic("PlcLanguages.VatService");
IVarTable ivt = iblo as IVarTable;
return ivt;
}
internal static VarTable ToVarTable(this IVarTable ivt)
{
return ivt as VarTable;
}
public static ISynchronizeInvoke GetSynchronizer(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.Basics.SynchronizerService);
}
public static IFolderService GetFolderService(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.DomainServices.FolderService);
}
public static ICommandProcessor GetCommandProcessor(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.CommonServices.CommandProcessor);
}
public static INameService GetNameService(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.ObjectFrame.NameService);
}
public static IRangeCheck GetRangeCheck(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Iecpl.BlockLogic.RangeCheck);
}
public static IBulkService GetBulkService(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.Basics.BulkService);
}
#endif
public static ConnectionServiceProvider GetConnectionServiceProvider(this ICoreObject coreObject)
{
ConnectionServiceProvider connectionService = null;
if (!coreObject.IsDeleted || !coreObject.IsDeleting)
{
IConnectionService ics = ((IDlc)coreObject.Context).WorkingContext.DlcManager.Load("Siemens.Automation.DomainServices.ConnectionService")
as IConnectionService;
ConnectionServiceProxy csp = ics as ConnectionServiceProxy;
connectionService = Reflector.GetInstancePropertyByName(csp, "RealConnectionService", ReflectionWays.SystemReflection) as ConnectionServiceProvider;
}
return connectionService;
}
public static IElementaryDataTypeService GetDataTypeService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
IElementaryDataTypeService datatype = idlcManager.Load("Siemens.Automation.DomainServices.ElementaryDataTypeService")
as IElementaryDataTypeService;
return datatype;
}
public static AccessManagerPE GetAccessManagerPE(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
AccessManagerPE datatype = idlcManager.Load("Siemens.Simatic.SystemDiagnosis.Sdal.SdalPE.AccessManagerPE")
as AccessManagerPE;
return datatype;
}
public static OmsLifelistExtension GetOmsLifelistExtension(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
OmsLifelistExtension datatype = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OmsLifelistExtension")
as OmsLifelistExtension;
return datatype;
}
public static SdalFacade GetSdalFacade(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
SdalFacade SdalFacade = idlcManager.Load("Siemens.Simatic.SystemDiagnosis.Sdal.SdalPE.SdalFacade")
as SdalFacade;
return SdalFacade;
}
public static string GetBoardConfigurationName(this ICoreObject boardConfiguration)
{
IOamIdentification attributes = CoreObjectExtension.GetAttributes<IOamIdentification>(boardConfiguration);
if(attributes != null)
{
return attributes.OamName;
}
else
{
return null;
}
}
public static IWorkingContext GetWorkingContext(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
return idlc.WorkingContext;
}
public static IDebugService GetDebugService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
IDebugService IDebugService = idlcManager.Load("PlcLanguages.BlockLogic.DebugService")
as IDebugService;
return IDebugService;
}
public static IBlockService GetBlockService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
IBlockService IBlockService = idlcManager.Load("PlcLanguages.BlockLogic.BlockService")
as IBlockService;
return IBlockService;
}
public static IOnlineService GetOnlineService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
IOnlineService IOnlineService = idlcManager.Load("Siemens.Automation.DomainServices.OnlineService")
as IOnlineService;
return IOnlineService;
}
public static IOnlineBlockService GetOnlineBlockService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
IOnlineBlockService IOnlineBlockService = idlcManager.Load("PlcLanguages.BlockLogic.OnlineBlockService")
as IOnlineBlockService;
return IOnlineBlockService;
}
public static ITagService GetTagService(this ICoreObject coreObject)
{
return DlcIdExtensions.LoadByDlcId(((IDlc)coreObject.Context).WorkingContext.DlcManager,
DlcIds.Platform.DomainServices.TagService);
}
public static Server GetTisPlusServer(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
Server server = idlcManager.Load("Siemens.Simatic.PlcLanguages.TisPlusServer") as Server;
return server;
}
public static TopologyDetection GetTopologyDetection(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
TopologyDetection TopologyDetection = idlcManager.Load("Siemens.Simatic.HwConfiguration.Application.TopologyDetection")
as TopologyDetection;
return TopologyDetection;
}
public static OnlineObjectService GetOnlineObjectService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
OnlineObjectService OnlineObjectService = idlcManager.Load(DiagDlcIds.OnlineObjectService)
as OnlineObjectService;
return OnlineObjectService;
}
public static OperatingModeObserverService GetOperatingModeObserverService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
OperatingModeObserverService OperatingModeObserverService = idlcManager.Load(DiagDlcIds.OperatingModeObserverService)
as OperatingModeObserverService;
return OperatingModeObserverService;
}
public static PLCMsgConnector GetPLCMsgConnector(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
PLCMsgConnector PLCMsgConnector = idlcManager.Load("Siemens.Simatic.PLCMessaging.PLCMsgConnector")
as PLCMsgConnector;
return PLCMsgConnector;
}
public static InnovationAlarmService GetInnovationAlarmService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
InnovationAlarmService InnovationAlarmService = idlcManager.Load("Siemens.Simatic.SystemDiagnosis.Comm.AlarmService.InnovationAlarmService")
as InnovationAlarmService;
return InnovationAlarmService;
}
public static IUpload GetPlusBlockConsistencyService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
PlusBlockConsistencyService PlusBlockConsistencyService = idlcManager.Load("BlockLogic.PlusBlockConsistencyService")
as PlusBlockConsistencyService;
return PlusBlockConsistencyService;
}
public static LifelistProxyFactory GetLifelistProxyFactory(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
LifelistProxyFactory LifelistProxyFactory = idlcManager.Load("Siemens.Automation.DomainServices.LifelistProxyFactory")
as LifelistProxyFactory;
return LifelistProxyFactory;
}
public static OnlineHostService GetOnlineHostService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
OnlineHostService OnlineHostService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.OnlineHostService")
as OnlineHostService;
return OnlineHostService;
}
public static NavigationService GetNavigationService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
NavigationService NavigationService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.NavigationService")
as NavigationService;
return NavigationService;
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/FrameGroupBaseProxy.cs
using System.Collections.Generic;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.FrameApplication
{
public class FrameGroupBaseProxy
{
FrameGroupBase FrameGroupBase;
public FrameGroupBaseProxy(IFrameGroup group)
{
FrameGroupBase = group as FrameGroupBase;
}
public List<IViewFrame> ViewFrameList
{
get
{
return Reflector.GetInstanceFieldByName(FrameGroupBase,
"m_ViewFrameList",
ReflectionWays.SystemReflection) as List<IViewFrame>;
}
}
public List<IFrame> NonViewFrameList
{
get
{
return Reflector.GetInstanceFieldByName(FrameGroupBase,
"m_NonViewFrameList",
ReflectionWays.SystemReflection) as List<IFrame>;
}
}
public IFrame ActiveFrame
{
get
{
return Reflector.GetInstancePropertyByName(FrameGroupBase,
"ActiveFrame",
ReflectionWays.SystemReflection) as IFrame;
}
}
public bool IsClosing
{
get
{
return FrameGroupBase.IsClosing;
}
}
public bool IsClosed
{
get
{
return FrameGroupBase.IsClosed;
}
}
public bool PendingRestoreActivate
{
get
{
return FrameGroupBase.PendingRestoreActivate;
}
}
}
}
<file_sep>/YZX.TIA/Extensions/Hwcn/FrameGroupManagerExtensions.cs
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reflection;
namespace YZX.Tia.Extensions.Hwcn
{
public static class FrameGroupManagerExtensions
{
public static List<IDoeInstanceAccess> GetDoeInstances(this FrameGroupManager manager)
{
return Reflector.GetInstanceFieldByName(manager, "m_DoeInstances", ReflectionWays.SystemReflection)
as List<IDoeInstanceAccess>;
}
public static string GetViewId(this FrameGroupManager manager)
{
return Reflector.GetInstanceFieldByName(manager, "m_ViewId", ReflectionWays.SystemReflection)
as string;
}
}
}
<file_sep>/GraphViewer/README.md
Open Graph Editor
打开顺序流程图编辑器
<file_sep>/YZX.TIA/Proxies/GraphBlockLogic/GraphBranchProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
namespace YZX.Tia.Proxies.GraphBlockLogic
{
public class GraphBranchProxy
{
GraphBranch GraphBranch;
internal GraphBranchProxy(GraphBranch branch)
{
GraphBranch = branch;
}
}
}
<file_sep>/MpkExtractor/README.md
MpkExtractor
解包TIA专用配置文件MPK

<file_sep>/YZX.TIA/Converter/GraphBlockLogicConverters.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphBlockLogic;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.GraphBlockLogic;
namespace YZX.Tia.Converter
{
public static class GraphBlockLogicConverters
{
internal static GraphActionProxy GraphActionProxy(GraphAction action)
{
return new GraphActionProxy(action);
}
internal static GraphActionsProxy GraphActionsProxy(GraphActions actions)
{
return new GraphActionsProxy(actions);
}
internal static GraphSequenceProxy GraphSequenceProxy(GraphSequence sequence)
{
return new GraphSequenceProxy(sequence);
}
internal static GraphStepProxy GraphStepProxy(GraphStep step)
{
return new GraphStepProxy(step);
}
internal static GraphJumpProxy GraphJumpProxy(GraphJump jump)
{
return new GraphJumpProxy(jump);
}
internal static GraphTransitionProxy GraphTransitionProxy(GraphTransition transition)
{
return new GraphTransitionProxy(transition);
}
internal static GraphBranchProxy GraphBranchProxy(GraphBranch branch)
{
return new GraphBranchProxy(branch);
}
internal static GraphSequencePartProxy GraphSequencePartProxy(GraphSequencePart part)
{
return new GraphSequencePartProxy(part);
}
internal static GraphConnectionProxy GraphConnectionProxy(GraphConnection connection)
{
return new GraphConnectionProxy(connection);
}
}
}
<file_sep>/YZX.TIA/Proxies/ProjectManager/TiaProjectProxy.cs
using System;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ProjectManager;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ProjectManager.Impl.Tia;
#if Tia
using Siemens.Simatic.PlcLanguages.BlockLogic;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.BlockLogic.PLDebug;
#endif
using Reflection;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
public partial class TiaProjectProxy
{
TiaProject tp;
ITiaProject TiaProject
{
get
{
return tp as ITiaProject;
}
}
ITiaProjectInternal TiaProjectInternal
{
get
{
return tp as ITiaProjectInternal;
}
}
public TiaProjectProxy(object o)
{
tp = o as TiaProject;
}
public IWorkingContext WorkingContext
{
get
{
return TiaProject.WorkingContext;
}
}
public IWorkingContext ProjectWorkingContext
{
get
{
ICoreContext projectContext = WorkingContext.GetCoreContext();
return ((IDlc)projectContext).WorkingContext;
}
}
private IWorkingContext projectViewWorkingContext;
public IWorkingContext ProjectViewWorkingContext
{
get
{
if (projectViewWorkingContext == null)
{
//projectViewWorkingContext = new WorkingContext(true,
// WorkingContextEnvironment.Project,
// "YZX"
// );
projectViewWorkingContext = new WorkingContext(TiaStarter.m_ViewApplicationContext,
WorkingContextEnvironment.Project);
//projectViewWorkingContext = TiaStarter.UIContextHolder.ProjectUIContext;
projectViewWorkingContext.SiblingInBusinessLogicContext = ProjectWorkingContext;
}
return projectViewWorkingContext;
}
}
public void UnlockStarterFile()
{
TiaProjectInternal.UnlockStarterFile();
}
public string DirectoryPath
{
get
{
return (string)Reflector.GetInstancePropertyByName(tp,
"DirectoryPath",
ReflectionWays.SystemReflection);
}
}
public string StarterFilePath
{
get
{
return (string)Reflector.GetInstancePropertyByName(tp,
"StarterFilePath",
ReflectionWays.SystemReflection);
}
}
public TiaProjectState TiaProjectState
{
get
{
return (TiaProjectState)Reflector.GetInstancePropertyByName(tp,
"TiaProjectState",
ReflectionWays.SystemReflection);
}
}
public event EventHandler MainWorkingContextIsClosing
{
add
{
tp.MainWorkingContextIsClosing += value;
}
remove
{
tp.MainWorkingContextIsClosing -= value;
}
}
public event EventHandler IsModifiedChanged
{
add
{
tp.IsModifiedChanged += value;
}
remove
{
tp.IsModifiedChanged -= value;
}
}
#if Tia
public QueryBasedControllerTargetLookupProxy QueryBasedControllerTargetLookup
{
get
{
ICoreContext coreContext = WorkingContext.GetCoreContext();
QueryBasedControllerTargetLookupProxy QueryBasedControllerTargetLookupProxy =
new QueryBasedControllerTargetLookupProxy(coreContext);
return QueryBasedControllerTargetLookupProxy;
}
}
public ICoreObject FindCPU(string name)
{
return QueryBasedControllerTargetLookup.FindControllerTargetByName(name);
}
public ILibraryVersionService LibraryVersionService
{
get
{
return ProjectWorkingContext.DlcManager.Load("Siemens.Simatic.PlcLanguages.BlockLogic.LibraryVersionService") as ILibraryVersionService;
}
}
#endif
}
}
<file_sep>/YZX.TIA/Extensions/CoreObjectExtension.cs
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.ObjectFrame.BusinessLogic;
namespace YZX.Tia.Extensions
{
public static class CoreObjectExtension
{
public static T GetAttributes<T>(this ICoreObject o) where T : class
{
return (o != null ? o.GetAttributeSet(typeof (T)) : null) as T;
}
public static T GetBl<T>(this ICoreObject coreObject, string serviceId)
{
return (T) ((IBusinessLogicConnector) coreObject).GetBusinessLogic(serviceId);
}
public static IBusinessLogicObject Connect(this ICoreObject coreObject, int cookie, IBusinessLogicObject bl)
{
((IBusinessLogicConnector) coreObject).SetBusinessLogic(cookie, bl);
return bl;
}
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.CoreContext.cs
using Siemens.Automation.Basics;
using Siemens.Automation.CommonServices;
using Siemens.Automation.ObjectFrame;
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static ICoreContextHandler GetCoreContextHandler(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ICoreContextHandler>("Siemens.Automation.CommonServices.CoreContextHandler");
}
public static ICoreContext GetCoreContext(this IWorkingContext workingContext)
{
return workingContext.GetCoreContextHandler().CoreContext;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.TisClassicServer.cs
using System.Collections;
using System.Collections.Generic;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.PlcLanguages.TisServer;
using Siemens.Simatic.Lang.Model.Idents;
namespace YZX.Tia
{
partial class TiaStarter
{
private Server m_TisServer;
public Server TisServer
{
get
{
if (this.m_TisServer == null)
this.m_TisServer = m_BusinessLogicApplicationContext.DlcManager.Load("Siemens.Simatic.PlcLanguages.TisServer") as Server;
return this.m_TisServer;
}
}
public Device CreateTisDevice(IConnection pConnection)
{
ITisDevice itd = TisServer.CreateDevice(pConnection);
Device d = itd as Device;
return d;
}
public DataAddress CreateTisDataAddress()
{
ITisDataAddress itda = TisServer.CreateDataAddress();
DataAddress da = itda as DataAddress;
return da;
}
public TisValue CreateTisValue()
{
ITisValue itv = TisServer.CreateTisValue();
TisValue tv = itv as TisValue;
return tv;
}
public static readonly OperandRange[] TisRangeToOperandRange = new OperandRange[15]
{
OperandRange.None,
OperandRange.Memory,
OperandRange.Input,
OperandRange.Output,
OperandRange.PInput,
OperandRange.POutput,
OperandRange.Timer,
OperandRange.Counter,
OperandRange.Data,
OperandRange.FC,
OperandRange.None,
OperandRange.None,
OperandRange.None,
OperandRange.Local,
OperandRange.None
};
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.PLCMessaging.cs
using Siemens.Automation.Basics;
using Siemens.Simatic.PLCMessaging.GUI;
#if TIAV13
#else
using Siemens.Simatic.PLCMessaging.UI;
#endif
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static PLCMessagingWindow GetPLCMessagingWindow(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<PLCMessagingWindow>("Siemens.Simatic.PLCMessaging.GUI.PLCMessagingWindow");
}
public static ArchiveGridService GetArchiveGridService(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<ArchiveGridService>("Siemens.Simatic.PLCMessaging.GUI.ArchiveGridService");
}
public static AlarmGridService GetAlarmGridService(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<AlarmGridService>("Siemens.Simatic.PLCMessaging.GUI.AlarmGridService");
}
#if TIAV13
#else
public static PlcMessagingView GetPlcMessagingView(this IWorkingContext workingContext)
{
return workingContext.GetRequiredDlc<PlcMessagingView>("Siemens.Simatic.PLCMessaging.GUI.PlcMessagingView");
}
#endif
}
}
<file_sep>/Siemens.Automation.DomainServices.Online.Test/Proxies/ConnectionServiceClassFactoryProxy.cs
using Siemens.Automation.DomainServices.ConnectionService;
namespace YZX.Tia.Proxies
{
public class ConnectionServiceClassFactoryProxy
{
ConnectionServiceClassFactory ConnectionServiceClassFactory;
internal ConnectionServiceClassFactoryProxy(IConnectionServiceClassFactory factory)
{
ConnectionServiceClassFactory = factory as ConnectionServiceClassFactory;
}
}
}
<file_sep>/YZX.TIA/Proxies/Vat/VatServiceProxy.cs
using Siemens.Simatic.PlcLanguages.VatService;
namespace YZX.Tia.Proxies
{
public class VatServiceProxy
{
private VatService m_VatService = null;
public VatServiceProxy(VatService vs)
{
m_VatService = vs;
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Proxies/Diagnostic/IconServerProxy.cs
using System.Collections.Generic;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
namespace YZX.Tia.Proxies.Diagnostic
{
public class IconServerProxy
{
IconServer IconServer;
public IconServerProxy(IIconServer server)
{
IconServer = server as IconServer;
}
public IDictionary<string, object> GetIcons()
{
return IconServer.GetIcons();
}
public IDictionary<string, object> GetSmallIcons()
{
return IconServer.GetSmallIcons();
}
}
}
<file_sep>/YZX.TIA/Extensions/ICoreObject/ICoreObjectExtensions.Lifelist.cs
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.DomainServices.OnlineService;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.HwConfiguration.Basics.Basics;
using Siemens.Simatic.HwConfiguration.Diagnostic.Services.Common;
using YZX.Tia.Proxies.OnlineService;
namespace YZX.Tia.Extensions
{
partial class ICoreObjectExtensions
{
public static object GetNodeDetails(this ICoreObject node)
{
return LifelistNodeDetailsFactory.GetNodeDetails(node);
}
public static ICoreObject GetOnlineDeviceNode(this ICoreObject lifelistNode)
{
var detail = lifelistNode.GetNodeDetails();
LifelistNodeDetailsProxy detailsProxy = new LifelistNodeDetailsProxy(detail);
var onlineDevice = detailsProxy.OnlineDeviceNode;
return onlineDevice;
}
public static IWorkingContext GetUIWorkingContext(this ICoreObject lifelistNode)
{
OnlineObjectService OnlineObjectService = lifelistNode.GetOnlineObjectService();
IConfigBase onlineProject = OnlineObjectService.CreateOnlineProject();
var PersistenceWorkingContext = onlineProject.CoreObject.GetWorkingContext();
var applicationWorkingContext = TiaStarter.m_ViewApplicationContext;
UIContextCreator creator = new UIContextCreator(PersistenceWorkingContext, applicationWorkingContext);
IWorkingContext context = creator.PersistenceUIContext;
return context;
}
}
}
<file_sep>/YZX.TIA/Extensions/BlockEditor/BlockEditorControlBaseExtensions.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Controls.TagComments;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor.View;
using YZX.Tia.Extensions;
using YZX.Tia.Proxies.Ladder;
using YZX.Tia.Proxies.Graph;
namespace YZX.Tia.Extensions.Ladder
{
public static class BlockEditorControlBaseExtensions
{
public static void DisablePLBlockInput(this BlockEditorControlBase ladder)
{
PLBlockEditorControlElementProxy pLBlockEditorControlElementProxy =
new PLBlockEditorControlElementProxy(ladder);
List<NetworkElementProxy> networks = pLBlockEditorControlElementProxy.GetNetworks();
foreach (NetworkElementProxy network in networks)
{
List<IUIControl> networkChildren = network.LanguagePaletteBaseElement.GetChildUIControls();
CommandTextBoxElement Title = network.CommandTextBoxElement;
Title.BackColor = Color.Red;
CollapsableTextBoxElement CommentElement = network.CommentElement;
CommentElement.BackColor = Color.Yellow;
TagCommentElement NetworkTagCommentElement = network.NetworkTagCommentElement;
NetworkTagCommentElement.BackColor = Color.Blue;
SimaticFLGraphicEditor SimaticFLGraphicEditor = network.SimaticFLGraphicEditor;
SimaticFLGraphicEditor.BackColor = Color.Gold;
SimaticFLGraphicEditor.Enabled = false;
FLGViewAccessibleObjectProxy FLGViewAccessibleObjectProxy = FLGViewExtensions.GetCorrectAccessibilityObject(SimaticFLGraphicEditor);
GraphicManager manager = SimaticFLGraphicEditor.GetGraphicManager();
List<GraphicObjectProxy> list = manager.ToGraphicObjectProxyList();
foreach (GraphicObjectProxy proxy in list)
{
if (proxy.SupportEdit)
{
IFLGEditBoxHandler handler = proxy.EditBoxHandler;
AccessibleObject AccessibleObject = FLGViewAccessibleObjectProxy.GetAccessibleChildObject(proxy);
}
}
}
pLBlockEditorControlElementProxy.FavouritsToolBar.Visible = false;
pLBlockEditorControlElementProxy.BlockHeaderPalette.Visible = false;
}
public static void DisableGraphBlockInput(this BlockEditorControlBase graph)
{
GraphBlockEditorControlProxy proxy = new GraphBlockEditorControlProxy(graph);
MainControlContainerProxy mainControlContainerProxy = proxy.MainControlContainer;
GraphBlockEditorControlProxy GraphBlockEditorControlProxy = mainControlContainerProxy.GraphBlockEditorControl;
List<DetailedSequenceViewProxy> seqList = mainControlContainerProxy.GetDetailedSequenceView();
foreach (var seqProxy in seqList)
{
seqProxy.DisableGraphBlockInput();
}
}
}
}<file_sep>/YZX.TIA/Proxies/Graph/OverlayBaseProxy.cs
using System.Collections.Generic;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.Overlays;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class OverlayBaseProxy
{
internal OverlayBase overlay;
internal OverlayBaseProxy(OverlayBase overlay)
{
this.overlay = overlay;
}
public List<DrawableTransitionProxy> GetTransitions()
{
List<DrawableTransitionProxy> list = new List<DrawableTransitionProxy>();
foreach (var element in overlay.ElementList)
{
if (element is DrawableTransition)
{
DrawableTransition step = element as DrawableTransition;
DrawableTransitionProxy proxy = new DrawableTransitionProxy(step);
list.Add(proxy);
}
}
return list;
}
public List<DrawableStepProxy> GetSteps()
{
List<DrawableStepProxy> list = new List<DrawableStepProxy>();
foreach(var element in overlay.ElementList)
{
if(element is DrawableStep)
{
DrawableStep step = element as DrawableStep;
DrawableStepProxy proxy = new DrawableStepProxy(step);
list.Add(proxy);
}
}
return list;
}
}
}<file_sep>/YZX.TIA/Proxies/Graph/UIElementWrapperProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class UIElementWrapperProxy : DrawableBoxElementProxy
{
internal UIElementWrapper UIElementWrapper;
internal UIElementWrapperProxy(UIElementWrapper wrapper)
: base(wrapper)
{
UIElementWrapper = wrapper as UIElementWrapper;
}
}
}
<file_sep>/YZX.TIA/TiaStarter/TiaStarter.OMS.cs
using System;
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.ConnectionService.Private;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.OnlineAccess.OnlineInterface;
using Siemens.Simatic.SystemDiagnosis.Comm.OMSPlusService;
using Siemens.Automation.Basics;
using Siemens.Simatic.SystemDiagnosis.Sdal.SdalPE;
using YZX.Tia.Proxies;
using YZX.Tia.Proxies.OnlineService;
using YZX.Tia.Extensions;
namespace YZX.Tia
{
partial class TiaStarter
{
public int GetClientSession(
string address,
string configName,
string accessibleName,
out ICoreObject AccessibleNode,
ConnectionOpenedEventHandler connectionOpenedEventHandler = null
){
ICoreObjectCollection boardConfigurations = ((IOnlineConfiguration)LifelistService.GetIConnectionService()).GetUsableConfigurations("OMS");
ICoreObject boardConfiguration = LifelistService.GetBoardConfigurationByName(configName);
ICoreObjectCollection accessibleNodes = LifelistService.GetAccessibleNodes(boardConfiguration, true);
var names = accessibleNodes.GetNames();
if (names.Contains(accessibleName))
{
AccessibleNode = accessibleNodes.GetCoreObjectByName(accessibleName);
Type t = AccessibleNode.GetType();
var onlineObject = LifelistService.GetOnlineNode(AccessibleNode);
var connection = onlineObject.GetConnectionServiceProvider();
ConnectionServiceProviderProxy ConnectionServiceProviderProxy = connection.ToProxy();
ConnectionServiceProviderProxy.ConnectionOpened += connectionOpenedEventHandler;
IOamAddress oamAddress;
int createResult = OamObjectCreatorProxy.CreateAddress(address, out oamAddress);
TargetConnectionInfo TargetConnectionInfo =
new TargetConnectionInfo(boardConfiguration, null, null, oamAddress);
connection.SetTargetConnectionPath(onlineObject, TargetConnectionInfo);
IConnection omsc = connection.ConnectToOnline(onlineObject, "OMS",
OnlineConnectionModes.UseTargetConnectionInfo,
TargetConnectionInfo);
return 0;
}
AccessibleNode = null;
return -1;
}
public OMSPlusConnectionService GetOMSPlusConnectionService(ICoreObject AccessibleNode,
CheckConnectionDelegate connectionReady,
string identifier)
{
return new OMSPlusConnectionService(AccessibleNode,
((IDlc)AccessibleNode.Context).WorkingContext,
connectionReady,
identifier);
}
}
}<file_sep>/YZX.TIA/Extensions/IWorkingContext/IWorkingContextExtensions.ViewLoader.cs
using Microsoft.Scripting.Runtime;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication;
using Siemens.Automation.FrameApplication.ViewManager;
namespace YZX.Tia.Extensions
{
partial class IWorkingContextExtensions
{
public static IView LoadViewFromDLCManager([NotNull] this IWorkingContext workingContext,string viewID)
{
return ViewLoader.LoadViewFromDLCManager(viewID, workingContext);
}
public static IViewDomainLogic LoadViewDomainLogicFromDLCManager([NotNull] this IWorkingContext workingContext, string domainLogicID)
{
return ViewLoader.LoadViewDomainLogicFromDLCManager(domainLogicID, workingContext);
}
}
}
<file_sep>/YZX.TIA/Proxies/PrimaryProjectManagerProxy.cs
using System;
using Siemens.Automation.ProjectManager;
using Siemens.Automation.UserProjectManagement.BL.PrimaryProject;
namespace YZX.Tia.Proxies
{
public class PrimaryProjectManagerProxy
{
internal IPrimaryProjectManager m_PrimaryProjectManager;
internal PrimaryProjectManagerProxy(IPrimaryProjectManager m_PrimaryProjectManager)
{
this.m_PrimaryProjectManager = m_PrimaryProjectManager;
m_PrimaryProjectManager.ProjectOpened += M_PrimaryProjectManager_ProjectOpened;
}
private void M_PrimaryProjectManager_ProjectOpened(object sender, TiaPrimaryProjectOpenedEventArgs e)
{
this.ProjectOpened?.Invoke(sender,e);
}
public TiaProjectProxy PrimaryProject
{
get
{
return new TiaProjectProxy(m_PrimaryProjectManager.PrimaryProject);
}
}
public event EventHandler<EventArgs> ProjectOpened;
public bool OpenProjectReadOnly(string path, out object projectO, bool silent = false)
{
OpenProjectParams parameters = new OpenProjectParams(path);
parameters.Access = TiaProjectAccess.ReadOnly;
parameters.Silent = silent;
ITiaProject project;
bool returnB = m_PrimaryProjectManager.OpenProject(parameters, out project);
if (project != null)
{
projectO = new TiaProjectProxy(project);
}
else
{
projectO = null;
}
return returnB;
}
public bool OpenProjectReadWrite(string path, out object projectO,bool silent = false)
{
OpenProjectParams parameters = new OpenProjectParams(path);
parameters.Access = TiaProjectAccess.ReadWrite;
parameters.Silent = silent;
ITiaProject project;
bool returnB = m_PrimaryProjectManager.OpenProject(parameters, out project);
if (project != null)
{
projectO = new TiaProjectProxy(project);
}
else
{
projectO = null;
}
return returnB;
}
}
}
<file_sep>/YZX.TIA/Extensions/BlockEditorControlBaseExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.NetworkEditorFrame.Editor.Logic;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Taskcards.Instruction;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class BlockEditorControlBaseExtensions
{
public static void SetFavouritesManager(this BlockEditorControlBase becb,
FavouritesManager favouritesManager)
{
Reflector.SetInstanceFieldByName(becb,
"m_FavouritesManager",
favouritesManager,
ReflectionWays.SystemReflection); ;
}
}
}
<file_sep>/LadderViewer/README.md
Open Ladder Editor
打开梯型图编辑器
<file_sep>/YZX.TIA/Proxies/OMS/OMSpFactoryProxy.cs
using System;
using System.Collections;
using Siemens.Simatic.PlcLanguages.BlockLogic.Online.Plus;
using Siemens.Automation.OMSPlus.Managed;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies
{
public class OMSpFactoryProxy
{
OMSpFactory OMSpFactory;
public OMSpFactoryProxy(ClientSession clientSession,
IWorkingContext workingContext,
ICoreObject controllerTarget)
{
OMSpFactory = new OMSpFactory(clientSession, workingContext, controllerTarget);
}
public ICollection GetTrimmerOnlineBlocks()
{
return OMSpFactory.GetTrimmerOnlineBlocks();
}
public ICollection GetTrimmerOnlineDBs()
{
return OMSpFactory.GetTrimmerOnlineDBs();
}
}
}
<file_sep>/YZX.TIA/Extensions/ITagServiceExtensions.cs
using Siemens.Automation.DomainServices;
using Siemens.Automation.DomainServices.TagService;
using Reflection;
namespace YZX.Tia.Extensions
{
public static class ITagServiceExtensions
{
internal static TagServiceCore GetTagServiceCore(this ITagService its)
{
object o = Reflector.GetInstanceFieldByName(its, "m_ServiceCore", ReflectionWays.SystemReflection);
TagServiceCore tsc = o as TagServiceCore;
return tsc;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/UIElementWrapperForUIContainerProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class UIElementWrapperForUIContainerProxy:SelectableUIElementWrapperProxy
{
internal UIElementWrapperForUIContainer UIElementWrapperForUIContainer;
internal UIElementWrapperForUIContainerProxy(UIElementWrapperForUIContainer container)
:base(container)
{
UIElementWrapperForUIContainer = container as UIElementWrapperForUIContainer;
}
}
}
<file_sep>/YZX.TIA/Proxies/Graph/DrawableTransitionProxy.cs
using Siemens.Simatic.PlcLanguages.BlockEditorFrame;
using Siemens.Simatic.PlcLanguages.BlockEditorFrame.Editor.View;
using Siemens.Simatic.PlcLanguages.FLGraphicEditor;
using Siemens.Simatic.PlcLanguages.GraphEditor.ActionList.View;
using Siemens.Simatic.PlcLanguages.GraphEditor.View.DrawableElements;
namespace YZX.Tia.Proxies.Graph
{
public class DrawableTransitionProxy:DrawableBoxElementProxy
{
internal DrawableTransition Transition;
internal DrawableTransitionProxy(DrawableTransition transition):
base(transition)
{
this.Transition = transition;
}
public GraphFLGraphicEditor GetGraphFLGraphicEditor()
{
if (Transition.ElementList.Count > 0)
{
DrawableLangModTogglerDSV dsv = Transition.ElementList[2] as DrawableLangModTogglerDSV;
if (dsv.ElementList.Count > 0)
{
UIElementWrapperForUIContainer container = dsv.ElementList[0] as UIElementWrapperForUIContainer;
UIElementWrapperForPalettes palettes = container.ElementList[0] as UIElementWrapperForPalettes;
UIElementWrapperForPalettesProxy palettesProxy = new UIElementWrapperForPalettesProxy(palettes);
LanguagePaletteBaseElement palette = palettesProxy.Palette;
UIControlWindowlessWrapper wrapper = palette.ChildControls[1] as UIControlWindowlessWrapper;
GraphFLGraphicEditor editor = wrapper.ChildControls[0] as GraphFLGraphicEditor;
return editor;
}
}
return null;
}
}
}<file_sep>/Siemens.Automation.Basics.Test/Extensions/ObjectFrame/ICoreObjectExtensions.Sync.cs
using System.ComponentModel;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
using Siemens.Simatic.PlcLanguages.Utilities;
namespace YZX.Tia.Extensions.ObjectFrame
{
public static partial class ICoreObjectExtensions
{
public static string GetObjectName(this ICoreObject element)
{
ICoreAttributes coreAttributes = element.GetAttributeSet(typeof(ICoreAttributes)) as ICoreAttributes;
if (coreAttributes == null)
return "";
return coreAttributes.Name;
}
public static ISynchronizeInvoke GetSynchronizer(this ICoreObject coreObject)
{
return ((IDlc)coreObject.Context).WorkingContext.DlcManager.LoadByDlcId(DlcIds.Platform.Basics.SynchronizerService);
}
}
}
<file_sep>/Siemens.Simatic.Hwcn.Diagnostic.UI.Test/Extensions/Diagnostic/ICoreObjectExtensions.Diag.cs
using System.Windows.Forms;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.CommonServices;
using Siemens.Automation.FrameApplication;
using Siemens.Simatic.HwConfiguration.Diagnostic.Editor.Basics;
using Siemens.Simatic.HwConfiguration.Diagnostic.Common;
using Siemens.Simatic.HwConfiguration.Diagnostic.ToolWindows.DeviceInfoTable.Service;
using Siemens.Simatic.HwConfiguration.Diagnostic.ToolWindows.DeviceInfoTable.Controller;
using YZX.Tia.Dlc;
using YZX.Tia.Extensions.Diagnostic;
using YZX.Tia.Proxies.FrameApplication;
using YZX.Tia.Extensions.ObjectFrame;
namespace YZX.Tia.Extensions.Diagnostic
{
public static partial class ICoreObjectExtensions
{
public static IDiagServiceProvider GetDiagServiceProvider(this ICoreObject coreObj)
{
return DiagServiceProviderAdminImpl.Instance.GetDiagServiceProviderFromCoreObject(coreObj);
}
public static DeviceInfoTableService GetDeviceInfoTableService(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
DeviceInfoTableService DeviceInfoTableService = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.DeviceInfoTableService")
as DeviceInfoTableService;
return DeviceInfoTableService;
}
public static DeviceInfoTableController GetDeviceInfoTableController(this ICoreObject coreObject)
{
IDlc idlc = (IDlc)coreObject.Context;
IDlcManager idlcManager = idlc.WorkingContext.DlcManager;
DeviceInfoTableController DeviceInfoTableController = idlcManager.Load("Siemens.Simatic.HwConfiguration.Diagnostic.DeviceInfoTableController")
as DeviceInfoTableController;
return DeviceInfoTableController;
}
public static Control ShowModuleState(this ICoreObject cpu)
{
var UIContextHolder = PrimaryProjectUiWorkingContextManagerProxy.Instance.IUIContextHolder;
var ProjectUIContext = UIContextHolder.ProjectUIContext;
IWorkingContext workingContext = cpu.FindWorkingContext();
FrameGroupManager manager = ProjectUIContext.GetHwcnFrameGroupManager();
ICommandProcessor processor = workingContext.GetCommandProcessor();
ICommand command = processor.CreateCommand("Hwcn.Diagnostic.ShowModuleState", new object[1]
{
cpu
}, new NameObjectCollection());
command.Arguments.Add("DoeStartCategory", "DiagCategoryEventLog");
CommandResult result = manager.Execute(command);
if (result.ReturnCode == CommandReturnCodes.Handled)
{
object resultObject = result.ReturnValue;
List<IDoeInstanceAccess> does = manager.GetDoeInstances();
foreach (IDoeInstanceAccess doe in does)
{
var DoeInstanceAccess = doe as DoeInstanceAccess;
var viewAccess = DoeInstanceAccess.GetDoeViewAccess() as DoeViewAccess;
ICoreObject viewObject = doe.ViewObject;
IEditorFrame frame = doe.EditorFrame;
if (viewObject == cpu)
{
return frame.FrameControl;
}
}
}
return null;
}
public static Control ShowLifelistNodeModuleState(ICoreObject cpu)
{
var workingContext = cpu.FindWorkingContext();
var LifelistNodeUIContext = workingContext;//= cpu.GetUIWorkingContext();
FrameGroupManager manager = LifelistNodeUIContext.GetHwcnFrameGroupManager();
ICommandProcessor processor = workingContext.GetCommandProcessor();
ICommand command = processor.CreateCommand("Hwcn.Diagnostic.ShowModuleState", new object[1]
{
cpu
}, new NameObjectCollection());
command.Arguments.Add("DoeStartCategory", "DiagCategoryEventLog");
CommandResult result = manager.Execute(command);
if (result.ReturnCode == CommandReturnCodes.Handled)
{
object resultObject = result.ReturnValue;
List<IDoeInstanceAccess> does = manager.GetDoeInstances();
foreach (IDoeInstanceAccess doe in does)
{
DoeInstanceAccess DoeInstanceAccess = doe as DoeInstanceAccess;
DoeViewAccess viewAccess = DoeInstanceAccess.GetDoeViewAccess() as DoeViewAccess;
ICoreObject viewObject = doe.ViewObject;
IEditorFrame frame = doe.EditorFrame;
if (viewObject == cpu)
{
return frame.FrameControl;
}
}
}
return null;
}
public static string GetObjectIdentification(this ICoreObject source)
{
return Helper.GetObjectIdentification(source);
}
}
}
<file_sep>/YZX.TIA/Proxies/ProjectManager/TiaProjectProxy.VatSerice.cs
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.ObjectFrame;
using Siemens.Simatic.PlcLanguages.VatService;
using Siemens.Simatic.PlcLanguages.VatService.Navigator;
using Siemens.Simatic.HwConfiguration.BusinessLogic.Acf.Devices;
using Siemens.Simatic.PlcLanguages.VatService.Businesslogic;
using Siemens.Simatic.PlcLanguages.VatService.Views;
using YZX.Tia.Extensions;
namespace YZX.Tia.Proxies
{
partial class TiaProjectProxy
{
private VatService m_VatService = null;
public VatService VatService
{
get
{
if (m_VatService == null)
{
m_VatService = new VatService();
IDlc dlc_VatService = m_VatService;
dlc_VatService.PreDetach();
dlc_VatService.Attach(ProjectWorkingContext);
m_VatService.SetDebugService(DebugService);
dlc_VatService.PostAttach();
}
return m_VatService;
}
}
public VatServiceProxy VatServiceProxy
{
get
{
VatServiceProxy vsp = new VatServiceProxy(VatService);
return vsp;
}
}
#region VatDevice
public IVatDevice GetVatDevice(ICoreObject controllerTarget)
{
return VatService.GetVatDevice(controllerTarget) as VatDevice;
}
public IVatDevice GetVatDevice(string str)
{
return VatService.GetVatDevice(str) as VatDevice;
}
internal VarTableViewModifyExtension VarTableViewModifyExtension
{
get
{
return ProjectWorkingContext.DlcManager.Load("PlcLanguages.VarTableViewModifyExtension") as VarTableViewModifyExtension;
}
}
#endregion
#region VatServiceNavigator
internal VatServiceNavigator VatServiceNavigator
{
get
{
return VatService.Navigator as VatServiceNavigator;
}
}
public List<IVarTableInfo> GetWatchTables(ICoreObject cpu)
{
if (this.VatService == null)
{
return null;
}
List<IVarTableInfo> vtiList = new List<IVarTableInfo>();
IVarTableInfo[] tableArray = VatServiceNavigator.GetWatchTables(cpu);
foreach (IVarTableInfo table in tableArray)
{
VarTableInfo vti = (VarTableInfo)table;
vtiList.Add(vti);
}
return vtiList;
}
public ICoreObject GetTableCoreObjectByName(string tableName,ICoreObject cpu)
{
ICoreObject table = VatServiceNavigator.GetTableCoreObjectByName(tableName, cpu);
return table;
}
public IVarTableInfo GetTable(string tableName,ICoreObject cpu)
{
IVarTableInfo ivti = VatServiceNavigator.GetTable(tableName, cpu);
VarTableInfo vti = ivti as VarTableInfo;
return vti;
}
public IVarTableInfo GetTableByCPUAndTableName(string cpuName,string tableName)
{
ICoreObject cpu = FindCPU(cpuName);
IVarTableInfo vti = GetTable(tableName, cpu);
return vti;
}
#endregion
}
}
<file_sep>/Siemens.Automation.Basics.Test/Dlc/IWorkingContextExtensions.MonitorLoop.cs
using System;
using Siemens.Automation.Basics;
namespace YZX.Tia.Dlc
{
partial class IWorkingContextExtensions
{
public static IDlc GetMonitorLoop(this IWorkingContext workingContext)
{
return workingContext.DlcManager.Load("Siemens.Simatic.Lang.Code.MonitorLoopFactory");
}
}
}
<file_sep>/Siemens.Automation.Archiving.Test/Proxies/Archiving/ZipCreatorProxy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens.Automation.Archiving;
using Siemens.Automation.Archiving.Private;
using Siemens.Simatic.Hmi.Utah.Common.Base.Reflection;
namespace YZX.Tia.Proxies.Archiving
{
public class ZipCreatorProxy
{
internal ZipCreator ZipCreator;
public ZipCreatorProxy(IWriteableDirectory directory)
{
ZipCreator = directory as ZipCreator;
}
public void CloseCurrentFile()
{
ZipCreator.CloseCurrentFile();
}
public void CloseArchive()
{
Reflector.RunInstanceMethodByName(ZipCreator,
"CloseArchive",
ReflectionWays.SystemReflection);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/WorkingContextAccessProxy.cs
using Siemens.Automation.FrameApplication;
using Siemens.Automation.ObjectFrame;
using Siemens.Automation.Basics;
namespace YZX.Tia.Proxies.FrameApplication
{
public static class WorkingContextAccessProxy
{
public static IWorkingContext GetWorkingContext(this ICoreContext coreContext)
{
return WorkingContextAccess.GetWorkingContext(coreContext);
}
public static IWorkingContext GetWorkingContext(this ICorePersistence corePersistence)
{
return WorkingContextAccess.GetWorkingContext(corePersistence);
}
}
}
<file_sep>/Siemens.Automation.FrameApplication.Test/Proxies/FrameApplication/FrameBaseMetaProxy.cs
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using Siemens.Automation.Basics;
using Siemens.Automation.FrameApplication.WindowManager;
namespace YZX.Tia.Proxies.FrameApplication
{
public class FrameBaseMetaProxy
{
FrameBaseMeta FrameBaseMeta;
internal static FrameBaseMetaProxy ToProxy(FrameBaseMeta meta)
{
if(meta is HierarchyFrameMeta)
{
return HierarchyFrameMetaProxy.ToProxy(meta as HierarchyFrameMeta);
}
return new FrameBaseMetaProxy(meta);
}
internal FrameBaseMetaProxy(FrameBaseMeta meta)
{
FrameBaseMeta = meta;
}
public string ParentId
{
get
{
return FrameBaseMeta.ParentId;
}
}
public string Id
{
get
{
return FrameBaseMeta.Id;
}
}
public Size Size
{
get
{
return FrameBaseMeta.Size;
}
}
public MultiLanguageString Caption
{
get
{
return FrameBaseMeta.Caption;
}
}
public MultiLanguageString ShortCaption
{
get
{
return FrameBaseMeta.ShortCaption;
}
}
public MultiLanguageString Name
{
get
{
return FrameBaseMeta.Name;
}
}
public bool SplitterTopTransparent
{
get
{
return FrameBaseMeta.SplitterTopTransparent;
}
}
public DockStyle Dock
{
get
{
return FrameBaseMeta.Dock;
}
}
public bool CanCollapse
{
get
{
return FrameBaseMeta.CanCollapse;
}
}
public bool Collapsed
{
get
{
return FrameBaseMeta.Collapsed;
}
}
public int Index
{
get
{
return FrameBaseMeta.Index;
}
}
public string[] ToolbarIds
{
get
{
return FrameBaseMeta.ToolbarIds;
}
}
public UserResizableStyle UserResizable
{
get
{
return FrameBaseMeta.UserResizable;
}
}
public Icon Icon
{
get
{
return FrameBaseMeta.Icon;
}
}
public bool IgnorePersist
{
get
{
return FrameBaseMeta.IgnorePersist;
}
}
public List<string> ShortcutIds
{
get
{
return FrameBaseMeta.ShortcutIds;
}
}
public FrameBackground Background
{
get
{
return FrameBaseMeta.Background;
}
}
}
}
|
dd720a9a313035a6664df8aa3aef10b2f5381456
|
[
"Markdown",
"C#",
"Python"
] | 392
|
C#
|
yanzixiang/YZX.TIA
|
5e37ac45f8b7b3ffefa6ab0f8a4f41aef5ef421e
|
ee2285f5e2cc7749b82727ef55193b420c964e4f
|
refs/heads/master
|
<file_sep>let Util = require('Util');
const CreateJobs = {
run: function () {
// CreateJobs
// Rooms - RoomNumber - room.name
// RoomLevel - 0 to 8
// MaxCreeps
// RoomJobs - JobName - [JobName(x,y)] - user friendly, unique per room, name
// JobId - real id
// JobType - int enum - Util.OBJECT_JOB = 1, Util.FLAG_JOB = 2
// CreepType - T, H, B...
// Creep - CreepName - H1 or B4... - if job is not taken then the value is vacant
let flagJobs = CreateFlagJobs();
CreateObjJobs(flagJobs);
//region create jobs
// this method is not just run in the Game.rooms loop because flags may be in 'invisible' rooms
function CreateFlagJobs() {
let jobs = {};
let notFound = false;
for (const gameFlagKey in Game.flags) {
const gameFlag = Game.flags[gameFlagKey];
const color = gameFlag.color;
const secColor = gameFlag.secondaryColor;
if (color === COLOR_ORANGE) { // scout and pos actions and hallway action
if (secColor === COLOR_ORANGE) { // scout tag
jobs = CreateFlagJob(jobs, 'TagCtrl', gameFlagKey, gameFlag, 'S');
} else if (secColor === COLOR_YELLOW) { // scout at pos
jobs = CreateFlagJob(jobs, 'ScoutPos', gameFlagKey, gameFlag, 'S');
} else if (secColor === COLOR_RED) { // flag to be placed on an observer that enables it to scan for power banks and deposits
// observers handle this flag
} else if (secColor === COLOR_PURPLE) { // flag that observers create and put on found power banks and deletes again when deadline is reached
jobs = PowerBankJobs(jobs, gameFlagKey, gameFlag);
} else if (secColor === COLOR_GREY) { // flag that is created for each transporter that should fetch the power
jobs = CreateFlagJob(jobs, 'TrnsprtP', gameFlagKey, gameFlag, 'T');
} else if (secColor === COLOR_CYAN) { // flag that observers create and put on deposits and deletes again when deadline is reached
jobs = CreateFlagJob(jobs, 'HrvstDpst', gameFlagKey, gameFlag, 'D');
} else if (secColor === COLOR_GREEN) { // harvester, transporter and builder move to pos
jobs = CreateFlagJob(jobs, 'HarvestPos', gameFlagKey, gameFlag, 'H');
jobs = CreateFlagJob(jobs, 'TransPos', gameFlagKey, gameFlag, 'T');
jobs = CreateFlagJob(jobs, 'BuildPos', gameFlagKey, gameFlag, 'B');
} else {
notFound = true;
}
} else if (color === COLOR_RED) { // aggressive jobs
if (secColor === COLOR_RED) { // warrior at pos
jobs = CreateFlagJob(jobs, 'GuardPos', gameFlagKey, gameFlag, 'W');
} else if (secColor === COLOR_BLUE) { // gunner at pos
jobs = CreateFlagJob(jobs, 'GuardGunPos', gameFlagKey, gameFlag, 'G');
} else if (secColor === COLOR_GREEN) { // medic at pos
jobs = CreateFlagJob(jobs, 'GuardMedPos', gameFlagKey, gameFlag, 'M');
} else {
notFound = true;
}
} else if (color === COLOR_YELLOW) { // energy actions
notFound = true;
} else if (color === COLOR_PURPLE) { // lab actions
if (secColor === COLOR_PURPLE) { // FillLabMineral
jobs = FillLabMineralJobs(jobs, gameFlagKey, gameFlag);
} else if (secColor === COLOR_WHITE) { // EmptyLabMineral
jobs = EmptyLabMineralJobs(jobs, gameFlagKey, gameFlag);
} else {
notFound = true;
}
} else if (color === COLOR_GREEN) { // claimer actions
if (secColor === COLOR_GREEN) { // claimer claim
jobs = CreateFlagJob(jobs, 'ClaimCtrl', gameFlagKey, gameFlag, 'C');
} else if (secColor === COLOR_YELLOW) { // claimer reserve
jobs = ReserveRoomJobs(jobs, gameFlagKey, gameFlag);
} else if (secColor === COLOR_ORANGE) { // claimer move to pos - used when one wants to enter a portal
jobs = CreateFlagJob(jobs, 'ClaimPos', gameFlagKey, gameFlag, 'C');
} else {
notFound = true;
}
} else if (color === COLOR_BLUE) { // power creep actions
if (secColor === COLOR_ORANGE) {
// PowerCreeps spawn based on flag name = power creep name
} else {
notFound = true;
}
} else {
notFound = true;
}
if (notFound) {
Util.ErrorLog('CreateJobs', 'CreateFlagJobs', 'flag color not found ' + gameFlagKey + ' ' + gameFlag.color + ' ' + gameFlag.secondaryColor + ' (' + gameFlag.pos.x + ',' + gameFlag.pos.y + ')');
}
}
return jobs;
}
function CreateFlagJob(jobs, jobName, gameFlagKey, gameFlag, creepType) {
//Util.Info('CreateJobs', 'CreateFlagJob', 'AddJob ' + gameFlagKey);
return AddJob(jobs, jobName + '-' + gameFlagKey + '(' + gameFlag.pos.x + ',' + gameFlag.pos.y + ')' + gameFlag.pos.roomName, gameFlagKey, Util.FLAG_JOB, creepType);
}
function CreateObjJobs(flagJobs) {
for (const gameRoomKey in Game.rooms) {
const gameRoom = Game.rooms[gameRoomKey]; // visible room
let jobs = {};
// weave flag jobs into the job array that is in this room object
for (const flagJobKey in flagJobs) {
if (flagJobKey.split(')').pop() === gameRoomKey) {
const flagJob = flagJobs[flagJobKey];
jobs[flagJobKey] = flagJob; // add job to this room job array
flagJobs[flagJobKey] = undefined;
//Util.Info('CreateJobs', 'CreateObjJobs', 'flagJobs found in ' + gameRoomKey + ' ' + flagJobKey + ' ' + JSON.stringify(jobs[flagJobKey]) + ' length ' + Object.keys(jobs).length);
}
}
if (gameRoom.controller && gameRoom.controller.my) { // create all the jobs in this room
if(!gameRoom.controller.pos.lookFor(LOOK_FLAGS)[0] && (!gameRoom.controller.sign || gameRoom.controller.sign.text !== 'Homebrewed code @ github.com/fbro/HScreeps ' + gameRoom.name)){
const result = gameRoom.createFlag(gameRoom.controller.pos, 'Homebrewed code @ github.com/fbro/HScreeps ' + gameRoom.name, COLOR_ORANGE, COLOR_ORANGE);
Util.InfoLog('CreateJobs', 'CreateObjJobs', 'createFlag sign flag ' + gameRoom.controller.pos + ' ' + result);
}
// Source
const sources = gameRoom.find(FIND_SOURCES);
for (const sourceKey in sources) {
const source = sources[sourceKey];
new RoomVisual(gameRoom.name).text('🏭', source.pos.x, source.pos.y);
AddJob(jobs, 'Src(' + source.pos.x + ',' + source.pos.y + ')' + gameRoom.name, source.id, Util.OBJECT_JOB, 'H');
if (gameRoom.controller.level < 3) {
const freeSpaces = Util.FreeSpaces(source.pos);
if (freeSpaces > 1) {
AddJob(jobs, 'Src(' + source.pos.x + ',' + source.pos.y + ')' + gameRoom.name, source.id, Util.OBJECT_JOB, 'H');
}
}
}
// Controller
new RoomVisual(gameRoom.name).text('🧠', gameRoom.controller.pos.x, gameRoom.controller.pos.y);
if(!gameRoom.storage || gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) >= Util.STORAGE_ENERGY_LOW || gameRoom.controller.ticksToDowngrade < 20000){
AddJob(jobs, 'Ctrl(' + gameRoom.controller.pos.x + ',' + gameRoom.controller.pos.y + ')' + gameRoom.name, gameRoom.controller.id, Util.OBJECT_JOB, 'B');
}
if (!gameRoom.storage || gameRoom.storage && gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) > Util.STORAGE_ENERGY_MEDIUM && gameRoom.controller.level < 8) {
AddJob(jobs, 'Ctrl1(' + gameRoom.controller.pos.x + ',' + gameRoom.controller.pos.y + ')' + gameRoom.name, gameRoom.controller.id, Util.OBJECT_JOB, 'B');
AddJob(jobs, 'Ctrl2(' + gameRoom.controller.pos.x + ',' + gameRoom.controller.pos.y + ')' + gameRoom.name, gameRoom.controller.id, Util.OBJECT_JOB, 'B');
}
// FillSpawnExtension
FillSpawnExtensionJobs(gameRoom, jobs);
// Construction
ConstructionJobs(gameRoom, jobs);
// Repair
RepairJobs(gameRoom, jobs);
// FillControllerContainer
FillControllerContainerJobs(gameRoom, jobs);
if (gameRoom.controller.level >= 3) {
// FillTower
FillTowerJobs(gameRoom, jobs);
if (gameRoom.controller.level >= 4) {
if (gameRoom.storage !== undefined) {
// FillStorage - link, container and resource drops
FillStorageJobs(gameRoom, jobs);
if (gameRoom.controller.level >= 6) {
// ExtractMineral
ExtractMineralJobs(gameRoom, jobs);
// FillTerminal
FillTerminalJobs(gameRoom, jobs);
// FillFactory
FillFactoryJobs(gameRoom, jobs);
// FillLabEnergy
FillLabEnergyJobs(gameRoom, jobs);
if (gameRoom.controller.level === 8) {
FillPowerSpawnEnergyJobs(gameRoom, jobs);
FillPowerSpawnPowerJobs(gameRoom, jobs);
}
}
}
}
}
}
if (!Memory.MemRooms[gameRoom.name] && Object.keys(jobs).length > 0) { // room not found and there are jobs in it - create it
CreateRoom(gameRoom.name, jobs);
} else if (Memory.MemRooms[gameRoom.name]) { // update jobs in memRoom
let addedNewJob = false;
// add new jobs
for (const newJobKey in jobs) { // loop through new jobs
if (!Memory.MemRooms[gameRoom.name].RoomJobs[newJobKey]) { // new job does not already exist
Memory.MemRooms[gameRoom.name].RoomJobs[newJobKey] = jobs[newJobKey]; // save it
//Util.Info('CreateJobs', 'CreateObjJobs', 'new job added ' + newJobKey);
IncrementMaxCreepsMForFlagJob(jobs[newJobKey], gameRoom.name);// increment M if it is a new flag job
addedNewJob = true;
}
}
// remove only old disappeared vacant jobs
for (const oldJobKey in Memory.MemRooms[gameRoom.name].RoomJobs) { // loop through old jobs
const oldJob = Memory.MemRooms[gameRoom.name].RoomJobs[oldJobKey];
if (oldJob.Creep === 'vacant' && !jobs[oldJobKey]) { // old job is vacant and old job id not in the new job array
Util.DeleteJob(oldJob, oldJobKey, gameRoom.name);
}
}
if (gameRoom.controller && Memory.MemRooms[gameRoom.name].RoomLevel !== gameRoom.controller.level) { // room level change
Memory.MemRooms[gameRoom.name].RoomLevel = gameRoom.controller.level;
Memory.MemRooms[gameRoom.name].SourceNumber = gameRoom.find(FIND_SOURCES).length;
for(const maxCreepKey in Memory.MemRooms[gameRoom.name].MaxCreeps){
Memory.MemRooms[gameRoom.name].MaxCreeps[maxCreepKey].M = undefined; // reset - maybe the MaxCreepsInRoom changes with room level
}
}
}
}
// now some flag jobs might still be unplaced, loop trough them and add them maybe also create the room object
// they might still be unplaced because they are in a room that is not in MemRooms
for (const flagJobKey in flagJobs) {
const roomName = flagJobKey.split(')').pop();
const flagJob = flagJobs[flagJobKey];
if (Memory.MemRooms[roomName]) {
if (!Memory.MemRooms[roomName].RoomJobs[flagJobKey]) {
Memory.MemRooms[roomName].RoomJobs[flagJobKey] = flagJob;
}
} else {
const jobs = {};
jobs[flagJobKey] = flagJob;
CreateRoom(roomName, jobs);
}
}
}
function IncrementMaxCreepsMForFlagJob(job, roomName){
// increase MaxCreeps.M for when flag jobs are created
if(Memory.MemRooms[roomName] && job.JobType === Util.FLAG_JOB && job.CreepType !== 'T' && job.CreepType !== 'B') {
if(Memory.MemRooms[roomName].MaxCreeps){
if(Memory.MemRooms[roomName].MaxCreeps[job.CreepType]){
if(!Memory.MemRooms[roomName].MaxCreeps[job.CreepType].M){
Memory.MemRooms[roomName].MaxCreeps[job.CreepType]['M'] = 0;
}
}else{
Memory.MemRooms[roomName].MaxCreeps[job.CreepType] = {'M' : 0};
}
}else{
Memory.MemRooms[roomName].MaxCreeps = {};
Memory.MemRooms[roomName].MaxCreeps[job.CreepType] = {'M' : 0};
}
Memory.MemRooms[roomName].MaxCreeps[job.CreepType].M += 1;
}
}
//endregion
//region flag jobs
function PowerBankJobs(jobs, gameFlagKey, gameFlag) {
jobs = CreateFlagJob(jobs, 'AtkP1', gameFlagKey, gameFlag, 'W');
jobs = CreateFlagJob(jobs, 'AtkP2', gameFlagKey, gameFlag, 'W');
jobs = CreateFlagJob(jobs, 'MedP1', gameFlagKey, gameFlag, 'M');
jobs = CreateFlagJob(jobs, 'MedP2', gameFlagKey, gameFlag, 'M');
return jobs;
}
function FillLabMineralJobs(jobs, gameFlagKey, gameFlag) {
const mineral = gameFlagKey.split(/[-]+/).filter(function (e) {
return e;
})[1];
const lab = gameFlag.pos.findInRange(FIND_MY_STRUCTURES, 0, {filter: function (s) {return s.structureType === STRUCTURE_LAB;}})[0];
if (lab && (!lab.mineralType || lab.mineralType === mineral)) {
// flagname rules: GET-L-roomname = get lemergium from all rooms, BUY-L-roomname = get lemergium from all rooms or then buy it from the terminal
if(lab.store.getFreeCapacity(mineral) >= Util.TRANSPORTER_MAX_CARRY && (lab.room.storage.store.getUsedCapacity(mineral) > 0 || lab.room.terminal.store.getUsedCapacity(mineral) > 0)){
jobs = CreateFlagJob(jobs, 'FillLabMin', gameFlagKey, gameFlag, 'T');
}
}else{ // flag must be on top of an existing lab!
Util.ErrorLog('CreateJobs', 'CreateFlagJobs', 'lab not found! ' + gameFlagKey);
gameFlag.remove();
}
return jobs;
}
function EmptyLabMineralJobs(jobs, gameFlagKey, gameFlag) {
const mineral = gameFlagKey.split(/[-]+/).filter(function (e) {
return e;
})[1];
const lab = gameFlag.pos.findInRange(FIND_MY_STRUCTURES, 0, {filter: function (s) {return s.structureType === STRUCTURE_LAB;}})[0];
if(lab && (!lab.mineralType || lab.mineralType === mineral)){
// flagname rules: EMPTY-GH-roomname = create the mineral and allows it to be emptied from the nearby lab to this lab
//Util.Info('CreateJobs', 'CreateFlagJobs', 'mineral ' + mineral + ' lab ' + lab.store.getUsedCapacity(mineral) + ' terminal ' + lab.room.terminal.store.getUsedCapacity(mineral));
if (lab.store.getUsedCapacity(mineral) >= Util.TRANSPORTER_MAX_CARRY && lab.room.terminal.store.getUsedCapacity(mineral) < Util.TERMINAL_MAX_RESOURCE) {
CreateFlagJob(jobs, 'EmptyLabMin', gameFlagKey, gameFlag, 'T');
}
}else{ // flag must be on top of an existing lab!
Util.ErrorLog('CreateJobs', 'CreateFlagJobs', 'lab not found! ' + gameFlagKey);
gameFlag.remove();
}
return jobs;
}
function ReserveRoomJobs(jobs, gameFlagKey, gameFlag) {
if (!gameFlag.room
|| !gameFlag.room.controller.reservation
|| !Memory.MemRooms[gameFlag.pos.roomName]
|| Memory.MemRooms[gameFlag.pos.roomName].RoomJobs['ReserveCtrl-' + gameFlagKey + '(' + gameFlag.pos.x + ',' + gameFlag.pos.y + ')' + gameFlag.pos.roomName]
|| (gameFlag.room.controller.reservation.ticksToEnd < 2500 && !Memory.MemRooms[gameFlag.pos.roomName].RoomJobs[gameFlagKey])) { // extra logic to try and optimize creep not being idle
jobs = CreateFlagJob(jobs, 'ReserveCtrl', gameFlagKey, gameFlag, 'R');
}
return jobs;
}
//endregion
//region room jobs
function FillPowerSpawnEnergyJobs(gameRoom, roomJobs) {
if (gameRoom.storage && gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) > Util.STORAGE_ENERGY_LOW) {
const powerSpawns = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return s.structureType === STRUCTURE_POWER_SPAWN;
}
});
for (const powerSpawnKey in powerSpawns) {
const powerSpawn = powerSpawns[powerSpawnKey];
if (powerSpawn && powerSpawn.store.getFreeCapacity(RESOURCE_ENERGY) > 0) {
new RoomVisual(gameRoom.name).text('⚡', powerSpawn.pos.x, powerSpawn.pos.y);
AddJob(roomJobs, 'FillPSpwnE(' + powerSpawn.pos.x + ',' + powerSpawn.pos.y + ')' + gameRoom.name, powerSpawn.id, Util.OBJECT_JOB, 'T');
}
}
}
}
function FillPowerSpawnPowerJobs(gameRoom, roomJobs) {
if (gameRoom.storage && gameRoom.storage.store.getUsedCapacity(RESOURCE_POWER) > 0 || gameRoom.terminal && gameRoom.terminal.store.getUsedCapacity(RESOURCE_POWER) > 0) {
const powerSpawn = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return s.structureType === STRUCTURE_POWER_SPAWN;
}
})[0];
if (powerSpawn && powerSpawn.store.getFreeCapacity(RESOURCE_POWER) > 0) {
new RoomVisual(gameRoom.name).text('🌪️', powerSpawn.pos.x, powerSpawn.pos.y);
AddJob(roomJobs, 'FillPSpwnP(' + powerSpawn.pos.x + ',' + powerSpawn.pos.y + ')' + gameRoom.name, powerSpawn.id, Util.OBJECT_JOB, 'T');
}
}
}
function FillLabEnergyJobs(gameRoom, roomJobs) {
if (gameRoom.storage && gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) > 5000) {
const labs = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return s.structureType === STRUCTURE_LAB;
}
});
for (const labKey in labs) {
const lab = labs[labKey];
if (lab && lab.store.getUsedCapacity(RESOURCE_ENERGY) < lab.store.getCapacity(RESOURCE_ENERGY)) {
new RoomVisual(gameRoom.name).text('⚡', lab.pos.x, lab.pos.y);
AddJob(roomJobs, 'FillLabE(' + lab.pos.x + ',' + lab.pos.y + ')' + gameRoom.name, lab.id, Util.OBJECT_JOB, 'T');
}
}
}
}
function FillTerminalJobs(gameRoom, roomJobs) {
if (gameRoom.storage && gameRoom.terminal) {
for (const resourceType in gameRoom.storage.store) {
const storageResourceAmount = gameRoom.storage.store.getUsedCapacity(resourceType);
let maxResources = 0;
let High = Util.STORAGE_HIGH; // 10000
let HighTransfer = Util.STORAGE_HIGH_TRANSFER; // 8000
let Medium = Util.STORAGE_MEDIUM; // 4000
let MediumTransfer = Util.STORAGE_MEDIUM_TRANSFER; // 6000
let Low = Util.STORAGE_LOW; // 0
let LowTransfer = Util.STORAGE_LOW_TRANSFER; // 3000
if (resourceType === RESOURCE_ENERGY) {
High = Util.STORAGE_ENERGY_HIGH; // 200000
HighTransfer = Util.STORAGE_ENERGY_HIGH_TRANSFER; // 100000
Medium = Util.STORAGE_ENERGY_MEDIUM; // 100000
MediumTransfer = Util.STORAGE_ENERGY_MEDIUM_TRANSFER; // 80000
Low = Util.STORAGE_ENERGY_LOW; // 10000
LowTransfer = Util.STORAGE_ENERGY_LOW_TRANSFER; // 50000
}
// if storage contains alot of the specified resource then allow the terminal to be filled to an extent where it will sell out
if (storageResourceAmount >= High) {
maxResources = HighTransfer;
} else if (storageResourceAmount >= Medium) {
maxResources = MediumTransfer;
} else if (storageResourceAmount >= Low) {
maxResources = LowTransfer;
}
if (gameRoom.terminal.store.getUsedCapacity(resourceType) < maxResources) {
new RoomVisual(gameRoom.name).text('🚄', gameRoom.terminal.pos.x, gameRoom.terminal.pos.y);
AddJob(roomJobs, 'FillTerm(' + resourceType + ')' + gameRoom.name, gameRoom.terminal.id, Util.OBJECT_JOB, 'T');
}
}
}
}
function FillFactoryJobs(gameRoom, roomJobs) {
if (gameRoom.storage && gameRoom.terminal) {
const factory = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return s.structureType === STRUCTURE_FACTORY;
}
})[0];
if (factory) {
if (factory.store.getUsedCapacity(RESOURCE_ENERGY) < 10000) {
AddJob(roomJobs, 'FillFctr(' + RESOURCE_ENERGY + ')' + gameRoom.name, factory.id, Util.OBJECT_JOB, 'T');
}
// Biological chain
if (gameRoom.storage.store.getUsedCapacity(RESOURCE_BIOMASS) > 0
|| gameRoom.terminal.store.getUsedCapacity(RESOURCE_BIOMASS) > 0
|| factory.store.getUsedCapacity(RESOURCE_BIOMASS) > 0
|| factory.store.getUsedCapacity(RESOURCE_CELL) > 0) {
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_BIOMASS);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_LEMERGIUM);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_LEMERGIUM_BAR);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_CELL);
if (factory.store.getUsedCapacity(RESOURCE_CELL) > 0 && factory.level === 1) { // level 1 specific
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_OXYGEN);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_OXIDANT);
}else if(factory.store.getUsedCapacity(RESOURCE_CELL) > 0 && factory.level === 2){ // level 2 specific
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_HYDROGEN);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_REDUCTANT);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_PHLEGM);
}
}
// Mechanical chain
if (gameRoom.storage.store.getUsedCapacity(RESOURCE_METAL) > 0
|| gameRoom.terminal.store.getUsedCapacity(RESOURCE_METAL) > 0
|| factory.store.getUsedCapacity(RESOURCE_METAL) > 0
|| factory.store.getUsedCapacity(RESOURCE_ALLOY) > 0) {
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_METAL);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_ZYNTHIUM);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_ZYNTHIUM_BAR);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_ALLOY);
if (factory.store.getUsedCapacity(RESOURCE_ALLOY) > 0 && factory.level === 1) { // level 1 specific
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_UTRIUM);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_UTRIUM_BAR);
}else if(factory.store.getUsedCapacity(RESOURCE_ALLOY) > 0 && factory.level === 2){ // level 2 specific
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_OXYGEN);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_OXIDANT);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_COMPOSITE); // used for lvl 2 FIXTURES
}else if(factory.store.getUsedCapacity(RESOURCE_ALLOY) > 0 && factory.level === 3){ // level 3 specific
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_FIXTURES);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_TUBE);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_HYDROGEN);
roomJobs = TryAddFillFactoryJob(gameRoom, factory, roomJobs, RESOURCE_REDUCTANT);
}
}
}
}
return roomJobs;
}
function TryAddFillFactoryJob(gameRoom, factory, roomJobs, resource) {
if (factory.store.getUsedCapacity(resource) < 2000 && (gameRoom.storage.store.getUsedCapacity(resource) > 0 || gameRoom.terminal.store.getUsedCapacity(resource) > 0)) {
roomJobs = AddJob(roomJobs, 'FillFctr(' + resource + ')' + gameRoom.name, factory.id, Util.OBJECT_JOB, 'T');
}
return roomJobs;
}
function ExtractMineralJobs(gameRoom, roomJobs) {
const mineral = gameRoom.find(FIND_MINERALS, {
filter: (s) => {
return s.mineralAmount > 0;
}
})[0];
if (mineral && gameRoom.storage && (gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) > Util.STORAGE_ENERGY_MEDIUM/*do not extract minerals when low on storage energy*/ && gameRoom.storage.store.getUsedCapacity(mineral.mineralType) < Util.DO_EXTRACTING_WHEN_STORAGE_UNDER_MINERAL
|| gameRoom.find(FIND_MY_CREEPS, {
filter: (c) => {
return c.name.startsWith('E');
}
})[0]
)) { // only create these jobs when one has energy in the room
const extractMineral = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return s.structureType === STRUCTURE_EXTRACTOR;
}
})[0];
if (extractMineral) {
new RoomVisual(gameRoom.name).text('⛏', extractMineral.pos.x, extractMineral.pos.y);
AddJob(roomJobs, 'ExtrMin-' + mineral.mineralType + '(' + extractMineral.pos.x + ',' + extractMineral.pos.y + ')' + gameRoom.name, mineral.id, Util.OBJECT_JOB, 'E');
}
}
}
function FillStorageJobs(gameRoom, roomJobs) {
if (gameRoom.storage.store.getFreeCapacity() < 5000) {
Util.Warning('CreateJobs', 'FillStorageJobs', 'storage full! ' + gameRoom.name);
return;
}
// container
const containers = gameRoom.find(FIND_STRUCTURES, {
filter: (s) => {
return (s.structureType === STRUCTURE_CONTAINER && Memory.MemRooms[gameRoom.name]);
}
});
for (const containerKey in containers) {
const container = containers[containerKey];
new RoomVisual(gameRoom.name).text('📦', container.pos.x, container.pos.y);
for (const resourceType in container.store) {
if (container.id !== Memory.MemRooms[gameRoom.name].CtrlConId && container.store.getUsedCapacity() >= 600 || resourceType !== RESOURCE_ENERGY) { // do not empty the controller container for energy
AddJob(roomJobs, 'FillStrg-' + container.structureType + '(' + container.pos.x + ',' + container.pos.y + ',' + resourceType + ')' + gameRoom.name, container.id, Util.OBJECT_JOB, 'T');
}
}
}
// link
const link = gameRoom.storage.pos.findInRange(FIND_MY_STRUCTURES, 1, {
filter: (s) => {
return s.structureType === STRUCTURE_LINK && s.store.getUsedCapacity(RESOURCE_ENERGY) >= 600;
}
})[0];
if (link) {
AddJob(roomJobs, 'FillStrg-' + link.structureType + '(' + link.pos.x + ',' + link.pos.y + ',' + RESOURCE_ENERGY + ')' + gameRoom.name, link.id, Util.OBJECT_JOB, 'T');
}
// terminal
if (gameRoom.terminal && (gameRoom.terminal.store.getUsedCapacity(RESOURCE_ENERGY) >= 120000 || (gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) < 5000 || !gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY)) && gameRoom.terminal.store.getUsedCapacity(RESOURCE_ENERGY) >= Util.TERMINAL_TARGET_ENERGY)) {
AddJob(roomJobs, 'FillStrg-' + gameRoom.terminal.structureType + '(' + gameRoom.terminal.pos.x + ',' + gameRoom.terminal.pos.y + ',' + RESOURCE_ENERGY + ')' + gameRoom.name, gameRoom.terminal.id, Util.OBJECT_JOB, 'T');
}
// factory
if(Memory.MemRooms[gameRoom.name].FctrId && Memory.MemRooms[gameRoom.name].FctrId !== '-'){
const factory = Game.getObjectById(Memory.MemRooms[gameRoom.name].FctrId);
if (factory) {
for (const resourceType in factory.store) {
const amount = factory.store.getUsedCapacity(resourceType);
if ( resourceType === RESOURCE_PHLEGM && amount >= 100 && factory.level === 1
|| resourceType === RESOURCE_TUBE && amount >= 100 && factory.level === 1
|| resourceType === RESOURCE_COMPOSITE && amount >= 100 && factory.level === 1
|| resourceType === RESOURCE_TISSUE && amount >= 50 && factory.level === 2
|| resourceType === RESOURCE_FIXTURES && amount >= 50 && factory.level === 2
|| resourceType === RESOURCE_MUSCLE && amount >= 1000 && factory.level === 3
|| resourceType === RESOURCE_ORGANOID && amount >= 1000 && factory.level === 4
|| resourceType === RESOURCE_ORGANISM && amount >= 1000 && factory.level === 5) {
new RoomVisual(gameRoom.name).text('🏭', factory.pos.x, factory.pos.y);
AddJob(roomJobs, 'FillStrg-' + factory.structureType + '(' + factory.pos.x + ',' + factory.pos.y + ',' + resourceType + ')' + gameRoom.name, factory.id, Util.OBJECT_JOB, 'T');
}
}
}
}
// drop
const resourceDrops = gameRoom.find(FIND_DROPPED_RESOURCES, {
filter: (drop) => {
return (drop.resourceType === RESOURCE_ENERGY && drop.amount > 100 || drop.resourceType !== RESOURCE_ENERGY && drop.amount > 30);
}
});
for (const resourceDropKey in resourceDrops) {
const resourceDrop = resourceDrops[resourceDropKey];
new RoomVisual(gameRoom.name).text('💰', resourceDrop.pos.x, resourceDrop.pos.y);
AddJob(roomJobs, 'FillStrg-drop' + '(' + resourceDrop.pos.x + ',' + resourceDrop.pos.y + ',' + resourceDrop.resourceType + ')' + gameRoom.name, resourceDrop.id, Util.OBJECT_JOB, 'T');
}
// tombstone
const tombstoneDrops = gameRoom.find(FIND_TOMBSTONES, {
filter: (tombstone) => {
return tombstone.store.getUsedCapacity() > 0;
}
});
for (const tombstoneDropKey in tombstoneDrops) {
const tombstoneDrop = tombstoneDrops[tombstoneDropKey];
new RoomVisual(gameRoom.name).text('⚰', tombstoneDrop.pos.x, tombstoneDrop.pos.y);
AddJob(roomJobs, 'FillStrg-tomb' + '(' + tombstoneDrop.pos.x + ',' + tombstoneDrop.pos.y + ')' + gameRoom.name, tombstoneDrop.id, Util.OBJECT_JOB, 'T');
}
// ruin
const ruinDrops = gameRoom.find(FIND_RUINS, {
filter: (ruin) => {
return ruin.store.getUsedCapacity() > 0;
}
});
for (const ruinDropKey in ruinDrops) {
const ruinDrop = ruinDrops[ruinDropKey];
new RoomVisual(gameRoom.name).text('🏚️', ruinDrop.pos.x, ruinDrop.pos.y);
AddJob(roomJobs, 'FillStrg-ruin' + '(' + ruinDrop.pos.x + ',' + ruinDrop.pos.y + ')' + gameRoom.name, ruinDrop.id, Util.OBJECT_JOB, 'T');
}
}
function FillTowerJobs(gameRoom, roomJobs) {
const fillTowers = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return ((s.structureType === STRUCTURE_TOWER) && s.store.getUsedCapacity(RESOURCE_ENERGY) < (s.store.getCapacity(RESOURCE_ENERGY) - 100));
}
});
for (const fillTowerKey in fillTowers) {
const fillTower = fillTowers[fillTowerKey];
new RoomVisual(gameRoom.name).text('🗼', fillTower.pos.x, fillTower.pos.y);
AddJob(roomJobs, 'FillTwr(' + fillTower.pos.x + ',' + fillTower.pos.y + ')' + gameRoom.name, fillTower.id, Util.OBJECT_JOB, 'T');
}
}
function FillSpawnExtensionJobs(gameRoom, roomJobs) {
const fillSpawnExtensions = gameRoom.find(FIND_MY_STRUCTURES, {
filter: (s) => {
return ((s.structureType === STRUCTURE_SPAWN || s.structureType === STRUCTURE_EXTENSION) && s.store.getUsedCapacity(RESOURCE_ENERGY) < s.store.getCapacity(RESOURCE_ENERGY));
}
});
for (const fillSpawnExtensionKey in fillSpawnExtensions) {
const fillSpawnExtension = fillSpawnExtensions[fillSpawnExtensionKey];
new RoomVisual(gameRoom.name).text('🌱', fillSpawnExtension.pos.x, fillSpawnExtension.pos.y);
AddJob(roomJobs, 'FillSpwnEx(' + fillSpawnExtension.pos.x + ',' + fillSpawnExtension.pos.y + ')' + gameRoom.name, fillSpawnExtension.id, Util.OBJECT_JOB, 'T');
}
}
function ConstructionJobs(gameRoom, roomJobs) {
const constructions = gameRoom.find(FIND_CONSTRUCTION_SITES);
for (const constructionKey in constructions) {
const construction = constructions[constructionKey];
new RoomVisual(gameRoom.name).text('🏗', construction.pos.x, construction.pos.y);
AddJob(roomJobs, 'Constr-' + construction.structureType + '(' + construction.pos.x + ',' + construction.pos.y + ')' + gameRoom.name, construction.id, Util.OBJECT_JOB, 'B');
}
}
function RepairJobs(gameRoom, roomJobs) {
const repairs = gameRoom.find(FIND_STRUCTURES, {
filter: (s) => {
return (
s.hits < s.hitsMax / 1.5 // health at 75%
&&
(
(
(s.structureType === STRUCTURE_RAMPART || s.structureType === STRUCTURE_WALL)
&& (gameRoom.controller.level < 5 && s.hits < Util.RAMPART_WALL_HITS_U_LVL5
|| gameRoom.controller.level >= 5 && gameRoom.controller.level < 8 && s.hits < Util.RAMPART_WALL_HITS_U_LVL8
|| gameRoom.controller.level === 8 && (s.hits < Util.RAMPART_WALL_HITS_O_LVL8 || gameRoom.storage && gameRoom.storage.store.getUsedCapacity(RESOURCE_ENERGY) > Util.RAMPART_WALL_MAX_HITS_WHEN_STORAGE_ENERGY))
||
s.structureType === STRUCTURE_ROAD && s.hits < s.hitsMax / 2
)
||
(
s.structureType !== STRUCTURE_RAMPART &&
s.structureType !== STRUCTURE_WALL &&
s.structureType !== STRUCTURE_ROAD
)
)
);
}
});
for (const repairKey in repairs) {
const repair = repairs[repairKey];
new RoomVisual(gameRoom.name).text('🛠', repair.pos.x, repair.pos.y);
AddJob(roomJobs, 'Rep-' + repair.structureType + '(' + repair.pos.x + ',' + repair.pos.y + ')' + gameRoom.name, repair.id, Util.OBJECT_JOB, 'B');
}
}
function FillControllerContainerJobs(gameRoom, roomJobs) {
let controllerContainer;
if (Memory.MemRooms[gameRoom.name] && Memory.MemRooms[gameRoom.name].CtrlConId) {
controllerContainer = Game.getObjectById(Memory.MemRooms[gameRoom.name].CtrlConId);
if (!controllerContainer) {
Util.InfoLog('CreateJobs', 'FillControllerContainerJobs', 'removed container id from mem' + gameRoom.name);
Memory.MemRooms[gameRoom.name].CtrlConId = undefined;
}
}else if (!controllerContainer && Memory.MemRooms[gameRoom.name]) {
controllerContainer = gameRoom.controller.pos.findInRange(FIND_STRUCTURES, 3, {
filter: (s) => {
return s.structureType === STRUCTURE_CONTAINER;
}
})[0];
if (controllerContainer) {
Util.InfoLog('CreateJobs', 'FillControllerContainerJobs', 'found new container (' + controllerContainer.pos.x + ',' + controllerContainer.pos.y + ',' + controllerContainer.pos.roomName + ') saving in memory');
Memory.MemRooms[gameRoom.name].CtrlConId = controllerContainer.id;
}
}
if (controllerContainer && controllerContainer.store.getFreeCapacity() > 0) {
new RoomVisual(gameRoom.name).text('🔋', controllerContainer.pos.x, controllerContainer.pos.y);
AddJob(roomJobs, 'FillCtrlCon(' + controllerContainer.pos.x + ',' + controllerContainer.pos.y + ')' + gameRoom.name, controllerContainer.id, Util.OBJECT_JOB, 'T');
}
}
//endregion
//region helper functions
function CreateRoom(roomName, jobs) {
const gameRoom = Game.rooms[roomName];
let level = -1;
let sourceNumber = 0;
if (gameRoom) {
if (gameRoom.controller) {
level = gameRoom.controller.level;
}
sourceNumber = gameRoom.find(FIND_SOURCES).length;
}
Memory.MemRooms[roomName] = {
'RoomLevel': level, // 0 to 8 or if there are NO controller then -1
'RoomJobs': jobs, // JobName - [JobName(x,y)] - user friendly, unique per room, name
'MaxCreeps': {}, // object that gives information on how many of each type of creep may be in the room and what creeps of that type is in the room
'SourceNumber': sourceNumber, // number of sources in room
};
Util.Info('CreateJobs', 'CreateRoom', 'add new room ' + roomName + ' level ' + level + ' sourceNumber ' + sourceNumber + ' jobs ' + JSON.stringify(jobs))
}
function AddJob(roomJobs, jobName, jobId, jobType, creepType) {
roomJobs[jobName] = { // create job - RoomJobs - JobName - [JobName(x,y)] - user friendly, unique per room, name
'JobId': jobId, // real id
'JobType': jobType, // int enum - Util.OBJECT_JOB = 1, Util.FLAG_JOB = 2
'CreepType': creepType, // T, H, B...
'Creep': 'vacant' // CreepName - H1 or B4... - if job is not taken then the value is vacant
};
return roomJobs;
}
//endregion
}
};
module.exports = CreateJobs;<file_sep>let Util = require('Util');
const Factories = {
run: function () {
for (const gameRoomKey in Game.rooms) {
const gameRoom = Game.rooms[gameRoomKey];
const memRoom = Memory.MemRooms[gameRoomKey];
if (memRoom && memRoom.FctrId !== '-' && gameRoom.controller && gameRoom.controller.my && gameRoom.controller.level === 8) {
let factory;
if(memRoom.FctrId){
factory = Game.getObjectById(memRoom.FctrId);
}
if(!factory){
factory = gameRoom.find(FIND_MY_STRUCTURES, {
filter: function (factory) {
return factory.structureType === STRUCTURE_FACTORY && factory.cooldown === 0 && factory.store.getUsedCapacity(RESOURCE_ENERGY) > 0;
}
})[0];
if(factory) {
memRoom.FctrId = factory.id;
Util.InfoLog('Factories', '', 'add new factory in ' + gameRoomKey + ' FctrId ' + memRoom.FctrId);
}
}
if(factory && factory.cooldown === 0){
let result;
const hasOperateFactoryEffect = factory.effects && factory.effects[0] && factory.effects[0].effect === PWR_OPERATE_FACTORY;
if(factory.level === 1 && hasOperateFactoryEffect){
result = Produce(factory, RESOURCE_PHLEGM, 2000, RESOURCE_OXIDANT, 36, RESOURCE_CELL, 20, RESOURCE_LEMERGIUM_BAR, 16, RESOURCE_ENERGY, 8);
if(result !== OK) {
result = Produce(factory, RESOURCE_COMPOSITE, 2000, RESOURCE_UTRIUM_BAR, 20, RESOURCE_ZYNTHIUM_BAR, 20, RESOURCE_ENERGY, 20);
if(result !== OK){
result = Produce(factory, RESOURCE_TUBE, 2000, RESOURCE_ALLOY, 40, RESOURCE_ZYNTHIUM_BAR, 16, RESOURCE_ENERGY, 8);
}
}
}else if(factory.level === 2 && hasOperateFactoryEffect){
result = Produce(factory, RESOURCE_TISSUE, 2000, RESOURCE_REDUCTANT, 110, RESOURCE_CELL, 10, RESOURCE_PHLEGM, 10, RESOURCE_ENERGY, 16);
if(result !== OK) {
result = Produce(factory, RESOURCE_FIXTURES, 2000, RESOURCE_COMPOSITE, 20, RESOURCE_ALLOY, 41, RESOURCE_OXIDANT, 161, RESOURCE_ENERGY, 8);
}
}else if(factory.level === 3 && hasOperateFactoryEffect){
result = Produce(factory, RESOURCE_FRAME, 2000, RESOURCE_FIXTURES, 2, RESOURCE_TUBE, 4, RESOURCE_REDUCTANT, 330, RESOURCE_ZYNTHIUM_BAR, 31, RESOURCE_ENERGY, 16);
}
if(result !== OK) {
result = Produce(factory, RESOURCE_LEMERGIUM_BAR, 1000, RESOURCE_LEMERGIUM, 500, RESOURCE_ENERGY, 200);
if(result !== OK) {
result = Produce(factory, RESOURCE_ZYNTHIUM_BAR, 1000, RESOURCE_ZYNTHIUM, 500, RESOURCE_ENERGY, 200);
if(result !== OK) {
result = Produce(factory, RESOURCE_UTRIUM_BAR, 1000, RESOURCE_UTRIUM, 500, RESOURCE_ENERGY, 200);
if (result !== OK) {
result = Produce(factory, RESOURCE_OXIDANT, 1000, RESOURCE_OXYGEN, 500, RESOURCE_ENERGY, 200);
if (result !== OK) {
result = Produce(factory, RESOURCE_REDUCTANT, 1000, RESOURCE_HYDROGEN, 500, RESOURCE_ENERGY, 200);
if (result !== OK) {
result = Produce(factory, RESOURCE_CELL, 1000, RESOURCE_BIOMASS, 100, RESOURCE_LEMERGIUM_BAR, 20, RESOURCE_ENERGY, 40);
if (result !== OK) {
result = Produce(factory, RESOURCE_ALLOY, 1000, RESOURCE_METAL, 100, RESOURCE_ZYNTHIUM_BAR, 20, RESOURCE_ENERGY, 40);
}
}
}
}
}
}
}
}else if(!factory){ // no factory in this room - set FctrId so that it wont look again
memRoom.FctrId = '-';
Util.InfoLog('Factories', '', 'no factory in ' + gameRoomKey + ' FctrId set to -');
}
}
}
/**@return {Number}
* @return {undefined}*/
function Produce(factory, resToProduceName, resToProduceMaxAmount,
res1Name, res1MinAmount,
res2Name, res2MinAmount,
res3Name, res3MinAmount,
res4Name, res4MinAmount,
res5Name, res5MinAmount){
if( factory.store.getUsedCapacity(res1Name) >= res1MinAmount
&& factory.store.getUsedCapacity(res2Name) >= res2MinAmount
&& (!res3Name || factory.store.getUsedCapacity(res3Name) >= res3MinAmount)
&& (!res4Name || factory.store.getUsedCapacity(res4Name) >= res4MinAmount)
&& (!res5Name || factory.store.getUsedCapacity(res5Name) >= res5MinAmount)
&& (factory.store.getUsedCapacity(resToProduceName) + factory.room.storage.store.getUsedCapacity(resToProduceName) + factory.room.terminal.store.getUsedCapacity(resToProduceName)) < resToProduceMaxAmount
){ // res 1 and 2 is always required but 3 - 5 may be undefined
const result = factory.produce(resToProduceName);
Util.Info('Factories', 'Produce',
factory.pos.roomName + ' producing ' + resToProduceName + ' ' + factory.store.getUsedCapacity(resToProduceName) + ' result ' + result
+ ' ' + res1Name + ' ' + factory.store.getUsedCapacity(res1Name)
+ ' ' + res2Name + ' ' + factory.store.getUsedCapacity(res2Name)
+ (res3Name?' ' + res3Name + ' ' + factory.store.getUsedCapacity(res3Name):'')
+ (res4Name?' ' + res4Name + ' ' + factory.store.getUsedCapacity(res4Name):'')
+ (res5Name?' ' + res5Name + ' ' + factory.store.getUsedCapacity(res5Name):''));
return result;
}
}
}
};
module.exports = Factories;<file_sep>// reset
Memory.MemRooms = {};
Memory.ErrorLog = undefined;
Memory.InfoLog = undefined;
Memory.Paths = undefined;
for (const creepName in Memory.creeps) {
const gc = Game.creeps[creepName];
const mc = Memory.creeps[creepName];
if (gc === undefined) {
delete Memory.creeps[creepName];
} else {
for(const memoryElementKey in gc.memory){
gc.memory[memoryElementKey] = undefined;
}
mc.JobName = 'idle(' + gc.pos.x + ',' + gc.pos.y + ')' + gc.pos.roomName;
}
}
gc.suicide();
console.log('manual search: ' + JSON.stringify(Game.getObjectById('5cee5f96d1936f6f4667aa35')));
console.log('Game.time: ' + Game.time);
console.log(JSON.stringify(Game.powerCreeps['Hulmir']));
// terminal send
Game.getObjectById('5d60034ce360cc20d4c6deee').send(RESOURCE_BIOMASS, 260, 'E28S29');
Game.market.deal('5e00325c7072b2051bcdb880', 4000, 'E29S31');
console.log(JSON.stringify(Game.rooms['E29S31'].controller.owner));
console.log(JSON.stringify(Game.rooms['E29S28'].controller.owner));
// check all flags
for (const flagKey in Game.flags) {
const flag = Game.flags[flagKey];
console.log(flagKey + ' ' + JSON.stringify(flag));
if(flag.color === COLOR_ORANGE && flag.secondaryColor === COLOR_ORANGE){
console.log('removing flag');
flag.remove()
}
}
console.log(Game.rooms['E35S29'].controller.owner);
Game.creeps['M1'].move(LEFT)
console.log(Game.rooms['E28S29'].energyAvailable);
console.log('RESOURCE_ENERGY ' + Game.getObjectById('5cf1a7158e8ea635474264ca').store.getUsedCapacity(RESOURCE_POWER));
// destroy all structures
const structures = Game.rooms['E29S31'].find(FIND_STRUCTURES);
for(const structureKey in structures){
structures[structureKey].destroy();
}
// get something in a rooms memory
Memory.MemRooms['E31S31'].FctrId = undefined;
// test spawn transporters
Game.spawns['Spawn3'].spawnCreep([CARRY, CARRY, MOVE], 'T51');
Game.spawns['Spawn17'].spawnCreep([CARRY, CARRY, MOVE], 'T52');
Game.spawns['Spawn9'].spawnCreep([CARRY, CARRY, MOVE], 'T53');
console.log((Object.keys(Memory.MemRooms['E29S31'].MaxCreeps['T']).length - 1))
console.log(JSON.stringify(Memory.MemRooms['E29S31'].MaxCreeps['T']['M']))
// empty a terminal
const terminal = Game.getObjectById('5cf1a7158e8ea635474264ca');
for(const resourceType in terminal.store){
const amount = terminal.store[resourceType];
if(resourceType !== RESOURCE_ENERGY && amount > 1){
terminal.send(resourceType, amount - 1, 'E28S29');
}
}
const terminal = Game.getObjectById('5cf1a7158e8ea635474264ca');
terminal.send(RESOURCE_ENERGY, (terminal.store[RESOURCE_ENERGY] * 0.9), 'E28S29');
delete Memory.MemRooms['E29S29'].FctrId;<file_sep>let CreateJobs = require('CreateJobs');
let AssignJobs = require('AssignJobs');
let ExecuteJobs = require('ExecuteJobs');
let Towers = require('Towers');
let Links = require('Links');
let Terminals = require('Terminals');
let Factories = require('Factories');
let PowerSpawns = require('PowerSpawns');
let Util = require('Util');
let Observers = require('Observers');
let PowerCreeps = require('PowerCreeps');
let Labs = require('Labs');
module.exports.loop = function () {
Controller();
function Controller(){
if (!Memory.MemRooms) {
Memory.MemRooms = {};
}
if(Game.time % Util.GAME_TIME_MODULO_2 === 0){
if (Game.time % Util.GAME_TIME_MODULO_3 === 0) {
if (Game.time % Util.GAME_TIME_MODULO_4 === 0) { // tick burst from https://docs.screeps.com/cpu-limit.html#Bucket
CreateJobs.run();
Links.run();
if (Game.time % Util.GAME_TIME_MODULO_5 === 0) {
Util.Info('Main', 'Controller', '--------------- main reset of memory ---------------');
const foundCreeps = {};
for (const memRoomKey in Memory.MemRooms) {
const memRoom = Memory.MemRooms[memRoomKey];
delete memRoom.links; // remove links - maybe the buildings have been deleted ect.
delete memRoom.FctrId; // remove FctrId - maybe the buildings have been deleted ect.
delete memRoom.PowerSpawnId; // remove PowerSpawnId - maybe the buildings have been deleted ect.
delete memRoom.TowerIds; // remove TowerIds - maybe a tower have been deleted ect.
delete memRoom.ObserverId; // remove ObserverId - maybe an observer have been deleted ect.
MaxCreepsCleanup(memRoomKey, memRoom, foundCreeps);
UnusedRoomsCleanup(memRoomKey, memRoom);
}
if(Game.time % Util.GAME_TIME_MODULO_6 === 0){ // approx every 3 days
delete Memory.Paths; // remove Paths to make room for new paths
delete Memory.InfoLog;
Util.InfoLog('Main', 'Controller', 'reset memory logs ' + Game.time);
}
}
Terminals.run();
Factories.run();
}
AssignJobs.run();
}
Labs.run();
}
ExecuteJobs.run();
for (const gameRoomKey in Game.rooms) {
const gameRoom = Game.rooms[gameRoomKey];
if(gameRoom.controller && gameRoom.controller.my && Memory.MemRooms[gameRoom.name]){
Towers.run(gameRoom);
if(gameRoom.controller.level === 8){
Observers.run(gameRoom, gameRoomKey);
PowerSpawns.run(gameRoom);
}
}
}
PowerCreeps.run();
if (Game.cpu.bucket >= 9000){
//Util.Info('Main', 'Controller', 'Game.cpu.bucket ' + Game.cpu.bucket);
Game.cpu.generatePixel();
}
}
function MaxCreepsCleanup(memRoomKey, memRoom, foundCreeps){
// search through MaxCreeps to see if they all have an alive creep and that there are only one of each creep names in MaxCreeps
for (const creepTypesKey in memRoom.MaxCreeps) {
let creepOfTypeFound = false;
for (const creepKey in memRoom.MaxCreeps[creepTypesKey]) {
if (creepKey !== 'M') {
let foundCreep = false;
for (const creepName in Memory.creeps) {
if (creepName === creepKey) {
foundCreep = true;
for (const foundCreepsKey in foundCreeps) {
if (foundCreepsKey === creepKey) {
foundCreep = false;
break;
}
}
foundCreeps[creepKey] = memRoomKey;
break;
}
}
if (!foundCreep) {
Util.ErrorLog('Main', 'Main', 'Lingering MaxCreeps found and removed ' + creepKey + ' in ' + memRoomKey);
// this bug might happen when there are an error somewhere in the code that prevents the normal creep memory cleanup
memRoom.MaxCreeps[creepTypesKey][creepKey] = undefined;
}else{
creepOfTypeFound = true;
}
}else{
memRoom.MaxCreeps[creepTypesKey][creepKey] = undefined; // reset - remove M
}
}
if(!creepOfTypeFound){
memRoom.MaxCreeps[creepTypesKey] = undefined; // remove creep type altogether
}
}
return foundCreeps;
}
function UnusedRoomsCleanup(memRoomKey, memRoom){
if (memRoom.RoomLevel <= 0 && Object.keys(memRoom.RoomJobs).length === 0) {
let foundCreep = false;
for (const creepType in memRoom.MaxCreeps) {
const maxCreep = memRoom.MaxCreeps[creepType];
if (maxCreep && Object.keys(maxCreep).length > 1) { // more than 'M' is present - a creep is still attached to the room. wait until it dies
foundCreep = true;
break;
}
}
if (!foundCreep) {
// room is unowned and there are no jobs in it - remove the room
Memory.MemRooms[memRoomKey] = undefined;
Util.InfoLog('Main', 'Main', 'removed unused room ' + memRoomKey);
}
}
}
};
// TODOs:
// TODO FillStrg-container can be very expensive!
// TODO possible optimization: when a creep is looking for spawnOrExtensions nearby it might as well do the spawn replenish at that point and remove the dedicated spawn look for creeps to replenish
// TODO flag jobs may spawn in neighbor room when it could spawn in own room - look at bestLinearDistance
// attack NPC strongholds
// harvest middle rooms
// harvest neutral rooms
// move creeps in formation
// if doing long distance work creep should make sure it has enough timeToLive to do the job
// add constructions
// monitor creeps and see if they can work more quickly by optimizing its actions - remove 'pausing' ticks
<file_sep>let Util = require('Util');
const Terminals = {
run: function () {
const terminals = LoadMyTerminals();
TerminalActions(terminals);
function LoadMyTerminals() {
let terminals = [];
for (const gameRoomKey in Game.rooms) {
const gameRoom = Game.rooms[gameRoomKey];
if (gameRoom.terminal && gameRoom.terminal.my) {
terminals.push(gameRoom.terminal);
}
}
return terminals;
}
function TerminalActions(terminals){
let marketDealSendCount = 0;
for (const terminalKey in terminals) {
const terminal = terminals[terminalKey];
if (terminal.cooldown === 0) {
if(terminal.store.getUsedCapacity(RESOURCE_ENERGY) >= Util.STORAGE_ENERGY_LOW){
DistributeResources(terminal, terminals);
marketDealSendCount = SellExcessResource(terminal, marketDealSendCount);
marketDealSendCount = BuyResources(terminal, marketDealSendCount);
marketDealSendCount = BuyLabResources(terminal, marketDealSendCount);
}
}
}
}
// distribute ALL available resources to all terminals 2k each and only to 5k - except with energy 50k each and only to 100k
function DistributeResources(fromTerminal, terminals) {
for (const resourceType in fromTerminal.store) { // for each resource type
let fromAmount = fromTerminal.store[resourceType];
let target;
if(resourceType === RESOURCE_FIXTURES || resourceType === RESOURCE_TUBE){
DistributeFactoryCommodities(fromTerminal, resourceType, fromAmount, 3); // only send to factories that are of lvl 3
} else if(resourceType === RESOURCE_SWITCH || resourceType === RESOURCE_PHLEGM || resourceType === RESOURCE_COMPOSITE || resourceType === RESOURCE_CONCENTRATE) { // SWITCH, PHLEGM, COMPOSITE or CONCENTRATE should only be sent to a terminal that has a factory of level 2
DistributeFactoryCommodities(fromTerminal, resourceType, fromAmount, 2); // only send to factories that are of lvl 2
} else if(resourceType === RESOURCE_SILICON || resourceType === RESOURCE_BIOMASS || resourceType === RESOURCE_METAL || resourceType === RESOURCE_MIST) { // SILICON, BIOMASS, METAL or MIST should only be sent to a terminal that has a factory that uses SILICON, BIOMASS, METAL or MIST
DistributeFactoryCommodities(fromTerminal, resourceType, fromAmount); // send to any level factory
} else{
if (resourceType === RESOURCE_ENERGY) {
target = Util.TERMINAL_TARGET_ENERGY;
} else {
target = Util.TERMINAL_TARGET_RESOURCE;
}
for (const toTerminalKey in terminals) {
const toTerminal = terminals[toTerminalKey];
const toAmount = toTerminal.store[resourceType];
if (fromAmount > (target + 500/*buffer to prevent many small send*/)
&& toAmount < target
&& toTerminal.id !== fromTerminal.id
) { // is allowed to send this resource to another terminal
let sendAmount = fromAmount - target; // possible send amount
const resourcesNeeded = (toAmount - target) * -1;
if (sendAmount > resourcesNeeded) {
sendAmount = resourcesNeeded; // does not need more resources than this
}
const result = fromTerminal.send(resourceType, sendAmount, toTerminal.pos.roomName);
Util.Info('Terminals', 'DistributeResources', sendAmount + ' ' + resourceType + ' from ' + fromTerminal.pos.roomName + ' to ' + toTerminal.pos.roomName + ' result ' + result + ' resourcesNeeded ' + resourcesNeeded);
toTerminal.store[resourceType] += sendAmount;
fromTerminal.store[resourceType] -= sendAmount;
fromAmount -= sendAmount;
break;
}
}
}
}
}
// factory commodities are not distributed like the other resources should be
/**@return {number}*/
function DistributeFactoryCommodities(fromTerminal, resourceType, fromAmount, sendToFactoryLevel = 0) {
const fromFactory = fromTerminal.room.find(FIND_MY_STRUCTURES, {
filter: function (s) {
return s.structureType === STRUCTURE_FACTORY && (sendToFactoryLevel === s.level || sendToFactoryLevel === 0);
}
})[0];
if(!fromFactory || fromTerminal.room.storage.store.getUsedCapacity(resourceType) > Util.STORAGE_HIGH) { // only send the resource if the factory lvl in sender room is not the same as sendToFactoryLevel unless there is a surplus
for (const toTerminalKey in terminals) {
const toTerminal = terminals[toTerminalKey];
if (toTerminal.id !== fromTerminal.id
&& toTerminal.store.getUsedCapacity(resourceType) < Util.TERMINAL_TARGET_RESOURCE // do not transfer anymore commodities if toTerminal already has more than STORAGE_HIGH_TRANSFER
&& toTerminal.room.find(FIND_MY_STRUCTURES, {
filter: function (s) {
return s.structureType === STRUCTURE_FACTORY && (sendToFactoryLevel === s.level || sendToFactoryLevel === 0);
}
})[0]) {
const result = fromTerminal.send(resourceType, fromAmount, toTerminal.pos.roomName);
Util.Info('Terminals', 'DistributeResources', fromAmount + ' ' + resourceType + ' from ' + fromTerminal.pos.roomName + ' to ' + toTerminal.pos.roomName + ' result ' + result);
break;
}
}
}
}
/**@return {number}*/
function SellExcessResource(fromTerminal, marketDealSendCount) {
for (const resourceType in fromTerminal.store) { // for each resource type
let fromAmount = fromTerminal.store.getUsedCapacity(resourceType);
let max;
let lowestSellingValue = 0.1; // if the mineral has a lower selling value than this then it is not worth the computational value to mine and sell
if (resourceType === RESOURCE_ENERGY) {
max = Util.TERMINAL_MAX_ENERGY;
} else if(resourceType === RESOURCE_TISSUE || resourceType === RESOURCE_FRAME){
max = 0; // right now i am selling out on tissue and frame
} else if (resourceType === RESOURCE_POWER
|| resourceType === RESOURCE_SILICON // deposit
|| resourceType === RESOURCE_WIRE // factory lvl 0
|| resourceType === RESOURCE_SWITCH // factory lvl 1
|| resourceType === RESOURCE_BIOMASS // deposit
|| resourceType === RESOURCE_CELL // factory lvl 0
|| resourceType === RESOURCE_PHLEGM // factory lvl 1
|| resourceType === RESOURCE_METAL // deposit
|| resourceType === RESOURCE_ALLOY // factory lvl 0
|| resourceType === RESOURCE_TUBE // factory lvl 1
|| resourceType === RESOURCE_FIXTURES // factory lvl 2
|| resourceType === RESOURCE_MIST // deposit
|| resourceType === RESOURCE_CONDENSATE // factory lvl 0
|| resourceType === RESOURCE_CONCENTRATE // factory lvl 1
|| resourceType === RESOURCE_COMPOSITE // factory lvl 1
|| resourceType === RESOURCE_CRYSTAL // factory lvl 2
|| resourceType === RESOURCE_LIQUID // factory lvl 3
) { // will never sell out on these resources
max = Number.MAX_SAFE_INTEGER;
} else {
max = Util.TERMINAL_MAX_RESOURCE;
}
if (marketDealSendCount <= 10 && fromAmount > max) { // is allowed to sell this resource
const resourceHistory = Game.market.getHistory(resourceType);
const orders = Game.market.getAllOrders(order => order.resourceType === resourceType
&& order.type === ORDER_BUY
/*&& Game.market.calcTransactionCost(500, fromTerminal.pos.roomName, order.roomName) <= 500*/
&&
(
(!resourceHistory[0]
|| IsOutdated(resourceHistory[resourceHistory.length - 1].date)
|| (resourceHistory[resourceHistory.length - 1].avgPrice / 1.5/*medium price fall is okay*/) <= order.price
) && lowestSellingValue <= order.price
||
resourceType === RESOURCE_ENERGY
&& fromTerminal.room.storage
&& fromTerminal.room.storage.store[RESOURCE_ENERGY] > Util.STORAGE_ENERGY_HIGH // hard sellout because storage is full with energy
)
&& order.remainingAmount > 0
);
if (orders.length > 0) {
orders.sort(comparePriceExpensiveFirst);
const order = orders[0];
let sendAmount = fromAmount - max; // possible send amount
if (sendAmount > order.remainingAmount) {
sendAmount = order.remainingAmount; // does not need more resources than this
}
const result = Game.market.deal(order.id, sendAmount, fromTerminal.pos.roomName);
if(result === OK) {
marketDealSendCount++;
}
if(resourceType === RESOURCE_TISSUE || resourceType === RESOURCE_FIXTURES){
Util.InfoLog('Terminals', 'SellExcessResource', sendAmount + ' ' + resourceType + ' from ' + fromTerminal.pos.roomName + ' to ' + order.roomName + ' result ' + result + ' marketDealSendCount ' + marketDealSendCount + ' order.remainingAmount ' + order.remainingAmount + ' price ' + order.price + ' total price ' + order.price * sendAmount + ' fromAmount ' + fromAmount);
}else{
Util.Info('Terminals', 'SellExcessResource', sendAmount + ' ' + resourceType + ' from ' + fromTerminal.pos.roomName + ' to ' + order.roomName + ' result ' + result + ' marketDealSendCount ' + marketDealSendCount + ' order.remainingAmount ' + order.remainingAmount + ' price ' + order.price + ' total price ' + order.price * sendAmount + ' fromAmount ' + fromAmount);
}
}
}
}
return marketDealSendCount;
}
/**@return {boolean}*/
function IsOutdated(date1, date2 = Date.now(), millisecondsToWait = 86400000/*24h*/){
const elapsed = date2 - Date.parse(date1); // date1 format: "2019-06-24"
if(elapsed > millisecondsToWait){
//Util.Info('Terminals', 'IsOutdated', 'date ' + date1 + ' elapsed ' + elapsed + ' parsed date ' + Date.parse(date1) + ' now ' + date2);
return true;
}
return false;
}
/**@return {number}*/
function BuyResources(terminal, marketDealSendCount) {
// buy resources to make sure that there are at least 500 Hydrogen, Oxygen, Utrium, Keanium, Lemergium, Zynthium and Catalyst in each terminal
const basicResourceList = [RESOURCE_HYDROGEN, RESOURCE_OXYGEN, RESOURCE_UTRIUM, RESOURCE_KEANIUM, RESOURCE_LEMERGIUM, RESOURCE_ZYNTHIUM, RESOURCE_CATALYST];
for (const basicResourceKey in basicResourceList) {
const basicResource = basicResourceList[basicResourceKey];
const usedCapacity = terminal.store.getUsedCapacity(basicResource);
if (usedCapacity === 0 && marketDealSendCount <= 10 && terminal.room.storage.store.getUsedCapacity(basicResource) === 0) {
marketDealSendCount = BuyResource(terminal, basicResource, 500, marketDealSendCount);
}
}
// buy power
const usedPowerCapacity = terminal.store.getUsedCapacity(RESOURCE_POWER);
if (usedPowerCapacity === 0 && marketDealSendCount <= 10 && terminal.room.storage.store.getUsedCapacity(RESOURCE_ENERGY) > Util.STORAGE_ENERGY_LOW_TRANSFER) {
marketDealSendCount = BuyResource(terminal, RESOURCE_POWER, 1000, marketDealSendCount, 1, 2);
}
return marketDealSendCount;
}
function BuyLabResources(terminal, marketDealSendCount){
// find FillLabMineralJobs flags
const labFlags = terminal.room.find(FIND_FLAGS, {filter : function (flag){return flag.color === COLOR_PURPLE && flag.secondaryColor === COLOR_PURPLE && flag.name.split('-') === 'BUY'}});
for(const labFlagKey in labFlags){
const labFlag = labFlags[labFlagKey];
const mineral = labFlag.name.split(/[-]+/).filter(function (e) {
return e;
})[1];
const usedMineralCapacity = terminal.store.getUsedCapacity(mineral);
if (usedMineralCapacity < 500 && marketDealSendCount <= 10 && terminal.room.storage.store.getUsedCapacity(mineral) === 0) {
marketDealSendCount = BuyResource(terminal, mineral, 500 - usedMineralCapacity, marketDealSendCount, 2, 2);
}
}
return marketDealSendCount;
}
/**@return {number}*/
function BuyResource(terminal, resourceType, amount, marketDealSendCount,
avgPrice = 1.5, // set if one wants a another acceptable average price
maxPrice = undefined // set if one should use a fixed price to buy under
) {
const resourceHistory = Game.market.getHistory(resourceType);
const orders = Game.market.getAllOrders(order => order.resourceType === resourceType
&& order.type === ORDER_SELL
&& Game.market.calcTransactionCost(500, terminal.pos.roomName, order.roomName) <= 500
&& (!resourceHistory[0] || (resourceHistory[0].avgPrice * avgPrice) >= order.price && (maxPrice && maxPrice >= order.price || !maxPrice))
&& order.remainingAmount > 0
);
if (orders.length > 0) {
orders.sort(comparePriceCheapestFirst);
Util.Info('Terminals', 'BuyResource', 'WTB ' + amount + ' ' + resourceType + ' from ' + terminal + ' ' + JSON.stringify(orders) + ' avg price ' + resourceHistory[0].avgPrice);
const order = orders[0];
if(order.remainingAmount < amount){
amount = order.remainingAmount;
}
const result = Game.market.deal(order.id, amount, terminal.pos.roomName);
if(result === OK) {
marketDealSendCount++;
}
Util.InfoLog('Terminals', 'BuyResource', amount + ' ' + resourceType + ' from ' + terminal.pos.roomName + ' to ' + order.roomName + ' result ' + result + ' marketDealSendCount ' + marketDealSendCount + ' order.remainingAmount ' + order.remainingAmount + ' price ' + order.price + ' total price ' + (order.price * amount));
}
return marketDealSendCount;
}
function comparePriceCheapestFirst(a, b) {
if (a.price < b.price) {
return -1;
}
if (a.price > b.price) {
return 1;
}
return 0;
}
function comparePriceExpensiveFirst(a, b) {
if (a.price > b.price) {
return -1;
}
if (a.price < b.price) {
return 1;
}
return 0;
}
}
};
module.exports = Terminals;
|
b9587c804594ac7745afce1a960dc4107ed7d15d
|
[
"JavaScript"
] | 5
|
JavaScript
|
benjamineckstein/HScreeps
|
90fc86e9504e0fe2b9efa7cc6e39b3ffa97727c3
|
4b0b7ebd9d40ea220db66f5b834864b577db3e17
|
refs/heads/master
|
<repo_name>ririgon/KJ<file_sep>/app/src/main/java/jp/ac/bemax/sawara/ButtonFactory.java
package jp.ac.bemax.sawara;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.TypedValue;
/**
* ボタンの画像を生成するクラス
* @author horikawa
* 2014/12/16
*/
public class ButtonFactory {
// テーマから取得する値
static int baseColor;
static int mainColor;
static int accentColor;
static int buttonSize = 200;
/**
* ボタンのDrawableを返す
* @param context
* @return ボタンのDrawable
*/
public static Drawable getButtonDrawable(Context context, int resource){
// contextから色コードを取得。static変数に設定する
setThemaColors(context);
// ボタンイラストを読み込む
Drawable image = context.getResources().getDrawable(resource);
// 背景Drawableと画像を合体
Drawable[] layers = {createBackFrame(context), image};
LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setLayerInset(1, 10, 0, 0, 10);
return layerDrawable;
}
/**
* ボタンの枠画像を作成する
* @return 枠画像のDrawable
*/
public static Drawable createBackFrame(Context context){
Paint main = new Paint();
main.setColor(mainColor);
Paint base = new Paint();
base.setColor(baseColor);
Paint accent = new Paint();
accent.setColor(accentColor);
RectF rectOut = new RectF(0,buttonSize/3f, buttonSize*4/5f, buttonSize);
RectF rectIn = new RectF(5, buttonSize/3f+5, (buttonSize*4/5f)-5, buttonSize-5);
Bitmap bitmap = Bitmap.createBitmap(buttonSize, buttonSize, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawRoundRect(rectOut, 15, 15, main);
canvas.drawRoundRect(rectIn, 15, 15, base);
BitmapDrawable mb = new BitmapDrawable(context.getResources(), bitmap);
bitmap = Bitmap.createBitmap(buttonSize, buttonSize, Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawRoundRect(rectOut, 15, 15, main);
canvas.drawRoundRect(rectIn, 15, 15, accent);
BitmapDrawable ma = new BitmapDrawable(context.getResources(), bitmap);
// 状態Drawable作成
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, ma);
stateListDrawable.addState(new int[0], mb);
return stateListDrawable;
}
/**
* @param context
* @return
*/
public static Drawable getThemaBackground(Context context){
// コンテキストからテーマを取得
Resources.Theme thema = context.getTheme();
TypedValue backgroundDrawableValue = new TypedValue();
thema.resolveAttribute(R.attr.mainBack, backgroundDrawableValue, true);
Drawable backgroundDrawable = context.getResources().getDrawable(backgroundDrawableValue.resourceId);
return backgroundDrawable;
}
public static Drawable getThemaFrame(Context context){
// コンテキストからテーマを取得
Resources.Theme thema = context.getTheme();
TypedValue frameDrawableValue = new TypedValue();
thema.resolveAttribute(R.attr.frameBack, frameDrawableValue, true);
Drawable frameDrawable = context.getResources().getDrawable(frameDrawableValue.resourceId);
return frameDrawable;
}
/**
* contextのテーマに沿って、3つの色変数に値を設定する
* @param context
*/
public static void setThemaColors(Context context){
// コンテキストからテーマを取得
Resources.Theme thema = context.getTheme();
// テーマデータの受け皿
TypedValue baseColorValue = new TypedValue();
TypedValue mainColorValue = new TypedValue();
TypedValue accentColorValue = new TypedValue();
// テーマのデータを変数にセットする
thema.resolveAttribute(R.attr.baseColor, baseColorValue, true);
thema.resolveAttribute(R.attr.mainColor, mainColorValue, true);
thema.resolveAttribute(R.attr.accentColor, accentColorValue, true);
// テーマの値から、色コードを取得
baseColor = context.getResources().getColor(baseColorValue.resourceId);
mainColor = context.getResources().getColor(mainColorValue.resourceId);
accentColor = context.getResources().getColor(accentColorValue.resourceId);
}
public static void setButtonFrameSize(int size){
buttonSize = size;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/CameraEx.java
package jp.ac.bemax.sawara;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
//カメラの制御
public class CameraEx extends Activity {
//アクティビティ起動時に呼ばれる
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
//フルスクリーンの指定(1)
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new CameraView(this));
}
}<file_sep>/app/src/main/java/jp/ac/bemax/sawara/HomeActivity.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
/**
* ホーム画面のアクティビティ
* @author <NAME>
* 2014/07/02
*/
public class HomeActivity extends Activity implements OnClickListener, OnMenuItemClickListener, OnItemClickListener{
// 画面更新用のID
static final int DISPLAY_CHANGE = 0;
static final int THEMA_CHANGE = 1;
// インテント呼び出し用ID
static final int REGISTER = 100;
// 画面用のID
private final int CATEGORY_VIEW = 1;
private final int ARTICLE_VIEW = 2;
// 各VIEW用のID
private final int HOME_LAYOUT = 1;
private final int NEW_BUTTON = 2;
private final int SETTING_BUTTON = 3;
private final int RETURN_BUTTON = 4;
private final int GRID_VIEW = 5;
private final int CATEGORY_TEXT_VIEW = 6;
private final int MP = RelativeLayout.LayoutParams.MATCH_PARENT;
private Handler mHandler;
private RelativeLayout homeLayout;
private GridAdapter gridAdapter;
//private List<ListItem> listItems;
private int viewMode;
private Category thisCategory;
private SawaraDBAdapter dbAdapter;
// ディスプレイ関連のstaticな変数
static float displayDensity;
static int buttonSize;
static int gridViewColmn;
static float displayWidth;
static float displayHeight;
static int frameSize;
// 初期設定用のオブジェクト
static Configuration conf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ディスプレイサイズを取得する
WindowManager windowManager = getWindowManager();
Point displaySize = new Point();
windowManager.getDefaultDisplay().getSize(displaySize);
DisplayMetrics outMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(outMetrics);
displayDensity = outMetrics.density;
displayWidth = displaySize.x;
displayHeight = displaySize.y - 25 * displayDensity;
buttonSize = (int)(displayHeight / 5);
gridViewColmn = (int)((displayWidth - buttonSize) / (buttonSize * 2));
ButtonFactory.setButtonFrameSize(buttonSize);
// 設定ファイルを読み込む
File confFile = new File(getFilesDir(), "sawara.conf");
conf = Configuration.loadConfig(confFile);
if(conf == null){
conf = new Configuration();
conf.setTheme("DefaultTheme");
Configuration.storeConfig(confFile, conf);
}
String themeVal = conf.getTheme();
int resid = getResources().getIdentifier(themeVal, "style", getPackageName());
setTheme(resid);
// DataBaseを開く
dbAdapter = new SawaraDBAdapter(this);
SQLiteDatabase db = dbAdapter.openDb();
dbAdapter.dump(db);
db.close();
// viewMode設定
viewMode = CATEGORY_VIEW;
// アダプタにカテゴリのリストを設定する
gridAdapter = new GridAdapter(this, R.layout.list_item, new ArrayList<ListItem>());
// ViewHolderを初期化
ViewHolder holder = new ViewHolder(this);
// homeLayoutを作成 R.id.home_layout
homeLayout = new RelativeLayout(this);
homeLayout.setId(HOME_LAYOUT);
homeLayout.setTag(holder);
setContentView(homeLayout);
homeLayout.setTag(holder);
// 画面更新用のハンドラを設定する
final HomeActivity thisObj = this;
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
List<ListItem> listItems;
ViewHolder holder = (ViewHolder) homeLayout.getTag();
SQLiteDatabase db = dbAdapter.openDb();
db.beginTransaction();
try {
switch (msg.what) {
case DISPLAY_CHANGE:
// 各VIEWを初期化&配置する
switch (viewMode) {
case CATEGORY_VIEW:
// カテゴリーのリストを取得
List<Category> categories = Category.getAllCategory(db, thisObj);
listItems = new ArrayList<ListItem>();
for (Category category : categories) {
File iconFile = category.getIconFile(db);
ListItem item = new ListItem(category.getId(), category.getName(db), iconFile);
listItems.add(item);
}
gridAdapter.clear();
gridAdapter.addAll(listItems);
holder.makeCategoryModeDisplay(homeLayout);
break;
case ARTICLE_VIEW:
List<Article> articles = thisCategory.getArticles(db);
listItems = new ArrayList<ListItem>();
try {
for (Article article : articles) {
File iconFile = article.getIconFile(db);
if(iconFile != null) {
ListItem item = new ListItem(article.getId(), article.getName(db), iconFile);
listItems.add(item);
}
}
gridAdapter.clear();
gridAdapter.addAll(listItems);
}catch (Exception e){
e.printStackTrace();
}
holder.makeArticleModeDisplay(homeLayout);
holder.categoryTextView.setText(thisCategory.getName(db));
break;
}
// ウィジェットを登録
holder.gridView.setAdapter(gridAdapter);
// 各アイテムをクリックした場合のリスナを登録
holder.gridView.setOnItemClickListener(thisObj);
break;
case THEMA_CHANGE:
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(R.attr.mainBack, outValue, true);
Bitmap backBitmap = BitmapFactory.decodeResource(getResources(), outValue.resourceId);
BitmapDrawable backDrawable = new BitmapDrawable(getResources(), backBitmap);
backDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
homeLayout.setBackground(backDrawable);
holder.settingButton.setBackground(ButtonFactory.getButtonDrawable(thisObj, R.drawable.setting_button_image));
holder.newButton.setBackground(ButtonFactory.getButtonDrawable(thisObj, R.drawable.new_button_image));
holder.returnButton.setBackground(ButtonFactory.getButtonDrawable(thisObj, R.drawable.return_button_image));
int count = holder.gridView.getChildCount();
for (int i = 0; i < count; i++) {
View targetView = holder.gridView.getChildAt(i);
holder.gridView.getAdapter().getView(i, targetView, holder.gridView);
}
break;
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
db.close();
}
}
};
mHandler.sendEmptyMessage(DISPLAY_CHANGE);
mHandler.sendEmptyMessage(THEMA_CHANGE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem gorstItem = menu.add(Menu.NONE, 0,Menu.NONE, "おばけ");
MenuItem heartItem = menu.add(Menu.NONE, 1,Menu.NONE, "夏");
MenuItem starItem = menu.add(Menu.NONE, 2, Menu.NONE, "秋");
MenuItem summerItem = menu.add(Menu.NONE, 3, Menu.NONE, "星");
gorstItem.setOnMenuItemClickListener(this);
heartItem.setOnMenuItemClickListener(this);
starItem.setOnMenuItemClickListener(this);
summerItem.setOnMenuItemClickListener(this);
return true;
}
@Override
public void onClick(View v) {
Intent intent = null;
switch(v.getId()){
case NEW_BUTTON:
intent = new Intent(this, RegisterActivity.class);
intent.putExtra("mode", RegisterActivity.NEW_MODE);
switch(viewMode){
case CATEGORY_VIEW:
break;
case ARTICLE_VIEW:
intent.putExtra("category_id", thisCategory.getId());
break;
}
startActivityForResult(intent, REGISTER);
break;
case RETURN_BUTTON:
switch(viewMode){
case ARTICLE_VIEW:
viewMode = CATEGORY_VIEW;
}
mHandler.sendEmptyMessage(DISPLAY_CHANGE);
break;
case SETTING_BUTTON:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SQLiteDatabase db = dbAdapter.openDb();
dbAdapter.dump(db);
switch(requestCode){
case REGISTER:
if(resultCode == RESULT_OK){
db.beginTransaction();
try {
// TODO 更新されたアーティクルのアイコンを更新する
long article_id = data.getLongExtra("article_id", -1);
Article article = Article.getArticle(this, article_id);
article.updateIcon(db);
// TODO 更新されたアーティクルのカテゴリのアイコンを更新する
Category[] categories = article.getCategoriesThis(db);
String sql = "select article_id from category_article_table where category_id=?";
for (Category category : categories) {
String[] selectionArgs = {"" + category.getId()};
Cursor cursor = db.rawQuery(sql, selectionArgs);
int i = 0;
for (boolean next = cursor.moveToFirst(); next && i < 6; next = cursor.moveToNext(), i++) {
if (cursor.getLong(0) == article_id)
category.updateIcon(db);
}
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
}
mHandler.sendEmptyMessage(DISPLAY_CHANGE);
break;
}
db.close();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case 0:
this.setTheme(R.style.GorstTheme);
conf.setTheme("GorstTheme");
break;
case 1:
this.setTheme(R.style.SummerTheme);
conf.setTheme("SummerTheme");
break;
case 2:
this.setTheme(R.style.AutumnTheme);
conf.setTheme("AutumnTheme");
break;
case 3:
this.setTheme(R.style.StarTheme);
conf.setTheme("StarTheme");
break;
}
File confFile = new File(getFilesDir(), "sawara.conf");
Configuration.storeConfig(confFile, conf);
mHandler.sendEmptyMessage(THEMA_CHANGE);
return true;
}
/*
* GridView上のアイテムをクリックしたときに呼び出されるメソッド
* (非 Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewHolder holder = (ViewHolder) homeLayout.getTag();
SQLiteDatabase db = dbAdapter.openDb();
ListItem item;
switch(viewMode){
case CATEGORY_VIEW:
viewMode = ARTICLE_VIEW;
item = gridAdapter.getItem(position);
thisCategory = Category.getCategory(db, this, item.getId());
mHandler.sendEmptyMessage(DISPLAY_CHANGE);
break;
case ARTICLE_VIEW:
Intent intent = new Intent(this, RegisterActivity.class);
item = gridAdapter.getItem(position);
Article article = Article.getArticle(this, item.getId());
intent.putExtra("article_id", article.getId());
intent.putExtra("mode", RegisterActivity.READ_MODE);
startActivityForResult(intent, REGISTER);
break;
}
db.close();
}
class ViewHolder{
RelativeLayout homeLayout;
GridView gridView;
VTextView categoryTextView;
Button settingButton;
Button newButton;
Button returnButton;
ViewHolder(HomeActivity context){
// gridViewを作成 R.id.grid_view
gridView = new GridView(context);
gridView.setId(GRID_VIEW);
gridView.setNumColumns(gridViewColmn);
//gridView.setOnClickListener(context);
// categoryTextViewを作成 R.id.category_text_view
categoryTextView = new VTextView(context);
categoryTextView.setId(CATEGORY_TEXT_VIEW);
// settingButtonを作成 R.id.setting_button
settingButton = new Button(context);
settingButton.setId(SETTING_BUTTON);
settingButton.setBackground(ButtonFactory.getButtonDrawable(context, R.drawable.setting_button_image));
settingButton.setOnClickListener(context);
// newButtonを作成 R.id.new_button
newButton = new Button(context);
newButton.setId(NEW_BUTTON);
newButton.setBackground(ButtonFactory.getButtonDrawable(context, R.drawable.new_button_image));
newButton.setOnClickListener(context);
// returnButtonを作成 R.id.return_button
returnButton = new Button(context);
returnButton.setId(RETURN_BUTTON);
returnButton.setBackground(ButtonFactory.getButtonDrawable(context, R.drawable.return_button_image));
returnButton.setOnClickListener(context);
System.gc();
}
void makeCategoryModeDisplay(RelativeLayout layout){
layout.removeAllViews();
// LayoutParamsを用意
RelativeLayout.LayoutParams params;
// 設定ボタンのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
settingButton.setLayoutParams(params);
layout.addView(settingButton);
// 新規作成ボタンのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
newButton.setLayoutParams(params);
layout.addView(newButton);
// GridViewのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(MP, MP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ABOVE, NEW_BUTTON);
params.addRule(RelativeLayout.LEFT_OF, SETTING_BUTTON);
gridView.setLayoutParams(params);
layout.addView(gridView);
System.gc();
}
void makeArticleModeDisplay(RelativeLayout layout){
// layoutのViewをリセットする
layout.removeAllViews();
// LayoutParamsを用意
RelativeLayout.LayoutParams params;
// 設定ボタンのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
settingButton.setLayoutParams(params);
layout.addView(settingButton);
// 戻るボタンのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
returnButton.setLayoutParams(params);
layout.addView(returnButton);
// 新規作成ボタンのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.RIGHT_OF, RETURN_BUTTON);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
newButton.setLayoutParams(params);
layout.addView(newButton);
// GridViewのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(MP, MP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ABOVE, NEW_BUTTON);
params.addRule(RelativeLayout.LEFT_OF, SETTING_BUTTON);
gridView.setLayoutParams(params);
layout.addView(gridView);
// categoryTextViewのLayoutParamsを設定する
params = new RelativeLayout.LayoutParams(MP, MP);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_LEFT, SETTING_BUTTON);
params.addRule(RelativeLayout.ABOVE, SETTING_BUTTON);
categoryTextView.setLayoutParams(params);
categoryTextView.setTextSize(100);
layout.addView(categoryTextView);
System.gc();
}
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/Article.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
/**
* 言葉事典で取り扱う、1情報単位を表すクラス
* @author <NAME>
* 2014/09/05
*/
public class Article{
//static final String TABLE_NAME = "article_table";
//static final String ID = "ROWID";
static final String NAME = "name";
static final String DESCRIPTION = "description";
static final String POSITION = "position";
static final String MODIFIED = "modified";
private long rowid;
private Context context;
/**
* Article.javaコンストラクタ
*/
private Article(long id, Context context){
rowid = id;
this.context = context;
}
public static Article getArticle(Context context, long id){
return new Article(id, context);
}
public Article(SQLiteDatabase db, Context context, String name, String description){
db.beginTransaction();
try {
rowid = insert(db, name, description);
setPosition(db, rowid);
this.context = context;
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
}
/**
*
* @param db
* @param context
* @param name
* @param description
* @param categories
*/
public Article(SQLiteDatabase db, Context context, String name, String description, Category[] categories){
db.beginTransaction();
try {
rowid = insert(db, name, description);
setPosition(db, rowid);
this.context = context;
// TODO category_article_tableを更新
for(Category category: categories) {
String sql = "insert into category_article_table(category_id, article_id) values (?,?)";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindLong(1, category.getId());
statement.bindLong(2, rowid);
statement.executeInsert();
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
}
public long insert(SQLiteDatabase db, String name, String description) {
String sql = "insert into article_table(name, description, modified) values (?,?,?)";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, name);
statement.bindString(2, description);
statement.bindLong(3, System.currentTimeMillis());
long id = statement.executeInsert();
return id;
}
public long getId(){
return rowid;
}
/**
*
* @return
* @throws Exception
*/
public long getModified(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select modified from article_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
long modified = cursor.getLong(0);
return modified;
}
/**
*
* @param modified
* @throws Exception
*/
public void setModified(SQLiteDatabase db, long modified) {
SQLiteStatement statement = db.compileStatement("update article_table set modified=? where ROWID=?");
statement.bindLong(1, modified);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
*
* @param name
*/
public void setName(SQLiteDatabase db, String name) {
SQLiteStatement statement = db.compileStatement("update article_table set name=? where ROWID=?");
statement.bindString(1, name);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
*
* @param description
* @throws Exception
*/
public void setDescription(SQLiteDatabase db, String description) {
SQLiteStatement statement = db.compileStatement("update article_table set description=? where ROWID=?");
statement.bindString(1, description);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
* item_nameを返す
* @return アイテムの名前
* @throws Exception
*/
public String getName(SQLiteDatabase db){
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select name from article_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
String name = cursor.getString(0);
return name;
}
/**
* descriptionを返す
* @return アイテムの詳細
* @throws Exception
*/
public String getDescription(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select description from article_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
String description = cursor.getString(0);
return description;
}
public long getPosition(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select position from article_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
long position = cursor.getLong(0);
return position;
}
public void setPosition(SQLiteDatabase db, long position) {
SQLiteStatement statement = db.compileStatement("update article_table set position=? where ROWID=?");
statement.bindLong(1, position);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
public List<Category> createCategoriesForArticle(SQLiteDatabase db, List<Category> categories){
String sql = "insert into category_article_table(category_id, article_id) values (?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
for(Category category: categories){
statement.bindLong(1, category.getId());
statement.bindLong(2, rowid);
statement.executeInsert();
}
return categories;
}
/**
*
* @param db
*/
public void updateIcon(SQLiteDatabase db){
String icon = null;
File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
db.beginTransaction();
try {
// TODO アイコンファイル名を読みだす
String sql = "select icon from article_table where ROWID=?";
String[] selectionArgs = {"" + rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
int row = cursor.getCount();
while (cursor.moveToNext()) {
icon = cursor.getString(0);
}
cursor.close();
// TODO 画像を保存する
icon = "article_icon_" + rowid + ".png";
FileOutputStream fos = null;
try {
Bitmap iconBitmap = makeArticleIconBitmap(db);
fos = new FileOutputStream(new File(dir, icon));
if (iconBitmap == null)
throw new Exception("アイコンメディアがない");
iconBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// TODO 新規作成の場合に実行する
SQLiteStatement statement = db.compileStatement("update article_table set icon=? where ROWID=?");
statement.bindString(1, icon);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}finally {
db.endTransaction();
}
}
public String getIconFileName(SQLiteDatabase db){
String fileName = null;
String sql = "select icon from article_table where ROWID=?";
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
fileName = cursor.getString(0);
}
cursor.close();
return fileName;
}
public Bitmap getIcon(SQLiteDatabase db) {
String fileName = getIconFileName(db);
Bitmap icon = null;
if(fileName != null){
icon = BitmapFactory.decodeFile(fileName);
}
return icon;
}
public File getIconFile(SQLiteDatabase db) {
String fileName = getIconFileName(db);
File iconFile = null;
if(fileName != null){
iconFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
}
return iconFile;
}
/**
* このアーティクルに属する画像の配列を返す
* @param db
* @param context
* @return 画像の配列
*/
public Media[] getMedias(SQLiteDatabase db, Context context){
Media[] medias = null;
db.beginTransaction();
try {
String sql = "select ROWID from media_table where article_id=?";
String[] selectionArgs = {"" + rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if(cursor.getCount() > 0) {
medias = new Media[cursor.getCount()];
while (cursor.moveToNext()) {
long mediaId = cursor.getLong(0);
Media media = Media.getMedia(db, context, mediaId);
medias[cursor.getPosition()] = media;
}
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
return medias;
}
public static List<Article> getAllArticles(SQLiteDatabase db, Context context){
List<Article> articles = new ArrayList<Article>();
db.beginTransaction();
try {
String sql = "select ROWID from article_table";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
Article article = new Article(id, context);
articles.add(article);
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
return articles;
}
public void setCategory(SQLiteDatabase db, Category category){
db.beginTransaction();
try {
String sql = "select category_id from category_article_table where article_id=? and category_id=?";
String[] selectionArgs = {"" + rowid, "" + category.getId()};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if (cursor.getCount() <= 0) {
sql = "insert into category_article_table(category_id, article_id) values (?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindLong(1, category.getId());
statement.bindLong(2, rowid);
long id = statement.executeInsert();
if (id == -1) {
throw new Exception("インサートに失敗したよ");
}
}
cursor.close();
db.setTransactionSuccessful();
}catch(Exception e){
e.printStackTrace();
}finally {
db.endTransaction();
}
}
public Category[] getCategoriesThis(SQLiteDatabase db){
String sql = "select category_id from category_article_table where article_id=?";
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
Category[] categories = new Category[cursor.getCount()];
while(cursor.moveToNext()){
categories[cursor.getPosition()] = Category.getCategory(db, context, cursor.getLong(0));
}
return categories;
}
public Bitmap makeArticleIconBitmap(SQLiteDatabase db){
Bitmap icon = null;
db.beginTransaction();
try {
String sql = "select ROWID from media_table where article_id=?";
String[] selectionArgs = {"" + rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if (cursor.getCount() > 0) {
Bitmap[] mediaBitmaps = new Bitmap[cursor.getCount()];
while (cursor.moveToNext()) {
mediaBitmaps[cursor.getPosition()] = Media.getMedia(null, context, cursor.getLong(0)).getIconBitmap(db);
}
icon = IconFactory.makeSixMatrixIcon(context, mediaBitmaps);
}
cursor.close();
db.setTransactionSuccessful();
}catch (Exception e){
e.printStackTrace();
}finally {
db.endTransaction();
}
return icon;
}
public List<ImageItem> getImageItems(SQLiteDatabase db, Context context){
List<ImageItem> iconList = new ArrayList<ImageItem>();
db.beginTransaction();
try {
String sql = "select ROWID, icon from media_table where article_id=?";
String[] selectionArgs = {"" + rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long mediaId = cursor.getLong(0);
String icon = cursor.getString(1);
File iconFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), icon);
ImageItem item = new ImageItem(mediaId, iconFile);
iconList.add(item);
}
}
db.setTransactionSuccessful();
}catch (Exception e){
e.printStackTrace();
}finally {
db.endTransaction();
}
return iconList;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/Configuration.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 初期設定を管理するクラス
* @author horikawa
*
*/
public class Configuration implements Serializable{
private String theme; // テーマ
public Configuration(){
theme = "";
}
/**
* @return theme
*/
public String getTheme() {
return theme;
}
/**
* @param theme セットする theme
*/
public void setTheme(String theme) {
this.theme = theme;
}
/**
* ファイルから、Configurationオブジェクトを取得する
* @param confFile 保存先のファイル
* @return Configurationオブジェクト
*/
static Configuration loadConfig(File confFile){
Configuration conf;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(confFile));
conf = (Configuration)ois.readObject();
} catch (Exception e) {
conf = null;
}
return conf;
}
/**
* ファイルに、Configurationオブジェクトを保存する
* @param confFile 保存先のファイル
* @param conf Configurationオブジェクト
* @return 保存に成功したらtrue
*/
static boolean storeConfig(File confFile, Configuration conf){
boolean result;
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(confFile));
oos.writeObject(conf);
result = true;
} catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/SplashActivity.java
package jp.ac.bemax.sawara;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.AlphaAnimation;
/**
* Created by Katuya on 2015/09/08.
*/
public class SplashActivity extends Activity {
Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// スプラッシュ用のビューを取得する
setContentView(R.layout.splash);
splashAnimation();
// 2秒したらMainActivityを呼び出してSplashActivityを終了する
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// MainActivityを呼び出す
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
// SplashActivityを終了する
SplashActivity.this.finish();
}
}, 5 * 1000); // 5000ミリ秒後(5秒後)に実行
}
private void splashAnimation(){
AlphaAnimation alphaanime = new AlphaAnimation(1, 0);
alphaanime.setStartOffset(2000);
alphaanime.setDuration(1000);
alphaanime.setFillAfter(true);
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/RegisterActivity.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.os.Bundle;
/**
* @author horikawa
*
*/
public class RegisterActivity extends Activity implements OnClickListener, OnItemClickListener{
// ** 各種定数の設定 **
// 画面モードの定数
static final int MODE_NOTHING = 0; // 画面モードの指定が無い → エラー
static final int NEW_MODE = 1; // 新規登録モード
static final int UPDATE_MODE = 2; // 更新モード
static final int READ_MODE = 3; // 閲覧モード
// ボタン用ID
static final int RETURN_BUTTON = 101; // 戻るボタン
static final int ALBAM_BUTTON = 102; // アルバムボタン
static final int MOVIE_BUTTON = 103; // 動画ボタン
static final int PHOTO_BUTTON = 104; // 写真ボタン
static final int REGIST_BUTTON = 105; // 決定ボタン
static final int UPDATE_BUTTON = 106; // 更新ボタン
static final int DELETE_BUTTON = 107; // 削除ボタン
// 画像アイテムの識別用
static final int PICTURE = 201; // 写真
static final int MOVIE = 202; // 動画
// 暗黙インテント呼び出し用
static final int IMAGE_CAPTUER = 301; // 画像キャプチャ
static final int MOVIE_CAPTUER = 302; // 動画撮影
static final int STRAGE_READ = 303; // アルバム呼び出し
// 動画撮影の最大時間(秒)
private final int MOVIE_MAX_TIME = 20; // 最大20秒撮影
private final int MOVIE_QUALITY = 0; // 動画のクオリティ(低)
private final int MP = RelativeLayout.LayoutParams.MATCH_PARENT;
// ** インスタンス変数の宣言 **
// ハンドラ
private Handler mHandler;
// View
private RelativeLayout registerLayout; // レイアウト
// 画像一覧用のアダプタ
private ImageAdapter imageViewerAdapter;
// 画像一覧用の変数
//private List<Media> mMediaList;
// タグ一覧用のアダプタ
private ArrayAdapter<VTextView> tagViewerAdapter;
// 写真、動画の保存先ファイル
private File mediaFile;
// 現在のカテゴリ(新規登録時に使用)
private Category thisCategory;
private Category[] thisArticleCategories;
private Article thisArticle;
private SawaraDBAdapter dbAdapter;
// ディスプレイ関連のstaticな変数
static float displayDensity;
static int buttonSize;
static int gridViewColmn;
static float displayWidth;
static float displayHeight;
static int frameSize;
// 初期設定用のオブジェクト
static Configuration conf;
private int mode;
private Bundle bundle = new Bundle();
/* (非 Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ディスプレイサイズを取得する
WindowManager windowManager = getWindowManager();
Point displaySize = new Point();
windowManager.getDefaultDisplay().getSize(displaySize);
DisplayMetrics outMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(outMetrics);
displayDensity = outMetrics.density;
displayWidth = displaySize.x;
displayHeight = displaySize.y - 25 * displayDensity;
buttonSize = (int)(displayHeight / 5);
gridViewColmn = (int)((displayWidth - buttonSize) / (buttonSize * 2));
// DBとのコネクション
dbAdapter = new SawaraDBAdapter(this);
setContentView(R.layout.register);
// ** アクティビティにテーマを設定する **
File confFile = new File(getFilesDir(), "sawara.conf");
conf = Configuration.loadConfig(confFile);
if(conf == null){
conf = new Configuration();
conf.setTheme("DefaultTheme");
Configuration.storeConfig(confFile, conf);
}
String themeVal = conf.getTheme();
int resid = getResources().getIdentifier(themeVal, "style", getPackageName());
setTheme(resid);
// ** インテントの処理 **
// インテントを取得する
Intent intent = getIntent();
mode = intent.getIntExtra("mode", 0); // モード設定が無い場合は、0
// ** ビューア用の初期設定 **
// イメージビューア用のアダプタ設定
imageViewerAdapter = new ImageAdapter(this);
//** Viewの設定 **
// レイアウト
registerLayout = (RelativeLayout)findViewById(R.id.register_layout);
// テーマから背景画像を設定
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(R.attr.mainBack, outValue, true);
Bitmap backBitmap = BitmapFactory.decodeResource(getResources(), outValue.resourceId);
BitmapDrawable backDrawable = new BitmapDrawable(getResources(), backBitmap);
backDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
registerLayout.setBackground(backDrawable);
// ** 各Viewの設定 **
ViewHolder holder = new ViewHolder();
RelativeLayout.LayoutParams params;
// 名前テキスト
holder.nameTextView = (VTextView)findViewById(R.id.register_name);
holder.nameTextView.setBackGround();
holder.nameTextView.setTextSize(100);
// 詳細テキスト
holder.discriptionTextView = (VTextView)findViewById(R.id.register_description);
holder.discriptionTextView.setBackGround();
holder.discriptionTextView.setTextSize(80);
// アルバムボタン作成
holder.albamButton = new Button(this);
holder.albamButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.album_image));
holder.albamButton.setId(ALBAM_BUTTON);
holder.albamButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.LEFT_OF, R.id.register_description);
params.setMargins(5, 5, 5, 5);
holder.albamButton.setLayoutParams(params);
// 動画ボタン作成
holder.movieButton = new Button(this);
holder.movieButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.movie_image));
holder.movieButton.setId(MOVIE_BUTTON);
holder.movieButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.LEFT_OF, ALBAM_BUTTON);
params.setMargins(5, 5, 5, 5);
holder.movieButton.setLayoutParams(params);
// 写真ボタン作成
holder.photoButton = new Button(this);
holder.photoButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.camera_image));
holder.photoButton.setId(PHOTO_BUTTON);
holder.photoButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.LEFT_OF, MOVIE_BUTTON);
params.setMargins(5, 5, 5, 5);
holder.photoButton.setLayoutParams(params);
// 決定ボタン
holder.registButton = new Button(this);
holder.registButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.regist_button_image));
holder.registButton.setId(REGIST_BUTTON);
holder.registButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(5, 5, 5, 5);
holder.registButton.setLayoutParams(params);
// 戻るボタン
holder.returnButton = new Button(this);
holder.returnButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.return_button_image));
holder.returnButton.setId(RETURN_BUTTON);
holder.returnButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.setMargins(5, 5, 5, 5);
holder.returnButton.setLayoutParams(params);
// 更新ボタン
holder.updateButton = new Button(this);
holder.updateButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.update_button_image));
holder.updateButton.setId(UPDATE_BUTTON);
holder.updateButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.LEFT_OF, R.id.register_description);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.setMargins(5, 5, 5, 5);
holder.updateButton.setLayoutParams(params);
// 削除ボタン
holder.deleteButton = new Button(this);
holder.deleteButton.setBackground(ButtonFactory.getButtonDrawable(this, R.drawable.delete_button_image));
holder.deleteButton.setId(DELETE_BUTTON);
holder.deleteButton.setOnClickListener(this);
params = new RelativeLayout.LayoutParams(buttonSize, buttonSize);
params.addRule(RelativeLayout.LEFT_OF, UPDATE_BUTTON);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.setMargins(5, 5, 5, 5);
holder.deleteButton.setLayoutParams(params);
// タグビューア
holder.tagViewerView = (GridView)findViewById(R.id.register_tag_viewer);
params = new RelativeLayout.LayoutParams(300, MP);
//params.addRule(RelativeLayout.ABOVE, REGIST_BUTTON);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.setMargins(5, 5, 5, 5);
holder.tagViewerView.setLayoutParams(params);
// 画像ビューア
holder.imageViewerView = (GridView)findViewById(R.id.register_image_viewer);
holder.imageViewerView.setAdapter(imageViewerAdapter);
params = new RelativeLayout.LayoutParams(MP, (int)(buttonSize*4));
//params.addRule(RelativeLayout.ABOVE, ALBAM_BUTTON);
params.addRule(RelativeLayout.LEFT_OF, R.id.register_description);
params.addRule(RelativeLayout.RIGHT_OF, R.id.register_tag_viewer);
params.setMargins(5, 5, 5, 5);
holder.imageViewerView.setLayoutParams(params);
registerLayout.setTag(holder);
final RegisterActivity thisObj = this;
mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
//Article article;
ViewHolder holder = (ViewHolder) registerLayout.getTag();
registerLayout.removeAllViews();
// ** Viewの配置 **
registerLayout.addView(holder.nameTextView);
registerLayout.addView(holder.discriptionTextView);
// タグビューア
registerLayout.addView(holder.tagViewerView);
// 画像ビューア
registerLayout.addView(holder.imageViewerView);
// LayoutParamsの宣言
RelativeLayout.LayoutParams params;
// DBアクセススタート
SQLiteDatabase db = dbAdapter.openDb();
// モードごとに配置する
switch (msg.what) {
case NEW_MODE: // == 新規登録モード ==
Toast.makeText(thisObj, "NEW_MODE", Toast.LENGTH_SHORT).show();
// ** インテントからカテゴリ情報を取得 **
long categoryId = getIntent().getLongExtra("category_id", -1);
thisCategory = Category.getCategory(db, thisObj, categoryId);
thisArticleCategories = new Category[]{thisCategory};
// ** ボタン配置 **
// アルバムボタン
registerLayout.addView(holder.albamButton);
// 動画ボタン
registerLayout.addView(holder.movieButton);
// 写真ボタン
registerLayout.addView(holder.photoButton);
// 決定ボタン
registerLayout.addView(holder.registButton);
// ** リスナー登録 **
// 名前テキスト
holder.nameTextView.setOnClickListener(thisObj);
holder.nameTextView.setFocusableInTouchMode(true);
// 詳細テキスト
holder.discriptionTextView.setOnClickListener(thisObj);
holder.discriptionTextView.setFocusableInTouchMode(true);
break;
case UPDATE_MODE: // == 更新モード ==
Toast.makeText(thisObj, "UPDATE_MODE", Toast.LENGTH_SHORT).show();
// ** Articleを取得 **
thisArticleCategories =thisArticle.getCategoriesThis(db);
holder.nameTextView.setText(thisArticle.getName(db));
holder.discriptionTextView.setText(thisArticle.getDescription(db));
// ImageViewerの初期化
imageViewerAdapter.clear();
imageViewerAdapter.addAll(thisArticle.getImageItems(db, thisObj));
// ** ボタン配置 **
// アルバムボタン
registerLayout.addView(holder.albamButton);
// 動画ボタン
registerLayout.addView(holder.movieButton);
// 写真ボタン
registerLayout.addView(holder.photoButton);
// 決定ボタン
registerLayout.addView(holder.registButton);
// ** リスナー登録 **
// 名前テキスト
holder.nameTextView.setOnClickListener(thisObj);
holder.nameTextView.setFocusableInTouchMode(true);
// 詳細テキスト
holder.discriptionTextView.setOnClickListener(thisObj);
holder.discriptionTextView.setFocusableInTouchMode(true);
// リスナを解除する
holder.imageViewerView.setOnItemClickListener(null);
break;
case READ_MODE: // == 閲覧モード ==
Toast.makeText(thisObj, "READ_MODE", Toast.LENGTH_SHORT).show();
// ** Articleを取得 **
long articleId = getIntent().getLongExtra("article_id", -1);
thisArticle = Article.getArticle(thisObj, articleId);
thisArticleCategories =thisArticle.getCategoriesThis(db);
holder.nameTextView.setText(thisArticle.getName(db));
holder.discriptionTextView.setText(thisArticle.getDescription(db));
// ImageViewerの初期化
imageViewerAdapter.clear();
imageViewerAdapter.addAll(thisArticle.getImageItems(db, thisObj));
// ** Viewの設置 **
// 戻るボタン
registerLayout.addView(holder.returnButton);
// 更新ボタン
registerLayout.addView(holder.updateButton);
// 削除ボタン
registerLayout.addView(holder.deleteButton);
// リスナ登録
holder.imageViewerView.setOnItemClickListener(thisObj);
// リスナ解除
holder.nameTextView.setOnClickListener(null);
holder.discriptionTextView.setOnClickListener(null);
break;
}
// DBを閉じる
db.close();
}
};
mHandler.sendEmptyMessage(mode);
}
/* (非 Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// ** ローカル変数の初期化 **
Intent intent = new Intent(); // インテント
File dir = null; // 保存先ファイル
ViewHolder holder = (ViewHolder) registerLayout.getTag();
switch(v.getId()){
case ALBAM_BUTTON: // == アルバム読み込みモード ==
// 結果を呼び出しもとActivityに返す
// Activityを終了
finish();
break;
case PHOTO_BUTTON: // == 写真撮影モード ==
// ** 保存先を作成 **
String fileName = "" + System.currentTimeMillis() + ".jpg";
mediaFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
Uri imageUri = Uri.fromFile(mediaFile);
CameraEx Camera = new CameraEx();
Camera.onCreate(bundle);
//p461
//このcase分をベースにしてビューをサンプルに作る。
// // ** 写真撮影用の暗黙インテントを呼び出す準備 **
// intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// intent.addCategory(Intent.CATEGORY_DEFAULT);
//
// // インテントを呼び出す
// startActivityForResult(intent, IMAGE_CAPTUER);
break;
case MOVIE_BUTTON: // == 動画撮影モード ==
// ** 保存先を作成 **
fileName = "" + System.currentTimeMillis() + ".mp4";
mediaFile = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES), fileName);
Uri movieUri = Uri.fromFile(mediaFile);
// ** 動画撮影用の暗黙院展とを呼び出す準備 **
intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, movieUri);
// 動画のクオリティを設定
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, MOVIE_QUALITY);
// 動画の最大撮影時間を設定
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, MOVIE_MAX_TIME);
// インテントを呼び出す
startActivityForResult(intent, MOVIE_CAPTUER);
break;
//*** 入力データを登録する ***
case REGIST_BUTTON:
// 基本値をセットする
String name = holder.nameTextView.getText().toString();
String description = holder.discriptionTextView.getText().toString();
SQLiteDatabase db = dbAdapter.openDb();
boolean success = false;
if(mode == NEW_MODE) {
// 新しいArticleを作成する
db.beginTransaction();
try {
if(name.length() == 0 || description.length() == 0)
throw new Exception("名前または説明がありません");
thisArticle = new Article(db, this, name, description);
//新しいMediaを登録する
List<ImageItem> items = imageViewerAdapter.getImageItems();
if(items.size() == 0)
throw new Exception("画像がありません");
Media[] medias = new Media[items.size()];
for(int i=0; i<medias.length; i++){
medias[i] = Media.getMedia(db, this, items.get(i).getId());
medias[i].setArticleId(db, thisArticle.getId());
}
//TODO カテゴリーアーティクルテーブルを更新する
for(Category category: thisArticleCategories){
thisArticle.setCategory(db, category);
}
db.setTransactionSuccessful();
success = true;
}catch(Exception e){
e.printStackTrace();
// TODO エラー画面を表示する
}finally {
db.endTransaction();
}
}else if(mode == UPDATE_MODE){
// Articleを更新する
db.beginTransaction();
try {
if(name.length() == 0 || description.length() == 0)
throw new Exception("名前または説明がありません");
thisArticle.setName(db, name);
thisArticle.setDescription(db, description);
thisArticle.setModified(db, System.currentTimeMillis());
List<ImageItem> items = imageViewerAdapter.getImageItems();
if(items.size() == 0)
throw new Exception("画像がありません");
// メディアを更新する
Media[] medias = new Media[items.size()];
for (int i = 0; i < medias.length; i++) {
medias[i] = Media.getMedia(db, this, items.get(i).getId());
if (medias[i].getArticleId(db) <= 0) {
medias[i].setArticleId(db, thisArticle.getId());
}
}
//TODO カテゴリーアーティクルテーブルを更新する
for(Category category: thisArticleCategories){
thisArticle.setCategory(db, category);
}
db.setTransactionSuccessful();
success = true;
}catch (Exception e){
e.printStackTrace();
}finally {
db.endTransaction();
}
}
// 成功
if(success){
intent.putExtra("article_id", thisArticle.getId());
setResult(RESULT_OK, intent);
}else{
setResult(RESULT_CANCELED, intent);
}
db.close();
finish();
break;
case RETURN_BUTTON:
finish();
break;
case UPDATE_BUTTON:
mHandler.sendEmptyMessage(UPDATE_MODE);
mode = UPDATE_MODE;
break;
}
}
/*
*
* (非 Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// インテントからの返信が成功した場合
if(resultCode == RESULT_OK){
SQLiteDatabase db = dbAdapter.openDb();
db.beginTransaction();
try {
switch (requestCode) {
//*** 写真を撮影した場合 ***
case IMAGE_CAPTUER:
Bitmap itemIcon;
try {
Media newMedia = new Media(db, this, mediaFile.getName(), Media.PHOTO);
File iconFile = newMedia.getIconFile(db);
ImageItem item = new ImageItem(newMedia.getId(), iconFile);
// ビューアに反映する
imageViewerAdapter.add(item);
imageViewerAdapter.notifyDataSetChanged();
}catch(Exception e){
e.printStackTrace();
}
break;
//*** 動画を撮影した場合 ***
case MOVIE_CAPTUER:
try {
Media newMedia = new Media(db, this, mediaFile.getName(), Media.MOVIE);
File iconFile = newMedia.getIconFile(db);
ImageItem item = new ImageItem(newMedia.getId(), iconFile);
imageViewerAdapter.add(item);
imageViewerAdapter.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
itemIcon = IconFactory.getNullImage();
}
break;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
}
/*
* viewerアイテムがクリックされたときに呼び出される
* (非 Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SQLiteDatabase db = dbAdapter.openDb();
db.beginTransaction();
try {
switch (parent.getId()) {
case R.id.register_image_viewer:
ImageItem item = imageViewerAdapter.getItem(position);
if (item.getId() != -1) {
Media media = Media.getMedia(db, this, item.getId());
long type = media.getType(db);
File mediaFile = media.getMediaFile(db);
Uri uri = Uri.fromFile(mediaFile);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
if (type == Media.PHOTO) {
intent.setDataAndType(uri, "image/*");
} else {
intent.setDataAndType(uri, "video/*");
}
startActivity(intent);
}
break;
case R.id.register_tag_viewer:
break;
}
db.setTransactionSuccessful();
}catch (Exception e){
}finally {
db.endTransaction();
db.close();
}
}
/*
void putNewModeButtons(){
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(200,200);
}
*/
private int[] getImageTypes(int photo, int movie){
int[] types = new int[photo + movie];
for(int i=0; i<types.length; i++){
if(i < photo){
types[i] = PICTURE;
}else{
types[i] = MOVIE;
}
}
return types;
}
private String[] getImagePaths(String[] photo, String[] movie){
String[] paths = new String[photo.length + movie.length];
for(int i=0; i<paths.length; i++){
if(i<photo.length){
paths[i] = photo[i];
}else{
paths[i] = movie[i-photo.length];
}
}
return paths;
}
class ViewHolder{
VTextView nameTextView;
VTextView discriptionTextView;
Button updateButton;
Button deleteButton;
Button registButton;
Button albamButton;
Button returnButton;
Button photoButton;
Button movieButton;
GridView imageViewerView;
GridView tagViewerView;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/Media.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
/**
* 写真および動画を扱うテーブル
*
*/
public class Media {
static final long PHOTO = 1;
static final long MOVIE = 2;
private long rowid;
private Context context;
/**
* IDを指定して、メディアを作成する。
* データベース上にメディアがあることを確かめ、あればメディアオブジェクトを返す。なければnull
* @param db データベース もしnullの場合は、データベース上にあることを確かめない
* @param context コンテキスト
* @param id ID
*/
public static Media getMedia(SQLiteDatabase db, Context context, long id){
Media media = null;
if(db != null) {
String sql = "select ROWID from media_table where ROWID=?";
String[] selectionArgs = {"" + id};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if (cursor.getCount() > 0) {
media = new Media(context, id);
}
}else{
media = new Media(context, id);
}
return media;
}
/**
* コンストラクタ
* @param context
* @param id
*/
private Media(Context context, long id){
this.context = context;
this.rowid = id;
}
private File getDir(long mediaType){
if(mediaType == Media.PHOTO){
return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
}else if(mediaType == Media.MOVIE){
return context.getExternalFilesDir(Environment.DIRECTORY_MOVIES);
}else{
return null;
}
}
/**
* 画像ファイル名とタイプ(画像、動画)を指定して、メディアを作る。
* DBへのインサートあり。
* @param db データベース
* @param context コンテキスト
* @param fileName 画像ファイル名
* @param mediaType 画像のタイプ
* @throws Exception 適当な例外を投げます
*/
public Media(SQLiteDatabase db, Context context, String fileName, long mediaType) throws Exception{
this.context = context;
db.beginTransaction();
try {
// メディアテーブルにデータを登録
String sql = "insert into media_table(file_name, type, modified) values (?,?,?)";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, fileName);
statement.bindLong(2, mediaType);
statement.bindLong(3, System.currentTimeMillis());
long id = statement.executeInsert();
rowid = id;
// アイコン画像を作成する
File iconFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "media_icon_"+rowid+".png");
File mediaFile = new File(getDir(mediaType), fileName);
Bitmap icon = IconFactory.makeNormalIcon(IconFactory.loadBitmapFromFileAndType(mediaFile, mediaType));
IconFactory.storeBitmapToFile(iconFile, icon);
sql = "update media_table set icon=? where ROWID=?";
statement = db.compileStatement(sql);
statement.bindString(1, iconFile.getName());
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("メディアを作成できませんでしたよ。");
} finally {
db.endTransaction();
}
}
public Media(SQLiteDatabase db, Context context, String fileName, long mediaType, Article article) throws Exception{
this(db, context, fileName, mediaType);
setArticleId(db, article.getId());
}
private String getFileName(SQLiteDatabase db){
String fileName = null;
String sql = "select file_name from media_table where ROWID=?";
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
if(cursor.getCount() > 0){
cursor.moveToFirst();
fileName = cursor.getString(0);
}
cursor.close();
return fileName;
}
/**
* データベースのデータから、画像ファイルを取得する
* @param db データベース
* @return メディアの画像ファイル
* @throws Exception 適当な例外を投げます
*/
public File getMediaFile(SQLiteDatabase db) {
String fileName = getFileName(db);
File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if(getType(db) == Media.MOVIE){
dir = context.getExternalFilesDir(Environment.DIRECTORY_MOVIES);
}
return new File(dir, fileName);
}
/**
* このメディアに関連するカテゴリを返す
* @param db データベース
* @return このメディアが関連するカテゴリの配列
*/
public Category[] getCategoriesRelationThisMedia(SQLiteDatabase db){
String sql = "select category_id from category_media_view where media_id=?";
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
Category[] categories = new Category[cursor.getCount()];
while(cursor.moveToNext()){
categories[cursor.getPosition()] = Category.getCategory(null, context, cursor.getLong(0));
}
return categories;
}
/**
* 画像のファイル名を、DBから取得する
* @param db データベース
* @return 取得した画像ファイルの絶対パス
* @throws Exception 適当な例外を投げる
*/
public String getMediaFilePath(SQLiteDatabase db) throws Exception {
return getMediaFile(db).getPath();
}
public Bitmap getIconBitmap(SQLiteDatabase db) {
Bitmap icon = null;
try {
File mediaFile = getMediaFile(db);
Bitmap bitmap = IconFactory.loadBitmapFromFileAndType(mediaFile, getType(db));
icon = IconFactory.makeNormalIcon(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return icon;
}
/**
* @param path セットする path
*/
public void setMediaFileName(SQLiteDatabase db, String path) {
SQLiteStatement statement = db.compileStatement("update media_table set file_name=? where ROWID=?");
statement.bindString(1, path);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
public File getIconFile(SQLiteDatabase db){
File iconFile = null;
String sql = "select icon from media_table where ROWID=?";
String[] selectionArgs ={""+rowid};
Cursor cursor = db.rawQuery(sql, selectionArgs);
while(cursor.moveToNext()){
iconFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), cursor.getString(0));
}
cursor.close();
return iconFile;
}
/**
* @return type
*/
public long getType(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select type from media_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
Long type = cursor.getLong(0);
cursor.close();
return type;
}
/**
* @param type セットする type
*/
public void setType(SQLiteDatabase db, int type) {
SQLiteStatement statement = db.compileStatement("update media_table set type=? where ROWID=?");
statement.bindLong(1, type);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
* @return modified
*/
public long getModified(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select modified from media_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
Long modified = cursor.getLong(0);
cursor.close();
return modified;
}
/**
* @param modified セットする modified
*/
public void setModified(SQLiteDatabase db, long modified) {
SQLiteStatement statement = db.compileStatement("update media_table set medified=? where ROWID=?");
statement.bindLong(1, modified);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
* @return modified
*/
public long getArticleId(SQLiteDatabase db) {
String[] selectionArgs = {""+rowid};
Cursor cursor = db.rawQuery("select article_id from media_table where ROWID=?", selectionArgs);
cursor.moveToFirst();
Long articleId = cursor.getLong(0);
cursor.close();
return articleId;
}
/**
* @param articleId セットする articleId
*/
public void setArticleId(SQLiteDatabase db, long articleId) {
SQLiteStatement statement = db.compileStatement("update media_table set article_id=? where ROWID=?");
statement.bindLong(1, articleId);
statement.bindLong(2, rowid);
statement.executeUpdateDelete();
}
/**
* @return id
*/
public long getId() {
return rowid;
}
/*
public static List<Media> getMedias(SQLiteDatabase db, Context context, List<ImageItem> items, Article article) throws Exception {
List<Media> medias = new ArrayList<Media>();
for(ImageItem item: items){
if(item.getId() == -1){
Media media = new Media(db, context, item.getFileName(), item.getType(), article);
medias.add(media);
}
}
return medias;
}
*/
public String dump(SQLiteDatabase db) throws Exception {
String str = "";
str += "ROWID:" + rowid;
str += "|PATH:"+ getMediaFilePath(db);
str += "|TYPE:" + getType(db);
str += "|ARTICLE_ID:" + getArticleId(db);
str += "|MODIFIED:" + getModified(db);
str += "|";
return str;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/CameraView.java
package jp.ac.bemax.sawara;
import android.content.Context;
import android.hardware.Camera;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.FileOutputStream;
//カメラの制御
public class CameraView extends SurfaceView
implements SurfaceHolder.Callback,Camera.PictureCallback {
private SurfaceHolder holder;//ホルダー
private Camera camera;//カメラ
//コンストラクタ
public CameraView(Context context) {
super(context);
//サーフェイスホルダーの生成
holder=getHolder();
holder.addCallback(this);
//プッシュバッッファの指定(2)
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
//サーフェイス生成イベントの処理
public void surfaceCreated(SurfaceHolder holder) {
//カメラの初期化(3)
try {
camera=Camera.open();
camera.setPreviewDisplay(holder);
} catch (Exception e) {
}
}
//サーフェイス変更イベントの処理
public void surfaceChanged(SurfaceHolder holder,int format,int w,int h) {
//カメラプレビューの開始(4)
camera.startPreview();
}
//サーフェイス解放イベントの処理
public void surfaceDestroyed(SurfaceHolder holder) {
//カメラのプレビュー停止(5)
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera=null;
}
//タッチ時に呼ばれる
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
//カメラのスクリーンショットの取得(6)
camera.takePicture(null,null,this);
}
return true;
}
//写真撮影完了時に呼ばれる
public void onPictureTaken(byte[] data,Camera camera) {
//SDカードへのデータ保存(7)
try {
String path=Environment.getExternalStorageDirectory()+
"/test.jpg";
data2file(data,path);
} catch (Exception e) {
}
//プレビュー再開
camera.startPreview();
}
//バイトデータ→ファイル
private void data2file(byte[] w,String fileName)
throws Exception {
FileOutputStream out=null;
try {
out=new FileOutputStream(fileName);
out.write(w);
out.close();
} catch (Exception e) {
if (out!=null) out.close();
throw e;
}
}
}<file_sep>/app/src/main/java/jp/ac/bemax/sawara/ImageAdapter.java
package jp.ac.bemax.sawara;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* 画像リストのためのアダプタ
* @author <NAME>
* 2014/11/22
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Resources.Theme theme;
private List<ImageItem> mList;
private int backDrawable;
private final int LMP = LinearLayout.LayoutParams.MATCH_PARENT;
private final int AMP = AbsListView.LayoutParams.MATCH_PARENT;
/**
* ImageAdapter.javaコンストラクタ
* @param context
*/
public ImageAdapter(Context context){
mContext = context;
this.theme = context.getTheme();
TypedValue outValue = new TypedValue();
theme.resolveAttribute(R.attr.frameBack, outValue, true);
backDrawable = outValue.resourceId;
mList = new ArrayList<ImageItem>();
}
/**
* アダプタに画像を追加する
* @param item
*/
public void add(ImageItem item){
mList.add(item);
}
public void addAll(List<ImageItem> items){
for(ImageItem item: items){
add(item);
}
}
public void setTheme(Resources.Theme theme){
this.theme = theme;
TypedValue outValue = new TypedValue();
theme.resolveAttribute(R.attr.frameBack, outValue, true);
backDrawable = outValue.resourceId;
}
/**
* アダプタのアイテム数を返す
*/
@Override
public int getCount() {
return mList.size();
}
/**
* 指定ポジションのアイテムを返す
* @param position アイテムのポジション
*/
@Override
public ImageItem getItem(int position) {
return mList.get(position);
}
/**
* アイテムのIDを返す(実際は何もしない)
*/
@Override
public long getItemId(int position) {
return 0;
}
/**
* GridViewに表示するViewを返す。
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
holder.imageView = new ImageView(mContext);
holder.imageView.setBackgroundResource(backDrawable);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LMP, LMP);
params.setMargins(10,10,10,10);
holder.imageView.setLayoutParams(params);
LinearLayout linearLayout = new LinearLayout(mContext);
linearLayout.addView(holder.imageView);
convertView = linearLayout;
AbsListView.LayoutParams absParams = new AbsListView.LayoutParams(AMP, AMP);
convertView.setLayoutParams(absParams);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
Bitmap image = BitmapFactory.decodeFile(mList.get(position).getFile().getPath());
holder.imageView.setImageBitmap(image);
return convertView;
}
public void clear(){
mList = new ArrayList<ImageItem>();
}
public List<ImageItem> getImageItems(){
return mList;
}
class ViewHolder{
ImageView imageView;
}
}
<file_sep>/app/src/main/java/jp/ac/bemax/sawara/VTextView.java
package jp.ac.bemax.sawara;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;
/**
* 縦書きのテキストView
* @author <NAME>
* 2014/09/30
*/
public class VTextView extends EditText{
private static final int TOP_SPACE = 20;
private static final int BOTTOM_SPACE = 20;
private static final int FONT_SIZE = 50;
//Androidで用意されているTypefaceクラスを使うための宣言(フォント等の設定が行える)
private Typeface mFace;
private Paint mPaint;
private String mText = "";
private int width;
private int height;
private Editable mEditable;
private Context mContext;
public VTextView(Context context){
super(context);
init(context);
}
public VTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context){
mContext = context;
mFace = Typeface.createFromAsset(context.getAssets(),"HGRKK.TTC");
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(FONT_SIZE);
mPaint.setColor(Color.BLACK);
mPaint.setTypeface(mFace);
mEditable = super.getEditableText();
setFocusable(false);
setFocusableInTouchMode(false);
}
public void setBackGround(){
Theme theme = mContext.getTheme();
TypedValue frameColorValue = new TypedValue();
theme.resolveAttribute(R.attr.mainColor, frameColorValue, true);
GradientDrawable drawable = new GradientDrawable();
drawable.setStroke(5, mContext.getResources().getColor(frameColorValue.resourceId));
drawable.setColor(Color.WHITE);
drawable.setCornerRadius(10);
this.setBackground(drawable);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w;
height = h;
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* テキストサイズつき、setText
*/
public void setText(String text, int size){
mPaint.setTextSize(size);
setText(text);
}
/**
* テキストサイズをセットする
* @param size
*/
public void setTextSize(int size){
mPaint.setTextSize(size);
}
/**
*
*/
@Override
public void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
}
/**
* 描画
*/
@Override
public void onDraw(Canvas canvas) {
float fontSpacing = mPaint.getFontSpacing();
float lineSpacing = fontSpacing * 1.5f;
float x = width - lineSpacing;
float y = TOP_SPACE + fontSpacing * 1.0f;
if(getText().length() > 0){
mText = getText().toString();
}else{
if(getHint() != null)
mText = getHint().toString();
}
// 改行キーで切り分ける
String[]ss = mText.split("\r\n|[\n\r\u2028\u2029\u0085]", 0);
for(int j=0; j<ss.length; j++){
boolean newLine = false;
String[] s = ss[j].split("");
for (int i = 1; i <= s.length-1; i++) {
newLine = false;
CharSetting setting = CharSetting.getSetting(s[i]);
if (setting == null) {
// 文字設定がない場合、そのまま描画
canvas.drawText(s[i], x, y, mPaint);
} else {
// 文字設定が見つかったので、設定に従い描画
canvas.save();
canvas.rotate(setting.angle, x, y);
canvas.drawText(s[i], x + fontSpacing * setting.x, y + fontSpacing * setting.y, mPaint);
canvas.restore();
}
if (y + fontSpacing > height - BOTTOM_SPACE) {
// もう文字が入らない場合
newLine = true;
} else {
// まだ文字が入る場合
newLine = false;
}
if (newLine) {
// 改行処理
x -= lineSpacing;
y = TOP_SPACE + fontSpacing;
} else {
// 文字を送る
y += fontSpacing;
}
}
x -= lineSpacing;
y = TOP_SPACE + fontSpacing * 1.0f;
}
}
/**
* インプットコネクション(必要ないかも)
*/
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection ic = super.onCreateInputConnection(outAttrs);
return ic; //new TextInputConnection(this, false);
}
/**
* インナークラス
* キー入力を受け付けるコネクター
* @author <NAME>
* 2014/11/19
*/
class TextInputConnection extends BaseInputConnection{
public TextInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
@Override
public Editable getEditable() {
return new SpannableStringBuilder("");
}
@Override
public boolean setComposingText(CharSequence text, int newCursorPosition) {
boolean ret = super.setComposingText(text, newCursorPosition);
mText = mEditable.toString() + text;
//editing = true;
invalidate();
Log.d("編集中"+newCursorPosition, mEditable.toString());
return ret;
}
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
boolean ret = super.commitText(text, newCursorPosition);
mEditable.append(text);
//mText = mEditable.toString();
//editing = false;
invalidate();
Log.d("確定済み"+newCursorPosition, mText.toString());
return ret;
}
}
}
|
5bd8336b7fa333a639076a4d58b7770535ed6f30
|
[
"Java"
] | 11
|
Java
|
ririgon/KJ
|
6d821d8cf34b1d10ae4ae45e8c09cff708f3a935
|
6e45eac510b8f1f581c44716b3b2ad48a5045916
|
refs/heads/master
|
<repo_name>LeCodeBae/eccommerce<file_sep>/server/helpers/passport.js
const User = require('../models/user.js');
const userControl = require('../controllers/userController.js');
const passport = require('passport');
const bcrypt = require('bcrypt');
// let isPasswordValid = (user, password) => {
// return bcrypt.compareSync(password, user.password);
// }
let passportAuth = (username, password, next) => {
let findUser = User.findOne({username: username}, (err, user) => {
if (err || user === null) {
next(null, false, {message: 'username is not found'});
} else {
bcrypt.compare(password, user.password, (err, res) => {
if (err) {
next(err);
} else {
if (res) {
next(null, user);
} else {
next(null, false, {message: 'password is incorrect'});
}
}
});
}
});
}
module.exports = passportAuth;<file_sep>/server/models/handphone.js
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var handphoneSchema = new Schema({
img: String,
brand: String,
price: String,
description: String,
rating: Number,
quantity: Number
});
module.exports = mongoose.model('Handphone', handphoneSchema);<file_sep>/server/routes/users.js
var express = require('express');
var router = express.Router();
var controller = require('../controllers/userController');
const passport = require('passport');
/* GET users listing. */
router.get('/', controller.findUsers);
router.post('/register', controller.addUser);
router.post('/', passport.authenticate('local', { session: false }), controller.createToken)
module.exports = router;
<file_sep>/server/controllers/userController.js
var User = require('../models/user');
const bcrypt = require('bcrypt');
const passport = require('passport');
const jwt = require('jsonwebtoken');
findUsers = (req, res) => {
User.find({}).then((users)=>{
res.send(users)
})
}
addUser = (req, res) => {
var user = new User({
username: req.body.username,
password: <PASSWORD>.hashSync(req.body.password,10)
})
user.save(function (err, user){
if (err) res.send(err)
res.send(user);
})
}
createToken = (req,res) =>{
let user = req.user
User.findOne({username: user.username}).then((user)=>{
let newToken = jwt.sign({
username: user.username
},'secret',{ expiresIn: '1h' })
res.send(newToken)
})
}
module.exports = {addUser, findUsers, createToken};<file_sep>/server/routes/handphones.js
const express = require('express');
var router = express.Router();
var controller = require('../controllers/handphoneController');
var jwtHelper = require('../helpers/jwt')
router.get('/',jwtHelper.jwtAuthenticate,controller.findHandphones);
router.post('/',controller.addHandphone);
router.delete('/',controller.deleteHandphone);
router.put('/',controller.updateHandphone);
module.exports = router;
|
8b00848ac41fa2377a3f2408c88549e5de20ba10
|
[
"JavaScript"
] | 5
|
JavaScript
|
LeCodeBae/eccommerce
|
68cf548fba0f00d4e13b831d3e14dcb45c2a09c8
|
524fda53594e38de188ccf218e9cad11467653fa
|
refs/heads/master
|
<repo_name>JianboTian/CppExamples<file_sep>/ComputerSales_oo/include/Exit.h
#ifndef EXIT_H
#define EXIT_H
#include <iostream>
using namespace std;
#include "MenuItem.h"
class Exit:public MenuItem
{
public:
Exit()
{
this->caption = "退出程序";
}
void act()
{
cout << "退出程序!" << endl;
}
bool isExit()
{
return true;
}
protected:
private:
};
#endif // EXIT_H
<file_sep>/ComputerSales_oo/src/ListWareHouse.cpp
#include "ListWareHouse.h"
#include "ComputerSales.h"
extern ComputerSales cs;
ListWareHouse::ListWareHouse()
{
this->caption = "查看库存";
}
void ListWareHouse::act(){
cs.getWareHouse().list();
}
<file_sep>/ComputerSales_oo/include/Menu.h
#ifndef MENU_H
#define MENU_H
#include <vector>
#include <string>
using namespace std;
#include "MenuItem.h"
class Menu
{
public:
Menu();
void append(MenuItem* mi);
void run();
protected:
private:
void show();
vector<MenuItem*> items;
};
#endif // MENU_H
<file_sep>/ComputerSales_oo/include/OutWareHouse.h
#ifndef OUTWAREHOUSE_H
#define OUTWAREHOUSE_H
#include "MenuItem.h"
class OutWareHouse:public MenuItem
{
public:
OutWareHouse(){
this->caption = "售出";
};
void act(){};
protected:
private:
};
#endif // OUTWAREHOUSE_H
<file_sep>/ComputerSales_oo/src/OutWareHouse.cpp
#include "OutWareHouse.h"
<file_sep>/ComputerSales_oo/include/WareHouse.h
#ifndef WAREHOUSE_H
#define WAREHOUSE_H
#include <vector>
using namespace std;
#include "Computer.h"
class WareHouse
{
public:
WareHouse();
void list();
protected:
private:
vector<Computer> computers;
};
#endif // WAREHOUSE_H
<file_sep>/ComputerSales_oo/src/Computer.cpp
#include "Computer.h"
Computer::Computer()
{
//ctor
}
<file_sep>/ComputerSales_oo/include/ComputerSales.h
#ifndef COMPUTERSALES_H
#define COMPUTERSALES_H
#include "wareHouse.h"
#include "Menu.h"
class ComputerSales
{
public:
ComputerSales();
void run();
WareHouse getWareHouse(){
return wareHouse;
}
protected:
private:
Menu menu;
WareHouse wareHouse;
};
#endif // COMPUTERSALES_H
<file_sep>/ComputerSales_oo/main.cpp
#include "ComputerSales.h"
ComputerSales cs;
int main()
{
cs.run();
return 0;
}
<file_sep>/ComputerSales_oo/include/MenuItem.h
#ifndef MENUITEM_H
#define MENUITEM_H
#include <string>
using namespace std;
class MenuItem
{
public:
string getCaption(){
return caption;
}
virtual bool isExit()
{
return false;
};
virtual void act() = 0;
protected:
string caption;
};
#endif // MENUITEM_H
<file_sep>/ComputerSales_oo/include/Computer.h
#ifndef COMPUTER_H
#define COMPUTER_H
#include <string>
using namespace std;
class Computer
{
public:
Computer();
string getModel(){
return this->model;
}
int getTotal(){
return this->total;
}
protected:
private:
string model;
int total;
};
#endif // COMPUTER_H
<file_sep>/ComputerSales_oo/src/WareHouse.cpp
#include "WareHouse.h"
#include <iostream>
using namespace std;
WareHouse::WareHouse()
{
//ctor
}
void WareHouse::list()
{
cout<<"-------库存-------"<<endl;
cout<<"型号\t"<<"数量"<<endl;
for(int i=0; i<computers.size(); i++)
{
cout<<computers[i].getModel()<<"\t"<<computers[i].getTotal()<<endl;
}
cout<<"-------库存-------"<<endl;
}
<file_sep>/ComputerSales_oo/include/ListWareHouse.h
#ifndef LISTWAREHOUSE_H
#define LISTWAREHOUSE_H
#include "MenuItem.h"
class ListWareHouse:public MenuItem
{
public:
ListWareHouse();
void act();
protected:
private:
};
#endif // LISTWAREHOUSE_H
<file_sep>/ComputerSales_oo/include/EnterWareHouse.h
#ifndef ENTERWAREHOUSE_H
#define ENTERWAREHOUSE_H
#include "MenuItem.h"
class EnterWareHouse:public MenuItem
{
public:
EnterWareHouse(){
this->caption="电脑入库";
}
virtual void act(){};
protected:
private:
};
#endif // ENTERWAREHOUSE_H
<file_sep>/ComputerSales_oo/src/Menu.cpp
#include "Menu.h"
#include <iostream>
using namespace std;
Menu::Menu()
{
//ctor
}
void Menu::append(MenuItem* mi)
{
items.push_back(mi);
}
void Menu::run()
{
int index;
MenuItem* selected;
while(1)
{
this->show();
cin>>index;
if(index<1 || index>4)
{
cout << "错误的菜单项,请重新输入:"<<endl;
continue;
}
selected = items[index-1];
if(selected->isExit()) break;
selected->act();
}
}
void Menu::show()
{
for(int i=0; i<items.size(); i++)
{
cout<< i+1 <<")" <<items[i]->getCaption() <<endl;
}
}
<file_sep>/ComputerSales_oo/src/EnterWareHouse.cpp
#include "EnterWareHouse.h"
|
3879f12def008bc0e77f220b706337b627fafc2f
|
[
"C++"
] | 16
|
C++
|
JianboTian/CppExamples
|
b5daffa2aa3f6b3f0c8a0e97a2bc5fc2fddb8d52
|
496944433435d293048fe6467137d115fcde2383
|
refs/heads/master
|
<file_sep>export * from './core/Interfaces';
export { Validator } from './core/Validator';
export * from './validation/ConstraintValidationFunctions';
export * from './validation/ValidationConstraints';
export * from './validation/ValidationFunctions';
export { Log } from './util/Log';
export { IntentValidator } from './validation/validators/IntentValidator';
export { MetaDataValidator } from './validation/validators/MetaDataValidator';
export { ResourceValidator } from './validation/validators/ResourceValidator';
export { SlotTypeValidator } from './validation/validators/SlotTypeValidator';
export { BaseError } from './errors/BaseError';
export { runValidation, LexModelValidator } from './LexModelValidator';
<file_sep>import {
Constraints,
Intent,
KeyValuePair,
Slot,
VALIDATION_CONSTRAINTS_INTENT,
VALIDATION_CONSTRAINTS_SLOT,
ValidationFunction,
Validator
} from '../..';
export class IntentValidator extends Validator {
getConstraints(): Constraints {
return {
'resource.intents': {
isArray: true,
validate: this.validateIntents
}
};
}
validateIntents: ValidationFunction<Intent[]> = (
validationPair: KeyValuePair
) => {
const intents = validationPair.value;
if (intents && intents.length > 0) {
intents.forEach((intent: Intent, intentIndex: number) => {
this.validate(
intent,
VALIDATION_CONSTRAINTS_INTENT,
validationPair.key + `[${intentIndex}]`
);
if (intent.slots && intent.slots.length > 0) {
intent.slots.forEach((slot: Slot, slotIndex: number) => {
this.validate(
slot,
VALIDATION_CONSTRAINTS_SLOT,
validationPair.key + `[${intentIndex}].slots[${slotIndex}]`
);
});
}
});
}
};
}
<file_sep>import {Constraint, CONSTRAINT_VALIDATION_FUNCTION_MAP, KeyValuePair, LexModelValidator, ValidationFunction, Validator} from '../src';
class TestValidator extends Validator {
getConstraints(): Record<string, Constraint> {
return {};
}
}
describe('test constraint validation functions', () => {
const constraintValidationFunctionMap = CONSTRAINT_VALIDATION_FUNCTION_MAP;
const validator = new LexModelValidator([TestValidator]);
const testValidator = validator.validator<TestValidator>('TestValidator')!;
const expectNoErrors = () => {
expect(validator.collectedErrors).toHaveLength(0);
};
const expectErrors = (amount?: number) => {
if (amount) {
expect(validator.collectedErrors).toHaveLength(amount);
} else {
expect(validator.collectedErrors).not.toHaveLength(0);
}
};
const fooBarPair: KeyValuePair<string> = {
key: 'foo',
value: 'bar',
};
beforeEach(() => {
validator.collectedErrors = [];
});
describe('test required', () => {
const {required} = constraintValidationFunctionMap;
test('test required enabled succeeds', () => {
required.call(testValidator, true, fooBarPair);
expectNoErrors();
});
test('test required enabled fails', () => {
required.call(testValidator, true, {key: 'foo', value: undefined});
expectErrors(1);
});
test('test required disabled undefined succeeds', () => {
required.call(testValidator, false, {key: 'foo', value: undefined});
expectNoErrors();
});
});
describe('test validate', () => {
const {validate} = constraintValidationFunctionMap;
// tslint:disable-next-line
const validationFunction: ValidationFunction<string> = function (validationPair: KeyValuePair) {
if (validationPair.value !== 'bar') {
this.pushError(`test error`);
}
};
test('test validate succeeds', () => {
validate.call(testValidator, validationFunction, fooBarPair);
expectNoErrors();
});
test('test validate fails', () => {
validate.call(testValidator, validationFunction, {key: 'foo', value: undefined});
expectErrors(1);
});
});
describe('test minLength', () => {
const {minLength} = constraintValidationFunctionMap;
test('test minLength succeeds', () => {
minLength.call(testValidator, 1, fooBarPair);
expectNoErrors();
});
test('test minLength fails', () => {
minLength.call(testValidator, 4, fooBarPair);
expectErrors(1);
});
});
describe('test maxLength', () => {
const {maxLength} = constraintValidationFunctionMap;
test('test maxLength succeeds', () => {
maxLength.call(testValidator, 10, fooBarPair);
expectNoErrors();
});
test('test maxLength fails', () => {
maxLength.call(testValidator, 2, fooBarPair);
expectErrors(1);
});
});
describe('test type', () => {
const {type} = constraintValidationFunctionMap;
test('test maxLength succeeds', () => {
type.call(testValidator, 'string', fooBarPair);
expectNoErrors();
});
test('test maxLength fails', () => {
type.call(testValidator, 'number', fooBarPair);
expectErrors(1);
});
});
describe('test isArray', () => {
const {isArray} = constraintValidationFunctionMap;
test('test isArray succeeds', () => {
isArray.call(testValidator, true, {key: 'foo', value: ['bar']});
expectNoErrors();
});
test('test isArray fails', () => {
isArray.call(testValidator, true, fooBarPair);
expectErrors(1);
});
});
describe('test min', () => {
const {min} = constraintValidationFunctionMap;
test('test min succeeds', () => {
min.call(testValidator, 3, {key: 'foo', value: 10});
expectNoErrors();
});
test('test min fails', () => {
min.call(testValidator, 3, {key: 'foo', value: 2});
expectErrors(1);
});
});
describe('test max', () => {
const {max} = constraintValidationFunctionMap;
test('test max succeeds', () => {
max.call(testValidator, 10, {key: 'foo', value: 10});
expectNoErrors();
});
test('test max fails', () => {
max.call(testValidator, 10, {key: 'foo', value: 11});
expectErrors(1);
});
});
describe('test equals', () => {
const {equals} = constraintValidationFunctionMap;
test('test equals succeeds', () => {
equals.call(testValidator, 'bar', fooBarPair);
expectNoErrors();
});
test('test equals fails', () => {
equals.call(testValidator, 'foo', fooBarPair);
expectErrors(1);
});
});
describe('test matches', () => {
const {matches} = constraintValidationFunctionMap;
test('test matches regexp succeeds', () => {
matches.call(testValidator, RegExp('bar', 'g'), fooBarPair);
expectNoErrors();
});
test('test matches regexp fails', () => {
matches.call(testValidator, RegExp('foo', 'g'), fooBarPair);
expectErrors(1);
});
test('test matches array succeeds', () => {
matches.call(testValidator, ['abc', 'bar'], fooBarPair);
expectNoErrors();
});
test('test matches array fails', () => {
matches.call(testValidator, ['abc', 'foo'], fooBarPair);
expectErrors(1);
});
});
});
<file_sep>import * as workingExample from '../json/working_example.json';
import {BaseError, LexModelValidator} from '../src';
const validator = new LexModelValidator();
describe('test LexModelValidator', () => {
test('test validateJson succeeds', () => {
expect<BaseError[]>(validator.validateJson(workingExample)).toHaveLength(0);
});
test('test validateJson fails', () => {
expect<BaseError[]>(validator.validateJson({})).not.toHaveLength(0);
});
});
<file_sep>import * as workingExample from '../json/working_example.json';
import {BaseError, IntentValidator, LexModelValidator, MetaDataValidator, ResourceValidator, SlotTypeValidator} from '../src';
describe('test validators', () => {
describe('test MetaDataValidator', () => {
const validator = new LexModelValidator([MetaDataValidator]);
test('test MetaDataValidator succeeds', () => {
expect<BaseError[]>(validator.validateJson(workingExample)).toHaveLength(0);
});
test('test MetaDataValidator fails', () => {
expect<BaseError[]>(validator.validateJson({})).not.toHaveLength(0);
});
});
describe('test ResourceValidator', () => {
const validator = new LexModelValidator([ResourceValidator]);
test('test ResourceValidator succeeds', () => {
expect<BaseError[]>(validator.validateJson(workingExample)).toHaveLength(0);
});
test('test ResourceValidator fails', () => {
expect<BaseError[]>(validator.validateJson({})).not.toHaveLength(0);
});
});
describe('test IntentValidator', () => {
const validator = new LexModelValidator([IntentValidator]);
test('test IntentValidator succeeds', () => {
expect<BaseError[]>(validator.validateJson(workingExample)).toHaveLength(0);
});
test('test IntentValidator fails', () => {
expect<BaseError[]>(validator.validateJson({})).not.toHaveLength(0);
});
});
describe('test SlotTypeValidator', () => {
const validator = new LexModelValidator([SlotTypeValidator]);
test('test SlotTypeValidator succeeds', () => {
expect<BaseError[]>(validator.validateJson(workingExample)).toHaveLength(0);
});
test('test SlotTypeValidator fails', () => {
expect<BaseError[]>(validator.validateJson({})).not.toHaveLength(0);
});
});
});
<file_sep>import { Constraints, Validator } from '../..';
export class MetaDataValidator extends Validator {
getConstraints(): Constraints {
return {
metadata: {
type: 'object'
},
'metadata.schemaVersion': {
minLength: 2,
type: 'string'
},
'metadata.importType': {
equals: 'LEX'
},
'metadata.importFormat': {
equals: 'JSON'
}
};
}
}
<file_sep>import {
BaseError,
InputModel,
IntentValidator,
Log,
MetaDataValidator,
ResourceValidator,
SlotTypeValidator,
Validator,
ValidatorConstructor
} from './';
export const runValidation = (json: InputModel, validator: Validator) => {
validator.run(json);
if (validator.childrenCount > 0) {
validator.runChildren(json);
}
};
export class LexModelValidator {
collectedErrors: BaseError[];
private readonly $validators: Validator[];
constructor(
validatorConstructors: ValidatorConstructor[] = [
MetaDataValidator,
ResourceValidator,
IntentValidator,
SlotTypeValidator
]
) {
this.collectedErrors = [];
this.$validators = [];
this.use(...validatorConstructors);
}
use(...validatorConstructors: ValidatorConstructor[]) {
this.addValidators(...validatorConstructors);
}
validator<T extends Validator = any>(name: string): T | undefined {
return this.$validators.find((validator: Validator) => {
return validator.name === name;
}) as T | undefined;
}
validateJson(json: InputModel): BaseError[] {
return this.validate(json);
}
private validate(json: InputModel): BaseError[] {
this.collectedErrors = [];
this.$validators.forEach(runValidation.bind(this, json));
let output = '';
this.collectedErrors.forEach((error: BaseError) => {
output += error.message + '\n';
});
if (output === '') {
Log.success(
'The given model should have no errors and there should be no problems while importing in Amazon Lex.'
);
} else {
Log.warning(output);
}
return this.collectedErrors;
}
private addValidator(validatorConstructor: ValidatorConstructor) {
if (
!this.$validators.some((validator: Validator) => {
return validator.name === validatorConstructor.name;
})
) {
this.$validators.push(new validatorConstructor(this));
}
}
private addValidators(...validatorConstructors: ValidatorConstructor[]) {
validatorConstructors.forEach((constructor: ValidatorConstructor) => {
this.addValidator(constructor);
});
}
}
<file_sep>import get from 'lodash.get';
import {
BaseError,
Constraint,
CONSTRAINT_VALIDATION_FUNCTION_MAP,
Constraints,
InputModel,
KeyValuePair,
LexModelValidator,
runValidation,
ValidatorConstructor,
ValidatorInterface
} from '..';
export abstract class Validator implements ValidatorInterface {
protected readonly $children: Validator[];
constructor(
protected readonly $master: LexModelValidator,
protected readonly $parent?: Validator
) {
this.$children = [];
}
get name(): string {
return this.constructor.name;
}
get childrenCount(): number {
return this.$children.length;
}
use(...validatorConstructors: ValidatorConstructor[]) {
validatorConstructors.forEach((constructor: ValidatorConstructor) => {
if (
!this.$children.some((validator: Validator) => {
return validator.name === constructor.name;
})
) {
this.$children.push(new constructor(this.$master, this.$parent));
}
});
}
abstract getConstraints(): Constraints;
run(data: InputModel) {
this.validate(data, this.getConstraints());
}
runChildren(data: InputModel) {
this.$children.forEach(runValidation.bind(this, data));
}
pushError(error: string | BaseError) {
if (typeof error === 'string') {
this.$master.collectedErrors.push(new BaseError(error));
} else {
this.$master.collectedErrors.push(error);
}
}
validate(data: InputModel, constraints: Constraints, prefix?: string) {
const pathsToObjectsToBeValidated = Object.keys(constraints);
for (const path of pathsToObjectsToBeValidated) {
const constraint: Constraint = constraints[path];
if (typeof constraint.required === 'undefined') {
constraint.required = true;
}
const objectToBeValidated = get(data, path);
const constraintProps = this.getSortedConstraintProperties(constraint);
for (const constraintProp of constraintProps) {
this.callValidation(
{
key: constraintProp,
value: constraint[constraintProp as keyof Constraint]
},
{
key: prefix ? `${prefix}.${path}` : path,
value: objectToBeValidated
}
);
}
}
}
private getSortedConstraintProperties(constraint: Constraint): string[] {
return Object.keys(constraint).sort((a: string, b: string) => {
if (a === 'required') {
return -1;
} else if (b === 'required') {
return 1;
} else {
return 0;
}
});
}
private callValidation(
constraintPair: KeyValuePair,
validationPair: KeyValuePair
) {
CONSTRAINT_VALIDATION_FUNCTION_MAP[
constraintPair.key as keyof Constraint
].call(this, constraintPair.value!, validationPair);
}
}
<file_sep>import {
Constraints,
LexModelValidator,
VALIDATION_FUNCTION_STATEMENT_MESSAGES,
Validator
} from '../..';
export class ResourceValidator extends Validator {
constructor(
protected readonly $master: LexModelValidator,
protected readonly $parent?: Validator
) {
super($master, $parent);
}
getConstraints(): Constraints {
return {
resource: {
type: 'object'
},
'resource.name': {
type: 'string',
minLength: 2
},
'resource.version': {
type: 'string',
minLength: 1
},
'resource.locale': {
type: 'string',
minLength: 2
},
'resource.childDirected': {
type: 'boolean'
},
'resource.idleSessionTTLInSeconds': {
type: 'number',
min: 0
},
'resource.clarificationPrompt': {
type: 'object'
},
'resource.clarificationPrompt.messages': {
isArray: true,
minLength: 1,
validate: VALIDATION_FUNCTION_STATEMENT_MESSAGES
},
'resource.clarificationPrompt.maxAttempts': {
type: 'number',
min: 1
},
'resource.abortStatement': {
type: 'object'
},
'resource.abortStatement.messages': {
isArray: true,
minLength: 1,
validate: VALIDATION_FUNCTION_STATEMENT_MESSAGES
}
};
}
}
<file_sep>import {BaseError, Constraint, LexModelValidator, VALIDATION_FUNCTION_CHECK_DUPLICATES, VALIDATION_FUNCTION_STATEMENT_MESSAGES, Validator} from '../src';
class TestStatementMessagesValidator extends Validator {
getConstraints(): Record<string, Constraint> {
return {
messages: {
validate: VALIDATION_FUNCTION_STATEMENT_MESSAGES,
},
};
}
}
// tslint:disable-next-line
class TestCheckDoublesValidator extends Validator {
getConstraints(): Record<string, Constraint> {
return {
stringValues: {
validate: VALIDATION_FUNCTION_CHECK_DUPLICATES,
},
};
}
}
describe('test validation functions', () => {
describe('test statementMessage', () => {
const validator = new LexModelValidator([TestStatementMessagesValidator]);
test('test statementMessages succeeds', () => {
const json = {
messages: [
{contentType: 'test', content: 'testing'},
],
};
expect<BaseError[]>(validator.validateJson(json)).toHaveLength(0);
});
test('test statementMessages fails', () => {
const json = {
messages: [
{contentType: '', content: 'testing'},
{},
{contentType: 'dasdas', content: ''},
],
};
expect<BaseError[]>(validator.validateJson(json)).not.toHaveLength(0);
});
});
describe('test checkDuplicates', () => {
const validator = new LexModelValidator([TestCheckDoublesValidator]);
test('test checkDuplicates succeeds', () => {
const json = {
stringValues: [
'hello',
'test',
'should work',
],
};
expect<BaseError[]>(validator.validateJson(json)).toHaveLength(0);
});
test('test checkDuplicates fails', () => {
const json = {
stringValues: [
'hello',
'test',
'should',
'not work',
'hello',
],
};
expect<BaseError[]>(validator.validateJson(json)).not.toHaveLength(0);
});
});
});
<file_sep>import { Constraints } from '..';
import {
VALIDATION_FUNCTION_CHECK_DUPLICATES,
VALIDATION_FUNCTION_STATEMENT_MESSAGES
} from './ValidationFunctions';
export const VALIDATION_CONSTRAINTS_SLOT: Constraints = {
name: {
type: 'string',
minLength: 2
},
priority: {
type: 'number',
min: 0
},
slotType: {
type: 'string',
minLength: 2
},
slotTypeVersion: {
required: false,
type: 'string',
minLength: 1
},
slotConstraint: {
matches: ['Required', 'Optional']
},
sampleUtterances: {
isArray: true,
validate: VALIDATION_FUNCTION_CHECK_DUPLICATES
},
valueElicitationPrompt: {
type: 'object'
},
'valueElicitationPrompt.messages': {
isArray: true,
minLength: 1,
validate: VALIDATION_FUNCTION_STATEMENT_MESSAGES
},
'valueElicitationPrompt.maxAttempts': {
type: 'number',
min: 1
}
};
export const VALIDATION_CONSTRAINTS_INTENT: Constraints = {
name: {
type: 'string',
minLength: 2
},
version: {
type: 'string',
minLength: 1
},
fulfillmentActivity: {
type: 'object'
},
'fulfillmentActivity.type': {
type: 'string',
minLength: 1
},
sampleUtterances: {
isArray: true,
minLength: 0,
validate: VALIDATION_FUNCTION_CHECK_DUPLICATES
},
slots: {
isArray: true
}
};
export const VALIDATION_CONSTRAINTS_SLOT_TYPE: Constraints = {
name: {
type: 'string',
minLength: 2
},
version: {
type: 'string',
minLength: 1
},
enumerationValues: {
isArray: true
},
valueSelectionStrategy: {
type: 'string',
minLength: 1
}
};
export const VALIDATION_CONSTRAINTS_ENUMERATION_VALUE: Constraints = {
value: {
type: 'string',
minLength: 1
},
synonyms: {
isArray: true,
validate: VALIDATION_FUNCTION_CHECK_DUPLICATES
}
};
export const VALIDATION_CONSTRAINTS_STATEMENT_MESSAGE: Constraints = {
contentType: {
type: 'string',
minLength: 2
},
content: {
type: 'string',
minLength: 1
}
};
<file_sep>import { AllowedType, Constraint, KeyValuePair, Validator } from '..';
export type ConstraintValidationFunction<T = any> = (
this: Validator,
constraintValue: T,
validationPair: KeyValuePair
) => void;
export type ValidationFunction<T = {}> = (
this: Validator,
validationPair: KeyValuePair<T | undefined>
) => void;
export type ConstraintValidationFunctionMap = Record<
keyof Constraint,
ConstraintValidationFunction
>;
// tslint:disable-next-line
const required: ConstraintValidationFunction<boolean> = function(
constraintValue: boolean,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if ((constraintValue && typeof value === 'undefined') || value === null) {
this.pushError(`'${key}' is required but 'undefined'`);
}
};
// tslint:disable-next-line
const validate: ConstraintValidationFunction<ValidationFunction> = function(
constraintValue: ValidationFunction,
validationPair: KeyValuePair
) {
constraintValue.call(this, validationPair);
};
// tslint:disable-next-line
const minLength: ConstraintValidationFunction<number> = function(
constraintValue: number,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (
Array.isArray(value) ||
typeof value === 'string' ||
typeof value === 'number'
) {
const length =
typeof value === 'number' ? String(value).length : value.length;
if (length < constraintValue) {
this.pushError(
`'${key}' has to be at least ${constraintValue} characters long but it's length is ${length}`
);
}
} else {
// this.pushError(`'${key}' is not a type that can have a minimum length`);
}
};
// tslint:disable-next-line
const maxLength: ConstraintValidationFunction<number> = function(
constraintValue: number,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (
Array.isArray(value) ||
typeof value === 'string' ||
typeof value === 'number'
) {
const length =
typeof value === 'number' ? String(value).length : value.length;
if (length > constraintValue) {
this.pushError(
`'${key}' has to be lower than or equal to ${constraintValue} characters long but it's length is ${length}`
);
}
} else {
// this.pushError(`'${key}' is not a type that can have a maximum length`);
}
};
// tslint:disable-next-line
const type: ConstraintValidationFunction<AllowedType> = function(
constraintValue: AllowedType,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
const valueType = typeof value;
if (value && valueType !== constraintValue) {
this.pushError(
`'${key}' is supposed to be of type '${constraintValue}' but is type '${valueType}'`
);
}
};
// tslint:disable-next-line
const isArray: ConstraintValidationFunction<boolean> = function(
constraintValue: boolean,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (value && constraintValue !== Array.isArray(value)) {
this.pushError(
`'${key}' is ${
constraintValue
? `supposed to be an array but is not`
: `not supposed to be an array but is`
}`
);
}
};
// tslint:disable-next-line
const min: ConstraintValidationFunction<number> = function(
constraintValue: number,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (typeof value === 'number' || typeof value === 'string') {
const numberValue = typeof value === 'string' ? +value : value;
if (numberValue < constraintValue) {
this.pushError(
`'${key}' has to be at least ${constraintValue} but is ${numberValue}`
);
}
} else {
// this.pushError(`'${key}' is a type that cannot have a minimum value.`);
}
};
// tslint:disable-next-line
const max: ConstraintValidationFunction<number> = function(
constraintValue: number,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (typeof value === 'number' || typeof value === 'string') {
const numberValue = typeof value === 'string' ? +value : value;
if (numberValue > constraintValue) {
this.pushError(
`'${key}' has to be lower than or equal to ${constraintValue} but is ${numberValue}`
);
}
} else {
// this.pushError(`'${key}' is a type that cannot have a maximum value.`);
}
};
// tslint:disable-next-line
const equals: ConstraintValidationFunction<any> = function(
constraintValue: any,
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (value !== constraintValue) {
this.pushError(
`'${key}' has to be equal to '${JSON.stringify(
constraintValue,
undefined,
2
)}' but is '${JSON.stringify(value, undefined, 2)}'`
);
}
};
// tslint:disable-next-line
const matches: ConstraintValidationFunction<
string | RegExp | string[]
> = function(
constraintValue: string | RegExp | string[],
validationPair: KeyValuePair
) {
const { value, key } = validationPair;
if (typeof value === 'string' || typeof value === 'number') {
const stringValue = typeof value === 'number' ? String(value) : value;
if (
typeof constraintValue === 'string' ||
constraintValue instanceof RegExp
) {
const regexp: RegExp =
typeof constraintValue === 'string'
? new RegExp(constraintValue)
: constraintValue;
if (!regexp.test(stringValue)) {
this.pushError(
`'${key}' has to match regexp '${regexp.source}' but is '${stringValue}'`
);
}
} else if (
Array.isArray(constraintValue) &&
!constraintValue.includes(stringValue)
) {
let allowedValuesString = '';
constraintValue.forEach((val: string, index: number) => {
allowedValuesString += `'${val}'${index !==
constraintValue.length - 1} ? ', ' : ''`;
});
this.pushError(
`'${key}' has to be one of the following values ${allowedValuesString} but is '${stringValue}'`
);
}
}
};
export const CONSTRAINT_VALIDATION_FUNCTION_MAP: ConstraintValidationFunctionMap = {
required,
validate,
minLength,
maxLength,
type,
isArray,
min,
max,
equals,
matches
};
<file_sep># lex-model-validator
Validate Amazon Lex models with ease.
This package checks for all possible errors Amazon Lex could throw while importing, building or even running your language model.
## Quickstart / Installation
to install it locally
```sh
npm install lex-model-validator
```
or globally
```sh
npm install -g lex-model-validator
```
Then you can use the following command to use the CLI.
```sh
lex-model-validator ./path/to/file
```
## CLI
```sh
lex-model-validator <path-to-file> [-v|--verbose]
```
[] = optional
## API
The validator can be used programmatically.
To do that you have to instantiate a new instance of ```LexModelValidator```.
This instance has a function called ```validateJson(json)``` which is the main entry point to use the validator. Pass in an object and the validator do the work.
## TO-DO
Improve Readme
<file_sep>export class BaseError {
private readonly $message: string;
constructor(message: string) {
this.$message = message;
}
get message() {
return this.$message;
}
}
<file_sep>import { KeyValuePair, Message } from '..';
import { ValidationFunction } from './ConstraintValidationFunctions';
import { VALIDATION_CONSTRAINTS_STATEMENT_MESSAGE } from './ValidationConstraints';
// tslint:disable-next-line
export const VALIDATION_FUNCTION_STATEMENT_MESSAGES: ValidationFunction<
Message[]
> = function(validationPair: KeyValuePair) {
const { value, key } = validationPair;
if (value && value.length > 0) {
value.forEach((message: Message) => {
this.validate(message, VALIDATION_CONSTRAINTS_STATEMENT_MESSAGE, key);
});
}
};
// tslint:disable-next-line
export const VALIDATION_FUNCTION_CHECK_DUPLICATES: ValidationFunction<
string[]
> = function(validationPair: KeyValuePair) {
const { value, key } = validationPair;
const collectedStrings: string[] = [];
if (value && value.length > 0) {
value.forEach((stringValue: string) => {
if (collectedStrings.includes(stringValue)) {
this.pushError(
`value '${stringValue}' in array '${key}' is supposed to have unique values but it does not`
);
} else {
collectedStrings.push(stringValue);
}
});
}
};
<file_sep>import { LexModelValidator, ValidationFunction, Validator } from '../index';
export interface KeyValuePair<T = {}> {
key: string;
value?: any;
}
export type InputModel = Record<string, any>;
export type ValidatorConstructor = new (
$master: LexModelValidator,
$parent?: Validator
) => Validator;
export interface ValidatorInterface {
run(data: InputModel): void;
runChildren(data: InputModel): void;
}
export type Constraints = Record<string, Constraint>;
export type AllowedType =
| 'object'
| 'string'
| 'boolean'
| 'undefined'
| 'function'
| 'number'
| 'symbol';
export interface Constraint {
required?: boolean;
validate?: ValidationFunction;
minLength?: number;
maxLength?: number;
type?: AllowedType;
isArray?: boolean;
min?: number;
max?: number;
equals?: any;
matches?: string | RegExp | string[];
}
export interface LexModel {
metadata: MetaData;
resource: Resource;
}
export interface MetaData {
schemaVersion: string;
importType: 'LEX';
importFormat: 'JSON';
}
export interface Resource {
name: string;
version: string;
locale: string;
childDirected: boolean;
idleSessionTTLInSeconds: number;
clarificationPrompt: Prompt;
abortStatement: Statement;
intents: Intent[];
slotTypes: SlotType[];
}
export interface Intent {
name: string;
version: string;
fulfillmentActivity: {
type: string;
};
sampleUtterances: string[];
slots: Slot[];
}
export type SlotConstraint = 'Required' | 'Optional';
export interface Slot {
name: string;
priority: number;
slotType: string;
slotTypeVersion?: string;
slotConstraint: SlotConstraint;
sampleUtterances: string[];
valueElicitationPrompt: Prompt;
}
export interface SlotType {
name: string;
version: string;
enumerationValues: SlotEnumerationValue[];
valueSelectionStrategy: ValueSelectionStrategy;
}
export type ValueSelectionStrategy = string;
export interface SlotEnumerationValue {
value: string;
synonyms: string[];
}
export interface Statement {
messages: Message[];
}
export interface Prompt extends Statement {
maxAttempts: number;
}
export interface Message {
contentType: string;
content: string;
}
<file_sep>import {
Constraints,
KeyValuePair,
SlotType,
ValidationFunction,
Validator
} from '../..';
export class SlotTypeValidator extends Validator {
getConstraints(): Constraints {
return {
'resource.slotTypes': {
isArray: true,
validate: this.validateSlotTypes
}
};
}
validateSlotTypes: ValidationFunction = (validationPair: KeyValuePair) => {
const slotTypes = validationPair.value as SlotType[] | undefined;
if (slotTypes && slotTypes.length > 0) {
// const collectedEnumValues: string[] = [];
// slotTypes.forEach((slotType: SlotType) => {
// this.validate(slotType, VALIDATION_CONSTRAINTS_SLOT_TYPE);
//
// if (slotType.enumerationValues && slotType.enumerationValues.length > 0) {
// slotType.enumerationValues.forEach((value: SlotEnumerationValue) => {
// this.validate(value, VALIDATION_CONSTRAINTS_ENUMERATION_VALUE);
// if (collectedEnumValues.includes(value.value)) {
// this.pushError(`value '${value.value}' in array '${validationPair.key + '.enumerationValues'}' is supposed to have unique values but it does not`);
// } else {
// collectedEnumValues.push(value.value);
// }
// });
// }
// });
}
};
}
|
3c4b6e6d6bfbdcc284a67e059b974c4ee70dcda4
|
[
"Markdown",
"TypeScript"
] | 17
|
TypeScript
|
m-ripper/lex-model-validator
|
d0e618d7ea8dcda35ff84b9494ad4d3fa9649315
|
74897afc638bd29cac80095600b9c164d935b531
|
refs/heads/main
|
<repo_name>verificationip/att<file_sep>/zaion_server.lua
local Proxy = module('vrp','lib/Proxy')
local Tunnel = module('vrp','lib/Tunnel')
local vRP = Proxy.getInterface('vRP')
local vRPclient = Tunnel.getInterface('vRP')
local zaiontoClient = {}
Tunnel.bindInterface('zaion-permissao', zaiontoClient)
-- print('<p style="color: red;">teste</p>')
------------------------------------------------------
-- Permissao
------------------------------------------------------
function zaiontoClient.checkPerm()
local source = source
local user_id = vRP.getUserId(source)
local hasPerm = vRP.hasPermission(user_id,SuaPermissao)
return hasPerm
end
----------------------------------------------
--
----------------------------------------------
function SendWebhookMessage(webhook,message)
if webhook ~= nil and webhook ~= "" then
PerformHttpRequest(webhook, function(err, text, headers) end, 'POST', json.encode({content = message}), { ['Content-Type'] = 'application/json' })
end
end
AddEventHandler('onResourceStart', function(nome)
if GetCurrentResourceName() ~= nome then
return
end
Wait(100)
PerformHttpRequest('api.ipify.org', function(e, i, h)
if i ~= nil then
ip = tostring(i)
Wait(100)
PerformHttpRequest('cosmosanticheat.com.br/zaionstore/admin/ip.php?ip='..ip, function(e2, a, h2)
auth = tostring(a)
if auth == "Autenticado" then
Wait(100)
PerformHttpRequest('cosmosanticheat.com.br/zaionstore/admin/status2.php?ip='..ip, function(e3, s, h3)
status = tostring(s)
local data = os.date ("%Y-%m-%d")
if status >= data then
print('^1[ZAIONSTORE] ^0Autenticando a sua key...')
Wait(4000)
print('^2[ZAIONSTORE] ^2Autenticado com sucesso!')
print('^7[ZAIONSTORE] ^4Key autenticada para o IP:^0 '..ip..'')
print('^5[ZAIONSTORE] ^4Você está utilizando o ZAION MECANICO^0')
print('^4[ZAIONSTORE] ^5Suporte somente via ticket^0')
Wait(1000)
TriggerClientEvent('zaion:autentificacao',-1)
local dmessage = "Um cliente teve o script ZAION MECANICO autenticado: " .. ip
PerformHttpRequest('https://discord.com/api/webhooks/867544371413647360/KnRhXcSv5esyoE4DBxVsCPYSwwuvZI0adwae9VGiD92mU1QaMq1uBCCxmp5xhmNg4l0G', function(err, text, headers) end, 'POST', json.encode({username = dname, content = dmessage}), { ['Content-Type'] = 'application/json' })
else
print('^1A sua licença expirou, por favor adquira uma nova licença.')
local dmessage = "Um cliente no qual a licença expirou tentou startar o script ZAION MECANICO. IP: " .. ip
PerformHttpRequest('https://discord.com/api/webhooks/867544741552586812/JZQk68SMI03eYE-PaBG7D3XjEr4ZGCRZBc0BTBBy_mfAeK5vj3RMN5ctNZL6xS86bg9V', function(err, text, headers) end, 'POST', json.encode({username = dname, content = dmessage}), { ['Content-Type'] = 'application/json' })
print('^0')
Wait(15000)
-- os.exit()
end
end)
else
local dmessage = "Um IP inválido tentou utilizar ao ZAION MECANICO " .. ip
PerformHttpRequest('https://discord.com/api/webhooks/867544895270027284/-BHYbQtG99YKO4wY0e_FRN3fQKacTAuCqBB6BtnSCINayrSnyu-jZtw8M-lHksKBq4Wl', function(err, text, headers) end, 'POST', json.encode({username = dname, content = dmessage}), { ['Content-Type'] = 'application/json' })
print('^1IP inválido ou você não possui licença, caso averiguarmos que você não possui acesso, seu IP será bloqueado.')
print('^1IP no qual foi iniciado o Script: '..ip..'')
print('^0')
Wait(15000)
-- os.exit()
end
end)
else
local dmessage = "Um IP não conseguiu se conectar com o servidor usando ZAION MECANICO " .. ip
PerformHttpRequest('https://discord.com/api/webhooks/867544985195511818/K3dQkzgNFx6S9BBzIRNpSYJDoCeTWOmZD56n07BmV73WhVry7jBilUnSLQrROCK0FE7-', function(err, text, headers) end, 'POST', json.encode({username = dname, content = dmessage}), { ['Content-Type'] = 'application/json' })
print('^4Um Log com mais informações foi enviado para nós.')
print('^4Servidor com problemas, por favor entre em contato via Ticket.')
print('^0')
Wait(5000)
-- os.exit()
end
end)
end)
-- AddEventHandler("onResourceStart",function(resourceName)
-- local weebhook = 'teste'
-- if GetCurrentResourceName() == resourceName then
-- PerformHttpRequest("https://raw.githubusercontent.com/usuario1416/ipsteste/main/ips.json", function (a, zaionresultado, b)
-- PerformHttpRequest("https://api.ipify.org", function (c, IPOficial, d)
-- local ips = json.decode(zaionresultado)
-- if ips == nil then
-- local source = source
-- SendWebhookMessage(weebhook,'```AUTENTIFICACAO COM SITE INVALIDO!\n[IP]: ' .. IPOficial .. '\nTentou startar o script mas o site de autentificacao esta invalido!```')
-- print('Erro ao Iniciar o script, contate o ! Caduh#0001, para ver oque pode ter acontecido!')
-- end
-- if GetCurrentResourceName() ~= 'zaion_mecanico' then
-- Wait(1000)
-- print('O SCRIPT "zaion_mecanico" TEVE SEU NOME TROCADO E POR ISSO NAO PODE SER AUTENTICADO!')
-- SendWebhookMessage(weebhook,'```MUDANCA DE NOME DE SCRIPT!\n[IP]: ' .. IPOficial .. 'MUDOU O NOME DO SCRIPT\n[DE]: zaion_mecanico\n[PARA]: '.. resourceName .. os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```")
-- return
-- end
-- for k,v in pairs(ips) do
-- if IPOficial == v then
-- IsAutenticado = true
-- CreateThread(function()
-- repeat
-- Wait(1000)
-- TriggerClientEvent('zaion:autentificacao',-1)
-- until false
-- end)
-- SendWebhookMessage(weebhook,'```IP AUTENTICADO! \n[IP]: ' .. IPOficial .. '\n[SCRIPT]: zaion_mecanico\nFOI AUTENTIFICADO COM SUCESSO!```')
-- Wait(1000)
-- print()
-- print()
-- print('SCRIPT "zaion_mecanico" AUTENTICADO COM SUCESSO!')
-- print('IP "' .. IPOficial .. '" AUTENTIFICADO COM SUCESSO!')
-- print('DUVIDAS? CONTATE O ! Caduh#0001')
-- print('OU NO DISCORD: discord.gg/')
-- print()
-- print()
-- return
-- end
-- end
-- SendWebhookMessage(weebhook,'```AUTENTIFICACAO FALHA! \n[IP]: ' .. IPOficial .. '\n[OCORRIDO]: Ip nao autorizado!\n[SCRIPT]: zaion_mecanico'..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```")
-- Wait(1000)
-- print()
-- print()
-- print('SCRIPT "zaion_mecanico" NAO AUTENTICADO!')
-- print('VOCE QUER ADQUIRIR ESSE SCRIPT?')
-- print('CONTATE O ! Caduh#0001')
-- print('OU NO DISCORD: discord.gg/')
-- print()
-- print()
-- end)
-- end)
-- end
-- end)
|
6d34eacdc0c0edb5e53ae7bff977871e847d25d4
|
[
"Lua"
] | 1
|
Lua
|
verificationip/att
|
df4c1214d2fb2bae900a6c7fdac1e7c924e096f2
|
8408dcfdd390a0b330801dedf7786c00a97ce6d9
|
refs/heads/main
|
<repo_name>wfong443/flake8-default-args<file_sep>/tests/test1.py
def test1(a, b, *, k1, k2):
pass
def test2(a, b, k1=None, k2=None):
pass
def test3(a, b, k1=2, k2="hye"):
pass
def test4(a, b, *, k0=None, k1=2, k2="hye"):
pass
def test5(a, b, *, k0=None, k1=None, k2=None):
pass
def test6(a, b, *, k0=None, k1=None, k2):
pass
<file_sep>/flake8_default_args.py
import ast
import sys
if sys.version_info < (3, 8):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
__version__ = '0.1.0'
class FcnDefaultArgsChecker(object):
"""Mutable default argument checker.
Flake8 extension that alerts when a mutable type is used
as an argument's default value.
"""
name = __name__
version = importlib_metadata.version(__name__)
def __init__(self, tree, filename):
self._debug = False
self.tree = tree
def get_default_values(self, defaults):
return [default.value for default in defaults if default is not None and default.value is not None]
def run(self):
for node in ast.walk(self.tree):
if isinstance(node, ast.FunctionDef):
defvals = []
if len(node.args.defaults) > 0:
if self._debug:
print(f"len(node.args.defaults)={len(node.args.defaults)}")
print(f"{node.name}.defaults={node.args.defaults}")
print(f"{node.name}.kwonlyargs={node.args.kwonlyargs}")
print(f"{node.name}.kw_defaults={node.args.kw_defaults}")
res = self.get_default_values(node.args.defaults)
if res != []:
defvals.append(res)
if len(node.args.kwonlyargs) > 0:
if self._debug:
print(f"len(node.args.kwonlyargs)={len(node.args.kwonlyargs)}")
print(f"{node.name}.defaults={node.args.defaults}")
print(f"{node.name}.kwonlyargs={node.args.kwonlyargs}")
print(f"{node.name}.kw_defaults={node.args.kw_defaults}")
res = self.get_default_values(node.args.kw_defaults)
if res != []:
defvals.append(res)
if len(defvals) > 0:
error_msg = f"Function {node.name} has keyword args with non-None default values {defvals}"
yield (node.lineno, node.col_offset, f"WFDA100 {error_msg}", type(self))
<file_sep>/README.md
# flake8-default-args
Checks to see if keyword arguments are assigned default values in a function signature.
An assigned value of None is allowed or no assigned value.
|
cfbb6c3b32f3513e1665d2df3624f87d06948980
|
[
"Markdown",
"Python"
] | 3
|
Python
|
wfong443/flake8-default-args
|
ae8e4fe350a0dd410db78cb40e11f45a5c01f50b
|
16288a5c8a50458dd344cc933bab81832ba81fb1
|
refs/heads/master
|
<repo_name>gavz/DES<file_sep>/PermutedChoice.hpp
//
// Created by steve on 1/26/19.
//
#ifndef CS465_DES_PERMUTEDCHOICE_HPP
#define CS465_DES_PERMUTEDCHOICE_HPP
#include "Block.hpp"
/**
*
* <NAME>
*
**/
/* Map a block of size N to a block of size M with the relation sources given
* via a choice vector and sinks their index in that vector*/
Block permute(const Block& data, const std::vector<uint8_t>& choiceTable) {
// output block is size of choice table (bit count)
Block out(choiceTable.size());
out.zero();
std::vector<uint8_t> vec;
for (int i = 0; i < choiceTable.size(); i++) {
uint8_t b = data.bitAt_OneIdx(choiceTable.at(i));
out.setBitAt(i, b);
}
return out;
}
Block leftHalf(const Block& data) {
std::vector<uint8_t> indices;
indices.reserve(data.blockSize());
for (size_t i = 0; i < (data.blockSize() / 2); i++) {
indices.push_back(i + 1);
}
return permute(data, indices);
}
Block rightHalf(const Block& data) {
std::vector<uint8_t> indices;
indices.reserve(data.blockSize());
for (size_t i = data.blockSize() / 2; i < data.blockSize(); i++) {
indices.push_back(i + 1);
}
return permute(data, indices);
}
Block circularLS(const Block& data, int amount) {
std::vector<uint8_t> indices;
indices.reserve(data.blockSize());
// all indices that dont fall off
for (size_t i = amount; i < data.blockSize(); i++) {
indices.push_back(i + 1);
}
// append the ones that fell
for (size_t i = 0; i < amount; i++) {
indices.push_back(i + 1);
}
return permute(data, indices);
}
Block join(const Block& lhs, const Block& rhs) {
Block out(lhs.blockSize() + rhs.blockSize());
out.zero();
size_t cursor = 0;
for (size_t i = 0; i < lhs.blockSize(); i++) {
out.setBitAt(cursor++, lhs.bitAt(i));
}
for (size_t i = 0; i < rhs.blockSize(); i++) {
out.setBitAt(cursor++, rhs.bitAt(i));
}
return out;
}
Block PC_1(const Block& data) {
return permute(data, {57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 21, 5
});
}
Block PC_2(const Block& data) {
return permute(data, {14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32
});
}
uint8_t sbox_lut[8][4][16] = {
{
{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
},
{
{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
},
{
{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
},
{
{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
},
{
{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
},
{
{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
},
{
{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
},
{
{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11},
},
};
uint8_t SBOX_6Bits(const uint8_t tableNum, uint8_t selector) {
uint8_t row = (uint8_t)((0b100000 & selector) >> 4 | (1UL & selector));
uint8_t col = (uint8_t)(0b011110 & selector) >> 1;
assert(row < 4 && row >= 0);
assert(col < 16 && col >= 0);
return sbox_lut[tableNum][row][col];
}
// walk a data block in 6 bit chunks, passing each chunk to SBOX_i
Block SBOX(const Block& data) {
assert(data.blockSize() == 48);
Block out(32);
out.zero();
uint8_t cursor = 0;
uint8_t tmp = 0;
uint8_t table = 0;
// Loop up-to and include 32bits
for (size_t i = 0; i <= data.blockSize(); i++) {
// every 6-th bit after the first 6 get substituted
if (i % 6 == 0 && i != 0) {
// 6Bits In -> 8bits Out (4 bit val) -> 4 bits Final
uint8_t sub = SBOX_6Bits(table, tmp);
// shift to 8 bit -> 4 bit value, then copy bits
for (size_t bit = 0; bit < 4; bit++) {
out.setBitAt(cursor++, GET_BIT(sub << 4, bit));
}
// each 6 bits uses next table
table++;
tmp = 0;
}
// build up bit cache one at a time, recheck bounds since inclusive loop
if (i < data.blockSize()) {
tmp <<= 1;
tmp |= data.bitAt(i);
}
}
return out;
}
// expand
Block E(const Block& data) {
return permute(data, {
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
});
}
// Initial data permuation
Block IP(const Block& data) {
return permute(data, {
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
});
}
Block IP_1(const Block& data) {
return permute(data, {
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
});
}
Block XOR(const Block& lhs, const Block& rhs) {
assert(lhs.blockSize() == rhs.blockSize());
Block out(lhs.blockSize());
out.zero();
for (size_t i = 0; i < lhs.blockSize(); i++) {
out.setBitAt(i, lhs.bitAt(i) ^ rhs.bitAt(i));
}
return out;
}
// Final permutation for F
Block P(const Block& data) {
return permute(data, {
16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25
});
}
// data should be the right of initial permutation
Block F(const Block& data, const Block& key) {
assert(data.blockSize() == 32);
assert(key.blockSize() == 48);
Block expanded = E(data);
std::cout << "E:" << std::endl;
expanded.str();
assert(expanded.blockSize() == 48);
Block x = XOR(expanded, key);
std::cout << "Xor w/ key:" << std::endl;
x.str();
Block s = SBOX(x);
assert(s.blockSize() == 32);
std::cout << "S-Box:" << std::endl;
s.str();
Block p = P(s);
std::cout << "P: " << std::endl;
p.str();
return p;
}
#endif //CS465_DES_PERMUTEDCHOICE_HPP
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(des)
set(CMAKE_CXX_STANDARD 11)
add_executable(des main.cpp Block.hpp PermutedChoice.hpp)
<file_sep>/main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>
#include "Block.hpp"
#include "PermutedChoice.hpp"
/**
*
* <NAME>
*
**/
Block permuteKey(const std::string& s) {
Block b(s, 64, true);
return PC_1(b);
}
int main() {
std::cout << "Enter a file path to open as input: ";
std::string fileInPath;
std::cin >> fileInPath;
std::ifstream in(fileInPath, std::ios::binary | std::ios::in);
std::string mode = "";
std::cout << "Encrypt Or Decrypt (D/E): ";
std::cin >> mode;
std::vector<Block> blocks;
if(mode == "E") {
std::vector<uint8_t> filtered;
filtered.reserve(128);
char c;
while (in.get(c)) {
if (c <= 0x20 || c > 0x7E)
continue;
filtered.push_back((uint8_t)c);
}
blocks = Block::buildBlocks(filtered, 64);
} else if(mode == "D") {
std::vector<uint8_t> buf;
buf.reserve(128);
char c;
while (in.get(c)) { buf.push_back((uint8_t)c); }
blocks = Block::buildBlocks(buf, 64);
} else {
std::cout << "Unsupported Mode, Exiting" << std::endl;
return 1;
}
// Key Permutation
std::cout << "Enter the password: ";
std::string password;
std::cin >> password;
Block PC_1 = permuteKey(password);
password = "";
// 16-Round Key Generation
std::vector<Block> keys;
Block Ci = leftHalf(PC_1);
Block Di = rightHalf(PC_1);
uint8_t round_shifts[16] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
for (size_t round = 0; round < 16; round++) {
Ci = circularLS(Ci, round_shifts[round]);
Di = circularLS(Di, round_shifts[round]);
keys.push_back(PC_2(join(Ci, Di)));
std::cout << "Round " << round + 1 << " key:" << std::endl;
keys.back().str();
}
// feed backwards through network in decrypt
if(mode == "D")
std::reverse(keys.begin(), keys.end());
// Feistel Network Model
std::vector<Block> cipherBlocks;
for(const auto& data : blocks) {
std::cout << "Data Block: " << std::endl;
data.str();
// Initial Permutation
Block I = IP(data);
Block L_i = leftHalf(I);
Block R_i = rightHalf(I);
// 16 Rounds
for(size_t round = 0; round < 16; round++) {
std::cout << "Round " << round + 1 << std::endl << std::endl;
std::cout << "L_i:" << std::endl;
L_i.str();
std::cout << "R_i:" << std::endl;
R_i.str();
Block oldLi = L_i;
L_i = R_i;
R_i = XOR(oldLi, F(R_i, keys[round]));
std::cout << "Xor w/ L_i - 1" << std::endl;
R_i.str();
}
// 32 bit Swap + Inverse Initial Permutation
cipherBlocks.push_back(IP_1(join(R_i,L_i)));
std::cout << std::endl << "Final Permutation:" << std::endl;
cipherBlocks.back().str();
}
std::cout << "Enter file path to output to: ";
std::string fileOut;
std::cin >> fileOut;
std::ofstream out(fileOut, std::ios::binary | std::ios::out);
for(const Block& block : cipherBlocks) {
out.write((char*)block.m_data.data(), block.m_data.size());
}
out.close();
return 0;
}
<file_sep>/Block.hpp
//
// Created by steve on 1/24/19.
//
#ifndef CS465_DES_BLOCK_HPP
#define CS465_DES_BLOCK_HPP
#include <stdint.h>
#include <vector>
#include <string>
#include <cassert>
#include <cmath>
#include <bitset>
#define BITS_P_BYTE 8
// MSB is 0, LSB is 7
#define GET_BIT(num, n) (((num) >> (7 - (n))) & 1UL)
#define CLR_BIT(num, n) ((num) &= ~(1UL << (7 - (n))))
#define SET_BIT(num, n) ((num) |= 1UL << (7 - (n)))
/**
*
* <NAME>
*
**/
void printBinary(const char* buf, const size_t sz, const size_t bits) {
size_t totalBits = 0;
for (size_t byte = 0; byte < sz; byte++) {
for (size_t bit = 0; bit < 8; bit++) {
if (totalBits++ >= bits)
break;
std::cout << (uint16_t)(((buf[byte]) >> (7 - bit)) & 1);
}
}
std::cout << std::endl;
};
class Block
{
public:
Block(std::vector<uint8_t>& data, const size_t blockSz) {
m_blockSize = blockSz;
size_t dSize = data.size() * BITS_P_BYTE;
assert(dSize <= blockSize());
m_data = data;
// pad if needed
for (size_t i = dSize; i < blockSize(); i += BITS_P_BYTE) {
m_data.push_back(0);
}
assert(m_data.size() * BITS_P_BYTE >= blockSize());
}
// assumes 7 bit ascii is desired from 8 bit input
Block(const std::string& str, const size_t blockSz, bool parityRemove) {
std::vector<uint8_t> data(str.begin(), str.end());
if(parityRemove) {
for (size_t i = 0; i < data.size(); i++) {
data.at(i) <<= 1;
}
}
m_blockSize = blockSz;
size_t dSize = data.size() * BITS_P_BYTE;
assert(dSize <= blockSize());
m_data = data;
// pad if needed
for (size_t i = dSize; i < blockSize(); i += BITS_P_BYTE) {
m_data.push_back(0);
}
assert(m_data.size() * BITS_P_BYTE >= blockSize());
}
Block(const size_t blockSz) {
m_blockSize = blockSz;
m_data.reserve(bytesPerBlock());
}
void zero() {
m_data.resize(bytesPerBlock(), 0);
}
static std::vector<Block> buildBlocks(std::vector<uint8_t>& data, const size_t blockSz) {
std::vector<Block> blocks;
std::vector<uint8_t> tmp;
// walk all data
size_t count = 0;
for (uint8_t b : data) {
// build blocks byte by byte
if (count >= (blockSz / BITS_P_BYTE)) {
blocks.emplace_back(tmp, blockSz);
count = 0;
tmp.clear();
}
count++;
tmp.push_back(b);
}
if (count != 0) {
blocks.emplace_back(tmp, blockSz);
}
return blocks;
}
size_t blockSize() const {
return m_blockSize;
}
size_t bytesPerBlock() const {
return (size_t)std::ceil((double)m_blockSize / BITS_P_BYTE);
}
/* given some index to a bit in the block, return that bit.
* MSB is bit 0, LSB is m_blockSz*/
uint8_t bitAt(const size_t bit_idx) const {
uint8_t byt = m_data.at(bit_idx / BITS_P_BYTE);
uint8_t bit = (uint8_t)bit_idx % (uint8_t)BITS_P_BYTE;
return (uint8_t)GET_BIT(byt, bit);
}
uint8_t bitAt_OneIdx(const size_t bit_idx) const {
return bitAt(bit_idx - 1);
}
void setBitAt(const size_t bit_idx, const uint8_t val) {
uint8_t byt = m_data.at(bit_idx / BITS_P_BYTE);
uint8_t bit = (uint8_t)bit_idx % (uint8_t)BITS_P_BYTE;
if (val) {
SET_BIT(byt, bit);
} else {
CLR_BIT(byt, bit);
}
m_data.at(bit_idx / BITS_P_BYTE) = byt;
}
void setBitAt_OneIdx(const size_t bit_idx, const uint8_t val) {
setBitAt(bit_idx - 1, val);
}
void str() const {
printBinary((char*)m_data.data(), m_data.size(), m_blockSize);
}
std::vector<uint8_t> m_data;
private:
size_t m_blockSize;
};
#endif //CS465_DES_BLOCK_HPP
<file_sep>/README.md
# DES
Des Encrypt/Decrypt Utility, 8 character ascii key, N byte data (filtered for ascii) processed in 64bit blocks
|
1919a3273396ce6b15d5f6a93d84fee710154f37
|
[
"Markdown",
"CMake",
"C++"
] | 5
|
C++
|
gavz/DES
|
a7304835f7243b7064e580e6fc8d22c4e349e56b
|
7210b1071889bbcb235f38c656777085d6776d23
|
refs/heads/master
|
<repo_name>vebg/ElectronicWallet<file_sep>/ElectronicWallet.Repositories/WalletTransactionRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class WalletTransactionRepository : RepositoryBase<WalletTransaction>, IWalletTransactionRepository
{
public WalletTransactionRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Common/GenericResponse.cs
namespace ElectronicWallet.Common
{
public class GenericResponse
{
public bool Success { get; set; }
public string[] Errors { get; set; }
public string Message { get; set; }
public GenericResponse(bool success = true,string message = "", string[] errors = null)
{
Success = success;
Message = message;
Errors = errors;
}
}
public class GenericResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; }
public string[] Errors { get; set; }
public string Message { get; set; }
public GenericResponse(T data, bool success = true, string message = "", string[] errors = null)
{
Success = success;
Message = message;
Errors = errors;
Data = data;
}
public GenericResponse(bool success = true, string message = "", string[] errors = null)
{
Success = success;
Message = message;
Errors = errors;
}
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IUserWalletRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IUserWalletRepository: IRepositoryBase<UserWallet>
{
}
}
<file_sep>/ElectronicWallet.Services/UserWalletService.cs
using AutoMapper;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ElectronicWallet.Services
{
public class UserWalletService: ManagementServiceBase<UserWalletDto, UserWallet>, IUserWalletService
{
IUserWalletRepository _userWalletRepository;
IMapper _mapper;
public UserWalletService(IUserWalletRepository repository,IMapper mapper):base(repository,mapper)
{
_userWalletRepository = repository;
_mapper = mapper;
}
public async Task<GenericResponse<WalletDto>> GetWalletByUserIdAndWalletId(Guid userId, Guid walletId)
{
try
{
var userWallet = await _userWalletRepository.Query.Where(x => x.UserId == userId && x.WalletId == walletId).Include(s => s.Wallet).FirstOrDefaultAsync();
if (userWallet is null)
{
return new GenericResponse<WalletDto>(false, errors: new string[] { "User don't have wallet." });
}
var walletDto = _mapper.Map<WalletDto>(userWallet.Wallet);
return new GenericResponse<WalletDto>(walletDto);
}
catch (Exception ex)
{
Console.WriteLine($"Error {ex}");
return new GenericResponse<WalletDto>(false, errors: new string[] { "Error." });
}
}
public async Task<GenericResponse<List<WalletDto>>> GetWalletsByUserId(Guid userId)
{
try
{
var userWallets = await _userWalletRepository.Query.Where(x => x.UserId == userId).Include(s => s.Wallet).ToListAsync();
if(userWallets is null || userWallets.Count == 0)
{
return new GenericResponse<List<WalletDto>>(false, errors: new string[] { "User don't have wallets." });
}
var wallets = new List<WalletDto>();
foreach (var item in userWallets)
{
wallets.Add(Mapper.Map<WalletDto>(item.Wallet));
}
return new GenericResponse<List<WalletDto>>(wallets);
}
catch (Exception ex)
{
Console.WriteLine($"Error {ex}");
return new GenericResponse<List<WalletDto>>(false, errors: new string[] { "Error." });
}
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/CorsInstaller.cs
using ElectronicWallet.Infraestructure.Installers.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class CorsInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddCors(options => options.AddPolicy("CorsOptions", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
}));
}
}
}
<file_sep>/ElectronicWallet.Database/DTO/UserWalletDto.cs
using System;
namespace ElectronicWallet.Database.DTO
{
public class UserWalletDto
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Guid WalletId { get; set; }
public bool IsActive { get; set; }
#region Relations
public UserDto User { get; set; }
public WalletDto Wallet { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Repositories/WalletRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class WalletRepository: RepositoryBase<Wallet>, IWalletRepository
{
public WalletRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Enums/UserType.cs
namespace ElectronicWallet.Infraestructure.Enums
{
public enum UserType
{
User
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/WalletEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class WalletEntityConfiguration : IEntityTypeConfiguration<Wallet>
{
public void Configure(EntityTypeBuilder<Wallet> builder)
{
builder.HasKey(e => e.Id);
builder.Property(e => e.Name)
.HasMaxLength(100)
.IsRequired();
builder.Property(e => e.Balance)
.HasMaxLength(4)
.IsRequired();
builder.Property(e => e.IsActive)
.HasDefaultValue(true)
.IsRequired();
builder.Property(e => e.IsDeleted)
.HasDefaultValue(false)
.IsRequired();
builder.HasOne(e => e.Currency)
.WithMany(user => user.Wallets)
.HasForeignKey(entity => entity.CurrencyId)
.OnDelete(DeleteBehavior.Cascade);
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/MvcInstaller.cs
using ElectronicWallet.Infraestructure.Installers.Contracts;
using ElectronicWallet.Infraestructure.Middlewares;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure
{
public class MvcInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddMvcCore(options =>
{
options.Filters.Add(typeof(ExceptionHandler));
options.Filters.Add(typeof(ValidateModel));
});
services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
}
}
}
<file_sep>/ElectronicWallet.Services/UserService.cs
using AutoMapper;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
using System;
using System.Threading.Tasks;
namespace ElectronicWallet.Services
{
public class UserService: ManagementServiceBase<UserDto,User>,IUserService
{
public UserService(IUserRepository repository,IMapper mapper):base(repository,mapper)
{
}
public override Task<PagedResult<UserDto>> GetAllAsync(int page, int size)
{
return base.GetAllAsync(page, size);
}
public override Task<UserDto> CreateAsync(UserDto request)
{
if(string.IsNullOrEmpty(request.Email))
{
throw new Exception("Email can't be null");
}
return base.CreateAsync(request);
}
public async Task<UserDto> GetByEmailAndPassword(string email, string password)
{
UserDto user = null;
try
{
var userSelected = await Repository.FindAsync(x => x.Email.ToLower() == email.ToLower());
//var passwordHash = EncryptPassword(password, userSelected.Salt);
/*if(passwordHash.Equals(userSelected.PasswordHash))
{
user = Mapper.Map<UserDto>(userSelected);
}*/
user = Mapper.Map<UserDto>(userSelected);
}
catch (Exception ex)
{
Console.WriteLine($"Error finding the user. Exeption {ex}");
}
return user;
}
}
}
<file_sep>/ElectronicWallet.Database/Entities/EntityBase.cs
using System;
namespace ElectronicWallet.Database.Entities
{
public abstract class EntityBase
{
public Guid CreatedBy { get; set; }
public Guid ModifiedBy { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
}
}
<file_sep>/ElectronicWallet.Database/DTO/OrderDto.cs
using System;
namespace ElectronicWallet.Database.DTO
{
public class OrderDto
{
public Guid Id { get; set; }
public Guid PaymentId { get; set; }
public Guid ServiceId { get; set; }
public string OrderNumber { get; set; }
#region Relations
public PaymentDto Payment { get; set; }
public ServiceDto Service { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Services/WalletTransactionService.cs
using AutoMapper;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
namespace ElectronicWallet.Services
{
public class WalletTransactionService : ManagementServiceBase<WalletTransactionDto, WalletTransaction>, IWalletTransactionService
{
public WalletTransactionService(IWalletTransactionRepository repository,IMapper mapper):base(repository,mapper)
{
}
}
}
<file_sep>/ElectronicWallet.Database/DTO/Request/AddBalanceRequest.cs
namespace ElectronicWallet.Database.DTO.Request
{
public class AddBalanceRequest
{
public decimal Amount { get; set; }
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IUserRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IUserRepository: IRepositoryBase<User>
{
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IOrderRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IOrderRepository: IRepositoryBase<Order>
{
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IPaymentService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Services.Contracts
{
public interface IPaymentService: IManagementServiceBase<PaymentDto, Payment>
{
}
}
<file_sep>/ElectronicWallet.Repositories/Extensions/PagedResultExtensions.cs
using ElectronicWallet.Common;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
namespace ElectronicWallet.Repositories.Extensions
{
public static class PagedResultExtensions
{
public static PagedResult<T> ToPagedResult<T>(this IQueryable<T> query, int? page = null, int? size = null) where T : class
{
var result = new PagedResult<T>(query.Count(), page, size);
result.Items = query.Skip((result.Page - 1) * result.Size).Take(result.Size).ToList();
return result;
}
public static async Task<PagedResult<T>> ToPagedResultAsync<T>(this IQueryable<T> query, int? page = null, int? size = null) where T : class
{
var result = new PagedResult<T>(await query.CountAsync(), page, size);
result.Items = await query.Skip((result.Page - 1) * result.Size).Take(result.Size).ToListAsync();
return result;
}
}
}
<file_sep>/ElectronicWallet.Database/Entities/UserWallet.cs
using System;
namespace ElectronicWallet.Database.Entities
{
public class UserWallet: EntityBase
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Guid WalletId { get; set; }
public bool IsActive { get; set; }
#region Relations
public User User { get; set; }
public Wallet Wallet { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IUserService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using System.Threading.Tasks;
namespace ElectronicWallet.Services.Contracts
{
public interface IUserService: IManagementServiceBase<UserDto,User>
{
public Task<UserDto> GetByEmailAndPassword(string email, string password);
}
}
<file_sep>/ElectronicWallet.Database/Entities/Order.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database.Entities
{
public class Order:EntityBase
{
public Guid Id { get; set; }
public Guid PaymentId { get; set; }
public Guid ServiceId { get; set; }
public string OrderNumber { get; set; }
#region Relations
public Payment Payment { get; set; }
public Service Service { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Entities/DTO/OrderDto.cs
using System;
namespace ElectronicWallet.Entities.DTO
{
public class OrderDto
{
public Guid Id { get; set; }
public Guid PaymentId { get; set; }
public Guid ServiceId { get; set; }
public string OrderNumber { get; set; }
}
}
<file_sep>/ElectronicWallet.Api/Model/V1/ApiRoutes.cs
namespace ElectronicWallet.Api.Model.V1
{
public static class ApiRoutes
{
public const string Root = "api";
public const string Version = "v1";
public const string Base = Root + "/" + Version;
public static class Users
{
public const string Update = Base + "/users/{userId}";
public const string Delete = Base + "/users/{userId}";
public const string Get = Base + "/users/{userId}";
public const string Create = Base + "/users";
public const string GetAll = Base + "/users";
}
public static class Authentication
{
public const string Login = Base + "/users/login";
public const string LogOut = Base + "/users/logout";
}
public static class Wallets
{
public const string Create = Base + "/wallets/{userId}";
public const string AddBalance = Base + "/wallets/{walletId}/users/{userId}/balance";
}
public static class UsersWallets
{
public const string GetAll = Base + "/users/{userId}/wallets";
public const string Get = Base + "/users/{userId}/wallets/{walletId}";
// public const string TransferMoney = Base + "/users/{userId}/wallets/{walletId}/transfer";
}
/*
public static class Orders
{
public const string Get = Base + "/orders/{orderId}";
public const string GetOrdersByWallet = Base + "/orders/wallets/{walletId}";
}
public static class Payments
{
public const string PayService = Base + "/payments/services/{serviceId}";
}*/
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IWalletTransactionsService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Services.Contracts
{
public interface IWalletTransactionService: IManagementServiceBase<WalletTransactionDto, WalletTransaction>
{
}
}
<file_sep>/ElectronicWallet.Repositories/ServiceRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class ServiceRepository: RepositoryBase<Service>, IServiceRepository
{
public ServiceRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Services/WalletService.cs
using AutoMapper;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ElectronicWallet.Services
{
public class WalletService: ManagementServiceBase<WalletDto, Wallet>, IWalletService
{
private readonly IUserWalletService _userWalletService;
private readonly IWalletService _walletService;
private readonly IUserWalletRepository _userWalletRepository;
private readonly IMapper _mapper;
public WalletService(IWalletRepository repository,IMapper mapper, IUserWalletService userWalletService, IUserWalletRepository userWalletRepository) :base(repository,mapper)
{
_userWalletService = userWalletService;
_userWalletRepository = userWalletRepository;
_mapper = mapper;
}
public async Task<GenericResponse> AddBalance(Guid userId, Guid walletId, decimal amount)
{
try
{
var userWallet = await _userWalletRepository.Query.Where(x => x.UserId == userId && x.WalletId == walletId).Include(s => s.Wallet).FirstOrDefaultAsync();
if (userWallet is null)
{
return new GenericResponse(false, errors: new string[] { "User don't have wallet." });
}
userWallet.Wallet.Balance += amount;
await Repository.CreateAsync(userWallet.Wallet);
await Repository.SaveChangesAsync();
return new GenericResponse(true);
}
catch (Exception ex)
{
Console.WriteLine($"Error {ex}");
return new GenericResponse(false, errors: new string[] { "Error." });
}
}
public async Task<GenericResponse> CreateAndAssingWallet(Guid userId, WalletDto request)
{
try
{
var entity = Mapper.Map<Wallet>(request);
await Repository.CreateAsync(entity);
await Repository.SaveChangesAsync();
var userWallet = new UserWalletDto
{
UserId = userId,
WalletId = entity.Id
};
await _userWalletService.CreateAsync(userWallet);
await Repository.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Error Creating the wallet: {ex}");
return new GenericResponse(false,errors: new string[] { "Error Creating the wallet." });
}
return new GenericResponse();
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/AutoMapperInstaller.cs
using AutoMapper;
using ElectronicWallet.Database.EntitiesConfigurations.Profile;
using ElectronicWallet.Infraestructure.Installers.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class AutoMapperInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperDefaultProfile());
});
var mapper = config.CreateMapper();
services.AddSingleton(mapper);
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/ServiceInstaller.cs
using ElectronicWallet.Infraestructure.Installers.Contracts;
using ElectronicWallet.Services;
using ElectronicWallet.Services.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class ServiceInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IUserService, UserService>();
services.AddScoped<ICurrencyService, CurrencyService>();
services.AddScoped<IUserWalletService, UserWalletService>();
services.AddScoped<IWalletService, WalletService>();
services.AddScoped<IWalletTransactionService, WalletTransactionService>();
services.AddScoped<IPaymentService, PaymentService>();
services.AddScoped<IOrderService, OrderService>();
services.AddScoped<IServiceService, ServiceService>();
services.AddScoped<IUserService, UserService>();
}
}
}
<file_sep>/ElectronicWallet.Entities/DTO/ServiceDto.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities.DTO
{
public class ServiceDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
}
}
<file_sep>/ElectronicWallet.Infraestructure/Middlewares/HttpSecurityHeaderMiddleware.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ElectronicWallet.Infraestructure.Middlewares
{
public class HttpSecurityHeaderMiddleware: IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
context.Response.Headers.TryAdd("X-Frame-Options", "DENY");
context.Response.Headers.Add("X-Content-Type-Options", new[] { "nosniff" }); //https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
await next(context);
}
}
public static class HttpSecurityHeaderMiddlewareExtensions
{
public static IApplicationBuilder UseHttpSecurityHeaderMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<HttpSecurityHeaderMiddleware>();
}
}
}
<file_sep>/ElectronicWallet.Database/Seeders/UserSeeder.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database.Seeders.Contracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace ElectronicWallet.Database.Seeders
{
public class UserSeeder : ISeeder
{
public void Seed(IServiceProvider serviceProvider)
{
using (var context = new ElectronicWalletContext(
serviceProvider.GetRequiredService<DbContextOptions<ElectronicWalletContext>>()))
{
if (context.Users.Any()) return;
context.Users.AddRange( new User [] {
CreateDefaultUsers(Guid.Parse("C25C298E-AD15-4DE7-9A15-B8A2B7C6923F"), "Victor", "Brito", "M", "<EMAIL>", "123456789"),
CreateDefaultUsers(Guid.Parse("E14FBA51-27D9-416E-86C6-5FB470AE4EA1"), "Solenny", "<NAME>", "F", "<EMAIL>", "123456789")
});
context.SaveChanges();
};
}
private User CreateDefaultUsers(Guid id, string name, string lasname, string gender, string email, string password)
{
return new User
{
Id = id,
Email = email,
Name = name,
LastName = lasname,
Gender = gender,
Password = <PASSWORD>,
IsActive = true
};
}
}
}
<file_sep>/ElectronicWallet.Entities/DTO/WalletTransactionDto.cs
using System;
namespace ElectronicWallet.Entities.DTO
{
public class WalletTransactionDto
{
public Guid Id { get; set; }
public Guid ToWalletId { get; set; }
public Guid FromWalletId { get; set; }
public decimal Amount { get; set; }
public bool IsProccessing { get; set; }
public decimal Fee { get; set; }
}
}
<file_sep>/ElectronicWallet.Api/Startup.cs
using ElectronicWallet.Database;
using ElectronicWallet.Infraestructure.Installers;
using ElectronicWallet.Infraestructure.Installers.Contracts;
using ElectronicWallet.Infraestructure.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
namespace ElectronicWallet.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var apiInstallers = typeof(DataInstaller).Assembly.ExportedTypes.Where(x =>
typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract).Select(Activator.CreateInstance)
.Cast<IInstaller>().ToList();
var installers = typeof(Startup).Assembly.ExportedTypes.Where(x =>
typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract).Select(Activator.CreateInstance)
.Cast<IInstaller>().ToList();
apiInstallers.ForEach(installer => installer.InstallServices(services, Configuration));
installers.ForEach(installer => installer.InstallServices(services, Configuration));
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpSecurityHeaderMiddleware();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsOptions");
app.UseAuthorization();
app.UseMiddleware<JwtMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Api V1");
});
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IManagementServiceBase.cs
using ElectronicWallet.Common;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ElectronicWallet.Services.Contracts
{
public interface IManagementServiceBase<T,TEntity> where T: class where TEntity : class
{
public Task<T> CreateAsync(T request);
public Task<T> GetAsync(Expression<Func<TEntity, bool>> condition);
public Task<PagedResult<T>> GetAllAsync(int page, int size);
public Task<bool> UpdateAsync(T request);
public Task<bool> InactivateAsync(int id);
public Task<bool> DeleteAsync(Expression<Func<TEntity, bool>> condition);
public Task<PagedResult<T>> SearchAsync(Expression<Func<TEntity, bool>> filters, int page, int size);
public Task<bool> ExistAsync(Expression<Func<TEntity, bool>> condition);
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IWalletService.cs
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using System;
using System.Threading.Tasks;
namespace ElectronicWallet.Services.Contracts
{
public interface IWalletService: IManagementServiceBase<WalletDto, Wallet>
{
public Task<GenericResponse> CreateAndAssingWallet(Guid userId,WalletDto request);
public Task<GenericResponse> AddBalance(Guid userId, Guid walletId, decimal amount);
}
}
<file_sep>/ElectronicWallet.Entities/DTO/PaymentDto.cs
using System;
namespace ElectronicWallet.Entities.DTO
{
public class PaymentDto
{
public Guid Id { get; set; }
public Guid WalletId { get; set; }
public decimal Amount { get; set; }
public decimal Fee { get; set; }
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/UserWalletEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class UserWalletEntityConfiguration : IEntityTypeConfiguration<UserWallet>
{
public void Configure(EntityTypeBuilder<UserWallet> builder)
{
builder.HasKey(e => e.Id);
builder.HasOne(e => e.User)
.WithMany(user => user.UserWallets)
.HasForeignKey(entity => entity.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(e => e.Wallet)
.WithMany(user => user.UsersWallets)
.HasForeignKey(entity => entity.WalletId)
.OnDelete(DeleteBehavior.Cascade);
builder.Property(e => e.IsActive)
.HasDefaultValue(true)
.IsRequired();
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Middlewares/JwtMiddleware.cs
using ElectronicWallet.Common.Options;
using ElectronicWallet.Infraestructure.Enums;
using ElectronicWallet.Services.Contracts;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicWallet.Infraestructure.Middlewares
{
public class JwtMiddleware
{
private readonly RequestDelegate _next;
private readonly JwtOptions _jwtOptions;
public JwtMiddleware(RequestDelegate next, IOptions<JwtOptions> JwtOptions)
{
_next = next;
_jwtOptions = JwtOptions.Value;
}
public async Task Invoke(HttpContext context, IUserService userService)
{
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ")?.Last();
if (token != null)
await AttachUserToContextAsync(context, token, userService);
await _next(context);
}
private async Task AttachUserToContextAsync(HttpContext context, string token, IUserService userService)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtOptions.Key);
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = true,
ValidAudiences = Enum.GetNames(typeof(UserType)),
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(key)
}, out SecurityToken validatedToken);
var jwtToken = validatedToken as JwtSecurityToken;
var id = Guid.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
UserType userType = (UserType)Enum.Parse(typeof(UserType), jwtToken.Audiences.First());
// attach user to context on successful jwt validation
var user = await userService.GetAsync(x => x.Id == id);
if (!user.AccessToken.Equals(token))
throw new ArgumentException($"Invalid token. User = {id}, Token = {token}", "Access Token");
context.Items["User"] = user;
}
catch (Exception)
{
// do nothing if jwt validation fails
// user is not attached to context so request won't have access to secure routes
//_logger.LogError("Error in authentication process. Ex: {ex}", ex);
}
}
}
}
<file_sep>/ElectronicWallet.Database/DTO/Request/WalletRequest.cs
using System;
namespace ElectronicWallet.Database.DTO.Request
{
public class WalletRequest
{
public Guid CurrencyId { get; set; }
public string Name { get; set; }
}
}
<file_sep>/ElectronicWallet.Database/Seeders/WalletSeeder.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database.Seeders.Contracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace ElectronicWallet.Database.Seeders
{
public class WalletSeeder : ISeeder
{
public void Seed(IServiceProvider serviceProvider)
{
using (var context = new ElectronicWalletContext(
serviceProvider.GetRequiredService<DbContextOptions<ElectronicWalletContext>>()))
{
if (context.Wallets.Any()) return;
context.Wallets.AddRange( new Wallet[] {
CreateDefaultWallets(Guid.Parse("45D6ED41-EDB1-4219-AEAE-FE71E756DC33"), "SavingHouse", Guid.Parse("9817AB27-EDFC-4949-A897-79A928F4774F"),1000),
});
context.SaveChanges();
};
}
private Wallet CreateDefaultWallets(Guid id, string name, Guid currencyId, decimal balance)
{
return new Wallet
{
Id = id,
Name = name,
CurrencyId = currencyId,
Balance = balance,
IsActive = true
};
}
}
}
<file_sep>/ElectronicWallet.Repositories/UserRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class UserRepository: RepositoryBase<User>, IUserRepository
{
public UserRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IPaymentRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IPaymentRepository: IRepositoryBase<Payment>
{
}
}
<file_sep>/ElectronicWallet.Database/Entities/User.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database.Entities
{
public class User :EntityBase
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string AccessToken { get; set; }
public string Password { get; set; }
public DateTime? TokenExpirationDate { get; set; }
public bool IsActive { get; set; }
#region Relations
public ICollection<UserWallet> UserWallets { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/UserEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(e => e.Id);
builder.Property(e => e.Name)
.HasMaxLength(255)
.IsRequired();
builder.Property(e => e.LastName)
.HasMaxLength(255)
.IsRequired();
builder.Property(e => e.Gender)
.HasMaxLength(1)
.IsRequired();
builder.Property(e => e.Email)
.HasMaxLength(255)
.IsRequired();
builder.Property(e => e.AccessToken)
.HasMaxLength(int.MaxValue)
.IsRequired(false);
builder.Property(e => e.TokenExpirationDate)
.IsRequired(false);
builder.Property(e => e.IsActive)
.HasDefaultValue(true)
.IsRequired();
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Entities/User.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities
{
public class User :EntityBase
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string AccessToken { get; set; }
public DateTime? TokenExpirationDate { get; set; }
public bool IsActive { get; set; }
public string PasswordHash { get; set; }
public string Salt { get; set; }
#region Relations
public ICollection<UserWallet> UserWallets { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Api/Controllers/V1/UserWalletController.cs
using ElectronicWallet.Api.Model.V1;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO.Request;
using ElectronicWallet.Services.Contracts;
using ElectronicWallet.Api.CustomAttributes;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace ElectronicWallet.Api.Controllers.V1
{
[Authorize]
[ApiController]
public class UserWalletController : ControllerBase
{
private readonly IUserWalletService _userWalletService;
public UserWalletController(IUserWalletService userWalletService)
{
_userWalletService = userWalletService;
}
[HttpGet(ApiRoutes.UsersWallets.GetAll)]
public async Task<ActionResult> GetUserWalletsByUserId(Guid userId)
{
try
{
return Ok(await _userWalletService.GetWalletsByUserId(userId));
}
catch (Exception ex)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { ex.Message }
});
}
}
[HttpGet(ApiRoutes.UsersWallets.Get)]
public async Task<ActionResult> GetBalance(Guid userId,Guid walletId)
{
try
{
return Ok(await _userWalletService.GetWalletByUserIdAndWalletId(userId, walletId));
}
catch (Exception ex)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { ex.Message }
});
}
}
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IUserWalletService.cs
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ElectronicWallet.Services.Contracts
{
public interface IUserWalletService : IManagementServiceBase<UserWalletDto, UserWallet>
{
public Task<GenericResponse<List<WalletDto>>> GetWalletsByUserId(Guid userId);
public Task<GenericResponse<WalletDto>> GetWalletByUserIdAndWalletId(Guid userId, Guid walletId);
}
}
<file_sep>/ElectronicWallet.Services/PaymentService.cs
using AutoMapper;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
namespace ElectronicWallet.Services
{
public class PaymentService : ManagementServiceBase<PaymentDto, Payment>, IPaymentService
{
public PaymentService(IPaymentRepository repository,IMapper mapper):base(repository,mapper)
{
}
}
}
<file_sep>/ElectronicWallet.Entities/DTO/CurrencyDto.cs
using System;
namespace ElectronicWallet.Entities.DTO
{
public class CurrencyDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/DataInstaller.cs
using ElectronicWallet.Database;
using ElectronicWallet.Infraestructure.Installers.Contracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class DataInstaller: IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ElectronicWalletContext>(options => options.UseInMemoryDatabase("ElectronicWallet"));
}
}
}
<file_sep>/ElectronicWallet.Database/Entities/Service.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database.Entities
{
public class Service:EntityBase
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
#region Relations
public ICollection<Order> Orders { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Repositories/RepositoryBase.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Repositories.Extensions;
using ElectronicWallet.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace ElectronicWallet.Repositories
{
public abstract class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class
{
protected readonly ElectronicWalletContext Context;
public IQueryable<TEntity> Query { get; }
public RepositoryBase(ElectronicWalletContext context)
{
Context = context;
Query = context.Set<TEntity>();
}
public Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate)
{
return Query.AnyAsync(predicate);
}
public virtual Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> predicate)
{
return Query.FirstOrDefaultAsync(predicate);
}
public virtual Task<TEntity> FindFirstAsync()
{
return Query.FirstOrDefaultAsync();
}
public virtual Task<PagedResult<TEntity>> WherePaginatedAsync(
Expression<Func<TEntity, bool>> predicate, int page, int size)
{
if (Query is IQueryable<EntityBase>)
return Query
.Where(predicate)
.Cast<EntityBase>()
.OrderByDescending(x => x.UpdatedAt)
.Cast<TEntity>()
.AsNoTracking()
.ToPagedResultAsync(page, size);
return Query
.Where(predicate)
.AsNoTracking()
.ToPagedResultAsync(page, size);
}
public Task CreateAsync(params TEntity[] entities)
{
return Context.AddRangeAsync(entities);
}
public virtual Task<List<TEntity>> ReadAsync()
{
if (Query is IQueryable<EntityBase>)
return Query
.Cast<EntityBase>()
.OrderByDescending(x => x.UpdatedAt)
.Cast<TEntity>()
.AsNoTracking()
.ToListAsync();
return Query.AsNoTracking().ToListAsync();
}
public virtual Task<PagedResult<TEntity>> ReadAsync(int? page, int? size)
{
if (Query is IQueryable<EntityBase>)
return Query
.Cast<EntityBase>()
.OrderByDescending(x => x.UpdatedAt)
.Cast<TEntity>()
.AsNoTracking()
.ToPagedResultAsync(page, size);
return Query.AsNoTracking().ToPagedResultAsync(page, size);
}
public Task UpdateAsync(params TEntity[] entities)
{
Context.UpdateRange(entities);
return Task.CompletedTask;
}
public Task DeleteAsync(params TEntity[] entities)
{
Context.RemoveRange(entities);
return Task.CompletedTask;
}
public Task SaveChangesAsync()
{
return Context.SaveChangesAsync();
}
public TEntity UpdateNotNullField(TEntity entity)
{
var entry = Context.Entry(entity);
entry.State = EntityState.Modified;
Type type = typeof(TEntity);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(entity, null) == null)
{
try
{
entry.Property(property.Name).IsModified = false;
}
catch (Exception)
{ }
}
}
return entity;
}
public Task DeleteAllAsync()
{
var entityType = Context.Model.FindEntityType(typeof(TEntity));
var schema = entityType.GetSchema() ?? "public";
var tableName = entityType.GetTableName();
return Context.Database.ExecuteSqlRawAsync($"TRUNCATE TABLE {schema}.\"{tableName}\"");
}
public Task<List<TEntity>> Where(Expression<Func<TEntity, bool>> predicate)
{
return Query.Where(predicate).AsNoTracking().ToListAsync();
}
}
}
<file_sep>/ElectronicWallet.Database/DTO/Response/UserResponse.cs
using System;
namespace ElectronicWallet.Database.DTO.Response
{
public class UserResponse
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
}
}
<file_sep>/ElectronicWallet.Entities/WalletTransaction.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities
{
public class WalletTransaction: EntityBase
{
public Guid Id { get; set; }
public Guid ToWalletId { get; set; }
public Guid FromWalletId { get; set; }
public decimal Amount { get; set; }
public bool IsProccessing { get; set; }
public decimal Fee { get; set; }
#region Relations
public Wallet Wallet { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/OrderEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class OrderEntityConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(e => e.Id);
builder.HasOne(e => e.Payment)
.WithMany(user => user.Orders)
.HasForeignKey(entity => entity.PaymentId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(e => e.Service)
.WithMany(user => user.Orders)
.HasForeignKey(entity => entity.ServiceId)
.OnDelete(DeleteBehavior.Cascade);
builder.Property(e => e.OrderNumber)
.IsRequired();
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Services/Contracts/ICurrencyService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Services.Contracts
{
public interface ICurrencyService: IManagementServiceBase<CurrencyDto, Currency>
{
}
}
<file_sep>/ElectronicWallet.Database/Seeders/UserWalletSeeder.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database.Seeders.Contracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace ElectronicWallet.Database.Seeders
{
public class UserWalletSeeder : ISeeder
{
public void Seed(IServiceProvider serviceProvider)
{
using (var context = new ElectronicWalletContext(
serviceProvider.GetRequiredService<DbContextOptions<ElectronicWalletContext>>()))
{
if (context.UsersWallets.Any()) return;
context.UsersWallets.AddRange( new UserWallet[] {
CreateDefaultWallets(Guid.Parse("A2AED979-D0A6-4DE5-A8A9-50F6B1B8E41A"),
Guid.Parse("C25C298E-AD15-4DE7-9A15-B8A2B7C6923F"),
Guid.Parse("45D6ED41-EDB1-4219-AEAE-FE71E756DC33")),
});
context.SaveChanges();
};
}
private UserWallet CreateDefaultWallets(Guid id, Guid walletId, Guid userId)
{
return new UserWallet
{
Id = id,
WalletId = walletId,
UserId = userId,
IsActive = true
};
}
}
}
<file_sep>/ElectronicWallet.Common/PagedResult.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Common
{
public class PagedResult<T> where T : class
{
public int Count { get; }
public int Page { get; }
public int Size { get; }
public IEnumerable<T> Items { get; set; }
public PagedResult(int count, int? page, int? size)
{
Count = Math.Max(0, count);
Page = Math.Max(1, page ?? 1);
Size = Math.Max(1, size ?? count);
}
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IWalletTransactionRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IWalletTransactionRepository: IRepositoryBase<WalletTransaction>
{
}
}
<file_sep>/ElectronicWallet.Services/CurrencyService.cs
using AutoMapper;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
namespace ElectronicWallet.Services
{
public class CurrencyService: ManagementServiceBase<CurrencyDto, Currency>, ICurrencyService
{
public CurrencyService(ICurrencyRepository repository,IMapper mapper):base(repository,mapper)
{
}
}
}
<file_sep>/ElectronicWallet.Api/Controllers/V1/WalletController.cs
using ElectronicWallet.Api.Model.V1;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.DTO.Request;
using ElectronicWallet.Services.Contracts;
using ElectronicWallet.Api.CustomAttributes;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace ElectronicWallet.Api.Controllers.V1
{
[Authorize]
[ApiController]
public class WalletController: ControllerBase
{
private readonly IWalletService _welletService;
private readonly IUserService _userService;
private const decimal DEFAULT_BALANCE = 500;
public WalletController(IWalletService welletService, IUserService userService)
{
_welletService = welletService;
_userService = userService;
}
[HttpPost(ApiRoutes.Wallets.Create)]
public async Task<ActionResult> Create(Guid userId, [FromBody] WalletRequest request)
{
try
{
var userExist = await _userService.ExistAsync(x => x.Id == userId);
if(!userExist)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { "User not found." }
});
}
if (request is null)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { "Error try again." }
});
}
var walletDto = new WalletDto
{
Balance = DEFAULT_BALANCE, //default
Name = request.Name,
CurrencyId = request.CurrencyId
};
var response = await _welletService.CreateAndAssingWallet(userId, walletDto);
return Ok(response);
}
catch (Exception ex)
{
return BadRequest(new GenericResponse {
Success = false,
Errors = new string [] { ex.Message }
});
}
}
[HttpPost(ApiRoutes.Wallets.AddBalance)]
public async Task<ActionResult> AddBalance(Guid walletId, Guid userId, [FromBody] AddBalanceRequest balance)
{
try
{
if (balance is null)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { "balance could not be added." }
});
}
var userWallet = await _welletService.AddBalance(userId, walletId, balance.Amount);
if (userWallet.Success)
{
return Ok(new GenericResponse());
}
return BadRequest(new GenericResponse(false, errors: new string[] { "balance could not be added." }));
}
catch (Exception)
{
return BadRequest(new GenericResponse
{
Success = false,
Errors = new string[] { "Error" }
});
}
}
}
}
<file_sep>/ElectronicWallet.Api/Controllers/V1/UserController.cs
using ElectronicWallet.Api.Model.V1;
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Services.Contracts;
using ElectronicWallet.Api.CustomAttributes;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using ElectronicWallet.Database.DTO.Request;
using AutoMapper;
using ElectronicWallet.Database.DTO.Response;
namespace ElectronicWallet.Api.Controllers.V1
{
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly IMapper _mapper;
public UserController(IUserService userService, IMapper mapper)
{
_userService = userService;
_mapper = mapper;
}
[Authorize]
[HttpGet(ApiRoutes.Users.Get)]
public async Task<ActionResult> Get(Guid userId)
{
return Ok(new GenericResponse<UserDto>(await _userService.GetAsync(x => x.Id == userId)));
}
[HttpPost(ApiRoutes.Users.Create)]
public async Task<ActionResult> Create([FromBody] UserCreateRequest request)
{
if (request is null)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "No data" }
});
}
var userExist = await _userService.ExistAsync(x => x.Email == request.Email);
if (userExist)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "User register." }
});
}
try
{
var user = new UserDto()
{
Gender = request.Gender.ToUpper(),
LastName = request.LastName,
Name = request.Name,
Email = request.Email,
//Password = request.Password
};
var userCreated = await _userService.CreateAsync(user);
if (userCreated == null)
{
return Ok(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "Error creating the user." }
});
}
return Ok(new GenericResponse<UserResponse>(_mapper.Map<UserResponse>(user)));
}
catch (Exception ex)
{
return BadRequest(new GenericResponse()
{
Success = false,
Errors = new[] { ex.Message }
});
}
}
[Authorize]
[HttpPut(ApiRoutes.Users.Update)]
public async Task<ActionResult> Update(Guid userId, [FromBody] UserUpdateRequest request)
{
if (string.IsNullOrEmpty(userId.ToString()))
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "UserId Empty" }
});
}
var userExist = await _userService.GetAsync(x => x.Id == userId);
if (userExist == null)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "User not exist." }
});
}
var user = new UserDto()
{
Id = userId,
Gender = request.Gender,
LastName = request.LastName,
Name = request.Name,
AccessToken = userExist.AccessToken,
Email = request.Email,
TokenExpirationDate = userExist.TokenExpirationDate
};
var updated = await _userService.UpdateAsync(user);
if (updated)
{
return Ok(new GenericResponse<UserDto>
{
Message = "User updated"
});
}
return Ok(new GenericResponse<UserDto>
{
Success = false,
Errors = new[] { "User not updated try again or contact the administration." }
});
}
[Authorize]
[HttpDelete(ApiRoutes.Users.Delete)]
public async Task<ActionResult> Delete(Guid userId)
{
var userExist = await _userService.ExistAsync(x => x.Id == userId);
if (!userExist)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "User not exist." }
});
}
var user = await _userService.GetAsync(x => x.Id == userId);
var deleted = await _userService.DeleteAsync(x => x.Id == userId);
if (deleted)
{
return Ok(new GenericResponse<UserDto>
{
Message = "User deleted"
});
}
return BadRequest(new GenericResponse<UserDto>
{
Success = false,
Errors = new[] { "User cannot be delete, please contact the administration." }
});
}
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/ServiceEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class ServiceEntityConfiguration : IEntityTypeConfiguration<Service>
{
public void Configure(EntityTypeBuilder<Service> builder)
{
builder.HasKey(e => e.Id);
builder.Property(e => e.Name)
.HasMaxLength(100)
.IsRequired();
builder.Property(e => e.IsActive)
.HasDefaultValue(true)
.IsRequired();
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Database/DTO/ServiceDto.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database.DTO
{
public class ServiceDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
#region Relations
public ICollection<OrderDto> Orders { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/CurrencyEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class CurrencyEntityConfiguration : IEntityTypeConfiguration<Currency>
{
public void Configure(EntityTypeBuilder<Currency> builder)
{
builder.HasKey(e => e.Id);
builder.Property(e => e.Name)
.HasMaxLength(100)
.IsRequired();
builder.Property(e => e.Abbreviation)
.HasMaxLength(4)
.IsRequired(false);
builder.Property(e => e.IsActive)
.HasDefaultValue(true)
.IsRequired();
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Entities/DTO/UserDto.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities.DTO
{
public class UserDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string AccessToken { get; set; }
public DateTime? TokenExpirationDate { get; set; }
public bool IsActive { get; set; }
public string PasswordHash { get; set; }
public string Salt { get; set; }
}
}
<file_sep>/ElectronicWallet.Infraestructure/Middlewares/ExceptionHandler.cs
using System;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace ElectronicWallet.Infraestructure.Middlewares
{
public class ExceptionHandler : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
SetExceptionResult(context, exception);
context.ExceptionHandled = true;
}
private void SetExceptionResult(
ExceptionContext context,
Exception exception,
HttpStatusCode statusCode = HttpStatusCode.BadRequest)
{
var result = new JsonResult(new
{
error = exception.Message
});
context.Result = result;
context.HttpContext.Response.StatusCode = (int)statusCode;
}
}
}<file_sep>/ElectronicWallet.Database/Entities/Currency.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database.Entities
{
public class Currency: EntityBase
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
#region Relations
public ICollection<Wallet> Wallets { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Repositories/UserWalletRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class UserWalletRepository: RepositoryBase<UserWallet>, IUserWalletRepository
{
public UserWalletRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Entities/DTO/UserWalletDto.cs
using System;
namespace ElectronicWallet.Entities.DTO
{
public class UserWalletDto
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Guid WalletID { get; set; }
public bool IsActive { get; set; }
}
}
<file_sep>/ElectronicWallet.Database/DTO/WalletDto.cs
using System;
namespace ElectronicWallet.Database.DTO
{
public class WalletDto
{
public Guid Id { get; set; }
public Guid CurrencyId { get; set; }
public decimal Balance { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
#region Relations
#endregion
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IOrderService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Services.Contracts
{
public interface IOrderService: IManagementServiceBase<OrderDto, Order>
{
}
}
<file_sep>/ElectronicWallet.Entities/DTO/WalletDto.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities.DTO
{
public class WalletDto
{
public Guid Id { get; set; }
public Guid CurrencyId { get; set; }
public decimal Balance { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
}
}
<file_sep>/ElectronicWallet.Services/Contracts/IServiceService.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Services.Contracts
{
public interface IServiceService: IManagementServiceBase<ServiceDto, Service>
{
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/ICurrencyRepository.cs
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface ICurrencyRepository: IRepositoryBase<Currency>
{
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/CommonInstaller.cs
using ElectronicWallet.Common.Options;
using ElectronicWallet.Infraestructure.Installers.Contracts;
using ElectronicWallet.Infraestructure.Middlewares;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class CommonInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddTransient<HttpSecurityHeaderMiddleware>();
services.Configure<JwtOptions>(options =>
{
configuration.Bind("Authentication:Jwt", options);
});
}
}
}
<file_sep>/ElectronicWallet.Repositories/PaymentRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class PaymentRepository: RepositoryBase<Payment>, IPaymentRepository
{
public PaymentRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IRepositoryBase.cs
using ElectronicWallet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IRepositoryBase<TEntity> where TEntity : class
{
public IQueryable<TEntity> Query { get; }
public Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate);
public Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> predicate);
public Task<TEntity> FindFirstAsync();
public Task<PagedResult<TEntity>> WherePaginatedAsync(Expression<Func<TEntity, bool>> predicate, int page, int size);
public Task CreateAsync(params TEntity[] entities);
public Task<List<TEntity>> ReadAsync();
public Task<List<TEntity>> Where(Expression<Func<TEntity, bool>> predicate);
public Task<PagedResult<TEntity>> ReadAsync(int? page, int? size);
public Task UpdateAsync(params TEntity[] entities);
public Task DeleteAsync(params TEntity[] entities);
public Task SaveChangesAsync();
public TEntity UpdateNotNullField(TEntity entity);
public Task DeleteAllAsync();
}
}
<file_sep>/ElectronicWallet.Database/DTO/Request/UserCreateRequest.cs
namespace ElectronicWallet.Database.DTO.Request
{
public class UserCreateRequest
{
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
<file_sep>/ElectronicWallet.Services/OrderService.cs
using AutoMapper;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
namespace ElectronicWallet.Services
{
public class OrderService : ManagementServiceBase<OrderDto, Order>, IOrderService
{
public OrderService(IOrderRepository repository,IMapper mapper):base(repository,mapper)
{
}
}
}
<file_sep>/ElectronicWallet.Repositories/OrderRepository.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class OrderRepository: RepositoryBase<Order>, IOrderRepository
{
public OrderRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Repositories/CurrencyRepository.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
namespace ElectronicWallet.Repositories
{
public class CurrencyRepository : RepositoryBase<Currency>, ICurrencyRepository
{
public CurrencyRepository(ElectronicWalletContext context): base (context)
{
}
}
}
<file_sep>/ElectronicWallet.Services/ServiceService.cs
using AutoMapper;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Services.Contracts;
namespace ElectronicWallet.Services
{
public class ServiceService : ManagementServiceBase<ServiceDto, Service>, IServiceService
{
public ServiceService(IServiceRepository repository,IMapper mapper):base(repository,mapper)
{
}
}
}
<file_sep>/ElectronicWallet.Database/ElectronicWalletContext.cs
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Database.Seeders;
using ElectronicWallet.Database.Seeders.Contracts;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Database
{
public class ElectronicWalletContext: DbContext
{
public ElectronicWalletContext(DbContextOptions<ElectronicWalletContext> options):base(options) { }
#region Tables
public DbSet<UserWallet> UsersWallets { get; set; }
public DbSet<Currency> Currencies { get; set; }
public DbSet<WalletTransaction> WalletTransactions { get; set; }
public DbSet<Wallet> Wallets { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Service> Services { get; set; }
public DbSet<User> Users { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Database/DTO/UserDto.cs
using System;
namespace ElectronicWallet.Database.DTO
{
public class UserDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string AccessToken { get; set; }
public DateTime? TokenExpirationDate { get; set; }
public bool IsActive { get; set; }
}
}
<file_sep>/ElectronicWallet.Entities/Wallet.cs
using System;
using System.Collections.Generic;
namespace ElectronicWallet.Entities
{
public class Wallet: EntityBase
{
public Guid Id { get; set; }
public Guid CurrencyId { get; set; }
public decimal Balance { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDeleted { get; set; }
#region Relations
public ICollection<Payment> Payments { get; set; }
public ICollection<UserWallet> UsersWallets { get; set; }
public ICollection<WalletTransaction> WalletTransactions { get; set; }
public Currency Currency { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IServiceRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IServiceRepository: IRepositoryBase<Service>
{
}
}
<file_sep>/ElectronicWallet.Services/ManagementServiceBase.cs
using AutoMapper;
using AutoMapper.Internal;
using ElectronicWallet.Database.Entities;
using ElectronicWallet.Repositories.Contracts;
using ElectronicWallet.Common;
using ElectronicWallet.Services.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ElectronicWallet.Services
{
public abstract class ManagementServiceBase<T, TEntity> : IManagementServiceBase<T, TEntity> where T : class where TEntity : class
{
protected readonly IRepositoryBase<TEntity> Repository;
protected readonly IMapper Mapper;
public virtual string IdPropertyName => nameof(User.Id);
public virtual string InactivatePropertyName => nameof(User.IsActive);
public ManagementServiceBase(IRepositoryBase<TEntity> repository, IMapper mapper)
{
Repository = repository;
Mapper = mapper;
}
public virtual async Task<T> CreateAsync(T request)
{
if (request == null) return null;
T result = null;
try
{
var entity = Mapper.Map<TEntity>(request);
//auditory data
if (entity is EntityBase _entity)
{
//_entity.CreatedBy = _entity.ModifiedBy = RequestUtils.GetUserEmail();
_entity.CreatedAt = _entity.CreatedAt = DateTime.UtcNow;
SetAuditoryDataToInternalEntitiesProperties(_entity, true);
}
await Repository.CreateAsync(entity);
await Repository.SaveChangesAsync();
result = request;
var id = GetIdValue(entity);
result.GetType().GetProperty(IdPropertyName).SetValue(result, id);
}
catch (Exception ex)
{
Console.WriteLine("Error creating entity. Entity = {name}, Request = {request}, Exception: {ex}", typeof(TEntity).Name, request, ex);
}
return result;
}
public virtual async Task<PagedResult<T>> GetAllAsync(int page, int size)
{
PagedResult<T> result = null;
try
{
var entities = await Repository.ReadAsync(page, size);
result = Mapper.Map<PagedResult<T>>(entities);
}
catch (Exception ex)
{
Console.WriteLine("Error getting all entities. Entity = {name}, Page = {page}, Size = {size}, Exception: {ex}", typeof(TEntity).Name, page, size, ex);
}
return result;
}
public virtual async Task<T> GetAsync(Expression<Func<TEntity, bool>> condition)
{
if (condition == null) return null;
T result = null;
try
{
var entity = await GetEntityByProperty(condition);
result = Mapper.Map<T>(entity);
}
catch (Exception ex)
{
Console.WriteLine("Error getting entity by property. Entity = {name}, Condition = {condition}, Exception: {ex}", typeof(TEntity).Name, condition, ex);
}
return result;
}
public virtual async Task<bool> InactivateAsync(int id)
{
if (id == default) return false;
bool success = false;
try
{
var condition = CreateEntityByPropertyCondition(IdPropertyName, id);
var entity = await GetEntityByProperty(condition);
var property = entity.GetType().GetProperty(InactivatePropertyName);
property.SetValue(entity, false);
//auditory data
if (entity is EntityBase _entity)
{
//_entity.ModifiedBy = RequestUtils.GetUserEmail();
_entity.UpdatedAt = DateTime.UtcNow;
SetAuditoryDataToInternalEntitiesProperties(_entity);
}
await Repository.UpdateAsync(entity);
await Repository.SaveChangesAsync();
success = true;
}
catch (Exception ex)
{
Console.WriteLine("Error inactivating entity. Entity = {name}, Id = {id}, Exception: {ex}", typeof(TEntity).Name, id, ex);
}
return success;
}
public virtual async Task<PagedResult<T>> SearchAsync(Expression<Func<TEntity, bool>> filters, int page, int size)
{
if (filters == null) return null;
PagedResult<T> result = null;
try
{
var entities = await Repository.WherePaginatedAsync(filters, Math.Abs(page), Math.Abs(size));
result = Mapper.Map<PagedResult<T>>(entities);
}
catch (Exception ex)
{
Console.WriteLine("Error searching entities. Entity = {name}, Filters = {filters}, Page = {page}, Size = {size}, Exception: {ex}", typeof(TEntity).Name, filters, page, size, ex);
}
return result;
}
public virtual async Task<bool> UpdateAsync(T request)
{
if (request == null) return false;
bool success = false;
try
{
var id = GetIdValue(request);
var condition = CreateEntityByPropertyCondition(IdPropertyName, id);
var entity = await GetEntityByProperty(condition);
entity = Mapper.Map(request, entity);
//auditory data
if (entity is EntityBase _entity)
{
//_entity.ModifiedBy = RequestUtils.GetUserEmail();
_entity.UpdatedAt = DateTime.UtcNow;
SetAuditoryDataToInternalEntitiesProperties(_entity);
}
await Repository.UpdateAsync(entity);
await Repository.SaveChangesAsync();
success = true;
}
catch (Exception ex)
{
Console.WriteLine("Error updating entity. Entity = {name}, Request = {request}, Exception: {ex}", typeof(TEntity).Name, request, ex);
}
return success;
}
public virtual async Task<bool> DeleteAsync(Expression<Func<TEntity, bool>> condition)
{
if (condition == null) return false;
bool success = true;
try
{
var entity = await GetEntityByProperty(condition);
await Repository.DeleteAsync(entity);
await Repository.SaveChangesAsync();
}
catch (Exception ex)
{
success = false;
Console.WriteLine("Error deleting entity. Entity = {name}, Condition = {condition}, Exception: {ex}", typeof(TEntity).Name, condition, ex);
}
return success;
}
public async Task<bool> ExistAsync(Expression<Func<TEntity, bool>> condition)
{
if (condition == null) return false;
bool exist = false;
try
{
exist = await Repository.ExistsAsync(condition);
}
catch (Exception ex)
{
Console.WriteLine("Error checking if entity exist. Entity = {name}, Condition = {condition}, Exception: {ex}", typeof(TEntity).Name, condition, ex);
}
return exist;
}
private async Task<TEntity> GetEntityByProperty(Expression<Func<TEntity, bool>> condition)
{
if (condition == null) return null;
TEntity entity = null;
try
{
entity = await Repository.FindAsync(condition);
}
catch (Exception ex)
{
Console.WriteLine("Error getting entity by property. Entity = {name}, Condition = {condition}, Exception: {ex}", typeof(TEntity).Name, condition, ex);
}
return entity;
}
private Expression<Func<TEntity, bool>> CreateEntityByPropertyCondition(string propertyName, object propertyValue)
{
var param = Expression.Parameter(typeof(TEntity));
var condition = Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal
(
Expression.Property(param, propertyName),
Expression.Constant(propertyValue, propertyValue.GetType())
),
param);
return condition;
}
private object GetIdValue(object source) => source.GetType().GetProperty(IdPropertyName).GetValue(source);
private void SetAuditoryDataToInternalEntitiesProperties(EntityBase entity, bool isCreating = false)
{
var entityProperties = entity.GetType().GetProperties().Where(x => x.PropertyType.IsNonStringEnumerable());
if (entityProperties == null || entityProperties.Count() == 0) return;
foreach (var entityProperty in entityProperties)
{
var entityPropertyValues = entityProperty?.GetValue(entity) as IEnumerable<EntityBase>;
entityPropertyValues?.ToList().ForEach(x =>
{
if (isCreating)
{
x.CreatedBy = entity.CreatedBy;
x.CreatedAt = entity.CreatedAt;
}
x.ModifiedBy = entity.ModifiedBy;
x.UpdatedAt = entity.UpdatedAt;
SetAuditoryDataToInternalEntitiesProperties(x, isCreating);
});
}
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/SwaggerInstaller.cs
using ElectronicWallet.Infraestructure.Installers.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System.Collections.Generic;
namespace ElectronicWallet.Infraestructure.Installers
{
public class SwaggerInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "ElectronicWallet.Api v1", Version = "v1" });
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference =new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer"}
},
new List<string>()
}
});
});
services.AddSwaggerGenNewtonsoftSupport();
}
}
}
<file_sep>/ElectronicWallet.Infraestructure/Installers/RepositoryInstaller.cs
using ElectronicWallet.Infraestructure.Installers.Contracts;
using ElectronicWallet.Repositories;
using ElectronicWallet.Repositories.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ElectronicWallet.Infraestructure.Installers
{
public class RepositoryInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<ICurrencyRepository, CurrencyRepository>();
services.AddScoped<IUserWalletRepository, UserWalletRepository>();
services.AddScoped<IWalletRepository, WalletRepository>();
services.AddScoped<IWalletTransactionRepository, WalletTransactionRepository>();
services.AddScoped<IPaymentRepository, PaymentRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IServiceRepository, ServiceRepository>();
services.AddScoped<IUserRepository, UserRepository>();
}
}
}
<file_sep>/ElectronicWallet.Repositories/Contracts/IWalletRepository.cs
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Repositories.Contracts
{
public interface IWalletRepository: IRepositoryBase<Wallet>
{
}
}
<file_sep>/ElectronicWallet.Database/Seeders/Contracts/ISeeder.cs
using System;
namespace ElectronicWallet.Database.Seeders.Contracts
{
public interface ISeeder
{
public void Seed(IServiceProvider serviceProvider);
}
}
<file_sep>/ElectronicWallet.Api/Program.cs
using ElectronicWallet.Database;
using ElectronicWallet.Database.Seeders;
using ElectronicWallet.Database.Seeders.Contracts;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
namespace ElectronicWallet.Api
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
//1 Find the service layer within our scope.
using (var scope = host.Services.CreateScope())
{
//2 Get the instance of ElectronicWalletContext in our services layer
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ElectronicWalletContext>();
//3 Call the Seed to create sample data
var seeders = new List<ISeeder>{
new UserSeeder(),
new WalletSeeder(),
new UserWalletSeeder()
};
foreach (var seeder in seeders)
{
seeder.Seed(services);
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/Profile/AutoMapperDefaultProfile.cs
using ElectronicWallet.Common;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.DTO.Response;
using ElectronicWallet.Database.Entities;
namespace ElectronicWallet.Database.EntitiesConfigurations.Profile
{
public class AutoMapperDefaultProfile: AutoMapper.Profile
{
public AutoMapperDefaultProfile(): this("GlobalElectronicWallet")
{
}
public AutoMapperDefaultProfile(string profileName) : base(profileName)
{
CreateMap<User,UserDto>().ReverseMap();
CreateMap<Wallet, WalletDto>().ReverseMap();
CreateMap<WalletTransaction, WalletTransactionDto>().ReverseMap();
CreateMap<Order, OrderDto>().ReverseMap();
CreateMap<Service, ServiceDto>().ReverseMap();
CreateMap<Payment, PaymentDto>().ReverseMap();
CreateMap<UserWallet, UserWalletDto>().ReverseMap();
CreateMap<Currency, CurrencyDto>().ReverseMap();
CreateMap<PagedResult<User>, PagedResult<UserDto>>().ReverseMap();
CreateMap<PagedResult<Wallet>, PagedResult<WalletDto>>().ReverseMap();
CreateMap<PagedResult<WalletTransaction>, PagedResult<WalletTransactionDto>>().ReverseMap();
CreateMap<PagedResult<Order>, PagedResult<OrderDto>>().ReverseMap();
CreateMap<PagedResult<Service>, PagedResult<ServiceDto>>().ReverseMap();
CreateMap<PagedResult<Payment>, PagedResult<PaymentDto>>().ReverseMap();
CreateMap<PagedResult<UserWallet>, PagedResult<UserWalletDto>> ().ReverseMap();
CreateMap<PagedResult<Currency>, PagedResult<CurrencyDto>>().ReverseMap();
CreateMap<UserDto, UserResponse>().ReverseMap();
}
}
}
<file_sep>/README.md
# ElectronicWallet
1- If you use visual studio community/ enterprices open the .sln and buid and run the project with will be opened direclty in the swegger page.
# COMMAND Line execution
1 - insite the ElectronicWallet/ElectronicWallet.Api run dotnet run, and use the localhost:5000/swagger or https localhost:5001/swagger, and paste on postman or use swgger directly
# Credentials
email: <EMAIL>
password: <PASSWORD>
email: <EMAIL>
password: <PASSWORD>
<file_sep>/ElectronicWallet.Database/DTO/WalletTransactionDto.cs
using System;
namespace ElectronicWallet.Database.DTO
{
public class WalletTransactionDto
{
public Guid Id { get; set; }
public Guid ToWalletId { get; set; }
public Guid FromWalletId { get; set; }
public decimal Amount { get; set; }
public bool IsProccessing { get; set; }
public decimal Fee { get; set; }
#region Relations
public WalletDto Wallet { get; set; }
#endregion
}
}
<file_sep>/ElectronicWallet.Database/EntitiesConfigurations/WalletTransactionEntityConfiguration.cs
using ElectronicWallet.Database.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ElectronicWallet.Database.EntitiesConfigurations
{
public class WalletTransactionEntityConfiguration : IEntityTypeConfiguration<WalletTransaction>
{
public void Configure(EntityTypeBuilder<WalletTransaction> builder)
{
builder.HasKey(e => e.Id);
builder.HasOne(e => e.Wallet)
.WithMany(user => user.WalletTransactions)
.HasForeignKey(entity => entity.ToWalletId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(e => e.Wallet)
.WithMany(user => user.WalletTransactions)
.HasForeignKey(entity => entity.FromWalletId)
.OnDelete(DeleteBehavior.Cascade);
builder.Property(e => e.Amount)
.IsRequired();
builder.Property(e => e.IsProccessing)
.HasDefaultValue(true)
.IsRequired();
builder.Property(e => e.Fee)
.HasDefaultValue(0)
.IsRequired(true);
#region Audition
builder.Property(e => e.CreatedBy)
.IsRequired();
builder.Property(e => e.UpdatedAt)
.IsRequired(false);
builder.Property(e => e.CreatedAt)
.HasDefaultValue(new System.DateTime())
.IsRequired(true);
builder.Property(e => e.ModifiedBy)
.IsRequired();
#endregion
}
}
}
<file_sep>/ElectronicWallet.Api/Controllers/V1/AuthenticationController.cs
using ElectronicWallet.Api.CustomAttributes;
using ElectronicWallet.Api.Model.V1;
using ElectronicWallet.Common;
using ElectronicWallet.Common.Options;
using ElectronicWallet.Database.DTO;
using ElectronicWallet.Database.DTO.Request;
using ElectronicWallet.Infraestructure.Enums;
using ElectronicWallet.Services.Contracts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicWallet.Api.Controllers.V1
{
[ApiController]
public class AuthenticationController: ControllerBase
{
private readonly IUserService _userService;
private readonly JwtOptions _jwtOptions;
private new UserDto User => HttpContext.Items["User"] as UserDto;
public AuthenticationController(IUserService userService, IOptions<JwtOptions> jwtOptions)
{
_userService = userService;
_jwtOptions = jwtOptions.Value;
}
[HttpPost(ApiRoutes.Authentication.Login)]
public async Task<ActionResult> Login([FromBody] LoginRequest login)
{
if (login is null)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "No data" }
});
}
if (string.IsNullOrEmpty(login.Email) || string.IsNullOrEmpty(login.Password))
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "Email or password invalid." }
});
}
var user = await _userService.GetByEmailAndPassword(login.Email, login.Password);
if(user == null)
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "Email or password invalid." }
});
}
//Create JWT
user = CreateJwt(user);
if (string.IsNullOrEmpty(user.AccessToken))
{
return BadRequest(new GenericResponse<UserDto>()
{
Success = false,
Errors = new[] { "Error creating the token." }
});
}
HttpContext.Items["User"] = user;
var updated = await _userService.UpdateAsync(user);
if(updated)
{
return Ok(new GenericResponse<UserDto>(user));
}
return BadRequest(new GenericResponse(false,errors: new string[] { "Login error, contact the admin." }) );
}
[Authorize]
[HttpPost(ApiRoutes.Authentication.LogOut)]
public async Task<ActionResult> Logout()
{
User.TokenExpirationDate = null;
User.AccessToken = null;
var updated = await _userService.UpdateAsync(User);
if (!updated)
{
return BadRequest(new GenericResponse<UserDto>
{
Success = false,
Errors = new string[]
{
"Error closing trying to logout."
}
});
}
return Ok(new GenericResponse<UserDto>
{
Success = true
});
}
private UserDto CreateJwt(UserDto user)
{
try
{
var now = DateTimeOffset.Now.DateTime;
user.TokenExpirationDate = now.AddDays(1);
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Key));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim("id", user.Id.ToString()),
new Claim("name", user.Name),
new Claim("last_name", user.LastName),
new Claim("email", user.Email)
};
if (user.Gender != null) claims.Add(new Claim("gender", user.Gender.ToString()));
var jwtSecurityToken = new JwtSecurityToken(
audience: Enum.GetName(typeof(UserType), UserType.User),
claims: claims,
notBefore: now,
expires: user.TokenExpirationDate,
signingCredentials: signingCredentials
);
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var token = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
user.AccessToken = token;
}
catch (Exception ex)
{
Console.WriteLine("Error creating token. User Id = {id} Exception = {ex}", user?.Id, ex);
}
return user;
}
}
}
|
909ab4ae978ccfd853da92158dd1f2e5e6ccac3f
|
[
"Markdown",
"C#"
] | 99
|
C#
|
vebg/ElectronicWallet
|
a75025dfb3027cc9bc7e80bf1f92cec6acfea010
|
65c5f82c3034eb384d47e49dbbcb064c5a574e05
|
refs/heads/master
|
<file_sep>#include "route_planner.h"
#include <algorithm>
RoutePlanner::RoutePlanner(RouteModel &model, float start_x, float start_y, float end_x, float end_y): m_Model(model) {
// Convert inputs to percentage.
start_x *= 0.01;
start_y *= 0.01;
end_x *= 0.01;
end_y *= 0.01;
// Using the m_Model.FindClosestNode method to find the closest nodes to the starting and ending coordinates.
// Storing the found nodes in the RoutePlanner's start_node and end_node attributes.
this->start_node = &model.FindClosestNode(start_x, start_y);
this->end_node = &model.FindClosestNode(end_x, end_y);
}
// CalculateHValue method calculates the h value for the given node.
// - It uses the distance to the end_node.
// - Note: Node objects have a distance method to determine the distance to another node.
float RoutePlanner::CalculateHValue(RouteModel::Node const *node) {
return node->distance(*end_node);
}
// AddNeighbors method expands the current node by adding all unvisited neighbors to the open list.
// - It uses the FindNeighbors() method of the current_node to populate current_node.neighbors vector with all the neighbors.
// - For each node in current_node.neighbors,it then sets the parent, the h_value, the g_value.
// - It also used the CalculateHValue to implement the h-Value calculation.
// - Finally, for each node in current_node.neighbors, it adds the neighbor to open_list and set the node's visited attribute to true.
void RoutePlanner::AddNeighbors(RouteModel::Node *current_node) {
current_node->FindNeighbors();
float current_g = current_node->g_value;
current_node->visited = true;
for (int i = 0; i < current_node->neighbors.size(); i++) {
RouteModel::Node *neighbor = current_node->neighbors[i];
neighbor->parent = current_node;
neighbor->g_value = current_g + neighbor->distance(*current_node);
neighbor->h_value = CalculateHValue(neighbor);
open_list.push_back(neighbor);
neighbor->visited = true;
}
}
// NextNode method sorts the open list and return the next node.
// - It sorts the open_list according to the sum of the h value and g value.
// - It then creates a pointer to the node in the list with the lowest sum
// and removes that node from the open_list.
// - Finaly it returns the pointer.
float Compare(RouteModel::Node* a, RouteModel::Node* b) {
float f1 = a->g_value + a->h_value;
float f2 = b->g_value + b->h_value;
return f1 > f2;
}
RouteModel::Node *RoutePlanner::NextNode() {
sort(this->open_list.begin(), this->open_list.end(), Compare);
RouteModel::Node* next = open_list.back();
return next;
}
// ConstructFinalPath method returns the final path found from the A* search.
// - This method takes the current (final) node as the argument and iteratively follow the
// chain of parents of nodes until the starting node is found.
// - For each node in the chain, it adds the distance from the node to its parent to the distance variable.
// - The returned vector will be reveres to be in the correct order: the start node should be the first element
// of the vector, the end node should be the last element.
std::vector<RouteModel::Node> RoutePlanner::ConstructFinalPath(RouteModel::Node *current_node) {
// Create path_found vector
distance = 0.0f;
std::vector<RouteModel::Node> path_found;
while(current_node->x != this->start_node->x && current_node->y != this->start_node->y){
path_found.push_back(*current_node);
distance += current_node->distance(*current_node->parent);
current_node = current_node->parent;
}
path_found.push_back(*current_node);
std::reverse(path_found.begin(), path_found.end());
distance *= m_Model.MetricScale(); // Multiply the distance by the scale of the map to get meters.
return path_found;
}
// The A* Search algorithm calculates the path from the start to the end node. It also calcualtes the distace between them.
// - This function uses the AddNeighbors method to add all of the neighbors of the current node to the open_list.
// - It then uses the NextNode() method to sort the open_list and return the next node.
// - When the search has reached the end_node, the function uses the ConstructFinalPath method to return the final path that was found.
// - Finally, it stores the final path in the m_Model.path attribute before the method exits. This path will then be displayed on the map tile.
void RoutePlanner::AStarSearch() {
RouteModel::Node *current_node = nullptr;
this->open_list.push_back(this->start_node);
while(this->open_list.size() > 0) {
current_node = this->NextNode();
this->open_list.pop_back();
if (current_node->x == this->end_node->x && current_node->y == this->end_node->y) {
m_Model.path = ConstructFinalPath(current_node);
break;
}
AddNeighbors(current_node);
}
}<file_sep># Street Route Planning
This project uses real map data and [A* search algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm) to find a path between two points, just as you might see in a desktop or mobile mapping application. The project uses data from the [OpenStreetMap](https://www.openstreetmap.org/) open source project. Maps of this project are completely generated by individuals who volunteer to perform ground surveys of their local environment.
## Demo

## Cloning
When cloning this project, be sure to use the `--recurse-submodules` flag to import sub modules.
```
git clone https://github.com/imehrdadmahdavi/street-route-planner.git --recurse-submodules
```
## Dependencies
* cmake 3.11.3+
* All OSes: [click here for installation instructions](https://cmake.org/install/)
* make 4.1+ (Linux, Mac), 3.81 (Windows)
* Linux: make is installed by default on most Linux distros
* Mac: [install Xcode command line tools to get make](https://developer.apple.com/xcode/features/)
* Windows: [Click here for installation instructions](http://gnuwin32.sourceforge.net/packages/make.htm)
* gcc/g++ 7.4.0+
* Linux: gcc/g++ is installed by default on most Linux distros
* Mac: same instructions as make - [install Xcode command line tools](https://developer.apple.com/xcode/features/)
* Windows: recommend using [MinGW](http://www.mingw.org/)
* IO2D (P0267)
* Installation instructions for all operating systems can be found [here](https://github.com/cpp-io2d/P0267_RefImpl/blob/master/BUILDING.md)
* This library must be built in a place where CMake `find_package` will be able to find it
This project was built and tested on an Ubuntu 18.04 machine. To install all of the above dependencies in Ubuntu, run the below commands in the Home directory:
```
sudo apt update
sudo apt install build-essential
sudo apt install cmake
sudo apt install libcairo2-dev
sudo apt install libgraphicsmagick1-dev
sudo apt install libpng-dev
git clone --recurse-submodules https://github.com/cpp-io2d/P0267_RefImpl
cd P0267_RefImpl
mkdir Debug
cd Debug
cmake --config Debug "-DCMAKE_BUILD_TYPE=Debug" ..
cmake --build .
sudo make install
```
## Compiling and Running
### Compiling
To compile the project, first, create a `build` directory in the project folder and change to that directory:
```
mkdir build && cd build
```
From within the `build` directory, then run `cmake` and `make` as follows:
```
cmake ..
make
```
### Running
The executable will be placed in the `build` directory. From within `build`, you can run the project as follows:
```
./OSM_A_star_search
[Enter Input Arguments]
```
Input arguments should be in the [s_x s_y e_x e_y] format which represent x and y coordinates of the starting and ending points of our search. Each value should also be between 0 and 100.
You can specify a map file as below (optional):
```
./OSM_A_star_search -f ../<your_osm_file.osm>
```
## Testing
The testing executable is also placed in the `build` directory. From within `build`, you can run the unit tests as follows:
```
./test
```
## Code Strucutre

|
76126bb5d1deebca9dd827a8a5864c54d14e2fa0
|
[
"Markdown",
"C++"
] | 2
|
C++
|
ayomide-adekunle/street-route-planner-1
|
d6e804be670954e383c37bdc0b2e574a7d7d5ef0
|
8d636d038460b16eb5b757f9d023646c0b092bc6
|
refs/heads/master
|
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
int kgetpid()
{
return running->pid;
}
int kgetppid()
{
return running->ppid;
}
char *pstatus[]={"FREE ","READY ","SLEEP ","BLOCK ","ZOMBIE", " RUN "};
int kps()
{
int i; PROC *p;
for (i=0; i<NPROC; i++){
p = &proc[i];
kprintf("proc[%d]: pid=%d ppid=%d", i, p->pid, p->ppid);
if (p==running)
printf("%s ", pstatus[5]);
else
printf("%s", pstatus[p->status]);
printf("name=%s\n", p->name);
}
}
int kchname(char *s)
{
kprintf("kchname: name=%s\n", s);
strcpy(running->name, s);
return 123;
}
int ktswitch()
{
tswitch();
}
int kgetPA()
{
return running->pgdir[2048] & 0xFFFF0000;
}
int kkfork()
{ /// Only loads U1
printf("[ ENTERED KFORK HELPER FUNCTION ]\n");
PROC *p = kfork("u1");
if (p)
return p->pid;
return -1;
}
int kkwait() {
printf("[ ENTERED KWAIT HELPER FUNCTION ]\n");
kwait(running->status);
}
int kkexit() {
printf("[ ENTERED KEXIT HELPER FUNCTION ]\n");
kexit(running->pid);
}
int kksleep() {
printf("[ ENTERED KSLEEP HELPER FUNCTION ]\n");
int e;
printf("Input an event to sleep on: ");
e = geti();
printf("\nEvent: %d\n", e);
ksleep(e);
}
int kkwakeup() {
printf("[ ENTERED KWAKEUP HELPER FUNCTION ]\n");
int e;
printf("Input an event to sleep on: ");
e = geti();
printf("\nEvent: %d\n", e);
kwakeup(e);
}
int kkopen() {
printf("[ ENTERED KOPEN HELPER FUNCTION ]\n");
open_file();
}
int kkclose() {
printf("[ ENTERED KCLOSE HELPER FUNCTION ]\n");
}
int kklseek() {
printf("[ ENTERED KLSEEK HELPER FUNCTION ]\n");
}
// called from svc_entry in ts.s
int svc_handler(int a, int b, int c, int d)
{
int r;
switch(a){
case 0: r = kgetpid(); break;
case 1: r = kgetppid(); break;
case 2: r = kps(); break;
case 3: r = kchname((char *)b); break;
case 4: r = ktswitch(); break;
// Insert Syscalls Here: kwait, ksleep, kwakeup
case 5: r = kkfork(); break;
case 6: r = kkwait(); break;
case 7: r = kkexit(); break;
case 8: r = kksleep(); break;
case 9: r = fork(); break;
case 10: r = exec((char *)b); break;
case 11: r = kkwakeup(); break;
case 12: r = kkopen(); break;
case 13: r = kkclose(); break;
case 14: r = kklseek(); break;
case 90: r = kgetc() &0x7F; break;
case 91: r = kputc(b); break;
case 92: r = kgetPA(); break;
default: printf("invalid syscall %d\n", a);
}
return r; // return to goUmode in ts.s; replace r0 in Kstack with r
}
<file_sep>int argc;
char *argv[32]; // assume at most 32 tokens in cmdline
int exec(char *cmdline)
{
int i, upa, usp;
char *cp, kline[128], file[32], filename[32];
PROC *p = running;
strcpy(kline, cmdline);
cp = kline;
i = 0;
while (*cp != ' ')
{
filename[i] = *cp;
i++;
cp++;
}
filename[i] = 0;
file[0] = 0;
upa = (int *)(p->pgdir[2048] & 0xFFFF0000);
if (!load(filename, p))
{
parseArg(cmdline);
return -1;
}
parseArg(cmdline);
usp = upa + 0x100000 - 128;
strcpy((char *)usp, kline);
p->usp = (int *)VA(0x100000 - 128);
for (i = 2; i < 14; i++)
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE - 1] = (int)VA(0);
return (int)p->usp;
}
int parseArg(char *line)
{
char *cp = line;
char cmd[32];
argc = 0;
while (*cp != 0)
{
int i = 0;
while (*cp == ' ')
*cp++ = 0; // skip over blanks
if (*cp != 0)
{
argv[argc++] = cp; // pointed by argv[ ]
}
while (*cp != ' ' && *cp != 0)
{ // scan token chars
cp++;
}
if (*cp != 0)
*cp = 0; // end of token
else
break; // end of line
printf("Argv[%d]: %s\n", argc-1, argv[argc-1]);
cp++; // continue scan
}
argv[argc] = 0; // argv[argc]=0
}<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
/**************************
need to catch Control-C, Contorl-D keys
so need to recognize LCTRL key pressed and then C or D key
Ref: 5.6.2.1
******************************/
#include "keymap"
#include "keymap2"
#define LSHIFT 0x12
#define RSHIFT 0x59
#define ENTER 0x5A
#define LCTRL 0x14
#define RCTRL 0xE014
#define ESC 0x76
#define F1 0x05
#define F2 0x06
#define F3 0x04
#define F4 0x0C
#define KCNTL 0x00
#define KSTAT 0x04
#define KDATA 0x08
#define KCLK 0x0C
#define KISTA 0x10
typedef volatile struct kbd
{
char *base;
char buf[128];
int head, tail;
int data, room;
} KBD;
volatile KBD kbd;
int shifted = 0;
int release = 0;
int control = 0;
volatile int keyset;
int kputc(char);
extern int color;
int kbd_init()
{
char scode;
keyset = 1; // default to scan code set-1
KBD *kp = &kbd;
kp->base = (char *)0x10006000;
*(kp->base + KCNTL) = 0x14; // bit4=Enable bit0=INT on //!!! 0x10 -> 0x14
*(kp->base + KCLK) = 8;
kp->head = kp->tail = 0;
kp->data = 0;
kp->room = 128;
shifted = 0;
release = 0;
control = 0;
printf("Detect KBD scan code: press the ENTER key : ");
while ((*(kp->base + KSTAT) & 0x10) == 0)
;
scode = *(kp->base + KDATA);
printf("scode=%x ", scode);
if (scode == 0x5A)
keyset = 2;
printf("keyset=%d\n", keyset);
}
// kbd_handler1() for scan code set 1
void kbd_handler1()
{
u8 scode, c;
KBD *kp = &kbd;
scode = *(kp->base + KDATA);
//printf("scan code = %x ", scode);
if (scode & 0x80)
return;
c = unsh[scode];
if (c == '\r')
kputc('\n');
kputc(c);
kp->buf[kp->head++] = c;
kp->head %= 128;
kp->data++;
kp->room--;
kwakeup(&kp->data);
}
// kbd_handelr2() for scan code set 2
void kbd_handler2()
{
// YOUR kbd handler for SET 2 scan code
}
/*void kbd_handler()
{
if (keyset == 1)
kbd_handler1();
else
kbd_handler2();
}*/
void kbd_handler()
{
u8 scode, c;
KBD *kp = &kbd;
color = YELLOW; // int color in vid.c file
scode = *(kp->base + KDATA); // get scan code from KDATA reg => clear IRQ
//printf("scanCode = %x\n", scode);
if (scode == 0xF0)
{ // key release
release = 1; // set flag
return;
}
if (scode == 0x12)
{ //L Shift is being pressed
shifted = 1;
}
if (scode == 0x14)
{ //L Ctrl is being pressed
control = 1;
}
if (scode == 0x12 && release == 1)
{ //L Shift is released
shifted = 0;
}
if (scode == 0x14 && release == 1)
{ //L Ctrl is released
control = 0;
}
if (release && scode)
{ // next scan code following key release
release = 0; // clear flag
return;
}
if (shifted && scode)
c = utab[scode]; //Lowercase
else // ONLY IF YOU can catch LEFT or RIGHT shift key
c = ltab[scode]; //Uppercase
if (control && scode)
{
if (scode == 0x21)
printf("PROGRAM IS TERMINATED\n");
if (scode == 0x23)
{
c = 0x04;
printf("FILE STREAMING IS TERMINATED\n");
}
}
if (c == '\r')
kputc('\n');
kputc(c);
kp->buf[kp->head++] = c; // Enter key into CIRCULAR buf[]
kp->head %= 128;
kp->data++;
kp->room--;
//kwakeup(&kp->data);
}
int kgetc()
{
char c;
KBD *kp = &kbd;
while (kp->data == 0)
; // BUSY wait for data
// !!!
/*while(kp->data == 0) {
ksleep(&kp->data);
}*/
lock();
c = kp->buf[kp->tail++];
kp->tail %= 128;
kp->data--;
kp->room++;
unlock();
return c;
}
/*int kgetc()
{
char c;
KBD *kp = &kbd;
while(1) {
lock();
if (kp->data==0) {
unlock();
ksleep(&kp->data);
}
else {
break;
}
}
c = kp->buf[kp->tail++];
kp->tail %= 128;
kp->data--; kp->room++;
unlock();
return c;
}*/
int kgets(char s[])
{
char c;
KBD *kp = &kbd;
while ((c = kgetc()) != '\r')
{
if (c == '\b')
{
s--;
continue;
}
*s++ = c;
}
*s = 0;
return strlen(s);
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// defines.h file
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#define UART0_BASE_ADDR 0x101f1000
#define UART0_DR (*((volatile u32 *)(UART0_BASE_ADDR + 0x000)))
#define UART0_FR (*((volatile u32 *)(UART0_BASE_ADDR + 0x018)))
#define UART0_IMSC (*((volatile u32 *)(UART0_BASE_ADDR + 0x038)))
#define UART1_BASE_ADDR 0x101f2000
#define UART1_DR (*((volatile u32 *)(UART1_BASE_ADDR + 0x000)))
#define UART1_FR (*((volatile u32 *)(UART1_BASE_ADDR + 0x018)))
#define UART1_IMSC (*((volatile u32 *)(UART1_BASE_ADDR + 0x038)))
#define KBD_BASE_ADDR 0x10006000
#define KBD_CR (*((volatile u32 *)(KBD_BASE_ADDR + 0x000)))
#define KBD_DR (*((volatile u32 *)(KBD_BASE_ADDR + 0x008)))
#define TIMER0_BASE_ADDR 0x101E2000
#define TIMER0_LR (*((volatile u32 *)(UART0_BASE_ADDR + 0x000)))
#define TIMER0_BR (*((volatile u32 *)(UART0_BASE_ADDR + 0x032)))
#define VIC_BASE_ADDR 0x10140000
#define VIC_STATUS (*((volatile u32 *)(VIC_BASE_ADDR + 0x000)))
#define VIC_INTENABLE (*((volatile u32 *)(VIC_BASE_ADDR + 0x010)))
#define VIC_VADDR (*((volatile u32 *)(VIC_BASE_ADDR + 0x030)))
#define SIC_BASE_ADDR 0x10003000
#define SIC_STATUS (*((volatile u32 *)(SIC_BASE_ADDR + 0x000)))
#define SIC_INTENABLE (*((volatile u32 *)(SIC_BASE_ADDR + 0x008)))
#define SIC_ENSET (*((volatile u32 *)(SIC_BASE_ADDR + 0x008)))
#define SIC_PICENSET (*((volatile u32 *)(SIC_BASE_ADDR + 0x020)))
#define BLUE 0
#define GREEN 1
#define RED 2
#define CYAN 3
#define YELLOW 4
#define PURPLE 5
#define WHITE 6
#define NPROC 9 // number of PROCs
#define SSIZE 1024 // stack size = 4KB
// PROC status
#define FREE 0
#define READY 1
#define SLEEP 2
#define ZOMBIE 3
#define BLOCK 4
#define FALSE 0
#define TRUE 1
typedef struct proc
{
struct proc *next; // next proc pointer
int *ksp; // saved sp: at byte offset 4
int pid; // process ID
int ppid; // parent process pid
int status; // PROC status=FREE|READY, etc.
int timer_display;
int priority; // scheduling priority
int event; // event value to sleep on
int exitCode; // exit value
struct proc *child; // first child PROC pointer
struct proc *sibling; // sibling PROC pointer
struct proc *parent; // parent PROC pointer
int kstack[1024]; // process stack
} PROC;
<file_sep>/*********** type.h file ************/
#define NPROC 9 // number of PROCs
#define SSIZE 1024 // stack size = 4KB
// PROC status
#define FREE 0
#define READY 1
#define SLEEP 2
#define ZOMBIE 3
#define BLOCK 4
typedef struct proc{
struct proc *next; // next proc pointer
int *ksp; // saved sp: at byte offset 4
int pid; // process ID
int ppid; // parent process pid
int status; // PROC status=FREE|READY, etc.
int priority; // scheduling priority
int event; // event value to sleep on
int exitCode; // exit value
struct proc *child; // first child PROC pointer
struct proc *sibling; // sibling PROC pointer
struct proc *parent; // parent PROC pointer
int kstack[1024]; // process stack
}PROC;
typedef struct semaphore {
int lock;
int value;
PROC queue;
} SEMAPHORE;<file_sep>#include "type.h"
#include "string.c"
PROC proc[NPROC]; // NPROC PROCs
PROC *freeList; // freeList of PROCs
PROC *readyQueue; // priority queue of READY procs
PROC *zombieList;
PROC *timerQueue;
PROC *running; // current running proc pointer
PROC *sleepList; // list of SLEEP procs
PROC *ptemp; // list of SLEEP procs
int procsize = sizeof(PROC);
#define printf kprintf
#define gets kgets
#include "kbd.c"
#include "vid.c"
#include "exceptions.c"
#include "queue.c"
#include "wait.c"
#include "pv.c"
#include "pipe.c"
#include "uart.c"
#include "timer.c"
UART *up;
/*******************************************************
kfork() creates a child process; returns child pid.
When scheduled to run, child PROC resumes to body();
********************************************************/
int body(), tswitch(), do_sleep(), do_wakeup(), do_exit(), do_switch();
int do_kfork();
int scheduler();
int kprintf(char *fmt, ...);
void copy_vectors(void)
{
extern u32 vectors_start;
extern u32 vectors_end;
u32 *vectors_src = &vectors_start;
u32 *vectors_dst = (u32 *)0;
while (vectors_src < &vectors_end)
*vectors_dst++ = *vectors_src++;
}
int timer_handler();
TIMER *tp[4]; // 4 TIMER structure pointers
void IRQ_handler()
{
int vicstatus, sicstatus;
int ustatus, kstatus;
// read VIC SIV status registers to find out which interrupt
vicstatus = VIC_STATUS;
sicstatus = SIC_STATUS;
if (vicstatus & 0x80000000)
{ // SIC interrupts=bit_31=>KBD at bit 3
if (sicstatus & 0x08)
{
kbd_handler();
}
}
int flag;
flag = timer_handler(0);
// ADD ENQUEUE TO ADD_TIMER
if (timerQueue != 0 && total_timers <= 1)
{
int sr = int_off();
PROC *p = dequeue(&timerQueue);
timer_start(total_timers, p->pid, p->timer_sec);
int_on(sr);
//dequeue(&timerQueue);
}
for (int i = 1; i < total_timers; i++)
{
flag = timer_handler(i);
if (flag != 0)
{
printf("---- AWAKEN THE CHILD %d\n", flag);
kwakeup(&proc[flag]);
printList("sleepList", sleepList);
// Add next item on list to timer
if (ptemp != 0)
{
PROC *p = dequeue(ptemp);
enqueue(&timerQueue, p);
ksleep(p);
}
}
}
}
// initialize the MT system; create P0 as initial running process
int init()
{
int i;
PROC *p;
for (i = 0; i < NPROC; i++)
{ // initialize PROCs
p = &proc[i];
p->pid = i; // PID = 0 to NPROC-1
p->status = FREE;
p->timer_display = FALSE;
p->timer_sec = 0;
p->priority = 0;
p->next = p + 1;
}
p[0].timer_display = TRUE;
proc[NPROC - 1].next = 0;
freeList = &proc[0]; // all PROCs in freeList
readyQueue = 0; // readyQueue = empty
sleepList = 0; // sleepList = empty
timerQueue = 0;
// create P0 as the initial running process
p = running = dequeue(&freeList); // use proc[0]
p->status = READY;
p->priority = 0;
p->ppid = 0; // P0 is its own parent
p->parent = p;
printList("freeList", freeList);
printf("init complete: P0 running\n");
}
int INIT()
{
int pid, status;
PIPE *p = &pipe;
printf("P1 running: create pipe and writer reader processes\n");
kpipe();
kfork((int)pipe_writer());
kfork((int)pipe_reader());
printf("P1 waits for ZOMBIE child\n");
while (1)
{
pid = kwait(&status);
if (pid < 0)
{
printf("no more child, P1 loops\n");
while (1)
;
}
printf("P1 buried a ZOMBIE child %d\n", pid);
}
}
int menu()
{
printf("***************************************\n");
printf(" ps fork switch exit wait sleep wakeup \n");
printf("***************************************\n");
}
char *status[] = {"FREE", "READY", "SLEEP", "ZOMBIE", "BLOCK"};
int do_ps()
{
int i;
PROC *p;
printf("PID PPID status\n");
printf("--- ---- ------\n");
for (i = 0; i < NPROC; i++)
{
p = &proc[i];
printf(" %d %d ", p->pid, p->ppid);
if (p == running)
printf("RUNNING\n");
else
printf("%s\n", status[p->status]);
}
}
int body() // process body function
{
int c;
char cmd[64];
printf("proc %d starts from body()\n", running->pid);
while (1)
{
printf("***************************************\n");
printf("proc %d running: parent=%d\n", running->pid, running->ppid);
printList("readyQueue", readyQueue);
printSleepList(sleepList);
//printList("freeList", freeList);
//printList("zombieList", zombieList);
//printList("running", running);
if (running->child != 0)
{ // Displays child
printf("-child list: [%d %s ]", running->child->pid, status[running->child->status]);
PROC *temp = running->child; // Gets current running child
while (temp->sibling != 0)
{ // Displays sibling of child
printf("->[%d %s ]", temp->sibling->pid, status[running->child->status]);
temp = temp->sibling;
}
printf("\n");
}
//menu();
//show_pipe();
printf("enter a command:\n>> ");
gets(cmd);
printf("\n");
if (strcmp(cmd, "p") == 0)
do_ps();
else if (strcmp(cmd, "f") == 0)
do_kfork();
else if (strcmp(cmd, "s") == 0)
do_switch();
else if (strcmp(cmd, "wait") == 0)
do_wait();
else if (strcmp(cmd, "exit") == 0)
do_exit();
else if (strcmp(cmd, "sleep") == 0)
do_sleep();
else if (strcmp(cmd, "wakeup") == 0)
do_wakeup();
else if (strcmp(cmd, "t") == 0)
do_timer();
else if (strcmp(cmd, "w") == 0)
do_write();
else if (strcmp(cmd, "r") == 0)
do_read();
else
printf("[!] - INVALID INPUT\n");
}
}
int kfork()
{
int i;
PIPE *pp = &pipe;
PROC *p = dequeue(&freeList);
if (p == 0)
{
kprintf("kfork failed\n");
return -1;
}
p->ppid = running->pid;
p->parent = running;
p->status = READY;
p->priority = 1;
p->parent = running; // Saves content of parent proc
if (p->parent->child == 0)
{ /// child is empty
p->parent->child = p; // Stores p in binary tree
}
else
{ /// child is not empty
PROC *temp = p->parent->child;
while (temp->sibling != 0)
{
temp = temp->sibling; // traverse until free node
}
temp->sibling = p; //Stores p in binary tree @node
}
// set kstack to resume to body
// stack = r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r14
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (i = 1; i < 15; i++)
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE - 1] = (int)body; // in dec reg=address ORDER !!!
p->ksp = &(p->kstack[SSIZE - 14]);
enqueue(&readyQueue, p);
return p->pid;
}
int do_kfork()
{
int child = kfork();
if (child < 0)
printf("kfork failed\n");
else
{
printf("proc %d kforked a child = %d\n", running->pid, child);
printList("readyQueue", readyQueue);
}
return child;
}
int do_switch()
{
tswitch();
}
int do_wait()
{
int pid, status;
pid = kwait(&status);
printf("pid = %d, exitVal = %d\n", pid, status);
}
int do_exit()
{
kexit(running->pid); // exit with own PID value
}
int do_sleep()
{
int event;
printf("enter an event value to sleep on : ");
event = geti();
ksleep(event);
}
int do_wakeup()
{
int event;
printf("enter an event value to wakeup with : ");
event = geti();
kwakeup(event);
}
int add_queue(int sec)
{
running->timer_sec = sec;
if (timerQueue != 0 && total_timers > 1)
{
enqueue(&ptemp, running);
}
else
{
enqueue(&timerQueue, running);
ksleep(running);
printf("\n+ ADDED PROC %d TO ENQUEUE (%d SEC)\n", running->pid, running->timer_sec);
printList("sleepList", sleepList);
}
}
int do_timer()
{
int sec;
printf("enter a time value to wakeup with : ");
sec = geti();
printf("\n+ New TIMER (%d sec) for P%d", sec, running->pid);
add_queue(sec);
}
int do_write()
{
pipe_writer();
}
int do_read()
{
pipe_reader();
}
int do_pipe()
{
INIT();
}
int main()
{
int i;
char line[128];
u8 kbdstatus, key, scode;
KBD *kp = &kbd;
color = YELLOW;
row = col = 0;
fbuf_init();
kprintf("Welcome to Wanix in ARM\n");
kbd_init();
uart_init();
VIC_INTENABLE |= (1 << 4); // timer0,1 at bit4
VIC_INTENABLE |= (1 << 5); // timer2,3 at bit5
/* enable SIC interrupts */
VIC_INTENABLE |= (1 << 31); // SIC to VIC's IRQ31
/* enable KBD IRQ */
SIC_INTENABLE = (1 << 3); // KBD int=bit3 on SIC
SIC_ENSET = (1 << 3); // KBD int=3 on SIC
*(kp->base + KCNTL) = 0x12;
timer_init();
timer_start(0, 0, 1);
init();
printQ(readyQueue);
kfork(); // kfork P1 into readyQueue
//kfork(INIT());
unlock();
while (1)
{
if (readyQueue)
tswitch();
}
}
/*********** scheduler *************/
int scheduler()
{
printf("proc %d in scheduler()\n", running->pid);
if (running->status == READY)
enqueue(&readyQueue, running);
printList("readyQueue", readyQueue);
running = dequeue(&readyQueue);
printf("next running = %d\n", running->pid);
}
<file_sep> YOU MAY USE THESE FUNCTIONS in util.o
/************** util.c file ****************/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ext2fs/ext2_fs.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>
#include "type.h"
/**** globals defined in main.c file ****/
extern MINODE minode[NMINODE];
extern MINODE *root;
extern PROC proc[NPROC], *running;
extern char gpath[128];
extern char *name[64];
extern int n;
extern int fd, dev;
extern int nblocks, ninodes, bmap, imap, inode_start;
extern char line[256], cmd[32], pathname[256];
int get_block(int dev, int blk, char *buf)
{
// read disk block blk into char buf[BLKSIZE]
}
int put_block(int dev, int blk, char *buf)
{
// write buf[ ] to disk block blk
}
int tokenize(char *pathname)
{
// tokenize pathname into n components: name[0] to name[n-1];
// n = number of token strings
}
MINODE *iget(int dev, int ino)
{
// return minode pointer containing loaded INODE
//(1). Search minode[ ] for an existing entry with the needed (dev, ino):
if found: inc its refCount by 1;
return pointer to this minode;
//(2). // needed entry not in memory:
find a FREE minode (refCount = 0); Let mip-> to this minode;
set its refCount = 1;
set its dev, ino
//(3). load INODE of (dev, ino) into mip->INODE:
blk = (ino-1) / 8 + inode_start;
disp = (ino-1) % 8;
get_block(dev, blk, buf);
ip = (INODE *)buf + disp;
mip->INODE = *ip; // copy INODE to mip->INODE
return mip;
}
int iput(MINODE *mip) // dispose a used minode by mip
{
mip->refCount--;
if (mip->refCount > 0) return;
if (!mip->dirty) return;
// write INODE back to disk
blk = (mip->ino - 1) / 8 + inode_start;
offset = (mip->ino - 1) % 8;
get_block(mip->dev, blk, buf);
ip = (INODE *)buf + offset;
*ip = mip->INODE;
put_block(mip->dev, blk, buf);
}
// serach a DIRectory INODE for entry with given name
int search(MINODE *mip, char *name)
{
// return ino of name if found; return 0 if NOT
}
// retrun inode number of pathname
int getino(int *dev, char *pathname)
{
return ino of pathname if exist;
return 0 if not
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// uart.c file
/************************************
UART0 base address: 0x101f1000;
UART1 base address: 0x101f2000;
UART2 base address: 0x101f3000;
UART3 base address: 0x10009000;
// UART's flag register at 0x18
// 7 6 5 4 3 2 1 0
// TXFE RXFF TXFF RXFE BUSY
// TX FULL : 0x20
// TX empty: 0x80
// RX FULL : 0x40
// RX empty: 0x10
// BUSY=1 : 0x08
***********************************/
int kprintf(char *fmt, ...);
/******** bytes offsets: for char *base ********/
#define UDR 0x00
#define UDS 0x04
#define UFR 0x18
#define CNTL 0x2C
#define IMSC 0x38
#define UMIS 0x40
#define SBUFSIZE 128
typedef volatile struct uart{
char *base; // base address; as char *
u32 n; // uart number 0-3
char inbuf[SBUFSIZE];
int indata, inroom, inhead, intail;
char outbuf[SBUFSIZE];
int outdata, outroom, outhead, outtail;
int txon; // 1=TX interrupt is on
}UART;
UART uart[4]; // 4 UArt structures
int uart_init()
{
int i;
UART *up;
for (i=0; i<4; i++){ // uart0 to uart2 are adjacent
up = &uart[i];
up->base = (char *)(0x101f1000 + i*0x1000);
*(up->base+0x2C) &= ~0x10; // disable FIFO
*(up->base+0x38) |= 0x30;
up->n = i;
up->indata = up->inhead = up->intail = 0;
up->inroom = SBUFSIZE;
up->outdata = up->outhead = up->outtail = 0;
up->outroom = SBUFSIZE;
up->txon = 0;
}
uart[3].base = (char *)(0x10009000); // uart3 at 0x10009000
}
void uart_handler(UART *up)
{
u8 mask, mis;
// mask = *(up->base + MASK); // read MASK register
mis = *(up->base + UMIS); // read UMIS register
//kprintf("uart%d interrupt mask=%x MIS=%x\n", up->n, mask, mis);
if (mis & 0x10)
do_rx(up);
if (mis & 0x20)
do_tx(up);
}
int do_rx(UART *up)
{
char c;
color = GREEN;
// do we need this?
// while(!(*(up->base + UFR) & 0x40));
c = *(up->base+UDR);
//kprintf("rx interrupt: %c\n", c);
if (c==0xD)
kprintf("\n");
up->inbuf[up->inhead++] = c;
up->inhead %= SBUFSIZE;
up->indata++; up->inroom--;
color=RED;
}
int do_tx(UART *up)
{
char c; u8 mask;
//kprintf("TX interrupt\n");
if (up->outdata <= 0){
// disable TX interrupt; return
*(up->base+IMSC) = 0x10; // mask out TX interrupt
up->txon = 0;
return;
}
c = up->outbuf[up->outtail++];
up->outtail %= 128;
//while( *(up->base+UFR) & 0x20 ); // loop while FR=TXF
*(up->base+UDR) = (int)c; // write c to DR
up->outdata--; up->outroom++;
}
int ugetc(UART *up)
{
char c;
while(up->indata <= 0); // loop until up->data > 0 READONLY, no need for lock
c = up->inbuf[up->intail++];
up->intail %= SBUFSIZE;
// updating variables: must disable interrupts
int_off();
up->indata--; up->inroom++;
int_on();
return c;
}
// TO DO: UART outputs should be intertupt-driven also
int uputc(UART *up, char c)
{
//kprintf("uputc to UART%d %c ", up->n, c);
if (up->txon){ // if TX is on => still transmitting, enter c into outbuf[]
up->outbuf[up->outhead++] = c;
up->outhead %= 128;
int_off();
up->outdata++; up->outroom--;
int_on();
return;
}
// txon==0 means TX is off => output c & enable TX interrupt
// PL011 TX is riggered only if write char, else no TX interrupt
int i = *(up->base+UFR); // read FR
while( *(up->base+UFR) & 0x20 ); // loop while FR=TXF
*(up->base+UDR) = (int)c; // write c to DR
// UART0_IMSC |= 0x30; // 0000 0000: bit5=TX mask bit4=RX mask
*(up->base+IMSC) |= 0x30;
up->txon = 1;
}
int ugets(UART *up, char *s)
{
kprintf("in ugets() of UART%d", up->n);
while ((*s = (char)ugetc(up)) != '\r'){
uputc(up, *s);
s++;
}
*s = 0;
}
int uprints(UART *up, char *s)
{
while(*s)
uputc(up, *s++);}
int urpx(UART *up, int x)
{
char c;
if (x){
c = tab[x % 16];
urpx(up, x / 16);
}
uputc(up, c);
}
int uprintx(UART *up, int x)
{
uprints(up, "0x");
if (x==0)
uputc(up, '0');
else
urpx(up, x);
uputc(up, ' ');
}
int urpu(UART *up, int x)
{
char c;
if (x){
c = tab[x % 10];
urpu(up, x / 10);
}
uputc(up, c);
}
int uprintu(UART *up, int x)
{
if (x==0)
uputc(up, '0');
else
urpu(up, x);
uputc(up, ' ');
}
int uprinti(UART *up, int x)
{
if (x<0){
uputc(up, '-');
x = -x;
}
uprintu(up, x);
}
int ufprintf(UART *up, char *fmt,...)
{
int *ip;
char *cp;
cp = fmt;
ip = (int *)&fmt + 1;
while(*cp){
if (*cp != '%'){
uputc(up, *cp);
if (*cp=='\n')
uputc(up, '\r');
cp++;
continue;
}
cp++;
switch(*cp){
case 'c': uputc(up, (char)*ip); break;
case 's': uprints(up, (char *)*ip); break;
case 'd': uprinti(up, *ip); break;
case 'u': uprintu(up, *ip); break;
case 'x': uprintx(up, *ip); break;
}
cp++; ip++;
}
}
int uprintf(char *fmt, ...)
{
int *ip;
char *cp;
cp = fmt;
ip = (int *)&fmt + 1;
UART *up = &uart[0];
while(*cp){
if (*cp != '%'){
uputc(up, *cp);
if (*cp=='\n')
uputc(up, '\r');
cp++;
continue;
}
cp++;
switch(*cp){
case 'c': uputc(up, (char)*ip); break;
case 's': uprints(up, (char *)*ip); break;
case 'd': uprinti(up, *ip); break;
case 'u': uprintu(up, *ip); break;
case 'x': uprintx(up, *ip); break;
}
cp++; ip++;
}
}
<file_sep>int tswitch();
int sleep(int event)
{
printf("proc %d going to sleep on event=%d\n", running->pid, event);
running->event = event;
running->status = SLEEP;
enqueue(&sleepList, running);
printList("sleepList", sleepList);
tswitch();
}
int wakeup(int event)
{
PROC *temp, *p;
temp = 0;
printList("sleepList", sleepList);
while (p = dequeue(&sleepList)){
if (p->event == event){
printf("wakeup %d\n", p->pid);
p->status = READY;
enqueue(&readyQueue, p);
}
else{
enqueue(&temp, p);
}
}
sleepList = temp;
printList("sleepList", sleepList);
}
int kexit(int exitValue)
{
printf("proc %d in kexit(), value=%d\n", running->pid, exitValue);
running->exitCode = exitValue;
running->status = ZOMBIE;
tswitch();
}
<file_sep>/************ uio.c file: must implement printf() in U space **********/
#define printf uprintf
char *tab = "0123456789ABCDEF";
int uputc(char);
int ugetline(char *line)
{
char c, *cp = line;
while( (c = ugetc()) != '\r'){
//uputc('u'); uputc(c);
*cp = c;
cp++;
}
*cp = 0;
}
int uprints(char *s)
{
while(*s){
uputc(*s);
s++;
}
}
int urpx(u32 x)
{
char c;
if (x==0)
return;
c = tab[x % 16];
urpx(x / 16);
uputc(c);
}
int uprintx(u32 x)
{
uputc('0'); uputc('x');
if (x==0)
uputc('0');
else
urpx(x);
uputc(' ');
}
int urpu(u32 x)
{
char c;
if (x==0)
return;
c = tab[x % 10];
urpu(x / 10);
uputc(c);
}
int uprintu(u32 x)
{
if (x==0){
uputc('0');
}
else
urpu(x);
uputc(' ');
}
int uprinti(int x)
{
if (x<0){
uputc(' ');
uputc('-');
x = -x;
}
uprintu((u32)x);
}
int uprintf(char *fmt,...)
{
int *ip;
char *cp;
cp = fmt;
ip = (int *)&fmt + 1;
while(*cp){
if (*cp != '%'){
uputc(*cp);
if (*cp=='\n')
uputc('\r');
cp++;
continue;
}
cp++;
switch(*cp){
case 'c': uputc((char)*ip); break;
case 's': uprints((char *)*ip); break;
case 'd': uprinti(*ip); break;
case 'u': uprintu((u32)*ip); break;
case 'x': uprintx((u32)*ip); break;
}
cp++; ip++;
}
}
<file_sep># CS460 - Operating Systems and Computer Architecture
## Development Enviroment / Setup:
Development Software: (Ubuntu 18.04)<br />
(1). Intel x86 packages:
sudo apt-get install bcc
sudo apt-get insatll qemu-system-i386
(2). ARM packages:
sudo apt-get insatll gcc-arm-none-eabi
sudo apt-get insatll qemu-system-arm
<file_sep>//// login.c
#include "ucode.c"
int in, out, err;
char username[128], password[128];
int tokenize(char *line, char *buf[], char ch)
{
int len = 0;
char *cp = line;
/// Taken from 'token()' in crt0.c
while (*cp != 0)
{
/// Trims whitespace
while (*cp == ' ')
*cp++ = 0;
/// Scans string
if (*cp != 0)
buf[len++] = cp;
/// Splits lines
while (*cp != ch && *cp != 0)
cp++;
if (*cp != 0)
*cp = 0;
else
break;
cp++;
}
return len;
}
int main(int argc, char *argv[])
{
int i, pid = getpid();
char *lines[128], *acc_info[128], file_read[1024];
// (1). close file descriptors 0,1 inherited from INIT.
close(0);
close(1);
prints("[0] - Successfully Closed FD 0, 1.\n");
// (2). open argv[1] 3 times as in(0), out(1), err(2).
in = open(argv[1], 0);
out = open(argv[1], 1);
err = open(argv[1], 2);
prints("[0] - Successfully Opened argv[1] in(0), out(1), err(2).\n");
// (3). set tty username string in PROC.tty
fixtty(argv[1]);
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
while (1)
{
printf("CNG: PROC %d running login program\n", pid);
// (4). open /etc/passwd file for READ;
int file = open("/etc/passwd", O_RDONLY);
// (5). Get username, password & tokenize
printc('\n');
printf(">> LOGIN: ");
gets(username);
printf(">> PASSWORD: ");
gets(password);
read(file, file_read, 1024);
//prints(file_read); // Prints what was read in passwd for DEBUGGING
int len = tokenize(file_read, lines, '\n'); // Get individual lines from file read buf
for (i = 0; i < len; i++)
{
tokenize(lines[i], acc_info, ':'); // Splits individual lines to get info
// (6). if (user has a valid account){
int username_valid = strcmp(username, acc_info[0]) == 0;
int password_valid = strcmp(password, acc_info[1]) == 0;
if (username_valid && password_valid)
{ //if username and password both valid, account is VALID
// (7-1). change uid, gid to user's uid, gid; // chuid()
chuid(atoi(acc_info[2]), atoi(acc_info[3])); // chuid( uid, gid )
// (7-2).change cwd to user's home DIR // chdir()
chdir(acc_info[5]);
printf("[0] - CNG LOGIN SUCCESSFUL.\nuser:\t%s\npass:\t%s\ngid:\t%d\nuid:\t%d\nhome:\t%s\nshell:\t%s\n\n",
acc_info[0], acc_info[1], atoi(acc_info[2]), atoi(acc_info[3]), acc_info[5], acc_info[6]);
// (7-3). close opened /etc/passwd file // close()
close(file);
// (8). exec to program in user account // exec()
exec(acc_info[6]); // Execute Shell
break;
}
}
prints("[!] - Wrong Login.\n");
}
//printf("PROC %d exit\n", pid);
}<file_sep>/*********** util.c file ****************/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ext2fs/ext2_fs.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>
#include "type.h"
extern MINODE minode[NMINODE];
extern MINODE *root;
extern PROC proc[NPROC], *running;
extern char gpath[256];
extern char *name[64]; // assume at most 64 components in pathnames
extern int n;
extern int fd, dev;
extern int nblocks, ninodes, bmap, imap, inode_start;
extern char pathname[256], parameter[256];
int get_block(int dev, int blk, char *buf)
{
lseek(dev, (long)blk*BLKSIZE, 0);
read(dev, buf, BLKSIZE);
}
int put_block(int dev, int blk, char *buf)
{
lseek(dev, (long)blk*BLKSIZE, 0);
write(dev, buf, BLKSIZE);
}
int tokenize(char *pathname)
{
int i;
char *s;
printf("tokenize %s\n", pathname);
strcpy(gpath, pathname);
n = 0;
s = strtok(gpath, "/");
while(s){
name[n] = s;
n++;
s = strtok(0, "/");
}
for (i= 0; i<n; i++)
printf("%s ", name[i]);
printf("\n");
}
// return minode pointer to loaded INODE
MINODE *iget(int dev, int ino)
{
int i;
MINODE *mip;
char buf[BLKSIZE];
int blk, disp;
INODE *ip;
for (i=0; i<NMINODE; i++){
mip = &minode[i];
//if (mip->refCount){
if (mip->dev == dev && mip->ino == ino){
mip->refCount++;
//printf("found [%d %d] as minode[%d] in core\n", dev, ino, i);
return mip;
}
//}
}
for (i=0; i<NMINODE; i++){
mip = &minode[i];
if (mip->refCount == 0){
//printf("allocating NEW minode[%d] for [%d %d]\n", i, dev, ino);
mip->refCount = 1;
mip->dev = dev;
mip->ino = ino;
// get INODE of ino to buf
blk = (ino-1)/8 + inode_start;
disp = (ino-1) % 8;
//printf("iget: ino=%d blk=%d disp=%d\n", ino, blk, disp);
get_block(dev, blk, buf);
ip = (INODE *)buf + disp;
// copy INODE to mp->INODE
mip->INODE = *ip;
return mip;
}
}
printf("PANIC: no more free minodes\n");
return 0;
}
iput(MINODE *mip)
{
int i, block, offset;
char buf[BLKSIZE];
INODE *ip;
if (mip==0)
return;
mip->refCount--;
if (mip->refCount > 0) return;
if (!mip->dirty) return;
/* write back */
//printf("iput: dev=%d ino=%d\n", mip->dev, mip->ino);
block = ((mip->ino - 1) / 8) + inode_start;
offset = (mip->ino - 1) % 8;
/* first get the block containing this inode */
get_block(mip->dev, block, buf);
ip = (INODE *)buf + offset;
*ip = mip->INODE;
put_block(mip->dev, block, buf);
}
int search(MINODE *mip, char *name)
{
int i;
char *cp, c, sbuf[BLKSIZE];
DIR *dp;
INODE *ip;
printf("search for %s in MINODE = [%d, %d]\n", name,mip->dev,mip->ino);
ip = &(mip->INODE);
/********** search for a file name ***************/
for (i=0; i<12; i++){ /* search direct blocks only */
if (ip->i_block[i] == 0)
return 0;
printf("search: i=%d i_block[%d]=%d\n", i, i, ip->i_block[i]);
//getchar();
get_block(dev, ip->i_block[i], sbuf);
dp = (DIR *)sbuf;
cp = sbuf;
printf(" i_number rec_len name_len name\n");
while (cp < sbuf + BLKSIZE){
c = dp->name[dp->name_len];
dp->name[dp->name_len] = 0;
printf("%8d%8d%8u %s\n",
dp->inode, dp->rec_len, dp->name_len, dp->name);
if (strcmp(dp->name, name)==0){
printf("found %s : ino = %d\n", name, dp->inode);
return(dp->inode);
}
dp->name[dp->name_len] = c;
cp += dp->rec_len;
dp = (DIR *)cp;
}
}
return(0);
}
int getino(char *pathname)
{
int i, ino, blk, disp;
char buf[BLKSIZE];
INODE *ip;
MINODE *mip;
printf("getino: pathname=%s\n", pathname);
if (strcmp(pathname, "/")==0)
return 2;
if (pathname[0]=='/')
mip = iget(dev, 2);
else
mip = iget(running->cwd->dev, running->cwd->ino);
strcpy(buf, pathname);
tokenize(buf);
for (i=0; i<n; i++){
printf("===========================================\n");
printf("getino: i=%d name[%d]=%s\n", i, i, name[i]);
ino = search(mip, name[i]);
if (ino==0){
iput(mip);
printf("name %s does not exist\n", name[i]);
return 0;
}
iput(mip);
mip = iget(dev, ino);
}
iput(mip);
return ino;
}
int findmyname(MINODE *parent, u32 myino, char *myname)
{
int i;
char buf[BLKSIZE], temp[256], *cp;
DIR *dp;
MINODE *mip = parent;
/********** search for a file name ***************/
for (i=0; i<12; i++){ /* search direct blocks only */
if (mip->INODE.i_block[i] == 0)
return -1;
get_block(mip->dev, mip->INODE.i_block[i], buf);
dp = (DIR *)buf;
cp = buf;
while (cp < buf + BLKSIZE){
strncpy(temp, dp->name, dp->name_len);
temp[dp->name_len] = 0;
//printf("%s ", temp);
if (dp->inode == myino){
strncpy(myname, dp->name, dp->name_len);
myname[dp->name_len] = 0;
return 0;
}
cp += dp->rec_len;
dp = (DIR *)cp;
}
}
return(-1);
}
int findino(MINODE *mip, u32 *myino)
{
char buf[BLKSIZE], *cp;
DIR *dp;
get_block(mip->dev, mip->INODE.i_block[0], buf);
cp = buf;
dp = (DIR *)buf;
*myino = dp->inode;
cp += dp->rec_len;
dp = (DIR *)cp;
return dp->inode;
}
// ----
void mytruncate(MINODE * mip)
{
for(int i = 0; i < 12 && mip->INODE.i_block[i]; i++)
bdalloc(mip->dev, mip->INODE.i_block[i]);
uint32_t buf[256];
if(mip->INODE.i_block[12] != 0)
{
get_block(mip->dev, mip->INODE.i_block[12], (char*)buf);
for(int i = 0; i < 256 && buf[i] != 0; i++)
bdalloc(mip->dev, buf[i]);
}
if(mip->INODE.i_block[13] != 0)
{
get_block(mip->dev, mip->INODE.i_block[13], (char*)buf);
for(int i = 0; i < 256 && buf[i] != 0; i++)
{
uint32_t buf2[256];
get_block(mip->dev, buf[i], (char*)buf2);
for(int j = 0; j < 256 && buf2[j] != 0; j++)
{
bdalloc(mip->dev, buf2[j]);
}
bdalloc(mip->dev, buf[i]);
}
}
}
void zero_block(int dev, int blk)
{
char buf[BLKSIZE];
memset(buf, 0, BLKSIZE);
put_block(dev, blk, buf);
}<file_sep>/********** test.c file *************/
#include "ucode.c"
int main(int argc, char *argv[ ])
{
int i;
int pid = getpid();
printf("KCW: PROC %d running test program\n", pid);
printf("argc = %d\n", argc);
for (i=0; i<argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
printf("PROC %d exit\n", pid);
}
<file_sep>typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#include "string.c"
#include "uio.c"
int ubody(char *name)
{
int pid, ppid;
char line[64];
u32 mode, *up;
mode = getcsr();
mode = mode & 0x1F;
printf("CPU mode=%x\n", mode);
pid = getpid();
ppid = getppid();
while(1){
printf("**** PROCESS %s ****\n", name);
printf("This is process #%d in Umode at %x parent=%d\n", pid, getPA(),ppid);
umenu();
printf("input a command : ");
ugetline(line);
uprintf("\n");
if (strcmp(line, "getpid")==0)
ugetpid();
if (strcmp(line, "getppid")==0)
ugetppid();
if (strcmp(line, "ps")==0)
ups();
if (strcmp(line, "chname")==0)
uchname();
if (strcmp(line, "switch")==0)
uswitch();
if (strcmp(line, "kfork")==0)
ukfork();
if (strcmp(line, "wait")==0)
uwait();
if (strcmp(line, "exit")==0)
uexit();
if (strcmp(line, "sleep")==0)
usleep();
if (strcmp(line, "wakeup")==0)
uwakeup();
if (strcmp(line, "fork")==0)
ufork();
if (strcmp(line, "exec")==0)
uexec();
if (strcmp(line, "open")==0)
uopen();
if (strcmp(line, "close")==0)
uclose();
if (strcmp(line, "lseek")==0)
ulseek();
}
}
int umenu()
{
uprintf("-------------------------------\n");
uprintf("getpid getppid ps chname switch - kfork wait exit sleep wakeup - fork exec\n");
uprintf("-------------------------------\n");
}
int getpid()
{
int pid;
pid = syscall(0,0,0,0);
return pid;
}
int getppid()
{
return syscall(1,0,0,0);
}
int ugetpid()
{
int pid = getpid();
uprintf("pid = %d\n", pid);
}
int ugetppid()
{
int ppid = getppid();
uprintf("ppid = %d\n", ppid);
}
int ups()
{
return syscall(2,0,0,0);
}
int uchname()
{
char s[32];
uprintf("input a name string : ");
ugetline(s);
printf("\n");
return syscall(3,s,0,0);
}
int uswitch()
{
return syscall(4,0,0,0);
}
int ukfork()
{
return syscall(5,0,0,0);
}
int uwait()
{
return syscall(6,0,0,0);
}
int uexit()
{
return syscall(7,0,0,0);
}
int usleep()
{
return syscall(8,0,0,0);
}
int ufork()
{
return syscall(9,0,0,0);
}
int uexec()
{
char input[128];
uprintf("input a command string : ");
ugetline(input);
printf("\n");
return syscall(10,input,0,0);
}
int uwakeup()
{
return syscall(11,0,0,0);
}
int uopen()
{
return syscall(12,0,0,0);
}
int uclose(int fd)
{
return syscall(13,0,0,0);
}
int ulseek()
{
return syscall(14,0,0,0);
}
int ugetc()
{
return syscall(90,0,0,0);
}
int uputc(char c)
{
return syscall(91,c,0,0);
}
int getPA()
{
return syscall(92,0,0,0);
}
<file_sep>/*******************************************************
* t.c file *
*******************************************************/
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
#define TRK 18
#define CYL 36
#define BLK 1024
#include "ext2.h"
typedef struct ext2_group_desc GD;
typedef struct ext2_inode INODE;
typedef struct ext2_dir_entry_2 DIR;
GD *gp;
INODE *ip;
DIR *dp;
u32 *up;
char buf1[BLK], buf2[BLK];
int color = 0x0A;
void prints(char *s)
{
while (*s)
putc(*s++);
}
void gets(char *s)
{
while ((*s = getc()) != '\r')
{
putc(*s);
s++;
}
*s = '\0';
}
int getblk(u16 blk, char *buf)
{
readfd(blk / 18, ((blk) % 18) / 9, (((blk) % 18) % 9) << 1, buf);
}
u16 search(INODE *ip, char *name)
{
int i;
char c;
DIR *dp;
for (i = 0; i < 12; i++)
{
if ((u16)ip->i_block[i])
{
getblk((u16)ip->i_block[i], buf2);
dp = (DIR *)buf2;
while ((char *)dp < &buf2[BLK])
{
c = dp->name[dp->name_len];
dp->name[dp->name_len] = 0;
prints(dp->name); //Prints name
putc(' ');
if (strcmp(dp->name, name) == 0)
{
prints("\n\r");
return ((u16)dp->inode);
}
dp->name[dp->name_len] = c;
dp = (char *)dp + dp->rec_len;
}
}
}
error();
}
main()
{
u32 *up;
u16 i, ino, iblk;
char c, temp[64], *name[2], file[64];
name[0] = "boot";
name[1] = file;
prints("boot: ");
gets(file);
if (file[0] == 0)
name[1] = "mtx";
//prints("read block# 2 (GD)\n\r");
getblk(2, buf1);
gp = (GD *)buf1;
// 1. WRITE YOUR CODE to get iblk = bg_inode_table block number
iblk = (u16)gp->bg_inode_table;
prints("\n\r");
getblk(iblk, buf1);
// 2. WRITE YOUR CODE to get root inode
ip = (INODE *)buf1; //Begin Block
ip += 1;
for (i = 0; i < 2; i++)
{ //Will search for the given system name (in this case, mtx)
ino = search(ip, name[i]) - 1;
if (ino < 0)
error();
getblk(iblk + (ino / 8), buf1);
ip = (INODE *)buf1 + (ino % 8);
}
// 3. WRITE YOUR CODE to step through the data block of root inode
//prints("read data block of root DIR\n\r");
if ((u16)ip->i_block[12]) //Read Indirect Block
getblk((u16)ip->i_block[12], buf2);
setes(0x1000); //load the blocks into memory starting from (segment) 0x1000
for (i = 0; i < 12; i++)
{ //Gets DIRECT Blocks
getblk((u16)ip->i_block[i], 0);
inces(); // inc ES by 1KB/16 = 0x40
}
if ((u16)ip->i_block[12])
{ //Gets INDIRECT Blocks
up = (u32 *)buf2;
while (*up)
{
getblk((u16)*up, 0);
up++;
inces(); // inc ES by 1KB/16 = 0x40
}
}
getc();
}<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// interrupts.c file
int kprintf(char *fmt, ...);
/* all other handlers are infinite loops */
void __attribute__((interrupt)) undef_handler(void)
{
kprintf("undef exception\n");
while(1);
}
//void __attribute__((interrupt)) swi_handler(void) { for(;;); }
void __attribute__((interrupt)) prefetch_abort_handler(void)
{
kprintf("prefetch exception\n");
while(1);
}
void DATA_handler(void)
{
u32 fault_status, fault_addr, domain, status;
int spsr = get_spsr();
int oldcolor = color;
color = RED;
kprintf("data_abort exception in ");
if ((spsr & 0x1F)==0x13)
kprintf("SVC mode\n");
if ((spsr & 0x1F)==0x10)
kprintf("USER mode\n");
fault_status = get_fault_status();
fault_addr = get_fault_addr();
// fault_status = 7654 3210
// doma status
domain = (fault_status & 0xF0) >> 4;
status = fault_status & 0xF;
kprintf("domain=%x status=%x addr=%x\n", domain, status, fault_addr);
//kprintf("data_abort handler return\n");
color = oldcolor;
}
void __attribute__((interrupt)) fiq_handler(void) { for(;;); }
<file_sep>//// grep.c
#include "ucode.c"
char buf[1024], tty[32];
int main(int argc, char *argv[])
{
int in, out = 1, n_byt;
char line[128], *pattern, c;
gettty(tty);
int tty_o = open(tty, O_WRONLY);
if (argc < 2)
return -1;
if (argc == 2)
{
pattern = argv[1];
in = 0;
}
else
{ // contains filename
pattern = argv[1];
in = open(argv[2], O_RDONLY);
if (in < 1)
{
return;
}
}
int len = 0;
int i = 0, j = 0;
while (pattern[len] != '\0')
{ /// Gets length of pattern
len++;
}
int to_print = 0;
while (1)
{
n_byt = read(in, buf, 1);
if (n_byt < 1)
break;
line[i] = buf[0];
if (buf[0] == 10)
{
line[++i] = '\n';
if (to_print)
{
write(out, line, i);
write(tty_o, "\r", 1);
}
to_print = 0;
i = j = 0;
memset(line, 0, 128);
}
else
{
if (line[i] == pattern[j])
{
j++;
if (j == len && !to_print)
{
to_print = 1;
}
}
else
{
j = 0;
}
i++;
}
}
close(in);
close(out);
}<file_sep>Run these commands:
1.) ./mk
2.) ./q
<file_sep>//// cp.c
#include "ucode.c"
int main(int argc, char *argv[])
{
char buf[BLKSIZE];
int fd_src, fd_dest;
int n, bytes = 0;
if (argc < 3)
{ /// No source/destination file provided
exit(1);
}
fd_src = open(argv[1], O_RDONLY); // Opens source for input
if (fd_src < 0)
{ /// open src file failed
exit(2);
}
fd_dest = open(argv[2], O_WRONLY | O_CREAT); // Opens destination for output
if (fd_dest < 0)
{ /// Open dest file failed
exit(3);
}
while (n = read(fd_src, buf, BLKSIZE))
{ /// Writes src -> dest per char
write(fd_dest, buf, n);
}
close(fd_src);
close(fd_dest);
exit(0);
}<file_sep>/****************************************************************************
* KCW testing ext2 file system *
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ext2fs/ext2_fs.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>
#include "type.h"
MINODE minode[NMINODE];
MINODE *root;
PROC proc[NPROC], *running;
OFT oft[NOFT]; // !!!
char gpath[256];
char *name[64]; // assume at most 64 components in pathnames
int n;
int fd, dev;
int nblocks, ninodes, bmap, imap, inode_start;
char pathname[256], parameter[256];
#include "open_close_lseek.c"
#include "commands.c"
/********************
#include "util.c"
#include "alloc_dealloc.c"
#include "cd_ls_pwd.c"
#include "mkdir.c"
#include "creat.c"
#include "rmdir.c"
#include "link_unlink.c"
*********************/
int init()
{
int i, j;
MINODE *mip;
PROC *p;
printf("init()\n");
for (i=0; i<NMINODE; i++){
mip = &minode[i];
mip->dev = mip->ino = 0;
mip->refCount = 0;
mip->mounted = 0;
mip->mptr = 0;
}
for (i=0; i<NPROC; i++){
p = &proc[i];
p->pid = i;
p->uid = 0;
p->cwd = 0;
p->status = FREE;
for (j=0; j<NFD; j++)
p->fd[j] = 0;
}
}
// load root INODE and set root pointer to it
int mount_root()
{
printf("mount_root()\n");
root = iget(dev, 2);
}
//char *disk = "disk";
char *disk = "mydisk";
int main(int argc, char *argv[ ])
{
int ino;
char buf[BLKSIZE];
char line[256], cmd[64], path[128];
if (argc > 1)
disk = argv[1];
printf("checking EXT2 FS ....");
if ((fd = open(disk, O_RDWR)) < 0){
printf("open %s failed\n", disk); exit(1);
}
dev = fd;
/********** read super block at 1024 ****************/
get_block(dev, 1, buf);
sp = (SUPER *)buf;
/* verify it's an ext2 file system *****************/
if (sp->s_magic != 0xEF53){
printf("magic = %x is not an ext2 filesystem\n", sp->s_magic);
exit(1);
}
printf("OK\n");
ninodes = sp->s_inodes_count;
nblocks = sp->s_blocks_count;
get_block(dev, 2, buf);
gp = (GD *)buf;
bmap = gp->bg_block_bitmap;
imap = gp->bg_inode_bitmap;
inode_start = gp->bg_inode_table;
printf("bmp=%d imap=%d inode_start = %d\n", bmap, imap, inode_start);
init();
mount_root();
//printf("root refCount = %d\n", root->refCount);
printf("mydisk mounted on / OK\n");
printf("creating P0 as running process\n");
running = &proc[0];
running->status = READY;
running->cwd = iget(dev, 2);
//printf("root refCount = %d\n", root->refCount);
//printf("hit a key to continue : "); getchar();
while(1){
printf("\n[ls|cd|pwd|mkdir|creat|rmdir|link|unlink|symlink|readlink|quit]");
printf("[open|close|lseek|read|write|cat|cp|mv|pfd]\nInput a Command:\n>> ");
gets(line);
if (line[0]==0)
continue;
pathname[0] = 0;
parameter[0] = 0;
sscanf(line, "%s %s %s", cmd, pathname, parameter);
printf("cmd=%s path=%s param=%s\n", cmd, pathname, parameter);
if (strcmp(cmd, "ls")==0)
list_file();
if (strcmp(cmd, "cd")==0)
change_dir();
if (strcmp(cmd, "pwd")==0)
pwd(running->cwd);
if (strcmp(cmd, "mkdir")==0)
make_dir();
if (strcmp(cmd, "creat")==0)
creat_file();
if (strcmp(cmd, "rmdir")==0)
rmdir();
if (strcmp(cmd, "link")==0)
link();
if (strcmp(cmd, "unlink")==0)
unlink();
if (strcmp(cmd, "symlink")==0)
symlink();
if (strcmp(cmd, "readlink")==0){
readlink(line);
printf("symlink name = %s\n", line);
}
// -------------
if (strcmp(cmd, "open")==0){
open_file();
}
if (strcmp(cmd, "close")==0){
printf("CLOSING FILE");
myclose();
}
if (strcmp(cmd, "lseek")==0){
lseek_file();
}
if (strcmp(cmd, "pfd")==0){
pfd();
}
if (strcmp(cmd, "read")==0){
read_file();
}
if (strcmp(cmd, "write")==0){
write_file();
}
if (strcmp(cmd, "cat")==0){
mycat();
}
if (strcmp(cmd, "cp")==0){
cp();
}
if (strcmp(cmd, "mv")==0){
mymov();
}
// -------------
if (strcmp(cmd, "quit")==0)
quit();
}
}
int quit()
{
int i;
MINODE *mip;
for (i=0; i<NMINODE; i++){
mip = &minode[i];
if (mip->refCount > 0)
iput(mip);
}
exit(0);
}<file_sep>/*************** type.h file ************************/
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef struct ext2_super_block SUPER;
typedef struct ext2_group_desc GD;
typedef struct ext2_inode INODE;
typedef struct ext2_dir_entry_2 DIR;
SUPER *sp;
GD *gp;
INODE *ip;
DIR *dp;
#define FREE 0
#define READY 1
#define BLKSIZE 1024
#define NMINODE 256
#define NFD 64
#define NPROC 16
#define NOFT 20 // !!!
typedef struct minode{
INODE INODE;
int dev, ino;
int refCount;
int dirty;
int mounted;
struct mntable *mptr;
}MINODE;
typedef struct oft{
int mode;
int refCount;
MINODE *mptr;
int offset;
}OFT;
typedef struct proc{
struct proc *next;
int pid;
int ppid;
int status;
int uid, gid;
MINODE *cwd;
OFT *fd[NFD];
}PROC;
<file_sep>//// cat.c
#include "ucode.c"
int main(int argc, char *argv[])
{
int fd, n, i, terminal;
char c, c2, buf[BLKSIZE], ret = '\r';
char *tty;
if (argc < 2)
{ /// use stdin
while (gets(buf))
{
write(2, buf, (int)strlen(buf));
write(2, "\n\r", 2);
}
}
else if (argc >= 2)
{ /// filename provided
fd = open(argv[1], O_RDONLY);
if (fd < 0)
exit(1);
while ((n = read(fd, buf, BLKSIZE)) > 0)
{ /// Read through fd
for (i = 0; i < n; i++)
{
write(1, &(buf[i]), 1); // Write to fd 1 the character
if (buf[i] == '\n')
write(2, &ret, 1); // Write return for new line
}
for (i = 0; i < BLKSIZE; i++)
buf[i] = 0;
}
}
close(fd); // Close file descriptor
exit(0);
}<file_sep>//// l2u
#include "ucode.c"
int main(int argc, char *argv[ ])
{
int fd_src, fd_dest, n, c;
char buf[BLKSIZE], *cp;
fd_src = open(argv[1], O_RDONLY);
if (argc == 1)
{
while( read(0, &c, 1) > 0)
{
if ( c >= 'a' && c <= 'z')
printc(c - 'a' + 'A');
else
printc(c);
if (c == '\r')
printc('\n');
}
exit(0);
}
if (fd_src < 0)
{ /// Not enough arguments
exit(1);
}
fd_dest = open(argv[2], O_WRONLY|O_CREAT);
while( n = read(fd_src, buf, BLKSIZE) )
{
cp = buf;
while(cp < buf + n)
{
if (*cp >= 'a' && *cp <= 'z')
{
*cp = *cp - 'a' + 'A';
}
cp++;
}
write(fd_dest, buf, n);
}
exit(0);
}<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// timer.c file
#define CTL_ENABLE ( 0x00000080 )
#define CTL_MODE ( 0x00000040 )
#define CTL_INTR ( 0x00000020 )
#define CTL_PRESCALE_1 ( 0x00000008 )
#define CTL_PRESCALE_2 ( 0x00000004 )
#define CTL_CTRLEN ( 0x00000002 )
#define CTL_ONESHOT ( 0x00000001 )
typedef volatile struct timer{
u32 LOAD; // Load Register, TimerXLoad 0x00
u32 VALUE; // Current Value Register, TimerXValue, read only 0x04
u32 CONTROL; // Control Register, TimerXControl 0x08
u32 INTCLR; // Interrupt Clear Register, TimerXIntClr, write only 0x0C
u32 RIS; // Raw Interrupt Status Register, TimerXRIS, read only 0x10
u32 MIS; // Masked Interrupt Status Register,TimerXMIS, read only 0x14
u32 BGLOAD; // Background Load Register, TimerXBGLoad 0x18
u32 *base;
}TIMER;
volatile TIMER *tp[4]; // 4 timers; 2 timers per unit; at 0x00 and 0x20
// timer0 base=0x101E2000; timer1 base=0x101E2020
// timer3 base=0x101E3000; timer1 base=0x101E3020
int kprintf(char *fmt, ...);
//extern int strcpy(char *, char *);
extern int row, col;
int kpchar(char, int, int);
int unkpchar(char, int, int);
int srow, scol;
char clock[16];
char *blanks = " : : ";
int hh, mm, ss;
u32 tick=0;
int oldcolor;
void timer0_handler() {
int ris,mis, value, load, bload, i;
ris = tp[0]->RIS;
mis = tp[0]->MIS;
value = tp[0]->VALUE;
load = tp[0]->LOAD;
bload=tp[0]->BGLOAD;
tick++; ss = tick;
ss %= 60;
if ((ss % 60)==0){
mm++;
if ((mm % 60)==0){
mm = 0;
hh++;
}
}
oldcolor = color;
color = GREEN;
for (i=0; i<8; i++){
unkpchar(clock[i], 0, 70+i);
}
clock[7]='0'+(ss%10); clock[6]='0'+(ss/10);
clock[4]='0'+(mm%10); clock[3]='0'+(mm/10);
clock[1]='0'+(hh%10); clock[0]='0'+(hh/10);
for (i=0; i<8; i++){
kpchar(clock[i], 0, 70+i);
}
timer_clearInterrupt(0);
color = oldcolor;
return;
}
void timer_init()
{
int i;
kprintf("timer_init() ");
// set timer base address
tp[0] = (TIMER *)(0x101E2000);
tp[1] = (TIMER *)(0x101E2020);
tp[2] = (TIMER *)(0x101E3000);
tp[3] = (TIMER *)(0x101E3020);
// set control counter regs to defaults
for (i=0; i<4; i++){
tp[i]->LOAD = 0x0; // reset
tp[i]->VALUE= 0xFFFFFFFF;
tp[i]->RIS = 0x0;
tp[i]->MIS = 0x0;
tp[i]->LOAD = 0x100;
tp[i]->CONTROL = 0x62; // 011- 0000=|NOTEn|Pe|IntE|-|scal=00|32-bit|0=wrap|
tp[i]->BGLOAD = 0xF0000;
}
strcpy(clock, "00:00:00");
hh = mm = ss = 0;
}
void timer_start(int n) // timer_start(0), 1, etc.
{
TIMER *tpr;
kprintf("timer_start: ");
tpr = tp[n];
tpr->CONTROL |= 0x80; // set enable bit 7
}
int timer_clearInterrupt(int n) // timer_start(0), 1, etc.
{
TIMER *tpr = tp[n];
tpr->INTCLR = 0xFFFFFFFF;
}
void timer_stop(int n) // timer_start(0), 1, etc.
{
TIMER *tptr = tp[n];
tptr->CONTROL &= 0x7F; // clear enable bit 7
}
<file_sep>arm-none-eabi-as -mcpu=arm926ej-s -g ts.s -o ts.o
arm-none-eabi-gcc -c -mcpu=arm926ej-s -g t.c -o t.o
arm-none-eabi-ld -T t.ld ts.o t.o -o t.elf
arm-none-eabi-objcopy -O binary t.elf t.bin
rm *.o *.elf
echo ready to go?
read dummy
qemu-system-arm -M versatilepb -m 128M -kernel t.bin -serial mon:stdio
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
#define DR 0x00
#define FR 0x18
#define RXFE 0x10
#define TXFF 0x20
//char *tab = "0123456789ABCDEF";
typedef struct uart
{
char *base;
int n;
} UART;
UART uart[4];
int uart_init()
{
int i;
UART *up;
for (i = 0; i < 4; i++)
{
up = &uart[i];
up->base = (char *)(0x101F1000 + i * 0x1000);
up->n = i;
}
uart[3].base = (char *)(0x10009000); // uart3 at 0x10009000
}
int ugetc(UART *up)
{
while (*(up->base + FR) & RXFE)
;
return *(up->base + DR);
}
int uputc(UART *up, char c)
{
while (*(up->base + FR) & TXFF)
;
*(up->base + DR) = c;
}
int ugets(UART *up, char *s)
{
while ((*s = (char)ugetc(up)) != '\r')
{
uputc(up, *s);
s++;
}
*s = 0;
}
int uprints(UART *up, char *s)
{
while (*s)
uputc(up, *s++);
}
//Source(s): Book + vid.c (Lab 2 Part 2)
int urpx(UART *up, int x)
{
char c;
if (x)
{
c = tab[x % 16];
urpx(up, x / 16);
}
uputc(up, c);
}
int urpu(UART *up, int x)
{
char c;
if (x)
{
c = tab[x % 10];
urpu(up, x / 10);
}
uputc(up, c);
}
int uprintx(UART *up, int x)
{
uprints(up, "0x");
if (x == 0)
uputc(up, '0');
else
urpx(up, x);
uputc(up, ' ');
}
int uprintu(UART *up, int x)
{
if (x == 0)
uputc(up, '0');
else
urpu(up, x);
uputc(up, ' ');
}
int uprinti(UART *up, int x)
{
if (x < 0)
{
uputc(up, '-');
x = -x;
}
uprintu(up, x);
}
/** WRITE YOUR uprintf(UART *up, char *fmt, . . .) for formatted print **/
int uprintf(char *fmt, ...)
{
int *ip;
char *cp;
cp = fmt;
ip = (int *)&fmt + 1;
UART *up = &uart[0];
while (*cp)
{
if (*cp != '%')
{
uputc(up, *cp);
if (*cp == '\n')
uputc(up, '\r');
cp++;
continue;
}
cp++;
switch (*cp)
{
case 'c':
uputc(up, (char)*ip);
break;
case 's':
uprints(up, (char *)*ip);
break;
case 'd':
uprinti(up, *ip);
break;
case 'u':
uprintu(up, *ip);
break;
case 'x':
uprintx(up, *ip);
break;
}
cp++;
ip++;
}
}<file_sep># create .o files from .bmp image files; to be included as RAW data sections
arm-none-eabi-objcopy -I binary -O elf32-littlearm -B arm wsu.bmp wsu.o
# show exported symbols
nm -S -t d wsu.o
# compile-link
arm-none-eabi-as -mcpu=arm926ej-s -g ts.s -o ts.o
arm-none-eabi-gcc -c -mcpu=arm926ej-s -g t.c -o t.o
arm-none-eabi-ld -T t.ld ts.o t.o -o t.elf
arm-none-eabi-objcopy -O binary t.elf t.bin
rm *.o *.elf
echo ready to go?
read dummy
qemu-system-arm -M versatilepb -m 128M -kernel t.bin -serial mon:stdio
<file_sep>//#include "type.h"
int bsector;
int bmap, imap, iblk, blk, offset;
char buf[1024], buf1[1024], buf2[1024];
int search(INODE *ip, char *name)
{
int i;
char c, *cp;
DIR *dp;
printf("search for %s: ", name);
for (i = 0; i < 12; i++)
{
if (ip->i_block[i])
{
//printf("i_block[%d] = %d\n", i, ip->i_block[i]);
getblock(ip->i_block[i], buf2);
dp = (DIR *)buf2;
cp = buf2;
while (cp < &buf2[1024])
{
c = dp->name[dp->name_len]; // save last byte
dp->name[dp->name_len] = 0;
printf("%s ", dp->name);
if (strcmp(dp->name, name) == 0)
{
printf("found %s\n", name);
return (dp->inode);
}
dp->name[dp->name_len] = c; // restore that last byte
cp += dp->rec_len;
dp = (DIR *)cp;
}
}
}
printf("search failed\n");
}
load(char *filename, PROC *p)
{
int i, me, blk, iblk, count;
char *cp, *name[2], *addr;
u32 *up;
GD *gp;
INODE *ip;
DIR *dp;
name[0] = "bin";
name[1] = filename;
addr = (char *)(0x800000 + (p->pid - 1) * 0x100000);
printf("loading %s: ", filename);
/* read blk#2 to get group descriptor 0 */
getblock(2, buf1);
gp = (GD *)buf1;
iblk = (u16)gp->bg_inode_table;
printf("iblk=%d ", iblk);
getblock(iblk, buf1); // read first inode block block
ip = (INODE *)buf1 + 1; // ip->root inode #2
/* serach for system name */
for (i = 0; i < 2; i++)
{
me = search(ip, name[i]) - 1;
if (me < 0)
return 0;
getblock(iblk + (me / 8), buf1); // read block inode of me
ip = (INODE *)buf1 + (me % 8);
}
/* read indirect block into b2 */
if (ip->i_block[12]) // only if has indirect blocks
getblock(ip->i_block[12], buf2);
count = 0;
for (i = 0; i < 12; i++)
{
if (ip->i_block[i] == 0)
break;
//printf("location=%x count=%d\n", location, count);
getblock(ip->i_block[i], addr);
kputc('*');
addr += 1024;
count += 1024;
}
if (ip->i_block[12])
{ // only if file has indirect blocks
up = (u32 *)buf2;
while (*up)
{
getblock(*up, addr);
kputc('.');
addr += 1024;
up++;
count += 1024;
}
}
// printf("\n");
printf(" %d bytes loaded\n", count);
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// type.h file
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#define VA(x) (0x80000000 + (u32)x)
#define PA(x) (0x80000000 - (u32)x)
#define UART0_BASE_ADDR 0x101f1000
#define UART0_DR (*((volatile u32 *)(UART0_BASE_ADDR + 0x000)))
#define UART0_FR (*((volatile u32 *)(UART0_BASE_ADDR + 0x018)))
#define UART0_IMSC (*((volatile u32 *)(UART0_BASE_ADDR + 0x038)))
#define UART1_BASE_ADDR 0x101f2000
#define UART1_DR (*((volatile u32 *)(UART1_BASE_ADDR + 0x000)))
#define UART1_FR (*((volatile u32 *)(UART1_BASE_ADDR + 0x018)))
#define UART1_IMSC (*((volatile u32 *)(UART1_BASE_ADDR + 0x038)))
#define KBD_BASE_ADDR 0x10006000
#define KBD_CR (*((volatile u32 *)(KBD_BASE_ADDR + 0x000)))
#define KBD_DR (*((volatile u32 *)(KBD_BASE_ADDR + 0x008)))
#define TIMER0_BASE_ADDR 0x101E2000
#define TIMER0_LR (*((volatile u32 *)(UART0_BASE_ADDR + 0x000)))
#define TIMER0_BR (*((volatile u32 *)(UART0_BASE_ADDR + 0x032)))
#define VIC_BASE_ADDR 0x10140000
#define VIC_STATUS (*((volatile u32 *)(VIC_BASE_ADDR + 0x000)))
#define VIC_INTENABLE (*((volatile u32 *)(VIC_BASE_ADDR + 0x010)))
#define VIC_VADDR (*((volatile u32 *)(VIC_BASE_ADDR + 0x030)))
#define SIC_BASE_ADDR 0x10003000
#define SIC_STATUS (*((volatile u32 *)(SIC_BASE_ADDR + 0x000)))
#define SIC_INTENABLE (*((volatile u32 *)(SIC_BASE_ADDR + 0x008)))
#define SIC_ENSET (*((volatile u32 *)(SIC_BASE_ADDR + 0x008)))
#define SIC_PICENSET (*((volatile u32 *)(SIC_BASE_ADDR + 0x020)))
#define LINES 4
#define N_SCAN 64
#define BLUE 0
#define GREEN 1
#define RED 2
#define CYAN 3
#define YELLOW 4
#define PURPLE 5
#define WHITE 6
#define SSIZE 1024
#define NPROC 9
#define FREE 0
#define READY 1
#define SLEEP 2
#define BLOCK 3
#define ZOMBIE 4
#define printf kprintf
typedef struct proc{
struct proc *next;
int *ksp; // at 4
int *usp; // at 8 : Umode sp at time of syscall
int *upc; // at 12: linkR at time of syscall
int *cpsr; // at 16: Umode cpsr
int *ucpsr; // at 16: cpsr in user mode
u32 *pgdir; // level-1 page table pointer
int inkmode;
int status;
int priority;
int pid;
int ppid;
struct proc *parent;
int event;
int exitCode;
char name[64];
int kstack[SSIZE];
}PROC;
/**********************************************************************
pgdir of PROC in ARM:
initial plan: each PROC has a dedicated pgdir at 6M or 7MB by pid
in 7MB: 4KB for each pgdir ==> has space for 1m/4K= 256 pgdirs
defined as pgdir[256], for P0 to P255
P0: pgdir = initial PGDIR= low 2048 entries map 0-2G to PA(0-2G)
high 2048 entries map 2G-4G to PA(0-memSize)
Each Pi>0: pgdir = [
low entry 0: map VA(0-1M) to its PA at 8MB+(pid-1)1B
high entires: map VA(2G-mem) to (0-mem) for kernel access
]
During task switch: must switch to next running's pgdir (and flush TLB)
**********************************************************************/
#define BLOCK_SIZE 1024
#define BLKSIZE 1024
/*
typedef unsigned long u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef unsigned short ushort;
typedef unsigned long ulong;
*/
typedef struct ext2_super_block {
u32 s_inodes_count; /* Inodes count */
u32 s_blocks_count; /* Blocks count */
u32 s_r_blocks_count; /* Reserved blocks count */
u32 s_free_blocks_count; /* Free blocks count */
u32 s_free_inodes_count; /* Free inodes count */
u32 s_first_data_block; /* First Data Block */
u32 s_log_block_size; /* Block size */
u32 s_log_frag_size; /* Fragment size */
u32 s_blocks_per_group; /* # Blocks per group */
u32 s_frags_per_group; /* # Fragments per group */
u32 s_inodes_per_group; /* # Inodes per group */
u32 s_mtime; /* Mount time */
u32 s_wtime; /* Write time */
u16 s_mnt_count; /* Mount count */
u16 s_max_mnt_count; /* Maximal mount count */
u16 s_magic; /* Magic signature */
u16 s_state; /* File system state */
u16 s_errors; /* Behaviour when detecting errors */
u16 s_minor_rev_level; /* minor revision level */
u32 s_lastcheck; /* time of last check */
u32 s_checkinterval; /* max. time between checks */
u32 s_creator_os; /* OS */
u32 s_rev_level; /* Revision level */
u16 s_def_resuid; /* Default uid for reserved blocks */
u16 s_def_resgid; /* Default gid for reserved blocks */
/*
* These fields are for EXT2_DYNAMIC_REV superblocks only.
*
* Note: the difference between the compatible feature set and
* the incompatible feature set is that if there is a bit set
* in the incompatible feature set that the kernel doesn't
* know about, it should refuse to mount the filesystem.
*
* e2fsck's requirements are more strict; if it doesn't know
* about a feature in either the compatible or incompatible
* feature set, it must abort and not try to meddle with
* things it doesn't understand...
*/
u32 s_first_ino; /* First non-reserved inode */
u16 s_inode_size; /* size of inode structure */
u16 s_block_group_nr; /* block group # of this superblock */
u32 s_feature_compat; /* compatible feature set */
u32 s_feature_incompat; /* incompatible feature set */
u32 s_feature_ro_compat; /* readonly-compatible feature set */
u8 s_uuid[16]; /* 128-bit uuid for volume */
char s_volume_name[16]; /* volume name */
char s_last_mounted[64]; /* directory where last mounted */
u32 s_reserved[206]; /* Padding to the end of the block */
}SUPER;
typedef struct ext2_group_desc
{
u32 bg_block_bitmap; /* Blocks bitmap block */
u32 bg_inode_bitmap; /* Inodes bitmap block */
u32 bg_inode_table; /* Inodes table block */
u16 bg_free_blocks_count; /* Free blocks count */
u16 bg_free_inodes_count; /* Free inodes count */
u16 bg_used_dirs_count; /* Directories count */
u16 bg_pad;
u32 bg_reserved[3];
}GD;
typedef struct ext2_inode {
u16 i_mode; /* File mode */
u16 i_uid; /* Owner Uid */
u32 i_size; /* Size in bytes */
u32 i_atime; /* Access time */
u32 i_ctime; /* Creation time */
u32 i_mtime; /* Modification time */
u32 i_dtime; /* Deletion Time */
u16 i_gid; /* Group Id */
u16 i_links_count; /* Links count */
u32 i_blocks; /* Blocks count */
u32 i_flags; /* File flags */
u32 dummy;
u32 i_block[15]; /* Pointers to blocks */
u32 pad[5]; /* inode size MUST be 128 bytes */
u32 i_date; /* MTX date */
u32 i_time; /* MTX time */
}INODE;
typedef struct ext2_dir_entry_2 {
u32 inode; /* Inode number */
u16 rec_len; /* Directory entry length */
u8 name_len; /* Name length */
u8 file_type;
char name[255]; /* File name */
}DIR;
<file_sep>int ksleep(int event)
{
int sr = int_off();
printf("proc %d going to sleep on event=%d\n", running->pid, event);
running->event = event;
running->status = SLEEP;
enqueue(&sleepList, running);
//printList("sleepList", sleepList);
tswitch();
int_on(sr);
}
int kwakeup(int event)
{
PROC *temp, *p;
temp = 0;
int sr = int_off();
//printList("sleepList", sleepList);
while (p = dequeue(&sleepList))
{
if (p->event == event)
{
printf("wakeup %d\n", p->pid);
p->status = READY;
enqueue(&readyQueue, p);
}
else
{
enqueue(&temp, p);
}
}
sleepList = temp;
//printList("sleepList", sleepList);
int_on(sr);
}
int kexit(int exitValue)
{
int i;
PROC *p;
for (i = 2; i < NPROC; i++)
{ // Skip root proc[0] and proc[1]
p = &proc[i];
/// Child sent to parent (orphanage)
if (p->status != FREE && p->ppid == running->pid)
{
if (p->status == ZOMBIE)
{
p->status = FREE;
enqueue(&freeList, p); //Release all ZOMBIE childs
}
else
{
printf("Send child &d to proc[1] (parent)\n", p->pid);
p->ppid = 1;
p->parent = &proc[1];
}
}
}
running->exitCode = exitValue; // Record exitValue in proc for parent
running->status = ZOMBIE; // Will not free PROC
//enqueue(&zombieList, p);
kwakeup(&proc[1]);
kwakeup(running->parent);
tswitch(); //Switch process to give up CPU
}
int kwait(int *status)
{ /// proc waits for (and disposes of) a ZOMBIE child.
int i, hasChild = 0;
PROC *p;
while (1)
{
for (i = 1; i < NPROC; i++)
{
p = &proc[i];
/// Search for (any) zombie child
if (p->status != FREE && p->ppid == running->pid)
{
hasChild = 1;
if (p->status == ZOMBIE)
{
//dequeue(&zombieList);
*status = p->exitCode; // Get exit code
p->status = FREE; // Set status to Free
enqueue(&freeList, p); // release child PROC to freelist
return (p->pid); // Return pid
}
}
}
if (!hasChild)
{
printf("[!] - NO CHILD FOUND / P1 NO DIE\n");
return -1;
}
ksleep(running);
}
}<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
int body(), goUmode();
PROC *kfork(char *filename)
{
int i;
int *ptable, pentry;
char *addr;
PROC *p = dequeue(&freeList);
if (p == 0)
{
kprintf("kfork failed\n");
return (PROC *)0;
}
p->ppid = running->pid;
p->parent = running;
p->parent = running;
p->status = READY;
p->priority = 1;
p->cpsr = (int *)0x10;
// build p's pgtable
p->pgdir = (int *)(0x600000 + (p->pid - 1) * 0x4000);
ptable = p->pgdir;
// initialize pgtable
for (i = 0; i < 4096; i++)
ptable[i] = 0;
pentry = 0x412;
for (i = 0; i < 258; i++)
{
ptable[i] = pentry;
pentry += 0x100000;
}
// ptable entry flag=|AP0|doma|1|CB10|=110|0001|1|1110|=0xC3E or 0xC32
//ptable[2048] = 0x800000 + (p->pid - 1)*0x100000|0xC3E;
ptable[2048] = 0x800000 + (p->pid - 1) * 0x100000 | 0xC32;
p->cpsr = (int *)0x10; // previous mode was Umode
// set kstack to resume to goUmode, then to VA=0 in Umode image
for (i = 1; i < 29; i++) // all 28 cells = 0
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE - 15] = (int)goUmode; // in dec reg=address ORDER !!!
p->ksp = &(p->kstack[SSIZE - 28]);
// kstack must contain a resume frame FOLLOWed by a goUmode frame
// ksp
// -|-----------------------------------------
// r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 fp ip pc|
// -------------------------------------------
// 28 27 26 25 24 23 22 21 20 19 18 17 16 15
//
// usp NOTE: r0 is NOT saved in svc_entry()
// -|-----goUmode--------------------------------
// r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 ufp uip upc|
//-------------------------------------------------
// 14 13 12 11 10 9 8 7 6 5 4 3 2 1
/********************
// to go Umode, must set new PROC's Umode cpsr to Umode=10000
// this was done in ts.s dring init the mode stacks ==>
// user mode's cspr was set to IF=00, mode=10000
***********************/
// must load filename to Umode image area at 7MB+(pid-1)*1MB
addr = (char *)(0x700000 + (p->pid) * 0x100000);
load(filename, p);
// must fix Umode ustack for it to goUmode: how did the PROC come to Kmode?
// by swi # from VA=0 in Umode => at that time all CPU regs are 0
// we are in Kmode, p's ustack is at its Uimage (8mb+(pid-1)*1mb) high end
// from PROC's point of view, it's a VA at 1MB (from its VA=0)
// but we in Kmode must access p's Ustack directly
/***** this sets each proc's ustack differently, thinking each in 8MB+
ustacktop = (int *)(0x800000+(p->pid)*0x100000 + 0x100000);
TRY to set it to OFFSET 1MB in its section; regardless of pid
**********************************************************************/
//p->usp = (int *)(0x80100000);
p->usp = (int *)VA(0x100000);
// p->kstack[SSIZE-1] = (int)0x80000000;
p->kstack[SSIZE - 1] = VA(0);
// -|-----goUmode-------------------------------------------------
// r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 ufp uip upc|string |
//----------------------------------------------------------------
// 14 13 12 11 10 9 8 7 6 5 4 3 2 1 | |
enqueue(&readyQueue, p);
kprintf("proc %d kforked a child %d: ", running->pid, p->pid);
printQ(readyQueue);
return p;
}
int fork()
{
// fork a CHILD process as in Unix/Linux
int i, PA, CA;
PROC *p = getproc();
if (p == 0)
{
printf("fork failed\n");
return -1;
}
p->ppid = running->pid;
p->parent = running;
p->status = READY;
p->priority = 1;
// build p's pgtable
p->pgdir = (int *)(0x600000 + (p->pid - 1) * 0x4000);
int *ptable = p->pgdir;
// initialize pgtable
for (i = 0; i < 4096; i++)
ptable[i] = 0;
int pentry = 0x412;
for (i = 0; i < 258; i++)
{
ptable[i] = pentry;
pentry += 0x100000;
}
ptable[2048] = 0x800000 + (p->pid - 1) * 0x100000 | 0xC32;
printf("running usp = %x linkR = %x\n", running->usp, running->upc);
PA = (running->pgdir[2048] & 0xFFFF0000);
CA = (p->pgdir[2048] & 0xFFFF0000);
printf("FORK: child %d uimage at %x\n", p->pid, CA);
printf("copy Umode image from %x to %x\n", PA, CA);
memcpy((char *)CA, (char *)PA, 0x100000);
p->usp = running->usp;
p->ucpsr = running->ucpsr;
for (i = 1; i <= 14; i++)
{
p->kstack[SSIZE - i] = running->kstack[SSIZE - i];
}
for (i = 15; i <= 28; i++)
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE - 14] = 0;
p->kstack[SSIZE - 15] = (int)goUmode;
p->ksp = &(p->kstack[SSIZE - 28]);
enqueue(&readyQueue, p);
printf("KERNEL: proc %d forked a child %d\n", running->pid, p->pid);
printQ(readyQueue);
return p->pid;
}<file_sep>#define TLOAD 0x0
#define TVALUE 0x1
#define TCNTL 0x2
#define TINTCLR 0x3
#define TRIS 0x4
#define TMIS 0x5
#define TBGLOAD 0x6
typedef volatile struct timer{
u32 *base; // timer's base address; as u32 pointer
int tick, ss, proc_id; // per timer data area
char clock[16];
}TIMER;
int total_timers = 0;
volatile TIMER timer[4]; //4 timers; 2 per unit; at 0x00 and 0x20
void timer_init()
{
int i; TIMER *tp;
printf("timer_init()\n");
for (i=0; i<4; i++){
tp = &timer[i];
if (i==0) tp->base = (u32 *)0x101E2000;
if (i==1) tp->base = (u32 *)0x101E2020;
if (i==2) tp->base = (u32 *)0x101E3000;
if (i==3) tp->base = (u32 *)0x101E3020;
*(tp->base+TLOAD) = 0x0; // reset
*(tp->base+TVALUE)= 0xFFFFFFFF;
*(tp->base+TRIS) = 0x0;
*(tp->base+TMIS) = 0x0;
*(tp->base+TLOAD) = 0x100;
// CntlReg=011-0010=|En|Pe|IntE|-|scal=01|32bit|0=wrap|=0x66
*(tp->base+TCNTL) = 0x62;
*(tp->base+TBGLOAD) = 0x1C00; // timer counter value
tp->proc_id = 0;
tp->ss = 0; // initialize wall clock
strcpy((char *)tp->clock, "");
}
}
int timer_handler(int n) {
int i;
TIMER *t = &timer[n];
char label[4];
t->tick++; // Assume 120 ticks per second
if (t->ss != 0) {
if (t->tick==100*total_timers){
t->tick = 0;
if (n == 0)
t->ss++;
else
t->ss--;
t->clock[7]='0'+(t->ss%10);
t->clock[6]='0'+(t->ss/10);
}
if (n == 0) {
color = GREEN; // display in different color
label[n] = 'C';
} else {
color = RED; // display in different color
label[n] = 'P';
}
label[1] = (t->proc_id + '0');
label[2] = ':';
label[3] = ' ';
for (i=0; i<8; i++){
kpchar(label[i], n, 65+i); // to line n of LCD
kpchar(t->clock[i], n, 70+i); // to line n of LCD
}
color = YELLOW; // Revert to original colo
timer_clearInterrupt(n); // clear timer interrupt
} else {
timer_clearInterrupt(n); // clear timer interrupt
/*int last_timer_index = total_timers-1;
if (n > 0 && n != last_timer_index) { //if timer is > 2, swap to keep array consistent. Move deleting to end of list
printf("---- SWAPPING: %d > 0, timer[%d]\n", n, total_timers-1);
//TIMER *last_timer = &timer[last_timer_index];
//TIMER *timer_n = &timer[n];
//timer_n->proc_id = last_timer->proc_id;
//timer_n->ss = last_timer->ss;
//timer_n->tick = last_timer->tick;
//timer[n] = timer[last_timer_index];
//printf("timer[%d] id = %d, timer[%d] id = %d\n", n, timer_n->proc_id, total_timers-1, last_timer->proc_id);
}
return timer_stop(last_timer_index); //remove last timer in array
*/
return timer_stop(n);
}
return 0;
}
void timer_start(int n, int proc_id, int sec) // timer_start(0), 1, etc.
{
TIMER *tp = &timer[n];
tp->proc_id = proc_id;
tp->ss = sec;
kprintf("timer_start %d base=%x\n", n, tp->base);
*(tp->base+TCNTL) |= 0x80; // set enable bit 7
total_timers++;
}
int timer_clearInterrupt(int n) // timer_start(0), 1, etc.
{
TIMER *tp = &timer[n];
*(tp->base+TINTCLR) = 0xFFFFFFFF;
}
int timer_stop(int n) // stop a timer
{
TIMER *tp = &timer[n];
*(tp->base+TCNTL) &= 0x7F; // clear enable bit 7
total_timers--;
return tp->proc_id;
}<file_sep>/*********** t.c file of A Multitasking System *********/
#include <stdio.h>
#include "string.h"
#include "type.h"
PROC proc[NPROC]; // NPROC PROCs
PROC *freeList; // freeList of PROCs
PROC *readyQueue; // priority queue of READY procs
PROC *running; // current running proc pointer
PROC *sleepList; // list of SLEEP procs
struct semaphore full, empty, mutex;
#include "queue.c" // include queue.c file
#include "wait.c" // include wait.c file
#define PRSIZE 8
char buf[PRSIZE];
int head, tail;
//SEMAPHORE rwsem = 1, wsem = 1, rsem = 1;
//int nreader = 0; // Active Readers
/*******************************************************
kfork() creates a child process; returns child pid.
When scheduled to run, child PROC resumes to body();
********************************************************/
int body(), tswitch(), do_sleep(), do_wakeup(), do_exit(), do_switch();
int do_kfork();
int P(struct semaphore *s)
{ //Locking - print the BLOCKed process pid and semaphore queue;
int itr = 0;
PROC *p;
//int_off turns off interrupts, makes sure were alone
//itr = int_off();
//dec the value
s->value--;
//check the value
if(s-> value < 0)
{
running->status = BLOCK;
enqueue(&(s->queue), running); //Puts Proc in Semaphore Queue
tswitch(); //in the if? or out of the if?
}
//turn on interrupts again
//int_on(itr);
}
int V(struct semaphore *s)
{ //Unlocking - print the unBLOCKed process pid, semaphore queue and readyQueue;
int itr = 0;
PROC *p;
//int_off turns off interrupts, makes sure were alone
//itr = int_off();
//dec the value
s->value++;
//check the value
if(s->value <= 0)
{
p = dequeue(&(s->queue));
p->status = READY;
enqueue(&readyQueue, p);
}
//turn on interrupts again
//int_on(itr);
}
/*void Reader() {
while(1) {
P(rwsem);
P(rsem);
nreader++;
if (nreader == 1)
P(wsem);
V(rsem);
V(rwsem);
P(rsem);
nreader--;
if (nreader == 0)
V(wsem);
V(rsem);
}
}
void Write() {
while(1) {
P(rwsem);
P(wsem);
V(wsem);
V(rwsem);
}
}
*/
int producer() {
char c, *cp;
char line[PRSIZE];
while (1) {
//ugets(up, line);
printf("input something: ");
/// 1.) input a string
fgets(line,PRSIZE,stdin);
/// 2.) write chars of string to buff
strncpy(buf, line, PRSIZE);
cp = line;
while (*cp) {
printf("Producer %d P(empty=%d)\n", running->pid, empty.value);
P(&empty);
P(&mutex);
head %= PRSIZE;
V(&mutex);
printf("Producer %d V(full=%d)\n", running->pid, full.value);
V(&full);
}
}
}
int consumer() {
char c, line[PRSIZE];
int i;
/// 1.) get 10 chars from buf[]
strncpy(line, buf, 10);
/// 2.) show the chars
printf("buf[10]: %s\n", buf);
while(1) {
printf("Consumer %d P(full=%d)\n", running->pid, full.value);
P(&full);
P(&mutex);
c = buf[tail++];
tail %= PRSIZE;
V(&mutex);
printf("Consumer %d V(empty=%d) ", running->pid, empty.value);
V(&empty);
}
}
// initialize the MT system; create P0 as initial running process
int init()
{
int i;
PROC *p;
for (i=0; i<NPROC; i++){ // initialize PROCs
p = &proc[i];
p->pid = i; // PID = 0 to NPROC-1
p->status = FREE;
p->priority = 0;
p->next = p+1;
}
proc[NPROC-1].next = 0;
freeList = &proc[0]; // all PROCs in freeList
readyQueue = 0; // readyQueue = empty
sleepList = 0; // sleepList = empty
// create P0 as the initial running process
p = running = dequeue(&freeList); // use proc[0]
p->status = READY;
p->priority = 0;
p->ppid = 0; // P0 is its own parent
printList("freeList", freeList);
printf("init complete: P0 running\n");
}
int menu()
{
printf("****************************************\n");
printf(" ps fork switch exit jesus sleep wakeup \n");
printf("****************************************\n");
}
char *status[ ] = {"FREE", "READY", "SLEEP", "ZOMBIE", "BLOCK"};
int do_ps()
{
int i;
PROC *p;
printf("PID PPID status\n");
printf("--- ---- ------\n");
for (i=0; i<NPROC; i++){
p = &proc[i];
printf(" %d %d ", p->pid, p->ppid);
if (p == running)
printf("RUNNING\n");
else
printf("%s\n", status[p->status]);
}
}
int do_jesus()
{
int i;
PROC *p;
printf("Jesus perfroms miracles here\n");
for (i=1; i<NPROC; i++){
p = &proc[i];
if (p->status == ZOMBIE){
p->status = READY;
enqueue(&readyQueue, p);
printf("raised a ZOMBIE %d to live again\n", p->pid);
}
}
printList("readyQueue", readyQueue);
}
int body() // process body function
{
int c;
char cmd[64];
printf("proc %d starts from body()\n", running->pid);
while(1){
printf("***************************************\n");
printf("proc %d running: parent=%d\n", running->pid,running->ppid);
printList("readyQueue", readyQueue);
printSleep("sleepList ", sleepList);
menu();
printf("enter a command : ");
fgets(cmd, 64, stdin);
cmd[strlen(cmd)-1] = 0;
if (strcmp(cmd, "ps")==0)
do_ps();
if (strcmp(cmd, "fork")==0)
do_kfork();
if (strcmp(cmd, "switch")==0)
do_switch();
if (strcmp(cmd, "exit")==0)
do_exit();
if (strcmp(cmd, "jesus")==0)
do_jesus();
if (strcmp(cmd, "sleep")==0)
do_sleep();
if (strcmp(cmd, "wakeup")==0)
do_wakeup();
if (strcmp(cmd, "p")==0)
producer();
if (strcmp(cmd, "c")==0)
consumer();
}
}
int kfork()
{
int i;
PROC *p = dequeue(&freeList);
if (!p){
printf("no more proc\n");
return(-1);
}
/* initialize the new proc and its stack */
p->status = READY;
p->priority = 1; // ALL PROCs priority=1, except P0
p->ppid = running->pid;
/************ new task initial stack contents ************
kstack contains: |retPC|eax|ebx|ecx|edx|ebp|esi|edi|eflag|
-1 -2 -3 -4 -5 -6 -7 -8 -9
**********************************************************/
for (i=1; i<10; i++) // zero out kstack cells
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE-1] = (int)body; // retPC -> body()
p->ksp = &(p->kstack[SSIZE - 9]); // PROC.ksp -> saved eflag
enqueue(&readyQueue, p); // enter p into readyQueue
return p->pid;
}
int do_kfork()
{
int child = kfork();
if (child < 0)
printf("kfork failed\n");
else{
printf("proc %d kforked a child = %d\n", running->pid, child);
printList("readyQueue", readyQueue);
}
return child;
}
int do_switch()
{
tswitch();
}
int do_exit()
{
kexit(running->pid); // exit with own PID value
}
int do_sleep()
{
int event;
printf("enter an event value to sleep on : ");
scanf("%d", &event); getchar();
sleep(event);
}
int do_wakeup()
{
int event;
printf("enter an event value to wakeup with : ");
scanf("%d", &event); getchar();
wakeup(event);
}
/*************** main() function ***************/
int main()
{
printf("Welcome to the MT Multitasking System\n");
init(); // initialize system; create and run P0
kfork(); // kfork P1 into readyQueue
/* Product-Consumer */
head = tail = 0;
full.value = 0;
//full.queue = 0;
empty.value = PRSIZE;
//empty.queue = 0;
mutex.value = 1;
//mutex.queue = 0;
printf("P0 kfork tasks\n");
kfork((int)producer, 0); //157
kfork((int)consumer, 0);
kfork((int)producer, 1);
kfork((int)consumer, 1);
printf("PRODUCER + CONSUMER: \n");
printList("readyQueue", readyQueue);
while(1){
printf("P0: switch process\n");
while (readyQueue == 0);
tswitch();
}
}
/*********** scheduler *************/
int scheduler()
{
printf("proc %d in scheduler()\n", running->pid);
if (running->status == READY)
enqueue(&readyQueue, running);
printList("readyQueue", readyQueue);
running = dequeue(&readyQueue);
printf("next running = %d\n", running->pid);
}
<file_sep>// sdc.h file
#define COMMAND_REG_DELAY 300
#define DATA_REG_DELAY 1000
#define CLK_CHANGE_DELAY 2000
#define INIT_PWR 0xBF /* Power on, full power, not open drain */
#define ARM_MCLK (100*1000*1000)
#define MMC_CMD_GO_IDLE_STATE 0
#define MMC_CMD_SEND_OP_COND 1
#define MMC_CMD_ALL_SEND_CID 2
#define MMC_CMD_SET_RELATIVE_ADDR 3
#define MMC_CMD_SET_DSR 4
#define MMC_CMD_SWITCH 6
#define MMC_CMD_SELECT_CARD 7
#define MMC_CMD_SEND_EXT_CSD 8
#define MMC_CMD_SEND_CSD 9
#define MMC_CMD_SEND_CID 10
#define MMC_CMD_STOP_TRANSMISSION 12
#define MMC_CMD_SEND_STATUS 13
#define MMC_CMD_SET_BLOCKLEN 16
#define MMC_CMD_READ_SINGLE_BLOCK 17
#define MMC_CMD_READ_MULTIPLE_BLOCK 18
#define MMC_CMD_WRITE_SINGLE_BLOCK 24
#define MMC_CMD_WRITE_MULTIPLE_BLOCK 25
#define MMC_CMD_ERASE_GROUP_START 35
#define MMC_CMD_ERASE_GROUP_END 36
#define MMC_CMD_ERASE 38
#define MMC_CMD_APP_CMD 55
#define MMC_CMD_SPI_READ_OCR 58
#define MMC_CMD_SPI_CRC_ON_OFF 59
#define SD_CMD_SEND_RELATIVE_ADDR 3
#define SD_CMD_SWITCH_FUNC 6
#define SD_CMD_SEND_IF_COND 8
#define SD_CMD_APP_SET_BUS_WIDTH 6
#define SD_CMD_ERASE_WR_BLK_START 32
#define SD_CMD_ERASE_WR_BLK_END 33
#define SD_CMD_APP_SEND_OP_COND 41
#define SD_CMD_APP_SEND_SCR 51
#define CONFIG_ARM_PL180_MMCI_CLOCK_FREQ 6250000
#define MMC_RSP_PRESENT (1 << 0)
#define MMC_RSP_136 (1 << 1) /* 136 bit response */
#define MMC_RSP_CRC (1 << 2) /* expect valid crc */
#define MMC_RSP_BUSY (1 << 3) /* card may send busy */
#define MMC_RSP_OPCODE (1 << 4) /* response contains opcode */
#define MMC_RSP_NONE (0)
#define MMC_RSP_R1 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R1b (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE| \
MMC_RSP_BUSY)
#define MMC_RSP_R2 (MMC_RSP_PRESENT|MMC_RSP_136|MMC_RSP_CRC)
#define MMC_RSP_R3 (MMC_RSP_PRESENT)
#define MMC_RSP_R4 (MMC_RSP_PRESENT)
#define MMC_RSP_R5 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R6 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
#define MMC_RSP_R7 (MMC_RSP_PRESENT|MMC_RSP_CRC|MMC_RSP_OPCODE)
/* SDI Power Control register bits */
#define SDI_PWR_PWRCTRL_MASK 0x00000003
#define SDI_PWR_PWRCTRL_ON 0x00000003
#define SDI_PWR_PWRCTRL_OFF 0x00000000
#define SDI_PWR_DAT2DIREN 0x00000004
#define SDI_PWR_CMDDIREN 0x00000008
#define SDI_PWR_DAT0DIREN 0x00000010
#define SDI_PWR_DAT31DIREN 0x00000020
#define SDI_PWR_OPD 0x00000040
#define SDI_PWR_FBCLKEN 0x00000080
#define SDI_PWR_DAT74DIREN 0x00000100
#define SDI_PWR_RSTEN 0x00000200
#define VOLTAGE_WINDOW_MMC 0x00FF8080
#define VOLTAGE_WINDOW_SD 0x80010000
/* SDI clock control register bits */
#define SDI_CLKCR_CLKDIV_MASK 0x000000FF
#define SDI_CLKCR_CLKEN 0x00000100
#define SDI_CLKCR_PWRSAV 0x00000200
#define SDI_CLKCR_BYPASS 0x00000400
#define SDI_CLKCR_WIDBUS_MASK 0x00001800
#define SDI_CLKCR_WIDBUS_1 0x00000000
#define SDI_CLKCR_WIDBUS_4 0x00000800
/* V2 only */
#define SDI_CLKCR_WIDBUS_8 0x00001000
#define SDI_CLKCR_NEDGE 0x00002000
#define SDI_CLKCR_HWFC_EN 0x00004000
#define SDI_CLKCR_CLKDIV_INIT_V1 0x000000C6 /* MCLK/(2*(0xC6+1)) => 505KHz */
#define SDI_CLKCR_CLKDIV_INIT_V2 0x000000FD
/* SDI command register bits */
#define SDI_CMD_CMDINDEX_MASK 0x000000FF
#define SDI_CMD_WAITRESP 0x00000040
#define SDI_CMD_LONGRESP 0x00000080
#define SDI_CMD_WAITINT 0x00000100
#define SDI_CMD_WAITPEND 0x00000200
#define SDI_CMD_CPSMEN 0x00000400
#define SDI_CMD_SDIOSUSPEND 0x00000800
#define SDI_CMD_ENDCMDCOMPL 0x00001000
#define SDI_CMD_NIEN 0x00002000
#define SDI_CMD_CE_ATACMD 0x00004000
#define SDI_CMD_CBOOTMODEEN 0x00008000
#define SDI_DTIMER_DEFAULT 0xFFFF0000
/* SDI Status register bits */
#define SDI_STA_CCRCFAIL 0x00000001
#define SDI_STA_DCRCFAIL 0x00000002
#define SDI_STA_CTIMEOUT 0x00000004
#define SDI_STA_DTIMEOUT 0x00000008
#define SDI_STA_TXUNDERR 0x00000010
#define SDI_STA_RXOVERR 0x00000020
#define SDI_STA_CMDREND 0x00000040
#define SDI_STA_CMDSENT 0x00000080
#define SDI_STA_DATAEND 0x00000100
#define SDI_STA_STBITERR 0x00000200
#define SDI_STA_DBCKEND 0x00000400
#define SDI_STA_CMDACT 0x00000800
#define SDI_STA_TXACT 0x00001000
#define SDI_STA_RXACT 0x00002000
#define SDI_STA_TXFIFOBW 0x00004000
#define SDI_STA_RXFIFOBR 0x00008000
#define SDI_STA_TXFIFOF 0x00010000
#define SDI_STA_RXFIFOF 0x00020000
#define SDI_STA_TXFIFOE 0x00040000
#define SDI_STA_RXFIFOE 0x00080000
#define SDI_STA_TXDAVL 0x00100000
#define SDI_STA_RXDAVL 0x00200000
#define SDI_STA_SDIOIT 0x00400000
#define SDI_STA_CEATAEND 0x00800000
#define SDI_STA_CARDBUSY 0x01000000
#define SDI_STA_BOOTMODE 0x02000000
#define SDI_STA_BOOTACKERR 0x04000000
#define SDI_STA_BOOTACKTIMEOUT 0x08000000
#define SDI_STA_RSTNEND 0x10000000
/* SDI Interrupt Clear register bits */
#define SDI_ICR_MASK 0x1DC007FF
#define SDI_ICR_CCRCFAILC 0x00000001
#define SDI_ICR_DCRCFAILC 0x00000002
#define SDI_ICR_CTIMEOUTC 0x00000004
#define SDI_ICR_DTIMEOUTC 0x00000008
#define SDI_ICR_TXUNDERRC 0x00000010
#define SDI_ICR_RXOVERRC 0x00000020
#define SDI_ICR_CMDRENDC 0x00000040
#define SDI_ICR_CMDSENTC 0x00000080
#define SDI_ICR_DATAENDC 0x00000100
#define SDI_ICR_STBITERRC 0x00000200
#define SDI_ICR_DBCKENDC 0x00000400
#define SDI_ICR_SDIOITC 0x00400000
#define SDI_ICR_CEATAENDC 0x00800000
#define SDI_ICR_BUSYENDC 0x01000000
#define SDI_ICR_BOOTACKERRC 0x04000000
#define SDI_ICR_BOOTACKTIMEOUTC 0x08000000
#define SDI_ICR_RSTNENDC 0x10000000
#define SDI_MASK0_MASK 0x1FFFFFFF
/* SDI Data control register bits */
#define SDI_DCTRL_DTEN 0x00000001
#define SDI_DCTRL_DTDIR_IN 0x00000002
#define SDI_DCTRL_DTMODE_STREAM 0x00000004
#define SDI_DCTRL_DMAEN 0x00000008
#define SDI_DCTRL_DBLKSIZE_MASK 0x000000F0
#define SDI_DCTRL_RWSTART 0x00000100
#define SDI_DCTRL_RWSTOP 0x00000200
#define SDI_DCTRL_RWMOD 0x00000200
#define SDI_DCTRL_SDIOEN 0x00000800
#define SDI_DCTRL_DMAREQCTL 0x00001000
#define SDI_DCTRL_DBOOTMODEEN 0x00002000
#define SDI_DCTRL_BUSYMODE 0x00004000
#define SDI_DCTRL_DDR_MODE 0x00008000
#define SDI_DCTRL_DBLOCKSIZE_V2_MASK 0x7fff0000
#define SDI_DCTRL_DBLOCKSIZE_V2_SHIFT 16
#define SDI_FIFO_BURST_SIZE 8
/******* PL180 Register offsets from BASE *******/
#define POWER 0x00
#define CLOCK 0x04
#define ARGUMENT 0x08
#define COMMAND 0x0c
#define RESPCOMMAND 0x10
#define RESPONSE0 0x14
#define RESPONSE1 0x18
#define RESPONSE2 0x1c
#define RESPONSE3 0x20
#define DATATIMER 0x24
#define DATALENGTH 0x28
#define DATACTRL 0x2c
#define DATACOUNT 0x30
#define STATUS 0x34
#define STATUS_CLEAR 0x38
#define MASK0 0x3c
#define MASK1 0x40
#define CARD_SELECT 0x44
#define FIFO_COUNT 0x48
#define FIFO 0x80
/**** NOT USED ************
#define periph_id0 0xFE0
#define periph_id1 0xFE4
#define periph_id2 0xFE8
#define periph_id3 0xFEC
#define pcell_id0 0xFF0
#define pcell_id1 0xFF4
#define pcell_id2 0xFF8
#define pcell_id3 0xFFC
**************************/
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
#include "defines.h"
#include "string.c"
char *tab = "0123456789ABCDEF";
int color;
#include "interrupts.c"
#include "vid.c"
#include "kbd.c"
void copy_vectors(void) {
extern u32 vectors_start;
extern u32 vectors_end;
u32 *vectors_src = &vectors_start;
u32 *vectors_dst = (u32 *)0;
while(vectors_src < &vectors_end)
*vectors_dst++ = *vectors_src++;
}
int kprintf(char *fmt, ...);
void IRQ_handler()
{
int vicstatus, sicstatus;
int ustatus, kstatus;
// read VIC SIV status registers to find out which interrupt
vicstatus = VIC_STATUS;
sicstatus = SIC_STATUS;
if (vicstatus & (1<<31)){
if (sicstatus & (1<<3)){
kbd_handler();
}
}
}
int row, col;
int main()
{
int i;
char line[128], string[32];
color = YELLOW;
row = col = 0;
fbuf_init();
kbd_init();
/* enable timer0,1, uart0,1 SIC interrupts */
VIC_INTENABLE |= 1<<31; // SIC to VIC's IRQ31
/* enable KBD IRQ */
SIC_ENSET = 1<<3; // KBD int=3 on SIC
SIC_PICENSET = 1<<3; // KBD int=3 on SIC
kprintf("Test interrupt-driven KBD driver\n");
unlock();
while(1){
color = CYAN;
printf("Enter a line from KBD\n");
kgets(line);
printf("line = %s\n", line);
}
}
<file_sep>void write_file()
{
int fd = atoi(pathname);
if(running->fd[fd]->refCount == 0)
{
printf("File descriptor not open\n");
return;
}
if(running->fd[fd]->mode == R)
{
printf("File is open for read\n");
return;
}
mywrite(fd, parameter, strlen(parameter));
}
int mywrite(int fd, char buf[], int nbytes)
{
int original_nbytes = nbytes;
OFT * oftp = (running->fd[fd]);
MINODE * mip = oftp->mptr;
char * cq = buf;
while(nbytes > 0)
{
int lbk = oftp->offset / BLKSIZE, startByte = oftp->offset % BLKSIZE, blk;
if(lbk < 12)
{
if(mip->INODE.i_block[lbk] == 0)
mip->INODE.i_block[lbk] = balloc(mip->dev);
blk = mip->INODE.i_block[lbk];
}
else if(lbk >= 12 && lbk < 256 + 12)
{
if(mip->INODE.i_block[12] == 0)
{
mip->INODE.i_block[12] = balloc(mip->dev);
zero_block(mip->dev, mip->INODE.i_block[12]);
}
uint32_t ibuf[256];
get_block(mip->dev, mip->INODE.i_block[12], (char*)ibuf);
blk = ibuf[lbk - 12];
if(blk == 0)
{
if((blk = ibuf[lbk - 12] = balloc(mip->dev)) == 0)
{
printf("[!] ERROR: Insufficient Disk Space.\n");
return original_nbytes - nbytes;
}
put_block(mip->dev, mip->INODE.i_block[12], (char*)ibuf);
}
}
else
{
int indirect1 = (lbk - 256 - 12) / 256;
int indirect2 = (lbk - 256 - 12) % 256;
uint32_t ibuf[256];
if(mip->INODE.i_block[13] == 0)
{
mip->INODE.i_block[13] = balloc(mip->dev);
zero_block(mip->INODE.i_block[13], mip->INODE.i_block[13]);
}
get_block(mip->dev, mip->INODE.i_block[13], (char*)ibuf);
if(ibuf[indirect1] == 0)
{
ibuf[indirect1] = balloc(mip->dev);
zero_block(mip->dev, ibuf[indirect1]);
put_block(mip->dev, mip->INODE.i_block[13], (char*)ibuf);
}
uint32_t ibuf2[256];
get_block(mip->dev, ibuf[indirect1], (char*)ibuf2);
if(ibuf2[indirect2] == 0)
{
ibuf2[indirect2] = balloc(mip->dev);
zero_block(mip->dev, ibuf2[indirect2]);
put_block(mip->dev, ibuf[indirect1], (char*)ibuf2);
}
blk = ibuf2[indirect2];
}
char wbuf[BLKSIZE];
zero_block(mip->dev, blk);
get_block(mip->dev, blk, wbuf);
char * cp = wbuf + startByte;
int remain = BLKSIZE - startByte;
if(nbytes < remain)
remain = nbytes;
memcpy(cp, cq, remain);
cq += remain;
oftp->offset += remain;
nbytes -= remain;
mip->INODE.i_size += remain;
put_block(mip->dev, blk, wbuf);
}
mip->dirty = 1;
printf("wrote %d char into the file descriptor fd=%d\n", original_nbytes, fd);
return original_nbytes;
}
/// (4). myread() tries to read nbytes from fd to buf[ ], and returns the actual number of bytes read.
int myread(int fd, char *buf, int nbytes)
{
MINODE *mip = running->fd[fd]->mptr;
OFT *op = running->fd[fd];
int count = 0, avil = mip->INODE.i_size - op->offset;
char *cq = buf;
uint32_t dbuf[256];
int blk;
while(nbytes > 0 && avil > 0)
{
int lbk = op->offset / BLKSIZE, startByte = op->offset % BLKSIZE;
if (lbk < 12)
{
blk = mip->INODE.i_block[lbk];
}
else if(lbk >= 12 && lbk < 268)
{ /// Recieve blocks from indirect
get_block(mip->dev,mip->INODE.i_block[12], (char*)dbuf);
blk = dbuf[lbk - 12];
}
else
{ /// Get to indirect blocks from double indirect
get_block(mip->dev,mip->INODE.i_block[13], (char*)dbuf);
get_block(mip->dev, dbuf[(lbk - 268) / 256], (char*)dbuf); // Get to indirect block
blk = dbuf[(lbk-268) % 256];
}
char readbuf[BLKSIZE];
get_block(mip->dev,blk, readbuf);
cq = readbuf + startByte;
int remainingBytes = BLKSIZE - startByte;
if(nbytes < remainingBytes)
{
remainingBytes = nbytes;
}
memcpy((buf + count), cq, remainingBytes);
op->offset += remainingBytes;
count += remainingBytes;
avil -= remainingBytes;
nbytes -= remainingBytes;
if (nbytes <= 0 || avil <= 0)
break;
}
printf("FD: %d\tREAD-COUNT: %d\n", fd, count);
return count;
}
void read_file()
{
int fd = atoi(pathname), nbytes = atoi(parameter);
char buf[nbytes + 1];
if(running->fd[fd] == 0 || (running->fd[fd]->mode != R && running->fd[fd]->mode != RW))
{
printf("ERROR: FD %d is not open for read.\n", fd);
return;
}
int ret = myread(fd, buf, nbytes);
buf[ret] = 0;
printf("%s\n", buf);
}
void mycat()
{
int fd = myopen(pathname, R);
if(fd == -1)
{
return;
}
char *buf = malloc(sizeof(char) * (running->fd[fd]->mptr->INODE.i_size + 1));
myread(fd,buf,running->fd[fd]->mptr->INODE.i_size);
buf[running->fd[fd]->mptr->INODE.i_size] = 0;
printf("%s\n", buf);
free(buf);
close_file(fd);
}
void cp()
{
printf("SRC: %s\n", pathname);
printf("DST: %s\n", parameter);
/// 1. fd = open src for READ;
int fd = myopen(pathname, R); // Opens src via pathname
char temp[strlen(parameter) + 1];
strcpy(temp, parameter);
/// 2. gd = open dst for WR|CREAT;
int gd = myopen(parameter, W); // Opens dst via parameter
/// 3. write
printf("[READING SRC]\n");
char * buffer = malloc(sizeof(char) * running->fd[fd]->mptr->INODE.i_size + 1);
myread(fd, buffer, running->fd[fd]->mptr->INODE.i_size); // Read -> Source
buffer[running->fd[fd]->mptr->INODE.i_size] = 0;
printf("[WRITING DST]\n");
mywrite(gd, buffer, running->fd[fd]->mptr->INODE.i_size); // Write -> Parameter
/*while( n=read(fd, buf[ ], BLKSIZE) ){
mywrite(gd, buf, n); // notice the n in write()
}*/
free(buffer);
close_file(fd);
close_file(gd);
}
void mymov()
{
char * path1temp = strdup(pathname);
link();
strcpy(pathname, path1temp);
unlink();
free(path1temp);
}<file_sep>#include "ucode.c"
int main()
{
ubody("one");
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
#include "type.h"
#include "string.c"
#define VA(x) (0x80000000 + (u32)x)
char *tab = "0123456789ABCDEF";
int BASE;
int color;
#include "uart.c"
#include "kbd.c"
//#include "wait.c"
#include "timer.c"
#include "vid.c"
#include "exceptions.c"
#include "queue.c"
#include "kernel.c"
#include "fork.c"
#include "svc.c"
#include "exec.c"
#include "open_close_lseek.c"
#include "sdc.c"
#include "yourload.c"
void copy_vectors(void) {
extern u32 vectors_start;
extern u32 vectors_end;
u32 *vectors_src = &vectors_start;
u32 *vectors_dst = (u32 *)0;
while(vectors_src < &vectors_end)
*vectors_dst++ = *vectors_src++;
}
int mkPtable()
{
int i;
u32 *ut = (u32 *)0x4000; // at 16KB
u32 entry = 0 | 0x412; // 0x412; AP=01 (K R|W; U NO) domain=0 CB=00
for (i=0; i<4096; i++)
ut[i] = 0;
for (i=0; i<258; i++){
ut[i] = entry;
entry += 0x100000;
}
}
int kprintf(char *fmt, ...);
void timer0_handler();
void IRQ_handler()
{
int vicstatus, sicstatus;
int ustatus, kstatus;
// read VIC status register to find out which interrupt
vicstatus = VIC_STATUS;
sicstatus = SIC_STATUS;
if (vicstatus & 0x0010){
timer0_handler();
}
if (vicstatus & 0x1000){
uart_handler(&uart[0]);
}
if (vicstatus & 0x2000){
uart_handler(&uart[1]);
}
if (vicstatus & (1<<31)){
if (sicstatus & (1<<3)){
kbd_handler();
}
// SDC interrupt at 22 on SIC
if (sicstatus & (1<<22)){
sdc_handler();
}
}
}
int main()
{
int i,a;
char line[128];
UART *up;
color = RED;
row = col = 0;
BASE = 10;
fbuf_init();
kprintf(" Welcome to WANIX in Arm\n");
kprintf("LCD display initialized : fbuf = %x\n", fb);
color = CYAN;
kbd_init();
/* enable UART IRQ */
VIC_INTENABLE |= (1<<4); // timer0,1 at 4
VIC_INTENABLE |= (1<<12); // UART0 at 12
VIC_INTENABLE |= (1<<13); // UART1 at 13
VIC_INTENABLE |= (1<<31); // SIC to VIC's IRQ31
/* enable UART0 RXIM interrupt */
UART0_IMSC = 1<<4;
/* enable UART1 RXIM interrupt */
UART1_IMSC = 1<<4;
/* enable KBD and SDC IRQ */
SIC_ENSET |= (1<<3); // KBD int=3 on SIC
SIC_ENSET |= (1<<22); // SDC int=22 on SIC
unlock();
timer_init();
timer_start(0);
uart_init();
up = &uart[0];
ufprintf(up, "test UART\n");
sdc_init();
kernel_init();
kfork("u1");
//kfork("u2");
//kfork("u3");
//kfork("u4");
unlock();
color = WHITE;
kprintf("P0 switch to P1\n");
while(1){
unlock();
if (readyQueue)
tswitch();
}
}
<file_sep>int kprintf(char *, ...);
int strlen(char *s)
{
int i = 0;
while(*s){
i++; s++;
}
return i;
}
int strcmp(char *s1, char *s2)
{
while((*s1 && *s2) && (*s1==*s2)){
s1++; s2++;
}
if ((*s1==0) && (*s2==0))
return 0;
return(*s1 - *s2);
}
int strcpy(char *dest, char *src)
{
while(*src){
*dest++ = *src++;
}
*dest = 0;
}
int kstrcpy(char *dest, char *src)
{
while(*src){
*dest++ = *src++;
}
*dest = 0;
}
int atoi(char *s)
{
int v = 0;
while (*s){
v = 10*v + (*s - '0');
s++;
}
//kprintf("v=%d\n", v);
return v;
}
int geti()
{
char s[16];
ugetline(s);
return atoi(s);
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// queue.c file
extern PROC *freeList;
PROC *getproc()
{
PROC *p = freeList;
if (p){
freeList = p->next;
}
return p;
}
int putproc(PROC *p)
{
p->next = freeList;
freeList = p;
}
int enqueue(PROC **queue, PROC *p)
{
PROC *q = *queue;
if (q==0 || p->priority > q->priority){
*queue = p;
p->next = q;
return;
}
while (q->next && p->priority <= q->next->priority){
q = q->next;
}
p->next = q->next;
q->next = p;
}
PROC *dequeue(PROC **queue)
{
PROC *p = *queue;
if (p)
*queue = p->next;
return p;
}
int printQ(PROC *p)
{
kprintf("readyQueue = ");
while(p){
kprintf("[%d%d]->", p->pid,p->priority);
p = p->next;
}
kprintf("NULL\n");
}
int printSleepList(PROC *p)
{
printf("sleepList = ");
while(p){
kprintf("[%d%d]->", p->pid,p->event);
p = p->next;
}
kprintf("NULL\n");
}
int printList(PROC *p)
{
kprintf("freeList = ");
while(p){
kprintf("[%d]->", p->pid);
p = p->next;
}
kprintf("NULL\n");
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
/********************
#define SSIZE 1024
#define NPROC 9
#define FREE 0
#define READY 1
#define SLEEP 2
#define BLOCK 3
#define ZOMBIE 4
#define printf kprintf
typedef struct proc{
struct proc *next;
int *ksp; // at 4
int *usp; // at 8
int *upc; // at 12
int *cpsr; // at 16
int *pgdir; // ptable address
int status;
int priority;
int pid;
int ppid;
struct proc *parent;
int event;
int exitCode;
char name[32]; // name string
int kstack[SSIZE];
}PROC;
***************************/
extern PROC *kfork();
PROC proc[NPROC], *freeList, *readyQueue, *sleepList, *running;
int procsize = sizeof(PROC);
char *pname[NPROC]={"sun", "mercury", "venus", "earth", "mars", "jupiter",
"saturn","uranus","neptune"};
u32 *MTABLE = (u32 *)0x4000; // P0's ptable at 16KB
int kernel_init()
{
int i, j;
PROC *p; char *cp;
int *MTABLE, *mtable;
int paddr;
kprintf("kernel_init()\n");
for (i=0; i<NPROC; i++){
p = &proc[i];
p->pid = i;
p->status = FREE;
p->priority = 0;
p->ppid = 0;
strcpy(p->name, pname[i]);
p->next = p + 1;
}
proc[NPROC-1].next = 0;
freeList = &proc[0];
readyQueue = 0;
sleepList = 0;
running = getproc();
running->status = READY;
printList(freeList);
}
int scheduler()
{
char line[8];
int pid; PROC *old=running;
char *cp;
kprintf("proc %d in scheduler\n", running->pid);
if (running->status==READY)
enqueue(&readyQueue, running);
printQ(readyQueue);
running = dequeue(&readyQueue);
kprintf("next running = %d\n", running->pid);
pid = running->pid;
if (pid==1) color=WHITE;
if (pid==2) color=GREEN;
if (pid==3) color=CYAN;
if (pid==4) color=YELLOW;
if (pid==5) color=BLUE;
if (pid==6) color=PURPLE;
if (pid==7) color=RED;
// must switch to new running's pgdir; possibly need also flush TLB
if (running != old){
printf("switch to proc %d pgdir at %x ", running->pid, running->pgdir);
printf("pgdir[2048] = %x\n", running->pgdir[2048]);
switchPgdir((u32)running->pgdir);
}
}
/*---------------------*/
int ksleep(int event)
{
int sr = int_off();
printf("proc %d going to sleep on event=%d\n", running->pid, event);
running->event = event;
running->status = SLEEP;
enqueue(&sleepList, running);
printSleepList(sleepList);
tswitch();
int_on(sr);
}
int kwakeup(int event)
{
PROC *temp, *p;
temp = 0;
int sr = int_off();
printSleepList(sleepList);
while (p = dequeue(&sleepList))
{
if (p->event == event)
{
printf("wakeup %d\n", p->pid);
p->status = READY;
enqueue(&readyQueue, p);
}
else
{
enqueue(&temp, p);
}
}
sleepList = temp;
printSleepList(sleepList);
int_on(sr);
}
int kexit(int exitValue)
{
int i;
PROC *p;
for (i = 2; i < NPROC; i++)
{ // Skip root proc[0] and proc[1]
p = &proc[i];
/// Child sent to parent (orphanage)
if (p->status != FREE && p->ppid == running->pid)
{
if (p->status == ZOMBIE)
{
p->status = FREE;
enqueue(&freeList, p); //Release all ZOMBIE childs
}
else
{
printf("Send child &d to proc[1] (parent)\n", p->pid);
p->ppid = 1;
p->parent = &proc[1];
}
}
}
running->exitCode = exitValue; // Record exitValue in proc for parent
running->status = ZOMBIE; // Will not free PROC
//enqueue(&zombieList, p);
kwakeup(&proc[1]);
kwakeup(running->parent);
tswitch(); //Switch process to give up CPU
}
int kwait(int *status)
{ /// proc waits for (and disposes of) a ZOMBIE child.
int i, hasChild = 0;
PROC *p;
while (1)
{
for (i = 1; i < NPROC; i++)
{
p = &proc[i];
/// Search for (any) zombie child
if (p->status != FREE && p->ppid == running->pid)
{
hasChild = 1;
if (p->status == ZOMBIE)
{
//dequeue(&zombieList);
*status = p->exitCode; // Get exit code
p->status = FREE; // Set status to Free
enqueue(&freeList, p); // release child PROC to freelist
return (p->pid); // Return pid
}
}
}
if (!hasChild)
{
printf("[!] - NO CHILD FOUND / P1 NO DIE\n");
return -1;
}
ksleep(running);
}
}
<file_sep>/// init.c
#include "ucode.c"
int console, s0, s1;
int parent() // P1's code
{
int pid, status;
while (1)
{
prints("-- CNGINIT : wait for ZOMBIE child\n");
pid = wait(&status);
if (pid == console)
{ // if console login process died
printf("-- INIT: forks a new console login\n");
console = fork(); // fork another one
if (console)
continue;
else
exec("login /dev/tty0"); // new console login process
}
else if (pid == s0)
{
printf("CTINIT: forks a new login on serial port 0\n");
s0 = fork();
if (s0)
continue;
else
exec("login /dev/ttyS0");
}
else if (pid == s1)
{
printf("CTINIT: forks a new login on serial port 1\n");
s1 = fork();
if (s1)
continue;
else
exec("login /dev/ttyS1");
}
printf("-- CNGINIT: I just buried an orphan child proc %d\n", pid);
}
}
main()
{
int in = open("/dev/tty0", O_RDONLY); // file descriptor 0
int out = open("/dev/tty0", O_WRONLY); // for display to console
printf("-- CNGINIT : fork a login proc on console\n");
console = fork();
/*
P1 - INIT
P2 - /dev/tty0
P3 - /dev/ttyS0
P4 - /dev/ttyS1
*/
if (console) // parent
parent();
else // child: exec to login on tty0
exec("login /dev/tty0");
}<file_sep>//// sh.c
#include "ucode.c"
char tokens[16][32];
int numtokens, i;
int contain(char *buf, char ch)
{ /// Scans Left -> Right to find
int len = 0;
len = strlen(buf);
while (len > 0)
{
if (buf[len] == ch)
{
return len;
}
len--;
}
return len;
}
int scan(char *cmd_line, char *head, char *tail, char ch)
{
memset(head, 0, 128);
memset(tail, 0, 128);
char *cp = cmd_line;
int h_len = contain(cmd_line, ch), t_len, i;
//printf("[/] - h_len = %d\n", h_len);
/// if '|' found in cmd_line
if (h_len != 0)
{ /// Contains pipe
//prints("[1] - Contains \'|\' symbol.");
t_len = (strlen(cmd_line) - h_len) + 1;
//printf("[/] - strlen(cmd_line) = %d\n", strlen(cmd_line));
//printf("[/] - t_head = %d\n", h_len);
i = 0;
/// Splits Head + Tail
while (*cp)
{ /// Iterates through cmd_line
if (i < h_len)
{ /// Writes to Head
*head++ = *cp++;
//*tail++;
}
else if (i > h_len)
{ /// Writes to Tail
//*head++;
*tail++ = *cp++;
}
else
{ /// Skips over delimiter
*cp++;
}
i++; // Keeps track of cp iteration
}
return 1;
}
else
{ /// Does not contain pipe
//prints("[0] - Does not contain \'|\' symbol.");
strcpy(head, cmd_line);
return 0;
}
}
int exec_command(char *cmd_line)
{
char head[128], tail[128], *cmd = cmd_line;
int fd, len;
/// scan cmd_line for I/O (< > >>)
/// do I/O direction
if (scan(cmd_line, head, tail, '>'))
{ /// Contains > or >>, Handles stdout
len = contain(head, '>');
//printf("[/] - HEAD = %s, TAIL = %s, LEN = %d\n", head, tail, len);
if (head[len] == '>')
{ // Contains '>>' for APPEND
//prints("[0] = Found >> in command.\n");
//printf("[!] - Deleteing %c char from head.\n", head[len]);
head[len] = 0;
close(1); // Close fd 1
open(tail, O_WRONLY | O_APPEND);
printf("HEAD = %s\n", head);
exec(head);
}
// Contains '>' for CREAT
prints("[0] = Found > in command.\n");
close(1);
open(tail, O_WRONLY | O_CREAT);
exec(head);
}
if (len = scan(cmd, head, tail, '<'))
{ // Contains <, Handles stdin
prints("[0] = Found < in command.\n");
close(0);
open(tail, O_RDONLY);
exec(head);
}
exec(head);
}
int do_pipe(char *cmd_line, int *pd)
{
int has_pipe = 0;
char head[128], tail[128];
int lpd[2], pid;
if (pd)
{ // if Pipe passed in as WRITER
close(pd[0]); // closes pipe (READ)
dup2(pd[1], 1); // redirect stdin to pipe READ end
close(pd[1]); // closes pipe (WRITE)
}
//has_pipe = scan(cmd_line, head, tail, '|');
//printf("TAIL: %s\n", tail);
//printf("HEAD: %s\n", head);
//exec(cmd_line);
if (scan(cmd_line, head, tail, '|'))
{
if (pipe(lpd) < 0)
{
printf("[!] - Pipe could not be opened.\n");
exit(1);
}
pid = fork(); // fork a child to run pipe command
if (pid)
{ /// Parent (as READER)
close(lpd[1]); // closes pipe (WRITE)
dup2(lpd[0], 0); // redirect stdin to pipe READ end
close(lpd[0]); // closes pipe (READ)
exec_command(tail); // recursion call on the tail
}
else
{ /// Child (recursion w/ leftover)
do_pipe(head, lpd); // redirect stdout to pipe WRITE end
}
}
else
{ /// Leftover of command line
exec_command(head);
}
}
int main(int argc, char *argv[])
{
char cmd[128], buf1[128], buf2[128];
int status = 0;
/// (in sh) it loops forever (until "logout")
while (1)
{
memset(cmd, 0, 128); // Resets cmd buf each loop
/// 1.) gets command lines from the user
while (strcmp(cmd, "\0") == 0 || strcmp(cmd, "") == 0)
{ // if input is empty
printf("Input a Command: ");
gets(cmd);
}
/// 2.) executes the commands.
/// Non-trivial commands (exit, cd)
if (strcmp(cmd, "logout") == 0)
{ /// sycall to die;
//prints("[!] - Exiting Shell...");
exit(1);
}
if (cmd[0] == 'c' && cmd[1] == 'd')
{ /// Changes directory
scan(cmd, buf1, buf2, ' ');
printf("[0] - Changed to \'%s\' directory....\n", buf2);
chdir(buf2);
continue;
}
pid = fork(); // Fork a child sh process
//printf("PID = %d\n", pid);
if (pid == 0)
{ /// child sh - handles PIPE
prints("[~] - Entered child sh...\n");
do_pipe(cmd, 0);
}
else
{ /// parent sh
prints("[~] - Entered parent sh...\n");
pid = wait(&status);
}
//printc('\n');
}
}<file_sep>/********* t.c file *********************/
void prints(char *s)
{
int c;
for (c = 0; s[c] != '\0'; c++)
{
putc(s[c]);
}
}
void gets(char *s)
{
while ((*s = getc()) != '\r')
{
putc(*s);
s++;
}
*s = '\0';
}
char ans[64];
main()
{
while (1)
{
prints("What's your name? ");
gets(ans);
prints("\n\r");
if (ans[0] == 0)
{
prints("return to assembly and hang\n\r");
return;
}
prints("Welcome ");
prints(ans);
prints("\n\r");
}
}
<file_sep>int open_file()
{
int mode;
printf("[ ENTERED KOPEN() FUNCTION ]\n");
printf("0 = R\n1 = W\n2 = RW\n3 = APPEND\nInput a Value:\n>> ");
char pathname[128];
/// 1. ask for a pathname and mode to open:
mode = geti();
switch(mode) {
case 1:
printf("[ MODE: R ]\n");
break;
case 2:
printf("[ MODE: W ]\n");
break;
case 3:
printf("[ MODE: RW ]\n");
break;
case 4:
printf("[ MODE: APPEND ]\n");
break;
}
/// 2. get pathname's inumber:
/// 3. get its Minode pointer
/// 4. check mip->INODE.i_mode to verify it's a REGULAR file and permission OK.
/// 5. allocate a FREE OpenFileTable (OFT) and fill in values:
/// 6. Depending on the open mode 0|1|2|3, set the OFT's offset accordingly:
/// 7. find the SMALLEST i in running PROC's fd[ ] such that fd[i] is NULL
/// 8. update INODE's time field
/// 9. return i as the file descriptor
return 0;
}
void tokenize() {
}
/*int truncate(MINODE *mip)
{
return 0;
}*/
int close_file(int fd)
{
return 0;
}<file_sep>#include <time.h>
#include <stdint.h>
enum FILEMODE
{
R,
W,
RW,
APPEND
};
int open_file()
{
/// 1. ask for a pathname and mode to open:
int mode;
/*printf("0 = r\n1 = w\n2 = rw\n3 = append\nInput a mode:\n>> ");
scanf("%d", &mode);*/
if (strcmp(parameter, "r") == 0)
mode = R;
else if (strcmp(parameter, "w") == 0)
mode = W;
else if (strcmp(parameter, "rw") == 0)
mode = RW;
else if (strcmp(parameter, "append") == 0)
mode = APPEND;
int fd = myopen(pathname, mode);
if (fd >= 0 && fd < 10)
printf("Succesfully Opened FD @%d\n", fd);
}
int myopen(char *name, int mode)
{
/// 2. get pathname's inumber:
if (pathname[0] == '/')
dev = root->dev; // root INODE's dev
else
dev = running->cwd->dev;
int ino = getino(name);
if (mode < 0 || mode > 3)
{
printf("[!] - ERROR: Out of bounds mode\n");
return -1;
}
else if (!ino)
{
printf("[!] - ERROR: File does not exist\n");
return -1;
}
/// 3. get its Minode pointer
MINODE *mip = iget(dev, ino);
/// 4. check mip->INODE.i_mode to verify it's a REGULAR file and permission OK.
if (!S_ISREG(mip->INODE.i_mode))
{
printf("[!] ERROR: File is not REG\n");
return -1;
}
for (int i = 0; i < 20; i++)
{
if (oft[i].mptr == mip && oft[i].mode != R)
{
printf("[!] ERROR: Current file already in OPEN mode.\n");
return -1;
}
}
for (int i = 0; i < 20; i++)
{
/// 6. Depending on the open mode 0|1|2|3, set the OFT's offset accordingly:
if (oft[i].refCount == 0)
{
oft[i] = (OFT){.mode = mode, .refCount = 1, .mptr = mip, .offset = (mode == APPEND ? mip->INODE.i_size : 0)};
if (mode == W)
{
mytruncate(mip);
mip->INODE.i_size = 0;
}
for (int j = 0; j < NFD; j++)
{
if (!running->fd[j])
{
running->fd[j] = (oft + i);
break;
}
}
/// 8. update INODE's time field
time_t current_time = time(0L);
mip->INODE.i_atime = current_time;
if (mode != R)
mip->INODE.i_mtime = current_time;
mip->dirty = 1;
/// 9. return i as the file descriptor
return i;
}
}
return -1;
};
void close_file(int fd)
{
OFT *op = running->fd[fd];
op->refCount--;
if (op->refCount == 0)
iput(op->mptr);
oft[fd].mptr = NULL;
running->fd[fd] = NULL;
}
void myclose()
{
close_file(atoi(pathname));
}
void lseek_file()
{
int fd, position;
printf("Enter fd and position: ");
scanf("%d %d", &fd, &position);
}
void mylseek(int fd, int position)
{
int original = running->fd[fd]->offset;
running->fd[fd]->offset = (position <= running->fd[fd]->mptr->INODE.i_size && position >= 0) ? position : original;
}
int pfd()
{ ///This function displays the currently opened files
printf("fd\tmode\toffset\tINODE\n");
printf("---\t----\t------\t-----\n");
for (int i = 0; i < NOFT; i++)
if (oft[i].refCount)
{
char *mode;
switch (oft[i].mode)
{
case R:
mode = "R";
break;
case W:
mode = "W";
break;
case RW:
mode = "RW";
break;
case APPEND:
mode = "A";
}
printf("%d\t%s\t%d\t%d\n", i, mode, oft[i].offset, oft[i].mptr->ino);
}
}
/// Other Simple FILE DESCRIPTOR operations:
int dup(int fd)
{
if (oft[fd].refCount == 0)
return -1;
for (int i = 0; i < NOFT; i++)
{
if (oft[i].refCount == 0)
{
oft[i] = oft[fd];
oft[i].refCount = 1;
return i;
}
}
return -1;
}
int dup2(int fd, int gd)
{
if (oft[fd].refCount == 0)
return -1;
if (oft[gd].refCount)
close_file(gd);
oft[gd] = oft[fd];
oft[gd].refCount = 1;
}
<file_sep>Run these commands:
1.) ./mk
2.) ./q
How to use program:
1.) Boot up searching for "mtx".
a.) After the search is complete, hit Enter.
2.) Login with:
User: root
Password: <PASSWORD>
<file_sep>//// ls.c
#include "ucode.c"
char *t1 = "xwrxwrxwr-------";
char *t2 = "----------------";
int ls_file(char *fname)
{
struct stat fstat, *sp = &fstat;
int r, i;
char sbuf[4096];
r = stat(fname, sp);
if (sp->st_mode == 16877)
{ /// 16877 = ISREG, is a Directory
printc('d');
}
else
{ /// 33060 = ISDIR, is a File
printc('-');
}
// bit permissions
for (i = 8; i >= 0; i--)
{
/// Prints x, r, w
if (sp->st_mode & (1 << i))
printc(t1[i]); // Permission Allowed
else
printc(t2[i]); // Permission Denied
}
printf(" %d ", sp->st_nlink); // link count
printf(" %d", sp->st_uid); // uid
printf(" %d", sp->st_gid); // gid
printf(" %d", sp->st_size); // filesize
printf(" %s\n\r", fname); // filename
}
void ls_dir(char *path)
{
prints("---- CNG: Cong's LS Function ----\n");
char read_buf[BLKSIZE], name[128];
int fd = open(path, O_RDONLY);
chdir(path);
//printf("[/] - Path = %d\n", path);
int n = read(fd, read_buf, BLKSIZE);
//printf("[/] - read_buf = %d\n", read_buf);
DIR *dp = (DIR *)read_buf; // directory pointer
char *cp = read_buf;
while (cp < read_buf + BLKSIZE)
{
strcpy(name, dp->name);
strcat(name, "\0");
ls_file(name);
cp += dp->rec_len;
dp = (DIR *)cp;
}
close(fd);
}
main(int argc, char *argv[])
{
struct stat fstat, *sp = &fstat;
char path[128];
getcwd(path);
printf("argc = %d\n", argc);
if (argc == 1)
{ /// Print current directory
prints("[0] - ls for CWD.\n");
ls_dir(path);
}
else if (argc > 1)
{
int r = stat(argv[1], sp);
printf("[/] - st_mode = %d\n", sp->st_mode);
if (sp->st_mode == 33060) /// 33060 = ISREG
{ /// If arg is File
prints("[1] - File is Regular.\n");
ls_file(argv[1]); // ls file
}
else if (sp->st_mode == 16877) /// 16877 = ISDIR
{ /// If arg is Folder
prints("[0] - File is not Regular.\n");
ls_dir(argv[1]); // ls dir
}
else
{
prints("[!] - ERROR: No file type detected.\n");
}
}
}<file_sep>#include "font0"
char *tab = "0123456789ABCDEF";
u8 cursor;
int volatile *fb;
u8 *font;
int row, col;
int color;
int fbuf_init()
{
int x;
int i;
/**** for SVGA 800X600 these values are in ARM DUI02241 *********
*(volatile u32 *)(0x1000001c) = 0x2CAC; // 800x600
*(volatile u32 *)(0x10120000) = 0x1313A4C4;
*(volatile u32 *)(0x10120004) = 0x0505F6F7;
*(volatile u32 *)(0x10120008) = 0x071F1800;
*(volatile u32 *)(0x10120010) = (1*1024*1024);
*(volatile u32 *)(0x10120018) = 0x80B;
//***************************************************************/
//********* for VGA 640x480 ************************
*(volatile u32 *)(0x1000001c) = 0x2C77; // LCDCLK SYS_OSCCLK
*(volatile u32 *)(0x10120000) = 0x3F1F3F9C; // time0
*(volatile u32 *)(0x10120004) = 0x090B61DF; // time1
*(volatile u32 *)(0x10120008) = 0x067F1800; // time2
*(volatile u32 *)(0x10120010) = (1 * 1024 * 1024); // panelBaseAddress
*(volatile u32 *)(0x10120018) = 0x80B; //82B; // control register
*(volatile u32 *)(0x1012001c) = 0x0; // IntMaskRegister
/****** at 0x200-0x3FC are LCDpalletes of 128 words ***************
u32 *inten = (u32 *)(0x10120200);
for (i=0; i<128; i++){
inten[i]=0x8F008F00;
}
******** yet to figure out HOW TO use these palletes *************/
fb = (int *)(1 * 1024 * 1024); // at 1MB area; enough for 800x600 SVGA
font = fonts0; // use fonts0 for char bit patterns
// for (x = 0; x < (800 * 600); ++x) // for one BAND
/******** these will show 3 bands of BLUE, GREEN, RED *********
for (x = 0; x < (212*480); ++x)
fb[x] = 0x00FF0000; //00BBGGRR
for (x = 212*480+1; x < (424*480); ++x)
fb[x] = 0x0000FF00; //00BBGGRR
for (x = 424*480+1; x < (640*480); ++x)
fb[x] = 0x000000FF; //00BBGGRR
************* used only during intial testing ****************/
// for 800x600 SVGA mode display
/*********
for (x=0; x<640*480; x++)
fb[x] = 0x00000000; // clean screen; all pixels are BLACK
cursor = 127; // cursor bit map in font0 at 128
*********/
// for 640x480 VGA mode display
for (x = 0; x < 640 * 480; x++)
fb[x] = 0x00000000; // clean screen; all pixels are BLACK
cursor = 127; // cursor bit map in font0 at 128
}
int clrpix(int x, int y)
{
int pix = y * 640 + x;
fb[pix] = 0x00000000;
}
int setpix(int x, int y)
{
int pix = y * 640 + x;
if (color == RED)
fb[pix] = 0x000000FF;
if (color == BLUE)
fb[pix] = 0x00FF0000;
if (color == GREEN)
fb[pix] = 0x0000FF00;
if (color == GREEN)
fb[pix] = 0x0000FF00;
if (color == CYAN)
fb[pix] = 0x00FFFF00;
if (color == YELLOW)
fb[pix] = 0x0000FFFF;
if (color == PURPLE)
fb[pix] = 0x00FF00FF;
if (color == WHITE)
fb[pix] = 0x00FFFFFF;
}
int dchar(unsigned char c, int x, int y)
{
int r, bit;
u8 *caddress, byte;
caddress = font + c * 16;
// printf("c=%x %c caddr=%x\n", c, c, caddress);
for (r = 0; r < 16; r++)
{
byte = *(caddress + r);
for (bit = 0; bit < 8; bit++)
{
clrpix(x + bit, y + r); // clear pixel to BALCK
if (byte & (1 << bit))
setpix(x + bit, y + r);
}
}
}
int scroll()
{
int i;
for (i = 0; i < 640 * 480 - 640 * 16; i++)
{
fb[i] = fb[i + 640 * 16];
}
}
int kpchar(char c, int ro, int co)
{
int x, y;
x = co * 8;
y = ro * 16;
//printf("c=%x [%d%d] (%d%d)\n", c, ro,co,x,y);
dchar(c, x, y);
}
int erasechar()
{
// erase char at (row,col)
int r, bit, x, y;
x = col * 8;
y = row * 16;
//printf("ERASE: row=%d col=%d x=%d y=%d\n",row,col,x,y);
for (r = 0; r < 16; r++)
{
for (bit = 0; bit < 8; bit++)
{
clrpix(x + bit, y + r);
}
}
}
int clrcursor()
{
erasechar();
}
int putcursor()
{
kpchar(cursor, row, col);
}
int kputc(char c)
{
clrcursor();
if (c == '\r')
{
col = 0;
//printf("row=%d col=%d\n", row, col);
putcursor();
return;
}
if (c == '\n')
{
row++;
if (row >= 25)
{
row = 24;
scroll();
}
//printf("row=%d col=%d\n", row, col);
putcursor();
return;
}
if (c == '\b')
{
if (col > 0)
{
clrcursor();
col--;
putcursor();
}
return;
}
// c is ordinary char
kpchar(c, row, col);
col++;
if (col >= 80)
{
col = 0;
row++;
if (row >= 25)
{
row = 24;
scroll();
}
}
putcursor(cursor);
//printf("row=%d col=%d\n", row, col);
}
int kprints(char *s)
{
while (*s)
{
kputc(*s);
s++;
}
}
int krpx(int x)
{
char c;
if (x)
{
c = tab[x % 16];
krpx(x / 16);
}
kputc(c);
}
int kprintx(int x)
{
kputc('0');
kputc('x');
if (x == 0)
kputc('0');
else
krpx(x);
kputc(' ');
}
int krpu(int x)
{
char c;
if (x)
{
c = tab[x % 10];
krpu(x / 10);
}
kputc(c);
}
int kprintu(int x)
{
if (x == 0)
kputc('0');
else
krpu(x);
kputc(' ');
}
int kprinti(int x)
{
if (x < 0)
{
kputc('-');
x = -x;
}
kprintu(x);
}
int kprintf(char *fmt, ...)
{
int *ip;
char *cp;
cp = fmt;
ip = (int *)&fmt + 1;
while (*cp)
{
if (*cp != '%')
{
kputc(*cp);
if (*cp == '\n')
kputc('\r');
cp++;
continue;
}
cp++;
switch (*cp)
{
case 'c':
kputc((char)*ip);
break;
case 's':
kprints((char *)*ip);
break;
case 'd':
kprinti(*ip);
break;
case 'u':
kprintu(*ip);
break;
case 'x':
kprintx(*ip);
break;
}
cp++;
ip++;
}
}
int stestring(char *s)
{
char c;
while ((c = kgetc()) != '\r')
{
*s = c;
s++;
}
*s = 0;
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
/********* SDC Driver sdc.c **********
This SDC driver read/write 1KB blocks. It uses
semaphores to synchronize driver and interrupt handler
Consult Chapter 8 of text for reason WHY.
***************************************/
#define enterCR ps = int_off()
#define exitCR int_on(ps)
#include "sdc.h"
u32 base; //SDC base addres in I/O map
int do_command(int cmd, int arg, int resp)
{
*(u32 *)(base + ARGUMENT) = (u32)arg;
*(u32 *)(base + COMMAND) = 0x400 | (resp << 6) | cmd;
//delay();
}
// shared variables between SDC driver and interrupt handler
char *rxbuf, *txbuf;
int rxcount, txcount, rxdone, txdone;
int sdc_handler()
{
u32 status, status_err;
int i;
u32 *up;
int oldcolor;
// read status register to find out TXempty or RxAvail
status = *(u32 *)(base + STATUS);
oldcolor = color;
if (status & (1 << 17))
{ // RxFull: read 16 u32 at a time;
color = CYAN;
//printf("SDC RX interrupt: ");
up = (u32 *)rxbuf;
status_err = status & (SDI_STA_DCRCFAIL | SDI_STA_DTIMEOUT | SDI_STA_RXOVERR);
if (!status_err && rxcount)
{
//printf("R%d ", rxcount);
for (i = 0; i < 16; i++)
*(up + i) = *(u32 *)(base + FIFO);
up += 16;
rxcount -= 64;
rxbuf += 64;
status = *(u32 *)(base + STATUS); // read status to clear Rx interrupt
}
color = oldcolor;
if (rxcount == 0)
{
do_command(12, 0, MMC_RSP_R1); // stop transmission
rxdone = 1;
//printf("SDC handler done ");
// V(&rxsem);
}
}
else if (status & (1 << 18))
{ // TXempty: write 16 u32 at a time
color = YELLOW;
//printf("TX interrupt: ");
up = (u32 *)txbuf;
status_err = status & (SDI_STA_DCRCFAIL | SDI_STA_DTIMEOUT);
if (!status_err && txcount)
{
// printf("W%d ", txcount);
for (i = 0; i < 16; i++)
*(u32 *)(base + FIFO) = *(up + i);
up += 16;
txcount -= 64;
txbuf += 64; // advance txbuf for next write
status = *(u32 *)(base + STATUS); // read status to clear Tx interrupt
}
color = oldcolor;
if (txcount == 0)
{
do_command(12, 0, MMC_RSP_R1); // stop transmission
txdone = 1;
//V(&txsem);
}
}
//printf("write to clear register\n");
*(u32 *)(base + STATUS_CLEAR) = 0xFFFFFFFF;
// printf("SDC interrupt handler done\n");
}
int sdc_init()
{
u32 RCA = (u32)0x45670000; // QEMU's hard-coded RCA
base = (u32)0x10005000; // PL180 base address
printf("sdc_init : ");
*(u32 *)(base + POWER) = (u32)0xBF; // power on
*(u32 *)(base + CLOCK) = (u32)0xC6; // default CLK
// send init command sequence
do_command(0, 0, MMC_RSP_NONE); // idle state
do_command(55, 0, MMC_RSP_R1); // ready state
do_command(41, 1, MMC_RSP_R3); // argument must not be zero
do_command(2, 0, MMC_RSP_R2); // ask card CID
do_command(3, RCA, MMC_RSP_R1); // assign RCA
do_command(7, RCA, MMC_RSP_R1); // transfer state: must use RCA
do_command(16, 512, MMC_RSP_R1); // set data block length
// set interrupt MASK0 registers bits = RxFULL(17)|TxEmpty(18)
*(u32 *)(base + MASK0) = (1 << 17) | (1 << 18);
printf("done\n");
}
int getblock(int blk, char *buf)
{
u32 cmd, arg;
//printf("getblock %d ", blk);
rxbuf = buf;
rxcount = BLKSIZE;
rxdone = 0;
*(u32 *)(base + DATATIMER) = 0xFFFF0000;
// write data_len to datalength reg
*(u32 *)(base + DATALENGTH) = BLKSIZE;
cmd = 18; // CMD17 = READ single sector; 18=read block
arg = ((blk * 2) * 512); // absolute byte offset in disk
do_command(cmd, arg, MMC_RSP_R1);
//printf("dataControl=%x\n", 0x93);
// 0x93=|9|0011|=|9|DMA=0,0=BLOCK,1=Host<-Card,1=Enable
*(u32 *)(base + DATACTRL) = 0x93;
// P0 must use polling during mount_root
/*
if (running->pid)
P(&rxsem);
else
*/
while (rxdone == 0)
;
//printf("getblock return\n");
}
int putblock(int blk, char *buf)
{
u32 cmd, arg;
//printf("putblock %d %x\n", blk, buf);
txbuf = buf;
txcount = BLKSIZE;
txdone = 0;
*(u32 *)(base + DATATIMER) = 0xFFFF0000;
*(u32 *)(base + DATALENGTH) = BLKSIZE;
cmd = 25; // CMD24 = Write single sector; 25=read block
arg = (u32)((blk * 2) * 512); // absolute byte offset in diks
do_command(cmd, arg, MMC_RSP_R1);
//printf("dataControl=%x\n", 0x91);
// write 0x91=|9|0001|=|9|DMA=0,BLOCK=0,0=Host->Card, Enable
*(u32 *)(base + DATACTRL) = 0x91; // Host->card
// P0 must use polling but P0 never writes SDC
/*
if (running->pid)
P(&txsem);
else
*/
while (txdone == 0)
;
//printf("putblock return\n");
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
/***********************************************************************
io.c file of MTX
***********************************************************************/
char space = ' ';
char *ctable = "0123456789ABCDEF";
char cr = '\r';
int puts(const char *s){ }
#define printk printf
int printf(char *fmt,...);
typedef struct ext2_dir_entry_2 {
u32 inode; /* Inode number */
u16 rec_len; /* Directory entry length */
u8 name_len; /* Name length */
u8 file_type;
char name[255]; /* File name */
} DIR;
typedef struct stat {
u16 st_dev; /* major/minor device number */
u16 st_ino; /* i-node number */
u16 st_mode; /* file mode, protection bits, etc. */
u16 st_nlink; /* # links; TEMPORARY HACK: should be nlink_t*/
u16 st_uid; /* uid of the file's owner */
u16 st_gid; /* gid; TEMPORARY HACK: should be gid_t */
u16 st_rdev;
long st_size; /* file size */
long st_atime; /* time of last access */
long st_mtime; // time of last modification
long st_ctime; // time of creation
long st_dtime;
long st_date;
long st_time;
} STAT;
// UNIX <fcntl.h> constants: <asm/fcntl.h> in Linux
#define O_RDONLY 00
#define O_WRONLY 01
#define O_RDWR 02
#define O_CREAT 0100 /* not fcntl */
#define O_TRUNC 01000 /* not fcntl */
#define O_APPEND 02000
#define BLKSIZE 1024
#define EOF -1
#define exit mexit
/*
#define O_RDONLY 0
#define O_WRONLY 1
#define O_RDWR 2
*/
int mputc(char c)
{
write(1, &c, 1);
if (c=='\n')
write(1,&cr,1);
return 0;
}
void prints(char *s)
{
while (*s){
mputc(*s);
s++;
}
}
void mputs(char *s)
{
prints(s);
}
//void align(), printi(), prints();
/****************
int strcmp(char *s1, char *s2)
{
while(*s1 && *s2){
if (*s1 != *s2)
return *s1 - *s2;
s1++; s2++;
}
return 0;
}
***************/
/********
char getc()
{
return syscall(11,0,0,0);
}
void gets(char *s)
{ char c; int len=0;
while ( (c=getc()) != '\r' && len < 64){
*s++ = c; len++;
mputc(c);
}
prints("\n\r");
*s = 0;
}
********/
extern int strlen(const char *);
void print2f(char *s)
{
write(2, s, (int)strlen(s));
}
/*
void mptchar(char c)
{
mptc(c);
if (c=='\r')
mptc('\n');
}
*/
/***************
void align(u32 x)
{
int count;
count = 6;
if (x==0)
count = 5;
while (x){
count--;
x = (u32)(x/10);
}
while(count){
mputc(space);
count--;
}
}
***************/
void rpi(int x)
{
char c;
if (x==0) return;
c = ctable[x%10];
rpi((int)x/10);
mputc(c);
}
void printi(int x)
{
if (x==0){
prints("0 ");
return;
}
if (x < 0){
mputc('-');
x = -x;
}
rpi((int)x);
mputc(space);
}
void rpu(u32 x)
{
char c;
if (x==0) return;
c = ctable[x%10];
rpi((u32)x/10);
mputc(c);
}
void printu(u32 x)
{
if (x==0){
prints("0 ");
return;
}
rpu((u32)x);
mputc(space);
}
void rpx(u32 x)
{
char c;
if (x==0) return;
c = ctable[x%16];
rpx((u32)x/16);
mputc(c);
}
void printx(u32 x)
{
prints("0x");
if (x==0){
prints("0 ");
return;
}
rpx((u32)x);
mputc(space);
}
void printc(char c)
{
mputc(c);
c = c&0x7F;
if (c=='\n')
mputc(cr);
}
int printk(char *fmt,...)
{
char *cp, *cq;
int *ip;
cq = cp = (char *)fmt;
ip = (int *)&fmt + 1;
while (*cp){
if (*cp != '%'){
printc(*cp);
cp++;
continue;
}
cp++;
switch(*cp){
case 'd' : printi(*ip); break;
case 'u' : printu(*ip); break;
case 'x' : printx(*ip); break;
case 's' : prints((char *)*ip); break;
case 'c' : printc((char)*ip); break;
}
cp++; ip++;
}
}
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
// interrupts.c file
int kprintf(char *fmt, ...);
/*********
//void __attribute__((interrupt)) kc_handler() {
void kc_handler() {
int vicstatus, sicstatus;
int ustatus, kstatus;
// read VIC status register to find out which interrupt
vicstatus = VIC_STATUS;
sicstatus = SIC_STATUS;
//kprintf("vicstatus=%x sicstatus=%x\n", vicstatus, sicstatus);
if (vicstatus & 0x0010){
timer0_handler();
}
if (vicstatus & 0x1000){
uart0_handler();
}
if (vicstatus & 0x2000){
uart1_handler();
}
if (vicstatus & 0x80000000){
if (sicstatus & 0x08){
kbd_handler();
}
}
VIC_VADDR = 0xFF;
return;
}
***********/
/* all other handlers are infinite loops */
void __attribute__((interrupt)) undef_handler(void) { for(;;); }
void __attribute__((interrupt)) swi_handler(void) { for(;;); }
void __attribute__((interrupt)) prefetch_abort_handler(void) { for(;;); }
void __attribute__((interrupt)) data_abort_handler(void) { for(;;); }
void __attribute__((interrupt)) fiq_handler(void) { for(;;); }
<file_sep>/********************************************************************
Copyright 2010-2017 <NAME>, <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************/
/* crt0.c : main0(s) called from u.s, where s = oigianl command string
tokenlize s into char *argv[ ] and call main(argc, argv).
token() breaks up a string into argc of tokens, pointed by argv[]
*/
/* #include "uinclude.h" */
int argc;
char *argv[32];
void token(char *line)
{
char *cp;
cp = line;
argc = 0;
while (*cp != 0){
while (*cp == ' ') *cp++ = 0;
if (*cp != 0)
argv[argc++] = cp;
while (*cp != ' ' && *cp != 0) cp++;
if (*cp != 0)
*cp = 0;
else
break;
cp++;
}
argv[argc] = 0;
}
void showarg(int argc, char *argv[ ])
{
int i;
printf("argc=%d ", argc);
for (i=0; i<argc; i++)
//printf("argv[%d]=%s ", i, argv[i]);
printf("%s ", argv[i]);
prints("\n");
}
// BEFORE: r0 was trashed in goUmode(), so had to rely on r1->string
// NOW: r0 is NOT trashed in goUmode() ==> should be r0 alone
void main0(char *s)
{
if (s){
//printf("s=%s\n", s);
token(s);
}
//showarg(argc, argv);
main(argc, argv);
}
<file_sep>as86 -o bs.o bs.s
bcc -c -ansi t.c
ld86 -d bs.o t.o /usr/lib/bcc/libc.a
ls -l a.out
dd if=a.out of=mtximage bs=1024 count=1 conv=notrunc
rm *.o
echo done
<file_sep>#include "ucode.c"
int main()
{
ubody("two");
}
<file_sep>#include "ucode.c"
main()
{
ubody("three");
}
<file_sep>
#include "keymap2"
/********************************************************************************
//0 1 2 3 4 5 6 7 8 9 A B C D E F
char ltab[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 'q', '1', 0, 0, 0, 'z', 's', 'a', 'w', '2', 0,
0, 'c', 'x', 'd', 'e', '4', '3', 0, 0, ' ', 'v', 'f', 't', 'r', '5', 0,
0, 'n', 'b', 'h', 'g', 'y', '6', 0, 0, 0, 'm', 'j', 'u', '7', '8', 0,
0, ',', 'k', 'i', 'o', '0', '9', 0, 0, '.', '/', 'l', ';', 'p', '-', 0,
0, 0, '\'', 0, '[', '=', 0, 0, 0, 0, '\r', ']', 0, '\\', 0, 0,
0, 0, 0, 0, 0, 0, '\b', 0, 0, 0, 0, 0, 0, 0, 0, 0
};
char utab[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 'Q', '!', 0, 0, 0, 'Z', 'S', 'A', 'W', '@', 0,
0, 'C', 'X', 'D', 'E', '$', '#', 0, 0, ' ', 'V', 'F', 'T', 'R', '%', 0,
0, 'N', 'B', 'H', 'G', 'Y', '^', 0, 0, 0, 'M', 'J', 'U', '&', '*', 0,
0, '<', 'K', 'I', 'O', ')', '(', 0, 0, '>', '?', 'L', ':', 'P', '_', 0,
0, 0, '"', 0, '{', '+', 0, 0, 0, 0, '\r','}', 0, '|', 0, 0,
0, 0, 0, 0, 0, 0, '\b', 0, 0, 0, 0, 0, 0, 0, 0, 0
};
**********************************************************************************/
// KBD registers from base address
#define KCNTL 0x00
#define KSTAT 0x04
#define KDATA 0x08
#define KCLK 0x0C
#define KISTA 0x10
typedef struct kbd {
char *base;
char buf[128];
int head, tail, data, room;
}KBD;
KBD kbd;
int kputc(char);
int shifted = 0;
int release = 0;
int control = 0;
int kbd_init()
{
KBD *kp = &kbd;
kp->base = (char *)0x10006000;
//*(kp->base + KCNTL) = 0x11; // bit4=Enable bit0=INT on
*(kp->base + KCNTL) = 0x14; // 00010100=INTenable, Enable
*(kp->base + KCLK) = 8; // KBD internal clock setting
kp->head = kp->tail = 0; //Index to buffer
kp->data = 0; kp->room = 128; // Counter
release = 0; // key release flag
shifted = 0; // shift key down flag
control = 0; // control key down flag
}
// kbd_handler() for scan code set 2
/*******************************************
key press => scanCode
key release => 0xF0 scanCode
Example:
press 'a' => 0x1C
release 'a' => 0xF0 0x1C
******************************************/
void kbd_handler()
{
u8 scode, c;
KBD *kp = &kbd;
color = YELLOW; // int color in vid.c file
scode = *(kp->base + KDATA); // get scan code from KDATA reg => clear IRQ
//printf("scanCode = %x\n", scode);
if (scode == 0xF0){ // key release
release = 1; // set flag
return;
}
if (scode == 0x12) { //L Shift is being pressed
shifted = 1;
}
if (scode == 0x14) { //L Ctrl is being pressed
control = 1;
}
if (scode == 0x12 && release == 1) { //L Shift is released
shifted = 0;
}
if (scode == 0x14 && release == 1) { //L Ctrl is released
control = 0;
}
if (release && scode){ // next scan code following key release
release = 0; // clear flag
return;
}
if (shifted && scode)
c = utab[scode]; //Lowercase
else // ONLY IF YOU can catch LEFT or RIGHT shift key
c = ltab[scode]; //Uppercase
if (control && scode) {
if (scode == 0x21)
printf("PROGRAM IS TERMINATED\n");
if (scode == 0x23) {
c = 0x04;
printf("FILE STREAMING IS TERMINATED\n");
}
}
printf("c=%x %c\n", c, c);
kp->buf[kp->head++] = c; // Enter key into CIRCULAR buf[]
kp->head %= 128;
kp->data++;
kp->room--;
}
int kgetc()
{
char c;
KBD *kp = &kbd;
//printf("%d in kgetc\n", running->pid);
while(kp->data == 0);
lock();
c = kp->buf[kp->tail++];
kp->tail %= 128;
kp->data--; kp->room++;
unlock();
return c;
}
int kgets(char s[ ])
{
char c;
while( (c = kgetc()) != '\r'){
if (c=='\b'){
s--;
continue;
}
*s++ = c;
}
*s = 0;
return strlen(s);
}
<file_sep>/*********** t.c file of A Multitasking System *********/
#include <stdio.h>
#include "type.h"
#include "string.h"
#include "queue.c" // include queue.c file
PROC proc[NPROC]; // NPROC PROCs
PROC *freeList; // freeList of PROCs
PROC *readyQueue; // priority queue of READY procs
PROC *running; // current running proc pointer
PROC *zombieList; //
PROC *sleepList; // sleepList of PROCs
/*******************************************************
kfork() creates a child process; returns child pid.
When scheduled to run, child PROC resumes to body();
********************************************************/
int body();
int tswitch();
int ksleep(int event)
{
running->event = event;
running->status = SLEEP;
enqueue(&sleepList, running);
printList("sleepList", sleepList);
tswitch();
}
int kwakeup(int event) {
int i;
PROC *p = sleepList;
PROC *temp;
temp = 0;
if (p == NULL) // No Child in SleepList
{
printf("[!] - NO CHILD IN SLEEPLIST TO WAKEUP.\n");
return -1;
}
else
{
while(p = dequeue(&sleepList))
{
if (p->event == event)
{
printf("WAKE UP THE CHILD #%d\n", p->pid);
p->status = READY;
enqueue(&readyQueue, p);
}
else
{
enqueue(&temp, p);
}
}
sleepList = temp;
printList("sleepList", sleepList);
}
return 0;
}
int kfork()
{
int i;
PROC *p = dequeue(&freeList);
if (!p){
printf("no more proc\n");
return(-1);
}
/* initialize the new proc and its stack */
p->status = READY;
p->priority = 1; // ALL PROCs priority=1,except P0
p->ppid = running->pid;
p->parent = running; // Saves content of parent proc
if(p->parent->child == 0)
{ /// child is empty
p->parent->child = p; // Stores p in binary tree
}
else
{ /// child is not empty
PROC *temp = p->parent->child;
while(temp->sibling != 0)
{
temp = temp->sibling; // traverse until free node
}
temp->sibling = p; //Stores p in binary tree @node
}
/************ new task initial stack contents ************
kstack contains: |retPC|eax|ebx|ecx|edx|ebp|esi|edi|eflag|
-1 -2 -3 -4 -5 -6 -7 -8 -9
**********************************************************/
for (i=1; i<10; i++) // zero out kstack cells
p->kstack[SSIZE - i] = 0;
p->kstack[SSIZE-1] = (int)body; // retPC -> body()
p->ksp = &(p->kstack[SSIZE - 9]); // PROC.ksp -> saved eflag
enqueue(&readyQueue, p); // enter p into readyQueue
return p->pid;
}
int kexit(int exitValue)
{
int i;
PROC *p;
for (i = 2; i < NPROC; i++)
{ // Skip root proc[0] and proc[1]
p = &proc[i];
/// Child sent to parent (orphanage)
if(p->status != FREE && p->ppid == running->pid)
{
p->ppid = 1;
p->parent = &proc[1];
if (p->status == ZOMBIE) {
p->status = FREE;
enqueue(&freeList, p); //Release all ZOMBIE childs
}
else
{
printf("Send child #&d to proc[1] (parent)\n", p->pid);
p->ppid = 1;
p->parent = &proc[1];
}
}
}
running->exitCode = exitValue; // Record exitValue in proc for parent
running->status = ZOMBIE; // Will not free PROC
enqueue(&zombieList, p);
kwakeup(running->parent);
kwakeup(&proc[1]);
tswitch(); //Switch process to give up CPU
}
int kwait(int *status)
{ /// proc waits for (and disposes of) a ZOMBIE child.
int i, hasChild = 0;
PROC *p;
while (1) {
for (i=1; i<NPROC; i++) {
p = &proc[i];
/// Search for (any) zombie child
if (p->status != FREE && p->ppid == running->pid)
{
hasChild = 1;
if (p->status == ZOMBIE)
{
dequeue(&zombieList);
*status = p->exitCode; // Get exit code
p->status = FREE; // Set status to Free
enqueue(&freeList, p); // release child PROC to freelist
return (p->pid); // Return pid
}
}
}
if (!hasChild) {
printf("[!] - NO CHILD FOUND / P1 NO DIE\n");
return -1;
}
ksleep(running);
}
}
int do_kfork()
{
int child = kfork();
if (child < 0)
printf("kfork failed\n");
else {
printf("proc %d kforked a child = %d\n", running->pid, child);
printList("readyQueue", readyQueue);
//printList("sleepList", sleepList);
}
return child;
}
int do_sleep()
{
int event;
printf("enter an event value to sleep on: ");
//event = geti();
ksleep(event);
}
int do_wakeup() {
int event;
printf("Enter an event value to wakeup with: ");
//event = geti();
kwakeup(event);
}
int do_wait()
{
int pid, status;
pid = kwait(&status);
printf("pid = %d, exitVal = %d\n", pid, status);
}
int do_switch()
{
tswitch();
}
int do_exit()
{
kexit(running->pid);
}
int do_jesus()
{
int i;
PROC *p;
printf("Jesus performs miracles\n");
for (i=1; i<NPROC; i++){
p = &proc[i];
if (p->status == ZOMBIE){
p->status = READY;
enqueue(&readyQueue, p);
printf("raised a ZOMBIE %d to live again\n", p->pid);
}
}
printList("readyQueue", readyQueue);
}
int menu()
{
printf("********************************\n");
printf(" ps fork switch exit jesus \n");
printf("********************************\n");
}
char *status[ ] = {"FREE", "READY", "SLEEP", "ZOMBIE"};
int do_ps()
{
int i;
PROC *p;
printf("PID PPID status\n");
printf("--- ---- ------\n");
for (i=0; i<NPROC; i++){
p = &proc[i];
printf(" %d %d ", p->pid, p->ppid);
if (p == running)
printf("RUNNING\n");
else
printf("%s\n", status[p->status]);
}
}
int body() // process body function
{
int c;
char cmd[64];
printf("proc %d starts from body()\n", running->pid);
while(1){
printf("***************************************\n");
printf(":: proc %d running: parent=%d\n", running->pid,running->ppid);
printList("readyQueue", readyQueue);
printList("sleepList", sleepList);
printList("freeList", freeList);
printList("zombieList", zombieList);
printList("running", running);
if (running->child != 0) { // Displays child
printf("\n- child list: %d", running->child->pid);
PROC *temp = running->child; // Gets current running child
while(temp->sibling != 0) { // Displays sibling of child
printf(", %d", temp->sibling->pid);
temp = temp->sibling;
}
printf("\n\n");
}
menu();
printf("\nenter a command:\n>> ");
fgets(cmd, 64, stdin);
printf("\n");
cmd[strlen(cmd)-1] = 0;
if (strcmp(cmd, "ps")==0)
do_ps();
else if (strcmp(cmd, "fork")==0)
do_kfork();
else if (strcmp(cmd, "switch")==0)
do_switch();
else if (strcmp(cmd, "exit")==0)
do_exit();
else if (strcmp(cmd, "jesus")==0)
do_jesus();
else if (strcmp(cmd, "wait")==0)
do_wait();
else
printf("[!] - INVALID INPUT\n");
}
}
// initialize the MT system; create P0 as initial running process
int init()
{
int i;
PROC *p;
for (i=0; i<NPROC; i++){ // initialize PROCs to freeList
p = &proc[i];
p->pid = i; // PID = 0 to NPROC-1
p->status = FREE;
p->priority = 0;
p->next = p+1;
}
proc[NPROC-1].next = 0;
freeList = &proc[0]; // all PROCs in freeList
readyQueue = 0; // readyQueue = empty
sleepList = 0;
// create P0 as the initial running process
p = running = dequeue(&freeList); // use proc[0]
p->status = READY;
p->priority = 0; // P0 has the lowest priority 0
p->ppid = 0; // P0 is its own parent
p->parent = p;
printList("freeList", freeList);
printf("init complete: P0 running\n");
}
/*************** main() function ***************/
int main()
{
printf("Welcome to the MT Multitasking System\n");
init(); // initialize system; create and run P0
kfork(); // kfork P1 into readyQueue
while(1){
printf("P0: switch process\n");
while (readyQueue == 0); // loop if readyQueue empty
tswitch();
}
}
/*********** scheduler *************/
int scheduler()
{
printf("proc %d in scheduler()\n", running->pid);
if (running->status == READY)
enqueue(&readyQueue, running);
printList("readyQueue", readyQueue);
running = dequeue(&readyQueue);
printf("next running = %d\n", running->pid);
}
<file_sep>#define NPIPE 10
#define PSIZE 8
typedef struct pipe
{
char buf[8]; // circular data buffer
int head, tail; // circular buf index
int data, room; // number of data & room in pipe
} PIPE;
PIPE pipe;
int show_pipe()
{
PIPE *p = &pipe;
int i;
printf("----------------------------------------\n");
printf("room=%d data=%d buf=", p->room, p->data);
for (i = 0; i < p->data; i++)
kputc(p->buf[p->tail + i]);
printf("\n");
printf("----------------------------------------\n");
}
int kpipe()
{
int i;
PIPE *p = &pipe;
p->head = p->tail = 0;
p->data = 0;
p->room = PSIZE;
}
int read_pipe(PIPE *p, char *buf, int n)
{
int ret;
char c;
if (n <= 0)
return 0;
show_pipe();
while (n)
{
printf("reader %d reading pipe\n", running->pid);
ret = 0;
while (p->data)
{
*buf = p->buf[p->tail++];
p->tail %= PSIZE;
buf++;
ret++;
p->data--;
p->room++;
n--;
if (n <= 0)
break;
}
show_pipe();
if (ret)
{
kwakeup(&p->room);
return ret;
}
// No data found from Pipe, must Sleep
printf("reader %d sleep for data\n", running->pid);
kwakeup(&p->room);
ksleep(&p->data);
continue;
}
}
int write_pipe(PIPE *p, char *buf, int n)
{
char c;
int ret = 0;
show_pipe();
while (n)
{
printf("writer %d writing pipe\n", running->pid);
while (p->room)
{
p->buf[p->head++] = *buf; // write a byte to pipe;
p->head %= PSIZE;
buf++;
ret++;
p->data++;
p->room--;
n--;
if (n <= 0)
{
show_pipe();
kwakeup(&p->data);
return ret;
}
}
show_pipe();
printf("writer %d sleep for room\n", running->pid);
kwakeup(&p->data);
ksleep(&p->room);
}
}
int pipe_reader()
{
char line[128];
int nbytes, n;
PIPE *p = &pipe;
printf("proc %d as pipe reader\n", running->pid);
while (1)
{
/*if (p->data = 0)
{ //No data nor writer
printf("NO MORE DATA - TERMINATE\n");
return 0;
}*/
printf("input nbytes to read : ");
nbytes = geti();
if (nbytes == 0)
{
kwakeup(&p->room);
kexit(running->pid);
}
n = read_pipe(p, line, nbytes);
line[n] = 0;
printf("Read n=%d bytes : line=%s\n", n, line);
}
}
int pipe_writer()
{
char line[128];
int nbytes, n;
PIPE *p = &pipe;
printf("proc %d as pipe writer\n", running->pid);
while (1)
{
printf("input a string to write : ");
kgets(line); // Gets input from user
if (strcmp(line, "") == 0)
{
kexit(running->pid);
continue;
}
nbytes = strlen(line);
printf("nbytes=%d buf=%s\n", nbytes, line);
n = write_pipe(p, line, nbytes);
printf("wrote n=%d bytes\n", n);
}
}
|
a36efcd7a95ee2b867b561ae29da48a77326f070
|
[
"Markdown",
"C",
"Text",
"Shell"
] | 60
|
C
|
c-trinh/CS460
|
d45e897042e66bd2eec9188e48ed551b9965308b
|
dd3d8604c1edaaf27e9d435629bf78839627efb2
|
refs/heads/master
|
<file_sep>#include "header.h"
string str2hex(const string& input){
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
string hex2str(const string& input){
static const char* const lut = "0123456789ABCDEF";
size_t len = input.length();
if (len & 1) throw invalid_argument("odd length");
string output;
output.reserve(len / 2);
for (size_t i = 0; i < len; i += 2)
{
char a = input[i];
const char* p = lower_bound(lut, lut + 16, a);
if (*p != a) throw invalid_argument("not a hex digit");
char b = input[i + 1];
const char* q = lower_bound(lut, lut + 16, b);
if (*q != b) throw invalid_argument("not a hex digit");
output.push_back(((p - lut) << 4) | (q - lut));
}
return output;
}
string encrypt(string input){
string encryptThis = input;
/*string encryptThis;
char pad;
srand ((unsigned) time(NULL));
pad = rand()%26 + 'a';
encryptThis = pad;
encryptThis.append(input);
pad = rand()%26 + 'a';
encryptThis += pad;
pad = rand()%26 + 'a';
encryptThis += pad;
for( int i=0; encryptThis[i] != '\0'; ++i ){
++encryptThis[i];
encryptThis[i] = encryptThis[i]^(int(key)+i)%255;
}*/
return str2hex(encryptThis);
}
string decrypt(string input){
string tmp;
tmp = hex2str(input);
input = tmp;
string decryptThis = input;
/*
string decryptThis = input.substr(0,input.size()-2);
for( int i=0; decryptThis[i] != '\0'; ++i ){
decryptThis[i] = decryptThis[i]^(int(key)+i)%255;
--decryptThis[i];
}
decryptThis.erase(0,1);
*/
return decryptThis;
}
void getDatabaseDetails(string *DBHOST, string *USER, string *PASSWORD, string *DATABASE){
FILE *dbFile;
char buf[128];
string crypt;
dbFile = fopen("database.conf","r");
if (dbFile == NULL){
perror ("Couldn't open database.conf");
return;
}
fgets(buf, 128, dbFile);
crypt = buf;
crypt.pop_back();
fgets(buf, 128, dbFile);
*DBHOST = buf;
DBHOST->pop_back();
fgets(buf, 128, dbFile);
*USER = buf;
USER->pop_back();
fgets(buf, 128, dbFile);
*PASSWORD = buf;
PASSWORD->pop_back();
fgets(buf, 128, dbFile);
*DATABASE = buf;
DATABASE->pop_back();
fclose(dbFile);
if (crypt == "decrypted"){
dbFile = fopen("database.conf","w");
strncpy(buf, "encrypted\n", 128);
fputs(buf, dbFile);
strncpy(buf, encrypt(*DBHOST).c_str(), 128);
fputs(buf, dbFile); fputc('\n', dbFile);
strncpy(buf, encrypt(*USER).c_str(), 128);
fputs(buf, dbFile); fputc('\n', dbFile);
strncpy(buf, encrypt(*PASSWORD).c_str(), 128);
fputs(buf, dbFile); fputc('\n', dbFile);
strncpy(buf, encrypt(*DATABASE).c_str(), 128);
fputs(buf, dbFile);
fclose(dbFile);
}else if (crypt == "encrypted"){
*DBHOST = decrypt(*DBHOST);
*USER = decrypt(*USER);
*PASSWORD = decrypt(*PASSWORD);
*DATABASE = decrypt(*DATABASE);
}else{
printf("ERROR: This is not the database.conf you are looking for!");
}
}
int retrieveSQL(map<const int,Entry> &entries, hd44780 &lcd){
Entry person;
try {
Driver *driver;
Connection *con;
PreparedStatement *pstmt;
ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect(DBHOST, USER, PASSWORD);
con->setSchema(DATABASE);
pstmt = con->prepareStatement("SELECT * FROM dreg_persons");
res = pstmt->executeQuery();
string test;
while (res->next()){
Entry person( res->getInt("id"),
res->getString("last_name").c_str(),
res->getString("first_name").c_str(),
res->getInt("tab"),
res->getInt("cash"),
res->getInt("spent"),
res->getString("comment").c_str());
entries[res->getInt("id")] = person;
}
delete res;
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line "
<< __LINE__ << endl;
cout << "# ERR: " << e.what() << endl;
lcd.clear();
lcd.write("Error retrieving SQL\ndatabase!\nAre you connected to\nthe internet?",50);
}
return EXIT_SUCCESS;
}
int updateSQL(int id, string field, int int_value, hd44780 &lcd){
int n = -1;
enum FIELDS{
cash,
spent};
try {
Driver *driver;
Connection *con;
PreparedStatement *pstmt;
map<const int,Entry>::iterator it;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect(DBHOST, USER, PASSWORD);
con->setSchema(DATABASE);
if (field == "cash") {n = cash;}
else if (field == "spent") {n = spent;}
switch (FIELDS(n)){
case cash:
pstmt = con->prepareStatement("UPDATE dreg_persons SET cash = ? WHERE id = ? LIMIT 1");
pstmt->setInt(1,int_value);
break;
case spent:
pstmt = con->prepareStatement("UPDATE dreg_persons SET spent = ? WHERE id = ? LIMIT 1");
pstmt->setInt(1,int_value);
break;
default:
pstmt = con->prepareStatement("");
printf("SQL identifier not recognized!\n");
break;
}
pstmt->setInt(2,id);
pstmt->executeUpdate();
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line "
<< __LINE__ << endl;
cout << "# ERR: " << e.what() << endl;
lcd.clear();
lcd.write("Error updating SQL\ndatabase!\nAre you connected to\nthe internet?",50);
}
return EXIT_SUCCESS;
}
<file_sep># CMake's configuration
# Set the minimum required version of CMake for this project
cmake_minimum_required(VERSION 2.6)
# Set the compiler flags
add_definitions(-Wall -ansi -pedantic -pedantic-errors -std=c++11)
# Find dependencies
find_package(RpiHw REQUIRED)
find_package(Freetype REQUIRED)
find_package(Boost REQUIRED)
# Set the path to the header files
include_directories(${RpiHw_INCLUDE_DIRS})
include_directories(${MYSQLCPPCONN_SOURCE_DIR})
include_directories(${Boost_INCLUDE_DIRS})
# Add librares
add_library(mysql mysql.cpp)
add_library(functions functions.cpp)
add_library(classes classes.cpp)
# Build
add_executable(DeltaPi DeltaPi.cpp)
add_executable(EpsilonPi EpsilonPi.cpp)
target_link_libraries(DeltaPi classes functions mysql mysqlcppconn ${RpiHw_LIBRARIES} ${Boost_LIBRARIES})
target_link_libraries(EpsilonPi classes functions mysql mysqlcppconn ${RpiHw_LIBRARIES} ${Boost_LIBRARIES})
<file_sep>#include "header.h"
map<const int, Entry> entries;
string DBHOST; //Database host
string USER; //Database user
string PASSWORD; //<PASSWORD> password
string DATABASE; //Database directory
int main(int argc, char* argv[]){
hd44780 lcd(14, 15, 24, 25, 8, 7);
lcd.init(20, 4);
lcd.setAutoscroll(hd44780::HSCROLL_LINE | hd44780::VSCROLL);
rpihw::gpio &io = rpihw::gpio::get();
io.setup(23, rpihw::OUTPUT);
io.write(23, rpihw::HIGH); bool *backlight = new bool(true);
uint8_t blank[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
lcd.defChar(hd44780::CCHAR2, blank);
getDatabaseDetails(&DBHOST, &USER, &PASSWORD, &DATABASE);
retrieveSQL(entries, lcd);
entries.erase(0);
int card = 0;
lcd.move(0,2);
printfl("DeltaPi ver. 0.9.0",lcd);
do{
moveAndClearLine(0,0,lcd);
lcd.write("Retrieving database");
retrieveSQL(entries, lcd);
scanCard(entries, card, lcd);
if (!(*backlight))
changeBacklight(io, backlight, lcd);
if (card > 10){
moveAndClearLine(0,1,lcd);
lcd.write("Retrieving database");
retrieveSQL(entries, lcd);
printInfo(entries, card, lcd);
transaction(entries, card, lcd);
}
else if (card == 0){
printHelp(lcd);
}else if (card == 1){
lcd.write("Retrieving database");
retrieveSQL(entries, lcd);
printSummary(entries, lcd);
} else if (card == 3){
lcd.clear();
lcd.move(0,1);
printfl("Retrieving database", lcd);
retrieveSQL(entries, lcd);
} else if (card == 4){
printTime(lcd);
} else if (card == 6){
printLastCoffee(lcd);
} else if (card == 9){
changeBacklight(io, backlight, lcd);
}
}while (card != -1);
lcd.clear();
printfl(" Closing DeltaPi", lcd);
lcd.move(6,2);
lcd.write("Goodbye! .",128);
io.write(23, rpihw::LOW);
delete backlight;
return 0;
}
<file_sep><?php
// Get average functions and all that stuff
include 'lib/functions.php';
// Load the configuration
$config = getConfig();
// Load the temperature.log file
$temperatureFile = file_get_contents('temperature.log');
// Regex to capture format: 2013-07-22T21:30:01+0200;46.5
$regex = "/^((?:[0-9]{2,4}-?){3})T((?:[0-9]{2}:?){3}).*?;([0-9.]*$)/im";
preg_match_all($regex, $temperatureFile, $result);
// Prepare the values
$values = $result[3];
$floatValues = array();
foreach ($values as $value) {
$floatValue = floatval($value);
// Conversation to farenheit?
if ($config['unit'] == 'f') {
$floatValue = $floatValue * 9 / 5 + 32; // Conversion to Farenheit
}
$floatValues[] = $floatValue;
}
$valuesLast24Hours = array_slice($floatValues, -96);
$valuesLastWeek = array_slice($floatValues, -96*7);
// Merge date and time part together
$labels = array_map(function($a, $b){
$dateString = $a . ' ' . $b . ' UTC';
return strtotime($dateString) * 1000;
}, $result[1], $result[2]);
// Create Points for Flot charting library
$points = array_map(function($a, $b){
return array($a, $b);
}, $labels, $floatValues);
// Calculate average and min/max values
$average = average($floatValues);
$lowest = getMin($floatValues);
$highest = getMax($floatValues);
$average24Hours = average($valuesLast24Hours);
$lowest24Hours = getMin($valuesLast24Hours);
$highest24Hours = getMax($valuesLast24Hours);
$averageWeek = average($valuesLastWeek);
$lowestWeek = getMin($valuesLastWeek);
$highestWeek = getMax($valuesLastWeek);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Raspberry Pi Monitor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<meta http-equiv="refresh" content="900">
<!-- Le styles -->
<link href="css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-inverse 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="#">Raspberry Pi</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Temperature</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<h3>Last 24 Hours</h3>
<div id="day" style="height:300px" class="span9"></div>
<div class="span2 well">
<p>Average: <strong class="pull-right"><?php echo $average24Hours;?> C°</strong></p>
<p>Lowest: <strong class="pull-right"><?php echo $lowest24Hours?> C°</strong></p>
<p>Highest: <strong class="pull-right"><?php echo $highest24Hours?> C°</strong></p>
</div>
</div>
<div class="row">
<h3>Last Week</h3>
<div id="week" style="height:300px" class="span9"></div>
<div class="span2 well">
<p>Average: <strong class="pull-right"><?php echo $averageWeek;?> C°</strong></p>
<p>Lowest: <strong class="pull-right"><?php echo $lowestWeek?> C°</strong></p>
<p>Highest: <strong class="pull-right"><?php echo $highestWeek?> C°</strong></p>
</div>
</div>
<div class="row">
<h3>Overall</h3>
<div id="overall" style="height:300px" class="span9"></div>
<div class="span2 well">
<p>Average: <strong class="pull-right"><?php echo $average;?> C°</strong></p>
<p>Lowest: <strong class="pull-right"><?php echo $lowest?> C°</strong></p>
<p>Highest: <strong class="pull-right"><?php echo $highest?> C°</strong></p>
</div>
</div>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.flot.min.js"></script>
<script src="js/jquery.flot.time.min.js""></script>
<script src="js/jquery.flot.tooltip.min.js""></script>
<?php
// Prepare the data
$pointsDay = array_slice($points, -96);
$pointsWeek = array_slice($points, -672);
?>
<script type="text/javascript">
$(document).ready(function() {
var options = {
xaxis: {
mode: "time",
format: "%d.%m.Y %H:%M"
},
yaxis: {
tickFormatter: function(value) {
return value.toFixed(1) + ' <?php echo strtoupper($config['unit'])?>°';
}
},
grid: {
hoverable: true,
clickable: true,
},
tooltip: true,
tooltipOpts: {
content: "%y"
}
};
var dataDay = [{
color: "rgb(212,62, 48)",
data: <?php echo json_encode($pointsDay);?>
}];
$.plot($("#day"), dataDay, options);
var dataWeek = [{
color: "rgb(212,62, 48)",
data: <?php echo json_encode($pointsWeek);?>
}];
$.plot($("#week"), dataWeek, options);
var dataOverall = [{
color: "rgb(212,62, 48)",
data: <?php echo json_encode($points);?>
}];
$.plot($("#overall"), dataOverall, options);
});
</script>
</body>
</html><file_sep>DeltaPiBeer
===========
# Dependencies
Rpi-hw 0.7.3<br>
https://github.com/Wicker25/Rpi-hw
Boost 1.49.0<br>
sudo apt-get install libboost-all-dev
MySQL connector<br>
sudo apt-get install libmysqlcppconn-dev<br>
C 6.1.2<br>
C++ 1.1.3
## Root access to shared libraries (for MySQL connector)
``sudo bash -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/local.conf"``<br>
``sudo /sbin/ldconfig``
## Give file root access without running sudo
``sudo chown root ./DeltaPi`` <br>
``sudo chmod 4755 ./DeltaPi``
## Startup on boot
``$ vim ~/startup.sh``
``#!/bin/sh``<br>
``sleep 5``<br>
``/usr/local/DeltaPi``<br>
``sleep 2``<br>
``/usr/local/EpsilonPi``<br>
``shutdown -h now``
``$ chmod 771 startup.sh``<br>
``$ sudo chown root:USERNAME /sbin/shutdown && sudo chmod 4770 /sbin/shutdown``
``$ vim ~/.bashrc``
Run the startup bash script:<br>
``echo starting DeltaPi``<br>
``bash startup.sh``
# Autologin
``sudo vim /etc/inittab``
comment out line:<br>
``"1:2345:respawn:/sbin/ getty 115200 tty1" => "#1:2345:respawn:/sbin/ getty 115200 tty1"``
add:<br>
``1:2345:respawn:/bin/login -f USERNAME tty1\</dev/tty1 >/dev/tty1 2>&1``
# Webserver
``sudo addgroup www-data`` <br>
``sudo adduser www-data www-data`` <br>
``sudo mkdir /var/www`` <br>
``sudo chown -R www-data:www-data /var/www`` <br>
``sudo apt-get install apache2``
``sudo chown 640 "FILE"``
https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts
Web port: 80<br>
DNS port: 53
# Database
Place database.conf in same run directory as DeltaPi. (in ~/ following the setup.sh)
The syntax is as follows:<br>
``decrypted`` <br>
``'Host'`` <br>
``'User'`` <br>
``'Password'`` <br>
``'Database'`` <br>
<file_sep>#include "header.h"
int main(int argc, char* argv[]){
if(daemon(0,0) == -1)
err(1, NULL);
rpihw::gpio &io = rpihw::gpio::get();
//Office ports
io.setup(11, rpihw::INPUT);
io.setup(4, rpihw::OUTPUT);
//Coffee ports
io.setup(10, rpihw::INPUT);
io.setup(22, rpihw::OUTPUT);
bool office = io.read(11);
bool office_prev = !office;
FILE *officeFile;
time_t officeTime = 0;
bool coffee = true;
bool coffee_prev = !coffee;
FILE *coffeeFile;
FILE *coffeeLog;
time_t coffeeTime = 0;
time_t coffeePress = 0;
int coffeePots = 0;
time_t startTime = 0;
time(&startTime);
int startDay = localtime(&startTime)->tm_yday;
struct tm * timeinfo;
//hd44780 lcd(14, 15, 24, 25, 8, 7);
//lcd.init(20, 4);
//lcd.clear();
//lcd.move(0,1);
//lcd.write("EpsilonPi ver. 0.7.6");
while (true){
if (!office){ //There is light.
time(&officeTime);
}
if ((int)difftime(time(NULL),officeTime) >= 10){ //Check to close office every 10s
if (office_prev != office){
office_prev = true;
io.write(4, rpihw::LOW);
officeFile = fopen("/var/www/pi.deltahouse.no/public_html/office.txt","w");
if (officeFile == NULL){
perror ("Couldn't open office.txt");
}else{
fprintf(officeFile,"off");
fclose(officeFile);
}
//lcd.move(0,3);
//lcd.write(" Office closed! ");
//lcd.move(5,0);
}
}else{
if (office_prev != office){
office_prev = false;
io.write(4, rpihw::HIGH);
sleep(1);
officeFile = fopen("/var/www/pi.deltahouse.no/public_html/office.txt","w");
if (officeFile == NULL){
perror ("Couldn't open office.txt");
}else{
fprintf(officeFile,"on");
fclose(officeFile);
}
//lcd.move(0,3);
//lcd.write(" Office open! ");
//lcd.move(5,0);
}
}
if (!coffee){ //Coffee button is pressed.
time(&coffeeTime);
}
if ((int)difftime(time(NULL),coffeeTime) <= 30*60){ //Coffee light stays on for 30*60 s
if ((coffee_prev != coffee) && (int)difftime(coffeeTime,coffeePress) >= 30){
io.write(22, rpihw::HIGH);
char buf [64];
coffee_prev = coffee;
time(&coffeePress);
timeinfo = localtime(&coffeePress);
if (timeinfo->tm_yday != startDay){
coffeePots = 0;
time(&startTime);
startDay = localtime(&startTime)->tm_yday;
}
coffeePots++;
strftime(buf,64,"%d. %B %Y %T",timeinfo);
coffeeFile = fopen("/var/www/pi.deltahouse.no/public_html/coffee.txt","w");
if (coffeeFile == NULL){
perror ("Couldn't open coffee.txt");
}else{
fprintf(coffeeFile,"%i\n%s",coffeePots,buf);
fclose(coffeeFile);
}
coffeeLog = fopen("/var/www/pi.deltahouse.no/public_html/coffee_log.txt","a+");
if (coffeeLog == NULL){
perror ("Couldn't open coffee_log.txt");
}else{
fprintf(coffeeLog,"%i:%s\n",coffeePots,buf);
fclose(coffeeLog);
}
//lcd.move(0,3);
//lcd.write(" Brewed today: %2i", coffeePots);
//lcd.move(5,0);
}
}else{
if (coffee_prev != coffee){
io.write(22, rpihw::LOW);
coffee_prev = coffee;
}
}
office = io.read(11);
coffee = io.read(10);
usleep(650);
}
return 0;
}
<file_sep><?php
/**
* Merges the application and the local config and returns it.
*/
function getConfig()
{
$config = include dirname(__FILE__) . '/../config.php';
if (file_exists(dirname(__FILE__) . '/../local.config.php')) {
// Load the local config an merge
$localConfig = include dirname(__FILE__) . '/../local.config.php';
$config = array_merge($config, $localConfig);
}
return $config;
}
/**
* Calculates the average of the given values
*/
function average($values) {
$total = 0;
$count = 0;
foreach ($values as $temperature) {
$total += $temperature;
$count++;
}
return number_format(round($total / $count, 1), 1);
}
/**
* @return the minimum value in an array of integers.
*/
function getMin($values) {
$lowest = NULL;
foreach ($values as $temperature) {
$value = $temperature;
if ($lowest === NULL || $value < $lowest) {
$lowest = $value;
}
}
return number_format($lowest, 1);
}
/**
* @return the maximum value in an array of integers
*/
function getMax($values) {
$highest = NULL;
foreach ($values as $temperature) {
$value = $temperature;
if ($highest === NULL || $value > $highest) {
$highest = $value;
}
}
return number_format($highest, 1);
}
/**
* Sends a notification email to the email address defined
* in the configuration file.
* If no email address is defined, this method files silently.
* @param $temp The measured temperature
* @param $addresses The addresses you want to send an email to.
*/
function sendEmailNotification($temp, $addresses = array())
{
$to = join(",", $addresses);
$subject = "PiTemp Notification";
$message = createNotificationText($temp);
$headers = "From: PiTemp <<EMAIL>mp.local> \r\n";
// Send the mail!
mail($to, $subject, $message, $headers);
}
/**
* Sends a notification over pushover.net to the user
* that is defined in the configuration file.
* This method uses a small script on our server to "hide" our
* application key.
* The script used on our server is also available on github if you
* want to review it.
* @todo Add Github URL to server script
* @param $temp The measured temperature
* @param $userKey The Pushover User key.
*/
function sendPushoverNotification($temp, $userKey)
{
// Get the url to the PiTemp Server
$config = getConfig();
$pitempServer = $config['pi_temp_server'];
// Initialize cURL for the request
$curl = curl_init();
// Set the options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $pitempServer . "?temp=" . $temp . "&userkey=" . $userKey
));
// Send the request
$response = curl_exec($curl);
// @todo Add some sort of log to log failed attempts.
// Close the request
curl_close($curl);
}
/**
* Sends a notification via pushbullet.com to the device
* that is defined in the configuration file.
* @param $temp The measured temperature
* @param $deviceid The Pushbullet device ID.
* @param $apikey The Pushbullet API key.
*/
function sendPushbulletNotification($temp, $deviceid, $apikey)
// some code snippets from https://github.com/fodawim/PushBullet-API-PHP/blob/master/pushbullet.php
{
$post_data = array(
'device_id' => $deviceid,
'type' => 'note',
'title' => 'PiTemp notification',
'body' => createNotificationText($temp)
);
$post_data_string = http_build_query($post_data);
$ch = curl_init('https://www.pushbullet.com/api/pushes');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $apikey . ":");
curl_setopt($ch, CURLOPT_POST, count($post_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
$response = curl_exec($ch);
// Close the request
curl_close($ch);
}
/**
* Gets the local IP address (hopefully)
* works with German console language
* @todo Implement independent from language
* @param $interface The network interface
*/
function getServerAddress($interface)
{
// Parse the result of ifconfig to get the ip address
$ifconfig = shell_exec('/sbin/ifconfig ' . $interface);
preg_match('/inet [A-Za-z]*?:([\d\.]+)/', $ifconfig, $match);
return isset($match[1]) ? $match[1] : '';
}
/**
* Creates the notification text
* @param float $temp The temperature in degree C.
*/
function createNotificationText($temp)
{
$config = getConfig();
$notifiactionConfig = $config['notification'];
$message = "Your Raspberry Pi's temperature raised above your defined maximum temperature. \r\n\r\n";
// Add Temp
$message .= "Current temperature: " . $temp . "C\r\n";
// Add (optional) hostname
if ($notifiactionConfig['show_hostname']) {
$message .= "Hostname: " . gethostname() . "\r\n";
}
// Add (optional) IP address
if ($notifiactionConfig['show_ip_address']) {
$message .= "IP Address: " . getServerAddress('eth0') . "\r\n";
}
return $message;
}
<file_sep>#!/usr/bin/php
<?php
include dirname(__FILE__) . '/lib/functions.php';
// Get temperature (see http://www.raspberrypi.org/phpBB3/viewtopic.php?f=45&t=25100)
$temp = exec('/opt/vc/bin/vcgencmd measure_temp');
preg_match("/^temp=([\d.]+)/", $temp, $matches);
// Temperature is stored in at index 1.
$temp = $matches[1];
$date = new DateTime();
$line = $date->format(DateTime::ISO8601) . ";" . $temp . "\n";
// Write the temp to a file
$filePath = realpath(dirname(__FILE__));
file_put_contents(dirname(__FILE__) . '/temperature.log', $line, FILE_APPEND);
// Check if we should send a notification
$config = getConfig();
$notificationConfig = $config['notification'];
$maxTemp = $notificationConfig['max_temp'];
if ((int)$temp >= $maxTemp) {
// Temp is too high! Send notification!
if ($notificationConfig['enable_email']) {
$addresses = $notificationConfig['email_addresses'];
sendEmailNotification($temp, $addresses);
}
if ($notificationConfig['enable_pushover']) {
$userkey = $notificationConfig['pushover_userkey'];
sendPushoverNotification($temp, $userkey);
}
if ($notificationConfig['enable_pushbullet']) {
$deviceid = $notificationConfig['pushbullet_deviceid'];
$apikey = $notificationConfig['pushbullet_apikey'];
sendPushbulletNotification($temp, $deviceid, $apikey);
}
}<file_sep>#include "header.h"
void moveAndClearLine(int i, int j, hd44780 &lcd){
lcd.move(i,j);
lcd.write(" ");
lcd.move(i,j);
}
char getch(){
struct termios old_tio, new_tio;
char buf = 0;
tcgetattr(STDIN_FILENO,&old_tio);
new_tio=old_tio;
new_tio.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);
if (read(0, &buf, 1) < 0)
perror ("read()");
tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
return (buf);
}
void getLine(char buf[], hd44780 &lcd){
char c;
int i = 0;
lcd.setCursor(hd44780::CURSOR_BLINKING);
uint8_t startx = lcd.getCursorX();
uint8_t starty = lcd.getCursorY();
uint8_t xpos;
do{
xpos = lcd.getCursorX();
c = getch();
if ((int)c == 127){
if (i > 0){
write(1, "\b \b", 3);
i--;
}
xpos = (xpos <= startx)?(startx):(xpos-1);
lcd.move(xpos,starty);
lcd.write(' ');
lcd.move(xpos,starty);
}else{
buf[(i++)%128] = c;
lcd.write(c);
write(1, &c, 1);
}
}while (c != '\n');
buf[i%128] = '\0';
lcd.setCursor(hd44780::NO_CURSOR);
}
void printfl(string str, hd44780 &lcd){
printf("%s\n", str.c_str());
lcd.write(str);
}
char* str2char(string s){
char *c=new char[s.size()+1];
c[s.size()]=0;
memcpy(c,s.c_str(),s.size());
return c;
}
void scanCard(map<const int, Entry> &entries, int &card, hd44780 &lcd){
string input;
char buf[128];
do{
moveAndClearLine(0,0,lcd);
printfl("Scan:", lcd);
getLine(buf, lcd);
input = buf;
stringstream checkIfNumber(input);
if (checkIfNumber >> card){
if (card == -1){return;}
if (card <= 10){
printfl(" command",lcd);
return;
}
if (entries.find(card) == entries.end()){
moveAndClearLine(0,3,lcd);
moveAndClearLine(0,2,lcd);
moveAndClearLine(0,1,lcd);
printfl("Card ID not found!",lcd);
}else{
return;
}
}
else{
moveAndClearLine(0,3,lcd);
moveAndClearLine(0,2,lcd);
moveAndClearLine(0,1,lcd);
printfl("Invalid input!",lcd);
}
}while (true);
return;
}
void printInfo(map<const int, Entry> &entries, int &card, hd44780 &lcd){
char buf[128];
lcd.clear(); lcd.move(0, 0);
sprintf(buf, "%s", entries.find(card)->second.getFirstName().c_str());
printfl(buf, lcd);
lcd.move(0,1);
sprintf(buf, "Balance: %i Δ", entries.find(card)->second.getCash());
printfl(buf, lcd);
}
void transaction(map<const int, Entry> &entries, int &card, hd44780 &lcd){
char buf[128];
string input;
int *amount = new int(-1);
moveAndClearLine(0,2,lcd);
printfl("Amount:", lcd);
moveAndClearLine(0,3,lcd);
printfl("Prefix + to donate Δ", lcd);
lcd.move(8,2);
getLine(buf, lcd);
input = buf;
if (input.substr(0,1) == "+"){
input.erase(0,1);
if ((*amount = atoi(input.c_str())) && (*amount <= maxAmount)){
entries.find(card)->second.depositCash(*amount);
moveAndClearLine(0,1,lcd);
moveAndClearLine(0,2,lcd);
sprintf(buf, "%i Δ donated.", *amount);
printfl(buf, lcd);
moveAndClearLine(0,3,lcd);
sprintf(buf, "New tokens: %i Δ", entries.find(card)->second.getCash());
printfl(buf, lcd);
printf("\n");
}else if(buf[1] == '0'){
moveAndClearLine(0,1,lcd);
printfl("You used 0.", lcd);
moveAndClearLine(0,2,lcd);
printfl("It's not very ", lcd);
moveAndClearLine(0,3,lcd);
printfl("effective...", lcd);
}else{
moveAndClearLine(0,2,lcd);
printfl("Invalid input!", lcd);
moveAndClearLine(0,3,lcd);
sprintf(buf, "Input int <= %i", maxAmount);
printfl(buf, lcd);
}
}else{
if ((*amount = abs(atoi(input.c_str()))) && (*amount <= maxAmount)){
if ((entries.find(card)->second.getCash() - *amount) >= -((entries.find(card)->second.getTab()*maxCredit))){
entries.find(card)->second.withdrawCash(*amount);
entries.find(card)->second.increaseSpent(*amount);
moveAndClearLine(0,1,lcd);
moveAndClearLine(0,2,lcd);
sprintf(buf, "%i Δ used.", *amount);
printfl(buf, lcd);
moveAndClearLine(0,3,lcd);
sprintf(buf, "New balance: %i Δ", entries.find(card)->second.getCash());
printfl(buf, lcd);
}else{
moveAndClearLine(0,3,lcd);
moveAndClearLine(0,2,lcd);
printfl("Not enough Δ!",lcd);
}
}else if (buf[0] == '0'){
moveAndClearLine(0,1,lcd);
printfl("You used 0.", lcd);
moveAndClearLine(0,2,lcd);
printfl("It's not very ", lcd);
moveAndClearLine(0,3,lcd);
printfl("effective...", lcd);
}else{
moveAndClearLine(0,2,lcd);
printfl("Invalid input!", lcd);
moveAndClearLine(0,3,lcd);
sprintf(buf, "Input int <= %i", maxAmount);
printfl(buf, lcd);
}
}
updateSQL(card, "cash", entries.find(card)->second.getCash(), lcd);
updateSQL(card, "spent", entries.find(card)->second.getSpent(), lcd);
}
void printHelp(hd44780 &lcd){
lcd.clear();
printfl("0-help 1-summary", lcd);
lcd.move(0,1);
printfl("3-retrieve SQL", lcd);
lcd.move(0,2);
printfl("4-timestamp 6-coffee", lcd);
lcd.move(0,3);
printfl("9-backlight", lcd);
sleep(5);
}
void printSummary(map<const int, Entry> &entries, hd44780 &lcd){
map<const int,Entry>::iterator i;
int persons = 0;
long money = 0;
long spent = 0;
long credit = 0;
int tabs = 0;
char buf[128];
lcd.clear();
printfl("Database summary.\nGathering info...",lcd);
for (i = entries.begin(); i != entries.end(); i++){
persons++;
if (i->second.getTab()){tabs++;}
if (i->second.getCash() >= 0){
money += i->second.getCash();
}else{
credit -= i->second.getCash();
}
spent += i->second.getSpent();
}
lcd.clear();
sprintf(buf, "Persons: %5i", persons);
printfl(buf,lcd);
sprintf(buf, "Tot tokens: %5li Δ", money);
lcd.move(0,1);
printfl(buf,lcd);
sprintf(buf, "Tot credit: %5li Δ", credit);
lcd.move(0,2);
printfl(buf,lcd);
sprintf(buf, "Tot used: %5li Δ", spent);
lcd.move(0,3);
printfl(buf,lcd);
sleep(5);
}
void printTime(hd44780 &lcd){
time_t now;
struct tm timeinfo;
char buf [64];
time(&now);
timeinfo = *localtime(&now);
strftime(buf,64,"%a %d %b %H:%M:%S \nWeek %V Year %G",&timeinfo);
lcd.clear();
lcd.move(0,1);
printfl("Timestamp:", lcd);
lcd.move(0,2);
printfl(buf, lcd);
}
void printLastCoffee(hd44780 &lcd){
FILE *coffeeFile;
char buf[128];
char c = 'a';
int i = 0;
lcd.clear();
lcd.move(0,1);
printfl("Last coffee: ", lcd);
coffeeFile = fopen("/var/www/pi.deltahouse.no/public_html/coffee.txt","r");
if (coffeeFile == NULL){
perror ("Couldn't open coffee.txt");
lcd.write("Err open coffee.txt");
return;
}else{
fread(buf,1,128,coffeeFile);
fclose(coffeeFile);
}
while ((c != '\0')&&(i < 128)){
c = buf[i++];
}
buf[i-10] = '\n';
printfl(buf, lcd);
}
void changeBacklight(rpihw::gpio &io, bool *backlight, hd44780 &lcd){
lcd.clear();
lcd.move(0,1);
if (*backlight){
io.write(23, rpihw::LOW);
*backlight = false;
printfl("Backlight: OFF", lcd);
}else{
io.write(23, rpihw::HIGH);
*backlight = true;
printfl("Backlight: ON", lcd);
}
}
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/delta/DeltaPi
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/delta/DeltaPi
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
/usr/bin/cmake -i .
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /home/delta/DeltaPi/CMakeFiles /home/delta/DeltaPi/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /home/delta/DeltaPi/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named DeltaPi
# Build rule for target.
DeltaPi: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 DeltaPi
.PHONY : DeltaPi
# fast build rule for target.
DeltaPi/fast:
$(MAKE) -f CMakeFiles/DeltaPi.dir/build.make CMakeFiles/DeltaPi.dir/build
.PHONY : DeltaPi/fast
#=============================================================================
# Target rules for targets named EpsilonPi
# Build rule for target.
EpsilonPi: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 EpsilonPi
.PHONY : EpsilonPi
# fast build rule for target.
EpsilonPi/fast:
$(MAKE) -f CMakeFiles/EpsilonPi.dir/build.make CMakeFiles/EpsilonPi.dir/build
.PHONY : EpsilonPi/fast
#=============================================================================
# Target rules for targets named classes
# Build rule for target.
classes: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 classes
.PHONY : classes
# fast build rule for target.
classes/fast:
$(MAKE) -f CMakeFiles/classes.dir/build.make CMakeFiles/classes.dir/build
.PHONY : classes/fast
#=============================================================================
# Target rules for targets named functions
# Build rule for target.
functions: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 functions
.PHONY : functions
# fast build rule for target.
functions/fast:
$(MAKE) -f CMakeFiles/functions.dir/build.make CMakeFiles/functions.dir/build
.PHONY : functions/fast
#=============================================================================
# Target rules for targets named mysql
# Build rule for target.
mysql: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 mysql
.PHONY : mysql
# fast build rule for target.
mysql/fast:
$(MAKE) -f CMakeFiles/mysql.dir/build.make CMakeFiles/mysql.dir/build
.PHONY : mysql/fast
DeltaPi.o: DeltaPi.cpp.o
.PHONY : DeltaPi.o
# target to build an object file
DeltaPi.cpp.o:
$(MAKE) -f CMakeFiles/DeltaPi.dir/build.make CMakeFiles/DeltaPi.dir/DeltaPi.cpp.o
.PHONY : DeltaPi.cpp.o
DeltaPi.i: DeltaPi.cpp.i
.PHONY : DeltaPi.i
# target to preprocess a source file
DeltaPi.cpp.i:
$(MAKE) -f CMakeFiles/DeltaPi.dir/build.make CMakeFiles/DeltaPi.dir/DeltaPi.cpp.i
.PHONY : DeltaPi.cpp.i
DeltaPi.s: DeltaPi.cpp.s
.PHONY : DeltaPi.s
# target to generate assembly for a file
DeltaPi.cpp.s:
$(MAKE) -f CMakeFiles/DeltaPi.dir/build.make CMakeFiles/DeltaPi.dir/DeltaPi.cpp.s
.PHONY : DeltaPi.cpp.s
EpsilonPi.o: EpsilonPi.cpp.o
.PHONY : EpsilonPi.o
# target to build an object file
EpsilonPi.cpp.o:
$(MAKE) -f CMakeFiles/EpsilonPi.dir/build.make CMakeFiles/EpsilonPi.dir/EpsilonPi.cpp.o
.PHONY : EpsilonPi.cpp.o
EpsilonPi.i: EpsilonPi.cpp.i
.PHONY : EpsilonPi.i
# target to preprocess a source file
EpsilonPi.cpp.i:
$(MAKE) -f CMakeFiles/EpsilonPi.dir/build.make CMakeFiles/EpsilonPi.dir/EpsilonPi.cpp.i
.PHONY : EpsilonPi.cpp.i
EpsilonPi.s: EpsilonPi.cpp.s
.PHONY : EpsilonPi.s
# target to generate assembly for a file
EpsilonPi.cpp.s:
$(MAKE) -f CMakeFiles/EpsilonPi.dir/build.make CMakeFiles/EpsilonPi.dir/EpsilonPi.cpp.s
.PHONY : EpsilonPi.cpp.s
classes.o: classes.cpp.o
.PHONY : classes.o
# target to build an object file
classes.cpp.o:
$(MAKE) -f CMakeFiles/classes.dir/build.make CMakeFiles/classes.dir/classes.cpp.o
.PHONY : classes.cpp.o
classes.i: classes.cpp.i
.PHONY : classes.i
# target to preprocess a source file
classes.cpp.i:
$(MAKE) -f CMakeFiles/classes.dir/build.make CMakeFiles/classes.dir/classes.cpp.i
.PHONY : classes.cpp.i
classes.s: classes.cpp.s
.PHONY : classes.s
# target to generate assembly for a file
classes.cpp.s:
$(MAKE) -f CMakeFiles/classes.dir/build.make CMakeFiles/classes.dir/classes.cpp.s
.PHONY : classes.cpp.s
functions.o: functions.cpp.o
.PHONY : functions.o
# target to build an object file
functions.cpp.o:
$(MAKE) -f CMakeFiles/functions.dir/build.make CMakeFiles/functions.dir/functions.cpp.o
.PHONY : functions.cpp.o
functions.i: functions.cpp.i
.PHONY : functions.i
# target to preprocess a source file
functions.cpp.i:
$(MAKE) -f CMakeFiles/functions.dir/build.make CMakeFiles/functions.dir/functions.cpp.i
.PHONY : functions.cpp.i
functions.s: functions.cpp.s
.PHONY : functions.s
# target to generate assembly for a file
functions.cpp.s:
$(MAKE) -f CMakeFiles/functions.dir/build.make CMakeFiles/functions.dir/functions.cpp.s
.PHONY : functions.cpp.s
mysql.o: mysql.cpp.o
.PHONY : mysql.o
# target to build an object file
mysql.cpp.o:
$(MAKE) -f CMakeFiles/mysql.dir/build.make CMakeFiles/mysql.dir/mysql.cpp.o
.PHONY : mysql.cpp.o
mysql.i: mysql.cpp.i
.PHONY : mysql.i
# target to preprocess a source file
mysql.cpp.i:
$(MAKE) -f CMakeFiles/mysql.dir/build.make CMakeFiles/mysql.dir/mysql.cpp.i
.PHONY : mysql.cpp.i
mysql.s: mysql.cpp.s
.PHONY : mysql.s
# target to generate assembly for a file
mysql.cpp.s:
$(MAKE) -f CMakeFiles/mysql.dir/build.make CMakeFiles/mysql.dir/mysql.cpp.s
.PHONY : mysql.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... DeltaPi"
@echo "... EpsilonPi"
@echo "... classes"
@echo "... edit_cache"
@echo "... functions"
@echo "... mysql"
@echo "... rebuild_cache"
@echo "... DeltaPi.o"
@echo "... DeltaPi.i"
@echo "... DeltaPi.s"
@echo "... EpsilonPi.o"
@echo "... EpsilonPi.i"
@echo "... EpsilonPi.s"
@echo "... classes.o"
@echo "... classes.i"
@echo "... classes.s"
@echo "... functions.o"
@echo "... functions.i"
@echo "... functions.s"
@echo "... mysql.o"
@echo "... mysql.i"
@echo "... mysql.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep><p align="center">
<img src="img/PiTemp.png" />
</p>
#PiTemp
A simple script that monitors your Raspberry Pi's temperature.
----

##Installation
Before you can start monitoring your Pis temperature in your webbrowser you need to install a webserver with PHP. I use a LAMP setup. Follow one of the many guides like [this](http://www.dingleberrypi.com/2012/09/tutorial-install-apache-php-and-mysql-on-raspberry-pi/) or [this one](http://www.wikihow.com/Make-a-Raspberry-Pi-Web-Server) to setup your Raspberry Pi as a webserver.
If you have git installed on your Raspberry you can easily clone the repo into the webroot of your webserver.
// Example is for apache only.
// Replace /var/www/ with the webroot of your webserver
cd /var/www
git clone https://github.com/fechu/PiTemp
The next thing to do is to setup cron to execute the `monitor.php` script every 15 minutes to write down the temperature. You do this by modifing the file `/etc/crontab` like this:
sudo nano /etc/crontab
Add the following line to the end of the file.
*/15 * * * * root /var/www/PiTemp/monitor.php
This tells cron to execute the script every 15 minutes of an hour. `root` is the user that executes the script. and `/var/www/PiTemp/monitor.php` is the script that is executed.
That's it! Now you need to wait for your script to collect the data.
As soon as you can't wait anymore, just open your browser (the computer has to be connected to the same network as the Raspberry Pi) and navigate to `http://<Your Pi's IP>/PiTemp`.
##Configuration
You can find all configuration options in the `config.php` file. Have a look at it. Everything is directly documented in the `config.php` file.
###Override Configuration
In case you want to override the configuration but keep it easy to update PiTemp with a `git pull`, you can copy the `config.php` file and name it `local.config.php`. This file will then be ignored by git but merged with the `config.php`. This way you the `config.php` file stays untouched.
###Email Notification
Since version 0.1.0 there's support for email notification. You can define a maximum temperature in the `config.php` (or `local.config.php`) file. If the temperature raises above this level, you receive an email notification to the configured address.
The configuration of email notification is not that hard once you've configured your Raspberry Pi to send emails. However, this can be a little bit tricky. Use one of the many tutorials out there in the world wide web. I used [this one](http://www.dingleberrypi.com/2012/09/tutorial-install-postfix-to-allow-outgoing-email-on-raspberry-pi/) to set `postfix` up. You just have to make the PHP `mail()` function work.
###Pushover Notification
Since version 0.2.0 there's support for [Pushover](http://pushover.net) notification. If you want to use this feature, make sure you have the `cURL` extension for PHP installed. You can do so by executing the following commands:
sudo apt-get install php5-curl
The next (and last) thing you have to do is insert your Pushover userkey in your `config.php`/`local.config.php` file.
###Pushbullet Notification
Since version 0.3.0 there's support for [Pushbullet](https://www.pushbullet.com). If you want to use this feature you just have to drop in your API Key and Device ID into the `config`/`local.config.php` file.
##Todo
- Support F° & C° in notifications
- Support multiple Raspberry Pi
- Select timespan
- Use Sqlite/Mysql database instead of textfile
- Add possibility to test notifications
- Add support for hostname/IPAddress in Pushover notification
##Libraries
This project uses the following libraries or parts of them:
- Flot ([flotcharts.org](http://www.flotcharts.org)) Released under [MIT License](http://opensource.org/licenses/MIT)
- Twitter Bootstrap ([twitter.github.io/bootstrap/](https://twitter.github.io/bootstrap)) Released under [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
- jQuery ([jquery.com](http://jquery.com)) Released under [MIT License](http://opensource.org/licenses/MIT)
##Contributors
- [Litschi](https://github.com/Litschi) Created the awesome Logo!
- [elpatron68](https://github.com/elpatron68) Added the Pushbullet support
- [fechu](https://github.com/fechu) Yep. That's me!
##License
The MIT License (MIT)
Copyright (c) 2013 <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.
<file_sep><?php
return array(
/**
* Defines whether to display the temperature in degrees Fahrenheit or degrees Celsius.
*
* Values:
* "c" Ceslius
* "f" Farenheit
*/
"unit" => "c",
/**
* Contains settings for notifications
*/
"notification" => array(
/**
* The maximum temperature of the Pi. If the temperature raises
* above this level, a notification will be sent.
*/
'max_temp' => 50.0,
/**
* Define if the IP address of the Raspberry Pi is added to the notification.
*/
'show_ip_address' => false,
/**
* Define if the hostname of the Raspberry Pi is added to the notification.
*/
'show_hostname' => false,
/**
* Enable email notifications.
* Keep in mind that you have to set the email_address
* too. Otherwise you won't get any email.
*/
'enable_email' => false,
/**
* An array of all email addresses that should receive an email notification
* when the temperature is raised too high.
*/
'email_addresses' => array(
'<EMAIL>',
),
/**
* Enable notifications with Pushover.
* Take a look at http://pushover.net if you don't know that service.
* You just need to download their application and signup.
*/
'enable_pushover' => false,
/**
* Drop in your userkey from Pushover. This one is used for sending messages
* to your devices.
*/
'pushover_userkey' => 'YOUR_USER_KEY',
/**
* Enable notifications with Pushbullet (Android only).
* Take a look at https://www.pushbullet.com if you don't know that service.
* You just need to download their application and signup.
*/
'enable_pushbullet' => false,
/**
* Drop in your device-id from Pushbullet. It is used for sending messages
* to your device. You can find your device ID in Pushbullet´s dashboard.
*/
'pushbullet_deviceid' => 'YOUR_DEVICE_ID',
/**
* Drop in your API-Key from Pushbullet. It is used to access the Pushbullet
* service. You can find your device ID in Pushbullet´s account settings.
*/
'pushbullet_apikey' => 'YOUR_API_KEY',
),
/**
* The instance of PiTemp Server.
* At the moment the PiTemp Server is only used to deliver Pushover notifications
* to Pushover.net. It's a way to hide our Pushover application key.
* If you want to use your own instance you can get it from
* https://github.com/fechu/PiTemp-Server.git. Installation instructions are also
* available on github. Once you have your setup configured just drop in
* the URL to the pushover.php file in the root directory of PiTemp Server.
*/
'pi_temp_server' => 'http://pitemp.fidelisfactory.ch/pushover.php',
);<file_sep>#include "header.h"
Entry::Entry(){
this->cardId = 0;
this->firstName = "No";
this->lastName = "Name";
this->tab = false;
this->cash = 0;
this->spent = 0;
this->comment = "";
}
Entry::~Entry(){
}
Entry::Entry(int cardID, string lastName, string firstName, int tab, int cash, long spent, string comment){
this->cardId = cardID;
this->firstName = firstName;
this->lastName = lastName;
this->tab = tab;
this->cash = cash;
this->spent = spent;
this->comment = comment;
}
int Entry::getID(){
return this->cardId;
}
string Entry::getNameFirstLast(){
return this->firstName + " " + this->lastName;
}
string Entry::getFirstName(){
return this->firstName;
}
string Entry::getLastName(){
return this->lastName;
}
int Entry::getTab(){
return this->tab;
}
int Entry::getCash(){
return this->cash;
}
long Entry::getSpent(){
return this->spent;
}
string Entry::getComment(){
return this->comment;
}
void Entry::depositCash(int amount){
this->cash += amount;
}
void Entry::withdrawCash(int amount){
this->cash -= amount;
}
void Entry::increaseSpent(int amount){
this->spent += amount;
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html;charset=UTF-8">
<title>EpsilonPi</title>
<style>
body {background-color:#0C371D}
h1 {font-family:"Lucida Console";
text-decoration:underline;}
div {text-align:center;
border:10px;
margin-right:40%;
margin-left:40%;
margin-top:5%;
width:300px;
background-color:white;
font-family:"Courier";}
a {color:#00703C;}
open {color:#00CC00;}
closed {color:#CC0000;}
</style>
</head>
<body>
<div>
<br>
<h1>EpsilonPi</h1>
<?php
$fh = fopen('office.txt','r');
$line = fgets($fh);
if ($line == 'on'){
echo '<p>Office:<br><open>Open</open></p>';
}
else{
echo '<p>Office:<br><closed>Closed</closed></p>';
}
fclose($fh);
?>
<?php
$fh = fopen('coffee.txt','r');
$line = fgets($fh);
$line = fgets($fh);
echo '<p>Last coffee: <br>' . $line . '</p>';
?>
<h2>
<a href="http://deltahouse.no">
<img src="Coffee.svg" alt="Coffee time!"></a>
<?php
echo 'Week: ' . date("W") . '';
?></h2>
<p><a href="card.php">Find RFID tag</a></p>
<p>
<a href="office.txt">office.txt</a>
<a href="coffee.txt">coffee.txt</a>
<a href="coffee_log.txt">coffee_log.txt</a>
</p>
<p><a href="http://deltahouse.no/docs/">misc documents</a></p>
<p>π = 4⋅atan(1)</p>
<p><a href="/PiTemp">Temperature log</a></p>
<br>
</div>
</body>
</html>
<file_sep>#!/bin/sh
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install vim g++-4.7 cmake libfreetype6-dev libgraphicsmagick++1-dev doxygen
sudo ln -fs /usr/bin/g++-4.7 /usr/bin/g++
git clone https://github.com/Wicker25/Rpi-hw
cd Rpi-hw*
cmake . -DCMAKE_INSTALL_PREFIX=/usr -DFREETYPE_INCLUDE_DIRS=/usr/include/freetype/
make
sudo make install
cd ..
sudo apt-get install libboost-all-dev
sudo apt-get install libmysqlcppconn-dev
sudo bash -c "echo /usr/local/lib/ > /etc/ld.so.conf.d/local.conf"
sudo /sbin/ldconfig
git clone https://github.com/vehagn/DeltaPi
cd DeltaPi/
mkdir Release
cd Release/
cmake .. -DCMAKE_BUILD_TYPE=Release -DFREETYPE_INCLUDE_DIRS=/usr/include/freetype/
make
sudo cp *Pi /usr/local
sudo chown root /usr/local/*Pi
sudo chmod 4755 /usr/local/*Pi
cd ..
chmod 771 startup.sh
sudo chown root:pi /sbin/shutdown
sudo chmod 4770 /sbin/shutdown
echo 'bash ~/DeltaPi/startup.sh' >> ~/.bashrc
cp database.conf ~/
sudo addgroup www-data
sudo adduser www-data www-data
sudo mkdir /var/www
sudo mkdir /var/www/pi.deltahouse.no
sudo mkdir /var/www/pi.deltahouse.no/public_html
sudo chown -R www-data:www-data /var/www
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install php5 apache2
sudo cp -r ~/DeltaPi/web/public_html/* /var/www/pi.deltahouse.no/public_html/
sudo chown www-data:www-data /var/www/pi.deltahouse.no/public_html/*
echo 'Make changes to Apache to complete installation'
<file_sep>/* Standard C++ headers */
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
#include <err.h>
/* Rpi-hw headers */
#include <rpi-hw.hpp>
#include <rpi-hw/utils.hpp>
#include <rpi-hw/time.hpp>
#include <rpi-hw/gpio.hpp>
#include <rpi-hw/display/hd44780.hpp>
/* MySQL Connector/C++ specific headers */
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/connection.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/warning.h>
using namespace std;
using namespace sql;
using namespace rpihw::iface;
using namespace rpihw::display;
using namespace rpihw::utils;
extern string DBHOST, USER, PASSWORD, DATABASE;
const int maxCredit = 100; //Maximum allowed credit.
const int maxAmount = 500; //Maximum allowed transfer.
//Entry
class Entry{
private:
int cardId;
string firstName;
string lastName;
string comment;
int cash;
long spent;
int tab;
public:
Entry();
~Entry();
Entry(int, string, string, int, int, long, string);
void setInfo(map<const int,Entry> *);
int getID();
string getNameFirstLast();
string getFirstName();
string getLastName();
string getComment();
int getCash();
long getSpent();
int getTab();
void depositCash(int);
void withdrawCash(int);
void increaseSpent(int);
void openTab(bool);
};
//Functions
void moveAndClearLine(int, int, hd44780&);
char getch();
void getLine(char[], hd44780&);
void printfl(string, hd44780&);
char* str2char(string);
void scanCard(map<const int, Entry>&, int&, hd44780&);
void printInfo(map<const int, Entry>&, int&, hd44780&);
void transaction(map<const int, Entry>&, int&, hd44780&);
void printHelp(hd44780&);
void printSummary(map<const int, Entry>&, hd44780&);
void printTime(hd44780&);
void printLastCoffee(hd44780&);
void changeBacklight(rpihw::gpio&, bool*, hd44780&);
//SQL
string str2hex(const string&);
string hex2str(const string&);
string encrypt(string);
string decrypt(string);
void getDatabaseDetails(string*, string*, string*, string*);
int retrieveSQL(map<const int,Entry> &, hd44780 &lcd);
int updateSQL(int, string, int, hd44780 &lcd);
<file_sep>#!/bin/sh
sleep 1
echo Starting EpsilonPi
/usr/local/EpsilonPi
sleep 1
echo Starting DeltaPi
/usr/local/DeltaPi
echo Shutting down in 10 s. ctrl-c to cancel shutdown.
sleep 10
shutdown -h now<file_sep><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html;charset=UTF-8">
<title>Find RFID tag</title>
<style>
body {background-color:#0C371D}
h1 {font-family:"Lucida Console";
text-decoration:underline;}
div {text-align:center;
border:10px;
margin-right:40%;
margin-left:40%;
margin-top:5%;
width:300px;
background-color:white;
font-family:"Courier";}
a {color:#00703C;}
open {color:#00CC00;}
closed {color:#CC0000;}
</style>
</head>
<body>
<div>
<br>
<h1>Find RFID tag</h1>
<form action="card.php" method="get"><p>
Card ID<br>(lower left corner)<br>
<input type="number" name="n" min="0" max="4294967295" step="1" value="<?=$_GET["n"]?>">
<input type="submit"><br>
<input type="checkbox" name="magic" <?php if (isset($_GET["magic"])){echo checked;} ?>>Show me the magic
</p></form>
<p><?php
if (isset($_GET["n"])){
$b = sprintf('%032b',(int)$_GET["n"]);
$bflip = strrev(substr($b,0,8)).strrev(substr($b,8,8)).strrev(substr($b,16,8)).strrev(substr($b,24,8));
if (isset($_GET["magic"])){
echo 'Get number as int32<br>';
echo (int)$_GET["n"];
echo '<br>Convert to binary<br>';
echo substr($b,0,8).' '.substr($b,8,8).' '.substr($b,16,8).' '.substr($b,24,8);
echo '<br>Reverse every 8-bit word<br>';
echo substr($bflip,0,8).' '.substr($bflip,8,8).' '.substr($bflip,16,8).' '.substr($bflip,24,8);
echo '<br>Convert back to int32<br>';
echo bindec($bflip);
}else{
echo 'Your RFID tag is<br>';
echo bindec($bflip);
}
}
?></p>
<p>Protip:<br> Also works in reverse!</p>
<p>
<a href="http://deltahouse.no">Deltahouse.no</a>
<a href="index.php">EpsilonPi</a>
</p>
<br>
</div>
</body>
</html>
<file_sep>##Changelog
###0.1.0
- Initial release with basic functionality
###0.1.1
- Fix typo in installation description
###0.1.2
- Fix [flotcharts.org](http://flotcharts.org) link
###0.2.0
- Add Pushover support
- Add configuration for [PiTemp Server](https://github.com/fechu/PiTemp-Server.git)
###0.3.0
- Fix many Typos. ([Litschi](https://github.com/Litschi))
- Add [Pushbullet](https://www.pushbullet.com) support ([elpatron68](https://github.com/elpatron68))
- Add configuration for adding Hostname and IP address to notifications. (Thanks to [elpatron68](https://github.com/elpatron68) for the idea)
###0.3.0
- Add Contributor section to README
- Add awesome logo (Thanks to [Litschi](https://github.com/Litschi))
|
e63dca6410e8d8f8cd65f84b686a7604f28281a3
|
[
"CMake",
"Markdown",
"Makefile",
"PHP",
"C++",
"Shell"
] | 19
|
C++
|
vehagn/DeltaPi
|
5a405bd96b8a0c883b688626f90bbfe93c1244f9
|
8303984fb8ddeec435c16c0a2ba961c1ddd9c709
|
refs/heads/main
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleVersion.Helpers;
namespace ConsoleVersion
{
class FactoryInit
{
public static IBenchmarkTimer BenchmarkTimer
{
get
{
return new BenchmarkStopWatch();
}
}
public static IKeyGenerator SecureKey
{
get
{
return new KeyGenerator();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion.Helpers
{
/// <summary>
/// Key generator.
/// Can be used in order to get truly random values.
/// </summary>
class KeyGenerator : IKeyGenerator
{
public byte[] GenerateKey(int keySize)
{
// Uses RNGCryptoServiceProvider instead of fx. Random, to create more random and secure values.
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[keySize];
randomNumberGenerator.GetBytes(randomNumber);
return randomNumber;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion
{
class TripleDESEncrypter : IEncryption
{
public string Name => "TripleDES";
public byte[] Encrypt(byte[] dataToEncrypt, byte[] key, byte[] iv)
{
using (var cipher = new TripleDESCryptoServiceProvider())
{
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;
cipher.Key = key;
cipher.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, cipher.CreateEncryptor(),
CryptoStreamMode.Write);
cryptoStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
public byte[] Decrypt(byte[] dataToDecrypt, byte[] key, byte[] iv)
{
using (var cipher = new TripleDESCryptoServiceProvider())
{
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;
cipher.Key = key;
cipher.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, cipher.CreateDecryptor(),
CryptoStreamMode.Write);
cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);
cryptoStream.FlushFinalBlock();
var decryptBytes = memoryStream.ToArray();
return decryptBytes;
}
}
}
}
}
<file_sep># H4_SymmetricEncryption
H4 - Symmetrisk Kryptering
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion
{
class Program
{
static void Main(string[] args)
{
IBenchmarkTimer timer = FactoryInit.BenchmarkTimer;
string menuSelection = string.Empty;
int keySize = 0;
int IVSize = 0;
do
{
Console.Clear();
Console.Write("Input to encrypt: ");
string plaintTextInput = Console.ReadLine();
Console.WriteLine("Hashing menu:");
Console.WriteLine("1. DES");
Console.WriteLine("2. Triple DES");
Console.WriteLine("3. AES");
IEncryption encrypter = null;
byte[] encryptedValue = null;
menuSelection = Console.ReadLine();
switch (menuSelection)
{
case "1":
// Different keysizes are available to diffrent Encryption methods.
keySize = 8;
IVSize = 8;
encrypter = new DESEncrypter();
break;
case "2":
keySize = 24;
IVSize = 8;
encrypter = new TripleDESEncrypter();
break;
case "3":
keySize = 32;
IVSize = 16;
encrypter = new AESEncrypter();
break;
default:
break;
}
byte[] generatedKey = FactoryInit.SecureKey.GenerateKey(keySize);
byte[] generatedIV = FactoryInit.SecureKey.GenerateKey(IVSize);
Console.WriteLine("Generated Key : " + Convert.ToBase64String(generatedKey));
Console.WriteLine("Generated IV : " + Convert.ToBase64String(generatedIV));
Console.WriteLine();
timer.Start();
encryptedValue = encrypter.Encrypt(Encoding.UTF8.GetBytes(plaintTextInput), generatedKey, generatedIV);
timer.Stop();
Console.Write($"{encrypter.Name} encryption: ");
Console.Write(Convert.ToBase64String(encryptedValue));
Console.WriteLine();
Console.Write($"Benchmark: " + timer.TimingResult());
timer.Reset();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to Decrypt:");
Console.ReadKey();
Console.WriteLine("Encrypted Value : " + Convert.ToBase64String(encryptedValue));
timer.Start();
Console.WriteLine("Decrypted Value : " + Encoding.UTF8.GetString(encrypter.Decrypt(encryptedValue, generatedKey, generatedIV)));
timer.Stop();
Console.WriteLine($"Benchmark : " + timer.TimingResult());
timer.Reset();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to try again...");
Console.ReadKey();
} while (true);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion.Helpers
{
interface IKeyGenerator
{
byte[] GenerateKey(int keySize);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion
{
interface IEncryption
{
string Name { get; }
byte[] Decrypt(byte[] dataToDecrypt, byte[] key, byte[] iv);
byte[] Encrypt(byte[] dataToEncrypt, byte[] key, byte[] iv);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleVersion
{
class AESEncrypter : IEncryption
{
private string name = "AES";
public string Name { get { return this.name; } }
public byte[] Encrypt(byte[] dataToEncrypt, byte[] key, byte[] iv)
{
using (var cipher = new AesCryptoServiceProvider())
{
cipher.Mode = CipherMode.CBC; //Chose the Cipher MODE. Sat to CBC Cipher Block Chaining - to avoid possible dublicate values in the same encryption.
cipher.Padding = PaddingMode.PKCS7; // Choose paddingmode - Sat, as standard, to PKCS7
cipher.Key = key;
cipher.IV = iv; // AES has to have an IV with a bit lenght of 16.
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, cipher.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
cryptoStream.FlushFinalBlock(); // Flushing to clear variables from memory.
return memoryStream.ToArray();
}
}
}
public byte[] Decrypt(byte[] dataToDecrypt, byte[] key, byte[] iv)
{
using (var cipher = new AesCryptoServiceProvider())
{
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;
cipher.Key = key;
cipher.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, cipher.CreateDecryptor(),
CryptoStreamMode.Write);
cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);
cryptoStream.FlushFinalBlock();
var decryptBytes = memoryStream.ToArray();
return decryptBytes;
}
}
}
}
}
|
783ea8e047435e412f0ea618bf900265b607a8ad
|
[
"Markdown",
"C#"
] | 8
|
C#
|
bentikki/H4_SymmetricEncryption
|
7b5d761807a7cdd1f9973a81d78f9ebf884b6466
|
bdaf5c306e2f9611fea28344a9d7ad83bd7ae33d
|
refs/heads/master
|
<repo_name>atal80/SeleniunPageObjectsModelAssignment<file_sep>/src/main/java/Pages/BooksByLanguage.java
package Pages;
import org.openqa.selenium.WebElement;
public class BooksByLanguage extends BasePage {
public static String ENGLISH_ONLY_HEADER = "//h1[text()='English Only']";
public WebElement englishOnlyPageHeaderExist() {
return findElementByXpath(ENGLISH_ONLY_HEADER);
}
}
<file_sep>/src/test/java/TeamCityFinalAssignmentTest.java
import Consts.Consts;
import Pages.*;
import Utils.ShareDriver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.junit.jupiter.api.Assertions.*;
public class TeamCityFinalAssignmentTest {
private static WebDriver webDriver;
private static MainPage mainPage;
private static WebDriverWait wait;
@BeforeAll
public static void BeforeAllSetup() {
mainPage = new MainPage();
webDriver = ShareDriver.getWebDriver();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
}
@BeforeEach
public void beforeAllSetup() {
webDriver.get(Consts.MAIN_PAGE_URL);
wait = new WebDriverWait(webDriver, 5);
}
@AfterAll
public static void afterAllSetup() {
ShareDriver.closeDriver();
webDriver = null;
}
//Add books to cart test
@Test
public void AddBooksToCart() {
// English books
AllLanguages englishLanguage = mainPage.allLanguagesEnglish();
WebElement allLanguagesEnglishHeader = englishLanguage.allLanguagesEnglishHeaderExist();
assertNotNull(allLanguagesEnglishHeader);
WebElement englishBook = englishLanguage.findEnglishBook();
englishBook.click();
WebElement englishBookAddToCart = englishLanguage.addBookToCart();
englishBookAddToCart.click();
// Russian books
AllLanguages russianLanguage = mainPage.allLanguagesRussian();
WebElement allLanguagesRussianHeader = russianLanguage.allLanguagesRussianHeaderExist();
assertNotNull(allLanguagesRussianHeader);
WebElement russianBook = russianLanguage.findRussianBook();
russianBook.click();
WebElement russianBookAddToCart = russianLanguage.addBookToCart();
russianBookAddToCart.click();
//Cart test
CartPage cartPage = mainPage.cartPage();
WebElement englishBookInCartExist = cartPage.englishBookCartTest();
WebElement russianBookInCartExist = cartPage.russianBookCartTest();
WebElement booksPageLogo = cartPage.continueShoppingButton();
assertNotNull(booksPageLogo);
}
}
<file_sep>/src/test/java/TestPages.java
import Consts.Consts;
import Pages.*;
import Utils.ShareDriver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.junit.jupiter.api.Assertions.*;
public class TestPages {
public static final Logger logger = LogManager.getLogger(TestPages.class);
private static WebDriver webDriver;
private static MainPage mainPage;
private static WebDriverWait wait;
@BeforeAll
public static void BeforeAllSetup() {
mainPage = new MainPage();
webDriver = ShareDriver.getWebDriver();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
}
@BeforeEach
public void beforeAllSetup() {
webDriver.get(Consts.MAIN_PAGE_URL);
wait = new WebDriverWait(webDriver, 5);
}
@AfterAll
public static void afterAllSetup() {
ShareDriver.closeDriver();
webDriver = null;
}
// Home PAge Logo Test
@Test
public void HomePageTest() {
logger.info("Home page load test");
WebElement mainPagelogoExists = mainPage.mainPage();
mainPage.takeScreensShot("HomePageTest");
assertNotNull(mainPagelogoExists);
}
// Contact Us Menu Test
@Test
public void ContactUsPageTest() {
logger.info("Contact us load page test");
ContactUsPage contactUsPage = mainPage.contactUsPage();
WebElement contactUsPageHeader = contactUsPage.contactUsPageNameHeaderExist();
assertNotNull(contactUsPageHeader);
WebElement contactUsPageEmailField = contactUsPage.sendText();
assertNotNull(contactUsPageEmailField);
WebElement errorMessage = contactUsPage.contactUsErrorMessage();
assertNotNull(errorMessage);
}
//FAQs Menu Test
@Test
public void FaqsTest() {
logger.info("FAQs load page test");
FAQsPage faQsPage = mainPage.faqsPage();
WebElement faqsPageHeader = faQsPage.faqsNamePageHeaderExist();
assertNotNull(faqsPageHeader);
}
// Books By Language Menu Test
@Test
public void BooksByLanguageTest() {
logger.info("Books by language drop list test");
BooksByLanguage booksByLanguage = mainPage.booksByLanguage();
WebElement englishOnlyHeader = booksByLanguage.englishOnlyPageHeaderExist();
assertNotNull(englishOnlyHeader);
}
//eBooks By Language Menu Test
@Test
public void eBooksByLanguageTest() {
logger.info("eBooks by language drop list test");
EBooksByLanguage eBooksByLanguage = mainPage.eBooksByLanguage();
WebElement eBooksInEnglishOnlyHeader = eBooksByLanguage.eBooksInEglishOnlyHeaderExist();
assertNotNull(eBooksInEnglishOnlyHeader);
}
//Resources Menu Test
@Test
public void ResourcesTest() {
logger.info("Resources drop list test");
Resources resources = mainPage.resouces();
WebElement resourcesVideoHeader = resources.resourcesVideoPageHeaderExist();
assertNotNull(resourcesVideoHeader);
}
//All Languages Menu Test Hebrew Language
@Test
public void AllLanguagesTestHebrew() {
logger.info("All languages drop list test");
AllLanguages allLanguages = mainPage.allLanguagesHebrew();
WebElement allLanguagesHebrewHeader = allLanguages.allLanguagesHebrewHeaderExist();
assertNotNull(allLanguagesHebrewHeader);
}
// Blog Page Test
@Test
public void BlogPageTest() {
logger.info("Blog load page test");
BlogPage blogPage = mainPage.blogPage();
WebElement blogHeader = blogPage.blogPageNameHeaderExist();
assertNotNull(blogHeader);
// WebElement holiday = blogPage.holidayDropListExist();
// assertNotNull(holiday);
}
// LogIn Page Test
// @Test
// public void LogInTest() {
// logger.info("LogIn page test");
// LogInPage logInPage = mainPage.logInPage();
// WebElement logInHeader = logInPage.logInHeaderExist();
// assertNotNull(logInHeader);
// WebElement element = logInPage.emailField();
// assertNotNull(element);
// WebElement incorrectEmailOrPassword = logInPage.logInErrorMessage();
// assertNotNull(incorrectEmailOrPassword);
// }
// Create Account Test
@Test
public void CreateAccountTest() throws InterruptedException {
CreateAccount createAccount = mainPage.createAccount();
WebElement firstName = createAccount.firstNameField();
assertNotNull(firstName);
WebElement lastName = createAccount.lastNameField();
assertNotNull(lastName);
WebElement email = createAccount.emailField();
assertNotNull(email);
WebElement password = createAccount.passwordField();
assertNotNull(password);
}
//All Languages Menu Test English Language
@Test
public void AllLanguagesTestEnglish(){
}
// Cart Test
@Test
public void CartTest() {
CartPage cartPage = mainPage.cartPage();
WebElement yourCartHeader = cartPage.yourCartHeaderExist();
assertNotNull(yourCartHeader);
WebElement homePageLogo = cartPage.letsGetReadingButton();
assertNotNull(homePageLogo);
}
}<file_sep>/src/main/java/Pages/FAQsPage.java
package Pages;
import org.openqa.selenium.WebElement;
public class FAQsPage extends BasePage {
public static String FAQS_HEADER = "//h1[text()='FAQ/addition info']";
public WebElement faqsNamePageHeaderExist() {
return findElementByXpath(FAQS_HEADER);
}
}
<file_sep>/src/main/java/Pages/CreateAccount.java
package Pages;
import org.openqa.selenium.WebElement;
public class CreateAccount extends BasePage {
public static String FIRST_NAME_FIELD = "//input[@id='FirstName']";
public static String FIRST_NAME = "Andrey";
public static String LAST_NAME_FIELD = "//input[@id='LastName']";
public static String LAST_NAME = "T";
public static String EMAIL_FIELD = "//input[@id='Email']";
public static String EMAIL = "<EMAIL>";
public static String PASSWORD_FIELD = "//input[@id='CreatePassword']";
public static String PASSWORD = "<PASSWORD>";
public WebElement firstNameField() {
return sendTextToField(FIRST_NAME_FIELD, FIRST_NAME);
}
public WebElement lastNameField() {
return sendTextToField(LAST_NAME_FIELD, LAST_NAME);
}
public WebElement emailField() {
return sendTextToField(EMAIL_FIELD, EMAIL);
}
public WebElement passwordField() {
return sendTextToField(PASSWORD_FIELD, PASSWORD);
}
}
|
07c6a866ac9721a85678b9c3e025414bf88c527a
|
[
"Java"
] | 5
|
Java
|
atal80/SeleniunPageObjectsModelAssignment
|
5606c6c5484e0bf61f2e9c730db8a6bc6d2b8af4
|
ca75f7ac6cb82d36395dbbed4fa02877c8c18201
|
refs/heads/master
|
<repo_name>rocketjump/queued<file_sep>/lib/queued/services/amazon_sqs/message.rb
require 'queued/message'
module Queued
module Services
module AmazonSqs
class Message < Queued::Message
def initialize(queue, id = nil, body = nil, sqs_message = nil)
super(queue, id, body)
if @sqs_message = sqs_message
@id = sqs_message.id
self.body = sqs_message.body
end
end
def send
@queue.send_message(self) unless @sqs_message
end
def delete
@sqs_message.delete if @sqs_message
end
def to_sqs_message
@sqs_message || RightAws::SqsGen2::Message.new(@queue.queue, @id, nil, @body)
end
end
end
end
end
<file_sep>/lib/queued.rb
$:.unshift(File.dirname(__FILE__)) unless
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'core_extensions/extract_options'
require 'queued/message'
require 'queued/queue'
require 'queued/service'
module Queued
VERSION = '0.0.4'
@@service = :amazon_sqs
def self.service=(service)
@@service = service
end
def self.service(options = {})
require "queued/services/#{@@service}"
mod = Queued::Services.const_get(camelize(@@service))
mod.const_get('Service').new(options)
end
private
def self.camelize(string)
string.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }
end
end<file_sep>/lib/queued/services/amazon_sqs/service.rb
require 'queued/service'
begin
require 'right_aws'
rescue LoadError
puts "Please install the RightAws gem to use an AmazonSQS queue."
exit(1)
end
module Queued
module Services
module AmazonSqs
class Service < Queued::Service
def initialize(options = {})
@access_key_id = options[:access_key_id]
@secret_access_key = options[:secret_access_key]
sqs(options)
end
##
# See Queued::Service.queues
#
def queues
sqs_queues = sqs.queues
sqs_queues.collect { |queue| Queued::Services::AmazonSqs::Queue.new(self, queue.name, queue) } if sqs_queues
end
##
# See Queued::Service.queue
#
def queue(queue_name, create = false)
sqs_queue = sqs.queue(queue_name, create)
Queued::Services::AmazonSqs::Queue.new(self, queue_name, sqs_queue) if sqs_queue
end
def sqs_service #:nodoc:
sqs
end
private
def sqs(options = {})
@sqs ||= RightAws::SqsGen2.new(@access_key_id, @secret_access_key, options)
end
end
end
end
end
<file_sep>/lib/queued/queue.rb
module Queued
##
# Basic class for managing queues found on a queueing +Service+. This class
# should be inherited or extended to correctly enable the given
# functionality for each service.
#
class Queue
attr_reader :name
attr_reader :service
def initialize(service, name)
@service = service
@name = name
end
##
# Create a new queue on the given +service+.
#
def self.create(service, name)
raise(NotImplementedError, "You must override the create method for #{self.class.name}")
end
##
# Returns an integer representing the number of visible messages in the
# queue.
#
def size
raise(NotImplementedError, "You must override the size method for #{self.class.name}")
end
##
# Empties the queue of all visible messages, effectively clearing the
# queue.
#
def clear!
raise(NotImplementedError, "You must override the clear! method for #{self.class.name}")
end
##
# Permanently destroys (deletes) the queue from its +Service+.
#
def destroy
raise(NotImplementedError, "You must override the destroy method for #{self.class.name}")
end
##
# Returns the next +Message+ in the queue.
#
def first
raise(NotImplementedError, "You must override the first method for #{self.class.name}")
end
##
# Returns a new message for the queue.
#
def build_message(*args)
raise(NotImplementedError, "You must override the first method for #{self.class.name}")
end
##
# Sends a +message+ to the queue.
def send_message(message)
raise(NotImplementedError, "You must override the first method for #{self.class.name}")
end
end
end
<file_sep>/lib/queued/services/amazon_sqs.rb
require 'queued/services/amazon_sqs/message'
require 'queued/services/amazon_sqs/queue'
require 'queued/services/amazon_sqs/service'
module Queued
module Services
module AmazonSqs
end
end
end
<file_sep>/lib/queued/services/test/message.rb
require 'queued/message'
module Queued
module Services
module Test
class Message < Queued::Message
def send
@queue.send_message(self)
end
def delete
@queue._sent_messages.delete(self)
end
end
end
end
end
<file_sep>/lib/queued/services/test.rb
require 'queued/services/test/message'
require 'queued/services/test/queue'
require 'queued/services/test/service'
module Queued
module Services
module Test
end
end
end
<file_sep>/lib/queued/services/test/queue.rb
require 'queued/queue'
module Queued
module Services
module Test
class Queue < Queued::Queue
##
# Create a new queue on the given +service+.
#
def self.create(service, name)
true
end
##
# Returns an integer representing the number of visible messages in the
# queue.
#
def size
_sent_messages.size
end
##
# Empties the queue of all visible messages, effectively clearing the
# queue.
#
def clear!
_sent_messages.clear
end
##
# Permanently destroys (deletes) the queue from its +Service+.
#
def destroy
@service.queues.delete(@name)
end
##
# Returns the next +Message+ in the queue.
#
def first
_sent_messages.first
end
##
# Returns a new message for the queue.
#
def build_message(*args)
options = args.extract_options!
Queued::Services::Test::Message.new(self, options[:id], options[:body])
end
##
# Sends a +message+ to the queue.
#
def send_message(message)
_sent_messages << message
true
end
def _sent_messages
@messages ||= []
end
end
end
end
end
<file_sep>/lib/queued/service.rb
module Queued
class Service
def queues
raise(NotImplementedError, "You must override the queues method for #{self.class.name}")
end
def queue(queue_name)
raise(NotImplementedError, "You must override the queue() method for #{self.class.name}")
end
end
end
<file_sep>/lib/queued/message.rb
module Queued
##
# Basic class for managing queue messages. This class should be inherited
# from / extended to correctly enable +send+ and +delete+ functionality for
# each service.
#
class Message
attr_reader :id # Unique identifier of the message in the queue.
attr_reader :queue # The queue in which this message belongs.
def initialize(queue, id = nil, body = nil)
@queue = queue
@id = id
self.body = body
end
##
# Sends the message to the +queue+.
#
def send
raise(NotImplementedError, "You must override the send method for #{self.class.name}")
end
##
# Deletes the message from the +queue+.
#
def delete
raise(NotImplementedError, "You must override the delete method for #{self.class.name}")
end
def body=(body_content)
@body = body_content.kind_of?(String) ? body_content : body_content.to_yaml
end
def body
YAML.load(@body)
end
##
# Returns the +body+ of the Message.
#
def to_s
@body
end
end
end
<file_sep>/lib/queued/services/test/service.rb
require 'queued/service'
module Queued
module Services
module Test
class Service < Queued::Service
def initialize(options = {})
@queues = {}
options[:queues].each do |queue|
generate_queue(queue)
end if options[:queues].respond_to?(:each)
end
##
# See Queued::Service.queues
#
def queues
@queues.values
end
##
# See Queued::Service.queue
#
def queue(queue_name, create = false)
generate_queue(queue_name) if create && !@queues.has_key?(queue_name)
@queues[queue_name]
end
private
def generate_queue(name)
@queues[name] = Queued::Services::Test::Queue.new(self, name)
end
end
end
end
end
<file_sep>/lib/queued/services/amazon_sqs/queue.rb
require 'queued/queue'
module Queued
module Services
module AmazonSqs
class Queue < Queued::Queue
attr_reader :queue
def initialize(service, name, queue = nil)
super(service, name)
@queue = queue
end
##
# Create a new queue on the given +service+.
#
def self.create(service, name)
queue = service.queue(name, true)
Queue.new(service, name, queue)
end
##
# Returns an integer representing the number of visible messages in the
# queue.
#
def size
@queue.size
end
##
# Empties the queue of all visible messages, effectively clearing the
# queue.
#
def clear!
@queue.clear
end
##
# Permanently destroyes (deletes) the queue from its +Service+.
#
def destroy
@queue.delete(true) # forced!
end
##
# Returns the next +Message+ in the queue.
#
def first
message = @queue.receive
Queued::Services::AmazonSqs::Message.new(self, nil, nil, message) if message
end
##
# Builds and returns a new +Message+ for the queue.
#
def build_message(*args)
options = args.extract_options!
Queued::Services::AmazonSqs::Message.new(self, options[:id], options[:body])
end
##
# Sends a +message+ to the queue.
#
def send_message(message)
sent_message = @queue.send_message(message.to_sqs_message)
Queued::Services::AmazonSqs::Message.new(self, nil, nil, sent_message)
end
end
end
end
end
|
736a7409fa7af42bc2c9cd5a8210cc66025301d5
|
[
"Ruby"
] | 12
|
Ruby
|
rocketjump/queued
|
9081a3e50fdcf7eab5ff85fc615b8d6bfd2f736a
|
c6f07b8b44e385d9166ac4b5e675446be531c6e5
|
refs/heads/master
|
<file_sep>apply {
from "${rootDir.path}/config_lib.gradle"
plugin "com.android.library"
}
// in config.gradle
configAndroidModuleDomain project
configModuleBaseDependences project
<file_sep>apply {
from "${rootDir.path}/config_app.gradle"
}
configAndroidAppDomain project
configAppBaseDependences project
configLibDependences project
configNdk project<file_sep>package indi.toaok.androiddemo.api.splash;
import android.util.Log;
import java.util.Map;
import indi.toaok.androiddemo.api.vo.request.SplashRequestBean;
import indi.toaok.androiddemo.api.vo.response.SplashResultBean;
import indi.toaok.androiddemo.http.rx.RequestManager;
import indi.toaok.androiddemo.http.rx.RxSchedulers;
import indi.toaok.androiddemo.http.rx.RxSubscriberHelper;
import indi.toaok.androiddemo.http.rx.request.BaseRequestBody;
import io.reactivex.Observable;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public class SplashApi {
interface Api {
@FormUrlEncoded
@POST("/getImages")
Observable<SplashResultBean> getImages(@FieldMap Map<String, Object> params);
}
private Api api;
public SplashApi() {
api = RequestManager.getRequest(Api.class);
}
public void getImages(SplashRequestBean requestBean, final RxSubscriberHelper<SplashResultBean> subscriberHelper) {
api.getImages(new BaseRequestBody(requestBean).toRequestBody())
.compose(RxSchedulers.rxSchedulerHelper())
.compose(RxSchedulers.handleResult())
.subscribe(subscriberHelper);
}
}
<file_sep>package indi.toaok.androiddemo.http.rx.request;
import android.util.Log;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public class BaseRequestBody<T> implements Serializable, IRequestBody {
private T body;
public BaseRequestBody(T body) {
this.body = body;
}
public void setBody(T body) {
this.body = body;
}
@Override
public Map<String, Object> toRequestBody() {
Map<String, Object> params = null;
try {
params = convertToMap(body);
} catch (Exception e) {
e.printStackTrace();
}
Log.i("reuqestInfo", "request-param" + params);
return params;
}
public HashMap<String, Object> convertToMap(Object obj)
throws Exception {
HashMap<String, Object> map = new HashMap<>();
Field[] fields = obj.getClass().getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
String varName = fields[i].getName();
boolean accessFlag = fields[i].isAccessible();
fields[i].setAccessible(true);
Object o = fields[i].get(obj);
if (o != null)
map.put(varName, o.toString());
fields[i].setAccessible(accessFlag);
}
return map;
}
}
<file_sep>package indi.toaok.androiddemo.module.home.view;
import android.widget.TextView;
import androidx.viewpager.widget.PagerAdapter;
import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.base.view.BaseDelegate;
import indi.toaok.androiddemo.common.animation.Animation;
import indi.toaok.androiddemo.module.home.activity.MainActivity;
import indi.toaok.androiddemo.module.home.widget.NoScrollViewPager;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_KLINE;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_MAP;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_OTHER;
/**
* 主页面
*
* @author Toaok
* @version 1.0 2018/9/8.
*/
public class FMainDelegate extends BaseDelegate {
@BindView(R.id.btn_map)
TextView mMap;
@BindView(R.id.btn_kline)
TextView mKLine;
@BindView(R.id.btn_other)
TextView mOther;
@BindView(R.id.ssvp_home)
NoScrollViewPager mViewPager;
//String
@BindString(R.string.home_map)
String strHomeMap;
@BindString(R.string.home_kline)
String strHomeKline;
@BindString(R.string.home_other)
String strHomeOther;
//Color
@BindColor(R.color.colorPrimary)
int colorSelect;
@BindColor(R.color.color_80000000)
int colorUnselect;
@Override
public int getRootLayoutId() {
return R.layout.fragment_main;
}
public void setViewPagerAdapter(PagerAdapter pagerAdapter) {
mViewPager.setAdapter(pagerAdapter);
}
public void setOffscreenPageLimit(int limit) {
mViewPager.setOffscreenPageLimit(limit);
}
public void setTabBackground(@Animation.VPI int pager) {
if (getActivity() != null && getActivity() instanceof MainActivity) {
switch (pager) {
case PAGER_MAP:
mMap.setTextColor(colorSelect);
mKLine.setTextColor(colorUnselect);
mOther.setTextColor(colorUnselect);
mViewPager.setCurrentItem(PAGER_MAP, false);
((MainActivity) getActivity()).setTitle(strHomeMap);
break;
case PAGER_KLINE:
mMap.setTextColor(colorUnselect);
mKLine.setTextColor(colorSelect);
mOther.setTextColor(colorUnselect);
mViewPager.setCurrentItem(PAGER_KLINE, false);
((MainActivity) getActivity()).setTitle(strHomeKline);
break;
case PAGER_OTHER:
mMap.setTextColor(colorUnselect);
mKLine.setTextColor(colorUnselect);
mOther.setTextColor(colorSelect);
mViewPager.setCurrentItem(PAGER_OTHER, false);
((MainActivity) getActivity()).setTitle(strHomeOther);
break;
default:
break;
}
}
}
}
<file_sep>package indi.toaok.androiddemo.module.map.marker;
import android.content.Context;
import java.util.List;
import indi.toaok.androiddemo.module.map.marker.bean.imp.MarkerInfoBean;
import indi.toaok.androiddemo.module.map.marker.convert.PointsMarkerConverter;
import indi.toaok.androiddemo.module.map.marker.widget.imp.PointMarkerView;
/**
* @author Toaok
* @version 1.0 2019/2/13.
*/
public class MarkerConvertFactory {
private PointsMarkerConverter<MarkerInfoBean> pointsMarkerConverter;
private MarkerConvertFactory() {
pointsMarkerConverter = new PointsMarkerConverter<>();
}
public static MarkerConvertFactory create() {
return new MarkerConvertFactory();
}
public List<GDMarkerOptions> points2Converter(List<MarkerInfoBean> values, Context context) {
return pointsMarkerConverter.converts(values, (value, centerPoint) -> {
PointMarkerView pointMarkerView = new PointMarkerView(context);
if (centerPoint == null) {
//下
pointMarkerView.setBottomtName(value.getTitle());
} else {
//do something
if (value.getLatLng() != null) {
if (value.getLatLng().longitude > centerPoint.longitude) {
//右
pointMarkerView.setRightName(value.getTitle());
} else {
//左
pointMarkerView.setLeftName(value.getTitle());
}
}
}
return pointMarkerView;
});
}
public GDMarkerOptions point2Converter(MarkerInfoBean value, Context context) {
return pointsMarkerConverter.convert(value, (value1, centerPoint) -> null);
}
}
<file_sep>package indi.toaok.androiddemo.model.local.db.dao.impl;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import indi.toaok.androiddemo.model.local.db.SQL;
import indi.toaok.androiddemo.model.vo.SplashImageBean;
import java.util.ArrayList;
import java.util.List;
/**
* @author Toaok
* @version 1.0 2018/9/10.
*/
public class SplashImageDao extends BaseDaoImpl<SplashImageBean> {
private static final String TABLE = SQL.SPLASH_TABLE;
private final String IMAGE_ID = SQL.SPLASH_IMAGE_ID;
private final String IMAGE_URL = SQL.SPLASH_IMAGE_URL;
public SplashImageDao(Context context) {
super(context);
}
@Override
public List<SplashImageBean> queryAll() {
db = getReadableDatabase();
List<SplashImageBean> splashImageBeanList = new ArrayList<>();
Cursor cursor = db.query(TABLE, null, null, null, null, null, null);
int idIndex = cursor.getColumnIndex(IMAGE_ID);
int urlIndex = cursor.getColumnIndex(IMAGE_URL);
while (cursor.moveToNext()) {
SplashImageBean splashImageBean = new SplashImageBean();
splashImageBean.setId(cursor.getInt(idIndex));
splashImageBean.setUrl(cursor.getString(urlIndex));
splashImageBeanList.add(splashImageBean);
}
cursor.close();
close();
return splashImageBeanList;
}
@Override
public void save(List<SplashImageBean> list) {
try {
getWritableDatabase().beginTransaction();
preCompileSave(list);
getWritableDatabase().setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
getWritableDatabase().endTransaction();
close();
}
close();
}
private void preCompileSave(List<SplashImageBean> list) {
String sql = "insert into " + TABLE+"(url)" + " values (?);";
SQLiteStatement sqLiteStatement = getReadableDatabase().compileStatement(sql);
for (SplashImageBean bean : list) {
sqLiteStatement.clearBindings();
sqLiteStatement.bindString(1, bean.getUrl());
sqLiteStatement.executeInsert();
}
}
@Override
public long insert(SplashImageBean splashImageBean) {
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(IMAGE_URL, splashImageBean.getUrl());
long result = db.insert(TABLE, null, values);
close();
return result;
}
@Override
public long delete(SplashImageBean splashImageBean) {
db = getReadableDatabase();
long result = db.delete(TABLE, IMAGE_ID + "=?", new String[]{splashImageBean.getId() + ""});
close();
return result;
}
@Override
public long update(SplashImageBean splashImageBean) {
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(IMAGE_URL, splashImageBean.getUrl());
long result = db.update(TABLE, values, IMAGE_ID + "=?", new String[]{splashImageBean.getId() + ""});
close();
return result;
}
@Override
public SplashImageBean query(int id) {
db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE +
" WHERE " + IMAGE_ID + "=?",
new String[]{id+""});
SplashImageBean splashImageBean = new SplashImageBean();
int idIndex = cursor.getColumnIndex(IMAGE_ID);
int urlIndex = cursor.getColumnIndex(IMAGE_URL);
if (cursor.moveToNext()) {
splashImageBean.setId(cursor.getInt(idIndex));
splashImageBean.setUrl(cursor.getString(urlIndex));
}
cursor.close();
close();
return splashImageBean;
}
/**
* 随机查询一条记录
* @return
*/
public SplashImageBean randomQueryOne() {
List<SplashImageBean> splashImageBeanList = randomQuery(1);
if (splashImageBeanList != null && splashImageBeanList.size() > 0) {
return randomQuery(1).get(0);
} else {
return null;
}
}
/**
* 随机查询
* @param count 查询个数
*/
public List<SplashImageBean> randomQuery(int count) {
String limit = count <= 0 ? "1" : count + "";
String sql = "SELECT *" +
" FROM " + TABLE + "" +
" ORDER BY RANDOM()" +
" LIMIT ?;";
List<SplashImageBean> splashImageBeanList = new ArrayList<>();
db = getReadableDatabase();
Cursor cursor = db.rawQuery(sql, new String[]{limit});
int idIndex = cursor.getColumnIndex(IMAGE_ID);
int urlIndex = cursor.getColumnIndex(IMAGE_URL);
while (cursor.moveToNext()) {
SplashImageBean splashImageBean = new SplashImageBean();
splashImageBean.setId(cursor.getInt(idIndex));
splashImageBean.setUrl(cursor.getString(urlIndex));
splashImageBeanList.add(splashImageBean);
}
return splashImageBeanList;
}
}
<file_sep>#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
char *_encrypt(char * str) ;
char *_encrypt_key(char * key, char * str) ;
char *_decrypt(char * str) ;
char *_decrypt_key(char * key, char * str) ;
#ifdef __cplusplus
}
#endif
<file_sep>package indi.toaok.encrypt.security.crypt;
import android.text.TextUtils;
import java.security.GeneralSecurityException;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class AESCrypt extends AESCryptBase {
private AESCrypt() {
super();
}
public static String encryptStr(String salt, String content) {
if (TextUtils.isEmpty(content) || TextUtils.isEmpty(salt)) {
return "";
}
try {
return encrypt(salt, content);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return "";
}
public static String decryptStr(String salt, String content) {
if (TextUtils.isEmpty(content) || TextUtils.isEmpty(salt)) {
return "";
}
try {
return decrypt(salt, content);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
<file_sep>package indi.toaok.encrypt;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.runner.AndroidJUnit4;
import indi.toaok.ndk.Security;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
String key="abcd";
String str = "dzcx";
String strEn = null;
String strDe = null;
try {
strEn = Security.encryptWithKey(key,str);
strDe = Security.decryptWithKey(key,strEn);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("加密前:" + str);
System.out.println("加密后:" + strEn);
System.out.println("解密后:" + strDe);
}
}
<file_sep>package indi.toaok.androiddemo.base.view;
import androidx.annotation.StringRes;
import butterknife.ButterKnife;
import indi.toaok.themvp.view.AppDelegate;
/**
* 基准BaseDelegate 所有在该项目中使用TheMVP框架的BaseDelegate都必须继承该抽象类
*
* @author Toaok
* @version 1.0 2018/9/26.
*/
public abstract class BaseDelegate extends AppDelegate {
@Override
public void initView() {
ButterKnife.bind(this,getRootView());
super.initView();
}
protected String getString(@StringRes int resId){
if(getActivity()==null){
return "";
}
return getActivity().getString(resId);
}
protected String getString(@StringRes int resId,Object ...formatArgs){
if(getActivity()==null){
return "";
}
return getActivity().getString(resId,formatArgs);
}
}
<file_sep>package indi.toaok.androiddemo.model.local.db.dao;
import java.util.List;
/**
* @author Toaok
* @version 1.0 2018/9/10.
*/
public interface ExtendDao<T> extends BaseDao<T> {
//查询所有
List<T> queryAll();
//插入多条数据
void save(List<T> list);
}
<file_sep>package indi.toaok.androiddemo.module.map.databinder;
import indi.toaok.androiddemo.base.databinder.BaseDataBinder;
import indi.toaok.androiddemo.module.map.bean.MapBean;
import indi.toaok.androiddemo.module.map.view.MapDelegate;
/**
* @author Toaok
* @version 1.0 2018/11/7.
*/
public class MapDataBinder extends BaseDataBinder<MapDelegate,MapBean> {
@Override
public void viewBindModel(MapDelegate viewDelegate, MapBean data) {
super.viewBindModel(viewDelegate, data);
}
}
<file_sep>package indi.toaok.androiddemo.model.local.db;
/**
* @author Toaok
* @version 1.0 2018/9/10.
*/
public class SQL {
/**
* 表t_splash_image
* 缓存启动页图片url
*/
public static final String SPLASH_TABLE = "t_splash_image";
public static final String SPLASH_IMAGE_ID = "id";
public static final String SPLASH_IMAGE_URL = "url";
/**
* 创建表t_splash_image
* SPLASH_IMAGE_ID
* SPLASH_IMAGE_URL
*/
public static final String CREATE_SPLASH_TABLE = "CREATE TABLE " + SPLASH_TABLE + " ( \n" +
" " + SPLASH_IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT\n" +
" NOT NULL\n" +
" UNIQUE,\n" +
" " + SPLASH_IMAGE_URL + " VARCHAR( 255 ) NOT NULL\n" +
" UNIQUE \n" +
");\n";
}
<file_sep>#include <jni.h>
#include <string.h>
#include <android/log.h>
#define LOG_TAG "Security-native"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
char *_JString2CStr(JNIEnv *env, jstring jstr)
{
char *rtn = NULL;
jclass clsstring = (*env)->FindClass(env, "java/lang/String");
jstring strencode = (*env)->NewStringUTF(env, "GB2312");
jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr = (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode);
jsize alen = (*env)->GetArrayLength(env, barr);
jbyte *ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);
if (alen > 0)
{
rtn = (char *)malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}
(*env)->ReleaseByteArrayElements(env, barr, ba, 0);
return rtn;
}
char *str_combine(const char *str1, const char *str2)
{
char *result;
result = (char *)malloc(strlen(str1) + strlen(str2) + 1); //str1的长度 + str2的长度 + \0;
if (!result)
{
printf("Error: malloc failed in concat! \n");
}
strcpy(result, str1);
strcat(result, str2);
return result;
}
#ifdef __cplusplus
}
#endif<file_sep>package indi.toaok.encrypt.uitl;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class JSONParserHelper {
public static HashMap<String, String> jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
return map;
}
public static String mapToJson(HashMap map) throws JSONException {
JSONObject jObject = new JSONObject();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
jObject.put((String) key, val);
}
return jObject.toString();
}
}
<file_sep>apply {
from "${rootDir.path}/config_lib.gradle"
plugin "com.android.library"
}
//in config.gradle
configAndroidModuleDomain project
configModuleBaseDependences project
dependencies {
implementation fileTree(include: '*.jar', dir: 'libs')
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
// Optional, if you use support library fragments:
debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'
}
<file_sep>
## 在工程中应用submodule
### project/settings.gradle 声明子模块
```groovy
include ':librarys:Leaks'
project(':Leaks').projectDir = new File('librarys/Leaks')
```
### 主工程app/build.gradle 注册子模块
```groovy
debugImplementation project(':librarys:Leaks')
```
## debug build type
### 主工程app/build.gradle 声明buildtype的工程入口
```groovy
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
// 声明debug的变种
debug.setRoot('src/debug')
}
```
### 重写debug buildtype的相关代码
#### 重写debug buildtype的AndroidManifest
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.visionet.cx_ckd">
<application
android:name="com.visionet.dzcx. DApplication_BT"
android:label="@string/app_name"
tools:replace="android:name,android:label">
</application>
</manifest>
```
#### 重写debug buildtype的Application
```java
public class DApplication_BT extends DApplication {
@Override
public void onCreate() {
super.onCreate();
init();
}
private void init() {
Leaks.init(getAppContext());
}
}
```
## 示例
```java
Leaks.init(getAppContext());
```
# chrome 中调起
1.运行app
2.浏览器输入
chrome://inspect/#devices
3.inspect<file_sep>package indi.toaok.androiddemo.model.vo;
import indi.toaok.androiddemo.BuildConfig;
import indi.toaok.utils.core.AppUtils;
import lombok.Data;
/**
* APP 基本信息
*
* @author Toaok
* @version 1.0 2018/9/8.
*/
@Data
public class AppInfo {
public AppInfo() {
applicationId = BuildConfig.APPLICATION_ID;
buildType = BuildConfig.BUILD_TYPE;
environment = BuildConfig.API_HOST;
channel = BuildConfig.FLAVOR;
versionName = AppUtils.getAppVersionName();
versionCode = AppUtils.getAppVersionCode();
}
/**
* applicationId
*/
private String applicationId;
/*
* 开发环境
* */
private String environment;
/**
* 打包方式
*/
private String buildType;
/*
*打包渠道
* */
private String channel;
/*
* versionName
* 版本名
* */
private String versionName;
/**
* versionCode
* 版本号
*/
private int versionCode;
}
<file_sep>package indi.toaok.androiddemo.base.model;
import indi.toaok.themvp.model.IModel;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public interface IBaseModel extends IModel {
String getMessage();
void setMessage(String message);
}
<file_sep>#include <jni.h>
#ifndef _Included_indi_toaok_ndk_Security
#define _Included_indi_toaok_ndk_Security
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getSalt(JNIEnv *, jobject, jstring);
JNIEXPORT jboolean JNICALL Java_indi_toaok_ndk_Security_isDz(JNIEnv *, jobject, jstring);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getSign(JNIEnv *, jobject);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getVersion(JNIEnv *, jobject);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_encrypt(JNIEnv *, jobject, jstring);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_decrypt(JNIEnv *, jobject, jstring);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_encryptWithKey(JNIEnv *, jobject, jstring, jstring);
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_decryptWithKey(JNIEnv *, jobject, jstring, jstring);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>
# 该项目作为Android 练习项目
> 通过参考网上其他项目和自己对gradle、Groovy的理解通过配置实现多渠道打包
## 所引用的技术:
1. 整个项目的是以The MVP框架来搭建的,并且为了加深对[The MVP](https://github.com/kymjs/TheMVP)的理解和设计思想自己动手写了一遍
2. 项目中使用Retrofit负责网络调度,OKHttp负责网络请求,RxJava 进行异步事件处理
* [Retrofit](https://github.com/square/retrofit)
* [OkHttp](https://github.com/square/okhttp)
* [RxJava](https://github.com/ReactiveX/RxJava)
3. 为了使项目更完善,项目中引用了[AndroidUtilCode](https://github.com/Blankj/AndroidUtilCode)库中的很多工具类
4. 封装网络图片的加载框架
* [默认glide](https://github.com/bumptech/glide)
5.
...
6.
...<file_sep>package indi.toaok.androiddemo.model.vo;
import com.google.gson.Gson;
import lombok.Data;
/**
* @author Toaok
* @version 1.0 2018/9/10.
*/
@Data
public class SplashImageBean {
private int id;
private String url;
public String toJson() {
return new Gson().toJson(this);
}
public static SplashImageBean fromJson(String json) {
return new Gson().fromJson(json, SplashImageBean.class);
}
}
<file_sep>#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
char* base64_encode(const char* data, int data_len);
char *base64_decode(const char* data, int data_len);
#ifdef __cplusplus
}
#endif
<file_sep>apply {
from "${rootDir.path}/config_lib.gradle"
plugin "com.android.library"
}
configAndroidModuleDomain project
configModuleBaseDependences project<file_sep>package indi.toaok.androiddemo.module.home.view;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.drawerlayout.widget.DrawerLayout;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import com.google.android.material.navigation.NavigationView;
import butterknife.BindDrawable;
import butterknife.BindView;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.base.view.BaseToolbarDelegate;
import indi.toaok.utils.core.BarUtils;
/**
* @author Toaok
* @version 1.0 2018/10/18.
*/
public class AMainDelegate extends BaseToolbarDelegate {
//View
@BindView(R.id.drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view)
NavigationView navigationView;
//Drable
@BindDrawable(R.drawable.ic_menu_white)
Drawable drawableMenuWhite;
@BindDrawable(R.drawable.ic_more_vert_white)
Drawable drawableMoreVertWhite;
@Override
public int getRootLayoutId() {
return R.layout.activity_main;
}
@Override
public void initView() {
super.initView();
initDrawerLayout();
initToolbarView();
}
protected void initToolbarView() {
setLeftIcon(drawableMenuWhite);
setRightIcon(drawableMoreVertWhite);
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
public NavigationView getNavigationView() {
return navigationView;
}
/**
* 在这里初始化Drawerlayout时会影响ToobarLeftIcon的显示
*/
private void initDrawerLayout() {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(getActivity(),
mDrawerLayout,
getToolbar(),
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
initDrawerBar();
}
private void initDrawerBar() {
View fakeStatusBar = get(R.id.fake_status_bar);
BarUtils.setStatusBarAlpha4Drawer(getActivity(), mDrawerLayout, fakeStatusBar, 0, false);
BarUtils.addMarginTopEqualStatusBarHeight(getToolbar());
}
public void setMenuItemSelectListener(OnMenuItemSelectListener listener) {
navigationView.setNavigationItemSelectedListener(item -> {
boolean isSuccess = listener.onMenuItemSelect(item);
mDrawerLayout.post(() -> mDrawerLayout.closeDrawer(Gravity.LEFT, false));
return isSuccess;
});
}
public interface OnMenuItemSelectListener {
boolean onMenuItemSelect(@NonNull MenuItem item);
}
}
<file_sep>package indi.toaok.androiddemo.module.base.view;
import android.graphics.drawable.Drawable;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import butterknife.BindDrawable;
import butterknife.BindView;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.base.view.BaseDelegate;
/**
* 带有toolbar的View
*
* @author Toaok
* @version 1.0 2018/9/26.
*/
public class BaseToolbarDelegate extends BaseDelegate {
//View
@BindView(R.id.text_title)
TextView titleTextView;
@BindView(R.id.text_right)
TextView rightTextView;
@BindView(R.id.btn_right)
ImageButton rightImagButton;
@BindView(R.id.toolbar)
Toolbar toolbar;
//Drable
@BindDrawable(R.drawable.ic_arrow_back_white)
Drawable drawableBackWhite;
private OnClickToolBarListener mToolBarListener;
@Override
public int getRootLayoutId() {
return R.layout.activity_fragment;
}
@Override
public Toolbar getToolbar() {
return toolbar;
}
@Override
public void initView() {
super.initView();
initToolbarView();
initToolbarEvent();
}
private void initToolbarView() {
toolbar.setNavigationIcon(drawableBackWhite);
}
public void setToolBarListener(OnClickToolBarListener toolBarListener) {
mToolBarListener = toolBarListener;
}
public interface OnClickToolBarListener {
void onClickLeftButton();
void onClickRightButton();
void onClickRightText();
}
/**
* 初始化toolbar事件
*/
private void initToolbarEvent() {
toolbar.setNavigationOnClickListener(v -> mToolBarListener.onClickLeftButton());
rightTextView.setOnClickListener(v -> mToolBarListener.onClickRightText());
rightImagButton.setOnClickListener(v -> mToolBarListener.onClickRightButton());
}
public void setLeftIcon(@DrawableRes int resId) {
toolbar.setNavigationIcon(resId);
}
public void setLeftIcon(@Nullable Drawable icon) {
toolbar.setNavigationIcon(icon);
}
public void setTitle(CharSequence title) {
titleTextView.setVisibility(View.VISIBLE);
titleTextView.setText(title);
}
public void setRightText(CharSequence rightText) {
rightTextView.setVisibility(View.VISIBLE);
rightTextView.setText(rightText);
}
public void setRightIcon(@DrawableRes int resId) {
rightImagButton.setVisibility(View.VISIBLE);
rightImagButton.setImageResource(resId);
}
public void setRightIcon(@Nullable Drawable icon) {
rightImagButton.setVisibility(View.VISIBLE);
rightImagButton.setImageDrawable(icon);
}
}
<file_sep>package indi.toaok.androiddemo.module.home.bean;
import android.graphics.Bitmap;
import indi.toaok.androiddemo.base.model.IBaseModel;
import lombok.Data;
/**
* @author Toaok
* @version 1.0 2018/9/8.
*/
@Data
public class SplashBean implements IBaseModel {
private Bitmap image;
private String url;
private String countDownTimer;
private boolean isHaveAd = false;
private String message;
public void setSplashBean(SplashBean splashBean) {
this.url = splashBean.url;
this.image = splashBean.image;
this.countDownTimer = splashBean.countDownTimer;
this.isHaveAd = splashBean.isHaveAd;
}
}
<file_sep>package indi.toaok.androiddemo.module.map.marker;
import com.amap.api.maps.model.MarkerOptions;
/**
* @author Toaok
* @version 1.0 2019/2/14.
*/
public class GDMarkerOptions<T> {
private MarkerOptions markerOptions;
private float rotateAngle;
private T object;
public MarkerOptions getMarkerOptions() {
return markerOptions;
}
public void setMarkerOptions(MarkerOptions markerOptions) {
this.markerOptions = markerOptions;
}
public float getRotateAngle() {
return rotateAngle;
}
public void setRotateAngle(float rotateAngle) {
this.rotateAngle = rotateAngle;
}
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
}
}
<file_sep>package indi.toaok.androiddemo.view;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.home.view.SplashDelegate;
/**
* @author Toaok
* @version 1.0 2018/9/8.
*/
public class SplashDelegate_BT extends SplashDelegate {
private TextView mEnvironment;
private TextView mChannel;
private TextView mVersion;
private TextView mApplicationId;
private TextView mBuildType;
@Override
public void initView() {
super.initView();
View view= LayoutInflater.from(getActivity()).inflate(R.layout.activity_splash_bt,getFrameLayout());
mEnvironment = view.findViewById(R.id.tv_env);
mChannel = view.findViewById(R.id.tv_channel);
mVersion = view.findViewById(R.id.tv_version);
mApplicationId = view.findViewById(R.id.tv_application_id);
mBuildType = view.findViewById(R.id.tv_buildtype);
}
public void setEnvironment(CharSequence environment) {
mEnvironment.setText(mEnvironment.getText().toString()+environment);
}
public void setChannel(CharSequence channel) {
mChannel.setText(mChannel.getText().toString()+channel);
}
public void setVersion(CharSequence version) {
mVersion.setText(mVersion.getText().toString()+version);
}
public void setApplicationId(CharSequence applicationId) {
mApplicationId.setText(mApplicationId.getText().toString() + applicationId);
}
public void setBuildType(CharSequence buildType) {
mBuildType.setText(mBuildType.getText().toString() + buildType);
}
}
<file_sep>package indi.toaok.androiddemo.http.exception;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public class ServerException extends RuntimeException{
public int code;
public String message;
public Object object;
public ServerException(int code, String message) {
this(code, message, null);
}
public ServerException(int code, String message, Object object) {
this.code = code;
this.message = message;
this.object = object;
}
}
<file_sep>package indi.toaok.androiddemo.databind;
import indi.toaok.androiddemo.model.vo.AppInfo;
import indi.toaok.androiddemo.module.home.bean.SplashBean;
import indi.toaok.androiddemo.module.home.databinder.SplashDataBinder;
import indi.toaok.androiddemo.module.home.view.SplashDelegate;
import indi.toaok.androiddemo.view.SplashDelegate_BT;
import indi.toaok.androiddemo.vo.SplashBean_BT;
/**
* 数据绑定
*
* @author Toaok
* @version 1.0 2018/9/8.
*/
public class SplashDataBinder_BT extends SplashDataBinder<SplashDelegate, SplashBean> {
@Override
public void viewBindModel(SplashDelegate viewDelegate, SplashBean data) {
super.viewBindModel(viewDelegate, data);
if ((data instanceof SplashBean_BT)&&(viewDelegate instanceof SplashDelegate_BT) ){
SplashBean_BT splashBean_bt=(SplashBean_BT)data;
SplashDelegate_BT splashDelegate_bt= (SplashDelegate_BT) viewDelegate;
AppInfo appInfo=splashBean_bt.getAppInfo();
if (!splashBean_bt.isAppinfoDisplay()) {
if (!splashBean_bt.isAppinfoDisplay()) {
splashDelegate_bt.setEnvironment(appInfo.getEnvironment());
splashDelegate_bt.setChannel(appInfo.getChannel());
splashDelegate_bt.setVersion(appInfo.getVersionName());
splashDelegate_bt.setApplicationId(appInfo.getApplicationId());
splashDelegate_bt.setBuildType(appInfo.getBuildType());
}
}
splashBean_bt.setAppinfoDisplay(true);
}
}
}
<file_sep>package indi.toaok.androiddemo.module.other.bean;
import lombok.Data;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
@Data
public class OtherItemBean {
String text;
}
<file_sep> **********************************************************************************************
1.Unable to find a matching configuration of project :Themvp:
- Configuration 'debugApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'debug'.
- Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required efault 'androidDemo' but no value provided.
- Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
- Configuration 'debugRuntimeElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'debug'.
- Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required efault 'androidDemo' but no value provided.
- Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
- Configuration 'releaseApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required efault 'androidDemo' but no value provided.
- Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
- Configuration 'releaseRuntimeElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'dev' and found incompatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required efault 'androidDemo' but no value provided.
- Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
**********************************************************************************************
2. Unable to resolve dependency for ':app@androidDemoDev/compileClasspath': Could not resolve project :Themvp.
Open File
Show Details
**********************************************************************************************
原因:android studio 3.0以后出现的,老版本没有该问题,出现以上两种问题是由于依赖库和被依赖库中拥有不同元素的buildTypes
解决方案:被依赖的模块的buildTypes种类必须是依赖模块的超集<file_sep>package indi.toaok.androiddemo.module.map.marker.bean.imp;
import com.amap.api.maps.model.LatLng;
import indi.toaok.androiddemo.module.map.marker.bean.MarkerInfo;
/**
* @author Toaok
* @version 1.0 2019/2/14.
*/
public class MarkerInfoBean implements MarkerInfo {
private String title;
private LatLng latLng;
@Override
public LatLng getLatLng() {
return latLng;
}
@Override
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setLatLng(LatLng latLng) {
this.latLng = latLng;
}
}
<file_sep>
## 在工程中应用submodule
### project/settings.gradle 声明子模块
```groovy
include ':librarys:Themvp'
project(':Themvp').projectDir = new File('librarys/Themvp')
```
### 主工程app/build.gradle 注册子模块
```groovy
implementation project(':librarys:Themvp')
```<file_sep>package indi.toaok.androiddemo.module.map.marker.icon;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import indi.toaok.androiddemo.R;
import java.lang.ref.SoftReference;
import indi.toaok.androiddemo.utils.AppUtil;
import indi.toaok.utils.Utils;
/**
* @author Toaok
* @version 1.0 2019/2/13.
*/
public class PointsMarkerIconHelper {
static SoftReference<BitmapDescriptor> pointBitmapDescriptor;
static SoftReference<BitmapDescriptor> pointBitmapDescriptorDefault;
/**
* @param bitmap 自定义图标
* @return
*/
public static BitmapDescriptor getPointBitmapDescriptor(Bitmap bitmap) {
//使用自定义图标
if (pointBitmapDescriptor != null && pointBitmapDescriptor.get() != null) {
return pointBitmapDescriptor.get();
} else if (bitmap != null) {
pointBitmapDescriptor = new SoftReference<>(BitmapDescriptorFactory.fromBitmap(bitmap));
return pointBitmapDescriptor.get();
}
//使用默认图标
if (pointBitmapDescriptorDefault != null && pointBitmapDescriptorDefault.get() != null) {
return pointBitmapDescriptorDefault.get();
} else {
pointBitmapDescriptorDefault = new SoftReference<>(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(AppUtil.getApplication().getApplicationContext().getResources(), R.drawable.shape_oval_solid_0076ee_size_6)));
return pointBitmapDescriptorDefault.get();
}
}
}
<file_sep>package indi.toaok.encrypt.security.except;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class EncryptException extends Exception {
/**
* -2 无法获取签名信息
* -1 签名校验失败
*/
int code;
String detailMessage;
public EncryptException(int code, String msg) {
this.code = code;
this.detailMessage = msg;
}
public String getDetailMessage() {
return detailMessage;
}
}
<file_sep>package indi.toaok.androiddemo.module.map.view;
import com.amap.api.maps.AMap;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.comment.widget.LoadingDialog;
/**
* 路线规划和点的平滑移动
*
* @author Toaok
* @version 1.0 2018/12/20.
*/
public class MapDelegate extends BaseMapDelegate implements AMap.OnMapLoadedListener {
private LoadingDialog.DialogDismissListener mDialogDismissListener;
@Override
protected void init() {
super.init();
mDialogDismissListener=LoadingDialog.createLoadingDialog(getActivity(),null,getString(R.string.loading_wait_a_moment));
aMap.setOnMapLoadedListener(this);
}
@Override
public void onMapLoaded() {
mDialogDismissListener.onDismiss();
}
}
<file_sep>#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
char *_JString2CStr(JNIEnv *env, jstring jstr);
char *str_combine(const char *str1, const char *str2);
#ifdef __cplusplus
}
#endif
<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
apply from: 'version.gradle'
repositories {
google()
jcenter()
}
dependencies {
classpath pluginsDependence.gradle
classpath pluginsDependence.butterknife
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
/**
* 使用了未经检查或不安全的操作。
* 注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
*/
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}<file_sep>package indi.toaok.androiddemo.http.rx;
import android.util.Log;
import indi.toaok.androiddemo.http.exception.ServerException;
import indi.toaok.androiddemo.http.rx.response.IResponse;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public class RxSchedulers {
/**
* @param <T>
* @return
*/
public static <T> ObservableTransformer<T, T> rxSchedulerHelper() {
return observable -> observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
/**
* @param <T>
* @return
*/
public static <T> ObservableTransformer<T, T> handleResult() {
return httpResponseObservable -> httpResponseObservable.flatMap((Function<T, Observable<T>>) response -> {
if (response instanceof IResponse) {
Log.d("reuqestInfo", response.toString());
if (((IResponse) response).isSuccess()) {
return createData(response);
} else {
return Observable.error(new ServerException(((IResponse) response).getCode(), ((IResponse) response).getMessage(), response));
}
}
return createData(response);
});
}
/**
* 生成Observable
*
* @param <T>
* @return
*/
public static <T> Observable<T> createData(final T t) {
return Observable.create(emitter -> {
try {
emitter.onNext(t);
} catch (Exception e) {
emitter.onError(e);
}
});
}
}
<file_sep>package indi.toaok.androiddemo.common.animation;
import android.view.View;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import androidx.annotation.IntDef;
/**
* @author Toaok
* @version 1.0 2019/3/20.
*/
public class Animation {
public static final int PAGER_MAP = 0;
public static final int PAGER_KLINE = 1;
public static final int PAGER_OTHER = 2;
public static final int GONE = View.GONE;
public static final int INVISIBLE = View.INVISIBLE;
public static final int VISIBLE = View.VISIBLE;
/**
* @author Toaok
* @version 1.0 2019/3/20.
*/
@IntDef({VISIBLE, INVISIBLE, GONE})
@Retention(RetentionPolicy.SOURCE)
public @interface Visibility {
}
/**
* view pager index
* 使用注解代替Enum,限定类型
*/
@IntDef({PAGER_MAP, PAGER_KLINE, PAGER_OTHER})
@Retention(RetentionPolicy.SOURCE)
public @interface VPI {
}
}
<file_sep>package indi.toaok.androiddemo.module.home.fragemnt;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import android.view.View;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.home.databinder.MainDataBinder;
import indi.toaok.androiddemo.module.other.fragment.OtherFragment;
import indi.toaok.themvp.databind.DataBinder;
import java.util.ArrayList;
import java.util.List;
import indi.toaok.androiddemo.base.presenter.fragment.BaseFragment;
import indi.toaok.androiddemo.module.home.view.FMainDelegate;
import indi.toaok.androiddemo.module.map.fragment.MapFragment;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_KLINE;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_MAP;
import static indi.toaok.androiddemo.common.animation.Animation.PAGER_OTHER;
/**
* 主界面
*/
public class MainFragment extends BaseFragment<FMainDelegate> implements View.OnClickListener {
private static final String TAG = "indi.toaok.androiddemo.module.home.fragemnt.MainFragment";
public static MainFragment newInstance(String desc) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
bundle.putString(TAG, desc);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData();
}
final List<Fragment> fragmentList = new ArrayList<>();
/**
* 初始化数据
*/
private void initData() {
Fragment mapFragment = MapFragment.newInstance("map");
Fragment klineFragment = OtherFragment.newInstance("");
Fragment otherFragment = OtherFragment.newInstance("");
fragmentList.add(mapFragment);
fragmentList.add(klineFragment);
fragmentList.add(otherFragment);
/*
在子fragment中获取FragmentManager应该使用{@link this#getChildFragmentManager()}
*/
viewDelegate.setViewPagerAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
});
/*
* 设置viewPager缓存数量,不然会造成内存泄漏。
* 内存泄漏原因:
* ViewPager会帮我们管理Fragment,默认缓存当前页面的前一页和后一页,当页面数》=3时就很容易发生内存泄漏
* 若不设置ViewPager缓存页数
* 在页面切换到最后一页时会ViewPager删掉当前页面的前一页之前的页面,但是list中又一直持有Fragment的实例,导致该fragment不能被销毁
* 当页面再次切换时,被删掉的页面又从List中重新加入了ViewPager的管理队列,如此反复就造成了内存的大量泄漏。
* */
viewDelegate.setOffscreenPageLimit(2);
viewDelegate.setTabBackground(PAGER_OTHER);
}
@Override
protected void bindEvenListener() {
super.bindEvenListener();
viewDelegate.setOnClickListener(this, R.id.btn_map, R.id.btn_kline, R.id.btn_other);
}
/**
* @return 视图层对象的字节码
*/
@Override
protected Class<FMainDelegate> getDelegateClass() {
return FMainDelegate.class;
}
@Override
public DataBinder getDataBinder() {
return new MainDataBinder();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_map:
viewDelegate.setTabBackground(PAGER_MAP);
break;
case R.id.btn_kline:
viewDelegate.setTabBackground(PAGER_KLINE);
break;
case R.id.btn_other:
viewDelegate.setTabBackground(PAGER_OTHER);
break;
}
}
}
<file_sep>package indi.toaok.androiddemo.module.other.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import indi.toaok.androiddemo.utils.AppUtil;
import indi.toaok.androiddemo.utils.FilePathUtil;
/**
* Created by sj on 10/24/16.
*/
public class DWebView<T> extends WebView {
T data;
public DWebView(Context context) {
this(context, null);
}
public DWebView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
/*
Android 8.0以上的问题webView的bug
java.lang.ClassNotFoundException: Didn't find class "android.webkit.SafeBrowsingResponse" on path: DexPathList[[zip file "/data/hw_init/system/app/WebViewGoogle/WebViewGoogle.apk"],nativeLibraryDirectories=[/data/hw_init/system/app/WebViewGoogle/lib/arm64, /data/hw_init/system/app/WebViewGoogle/WebViewGoogle.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64, /product/lib64, /system/lib64, /vendor/lib64, /product/lib64]]
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//this.getSettings().setSafeBrowsingEnabled(false);
}
this.getSettings().setJavaScriptEnabled(true);
this.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
String cacheDirPath = FilePathUtil.getCacheWebPath();
this.getSettings().setAppCachePath(cacheDirPath);
this.getSettings().setDomStorageEnabled(true);
this.getSettings().setDatabaseEnabled(true);
this.getSettings().setAppCacheEnabled(true);
this.getSettings().setAllowFileAccess(true);
this.getSettings().setLoadWithOverviewMode(true);
this.setWebViewClient(new JWebViewClient());
this.setWebChromeClient(new JWebChromeClient());
fixWebView();
}
@TargetApi(11)
private void fixWebView() {
int version = AppUtil.getAndroidSDKVersion();
if (version > 10 && version < 17) {
removeJavascriptInterface("searchBoxJavaBridge_");
}
}
class JWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.cancelShowLoading();
}
super.onReceivedError(view, request, error);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (onJWebViewOverrideUrlLoadingLinstener != null) {
OverrideUrlLoadingState overrideUrlLoadingState = onJWebViewOverrideUrlLoadingLinstener.shouldOverrideUrlLoading(view, request);
if (overrideUrlLoadingState != OverrideUrlLoadingState.Default) {
return overrideUrlLoadingState != OverrideUrlLoadingState.False;
}
}
return super.shouldOverrideUrlLoading(view, request);
}
}
class JWebChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.cancelShowLoading();
}
} else {
if (onJWebViewProgressLinstener != null) {
onJWebViewProgressLinstener.showLoading(newProgress);
}
}
super.onProgressChanged(view, newProgress);
}
}
public enum OverrideUrlLoadingState {
Default, False, Ture
}
OnJWebViewOverrideUrlLoadingLinstener onJWebViewOverrideUrlLoadingLinstener;
public void setOnJWebViewOverrideUrlLoadingLinstener(OnJWebViewOverrideUrlLoadingLinstener onJWebViewOverrideUrlLoadingLinstener) {
this.onJWebViewOverrideUrlLoadingLinstener = onJWebViewOverrideUrlLoadingLinstener;
}
public interface OnJWebViewOverrideUrlLoadingLinstener {
OverrideUrlLoadingState shouldOverrideUrlLoading(WebView view, WebResourceRequest request);
}
OnJWebViewProgressLinstener onJWebViewProgressLinstener;
public void setOnJWebViewProgressLinstener(OnJWebViewProgressLinstener onJWebViewProgressLinstener) {
this.onJWebViewProgressLinstener = onJWebViewProgressLinstener;
}
public interface OnJWebViewProgressLinstener {
void showLoading(int newProgress);
void cancelShowLoading();
}
}
<file_sep>package indi.toaok.androiddemo.module.map.view;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import butterknife.BindView;
import indi.toaok.androiddemo.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import indi.toaok.androiddemo.base.view.BaseDelegate;
import indi.toaok.androiddemo.module.map.marker.GDMarkerOptions;
import indi.toaok.androiddemo.module.map.marker.MarkerBuilder;
import indi.toaok.androiddemo.module.map.marker.MarkerHelper;
/**
* @author Toaok
* @version 1.0 2018/9/8.
*/
public class BaseMapDelegate extends BaseDelegate {
/**
* 默认的地图缩放比例
*/
private final int MAP_ZOOM_SIZE_NORMAL = 16;
@BindView(R.id.map_view)
protected MapView mapView;
protected AMap aMap;
protected int mapZoom = MAP_ZOOM_SIZE_NORMAL;
/**
* 存在地图上的markers
*/
private HashMap<MarkerHelper.MarkerType, List<Marker>> markersMap = new HashMap<>();
@Override
public int getRootLayoutId() {
return R.layout.fragment_map;
}
@Override
public void initView() {
super.initView();
init();
}
protected void init() {
mapView = get(R.id.map_view);
initMap(mapView.getMap());
}
protected void initMap(MapView mapView) {
this.mapView = mapView;
initMap(mapView.getMap());
}
protected void initMap(AMap amap) {
if (aMap == null) {
aMap = amap;
}
//设置定位按钮是否显示
aMap.getUiSettings().setMyLocationButtonEnabled(true);
//设置缩放按钮是否可见
aMap.getUiSettings().setZoomControlsEnabled(false);
//设置地图是否支持倾斜手势
aMap.getUiSettings().setTiltGesturesEnabled(true);
//设置地图是否支持旋转旋转
aMap.getUiSettings().setRotateGesturesEnabled(true);
//设置高德logo位置
aMap.getUiSettings().setLogoBottomMargin(-100);
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.strokeWidth(0);
myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//连续定位、且将视角移动到地图中心点,定位蓝点跟随设备移动。(1秒1次定位)
myLocationStyle.radiusFillColor(Color.TRANSPARENT);
myLocationStyle.strokeColor(Color.WHITE);
aMap.setMyLocationEnabled(true);
aMap.setMyLocationStyle(myLocationStyle);
/**
* 地图移动摄像头监听
*/
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChangeFinish(CameraPosition arg0) {
BaseMapDelegate.this.onCameraChangeFinish(arg0);
}
@Override
public void onCameraChange(CameraPosition arg0) {
BaseMapDelegate.this.onCameraChange(arg0);
}
});
/**
* 点击marker 回调 InfoWindowAdapter 控制弹出的窗口渲染
*/
aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return BaseMapDelegate.this.getInfoWindow(marker);
}
@Override
public View getInfoContents(Marker marker) {
return BaseMapDelegate.this.getInfoContents(marker);
}
});
}
/**
* 地图中心点移动结束回调
*
* @param cameraPosition
*/
protected void onCameraChangeFinish(CameraPosition cameraPosition) {
}
/**
* 地图中心点移动时回调
*
* @param cameraPosition
*/
protected void onCameraChange(CameraPosition cameraPosition) {
/*
Log.d("坐标装换", "转换前:" + cameraPosition.target.toString());
CoordinateConverter converter = new CoordinateConverter(getActivity());
// CoordType.GPS 待转换坐标类型
converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 LatLng类型
converter.coord(cameraPosition.target);
// 执行转换操作
LatLng desLatLng = converter.convert();
Log.d("坐标装换", "转换后:" + desLatLng.toString());*/
}
/**
* 点击marker 回调 InfoWindowAdapter 控制弹出的窗口渲染
*
* @param marker
*/
protected View getInfoContents(Marker marker) {
return null;
}
protected View getInfoWindow(Marker marker) {
return null;
}
public MapView getMapView() {
return mapView;
}
public void addMarkers(MarkerBuilder builder) {
if (aMap == null || builder == null || builder.getDatas() == null || builder.getDatas().isEmpty()) {
return;
}
List<Marker> markerList;
if (markersMap.containsKey(builder.getType())) {
markerList = markersMap.get(builder.getType());
} else {
markerList = new ArrayList<>();
markersMap.put(builder.getType(), markerList);
}
// 渲染并加入缓存
for (GDMarkerOptions markerOption : builder.getDatas()) {
if (markerOption.getMarkerOptions() != null) {
Marker marker = aMap.addMarker(markerOption.getMarkerOptions());
markerList.add(marker);
marker.setRotateAngle(markerOption.getRotateAngle());
marker.showInfoWindow();
}
}
}
public void moveToLatLng(LatLng latLng) {
if (aMap == null || latLng == null) {
return;
}
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, mapZoom));
}
}
<file_sep>package indi.toaok.study;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import indi.toaok.androiddemo.api.vo.request.SplashRequestBean;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class UnitTest {
@Test
public void test() {
try {
Map map=convertToMap(new SplashRequestBean());
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
static class CountDownTimer implements Runnable {
public CountDownTimer(int time) {
this.time = time * 1000;
remaainingTime = this.time;
System.out.println("执行时间" + this.time);
}
long time;
//毫秒级
long startTime = -1;
//剩余时间
long remaainingTime = -1;
@Override
public void run() {
startTime = System.currentTimeMillis();
System.out.println("开始时间" + startTime);
if (startTime > 0) {
while (remaainingTime > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("I has interputed");
time=remaainingTime;
break;
}
remaainingTime = time - (System.currentTimeMillis() - startTime);
System.out.println(Thread.currentThread()+":剩余时间" + (remaainingTime+1000) / 1000);
}
if (remaainingTime <= 0) {
System.out.println("I can do somthing ");
}
}
}
}
public static HashMap<String, Object> convertToMap(Object obj)
throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
Field[] fields = obj.getClass().getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
String varName = fields[i].getName();
boolean accessFlag = fields[i].isAccessible();
fields[i].setAccessible(true);
Object o = fields[i].get(obj);
if (o != null)
map.put(varName, o.toString());
fields[i].setAccessible(accessFlag);
}
return map;
}
}<file_sep>package indi.toaok.androiddemo.module.other.databinder;
import indi.toaok.androiddemo.base.databinder.BaseDataBinder;
import indi.toaok.androiddemo.module.other.bean.OtherListBean;
import indi.toaok.androiddemo.module.other.view.OtherDelegate;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class OtherListDataBinder extends BaseDataBinder<OtherDelegate, OtherListBean> {
@Override
public void viewBindModel(OtherDelegate viewDelegate, OtherListBean data) {
super.viewBindModel(viewDelegate, data);
viewDelegate.setAdapter(data.getAdapter());
}
}
<file_sep>include ':app', ':Leaks', ':Themvp', ':Imageloder', ':Utils', ':Encrypt'
project(':Leaks').projectDir = new File('librarys/Leaks')
project(':Themvp').projectDir = new File('librarys/Themvp')
project(':Imageloder').projectDir = new File('librarys/Imageloder')
project(':Utils').projectDir = new File('librarys/Utils')
project(':Encrypt').projectDir = new File('librarys/Encrypt')<file_sep>package indi.toaok.androiddemo.module.comment.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import java.lang.reflect.Field;
import androidx.appcompat.widget.AppCompatTextView;
import indi.toaok.androiddemo.R;
/**
* 文字带边框的TextView
* @author Toaok
* @version 1.0 2019/2/25.
*/
public class StrokeTextView extends AppCompatTextView {
private static final String TAG=StrokeTextView.class.getSimpleName();
private Paint mStrokePaint;
private float mStrokeSize;
private int mStrokeColor;
private boolean isDrawStroke = false; // 默认不采用描边
public StrokeTextView(Context context) {
this(context, null);
}
public StrokeTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StrokeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView, 0, 0);
if (typedArray != null) {
mStrokeColor = typedArray.getColor(R.styleable.StrokeTextView_strokeColor, Color.WHITE);
mStrokeSize = typedArray.getDimension(R.styleable.StrokeTextView_strokeSize, 0.0f);
isDrawStroke = typedArray.getBoolean(R.styleable.StrokeTextView_isDrawStroke, false);
typedArray.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
if (isDrawStroke) {
mStrokePaint = getPaint();//获取当前画笔
TextPaint oldPaint = new TextPaint();
oldPaint.set(mStrokePaint);//备份原始画笔
int oldColor=getCurrentTextColor();//备份原始颜色
// 描边
setTextColorUseReflection(mStrokeColor);
mStrokePaint.setStrokeWidth(mStrokeSize); // 描边宽度
mStrokePaint.setStyle(Paint.Style.FILL_AND_STROKE); //描边种类
mStrokePaint.setFakeBoldText(true); // 外层text采用粗体
super.onDraw(canvas);
//恢复原先的画笔
setTextColorUseReflection(oldColor);
mStrokePaint.set(oldPaint);
}
super.onDraw(canvas);
}
private void setTextColorUseReflection(int color) {
Field textColorField;
try {
textColorField = TextView.class.getDeclaredField("mCurTextColor");
textColorField.setAccessible(true);
textColorField.set(this,color);
textColorField.setAccessible(false);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
mStrokePaint.setColor(color);
}
}<file_sep>package indi.toaok.androiddemo.http.rx.response;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public interface IResponse {
int getCode();
boolean isSuccess();
String getMessage();
}
<file_sep>package indi.toaok.androiddemo.model.local.preferences;
import indi.toaok.androiddemo.BuildConfig;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class Salt {
public static String getCommonBase() {
return BuildConfig.SALT;
}
}
<file_sep>apply {
from "${rootDir.path}/config_lib.gradle"
plugin "com.android.library"
}
configAndroidModuleDomain project
configModuleBaseDependences project
dependencies {
implementation dependencesLibrary.glide
annotationProcessor dependencesLibrary.glide_compiler
implementation dependencesLibrary.glide_okhttp3_integration
}
<file_sep>package indi.toaok.androiddemo.module.rxandroid.databinder;
import indi.toaok.androiddemo.base.databinder.BaseDataBinder;
import indi.toaok.androiddemo.module.rxandroid.bean.AppListBean;
import indi.toaok.androiddemo.module.rxandroid.view.AppListDelegate;
/**
* @author Toaok
* @version 1.0 2019/3/20.
*/
public class AppListDataBinder extends BaseDataBinder<AppListDelegate, AppListBean> {
@Override
public void viewBindModel(AppListDelegate viewDelegate, AppListBean data) {
super.viewBindModel(viewDelegate,data);
if (!viewDelegate.isSetAdapter()) {
viewDelegate.setAdapter(data.getAdapter());
}
if (!viewDelegate.isSetRefreshingListener()) {
viewDelegate.setOnRefreshListener(data.getRefreshListener());
}
viewDelegate.setRefreshing(data.isRefreshing());
viewDelegate.setVisibility(data.getVisibility());
}
}
<file_sep>#include <jni.h>
#include <malloc.h>
#include <string.h>
#include <android/log.h>
#include "aes.h"
#include "base64.h"
#include "../util.h"
#include "../constant.h"
#include "md5.h"
#define LOG_TAG "Security-native"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
const static int SIZE_M = 32;
/**
* 将秘钥转为32位
*/
char *keyToMd5_32(char *key_original)
{
Md5Context md5Context;
MD5_HASH md5Hash;
Md5Initialise(&md5Context);
Md5Update(&md5Context, key_original, (uint32_t)strlen(key_original));
Md5Finalise(&md5Context, &md5Hash);
char tmp[3] = {}, buf[33] = {};
int j;
for (j = 0; j < sizeof(md5Hash); j++)
{
sprintf(tmp, "%02X", md5Hash.bytes[j]);
strcat(buf, tmp);
}
return buf;
}
/**
* 加密
*/
char *_encrypt(char *str)
{
char *key = DEFAULT_KEY;
//计算字符串的长度 (字符长度/16)*16+16 确保长度为16的倍数
long strLen = ((strlen(str) / SIZE_M) * SIZE_M) + SIZE_M;
char *aesEnc = malloc(strLen);
memset(aesEnc, 0, strLen);
AES_KEY aes_key;
//设置AES加密密钥
AES_set_encrypt_key(key, 256, &aes_key);
int i = 0;
//AES加密
for (i = 0; i < strlen(str); i += SIZE_M)
{
AES_encrypt(str + i, aesEnc + i, &aes_key);
}
//Base64一次加密
char *basEnc = base64_encode(aesEnc, strlen(aesEnc));
//拼接 到 加密字符
char len[strLen + 2];
sprintf(len, "%d__", strLen);
char *len_str = str_combine(len, basEnc);
// Base64二次加密
char *result = base64_encode(len_str, strlen(len_str));
return result;
}
/**
* 加密
*/
char *_encrypt_key(char *key, char *str)
{
//计算字符串的长度 (字符长度/16)*16+16 确保长度为16的倍数
long strLen = ((strlen(str) / SIZE_M) * SIZE_M) + SIZE_M;
char *aesEnc = malloc(strLen);
memset(aesEnc, 0, strLen);
AES_KEY aes_key;
//设置AES加密密钥
AES_set_encrypt_key(key, 256, &aes_key);
int i = 0;
//AES加密
for (i = 0; i < strlen(str); i += SIZE_M)
{
AES_encrypt(str + i, aesEnc + i, &aes_key);
}
//Base64一次加密
char *basEnc = base64_encode(aesEnc, strlen(aesEnc));
//拼接 到 加密字符
char len[strLen + 2];
sprintf(len, "%d__", strLen);
char *len_str = str_combine(len, basEnc);
// Base64二次加密
char *result = base64_encode(len_str, strlen(len_str));
return result;
}
/**
* 解密
*/
char *_decrypt(char *str)
{
char *key = DEFAULT_KEY;
//Base64一次解密
char *len_str = base64_decode(str, strlen(str));
//分割字符串
char strs[strlen(len_str)];
char cstrlen[SIZE_M];
sscanf(len_str, "%[0-9]__%[^.]", cstrlen, strs);
long strLen = atoi(cstrlen);
//Base64二次解密
char *basDec = base64_decode(strs, strlen(strs));
char *aesDec = malloc(strLen);
memset(aesDec, 0, strLen);
AES_KEY aes_key;
AES_set_decrypt_key(key, 256, &aes_key);
int i = 0;
//AES解密,解密basDec,得aesDec
for (i = 0; i < strLen; i += SIZE_M)
{
AES_decrypt(basDec + i, aesDec + i, &aes_key);
}
return aesDec;
}
/**
* 解密
*/
char *_decrypt_key(char *key, char *str)
{
//Base64一次解密
char *len_str = base64_decode(str, strlen(str));
//分割字符串
char strs[strlen(len_str)];
char cstrlen[SIZE_M];
sscanf(len_str, "%[0-9]__%[^.]", cstrlen, strs);
long strLen = atoi(cstrlen);
//Base64二次解密
char *basDec = base64_decode(strs, strlen(strs));
char *aesDec = malloc(strLen);
memset(aesDec, 0, strLen);
AES_KEY aes_key;
AES_set_decrypt_key(key, 256, &aes_key);
int i = 0;
//AES解密,解密basDec,得aesDec
for (i = 0; i < strLen; i += SIZE_M)
{
AES_decrypt(basDec + i, aesDec + i, &aes_key);
}
return aesDec;
}<file_sep>package indi.toaok.themvp.databind;
import android.os.Bundle;
import androidx.annotation.Nullable;
import indi.toaok.themvp.model.IModel;
import indi.toaok.themvp.presenter.ActivityPresenter;
import indi.toaok.themvp.view.IDelegate;
/**
* 集成数据-视图绑定的activity基类
*
* @param <T> View层代理
* @author Toaok
* @version 1.0 2018/9/7.
*/
public abstract class DataBindActivity<T extends IDelegate> extends
ActivityPresenter<T> {
protected DataBinder binder;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binder = getDataBinder();
}
public abstract DataBinder getDataBinder();
public <D extends IModel> void notifyModelChanged(D data) {
if (binder != null && viewDelegate != null) {
if (viewDelegate instanceof IDelegate && data instanceof IModel) {
binder.viewBindModel(viewDelegate, data);
}
}
}
}
<file_sep>package indi.toaok.themvp.model;
/**
* @author Toaok
* @version 1.0 2018/9/7.
*/
public interface IModel {
}
<file_sep>package indi.toaok.androiddemo.module.map.marker;
import java.util.ArrayList;
import java.util.List;
/**
* @author Toaok
* @version 1.0 2019/2/14.
*/
public class MarkerBuilder {
List<GDMarkerOptions> datas;
MarkerHelper.MarkerType type;
private MarkerBuilder(Builder builder) {
datas = builder.datas;
type = builder.type;
}
public static final class Builder {
private List<GDMarkerOptions> datas;
private MarkerHelper.MarkerType type;
public Builder() {
}
public Builder datas(List<GDMarkerOptions> val) {
datas = val;
return this;
}
public Builder data(GDMarkerOptions val) {
if(datas==null){
datas=new ArrayList<>();
datas.add(val);
}
return this;
}
public Builder type(MarkerHelper.MarkerType val) {
type = val;
return this;
}
public MarkerBuilder build() {
return new MarkerBuilder(this);
}
}
public List<GDMarkerOptions> getDatas() {
return datas;
}
public MarkerHelper.MarkerType getType() {
return type;
}
}
<file_sep>package indi.toaok.androiddemo.module.rxandroid.fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import indi.toaok.androiddemo.base.presenter.fragment.BaseFragment;
import indi.toaok.androiddemo.common.animation.Animation;
import indi.toaok.androiddemo.module.rxandroid.bean.AppInfo;
import indi.toaok.androiddemo.module.rxandroid.bean.AppInfoRich;
import indi.toaok.androiddemo.module.rxandroid.bean.AppListBean;
import indi.toaok.androiddemo.module.rxandroid.databinder.AppListDataBinder;
import indi.toaok.androiddemo.module.rxandroid.view.AppListDelegate;
import indi.toaok.androiddemo.utils.FilePathUtil;
import indi.toaok.themvp.databind.DataBinder;
import indi.toaok.utils.core.ImageUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
* @author Toaok
* @version 1.0 2019/3/19.
*/
public class AppListFragment extends BaseFragment<AppListDelegate> {
private AppListBean mAppListBean;
public static AppListFragment newInstance() {
AppListFragment fragment = new AppListFragment();
return fragment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
mAppListBean = new AppListBean();
mAppListBean.setRefreshListener(() -> refreshAppList());
refreshAppList();
}
private Observable<AppInfo> getApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
return Observable.fromIterable(getContext().getPackageManager().queryIntentActivities(mainIntent, 0))
.map(resolveInfo -> {
AppInfoRich appInfoRich = new AppInfoRich(getContext(), resolveInfo);
Bitmap icon = ImageUtil.drawable2Bitmap(appInfoRich.getIcon());
String name = appInfoRich.getName();
//保存PNG格式图片时要注意加上后缀,不然不会以png方式读取
String iconPath = FilePathUtil.getCacheImagePath() + name + ".png";
ImageUtil.save(icon, iconPath, Bitmap.CompressFormat.PNG);
return new AppInfo(name, iconPath, appInfoRich.getVersion(), appInfoRich.getLastUpdateTime());
});
}
@SuppressLint("CheckResult")
private void refreshAppList() {
getApps().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(appInfo -> {//next
mAppListBean.setVisibility(Animation.VISIBLE);
mAppListBean.getAdapter().append(appInfo);
notifyModelChanged(mAppListBean);
}, throwable -> {//异常
mAppListBean.setMessage("Something went wrong!");
mAppListBean.setRefreshing(false);
notifyModelChanged(mAppListBean);
}, () -> {//完成
mAppListBean.setMessage("There is the list!");
mAppListBean.setRefreshing(false);
notifyModelChanged(mAppListBean);
}, disposable -> {//订阅时清除数据
mAppListBean.clearData();
mAppListBean.setMessage("list has subscribe!");
notifyModelChanged(mAppListBean);
});
}
@Override
protected Class<AppListDelegate> getDelegateClass() {
return AppListDelegate.class;
}
@Override
protected DataBinder getDataBinder() {
return new AppListDataBinder();
}
}
<file_sep>ext {
//app version config info
androidConfig = [
applicationId : "indi.toaok.androiddemo",
appName : "AndroidDemo",
compileSdkVersion: 28,
minSdkVersion : 15,
targetSdkVersion : 28,
versionCode : 1_0_0,
versionName : '1.0.0',
flavorDimensions : 'default'
]
//kind of plugins version info
pluginsVsersion = [
//gradle
gradle : '3.2.1',
butterknife: '10.1.0'
]
//plugins dependence info
pluginsDependence = [
gradle : "com.android.tools.build:gradle:$pluginsVsersion.gradle",
butterknife: "com.jakewharton:butterknife-gradle-plugin:$pluginsVsersion.butterknife"
]
//base dependence version info
baseDependdencsVersion = [
/**
* https://developer.android.google.cn/jetpack/androidx/migrate
*/
androidx: [
appcompat : '1.0.0',
material : '1.0.0',
constraintlayout: '1.1.2'
],
//test
test : [
junit : '4.12',
runner : '1.1.0',
espresso_core: '3.1.0'
],
//multidex
multidex: '2.0.0'
]
//base dependence info
baseDependences = [
//androidx
appcompat : "androidx.appcompat:appcompat:$baseDependdencsVersion.androidx.appcompat",
material : "com.google.android.material:material:$baseDependdencsVersion.androidx.material",
constraintlayout: "androidx.constraintlayout:constraintlayout:$baseDependdencsVersion.androidx.constraintlayout",
//test
junit : "junit:junit:$baseDependdencsVersion.test.junit",
runner : "androidx.test:runner:$baseDependdencsVersion.test.runner",
espresso_core : "androidx.test.espresso:espresso-core:$baseDependdencsVersion.test.espresso_core",
//multidex
multidex : "androidx.multidex:multidex:$baseDependdencsVersion.multidex"
]
//the third-party library version info
dependencesLibraryVersion = [
/**
* https://projectlombok.org/setup/android
*/
lombok : '1.16.18',
/**
* https://github.com/JakeWharton/butterknife
*/
butterknife : '10.1.0',
/**
* https://github.com/ReactiveX/RxJava
* https://github.com/ReactiveX/RxAndroid
*/
rxjava : '2.0.1',
/**
* https://github.com/square/okhttp
*/
okhttp : '3.11.0',
/**
* https://github.com/square/retrofit
*/
retrofit : '2.4.0',
/**
* https://github.com/bumptech/glide
*/
glide : '4.8.0',
/**
* https://jsoup.org/
*/
jsoup : '1.11.3',
/**
* https://github.com/google/gson
*/
gson : '2.8.2',
/**
* https://github.com/tbruyelle/RxPermissions
* add maven { url 'https://jitpack.io' } in project build.gradle
*/
rxpermissions: '0.10.2',
/**
* https://lbs.amap.com/api/android-sdk/guide/create-project/android-studio-create-project
*/
gaode : [
map : 'latest.integration',
navi : 'latest.integration',
location: 'latest.integration',
search : 'latest.integration'
]
]
//the third-party library dependences info
dependencesLibrary = [
//lombok
lombok : "org.projectlombok:lombok:$dependencesLibraryVersion.lombok",
//butterknife
butterknife : "com.jakewharton:butterknife:$dependencesLibraryVersion.butterknife",
butterknife_compiler : "com.jakewharton:butterknife-compiler:$dependencesLibraryVersion.butterknife",
//rx
rxjava : "io.reactivex.rxjava2:rxjava:$dependencesLibraryVersion.rxjava",
rxandroid : "io.reactivex.rxjava2:rxandroid:$dependencesLibraryVersion.rxjava",
//okhttp
okhttp : "com.squareup.okhttp3:okhttp:$dependencesLibraryVersion.okhttp",
//retrofit
retrofit : "com.squareup.retrofit2:retrofit:$dependencesLibraryVersion.retrofit",
converter_gson : "com.squareup.retrofit2:converter-gson:$dependencesLibraryVersion.retrofit",
adapter_rxjava : "com.squareup.retrofit2:adapter-rxjava2:$dependencesLibraryVersion.retrofit",
//glide
glide : "com.github.bumptech.glide:glide:$dependencesLibraryVersion.glide",
glide_compiler : "com.github.bumptech.glide:compiler:$dependencesLibraryVersion.glide",
glide_okhttp3_integration: "com.github.bumptech.glide:okhttp3-integration:$dependencesLibraryVersion.glide",
//jsoup
jsoup : "org.jsoup:jsoup:$dependencesLibraryVersion.jsoup",
//gson
gson : "com.google.code.gson:gson:$dependencesLibraryVersion.gson",
//rxpermissions
rxpermissions : "com.github.tbruyelle:rxpermissions:$dependencesLibraryVersion.rxpermissions",
//gaode
//3d map
gaode_map : "com.amap.api:3dmap:$dependencesLibraryVersion.gaode.map",
//导航
gaode_navi : "com.amap.api:navi-3dmap:$dependencesLibraryVersion.gaode.navi",
//定位
gaode_location : "com.amap.api:location:$dependencesLibraryVersion.gaode.location",
//查询
gaode_search : "com.amap.api:search:$dependencesLibraryVersion.gaode.search",
]
//高德APP_KEY
gaode = [
APP_KEY: "eeb4c8860aee338e342a82e82f08f623"
]
/**
* host
*/
host = [
/**
* 生产环境
*/
host_prod: 'https://api.apiopen.top/',
/**
* 开发环境
*/
host_dev : 'https://api.apiopen.top/',
]
/**
* 默认环境
*/
host_default = host.host_dev
/**
* release 生产 环境
*/
host_prod = host.host_prod
}<file_sep>package indi.toaok.androiddemo.http;
import indi.toaok.androiddemo.BuildConfig;
/**
* @author Toaok
* @version 1.0 2019/4/25.
*/
public class HostUtil {
private static final String HOST_URL_DEFAULT = BuildConfig.API_HOST;
public static String getServerHost(){
return HOST_URL_DEFAULT;
}
}
<file_sep>#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <android/log.h>
#include <malloc.h>
#include "constant.h"
#include "signature.h"
#include "openssl/crypt.h"
#include "util.h"
#define LOG_TAG "Security-native"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#ifndef _Included_indi_toaok_ndk_Security
#define _Included_indi_toaok_ndk_Security
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getSalt(JNIEnv *env, jclass object, jstring ketStr)
{
return (*env)->NewStringUTF(env, SALT);
}
JNIEXPORT jboolean JNICALL Java_indi_toaok_ndk_Security_isDz(JNIEnv *env, jclass object, jstring key)
{
char *str = _JString2CStr(env, key);
char *decrypt_str = _decrypt(DEV_SIGN);
return (strcmp(str, DEV_SIGN) == 0);
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getSign(JNIEnv *env, jclass object)
{
int length;
length = sizeof(SIGN_ARRAY) / sizeof(SIGN_ARRAY[0]);
int i, size = 0;
for (i = 0; i < length; ++i)
{
size += strlen(SIGN_ARRAY[i]);
}
size += length - 1;
char *reslut = NULL;
if ((reslut = (char *)malloc(sizeof(char) * (size + 1))) == NULL)
{
LOGD("Malloc heap failed!");
return NULL;
}
memset(reslut, 0, sizeof(char) * (size + 1));
strcpy(reslut, SIGN_ARRAY[0]);
for (i = 1; i < length; ++i)
{
strcat(reslut, ",");
strcat(reslut, SIGN_ARRAY[i]);
}
return (*env)->NewStringUTF(env, reslut);
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_getVersion(JNIEnv *env, jclass object)
{
return (*env)->NewStringUTF(env, VERSION);
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_encrypt(JNIEnv *env, jclass object, jstring data)
{
char *str = _JString2CStr(env, data);
return (*env)->NewStringUTF(env, _encrypt(str));
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_decrypt(JNIEnv *env, jclass object, jstring data)
{
char *str = _JString2CStr(env, data);
return (*env)->NewStringUTF(env, _decrypt(str));
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_encryptWithKey(JNIEnv *env, jclass object, jstring keyStr, jstring data)
{
char *key = _JString2CStr(env, keyStr);
char *str = _JString2CStr(env, data);
return (*env)->NewStringUTF(env, _encrypt_key(key, str));
}
JNIEXPORT jstring JNICALL Java_indi_toaok_ndk_Security_decryptWithKey(JNIEnv *env, jclass object, jstring keyStr, jstring data)
{
char *key = _JString2CStr(env, keyStr);
char *str = _JString2CStr(env, data);
return (*env)->NewStringUTF(env, _decrypt_key(key, data));
}
#ifdef __cplusplus
}
#endif
#endif<file_sep>package indi.toaok.androiddemo.module.other.adapter;
import java.util.List;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.base.recyclerview.BaseRecyclerAdapter;
import indi.toaok.androiddemo.module.base.recyclerview.BaseViewHolder;
import indi.toaok.androiddemo.module.other.bean.OtherItemBean;
/**
* @author Toaok
* @version 1.0 2019/4/26.
*/
public class OtherListAdapter extends BaseRecyclerAdapter<OtherItemBean, BaseViewHolder> {
public OtherListAdapter(List<OtherItemBean> data) {
super(data);
}
@Override
public int getItemLayoutId() {
return R.layout.view_item_other;
}
@Override
public void bindData(BaseViewHolder holder, int position) {
OtherItemBean itemBean = mData.get(position);
holder.getButton(R.id.btn_other_item).setText(itemBean.getText());
}
}
<file_sep>package indi.toaok.androiddemo.module.home.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.MenuItem;
import indi.toaok.androiddemo.Config;
import indi.toaok.androiddemo.R;
import indi.toaok.androiddemo.module.base.presenter.activity.BaseToolbarActivity;
import indi.toaok.androiddemo.module.home.fragemnt.MainFragment;
import indi.toaok.androiddemo.module.home.view.AMainDelegate;
import indi.toaok.androiddemo.module.other.activity.WebActivity;
/**
* 主界面
*/
public class MainActivity extends BaseToolbarActivity<AMainDelegate> implements AMainDelegate.OnMenuItemSelectListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewDelegate.setMenuItemSelectListener(this);
}
@Override
protected Class<AMainDelegate> getDelegateClass() {
return AMainDelegate.class;
}
@Override
protected Fragment createFragment() {
return MainFragment.newInstance("MainFragment");
}
public static void startActivity(Context context) {
Intent intent = new Intent();
intent.setClass(context, MainActivity.class);
context.startActivity(intent);
}
/**
* Called when an item in the navigation menu is selected.
*
* @param item The selected item
* @return true to display the item as the selected item
*/
@Override
public boolean onMenuItemSelect(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_git_hub:
WebActivity.startActivity(this, Config.GITHUB, getString(R.string.menu_item_git_hub), true, true);
return true;
case R.id.action_blog:
WebActivity.startActivity(this, Config.BLOG, getString(R.string.menu_item_blog), true, true);
return true;
case R.id.action_website:
WebActivity.startActivity(this, Config.BLOG, getString(R.string.menu_item_website), true, true);
return true;
case R.id.action_about:
WebActivity.startActivity(this, Config.BLOG, getString(R.string.menu_item_about), true, true);
return true;
default:
break;
}
return false;
}
}
<file_sep>package indi.toaok.androiddemo.activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import indi.toaok.androiddemo.databind.SplashDataBinder_BT;
import indi.toaok.androiddemo.model.vo.AppInfo;
import indi.toaok.androiddemo.module.home.activity.BaseSplashActivity;
import indi.toaok.themvp.databind.DataBinder;
import indi.toaok.androiddemo.view.SplashDelegate_BT;
import indi.toaok.androiddemo.vo.SplashBean_BT;
/**
* Created by sj on 2016/11/25.
*/
public class SplashActivity_BT extends BaseSplashActivity<SplashDelegate_BT> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppInfo appInfo=new AppInfo();
if (mSplashBean == null) {
mSplashBean = new SplashBean_BT(appInfo);
} else {
if (mSplashBean instanceof SplashBean_BT) {
((SplashBean_BT) mSplashBean).setAppInfo(appInfo);
}else {
mSplashBean=new SplashBean_BT(appInfo,mSplashBean);
}
}
notifyModelChanged(mSplashBean);
}
@Override
protected Class<SplashDelegate_BT> getDelegateClass() {
return SplashDelegate_BT.class;
}
@Override
public DataBinder getDataBinder() {
return new SplashDataBinder_BT();
}
}
|
1d744d60f3eda0a282c48823e7e3fbec2671a7be
|
[
"Markdown",
"Gradle",
"Java",
"Text",
"C"
] | 65
|
Gradle
|
Toaok/AndroidDemo
|
44fdb162a3953dcc5d337bf09e0295df3be14c07
|
fcc5f26b467d8727ade59e03e62bb1b267e0b72f
|
refs/heads/master
|
<repo_name>KunalGautam/WPBS<file_sep>/index.php
<?php get_header(); ?>
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<div class="row">
<header>
<h3><?php the_title(); ?></h3> <!-- Title of the post -->
</header>
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. ?>
<aside>
<?php the_post_thumbnail(); ?>
</aside>
<?php } ?>
<?php the_content(); ?> <!-- Contents of a post -->
<footer>
<?php the_category(', ') ?> <!-- Post category -->
<?php the_tags(', ') ?> <!-- Post tags -->
<?php comments_popup_link(); ?>. <!-- comments_number -->
<?php edit_post_link(); ?>
<?php comments_template(); ?>
</footer>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
<file_sep>/wp-admin/index.php
<?php
if (!current_user_can('manage_options')) {
wp_die('You do not have sufficient permissions to access this page.');
}
if ( is_admin() ){
add_action( 'admin_init', 'theme_options_init' );
add_action( 'admin_menu', 'theme_options_add_page' );
function theme_options_init(){
register_setting( 'WPBS', 'sample_theme_options', 'theme_options_validate' );
}
// Load up the menu page
function theme_options_add_page() {
add_theme_page( __( 'Theme Options For WPBS', 'WPBS' ), __( 'WPBS Theme Options', 'WPBS' ), 'edit_theme_options', 'theme_options', 'theme_options_display' );
add_menu_page( "Setting For WPBS", "WPBS", "manage_options", "wpbs", "theme_option_display_home", "dashicons-carrot", "58" );
add_submenu_page( "wpbs", "WPBS Version Check", "Version", "manage_options", "wpbsversioncheck", "wpbs_version_check" );
}
function theme_options_display() {
?>
<div class="wrap">
<h2>Welcome to WPBS.</h2>
<p>This is placeholder for Theme Setting.</p>
<?php
}// End of theme_option_add_page
function theme_option_display_home() {
include("home.php");
}
function wpbs_version_check() {
include("version.php");
}
}//End of If admin function
?>
<file_sep>/README.md
WPBS
====
Wordpress bootstrap theme from scratch
<file_sep>/footer.php
</div> <!-- /container -->
<div id="spacer"></div>
<div id="footer">
<div class="container">
<p class="text-muted">Place sticky footer content here.</p>
</div>
</div>
<?php wp_footer(); ?>
<script src="<?php bloginfo( 'stylesheet_directory' ); ?>/js/jquery.min.js"></script>
<script src="<?php bloginfo( 'stylesheet_directory' ); ?>/js/function.js"></script>
<script src="<?php bloginfo( 'stylesheet_directory' ); ?>/js/bootstrap.js"></script>
</body>
</html>
<file_sep>/functions.php
<?php
// Update Function
require_once('include/update.php');
// Register Custom Navigation Walker
require_once('include/wp_bootstrap_navwalker.php');
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'THEMENAME' ),
) );
// Register Custom pagination
require_once('include/wp-pagination.php');
?>
<file_sep>/front-page.php
<?php get_header(); ?>
<?php while ( have_posts() ) : the_post() ?>
<div class="row">
<div class="col-md-2 align-center height-fix visible-md-* visible-lg-* hidden-sm hidden-xs"> <br><div class="date"><p><?php echo get_the_date("d"); ?>
<span><?php echo get_the_date("F"); ?></span>
<h4><?php echo get_the_date("Y"); ?></h4>
<?php edit_post_link('Edit Post', '<button type="button" class="btn btn-info">', '</button>'); ?> </div>
</div>
<div class="col-md-10 col-lg-10 col-xs-12 col-sm-12">
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. ?>
<aside>
<?php the_post_thumbnail(); ?>
</aside>
<?php } ?>
<?php the_content(); ?> <!-- Contents of a post -->
</div>
</div>
<footer><br>
<b>Published by:</b> <?php the_author(); ?><div class="hidden-md hidden-lg"> Published on <?php echo get_the_date(""); ?></div> | <?php the_category(', ') ?> | <?php comments_popup_link(); ?>.
</footer>
<?php endwhile; ?>
<?php
if ( function_exists('wp_bootstrap_pagination') )
wp_bootstrap_pagination();
?>
<?php get_footer(); ?>
<file_sep>/single.php
<?php get_header(); ?>
<?php if(have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
<div class="row">
<header>
<h3><?php the_title(); ?></h3> <!-- Title of the post -->
</header>
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. ?>
<aside>
<?php the_post_thumbnail(); ?>
</aside>
<?php } ?>
<?php the_content(); ?> <!-- Contents of a post -->
<footer>
Published on : <?php echo get_the_date( ); ?> <?php the_time(); ?> by <b><?php the_author(); ?><br /> <!-- Author of the post --></b>
<?php the_category(', ') ?> <!-- Post category -->
<?php the_tags(', ') ?> <!-- Post tags -->
<?php comments_popup_link(); ?>. <!-- comments_number -->
<?php edit_post_link(); ?>
<?php comments_template(); ?>
</footer>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
<file_sep>/js/function.js
$('.navbar-nav>li.dropdown>a').click(function() {
if( $(this).parent().hasClass("open") ) {
$(this).parent().removeClass('open');
return false;
}
else {
$(this).parent().addClass('open');
return false;
}
});
$('.dropdown-submenu>a').click(function() {
if( $(this).parent().hasClass("open") ) {
$(this).parent().removeClass('open');
return false;
}
else {
$(this).parent().addClass('open');
return false;
}
});
<file_sep>/header.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title><?php bloginfo( 'name' ); ?> <?php bloginfo( 'description' ); ?></title>
<link rel="stylesheet" href="<?php bloginfo( 'stylesheet_url' ); ?>" type="text/css"/>
<!-- Bootstrap core CSS -->
<link href="<?php bloginfo( 'stylesheet_directory' ); ?>/css/bootstrap.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="<?php bloginfo( 'stylesheet_directory' ); ?>/js/html5shiv.js"></script>
<script src="<?php bloginfo( 'stylesheet_directory' ); ?>/js/respond.min.js"></script>
<![endif]-->
<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>> <!-- http://codex.wordpress.org/Template_Tags/body_class -->
<header id="header">
<nav class="navbar navbar-bg navbar-inverse navbar-fixed-top" role="navigation">
<?php
// Fix menu overlap bug..
if ( is_admin_bar_showing() ) echo '<div style="min-height: 28px;"></div>';
?>
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo home_url(); ?>"><?php bloginfo('name'); ?></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<?php
wp_nav_menu( array(
'menu' => 'primary',
'theme_location' => 'primary',
'depth' => 5,
'container' => '',
'container_class' => '',
'menu_class' => 'nav navbar-nav no-float',
'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
'walker' => new wp_bootstrap_navwalker())
);
?>
</div>
</div>
</nav>
</header>
<div class="container">
|
92cc011d9cfe1d1bc34dfb20c26a0f3eac6d3b05
|
[
"Markdown",
"JavaScript",
"PHP"
] | 9
|
PHP
|
KunalGautam/WPBS
|
7ef637b497565e4a572ea20c3b4e61b73974092d
|
abb028f0b8962a1a54a536d4ada9b75004a5a9a0
|
refs/heads/master
|
<file_sep>import { inject, bindable } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Service } from './service';
@inject(Router, Service)
export class DataForm {
@bindable data = {};
@bindable error = {};
sources = [];
destinations = [];
item;
barcode;
qtyFg;
price;
firstPrice = 0;
indexSource = 0;
hasFocus = true;
constructor(router, service) {
this.router = router;
this.service = service;
}
sumTotalQty;
sumPrice;
getStorage(config) {
return new Promise((resolve, reject) => {
var getStorages = [];
if (config.source.type && config.source.type == "selection") {
for (var sourceId of config.source.value) {
getStorages.push(this.service.getStorageById(sourceId.toString()));
this.indexSource++;
}
}
else {
if (config.source.value) {
getStorages.push(this.service.getStorageById(config.source.value.toString()));
this.indexSource++
}
}
var getStoragesDestination = [];
if (config.destination.type && config.destination.type == "selection") {
for (var destinationId of config.destination.value) {
getStorages.push(this.service.getStorageById(destinationId.toString()));
}
}
else {
if (config.destination.value) {
getStorages.push(this.service.getStorageById(config.destination.value.toString()));
}
}
resolve(Promise.all(getStorages));
})
}
// constructor(router, service, bindingEngine) {
// this.router = router;
// this.service = service;
// this.bindingEngine = bindingEngine;
// this.service.getModuleConfig()
// .then(config => {
// var getStorages = [];
// var indexSource = 0;
// if (config.source.type == "selection") {
// for (var sourceId of config.source.value) {
// getStorages.push(this.service.getStorageById(sourceId.toString()));
// indexSource++;
// }
// }
// else {
// getStorages.push(this.service.getStorageById(config.source.value.toString()));
// indexSource++
// }
// var getStoragesDestination = [];
// if (config.destination.type == "selection") {
// for (var destinationId of config.destination.value) {
// getStorages.push(this.service.getStorageById(destinationId.toString()));
// }
// }
// else {
// getStorages.push(this.service.getStorageById(config.destination.value.toString()));
// }
// Promise.all(getStorages)
// .then(storages => {
// this.sources = storages.splice(0, storages.length - indexSource);
// this.destinations = storages.splice(0);
// this.data.sourceId = this.sources[0]._id;
// this.data.source = this.sources[0];
// this.data.destinationId = this.destinations[0]._id;
// this.data.destination = this.destinations[0];
// this.inventoryApiUri = require('../../host').inventory + '/storages/' + this.data.sourceId + '/inventories';
// })
// })
// .catch(e => {
// console.log(e)
// this.loadFailed = true;
// })
// }
// attached() {
// this.bindingEngine.collectionObserver(this.data.items)
// .subscribe(splices => {
// var item = this.data.items[splices[0].index];
// this.observeItem(item);
// });
// }
// observeItem(item) {
// this.bindingEngine.propertyObserver(item, "selection").subscribe((newValue, oldValue) => {
// item.articleVariantId = newValue._id;
// item.articleVariant = newValue.articleVariant;
// item.availableQuantity = newValue.availableQuantity;
// });
// }
async attached() {
this.sumTotalQty = 0;
this.sumPrice = 0;
var storages = await this.service.getModuleConfig();
var result = await this.getStorage(storages[0].config);
this.sources = result.splice(0, this.indexSource);
this.destinations = result.splice(0);
this.sources = this.sources.map(source => {
source.toString = function () {
return this.name;
}
return source;
})
this.destinations = this.destinations.map(destination => {
destination.toString = function () {
return this.name;
}
return destination;
})
}
async barcodeChoose(e) {
var itemData = e.target.value;
this.price = 0;
if (itemData && itemData.length >= 13) {
var fgTemp = await this.service.getByCode(itemData);
if (fgTemp != undefined) {
if (Object.getOwnPropertyNames(fgTemp).length > 0) {
var fg = fgTemp[0];
this.price = fg.domesticSale;
if (fg != undefined && Object.getOwnPropertyNames(fg).length > 0) {
var newItem = {};
var _data = this.data.items.find((item) => item.code === fg.code);
if (!_data) {
this.qtyFg = 0;
this.price = 0;
newItem.itemId = fg._id;
newItem.availableQuantity = 0;
var result = await this.service.getDataInventory(this.data.source._id, newItem.itemId);
if (result != undefined) {
newItem.availableQuantity = result.quantity;
}
newItem.name = fg.name;
newItem.code = fg.code;
this.qtyFg = this.qtyFg + 1;
newItem.quantity = 1;
newItem.price = parseFloat(fg.domesticSale)
newItem.remark = "";
this.data.items.push(newItem);
} else {
this.firstPrice = 0;
this.qtyFg = parseInt(_data.quantity) + 1;
this.firstPrice = this.qtyFg * this.price
_data.price = parseFloat(this.firstPrice)
_data.quantity = this.qtyFg;
}
}
}
}
this.makeTotal(this.data.items);
this.barcode = "";
}
}
async nameChoose(e) {
this.hasFocus = false;
var itemData = e.detail;
if (itemData != undefined) {
if (Object.getOwnPropertyNames(itemData).length > 0) {
var newItem = {};
var _data = this.data.items.find((item) => item.code === itemData.code);
if (!_data) {
this.qtyFg = 0;
this.price = 0;
newItem.itemId = itemData._id;
newItem.availableQuantity = 0;
var result = await this.service.getDataInventory(this.data.source._id, newItem.itemId);
if (result != undefined) {
newItem.availableQuantity = result.quantity;
}
newItem.name = itemData.name;
newItem.code = itemData.code;
newItem.quantity = 1;
this.qtyFg = this.qtyFg + 1;
this.price = itemData.domesticSale;
newItem.price = parseFloat(itemData.domesticSale);
newItem.remark = "";
this.data.items.push(newItem);
}
this.makeTotal(this.data.items);
this.item = null;
}
}
}
async qtyChange(code, qty) {
var barcode = code;
var quantity = qty;
this.price = 0;
if (quantity != undefined) {
var fgTemp = await this.service.getByCode(code);
var fg = fgTemp[0];
this.price = fg.domesticSale;
var newItem = {};
var _data = this.data.items.find((item) => item.code === barcode);
if (_data) {
this.price = parseInt(_data.quantity) * this.price
_data.price = parseFloat(this.price);
}
}
this.makeTotal(this.data.items);
}
makeTotal(items) {
debugger
this.sumTotalQty = 0;
this.sumPrice = 0;
if (Object.getOwnPropertyNames(items).length > 0) {
for (var i = 0; i < items.length; i++) {
this.sumTotalQty = this.sumTotalQty + parseInt(items[i].quantity);
this.sumPrice += items[i].price;
}
}
}
addItem() {
var item = {};
item.articleVariantId = '';
this.data.items.push(item);
}
removeItem(item) {
var itemIndex = this.data.items.indexOf(item);
this.data.items.splice(itemIndex, 1);
this.makeTotal(this.data.items);
}
map(result) {
return result.data.map(item => {
return {
_id: item.articleVariantId,
name: item.articleVariant.name,
articleVariant: item.articleVariant
}
});
}
// selectionSource() {
// this.inventoryApiUri = require('../../host').inventory + '/storages/' + this.data.sourceId + '/inventories';
// this.data.items = [];
// }
}
<file_sep>import { inject, Lazy, bindable } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Service } from './service';
@inject(Router, Service)
export class View {
@bindable data = {};
constructor(router, service) {
this.router = router;
this.service = service;
this.data = { spkDocuments: [] };
}
async activate(params) {
var id = params.id;
this.data = await this.service.getById(id);
this.data.expedition.toString = function(){
return this.name;
}
this.data.spkDocuments = this.data.spkDocuments.map(spk => {
spk.toString = function () {
return this.code
}
if (spk.items.length > 1) {
spk.quantity = spk.items.reduce((prev, curr) => prev.quantity + curr.quantity);
} else {
spk.quantity = spk.items[0].quantity;
}
return spk;
})
}
list() {
this.router.navigateToRoute('list');
}
print() {
console.log(this.data._id);
this.service.getPdfById(this.data._id);
}
}<file_sep>import { Container } from 'aurelia-dependency-injection';
import { Config } from "aurelia-api";
const resource = 'docs/efr-pk/expedition';
module.exports = function (keyword, filter) {
var config = Container.instance.get(Config);
var endpoint = config.getEndpoint("merchandiser");
return endpoint.find(resource, { keyword: keyword })
.then(results => {
return results.data.map(spk => {
spk.toString = function () {
return this.code
}
if (spk.items.length > 1) {
spk.quantity = spk.items.reduce((prev, curr) => prev.quantity + curr.quantity);
} else {
spk.quantity = spk.items[0].quantity;
}
return spk;
})
});
}<file_sep>import { inject, Lazy, bindable } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Service } from './service';
var FinishedGoodsLoader = require('../../../loader/finished-goods-loader');
@inject(Router, Service)
export class Upload {
@bindable data;
@bindable error;
contacts = [];
productFilter = {};
product;
dataSource = [];
dataDestination = [];
article_motif = {};
article_colors = [];
article_color = {};
color = "#FF0000";
ro = "";
columns = [
{ header: "", value: "check" },
{ header: "Code", value: "code" },
{ header: "Name", value: "name" }
]
constructor(router, service) {
this.router = router;
this.service = service;
this.data = { items: [] };
this.isNotRO = false;
this.isNotName = true;
this.service.getColors()
.then(result => {
this.article_colors = result.data.data;
if (this.article_colors.length > 0)
this.article_color = this.article_colors[0];
this.article_colors.forEach((s) => {
s.toString = function () {
return s.name;
}
});
})
}
controlOptions = {
label: {
length: 2,
align: "right"
},
control: {
length: 6
}
}
loaderSource = (info) => {
return this.dataSource;
}
check(e) {
if (e.keyCode == 13) {
this.service.searchByRo(this.ro)
.then((result) => {
this.deleteAll();
this.dataSource = result;
if (result) {
var firstResult = result[0];
this.service.getMotif(firstResult.code.substring(9, 11))
.then((motif) => {
if (motif) {
this.article_motif = motif.data;
}
})
}
})
return false;
} else {
return true;
}
}
updateType(e) {
this.deleteAll();
var type = e.target.value;
this.isNotRO = type != "ro";
this.isNotName = type != "name";
if (this.isNotRO)
this.ro = "";
if (this.isNotName)
this.name = "";
}
get finishedGoodsLoader() {
return FinishedGoodsLoader;
}
finishedGoodsChange(e) {
this.clearTable();
this.dataSource.push(this.product);
this.service.getMotif(this.product.code.substring(9, 11))
.then((motif) => {
if (motif) {
this.article_motif = motif.data;
}
})
}
changeColor(e) {
console.log(e);
}
deleteAll() {
this.clearTable();
}
moveRight() {
var filter = this.dataSource.filter(function (item) {
return item.check
});
this.dataDestination = this.dataDestination.concat(filter);
var temp = this.dataSource;
for (var item of filter) {
var i = this.dataSource.indexOf(item);
if (i != -1) {
temp.splice(i, 1);
}
}
this.dataSource = [].concat(temp);
}
moveLeft() {
var filter = this.dataDestination.filter(function (item) {
return item.check
});
this.dataSource = this.dataSource.concat(filter);
var temp = this.dataDestination;
for (var item of filter) {
var i = this.dataDestination.indexOf(item);
if (i != -1) {
temp.splice(i, 1);
}
}
this.dataDestination = [].concat(temp);
}
clearTable() {
this.dataSource = [];
this.dataDestination = [];
this.article_motif = {};
}
activate(params) {
}
select(contact) {
this.selectedId = contact.id;
return true;
}
list() {
this.router.navigateToRoute('list');
}
upload() {
var e = [];
var imageUpload = document.getElementById("imageUpload");
var fileList1 = imageUpload.files;
var motifUpload = document.getElementById("motifUpload");
var fileList2 = motifUpload.files;
if (fileList1[0] == undefined)
e["imageUpload"] = "Gambar harus dipilih"
if (fileList2[0] == undefined)
e["motifUpload"] = "Gambar motif harus dipilih"
if (this.dataDestination.length == 0) {
e["dataDestination"] = "Produk harus dipilih"
if (this.dataSource.length == 0) {
e["dataSource"] = "Tidak ada produk ditemukan"
}
}
if (Object.keys(e).length > 0) {
this.error = e;
} else {
var formData = new FormData();
formData.append("imageUpload", fileList1[0]);
formData.append("motifUpload", fileList2[0]);
// console.log(formData);
var endpoint = 'upload/image';
var request = {
method: 'POST',
headers: {
},
data: {
"products": this.dataDestination,
"color": this.color,
"article-color": this.article_color
},
body: formData
};
var promise = this.service.endpoint.client.fetch(endpoint, request)
this.service.publish(promise);
return promise.then(response => {
this.service.publish(promise);
if (response) {
return response.json().then(result => {
var data = {}
data.products = this.dataDestination;
data.colorCode = this.color;
data.articleColor = this.article_color;
data.imagePath = result.data[0];
data.motifPath = result.data[1];
this.service.updateProductImage(data)
.then(result2 => {
this.list();
}).catch(e => {
this.error = e;
});
});
} else {
return Promise.resolve({});
}
})
}
}
list() {
this.router.navigateToRoute('list');
}
}
<file_sep>module.exports = [
{
route: 'upload-file-pbj',
name: 'upload-file-pbj',
moduleId: './modules/upload-file-pbj/index',
nav: true,
title: 'Upload Packing List Barang Jadi ke Toko',
auth: true,
settings: {
group: "gudang pusat",
permission: { "GDG1": 1 },
iconClass: 'fa fa-bank'
}
},
{
route: 'upload-file-pba',
name: 'upload-file-pba',
moduleId: './modules/upload-file-pba/index',
nav: true,
title: 'Upload Packing List Embalase ke Toko',
auth: true,
settings: {
group: "gudang pusat",
permission: { "GDG1": 1 },
iconClass: 'fa fa-bank'
}
}
// ,
// {
// route: 'efr-tb-bbp',
// name: 'efr-tb-bbp',
// moduleId: './modules/efr-tb-bbp-cr/index',
// nav: true,
// title: 'Pemasukan Barang Jadi',
// auth: true,
// settings: {
// group: "gudang pusat",
// permission: { "GDG1": 1 },
// iconClass: 'fa fa-bank'
// }
// },
// {
// route: 'packingList',
// name: 'packingList',
// moduleId: './modules/packing-list-cr/index',
// nav: true,
// title: 'PackingList',
// auth: true,
// settings: {
// group: "gudang pusat",
// permission: { "GDG1": 1 },
// iconClass: 'fa fa-bank'
// }
// }
]
|
a4a9265a814b47c81713cfc84d788abf594f068e
|
[
"JavaScript"
] | 5
|
JavaScript
|
SirDimas/bateeq-ui
|
d50a909466c8211d45dbde581a920bdd56b611b3
|
4ae96165346b17f2985e3f7fd07b6ae2d126e679
|
refs/heads/main
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 09:10:20 2021
@author: Jonathan
"""
import pandas as pd
import time
import numpy as np
import matplotlib.pyplot as plt
from dateutil.parser import parse
import math
import tqdm
import tensorflow as tf
#import stock price dfs
dfamzn = pd.read_csv('data/30MinAMZN2yrs.csv', index_col=(0))
dfaapl = pd.read_csv('data/30MinAAPL2yrs.csv', index_col=(0))
dfgoog = pd.read_csv('data/30MinGOOG2yrs.csv', index_col=(0))
#change dates to workable datetimes
for j in range(len(dfamzn)):
dfamzn.loc[j,'date'] = parse(dfamzn['date'][j])
for j in range(len(dfaapl)):
dfaapl.loc[j,'date'] = parse(dfaapl['date'][j])
for j in range(len(dfgoog)):
dfgoog.loc[j,'date'] = parse(dfgoog['date'][j])
#import and prepare news df
def prepNews(ticker):
df = pd.read_csv('data/news'+str(ticker)+'2yrs.csv', index_col=(0))
for j in range(len(df)):
df['date'][j] = parse(df['date'][j])
df = df.drop_duplicates(subset='title', keep='last')
df = df[df.source != 'SEC']
df['description'] = df['description'].replace(np.nan, '')
return df.reset_index(drop=True)
dfamznNews = prepNews('AMZN')
dfaaplNews = prepNews('AAPL')
dfgoogNews = prepNews('GOOG')
#Use pretrained bert model to get sentiments for 'title' and 'description' of articles
from transformers import BertTokenizer, TFBertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('ProsusAI/finbert', from_pt=True)
model = TFBertForSequenceClassification.from_pretrained("ProsusAI/finbert", from_pt=True)
#or
tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
model = tf.keras.models.load_model("my_FinBERT_96289")
def sentScore(dfNews):
df = dfNews.copy()
df['pos'] = 0
df['neg'] = 0
df['neut'] = 0
df['pred'] = 0
MAX_LEN = 160
class_names = ['positive', 'negative', 'neutral']
i = 0
start = time.time()
for sentence in tqdm(df['title']):
encoded_new = tokenizer.encode_plus(
sentence,
add_special_tokens = True,
max_length = MAX_LEN,
truncation = True,
padding = 'max_length',
return_attention_mask = True,
return_tensors = 'tf',
)
input_idst = (encoded_new['input_ids'])
attention_maskst = (encoded_new['attention_mask'])
new_test_output = model(input_idst, token_type_ids=None,
attention_mask=attention_maskst)
predicted = new_test_output[0].numpy()
flat_predictions = np.concatenate(predicted, axis=0)
new_predictions = np.argmax(flat_predictions).flatten()
df.loc[i,'pos'] = predicted[0][0]
df.loc[i,'neg'] = predicted[0][1]
df.loc[i,'neut'] = predicted[0][2]
df.loc[i,'pred'] = class_names[new_predictions[0]]
i += 1
df['posDes'] = 0
df['negDes'] = 0
df['neutDes'] = 0
df['predDes'] = 0
i = 0
for sentence in df['description']:
encoded_new = tokenizer.encode_plus(
sentence,
add_special_tokens = True,
max_length = MAX_LEN,
truncation = True,
pad_to_max_length = True,
return_attention_mask = True,
return_tensors = 'tf',
)
input_idst = (encoded_new['input_ids'])
attention_maskst = (encoded_new['attention_mask'])
new_test_output = model(input_idst, token_type_ids=None,
attention_mask=attention_maskst)
predicted = new_test_output[0].numpy()
flat_predictions = np.concatenate(predicted, axis=0)
new_predictions = np.argmax(flat_predictions).flatten()
df.loc[i,'posDes'] = predicted[0][0]
df.loc[i,'negDes'] = predicted[0][1]
df.loc[i,'neutDes'] = predicted[0][2]
df.loc[i,'predDes'] = class_names[new_predictions[0]]
i += 1
finish = time.time()
totalTime = (finish - start)/60
print(totalTime)
return df
dfamznNewsWsent = sentScore(dfamznNews)
dfaaplNewsWsent = sentScore(dfaaplNews)
dfgoogNewsWsent = sentScore(dfgoogNews)
'''
dfamznNewsWsent = pd.read_csv('data/amznNewsWsent.csv')
dfaaplNewsWsent = pd.read_csv('data/aaplNewsWsent.csv')
dfgoogNewsWsent = pd.read_csv('data/googNewsWsent.csv')
'''
#create empty df and sort articles for each time step then get average
def dividingFunc(dfNewsWsent, dfStock):
NewsSortedTitle = np.zeros(shape=(len(dfamzn),500,3))
NewsSortedDescrip = np.zeros(shape=(len(dfamzn),500,3))
for i in range(len(dfStock)-1):
k = 0
for j in range(len(dfNewsWsent)):
if (parse(dfNewsWsent['date'][j]) < dfStock['date'][i+1]) and (parse(dfNewsWsent['date'][j]) > dfStock['date'][i]):
NewsSortedTitle[i,k]=np.array([dfNewsWsent['pos'][j],dfNewsWsent['neut'][j],dfNewsWsent['neg'][j]])
NewsSortedDescrip[i,k]=np.array([dfNewsWsent['posDes'][j],dfNewsWsent['neutDes'][j],dfNewsWsent['negDes'][j]])
k+=1
print(i)
#get averages of sentiments to use as features
tCnt = np.count_nonzero(NewsSortedTitle, axis=1)
tSum = np.sum(NewsSortedTitle, axis=1)
tAve = tSum/tCnt
dCnt = np.count_nonzero(NewsSortedDescrip, axis=1)
dSum = np.sum(NewsSortedDescrip, axis=1)
dAve = dSum/dCnt
#tAve = pd.DataFrame(tAve)
#dAve = pd.DataFrame(dAve)
return tAve, dAve, tCnt, dCnt, NewsSortedTitle, NewsSortedDescrip
amznSentInfo = dividingFunc(dfamznNewsWsent, dfamzn)
aaplSentInfo = dividingFunc(dfaaplNewsWsent, dfaapl)
googSentInfo = dividingFunc(dfgoogNewsWsent, dfgoog)
'''
amznSentInfo = pd.read_csv('data/amznInfo.csv', index_col=0)
aaplSentInfo = pd.read_csv('data/aaplInfo.csv', index_col=0)
googSentInfo = pd.read_csv('data/googInfo.csv', index_col=0)
def convertBack(df):
tAve = df[['tAvePos','tAveNeg','tAveNeut']].to_numpy()
dAve = df[['dAvePos','dAveNeg','dAveNeut']].to_numpy()
Cnt = np.reshape(np.array(df['Cnt']),(-1,1))
return [tAve,dAve,Cnt]
amznSentInfo = convertBack(amznSentInfo)
aaplSentInfo = convertBack(aaplSentInfo)
googSentInfo = convertBack(googSentInfo)
'''
#import stock vix's
vxamzn = pd.read_csv('data/vxamzndailyprices.csv', header=1)
vxamzn = vxamzn[2180:].reset_index(drop=True)
vxaapl = pd.read_csv('data/vxaapldailyprices.csv', header=1)
vxaapl = vxaapl[2180:].reset_index(drop=True)
vxgoog = pd.read_csv('data/vxgoogdailyprices.csv', header=1)
vxgoog = vxgoog[2180:].reset_index(drop=True)
#add vix and sentiment features to 30min stock df
def addingDailyFeatures(vxStock, dfStock, tAve, dAve, tCnt):
dfStock = dfStock.copy()
dfStock.loc[:,'vixOpen'] = 0
dfStock.loc[:,'vixHigh'] = 0
dfStock.loc[:,'vixLow'] = 0
dfStock.loc[:,'vixClose'] = 0
for i in range(len(dfStock)):
for j in range(len(vxStock)):
if dfStock.loc[i,'date'].date()==parse(vxStock.loc[j,'Date']).date():
dfStock.loc[i,'vixOpen'] = vxStock.loc[j,'Open']
dfStock.loc[i,'vixHigh'] = vxStock.loc[j,'High']
dfStock.loc[i,'vixLow'] = vxStock.loc[j,'Low']
dfStock.loc[i,'vixClose'] = vxStock.loc[j,'Close']
print(i)
break
dfStock['tPos'] = tAve[:,0]
dfStock['tNeg'] = tAve[:,1]
dfStock['tNeut'] = tAve[:,2]
dfStock['dPos'] = dAve[:,0]
dfStock['dNeg'] = dAve[:,1]
dfStock['dNeut'] = dAve[:,2]
dfStock['artCnt'] = tCnt[:,0]
return dfStock
dfamzn = addingDailyFeatures(vxamzn, dfamzn, amznSentInfo[0], amznSentInfo[1], amznSentInfo[2])
dfaapl= addingDailyFeatures(vxaapl, dfaapl, aaplSentInfo[0], aaplSentInfo[1], aaplSentInfo[2])
dfgoog = addingDailyFeatures(vxgoog, dfgoog, googSentInfo[0], googSentInfo[1], googSentInfo[2])
#add weekday features to df
def addWeekday(dfStock):
df = dfStock.copy()
df['weekday'] = 0
for i in range(len(df['date'])):
df.loc[i,'weekday'] = df['date'][i].weekday()
return df
dfamzn = addWeekday(dfamzn)
dfaapl = addWeekday(dfaapl)
dfgoog = addWeekday(dfgoog)
#read in spy and vix
dfspy = pd.read_csv('data/30MinSPY2yrs.csv', index_col=(0))
vxspy = pd.read_csv('data/VIX_NEW_YAHOO.csv')
vxspy = vxspy[743:].reset_index(drop=True)
#add vix to 30 min spy
def addingDailyVixToSpy(vxStock, dfStock):
dfStock = dfStock.copy()
dfStock.loc[:,'vixOpen'] = 0
dfStock.loc[:,'vixHigh'] = 0
dfStock.loc[:,'vixLow'] = 0
dfStock.loc[:,'vixClose'] = 0
for i in range(len(dfStock)):
for j in range(len(vxStock)):
if parse(dfStock.loc[i,'date']).date()==parse(vxStock.loc[j,'Date']).date():
dfStock.loc[i,'vixOpen'] = vxStock.loc[j,'Open']
dfStock.loc[i,'vixHigh'] = vxStock.loc[j,'High']
dfStock.loc[i,'vixLow'] = vxStock.loc[j,'Low']
dfStock.loc[i,'vixClose'] = vxStock.loc[j,'Close']
print(i)
break
return dfStock
dfspyWvix = addingDailyVixToSpy(vxspy, dfspy)
#Create return features and target columns
def creatingReturnFeat(dfStock):
df = dfStock.copy()
#create vix-based return features
df.loc[df.volume==0,'volume']=df['volume'].mean()
for i in range(len(df.vixOpen)):
df.loc[i,'vixRand'] = (np.random.random()*(df.loc[i,'vixHigh']-df.loc[i,'vixLow']))+df.loc[i,'vixLow']
df['vixAve'] = (df.vixHigh+df.vixLow)/2
vixTimestep = 14000
df['close_open'] = np.log(df.close/df.opn)/((df.vixRand/100)/math.sqrt(vixTimestep))
df['high_open'] = np.log(df.high/df.opn)/((df.vixRand/100)/math.sqrt(vixTimestep))
df['low_open'] = np.log(df.opn/df.low)/((df.vixRand/100)/math.sqrt(vixTimestep))
#create vix-based magnitude target
df['large'] = 0
df['small'] = 0
df['magnitude'] = abs(np.log(df.close/df.opn))/((df.vixRand/100)/math.sqrt(vixTimestep))
df.loc[(df.magnitude >= 0.675), 'large'] = 1
df.loc[(df.magnitude < 0.675), 'small'] = 1
for i in range(len(df['volume'])-1):
df.loc[i+1,'volPercent'] = np.log(df.loc[i+1,'volume']/df.loc[i,'volume'])
df['vixClose'] = df.vixClose/100
#create direction target
df['up'] = 0
df['down'] = 0
df.loc[(df.close_open >= 0), 'up'] = 1
df.loc[(df.close_open < 0), 'down'] = 1
return df
dfamzn = creatingReturnFeat(dfamzn)
dfaapl = creatingReturnFeat(dfaapl)
dfgoog = creatingReturnFeat(dfgoog)
dfspy = creatingReturnFeat(dfspyWvix)
#add spy to dfs and drop rows
def addSpy(dfStock, dfSpy=dfspy):
dfStock = dfStock.copy()
dfSpy = dfSpy.copy()
dfStock['spy_close_open'] = dfSpy['close_open']
dfStock['spy_high_open'] = dfSpy['high_open']
dfStock['spy_low_open'] = dfSpy['low_open']
dfStock['spy_vix'] = dfSpy['vixClose']
return dfStock
dfamzn = addSpy(dfamzn)
dfaapl = addSpy(dfaapl)
dfgoog = addSpy(dfgoog)
#shift target column and drop last row
def shiftTarget(dfStock):
df = dfStock.copy()
df['large'] = df['large'].shift(-1)
df['small'] = df['small'].shift(-1)
df['up'] = df['up'].shift(-1)
df['down'] = df['down'].shift(-1)
return df[78:(len(df)-1)].reset_index(drop=True)
#shift targets
dfamznShiftedTar = shiftTarget(dfamzn)
dfaaplShiftedTar = shiftTarget(dfaapl)
dfgoogShiftedTar = shiftTarget(dfgoog)
#split df into train/test
def trainTestSplit(dfStock):
df = dfStock.copy()
dfTrain = df[:4000]
dfTest = df[4000:]
return dfTrain, dfTest
dfamznTrain, dfamznTest = trainTestSplit(dfamznShiftedTar)
dfaaplTrain, dfaaplTest = trainTestSplit(dfaaplShiftedTar)
dfgoogTrain, dfgoogTest = trainTestSplit(dfgoogShiftedTar)
#combine train sets
def combTrainSet(*args):
frms = [*args]
combinedTrain = pd.concat(frms).reset_index(drop=True)
return combinedTrain
combinedTrain = combTrainSet(dfamznTrain, dfaaplTrain, dfgoogTrain)
#find value to fill na sentiment values
def naFunc(combTrainSet):
t_pos_neg_NAfill = ((combTrainSet['tPos']+combTrainSet['tNeg'])/2).min()
t_neut_NAfill = combTrainSet['tNeut'].max()
d_pos_neg_NAfill = ((combTrainSet['dPos']+combTrainSet['dNeg'])/2).min()
d_neut_NAfill = combTrainSet['dNeut'].max()
return t_pos_neg_NAfill, t_neut_NAfill, d_pos_neg_NAfill, d_neut_NAfill
t_pos_neg_NAfill, t_neut_NAfill, d_pos_neg_NAfill, d_neut_NAfill = naFunc(combinedTrain)
#fill Nan for missing sentiments - Train and Test
def fillNA(df):
df = df.copy()
df['tNeg'].fillna(t_pos_neg_NAfill, inplace=True)
df['tNeut'].fillna(t_neut_NAfill, inplace=True)
df['tPos'].fillna(t_pos_neg_NAfill, inplace=True)
df['dNeg'].fillna(d_pos_neg_NAfill, inplace=True)
df['dNeut'].fillna(d_neut_NAfill, inplace=True)
df['dPos'].fillna(d_pos_neg_NAfill, inplace=True)
return df
combinedTrainNoNa = fillNA(combinedTrain)
#build column transformer pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import MinMaxScaler, StandardScaler, OneHotEncoder
def createPipeline(combinedTrainNoNa):
dfTrain = combinedTrainNoNa.copy().drop(['large','small','up','down'], axis=1)
dfTrainTargets = combinedTrainNoNa.copy()[['large','small','up','down']]
sentiments = ['tNeg','tNeut','tPos','dNeg','dNeut','dPos']
logReturns = ['close_open','high_open','low_open','spy_close_open',
'spy_high_open', 'spy_low_open','volPercent']
weekday = ['weekday']
artCnt = ['artCnt']
vix = ['vixClose','spy_vix']
minmaxer = MinMaxScaler((-1,1))
full_pipeline = ColumnTransformer([
("sent", minmaxer, sentiments),
("artCnt", MinMaxScaler(), artCnt),
("ret", StandardScaler(), logReturns),
("weekday", OneHotEncoder(), weekday),
("pass", 'passthrough', vix)
])
transformedTrainSet = full_pipeline.fit_transform(dfTrain)
transformedTrainSet = transformedTrainSet, dfTrainTargets
return transformedTrainSet, full_pipeline
transformedTrainSet, full_pipeline = createPipeline(combinedTrainNoNa)
#prep and transform test sets
def prepTestData(dfTest):
df = dfTest.copy()
df = fillNA(df)
dfNoTarget = df.copy().drop(['large','small','up','down'], axis=1)
testTargets = df.copy()[['large','small','up','down']]
transformedTestSet = full_pipeline.transform(dfNoTarget)
return transformedTestSet, testTargets
amznTransformedTestSet = prepTestData(dfamznTest)
aaplTransformedTestSet = prepTestData(dfaaplTest)
googTransformedTestSet = prepTestData(dfgoogTest)
#split dfs into 3Dim samples
from numpy import array, vstack
from sklearn.utils import shuffle
def split_sequences(sequences, targets, n_steps):
X, y = list(), list()
for i in range(len(sequences)):
end_ix = i + n_steps
if end_ix > len(sequences):
break
seq_x, seq_y = sequences[i:end_ix, :], targets[end_ix-1, :]
X.append(seq_x)
y.append(seq_y)
return array(X), array(y)
n_steps = 5
#finish prep for RNN inputs and shuffle
def prepShuf(transformedTrainSet,amznTransformedTestSet,aaplTransformedTestSet,googTransformedTestSet,mag):
if mag==True:
x = 0
y = 2
else:
x = 2
y = 4
amznX, amznY = split_sequences(transformedTrainSet[0][:4000], (array(transformedTrainSet[1][:4000]))[:,x:y], n_steps=n_steps)
aaplX, aaplY = split_sequences(transformedTrainSet[0][4000:8000], (array(transformedTrainSet[1][4000:8000]))[:,x:y], n_steps=n_steps)
googX, googY = split_sequences(transformedTrainSet[0][8000:], (array(transformedTrainSet[1][8000:]))[:,x:y], n_steps=n_steps)
amznValX, amznValY = split_sequences(amznTransformedTestSet[0], (array(amznTransformedTestSet[1]))[:,x:y], n_steps=n_steps)
aaplValX, aaplValY = split_sequences(aaplTransformedTestSet[0], (array(aaplTransformedTestSet[1]))[:,x:y], n_steps=n_steps)
googValX, googValY = split_sequences(googTransformedTestSet[0], (array(googTransformedTestSet[1]))[:,x:y], n_steps=n_steps)
splitCombTrain = vstack((amznX,aaplX,googX))
splitCombTrainTargets = vstack((amznY,aaplY,googY))
Xshuffled, Yshuffled = shuffle(splitCombTrain, splitCombTrainTargets, random_state=37)
amznValShuffledX, amznValShuffledY = shuffle(amznValX, amznValY, random_state=41)
aaplValShuffledX, aaplValShuffledY = shuffle(aaplValX, aaplValY, random_state=41)
googValShuffledX, googValShuffledY = shuffle(googValX, googValY, random_state=41)
return Xshuffled, Yshuffled, amznValShuffledX, amznValShuffledY, aaplValShuffledX, aaplValShuffledY, googValShuffledX, googValShuffledY
preppedMagData = prepShuf(transformedTrainSet,amznTransformedTestSet,aaplTransformedTestSet,googTransformedTestSet,mag=True)
preppedDirData = prepShuf(transformedTrainSet,amznTransformedTestSet,aaplTransformedTestSet,googTransformedTestSet,mag=False)
#functions to evaluate models and learning curves
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score
from sklearn.metrics import precision_recall_curve, roc_curve, roc_auc_score
def evalModel(model, DataSet=preppedMagData):
u = model.predict(DataSet[6])
v = np.argmax(u, axis = 1)
w = np.argmax(np.array(DataSet[7]), axis=1)
print(confusion_matrix(w,v))
print("Accuracy:", accuracy_score(w,v))
print("F1:", f1_score(w,v))
print("Precision:", precision_score(w,v))
print("Recall:", recall_score(w,v))
print("AUC:", roc_auc_score(w,v))
def plotRocCurve(model, DataSet=preppedMagData):
v = model.predict(DataSet[6])[:,1]
w = np.argmax(np.array(DataSet[7]), axis=1)
fpr, tpr, thresholds = roc_curve(w, v)
plt.plot(fpr, tpr, linewidth=2, label=None)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate (Fall-Out)', fontsize=16)
plt.ylabel('True Positive Rate (Recall)', fontsize=16)
plt.grid(True)
def plotPrecRecall(model, DataSet=preppedMagData):
v = model.predict(DataSet[6])[:,1]
w = np.argmax(np.array(DataSet[7]), axis=1)
precisions, recalls, thresholds = precision_recall_curve(w, v)
plt.plot(recalls, precisions, "b-", linewidth=2)
plt.xlabel("Recall", fontsize=16)
plt.ylabel("Precision", fontsize=16)
plt.axis([0, 1, 0, 1])
plt.grid(True)
def plotLoss():
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('tain loss vs val loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
plt.show()
def plotAcc():
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('train acc vs val acc')
plt.ylabel('acc')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
plt.show()
#build, compile, and train models
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
n_features = preppedMagData[0].shape[2]
np.random.seed(37)
tf.random.set_seed(37)
opt = Adam(1e-5, clipvalue=1.0)
#build LSTM model
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(10, return_sequences=True, input_shape=[None, n_features]),
tf.keras.layers.LSTM(10),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Dense(2, activation='softmax')
])
#build GRU model
np.random.seed(37)
tf.random.set_seed(37)
model = tf.keras.models.Sequential([
tf.keras.layers.GRU(10, return_sequences=True, input_shape=[None, n_features]),
tf.keras.layers.GRU(10),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Dense(2, activation='softmax')
])
#build Conv1D model
np.random.seed(37)
tf.random.set_seed(37)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=20, kernel_size=2, strides=1, padding="valid", input_shape=[n_steps, n_features]),
#tf.keras.layers.GRU(20, return_sequences=True),
tf.keras.layers.GRU(20),
tf.keras.layers.Dense(2, activation='softmax')
])
#build WaveNet model
np.random.seed(37)
tf.random.set_seed(37)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.InputLayer(input_shape=[n_steps, n_features]))
for rate in (1, 2, 4, 8) * 2:
model.add(tf.keras.layers.Conv1D(filters=20, kernel_size=2, padding="causal",
activation="relu", dilation_rate=rate))
model.add(tf.keras.layers.GRU(20, return_sequences=True))
model.add(tf.keras.layers.GRU(20))
model.add(tf.keras.layers.Dense(2, activation='softmax'))
#compile and fit model
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=['accuracy'])
history = model.fit(x=preppedMagData[0], y=preppedMagData[1], epochs=40, validation_data=(preppedMagData[2],preppedMagData[3]), shuffle=(True), batch_size = 16)
plotLoss()
plotAcc()
evalModel(model)
plotRocCurve(model)
plotPrecRecall(model)
#Monte Carlo Dropout
tf.random.set_seed(42)
np.random.seed(42)
y_probs = np.stack([model(preppedMagData[6], training=True) for sample in range(100)])
y_probAve = y_probs.mean(axis=0)
y_std = y_probs.std(axis=0)
y_pred = np.argmax(y_probAve, axis=1)
#adjusting threshold
thresh=.70
z = model.predict(preppedMagData[6])
z1 = pd.DataFrame(z)
zz = np.array(preppedMagData[7])
z1['T'] = zz[:,0]
z1['F'] = zz[:,1]
z2 = z1.loc[(z1[0]>thresh) | (z1[1]>thresh)]
w = np.argmax(np.array(z2[['T','F']]), axis = 1)
v = np.argmax(np.array(z2[[0,1]]), axis = 1)
print(confusion_matrix(w,v))
print("Accuracy:", accuracy_score(w,v))
print("F1:", f1_score(w,v))
print("Precision:", precision_score(w,v))
print("Recall:", recall_score(w,v))
print("AUC:", roc_auc_score(w,v))
<file_sep># Stock_Price_Analysis
Analyzing absolute and directional stock price movement
API_DataPulls :
newsfilteriioPull.py - script to pull historical news data from newsfilter.io's API
polygonPull.py - script to pull historical stock price data from polygon.io's API
redditDataPull.py - script to pull historical reddit submissions data from pushshift.io (an API with historical reddit data)
DataPrep_AND_Models :
RNN_DataPrep.py - data preparation and models (RNNs, Conv1D, WaveNet)
non_RNN_DataPrep.py - data preparation and models (all others)
data - all data used for RNN_DataPrep.py and non_RNN_DataPrep.py
Financial_Sentiment_Analyzers :
Creating_A_FinBert - scripts that show how to fine-tune, save, and reload a BERT model for financial sentiment analysis (final model achieved over 96% accuracy on the Financial PhraseBank dataset)
HuggingFace_PreTrained_FinBERT - a pretrained and ready-to-go model for financial sentiment analysis from Hugging Face Transformers
(the output of either of these models can be used as inputs for both data prep/model files - RNN_DataPrep.py, non_RNN_DataPrep.py)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 17:09:24 2020
@author: Jonathan
"""
import json
import requests
import numpy as np
import time
import pandas as pd
#APIkey = Api key issued by polygon.io, free and paid versions available
APIkey='[API key]'
#request data - one day, 30 min bars, ohlc - 13 rows
def getPolygonData(after, ticker):
min30 = 1800000
timeFrame = 14*min30
def fire_away(after=after):
before = int(after)+timeFrame
before = str(before)
url = 'https://api.polygon.io/v2/aggs/ticker/{ticker}/range/30/minute/{after}/{before}?unadjusted=false&apiKey={APIkey}'.format(ticker=ticker, after=after, before=before, APIkey=APIkey)
print(url)
response = requests.get(url)
assert response.status_code == 200
data = json.loads(response.text)
return data
current_tries = 1
while current_tries < 6:
try:
time.sleep(.2)
response = fire_away()
return response
except:
time.sleep(.2)
current_tries += 1
return fire_away()
#loop through and record 13 lines of data for each day in given time period
def recordData(after, last, ticker):
start_time = time.time()
count = 0
opn, high, low, close, volume, epochDate = [], [], [], [], [], []
df = pd.DataFrame()
min30 = 1800000
oneDay = 86400000
while int(after) < int(last):
#account for daylight savings
if after in ('1667827800000','1636378200000','1604323800000', '1572874200000',
'1541424600000', '1509975000000', '1478525400000', '1446471000000',
'1415021400000'):
after = str(int(after)+(2*min30))
print('added one hour')
if after in ('1647181800000','1615732200000','1583677800000', '1552314600000',
'1520778600000', '1489329000000', '1457879400000', '1425825000000',
'1394375400000'):
after = str(int(after)-(2*min30))
print('subtracted one hour')
tries = 0
while tries < 2:
data = getPolygonData(after=after, ticker=ticker)
#ensure it is a full day of trading (no weekends, half days, or holidays)
if data['resultsCount'] < 13:
tries += 1
time.sleep(10)
else:
z = 0
length = 13
#record data
while z < length:
opn.append(data['results'][z]['o'])
high.append(data['results'][z]['h'])
low.append(data['results'][z]['l'])
close.append(data['results'][z]['c'])
volume.append(data['results'][z]['v'])
epochDate.append(data['results'][z]['t'])
z+=1
break
count
count+=1
print(count)
after = int(after)
after+=oneDay
after = str(after)
time.sleep(12)
#copy to dataframe
df['opn'] = opn
df['high'] = high
df['low'] = low
df['close'] = close
df['volume'] = volume
df['epochDate'] = epochDate
df['date'] = pd.to_datetime(df['epochDate'], unit='ms').dt.tz_localize('utc').dt.tz_convert('America/Los_Angeles')
end_time = time.time()
totalTime = (end_time-start_time)/60
#df.to_csv('30Min'+str(ticker)+'2yrs.csv')
return df, totalTime
df, totalTime = recordData('[starting_epoch_in_ms]', '[ending_epoch_in_ms]', '[stock_ticker]')
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Dec 12 10:59:14 2020
@author: Jonathan
"""
# Package used to execute HTTP POST request to the API
import json
import urllib.request
import pandas as pd
import time
import pytz
from dateutil.parser import parse
#format request
def newsFilterPull(frm, ticker, company, begin, end):
# API key
API_KEY = 'API_KEY'
# Define the filter parameters
queryString = "(title:{company} OR title:{ticker}) AND publishedAt:[{begin} TO {end}]".format(company=company,ticker=ticker,begin=begin,end=end)
payload = {
"type": "filterArticles",
"queryString": queryString,
"from": frm,
"size": 50
}
#establish and send request
jsondata = json.dumps(payload)
jsondataasbytes = jsondata.encode('utf-8')
API_ENDPOINT = "https://api.newsfilter.io/public/actions?token={}".format(API_KEY)
req = urllib.request.Request(API_ENDPOINT)
req.add_header('Content-Type', 'application/json; charset=utf-8')
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
res_body = response.read()
articles = json.loads(res_body.decode("utf-8"))
return articles
#looping and recording function
def createDateframe(frm, ticker, company, begin, end):
start_time = time.time()
date = []
title = []
desc = []
source = []
#create looping function
def loopingFunc(frm, ticker, company, begin, end):
y = frm + 1
#loop through articles pulling and recording 50 at a time
while frm < y:
time.sleep(2)
print('running - slowly but surely : ', frm)
articles = newsFilterPull(frm=frm, ticker=ticker, company=company, begin=begin, end=end)
l = 0
#record title, date, source, and description if it exists
while l < len(articles['articles']):
title.append(articles['articles'][l]['title'])
date.append(articles['articles'][l]['publishedAt'])
source.append(articles['articles'][l]['source']['name'])
try:
desc.append(articles['articles'][l]['description'])
except:
desc.append('')
l+=1
y = articles['total']['value']
frm += 50
#when at the end and if total exeeds 10,000 restart request with updated parameters
if (frm >= y) and (articles['total']['relation'] == 'gte'):
timestampStr = parse(date[-1]).strftime("%Y-%m-%d")
loopingFunc(frm=0, ticker=ticker, company=company, begin=begin, end=timestampStr)
#run looping func
loopingFunc(frm=frm,ticker=ticker,company=company,begin=begin,end=end)
#create dataframe and copy lists to dataframe
df = pd.DataFrame()
df['date'] = date
df['title'] = title
df['description'] = desc
df['source'] = source
#convert dates to same timezone
for j in range(len(df)):
df['date'][j] = parse(df['date'][j]).astimezone(pytz.timezone('America/Los_Angeles'))
end_time = time.time()
totalTime = (end_time-start_time)/60
#df.to_csv('news'+str(ticker)+'2yrs.csv')
return df, totalTime
df, totalTime = createDateframe(frm=0, ticker='GS', company='Goldman Sachs', begin='2019-03-08', end='2021-03-13')
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 09:10:20 2021
@author: Jonathan
"""
import pandas as pd
import time
import numpy as np
import matplotlib.pyplot as plt
from dateutil.parser import parse
import math
import tqdm
import tensorflow as tf
#import stock price dfs
dfamzn = pd.read_csv('data/30MinAMZN2yrs.csv', index_col=(0))
dfaapl = pd.read_csv('data/30MinAAPL2yrs.csv', index_col=(0))
dfgoog = pd.read_csv('data/30MinGOOG2yrs.csv', index_col=(0))
#change dates to workable datetimes
for j in range(len(dfamzn)):
dfamzn.loc[j,'date'] = parse(dfamzn['date'][j])
for j in range(len(dfaapl)):
dfaapl.loc[j,'date'] = parse(dfaapl['date'][j])
for j in range(len(dfgoog)):
dfgoog.loc[j,'date'] = parse(dfgoog['date'][j])
#import and prepare news df
def prepNews(ticker):
df = pd.read_csv('data/news'+str(ticker)+'2yrs.csv', index_col=(0))
for j in range(len(df)):
df['date'][j] = parse(df['date'][j])
df = df.drop_duplicates(subset='title', keep='last')
df = df[df.source != 'SEC']
df['description'] = df['description'].replace(np.nan, '')
return df.reset_index(drop=True)
dfamznNews = prepNews('AMZN')
dfaaplNews = prepNews('AAPL')
dfgoogNews = prepNews('GOOG')
#Use pretrained bert model to get sentiments for 'title' and 'description' of articles
from transformers import BertTokenizer, TFBertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('ProsusAI/finbert', from_pt=True)
model = TFBertForSequenceClassification.from_pretrained("ProsusAI/finbert", from_pt=True)
#or
tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
model = tf.keras.models.load_model("my_FinBERT_96289")
def sentScore(dfNews):
df = dfNews.copy()
df['pos'] = 0
df['neg'] = 0
df['neut'] = 0
df['pred'] = 0
MAX_LEN = 160
class_names = ['positive', 'negative', 'neutral']
i = 0
start = time.time()
for sentence in tqdm(df['title']):
encoded_new = tokenizer.encode_plus(
sentence,
add_special_tokens = True,
max_length = MAX_LEN,
pad_to_max_length = True,
return_attention_mask = True,
return_tensors = 'tf',
)
input_idst = (encoded_new['input_ids'])
attention_maskst = (encoded_new['attention_mask'])
new_test_output = model(input_idst, token_type_ids=None,
attention_mask=attention_maskst)
predicted = new_test_output[0].numpy()
flat_predictions = np.concatenate(predicted, axis=0)
new_predictions = np.argmax(flat_predictions).flatten()
df.loc[i,'pos'] = predicted[0][0]
df.loc[i,'neg'] = predicted[0][1]
df.loc[i,'neut'] = predicted[0][2]
df.loc[i,'pred'] = class_names[new_predictions[0]]
i += 1
df['posDes'] = 0
df['negDes'] = 0
df['neutDes'] = 0
df['predDes'] = 0
i = 0
for sentence in df['description']:
encoded_new = tokenizer.encode_plus(
sentence,
add_special_tokens = True,
max_length = MAX_LEN,
truncation = True,
padding = 'max_length',
return_attention_mask = True,
return_tensors = 'tf',
)
input_idst = (encoded_new['input_ids'])
attention_maskst = (encoded_new['attention_mask'])
new_test_output = model(input_idst, token_type_ids=None,
attention_mask=attention_maskst)
predicted = new_test_output[0].numpy()
flat_predictions = np.concatenate(predicted, axis=0)
new_predictions = np.argmax(flat_predictions).flatten()
df.loc[i,'posDes'] = predicted[0][0]
df.loc[i,'negDes'] = predicted[0][1]
df.loc[i,'neutDes'] = predicted[0][2]
df.loc[i,'predDes'] = class_names[new_predictions[0]]
i += 1
finish = time.time()
totalTime = (finish - start)/60
print(totalTime)
return df
dfamznNewsWsent = sentScore(dfamznNews)
dfaaplNewsWsent = sentScore(dfaaplNews)
dfgoogNewsWsent = sentScore(dfgoogNews)
'''
dfamznNewsWsent = pd.read_csv('data/amznNewsWsent.csv')
dfaaplNewsWsent = pd.read_csv('data/aaplNewsWsent.csv')
dfgoogNewsWsent = pd.read_csv('data/googNewsWsent.csv')
'''
#create empty df and sort articles for each time step then get average
def dividingFunc(dfNewsWsent, dfStock):
NewsSortedTitle = np.zeros(shape=(len(dfamzn),500,3))
NewsSortedDescrip = np.zeros(shape=(len(dfamzn),500,3))
for i in range(len(dfStock)-1):
k = 0
for j in range(len(dfNewsWsent)):
if (parse(dfNewsWsent['date'][j]) < dfStock['date'][i+1]) and (parse(dfNewsWsent['date'][j]) > dfStock['date'][i]):
NewsSortedTitle[i,k]=np.array([dfNewsWsent['pos'][j],dfNewsWsent['neut'][j],dfNewsWsent['neg'][j]])
NewsSortedDescrip[i,k]=np.array([dfNewsWsent['posDes'][j],dfNewsWsent['neutDes'][j],dfNewsWsent['negDes'][j]])
k+=1
print(i)
#get averages of sentiments to use as features
tCnt = np.count_nonzero(NewsSortedTitle, axis=1)
tSum = np.sum(NewsSortedTitle, axis=1)
tAve = tSum/tCnt
dCnt = np.count_nonzero(NewsSortedDescrip, axis=1)
dSum = np.sum(NewsSortedDescrip, axis=1)
dAve = dSum/dCnt
#tAve = pd.DataFrame(tAve)
#dAve = pd.DataFrame(dAve)
return tAve, dAve, tCnt, dCnt, NewsSortedTitle, NewsSortedDescrip
amznSentInfo = dividingFunc(dfamznNewsWsent, dfamzn)
aaplSentInfo = dividingFunc(dfaaplNewsWsent, dfaapl)
googSentInfo = dividingFunc(dfgoogNewsWsent, dfgoog)
'''
amznSentInfo = pd.read_csv('data/amznInfo.csv', index_col=0)
aaplSentInfo = pd.read_csv('data/aaplInfo.csv', index_col=0)
googSentInfo = pd.read_csv('data/googInfo.csv', index_col=0)
def convertBack(df):
tAve = df[['tAvePos','tAveNeg','tAveNeut']].to_numpy()
dAve = df[['dAvePos','dAveNeg','dAveNeut']].to_numpy()
Cnt = np.reshape(np.array(df['Cnt']),(-1,1))
return [tAve,dAve,Cnt]
amznSentInfo = convertBack(amznSentInfo)
aaplSentInfo = convertBack(aaplSentInfo)
googSentInfo = convertBack(googSentInfo)
'''
#import stock vix's
vxamzn = pd.read_csv('data/vxamzndailyprices.csv', header=1)
vxamzn = vxamzn[2180:].reset_index(drop=True)
vxaapl = pd.read_csv('data/vxaapldailyprices.csv', header=1)
vxaapl = vxaapl[2180:].reset_index(drop=True)
vxgoog = pd.read_csv('data/vxgoogdailyprices.csv', header=1)
vxgoog = vxgoog[2180:].reset_index(drop=True)
#add vix and sentiment features to 30min stock df
def addingDailyFeatures(vxStock, dfStock, tAve, dAve, tCnt):
dfStock = dfStock.copy()
dfStock.loc[:,'vixOpen'] = 0
dfStock.loc[:,'vixHigh'] = 0
dfStock.loc[:,'vixLow'] = 0
dfStock.loc[:,'vixClose'] = 0
for i in range(len(dfStock)):
for j in range(len(vxStock)):
if dfStock.loc[i,'date'].date()==parse(vxStock.loc[j,'Date']).date():
dfStock.loc[i,'vixOpen'] = vxStock.loc[j,'Open']
dfStock.loc[i,'vixHigh'] = vxStock.loc[j,'High']
dfStock.loc[i,'vixLow'] = vxStock.loc[j,'Low']
dfStock.loc[i,'vixClose'] = vxStock.loc[j,'Close']
print(i)
break
dfStock['tPos'] = tAve[:,0]
dfStock['tNeg'] = tAve[:,1]
dfStock['tNeut'] = tAve[:,2]
dfStock['dPos'] = dAve[:,0]
dfStock['dNeg'] = dAve[:,1]
dfStock['dNeut'] = dAve[:,2]
dfStock['artCnt'] = tCnt[:,0]
return dfStock
dfamzn = addingDailyFeatures(vxamzn, dfamzn, amznSentInfo[0], amznSentInfo[1], amznSentInfo[2])
dfaapl= addingDailyFeatures(vxaapl, dfaapl, aaplSentInfo[0], aaplSentInfo[1], aaplSentInfo[2])
dfgoog = addingDailyFeatures(vxgoog, dfgoog, googSentInfo[0], googSentInfo[1], googSentInfo[2])
#add weekday features to df
def addWeekday(dfStock):
df = dfStock.copy()
df['weekday'] = 0
for i in range(len(df['date'])):
df.loc[i,'weekday'] = df['date'][i].weekday()
return df
dfamzn = addWeekday(dfamzn)
dfaapl = addWeekday(dfaapl)
dfgoog = addWeekday(dfgoog)
#read in spy and vix
dfspy = pd.read_csv('data/30MinSPY2yrs.csv', index_col=(0))
vxspy = pd.read_csv('data/VIX_NEW_YAHOO.csv')
vxspy = vxspy[743:].reset_index(drop=True)
#add vix to 30 min spy
def addingDailyVixToSpy(vxStock, dfStock):
dfStock = dfStock.copy()
dfStock.loc[:,'vixOpen'] = 0
dfStock.loc[:,'vixHigh'] = 0
dfStock.loc[:,'vixLow'] = 0
dfStock.loc[:,'vixClose'] = 0
for i in range(len(dfStock)):
for j in range(len(vxStock)):
if parse(dfStock.loc[i,'date']).date()==parse(vxStock.loc[j,'Date']).date():
dfStock.loc[i,'vixOpen'] = vxStock.loc[j,'Open']
dfStock.loc[i,'vixHigh'] = vxStock.loc[j,'High']
dfStock.loc[i,'vixLow'] = vxStock.loc[j,'Low']
dfStock.loc[i,'vixClose'] = vxStock.loc[j,'Close']
print(i)
break
return dfStock
dfspyWvix = addingDailyVixToSpy(vxspy, dfspy)
#Create return features and target columns
def creatingReturnFeat(dfStock):
df = dfStock.copy()
#create vix-based return features
df.loc[df.volume==0,'volume']=df['volume'].mean()
for i in range(len(df.vixOpen)):
df.loc[i,'vixRand'] = (np.random.random()*(df.loc[i,'vixHigh']-df.loc[i,'vixLow']))+df.loc[i,'vixLow']
df['vixAve'] = (df.vixHigh+df.vixLow)/2
vixTimestep = 14000
df['close_open'] = np.log(df.close/df.opn)/((df.vixAve/100)/math.sqrt(vixTimestep))
df['high_open'] = np.log(df.high/df.opn)/((df.vixAve/100)/math.sqrt(vixTimestep))
df['low_open'] = np.log(df.opn/df.low)/((df.vixAve/100)/math.sqrt(vixTimestep))
#create vix-based magnitude target
df['large'] = 0
df['small'] = 0
df['magnitude'] = abs(np.log(df.close/df.opn))/((df.vixAve/100)/math.sqrt(vixTimestep))
df.loc[(df.magnitude >= 0.675), 'large'] = 1
df.loc[(df.magnitude < 0.675), 'small'] = 1
for i in range(len(df['volume'])-1):
df.loc[i+1,'volPercent'] = np.log(df.loc[i+1,'volume']/df.loc[i,'volume'])
df['vixClose'] = df.vixClose/100
#create direction target
df['up'] = 0
df['down'] = 0
df.loc[(df.close_open >= 0), 'up'] = 1
df.loc[(df.close_open < 0), 'down'] = 1
return df
dfamzn = creatingReturnFeat(dfamzn)
dfaapl = creatingReturnFeat(dfaapl)
dfgoog = creatingReturnFeat(dfgoog)
dfspy = creatingReturnFeat(dfspyWvix)
#add spy to dfs
def addSpy(dfStock, dfSpy=dfspy):
dfStock = dfStock.copy()
dfSpy = dfSpy.copy()
dfStock['spy_close_open'] = dfSpy['close_open']
dfStock['spy_high_open'] = dfSpy['high_open']
dfStock['spy_low_open'] = dfSpy['low_open']
dfStock['spy_vix'] = dfSpy['vixClose']
return dfStock
dfamzn = addSpy(dfamzn)
dfaapl = addSpy(dfaapl)
dfgoog = addSpy(dfgoog)
#shift target column and drop last row
def shiftTarget(dfStock):
df = dfStock.copy()
df['large'] = df['large'].shift(-1)
df['small'] = df['small'].shift(-1)
df['up'] = df['up'].shift(-1)
df['down'] = df['down'].shift(-1)
return df[78:(len(df)-1)].reset_index(drop=True)
dfamznShiftedTar = shiftTarget(dfamzn)
dfaaplShiftedTar = shiftTarget(dfaapl)
dfgoogShiftedTar = shiftTarget(dfgoog)
#split df into train/test
def trainTestSplit(dfStock):
df = dfStock.copy()
dfTrain = df[:4000]
dfTest = df[4000:]
return dfTrain, dfTest
dfamznTrain, dfamznTest = trainTestSplit(dfamznShiftedTar)
dfaaplTrain, dfaaplTest = trainTestSplit(dfaaplShiftedTar)
dfgoogTrain, dfgoogTest = trainTestSplit(dfgoogShiftedTar)
#combine train sets
def combTrainSet(*args):
frms = [*args]
combinedTrain = pd.concat(frms).reset_index(drop=True)
return combinedTrain
combinedTrain = combTrainSet(dfamznTrain, dfaaplTrain, dfgoogTrain)
#find value to fill na sentiment values
def naFunc(combTrainSet):
t_pos_neg_NAfill = ((combTrainSet['tPos']+combTrainSet['tNeg'])/2).min()
t_neut_NAfill = combTrainSet['tNeut'].max()
d_pos_neg_NAfill = ((combTrainSet['dPos']+combTrainSet['dNeg'])/2).min()
d_neut_NAfill = combTrainSet['dNeut'].max()
return t_pos_neg_NAfill, t_neut_NAfill, d_pos_neg_NAfill, d_neut_NAfill
t_pos_neg_NAfill, t_neut_NAfill, d_pos_neg_NAfill, d_neut_NAfill = naFunc(combinedTrain)
#fill Nan for missing sentiments - Train and Test
def fillNA(df):
df = df.copy()
df['tNeg'].fillna(t_pos_neg_NAfill, inplace=True)
df['tNeut'].fillna(t_neut_NAfill, inplace=True)
df['tPos'].fillna(t_pos_neg_NAfill, inplace=True)
df['dNeg'].fillna(d_pos_neg_NAfill, inplace=True)
df['dNeut'].fillna(d_neut_NAfill, inplace=True)
df['dPos'].fillna(d_pos_neg_NAfill, inplace=True)
return df
combinedTrainNoNa = fillNA(combinedTrain)
#inspect correlation matrix before splitting targets from features
corrMatrix = combinedTrainNoNa.corr()
#build column transformer pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import MinMaxScaler, StandardScaler, OneHotEncoder
def createPipeline(combinedTrainNoNa):
dfTrain = combinedTrainNoNa.copy().drop(['large','small','up','down'], axis=1)
dfTrainTargets = combinedTrainNoNa.copy()[['large','small','up','down']]
sentiments = ['tNeg','tNeut','tPos','dNeg','dNeut','dPos']
logReturns = ['close_open','high_open','low_open','spy_close_open',
'spy_high_open', 'spy_low_open','volPercent']
weekday = ['weekday']
artCnt = ['artCnt']
vix = ['vixClose','spy_vix']
minmaxer = MinMaxScaler((-1,1))
full_pipeline = ColumnTransformer([
("sent", minmaxer, sentiments),
("artCnt", MinMaxScaler(), artCnt),
("ret", StandardScaler(), logReturns),
("weekday", OneHotEncoder(), weekday),
("pass", 'passthrough', vix)
])
transformedTrainSet = full_pipeline.fit_transform(dfTrain)
transformedTrainSet = transformedTrainSet, dfTrainTargets
return transformedTrainSet, full_pipeline
transformedTrainSet, full_pipeline = createPipeline(combinedTrainNoNa)
#prep and transform test sets
def prepTestData(dfTest):
df = dfTest.copy()
df = fillNA(df)
dfNoTarget = df.copy().drop(['large','small','up','down'], axis=1)
testTargets = df.copy()[['large','small','up','down']]
transformedTestSet = full_pipeline.transform(dfNoTarget)
return transformedTestSet, testTargets
amznTransformedTestSet = prepTestData(dfamznTest)
aaplTransformedTestSet = prepTestData(dfaaplTest)
googTransformedTestSet = prepTestData(dfgoogTest)
#shuffle datasets
from sklearn.utils import shuffle
def shuffleData(tup):
shuffledData = shuffle(tup[0], tup[1], random_state=37)
return shuffledData
shufTrainSet = shuffleData(transformedTrainSet)
amznShufTestSet = shuffleData(amznTransformedTestSet)
aaplShufTestSet = shuffleData(aaplTransformedTestSet)
googShufTestSet = shuffleData(googTransformedTestSet)
preppedMagData = (shufTrainSet[0], np.array(shufTrainSet[1][['large','small']]),
amznShufTestSet[0], np.array(amznShufTestSet[1][['large','small']]),
aaplShufTestSet[0], np.array(aaplShufTestSet[1][['large','small']]),
googShufTestSet[0], np.array(googShufTestSet[1][['large','small']]))
preppedDirData = (shufTrainSet[0], np.array(shufTrainSet[1][['up','down']]),
amznShufTestSet[0], np.array(amznShufTestSet[1][['up','down']]),
aaplShufTestSet[0], np.array(aaplShufTestSet[1][['up','down']]),
googShufTestSet[0], np.array(googShufTestSet[1][['up','down']]))
#functions to evaluate models and learning curves
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score
from sklearn.metrics import precision_recall_curve, roc_curve, roc_auc_score
def evalModel(yTrue, yPred):
print(confusion_matrix(yTrue,yPred))
print("Accuracy:", accuracy_score(yTrue,yPred))
print("F1:", f1_score(yTrue,yPred))
print("Precision:", precision_score(yTrue,yPred))
print("Recall:", recall_score(yTrue,yPred))
def plotRocCurve(yTrue, yPred):
fpr, tpr, thresholds = roc_curve(yTrue, yPred)
plt.plot(fpr, tpr, linewidth=2, label=None)
plt.plot([0, 1], [0, 1], 'k--')
plt.axis([0, 1, 0, 1])
plt.xlabel('False Positive Rate (Fall-Out)', fontsize=16)
plt.ylabel('True Positive Rate (Recall)', fontsize=16)
plt.grid(True)
print("AUC:", roc_auc_score(yTrue,yPred))
def plotPrecRecall(yTrue, yPred):
precisions, recalls, thresholds = precision_recall_curve(yTrue, yPred)
plt.plot(recalls, precisions, "b-", linewidth=2)
plt.xlabel("Recall", fontsize=16)
plt.ylabel("Precision", fontsize=16)
plt.axis([0, 1, 0, 1])
plt.grid(True)
def plotLoss():
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('tain loss vs val loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
plt.show()
def plotAcc():
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('train acc vs val acc')
plt.ylabel('acc')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper right')
plt.show()
yTrue = np.argmax(preppedMagData[7], axis=1)
#logistic regression modle with grid search and cross validation
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
param_grid = [
{'solver': ['lbfgs'], 'penalty': ['l2'], 'C': [0.01,0.1,0.3,0.5,0.7,0.9,1]},
{'solver': ['liblinear'], 'penalty': ['l1'], 'C': [0.01,0.1,0.3,0.5,0.7,0.9,1]},
{'solver': ['saga'], 'penalty': ['elasticnet'], 'l1_ratio': [0,0.1,0.3,0.5,0.7,0.9,1]},
]
logReg = LogisticRegression(random_state=42, max_iter=2000)
logRegGS = GridSearchCV(logReg, param_grid, cv=5, scoring='accuracy', return_train_score=True)
logRegGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
logRegGS.best_params_
bestLogReg = logRegGS.best_estimator_
results = logRegGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestLogReg.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestLogReg.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, bestLogReg.decision_function(preppedMagData[6]))
#KNeighbors
from sklearn.neighbors import KNeighborsClassifier
param_grid = [
{'n_neighbors': [3,15,35,75,105,155,205]}
]
knn = KNeighborsClassifier()
knnGS = GridSearchCV(knn, param_grid, cv=5, scoring='accuracy', return_train_score=True)
knnGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
knnGS.best_params_
bestKnn = knnGS.best_estimator_
results = knnGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestKnn.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestKnn.predict_proba(preppedMagData[6])[:,1])
plotRocCurve(yTrue, bestKnn.predict_proba(preppedMagData[6])[:,1])
#SVM models - grid search with multiple kernels
from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
param_grid = [
{'kernel': ['linear'], 'C': [0.1, 0.5, 1, 5]},
{'kernel': ['rbf'], 'gamma': [0.1, 0.5, 1, 5], 'C': [0.1, 0.5, 1, 5]},
{'kernel': ['poly'], 'degree': [1, 3, 5],'coef0': [0.1, 0.5, 1, 5], 'C': [0.1, 0.5, 1, 5]}
]
SVCmod = SVC(probability=True)
SVCmodGS = GridSearchCV(SVCmod, param_grid, cv=5, scoring='accuracy', return_train_score=True)
SVCmodGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
SVCmodGS.best_params_
bestSVCmod = SVCmodGS.best_estimator_
results = SVCmodGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestSVCmod.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestSVCmod.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, bestSVCmod.decision_function(preppedMagData[6]))
#sgd svm
sgdSVM = SGDClassifier(max_iter=2000, random_state=42) #SGDClassifier with hinge loss (svm)
sgdSVM.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
evalModel(yTrue, sgdSVM.predict(preppedMagData[6]))
plotPrecRecall(yTrue, sgdSVM.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, sgdSVM.decision_function(preppedMagData[6]))
#build random forest model
from sklearn.ensemble import RandomForestClassifier
param_grid = [
{'n_estimators': [50,100,300,500,1000],'min_samples_split': [2,4,7,10],
'min_samples_leaf': [1,2,4,7,10,15,20]}
]
RF = RandomForestClassifier(random_state=42)
RFGS = GridSearchCV(RF, param_grid, cv=5, scoring='accuracy', return_train_score=True)
RFGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
RFGS.best_params_
bestRF = RFGS.best_estimator_
results = RFGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestRF.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestRF.predict_proba(preppedMagData[6])[:,1])
plotRocCurve(yTrue, bestRF.predict_proba(preppedMagData[6])[:,1])
#feature importance with random forest
columns = ['tNeg','tNeut','tPos','dNeg','dNeut','dPos', 'artCnt', 'close_open','high_open','low_open','spy_close_open',
'spy_high_open', 'spy_low_open','volPercent', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'vixClose','spy_vix']
for name, score in zip(columns, bestRF.feature_importances_):
print(name, score)
#Ada Boost
from sklearn.ensemble import AdaBoostClassifier
param_grid = [
{'n_estimators': [10, 100, 200, 500, 1000], 'learning_rate': [0.1, 0.5, 1, 5, 10]}
]
ada = AdaBoostClassifier(algorithm="SAMME.R", random_state=42)
adaGS = GridSearchCV(ada, param_grid, cv=5, scoring='accuracy', return_train_score=True)
adaGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
adaGS.best_params_
bestada = adaGS.best_estimator_
results = adaGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestada.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestada.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, bestada.decision_function(preppedMagData[6]))
#gradient boosting
from sklearn.ensemble import GradientBoostingClassifier
param_grid = [
{'n_estimators': [50, 200, 500, 1000], 'learning_rate': [0.1, 0.5, 1, 5],
'subsample': [0.1, 0.5, 1], 'max_depth': [2, 3], }
]
gbrt = GradientBoostingClassifier(random_state=42)
gbrtGS = GridSearchCV(gbrt, param_grid, cv=5, scoring='accuracy', return_train_score=True)
gbrtGS.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
gbrtGS.best_params_
bestgbrt = gbrtGS.best_estimator_
results = gbrtGS.cv_results_
dfResults = pd.DataFrame(results)
for mean_score, params in zip(results["mean_test_score"], results["params"]):
print(mean_score, params)
evalModel(yTrue, bestgbrt.predict(preppedMagData[6]))
plotPrecRecall(yTrue, bestgbrt.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, bestgbrt.decision_function(preppedMagData[6]))
#Voting Classifier with best model from each grid search
from sklearn.ensemble import VotingClassifier
logReg = LogisticRegression(random_state=42, max_iter=2000, C=0.7, penalty='l1', solver='liblinear')
knn = KNeighborsClassifier(n_neighbors=50)
RF = RandomForestClassifier(random_state=42, min_samples_leaf=2, min_samples_split=10, n_estimators=500)
SVCmod = SVC(probability=True, kernel='poly', degre=3, C=0.5, ceof0=0.5)
ada = AdaBoostClassifier(algorithm="SAMME.R", random_state=42, learning_rate=0.1, n_estimators=200)
gbrt = GradientBoostingClassifier(random_state=42, learning_rate=0.1, max_depth=3, n_estimators=50, subsample=1)
voting_clf = VotingClassifier(estimators=[('lr', logReg), ('knn', knn), ('RF', RF), ('ada', ada),
('gbrt', gbrt), ('SVCmod', SVCmod)], voting='soft')
voting_clf.fit(preppedMagData[0], np.argmax(preppedMagData[1], axis=1))
evalModel(yTrue, voting_clf.predict(preppedMagData[6]))
plotPrecRecall(yTrue, voting_clf.decision_function(preppedMagData[6]))
plotRocCurve(yTrue, voting_clf.decision_function(preppedMagData[6]))
#build, compile, and train Dense network
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
n_features = preppedMagData[0].shape[1]
np.random.seed(42)
tf.random.set_seed(42)
opt = Adam(1e-5)
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, input_shape=[n_features]),
tf.keras.layers.Dense(10),
tf.keras.layers.Dropout(.3),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(2, activation='softmax')
])
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=['accuracy'])
history = model.fit(x=preppedMagData[0], y=preppedMagData[1], epochs=50, validation_data=(preppedMagData[2],preppedMagData[3]), shuffle=(True), batch_size = 16)
evalModel(yTrue, np.argmax(model.predict(preppedMagData[6]),axis=1))
plotPrecRecall(yTrue, model.predict(preppedMagData[6])[:,1])
plotRocCurve(yTrue, model.predict(preppedMagData[6])[:,1])
plotLoss()
plotAcc()
#Monte Carlo Dropout
tf.random.set_seed(42)
np.random.seed(42)
y_probs = np.stack([model(preppedMagData[6], training=True) for sample in range(100)])
y_probAve = y_probs.mean(axis=0)
y_std = y_probs.std(axis=0)
y_pred = np.argmax(y_probAve, axis=1)
#adjusting threshold
thresh=.70
z = model.predict(preppedMagData[6])
z1 = pd.DataFrame(z)
zz = np.array(preppedMagData[7])
z1['T'] = zz[:,0]
z1['F'] = zz[:,1]
z2 = z1.loc[(z1[0]>thresh) | (z1[1]>thresh)]
w = np.argmax(np.array(z2[['T','F']]), axis = 1)
v = np.argmax(np.array(z2[[0,1]]), axis = 1)
print(confusion_matrix(w,v))
print("Accuracy:", accuracy_score(w,v))
print("F1:", f1_score(w,v))
print("Precision:", precision_score(w,v))
print("Recall:", recall_score(w,v))
print("AUC:", roc_auc_score(w,v))
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Oct 15 10:57:14 2020
@author: Jonathan
"""
import math
import json
import requests
import numpy as np
import time
import pandas as pd
start_time = time.time()
df = pd.read_csv('spy_30Min2yrsNum2.csv')
title = [[]]*20
doc_count = [[]]*20
beforelist = []
afterlist = []
df2 = pd.DataFrame()
def getPushshiftData(after, before, subred):
def fire_away(after=after, before=before, subred=subred):
url = 'https://api.pushshift.io/reddit/search/comment/?subreddit='+str(subred)+'&after='+str(after)+'&before='+str(before)+'&sort=desc&aggs=link_id'
response = requests.get(url)
assert response.status_code == 200
data = json.loads(response.content)
return data
current_tries = 1
while current_tries < 5:
try:
time.sleep(.3)
response = fire_away()
return response
except:
time.sleep(.3)
current_tries += 1
return fire_away()
def loopDayData(after, before, numPerDay, subred):
tries = 1
while tries < 5:
data = getPushshiftData(after = after, before = before, subred = subred)
if type(data['aggs']['link_id']) is not list:
tries += 1
time.sleep(10)
else:
break
beforelist.append(before)
afterlist.append(after)
l=0
while l < numPerDay:
if l < len(data['aggs']['link_id']):
print('l', l)
title[l].append(data['aggs']['link_id'][l]['data']['title'])
doc_count[l].append(data['aggs']['link_id'][l]['doc_count'])
l+=1
else:
print('l', l)
title[l].append('nan')
doc_count[l].append(0)
l+=1
def multiDayLoop(numPerDay, subred):
y=0
while y < (len(df['epochDate'])-1):
print('y' , y)
after = ((df['epochDate'][y])/1000)
after = math.trunc(after)
after = str(after)
before = ((df['epochDate'][y+1])/1000)
before = math.trunc(before)
before = str(before)
loopDayData(after = after, before = before, numPerDay=numPerDay, subred=subred)
time.sleep(.3)
y+=1
def loopAndCreateDF(numPerDay, subred):
global df2
multiDayLoop(numPerDay=numPerDay, subred=subred)
df2['afterEpoch'] = afterlist
df2['after'] = pd.to_datetime(df2['afterEpoch'], unit='s').dt.tz_localize('utc').dt.tz_convert('America/Los_Angeles')
df2['beforeEpoch'] = beforelist
df2['before'] = pd.to_datetime(df2['beforeEpoch'], unit='s').dt.tz_localize('utc').dt.tz_convert('America/Los_Angeles')
e = 0
while e < numPerDay:
df2['art'+str(e)] = title[e]
df2['cnt'+str(e)] = doc_count[e]
e += 1
df2.loc[len(df)] = 0
df2 = df2.shift(1)
df2.to_csv('red'+str(subred)+'.csv')
loopAndCreateDF(20, 'politics')
print("--- %s seconds ---" % (time.time() - start_time))
|
af4c8fa570f5609ff06181d4fd68fc51365393f8
|
[
"Markdown",
"Python"
] | 6
|
Python
|
JTisch7/Stock_Price_Analysis
|
dcde77bc00b2a89c0efe5ab2988dfafca1a5c65b
|
40e2a0f567e364d678a5b42b4cf1d9f5e836b941
|
refs/heads/main
|
<repo_name>Xanos20/Linux_Kernel_Modules<file_sep>/SPI_Driver_With_Netlink_User_Kernel_Communication/Readme.txt
README.txt
<NAME>
1209035928
Instructions:
1)
In the genl_ex directory type "make"
2)
The default IO Pins Are
- Trigger = 7
- Echo = 4
- Chip Select = 8
- To change this configuration, when you are about to run ./genl_ex ...
./genl_ex -c <IO_chip_select> -d <distance counter> -e <IO_echo> -t <IO_trigger>
3)
Load the following modules in any order
- insmod driver_spi_nl.ko
- insmod spidev_device.ko
4)
Run ./genl_ex (with optional flags)
5)
To remove modules...
- rmmod driver_spi_nl.ko
- rmmod spidev_device.ko
Note:
ELF binaries are included in case source files were deleted in preparing to put them in the zip file
ADDITIONAL INFO
1)
The pattern consists of a civil war type battle where soldiers line up in columns to face the enemy
2)
From the north end, the soldiers continue to move south against enemy positions
3)
Some soldier lines will fall and others will take their place
The time that it takes to replenish the ranks is dependent on sensor distance measurements (an increase in change of distance leads to an increase in time and vice versa)
4)
Eventually the north soldiers will capture around half of the battlefield
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/Sample_platform_device.c
/*
* A sample program to show the binding of platform driver and device.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include<linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include "Sample_platform_device.h"
struct list_head device_list;
LIST_HEAD(device_list);
static int NUMBER_OF_DEVICES = 2;
module_param(NUMBER_OF_DEVICES,int,0000);
static void torelease(struct device* device) {
return;
}
/*
static struct P_chip P1_chip = {
.name = "xyz01",
.dev_no = 1,
.plf_dev = {
.name = "plat_1",
.id = -1,
.dev = {.release = torelease,}
}
};
static struct P_chip P2_chip = {
.name = "xyz02",
.dev_no = 2,
.plf_dev = {
.name = "plat_2",
.id = -1,
.dev = {.release = torelease,}
}
};
*/
/*
static struct P_chip P3_chip = {
.name = "xyz03",
.dev_no = 3,
.plf_dev = {
.name = "plat_3",
.id = -1,
.dev = {.release = torelease,}
}
};
static struct P_chip P4_chip = {
.name = "xyz04",
.dev_no = 4,
.plf_dev = {
.name = "plat_4",
.id = -1,
.dev = {.release = torelease,}
}
};
static struct P_chip P5_chip = {
.name = "xyz05",
.dev_no = 5,
.plf_dev = {
.name = "plat_5",
.id = -1,
.dev = {.release = torelease,}
}
};
*/
/*
static struct P_chip P3_chip = {
.name = "xyz03",
.dev_no = 55,
.plf_dev = {
.name = "defg",
.id = -1,
.dev = {.release = torelease,}
}
};
*/
#define DEV1 "plat_1"
#define DEV2 "plat_2"
#define DEV3 "plat_3"
#define DEV4 "plat_4"
#define DEV5 "plat_5"
#define DEV6 "plat_6"
static int p_device_init(void)
{
int ret = 0;
int i;
struct P_chip* chip;
printk("INFO: NUMBER_OF_DEVICES=%d\n", NUMBER_OF_DEVICES);
if(NUMBER_OF_DEVICES <= 0) {
return -1;
}
if(NUMBER_OF_DEVICES > 6) {
NUMBER_OF_DEVICES = 6;
}
//char name[7] = {'p', 'l', 'a', 't', '_', '1', '\0'};
for(i=0; i < NUMBER_OF_DEVICES; i++) {
// Allocate new P_chip for each iteration
printk("VAR: i=%d\n", i);
printk("TRY: Allocate New Chip\n");
chip = kmalloc(sizeof(struct P_chip), GFP_KERNEL);
if(!chip) {
printk("ERROR: Kmalloc failed for %d\n", i);
}
memset(chip, 0, sizeof(struct P_chip));
if(i == 0) {
printk("TRY: Set fields for i=0\n");
chip->name = DEV1;
printk("TRY: Set plfdev\n");
chip->plf_dev.name = DEV1;
}
else if(i == 1) {
chip->name = DEV2;
chip->plf_dev.name = DEV2;
}
else if(i == 2) {
chip->name = DEV3;
chip->plf_dev.name = DEV3;
}
else if(i == 3) {
chip->name = DEV4;
chip->plf_dev.name = DEV4;
}
else if(i == 4) {
chip->name = DEV5;
chip->plf_dev.name = DEV5;
}
else {
chip->name = DEV6;
chip->plf_dev.name = DEV6;
}
printk("TRY: Set more device fields\n");
chip->dev_no = i;
chip->plf_dev.id = -1;
chip->plf_dev.dev.release = torelease;
printk("TRY: Register device\n");
platform_device_register(&chip->plf_dev);
printk("TRY: Add to list\n");
list_add_tail(&(chip->list_ptr), &device_list);
}
return ret;
}
static void p_device_exit(void)
{
struct P_chip* device;
struct P_chip* tmp;
list_for_each_entry_safe(device, tmp, &device_list, list_ptr) {
printk("TRY: Found Device\n");
platform_device_unregister(&device->plf_dev);
memset(device, 0, sizeof(struct P_chip));
kfree(device);
}
printk(KERN_ALERT "Goodbye, unregister the device\n");
}
/**
* register the device when module is initiated
*/
/*
static int p_device_init(void)
{
int ret = 0;
int i;
LIST_HEAD(DEVICE_LIST);
// Register the device
platform_device_register(&P1_chip.plf_dev);
printk(KERN_ALERT "Platform device 1 is registered in init \n");
platform_device_register(&P2_chip.plf_dev);
printk(KERN_ALERT "Platform device 2 is registered in init \n");
char name[7] = {'H', 'C', 'S', 'R', '_', '1', '\0'};
printk("INFO: NUMBER_OF_DEVICES=%d\n", NUMBER_OF_DEVICES);
if(NUMBER_OF_DEVICES <= 0 || NUMBER_OF_DEVICES > 9) {
return -1;
}
return ret;
}
*/
/*
static void p_device_exit(void)
{
platform_device_unregister(&P1_chip.plf_dev);
platform_device_unregister(&P2_chip.plf_dev);
printk(KERN_ALERT "Goodbye, unregister the device\n");
}
*/
module_init(p_device_init);
module_exit(p_device_exit);
MODULE_LICENSE("GPL");
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part1_With_Binaries/ioctl.h
#define CONFIG_PINS 0
#define SET_PARAMETERS 1
struct sampling_params_from_user {
int num_samples;
int period;
};
struct pin_params_from_user {
int trigger;
int echo;
};<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/Sample_platform_driver.c
/*
* A sample program to show the binding of platform driver and device.
*/
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include "Sample_platform_device.h"
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include "hcsr.h"
#include <linux/sysfs.h>
#include <linux/uaccess.h>
#include <asm/msr.h>
#define DRIVER_NAME "platform_driver_0"
#define DEVICE_NAME "PLAT_HCSR"
/*
static struct class_atrribute hcsr_class_attrs[] = {
};
*/
static struct class HCSR_CLASS = {
.name = "HCSR",
.owner = THIS_MODULE,
//.class_attrs = hcsr_class_attrs,
};
static dev_t dev_major = 12;
// Driver workqueue for all devices
static struct workqueue_struct* my_wq;
static const struct platform_device_id P_id_table[] = {
{ "plat_1", 0 },
{ "plat_2", 0 },
{ "plat_3", 0 },
{ "plat_4", 0 },
{ "plat_5", 0 },
{ "plat_6", 0 },
{ },
};
//====================================================================================
// Determines whether to add a new class that each device created by module is initialized under
static bool class_enabled = false;
// The global list that holds each created hcsr_dev device
struct list_head device_list;
LIST_HEAD(device_list);
//====================================================================================
int hcsr_driver_open(struct inode *inode, struct file *file)
{
struct hcsr_dev *hcsr_devps;
/* Get the per-device structure that contains this cdev */
//hcsr_devps = container_of(inode->i_cdev, struct hcsr_dev, cdev);
int minor_number = iminor(inode);
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
printk("\n%s is openning \n", hcsr_devps->misc.name);
return 0;
}
}
printk("ERROR: Could not find device\n");
return -1;
}
/*
* Release hcsr driver
*/
int hcsr_driver_release(struct inode *inode, struct file *file)
{
struct hcsr_dev *hcsr_devps = file->private_data;
printk("\n%s is closing\n", hcsr_devps->name);
return 0;
}
// TRIGGER PARSING ==================================================================================================
/*
Set corresponding trigger pin sequence based on user chosen IO trigger pin
*/
long set_trigger_pins(struct hcsr_dev *hcsr_devps) {
int ret;
int io_trig = hcsr_devps->trigger;
if(io_trig == 0) {
printk("TRY: Request gpio11, gpio33\n");
// 11
ret = gpio_request(11, "gpio11");
if(ret != 0) {
printk("ERROR: gpio11\n");
return -1;
}
ret = gpio_direction_output(11, 0);
if(ret != 0) {
printk("ERROR: gpio11 direction\n");
return -1;
}
hcsr_devps->gpio_trigger = 11;
// 33
ret = gpio_request(33, "gpio33");
if(ret != 0) {
printk("ERROR: gpio33\n");
return -1;
}
ret = gpio_direction_output(33, 0);
if(ret != 0) {
printk("ERROR: gpio33 output\n");
return -1;
}
}
else if(io_trig == 1) {
printk("TRY gpio12, gpio28, gpio45\n");
// 12
ret = gpio_request(12, "gpio12");
if(ret != 0) {
printk("ERROR: gpio12\n");
return -1;
}
ret = gpio_direction_output(12, 0);
if(ret != 0) {
printk("ERROR: gpio12 output\n");
return -1;
}
hcsr_devps->gpio_trigger = 12;
// 28
ret = gpio_request(28, "gpio28");
if(ret != 0) {
printk("ERROR\n");
return -1;
}
ret = gpio_direction_output(28, 0);
if(ret != 0) {
return -1;
}
// 45
ret = gpio_request(45, "gpio45");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(45, 0);
if(ret != 0) {
return -1;
}
}
else if(io_trig == 4) {
printk("TRY: gpio6, gpio36\n");
// 6
ret = gpio_request(6, "gpio6");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(6, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 6;
// 36
ret = gpio_request(36, "gpio36");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(36, 0);
if(ret != 0) {
return -1;
}
}
else if(io_trig == 5) {
printk("TRY: gpio0, gpio18, gpio66\n");
// 0
ret = gpio_request(0, "gpio0");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(0, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 0;
// 18
ret = gpio_request(18, "gpio18");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(18, 0);
if(ret != 0) {
return -1;
}
// 66
ret = gpio_request(66, "gpio66");
if(ret != 0) {
return -1;
}
gpio_set_value_cansleep(66, 0);
}
else if(io_trig == 6) {
printk("TRY: gpio1, gpio20, gpio68\n");
// 1
ret = gpio_request(1, "gpio1");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(1, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 1;
// 20
ret = gpio_request(20, "gpio20");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(20, 0);
if(ret != 0) {
return -1;
}
// 68
ret = gpio_request(68, "gpio68");
if(ret != 0) {
return -1;
}
gpio_set_value_cansleep(68, 0);
}
else if(io_trig == 7) {
printk("TRY: gpio38\n");
// 38
ret = gpio_request(38, "gpio38");
if(ret != 0) {
gpio_free(38);
ret = gpio_request(38, "gpio38");
if(ret != 0) {
printk("ERROR: gpio38\n");
return -1;
}
}
ret = gpio_direction_output(38, 0);
if(ret != 0) {
printk("ERROR: gpio38 direction out\n");
return -1;
}
hcsr_devps->gpio_trigger = 38;
printk("SUCCESS: gpio38\n");
}
else if(io_trig == 8) {
printk("TRY: gpio40\n");
// 40
ret = gpio_request(40, "gpio40");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(40, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 40;
}
else {
}
printk("SUCCESS: Trigger Pin setup\n");
hcsr_devps->trigger_enabled = true;
return 0;
}
// ECHO INTERRUPT AND PARSING ==============================================================================================
/*
Assembly code to get the Time Stamp Counter
*/
static __always_inline unsigned long long get_native_read_tsc_here(void) {
DECLARE_ARGS(val, low, high);
asm volatile("rdtsc" : EAX_EDX_RET(val, low, high));
return (unsigned long long) EAX_EDX_VAL(val, low, high);
}
/*
INFO: the echo pin interrupt handler, should be initialized as a rising edge first
and should be activated first when echo pin becomes high in the thread function
ACTION: Should write the start and end time stamp counters of the sensor measurement into the internal buffer
*/
irqreturn_t irq_echo_handler(int irq, void* dev_id) {
struct hcsr_dev* hcsr_devps;
hcsr_devps = (struct hcsr_dev*) dev_id;
//printk("INFO: In Interrupt\n");
// LOCK: to prevent race conditions in the internal buffer and irq flag
spin_lock_irqsave(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
if(irq == hcsr_devps->irq_desc_echo) {
// Verify this the correct irq number
if(hcsr_devps->irq_is_rising) {
// RISING EDGE
//printk("INFO: RISING\n");
// Write timestamp of start of sensor measurement
hcsr_devps->cursor->tsc_rising = get_native_read_tsc_here();
// Change trigger for falling edge
irq_set_irq_type(irq, IRQ_TYPE_EDGE_FALLING);
// update flag
hcsr_devps->irq_is_rising = false;
}
else if(hcsr_devps->irq_is_rising == false) {
// FALLING EDGE
//printk("INFO: FALLING\n");
// Write timestamp of start of sensor measurement
hcsr_devps->cursor->tsc_falling = get_native_read_tsc_here();
// Change irq type back to rising
irq_set_irq_type(irq, IRQ_TYPE_EDGE_RISING);
// update flag
hcsr_devps->irq_is_rising = true;
}
else {
// Ignore interrupt
}
}
else {
// Different IRQ Number
}
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return IRQ_HANDLED;
}
/*
Setup new interrupt for the gpio echo pin that is the first one for respective IO shield pin
*/
int setup_echo_pin_interrupt(struct hcsr_dev* hcsr_devps) {
int verify_irq;
// Request new interrupt line
hcsr_devps->irq_desc_echo = gpio_to_irq(hcsr_devps->gpio_echo);
if(hcsr_devps->irq_desc_echo < 0) {
printk("ERROR=%d: gpio_to_irq\n", hcsr_devps->irq_desc_echo);
return -1;
}
// Request interrupt for gpio_echo, the interrupt is first triggered at a rising edge (gpio_trig value goes from 0 to 1)
verify_irq = request_irq(hcsr_devps->irq_desc_echo, (irq_handler_t) irq_echo_handler, IRQF_TRIGGER_RISING, hcsr_devps->misc.name, (void*) hcsr_devps);
if(verify_irq != 0) {
printk("ERROR=%d: request_irq", verify_irq);
return -1;
}
printk("SUCCESS: Interrupt Requested\n");
hcsr_devps->has_interrupt = true;
return 0;
}
long set_echo_pins(struct hcsr_dev *hcsr_devps) {
//int ver;
int ret;
//int c;
int io_echo = hcsr_devps->echo;
if(io_echo == 4) {
printk("TRY: Setting up gpio6 & gpio36\n");
// 6
ret = gpio_request(6, "gpio6");
if(ret != 0) {
printk("ERROR: gpio6\n");
return -1;
}
ret = gpio_direction_input(6);
if(ret != 0) {
printk("ERROR: gpio6 direction input\n");
return -1;
}
// 36
ret = gpio_request(36, "gpio36");
if(ret != 0) {
printk("ERROR: gpio36");
return -1;
}
ret = gpio_direction_output(36, 1);
if(ret != 0) {
printk("ERROR: gpio36 direction out\n");
return -1;
}
// For interrupts
hcsr_devps->gpio_echo = 6;
}
else if(io_echo == 5) {
printk("TRY: Setting up gpio0, gpio18, gpio66\n");
// 0
ret = gpio_request(0, "gpio0");
if(ret != 0) {
printk("ERROR: gpio0\n");
return -1;
}
ret = gpio_direction_input(0);
if(ret != 0) {
printk("ERROR: gpio0 input\n");
return -1;
}
// 18
ret = gpio_request(18, "gpio18");
if(ret != 0) {
printk("ERROR: gpio18\n");
return -1;
}
ret = gpio_direction_output(18, 1);
if(ret != 0) {
printk("ERROR: gpio18 direction\n");
return -1;
}
// 66
ret = gpio_request(66, "gpio66");
if(ret != 0) {
printk("ERROR: gpio66\n");
return -1;
}
gpio_set_value_cansleep(66, 0);
// For interrupts
hcsr_devps->gpio_echo = 0;
}
else if(io_echo == 6) {
printk("TRY: Setting up gpio1, gpio20, gpio68\n");
// 1
ret = gpio_request(1, "gpio1");
if(ret != 0) {
printk("ERROR: gpio1\n");
return -1;
}
ret = gpio_direction_input(1);
if(ret != 0) {
printk("ERROR: gpio1\n");
return -1;
}
// 20
ret = gpio_request(20, "gpio20");
if(ret != 0) {
printk("ERROR: gpio20\n");
return -1;
}
ret = gpio_direction_output(20, 1);
if(ret != 0) {
printk("ERROR: gpio20 direction\n");
return -1;
}
// 68
ret = gpio_request(68, "gpio68");
if(ret != 0) {
printk("ERROR: gpio68\n");
return -1;
}
gpio_set_value_cansleep(68, 0);
// For interrupts
hcsr_devps->gpio_echo = 1;
}
else if(io_echo == 9) {
printk("TRY: Request gpio4, gpio22, gpio70\n");
// 4
ret = gpio_request(4, "gpio4");
if(ret != 0) {
printk("ERROR: gpio4\n");
return -1;
}
ret = gpio_direction_input(4);
if(ret != 0) {
printk("ERROR: gpio4 direction\n");
return -1;
}
// 22
ret = gpio_request(22, "gpio22");
if(ret != 0) {
printk("ERROR: gpio22\n");
return -1;
}
ret = gpio_direction_output(22, 1);
if(ret != 0) {
printk("ERROR: gpio22 output\n");
return -1;
}
// 70
ret = gpio_request(70, "gpio70");
if(ret != 0) {
printk("ERROR: gpio70\n");
return -1;
}
gpio_set_value_cansleep(70, 0);
// For interrupt
hcsr_devps->gpio_echo = 4;
}
else if(io_echo == 11) {
// TODO
}
else if(io_echo == 13) {
printk("TRY: Enable gpio7, gpio30, gpio46");
// 7
ret = gpio_request(7, "gpio7");
if(ret != 0) {
printk("ERROR: gpio7\n");
return -1;
}
ret = gpio_direction_input(7);
if(ret != 0) {
printk("ERROR: gpio7 input\n");
return -1;
}
// 30
ret = gpio_request(30, "gpio30");
if(ret != 0) {
printk("ERROR: gpio30\n");
return -1;
}
ret = gpio_direction_output(30, 1);
if(ret != 0) {
printk("ERROR: gpio30 output\n");
return -1;
}
// 46
ret = gpio_request(46, "gpio46");
if(ret != 0) {
printk("ERROR: gpio46\n");
return -1;
}
ret = gpio_direction_output(46, 0);
if(ret != 0) {
printk("ERROR: gpio46 direction\n");
return -1;
}
// For interrupt
hcsr_devps->gpio_echo = 7;
}
else {
printk("ERROR: Parse io_echo\n");
return -1;
}
printk("SUCCESS: Setup Echo Pin\n");
hcsr_devps->echo_enabled = true;
return 0;
}
// Latest Distance ==========================================================================================
static ssize_t show_latest_distance(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
hcsr_devps = dev_get_drvdata(dev);
if(hcsr_devps->external.position == 0) {
status = snprintf(buf, 4096, "Latest_Average_Distance=%llu\n", hcsr_devps->external.buffer[hcsr_devps->external.position].distance);
}
else {
status = snprintf(buf, 4096, "Latest_Average_Distance=%llu\n", hcsr_devps->external.buffer[hcsr_devps->external.position-1].distance);
}
return status;
}
static struct device_attribute dev_attr_latest_distance = {
.attr = {
.name = "latest_distance",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_latest_distance,
};
// Enable Measurement =========================================================================================================
/*
The work_queue function to activate interrupt by turning the trigger pin on and off
*/
void work_function(struct work_struct* work) {
unsigned long long pulse_width;
struct hcsr_dev* hcsr_devps;
struct sample_tsc* tmp;
struct sample_tsc* cursor;
struct sample_tsc* temp;
struct sample_tsc* curr;
unsigned long long velocity = 340;
unsigned long long average_distance = 0;
//int p = 0;
//printk("TRY: Work Function\n");
hcsr_devps = container_of(work, struct hcsr_dev, my_work);
while(spin_is_locked(&(hcsr_devps->lock_ops)) == 1) {
//printk("INFO: WAIT FOR LOCK\n");
// Wait for lock
msleep(10);
}
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
hcsr_devps->take_meas = true;
if(hcsr_devps->take_meas == true) {
// Trigger Interrupts and take samples
hcsr_devps->currently_sampling = true;
printk("TRY: Work Function Take Measurements\n");
// Update external buffer pointer to current position
hcsr_devps->external.position = hcsr_devps->external.position % 5;
// Make sure trigger pin is off before sampling since irq is rising first
//gpio_set_value_cansleep(hcsr_devps->gpio_trigger, TRIG_PIN_OFF);
list_for_each_entry_safe(cursor, tmp, &(hcsr_devps->samples_head), list_ptr) {
//printk("TRY: Trigger\n");
// Take measurements for cursor in irq handler
hcsr_devps->cursor = cursor;
// enable interrupt and take measurements for time period delta
gpio_set_value_cansleep(hcsr_devps->gpio_trigger, TRIG_PIN_ON);
// delay for echo time
udelay((unsigned long) 100);
// take last sample for time period
gpio_set_value_cansleep(hcsr_devps->gpio_trigger, TRIG_PIN_OFF);
// sleep for delta time
msleep((unsigned int) hcsr_devps->sampling_period);
}
printk("INFO: Sampling Finished\n");
list_for_each_entry_safe(curr, temp, &(hcsr_devps->samples_head), list_ptr) {
// Calculate distances for each internal sample, add each valid distance to average, and get last timestamp
pulse_width = curr->tsc_falling - curr->tsc_rising;
//printk("VAR: Falling-Rising = %lld\n", pulse_width);
//printk("VAR: Falling-Rising INT = %d\n", (int) pulse_width);
pulse_width = pulse_width * velocity;
//printk("VAR: Pulse Width = %llu\n", pulse_width);
curr->distance = ((int) pulse_width) / 2;
if(curr->order > 0 && curr->order < hcsr_devps->number_samples+1) {
// Add to average distance
average_distance += ((unsigned long long) curr->distance);
//printk("VAR: Current Average Distance = %llu\n", average_distance);
}
if(curr->order == hcsr_devps->number_samples+1) {
// Get last timestamp
hcsr_devps->external.buffer[hcsr_devps->external.position].tsc_last = curr->tsc_falling;
}
}
average_distance = (unsigned long long) ( ((int) average_distance) / hcsr_devps->number_samples);
printk("INFO: AVERAGE DISTANCE = %llu\n", average_distance);
// Set average distance
hcsr_devps->external.buffer[hcsr_devps->external.position].distance = (unsigned long long) average_distance;
// Update external buffer counter for next samples
hcsr_devps->external.position += 1;
// Do not take any more measurements until the write function changes take_meas to true
hcsr_devps->take_meas = false;
}
else {
msleep(10);
}
hcsr_devps->currently_sampling = false;
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return;
}
static ssize_t store_enable_measurements(struct device* dev, struct device_attribute* attr, const char* buf, size_t size) {
struct hcsr_dev* hcsr_devps;
long value;
int enable;
int status;
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = kstrtol(buf, 10, &value);
if(status != 0) {
printk("ERROR: store_sampling_period\n");
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
enable = (int) value;
if(hcsr_devps->currently_sampling == true) {
printk("ERROR: Measurement In Progress\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
if(hcsr_devps->trigger_enabled==false || hcsr_devps->echo_enabled==false) {
printk("ERROR: Echo and/or Trigger Pins Not Enabled\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
if(hcsr_devps->has_interrupt == false) {
printk("ERROR: Missing interrupt\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
if(enable == 1) {
// Trigger interrupts and take measurements
printk("TRY: Trigger Measurements\n");
hcsr_devps->take_meas = true;
//hcsr_devps->currently_sampling == true;
INIT_WORK(&(hcsr_devps->my_work), work_function);
status = queue_work(my_wq, &(hcsr_devps->my_work));
}
else {
enable = 0;
}
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
static ssize_t show_enable_measurements(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
hcsr_devps = dev_get_drvdata(dev);
//spin_lock(&(hcsr_devps->lock_ops));
status = snprintf(buf, 4096, "Enable_Measurements=%d\n", hcsr_devps->take_meas);
//spin_unlock(&(hcsr_devps->lock_ops));
return status;
}
static struct device_attribute dev_attr_enable_measurements = {
.attr = {
.name = "enable_measurements",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_enable_measurements,
.store = store_enable_measurements,
};
// Sampling Period ======================================================================================================
static ssize_t store_sampling_period(struct device* dev, struct device_attribute* attr, const char* buf, size_t size) {
struct hcsr_dev* hcsr_devps;
long value;
int status;
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = kstrtol(buf, 10, &value);
if(status != 0) {
printk("ERROR: store_sampling_period input\n");
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
if(((int) value) < 100 || ((int) value) > 500) {
hcsr_devps->sampling_period = 100;
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
hcsr_devps->sampling_period = (int) value;
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
static ssize_t show_sampling_period(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = snprintf(buf, 4096, "Sampling_Period=%d\n", hcsr_devps->sampling_period);
spin_unlock(&(hcsr_devps->lock_ops));
return status;
}
static struct device_attribute dev_attr_sampling_period = {
.attr = {
.name = "sampling_period",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_sampling_period,
.store = store_sampling_period,
};
// Number Of Samples (number_samples) ================================================================================
/*
static ssize_t make_internal_buffer(struct hcsr_dev* hcsr_devps) {
int p = 0;
for(; p < hcsr_devps->number_samples+2; p++) {
// Create internal sample buffer which has two additional samples for first and last sample
struct sample_tsc* sample;
sample = kmalloc(sizeof(struct sample_tsc), GFP_KERNEL);
if(!sample) {
printk("ERROR: Kmalloc error in creating internal buffer\n");
return -1;
}
memset(sample, 0, sizeof(struct sample_tsc));
sample->order = p;
if(p == 0) {
INIT_LIST_HEAD(&(hcsr_devps->samples_head));
}
// add to back of list
list_add_tail(&(sample->list_ptr), &(hcsr_devps->samples_head));
hcsr_devps->sample_list_size += 1;
}
return 0;
}
*/
ssize_t recreate_internal_buffer(struct hcsr_dev* hcsr_devps) {
struct sample_tsc* cursor;
struct sample_tsc* tmp;
int p;
if(hcsr_devps->currently_sampling == true) {
printk("INFO: Currently Sampling\n");
return 0;
}
// LOCK: to prevent race conditions in the internal buffer and irq flag
spin_lock_irqsave(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
list_for_each_entry_safe(cursor, tmp, &(hcsr_devps->samples_head), list_ptr) {
list_del(&(cursor->list_ptr));
memset(cursor, 0, sizeof(struct sample_tsc));
kfree(cursor);
}
hcsr_devps->sample_list_size = 0;
//printk("TRY: Create New Internal Buffer\n");
for(p=0; p < hcsr_devps->number_samples+2; p++) {
// Create internal sample buffer which has two additional samples for first and last sample
struct sample_tsc* sample;
sample = kmalloc(sizeof(struct sample_tsc), GFP_KERNEL);
if(!sample) {
printk("ERROR: Kmalloc error in creating internal buffer\n");
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return -1;
}
memset(sample, 0, sizeof(struct sample_tsc));
sample->order = p;
// add to back of list
list_add_tail(&(sample->list_ptr), &(hcsr_devps->samples_head));
hcsr_devps->sample_list_size += 1;
}
printk("SUCCESS: Created Internal Buffer\n");
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return 0;
}
static ssize_t store_number_samples(struct device* dev, struct device_attribute* attr, const char* buf, size_t size) {
struct hcsr_dev* hcsr_devps;
long value;
int status;
//printk("TRY: Store Trigger\n");
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = kstrtol(buf, 10, &value);
if(status != 0) {
printk("ERROR: store_trigger input\n");
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
hcsr_devps->number_samples = (int) value;
//status = make_internal_buffer(hcsr_devps);
status = recreate_internal_buffer(hcsr_devps);
if(status != 0) {
printk("ERROR: Create internal buffer\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
static ssize_t show_number_samples(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = snprintf(buf, 4096, "Number_Samples=%d\n", hcsr_devps->number_samples);
spin_unlock(&(hcsr_devps->lock_ops));
return status;
}
static struct device_attribute dev_attr_number_samples = {
.attr = {
.name = "number_samples",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_number_samples,
.store = store_number_samples,
};
// Trigger ==========================================================================================================
static ssize_t show_trigger(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
printk("TRY: In show_echo\n");
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = snprintf(buf, 4096, "Trigger IO=%d\n", hcsr_devps->trigger);
spin_unlock(&(hcsr_devps->lock_ops));
return status;
}
static ssize_t store_trigger(struct device* dev, struct device_attribute* attr, const char* buf, size_t size) {
struct hcsr_dev* hcsr_devps;
long value;
int status;
//printk("TRY: Store Trigger\n");
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = kstrtol(buf, 10, &value);
if(status != 0) {
printk("ERROR: store_trigger input\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
hcsr_devps->trigger = (int) value;
status = set_trigger_pins(hcsr_devps);
if(status != 0) {
printk("ERROR: Trigger Pin Not Setup\n");
hcsr_devps->trigger = -1;
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
static struct device_attribute dev_attr_trigger = {
.attr = {
.name = "trigger_pin",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_trigger,
.store = store_trigger,
};
// ECHO =========================================================================================================
static ssize_t show_echo(struct device* dev, struct device_attribute* attr, char* buf) {
struct hcsr_dev* hcsr_devps;
int status;
hcsr_devps = dev_get_drvdata(dev);
spin_lock(&(hcsr_devps->lock_ops));
status = snprintf(buf, 4096, "Echo IO=%d\n", hcsr_devps->echo);
spin_unlock(&(hcsr_devps->lock_ops));
printk("INFO: Finished snprintf\n");
return status;
}
static ssize_t store_echo(struct device* dev, struct device_attribute* attr, const char* buf, size_t size) {
struct hcsr_dev* hcsr_devps;
long value;
int status;
hcsr_devps = dev_get_drvdata(dev);
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
status = kstrtol(buf, 10, &value);
if(status != 0) {
printk("ERROR: Store_Echo Input\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
hcsr_devps->echo = (int) value;
status = set_echo_pins(hcsr_devps);
if(status != 0) {
printk("ERROR: Echo Pin Not Set\n");
spin_unlock(&(hcsr_devps->lock_ops));
hcsr_devps->echo = -1;
return 4096;
}
status = setup_echo_pin_interrupt(hcsr_devps);
if(status != 0) {
printk("ERROR: Interrupt Not Setup\n");
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
spin_unlock(&(hcsr_devps->lock_ops));
return 4096;
}
static struct device_attribute dev_attr_echo = {
.attr = {
.name = "echo_pin",
.mode = S_IWUSR | S_IRUGO,
},
.show = show_echo,
.store = store_echo,
};
// All attributes ========================================================================
// Holds the operations that a user can use for corresponding hcsr device
static struct attribute *hcsr_attrs[] = {
&dev_attr_echo.attr,
&dev_attr_trigger.attr,
&dev_attr_number_samples.attr,
&dev_attr_sampling_period.attr,
&dev_attr_enable_measurements.attr,
&dev_attr_latest_distance.attr,
NULL,
};
static const struct attribute_group hcsr_group = {
.attrs = hcsr_attrs,
};
static const struct attribute_group *hcsr_groups[] = {
&hcsr_group,
NULL,
};
// ====================================================================================
/* File operations structure. Defined in linux/fs.h */
static struct file_operations hcsr_fops = {
.owner = THIS_MODULE, /* Owner */
.open = hcsr_driver_open, /* Open method */
.release = hcsr_driver_release, /* Release method */
};
static int counter = 0;
static int create_hcsr_dev(struct P_chip *pchip) {
struct hcsr_dev* device;
struct device* new;
int p;
int verify_register;
printk("TRY: Kmalloc\n");
device = kmalloc(sizeof(struct hcsr_dev), GFP_KERNEL);
if(!device) {
printk("ERROR: kmalloc error for device\n");
return -1;
}
memset(device, 0, sizeof(struct hcsr_dev));
// Declare lock fields
spin_lock_init(&(device->lock_ops));
spin_lock_init(&(device->lock_irq));
device->pchip = *pchip;
//memcpy(&pchip_cpy, pchip, sizeof(struct P_chip));
// Initialize misc device fields
device->misc.minor = pchip->dev_no;
device->misc.fops = &hcsr_fops;
if(counter == 0) {
char* the_name = "hcsr_1";
device->misc.name = the_name;
}
else if(counter == 1) {
char* new = "hcsr_2";
device->misc.name = new;
}
else {
char* new = "hcsr_2";
device->misc.name = new;
}
counter += 1;
// Register misc device (used for holding minor number)
verify_register = misc_register(&(device->misc));
if(verify_register != 0) {
printk("ERROR: Misc device not registered for minor number = %d\n", pchip->dev_no);
printk("ERROR=%d: misc register error\n", verify_register);
return -1;
}
// Minor Number
printk("TRY: Minor Number\n");
device->minor = (counter+1);
counter += 1;
// IO Pins
device->trigger = -1;
device->echo = -1;
// Sampling Parameters
printk("TRY: Sampling Params\n");
device->number_samples = 7;
device->sampling_period = 200;
device->sample_list_size = 0;
// Create internal buffer
for(p=0; p < device->number_samples+2; p++) {
// Create internal sample buffer which has two additional samples for first and last sample
struct sample_tsc* sample;
sample = kmalloc(sizeof(struct sample_tsc), GFP_KERNEL);
if(!sample) {
printk("ERROR: Kmalloc error in creating internal buffer\n");
return -1;
}
memset(sample, 0, sizeof(struct sample_tsc));
sample->order = p;
if(p == 0) {
// First time internal buffer is initialized
INIT_LIST_HEAD(&(device->samples_head));
}
// Add to back of list
list_add_tail(&(sample->list_ptr), &(device->samples_head));
//pchip->device = new;
// Update
device->sample_list_size += 1;
}
// Measurement info fields
device->enable_measurements = 0;
device->latest_distance = 0;
// Internal list fields
device->sample_list_size = 0;
device->cursor = NULL;
// External fields
device->external.position = 0;
// Interrupt field
device->irq_is_rising = true;
device->number = MKDEV(MAJOR(dev_major), MINOR(device->misc.minor));
printk("NUMBER=%d\n", device->number);
// Register device in class
printk("TRY: Register Device\n");
//new = device_create_with_groups(&HCSR_CLASS, NULL, MKDEV(MAJOR(dev_major), MINOR(device->misc.minor)), device, hcsr_groups, "HCSR_%d", device->misc.minor);
new = device_create_with_groups(&HCSR_CLASS, NULL, device->number, (void*) device, hcsr_groups, "HCSR_%d", device->minor);
if(IS_ERR(new)) {
printk("ERROR: In create device\n");
kfree(device);
return -1;
}
// Store device in global list
list_add_tail(&(device->list_ptr), &(device_list));
printk("SUCCESS: Registered and stored device minor number = %d\n", pchip->dev_no);
return 0;
}
static int devices_allocated = 0;
static int P_driver_probe(struct platform_device *dev_found)
{
struct P_chip *pchip;
int verify_device;
int verify_class;
char* my_wq_name = "my_wq";
pchip = container_of(dev_found, struct P_chip, plf_dev);
printk(KERN_ALERT "Found the device -- %s %d \n", pchip->name, pchip->dev_no);
if(class_enabled == false) {
// Create class that each device is represented in sysfs
verify_class = class_register(&HCSR_CLASS);
if(verify_class < 0) {
printk("ERROR: Class register\n");
return -1;
}
printk("SUCCESS: New Class Created\n");
class_enabled = true;
// Create global driver workqueue to handle measurements
my_wq = create_workqueue(my_wq_name);
}
printk("TRY: Creating Corresponding HCSR Device\n");
verify_device = create_hcsr_dev(pchip);
if(verify_device != 0) {
printk("ERROR: probe error in creating new device\n");
return -1;
}
devices_allocated += 1;
return 0;
}
static int devices_removed = 0;
static int P_driver_remove(struct platform_device *pdev)
{
// External
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
// Internal
struct sample_tsc* curr_tsc;
struct sample_tsc* hold_tsc;
if(devices_removed == devices_allocated) {
printk("INFO: Do Nothing\n");
return 0;
}
printk("TRY: Free devices\n");
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(devices_removed == devices_allocated) {
printk("INFO: Condition\n");
// Unregister class once all devices cleared
printk("TRY: Unregister Class\n");
class_unregister(&HCSR_CLASS);
// Destroy workqueue
destroy_workqueue(my_wq);
return 0;
}
printk("TRY: Deallocate internal buffer\n");
list_for_each_entry_safe(curr_tsc, hold_tsc, &(cursor->samples_head), list_ptr) {
//printk("VAR: Order = %d\n", curr_tsc->order);
//printk("VAR: TSC Rising = %lld\n", curr_tsc->tsc_rising);
//printk("VAR: TSC Falling = %lld\n", curr_tsc->tsc_rising);
list_del(&(curr_tsc->list_ptr));
kfree(curr_tsc);
}
list_del(&(cursor->list_ptr));
if(cursor->has_interrupt == true) {
printk("TRY: Free IRQ\n");
free_irq(cursor->irq_desc_echo, (void*) cursor);
}
//printk("TRY: Remove misc device\n");
misc_deregister(&(cursor->misc));
printk("TRY: Remove Device\n");
printk("NUMBER=%d\n", cursor->number);
//device_destroy(&HCSR_CLASS, MKDEV(dev_major, cursor->minor));
device_destroy(&HCSR_CLASS, MKDEV(MAJOR(dev_major), MINOR(cursor->misc.minor)));
devices_removed += 1;
memset(cursor, 0, sizeof(struct hcsr_dev));
kfree(cursor);
}
return 0;
};
/*
static int P_driver_probe(struct platform_device *dev_found)
{
struct P_chip *pchip;
int verify_device;
int verify_class;
char* my_wq_name = "my_wq";
pchip = container_of(dev_found, struct P_chip, plf_dev);
*/
//static int devices_removed = 0;
/*
static int P_driver_remove(struct platform_device *dev_found)
{
// Internal
struct sample_tsc* curr_tsc;
struct sample_tsc* hold_tsc;
struct hcsr_dev* hcsr_devps;
struct P_chip *pchip;
pchip = container_of(dev_found, struct P_chip, plf_dev);
printk("Pchip Name = %s\n", pchip->name);
hcsr_devps = container_of(pchip, struct hcsr_dev, pchip);
printk("DEVICE_NUMBER=%d\n", hcsr_devps->number);
//printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
printk("TRY: Deallocate internal buffer\n");
list_for_each_entry_safe(curr_tsc, hold_tsc, &(hcsr_devps->samples_head), list_ptr) {
//printk("VAR: Order = %d\n", curr_tsc->order);
//printk("VAR: TSC Rising = %lld\n", curr_tsc->tsc_rising);
//printk("VAR: TSC Falling = %lld\n", curr_tsc->tsc_rising);
list_del(&(curr_tsc->list_ptr));
kfree(curr_tsc);
}
list_del(&(hcsr_devps->list_ptr));
if(hcsr_devps->has_interrupt == true) {
printk("TRY: Free IRQ\n");
free_irq(hcsr_devps->irq_desc_echo, (void*) hcsr_devps);
}
//printk("TRY: Remove misc device\n");
misc_deregister(&(hcsr_devps->misc));
printk("TRY: Remove Device\n");
printk("NUMBER=%d\n", hcsr_devps->number);
//device_destroy(&HCSR_CLASS, MKDEV(dev_major, cursor->minor));
device_destroy(&HCSR_CLASS, hcsr_devps->number);
//device_unregister(hcsr_devps);
memset(hcsr_devps, 0, sizeof(struct hcsr_dev));
kfree(hcsr_devps);
devices_removed += 1;
if(devices_removed == devices_allocated) {
// Unregister class once all devices cleared
printk("TRY: Unregister Class\n");
class_unregister(&HCSR_CLASS);
// Destroy workqueue
destroy_workqueue(my_wq);
}
return 0;
}
*/
static struct platform_driver P_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.probe = P_driver_probe,
.remove = P_driver_remove,
.id_table = P_id_table,
};
module_platform_driver(P_driver);
MODULE_LICENSE("GPL");
<file_sep>/README.md
# Linux_Kernel_Modules
Linux Kernel Modules for the Intel Galileo Gen 2 board embedded device
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/Makefile
IOT_HOME = /opt/iot-devkit/1.7.2/sysroots
#PWD:= $(shell pwd)
KDIR:=$(IOT_HOME)/i586-poky-linux/usr/src/kernel
PATH := $(PATH):$(IOT_HOME)/x86_64-pokysdk-linux/usr/bin/i586-poky-linux
CC = i586-poky-linux-gcc
ARCH = x86
CROSS_COMPILE = i586-poky-linux-
SROOT=$(IOT_HOME)/i586-poky-linux/
APP=main
obj-m = Sample_platform_device.o Sample_platform_driver.o
all:
make ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) -C $(KDIR) M=$(PWD) modules
$(CC) -o $(APP) main.c -Wall -g --sysroot=$(SROOT)
clean:
make ARCH=x86 CROSS_COMPILE=i586-poky-linux- -C $(SROOT)/usr/src/kernel M=$(PWD) clean
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/main.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <sys/time.h>
#include <linux/ioctl.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/ioctl.h>
int fd_plat1;
int fd_plat2;
void open_fds() {
fd_plat1 = open("/dev/hcsr_1", O_RDWR);
if(fd_plat1 < 0) {
fprintf(stderr, "Cannot open fd_plat1 code = %d\n", fd_plat1);
exit(-1);
}
fd_plat2 = open("/dev/hcsr_2", O_RDWR);
if(fd_plat2 < 0) {
fprintf(stderr, "Cannot open fd_plat2 code = %d\n", fd_plat2);
exit(-1);
}
return;
}
void close_fds() {
int ret = 0;
ret = close(fd_plat1);
if(ret != 0) {
fprintf(stderr, "Cannont close fd_plat1 code = %d\n", ret);
exit(-1);
}
ret = close(fd_plat2);
if(ret != 0) {
fprintf(stderr, "Cannont close fd_plat2 code = %d\n", ret);
exit(-1);
}
return;
}
int main() {
open_fds();
close_fds();
return 0;
}
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part1_With_Binaries/HCSR_Sensor_Driver.c
#include "hcsr.h"
#include "ioctl.h"
/* ----------------------------------------------- DRIVER HCSR_Sensor_Driver --------------------------------------------------
Driver controls <NUMBER_OF_DEVICES> Devices that eacho control a HCSR Sensor
and process measurments and requests to each device
----------------------------------------------------------------------------------------------------------------*/
static char* user_name = "Kamal"; /* the default user name, can be replaced if a new name is attached in insmod command */
module_param(user_name,charp,0000); //to get parameter from load.sh script to greet the user
// NUMBER_OF_DEVICES is the number of misc and hcsr devices to create (default=2)
static int NUMBER_OF_DEVICES = 2;
module_param(NUMBER_OF_DEVICES,int,0000);
// Driver workqueue for all devices that handles sampling requests
static struct workqueue_struct* my_wq;
// List holds the devices
struct list_head device_list;
LIST_HEAD(device_list);
// Names of devices
#define DEV1 "HCSR_1"
#define DEV2 "HCSR_2"
#define DEV3 "HCSR_3"
#define DEV4 "HCSR_4"
#define DEV5 "HCSR_5"
#define DEV6 "HCSR_6"
/*
* Open corresponding hcsr device for file descriptor
*/
int hcsr_driver_open(struct inode *inode, struct file *file)
{
struct hcsr_dev *hcsr_devps;
int minor_number = iminor(inode);
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
printk("\n%s is openning \n", hcsr_devps->misc.name);
return 0;
}
}
printk("ERROR: Could not find device\n");
return -1;
}
/*
* Release file descriptor for corresponding hcsr device based in minor number
*/
int hcsr_driver_release(struct inode *inode, struct file *file)
{
struct hcsr_dev* hcsr_devps;
int minor_number = iminor(file->f_path.dentry->d_inode);
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
bool found = false;
//printk("MINOR NUMBER READ =%d\n", iminor(file->f_path.dentry->d_inode));
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
//printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
found = true;
}
}
if(found == false) {
printk("ERROR: Could Not Find File\n");
return -1;
}
if(hcsr_devps != NULL) {
printk("SUCCESS: %s is closing\n", hcsr_devps->name);
}
return 0;
}
/*
Assembly code to get the Time Stamp Counter
*/
static __always_inline unsigned long long get_native_read_tsc_here(void) {
DECLARE_ARGS(val, low, high);
asm volatile("rdtsc" : EAX_EDX_RET(val, low, high));
return (unsigned long long) EAX_EDX_VAL(val, low, high);
}
/*
INFO: the echo pin interrupt handler, should be initialized as a rising edge first
and should be activated first when echo pin becomes high in the thread function
ACTION: Should write the start and end time stamp counters of the sensor measurement into the internal buffer
*/
irqreturn_t irq_echo_handler(int irq, void* dev_id) {
struct hcsr_dev* hcsr_devps;
hcsr_devps = (struct hcsr_dev*) dev_id;
//printk("INFO: In Interrupt\n");
// LOCK: to prevent race conditions in the internal buffer and irq flag
spin_lock_irqsave(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
if(irq == hcsr_devps->irq_desc_echo) {
// Verify this the correct irq number
if(hcsr_devps->irq_is_rising) {
// RISING EDGE
//printk("INFO: RISING\n");
// Write timestamp of start of sensor measurement
hcsr_devps->cursor->tsc_rising = get_native_read_tsc_here();
// Change trigger for falling edge
irq_set_irq_type(irq, IRQ_TYPE_EDGE_FALLING);
// update flag
hcsr_devps->irq_is_rising = false;
}
else if(hcsr_devps->irq_is_rising == false) {
// FALLING EDGE
//printk("INFO: FALLING\n");
// Write timestamp of start of sensor measurement
hcsr_devps->cursor->tsc_falling = get_native_read_tsc_here();
// Change irq type back to rising
irq_set_irq_type(irq, IRQ_TYPE_EDGE_RISING);
// update flag
hcsr_devps->irq_is_rising = true;
}
else {
// Ignore interrupt
}
}
else {
// Different IRQ Number
}
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return IRQ_HANDLED;
}
//________________________________________________________________________________________
void free_trigger_pins(struct hcsr_dev *hcsr_devps) {
int io_trig = hcsr_devps->trigger;
if(io_trig == 0) {
gpio_free(32);
gpio_free(11);
}
else if(io_trig == 1) {
gpio_free(45);
gpio_free(28);
gpio_free(12);
}
else if(io_trig == 4) {
gpio_free(36);
gpio_free(6);
}
else if(io_trig == 5) {
gpio_free(66);
gpio_free(18);
gpio_free(0);
}
else if(io_trig == 6) {
gpio_free(68);
gpio_free(20);
gpio_free(1);
}
else if(io_trig == 7) {
gpio_free(38);
}
else if(io_trig == 8) {
gpio_free(40);
}
else {
// Do Nothing
}
return;
}
/*
Set corresponding trigger pin sequence based on user chosen IO trigger pin
*/
long set_trigger_pins(struct hcsr_dev *hcsr_devps, struct pin_params_from_user* io_params) {
int ret;
int io_trig = io_params->trigger;
gpio_free(64);
printk("VAR: IO PARAMS TRIG=%d\n", io_trig);
if(io_trig == 0) {
printk("TRY: Request gpio11, gpio32\n");
// 11
ret = gpio_request(11, "gpio11");
if(ret != 0) {
printk("ERROR: gpio11\n");
return -1;
}
ret = gpio_direction_output(11, 0);
if(ret != 0) {
printk("ERROR: gpio11 direction\n");
return -1;
}
// For triggering interrupts
hcsr_devps->gpio_trigger = 11;
// 33
ret = gpio_request(32, "gpio32");
if(ret != 0) {
printk("ERROR: gpio32\n");
return -1;
}
ret = gpio_direction_output(32, 0);
if(ret != 0) {
printk("ERROR: gpio32 output\n");
return -1;
}
}
else if(io_trig == 1) {
printk("TRY gpio12, gpio28, gpio45\n");
// 12
ret = gpio_request(12, "gpio12");
if(ret != 0) {
printk("ERROR: gpio12\n");
return -1;
}
ret = gpio_direction_output(12, 0);
if(ret != 0) {
printk("ERROR: gpio12 output\n");
return -1;
}
hcsr_devps->gpio_trigger = 12;
// 28
ret = gpio_request(28, "gpio28");
if(ret != 0) {
printk("ERROR\n");
return -1;
}
ret = gpio_direction_output(28, 0);
if(ret != 0) {
return -1;
}
// 45
ret = gpio_request(45, "gpio45");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(45, 0);
if(ret != 0) {
return -1;
}
}
else if(io_trig == 4) {
printk("TRY: gpio6, gpio36\n");
// 6
ret = gpio_request(6, "gpio6");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(6, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 6;
// 36
ret = gpio_request(36, "gpio36");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(36, 0);
if(ret != 0) {
return -1;
}
}
else if(io_trig == 5) {
printk("TRY: gpio0, gpio18, gpio66\n");
// 0
ret = gpio_request(0, "gpio0");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(0, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 0;
// 18
ret = gpio_request(18, "gpio18");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(18, 0);
if(ret != 0) {
return -1;
}
// 66
ret = gpio_request(66, "gpio66");
if(ret != 0) {
return -1;
}
gpio_set_value_cansleep(66, 0);
}
else if(io_trig == 6) {
printk("TRY: gpio1, gpio20, gpio68\n");
// 1
ret = gpio_request(1, "gpio1");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(1, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 1;
// 20
ret = gpio_request(20, "gpio20");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(20, 0);
if(ret != 0) {
return -1;
}
// 68
ret = gpio_request(68, "gpio68");
if(ret != 0) {
return -1;
}
gpio_set_value_cansleep(68, 0);
}
else if(io_trig == 7) {
printk("TRY: gpio38\n");
// 38
ret = gpio_request(38, "gpio38");
if(ret != 0) {
gpio_free(38);
ret = gpio_request(38, "gpio38");
if(ret != 0) {
printk("ERROR: gpio38\n");
return -1;
}
}
ret = gpio_direction_output(38, 0);
if(ret != 0) {
printk("ERROR: gpio38 direction out\n");
return -1;
}
// For triggering interrupts
hcsr_devps->gpio_trigger = 38;
printk("SUCCESS: gpio38\n");
}
else if(io_trig == 8) {
printk("TRY: gpio40");
// 40
ret = gpio_request(40, "gpio40");
if(ret != 0) {
return -1;
}
ret = gpio_direction_output(40, 0);
if(ret != 0) {
return -1;
}
hcsr_devps->gpio_trigger = 40;
}
else {
}
return 0;
}
// _________________________________________________________________________________________
/*
Free matching series of echo pins based on chosen IO echo pin
*/
void free_echo_pins(struct hcsr_dev* hcsr_devps) {
int io_echo = hcsr_devps->echo;
//gpio_free(38);
if(io_echo == 4) {
gpio_free(36);
gpio_free(6);
}
else if(io_echo == 5) {
gpio_free(66);
gpio_free(18);
gpio_free(0);
}
else if(io_echo == 6) {
gpio_free(68);
gpio_free(20);
gpio_free(1);
}
else if(io_echo == 9) {
gpio_free(70);
gpio_free(22);
gpio_free(4);
}
else if(io_echo == 11) {
gpio_free(72);
gpio_free(44);
gpio_free(24);
gpio_free(5);
}
else if(io_echo == 13) {
gpio_free(46);
gpio_free(30);
gpio_free(7);
}
else {
// Do Nothing
}
return;
}
/*
Set up rising edge interrupt for first echo pin in series corresponding to IO pin chosen for echo
*/
int setup_echo_pin_interrupt(struct hcsr_dev* hcsr_devps) {
// Setup new interrupt for the gpio echo pin that is the first one for respective IO shield pin
int verify_irq;
printk("VAR: IRQ DESC=%d\n", hcsr_devps->irq_desc_echo);
if(hcsr_devps->has_interrupt == true) {
free_irq(hcsr_devps->irq_desc_echo, (void*) hcsr_devps);
}
// Request new interrupt line
hcsr_devps->irq_desc_echo = gpio_to_irq(hcsr_devps->gpio_echo);
if(hcsr_devps->irq_desc_echo < 0) {
printk("ERROR=%d: gpio_to_irq\n", hcsr_devps->irq_desc_echo);
return -1;
}
printk("VAR: New IRQ DESC=%d\n", hcsr_devps->irq_desc_echo);
//printk("VAR: NAME=%s\n", hcsr_devps->name);
// Request interrupt for gpio_echo, the interrupt is first triggered at a rising edge (gpio_trig value goes from 0 to 1)
verify_irq = request_irq(hcsr_devps->irq_desc_echo, (irq_handler_t) irq_echo_handler, IRQF_TRIGGER_RISING, "hcsr_interrupt", (void*) hcsr_devps);
if(verify_irq != 0) {
printk("ERROR=%d: request_irq", verify_irq);
return -1;
}
hcsr_devps->has_interrupt = true;
printk("SUCCESS: Interrupt Requested\n");
return 0;
}
/*
Set up the user chosen echo pins based on IO selection
*/
long set_echo_pins(struct hcsr_dev *hcsr_devps, struct pin_params_from_user* io_params) {
int ret;
int io_echo = io_params->echo;
if(io_echo == 4) {
printk("TRY: Setting up gpio6 & gpio36\n");
// 6
ret = gpio_request(6, "gpio6");
if(ret != 0) {
gpio_free(36);
gpio_free(6);
ret = gpio_request(6, "gpio6");
if(ret != 0) {
printk("ERROR: gpio6\n");
return -1;
}
}
ret = gpio_direction_input(6);
if(ret != 0) {
printk("ERROR: gpio6 direction input\n");
return -1;
}
// 36
ret = gpio_request(36, "gpio36");
if(ret != 0) {
printk("ERROR: gpio36");
return -1;
}
ret = gpio_direction_output(36, 1);
if(ret != 0) {
printk("ERROR: gpio36 direction out\n");
return -1;
}
// For interrupts
hcsr_devps->gpio_echo = 6;
}
else if(io_echo == 5) {
printk("TRY: Setting up gpio0, gpio18, gpio66\n");
// 0
ret = gpio_request(0, "gpio0");
if(ret != 0) {
printk("ERROR: gpio0\n");
return -1;
}
ret = gpio_direction_input(0);
if(ret != 0) {
printk("ERROR: gpio0 input\n");
return -1;
}
// 18
ret = gpio_request(18, "gpio18");
if(ret != 0) {
printk("ERROR: gpio18\n");
return -1;
}
ret = gpio_direction_output(18, 1);
if(ret != 0) {
printk("ERROR: gpio18 direction\n");
return -1;
}
// 66
ret = gpio_request(66, "gpio66");
if(ret != 0) {
printk("ERROR: gpio66\n");
return -1;
}
gpio_set_value_cansleep(66, 0);
// For interrupts
hcsr_devps->gpio_echo = 0;
}
else if(io_echo == 6) {
printk("TRY: Setting up gpio1, gpio20, gpio68\n");
// 1
ret = gpio_request(1, "gpio1");
if(ret != 0) {
printk("ERROR: gpio1\n");
return -1;
}
ret = gpio_direction_input(1);
if(ret != 0) {
printk("ERROR: gpio1\n");
return -1;
}
// 20
ret = gpio_request(20, "gpio20");
if(ret != 0) {
printk("ERROR: gpio20\n");
return -1;
}
ret = gpio_direction_output(20, 1);
if(ret != 0) {
printk("ERROR: gpio20 direction\n");
return -1;
}
// 68
ret = gpio_request(68, "gpio68");
if(ret != 0) {
printk("ERROR: gpio68\n");
return -1;
}
gpio_set_value_cansleep(68, 0);
// For interrupts
hcsr_devps->gpio_echo = 1;
}
else if(io_echo == 9) {
printk("TRY: Request gpio4, gpio22, gpio70\n");
// 4
ret = gpio_request(4, "gpio4");
if(ret != 0) {
printk("ERROR: gpio4\n");
return -1;
}
ret = gpio_direction_input(4);
if(ret != 0) {
printk("ERROR: gpio4 direction\n");
return -1;
}
// 22
ret = gpio_request(22, "gpio22");
if(ret != 0) {
printk("ERROR: gpio22\n");
return -1;
}
ret = gpio_direction_output(22, 1);
if(ret != 0) {
printk("ERROR: gpio22 output\n");
return -1;
}
// 70
ret = gpio_request(70, "gpio70");
if(ret != 0) {
printk("ERROR: gpio70\n");
return -1;
}
gpio_set_value_cansleep(70, 0);
// For interrupt
hcsr_devps->gpio_echo = 4;
}
else if(io_echo == 11) {
// TODO
}
else if(io_echo == 13) {
printk("TRY: Enable gpio7, gpio30, gpio46");
// 7
ret = gpio_request(7, "gpio7");
if(ret != 0) {
printk("ERROR: gpio7\n");
return -1;
}
ret = gpio_direction_input(7);
if(ret != 0) {
printk("ERROR: gpio7 input\n");
return -1;
}
// 30
ret = gpio_request(30, "gpio30");
if(ret != 0) {
printk("ERROR: gpio30\n");
return -1;
}
ret = gpio_direction_output(30, 1);
if(ret != 0) {
printk("ERROR: gpio30 output\n");
return -1;
}
// 46
ret = gpio_request(46, "gpio46");
if(ret != 0) {
printk("ERROR: gpio46\n");
return -1;
}
ret = gpio_direction_output(46, 0);
if(ret != 0) {
printk("ERROR: gpio46 direction\n");
return -1;
}
// For interrupt
hcsr_devps->gpio_echo = 7;
}
else {
printk("ERROR: Parse io_echo\n");
return -1;
}
printk("SUCCESS: Setup Echo Pin\n");
return 0;
}
long recreate_internal_buffer(struct hcsr_dev* hcsr_devps) {
struct sample_tsc* cursor;
struct sample_tsc* tmp;
int p;
if(hcsr_devps->currently_sampling == true) {
printk("INFO: Currently Sampling\n");
return 0;
}
//printk("VAR: DEVICE NAME MINOR =%d\n", hcsr_devps->misc.minor);
//printk("TRY: Replace internal buffer\n");
// LOCK: to prevent race conditions in the internal buffer and irq flag
spin_lock_irqsave(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
list_for_each_entry_safe(cursor, tmp, &(hcsr_devps->samples_head), list_ptr) {
list_del(&(cursor->list_ptr));
memset(cursor, 0, sizeof(struct sample_tsc));
kfree(cursor);
}
hcsr_devps->sample_list_size = 0;
//printk("TRY: Create New Internal Buffer\n");
for(p=0; p < hcsr_devps->sensor_params.num_samples+2; p++) {
// Create internal sample buffer which has two additional samples for first and last sample
struct sample_tsc* sample;
sample = kmalloc(sizeof(struct sample_tsc), GFP_KERNEL);
if(!sample) {
printk("ERROR: Kmalloc error in creating internal buffer\n");
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return -1;
}
memset(sample, 0, sizeof(struct sample_tsc));
sample->order = p;
if(p == 0) {
//INIT_LIST_HEAD(&(hcsr_devps->samples_head));
}
// add to back of list
list_add_tail(&(sample->list_ptr), &(hcsr_devps->samples_head));
hcsr_devps->sample_list_size += 1;
}
printk("SUCCESS: Created Internal Buffer\n");
// UNLOCK
spin_unlock_irqrestore(&(hcsr_devps->lock_irq), hcsr_devps->lock_irq_flags);
return 0;
}
long parse_sample_input(struct sampling_params_from_user* sampling_params) {
if((sampling_params->num_samples < 3) || (sampling_params->num_samples > 50)) {
// The minimum samples is 3 since the first and last are not included in the average distance
// Upper limit for protection from a malicious user
printk("ERROR: sampling params number of samples must be within [3, 50]\n");
return -1;
}
if((sampling_params->period < 1) || (sampling_params->period > 300)) {
// Upper limit for protection from a malicious user
printk("ERROR: sampling params period must be within [1, 300]\n");
return -1;
}
return 0;
}
long hcsr_driver_unlocked_ioctl(struct file* file, unsigned int ioctl_num, unsigned long ioctl_param) {
int verify_user_input;
int verify_pins;
int verify_interr;
struct hcsr_dev* hcsr_devps;
struct pin_params_from_user io_params;
struct sampling_params_from_user sampling_params;
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
int minor_number = iminor(file->f_path.dentry->d_inode);
bool found = false;
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
//printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
found = true;
}
}
if(found == false) {
printk("ERROR: IOCTL Could Not Find File\n");
return -1;
}
//printk("VAR: MINOR NUMBER = %d\n", hcsr_devps->misc.minor);
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
if(hcsr_devps->currently_sampling == true) {
printk("ERROR: Write Blocked: Measurement in Progress\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
if(ioctl_num == CONFIG_PINS) {
// CONFIG_PINS
//printk("INFO: CONFIG_PINS Selected\n");
verify_user_input = copy_from_user(&io_params, (struct pin_params_from_user*) ioctl_param, sizeof(struct pin_params_from_user));
if(verify_user_input != 0) {
printk("ERROR=%d: copy_from_user in ioctl for CONFIG_PINS error\n", verify_user_input);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
if(io_params.trigger == io_params.echo) {
printk("ERROR: Pins must be different\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
if(hcsr_devps->ioctl_pins_blocked == true) {
// Echo and Trigger pins should only be set once for board safety reasons
printk("ERROR: Pins should be only be set once\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
//printk("VAR: IO TRIGGER = %d\n", (int) io_params.trigger);
verify_pins = set_trigger_pins(hcsr_devps, &io_params);
if(verify_pins != 0) {
printk("ERROR: set_trigger_pins\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
verify_pins = set_echo_pins(hcsr_devps, &io_params);
if(verify_pins != 0) {
printk("ERROR: set_echo_pins\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
//printk("TRY: Setup Interrupt\n");
verify_interr = setup_echo_pin_interrupt(hcsr_devps);
if(verify_interr != 0) {
printk("ERROR: setup echo interrupt\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
// Pins shold not change for device once set
hcsr_devps->ioctl_pins_blocked = true;
// Only take measurements when trigger and echo enabled
hcsr_devps->trigger_enabled = true;
hcsr_devps->echo_enabled = true;
}
else if(ioctl_num == SET_PARAMETERS) {
// SET_PARAMETERS (Sampling) (can be changed later)
//printk("TRY: In SET_PARAMETERS\n");
verify_user_input = copy_from_user(&sampling_params, (struct sampling_params_from_user*) ioctl_param, sizeof(struct sampling_params_from_user));
if(verify_user_input != 0) {
printk("ERROR=%d: copy_from_user in ioctl for SET_PARAMETERS error\n", verify_user_input);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
if(parse_sample_input(&sampling_params) != 0) {
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
//printk("TRY: Setting sampling parameters\n");
// Set sampling parameters
hcsr_devps->sensor_params.num_samples = sampling_params.num_samples;
hcsr_devps->sensor_params.sampling_period = sampling_params.period;
verify_user_input = recreate_internal_buffer(hcsr_devps);
if(verify_user_input != 0) {
printk("ERROR: Recreating internal buffer\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
}
else {
printk("ERROR=%d: Unknown ioctl command\n", ioctl_num);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
printk("SUCCESS: IOCTL Completed\n");
return 0;
}
/*
The work_queue function to activate interrupt by turning the trigger pin on and off
*/
void work_function(struct work_struct* work) {
unsigned long long pulse_width;
struct hcsr_dev* hcsr_devps;
struct sample_tsc* tmp;
struct sample_tsc* cursor;
struct sample_tsc* temp;
struct sample_tsc* curr;
unsigned long long velocity = 340;
unsigned long long average_distance = 0;
//int p = 0;
//printk("TRY: Work Function\n");
// Retrieve matching device that called work_function
hcsr_devps = container_of(work, struct hcsr_dev, my_work);
while(spin_is_locked(&(hcsr_devps->lock_ops)) == 1) {
//printk("INFO: WAIT FOR LOCK\n");
// Wait for lock
msleep(10);
}
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
//printk("TRY: Device\n");
//printk("INFO: Number of samples = %d\n", hcsr_devps->sensor_params.num_samples);
hcsr_devps->take_meas = true;
if(hcsr_devps->take_meas == true) {
// Trigger Interrupts and take samples
hcsr_devps->currently_sampling = true;
printk("TRY: Work Function Take Measurements\n");
// Update external buffer pointer to current position (functions like a ring buffer)
hcsr_devps->external.position = hcsr_devps->external.position % 5;
list_for_each_entry_safe(cursor, tmp, &(hcsr_devps->samples_head), list_ptr) {
//printk("TRY: Trigger\n");
// Take measurements for cursor in irq handler
hcsr_devps->cursor = cursor;
// enable interrupt and take measurements for time period delta
gpio_set_value_cansleep(hcsr_devps->gpio_trigger, TRIG_PIN_ON);
// delay for echo time
udelay((unsigned long) 100);
// take last sample for time period
gpio_set_value_cansleep(hcsr_devps->gpio_trigger, TRIG_PIN_OFF);
// sleep for delta time
msleep((unsigned int) hcsr_devps->sensor_params.sampling_period);
}
printk("INFO: Sampling Finished\n");
list_for_each_entry_safe(curr, temp, &(hcsr_devps->samples_head), list_ptr) {
// Calculate distances for each internal sample, add each valid distance to average, and get last timestamp
pulse_width = curr->tsc_falling - curr->tsc_rising;
//printk("VAR: Falling-Rising INT = %d\n", (int) pulse_width);
pulse_width = pulse_width * velocity;
//printk("VAR: Pulse Width = %llu\n", pulse_width);
// Have to briefly convert to int due to architecture
curr->distance = ((int) pulse_width) / 2;
if(curr->order > 0 && curr->order < hcsr_devps->sensor_params.num_samples+1) {
// Add to average distance
average_distance += ((unsigned long long) curr->distance);
//printk("VAR: Current Average Distance = %llu\n", average_distance);
}
if(curr->order == hcsr_devps->sensor_params.num_samples+1) {
// Get last timestamp of measurement sequence
hcsr_devps->external.buffer[hcsr_devps->external.position].tsc_last = curr->tsc_falling;
}
}
// Briefly convert average distance due to architecture
average_distance = (unsigned long long) ( ((int) average_distance) / hcsr_devps->sensor_params.num_samples);
printk("INFO: AVERAGE DISTANCE = %llu\n", average_distance);
// Set average distance
hcsr_devps->external.buffer[hcsr_devps->external.position].distance = (unsigned long long) average_distance;
// Update external buffer counter for next samples
hcsr_devps->external.position += 1;
// Do not take any more measurements until the write function changes take_meas to true
hcsr_devps->take_meas = false;
}
else {
msleep(10);
}
//printk("SUCCESS: Work Function Completed\n");
// Signal sampling is completed and more samples can be taken
hcsr_devps->currently_sampling = false;
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return;
}
int setup_default_echo_pins_parse(struct hcsr_dev* hcsr_devps) {
int ret;
int io_echo = hcsr_devps->echo;
if(io_echo == 4) {
printk("Setting up gpio6 & gpio36\n");
// 6
ret = gpio_request(6, "gpio6");
if(ret != 0) {
printk("ERROR: gpio6\n");
return -1;
}
ret = gpio_direction_input(6);
if(ret != 0) {
printk("ERROR: gpio6 direction input\n");
return -1;
}
// 36
ret = gpio_request(36, "gpio36");
if(ret != 0) {
printk("ERROR: gpio36");
return -1;
}
ret = gpio_direction_output(36, 1);
if(ret != 0) {
printk("ERROR: gpio36 direction out\n");
return -1;
}
hcsr_devps->gpio_echo = 6;
}
return 0;
}
void free_default_echo_pins_parse(struct hcsr_dev* hcsr_devps) {
if(hcsr_devps->echo == 4) {
gpio_free(36);
gpio_free(6);
}
return;
}
int setup_default_trigger_pins_parse(struct hcsr_dev* hcsr_devps) {
int ret;
int io_trig = hcsr_devps->trigger;
//printk("INFO: hcsr->trigger = %d\n", io_trig);
if(io_trig == 7) {
// 38
ret = gpio_request(38, "gpio38");
if(ret != 0) {
gpio_free(38);
ret = gpio_request(38, "gpio38");
if(ret != 0) {
printk("ERROR: gpio38\n");
return -1;
}
}
// 38 set dir
ret = gpio_direction_output(38, 0);
if(ret != 0) {
printk("ERROR: gpio38 direction out\n");
return -1;
}
hcsr_devps->gpio_trigger = 38;
printk("SUCCESS: gpio38\n");
}
return 0;
}
void free_default_trigger_pins_parse(struct hcsr_dev* hcsr_devps) {
if(hcsr_devps->echo == 7) {
gpio_free(38);
}
}
/*
* Write to hcsr driver
*/
ssize_t hcsr_driver_write(struct file *file, const char *buf,
size_t count, loff_t *ppos)
{
struct write_argument arg;
int verify_user_arg;
int ret_wq;
int i;
struct hcsr_dev* hcsr_devps;
bool found = false;
int minor_number = iminor(file->f_path.dentry->d_inode);
//printk("MINOR NUMBER READ =%d\n", iminor(file->f_path.dentry->d_inode));
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
//printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
found = true;
}
}
if(found == false) {
printk("ERROR: Cound Not Find File\n");
return -1;
}
//printk("MINOR NUMBER WRITE =%d\n", iminor(file->f_path.dentry->d_inode));
//printk("MISC MINOR Number = %d\n", hcsr_devps->misc.minor);
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
if(hcsr_devps->currently_sampling == true) {
printk("ERROR: Write Blocked: Measurement in Progress\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
// Check for trigger and echo pins enabled status
if(hcsr_devps->trigger_enabled == false) {
printk("ERROR: Trigger Has To Be Enabled\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
if(hcsr_devps->echo_enabled == false) {
printk("ERROR: Echo Not Enabled\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
verify_user_arg = copy_from_user(&arg, buf, sizeof(struct write_argument));
if(verify_user_arg != 0) {
printk("ERROR=%d: Could not copy user data\n", verify_user_arg);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
if(arg.cmd < 0) {
// Clear external buffer
//printk("TRY: Clear external buffer\n");
i = 0;
for(; i < 5; i++) {
hcsr_devps->external.buffer[i].distance = 0;
hcsr_devps->external.buffer[i].tsc_first = 0;
hcsr_devps->external.buffer[i].tsc_last = 0;
}
}
else if(arg.cmd > 0) {
// Take new measurements
//printk("TRY: START SAMPLING\n");
hcsr_devps->take_meas = true;
//hcsr_devps->currently_sampling == true;
// Initialize sampling operation and place into queue
INIT_WORK(&(hcsr_devps->my_work), work_function);
ret_wq = queue_work(my_wq, &(hcsr_devps->my_work));
}
else {
printk("NO ACTION: cmd = 0\n");
}
while(1) {
// Sleep until taking and processing measurements is done (worker_function should be done)
if(hcsr_devps->currently_sampling == false) {
//printk("INFO: Leave Loop\n");
break;
}
else {
msleep(100);
}
}
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
//printk("SUCCESS: Write Completed\n");
return 0;
}
/*
* Read to hcsr driver
Return current external buffer distance and timestamp
*/
ssize_t hcsr_driver_read(struct file *file, char *buf,
size_t count, loff_t *ppos)
{
int ver;
struct hcsr_dev* hcsr_devps;
int bytes_read = 0;
int minor_number = iminor(file->f_path.dentry->d_inode);
struct hcsr_dev* tmp;
struct hcsr_dev* cursor;
bool found = false;
list_for_each_entry_safe(cursor, tmp, &device_list, list_ptr) {
// Search for matching device
//printk("INFO: Found Device Minor Number = %d\n", cursor->misc.minor);
if(cursor->misc.minor == minor_number) {
hcsr_devps = cursor;
found = true;
}
}
if(found == false) {
printk("ERROR: Could Not Find File\n");
return -1;
}
//struct hcsr_dev *hcsr_devps = file->private_data;
// LOCK
spin_lock(&(hcsr_devps->lock_ops));
if(hcsr_devps->currently_sampling == true) {
printk("ERROR: Read Blocked: Measurement in Progress\n");
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -EINVAL;
}
ver = copy_to_user(buf, &(hcsr_devps->external.buffer[hcsr_devps->external.position-1]), sizeof(struct fifo_buffer));
if(ver < 0) {
printk("ERROR=%d: Copy to user in read error\n", ver);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
return -1;
}
// Update bytes read counter
bytes_read += sizeof(struct fifo_buffer);
// UNLOCK
spin_unlock(&(hcsr_devps->lock_ops));
//Most read functions return the number of bytes put into the buffer
return bytes_read;
}
/* File operations structure for misc devices created by module. Defined in linux/fs.h */
static struct file_operations hcsr_fops = {
.owner = THIS_MODULE, /* Owner */
.open = hcsr_driver_open, /* Open method */
.release = hcsr_driver_release, /* Release method */
.write = hcsr_driver_write, /* Write method */
.read = hcsr_driver_read, /* Read method */
.unlocked_ioctl = hcsr_driver_unlocked_ioctl /* Set pins or change sampling parameters */
};
/*
Helper function for module init that creates the misc device and initializes fields
*/
int create_device(int counter) {
//int verify_pins;
int verify_misc;
int p;
struct hcsr_dev* HCSR_DEVPS;
//printk("TRY: In create_device\n");
HCSR_DEVPS = kmalloc(sizeof(struct hcsr_dev), GFP_KERNEL);
if (!HCSR_DEVPS) {
printk("ERROR: Bad Kmalloc in init\n"); return -ENOMEM;
}
memset(HCSR_DEVPS, 0, sizeof(struct hcsr_dev));
// Initialize fields
//printk("TRY: Initialize misc fields\n");
HCSR_DEVPS->misc.minor = (counter+1);
//printk("TRY: fops\n");
HCSR_DEVPS->misc.fops = &hcsr_fops;
//printk("TRY: Locks\n");
// Set up irq and file operation locks
spin_lock_init(&(HCSR_DEVPS->lock_irq));
spin_lock_init(&(HCSR_DEVPS->lock_ops));
// Name both the misc device and the hcsr_dev device the same
if(counter == 0) {
HCSR_DEVPS->misc.name = DEV1;
//sprintf(HCSR_DEVPS->misc.name, "HCSR_%d", counter +1)
//printk("TRY: hcsrdev name\n");
HCSR_DEVPS->name = DEV1;
}
else if(counter == 1) {
HCSR_DEVPS->misc.name = DEV2;
HCSR_DEVPS->name = DEV2;
}
else if(counter == 2) {
HCSR_DEVPS->misc.name = DEV3;
HCSR_DEVPS->name = DEV3;
}
else if(counter == 3) {
HCSR_DEVPS->misc.name = DEV4;
HCSR_DEVPS->name = DEV4;
}
else if(counter == 4) {
HCSR_DEVPS->misc.name = DEV5;
HCSR_DEVPS->name = DEV5;
}
else {
HCSR_DEVPS->misc.name = DEV6;
HCSR_DEVPS->name = DEV6;
}
//printk("TRY: Register Device\n");
verify_misc = misc_register(&(HCSR_DEVPS->misc));
if(verify_misc != 0) {
printk("ERROR=%d: did not register misc device\n", verify_misc);
memset(HCSR_DEVPS, 0, sizeof(struct hcsr_dev));
kfree(HCSR_DEVPS);
return -1;
}
printk("SUCCESS: Allocated and Registered Device\n");
// Interrupt should start out as rising triggered
HCSR_DEVPS->irq_is_rising = true;
// The average distance buffer pointer starts at position 0 and wraps around [0, 4]
HCSR_DEVPS->external.position = 0;
// Take measurements if this field is true
HCSR_DEVPS->take_meas = false;
// IO Pins should only be set once to prevent user from changing wires while board is running
HCSR_DEVPS->ioctl_pins_blocked = false;
// The general list size of the internal sampling buffer
HCSR_DEVPS->sample_list_size = 0;
// Default sampling parameters
HCSR_DEVPS->sensor_params.num_samples = 5;
HCSR_DEVPS->sensor_params.sampling_period = 200;
// If this is true, write and read operations cannot proceed
HCSR_DEVPS->currently_sampling = false;
// Create internal buffer as a linked list
//printk("TRY: Create internal buffer\n");
for(p=0; p < HCSR_DEVPS->sensor_params.num_samples+2; p++) {
// Create internal sample buffer which has two additional samples for first and last sample
struct sample_tsc* sample;
sample = kmalloc(sizeof(struct sample_tsc), GFP_KERNEL);
if(!sample) {
printk("ERROR: Kmalloc error in creating internal buffer\n");
return -1;
}
memset(sample, 0, sizeof(struct sample_tsc));
sample->order = p;
if(p == 0) {
// First time internal buffer is initialized
INIT_LIST_HEAD(&(HCSR_DEVPS->samples_head));
}
// Add to back of list
list_add_tail(&(sample->list_ptr), &(HCSR_DEVPS->samples_head));
// Update
HCSR_DEVPS->sample_list_size += 1;
}
// NOTE: T=7, I=4 are the default IO parameters
//HCSR_DEVPS->trigger = 7;
//HCSR_DEVPS->echo = 4;
// NOW: pins must be enabled usign IOCTL before write can be called
HCSR_DEVPS->trigger = -1;
HCSR_DEVPS->echo = -1;
HCSR_DEVPS->trigger_enabled = false;
HCSR_DEVPS->echo_enabled = false;
// The IRQ Descriptor for the base echo pin
HCSR_DEVPS->irq_desc_echo = 0;
// Prevents module exit from freeing an uninitialized IRQ
HCSR_DEVPS->has_interrupt = false;
//printk("TRY: Add Device to List");
list_add_tail(&(HCSR_DEVPS->list_ptr), &(device_list));
printk("SUCCESS: Device %d Registered\n", counter+1);
return 0;
}
/*
* Driver Initialization
*/
static bool wq_created = false;
int __init hcsr_driver_init(void)
{
int verify_device;
int counter;
char* my_wq_name = "my_wq";
if(wq_created == false) {
// Create global driver workqueue for handling write calls from multiple devices
//printk("TRY: Create Driver WorkQueue\n");
my_wq = create_workqueue(my_wq_name);
wq_created = true;
}
// Parse user input from insmod
if(NUMBER_OF_DEVICES <= 0) {
printk("ERROR: NUMBER_OF_DEVICES OUT OF RANGE\n");
return -1;
}
if(NUMBER_OF_DEVICES > 6) {
// Cap number of devices at 6
NUMBER_OF_DEVICES = 6;
}
// Create Devices
for(counter = 0; counter < NUMBER_OF_DEVICES; counter++) {
// Create Devices
printk("TRY: Create Device=%d\n", counter+1);
verify_device = create_device(counter);
if(verify_device != 0) {
printk("ERROR: create_device for %d\n", counter+1);
return -1;
}
}
printk("SUCCESS: Created %d Devices\n", counter);
return 0;
}
/* Driver Exit */
void __exit hcsr_driver_exit(void)
{
int i;
// devices
struct hcsr_dev* device;
struct hcsr_dev* tmp;
// internal lists
struct sample_tsc* cursor;
struct sample_tsc* temp;
// Destroy driver workqueue
printk("TRY: Destroy workqueue\n");
destroy_workqueue(my_wq);
list_for_each_entry_safe(device, tmp, &device_list, list_ptr) {
printk("TRY: Free Device Minor Number =%d\n", device->misc.minor);
printk("TRY: Deallocate internal buffer\n");
list_for_each_entry_safe(cursor, temp, &(device->samples_head), list_ptr) {
printk("VAR: Order = %d\n", cursor->order);
printk("VAR: TSC Rising = %lld\n", cursor->tsc_rising);
//printk("VAR: TSC Falling = %lld\n", cursor->tsc_rising);
list_del(&(cursor->list_ptr));
memset(cursor, 0, sizeof(struct sample_tsc));
kfree(cursor);
}
// View external buffer values
for(i=0; i < 5; i++) {
printk("VAR: External Distance = %llu\n",device->external.buffer[i].distance);
}
// Free corresponding interrupt for echo pin if an interrupt handler has been created
if(device->has_interrupt == true) {
printk("TRY: Free Interrupt\n");
free_irq(device->irq_desc_echo, (void*) device);
}
// Free gpio pins
printk("TRY: Free default pins\n");
free_default_trigger_pins_parse(device);
free_default_echo_pins_parse(device);
printk("TRY: Free echo and trigger pins\n");
free_trigger_pins(device);
free_echo_pins(device);
// Deregister device and free it
printk("TRY: Deregister Device\n");
misc_deregister(&(device->misc));
memset(device, 0, sizeof(struct hcsr_dev));
kfree(device);
}
printk("SUCCESS: hcsr driver removed.\n");
}
module_init(hcsr_driver_init);
module_exit(hcsr_driver_exit);
MODULE_LICENSE("GPL");
<file_sep>/Linux_Kernel_Build_With_New_Syscalls/Test/main.c
/* A test program for /dev/kbuf
To run the program, enter "kbuf_tester show" to show the current contend of the buffer.
enter "kbuf_tester write <input_string> to append the <input_string> into the buffer
*/
// TODO: define macros in main
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
/*#include <sys/time.h>
#include <linux/ioctl.h>
#include <linux/rtc.h>*/
#include <time.h>
pthread_t p1;
int fd;
void* access_write() {
char pbuff[1024];
int res;
sleep(1);
memset(pbuff, 0, 1024);
sprintf(pbuff,"%s", "write this");
//printf("'%s'\n", buff);
res = write(fd, pbuff, strlen(pbuff)+1);
if(res == strlen(pbuff)+1){
fprintf(stderr, "Can not write to the device file.\n");
return (void*)-1;
}
return (void*) 0;
}
int main(int argc, char **argv)
{
int res;
unsigned int test;
unsigned int dumpid_open;
unsigned int dumpid_read;
unsigned int dumpid_write;
//unsigned int dumpid_read_2;
unsigned int dumpid_release;
unsigned int second_dumpid_release;
char buff[1024];
int i = 0;
if(argc == 1){
return 0;
}
char* invalid_symbol = "totatlly_invalid";
test = syscall(359, invalid_symbol, 0);
if(test < 0) {
fprintf(stderr,"Expected Value for invalid symbol\n");
sleep(2);
}
char* symbol = "kbuf_driver_open";
dumpid_open = syscall(359, symbol, 1);
if(dumpid_open < 0) {
fprintf(stderr, "ERROR=%d: syscall insdump\n", dumpid_open);
exit(-1);
}
fprintf(stderr, "UVAR: dumpid_open = %u\n", dumpid_open);
char* read_symbol = "kbuf_driver_read";
dumpid_read = syscall(359, read_symbol, 0);
if(dumpid_read < 0) {
fprintf(stderr, "ERROR=%d: insdump read\n", dumpid_read);
exit(-1);
}
char* release_symbol = "kbuf_driver_release";
dumpid_release = syscall(359, release_symbol, 0);
if(dumpid_release < 0) {
fprintf(stderr, "ERROR: insdump release 1\n");
exit(-1);
}
second_dumpid_release = syscall(359, release_symbol, 2);
if(second_dumpid_release < 0) {
fprintf(stderr, "ERROR: insdump release 2\n");
exit(-1);
}
/*
pid_t child_pid = fork();
fprintf(stderr, "UVAR: child_pid = %d\n", child_pid);
if(child_pid < 0) {
fprintf(stderr, "UERROR: child_pid fork\n");
exit(-1);
}
*/
char* write_symbol = "kbuf_driver_write";
dumpid_write = syscall(359, write_symbol, 1);
if(dumpid_write < 0)
{
fprintf(stderr, "ERROR: kbuf_driver_write\n");
exit(-1);
}
res = pthread_create(&p1, NULL, access_write, NULL);
if(res < 0) {
fprintf(stderr, "ERROR=%d: pthread_create\n", res);
exit(-1);
}
/* open devices */
fd = open("/dev/kbuf", O_RDWR);
if (fd < 0 ){
fprintf(stderr, "Can not open device file.\n");
return 0;
}else{
if(strcmp("show", argv[1]) == 0){
memset(buff, 0, 1024);
res = read(fd, buff, 256);
sleep(1);
// printf("'%s'\n", buff);
}else if(strcmp("write", argv[1]) == 0){
memset(buff, 0, 1024);
if(argc >= 3){
sprintf(buff,"%s", argv[2]);
for(i = 3; i < argc; i++)
sprintf(buff,"%s %s",buff,argv[i]);
}
//printf("'%s'\n", buff);
res = write(fd, buff, strlen(buff)+1);
if(res == strlen(buff)+1){
fprintf(stderr, "Can not write to the device file.\n");
return 0;
}
}
/* close devices */
pthread_join(p1, NULL);
close(fd);
}
res = syscall(360, dumpid_open);
if(res < 0) {
fprintf(stderr, "ERROR=%d: rmdump\n", res);
exit(-1);
}
fprintf(stderr, "UINFO: Removed dumpid for open\n");
res = syscall(360, dumpid_read);
if(res < 0) {
fprintf(stderr, "ERROR=%d: rmdump\n", res);
exit(-1);
}
fprintf(stderr, "UINFO; Removed dumpid for read\n");
res = syscall(360, dumpid_release);
if(res < 0) {
fprintf(stderr, "ERROR: rmdump\n");
exit(-1);
}
fprintf(stderr, "UINFO: Removed dumpid for first release\n");
return 0;
}
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/test.sh
#!/bin/bash
echo "Set Trigger"
echo -n 7 > /sys/class/HCSR/HCSR_2/trigger_pin
cat /sys/class/HCSR/HCSR_2/trigger_pin
echo "Set Echo"
echo -n 4 > /sys/class/HCSR/HCSR_2/echo_pin
cat /sys/class/HCSR/HCSR_2/echo_pin
echo "Sampling Period"
echo -n 150 > /sys/class/HCSR/HCSR_2/sampling_period
cat /sys/class/HCSR/HCSR_2/sampling_period
echo "Number Samples"
echo -n 7 > /sys/class/HCSR/HCSR_2/number_samples
cat /sys/class/HCSR/HCSR_2/sampling_period
echo "Latest Distance="
cat /sys/class/HCSR/HCSR_2/latest_distance
echo "Check Enable="
cat /sys/class/HCSR/HCSR_2/enable_measurements
sleep 2
echo "Start Measurements"
echo -n 1 > /sys/class/HCSR/HCSR_2/enable_measurements
sleep 7
echo "Latest Distance="
cat /sys/class/HCSR/HCSR_2/latest_distance
sleep 5
echo "Start Second Device"
echo "Set Echo"
echo -n 5 > /sys/class/HCSR/HCSR_4/echo_pin
cat /sys/class/HCSR/HCSR_4/echo_pin
echo "Set Trigger"
echo -n 8 > /sys/class/HCSR/HCSR_4/trigger_pin
cat /sys/class/HCSR/HCSR_4/trigger_pin
echo -n 1 > /sys/class/HCSR/HCSR_4/enable_measurements
sleep 5
cat /sys/class/HCSR/HCSR_4/latest_distance
<file_sep>/Linux_Kernel_Build_With_New_Syscalls/README.txt
<NAME>
1209035928
Syscall Assignment
README
1)
Apply the patch file to the original kernel (under the .../kernel directory)
patch -p1 < patch.txt
(command should be executed in the same directory that .../kernel is in)
2)
Place the script.sh script in the directory above /kernel
- Modify the path names to match the current system files
- /home/linux/Kernel_Compare/Test/kernel ------> (modify)
- chmod 777 script.sh
- Now run the script ./script.sh
3)
In the galileo_install directory retrieve the bzImage
../galileo-install/lib/modules/3.19.8-yocto-standard/build/arch/x86/boot/bzImage
Then place the image on the SD card and place the SD card in the Galileo board
4)
Boot into the new kernel
5)
Compile Mydriver.c and main.c in the ../Test directory and place main and Mydriver.ko in the Galileo Board
6)
insmod Mydriver.ko
7)
Run the test program
./main show
8)
To go back to the original kernel use
- patch -R p1 < patch.txt
Examples:
[ 123.550811] [<c111d028>] ____fput+0x8/0x10
[ 123.550811] [<c104cdd1>] task_work_run+0x61/0x90
[ 123.550811] [<c1002445>] do_notify_resume+0x65/0x70
[ 123.550811] [<c145762b>] work_notifysig+0x20/0x25
[ 123.550811] KTRY: dump_stack mode 0
[ 123.550811] CPU: 0 PID: 309 Comm: main Tainted: G O 3.19.8-yocto-standard #1
[ 123.550811] Hardware name: Intel Corp. QUARK/GalileoGen2, BIOS 0x01000200 01/01/2014
[ 123.550811] c16488dc c16488dc cd7e3ec4 c1453bb1 cd7e3edc c1256585 c15b1144 ce60e418
[ 123.550811] ce7f95a0 cd7e3f24 cd7e3ef4 c10a27c2 ce60e420 cd7e3f24 ce7f95a0 d29c5021
[ 123.550811] cd7e3f0c c1027fa4 d29c5020 cd7e3f24 00000000 cd7a1168 cd7e3f1c c1002964
[ 123.550811] Call Trace:
[ 123.550811] [<c1453bb1>] dump_stack+0x16/0x18
[ 123.550811] [<c1256585>] Pre_Handler+0x95/0xe0
[ 123.550811] [<c10a27c2>] aggr_pre_handler+0x32/0x70
[ 123.550811] [<d29c5021>] ? kbuf_driver_release+0x1/0x20 [Mydriver]
[ 123.550811] [<c1027fa4>] kprobe_int3_handler+0xb4/0x130
[ 123.550811] [<d29c5020>] ? kbuf_driver_open+0x20/0x20 [Mydriver]
[ 123.550811] [<c1002964>] do_int3+0x44/0xa0
[ 123.550811] [<c1458113>] int3+0x33/0x40
[ 123.550811] [<d29c5020>] ? kbuf_driver_open+0x20/0x20 [Mydriver]
[ 123.550811] [<d29c5021>] ? kbuf_driver_release+0x1/0x20 [Mydriver]
[ 123.550811] [<c111ceda>] ? __fput+0xaa/0x1c0
[ 123.550811] [<c111d028>] ____fput+0x8/0x10
[ 123.550811] [<c104cdd1>] task_work_run+0x61/0x90
[ 123.550811] [<c1002445>] do_notify_resume+0x65/0x70
[ 123.550811] [<c145762b>] work_notifysig+0x20/0x25
[ 124.765917]
[ 124.765917] kbuf is closing
[ 124.780332] KINFO: Found entry in sys_myservice_clear
UINFO: Removed d[ 124.785611] KINFO: Found entry in sys_myservice_clear
umpid for open
UINFO; Removed d[ 124.800250] KINFO: Found entry in sys_myservice_clear
umpid for read
[ 124.806836] KINFO: Unregistered a kprobe in do_exit
[ 124.810054] KINFO: Unregistered a kprobe in do_exit
UINFO: Removed dumpid for first release
<file_sep>/Sensor_Driver_With_Interrupt_Handling/Part2/hcsr.h
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/string.h>
#include <linux/device.h>
#include <linux/jiffies.h>
#include<linux/init.h>
#include<linux/moduleparam.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
//#include <asm/uaccess.h>
#include <linux/uaccess.h>
#include <linux/interrupt.h>
#include <linux/miscdevice.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/time.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/err.h>
#include <asm/msr.h>
#include <linux/spinlock_types.h>
#include <linux/unistd.h>
#include <linux/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/workqueue.h>
#include <linux/list.h>
#define TRIG_PIN_OFF 0
#define TRIG_PIN_ON 1
struct write_argument {
int cmd;
};
struct gpio_pins {
int echo;
int trigger;
};
struct fifo_buffer {
unsigned long long distance;
unsigned long long tsc_first;
unsigned long long tsc_last;
};
struct measurement_sample_params {
int num_samples;
int period_samples;
};
struct return_to_user {
struct fifo_buffer buffer[5];
};
struct sample_tsc {
struct list_head list_ptr;
int order;
unsigned long long distance;
unsigned long long tsc_rising;
unsigned long long tsc_falling;
};
struct external_buffer {
int position;
bool is_ready;
struct fifo_buffer buffer[5];
};
struct hcsr_dev {
struct list_head list_ptr;
struct P_chip pchip;
struct miscdevice misc;
int minor;
spinlock_t lock;
struct list_head samples_head;
struct sample_tsc* cursor;
int sample_list_size;
bool currently_sampling;
int trigger;
int echo;
int number_samples;
int sampling_period;
int enable_measurements;
long long int latest_distance;
bool trigger_enabled;
bool echo_enabled;
dev_t number;
struct external_buffer external;
spinlock_t lock_ops;
spinlock_t lock_irq;
unsigned long lock_irq_flags;
int gpio_trigger;
int gpio_echo;
int irq_desc_echo;
bool irq_is_rising;
bool has_interrupt;
struct work_struct my_work;
bool take_meas;
bool trig_set;
bool echo_set;
bool number_samples_set;
bool sampling_period_set;
bool ioctl_blocked;
char name[20];
char in_string[256];
};<file_sep>/Linux_Kernel_Build_With_New_Syscalls/script.sh
ARCH=x86i
LOCALVERSION=
INSTALL_MOD_PATH=../galileo-install
CROSS_COMPILE=i586-poky-linux-
export PATH=/opt/iot-devkit/1.7.2/sysroots/x86_64-pokysdk-linux/usr/bin/i586-poky-linux:$PATH
make -C /home/linux/Kernel_Compare/Test/kernel headers_check
make -C /home/linux/Kernel_Compare/Test/kernel headers_install
make -C /home/linux/Kernel_Compare/Test/kernel ARCH=x86 CROSS_COMPILE=i586-poky-linux-
make -C /home/linux/Kernel_Compare/Test/kernel ARCH=x86 INSTALL_MOD_PATH=/home/linux/Kernel_Compare/Test/galileo-install CROSS_COMPILE=i586-poky-linux- modules_install
|
60137abf4cfc23e30a5c89b9260f78ca4f887e1b
|
[
"Markdown",
"Makefile",
"Text",
"C",
"Shell"
] | 13
|
Text
|
Xanos20/Linux_Kernel_Modules
|
89444aff2521ddc8adc05f31a4f95dd969080f7b
|
82681a35314575c14d96f0ae3d013c4a114f0f8f
|
refs/heads/master
|
<file_sep>import uuid
from datetime import datetime, timedelta
from .. import db, mail
from ..model.config import Config
def getConfig(dateChange = None):
if dateChange:
return Config.query.filter({"updateDate" : {"$gte": dateChange}}).all()
else:
return Config.query.filter().all()
<file_sep>from .. import db, flask_bcrypt
from passlib.hash import pbkdf2_sha256 as sha256
from datetime import datetime
from .base_model import BaseModel
class Config(BaseModel):
""" User Model for storing user related details """
# query_class = UserQuery
key = db.StringField(required=True)
value = db.StringField(required=True)
def json(self):
return {
'key' : self.key,
'value': self.value,
'updateDate': self.updateDate.strftime("%Y-%m-%d %H:%M:%S"),
'action' : self.action
}
<file_sep>package com.avtdev.jokeworld.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.provider.Settings;
import com.google.gson.Gson;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import androidx.annotation.NonNull;
public class Utils {
public static String getDeviceModel() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private static String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
public static String getDevideId(Context context){
return Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
}
public static String utcToLocal(String utcDate){
String localDate = null;
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(utcDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getDefault());
localDate = dateFormatter.format(value);
} catch (ParseException e) {
localDate = "00-00-0000 00:00";
}
return localDate;
}
public static String localToUtc(String localDate){
String utcDate = null;
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getDefault());
Date value = formatter.parse(localDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
utcDate = dateFormatter.format(value);
} catch (ParseException e) {
utcDate = "00-00-0000 00:00";
}
return utcDate;
}
public static boolean hasChange(Object originalObject, Object newObject){
if(newObject == null){
return false;
}
if(originalObject == null){
return true;
}
String objectString1 = new Gson().toJson(originalObject);
String objectString2 = new Gson().toJson(newObject);
return !objectString1.equals(objectString2);
}
public static boolean isNull(String data){
return data == null || data.trim().length() == 0;
}
public static Object getSharedPreferences(Context context, String key, @NonNull Object defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES.PREFERENCES_FILE, Context.MODE_PRIVATE);
if(defaultValue instanceof String){
return sharedPreferences.getString(key, (String) defaultValue);
}else if(defaultValue instanceof Integer){
return sharedPreferences.getInt(key, (Integer) defaultValue);
}else if(defaultValue instanceof Boolean){
return sharedPreferences.getBoolean(key, (Boolean) defaultValue);
}else{
return null;
}
}
public static String getStringSharedPreferences(Context context, String key, @NonNull String defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES.PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
public static int getIntSharedPreferences(Context context, String key, @NonNull int defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES.PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultValue);
}
public static boolean getBooleanSharedPreferences(Context context, String key, @NonNull boolean defaultValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES.PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, defaultValue);
}
public static void setSharedPreferences(Context context, String key, Object value){
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES.PREFERENCES_FILE, Context.MODE_PRIVATE);
try{
SharedPreferences.Editor edit = sharedPreferences.edit();
if(value == null){
edit.remove(key);
}else if(value instanceof String){
edit.putString(key, (String) value);
}else if(value instanceof Integer){
edit.putInt(key, (Integer) value);
}else if(value instanceof Boolean){
edit.putBoolean(key, (Boolean) value);
}
edit.commit();
}catch (Exception ex){
Logger.error("setSharedPreferences", ex.getMessage());
}
}
}
<file_sep>import os
# uncomment the line below for postgres database url from environment variable
# postgres_local_base = os.environ['DATABASE_URL']
class Config:
SECRET_KEY = os.getenv('SECRET_KEY', 'jwt-secret-string')
JWT_SECRET_KEY = os.getenv('SECRET_KEY', 'jwt-secret-string')
UPLOAD_FOLDER = '/var/www/jokeworld/images'
JWT_REFRESH_TOKEN_EXPIRES = False
MONGOALCHEMY_DATABASE = 'jokeworld'
MONGOALCHEMY_SAFE_SESSION = True
MONGOALCHEMY_PORT = 27017
MONGOALCHEMY_SERVER = "127.0.0.1"
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USERNAME = '<EMAIL>'
MAIL_PASSWORD = '<PASSWORD>'
MAIL_USE_TLS = False
MAIL_USE_SSL = True
class DevelopmentConfig(Config):
DEBUG = True
ENV = ""
class ProductionConfig(Config):
DEBUG = False
ENV = "Production"
config_by_name = dict(
dev=DevelopmentConfig,
prod=ProductionConfig
)
key = Config.SECRET_KEY
<file_sep>import uuid
from datetime import datetime, timedelta
from .. import db, mail
from ..model.user import User
from ..model.device import Device
from flask_mail import Message
from flask import render_template
from ..util.utils import generate_token
def register(email, password, username, deviceId, deviceModel, deviceToken, appVersion, language):
email = email.lower()
user = User.query.filter_by(email=email).first()
if not user:
user = User.query.filter_by(username=username).first()
if not user:
device = Device(deviceId=deviceId, deviceModel=deviceModel, deviceToken=deviceToken, appVersion=appVersion)
new_user = User(
email=email,
username=username,
password=<PASSWORD>.generate_hash(password),
language=language,
deviceInfo=[device]
)
new_user.save()
return 1
else:
return -1
else:
return -2
def find_user(email):
if email:
return User.query.filter_by(email=email.lower()).first()
else:
return None
def get_user(id):
return User.query.get(id)
def login(email, password, deviceId, deviceModel, deviceToken, appVersion):
email = email.lower()
user = User.query.filter_by(email=email).first()
if user:
if user.verify_hash(password):
user.lastLoginDate = datetime.utcnow()
actual_device = Device(deviceId=deviceId, deviceModel=deviceModel, deviceToken=deviceToken, appVersion=appVersion)
for i in range(len(user.deviceInfo)):
if user.deviceInfo[i].deviceId == actual_device.deviceId:
user.deviceInfo[i] = actual_device
actual_device = None
break;
if actual_device is not None:
user.deviceInfo.append(actual_device)
user.save()
return user
else:
return -1
else:
return -1
def modify_user(id, data):
user = User.query.get(id)
if user:
for key in data:
if data[key]:
if key == 'password':
user.password = User.generate_hash(data[key])
else:
setattr(user, key, data[key])
user.save()
return user
else:
return -1
def get_all_users():
return {'users': list(map(lambda user: user.to_json(), User.query.all()))}
def get_a_user(username):
return User.query.filter_by(username=username).first()
def verify_hash(user, password):
return user.verify_hash(password)
def sendPasswordToken(url, email):
user = User.query.filter_by(email = email).first()
if(user is not None):
token = generate_token(30)
msg = Message("jokeworld - Password Reset",
sender="jokeworld",
recipients=[email])
password_reset_url = url+token
msg.html = render_template('passwordEmail.html', url=password_reset_url)
mail.send(msg)
user.save()
user.tokenRecoverDate = datetime.utcnow() + timedelta(days=1)
user.tokenRecoverPassword = token
user.save()
def resetPassword(email, password, token):
user = User.query.filter({"$and": [
{"email" : email},
{"tokenRecoverPassword" : token}
]}).first()
if(user is not None and user.tokenRecoverDate > datetime.utcnow()):
user.password = User.generate_hash(password)
user.tokenRecoverDate = None
user.tokenRecoverPassword = None
user.save()
return 1
else:
return -1
<file_sep>
import traceback
import logging
CODE = {
200 : "OK",
201 : "Created",
202 : "Accepted",
204 : "No Content",
205 : "Reset Content",
206 : "Partial Content",
301 : "Moved Permanently",
302 : "Found",
303 : "See Other",
304 : "Not Modified",
307 : "Temporary Redirect",
400 : "Bad Request",
401 : "Unauthorized",
402 : "Payment Required",
403 : "Forbidden",
404 : "Not Found",
405 : "Method Not Allowed",
406 : "Not Acceptable",
408 : "Request Timeout",
409 : "Already Exists",
412 : "Precondition Failed",
415 : "Unsupported Media Type",
428 : "Precondition Required",
500 : "Internal Server Error",
501 : "Not Implemented"
}
class Response():
def __init__(self, status, *args, **kwargs):
self.status = status
self.message = CODE[status]
if kwargs:
self.response = kwargs
else:
self.response = None
def catchException(e):
if e.__class__.__name__ == "BadRequest":
return Response(400).__dict__
else:
logging.error(traceback.format_exc())
return Response(500).__dict__
<file_sep>from .. import db, flask_bcrypt
from passlib.hash import pbkdf2_sha256 as sha256
from datetime import datetime
from .base_model import BaseModel
from .device import Device
class User(BaseModel):
""" User Model for storing user related details """
# query_class = UserQuery
email = db.StringField(required=True)
username = db.StringField(required=False)
password = db.StringField(required=False)
registeredDate = db.DateTimeField(required=True, default=datetime.utcnow())
lastLoginDate = db.DateTimeField(required=True, default=datetime.utcnow())
country = db.StringField(required=False)
profileImage = db.StringField(required=False)
deviceInfo = db.ListField(db.DocumentField(Device))
language = db.StringField(required=True, default="en")
tokenRecoverPassword = db.StringField(required=True, default=None)
tokenRecoverDate = db.DateTimeField(required=True, default=None)
privacyAcceptedVersion = db.IntField(required=True, default=0)
notificationEnabled = db.BoolField(required=True, default=True)
@staticmethod
def generate_hash(password):
return sha256.hash(password)
def verify_hash(self, password):
return sha256.verify(password, self.password)
def json(self):
return {
'_id' : str(self.mongo_id),
'email' : self.email,
'username': self.username,
'language': self.language,
'registeredDate': self.registeredDate.strftime("%Y-%m-%d %H:%M:%S"),
'country': getattr(self, 'country', None),
'deviceInfo': list(map(lambda device: device.json(), self.deviceInfo)),
'profileImage' : getattr(self, 'profileImage,', None),
'notificationEnabled' : self.notificationEnabled,
'privacyAcceptedVersion' : self.privacyAcceptedVersion,
'updateDate': self.updateDate.strftime("%Y-%m-%d %H:%M:%S"),
'action' : self.action
}
<file_sep>package com.avtdev.jokeworld.utils;
public class Constants {
public static final class PERMISSIONS{
public static final int READ_USER = 1;
public static final int READ_JOKE = 2;
}
public static final class CALLBACKS{
public static final int USER_IMAGE = 1;
public static final int JOKE_IMAGE= 2;
}
public static final class PREFERENCES{
public static final String PREFERENCES_FILE = "JOKE_PREFERENCES";
public static final String ACCESS_TOKEN = "ACCESS_TOKEN";
public static final String REFRESH_TOKEN = "REFRESH_TOKEN";
}
public static final class HTTP_CODES{
public static final int OK = 200;
public static final int UNAUTHORIZED = 401;
}
}
<file_sep>package com.avtdev.jokeworld.cache;
import io.realm.DynamicRealm;
import io.realm.RealmMigration;
public class Migration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
if (oldVersion < 105) {
realm.deleteAll();
return;
}
}
}
<file_sep>alembic==1.0.7
aniso8601==4.1.0
bcrypt==3.1.6
cffi==1.11.5
Click==7.0
Flask==1.0.2
Flask-Bcrypt==0.7.1
Flask-JWT-Extended==3.17.0
Flask-MongoAlchemy==0.7.2
Flask-PyMongo==2.2.0
Flask-RESTful==0.3.7
Flask-Script==2.0.6
itsdangerous==1.1.0
Jinja2==2.10
jsonschema==2.6.0
Mako==1.0.7
MarkupSafe==1.1.0
MongoAlchemy==0.19
passlib==1.7.1
pycparser==2.19
PyJWT==1.7.1
pymongo==2.8.1
python-dateutil==2.8.0
python-editor==1.0.4
pytz==2018.9
six==1.12.0
Werkzeug==0.15.3
<file_sep>import os
import sys
import time
import signal
import threading
import atexit
from pathlib import Path
try:
import Queue as queue
except ImportError:
import queue
_interval = 1.0
_times = {}
_files = []
_running = False
_queue = queue.Queue()
_lock = threading.Lock()
def _restart(path):
_queue.put(True)
os.kill(os.getpid(), signal.SIGINT)
def _modified(path):
try:
# If path doesn't denote a file and were previously
# tracking it, then it has been removed or the file type
# has changed so force a restart. If not previously
# tracking the file then we can ignore it as probably
# pseudo reference such as when file extracted from a
# collection of modules contained in a zip file.
if not os.path.isfile(path):
return path in _times
# Check for when file last modified.
mtime = os.stat(path).st_mtime
if path not in _times:
_times[path] = mtime
# Force restart when modification time has changed, even
# if time now older, as that could indicate older file
# has been restored.
if mtime != _times[path]:
return True
except:
# If any exception occured, likely that file has been
# been removed just before stat(), so force a restart.
return True
return False
def _monitor():
while 1:
# Check modification times on all files in sys.modules.
for folder in _files:
for file in Path(folder).glob('**/*.py'):
if _modified(file):
_restart(file)
break
# Go to sleep for specified interval.
try:
return _queue.get(timeout=_interval)
except:
pass
_thread = threading.Thread(target=_monitor)
_thread.setDaemon(True)
def _exiting():
try:
_queue.put(True)
except:
pass
_thread.join()
atexit.register(_exiting)
def track(path):
if not path in _files:
_files.append(path)
def start(interval=1.0):
global _interval
if interval < _interval:
_interval = interval
global _running
_lock.acquire()
if not _running:
_running = True
_thread.start()
_lock.release()
<file_sep>from .. import db, flask_bcrypt
from datetime import datetime
class BaseModel(db.Document):
createdDate = db.DateTimeField(required=True, default=datetime.utcnow())
updateDate = db.DateTimeField(required=True, default=datetime.utcnow())
action = db.StringField(required=True, default="INSERTED")
def save(self, *args, **kwargs):
if not hasattr(self, 'mongo_id'):
self.startDate = datetime.utcnow()
self.action = "INSERTED"
else:
self.action = "UPDATED"
self.updateDate = datetime.utcnow()
return super(BaseModel, self).save(*args, **kwargs)
def remove(self, *args, **kwargs):
self.action = "DELETED"
self.updateDate = datetime.utcnow()
return super(BaseModel, self).save(*args, **kwargs)
<file_sep>from .. import db, flask_bcrypt
from .base_model import BaseModel
class Device(db.Document):
deviceId = db.StringField()
deviceModel = db.StringField()
deviceToken = db.StringField()
appVersion = db.StringField()
def json(self):
return {
'deviceId' : self.deviceId,
'deviceModel' : self.deviceModel,
'deviceToken' : self.deviceToken,
'appVersion': self.appVersion
}
<file_sep>package com.avtdev.jokeworld.interfaces;
import java.util.List;
public interface ILoginActivityCallback {
/*
public void loginReslt(int status, SerializedUser serializedUser, List<SerializedConfig> serializedConfig);
public void signupResult(int status, SerializedUser serializedUser, List<SerializedConfig> serializedConfig);
public void passwordRecoveryResult(int status);*/
}
<file_sep>package com.avtdev.jokeworld.activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.avtdev.jokeworld.cache.CacheManager;
import com.avtdev.jokeworld.cache.model.Config;
import com.avtdev.jokeworld.utils.Constants;
import com.avtdev.jokeworld.utils.ImageManager;
import com.avtdev.jokeworld.utils.Logger;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
public class BaseActivity extends AppCompatActivity {
protected CacheManager mCacheManager;
private AlertDialog mProgressDialog;
boolean declined = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCacheManager = CacheManager.getInstance(this);
}
protected boolean checkPermission(int permissionCode) {
boolean permissionGranted = false;
switch (permissionCode) {
case Constants.PERMISSIONS.READ_USER:
case Constants.PERMISSIONS.READ_JOKE:
if (ActivityCompat.checkSelfPermission(BaseActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(BaseActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, permissionCode);
} else {
permissionGranted = true;
}
break;
}
return permissionGranted;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case Constants.PERMISSIONS.READ_USER:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ImageManager.pickImage(this, Constants.CALLBACKS.USER_IMAGE);
} else {
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
case Constants.PERMISSIONS.READ_JOKE:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ImageManager.pickImage(this, Constants.CALLBACKS.JOKE_IMAGE);
} else {
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
}
}
/*
protected void showErrorDialog(Integer iconId, Integer titleId, Integer infoId){
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.dialog_error, null);
((ImageView) dialogView.findViewById(R.id.errorDialogIcon)).setImageDrawable(getDrawable(iconId != null ? iconId : R.drawable.ic_default_error));
((TextView) dialogView.findViewById(R.id.errorDialogTitle)).setText(getString(titleId != null ? titleId : R.string.error_server_title));
((TextView) dialogView.findViewById(R.id.errorDialogInfo)).setText(getString(infoId != null ? infoId : R.string.error_server_info));
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setView(dialogView);
dialogView.findViewById(R.id.bt_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
protected void showNoInternetDialog(){
showErrorDialog(R.drawable.ic_no_internet, R.string.error_no_internet_title, R.string.error_no_internet_info);
}
protected void showServerErrorDialog(){
showErrorDialog(R.drawable.ic_cloud_off, R.string.error_server_title, R.string.error_server_info);
}
public void showProgressDialog(){
if(mProgressDialog == null){
ProgressBar progressBar = new ProgressBar(this);
progressBar.setIndeterminate(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(progressBar);
builder.setCancelable(false);
mProgressDialog = builder.create();
mProgressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
mProgressDialog.show();
}
public void hideProgressDialog(){
if(mProgressDialog != null){
mProgressDialog.hide();
}
}
protected void showPrivacyDialog(){
Config privacyConfig = mCacheManager.findConfig(Constants.ConfigKeys.PRIVACY_URL);
Config privacyVersionConfig = mCacheManager.findConfig(Constants.ConfigKeys.PRIVACY_VERSION);
Integer privacyVersion = -1;
try {
privacyVersion = privacyVersionConfig != null ? Integer.valueOf(privacyVersionConfig.getValue()) : privacyVersion;
}catch (Exception e){
Logger.error(null, e.getMessage());
}
declined = false;
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.dialog_privacy, null);
WebView webView = dialogView.findViewById(R.id.privacyWebView);
if(privacyVersion == null || privacyVersion <= serializedUser.getPrivacyAcceptedVersion()){
((LoginActivity) this).enterApplication(serializedUser);
return;
}
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setView(dialogView);
final Button acceptButton = dialogView.findViewById(R.id.btn_accept);
acceptButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
((LoginActivity) BaseActivity.this).enterApplication(serializedUser);
}
});
dialogView.findViewById(R.id.btn_decline).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(declined){
dialog.dismiss();
logout();
}else{
declined = true;
showErrorDialog(R.drawable.ic_lock, R.string.error_privacy_declined_title, R.string.error_privacy_declined_info);
}
}
});
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(final WebView view, String url) {
super.onPageFinished(view, url);
acceptButton.setEnabled(true);
view.postDelayed( new Runnable () {
@Override
public void run() {
view.scrollTo(0, 0);
}
}, 100);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
setTitle("Loading...");
setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
setTitle(R.string.app_name);
}
});
webView.loadUrl(privacyConfig.getValue());
dialog.show();
}
protected void logout(){
if(!(this instanceof LoginActivity)){
mCacheManager.logout();
Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}*/
}
<file_sep>import json
from json import JSONEncoder
from ..model.base_model import BaseModel
class JSONEncoder(JSONEncoder):
def default (self, obj):
if isinstance (obj, BaseModel):
return obj.json()
return json.JSONEncoder.default(self, obj)
<file_sep>import os
from flask import url_for
from werkzeug.utils import secure_filename
def upload_image(image):
if image and allowed_file(image.filename):
# From flask uploading tutorial
filename = secure_filename(image.filename)
image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return url_for('uploaded_file', filename=filename)
else:
return -1
<file_sep>package com.avtdev.jokeworld.cache.model;
import io.realm.RealmModel;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Config extends RealmObject implements RealmModel {
@PrimaryKey
private String key;
private String value;
public Config(){}
/*
public Config(SerializedConfig serializedUser){
this.key = serializedUser.getKey();
this.value = serializedUser.getValue();
}*/
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value ;
}
}
<file_sep>from flask import Flask
from flask_mongoalchemy import MongoAlchemy
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager
from flask_mail import Mail
from .config import config_by_name
db = MongoAlchemy()
flask_bcrypt = Bcrypt()
jwt = JWTManager()
mail = Mail()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_by_name[config_name])
db.init_app(app)
jwt.init_app(app)
mail.init_app(app)
flask_bcrypt.init_app(app)
return app
<file_sep>package com.avtdev.jokeworld.nerwork;
import android.content.Context;
import com.avtdev.jokeworld.BuildConfig;
import com.avtdev.jokeworld.utils.Constants;
import com.avtdev.jokeworld.utils.Utils;
import com.google.gson.Gson;
import java.io.IOException;
import javax.xml.validation.Validator;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import static co.abc.utils.abcConstants.ACCESS_TOKEN;
import static co.abc.utils.abcConstants.BASE_URL;
import static co.abc.utils.abcConstants.GCM_TOKEN;
import static co.abc.utils.abcConstants.JWT_TOKEN_PREFIX;
import static co.abc.utils.abcConstants.REFRESH_TOKEN;
import static com.avtdev.jokeworld.utils.Constants.PREFERENCES.ACCESS_TOKEN;
/**
* Created by ravindrashekhawat on 21/03/17.
*/
public class AuthorizationInterceptor implements Interceptor {
private static Retrofit retrofit = null;
private static String accessToken;
private static String refreshToken;
private static Context mContext;
public AuthorizationInterceptor(Context context) {
this.mContext = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request modifiedRequest = null;
accessToken = Utils.getStringSharedPreferences(mContext, ACCESS_TOKEN, "");
Response response = chain.proceed(request);
accessToken = Utils.getStringSharedPreferences(mContext, ACCESS_TOKEN, "");
if (response.code() == Constants.HTTP_CODES.UNAUTHORIZED && !Utils.isNull(accessToken)) {
if(accessToken != null){
modifiedRequest = request.newBuilder()
.addHeader("Authorization", "Bearer " + accessToken)
.build();
return chain.proceed(modifiedRequest);
}
}
return response;
}
public String refreshToken() {
final String accessToken = null;
RequestBody reqbody = RequestBody.create(null, new byte[0]);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BuildConfig.URL + "/autologin")
.method("POST", reqbody)
.addHeader("Authorization", "Bearer " + refreshToken)
.build();
try {
Response response = client.newCall(request).execute();
if (response.code() == Constants.HTTP_CODES.OK) {
// Get response
String jsonData = response.body().string();
Gson gson = new Gson();
RefreshTokenResponseModel refreshTokenResponseModel = gson.fromJson(jsonData, RefreshTokenResponseModel.class);
if (refreshTokenResponseModel.getRespCode().equals("1")) {
Utils.setSharedPreferences(mContext, ACCESS_TOKEN, refreshTokenResponseModel.getResponse());
return refreshTokenResponseModel.getResponse();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return accessToken;
}
}<file_sep>from flask_restful import Resource, reqparse
from ..model.user import User
from ..model.config import Config
from ..service import user_service, config_service
import traceback
import logging
from ..util.response import Response, catchException
from ..util import image_manager
from ..util import utils
import datetime
from flask import render_template, make_response, request
from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt)
general_parser = reqparse.RequestParser(bundle_errors=False)
expires = datetime.timedelta(minutes=1)
class UserRegistration(Resource):
def post(self):
parser = general_parser.copy()
parser.add_argument('username', required = True, trim=True)
parser.add_argument('email', required = True, trim=True)
parser.add_argument('password', required = True, trim=True)
parser.add_argument('deviceId', required = True, trim=True)
parser.add_argument('deviceModel', required = True, trim=True)
parser.add_argument('deviceToken', required = True, trim=True)
parser.add_argument('appVersion', required = True, trim=True)
parser.add_argument('language', required = False, default="en", trim=True)
try:
data = parser.parse_args()
if not data["username"] or not data["email"] or not data["password"] or not data["deviceId"] or not data["deviceModel"] or not data["deviceToken"] or not data["appVersion"]:
return Response(400).__dict__
result = user_service.register(
email=data["email"],
password=data["<PASSWORD>"],
username=data["username"],
deviceId=data["deviceId"],
deviceModel=data["deviceModel"],
deviceToken=data["deviceToken"],
appVersion=data["appVersion"],
language=data["language"]
)
if result == 1:
new_user = user_service.find_user(data['email'])
config = config_service.getConfig()
access_token = create_access_token(identity = str(new_user.mongo_id), expires_delta=expires)
refresh_token = create_refresh_token(identity = str(new_user.mongo_id), expires_delta=False)
expired_date = datetime.datetime.utcnow() + expires
return Response(200, user=new_user.json(), access_token=access_token, refresh_token=refresh_token, expired_date=expired_date.strftime("%Y-%m-%d %H:%M:%S"), config=utils.list_to_json(config)).__dict__
elif result == -1:
return Response(406).__dict__
else:
return Response(409).__dict__
except Exception as e:
return catchException(e)
class UserLogin(Resource):
def post(self):
parser = general_parser.copy()
parser.add_argument('email', required = True)
parser.add_argument('password', required = True)
parser.add_argument('deviceId', required = True)
parser.add_argument('deviceModel', required = True)
parser.add_argument('deviceToken', required = True)
parser.add_argument('appVersion', required = True)
parser.add_argument('language', required = False, default="en")
try:
data = parser.parse_args()
result = user_service.login(
email=data['email'],
password=data['<PASSWORD>'],
deviceId=data['deviceId'],
deviceModel=data['deviceModel'],
deviceToken=data['deviceToken'],
appVersion=data['appVersion'])
if result == -1:
return Response(401).__dict__
else:
config = config_service.getConfig()
access_token = create_access_token(identity = str(result.mongo_id), expires_delta=expires)
refresh_token = create_refresh_token(identity = str(result.mongo_id), expires_delta=False)
expired_date = datetime.datetime.utcnow() + expires
return Response(200, user=result.json(), config=utils.list_to_json(config), access_token=access_token, refresh_token=refresh_token, expired_date=expired_date.strftime("%Y-%m-%d %H:%M:%S")).__dict__
except Exception as e:
return catchException(e)
class UserModify(Resource):
@jwt_required
def post(self):
parser = general_parser.copy()
parser.add_argument('language', required = False)
parser.add_argument('country', required = False)
parser.add_argument('password', required = False)
try:
data = parser.parse_args()
print(data)
user_id = get_jwt_identity()
user = user_service.modify_user(user_id, data)
if user == -1:
return Response(304).__dict__
else:
return Response(200, user=user.json()).__dict__
except Exception as e:
return catchException(e)
class ChangeProfilePicture(Resource):
@jwt_required
def post(self):
parser = general_parser.copy()
parser.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files')
try:
data = change_picture_parser.parse_args()
current_user = get_jwt_identity()
except Exception as e:
return catchException(e)
class TokenRefresh(Resource):
@jwt_refresh_token_required
def post(self):
try:
user_id = get_jwt_identity()
user = user_service.get_user(user_id)
access_token = create_access_token(identity = user_id)
return Response(200, user=user.json(), access_token=access_token).__dict__
except Exception as e:
return catchException(e)
class PasswordRecoverEmail(Resource):
def post(self):
parser = general_parser.copy()
parser.add_argument('email', required = True)
try:
data = parser.parse_args()
url_base = request.base_url.replace(request.path, "/recoverPassword/")
user_service.sendPasswordToken(url=url_base , email=data['email'])
return Response(200).__dict__
except Exception as e:
return catchException(e)
class PasswordRecoverChange(Resource):
def post(self):
parser = general_parser.copy()
parser.add_argument('email', required = True)
parser.add_argument('password', required = True)
parser.add_argument('token', required = True)
try:
data = parser.parse_args()
url_base = request.base_url.replace(request.path, "/recoverPassword/")
user_service.resetPassword(email=data['email'], password=data['<PASSWORD>'], token=data['token'])
print(data)
headers = {'Content-Type': 'text/html'}
return make_response(render_template('resetPasswordOk.html'), 200, headers)
except Exception as e:
return catchException(e)
class PasswordRecoverPage(Resource):
def get(self, token):
try:
headers = {'Content-Type': 'text/html'}
return make_response(render_template('resetPassword.html', token=token ), 200, headers)
except Exception as e:
return catchException(e)
<file_sep>package com.avtdev.jokeworld.nerwork.controllers;
import android.content.Context;
import com.avtdev.jokeworld.nerwork.apis.UserApi;
import com.avtdev.jokeworld.utils.Logger;
public class UserController extends AbstractController{
public static UserController mInstance;
UserApi mUserApi;
private UserController(){
super();
mUserApi = mRetrofitBuilder.build().create(UserApi.class);
}
public UserController getInstance(){
if(mInstance == null) {
mInstance = new UserController();
}
return mInstance;
}
public void login(Context context, String email, String password, ICallback listener){
try{
mUserApi.
}catch (Exception ex){
Logger.error("login", ex.getMessage());
}
}
}
<file_sep>import sys
import logging
import os
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/home/jokeworld/flask/')
import monitor
monitor.start(interval=1.0)
monitor.track('/home/jokeworld/flask/')
from app import blueprint
from flask_script import Manager
from app.main import create_app
application = create_app(os.getenv('BOILERPLATE_ENV') or 'dev')
application.register_blueprint(blueprint)
application.app_context().push()
manager = Manager(application)
@manager.command
def run():
application.run()
if __name__ == '__main__':
manager.run()
<file_sep>import random
import re
import json
def create_alphabet(numbers = True, upper_case = True, lower_case = True):
alphabet = []
# Numbers
if numbers:
for letter in range(65, 91):
alphabet.append(chr(letter))
# Upper Case
if upper_case:
for letter in range(65, 91):
alphabet.append(chr(letter))
# Lower Case
if lower_case:
for letter in range(65, 91):
alphabet.append(chr(letter))
return alphabet
def generate_token(length, word = ''):
word = re.sub('[^A-Za-z0-9]', '', word)
length = length - len(word)
token = ''.join(random.choice(create_alphabet()) for _ in range(length))
for char in word.upper():
index = range(len(token))
token = token[index:] + char + token[:index]
return token
def list_to_json(value_list):
return list(map(lambda value: value.json(), value_list))
<file_sep>from flask_restful import Api
from flask import Blueprint
import app
blueprint = Blueprint('api', __name__)
api = Api(blueprint)
# Routes
from .main.controller import user_controller
api.add_resource(user_controller.UserRegistration, '/registration')
api.add_resource(user_controller.UserLogin, '/login')
api.add_resource(user_controller.TokenRefresh, '/autologin')
api.add_resource(user_controller.UserModify, '/modify')
api.add_resource(user_controller.PasswordRecoverEmail, '/passwordRecover')
api.add_resource(user_controller.PasswordRecoverPage, '/recoverPassword/<string:token>')
api.add_resource(user_controller.PasswordRecoverChange, '/changePassword')
|
7656899888f6ccfcfc63f248fcac6118785a91b0
|
[
"Java",
"Python",
"Text"
] | 25
|
Python
|
SarkV/JokeWorld
|
8f8cefb83c74a3aedb5672b12e58dafa559134d2
|
f3f74cd32238ff1b94a0986d4716d37701c56855
|
refs/heads/main
|
<file_sep># Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [6.1.4](https://github.com/marko-js/testing-library/compare/v6.1.3...v6.1.4) (2023-05-09)
### Bug Fixes
* allow in template input types ([058b839](https://github.com/marko-js/testing-library/commit/058b839c9354dfdc9780569f87bb9689fd93c3e1))
### [6.1.3](https://github.com/marko-js/testing-library/compare/v6.1.2...v6.1.3) (2023-05-08)
### [6.1.2](https://github.com/marko-js/testing-library/compare/v6.1.1...v6.1.2) (2022-04-22)
### Bug Fixes
* avoid erroring when reading instance in ssr mode ([2f5fcc0](https://github.com/marko-js/testing-library/commit/2f5fcc0f16d38e8cd9d96de14578d53f8e2353e8))
### [6.1.1](https://github.com/marko-js/testing-library/compare/v6.1.0...v6.1.1) (2022-04-22)
### Bug Fixes
* issue with instance property being read on ssr test load ([7fb3398](https://github.com/marko-js/testing-library/commit/7fb3398d30ce66888a1265cc2e3e9b47eab39355))
## [6.1.0](https://github.com/marko-js/testing-library/compare/v6.0.0...v6.1.0) (2022-04-01)
### Features
* expose instance property from render ([0fd1e22](https://github.com/marko-js/testing-library/commit/0fd1e220fcba4a5f5d0b951bae925241e1afaca3))
## [6.0.0](https://github.com/marko-js/testing-library/compare/v5.1.0...v6.0.0) (2021-10-21)
### ⚠ BREAKING CHANGES
* see https://github.com/testing-library/dom-testing-library/releases/tag/v8.0.0
### Features
* upgrade to @testing-library/dom@8 ([2760e58](https://github.com/marko-js/testing-library/commit/2760e58b26459f9a804a2751619c0e0e62a88229))
## [5.1.0](https://github.com/marko-js/testing-library/compare/v5.0.4...v5.1.0) (2021-07-23)
### Features
* expose helper to perform action and wait for update ([#13](https://github.com/marko-js/testing-library/issues/13)) ([7cd9d12](https://github.com/marko-js/testing-library/commit/7cd9d12f510a61b42d96fa0aae8d784692a555d8))
### [5.0.4](https://github.com/marko-js/testing-library/compare/v5.0.3...v5.0.4) (2021-06-11)
### Bug Fixes
* improve commonjs support for ssr screen api ([4ef10a3](https://github.com/marko-js/testing-library/commit/4ef10a3bcd072c6e54895213d63e6f317581db1e))
### [5.0.3](https://github.com/marko-js/testing-library/compare/v5.0.2...v5.0.3) (2021-06-03)
### Bug Fixes
* use batching closer to Marko's for fireEvent ([69c0d99](https://github.com/marko-js/testing-library/commit/69c0d99eeac8efc1749ae2a9f57d4e7447d9af81))
### [5.0.2](https://github.com/marko-js/testing-library/compare/v5.0.1...v5.0.2) (2021-06-02)
### Bug Fixes
* issue with resolving browser utils ([fa94d16](https://github.com/marko-js/testing-library/commit/fa94d16bf116be6e8f63ac5639c9d07d35171bd3))
### [5.0.1](https://github.com/marko-js/testing-library/compare/v5.0.0...v5.0.1) (2021-06-02)
### Bug Fixes
* don't publish tsbuildinfo ([0562beb](https://github.com/marko-js/testing-library/commit/0562beb17ec20cd1fe9442efe17dc84c11e734f5))
## [5.0.0](https://github.com/marko-js/testing-library/compare/v4.1.0...v5.0.0) (2021-06-02)
### ⚠ BREAKING CHANGES
* drop support for `cleanup-after-each` import, now this is the default
### Features
* support `screen` export ([#12](https://github.com/marko-js/testing-library/issues/12)) ([fe01359](https://github.com/marko-js/testing-library/commit/fe0135949c19029645293d722ba75b165281e5af))
## [4.1.0](https://github.com/marko-js/testing-library/compare/v4.0.3...v4.1.0) (2021-04-06)
### Features
* better support @testing-library/jest-dom for ssr tests ([333d860](https://github.com/marko-js/testing-library/commit/333d860b13fed9049302ba4ba5da8fb0852f44dd))
### [4.0.3](https://github.com/marko-js/testing-library/compare/v4.0.2...v4.0.3) (2020-07-30)
### [4.0.2](https://github.com/marko-js/testing-library/compare/v4.0.1...v4.0.2) (2020-05-13)
### Bug Fixes
* ignore coverage for batched uupdate fallback ([68d1756](https://github.com/marko-js/testing-library/commit/68d1756eaa20f8ded99b9a6afc65a82f09ee164a))
* regression caused by tslib update ([0c740ea](https://github.com/marko-js/testing-library/commit/0c740eaa4794d9ef31f580acf295108fdcb4ceb3))
### [4.0.1](https://github.com/marko-js/testing-library/compare/v4.0.0...v4.0.1) (2020-04-20)
### Bug Fixes
* prevent race conditions when waiting for updates from fireEvent ([92fd78f](https://github.com/marko-js/testing-library/commit/92fd78fd7829c5fcb1dcde31e9fd82deff5de751))
## [4.0.0](https://github.com/marko-js/testing-library/compare/v3.0.2...v4.0.0) (2020-04-13)
### ⚠ BREAKING CHANGES
* https://github.com/testing-library/dom-testing-library/releases/tag/v7.0.0
### Features
* upgrade @testing-library/dom-testing-library ([#7](https://github.com/marko-js/testing-library/issues/7)) ([9b39530](https://github.com/marko-js/testing-library/commit/9b39530bd5800f192cf7e90a041d5d7179d1e040))
### [3.0.2](https://github.com/marko-js/testing-library/compare/v3.0.1...v3.0.2) (2020-04-10)
### Bug Fixes
* return the result of fireEvent in our async wrapper ([71fdfd1](https://github.com/marko-js/testing-library/commit/71fdfd1))
### [3.0.1](https://github.com/marko-js/testing-library/compare/v3.0.0...v3.0.1) (2020-02-22)
### Bug Fixes
* reset id counter on cleanup ([#5](https://github.com/marko-js/testing-library/issues/5)) ([335ab49](https://github.com/marko-js/testing-library/commit/335ab49))
## [3.0.0](https://github.com/marko-js/testing-library/compare/v2.1.0...v3.0.0) (2019-10-24)
### ⚠ BREAKING CHANGES
* @testing-library/dom has been upgraded, see https://github.com/testing-library/dom-testing-library/releases/tag/v6.0.0
### Bug Fixes
* allow Marko 3 as a peerDep and upgrade testing library deps ([a6e0156](https://github.com/marko-js/testing-library/commit/a6e0156b71d69be2e95e5afb4f477ac6da03a4f0))
## [2.1.0](https://github.com/marko-js/testing-library/compare/v2.0.1...v2.1.0) (2019-10-11)
### Features
* add browser context to server tests, improve errors ([e94c651](https://github.com/marko-js/testing-library/commit/e94c651))
### [2.0.1](https://github.com/marko-js/testing-library/compare/v2.0.0...v2.0.1) (2019-08-01)
### Bug Fixes
* rerender legacy compatibility components ([ad3f90b](https://github.com/marko-js/testing-library/commit/ad3f90b))
## [2.0.0](https://github.com/marko-js/testing-library/compare/v1.1.2...v2.0.0) (2019-07-30)
### Features
* export our own async version of fireEvent ([#3](https://github.com/marko-js/testing-library/issues/3)) ([7ff8fbe](https://github.com/marko-js/testing-library/commit/7ff8fbe))
### BREAKING CHANGES
* fireEvent no longer returns a boolean and instead
returns a promise.
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<file_sep>import type { EventType } from "@testing-library/dom";
import {
fireEvent as originalFireEvent,
FireFunction as originalFireFunction,
FireObject as originalFireObject,
} from "@testing-library/dom";
export interface EventRecord {
"*"?: Array<{ type: string; args: unknown[] }>;
[x: string]: unknown[] | undefined;
}
export interface RenderOptions {
container?: Element | DocumentFragment;
}
export const INTERNAL_EVENTS = [
"create",
"input",
"render",
"mount",
"update",
"destroy",
] as const;
export type InternalEventNames = (typeof INTERNAL_EVENTS)[number];
export type FireFunction = (
...params: Parameters<originalFireFunction>
) => Promise<ReturnType<originalFireFunction>>;
export type FireObject = {
[K in EventType]: (
...params: Parameters<originalFireObject[keyof originalFireObject]>
) => Promise<ReturnType<originalFireFunction>>;
};
export async function act<T extends (...args: unknown[]) => unknown>(fn: T) {
type Return = ReturnType<T>;
if (typeof window === "undefined") {
throw new Error(
"Cannot perform client side interaction tests on the server side. Please use @marko/testing-library in a browser environment."
);
}
const result = await fn();
await waitForBatchedUpdates();
return result as T extends (...args: unknown[]) => Promise<unknown>
? AsyncReturnValue<T>
: Return;
}
export const fireEvent = ((...params) =>
act(() => originalFireEvent(...params))) as FireFunction & FireObject;
(Object.keys(originalFireEvent) as EventType[]).forEach(
(eventName: EventType) => {
const fire = originalFireEvent[eventName];
fireEvent[eventName] = (...params) => act(() => fire(...params));
}
);
export type AsyncReturnValue<
AsyncFunction extends (...args: any) => Promise<any>
> = Parameters<
NonNullable<Parameters<ReturnType<AsyncFunction>["then"]>[0]>
>[0];
type Callback = (...args: unknown[]) => void;
const tick =
// Re-implements the same scheduler Marko 4/5 is using internally.
typeof window === "object" && typeof window.postMessage === "function"
? (() => {
let queue: Callback[] = [];
const id = `${Math.random()}`;
window.addEventListener("message", ({ data }) => {
if (data === id) {
const callbacks = queue;
queue = [];
for (const cb of callbacks) {
cb();
}
}
});
return (cb: Callback) => {
if (queue.push(cb) === 1) {
window.postMessage(id, "*");
}
};
})()
: (cb: Callback) => setTimeout(cb, 0);
function waitForBatchedUpdates() {
return new Promise(tick);
}
<file_sep>import { render, cleanup } from "../index";
import HelloWorld from "./fixtures/hello-world.marko";
beforeEach(() => {
jest.spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
cleanup();
(console.log as any).mockRestore();
});
test("debug pretty prints the component content as html", async () => {
const { debug } = await render(HelloWorld);
debug();
expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining("Hello World")
);
});
test("when passed an html element, will print it's content as html instead", async () => {
const { debug, container } = await render(HelloWorld);
const exampleNode = container.ownerDocument!.createElement("span");
exampleNode.innerHTML = "Example Debug";
debug(exampleNode);
expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining("Example Debug")
);
});
<file_sep>import { render, screen, fireEvent, cleanup, act } from "..";
import Counter from "./fixtures/counter.marko";
import SplitCounter from "./fixtures/split-counter.marko";
import LegacyCounter from "./fixtures/legacy-counter";
import Clickable from "./fixtures/clickable.marko";
import HelloName from "./fixtures/hello-name.marko";
test("renders static content in a document with a browser context", async () => {
const { getByText, container } = await render(Counter);
expect(
expect(getByText("Value: 0")).toHaveProperty([
"ownerDocument",
"defaultView",
])
).not.toBeNull();
expect(container.firstElementChild).toHaveAttribute("class", "counter");
});
test("renders split component in the document", async () => {
const { getByText } = await render(SplitCounter, { message: "Count" });
expect(getByText(/0/)).toBeDefined();
expect(getByText(/Count/)).toBeDefined();
});
test("renders static content from a Marko 3 component", async () => {
const { getByText } = await render(LegacyCounter);
expect(
expect(getByText("Value: 0")).toHaveProperty([
"ownerDocument",
"defaultView",
])
).not.toBeNull();
});
test("global cleanup removes content from the document", async () => {
await render(Counter);
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(1);
cleanup();
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(0);
});
test("local cleanup removes single component from the document", async () => {
const { cleanup } = await render(Counter);
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(1);
cleanup();
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(0);
expect(() => cleanup()).toThrowErrorMatchingSnapshot();
});
test("instance is undefined on the server", async () => {
const result = await render(Clickable);
expect(result.instance).toBeUndefined();
});
test("fails when rerendering", async () => {
const { rerender } = await render(HelloName, { name: "Michael" });
await expect(
rerender({ name: "Dylan" })
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Components cannot re-render on the server side."`
);
});
test("fails when checking emitted events", async () => {
const { emitted } = await render(Clickable);
expect(() => emitted("button-click")).toThrowErrorMatchingInlineSnapshot(
`"Components should not emit events on the server side."`
);
});
test("fails when calling act", async () => {
const { getByText } = await render(Counter);
await expect(
act(() => getByText("Increment").click())
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cannot perform client side interaction tests on the server side. Please use @marko/testing-library in a browser environment."`
);
});
test("fails when emitting events", async () => {
const { getByText } = await render(Counter);
await expect(
fireEvent.click(getByText("Increment"))
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Cannot perform client side interaction tests on the server side. Please use @marko/testing-library in a browser environment."`
);
});
<file_sep>export = class {
increment() {
const node = (this as any).getEl("value");
node.textContent = +node.textContent + 1;
}
};
<file_sep>module.exports = {
projects: [
project("browser", {
preset: "@marko/jest/preset/browser",
}),
project("server", {
preset: "@marko/jest/preset/node",
}),
],
};
function project(displayName, config) {
return {
...config,
displayName,
coveragePathIgnorePatterns: ["/__tests__/"],
setupFilesAfterEnv: ["<rootDir>/jest-setup.js"],
testRegex: `/__tests__/([^.]+\\.)?${displayName}\\.ts$`,
transform: { "\\.ts$": ["esbuild-jest", { sourcemap: true }] },
};
}
<file_sep><div align="center">
<!-- Logo -->
<a href="https://www.joypixels.com/emoji/1f986">
<img
height="80"
width="80"
alt="duck"
src="https://raw.githubusercontent.com/marko-js/testing-library/master/assets/duck.png"
/>
</a>
<br/>
<h1>@marko/testing-library</h1>
<p>Simple and complete Marko testing utilities that encourage good testing practices.</p>
<!-- CI -->
<a href="https://travis-ci.org/marko-js/testing-library">
<img src="https://img.shields.io/travis/marko-js/testing-library.svg" alt="Build status"/>
</a>
<!-- Coverage -->
<a href="https://codecov.io/gh/marko-js/testing-library">
<img src="https://codecov.io/gh/marko-js/testing-library/branch/master/graph/badge.svg?token=LirxYQjltb" alt="Test Coverage"/>
</a>
<!-- Language -->
<a href="http://typescriptlang.org">
<img src="https://img.shields.io/badge/%3C%2F%3E-typescript-blue.svg" alt="TypeScript"/>
</a>
<!-- Format -->
<a href="https://github.com/prettier/prettier">
<img src="https://img.shields.io/badge/styled_with-prettier-ff69b4.svg" alt="Styled with prettier"/>
</a>
<!-- NPM Version -->
<a href="https://npmjs.org/package/@marko/testing-library">
<img src="https://img.shields.io/npm/v/@marko/testing-library.svg" alt="NPM Version"/>
</a>
<!-- Downloads -->
<a href="https://npmjs.org/package/@marko/testing-library">
<img src="https://img.shields.io/npm/dm/@marko/testing-library.svg" alt="Downloads"/>
</a>
</div>
## Table of Contents
- [**Read The Docs**](https://testing-library.com/docs/marko-testing-library/intro) | [Edit the docs](https://github.com/testing-library/testing-library-docs)
- [The problem](#the-problem)
- [This solution](#this-solution)
- [Installation](#installation)
- [API](#api)
- [Setup](#setup)
- [Guiding Principles](#guiding-principles)
- [Docs](#docs)
- [Code of Conduct](#code-of-conduct)
## The problem
You want to write maintainable tests for your Marko components. As a part of
this goal, you want your tests to avoid including implementation details of your
components and rather focus on making your tests give you the confidence for
which they are intended. As part of this, you want your testbase to be
maintainable in the long run so refactors of your components (changes to
implementation but not functionality) don't break your tests and slow you and
your team down.
## This solution
The `@marko/testing-library` is a very lightweight solution for testing Marko
components. It provides light utility functions on top of [`@testing-library/dom`](https://github.com/testing-library/dom-testing-library) in a way that encourages better testing practices. Its primary guiding principle is:
> [The more your tests resemble the way your software is used, the more confidence they can give you.](#guiding-principles)
## Installation
```console
npm install --save-dev @marko/testing-library
```
You may also be interested in installing `jest-dom` so you can use
[the custom jest matchers](https://github.com/testing-library/jest-dom#readme). Or if using another test runner like [mocha](https://mochajs.org) you could check out [`chai-dom`](https://www.chaijs.com/plugins/chai-dom/).
## API
Marko testing library exposes all of the same utilities for [querying the dom](https://testing-library.com/docs/dom-testing-library/api-queries), [firing events](https://testing-library.com/docs/dom-testing-library/api-events) and [testing asynchronous behavior](https://testing-library.com/docs/dom-testing-library/api-async) as [@testing-library/dom](https://github.com/testing-library/dom-testing-library). This module only exposes two additional APIs to make testing against your components easier.
### `render(template, input?, { container }?)`
This funcition renders your template asynchronously and provides you with [query helpers](https://testing-library.com/docs/dom-testing-library/api-queries) that are scoped to output DOM.
```javascript
import { render, screen } from "@marko/testing-library";
import HelloTemplate from "./src/__test__/fixtures/hello-name.marko";
test("contains the text", async () => {
const { rerender } = await render(HelloTemplate, {
name: "World",
});
// Will find the element within the rendered result from the template.
expect(screen.getByText("Hello World")).toBeInTheDocument();
// You can also rerender the component if needed.
await rerender({ name: "Marko" });
expect(screen.getByText("Hello Marko")).toBeInTheDocument();
});
```
The render result will also provide you with a `container` HTMLElement. This acts as an escape hatch and allows you to test your components going against the [guiding principles](#guiding-principles). With the `container` you can grab any element using `querySelector` or other means that mean nothing to your users.
```javascript
test("not a great test", async () => {
const { container } = await render(HelloTemplate, { name: "World" });
expect(container.querySelector("div")).toBeInTheDocument();
});
```
The problem with the above test is that your user does not care about or see that there is a `div` element, the user only see's the text content of the div. Maybe it turns out that a div wasn't the best element and we should switch to an h1? Now your tests are broken, even though there is likely no perceptable change to the user.
### `cleanup()`
With client side tests your components are rendered into a placeholder HTMLElement.
You can call `cleanup` at any time to destroy any attached components and remove them from the DOM.
```javascript
import { cleanup, screen } from "@marko/testing-library";
import HelloTemplate from "./src/__test__/fixtures/hello-name.marko";
test("contains the text", async () => {
await render(HelloTemplate, { name: "World" });
expect(screen.getByText("Hello World")).toBeInTheDocument();
cleanup();
expect(screen.queryByText("Hello Marko")).toBeNull();
});
```
By default if your testing framework exposes an `afterEach` hook (such as `jest` and `mocha`) then `cleanup` will be automatically invoked after each of your tests run.
If you'd like to disable the automatic cleanup behavior described above you can import `@marko/testing-library/dont-cleanup-after-each`.
```javascript
import "@marko/testing-library/dont-cleanup-after-each";
```
With mocha you can use `mocha -r @marko/testing-library/dont-cleanup-after-each` as a shorthand.
If you are using Jest, you can include `setupFilesAfterEnv: ["@marko/testing-library/dont-cleanup-after-each"]` in your Jest config to avoid doing this in each file.
## Setup
Marko testing library is not dependent on any test runner, however it is dependent on the test environment. These utilities work for testing both server side, and client side Marko templates and provide a slightly different implementation for each. This is done using a [browser shim](https://github.com/defunctzombie/package-browser-field-spec), just like in Marko.
The [browser shim](https://github.com/defunctzombie/package-browser-field-spec) is picked up by many tools, including all bundlers and some test runners.
Below is some example configurations to test both server and browser components with some popular test runners.
### [Jest](http://jestjs.io)
For Jest to understand Marko templates you must first [install the @marko/jest preset](https://github.com/marko-js/jest#installation). This allows your Marko templates to be imported into your tests.
To test components rendered in the client side, be sure to use the `@marko/jest/preset/browser` jest preset and you are good to go!
**jest.config.js**
```javascript
module.exports = {
preset: "@marko/jest/preset/browser",
};
```
If you'd like to test components using server side rendering you can instead use the `@marko/jest/preset/node` jest preset.
**jest.config.js**
```javascript
module.exports = {
preset: "@marko/jest/preset/node",
};
```
A Jest configuration can also have multiple [projects](https://jestjs.io/docs/en/configuration#projects-array-string-projectconfig) which we can use to create a combined configuration for server side tests, and browser side tests, like so:
**jest.config.js**
```javascript
module.exports = {
projects: [
{
displayName: "server",
preset: "@marko/jest/preset/node",
testRegex: "/__tests__/[^.]+\\.server\\.js$",
},
{
displayName: "browser",
preset: "@marko/jest/preset/browser",
testRegex: "/__tests__/[^.]+\\.browser\\.js$",
},
],
};
```
### [Mocha](https://mochajs.org)
Mocha also works great for testing Marko components. Mocha, however, has no understanding of [browser shims](https://github.com/defunctzombie/package-browser-field-spec) which means out of the box it can only work with server side Marko components.
To run server side Marko tests with `mocha` you can simply run the following command:
```console
mocha -r marko/node-require
```
This enables the [Marko require hook](https://markojs.com/docs/installing/#require-marko-views) and allows you to require server side Marko templates directly in your tests.
For client side testing of your components with Mocha often you will use a bundler to build your tests (this will properly resolve the browser shims mentioned above) and then you can load these tests in some kind of browser context.
## Guiding Principles
> [The more your tests resemble the way your software is used, the more
> confidence they can give you.][https://testing-library.com/docs/guiding-principles]
We try to only expose methods and utilities that encourage you to write tests
that closely resemble how your Marko components are used.
Utilities are included in this project based on the following guiding
principles:
1. If it relates to rendering components, then it should deal with DOM nodes
rather than component instances, and it should not encourage dealing with
component instances.
2. It should be generally useful for testing the application components in the
way the user would use it. We _are_ making some trade-offs here because
we're using a computer and often a simulated browser environment, but in
general, utilities should encourage tests that use the components the way
they're intended to be used.
3. Utility implementations and APIs should be simple and flexible.
At the end of the day, what we want is for this library to be pretty
light-weight, simple, and understandable.
## Docs
[**Read The Docs**](https://testing-library.com/docs/marko-testing-library/intro) |
[Edit the docs](https://github.com/testing-library/testing-library-docs)
## Code of Conduct
This project adheres to the [eBay Code of Conduct](./.github/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
<file_sep>import { render, fireEvent, screen, cleanup, act } from "../index-browser";
import Counter from "./fixtures/counter.marko";
import SplitCounter from "./fixtures/split-counter.marko";
import LegacyCounter from "./fixtures/legacy-counter";
import UpdateCounter from "./fixtures/update-counter.marko";
import HelloWorld from "./fixtures/hello-world.marko";
import HelloName from "./fixtures/hello-name.marko";
import Clickable from "./fixtures/clickable.marko";
import ScopedId from "./fixtures/scoped-id.marko";
test("renders interactive content in the document", async () => {
const { getByText } = await render(Counter);
expect(getByText(/Value: 0/)).toBeInTheDocument();
expect(screen.getByText(/Value: 0/)).toBeInTheDocument();
await fireEvent.click(getByText("Increment"));
expect(getByText("Value: 1")).toBeInTheDocument();
});
test("renders interactive split component in the document", async () => {
const { getByText } = await render(SplitCounter, { message: "Count" });
expect(getByText(/0/)).toBeInTheDocument();
expect(getByText(/Count/)).toBeInTheDocument();
expect(screen.getByText(/0/)).toBeInTheDocument();
await fireEvent.click(getByText("Increment"));
expect(getByText("1")).toBeInTheDocument();
});
test("renders interactive content in the document with Marko 3", async () => {
const { getByText } = await render(LegacyCounter);
expect(getByText(/Value: 0/)).toBeInTheDocument();
await fireEvent.click(getByText("Increment"));
expect(getByText("Value: 1")).toBeInTheDocument();
});
test("can be rerendered with new input", async () => {
const { getByText, rerender } = await render(HelloName, { name: "Michael" });
expect(getByText(/Hello \w+/)).toHaveProperty(
"textContent",
expect.stringContaining("Michael")
);
await rerender({ name: "Dylan" });
expect(getByText(/Hello \w+/)).toHaveProperty(
"textContent",
expect.stringContaining("Dylan")
);
});
test("can be rerendered with no input (forced update)", async () => {
const { getByText, rerender } = await render(UpdateCounter);
expect(getByText(/Render Count: \d+/)).toHaveProperty(
"textContent",
expect.stringContaining("Render Count: 1")
);
await rerender();
expect(getByText(/Render Count: \d+/)).toHaveProperty(
"textContent",
expect.stringContaining("Render Count: 2")
);
});
test("records user events", async () => {
const { getByText, emitted } = await render(Clickable);
const button = getByText("Click");
await fireEvent.click(button);
await fireEvent.click(button);
expect(emitted("unknown-event")).toHaveProperty("length", 0);
expect(emitted("button-click")).toMatchSnapshot();
expect(emitted().map(({ type }) => type)).toMatchSnapshot();
await fireEvent.click(button);
expect(emitted("button-click")).toMatchSnapshot();
expect(emitted().map(({ type }) => type)).toMatchSnapshot();
});
test("errors when trying to record internal events", async () => {
const { emitted } = await render(Clickable);
expect(() => emitted("mount" as string)).toThrowErrorMatchingSnapshot();
});
test("can access component instance in browser tests", async () => {
const { instance } = await render(Clickable, { a: 1 });
expect(instance.input).toHaveProperty("a", 1);
});
test("global cleanup removes content from the document", async () => {
const component = await render(Counter);
const node = component.getByText(/Value: 0/);
expect(node).toBeInTheDocument();
expect(screen.getByText(/Value: 0/)).toEqual(node);
cleanup();
expect(node).not.toBeInTheDocument();
});
test("local cleanup removes single component from the document", async () => {
const componentA = await render(Counter);
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(1);
const componentB = await render(Counter);
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(2);
componentA.cleanup();
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(1);
componentB.cleanup();
expect(screen.queryAllByText(/Value: 0/)).toHaveLength(0);
});
test("local cleanup fails if component already cleaned up", async () => {
const componentA = await render(Counter);
const componentB = await render(Counter);
expect(screen.getAllByText(/Value: 0/)).toHaveLength(2);
componentA.cleanup();
expect(() => componentA.cleanup()).toThrowErrorMatchingSnapshot();
cleanup();
expect(() => componentB.cleanup()).toThrowErrorMatchingSnapshot();
});
test("can render into a different container", async () => {
const container = document.createElement("main");
const { getByText } = await render(HelloWorld, null, { container });
expect(getByText("Hello World")).toHaveProperty("parentNode", container);
});
test("act waits for pending updates", async () => {
const { getByText } = await render(Counter);
expect(getByText(/Value: 0/)).toBeInTheDocument();
await act(() => getByText("Increment").click());
expect(getByText("Value: 1")).toBeInTheDocument();
});
test("fireEvent waits for pending updates", async () => {
const { getByText } = await render(Counter);
expect(getByText(/Value: 0/)).toBeInTheDocument();
await fireEvent(
getByText("Increment"),
new MouseEvent("click", {
bubbles: true,
cancelable: true,
})
);
expect(getByText("Value: 1")).toBeInTheDocument();
});
test("it renders a stable scoped id", async () => {
const r1 = await render(ScopedId);
expect(r1.getByRole("main")).toHaveProperty("id", "c0-test");
cleanup();
const r2 = await render(ScopedId);
expect(r2.getByRole("main")).toHaveProperty("id", "c0-test");
});
<file_sep>globalThis.___disable_marko_test_auto_cleanup___ = true;
<file_sep>import type {
AsyncReturnValue,
RenderOptions,
EventRecord,
InternalEventNames,
} from "./shared";
import { JSDOM } from "jsdom";
import {
within,
logDOM,
BoundFunctions,
queries as Queries,
screen as testingLibraryScreen,
} from "@testing-library/dom";
export { FireFunction, FireObject, fireEvent, act } from "./shared";
export type RenderResult = AsyncReturnValue<typeof render>;
export const screen: typeof testingLibraryScreen = {} as any;
let activeContainer: DocumentFragment | undefined;
export async function render<T extends Marko.Template>(
template: T | { default: T },
input: Marko.TemplateInput<Marko.Input<T>> = {} as any,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
options?: RenderOptions
): Promise<
BoundFunctions<typeof Queries> & {
container: HTMLElement | DocumentFragment;
instance: any;
debug: (typeof testingLibraryScreen)["debug"];
emitted<N extends string = "*">(
type?: N extends InternalEventNames ? never : N
): NonNullable<EventRecord[N]>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
rerender(newInput?: typeof input): Promise<void>;
cleanup(): void;
}
> {
if (template && "default" in template) {
template = template.default;
}
// Doesn't use promise API so that we can support Marko v3
const renderMethod = (template as any).renderToString
? "renderToString"
: "render";
const html = String(
await new Promise((resolve, reject) =>
(template as any)[renderMethod]!(input, (err: any, result: any) =>
err ? reject(err) : resolve(result)
)
)
);
const {
window: { document },
} = new JSDOM();
const container = (activeContainer = document.importNode(
JSDOM.fragment(html),
true
));
(container as any).outerHTML = html; // Fixes prettyDOM for container
const queries = {
debug: function debug(element, maxLength, options) {
if (!element) {
debug(Array.from(container.children), maxLength, options);
} else if (Array.isArray(element)) {
for (const child of element) {
logDOM(child, maxLength, options);
}
} else {
logDOM(element, maxLength, options);
}
},
...within(container as any as HTMLElement),
} as typeof testingLibraryScreen;
// For SSR tests screen is always references the last rendered component.
Object.assign(screen, queries);
return {
container,
instance: undefined as any,
emitted<N extends string = "*">(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type?: N extends InternalEventNames ? never : N
): NonNullable<EventRecord[N]> {
throw new Error("Components should not emit events on the server side.");
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
rerender(newInput?: typeof input): Promise<void> {
return Promise.reject(
new Error("Components cannot re-render on the server side.")
);
},
cleanup() {
if (activeContainer !== container) {
throw new Error(
"Component was already destroyed before cleanup called."
);
}
cleanupComponent();
},
...queries,
} as const;
}
export function cleanup() {
cleanupComponent();
}
function cleanupComponent() {
if (activeContainer) {
(activeContainer as any).outerHTML = "";
while (activeContainer.firstChild) {
activeContainer.removeChild(activeContainer.firstChild);
}
activeContainer = undefined;
}
}
export * from "@testing-library/dom";
if (
!(globalThis as any).___disable_marko_test_auto_cleanup___ &&
typeof afterEach === "function"
) {
afterEach(cleanup);
}
<file_sep>declare module "*.marko" {
let x: any;
export default x;
}
declare namespace Marko {
// TODO: this project should use Marko 5 for the types on the cli
// However this is not currently possible since it also needs to test
// against the v3 compat layer in Marko 4.
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Template {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type TemplateInput<T> = any;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type Input<T> = any;
}
<file_sep>import type {
RenderOptions,
EventRecord,
InternalEventNames,
AsyncReturnValue,
} from "./shared";
import { within, logDOM, PrettyDOMOptions } from "@testing-library/dom";
import { INTERNAL_EVENTS } from "./shared";
interface MountedComponent {
container: Element | DocumentFragment;
instance: any;
isDefaultContainer: boolean;
}
const mountedComponents = new Set<MountedComponent>();
export { FireFunction, FireObject, fireEvent, act } from "./shared";
export type RenderResult = AsyncReturnValue<typeof render>;
export async function render<T extends Marko.Template>(
template: T | { default: T },
input: Marko.TemplateInput<Marko.Input<T>> = {} as any,
options: RenderOptions = {}
) {
if (template && "default" in template) {
template = template.default;
}
let isDefaultContainer = false;
const {
container = (isDefaultContainer = true) &&
document.body.appendChild(document.createElement("div")),
} = options;
// Doesn't use promise API so that we can support Marko v3
const renderResult = (await new Promise((resolve, reject) =>
(template as any).render(input, (err: any, result: any) =>
err ? reject(err) : resolve(result)
)
)) as any;
const isV4 = renderResult.getComponent;
const instance = renderResult
.appendTo(container)
[isV4 ? "getComponent" : "getWidget"]();
const eventRecord: EventRecord = {};
const mountedComponent: MountedComponent = {
container,
instance,
isDefaultContainer,
};
mountedComponents.add(mountedComponent);
const _emit = instance.emit;
instance.emit = (...args: [string, ...unknown[]]) => {
const [type] = args;
if (!INTERNAL_EVENTS.includes(type as InternalEventNames)) {
const userArgs = args.slice(1);
(eventRecord["*"] || (eventRecord["*"] = [])).push({
type,
args: userArgs,
});
(eventRecord[type] || (eventRecord[type] = [])).push(userArgs);
}
return _emit.apply(instance, args);
};
return {
container,
instance,
emitted<N extends string = "*">(
type?: N extends InternalEventNames ? never : N
) {
if (INTERNAL_EVENTS.includes(type as InternalEventNames)) {
throw new Error(
"The emitted helper cannot be used to listen to internal events."
);
}
const events = eventRecord[type || "*"];
const copy = events ? events.slice() : [];
if (events) {
events.length = 0;
}
return copy as NonNullable<EventRecord[N]>;
},
rerender(newInput?: typeof input): Promise<void> {
return new Promise((resolve) => {
instance.once(isV4 ? "update" : "render", () => resolve());
if (newInput) {
if (instance.setProps) {
instance.setProps(newInput);
} else {
instance.input = newInput;
}
} else {
if (instance.forceUpdate) {
instance.forceUpdate();
} else {
instance.setStateDirty("__forceUpdate__");
}
}
});
},
cleanup() {
if (!mountedComponents.has(mountedComponent)) {
throw new Error(
"Component was already destroyed before cleanup called."
);
}
cleanupComponent(mountedComponent);
},
debug: function debug(
element?: Element | HTMLDocument | (Element | HTMLDocument)[] | undefined,
maxLength?: number,
options?: PrettyDOMOptions
) {
if (!element) {
debug(Array.from(container.children), maxLength, options);
} else if (Array.isArray(element)) {
for (const child of element) {
logDOM(child, maxLength, options);
}
} else {
logDOM(element, maxLength, options);
}
},
...within(container as any as HTMLElement),
} as const;
}
export function cleanup() {
mountedComponents.forEach(cleanupComponent);
// reset internal Marko component id count
const counter = (window as any).$MUID;
if (counter) {
counter.i = 0;
}
}
function cleanupComponent(mountedComponent: MountedComponent) {
const { instance, container, isDefaultContainer } = mountedComponent;
instance.destroy();
if (isDefaultContainer && container.parentNode === document.body) {
document.body.removeChild(container);
}
mountedComponents.delete(mountedComponent);
}
export * from "@testing-library/dom";
if (
!(globalThis as any).___disable_marko_test_auto_cleanup___ &&
typeof afterEach === "function"
) {
afterEach(cleanup);
}
|
9ce81811bd0cbfe19c320da90609c8855fadc244
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 12
|
Markdown
|
marko-js/testing-library
|
7d5c3127ed7c6e3c22518f4c0c044cf16ccdadcf
|
d9a04f908d3a40fcb40fa32d6ded2119b0e051b2
|
refs/heads/master
|
<repo_name>angolubev/AI_Lab_2<file_sep>/global_co2.py
import pandas
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
# считываем данные
data = pandas.read_csv('global_co2.csv')
x = data.iloc[:, 1:4]
y = data.iloc[:, 4]
# делим датасет на данные для обучения и данные для проверки
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42, shuffle = True)
# точки необходимо отсортировать для корректного отображения графика
y_test = y_test.sort_index()
x_test = x_test.sort_index()
# вычисляем линейную регрессию
regr = linear_model.LinearRegression()
regr.fit(x_train, y_train)
y_pred = regr.predict(x_test)
# строим график
plt.scatter(y_test.index, y_test, color='red', alpha = 0.5)
plt.plot(y_test.index, y_pred, color='blue', linewidth=2)
plt.xlabel("Year")
plt.ylabel('Solid Fuel')
plt.show()
<file_sep>/challenge_dataset.py
import pandas
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
# считываем данные из файла
data = pandas.read_csv('challenge_dataset.txt', names = ['x', 'y'])
x = data['x']
y = data['y']
# строим точки
plt.scatter(x, y, color='red', alpha = 0.5)
# делим датасет на данные для обучения и данные для проверки
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=50)
# вычисляем линейную регрессию
regr = linear_model.LinearRegression()
regr.fit(x_train.values.reshape(-1, 1), y_train)
y_pred = regr.predict(x_test.values.reshape(-1, 1))
# строим график прямой
plt.plot(x_test, y_pred, color='blue', linewidth=2)
plt.xlabel("x")
plt.ylabel("y")
plt.show()<file_sep>/Wiki_GOOGL.py
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
import quandl
# считываем данные из файла
data = quandl.get('Wiki/GOOGL')
x = data[['Open', 'High', 'Low']]
y = data.Close
# делим датасет на данные для обучения и данные для проверки
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42, shuffle = True)
# точки необходимо отсортировать для корректного отображения графика
y_test = y_test.sort_index()
x_test = x_test.sort_index()
# вычисляем линейную регрессию
regr = linear_model.LinearRegression()
regr.fit(x_train, y_train)
y_pred = regr.predict(x_test)
# строим график
plt.scatter(y_test.index, y_test, color='red', alpha = 0.5)
plt.plot(y_test.index, y_pred, color='blue', linewidth=1)
plt.xlabel("Date")
plt.ylabel("Close")
plt.show()
<file_sep>/README.md
# Лабораторная работа №2 по курсу "Искусственный Интеллект"
## Постановка задачи
Построить модель линейной регрессии для трех выборок: торги акций компании, его можно получить с помощью quandl (quandl.get('Wiki/GOOGL')),
два оставшихся датасета приложены в zip архиве. Визуализировать все данные и полученную на выходе линию.
## Результаты
### challenge_dataset

### global_co2

### Wiki_GOOGL

|
3de8e8feb216bbbef5c15be3f56c1286b2c68ddb
|
[
"Markdown",
"Python"
] | 4
|
Python
|
angolubev/AI_Lab_2
|
1b26db20f6dc5925833f37215fd348dc423c5e33
|
d2376414a2e68d036852ed61316a6dc66fd193af
|
refs/heads/master
|
<repo_name>muhrizqullah/FinalProjectMBD<file_sep>/TIXID_App/database/seeders/MetodePembayaranSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Pelanggan;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class MetodePembayaranSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
$pel_ids = Pelanggan::all()->pluck('pel_id')->toArray();
for($i = 1; $i <= 15000; $i++)
{
$kategoriData[] = [
'pel_id' => $pel_ids[array_rand($pel_ids)],
'mtd_jenis' => $faker->creditCardType(),
'mtd_bank' => $faker->company(),
'mtd_nomor_kartu' => $faker->creditCardNumber(),
'mtd_expired' => $faker->creditCardExpirationDateString(),
'mtd_cvv' => $faker->numberBetween(101, 999)
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($kategoriData, 10000);
foreach($chunks as $chunk) {
DB::table('metode_pembayaran')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/FilmSeeder.php
<?php
namespace Database\Seeders;
use App\Models\KategoriFilm;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class FilmSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
$category_ids = KategoriFilm::all()->pluck('cat_id')->toArray();
for($i = 1; $i <= 200; $i++)
{
$filmData[] = [
'cat_id' => $category_ids[array_rand($category_ids)],
'mov_judul' => $faker->word(),
'mov_durasi' => $faker->numberBetween(60,180)
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($filmData, 10000);
foreach($chunks as $chunk) {
DB::table('film')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/PelangganSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class PelangganSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
for($i = 1; $i <= 10000; $i++)
{
$pelangganData[] = [
'pel_nama' => $faker->name(),
'pel_email' => $faker->email(),
'pel_no_telepon' => $faker->phoneNumber()
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($pelangganData, 10000);
foreach($chunks as $chunk) {
DB::table('pelanggan')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/JadwalSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Film;
use App\Models\Studio;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class JadwalSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
$film_ids = Film::all()->pluck('mov_id')->toArray();
$studio_ids = Studio::all()->pluck('std_id')->toArray();
for($i = 1; $i <= 10000; $i++)
{
$jadwalData[] = [
'mov_id' => $film_ids[array_rand($film_ids)],
'std_id' => $studio_ids[array_rand($studio_ids)],
'sch_waktu' => $faker->dateTimeThisYear(),
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($jadwalData, 10000);
foreach($chunks as $chunk) {
DB::table('jadwal')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/app/Models/KategoriFilm.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class KategoriFilm extends Model
{
use HasFactory;
protected $table = "kategori_film";
protected $fillable = ['cat_nama'];
protected $primaryKey = "cat_id";
public function films()
{
return $this->hasMany(Film::class, 'cat_id', 'cat_id');
}
}
<file_sep>/TIXID_App/database/seeders/TiketSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Bioskop;
use App\Models\Film;
use App\Models\Jadwal;
use App\Models\Transaksi;
use App\Models\Kursi;
use App\Models\Studio;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class TiketSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
ini_set('memory_limit', '-1');
$faker = Faker::create();
$trx_id = Transaksi::all()->pluck('trx_id')->toArray();
$chr_id = Kursi::all()->pluck('chr_id')->toArray();
for($i = 1; $i <= 1000; $i++)
{
$tiketData[] = [
'trx_id' => $trx_id[array_rand($trx_id)],
'chr_id' => $chr_id[array_rand($chr_id)],
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($tiketData, 10000);
foreach($chunks as $chunk) {
DB::table('tiket')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
BioskopSeeder::class,
StudioSeeder::class,
KategoriFilmSeeder::class,
FilmSeeder::class,
JadwalSeeder::class,
PelangganSeeder::class,
MetodePembayaranSeeder::class,
TransaksiSeeder::class,
KursiSeeder::class,
VoucherSeeder::class,
DetailVoucherSeeder::class,
TiketSeeder::class,
]);
}
}
<file_sep>/TIXID_App/database/seeders/DetailVoucherSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Voucher;
use App\Models\Transaksi;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DetailVoucherSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// ini_set('memory_limit', '-1');
$faker = Faker::create();
$Voucher_ids = Voucher::all()->pluck('voc_id')->toArray();
$Transaksi_ids = Transaksi::all()->pluck('trx_id')->toArray();
for($i = 1; $i <= 1000; $i++)
{
$detailVoucherData[] = [
'trx_id' => $Transaksi_ids[array_rand($Transaksi_ids)],
'voc_id' => $Voucher_ids[array_rand($Voucher_ids)]
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($detailVoucherData, 10000);
foreach($chunks as $chunk) {
DB::table('detail_voucher')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/app/Models/Tiket.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tiket extends Model
{
use HasFactory;
protected $table = "tiket";
protected $fillable = ['trx_id', 'chr_id'];
protected $primaryKey = "tik_id";
public function transaksi()
{
return $this->belongsTo(Transaksi::class, 'trx_id', 'trx_id');
}
public function Kursi()
{
return $this->belongsTo(Kursi::class, "tik_id", "tik_id");
}
}
<file_sep>/TIXID_App/database/seeders/TransaksiSeeder.php
<?php
namespace Database\Seeders;
use App\Models\MetodePembayaran;
use App\Models\Pelanggan;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class TransaksiSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
$pel_ids = Pelanggan::all()->pluck('pel_id')->toArray();
$mtd_ids = MetodePembayaran::all()->pluck('mtd_id')->toArray();
for($i = 1; $i <= 30000; $i++)
{
$kategoriData[] = [
'pel_id' => $pel_ids[array_rand($pel_ids)],
'mtd_id' => $mtd_ids[array_rand($mtd_ids)],
'trx_total_tiket' => $faker->numberBetween(1,20),
'trx_total_harga' => $faker->numberBetween(35000, 1000000)
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($kategoriData, 10000);
foreach($chunks as $chunk) {
DB::table('transaksi')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/app/Models/Studio.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Studio extends Model
{
use HasFactory;
protected $table = "studio";
protected $fillable = ['cin_id', 'std_kapasitas'];
protected $primaryKey = "std_id";
public function bioskop()
{
return $this->belongsTo(Bioskop::class, 'cin_id', 'cin_id');
}
}
<file_sep>/TIXID_App/app/Models/Bioskop.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Bioskop extends Model
{
use HasFactory;
protected $table = "bioskop";
protected $fillable = ['cin_nama', 'cin_lokasi'];
protected $primaryKey = "cin_id";
public function studios()
{
return $this->hasMany(Studio::class, 'cin_id', 'cin_id');
}
}
<file_sep>/README.md
# FinalProjectMBD
Repositori Final Project Manajemen Basis Data Kelas D Teknik Informatika ITS
1. buat database baru
2. atur direktori ke working direktori TIXID_App
3. buka terminal, composer install
4. cp .env.example .env
5. buka app, file .env, sesuaikan database
- DB_CONNECTION=pgsql
- DB_HOST=127.0.0.1
- DB_PORT=5432
- DB_DATABASE={nama database}
- DB_USERNAME=postgres
- DB_PASSWORD={<PASSWORD>}
7. php artisan db:seed
<file_sep>/DDL_Table.sql
CREATE SEQUENCE Bioskop_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Film_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Jadwal_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Kategori_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Kursi_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Metode_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Pelanggan_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Studio_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Tiket_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Transaksi_Seq START 0 MINVALUE 0;
CREATE SEQUENCE Voucher_Seq START 0 MINVALUE 0;
/*==============================================================*/
/* Table: BIOSKOP */
/*==============================================================*/
create table BIOSKOP (
CIN_ID VARCHAR(50) PRIMARY KEY,
CIN_NAMA VARCHAR(50),
CIN_LOKASI VARCHAR(50) NOT NULL,
CIN_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
CIN_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: FILM */
/*==============================================================*/
create table FILM (
MOV_ID VARCHAR(50) PRIMARY KEY,
CAT_ID VARCHAR(50) NOT NULL,
MOV_JUDUL VARCHAR(50) NOT NULL,
MOV_DURASI INTEGER NOT NULL,
MOV_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
MOV_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: JADWAL */
/*==============================================================*/
create table JADWAL (
SCH_ID VARCHAR(50) PRIMARY KEY,
MOV_ID VARCHAR(50) NOT NULL,
STD_ID VARCHAR(50) NOT NULL,
SCH_WAKTU TIMESTAMPTZ NOT NULL,
SCH_HARGA INTEGER,
SCH_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
SCH_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: KATEGORI_FILM */
/*==============================================================*/
create table KATEGORI_FILM (
CAT_ID VARCHAR(50) PRIMARY KEY,
CAT_NAMA VARCHAR(50) NOT NULL,
CAT_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
CAT_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: TIKET */
/*==============================================================*/
create table TIKET (
TIK_ID VARCHAR(50) PRIMARY KEY,
TRX_ID VARCHAR(50) NOT NULL,
CHR_ID VARCHAR(50) NOT NULL,
TIK_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
TIK_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: KURSI */
/*==============================================================*/
create table KURSI (
CHR_ID VARCHAR(50) PRIMARY KEY,
CHR_KODE VARCHAR(20) NOT NULL,
SCH_ID VARCHAR(50) NOT NULL,
CHR_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
CHR_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: METODE_PEMBAYARAN */
/*==============================================================*/
create table METODE_PEMBAYARAN (
MTD_ID VARCHAR(50) PRIMARY KEY,
PEL_ID VARCHAR(50) NOT NULL,
MTD_JENIS VARCHAR(50) NOT NULL,
MTD_BANK VARCHAR(50) NOT NULL,
MTD_NOMOR_KARTU VARCHAR(16) NOT NULL,
MTD_EXPIRED VARCHAR(5) NOT NULL,
MTD_CVV VARCHAR(3) NOT NULL,
MTD_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
MTD_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: PELANGGAN */
/*==============================================================*/
create table PELANGGAN (
PEL_ID VARCHAR(50) PRIMARY KEY,
PEL_NAMA VARCHAR(50) NOT NULL,
PEL_EMAIL VARCHAR(50) NOT NULL,
PEL_NO_TELEPON VARCHAR(50) NOT NULL,
PEL_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
PEL_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: DetailVoucher */
/*==============================================================*/
create table DETAIL_VOUCHER (
TRX_ID VARCHAR(50),
VOC_ID VARCHAR(50),
DV_Created_At TIMESTAMPTZ DEFAULT NOW(),
DV_Updated_At TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: STUDIO */
/*==============================================================*/
create table STUDIO (
STD_ID VARCHAR(50) PRIMARY KEY,
CIN_ID VARCHAR(50) NOT NULL,
STD_KAPASITAS INTEGER NOT NULL,
STD_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
STD_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: TRANSAKSI */
/*==============================================================*/
create table TRANSAKSI (
TRX_ID VARCHAR(50) PRIMARY KEY,
PEL_ID VARCHAR(50) NOT NULL,
MTD_ID VARCHAR(50) NOT NULL,
TRX_TOTAL_HARGA INTEGER,
TRX_TOTAL_TIKET INTEGER,
TRX_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
TRX_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
/*==============================================================*/
/* Table: VOUCHER */
/*==============================================================*/
create table VOUCHER (
VOC_ID VARCHAR(50) PRIMARY KEY,
VOC_KODE_VOUCHER VARCHAR(50) NOT NULL,
VOC_NOMINAL INTEGER NOT NULL,
VOC_CREATED_AT TIMESTAMPTZ DEFAULT NOW(),
VOC_UPDATED_AT TIMESTAMPTZ DEFAULT NOW()
);
alter table FILM
add constraint FK_FILM_RELATIONS_KATEGORI foreign key (CAT_ID)
references KATEGORI_FILM (CAT_ID);
alter table JADWAL
add constraint FK_JADWAL_RELATIONS_FILM foreign key (MOV_ID)
references FILM (MOV_ID);
alter table JADWAL
add constraint FK_JADWAL_RELATIONS_STUDIO foreign key (STD_ID)
references STUDIO (STD_ID);
alter table KURSI
add constraint FK_KURSI_RELATIONS_JADWAL foreign key (SCH_ID)
references JADWAL (SCH_ID);
alter table METODE_PEMBAYARAN
add constraint FK_METODE_P_RELATIONS_PELANGGA foreign key (PEL_ID)
references PELANGGAN (PEL_ID);
alter table DETAIL_VOUCHER
add constraint FK_RELATION_RELATIONS_TRANSAKS foreign key (TRX_ID)
references TRANSAKSI (TRX_ID);
alter table DETAIL_VOUCHER
add constraint FK_RELATION_RELATIONS_VOUCHER foreign key (VOC_ID)
references VOUCHER (VOC_ID);
alter table STUDIO
add constraint FK_STUDIO_RELATIONS_BIOSKOP foreign key (CIN_ID)
references BIOSKOP (CIN_ID);
alter table TIKET
add constraint FK_TIKET_RELATIONS_TRANSAKS foreign key (TRX_ID)
references TRANSAKSI (TRX_ID);
alter table TIKET
add constraint FK_TIKET_RELATIONS_KURSI foreign key (CHR_ID)
references KURSI (CHR_ID);
alter table TRANSAKSI
add constraint FK_TRANSAKS_RELATIONS_METODE_P foreign key (MTD_ID)
references METODE_PEMBAYARAN (MTD_ID);
alter table TRANSAKSI
add constraint FK_TRANSAKS_RELATIONS_PELANGGA foreign key (PEL_ID)
references PELANGGAN (PEL_ID);
<file_sep>/TIXID_App/app/Models/Jadwal.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Jadwal extends Model
{
use HasFactory;
protected $table = "jadwal";
protected $fillable = ['mov_id', 'std_id', 'sch_waktu'];
protected $primaryKey = "sch_id";
public function film()
{
return $this->belongsTo(Film::class, 'mov_id', 'mov_id');
}
public function kursis()
{
return $this->hasMany(Kursi::class, "chr_id", "chr_id");
}
public function studio()
{
return $this->belongsTo(Studio::class, "std_id", "std_id");
}
}
<file_sep>/TIXID_App/database/seeders/BioskopSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class BioskopSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
for($i = 1; $i <= 100; $i++)
{
$bioskopData[] = [
'cin_nama' => $faker->company(),
'cin_lokasi' => $faker->streetAddress()
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($bioskopData, 10000);
foreach($chunks as $chunk) {
DB::table('bioskop')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/DML_ComplexQueries.sql
-- A Tiket yang dibeli
SELECT PELANGGAN.PEL_NAMA AS "Pelanggan", TRANSAKSI.ID AS "Nomor Transaksi", TIKET.ID AS "Nomor Tiket"
FROM PELANGGAN, TRANSAKSI, TIKET
WHERE PELANGGAN.ID = TRANSAKSI.PEL_ID AND TRANSAKSI.ID = TIKET.TRX_ID
AND PELANGGAN.ID = '1';
-- C Jadwal yang tersedia dan filmnya
SELECT JADWAL.SCH_WAKTU as "Waktu", FILM.MOV_JUDUL as "Judul"
FROM JADWAL JOIN FILM ON JADWAL.MOV_ID=FILM.ID
WHERE SCH_WAKTU > CURRENT_TIMESTAMP;
-- Metode Pembayaran yg digunakan
SELECT PELANGGAN.PEL_NAMA AS "Pelanggan", METODE_PEMBAYARAN.MTD_JENIS AS "Jenis Kartu", METODE_PEMBAYARAN.MTD_BANK AS "Bank", METODE_PEMBAYARAN.MTD_NOMOR_KARTU AS "Nomor Kartu"
FROM PELANGGAN JOIN METODE_PEMBAYARAN ON PELANGGAN.ID = METODE_PEMBAYARAN.ID
WHERE PELANGGAN.ID = '100';
<file_sep>/TIXID_App/app/Models/Transaksi.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Transaksi extends Model
{
use HasFactory;
protected $table = "transaksi";
protected $fillable = ['pel_id', 'mtd_id', 'trx_total_harga', 'trx_total_tiket'];
protected $primaryKey = "trx_id";
public function pelanggan()
{
return $this->belongsTo(Pelanggan::class, 'pel_id', 'pel_id');
}
public function tikets()
{
return $this->hasMany(Tiket::class, 'trx_id', 'trx_id');
}
public function metodepembayaran()
{
return $this->belongsTo(MetodePembayaran::class, "mtd_id", "mtd_id");
}
public function vouchers()
{
return $this->belongsToMany(Voucher::class, "detail_voucher");
}
}
<file_sep>/TIXID_App/app/Models/Pelanggan.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pelanggan extends Model
{
use HasFactory;
protected $table = "pelanggan";
protected $fillable = ['pel_nama', 'pel_email', 'pel_no_telepon'];
protected $primaryKey = "pel_id";
public function transaksis()
{
return $this->hasMany(Transaksi::class, 'pel_id', 'pel_id');
}
public function metodepembayarans(){
return $this->hasMany(MetodePembayaran::class, 'pel_id', 'pel_id');
}
}
<file_sep>/DML_Insert_Test.sql
INSERT INTO BIOSKOP(CIN_NAMA, CIN_LOKASI) VALUES ('XXI', 'KARAWACI');
SELECT * FROM BIOSKOP;
INSERT INTO STUDIO(CIN_ID, STD_KAPASITAS) VALUES ('0', 3);
SELECT * FROM STUDIO;
INSERT INTO KATEGORI_FILM(CAT_NAMA) VALUES ('SCIENCE FICTION');
SELECT * FROM KATEGORI_FILM;
INSERT INTO FILM(CAT_ID, MOV_JUDUL, MOV_DURASI) VALUES ('0', 'BIRD BOX', 120);
SELECT * FROM FILM;
INSERT INTO JADWAL(MOV_ID, STD_ID, SCH_WAKTU) VALUES ('0', '0', '2021-07-05');
SELECT * FROM JADWAL;
INSERT INTO PELANGGAN(PEL_NAMA, PEL_EMAIL, PEL_NO_TELEPON) VALUES('AKBAR', '<EMAIL>', '0811111111');
SELECT * FROM PELANGGAN;
INSERT INTO METODE_PEMBAYARAN(PEL_ID, MTD_JENIS, MTD_BANK, MTD_NOMOR_KARTU, MTD_EXPIRED, MTD_CVV)
VALUES('0', 'DEBIT', 'BNI', '1234567891234567', '0424', '392');
SELECT * FROM METODE_PEMBAYARAN;
INSERT INTO TRANSAKSI(PEL_ID, MTD_ID) VALUES('0', '0');
SELECT * FROM TRANSAKSI;
INSERT INTO KURSI(SCH_ID, CHR_KODE) VALUES('0', 'A01');
INSERT INTO KURSI(SCH_ID, CHR_KODE) VALUES('0', 'A02');
INSERT INTO KURSI(SCH_ID, CHR_KODE) VALUES('0', 'A03');
SELECT * FROM KURSI;
--INSERT INTO KURSI(SCH_ID, CHR_KODE) VALUES('0', 'A04');
--INSERT INTO KURSI(SCH_ID, CHR_KODE) VALUES('0', 'A05');
INSERT INTO VOUCHER(VOC_KODE_VOUCHER, VOC_NOMINAL) VALUES ('DISC10', 10000);
INSERT INTO VOUCHER(VOC_KODE_VOUCHER, VOC_NOMINAL) VALUES ('DISC5', 5000);
SELECT * FROM VOUCHER;
INSERT INTO Detail_Voucher(TRX_ID, VOC_ID) VALUES('0','0');
INSERT INTO Detail_Voucher(TRX_ID, VOC_ID) VALUES('0','1');
SELECT * FROM Detail_Voucher;
INSERT INTO TIKET(TRX_ID, CHR_ID)
VALUES ('0', '0');
INSERT INTO TIKET(TRX_ID, CHR_ID)
VALUES ('0', '1');
INSERT INTO TIKET(TRX_ID, CHR_ID)
VALUES ('0', '2');
SELECT * FROM TIKET;
--test
SELECT COUNT(TIK_ID) FROM TIKET WHERE TIKET.TRX_ID = 'TRX000001';
SELECT SUM(SCH_HARGA) FROM TIKET JOIN JADWAL ON TIKET.SCH_ID = JADWAL.SCH_ID
WHERE TIKET.TRX_ID = 'TRX000001';
SELECT SUM(VOC_NOMINAL)
FROM VOUCHER, TRANSAKSI, DetailVoucher
WHERE DetailVoucher.TRX_ID = TRANSAKSI.TRX_ID AND DetailVoucher.VOC_ID = VOUCHER.VOC_ID
AND TRANSAKSI.TRX_ID='TRX000001';
SELECT SUM(SCH_HARGA)
FROM TIKET, KURSI, JADWAL
WHERE TIKET.CHR_ID = KURSI.CHR_ID AND KURSI.SCH_ID = JADWAL.SCH_ID
AND TIKET.TRX_ID = '0'
SELECT ((SELECT SUM(SCH_HARGA)
FROM TIKET, KURSI, JADWAL
WHERE TIKET.CHR_ID = KURSI.CHR_ID AND KURSI.SCH_ID = JADWAL.SCH_ID
AND TIKET.TRX_ID = '0') - (SELECT SUM(VOC_NOMINAL)
FROM VOUCHER, TRANSAKSI, DETAIL_VOUCHER
WHERE DETAIL_VOUCHER.TRX_ID = TRANSAKSI.TRX_ID AND DETAIL_VOUCHER.VOC_ID = VOUCHER.VOC_ID
AND TRANSAKSI.TRX_ID='0'));<file_sep>/TIXID_App/app/Models/Kursi.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kursi extends Model
{
use HasFactory;
protected $table = "kursi";
protected $fillable = ['tik_id', 'sch_id', 'chr_kode'];
protected $primaryKey = "chr_id";
public function tiket()
{
return $this->hasOne(Tiket::class, "tik_id", "tik_id");
}
}
<file_sep>/TIXID_App/app/Models/DetailVoucher.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class DetailVoucher extends Model
{
use HasFactory;
protected $table = "detail_voucher";
protected $fillable = ['trx_id', 'voc_id'];
protected $primaryKey = "trx_id";
// public function voucher()
// {
// return $this->belongsTo(Voucher::class, "voc_id", "voc_id");
// }
// public function transaksi()
// {
// return $this->belongsTo(Transaksi::class, "trx_id", "trx_id");
// }
}
<file_sep>/TIXID_App/app/Models/Film.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Film extends Model
{
use HasFactory;
protected $table = "film";
protected $fillable = ['cat_id', 'mov_judul', 'mov_durasi'];
protected $primaryKey = "mov_id";
public function kategorifilm()
{
return $this->belongsTo(KategoriFilm::class, "cat_id", "cat_id");
}
public function jadwals()
{
return $this->hasMany(Jadwal::class, 'mov_id', 'mov_id');
}
}
<file_sep>/TIXID_App/database/seeders/KategoriFilmSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class KategoriFilmSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
for($i = 1; $i <= 10; $i++)
{
$kategoriData[] = [
'cat_nama' => $faker->word()
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($kategoriData, 10000);
foreach($chunks as $chunk) {
DB::table('kategori_film')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/KursiSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Jadwal;
use App\Models\Tiket;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class KursiSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
ini_set('memory_limit','-1');
$faker = Faker::create();
$Jadwal_ids = Jadwal::all()->pluck('sch_id')->toArray();
for($i = 1;$i <= 50000; $i++){
$KursiData[]= [
'sch_id' => $Jadwal_ids[array_rand($Jadwal_ids)],
'chr_kode' => $faker->bothify('?-##')
];
echo 'Creating data: ' .$i.PHP_EOL;
}
$chunks = array_chunk($KursiData, 10000);
foreach($chunks as $chunk) {
DB::table('kursi')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/VoucherSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class VoucherSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
for($i = 1; $i <= 500; $i++)
{
$voucherData[] = [
'voc_kode_voucher' => $faker->word(),
'voc_nominal' => $faker->numberBetween(5000, 25000)
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($voucherData, 10000);
foreach($chunks as $chunk) {
DB::table('voucher')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/database/seeders/StudioSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Bioskop;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class StudioSeeder extends Seeder
{
/*
*
* Run the database seeds.
*
* @return void
*/
public function run()
{
ini_set('memory_limit', '-1');
$faker = Faker::create();
$cin_ids = Bioskop::all()->pluck('cin_id')->toArray();
for($i = 1; $i <= 1000; $i++)
{
$studioData[] = [
'cin_id' => $cin_ids[array_rand($cin_ids)],
'std_kapasitas' => $faker->numberBetween(50, 250)
];
echo 'Creating data: '.$i.PHP_EOL;
}
$chunks = array_chunk($studioData, 10000);
foreach($chunks as $chunk) {
DB::table('studio')->insertOrIgnore($chunk);
echo 'Inserting data...'.PHP_EOL;
}
}
}
<file_sep>/TIXID_App/app/Models/MetodePembayaran.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MetodePembayaran extends Model
{
use HasFactory;
protected $table = "metode_pembayaran";
protected $fillable = ['pel_id', 'mtd_jenis', 'mtd_bank', 'mtd_nomor_kartu', 'mtd_expired', 'mtd_cvv'];
protected $primaryKey = "mtd_id";
public function pelanggans()
{
return $this->belongsTo(Pelanggan::class, 'pel_id', 'pel_id');
}
public function transaksis()
{
return $this->hasMany(Transaksi::class, "mtd_id", "mtd_id");
}
}
|
69409cb9951513214d2b7255c901af45cf21ddc7
|
[
"Markdown",
"SQL",
"PHP"
] | 28
|
PHP
|
muhrizqullah/FinalProjectMBD
|
728ecd67a766ff79cd977176b7729acd76b72208
|
3c276b8ddf7c43683ced3053d24336adfda0084b
|
refs/heads/master
|
<repo_name>dorage123/Rabbit<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Push_setting.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.pw_find.*
class Push_setting : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.push_setting)
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Join.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.join.*
class Join : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.join)
txtHeaderTitle.text="회원가입";
btnHeaderBack.setOnClickListener {
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
btnSubmit.setOnClickListener {
val intent = Intent(this, JoinOk::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Main.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceFragment
import android.preference.SwitchPreference
import android.util.Log
import kotlinx.android.synthetic.main.main.*
class Main : Common() {
val fragment=MyPreferenceFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
//fragmentManager.beginTransaction().replace(R.id.preferenceContent,fragment).commit()
}
class MyPreferenceFragment:PreferenceFragment(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
activity.startForegroundService(Intent(activity, LockScreenService::class.java))
} else {
activity.startService(Intent(activity, LockScreenService::class.java))
}
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Login.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.login.*
class Login : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login)
txtHeaderTitle.text="로그인";
btnLogin.setOnClickListener {
val intent = Intent(this, Main::class.java)
startActivity(intent)
}
btnFind.setOnClickListener {
val intent = Intent(this, ID_find::class.java)
startActivity(intent)
}
btnJoin.setOnClickListener {
val intent = Intent(this, Join::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/PW_change.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.pw_change.*
class PW_change : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.pw_change)
txtHeaderTitle.text="비밀번호 변경";
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/DetailModify.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.member_modify.*
class DetailModify : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.detail_modify)
txtHeaderTitle.text="상세정보 수정";
btnSubmit.setOnClickListener {
val intent = Intent(this, Setting::class.java)
startActivity(intent)
}
}
}
<file_sep>/homeclass_siren_ver4(insert)/sirenTest/src/main/java/dealim/cs/siren/bean/TestBean.java
<<<<<<< HEAD
package dealim.cs.siren.bean;
public class TestBean {
private String userid;
private String name;
private String tel;
private String addr;
private String user_password;
private String user_email;
private String medicament;
private String blood_type;
private String date_of_birth;
private String user_weight;
private String oft_hospital;
private String disease_name;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getMedicament() {
return medicament;
}
public void setMedicament(String medicament) {
this.medicament = medicament;
}
public String getBlood_type() {
return blood_type;
}
public void setBlood_type(String blood_type) {
this.blood_type = blood_type;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getUser_weight() {
return user_weight;
}
public void setUser_weight(String user_weight) {
this.user_weight = user_weight;
}
public String getOft_hospital() {
return oft_hospital;
}
public void setOft_hospital(String oft_hospital) {
this.oft_hospital = oft_hospital;
}
public String getDisease_name() {
return disease_name;
}
public void setDisease_name(String disease_name) {
this.disease_name = disease_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
=======
package dealim.cs.siren.bean;
public class TestBean {
private String userid;
private String name;
private String tel;
private String addr;
private String user_password;
private String user_email;
private String medicament;
private String blood_type;
private String date_of_birth;
private String user_weight;
private String oft_hospital;
private String disease_name;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getMedicament() {
return medicament;
}
public void setMedicament(String medicament) {
this.medicament = medicament;
}
public String getBlood_type() {
return blood_type;
}
public void setBlood_type(String blood_type) {
this.blood_type = blood_type;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getUser_weight() {
return user_weight;
}
public void setUser_weight(String user_weight) {
this.user_weight = user_weight;
}
public String getOft_hospital() {
return oft_hospital;
}
public void setOft_hospital(String oft_hospital) {
this.oft_hospital = oft_hospital;
}
public String getDisease_name() {
return disease_name;
}
public void setDisease_name(String disease_name) {
this.disease_name = disease_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
>>>>>>> <PASSWORD>c
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Setting.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.setting.*
class Setting : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.setting)
imgbtn_user_re.setOnClickListener {
val intent = Intent(this, Identification::class.java)
startActivity(intent)
}
imgbtn_user_re2.setOnClickListener {
val intent = Intent(this, DetailModify::class.java)
startActivity(intent)
}
imgbtn_user_re3.setOnClickListener {
val intent = Intent(this, PW_change::class.java)
startActivity(intent)
}
imageButton4.setOnClickListener {
val intent = Intent(this, Push_setting::class.java)
startActivity(intent)
}
imageButton6.setOnClickListener {
val intent = Intent(this, Notification_list::class.java)
startActivity(intent)
}
btnLogin.setOnClickListener {
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/MemberModify.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.member_modify.*
class MemberModify : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.member_modify)
txtHeaderTitle.text="기본정보 수정";
btnHeaderBack.setOnClickListener {
val intent = Intent(this, Join::class.java)
startActivity(intent)
}
btnSubmit.setOnClickListener {
val intent = Intent(this, Setting::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Identification.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.identification.*
import kotlinx.android.synthetic.main.setting.*
class Identification : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.identification)
txtHeaderTitle.text="본인확인";
btnHeaderBack.setOnClickListener {
val intent = Intent(this, Setting::class.java)
startActivity(intent)
}
btnSubmit.setOnClickListener {
val intent = Intent(this, MemberModify::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/PW_find.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.pw_find.*
class PW_find : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.pw_find)
txtHeaderTitle.text="아이디/비밀번호 찾기";
btnIdFind.setOnClickListener {
val intent = Intent(this,ID_find::class.java)
startActivity(intent)
}
btnPwFind.setOnClickListener {
val intent = Intent(this, PW_change::class.java)
startActivity(intent)
}
}
}
<file_sep>/homeclass_siren_ver4(insert)/sirenTest/src/main/java/dealim/cs/siren/sevice/TestService.java
<<<<<<< HEAD
package dealim.cs.siren.sevice;
import java.util.List;
import dealim.cs.siren.bean.TestBean;
public interface TestService {
public List<TestBean> user_db() throws Exception;
public void user_insert(TestBean vo) throws Exception;
}
=======
package dealim.cs.siren.sevice;
import java.util.List;
import dealim.cs.siren.bean.TestBean;
public interface TestService {
public List<TestBean> user_db() throws Exception;
public void user_insert(TestBean vo) throws Exception;
}
>>>>>>> 3d7f0d00237b3cbfd5e754bbf7676b2b0da9e90c
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/JoinOk.kt
package com.cookandroid.kotlinapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.header.*
import kotlinx.android.synthetic.main.join_ok.*
class JoinOk : Common() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.join_ok)
txtHeaderTitle.text="회원가입 완료";
btnHome.setOnClickListener {
val intent = Intent(this, Main::class.java)
startActivity(intent)
}
btnHeaderBack.setOnClickListener {
val intent = Intent(this, Main::class.java)
startActivity(intent)
}
}
}
<file_sep>/ppiyongppiyong4/app/src/main/java/com/cookandroid/kotlinapp/Common.kt
package com.cookandroid.kotlinapp
import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.view.View
@SuppressLint("Registered")
open class Common: AppCompatActivity() {
fun back(@Suppress("UNUSED_PARAMETER")v: View) {
finish()
}
fun goSetting(@Suppress("UNUSED_PARAMETER")v: View) {
val intent = Intent(this, Setting::class.java)
startActivity(intent)
}
}
|
ae20df75d50502deae2c927646e8ead46421766f
|
[
"Java",
"Kotlin"
] | 14
|
Kotlin
|
dorage123/Rabbit
|
7afd14492d87cf3d63ac5deeb02aa8f6385d4cd7
|
b62d9297e85b574066c6da9969c99a51f47bc96d
|
refs/heads/master
|
<repo_name>A-Rejo/GitHub-Practice<file_sep>/HelloWorld.java
public class HelloWorld{
public static void main (String [] args){
System.out.println("Hello World");
System.out.println("Hello Again");
System.out.println("Alright bye!");
System.out.println("Gotta say good bye one last time!");
}
}
|
b61cab1ef8f9520e1a6d179424b41a6c054c4b16
|
[
"Java"
] | 1
|
Java
|
A-Rejo/GitHub-Practice
|
550982f4860ae429eeb2aca2979242c4601704ba
|
dbc957385396762b6b70a24e5909445fb040b4be
|
refs/heads/master
|
<file_sep>/* gcc -o proj -Wl,-rpath=. -L. -I. -l poem proj.c */
#include "libpoem.h"
int main() {
int ret;
ret=this_is_an_external_func_in_a_lib();
return ret;
}
<file_sep>#! /usr/bin/python
import os,struct,sys
DEBUG=1
BIBAL="libbjr.so.ori"
#BIBAL="libc.so"
PROG="proj"
if len(sys.argv) == 2:
BIBAL=sys.argv[1]
def _print(s):
if DEBUG==1:
print s
def get_gnu_hash_position(lib):
_print("*** Get GNU HASH section for %s"%lib)
result=os.popen("readelf -S "+lib+" | grep .gnu.hash | awk '{ print $5,$6,$7; }'").readlines()
if len(result)==1:
_print("[+] Ok, one line. Good")
else:
print "[ ] Problem with readelf. Quitting"
exit(1)
result=result[0].rstrip()
start,offset,size=result.split(' ')
if int(start,16)==int(offset,16):
_print("[+] GNU HASH mapping fits perfectly disk and memory layout")
_print(" starting at 0x%s" % start)
_print(" and size is 0x%s long" % size)
else:
print "[ ] GNU HASH not aligned with file layout"
print " It can be enhanced"
exit(1)
return int(start,16),int(size,16)
def extract_gnu_hash(lib,start,size):
_print("*** Extracting .gnu.hash")
f=open(lib,"rb")
data = f.read(start+size)[start:start+size]
f.close()
return data
def parse_hash(blob):
_print("*** Parsing...")
header=blob[0:16]
nbuckets,symndx,maskwords,shift2=struct.unpack("<IIII",header)
print "[+] Header"
print "%d hash buckets" % nbuckets
print "%d symndx" % symndx
print "%d bloom masks" % maskwords
print "%d bloomshift (minimum 6)" % shift2
print "[+] Part 2 - bloom masks"
for i in range(maskwords):
mL=struct.unpack("<I",blob[(4+i)*4:(4+i+1)*4])
mB=struct.unpack(">I",blob[(4+i)*4:(4+i+1)*4])
print " Mask %d : %s \t| %s" % (i,hex(mL[0]),hex(mB[0]))
print "[+] Part 3 - N Buckets of hash"
cursor=4+maskwords
for i in range(nbuckets):
nL=struct.unpack("<I",blob[(cursor+i)*4:(cursor+i+1)*4])
nB=struct.unpack(">I",blob[(cursor+i)*4:(cursor+i+1)*4])
print " Bucket %d : %s \t| %s" % (i,hex(nL[0]),hex(nB[0]))
print "[+] Part 4 - Hashes"
cursor=(4+maskwords+nbuckets)
end=len(blob)/4
for i in range(cursor,end):
hL=struct.unpack("<I",blob[(i)*4:(i+1)*4])
hB=struct.unpack(">I",blob[(i)*4:(i+1)*4])
print " Hash %d : %s \t| %s" % (i-cursor,hex(hL[0]),hex(hB[0]))
start,size=get_gnu_hash_position(BIBAL)
blob=extract_gnu_hash(BIBAL,start,size)
parse_hash(blob)
<file_sep>#! /usr/bin/python
#This is propa codaz
#Will rewrite it someday. perhaps. "It works for me (c)"
#For the moment, it only works with libpoem.so because of hardcoded offsets.
import sys
import os
import struct
old_func="this_is_an_external_func_in_a_lib"
len_func=len(old_func)
old_lib="libpoem.so.ori"
old_proj="proj.ori"
new_lib="libpoem.so"
new_proj="proj"
if len(sys.argv) == 2:
if len(sys.argv[1]) == 33:
chaine = sys.argv[1]
elif len(sys.argv[1]) > 10 and len(sys.argv[1]) != 33:
chaine = sys.argv[1]
if len(chaine)%2 != 0:
print "give input in hex"
exit(1)
l=len(chaine)
print "we have %d char, must add %d to get 33" % (l/2,33-l/2)
chaine = chaine + '41'*(33-(l/2))
chaine=chaine.decode('hex')
else:
print "Give a longer chaine"
exit(1)
else:
print "Give a new name"
exit(1)
def dl_new_hash(func):
h=5381
for c in list(func):
h=h*33+ord(c)
h=hex(h & 0xffffffff)[2:-1]
print " [+] hash results for %s is 0x%s" % (func,h.upper())
return h[6:8]+h[4:6]+h[2:4]+h[0:2]
print "[+] Patching func with name (in hex): %s\n" % chaine.encode('hex')
##Get buckets number
result=os.popen("readelf -S "+old_lib+" | grep .gnu.hash | awk '{ print $5,$6,$7; }'").readlines()
if len(result)==1:
print "[+] Ok, one line. Good"
else:
print "[ ] Problem with readelf, quitting here"
exit(1)
result=result[0].rstrip()
start,offset,size=result.split(' ')
start=int(start,16)
f=open(old_lib,"rb")
data=f.read(start+4)[start:start+4]
f.close()
nbuckets=struct.unpack("<I",data)
print "[+] nbuckets is %d" % nbuckets
nbuckets=nbuckets[0]
a=int(dl_new_hash(old_func),16)
b=int(dl_new_hash(chaine),16)
if (a % nbuckets) == (b % nbuckets):
print " Guess: Working"
else:
print " Guess: Broken"
exit(1)
print "[+] Patching proj binary"
f=open(old_proj,"rb")
data=f.read()
f.close()
#Beware of string findings
new_data=data.replace(old_func,chaine)
f=open(new_proj,"wb")
f.write(new_data)
f.close()
print "[+] Opening %s" % old_lib
f=open(old_lib,"rb")
data=f.read()
f.close()
#This is hardcoded. You can change them.
#Or write a function findings those offsets.
#offsets list
ofbloom1=0x128
ofbloom2=0x12c
ofh=0x144
of1=0x2e5
of2=0x1795
print " [+] Patching bloom filter"
new_data=data[0:ofbloom1]+"\xff\xff\xff\xff"+data[ofbloom1+4:ofbloom2]+"\xff\xff\xff\xff"
print " [+] Patching hash"
new_data=new_data+data[ofbloom2+4:ofh]+dl_new_hash(chaine).zfill(8).decode('hex')
print " [+] Patching function name"
new_data=new_data+data[ofh+4:of1]+chaine+data[of1+len_func:of2]+chaine+data[of2+len_func:]
f=open(new_lib,"wb")
f.write(new_data)
f.close()
<file_sep>/* Compile with gcc -shared -o libpoem.so libpoem.c */
#include <stdio.h>
int this_is_an_external_func_in_a_lib() {
puts("ARM disassembly"); //5
puts("Reading symbol resolving"); //7
puts("In the cold of night"); //5
return 42;
}
<file_sep>int this_is_an_external_func_in_a_lib();
<file_sep>#! /usr/bin/python
import sys
if len(sys.argv) !=2:
print "Give a name"
print "Bye.."
if len(sys.argv) == 2:
print "[+] Calculating hash for %s" % sys.argv[1]
func=sys.argv[1]
else:
func='\x0d\x0aA\x0d\x0a'
h=5381
for c in list(func):
h=h*33+ord(c)
hash=hex(h & 0xffffffff)[2:-1].upper()
print "Output is 0x%s" % hash
#print "Output2 is 0x%s" % hex(h)[2:-1].upper()
<file_sep># PatchFuncName
Warning, this is highly experimental code. for the moment, it can patch function name in the proj and libpoem.so.
You can use the _patch.py_ program to do so. You can use any string with 33 characters, with any characters except the \x00. There is hardcoded offsets in the file, so don't expect it to work anywhere than the libpoem.so provided. It should be easy to modify it to work for any file, though. proj and libpoem.so are compiled for a raspberrypi.
The _hashparse.py_ can parse the .gnu.hash section of ELF files, it should work anywhere.
The dl\_new\_hash.py can calculate hashes.
Those files have been used to create the blogpost: http://0x90909090.blogspot.fr/2018/02/fun-with-function-names-where-resolving.html
|
b7bf31ca064cc99077946c58303b06243c144004
|
[
"Markdown",
"C",
"Python"
] | 7
|
C
|
0xmitsurugi/PatchFuncName
|
f2f797ac36a66ec2499d998ceb518a5d8afde13a
|
8dfa302822f3a399b51902252e5e5c8bc7d91ad0
|
refs/heads/master
|
<repo_name>WeMustFly/oop-store<file_sep>/index.php
<?php
\spl_autoload_register(function ($class) {
$classFilename = __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR
. \str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
require $classFilename;
});
$category = new \OOPStore\Category('TV');
$product1 = new \OOPStore\Product($category, 'LG LX35', 1000000);
$product2 = new \OOPStore\Product($category, 'LG LX35', 1000000);
$store = new \OOPStore\Store();
$customer = new \OOPStore\Customer('Ivan', 'Ivanovich');
$cart = new \OOPStore\Models\Cart($customer);
foreach ([$product1, $product1, $product2] as $product) {
try {
$store->addProduct($product);
} catch (\OOPStore\StoreException $e) {
echo $e->getMessage() . PHP_EOL;
}
}
$store->removeProduct($product1);
$cart->addProduct($product1);
try {
$store->removeProduct($product1);
} catch (\OOPStore\StoreException $e) {
echo $e->getMessage() . PHP_EOL;
}
print_r($store->getProducts());
print_r($cart->getTotal());
<file_sep>/src/OOPStore/Product.php
<?php
namespace OOPStore;
class Product implements ProductInterface
{
private $id;
private $category;
private $name;
private $price;
static private $lastID = 0;
public function __construct(Category $category, $name, $price)
{
$this->id = ++self::$lastID;
$this->category = $category;
$this->name = $name;
$this->price = $price;
}
public function getId(): int
{
return $this->id;
}
public function setPrice($price)
{
if ($price > 0) {
$this->price = $price;
}
}
public function getPrice(): float
{
return $this->price;
}
public function getCategory(): Category
{
return $this->category;
}
}<file_sep>/src/OOPStore/StoreInterface.php
<?php
namespace OOPStore;
interface StoreInterface
{
public function getProducts(): array;
public function addProduct(Product $product): void;
public function removeProduct(Product $product): void;
public function hasProduct(Product $product): bool;
}
<file_sep>/src/OOPStore/Models/Cart.php
<?php
namespace OOPStore\Models;
use OOPStore\Customer;
use OOPStore\Product;
use OOPStore\Purchase;
class Cart
{
private $customer;
private $products;
private $purchase;
public function __construct(Customer $customer)
{
$this->customer = $customer;
$this->products = [];
}
public function getCustomer()
{
return $this->customer;
}
public function addProduct(Product $product)
{
if (empty($this->purchase)) {
$this->products[] = $product;
}
}
public function getTotal()
{
$total = 0;
foreach ($this->products as $product) {
$total += $product->getPrice();
}
return $total;
}
public function createPurchase(): Purchase
{
$this->purchase = new Purchase($this);
return $this->purchase;
}
}
<file_sep>/src/OOPStore/Purchase.php
<?php
namespace OOPStore;
class Purchase
{
private $cart;
public function __construct(Cart $cart)
{
$this->cart = $cart;
}
}
<file_sep>/src/OOPStore/CustomerInterface.php
<?php
namespace OOPStore;
interface CustomerInterface
{
public function getFirstName(): string;
public function getLastName(): string;
}
<file_sep>/src/OOPStore/Store.php
<?php
namespace OOPStore;
class Store implements StoreInterface
{
private $products = [];
public function getProducts(): array
{
return $this->products;
}
public function addProduct(Product $product): void
{
if ($this->hasProduct($product)) {
throw new StoreException('Duplicate product');
}
$this->products[$product->getId()] = $product;
}
public function removeProduct(Product $product): void
{
if (!$this->hasProduct($product)) {
throw new StoreException('Product not found');
}
unset($this->products[$product->getId()]);
}
public function hasProduct(Product $product): bool
{
return isset($this->products[$product->getId()]);
}
}
<file_sep>/src/OOPStore/StoreException.php
<?php
namespace OOPStore;
use Exception;
class StoreException extends Exception
{
}
<file_sep>/src/OOPStore/ProductInterface.php
<?php
namespace OOPStore;
interface ProductInterface
{
public function getId(): int;
public function getPrice(): float;
public function getCategory(): Category;
}
|
47943948711e9098647d84bc9d8894f63dd41a6c
|
[
"PHP"
] | 9
|
PHP
|
WeMustFly/oop-store
|
1650e8c4c86a652a0951760f8032a3684dec88ac
|
5b524758d25d6a69f5b510437b9f5aaa6e6b46ec
|
refs/heads/master
|
<file_sep>XBNCEventful
============
[](https://github.com/MKGitHub/XBNCEventful)
[](https://github.com/MKGitHub/XBNCEventful)
[](https://github.com/MKGitHub/XBNCEventful)
Library for sending & receiving events much like notifications but only in your app for event-based architecture.
Please visit the [Wiki](https://github.com/MKGitHub/XBNCEventful/wiki) for full introduction.
-
https://github.com/MKGitHub/XBNCEventful
http://www.xybernic.com
http://www.khanofsweden.com
Copyright 2014 <NAME>
Licensed under the Apache License, Version 2.0.
<file_sep>Pod::Spec.new do |s|
s.name = "XBNCEventful"
s.version = "0.1.0"
s.summary = "Library for sending & receiving events much like notifications but only in your app for event-based architecture."
s.description = <<-DESC
XBNCEventful is a library for sending & receiving events much like notifications but only in your app for event-based architecture.
- Lightweight and simple to use.
- Avoid all the mysteries of notifications and the notification center.
- Private and local in your app, not globally shared with the entire OS eco system and other apps.
- Guaranteed to send & receive events, also debug friendly.
- Keep loose coupling, get rid of strong direct method invocation and direct relationships between objects.
- Distributed, low-coupling characteristics, benefit from greater circulation.
- Easily scalable architecture.
- Get rid of boilerplate, glue-code and spaghetti-code.
- Receive event in block or selector.
DESC
s.homepage = "https://github.com/MKGitHub/XBNCEventful"
s.screenshots = "https://raw.githubusercontent.com/MKGitHub/XBNCEventful/master/Media/MacOSX_Demo.gif", "https://raw.githubusercontent.com/MKGitHub/XBNCEventful/master/Media/iOS_Demo.gif", "https://raw.githubusercontent.com/MKGitHub/XBNCEventful/master/Media/Patterns.png"
s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE.txt" }
s.author = { "<NAME>" => "<EMAIL>" }
s.ios.deployment_target = "4.0"
s.osx.deployment_target = "10.6"
s.source = { :git => "https://github.com/MKGitHub/XBNCEventful.git", :tag => "0.1.0" }
s.source_files = "Classes", "Classes/**/*.{h,m}"
s.public_header_files = "Classes/**/*.h"
s.requires_arc = true
end
<file_sep>//
// XBNCHeader.h
// XBNCEventful
//
// https://github.com/MKGitHub/XBNCEventful
// http://www.xybernic.com
// http://www.khanofsweden.com
//
// Copyright 2014 <NAME>
//
// 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.
//
/*!
* @brief Header file with useful macros.
*
* @since 1.0.0
*/
#ifndef XBNCEventful_XBNCHeader_h
#define XBNCEventful_XBNCHeader_h
#pragma mark - Event Trigger Limit
/*!
* @define XBNCEventTriggerLimit
*
* @abstract Macro typedef (NSUInteger) for convenience.
*
* @since 1.0.0
*/
#define XBNCEventTriggerLimit NSUInteger
/*!
* @define XBNCEventTriggerLimitUnlimited
*
* @abstract Macro typedef (NSUIntegerMax) for convenience.
*
* @since 1.0.0
*/
#define XBNCEventTriggerLimitUnlimited NSUIntegerMax
#pragma mark - Standard Console Logging (Private, used internally)
/*!
* @abstract Console logging.
*
* @since 1.0.0
*/
#define XBNCLogNL printf("\n");
#define XBNCLogC(fmt, ...) printf(fmt, ## __VA_ARGS__); printf("\n");
#define XBNCLogCi(fmt, ...) printf(fmt, ## __VA_ARGS__);
#define XBNCLogS(fmt, ...) printf("%s\n", [[NSString stringWithFormat: fmt, ## __VA_ARGS__] cStringUsingEncoding: NSUTF8StringEncoding]);
#define XBNCLogSi(fmt, ...) printf("%s", [[NSString stringWithFormat: fmt, ## __VA_ARGS__] cStringUsingEncoding: NSUTF8StringEncoding]);
#define XBNCTestLogS(fmt, ...) printf(">>>>> [XBNCEventful Test] %s\n", [[NSString stringWithFormat: fmt, ## __VA_ARGS__] cStringUsingEncoding: NSUTF8StringEncoding]);
#define XBNCCalledLog(fmt, ...) printf("[CALLED] %s %s\n", __FUNCTION__, [[NSString stringWithFormat: fmt, ## __VA_ARGS__] cStringUsingEncoding: NSUTF8StringEncoding]);
#define XBNCError(fmt, ...) printf("[ERROR] %s\n", [[NSString stringWithFormat: fmt, ## __VA_ARGS__] cStringUsingEncoding: NSUTF8StringEncoding]);
#pragma mark - Strings (Private, used internally)
/*!
* @abstract Strings.
*
* @since 1.0.0
*/
#define XBNC_$(...) [NSString stringWithFormat:__VA_ARGS__, nil]
#define XBNC_STR_FORMAT(fmt, ...) [NSString stringWithFormat: fmt, ## __VA_ARGS__]
#define XBNC_STR_JOIN(_a_, _b_) [(_a_) stringByAppendingString:(_b_)]
#endif
|
f26b4c4e259daaff80204753a694d57326aec47d
|
[
"Markdown",
"C",
"Ruby"
] | 3
|
Markdown
|
MKGitHub/XBNCEventful
|
abc3ad641190dfd6c1f7756096db727ba14a413d
|
056d4e941dd7ba49f08ab0332a84bc0734993dc8
|
refs/heads/main
|
<file_sep><?php
namespace App\Services;
use App\Entity\Meteo;
class ApiBuilder
{
public function buildMeteoInfos ($meteoData)
{
$meteo = new Meteo();
$meteo->setName($meteoData->location->name);
$meteo->setWeatherDescriptions($meteoData->current->weather_descriptions[0]);
$meteo->setTemperature($meteoData->current->temperature);
$meteo->setHumidity($meteoData->current->humidity);
$meteo->setWeatherIcons($meteoData->current->weather_icons[0]);
}
}<file_sep><?php
namespace App\Services;
use App\Entity\Meteo;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
class Service
{
private $param;
private $request;
public function __construct(ParameterBagInterface $param, Request $request)
{
$this->param = $param;
$this->request = $request;
}
public function findMeteoInfos(): array
{
$url = $this->param->get('api.meteo.url');
$key = $this->param->get('api.meteo.key');
$ville = $this->request->request->get('search');
$apiService = new ApiService();
$apiBuilder = new ApiBuilder();
$apiService->requestData($url , $key, $ville);
}
}<file_sep><?php
namespace App\Entity;
use App\Repository\MeteoRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=MeteoRepository::class)
* @UniqueEntity(fields={"name"},
* message="Votre selection se trouve dans mes favoris")
*/
class Meteo
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255, unique=true)
*/
private $name;
/**
* @ORM\Column(type="string", length=255)
*/
private $weather_descriptions;
/**
* @ORM\Column(type="integer")
*/
private $temperature;
/**
* @ORM\Column(type="integer")
*/
private $humidity;
/**
* @ORM\Column(type="string", length=255)
*/
private $weather_icons;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getWeatherDescriptions(): ?string
{
return $this->weather_descriptions;
}
public function setWeatherDescriptions(string $weather_descriptions): self
{
$this->weather_descriptions = $weather_descriptions;
return $this;
}
public function getTemperature(): ?int
{
return $this->temperature;
}
public function setTemperature(int $temperature): self
{
$this->temperature = $temperature;
return $this;
}
public function getHumidity(): ?int
{
return $this->humidity;
}
public function setHumidity(int $humidity): self
{
$this->humidity = $humidity;
return $this;
}
public function getWeatherIcons(): ?string
{
return $this->weather_icons;
}
public function setWeatherIcons(string $weather_icons): self
{
$this->weather_icons = $weather_icons;
return $this;
}
public function getweather_icons(): ?string
{
return $this->weather_icons;
}
public function getweather_descriptions(): ?string
{
return $this->weather_descriptions;
}
public function isUnique()
{
return $this->name;
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addConstraint(new UniqueEntity([
'fields' => 'name',
'message'=> "Votre selection se trouve dans vos favoris"
]));
$metadata->addPropertyConstraint('name', new Assert\Unique());
}
}
<file_sep>import './styles/app.css';
import {main} from "./scripts/service";
/**
* affiche le resultat de l'api local
*/
// main();
<file_sep>import {displayWeatherInfos} from "./services/apiDataBuilder";
/**
* renvoie des données recupérées à partir de l'IP
*/
export async function main() {
let ip = await fetch("http://api.ipify.org?format=json")
.then((response) => response.json())
.then((json) => json.ip);
let ville = await fetch("http://ip-api.com/json/" + ip)
.then((response) => response.json())
.then((json) => json.city);
let meteo = await fetch(
"http://api.weatherstack.com/current?access_key=a8428b479404066eb4cc869472318314&lang=fr&query=" +
ville
)
.then((response) => response.json())
.then((json) => json);
displayWeatherInfos(meteo);
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Meteo;
use App\Form\MeteoType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class HomeController extends AbstractController
{
private $param;
public function __construct(ParameterBagInterface $param)
{
$this->param = $param;
}
/**
* @Route("/", name="home", methods={"GET", "POST"})
*/
public function addMeteoInfos(Request $request)
{
$meteo = new Meteo();
$form = $this->createForm(MeteoType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$url = $this->param->get('api.meteo.url');
$key = $this->param->get('api.meteo.key');
$ville = $request->request->get('search');
$fullUrl = $url . $key . $ville;
$meteoInfos = json_decode(file_get_contents($fullUrl));
$meteo->setName($meteoInfos->location->name);
$meteo->setWeatherDescriptions($meteoInfos->current->weather_descriptions[0]);
$meteo->setTemperature($meteoInfos->current->temperature);
$meteo->setHumidity($meteoInfos->current->humidity);
$meteo->setWeatherIcons($meteoInfos->current->weather_icons[0]);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($meteo);
$entityManager->flush();
} catch (\Exception $exception) {
$this->addFlash(
'error',
'Server error: ' . $exception->getMessage()
);
}
return $this->redirectToRoute('meteo-show');
}
return $this->render('home/index.html.twig', [
'meteo' => $meteo,
'form' => $form->createView(),
]);
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\Meteo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Meteo|null find($id, $lockMode = null, $lockVersion = null)
* @method Meteo|null findOneBy(array $criteria, array $orderBy = null)
* @method Meteo[] findAll()
* @method Meteo[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MeteoRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Meteo::class);
}
public function findMeteoByName($name)
{
return $this->createQueryBuilder("m")
->andWhere("m.name=:NAME")
->setParameter('NAME', $name)
->orderBy('m.id', 'DESC')
->setMaxResults(1)
->setLifetime(1)
->getQuery()->getResult();
}
// /**
// * @return Meteo[] Returns an array of Meteo objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('m')
->andWhere('m.exampleField = :val')
->setParameter('val', $value)
->orderBy('m.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Meteo
{
return $this->createQueryBuilder('m')
->andWhere('m.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep><?php
namespace App\Services;
class ApiService
{
public function requestData($url, $key, $ville)
{
$fullUrl = $url.$key.$ville;
$meteoInfos = json_decode(file_get_contents($fullUrl));
return $meteoInfos;
}
}<file_sep><?php
namespace App\Controller;
use App\Entity\Meteo;
use App\Repository\MeteoRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class MeteoController
* @package App\Controller
* @Route ("/meteo")
*/
class MeteoController extends AbstractController
{
/**
* @Route("/", name="meteo")
*/
public function index(MeteoRepository $meteoRepository): Response
{
return $this->render('meteo/index.html.twig', [
'meteo' => $meteoRepository->findAll(),
]);
}
/**
* @Route("/city/", name="meteo-show", methods={"GET", "POST"})
*/
public function show(EntityManagerInterface $entityManager)
{
try {
$q = $entityManager->createQuery("SELECT m FROM App:Meteo m ORDER BY m.id DESC")
->setMaxResults(1)
->setLifetime(1);
} catch (\Exception $exception) {
$this->addFlash(
'error',
'Server error: ' . $exception->getMessage()
);
}
$meteo = $q->getResult();
return $this->render('meteo/show.html.twig', [
'meteo' => $meteo,
]);
}
/**
* @Route ("/{id}", name="meteo-delete", methods={"DELETE"})
*/
public function delete(Request $request, Meteo $meteo): Response
{
if ($this->isCsrfTokenValid('delete' . $meteo->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($meteo);
$entityManager->flush();
}
return $this->redirectToRoute('meteo');
}
/**
* @Route("/detail/{name}", name="detail-meteo")
*/
public function detail(MeteoRepository $meteoRepository, $name)
{
$meteo = $meteoRepository->findMeteoByName($name);
return $this->render("meteo/detail.html.twig", [
'meteo' => $meteo,
'name' => $name,]);
}
}
|
543044e7fdd03835e84f570dc8c74a5cc69c85a4
|
[
"JavaScript",
"PHP"
] | 9
|
PHP
|
boubasano/appli_meteo
|
eb88fb9f9dc818a3c62e2b1318564f5d61bd804e
|
97b7e47b57cc1e02661b9a9842d5141b494f4317
|
refs/heads/master
|
<file_sep>#!/usr/bin/env nodejs
//Followed example in https://github.com/dimircea/WebRTC/blob/master/SimpleVideoChat/server.js
const WebSocketServer = require('ws').Server,
express = require('express'),
bodyParser = require('body-parser'),
http = require('https'),
app = express(),
fs = require('fs'),
config = require('./config.js'),
schedule = require('node-schedule');
var cfg = {
ssl: true,
ssl_key: './ssl/privkey.pem',
ssl_cert:'./ssl/fullchain.pem'
};
var wsClients = {}; //Stores a map of doctor IDs to a map of web session IDs to web socket clients.
var availDocs = 0; //Number of available doctors.
var emts = [];
//Keys for TWilio
var twilioClient = require('twilio')(config.twilioSid, config.twilioKey);
var stats = {};
schedule.scheduleJob('0 0 0 * * *', function(){
//Everyday at midnight, reset the statistics.
stats = {};
});
//Keys for SendGrid
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(config.sendGridKey);
const emailBody = "You have been called as an Emergency Contact. Start a conversation with the doctor here: ";
const emailMsg = {
from: '<EMAIL>',
subject: 'You have been selected as an Emergency Contact!',
};
const pKey = fs.readFileSync(cfg.ssl_key),
pCert = fs.readFileSync(cfg.ssl_cert),
options = {key: pKey, cert: pCert};
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
if(req.headers['x-forwarded-proto']==='http') {
return res.redirect(['https://', req.get('host'), req.url].join(''));
}
next();
});
app.post('/api/v1/requestdoctor', function(req, res) {
console.log('/api/v1/requestdoctor received: ' + JSON.stringify(req.body));
var obj = {};
obj['type'] = 'request';
obj['skypeid'] = req.body.skypeid;
obj['email'] = req.body.email;
obj['number'] = req.body.number;
obj['requestTime'] = new Date();
obj['message'] = JSON.stringify(req.body);
emts.push(obj);
sendMessage(obj);
res.status(200).send("OK");
});
app.post('/api/v1/getavailabledoctors', function(req, res) {
console.log('/api/v1/getavailabledoctors received: ' + JSON.stringify(req.body));
updateClients();
var obj = {};
obj['availabledoctors'] = availDocs;
res.status(200).send(JSON.stringify(obj));
});
function emtAccepted(emtId, webId) {
for(var i = emts.length - 1; i >= 0; i--) {
if (emts[i].skypeid == emtId) {
emts.splice(i, 1);
}
}
var obj = {};
obj['type'] = 'remove';
obj['skypeid'] = emtId;
obj['message'] = 'Remove id: ' + emtId;
sendMessage(obj);
availDocs--;
}
function sendMessage(obj){
updateClients();
if(Object.keys(wsClients).length == 0) {
//res.status(500).send("No doctors connected");
return;
}
for (var key in wsClients) {
var cliList = wsClients[key];
for (var i in cliList) {
var cli = cliList[i];
if(cli.readyState == cli.OPEN) {
console.log("Sending obj: " + JSON.stringify(obj) + " to key: " + key);
cli.send(JSON.stringify(obj));
}
}
}
}
function sendMessageToWeb(obj, docId, webId) {
for (var key in wsClients) {
if (key == docId){
var cliList = wsClients[key];
for (var i in cliList) {
if (i == webId) {
var cli = cliList[i];
if(cli.readyState == cli.OPEN) {
console.log("Sending obj: " + JSON.stringify(obj) + " to key: " + key);
cli.send(JSON.stringify(obj));
}
}
}
}
}
}
//Check if clients are open, if not, remove them from dictionary.
function updateClients() {
var tmp = {};
for (var key in wsClients) {
var cliList = wsClients[key];
for (var i in cliList) {
var cli = cliList[i];
if(cli.readyState != cli.OPEN) {
console.log("Removing id: " + i);
delete cliList[cli];
if (availDocs > 0){
availDocs--;
}
} else {
if(!(key in tmp)){
tmp[key] = {};
}
tmp[key][i] = cli;
}
}
}
wsClients = tmp;
}
var server = http.createServer({key:pKey, cert:pCert}, app).listen(3001, function(){
console.log("server running at https://localhost:3001");
});
var wss = new WebSocketServer({server: server});
/* on connect */
wss.on('connection', function(client) {
console.log("A new WebSocket client was connected.");
//wsClients.push(client);
var obj = {};
obj['type'] = 'hello';
obj['message'] = 'hello';
client.send(JSON.stringify(obj));
client.on('message', function(message) {
var msg = JSON.parse(message);
if (msg.type == 'hello') {
console.log("received doc id: " + msg.docId, " webId: " + msg.webId);
if(!(msg.docId in wsClients)) {
//We haven't seen this doctor yet.
//Create an object that maps the web session IDs to web socket clients.
wsClients[msg.docId] = {};
}
wsClients[msg.docId][msg.webId] = client;
for (var i = 0; i < emts.length; i++) {
client.send(JSON.stringify(emts[i]));
}
availDocs++;
if (msg.docId in stats) {
var obj = {};
obj['type'] = 'stats';
obj['stats'] = JSON.stringify(stats[msg.docId]);
console.log("Sending stats to: " + msg.docId);
client.send(JSON.stringify(obj));
} else {
stats[msg.docId] = {};
}
} else if(msg.type == 'sms'){
//Received request to send SMS.
emtAccepted(msg.skypeid, msg.webId);
console.log("Sending text to: " + msg.number);
twilioClient.messages.create({
to: "+1" + msg.number,
from: "+12062026089",
body: "You have been called as an Emergency Contact. Start a conversation with the doctor here: " + msg.link,
}, function(err, message) {
if (err){
console.log(err);
}
});
} else if (msg.type == 'email') {
//Received request to send email.
emtAccepted(msg.skypeid, msg.webId);
console.log("Sending email to: " + msg.email);
emailMsg.to = msg.email;
emailMsg.text = emailBody + msg.link;
sgMail.send(emailMsg);
} else if (msg.type == 'accept') {
//Resolved Skype ID without an email or sms request.
emtAccepted(msg.skypeid, msg.webId);
} else if (msg.type == 'upload') {
//Received request from contact to upload a photo.
//Notify the corresponding doctor web session.
var payload = {};
payload['type'] = 'upload';
payload['filename'] = msg.filename;
payload['handle'] = msg.handle;
payload['message'] = JSON.stringify(msg);
sendMessageToWeb(payload, msg.docId, msg.webId);
} else if (msg.type == 'delete') {
//Received request from contact to delete a photo.
//Notify the corresponding doctor web session.
var payload = {};
payload['type'] = 'delete';
payload['filename'] = msg.filename;
payload['handle'] = msg.handle;
payload['message'] = JSON.stringify(msg);
sendMessageToWeb(payload, msg.docId, msg.webId);
} else if (msg.type == 'endCall') {
//Received notification that doctor has finished call.
//Update the number of available doctors.
console.log("Received endCall from: " + msg.webId);
availDocs++;
} else if (msg.type == 'stats') {
//Received the stats from a doctor.
//Update today's statistics.
console.log("Received stats from: " + msg.webId);
console.log("Stats: " + msg.stats);
stats[msg.docId] = JSON.parse(msg.stats);
}
});
});
<file_sep>namespace PatientNet
{
using System;
using System.Diagnostics;
using System.IO;
using Windows.Storage;
public class Logger : ILogger
{
private StorageFile logFile;
public Logger(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(nameof(filename));
}
LoadLogFile(filename);
}
public async void Log(string message)
{
Debug.WriteLine(message);
try
{
await FileIO.WriteTextAsync(this.logFile, message);
}
catch
{
Debug.WriteLine("Could not write to log file...");
}
}
private async void LoadLogFile(string filename)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
this.logFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
namespace PatientNet
{
public class SkypeNames
{
public string Name { get; set; }
}
public static class SkypeNameDataSource
{
private static List<SkypeNames> _names = new List<SkypeNames>();
public static async Task CreateSkypeNameDataAsync()
{
// Don't need to do this more than once.
if (_names.Count > 0)
{
return;
}
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///temp/Names.txt"));
// StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Contacts.txt"));
IList<string> lines = await FileIO.ReadLinesAsync(file);
// Verify that it hasn't been done by someone else in the meantime.
if (_names.Count == 0)
{
for (int i = 0; i < lines.Count; i += 3)
{
_names.Add(new SkypeNames() { Name = lines[i] });
}
}
_names = _names.OrderBy(n => n.Name).ToList();
}
/// <summary>
/// Do a fuzzy search on all names and order results based on a pre-defined rule set
/// </summary>
/// <param name="query">The part of the name to look for</param>
/// <returns>An ordered list of names that matches the query</returns>
public static IEnumerable<SkypeNames> GetMatchingNames(string query)
{
return SkypeNameDataSource._names
.Where(n => n.Name.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) > -1)
.OrderByDescending(n => n.Name.StartsWith(query, StringComparison.CurrentCultureIgnoreCase));
}
}
}
<file_sep>## PatientNet
# To run HoloLens application as EMT:
* Put on the Hololens and ensure that the PatientNet application is installed
* If it is not installed:
* From the Hololens, open Settings > Network & Internet > Advanced Options to obtain the IP address of the Hololens
* From a web browser, enter the IP address of the Hololens and hit enter to open the Windows Device Portal
* Username: PatientNet
* Password: <PASSWORD>
* Retrieve the latest version of PatientNet from PatientNet/AppPackages/ on this github page, and install the x86 version of the package (with its 2 dependencies) in the 'Apps' tab of the Windows Device Portal
* Enter the EMT's skype name (e.g. eric.hwang8) into the 'Enter Skype Name' textbox. For more instructions, hover the Hololens pointer over the textbox.
* Enter the phone number and/or email address of the emergency contact into the 'Enter Contact Phone' and 'Enter Contact Email' textboxes, respectively. For more detailed instructions, hover the Hololens pointer over either textbox.
* Click the 'Notify Parties' button to request a doctor at the hospital and notify the emergency contact via text message, email, or both. Note that this request will be successful only if a skype name is entered. The contact information is not required, but is recommended.
* For general help on using the applcation, click the question mark icon at the top right of the application.
* To increase or decrease the font size, click the 'AA' icon on the top right of the application.
# Run web application as doctor
* Go to [481patientnet.com](https://481patientnet.com)
* Log in with doctor credentials:
* Email us for the passwords. We don't want them posted on Github.
There will be a list of EMT requests. Clicking on the EMT Skype name will automatically generate a meeting for the emergency contact and open Skype to call the EMT.
Note:
* Only audio calls are supported with the emergency contact
* You will need a <i>personal</i> Skype account and the classic [Skype Desktop app](https://www.skype.com/en/download-skype/skype-for-computer/) (the built-in Windows 10 Skype app doesn't support Hololens drawing)
* Both video and audio are supported for the call with the EMT
* If the EMT's video is blank, please follow instructions [here](https://forums.hololens.com/discussion/2343/hololens-add-in-is-causing-black-screen) to remedy
# To run web application as emergency contact
* Go to the link texted and/or emailed to you
* The emergency contact's number and/or email will be provided by the EMT on the HoloLens
* Fill out your name to join the meeting
* Call the doctor
* Note: Only audio calls are supported with the doctor
# Linux Commands to test API calls without using HoloLens
There are two options to test the emergency contact's web page without sending a text from the HoloLens:
1. Send a request for a doctor:
```
curl -i -X POST -H 'Content-Type: application/json' -d '{"skypeid":[id], "email":[<EMAIL>], "number":[number]}' https://481patientnet.com:3001/api/v1/requestdoctor
```
Note: Only "skypeid" is required.
2. Query the number of available doctors:
```
curl -i -X POST https://481patientnet.com:3001/api/v1/getavailabledoctors
```
<file_sep>namespace PatientNet
{
using System;
public class EnterEventArgs : EventArgs
{
public EnterEventArgs(MessageType type_)
{
this.Type = type_;
}
public MessageType Type { get; }
}
}<file_sep>namespace PatientNet
{
/**
* TODO:
* 1) Add summaries
* 2) Organize member functions
* 3) Improve UI
* 4) Add sound button enable / disable for HoloLens clicks
* 5) Improve user notification textbox (something more like toast)
* 6) Add headers to fields to better distinguish contact vs emt info
*
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.System.Display;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.Storage;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
public enum MessageType
{
Number, Skype, Email
};
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
DisplayRequest _displayRequest = new DisplayRequest();
private const int FormattedPhoneLength = 13;
private const int SleepTimeInMilliseconds = 1000;
private const string SendSmsEndpoint = "api/v1/sendsms";
private const string SendEmailEndpoint = "api/v1/sendemail";
private const string RequestDoctorsEndpoint = "api/v1/requestdoctor";
private const string AvailableDoctorsEndpoint = "api/v1/getavailabledoctors";
private enum TextSize
{
Small = 15, Large = 20
};
private TextSize textSize = TextSize.Small;
private Logger logger;
private const string LogFolder = ".logs";
private HashSet<string> numbersSentTo = new HashSet<string>();
private HashSet<string> emailsSentTo = new HashSet<string>();
private HashSet<string> skypesSentTo = new HashSet<string>();
private HashSet<MessageType> entersPressed = new HashSet<MessageType>();
HttpClient httpClient;
private const string ContentType = "application/json";
private StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
private const string skypeNameFile = ".skype.txt";
private DispatcherTimer availableDoctorTimer = new DispatcherTimer();
TimeSpan doctorTimerInterval = TimeSpan.FromSeconds(30); // Query every 30 seconds
private int oldPhoneLength = 0; // Used to determine if change was insert or delete
private bool skypeFocused = false;
private bool contactFocused = false;
private bool helpOn = false;
private delegate void SendRequestEventHandler(object sender, RequestEventArgs e);
private event SendRequestEventHandler SentRequest; // Invoke on phone click
private delegate void EnterEventHandler(object sender, EnterEventArgs e);
private event EnterEventHandler EnterPressed; // Invoke on enter
/// <summary>
/// Initializes page state upon opening the application
/// </summary>
public MainPage()
{
this.InitializeComponent();
string time = DateTime.Now.ToString("yyyyMMddHHmmss");
string logFolder = Path.Combine(storageFolder.Path, MainPage.LogFolder);
var filename = Path.Combine(MainPage.LogFolder, time + ".log");
if (!Directory.Exists(logFolder)) {
Directory.CreateDirectory(logFolder);
}
this.logger = new Logger(filename);
this.SentRequest += this.OnRequestSent;
this.EnterPressed += this.OnEnterPressed;
Application.Current.Resources["ToggleButtonBackgroundChecked"] = new SolidColorBrush(Colors.Transparent);
Application.Current.Resources["ToggleButtonBackgroundCheckedPointerOver"] = new SolidColorBrush(Colors.Transparent);
Application.Current.Resources["ToggleButtonBackgroundCheckedPressed"] = new SolidColorBrush(Colors.Transparent);
LoadSavedData(); // Load the previous skype name
InitHttpClient(); // Initialize http client to make api calls
availableDoctorTimer.Interval = this.doctorTimerInterval;
availableDoctorTimer.Tick += QueryAvailableDoctors;
availableDoctorTimer.Start();
QueryAvailableDoctors(null, null); // Initial query for available doctors
}
/// <summary>
/// Initializes the base url to connect to the server
/// </summary>
private void InitHttpClient()
{
this.httpClient = new HttpClient
{
BaseAddress = new Uri("https://481patientnet.com:3001")
};
this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MainPage.ContentType));
this.httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
}
/// <summary>
/// Returns the number of doctors available to service an EMT's request
/// </summary>
private async void QueryAvailableDoctors(object sender, object e)
{
this.logger.Log("Querying available doctors");
// Send empty content
HttpContent content = new StringContent(string.Empty, Encoding.UTF8, MainPage.ContentType);
HttpResponseMessage response = null;
try
{
response = await this.httpClient.PostAsync(this.httpClient.BaseAddress + AvailableDoctorsEndpoint, content);
}
catch (HttpRequestException ex) {
this.logger.Log("QueryAvailableDoctors: While querying for available doctors, got exception: " + ex.Message);
}
// API Call
if (response != null && response.IsSuccessStatusCode)
{
this.logger.Log(response.Content.ReadAsStringAsync().Result);
var responseBody = response.Content.ReadAsStringAsync().Result;
JObject s = JObject.Parse(responseBody);
int numAvailableDoctors = (int)s["availabledoctors"];
AvailableDoctors.Text = $"Available Doctors: {numAvailableDoctors}";
}
else
{
this.logger.Log("QueryAvailableDoctors: When querying for available doctors, did not get a success message.");
}
}
/// <summary>
/// Auto-populates the skype name box with the last name entered
/// </summary>
private async void LoadSavedData()
{
try
{
StorageFile storageFile = await this.storageFolder.GetFileAsync(MainPage.skypeNameFile);
SkypeName.Text = await FileIO.ReadTextAsync(storageFile);
this.logger.Log($"LoadSavedData: Found {skypeNameFile} in path {ApplicationData.Current.LocalFolder.Path}");
}
catch (FileNotFoundException)
{
this.logger.Log($"LoadSavedData: Did not find {skypeNameFile} in path {ApplicationData.Current.LocalFolder.Path}");
}
}
/// <summary>
/// Used to send skype names, phone numbers, and email addresses
/// </summary>
private async void SendHTTP(string endpoint, Dictionary<MessageType, string> sendTypes)
{
if (string.IsNullOrWhiteSpace(endpoint))
{
throw new ArgumentNullException(nameof(endpoint));
}
string title = "Request Doctors";
string success_message_both = "Successfully Notified Emergency Contact and Doctors";
string success_message_contact = "Successfully Notified Emergency Contact";
string success_message_doctor = "Successfully Notified Doctors";
string success_message;
try
{
string info;
string emailString = "email";
string skypeString = "skypeid";
string numberString = "number";
bool contains_email = sendTypes.ContainsKey(MessageType.Email);
bool contains_skype = sendTypes.ContainsKey(MessageType.Skype);
bool contains_number = sendTypes.ContainsKey(MessageType.Number);
if (sendTypes.Count == 1 && contains_skype)
{
info = $"{{ \"{skypeString}\": \"{sendTypes[MessageType.Skype]}\" }}";
success_message = success_message_doctor;
}
else if (sendTypes.Count == 2)
{
if (contains_email && contains_skype)
{
info = $"{{ \"{emailString}\": \"{sendTypes[MessageType.Email]}\", \"{skypeString}\": \"{sendTypes[MessageType.Skype]}\" }}";
success_message = success_message_both;
}
else if (contains_number && contains_skype)
{
info = $"{{ \"{numberString}\": \"{sendTypes[MessageType.Number]}\", \"{skypeString}\": \"{sendTypes[MessageType.Skype]}\" }}";
success_message = success_message_both;
}
else // information is only for emergency contact
{
info = $"{{ \"{numberString}\": \"{sendTypes[MessageType.Number]}\", \"{emailString}\": \"{sendTypes[MessageType.Email]}\" }}";
success_message = success_message_contact;
}
}
else if (sendTypes.Count == 3)
{
info = $"{{ \"{numberString}\": \"{sendTypes[MessageType.Number]}\", \"{emailString}\": \"{sendTypes[MessageType.Email]}\", \"{skypeString}\": \"{sendTypes[MessageType.Skype]}\" }}";
success_message = success_message_both;
}
else // sanity check
{
return;
}
HttpContent content = new StringContent(info, Encoding.UTF8, MainPage.ContentType);
this.logger.Log("Sending " + info + " to " + endpoint);
HttpResponseMessage response = await this.httpClient.PostAsync(this.httpClient.BaseAddress + endpoint, content);
if (response.IsSuccessStatusCode)
{
NotifyUser($"{title}: {success_message}");
// Save Skype name for future use
StorageFile storageFile = await this.storageFolder.CreateFileAsync(MainPage.skypeNameFile, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(storageFile, sendTypes[MessageType.Skype]);
this.logger.Log($"SendHTTP: Wrote to {skypeNameFile} in path {ApplicationData.Current.LocalFolder.Path}");
}
else
{
NotifyUser($"{title}: Unsuccessful. Please try again.");
}
}
catch (Exception ex)
{
this.logger.Log($"SendHTTP: Got exception: {ex.Message}");
}
}
/// <summary>
/// Prevents the HoloLens' click-twice anomaly
/// </summary>
private async void OnRequestSent(object sender, RequestEventArgs e)
{
e.Set.Add(e.Content);
// Disallow sending again for 1 second (debouncer)
await Task.Delay(MainPage.SleepTimeInMilliseconds);
e.Set.Remove(e.Content);
this.logger.Log($"OnRequestSent: Removed {e.Content} from {nameof(e.Set)}");
}
/// <summary>
/// Prevents the HoloLens' click-twice anomaly
/// </summary>
private async void OnEnterPressed(object sender, EnterEventArgs e)
{
this.entersPressed.Add(e.Type);
// Disallow pressing enter again for 1 second (debouncer)
await Task.Delay(MainPage.SleepTimeInMilliseconds);
this.entersPressed.Remove(e.Type);
this.logger.Log($"OnEnterPressed: Removed {e.Type} from entersPressed set");
}
/// <summary>
/// Handles when the EMT clicks the submit button
/// </summary>
private void RequestDoctors_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(SkypeName.Text))
{
NotifyUser("Please enter a skype name.");
return;
}
string phoneNumber = Phone.Text;
string email = Email.Text;
string skypeName = SkypeName.Text;
Dictionary<MessageType, string> sendTypes = new Dictionary<MessageType, string>();
// Handling Phone Number
if (!string.IsNullOrWhiteSpace(phoneNumber))
{
if (phoneNumber.Length != MainPage.FormattedPhoneLength)
{
NotifyUser($"Invalid Number. Please try again.");
return;
}
else if (this.numbersSentTo.Contains(phoneNumber))
{
this.logger.Log($"Recently sent to {phoneNumber}. Skipping.");
return; // Don't do anything
}
// Add phone number to set of numbers
this.logger.Log($"Adding {phoneNumber} to {this.numbersSentTo}");
SentRequest.Invoke(this, new RequestEventArgs(this.numbersSentTo, phoneNumber));
sendTypes.Add(MessageType.Number, phoneNumber);
}
// Handling Email
if (!string.IsNullOrWhiteSpace(email))
{
if (this.emailsSentTo.Contains(email))
{
this.logger.Log($"Recently sent to {email}. Skipping.");
return; // Don't do anything
}
// Add email to set of emails
this.logger.Log($"Adding {email} to {this.emailsSentTo}");
SentRequest.Invoke(this, new RequestEventArgs(this.emailsSentTo, email));
sendTypes.Add(MessageType.Email, email);
}
// Handle sending skype name twice
if (this.skypesSentTo.Contains(skypeName))
{
this.logger.Log($"Recently sent to {skypeName}. Skipping.");
return; // Don't do anything
}
// Add skype name to set of skypes
this.logger.Log($"Adding {skypeName} to {nameof(this.skypesSentTo)}");
SentRequest.Invoke(this, new RequestEventArgs(this.skypesSentTo, skypeName));
sendTypes.Add(MessageType.Skype, skypeName);
// Sending HTTP Request containing all non-empty parameters
try
{
string endpoint = RequestDoctorsEndpoint;
SendHTTP(endpoint, sendTypes); // TODO: NEED TO CHANGE SendHTTP INTERFACE
}
catch (Exception ex)
{
this.logger.Log($"Error: when notifying contact, got exception: {ex.Message}");
NotifyUser($"Error notifying contact: {ex.Message}");
}
}
/// <summary>
/// Prevents the HoloLens' click-twice anomaly
/// </summary>
private void Skype_KeyDownHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
// Protect against enter registering twice
if (this.entersPressed.Contains(MessageType.Skype))
{
return;
}
Phone.Focus(FocusState.Pointer);
this.logger.Log("Focusing on Phone!");
this.EnterPressed.Invoke(this, new EnterEventArgs(MessageType.Number));
}
}
/// <summary>
/// Prevents the HoloLens' click-twice anomaly
/// </summary>
private void Phone_KeyDownHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
// Protect against enter registering twice
if (this.entersPressed.Contains(MessageType.Number))
{
return;
}
Email.Focus(FocusState.Pointer);
this.logger.Log("Focusing on Email!");
this.EnterPressed.Invoke(this, new EnterEventArgs(MessageType.Email));
}
}
/// <summary>
/// Prevents the HoloLens' click-twice anomaly
/// </summary>
private void Email_KeyDownHandler(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
// Protect against enter registering twice
if (this.entersPressed.Contains(MessageType.Email))
{
return;
}
RequestDoctors_Click(sender, e);
}
}
private void PhoneNumberFormatter(TextBox textBox, bool insert)
{
string value = textBox.Text;
var oldSelectionStart = textBox.SelectionStart;
value = new Regex(@"\D").Replace(value, string.Empty);
if (string.IsNullOrEmpty(value))
{
// Do nothing
}
else if (value.Length < 4)
{
value = string.Format("({0}", value.Substring(0, value.Length));
}
else if (value.Length < 7)
{
value = string.Format("({0}){1}", value.Substring(0, 3), value.Substring(3, value.Length - 3));
}
else if (value.Length < 11)
{
value = string.Format("({0}){1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
}
else
{
value = value.Remove(value.Length - 1, 1);
value = string.Format("({0}){1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
}
textBox.Text = value;
if (insert)
{
// Move cursor over to account for phone format character
if (oldSelectionStart == 1 || oldSelectionStart == 5 || oldSelectionStart == 9)
{
++oldSelectionStart;
}
}
else
{
// Move cursor behind phone format character
if (oldSelectionStart == 5 || oldSelectionStart == 9)
{
--oldSelectionStart;
}
}
textBox.SelectionStart = oldSelectionStart;
}
/// <summary>
/// Calls the phone string formatter whenever a user enters text
/// </summary>
private void Phone_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
bool insert = textBox.Text.Length > oldPhoneLength;
PhoneNumberFormatter(textBox, insert);
oldPhoneLength = textBox.Text.Length;
}
/// <summary>
/// Displays user help information when Skype name textbox is clicked
/// </summary>
private void SkypeName_GotFocus(object sender, RoutedEventArgs e)
{
this.skypeFocused = true;
UserHelpSkype.Visibility = Visibility.Visible;
}
/// <summary>
/// Hides user help information when cursor is removed from Skype name textbox
/// </summary>
private void SkypeName_LostFocus(object sender, RoutedEventArgs e)
{
this.skypeFocused = false;
if (!this.helpOn)
{
UserHelpSkype.Visibility = Visibility.Collapsed;
}
}
/// <summary>
/// Displays user help information when phone or email textbox are clicked
/// </summary>
private void Contact_GotFocus(object sender, RoutedEventArgs e)
{
this.contactFocused = true;
UserHelpContact.Visibility = Visibility.Visible;
}
/// <summary>
/// Hides user help information when cursor is removed from phone or email textbox
/// </summary>
private void Contact_LostFocus(object sender, RoutedEventArgs e)
{
this.contactFocused = false;
if (!this.helpOn)
{
UserHelpContact.Visibility = Visibility.Collapsed;
}
}
/// <summary>
/// Displays user help information when cursor hovers over phone or email textbox
/// </summary>
private void Contact_PointerEntered(object sender, PointerRoutedEventArgs e)
{
UserHelpContact.Visibility = Visibility.Visible;
}
/// <summary>
/// Hides user help information when cursor is removed from phone or email textbox
/// </summary>
private void Contact_PointerExited(object sender, PointerRoutedEventArgs e)
{
if (!(this.helpOn || contactFocused))
{
UserHelpContact.Visibility = Visibility.Collapsed;
}
}
/// <summary>
/// Displays user help information when cursor hovers over Skype name textbox
/// </summary>
private void SkypeName_PointerEntered(object sender, PointerRoutedEventArgs e)
{
UserHelpSkype.Visibility = Visibility.Visible;
}
/// <summary>
/// Hides user help information when cursor is removed from Skype name textbox
/// </summary>
private void SkypeName_PointerExited(object sender, PointerRoutedEventArgs e)
{
if (!(this.helpOn || skypeFocused))
{
UserHelpSkype.Visibility = Visibility.Collapsed;
}
}
/// <summary>
/// Toggles the help menu when the help icon is clicked
/// </summary>
private void HelpButtonClicked(object sender, RoutedEventArgs e)
{
if ((bool)this.HelpButton.IsChecked)
{
StepOne.Visibility = Visibility.Visible;
StepTwo.Visibility = Visibility.Visible;
StepThree.Visibility = Visibility.Visible;
UserHelpSkype.Visibility = Visibility.Visible;
UserHelpContact.Visibility = Visibility.Visible;
this.helpOn = true;
}
else
{
StepOne.Visibility = Visibility.Collapsed;
StepTwo.Visibility = Visibility.Collapsed;
StepThree.Visibility = Visibility.Collapsed;
UserHelpSkype.Visibility = Visibility.Collapsed;
UserHelpContact.Visibility = Visibility.Collapsed;
this.helpOn = false;
}
}
private void FontButtonClicked(object sender, RoutedEventArgs e)
{
// Toggle size
this.textSize = this.textSize == TextSize.Small ? TextSize.Large : TextSize.Small;
// Apply new size to all text
StepOne.FontSize = StepTwo.FontSize = StepThree.FontSize = (double)this.textSize;
UserNotifications.FontSize = UserHelpContact.FontSize = UserHelpSkype.FontSize = (double)this.textSize;
EmailHeader.FontSize = SkypeHeader.FontSize = PhoneHeader.FontSize = (double)this.textSize;
EmailHeader.Height = SkypeHeader.Height = PhoneHeader.Height = this.textSize == TextSize.Small ? 20 : 30;
RequestHelp.FontSize = AvailableDoctors.FontSize = (double)this.textSize;
}
/// <summary>
/// Notifies the user using the Usernotifications textbox
/// </summary>
private async void NotifyUser(string content)
{
UserNotifications.Text = content;
await Task.Delay(3000);
// Clear text if notification did not change in the past three seconds
if (UserNotifications.Text == content)
{
UserNotifications.Text = string.Empty;
}
}
}
}
<file_sep>namespace PatientNet
{
using System;
using System.Collections.Generic;
public class RequestEventArgs : EventArgs
{
public RequestEventArgs(HashSet<string> set_, string content_)
{
this.Set = set_;
this.Content = content_;
}
public HashSet<string> Set { get; }
public string Content { get; }
}
}
|
5d810b09994bb4be21683ef310e2e566ebde70b4
|
[
"JavaScript",
"C#",
"Markdown"
] | 7
|
JavaScript
|
azhu7/PatientNet
|
9213da4de2a4c32c07698eb82397e9df42879e49
|
f61823476c2bcbd83b447fe342c52cd3a6897ecc
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'featuredranking',
templateUrl: './featuredranking.component.html',
styleUrls: ['./featuredranking.component.css']
})
export class FeaturedrankingComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CountrysnapshotsComponent } from './countrysnapshots/countrysnapshots.component';
import { SectorsnapshotsComponent } from './sectorsnapshots/sectorsnapshots.component';
import { RegionsnapshotsComponent } from './regionsnapshots/regionsnapshots.component';
import { FeaturedrankingComponent } from './featuredranking/featuredranking.component';
@NgModule({
declarations: [
AppComponent,
CountrysnapshotsComponent,
SectorsnapshotsComponent,
RegionsnapshotsComponent,
FeaturedrankingComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component,ElementRef,ViewChild } from '@angular/core';
@Component({
selector: 'ppisnapshots',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
snapshots:string;
constructor(private element: ElementRef){
this.snapshots = this.element.nativeElement.getAttribute('snapshots');
}
title = 'ppisnapshots';
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'sectorsnapshots',
templateUrl: './sectorsnapshots.component.html',
styleUrls: ['./sectorsnapshots.component.css']
})
export class SectorsnapshotsComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
|
cdc9dbd507303cc19495a2b7ec0d992a9a72c9f6
|
[
"TypeScript"
] | 4
|
TypeScript
|
ssiva44/ppisnapshots
|
21b9140b71d7ed03487620cf75f7b81e699aae3a
|
de3b4fa14f1c640f8cea6ff09a109b2cb237738c
|
refs/heads/master
|
<repo_name>amalalex/algorithms<file_sep>/README.md
# algorithms
Algorithms Samples in Java & JEE
<file_sep>/src/main/java/Library.java
/*
* This Java source file was auto generated by running 'gradle buildInit --type java-library'
* by 'amalalex' at '3/27/16 10:39 PM' with Gradle 2.7
*
* @author amalalex, @date 3/27/16 10:39 PM
*/
public class Library {
public boolean someLibraryMethod() {
return true;
}
}
|
fd135b8aebfc74cd950d788cd906ce56505f7415
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
amalalex/algorithms
|
4f2249590d2ff0b6f52a63fae1e6a5ab687d74c6
|
0e7505880f5c455842c7276174a8bf9cf2925759
|
refs/heads/main
|
<repo_name>Yoha202030086/DamasChinas-<file_sep>/src/tablero/Ficha.java
package src.tablero;
public class Ficha {
private boolean esColor;
public Ficha(boolean esColor){
this.esColor = esColor;
}
}
<file_sep>/src/tablero/Celda.java
package src.tablero;
public class Celda {
private boolean esColor;
private Ficha ficha;
private char celda = (char) 178;
private char celdaColor = (char) 177;
public Celda(boolean esColor){
this.esColor = esColor;
this.ficha = null;
}
public String pintarCelda( int linea) {
String res = "";
if(esColor){
res = celdaColor+celdaColor+celdaColor+celdaColor+"";
}
else{
res = celda+celda+celda+celda+"";
}
return res;
}
}
|
6409c4747557adfe49a4311b3e68f40457ff54bb
|
[
"Java"
] | 2
|
Java
|
Yoha202030086/DamasChinas-
|
5b85b83e7dcb94ccc65f31253df619ac8411701a
|
d2f1f9aa00ea13a498a1fa240846989fb050dcbc
|
refs/heads/master
|
<file_sep># About this Repo
[](https://travis-ci.org/anaxexp/base-php)
[](https://hub.docker.com/r/anaxexp/base-php)
[](https://hub.docker.com/r/anaxexp/base-php)
[](https://microbadger.com/images/anaxexp/base-php)
This repository is a fork of https://github.com/docker-library/php with a few changes:
* We build only Alpine FPM variants
* Built with LibreSSL instead of OpenSSL
* Additional debug variants of images with --enable-debug and non-stripped bins
* Legacy PHP 5.3 variant
## Docker Images
* All images are based on Alpine Linux 3.7 (except legacy 5.3 on Alpine 3.4)
* Base image: [anaxexp/alpine](https://github.com/anaxexp/alpine)
* [Travis CI builds](https://travis-ci.org/anaxexp/base-php)
* [Docker Hub](https://hub.docker.com/r/anaxexp/base-php)
[_(Dockerfile 7.2)_]: https://github.com/anaxexp/base-php/tree/master/7.2/alpine3.7/fpm/Dockerfile.anaxexp
[_(Dockerfile 7.1)_]: https://github.com/anaxexp/base-php/tree/master/7.1/alpine3.7/fpm/Dockerfile.anaxexp
[_(Dockerfile 7.0)_]: https://github.com/anaxexp/base-php/tree/master/7.0/alpine3.7/fpm/Dockerfile.anaxexp
[_(Dockerfile 5.6)_]: https://github.com/anaxexp/base-php/tree/master/5.6/alpine3.7/fpm/Dockerfile.anaxexp
[_(Dockerfile 5.3)_]: https://github.com/anaxexp/base-php/tree/master/5.3/alpine3.4/fpm/Dockerfile.anaxexp
Supported tags and respective `Dockerfile` links:
* `7.2.9`, `7.2`, `7`, `latest` [_(Dockerfile 7.2)_]
* `7.1.20`, `7.1` [_(Dockerfile 7.1)_]
* `7.0.31`, `7.0` [_(Dockerfile 7.0)_]
* `5.6.37`, `5.6`, `5` [_(Dockerfile 5.6)_]
* `5.3.29`, `5.3` [_(Dockerfile 5.3)_]
* `7.2.9-debug`, `7.2-debug`, `7-debug` [_(Dockerfile 7.2)_]
* `7.1.20-debug`, `7.1-debug` [_(Dockerfile 7.1)_]
* `7.0.31-debug`, `7.0-debug` [_(Dockerfile 7.0)_]
* `5.6.37-debug`, `5.6-debug`, `5-debug` [_(Dockerfile 5.6)_]
## Image with more PHP extensions and orchestration actions
See https://github.com/anaxexp/php
<file_sep>#!/bin/bash
set -e
cp Dockerfile-alpine.template tmp
# Change basic image.
sed -i '/FROM alpine/i\ARG BASE_IMAGE_TAG\n' tmp
sed -i '/FROM alpine/a\\nARG PHP_DEBUG' tmp
sed -i 's/FROM alpine.*/FROM anaxexp\/alpine:${BASE_IMAGE_TAG}/' tmp
# For -debug images.
sed -i -E "s/\&\&(.+?-exec strip.+)/\1/" tmp
sed -i '/exec strip/i\ && if [[ \$PHP_DEBUG != 1 ]]; then \\' tmp
sed -i '/exec strip/a\ fi \\' tmp
sed -i '/\$PHP_EXTRA_CONFIGURE_ARGS/i\ $(test "${PHP_DEBUG}" = 1 && echo '"'"'--enable-debug'"'"') \\' tmp
mv tmp Dockerfile-alpine.anaxexp.template
cp update.sh tmp
# Exclude 7.3-rc, 5.3
sed -i '/versions=( "${versions\[@\]%\/}" )/a\
delete=(5.3 7.3-rc) \
for target in "${delete[@]}"; do \
for i in "${!versions[@]}"; do \
if [[ ${versions[i]} = "${target}" ]]; then \
unset versions[i] \
fi \
done \
done' tmp
# Use our template for fmp alpine variants.
sed -i 's/Dockerfile-alpine.template/Dockerfile-alpine.anaxexp.template/' tmp
sed -i -E 's/stretch jessie alpine.+?\;/alpine3.7;/' tmp
sed -i 's/cli apache fpm zts/fpm/' tmp
sed -i 's/\/Dockerfile"/\/Dockerfile.anaxexp"/' tmp
# Change .travis.yml modifications.
sed -i -E 's/^(echo "\$travis.*)/#\1/' tmp
sed -i '/fullVersion=/a\ sed -i -E "s/(PHP$majorVersion$minorVersion)=.*/\\1=$fullVersion/" .travis.yml\n' tmp
# Update README.
sed -i '/fullVersion=/a\ sed -i -E "s/\\`$majorVersion\.$minorVersion\.[0-9]+\\`/\\`$fullVersion\\`/" README.md' tmp
sed -i '/fullVersion=/a\\n sed -i -E "s/\\`$majorVersion\.$minorVersion\.[0-9]+-debug\\`/\\`$fullVersion-debug\\`/" README.md' tmp
mv tmp update.anaxexp.sh
./update.anaxexp.sh
rm Dockerfile-alpine.anaxexp.template
rm update.anaxexp.sh
|
49c63c8b33482b44bb1af2fb0c6c359d97e990c9
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
anaxexp/base-php
|
dfbd8701f9b27d4eab111caa6ca2324ac0660971
|
b3d77f9efe1f3fab770914421ee5e873378f860d
|
refs/heads/master
|
<repo_name>marshi23/js-adagrams<file_sep>/src/adagrams.js
const Adagrams = {
drawLetters() {
let letterDistribution = [
'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
'B', 'B',
'C', 'C',
'D', 'D', 'D', 'D',
'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E',
'F', 'F',
'G', 'G', 'G',
'H', 'H',
'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I', 'I',
'J',
'K',
'L', 'L', 'L', 'L',
'M', 'M',
'N', 'N', 'N', 'N', 'N', 'N',
'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
'P', 'P',
'Q',
'R', 'R', 'R', 'R', 'R', 'R',
'S', 'S', 'S', 'S',
'T', 'T', 'T', 'T', 'T', 'T',
'U', 'U', 'U', 'U',
'V', 'V',
'W', 'W',
'X',
'Y', 'Y',
'Z'
];
let random = function(items) {
return items[Math.floor(Math.random()*items.length)];
}
let drawn = [];
for (let i = 0; i < 10; i++) {
let letter = random(letterDistribution);
drawn.push(letter)
}
return drawn
},
usesAvailableLetters(input, lettersInHand) {
let result = true
let letters_array = input.toUpperCase().split('')
letters_array.forEach(function(letter) {
if (!lettersInHand.includes(letter)) {
result = false;
} else {
let index_2 = lettersInHand.indexOf(letter)
lettersInHand.splice(index_2, 1);
}
});
return result;
},
scoreWord(word) {
const scoreChart = {
"A" : 1,
"B" : 3,
"C" : 3,
"D" : 2,
"E" : 1,
"F" : 4,
"G" : 2,
"H" : 4,
"I" : 1,
"J" : 8,
"K" : 5,
"L" : 1,
"M" : 3,
"N" : 1,
"O" : 1,
"P" : 3,
"Q" : 10,
"R" : 1,
"S" : 1,
"T" : 1,
"U" : 1,
"V" : 4,
"W" : 4,
"X" : 8,
"Y" : 4,
"Z" : 10,
};
let score = 0;
if (word.length > 6) {
score += 8;
}
let letters = word.toUpperCase().split('')
letters.forEach(function(letter) {
if (scoreChart[letter]) {
score += scoreChart[letter]
} else {
console.log("Letter does not exits")
}
});
return score;
},
highestScoreFrom(words) {
let highestScoringWord = {
word: '',
score: 0
};
// console.log(words)
for (let word of words) {
let score = this.scoreWord(word);
// console.log(word)
// console.log(score)
if (score > highestScoringWord.score) {
highestScoringWord.score = score;
highestScoringWord.word = word;
} else if (score == highestScoringWord.score) {
if (word.length == 10 && highestScoringWord.word.length != 10) {
highestScoringWord.score = score;
highestScoringWord.word = word;
} else if (word.length < highestScoringWord.word.length && highestScoringWord.word.length != 10) {
highestScoringWord.score = score;
highestScoringWord.word = word;
}
}
}
return highestScoringWord;
},
};
// Do not remove this line or your tests will break!
export default Adagrams;
|
1dfe32c63fa73cc4118d2d49b858bc5959784ae3
|
[
"JavaScript"
] | 1
|
JavaScript
|
marshi23/js-adagrams
|
67e753cd34aefdde2491a6cf07de3ed00fce7ee6
|
46fe83cc50b2838d7839ecc69729f5bd6726bd96
|
refs/heads/main
|
<file_sep>a=set(input("Dati un sir A: "))
b=set(input("Dati un sir B: "))
print("Caractere ce se intilnesc cel putin o singura data:", a.union(b))
print("Intersectia:", a.intersection(b))
print("Apar in A si nu in B:", a.difference(b))
|
a22445c30297d166d8e15301d4e68e5c76ce575d
|
[
"Python"
] | 1
|
Python
|
loredana-stirbu/Tipul_De_date_Multimi
|
d2b1aa72d5ac251be5aca30a4abd8e5bb25e2dbb
|
50865929e53798abe7ee419c5cd712901ee83096
|
refs/heads/master
|
<file_sep>import pandas as pd
import numpy as np
import math
def response_outlier_capping(df, variable, multiplier):
''' windsorise the response variable '''
q1 = np.percentile(df[variable],25)
q3 = np.percentile(df[variable],75)
iqr = q3 - q1
lower = q1 - (iqr * multiplier)
upper = q3 + (iqr * multiplier)
df[variable] = np.where(df[variable]<=lower, lower, df[variable])
df[variable] = np.where(df[variable]>=upper, upper, df[variable])
return df
def log_response(df, response):
''' take the natural log of the response variable '''
print('Skewness of untransformed response:\t' + str(df[response].skew()))
# transform response column to ensure +ve
minimum_val = math.ceil(min(abs(np.log(df[response]))))
original_data = np.log(df[response]) + minimum_val
df[response] = np.log(df[response])
print('Skewness of transformed response:\t' + str(df[response].skew()))
return df
def predictors_one_hot_encoding(df):
''' one hot encode categorical features '''
# find all relevant columns
all_columns = list(df.columns)
numeric_types = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64', 'uint8']
numeric_columns = df.select_dtypes(include=numeric_types).columns.to_list()
categoric_columns = list(set(all_columns) - set(numeric_columns))
for i in categoric_columns:
one_hot = pd.get_dummies(df[i], prefix=i)
df = df.join(one_hot)
# remove categoric cols
numeric_columns = df.select_dtypes(include=numeric_types).columns.to_list()
df = df[numeric_columns]
return df
def exp_response(df, response):
''' transform the response variable back to original'''
df[response] = np.exp(df[response])
def find_numerics(df):
''' searches a dataframe and returns numeric columns (excluding id cols)'''
# numeric data types
numeric_dtype = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
# define all numeric cols
all_numeric_columns = list(df.select_dtypes(include=numeric_dtype).columns)
id_columns = ['id', 'loss']
# define all numeric cols excluding id cols
numeric_columns = list(set(all_numeric_columns) - set(id_columns))
return numeric_columns
def store_scaling_values(df):
''' stores mean and std values '''
# load numeric features to be scaled
numeric_columns=find_numerics(df)
# create dataframe with stored values
scaling_df = pd.DataFrame([p, df[p].mean(), df[p].std()] for p in numeric_columns)
scaling_df.columns = ['col', 'mean', 'std']
# save the values
scaling_df.to_csv('outputs/scaling.csv', index=False)
def scale_numerics(df):
''' read the scaled values and convert numeric features '''
# read the scaled values
scaling_df = pd.read_csv('outputs/scaling.csv')
# scale columns
for i in range(scaling_df.shape[0]):
col = scaling_df.iloc[i][0]
mean = scaling_df.iloc[i][1]
std = scaling_df.iloc[i][2]
df[col] = (df[col] - mean) / std
<file_sep>from concurrent.futures import ThreadPoolExecutor
from time import strftime, gmtime
from data import load_data
from data_partitioning import training_validation_subset
from data_transformation import response_outlier_capping, log_response, predictors_one_hot_encoding, \
store_scaling_values, scale_numerics
from modelling import bayes_cv_tuner, status_print, save_model
from prediction import scores_and_fe, predict_test
# hardcoded settings
current_time = strftime("%Y%m%d%H%M%S", gmtime())
with ThreadPoolExecutor (max_workers=64) as executor:
# load data
training_df, test_df = load_data()
print('dataset loaded...')
# data partitioning
training_df, validation_df=training_validation_subset(training_df)
print('dataset partitioned...')
# encode features
training_df=predictors_one_hot_encoding(training_df)
training_df=response_outlier_capping(training_df, 'loss', 2.2)
training_df=log_response(training_df, 'loss')
store_scaling_values(training_df)
scale_numerics(training_df)
print('dataset encoded...')
# feature set
X=training_df.drop(['id', 'loss'], axis=1)
y=training_df['loss']
print('feature set selected...')
# fit (and save) the model
xgb_bo = bayes_cv_tuner.fit(X, y, callback=status_print)
save_model(xgb_bo.best_estimator_,current_time)
print('modelling complete...')
# scores and feature importance
scores_and_fe(X, y, training_df, validation_df, xgb_bo.best_estimator_, current_time)
print('modelling scores created...')
# predict on test dataset
predict_test(training_df, test_df, xgb_bo.best_estimator_, current_time)
print('predictions complete...')<file_sep>import pandas as pd
def load_data():
''' read train and test datasets '''
training_df = pd.read_csv('/Users/Ben/Desktop/optimal_decision_trees/data/modelling.csv')
holdout_df=pd.read_csv('/Users/Ben/Desktop/optimal_decision_trees/data/holdout.csv')
test_df=pd.read_csv('/Users/Ben/Desktop/optimal_decision_trees/data/test.csv')
return training_df, holdout_df, test_df<file_sep>import pandas as pd
def training_validation_subset(df):
''' function to create training and validation subsets
chosen this methodology as a method to replicate in the future '''
training_df = df.sample(frac=0.7)
print('Training dataset rows:\t', training_df.shape[0])
validation_df = pd.concat([df, training_df]).drop_duplicates(keep=False)
print('Validation dataset rows:\t', validation_df.shape[0])
return training_df, validation_df<file_sep>import pandas as pd
import numpy as np
import xgboost as xgb
import pickle
# import sklearn2pmml
from skopt import BayesSearchCV
from sklearn.model_selection import KFold
# Hardcoded settings
ITERATIONS = 10 # 1000
# Regressor
bayes_cv_tuner = BayesSearchCV(
estimator=xgb.XGBRegressor(
n_jobs=1,
objective='reg:linear',
eval_metric='mae',
silent=1,
tree_method='approx'
),
search_spaces={
'learning_rate': (0.01, 1.0, 'log-uniform'),
'min_child_weight': (0, 10),
'max_depth': (0, 50),
'max_delta_step': (0, 20),
'subsample': (0.01, 1.0, 'uniform'),
'colsample_bytree': (0.01, 1.0, 'uniform'),
'colsample_bylevel': (0.01, 1.0, 'uniform'),
#'reg_lambda': (1e-9, 1000, 'log-uniform'),
'reg_alpha': (1e-9, 1.0, 'log-uniform'),
'gamma': (1e-9, 1.0, 'log-uniform'),
'min_child_weight': (0, 5),
'n_estimators': (50, 100)
# 'scale_pos_weight': (1e-6, 500, 'log-uniform')
},
scoring='neg_mean_absolute_error',
cv=KFold(n_splits=5,
random_state=None,
shuffle=False),
n_jobs=3,
n_iter=ITERATIONS,
verbose=0,
refit=True,
random_state=42
)
def status_print(optim_result):
''' status callback during bayesian hyperparameter search '''
# Get all the models tested so far in DataFrame format
all_models = pd.DataFrame(bayes_cv_tuner.cv_results_)
# Get current parameters and the best parameters
best_params = pd.Series(bayes_cv_tuner.best_params_)
print('Model #{}\nBest Result: {}\nBest params: {}\n'.format(
len(all_models),
np.round(bayes_cv_tuner.best_score_, 4),
bayes_cv_tuner.best_params_
))
# Save all model results
clf_name = bayes_cv_tuner.estimator.__class__.__name__
all_models.to_csv(f'outputs/' + clf_name + "_cv_results.csv")
def save_model(model, current_time):
''' pickle and save as pmml '''
# pickle
pickle.dump(model, open(f'outputs/model_{current_time}.sav', 'wb'))
# # pmml
# pmml_object=sklearn2pmml.make_pmml_pipeline(model)
# sklearn2pmml.sklearn2pmml(pmml_object, f'outputs/model_{current_time}.pmml.xml')<file_sep>
## Objective
To investigate the performance of GLM, Optimal Decision Trees and XGBoost algorithms on the Allstate Claims Severity Kaggle challenge (https://www.kaggle.com/c/allstate-claims-severity/overview).
## Contents
This repository contains:
- *data* - datasets for the analysis
- *evaluation* - summary statistics
- *glm* - code to build model
- *img* - images
- *notebooks* - workings for learning and development
- *optimal_decision_trees* - code to build model
- *outputs* - results
- *xgb* - code to build model
## Data
Each row in this dataset represents an insurance claim. Variables prefaced with 'cat' are categorical, while those prefaced with 'cont' are continuous. The objective is to predict the value for the 'loss' column. <br>
*train.csv* and *test.csv* datasets are provided for the challenge which contain 188318 and 125546 rows respectively. <br>
In order to develop the models, the *train.csv* dataset has been further partitioned into *modelling.csv* and *holdout.csv* samples where *modelling.csv* contains 160001 rows and *holdout.csv* contains 28317 rows.
An example of the dataset:

## Feature Engineering
Since the objective of this task is to assess the model performance, basic feature engineering methods were employed. In more detail:
- For all models, the response variable was subject to a log transformation and outlier capping. For categorical features with many levels, frequency binning was applied.
- For GLM and ODT models, categorical features were encoded as categoric, however, for the XGBoost model, the features were one-hot encoded.
## Method
Build three models:
- *GLM* - automated build fitting factors using forward selection.
- *XGBoost* - automated model build using XGBoost algorithm with Bayesian Hyper-optimisation.
- *ODT* - tuned as per interpretable.ai user guide with search range from max_depth 1 to 9.
## Results
#### Mean Absolute Error:
For reference, the winning kaggle competition (stacked NN and XGB model) has has a MAE of 1109.71.
- GLM mae result: 1605.18 (2dp)
- GLM kaggle mae result: 1604.37 (2dp)
- ODT mae result: 1298.60 (2dp)
- ODT kaggle mae result: 1291.27 (2dp)
- XGB mae result: 1191.18 (2dp)
- XGB kaggle mae result: 1189.11 (2dp)
#### X-graphs:



#### Gini:

## Conclusions
- ODT significantly outperforms GLM.
- XGB is the most accurate model and reasonably efficient given the time and computation taken to train (c. 3 hours).
- ODT takes considerably longer to tune (c. 6 hours) and is considerably more complex to install.
- Although ODT does not perform as well as XGB, there is a considerable value to the level interpretability which it provides. With this functionality, an interpretability based proposition is plausible which could be useful for certain product lines / brands.
## Future Developments
Developments to improve study:
- additional feature engineering
- modularise code and add orchestration file
- alter ODT code such that it is written in Julia in order to allow for multi-threading
- build XGBoost model on AWS GPU machine
## Author
<NAME> with a special thanks to interpretable.ai for allowing me to trial their interpretableai package for personal use. <br>
Q4 2020<file_sep>import pandas as pd
import numpy as np
from xgboost import plot_importance
from matplotlib import pyplot as plt
from data_transformation import predictors_one_hot_encoding, log_response, exp_response, scale_numerics
from sklearn.metrics import mean_absolute_error
def transform_validation(training_df, test_df):
''' transform to include common factors between train and test '''
training_df = predictors_one_hot_encoding(training_df)
test_df = predictors_one_hot_encoding(test_df)
# As automated, ensure that same cols exist in both
cols = list(set(list(training_df.columns)) - set(list(test_df.columns)))
for i in cols:
test_df[i] = pd.Series([0 for x in range(len(test_df.index))])
df_cols = list(training_df.columns)
test_df = test_df[df_cols]
return test_df
def transform_test(training_df, test_df):
''' transform to include common factors between train and test '''
training_df = predictors_one_hot_encoding(training_df)
test_df = predictors_one_hot_encoding(test_df)
# As automated, ensure that same cols exist in both
cols = list(set(list(training_df.columns)) - set(list(test_df.columns)))
for i in cols:
test_df[i] = pd.Series([0 for x in range(len(test_df.index))])
df_cols = list(training_df.columns)
df_cols.remove('loss')
df_cols.remove('id')
test_df = test_df[df_cols]
scale_numerics(test_df)
return test_df
def scores_and_fe(X_train, y_train, training_df, validation_df, model, current_time):
''' score the trained model and export feature importance plots '''
# performance metrics on train
y_pred=model.predict(X_train)
print('Training:\t', (mean_absolute_error(y_train, y_pred)))
# performance metrics on validation
validation_df = predictors_one_hot_encoding(validation_df)
validation_df = transform_validation(training_df, validation_df)
validation_df['loss'] = np.log(validation_df['loss']) #log_response
scale_numerics(validation_df)
X_valid = validation_df.drop(['id', 'loss'], axis=1)
y_valid = validation_df['loss']
y_test_pred = model.predict(X_valid)
print('Validation:\t', (mean_absolute_error(y_valid, y_test_pred)))
# summarize feature importance
plt.rcParams["figure.figsize"] = (25, 25)
ax = plot_importance(model)
ax.figure.tight_layout()
ax.figure.savefig(f'outputs/feature_importance_{current_time}.png')
def predict_test(training_df, test_df, model, current_time):
''' predict on the test dataset for Kaggle upload '''
# Copy of test_df
df_test = test_df.copy()
# Transform test dataset to the same as train
test_df=transform_test(training_df, test_df)
# Transform for XGB
prediction=model.predict(test_df)
# Aggregate for Kaggle prediction
y_prediction = pd.DataFrame(prediction)
y_out = pd.DataFrame(df_test.id)
y_out = y_out.join(y_prediction)
y_out.columns=['id','loss']
exp_response(y_out, 'loss')
y_out.to_csv(f'outputs/kaggle_xgb_predictions.csv', index=False)
def predict_holdout(training_df, test_df, model, current_time):
''' predict on the test dataset for holdout '''
# Copy of test_df
df_test = test_df.copy()
# Transform test dataset to the same as train
test_df=transform_test(training_df, test_df)
# Transform for XGB
prediction=model.predict(test_df)
# Aggregate for Kaggle prediction
y_prediction = pd.DataFrame(prediction)
y_out = pd.DataFrame(df_test.id)
y_out = y_out.join(y_prediction)
y_out.columns=['id','loss']
exp_response(y_out, 'loss')
y_out.to_csv(f'outputs/holdout_xgb_predictions.csv', index=False)
|
d5156c0ee85f143f94d5564065dbe293a2f2a8a8
|
[
"Markdown",
"Python"
] | 7
|
Python
|
benturner993/optimal_decision_trees
|
2ee67347db602606eafa0279e977c8ca7eed941d
|
b3dad1aa2a59065bd2ee22c1eeb4a89ce66e765c
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine("1. Bài 1");
Console.WriteLine("2. Bài 2");
Console.WriteLine("3. Bài 3");
Console.Write("\n\n\n\n\n\t\t\t\t\nNhập lựa chọn của bạn: ");
String s = Console.ReadLine();
switch (s)
{
case "1":
b1();
break;
case "2":
b2();
break;
case "3":
b3();
break;
}
Console.Clear();
Console.ReadKey();
}
static void b1()
{
Console.WriteLine("1. 1 chiều");
Console.WriteLine("2. 2 chiều");
Console.Write("\n\n\n\n\n\t\t\t\t\nNhập lựa chọn của bạn: ");
String s = Console.ReadLine();
switch (s)
{
case "1":
Console.WriteLine("nhập số phần tử của mảng ");
int so = int.Parse(Console.ReadLine());
int[] arr1 = new int[so];
for (int i = 0; i < so; i++)
{
Console.WriteLine("Phan tu - {0}:", i);
arr1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Các phần tử của mảng :");
for (int i = 0; i < so; i++)
Console.WriteLine("{0} ", arr1[i]);
Console.ReadKey();
break;
case "2":
Console.WriteLine("nhập kích cỡ mảng 2 chiều");
Console.WriteLine("chiều 1");
int c1 = int.Parse(Console.ReadLine());
Console.WriteLine("chiều 2");
int c2 = int.Parse(Console.ReadLine());
int[,] arr2 = new int[c1, c2];
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
Console.WriteLine("Phần tử số {0},{1}", i, j);
arr2[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
Console.WriteLine("phần tử số :[" + i + "][" + j + "] = " + arr2[i, j]);
}
}
Console.ReadKey();
break;
}
}
static void b2()
{
Console.WriteLine("1. 1 chiều");
Console.WriteLine("2. 2 chiều");
Console.Write("\n\n\n\n\n\t\t\t\t\nNhập lựa chọn của bạn: ");
String s = Console.ReadLine();
switch (s)
{
case "1":
Console.WriteLine("nhập số phần tử của mảng ");
int so = int.Parse(Console.ReadLine());
int[] arr1 = new int[so];
Console.WriteLine("Nhập giá trị bé nhất để ngẫu nhiên");
int rmin = int.Parse(Console.ReadLine());
Console.WriteLine("Nhập giá trị lớn nhất để ngẫu nhiên");
int rmax = int.Parse(Console.ReadLine());
Random r = new Random();
for (int i = 0; i < so; i++)
{
int nn = r.Next(rmin, rmax);
Console.WriteLine("Phan tu - {0}: {1}", i, nn);
arr1[i] = nn;
}
Console.WriteLine("Các phần tử của mảng :");
for (int i = 0; i < so; i++)
Console.WriteLine("{0} ", arr1[i]);
Console.ReadKey();
break;
case "2":
Console.WriteLine("nhập kích cỡ mảng 2 chiều");
Console.WriteLine("chiều 1");
int c1 = int.Parse(Console.ReadLine());
Console.WriteLine("chiều 2");
int c2 = int.Parse(Console.ReadLine());
int[,] arr2 = new int[c1, c2];
Console.WriteLine("Nhập giá trị bé nhất để ngẫu nhiên");
int rmin2 = int.Parse(Console.ReadLine());
Console.WriteLine("Nhập giá trị lớn nhất để ngẫu nhiên");
int rmax2 = int.Parse(Console.ReadLine());
Random r2 = new Random();
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
int nn = r2.Next(rmin2, rmax2);
Console.WriteLine("Nhập phần tử - {0}: {1}", i, nn);
arr2[i, j] = nn;
}
}
Console.WriteLine("Mảng cừa được tạo là :");
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
Console.WriteLine("phần tử số :[" + i + "][" + j + "] = " + arr2[i, j]);
}
}
Console.ReadKey();
break;
}
}
static void b3()
{
Console.WriteLine("1. 1 chiều");
Console.WriteLine("2. 2 chiều");
Console.Write("\n\n\n\n\n\t\t\t\t\nNhập lựa chọn của bạn: ");
String s = Console.ReadLine();
switch (s)
{
case "1":
Console.WriteLine("nhập số phần tử của mảng ");
int so = int.Parse(Console.ReadLine());
int[] arr1 = new int[so];
for (int i = 0; i < so; i++)
{
Console.WriteLine("Phan tu - {0}: ", i);
arr1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Các phần tử của mảng :");
for (int i = 0; i < so; i++)
Console.WriteLine("{0} ", arr1[i]);
Console.ReadKey();
int mx = arr1[0];
int mn = arr1[0];
for (int i = 1; i < so; i++)
{
if (arr1[i] > mx)
{
mx = arr1[i];
}
if (arr1[i] < mn)
{
mn = arr1[i];
}
}
Console.Write("Phần tử lớn nhất trong mảng là {0}\n", mx);
Console.Write("Phần tử nhỏ nhất trong mảng là {0}\n", mn);
Console.ReadKey();
break;
case "2":
Console.WriteLine("nhập kích cỡ mảng 2 chiều");
Console.WriteLine("chiều 1");
int c1 = int.Parse(Console.ReadLine());
Console.WriteLine("chiều 2");
int c2 = int.Parse(Console.ReadLine());
int[,] arr2 = new int[c1, c2];
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
Console.WriteLine("Phần tử số {0},{1}", i, j);
arr2[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
Console.WriteLine("phần tử số :[" + i + "][" + j + "] = " + arr2[i, j]);
}
}
Console.ReadKey();
int max = arr2[0,0];
int min = arr2[0,0];
for (int i = 0; i < c1; i++)
{
for (int j = 0; j < c2; j++)
{
if (max < arr2[i, j])
max = arr2[i, j];
if (min > arr2[i, j])
min = arr2[i, j];
}
}
Console.Write("Phần tử lớn nhất trong mảng là {0}\n", max);
Console.Write("Phần tử nhỏ nhất trong mảng là {0}\n", min);
Console.ReadKey();
break;
}
}
}
}
|
17de2c8be791e28828094c3cc5f2576b39465662
|
[
"C#"
] | 1
|
C#
|
alta1212/baitapnopthayhau-27-8
|
94c7907310e893644b4e6d76422be7840b4eb247
|
f7e722296ac3e08eae5d53fdf1ebedc3ac9cfbd7
|
refs/heads/main
|
<repo_name>SiyangXiao/SiyangAlgorithm<file_sep>/src/LeetCode/二分法/sqrtx.java
package LeetCode.二分法;
public class sqrtx {
public static int sqrt(int x){
if(x == 1) return 1;
double i = 0;
double left = 0;
double right = x;
while(left < right - 1){
i = left + (right - left) / 2;
if (i * i > x){
right = i;
}else if (i * i == x){
return (int)i;
}else{
left = i;
}
}
return (int)i;
}
public static void main(String[] args) {
int i = sqrt(100000000);
System.out.println(i);
double a = 31622.9;
System.out.println((int)a);
}
}
<file_sep>/src/LeetCode/Hash/mainElement48.java
package LeetCode.Hash;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* 给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k。
*/
public class mainElement48 {
public int majorityNumber(List<Integer> nums, int k) {
// write your code here
//
HashMap<Integer, Integer> map = new HashMap<>();
int count = nums.size()/k + 1;
Iterator it = nums.iterator();
while(it.hasNext()){
int temp = (int)it.next();
if (map.containsKey(temp)){
int m = (int)map.get(temp) + 1;
map.put(temp, m);
if (m >= count) return temp;
}else{
map.put(temp, 1);
}
}
return 0;
}
public static void main(String[] args) {
List l = new ArrayList();
l.add("aa");
l.add("bb");
l.add("cc");
for (Iterator iter = l.iterator(); iter.hasNext();) {
String str = (String)iter.next();
System.out.println(str);
}
Iterator iter = l.iterator();
while(iter.hasNext()){
String str = (String) iter.next();
System.out.println(str);
}
}
}
<file_sep>/src/LeetCode/链表/linkDevide96.java
package LeetCode.链表;
public class linkDevide96 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode partition(ListNode head, int x) {
// write your code here
if (head == null) return null;
ListNode small = new ListNode(0);
ListNode big = new ListNode(0);
ListNode big0 = big, small0 = small;
while(head != null){
if (head.val < x){
small0.next = head;
small0 = head;
}else{
big0.next = head;
big0 = head;
}
head = head.next;
}
big0.next = null;
small0.next = big.next;
System.out.println(big0 == big);
return small.next;
}
}
<file_sep>/src/LeetCode/分治法/汉诺塔.java
package LeetCode.分治法;
public class 汉诺塔 {
public static void main(String[] args) {
System.out.println(calculate(3));
tower(3, 'a', 'b', 'c');
}
public static double calculate(double layer){
if (layer == 1){
return 1;
}else{
return calculate(layer - 1) * 2 + 1;
}
}
public static void tower(int num, char a, char b, char c){
if (num == 1){
System.out.println(a + " -> " + c);
}else{
tower(num - 1, a, c, b);
System.out.println(+ a + " -> " + c);
tower(num - 1, b, a, c);
}
}
}
<file_sep>/README.md
# SiyangAlgorithm
一些做过的LeetCode题目的代码
<file_sep>/src/LeetCode/排序/中位数_80.java
package LeetCode.排序;
import java.util.Arrays;
/**
* 给定一个未排序的整数数组,找到其中位数。
*
* 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
*/
public class 中位数_80 {
public static void main(String[] args) {
System.out.println(5/2);
}
public static int median(int[] nums){
Arrays.sort(nums);
if (nums.length % 2 == 0) return nums[nums.length / 2 - 1];
return nums[nums.length / 2];
}
}
<file_sep>/src/LeetCode/二分法/SearchRotateQueueArray.java
package LeetCode.二分法;
/**假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,
* 如果在数组中找到目标值返回数组中的索引位置,否则返回-1。你可以假设数组中不存在重复的元素。
*
*/
public class SearchRotateQueueArray {
public int search(int[] A, int target) {
// write your code here
if (A.length == 0) return -1;//empty array
/*if (A.length == 1) {
if (A[0] == target) {
return 0;
}else{
return -1;
}
}*/
//find smallest num
int minposition = 0;
int left = 0;
int right = A.length - 1;
int mid = 0;
while (left + 1 < right){
mid = left + (right - left) / 2;
if (A[mid] > A[right]){
left = mid;
}else{
right = mid;
}
}
if (A[left] < A[right]){
minposition = left;
}else{
minposition = right;
}
//determine which scale target may in
if (A[A.length - 1] < target){
left = 0;
right = minposition - 1;
}else{
left = minposition;
right = A.length - 1;
}
//find position
while (left + 1 < right) {
mid = left + (right - left) / 2;
if (A[mid] > target) {
right = mid;
} else{
left = mid;
}
}
if (A[left] == target) return left;
if (A[right] == target) return right;
return -1;
}
public int search2(int[] A, int target){
if (A == null || A.length == 0) {
return -1;
}
//找到数组最小值位置minPosition,即第二个数组的起始位置
int minPosition = 0;
int left = 0;
int right = A.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (A[mid] > A[right]) {
left = mid;
} else {
right = mid;
}
}
if (A[left] < A[right]) {
minPosition = left;
} else {
minPosition = right;
}
//判断target在哪一个数组中
if (A[A.length - 1] < target) {
left = 0;
right = minPosition - 1;
} else {
left = minPosition;
right = A.length - 1;
}
//对target所在数组二分搜索
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (A[mid] < target) {
left = mid;
} else {
right = mid;
}
}
if (A[left] == target) {
return left;
}
if (A[right] == target) {
return right;
}
return -1;
}
}
|
e77d2b8ebe23f3d36898738341d6c8894c1b0382
|
[
"Markdown",
"Java"
] | 7
|
Java
|
SiyangXiao/SiyangAlgorithm
|
e2dd9a2e374e0f3186c315dc2ac770c15b7d008a
|
1b7ffc7866ab321f7719e45dca62cddb9a22cda9
|
refs/heads/master
|
<repo_name>Prazon/OpenMelee2D<file_sep>/Source/OpenMelee2d/OpenMeleeMath.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "OpenMelee2d.h"
#include "OpenMeleeMath.h"
int32 UOpenMeleeMath::Antitruncate(float number)
{
if (number > 0){
return ceil(number);
}
else
{
return floor(number);
}
return 0;
}<file_sep>/Config/DefaultGame.ini
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=B48DB409440BE8D7C695B7B5859F674D
ProjectName=2D Side Scroller Game Blueprint Template
[/Script/UnrealEd.ProjectPackagingSettings]
BuildConfiguration=PPBC_Development
StagingDirectory=(Path="C:/Users/ALEX/SmashUE4Test/32")
FullRebuild=True
ForDistribution=False
IncludeDebugFiles=False
UsePakFile=False
bGenerateChunks=False
IncludePrerequisites=True
IncludeCrashReporter=True
InternationalizationPreset=English
-CulturesToStage=en
+CulturesToStage=en
<file_sep>/Source/OpenMelee2d/OpenMeleeMath.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Kismet/BlueprintFunctionLibrary.h"
#include "OpenMeleeMath.generated.h"
/**
*
*/
UCLASS()
class OPENMELEE2D_API UOpenMeleeMath : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintPure, Category = "OpenMelee2D")
static int32 Antitruncate(float number);
};
<file_sep>/Source/OpenMelee2d/OpenMelee2d.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "OpenMelee2d.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, OpenMelee2d, "OpenMelee2d" );
|
e9c6107954ac1a33c0973f7496aed4b0942fe7eb
|
[
"C++",
"INI"
] | 4
|
C++
|
Prazon/OpenMelee2D
|
e137fc23bc938633c21313c3192ffdf9476cff93
|
530e6447a224f2d64fc57617f3185aac2fcb20c7
|
refs/heads/master
|
<file_sep>/*
* Data Structure for Stack Using Lnked List
*/
const Node = require('./Node.js');
module.exports = class LinkedListStack {
constructor() {
this.head = null;
}
isEmpty() {
return (this.head == null);
}
pop() {
if(this.isEmpty()) {
} else {
var data = this.head.data;
this.head = this.head.next;
return data;
}
}
push(data) {
let newnode = new Node(data);
if(this.isEmpty()) {
this.head = newnode;
} else {
newnode.next = this.head;
this.head = newnode;
}
}
}
<file_sep>/******************************************************************************
*
* Purpose: Take a range of 0 - 1000 Numbers and find the Prime numbers in
* that range and print using queue.
*
* @author <NAME>
* @version 1.0
* @since 27-07-2018
*
******************************************************************************/
var common = require('./utility.js');
const LinkedListQueue = require('./LinkedListQueue.js');
function primeAnagramUsingQueue() {
var prime = [];
var i=0;
/*
* To check prime or not and store into prime array.
*/
for(var index=2;index<1000;index++) {
if(common.checkPrime(index)) {
prime[i] = index;
i++;
}
}
/*
* To check calculatd prime numbers are anagram or not and insert into queue.
*/
let que = new LinkedListQueue();
for(var i=0;i<prime.length;i++) {
for(var j=i+1;j<prime.length;j++) {
if(common.isAnagram(prime[j], prime[i])) {
que.enqueue(prime[i]);
que.enqueue(prime[j]);
}
}
}
/*
* To pop deque anagram from queue and display all
*/
console.log("Prime Anagrams : ");
for(var index=0;index<prime.length;index++) {
if(que.isEmpty()) {
console.log("Queue is Empty");
break;
} else {
var primeAnagram = que.dequeue();
console.log(primeAnagram+" ");
}
}
}
primeAnagramUsingQueue();<file_sep>/******************************************************************************
*
* Purpose: To print Calender.
*
* @author <NAME>
* @version 1.0
* @since 26-07-2018
*
******************************************************************************/
var readline = require('readline');
// var common = require('/home/bridgeit/Desktop/Swati/FunctionalPrograms/utility.js');
// var common1 = require('/home/bridgeit/Desktop/Swati/AlorithmPrograms/utility.js');
var common = require('./utility.js');
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/*
* Function to print calender
*
* @param month contains value for month
* @param year contains value for year
*/
function printCalendar() {
read.question("Enter month : ",(month) => {
read.question("Enter year : ",(year) => {
common.calendar(month,year);
});
});
}
printCalendar();
<file_sep>/*
* Class for Ordered Linked List Operations.
*/
fs = require('fs');
const Node = require('./Node.js');
module.exports = class OrderedLinkedList {
constructor() {
this.head = null;
}
/**
* Function to add word into Linked List
* @param data
*/
add(data) {
let newnode = new Node(data);
if(this.head == null)
this.head = newnode;
else if(data < this.head.data) {
var temp = new Node(data);
temp.next = this.head;
this.head = temp;
} else {
var flag = true;
var prev = this.head;
var temp = this.head.next;
while(temp != null) {
if(data > temp.data) {
prev = temp;
temp = temp.next;
} else {
var newNode = new Node(data);
newNode.next = temp;
prev.next = newNode;
flag = false;
break;
}
}
if(flag) {
var temp1 = this.head;
while(temp1.next != null) {
temp1 = temp1.next;
}
temp1.next = new Node(data);
}
}
}
/**
* Function to display contents of Linked List.
*/
display() {
var temp = this.head;
while( temp != null) {
console.log(temp.data);
temp = temp.next;
}
}
/**
* Function to search a given word.
* @param word
*/
search(word) {
var temp = this.head;
var flag = 0;
while(temp != null) {
if((temp.data) == (word))
flag = 1;
temp = temp.next;
}
if(flag == 1)
return true;
else
return false;
}
/**
* Function to remove word from Linked List.
* @param word
*/
remove(word) {
if((this.head.data) == (word))
this.head = this.head.next;
else {
var temp = this.head.next;
var prev = this.head;
while(((temp.data) != (word))) {
prev = temp;
temp = temp.next;
}
prev.next = temp.next;
temp = null;
}
}
/**
* Function to write updated Linked List into file.
*/
writeToFile() {
var array = [];
var index = 0;
var temp = this.head;
while(temp != null) {
array[index] = temp.data;
temp = temp.next;
index++;
}
fs.writeFile('abc.txt', array , function (err) {
if (err)
return console.log(err);
});
/*var writeStream = fs.createWriteStream("ab.txt");
if(this.head == null) {
console.log("List is empty");
}
else {
var temp = this.head;
while(temp != null) {
writeStream.write(temp.data+" ");
temp = temp.next;
}
}*/
}
}<file_sep>/*
* Data Structure for Queue Operations.
*/
module.exports = class Queue{
constructor(size,noofppl) {
this.front = 0;
this.rear = 0;
this.size = size;
this.cnt = noofppl;
}
isEmpty() {
return (this.cnt == 0);
}
isFull() {
return (this.rear == this.size);
}
sizeofQueue() {
return this.cnt;
}
enqueue() {
if(this.isFull())
console.log("Queue is full");
else {
this.rear++;
this.cnt++;
}
}
dequeue() {
if(this.isEmpty())
console.log("Queue is empty");
else {
this.cnt--;
this.front--;
}
}
};
<file_sep>/******************************************************************************
*
* Purpose: Take a range of 0 - 1000 Numbers and find the Prime numbers in
* that range and print in 2D array.
*
* @author <NAME>
* @version 1.0
* @since 27-07-2018
*
******************************************************************************/
var readline = require('readline');
var common = require('./utility.js');
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/*
* Function to take range for prime numbers.
*
* @param range contains value of range to find prime numbers.
*/
function primeNumbers2DArray() {
read.question("Enter range between 1 - 1000 : ",(range) => {
var prime = [];
var i = 0;
for(var index=2;index<=range;index++) {
/*
* Function to check whether a number is prime or not.
*/
if(common.checkPrime(index)) {
prime[i] = index;
i++;
}
}
/*
* Function to print 2D array.
*/
common.twoDPrimeArray(prime);
read.close();
});
}
primeNumbers2DArray();<file_sep>/******************************************************************************
*
* Purpose: Take a range of 0 - 1000 Numbers and find the Prime numbers in
* that range and print using stack.
*
* @author <NAME>
* @version 1.0
* @since 27-07-2018
*
******************************************************************************/
var common = require('./utility.js');
const LinkedListStack = require('./LinkedListStack.js');
function primeAnagramUsingStack() {
let stk = new LinkedListStack();
var prime = [];
var i=0;
/*
* To check prime or not and store into prime array.
*/
for(var index=2;index<1000;index++) {
if(common.checkPrime(index)) {
prime[i] = index;
i++;
}
}
/*
* To check calculatd prime numbers are anagram or not and push into stack.
*/
for(var i=0;i<prime.length;i++) {
for(var j=i+1;j<prime.length;j++) {
if(common.isAnagram(prime[j], prime[i])) {
stk.push(prime[i]);
stk.push(prime[j]);
}
}
}
/*
* To pop prime anagram from stack and display all
*/
console.log("Prime Anagrams : ");
for(var index=0;index<prime.length;index++) {
if(stk.isEmpty()) {
console.log("Stack is Empty");
break;
} else {
var primeAnagram = stk.pop();
console.log(primeAnagram+" ");
}
}
}
primeAnagramUsingStack();<file_sep>/******************************************************************************
*
* Purpose: Simulate Banking Cash Counter Using Queue.
*
* @author <NAME>
* @version 1.0
* @since 24-07-2018
*
******************************************************************************/
var readline = require('readline');
const Queue = require('./Queue.js');
var read = readline.createInterface(process.stdin, process.stdout);
console.log("\n<---------------- Menu ------------------>");
console.log("===========================================")
console.log("0. Exit(exit)");
console.log("1. Deposit Amount");
console.log("2. Withdraw Amount");
console.log("3. Check Balance");
console.log("4. Add people into Queue");
console.log("5. Delete from Queue");
console.log("6. Check Number of persons in queue");
let balance = 10000;
var noofppl = 4;
var size = 10;
let que = new Queue(size, noofppl);
/*
* T o promt for user input unless he exits.
*/
read.setPrompt('choice> ');
read.prompt();
read.on('line', function(line) {
//Continue if noofppl > 0
if(noofppl > 0) {
/*
* Exit from input command if type exit
*/
if (line === "0")
read.close();
/*
* To perform deposite operation
*/
else if(line === '1') {
console.log(noofppl+" person's Transaction is Running....");
read.question("Enter amount to deposit : ",(deposit) => {
balance = Number(balance) + Number(deposit);
console.log("Total Balance is : "+balance);
noofppl--;
que.cnt--;
read.prompt();
});
}
/*
* To perform withdraw operation
*/
else if(line === '2') {
console.log(noofppl+" person's Transaction is Running....");
read.question("Enter amount to withdraw : ",(withdraw) => {
if(balance >= withdraw) {
balance = balance - withdraw;
console.log("Total Balance is : "+balance);
}
else
console.log("Insufficient Balance");
noofppl--;
que.cnt--;
read.prompt();
});
}
/*
* To Check bank balance
*/
else if(line === '3') {
console.log("Total Amount in bank account is : "+balance);
read.prompt();
}
/*
* To add peoples into queue
*/
else if(line === '4') {
que.enqueue();
noofppl = que.sizeofQueue();
console.log("Number of people in queue after newly add people : "+noofppl);
read.prompt();
}
/*
* To delete people from queue
*/
else if(line === '5') {
que.dequeue();
noofppl = que.sizeofQueue();
console.log("Number of people in queue after deleting people : "+noofppl);
read.prompt();
}
/*
* To check number of peoples in a queue
*/
else if(line === '6') {
noofppl = que.sizeofQueue();
console.log("Number of people in queue are : "+noofppl);
read.prompt();
}
else {
console.log(`Enter correct choice `);
read.prompt();
}
}
else {
console.log("Queue is empty");
read.close();
}
}).on('close',function(){
process.exit(0);
});
<file_sep>/*
* Data Structure forStack operations.
*/
module.exports = class Stack{
constructor() {
this.stk = [];
this.top = -1;
}
isEmpty() {
return (this.top == -1);
}
push(item) {
this.stk[++this.top] = item;
}
pop() {
return this.stk[this.top--];
}
peek() {
return this.stk[this.top];
}
};
<file_sep>/*
* Class for Unordered Linked List Operations.
*
*/
fs = require('fs');
const Node = require('./Node.js');
module.exports = class UnOrderedLinkedList {
constructor() {
this.head = null;
}
/**
* Function to add word into Linked List
* @param data
*/
add(data) {
let newnode = new Node(data);
if(this.head == null)
this.head = newnode;
else {
var temp = this.head;
while(temp.next != null)
temp = temp.next;
temp.next = newnode;
}
}
/**
* Function to display contents of Linked List.
*/
display() {
var temp = this.head;
while( temp != null) {
console.log(temp.data);
temp = temp.next;
}
}
/**
* Function to search a given word.
* @param word
*/
search(word) {
var temp = this.head;
var flag = 0;
while(temp != null) {
if((temp.data) == (word))
flag = 1;
temp = temp.next;
}
if(flag == 1)
return true;
else
return false;
}
/**
* Function to remove word from Linked List.
* @param word
*/
remove(word) {
if((this.head.data) == (word))
this.head = this.head.next;
else {
var temp = this.head.next;
var prev = this.head;
while(((temp.data) != (word))) {
prev = temp;
temp = temp.next;
}
prev.next = temp.next;
temp = null;
}
}
/**
* Function to write updated Linked List into file.
*/
writeToFile() {
var array = [];
var index = 0;
var temp = this.head;
while(temp != null) {
array[index] = temp.data;
temp = temp.next;
index++;
}
fs.writeFile('ab.txt', array , function (err) {
if (err)
return console.log(err);
});
/*var writeStream = fs.createWriteStream("ab.txt");
if(this.head == null) {
console.log("List is empty");
}
else {
var temp = this.head;
while(temp != null) {
writeStream.write(temp.data+" ");
temp = temp.next;
}
}*/
}
}<file_sep>/*
* Data Structure class for Double Ended Queue.
*/
module.exports = class Deque {
constructor() {
this.front = this.rear = -1;
this.dque = [];
}
isEmpty() {
return (front == rear);
}
addRear(data) {
this.rear++;
this.dque[this.rear] = data;
}
addFront(data) {
this.front--
this.dque[this.front] = data;
}
removeRear() {
var data = this.dque[this.rear];
this.rear--;
return data;
}
removeFront() {
var data = this.dque[this.front];
this.front++;
return data;
}
}
<file_sep># DataStructurePrograms
Data Structure Programs in nodejs
<file_sep>/******************************************************************************
*
* Purpose: Take a range of 0 - 1000 Numbers and find the Prime Anagram numbers in
* that range and print in 2D array.
*
* @author <NAME>
* @version 1.0
* @since 27-07-2018
*
******************************************************************************/
var readline = require('readline');
var common = require('./utility.js');
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/*
* Function to take range to find prime numbers and anagram.
*
* @param range contains value of range upto which find prime anagrams.
*/
function primeAnagram2DArray() {
read.question("Enter range between 1 - 1000 : ",(range) => {
var prime = [];
var i = 0;
var anagram = [];
var count1 = 0;
for(var index=2;index<=range;index++) {
/*
* To check prime or not and store into prime array.
*/
if(common.checkPrime(index)) {
prime[i] = index;
i++;
}
}
/*
* To check calculatd prime numbers are anagram or not and store into array.
*/
for(var i=0;i<prime.length;i++) {
for(var j=i+1;j<prime.length;j++) {
if(common.isAnagram(prime[j],prime[i])) {
anagram[count1] = prime[i];
count1++;
anagram[count1] = prime[j];
count1++;
}
}
}
//print prime and anagram numbers.
for(var i=0;i<anagram.length;i++) {
console.log(anagram[i]);
}
read.close();
});
}
primeAnagram2DArray();<file_sep>/******************************************************************************
*
* Purpose: To print Calender using Linked List Queue.
*
* @author <NAME>
* @version 1.0
* @since 26-07-2018
*
******************************************************************************/
var readline = require('readline');
var common = require('./utility.js');
var read = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/*
* Function to take user input for month and year
*/
function calenderQueue() {
read.question("Enter month : ",(month) => {
read.question("Enter year : ",(year) => {
/*
* Function to print calender of given month.
*/
common.queueCalendar(month,year);
})
})
}
calenderQueue();
|
719e7129c0d41f60b95dfd174948674efe1f9084
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
swatidesale/DataStructurePrograms
|
5be5c81144877c51a186f661a675bf1f9c7ac6b3
|
bc9ab80f05388d9cd4222c70a3cc47162d51a0fe
|
refs/heads/master
|
<repo_name>galeanojav/Stability_equations<file_sep>/sommers_stability.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 10:36:42 2018
@author: javiergaleano
"""
# Sommers's stability
import numpy as np
import matplotlib.pyplot as plt
S = 1000 # number of species
### Sommers et al. Stability
vari = 1/S
somer = np.zeros((S,S))
ma_som = np.random.normal(loc = 0.0, scale =vari, size=(S*S-S))
t=0
for i in range(S):
for j in range(S):
if i != j:
somer[i][j]= ma_som[t]
t +=1
### mean and var of the matrix
mediasom = np.mean(somer, dtype = np.float64)
varianzasom = np.var(somer,dtype=np.float64)
print(mediasom, varianzasom)
### calculating eigenvalues and plotting
autovalor = np.linalg.eigvals(somer)
X=[]
Y=[]
for i in autovalor:
X.append(i.real)
Y.append(i.imag)
fig, ax = plt.subplots(1, 1)
ax.scatter(X,Y,alpha=0.3)
ax.grid(True)
ax.set_title("Sommers'stability")
ax.set(xlabel="Real", ylabel="Im")
#mean, var, skew, kurt = halfnorm.stats(moments='mvsk')
#x = np.linspace(halfnorm.ppf(0.01), halfnorm.ppf(0.99), 100)
#ax.plot(x, halfnorm.pdf(x), 'ro', lw=5, alpha=0.6, label='halfnorm pdf')
#r = halfnorm.rvs(size=10000)
#ax.hist(r, normed=True, histtype='stepfilled', bins = 20, alpha=0.2)
#ax.legend(loc='best', frameon=False)
#plt.show()
<file_sep>/allesina_stability.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 10:36:42 2018
@author: javiergaleano
"""
# Sommers's stability
import numpy as np
import matplotlib.pyplot as plt
S = 1000 # number of species
### Sommers et al. Stability
vari = 1/S
sigma = vari
### matrix with -1.0 in the diagonal
diago = np.full_like(np.arange(S), -10.0, dtype=np.float32)
diagonal1 = np.diagflat(diago)
diagonal2 = np.diagflat(diago)
diagonal3 = np.diagflat(diago)
diagonal4 = np.diagflat(diago)
### Array with normal distribution mean = 0.0 and var = sigma
matriz1 = np.random.normal(loc = 0.0, scale =sigma, size=(S*S-S))
matriz2 = np.random.triangular(-20, -10, 3, size=(S*S-S))
matriz3 = np.random.wald(0.2, sigma, size=(S*S-S))
matriz4 = np.random.exponential(sigma, size=(S*S-S))
### Random matrix complete
k=0
for i in range(S):
for j in range(S):
if i != j:
diagonal1[i][j]= matriz1[k]
diagonal2[i][j]= matriz2[k]
diagonal3[i][j]= matriz3[k]
diagonal4[i][j]= matriz4[k]
k +=1
### mean and var of the matrix
media1 = np.mean(diagonal1, dtype = np.float64)
varianza1 = np.var(diagonal1,dtype=np.float64)
print(media1, varianza1)
media2 = np.mean(diagonal2, dtype = np.float64)
varianza2 = np.var(diagonal2,dtype=np.float64)
print(media2, varianza2)
media3 = np.mean(diagonal3, dtype = np.float64)
varianza3 = np.var(diagonal3,dtype=np.float64)
print(media3, varianza3)
media4 = np.mean(diagonal4, dtype = np.float64)
varianza4 = np.var(diagonal4,dtype=np.float64)
print(media4, varianza4)
### calculating eigenvalues and plotting
autovalor1 = np.linalg.eigvals(diagonal1)
autovalor2 = np.linalg.eigvals(diagonal2)
autovalor3 = np.linalg.eigvals(diagonal3)
autovalor4 = np.linalg.eigvals(diagonal4)
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2)
X1=[]
Y1=[]
for i in autovalor1:
X1.append(i.real)
Y1.append(i.imag)
X2=[]
Y2=[]
for j in autovalor2:
X2.append(j.real)
Y2.append(j.imag)
X3=[]
Y3=[]
for k in autovalor3:
X3.append(k.real)
Y3.append(k.imag)
X4=[]
Y4=[]
for l in autovalor4:
X4.append(l.real)
Y4.append(l.imag)
ax1.scatter(X1,Y1,alpha=0.3)
ax1.set(xlabel="Real", ylabel="Im")
ax2.scatter(X2,Y2,alpha=0.3)
ax2.set(xlabel="Real", ylabel="Im")
ax3.scatter(X3,Y3,alpha=0.3)
ax3.set(xlabel="Real", ylabel="Im")
ax4.scatter(X4,Y4,alpha=0.3)
ax4.set(xlabel="Real", ylabel="Im")
#mean, var, skew, kurt = halfnorm.stats(moments='mvsk')
#x = np.linspace(halfnorm.ppf(0.01), halfnorm.ppf(0.99), 100)
#ax.plot(x, halfnorm.pdf(x), 'ro', lw=5, alpha=0.6, label='halfnorm pdf')
#r = halfnorm.rvs(size=10000)
#ax.hist(r, normed=True, histtype='stepfilled', bins = 20, alpha=0.2)
#ax.legend(loc='best', frameon=False)
#plt.show()
<file_sep>/allesina_stability_function.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 10:36:42 2018
@author: javiergaleano
"""
# Sommers's stability
import numpy as np
import matplotlib.pyplot as plt
def random_matrix(S,center,sigma, ty=None):
"""
Function to calculate the random matrix.
S = size of the matrix SxS
center = value of the matrix diagonal
sigma = var
ty [optinal]= None --> normal distibution (0,sigma)
ty = 'halfnorm' --> half normal distribution
ty = "exponential" --> exponential distribution scale sigma
"""
### matrix with "center" in the diagonal
diago = np.full_like(np.arange(S), center, dtype=np.float32)
diagonal = np.diagflat(diago)
### Array with normal distribution mean = 0.0 and var = sigma
if ty == 'exponential':
matriz = np.random.exponential(sigma, size=(S*S-S))
if ty == 'halfnorm':
matriz = np.abs(np.random.normal(loc = 0.0, scale =sigma, size=(S*S-S)))
else:
matriz = np.random.normal(loc = 0.0, scale =sigma, size=(S*S-S))
### Random matrix complete
k=0
for i in range(S):
for j in range(S):
if i != j:
diagonal[i][j]= matriz[k]
k +=1
return diagonal
def plot_eig(autovalor):
"""
Plot eigenvalues. Axis X real part, Axis Y imaginary part
"""
fig, ax1 = plt.subplots(1, 1)
X1=[]
Y1=[]
for i in autovalor:
X1.append(i.real)
Y1.append(i.imag)
ax1.scatter(X1,Y1,alpha=0.3)
ax1.set(xlabel="Real", ylabel="Im")
return
S = 1000 # number of species
center = -10.0
sigma = 1/S
diagonal = random_matrix(S,center,sigma, ty='halfnorm')
### mean and var of the matrix
media1 = np.mean(diagonal, dtype = np.float64)
varianza1 = np.var(diagonal,dtype=np.float64)
print(media1, varianza1)
### calculating eigenvalues and plotting
autovalor1 = np.linalg.eigvals(diagonal)
plot_eig(autovalor1)
plt.show()
#mean, var, skew, kurt = halfnorm.stats(moments='mvsk')
#x = np.linspace(halfnorm.ppf(0.01), halfnorm.ppf(0.99), 100)
#ax.plot(x, halfnorm.pdf(x), 'ro', lw=5, alpha=0.6, label='halfnorm pdf')
#r = halfnorm.rvs(size=10000)
#ax.hist(r, normed=True, histtype='stepfilled', bins = 20, alpha=0.2)
#ax.legend(loc='best', frameon=False)
#plt.show()
<file_sep>/README.md
# Stability_equations
Programs of the stability analysis
|
3806a15a536ed81a60f40c8368aa2643cba9797f
|
[
"Markdown",
"Python"
] | 4
|
Python
|
galeanojav/Stability_equations
|
22e881569f46e7c02a0985bae8b9bd7757bad764
|
535bb79e22243efcdd548212c853a66c2e10a2b8
|
refs/heads/master
|
<repo_name>tmahata009/readyaml<file_sep>/readyaml.py
import yaml
myfile = "config_global.yaml"
class readyaml:
def readfile(self,conf):
try:
with open(conf) as ymal_data:
ymaldata=yaml.load(ymal_data)
yield ymaldata, True
except e:
yield e ,False
a = readyaml()
data = a.readfile(myfile)
for i in data:
print(i)
print(id(i))
<file_sep>/README.md
# readyaml
read yaml file using generator in python
|
6a085ec94c507a995d4ee8404acf4f3666ba7644
|
[
"Markdown",
"Python"
] | 2
|
Python
|
tmahata009/readyaml
|
ae11f0caf7d842a1745895eb243a38f474d25971
|
4470f4e2a11674344b179bf89549440622052f56
|
refs/heads/master
|
<repo_name>JavaMinor2015/LeonAngularJS<file_sep>/app/scripts/controllers/main.js
'use strict';
/**
* @ngdoc function
* @name angularJsApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the angularJsApp
*/
angular.module('angularJsApp')
.controller('MainCtrl', function ($scope) {
//Vars
$scope.contacts = [
{
id: 1,
firstName: 'Swek',
surname: 'Swekker',
email: '<EMAIL>',
editMode: false
},
{
id: 2,
firstName: 'Swag',
surname: 'Swagger',
email: '<EMAIL>',
editMode: false
}
];
$scope.newContact = {};
$scope.addingNew = false;
//Methods
$scope.saveContact = function() {
$scope.newContact.id = $scope.findNextId();
$scope.contacts.push($scope.newContact);
$scope.newContact = {};
$scope.addingNew = false;
};
$scope.delete = function(contact) {
var index = $scope.contacts.indexOf(contact);
$scope.contacts.splice(index, 1);
};
$scope.edit = function(contact) {
$scope.contacts.forEach(function(contact) {
contact.editMode = false;
});
contact.editMode = true;
};
$scope.findNextId = function() {
var foundIds = [];
$scope.contacts.forEach(function(contact){
foundIds.push(contact.id);
});
foundIds = foundIds.sort();
console.log(foundIds);
var selectId = -1;
var i = 1;
while(selectId == -1) {
if (foundIds[i - 1] != i) {
selectId = i;
console.log("Selected ID: " + selectId);
} else {
i++;
}
}
return selectId;
}
});
<file_sep>/test/e2e/contactFile.js
/**
* Created by <NAME> on 1-12-2015.
*/
describe('E2E: Contact form', function() {
var showButton = function() {
element(by.id('addNewContactBtn')).click();
};
beforeEach(function() {
browser.get('http://localhost:9000');
});
it('shouldn\'t show the new contact form from the start', function() {
var addButton = element(by.id('newContactSaveBtn'));
expect(addButton.isDisplayed()).toBe(false);
var newButton = element(by.id('addNewContactBtn'));
newButton.click();
expect(addButton.isDisplayed()).toBe(true);
});
it('should disable the submit button when the form is invalid', function() {
showButton();
var addButton = element(by.id('newContactSaveBtn'));
expect(addButton.isEnabled()).toBe(false);
});
it('should enable the submit button when the form is valid', function() {
showButton();
element(by.model('newContact.firstName')).sendKeys('Frits');
element(by.model('newContact.surname')).sendKeys('Spits');
element(by.model('newContact.email')).sendKeys('<EMAIL>');
var addButton = element(by.id('newContactSaveBtn'));
expect(addButton.isEnabled()).toBe(true);
});
it('should add a contact to the list when submitting the form', function() {
showButton();
element(by.model('newContact.firstName')).sendKeys('Frits');
element(by.model('newContact.surname')).sendKeys('Spits');
element(by.model('newContact.email')).sendKeys('<EMAIL>');
var contacts = by.repeater('contact in contacts');
var addButton = element(by.id('newContactSaveBtn'));
addButton.click();
expect(element.all(contacts).count()).toBe(3);
var email = contacts.row(2).column('email');
expect(element(email).getText()).toBe('<EMAIL>');
});
});
|
113d4d9397d94c356f40239a0e7c0cd01def20af
|
[
"JavaScript"
] | 2
|
JavaScript
|
JavaMinor2015/LeonAngularJS
|
ddf9f15b272c126083476fe9372e618d6b1fe676
|
228f0bd2dcf36df1fb8360b2d1e773b4cd0a837e
|
refs/heads/master
|
<repo_name>nopnop2002/esp8266-mqtt-uart-bridge<file_sep>/README.md
# esp8266_mqtt_uart_bridge
esp8266 mqtt uart bridge.
- Convert from UART output to MQTT publish.
- Convert from MQTT subscribe to UART input.
# Monitoring
You can monitor ESP8266 using Serial1.
Serial1 outputs to GPIO2
# How to disable ESP8266 boot messages
ESP8266 boot rom writes a log to the UART when booting like this:
```
ets Jan 8 2014,rst cause 1, boot mode:(3,7)
load 0x40100000, len 24236, room 16
tail 12
chksum 0xb7
ho 0 tail 12 room 4
load 0x3ffe8000, len 3008, room 12
tail 4
chksum 0x2c
load 0x3ffe8bc0, len 4816, room 4
tail 12
chksum 0x46
csum 0x46
```
This message can cause unexpected trouble.
## Swap UART
UART can be swapped by adding the following one line:
```
Serial.swap();
```
TX / RX changes to the following when UART is swapped.
```
GPIO15(TXD) --- RX
GPIO13(RXD) --- TX
```
The boot message does not reach RX port of other side.
However, since GPIO15 is a pin that determines the boot mode, ESP8266 does not start.
__This method cannot be used.__
## Add a circuit
If the following circuit is added, All message does not reach RX port of other side.
I used 1N5819 Schottky Barrier Plastic Rectifier.

To start transmission, set the GPIO polarity to OUTPUT and the level to LOW.
```
pinMode(GPIO, OUTPUT);
digitalWrite(GPIO, LOW);
Serial.begin(115200);
```
NOTE:GPIO15 is pulled down and cannot be used for this.
# MQTT to UART

You need to adjust the following environment.
- #define MQTT_SERVER "192.168.10.40"
IP of MQTT Broker
- #define MQTT_PORT 1883
Port of MQTT Broker
- #define MQTT_TOPIC "atmega328"
Subscribe topic
- #define MQTT_WILL_TOPIC "atmega328"
Will topic
- #define MQTT_WILL_MSG "I am leaving..."
Will message
- #define UART_BAUDRATE 115200
UART boudrate
- const char* ssid = "SSID of Your AP";
SSID of your Access Point
- const char* password = "<PASSWORD>";
Password of your Access Point
# UART to MQTT

You need to adjust the following environment.
- #define MQTT_SERVER "192.168.10.40"
IP of MQTT Broker
- #define MQTT_PORT 1883
Port of MQTT Broker
- #define MQTT_TOPIC "atmega328"
Publish topic
- #define MQTT_WILL_TOPIC "atmega328"
Will topic
- #define MQTT_WILL_MSG "I am leaving..."
Will message
- #define UART_BAUDRATE 115200
UART boudrate
- const char* ssid = "SSID of Your AP";
SSID of your Access Point
- const char* password = "<PASSWORD>";
Password of your Access Point
<file_sep>/ESP8266_UART_to_MQTT/ESP8266_UART_to_MQTT.ino
/*
* ESP8266 UART-->WiFi(MQTT) Converter
*
* TX of Serial1 for ESP8266 is GPIO2
*
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#define MQTT_SERVER "192.168.10.40" // You can change
#define MQTT_PORT 1883
#define MQTT_WILL_TOPIC "atmega328" // You can change
#define MQTT_TOPIC "atmega328" // You can change
#define MQTT_WILL_MSG "I am leaving..." // You can change
#define UART_BAUDRATE 115200 // You can change
#define RXBUFFERSIZE 1024
const char* ssid = "SSID of Your AP";
const char* password = "<PASSWORD>";
WiFiClient espClient;
PubSubClient client(espClient);
#define bufferSize 8192
char buf[bufferSize];
uint8_t iofs=0;
#define RXBUFFERSIZE 1024
#define UART_BAUDRATE 115200 // You can change
errorDisplay(char* buff) {
Serial1.print("Error:");
Serial1.println(buff);
for (int i=0;i<10;i++) {
delay(1000);
}
ESP.restart();
}
void setup()
{
delay(1000);
Serial1.begin(115200); // for DEBUG
Serial.begin(UART_BAUDRATE);
// Allow to define the receiving buffer depth.
// The default value is 256.
Serial.setRxBufferSize(RXBUFFERSIZE);
// Hardware serial is now on RX:GPIO13 TX:GPIO15
//Serial.swap();
// Connect Wifi
Serial1.println();
Serial1.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial1.print(".");
}
Serial1.println("WiFi connected");
Serial1.print("IP address: ");
Serial1.println(WiFi.localIP());
Serial1.print("subnetMask: ");
Serial1.println(WiFi.subnetMask());
Serial1.print("gatewayIP: ");
Serial1.println(WiFi.gatewayIP());
// Connect MQTT
client.setServer(MQTT_SERVER, MQTT_PORT);
char clientid[20];
sprintf(clientid,"ESP8266-%06x",ESP.getChipId());
Serial1.print("clientid=");
Serial1.println(clientid);
Serial1.print("Attempting MQTT connection...");
// Attempt to connect
if (strlen(MQTT_WILL_MSG)) {
if (!client.connect(clientid, MQTT_WILL_TOPIC, 0, 0, MQTT_WILL_MSG)) {
errorDisplay("connect Fail");
}
} else {
if (!client.connect(clientid)) {
errorDisplay("connect Fail");
}
}
Serial1.println("connected");
Serial1.print("Waiting for input from UART at ");
Serial1.print(UART_BAUDRATE);
Serial1.println("bps");
}
void loop()
{
static int term = 0;
if (!client.connected()) {
errorDisplay("not connect");
}
client.loop();
if(Serial.available()) {
char ch = Serial.read(); // read char from UART
//Serial1.print("ch=0x");
//Serial1.println(ch,HEX);
if (ch == 0x0d) {
} else if (ch == 0x0a) {
Serial1.println();
Serial1.print("Publish to ");
Serial1.println(MQTT_SERVER);
if (!client.publish(MQTT_TOPIC, buf)) {
errorDisplay("publish fail");
}
iofs = 0;
} else {
buf[iofs] = ch;
buf[iofs+1] = 0;
Serial1.print(buf[iofs]);
if(iofs<bufferSize-1) iofs++;
}
}
}
<file_sep>/ESP8266_MQTT_to_UART/ESP8266_MQTT_to_UART.ino
/*
* ESP8266 Wifi(MQTT)--->UART Converter
*
* TX of Serial1 for ESP8266 is GPIO2
*
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#define MQTT_SERVER "192.168.10.40" // You can change
#define MQTT_PORT 1883
#define MQTT_TOPIC "atmega328" // You can change
#define MQTT_WILL_TOPIC "atmega328" // You can change
#define MQTT_WILL_MSG "I am leaving..." // You can change
#define UART_BAUDRATE 115200 // You can change
#define RXBUFFERSIZE 1024
const char* ssid = "SSID of Your AP";
const char* password = "<PASSWORD>";
WiFiClient espClient;
PubSubClient client(espClient);
//#define bufferSize 8192
//char buf[bufferSize];
//uint8_t iofs = 0;
void errorDisplay(char* buff) {
Serial1.print("Error:");
Serial1.println(buff);
for (int i=0;i<10;i++) {
delay(1000);
}
ESP.restart();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial1.print("Message arrived [");
Serial1.print(topic);
Serial1.print("] ");
for (int i = 0; i < length; i++) {
Serial1.print((char)payload[i]);
Serial.print((char)payload[i]);
}
Serial1.println();
Serial.println();
}
void setup()
{
delay(1000);
Serial1.begin(115200); // for DEBUG
Serial.begin(UART_BAUDRATE);
// Allow to define the receiving buffer depth.
// The default value is 256.
Serial.setRxBufferSize(RXBUFFERSIZE);
// Hardware serial is now on RX:GPIO13 TX:GPIO15
//Serial.swap();
// Connect Wifi
Serial1.println();
Serial1.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial1.print(".");
}
Serial1.println("WiFi connected");
Serial1.print("IP address: ");
Serial1.println(WiFi.localIP());
Serial1.print("subnetMask: ");
Serial1.println(WiFi.subnetMask());
Serial1.print("gatewayIP: ");
Serial1.println(WiFi.gatewayIP());
// Connect MQTT
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
char clientid[20];
sprintf(clientid,"ESP8266-%06x",ESP.getChipId());
Serial1.print("clientid=");
Serial1.println(clientid);
Serial1.print("Attempting MQTT connection...");
// Attempt to connect
if (strlen(MQTT_WILL_MSG)) {
if (!client.connect(clientid, MQTT_WILL_TOPIC, 0, 0, MQTT_WILL_MSG)) {
errorDisplay("connect Fail");
}
} else {
if (!client.connect(clientid)) {
errorDisplay("connect Fail");
}
}
if (!client.subscribe(MQTT_TOPIC)) {
errorDisplay("subscribe Fail");
}
Serial1.println("connected");
Serial1.print("Waiting for input from MQTT on [");
Serial1.print(MQTT_TOPIC);
Serial1.println("] topic");
}
void loop()
{
if (!client.connected()) {
errorDisplay("not connect");
}
client.loop();
if(Serial.available()) {
char ch = Serial.read(); // read char from UART
if (ch == 0x0d) {
} else if (ch == 0x0a) {
Serial1.println();
//iofs = 0;
} else {
//buf[iofs] = ch;
//buf[iofs+1] = 0;
//Serial1.print(buf[iofs]);
//if(iofs<bufferSize-1) iofs++;
Serial1.print(ch);
}
}
}
|
3353e25d1f8af0f60e967c0d68cb2c150e1201ec
|
[
"Markdown",
"C++"
] | 3
|
Markdown
|
nopnop2002/esp8266-mqtt-uart-bridge
|
6a9a226557704246aff8cdbdcd982bf9fe97af0e
|
d6db546ce43226d0e7d849254a0ba15be16a12db
|
refs/heads/master
|
<repo_name>JacobYLiu/Assembly<file_sep>/spring2017_jliu_disassembler/src/edu/sbcc/cs107/HexFile.java
package edu.sbcc.cs107;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author <NAME> CS 107: Disassembler Project
*
* This code implements working with a Hex file. The hex file format is
* documented at http://www.keil.com/support/docs/1584/
*/
public class HexFile {
/**
* This is where you load the hex file. By making it an ArrayList you can easily
* traverse it in order.
*/
private ArrayList<String> hexFile = null;
/* Add other variables here. */
int lineIndex = 0; // line index
int elementIndex = 9; // element index
int address; // to increment address
int recordType; // record type
/**
* Constructor that loads the .hex file.
*
* @param hexFileName
* @throws FileNotFoundException
*/
// Scanner for HexFile
public HexFile(String hexFileName) throws FileNotFoundException {
Scanner hexScanner = new Scanner(new File(hexFileName));
hexFile = new ArrayList<String>();
while (hexScanner.hasNextLine()) {
hexFile.add(hexScanner.nextLine());
}
hexScanner.close();
}
/**
* Pulls the length of the data bytes from an individual record.
*
* This extracts the length of the data byte field from an individual hex
* record. This is referred to as LL->Record Length in the documentation.
*
* @param Hex
* file record (one line).
* @return record length.
*/
public int getDataBytesOfRecord(String record) { // separating length and converting to hexadecimal
int record16 = Integer.parseInt(record.substring(1, 3), 16);
return record16;
}
/**
* Get the starting address of the data bytes.
*
* Extracts the starting address for the data. This tells you where the data
* bytes start and are referred to as AAAA->Address in the documentation.
*
* @param Hex
* file record (one line).
* @return Starting address of where the data bytes go.
*/
public int getAddressOfRecord(String record) { // separating address and converting to hexadecimal
int address16 = Integer.parseInt(record.substring(3, 7), 16);
return address16;
}
/**
* Gets the record type.
*
* The record type tells you what the record can do and determines what happens
* to the data in the data field. This is referred to as DD->Data in the
* documentation.
*
* @param Hex
* file record (one line).
* @return Record type.
*/
public int getRecordType(String record) { // separating record type and converting to hexadecimal
int rtype = Integer.parseInt(record.substring(7, 9), 16);
return rtype;
}
/**
* Returns the next halfword data byte.
*
* This function will extract the next halfword from the Hex file. By repeatedly
* calling this function it will look like we are getting a series of halfwords.
* Behind the scenes we must parse the HEX file so that we are extracting the
* data from the data files as well as indicating the correct address. This
* requires us to handle the various record types. Some record types can effect
* the address only. These need to be processed and skipped. Only data from
* recordType 0 will result in something returned. When finished processing null
* is returned.
*
* @return Next halfword.
*/
public Halfword getNextHalfword() {
while (lineIndex < hexFile.size()) { // will break out of loop once recNdex is at end
String rec = hexFile.get(lineIndex); // string
int tt = getRecordType(rec);
int aaaa = getAddressOfRecord(rec);
int ll = getDataBytesOfRecord(rec);
if (tt != 0) { // if record type != 0 then keep going, but if it's equal to 1, then
lineIndex++;
elementIndex = 9;
} else {
address = aaaa + (elementIndex - 9) / 2; // every time the byte element indexes move, then the address values increments by 2.
String firstByte = rec.substring(elementIndex, elementIndex + 2); // first byte gets reassigned every time
String secondByte = rec.substring(elementIndex + 2, elementIndex + 4); // second byte gets reassigned too
String halfwordString = secondByte + firstByte; // putting second and first in order.
Halfword hw = new Halfword(address, Integer.parseInt((halfwordString), 16));
elementIndex += 4; // element index adds 4
if (elementIndex >= 9 + ll * 2) { // continues the next line and data index starts at 9 again.
lineIndex++;
elementIndex = 9;
}
return hw;
}
}
return null;
}
}
|
d7cd3eea4c9cfa5c5c3bf44d56294bc534fb45ed
|
[
"Java"
] | 1
|
Java
|
JacobYLiu/Assembly
|
8a87e3df5635abe6989f0271054246de60a91632
|
1d05a5503ad7cfc1d8d1541172e8e07692a89306
|
refs/heads/master
|
<repo_name>krystollia/grpc-java<file_sep>/examples/src/generated/main/io/grpc/examples/bi/MisBiGrpc.java
package io.grpc.examples.bi;
import static io.grpc.stub.Calls.createMethodDescriptor;
import static io.grpc.stub.Calls.asyncUnaryCall;
import static io.grpc.stub.Calls.asyncServerStreamingCall;
import static io.grpc.stub.Calls.asyncClientStreamingCall;
import static io.grpc.stub.Calls.duplexStreamingCall;
import static io.grpc.stub.Calls.blockingUnaryCall;
import static io.grpc.stub.Calls.blockingServerStreamingCall;
import static io.grpc.stub.Calls.unaryFutureCall;
import static io.grpc.stub.ServerCalls.createMethodDefinition;
import static io.grpc.stub.ServerCalls.asyncUnaryRequestCall;
import static io.grpc.stub.ServerCalls.asyncStreamingRequestCall;
@javax.annotation.Generated("by gRPC proto compiler")
public class MisBiGrpc {
private static final io.grpc.stub.Method<io.grpc.examples.bi.BiLog,
io.grpc.examples.bi.BiResult> METHOD_BI =
io.grpc.stub.Method.create(
io.grpc.MethodType.UNARY, "Bi",
io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.examples.bi.BiLog.PARSER),
io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.examples.bi.BiResult.PARSER));
public static MisBiStub newStub(io.grpc.Channel channel) {
return new MisBiStub(channel, CONFIG);
}
public static MisBiBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new MisBiBlockingStub(channel, CONFIG);
}
public static MisBiFutureStub newFutureStub(
io.grpc.Channel channel) {
return new MisBiFutureStub(channel, CONFIG);
}
public static final MisBiServiceDescriptor CONFIG =
new MisBiServiceDescriptor();
@javax.annotation.concurrent.Immutable
public static class MisBiServiceDescriptor extends
io.grpc.stub.AbstractServiceDescriptor<MisBiServiceDescriptor> {
public final io.grpc.MethodDescriptor<io.grpc.examples.bi.BiLog,
io.grpc.examples.bi.BiResult> bi;
private MisBiServiceDescriptor() {
bi = createMethodDescriptor(
"p.MisBi", METHOD_BI);
}
@SuppressWarnings("unchecked")
private MisBiServiceDescriptor(
java.util.Map<java.lang.String, io.grpc.MethodDescriptor<?, ?>> methodMap) {
bi = (io.grpc.MethodDescriptor<io.grpc.examples.bi.BiLog,
io.grpc.examples.bi.BiResult>) methodMap.get(
CONFIG.bi.getName());
}
@java.lang.Override
protected MisBiServiceDescriptor build(
java.util.Map<java.lang.String, io.grpc.MethodDescriptor<?, ?>> methodMap) {
return new MisBiServiceDescriptor(methodMap);
}
@java.lang.Override
public com.google.common.collect.ImmutableList<io.grpc.MethodDescriptor<?, ?>> methods() {
return com.google.common.collect.ImmutableList.<io.grpc.MethodDescriptor<?, ?>>of(
bi);
}
}
public static interface MisBi {
public void bi(io.grpc.examples.bi.BiLog request,
io.grpc.stub.StreamObserver<io.grpc.examples.bi.BiResult> responseObserver);
}
public static interface MisBiBlockingClient {
public io.grpc.examples.bi.BiResult bi(io.grpc.examples.bi.BiLog request);
}
public static interface MisBiFutureClient {
public com.google.common.util.concurrent.ListenableFuture<io.grpc.examples.bi.BiResult> bi(
io.grpc.examples.bi.BiLog request);
}
public static class MisBiStub extends
io.grpc.stub.AbstractStub<MisBiStub, MisBiServiceDescriptor>
implements MisBi {
private MisBiStub(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
super(channel, config);
}
@java.lang.Override
protected MisBiStub build(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
return new MisBiStub(channel, config);
}
@java.lang.Override
public void bi(io.grpc.examples.bi.BiLog request,
io.grpc.stub.StreamObserver<io.grpc.examples.bi.BiResult> responseObserver) {
asyncUnaryCall(
channel.newCall(config.bi), request, responseObserver);
}
}
public static class MisBiBlockingStub extends
io.grpc.stub.AbstractStub<MisBiBlockingStub, MisBiServiceDescriptor>
implements MisBiBlockingClient {
private MisBiBlockingStub(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
super(channel, config);
}
@java.lang.Override
protected MisBiBlockingStub build(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
return new MisBiBlockingStub(channel, config);
}
@java.lang.Override
public io.grpc.examples.bi.BiResult bi(io.grpc.examples.bi.BiLog request) {
return blockingUnaryCall(
channel.newCall(config.bi), request);
}
}
public static class MisBiFutureStub extends
io.grpc.stub.AbstractStub<MisBiFutureStub, MisBiServiceDescriptor>
implements MisBiFutureClient {
private MisBiFutureStub(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
super(channel, config);
}
@java.lang.Override
protected MisBiFutureStub build(io.grpc.Channel channel,
MisBiServiceDescriptor config) {
return new MisBiFutureStub(channel, config);
}
@java.lang.Override
public com.google.common.util.concurrent.ListenableFuture<io.grpc.examples.bi.BiResult> bi(
io.grpc.examples.bi.BiLog request) {
return unaryFutureCall(
channel.newCall(config.bi), request);
}
}
public static io.grpc.ServerServiceDefinition bindService(
final MisBi serviceImpl) {
return io.grpc.ServerServiceDefinition.builder("p.MisBi")
.addMethod(createMethodDefinition(
METHOD_BI,
asyncUnaryRequestCall(
new io.grpc.stub.ServerCalls.UnaryRequestMethod<
io.grpc.examples.bi.BiLog,
io.grpc.examples.bi.BiResult>() {
@java.lang.Override
public void invoke(
io.grpc.examples.bi.BiLog request,
io.grpc.stub.StreamObserver<io.grpc.examples.bi.BiResult> responseObserver) {
serviceImpl.bi(request, responseObserver);
}
}))).build();
}
}
|
1fe9aa27fcb28023951d934d34e248b9be9a6ed2
|
[
"Java"
] | 1
|
Java
|
krystollia/grpc-java
|
17d02a77cf869afed280cdabdb93ee7069d234df
|
2dda8d050cf222c395748a75a72558fdee34ee28
|
refs/heads/master
|
<repo_name>cross-ts/sinatra-example<file_sep>/Dockerfile
FROM ruby:2.5.3-alpine3.8
WORKDIR /app
COPY Gemfile Gemfile.lock /app/
RUN bundle install
COPY . /app
EXPOSE 4567
CMD ./app.rb -o 0.0.0.0
<file_sep>/app.rb
#!/usr/bin/env ruby
%w(sinatra slim).each do |gem|
require gem
end
get '/' do
slim :index
end
|
1f743255cdc5098cd334cc928266b6c81655baf0
|
[
"Ruby",
"Dockerfile"
] | 2
|
Dockerfile
|
cross-ts/sinatra-example
|
9af84d8edc023db417030ec25be3613a719b4cc4
|
d689e0f70507cbb0963750652a6142efbfdeb343
|
refs/heads/master
|
<repo_name>luccawilli/PublicFieldsToProperties<file_sep>/TestProjekt/PublicFieldsToProperties/PublicFieldsToProperties/Program.cs
using System;
using System.Text.RegularExpressions;
namespace PublicFieldsToProperties
{
public class Program
{
private Boolean H = true;
public Boolean s = true;
public String Ps;
public String RS { get; set; }
public static void Main(string[] args)
{
}
}
}
<file_sep>/README.md
# Public Fields To Properties
Konvertiert Public Fields zu Properties
## Danksagung
@schwiaur für seine grosszügige Hilfe
|
7f950c807ee0a563412b9350bfcdeec55fcb02c4
|
[
"Markdown",
"C#"
] | 2
|
C#
|
luccawilli/PublicFieldsToProperties
|
3776a12383d23cd70244f77194cf1b84520d9abd
|
93d82343c35a8c9ccfad6ef8c0df4af91218f44e
|
refs/heads/master
|
<file_sep>package org.de_studio.phonetools;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.IOException;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static final String LOG_TAG = MainActivity.class.getSimpleName();
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private static final int MAIN_LOADER = 0;
MainFragment mainFragment;
DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout =(DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
SharedPreferences sharedPreferences =getSharedPreferences(SettingActivity.defaultSharedPreferenceName, 0);
if (!sharedPreferences.contains("fistLaunch")) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_choose_carrier_title)
.setSingleChoiceItems(R.array.pref_carriers_options, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String[] carrierArray = getResources().getStringArray(R.array.pref_carriers_values);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(SettingActivity.defaultSharedPreferenceName, 0);
sharedPreferences.edit().putString("carrier", carrierArray[which]).putBoolean("fistLaunch",false).commit();
Toast.makeText(getApplicationContext(), "Carrier is : " + carrierArray[which] + " and preference is: " + sharedPreferences.getString("carrier", ""), Toast.LENGTH_LONG).show();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mainFragment.onCarrierChange();
}
});
builder.show();
}
try{
dataBaseHelper.createDataBase();
}catch (IOException e){
throw new Error("Unable to create database");
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabbar);
tabLayout.setupWithViewPager(mViewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingActivity.class));
return true;
}else if (id ==android.R.id.home){
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
mainFragment = MainFragment.newInstance(position + 1);
return mainFragment;
case 1:
return ServicesFragment.newInstance(position + 1);
case 2:
return AdvertisingTabFragment.newInstance(position +1);
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Main".toLowerCase();
case 1:
return "Service".toLowerCase();
case 2:
return "Advertising".toLowerCase();
}
return null;
}
}
@Override
protected void onResume() {
super.onResume();
// DataBaseHelper dataBaseHelper = new DataBaseHelper(getApplicationContext());
// dataBaseHelper.deleteActionTable();
// dataBaseHelper.createActionTable();
// dataBaseHelper.insertActionTable();
this.getContentResolver().notifyChange(PhoneToolsContract.ActionEntry.CONTENT_URI, null);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
}
<file_sep>package org.de_studio.phonetools;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
/**
* Created by hai on 10/15/2015.
*/
public class PhoneToolsProvider extends ContentProvider{
static final int MAIN = 100;
static final int MAIN_WITH_ID = 101;
static final int ACTION = 200;
static final int ACTION_WITH_ID = 201;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final String LOG_TAG = PhoneToolsProvider.class.getSimpleName();
private DataBaseHelper mOpenHelper;
private static final SQLiteQueryBuilder sMainByCarriersSettingQueryBuilder;
private static final SQLiteQueryBuilder sActionByCarriersSettingQueryBuilder;
static{
sMainByCarriersSettingQueryBuilder = new SQLiteQueryBuilder();
//This is an inner join which looks like
//weather INNER JOIN location ON weather.location_id = location._id
sMainByCarriersSettingQueryBuilder.setTables(
PhoneToolsContract.MainEntry.TABLE_NAME + " INNER JOIN " +
PhoneToolsContract.CarriersEntry.TABLE_NAME +
" ON " + PhoneToolsContract.MainEntry.TABLE_NAME +
"." + PhoneToolsContract.MainEntry.COLUMN_CARRIER_ID +
" = " + PhoneToolsContract.CarriersEntry.TABLE_NAME +
"." + PhoneToolsContract.CarriersEntry._ID);
}
static{
sActionByCarriersSettingQueryBuilder = new SQLiteQueryBuilder();
//This is an inner join which looks like
//weather INNER JOIN location ON weather.location_id = location._id
sActionByCarriersSettingQueryBuilder.setTables(
PhoneToolsContract.ActionEntry.TABLE_NAME + " INNER JOIN " +
PhoneToolsContract.CarriersEntry.TABLE_NAME +
" ON " + PhoneToolsContract.ActionEntry.TABLE_NAME +
"." + PhoneToolsContract.ActionEntry.COLUMN_CARRIER_ID +
" = " + PhoneToolsContract.CarriersEntry.TABLE_NAME +
"." + PhoneToolsContract.CarriersEntry._ID);
}
private static final String sIdSelection =
PhoneToolsContract.MainEntry.TABLE_NAME +
"." + PhoneToolsContract.MainEntry._ID + " = ? ";
private static final String sIdInActionSelection =
PhoneToolsContract.ActionEntry.TABLE_NAME +
"." + PhoneToolsContract.ActionEntry._ID + " = ? ";
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
switch (match) {
// Student: Uncomment and fill out these two cases
case MAIN_WITH_ID:
return PhoneToolsContract.MainEntry.CONTENT_ITEM_TYPE;
case MAIN:
return PhoneToolsContract.MainEntry.CONTENT_TYPE;
case ACTION:
return PhoneToolsContract.ActionEntry.CONTENT_TYPE;
case ACTION_WITH_ID:
return PhoneToolsContract.ActionEntry.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case MAIN:
rowsUpdated = db.update(PhoneToolsContract.MainEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
case ACTION:
rowsUpdated = db.update(PhoneToolsContract.ActionEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case MAIN:
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
long _id = db.insert(PhoneToolsContract.MainEntry.TABLE_NAME, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
default:
return super.bulkInsert(uri, values);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match){
case (MAIN):{
long _id = db.insert(PhoneToolsContract.MainEntry.TABLE_NAME, null, values);
if (_id>0) {
returnUri = PhoneToolsContract.MainEntry.buildMainUri(_id);
}else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
case ACTION : {
long _id = db.insert(PhoneToolsContract.ActionEntry.TABLE_NAME, null, values);
if (_id>0) {
returnUri = PhoneToolsContract.ActionEntry.buildActionUri(_id);
}else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public boolean onCreate() {
mOpenHelper = new DataBaseHelper(getContext());
try {
mOpenHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
// try {
// mOpenHelper.openDataBase();
//
// } catch (SQLException sqle) {
//
// throw sqle;
// }
return true;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor reCursor;
switch (sUriMatcher.match(uri)){
case (MAIN):{
// reCursor = mOpenHelper.getReadableDatabase().query(
// PhoneToolsContract.MainEntry.TABLE_NAME,
// projection,
// selection,
// selectionArgs,
// null,
// null,
// sortOrder
// );
reCursor = sMainByCarriersSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
case ACTION: {
reCursor = sActionByCarriersSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
case (MAIN_WITH_ID):{
reCursor = getMainById(uri,projection,sortOrder);
break;
}
case ACTION_WITH_ID: {
reCursor = getActionById(uri,projection,sortOrder);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
reCursor.setNotificationUri(getContext().getContentResolver(), uri);
return reCursor;
}
private Cursor getMainById(
Uri uri, String[] projection, String sortOrder) {
long id = PhoneToolsContract.MainEntry.getIdFromUri(uri);
return sMainByCarriersSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sIdSelection,
new String[]{Long.toString(id)},
null,
null,
sortOrder
);
}
private Cursor getActionById(Uri uri, String[] projection, String sortOrder){
long id = PhoneToolsContract.ActionEntry.getIdFromUri(uri);
return sActionByCarriersSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sIdInActionSelection,
new String[]{Long.toString(id)},
null,
null,
sortOrder
);
}
static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = PhoneToolsContract.CONTENT_AUTHORITY;
matcher.addURI(authority,PhoneToolsContract.PATH_MAIN,MAIN);
matcher.addURI(authority,PhoneToolsContract.PATH_MAIN + "/#",MAIN_WITH_ID);
matcher.addURI(authority,PhoneToolsContract.PATH_ACTION,ACTION);
matcher.addURI(authority,PhoneToolsContract.PATH_ACTION + "/#",ACTION_WITH_ID);
return matcher;
}
public boolean move(int i, int i1){
i = i +1;
i1 = i1 +1;
Log.e(LOG_TAG, "i = "+ i + " i1 = "+ i1 );
int rows;
Cursor rowsCursor;
rowsCursor = query(PhoneToolsContract.ActionEntry.CONTENT_URI,null,null,null,null);
rows = rowsCursor.getCount();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Cursor cursor;
cursor = query(PhoneToolsContract.ActionEntry.buildActionUri(i),MainFragment.PHONE_TOOLS_COLUMNS,null,null,null);
Log.e(LOG_TAG, "count of cursor is " + cursor.getCount());
ContentValues contentValues = new ContentValues();
cursor.moveToFirst();
DatabaseUtils.cursorRowToContentValues(cursor, contentValues);
db.delete(PhoneToolsContract.ActionEntry.TABLE_NAME, "_id = ?", new String[]{i + ""});
// db.rawQuery("UPDATE " + PhoneToolsContract.MainEntry.TABLE_NAME + " SET _id = _id - 1 WHERE _id > ? ", new String[]{i + ""});
for (int t= i+1;t<= rows; t++){
Cursor tempCursor = query(PhoneToolsContract.ActionEntry.buildActionUri(t),MainFragment.PHONE_TOOLS_COLUMNS,null,null,null);
tempCursor.moveToFirst();
ContentValues tempContent= new ContentValues();
DatabaseUtils.cursorRowToContentValues(tempCursor, tempContent);
tempContent.remove("_id");
tempContent.remove("carrier_name");
tempContent.put("_id",t-1);
db.update(PhoneToolsContract.ActionEntry.TABLE_NAME,tempContent,"_id = ? ",new String[] {t+""});
}
// db.rawQuery("UPDATE " + PhoneToolsContract.MainEntry.TABLE_NAME + " SET _id = _id + 1 WHERE _id >= ? ", new String[]{i1 + ""});
for (int t =rows - 1;t>= i1; t--){
Cursor tempCursor = query(PhoneToolsContract.ActionEntry.buildActionUri(t),MainFragment.PHONE_TOOLS_COLUMNS,null,null,null);
tempCursor.moveToFirst();
ContentValues tempContent= new ContentValues();
DatabaseUtils.cursorRowToContentValues(tempCursor, tempContent);
tempContent.remove("_id");
tempContent.remove("carrier_name");
tempContent.put("_id",t+1);
db.update(PhoneToolsContract.ActionEntry.TABLE_NAME,tempContent,"_id = ? ",new String[] {t+""});
}
Log.e(LOG_TAG, "_id = " + contentValues.getAsString("_id"));
// contentValues.remove("_id");
contentValues.remove("carrier_name");
contentValues.remove("_id");
contentValues.put("_id",i1);
// Cursor cursor1 = db.rawQuery("SELECT seq FROM sqlite_sequence WHERE name=?",
// new String[] { "main" });
// int last = (cursor1.moveToFirst() ? cursor1.getInt(0) : 0);
// Log.e(LOG_TAG, "number of rows is " +last);
Uri uri = insert(PhoneToolsContract.ActionEntry.CONTENT_URI, contentValues);
Log.e(LOG_TAG, "Uri of last insert is " + uri.toString());
// db.rawQuery("UPDATE " + PhoneToolsContract.MainEntry.TABLE_NAME + " SET _id = ? WHERE _id = ? ", new String[]{i1 + "",last +""});
getContext().getContentResolver().notifyChange(PhoneToolsContract.ActionEntry.CONTENT_URI, null);
return true;
}
@Override
public Bundle call(String method, String arg, Bundle extras) {
if (method.equals("move")){
move(extras.getInt("i"),extras.getInt("i1"));
}
return super.call(method, arg, extras);
}
}
<file_sep>package org.de_studio.phonetools;
/**
* Created by hai on 10/13/2015.
*/
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class ServicesFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
ArrayList<String> list;
private static final int SERVICE_LOADER =2;
private int mListLevel;
private String mCategory;
private ItemDetailAdapter itemDetailAdapter;
private static final String ARG_SECTION_NUMBER = "section_number";
public static ServicesFragment newInstance(int sectionNumber) {
ServicesFragment fragment = new ServicesFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<String>();
list.add(getString(R.string.list_goi_nhan_tin));
list.add(getString(R.string.list_3g));
list.add(getString(R.string.list_tien_ich));
mListLevel = 1;
setListAdapter(new ArrayAdapter<String>(
getActivity(),
R.layout.fragment_item_list,
R.id.item_list_item,
list));
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v =inflater.inflate(R.layout.fragment_services,container,false);
// return v;
// }
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (mListLevel == 1) {
switch (position) {
case 0: {
mCategory = "gn";
break;
}
case 1: {
mCategory = "3g";
break;
}
case 2: {
mCategory = "ti";
break;
}
}
itemDetailAdapter = new ItemDetailAdapter(getActivity(),null,0);
setListAdapter(itemDetailAdapter);
mListLevel = 2;
getLoaderManager().initLoader(SERVICE_LOADER,null,this);
}else if (mListLevel==2){
Cursor cursor = itemDetailAdapter.getCursor();
cursor.moveToPosition(position);
String message = cursor.getString(ItemDetailFragment.COL_MAIN_DESCRIPTION);
String title = cursor.getString(ItemDetailFragment.COL_MAIN_TITLE);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message)
.setTitle(title)
.setPositiveButton("Đăng ký", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNeutralButton("Hủy DV", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
itemDetailAdapter.swapCursor(null);
String sortOrder = PhoneToolsContract.MainEntry.TABLE_NAME + "." + PhoneToolsContract.MainEntry._ID + " ASC";
String selection = " category = ? AND carrier_name = ? ";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String[] selectionAgrm = new String[]{mCategory ,prefs.getString("carrier", "viettel")};
return new CursorLoader(getActivity(),
PhoneToolsContract.MainEntry.CONTENT_URI,
ItemDetailFragment.PHONE_TOOLS_COLUMNS,
selection,
selectionAgrm,
sortOrder); }
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
itemDetailAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader loader) {
itemDetailAdapter.swapCursor(null);
}
}
<file_sep>package org.de_studio.phonetools;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by hai on 10/15/2015.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/org.de_studio.phonetools/databases/";
private static String DB_NAME = "phonetools.db";
private static String mMyPath = DB_PATH + DB_NAME;
private SQLiteDatabase myDataBase;
private final Context myContext;
private static final String LOG_TAG = DataBaseHelper.class.getSimpleName();
private static final String selectColumnToInsert = " "+
PhoneToolsContract.ActionEntry.COLUMN_TYPE +", "+
PhoneToolsContract.ActionEntry.COLUMN_DESTINATION + ", "+
PhoneToolsContract.ActionEntry.COLUMN_TITLE + ", " +
PhoneToolsContract.ActionEntry.COLUMN_DESCRIPTION + ", "+
PhoneToolsContract.ActionEntry.COLUMN_CARRIER_ID + ", "+
PhoneToolsContract.ActionEntry.COLUMN_TEXT + ", " +
PhoneToolsContract.ActionEntry.COLUMN_CANCEL + ", " +
PhoneToolsContract.ActionEntry.COLUMN_MONEY + ", " +
PhoneToolsContract.ActionEntry.COLUMN_CYCLE + ", " +
PhoneToolsContract.ActionEntry.COLUMN_IN_MAIN + " ";
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException {
// SQLiteDatabase db;
// String myPath = DB_PATH + DB_NAME;
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
Log.e(LOG_TAG,"dbexist ");
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
Log.e(LOG_TAG, "create and insert action table ");
// db = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
createActionTable();
// insertActionTable();
} catch (IOException e) {
Log.e(LOG_TAG,"copping database err");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
Log.e(LOG_TAG,"database doesn't exist yet");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void changeCarrier(int carrierId){
}
public void createActionTable(){
SQLiteDatabase db;
db = SQLiteDatabase.openDatabase(mMyPath,null,SQLiteDatabase.OPEN_READWRITE);
final String SQL_CREATE_ACTION_TABLE = "CREATE TABLE " + PhoneToolsContract.ActionEntry.TABLE_NAME + " (" +
PhoneToolsContract.ActionEntry._ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
PhoneToolsContract.ActionEntry.COLUMN_TYPE + " INTEGER NOT NULL, " +
PhoneToolsContract.ActionEntry.COLUMN_DESTINATION + " TEXT NOT NULL, " +
PhoneToolsContract.ActionEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
PhoneToolsContract.ActionEntry.COLUMN_SHORT_DESCRIPTION + " TEXT DEFAULT null," +
PhoneToolsContract.ActionEntry.COLUMN_DESCRIPTION + " TEXT DEFAULT null," +
PhoneToolsContract.ActionEntry.COLUMN_CARRIER_ID + " INTEGER NOT NULL, " +
PhoneToolsContract.ActionEntry.COLUMN_TEXT + " TEXT DEFAULT null, " +
PhoneToolsContract.ActionEntry.COLUMN_CANCEL + " TEXT, " +
PhoneToolsContract.ActionEntry.COLUMN_MONEY + " REAL, " +
PhoneToolsContract.ActionEntry.COLUMN_CYCLE + " TEXT, " +
PhoneToolsContract.ActionEntry.COLUMN_IN_MAIN + " INTEGER NOT NULL, " +
PhoneToolsContract.ActionEntry.COLUMN_CATEGORY + " TEXT, " +
" FOREIGN KEY (" + PhoneToolsContract.ActionEntry.COLUMN_CARRIER_ID + ") REFERENCES " +
PhoneToolsContract.CarriersEntry.TABLE_NAME + " (" + PhoneToolsContract.CarriersEntry._ID + ")" + ");";
db.execSQL(SQL_CREATE_ACTION_TABLE);
}
public void insertActionTable (){
SQLiteDatabase db;
int carrierId = 3;
SharedPreferences sharedPreferences = myContext.getSharedPreferences(SettingActivity.defaultSharedPreferenceName, 0);
if (sharedPreferences.contains("carrier")){
Log.e(LOG_TAG,"there are a carrier preference " + sharedPreferences.toString());
}
switch (sharedPreferences.getString("carrier","")){
case "viettel" :{
carrierId=1;
break;
}
case "vinaphone":{
carrierId = 2;
break;
}
case "mobifone":{
carrierId = 3;
break;
}
case "vietnamobile":{
carrierId= 4;
break;
}
}
Log.e(LOG_TAG," insert database nay");
db = SQLiteDatabase.openDatabase(mMyPath,null,SQLiteDatabase.OPEN_READWRITE);
final String SQL_INSERT_ACTION_TABLE = "INSERT INTO " + PhoneToolsContract.ActionEntry.TABLE_NAME +
" SELECT * FROM "+
PhoneToolsContract.MainEntry.TABLE_NAME + " WHERE "+ PhoneToolsContract.MainEntry.COLUMN_CARRIER_ID
+ " = " + carrierId + " AND " + PhoneToolsContract.MainEntry.COLUMN_IN_MAIN +
" >= " + 1 + " ;"
;
// final String SQL_INSERT_ID_COLUMN = "ALTER TABLE " + PhoneToolsContract.ActionEntry.TABLE_NAME + " ADD COLUMN " +
// PhoneToolsContract.ActionEntry._ID + " INTEGER NOT NULL AUTOINCREMENT ;";
db.execSQL(SQL_INSERT_ACTION_TABLE);
// db.execSQL(SQL_INSERT_ID_COLUMN);
String sql = "SELECT COUNT(*) FROM " + PhoneToolsContract.ActionEntry.TABLE_NAME;
SQLiteStatement statement = db.compileStatement(sql);
Long count = statement.simpleQueryForLong();
Cursor cursor = db.query(PhoneToolsContract.ActionEntry.TABLE_NAME,null,null,null,null,null,null);
cursor.moveToFirst();
int i =1;
do {
int oldIndex = cursor.getInt(0);
ContentValues contentValues = new ContentValues();
contentValues.put("_id",i);
db.update(PhoneToolsContract.ActionEntry.TABLE_NAME,contentValues," _id = ? ", new String[]{oldIndex + ""});
i++;
}while (cursor.moveToNext());
}
public void deleteActionTable(){
SQLiteDatabase db;
db = SQLiteDatabase.openDatabase(mMyPath,null,SQLiteDatabase.OPEN_READWRITE);
db.execSQL("DROP TABLE "+ PhoneToolsContract.ActionEntry.TABLE_NAME);
}
}
<file_sep>package org.de_studio.phonetools;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.Toast;
public class ItemDetailActivity extends AppCompatActivity {
public Integer mPosition;
private static final String LOG_TAG = ItemDetailActivity.class.getSimpleName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
mPosition = getIntent().getIntExtra(ItemDetailFragment.ARG_ITEM_ID, 1);
Toast.makeText(this," mPosition =" + mPosition,Toast.LENGTH_SHORT).show();
ItemDetailFragment itemDetailFragment = (ItemDetailFragment) getSupportFragmentManager().findFragmentById(R.id.item_detail_container);
itemDetailFragment.setPosition(mPosition);
}
// Bundle bundle = new Bundle();
// bundle.putInt("position", mPosition);
// ItemDetailFragment itemDetailFragment = (ItemDetailFragment) getSupportFragmentManager().findFragmentById(R.id.item_detail_container);
//
// itemDetailFragment.setArguments(bundle);
// if (itemDetailFragment == null){
// Log.e(LOG_TAG, " null itemDetailFragment");
// }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package org.de_studio.phonetools;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by hai on 10/15/2015.
*/
public class PhoneToolsContract {
public static final String CONTENT_AUTHORITY = "org.de_studio.phonetools";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_MAIN = "main";
public static final String PATH_ACTION = "action";
public static final String PATH_CARRIERS = "carriers";
public static final class MainEntry implements BaseColumns{
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_MAIN).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MAIN;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MAIN;
public static final String TABLE_NAME = "main";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_SHORT_DESCRIPTION = "short_description";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_CARRIER_ID = "carrier_id";
public static final String COLUMN_TEXT = "text";
public static final String COLUMN_CANCEL = "cancel";
public static final String COLUMN_MONEY = "money";
public static final String COLUMN_CYCLE = "_cycle";
public static final String COLUMN_IN_MAIN = "in_main";
public static final String COLUMN_CATEGORY = "category";
public static long getIdFromUri(Uri uri) {
return Long.parseLong(uri.getPathSegments().get(1));
}
public static Uri buildMainUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
public static final class ActionEntry implements BaseColumns{
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ACTION).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_ACTION;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_ACTION;
public static final String TABLE_NAME = "action";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_DESTINATION = "destination";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_SHORT_DESCRIPTION = "short_description";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_CARRIER_ID = "carrier_id";
public static final String COLUMN_TEXT = "text";
public static final String COLUMN_CANCEL = "cancel";
public static final String COLUMN_MONEY = "money";
public static final String COLUMN_CYCLE = "_cycle";
public static final String COLUMN_IN_MAIN = "in_main";
public static final String COLUMN_CATEGORY = "category";
public static long getIdFromUri(Uri uri) {
return Long.parseLong(uri.getPathSegments().get(1));
}
public static Uri buildActionUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
}
public static final class CarriersEntry implements BaseColumns{
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_CARRIERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CARRIERS;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CARRIERS;
public static final String TABLE_NAME = "carriers";
public static final String COLUMN_CARRIER_NAME = "carrier_name";
}
}
|
72c37556eadd9d513bf72329978e1180d11d5487
|
[
"Java"
] | 6
|
Java
|
thanhhai08sk/phoneTools
|
f056a1751828952bf49cb4bf2871a6c6cf3125a5
|
fe4663d00e9372d35209f62ba5ed65a9b6611c2d
|
refs/heads/main
|
<repo_name>stkudryashov/netology-decorators<file_sep>/decorators.py
import requests
import hashlib
import datetime
def logger(path):
def inner(func):
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
with open(path, 'a', encoding='utf-8') as f:
time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
line = [time, func.__name__, args, kwargs, result]
f.write(str(line) + '\n')
return result
return wrapped
return inner
@logger('logs.txt')
def plus(a, b):
return a + b
@logger('logs.txt')
def get_page(link):
response = requests.get(link)
return response.status_code
@logger('logs.txt')
def hash_this(string):
return hashlib.md5(string.encode('utf-8')).hexdigest()
def main():
print(plus(4, 5))
print(get_page('https://google.com'))
print(hash_this('pls hash this string'))
if __name__ == '__main__':
main()
<file_sep>/README.md
# netology-decorators
Study task in Netology
|
c47a618e32661aca96ef9400c0bb383865df51fe
|
[
"Markdown",
"Python"
] | 2
|
Python
|
stkudryashov/netology-decorators
|
821da2502d85f838367bbcd2457f5d9e41b91959
|
3c4f313a3deb175819fe8877647b000225b42c0b
|
refs/heads/master
|
<file_sep>#!/bin/bash
cd $TOMCAT_HOME/bin
./shutdown.sh
cd $SCRABBLE_MANIA_HOME
mvn clean install
rm -r $TOMCAT_HOME/webapps/scrabble-mania
rm $TOMCAT_HOME/webapps/scrabble-mania.war
cp $SCRABBLE_MANIA_HOME/target/scrabble-mania.war $TOMCAT_HOME/webapps/scrabble-mania.war
cd $TOMCAT_HOME/bin
./startup.sh
|
96636e09c217f2719cd2f0a03b546c75aa6b1a93
|
[
"Shell"
] | 1
|
Shell
|
tomstalk/Scrabble-Mania
|
f513a272f44e06f9a73ca3daa1e71f77ecd0d485
|
7065cab0a87c195871d112e06f7b1e8075c723ce
|
refs/heads/master
|
<repo_name>LucasRoesler/golang-http-template<file_sep>/template/golang-http/go.mod
module handler
go 1.18
require github.com/openfaas/templates-sdk/go-http v0.0.0-20220408082716-5981c545cb03
<file_sep>/README.md
# OpenFaaS Golang HTTP templates
This repository contains two Golang templates for OpenFaaS which give additional control over the HTTP request and response. They will both handle higher throughput than the classic watchdog due to the process being kept warm.
Our recommended template for Go developers is golang-middleware.
You'll find a chapter dedicated to writing functions with Go in [Everyday Golang by <NAME>](https://store.openfaas.com/l/everyday-golang)
Using the templates:
```bash
faas-cli template store pull golang-http
faas-cli template store pull golang-middleware
```
Or:
```bash
$ faas template pull https://github.com/openfaas/golang-http-template
$ faas new --list
Languages available as templates:
- golang-http
- golang-middleware
```
The two templates are very similar:
* `golang-middleware` implements a `http.HandleFunc` from Go's stdlib.
* `golang-http` uses a structured request/response object
## Dependencies
You can manage dependencies in one of the following ways:
- To use Go modules without vendoring, the default already is set `GO111MODULE=on` but you also can make that explicit by adding `--build-arg GO111MODULE=on` to `faas-cli up`, you can also use `--build-arg GOPROXY=https://` if you want to use your own mirror for the modules
- You can also Go modules with vendoring, run `go mod vendor` in your function folder and add `--build-arg GO111MODULE=off --build-arg GOFLAGS='-mod=vendor'` to `faas-cli up`
- If you have a private module dependency, we recommend using the vendoring technique from above.
### SSH authentication for private Git repositories and modules
If you do not wish to, or cannot use vendoring for some reason, then we provide an alternative set of templates for OpenFaaS Pro customers:
* [OpenFaaS Pro templates for Go](https://github.com/openfaas/pro-templates)
## 1.0 golang-middleware (recommended template)
This is one of the fastest templates available for Go available. Its signature is a [http.HandlerFunc](https://golang.org/pkg/net/http/#HandlerFunc), instead of a traditional request and response that you may expect from a function.
The user has complete control over the HTTP request and response.
### Get the template
```
$ faas template store pull golang-middleware
# Or
$ faas template pull https://github.com/openfaas/golang-http-template
$ faas new --lang golang-middleware <fn-name>
```
### Example usage
Example writing a JSON response:
```go
package function
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func Handle(w http.ResponseWriter, r *http.Request) {
var input []byte
if r.Body != nil {
defer r.Body.Close()
// read request payload
reqBody, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
input = reqBody
}
}
// log to stdout
fmt.Printf("request body: %s", string(input))
response := struct {
Payload string `json:"payload"`
Headers map[string][]string `json:"headers"`
Environment []string `json:"environment"`
}{
Payload: string(input),
Headers: r.Header,
Environment: os.Environ(),
}
resBody, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// write result
w.WriteHeader(http.StatusOK)
w.Write(resBody)
}
```
Example persistent database connection pool between function calls:
```go
package function
import (
"database/sql"
"fmt"
"io"
"net/http"
"strings"
_ "github.com/go-sql-driver/mysql"
)
// db pool shared between function calls
var db *sql.DB
func init() {
var err error
db, err = sql.Open("mysql", "user:password@/dbname")
if err != nil {
panic(err.Error())
}
err = db.Ping()
if err != nil {
panic(err.Error())
}
}
func Handle(w http.ResponseWriter, r *http.Request) {
var query string
ctx := r.Context()
if r.Body != nil {
defer r.Body.Close()
// read request payload
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
query = string(body)
}
// log to stdout
fmt.Printf("Executing query: %s", query)
rows, err := db.QueryContext(ctx, query)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
ids := make([]string, 0)
for rows.Next() {
if e := ctx.Err(); e != nil {
http.Error(w, e, http.StatusBadRequest)
return
}
var id int
if err := rows.Scan(&id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ids = append(ids, string(id))
}
if err := rows.Err(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result := fmt.Sprintf("ids %s", strings.Join(ids, ", "))
// write result
w.WriteHeader(http.StatusOK)
w.Write([]byte(result))
}
```
Example retrieving request query strings
```go
package function
import (
"fmt"
"net/http"
)
func Handle(w http.ResponseWriter, r *http.Request) {
// Parses RawQuery and returns the corresponding
// values as a map[string][]string
// for more info https://golang.org/pkg/net/url/#URL.Query
query := r.URL.Query()
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("id: %s", query.Get("id"))))
}
```
### Adding static files to your image
If a folder named `static` is found in the root of your function's source code, **it will be copied** into the final image published for your function.
To read this back at runtime, you can do the following:
```go
package function
import (
"net/http"
"os"
)
func Handle(w http.ResponseWriter, r *http.Request) {
data, err := os.ReadFile("./static/file.txt")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Write(data)
}
```
## 2.0 golang-http
This template provides additional context and control over the HTTP response from your function.
### Status of the template
Like the `golang-middleware` template, this template is highly performant and suitable for production.
### Get the template
```sh
$ faas template store pull golang-http
# Or
$ faas template pull https://github.com/openfaas/golang-http-template
$ faas new --lang golang-http <fn-name>
```
### Example usage
Example writing a successful message:
```go
package function
import (
"fmt"
"net/http"
handler "github.com/openfaas/templates-sdk/go-http"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
message := fmt.Sprintf("Hello world, input was: %s", string(req.Body))
return handler.Response{
Body: []byte(message),
}, err
}
```
Example writing a custom status code
```go
package function
import (
"fmt"
"net/http"
handler "github.com/openfaas/templates-sdk/go-http"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
return handler.Response{
Body: []byte("Your workload was accepted"),
StatusCode: http.StatusAccepted,
}, err
}
```
Example writing an error / failure.
```go
package function
import (
"fmt"
"net/http"
handler "github.com/openfaas/templates-sdk/go-http"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
return handler.Response{
Body: []byte("the input was invalid")
}, fmt.Errorf("invalid input")
}
```
The error will be logged to `stderr` and the `body` will be written to the client along with a HTTP 500 status code.
Example reading a header.
```go
package function
import (
"log"
handler "github.com/openfaas/templates-sdk/go-http"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
log.Println(req.Header) // Check function logs for the request headers
return handler.Response{
Body: []byte("This is the response"),
Header: map[string][]string{
"X-Served-By": []string{"My Awesome Function"},
},
}, err
}
```
Example responding to an aborted request.
The `Request` object provides access to the request context. This allows you to check if the request has been cancelled by using the context's done channel `req.Context().Done()` or the context's error `req.Context().Err()`
```go
package function
import (
"fmt"
"net/http"
handler "github.com/openfaas/templates-sdk/go-http"
)
// Handle a function invocation
func Handle(req handler.Request) (handler.Response, error) {
var err error
for i := 0; i < 10000; i++ {
if req.Context().Err() != nil {
return handler.Response{}, fmt.Errorf("request cancelled")
}
fmt.Printf("count %d\n", i)
}
message := fmt.Sprintf("Hello world, input was: %s", string(req.Body))
return handler.Response{
Body: []byte(message),
StatusCode: http.StatusOK,
}, err
}
```
This context can also be passed to other methods so that they can respond to the cancellation as well, for example [`db.ExecContext(req.Context())`](https://golang.org/pkg/database/sql/#DB.ExecContext)
#### Advanced usage
##### Sub-packages
It is often natural to organize your code into sub-packages, for example you may have a function with the following structure
```
./echo
├── go.mod
├── go.sum
├── handler.go
└── pkg
└── version
└── version.go
```
Now if you want to reference the`version` sub-package, import it as
```go
import "handler/function/pkg/version"
```
This works like any local Go project.
##### Go sub-modules
Sub-modules (meaning sub-folders with a `go.mod`) are not supported.
<file_sep>/template/golang-http/modules-cleanup.sh
#!/usr/bin/env sh
set -e
GO111MODULE=$(go env GO111MODULE)
[ -z "$DEBUG" ] && DEBUG=0
# move_vendor will copy the function's vendor folder,
# if it exists.
move_vendor() {
if [ ! -d ./function/vendor ]; then
echo "vendor not found"
return
fi
echo "moving function vendor"
mv -f ./function/vendor .
}
# cleanup_gomod will move the function's go module
cleanup_gomod() {
# Nothing to do when modules is explicitly off
# the z prefix protects against any SH wonkiness
# see https://stackoverflow.com/a/18264223
if [ "z$GO111MODULE" = "zoff" ]; then
echo "modules disabled, skipping go.mod cleanup"
return;
fi
if [ ! -f ./function/go.mod ]; then
echo "module not initialized, skipping go.mod cleanup"
return;
fi
echo "cleaning up go.mod"
# Copy the user's go.mod
mv -f ./function/go.mod .
mv -f ./function/go.sum .
# Clean up the go.mod
# Cleanup any sub-module replacements.
# This requires modifying any replace that points to "./*",
# the user has will use this to reference sub-modules instead
# of sub-packages, which we cleanup below.
echo "cleanup local replace statements"
# 1. Replace references to the local folder with `./function`
sed -i 's/=> \.\//=> \.\/function\//' go.mod
# Remove any references to the handler/function module.
# It is ok to just remove it because we will replace it later.
#
# Note that these references may or may not exist. We expect the
# go.mod to have a replace statement _if_ developer has subpackages
# in their handler. In this case they will need a this replace statement
#
# replace handler/function => ./
#
# `go mod` will then add a line that looks like
#
# handler/function v0.0.0-00010101000000-000000000000
#
# both of these lines need to be replaced, this grep selects everything
# _except_ those offending lines.
grep -v "\shandler/function" go.mod > gomod2; mv gomod2 go.mod
# Now update the go.mod
#
# 1. use replace so that imports of handler/function use the local code
# 2. we need to rename the module to handler because our main.go assumes
# this is the package name
go mod edit \
-replace=handler/function=./function \
-module handler
if [ "$DEBUG" -eq 1 ]; then
cat go.mod
echo ""
fi
}
# cleanup_vendor_modulestxt will cleanup the modules.txt file in the vendor folder
# this file is needed when modules are enabled and it must be in sync with the
# go.mod. To function correctly we need to modify the references to handler/function,
# if they exist.
cleanup_vendor_modulestxt() {
if [ ! -d ./vendor ]; then
echo "no vendor found, skipping modules.txt cleanup"
return
fi
# Nothing to do when modules is explicitly off
# the z prefix protects against any SH wonkiness
# see https://stackoverflow.com/a/18264223
if [ "z$GO111MODULE" = "zoff" ]; then
echo "modules disabled, skipping modules.txt cleanup"
return;
fi
echo "cleanup vendor/modules.txt"
# just in case
touch "./vendor/modules.txt"
# when vendored, we need to do similar edits to the vendor/modules.txt
# as we did to the go.mod
# 1. we need to replace any possible copy of the handler code
rm -rf vendor/handler && \
# 2. in modules.txt, we remove existing references to the handler/function
# we reconstruct these in the last step
grep -v "\shandler/function" ./vendor/modules.txt> modulestext; mv modulestext ./vendor/modules.txt
# 3. Handle any other local replacements.
# any replace that points to `./**` needs to be udpat echo "cleanup local replace statements"
sed -i 's/=> \.\//=> \.\/function\//' ./vendor/modules.txt
# 4. To make the modules.txt consistent with the new go.mod,
# we add the mising replace to the vendor/modules.txt
echo "## explicit" >> ./vendor/modules.txt
echo "# handler/function => ./function" >> ./vendor/modules.txt
if [ "$DEBUG" -eq 1 ]; then
cat ./vendor/modules.txt;
echo ""
fi
}
# has_local_replacement checks if the file contains local go module replacement
has_local_replacement() {
return "$(grep -E -c '=> \./\S+' "$1")"
}
################
# main
################
move_vendor
cleanup_gomod
cleanup_vendor_modulestxt
<file_sep>/template/golang-http/function/go.mod
module handler/function
go 1.18
require github.com/openfaas/templates-sdk/go-http v0.0.0-20220408082716-5981c545cb03
<file_sep>/template/golang-middleware/function/go.mod
module handler/function
go 1.18
|
3b2ab32b701bbc8db8839d8975c4bf8d9dff85e5
|
[
"Markdown",
"Go Module",
"Shell"
] | 5
|
Go Module
|
LucasRoesler/golang-http-template
|
e3d205eb26280a09c31236dcede937dff9882836
|
c887124acb88559e3590d01a53e00c8e18e64751
|
refs/heads/master
|
<repo_name>CodeXMakerCompany/phpMasterBasics<file_sep>/principiosPHP/14-arrays/index.php
<?php
/*
Arrays
Un array es un conjunto de datos/valores bajo un unico nombre.
Para acceder a esos valores podemos usar un indice numero o alfanumerico.
*/
$pelicula ="Batman";
$peliculas = array('Batman','Spiderman','Thor');
$cantantes = ['SakiFujita', "Drake", "SamPadrul"];
echo "<h1>Array asociativo</h1>";
#array asociativo
$personas = array(
'nombre' => 'Samuel',
'apellidos' => '<NAME>',
'web' => 'codexmaker.com'
);
echo $personas['apellidos'];
//for: recorrer array
echo "<h1>Listado de peliculas</h1>";
echo "<ul>";
for ($i=0; $i < count($peliculas); $i++) {
echo "<li>".$peliculas[$i]."</li>";
}
echo "</ul>";
//foreach: recorrer arrays + *preferido*
echo "<br>";
echo "<h1>Listado de cantantes con for each</h1>";
echo "<ul>";
#recorre todo el array y por cada valor genera una variable independiente
foreach ($cantantes as $cantante) {
echo "<li>".$cantante."</li>";
}
echo "</ul>";
echo "<br>";
//arrays multidimensionales
echo "<h1>Listado de array multidimensional</h1>";
$contactos = array(
array(
'nombre' => 'Samuel',
'email' => '<EMAIL>',
'web' => 'codexmaker.com'
),
array(
'nombre' => 'miku',
'email' => '<EMAIL>',
'web' => 'miku.com'
),
array(
'nombre' => 'ayanami',
'email' => '<EMAIL>',
'web' => 'ayanami.com'
),
);
echo "<ul>";
foreach ($contactos as $key => $contacto) {
echo "<li>".$contacto['nombre']."</li>";
}
echo "</ul>";
?><file_sep>/principiosPHP/11-ejercicios/ejercicio2.php
<?php
/*
Sacar todos los numero pares del 1 al 100
*/
for ($i=1; $i <=100 ; $i++) {
#cuando la division entre 2 sea exacta
if ($i%2 == 0) {
echo $i."<br>";
}
}
?><file_sep>/mysqlYphp/index.php
<?php
//Conectar a la BD
$conexion = mysqli_connect("localhost", "root", "", "redsocial");
//Comprobar si la conexion es correcta
if (mysqli_connect_errno()) {
echo "La conexion a la BD ha fallado : ".mysql_connect_error();
}else{
echo "conexion exitosa"."<br>";
}
// Consulta para configurar la codificacion de caracteres
mysqli_query($conexion, "SET NAMES 'utf8'");
// Consulta SELECT desde PHP
$query = mysqli_query($conexion, "SELECT * FROM profile");
// Traer todos los datos
$profile = mysqli_fetch_all($query);
var_dump(count($profile));
//Insertar en la base de datos desde PHP
/*$sql = "INSERT INTO profile VALUES(NULL, 'diana', 'ruiz', '<EMAIL>', '12345', 'codexmaker', 'foto/');";
$insert = mysqli_query($conexion, $sql);
if ($insert) {
echo "Datos insertados corectamente";
}else{
echo "Error: ".mysql_error($conexion);
}*/
?><file_sep>/principiosPHP/18-formularios/index.php
<?php
/*
Formulario
*/
?>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Formulario PHP y Html</title>
</head>
<h1>Formulario</h1>
<form action="" method="POST" enctype="multipart/form-data">
<label for="nombre">Nombre :</label>
<p><input type="text" name="nombre" autofocus="autofocus" maxlength="10" placeholder="Ingresa tu nombre" /></p>
<label for="apellido">Apellido:</label>
<p><input type="text" name="apellido" minlength="4" required="required" placeholder="Ingresa tu apellido" /></p>
<label for="boton">Botón: </label>
<p><input type="button" name="boton" value="Clickame" /></p>
<label for="sexo">Sexo:</label>
<p>
Hombre <input type="checkbox" name="sexo" value="Masculino" />
Mujer <input type="checkbox" name="sexo" value="Femenino" />
</p>
<label for="color">Color:</label>
<p><input type="color" name="color" /></p>
<label for="fecha">Fecha:</label>
<p><input type="date" name="fecha" /></p>
<label for="correo">Email:</label>
<p><input type="email" name="correo" /></p>
<label for="archivo">File:</label>
<p><input type="file" name="archivo" multiple="multiple" /></p>
<label for="numero">Numero:</label>
<p><input type="number" name="numero" /></p>
<label for="pass">Contraseña:</label>
<p><input type="password" name="pass" /></p>
<label for="continente">Continente:</label>
<p>
Sudamerica<input type="radio" name="continente" value="America del Sur" />
<br>
America del norte<input type="radio" name="continente" value="America del Norte" />
<br>
Centroamerica<input type="radio" name="continente" value="America del Centro" />
<br>
Europa<input type="radio" name="continente" value="Europa" />
<br>
Asia<input type="radio" name="continente" value="Asia" />
</p>
<label for="web">Pagina web:</label>
<p><input type="url" name="web" /></p>
<textarea name="" id="" cols="30" rows="10"></textarea>
<br>
Peliculas:
<select name="peliculas" id="">
<option value="Spiderman">Spiderman</option>
<option value="Batman">Batman</option>
<option value="Ironman">Ironman</option>
<option value="Darkman">Darkman</option>
<option value="Lightman">Lightman</option>
</select>
<br>
<input type="submit" value="Enviar" />
</form>
</html>
<file_sep>/principiosPHP/11-ejercicios/ejercicio1.php
<h1>Ejercicio1</h1>
<?php
/*
crear dos variables cuyo nombre sea pais y continenete, inicializarlas e imprimiralas por pantalla e imprimir el tipo de variable que son
*/
$pais = "México";
$continente ="Latinoamerica";
echo '<h2>País: '.$pais.' Continente : '.$continente.'</h2>';
?><file_sep>/principiosSQL/09-ejercicios/ejercicio28.sql
/*
28. Mostrar todos los usuarios y el numero de posts.
Se deben mostrar tengan o no posts
*/
SELECT v.nombre, v.apellidos, COUNT(c.id) FROM profile v
LEFT JOIN post c ON c.id = v.id
GROUP BY v.id;
<file_sep>/principiosPHP/23-ejercicios/ejercicio3.php
<?php
/*
Hacer interfax de usuario
con dos inputs y cuatro botones
Uno para sumar dividir restar y multiplicar
*/
if (!empty($_POST['n1']) && !empty($_POST['n2'])) {
$resultado = false;
if (isset($_POST['sumar'])) {
echo "me llego la info de suma";
$resultado = "El resultado es: ".($_POST['n1']+$_POST['n2']);
}elseif (isset($_POST['restar'])) {
echo "me llego la info de resta";
$resultado = "El resultado es: ".($_POST['n1']-$_POST['n2']);
}elseif (isset($_POST['dividir'])) {
echo "me llego la info de division";
$resultado = "El resultado es: ".($_POST['n1']/$_POST['n2']);
}elseif (isset($_POST['multiplicar'])) {
echo "me llego la info de multiplicacion";
$resultado = "El resultado es: ".($_POST['n1']*$_POST['n2']);
}
}
?>
<html>
<head>
<meta>
<title>Calculadora básica</title>
</head>
<body>
<h2>Calculadora básica</h2>
<form action="ejercicio3.php" method="POST">
<label for="n1">Valor1</label>
<input type="number" name="n1">
<br>
<label for="n2">Valor2</label>
<input type="number" name="n2">
<br><br>
<input type="submit" value="sumar" name="sumar">
<input type="submit" value="restar" name="restar">
<input type="submit" value="dividir" name="dividir">
<input type="submit" value="multiplicar" name="multiplicar">
<hr>
<?php
if ($resultado != false) {
echo "$resultado";
}
?>
</form>
</body>
</html><file_sep>/principiosPHP/21-directorios/index.php
<?php
if (!is_dir('nueva_carpeta')) {
mkdir('nueva_carpeta', 0777) or die('No se puede crear la carpeta');
echo "carpeta creada";
echo "<hr>";
}else{
echo "Ya existe la carpeta<br>";
echo "<hr>";
}
//borrar dir
//rmdir('nueva_carpeta');
echo "<h1>Contenido carpeta</h1>";
if ($gestor = opendir('./nueva_carpeta')) {
while (false != ($archivo = readdir($gestor))) {
if ($archivo != '.' && $archivo != '..') {
echo $archivo."<br>";
}
}
}
?><file_sep>/principiosSQL/04-dml/where.sql
# CONSULTA CON UNA CONDICIÓN #
SELECT * FROM usuarios WHERE email = '<EMAIL>';
/*
OPERADORES DE COMPARACION:
Igual =
Distinto !=
Menor <
Mayor >
Menor o igual <=
Mayor o igual >=
Entre between A and B
En in
Es nulo is null
No nulo is not null
Como like
No es como not like
*/
/*
OPERADORES LOGICOS:
O OR
Y AND
NO NOT
*/
/*
COMODINES:
Cualquier cantidad de caracteres: %
Un caracter desconocido: _
*/
#EJEMPLOS#
# 1. Mostrar Nombre y Apellidos de todos los usuarios registrados en 2019
SELECT nombre, apellidos FROM usuarios WHERE YEAR(fecha) = 2019;
# 2. Mostrar Nombre y Apellidos de todos los usuarios QUE NO se registraron en 2019
SELECT nombre, apellidos FROM usuarios WHERE YEAR(fecha) != 2019 OR ISNULL(fecha);
# 3. Mostrar el email de los usuarios cuyo apellido contenga la letra A
# y que contraseña sea <PASSWORD>
SELECT email FROM usuarios WHERE apellidos LIKE '%a%' AND password = '<PASSWORD>';
# 4. Sacar todos los registros de la tabla usuarios cuyo año sea PAR
SELECT * FROM usuarios WHERE (YEAR(fecha)%2 = 0);
# 5. Sacar todos los registro de la tabla usuarios cuyo nombre tenga más de
# 5 letras y que se hayan registrado antes de 2020, y mostrar el nombre en mayus
SELECT UPPER(nombre) AS 'Nombre', apellidos FROM usuarios WHERE LENGTH(nombre) > 5 AND YEAR(FECHA) < 2020;<file_sep>/principiosPHP/05-Constantes/index.php
<?php
//Constantes el valor de estas variables nuca cambiara
//
define('nombre', '<NAME> ');
define('web', 'Web');
echo '<h1>'.nombre.'</h1>';
echo '<h1>'.web.'</h1>';
//Constantes predefinidas
echo '<ul>
<li><h2>Version de php</h2>';
echo phpversion();
echo'</li>
<li><h2>Linea de codigo en la que se encuentra el comando</h2>';
echo __LINE__;
echo'</li>
<li><h2>Directorio donde se encuentra instalado PHP</h2>';
echo PHP_EXTENSION_DIR;
echo'</li>
<li><h2>Ruta completa de la extension</h2>';
echo __FILE__;
echo'</li>
<li><h2>Nombre de la funcion en curso</h2>';
function primeraFuncion(){
echo __FUNCTION__;
}
primeraFuncion();
echo'</li>
<li><h2>Sistema operativo que nos visita</h2>';
echo PHP_OS;
echo'</li>
<li><h2>Características del sistema operativo</h2>';
echo php_uname();
echo'</li>
<li><h2>Creditos</h2>';
echo phpcredits();
echo'</li>
</ul>';
?><file_sep>/principiosPHP/12-funciones/index.php
<h1>Primera funcion</h1>
<?php
/*FUNCIONES: CONJUNTOS DE INSTRUCCIONES AGRUPÁDOS POR UN NOMBRE EN COMPLETO
-SE PUEDE INVOCAR ILIM VECES
EJEMPLO:
function nombreDeMiFuncion($parametro) {
//BLOQUE DE INSTRUCCIONES
}*/
//Ejemplo1
#funcion sin parametros
function muestraNombres(){
echo "Samuel<br>";
echo "Vazquez<br>";
echo "Ruiz<br>";
echo "<hr>";
}
#invocar funcion sin parametros
muestraNombres();
//Ejemplo2
#funcion con parametro
function tabla($numero){
echo "<h3>Tabla de multiplicar del numero: $numero </h3>";
for ($i=1; $i <=10 ; $i++) {
$resultado = $numero*$i;
echo "$numero x $i = $resultado <br>";
}
}
if (isset($_GET['numero'])) {
tabla($_GET['numero']);
echo "<hr>";
}else{
echo "No hay parametro para la funcion";
echo "<hr>";
}
//Ejemplo 3
function calculadora($numero1, $numero2, $negrita){
//Conjunto de instrucciones a ejecutar
$suma = $numero1 + $numero2;
$resta = $numero1 - $numero2;
$multiplicacion = $numero1 * $numero2;
$division = $numero1 / $numero2;
$cadena_texto = "";
echo "<h3>CALCULADORA</h3>";
if ($negrita) {
$cadena_texto.="<h1>";
}
$cadena_texto .= "Suma: ".$suma."<br>";
$cadena_texto .= "Resta: ".$resta."<br>";
$cadena_texto .= "Multiplicación: ".$multiplicacion."<br>";
$cadena_texto .= "División: ".$division."<br>";
if ($negrita) {
$cadena_texto .="</h1>";
}
$cadena_texto .= "<hr>";
return $cadena_texto;
}
echo calculadora(10, 30, true);
//ejercicio 4 correcta sintaxis
// ya que la funcion siempre debe devolver un valor y no debe tener instrucciones de impresion en la misma funcion
function getNombre($nombre){
$texto = "El nombre es: $nombre";
return $texto;
}
function getApellidos($apellidos){
$texto = "Los apellidos son: $apellidos";
return $texto;
}
function devuelveElNombre($nombre, $apellidos){
#anidar funcion
$texto = getNombre($nombre)
."<br>".
getApellidos($apellidos);
return $texto;
}
echo devuelveElNombre("Samuel","<NAME>");
?><file_sep>/proyectoBlog/registro.php
<?php
if (isset($_POST)) {
//Conexion a la bd
require_once 'modelos/conexion.php';
// Iniciar sesion si no existe
if (!isset($_SESSION)) {
session_start();
}
//Recoger
//real_scape_string = "añade datos que escapen como comillas"
//trim = "elimina los espacios"
$nombre = isset($_POST['nombre']) ? mysqli_real_escape_string($db, $_POST['nombre']) : false;
$apellidos = isset($_POST['apellidos']) ? mysqli_real_escape_string($db, $_POST['apellidos']) : false;
$email = isset($_POST['email']) ? mysqli_real_escape_string($db, trim($_POST['email'])) : false;
$password = isset($_POST['password']) ? mysqli_real_escape_string($db, $_POST['password']) : false;
// Array de errores
$errores = array();
//Validar los datos antes de guardarlos en la BD
#validar nombre
if (!empty($nombre) && !is_numeric($nombre) && !preg_match("/[0-9]/", $nombre)) {
$nombre_validate = true;
}else{
$nombre_validate = false;
$errores['nombre'] = "El nombre no es valido";
}
#validar apellidos
if (!empty($apellidos) && !is_numeric($apellidos) && !preg_match("/[0-9]/", $apellidos)) {
$apellidos_validate = true;
}else{
$apellidos_validate = false;
$errores['apellidos'] = "Los apellidos no son validos";
}
#validar email
if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_validate = true;
}else{
$email_validate = false;
$errores['email'] = "El email no es valido";
}
#validar password
if (!empty($password)) {
$pass_validate = true;
}else{
$pss_validate = false;
$errores['password'] = "La contraseña no es valida";
}
$guardar_usuario = false;
if (count($errores) === 0) {
$guardar_usuario = true;
// CIFRAR LA CONTRASEÑA
$password_segura = password_hash($password, PASSWORD_BCRYPT, ['cost'=>4]);
$sql = "INSERT INTO usuarios VALUES(null, '$nombre', '$apellidos', '$email', '$password_segura', CURDATE());";
$guardar = mysqli_query($db, $sql);
if ($guardar) {
$_SESSION['completado'] = "El registro se ha completado con exito.";
}else{
$_SESSION['errores']['general'] = "Fallo al guardar el usuario!";
}
// INSERTAR USUARIO EN LA BD
}else{
$_SESSION['errores'] = $errores;
}
}
header('Location: index.php');
<file_sep>/proyecto-php-poo-eshop/views/pedido/confirmado.php
<?php if(isset($_SESSION['pedido']) && $_SESSION['pedido'] == 'complete') : ?>
<h1>Pedido se ha confirmado</h1>
<p>Tu pedido ha sido guardado con exito, una vez que realizes el pago sera procesado y enviado!</p>
<br>
<div class="col-md-12">
<div class="row">
<div class="col-md-6 col-sm-12">
<label for="cBancaria">Cuenta bancaria: </label>
<input type="text" id="url" class="clipboard" value="5204 1653 4452 4099">
<i class="fa fa-copy">copy</i>
<span class="mensaje" id="mensaje"></span>
</div>
<div class="col-md-6 col-sm-12">
<label for="cPaypal">Cuenta paypal: </label>
<input type="text" id="url2" class="clipboard" value="<EMAIL>">
<i class="fa fa-clipboard"></i>
<span class="mensaje2" id="mensaje2"></span>
</div>
</div>
</div>
<br>
<?php if (isset($pedido)) : ?>
<center><h4>Datos del pedido:</h4>
<label for="">Numero de pedido : <?=$pedido->id ?></label>
<label for="">Total a pagar : <?=$pedido->coste ?> mxn</label>
<h5>Producto(s)</h5>
<table>
<?php while ($producto = $productos->fetch_object()) : ?>
<tr>
<td>
<?php if ($producto->imagen !=null) : ?>
<img src="<?=base_url?>uploads/images/<?=$producto->imagen ?>" class="img_carrito" alt="">
<?php else: ?>
<?php echo "No se encontrol la imagen"; ?>
<?php endif; ?>
</td>
<td>
<a href="<?=base_url?>producto/ver&id=<?=$producto->id?>"><?=$producto->nombre?></a>
</td>
<td>
<?=$producto->precio?>
</td>
<td>
<!-- Al ser un array se entra con esta sintaxis -->
<?=$producto->unidades?>
</td>
</tr>
<?php endwhile; ?>
</table>
</center>
<?php endif; ?>
<br>
<h6>Envia tu comprobante de pago o screenshot del pago a este email: <a href="https://mail.google.com/"><EMAIL></a></h6>
<br>
<?php elseif(isset($_SESSION['pedido']) && $_SESSION['pedido'] != 'complete'): ?>
<h2>Tu pedido no ha podido procesarse</h2>
<?php endif; ?><file_sep>/proyecto-php-poo-eshop/views/categoria/index.php
<h1>Gestionar categorias</h1>
<a class="button btn-small" href="<?=base_url?>/categoria/crear">
Crear categoría
</a>
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
</tr>
<?php while ($cat = $categorias->fetch_object()) : ?>
<tr>
<th scope="col"><?=$cat->id; ?></th>
<th scope="col"><?=$cat->nombre; ?></th>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<file_sep>/principiosPHP/13-includes/contact.php
<?php
include "modulos/cabecera.php";
?>
<!--Contenido -->
<div>
<h2>Esta es la pagina de contacto</h2>
<p>Texto de prueba de la pagina de contacto</p>
</div>
<?php
include "modulos/footer.php";
?>
</body>
</html>
<file_sep>/principiosSQL/09-ejercicios/ejercicio17.sql
/*
17. Obtener listado con los post y comentarios realizados por el usuario 'codexmaker'
*/
SELECT * FROM post p
INNER JOIN categoria c ON c.id = p.id_categoria
INNER JOIN comentario co ON co.id = p.id
WHERE p.id_profile IN
(SELECT id FROM profile WHERE nombre = 'codexmaker');<file_sep>/proyectoBlog/actualizar-perfil.php
<?php
if (isset($_POST)) {
//Conexion a la bd
require_once 'modelos/conexion.php';
//Recoger
//real_scape_string = "añade datos que escapen como comillas"
//trim = "elimina los espacios"
$nombre = isset($_POST['nombre']) ? mysqli_real_escape_string($db, $_POST['nombre']) : false;
$apellidos = isset($_POST['apellidos']) ? mysqli_real_escape_string($db, $_POST['apellidos']) : false;
$email = isset($_POST['email']) ? mysqli_real_escape_string($db, trim($_POST['email'])) : false;
// Array de errores
$errores = array();
//Validar los datos antes de guardarlos en la BD
#validar nombre
if (!empty($nombre) && !is_numeric($nombre) && !preg_match("/[0-9]/", $nombre)) {
$nombre_validate = true;
}else{
$nombre_validate = false;
$errores['nombre'] = "El nombre no es valido";
}
#validar apellidos
if (!empty($apellidos) && !is_numeric($apellidos) && !preg_match("/[0-9]/", $apellidos)) {
$apellidos_validate = true;
}else{
$apellidos_validate = false;
$errores['apellidos'] = "Los apellidos no son validos";
}
#validar email
if (!empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_validate = true;
}else{
$email_validate = false;
$errores['email'] = "El email no es valido";
}
$guardar_usuario = false;
if (count($errores) === 0) {
$usuario = $_SESSION['usuario'];
$guardar_usuario = true;
//Comprobar si el email ya existe
$sql = "SELECT id, email FROM usuarios WHERE email = '$email'";
$isset_email = mysqli_query($db, $sql);
$isset_user = mysqli_fetch_assoc($isset_email);
if ($isset_user['id'] == $usuario['id'] || empty($isset_user)) {
//Actualizar el usuario
$sql = "UPDATE usuarios SET ".
"nombre = '$nombre', ".
"apellidos = '$apellidos', ".
"email = '$email' ".
"WHERE id = ".$usuario['id'];
$guardar = mysqli_query($db, $sql);
if ($guardar) {
$_SESSION['usuario']['nombre'] = $nombre;
$_SESSION['usuario']['apellidos'] = $apellidos;
$_SESSION['usuario']['email'] = $email;
$_SESSION['completado'] = "El perfil se ha actualizado con éxito.";
}else{
$_SESSION['errores']['general'] = "Fallo al actualizar tus datos!";
}
}else{
$_SESSION['errores']['general'] = "El usuario ya existe";
}
}else{
$_SESSION['errores'] = $errores;
}
}
header('Location: perfil.php');<file_sep>/proyecto-php-poo-eshop/controllers/categoriaController.php
<?php
require_once 'models/categoriaModel.php';
require_once 'models/productosModel.php';
class categoriaController{
public function index(){
$categoria = new categoriaModel();
$categorias = $categoria->mostrarCategorias();
require_once 'views/categoria/index.php';
}
public function ver() {
if (isset($_GET['id'])) {
$id = $_GET['id'];
//conseguir categoria
$categoria = new categoriaModel();
$categoria->setId($id);
$categoria = $categoria->mostrarUnaCategoria();
//conseguir productos
$producto = new productoModel();
$producto->setCategoriaId($id);
$productos = $producto->mostrarProdCategorias();
}
require_once 'views/categoria/ver.php';
}
public function crear(){
require_once 'views/categoria/crear.php';
}
public function save() {
//funcion que verifica si el usuario es admin
utils::isAdmin();
if (isset($_POST) && isset($_POST['nombre'])) {
//Guardar la categoría en la bd
$categoria = new categoriaModel();
$categoria->setNombre($_POST['nombre']);
$save = $categoria->save();
}
header("Location:".base_url."categoria/index");
}
}<file_sep>/principiosPHP/14-arrays/funciones.php
<?php
$cantantes = ['SakiFujita', "Drake", "SamPadrul", "ArticM"];
$numeros = ["1","6","2","5","3","4"];
//ordenar
sort($numeros);
var_dump($numeros);
echo "<hr>";
//añadir elementos a un array
$cantantes[] = "extraSinger";
array_push($cantantes, "AnotherMore");
var_dump($cantantes);
echo "<br>";
//eliminar el ultimo elemento
array_pop($cantantes);
var_dump($cantantes);
echo "<br>";
//eliminar elemento array
unset($cantantes[4]);
var_dump($cantantes);
echo "<hr>";
//aleatorio
$indice = array_rand($cantantes);
echo $cantantes[$indice];
echo "<br>";
//dar la vuelta
var_dump(array_reverse($numeros));
echo "<br>";
//Buscar dentro de un array
$resultado = array_search('SamPadrul', $cantantes);
var_dump($resultado);
echo "<br>";
//Contar numero de elemntos
echo count($cantantes);
?><file_sep>/principiosSQL/04-dml/select.sql
#MOSTRAR TODOS REGISTROS / FILAS DE UNA TABLA#
SELECT email, nombre, apellidos FROM usuarios;
#MOSTRAR TODOS LOS CAMPOS#
SELECT * FROM usuarios;
#OPERADORES ARITMETICOS#
SELECT email, (7+7) AS 'OPERACION' FROM usuarios;
#FUNCIONES MATEMATICAS#
SELECT CEIL(7.34) AS 'OPERACION' FROM usuarios;<file_sep>/proyecto-php-poo-eshop/models/productosModel.php
<?php
class productoModel{
//privadas por que solo podremos acceder a ellas por metodos
private $id;
private $categoria_id;
private $nombre;
private $descripcion;
private $precio;
private $stock;
private $oferta;
private $fecha;
private $imagen;
private $db;
public function __construct() {
$this->db = conexion::conectar();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*
* @return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return mixed
*/
public function getCategoriaId()
{
return $this->categoria_id;
}
/**
* @param mixed $categoria_id
*
* @return self
*/
public function setCategoriaId($categoria_id)
{
$this->categoria_id = $categoria_id;
return $this;
}
/**
* @return mixed
*/
public function getNombre()
{
return $this->nombre;
}
/**
* @param mixed $nombre
*
* @return self
*/
public function setNombre($nombre)
{
$this->nombre = $this->db->real_escape_string($nombre);
return $this;
}
/**
* @return mixed
*/
public function getDescripcion()
{
return $this->descripcion;
}
/**
* @param mixed $descripcion
*
* @return self
*/
public function setDescripcion($descripcion)
{
$this->descripcion = $this->db->real_escape_string($descripcion);
return $this;
}
/**
* @return mixed
*/
public function getPrecio()
{
return $this->precio;
}
/**
* @param mixed $precio
*
* @return self
*/
public function setPrecio($precio)
{
$this->precio = $this->db->real_escape_string($precio);
return $this;
}
/**
* @return mixed
*/
public function getStock()
{
return $this->stock;
}
/**
* @param mixed $stock
*
* @return self
*/
public function setStock($stock)
{
$this->stock = $this->db->real_escape_string($stock);
return $this;
}
/**
* @return mixed
*/
public function getOferta()
{
return $this->oferta;
}
/**
* @param mixed $oferta
*
* @return self
*/
public function setOferta($oferta)
{
$this->oferta = $this->db->real_escape_string($oferta);
return $this;
}
/**
* @return mixed
*/
public function getFecha()
{
return $this->fecha;
}
/**
* @param mixed $fecha
*
* @return self
*/
public function setFecha($fecha)
{
$this->fecha = $this->db->real_escape_string($fecha);
return $this;
}
/**
* @return mixed
*/
public function getImagen()
{
return $this->imagen;
}
/**
* @param mixed $imagen
*
* @return self
*/
public function setImagen($imagen)
{
$this->imagen = $this->db->real_escape_string($imagen);
return $this;
}
public function mostrarProductos() {
$productos = $this->db->query("SELECT * FROM producto ORDER BY id DESC");
return $productos;
}
public function mostrarProdCategorias() {
$sql= "SELECT p.*, c.nombre AS 'catNombre' FROM producto p "
. "INNER JOIN categoria c ON c.id = p.categoria_id "
. "WHERE p.categoria_id={$this->getCategoriaId()} "
. "ORDER BY id DESC";
$productos = $this->db->query($sql);
return $productos;
}
public function mostrarUnProducto() {
$producto = $this->db->query("SELECT * FROM producto WHERE id = {$this->getId()}");
return $producto->fetch_object();
}
public function getRandom($limit) {
$productos = $this->db->query("SELECT * FROM producto ORDER BY RAND() LIMIT $limit");
return $productos;
}
public function save() {
$sql = "INSERT INTO producto VALUES(NULL, '{$this->getCategoriaId()}','{$this->getNombre()}', '{$this->getDescripcion()}', '{$this->getPrecio()}', {$this->getStock()}, null, CURDATE(), '{$this->getImagen()}')";
$save = $this->db->query($sql);
$result = false;
if ($save) {
$result = true;
}
return $result;
}
public function edit() {
$sql = "UPDATE `producto` SET `categoria_id`='{$this->getCategoriaId()}',`nombre`='{$this->getNombre()}',`descripcion`='{$this->getDescripcion()}',`precio`={$this->getPrecio()},`stock`={$this->getStock()}";
if ($this->getImagen() != null) {
$sql .=", imagen = '{$this->getImagen()}'";
}
$sql .=" WHERE id={$this->id};";
$save = $this->db->query($sql);
$result = false;
if ($save) {
$result = true;
}
return $result;
}
public function delete() {
$sql = "DELETE FROM producto WHERE id={$this->id}";
$delte = $this->db->query($sql);
$result = false;
if ($delete) {
$result = true;
}
return $result;
}
}<file_sep>/PHP-POO/12-autoload/clases/panelAdministrador/usuario.php
<?php
namespace panelAdministrador;
class usuario{
public $nombre;
public $email;
public function __construct() {
$this->nombre = "Codexmaker";
$this->email = "<EMAIL>";
}
}<file_sep>/principiosSQL/09-ejercicios/ejercicio27.sql
/*
27. Visualizar los nombres de los usuarios y la cantidad de post realizados,
incluyendos los que no hayan realizado post.
*/
SELECT c.nombre, COUNT(e.id) FROM profile c
LEFT JOIN post e ON c.id = e.id
GROUP BY 1;<file_sep>/basicsLaravel/app/Http/Controllers/usuarioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
//controlador de tipo resource
class usuarioController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$usuarios = DB::table('usuario')
->orderBy('id','desc')
->get();
return view('usuarios.index',[
'usuarios' => $usuarios
]);
}
public function details($id){
$usuario = DB::table('usuario')->where('id', '=', $id)->first();
return view('usuarios.details',[
'usuario' => $usuario
]);
}
public function create()
{
return view('usuarios.create');
}
public function save(Request $request) {
//guardar el registro
$usuario = DB::table('usuario')->insert(array(
'nombre' => $request->input('nombre'),
'apellidos' => $request->input('apellidos'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'rol' => $request->input('rol')
));
return redirect()->action('usuarioController@index')->with('status', 'Usuario creado con exito');
}
public function delete($id) {
//borrar registro
$usuario = DB::table('usuario')->where('id', $id)->delete();
return redirect()->action('usuarioController@index')->with('status', 'Usuario eliminado con exito');
}
public function edit($id)
{
//sacar el registro de la bd
$usuario = DB::table('usuario')->where('id', $id)->first();
//pasarle a la vista el objeto y rellenar el formulario
return view('usuarios.create',[
'usuario' => $usuario
]);
}
public function update(Request $request) {
$id = $request->input('id');
$usuario = DB::table('usuario')
->where('id', $id)
->update(array(
'nombre' => $request->input('nombre'),
'apellidos' => $request->input('apellidos'),
'email' => $request->input('email'),
'password' => $request->input('<PASSWORD>'),
'rol' => $request->input('rol')
));
return redirect()->action('usuarioController@index')->with('status', 'Usuario actualizado con exito');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/principiosPHP/23-ejercicios/ejercicio1.php
<?php
/*
Crear una sesion que aumente su valor en uno disminuya en 1 en funcion de si el parametro get counter esta a uno o cero.
*/
session_start();
if (!isset($_SESSION['numeroSesion'])) {
$_SESSION['numeroSesion'] = 0;
}
if (isset($_GET['counter']) && $_GET['counter'] == 1) {
$_SESSION['numeroSesion']++;
}
if (isset($_GET['counter']) && $_GET['counter'] == 0) {
$_SESSION['numeroSesion']--;
}
?>
<h1>El valor de la sesion numero es: <?= $_SESSION['numeroSesion'] ?></h1>
<a href="ejercicio1.php?counter=1">Aumenta</a>
<a href="ejercicio1.php?counter=0">Disminuye</a>
<hr>
<?php
?><file_sep>/PHP-POO/03-herencia/clases.php
<?php
//HERENCIA: posibilidad de compartir atributos y metodos entre clases
//
class Persona {
public $nombre;
public $apellidos;
public $altura;
public $edad;
public function getNombre(){
return $this->nombre;
}
public function setNombre($nombre){
$this->nombre = $nombre;
}
public function getApellidos(){
return $this->apellidos;
}
public function setApellidos($apellidos){
$this->apellidos = $apellidos;
}
public function getAltura(){
return $this->altura;
}
public function setAltura($altura){
$this->altura = $altura;
}
public function getEdad(){
return $this->edad;
}
public function setEdad($edad){
$this->edad = $edad;
}
public function hablar() {
return "Estoy hablando";
}
public function caminar() {
return "Estoy caminando";
}
public function comiendo() {
return "Estoy comiendo";
}
}
//heredar de clase persona
class desarrolladorWeb extends Persona{
public $lenguajes;
public $experienciaProgramador;
public function __construct() {
$this->lenguajes = "HTML, CSS, PHP y JS";
$this->experienciaProgramador = 3;
}
public function sabeLenguajes($lenguajes) {
$this->lenguajes = $lenguajes;
return $this->lenguajes;
}
public function programar() {
return "Soy programador";
}
public function crearBD() {
return "Estoy creando la base de datos";
}
public function diseñarMaquetadoWeb() {
return "Estoy diseñando la web";
}
}
class tecnicoRedes extends desarrolladorWeb {
public $auditarRedes;
public $experienciaRedes;
public function __construct() {
//llamar de manera estatica al metodo que hereda para recibir la data del padre
parent::__construct();
$this->auditarRedes = "experto";
$this->experienciaRedes = 5;
}
public function auditoria(){
return "Estoy auditando una red";
}
}
?><file_sep>/principiosSQL/07-multitabla/consultas.sql
/*
CONSULTA MULTITABLA:
Son consultas que sirven para consultar varias tablas en una sola sentencia
*/
#Mostrar las entradas con el nombre del autor y el nombre de la categoria#
SELECT e.id, e.titulo, u.nombre AS 'Autor', c.nombre AS 'Categoría'
FROM entradas e, usuarios u, categorias c
WHERE e.usuario_id = u.id AND e.categoria_id = c.id;
#INNNER JOIN#
SELECT e.id, e.titulo, u.nombre AS 'Autor', c.nombre AS 'Categoría'
FROM entradas e
INNER JOIN usuarios u ON e.usuario_id = u.id
INNER JOIN categorias c ON e.categoria_id = c.id;
#Mostrar el nombre de las categorias y al lado cuantas entradas tienen#
SELECT c.nombre, COUNT(e.id) FROM categorias c, entradas e
WHERE e.categoria_id = c.id GROUP BY e.categoria_id;
SELECT c.nombre, COUNT(e.id) FROM categorias c
LEFT JOIN entradas e ON e.categoria_id = c.id
GROUP BY e.categoria_id;
SELECT c.nombre, COUNT(e.id) FROM entradas e
RIGHT JOIN categorias c ON e.categoria_id = c.id
GROUP BY e.categoria_id;
SELECT c.nombre, COUNT(e.id) FROM entradas e
OUTER JOIN categorias c ON e.categoria_id = c.id
GROUP BY e.categoria_id;
#Mostrar el email de los usuarios y al lado cuantas entradas tienen#
SELECT u.email, COUNT(titulo) FROM usuarios u, entradas e
WHERE e.usuario_id = u.id GROUP BY e.usuario_id;
<file_sep>/PHP-POO/02-constructor/pcMasterRace.php
<?php
class pcMasterRace{
//Atributos o propiedades
public $color; #podemos acceder desde cualquier lugar al tipo public
protected $tarjetaVideo; #podemos acceder desde la clase que los define
#y hereden
private $motherboard; #podemos acceder desde esta clase y nada mas
public $ram;
public $processor;
public $coldSystem;
public $gabinete;
//Contructor asigna los valores
public function __construct($color, $tarjetaVideo, $motherboard, $ram, $processor, $coldSystem, $gabinete) {
$this->color = $color;
$this->tarjetaVideo = $tarjetaVideo;
$this->motherboard = $motherboard;
$this->ram = $ram;
$this->processor = $processor;
$this->coldSystem = $coldSystem;
$this->gabinete = $gabinete;
}
//Metodos, acciones que hace el objeto (antes funciones)
public function getColor(){
//this significa busca en esta clase la propiedad x
return $this->color;
}
public function setColor($color){
$this->color = $color;
}
public function aumentarRAM(){
$this->ram++;
}
public function disminuirRAM(){
$this->ram--;
}
public function getRam(){
return $this->ram;
}
public function getProcessor(){
return $this->processor;
}
public function getMotherboard(){
return $this->motherboard;
}
public function setMotherboard($motherboard){
$this->motherboard = $motherboard;
}
public function setTarjetaVideo($tarjetaVideo){
$this->tarjetaVideo = $tarjetaVideo;
}
//Metodo para imprimir la informacion de un coche
public function mostrarInformacion(pcMasterRace $pcMasterRace){
if (is_object($pcMasterRace)) {
$info = "<h1>Informacion de la PC</h1>";
$info .= "Gabinete: ".$pcMasterRace->gabinete."<br>";
$info .= "Motherboard: ".$pcMasterRace->motherboard."<br>";
$info .= "Ram: ".$pcMasterRace->ram."<br>";
$info .= "Processor: ".$pcMasterRace->processor."<br>";
$info .= "TarjetaVideo: ".$pcMasterRace->tarjetaVideo."<br>";
$info .= "Sistema enfriamiento: ".$pcMasterRace->coldSystem."<br>";
}else{
$info = "Tu dato es este: $pcMasterRace";
}
return $info;
}
} //fin definicion de la clase
?><file_sep>/principiosPHP/13-includes/modulos/cabecera.php
<html lang="es">
<head>
<meta charset="utf-8">
</head>
<title>Includes en PHP</title>
<body>
<!--Cabecera -->
<div class="cabecera">
<h1>Includes en PHP</h1>
<ul>
<li><a href="index.php">Inicio</a></li>
<li><a href="about.php">Acerca</a></li>
<li><a href="contact.php">Contacto</a></li>
</ul>
<hr>
</div>
<?php $nombre = "codexmaker"; ?> <file_sep>/principiosSQL/09-ejercicios/ejercicio08.sql
/*
8. Visualizar todos los post en cuyo titular exista la letra "A" y cuyo titulo empiece por "M"
*/
SELECT * FROM post WHERE titular LIKE '%a%' AND titulo LIKE 'M%';<file_sep>/proyecto-php-poo-eshop/views/usuario/registro.php
<h1>Registrarse</h1>
<?php if (isset($_SESSION['register']) && $_SESSION['register'] == 'complete' ): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">Registro completado correctamente
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php elseif(isset($_SESSION['register']) && $_SESSION['register'] == 'failed'): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">Registro fallido, introduce bien los datos
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php endif; ?>
<?php utils::deleteSession('register');?>
<form action="<?=base_url?>usuario/save" method="POST">
<label for="nombre">Nombre</label>
<input type="text" name="nombre" required>
<label for="apellidos">Apellidos</label>
<input type="text" name="apellidos" required>
<label for="email">Email</label>
<input type="email" name="email" required>
<label for="password">Contraseña</label>
<input type="password" name="password" required>
<input type="submit" value="registrarse">
</form><file_sep>/principiosSQL/09-ejercicios/ejercicio24.sql
/*
24. Listar los post con el nombre del post, el nombre del usuario y
el contenido del comentario, pero unicamente cuando sean del usario codexmaker.
*/
SELECT com.comentario, p.titular, pro.nombre FROM comentario com
INNER JOIN post p ON p.id = com.id_profile
INNER JOIN profile pro ON pro.id = com.id_profile
WHERE pro.nombre = 'codexmaker';<file_sep>/principiosPHP/11-ejercicios/ejercicio6.php
<?php
/*
Ex6. Imprimir por pantalla todas las tablas del 1 al 10 e imprimirlas en una tabla por html
*/
echo "<table border='1'> </tr>";//inicio de la tabla
echo "<tr>";//inicio fila 1 de celdas
for ($cabecera=1; $cabecera <=10 ; $cabecera++) {
echo "<td>Tabla del : $cabecera</td>";
}
echo "</tr>";// cierre fila 1 de celdas
echo "<tr>";//inicio fila 2 de celdas
for ($filas=1; $filas <=10 ; $filas++) {
echo "<td>";
for ($i=1; $i <=10 ; $i++) {
echo "$filas * $i = ".($filas*$i).'<br>';
}
echo "</td>";
}
echo "</tr>";// cierre fila 2 de celdas
echo '</table>';//fin de la tabla
?><file_sep>/principiosPHP/15-ejerciciosN2/ejercicio4.php
<?php
/*
ex4. Crear script en php que tenga 4 variables, una de tipo array,
otra de tipo string, otra int y otra booleana y que imprima un mensaje segun el tipo de variable que sea.
*/
$artistas = array('miku','luka','rin','megumin','aiChan');
$nombre = "Sam";
$numero = 15;
$estado = true;
$tipoArtistas = gettype($artistas);
$tipoNombre = gettype($nombre);
$tipoNumero = gettype($numero);
$tipoEstado = gettype($estado);
if ($tipoArtistas == "array") {
echo "<br>";
var_dump($artistas);
}
if ($tipoNombre == "string") {
echo "<br>";
var_dump($nombre);
}
if ($tipoNumero == "integer") {
echo "<br>";
var_dump($numero);
}
if ($tipoEstado == "boolean") {
echo "<br>";
var_dump($estado);
}
?><file_sep>/principiosPHP/13-includes/index.php
<?php
/*Incluye un modulo para hacer el programa facilmente escalable y modificable*/
//include_once solo incluye 1 sola vez y limita la funcion a 1
require_once "modulos/cabecera.php";
#si no se ejecuta correctamente no carga toda la pagina se detiene la ejecucion es mas estricto
//require "modeulos/cabecera.php";
?>
<!--Contenido -->
<div>
<h2>Esta es la pagina de inicio</h2>
<p>Texto de prueba de la pagina de inicio</p>
</div>
<?php
//veces n se puede incluir la funcion
include "modulos/footer.php";
?>
</body>
</html>
<file_sep>/principiosPHP/09-Bucles/index.php
<h1>Bucles</h1>
<?php
/*Bucle while
Estructura de control que repite la ejecucion de una seria de
instrucciones tantas veces sea necesario, dependiente de una condicion.
while(condicion){
bloque de instrucciones
otra instruccion
}
*/ echo "<h2>Ejemplo_1</h2>";
$numero = 0;
while ($numero <=100) {
echo $numero;
if ($numero != 100) {
echo ", ";
}
$numero++;
}
echo "<hr>";
echo "<h2>Ejemplo_2</h2>";
if (isset($_GET['numero'])) {
#casteo de datos cambiar tipo de dato
$numero = (int)$_GET['numero'];
}else{
$numero = 1;
}
echo "<h3>Tabla de multiplicar del número $numero</h3>";
$contador = 1;
while ($contador <= 10) {
echo "$numero x $contador =".($numero*$contador)."<br>";
$contador++;
}
// DO WHILE
$edad = 18;
$contador =1;
do{
//Bloque de instrucciones
echo "Tienes acceso al sistema $contador <br>";
$contador++;
}while($edad >= 18 && $contador <= 10);
?>
<file_sep>/PHP-POO/01-clases/index.php
<?php
//Programacion orientada a objetos en PHP (POO)
//
//
//
//Definir una clase -Molde para crear mas objetos del tipo pcMasterRace con caracteristicas parecidas-
class pcMasterRace{
//Atributos o propiedades
public $color = "blackMetal";
public $tarjetaVideo = "nVidia 1070";
public $motherboard = "Gaming AB";
public $ram = "8";
public $processor = "Ryzen 5 1600x";
public $coldSystem = "CAM";
public $gabinete = "Aliance TUF Gaming";
//Metodos, acciones que hace el objeto (antes funciones)
public function getColor(){
//this significa busca en esta clase la propiedad x
return $this->color;
}
public function setColor($color){
$this->color = $color;
}
public function aumentarRAM(){
$this->ram++;
}
public function disminuirRAM(){
$this->ram--;
}
public function getRam(){
return $this->ram;
}
public function getProcessor(){
return $this->processor;
}
} //fin definicion de la clase
//Crear objeto o Instanciar la clase
//
$pcMasterRace = new pcMasterRace();
// Usar los metodos
echo $pcMasterRace->getRam();
$pcMasterRace->setColor("red");
echo "<br>";
echo "El color de la pc Gamer es: ".$pcMasterRace->getColor()."<br>";
//aumentar la ram
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->aumentarRAM();
$pcMasterRace->disminuirRAM();
echo "Ram actual es: ".$pcMasterRace->getRam()."<hr>";
//Creacion de nuevo objeto solo se cambia el nombre
$pcMasterRace2 = new pcMasterRace();
$pcMasterRace2->setColor("Negra");
echo "El color de la pc Gamer es: ".$pcMasterRace2->getColor()."<br>";
echo "Ram actual es: ".$pcMasterRace2->getRam()."<br>";
echo "El procesador que usa es: ".$pcMasterRace2->getProcessor()."<br>";
?><file_sep>/principiosPHP/08-condicionales/index.php
<h1>Condicionales</h1>
<?php
/*
CONDICIONALES
IF:
if(condicion){
instrucciones
}else{
otras instrucciones
}
//OPERADORES DE COMPARACIÓN
== igual
=== identico
!= distinto
<> diferente
!== no identico
< menor que
> mayor que
<= menor o igual que
>= mayor o igual que
// OPERADORES LOGICOS
&& and
|| or
! not
and, or
*/
#ejemplo1
$color = "rojo";
if ($color == "rojo") {
echo "El color es rojo<br>";
}else{
echo "El color no es rojo<br>";
}
#ejemplo2
echo "<hr>";
$year = 2019;
if ($year >= 2019) {
echo "Estamos de 2019 en adelante";
}else{
echo "Es un año anterior a 2019";
}
echo "<br>";
echo "<hr>";
#ejemplo3
$nombre = "<NAME>";
$ciudad = "México";
$continente = "Latinoamerica";
$edad = 23;
$mayoria_edad = 18;
if ($edad >= $mayoria_edad) {
echo '<h2>'.$nombre.' es mayor de edad</h2>';
if ($continente == "Latinoamerica") {
echo '<h3>Y es de'.$ciudad.'</h3>';
}else{
echo "No es latinoamericano";
}
}else{
echo '<h2>'.$nombre.' es menor de edad, chao.</h2>';
}
echo "<hr>";
#ejemplo4
$dia = 6;
if ($dia == 1) {
echo "LUNES";
}elseif ($dia == 2) {
echo "MARTES";
}elseif ($dia == 3){
echo("MIERCOLES");
}elseif ($dia == 4){
echo "JUEVES";
}elseif ($dia == 5) {
echo "VIERNES";
}else{
echo "Es fin de semana";
}
echo "<hr>";
#ejemplo5
$edad1 = 18;
$edad2 = 64;
$edad_oficial = 23;
if ($edad_oficial >= $edad1 && $edad_oficial <= $edad2) {
echo "Esta en edad de trabajar";
}else{
echo "No puede trabajar";
}
echo "<br>";
$pais = "Mexico";
if ($pais == "Mexico" || $pais == "España" || $pais =="Colombia") {
echo "En este pais se habla español";
}else{
echo "no se habla español";
}
echo "<hr>";
//switch
$dia = 4;
switch ($dia) {
case 1:
echo "numero1";
break;
case 2:
echo "numero2";
break;
case 3:
echo "numero3";
break;
case 4:
echo "numero4";
break;
default:
echo "La variable contiene un dato diferente";
}
echo "<hr>";
goto marca;
echo "<h3>Intruccion 1</h3>";
echo "<h3>Intruccion 2</h3>";
echo "<h3>Intruccion 3</h3>";
echo "<h3>Intruccion 4</h3>";
marca:
echo "Me he saltado 4 echos";
?><file_sep>/proyectoBlog/index.php
<?php
require_once 'modelos/cabecera.php';
?>
<?php
require_once 'modelos/lateral.php';
?>
<!-- CAJA PRINCIPAL -->
<?php require_once 'modelos/principal.php'; ?>
<!-- PIE DE PÁGINA -->
<?php require_once 'modelos/footer.php'; ?>
<file_sep>/principiosPHP/15-ejerciciosN2/ejercicio3.php
<?php
/*
ex3. Hacer un programa en PHP que compruebe si una variable esta vacia y si esta vacia rellenarla con texto en minusculas y mostrarlo en mayusculas y negritas
*/
$texto = "";
if (empty($texto)) {
$texto = "rellenado de texto";
$aMayusculas = strtoupper($texto);
echo '<strong>'.$aMayusculas.'</strong>';
}
?><file_sep>/librerias-php/generar-paginacion/index.php
<?php
require_once '../vendor/autoload.php';
//Conexion a bd
$conexion = new mysqli("localhost", "root", "", "blog");
$conexion->query("SET NAMES 'utf-8'");
//Consultar para contar elementos totales
$consulta = $conexion->query("SELECT * FROM usuarios");
$numero_elementos = $consulta->num_rows;
$numero_elementos_pagina = 2;
//Hacer paginacion
$pagination = new Zebra_Pagination();
//Numero de elementos a paginar
$pagination->records($numero_elementos);
//Numero de elementos por página
$pagination->records_per_page($numero_elementos_pagina);
$page = $pagination->get_page();
$empieza_aqui = (($page - 1)*$numero_elementos_pagina);
$sql ="SELECT * FROM usuarios LIMIT $empieza_aqui, $numero_elementos_pagina";
$usuarios = $conexion->query($sql);
echo '<link rel="stylesheet" href="../vendor/stefangabos/zebra_pagination/public/css/zebra_pagination.css" type="text/css">';
while ($usuario = $usuarios->fetch_object()) {
echo "<h1>{$usuario->nombre}</h1>";
echo "<h2>{$usuario->email}</h2><hr>";
}
$pagination->render();<file_sep>/principiosPHP/23-ejercicios/funciones/functions.php
<?php
function validarEmail($email){
$status = "no valido";
if (!empty($_GET['email']) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$status = "valido";
}
return $status;
}
<file_sep>/principiosSQL/04-dml/insert.sql
#INSERTAR NUEVOS REGISTROS#
INSERT INTO usuarios VALUES(null, 'Víctor', 'Apellidos', '<EMAIL>', '1234', '2019-05-01');
INSERT INTO usuarios VALUES(null, 'Antonio', 'Martinez', '<EMAIL>', '1234', '2019-08-05');
INSERT INTO usuarios VALUES(null, 'Paco', 'Lopez', '<EMAIL>', '1234', '2020-05-01');
#INSERTAR FILAS SOLO CON CIERTAS COLUMNAS#
INSERT INTO usuarios(email, password) VALUES('<EMAIL>', '<PASSWORD>'); <file_sep>/principiosPHP/01-holaMundo/index.php
<h1>Hola Mundo con HTML</h1>
<?php
echo "<h2>Hola mundo con PHP 7</h2>";
?>
<file_sep>/principiosSQL/08-vistas/vistas.sql
/*
Vistas:
Las podemos definir como una consta almacenada en la base de datos que
se utiliza como una tabla virtual.
No almacena datos sino que utiliza asociaciones y los datos originales
de las tablas, de forma que siempre se mantiene actualizada.
*/
CREATE VIEW entradas_con_nombres AS
SELECT e.id, e.titulo, u.nombre AS 'Autor', c.nombre AS 'Categoría'
FROM entradas e
INNER JOIN usuarios u ON e.usuario_id = u.id
INNER JOIN categorias c ON e.categoria_id = c.id;
<file_sep>/principiosSQL/09-ejercicios/ejercicio01.sql
/*
1. Diseñar y crear la base de datos de una red social.
*/
CREATE DATABASE IF NOT EXISTS redSocial;
USE redSocial;
CREATE TABLE profile(
id int(10) auto_increment not null,
nombre varchar(100) not null,
apellidos varchar(50),
correo varchar(25) not null,
contraseña varchar(20) not null,
alias varchar(20) not null,
foto varchar(20) not null,
CONSTRAINT pk_profile PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE post(
id int(10) auto_increment not null,
titulo varchar(100) not null,
titular varchar(100),
descripcion varchar(100) not null,
foto varchar(100) not null,
link varchar(100) not null,
CONSTRAINT pk_post PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE categoria(
id int(10) auto_increment not null,
nombre varchar(100) not null,
CONSTRAINT pk_categoria PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE mail_boxes(
id int(10) auto_increment not null,
id_profile int(100) not null,
mensaje varchar(100),
data_recibida varchar(100) not null,
direccion_email varchar(100) not null,
asunto varchar(100) not null,
detalles varchar(100) not null,
CONSTRAINT pk_mail_boxes PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE mensajes_enviados(
id int(10) auto_increment not null,
id_profile int(100) not null,
data_enviada varchar(100),
to_email_address varchar(100) not null,
asunto varchar(100) not null,
mensaje varchar(100) not null,
detalles varchar(100) not null,
CONSTRAINT pk_mensajes_enviados PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE notificaciones(
id int(10) auto_increment not null,
id_profile int(100) not null,
data_recibida varchar(100) not null,
asunto varchar(100) not null,
mensaje varchar(100) not null,
detalles varchar(100) not null,
CONSTRAINT pk_notificaciones PRIMARY KEY(id)
)ENGINE=InnoDB;
CREATE TABLE comentario(
id int(10) auto_increment not null,
id_profile int(100) not null,
comentario varchar(100) not null,
hora timestamp(100) not null,
ip int(100) not null,
CONSTRAINT pk_comentario PRIMARY KEY(id)
)ENGINE=InnoDB;
#RELLENAR LA BASE DE DATOS CON INFORMACIÓN - INSERTS#
#USUARIOS
INSERT INTO profile VALUES(NULL, 'samuel', '<NAME>', '<EMAIL>', '12345', 'codexmaker', 'foto/');
#post
INSERT INTO post VALUES(NULL, 1, 1, "miSegundoPost", "titular de mi segundo post", "lorem ipsum", "foto/", "link:xxx-x.com", "2019-05-23 13:02:55");
#categoria
INSERT INTO categoria VALUES(NULL, "tecnologia");
#mail_boxes
INSERT INTO mail_boxes VALUES(NULL, 1, 'Este es un mensaje de prueba', 'lorem ipsum', '<EMAIL>', "test", "sinDetalles");
#mensajes_enviados
INSERT INTO mensajes_enviados VALUES(NULL, 1, 'Este es un mensaje de prueba', 'lorem ipsum', '<EMAIL>', "test", "sinDetalles");
#notificaciones
INSERT INTO notificaciones VALUES(NULL, 1, "se actualizo la bd", "Base de datos", "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat accusamus, beatae perferendis, molestiae facilis odit fugit voluptatem voluptatibus ipsum sunt molestias quibusdam modi a, tempora voluptatum eos doloremque ad dolorem.", "sin detalles");
#comentario
INSERT INTO comentario VALUES(NULL, 1, "este es mi primer comentario", TIMESTAMP(), "192.168.102");
<file_sep>/principiosPHP/03-Variables/index.php
<h1>Variables</h1>
<?php
#Variable de tipo texto
$miPrimeraVariable ="<NAME>";
$numero = 50;
$condicion = true;
//Reasignacion de valor
$numero = 81;
#Concatenacion
echo '<h2>'.$miPrimeraVariable.'</h2>';
if ($condicion == true) {
$numero = 150;
echo "Tu dato booleano es verdadero <br> Se te asigna el numero: ".$numero;
}else{
echo "Tu dato booleano es falso <br> Se te asigna el numero: ".$numero;
}
?>
<file_sep>/principiosSQL/09-ejercicios/ejercicio04.sql
/*
4. Sacar todos los post cuya fecha de alta sea posterior
al 1 de Julio de 2019
*/
SELECT * FROM post WHERE fecha >= '2019-07-01';
<file_sep>/principiosSQL/09-ejercicios/ejercicio23.sql
/*
23. Listar todos los comentarios realizados en los post y el nombre
del profile.
*/
SELECT com.comentario, p.titular, pro.nombre FROM comentario com
INNER JOIN post p ON p.id = com.id_profile
INNER JOIN profile pro ON pro.id = com.id_profile;<file_sep>/PHP-POO/12-autoload/autoload.php
<?php
function clases_autoload($class) {
require_once 'clases/'.$class.'.php';
}
spl_autoload_register('clases_autoload');<file_sep>/principiosPHP/15-ejerciciosN2/ejercicio2.php
<?php
/*
ex2. Escribir programa con PHP que añada valores a un array mientras su longitud sea menor a 120 y luego mostrarlo por pantalla.
*/
$numeros = array();
$longitud = count($numeros);
for ($i=0; $i <120 ; $i++) {
array_push($numeros, "elemento-".$i."<br>");
}
var_dump($numeros);
?><file_sep>/principiosPHP/11-ejercicios/ejercicio4.php
<?php
/*
Ex4. RECOGER 2 NUMEROS POR LA URL POR PARAMETRO GET Y HACER UNA CALCULADORA CON LAS OPERACIONES BASICAS
*/
if (isset($_GET['numeroA']) && isset($_GET['numeroB'])) {
$numeroA = $_GET['numeroA'];
$numeroB = $_GET['numeroB'];
$numeroA = (int)$_GET['numeroA'];
$numeroB = (int)$_GET['numeroB'];
echo 'La varible A es : '.$numeroA.'<br>';
echo 'La varible B es : '.$numeroB.'<br>';
echo "Suma: ".($numeroA+$numeroB).'<br>';
echo "Resta: ".($numeroA-$numeroB).'<br>';
echo "Multiplicacion: ".($numeroA*$numeroB).'<br>';
echo "División: ".($numeroA/$numeroB).'<br>';
}else{
echo "Introduce correctamente los valores";
}
?><file_sep>/basicsLaravel/app/Http/Controllers/peliculaController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class peliculaController extends Controller
{
//Acciones
#vistas del index de peliculas
public function index($pagina = 1) {
$titulo = "Listado de mis peliculas";
return view('pelicula.index', [
'titulo' => $titulo,
'pagina' => $pagina
]);
}
public function detalle($year = null){
return view('pelicula.detalle');
}
public function reedirigir(){
return redirect()->route('detalle.pelicula');
}
public function formulario(){
return view('pelicula.formulario');
}
public function recibirData(Request $request){
$nombre = $request->input('nombre');
$email = $request->input('email');
return "El nombre es : $nombre y el email es: $email";
}
}
<file_sep>/principiosSQL/05-agrupamiento/consultas.sql
# CONSULTAS AGRUPAMIENTO #
SELECT COUNT(titulo) AS 'NÚMERO DE ENTRADAS', categoria_id FROM entradas GROUP BY categoria_id;
# CONSULTAS AGRUPAMIENTO CON CONDICIONES#
SELECT COUNT(titulo) AS 'NÚMERO DE ENTRADAS', categoria_id
FROM entradas GROUP BY categoria_id HAVING COUNT(titulo) >= 4;
/*
FUNCIONES AGRUPAMIENTO:
AVG Sacar la media
COUNT Contar el numero de elementos
MAX Valor maximo del grupo
MIN Valor minimo del grupo
SUM Sumar todo el contenido del grupo
*/
SELECT AVG(id) AS 'Media de entradas' FROM entradas;
SELECT MAX(id) AS 'MAXIMO ID', titulo FROM entradas;
SELECT SUM(id) AS 'SUMA DE ID', titulo FROM entradas;
<file_sep>/principiosSQL/09-ejercicios/ejercicio05.sql
/*
5. Mostrar todos los post con su titulo y el numero de dias que llevan
en el sistema.
*/
SELECT nombre, DATEDIFF(CURDATE(), fecha) AS 'DÍAS' FROM post;
<file_sep>/principiosPHP/15-ejerciciosN2/ejercicio5.php
<?php
/*
Crear un array con el contenido de la siguiente tabla:
Accion Aventura Deportes
gta assasins fifa 19
cod crashban pes 19
pug princeof moto 19
Cada columna debe ir en un fichero separado(includes).
*/
$tabla = array(
"ACCION" => array("GTA","COD","PUG"),
"AVENTURA" => array("ASSASINS","CRASHBANDICOOT","PRINCEOFPERSIA"),
"DEPORTES" => array("FIFA 19", "PES 19", "MOTO 19")
);
#crearle los indices
$categorias = array_keys($tabla);
?>
<table border="1">
<tr>
<?php
foreach ($categorias as $key => $categorias) {
echo "<th>$categorias</th>";
}
?>
</tr>
<?php
require_once "modulos/fila0.php";
require_once "modulos/fila1.php";
require_once "modulos/fila2.php";
?>
</table><file_sep>/principiosPHP/13-includes/modulos/footer.php
<!--Pie de pagina -->
<footer>
<hr>
Todos los reservados © <?php echo $nombre; ?> <?php echo date('Y'); ?>
</footer><file_sep>/principiosPHP/19-validacion/index.php
<html>
<head>
<meta charset="utf-8">
<title>Validación de formularios PHP</title>
</head>
<body>
<h1>Validar formularios en PHP</h1>
<?php
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == 'faltan_valores') {
echo '<strong style="color: red">Faltan valores</strong>';
}
if ($error == 'nombre') {
echo '<strong style="color: red">Nombre deb ser sin numeros</strong>';
}
if ($error == 'apellidos') {
echo '<strong style="color: red">Apellidos debe ser sin numeros</strong>';
}
if ($error == 'edad') {
echo '<strong style="color: red">Escriba correctamente la edad</strong>';
}
if ($error == 'correo') {
echo '<strong style="color: red">Escriba correctamente su correo</strong>';
}
if ($error == 'pass') {
echo '<strong style="color: red">La contraseña no debe ser menos a 5 caracteres</strong>';
}
}
?>
<form method="POST" action="procesar_formulario.php">
<label for="nombre">Nombre:</label><br>
<input type="text" name="nombre" required="required" pattern="[a-zA-ZA]+" /><br>
<label for="apellidos">Apellidos:</label><br>
<input type="text" name="apellidos" required="required" pattern="[a-zA-ZA]+" /><br>
<label for="edad">Edad:</label><br>
<input type="number" name="edad" required="required" pattern="[0-9]+"/><br>
<label for="correo">Correo:</label><br>
<input type="email" name="correo" required="required" /><br>
<label for="pass">Contraseña:</label><br>
<input type="password" name="pass" required="required" minlength="5" /><br/>
<input type="submit" value="Enviar" />
</form>
</body>
</html><file_sep>/librerias-php/manipular-imgs/index.php
<?php
require_once '../vendor/autoload.php';
$foto_original = 'SILVpORTADA.jpg';
$guardar_en = 'nueva_portada.jpg';
$thumb = new PHPThumb\GD($foto_original);
//Redimensionar
$thumb->resize(250, 250);
//Recortar
$thumb->crop(50, 50, 120, 120);
//Show
$thumb->show();
$thumb->save($guardar_en);<file_sep>/principiosPHP/15-ejerciciosN2/modulos/fila1.php
<tr>
<td><?php echo $tabla['ACCION'][1]?></td>
<td><?php echo $tabla['AVENTURA'][1]?></td>
<td><?php echo $tabla['DEPORTES'][1]?></td>
</tr><file_sep>/php-MVC/config/conexion.php
<?php
class conexion{
public static function conectar(){
$conexion = new mysqli("localhost", "root", "", "blog");
$conexion->query("SET NAMES 'utf-8'");
return $conexion;
}
}<file_sep>/PHP-POO/12-autoload/clases/MisClases/categoria.php
<?php
namespace MisClases;
class categoria{
public $nombre;
public $descripcion;
public function __construct() {
$this->nombre = "tecnología";
$this->descripcion = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus repudiandae doloremque sint corporis veritatis veniam hic neque maiores, non nihil est ut dolore numquam laboriosam at minima unde excepturi, architecto.";
}
}<file_sep>/PHP-POO/index.php
<?php
require_once './02-constructor/pcMasterRace.php';
?><file_sep>/principiosSQL/09-ejercicios/ejercicio19.sql
/*
19. Obtener los profiles con 2 o más posts.
*/
SELECT * FROM profiles WHERE id IN
(SELECT id_profile FROM post GROUP BY id_profile HAVING COUNT(id)>=2 );
<file_sep>/principiosSQL/09-ejercicios/ejercicio03.sql
/*
3. Incrementar el id en 5 de la tabla categorias.
*/
UPDATE categoria SET id = 5;
<file_sep>/principiosSQL/09-ejercicios/ejercicio07.sql
/*
7. Mostrar el nombre y el id de los profiles con alias codexmaker
*/
SELECT nombre, id FROM profile WHERE alias='codexmaker';
<file_sep>/principiosSQL/09-ejercicios/ejercicio21.sql
/*
21. Obtener los nombre y ids de los usuarios con posts de 3 unidades adelante
*/
SELECT nombre, id FROM profile WHERE id IN
(SELECT id_profile FROM post);
<file_sep>/php-MVC/controllers/notaController.php
<?php
class notaController {
public function listar() {
//Modelo
require_once 'models/nota.php';
//Logica accion del controlador
$nota = new nota();
$notas = $nota->conseguirTodos('nota');
//Vista
require_once 'views/nota/listar.php';
}
public function crearNota() {
//Modelo
require_once 'models/nota.php';
$nota = new nota();
$nota->setUsuario_id(8);
$nota->setTitulo("Nota desde PHP MVC 2");
$nota->setContenido("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id blanditiis saepe totam, perferendis sapiente expedita ea, inventore obcaecati amet est illo eligendi, voluptatum aliquid odio alias hic nostrum accusantium sed.");
$guardar = $nota->guardar();
header("Location:index.php?controller=nota&action=listar");
}
public function borrarNota() {
}
public function conseguirTodos() {
return "Sacando todos los usuarios";
}
}<file_sep>/proyecto-php-poo-eshop/views/layout/header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Eshop</title>
<link rel="stylesheet" href="<?=base_url?>dist/css/styles.css">
<link rel="stylesheet" href="<?=base_url?>dist/css/bootstrap.min.css">
<link rel="stylesheet" href="<?=base_url?>dist/css/sweetalert2.min.css">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div id="container">
<!-- CABECERA -->
<header id="header">
<div id="logo">
<img src="<?=base_url?>dist/assets/img/logo.jpg" class="img-responsive" alt="logo">
<a href="<?=base_url?>">
Tienda Online
</a>
</div>
</header>
<!-- MENU -->
<?php $categorias = utils::showCategorias(); ?>
<nav id="menu">
<ul>
<li>
<a href="<?=base_url?>">Inicio</a>
</li>
<?php while ($cat = $categorias->fetch_object()) :?>
<li>
<a href="<?=base_url?>categoria/ver&id=<?=$cat->id?>"><?=$cat->nombre?></a>
</li>
<?php endwhile; ?>
</ul>
</nav>
<div id="content"><file_sep>/proyectoBlog/editar-entrada.php
<?php require_once 'modelos/redireccion.php'; ?>
<?php include_once 'modelos/helpers.php'; ?>
<?php include_once 'modelos/cabecera.php'; ?>
<?php
$entrada_actual = conseguirEntrada($db, $_GET['id']);
?>
<?php require_once 'modelos/lateral.php'; ?>
<div id="principal">
<h1>Editar Entrada</h1>
<p>
Edita tu post <?=$entrada_actual['titulo'] ?> y guarda los cambios!
</p>
<br>
<form action="guardar-entrada.php?editar=<?=$entrada_actual['id'] ?>" method="POST">
<label for="titulo">Titulo : </label>
<input type="text" name="titulo" value="<?=$entrada_actual['titulo'] ?>">
<?php echo isset($_SESSION['errores_entrada']) ? mostrarError($_SESSION['errores_entrada'], 'titulo'): ''; ?>
<label for="descripcion">Descripción : </label>
<textarea name="descripcion" id="" cols="100" rows="10"><?=$entrada_actual['descripcion'] ?></textarea>
<?php echo isset($_SESSION['errores_entrada']) ? mostrarError($_SESSION['errores_entrada'], 'descripcion'): ''; ?>
<label for="categoria">Categoría</label>
<select name="categoria" id="">
<?php echo isset($_SESSION['errores_entrada']) ? mostrarError($_SESSION['errores_entrada'], 'categoria'): ''; ?>
<?php $categorias = mostrarCategorias($db);
if (!empty($categorias)) :
while ($categoria =mysqli_fetch_assoc($categorias)) :
?>
<option value="<?=$categoria['id']?>"
<?=($categoria['id'] == $entrada_actual['categoria_id']) ? 'selected=selected' : '' ?>>
<?=$categoria['nombre']?>
</option>
<?php
endwhile;
endif;
?>
</select>
<input type="submit" value="Guardar">
</form>
<?php borrarErrores(); ?>
</div>
<?php require_once 'modelos/footer.php'; ?> <file_sep>/principiosPHP/15-ejerciciosN2/ejercicio1.php
<?php
/*
ex1. Hacer un programa en PHP que tenga un array con 8 numeros enteros y que haga lo siguiente:
-recorrerlo y mostrarlo
-ordenarlo y mostrarlo
-mostrar su longitud
-buscar algun elemento
-buscar por el parametro que me lluegue por la url
*/
// FUNCIONES
function mostrarArray($numeros){
$resultado = "";
foreach ($numeros as $key => $numero) {
#$resultado = $resultado.$numero."<br>"
$resultado .= $numero."<br>";
}
return $resultado;
}
$numeros = ['7','4','2','1','3','5','6','8'];
echo "<h2>Recorrer y mostrar</h2>";
echo mostrarArray($numeros);
echo "<hr>";
echo "<h2>Ordenar y mostrar</h2>";
sort($numeros);
echo mostrarArray($numeros);
echo "<hr>";
echo "<h2>Mostrar longitud</h2>";
$numElementos = count($numeros);
echo $numElementos;
echo "<hr>";
$valor = $_GET['value'];
$search = array_search($valor, $numeros);
echo "<h2>Buscar dato en el array</h2>";
if (!empty($search)) {
echo "<h4>El numero buscado existe, en el indice: $search</h4>";
}else{
echo "El numero no existe";
}
?><file_sep>/principiosPHP/12-funciones/variables.php
<?php
/*
Variables locales:Se definen dentro de una funcion y no pueden ser usadas fuera de la funcion, solo disponibles dentro. A no ser que haga un return.
*
Variables globales: son las que se declaran fuera de una funcion y estan disponibles dentro y fuera de las funciones.
*/
//Variable global
$frase = "Ni los genios son tan genios, ni los mediocres tan mediocres";
function holaMundo(){
#decirle que la varieble es global o no se imbuira
global $frase;
echo "<h1>$frase</h1><br>";
$year = 2019;
echo "<h1>$year</h1>";
echo "<hr>";
return $year;
}
holaMundo();
//Funciones variables
function buenosDias(){
echo "<h3>Hola, buenos dias</h3>";
}
function buenasTrades(){
echo "<h3>Bienvenido de vuelta</h3>";
}
function buenasNoches(){
echo "<h3>Es hora de salir</h3>";
}
$horario = "Noches";
$miFuncion = "buenas".$horario;
echo $miFuncion();
?><file_sep>/principiosPHP/07-Superglobales/index.php
<?php
//Variables superglobales
//Variables servidor
#manda la direccion IP donde se encuentra el servidor
echo '<h1>'.$_SERVER['SERVER_ADDR'].'</h1>';
#MANDA EL NOMBRE DEL SERVIDOR
echo '<h1>'.$_SERVER['SERVER_NAME'].'</h1>';
#manda el software en el que correl el servidor
echo '<h1>'.$_SERVER['SERVER_SOFTWARE'].'</h1>';
#manda el navegador que usa el usuario
echo '<h1>'.$_SERVER['HTTP_USER_AGENT'].'</h1>';
#manda la ip del usuario
echo '<h1>'.$_SERVER['REMOTE_ADDR'].'</h1>';
?><file_sep>/principiosSQL/09-ejercicios/ejercicio22.sql
/*
22. Mostrar listado de post (id y titular)
mostrar tambien el numero del usuario y su nombre.
*/
SELECT p.id, p.titulo, pro.id, CONCAT(pro.nombre,' ',pro.apellidos) as 'publicacion'
FROM post p, profile pro
WHERE p.id_profile =pro.id;<file_sep>/principiosSQL/09-ejercicios/ejercicio10.sql
/*
10. Visualizar los apellidos de los profiles, su numero de id, mostrar los 4 ultimos
ordenado por nombre */
SELECT apellidos, id FROM profiles ORDER BY nombre DESC LIMIT 4;
<file_sep>/proyecto-php-poo-eshop/views/productos/gestion.php
<h1>Gestion productos</h1>
<a class="button btn-small" href="<?=base_url?>producto/crear">
Crear producto
</a>
<!-- Alerta Exito&Error agregar producto -->
<?php if (isset($_SESSION['producto']) && $_SESSION['producto'] == 'complete'):?>
<div class="alert alert-success alert-dismissible fade show" role="alert">Registro completado correctamente
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php elseif (isset($_SESSION['producto']) && $_SESSION['producto'] !== 'complete'):?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">Registro fallido, introduce bien los datos
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php endif; ?>
<?php utils::deleteSession('producto'); ?>
<!-- Alerta Exito&Error eliminado producto -->
<?php if (isset($_SESSION['delete']) && $_SESSION['delete'] == 'complete'):?>
<div class="alert alert-success alert-dismissible fade show" role="alert">Registro borrado correctamente
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php elseif (isset($_SESSION['delete']) && $_SESSION['delete'] !== 'complete'):?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">Borrado fallido
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button></div>
<?php endif; ?>
<?php utils::deleteSession('delete'); ?>
<table class="table">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Precio</th>
<th scope="col">Stock</th>
<th scope="col">Acciones</th>
</tr>
<?php while ($pro = $productos->fetch_object()) : ?>
<tr>
<th scope="col"><?=$pro->id; ?></th>
<th scope="col"><?=$pro->nombre; ?></th>
<th scope="col"><?=$pro->precio; ?></th>
<th scope="col"><?=$pro->stock; ?></th>
<td>
<a href="<?=base_url?>producto/editar&id=<?=$pro->id; ?>" class="button button-gestion">Editar</a>
<a href="<?=base_url?>producto/eliminar&id=<?=$pro->id; ?>" class="button button-gestion button-eliminar">Eliminar</a>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<file_sep>/principiosSQL/09-ejercicios/ejercicio18.sql
/*
18. Listar los profiles que han hecho algun comentario en el post con la ip "192.168.102"
*/
SELECT * FROM profile WHERE id IN
(SELECT id_profile FROM post WHERE id_profile
IN (SELECT id FROM comentario WHERE ip LIKE '%192.168.102%'));
<file_sep>/principiosSQL/06-subconsultas/consultas.sql
/*
SUBCONSULTAS:
- Son consultas que se ejecutan dentro de otras.
- Consiste en uutilizar los resultados de la subconsulta para operar en la
consulta principal.
- Jugando con las claves ajenas / foraneas.
*/
#Sacar usuarios con entradas#
SELECT * FROM usuarios WHERE id IN (SELECT usuario_id FROM entradas);
#Sacar los usuarios que tengan alguna entrada que en su titulo hable de GTA#
SELECT nombre, apellidos FROM usuarios WHERE id
IN (SELECT usuario_id FROM entradas WHERE titulo LIKE "%GTA%");
#Sacar todas las entradas de la categoria acción utilizando su nombre#
SELECT categoria_id, titulo FROM entradas WHERE categoria_id
IN (SELECT id FROM categorias WHERE nombre = 'Deportes');
#Mostrar las categorias con 3 o más entradas#
SELECT * FROM categorias WHERE
id IN (SELECT categoria_id FROM entradas GROUP BY categoria_id HAVING COUNT(categoria_id)>=3);
#Mostrar los usuarios que crearon una entrada un martes#
SELECT * FROM usuarios WHERE id IN
(SELECT usuario_id FROM entradas WHERE DAYOFWEEK(fecha)=3);
#Mostrar el nombre del usuario que tenga mas entradas#
SELECT CONCAT(nombre,' ',apellidos) AS 'El usuario con mas entradas' FROM usuarios WHERE id =
(SELECT usuario_id FROM entradas GROUP BY usuario_id ORDER BY COUNT(id) DESC LIMIT 1);
#Mostrar las categorias sin entradas#
SELECT * FROM categorias WHERE id
NOT IN (SELECT categoria_id FROM entradas);
<file_sep>/principiosSQL/02-modificar-tablas/modificar.sql
# RENOMBRAR UNA TABLA #
ALTER TABLE usuarios RENAME TO usuarios_renom;
# CAMBIAR NOMBRE DE UNA COLUMNA #
ALTER TABLE usuarios_renom CHANGE apellidos apellido varchar(100) null;
# MODIFICAR COLUMNA SIN CAMBIAR NOMBRE #
ALTER TABLE usuarios_renom MODIFY apellido char(40) not null;
# AÑADIR COLUMNA #
ALTER TABLE usuarios_renom ADD website varchar(100) null;
# AÑADIR RESTRICCIÓN A COLUMNA #
ALTER TABLE usuarios_renom ADD CONSTRAINT uq_email UNIQUE(email);
# BORRAR UNA COLUMNA #
ALTER TABLE usuarios_renom DROP website;<file_sep>/PHP-POO/04-estaticas/index.php
<?php
require_once 'configuracion.php';
configuracion::setColor("black");
configuracion::setEntorno("localhost");
configuracion::setNewsletter(true);
echo configuracion::$color . '<br>';
echo configuracion::$entorno . '<br>';
echo configuracion::$newsletter . '<br>';
$configuracion = new configuracion();
//asi se accede a propiedades estaticas
$configuracion::$color = "red";
echo $configuracion::$color;<file_sep>/basicsLaravel/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/peliculas/{pagina?}', 'peliculaController@index');
Route::get('/detalle/{year?}',[
'middleware' => 'testYear',
'uses' => 'peliculaController@detalle',
'as' => 'detalle.pelicula'
]);
//reedirigir
Route::get('/reedirigir', 'peliculaController@index');
Route::get('/formulario', 'peliculaController@formulario');
Route::post('/recibir', 'peliculaController@recibirData');
//Rutas usuario
Route::group(['prefix'=>'usuario'], function(){
Route::get('/index','usuarioController@index');
Route::get('/details/{id}','usuarioController@details');
Route::get('/create', 'usuarioController@create');
Route::post('/save', 'usuarioController@save');
Route::get('/delete/{id}', 'usuarioController@delete');
Route::get('/edit/{id}', 'usuarioController@edit');
Route::post('update', 'usuarioController@update');
});
/*
GET: Conseguir datos
POST: Guardar datos
PUT: Actualizar recursos
DELETE: Borrar recursos
*/
/*
Route::get('/mostrar-fecha', function(){
$titulo = "Esta es la fecha de hoy:";
return view('mostrar_fecha', array(
'titulo' => $titulo
));
});
Route::get('/pelicula/{titulo}/{year?}', function($titulo = 'No hay una pelicula selecionada', $year ='2019'){
return view('pelicula', array(
'titulo' => $titulo,
'year' => $year
));
})->where(array(
'titulo' => '[a-z]+',
'year' => '[0-9]+'
));
Route::get('/listado-peliculas', function(){
$title = 'Listado de elementos 2';
$name = '<NAME>';
$lista = array('uno', 'dos', 'tres');
$user1 = "Hola soy el usuario 1";
return view('peliculas.listado')
->with('title',$title)
->with('lista',$lista)
->with('user1',$user1);
});
Route::get('pagina-generica', function(){
return view('pagina');
});*/
<file_sep>/principiosPHP/06-OperadoresAritmeticos/index.php
<h1>Operadores aritméticos</h1>
<?php
//Operadores aritméticos
$numero1 = 55;
$numero2 = 33;
echo 'Suma: '.($numero1+$numero2).'<br>';
echo 'Resta: '.($numero1-$numero2).'<br>';
echo 'Multiplicación: '.($numero1*$numero2).'<br>';
echo 'División: '.($numero1/$numero2).'<br>';
echo 'Resto: '.($numero1%$numero2).'<br>';
echo '<h2>Operadores incremento y decremento</h2>';
//Operadores incremento y decremento
$year = 2019;
#incremento $year = $year+1
$year++;
echo '<h1>'.$year.'</h1>';
#decremento $year = $year-1
$year--;
echo '<h1>'.$year.'</h1>';
//Operadores de asignación
echo '<h2>Operadores de asignación</h2>';
$edad = 55;
echo $edad.'<br>';
#edad = edad + 5 - * o /
echo ($edad+=5);
?><file_sep>/librerias-php/depurar/index.php
<?php
require_once '../vendor/autoload.php';
$frutas = array("mazanas", "peras", "naranjas");
\FB::log($frutas);
echo "Hola Mundo!!";
\FB::log("Muestrame esto en consola"); <file_sep>/principiosSQL/09-ejercicios/ejercicio14.sql
/*
14. Visualizar las unidades totales vendidas de cada coche a cada cliente.
Mostrando el nombre del coche, numero de cliente y la suma de unidades.
*/
SELECT co.modelo AS 'COCHE', cl.nombre AS 'CLIENTE', SUM(e.cantidad) AS 'UNIDADES'
FROM encargos e
INNER JOIN coches co ON co.id = e.coche_id
INNER JOIN clientes cl ON cl.id = e.cliente_id
GROUP BY e.coche_id, e.cliente_id;<file_sep>/principiosSQL/09-ejercicios/ejercicio11.sql
/*
11. Visualizar todos los correos y el numero de profiles que hay en cada registro
*/
SELECT correo, COUNT(id) FROM profile GROUP BY correo;
<file_sep>/principiosPHP/16-sesiones/logout.php
<?php
/**/
session_start();
//cierro la session
session_destroy();
?><file_sep>/principiosSQL/09-ejercicios/ejercicio02.sql
/*
2. Modificar el nombre del perfil donde nombre sea samuel
*/
UPDATE profile SET nombre = 'codexmaker' WHERE nombre = 'samuel';
<file_sep>/principiosSQL/09-ejercicios/ejercicio29.sql
/*
29. Crear una vista llamada primerosUsuarios que incluirá todos los usuarios que tengan relacion su correo con
las la silaba cod
*/
CREATE VIEW primerosUsuarios AS
SELECT * FROM profile WHERE grupo_id IN
(SELECT id FROM grupos WHERE nombre="<NAME>");
<file_sep>/principiosPHP/11-ejercicios/ejercicio7.php
<?php
/*
Ex7. Hacer un programa que muestre todos los numeros 'IMAPARES' entre dos numeros nos lleguen por la URL($_GET)
*/
if (isset($_GET['value1']) && isset($_GET['value2'])) {
$value1 = $_GET['value1'];
$value2 = $_GET['value2'];
echo '<h2>Las variables que vienen por GET son: '.$value1." and ".$value2.'</h2>';
echo "<h3>Numeros entre el value1 y el value2</h3>";
if ($value1 < $value2) {
for ($i=$value1; $i <=$value2 ; $i++) {
if ($i%2 != 0) {
echo $i.'<br>';
}
}
}else{
echo "<h2>El numero 1 debe ser menos al numero 2</h2>";
}
}else{
echo "<h3>Error de parametros get</h3>";
}
?><file_sep>/principiosPHP/07-Superglobales/recibir.php
<h1>Recibir data por methodo POST</h1>
<?php
//Recibir data
echo '<h2>'.$_POST['nombre'].'</h2>';
echo '<h2>'.$_POST['apellidos'].'</h2>';
var_dump($_POST);
?><file_sep>/proyecto-php-poo-eshop/autoload.php
<?php
function controller_autoload($class) {
include 'controllers/'.$class.'.php';
}
spl_autoload_register('controller_autoload');
<file_sep>/principiosPHP/02-ImprimirPantalla/index.php
<html>
<head>
<meta charset="utf-8">
<title>Imprimir por pantalla</title>
</head>
<body>
<h1>Impresion por pantalla con PHP-GUIDE by
<!--Se designa la variable con un nombre y se imprime -->
<?php $nombre = "CODEXMAKER";
echo $nombre;?>
</h1>
<!--Echo implicito -->
<?="Bienvenido a las clases de codexmaker"?>
<?php
// Titular de la seccion
/*Comentario multilinea
-----------testing*/
echo "<h3>Listado de datos</h3>";
#listado de datos
echo "<ul>"
."<li>PrimerDato</li>"
."<li>SegundoDato</li>"
."<li>TercerDato</li>"
."</ul>";
#concatenacion de codigo
echo '<p>Esta es toda'.'-'.' lista de datos</p>';
?>
</body>
</html>
<file_sep>/principiosSQL/09-ejercicios/ejercicio26.sql
/*
26. Sacar los usuarios que tienen comentarios y sacar el contenido del comentario
*/
SELECT CONCAT(v1.nombre,' ',v1.apellidos) AS 'USUARIOS', CONCAT(v2.comentario) AS 'COMENTARIOS'
FROM profile v1
INNER JOIN comentario v2 ON v1.id = v2.id;<file_sep>/PHP-POO/07-interfaces/index.php
<?php
interface Ordenador{
public function encender();
public function apagar();
public function reiniciar();
public function desfragmentar();
public function detectarUsb();
}
class iMac implements Ordenador{
private $modelo;
function getModelo() {
return $this->modelo;
}
function setModelo($modelo) {
$this->modelo = $modelo;
}
//cumplo contrato de la interfaz
public function encender() {
}
public function apagar() {
}
public function reiniciar() {
}
public function desfragmentar(){
}
public function detectarUsb(){
}
}
$maquintosh = new iMac();
$maquintosh->setModelo('Macbook Pro 2019');
echo $maquintosh->getModelo(); <file_sep>/PHP-POO/12-autoload/clases/MisClases/entrada.php
<?php
namespace MisClases;
class entrada{
public $titulo;
public $fecha;
public function __construct() {
$this->titulo = "Primera entrada";
$this->fecha = "2 agosto 2019";
}
}
<file_sep>/principiosPHP/20-ficheros/index.php
<h1>Test de ficheros</h1>
<form method="POST" action="index.php">
<label for="texto">Texto:</label><br>
<input type="text" name="texto" required="required" pattern="[a-zA-ZA ]+" /><br>
<input type="submit" value="Enviar" />
<?php
/*
if (!empty($_POST['texto'])) {
$texto = $_POST['texto'];
echo "recibi el texto y es: $texto"."<br>";
#abrir archivo
#permisos a+ permiten leer y escribir
$archivo = fopen("fichero_texto.txt","a+");
echo "<hr>";
#leer archivo
while (!feof($archivo)) {
$contenido = fgets($archivo);
echo $contenido."<br>";
}
fwrite($archivo, $texto);
#cerrar archivo
fclose($archivo);
}
*/
?>
</form>
<?php
/*COPIAR ARCHIVO
copy('fichero_texto.txt', 'fichero_copiado.txt') or die("Error al copiar");
*/
//renombrar fichero
//rename('fichero_copiado.txt','archivito_recopiadito.doc');
if (file_exists("fichero_texto.txt")) {
echo "El archivo existe";
}
?><file_sep>/principiosPHP/10-bucle-for/index.php
<?php
/*
for(expresion inicial, condición, incremento o decremento del contador){
//Bloque de instrucciones
}
*/
$resultado = 0;
for ($i=0; $i <= 100 ; $i++) {
$resultado += $i;
}
echo '<h1> El resultado es: '.$resultado.'</h1><br>';
#tabla de multiplicar
if (isset($_GET['numero'])) {
//Cambiar tipo de dato
$numero = (int)$_GET['numero'];
}else{
$numero =1;
}
echo "<h1>Tabla de multiplicar del numero: $numero</h1>";
for($contador = 1; $contador <= 10; $contador++) {
#adentro del bucle comprueba y ejecuta la detencion de la funcion
if ($numero == 27) {
echo "No se puede mostrar este numero";
break;
}
echo "$numero x $contador =".($numero*$contador)."<br>";
}
?><file_sep>/proyectoBlog/crear-categoria.php
<?php require_once 'modelos/redireccion.php'; ?>
<?php include_once 'modelos/cabecera.php'; ?>
<?php require_once 'modelos/lateral.php'; ?>
<div id="principal">
<h1>Crear categorías</h1>
<p>
Añade nuevas categorias al blog para que los usuarios puedan usarlas al crear sus entradas
</p>
<br>
<form action="guardar-categoria.php" method="POST">
<label for="nombre">Nombre de la categoria :</label>
<input type="text" name="nombre">
<input type="submit" value="Guardar">
</form>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><hr>
</div>
<!-- PIE DE PÁGINA -->
<?php require_once 'modelos/footer.php'; ?> <file_sep>/PHP-POO/12-autoload/index.php
<?php
require_once 'autoload.php';
//Si se va a ocupar mucho el namespace
use MisClases\usuario;
use MisClases\categoria;
use MisClases\entrada;
use panelAdministrador\usuario as usuarioAdmin;
class Principal{
public $usuario;
public $categoria;
public $entrada;
public function __construct() {
$this->usuario = new usuario();
$this->categoria = new categoria();
$this->entrada = new entrada();
}
public function getUsuario() {
return $this->usuario;
}
public function setUsuario($usuario) {
$this->usuario = $usuario;
}
public function getCategoria() {
return $this->categoria;
}
public function setCategoria($categoria) {
$this->categoria = $categoria;
}
public function getEntrada() {
return $this->entrada;
}
public function setEntrada($entrada) {
$this->entrada = $entrada;
}
function informacion() {
echo __CLASS__."<br>";
echo __METHOD__."<br>";
echo __FILE__."<br>";
}
}
$principal = new Principal();
$principal->informacion();
//var_dump($principal->usuario);
echo("<br>");
//sacar los metodos de una clase
$metodos = get_class_methods($principal);
$busqueda = array_search('setEntrada', $metodos);
var_dump($busqueda);//buscar el metodo en el array
//Objeto de otro paquete
//$usuario = new usuarioAdmin();
//var_dump($usuario);
// Comprobar si existe una clase
$clase = class_exists('MisClases\usuario');
if ($clase) {
echo "<h1>La clase si existe</h1>";
}else{
echo "<h1>La clase no existe</h1>";
}<file_sep>/principiosSQL/09-ejercicios/ejercicio20.sql
/*
20. Seleccionar el comentario donde el usuario comento
*/
SELECT * FROM comentario WHERE id IN
(SELECT id_profile FROM);
<file_sep>/principiosSQL/05-agrupamiento/insert.sql
#INSERTS PARA CATEGORIAS#
INSERT INTO categorias VALUES(null, 'Acción');
INSERT INTO categorias VALUES(null, 'Rol');
INSERT INTO categorias VALUES(null, 'Deportes');
#INSERTS PARA ENTRADAS#
INSERT INTO entradas VALUES(null, 1, 1, 'Novedades de GTA 5 Online', 'Review del GTA 5', CURDATE());
INSERT INTO entradas VALUES(null, 1, 2, 'REVIEW de LOL Online', 'Todo sobre el LOL', CURDATE());
INSERT INTO entradas VALUES(null, 1, 3, 'Nuevos jugadores de Fifa 19', 'Review del Fifa 19', CURDATE());
INSERT INTO entradas VALUES(null, 2, 1, 'Novedades de Assasins Online', 'Review del Assasins', CURDATE());
INSERT INTO entradas VALUES(null, 2, 2, 'REVIEW de WOW Online', 'Todo sobre el WOW', CURDATE());
INSERT INTO entradas VALUES(null, 2, 3, 'Nuevos jugadores de PES 19', 'Review del Pro 19', CURDATE());
INSERT INTO entradas VALUES(null, 3, 1, 'Novedades de Call Of Duty Online', 'Review del COD', CURDATE());
INSERT INTO entradas VALUES(null, 3, 1, 'REVIEW de Fortnite Online', 'Todo sobre el Fortnite', CURDATE());
INSERT INTO entradas VALUES(null, 3, 3, 'Nuevos jugadores de Formula 1 2k20', 'Review del Formula 1', CURDATE());<file_sep>/PHP-POO/09-destructor/index.php
<?php
class Usuario{
public $nombre;
public $email;
public function __construct() {
$this->nombre = "<NAME>";
$this->email = "<EMAIL>";
echo "Creando el objeto creada <br>";
}
public function __toString() {
return "Hola, {$this->nombre}, estas registrado con: {$this->email} ";
}
public function __destruct() {
echo " <br> Destruyendo el objeto";;
}
}
$usuario = new Usuario();
echo $usuario;
<file_sep>/principiosSQL/01-tablas/crear-tabla.sql
/*
TIPOS DE DATOS:
int(nº cifras) ENTERO
integer(nº cifras) ENTERO (maximo 4294967295)
varchar(nº caracteres) STRING / ALFANUMERICO (maximo 255)
char(nº caracteres) STRING / ALFANUMERICO
float(nº cifras, nº decimales) DECIMAL / COMA FLOTANTE
date, time, timestamp
// STRING MAS GRANDES
TEXT 65535 caracteres
MEDIUMTEXT 16 millones
LONGTEXT 4 billones de caracteres
// ENTEROS MAS GRANDE
MEDIUMINT
BIGINT
*/
/*
CREAR TABLA
*/
CREATE TABLE usuarios(
id int(11) auto_increment not null,
nombre varchar(100) not null,
apellidos varchar(255) default '<PASSWORD>',
email varchar(100) not null,
password varchar(255),
CONSTRAINT pk_usuarios PRIMARY KEY(id)
);<file_sep>/proyectoBlog/entrada.php
<?php include_once 'modelos/helpers.php'; ?>
<?php include_once 'modelos/cabecera.php'; ?>
<?php
$entrada_actual = conseguirEntrada($db, $_GET['id']);
?>
<?php require_once 'modelos/lateral.php'; ?>
<div id="principal">
<h1><?= $entrada_actual['titulo']; ?></h1>
<a href="categoria.php?id=<?= $entrada_actual['categoria_id'] ?>">
<h2><?= $entrada_actual['categoria']; ?></h2>
</a>
<h4><?= $entrada_actual['fecha']; ?> | <?=$entrada_actual['usuario'];?></h4>
<p><?= $entrada_actual['descripcion']; ?></p>
<?php if(isset($_SESSION['usuario']) && $_SESSION['usuario']['id'] == $entrada_actual['usuario_id']): ?>
<a href="editar-entrada.php?id=<?= $entrada_actual['id'] ?>" class="boton boton-A0"> Editar entrada</a>
<a href="borrar-entrada.php?id=<?= $entrada_actual['id'] ?>" class="boton boton-B"> Borrar entrada</a>
<?php endif; ?>
</div>
<?php require_once 'modelos/footer.php'; ?> <file_sep>/principiosPHP/17-cookies/ver_cookies.php
<?php
/*Ver las cookies*/
if (isset($_COOKIE['micookie'])) {
echo "<h1>".$_COOKIE['micookie']."</h1>";
}else{
echo "No existe la cookie";
}
if (isset($_COOKIE['unyear'])) {
echo "<h1>".$_COOKIE['unyear']."</h1>";
}else{
echo "No existe la cookie";
}
?>
<a href="crear_cookies.php">Crear mis galletas</a>
<a href="borrar_cookies.php">Borrar mis galletas</a><file_sep>/principiosPHP/15-ejerciciosN2/modulos/fila0.php
<tr>
<td><?php echo $tabla['ACCION'][0]?></td>
<td><?php echo $tabla['AVENTURA'][0]?></td>
<td><?php echo $tabla['DEPORTES'][0]?></td>
</tr><file_sep>/principiosPHP/16-sesiones/pagina1.php
<?php
/*Pasar la variable de sesion*/
session_start();
echo $_SESSION["variable_persistente"];
?><file_sep>/principiosPHP/16-sesiones/index.php
<?php
/*
SESIONES:
PERIODO DE TIEMPO QUE EL USUARIO PERMANECE EN LA PAGINA SIN NECESIDAD DE IDENTIFICARSE MIENTRAS ESTA EN LA PAGINA:
DEBE SOPORTAR DOS COSAS
-SESION PERSISTE HASTA QUE USUARIO CIERRE SESION O EL NAVEGADOR
-GUARDAR INFORMACION
*/
//INICIAR LA SESION
session_start();
#VARIABLE LOCAL
$variable_normal = "Soy una cadena de texto";
#VARIABLE DE SESION
$_SESSION['variable_persistente'] = "HOLA SOY UNA SESION ACTIVA";
echo $variable_normal."<br>";
echo $_SESSION['variable_persistente'];
?><file_sep>/principiosPHP/12-funciones/predefinidas.php
<?php
/*
//Funciones predefinidas de php
*/
//Debuggear
$nombre ="<NAME>";
var_dump($nombre);
echo "<hr>";
//Fechas
echo date('d-m-Y');
echo "<br>";
echo "timestamp:".time();
echo "<hr>";
//Matematicas
echo "Raiz cuadrada de 10: ".sqrt(10);
echo "<br>";
echo "Numero aletorio entre 0 y 1000: ".rand(0,1000);
echo "<br>";
echo "Numero Pi: ".pi();
echo "<br>";
echo "Redondear: ".round(17.58421);
echo "<br>";
echo "<hr>";
//Más funciones generales
echo gettype($nombre);
echo "<br>";
#detecion de tipo de dato
if (is_string($nombre)) {
echo "Esta variable es un string";
}else{
echo "La variable no es una string";
}
echo "<br>";
#detecion de tipo de dato
if (is_float($nombre)) {
echo "Esta variable es un double";
}else{
echo "La variable no es un numero con decimales";
}
echo "<br>";
#comprobar existencia
if (isset($edad)) {
echo "La variable existe";
}else{
echo "La variable no existe";
}
echo "<br>";
$frase = " mi contenido ";
var_dump(trim($frase));
echo "<br>";
//Eliminar variablews / indices
$year = 2222;
unset($year);
//Comprueba si la variable esta vacia
$texto ="";
if (empty($texto)) {
echo "La variable texto esta vacia.";
}else{
echo "La variable tiene contenido";
}
echo "<br>";
//Cuantos carateres tiene una cadena/string
$cadena ="12345";
echo strlen($cadena);
echo "<br>";
//encontrar caracter
$frase = "la vida es bella";
echo strpos($frase, "vida");
echo "<br>";
//Reemplazar contenido de un string
$frase = str_replace("vida", "moto", $frase);
echo "$frase";
echo "<br>";
//Mayusculas y minusculas
echo strtolower($frase);
echo "<br>";
echo strtoupper($frase);
?><file_sep>/principiosSQL/09-ejercicios/ejercicio12.sql
/*
12. Conseguir la masa de la suma de las id´s de profile
*/
SELECT SUM(id) as 'Masa Id´s' FROM profile;
<file_sep>/principiosSQL/09-ejercicios/ejercicio06.sql
/*
6. Visualizar el titulo y titular de los post en una misma columna,
su fecha de registro y el dia de la semana en la que se registraron.
*/
SELECT CONCAT(titulo, ' ', titular) AS 'titulo y titular',
fecha, DAYNAME(fecha) FROM post;
<file_sep>/principiosSQL/09-ejercicios/ejercicio30.sql
/*
30. Mostrar los datos del post con mas antiguedad en el sistema.
*/
SELECT * FROM post ORDER BY fecha ASC LIMIT 1;
<file_sep>/principiosPHP/17-cookies/crear_cookies.php
<?php
/*
Cookie: eEs un fichero que almacena en el ordenador del usuario que visita
la web, con el fin de recordar datos o rastrear el comportamiento del mismo
en la web.
*/
//setcookie("nombre","valor que solo pude ser texto", caducidad, ruta, dominio);
//cookie basica
setcookie("micookie","valor de mi galleta");
//cookie con expiracion
setcookie("unyear","valor de mi cookie de 365 dias", time()+(60*60*24*365));
header('Location:ver_cookies.php');
?>
<file_sep>/principiosSQL/09-ejercicios/ejercicio09.sql
/*
9. Mostrar todos los post del profile numero 1, ordenados titulo alfabeto descendente
*/
SELECT * FROM post WHERE id_profile=1 ORDER BY sueldo DESC;
<file_sep>/principiosSQL/04-dml/update.sql
#MODIFICAR FILAS / ACTUALIZAR DATOS#
UPDATE usuarios SET fecha='2019-07-09', apellidos='ADMIN' WHERE id=4; <file_sep>/principiosPHP/23-ejercicios/ejercicio2.php
<a href="ejercicio2.php?email=<EMAIL>">Mandar email</a>
<hr>
<?php
/*
validar un email con una funcion
pasar el parametro get a la funcion
imprimir la validacion
*/
require_once "funciones/functions.php";
if (isset($_GET['email'])) {
echo validarEmail($_GET['email']);
}else{
echo "Ingresa un email como variable get"."<br>";
}
?><file_sep>/PHP-POO/02-constructor/index.php
<?php
require_once 'pcMasterRace.php';
//Envio de datos al constructor
$pcMasterRace = new pcMasterRace("BlackSilver", "nvidia 1070 DualStrix", "AB gaming 2", "8", "ryzen 5 1600x", "CAM", "TUF Gaming Alliance");
//Visibilidad de propiedades y metodos
#publico cambia sin problemas
$pcMasterRace->color = "Rosa";
#protected necesita un metodo desde el constructor de modelo set
$pcMasterRace->setTarjetaVideo("ASUS 1080ti");
#private necesita un metodo get para obtnerse
#$pcMasterRace->setMotherboard("Plus Gaming xtreme");
//var_dump($pcMasterRace->getMotherboard()."<br>");
//var_dump($pcMasterRace);
//
//Llamar la funcion de mostrar pc
echo $pcMasterRace->mostrarInformacion($pcMasterRace);
?><file_sep>/proyecto-php-poo-eshop/views/pedido/detalle.php
<h1>Detalles del pedido</h1>
<?php if (isset($pedido)) : ?>
<?php if (isset($_SESSION['admin'])) : ?>
<center>
<h3>Cambiar estado del pedido</h3>
<form action="<?=base_url?>pedido/estado" method="POST">
<input type="hidden" value="<?=$pedido->id?>" name="pedido_id">
<select name="estado" style="width: 50%;">
<option value="confirm">Pendiente</option>
<option value="preparation">En preparación</option>
<option value="ready">Preparado para enviar</option>
<option value="sended">Enviado</option>
</select>
<input type="submit" value="Actualizar">
</form>
</center>
<br>
<?php endif ?>
<center>
<div class="col-md-12">
<h3>Dirección de envio</h3>
<label for="pro">Estado: <?=utils::showStatus($pedido->estado )?></label>
<label for="pro">Provincia: <?=$pedido->provincia ?></label>
<label for="pro">Ciudad: <?=$pedido->localidad ?></label>
<label for="pro">Dirección: <?=$pedido->direccion ?></label>
</div>
</center>
<center><h3>Datos del pedido</h3>
<label for="">Numero de pedido : <?=$pedido->id ?></label>
<label for="">Total a pagar : <?=$pedido->coste ?> mxn</label>
<h5>Producto(s)</h5>
<table>
<?php while ($producto = $productos->fetch_object()) : ?>
<tr>
<td>
<?php if ($producto->imagen !=null) : ?>
<img src="<?=base_url?>uploads/images/<?=$producto->imagen ?>" class="img_carrito" alt="">
<?php else: ?>
<?php echo "No se encontrol la imagen"; ?>
<?php endif; ?>
</td>
<td>
<a href="<?=base_url?>producto/ver&id=<?=$producto->id?>"><?=$producto->nombre?></a>
</td>
<td>
<?=$producto->precio?>
</td>
<td>
<!-- Al ser un array se entra con esta sintaxis -->
<?=$producto->unidades?>
</td>
</tr>
<?php endwhile; ?>
</table>
</center>
<?php endif; ?><file_sep>/PHP-POO/03-herencia/index.php
<?php
require_once 'clases.php';
$persona = new Persona();
var_dump($persona)."<br>";
$devWeb = new desarrolladorWeb();
var_dump($devWeb);
echo "<br>";
$auditor = new tecnicoRedes();
var_dump($auditor);
?><file_sep>/principiosSQL/09-ejercicios/ejercicio15.sql
/*
15. Mostrar los clientes que más encargos han hecho y mostrar cuantos hicieron
*/
SELECT c.nombre, COUNT(e.id) FROM encargos e
INNER JOIN clientes c ON c.id = e.cliente_id
GROUP BY cliente_id ORDER BY 2 DESC LIMIT 2;
<file_sep>/principiosPHP/11-ejercicios/ejercicio3.php
<?php
/*
Imprimir por pantalla los cuadrados de los 40 primeros numeros naturales o sea del 1 al 40
PD.Con bucle While
*/
$contador = 1;
while ($contador <= 40) {
$cuadrado = $contador*$contador;
echo "<h3>El cuadrado de : ".$contador." es ".$cuadrado."</h3><br>";
$contador++;
}
?><file_sep>/principiosPHP/04-TiposDatos/index.php
<?php
/*
TIPOS DE DATOS:
Entero (int / integer) = 99
Flotante / decimales (float / double) = 3.14
Cadenas (string) = "Codexm<NAME>"
Boleano (bool) = true, false
null
Array (Coleccion de datos)
Objetos
*/
$numero = 20;
$decimal = 25.23;
$texto = 'Soy un texto y concateno un valor '.$numero;
$verdadero = true;
$nula = null;
//Funcion que retorna el tipo de dato
echo $texto;
echo "<br>";
echo gettype($texto);
echo "<br>";
// Debugear
$mi_nombre[] = "SamuelVazquezRuiz Programador WEB";
$mi_nombre[] = "SamuelVazquezRuiz Programador WEB";
var_dump($mi_nombre);
?><file_sep>/proyecto-php-poo-eshop/views/carrito/index.php
<h1>Carrito de la compra</h1>
<?php if (isset($_SESSION['carrito']) && $_SESSION['carrito'] !=null) : ?>
<table class="table">
<thead>
<tr>
<th scope="col">Imagen</th>
<th scope="col">Nombre</th>
<th scope="col">Precio</th>
<th scope="col">Unidades</th>
<th class="col">Eliminar</th>
</tr>
<?php
foreach ($carrito as $indice => $elemento):
$producto = $elemento['producto'];
?>
<tr>
<td>
<?php if ($producto->imagen !=null) : ?>
<img src="<?=base_url?>uploads/images/<?=$producto->imagen ?>" class="img_carrito" alt="">
<?php else: ?>
<?php echo "No se encontrol la imagen"; ?>
<?php endif; ?>
</td>
<td>
<a href="<?=base_url?>producto/ver&id=<?=$producto->id?>"><?=$producto->nombre?></a>
</td>
<td>
<?=$producto->precio?>
</td>
<td>
<!-- Al ser un array se entra con esta sintaxis -->
<div class="updown-unidades">
<div class="row">
<div class="col-md-4">
<a href="<?=base_url?>carrito/down&index=<?=$indice?>" class="button" >-</a>
</div>
<div class="col-md-4">
<?=$elemento['unidades']?>
</div>
<div class="col-md-4">
<a href="<?=base_url?>carrito/up&index=<?=$indice?>" class="button" >+</a>
</div>
</div>
</div>
</td>
<td>
<center>
<div class="col-md-6">
<a href="<?=base_url?>carrito/remove&index=<?=$indice?>" class="btn btn-danger button" style="size: 50px;">Quitar producto</a>
</div>
</center>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="total_carrito">
<div class="row">
<div class="col-md-6">
<a href="<?=base_url?>carrito/delete_all" class="btn btn-danger button button_pedido">Eliminar todo(s)</a>
</div>
<div class="col-md-6">
<?php $stats = utils::statsCarrito(); ?>
<h3>Precio total: <?=$stats['total']?> mxn</h3>
<a href="<?=base_url?>pedido/hacer" class="button button_pedido">Hacer pedido</a>
</div>
</div>
</div>
<?php else: ?>
<p>El carrito esta vacio, añade algun producto</p>
<?php endif; ?><file_sep>/principiosPHP/18-formularios/guardar.php
<?php
/**/
if (isset($_POST['titulo']) && isset($_POST['descripcion'])) {
echo "datos recibidos"."<br>";
echo "<h1>".$_POST['titulo']."</h1><br>";
echo "<h1>".$_POST['descripcion']."</h1><br>";
}
?><file_sep>/principiosPHP/17-cookies/borrar_cookies.php
<?php
//caducar la cookie
if ($_COOKIE['micookie']) {
unset($_COOKIE['micookie']);
setcookie('micookie','',time()-100);
}
//funcion para modificar las cabeceras
header('Location:ver_cookies.php');
?>
|
c66d1cbc04cfedf2d991a31d310235b2145edebe
|
[
"SQL",
"PHP"
] | 125
|
PHP
|
CodeXMakerCompany/phpMasterBasics
|
f30e06af134f307dc509acecfd2cc2655e1e2a2f
|
ced7cd6a58bed2a9476d1462e8c21087ca726dc0
|
refs/heads/master
|
<file_sep>import 'styled-components';
import 'system-props';
export type Breakpoints = {
sm?: string;
md?: string;
lg?: string;
xl?: string;
};
type StyledTheme = typeof import('../styles/theme').default;
declare module 'styled-components' {
export interface DefaultTheme extends StyledTheme {}
}
declare module 'system-props' {
export interface Theme extends StyledTheme {}
}
<file_sep>import { modifyResponsiveValue } from '../modifyResponsiveValue';
test('works for all kind of responsive data structures', () => {
expect(modifyResponsiveValue([1, 2, 3], (n) => n + 1)).toEqual([2, 3, 4]);
expect(modifyResponsiveValue({ a: 1, b: 2 }, (n) => n - 1)).toEqual({
a: 0,
b: 1,
});
expect(modifyResponsiveValue(12, (n) => n * 2)).toEqual(24);
});
<file_sep>import { Breakpoints } from './styled';
const theme = {
colors: {
primary400: '#55F1D2',
primary500: '#18ECC0',
secondary400: '#984EF9',
secondary500: '#862EF7',
white: '#fff',
grey100: '#F9F9F8',
grey200: '#E2E2E0',
grey300: '#bdbdbd',
grey400: '#A8A8A8',
grey600: '#969696',
grey700: '#737373',
grey800: '#343434',
grey900: '#1B1B1B',
warning100: '#FFF0BD',
warning500: '#F0BB00',
success100: '#DBFFE3',
success500: '#0C9151',
error100: '#FFD1D1',
error500: '#CA1818',
transparent: 'rgba(255, 255, 255, 0);',
},
fontWeights: {
regular: 400,
medium: 500,
bold: 700,
},
fonts: {
heading: `Domaine Disp`,
body: `Inter`,
mono: `SFMono-Regular, Menlo, Monaco,C onsolas, "Liberation Mono", "Courier New", monospace`,
},
fontSizes: {
root: '14px',
0: '10px',
1: '12px',
2: '14px',
3: '16px',
4: '18px',
5: '20px',
6: '24px',
7: '32px',
8: '40px',
9: '48px',
10: '56px',
11: '64px',
heading: '32px',
},
lineHeights: {
normal: 1,
medium: 1.25,
high: 1.5,
},
space: {
0: 0,
'1/4': 2,
'1/2': 4,
'3/4': 6,
1: 8,
'5/4': 10,
'6/4': 12,
2: 16,
3: 24,
4: 32,
5: 40,
6: 48,
7: 56,
8: 64,
9: 72,
10: 80,
15: 120,
20: 160,
mobileGutter: 16,
},
sizes: {
maxWidth: 1140,
},
breakpoints: ['768px', '1024px', '1280px', '1440px'] as Breakpoints,
zIndices: {
hide: -1,
base: 0,
docked: 10,
dropdown: 1000,
sticky: 1100,
banner: 1200,
overlay: 1300,
modal: 1400,
popover: 1500,
skipLink: 1600,
toast: 1700,
tooltip: 1800,
},
radii: {
none: '0',
xs: '4px',
sm: '6px',
md: '8px',
lg: '16px',
full: '9999px',
},
borders: {
none: 0,
'1px': '1px solid',
'2px': '2px solid',
'4px': '4px solid',
},
shadows: {
sm: '0px 2px 0px rgba(0, 0, 0, 0.1), 0px 5px 10px rgba(0, 0, 0, 0.05)',
normal: '0px 2px 0px rgba(0, 0, 0, 0.1), 0px 5px 10px rgba(0, 0, 0, 0.05)',
big: '0px 2px 4px rgba(0, 0, 0, 0.1), 0px 10px 20px rgba(0, 0, 0, 0.1)',
none: 'none',
},
};
theme.breakpoints.sm = theme.breakpoints[0];
theme.breakpoints.md = theme.breakpoints[1];
theme.breakpoints.lg = theme.breakpoints[2];
theme.breakpoints.xl = theme.breakpoints[3];
export default theme;
<file_sep>export { default as css } from './css';
export * from './modifyResponsiveValue';
export * from './system';
export * from './styled';
<file_sep>export * from './components';
/** export all default icons */
export * from './components/common/Icon/library';
export * from './lib/modifyResponsiveValue';
export { default as css } from './lib/css';
export type { SystemProps } from './lib/system';
export * from './lib/system';
export * from './lib/styled';
export { default as theme } from './styles/theme';
<file_sep>/* istanbul ignore file */
export { default as Arrow } from './arrow';
export { default as BadgeError } from './badge-error';
export { default as Calendar } from './calendar';
export { default as Checkout } from './checkout';
export { default as ChevronDown } from './chevron-bottom';
export { default as ChevronLeft } from './chevron-left';
export { default as ChevronRight } from './chevron-right';
export { default as ChevronUp } from './chevron-top';
export { default as Close } from './close';
export { default as Facebook } from './facebook';
export { default as Gift } from './gift';
export { default as Heart } from './heart';
export { default as Help } from './help';
export { default as House } from './house';
export { default as Instagram } from './instagram';
export { default as Play } from './play';
export { default as Search } from './search';
export { default as Star } from './star';
export { default as Twitter } from './twitter';
export { default as Volume } from './volume';
export { default as ZoomIn } from './zoom-in';
export { default as ZoomOut } from './zoom-out';
<file_sep>import type { Config } from '@jest/types';
const config: Config.InitialOptions = {
testEnvironment: 'jsdom',
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
moduleNameMapper: {
'^~(.*)$': '<rootDir>/src/$1',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/components/common/Icon/__mocks__/req',
'\\.(css|less)$': '<rootDir>/__mocks__/styleMock.ts',
},
moduleDirectories: [
'node_modules',
'src/lib', // a utility folder
__dirname, // the root directory
],
setupFilesAfterEnv: ['./jest.setup.ts'],
coverageDirectory: './coverage',
};
export default config;
<file_sep><p align="center">
<a href="https://storyofams.com/" target="_blank" align="center">
<img src="https://storyofams.com/blog/story-of-ams-logo-small@3x.png" alt="Story of AMS" width="120">
</a>
<h1 align="center">@storyofams/react-ui example</h1>
</p>
<file_sep>import type {
ComponentType,
FunctionComponent,
ComponentClass,
ElementType,
} from 'react';
import type {
PolymorphicForwardRefExoticComponent,
PolymorphicPropsWithoutRef,
} from 'react-polymorphic-types';
import { default as _styled } from 'styled-components';
import { variant, ResponsiveValue } from 'styled-system';
import { system } from '~lib/system';
import css from './css';
type GenericObjectType = { readonly [key: string]: any };
type GenericNestedObjectType = { readonly [key: string]: GenericObjectType };
type GenericOptionalNestedObjectType = {
// allow for a non-nested structure as well
readonly [key: string]: string | number | GenericObjectType;
};
export type StyledConfigType = {
config?: {
readonly variant: GenericObjectType;
readonly [key: string]: GenericObjectType;
};
};
export type WithPolyMorphicProps<
DefaultElement extends ElementType,
Props extends {},
> = PolymorphicPropsWithoutRef<Props, DefaultElement>;
export type ComponentWithConfig<P> = FunctionComponent<P> & StyledConfigType;
type ComponentProps<Component> =
Component extends PolymorphicForwardRefExoticComponent<infer P, any>
? P
: Component extends FunctionComponent<infer P>
? P
: Component extends ComponentClass<infer P>
? P
: never;
type Intersection<
T1 extends Record<string | symbol | number, any>,
T2 extends Record<string | symbol | number, any>,
> = {
[P in keyof T1 | keyof T2 as unknown extends T1[P]
? never
: unknown extends T2[P]
? never
: P]?: ResponsiveValue<T1[P] | T2[P]>;
};
type Blend<T, U> = Omit<T, keyof U> & Omit<U, keyof T> & Intersection<T, U>;
type VariantKeys<T> = {
[P in keyof T]?: keyof T[P];
};
type OptionProps = {
readonly baseStyles?: GenericOptionalNestedObjectType;
readonly variants?: GenericNestedObjectType;
};
const mergeVariants = (
oldVariants: GenericNestedObjectType = {},
newVariants: GenericNestedObjectType = {},
) => ({
...oldVariants,
...Object.keys(newVariants)?.reduce(
(acc, curr) => ({
...acc,
[curr]: {
...oldVariants?.[curr],
...newVariants[curr],
},
}),
{},
),
});
export const styled = <
InheritedProps extends ComponentProps<Component>,
Variants extends OptionProps,
Component extends ComponentWithConfig<any>,
>(
component: Component,
{ baseStyles, variants = {} }: Variants,
): ComponentType<Blend<InheritedProps, VariantKeys<Variants['variants']>>> => {
const variantKeys = [
...Object.keys(variants),
...Object.keys(component?.config ?? {}).filter(
(variantKey) => Object.keys(variants).indexOf(variantKey) === -1,
),
] as const;
const newVars = variantKeys.map((varKey) => ({
prop: varKey,
variants: mergeVariants(component?.config?.[varKey], variants?.[varKey]),
}));
return _styled(component as any)`
${css(baseStyles)}
${newVars.map((newVariant) => variant(newVariant))}
&& {
${(props) => props.css}
${system}
}
` as Component;
};
<file_sep>export * from './common/Accordion';
export * from './common/Box';
export * from './common/Button';
export * from './common/Checkbox';
export * from './common/DatePicker';
export * from './common/Flex';
export * from './common/Grid';
export * from './common/Heading';
export * from './common/Icon';
export * from './common/Input';
export * from './common/InputWrapper';
export * from './common/Modal';
export * from './common/Breadcrumb';
export * from './common/Radio';
export * from './common/Select';
export * from './common/Spinner';
export * from './common/Stack';
export * from './common/StatusMessage';
export * from './common/Tag';
export * from './common/Text';
export * from './common/Textarea';
export * from './common/Toggle';
<file_sep>import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import filesize from 'rollup-plugin-filesize';
import external from 'rollup-plugin-peer-deps-external';
// import rename from 'rollup-plugin-rename';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';
import ttypescript from 'ttypescript';
const clear = require('rollup-plugin-clear');
const extensions = ['.tsx', '.ts'];
export default {
external: ['react', 'react-dom'],
input: ['./src/index.ts'],
output: [
{
dir: 'dist/cjs',
format: 'cjs',
exports: 'named',
sourcemap: true,
},
{
dir: 'dist/esm',
format: 'es',
exports: 'named',
sourcemap: true,
},
],
preserveModules: true,
plugins: [
clear({
targets: ['dist'],
watch: true,
}),
// external handles the third-party deps we've listed in the package.json
/** @note needs to come before resolve! */
external(),
resolve({
preferBuiltins: true,
}),
commonjs(),
typescript({
clean: true,
tsconfig: './tsconfig.build.json',
typescript: ttypescript,
}),
babel({
extensions,
babelHelpers: 'runtime',
exclude: ['node_modules/**'],
}),
// rename({
// include: ['**/*.js'],
// map: (name) => name.replace('node_modules/', 'external/'),
// }),
terser(),
filesize(),
],
};
<file_sep>import {create} from '@storybook/theming/create'
export default create({
base: 'light',
brandTitle: 'Story of AMS | React UI',
brandUrl: 'https://github.com/storyofams/react-ui',
brandImage: 'https://avatars.githubusercontent.com/u/19343504?v=2&s=75',
})
<file_sep><div align="center">
<a aria-label="Story of AMS logo" href="https://storyofams.com/" target="_blank" align="center">
<img src="https://avatars.githubusercontent.com/u/19343504" alt="Story of AMS" width="100">
</a>
<h1 align="center">@storyofams/react-ui</h1>
<p align="center">
<a aria-label="releases" href="https://GitHub.com/storyofams/react-ui/releases/" target="_blank">
<img src="https://github.com/storyofams/react-ui/workflows/Release/badge.svg">
</a>
<a aria-label="npm" href="https://www.npmjs.com/package/@storyofams/react-ui" target="_blank">
<img src="https://img.shields.io/npm/v/@storyofams/react-ui">
</a>
<a aria-label="codecov" href="https://codecov.io/gh/storyofams/react-ui" target="_blank">
<img src="https://codecov.io/gh/storyofams/react-ui/branch/master/graph/badge.svg?token=ZV0YT4HU5H">
</a>
<a aria-label="stars" href="https://github.com/storyofams/react-ui/stargazers/" target="_blank">
<img src="https://img.shields.io/github/stars/storyofams/react-ui.svg?style=social&label=Star&maxAge=86400" />
</a>
</p>
</div>
---
A collection of UI components build to create a production grade front-end experience with react & [Next.js](https://nextjs.org/)
---
# [Available components](https://react-ui-storyofams.vercel.app/)
| component | description |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [Accordion](https://react-ui-storyofams.vercel.app/?path=/story/components-accordion--basic) | Vertically stacked list of items that can be collapsed/expanded individually |
| [Box](https://react-ui-storyofams.vercel.app/?path=/story/components-box--basic) | The base for all components |
| [Breadcrumb](https://react-ui-storyofams.vercel.app/?path=/story/components-breadcrumb--basic) | Shows the current path with the ability to navigate to each sub-path individually |
| [Button](https://react-ui-storyofams.vercel.app/?path=/story/components-button--primary) | Simple button component (see storybook for the most up to date variants) |
| [Checkbox](https://react-ui-storyofams.vercel.app/?path=/story/components-checkbox--basic) | Checkbox with label and an optional statusmessage (optimized for usage with react-hook-form) |
| [DatePicker](https://react-ui-storyofams.vercel.app/?path=/story/components-DatePicker--basic) | Datepicker that utilizes 'react-flatpickr' |
| [Flex](https://react-ui-storyofams.vercel.app/?path=/story/components-flex--basic) | Mimics a `flexbox` implementation |
| [Grid](https://react-ui-storyofams.vercel.app/?path=/story/components-grid--basic) | Mimics a `grid` implementation using flexbox for compatibility reasons (with few limitations in comparison to the actual grid spec) |
| [Heading](https://react-ui-storyofams.vercel.app/?path=/story/components-heading--basic) | Semantically correct headings (see storybook for all default variants) |
| [Icon](https://react-ui-storyofams.vercel.app/?path=/story/components-icon--library) | Allows for svgs to be used as icon. We also provide some default icons you can choose to import and use with the icon component (see storybook for a complete overview). *Note: please consider using something like [SVGR](https://react-svgr.com/) when using your own icons |
| [Input](https://react-ui-storyofams.vercel.app/?path=/story/components-input--basic) | Input box with label and an optional statusmessage (optimized for usage with react-hook-form) |
| [Modal](https://react-ui-storyofams.vercel.app/?path=/story/components-modal--basic) | Modal build with `reach-dialog` which uses framer-motion to ensure smooth state transition animations |
| [Radio](https://react-ui-storyofams.vercel.app/?path=/story/components-radio--basic) | Radio group with labels and an optional statusmessage (optimized for usage with react-hook-form) |
| [Select](https://react-ui-storyofams.vercel.app/?path=/story/components-select--basic) | Select (created with `react-select`) input with label and an optional statusmessage (optimized for usage with react-hook-form) |
| [Spinner](https://react-ui-storyofams.vercel.app/?path=/story/components-spinner--basic) | Indicator to display a loading state |
| [Stack](https://react-ui-storyofams.vercel.app/?path=/story/components-stack--basic) | Automagically creates a (horizontal or vertical) stack of items with evenly spaced |
| [StatusMessage](https://react-ui-storyofams.vercel.app/?path=/story/components-statusmessage--basic) | Displays a message in a certain colour based on the type of status (default, warning, error, success) |
| [Tag](https://react-ui-storyofams.vercel.app/?path=/story/components-tag--basic) | Tag component used to create a list of toggleable tags with an optional statusmessage (optimized for usage with react-hook-form) |
| [Text](https://react-ui-storyofams.vercel.app/?path=/story/components-text--basic) | Semantically correct text blocks (see storybook for all default variants) |
| [TextArea](https://react-ui-storyofams.vercel.app/?path=/story/components-textarea--basic) | Text area with label and an optional statusmessage (optimized for usage with react-hook-form) |
| [Toggle](https://react-ui-storyofams.vercel.app/?path=/story/components-toggle--basic) | Toggle with label and an optional statusmessage (optimized for usage with react-hook-form) |
* Note: If a component does not satisfies your needs you can easily copy the contents of the components into your own project to extend / modify to fit your use-case (for other, less dramatic, customization options keep on reading 😉)
# Motivation
When the thought about creating (yet another) ui-library for react, the obvious questions were unavoidable:
* Why?
* Aren't there already many ui-libraries out there? What are we solving that others don't?
Yes there are already a bunch of ui-libraries but none specifically tailored to our setup which in the end resulted in a lot of repetitive work and/or tweaking or customizing the already existing libraries to the point where "building your own" becomes a viable option.
Our focus was to redo as less as possible and utilize as much as possible with battled tested libraries (preferably backed by an open source community). So we took some time to stitch everthing together to come up with a setup that enables us to get up and running quickly.
# Getting started
During development of this library certain choices have been made which enforce certain constraints on the developer 🔒
This done in order make the experience between projects as similar as possible.
Most of these constraints are considered 'best-practices' anyway so they shouldn't be surprising to deal with 🤓
> Using typescript is highly recommended
## Installation
Quickest way to get started is by running the following command:
```
yarn install @storyofams/react-ui
```
The library requires the following dependencies to be already installed:
```
- React (^17.0.0)
- Next.js (^10.0.0)
- styled-system (^5.1.0)
- @styled-system/css (^5.1.0)
- @styled-system/props (^5.1.0)
- styled-components (^5.2.0)
- @reach/alert (^0.13.0)
- @reach/checkbox (^0.13.0)
- @reach/dialog (^0.13.0)
- flatpickr (^4.6.9)
- react-flatpickr (^3.10.7)
- framer-motion (^3.10.0)
- react-id-generator (^3.0.0)
- react-select (^4.1.0)
```
## Setup
You can get started right away by importing whichever component you fancy into your project, however to get the most optimal developer experience keep on reading!
### Types
Add the following file to your project as `styled.d.ts`
```ts
import 'styled-components';
export interface Breakpoints extends Array<string> {
sm?: string;
md?: string;
lg?: string;
xl?: string;
}
declare module 'styled-components' {
type Theme = typeof import('./path/to/theme-default-export.ts').default;
export interface DefaultTheme extends Theme {
breakpoints: Breakpoints;
}
}
```
### Theme
Setting up requires adding a theme that should comply with the theme definition specified [here](https://styled-system.com/theme-specification) with a slight adjustment to the breakpoints. If you want to get started quickly just copy and paste the theme from the library (for the Breakpoints import see the above `Types` step).
### Icons
We export a list of commonly used icons to get started quickly which you can view [here](https://react-ui-storyofams.vercel.app/?path=/story/components-icon--library). Besides the icons we provide you can also supply your own svg to the Icon component as a React component. This recommended way of adding icons to load them into your application is by using [svgr](https://react-svgr.com/).
## Out of the box
Have a look at [the latest storybook deployment](https://react-ui-git-dev.storyofams.vercel.app/) to view all the components. Most likely you'll find what you need there and won't even have to look further.
## Extended variants
This library is made to get up and running fast which means we're providing variants we think that are useful that work for most use-cases. There will however always be projects that require `new` variants or slight adjustments on the already existing variants. To allow for this we're exporting a function called `styled`. This function is a wrapper on top of styled-components that pretty much works like [the styled function created by stitches](https://stitches.dev/docs/styling#base-styles).
**example:**
```ts
import { Button, styled } from '@storyofams/react-ui';
// Button has the following variants by default:
// - variant (primary, secondary, link, underline)
// - buttonSize (small, medium, large)
const ExtendedButton = styled(Button, {
variants: {
newVariant: {
primary: {
fontSize: 21,
'&:hover': {
backgroundColor: 'primary100',
},
},
},
buttonSize: {
'medium-screen-xl': {
fontSize: 2.2,
lineHeight: 'medium',
},
},
variant: {
icon: {
fontSize: 14,
borderRadius: 9999,
},
},
},
});
export const Extended = () => (
<>
<ExtendedButton variant="primary">button</ExtendedButton>
<ExtendedButton variant="icon" newVariant="primary">
button
</ExtendedButton>
<ExtendedButton
variant="icon"
buttonSize={['large', 'medium', 'medium-screen-xl']}
>
button
</ExtendedButton>
</>
);
```
### Css
Thanks to styled-system we get access to a `css` function. This css function can be used when you don't quite want to wrap a whole new styled-component, but you do need some specific css selectors to make it look pretty 🥰
To utilize the full potential of typescript we've re-exported the css function for you but added some autocomplete for values that live in your theme.
**comparison:**
```ts
import { css } from '@styled-system/css'
<Component
css={css({
backgroundColor: 'red' // autocompleted
backgroundColor: 'primary500' // not-autocompleted
})}
/>
```
VS
```ts
import { css } from '@storyofams/react-ui'
<Component
css={css({
backgroundColor: 'red' // autocompleted
backgroundColor: 'primary500' // autocompleted
})}
/>
```
### Adding custom props
For those components that just require extra customization or that really can't do without those few extra lines of css you can extend `systemprops`.
**example:**
```ts
import styled from 'styled-components';
import { Box, SystemProps } from '@storyofams/react-ui';
type CustomBoxProps = SystemProps & {
/** add any CustomBoxProps here */
customProp: string;
}
const CustomBox = styled(Box)<CustomBoxProps>`
// very specific styling that cannot be applied through either;
// * props
// * cssProp
`;
export const CustomComponent = (({ customProp, ...rest}): CustomBoxProps) => {
return (
<CustomBox {...rest}>
{/** ... */}
</CustomBox>
)
};
```
## Gotchas
Following are some things to take note of when using the library.
> I'm not using next.js, why do I need to install next.js?
Every project is different, we've found that next.js offers us a rich environment to get up and running fast for small to huge applications. Having that said, using react-ui is not completely depended on Next.js, with the only exception being the button component. This component can act as a link between content for your application and uses the next link since that's what we use most. We are looking into the possibilities to allow to provide a custom Link component to the button.
> I'm seeing a lot of properties on the dom but no actual styling is applied?
>
This is a know issue when using a component that uses a forwardingRef. Our current setup requires the `as` prop to enable autocomplete on certain HTML properties, since that components accepts an `as` property but is also forwarding a ref to another styled-component (which again accepts `as`) [you'll need to forward the `as`](https://styled-components.com/docs/api#forwardedas-prop). We're looking into the misconfiguration that is happening between those properties and why it's causing the properties to be passed to the dom rather than being used for styling.
> Some things do not have color am I going colourblind?
Most likely a theme variable we're using isn't covered in your theme. Don't worry you can style those all individually as component props. If you do find a color that's playing nice please let us know by filing an [issue](https://github.com/storyofams/react-ui/issues/new/choose)
> Props are not autocompleting with values from my theme
Make sure to go through the setup section of this readme. If the problem persists check if your implementation differs from the one in the `/example` folder. If all of the above fails let us know by filing an [issue](https://github.com/storyofams/react-ui/issues/new/choose)
# Acknowledgements
When creating this library we couldn't have done it without the following pioneers.
## styled-components
This library has really been on the forefront of developing react applications that are easily styled since the early days. It has served us very well over the course of the years and it will be hard to part ways if there ever comes a time where on of the other solutions in this space takes over.
You're probably already familiar with [styled-component](https://styled-components.com/) but be sure to give them some love 💜
## styled-system
This library, but more specifically [<NAME>](https://github.com/jxnblk) has really shaped up how we look to design systems. The foundation he has created with [styled-system](https://styled-system.com/) is really the dream of every developer.
Not sure what happened but the repo's have stayed unmaintained / unchanged for a while now. So we are using styled-system and the complimentary packages props and css to create the best DX we could come up with.
Huge shout out to this library and it's author for paving the way that enabled us to do this 💯
## system-props
[This library](https://github.com/system-props/system-props) is a more recent addition to the stack, but caught our eye because the shared philosophy that builds on styled-system and even includes some extensive pseudo elements as props (based on the chakra-ui implementation).
## reach-ui
Another library that has been there for a while is [reach-ui](https://reach.tech/). This library gives you the building blocks to build, the hard to get right, react components with a great attention to accessibility 🕵️♂️
This has been our go to when it comes to implementing those impossible components, with great success and most importantly ease of use.
## Modulz / Radix / Stitches
If you are not aware of these guys already I highly recommend checking out both [radix](https://github.com/radix-ui?type=source) and [modulz](https://github.com/modulz?type=source). They have been a great source of inspiration for some aspects of this UI-library.
We feel like they are the breath of fresh air this section of industry is really urging for. Stitches is highly innovative taking modern css capabilities to the css-in-js that we've all gotten to love. Radix is just a work of love, a product of hard work and dedication, to make the web more accessible to everyone 🥰
Having that said we also feel like it is still too early to convert our entire codebase. We are however keeping a close eye on what they are up to and will most likely jump on the wagon as soon as we feel it's matured enough to be steadily used in production grade font-end applications.
<file_sep>import * as CSS from 'csstype';
import {
AllSystemProps,
createSystem,
PseudoProps,
SystemProp,
background,
typography,
ColorProps,
position,
flexbox,
shadow,
border,
layout,
color,
space,
grid,
} from 'system-props';
const extraProps = {
cursor: true,
transform: true,
whiteSpace: true,
transition: true,
textOverflow: true,
pointerEvents: true,
textTransform: true,
textDecoration: true,
} as const;
type BaseProps = AllSystemProps<'noprefix'> &
{
[k in keyof typeof extraProps]?: SystemProp<CSS.Properties[k]>;
};
type Pseudo = PseudoProps<BaseProps>;
export interface SystemProps extends BaseProps, Pseudo {
css?: any;
color?: string & ColorProps['color'];
}
export const shouldForwardExtraProp = (prop: string) => !extraProps[prop];
const _system = createSystem({
strict: false,
tokenPrefix: 'noprefix',
});
export const system = _system({
...color,
...border,
...background,
...flexbox,
...grid,
...shadow,
...position,
...layout,
...space,
...typography,
...extraProps,
});
<file_sep>import { Breakpoints } from '~types/styled';
import space from './space';
const theme = {
colors: {
primary50: '#F0F9FF',
primary100: '#E0F2FE',
primary200: '#BAE6FD',
primary300: '#7DD3FC',
primary400: '#38BDF8',
primary500: '#0EA5E9',
primary600: '#0284C7',
primary700: '#0369A1',
primary800: '#075985',
primary900: '#083853',
secondary50: '#F5F3FF',
secondary100: '#EDE9FE',
secondary200: '#DDD6FE',
secondary300: '#C4B5FD',
secondary400: '#A78BFA',
secondary500: '#8B5CF6',
secondary600: '#7C3AED',
secondary700: '#6D28D9',
secondary800: '#541EAA',
secondary900: '#3C137B',
white: '#ffffff',
grey50: '#FAFAFA',
grey100: '#F4F4F5',
grey200: '#E4E4E7',
grey300: '#D4D4D8',
grey400: '#A1A1AA',
grey500: '#71717A',
grey600: '#52525B',
grey700: '#3F3F46',
grey800: '#27272A',
grey900: '#18181B',
warning50: '#FEFCE8',
warning100: '#FEF08A',
warning300: '#FACC15',
warning600: '#CA8A04',
warning800: '#713F12',
success50: '#F0FDF4',
success100: '#BBF7D0',
success300: '#4ADE80',
success600: '#16A34A',
success800: '#14532D',
error50: '#FEF2F2',
error100: '#FEE2E2',
error300: '#F87171',
error600: '#DC2626',
error800: '#7F1D1D',
transparent: 'rgba(255, 255, 255, 0);',
},
fontWeights: {
regular: 400,
medium: 500,
semiBold: 600,
bold: 700,
},
fonts: {
heading: `Domaine Disp`,
body: `Inter`,
mono: `SFMono-Regular, Menlo, Monaco,C onsolas, "Liberation Mono", "Courier New", monospace`,
},
fontSizes: {
1.25: space['1.25'],
1.5: space['1.5'],
1.75: space['1.75'],
2: space['2'],
2.25: space['2.25'],
2.5: space['2.5'],
3: space['3'],
4: space['4'],
5: space['5'],
6: space['6'],
7: space['7'],
8: space['8'],
10: space['9'],
20: space['20'],
root: space['1.75'],
heading: space['4'],
},
lineHeights: {
normal: 1,
heading: 1.1,
medium: 1.25,
high: 1.6,
},
space: {
...space,
mobileGutter: space['2'],
},
sizes: {
maxWidth: 1140,
},
breakpoints: ['768px', '1024px', '1280px', '1440px'] as Breakpoints,
zIndices: {
hide: -1,
base: 0,
docked: 10,
dropdown: 1000,
sticky: 1100,
banner: 1200,
overlay: 1300,
modal: 1400,
popover: 1500,
skipLink: 1600,
toast: 1700,
tooltip: 1800,
},
radii: {
none: '0',
xs: '4px',
sm: '6px',
md: '8px',
lg: '16px',
full: '9999px',
},
borders: {
none: 0,
'1px': '1px solid',
'2px': '2px solid',
'4px': '4px solid',
},
shadows: {
sm: '0px 2px 0px rgba(0, 0, 0, 0.1), 0px 5px 10px rgba(0, 0, 0, 0.05)',
md: '0px 2px 0px rgba(0, 0, 0, 0.1), 0px 5px 10px rgba(0, 0, 0, 0.05)',
lg: '0px 2px 4px rgba(0, 0, 0, 0.1), 0px 10px 20px rgba(0, 0, 0, 0.1)',
none: 'none',
},
};
theme.breakpoints.sm = theme.breakpoints[0];
theme.breakpoints.md = theme.breakpoints[1];
theme.breakpoints.lg = theme.breakpoints[2];
theme.breakpoints.xl = theme.breakpoints[3];
export default theme;
<file_sep>export const modifyResponsiveValue = (value, cb) => {
if (typeof value === 'string' || typeof value === 'number') {
return cb(value);
} else if (Array.isArray(value)) {
return value.map(cb);
} else {
const newObj = {};
Object.keys(value).forEach((k) => (newObj[k] = cb(value[k])));
return newObj;
}
};
<file_sep>import {INITIAL_VIEWPORTS} from '@storybook/addon-viewport'
import theme from '../src/styles/theme'
const viewportByBreakpoint = () => {
const viewPorts = {}
theme.breakpoints.forEach((breakpoint, key) =>
Object.assign(viewPorts, {
[key]: {
name: `Breakpoint: ${breakpoint}`,
styles: {
width: breakpoint,
height: '963px',
},
},
}),
)
return viewPorts
}
const customViewPorts = {
...viewportByBreakpoint(),
}
export const viewPorts = {
...customViewPorts,
...INITIAL_VIEWPORTS,
}
<file_sep>import '@testing-library/jest-dom';
import 'jest-axe/extend-expect';
jest.mock('src/components/common/Icon/__mocks__/req');
<file_sep>const siteTitle = 'Boilerplate';
const defaultSeo = {
openGraph: {
type: 'website',
locale: 'en_IE',
url: 'https://www.Boilerplate.com/',
site_name: siteTitle,
},
twitter: {
handle: '@Boilerplate',
cardType: 'summary_large_image',
},
titleTemplate: `%s | ${siteTitle}`,
};
if (process.env.NODE_ENV === 'development') {
defaultSeo.titleTemplate = `%s | dev-${siteTitle}`;
}
export default defaultSeo;
<file_sep>import 'styled-components';
export interface Breakpoints extends Array<string> {
sm?: string;
md?: string;
lg?: string;
xl?: string;
}
declare module 'styled-components' {
type Theme = typeof import('./theme').default;
export interface DefaultTheme extends Theme {
breakpoints: Breakpoints;
}
}
|
887705f26598e1d1b112a5e770787e5d8a594240
|
[
"Markdown",
"TypeScript"
] | 20
|
TypeScript
|
tarekalmanabri/react-ui
|
d1732c4e2bbfc977d6af3e94ce96f90d9919d8c0
|
42e073a0b9476d3d2c7ac61d819a70118fbc512a
|
refs/heads/master
|
<file_sep>liauth() {
command -v curl >/dev/null 2>/dev/null
if [ $? != 0 ]; then echo "ERROR: curl command required"; fi
if [ "$2" != "Local" -a "$2" != "ActiveDirectory" -o -z "$4" ]; then
echo "USAGE: liauth <FQDN> <Local|ActiveDirectory> <USERNAME> <PASSWORD>"
else
LISESSIONID=$(curl -ski -X POST -H "content-type: application/json" \
-d '{ "provider": "'$2'", "username": "'$3'", "password": "'$4'" }' \
https://$1:9543/api/v1/sessions)
if [ ! -z "$(echo $LISESSIONID | grep -i sessionid)" ]; then
LISESSIONID2=$(echo $LISESSIONID | awk '{split($0,a,"\""); print a[8];}')
fi
if [ ! -z "$LISESSIONID2" -a "$LISESSIONID2" != "FIELD_ERROR" ]; then
export LISESSIONID=
export LISESSIONID=$LISESSIONID2
echo SUCCESS!
else echo "$LISESSIONID"; fi
fi
}
liapiusage() {
echo 'USAGE: liget <FQDN> <GET|POST|PUT> <METHOD> [--pretty | <JSON> --pretty]
GET Methods
===========
ad/config
adgroups|adgroups/<domain>/<name>|adgroups/<domain>/<name>/[capabilities|groups|datasets]|
agent|agent/groups|
appliance/support-bundles/<id>?timeout=<timeout>|
archiving/config|
cluster/nodes|cluster/nodes/:<nodetoken>|
datasets|datasets/<dataSetsID>|
forwarding|
health/resources/:<clusternodeid>|health/activequeries|health/statistics|
groups|groups/<groupId>|groups/<groupId>/[users|adgroups|capabilities|datasets]|
ilb|ilb/status|
licenses|
notifications|
time|time/config|
upgrades/:version|upgrades/:version/nodes/:node|
users|users/<userId>|users/<userId>/[capabilities|groups|datasets]|
version|
vrops|vrops/:exampleHostname|
vsphere|vsphere/:hostname|vsphere/:vspherehostname/hosts|vsphere/:hostname/hosts/esxihost>
POST Methods
============
appliance/vm-support-bundles
{"target": "SINGLE", "manifests": {"Core:Logs"}}
deployment/approve
{"workerAddress": "10.0.0.124", "workerPort": 16520, "workerToken": "<PASSWORD>", "approved": true}
deployment/join
{"masterFQDN": "li.example.com"}
deployment/new
{"user": {"userName": "admin", "password": "<PASSWORD>!", "email": "<EMAIL>"}}
events/ingest/<agentId>
{"events": [{"text": "Hello world.", "timestamp": 123456789, "fields": [{"name": "field", "content": "value", "startPosition": 1, "length": 12, },...] },...] }
forwarding (create)
{"id": "test1", "host": "192.168.1.1", "port": 514, "protocol": "<syslog|cfapi>", "transportProtocol": "<tcp|udp>", "sslEnabled": <true|false>, "workerCount": <1-4>, "diskCacheSize": <200-2000>, "tags": {key: value, ...}, "filter": "(((not (text=~\"*1234\")) and ..." }
rollback
upgrades
{"pakUrl": "http://example.com/sb/api/7580600/deliverable/?file=publish/VMware-vRealize-Log-Insight-3.7.0-7580600.UNSTABLE.TP.pak"}
PUT Methods
===========
forwarding (update)
{"id": "test1", "host": "192.168.1.1", "port": 514, "protocol": "<syslog|cfapi>", "transportProtocol": "<tcp|udp>", "sslEnabled": <true|false>, "workerCount": <1-4>, "diskCacheSize": <200-2000>, "tags": {key: value, ...}, "filter": "(((not (text=~\"*1234\")) and ..." }
upgrades/<version>/eula
{"accepted": "true"}
'
}
liapi() {
# Parameters
if [ ! -z "$4" -a "$4" != "--pretty" ]; then DATA="-d $4"; fi
# Checks
command -v python >/dev/null 2>/dev/null
if [ ! -z "$3" -a $? != 0 ]; then echo "ERROR: curl command required"
elif [ -z "$3" ]; then liapiusage
# Some API requests require authentication, otherwise do not
elif [[ -z "$LISESSIONID" && \
"$3" != deployment/join && \
"$3" != deployment/new && \
"$3" != events/ingest/* && \
"$3" != version ]]; then echo "ERROR: Must authenticate first with liauth"
# API -- must swallow errors given DATA variable requiring double quotations
else
echo curl -ski -X $2 -H 'Content-Type: application/json' -H 'Authorization: Bearer $(echo -n $LISESSIONID)' "$DATA" https://$1:9543/api/v1/$3
RESPONSE=$(curl -ski -X $2 -H 'Content-Type: application/json' -H 'Authorization: Bearer $(echo -n $LISESSIONID)' "$DATA" https://$1:9543/api/v1/$3)
fi
if [ "$4" == "--pretty" -o "$5" == "--pretty" ]; then
echo "$RESPONSE" | sed \$d
echo "$RESPONSE" | tail -n 1 | python -m json.tool
else echo "$RESPONSE"; fi
}
ncevent() {
if [ -z "$3" ]; then echo "USAGE: ncevent <FQDN> <PORT> '<EVENT>'"
else echo "$3" | nc -v -w 0 $1 $2; fi
}
|
0e8f72973b031c3ab822ba3c67ec4089b16d0a32
|
[
"Shell"
] | 1
|
Shell
|
vmw-loginsight/api-clients
|
fe400a852d476b10d1ee733c1b04ddc7c340c08d
|
304ebf929fd5aeaf7c90b5394c4aefa315d663c6
|
refs/heads/master
|
<repo_name>farizputradandi/progjar<file_sep>/progjar4/chat.py
import sys
import os
import json
import uuid
from queue import Queue
class Chat:
def __init__(self):
self.sessions={}
self.users = {}
self.users['messi']={ 'nama': '<NAME>', 'negara': 'Argentina', 'password': '<PASSWORD>', 'incoming' : {}, 'outgoing': {}}
self.users['henderson']={ 'nama': '<NAME>', 'negara': 'Inggris', 'password': '<PASSWORD>', 'incoming': {}, 'outgoing': {}}
self.users['lineker']={ 'nama': '<NAME>', 'negara': 'Inggris', 'password': '<PASSWORD>','incoming': {}, 'outgoing':{}}
def proses(self,data):
j=data.split(" ")
try:
command=j[0]
if (command=='auth'):
username=j[1]
password=j[2]
return self.autentikasi_user(username,password)
else:
return {'status': 'ERROR', 'message': 'Protocol Tidak Benar'}
except IndexError:
return {'status': 'ERROR', 'message': 'Protocol Tidak Benar'}
def autentikasi_user(self,username,password):
if (username not in self.users):
return { 'status': 'ERROR', 'message': 'User Tidak Ada' }
if (self.users[username]['password']!= password):
return { 'status': 'ERROR', 'message': 'Password Salah' }
tokenid = str(uuid.uuid4())
self.sessions[tokenid]=self.users[username]
return { 'status': 'OK', 'tokenid': tokenid }
def get_user(self,username):
if (username not in self.users):
return False
return self.users[username]
def send_message(self,sessionid,username_from,username_dest,message):
if (sessionid not in self.sessions):
return {'status': 'ERROR', 'message': 'Session Tidak Ditemukan'}
s_fr = self.get_user(username_from)
s_to = self.get_user(username_dest)
if (s_fr==False or s_to==False):
return {'status': 'ERROR', 'message': 'User Tidak Ditemukan'}
message = { 'msg_from': s_fr['nama'], 'msg_to': s_to['nama'], 'msg': message }
outqueue_sender = s_fr['outgoing']
inqueue_receiver = s_to['incoming']
try:
outqueue_sender[username_from].put(message)
except KeyError:
outqueue_sender[username_from]=Queue()
outqueue_sender[username_from].put(message)
try:
inqueue_receiver[username_from].put(message)
except KeyError:
inqueue_receiver[username_from]=Queue()
inqueue_receiver[username_from].put(message)
return {'status': 'OK', 'message': 'Message Sent'}
def get_inbox(self,username):
s_fr = self.get_user(username)
incoming = s_fr['incoming']
msgs={}
for users in incoming:
msgs[users]=[]
while not incoming[users].empty():
msgs[users].append(s_fr['incoming'][users].get_nowait())
return {'status': 'OK', 'messages': msgs}
if __name__=="__main__":
j = Chat()
print j.send_message('xmessi','0','henderson','hello son')
print j.send_message('henderson','0','messi','hello si')
print j.send_message('lineker','0','messi','hello si dari lineker')
print j.get_inbox('messi')
|
3bf1770319ef121095734b36e5296745119ad955
|
[
"Python"
] | 1
|
Python
|
farizputradandi/progjar
|
26cffaf8ce47c71719d584aba1d30f70cf036437
|
18a5dd7b1fc73eac61a895e33d02f06d65e8c391
|
refs/heads/master
|
<repo_name>kjk93/KyleKravetteSite<file_sep>/app/controllers/main_page_controller.rb
class MainPageController < ApplicationController
def home
end
def temp
end
end
|
b32140883645e2d93f3a933ddcf5a177a91393ab
|
[
"Ruby"
] | 1
|
Ruby
|
kjk93/KyleKravetteSite
|
f981d3ced8ac7d4eb3b765f03f2400c14990b804
|
74c293ce5456e9701274a7c8a55a7209c5ef6c2d
|
refs/heads/master
|
<file_sep>import boto3
import os
ec2_resource = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
class Create_SG:
def __init__(self, sg_type, sgname):
self.sg_type = sg_type
self.sgname = sgname
def ec2_create_sg(self):
try:
if self.sg_type == 'ssh':
response = ec2_client.create_security_group(GroupName=self.sgname, Description='SG for ssh')
ec2_client.authorize_security_group_ingress(
GroupId=response['GroupId'],
IpPermissions=[
{'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
]
)
print("Security GroupID {} was crated".format(response['GroupdId']))
return 1
elif self.sg_type == 'web':
response = ec2_client.create_security_group(GroupName=self.sgname, Description='SG for web')
ec2_client.authorize_security_group_ingress(
GroupId=response['GroupId'],
IpPermissions=[
{'IpProtocol': 'tcp',
'FromPort': 443,
'ToPort': 443,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
{'IpProtocol': 'tcp',
'FromPort': 80,
'ToPort': 80,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
{'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
]
)
print("Security GroupID {} was crated".format(response['GroupdId']))
return 1
else:
print("Security Group creation process had failed, unknown type!")
return 0
except:
print("Security Group creation process had failed, very likely due to duplicate SG Naming!")
return 0
class Create_Key:
def __init__(self, key_name):
self.key_name = key_name
def ec2_create_key(self):
my_path = os.path.expanduser("~/" + self.key_name + "_ssh.pem")
try:
if os.path.exists(my_path) and os.path.getsize(my_path) > 0:
print("Warning!!! Key wasn't created because " + my_path + " already exists")
return 0
else:
keypair = ec2_client.create_key_pair(KeyName=self.key_name)
print("Key is being exported to " + my_path)
with open(my_path, "w+") as line:
print(keypair['KeyMaterial'], file=line)
print(keypair['KeyMaterial'])
line .close()
return 1
except:
return 0
class Create_EC2(Create_SG, Create_Key):
def __init__(self, sg_type, sg_name, key_name):
self.sg_name = sg_name
self.key_name = key_name
Create_SG.__init__(self, sg_type, sg_name)
Create_Key.__init__(self, key_name)
def create_ec2_instance(self):
instance = ec2_resource.create_instances(ImageId='ami-bf4193c7', MinCount=1, MaxCount=1, SecurityGroups=[self.sg_name], KeyName=self.key_name, InstanceType='t2.micro')
print(instance)
web1 = Create_EC2("web", "web1_sg", "web1_key")
web1.ec2_create_sg()
web1.ec2_create_key()
web1.create_ec2_instance()
<file_sep># aws_create_ec2_security-group_key
this cript will create ec2 instance ,security group and key
|
2c206b6b28c5640efd70642acada51716f3865d7
|
[
"Markdown",
"Python"
] | 2
|
Python
|
aia89/aws_create_ec2_security-group_key
|
a2b708ae1393e214f2575001534fe6af0bda84f4
|
15e284e08e8e5b38d576032d8363fab01285fadb
|
refs/heads/master
|
<repo_name>wujialing1988/ssh<file_sep>/src/main/webapp/process/FlowDesigner.js
FlowDesigner = {};
FlowDesigner.addInitCallback = function(bname,callback){
if(callback != null && callback != undefined){
FABridge.addInitializationCallback(bname, callback);
}
};
/**
* 添加模板
* bname bridgeName 的值
*/
FlowDesigner.add = function(bname) {
try{
FABridge[bname].root().add();
}catch(e){}
};
/**
* 修改模板
* bname bridgeName 的值
* key 流程模板编码
*/
FlowDesigner.edit = function(bname,key) {
try{
FABridge[bname].root().edit(key);
}catch(e){}
};
/**
* 修改实例
* bname bridgeName 的值
* key 流程模板编码
*/
FlowDesigner.editInst = function(bname,isntId) {
try{
FABridge[bname].root().editInst(isntId);
}catch(e){}
};
/**
* 查询模板
* bname bridgeName 的值
* key 流程模板编码
*/
FlowDesigner.see = function(bname,key) {
try{
FABridge[bname].root().see(key);
}catch(e){}
};
/**
* 监控实例
* bname bridgeName 的值
* instId 流程实例id
*/
FlowDesigner.monitor = function(bname,instId) {
try{
FABridge[bname].root().monitor(instId);
}catch(e){}
};
<file_sep>/src/main/webapp/scripts/login/isLogin.js
/**
* 实现记住密码和自动登录
* 哥特死亡工业
* 2014年2月12日
*/
//注销系统后不能再自动登录
function isLogOut(){
var date = new Date();
date.setTime(date.getTime() + (0.1 * 60 * 1000));
$.cookie('isLogOut', 'true', { expires: date });
//$.cookie("isLogOut", "true"); // 存储一个带7天期限的 cookie
}
//点击登录后,即可实现自动登录
function log1(){
$.cookie("isLogOut", "false", { expires: 7 }); // 存储一个带7天期限的 cookie
}
<file_sep>/src/main/webapp/scripts/role/RoleGrid.js
/**
* 角色管理的列表功能,包含功能有 列表、添加、修改和删除功能。
* @date 20150616
* @author hedaojun
*/
/**
* 定义角色Model
*/
Ext.define("sshframe.role.roleModel", {
extend : "Ext.data.Model",
fields : [{
name : "roleId",
type : "int"
}, {
name : "roleName"
}, {
name : "roleCode"
}, {
name : "description"
} ]
});
/**
* 定义Store
*/
sshframe.role.RoleStore = Ext.create('Ext.data.Store', {
model : 'sshframe.role.roleModel',
proxy : {
type : "format",
url : basePath + "/role/getRoleList.action"
}
});
/**
* 定义Grid
*/
sshframe.role.RoleGrid = Ext.create("Ext.grid.Panel", {
title : '角色管理',
region : "center",
bbar : Ext.create("Ext.PagingToolbar", {
store : sshframe.role.RoleStore
}),
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : sshframe.role.RoleStore,
columns : [ {
xtype : "rownumberer",
text : '序号',
width : 60,
align : "center"
}, {
header : "roleId",
width : 70,
dataIndex : "id",
hidden : true
}, {
header : "角色名称",
width : 200,
dataIndex : "roleName"
}, {
header : "角色编码",
width : 200,
dataIndex : "roleCode"
}, {
header : "描述",
width : 200,
dataIndex : "description"
}, {
header : "资源",
xtype : "actioncolumn",
align : 'center',
renderer : function() {},
items : [ {
iconCls : "icon-view",
tooltip : "分配资源",
handler : function(grid, rindex, cindex) {
var record = grid.getStore().getAt(rindex);
//toAddResource(record.get('roleId'));
toAddResource(record.get('id'));
}
} ]
} ],
tbar : [ '角色名称', {
xtype : 'textfield',
stripCharsRe : /^\s+|\s+$/g, // 禁止输入空格
id : 'inputRoleName'
}, {
text : "查询",
iconCls : "search-button",
handler : function(button) {
sshframe.role.RoleStore.getProxy().setExtraParam("roleName", button.prev().getValue());
sshframe.role.RoleStore.loadPage(1);
}
}, '->', {
xtype : 'button',
text : '添加',
iconCls : 'add-button',
handler : function() {
sshframe.role.addRole();
}
}, {
xtype : 'button',
text : '修改',
disabledExpr : "$selectedRows != 1 || $roleCode=='admin'",// $selected 表示选中的记录数不等于1
disabled : true,
iconCls : 'edit-button',
handler : function() {
sshframe.role.updateRole();
}
}, {
xtype : 'button',
text : '删除',
disabled : true,
disabledExpr : "$selectedRows == 0 || $roleCode=='admin'",
iconCls : 'delete-button',
handler : function() {
sshframe.role.deleteRole();
}
} ]
});
/**
* 调用后台修改角色
*/
sshframe.role.updateRole = function() {
sshframe.role.RoleWin.setTitle('修改');
var row = sshframe.role.RoleGrid.getSelectionModel().getSelection();
var roleId = row[0].data.id;
var basicForm = sshframe.role.RoleWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/role/updateRole.action';
basicForm.findField('roleId').setValue(roleId);
basicForm.load({
url : basePath + '/role/getRoleById.action',
params : {
id : roleId
}
});
sshframe.role.RoleWin.show();
};
/**
* 调用后台添加角色
*/
sshframe.role.addRole = function() {
sshframe.role.RoleWin.setTitle('添加');
var basicForm = sshframe.role.RoleWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/role/addRole.action';
// 设置默认值
var roleTypeField = basicForm.findField('roleType');
var typeTreeSelected = Ext.getCmp('typeTree').getSelectionModel().getSelection();
if (typeTreeSelected) {
roleTypeField.setValue(typeTreeSelected[0].raw.code);
}
else {
roleTypeField.setValue(roleTypeField.getStore().getAt(0));
}
sshframe.role.RoleWin.show();
};
/**
* 调用后台删除角色
*/
sshframe.role.deleteRole = function() {
var rows = sshframe.role.RoleGrid.getSelectionModel().getSelection();
var ids = "";
for (var i = 0; i < rows.length; i++) {
ids += (rows[i].data.id + ",");
}
ids = ids.substring(0, ids.length - 1);
Ext.Ajax.request({
url : basePath +'/role/isCanDelete.action',
params : {ids: ids},
success : function(res, options) {
var data = Ext.decode(res.responseText);
if(data.success){
Ext.Msg.confirm(SystemConstant.alertTitle, "确认删除这" + rows.length + "条角色信息吗(角色的数据范围等将被一并删除)?", function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : basePath + '/role/deleteRole.action',
params : {
ids : ids
},
success : function(res, options) {
var data = Ext.decode(res.responseText);
if (data.success) {
Ext.Msg.showTip(data.msg);
sshframe.role.RoleStore.loadPage(1);
} else {
Ext.Msg.showError(data.msg);
}
},
failure : sshframe.FailureProcess.Ajax
});
}
});
}else{
sshframe.role.RoleStore.loadPage(1);
Ext.MessageBox.show({
title: SystemConstant.alertTitle,
msg: data.msg,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.INFO
});
return false;
}
}
});
};<file_sep>/src/main/resources/createObjects.sql
create sequence HIBERNATE_SEQUENCE
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
cache 100
noorder;
create sequence SEQ_ACTIVITI_CATEGORY
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_ACTIVITI_FORM
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_ACTIVITI_TASK_ROLE
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_DICTIONARY
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_GROUP
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_GROUP_MEMBER
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_LOG
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_ORGANIZATION
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_ORG_USER
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_RESOURCE
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_ROLE
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_ROLE_MEMBER_SCOPE
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_ROLE_RESOURCE
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence SEQ_SCOPE_MEMBER
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence SEQ_USER
increment by 1
start with 1
nomaxvalue
nominvalue
nocycle
noorder;
create sequence S_ACTIVITI_DEFINE_TEMPLATE
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence S_ACTIVITI_DELEGATE
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence S_ACTIVITI_PROCESS_APPROVAL
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
create sequence S_ACTIVITI_PROCESS_INST
increment by 1
start with 1
maxvalue 9999999999999999999999999999
nominvalue
nocycle
noorder;
/*==============================================================*/
/* Table: SYS_ACTIVITI_CATEGORY */
/*==============================================================*/
create table SYS_ACTIVITI_CATEGORY
(
PK_ACTIVITI_CATEGORY_ID NUMBER(10) not null,
CATEGORY_CODE VARCHAR2(50) not null,
DESCRIPTION VARCHAR2(1000),
ISDELETE NUMBER(10),
LEAF NUMBER(10),
NAME VARCHAR2(100) not null,
PARENTID NUMBER(10),
SORT NUMBER(10),
constraint SYS_C0053661 primary key (PK_ACTIVITI_CATEGORY_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_DEFINE_TEMPLATE */
/*==============================================================*/
create table SYS_ACTIVITI_DEFINE_TEMPLATE
(
PK_ACTIVITI_DEFINE_TEMPLATE_ID NUMBER(10) not null,
ISDELETE NUMBER(10),
NAME VARCHAR2(255) not null,
PROCESS_DEFINE_KEY VARCHAR2(255) not null,
REAL_NAME VARCHAR2(255),
URL VARCHAR2(255) not null,
FK_CATEGORY_ID NUMBER(10) not null,
constraint SYS_C0053667 primary key (PK_ACTIVITI_DEFINE_TEMPLATE_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_DELEGATE */
/*==============================================================*/
create table SYS_ACTIVITI_DELEGATE
(
PK_ACTIVITI_DELEGATE_ID NUMBER(10) not null,
DELEGATE_END_TIME DATE,
DELEGATE_START_TIME DATE,
DELEGATE_STATUS NUMBER(10),
ISDELETE NUMBER(10),
DELEGATE_ID NUMBER(10),
OWNER_ID NUMBER(10),
constraint SYS_C0053678 primary key (PK_ACTIVITI_DELEGATE_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_FORM */
/*==============================================================*/
create table SYS_ACTIVITI_FORM
(
PK_ACTIVITI_FORM_ID NUMBER(10) not null,
ADAPTATION_NODE VARCHAR2(500),
DESCRIPTION VARCHAR2(500),
FORM_NAME VARCHAR2(200),
FORM_URL VARCHAR2(200),
ISDELETE NUMBER(10),
constraint SYS_C0053680 primary key (PK_ACTIVITI_FORM_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_FORM_CATEGORY */
/*==============================================================*/
create table SYS_ACTIVITI_FORM_CATEGORY
(
PK_ACTIVITI_FORM_ID NUMBER(10) not null,
PK_CATEGORY_ID NUMBER(10) not null
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_PROCESS_APPROVAL */
/*==============================================================*/
create table SYS_ACTIVITI_PROCESS_APPROVAL
(
PK_ACTIVITI_PRO_APPROVAL_ID NUMBER(10) not null,
APPROVAL NUMBER(10),
ELECTRONIC_SIGNATURE BLOB,
ELECTRONIC_SOURCE NUMBER(10),
ELECTRONIC_URL VARCHAR2(300),
ISDELETE NUMBER(10),
OPINION VARCHAR2(2000),
PROCESS_INSTANCE_ID VARCHAR2(255),
TASKID VARCHAR2(255),
FK_USER_ID NUMBER(10),
constraint SYS_C0053671 primary key (PK_ACTIVITI_PRO_APPROVAL_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_PROCESS_INST */
/*==============================================================*/
create table SYS_ACTIVITI_PROCESS_INST
(
PK_ACTIVITI_PROCESS_INST_ID NUMBER(10) not null,
BUSINESS_ID VARCHAR2(1000),
BUSINESS_ORG VARCHAR2(300),
BUSINESS_TITLE VARCHAR2(1000),
ISDELETE NUMBER(10),
PROCESS_CODE VARCHAR2(255),
PROCESS_CREATE_DATE DATE,
PROCESS_DEFINEKEY VARCHAR2(255),
PROCESS_INSTANCE_ID VARCHAR2(255),
PROCESS_NAME VARCHAR2(255),
PROCESS_TYPE VARCHAR2(255),
FK_ACTIVITI_CATEGORY_ID NUMBER(10),
FK_PROCESS_CREATER NUMBER(10),
constraint SYS_C0053673 primary key (PK_ACTIVITI_PROCESS_INST_ID)
);
/*==============================================================*/
/* Table: SYS_ACTIVITI_ROLE */
/*==============================================================*/
create table SYS_ACTIVITI_ROLE
(
PK_ACTIVITI_TASK_ROLE_ID NUMBER(10) not null,
TASKID VARCHAR2(300) not null,
FK_ROLE_ID NUMBER(10),
constraint SYS_C0053676 primary key (PK_ACTIVITI_TASK_ROLE_ID)
);
/*==============================================================*/
/* Table: T_ATTACH */
/*==============================================================*/
create table T_ATTACH
(
ATTACH_ID NUMBER(10) not null,
ATTACH_NAME VARCHAR2(100) not null,
ATTACH_TYPE VARCHAR2(100),
ATTACH_URL VARCHAR2(200) not null,
DESCRIPTION VARCHAR2(1000),
DOWNLOAD_TIME NUMBER(10),
FILE_SIZE VARCHAR2(50),
REMARKS VARCHAR2(2000),
STATUS NUMBER(10) not null,
SUBMIT_DATE DATE not null,
ATTACH_GROUP_ID NUMBER(10) not null,
constraint SYS_C0045410 primary key (ATTACH_ID)
);
/*==============================================================*/
/* Table: T_ATTACH_GROUP */
/*==============================================================*/
create table T_ATTACH_GROUP
(
ATTACH_ID NUMBER(10) not null,
REMARKS VARCHAR2(2000),
STATUS NUMBER(10) not null,
SUBMIT_DATE DATE not null,
constraint SYS_C0045414 primary key (ATTACH_ID)
);
/*==============================================================*/
/* Table: T_DICTIONARY */
/*==============================================================*/
create table T_DICTIONARY
(
PK_ID NUMBER(10) not null,
DICT_CODE VARCHAR2(255),
DICT_UUID VARCHAR2(255),
DICTIONARY_NAME VARCHAR2(48),
DICTIONARY_VALUE VARCHAR2(480),
FK_DICT_TYPE_UUID VARCHAR2(255),
LEVEL_ORDER NUMBER(10),
STATUS VARCHAR2(1),
PARENT_ID NUMBER(10),
constraint SYS_C0053979 primary key (PK_ID)
);
/*==============================================================*/
/* Table: T_GROUP */
/*==============================================================*/
create table T_GROUP
(
ID NUMBER(10) not null,
CREATE_DATE DATE not null,
GROUP_NAME VARCHAR2(100) not null,
REMARK VARCHAR2(2000),
constraint SYS_C0053983 primary key (ID)
);
/*==============================================================*/
/* Table: T_GROUP_MEMBER */
/*==============================================================*/
create table T_GROUP_MEMBER
(
ID NUMBER(10) not null,
GROUP_ID NUMBER(10) not null,
ORG_ID NUMBER(10),
USER_ID NUMBER(10),
constraint SYS_C0053986 primary key (ID)
);
/*==============================================================*/
/* Table: T_LOG */
/*==============================================================*/
create table T_LOG
(
PK_LOG_ID NUMBER(19) not null,
IP_URL VARCHAR2(50),
FK_LOG_TYPE_UUID VARCHAR2(255),
OP_CONTENT VARCHAR2(4000),
OP_DATE DATE not null,
LOG_TYPE NUMBER(10),
USER_ID NUMBER(10),
constraint SYS_C0053989 primary key (PK_LOG_ID)
);
/*==============================================================*/
/* Table: T_ORGANIZATION */
/*==============================================================*/
create table T_ORGANIZATION
(
ORG_ID NUMBER(10) not null,
DIS_ORDER NUMBER(10),
ENABLE NUMBER(10) not null,
ISDELETEABLE NUMBER(10) not null,
ORG_CODE VARCHAR2(50),
ORG_FROM NUMBER(10),
ORG_NAME VARCHAR2(100) not null,
FK_ORGTYPE_UUID VARCHAR2(255),
STATUS NUMBER(10) not null,
FK_ORGTYPE NUMBER(10),
PARENT_ID NUMBER(10),
constraint SYS_C0053995 primary key (ORG_ID)
);
/*==============================================================*/
/* Table: T_ORG_USER */
/*==============================================================*/
create table T_ORG_USER
(
PK_ORG_USER_ID NUMBER(10) not null,
ISDELETE NUMBER(10) not null,
FK_ORG_ID NUMBER(10) not null,
FK_USER_ID NUMBER(10) not null,
constraint SYS_C0054000 primary key (PK_ORG_USER_ID)
);
/*==============================================================*/
/* Table: T_RESOURCE */
/*==============================================================*/
create table T_RESOURCE
(
RESOURCE_ID NUMBER(10) not null,
CODE VARCHAR2(100),
CREATE_DATE DATE not null,
DIS_ORDER NUMBER(10),
ISDELETEABLE NUMBER(10) not null,
REMARKS VARCHAR2(200),
RESOURCE_FROM NUMBER(10),
RESOURCE_NAME VARCHAR2(100) not null,
RESOURCE_TYPE_UUID VARCHAR2(255),
STATUS NUMBER(10) not null,
URLPATH VARCHAR2(200),
PARENT_ID NUMBER(10),
RESOURCE_TYPE NUMBER(10),
constraint SYS_C0054006 primary key (RESOURCE_ID)
);
/*==============================================================*/
/* Table: T_ROLE */
/*==============================================================*/
create table T_ROLE
(
ROLE_ID NUMBER(10) not null,
DESCRIPTION VARCHAR2(200),
ISDELETE NUMBER(10) not null,
ISDELETEABLE NUMBER(10) not null,
ROLE_CODE VARCHAR2(50),
ROLE_NAME VARCHAR2(50) not null,
FK_ROLE_TYPE_UUID VARCHAR2(255),
FK_ROLE_TYPE NUMBER(10),
constraint SYS_C0054011 primary key (ROLE_ID)
);
/*==============================================================*/
/* Table: T_ROLE_MEMBER */
/*==============================================================*/
create table T_ROLE_MEMBER
(
ID NUMBER(10) not null,
GROUP_ID NUMBER(10),
ROLE_ID NUMBER(10) not null,
USER_ID NUMBER(10),
constraint SYS_C0054014 primary key (ID)
);
/*==============================================================*/
/* Table: T_ROLE_RESOURCE */
/*==============================================================*/
create table T_ROLE_RESOURCE
(
ROLE_RESOURCE_ID NUMBER(10) not null,
RESOURCE_ID NUMBER(10) not null,
ROLE_ID NUMBER(10) not null,
constraint SYS_C0054018 primary key (ROLE_RESOURCE_ID)
);
/*==============================================================*/
/* Table: T_DATA_SCOPE */
/*==============================================================*/
create table T_DATA_SCOPE
(
ID NUMBER(10) not null,
GROUP_ID NUMBER(10),
ORG_ID NUMBER(10),
ROLE_MEMBER_ID NUMBER(10),
USER_ID NUMBER(10),
constraint SYS_C0054026 primary key (ID)
);
/*==============================================================*/
/* Table: T_TEMP_TEAM */
/*==============================================================*/
create table T_TEMP_TEAM
(
ID NUMBER not null,
NAME VARCHAR2(100),
CREATE_DATE DATE,
REMARKS VARCHAR2(1000),
constraint PK_TEMP_TEAM_ID primary key (ID)
);
/*==============================================================*/
/* Table: T_TEMP_TEAM_MENBER */
/*==============================================================*/
create table T_TEMP_TEAM_MENBER
(
ID NUMBER not null,
USER_ID NUMBER not null,
TEMP_TEAM_ID NUMBER,
constraint PK_RULE_ROUND_USER primary key (ID)
);
/*==============================================================*/
/* Table: T_USER */
/*==============================================================*/
create table T_USER
(
USER_ID NUMBER(10) not null,
BIRTHDAY VARCHAR2(50),
BIRTH_PLACE VARCHAR2(255),
CARD_CODE VARCHAR2(255),
DIS_ORDER NUMBER(10),
ELECTRONIC_SIGNATURE VARCHAR2(255),
EMAIL VARCHAR2(255),
ISENABLE NUMBER(10),
ERP_ID VARCHAR2(255),
GENDER VARCHAR2(3),
ID_CARD VARCHAR2(255),
ISDELETABLE NUMBER(10),
FK_JOB1_UUID VARCHAR2(255),
FK_JOB2_UUID VARCHAR2(255),
FK_JOBLEVEL_UUID VARCHAR2(255),
MOBILE_PHONE1 VARCHAR2(20),
MOBILE_PHONE2 VARCHAR2(20),
PASSWORD VARCHAR2(50),
PERSONAL_IMAGE VARCHAR2(255),
PHONE_NO VARCHAR2(20),
FK_POSTTITLE_UUID VARCHAR2(255),
FK_POST_UUID VARCHAR2(255),
REALNAME VARCHAR2(50),
SHORT_NO1 VARCHAR2(20),
SHORT_NO2 VARCHAR2(20),
STATUS NUMBER(10),
FK_TEAM_UUID VARCHAR2(255),
USER_ONLINE NUMBER(19),
FK_USERTYPE_UUID VARCHAR2(255),
USERNAME VARCHAR2(50),
FK_JOB1 NUMBER(10),
FK_JOB2 NUMBER(10),
FK_JOBLEVEL NUMBER(10),
FK_POST NUMBER(10),
FK_POSTTITLE NUMBER(10),
FK_TEAM NUMBER(10),
FK_TYPE NUMBER(10),
constraint SYS_C0054028 primary key (USER_ID)
);
/*===================注释======================*/
comment on column SYS_ACTIVITI_PROCESS_INST.BUSINESS_ORG is
'业务数据的归属组织ID';
comment on column SYS_ACTIVITI_PROCESS_INST.BUSINESS_ORG is
'业务数据的归属组织ID';
comment on table T_DICTIONARY is
'字典表';
comment on column T_DICTIONARY.PK_ID is
'字典表主键';
comment on column T_DICTIONARY.DICTIONARY_NAME is
'字典名称';
comment on column T_DICTIONARY.DICTIONARY_VALUE is
'字典值';
comment on column T_DICTIONARY.LEVEL_ORDER is
'等级或排序号';
comment on column T_DICTIONARY.STATUS is
'删除标志 0未删除 1 已删除';
comment on column T_DICTIONARY.FK_DICT_TYPE_UUID is
'字典类型随机数';
comment on column T_DICTIONARY.DICT_UUID is
'字典数据随机数';
comment on column T_DICTIONARY.DICT_CODE is
'字典编码';
comment on column T_DICTIONARY.PARENT_ID is
'字典类型ID';
comment on table T_GROUP is
'群组';
comment on column T_GROUP.GROUP_NAME is
'群组名称';
comment on column T_GROUP.CREATE_DATE is
'创建时间';
comment on column T_GROUP.REMARK is
'备注';
comment on table T_GROUP_MEMBER is
'群组成员';
comment on column T_GROUP_MEMBER.USER_ID is
'用户ID';
comment on column T_GROUP_MEMBER.ORG_ID is
'部门ID';
comment on column T_GROUP_MEMBER.GROUP_ID is
'群组ID';
comment on table T_LOG is
'日志表';
comment on column T_LOG.PK_LOG_ID is
'日志表主键';
comment on column T_LOG.USER_ID is
'操作人ID';
comment on column T_LOG.OP_DATE is
'操作时间';
comment on column T_LOG.OP_CONTENT is
'日志内容';
comment on column T_LOG.IP_URL is
'操作IP地址';
comment on column T_LOG.LOG_TYPE is
'日志类型 1系统日志,2,用户日志 3,系统错误日志';
comment on column T_LOG.FK_LOG_TYPE_UUID is
'日志类型字典数据UUID';
comment on table T_ORGANIZATION is
'组织表';
comment on column T_ORGANIZATION.ORG_CODE is
'为了给用户使用方便,这里增加组织代码,例如:生产管理部的代码:SCGL';
comment on column T_ORGANIZATION.FK_ORGTYPE is
'字典数据';
comment on column T_ORGANIZATION.DIS_ORDER is
'同级排序';
comment on column T_ORGANIZATION.ENABLE is
'0:可用;1:禁用';
comment on column T_ORGANIZATION.STATUS is
'0:未删除
1:删除 2架构删除';
comment on column T_ORGANIZATION.ORG_FROM is
'组织来源 0:架构自行添加 1:继承平台同步';
comment on column T_ORGANIZATION.FK_ORGTYPE_UUID is
'组织类型字典数据UUID';
comment on column T_ORGANIZATION.ISDELETEABLE is
'1不允许删除;0可以删除';
comment on table T_ORG_USER is
'用户-组织表';
comment on column T_ORG_USER.PK_ORG_USER_ID is
'主键';
comment on column T_ORG_USER.FK_ORG_ID is
'组织ID';
comment on column T_ORG_USER.FK_USER_ID is
'用户ID';
comment on column T_ORG_USER.ISDELETE is
'0:未删除 1:已删除';
comment on table T_RESOURCE is
'资源表';
comment on column T_RESOURCE.RESOURCE_ID is
'主键';
comment on column T_RESOURCE.RESOURCE_NAME is
'资源名称';
comment on column T_RESOURCE.CODE is
'资源编码';
comment on column T_RESOURCE.RESOURCE_TYPE is
'字典数据';
comment on column T_RESOURCE.URLPATH is
'该字段可以存储菜单或页面的URL';
comment on column T_RESOURCE.REMARKS is
'备注';
comment on column T_RESOURCE.PARENT_ID is
'父菜单ID';
comment on column T_RESOURCE.DIS_ORDER is
'从1开始排序';
comment on column T_RESOURCE.STATUS is
'0:未删除
1:已删除 2:同步时删除';
comment on column T_RESOURCE.CREATE_DATE is
'录入时间';
comment on column T_RESOURCE.RESOURCE_FROM is
'资源来源 0:架构自行添加 1:集成平台同步';
comment on column T_RESOURCE.RESOURCE_TYPE_UUID is
'资源类型字典数据UUID';
comment on column T_RESOURCE.ISDELETEABLE is
'1不允许删除;0可以删除';
comment on table T_ROLE is
'角色表';
comment on column T_ROLE.ROLE_ID is
'主键';
comment on column T_ROLE.ROLE_NAME is
'角色名';
comment on column T_ROLE.ROLE_CODE is
'角色编码';
comment on column T_ROLE.DESCRIPTION is
'描述';
comment on column T_ROLE.ISDELETE is
'删除标志:0未删除 1已删除';
comment on column T_ROLE.FK_ROLE_TYPE is
'角色种类:0:自有角色 1:授权角色';
comment on column T_ROLE.FK_ROLE_TYPE_UUID is
'角色种类字典数据UUID';
comment on column T_ROLE.ISDELETEABLE is
'1不允许删除;0可以删除';
comment on table T_ROLE_MEMBER is
'角色、角色成员、有效范围的关联表';
comment on column T_ROLE_MEMBER.ROLE_ID is
'角色ID';
comment on column T_ROLE_MEMBER.USER_ID is
'用户ID';
comment on column T_ROLE_MEMBER.GROUP_ID is
'群组的ID';
comment on table T_ROLE_RESOURCE is
'角色资源表';
comment on column T_ROLE_RESOURCE.ROLE_RESOURCE_ID is
'主键';
comment on column T_ROLE_RESOURCE.RESOURCE_ID is
'资源ID';
comment on column T_ROLE_RESOURCE.ROLE_ID is
'角色ID';
comment on table T_DATA_SCOPE is
'权限范围';
comment on column T_DATA_SCOPE.ROLE_MEMBER_ID is
'角色成员ID';
comment on column T_DATA_SCOPE.ORG_ID is
'组织ID';
comment on table T_USER is
'用户表';
comment on column T_USER.USER_ID is
'主键';
comment on column T_USER.USERNAME is
'登录名';
comment on column T_USER.ERP_ID is
'ERP编号';
comment on column T_USER.PASSWORD is
'密码';
comment on column T_USER.MOBILE_PHONE1 is
'手机号码1';
comment on column T_USER.ELECTRONIC_SIGNATURE is
'电子签名';
comment on column T_USER.PERSONAL_IMAGE is
'个人头像';
comment on column T_USER.REALNAME is
'真实姓名';
comment on column T_USER.GENDER is
'性别';
comment on column T_USER.STATUS is
'0:未删除
1:已删除';
comment on column T_USER.DIS_ORDER is
'排序';
comment on column T_USER.ISENABLE is
'0:未禁用;1:禁用';
comment on column T_USER.FK_TYPE is
'用户类型-字典表';
comment on column T_USER.USER_ONLINE is
'最后在线时刻(用毫秒表示)';
comment on column T_USER.FK_TEAM is
'班组';
comment on column T_USER.SHORT_NO1 is
'集团短号1';
comment on column T_USER.PHONE_NO is
'座机号码';
comment on column T_USER.BIRTH_PLACE is
'出生地';
comment on column T_USER.EMAIL is
'邮箱';
comment on column T_USER.CARD_CODE is
'卡号';
comment on column T_USER.ID_CARD is
'身份证号';
comment on column T_USER.FK_POSTTITLE is
'职称-字典表';
comment on column T_USER.FK_POST is
'职位-字典表';
comment on column T_USER.FK_JOB1 is
'职务1-字典表';
comment on column T_USER.FK_JOBLEVEL is
'职级-字典表';
comment on column T_USER.BIRTHDAY is
'出生日期';
comment on column T_USER.ISDELETABLE is
'是否允许删除: 0 允许 1 不允许';
comment on column T_USER.MOBILE_PHONE2 is
'手机号码2';
comment on column T_USER.SHORT_NO2 is
'集团短号2';
comment on column T_USER.FK_JOB2 is
'职务2-字典表';
comment on column T_USER.FK_USERTYPE_UUID is
'用户类型字典数据UUID';
comment on column T_USER.FK_TEAM_UUID is
'班组字典数据UUID';
comment on column T_USER.FK_POSTTITLE_UUID is
'职称字典数据UUID';
comment on column T_USER.FK_POST_UUID is
'职位字典数据UUID';
comment on column T_USER.FK_JOB1_UUID is
'职务1字典数据UUID';
comment on column T_USER.FK_JOB2_UUID is
'职务2字典数据UUID';
comment on column T_USER.FK_JOBLEVEL_UUID is
'职级字典数据UUID';
/*======================约束=====================*/
alter table SYS_ACTIVITI_DEFINE_TEMPLATE
add constraint FKB9E57A9010AF362B foreign key (FK_CATEGORY_ID)
references SYS_ACTIVITI_CATEGORY (PK_ACTIVITI_CATEGORY_ID)
not deferrable;
alter table SYS_ACTIVITI_FORM_CATEGORY
add constraint FK5E10EAABBAF7CEE9 foreign key (PK_ACTIVITI_FORM_ID)
references SYS_ACTIVITI_FORM (PK_ACTIVITI_FORM_ID)
not deferrable;
alter table SYS_ACTIVITI_FORM_CATEGORY
add constraint FK5E10EAABE3591661 foreign key (PK_CATEGORY_ID)
references SYS_ACTIVITI_CATEGORY (PK_ACTIVITI_CATEGORY_ID)
not deferrable;
alter table SYS_ACTIVITI_PROCESS_INST
add constraint FKA2CEB7644D6CC09F foreign key (FK_ACTIVITI_CATEGORY_ID)
references SYS_ACTIVITI_CATEGORY (PK_ACTIVITI_CATEGORY_ID)
not deferrable;
alter table T_ATTACH
add constraint FK2B049890EE20AD3D foreign key (ATTACH_GROUP_ID)
references T_ATTACH_GROUP (ATTACH_ID)
not deferrable;
alter table T_DICTIONARY
add constraint FKFEB7F561FA82F069 foreign key (PARENT_ID)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_GROUP_MEMBER
add constraint FKAF71F68558DC4FB2 foreign key (USER_ID)
references T_USER (USER_ID)
not deferrable;
alter table T_GROUP_MEMBER
add constraint FKAF71F685EFF3B282 foreign key (GROUP_ID)
references T_GROUP (ID)
not deferrable;
alter table T_GROUP_MEMBER
add constraint FKAF71F685F0C9319A foreign key (ORG_ID)
references T_ORGANIZATION (ORG_ID)
not deferrable;
alter table T_LOG
add constraint FK4CC0CB958DC4FB2 foreign key (USER_ID)
references T_USER (USER_ID)
not deferrable;
alter table T_LOG
add constraint FK4CC0CB9F7234EEE foreign key (LOG_TYPE)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_ORGANIZATION
add constraint FK6FC9673E11C78A3D foreign key (FK_ORGTYPE)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_ORGANIZATION
add constraint FK6FC9673EA84F3A14 foreign key (PARENT_ID)
references T_ORGANIZATION (ORG_ID)
not deferrable;
alter table T_ORG_USER
add constraint FKAC44D3F1109B2A54 foreign key (FK_ORG_ID)
references T_ORGANIZATION (ORG_ID)
not deferrable;
alter table T_ORG_USER
add constraint FKAC44D3F133496E38 foreign key (FK_USER_ID)
references T_USER (USER_ID)
not deferrable;
alter table T_RESOURCE
add constraint FK47D00399B9801C64 foreign key (RESOURCE_TYPE)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_RESOURCE
add constraint FK47D00399CC7298F9 foreign key (PARENT_ID)
references T_RESOURCE (RESOURCE_ID)
not deferrable;
alter table T_ROLE
add constraint FK94B8458186C37602 foreign key (FK_ROLE_TYPE)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_ROLE_MEMBER
add constraint FKAF0E2A4D58DC4FB2 foreign key (USER_ID)
references T_USER (USER_ID)
not deferrable;
alter table T_ROLE_MEMBER
add constraint FKAF0E2A4DB7F777FD foreign key (ROLE_ID)
references T_ROLE (ROLE_ID)
not deferrable;
alter table T_ROLE_MEMBER
add constraint FKAF0E2A4DEFF3B282 foreign key (GROUP_ID)
references T_GROUP (ID)
not deferrable;
alter table T_ROLE_RESOURCE
add constraint FK3E7E410C9AA17315 foreign key (RESOURCE_ID)
references T_RESOURCE (RESOURCE_ID)
not deferrable;
alter table T_ROLE_RESOURCE
add constraint FK3E7E410CB7F777FD foreign key (ROLE_ID)
references T_ROLE (ROLE_ID)
not deferrable;
alter table T_DATA_SCOPE
add constraint FKF65C251058DC4FB2 foreign key (USER_ID)
references T_USER (USER_ID)
not deferrable;
alter table T_DATA_SCOPE
add constraint FKF65C251089298BF8 foreign key (ROLE_MEMBER_ID)
references T_ROLE_MEMBER (ID)
not deferrable;
alter table T_DATA_SCOPE
add constraint FKF65C2510EFF3B282 foreign key (GROUP_ID)
references T_GROUP (ID)
not deferrable;
alter table T_DATA_SCOPE
add constraint FKF65C2510F0C9319A foreign key (ORG_ID)
references T_ORGANIZATION (ORG_ID)
not deferrable;
alter table T_TEMP_TEAM_MENBER
add constraint FK_TEMP_USER_TEMP_TEM foreign key (TEMP_TEAM_ID)
references T_TEMP_TEAM (ID)
on delete cascade
not deferrable;
alter table T_USER
add constraint FK94B9B0D64EDAFAE7 foreign key (FK_JOB1)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D64EDAFAE8 foreign key (FK_JOB2)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D64EDDB773 foreign key (FK_POST)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D64EDF6130 foreign key (FK_TEAM)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D64EDFAE0D foreign key (FK_TYPE)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D692BFBFBA foreign key (FK_JOBLEVEL)
references T_DICTIONARY (PK_ID)
not deferrable;
alter table T_USER
add constraint FK94B9B0D6EB41C257 foreign key (FK_POSTTITLE)
references T_DICTIONARY (PK_ID)
not deferrable;<file_sep>/src/main/webapp/examples/leftTreeData.js
/**
* 定义通用控件示例左侧树的数据
* @author HEDJ
*/
var lefttreedata = {
root : {
text : "通用控件",
expanded : true,
children : [{
text : 'ExtJs通用控件',
children : [{
text : '表格(grid)',
children : [{
text : '表格面板(Ext.grid.Panel)',
leaf : true,
url : 'grid/panel.html'
}, {
text : '单元格提示(Ext.grid.column.Column)',
leaf : true,
url : 'grid/column.html'
}, {
text : '无数据样式(Ext.grid.Panel)',
leaf : true,
url : 'grid/gridPanel.html'
}, {
text : '禁用排序(Ext.grid.header.Container)',
leaf : true,
url : 'grid/container.html'
}, {
text : '序号列(Ext.grid.RowNumberer)',
leaf : true,
url : 'grid/rowNumberer.html'
}, {
text : '分页大小(Ext.data.Store)',
leaf : true,
url : 'grid/store.html'
}, {
text : '分页信息(Ext.PagingToolbar)',
leaf : true,
url : 'grid/pagingToolbar.html'
}, {
text : '数据格式(Ext.data.proxy.Ajax)',
leaf : true,
url : 'grid/ajax.html'
},{
text : '按钮禁用(Ext.selection.CheckboxModel)',
leaf : true,
url : 'grid/checkboxModel.html'
}, {
text : '操作列按钮(Ext.grid.column.Action)',
leaf : true,
url : 'grid/columnAction.html'
}, {
text : '查询数据及隐藏列(Ext.SearchBtn)',
leaf : true,
url : 'grid/searchBtn.html'
}
]
}, {
text : '表单(form)',
children : [{
text : '必填项红色星号(Ext.form.field.Base)',
leaf : true,
url : 'form/base.html'
}, {
text : '表单验证(Ext.form.field.VTypes)',
leaf : true,
url : 'form/vtype.html'
}, {
text : '提交进度条(Ext.form.action.Action)',
leaf : true,
url : 'form/actionOverride.html'
}
]
}, {
text : '消息提示(msg)',
children : [{
text : '消息提示(Ext.Msg)',
leaf : true,
url : 'msg/msg.html'
}
]
}, {
text : '控件(widget)',
children : [{
text : 'My97日期控件(Ext.form.field.My97DateTimePicker)',
leaf : true,
url : 'my97DateTimePicker/my97DateTimePicker.html'
},{
text : '模糊查询翻页下拉(Ext.form.field.ComboBox.QuerySelectCombo)',
leaf : true,
url : 'querySelectCombo/querySelectCombo.html'
},{
text : '模糊查询弹出列表(Ext.form.field.ComboBox.QuerySelectGrid)',
leaf : true,
url : 'querySelectGrid/querySelectGrid.html'
},{
text : '附件组(Ext.Attach)',
leaf : true,
url : 'attach/attach.html'
},
{
text : '多附件上传(Ext.Attach)',
leaf : true,
url : 'attachMulti/attachMulti.html'
}
]
}, {
text : '业务优化(optimize)',
children : [{
text : '列表明细列(Ext.grid.column.DetailColumn)',
leaf : true,
url : 'detailColumn/detailColumn.html'
}]
}
]
}, {
text : '异常处理及兼容',
children : [{
text : '右侧嵌入式iframe空白加载',
leaf : true,
url : 'abnormal/a1.html'
}, {
text : 'IE下飘浮提示数字符号断行',
leaf : true,
url : 'abnormal/a2.html'
}, {
text : '多层弹出窗口异常',
leaf : true,
url : 'abnormal/a3.html'
}
]
}, {
text : 'jQuery通用控件',
leaf : false
}, {
text : '自定义JS通用控件',
leaf : false
}
]
}
};
<file_sep>/pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xx</groupId>
<artifactId>cd_xx</artifactId>
<packaging>war</packaging>
<version>${project.version}</version>
<name>${project.name}</name>
<url>http://maven.apache.org</url>
<properties>
<project.name>cd_xx</project.name>
<project.version>1.0-SNAPSHOT</project.version>
<spring.version>3.2.6.RELEASE</spring.version>
<struts.version>2.3.20</struts.version>
<hibernate.version>3.3.1.GA</hibernate.version>
<cxf.version>3.1.0</cxf.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<porject.reporting.outputEncoding>UTF-8</porject.reporting.outputEncoding>
</properties>
<dependencies>
<!-- struts -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<classifier>sources</classifier>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>${hibernate.version}</version>
<exclusions>
<exclusion>
<artifactId>hibernate</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.1.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>ejb3-persistence</artifactId>
<version>1.0.2.GA</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>14</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.xfire</groupId>
<artifactId>bcprov-jdk15</artifactId>
<version>133</version>
</dependency>
<dependency>
<groupId>activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.9</version>
</dependency>
<dependency>
<groupId>activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.9</version>
</dependency>
<dependency>
<groupId>activiti</groupId>
<artifactId>activiti-cxf</artifactId>
<version>5.9</version>
</dependency>
<dependency>
<groupId>mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.0.6</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>com.dqgb</groupId>
<artifactId>cordys-client</artifactId>
<version>1.7.3</version>
</dependency>
<!-- <dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${JAVA_HOME}\lib\tools.jar</systemPath>
</dependency> -->
<!-- apache cxf -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>nexus-releases</id>
<name>Nexus Release Repository</name>
<url>http://10.114.72.106:8081/nexus/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://10.114.72.106:8081/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>com.idfconnect.devtools</groupId>
<artifactId>idfc-proguard-maven-plugin</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>obfuscate</goal>
</goals>
</execution>
</executions>
<configuration>
<proguardIncludeFile>${basedir}/proguard.pro</proguardIncludeFile>
<includeJreRuntimeJar>true</includeJreRuntimeJar>
<includeDependencies>true</includeDependencies>
<libraryArtifacts>
<libraryArtifact>javax.servlet:servlet-api:2.5</libraryArtifact>
<libraryArtifact>org.apache.tomcat:jsp-api:6.0.37</libraryArtifact>
<libraryArtifact>org.apache.tomcat:el-api:6.0.37</libraryArtifact>
</libraryArtifacts>
<excludeManifests>false</excludeManifests>
<excludeMavenDescriptor>false</excludeMavenDescriptor>
</configuration>
<dependencies>
<dependency>
<groupId>net.sf.proguard</groupId>
<artifactId>proguard-base</artifactId>
<version>4.9</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.4</version>
<configuration>
<locales>zh_CN</locales>
</configuration>
</plugin>
</plugins>
<finalName>${project.name}</finalName>
</build>
</project>
<file_sep>/src/main/webapp/examples/my97DateTimePicker/my97DateTimePicker.js
/**
* My97日期控件示例
* @author zengchao
* @date 2016-01-05
*/
Ext.onReady(function() {
var my97DateTimePickerForm1 = Ext.create('Ext.form.Panel', {
renderTo: 'my97DateTimePicker-example1',
width:500,
items: [{
layout : 'form',
columnWidth : 0.5,
border : false,
items : [{
fieldLabel : '开始时间',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd HH:mm:ss',
id:'purchaseDate',
maxDate:'startRunDate'
}
]
}, {
layout : 'form',
columnWidth : 0.5,
items : [{
fieldLabel : '结束时间',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd HH:mm:ss',
id:'startRunDate',
minDate:'purchaseDate'
}]
}]
});
var my97DateTimePickerForm2 = Ext.create('Ext.form.Panel', {
renderTo: 'my97DateTimePicker-example2',
width:800,
items: [{
layout : 'form',
columnWidth : 0.3,
border : false,
items : [{
fieldLabel : '不早于时间',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd',
maxDate:'2016-01-11'
}
]
}, {
layout : 'form',
columnWidth : 0.3,
items : [{
fieldLabel : '不晚于时间',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd HH:mm:ss',
minDate:'2016-01-11'
}]
}, {
layout : 'form',
columnWidth : 0.3,
items : [{
fieldLabel : '同时满足',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd HH:mm:ss',
minDate:'2016-01-11',
maxDate:'2016-01-22'
}]
}]
});
var my97DateTimePickerForm3 = Ext.create('Ext.form.Panel', {
renderTo: 'my97DateTimePicker-example3',
width:500,
items: [{
layout : 'form',
columnWidth : 0.5,
border : false,
items : [{
fieldLabel : '选择后回调',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd',
allowBlank : false,
changedCallback:alertCallback
}
]
}]
});
var my97DateTimePickerForm4 = Ext.create('Ext.form.Panel', {
renderTo: 'my97DateTimePicker-example4',
width:800,
items: [{
layout : 'form',
columnWidth : 0.3,
border : false,
items : [{
fieldLabel : '年',
xtype : "dateTimePicker",
dateFmt : 'yyyy年'
},{
fieldLabel : '年月日',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd'
},
]
}, {
layout : 'form',
columnWidth : 0.3,
items : [{
fieldLabel : '月',
xtype : "dateTimePicker",
dateFmt : 'M月'
},{
fieldLabel : '年月日时分秒',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd HH:mm:ss'
}]
}, {
layout : 'form',
columnWidth : 0.3,
items : [{
fieldLabel : '年月',
xtype : "dateTimePicker",
dateFmt : 'yyyy年MM月'
},{
fieldLabel : '时分秒',
xtype : "dateTimePicker",
dateFmt : 'HH:mm:ss'
}]
}]
});
});
function alertCallback(){
alert('这是日期选择后的回调')
}<file_sep>/src/main/webapp/examples/grid/searchBtnGrid.js
/*var basePath=(function(){
var href=window.location.href;
var host=window.location.host;
var index = href.indexOf(host)+host.length+1; //host结束位置的索引(包含/)
return href.substring(0,href.indexOf('/',index));
})(window);*/
/**
* @date 20160121
* @author zengchao
*/
/**
* 定义Model
*/
Ext.define("searchBtnModel", {
extend : "Ext.data.Model",
fields : [ {
name : 'id',
type : 'string'
},{
name : 'deviceCode',//设备编码
type : 'string'
},{
name : 'deviceName',//设备名称
type : 'string'
},{
name : 'className',//设备分类
type : 'string'
},{
name: 'purchaseDate',//购置日期
type : 'string'
}, {
name : 'planUserGroupName',//计划员组
type : 'string'
}, {
name : 'planUserGroupID',//计划员组外键
type : 'string'
},{
name : 'principal',//责任人
type : 'string'
},{
name : 'isDisabled',
type : 'int'
}]
});
/**
* 定义Store(生成列表的动态数据)
*/
var searchBtnStore = Ext.create('Ext.data.Store', {
model : searchBtnModel,
proxy : {
type : "format",
url : "../../examples/getEquipmentListByPage.action"
},
autoLoad:true
});
/**
* 定义数据显示列
*/
var searchBtnCm = [{
xtype : "rownumberer",
text : "序号",
width : 40,
align : "center"
},{
text: '设备编码',
dataIndex: 'deviceCode',
width: 80
},{
text: '设备名称',
dataIndex: 'deviceName',
menuDisabled : true,
width: 80
},{
text: '设备分类',
dataIndex: 'className',
width: 100
},{
text: '计划员组',
dataIndex: 'planUserGroupName',
width: 80
},{
text: '购置日期',
dataIndex: 'purchaseDate',
width: 120
},{
text: '投运日期',
dataIndex: 'startRunDate',
width: 120
}];
/**
* 定义Grid(生成列表页面)
*/
Ext.onReady(function() {
Ext.QuickTips.init();
var searchBtnGrid = Ext.create("Ext.grid.Panel",{
title : '示例',
height:250,
region : "center",
resizable:{
handles: 's' //只向下(南:south)拖动改变列表的高度
},
renderTo: 'searchBtnGrid-example',
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : searchBtnStore,
columns : searchBtnCm,
//头部工具条
tbar:['设备名称',{
xtype : 'textfield',
itemId : 'deviceName',
dataIndex:'deviceCode&deviceName',
width:90
},'关键字',{
xtype : 'textfield',
itemId : 'keyString',
width:90
},{
xtype:'searchBtn', //查询按钮
}
],
//底部工具条
bbar : Ext.create("Ext.PagingToolbar", {
store : searchBtnStore
})
});
});<file_sep>/src/main/webapp/scripts/common/redundancyData.js
Ext.define('Ext.grid.column.Element', {
extend : 'Ext.grid.column.Column',
text: '组织',
xtype:'elementColumn',
menuDisabled: true,
renderer : function(v , ctx , record){
var me=this
var tdAttrStr='';
Ext.Ajax.request({
url : basePath + '/user/getUserByIdForUpdate.action',
async:false,
params : {
id:'4028b881522eb08001522f2c62e20005'
},
success : function(response, action) {
var response = Ext.decode(response.responseText);
var data=response.data;
tdAttrStr='部门名称:'+data['orgNames']+'<br/>ERPID:'+data['user.erpId']+'<br/>性别:'+data['user.gender']+'<br/>实名:'+data['user.realname']+'<br/>用户名:'+data['user.username'];
}
});
ctx.tdAttr = 'data-qtip="' + tdAttrStr+ '"';
return v;
}
});<file_sep>/src/main/webapp/examples/grid/ResponseVo.java
package com.dqgb.sshframe.common.vo;
import java.util.List;
import com.dqgb.sshframe.common.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ResponseVo {
/**
* 是否成功
*/
private boolean success = true;
/**
* 提示消息
*/
private String msg;
/**
* 分页大小
*/
private Integer totalSize;
/**
* 分页 list 对象,封装一页的数据
*/
private List<?> list;
/**
* 单个对象,用于封装记录详细
*/
private Object data;
/**
* 返回全部非空的属性JSON对象。
* @return JSONObject
*/
public JSONObject getJsonObject() {
JSONObject jo = new JSONObject();
jo.put("success", success);
if (totalSize != null) {
jo.put("totalSize", totalSize);
}
if (StringUtil.isNotBlank(msg)) {
jo.put("msg", msg);
}
if (list != null) {
jo.put("list", JSONArray.fromObject(list));
}
if (data != null) {
jo.put("data", JSONObject.fromObject(data));
}
return jo;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getTotalSize() {
return totalSize;
}
public void setTotalSize(Integer totalSize) {
this.totalSize = totalSize;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
<file_sep>/src/main/webapp/scripts/log/LogGrid.js
/**
* 日志管理的列表功能,包含功能有 列表、查看功能。
* @date 20150706
* @author wujl
*/
/**
* 定义角色Model
*/
Ext.define("sshframe.log.logModel",{
extend:"Ext.data.Model",
fields:[
{
name: "id",
mapping:"pkLogId"
},
{
name: "typeId",
mapping:"logTypeCode"
},
{
name: "typeName",
mapping:"logTypeText"
},
{
name: "userId",
mapping:"userId"
},
{
name: "userName",
mapping:"userName"
},
{
name: "opDate",
mapping:"opDate"
},
{
name: "ipUrl",
mapping:"ipUrl"
},
{
name: "opContent",
mapping:"opContent"
},
{name: "realName"}
]
});
/**
* 定义Store
*/
sshframe.log.logStore=Ext.create("Ext.data.Store", {
model:"sshframe.log.logModel",
proxy: {
type: "format",
url: basePath+"/log/getLog.action"
}
});
/**
* 定义Grid
*/
sshframe.log.logGrid = Ext.create("Ext.grid.Panel",{
title:'日志管理',
region: "center",
store: sshframe.log.logStore,
columns:[
{header:"序号",xtype: "rownumberer",width:60,align:"center"},
{header: "操作用户ID",width: 100,dataIndex: "userId",hidden: true},
{header: "ID",width: 70,dataIndex: "id",hidden: true,},
{header: "typeId",width: 200,dataIndex: "typeId",hidden: true},
{header: "日志类型",width: 70,dataIndex: "typeName"},
{header: "发生日期",width: 150,dataIndex: "opDate"},
{header: "操作用户",width: 80,dataIndex: "userName",
renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
var realName = record.get('realName');
return realName+"("+value+")";
}
},
{header: "链接信息",width: 120,dataIndex: "ipUrl"},
{header: "日志内容",width: 400,dataIndex: "opContent",
renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
var answerStr = JSON.stringify(value);
eval(" var g_policy = '"+answerStr+"';");
return g_policy;
}
}
],
bbar: Ext.create("Ext.PagingToolbar", {
store: sshframe.log.logStore
}),
tbar:
{
xtype: 'toolbar',
preventItemsBubble: false,
items: [
'开始时间',
{ xtype: 'dateTimePicker',id:'startDate',name:'startDate', maxDate : 'endDate'},
' ',
'结束时间',
{ xtype: 'dateTimePicker',id:'endDate',name:'endDate', minDate : 'startDate'},
' ',
"日志内容",
{
xtype:"textfield",
id:"logContent"
},{
text: '查询',
iconCls:'search-button',
handler:function(){
var proxy = sshframe.log.logStore.getProxy();
proxy.setExtraParam("startDate",Ext.getCmp('startDate').getValue());
proxy.setExtraParam("endDate",Ext.getCmp('endDate').getValue());
proxy.setExtraParam("logContent",Ext.getCmp('logContent').getValue());
sshframe.log.logStore.loadPage(1);
//sshframe.log.logStore.load(proxy);
}
}
]}
});
sshframe.log.logGrid.on("itemdblclick",function(gridView, record, item, index, e, eOpts ){
Ext.create("Ext.window.Window", {
title:"日志内容",
height:400,
width:750,
modal: true,
autoScroll: true,
bodyStyle:"background-color:#FFFFFF",
html:"<table bgcolor='#FFFFFF' cellspacing='2' cellpadding='2' >"+
"<tr><td width='100'>日志类型:</td><td>"+record.get('typeName')+"</td><td width='100'>发生日期:</td><td>"+record.get('opDate').substr(0,19)+"</td></tr>"+
"<tr><td width='100'>操作用户:</td><td>"+record.get('userName')+"</td><td width='100'>链接信息:</td><td>"+record.get('ipUrl')+"</td></tr>"+
"<tr><td width='100'>日志内容:</td><td colspan='3'>"+eval("'"+JSON.stringify(record.get('opContent'))+"'")+"</td></tr>"+
"</table>",
buttonAlign:'center',
buttons:[{text:"关闭",handler:function(){
this.up('window').close();
}}
]
}).show();
});
<file_sep>/src/main/webapp/scripts/user/UserGrid.js
/**
* 用户管理的列表功能,包含功能有 列表、查看功能。
* @date 20150706
* @author wujl
*/
/**
* 定义用户Model
*/
Ext.define("sshframe.user.roleManageModel",{
extend:"Ext.data.Model",
fields:[
{name:'roleName'},
{name:'roleCode'},
{name:'description'},
{name:'roleId',type:'int'}
]
});
Ext.define("sshframe.user.permissionManageModel",{
extend:"Ext.data.Model",
fields:[
{name:'resourceName'},
{name:'code'},
{name:'resourceType'},
{name:'remarks'},
{name:'resourceId',type:'int'}
]
});
Ext.define("sshframe.user.userModel",{
extend:"Ext.data.Model",
fields:[
{name:"id",mapping:"id"},
{name:"orgName"},
{name:"username"},
{name:"<PASSWORD>"},
{name:"realname"},
{name:"gender"},
{name:"mobileNo1"},
{name:"mobileNo2"},
{name:"phoneNo"},
{name:"shortNo1"},
{name:"shortNo2"},
{name:"idCard"},
{name:"birthPlace"},
{name:"erpId"},
{name:"orgId"},
{name:"isDeleted"},
{name:"disOrder"},
{name:"type"},
{name: "post"},
{name: "postDictCode"},
{name: "postTitle"},
{name: "jobDictCode"},
{name: "job"},
{name: "jobLevelDictCode"},
{name: "jobLevel"},
{name: "email"},
{name: "isDisabled"},
{name: "birthDay"}
]
});
/**
* 定义Store
*/
sshframe.user.userStore=Ext.create("Ext.data.Store", {
pageSize: SystemConstant.commonSize,
model:"sshframe.user.userModel",
remoteSort:true,
proxy: {
type:"ajax",
actionMethods: {
read: 'POST'
},
url: basePath+"/user/getUserList.action",
reader: {
totalProperty: "totalSize",
root: "list"
},
simpleSortMode :true
},
sorters:[{
property:"userId",
direction:"ASC"
}]
});
var cm=[
{xtype: "rownumberer",text:"序号",width:60,align:"center"},
{header: "ID",align:'left',dataIndex: "userId",hidden: true},
{header: "部门",align:'left',dataIndex: "orgName",width:90},
{header: "登录名",align:'left',dataIndex: "username",width:90},
{header: "姓名",align:'left',dataIndex: "realname",width:90},
{header: "ERPID",align:'left',dataIndex: "erpId",width:90},
{header: "职务",align:'left',dataIndex: "job",width:90},
{header: "用户类别",align:'left',dataIndex: "type",width:90,
renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
if (value == 0) {
return '本地用户';
}
else {
return '中油用户';
}
}
},
{header: "性别",dataIndex: "gender",width:50},
{header: "手机1",align:'left',dataIndex: "mobileNo1",width:90},
{header: "集团短号1",align:'left',dataIndex: "shortNo1",width:90},
{header: "禁用",dataIndex: "",width:50,
renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
var isLockup = record.get('isDisabled');
if(isLockup == null || typeof(isLockup) == "undefined"){
return ;
}
var userId = record.get('id');
if(isLockup == 0){
return '<img title="点击锁定用户" src="'+basePath+'/images/icons/unlock.gif" style="cursor: pointer" onclick="sshframe.user.lockupUser(\''+userId+'\')"/>';
}else if(isLockup == 1){
return '<img title="点击解锁用户" src="'+basePath+'/images/icons/lock.gif" style="cursor: pointer" onclick="sshframe.user.lockupUser(\''+userId+'\')"/>';
}
},
align:'center'
}
];
/**
* 定义Grid
*/
sshframe.user.userGrid = Ext.create("Ext.grid.Panel",{
title:'用户管理',
width: "100%",
maxHeight:900,
id: "userGrid",
region: "center",
bbar: Ext.create("Ext.PagingToolbar", {
store: sshframe.user.userStore
}),
selModel:Ext.create("Ext.selection.CheckboxModel"),
store: sshframe.user.userStore,
columns:cm,
listeners:{
'render': function(g) {
sshframe.user.userStore.loadPage(1);
}
},
tbar: [
"姓名",
{
xtype:'textfield',
stripCharsRe : /^\s+|\s+$/g, // 禁止输入空格
id:'inputSearchName'
},
{
text : "查询",
iconCls: "search-button",
handler:function(){
var proxy = sshframe.user.userStore.getProxy();
proxy.setExtraParam("userName",Ext.getCmp('inputSearchName').getValue());
sshframe.user.userStore.loadPage(1);
}
},
"->",
{
text:SystemConstant.addBtnText,
id:"addUser",
iconCls: "add-button",
handler: function(){
sshframe.user.addUser();
}
},
{
text:SystemConstant.modifyBtnText,
id:"updateUser",
disabled: true,
disabledExpr : "$selectedRows != 1",
iconCls: "edit-button",
handler:function(){
var rows = sshframe.user.userGrid.getSelectionModel().getSelection();
cUserIsExist(rows[0].get('id'));
}
},
{
text:SystemConstant.deleteBtnText,
id:"deleteUser",
disabled:true,
disabledExpr : "$selectedRows == 0",
iconCls: "delete-button",
handler:function(){
sshframe.user.deleteUser();
}
},
{
text:'Excel',
id:'excelGroupBtn',
iconCls:'excel-button',
xtype:'splitbutton',
menu:[
{
text:SystemConstant.importUserInfoBtnText,
id:"userImport",
iconCls: "import-button",
handler: function(){
importUserWin.show();
}
},
{
text:SystemConstant.exportUserInfoBtnText,
id:"userExport",
iconCls: "export-button",
handler: function(){
Ext.MessageBox.wait("", "导出数据", {
text:"请稍后..."
});
$('#exportUsers').submit();
Ext.MessageBox.hide();
}
},
{
text:SystemConstant.downloadUserInfoImportTemplateBtnText,
id:'userImortTemplateDownload',
iconCls:'excel-button',
handler:function(){
$('#downloadType').val('user');
$('#downloadExcel').submit();
}
}
]
},
{
text:SystemConstant.resetPwd,
id:"userResetPwd",
iconCls: "resetPwd",
hidden:false,
disabled:true,
disabledExpr : "$selectedRows != 1",
handler: function(){
sshframe.user.resetPwd();
}
},
{
text : SystemConstant.synchronizeBtnText,
iconCls: "refresh-button",
id: "synchronizeUserInfoBtn",
handler:function(){
sshframe.user.synchronizeUser();
}
}
]
});
//锁定/解锁用户
sshframe.user.lockupUser = function (userId){
if(userId == currentUserId ){
Ext.Msg.showInfo("不允许禁用/解禁用户本身!");
return false;
}
Ext.Ajax.request({
url: basePath+'/user/updateUserEnable.action',
params: {
userId: userId
},
success: function(response, opts) {
var result = Ext.decode(response.responseText);
var flag = result.success;
if(flag){
refreshUserGrid();
Ext.Msg.showTip(result.msg);
}else{
Ext.Msg.showInfo(result.msg);
}
}
});
};
//重置密码
sshframe.user.resetPwd =function(){
var rows = sshframe.user.userGrid.getSelectionModel().getSelection();
if(rows.length > 0){
if(rows[0].get('type') != 0){
Ext.Msg.showInfo('非本地用户不能重置密码');
return;
}
Ext.Msg.confirm('系统提示','你确定要将这'+rows.length+'条数据密码重置为'+ SystemConstant.defaultPassword +'吗?',function(btn){
if(btn=='yes'){
var userIds = new Array();
for(var i=0;i<rows.length;i++){
var row=rows[i];
userIds.push(row.get('id'));
}
Ext.Ajax.request({
url: basePath+'/user/resetUserPassword.action',
params: {
userIds: userIds
},
success: function(response, opts) {
var result = Ext.decode(response.responseText);
var flag = result.success;
if(flag){
refreshUserGrid();
Ext.Msg.showTip(result.msg);
if(rows[0].get('id') == currentUserId){
setTimeout(function(){
Ext.Ajax.request({
url : basePath+'/user/logout.action',
success : function(res ,options) {
var json = Ext.decode(res.responseText);
if(json.success){
parent.window.location.href=basePath+"/toLogin.action";
}
}
});
},2000);
}
}else{
Ext.Msg.showInfo(result.msg);
}
}
});
}
});
}
};
importUserWin = new Ext.Window({
title: '用户导入',
closable:true,
width:400,
closeAction:'hide',
height:150,
modal:true,
resizable:false,
layout :"fit",
buttonAlign:'center',
html:'<form id="importUserFormDom" style="padding: 25 0 0 50" action="'+basePath+'/user/importUser.action" method="post" enctype="multipart/form-data">'+
'EXCEL文件:<input type="file" name="uploadAttach" id="uploadAttach" onchange="javascript:$(\'#filename\').val(this.value);"></input><br />'+
'<span id="uploadTip" style="color: red;"></span>'+
'<input type="hidden" name="filename" id="filename"></input>'+
'</form>',
buttons:[{
text:SystemConstant.uploadBtnText,
handler:importUserInfo
},{
text:SystemConstant.closeBtnText,
handler:function(){
importUserWin.hide();
}
}]
});
function importUserInfo(){
if($('#uploadAttach').val()=="" || null==$('#uploadAttach').val()){
$('#uploadTip').text('请先选择Excel文件');
setTimeout("$('#uploadTip').text('')",1500);
return;
}
var fileURL = $('#uploadAttach').val();
var type = fileURL.substring(fileURL.lastIndexOf(".")+1).toLowerCase();
if (type != 'xls' && type != 'xlsx') {
Ext.Msg.showInfo('文件格式错误,支持[.xls或.xlsx]结尾的excel格式!');
$('#uploadAttach').val('');
return;
}
Ext.MessageBox.wait("", "导入数据", {
text:"请稍后..."
});
Ext.Ajax.request({
url:basePath+'/user/importUser.action',
isUpload:true,
form:'importUserFormDom',
success:function(response, opts){
var result = Ext.decode(response.responseText);
var flag = result.msg;
if(flag == "importSuccess"){
Ext.MessageBox.hide();
Ext.Msg.showTip('用户导入成功');
importUserWin.hide();
sshframe.user.userGrid.getStore().load();
}else{
Ext.Msg.showError(flag);
}
}
});
}
//刷新用户列表
function refreshUserGrid(){
var store = sshframe.user.userGrid.getStore();
store.load();
}
/**
* 调用后台同步用户
*/
sshframe.user.synchronizeUser = function(){
Ext.Msg.confirm(SystemConstant.alertTitle,"同步将会删除现有数据,确定要同步吗?",function(btn) {
if (btn == 'yes') {
Ext.MessageBox.wait("", "同步用户数据", {
text:"请稍后..."
});
Ext.Ajax.request({
timeout:600000000,
url:basePath+'/user/synchronizeUserInfo.action',
success:function(response, opts){
var data = Ext.decode(response.responseText);
Ext.MessageBox.hide();
if(data.success){
Ext.Msg.showTip(data.msg);
sshframe.user.userStore.load();
orgTreeStore2.load();
}else{
Ext.Msg.showInfo(data.msg);
}
}
});
}
});
};
//在点击修改按钮之前,判断当前用户是否存在
function cUserIsExist(userId){
Ext.Ajax.request({
url: basePath+'/user/userIsExist.action',
params: {
userId: userId
},
success: function(response, opts) {
var result = Ext.decode(response.responseText);
var flag = result.success;
if(!flag){
Ext.Msg.showInfo("用户不存!");
}else{
//打开修改窗口
sshframe.user.updateUser(userId);
}
}
});
}
/**
* 调用后台删除用户
*/
sshframe.user.deleteUser = function() {
var rows = sshframe.user.userGrid.getSelectionModel().getSelection();
if(rows.length <= 0){
Ext.Msg.showInfo('请先选择要删除的数据');
return;
}
Ext.Msg.confirm(SystemConstant.alertTitle,SystemConstant.deleteMsgStart+rows.length+SystemConstant.deleteMsgEnd,function(btn){
if(btn=='yes'){
var userIds = "";
if(rows.length==1){
if(rows[0].get('id') == currentUserId ){
Ext.Msg.showInfo('不允许删除用户本身');
return;
}
userIds = rows[0].get('id');
}else{
for(var i=0;i<rows.length;i++){
userIds += ',' + rows[i].get('id');
if(rows[i].get('id') == currentUserId ){
Ext.Msg.showInfo('不允许删除用户本身');
return;
}
}
userIds = userIds.substring(1);
}
$.post(basePath+'/user/deleteUser.action', {userIds : userIds},
function(data){
var result = Ext.decode(data);
if (result.success) {
Ext.Msg.showTip(result.msg);
sshframe.user.userStore.loadPage(1);
}
else {
Ext.Msg.showInfo(result.msg);
}
});
/*
Ext.Ajax.request({
url: basePath+'/user/isCanDelete.action',
params: {
userId: userIds
},
success: function(response, opts) {
var result = Ext.decode(response.responseText);
var flag = result.success;
if(!flag){
Ext.Msg.showInfo(result.msg);
}else{
$.post(basePath+'/user/deleteUser.action', {userIds : userIds},
function(data){
Ext.Msg.showTip('删除用户成功');
sshframe.user.userStore.loadPage(1);
});
}
}
});
*/
}
});
};
/**
* 调用后台添加用户
*/
sshframe.user.addUser = function() {
sshframe.user.UserWin.setTitle('添加');
var basicForm = sshframe.user.UserWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath+'/user/addUser.action';
basicForm.findField('user.password').setVisible(true);
basicForm.findField('confirmPassword').setVisible(true);
basicForm.findField('user.password').setDisabled(false);
basicForm.findField('confirmPassword').setDisabled(false);
basicForm.findField('user.username').setDisabled(false);
basicForm.findField('user.type').setValue(0);
sshframe.user.UserWin.show();
};
/**
* 调用后台修改用户
*/
sshframe.user.updateUser = function(userId) {
sshframe.user.UserWin.setTitle('修改');
var basicForm = sshframe.user.UserWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/user/updateUser.action';
basicForm.findField('user.id').setValue(userId);
basicForm.findField('user.password').setVisible(false);
basicForm.findField('confirmPassword').setVisible(false);
basicForm.findField('user.password').setDisabled(true);
basicForm.findField('confirmPassword').setDisabled(true);
basicForm.findField('user.username').setDisabled(true);
basicForm.load({
url : basePath + '/user/getUserByIdForUpdate.action',
params : {
id : userId
},success :function(form, action){
var response = Ext.decode(action.response.responseText);
if(response.success){
sshframe.user.username = response.data['user.username'];
}
}
});
sshframe.user.UserWin.show();
};
<file_sep>/src/main/webapp/scripts/resource/TreeGrid.js
/**
* 定义资源树store
*/
var treeStore = Ext.create("Ext.data.TreeStore", {
proxy : {
type : "ajax",
actionMethods : {
read : 'POST'
},
url : basePath+ '/resource/getResourceByParentId.action'
},
root : {
text : "资源",
nodeId : "0",
expanded:true
},
listeners : {
beforeload : function(ds, opration, opt) {
opration.params.parentResId = opration.node.raw.nodeId;
}
}
});
/*
* 定义资源树load事件
**/
treeStore.on("load", function(store, node, records) {
if (selectNode == null && node != null && node.raw.nodeId == "0") {
treePanel.getSelectionModel().select(node, true);
treePanel.fireEvent("itemclick", treePanel.getView(), node);
}
});
/*
* 定义资源树panel
**/
var treePanel = Ext.create("Ext.tree.Panel", {
title : '资源信息',
region : "west",
width : 200,
store : treeStore,
rootVisible : true,
id : "typeTree",
dockedItems : [ {
xtype : 'toolbar',
style : "border-top:0px;border-left:0px",
items : [ {
iconCls : "icon-expand-all",
text : '展开',
tooltip : "展开所有",
handler : function() {
treePanel.expandAll();
},
scope : this
}, {
iconCls : "icon-collapse-all",
text : '折叠',
tooltip : "折叠所有",
handler : function() {
treePanel.collapseAll();
},
scope : this
} ]
} ],
listeners : {
"itemcontextmenu" : function(tree, record, item, index, e, eOpts) {
selectNode = record;
e.preventDefault();
if (record.raw.nodeId == "0") {
Ext.getCmp("updateResource").setVisible(false);
Ext.getCmp("deleteResource").setVisible(false);
}
},
"afterrender" : function(treePanel, eOpts) {
var path = treePanel.getRootNode().getPath();
treePanel.expandPath(path)
}
}
});
treePanel.on("itemclick",function(view,record,item,index,e,opts){
//获取当前点击的节点
var treeNode=record.raw;
var text=treeNode.text;
var id = treeNode.nodeId;
selectNode=record;
resourceStore.on('beforeload',function(store,options){
var new_params = {"parentResId":id};
Ext.apply(store.proxy.extraParams,new_params);
});
resourceStore.loadPage(1);
});
<file_sep>/src/main/webapp/scripts/extjs/ux/ExtjsExtend.js
/**
* @date 2015-05-27
* 设置EXTJS控制的默认值,为控制添加默认监听事件或行为等。
*/
/**
* 初始化消息提示
*/
Ext.QuickTips.init();
/**
* @author hedjaojun
* @date 2015-05-28
*
* 默认显示分页信息
*/
Ext.define('Ext.ux.pagingToolbarOverride', {
override : 'Ext.PagingToolbar',
displayInfo : true // 第 {0} - {1} 条,共 {2} 条
});
/**
* @author hedjaojun
* @date 2015-05-28
*
* 设置表格单元格在鼠标移动上去后,默认出现提示信息
*/
Ext.define('Ext.grid.column.ColumnOverride', {
override : 'Ext.grid.column.Column',
menuDisabled: true,
renderer : function(v , ctx , record){
ctx.tdAttr = 'data-qtip="' + v + '"';
return v;
}
});
/**
* @author zengchao
* @date 2016-01-21
*
* 在列表的序号列
*/
Ext.define('Ext.grid.RowNumbererOverride', {
override : 'Ext.grid.RowNumberer',
text:"序号",
width:30,
align:"center",
renderer: function(value, metaData, record, rowIdx, colIdx, store) {
var me=this;
var rowspan = this.rowspan,
page = store.currentPage,
result = record.index;
if (rowspan) {
metaData.tdAttr = 'rowspan="' + rowspan + '"';
}
if (result == null) {
result = rowIdx;
if (page > 1) {
result += (page - 1) * store.pageSize;
}
}
var digit=result.toString().length-1;
me.width=35+5*digit;
return result + 1;
}
});
/**
* @author zenchao
* @date 2015-05-29
*
* 设置默认没有排序功能
*/
Ext.define('Ext.grid.header.ContainerOverride', {
override : 'Ext.grid.header.Container',
defaults: { // defaults 将会应用所有的子组件上,而不是父容器
sortable : false
}
});
/**
* @author hedjaojun
* @date 2015-05-29
*
* 设置分页条数为 99
*/
Ext.define('Ext.data.StoreOverride', {
override : 'Ext.data.Store',
pageSize: 99
});
/**
* @author hedjaojun
* @date 2015-05-29 定义数据格式
*/
Ext.define('Ext.ux.data.proxy.Format', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.format',
actionMethods: {
read: 'POST'
},
reader: {
type: 'json',
root: "list",
totalProperty: "totalSize",
messageProperty: "msg"
},
listeners: {
exception : function (proxy, response, options, epots) {
sshframe.FailureProcess.Proxy.apply(this, arguments);
}
}
});
/**
* @author zengchao
* @date 2015-05-29
*
* @edit hedaojun
* @data 2015-06-03 复选框,实现根据选择的记录条数,disable 删除,添加等按钮。 使用时,需要为CheckboxModel
* 添加 使用时,在列表的button配置里添加 属性 disabledExpr 例:
* disabledExpr:"$selectedRows != 1 || $status =='1'" $selectedRows
* 表示选中的记录数不等于1,或者选择行记录的状态为禁用 $status 为modal中定义的字段。
*
*/
Ext.define("Ext.selection.CheckboxModelOverride", {
override : 'Ext.selection.CheckboxModel',
injectCheckbox : 1,
listeners :{
"selectionchange" : function (checkModel){
// 定义计算表达式的函数。
var evalExpr = function(expr){
var result = false;
try{ result = eval(expr); }catch(e){
// alert('禁用按钮表达示错误: '+e.name+' '+e.message);
}
return result;
};
var ownerCt=checkModel.view.initialConfig.grid;
var selectRows = ownerCt.getSelectionModel().getSelection();
var selLenth=selectRows.length;
var buttons = Ext.ComponentQuery.query('button',ownerCt);
var exps,disabled;
for(var i=0;i<buttons.length;i++){
if(buttons[i].disabledExpr){
var exps = buttons[i].disabledExpr;
// selLenth为前面定义的选择的行数
exps = exps.replace(/\$selectedRows/g, 'selLenth');
if(selLenth==0){
disabled = evalExpr(exps);
}else{
for(var j = 0; j<selLenth ; j++) {
var data = selectRows[j].data;
exps = exps.replace(/\$/g, 'data.');
disabled = evalExpr(exps);
if(disabled === true){
break;
}
}
}
if(disabled === true){
buttons[i].setDisabled(true);
}else{
buttons[i].setDisabled(false);
}
}
}
}
}
});
/**
* @author hedjaojun
* @date 2015-05-28
* 设置表格列边框,强制适应页面等基本样式
*
* @author zengchao
* @date 2015-12-24
* 列表的自动显示暂无数据和查询条件下午数据的图片展示方式
*/
var judgeArrIsAllthenull=function(arr){//判断store中是否没有参数,或者参数全部为空
var result = true;
if(arr.length===0){
return true;
}else{
for(x in arr){
if(arr[x]==''||arr[x]==undefined||arr[x]==null){
}else{
result=false;
break;
}
}
}
return result;
};
Ext.define('Ext.grid.PanelOverride', {
override : 'Ext.grid.Panel',
columnLines : true, // 列边框线
forceFit : true, // 列表自适应页面
autoScroll: true,
stripeRows: true,
store:{},
gridNoNumber:'',
initComponent:function(){
var me=this;
me.store.on("load",function(dataStore) {
var count = dataStore.getCount();
var paramsArr = Ext.Object.getValues(dataStore.getProxy().extraParams);
paramsResult=judgeArrIsAllthenull(paramsArr);
if (count <= 0) {
if (paramsResult==false) {
var gridNoimg2_id='gridNoimg2_'+me.id;
me.getView().update('<div id="'+gridNoimg2_id+'" class="gridNoimg_2"></div>');
} else {
var gridNoimg1_id='gridNoimg1_'+me.id;
me.getView().update('<div id="'+gridNoimg1_id+'"class="gridNoimg_1"></div>');
}
} else {
if (Ext.getDom('gridNoimg1_'+me.id)) {
Ext.getDom('gridNoimg1_'+me.id).style.cssText = 'display:none;';
}
if (Ext.getDom('gridNoimg2_'+me.id)) {
Ext.getDom('gridNoimg2_'+me.id).style.cssText = 'display:none;';
}
}
},this);
me.store.on("add",function(store) {
if (Ext.getDom('gridNoimg1_'+me.id)) {
Ext.getDom('gridNoimg1_'+me.id).style.cssText = 'display:none;';
}else if (Ext.getDom('gridNoimg2_'+me.id)) {
Ext.getDom('gridNoimg2_'+me.id).style.cssText = 'display:none;';
}
},this);
this.callParent(arguments);
}
});
Ext.define("Ext.form.action.ActionOverride",{
override : 'Ext.form.action.Action',
waitTitle : '请等待...',
waitMsg : '正在提交...'
});
/**
* @author zengchao
* @date 2015-06-01
*
* 为弹出的form中的录入控件增加必填项标示*
*
*/
Ext.override(Ext.form.field.Base, { // 针对form中的基本组件
width:90,
validateOnChange:false,
initComponent : function () {
if (this.allowBlank !== undefined && !this.allowBlank) {
if (this.fieldLabel) {
this.fieldLabel = "<span style='color:red;'>*</span>" + this.fieldLabel;
}
}
this.callParent(arguments);
}
});
Ext.override(Ext.container.Container, { // 针对form中的容器组件
validateOnChange:false,
initComponent : function () {
if (this.allowBlank !== undefined && !this.allowBlank) {
if (this.fieldLabel) {
this.fieldLabel = "<span style='color:red;'>*</span>" + this.fieldLabel;
}
}
this.callParent(arguments);
}
});
/**
* @author zengchao
* @date 2015-06-01
*
* 弹出框windows 在不同的展示中可能会对layout进行多种调整,默认为auto,这样的窗口会从上至下的去展示items中的组件;
*
*/
Ext.define("Ext.window.WindowOverride",{
override : 'Ext.window.Window',
closable: true,
resizable: false,
buttonAlign: "center",
modal: true,
layout : 'fit',
closeAction : 'hide'
});
/**
* @author zengchao
* @date 2015-06-02
*
* xtype:'combo'在from表单中 默认显示为 请选择
*
*/
Ext.define("Ext.form.ComboBoxOverride",{
override : 'Ext.form.ComboBox',
typeAhead:false,
editable:false,
queryMode: 'local'
});
/**
* @author hedaojun
* @date 2015-06-30
* 根据表达式判断返回一个布尔值的方法
*
*/
var evalExpr = function(expr){
var result = false;
try{
result = eval(expr);
}catch(e){
Ext.Msg.showError('计算表达式错误: '+e.name+' '+e.message);
}
return result;
};
/**
* @author zengchao
* @date 2015-06-30
*
* @rewrite zengchao
* @date 2015-06-30
* grid.column中的操作列,图标按钮控制,需要配置showExpr表达式参数来确定根据什么条件显示此按钮
* 例: showExpr:'$d=="同意"||$e==3' /$d=="同意" 表示model中取得的行数据等于 "同意"的时候显示
* 注意:将过去的$name$=='value'方式调整为$name=='value'
*/
Ext.define('Ext.grid.column.ActionOverride', {
override : 'Ext.grid.column.Action',
iconClsArray : new Array(),
initComponent : function(){
var me = this;
me.iconClsArray.length = 0;
me.callParent(arguments);
},
renderer : function (value, cellmeta, record, rowIndex, columnIndex, store) {
// 定义计算表达式的函数。
var evalExpr = function(expr){
var result = false;
try{ result = eval(expr); }catch(e){
// alert('禁用按钮表达示错误: '+e.name+' '+e.message);
}
return result;
}
var pd=true;
for (var i = 0; i < this.items.length; i++) {
if(this.items[i].iconCls=='null-button'){
pd=false;
break;
}
else{
}
}
if(pd==true){
this.iconClsArray.length = 0;
}else{
}
for (var i = 0; i < this.items.length; i++) {
var exps = this.items[i].showExpr;
if(exps){
this.iconClsArray.push(this.items[i].iconCls);
exps = exps.replace(/\$/g, 'record.data.');
disabled = evalExpr(exps);
if (disabled == false) {
this.items[i].iconCls = 'null-button';
} else {
this.items[i].iconCls = this.iconClsArray[i];
}
}
}
}
});
/**
* @author zengchao
* @date 2015-09-23
*
* 封装tree树形菜单,简化前端代码;
*/
Ext.define('Ext.tree.PanelOverride', {
override : 'Ext.tree.Panel',
border : true,
collapseMode : "mini",
collapsible : false,
split : true,
rootVisible : false
});
/**
* @author zengchao
* @date 2015-09-15
*
* 封装form.Panel普通面板,单纯对整体样式风格进行封装:内容整体边距为10px;items标题长度为80;
*/
Ext.define("Ext.form.PanelOverride", {
override : 'Ext.form.Panel',
frame: false,
bodyPadding: 0,
border: 0,
border: false,
layout: 'column',
bodyStyle: 'padding:0px 3px 0px 2px',
fieldDefaults: {
labelWidth: 80,
labelAlign: 'right',
anchor: '100%'
},
defaults: {
border: 0,
border: false,
bodyStyle :'padding-right:3px;padding-left:3px'
}
});
/**
* @author zengchao
* @date 2015-07-01
*
* 创建searchButton按钮类,按钮作用于gird中tbar下的查询按钮
* 1,遍历查询按钮之前的
* 2,遍历tbar下的查询条件,对存在dataIndex的控件提取值,用于对columns列隐藏;
* 例:dataIndex=a&b,标示columns中dataIndex值为a和b的都隐藏
* 注:在显示的时候如果前置条件存在a值并且隐藏掉了,那么当前条件如果dataIndex=a&b,并且值为全部的时候a不会被显示出来
*/
Ext.define("Ext.SearchBtn", {
extend : 'Ext.Button',
xtype : 'searchBtn',
text : "查询",
iconCls : "search-button",
handler : function (button) {
var myGrid = this.findParentByType("grid");
var tbarItems = this.findParentByType("toolbar").items;
var tbarItemsKeys = tbarItems.keys;
var new_params = {};
var arr = new Array();
for (key in tbarItemsKeys) {
var buttonItmes = button.prev('#' + tbarItemsKeys[key]);
if (buttonItmes) {
if (buttonItmes.itemId != undefined) {
arr.push(buttonItmes.itemId);
new_params[buttonItmes.itemId] = buttonItmes.getValue();
}
}
}
var dataStore = myGrid.getStore();
Ext.apply(dataStore.getProxy().extraParams, new_params);
dataStore.loadPage(1);
var gridColumns = myGrid.columns;
var dataIndexArray = new Array();
for (var i = 0; i < tbarItems.length; i++) {
var hideIndex = (tbarItems.items)[i].dataIndex
var patt = new RegExp('&');
var relation = patt.test(hideIndex);
if (relation == false && hideIndex) {
dataIndexArray.push(hideIndex);
}
}
for (var i = 0; i < tbarItems.length; i++) {
if ((tbarItems.items)[i].dataIndex && (tbarItems.items)[i].value != 'all') {
var hideIndex = (tbarItems.items)[i].dataIndex
var hideIndexArray = hideIndex.split("&"); //拆分表达式
for (var y in hideIndexArray) { //遍历判断
for (var x in gridColumns) {
if (myGrid.columns[x].dataIndex == hideIndexArray[y]) {
gridColumns[x].hide();
}
}
}
} else if ((tbarItems.items)[i].dataIndex && (tbarItems.items)[i].value == 'all') {
var hideIndex = (tbarItems.items)[i].dataIndex
var hideIndexArray = hideIndex.split("&");
var patt = new RegExp('&');
var relation = patt.test(hideIndex);
if (relation == true) {
for (var z in dataIndexArray) {
Ext.Array.remove(hideIndexArray, dataIndexArray[z])
}
for (var y in hideIndexArray) {
for (var x in gridColumns) {
if (myGrid.columns[x].dataIndex == hideIndexArray[y]) {
gridColumns[x].show();
}
}
}
} else if (relation == false) {
for (var y in hideIndexArray) {
for (var x in gridColumns) {
if (myGrid.columns[x].dataIndex == hideIndexArray[y]) {
gridColumns[x].show();
}
}
}
}
}
}
}
});
/**
* @author zengchao
* @date 2015-09-18
* 封装日期控件dateTimePicker;
* 1,需要设置dateFmt属性,标示出时间格式;默认为值dateFmt:'yyyy-MM-dd',既 年-月-日的显示方式;
* 2,当控件实例中设置了allowBlank:false默认必填,那么控件会自动给出当前日期;
* 3,需要设置参数maxDate或者minDate;其中maxDate为最大日期限制的日期控件id,minDate为最小日期限制的日期控件id;
* 例:maxDate:'endDate',那么此日期控件能选择的范围不得超过id为endDate的控件日期的范围;
* 例:maxDate:'2016-01-05',那么此日期控件能选择的范围不得超过2016年1月5日的控件日期的范围;
* 注:控件的内核代码为my97DatePicker;
* 注:此封装只是针对了这种联锁关系限制的简化控制,如果有特殊情况比如需要一个特点日期的限制,请不要使用此dateTimePicker控件,用my97日期控件原始去做控制;
*/
Ext.define("Ext.form.field.My97DateTimePicker", {
extend : 'Ext.form.field.Text',
xtype : "dateTimePicker",
dateFmt:'yyyy-MM-dd',
minTime : "1900-01-01 00:00:00",
maxTime : "2099-12-31 23:59:59",
readOnly:true,
initComponent : function(){
var me = this;
var changedFun=me.changedFun
if(this.allowBlank==false){
var curDate = new Date();
var dateFmtRequired=this.dateFmt;
dateFmtRequired=dateFmtRequired.replace(/yyyy/, "Y");
dateFmtRequired=dateFmtRequired.replace(/MM/, "m");
dateFmtRequired=dateFmtRequired.replace(/dd/, "d");
dateFmtRequired=dateFmtRequired.replace(/HH/, "H");
dateFmtRequired=dateFmtRequired.replace(/mm/, "m");
dateFmtRequired=dateFmtRequired.replace(/ss/, "s");
var time=Ext.Date.format(curDate, dateFmtRequired);
this.setValue(time);
}
me.callParent(arguments);
},
listeners : {
'render' : function (p) {
var me=this;
var thisinputEl=this.id+'-inputEl';
var thisInput = Ext.getDom(thisinputEl);
thisInput.className = 'dateTime-icon';
var dateFmt=this.dateFmt;
if(this.maxDate){
var dateRequired=this.maxDate;
dateRequired=dateRequired.replace(/\-/g, "");
dateRequired=dateRequired.replace(/\:/g, "");
dateRequired=dateRequired.replace(/[\u4E00-\u9FA5]/g, "");
var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字
if (!re.test(dateRequired))
{
this.maxTime="#F{$dp.$D(\'"+this.maxDate+"-inputEl\')}";
}else{
this.maxTime=this.maxDate;
}
}if(this.minDate){
var dateRequired=this.minDate;
dateRequired=dateRequired.replace(/\-/g, "");
dateRequired=dateRequired.replace(/\:/g, "");
dateRequired=dateRequired.replace(/[\u4E00-\u9FA5]/g, "");
var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字
if (!re.test(dateRequired))
{
this.minTime="#F{$dp.$D(\'"+this.minDate+"-inputEl\')}";
}else{
this.minTime=this.minDate;
}
}
thisInput.onclick = function(){
WdatePicker({
readOnly : true,
dateFmt : dateFmt,
minDate : me.minTime,
maxDate : me.maxTime,
onpicked: dateTimePickerCallBack
});
};
function dateTimePickerCallBack(){
if (me.changedCallback) {
var changedCallback = me.changedCallback;
changedCallback();
}
}
}
}
});
/**
* @author zengchao
* @date 2015-10-27
* 封装combox下拉分页控件;
* 1,需要配置pathByUrl通过id去查询数据的action地址;
* 2,解决如果初始化或者更新数据不在第一页或者本页的情况下,不能赋值的漏洞
* 3,解决翻页后,已选择数据会被置空的漏洞
* 4,通过对Ext.locale.zh_CN.toolbar.Paging重构的改写,对数据combo的翻页样式进行了编辑,以适应在较短的输入框中也能显示完全
*/
Ext.define("Ext.form.field.ComboBox.QuerySelectCombo", {
extend : 'Ext.form.field.ComboBox',
xtype:'querySelectCombo',
forceSelection : true,
queryParam : 'keystring',
valueField : 'id',
minChars : 0,
triggerAction : 'all',
pageSize :5,
editable : true,
typeAhead : false,
queryMode : 'remote',
displayFieldValue:'',
valueFieldValue:'',
targetObject:'',
validateOnChange:false,
setDefaultValue : function(val) {
var me = this;
if (val != '') {
me.setValue(val);
}
},
setValue:function(idd){
var me = this;
var paramsId=idd;
if(paramsId==undefined|| paramsId == ''){
if(paramsId==undefined){
me.setRawValue('');
me.value='';
} else{
// 设置空数据
var data ;
Ext.Array.forEach(me.store.data.items, function(element,i , list) {
if(element.data[me.valueField]==''){
data = element.data;
return ;
}
});
if(data!=undefined){
me.displayTplData =[data];
me.setRawValue(data[me.displayField]);
me.value=paramsId;
} else{
me.setRawValue('');
me.value='';
}
}
}else if(typeof(idd)=='object'){
// 设置行数据时的处理
var path=me.pathByUrl;
paramsId=idd[0].data[me.valueField];
if(paramsId==''){
// 选中值为''的时候
var data ;
Ext.Array.forEach(me.store.data.items, function(element,i , list) {
if(element.data[me.valueField]==paramsId){
data = element.data;
return ;
}
});
if(data!=undefined){
me.displayTplData =[data];
me.setRawValue(data[me.displayField]);
me.value=paramsId;
}
} else if(me.store.find(me.valueField,paramsId) >=0){
// 绑定数据列表的时候
var data ;
Ext.Array.forEach(me.store.data.items, function(element,i , list) {
if(element.data[me.valueField]==paramsId){
data = element.data;
return ;
}
});
if(data!=undefined){
me.displayTplData =[data];
me.setRawValue(data[me.displayField]);
me.value=paramsId;
}
} else{
// 其他时候
me.setRawValue(idd[0].data[me.displayField]);
me.value=paramsId;
}
if(me.propertyMap){
setPropertyMap(me.propertyMap,idd[0].data)
}
} else { //if (me.store.find(me.valueField,paramsId) == -1) {
// 数据不在Store列表中
var path=me.pathByUrl;
var queryCondition={};
queryCondition[me.valueField]=paramsId;
Ext.Ajax.request({
url:path,
params:queryCondition,
success : function(res) {
var ret = Ext.decode(res.responseText);
if (ret.success) {
var udata = ret.data;
if(me.store.data.items.length>0 && udata!==undefined){
var rdata = me.store.data.items[0].copy();
if(targetObject!=''){
rdata[me.displayField] = udata[targetObject+'.'+me.displayField];
rdata[me.valueField] = paramsId;
}else{
rdata[me.displayField] = udata[me.displayField];
rdata[me.valueField] = paramsId;
}
me.displayTplData = [ rdata ];
me.setRawValue(rdata[me.displayField]);
me.value=paramsId;
} else{
me.setRawValue(udata[me.displayField]);
me.value=paramsId;
}
if(me.propertyMap){
setPropertyMap(me.propertyMap,udata)
}
}
}
});
}
},
initComponent : function(){
var me = this;
displayFieldValue=me.displayField;
valueFieldValue=me.valueField;
targetObject=me.targetObject;
me.on('change', function(ctrl, newval, oldval) {
if(me.store.findRecord(me.valueField, newval)){
me.setDefaultValue(newval);
}else if (newval != '' && oldval == '') {
me.setDefaultValue(newval);
}
});
me.callParent(arguments);
}
});
function setPropertyMap(propertyMap,record){
for (name in propertyMap) {
var key = propertyMap[name];
if (typeof key == 'function') {
key(record[name]); // 执行传入方法
continue;
}
var relation = name.indexOf('.')
var resultValue;
if (name && relation > 0) {
var showExprArray = name.split("."); // 拆分表达式
resultValue = record[showExprArray[0]][showExprArray[1]];
} else if (relation == -1) {
resultValue = record[name];
}
Ext.getCmp(propertyMap[name]).setValue(resultValue);
}
}
function emptyPropertyMap(propertyMap){
for (name in propertyMap) {
var key = propertyMap[name];
if (typeof key == 'function') {
continue;
};
Ext.getCmp(propertyMap[name]).setValue('');
}
}
/**
*
*/
Ext.define("Ext.form.field.ComboBox.QuerySelectGrid", {
extend : 'Ext.form.field.ComboBox',
hideTrigger : true,
queryMode : 'local',
xtype : "querySelectGrid",
fieldLabel:'',
queryParam : 'keystring',
targetObject:'',
listeners : {
'render' : function(p) {
var thisinputEl = this.id + '-inputEl'
var thisInput = Ext.getDom(thisinputEl);
thisInput.className = 'selectGrid-icon';
},'focus' : function() {
var me = this;
createGridWin(me.columnsMap,me.store,me);
}
},
setValue:function(idd){
if(idd){
var me=this;
var path=me.pathByUrl;
var queryCondition={};
var paramsId=idd;
var targetObject=me.targetObject
queryCondition[me.valueField]=paramsId;
Ext.Ajax.request({
url:path,
params:queryCondition,
success : function(res) {
var ret = Ext.decode(res.responseText);
if (ret.success) {
var udata = ret.data;
if(me.store.data.items.length>0 && udata!==undefined){
var rdata = me.store.data.items[0].copy();
if(targetObject!=''){
rdata[me.displayField] = udata[targetObject+'.'+me.displayField];
rdata[me.valueField] = paramsId;
}else{
rdata[me.displayField] = udata[me.displayField];
rdata[me.valueField] = paramsId;
}
me.displayTplData = [ rdata ];
me.setRawValue(rdata[me.displayField]);
me.value=paramsId;
} else{
me.setRawValue(udata[me.displayField]);
me.value=paramsId;
}
if(me.propertyMap){
setPropertyMap(me.propertyMap,udata)
}
}
}
});
}
},
initComponent : function() {
var me = this;
me.callParent(arguments);
}
});
function createGridWin(columnsMap,querySelectGridStore,target){
var querySelectGridCm=[{
xtype : "rownumberer",
text : "序号",
width : 40,
align : "center"
}];
for (name in columnsMap) {
var new_columns ={};
if(typeof(columnsMap[name])=='object'){
new_columns=columnsMap[name];
}else{
new_columns = {
text : columnsMap[name],
dataIndex : name,
width : 120
};
}
querySelectGridCm.push(new_columns);
}
var querySelectGridGrid = Ext.create("Ext.grid.Panel",{
border:0,
selModel : Ext.create("Ext.selection.CheckboxModel",{}),
store : querySelectGridStore,
columns : querySelectGridCm,
//头部工具条
tbar:['关键字',{
xtype : 'textfield',
itemId : target.queryParam,
width:90
},{
xtype:'searchBtn'
}
],
bbar : Ext.create("Ext.PagingToolbar", {
store : querySelectGridStore
})
});
querySelectGridWin= Ext.create("Ext.window.Window", {
title : target.fieldLabel+'选择',
width : 600,
height:400,
closeAction : 'destroy',
items : [querySelectGridGrid],
buttons : [ {
text : SystemConstant.saveBtnText,
handler : function() {
var record = querySelectGridGrid.getSelectionModel().getSelection()[0];
target.displayTplData =[record.data];//这是核心,extjs原生的属性
target.setRawValue(record.get(target.displayField));
target.value=record.get(target.valueField);
if(target.propertyMap){
setPropertyMap(target.propertyMap,record.data)
}
this.findParentByType("window").close();
}
}, {
text : '清空',
handler : function() {
target.setValue('');
target.setRawValue('');
if(target.propertyMap){
emptyPropertyMap(target.propertyMap)
};
this.findParentByType("window").close();
}
}, {
text : SystemConstant.closeBtnText,
handler : function() {
querySelectGridGrid.destroy();
this.findParentByType("window").close();
}
}]
}).show();
}
/*外键显示字段*/
Ext.define("Ext.form.field.Display", {
override : 'Ext.form.field.Display',
targetObject:'',
valueField : 'id',
setValue:function(idd){
var me=this;
if(idd&&!me.pathByUrl){
me.setRawValue(idd);
me.value=idd;
} else if(idd&&me.pathByUrl){
var path=me.pathByUrl;
var queryCondition={};
var paramsId=idd;
var targetObject=me.targetObject
queryCondition[me.valueField]=paramsId;
Ext.Ajax.request({
url:path,
params:queryCondition,
success : function(res) {
var ret = Ext.decode(res.responseText);
if (ret.success) {
var udata = ret.data;
if(udata!==undefined){
var rdata = udata;
if(targetObject!=''){
rdata[me.displayField] = udata[targetObject+'.'+me.displayField];
rdata[me.valueField] = paramsId;
}else{
rdata[me.displayField] = udata[me.displayField];
rdata[me.valueField] = paramsId;
}
me.displayTplData = [ rdata ];
me.setRawValue(rdata[me.displayField]);
me.value=paramsId;
} else{
me.setRawValue(udata[me.displayField]);
me.value=paramsId;
}
}
}
});
}
}
});
/**/
Ext.define("Ext.window.BasicWindow", {
extend:'Ext.window.Window',
xtype:'basicWindow',
title:'',
actionUrl:'',
targetStore:{},
targetGrid:{},
init:function(way,actionUrl,target,idd) {
var me=this
me.targetGrid=target;
me.targetStore = target.store;
me.actionUrl = actionUrl;
if (way == 'add') {
this.setTitle('添加');
} else if (way == 'edit') {
this.setTitle('修改');
var basicForm = me.down('form').getForm();
basicForm.reset();
basicForm.load({
url : me.actionUrl,
params : {
id : idd
}
});
} else if (way == 'detail') {
this.setTitle('详情');
var basicForm = me.down('form').getForm();
basicForm.reset();
basicForm.load({
url : me.actionUrl,
params : {
id : idd
}
});
}
},
buttons : [ {
text : '保存',
//text : SystemConstant.saveBtnText,
handler : function() {
var basicWin=this.findParentByType("window");
var basicForm =basicWin.down('form').getForm();
basicForm.url = basicWin.actionUrl;
if (basicForm.isValid()) {
basicForm.submit({
success : function(form, action) {
if(action.result.success){
Ext.Msg.showTip(action.result.msg);
basicWin.targetStore.loadPage(1);
basicWin.close();
} else{
Ext.Msg.showError(action.result.msg);
}
},
failure : function(form, action) {
Ext.Msg.showError(action.result.msg);
}
});
}
}
}, {
text : '关闭',
//text : SystemConstant.closeBtnText,
handler : function() {
this.findParentByType("window").close();
}
}]
});
/**
* @author zengchao
* @date 2015-09-15
*
* 创建添加按钮封装样式
*/
Ext.define("Ext.AddBtn", {
extend : 'Ext.Button',
xtype : 'addBtn',
text : SystemConstant.addBtnText,
iconCls: "add-button"
});
/**
* @author zengchao
* @date 2015-09-15
*
* 创建修改按钮封装样式
*/
Ext.define("Ext.EditBtn", {
extend : 'Ext.Button',
xtype : 'editBtn',
text : SystemConstant.modifyBtnText,
iconCls: "edit-button"
});
/**
* @author zengchao
* @date 2015-09-15
*
* 创建删除按钮封装样式
*/
Ext.define("Ext.DeleteBtn", {
extend : 'Ext.Button',
xtype : 'deleteBtn',
text : SystemConstant.deleteBtnText,
iconCls: "delete-button"
});<file_sep>/src/main/webapp/examples/framePage/FramePageWin.js
/**
* 定义常规数据信息form表单
*/
Ext.define("sshframe.examples.framePage.PlanUserGroupModel", {
extend : "Ext.data.Model",
fields : [{
name : 'id',
type : 'string'
},{
name : 'code', //计划员组编码
type : 'string'
}, {
name : 'description', //计划员组描述
type : 'string'
}]
});
sshframe.examples.framePage.PlanUserGroupStore = Ext.create('Ext.data.Store', {
model : 'sshframe.examples.framePage.PlanUserGroupModel',
pageSize: 5,
proxy : {
type : "format",
url :basePath + '/examples/getPlanUserGrouListByPage.action'
},
autoLoad:true
});
Ext.define("sshframe.examples.framePage.EquipmentClassModel", {
extend : "Ext.data.Model",
fields : [{
name : 'id',
type : 'string'
},{
name : 'code', //设备分类编码
type : 'string'
}, {
name : 'description', //设备分类描述
type : 'string'
}, {
name : 'isDisabled', //设备分类状态
type : 'string'
}]
});
sshframe.examples.framePage.EquipmentClassStore = Ext.create('Ext.data.Store', {
model : 'sshframe.examples.framePage.EquipmentClassModel',
pageSize: 5,
proxy : {
type : "format",
url :basePath + '/examples/getEquipmentClassList.action'
},
autoLoad:true
});
sshframe.examples.FramePageForm = Ext.create('Ext.form.Panel', {
items: [{
layout : 'form',
columnWidth : 0.5,
border : false,
items : [{
fieldLabel : '设备ID',
name : 'equipment.id',
xtype : 'hidden'
}, {
fieldLabel : '设备编码',
name : 'equipment.deviceCode',
xtype : 'textfield'
}, {
fieldLabel : '计划员组',
name : 'equipment.planUserGroup.id',
xtype : 'querySelectCombo',
store :sshframe.examples.framePage.PlanUserGroupStore,
valueField : 'id',
displayField : 'description'
},{
fieldLabel : '购置日期',
name : 'equipment.purchaseDate',
id:'purchaseDate',
maxDate:'startRunDate',
allowBlank : false,
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd'
},{
fieldLabel : '是否可用',
name : 'equipment.isDisabled',
xtype : 'textfield'
}
]
}, {
layout : 'form',
columnWidth : 0.5,
items : [{
fieldLabel : '设备名称',
name :'equipment.deviceName',
xtype : 'textfield'
}, {
fieldLabel : '设备分类',
name : 'equipment.equipmentClass.id',
xtype : 'querySelectGrid',
valueField : 'id',
displayField : 'description',
store :sshframe.examples.framePage.EquipmentClassStore,
pathByUrl :basePath + '/examples/getEquClassById.action',
columnsMap : {
"code":"分类编码",
"description":"分类描述",
"isDisabled":{ text: '设备状态', dataIndex: 'isDisabled', width: 60,renderer:function(val){
if(val==1){
return '<div class="color_green">启用</div>';
}else{
return '<div class="color_red">停用</div>';
}
}
}
}
},{
fieldLabel : '投运日期',
name : 'equipment.startRunDate',
id:'startRunDate',
minDate:'purchaseDate',
xtype : "dateTimePicker",
dateFmt : 'yyyy-MM-dd'
}]
}]
});
/**
* 生成添加修改页面
*/
sshframe.examples.FramePageWin= Ext.create("Ext.window.Window.BasicWindow", {
width : 600,
items : [sshframe.examples.FramePageForm]
});
/*sshframe.examples.FramePageWin= Ext.create("Ext.window.Window", {
width : 600,
items : [sshframe.examples.FramePageForm],
buttons : [ {
text : SystemConstant.saveBtnText,
handler : function() {
if (sshframe.examples.FramePageForm.isValid()) {
sshframe.examples.FramePageForm.submit({
success : function(form, action) {
if(action.result.success){
Ext.Msg.showTip(action.result.msg);
sshframe.examples.FramePageStore.loadPage(1);
sshframe.examples.FramePageWin.close();
} else{
Ext.Msg.showError(action.result.msg);
}
},
failure : function(form, action) {
Ext.Msg.showError(action.result.msg);
}
});
}
}
}, {
text : SystemConstant.closeBtnText,
handler : function() {
sshframe.examples.FramePageWin.close();
}
}]
});*/<file_sep>/src/main/webapp/examples/grid/rowNumberer.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../scripts/extjs/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="../shared/example.css" />
<link href="../../styles/icons.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../../scripts/extjs/ext-all.js"></script>
<script type="text/javascript" src="../../scripts/extjs/locale/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="../../scripts/extjs/ux/ExtjsExtend.js"></script>
<meta charset="UTF-8">
<title>表格-序号列</title>
</head>
<body>
<h1>序号列</h1>
<h2>扩展类:Ext.grid.RowNumberer</h2>
<h2>扩展方式:<a href="../right.html">override</a></h2>
<h2>扩展功能:</h2>
<p>1.不在需要编写任何控制配置代码,序号列会根据当前页最大的数据自动增加宽度</p>
<h2>用法:</h2>
<p>直接引用封装控件代码即可,不需额外编写代码。</p>
<pre class="code">
<script type="text/javascript" src="../../scripts/extjs/ux/ExtjsExtend.js"></script>
<br/>
在配置columns的时候可以写最简方式{xtype: "rownumberer"}
</pre>
<h2>示例截图:</h2>
<pre class="code"><img src='rowNumberer_1.bmp'/></pre>
<pre class="code"><img src='rowNumberer_2.bmp'/></pre>
</body>
</html><file_sep>/src/main/java/com/xx/vo/AddressVo.java
package com.xx.vo;
/**
* 地址vo
*
* @author wujialing
*/
public class AddressVo {
private String country ; //国家
private String city ; //城市
public AddressVo() {
}
public AddressVo(String country,String city) {
this.country = country ;
this.city = city ;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
<file_sep>/src/main/webapp/scripts/swfupload/UploadPanel.js
/**
* 多文件上传组件
* for extjs4.0
* @author caizhiping
* @since 2012-11-15
*/
Ext.define("sshFrame.multi.AttachModel",{
extend:"Ext.data.Model",
fields:[
{name: "id"},
{name: "attachId",mapping:function(v){
return v.id;
}},
{name: "attachName"},
{name: "attachType"},
{name: "fileSize"},
{name: 'percent',mapping:function(v){
return 100;
}},
{name: 'status',mapping:function(v){
return -4;
}}
]
});
sshFrame.multi.attachStore=Ext.create("Ext.data.Store", {
model:"sshFrame.multi.AttachModel",
proxy: {
type:"format",
url: basePath+"/attach/getAttachsByGroupId.action"
}
});
Ext.define('Ext.grid.UploadPanel',{
extend : 'Ext.grid.Panel',
alias : 'uploadpanel',
width : 700,
height : 300,
columns : [
{xtype: 'rownumberer'},
{text: '文件名', width: 100,dataIndex: 'attachName',renderer:function(vaule, metadata, record, rowIndex, columnIndex, store){
var attachId = record.get('attachId');
if (attachId) {
return '<a target="_blank" href="'+basePath+'/attach/downloadAttach.action?attachId='+attachId+'" title="下载" >'+vaule+'</a>';
}else{
return vaule;
}
}},
/*{text: '自定义文件名', width: 130,dataIndex: 'fileName',editor: {xtype: 'textfield'}},*/
{text: '类型', width: 70,dataIndex: 'attachType'},
{text: '大小', width: 70,dataIndex: 'fileSize',renderer:function(vaule, metadata, record, rowIndex, columnIndex, store){
return vaule;
}},
{text: '进度', width: 130,dataIndex: 'percent',renderer:function(v){
if(isNaN(v)){
v=100;
}
var stml =
'<div>'+
'<div style="float:left;background:#FFCC66;width:'+v+'%;height:8px;"><div></div></div>'+
'</div>'+
'</div>';
return stml;
}},
{text: '状态', width: 80,dataIndex: 'status',renderer:function(v){
var status;
if(v==-1){
status = "等待上传";
}else if(v==-2){
status = "上传中...";
}else if(v==-3){
status = "<div style='color:red;'>上传失败</div>";
}else if(v==-4){
status = "上传成功";
}else if(v==-5){
status = "停止上传";
}
return status;
}}
],
listeners:{
afterrender:function(comm,eOpts){
var proxy = this.getStore().getProxy();
proxy.setExtraParam("attachGroupId",comm.attachGroupId);
this.getStore().load();
}
},
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
],
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : sshFrame.multi.attachStore,
onUploadSuccess:function(){},//附件回调,如果没有groupId,传groupid给业务进行处理
addFileBtnText : '选择文件',
uploadBtnText : '上传',
removeBtnText : '删除附件',
cancelBtnText : '取消上传',
downloadBtnText : '批量下载',
debug : false,
file_size_limit : 100,//MB
file_types : '*.*',
file_types_description : 'All Files',
file_upload_limit : 50,
file_queue_limit : 0,
post_params : {},
attachGroupId:'',
upload_url : basePath+'test.do',
flash_url : basePath+"/scripts/swfupload/swfupload.swf",
flash9_url : basePath+"/scripts/swfupload/swfupload_fp9.swf",
initComponent : function(){
this.dockedItems = [{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype:'button',
itemId: 'addFileBtn',
iconCls : 'add',
id : '_btn_for_swf_',
text : this.addFileBtnText
},{ xtype: 'tbseparator' },{
xtype : 'button',
itemId : 'uploadBtn',
iconCls : 'up',
text : this.uploadBtnText,
scope : this,
handler : this.onUpload
},{ xtype: 'tbseparator' },{
xtype : 'button',
itemId : 'removeBtn',
iconCls : 'trash',
text : this.removeBtnText,
disabled:true,
disabledExpr : "$selectedRows == 0",
scope : this,
handler : this.onRemove
},{ xtype: 'tbseparator' },{
xtype : 'button',
itemId : 'cancelBtn',
iconCls : 'cancel',
disabled : true,
text : this.cancelBtnText,
scope : this,
handler : this.onCancelUpload
},
{ xtype: 'tbseparator' },{
xtype : 'button',
itemId : 'downloadBtn',
iconCls : 'download-button',
text : this.downloadBtnText,
disabled:true,
disabledExpr : "$selectedRows == 0 || $attachId == ''",
scope : this,
handler : this.downLoadZip
}
]
}];
this.callParent();
this.down('button[itemId=addFileBtn]').on({
afterrender : function(btn){
var config = this.getSWFConfig(btn);
this.swfupload = new SWFUpload(config);
Ext.get(this.swfupload.movieName).setStyle({
position : 'absolute',
top : 0,
left : -2
});
},
scope : this,
buffer:300
});
},
getSWFConfig : function(btn){
var me = this;
var placeHolderId = Ext.id();
var em = btn.getEl().child('em');
if(em==null){
em = Ext.get(btn.getId()+'-btnWrap');
}
em.setStyle({
position : 'relative',
display : 'block'
});
em.createChild({
tag : 'div',
id : placeHolderId
});
return {
debug: me.debug,
flash_url : me.flash_url,
flash9_url : me.flash9_url,
upload_url: me.upload_url,
post_params: me.post_params||{savePath:'upload\\'},
file_size_limit : (me.file_size_limit*1024),
file_types : me.file_types,
file_types_description : me.file_types_description,
file_upload_limit : me.file_upload_limit,
file_queue_limit : me.file_queue_limit,
button_width: em.getWidth(),
button_height: em.getHeight(),
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
button_placeholder_id: placeHolderId,
custom_settings : {
scope_handler : me
},
swfupload_preload_handler : me.swfupload_preload_handler,
file_queue_error_handler : me.file_queue_error_handler,
swfupload_load_failed_handler : me.swfupload_load_failed_handler,
upload_start_handler : me.upload_start_handler,
upload_progress_handler : me.upload_progress_handler,
upload_error_handler : me.upload_error_handler,
upload_success_handler : me.upload_success_handler,
upload_complete_handler : me.upload_complete_handler,
file_queued_handler : me.file_queued_handler/*,
file_dialog_complete_handler : me.file_dialog_complete_handler*/,
file_post_name: me.file_post_name,
attachGroupId: me.attachGroupId
};
},
swfupload_preload_handler : function(){
if (!this.support.loading) {
Ext.Msg.show({
title : '提示',
msg : '浏览器Flash Player版本太低,不能使用该上传功能!',
width : 250,
icon : Ext.Msg.ERROR,
buttons :Ext.Msg.OK
});
return false;
}
},
file_queue_error_handler : function(file, errorCode, message){
switch(errorCode){
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED : msg('上传文件列表数量超限,不能选择!');
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT : msg('文件大小超过限制, 不能选择!');
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE : msg('该文件大小为0,不能选择!');
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE : msg('该文件类型不允许上传!');
break;
}
function msg(info){
Ext.Msg.show({
title : '提示',
msg : info,
width : 250,
icon : Ext.Msg.WARNING,
buttons :Ext.Msg.OK
});
}
},
swfupload_load_failed_handler : function(){
Ext.Msg.show({
title : '提示',
msg : 'SWFUpload加载失败!',
width : 180,
icon : Ext.Msg.ERROR,
buttons :Ext.Msg.OK
});
},
upload_start_handler : function(file){
var me = this.settings.custom_settings.scope_handler;
me.down('#cancelBtn').setDisabled(false);
var rec = me.store.getById(file.id);
var params = {'attachGroupId':me.attachGroupId,'attachType':file.type};
this.setPostParams(params);
//this.setFilePostName(encodeURIComponent(rec.get('fileName')));
},
upload_progress_handler : function(file, bytesLoaded, bytesTotal){
var me = this.settings.custom_settings.scope_handler;
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
percent = percent == 100? 99 : percent;
var rec = me.store.getById(file.id);
rec.set('percent', percent);
rec.set('status', file.filestatus);
rec.commit();
},
upload_error_handler : function(file, errorCode, message){
var me = this.settings.custom_settings.scope_handler;
var rec = me.store.getById(file.id);
rec.set('percent', 0);
rec.set('status', file.filestatus);
rec.commit();
if (this.getStats().files_queued > 0 && this.uploadStopped == false) {
this.startUpload();
}else{
me.showBtn(me,true);
}
},
upload_success_handler : function(file, serverData, responseReceived){
var me = this.settings.custom_settings.scope_handler;
var rec = me.store.getById(file.id);
var data = Ext.decode(serverData);
if(!data.success || data.success=='false')
{
// file.filestatus = -3;
// this.queueEvent("upload_error_handler", [file, SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED, '上传文件失败']);
// return;
rec.set('percent', 0);
rec.set('status', SWFUpload.FILE_STATUS.ERROR);
}else{
rec.set('attachId', data.attachId);
rec.set('percent', 100);
rec.set('status', file.filestatus);
}
rec.commit();
if (this.getStats().files_queued > 0 && this.uploadStopped == false) {
this.startUpload();
}else{
me.showBtn(me,true);
}
//设置回调
if(!me.attachGroupId && data.attachGroupId){
me.onUploadSuccess(data.attachGroupId);
me.attachGroupId = data.attachGroupId ;
}
},
upload_complete_handler : function(file){
},
file_queued_handler : function(file){
var me = this.settings.custom_settings.scope_handler;
me.store.add({
id : file.id,
attachName : file.name,
fileSize : Ext.util.Format.fileSize(file.size),
attachType : file.type,
status : file.filestatus,
percent : 0
});
},
onUpload : function(){
if (this.swfupload&&this.store.getCount()>0) {
if (this.swfupload.getStats().files_queued > 0) {
this.showBtn(this,false);
this.swfupload.uploadStopped = false;
this.swfupload.startUpload();
}
}
},
showBtn : function(me,bl){
me.down('#addFileBtn').setDisabled(!bl);
me.down('#uploadBtn').setDisabled(!bl);
me.down('#cancelBtn').setDisabled(bl);
},
onRemove : function(){
var ds = this.getStore();
var rows = this.getSelectionModel().getSelection();
var attachIds='';
for(var i=0;i<rows.length;i++){
var file_id = rows[i].get('id');
var attachId = rows[i].get('attachId');
if(attachId!=null&&attachId!=''){
attachIds+=attachId+',';
}
ds.remove(rows[i]);
this.swfupload.cancelUpload(file_id,false);
}
if(attachIds.length>0){
attachIds=attachIds.substring(0,attachIds.length-1);
Ext.Ajax.request({
url : basePath+'/attach/deleteAttachs.action',
async:false,
params : {attachIds:attachIds},
success : function(res, options) {
}
});
}
this.swfupload.uploadStopped = false;
},
onCancelUpload : function(){
if (this.swfupload) {
this.swfupload.uploadStopped = true;
this.swfupload.stopUpload();
this.showBtn(this,true);
}
},
downLoadZip : function(){
var rows = this.getSelectionModel().getSelection();
var attachIds="";
if(rows.length==1){
attachIds = rows[0].get('attachId');
}else{
for(var i=0;i<rows.length-1;i++){
attachIds += rows[i].get('attachId')+',';
}
attachIds += rows[rows.length-1].get('attachId');
}
window.open(basePath+"/attach/downLoadZip.action?attachIds="+attachIds,"下载文件")
}
});<file_sep>/src/main/webapp/scripts/resource/ResourceStore.js
/**
* 资源类型 model
* */
Ext.define('resourceTypeModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'id'},
{name: 'dictionaryName'},
{name: 'dictionaryCode'}
]
});
/**
* 资源类型 store
* */
var parentResourceTypeStore = Ext.create('Ext.data.Store', {
model: 'resourceTypeModel',
proxy: {
type: 'ajax',
url: basePath + '/dict/getDictListByTypeCode.action',
extraParams:{dictTypeCode:"RESOURCETYPE"},
reader: {
type: 'json'
}
},
autoLoad: false,
listeners:{
load:function(storeObj,records){
if(records.length>0){
Ext.getCmp("parentResourceId").setValue(records[0].get("dictionaryCode"));
}
}
}
});<file_sep>/src/main/webapp/scripts/extjs/ux/data/FailureProcess.js
Ext.define('sshframe.ux.data.FailureProcess', {
singleton: true,
alternateClassName: 'sshframe.FailureProcess',
requires: [
'Ext.Msg'
],
Ajax: function (response, options) {
if (response.status == 404) {
Ext.Msg.alert("错误信息", "错误的请求地址。");
} else if (response.status == 500) {
Ext.Msg.alert("错误信息", "服务器内部错误。");
} else {
Ext.Msg.alert("错误信息", Ext.String.format('错误代码:{0}<br\>响应:{1}', response.status, response.responseText));
}
},
Proxy: function (proxy, response, options, epots) {
var status = response.status;
if ((status >= 200 && status < 300) || status == 304) {
Ext.Msg.alert("信息", options.error);
} else {
SimpleCMS.FailureProcess.Ajax(response, options);
}
},
Form: function (form, action) {
var status = action.response.status;
if ((status >= 200 && status < 300) || status == 304) {
if (action.result.errors === undefined) {
Ext.Msg.alert("信息", action.result.msg);
}
} else {
SimpleCMS.FailureProcess.Ajax(action.response);
}
}
});
<file_sep>/src/main/webapp/examples/attach/attachGridDemo.js
/**
* 附件组示例
* @author hedjaojun
* @date 2015-07-01
*/
Ext.onReady(function() {
//定义表格grid
var attachGrid = Ext.create("Ext.grid.AttachPanel",{
renderTo: 'attach-grid-example',
attachGroupId:'', //修改时,设置附件组ID的值。添加新附件组时,设置attachGroupId为0或不设置。默认值为0
allowFileType:["gif","jpg","jpeg","bmp","png","rar","zip","txt","doc","docx","xls","xlsx","ppt","pdf"],
maxFileCount:6, // 最多上传文件数。
maxFileSize:10*1024*1024,//文件大小限制 此处为10M
savePath:'',//文件存放目录 默认为 C:\\uploadFile\\$date{yyyy}\\$date{MM} $date{yyyy-MM}表示当前日期的月份
showAddButton:true, // 是否显示"添加"按钮,默认值为"false"
showDelButton:true, // 是否显示"删除"按钮,默认值为"false"
showDownloadButton:true, // 是否显示"批量下载"按钮,默认值为"true"
//上传附件成功回调函数,用于设置业务表与附件组ID关联。此示例中将新附件组ID添加到页面中附件ID下拉选择框中。
onUploadSuccess:function(newAttachGroupId){
var groupIdDom = Ext.get('attachGroupId');
//如果下拉选择框中无返回的 附件组ID: newAttachGroupId,则添加到下拉框。
if(!groupIdDom.child('option[value="'+newAttachGroupId+'"]')){
groupIdDom.createChild({
tag : 'option',
value : newAttachGroupId,
selected:"selected",
html:newAttachGroupId
});
Ext.Msg.showInfo("新附件组 ID为: "+newAttachGroupId);
}
}
});
/**
* 设置"加载"按钮点击事件。重新选择附件组ID下的全部附件。
*/
Ext.get('loadButton').on('click',function(event,target){
var groupId = Ext.get('attachGroupId').getValue();
//为附件组表格设置新的附件组ID,并刷新列表。
attachGrid.setAttachGroupId(groupId);
});
})<file_sep>/src/main/webapp/scripts/extjs/ux/AttachGrid.js
/**
* 附件组控件扩展EXTJS表格控件,实现附件列表显示、添加、删除和批量下载附件的功能。
* 同时实现过虑文件大小、文件类型、最多上文件数和设置保存目录功能
* @author hedjaojun
* @date 2015-05-28
*/
/**
* 建立model对象
*/
Ext.define("sshframe.attach.attachModel",{
extend:"Ext.data.Model",
fields:[
{name:'attachId',mapping:'attachId'},
{name:'attachName',mapping:'attachName'},
{name:'attachUrl',mapping:'attachUrl'},
{name:'downloadTime',mapping:'downloadTime'}
]
});
//建立数据Store
sshframe.attach.attachStore=Ext.create("Ext.data.Store", {
model:"sshframe.attach.attachModel",
proxy: {
type:"format",
url: basePath+"/attach/getAttachsByGroupId.action"
}
});
Ext.define("Ext.grid.AttachPanel",{
extend:"Ext.grid.Panel",
title:'附件',
attachGroupId:'', // 修改时,设置附件组ID的值。添加新附件组时,设置attachGroupId为0或不设置。默认值为0
showAddButton:false, // 是否显示"添加"按钮,默认值为"false"
showDelButton:false, // 是否显示"删除"按钮,默认值为"false"
showDownloadButton:true, // 是否显示"批量下载"按钮,默认值为"true"
allowFileType:["gif","jpg","jpeg","bmp","png","rar","zip","txt","doc","docx","xls","xlsx","ppt","pdf"],
maxFileCount:0, // 最多上传文件数。为0时不限制,默认为0
maxFileSize:0,//文件大小限制,
savePath:'',//文件存放目录 默认为 C:\\uploadFile\\$date{yyyy}\\$date{MM} 根据当前日期生成目录,如:C:\\uploadFile\\2015\\07
existFileCount:0, //已成功上传的文件数
onUploadSuccess:function(){},
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : sshframe.attach.attachStore,
initComponent: function () {
var me = this;
var topBar = ['->'];
if(me.showAddButton){
topBar.push({
buttonOnly: true,hideLabel: true,name: 'uploadAttach',
text: '添加', iconCls: 'add-button',
handler: function(fb, v){
me.addAttachWin.show();
}
});
}
if(me.showDelButton){
topBar.push({
iconCls : 'delete-button', text : '删除',
disabled : true, disabledExpr : "$selectedRows == 0",
handler : function(){
me.deleteAttachs();
}
});
}
if(me.showDownloadButton){
topBar.push({
iconCls : 'download-button', text : '批量下载',
disabled:true, disabledExpr : "$selectedRows == 0",
handler : function(){
me.downLoadZip();
}
});
}
if(topBar.length > 1){
me.tbar = topBar;
}
me.columns = [{
xtype : "rownumberer",text : "序号",width : 60,align : "center"
},{
text : '文件名称',dataIndex : 'attachName',
renderer : function (data, metadata, record, rowIndex, columnIndex, store){
return '<a target="_blank" href="'+basePath+'/attach/downloadAttach.action?attachId='+record.get('attachId')+'" title="下载" >'
+record.get('attachName')+'</a>';
}
}];
me.callParent(arguments);
me.attachFormPanel = Ext.create('Ext.form.Panel', {
width: 500,
border:false,
bodyPadding: '10 10 0',
defaults: {
xtype: 'textfield',
anchor: '100%',
labelWidth: 50
},
items: [{
name:'attachGroupId',
value:'',
hidden:true
},{
name:'maximumSize',
value:me.maxFileSize,
hidden:true
},{
name:'savePath',
value:me.savePath,
hidden:true
},{
xtype: 'filefield',
emptyText: '选择文件',
fieldLabel: '文件',
allowBlank : false,
name: 'uploadAttach',
buttonText: '',
buttonConfig: {
iconCls: 'add-button'
},
listeners: {
'change': function(fb, v){
if(v){
me.addAttach(fb, v);
}
}
}
}]
});
//上传附件窗口
me.addAttachWin = new Ext.Window({
title:'添加',
closable:true,
width:400,
closeAction:'hide',
height:100,
modal:true,
resizable:false,
layout :"fit",
items : [
me.attachFormPanel
]
});
/**
* 设置grid 和 form 的 attachGroupId参数
*/
me.setAttachGroupId = function(attachGroupId){
var form = me.attachFormPanel.getForm();
form.findField('attachGroupId').setValue(attachGroupId);
sshframe.attach.attachStore.getProxy().setExtraParam("attachGroupId", attachGroupId);
sshframe.attach.attachStore.load(function(records, operation, success) {
me.existFileCount = records.length;
});
}
me.setAttachGroupId(me.attachGroupId);
/**
* 调用后台上传附件
*/
me.addAttach = function(fb, v){
var form = me.attachFormPanel.getForm();
if(me.allowFileType&& me.allowFileType.length && !RegExp("\.(" + this.allowFileType.join("|") + ")$", "i").test(v)){
Ext.Msg.showError("支持的文件格式为:"+this.allowFileType.join(",")+"。");
return;
}
if(this.maxFileCount && this.existFileCount >= this.maxFileCount){
bCheck = false;
Ext.Msg.showError('最多只能上传'+this.maxFileCount+'个文件!当前已有'+this.existFileCount+'个!');
return;
}
if(form.isValid() && v){
form.submit({
url: basePath+"/attach/addAttach.action",
success: function(fp, o) {
me.setAttachGroupId(o.result.attachGroupId)
Ext.Msg.showTip('添加成功。');
me.addAttachWin.close();
me.onUploadSuccess(o.result.attachGroupId);
},
failure: function (form, action) {
Ext.Msg.showError(action.result.result);
}
});
}
}
/**
* 调用后台批量下载附件
*/
me.downLoadZip = function(){
var rows = me.getSelectionModel().getSelection();
var attachIds="";
if(rows.length==1){
attachIds = rows[0].get('attachId');
}else{
for(var i=0;i<rows.length-1;i++){
attachIds += rows[i].get('attachId')+',';
}
attachIds += rows[rows.length-1].get('attachId');
}
window.open(basePath+"/attach/downLoadZip.action?attachIds="+attachIds,"下载文件")
}
/**
* 调用后台批量删除附件
*/
me.deleteAttachs = function(){
var rows = me.getSelectionModel().getSelection();
Ext.Msg.confirm(SystemConstant.alertTitle,"确认删除这" + rows.length + "条记录吗?",function(btn){
if(btn=='yes'){
var attachIds = "";
if(rows.length==1){
attachIds = rows[0].get('attachId');
}else{
for(var i=0;i<rows.length-1;i++){
attachIds += rows[i].get('attachId')+',';
}
attachIds += rows[rows.length-1].get('attachId');
}
Ext.Ajax.request({
url: basePath+'/attach/deleteAttachs.action',
params: {
attachIds: attachIds
},
success: function(response, opts) {
var result = Ext.decode(response.responseText);
var flag = result.success;
if(flag){
sshframe.attach.attachStore.load(function(records, operation, success) {
me.existFileCount = records.length;
});
Ext.Msg.showTip('删除成功。')
}else{
Ext.Msg.showError(result.msg)
}
}
});
}
});
}
}
});<file_sep>/src/main/webapp/examples/attachMulti/attachGridDemo.js
/**
* 附件组示例
* @author wujialing
* @date 2016-01-28
*/
Ext.onReady(function() {
var attachPanel = Ext.create('Ext.grid.UploadPanel',{
renderTo: 'attach-grid-example-multi',
addFileBtnText : '选择文件',
uploadBtnText : '上传',
removeBtnText : '删除附件',
cancelBtnText : '取消上传',
file_post_name:'uploadAttach',
file_size_limit : 100,//MB
file_types:'*.*',//限制格式 如“txt;doc,docx”,用英文分号隔开
upload_url : basePath+'/attach/addAttach.action',
attachGroupId:'',
onUploadSuccess:function(newAttachGroupId){
var groupIdDom = Ext.get('attachGroupId');
//如果下拉选择框中无返回的 附件组ID: newAttachGroupId,则添加到下拉框。
if(!groupIdDom.child('option[value="'+newAttachGroupId+'"]')){
groupIdDom.createChild({
tag : 'option',
value : newAttachGroupId,
selected:"selected",
html:newAttachGroupId
});
Ext.Msg.showInfo("新附件组 ID为: "+newAttachGroupId);
}
}
});
/**
* 设置"加载"按钮点击事件。重新选择附件组ID下的全部附件。
*/
Ext.get('loadButton').on('click',function(event,target){
var groupId = Ext.get('attachGroupId').getValue();
//为附件组表格设置新的附件组ID,并刷新列表。
attachPanel.getStore().getProxy().setExtraParam("attachGroupId", groupId)
attachPanel.getStore().load();
});
})<file_sep>/src/main/webapp/scripts/org/OrgStore.js
Ext.define('orgTypeModel', {
extend : 'Ext.data.Model',
fields : [
{name: 'id'},
{name: 'dictionaryName'},
{name: 'dictionaryCode'}
]
});
var orgTypeStore = Ext.create('Ext.data.Store', {
model: 'orgTypeModel',
proxy: {
type: 'ajax',
url: basePath+'/dict/getDictListByTypeCode.action',
extraParams:{dictTypeCode:"ORGTYPE"},
reader: {
type: 'json'
}
},
autoLoad: true
});<file_sep>/src/main/webapp/scripts/org/OrgWin.js
var orgForm=Ext.create("Ext.form.Panel", {
layout: 'form',
bodyStyle :'padding:15px 10px 0 0',
border: false,
labelAlign: 'right',
fieldDefaults: {
labelWidth: 60,
labelAlign: 'right'
},
defaults: {
anchor: '60%'
},
defaultType: 'textfield',
items: [{
name : 'org.id',
hidden:true
},{
name: 'hiddenOrgCode',
hidden:true
},{
name : 'org.organization.id',
hidden:true
},{
fieldLabel: '上级',
name: 'org.organization.orgName',
disabled:true,
width: 100
},{
xtype: 'combobox',
fieldLabel: '类型',
id:'addOrgSelectionId',
name: 'org.orgType',
store: orgTypeStore,
valueField: 'dictionaryCode',
displayField: 'dictionaryName',
editable:false,
queryMode: 'remote',
width: 100,
allowBlank: false
},{
fieldLabel: '名称',
name: 'org.orgName',
vtype:'filterHtml',
width: 100,
maxLength:20,
allowBlank: false
/*validator: function(value){
var returnObj = null;
$.ajax({
url : basePath+'/org/validateOrgProperties.action',
data:{
key:'0',
value:value,
parentOrgId:selectNode.raw.nodeId
},
cache : false,
async : false,
type : "POST",
dataType : 'json',
success : function (result){
if(!result.valid){
returnObj = result.reason;
}else{
returnObj = true;
}
}
});
return returnObj;
}
*/
},{
fieldLabel: '编码',
vtype:'filterHtml',
name: 'org.orgCode',
width: 100,
maxLength:30,
allowBlank: false,
validator: function(value){
var returnObj = null;
$.ajax({
url : basePath+'/org/validateOrgProperties.action',
data:{key:'1',value:value,parentOrgId:selectNode.raw.nodeId},
cache : false,
async : false,
type : "POST",
dataType : 'json',
success : function (result){
if(!result.valid){
returnObj = result.reason;
}else{
returnObj = true;
}
}
});
return returnObj;
}
},{
fieldLabel: '排序',
name: 'org.disOrder',
width: 100,
xtype: 'numberfield',
minValue:0,
maxValue:999
}]
});
var orgWin = Ext.create("Ext.window.Window", {
height : 250,
width : 380,
items : [orgForm],
buttons : [ {
text : SystemConstant.yesBtnText,
handler : function() {
if (orgForm.form.isValid()) {
orgForm.form.submit({
success : function(form, action) {
treePanel.getStore().reload({
node:treePanel.getRootNode(),
callback: function () {
}
});
orgStore.loadPage(1);
orgWin.close();
Ext.Msg.showTip(action.result.msg);
},
failure : function(form, action) {
Ext.Msg.showError(action.result.msg);
}
});
}
}
}, {
text : SystemConstant.closeBtnText,
handler : function() {
orgWin.close();
}
} ]
});
<file_sep>/src/main/webapp/scripts/resource/ResourceGrid.js
/**
* 定义资源Model
* */
Ext.define("resourceModel",{
extend:"Ext.data.Model",
fields:[
{name: "id"},
{name: "resourceName"},
{name: "code"},
{name: "resourceTypeId"},
{name: "resourceTypeName"},
{name: "resourceTypeValue"},
{name: "resourceTypeDictCode"},
{name: "href"},
{name: "hrefTarget"},
{name: "iconUrl"},
{name: "createDate"},
{name: "parentResourceId"},
{name: "parentResourceName"},
{name: "remarks"}
]
});
/**
* 定义资源数据源
* */
var resourceStore=Ext.create("Ext.data.Store", {
model:"resourceModel",
proxy : {
type : "format",
url : basePath + "/resource/getResourceList.action"
}
});
/**
* 定义资源grid
*/
var resourceGrid = Ext.create("Ext.grid.Panel", {
title : '资源管理',
region : "center",
bbar : Ext.create("Ext.PagingToolbar", {
store : resourceStore
}),
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : resourceStore,
columns : [
{xtype: "rownumberer",width:60,text:'序号',align:"center"},
{header: "id",dataIndex: "id",hidden: true},
{header: "parentResId",dataIndex: "parentResourceId",hidden: true},
{header: "上级",width: 200,dataIndex: "parentResourceName"},
{header: "名称",width: 200,dataIndex: "resourceName"},
{header: "类型",width: 200,dataIndex: "resourceTypeName",},
{header: "编码",width: 200,dataIndex: "code"},
{header: "URL",width: 200,dataIndex: "href"},
{header: "描述",width: 200,dataIndex: "remarks"}
],
tbar : [ '->', {
xtype : 'button',
text : SystemConstant.addNextBtnText,
iconCls : 'add-button',
id : 'addResource',
handler : function() {
addResource();
}
}, {
xtype : 'button',
id : 'updateResource',
text : SystemConstant.modifyBtnText,
disabledExpr : "$selectedRows != 1",// $selected 表示选中的记录数不等于1
disabled : true,
iconCls : 'edit-button',
handler : function() {
updateResource();
}
}, {
xtype : 'button',
text : SystemConstant.deleteBtnText,
disabled : true,
disabledExpr : "$selectedRows == 0",
iconCls : 'delete-button',
handler : function() {
deleteResource();
}
} ]
});
/**
* 添加资源方法
*/
var addResource = function() {
parentResourceWin.setTitle(SystemConstant.addBtnText);
var basicForm = parentResourceWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/resource/addResource.action';
parentResourceTypeStore.load();
basicForm.findField('resourceCode').setDisabled(false);
if(selectNode.raw.nodeId!=0){
basicForm.findField('resource.resource.id').setValue(selectNode.raw.nodeId);
basicForm.findField('resource.resource.resourceName').setValue(selectNode.raw.text);
basicForm.findField('parentResourceName').setVisible(true);
}else{
basicForm.findField('parentResourceName').setVisible(false);
}
parentResourceWin.show();
};
/**
* 修改资源方法
* */
var updateResource = function() {
parentResourceWin.setTitle(SystemConstant.modifyBtnText);
var row = resourceGrid.getSelectionModel().getSelection()
var resourceId = row[0].data.id;
var basicForm = parentResourceWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/resource/updateResource.action';
parentResourceTypeStore.load();
basicForm.findField('resource.id').setValue(resourceId);
basicForm.load({
url : basePath + '/resource/getResourceById.action',
params : {
resourceId : resourceId
}
});
if(row[0].data.parentResourceId!=0){
basicForm.findField('parentResourceName').setVisible(true);
}else{
basicForm.findField('parentResourceName').setVisible(false);
}
basicForm.findField('resourceCode').setDisabled(true);
parentResourceWin.show();
};
/**
* 删除资源方法
* */
var deleteResource = function(){
var rows = resourceGrid.getSelectionModel().getSelection();
var ids = "";
for (var i = 0; i < rows.length; i++) {
ids += (rows[i].data.id + ",");
}
ids = ids.substring(0, ids.length - 1);
Ext.Ajax.request({
url : basePath+'/resource/isCanDelete.action',
params : {resourceIds: ids},
success : function(res, options) {
var data = Ext.decode(res.responseText);
if(data.success){
Ext.Msg.confirm(SystemConstant.alertTitle, "确认删除所选资源吗?", function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : basePath + '/resource/deleteResource.action',
params : {
resourceIds : ids
},
success : function(res, options) {
var data = Ext.decode(res.responseText);
if (data.success) {
treePanel.getStore().reload({
node:treePanel.getRootNode(),
callback: function () {
}
});
resourceStore.loadPage(1);
Ext.Msg.showTip(data.msg);
} else {
Ext.Msg.showError(data.msg);
}
},
failure : sshframe.FailureProcess.Ajax
});
}
});
}else{
Ext.MessageBox.show({
title: SystemConstant.alertTitle,
msg: data.msg,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.INFO
});
return false;
}
}
});
};
<file_sep>/src/main/webapp/examples/grid/RoleGrid.js
/**
* 角色管理的列表功能,包含功能有 列表、添加、修改和删除功能。
* @date 20150616
* @author hedaojun
*/
/**
* 定义角色Model
*/
Ext.define("sshframe.role.roleModel", {
extend : "Ext.data.Model",
fields : [{
name : "roleId",
type : "int"
}, {
name : "roleName"
}, {
name : "roleCode"
}, {
name : "description"
} ]
});
/**
* 定义Store
*/
sshframe.role.RoleStore = Ext.create('Ext.data.Store', {
model : 'sshframe.role.roleModel',
proxy : {
type : "format",
url : "roleListData.json"
},
autoLoad:true
})
Ext.onReady(function() {
Ext.QuickTips.init();
/**
* 定义Grid
*/
sshframe.role.RoleGrid = Ext.create("Ext.grid.Panel", {
title : '角色管理',
renderTo: 'grid-example',
region : "center",
resizable:{
handles: 's' //只向下(南:south)拖动改变列表的高度
},
bbar : Ext.create("Ext.PagingToolbar", {
store : sshframe.role.RoleStore
}),
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : sshframe.role.RoleStore,
columns : [ {
xtype : "rownumberer",
text : '序号',
width : 60,
align : "center"
}, {
header : "roleId",
dataIndex : "id",
hidden : true
}, {
header : "角色名称",
dataIndex : "roleName"
}, {
header : "角色编码",
dataIndex : "roleCode"
}, {
header : "描述",
dataIndex : "description"
} ],
tbar : [ '角色名称', {
xtype : 'textfield',
stripCharsRe : /^\s+|\s+$/g, // 禁止输入空格
id : 'inputRoleName'
}, {
text : "查询",
iconCls : "search-button",
handler : function(button) {
sshframe.role.RoleStore.getProxy().setExtraParam("roleName", button.prev().getValue());
sshframe.role.RoleStore.loadPage(1);
alert('查询条件为:'+button.prev().getValue());
}
}, '->', {
xtype : 'button',
text : '添加',
iconCls : 'add-button',
handler : function() {
alert('添加');
}
}, {
xtype : 'button',
text : '修改',
disabledExpr : "$selectedRows != 1 || $roleCode=='admin'",// $selected 表示选中的记录数不等于1
disabled : true,
iconCls : 'edit-button',
handler : function() {
alert('修改')
}
}, {
xtype : 'button',
text : '删除',
disabled : true,
disabledExpr : "$selectedRows == 0 || $roleCode=='admin'",
iconCls : 'delete-button',
handler : function() {
alert('删除');
}
} ]
})
});
<file_sep>/src/main/webapp/scripts/common/SystemConstant.js
var SystemConstant = {
companyName:"大庆金桥信息技术工程有限公司成都分公司",
projectName:"公司架构系统",
displayMsg: "第 {0} - {1} 条,共 {2} 条",
emptyMsg: "没有数据",
commonSize: 99,//分页条数
alertTitle:"系统提示",
deleteMsg:"确认删除这些数据吗?" ,
delSuccess:"删除成功",
addSuccess:"添加成功",
editSuccess:"修改成功",
blankText:"该项不能为空!" ,
regexText:"内容不符合规范!" ,
ajaxFailure:"系统繁忙,请稍后再试!",
delFailure:"删除失败,请联系管理员",
delSuccess:"删除成功",
deleteMsgStart:"确认删除这",
deleteMsgEnd:"条数据吗?",
addBtnText:"添加",
deleteBtnText:"删除",
modifyBtnText:"修改",
updateBtnText:"更新",
searchBtnText:"查询",
synchronizeBtnText:"同步",
resetBtnText:"重置",
uploadBtnText:"上传",
importBtnText:"导入",
exportBtnText:"导出",
saveBtnText:"确定",
allocationOperaText:"分配",
closeBtnText:"关闭",
yesBtnText:"确定",
cancelBtnText:"取消",
resource_user:"用户",
resource_role:"角色",
resource_org:"组织",
resource_res:"资源",
resource_dict:"字典",
resource_user_role:"用户角色关系",
resource_role_resource:"角色资源关系",
resource_user_org:"用户组织关系",
importUserInfoBtnText:"用户导入",
exportUserInfoBtnText:"用户导出",
downloadUserInfoImportTemplateBtnText:"下载用户导入模板",
importRoleInfoBtnText:"角色导入",
exportRoleInfoBtnText:"角色导出",
downloadRoleInfoImportTemplateBtnText:"下载角色导入模板",
importUserRoleInfoBtnText:"用户角色关系导入",
exportUserRoleInfoBtnText:"用户角色关系导出",
downloadUserRoleInfoImportTemplateBtnText:"下载用户角色关系导入模板",
importResourceInfoBtnText:"资源导入",
exportResourceInfoBtnText:"资源导出",
downloadResourceInfoImportTemplateBtnText:"下载用户角色关系导入模板",
importRoleResourceInfoBtnText:"角色与资源关系导入",
exportRoleResourceInfoBtnText:"角色与资源关系导出",
downloadRoleResourceInfoImportTemplateBtnText:"下载角色与资源关系导入模板",
processTemplate:'模板',
process:'流程',
gender_male:"男",
gender_female:"女",
basicInfo:"基本信息",
please:'请',
chooseOneInfo:'请选择一条数据',
viewInfo:'查看',
manageInfo:"管理",
onlyOneInfo:"只能选择一条数据",
notApproveInfo:"未找到相关审核记录!",
expandInfo:"扩展信息",
userIsExist:"用户不存在!",
userDisable:"用户已禁用!",
userResourcesFailure:"获取用户资源失败!",
theSystemIsBusy:"系统繁忙,请稍后再试!",
expandInfo:"扩展信息",
passwordMinLength:6, //用户密码最小长度
logoutError:"注销错误,请联系管理员",
startTime:"开始时间",
endTime:"结束时间",
addParentBtnText:"添加根节点",
addNextBtnText:"添加下级资源",
addNextOrgBtnText:"添加下级组织",
resetPwd:"<PASSWORD>",
updatePwd:"<PASSWORD>",
defaultPassword:'<PASSWORD>'
};
var basePath=(function(){
var href=window.location.href;
var host=window.location.host;
var index = href.indexOf(host)+host.length+1; //host结束位置的索引(包含/)
return href.substring(0,href.indexOf('/',index));
})(window);<file_sep>/src/main/java/com/xx/action/FreeMarkerTestAction.java
package com.xx.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xx.vo.AddressVo;
/**
* FreeMarker结合Struts2测试
*
* @author wujialing
*/
public class FreeMarkerTestAction extends ActionSupport {
/**
* 序列号
*/
private static final long serialVersionUID = 1L;
/**
* 测试页面 hello world!
*
* @return
*/
public String test(){
Map<String, Object> map = ActionContext.getContext().getSession();
//字符串显示到页面
map.put("user", "何东");
//用户页面if判断
map.put("random", new Random().nextInt(100));
//列表在页面进行遍历
List<AddressVo> list = new ArrayList<AddressVo>();
list.add(new AddressVo("中国","北京"));
list.add(new AddressVo("中国","上海"));
list.add(new AddressVo("美国","纽约"));
map.put("lst", list);
return "success";
}
}
<file_sep>/src/main/webapp/scripts/org/OrgGrid.js
Ext.define("orgModel",{
extend:"Ext.data.Model",
fields:[
{name: "id"},
{name: "orgName"},
{name: "parentOrgId"},
{name: "parentOrgName"},
{name: "orgTypeDictCode"},
{name: "orgType"},
{name: "orgCode"}
]
});
var orgStore=Ext.create("Ext.data.Store", {
model:"orgModel",
proxy: {
type:"format",
url: basePath+"/org/getOrgList.action"
}
});
var orgGrid = Ext.create("Ext.grid.Panel", {
title : '组织管理',
region : "center",
bbar : Ext.create("Ext.PagingToolbar", {
store : orgStore
}),
selModel : Ext.create("Ext.selection.CheckboxModel"),
store : orgStore,
columns : [
{xtype: "rownumberer",width:60,text:'序号',align:"center"},
{header: "id",dataIndex: "id",hidden: true},
{header: "parentOrgId",dataIndex: "parentOrgId",hidden: true},
{header: "上级",width: 200,dataIndex: "parentOrgName"},
{header: "名称",width: 200,dataIndex: "orgName"},
{header: "类型",width: 200,dataIndex: "orgType",sortable :false,menuDisabled: true},
{header: "编码",width: 200,dataIndex: "orgCode"}
],
tbar : [ '->', {
xtype : 'button',
text : SystemConstant.addNextOrgBtnText,
iconCls : 'add-button',
id : 'addOrg',
handler : function() {
addOrg();
}
}, {
xtype : 'button',
id : 'updateOrg',
text : SystemConstant.modifyBtnText,
disabledExpr : "$selectedRows != 1",// $selected 表示选中的记录数不等于1
disabled : true,
iconCls : 'edit-button',
handler : function() {
updateOrg();
}
}, {
xtype : 'button',
text : SystemConstant.deleteBtnText,
id:'deleteOrg',
disabled : true,
disabledExpr : "$selectedRows == 0",
iconCls : 'delete-button',
handler : function() {
deleteOrg();
}
},{
text:"组织导出",
id:"userExport",
iconCls: "export-button",
handler: function(){
Ext.MessageBox.wait("", "导出数据",
{
text:"请稍后..."
}
);
$('#exportOrgs').submit();
Ext.MessageBox.hide();
}
} ]
});
var addOrg = function() {
orgWin.setTitle(SystemConstant.addBtnText);
var row = orgGrid.getSelectionModel().getSelection();
var basicForm = orgWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/org/addOrg.action';
orgTypeStore.load();
if(row!=''){
basicForm.findField('org.organization.id').setValue(row[0].data.parentOrgId);
basicForm.findField('org.organization.orgName').setValue(row[0].data.parentOrgName);
}else{
basicForm.findField('org.organization.id').setValue(selectNode.raw.nodeId);
basicForm.findField('org.organization.orgName').setValue(selectNode.raw.text);
}
basicForm.findField('org.orgCode').setDisabled(false);
orgTypeStore.load(function(records){
if(records.length>0){
Ext.getCmp("addOrgSelectionId").setValue(records[0].get("dictCode"));
}
});
orgWin.show();
};
var updateOrg = function() {
orgWin.setTitle(SystemConstant.modifyBtnText);
var row = orgGrid.getSelectionModel().getSelection();
var orgId = row[0].data.id;
var basicForm = orgWin.down('form').getForm();
basicForm.reset();
basicForm.url = basePath + '/org/updateOrg.action';
basicForm.findField('org.id').setValue(orgId);
basicForm.load({
url : basePath + '/org/getOrgById.action',
params : {
orgId : orgId
}
});
basicForm.findField('org.orgCode').setDisabled(true);
orgWin.show();
};
var deleteOrg = function(){
var rows = orgGrid.getSelectionModel().getSelection();
var ids = "";
for (var i = 0; i < rows.length; i++) {
ids += (rows[i].data.id + ",");
}
ids = ids.substring(0, ids.length - 1);
Ext.Msg.confirm(SystemConstant.alertTitle, "确认删除所选组织及其子组织吗?", function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : basePath + '/org/deleteOrg.action',
params : {
orgIds : ids
},
success : function(res, options) {
var data = Ext.decode(res.responseText);
if (data.success) {
treePanel.getStore().reload({
node:treePanel.getRootNode(),
callback: function () {
}
});
orgStore.loadPage(1);
Ext.Msg.showTip(data.msg);
} else {
Ext.Msg.showError(data.msg);
}
},
failure : sshframe.FailureProcess.Ajax
});
}
});
};
|
e19de501b764abef8784755c1e2832b3b53c7a25
|
[
"SQL",
"HTML",
"JavaScript",
"Maven POM",
"Java"
] | 30
|
JavaScript
|
wujialing1988/ssh
|
bb6a9373a561c98c4fe5af5ffcabb1daa10a93f0
|
23a2f7d25dd921fbf7342478e433e9639aa89ea3
|
refs/heads/master
|
<repo_name>sneakstarberry/c_algorithm<file_sep>/08_q5430/q5430.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int data;
struct Node *next;
struct Node *prev;
} d_Node;
int F = 0;
int R = 0;
int N;
d_Node *H;
d_Node *T;
void create(int input);
void push(int input);
void pop_f();
void pop_b();
void clean();
void print();
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
char cmd[100001];
int n;
scanf("%s", cmd);
scanf("%d", &n);
while (1) {
char t;
scanf(" %1c", &t);
if (t == '[' | t == ','){
int tmp;
scanf("%d", &tmp);
push(tmp);
continue;
} else if (t == ']')
break;
}
for (int j = 0; j < sizeof(cmd) / sizeof(char); j++) {
if (cmd[j] == 'R') {
R = R ? 0 : 1;
} else if (cmd[j] == 'D') {
if (n == 0) {
F = 1;
break;
}
R ? pop_b() : pop_f();
} else {
break;
}
}
if (F) {
printf("error\n");
} else {
printf("[");
print();
printf("]\n");
}
F = 0;
R = 0;
clean();
}
}
void create(int input) {
d_Node *node = malloc(sizeof(d_Node));
node->data = input;
node->next = NULL;
node->prev = NULL;
H = node;
T = node;
}
void push(int input) {
if (H == NULL) {
create(input);
return;
}
d_Node *node = malloc(sizeof(d_Node));
node->data = input;
node->next = NULL;
node->prev = T;
T->next = node;
T = node;
}
void pop_b() {
if (H == NULL) {
F = 1;
return;
}
d_Node *garbage = T;
if (H == T) {
H = NULL;
T = NULL;
free(garbage);
return;
}
T = T->prev;
free(garbage);
}
void pop_f() {
if (H == NULL) {
F = 1;
return;
}
d_Node *garbage = H;
if (H == T) {
H = NULL;
T = NULL;
free(garbage);
return;
}
H = H->next;
free(garbage);
}
void clean() {
while (H != NULL) {
pop_b();
}
}
void print() {
if (H == NULL) {
return;
}
d_Node *curr = R ? T : H;
while (1) {
if (R) {
if (curr == H) {
printf("%d", curr->data);
break;
}
printf("%d,", curr->data);
curr = curr->prev;
} else {
if (curr == T) {
printf("%d", curr->data);
break;
}
printf("%d,", curr->data);
curr = curr->next;
}
}
}
<file_sep>/13_q1697/q1697.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} q_Node;
int N, K,
ARR[100001] = {
0,
};
q_Node *H, *T;
void create(int input) {
q_Node *node = malloc(sizeof(q_Node));
node->data = input;
node->next = NULL;
H = node;
T = node;
}
void push(int input) {
if (H == NULL) {
create(input);
return;
}
q_Node *node = malloc(sizeof(q_Node));
node->data = input;
node->next = NULL;
T->next = node;
T = node;
}
void pop() {
q_Node *garbage = H;
H = H->next;
free(garbage);
}
int main() {
scanf("%d %d", &N, &K);
int seg = 1, cnt, ans=0, flag = 0;
push(N);
while (H != NULL) {
cnt = 0;
for (int i = 0; i < seg; i++) {
int data = H->data;
pop();
ARR[data] = 1;
flag = 0;
if (data == K) {
printf("%d\n", ans);
return 0;
}
if (data + 1 <= 100000 && !ARR[data + 1]) {
flag = 1;
cnt++;
push(data + 1);
}
if (data - 1 >= 0 && !ARR[data -1]) {
flag = 1;
cnt++;
push(data - 1);
}
if (data * 2 <= 100000 && !ARR[data * 2] ) {
flag = 1;
cnt++;
push(data * 2);
}
}
seg = cnt;
if (flag)
ans++;
}
printf("%d\n", ans);
}
<file_sep>/14_q1920/q1920.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} t_Node;
t_Node *root;
int N, M;
void push(int input) {
if (root == NULL) {
t_Node *node = malloc(sizeof(t_Node));
node->data = input;
node->left = NULL;
node->right = NULL;
root = node;
return;
}
t_Node *t = root;
t_Node * node = malloc(sizeof(t_Node));
while (t != NULL){
if (t->data > input) {
if (t->left == NULL) {
node->data = input;
node->left = NULL;
node->right = NULL;
t->left = node;
break;
}
t = t->left;
} else if (t->data < input) {
if (t->right == NULL) {
node->data = input;
node->left = NULL;
node->right = NULL;
t->right = node;
break;
}
t = t->right;
}
}
return;
}
void scan(int input) {
t_Node *t = root;
while (t != NULL) {
if (t->data == input) {
printf("1\n");
return;
}
if (t->data < input) {
if (t->right == NULL)
break;
t = t->right;
} else if (t->data > input) {
if (t->left == NULL)
break;
t = t->left;
}
}
printf("0\n");
return;
}
void trash(t_Node *node) {
t_Node *r = node->right;
t_Node *l = node->left;
if (r != NULL) {
trash(r);
}
if (l != NULL) {
trash(l);
}
free(node);
}
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
int tmp;
scanf("%d", &tmp);
push(tmp);
}
scanf("%d", &M);
for (int i = 0; i < M; i++) {
int tmp;
scanf("%d", &tmp);
scan(tmp);
}
trash(root);
return 0;
}
<file_sep>/02_q18258/q18258.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// 노드 구조체
typedef struct Node{
int data;
int cnt;
struct Node * next;
} q_Node;
// 전역 변수
int N;
q_Node * H;
q_Node * T;
// 함수 프로토타입
void create(int input);
void push(int input);
void pop();
void size();
int empty();
void front();
void back();
int main(){
scanf("%d", &N);
char c[20];
H = NULL;
T = NULL;
for(int i=0; i<N; i++){
scanf("%s", c);
if(!strcmp(c, "push")){
int tmp;
scanf("%d", &tmp);
push(tmp);
} else if(!strcmp(c, "pop")){
if(empty()){
printf("-1\n");
} else {
pop();
}
} else if(!strcmp(c, "size")){
if(empty()){
printf("0\n");
} else{
size();
}
} else if(!strcmp(c, "empty")){
printf("%d\n", empty());
} else if(!strcmp(c, "front")){
if(empty()){
printf("-1\n");
} else{
front();
}
} else if(!strcmp(c, "back")){
if(empty()){
printf("-1\n");
} else{
back();
}
}
}
return 0;
}
void create(int input){
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->cnt = 1;
node->next = NULL;
H = node;
T = node;
}
void push(int input){
if(T == NULL){
create(input);
return;
}
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->cnt = T->cnt+1;
node->next = NULL;
T->next = node;
T = node;
}
void pop(){
q_Node * garbage;
if(H == T){
garbage = H;
printf("%d\n", H->data);
H = NULL;
T = NULL;
free(garbage);
return;
} else {
garbage = H;
printf("%d\n", H->data);
H = H->next;
free(garbage);
return;
}
}
void size(){
printf("%d\n", T->cnt - H->cnt + 1);
}
int empty(){
if(T == NULL){
return 1;
} else {
return 0;
}
}
void front(){
printf("%d\n", H->data);
return;
}
void back(){
printf("%d\n", T->data);
return;
}
<file_sep>/10_q1012/q1012.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node{
int data;
int cnt;
struct Node * prev;
} s_Node;
s_Node * H,* L;
int N, X, Y, K, CNT=0;
int MAP[51][51] = {0,}, T[2], F[51][51] = {0,};
void dfs(int x, int y);
void create(int input);
void push(int input);
void size();
void scan();
int main() {
scanf("%d", &N);
for(int i=0; i< N; i++){
scanf("%d %d %d", &X, &Y, &K);
for(int j=0; j<51; j++){
memset(MAP[j], 0, sizeof(int) * 51);
memset(F[j], 0, sizeof(int) * 51);
}
for(int j=0; j<K; j++){
scanf("%d %d", &T[0], &T[1]);
MAP[T[0]][T[1]] = 1;
}
for(int j=0; j<X; j++){
for(int k=0; k<Y; k++){
if(MAP[j][k] && !F[j][k]){
CNT=0;
dfs(j, k);
push(CNT);
}
}
}
size();
scan();
}
}
void create(int input){
s_Node * node = malloc(sizeof(s_Node));
node->prev = NULL;
node->data = input;
node->cnt = 1;
H = node;
L = node;
}
void push(int input){
if(H == NULL){
create(input);
return;
}
s_Node * node = malloc(sizeof(s_Node));
node->prev = L;
node->data = input;
node->cnt = L->cnt+1;
L = node;
}
void size(){
printf("%d\n", L->cnt);
}
void scan(){
s_Node * garbage, *curr;
curr = L;
while(H == NULL){
garbage = curr;
curr = curr->prev;
free(garbage);
}
H = NULL;
L = NULL;
}
void dfs(int x, int y){
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
CNT++;
F[x][y] = 1;
for(int m=0; m<4; m++){
int newX = x + dx[m];
int newY = y + dy[m];
if(0<=newX && newX <X && 0<=newY && newY < Y)
if(MAP[newX][newY] && !F[newX][newY]){
dfs(newX, newY);
}
}
}
<file_sep>/06_q9012/q9012.c
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node{
char data;
struct Node * prev;
} s_Node;
s_Node * tail;
int N;
bool FLAG=false;
void create(char input){
s_Node * node;
node = malloc(sizeof(s_Node));
node->data = input;
node->prev = NULL;
tail = node;
}
void push(char input){
if(tail == NULL){
create(input);
return;
}
s_Node * node;
node = malloc(sizeof(s_Node));
node->data = input;
node->prev = tail;
tail = node;
}
void pop(){
if(tail == NULL){
FLAG = true;
return;
}
s_Node * garbage = tail;
if(tail->prev == NULL){
tail = NULL;
free(garbage);
return;
}
tail = tail->prev;
free(garbage);
}
void order(char input){
if(input == '('){
push(input);
}else if (input == ')'){
pop();
}
}
void scan(){
if(tail != NULL){
FLAG = true;
}
}
void buf_free(){
s_Node * garbage;
s_Node * curr;
curr = tail;
if(tail->prev == NULL){
garbage = tail;
tail = NULL;
free(garbage);
}
while(curr->prev != NULL){
garbage = curr;
curr = curr->prev;
free(garbage);
if(curr->prev == NULL){
garbage = curr;
tail = NULL;
free(garbage);
}
}
}
int main(){
char input;
scanf("%d", &N);
scanf("%1c", &input);
tail = NULL;
for(int i=0; i<N; i++){
FLAG=false;
while(1){
char glho;
scanf("%1c", &glho);
if(glho == '\n'){
break;
} else{
order(glho);
}
}
scan();
if(FLAG){
printf("NO\n");
if (tail != NULL){
buf_free();
}
} else{
printf("YES\n");
}
}
return 0;
}
<file_sep>/03_q1874/q1874.c
#include<stdio.h>
#include<stdlib.h>
// 숫자 스택
typedef struct Node{
int data;
struct Node * prev;
} i_Node;
// char 스택
typedef struct c_Node{
char data;
struct c_Node * prev;
struct c_Node * next;
} c_Node;
// 전역 변수
int N, arr[100001]={0,};
i_Node * Head;
i_Node * Tail;
c_Node * c_Head;
c_Node * c_Tail;
// 함수 프로토 타입
void create(int input);
void push(int input);
void pop();
void c_create(char input);
void c_push(char input);
void c_print();
int empty();
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++){
scanf("%d", &arr[i]);
}
int j = 0;
for(int i=1; i<=N; i++){
push(i);
c_push('+');
while(!empty() && Tail->data == arr[j]){
pop();
c_push('-');
j++;
}
}
if(!empty()){
printf("NO\n");
}else{
c_print();
}
return 0;
}
void create(int input){
i_Node * node;
node = malloc(sizeof(i_Node));
node->data = input;
node->prev = NULL;
Head = node;
Tail = node;
}
void push(int input){
if (Tail == NULL){
create(input);
return;
}
i_Node * node;
node = malloc(sizeof(i_Node));
node->data = input;
node->prev = Tail;
Tail = node;
}
void pop(){
i_Node * garbage = Tail;
if(Tail->prev == NULL){
Tail = NULL;
free(garbage);
return;
}
Tail = Tail->prev;
free(garbage);
}
int empty(){
if(Tail == NULL){
return 1;
} else {
return 0;
}
}
void c_create(char input){
c_Node * node;
node = malloc(sizeof(c_Node));
node->data = input;
node->prev = NULL;
node->next = NULL;
c_Head = node;
c_Tail = node;
}
void c_push(char input){
if(c_Tail== NULL){
c_create(input);
return;
}
c_Node * node;
node = malloc(sizeof(c_Node));
node->data = input;
node->prev = c_Tail;
c_Tail->next = node;
c_Tail = node;
}
void c_print(){
c_Node * curr = c_Head;
c_Node * garbage;
while(1){
printf("%c\n", curr->data);
garbage = curr;
curr = curr->next;
free(garbage);
if(curr == c_Tail){
printf("%c\n", curr->data);
free(curr);
return;
}
}
}
<file_sep>/07_q10866/q10866.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node {
int data;
int cnt;
struct Node * next;
struct Node * prev;
} d_Node;
int N;
d_Node * H;
d_Node * T;
void create(int input);
void push_front(int input);
void push_back(int input);
void pop_front();
void pop_back();
void size();
int empty();
void front();
void back();
int main(){
scanf("%d", &N);
for(int i=0; i<N; i++){
char cmd[20];
scanf("%s", cmd);
if(!strcmp(cmd, "push_front")){
int tmp;
scanf("%d", &tmp);
push_front(tmp);
} else if (!strcmp(cmd, "push_back")){
int tmp;
scanf("%d", &tmp);
push_back(tmp);
} else if (!strcmp(cmd, "pop_front")){
if(empty()){
printf("-1\n");
} else {
pop_front();
}
} else if (!strcmp(cmd, "pop_back")){
if(empty()){
printf("-1\n");
} else {
pop_back();
}
} else if (!strcmp(cmd, "size")){
if(empty()){
printf("0\n");
} else {
size();
}
} else if (!strcmp(cmd, "empty")){
printf("%d\n", empty());
} else if (!strcmp(cmd, "front")){
if(empty()){
printf("-1\n");
} else {
front();
}
} else if (!strcmp(cmd, "back")){
if(empty()){
printf("-1\n");
} else {
back();
}
}
}
}
void create(int input){
d_Node * node;
node = malloc(sizeof(d_Node));
node->data = input;
node->cnt = 1;
node->next = NULL;
node->prev = NULL;
H = node;
T = node;
}
void push_front(int input){
if(H == NULL){
create(input);
return;
}
d_Node * node;
node = malloc(sizeof(d_Node));
node->data = input;
node->cnt = H->cnt - 1;
node->next = H;
node->prev = NULL;
H->prev = node;
H = node;
}
void push_back(int input){
if(T == NULL){
create(input);
return;
}
d_Node * node;
node = malloc(sizeof(d_Node));
node->data = input;
node->cnt = T->cnt + 1;
node->next = NULL;
node->prev = T;
T->next = node;
T = node;
}
void pop_front() {
printf("%d\n", H->data);
d_Node * garbage = H;
if(H == T){
H = NULL;
T = NULL;
free(garbage);
return;
}
H = H->next;
free(garbage);
}
void pop_back() {
printf("%d\n", T->data);
d_Node * garbage = T;
if(H == T){
H = NULL;
T = NULL;
free(garbage);
return;
}
T = T->prev;
free(garbage);
}
void size(){
printf("%d\n", T->cnt - H->cnt + 1);
}
int empty(){
if(H == NULL){
return 1;
} else {
return 0;
}
}
void front(){
printf("%d\n", H->data);
}
void back(){
printf("%d\n", T->data);
}
<file_sep>/04_q1966/q1966.c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
int p;
struct Node * next;
} q_Node;
int N;
q_Node * H;
q_Node * T;
int compare(const void *a, const void *b);
void push(int input, int p);
void create(int input, int p);
void clean();
q_Node pop();
void bubble_sort(int *arr, int count);
int main(){
scanf("%d", &N);
H = NULL;
T = NULL;
for(int i=0; i<N; i++){
int n;
int p;
int c;
int * arr;
arr = malloc(sizeof(int) * n);
scanf("%d %d", &n, &p);
for(int j=0; j<n; j++){
int input;
scanf("%d", &input);
arr[j] = input;
if(j == p){
push(input, 1);
} else {
push(input, 0);
}
}
bubble_sort(arr, n);
int k=1;
while(1){
if(arr[k-1] != H->data){
q_Node tmp;
tmp = pop();
push(tmp.data, tmp.p);
} else {
if(H->p){
printf("%d\n", k);
break;
}
pop();
k++;
}
}
clean();
free(arr);
}
return 0;
}
int compare(const void *a, const void *b){
int num1 = *(int *)a;
int num2 = *(int *)b;
if(num1 > num2){
return -1;
}
if(num1 < num2){
return 1;
}
return 0;
}
void create(int input, int p){
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->p = p;
node->next = NULL;
H = node;
T = node;
}
void push(int input, int p){
if(H == NULL){
create(input, p);
return;
}
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->p = p;
node->next = NULL;
T->next = node;
T = node;
}
q_Node pop(){
q_Node * garbage = H;
q_Node out = *H;
if(H == T){
H = NULL;
T = NULL;
free(garbage);
return out;
}
H = H->next;
free(garbage);
return out;
}
void clean(){
if(H == NULL){
return;
}else{
while(H !=NULL){
pop();
}
return;
}
}
void bubble_sort(int * arr, int count){
int temp;
for (int i = 0; i < count; i++) // 요소의 개수만큼 반복
{
for (int j = 0; j < count - 1; j++) // 요소의 개수 - 1만큼 반복
{
if (arr[j] < arr[j + 1]) // 현재 요소의 값과 다음 요소의 값을 비교하여
{ // 큰 값을
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp; // 다음 요소로 보냄
}
}
}
}
<file_sep>/05_q2164/q2164.c
#include<stdio.h>
#include<stdlib.h>
// 노드 구조체
typedef struct Node{
int data;
int cnt;
struct Node * next;
} q_Node;
// 전역 변수
int N;
q_Node * H;
q_Node * T;
// 함수 프로토타입
void create(int input);
void push(int input);
int pop();
int empty();
int main(){
scanf("%d", &N);
for(int i=1; i<=N; i++){
push(i);
}
while(H!=T){
int poped;
pop();
poped = pop();
push(poped);
}
printf("%d", H->data);
return 0;
}
void create(int input){
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->cnt = 1;
node->next = NULL;
H = node;
T = node;
}
void push(int input){
if(empty()){
create(input);
return;
}
q_Node * node;
node = malloc(sizeof(q_Node));
node->data = input;
node->cnt = T->cnt+1;
node->next = NULL;
T->next = node;
T = node;
}
int pop(){
q_Node * garbage;
int out;
if(H == T){
garbage = H;
out = H->data;
H = NULL;
T = NULL;
free(garbage);
return out;
} else {
garbage = H;
out = H-> data;
H = H->next;
free(garbage);
return out;
}
}
int empty(){
if(T == NULL){
return 1;
} else {
return 0;
}
}
<file_sep>/09_q2667/q2667.c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
int cnt;
struct Node * next;
struct Node * prev;
} d_Node;
int N, CNT;
char M[25][25];
int F[25][25] = {0,};
d_Node * H;
d_Node * T;
void dfs(int i, int j);
void push(int input);
void create(int input);
void size();
void scan();
int main() {
scanf("%d", &N);
for(int i=0; i<N; i++){
scanf("%s", M[i]);
}
for(int i=0; i<N; i++){
for(int j=0; j<N; j++){
if(M[i][j] == '1' && !F[i][j]) {
CNT =0;
dfs(i,j);
push(CNT);
}
}
}
size();
scan();
return 0;
}
void create(int input){
d_Node * node = malloc(sizeof(d_Node));
node->data = input;
node->cnt = 1;
node->next = NULL;
node->prev = NULL;
H = node;
T = node;
}
void push(int input){
if(H == NULL){
create(input);
return;
}
d_Node * node = malloc(sizeof(d_Node));
node->data = input;
node->cnt = T->cnt + 1;
node->next = NULL;
node->prev = T;
T->next = node;
T = node;
}
void size(){
printf("%d\n", T->cnt);
}
void dfs(int i , int j){
int dx[4] = {0,1,0,-1};
int dy[4] = {-1,0,1,0};
CNT++;
F[i][j] = 1;
for(int k=0; k<4; k++){
int newX = i + dx[k];
int newY = j + dy[k];
if(0<= newX && newX < N && 0 <= newY && newY < N)
if(M[newX][newY] == '1'&& !F[newX][newY]) dfs(newX, newY);
}
}
int compare(const void* first, const void* second){
int a = *(int *)first;
int b = *(int *)second;
if(a < b){
return -1;
} else if(a>b){
return -1;
} else{
return 0;
}
}
void scan(){
int arr[625];
int n = T->cnt;
d_Node * curr = H;
d_Node * garbage;
for(int i=0; i< n; i++){
garbage = curr;
arr[i] = curr->data;
curr = curr->next;
free(garbage);
}
qsort(arr, n, sizeof(int), compare );
for(int i=0; i< n; i++){
printf("%d\n", arr[i]);
}
}
<file_sep>/15_q5639/q5639.c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node * left;
struct Node * right;
} t_Node;
t_Node * root;
void push(int num);
void post_order(t_Node * node);
int main(){
int tmp;
while(scanf("%d", &tmp) != EOF){
push(tmp);
}
post_order(root);
root = NULL;
return 0;
}
void post_order(t_Node * node){
if(node !=NULL){
post_order(node->left);
post_order(node->right);
t_Node * garbage;
garbage = node;
printf("%d\n", node->data);
free(garbage);
}
}
void push(int input){
if(root == NULL){
t_Node * node = malloc(sizeof(t_Node));
node->data = input;
node->left = NULL;
node->right = NULL;
root = node;
return;
}
t_Node * t = root;
while(1) {
t_Node * node = malloc(sizeof(t_Node));
if (t->data > input){
if(t->left == NULL){
node->data = input;
node->left = NULL;
node->right = NULL;
t->left = node;
return;
}
t = t->left;
} else if (t->data < input){
if(t->right == NULL){
node->data = input;
node->left = NULL;
node->right = NULL;
t->right = node;
return;
}
t = t->right;
}
}
}
<file_sep>/12_q7576/q7576.c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int fst;
int sec;
struct Node * next;
} q_Node;
int M, N;
int ARR[1001][1001], F[1001][1001];
q_Node *H, *T;
void create(int i, int j);
void push(int i, int j);
void pop();
void scan();
int main() {
scanf("%d %d", &M, &N);
int seg=0;
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
scanf("%d", &ARR[i][j]);
if(ARR[i][j] ==1){
push(i, j);
seg++;
}
}
}
int ans =0;
while(H != NULL){
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int cnt=0;
int traverse = 0;
for(int j=0; j<seg; j++){
int pair[2];
pair[0] = H->fst;
pair[1] = H->sec;
pop();
F[pair[0]][pair[1]] = 1;
for(int i=0; i<4; i++){
int newX = pair[0] + dx[i];
int newY = pair[1] + dy[i];
if(0<=newY && newY < M && 0<=newX && newX < N)
if(!F[newX][newY] && ARR[newX][newY] ==0){
ARR[newX][newY] = 1;
push(newX, newY);
cnt++;
traverse = 1;
}
}
}
seg = cnt;
if(traverse) ans++;
}
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
if(ARR[i][j] == 0) {
printf("-1\n");
return 0;
}
}
}
printf("%d\n", ans);
}
void create(int i, int j){
q_Node * node = malloc(sizeof(q_Node));
node->fst = i;
node->sec = j;
node->next = NULL;
H = node;
T = node;
}
void push(int i, int j){
if(H == NULL){
create(i, j);
return;
}
q_Node * node = malloc(sizeof(q_Node));
node->fst = i;
node->sec = j;
node->next = NULL;
T->next = node;
T = node;
}
void pop(){
q_Node * garbage = H;
H = H->next;
free(garbage);
}
<file_sep>/01_q10773/q10773.c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node * prev;
} s_Node;
s_Node * tail;
int N;
void create(int input){
s_Node * node;
node = malloc(sizeof(s_Node));
node->prev = NULL;
node->data = input;
tail = node;
}
void push(int input){
if(tail == NULL){
create(input);
} else{
s_Node * node;
node = malloc(sizeof(s_Node));
node->prev = tail;
node->data = input;
tail = node;
}
}
void pop(){
s_Node * garbage = tail;
if(tail->prev == NULL){
tail = NULL;
free(garbage);
} else{
tail = tail->prev;
free(garbage);
}
}
void scan(){
if(tail == NULL){
printf("0");
return;
}
s_Node * curr = tail;
int result = 0;
while(curr->prev != NULL){
result+=curr->data;
s_Node * garbage = curr;
curr = curr->prev;
if (curr->prev == NULL){
result+=curr->data;
}
free(garbage);
}
printf("%d", result);
}
int main(){
scanf("%d", &N);
for(int i=0; i<N;i++){
int input;
scanf("%d", &input);
if(input == 0){
pop();
} else{
push(input);
}
}
scan();
return 0;
}
|
2ec59002bacfa139da48ec4009290cb724246d66
|
[
"C"
] | 14
|
C
|
sneakstarberry/c_algorithm
|
0826a19fcb1ab660f2df419c4946a670caec243c
|
b38c70895a61bdfe5238151b483dd1921ac34573
|
refs/heads/main
|
<repo_name>eriik1/border<file_sep>/main.js
function preload(){
}
function setup(){
canvas=createCanvas(500,500)
canvas.position(110,250)
video=createCapture(VIDEO)
video.hide()
}
function draw(){
image(video,0,0,500,500)
fill("red")
stroke("blue")
rect(30,40,400,15)
rect(30,425,400,15)
rect(30,40,15,400)
rect(420,40,15,400)
fill("aqua")
stroke("white")
circle(50,50,50)
circle(425,50,50)
circle(50,425,50)
circle(425,425,50)
}
function takesnapeshot(){
save("selfe.png")
}
|
c5c8070570f136f4a022dc0e360b329325796c91
|
[
"JavaScript"
] | 1
|
JavaScript
|
eriik1/border
|
e07e52fc06a2a90984ca5f63e1e254e84b1dc637
|
54562361566767fd092ddbb2ce237c00791934f3
|
refs/heads/master
|
<repo_name>ryujinno/mconvert.rb<file_sep>/lib/mconvert.rb
require 'mconvert/version'
require 'mconvert/cli'
require 'mconvert/converter'
require 'mconvert/multi_process'
<file_sep>/spec/mconvert/convert_spec.rb
require 'spec_helper'
module MConvert
describe MConvert::FFMpeg do
before(:all) do
@ffmpeg = FFMpeg.new({})
end
describe '#has_commands!' do
context 'with command installed' do
it 'should not raise error' do
commands = [ 'true' ]
expect { @ffmpeg.has_commands!(commands) }.to_not raise_error
end
end
context 'with command not installed' do
it 'should raise runtime error' do
commands = [ 'not_instailed_command' ]
expect { @ffmpeg.has_commands!(commands) }.to raise_error(RuntimeError)
end
end
end
describe '#get_codecs' do
context 'with format' do
it 'should return codecs as a array' do
lines = [ 'Format: MPEG-4', 'Format: ALAC' ]
expect(@ffmpeg.get_codecs(lines)). to match_array([ 'MPEG-4', 'ALAC' ])
end
end
context 'without format' do
it 'should return empty array' do
lines = [ 'General', 'Audio' ]
expect(@ffmpeg.get_codecs(lines)). to be_empty
end
end
end
end
end
<file_sep>/README.md
# MConvert
[](https://travis-ci.org/ryujinno/mconvert.rb)
Multi-processed lossless music file converter.
## Installation
### Install dependant commands
For Mac OS X:
```
$ brew install ffmpeg mediainfo
```
For Linux:
```
$ apt-get install ffmpeg mediainfo
```
### Install with bundler
Add the following line to `${HOME}/Gemfile`:
```ruby
gem 'mconvert', github: 'ryujinno/mconvert.rb'
```
Install gems and commands as:
```
$ bundle install --binstubs
```
`mconvert` command is installed to `${HOME}/bin`.
## Usage
```
Commands:
mconvert alac LOSSLESS_FILES # Convert lossless files to ALAC
mconvert flac LOSSLESS_FILES # Convert lossless files to FLAC
mconvert help [COMMAND] # Describe available commands or one specific command
mconvert mp3 LOSSLESS_FILES # Convert lossless files to mp3 with lame
mconvert wave LOSSLESS_FILES # Convert lossless files to WAVE
Options:
-j, [--jobs=N] # Limit jobs under number of CPUs
```
## Contributing
1. Fork it ( https://github.com/ryujinno/mconvert.rb/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>/lib/mconvert/multi_process.rb
module MConvert
module MultiProcess
def get_jobs(option)
if option.nil?
jobs = n_cpus
else
jobs = [n_cpus, option].min
end
jobs
end
def n_cpus
if RUBY_PLATFORM.include?('-linux')
processor = 0
IO.foreach('/proc/cpuinfo') do |line|
match = line.match(/^processor\s*:\s*(\d)$/)
processor = match[1].to_i if match
end
processor + 1 # CPU number starts from 0
elsif RUBY_PLATFORM.include?('-darwin')
`sysctl -n hw.ncpu`.strip.to_i
else
1
end
end
def concurrent(n_processes, queue, *args)
pool = {}
queue.each_with_index do |q, i|
while pool.size >= n_processes do
pid, status = Process.wait2
unless status.success?
process_failed_middle(pool[pid])
end
pool.delete(pid)
end
pid = Process.fork do
yield(q, i, *args)
end
pool[pid] = { queue: q, index: i }
end
ensure
Process.waitall.each do |pid, status|
unless status.success?
process_failed_end(pool[pid])
end
end
end
def process_failed(failed)
raise "Process ##{failed[:index]} failed: #{failed[:queue]}"
end
alias :process_failed_middle :process_failed
alias :process_failed_end :process_failed
end
end
<file_sep>/lib/mconvert/converter.rb
require 'mconvert/multi_process'
require 'open3'
=begin
Adopted Format:
ALAC
FLAC
WAVE
MP3: lame 256kbps VBR
=end
module MConvert
class Converter
include MultiProcess
REQUIRED_COMMANDS = [ 'mediainfo', 'ffmpeg' ]
LOSSLESS_CODECS = [
'ALAC', 'FLAC', 'Wave',
# 'TAK', 'APE', 'TTA', 'WMA Lossless',
]
def destination_filename(source_filename)
# Example to convert into flac file
#source_filename.gsub(/\.\w+$/, '.flac')
end
def command_to_comvert(source_filename)
# Example to convert with ffmpeg
#[
# 'ffmpeg', '-y', '-loglevel', 'warning',
# '-i', source_filename,
# '-vn', destination_filename(source_filename)
#]
end
def initialize(options)
@jobs = get_jobs(options[:jobs])
@jobs.freeze
end
def convert(source_files)
has_commands!
is_lossless!(source_files)
concurrent(@jobs, source_files) do |source_filename, i|
do_convert_command(source_filename)
end
end
def has_commands!(mandatory = REQUIRED_COMMANDS)
mandatory.each do |command|
Open3.popen3(ENV, 'which', command) do |stdin, out, err, th|
raise("#{command} is required!") unless th.join.value.success?
end
end
end
def is_lossless!(files)
files.each do |file|
codecs = []
IO.popen([ 'mediainfo', file ]) do |io|
codecs = get_codecs(io)
end
lossless = LOSSLESS_CODECS & codecs
if lossless.empty?
raise("Input file is not lossless format: #{file}")
end
end
end
def get_codecs(io)
codecs = []
io.each do |line|
match = line.match(/Format\s*:\s*(.*)$/)
codecs << match[1] if match
end
codecs
end
def do_convert_command(source_filename)
puts("Converting: #{source_filename}")
suceeded = exec(*command_to_comvert(source_filename))
unless suceeded
raise "Cannot convert #{source_filename}"
end
end
end
class FFMpeg < Converter
def destination_filename(source_filename)
# Example to convert into flac file
#source_filename.gsub(/\.\w+$/, '.flac')
end
def command_to_comvert(source_filename)
[
'ffmpeg',
'-nostdin',
'-y',
'-loglevel', 'warning',
'-vn',
'-i', source_filename,
destination_filename(source_filename)
]
end
end
class FFMpegFlac < FFMpeg
def destination_filename(source_filename)
source_filename.gsub(/\.\w+$/, '.flac')
end
end
class FFMpegWave < FFMpeg
def destination_filename(source_filename)
source_filename.gsub(/\.\w+$/, '.wav')
end
end
class FFMpegAlac < FFMpeg
def destination_filename(source_filename)
source_filename.gsub(/\.\w+$/, '.m4a')
end
def command_to_comvert(source_filename)
[
'ffmpeg', '-y', '-loglevel', 'warning',
'-i', source_filename,
'-vn', '-acodec', 'alac', destination_filename(source_filename)
]
end
end
class FFMpegMP3 < FFMpeg
def destination_filename(source_filename)
source_filename.gsub(/\.\w+$/, '.mp3')
end
def command_to_comvert(source_filename)
[
'ffmpeg',
'-nostdin',
'-y',
'-loglevel', 'warning',
'-vn',
'-acodec', 'libmp3lame',
'-ab', '256k',
'-i', source_filename,
destination_filename(source_filename)
]
end
end
end
<file_sep>/exe/mconvert
#!/usr/bin/env ruby
require 'mconvert'
MConvert::CLI.start
<file_sep>/lib/mconvert/cli.rb
require 'thor'
module MConvert
class CLI < Thor
class_option :jobs, aliases: '-j', type: :numeric, desc: 'Limit jobs under number of CPUs'
desc 'alac LOSSLESS_FILES', 'Convert lossless files to ALAC'
def alac(*files)
FFMpegAlac.new(options).convert(files)
end
desc 'flac LOSSLESS_FILES', 'Convert lossless files to FLAC'
def flac(*files)
FFMpegFlac.new(options).convert(files)
end
desc 'wave LOSSLESS_FILES', 'Convert lossless files to WAVE'
def wave(*files)
FFMpegWave.new(options).convert(files)
end
desc 'mp3 LOSSLESS_FILES', 'Convert lossless files to mp3 with lame'
def mp3(*files)
FFMpegMP3.new(options).convert(files)
end
end
end
|
35c3295c7200bbbb3949f1d6ec705185a23140a6
|
[
"Markdown",
"Ruby"
] | 7
|
Ruby
|
ryujinno/mconvert.rb
|
cc716717b440b525570191a14a91afcab84dbdb7
|
ef275998f9c9548bfabe888de14a1600c4db98d9
|
refs/heads/master
|
<repo_name>redbox-digital/magento-docker<file_sep>/CHANGELOG.md
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog][link]
## 1.0.0 [unreleased]
### Added
* Introduce basic MySQL configuration.
* Add `update` command to global rd to pull latest rd file.
### Fixed
* Fix issue preventing asset compilation.
## 0.1.0
### Added
* A global utility to forward to local `rd`.
* `fix-permissions` command.
* README and CHANGELOG.
### Changed
* Introduced a build process for selective artifacts.
[link]: http://keepachangelog.com/
<file_sep>/compose/bin/rd
#! /usr/bin/env bash
set -e
function start_docker {
docker-compose up -d
}
function stop_docker {
docker-compose stop
}
function run {
local project_name="$(docker-compose ps | head -3 | tail -1 | cut -d_ -f1)"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-v "/etc/passwd:/etc/passwd" \
-v "$HOME/.ssh/known_hosts:$HOME/.ssh/known_hosts" \
-v "$HOME/.composer:$HOME/.composer" \
-v "$SSH_AUTH_SOCK:$SSH_AUTH_SOCK" \
-e COMPOSER_HOME="$HOME/.composer" \
-e SSH_AUTH_SOCK="$SSH_AUTH_SOCK" \
-w /mnt/www redboxdigital/docker-console \
"$@"
}
function fix_permissions {
local project_name="$(docker-compose ps | head -3 | tail -1 | cut -d_ -f1)"
echo "Beginning correction of owner"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "root:82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
chown -R "$(id -u):82" .
echo "Beginning correction of normal file permissions"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
find . -type f -exec chmod 744 {} \;
echo "Beginning correction of directory permissions"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
find . -type d -exec chmod 755 {} \;
echo "Adding sticky bit to group permissions for directories"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
find . -type d -exec chmod g+s {} \;
echo "Adding group write permissions to var/"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
find var/ -exec chmod g+w {} \;
echo "Adding group write permissions to pub/"
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
find pub/ -exec chmod g+w {} \;
docker run \
-it \
--rm \
--net=${project_name}_default \
-u "$(id -u):82" \
--volumes-from="${project_name}_appserver_1" \
-w /mnt/www alpine \
chmod +x bin/magento
echo "All finished"
}
function main {
case $1 in
"start")
start_docker
;;
"stop")
stop_docker
;;
"run")
run "${@:2}"
;;
"fix-permissions")
fix_permissions
;;
*)
echo "Please run a command"
;;
esac
}
main "$@"
<file_sep>/Makefile
all: project
project:
mkdir -p build tmp
cp -r compose tmp/rbd
tar czf build/rbd.tar.gz -C tmp rbd
rm -rf tmp
test:
echo "No tests yet, shame on me"
link:
ln -s "$(CURDIR)/rd" "/usr/local/bin/rdl"
unlink:
find /usr/local/bin -type l -name rdl -delete
clean:
rm -rf build tmp
<file_sep>/README.md
# Redbox Docker
A "batteries not included" best practice development environment for Magento 2,
based on Docker.
## Installation
```bash
curl -sS https://raw.githubusercontent.com/redbox-digital/magento-docker/master/rd > /usr/local/bin/rd
chmod +x /usr/local/bin/rd
rd create my-project
cd my-project
rd start
```
You should now be up and running. If you're not, then you are having fun and
games to get Magento up and running.
## What's Included
When we say "batteries not included", we mean that there is nothing here to
scaffold a Magento installation. Redbox Docker merely contains a good server
environment, and we leave installation to you.
An installation of Redbox Docker is quite small, and doesn't contain an awful
lot. In fact, this is it:
```
redbox-docker
├── .gitignore
├── bin
│ └── rd
├── docker-compose.yml
└── servers
├── appserver
│ └── etc
│ └── php.ini
└── webserver
└── etc
└── nginx.conf
```
Beyond the `docker-compose.yml` file, we have the following:
* `bin/rd`: This is a utility that allows you to manage your Magento
installation from outside your containers.
* `servers/`: We include volume mappings for some configuration files, since
these are commonly customised on a project by project basis. For example, if you
need to add multi-site functionality, you might amend your `nginx.conf` file to
handle this.
## Containers
Redbox Docker comes with:
* Nginx
* PHP 7.0,
* Percona 5.6
* Redis (for cache and session back end)
* RabbitMQ, with a management interface.
* Mailcatcher, for receiving emails.
## Debugging
There are two app servers, both largely identical. Where they differ is that one
of them has Xdebug installed.
These two containers are named `appserver` and `appserver_debug` respectively.
You should switch to use that container if you need to debug. Having no Xdebug
installed on the container used most of the time saves you from the performance
penalty associated with Xdebug.
Switching is very easy. Simply send the Xdebug cookie with an IDE key of
`docker`, and the web server will intelligently route your request. Since
everything else is shared, this switch is totally transparent.
## OS Support
We built this to run on Linux. We are pretty sure that it should run on Docker
for Mac, or Docker for Windows, but we haven't tested, and it's likely you will
suffer from poor volume performance.
## `rd`
This utility is the management console for the Redbox Docker environment. It
comes with a few commands, but the most common of these is `run`
`./bin/rd run` allows you to run commands inside your Docker environment. For
example, you might want to run `composer install`, or `n98-magerun
setup:upgrade`.
The way this command actually works is by inserting a container into the Redbox
Docker network, running your command, and then gracefully removing itself. This
keeps your server containers lean and without all that administration junk.
The container that runs these commands is based on a custom console image.
Please check its documentation for a full list of installed utilities, and to
remind us of anything that was missed.
If you want to run `rd` globally, we added a proxy command to speak to the `rd`
utility that is available on your environment. To install it, run the following:
```bash
curl -sS -O https://raw.githubusercontent.com/redbox-digital/magento-docker/master/rd
chmod +x ./rd
```
Then move it to some location in your `$PATH`, and you should be able to call
something like `rd run composer status`.
## Permissions
### tl;dr
```
./bin/rd fix-permissions
```
Docker can be fiddly about permissions. If you encounter troubles such as not
being able to write logs, or save media, we can help.
Since these containers (with the exception of `messagequeue` and `mail`) run on
Alpine Linux, the UIDs are different. The two containers that access files
(`webserver` and `appserver`) both run as `www-data:www-data`. In Alpine, these
names correspond to `82:82`. So you need to make sure that a user running with
those permissions has read and write to your project.
This can be achieved by setting the group to `82` on your host, and then making
sure that the group has read permissions on everything, and write permissions
where it needs them. Further, if you set the sticky flag on group permissions,
all new files will be created with the correct group.
It is important that your host user retain ownership of the files, so that you
can always read from and write to whatever you choose.
Any commands run via `./bin/rd run [...]` will run with your host user id, and the group 82.
## Known Issues
- [ ] Alpine Linux does not support the `GLOB_BRACE` constant, which exposes
a notice in the glob utility in the version of `Zend\StdLib` that Magento
2 currently uses. This is fixed in the latest version, and we are petitioning
Magento to upgrade their dependencies.
- [ ] It is not yet possible to debug a console command. This is important for
debugging upgrade scripts, or cron tasks.
<file_sep>/compose/servers/appserver/etc/fix_glob_brace.php
<?php
/**
* Alpine does not define GLOB_BRACE, and there is a bug in Zend Framework that
* depends on this, so a notice is generated. This is a bug that was fixed a
* while back, but it is present in all Magento 2 versions, and, notably, breaks
* setup:static-content:deploy.
*
* This will be removed when Magento 2 updates their damned dependencies.
*/
define('GLOB_BRACE', 0);
<file_sep>/rd
#! /usr/bin/env bash
set -e
function find_in_parent {
local filename="$1"
local start="$2"
if [ -z "$start" ]
then
start="$(pwd)"
fi
local candidate="$start/$filename"
if [ -e "$candidate" ]
then
echo -n "$candidate"
elif [ "$start" == "/" ]
then
>&2 echo -n "File $filename not found in any directory"
else
find_in_parent "$filename" "$(dirname $start)"
fi
}
function update_self {
local self_url="https://raw.githubusercontent.com/redbox-digital/magento-docker/master/rd"
local location="$BASH_SOURCE"
curl -sS "$self_url" | tee "$location" &> /dev/null
}
function main {
local rd="$(find_in_parent bin/rd 2> /dev/null)"
case $1 in
"update")
update_self
;;
*)
if [ -x "$rd" ]
then
exec "$rd" "$@"
else
>&2 echo "Unable to find a Redbox Docker project in any parent directory."
fi
;;
esac
}
main "$@"
<file_sep>/compose/docker-compose.yml
version: '2'
services:
webserver:
image: "nginx:alpine"
ports:
- "80:80"
volumes:
- "./servers/webserver/etc/nginx.conf:/etc/nginx/nginx.conf"
volumes_from:
- "appserver"
depends_on:
- "appserver"
- "appserver_debug"
appserver:
image: "redboxdigital/php:7.0"
volumes:
- "./src:/mnt/www"
- "./servers/appserver/etc/php.ini:/usr/local/etc/php/php.ini"
- "./servers/appserver/etc/fix_glob_brace.php:/usr/local/etc/php/fix_glob_brace.php"
depends_on:
- "database"
- "mail"
- "cache"
- "fpc"
- "session"
- "messagequeue"
appserver_debug:
image: "redboxdigital/php:7.0-xdebug"
volumes_from:
- "appserver"
depends_on:
- "appserver"
database:
image: percona:5.6
ports:
- "3306:3306"
volumes:
- "/var/lib/mysql"
- "./servers/database/etc/mysql/my.cnf:/etc/mysql/my.cnf"
environment:
MYSQL_ROOT_PASSWORD: "root"
mail:
image: "redboxdigital/mailcatcher"
ports:
- "1080:80"
cache:
image: "redis:alpine"
fpc:
image: "redis:alpine"
session:
image: "redis:alpine"
messagequeue:
image: "rabbitmq:management"
ports:
- "15672:15672"
|
c6bb90cd99aeafa2753c3630a466121f4dad2204
|
[
"YAML",
"Markdown",
"Makefile",
"PHP",
"Shell"
] | 7
|
Markdown
|
redbox-digital/magento-docker
|
53a8af0edff49287bf565222b8717e471ba16c8c
|
32d80042bdf97e47383d856a81335ae83e7c1d0c
|
refs/heads/master
|
<repo_name>stamay/SunshineAdapter<file_sep>/app/src/main/java/mx/edu/utcancun/android/sunshine/MainActivityFragment.java
package mx.edu.utcancun.android.sunshine;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container,false);
String [] datos= {
"Lunes - Soleado - 2*/8*",
"Martes - Nublado -15*/19*",
"Miercoles - Soleado -25*/28*",
"Jueves - Nublado -35*/40*",
"Viernes -Medio Soleado -30*/38*",
"Sabado - Soleado -17*/23*",
"Domingo - Medio Nublado -37*/38*"
};
List<String> lista = new ArrayList<String>(Arrays.asList(datos));
ArrayAdapter<String> adapter= new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_texview,
lista
);
ListView listView = (ListView)rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(adapter);
return rootView;
}
}
|
bf66a31b391c7aefca02eb4422eeb0593fafcdc8
|
[
"Java"
] | 1
|
Java
|
stamay/SunshineAdapter
|
6eba2947a813b7117c4fab6129ede63140db3497
|
b8568d29a340cf55614599ef8be330e689cbe842
|
refs/heads/master
|
<file_sep>package lnu.agt;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.codehaus.jackson.JsonNode;
/**
* @author jofrab
*
*/
public class TweetText {
String id;
String text;
String lang;
String cleanText;
JsonNode tweet;
ArrayList<Integer> userMentions;
ArrayList<Integer> hashtagMentions;
ArrayList<Integer> symbolMentions;
ArrayList<Integer> urlMentions;
ArrayList<Integer> mediaMentions;
int classification;
public TweetText(int classification, JsonNode tweet) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException{
text = tweet.get("text").asText();
id = tweet.get("id").asText();
lang = tweet.get("lang").asText();
this.tweet = tweet;
this.classification = classification;
setEntities();
cleanTweet();
}
public TweetText(JsonNode tweet) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException{
text = tweet.get("text").asText();
id = tweet.get("id").asText();
lang = tweet.get("lang").asText();
this.tweet = tweet;
setEntities();
cleanTweet();
}
public void setEntities(){
//get entities from Twitter
hashtagMentions = null;
urlMentions = null;
userMentions = null;
symbolMentions = null;
mediaMentions = null;
JsonNode rootNode = tweet.get("entities");
Iterator<JsonNode> entityIterator = rootNode.getElements();
int i = 0;
while (entityIterator.hasNext()) {
JsonNode entnode = entityIterator.next();
int index = entnode.toString().indexOf("\"indices\":");
int indexEnd =-1;
String s;
ArrayList<Integer> list = new ArrayList<Integer>();
if(index>=0){indexEnd = entnode.toString().substring(index).indexOf("]");}
while (index >= 0) {
s = entnode.toString().substring(index+11, index+indexEnd);
int innerIndex = s.indexOf(",");
int start = Integer.parseInt(s.substring(0, innerIndex));
int end = Integer.parseInt(s.substring(innerIndex+1));
list.add(start);
list.add(end);
index = entnode.toString().indexOf("\"indices\":", index + 1);
if(index>=0){indexEnd = entnode.toString().substring(index).indexOf("]");}
}
if(i==0){
hashtagMentions = list;
}else if (i==1){
urlMentions = list;
}else if (i==2){
userMentions = list;
}else if (i==3){
symbolMentions = list;
}else if (i==4){
mediaMentions = list;
}
i++;
}
}
public void cleanTweet() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
if(text.equals("")) {
System.out.println("Empty string");
return;
}
String tmp = text;
//use the supplied entity markers from Twitter to map #... -> hashtag, @.. -> user, etc.
byte[] arr32 = tmp.getBytes("UTF-32");
byte[] arrPart;
String newString;
Charset.forName("UTF-32").encode(tmp);
if(hashtagMentions != null) {
for(int i = 0; i < hashtagMentions.size(); i = i + 2){
arrPart = Arrays.copyOfRange(arr32, 4*hashtagMentions.get(i), 4*hashtagMentions.get(i+1));
newString = new String(arrPart, "UTF-32");
tmp = tmp.replaceAll(Pattern.quote(newString), " XHASHTAGX ");
}
}
if(urlMentions != null) {
for(int i = 0; i < urlMentions.size(); i = i + 2){
arrPart = Arrays.copyOfRange(arr32, 4*urlMentions.get(i), 4*urlMentions.get(i+1));
newString = new String(arrPart, "UTF-32");
tmp = tmp.replaceAll(Pattern.quote(newString), " XURLX ");
}
}
if(userMentions != null) {
for(int i = 0; i < userMentions.size(); i = i + 2){
arrPart = Arrays.copyOfRange(arr32, 4*userMentions.get(i), 4*userMentions.get(i+1));
newString = new String(arrPart, "UTF-32");
tmp = tmp.replaceAll(Pattern.quote(newString), " XUSERX ");
}
}
if(symbolMentions != null) {
for(int i = 0; i < symbolMentions.size(); i = i + 2){
arrPart = Arrays.copyOfRange(arr32, 4*symbolMentions.get(i), 4*symbolMentions.get(i+1));
newString = new String(arrPart, "UTF-32");
tmp = tmp.replaceAll(Pattern.quote(newString), " XSYMBOLX ");
}
}
if(mediaMentions != null) {
for(int i = 0; i < mediaMentions.size(); i = i + 2){
arrPart = Arrays.copyOfRange(arr32, 4*mediaMentions.get(i), 4*mediaMentions.get(i+1));
newString = new String(arrPart, "UTF-32");
tmp = tmp.replaceAll(Pattern.quote(newString), " XMEDIAX ");
}
}
//regex cleaning
tmp = tmp.replaceAll("[()\\[\\]/%\\\\:#]", "")
.replaceAll("-?\\d*[.,]?\\d+", "xnumberx ")
.replaceAll("[°'´\"`.,’!?@-]", " ")
.replaceAll("[…]", " ")
// .replaceAll("\\d+", "number ")
.replaceAll("[0-9][(k|m)?mh?]?[ms]?", "")
.replaceAll("\\s+", " ")
.trim()
.toLowerCase();
cleanText = tmp;
}
public void printTweet() {
System.out.println("id: " + id
+ "\ntext: " + text
+ "\ncleanText: " + cleanText
+ "\nclassification: " + classification
+ "\nlang: " + lang);
}
public ArrayList<Integer> getUserMentions() {
return userMentions;
}
public void setUserMentions(ArrayList<Integer> userMentions) {
this.userMentions = userMentions;
}
public ArrayList<Integer> getHashtagMentions() {
return hashtagMentions;
}
public void setHashtagMentions(ArrayList<Integer> hashtagMentions) {
this.hashtagMentions = hashtagMentions;
}
public ArrayList<Integer> getSymbolMentions() {
return symbolMentions;
}
public void setSymbolMentions(ArrayList<Integer> symbolMentions) {
this.symbolMentions = symbolMentions;
}
public ArrayList<Integer> getUrlMentions() {
return urlMentions;
}
public void setUrlMentions(ArrayList<Integer> urlMentions) {
this.urlMentions = urlMentions;
}
public ArrayList<Integer> getMediaMentions() {
return mediaMentions;
}
public void setMediaMentions(ArrayList<Integer> mediaMentions) {
this.mediaMentions = mediaMentions;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getClassification() {
return classification;
}
public void setClassification(int classification) {
this.classification = classification;
}
public String getCleanText() {
return cleanText;
}
public void setCleanText(String cleanText) {
this.cleanText = cleanText;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
<file_sep>/**
* ReadZipFiles.java
* 19 apr 2017
*/
package lnu.agt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
/**
* @author jlnmsi
*
*/
public class ReadZipFiles {
public static ArrayList<File> findZipFiles(File zipDir) {
System.out.println("Reading from directory: "+zipDir.getAbsolutePath());
File[] files = zipDir.listFiles();
ArrayList<File> toReturn = new ArrayList<File>();
for (File f : files) {
if (f.getName().endsWith(".zip"))
toReturn.add(f);
// else
// System.out.println("Dropping file "+f);
}
// System.out.println("Zip files: "+toReturn.size());
return toReturn;
}
private static SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
public static ArrayList<JsonNode> readZipFile(File f) {
ArrayList<JsonNode> toReturn = null;
try {
InputStream input= new FileInputStream(f);
ZipInputStream zip = new ZipInputStream(input);
zip.getNextEntry();
Scanner sc = new Scanner(zip);
toReturn = new ArrayList<JsonNode>();
ObjectMapper mapper = new ObjectMapper();
while (sc.hasNextLine()) {
String tweet = sc.nextLine();
JsonNode jsonTweet = null;
try {
jsonTweet = mapper.readTree(tweet);
}
catch (JsonParseException e) {
System.err.println("Unable to parse Json string in file: "+f.getName());
System.err.println(tweet);
System.err.println("Drops it!!");
continue;
}
toReturn.add(jsonTweet);
}
sc.close();
// Prepare summary print
String fName = f.getName();
// System.out.println("\t"+fName+", Count: "+toReturn.size());
}catch(IOException e) {
e.printStackTrace();
}
return toReturn;
}
public static File saveTweetsZip(List<JsonNode> collectedTweets, File outDir, String fileName) {
// Build output string
StringBuilder buf = new StringBuilder();
String lineSep = System.getProperty("line.separator");
for (JsonNode tweet : collectedTweets) {
buf.append( tweet.toString() );
buf.append(lineSep);
}
File outFile = new File(outDir,fileName+".zip");
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(outFile));
ZipEntry e = new ZipEntry(fileName+".json");
out.putNextEntry(e);
byte[] data = buf.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try{
if(out!=null)
out.close();
}catch(Exception ex){
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
return outFile;
}
// public static long getTimeStamp(JsonNode tweet) {
// String text = tweet.get("timestamp_ms").asText();
// return Long.parseLong(text);
// }
}
<file_sep>/**
* EvalTextClassifier.java
* 30 apr 2017
*/
package lnu.agt.main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.Scanner;
import lnu.agt.AGTProperties;
import lnu.agt.ReadZipFiles;
import lnu.agt.TCArff;
import lnu.agt.TextClassifier;
import lnu.agt.TweetText;
import org.codehaus.jackson.JsonNode;
import weka.classifiers.Classifier;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
/**
* Goal: Evaluate my text classifier (constructed in TrainTextClassifier,
* using tcTraining) using tweets from dmTraining. I am using <NAME>'s
* idea for how to recreate a text classifier and certain parts of
* Antonio's ideas to present the evaluation result.
*
*
* @author jlnmsi
*
*/
public class EvalTextClassifier {
public static void main(String[] args) {
// Read DM training data ==> setup tweetClassification mapping
HashMap<Long,Integer> tweetClassification = readClassification();
// Read json tweets to setup tweetID-to-json mapping
HashMap<Long,JsonNode> jsonTweets = readJsonTweets();
TextClassifier textClassifier = new TextClassifier();
try {
for (long tID : tweetClassification.keySet()) {
int actual = tweetClassification.get(tID);
JsonNode tweet = jsonTweets.get(tID);
double predicted = textClassifier.getClassification(tweet);
evalStat(tweet, tID, predicted, actual);
}
} catch (Exception e) {
e.printStackTrace();
}
// Present summary
System.out.println("\nInstances: "+tweetClassification.size()+", Correct: "+correct+", Incorrect: "+incorrect);
printConfusionMatrix();
System.out.println("\nError Classifications \n"+misclassified);
}
private static HashMap<Long,JsonNode> readJsonTweets() {
Properties localProps = AGTProperties.getLocalProperties();
File zipFile = new File(localProps.getProperty("random1JsonZip"));
ArrayList<JsonNode> tweets = ReadZipFiles.readZipFile(zipFile);
HashMap<Long,JsonNode> jsonTweets = new HashMap<Long,JsonNode>();
for (JsonNode tweet : tweets) {
long tweetID = tweet.get("id").asLong();
jsonTweets.put(tweetID,tweet);
}
System.out.println("Read "+jsonTweets.size()+
" Json tweets from file "+zipFile.getAbsolutePath());
return jsonTweets;
}
private static HashMap<Long,Integer> readClassification() {
Properties agtProps = AGTProperties.getAGTProperties();
File trainingData = new File(agtProps.getProperty("dmTrainingData"));
HashMap<Long,Integer> tweetClassification = new HashMap<Long,Integer>();
Scanner scanner = null;
try {
scanner = new Scanner(trainingData);
while (scanner.hasNext()) {
String row = scanner.nextLine();
String[] items = row.split(" ");
int classification = Integer.parseInt(items[0]);
long tweetID = Long.parseLong(items[1]);
tweetClassification.put(tweetID, classification);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
System.out.println("Read "+tweetClassification.size()+
" tweet classifications from file "+trainingData.getAbsolutePath());
return tweetClassification;
}
private static int humanHuman = 0, botBot = 0, predHumanActualBot = 0, predBotActualHuman = 0;
private static int correct = 0, incorrect = 0;
private static StringBuilder misclassified = new StringBuilder();
public static void evalStat(JsonNode tweet, long tweetID, double predicted, int actual) {
int pred = (int) Math.round(predicted);
String text = tweet.get("text").asText();
text = text.replaceAll("\n", " ").replaceAll("\t", " ");
if (pred == actual){
correct++;
if( pred == 0 ){
humanHuman++;
}
else {
botBot++;
}
}
else { // Classification error
String predString = String.format("%.3f", predicted);
misclassified.append(actual + "\t" + predString + "\t" + tweetID + "\t" + text + "\n");
incorrect++;
if(pred == 1){
predBotActualHuman++;
}
else
predHumanActualBot++;
}
}
public static void printConfusionMatrix(){
System.out.println("\n***** Confusion Matrix *******");
final Object[][] table = new String[3][];
table[0] = new String[] { "\t", "actual human", "actual AGT" };
table[1] = new String[] { "predicted human", Integer.toString(humanHuman), Integer.toString(predHumanActualBot) };
table[2] = new String[] { "predicted AGT", Integer.toString(predBotActualHuman), Integer.toString(botBot) };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s\n", row);
}
}
}
<file_sep>project=AGT
deviceClassification=config/device_classification.txt
userProfiles=config/user_profiles.txt
userProfiles1=config/user_profiles_1.txt
allUserProfiles=config/all_user_profiles.txt
modelNB=config/filtNB.model
modelRF=config/filtRF.model
modelSMO=config/filtSMO.model
dummy=config/dummy.arff
dmTrainingData=docs/decisionMakerTrainingData.txt
dmTrainingARFF=config/decisionMakingTrainingSet.arff
tcTrainingData=docs/textClassifierTrainingData.txt
trainingData10k=docs/trainingData10k.txt
dmModel=config/dmRF.model
tcModel=config/tcRF.model
tcDummy=config/tcDummy.arff<file_sep>package lnu.agt;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;
import org.codehaus.jackson.JsonNode;
import weka.classifiers.Classifier;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader.ArffReader;
/**
* @author jofrab
*
*/
public class TextClassifier {
private Instances data;
private Classifier cls;
// Properties agtProps;
// String newModel = "";
public TextClassifier() {
try {
// New approach by <NAME>
TCArff arff = new TCArff();
data = arff.getDummyArff();
//initilize classifier
Properties agtProps = AGTProperties.getAGTProperties();
//String modelPath = agtProps.getProperty("modelRF"); // <NAME>
String modelPath = agtProps.getProperty("tcModel"); // <NAME>
cls = (Classifier) weka.core.SerializationHelper.read(modelPath);
System.out.println("TextClassifier: Used Classifier: "+cls.getClass().getName()+
", Model: "+modelPath);
}
catch (Exception e) {
e.printStackTrace();
}
}
// public TextClassifier(String model) throws Exception {
// agtProps = AGTProperties.getAGTProperties();
// //String path = agtProps.getProperty("dummy"); // <NAME>
// String path = agtProps.getProperty("tcDummy"); // <NAME>
//
// //load dummy dataset to get correct format of Instances data
// BufferedReader reader = new BufferedReader(new FileReader(path));
// ArffReader arff = new ArffReader(reader);
// data = arff.getData();
// reader.close();
//
// //initilize classifier
// String modelPath = agtProps.getProperty(model);;
// cls = (Classifier) weka.core.SerializationHelper.read(modelPath);
// }
// public void setClassifier(String model) throws Exception {
// cls = (Classifier) weka.core.SerializationHelper.read(model);
// }
public double getClassification(JsonNode tweet) {
try {
TweetText tweetText = new TweetText(tweet);
Instance inst = new DenseInstance(data.numAttributes());
inst.setValue(data.attribute(0), data.attribute(0).addStringValue(tweetText.getCleanText()));
data.add(0, inst);
return cls.distributionForInstance(data.instance(0))[1];
}
catch (Exception e) {
e.printStackTrace();
}
return -1.0;
}
// public Classifier getClassifier(){
// return cls;
// }
// Demonstrator
public static void main(String[] args) throws Exception {
System.out.println("Working Directory: "+System.getProperty("user.dir"));
Properties props = AGTProperties.getLocalProperties();
File ntsDir = new File( props.getProperty("ntsDir") );
TextClassifier tc = new TextClassifier();
Random rand = new Random();
ArrayList<File> ntsFiles = ReadZipFiles.findZipFiles( ntsDir );
ArrayList<JsonNode> tweets = ReadZipFiles.readZipFile(ntsFiles.get(rand.nextInt(ntsFiles.size())));
int i = 0;
while(i < 3) {
int r = rand.nextInt(tweets.size());
//tc.setClassifier("modelNB"); uncomment for Naive Bayesian instead
//tc.setClassifier("modelSMO"); uncomment for support vector machine instead
TweetText tweetText = new TweetText(tweets.get(r));
if(tweetText.getLang().equals("en")) {
i++;
System.out.println(tweetText.getText()
+"\n"+tweetText.getCleanText()
+"\nP(AGT) = "+tc.getClassification(tweets.get(r))
);
}
}
}
}
<file_sep>/**
* UserProfile.java
* 19 apr 2017
*/
package lnu.agt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 0 = tweetCount
* 1 = chiMin
* 2 = chiSec
* 3 = entropyHour
* 4 = entropyMin
* 5 = entropySec
* 6 = accountRep
* 7 = urlRatio
* 8 = hashtagRatio
* 9 = mentionRatio
* 10 = retweetRatio
* 11 = replyRatio
* 12 = mobileDevice
* 13 = webDevice
* 14 = appDevice
* 15 = miscDevice
* 16 = botDevice
* 17 = otherDevice
*
*
* @author jlnmsi
*
*/
public class UserProfile {
private static int MAX_TWEETS = 3200; // Used to normalize tweet count
public final long userID;
public final String userName;
private double[] userProperties;
private boolean isDontknow = false;
public UserProfile(long uID, String uName, double[] props) {
userID = uID;
userName = uName;
userProperties = props;
}
public UserProfile(List<AGTStatus> tweets){
AGTStatus latestTweet = tweets.get(0);
userID = latestTweet.userId;
userName = latestTweet.userName;
//Start collecting numeric profile properties
ArrayList<Double> profile = new ArrayList<Double>();
// Profile tweet count
double tweetCount = (0.0+tweets.size())/MAX_TWEETS;
profile.add(tweetCount);
// Appending all the other properties
ChiSquared chiSquared = new ChiSquared(tweets);
double[] pValues = chiSquared.getpValues(); // 2 values, minutes followed by seconds
append(profile,pValues);
Entropy entropy = new Entropy(tweets);
double[] entropyData = entropy.getEntropies(); // 3 values
append(profile,entropyData);
AccountProperties accProp = new AccountProperties(tweets);
double[] props = accProp.getProperties(); // 6 values
append(profile,props);
double[] deviceProfile = DeviceProfiler.getDeviceProfile(tweets); // 6 values
append(profile,deviceProfile);
//System.out.println(Arrays.toString(deviceProfile));
// Convert list to double array
userProperties = new double[profile.size()];
for (int i=0;i<profile.size();i++)
userProperties[i] = profile.get(i);
// System.out.println(this);
// System.out.println(asRow('\t'));
// System.exit(-1);
}
public void setDontknow(boolean dontknow) { isDontknow = dontknow; }
public boolean isDontKnow() { return isDontknow; }
public void append(List<Double> list, double[] data) {
for( double d: data)
list.add(d);
}
@Override
public String toString() {
return userID+", "+userName+" "+Arrays.toString(userProperties);
}
public String asRow(char itemSeparator) {
StringBuilder buf = new StringBuilder();
buf.append(userID);
buf.append(itemSeparator).append(userName);
for (double d : userProperties)
buf.append(itemSeparator).append(d);
return buf.toString();
}
public double[] getProperties() {
return userProperties;
}
}
<file_sep>/**
* AGTProperties.java
* 20 apr 2017
*/
package lnu.agt;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @author jlnmsi
*
*/
public class AGTProperties {
private static final String localProperties = "src/main/resources/local.properties";
private static final String agtProperties = "src/main/resources/agt.properties";
public static Properties getLocalProperties() {
Properties props = new Properties();
return getProperties(localProperties);
}
public static Properties getAGTProperties() {
return getProperties(agtProperties);
}
public static Properties getProperties(String propertyFilePath) {
Properties props = new Properties();
try {
props.load(new FileInputStream(propertyFilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
// Demonstrator
public static void main(String[] args) {
Properties agtProps = getAGTProperties();
System.out.println(agtProps);
System.out.println("Project name: "+agtProps.getProperty("project") );
Properties localProps = getLocalProperties();
System.out.println(localProps);
}
}
<file_sep>README for the AGT-Detector Project
Folder Structure
===================
We plan to use a simple folder structure with initially 3 folders
- agt: Classes that are buyilding blocks for our programs
- agt.main: Program entry points (Main classes)
- agt.trying_things: Temporary stuff that might be removed at any point
The config Folder
=================
A folder containg files used to configure the system. For example, Weka models
and user-to-profile data.
Properties
==========
Properties are saved in the resources folder. We have a workspace specific property
file (agt.properties) that defines entities and points to resources within the workspace.
Each one of us is also expected to have another property file (local.properties) that
that defines entities and points to resources on our own computers. For example, a property
ntsDir gives the path to our own NTS tweet folder, and twitterKeys gives the path to a property
file with ourown Twitter API keys.
<file_sep>package lnu.agt;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.math3.stat.inference.ChiSquareTest;
public class ChiSquared {
private final int BIN_SIZE = 15;
// p-value for minute, p-value for seconds
private double[] pValues = new double[2];
public ChiSquared(List<AGTStatus> tweets){
calculatepValues(tweets);
}
private void calculatepValues(List<AGTStatus> tweets){
long[] minutes = getMinutes(tweets);
long[] seconds = getSeconds(tweets);
int numOfTweets = tweets.size();
/* putting the data into bins */
long[] minutesBins = putIntoBins(minutes, 0, 60, BIN_SIZE);
long[] secondsBins = putIntoBins(seconds, 0, 60, BIN_SIZE);
/* getting the expected normal distributions */
double[] expectedMinutes = expectedDistribution(numOfTweets, minutesBins);
double[] expectedSeconds = expectedDistribution(numOfTweets, secondsBins);
ChiSquareTest test = new ChiSquareTest();
double pValMin = test.chiSquareTest(expectedMinutes, minutesBins);
double pValSec = test.chiSquareTest(expectedSeconds, secondsBins);
pValues[0] = pValMin;
pValues[1] = pValSec;
}
// returning the array with uniform distribution of seconds, minutes or hours
private static double[] expectedDistribution(int numOfTweets, long[] timeUnitsInBins){
double[] expected = new double[timeUnitsInBins.length];
for(int j = 0; j < timeUnitsInBins.length; j++)
expected[j] = (double) numOfTweets/timeUnitsInBins.length;
return expected;
}
/* Organizing the data into bins, data are seconds, minutes, hours
max and min 0 and 60 or 0 and 24, numBins is the number of bins one wants to have */
public static long[] putIntoBins(long[] data, int min, int max, int numBins) {
final long[] result = new long[numBins];
final double binSize = (max - min)/numBins;
for (double d : data) {
int bin = (int) ((d - min) / binSize);
if (bin < 0) { /* this data is smaller than min */ }
else if (bin >= numBins) { /* this data point is bigger than max */ }
else {
result[bin] += 1;
}
}
return result;
}
private static Calendar calendar = Calendar.getInstance();
private static long[] getSeconds(List<AGTStatus> tweets){
long[] seconds = new long[tweets.size()];
for(int i = 0; i < tweets.size(); i++){
Date time = new Date(tweets.get(i).createdAt);
calendar.setTime(time);
int sec = calendar.get(Calendar.SECOND);
// System.out.println(sec+"\t"+time);
seconds[i] = sec; //seconds
//seconds[i] = Integer.parseInt(asString.substring(17, 19)); //seconds
}
return seconds;
}
private static long[] getMinutes(List<AGTStatus> tweets){
long[] minutes = new long[tweets.size()];
for(int i = 0; i < tweets.size(); i++){
Date time = new Date(tweets.get(i).createdAt);
calendar.setTime(time);
int min = calendar.get(Calendar.MINUTE);
// System.out.println(min+"\t"+time);
minutes[i] = min;
// minutes[i] = Integer.parseInt(asString.substring(14, 16)); //minutes
}
return minutes;
}
public double[] getpValues(){
return pValues;
}
}
<file_sep>package lnu.agt;
import java.util.Date;
import java.util.List;
import twitter4j.Status;
public class Entropy {
// entropy for hours, entropy for minutes, entropy for seconds
private double[] listOfEntropies = new double[3];
public Entropy(List<AGTStatus> tweets){
calculateAllEntropies(tweets);
}
// calculating all entropy quantities
public void calculateAllEntropies(List<AGTStatus> tweets){
long[] timeDelaysH = new long[tweets.size() - 1];
long[] timeDelaysM = new long[tweets.size() - 1];
long[] timeDelaysS = new long[tweets.size() - 1];
timeDelays(tweets, timeDelaysH, timeDelaysM, timeDelaysS);
int binNumH = 500;
int[] binsH = new int[binNumH];
int numOfDelaysH = fillingBins(binsH, binNumH, timeDelaysH);
int binNumM = 60;
int[] binsM = new int[60];
int numOfDelaysM = fillingBins(binsM, binNumM, timeDelaysM);
int binNumS = 60;
int[] binsS = new int[60];
int numOfDelaysS = fillingBins(binsS, binNumM, timeDelaysS);
double entropyH = computeEntropy(binsH, binNumH, numOfDelaysH);
double entropyM = computeEntropy(binsM, binNumM, numOfDelaysM);
double entropyS = computeEntropy(binsS, binNumS, numOfDelaysS);
listOfEntropies[0] = entropyH;
listOfEntropies[1] = entropyM;
listOfEntropies[2] = entropyS;
}
// computing one entropy quantity
private static double computeEntropy(int[] bins, int binNum, int numOfDelays){
double entropy = 0;
for (int k = 0; k < bins.length; k++){
if (bins[k] != 0){
double p = (double) bins[k]/numOfDelays;
entropy += p*(Math.log(p)/Math.log(2));
}
else if (bins[k] == 0){
entropy += 0;
}
}
if(entropy != 0){
entropy = (entropy*(-1))/(Math.log(binNum)/Math.log(2)); // denominator is the maximum possible entropy, so we divide with it to get a value in [0,1]
}
return entropy;
}
// orginizing the data into the bins
private static int fillingBins(int[] bins, int binNum, long[] timeDelays){
int numOfDelays = 0;
for(int i = 0; i < timeDelays.length; i++){
if(timeDelays[i] < binNum && timeDelays[i] >= 0){
bins[Math.toIntExact(timeDelays[i])] += 1;
numOfDelays++;
}
}
return numOfDelays;
}
// calculating time delays for hours, minutes and seconds
private static void timeDelays(List<AGTStatus> tweets, long[] timeDelaysH, long[] timeDelaysM, long[] timeDelaysS){
for(int j = 0; j < tweets.size() - 1; j++){
// Date date1 = tweets.get(j + 1).getCreatedAt();
// Date date2 = tweets.get(j).getCreatedAt();
// long diff = date2.getTime() - date1.getTime();
long date1 = tweets.get(j + 1).createdAt;
long date2 = tweets.get(j).createdAt;
long diff = date2 - date1;
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
timeDelaysH[j] = diffHours;
timeDelaysM[j] = diffMinutes;
timeDelaysS[j] = diffSeconds;
}
}
public double[] getEntropies(){
return listOfEntropies;
}
}<file_sep>/**
* UserTweetsMain.java
* 19 apr 2017
*/
package lnu.agt.main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Properties;
import lnu.agt.AGTProperties;
import lnu.agt.ProfileGenerator;
import lnu.agt.ReadZipFiles;
import lnu.agt.UserProfile;
import org.codehaus.jackson.JsonNode;
/**
* @author jlnmsi
*
*/
public class UserTweetsMain {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Working Directory: "+System.getProperty("user.dir"));
Properties props = AGTProperties.getLocalProperties();
File ntsDir = new File( props.getProperty("ntsDir") );
ArrayList<File> ntsFiles = ReadZipFiles.findZipFiles( ntsDir );
ProfileGenerator profileGenerator = new ProfileGenerator(true);
for (File f : ntsFiles) {
if (!f.getName().startsWith("2017-03-15"))
continue;
ArrayList<JsonNode> tweets = ReadZipFiles.readZipFile(f);
for (JsonNode tweet : tweets) {
// Select users from English tweets
JsonNode user = tweet.get("user");
long userID = user.get("id").asLong();
String lang = tweet.get("lang").asText();
if ( lang.equals("en")) {
UserProfile uProfile = profileGenerator.getUserProfile(userID);
}
//System.out.println(userID);
}
System.out.println("DownloadCount: "+profileGenerator.getDownloadCount());
}
}
}
|
5acf6899165d1488dbbff17dc0a80a865bd3a4c0
|
[
"Markdown",
"Java",
"INI"
] | 11
|
Java
|
jlnmsi/AGT-Detector
|
336a47d23b10bf035fda3763c019f7802edf2bca
|
afaeee0da80e188c22c4718a8111ac2d82ed88f6
|
refs/heads/master
|
<file_sep>package io.github.nikkoes.belajarkotlin.application
import android.app.Application
import com.androidnetworking.AndroidNetworking
import io.github.nikkoes.belajarkotlin.utils.TypefaceUtil
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
TypefaceUtil.overrideFont(applicationContext, "SERIF", "fonts/montserat.ttf")
AndroidNetworking.initialize(this)
AndroidNetworking.enableLogging()
}
}<file_sep>package io.github.nikkoes.belajarkotlin.activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.SyncStateContract.Helpers.update
import android.util.Log
import android.view.MenuItem
import android.widget.Toast
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.ParsedRequestListener
import io.github.nikkoes.belajarkotlin.R
import io.github.nikkoes.belajarkotlin.adapter.PenghuniAdapter
import io.github.nikkoes.belajarkotlin.data.Constant
import io.github.nikkoes.belajarkotlin.model.Penghuni
import io.github.nikkoes.belajarkotlin.model.PenghuniResponse
import io.github.nikkoes.belajarkotlin.model.PostResponse
import kotlinx.android.synthetic.main.activity_form.*
import kotlinx.android.synthetic.main.activity_main.*
class FormActivity : AppCompatActivity() {
lateinit var item: Penghuni
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_form)
supportActionBar?.title = "Manajemen Penghuni Kosan"
supportActionBar?.setDisplayHomeAsUpEnabled(true)
initActionButton()
}
private fun initActionButton() {
if (intent.hasExtra("edit")) {
item = intent.getSerializableExtra("item") as Penghuni
nama.setText(item.nama)
hp.setText(item.hp)
alamat.setText(item.alamat)
if (item.gender.equals("Laki-laki", true)) {
gender.check(R.id.pria)
} else {
gender.check(R.id.wanita)
}
for (i in 0 until status.getCount()) {
if (status.getItemAtPosition(i).toString().equals(item.status, true)) {
status.setSelection(i)
break
}
}
if (item.fasilitas!!.contains("TV")) {
tv.setChecked(true)
}
if (item.fasilitas!!.contains("Kulkas")) {
kulkas.setChecked(true)
}
if (item.fasilitas!!.contains("AC")) {
ac.setChecked(true)
}
}
btn_simpan.setOnClickListener {
val sNama = nama.text.toString()
val sHp = hp.text.toString()
val genderId = gender.checkedRadioButtonId
var gender = ""
if (genderId == R.id.pria) {
gender = "Laki-laki"
} else if (genderId == R.id.wanita) {
gender = "Perempuan"
}
val sStatus = status.selectedItem.toString()
var fasilitas = ""
if (tv.isChecked) {
fasilitas = fasilitas + "TV, "
} else if (ac.isChecked) {
fasilitas = fasilitas + "AC, "
} else if (kulkas.isChecked) {
fasilitas = fasilitas + "Kulkas, "
}
val sAlamat = alamat.text.toString()
if (intent.hasExtra("edit")) {
AndroidNetworking.post(Constant.UPDATE_PENGHUNI + item.id)
.setPriority(Priority.MEDIUM)
.addBodyParameter("id_penghuni", item.id)
.addBodyParameter("nama", sNama)
.addBodyParameter("no_hp", sHp)
.addBodyParameter("gender", gender)
.addBodyParameter("status", sStatus)
.addBodyParameter("fasilitas", fasilitas)
.addBodyParameter("alamat", sAlamat)
.build()
.getAsObject(PostResponse::class.java, object :
ParsedRequestListener<PostResponse> {
override fun onResponse(response: PostResponse) {
if (response.status.equals("success", true)) {
Toast.makeText(
applicationContext,
"Berhasil menyimpan data..",
Toast.LENGTH_SHORT
).show()
finish()
}
}
override fun onError(anError: ANError?) {
Toast.makeText(
applicationContext,
"Response / Connection Failure ! ",
Toast.LENGTH_SHORT
).show()
}
})
} else {
AndroidNetworking.post(Constant.CREATE_PENGHUNI)
.setPriority(Priority.MEDIUM)
.addBodyParameter("nama", sNama)
.addBodyParameter("no_hp", sHp)
.addBodyParameter("gender", gender)
.addBodyParameter("status", sStatus)
.addBodyParameter("fasilitas", fasilitas)
.addBodyParameter("alamat", sAlamat)
.build()
.getAsObject(PostResponse::class.java, object :
ParsedRequestListener<PostResponse> {
override fun onResponse(response: PostResponse) {
if (response.status.equals("success", true)) {
Toast.makeText(
applicationContext,
"Berhasil menambahkan data..",
Toast.LENGTH_SHORT
).show()
finish()
}
}
override fun onError(anError: ANError?) {
Toast.makeText(
applicationContext,
"Response / Connection Failure ! ",
Toast.LENGTH_SHORT
).show()
}
})
}
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
}
<file_sep>package io.github.nikkoes.belajarkotlin.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import io.github.nikkoes.belajarkotlin.R
import io.github.nikkoes.belajarkotlin.model.Penghuni
import kotlinx.android.synthetic.main.item_penghuni.view.*
class PenghuniAdapter(private val context: Context) : RecyclerView.Adapter<PenghuniAdapter.Holder>() {
private var listItem: ArrayList<Penghuni> = ArrayList()
var mOnItemClickListener: OnItemClickListener? = null
interface OnItemClickListener {
fun onItemClick(position: Int)
fun onDelete(position: Int)
}
fun setOnItemClickListener(mItemClickListener: OnItemClickListener) {
this.mOnItemClickListener = mItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PenghuniAdapter.Holder {
return Holder(
LayoutInflater.from(parent.context).inflate(R.layout.item_penghuni, parent, false
)
)
}
override fun getItemCount(): Int = listItem.size
override fun onBindViewHolder(holder: PenghuniAdapter.Holder, position: Int) {
val penghuni: Penghuni? = listItem[position]
holder.view.nama.text = penghuni?.nama
holder.view.status.text = penghuni?.status
holder.view.hp.text = penghuni?.hp
holder.view.gender.text = penghuni?.gender
holder.view.btn_edit.setOnClickListener {
mOnItemClickListener?.onItemClick(position)
}
holder.view.btn_delete.setOnClickListener {
mOnItemClickListener?.onDelete(position)
}
}
class Holder(val view: View) : RecyclerView.ViewHolder(view)
fun add(item: Penghuni) {
listItem.add(item)
notifyItemInserted(listItem.size + 1)
}
fun addAll(listItem: List<Penghuni>) {
for (item in listItem) {
add(item)
}
}
fun removeAll() {
listItem.clear()
notifyDataSetChanged()
}
fun swap(datas: List<Penghuni>) {
if (listItem.size >= 0)
listItem.clear()
listItem.addAll(datas)
notifyDataSetChanged()
}
fun getItem(pos: Int): Penghuni {
return listItem[pos]
}
fun setFilter(list: List<Penghuni>) {
listItem = ArrayList<Penghuni>()
listItem.addAll(list)
notifyDataSetChanged()
}
fun getListItem(): List<Penghuni> {
return listItem
}
}<file_sep>package io.github.nikkoes.belajarkotlin.utils
import android.text.TextUtils
import android.util.Patterns
import android.view.View
import android.widget.EditText
import com.google.gson.Gson
import org.json.JSONException
import org.json.JSONObject
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class CommonUtil {
companion object {
lateinit var gson: Gson
fun uppercaseString(str: String): String {
val ch = str.toCharArray()
for (i in 0 until str.length) {
if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') {
if (ch[i] in 'a'..'z') {
ch[i] = (ch[i] - 'a' + 'A'.toInt()).toChar()
}
} else if (ch[i] in 'A'..'Z')
ch[i] = ch[i] + 'a'.toInt() - 'A'.toInt()
}
return String(ch)
}
}
fun formatStringToDate(tanggal: String, fromFormat: String, toFormat: String) : String {
val fromString = SimpleDateFormat(fromFormat, Locale.ENGLISH)
val fromDate = SimpleDateFormat(toFormat, Locale.ENGLISH)
var date: Date? = null
try {
date = fromString.parse(tanggal)
} catch (e: ParseException) {
e.printStackTrace()
}
return fromDate.format(date)
}
fun formatDateToString(date: Date, format: String): String {
val df = SimpleDateFormat(format, Locale.ENGLISH)
return df.format(date)
}
fun currentDate(format: String): String {
val tanggal: String
val date = Date()
val dateFormat = SimpleDateFormat(format, Locale.ENGLISH)
val tz = TimeZone.getTimeZone("Asia/Jakarta")
dateFormat.timeZone = tz
tanggal = dateFormat.format(date)
return tanggal
}
fun currentTime(format: String): String {
val jam: String
val date = Date()
//val dateFormat = SimpleDateFormat("hh:mm a", Locale.ENGLISH)
val dateFormat = SimpleDateFormat(format, Locale.ENGLISH)
val tz = TimeZone.getTimeZone("Asia/Jakarta")
dateFormat.timeZone = tz
jam = dateFormat.format(date)
return jam
}
fun convertHari(num: Int): String {
var hari = ""
when (num) {
1 -> hari = "Senin"
2 -> hari = "Selasa"
3 -> hari = "Rabu"
4 -> hari = "Kamis"
5 -> hari = "Jumat"
6 -> hari = "Sabtu"
0 -> hari = "Minggu"
}
return hari
}
fun convertStringToJson(parameter: Array<String>, value: Array<String>): JSONObject {
val jsonObject = JSONObject()
for (i in parameter.indices) {
try {
jsonObject.put(parameter[i], value[i])
} catch (e: JSONException) {
e.printStackTrace()
}
}
return jsonObject
}
fun JsonToString(obj: Any): String {
return gson.toJson(obj)
}
fun <T> stringToJson(json: String, classOfT: Class<T>): T {
return gson.fromJson(json, classOfT)
}
fun formatPriceIndonesia(price: Double?): String {
val kursIndonesia = DecimalFormat.getCurrencyInstance() as DecimalFormat
val formatRp = DecimalFormatSymbols()
formatRp.currencySymbol = "Rp. "
formatRp.monetaryDecimalSeparator = ','
formatRp.groupingSeparator = '.'
kursIndonesia.decimalFormatSymbols = formatRp
return kursIndonesia.format(price)
}
fun validateEmptyEntries(fields: ArrayList<View>): Boolean {
var check = true
for (i in fields.indices) {
val currentField = fields[i] as EditText
if (currentField.text.toString().length <= 0) {
currentField.error = "Please fill out this field"
check = false
}
}
return check
}
fun isValidEmail(target: CharSequence): Boolean {
return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches()
}
}
<file_sep>package io.github.nikkoes.belajarkotlin.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class Penghuni (
@SerializedName("id") val id: String?,
@SerializedName("nama") val nama: String?,
@SerializedName("no_hp") val hp: String?,
@SerializedName("gender") val gender: String?,
@SerializedName("status") val status: String?,
@SerializedName("fasilitas") val fasilitas: String?,
@SerializedName("alamat") val alamat: String?
) : Serializable<file_sep>package io.github.nikkoes.belajarkotlin.utils
import android.content.Context
import android.net.ConnectivityManager
class NetworkUtil {
companion object {
fun isConnect(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return if (activeNetworkInfo != null) {
activeNetworkInfo.isConnected || activeNetworkInfo.isConnectedOrConnecting
} else {
false
}
}
}
}<file_sep>package io.github.nikkoes.belajarkotlin.data
class Constant {
companion object {
private val WEB_URL = "https://kosankoding.co.id/kosanku/"
private val WEB_URL_API = WEB_URL + "public/"
val API_PENGHUNI = WEB_URL_API + "penghuni/"
val GET_PENGHUNI = API_PENGHUNI
val CREATE_PENGHUNI = API_PENGHUNI
val UPDATE_PENGHUNI = API_PENGHUNI + "edit/"
val DELETE_PENGHUNI = API_PENGHUNI + "delete/"
}
}<file_sep>package io.github.nikkoes.belajarkotlin.model
import com.google.gson.annotations.SerializedName
data class PenghuniResponse(
@SerializedName("status") val status: String?,
@SerializedName("data") val data: ArrayList<Penghuni>
)<file_sep>package io.github.nikkoes.belajarkotlin.activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.widget.Toast
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.JSONObjectRequestListener
import com.androidnetworking.interfaces.ParsedRequestListener
import com.google.gson.Gson
import io.github.nikkoes.belajarkotlin.R
import io.github.nikkoes.belajarkotlin.adapter.PenghuniAdapter
import io.github.nikkoes.belajarkotlin.data.Constant
import io.github.nikkoes.belajarkotlin.model.Penghuni
import io.github.nikkoes.belajarkotlin.model.PenghuniResponse
import io.github.nikkoes.belajarkotlin.model.PostResponse
import io.github.nikkoes.belajarkotlin.utils.DialogUtil
import kotlinx.android.synthetic.main.activity_form.*
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
var list = ArrayList<Penghuni>()
lateinit var adapter: PenghuniAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.title = "Data Penghuni Kosan"
initRecyclerView()
initActionButton()
}
override fun onResume() {
super.onResume()
loadItems()
}
private fun loadItems() {
DialogUtil.openDialog(this)
AndroidNetworking.get(Constant.GET_PENGHUNI)
.setPriority(Priority.MEDIUM)
.build()
.getAsObject(
PenghuniResponse::class.java,
object : ParsedRequestListener<PenghuniResponse> {
override fun onResponse(response: PenghuniResponse) {
DialogUtil.closeDialog()
if (response.status.equals("success")) {
adapter.swap(response.data)
} else {
Toast.makeText(
applicationContext,
"Data tidak ditemukan ! ",
Toast.LENGTH_SHORT
).show()
}
}
override fun onError(anError: ANError?) {
Log.e("response: ", anError?.errorBody)
Toast.makeText(
applicationContext,
"Response / Connection Failure ! ",
Toast.LENGTH_SHORT
).show()
DialogUtil.closeDialog()
}
})
}
private fun initActionButton() {
btn_add.setOnClickListener {
startActivity(Intent(this, FormActivity::class.java))
}
}
private fun initRecyclerView() {
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter = PenghuniAdapter(applicationContext)
adapter.setOnItemClickListener(object : PenghuniAdapter.OnItemClickListener {
override fun onItemClick(position: Int) {
val intent = Intent(applicationContext, FormActivity::class.java)
intent.putExtra("edit", true)
intent.putExtra("item", adapter.getItem(position))
startActivity(intent)
}
override fun onDelete(position: Int) {
delete(position)
}
})
recyclerView.adapter = adapter
}
private fun delete(position: Int) {
DialogUtil.openDialog(this)
AndroidNetworking.post(Constant.DELETE_PENGHUNI + adapter.getItem(position).id)
.setPriority(Priority.MEDIUM)
.build()
.getAsObject(PostResponse::class.java, object :
ParsedRequestListener<PostResponse> {
override fun onResponse(response: PostResponse) {
DialogUtil.closeDialog()
if (response.status.equals("success", true)) {
Toast.makeText(
applicationContext,
"Berhasil menghapus data..",
Toast.LENGTH_SHORT
).show()
loadItems()
}
}
override fun onError(anError: ANError?) {
Toast.makeText(
applicationContext,
"Response / Connection Failure ! ",
Toast.LENGTH_SHORT
).show()
DialogUtil.closeDialog()
}
})
}
}
|
34c9002f2baf37c592952e9e36c6f0baa880a483
|
[
"Kotlin"
] | 9
|
Kotlin
|
NikkoES/base-android-kotlin
|
0180169c9d59ed6508da1a1f1bf59fc508b60c4b
|
90adc06f7321a28362e38c196c0e7bebd87ad43d
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en" id="theHTML">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
<script src="https://use.fontawesome.com/75360aa574.js"></script>
<title><NAME> - Scientist</title>
<style>
html{
background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-position: 100% 0%;
background-repeat: no-repeat;
background-attachment: fixed;
background-image: url('http://www.mr-ecology.com/wp-content/uploads/2017/09/background.jpg');
}
#header {
overflow: hidden;
background-size: cover;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-position: 100% 0%;
background-repeat: no-repeat;
background-attachment: fixed;
background-image: url('http://www.mr-ecology.com/wp-content/uploads/2017/09/background.jpg');
transition: all .3s linear;
}
#header-background-screen {
background-color: #159632;
background-color: rgba(0, 168, 38, .75);
background-blend-mode: color-burn;
background-position: 100% 0%;
background-repeat: no-repeat;
background-attachment: fixed;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
transition: opacity .3s linear;
}
#header-content-holder {
position: fixed;
top: 0;
right: 1em;
z-index: 50;
overflow: hidden;
}
#background-screen {
position: fixed;
width: 100vw;
height: 100vh;
background-color: rgba(255, 255, 255, .8);
background-blend-mode: screen;
z-index: 1;
pointer-events: none;
}
#background-screen::before{
content: '';
position: fixed;
top: -10em;
right: -2em;
width: 100%;
height: 100em;
background: -webkit-linear-gradient(left, transparent 20%, rgba(21, 150, 50, 1));
background: -o-linear-gradient(left, transparent 20%, rgba(21, 150, 50, 1));
background: -moz-linear-gradient(left, transparent 20%, rgba(21, 150, 50, 1));
background: linear-gradient(to right, transparent 20%, rgba(21, 150, 50, 1));
pointer-events: none;
opacity: 1;
transition: opacity .4s linear;
transform: rotate(5deg);
background-blend-mode: color-burn;
z-index: 2;
pointer-events: none;
}
</style>
</head>
<body <?php body_class();?> id="theBody">
<header id="header">
<div id="header-background-screen"></div>
<div id="header-content-holder">
<div id="menu-button">
<div></div>
<div></div>
<div></div>
</div>
<div id="avatar">
<?php echo get_avatar(get_the_author_meta('ID')); ?>
</div>
<h1 id ="author-name">
<?php
$f_name = get_the_author_meta('first_name');
$l_name = get_the_author_meta('last_name');
echo $f_name . ' ' . $l_name;
?>
</h1>
<div id="floaty-leaf"></div>
<nav id="navbar">
<?php wp_nav_menu(array('theme_location' => 'primary')); ?>
</nav>
</div>
</header>
<div id="background-screen"></div>
<div id="header-border"></div>
<div id="wrapper">
<main id="main"><file_sep><?php get_header(); ?>
<div class = "page-title"><h1>About Me</h1></div>
<article class="about-me">
<img class = "about-me" alt="A profile image of myself identifying native plants on the outskirts of Seattle." src= "http://mr-ecology.com/wp-content/uploads/2017/09/about-me.jpg">
<p>I’m currently working at a commercial Food and Environmental Science laboratory, but I have a wide array of professional interests. From urban agriculture to island ecology, I’m interested in how people interact with plants and ecosystems. More recently I’ve become interested in issues of food safety and how containments end up in what we eat. </p>
<h2>Education</h2>
<div class="about-me-school"><p>University of Wisconsin Eau Claire ♦ August 2015</p></div>
<p class="about-me-degree">♦B.S. in Ecology and Environmental Biology</p>
<div class="about-me-school"><p>University of Washington Professional and Continuing Education ♦ June 2016</p></div>
<p class="about-me-degree">♦Certificate in Wetland Science and Management</p>
</article>
<?php get_footer(); ?><file_sep><?php get_header(); ?>
<div class = "page-title" id='resume-page'>
<h1>Resume</h1>
<button id="printResume">Print</button>
</div>
<div class="resume-background">
<div class="float">
<div class="resume-name"><NAME></div>
<div class="resume-contact">
<address class="resume-address">
<div>1512 Boylston Ave #205 </div>
<div>♦ Seattle, WA 98122</div>
</address>
<div class="resume-message">
<div><EMAIL> </div>
<div>♦ 360-260-5417</div>
</div>
</div>
</div>
<div class="row"><h3 class="resume-heading">Education</h3></div>
<div class="resume-education">
<div class="heading-name">University of Wisconsin - Eau Claire<div> ♦ August 2015</div></div>
</div>
<div class="resume-education">
♦ Bachelor of Science -Ecology and Environmental Biology
</div>
<div class="resume-education">
<div class="heading-name">University of Washington – Professional & Continuing Education<div> ♦ June 2017</div></div>
</div>
<div class="resume-education">
♦ Certificate in Wetland Science & Management
</div>
<div class="row">
<h3 class ="resume-heading">Research</h3>
</div>
<div class="row">
<div class="heading-name">Narbeck Wetland Sanctuary Water Quality Assessment</div>
</div>
<div class="row">
<div class="resume-paragraph">
Designed and implemented a survey of water quality in the Narbeck Wetland Sanctuary. Samples were taken from five separate ponds that are hydrologically connected through leaky berms, but are otherwise separate. After collection samples were analyzed in a lab for five water quality parameters (alkalinity, temperature, conductivity, turbidly, and pH). Linear regressions were used to look for patterns in the data across the five ponds.
</div>
</div>
<div class="row">
<div class="heading-name">Studies in Tropical Environments</div>
</div>
<div class="row">
<div class="resume-paragraph">
Two weeks exploring the Galapagos Archipelago. Studied a wide variety of ecosystems and how various organizations were performing conservation biology. Interacted with locals to learn how they viewed their environment and what they considered important.<br>
Four days exploring Cloud Forest in mountains of Ecuador under field guide Nelson Jaramillo. Discussed plant communities and how they interact with wildlife to form a unique ecosystem.
</div>
</div>
<div class="row">
<div class="heading-name">Collaborative Research in Biology</div>
</div>
<div class="row">
<div class="resume-paragraph">
Worked within a team to develop and perform a study on the extent of earthworm invasion in the Boundary Waters Canoe Area Wilderness. Study included collecting worm specimens, soils samples, leaf litter, and assessing percent plant coverage of sample sites. Used R statistical software to perform both analysis of variants (ANOVAs) and Structural Equation Modeling to analyze the collected data.
</div>
</div>
<div class="row">
<h3 class ="resume-heading">Skills</h3>
</div>
<div class="row">
<div class="heading-name">Field</div>
<ul>
<li>Identification of herbaceous and woody plants in multiple plant communities (wetlands, riparian forest, wet and dry mesic forests) using dichotomous keys, field guides, and personal knowledge.</li>
<li>Preparation of soil samples for analyses of nitrogen and organic content.</li>
<li>Use of Munsell charts and soil texture classification methodology.</li>
<li>Wetland identification and delineation using data gathered in an office and on site.</li>
<li>Navigating too sites using maps, landmarks, and a GPS.</li>
</ul>
</div>
<div class="row">
<div class="heading-name">Lab</div>
<ul>
<li>Use of proximal and quantitave chemistry to determine the nutritional content of food, such as salt, moisture, fiber, and cellulose.</li>
<li>Analysis of water samples for various quality parameters, such as alkalinity, chloride, chlorine, hardness, turbidity, pH, and chlorophyll content.</li>
<li>Preparation of and cleaning samples for LCMS/MS and GC/MS via QUECHERS methodology and SPE techniques</li>
<li>Ability to follow standard lab quality assurance including: sample tracking, LIMS input, proper data handling, and use of duplicates and spikes.</li>
<li>Use and maintenance of common lab equipment including: pH meters, hot water baths, vacuum ovens, hot/stir plates, photospectrometers, and a variety of glass wares.</li>
<li>Use of PCR to analyze genotypic changes in fruit fly populations.</li>
<li>Investigation of how CO2 concentrations affect photosynthetic rates of C3 (Vicia faba) and C4 plants (Zea mays) using controlled atmospheres and handheld chlorophyll detectors.</li>
<li>Plating and transferring nematodes based on physical characteristics</li>
</ul>
<br>
</div>
<div class="row">
<h3 class="resume-heading">Professional History</h3>
</div>
<div class="row">
<div class="resume-employment">
IEH Analytical<br>
3927 Aurora Ave N #202<br>
Seattle, WA 98103<br>
(206) 632-2715<br>
03/24/2016 – Current
</div>
<div class="resume-position">
<div class="position-heading">Laboratory Analyst</div>
Proximate analysis<br>
Water quality analysis<br>
Data management<br>
General lab maintenance
</div>
</div>
<div class="row">
<div class="resume-employment">
T&L Nursery<br>
13245 Woodinville-Redmond Rd NE<br>
Redmond, WA 98052<br>
(425) 885-5050<br>
07/06/2015 – 02/26/2016
</div>
<div class="resume-position">
<div class="position-heading">Section Grower</div>
Greenhouse management<br>
Fertility management<br>
IPM application<br>
Irrigation and minor mechanical
</div>
</div>
<div class="row">
<div class="resume-employment">
Trefoil Cultural and Environmental<br>
1965 W Highview Drive<br>
Sauk Rapids, MN 56379<br>
please request contact info<br>
05/30/07 – 08/28/2014
</div>
<div class="resume-position">
<div class="position-heading">Archaeological Assistant</div>
Excavation and artifact handling<br>
Wetland identification via geographical conditions<br>
Map scanning and editing using GSI software<br>
Data entry and clerical tasks
</div>
</div>
</div>
<?php get_footer(); ?><file_sep>//==================================//
//print.js for MARothaus Theme
//==================================//
//event listeners for functions
document.getElementById('printResume').addEventListener('click', printPage);
//==================================//
//To print the resume
function printPage(){
window.print();
}<file_sep><?php get_header(); ?>
<?php
//code by Senador from https://stackoverflow.com/questions/4323411/how-can-i-write-to-console-in-php
//This function allows me to debug by sending to console
function console( $data ) {
$output = $data;
if ( is_array( $output ) )
$output = implode( ',', $output);
echo "<script>console.log( 'Debug Objects: " . $output . "' );</script>";
}
//Code composed based on two primary sources
//https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
//http://www.freecontactform.com/email_form.php
//variable builds errors to be echoed;
global $echo_to_dom;
$echo_to_dom = '<p>Please correct the following fields:</p>';
//regex tests
$regexname = '/^[a-zA-Z0-9.\-() ]{3,150}+$/';
$regexphone = '/^[0-9.\-()]{10,13}+$/';
$regexquestion = '/^[a-zA-Z0-9#$!%^&*()+=\-\[\]\';,.\/|":<>?~\\\\ \n\r]{10,10000}+$/';
$regexemail = '/^[a-zA-Z0-9_.+\-]+@[a-zA-Z0-9\-.]+\.[a-zA-Z0-9]{2,4}$/';
//regexEmail character class written by https://www.123contactform.com/jquery-contact-form.htm
//user posted variables
$name = $_POST['fName'];
$email = $_POST['fEmail'];
$phone = $_POST['fPhone'];
$question = $_POST['fQuestion'];
//php mailer variables
$to = '<EMAIL>';
$subject = 'Contact Request from Website!';
$message_body = 'Name: ' . $name . ' Email: ' . $email . ' Phone: ' . $phone . ' Question: ' . $question;
$headers = 'From: ' . $email . ' Reply-To: ' . $email;
//reCaptcha variables written with the help of https://codeforgeek.com/2014/12/google-recaptcha-tutorial/
$secretKey = '<KEY>';
$captcha=$_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
//Form checks if all variables meet conditions
if(empty($name) && empty($email) && empty($phone) && empty($question) && empty($human)){
console('do not show errors');
}else{
if(intval($responseKeys["success"]) !== 1){
$echo_to_dom .= '<p>Human verification was not met.</p>';
//Gives a separate error for each problem
if(!preg_match($regexemail, $email) || empty($email)){
$echo_to_dom .= '<p>The email you have entered is not valid.</p>';}
if(empty($name) || !preg_match($regexname, $name)){
$echo_to_dom .= '<p>The name is not invalid</p>';}
if(!preg_match($regexphone, $phone) && !empty($phone)){
$echo_to_dom .= '<p>The phone number must be valid or left blank</p>';}
if(!preg_match($regexquestion, $question) || empty($question)){
$echo_to_dom .= '<p>The question field must not contian any special characters such as {} or <></p>';}
}else{ //Test all variables
if(!preg_match($regexemail, $email) || empty($email) || empty($name) || !preg_match($regexname, $name) || (!preg_match($regexphone, $phone) && !empty($phone)) || !preg_match($regexquestion, $question) || empty($question)){
//Gives a separate error for each problem
if(!preg_match($regexemail, $email) || empty($email)){
$echo_to_dom .= '<p>The email you have entered is invalid.</p>';}
if(empty($name) || !preg_match($regexname, $name)){
$echo_to_dom .= '<p>The name is invalid</p>';}
if(!preg_match($regexphone, $phone) && !empty($phone)){
$echo_to_dom .= '<p>The phone number must be valid or left blank</p>';}
if(!preg_match($regexquestion, $question) || empty($question)){
$echo_to_dom .= '<p>The question field must not contian any special characters such as brackets</p>';}
}else{ //ready to go!
$sent = mail($to, $subject, $message_body, $headers);
if($sent){ //message sent!
$echo_to_dom = '<p>Thank you! the author will contact you shortly.</p>';
console('the message is sending!');
}else{ //message wasn't sent
$echo_to_dom = '<p>An error occurred with our servers. Please try again later!</p>';
console('the message has not sent!');
}
}
}
}
?>
<div class = "page-title"><h1>Contact the Author</h1></div>
<div class="validateSend" id="errorBox"><?php echo $echo_to_dom; ?></div>
<form name="contactMe" id="contactMe" method="post" action="<?php the_permalink(); ?>">
<div class="formFlex">
<div class="formLabel" id="fNameLabel">
<label for="fName">Name:*</label>
</div>
<div class="formField">
<input type="text" name="fName" id="fName" value="<?php echo esc_attr($_POST['fName']); ?>">
</div>
</div>
<div class="formFlex">
<div class="formLabel" id="fEmailLabel">
<label for="fEmail">Email:*</label>
</div>
<div class="formField">
<input type="text" name="fEmail" id="fEmail" value="<?php echo esc_attr($_POST['fEmail']); ?>">
</div>
</div>
<div class="formFlex">
<div class="formLabel" id="fPhoneLabel">
<label for="fPhone">Phone:</label>
</div>
<div class="formField">
<input type="tel" name="fPhone" id="fPhone" value="<?php echo esc_attr($_POST['fPhone']); ?>">
</div>
</div>
<div class="row"><label for="fQuestion" class="textareaQuestion" id="fQuestionLabel">Question:*</label></div>
<div class="row">
<textarea id="fQuestion" name="fQuestion" placeholder="Please type a brief question for Matt, and watch for your confirmation email!"><?php echo esc_textarea($_POST['fQuestion']); ?></textarea>
</div>
<input type="hidden" name="submitted" value="1">
<div class="row">
<button type="submit" id="submitForm" name="submitForm">Send</button></div>
<div class="formFlex">
<div class="g-recaptcha" data-sitekey="<KEY>"></div>
</div>
</form>
<?php get_footer(); ?><file_sep><?php get_header(); ?>
<?php if(have_posts()) : ?>
<div class = "page-title"><h1><?php $category = get_the_category(); echo $category[0]->cat_name; ?></h1></div>
<?php while(have_posts()) : the_post();
if(has_category('blog')) : ?>
<article class ="postBlog">
<?php if(has_post_thumbnail()):?>
<div class="postThumb"><?php the_post_thumbnail('thumbnail');?></div>
<?php endif; ?>
<a href="<?php the_permalink()?>"><h3><?php the_title(); ?></h3></a>
<small><?php edit_post_link() ?></small>
<?php the_content(); ?>
<hr>
<div class="flexPost">
<p class="postTime">Posted on <?php the_time('F j, Y') ?></p>
<div class="openPost" id="<?php the_ID() ?>"><i class="fa fa-plus-square" aria-hidden="true"></i></div>
</div>
<aside class="postCollapse" id="post_<?php the_ID() ?>" style = "height:4em;">
<div id ="content_<?php the_ID() ?>" class="hideContent">
<?php
global $withcomments;
$withcomments = 1;
comments_template('/comments.php', true); ?>
</div>
</aside>
</article>
<?php endif;
if(has_category('publications')) : ?>
<article class ="postPub">
<?php if(has_post_thumbnail()):?>
<div class="postThumb"><?php the_post_thumbnail('thumbnail');?></div>
<?php endif; ?>
<a href="<?php the_permalink()?>"><cite><?php the_title(); ?></cite></a>
<cite class="pubDetails"><?php the_secondary_title(); ?></cite>
<small><?php edit_post_link() ?></small>
<div class="flexPost">
<p class="postTime">Published on <?php the_time('F j, Y') ?></p>
<div class="openPost" id="<?php the_ID() ?>"><i class="fa fa-plus-square" aria-hidden="true"></i></div>
</div>
<hr>
<aside class="pubCollapse" id="post_<?php the_ID() ?>" style = "height:4em;">
<div id ="content_<?php the_ID() ?>" class="hideContent">
<?php the_content(); ?>
</div>
</aside>
</article>
<?php
endif;
endwhile;
endif; ?>
<?php get_footer(); ?><file_sep># [mr-ecology.com][website-link]
### My first WordPress site/theme built from scratch.
---
Unlike other WordPress themes, this one was not built to be used across any website, and in fact has custom pages designed and coded for the website author.
![This man is named <NAME>. He is the author of mr-ecology.com and an environmental scientist.][web-image]
This site was an experiment in WordPress and PHP. Anything that is not a wordPress function was custom code developed by the frontend developer (@booellean).
In short, this a small experiment in WordPress and PHP. Fixes will be implemented to make it more cross browser compatible as time goes on.
[website-link]: http://mr-ecology.com
[web-image]: http://www.missellepope.com/images/website-matt-rothaus.jpg
<file_sep>//==================================//
//verify.js for contact form in MARothaus Theme
//==================================//
//global variables
var errorMessage;
//==================================//
//event listeners
window.addEventListener('load', verifyFillContents);
document.getElementById('errorBox').addEventListener('click', closeBox);
//still need the div name - document.getElementById('').addEventListener('click',resetMessages);
//==================================//
//function verifies content in form is correct
function verifyFillContents(){
var fNameField = document.getElementById('fName');
var fNameLabel = document.getElementById('fNameLabel');
var fName = fNameField.value;
var fEmailField = document.getElementById('fEmail');
var fEmailLabel = document.getElementById('fEmailLabel');
var fEmail = fEmailField.value;
var fPhoneField = document.getElementById('fPhone');
var fPhoneLabel = document.getElementById('fPhoneLabel');
var fPhone = fPhoneField.value;
var fQuestionField = document.getElementById('fQuestion');
var fQuestionLabel = document.getElementById('fQuestionLabel');
var fQuestion = fQuestionField.value;
var errorBox= document.getElementById('errorBox');
if(fName === '' && fEmail === '' && fPhone === '' && fQuestion === '' ){
errorBox.style.display = 'none';
}else {
//This area is to change form input and label stylings based on incorrect data
var regexName = /^[a-zA-Z0-9.\-() ]{3,150}$/;
var regexPhone = /^[0-9.\-()]{10,13}$/;
var regexEmail = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//regexEmail character class written by https://www.123contactform.com/jquery-contact-form.htm
var regexQuestion = /^[a-zA-Z0-9.,\\/\-()\[\]\n\r+=_~`;:"'?!@#$%\^&* ]{10,1000}$/;
if(!regexName.test(fName) || fName == ''){
fNameField.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fNameField.style.borderColor = '#cc4747';
fNameLabel.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fNameLabel.style.borderColor = '#cc4747';
fNameLabel.style.color = '#c41f1f';
}else{
fNameField.style.boxShadow = '';
fNameField.style.borderColor = '';
fNameLabel.style.boxShadow = '';
fNameLabel.style.borderColor = '';
fNameLabel.style.color = '';
}
if(!regexPhone.test(fPhone)){
fPhoneField.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fPhoneField.style.borderColor = '#cc4747';
fPhoneLabel.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fPhoneLabel.style.borderColor = '#cc4747';
fPhoneLabel.style.color = '#c41f1f';
}else{
fPhoneField.style.boxShadow = '';
fPhoneField.style.borderColor = '';
fPhoneLabel.style.boxShadow = '';
fPhoneLabel.style.borderColor = '';
fPhoneLabel.style.color = '';
}
if(!regexEmail.test(fEmail) || fEmail ===''){
fEmailField.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fEmailField.style.borderColor = '#cc4747';
fEmailLabel.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fEmailLabel.style.borderColor = '#cc4747';
fEmailLabel.style.color = '#c41f1f';
}else{
fEmailField.style.boxShadow = '';
fEmailField.style.borderColor = '';
fEmailLabel.style.boxShadow = '';
fEmailLabel.style.borderColor = '';
fEmailLabel.style.color = '';
}
if(!regexQuestion.test(fQuestion) || (fQuestion.length>0 && fQuestion.length<=11)){
fQuestionField.style.boxShadow = 'inset 0 0 1.7em .3em #cc4747';
fQuestionField.style.borderColor = '#cc4747';
fQuestionLabel.style.boxShadow = 'inset 0 0 .4em .2em #cc4747';
fQuestionLabel.style.borderColor = '#cc4747';
fQuestionLabel.style.color = '#c41f1f';
}else{
fQuestionField.style.boxShadow = '';
fQuestionField.style.borderColor = '';
fQuestionLabel.style.boxShadow = '';
fQuestionLabel.style.borderColor = '';
fQuestionLabel.style.color = '';
}
errorBox.style.left = '4em';
errorBox.style.display = 'block';
setTimeout(function(){
closeBox();
},60000);
}
}
//==================================//
//function resets error messages
function closeBox() {
var errorBox= document.getElementById('errorBox');
errorBox.style.left = '100em';
setTimeout(function(){
errorBox.style.display = 'none';
},600);
}<file_sep><?php if (have_comments()) : ?>
<div class="postComment">
<ol>
<?php wp_list_comments('callback=custom_comments'); ?>
</ol>
</div>
<?php endif; ?>
<?php comment_form();?><file_sep><?php
//==============================================================//
//function to call scripts/css
function MARothaus_scripts_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() .'/css/style.css', array(), '1.0.0', 'all');
wp_enqueue_style('customprint', get_template_directory_uri() .'/css/print.css', array(), '1.0.0', 'all');
wp_enqueue_script('customscript', get_template_directory_uri() .'/js/script.js', array(), '1.0.0', true);
wp_enqueue_script('customform', get_template_directory_uri() .'/js/verify.js', array(), '1.0.0', true);
wp_enqueue_script('customprint', get_template_directory_uri() .'/js/print.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'MARothaus_scripts_enqueue');
function MARothaus_theme_setup() {
add_theme_support('menus');
register_nav_menu('primary', 'Primary Header Navigation');
register_nav_menu('secondary', 'Social Media Navigation');
}
add_action('init', 'MARothaus_theme_setup');
add_theme_support('custom-background');
add_theme_support('custom-header');
add_theme_support('post-thumbnails');
add_theme_support('editor-style');
add_theme_support('widgets');
//==============================================================//
//This function is for the avatar-manager plug-in... which doesn't work right now
function custom_avatar_defaults ( $avatar_defaults ) {
$avatar_url = get_bloginfo( 'template_directory' ) . '/images/avatar-default.png';
$avatar_defaults[$avatar_url] = __( 'Custom Default Avatar', 'mytextdomain' );
return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'custom_avatar_defaults' );
//==============================================================//
//if (get_option ('thread_comments')){
// wp_enqueue_script('commen-reply');
//}
//==============================================================//
//comments function
//code written by GameGrind and modified https://www.youtube.com/watch?v=p2zsIJYBOEg
function custom_comments ($comment, $args, $depth){
$GLOBALS[' comment '] = $comment; ?>
<li class="postComment" id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>">
<div class="postCommentAuthor">
<?php echo get_avatar($comment, $size='30', $default='<path_to_url>' ); ?>
<?php echo get_comment_author_link(); ?>
</div>
<?php if ($comment->comment_approved =='0') : ?>
<em><?php _e('Your Comment is Awaiting Moderation.') ?> </em>
<br />
<?php endif ; ?>
<div class="comment-meta"><a href="<?php echo htmlspecialchars( get_comment_link($comment->comment_ID )) ?>"><?php printf(get_comment_date(), get_comment_time() ) ?> </a> <?php edit_comment_link(__(' (Edit) '), ' ', ' ') ?> </div>
<?php comment_text() ?>
<div class="reply">
<?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth'] ))) ?>
</div>
<?php
}
?>
|
74e2497f336eb7bc4d12ad401b6528057b23c429
|
[
"JavaScript",
"Markdown",
"PHP"
] | 10
|
PHP
|
booellean/MARothaus-Blog
|
3bb49f06bb70fe84e1e11579435c7c57bdf66a3e
|
15a5fa47148b6065c3f134a6d3ce765703be5dd3
|
refs/heads/master
|
<file_sep>const fs = require('fs-extra');
const chalk = require('chalk');
const path = require('path');
const logger = console.log;
const {
// runCmd,
toInquirer,
modifyProName,
cloneProject,
generateReadme
} = require('./utils');
async function create(appName, options) {
// 打印目标路径
const cwd = options.cwd || process.cwd();
const targetDir = path.resolve(cwd, appName || '.');
logger(chalk.yellowBright('🌰 your dir is: '), chalk.bgMagentaBright(targetDir));
// 如果存在同名文件夹
if (fs.existsSync(targetDir)) {
//目标文件目录已存在,询问是否覆盖
const action = await toInquirer({
message: `Target directory already exists. Pick an action:`,
choices: [
{ name: 'Overwrite', value: 'overwrite' },
{ name: 'Cancel', value: false }
]
});
if (!action) {
logger('你选择了取消,请重新命名!');
return;
}
await fs.remove(targetDir)
}
// clone...
const cloneResult = await cloneProject(appName);
if (!cloneResult) return;
// 删除.git文件及README.md
if (fs.existsSync(`${targetDir}/.git`)) {
fs.removeSync(`${targetDir}/.git`);
}
if (fs.existsSync(`${targetDir}/README.md`)) {
fs.removeSync(`${targetDir}/README.md`);
}
// 创建新的README.md
await generateReadme(appName, 'npm', targetDir);
// 修改package项目名称
await modifyProName(targetDir, appName);
logger(chalk.bgGreen.white('finish create!'));
// 询问是否立即开始安装依赖及开始运行
// const isInstall = await toInquirer({
// message: `是否立即开始项目:`,
// choices: [
// { name: 'Go', value: 'yes' },
// { name: 'Cancel', value: 'cancel' }
// ]
// });
// if (isInstall === 'cancel') {
// logger('项目创建已完成!');
// return;
// }
// cd当前项目目录并执行install
// console.log(await runCmd('cd', [targetDir]));
}
module.exports = (...arg) => {
return create(...arg).catch(err => {
logger(chalk.red('Error: %s'), err.toString());
})
}<file_sep># react-m-cli
react移动端脚手架搭建工具
### Install
```
npm install react-m-cli -g
```
### Create a new project
```
react-m-cli create my-project
```
### Get version
```
react-m-cli -v
```
### Get help
```
react-m-cli -h
```
|
fecc71988987dafdb2318d174c1cb547a4783f86
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
dongkaifei/react-m-cli
|
40e29a72b2a252b9672b20b32f93aa238d05a94e
|
cba7afe524ff7721a32a71f8ca240ba170f9fad3
|
refs/heads/master
|
<repo_name>HarmanHass/Java<file_sep>/8.23.2917/Tutorial6/src/Application6If.java
public class Application6If {
public static void main(String[] args) {
int myInt = 15;
if(myInt < 10) {
System.out.println("Yes, its true!");
}
else if (myInt > 20) {
System.out.println("No Boy!");
}
else {
System.out.println("None of the above.");
}
}
}
<file_sep>/8.29.2017/methods/src/methods/apps.java
package methods;
public class apps {
public static void main(String[] args) {
calculateScore(true, 800, 5, 100);
calculateScore(true, 10000, 8, 200);
}
public static void calculateScore( boolean gameOver, int score, int levelCompleted, int bonus){
if(gameOver){
int finalScore = score + (levelCompleted * bonus);
finalScore += 2000;
System.out.println("Your final score was " + finalScore);
}
}
}
<file_sep>/9.14.2017/TestPractice/src/Test2.java
public class Test2 {
public static void main(String[] args) {
/*
double myFirstValue = 20;
double mySecondValue = 80;
double myTotal = (myFirstValue + mySecondValue) * 25;
System.out.println("My total = " + myTotal);
double theRemainder = myTotal % 40;
System.out.println("The remainder is " + theRemainder);
if (theRemainder <=20)
System.out.println("Total was over the limit");
*/
/*
int Score = 100;
if(Score > 90) {
System.out.println("Yout got the high score!");
}
*/
/*
boolean gameOver2 = true;
int Score2 = 1000;
int levelCompleted2 = 8;
int bonus2 = 200;
if (gameOver2){
int finalFinalScore = Score2 + (levelCompleted2 * bonus2);
System.out.println("Good job, Final Score: " + finalFinalScore);
}
*/
}
}
<file_sep>/12.4.2017/ConstructorsExercise3/src/Main.java
public class Main {
public static void main(String[] args) {
// Account bobsAccount = new Account();
// System.out.println(bobsAccount.getNumber());
// System.out.println(bobsAccount.getBalance());
VipPerson person1 = new VipPerson();
System.out.println(person1.getName());
VipPerson person2 = new VipPerson("bob", 250000);
System.out.println(person2.getName());
VipPerson person3 = new VipPerson("Harman", 100.0, "<EMAIL>");
System.out.println(person3.getName());
}
}
/*
Create a new class VipCustomer
it should have 3 fields name, credit limit and email address
create 3 constructors
1st constructor empty should call the constructor with 3 parameters with default values
2nd constructor should pass on the 2 values it receives and add a default value for the 3rd
3rd constructor should save all fields
create getters
*/<file_sep>/12.27.2017/components/src/components/PC.java
package components;
public class PC {
private Case theCase;
private minitor minitor;
private Motherboard motherboard;
public PC(Case theCase, components.minitor minitor, Motherboard motherboard) {
super();
this.theCase = theCase;
this.minitor = minitor;
this.motherboard = motherboard;
}
public Case getTheCase() {
return theCase;
}
public minitor getMinitor() {
return minitor;
}
public Motherboard getMotherboard() {
return motherboard;
}
}
<file_sep>/9.4.2017/Switch/src/App.java
//ex: Create a new switch state using char
//create a new char variable
//create a switch statement test for
//A, B, C, D, OR E
//display a message if any of these are found and then break
//add a default which displays a message saying not found
public class App {
public static void main(String[] args) {
char value = 'H';
switch(value){
case 'A':
System.out.println("Char was A");
break;
case 'B':
System.out.println("char was B");
break;
case 'C':
System.out.println("Char was C");
break;
case 'D': case 'E': case'F':
System.out.println(value + "was found");
break;
default:
System.out.println("Char wasnt found");
break;
}
String month = "January";
switch(month.toLowerCase()){
case "january":
System.out.println("Jan");
break;
case "june":
System.out.println("June");
break;
default:
System.out.println("Idk!");
break;
}
}
}
<file_sep>/12.27.2017/components/src/components/Main.java
package components;
public class Main {
public static void main(String[] args) {
Demensions demensions = new Demensions(20,20,5);
Case theCase = new Case ("220B", "Dell", "240", demensions);
minitor theMinitor = new Minitor("27inch Beast", "Acer", 27, nativeResolution);
}
}
|
62393cecdefa58a385c116c089010b58dd82d500
|
[
"Java"
] | 7
|
Java
|
HarmanHass/Java
|
993535e0a5a8e8c4306362cde671d064b16b13ff
|
61009e4b7a9d1da5e1720266fb8e86fc94cf1bcd
|
refs/heads/master
|
<file_sep>/*
* Created by saurabh on 2/24/2017.
*/
package cs455.scaling.WireFormats;
public class test
{
}
<file_sep>/*
* Created by saurabh on 2/24/2017.
*/
package cs455.scaling.util;
import cs455.scaling.Threads.ServerStatsPrinter;
import cs455.scaling.Threads.Worker_Thread;
import java.util.LinkedList;
public class ThreadPoolManager
{
private final Task_Manager manager;
private final static LinkedList<Worker_Thread> Thread_list = new LinkedList<>();
private final SelectorManager selectorManager;
private final ServerStatsPrinter statsPrinter;
public ThreadPoolManager(int thread_count, Task_Manager M,
SelectorManager selectorManager, ServerStatsPrinter printer)
{
// Creating the requested number of threads,
// starting the thread and adding it to Thread list
for (int i = 0; i < thread_count; i++ )
{
Worker_Thread W = new Worker_Thread(M, "Thread-" +i, selectorManager, printer);
// Thread thread = new Thread(W);
Thread_list.add(W);
// W.start();
}
System.out.println("Created the requested number of threads");
this.manager = M;
this.selectorManager = selectorManager;
this.statsPrinter = printer;
}
public void initialize()
{
for (Worker_Thread worker : Thread_list)
{
worker.start();
}
}
// public void run()
// {
// while (true)
// {
//// if (manager.get_task() != null)
// if (manager.Task_count() != 0)
// {
// System.out.println("Task is not null");
// if (Thread_list.peekFirst() != null)
// {
// Worker_Thread worker = Thread_list.peekFirst();
// Thread_list.remove(worker);
//
// Tasks task = manager.get_task();
// worker.setDone(task);
//// manager.remove_task();
//// System.out.println("Task Type: "+task.getType());
//
// }
// }
//
// }
// }
// static void getBackInList(Worker_Thread worker)
// {
// System.out.println(worker.getName() + " Back to the queue..");
// Thread_list.addLast(worker);
// }
}
<file_sep># ScalableServer
Developed a Scalable Server to handle network traffic by designing own thread pool with configurable number of threads.
Thread pool is used to manage tasks relating to network communications
|
c7a9f32a584145b8480ba4c42aae9243fd80780d
|
[
"Markdown",
"Java"
] | 3
|
Java
|
saurabhshendye/ScalableServer
|
0810b94a03725a56f4fadd77f40f46e90ea8ce81
|
872ec8f7afd484edf43def3f26db982678a2a3dd
|
refs/heads/master
|
<file_sep>#ifndef QUICKPASS_H
#define QUICKPASS_H
#include "../Command.h"
#define QUICKPASS_VELOCITY_THRESHOLD 0.005f
#define QUICKPASS_MAXIMUM_DISTANCE 130
#define QUICKPASS_ANGLE_BIAS 4.25f
#define QUICKPASS_BALL_VElOCITY_THRESHOLD 0.01f
class QuickPass : public Command
{
public:
QuickPass(Master* pMaster, Robot* pTargetRobot);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
Robot* m_pTargetRobot;
QVector2D m_startPosition;
QVector2D m_ballDirectionVector;
};
#endif // QUICKPASS_H
<file_sep>#include "CommandSeries.h"
#include <iostream>
CommandSeries::CommandSeries(Master* pMaster) :
Command(pMaster)
{
m_pCommand = 0;
}
void CommandSeries::addCommand(Command* pCommand)
{
m_commands.push_back(pCommand);
}
void CommandSeries::init()
{
if (!m_commands.empty())
{
for (int i = 0; i < m_commands.size(); i++)
if (!m_commands[i]->setRobot(m_pRobot))
std::cout << "Warning: cannot add Commands to a CommandSeries that have already been added to another robot!\n";
}
}
void CommandSeries::start()
{
m_commandIndex = 0;
m_isFinished = false;
m_pCommand = m_commands.front();
m_pCommand->start();
}
void CommandSeries::update(double deltaTime)
{
if (m_pCommand != 0)
{
if (m_pCommand->isFinished())
{
m_pCommand->end();
if (m_commandIndex < m_commands.size() - 1)
{
m_pCommand = m_commands[++m_commandIndex];
m_pCommand->start();
}
else
{
m_isFinished = true;
return;
}
}
m_pCommand->update(deltaTime);
}
else
{
m_isFinished = true;
}
}
bool CommandSeries::isFinished()
{
return m_isFinished;
}
<file_sep>#ifndef SETKICKER_H
#define SETKICKER_H
#include "../Command.h"
class SetKicker : public Command
{
public:
/**
* @brief Creates a new SetKicker instance
* @param pMaster The master instance associated with the SetKicker command
* @param speed The speed to set the kicker to
*/
SetKicker(Master* pMaster, float speed);
virtual void start();
virtual bool isFinished();
virtual void end();
private:
float m_speed;
};
#endif // SETKICKER_H
<file_sep>#ifndef AIMATROBOT_H
#define AIMATROBOT_H
#include "../Command.h"
#define AIM_ORBIT_RADIUS 240.0f
#define AIM_VELOCITY_THRESHOLD 0.005f
#define AIM_MAXIMUM_DISTANCE 5.0f
/**
* @brief The AimAtRobot @see Command is used for positioning the robot so the ball lies between this robot and the target robot
*/
class AimAtRobot : public Command
{
public:
/**
* @brief Initializes a new AimAtRobot instance
* @param pMaster The Master instance the AimAtRobot Command is associated with
* @param pTargetRobot The robot to aim at
*/
AimAtRobot(Master* pMaster, Robot* pTargetRobot);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
Robot* m_pTargetRobot;
QVector2D m_targetPos;
};
#endif // AIMATROBOT_H
<file_sep>#include "QuickPass.h"
#include "OneTimerPass.h"
#include "PassToRobot.h".h"
#include "../MathHelper.h"
#include <cmath>
#include <iostream>
QuickPass::QuickPass(Master* pMaster, Robot* pTargetRobot) :
Command(pMaster)
{
m_pTargetRobot = pTargetRobot;
}
void QuickPass::start()
{
m_startPosition = m_pRobot->getPosition();
}
void QuickPass::update(double deltaTime)
{
float ballDirection = m_pMaster->getBall()->getDirection();
m_ballDirectionVector = QVector2D(std::cos(ballDirection), -std::sin(ballDirection));
ballDirection = std::atan2(m_ballDirectionVector.y(), m_ballDirectionVector.x()) + M_PI;
QVector2D ballPos = m_pMaster->getBall()->getPosition();
QVector2D pointOfContact = MathHelper::getClosestPoint(ballPos, ballPos + m_ballDirectionVector, m_startPosition);
float robotAngle = MathHelper::getLineAngle(pointOfContact, m_pTargetRobot->getPosition());
ballDirection = MathHelper::adjustAngleValue(robotAngle, ballDirection);
float targetAngle = MathHelper::biasAngle(ballDirection, robotAngle, QUICKPASS_ANGLE_BIAS / m_pMaster->getBall()->getSpeed());
m_pRobot->setTargetOrientation(targetAngle);
QVector2D targetPos = pointOfContact - QVector2D(std::cos(targetAngle), std::sin(targetAngle)) * 90.0f;
QVector2D robotPos = m_pRobot->getPosition();
float targetDirection = -MathHelper::getLineAngle(robotPos, targetPos);
m_pRobot->setTargetDirection(targetDirection);
m_pRobot->setTargetSpeed(std::min((float)(robotPos - targetPos).length() * QUICKPASS_VELOCITY_THRESHOLD, 1.0f));
}
bool QuickPass::isFinished()
{
return (m_pMaster->getBall()->getPosition() - m_pRobot->getPosition()).length() < QUICKPASS_MAXIMUM_DISTANCE ||
(m_pMaster->getBall()->getPosition() + m_ballDirectionVector * 0.001 - m_pRobot->getPosition()).length() >
(m_pMaster->getBall()->getPosition() - m_pRobot->getPosition()).length() ||
(m_pMaster->getBall()->getSpeed() < QUICKPASS_BALL_VElOCITY_THRESHOLD);
}
void QuickPass::end()
{
m_pRobot->setKickerSpeed(4);
}
<file_sep>#ifndef TEAM_H
#define TEAM_H
/**
* @brief The Team enum is used for describing which team a robot is on
*/
enum Team
{
YELLOW,
BLUE
};
#endif // TEAM_H
<file_sep>#include "GetOpen.h"
#include "../MathHelper.h"
#include <cmath>
GetOpen::GetOpen(Master* pMaster) :
Command(pMaster)
{
}
void GetOpen::start()
{
if (m_startPosition.isNull())
m_startPosition = m_pRobot->getPosition();
}
void GetOpen::update(double deltaTime)
{
QVector2D robotPos = m_pRobot->getPosition();
m_pRobot->setTargetSpeed(std::min((float)(robotPos - m_startPosition).length() * GETOPEN_VELOCITY_THRESHOLD, 1.0f));
float targetDirection = -MathHelper::getLineAngle(robotPos, m_startPosition);
m_pRobot->setTargetDirection(targetDirection);
QVector2D ballPos = m_pMaster->getBall()->getPosition();
float targetOrientation = MathHelper::getLineAngle(robotPos, ballPos);
m_pRobot->setTargetOrientation(targetOrientation);
}
bool GetOpen::isFinished()
{
return false;
}
<file_sep>from LogData import *
from GeometryRenderer import *
from RobotContainer import *
from BallContainer import *
from GUI import *
class Viewer:
START_OFFSET_SECONDS = 0 # 4500 # For testing
SCALE_RATE = 1.05
MIN_SCALE = 0.01
MAX_SCALE = 1.0
def __init__(self, log_data: LogData, title: str, width: int, height: int, background: (int, int, int)):
"""
Creates a new Viewer instance
:param log_data: The protobuf log data to view
:param title: The title of the Viewer's window
:param size: The window size of the Viewer
:param background: The background color of the Viewer
"""
self.log_data = log_data
self.title = title
self.window_width = width
self.window_height = height
self.scale = 0.1
self.background = background
self._geometry = None
self.actors = [GeometryRenderer(self), BallContainer(self), RobotContainer(self), GUI(self)]
# Initialize pygame for rendering
pygame.init()
self.current_time_ns = log_data.packets[0].time_ns + self.START_OFFSET_SECONDS * 1000000000
self.last_time = pygame.time.get_ticks()
self.packet_id = 0
# Set the title of the window
pygame.display.set_caption(self.title)
# Load the surfaces (images)
self.screen = pygame.display.set_mode((self.window_width, self.window_height))
def run(self) -> None:
"""
Starts the run loop for the viewer
"""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4:
self.scale *= self.SCALE_RATE
elif event.button == 5:
self.scale /= self.SCALE_RATE
self.scale = min(self.MAX_SCALE, max(self.MIN_SCALE, self.scale))
self.update()
self.render()
def update(self) -> None:
"""
Updates each ball and robot
"""
ticks = pygame.time.get_ticks()
time_delta_ms = ticks - self.last_time
self.current_time_ns += time_delta_ms * 1000000
self.last_time = ticks
if self.packet_id >= self.log_data.num_packets:
return
# Read all the packets leading up to the current time
while True:
current_packet = self.log_data.packets[self.packet_id]
wrapper_packet = current_packet.wrapper_packet
# If the packet contains ball and robot positions, update each position
if wrapper_packet is not None:
for actor in self.actors:
actor.update(wrapper_packet, time_delta_ms)
# If we've gone through all packets leading up to this point in time, finish updating
if current_packet.time_ns >= self.current_time_ns:
self._geometry = current_packet.geometry
break
self.packet_id += 1
def render(self) -> None:
"""
Render all the balls and robots
"""
self.screen.fill(self.background)
for actor in self.actors:
actor.draw(self._geometry.scale(self.scale))
# Present the new image to the window
pygame.display.flip()
def screen_point(self, x: float, y: float) -> (int, int):
"""
Converts x and y field coordinates to screen coordinates
:param x: The x field coordinate
:param y: The y field coordinate
:return: A tuple containing the updated x and y positions
"""
return int(x * self.scale + self.window_width * 0.5), int(y * self.scale + self.window_height * 0.5)
def screen_scalar(self, value: float) -> int:
"""
Scales the value field to correspond with screen units
:param value: The value to scale
:return: The scaled value
"""
return int(value * self.scale)
def set_packet(self, id):
self.packet_id = id
if self.packet_id < self.log_data.num_packets:
self.current_time_ns = self.log_data.packets[self.packet_id].time_ns
<file_sep>#include "CatchBall.h"
#include "../MathHelper.h"
#include "PassToRobot.h"
#include <cmath>
CatchBall::CatchBall(Master* pMaster) :
Command(pMaster)
{
}
void CatchBall::update(double deltaTime)
{
float ballSpeed = m_pMaster->getBall()->getSpeed();
QVector2D robotPos = m_pRobot->getPosition();
QVector2D ballPos = m_pMaster->getBall()->getPosition();
float ballDirection = m_pMaster->getBall()->getDirection();
m_ballDirectionVector = QVector2D(std::cos(ballDirection), -std::sin(ballDirection));
m_pRobot->setTargetOrientation(std::atan2(m_ballDirectionVector.y(), m_ballDirectionVector.x()) + M_PI);
QVector2D targetPos = MathHelper::getClosestPoint(ballPos, ballPos + m_ballDirectionVector, robotPos);
float targetDirection = -MathHelper::getLineAngle(robotPos, targetPos);
m_pRobot->setTargetDirection(targetDirection);
m_pRobot->setTargetSpeed(std::min((float)(robotPos - targetPos).length() * CATCH_VELOCITY_THRESHOLD, 1.0f));
}
bool CatchBall::isFinished()
{
return (m_pMaster->getBall()->getSpeed() < CATCH_BALL_VElOCITY_THRESHOLD) ||
(m_pRobot->getPosition() - m_pMaster->getBall()->getPosition()).length() < CATCH_MAXIMUM_DISTANCE ||
(m_pMaster->getBall()->getPosition() + m_ballDirectionVector * 0.001 - m_pRobot->getPosition()).length() >
(m_pMaster->getBall()->getPosition() - m_pRobot->getPosition()).length();
}
void CatchBall::end()
{
// vvv This is just for testing
m_pRobot->setTargetSpeed(0.0f);
int nextIndex = (m_pRobot->getId() + 1) % TEAM_SIZE;
m_pRobot->runCommmand(new PassToRobot(m_pMaster, m_pMaster->getTeamBot(nextIndex)));
// ^^^
destroy();
}
<file_sep>import gzip
import messages_robocup_ssl_wrapper_legacy_pb2
import referee_pb2
from struct import *
from Geometry import *
class LogData:
LOG_HEADER_SIZE = 12
LOG_HEADER_STR = b'SSL_LOG_FILE'
def __init__(self):
"""
Creates a new LogData instance
"""
self.packets = []
self.num_packets = 0
self.skipping = True
self.skip_start = 0
self.skip_time_total = 0
def parse(self, file: gzip.GzipFile, skip_starts = [0,1,4,5,6,7,12,13,14,15]) -> None:
"""
Generates packets from the given gzipped log file
:param file: The gzip file to parse
"""
if file.read(self.LOG_HEADER_SIZE) != self.LOG_HEADER_STR:
raise RuntimeError("Invalid file type")
vn, = unpack('>I', file.read(4))
if vn != 1:
raise RuntimeError("Invalid version number: " + str(vn))
geometry = Geometry()
while True:
# Read the time stamp of the packet
ts = file.read(8)
# If the time stamp is empty, we're done parsing the file, so exit the loop
if not ts:
#print("done parsing")
break
# Convert the time stamp tp an integer
ns, = unpack('>Q', ts)
# Parse the message type as an integer
mt, = unpack('>I', file.read(4))
# Parse the message string
ms, = unpack('>I', file.read(4))
mc = file.read(ms)
# Construct a new SSLPacket
ssl_packet = SSLPacket(ns - self.skip_time_total, mt, geometry)
# Generate the SSLPacket's wrapper packet based on the message type
if not ssl_packet.gen_wrapper_packet(mc):
continue
geometry = ssl_packet.geometry
#start skipping for HALT command
if (mt == 3 and not self.skipping and ssl_packet.wrapper_packet.command in skip_starts):
self.skipping = True
self.skip_start = ns
#print("skip")
#stop skipping at any other value
if (mt == 3 and self.skipping and (not ssl_packet.wrapper_packet.command in skip_starts)):
self.skipping = False
self.skip_time_total += ns - self.skip_start
#print("to", ts)
#if good data point push it to packets
if (not self.skipping and mt == 2):
self.packets.append(ssl_packet)
self.num_packets += 1
class SSLPacket:
def __init__(self, time_ns: int, message_type: int, geometry: Geometry):
"""
Creates a new SSLPacket instance
:param time_ns: The time stamp in nanoseconds of the packet
:param message_type:
"""
self.time_ns = time_ns
self.message_type = message_type
self.wrapper_packet = None
self.geometry = geometry
def gen_wrapper_packet(self, message: str) -> bool:
"""
Generates a wrapper packet from the given message
:param message: The message as a string
"""
if self.message_type == 2:
self.wrapper_packet = messages_robocup_ssl_wrapper_legacy_pb2.SSL_WrapperPacket()
# Generate geometry data for vision data only
# Moved so this isn't run for referee data
if self.wrapper_packet.geometry is not None:
self.geometry = Geometry._make([
getattr(self.wrapper_packet.geometry.field, v) or getattr(self.geometry, v) for
v in list(self.wrapper_packet.geometry.field.DESCRIPTOR.fields_by_name) if
v in self.geometry._fields])
elif self.message_type == 3:
#read referee data
#no geometry data for referee
self.wrapper_packet = referee_pb2.SSL_Referee()
else:
return False
self.wrapper_packet.ParseFromString(message)
return True
<file_sep>#include "AimAtRobot.h"
#include "../MathHelper.h"
#include <cmath>
#include <iostream>
AimAtRobot::AimAtRobot(Master* pMaster, Robot* pTargetRobot) :
Command(pMaster)
{
m_pTargetRobot = pTargetRobot;
}
void AimAtRobot::start()
{
m_targetPos = QVector2D(0, 0);
}
void AimAtRobot::update(double deltaTime)
{
QVector2D robotPos = m_pRobot->getPosition();
QVector2D ballPos = m_pMaster->getBall()->getPosition();
float targetOrientation = MathHelper::getLineAngle(robotPos, ballPos);
m_pRobot->setTargetOrientation(targetOrientation);
QVector2D targetRobotPos = m_pTargetRobot->getPosition();
m_targetPos = ballPos + (ballPos - targetRobotPos).normalized() * AIM_ORBIT_RADIUS;
m_pRobot->setTargetSpeed(std::min((float)(robotPos - m_targetPos).length() * AIM_VELOCITY_THRESHOLD, 1.0f));
QVector2D currentTargetPos = m_targetPos;
if ((robotPos - currentTargetPos).length() > AIM_ORBIT_RADIUS)
currentTargetPos = ballPos - (ballPos - MathHelper::getClosestPoint(robotPos, currentTargetPos, ballPos)).normalized() * AIM_ORBIT_RADIUS;
float targetDirection = -MathHelper::getLineAngle(robotPos, currentTargetPos);
m_pRobot->setTargetDirection(targetDirection);
}
bool AimAtRobot::isFinished()
{
return (m_pRobot->getPosition() - m_targetPos).length() < AIM_MAXIMUM_DISTANCE;
}
void AimAtRobot::end()
{
m_pRobot->setTargetSpeed(0.0f);
}
<file_sep>#include "Master.h"
#include <iostream>
#include <QPainter>
#include <QMatrix>
#include <QImage>
#include <qmath.h>
Master::Master(qint16 port, const std::string netAddress, Team team, QWidget* parent) :
QWidget(parent),
m_WIDTH(1040),
m_HEIGHT(740),
m_team(team),
m_lastFrameNumber(0),
m_framesUntilStart(2)
{
setWindowTitle("Cal Poly RoboCup SSL Engine");
setFixedSize(m_WIDTH, m_HEIGHT);
// Initailize each team of robots
for (unsigned char i = 0; i < TEAM_SIZE; i++)
{
m_yellowBots[i] = new Robot(YELLOW, i);
m_blueBots[i] = new Robot(BLUE, i);
}
if (m_team == YELLOW)
{
m_teamBots = m_yellowBots;
m_opponentBots = m_blueBots;
}
else
{
m_teamBots= m_blueBots;
m_opponentBots = m_yellowBots;
}
m_ball = new Ball;
m_pFieldPixmap = new QPixmap();
m_pYellowBot = new QPixmap();
m_pBlueBot = new QPixmap();
m_pFieldPixmap->load(":/images/Field.png");
m_pYellowBot->load(":/images/YellowBot.png");
m_pBlueBot->load(":/images/BlueBot.png");
// Open the SSL client
m_pClient = new RoboCupSSLClient(port, netAddress, "");
m_pClient->open();
m_pTimer = new QTimer(this);
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(run()));
m_pTimer->start(0);
}
Master::~Master()
{
delete m_ball;
for (int i = 0; i < TEAM_SIZE; i++)
{
delete m_yellowBots[i];
delete m_blueBots[i];
}
delete m_pClient;
delete m_pFieldPixmap;
delete m_pYellowBot;
delete m_pBlueBot;
delete m_pTimer;
}
void Master::run()
{
SSL_WrapperPacket wrapperPacket;
// If a packet was received, update robot information
if (m_pClient->receive(wrapperPacket))
{
SSL_DetectionFrame frame = wrapperPacket.detection();
// Calculate the delta time and update the robots if this is the start of a new frame
int frameNumber = frame.frame_number();
int deltaFrames = frameNumber - m_lastFrameNumber;
if (deltaFrames > 0)
{
m_lastFrameNumber = frameNumber;
if (m_framesUntilStart > 0)
m_framesUntilStart--;
else
update(deltaFrames * FIXED_DELTA_TIME);
}
// Update each yellow robot
int yellowSize = frame.robots_yellow_size();
for (int i = 0; i < yellowSize; i++)
{
SSL_DetectionRobot robot = frame.robots_yellow(i);
m_yellowBots[robot.robot_id()]->refresh(robot);
}
// Update each blue robot
int blueSize = frame.robots_blue_size();
for (int i = 0; i < blueSize; i++)
{
SSL_DetectionRobot robot = frame.robots_blue(i);
m_blueBots[robot.robot_id()]->refresh(robot);
}
if (frame.balls_size() > 0)
{
SSL_DetectionBall ball = frame.balls(0);
m_ball->refresh(ball);
}
}
}
void Master::update(double deltaTime)
{
// Update each robot on the controlling team
for (int i = 0; i < TEAM_SIZE; i++)
m_teamBots[i]->updateStats(deltaTime);
m_ball->updateStats(deltaTime);
for (int i = 0; i < TEAM_SIZE; i++)
m_teamBots[i]->updateCommand(deltaTime);
writeOutput();
repaint();
}
void Master::paintEvent(QPaintEvent* e)
{
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(0, 0, m_WIDTH, m_HEIGHT, *m_pFieldPixmap);
painter.setPen(Qt::black);
painter.setBrush(Qt::red);
QPoint ballPosition = convertToScreenPoint(m_ball->getPosition());
painter.drawEllipse(ballPosition, 2, 2);
for (int i = 0; i < TEAM_SIZE; i++)
{
QPoint robotPoint = convertToScreenPoint(m_yellowBots[i]->getPosition());
painter.translate(robotPoint.x(), robotPoint.y());
painter.rotate(-m_yellowBots[i]->getOrientation() * (180.0 / M_PI));
painter.drawPixmap(-9, -9, 18, 18, *m_pYellowBot);
painter.resetTransform();
robotPoint = convertToScreenPoint(m_blueBots[i]->getPosition());
painter.translate(robotPoint.x(), robotPoint.y());
painter.rotate(-m_blueBots[i]->getOrientation() * (180.0 / M_PI));
painter.drawPixmap(-9, -9, 18, 18, *m_pBlueBot);
painter.resetTransform();
}
for (int i = 0; i < TEAM_SIZE; i++)
{
QPoint robotPoint = convertToScreenPoint(m_yellowBots[i]->getPosition());
painter.drawText(robotPoint.x() + 9, robotPoint.y() - 9, QString::number(i));
robotPoint = convertToScreenPoint(m_blueBots[i]->getPosition());
painter.drawText(robotPoint.x() + 9, robotPoint.y() - 9, QString::number(i));
}
}
QPoint Master::convertToScreenPoint(QVector2D pos)
{
QPoint point = pos.toPoint() * 0.1;
point.setY(point.y() * -1);
point += QPoint(m_WIDTH / 2, m_HEIGHT / 2);
return point;
}
<file_sep>#ifndef PID_H
#define PID_H
/**
* @brief The PID class is used for performing PID calculations given PID constasnts, min and max values, an input, and a delta time
*/
class PID
{
public:
/**
* @brief Creates a new PID instance
* @param p The P (proportional) constant
* @param i The I (integral) constant
* @param d The D (derivative) constant
* @param min The minimum output value
* @param max The maximum output value
*/
PID(float p, float i, float d, float min, float max);
/**
* @brief Calculates the output from the given delta time and input
* @param deltaTime The time passed since the last calculate call
* @param input The input to the PID calculation
* @return The output of the PID calculations
*/
float calculate(float deltaTime, float input);
/**
* @brief Used for accessing the P constant
* @return The P constant
*/
float getP() const { return m_p; }
/**
* @brief Used for accessing the I constant
* @return The I constant
*/
float getI() const { return m_i; }
/**
* @brief Used for accessing the D constant
* @return The D constant
*/
float getD() const { return m_d; }
/**
* @brief Used for accessing the minimum output limit
* @return The mimimum output limit
*/
float getMin() const { return m_min; }
/**
* @brief Used for accessing the maximum output limit
* @return The maximum output limit
*/
float getMax() const { return m_max; }
/**
* @brief Used for accessing the setpoint
* @return The setpoint
*/
float getSetpoint() const { return m_setpoint; }
/**
* @brief Used for setting the P constant
*/
void setP(float p) { m_p = p; }
/**
* @brief Used for setting the I constant
*/
void setI(float i) { m_i = i; }
/**
* @brief Used for setting the D constant
*/
void setD(float d) { m_d = d; }
/**
* @brief Used for setting the setpoint
*/
void setSetpoint(float setpoint) { m_setpoint = setpoint; }
private:
float m_p;
float m_i;
float m_d;
float m_min;
float m_max;
float m_setpoint;
float m_lastError;
float m_integral;
};
#endif // PID_H
<file_sep>#ifndef BALL_H
#define BALL_H
#include <QVector2D>
#include "messages_robocup_ssl_wrapper.pb.h"
/**
* @brief The Ball class is used for accessing ball information, like position, direction, and speed
*/
class Ball
{
private:
bool m_initialized;
// Transform information
QVector2D m_position;
QVector2D m_lastPosition;
// Velocity information
float m_speed;
float m_direction;
public:
Ball();
/**
* @brief Used for accessing the position of the ball
* @return The position of the ball as a @see QVector2D
*/
QVector2D getPosition() const { return m_position; }
/**
* @brief Used for accessing the speed of the ball
* @return The speed of the ball in m/s as a float
*/
float getSpeed() const { return m_speed; }
/**
* @brief Used for accessing the direction of the ball
* @return The direction of the ball in radians
*/
float getDirection() const { return m_direction; }
/**
* @brief Updates the positional information of the ball
* @param ball The @see SSL_DetectionBall used to update the Ball's information
*/
void refresh(SSL_DetectionBall& ball);
/**
* @brief Updates the velocity information of the ball with the given delta time
* @param deltaTime The time passed in seconds since the last update call
*/
void updateStats(double deltaTime);
};
#endif // BALL_H
<file_sep>#include "PassBall.h"
#include "../MathHelper.h"
#include <cmath>
#include <iostream>
PassBall::PassBall(Master* pMaster, Robot* pTargetRobot) :
Command(pMaster),
m_targetOrientation(0.0f),
m_targetDirection(0.0f)
{
m_pTargetRobot = pTargetRobot;
}
void PassBall::update(double deltaTime)
{
QVector2D robotPos = m_pRobot->getPosition();
QVector2D targetRobotPos = m_pTargetRobot->getPosition();
m_targetOrientation = MathHelper::getLineAngle(robotPos, targetRobotPos);
m_pRobot->setTargetOrientation(m_targetOrientation);
QVector2D ballPos = m_pMaster->getBall()->getPosition();
m_pRobot->setTargetSpeed(std::min(std::max((float)((robotPos - ballPos).length() - PASS_TARGET_DISTANCE) * PASS_VELOCITY_THRESHOLD, 0.0f), 1.0f));
m_targetDirection = -MathHelper::getLineAngle(robotPos, ballPos);
m_pRobot->setTargetDirection(m_targetDirection);
}
bool PassBall::isFinished()
{
return (m_pRobot->getPosition() - m_pMaster->getBall()->getPosition()).length() < PASS_MAXIMUM_DISTANCE ||
std::abs(std::abs(m_targetOrientation) - std::abs(m_targetDirection)) > PASS_MAXIMUM_ANGLE;
}
void PassBall::end()
{
m_pRobot->setTargetSpeed(0.0f);
}
<file_sep>#include "OneTimerPass.h"
#include "QuickPass.h"
#include "Delay.h"
#include "SetKicker.h"
OneTimerPass::OneTimerPass(Master* pMaster, Robot* pTargetRobot)
: CommandSeries(pMaster)
{
m_pTargetRobot = pTargetRobot;
addCommand(new QuickPass(pMaster, pTargetRobot));
addCommand(new Delay(pMaster, 0.05));
addCommand(new SetKicker(pMaster, 0.0f));
}
void OneTimerPass::end()
{
m_pTargetRobot->runCommmand(new OneTimerPass(m_pMaster, m_pMaster->getTeamBot((m_pTargetRobot->getId() + 1) % 6)));
destroy();
}
<file_sep>#ifndef ROBOTMANAGER_H
#define ROBOTMANAGER_H
#include <map>
#include "Robot.h"
class RobotManager
{
public:
RobotManager();
~RobotManager();
Robot* get(int index);
private:
std::map<int, Robot*> m_robots;
};
#endif // ROBOTMANAGER_H
<file_sep>#include "Ball.h"
#include <cmath>
Ball::Ball() :
m_initialized(false),
m_position(0, 0),
m_lastPosition(0, 0),
m_speed(0),
m_direction(0)
{
}
void Ball::refresh(SSL_DetectionBall& ball)
{
m_position.setX(ball.x());
m_position.setY(ball.y());
if (!m_initialized)
{
m_initialized = true;
m_lastPosition = m_position;
}
}
void Ball::updateStats(double deltaTime)
{
// Update the speed of the ball
if (m_position != m_lastPosition)
{
m_speed = (m_position - m_lastPosition).length() / deltaTime * 0.001;
if (m_speed > 0)
m_direction = std::atan2(-(m_position.y() - m_lastPosition.y()), m_position.x() - m_lastPosition.x());
m_lastPosition = m_position;
}
}
<file_sep>#include "RobotManager.h"
#include "Team.h"
RobotManager::RobotManager()
{
}
Robot* RobotManager::get(int index)
{
std::map<int, Robot*>::iterator item = m_robots.find(index);
if (item != m_robots.end())
return item->second;
Robot* robot = new Robot(YELLOW, index);
m_robots.insert(std::pair<int, Robot*>(index, robot));
return robot;
}
<file_sep>#ifndef COMMANDSERIES_H
#define COMMANDSERIES_H
#include <vector>
#include "Command.h"
/**
* @brief The CommandSeries class is used to group multiple Commands into one
*/
class CommandSeries : public Command
{
public:
/**
* @brief Initializes a new CommandSeries instance
* @param pMaster The Master instance
*/
CommandSeries(Master* pMaster);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
protected:
/**
* @brief Adds a @see Command to the CommandSeries
* @param pCommand The @see Command to add
*/
void addCommand(Command* pCommand);
virtual void init();
private:
std::vector<Command*> m_commands;
Command* m_pCommand;
int m_commandIndex;
bool m_isFinished;
};
#endif // COMMANDSERIES_H
<file_sep>#include "SetKicker.h"
SetKicker::SetKicker(Master* pMaster, float speed):
Command(pMaster),
m_speed(speed)
{
}
void SetKicker::start()
{
m_pRobot->setKickerSpeed(m_speed);
}
bool SetKicker::isFinished()
{
return true;
}
void SetKicker::end()
{
destroy();
}
<file_sep>import pygame
from ScreenActor import *
class Ball(ScreenActor):
DETECTION_TIMEOUT_MS = 750
def __init__(self, viewer, x=0, y=0):
"""
Creates a new Ball instance
:param viewer: The viewer to be rendered to
:param x: The Ball's X position
:param y: The Ball's Y position
"""
super().__init__(viewer, 22, x, y)
self.time_since_update = 0
def update(self, packet, delta):
pass
def draw(self, geometry):
"""
Renders the Ball to the Viewer
:param geometry: (unused)
"""
pygame.draw.circle(self.viewer.screen, (255, 127, 0), self.viewer.screen_point(self.x, self.y),
self.viewer.screen_scalar(self.radius), 0)
<file_sep>#ifndef MATHHELPER_H
#define MATHHELPER_H
#include <QVector2D>
namespace MathHelper
{
/**
* @brief Returns the point along the given line closes to the point provided
* @param lineStart The start of the line
* @param lineEnd The end of the line
* @param point The point to compare with the line
* @return A @see QVector2D describing the point along the line closest to the point provided
*/
QVector2D getClosestPoint(QVector2D lineStart, QVector2D lineEnd, QVector2D point);
/**
* @brief Returns the angle in radians of the line drawn from point A to point B
* @param pointA The first point in the line
* @param pointB The second point in the line
* @return A float representing the radians of the line drawn from point A to point B
*/
float getLineAngle(QVector2D pointA, QVector2D pointB);
/**
* @brief Returns the angle in radians that results in the lowest difference between the two given angles
* @param baseAngle The angle used to adjust the other angle
* @param otherAngle The angle to be adjusted
* @return The value of the adjusted angle
*/
float adjustAngleValue(float baseAngle, float otherAngle);
/**
* @brief Returns the angle that represents a bisection of the two given angles, but biased toward the outgoing angle from the given bias
* @param incoming The incoming angle
* @param outgoing The outgoing angle (the bias controls how influential this is)
* @param outoingBias The outgoing angle bias constant
* @return The baised angle
*/
float biasAngle(float incoming, float outgoing, float outgoingBias);
}
#endif // MATHHELPER_H
<file_sep>import pygame
from UIRect import *
class Slider(Actor):
SLIDER_PADDING_H = 32
SLIDER_PADDING_V = 32
SLIDER_THICKNESS = 8
OUTLINE_PADDING = 2
THUMB_WIDTH = 12
THUMB_HEIGHT = 24
def __init__(self, viewer):
super().__init__(viewer)
self.slider_bar = UIRect(viewer, self.SLIDER_PADDING_H, self.SLIDER_PADDING_V,
self.viewer.window_width - self.SLIDER_PADDING_H * 2,
self.SLIDER_THICKNESS, self.OUTLINE_PADDING, (127, 127, 255))
self.thumb = UIRect(viewer, self.SLIDER_PADDING_H,
self.SLIDER_PADDING_V - self.THUMB_HEIGHT // 2 + self.SLIDER_THICKNESS // 2,
self.THUMB_WIDTH, self.THUMB_HEIGHT, self.OUTLINE_PADDING, (191, 191, 255))
self.elements = [self.slider_bar, self.thumb]
self.sliding = False
def update(self, packet, delta):
pass
def draw(self, geometry):
if self.sliding:
if pygame.mouse.get_pressed()[0]:
self.thumb.x = min(max(pygame.mouse.get_pos()[0] - self.THUMB_WIDTH // 2, self.SLIDER_PADDING_H),
self.viewer.window_width - self.SLIDER_PADDING_H)
else:
self.sliding = False
self.viewer.set_packet(int((self.thumb.x - self.SLIDER_PADDING_H) /
(self.viewer.window_width - self.SLIDER_PADDING_H * 2) *
self.viewer.log_data.num_packets))
elif (self.thumb.mouse_hover() or self.slider_bar.mouse_hover()) and pygame.mouse.get_pressed()[0]:
self.sliding = True
else:
self.thumb.x = self.SLIDER_PADDING_H + int(self.viewer.packet_id / self.viewer.log_data.num_packets *
(self.viewer.window_width - self.SLIDER_PADDING_H * 2))
for e in self.elements:
e.draw(geometry)
<file_sep>from collections import namedtuple
GeometryBase = namedtuple('Geometry',
['line_width',
'field_length',
'field_width',
'boundary_width',
'goal_width',
'goal_depth',
'goal_wall_width',
'center_circle_radius',
'defense_radius'])
class Geometry(GeometryBase):
"""
Used for storing field geometry
"""
def scale(self, factor):
"""
Scales each property by the given factor
:param factor: The factor by which to scale the fields of this Geometry instance
:return:
"""
return Geometry._make([max(0, int(v * factor)) for v in self])
# Allow creation of a Geometry instance without parameters
Geometry.__new__.__defaults__ = (10, 9000, 6000, 300, 1000, 300, 10, 500, 1000)
<file_sep>#ifndef CLIENTMASTER_H
#define CLIENTMASTER_H
#include "Master.h"
#include <QUdpSocket>
#include <vector>
/**
* @brief The ClientMaster class derives from @see Master and implement communication to the grSim client
*/
class ClientMaster : public Master
{
public:
/**
* @brief Initializes a new ClientMaster instance
* @param port The vision mulicast port
* @param netAddress The vision multicast address
* @param team The team the @see ClientMaster is controlling
*/
ClientMaster(qint16 port, const std::string netAddress, Team team, QWidget* parent = 0);
/**
* @brief Destroys any dynamically allocated memory by the ClientMaster
*/
~ClientMaster();
protected:
/**
* @brief update Updates each child robot and sends command packets to grSim
* @param deltaTime the time passed since the last update
*/
virtual void writeOutput();
private:
QUdpSocket* m_pUdpSocket;
};
#endif // CLIENTMASTER_H
<file_sep>#ifndef MASTER_H
#define MASTER_H
#include <QWidget>
#include <QTimer>
#include <QPixmap>
#include "Robot.h"
#include "Ball.h"
#include "Team.h"
#include "robocup_ssl_client.h"
#define TEAM_SIZE 8
#define FIXED_DELTA_TIME 1.0f/60.0f
class Robot;
/**
* @brief The Master class is an abstract class that handles receiving packets from the SSL server and updating robot information
*/
class Master : public QWidget
{
Q_OBJECT
public:
/**
* @brief Initializes a new instance of the Master class
* @param port The vision mulicast port
* @param netAddress The vision multicast address
* @param parent The parent QWidget to the Master instance
*/
explicit Master(qint16 port, const std::string netAddress, Team team, QWidget* parent = 0);
/**
* @brief Frees any dynamically allocated memory by the Master class
*/
virtual ~Master();
/**
* @brief Returns the yellow bot of the given ID
* @param id The ID of the yellow robot to access
* @return The yellow robot of the given ID
*/
Robot* getYellowBot(int id) const { return m_yellowBots[id]; }
/**
* @brief Returns the blue bot of the given ID
* @param id The ID of the blue robot to access
* @return The blue robot of the given ID
*/
Robot* getBlueBot(int id) const { return m_blueBots[id]; }
/**
* @brief Returns the bot on the controlling team of the given ID
* @param id The ID of the robot to access
* @return The robot of the given ID
*/
Robot* getTeamBot(int id) const { return m_teamBots[id]; }
/**
* @brief Returns the bot on the opposing team of the given ID
* @param id The ID of the robot to access
* @return The robot of the given ID
*/
Robot* getOpponentBot(int id) const { return m_opponentBots[id]; }
/**
* @brief Returns the Ball instance
* @return The Ball instance
*/
Ball* getBall() const { return m_ball; }
/**
* @brief Returns the @see Team that Master is controlling
* @return The Team that master is controlling
*/
Team getTeam() const { return m_team; }
protected:
/**
* @brief Defines how communication is completed with the robots
* @param deltaTime the time passed since the last writeOutput call
*/
virtual void writeOutput() = 0;
private:
const int m_WIDTH;
const int m_HEIGHT;
int m_framesUntilStart;
Robot* m_yellowBots[TEAM_SIZE];
Robot* m_blueBots[TEAM_SIZE];
Ball* m_ball;
Team m_team;
Robot** m_teamBots;
Robot** m_opponentBots;
QPixmap* m_pFieldPixmap;
QPixmap* m_pYellowBot;
QPixmap* m_pBlueBot;
RoboCupSSLClient* m_pClient;
QTimer* m_pTimer;
int m_lastFrameNumber;
void update(double deltaTime);
void paintEvent(QPaintEvent* e);
QPoint convertToScreenPoint(QVector2D point);
public slots:
/**
* @brief run Receives any packets sent from SSL_Vision, refreshes the robots' positions,
* updates the robots, then redraws the window
*/
void run();
};
#endif // MASTER_H
<file_sep>#ifndef COMMAND_H
#define COMMAND_H
#include "Master.h"
#include "Robot.h"
class Master;
class Robot;
/**
* @brief The Command class provides a means of assigning actions to Robots.
* Commands are designed to allow reuseability, so any given Command should be designed
* to be initialized, updated, and ended multiple times.
*/
class Command
{
public:
Command(Master* pMaster);
/**
* @brief Defines the robot that this Command is attached to
* @note Once the robot is defined, it cannot be changed
* @param pRobot The robot to assign the Command to
* @return true if the robot was properly assigned, otherwise false
*/
bool setRobot(Robot* pRobot);
/**
* @brief Used for deallocating a Command instance.
*/
void destroy() { delete this; }
/**
* @brief Called when the Command is first started
*/
virtual void start() { }
/**
* @brief Called when the Command is updated
* @param deltaTime The time passed since the last update
*/
virtual void update(double deltaTime) { }
/**
* @brief Should return true when the command has finished
* @return True if the command has finished
*/
virtual bool isFinished() { return false; }
/**
* @brief Called when the command has been interrupted with another incoming command
*/
virtual void interrupted() { }
/**
* @brief Called when the command ends
*/
virtual void end() { }
/**
* @brief Returns the @see Robot associated with this Command
* @return The @see Robot associated with this Comand
*/
Robot* getRobot() const { return m_pRobot; }
protected:
Master* m_pMaster;
Robot* m_pRobot;
/**
* @brief Called when the Command is first assigned to a robot
*/
virtual void init() { }
};
#endif // COMMAND_H
<file_sep>#ifndef PASSBALL_H
#define PASSBALL_H
#include "../Command.h"
#define PASS_VELOCITY_THRESHOLD 0.005f
#define PASS_TARGET_DISTANCE 90
#define PASS_MAXIMUM_DISTANCE 110
#define PASS_MAXIMUM_ANGLE M_PI*0.25f
class PassBall : public Command
{
public:
/**
* @brief Creates a new PassBall instance
* @param pMaster The Master instance associated with the command
* @param pTargetRobot The @see Robot to pass the ball to
*/
PassBall(Master* pMaster, Robot* pTargetRobot);
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
Robot* m_pTargetRobot;
float m_targetOrientation;
float m_targetDirection;
};
#endif // PASSBALL_H
<file_sep>#include "ClientMaster.h"
#include <iostream>
#include <QString>
#include <QKeyEvent>
#include <qmath.h>
#include <cmath>
#include "commands/PassToRobot.h"
#include "commands/AimAtRobot.h"
#include "commands/GetOpen.h"
ClientMaster::ClientMaster(qint16 port, const std::string netAddress, Team team, QWidget* parent) :
Master(port, netAddress, team, parent)
{
m_pUdpSocket = new QUdpSocket();
for (int i = 0; i < TEAM_SIZE; i++)
getTeamBot(i)->setDefaultCommand(new GetOpen(this));
getTeamBot(0)->runCommmand(new PassToRobot(this, getTeamBot(1)));
}
ClientMaster::~ClientMaster()
{
delete m_pUdpSocket;
}
void ClientMaster::writeOutput()
{
// Creates the packet and initializes the metadata
grSim_Packet simPacket;
simPacket.mutable_commands()->set_isteamyellow(getTeam() == YELLOW);
simPacket.mutable_commands()->set_timestamp(0.0);
for (int i = 0; i < TEAM_SIZE; i++)
getTeamBot(i)->writeOutput(simPacket.mutable_commands()->add_robot_commands());
// Serialize the packet and send it to grSim
QByteArray dgram;
dgram.resize(simPacket.ByteSize());
simPacket.SerializeToArray(dgram.data(), dgram.size());
m_pUdpSocket->writeDatagram(dgram, QHostAddress("127.0.0.1"), 20011);
}
<file_sep>#ifndef ROBOT_H
#define ROBOT_H
#include <QVector2D>
#include "Command.h"
#include "Team.h"
#include "PID.h"
#include "messages_robocup_ssl_wrapper.pb.h"
#include "grSim_Packet.pb.h"
class Command;
/**
* @brief The Robot class is used for accessing robot information and controlling a robot's outputs
*/
class Robot
{
public:
/**
* @brief Initailizes a new Robot instance
* @param team The team the robot is on
* @param id The ID of the robot
*/
Robot(Team team, unsigned char id);
/**
* @brief Destroys any dynamically allocated memory by the Robot
*/
~Robot();
// Transformational getters
/**
* @brief Used for accessing the position of the robot
* @return A copy of the position of the robot
*/
QVector2D getPosition() const { return m_position; }
/**
* @brief Used for accessing the orientation of the robot
* @return The orientation of the robot in radians
*/
float getOrientation() const { return m_orientation; }
// Velocity getters
/**
* @brief Used for accessing the speed of the robot
* @return The speed of the robot in m/s
*/
float getSpeed() const { return m_speed; }
/**
* @brief Used for accessing the direction of the robot
* @return The direction of the robot in radians
*/
float getDirection() const { return m_direction; }
/**
* @brief Used for accessing the angular velocity of the robot
* @return The angular velocity of the robot in rad/s
*/
float getAngularVelocity() const { return m_angularVelocity; }
// Target value getters
/**
* @brief Used for accessing the target speed of the robot
* @return The target speed of the robot in m/s
*/
float getTargetSpeed() const { return m_targetSpeed; }
/**
* @brief Used for accessing the target direction of the robot
* @return The target direction of the robot in radians
*/
float getTargetDirection() const { return m_targetDirection; }
/**
* @brief Used for accessing the kicker speed of the robot
* @return The kicker speed of the robot
*/
float getKickerSpeed() const { return m_kickerSpeed; }
/**
* @brief Used for accessing the target orientation of the robot
* @return The target orientation of the robot in radians
*/
float getTargetOrientation() const { return m_orientationPid->getSetpoint(); }
// Metadata getters
/**
* @brief Used for determining which team the robot is on
* @return The @see Team the robot is on
*/
Team getTeam() const { return m_team; }
/**
* @brief Used for determining the ID of the robot
* @return The ID of the robot as a byte
*/
unsigned char getId() const { return m_id; }
// Updating robot information
/**
* @brief Updates positional information of the robot
* @param robot The @see SSL_DetectionRobot from which to refresh
*/
void refresh(SSL_DetectionRobot& robot);
/**
* @brief Updates the robot's motor outputs and writes them to the given @see grSim_Robot_Command
* @param pCommand The command to which the function will write the outputs
* @param deltaTime The time passed since the last update call
*/
void updateStats(double deltaTime);
/**
* @brief Performs an update call for the Robot's current Command
* @param deltaTime The time passed since the last update call
*/
void updateCommand(double deltaTime);
/**
* @brief Generates the @see grSim_Robot_Command information to be sent to GrSim
* @param pCommand The command to be populated
*/
void writeOutput(grSim_Robot_Command* pCommand);
// Target value setters
/**
* @brief Sets the target speed of the robot
* @param speed The target speeed in m/s
*/
void setTargetSpeed(float speed);
/**
* @brief Sets the target direction of the robot
* @param angle The target direction angle in radians
*/
void setTargetDirection(float angle);
/**
* @brief Sets the target orientation of the robot
* @param angle The angle in radians
*/
void setTargetOrientation(float angle);
/**
* @brief Sets the speed of the kicker on the robot
* @param speed The speed to set the kicker
*/
void setKickerSpeed(float speed);
/**
* @brief Sets the command to be executed before one is assigned or after a command ends
* @param pCommand The default command
*/
void setDefaultCommand(Command* pCommand);
/**
* @brief Runs the given command
* @note Robot does NOT assume ownership of the command passed; eventual deallocation is the responsibility of the caller
* @param pCommand The @see Command to run
*/
void runCommmand(Command* pCommand);
private:
bool m_initialized;
// Transform information
QVector2D m_position;
float m_orientation;
// Transform information from the last frame for calculating velocity
QVector2D m_lastPosition;
float m_lastOrientation;
// Velocity information
float m_speed;
float m_direction;
float m_angularVelocity;
float m_kickerSpeed;
// Target velocity information
float m_targetSpeed;
float m_targetDirection;
float m_targetOrientation;
float m_targetAngularVelocity;
// PID information
PID* m_orientationPid;
// Command information
Command* m_pDefaultCommand;
Command* m_pWaitingCommand;
Command* m_pCommand;
// Metadata
Team m_team;
unsigned char m_id;
};
#endif // ROBOT_H
<file_sep>import math
from Actor import *
from Ball import *
class BallContainer(Actor):
"""
Used to track, manage, update, and render Ball instances
"""
def __init__(self, viewer):
"""
Creates a new BallContainer instance
:param viewer: The Viewer to be rendered to
"""
super().__init__(viewer)
self.balls = []
def update(self, packet, delta):
"""
Updates each ball
:param packet: The most up-to-date SSLPacket
:param delta: The time since the last update
"""
# Remove any balls that aren't being detected anymore
for b in self.balls:
b.time_since_update += delta
self.balls[:] = [b for b in self.balls if b.time_since_update < Ball.DETECTION_TIMEOUT_MS]
remaining_balls = self.balls[:]
# Update the positions of the remaining balls
for db in packet.detection.balls:
ball = None
smallest_distance = math.inf
# Find the closest viewer ball to the current detection ball, if it exists
for vb in remaining_balls:
distance = math.sqrt(math.pow(vb.x - db.x, 2) + math.pow(vb.y - db.y, 2))
if distance < smallest_distance:
ball = vb
smallest_distance = distance
# If there aren't any viewer balls found, add a new one, otherwise update the closest ball
if ball is None:
self.balls.append(Ball(self.viewer, db.x, db.y))
else:
remaining_balls.remove(ball)
ball.x = db.x
ball.y = db.y
ball.time_since_update = 0
def draw(self, geometry):
"""
Renders each ball
:param geometry: (unused)
"""
for b in self.balls:
b.draw(geometry)
<file_sep>#ifndef ONETIMERPASS_H
#define ONETIMERPASS_H
#include "../CommandSeries.h"
class OneTimerPass : public CommandSeries
{
public:
OneTimerPass(Master* pMaster, Robot* pTargetRobot);
virtual void end();
private:
Robot* m_pTargetRobot;
};
#endif // ONETIMERPASS_H
<file_sep>#ifndef TESTCOMMAND_H
#define TESTCOMMAND_H
#include "../Command.h"
class TestCommand : public Command
{
public:
TestCommand(Master* pMaster, std::string name, int lifetime);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
std::string m_name;
int m_lifetime;
int m_numFrames;
};
#endif // TESTCOMMAND_H
<file_sep>#include "PID.h"
PID::PID(float p, float i, float d, float min, float max) :
m_p(p),
m_i(i),
m_d(d),
m_min(min),
m_max(max),
m_setpoint(0),
m_lastError(0),
m_integral(0)
{
}
float PID::calculate(float deltaTime, float input)
{
float error = m_setpoint - input;
float pOut = m_p * error;
m_integral += error * deltaTime;
float iOut = m_i * m_integral;
float derivative = (error - m_lastError) / deltaTime;
float dOut = m_d * derivative;
float output = pOut + iOut + dOut;
if (output > m_max)
output = m_max;
else if (output < m_min)
output = m_min;
m_lastError = error;
return output;
}
<file_sep>#ifndef ORIENTROBOT_H
#define ORIENTROBOT_H
#include "../Command.h"
class OrientRobot : public Command
{
public:
OrientRobot(Master* pMaster);
virtual void update(double deltaTime);
};
#endif // ORIENTROBOT_H
<file_sep>#ifndef TESTCOMMANDSERIES_H
#define TESTCOMMANDSERIES_H
#include "../CommandSeries.h"
class TestCommandSeries : public CommandSeries
{
public:
TestCommandSeries(Master* pMaster);
virtual void start();
virtual void end();
};
#endif // TESTCOMMANDSERIES_H
<file_sep>#include "Robot.h"
#include "MathHelper.h"
#include <cmath>
#include <iostream>
Robot::Robot(Team team, unsigned char id) :
m_initialized(false),
m_position(0, 0),
m_orientation(0),
m_lastPosition(0, 0),
m_lastOrientation(0),
m_speed(0),
m_direction(0),
m_angularVelocity(0),
m_targetSpeed(0),
m_targetDirection(0),
m_targetOrientation(0),
m_targetAngularVelocity(0),
m_kickerSpeed(0),
m_team(team),
m_id(id)
{
m_orientationPid = new PID(10.0, 0.0, 0.25, -M_PI * 4, M_PI * 4);
m_pDefaultCommand = 0;
m_pWaitingCommand = 0;
m_pCommand = 0;
}
Robot::~Robot()
{
delete m_orientationPid;
if (m_pDefaultCommand)
delete m_pDefaultCommand;
if (m_pWaitingCommand && m_pWaitingCommand != m_pDefaultCommand)
delete m_pWaitingCommand;
if (m_pCommand && m_pCommand != m_pDefaultCommand)
delete m_pCommand;
}
void Robot::refresh(SSL_DetectionRobot& robot)
{
// Update positional information
m_position.setX(robot.x());
m_position.setY(robot.y());
m_orientation = robot.orientation();
// If this is the first frame, set the last position and orientation to the current position and orientation
if (!m_initialized)
{
m_initialized = true;
m_lastPosition = m_position;
m_lastOrientation = m_orientation;
}
}
void Robot::updateStats(double deltaTime)
{
// Update the speed of the robot
if (m_position != m_lastPosition)
{
m_speed = (m_position - m_lastPosition).length() / deltaTime * 0.001;
if (m_speed > 0)
m_direction = std::atan2(m_position.y() - m_lastPosition.y(), m_position.x() - m_lastPosition.x());
m_lastPosition = m_position;
}
// Update the angular velocity of the robot
if (m_orientation != m_lastOrientation)
{
m_angularVelocity = (m_orientation - m_lastOrientation) / deltaTime;
m_lastOrientation = m_orientation;
}
}
void Robot::updateCommand(double deltaTime)
{
if (m_pWaitingCommand != 0)
{
if (m_pCommand != 0)
{
m_pCommand->interrupted();
m_pCommand->end();
}
m_pCommand = m_pWaitingCommand;
m_pWaitingCommand = 0;
m_pCommand->start();
}
if (m_pCommand != 0)
{
if (m_pCommand->isFinished())
{
m_pCommand->end();
m_pCommand = 0;
}
else
{
m_pCommand->update(deltaTime);
}
}
if (m_pCommand == 0 && m_pWaitingCommand == 0 && m_pDefaultCommand != 0)
{
m_pCommand = m_pDefaultCommand;
m_pCommand->start();
}
m_targetAngularVelocity = m_orientationPid->calculate(deltaTime, MathHelper::adjustAngleValue(m_orientationPid->getSetpoint(), m_orientation));
}
void Robot::writeOutput(grSim_Robot_Command *pCommand)
{
// Define the ID of the robot
pCommand->set_id(m_id);
// Make sure we're defining x and y speed, not individual wheel speeds
pCommand->set_wheelsspeed(false);
pCommand->set_wheel1(0.0f);
pCommand->set_wheel2(0.0f);
pCommand->set_wheel3(0.0f);
pCommand->set_wheel4(0.0f);
// Calculate the horizontal speed from the target speed, target direction, and orientation
pCommand->set_veltangent(m_targetSpeed * std::cos(m_targetDirection + m_orientation));
// Calculate the vertical speed from the target speed, taret direction, and orientation
pCommand->set_velnormal(-m_targetSpeed * std::sin(m_targetDirection + m_orientation));
pCommand->set_velangular(m_targetAngularVelocity);
// Set kicker speeds
pCommand->set_kickspeedx(m_kickerSpeed);
pCommand->set_kickspeedz(0.0f);
pCommand->set_spinner(false);
}
void Robot::setTargetSpeed(float speed)
{
m_targetSpeed = speed;
}
void Robot::setTargetDirection(float angle)
{
m_targetDirection = angle;
}
void Robot::setTargetOrientation(float angle)
{
m_targetOrientation = angle;
while (angle < 0)
angle += M_PI * 2;
while (angle > M_PI * 2)
angle -= M_PI * 2;
m_orientationPid->setSetpoint(angle);
}
void Robot::setKickerSpeed(float speed)
{
m_kickerSpeed = speed;
}
void Robot::setDefaultCommand(Command *pCommand)
{
if (pCommand->getRobot() == this || pCommand->setRobot(this))
m_pDefaultCommand = pCommand;
else
std::cout << "Cannot set a default Command that's already been assigned to another robot!\n";
}
void Robot::runCommmand(Command *pCommand)
{
if (pCommand->getRobot() == this || pCommand->setRobot(this))
m_pWaitingCommand = pCommand;
else
std::cout << "Cannot run a Command that's already been assigned to another robot!\n";
}
<file_sep>from Actor import *
class ScreenActor(Actor):
"""
Used to represent Actors visualized on the screen
"""
def __init__(self, viewer, radius: int, x=0, y=0):
"""
Creates a new ScreenActor instance
:param viewer: The Viewer to be rendered to
:param radius: The radius of the actor
:param x: The x position of the actor
:param y: The y position of the actor
"""
super().__init__(viewer)
self.radius = radius
self.x = x
self.y = y
@abstractmethod
def update(self, packet, delta):
pass
@abstractmethod
def draw(self, geometry):
pass
def _get_radius(self) -> int:
return self._radius
def _set_radius(self, radius: int):
if radius <= 0:
raise ValueError('Radius must be nonzero')
self._radius = radius
def _get_x(self) -> int:
return self._x
def _set_x(self, x: int):
self._x = x
def _get_y(self) -> int:
return self._y
def _set_y(self, y: int):
self._y = y
radius = property(_get_radius, _set_radius)
x = property(_get_x, _set_x)
y = property(_get_y, _set_y)
<file_sep>import pygame
from ScreenActor import *
import math
class UIRect(ScreenActor):
def __init__(self, viewer, x, y, width, height, padding, color):
super().__init__(viewer, int(math.sqrt(width ** 2 + height ** 2)) // 2, x, y)
self.padding = padding
self.color = color
self.outline = pygame.Rect(x, y, width, height)
def update(self, packet, delta):
pass
def draw(self, geometry):
self.outline.x, self.outline.y = self.x, self.y
pygame.draw.rect(self.viewer.screen, (0, 0, 0), self.outline, 0)
pygame.draw.rect(self.viewer.screen, self.color, self.outline.inflate(-self.padding, -self.padding), 0)
def mouse_hover(self):
mx, my = pygame.mouse.get_pos()
return mx >= self.x and my >= self.y and mx < self.x + self.outline.width and my < self.y + self.outline.height
<file_sep>#ifndef CATCHBALL_H
#define CATCHBALL_H
#include "../Command.h"
#define CATCH_BALL_VElOCITY_THRESHOLD 0.01f
#define CATCH_VELOCITY_THRESHOLD 0.005f
#define CATCH_MAXIMUM_DISTANCE 130
class CatchBall : public Command
{
public:
/**
* @brief Initializes a new CatchBall instance
* @param pMaster The Master instance associated with the CatchBall command
*/
CatchBall(Master* pMaster);
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
QVector2D m_ballDirectionVector;
};
#endif // CATCHBALL_H
<file_sep>from Actor import *
from Slider import *
class GUI(Actor):
def __init__(self, viewer):
super().__init__(viewer)
self.elements = [Slider(viewer)]
def update(self, packet, delta):
for e in self.elements:
e.update(packet, delta)
def draw(self, geometry):
for e in self.elements:
e.draw(geometry)
<file_sep>import pygame
from ScreenActor import *
class Robot(ScreenActor):
DETECTION_TIMEOUT_MS = 500
def __init__(self, viewer, image):
"""
Creates a new Robot instance
:param viewer: The Viewer to be rendered to
:param image: The image to render to the Viewer
"""
super().__init__(viewer, 90)
self.time_since_update = 0
self.image = image
self.orientation = 0
def update(self, packet, delta):
pass
def draw(self, geometry):
"""
Render the bot
:param geometry: (unused)
"""
if self.time_since_update > self.DETECTION_TIMEOUT_MS:
return
scaled_radius = max(1, self.viewer.screen_scalar(self.radius))
# Render the robot
surface = pygame.transform.scale(self.image, (scaled_radius * 2, scaled_radius * 2))
rect = surface.get_rect().move((self.x, self.y))
rect = rect.move((-rect.width / 2, -rect.height / 2))
surface = pygame.transform.rotate(surface, self.orientation)
self.viewer.screen.blit(surface, rect)
<file_sep>#ifndef GETOPEN_H
#define GETOPEN_H
#include "../Command.h"
#define GETOPEN_VELOCITY_THRESHOLD 0.005f
class GetOpen : public Command
{
public:
/**
* @brief Creates a new GetOpen instance
* @param pMaster The Master instance associated with the GetOpen command
*/
GetOpen(Master* pMaster);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
private:
QVector2D m_startPosition;
};
#endif // GETOPEN_H
<file_sep>#ifndef PASSTOROBOT_H
#define PASSTOROBOT_H
#include "../CommandSeries.h"
class PassToRobot : public CommandSeries
{
public:
/**
* @brief Initializes a new PassToRobot command
* @param pMaster The Master instance the PassToRobot Command is associated with
* @param pTargetRobot The robot to pass the ball to
*/
PassToRobot(Master* pMaster, Robot* pTargetRobot);
virtual void end();
private:
Robot* m_pTargetRobot;
};
#endif // PASSTOROBOT_H
<file_sep>from abc import *
class Actor(ABC):
"""
An abstract base class for everything updated by the viewer
"""
def __init__(self, viewer):
self._viewer = viewer
@abstractmethod
def update(self, packet, delta):
"""
Called when the Actor is updated
:param packet: The most up-to-date packet
:param delta: The time since the last update
"""
pass
@abstractmethod
def draw(self, geometry):
"""
Draws the Actor to the Viewer
:param geometry: The most up-to-date field geometry
"""
pass
def _get_viewer(self):
return self._viewer
viewer = property(_get_viewer)
<file_sep>#include "Command.h"
Command::Command(Master *pMaster) :
m_pMaster(pMaster)
{
m_pRobot = 0;
}
bool Command::setRobot(Robot *pRobot)
{
if (m_pRobot != 0)
return false;
m_pRobot = pRobot;
init();
return true;
}
<file_sep>from Actor import *
import pygame
class GeometryRenderer(Actor):
"""
Used for rendering field geometry
"""
LINE_COLOR = (255, 255, 255)
def __init__(self, viewer):
"""
Creates a new GeometryRenderer instance
:param viewer: The Viewer to be rendered to
"""
super().__init__(viewer)
def update(self, packet, delta):
pass
def draw(self, geometry):
"""
Draws the field based on the given geometry
:param geometry: The geometry by which to render the field
"""
if geometry is None:
return
thickness = max(1, geometry.line_width)
field_rect = pygame.Rect((self.viewer.window_width - geometry.field_length) // 2,
(self.viewer.window_height - geometry.field_width) // 2,
geometry.field_length, geometry.field_width)
boundary_rect = field_rect.inflate(geometry.boundary_width, geometry.boundary_width)
goal_rect = pygame.Rect(field_rect.x - geometry.goal_depth,
self.viewer.window_height // 2 - geometry.goal_width // 2,
geometry.goal_depth, geometry.goal_width)
pygame.draw.rect(self.viewer.screen, (0, 127, 0), boundary_rect, 0)
pygame.draw.rect(self.viewer.screen, self.LINE_COLOR, field_rect, thickness)
pygame.draw.rect(self.viewer.screen, self.LINE_COLOR, goal_rect, thickness)
goal_rect.x = field_rect.x + field_rect.width
pygame.draw.rect(self.viewer.screen, self.LINE_COLOR, goal_rect, thickness)
pygame.draw.line(self.viewer.screen, self.LINE_COLOR,
(field_rect.x, self.viewer.window_height // 2),
(field_rect.x + field_rect.width, self.viewer.window_height // 2),
thickness)
pygame.draw.line(self.viewer.screen, self.LINE_COLOR,
(self.viewer.window_width // 2, field_rect.y),
(self.viewer.window_width // 2, field_rect.y + field_rect.height),
thickness)
pygame.draw.circle(self.viewer.screen, self.LINE_COLOR,
(self.viewer.window_width // 2, self.viewer.window_height // 2),
geometry.center_circle_radius, thickness)
<file_sep>#include "MathHelper.h"
#include <cmath>
namespace MathHelper
{
QVector2D getClosestPoint(QVector2D lineStart, QVector2D lineEnd, QVector2D point)
{
QVector2D dir = (lineEnd - lineStart).normalized();
float t = dir.x() * (point.x() - lineStart.x()) + dir.y() * (point.y() - lineStart.y());
return QVector2D(t * dir.x() + lineStart.x(), t * dir.y() + lineStart.y());
}
float getLineAngle(QVector2D pointA, QVector2D pointB)
{
return std::atan2(pointB.y() - pointA.y(), pointB.x() - pointA.x());
}
float adjustAngleValue(float baseAngle, float otherAngle)
{
while (baseAngle - otherAngle > M_PI)
otherAngle += M_PI * 2;
while (otherAngle - baseAngle > M_PI)
otherAngle -= M_PI * 2;
return otherAngle;
}
float biasAngle(float incoming, float outgoing, float outgoingBias)
{
return (incoming + outgoing * outgoingBias) / (1 + outgoingBias);
}
}
<file_sep>RoboCup-simulator
Installation instructions
1. Download grSim and follow its install instructions
2. Download QtCreator, get the open source version
3. Open QtCreator and select Open Project and navigate to the client.pro file for this package and open it
4. Under the Projects tab, go to build and add a custom build step
5. Set the Working Directory to the client directory for this package
6. Set command to protoc and set the arguments to: --proto_path=proto --cpp_out=src proto/*.proto
7. Run a build to be sure that everything works
Other Notes
1. You must be running grSim in order to get use work out of the simulator
TODO
1. Write a Makefile
<file_sep>#ifndef DELAY_H
#define DELAY_H
#include "../Command.h"
class Delay : public Command
{
public:
Delay(Master* pMaster, double seconds);
virtual void start();
virtual void update(double deltaTime);
virtual bool isFinished();
virtual void end();
private:
double m_delayTime;
double m_secondsPassed;
};
#endif // DELAY_H
<file_sep>#include "PassToRobot.h"
#include "AimAtRobot.h"
#include "PassBall.h"
#include "SetKicker.h"
#include "Delay.h"
#include "CatchBall.h"
#include "OneTimerPass.h"
PassToRobot::PassToRobot(Master* pMaster, Robot* pTargetRobot) :
CommandSeries(pMaster)
{
m_pTargetRobot = pTargetRobot;
addCommand(new AimAtRobot(pMaster, pTargetRobot));
addCommand(new PassBall(pMaster, pTargetRobot));
addCommand(new SetKicker(pMaster, 4.0f));
addCommand(new Delay(pMaster, 0.05f));
addCommand(new SetKicker(pMaster, 0.0f));
}
void PassToRobot::end()
{
m_pTargetRobot->runCommmand(new /*OneTimerPass(m_pMaster, m_pMaster->getTeamBot((m_pTargetRobot->getId() + 1) % 6))*/CatchBall(m_pMaster));
destroy();
}
<file_sep>#include "Delay.h"
Delay::Delay(Master* pMaster, double seconds) :
Command(pMaster),
m_delayTime(seconds)
{
}
void Delay::start()
{
m_secondsPassed = 0;
}
void Delay::update(double deltaTime)
{
m_secondsPassed += deltaTime;
}
bool Delay::isFinished()
{
return m_secondsPassed >= m_delayTime;
}
void Delay::end()
{
destroy();
}
<file_sep>#include "TestCommandSeries.h"
#include "TestCommand.h"
#include <iostream>
TestCommandSeries::TestCommandSeries(Master* pMaster) :
CommandSeries(pMaster)
{
addCommand(new TestCommand(pMaster, "Command 1", 3));
addCommand(new TestCommand(pMaster, "Command 2", 5));
}
void TestCommandSeries::start()
{
std::cout << "Command series started!\n";
CommandSeries::start();
}
void TestCommandSeries::end()
{
std::cout << "Command series ended!\n";
}
<file_sep>#include <iostream>
#include <QApplication>
#include "ClientMaster.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
ClientMaster* master = new ClientMaster(10020, "224.5.23.2", YELLOW);
master->show();
app.exec();
delete master;
return 0;
}
<file_sep>from Viewer import *
def start() -> None:
"""
Loads the log file given via the command line arguments, and starts the log viewer
"""
if len(sys.argv) < 2:
return
with gzip.open(sys.argv[1], 'rb') as file:
ld = LogData()
ld.parse(file)
viewer = Viewer(ld, "RoboCup SSL Log Viewer", 1040, 740, (0, 95, 0))
viewer.run()
if __name__ == '__main__':
start()
<file_sep>#include "OrientRobot.h"
#include <qmath.h>
OrientRobot::OrientRobot(Master* pMaster) :
Command(pMaster)
{
}
void OrientRobot::update(double deltaTime)
{
if (m_pRobot->getSpeed() < 0.1)
return;
m_pRobot->setTargetOrientation(m_pRobot->getDirection());
}
<file_sep>#include "TestCommand.h"
#include <iostream>
TestCommand::TestCommand(Master* pMaster, std::string name, int lifetime) :
Command(pMaster),
m_name(name),
m_lifetime(lifetime),
m_numFrames(0)
{
}
void TestCommand::start()
{
m_numFrames = 0;
std::cout << m_name << " has started!\n";
}
void TestCommand::update(double deltaTime)
{
std::cout << m_name << " has updated!\n";
m_numFrames++;
}
bool TestCommand::isFinished()
{
return m_numFrames == m_lifetime;
}
void TestCommand::end()
{
std::cout << m_name << " has ended!\n";
}
<file_sep>import math
from Actor import *
from typing import *
from Robot import *
from messages_robocup_ssl_detection_pb2 import *
class RobotContainer(Actor):
def __init__(self, viewer):
"""
Creates a new RobotContainer instance
:param viewer: The Viewer to be rendered to
"""
super().__init__(viewer)
self.robots_yellow = {}
self.robots_blue = {}
self.yellow_image = pygame.image.load("images/YellowBot.png")
self.blue_image = pygame.image.load("images/BlueBot.png")
def update(self, packet, delta):
"""
Updates each yellow and blue robot
:param packet: The packet data used to update the robots
:param delta: The time since the last update
"""
self.update_bots(packet.detection.robots_yellow, self.robots_yellow, self.yellow_image, delta)
self.update_bots(packet.detection.robots_blue, self.robots_blue, self.blue_image, delta)
def draw(self, geometry):
"""
Draws each yellow and blue robot
:param geometry: (unused)
"""
for r in self.robots_yellow.values():
r.draw(geometry)
for r in self.robots_blue.values():
r.draw(geometry)
def update_bots(self, detection_bots: List[SSL_DetectionRobot],
viewer_bots: Dict[int, Robot], image, delta: int):
"""
Updates each bot with the provided detection and viewer bots
:param detection_bots: The SSL bot data
:param viewer_bots: The bot instances
:param image: The image associated with the updated bots
:param delta: The time since the last update
"""
# Add the delta time to each robot's time since the last update
for r in viewer_bots.values():
r.time_since_update += delta
# Update each robot's position
for r in detection_bots:
# Get a robot from the viewer bots or create a new one if it does not exist
if r.robot_id in viewer_bots.keys():
robot = viewer_bots[r.robot_id]
else:
robot = viewer_bots[r.robot_id] = Robot(self.viewer, image)
# Update the robot's position and orientation, and reset its time since the last update
robot.x, robot.y = self.viewer.screen_point(r.x, r.y)
robot.orientation = math.degrees(-r.orientation)
robot.time_since_update = 0
|
68536efc5dea3b5aae6a10eeefca49165c3ae6eb
|
[
"Markdown",
"C",
"Python",
"C++"
] | 59
|
C++
|
CalPolyRobotics/RoboCup-simulator
|
e291e601c85a6b2622249888568810b560a7d4eb
|
375a4236a6833b6227dc47c6a2c77360f34f27cf
|
refs/heads/master
|
<repo_name>ernane/SOAP<file_sep>/locadora/src/com/playmovie/locadora/modelos/Filme.java
package com.playmovie.locadora.modelos;
public class Filme {
private String titulo;
private String categoria;
private String diretor;
private Integer anoLancamento;
public Filme(){}
public Filme(String titulo, String categoria, String diretor, Integer anoLancamento){
super();
this.titulo = titulo;
this.categoria = categoria;
this.diretor = diretor;
this.anoLancamento = anoLancamento;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getDiretor() {
return diretor;
}
public void setDiretor(String diretor) {
this.diretor = diretor;
}
public Integer getAnoLancamento() {
return anoLancamento;
}
public void setAnoLancamento(Integer anoLancamento) {
this.anoLancamento = anoLancamento;
}
}
<file_sep>/php/lista_filme.php
<?php
$client = new SoapClient('http://localhost:8080/filmes?wsdl');
$result = $client->__soapCall("listarFilmes", array($a, $b, $c), NULL);
$array = (array)$result;
print_r($array);
?><file_sep>/ruby/lista_filme.rb
require 'savon'
class ListaFilme
attr_reader :filmes
def initialize
client = Savon.client(wsdl: "http://localhost:8080/filmes?wsdl")
response = client.call(:listar_filmes)
if response.success?
@filmes = response.to_array(:listar_filmes_response, :return)
end
end
def lista_filmes
@filmes.map do |filme|
puts "Titulo: #{filme[:titulo]} - #{filme[:ano_lancamento]}"
end
end
end
l = ListaFilme.new
l.lista_filmes<file_sep>/java/src/com/playmovie/locadora/servicos/Cliente.java
package com.playmovie.locadora.servicos;
import java.util.List;
public class Cliente {
public static void main(String[] args){
ListagemFilmesService listagemFilmesFactory = new ListagemFilmesService();
ListagemFilmes listagemFilmes = listagemFilmesFactory.getListagemFilmesPort();
List<Filme> filmes = listagemFilmes.listarFilmes();
for (Filme filme : filmes) {
System.out.println("Titulo: " + filme.getTitulo() + " - " + filme.getAnoLancamento());
}
}
}
<file_sep>/locadora/src/com/playmovie/locadora/daos/FilmeDAO.java
package com.playmovie.locadora.daos;
import java.util.ArrayList;
import java.util.List;
import com.playmovie.locadora.modelos.Filme;
public class FilmeDAO {
public List<Filme> listaFilmes(){
List<Filme> filmes = new ArrayList<Filme>();
filmes.add(new Filme("Interstellar", "Adventure", "<NAME>", 2014));
filmes.add(new Filme("The Imitation Game", "Biography", "<NAME>", 2014));
filmes.add(new Filme("12 Years a Slave", "Biography", "<NAME>", 2013));
filmes.add(new Filme("The Theory of Everything", "Biography", "<NAME>", 2014));
filmes.add(new Filme("Guardians of the Galaxy", "Action", "<NAME>", 2014));
filmes.add(new Filme("The Sixth Sense", "Drama", "<NAME>", 1999));
filmes.add(new Filme("The Hobbit: The Desolation of Smaug", "Adventure", "<NAME>", 2013));
filmes.add(new Filme("Catch Me If You Can", "Biography", "<NAME>", 2002));
filmes.add(new Filme("Stand by Me", "Adventure", "<NAME>", 1986));
return filmes;
}
}
|
7c17440b33b8b38b2133fbebdce1593c1b1b2e9f
|
[
"Java",
"Ruby",
"PHP"
] | 5
|
Java
|
ernane/SOAP
|
37329b748e2f11a3afa1b4bd30d6daa1dcf90cdf
|
295314b6abfc6bfa5084940d5d6a42e2fe317431
|
refs/heads/master
|
<file_sep># Proj1-Pageserver
---------------------------------------------
Author: <NAME>
Contact email: <EMAIL>
# Introduction
-------------------------------
This project is the third mini project from the CIS322 course at the Univeristy of Oregon, it uses docker and flask to create local images
# Requirements
-----------------------------------
This project requires the following setup:
* Python 3.4 or higher
* Docker
# Installation/How it works
-----------------------------------------------------------
1) clone this repo into your local development.
2) open up the command-line interface (CLI) and get into the folder directory
3) manual turn on Docker
3) type the following command in the CLI
docker build -t <container name> .
docker run -d -p 5000:5000 <container name>
4) Launch: http://127.0.0.1:5000
<file_sep>from flask import Flask
from flask import render_template
app = Flask(__name__)
#Error handlers
@app.errorhandler(404)
def error_404(error):
return render_template('404.html'), 404
@app.errorhandler(403)
def error_403(error):
return render_template('403.html'), 403
@app.route("/<name>")
def hello(name):
if (len(name) > 1):
if ("//" not in name) and ("~" not in name) and (".." not in name):
try:
return open(name,"r").read()
except IOError:
return error_404(404)
else:
return error_403(403)
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0')
|
d855eb5754a9982017c345cf66fb8d3264c276f4
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
Yanhualuo/proj2-dockerintro
|
e008613f130816feaacc2e5b0d3ba50246b4a3c4
|
a097a267d1b3211a60401cb1ceac370b492b0ea0
|
refs/heads/master
|
<file_sep>//
// CategoryCell.swift
// CoderSwag
//
// Created by <NAME> on 23/03/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CategoryCell: UITableViewCell {
@IBOutlet weak var categoryTitle : UILabel!
@IBOutlet weak var categoryImage: UIImageView!
func updateViews(categories : Category)
{
categoryImage.image = UIImage(named: categories.imageName)
categoryTitle.text = categories.title
}
}
<file_sep>//
// Products.swift
// CoderSwag
//
// Created by <NAME> on 26/03/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct Product {
private(set) public var title : String
private(set) public var price : String
private(set) public var imageName : String
init(title :String, price :String, imageName:String) {
self.title = title
self.price = price
self.imageName = imageName
}
}
<file_sep>//
// Category.swift
// CoderSwag
//
// Created by <NAME> on 24/03/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct Category {
private(set) public var title : String
private(set) public var imageName : String
init(title : String, imageName : String) {
self.title = title
self.imageName = imageName
}
}
<file_sep># coder-swag
An App that is like a store or Ecommerce App that displays data in table views and collection views.
The table view shows the category of items and the collection view shows the image, name and price of the item.
## Screenshots
| Screenshot 1 | Screenshot 2 |
|:----------------------:|:------------:|
|  |  |
| Screenshot 3 | Screenshot 4 |
|:----------------------:|:------------:|
|  |  |
|
76e8395c45c0cc6cf2da1139869aad22fc569d02
|
[
"Swift",
"Markdown"
] | 4
|
Swift
|
jainijhawan/Coder-Swag
|
310cee98c66d6ea7ead431ca2a87da92d367116d
|
42bd966c37aebf51ef66524210f48fd9eeab74b9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.